Christian Boos committed 3a9049d

env: unify `get_db_cnx` with `get_read_db`.

As ''transaction-safe'' usage of db connection require the use of `with_transaction`, the legacy `get_db_cnx` which was used to indifferently get connections for reading or for writing should not be used anymore. However, as we continue to support it for 0.12.x, it can nevertheless be made aware of the new mechanism by doing the same thing as `get_read_db`:
- when used for reading, it can therefore benefit from the immediate reuse of the thread-local Connection used for the transaction in progress, if there is one
- when used for writing, what happens is not worse than before, the "explicit" transaction management (i.e. the `commit` pairing the `get_db_cnx`) may terminate a transaction sooner than wanted, in the case this was a nested transaction

  • Participants
  • Parent commits 39b345d
  • Branches trunk

Comments (0)

Files changed (4)

File trac/admin/tests/

     A subclass of Environment that keeps its DB in memory.
+    def get_read_db(self):
+        return self.get_db_cnx()
     def get_db_cnx(self):
         if not hasattr(self, '_db'):
             self._db = InMemoryDatabase()
             value = out.getvalue()
             if isinstance(value, str): # reverse what print_listing did
                 value = value.decode('utf-8')
+            # DEBUG: uncomment in case of `AssertionError: 0 != 2` in tests
+            #if retval != 0:
+            #    print>>_err, value
             if strip_trailing_space:
                 return retval, STRIP_TRAILING_SPACE.sub('', value)

File trac/db/

 def get_read_db(env):
     """Get a database connection for reading only."""
-    return _transaction_local.db or env.get_db_cnx()
+    from trac.db.api import DatabaseManager
+    return _transaction_local.db or DatabaseManager(env).get_connection()
 def sql_escape_percent(sql):
         Use `with_transaction` for obtaining a writable database connection
         and `get_read_db` for anything else.
-        return DatabaseManager(self).get_connection()
+        return get_read_db(self)
     def with_transaction(self, db=None):
         """Decorator for transaction functions.

File trac/

         self.known_users = []
         translation.activate(Locale and Locale('en', 'US'))
+    def get_read_db(self):
+        return self.get_db_cnx()
     def get_db_cnx(self, destroying=False):
         if self.db:
             return self.db # in-memory SQLite