[server] use internal_cnx instead of internal_session in deserialize_schema
authorJulien Cristau <julien.cristau@logilab.fr>
Tue, 28 Jan 2014 18:24:29 +0100
changeset 9490 b3d2c4065e6a
parent 9489 0581f6d2812e
child 9491 e82370a30018
[server] use internal_cnx instead of internal_session in deserialize_schema
server/repository.py
server/schemaserial.py
--- a/server/repository.py	Tue Jan 28 18:40:19 2014 +0100
+++ b/server/repository.py	Tue Jan 28 18:24:29 2014 +0100
@@ -325,9 +325,9 @@
         from cubicweb.server.schemaserial import deserialize_schema
         appschema = schema.CubicWebSchema(self.config.appid)
         self.debug('deserializing db schema into %s %#x', appschema.name, id(appschema))
-        with self.internal_session() as session:
+        with self.internal_cnx() as cnx:
             try:
-                deserialize_schema(appschema, session)
+                deserialize_schema(appschema, cnx)
             except BadSchemaDefinition:
                 raise
             except Exception as ex:
--- a/server/schemaserial.py	Tue Jan 28 18:40:19 2014 +0100
+++ b/server/schemaserial.py	Tue Jan 28 18:24:29 2014 +0100
@@ -81,26 +81,26 @@
 
 # schema / perms deserialization ##############################################
 
-def deserialize_schema(schema, session):
+def deserialize_schema(schema, cnx):
     """return a schema according to information stored in an rql database
     as CWRType and CWEType entities
     """
-    repo = session.repo
+    repo = cnx.repo
     dbhelper = repo.system_source.dbhelper
     # XXX bw compat (3.6 migration)
-    sqlcu = session.cnxset.cu
-    sqlcu.execute("SELECT * FROM cw_CWRType WHERE cw_name='symetric'")
-    if sqlcu.fetchall():
-        sql = dbhelper.sql_rename_col('cw_CWRType', 'cw_symetric', 'cw_symmetric',
-                                      dbhelper.TYPE_MAPPING['Boolean'], True)
-        sqlcu.execute(sql)
-        sqlcu.execute("UPDATE cw_CWRType SET cw_name='symmetric' WHERE cw_name='symetric'")
-        session.commit(False)
+    with cnx.ensure_cnx_set:
+        sqlcu = cnx.system_sql("SELECT * FROM cw_CWRType WHERE cw_name='symetric'")
+        if sqlcu.fetchall():
+            sql = dbhelper.sql_rename_col('cw_CWRType', 'cw_symetric', 'cw_symmetric',
+                                          dbhelper.TYPE_MAPPING['Boolean'], True)
+            sqlcu.execute(sql)
+            sqlcu.execute("UPDATE cw_CWRType SET cw_name='symmetric' WHERE cw_name='symetric'")
+            cnx.commit(False)
     ertidx = {}
     copiedeids = set()
-    permsidx = deserialize_ertype_permissions(session)
+    permsidx = deserialize_ertype_permissions(cnx)
     schema.reading_from_database = True
