server/schemaserial.py
branchtls-sprint
changeset 1398 5fe84a5f7035
parent 0 b97547f5f1fa
child 1630 41aadba8b29f
equal deleted inserted replaced
1397:6cbc7bc8ea6d 1398:5fe84a5f7035
     1 """functions for schema / permissions (de)serialization using RQL
     1 """functions for schema / permissions (de)serialization using RQL
     2 
     2 
     3 :organization: Logilab
     3 :organization: Logilab
     4 :copyright: 2001-2008 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
     4 :copyright: 2001-2009 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
     5 :contact: http://www.logilab.fr/ -- mailto:contact@logilab.fr
     5 :contact: http://www.logilab.fr/ -- mailto:contact@logilab.fr
     6 """
     6 """
     7 __docformat__ = "restructuredtext en"
     7 __docformat__ = "restructuredtext en"
     8 
     8 
       
     9 import sys
     9 from itertools import chain
    10 from itertools import chain
    10 
    11 
    11 from logilab.common.shellutils import ProgressBar
    12 from logilab.common.shellutils import ProgressBar
    12 
    13 
    13 from yams import schema as schemamod, buildobjs as ybo
    14 from yams import schema as schemamod, buildobjs as ybo
    16 
    17 
    17 def group_mapping(cursor, interactive=True):
    18 def group_mapping(cursor, interactive=True):
    18     """create a group mapping from an rql cursor
    19     """create a group mapping from an rql cursor
    19 
    20 
    20     A group mapping has standard group names as key (managers, owners at least)
    21     A group mapping has standard group names as key (managers, owners at least)
    21     and the actual EGroup entity's eid as associated value.
    22     and the actual CWGroup entity's eid as associated value.
    22     In interactive mode (the default), missing groups'eid will be prompted
    23     In interactive mode (the default), missing groups'eid will be prompted
    23     from the user.
    24     from the user.
    24     """
    25     """
    25     res = {}
    26     res = {}
    26     for eid, name in cursor.execute('Any G, N WHERE G is EGroup, G name N'):
    27     for eid, name in cursor.execute('Any G, N WHERE G is CWGroup, G name N'):
    27         res[name] = eid
    28         res[name] = eid
    28     if not interactive:
    29     if not interactive:
    29         return res
    30         return res
    30     missing = [g for g in ('owners', 'managers', 'users', 'guests') if not g in res]
    31     missing = [g for g in ('owners', 'managers', 'users', 'guests') if not g in res]
    31     if missing:
    32     if missing:
    44                 except ValueError:
    45                 except ValueError:
    45                     print 'eid should be an integer'
    46                     print 'eid should be an integer'
    46                     continue
    47                     continue
    47     return res
    48     return res
    48 
    49 
       
    50 def _set_sql_prefix(prefix):
       
    51     """3.2.0 migration function: allow to unset/reset SQL_PREFIX"""
       
    52     for module in ('checkintegrity', 'migractions', 'schemahooks',
       
    53                    'sources.rql2sql', 'sources.native'):
       
    54         try:
       
    55             sys.modules['cubicweb.server.%s' % module].SQL_PREFIX = prefix
       
    56             print 'changed SQL_PREFIX for %s' % module
       
    57         except KeyError:
       
    58             pass
       
    59         
       
    60 def _update_database(schema, sqlcu):
       
    61     """3.2.0 migration function: update database schema by adding SQL_PREFIX to
       
    62     entity type tables and columns
       
    63     """
       
    64     for etype in schema.entities():
       
    65         if etype.is_final():
       
    66             continue
       
    67         try:
       
    68             sql = 'ALTER TABLE %s RENAME TO cw_%s' % (
       
    69                 etype, ETYPE_NAME_MAP.get(etype, etype))
       
    70             print sql
       
    71             sqlcu.execute(sql)
       
    72         except:
       
    73             pass
       
    74         for rschema in etype.subject_relations():
       
    75             if rschema == 'has_text':
       
    76                 continue
       
    77             if rschema.is_final() or rschema.inlined:
       
    78                 sql = 'ALTER TABLE cw_%s RENAME %s TO cw_%s' % (
       
    79                     etype, rschema, rschema)
       
    80                 print sql
       
    81                 sqlcu.execute(sql)
       
    82 
    49 # schema / perms deserialization ##############################################
    83 # schema / perms deserialization ##############################################
    50 
    84 
    51 def deserialize_schema(schema, session):
    85 def deserialize_schema(schema, session):
    52     """return a schema according to information stored in an rql database
    86     """return a schema according to information stored in an rql database
    53     as ERType and EEType entities
    87     as CWRType and CWEType entities
    54     """
    88     """
       
    89     #
       
    90     repo = session.repo
       
    91     sqlcu = session.pool['system']
       
    92     _3_2_migration = False
       
    93     if 'eetype' in [t.lower() for t in repo.system_source.dbhelper.list_tables(sqlcu)]:
       
    94         _3_2_migration = True
       
    95         # 3.2 migration
       
    96         _set_sql_prefix('')
       
    97         # first rename entity types whose name changed in 3.2 without adding the
       
    98         # cw_ prefix
       
    99         for etype in ('EFRDef', 'ENFRDef', 'ERType', 'EEType',
       
   100                       'EConstraintType', 'EConstraint', 'EGroup', 'EUser',
       
   101                       'ECache', 'EPermission', 'EProperty'):
       
   102             sql = 'ALTER TABLE %s RENAME TO %s' % (etype, ETYPE_NAME_MAP[etype])
       
   103             print sql
       
   104             sqlcu.execute(sql)
       
   105         # other table renaming done once schema has been readen
    55     # print 'reading schema from the database...'
   106     # print 'reading schema from the database...'
    56     index = {}
   107     index = {}
    57     permsdict = deserialize_ertype_permissions(session)
   108     permsdict = deserialize_ertype_permissions(session)
    58     schema.reading_from_database = True
   109     schema.reading_from_database = True
    59     for eid, etype, desc, meta in session.execute('Any X, N, D, M WHERE '
   110     for eid, etype, desc, meta in session.execute('Any X, N, D, M WHERE '
    60                                                   'X is EEType, X name N, '
   111                                                   'X is CWEType, X name N, '
    61                                                   'X description D, X meta M',
   112                                                   'X description D, X meta M',
    62                                                   build_descr=False):
   113                                                   build_descr=False):
    63         # base types are already in the schema, skip them
   114         # base types are already in the schema, skip them
    64         if etype in schemamod.BASE_TYPES:
   115         if etype in schemamod.BASE_TYPES:
    65             # just set the eid
   116             # just set the eid
    68             index[eid] = eschema
   119             index[eid] = eschema
    69             continue
   120             continue
    70         if etype in ETYPE_NAME_MAP: # XXX <2.45 bw compat
   121         if etype in ETYPE_NAME_MAP: # XXX <2.45 bw compat
    71             print 'fixing etype name from %s to %s' % (etype, ETYPE_NAME_MAP[etype])
   122             print 'fixing etype name from %s to %s' % (etype, ETYPE_NAME_MAP[etype])
    72             # can't use write rql queries at this point, use raw sql
   123             # can't use write rql queries at this point, use raw sql
    73             session.system_sql('UPDATE EEType SET name=%(n)s WHERE eid=%(x)s',
   124             session.system_sql('UPDATE CWEType SET name=%(n)s WHERE eid=%(x)s',
    74                                {'x': eid, 'n': ETYPE_NAME_MAP[etype]})
   125                                {'x': eid, 'n': ETYPE_NAME_MAP[etype]})
    75             session.system_sql('UPDATE entities SET type=%(n)s WHERE type=%(x)s',
   126             session.system_sql('UPDATE entities SET type=%(n)s WHERE type=%(x)s',
    76                                {'x': etype, 'n': ETYPE_NAME_MAP[etype]})
   127                                {'x': etype, 'n': ETYPE_NAME_MAP[etype]})
    77             session.commit(False)
   128             session.commit(False)
    78             try:
   129             try:
    89         etype = ybo.EntityType(name=etype, description=desc, meta=meta, eid=eid)
   140         etype = ybo.EntityType(name=etype, description=desc, meta=meta, eid=eid)
    90         eschema = schema.add_entity_type(etype)
   141         eschema = schema.add_entity_type(etype)
    91         index[eid] = eschema
   142         index[eid] = eschema
    92         set_perms(eschema, permsdict.get(eid, {}))
   143         set_perms(eschema, permsdict.get(eid, {}))
    93     try:
   144     try:
    94         rset = session.execute('Any XN, ETN WHERE X is EEType, X name XN, '
   145         rset = session.execute('Any XN, ETN WHERE X is CWEType, X name XN, '
    95                                'X specializes ET, ET name ETN')
   146                                'X specializes ET, ET name ETN')
    96     except: # `specializes` relation not available for versions prior to 2.50
   147     except: # `specializes` relation not available for versions prior to 2.50
    97         session.rollback(False)
   148         session.rollback(False)
    98     else:
   149     else:
    99         for etype, stype in rset:
   150         for etype, stype in rset:
   100             eschema = schema.eschema(etype)
   151             eschema = schema.eschema(etype)
   101             seschema = schema.eschema(stype)
   152             seschema = schema.eschema(stype)
   102             eschema._specialized_type = stype
   153             eschema._specialized_type = stype
   103             seschema._specialized_by.append(etype)
   154             seschema._specialized_by.append(etype)
   104     for eid, rtype, desc, meta, sym, il in session.execute(
   155     for eid, rtype, desc, meta, sym, il in session.execute(
   105         'Any X,N,D,M,S,I WHERE X is ERType, X name N, X description D, '
   156         'Any X,N,D,M,S,I WHERE X is CWRType, X name N, X description D, '
   106         'X meta M, X symetric S, X inlined I', build_descr=False):
   157         'X meta M, X symetric S, X inlined I', build_descr=False):
   107         try:
   158         try:
   108             # bw compat: fulltext_container added in 2.47
   159             # bw compat: fulltext_container added in 2.47
   109             ft_container = session.execute('Any FTC WHERE X eid %(x)s, X fulltext_container FTC',
   160             ft_container = session.execute('Any FTC WHERE X eid %(x)s, X fulltext_container FTC',
   110                                            {'x': eid}).rows[0][0]
   161                                            {'x': eid}).rows[0][0]
   117         rschema = schema.add_relation_type(rtype)
   168         rschema = schema.add_relation_type(rtype)
   118         index[eid] = rschema
   169         index[eid] = rschema
   119         set_perms(rschema, permsdict.get(eid, {}))        
   170         set_perms(rschema, permsdict.get(eid, {}))        
   120     cstrsdict = deserialize_rdef_constraints(session)
   171     cstrsdict = deserialize_rdef_constraints(session)
   121     for values in session.execute(
   172     for values in session.execute(
   122         'Any X,SE,RT,OE,CARD,ORD,DESC,IDX,FTIDX,I18N,DFLT WHERE X is EFRDef,'
   173         'Any X,SE,RT,OE,CARD,ORD,DESC,IDX,FTIDX,I18N,DFLT WHERE X is CWAttribute,'
   123         'X relation_type RT, X cardinality CARD, X ordernum ORD, X indexed IDX,'
   174         'X relation_type RT, X cardinality CARD, X ordernum ORD, X indexed IDX,'
   124         'X description DESC, X internationalizable I18N, X defaultval DFLT,'
   175         'X description DESC, X internationalizable I18N, X defaultval DFLT,'
   125         'X fulltextindexed FTIDX, X from_entity SE, X to_entity OE',
   176         'X fulltextindexed FTIDX, X from_entity SE, X to_entity OE',
   126         build_descr=False):
   177         build_descr=False):
   127         rdefeid, seid, reid, teid, card, ord, desc, idx, ftidx, i18n, default = values
   178         rdefeid, seid, reid, teid, card, ord, desc, idx, ftidx, i18n, default = values
   135                                   indexed=idx, fulltextindexed=ftidx,
   186                                   indexed=idx, fulltextindexed=ftidx,
   136                                   internationalizable=i18n,
   187                                   internationalizable=i18n,
   137                                   default=default, eid=rdefeid)
   188                                   default=default, eid=rdefeid)
   138         schema.add_relation_def(rdef)
   189         schema.add_relation_def(rdef)
   139     for values in session.execute(
   190     for values in session.execute(
   140         'Any X,SE,RT,OE,CARD,ORD,DESC,C WHERE X is ENFRDef, X relation_type RT,'
   191         'Any X,SE,RT,OE,CARD,ORD,DESC,C WHERE X is CWRelation, X relation_type RT,'
   141         'X cardinality CARD, X ordernum ORD, X description DESC, '
   192         'X cardinality CARD, X ordernum ORD, X description DESC, '
   142         'X from_entity SE, X to_entity OE, X composite C', build_descr=False):
   193         'X from_entity SE, X to_entity OE, X composite C', build_descr=False):
   143         rdefeid, seid, reid, teid, card, ord, desc, c = values
   194         rdefeid, seid, reid, teid, card, ord, desc, c = values
   144         frometype = index[seid].type
   195         frometype = index[seid].type
   145         rtype = index[reid].type
   196         rtype = index[reid].type
   149                                   order=ord, description=desc, 
   200                                   order=ord, description=desc, 
   150                                   composite=c, constraints=constraints,
   201                                   composite=c, constraints=constraints,
   151                                   eid=rdefeid)
   202                                   eid=rdefeid)
   152         schema.add_relation_def(rdef)
   203         schema.add_relation_def(rdef)
   153     schema.infer_specialization_rules()
   204     schema.infer_specialization_rules()
       
   205     if _3_2_migration:
       
   206         _update_database(schema, sqlcu)
       
   207         _set_sql_prefix('cw_')
   154     session.commit()
   208     session.commit()
   155     schema.reading_from_database = False
   209     schema.reading_from_database = False
   156 
   210 
   157 
   211 
   158 def deserialize_ertype_permissions(session):
   212 def deserialize_ertype_permissions(session):
   159     """return sect action:groups associations for the given
   213     """return sect action:groups associations for the given
   160     entity or relation schema with its eid, according to schema's
   214     entity or relation schema with its eid, according to schema's
   161     permissions stored in the database as [read|add|delete|update]_permission
   215     permissions stored in the database as [read|add|delete|update]_permission
   162     relations between EEType/ERType and EGroup entities
   216     relations between CWEType/CWRType and CWGroup entities
   163     """
   217     """
   164     res = {}
   218     res = {}
   165     for action in ('read', 'add', 'update', 'delete'):
   219     for action in ('read', 'add', 'update', 'delete'):
   166         rql = 'Any E,N WHERE G is EGroup, G name N, E %s_permission G' % action
   220         rql = 'Any E,N WHERE G is CWGroup, G name N, E %s_permission G' % action
   167         for eid, gname in session.execute(rql, build_descr=False):
   221         for eid, gname in session.execute(rql, build_descr=False):
   168             res.setdefault(eid, {}).setdefault(action, []).append(gname)
   222             res.setdefault(eid, {}).setdefault(action, []).append(gname)
   169         rql = ('Any E,X,EXPR,V WHERE X is RQLExpression, X expression EXPR, '
   223         rql = ('Any E,X,EXPR,V WHERE X is RQLExpression, X expression EXPR, '
   170                'E %s_permission X, X mainvars V' % action)
   224                'E %s_permission X, X mainvars V' % action)
   171         for eid, expreid, expr, mainvars in session.execute(rql, build_descr=False):
   225         for eid, expreid, expr, mainvars in session.execute(rql, build_descr=False):
   192 
   246 
   193 def deserialize_rdef_constraints(session):
   247 def deserialize_rdef_constraints(session):
   194     """return the list of relation definition's constraints as instances"""
   248     """return the list of relation definition's constraints as instances"""
   195     res = {}
   249     res = {}
   196     for rdefeid, ceid, ct, val in session.execute(
   250     for rdefeid, ceid, ct, val in session.execute(
   197         'Any E, X,TN,V WHERE E constrained_by X, X is EConstraint, '
   251         'Any E, X,TN,V WHERE E constrained_by X, X is CWConstraint, '
   198         'X cstrtype T, T name TN, X value V', build_descr=False):
   252         'X cstrtype T, T name TN, X value V', build_descr=False):
   199         cstr = CONSTRAINTS[ct].deserialize(val)
   253         cstr = CONSTRAINTS[ct].deserialize(val)
   200         cstr.eid = ceid
   254         cstr.eid = ceid
   201         res.setdefault(rdefeid, []).append(cstr)
   255         res.setdefault(rdefeid, []).append(cstr)
   202     return res
   256     return res
   213     aller = eschemas + schema.relations()
   267     aller = eschemas + schema.relations()
   214     if not verbose:
   268     if not verbose:
   215         pb_size = len(aller) + len(CONSTRAINTS) + len([x for x in eschemas if x.specializes()])
   269         pb_size = len(aller) + len(CONSTRAINTS) + len([x for x in eschemas if x.specializes()])
   216         pb = ProgressBar(pb_size)
   270         pb = ProgressBar(pb_size)
   217     for cstrtype in CONSTRAINTS:
   271     for cstrtype in CONSTRAINTS:
   218         rql = 'INSERT EConstraintType X: X name "%s"' % cstrtype
   272         rql = 'INSERT CWConstraintType X: X name "%s"' % cstrtype
   219         if verbose:
   273         if verbose:
   220             print rql
   274             print rql
   221         cursor.execute(rql)
   275         cursor.execute(rql)
   222         if not verbose:
   276         if not verbose:
   223             pb.update()
   277             pb.update()
   339             yield rql, values
   393             yield rql, values
   340 
   394 
   341 
   395 
   342 def schema2rql(schema, skip=None, allow=None):
   396 def schema2rql(schema, skip=None, allow=None):
   343     """return a list of rql insert statements to enter the schema in the
   397     """return a list of rql insert statements to enter the schema in the
   344     database as ERType and EEType entities
   398     database as CWRType and CWEType entities
   345     """
   399     """
   346     assert not (skip is not None and allow is not None), \
   400     assert not (skip is not None and allow is not None), \
   347            'can\'t use both skip and allow'
   401            'can\'t use both skip and allow'
   348     all = schema.entities() + schema.relations()
   402     all = schema.entities() + schema.relations()
   349     if skip is not None:
   403     if skip is not None:
   357         return eschema2rql(erschema)
   411         return eschema2rql(erschema)
   358     return rschema2rql(erschema)
   412     return rschema2rql(erschema)
   359 
   413 
   360 def eschema2rql(eschema):
   414 def eschema2rql(eschema):
   361     """return a list of rql insert statements to enter an entity schema
   415     """return a list of rql insert statements to enter an entity schema
   362     in the database as an EEType entity
   416     in the database as an CWEType entity
   363     """
   417     """
   364     relations, values = eschema_relations_values(eschema)
   418     relations, values = eschema_relations_values(eschema)
   365     # NOTE: 'specializes' relation can't be inserted here since there's no
   419     # NOTE: 'specializes' relation can't be inserted here since there's no
   366     # way to make sure the parent type is inserted before the child type
   420     # way to make sure the parent type is inserted before the child type
   367     yield 'INSERT EEType X: %s' % ','.join(relations) , values
   421     yield 'INSERT CWEType X: %s' % ','.join(relations) , values
   368 
   422 
   369 def specialize2rql(schema):
   423 def specialize2rql(schema):
   370     for eschema in schema.entities():
   424     for eschema in schema.entities():
   371         for rql, kwargs in eschemaspecialize2rql(eschema):
   425         for rql, kwargs in eschemaspecialize2rql(eschema):
   372             yield rql, kwargs
   426             yield rql, kwargs
   377         values = {'x': eschema.type, 'et': specialized_type.type}
   431         values = {'x': eschema.type, 'et': specialized_type.type}
   378         yield 'SET X specializes ET WHERE X name %(x)s, ET name %(et)s', values
   432         yield 'SET X specializes ET WHERE X name %(x)s, ET name %(et)s', values
   379 
   433 
   380 def rschema2rql(rschema, addrdef=True):
   434 def rschema2rql(rschema, addrdef=True):
   381     """return a list of rql insert statements to enter a relation schema
   435     """return a list of rql insert statements to enter a relation schema
   382     in the database as an ERType entity
   436     in the database as an CWRType entity
   383     """
   437     """
   384     if rschema.type == 'has_text':
   438     if rschema.type == 'has_text':
   385         return
   439         return
   386     relations, values = rschema_relations_values(rschema)
   440     relations, values = rschema_relations_values(rschema)
   387     yield 'INSERT ERType X: %s' % ','.join(relations), values
   441     yield 'INSERT CWRType X: %s' % ','.join(relations), values
   388     if addrdef:
   442     if addrdef:
   389         for rql, values in rdef2rql(rschema):
   443         for rql, values in rdef2rql(rschema):
   390             yield rql, values
   444             yield rql, values
   391             
   445             
   392 def rdef2rql(rschema, subjtype=None, objtype=None, props=None):
   446 def rdef2rql(rschema, subjtype=None, objtype=None, props=None):
   399 
   453 
   400 def frdef2rql(rschema, subjtype, objtype, props):
   454 def frdef2rql(rschema, subjtype, objtype, props):
   401     relations, values = frdef_relations_values(rschema, objtype, props)
   455     relations, values = frdef_relations_values(rschema, objtype, props)
   402     relations.append(_LOCATE_RDEF_RQL0)
   456     relations.append(_LOCATE_RDEF_RQL0)
   403     values.update({'se': str(subjtype), 'rt': str(rschema), 'oe': str(objtype)})
   457     values.update({'se': str(subjtype), 'rt': str(rschema), 'oe': str(objtype)})
   404     yield 'INSERT EFRDef X: %s WHERE %s' % (','.join(relations), _LOCATE_RDEF_RQL1), values
   458     yield 'INSERT CWAttribute X: %s WHERE %s' % (','.join(relations), _LOCATE_RDEF_RQL1), values
   405     for rql, values in rdefrelations2rql(rschema, subjtype, objtype, props):
   459     for rql, values in rdefrelations2rql(rschema, subjtype, objtype, props):
   406         yield rql + ', EDEF is EFRDef', values
   460         yield rql + ', EDEF is CWAttribute', values
   407             
   461             
   408 def nfrdef2rql(rschema, subjtype, objtype, props):
   462 def nfrdef2rql(rschema, subjtype, objtype, props):
   409     relations, values = nfrdef_relations_values(rschema, objtype, props)
   463     relations, values = nfrdef_relations_values(rschema, objtype, props)
   410     relations.append(_LOCATE_RDEF_RQL0)
   464     relations.append(_LOCATE_RDEF_RQL0)
   411     values.update({'se': str(subjtype), 'rt': str(rschema), 'oe': str(objtype)})
   465     values.update({'se': str(subjtype), 'rt': str(rschema), 'oe': str(objtype)})
   412     yield 'INSERT ENFRDef X: %s WHERE %s' % (','.join(relations), _LOCATE_RDEF_RQL1), values
   466     yield 'INSERT CWRelation X: %s WHERE %s' % (','.join(relations), _LOCATE_RDEF_RQL1), values
   413     for rql, values in rdefrelations2rql(rschema, subjtype, objtype, props):
   467     for rql, values in rdefrelations2rql(rschema, subjtype, objtype, props):
   414         yield rql + ', EDEF is ENFRDef', values
   468         yield rql + ', EDEF is CWRelation', values
   415                 
   469                 
   416 def rdefrelations2rql(rschema, subjtype, objtype, props):
   470 def rdefrelations2rql(rschema, subjtype, objtype, props):
   417     iterators = []
   471     iterators = []
   418     for constraint in props['constraints']:
   472     for constraint in props['constraints']:
   419         iterators.append(constraint2rql(rschema, subjtype, objtype, constraint))
   473         iterators.append(constraint2rql(rschema, subjtype, objtype, constraint))
   421 
   475 
   422 def constraint2rql(rschema, subjtype, objtype, constraint):
   476 def constraint2rql(rschema, subjtype, objtype, constraint):
   423     values = {'ctname': unicode(constraint.type()),
   477     values = {'ctname': unicode(constraint.type()),
   424               'value': unicode(constraint.serialize()),
   478               'value': unicode(constraint.serialize()),
   425               'rt': str(rschema), 'se': str(subjtype), 'oe': str(objtype)}
   479               'rt': str(rschema), 'se': str(subjtype), 'oe': str(objtype)}
   426     yield 'INSERT EConstraint X: X value %(value)s, X cstrtype CT, EDEF constrained_by X WHERE \
   480     yield 'INSERT CWConstraint X: X value %(value)s, X cstrtype CT, EDEF constrained_by X WHERE \
   427 CT name %(ctname)s, EDEF relation_type ER, EDEF from_entity SE, EDEF to_entity OE, \
   481 CT name %(ctname)s, EDEF relation_type ER, EDEF from_entity SE, EDEF to_entity OE, \
   428 ER name %(rt)s, SE name %(se)s, OE name %(oe)s', values
   482 ER name %(rt)s, SE name %(se)s, OE name %(oe)s', values
   429 
   483 
   430 def perms2rql(schema, groupmapping):
   484 def perms2rql(schema, groupmapping):
   431     """return rql insert statements to enter the schema's permissions in
   485     """return rql insert statements to enter the schema's permissions in
   432     the database as [read|add|delete|update]_permission relations between
   486     the database as [read|add|delete|update]_permission relations between
   433     EEType/ERType and EGroup entities
   487     CWEType/CWRType and CWGroup entities
   434 
   488 
   435     groupmapping is a dictionnary mapping standard group names to
   489     groupmapping is a dictionnary mapping standard group names to
   436     eids
   490     eids
   437     """
   491     """
   438     for etype in sorted(schema.entities()):
   492     for etype in sorted(schema.entities()):
   441         yield erperms2rql(schema[rtype], groupmapping)
   495         yield erperms2rql(schema[rtype], groupmapping)
   442 
   496 
   443 def erperms2rql(erschema, groupmapping):
   497 def erperms2rql(erschema, groupmapping):
   444     """return rql insert statements to enter the entity or relation
   498     """return rql insert statements to enter the entity or relation
   445     schema's permissions in the database as
   499     schema's permissions in the database as
   446     [read|add|delete|update]_permission relations between EEType/ERType
   500     [read|add|delete|update]_permission relations between CWEType/CWRType
   447     and EGroup entities
   501     and CWGroup entities
   448     """
   502     """
   449     etype = isinstance(erschema, schemamod.EntitySchema) and 'EEType' or 'ERType'
   503     etype = isinstance(erschema, schemamod.EntitySchema) and 'CWEType' or 'CWRType'
   450     for action in erschema.ACTIONS:
   504     for action in erschema.ACTIONS:
   451         for group in sorted(erschema.get_groups(action)):
   505         for group in sorted(erschema.get_groups(action)):
   452             try:
   506             try:
   453                 yield ('SET X %s_permission Y WHERE X is %s, X name "%s", Y eid %s'
   507                 yield ('SET X %s_permission Y WHERE X is %s, X name "%s", Y eid %s'
   454                        % (action, etype, erschema, groupmapping[group]), None)
   508                        % (action, etype, erschema, groupmapping[group]), None)
   463 
   517 
   464 
   518 
   465 def updateeschema2rql(eschema):
   519 def updateeschema2rql(eschema):
   466     relations, values = eschema_relations_values(eschema)
   520     relations, values = eschema_relations_values(eschema)
   467     values['et'] = eschema.type
   521     values['et'] = eschema.type
   468     yield 'SET %s WHERE X is EEType, X name %%(et)s' % ','.join(relations), values
   522     yield 'SET %s WHERE X is CWEType, X name %%(et)s' % ','.join(relations), values
   469 
   523 
   470 def updaterschema2rql(rschema):
   524 def updaterschema2rql(rschema):
   471     relations, values = rschema_relations_values(rschema)
   525     relations, values = rschema_relations_values(rschema)
   472     values['rt'] = rschema.type
   526     values['rt'] = rschema.type
   473     yield 'SET %s WHERE X is ERType, X name %%(rt)s' % ','.join(relations), values
   527     yield 'SET %s WHERE X is CWRType, X name %%(rt)s' % ','.join(relations), values
   474             
   528             
   475 def updaterdef2rql(rschema, subjtype=None, objtype=None, props=None):
   529 def updaterdef2rql(rschema, subjtype=None, objtype=None, props=None):
   476     genmap = {True: updatefrdef2rql, False: updatenfrdef2rql}
   530     genmap = {True: updatefrdef2rql, False: updatenfrdef2rql}
   477     return __rdef2rql(genmap, rschema, subjtype, objtype, props)
   531     return __rdef2rql(genmap, rschema, subjtype, objtype, props)
   478 
   532 
   479 def updatefrdef2rql(rschema, subjtype, objtype, props):
   533 def updatefrdef2rql(rschema, subjtype, objtype, props):
   480     relations, values = frdef_relations_values(rschema, objtype, props)
   534     relations, values = frdef_relations_values(rschema, objtype, props)
   481     values.update({'se': subjtype, 'rt': str(rschema), 'oe': objtype})
   535     values.update({'se': subjtype, 'rt': str(rschema), 'oe': objtype})
   482     yield 'SET %s WHERE %s, %s, X is EFRDef' % (','.join(relations),
   536     yield 'SET %s WHERE %s, %s, X is CWAttribute' % (','.join(relations),
   483                                                  _LOCATE_RDEF_RQL0,
   537                                                  _LOCATE_RDEF_RQL0,
   484                                                  _LOCATE_RDEF_RQL1), values
   538                                                  _LOCATE_RDEF_RQL1), values
   485             
   539             
   486 def updatenfrdef2rql(rschema, subjtype, objtype, props):
   540 def updatenfrdef2rql(rschema, subjtype, objtype, props):
   487     relations, values = nfrdef_relations_values(rschema, objtype, props)
   541     relations, values = nfrdef_relations_values(rschema, objtype, props)
   488     values.update({'se': subjtype, 'rt': str(rschema), 'oe': objtype})
   542     values.update({'se': subjtype, 'rt': str(rschema), 'oe': objtype})
   489     yield 'SET %s WHERE %s, %s, X is ENFRDef' % (','.join(relations),
   543     yield 'SET %s WHERE %s, %s, X is CWRelation' % (','.join(relations),
   490                                                  _LOCATE_RDEF_RQL0,
   544                                                  _LOCATE_RDEF_RQL0,
   491                                                  _LOCATE_RDEF_RQL1), values
   545                                                  _LOCATE_RDEF_RQL1), values