[connection] remove ensure_cnx_set context manager uses

It has been deprecated in a previous changeset and is now a no-op.

Related to #2919309.

authorAurelien Campeas <aurelien.campeas@logilab.fr>
changeset21461f80f348
branchdefault
phasepublic
hiddenno
parent revision#8b35a898b334 [server] remove cnxset tracking, it is now unneeded
child revision#38c7598b5c61 [connection] remove the `mode` attribute
files modified by this revision
devtools/repotest.py
hooks/test/unittest_syncschema.py
server/checkintegrity.py
server/migractions.py
server/repository.py
server/schemaserial.py
server/sources/native.py
server/test/unittest_querier.py
server/test/unittest_repository.py
server/test/unittest_undo.py
# HG changeset patch
# User Aurelien Campeas <aurelien.campeas@logilab.fr>
# Date 1402499672 -7200
# Wed Jun 11 17:14:32 2014 +0200
# Node ID 21461f80f348fb811d6709f098edf94f83681a8e
# Parent 8b35a898b334930ac7fe5c55ce117cd25c5ef239
[connection] remove ensure_cnx_set context manager uses

It has been deprecated in a previous changeset and is now a no-op.

Related to #2919309.

diff --git a/devtools/repotest.py b/devtools/repotest.py
@@ -257,16 +257,15 @@
1              s = Session(u, self.repo)
2              return s
3 
4      def qexecute(self, rql, args=None, build_descr=True):
5          with self.session.new_cnx() as cnx:
6 -            with cnx.ensure_cnx_set:
7 -                try:
8 -                    return self.o.execute(cnx, rql, args, build_descr)
9 -                finally:
10 -                    if rql.startswith(('INSERT', 'DELETE', 'SET')):
11 -                        cnx.commit()
12 +            try:
13 +                return self.o.execute(cnx, rql, args, build_descr)
14 +            finally:
15 +                if rql.startswith(('INSERT', 'DELETE', 'SET')):
16 +                    cnx.commit()
17 
18 
19  class BasePlannerTC(BaseQuerierTC):
20 
21      def setup(self):
diff --git a/hooks/test/unittest_syncschema.py b/hooks/test/unittest_syncschema.py
@@ -36,16 +36,15 @@
22          self.repo.set_schema(self.repo.deserialize_schema(), resetvreg=False)
23          self.__class__.schema_eids = schema_eids_idx(self.repo.schema)
24 
25      def index_exists(self, cnx, etype, attr, unique=False):
26          dbhelper = self.repo.system_source.dbhelper
27 -        with cnx.ensure_cnx_set:
28 -            sqlcursor = cnx.cnxset.cu
29 -            return dbhelper.index_exists(sqlcursor,
30 -                                         SQL_PREFIX + etype,
31 -                                         SQL_PREFIX + attr,
32 -                                         unique=unique)
33 +        sqlcursor = cnx.cnxset.cu
34 +        return dbhelper.index_exists(sqlcursor,
35 +                                     SQL_PREFIX + etype,
36 +                                     SQL_PREFIX + attr,
37 +                                     unique=unique)
38 
39      def _set_perms(self, cnx, eid):
40          cnx.execute('SET X read_permission G WHERE X eid %(x)s, G is CWGroup',
41                      {'x': eid})
42          cnx.execute('SET X add_permission G WHERE X eid %(x)s, G is CWGroup, '
diff --git a/server/checkintegrity.py b/server/checkintegrity.py
@@ -86,15 +86,14 @@
43      """reindex all entities in the repository"""
44      # deactivate modification_date hook since we don't want them
45      # to be updated due to the reindexation
46      repo = cnx.repo
47      dbhelper = repo.system_source.dbhelper
48 -    with cnx.ensure_cnx_set:
49 -        cursor = cnx.cnxset.cu
50 -        if not dbhelper.has_fti_table(cursor):
51 -            print 'no text index table'
52 -            dbhelper.init_fti(cursor)
53 +    cursor = cnx.cnxset.cu
54 +    if not dbhelper.has_fti_table(cursor):
55 +        print 'no text index table'
56 +        dbhelper.init_fti(cursor)
57      repo.system_source.do_fti = True  # ensure full-text indexation is activated
58      if etypes is None:
59          print 'Reindexing entities'
60          etypes = set()
61          for eschema in schema.entities():
@@ -398,18 +397,16 @@
62      if checks:
63          eids_cache = {}
64          with cnx.security_enabled(read=False, write=False): # ensure no read security
65              for check in checks:
66                  check_func = globals()['check_%s' % check]
67 -                with cnx.ensure_cnx_set:
68 -                    check_func(repo.schema, cnx, eids_cache, fix=fix)
69 +                check_func(repo.schema, cnx, eids_cache, fix=fix)
70          if fix:
71              cnx.commit()
72          else:
73              print
74          if not fix:
75              print 'WARNING: Diagnostic run, nothing has been corrected'
76      if reindex:
77          cnx.rollback()
78 -        with cnx.ensure_cnx_set:
79 -            reindex_entities(repo.schema, cnx, withpb=withpb)
80 +        reindex_entities(repo.schema, cnx, withpb=withpb)
81          cnx.commit()
diff --git a/server/migractions.py b/server/migractions.py
@@ -176,19 +176,18 @@
82          # disable notification during migration
83          with self.cnx.allow_all_hooks_but('notification'):
84              super(ServerMigrationHelper, self).migrate(vcconf, toupgrade, options)
85 
86      def cmd_process_script(self, migrscript, funcname=None, *args, **kwargs):
87 -        with self.cnx.ensure_cnx_set:
88 -            try:
89 -                return super(ServerMigrationHelper, self).cmd_process_script(
90 -                      migrscript, funcname, *args, **kwargs)
91 -            except ExecutionError as err:
92 -                sys.stderr.write("-> %s\n" % err)
93 -            except BaseException:
94 -                self.rollback()
95 -                raise
96 +        try:
97 +            return super(ServerMigrationHelper, self).cmd_process_script(
98 +                  migrscript, funcname, *args, **kwargs)
99 +        except ExecutionError as err:
100 +            sys.stderr.write("-> %s\n" % err)
101 +        except BaseException:
102 +            self.rollback()
103 +            raise
104 
105      # Adjust docstring
106      cmd_process_script.__doc__ = MigrationHelper.cmd_process_script.__doc__
107 
108      # server specific migration methods ########################################
diff --git a/server/repository.py b/server/repository.py
@@ -446,12 +446,11 @@
109          # iter on sources_by_uri then check enabled source since sources doesn't
110          # contain copy based sources
111          for source in self.sources_by_uri.itervalues():
112              if self.config.source_enabled(source) and source.support_entity('CWUser'):
113                  try:
114 -                    with cnx.ensure_cnx_set:
115 -                        return source.authenticate(cnx, login, **authinfo)
116 +                    return source.authenticate(cnx, login, **authinfo)
117                  except AuthenticationError:
118                      continue
119          else:
120              raise AuthenticationError('authentication failed with all sources')
121 
@@ -466,23 +465,22 @@
122              raise AuthenticationError('user is not in authenticable state')
123          return cwuser
124 
125      def _build_user(self, cnx, eid):
126          """return a CWUser entity for user with the given eid"""
127 -        with cnx.ensure_cnx_set:
128 -            cls = self.vreg['etypes'].etype_class('CWUser')
129 -            st = cls.fetch_rqlst(cnx.user, ordermethod=None)
130 -            st.add_eid_restriction(st.get_variable('X'), 'x', 'Substitute')
131 -            rset = cnx.execute(st.as_string(), {'x': eid})
132 -            assert len(rset) == 1, rset
133 -            cwuser = rset.get_entity(0, 0)
134 -            # pylint: disable=W0104
135 -            # prefetch / cache cwuser's groups and properties. This is especially
136 -            # useful for internal sessions to avoid security insertions
137 -            cwuser.groups
138 -            cwuser.properties
139 -            return cwuser
140 +        cls = self.vreg['etypes'].etype_class('CWUser')
141 +        st = cls.fetch_rqlst(cnx.user, ordermethod=None)
142 +        st.add_eid_restriction(st.get_variable('X'), 'x', 'Substitute')
143 +        rset = cnx.execute(st.as_string(), {'x': eid})
144 +        assert len(rset) == 1, rset
145 +        cwuser = rset.get_entity(0, 0)
146 +        # pylint: disable=W0104
147 +        # prefetch / cache cwuser's groups and properties. This is especially
148 +        # useful for internal sessions to avoid security insertions
149 +        cwuser.groups
150 +        cwuser.properties
151 +        return cwuser
152 
153      # public (dbapi) interface ################################################
154 
155      @deprecated("[3.19] use _cw.call_service('repo_stats')")
156      def stats(self): # XXX restrict to managers session?
@@ -717,12 +715,11 @@
157          connections have all hooks beside security enabled.
158          """
159          with Session(InternalManager(), self) as session:
160              with session.new_cnx() as cnx:
161                  with cnx.security_enabled(read=False, write=False):
162 -                    with cnx.ensure_cnx_set:
163 -                        yield cnx
164 +                    yield cnx
165 
166      def _get_session(self, sessionid, txid=None, checkshuttingdown=True):
167          """return the session associated with the given session identifier"""
168          if checkshuttingdown and self.shutting_down:
169              raise ShuttingDown('Repository is shutting down')
@@ -810,50 +807,47 @@
170          """
171          try:
172              return self._extid_cache[extid]
173          except KeyError:
174              pass
175 -        with cnx.ensure_cnx_set:
176 -            eid = self.system_source.extid2eid(cnx, extid)
177 +        eid = self.system_source.extid2eid(cnx, extid)
178          if eid is not None:
179              self._extid_cache[extid] = eid
180              self._type_source_cache[eid] = (etype, extid, source.uri)
181              return eid
182          if not insert:
183              return
184          # no link between extid and eid, create one
185 -        with cnx.ensure_cnx_set:
186 -            # write query, ensure connection's mode is 'write' so connections
187 -            # won't be released until commit/rollback
188 -            cnx.mode = 'write'
189 -            try:
190 -                eid = self.system_source.create_eid(cnx)
191 -                self._extid_cache[extid] = eid
192 -                self._type_source_cache[eid] = (etype, extid, source.uri)
193 -                entity = source.before_entity_insertion(
194 -                    cnx, extid, etype, eid, sourceparams)
195 +        # write query, ensure connection's mode is 'write' so connections
196 +        # won't be released until commit/rollback
197 +        try:
198 +            eid = self.system_source.create_eid(cnx)
199 +            self._extid_cache[extid] = eid
200 +            self._type_source_cache[eid] = (etype, extid, source.uri)
201 +            entity = source.before_entity_insertion(
202 +                cnx, extid, etype, eid, sourceparams)
203 +            if source.should_call_hooks:
204 +                # get back a copy of operation for later restore if
205 +                # necessary, see below
206 +                pending_operations = cnx.pending_operations[:]
207 +                self.hm.call_hooks('before_add_entity', cnx, entity=entity)
208 +            self.add_info(cnx, entity, source, extid)
209 +            source.after_entity_insertion(cnx, extid, entity, sourceparams)
210 +            if source.should_call_hooks:
211 +                self.hm.call_hooks('after_add_entity', cnx, entity=entity)
212 +            return eid
213 +        except Exception:
214 +            # XXX do some cleanup manually so that the transaction has a
215 +            # chance to be commited, with simply this entity discarded
216 +            self._extid_cache.pop(extid, None)
217 +            self._type_source_cache.pop(eid, None)
218 +            if 'entity' in locals():
219 +                hook.CleanupDeletedEidsCacheOp.get_instance(cnx).add_data(entity.eid)
220 +                self.system_source.delete_info_multi(cnx, [entity])
221                  if source.should_call_hooks:
222 -                    # get back a copy of operation for later restore if
223 -                    # necessary, see below
224 -                    pending_operations = cnx.pending_operations[:]
225 -                    self.hm.call_hooks('before_add_entity', cnx, entity=entity)
226 -                self.add_info(cnx, entity, source, extid)
227 -                source.after_entity_insertion(cnx, extid, entity, sourceparams)
228 -                if source.should_call_hooks:
229 -                    self.hm.call_hooks('after_add_entity', cnx, entity=entity)
230 -                return eid
231 -            except Exception:
232 -                # XXX do some cleanup manually so that the transaction has a
233 -                # chance to be commited, with simply this entity discarded
234 -                self._extid_cache.pop(extid, None)
235 -                self._type_source_cache.pop(eid, None)
236 -                if 'entity' in locals():
237 -                    hook.CleanupDeletedEidsCacheOp.get_instance(cnx).add_data(entity.eid)
238 -                    self.system_source.delete_info_multi(cnx, [entity])
239 -                    if source.should_call_hooks:
240 -                        cnx.pending_operations = pending_operations
241 -                raise
242 +                    cnx.pending_operations = pending_operations
243 +            raise
244 
245      def add_info(self, cnx, entity, source, extid=None):
246          """add type and source info for an eid into the system table,
247          and index the entity with the full text index
248          """
diff --git a/server/schemaserial.py b/server/schemaserial.py
@@ -106,18 +106,17 @@
249      except Exception:
250          cnx.rollback()
251          has_computed_attributes = False
252 
253      # XXX bw compat (3.6 migration)
254 -    with cnx.ensure_cnx_set:
255 -        sqlcu = cnx.system_sql("SELECT * FROM cw_CWRType WHERE cw_name='symetric'")
256 -        if sqlcu.fetchall():
257 -            sql = dbhelper.sql_rename_col('cw_CWRType', 'cw_symetric', 'cw_symmetric',
258 -                                          dbhelper.TYPE_MAPPING['Boolean'], True)
259 -            sqlcu.execute(sql)
260 -            sqlcu.execute("UPDATE cw_CWRType SET cw_name='symmetric' WHERE cw_name='symetric'")
261 -            cnx.commit(False)
262 +    sqlcu = cnx.system_sql("SELECT * FROM cw_CWRType WHERE cw_name='symetric'")
263 +    if sqlcu.fetchall():
264 +        sql = dbhelper.sql_rename_col('cw_CWRType', 'cw_symetric', 'cw_symmetric',
265 +                                      dbhelper.TYPE_MAPPING['Boolean'], True)
266 +        sqlcu.execute(sql)
267 +        sqlcu.execute("UPDATE cw_CWRType SET cw_name='symmetric' WHERE cw_name='symetric'")
268 +        cnx.commit()
269      ertidx = {}
270      copiedeids = set()
271      permsidx = deserialize_ertype_permissions(cnx)
272      schema.reading_from_database = True
273      # load every entity types
diff --git a/server/sources/native.py b/server/sources/native.py
@@ -1017,14 +1017,13 @@
274                  sql += ' WHERE %s' % ' OR '.join(subqsqls)
275              restr.update(trarestr)
276              restr.update(tearestr)
277          # we want results ordered by transaction's time descendant
278          sql += ' ORDER BY tx_time DESC'
279 -        with cnx.ensure_cnx_set:
280 -            cu = self.doexec(cnx, sql, restr)
281 -            # turn results into transaction objects
282 -            return [tx.Transaction(cnx, *args) for args in cu.fetchall()]
283 +        cu = self.doexec(cnx, sql, restr)
284 +        # turn results into transaction objects
285 +        return [tx.Transaction(cnx, *args) for args in cu.fetchall()]
286 
287      def tx_info(self, cnx, txuuid):
288          """See :class:`cubicweb.repoapi.Connection.transaction_info`"""
289          return tx.Transaction(cnx, txuuid, *self._tx_info(cnx, unicode(txuuid)))
290 
@@ -1117,23 +1116,22 @@
291          """return transaction's time and user of the transaction with the given uuid.
292 
293          raise `NoSuchTransaction` if there is no such transaction of if the
294          connection's user isn't allowed to see it.
295          """
296 -        with cnx.ensure_cnx_set:
297 -            restr = {'tx_uuid': txuuid}
298 -            sql = self.sqlgen.select('transactions', restr,
299 -                                     ('tx_time', 'tx_user'))
300 -            cu = self.doexec(cnx, sql, restr)
301 -            try:
302 -                time, ueid = cu.fetchone()
303 -            except TypeError:
304 -                raise tx.NoSuchTransaction(txuuid)
305 -            if not (cnx.user.is_in_group('managers')
306 -                    or cnx.user.eid == ueid):
307 -                raise tx.NoSuchTransaction(txuuid)
308 -            return time, ueid
309 +        restr = {'tx_uuid': txuuid}
310 +        sql = self.sqlgen.select('transactions', restr,
311 +                                 ('tx_time', 'tx_user'))
312 +        cu = self.doexec(cnx, sql, restr)
313 +        try:
314 +            time, ueid = cu.fetchone()
315 +        except TypeError:
316 +            raise tx.NoSuchTransaction(txuuid)
317 +        if not (cnx.user.is_in_group('managers')
318 +                or cnx.user.eid == ueid):
319 +            raise tx.NoSuchTransaction(txuuid)
320 +        return time, ueid
321 
322      def _reedit_entity(self, entity, changes, err):
323          cnx = entity._cw
324          eid = entity.eid
325          entity.cw_edited = edited = EditedEntity(entity)
diff --git a/server/test/unittest_querier.py b/server/test/unittest_querier.py
@@ -1170,15 +1170,14 @@
326          self.assertEqual(len(rset.rows), 0, rset.rows)
327 
328      def test_delete_3(self):
329          s = self.user_groups_session('users')
330          with s.new_cnx() as cnx:
331 -            with cnx.ensure_cnx_set:
332 -                peid, = self.o.execute(cnx, "INSERT Personne P: P nom 'toto'")[0]
333 -                seid, = self.o.execute(cnx, "INSERT Societe S: S nom 'logilab'")[0]
334 -                self.o.execute(cnx, "SET P travaille S")
335 -                cnx.commit()
336 +            peid, = self.o.execute(cnx, "INSERT Personne P: P nom 'toto'")[0]
337 +            seid, = self.o.execute(cnx, "INSERT Societe S: S nom 'logilab'")[0]
338 +            self.o.execute(cnx, "SET P travaille S")
339 +            cnx.commit()
340          rset = self.qexecute('Personne P WHERE P travaille S')
341          self.assertEqual(len(rset.rows), 1)
342          self.qexecute("DELETE X travaille Y WHERE X eid %s, Y eid %s" % (peid, seid))
343          rset = self.qexecute('Personne P WHERE P travaille S')
344          self.assertEqual(len(rset.rows), 0)
@@ -1209,16 +1208,15 @@
345          #'INSERT Email X: X messageid "<1234>", X subject "test", X sender Y, X recipients Y'
346          eeid, = self.qexecute('INSERT Email X: X messageid "<1234>", X subject "test", '
347                                'X sender Y, X recipients Y WHERE Y is EmailAddress')[0]
348          self.qexecute("DELETE Email X")
349          with self.session.new_cnx() as cnx:
350 -            with cnx.ensure_cnx_set:
351 -                sqlc = cnx.cnxset.cu
352 -                sqlc.execute('SELECT * FROM recipients_relation')
353 -                self.assertEqual(len(sqlc.fetchall()), 0)
354 -                sqlc.execute('SELECT * FROM owned_by_relation WHERE eid_from=%s'%eeid)
355 -                self.assertEqual(len(sqlc.fetchall()), 0)
356 +            sqlc = cnx.cnxset.cu
357 +            sqlc.execute('SELECT * FROM recipients_relation')
358 +            self.assertEqual(len(sqlc.fetchall()), 0)
359 +            sqlc.execute('SELECT * FROM owned_by_relation WHERE eid_from=%s'%eeid)
360 +            self.assertEqual(len(sqlc.fetchall()), 0)
361 
362      def test_nonregr_delete_cache2(self):
363          eid = self.qexecute("INSERT Folder T: T name 'toto'")[0][0]
364          # fill the cache
365          self.qexecute("Any X WHERE X eid %(x)s", {'x': eid})
@@ -1361,38 +1359,36 @@
366          self.assertEqual(len(rset.rows), 1)
367          self.assertEqual(rset.description, [('CWUser',)])
368          self.assertRaises(Unauthorized,
369                            self.qexecute, "Any P WHERE X is CWUser, X login 'bob', X upassword P")
370          with self.session.new_cnx() as cnx:
371 -            with cnx.ensure_cnx_set:
372 -                cursor = cnx.cnxset.cu
373 -                cursor.execute("SELECT %supassword from %sCWUser WHERE %slogin='bob'"
374 -                               % (SQL_PREFIX, SQL_PREFIX, SQL_PREFIX))
375 -                passwd = str(cursor.fetchone()[0])
376 -                self.assertEqual(passwd, crypt_password('toto', passwd))
377 +            cursor = cnx.cnxset.cu
378 +            cursor.execute("SELECT %supassword from %sCWUser WHERE %slogin='bob'"
379 +                           % (SQL_PREFIX, SQL_PREFIX, SQL_PREFIX))
380 +            passwd = str(cursor.fetchone()[0])
381 +            self.assertEqual(passwd, crypt_password('toto', passwd))
382          rset = self.qexecute("Any X WHERE X is CWUser, X login 'bob', X upassword %(pwd)s",
383                              {'pwd': Binary(passwd)})
384          self.assertEqual(len(rset.rows), 1)
385          self.assertEqual(rset.description, [('CWUser',)])
386 
387      def test_update_upassword(self):
388          with self.session.new_cnx() as cnx:
389 -            with cnx.ensure_cnx_set:
390 -                rset = cnx.execute("INSERT CWUser X: X login 'bob', X upassword %(pwd)s",
391 -                                   {'pwd': 'toto'})
392 -                self.assertEqual(rset.description[0][0], 'CWUser')
393 -                rset = cnx.execute("SET X upassword %(pwd)s WHERE X is CWUser, X login 'bob'",
394 -                                   {'pwd': 'tutu'})
395 -                cursor = cnx.cnxset.cu
396 -                cursor.execute("SELECT %supassword from %sCWUser WHERE %slogin='bob'"
397 -                               % (SQL_PREFIX, SQL_PREFIX, SQL_PREFIX))
398 -                passwd = str(cursor.fetchone()[0])
399 -                self.assertEqual(passwd, crypt_password('tutu', passwd))
400 -                rset = cnx.execute("Any X WHERE X is CWUser, X login 'bob', X upassword %(pwd)s",
401 -                                   {'pwd': Binary(passwd)})
402 -                self.assertEqual(len(rset.rows), 1)
403 -                self.assertEqual(rset.description, [('CWUser',)])
404 +            rset = cnx.execute("INSERT CWUser X: X login 'bob', X upassword %(pwd)s",
405 +                               {'pwd': 'toto'})
406 +            self.assertEqual(rset.description[0][0], 'CWUser')
407 +            rset = cnx.execute("SET X upassword %(pwd)s WHERE X is CWUser, X login 'bob'",
408 +                               {'pwd': 'tutu'})
409 +            cursor = cnx.cnxset.cu
410 +            cursor.execute("SELECT %supassword from %sCWUser WHERE %slogin='bob'"
411 +                           % (SQL_PREFIX, SQL_PREFIX, SQL_PREFIX))
412 +            passwd = str(cursor.fetchone()[0])
413 +            self.assertEqual(passwd, crypt_password('tutu', passwd))
414 +            rset = cnx.execute("Any X WHERE X is CWUser, X login 'bob', X upassword %(pwd)s",
415 +                               {'pwd': Binary(passwd)})
416 +            self.assertEqual(len(rset.rows), 1)
417 +            self.assertEqual(rset.description, [('CWUser',)])
418 
419      # ZT datetime tests ########################################################
420 
421      def test_tz_datetime(self):
422          self.qexecute("INSERT Personne X: X nom 'bob', X tzdatenaiss %(date)s",
diff --git a/server/test/unittest_repository.py b/server/test/unittest_repository.py
@@ -201,14 +201,13 @@
423      def test_internal_api(self):
424          repo = self.repo
425          cnxid = repo.connect(self.admlogin, password=self.admpassword)
426          session = repo._get_session(cnxid)
427          with session.new_cnx() as cnx:
428 -            with cnx.ensure_cnx_set:
429 -                self.assertEqual(repo.type_and_source_from_eid(2, cnx),
430 -                                 ('CWGroup', None, 'system'))
431 -                self.assertEqual(repo.type_from_eid(2, cnx), 'CWGroup')
432 +            self.assertEqual(repo.type_and_source_from_eid(2, cnx),
433 +                             ('CWGroup', None, 'system'))
434 +            self.assertEqual(repo.type_from_eid(2, cnx), 'CWGroup')
435          repo.close(cnxid)
436 
437      def test_public_api(self):
438          self.assertEqual(self.repo.get_schema(), self.repo.schema)
439          self.assertEqual(self.repo.source_defs(), {'system': {'type': 'native',
@@ -383,42 +382,41 @@
440              self.repo.set_schema(self.repo.deserialize_schema())
441              table = SQL_PREFIX + 'CWEType'
442              namecol = SQL_PREFIX + 'name'
443              finalcol = SQL_PREFIX + 'final'
444              with self.admin_access.repo_cnx() as cnx:
445 -                with cnx.ensure_cnx_set:
446 -                    cu = cnx.system_sql('SELECT %s FROM %s WHERE %s is NULL'
447 -                                        % (namecol, table, finalcol))
448 -                    self.assertEqual(cu.fetchall(), [])
449 -                    cu = cnx.system_sql('SELECT %s FROM %s '
450 -                                        'WHERE %s=%%(final)s ORDER BY %s'
451 -                                        % (namecol, table, finalcol, namecol),
452 -                                        {'final': True})
453 -                    self.assertEqual(cu.fetchall(),
454 -                                     [(u'BabarTestType',),
455 -                                      (u'BigInt',), (u'Boolean',), (u'Bytes',),
456 -                                      (u'Date',), (u'Datetime',),
457 -                                      (u'Decimal',),(u'Float',),
458 -                                      (u'Int',),
459 -                                      (u'Interval',), (u'Password',),
460 -                                      (u'String',),
461 -                                      (u'TZDatetime',), (u'TZTime',), (u'Time',)])
462 -                    sql = ("SELECT etype.cw_eid, etype.cw_name, cstr.cw_eid, rel.eid_to "
463 -                           "FROM cw_CWUniqueTogetherConstraint as cstr, "
464 -                           "     relations_relation as rel, "
465 -                           "     cw_CWEType as etype "
466 -                           "WHERE cstr.cw_eid = rel.eid_from "
467 -                           "  AND cstr.cw_constraint_of = etype.cw_eid "
468 -                           "  AND etype.cw_name = 'Personne' "
469 -                           ";")
470 -                    cu = cnx.system_sql(sql)
471 -                    rows = cu.fetchall()
472 -                    self.assertEqual(len(rows), 3)
473 -                    person = self.repo.schema.eschema('Personne')
474 -                    self.assertEqual(len(person._unique_together), 1)
475 -                    self.assertItemsEqual(person._unique_together[0],
476 -                                          ('nom', 'prenom', 'inline2'))
477 +                cu = cnx.system_sql('SELECT %s FROM %s WHERE %s is NULL'
478 +                                    % (namecol, table, finalcol))
479 +                self.assertEqual(cu.fetchall(), [])
480 +                cu = cnx.system_sql('SELECT %s FROM %s '
481 +                                    'WHERE %s=%%(final)s ORDER BY %s'
482 +                                    % (namecol, table, finalcol, namecol),
483 +                                    {'final': True})
484 +                self.assertEqual(cu.fetchall(),
485 +                                 [(u'BabarTestType',),
486 +                                  (u'BigInt',), (u'Boolean',), (u'Bytes',),
487 +                                  (u'Date',), (u'Datetime',),
488 +                                  (u'Decimal',),(u'Float',),
489 +                                  (u'Int',),
490 +                                  (u'Interval',), (u'Password',),
491 +                                  (u'String',),
492 +                                  (u'TZDatetime',), (u'TZTime',), (u'Time',)])
493 +                sql = ("SELECT etype.cw_eid, etype.cw_name, cstr.cw_eid, rel.eid_to "
494 +                       "FROM cw_CWUniqueTogetherConstraint as cstr, "
495 +                       "     relations_relation as rel, "
496 +                       "     cw_CWEType as etype "
497 +                       "WHERE cstr.cw_eid = rel.eid_from "
498 +                       "  AND cstr.cw_constraint_of = etype.cw_eid "
499 +                       "  AND etype.cw_name = 'Personne' "
500 +                       ";")
501 +                cu = cnx.system_sql(sql)
502 +                rows = cu.fetchall()
503 +                self.assertEqual(len(rows), 3)
504 +                person = self.repo.schema.eschema('Personne')
505 +                self.assertEqual(len(person._unique_together), 1)
506 +                self.assertItemsEqual(person._unique_together[0],
507 +                                      ('nom', 'prenom', 'inline2'))
508 
509          finally:
510              self.repo.set_schema(origshema)
511 
512      def test_custom_attribute_param(self):
@@ -437,34 +435,31 @@
513 
514  class DataHelpersTC(CubicWebTC):
515 
516      def test_type_from_eid(self):
517          with self.admin_access.repo_cnx() as cnx:
518 -            with cnx.ensure_cnx_set:
519 -                self.assertEqual(self.repo.type_from_eid(2, cnx), 'CWGroup')
520 +            self.assertEqual(self.repo.type_from_eid(2, cnx), 'CWGroup')
521 
522      def test_type_from_eid_raise(self):
523          with self.admin_access.repo_cnx() as cnx:
524 -            with cnx.ensure_cnx_set:
525 -                self.assertRaises(UnknownEid, self.repo.type_from_eid, -2, cnx)
526 +            self.assertRaises(UnknownEid, self.repo.type_from_eid, -2, cnx)
527 
528      def test_add_delete_info(self):
529          with self.admin_access.repo_cnx() as cnx:
530 -            with cnx.ensure_cnx_set:
531 -                cnx.mode = 'write'
532 -                entity = self.repo.vreg['etypes'].etype_class('Personne')(cnx)
533 -                entity.eid = -1
534 -                entity.complete = lambda x: None
535 -                self.repo.add_info(cnx, entity, self.repo.system_source)
536 -                cu = cnx.system_sql('SELECT * FROM entities WHERE eid = -1')
537 -                data = cu.fetchall()
538 -                self.assertEqual(tuplify(data), [(-1, 'Personne', 'system', None)])
539 -                self.repo._delete_cascade_multi(cnx, [entity])
540 -                self.repo.system_source.delete_info_multi(cnx, [entity])
541 -                cu = cnx.system_sql('SELECT * FROM entities WHERE eid = -1')
542 -                data = cu.fetchall()
543 -                self.assertEqual(data, [])
544 +            cnx.mode = 'write'
545 +            entity = self.repo.vreg['etypes'].etype_class('Personne')(cnx)
546 +            entity.eid = -1
547 +            entity.complete = lambda x: None
548 +            self.repo.add_info(cnx, entity, self.repo.system_source)
549 +            cu = cnx.system_sql('SELECT * FROM entities WHERE eid = -1')
550 +            data = cu.fetchall()
551 +            self.assertEqual(tuplify(data), [(-1, 'Personne', 'system', None)])
552 +            self.repo._delete_cascade_multi(cnx, [entity])
553 +            self.repo.system_source.delete_info_multi(cnx, [entity])
554 +            cu = cnx.system_sql('SELECT * FROM entities WHERE eid = -1')
555 +            data = cu.fetchall()
556 +            self.assertEqual(data, [])
557 
558 
559  class FTITC(CubicWebTC):
560 
561      def test_fulltext_container_entity(self):
diff --git a/server/test/unittest_undo.py b/server/test/unittest_undo.py
@@ -212,12 +212,11 @@
562              txs = cnx.undoable_transactions()
563              self.assertEqual(len(txs), 2)
564              self.assertRaises(NoSuchTransaction,
565                                cnx.transaction_info, txuuid)
566          with self.admin_access.repo_cnx() as cnx:
567 -            with cnx.ensure_cnx_set:
568 -                self.check_transaction_deleted(cnx, txuuid)
569 +            self.check_transaction_deleted(cnx, txuuid)
570              # the final test: check we can login with the previously deleted user
571          with self.new_access('toto').client_cnx():
572              pass
573 
574      def test_undo_deletion_integrity_1(self):
@@ -271,22 +270,21 @@
575              cnx.commit()
576              self.assertFalse(cnx.execute('Any X WHERE X eid %(x)s', {'x': c.eid}))
577              self.assertFalse(cnx.execute('Any X WHERE X eid %(x)s', {'x': p.eid}))
578              self.assertFalse(cnx.execute('Any X,Y WHERE X fiche Y'))
579          with self.admin_access.repo_cnx() as cnx:
580 -            with cnx.ensure_cnx_set:
581 -                for eid in (p.eid, c.eid):
582 -                    self.assertFalse(cnx.system_sql(
583 -                        'SELECT * FROM entities WHERE eid=%s' % eid).fetchall())
584 -                    self.assertFalse(cnx.system_sql(
585 -                        'SELECT 1 FROM owned_by_relation WHERE eid_from=%s' % eid).fetchall())
586 -                    # added by sql in hooks (except when using dataimport)
587 -                    self.assertFalse(cnx.system_sql(
588 -                        'SELECT 1 FROM is_relation WHERE eid_from=%s' % eid).fetchall())
589 -                    self.assertFalse(cnx.system_sql(
590 -                        'SELECT 1 FROM is_instance_of_relation WHERE eid_from=%s' % eid).fetchall())
591 -                self.check_transaction_deleted(cnx, txuuid)
592 +            for eid in (p.eid, c.eid):
593 +                self.assertFalse(cnx.system_sql(
594 +                    'SELECT * FROM entities WHERE eid=%s' % eid).fetchall())
595 +                self.assertFalse(cnx.system_sql(
596 +                    'SELECT 1 FROM owned_by_relation WHERE eid_from=%s' % eid).fetchall())
597 +                # added by sql in hooks (except when using dataimport)
598 +                self.assertFalse(cnx.system_sql(
599 +                    'SELECT 1 FROM is_relation WHERE eid_from=%s' % eid).fetchall())
600 +                self.assertFalse(cnx.system_sql(
601 +                    'SELECT 1 FROM is_instance_of_relation WHERE eid_from=%s' % eid).fetchall())
602 +            self.check_transaction_deleted(cnx, txuuid)
603 
604      def test_undo_creation_integrity_1(self):
605          with self.admin_access.client_cnx() as cnx:
606              tutu = self.create_user(cnx, 'tutu', commit=False)
607              txuuid = cnx.commit()
@@ -355,13 +353,12 @@
608                  "Can't restore relation fiche, object entity %d doesn't exist anymore." % c.eid])
609              cnx.commit()
610              p.cw_clear_all_caches()
611              self.assertFalse(p.fiche)
612          with self.admin_access.repo_cnx() as cnx:
613 -            with cnx.ensure_cnx_set:
614 -                self.assertIsNone(cnx.system_sql(
615 -                    'SELECT cw_fiche FROM cw_Personne WHERE cw_eid=%s' % p.eid).fetchall()[0][0])
616 +            self.assertIsNone(cnx.system_sql(
617 +                'SELECT cw_fiche FROM cw_Personne WHERE cw_eid=%s' % p.eid).fetchall()[0][0])
618 
619      def test_undo_inline_rel_add_ok(self):
620          """Undo add relation  Personne (?) fiche (?) Card
621 
622          Caution processed by `_undo_u`, not `_undo_a` !"""