Managing database connections

The basic XRecordDatabase functionality is not very different from other connection objects provided by RDBMS backend drivers. It connects to the backend, and serves as a proxy for sending queries and receiving results.

It also provides an API to query the database and receive results in object format (Record and XRecord), but some backend drivers also have this functionality built-in.

The main difference comes from the way XRecord ORM was utilized, before it was called XRecord ORM - it was used in long-running daemons and system services. All of these are vulnerable to database backend failures, restarts, network downtime etc., so graceful re-connection had to be made easy at the database API level. It’s nothing fancy, but it does its job, a primitive example could look like this

while True:
    try:
       arr = db.XArray("blog_entry")
       for e in arr:
          do_something()
    except db.Error:
       while not db.Test():
          time.sleep(10)
          db.Reconnect()

XRecord was also used in short-lived programs, some of which required speed, and the additional overhead caused by fetching meta-data for each session was simply not acceptable. This is why we decided for the meta-data fetching functions to be lazy, ie. fetching it only when it is needed (when XRecords for a specific table are instantiated), so when not using the XRecord.X????? functions, no hidden hits to the database are made.

XRecordDatabase

class xRecord.XRecordDatabase(*args, **kwargs)

This class represents a database.

classmethod getInstance(*args, **kwargs)

This class method should be used to retrieve an instance of this class, or instantiate a new object if it does not exist. Using this method ensures that only one connection is used throughout the whole process.

If you want a new instance, call the constructor directly.

multithreading/multiprocessing: NOTE: As most backend drivers are not thread safe, each new thread should have its own instance, or protect the access to its methods. YOU HAVE BEEN WARNED.

Test()

Check if the connection is still active

Return type:boolean
Returns:True if connection is alive, False otherwise
Close()

Close the backend connection

Reconnect()

Reconnect to the back-end, using last known parameters

CheckConnection()

Check if the connection to the backend is alive, and reconnect if necessary.

Connection

Return the backend driver’s connection object.

Return type:instance
Manager

The Manager attribute provides a way to access the generated classes for database tables. This may come in handy if you defined custom class methods for your table proxy.:

>> db.Manager.blog_entry.getByCategory ( "programming", "python" )
[<xrecord::blog_entry(1)>, <xrecord::blog_entry(2)>]
SQLLog(stream)

Set the output stream object, to which all SQL queries run by this database instance are logged.

Parameters:stream – file object or None
CommandQuery(sql, *args)

Run an SQL query, returning the number of affected rows.

Best used for UPDATE and DELETE queries.

InsertQuery(sql, *args)

Run an SQL query. If it succeeds, return the id of the last inserted row, otherwise return the number of affected rows.

SingleValue(sql, *args)

Run the query, and return the value of the first column in the first row of the returned result set.

SingleObject(sql, *args, **kwargs)

Run the query, and return the first row of the returned result set as a Record object.

ArrayObject(sql, *args, **kwargs)

Run the query, and return the result set as an array of Record objects.

ArrayObjectIndexed(sql, index_column, *args, **kwargs)

Run the query, and return the result set as dictionary with the key set to the value of the index_column of each row of the returned result set, and the value set to the corresponding Record object.

If values of index_column are not unique, each subsequent record overwrites the previous key-value mapping for the given key.

Return type:ordereddict
ArrayObjectIndexedList(sql, index_column, *args, **kwargs)

Run the query, and return the result set as dictionary with the key set to the value of the index_column of each row of the returned result set, and the value set to a list of the corresponding :class:`Record`objects.

If values of index_column are unique, this function returns a key=>value mapping where all values are lists of length 1.

Return type:ordereddict
SingleAssoc(sql, *args, **kwargs)

Run the query, and return the first row of the returned result set as a dictionary.

ArrayAssoc(sql, *args)

Same as ArrayObject, but returns dicts instead of Record objects;

ArrayAssocIndexed(sql, index_column, *args, **kwargs)

Same as ArrayObjectIndexed, but returns dicts instead of Record objects;

ArrayAssocIndexedList(sql, index_column, *args, **kwargs)

Same as ArrayObjectIndexedList, but returns dicts instead of Record objects;

XRecord(tablename, *args, **kwargs)

Create a new instance of XRecord subclass for the given table. If there are any unnamed arguments, they are treated as primary key value, and a Fetch is performed on the record after initialization.

The keyword arguments are used as default values for attributes, but only if they appear in the table schema as columns.

Parameters:
  • tablename – name of the table
  • *args

    primary key value

  • **kwargs

    default attribute values

Returns:

new record

Return type:

XRecord

XSingle(table, sql=None, *args)

Same as SingleObject, but returns XRecord objects for the given table instead of Record objects.

If sql is None returns the object with its primary key value equal to the unnamed arguments.

XArray(table, sql=None, *args, **kwargs)

Same as ArrayObject, but returns XRecord objects for the given table instead of Record objects.

If sql is None (default) returns all records in the table.

XArrayIndexed(table, index_column, sql=None, *args, **kwargs)

Same as ArrayObjectIndexed, but returns XRecord objects for the given table instead of Record objects.

If sql is None (default) returns all records in the table.

XArrayIndexedList(table, index_column, sql=None, *args, **kwargs)

Same as ArrayObjectIndexedList, but returns XRecord objects for the given table instead of Record objects.

If sql is None (default) returns all records in the table.

XRecordRefCacheEnable(tablename, key_column, cache={})

Enable reference cache for a Foreign Key (key_column) in table ‘tablename’ The optional ‘cache’ argument may be initialized to a dictionary like object containing pairs of (pk : XRecord)

XRecordRefCacheDisable(tablename, key_column, cache={})
Initialize()

Called after the contructor is finished, may be overloaded to define custom XRecord and XSchema classes

XRecordMySQL

class xRecord.XRecordMySQL

The named attributes accepted by the constructor of this class are:

name
database name
host
server host name
port
server tcp port
user
user name
password
user’s password

XRecordSqlite

class xRecord.XRecordSqlite

The named attributes accepted by the constructor of this class are:

name
path to the file containing the database

XRecordPostgreSQL

class xRecord.XRecordPostgreSQL

The named attributes accepted by the constructor of this class are:

name
database name
host
server host name
port
server tcp port
user
user name
password
user’s password

Project Versions

Table Of Contents

Previous topic

XRecord reference and tutorial

Next topic

Working with records / data rows

This Page