Edgewall Software

Changes between Version 9 and Version 10 of TracDev/DatabaseApi


Ignore:
Timestamp:
Apr 15, 2009, 11:49:38 PM (15 years ago)
Author:
jerry
Comment:

Add some information about pooled connections

Legend:

Unmodified
Added
Removed
Modified
  • TracDev/DatabaseApi

    v9 v10  
    1212== Accessing the Database ==
    1313
    14 Code accessing the database in Trac go through this layer simply by using the {{{Environment}}} method {{{get_db_cnx()}}}:
     14Code accessing the database in Trac go through this layer simply by using the {{{Environment}}} method {{{get_db_cnx()}}} in order to get a pooled database connection.  A database cursor can be obtained from the pooled database connection, and the code uses the cursor in conjunction with SQL statements to implement the behavior. 
    1515
    1616{{{
    1717#!python
    1818from trac.env import Environment
     19def myFunc():
     20    env = Environment('/path/to/projenv')
     21    db = env.get_db_cnx()
     22    cursor = db.cursor()
     23    # Execute some SQL statements
    1924
    20 env = Environment('/path/to/projenv')
    21 db = env.get_db_cnx()
    22 cursor = db.cursor()
    23 # Execute some SQL statements
    24 
    25 db.commit()
     25    db.commit()
     26    return
    2627}}}
    2728
     
    3435
    3536 ''The connection URI syntax has been designed to be compatible with that provided by [http://sqlobject.org/docs/SQLObject.html#declaring-the-class SQLObject] (see also the Wiki page on SQLObject [http://wiki.sqlobject.org/connections.html connections]). The only supported URI schemes at this point are {{{sqlite}}} and {{{postgres}}}.''
     37
     38=== Pooled Connections ===
     39
     40The {{{Environment}}} method {{{get_db_cnx()}}} returns a connection from the pool of connections.  This connection needs to be returned, and Trac is written so that the return will happen automatically by the garbage collector if the code is written to follow a simple rule.  When the garbage collector determines the pooled database connection is no longer being used, it's __del__ method will return the pooled connection to the pool for reuse.  If you have set a lexical variable in the function's body to the pooled connection, this typically occurs when the function is returning.  In the example above of {{{myFunc}}} it occurs at the return statement since {{{db}}} is a variable local to {{{myFunc}}}
    3641
    3742== Rules for DB API Usage ==