-    for eid, etype, desc in session.execute(
+    for eid, etype, desc in cnx.execute(
         'Any X, N, D WHERE X is CWEType, X name N, X description D',
         build_descr=False):
         # base types are already in the schema, skip them
@@ -114,7 +114,7 @@
             needcopy = False
             netype = ETYPE_NAME_MAP[etype]
             # can't use write rql queries at this point, use raw sql
-            sqlexec = session.system_sql
+            sqlexec = cnx.system_sql
             if sqlexec('SELECT 1 FROM %(p)sCWEType WHERE %(p)sname=%%(n)s'
                        % {'p': sqlutils.SQL_PREFIX}, {'n': netype}).fetchone():
                 # the new type already exists, we should copy (eg make existing
@@ -131,12 +131,12 @@
                     sqlexec(alter_table_sql)
             sqlexec('UPDATE entities SET type=%(n)s WHERE type=%(x)s',
                     {'x': etype, 'n': netype})
-            session.commit(False)
+            cnx.commit(False)
             tocleanup = [eid]
             tocleanup += (eid for eid, cached in repo._type_source_cache.iteritems()
                           if etype == cached[0])
             repo.clear_caches(tocleanup)
-            session.commit(False)
+            cnx.commit(False)
             if needcopy:
                 ertidx[eid] = netype
                 copiedeids.add(eid)
@@ -148,14 +148,14 @@
         eschema = schema.add_entity_type(
             ybo.EntityType(name=etype, description=desc, eid=eid))
         set_perms(eschema, permsidx)
-    for etype, stype in session.execute(
+    for etype, stype in cnx.execute(
         'Any XN, ETN WHERE X is CWEType, X name XN, X specializes ET, ET name ETN',
         build_descr=False):
         etype = ETYPE_NAME_MAP.get(etype, etype)
         stype = ETYPE_NAME_MAP.get(stype, stype)
         schema.eschema(etype)._specialized_type = stype
         schema.eschema(stype)._specialized_by.append(etype)
-    for eid, rtype, desc, sym, il, ftc in session.execute(
+    for eid, rtype, desc, sym, il, ftc in cnx.execute(
         'Any X,N,D,S,I,FTC WHERE X is CWRType, X name N, X description D, '
         'X symmetric S, X inlined I, X fulltext_container FTC', build_descr=False):
         ertidx[eid] = rtype
@@ -163,7 +163,7 @@
             ybo.RelationType(name=rtype, description=desc,
                              symmetric=bool(sym), inlined=bool(il),
                              fulltext_container=ftc, eid=eid))
-    cstrsidx = deserialize_rdef_constraints(session)
+    cstrsidx = deserialize_rdef_constraints(cnx)
     pendingrdefs = []
     # closure to factorize common code of attribute/relation rdef addition
     def _add_rdef(rdefeid, seid, reid, oeid, **kwargs):
@@ -192,13 +192,13 @@
                 set_perms(rdefs, permsidx)
     # Get the type parameters for additional base types.
     try:
-        extra_props = dict(session.execute('Any X, XTP WHERE X is CWAttribute, '
+        extra_props = dict(cnx.execute('Any X, XTP WHERE X is CWAttribute, '
                                            'X extra_props XTP'))
     except Exception:
-        session.critical('Previous CRITICAL notification about extra_props is not '
+        cnx.critical('Previous CRITICAL notification about extra_props is not '
                          'a problem if you are migrating to cubicweb 3.17')
         extra_props = {} # not yet in the schema (introduced by 3.17 migration)
-    for values in session.execute(
+    for values in cnx.execute(
         'Any X,SE,RT,OE,CARD,ORD,DESC,IDX,FTIDX,I18N,DFLT WHERE X is CWAttribute,'
         'X relation_type RT, X cardinality CARD, X ordernum ORD, X indexed IDX,'
         'X description DESC, X internationalizable I18N, X defaultval DFLT,'
@@ -216,7 +216,7 @@
                   cardinality=card, description=desc, order=ord,
                   indexed=idx, fulltextindexed=ftidx, internationalizable=i18n,
                   default=default, **typeparams)
-    for values in session.execute(
+    for values in cnx.execute(
         'Any X,SE,RT,OE,CARD,ORD,DESC,C WHERE X is CWRelation, X relation_type RT,'
         'X cardinality CARD, X ordernum ORD, X description DESC, '
         'X from_entity SE, X to_entity OE, X composite C', build_descr=False):
@@ -232,7 +232,7 @@
         if rdefs is not None:
             set_perms(rdefs, permsidx)
     unique_togethers = {}
-    rset = session.execute(
+    rset = cnx.execute(
     'Any X,E,R WHERE '
     'X is CWUniqueTogetherConstraint, '
     'X constraint_of E, X relations R', build_descr=False)
@@ -251,11 +251,11 @@
     for eschema, unique_together in unique_togethers.itervalues():
         eschema._unique_together.append(tuple(sorted(unique_together)))
     schema.infer_specialization_rules()
-    session.commit()
+    cnx.commit()
     schema.reading_from_database = False
 
 
-def deserialize_ertype_permissions(session):
+def deserialize_ertype_permissions(cnx):
     """return sect action:groups associations for the given
     entity or relation schema with its eid, according to schema's
     permissions stored in the database as [read|add|delete|update]_permission
@@ -264,21 +264,21 @@
     res = {}
     for action in ('read', 'add', 'update', 'delete'):
         rql = 'Any E,N WHERE G is CWGroup, G name N, E %s_permission G' % action
-        for eid, gname in session.execute(rql, build_descr=False):
+        for eid, gname in cnx.execute(rql, build_descr=False):
             res.setdefault(eid, {}).setdefault(action, []).append(gname)
         rql = ('Any E,X,EXPR,V WHERE X is RQLExpression, X expression EXPR, '
                'E %s_permission X, X mainvars V' % action)
-        for eid, expreid, expr, mainvars in session.execute(rql, build_descr=False):
+        for eid, expreid, expr, mainvars in cnx.execute(rql, build_descr=False):
             # we don't know yet if it's a rql expr for an entity or a relation,
             # so append a tuple to differentiate from groups and so we'll be
             # able to instantiate it later
             res.setdefault(eid, {}).setdefault(action, []).append( (expr, mainvars, expreid) )
     return res
 
-def deserialize_rdef_constraints(session):
+def deserialize_rdef_constraints(cnx):
     """return the list of relation definition's constraints as instances"""
     res = {}
-    for rdefeid, ceid, ct, val in session.execute(
+    for rdefeid, ceid, ct, val in cnx.execute(
         'Any E, X,TN,V WHERE E constrained_by X, X is CWConstraint, '
         'X cstrtype T, T name TN, X value V', build_descr=False):
         cstr = CONSTRAINTS[ct].deserialize(val)