API Reference

Persistent Types

class persistent.Persistent

Base class for persistent objects.

Implements:IPersistent
class persistent.list.PersistentList(initlist=None)

Bases: UserList.UserList, persistent.Persistent

Python implementation of persistent list.

$Id: list.py 113734 2010-06-21 15:33:46Z ctheune $

class persistent.mapping.PersistentMapping(dict=None, **kwargs)

Bases: UserDict.IterableUserDict, persistent.Persistent

A persistent wrapper for mapping objects.

This class allows wrapping of mapping objects so that object changes are registered. As a side effect, mapping objects may be subclassed.

A subclass of PersistentMapping or any code that adds new attributes should not create an attribute named _container. This is reserved for backwards compatibility reasons.

Storages

Single File

class ZODB.FileStorage.FileStorage(file_name, create=False, read_only=False, stop=None, quota=None, pack_gc=True, pack_keep_old=True, packer=None, blob_dir=None)
cleanup()

Remove all files created by this storage.

lastTid(oid)

Return last serialno committed for object oid.

If there is no serialno for this oid – which can only occur if it is a new object – return None.

load(oid, version='')

Return pickle data and serial number.

pack(t, referencesf, gc=None)

Copy data from the current database file to a packed file

Non-current records from transactions with time-stamp strings less than packtss are ommitted. As are all undone records.

Also, data back pointers that point before packtss are resolved and the associated data are copied, since the old records are not copied.

undo(transaction_id, transaction)

Undo a transaction, given by transaction_id.

Do so by writing new data that reverses the action taken by the transaction.

Usually, we can get by with just copying a data pointer, by writing a file position rather than a pickle. Sometimes, we may do conflict resolution, in which case we actually copy new data that results from resolution.

Client/Server Model

class ZEO.ClientStorage.ClientStorage(addr, storage='1', cache_size=20971520, name='', client=None, var=None, min_disconnect_poll=1, max_disconnect_poll=30, wait_for_server_on_startup=None, wait=None, wait_timeout=None, read_only=0, read_only_fallback=0, drop_cache_rather_verify=False, username='', password='', realm=None, blob_dir=None, shared_blob_dir=False, blob_cache_size=None, blob_cache_size_check=10, client_label=None)

A storage class that is a network client to a remote storage.

This is a faithful implementation of the Storage API.

This class is thread-safe; transactions are serialized in tpc_begin().

ClientCacheClass

alias of ClientCache

ConnectionManagerClass

alias of ConnectionManager

close()

Storage API: finalize the storage, releasing external resources.

copyTransactionsFrom(other, verbose=0)

Copy transactions from another storage.

This is typically used for converting data from one storage to another. other must have an .iterator() method.

end()

Server callback to signal end of cache validation.

endVerify()

Server callback to signal end of cache validation.

end_transaction()

Internal helper to end a transaction.

getExtensionMethods()

This returns a dictionary whose keys are names of extra methods provided by this storage. Storage proxies (such as ZEO) should call this method to determine the extra methods that they need to proxy in addition to the standard storage methods. Dictionary values should be None; this will be a handy place for extra marshalling information, should we need it

getName()

Storage API: return the storage name as a string.

The return value consists of two parts: the name as determined by the name and addr argments to the ClientStorage constructor, and the string ‘connected’ or ‘disconnected’ in parentheses indicating whether the storage is (currently) connected.

getSize()

Storage API: an approximate size of the database, in bytes.

getTid(oid)

Storage API: return current serial number for oid.

history(oid, size=1)

Storage API: return a sequence of HistoryEntry objects.

info(dict)

Server callback to update the info dictionary.

invalidate(oid)

Server callback to invalidate an oid pair.

This is called as part of cache validation.

invalidateTransaction(tid, oids)

Server callback: Invalidate objects modified by tid.

invalidateVerify(oid)

Server callback to invalidate an oid pair.

This is called as part of cache validation.

isReadOnly()

Storage API: return whether we are in read-only mode.

is_connected()

Return whether the storage is currently connected to a server.

iterator(start=None, stop=None)

Return an IStorageTransactionInformation iterator.

load(oid, version='')

Storage API: return the data for a given object.

This returns the pickle data and serial number for the object specified by the given object id, if they exist; otherwise a KeyError is raised.

loadSerial(oid, serial)

Storage API: load a historical revision of an object.

new_oid()

Storage API: return a new object identifier.

notifyConnected(conn)

Internal: start using the given connection.

This is called by ConnectionManager after it has decided which connection should be used.

notifyDisconnected()

Internal: notify that the server connection was terminated.

This is called by ConnectionManager when the connection is closed or when certain problems with the connection occur.

pack(t=None, referencesf=None, wait=1, days=0)

Storage API: pack the storage.

Deviations from the Storage API: the referencesf argument is ignored; two additional optional arguments wait and days are provided:

wait – a flag indicating whether to wait for the pack to
complete; defaults to true.
days – a number of days to subtract from the pack time;
defaults to zero.
record_iternext(next=None)

Storage API: get the next database record.

This is part of the conversion-support API.

registerDB(db)

Storage API: register a database for invalidation messages.

This is called by ZODB.DB (and by some tests).

The storage isn’t really ready to use until after this call.

restore(oid, serial, data, version, prev_txn, transaction)

Write data already committed in a separate database.

serialnos(args)

Server callback to pass a list of changed (oid, serial) pairs.

store(oid, serial, data, version, txn)

Storage API: store data for an object.

storeBlob(oid, serial, data, blobfilename, version, txn)

Storage API: store a blob object.

supportsUndo()

Storage API: return whether we support undo.

testConnection(conn)

Internal: test the given connection.

This returns: 1 if the connection is an optimal match,
0 if it is a suboptimal but acceptable match.

It can also raise DisconnectedError or ReadOnlyError.

This is called by ZEO.zrpc.ConnectionManager to decide which connection to use in case there are multiple, and some are read-only and others are read-write.

This works by calling register() on the server. In read-only mode, register() is called with the read_only flag set. In writable mode and in read-only fallback mode, register() is called with the read_only flag cleared. In read-only fallback mode only, if the register() call raises ReadOnlyError, it is retried with the read-only flag set, and if this succeeds, this is deemed a suboptimal match. In all other cases, a succeeding register() call is deemed an optimal match, and any exception raised by register() is passed through.

tpc_abort(txn)

Storage API: abort a transaction.

tpc_begin(txn, tid=None, status=' ')

Storage API: begin a transaction.

tpc_finish(txn, f=None)

Storage API: finish a transaction.

tpc_vote(txn)

Storage API: vote on a transaction.

undo(trans_id, txn)

Storage API: undo a transaction.

This is executed in a transactional context. It has no effect until the transaction is committed. It can be undone itself.

Zope uses this to implement undo unless it is not supported by a storage.

undoInfo(first=0, last=-20, specification=None)

Storage API: return undo information.

undoLog(first=0, last=-20, filter=None)

Storage API: return a sequence of TransactionDescription objects.

The filter argument should be None or left unspecified, since it is impossible to pass the filter function to the server to be executed there. If filter is not None, an empty sequence is returned.

verify_cache(server)

Internal routine called to verify the cache.

The return value (indicating which path we took) is used by the test suite.

In-Memory for Testing

class ZODB.DemoStorage.DemoStorage(name=None, base=None, changes=None, close_base_on_close=None, close_changes_on_close=None)

Demo ZODB storage

A demo storage supports demos by allowing a volatile changed database to be layered over a base database.

The base storage must not change.

class ZODB.MappingStorage.MappingStorage(name='MappingStorage')

A simple in-memory mapping-based ZODB storage

This storage provides an example implementation of a fairly full storage without distracting storage details.

class DataRecord(oid, tid, data)

Abstract base class for iterator protocol

MappingStorage.not_in_transaction()

The storage is not committing a transaction

MappingStorage.opened()

The storage is open

Connection Pool

class ZODB.DB(storage, pool_size=7, pool_timeout=2147483648, cache_size=400, cache_size_bytes=0, historical_pool_size=3, historical_cache_size=1000, historical_cache_size_bytes=0, historical_timeout=300, database_name='unnamed', databases=None, xrefs=True, large_record_size=16777216, **storage_args)

The DB class coordinates the activities of multiple database Connection instances. Most of the work is done by the Connections created via the open method.

The DB instance manages a pool of connections. If a connection is closed, it is returned to the pool and its object cache is preserved. A subsequent call to open() will reuse the connection. There is no hard limit on the pool size. If more than pool_size connections are opened, a warning is logged, and if more than twice that many, a critical problem is logged.

The class variable ‘klass’ is used by open() to create database connections. It is set to Connection, but a subclass could override it to provide a different connection implementation.

The database provides a few methods intended for application code – open, close, undo, and pack – and a large collection of methods for inspecting the database and its connections’ caches.

Cvariables:
  • klass: Class used by L{open} to create database connections
Groups:
  • User Methods: __init__, open, close, undo, pack, classFactory
  • Inspection Methods: getName, getSize, objectCount, getActivityMonitor, setActivityMonitor
  • Connection Pool Methods: getPoolSize, getHistoricalPoolSize, setPoolSize, setHistoricalPoolSize, getHistoricalTimeout, setHistoricalTimeout
  • Transaction Methods: invalidate
  • Other Methods: lastTransaction, connectionDebugInfo
  • Cache Inspection Methods: cacheDetail, cacheExtremeDetail, cacheFullSweep, cacheLastGCTime, cacheMinimize, cacheSize, cacheDetailSize, getCacheSize, getHistoricalCacheSize, setCacheSize, setHistoricalCacheSize
cacheDetail()

Return information on objects in the various caches

Organized by class.

close()

Close the database and its underlying storage.

It is important to close the database, because the storage may flush in-memory data structures to disk when it is closed. Leaving the storage open with the process exits can cause the next open to be slow.

What effect does closing the database have on existing connections? Technically, they remain open, but their storage is closed, so they stop behaving usefully. Perhaps close() should also close all the Connections.

invalidate(tid, oids, connection=None, version='')

Invalidate references to a given oid.

This is used to indicate that one of the connections has committed a change to the object. The connection commiting the change should be passed in to prevent useless (but harmless) messages to the connection.

invalidateCache()

Invalidate each of the connection caches

klass

alias of Connection

open(transaction_manager=None, at=None, before=None)

Return a database Connection for use by application code.

Note that the connection pool is managed as a stack, to increase the likelihood that the connection’s stack will include useful objects.

Parameters:
  • transaction_manager: transaction manager to use. None means use the default transaction manager.
  • at: a datetime.datetime or 8 character transaction id of the time to open the database with a read-only connection. Passing both at and before raises a ValueError, and passing neither opens a standard writable transaction of the newest state. A timezone-naive datetime.datetime is treated as a UTC value.
  • before: like at, but opens the readonly state before the tid or datetime.
pack(t=None, days=0)

Pack the storage, deleting unused object revisions.

A pack is always performed relative to a particular time, by default the current time. All object revisions that are not reachable as of the pack time are deleted from the storage.

The cost of this operation varies by storage, but it is usually an expensive operation.

There are two optional arguments that can be used to set the pack time: t, pack time in seconds since the epcoh, and days, the number of days to subtract from t or from the current time if t is not specified.

undo(id, txn=None)

Undo a transaction identified by id.

A transaction can be undone if all of the objects involved in the transaction were not modified subsequently, if any modifications can be resolved by conflict resolution, or if subsequent changes resulted in the same object state.

The value of id should be generated by calling undoLog() or undoInfo(). The value of id is not the same as a transaction id used by other methods; it is unique to undo().

Parameters:
  • id: a transaction identifier
  • txn: transaction context to use for undo(). By default, uses the current transaction.
undoMultiple(ids, txn=None)

Undo multiple transactions identified by ids.

A transaction can be undone if all of the objects involved in the transaction were not modified subsequently, if any modifications can be resolved by conflict resolution, or if subsequent changes resulted in the same object state.

The values in ids should be generated by calling undoLog() or undoInfo(). The value of ids are not the same as a transaction ids used by other methods; they are unique to undo().

Parameters:
  • ids: a sequence of storage-specific transaction identifiers
  • txn: transaction context to use for undo(). By default, uses the current transaction.

Connections

class ZODB.Connection.Connection(db, cache_size=400, before=None, cache_size_bytes=0)

Connection to ZODB for loading and storing objects.

abort(transaction)

Abort a transaction and forget all changes.

add(obj)

Add a new object ‘obj’ to the database and assign it an oid.

cacheGC()

Reduce cache size to target size.

cacheMinimize()

Deactivate all unmodified objects in the cache.

close(primary=True)

Close the Connection.

commit(transaction)

Commit changes to an object

db()

Returns a handle to the database this connection belongs to.

get(oid)

Return the persistent object with oid ‘oid’.

getDebugInfo()

Returns a tuple with different items for debugging the connection.

getTransferCounts(clear=False)

Returns the number of objects loaded and stored.

get_connection(database_name)

Return a Connection for the named database.

invalidate(tid, oids)

Notify the Connection that transaction ‘tid’ invalidated oids.

isReadOnly()

Returns True if this connection is read only.

oldstate(obj, tid)

Return copy of ‘obj’ that was written by transaction ‘tid’.

onCloseCallback(f)

Register a callable, f, to be called by close().

open(transaction_manager=None, delegate=True)

Register odb, the DB that this Connection uses.

This method is called by the DB every time a Connection is opened. Any invalidations received while the Connection was closed will be processed.

If the global module function resetCaches() was called, the cache will be cleared.

Parameters: odb: database that owns the Connection transaction_manager: transaction manager to use. None means

use the default transaction manager.

register for afterCompletion() calls.

register(obj)

Register obj with the current transaction manager.

A subclass could override this method to customize the default policy of one transaction manager for each thread.

obj must be an object loaded from this Connection.

root

Return the database root object.

setDebugInfo(*args)

Add the given items to the debug information of this connection.

setstate(obj)

Turns the ghost ‘obj’ into a real object by loading its state from the database.

sortKey()

Return a consistent sort key for this connection.

sync()

Manually update the view on the database.

tpc_begin(transaction)

Begin commit of a transaction, starting the two-phase commit.

tpc_finish(transaction)

Indicate confirmation that the transaction is done.

tpc_vote(transaction)

Verify that a data manager can commit the transaction.

Transactions

transaction.begin()

Begin a new transaction in the default manager.

transaction.commit()

Commit the current transaction in the default manager.

transaction.abort()

Abort the current transaction in the default manager.

transaction.doom()

Doom the current transaction in the default manager.

transaction.isDoomed()

Check if the current transaction in the default manager is doomed.

transaction.savepoint(optimistic=False)

Create a savepoint from the current transaction in the default manager.

If the optimistic argument is true, then data managers that don’t support savepoints can be used, but an error will be raised if the savepoint is rolled back.

An ISavepoint object is returned.

transaction.get()

Get the current transaction from the default manager.

transaction.manager

Default transaction manager.

Type:ThreadTransactionManager
class transaction.TransactionManager
Implements:ITransactionManager
abort()

See ITransactionManager.

begin()

See ITransactionManager.

commit()

See ITransactionManager.

doom()

See ITransactionManager.

get()

See ITransactionManager.

isDoomed()

See ITransactionManager.

registerSynch(synch)

See ITransactionManager.

savepoint(optimistic=False)

See ITransactionManager.

unregisterSynch(synch)

See ITransactionManager.

class transaction.ThreadTransactionManager

Thread-aware transaction manager.

Each thread is associated with a unique transaction.

Bases:TransactionManager, threading.local
class transaction.Transaction(synchronizers=None, manager=None)
Implements:ITransaction
abort()

See ITransaction.

addAfterCommitHook(hook, args=(), kws=None)

See ITransaction.

addBeforeCommitHook(hook, args=(), kws=None)

See ITransaction.

commit()

See ITransaction.

doom()

See ITransaction.

getAfterCommitHooks()

See ITransaction.

getBeforeCommitHooks()

See ITransaction.

isDoomed()

See ITransaction.

join(resource)

See ITransaction.

note(text)

See ITransaction.

register(obj)

See ITransaction.

savepoint(optimistic=False)

See ITransaction.

setExtendedInfo(name, value)

See ITransaction.

setUser(user_name, path='/')

See ITransaction.

Errors

exception transaction.interfaces.DoomedTransaction

A commit was attempted on a transaction that was doomed.

exception transaction.interfaces.InvalidSavepointRollbackError

Attempt to rollback an invalid savepoint.

A savepoint may be invalid because:

  • The surrounding transaction has committed or aborted.
  • An earlier savepoint in the same transaction has been rolled back.

Interfaces

interface persistent.interfaces.IPersistent

Python persistent interface

A persistent object can be in one of several states:

  • Unsaved

    The object has been created but not saved in a data manager.

    In this state, the _p_changed attribute is non-None and false and the _p_jar attribute is None.

  • Saved

    The object has been saved and has not been changed since it was saved.

    In this state, the _p_changed attribute is non-None and false and the _p_jar attribute is set to a data manager.

  • Sticky

    This state is identical to the saved state except that the object cannot transition to the ghost state. This is a special state used by C methods of persistent objects to make sure that state is not unloaded in the middle of computation.

    In this state, the _p_changed attribute is non-None and false and the _p_jar attribute is set to a data manager.

    There is no Python API for detecting whether an object is in the sticky state.

  • Changed

    The object has been changed.

    In this state, the _p_changed attribute is true and the _p_jar attribute is set to a data manager.

  • Ghost

    the object is in memory but its state has not been loaded from the database (or its state has been unloaded). In this state, the object doesn’t contain any application data.

    In this state, the _p_changed attribute is None, and the _p_jar attribute is set to the data manager from which the object was obtained.

In all the above, _p_oid (the persistent object id) is set when _p_jar first gets set.

The following state transitions are possible:

  • Unsaved -> Saved

    This transition occurs when an object is saved in the database. This usually happens when an unsaved object is added to (e.g. as an attribute or item of) a saved (or changed) object and the transaction is committed.

  • Saved -> Changed Sticky -> Changed Ghost -> Changed

    This transition occurs when someone sets an attribute or sets _p_changed to a true value on a saved, sticky or ghost object. When the transition occurs, the persistent object is required to call the register() method on its data manager, passing itself as the only argument.

    Prior to ZODB 3.6, setting _p_changed to a true value on a ghost object was ignored (the object remained a ghost, and getting its _p_changed attribute continued to return None).

  • Saved -> Sticky

    This transition occurs when C code marks the object as sticky to prevent its deactivation.

  • Saved -> Ghost

    This transition occurs when a saved object is deactivated or invalidated. See discussion below.

  • Sticky -> Saved

    This transition occurs when C code unmarks the object as sticky to allow its deactivation.

  • Changed -> Saved

    This transition occurs when a transaction is committed. After saving the state of a changed object during transaction commit, the data manager sets the object’s _p_changed to a non-None false value.

  • Changed -> Ghost

    This transition occurs when a transaction is aborted. All changed objects are invalidated by the data manager by an abort.

  • Ghost -> Saved

    This transition occurs when an attribute or operation of a ghost is accessed and the object’s state is loaded from the database.

Note that there is a separate C API that is not included here. The C API requires a specific data layout and defines the sticky state.

About Invalidation, Deactivation and the Sticky & Ghost States

The sticky state is intended to be a short-lived state, to prevent an object’s state from being discarded while we’re in C routines. It is an error to invalidate an object in the sticky state.

Deactivation is a request that an object discard its state (become a ghost). Deactivation is an optimization, and a request to deactivate may be ignored. There are two equivalent ways to request deactivation:

  • call _p_deactivate()
  • set _p_changed to None

There are two ways to invalidate an object: call the _p_invalidate() method (preferred) or delete its _p_changed attribute. This cannot be ignored, and is used when semantics require invalidation. Normally, an invalidated object transitions to the ghost state. However, some objects cannot be ghosts. When these objects are invalidated, they immediately reload their state from their data manager, and are then in the saved state.

_p_jar

The data manager for the object.

The data manager implements the IPersistentDataManager interface. If there is no data manager, then this is None.

__setstate__(state)

Set the object data.

_p_deactivate()

Deactivate the object.

Possibly change an object in the saved state to the ghost state. It may not be possible to make some persistent objects ghosts, and, for optimization reasons, the implementation may choose to keep an object in the saved state.

_p_invalidate()

Invalidate the object.

Invalidate the object. This causes any data to be thrown away, even if the object is in the changed state. The object is moved to the ghost state; further accesses will cause object data to be reloaded.

_p_serial

The object serial number.

This member is used by the data manager to distiguish distinct revisions of a given persistent object.

This is an 8-byte string (not Unicode).

_p_oid

The object id.

It is up to the data manager to assign this. The special value None is reserved to indicate that an object id has not been assigned. Non-None object ids must be non-empty strings. The 8-byte string ‘’*8 (8 NUL bytes) is reserved to identify the database root object.

_p_activate()

Activate the object.

Change the object to the saved state if it is a ghost.

__getstate__()

Get the object data.

The state should not include persistent attributes (“_p_name”). The result must be picklable.

_p_changed

The persistent state of the object.

This is one of:

None – The object is a ghost.

false but not None – The object is saved (or has never been saved).

true – The object has been modified since it was last saved.

The object state may be changed by assigning or deleting this attribute; however, assigning None is ignored if the object is not in the saved state, and may be ignored even if the object is in the saved state.

At and after ZODB 3.6, setting _p_changed to a true value for a ghost object activates the object; prior to 3.6, setting _p_changed to a true value on a ghost object was ignored.

Note that an object can transition to the changed state only if it has a data manager. When such a state change occurs, the ‘register’ method of the data manager must be called, passing the persistent object.

Deleting this attribute forces invalidation independent of existing state, although it is an error if the sticky state is current.

interface persistent.interfaces.IPersistentDataManager

Provide services for managing persistent state.

This interface is used by a persistent object to interact with its data manager in the context of a transaction.

oldstate(obj, tid)

Return copy of ‘obj’ that was written by transaction ‘tid’.

The returned object does not have the typical metadata (_p_jar, _p_oid, _p_serial) set. I’m not sure how references to other peristent objects are handled.

Parameters obj: a persistent object from this Connection. tid: id of a transaction that wrote an earlier revision.

Raises KeyError if tid does not exist or if tid deleted a revision of obj.

register(object)

Register an IPersistent with the current transaction.

This method must be called when the object transitions to the changed state.

A subclass could override this method to customize the default policy of one transaction manager for each thread.

setstate(object)

Load the state for the given object.

The object should be in the ghost state. The object’s state will be set and the object will end up in the saved state.

The object must provide the IPersistent interface.

interface ZODB.interfaces.IConnection

Connection to ZODB for loading and storing objects.

The Connection object serves as a data manager. The root() method on a Connection returns the root object for the database. This object and all objects reachable from it are associated with the Connection that loaded them. When a transaction commits, it uses the Connection to store modified objects.

Typical use of ZODB is for each thread to have its own Connection and that no thread should have more than one Connection to the same database. A thread is associated with a Connection by loading objects from that Connection. Objects loaded by one thread should not be used by another thread.

A Connection can be frozen to a serial–a transaction id, a single point in history– when it is created. By default, a Connection is not associated with a serial; it uses current data. A Connection frozen to a serial is read-only.

Each Connection provides an isolated, consistent view of the database, by managing independent copies of objects in the database. At transaction boundaries, these copies are updated to reflect the current state of the database.

You should not instantiate this class directly; instead call the open() method of a DB instance.

In many applications, root() is the only method of the Connection that you will need to use.

A Connection instance is not thread-safe. It is designed to support a thread model where each thread has its own transaction. If an application has more than one thread that uses the connection or the transaction the connection is registered with, the application should provide locking.

The Connection manages movement of objects in and out of object storage.

TODO: We should document an intended API for using a Connection via multiple threads.

TODO: We should explain that the Connection has a cache and that multiple calls to get() will return a reference to the same object, provided that one of the earlier objects is still referenced. Object identity is preserved within a connection, but not across connections.

TODO: Mention the database pool.

A database connection always presents a consistent view of the objects in the database, although it may not always present the most current revision of any particular object. Modifications made by concurrent transactions are not visible until the next transaction boundary (abort or commit).

Two options affect consistency. By default, the mvcc and synch options are enabled by default.

If you pass mvcc=False to db.open(), the Connection will never read non-current revisions of an object. Instead it will raise a ReadConflictError to indicate that the current revision is unavailable because it was written after the current transaction began.

The logic for handling modifications assumes that the thread that opened a Connection (called db.open()) is the thread that will use the Connection. If this is not true, you should pass synch=False to db.open(). When the synch option is disabled, some transaction boundaries will be missed by the Connection; in particular, if a transaction does not involve any modifications to objects loaded from the Connection and synch is disabled, the Connection will miss the transaction boundary. Two examples of this behavior are db.undo() and read-only transactions.

Groups of methods:

User Methods:
root, get, add, close, db, sync, isReadOnly, cacheGC, cacheFullSweep, cacheMinimize
Experimental Methods:
onCloseCallbacks
Database Invalidation Methods:
invalidate
Other Methods: exchange, getDebugInfo, setDebugInfo,
getTransferCounts
getDebugInfo()

Returns a tuple with different items for debugging the connection.

Debug information can be added to a connection by using setDebugInfo.

invalidate(tid, oids)

Notify the Connection that transaction ‘tid’ invalidated oids.

When the next transaction boundary is reached, objects will be invalidated. If any of the invalidated objects are accessed by the current transaction, the revision written before Connection.tid will be used.

The DB calls this method, even when the Connection is closed.

Parameters: tid: the storage-level id of the transaction that committed oids: oids is an iterable of oids.

cacheGC()

Reduce cache size to target size.

Call _p_deactivate() on cached objects until the cache size falls under the target size.

getTransferCounts(clear=False)

Returns the number of objects loaded and stored.

If clear is True, reset the counters.

get(oid)

Return the persistent object with oid ‘oid’.

If the object was not in the cache and the object’s class is ghostable, then a ghost will be returned. If the object is already in the cache, a reference to the cached object will be returned.

Applications seldom need to call this method, because objects are loaded transparently during attribute lookup.

Parameters: oid: an object id

Raises KeyError if oid does not exist.

It is possible that an object does not exist as of the current transaction, but existed in the past. It may even exist again in the future, if the transaction that removed it is undone.

Raises ConnectionStateError if the connection is closed.

isReadOnly()

Returns True if the storage for this connection is read only.

db()

Returns a handle to the database this connection belongs to.

sync()

Manually update the view on the database.

This includes aborting the current transaction, getting a fresh and consistent view of the data (synchronizing with the storage if possible) and calling cacheGC() for this connection.

This method was especially useful in ZODB 3.2 to better support read-only connections that were affected by a couple of problems.

setDebugInfo(*items)

Add the given items to the debug information of this connection.

connections

A mapping from database name to a Connection to that database.

In multi-database use, the Connections of all members of a database collection share the same .connections object.

In single-database use, of course this mapping contains a single entry.

add(ob)

Add a new object ‘obj’ to the database and assign it an oid.

A persistent object is normally added to the database and assigned an oid when it becomes reachable to an object already in the database. In some cases, it is useful to create a new object and use its oid (_p_oid) in a single transaction.

This method assigns a new oid regardless of whether the object is reachable.

The object is added when the transaction commits. The object must implement the IPersistent interface and must not already be associated with a Connection.

Parameters: obj: a Persistent object

Raises TypeError if obj is not a persistent object.

Raises InvalidObjectReference if obj is already associated with another connection.

Raises ConnectionStateError if the connection is closed.

cacheMinimize()

Deactivate all unmodified objects in the cache.

Call _p_deactivate() on each cached object, attempting to turn it into a ghost. It is possible for individual objects to remain active.

invalidateCache()

Invalidate the connection cache

This invalidates all objects in the cache. If the connection is open, subsequent reads will fail until a new transaction begins or until the connection os reopned.

get_connection(database_name)

Return a Connection for the named database.

This is intended to be called from an open Connection associated with a multi-database. In that case, database_name must be the name of a database within the database collection (probably the name of a different database than is associated with the calling Connection instance, but it’s fine to use the name of the calling Connection object’s database). A Connection for the named database is returned. If no connection to that database is already open, a new Connection is opened. So long as the multi-database remains open, passing the same name to get_connection() multiple times returns the same Connection object each time.

readCurrent(obj)

Make sure an object being read is current

This is used when applications want to ensure a higher level of consistency for some operations. This should be called when an object is read and the information read is used to write a separate object.

close()

Close the Connection.

When the Connection is closed, all callbacks registered by onCloseCallback() are invoked and the cache is garbage collected.

A closed Connection should not be used by client code. It can’t load or store objects. Objects in the cache are not freed, because Connections are re-used and the cache is expected to be useful to the next client.

root()

Return the database root object.

The root is a persistent.mapping.PersistentMapping.

onCloseCallback(f)

Register a callable, f, to be called by close().

f will be called with no arguments before the Connection is closed.

Parameters: f: method that will be called on close

interface ZODB.interfaces.IDatabase

Extends: ZODB.interfaces.IStorageWrapper

ZODB DB.

storage

The object that provides storage for the database

This attribute is useful primarily for tests. Normal application code should rarely, if ever, have a need to use this attribute.

undo(id, txn=None)

Undo a transaction identified by id.

A transaction can be undone if all of the objects involved in the transaction were not modified subsequently, if any modifications can be resolved by conflict resolution, or if subsequent changes resulted in the same object state.

The value of id should be generated by calling undoLog() or undoInfo(). The value of id is not the same as a transaction id used by other methods; it is unique to undo().

id: a storage-specific transaction identifier txn: transaction context to use for undo().

By default, uses the current transaction.
databases

A mapping from database name to DB (database) object.

In multi-database use, all DB members of a database collection share the same .databases object.

In single-database use, of course this mapping contains a single entry.

close()

Close the database and its underlying storage.

It is important to close the database, because the storage may flush in-memory data structures to disk when it is closed. Leaving the storage open with the process exits can cause the next open to be slow.

What effect does closing the database have on existing connections? Technically, they remain open, but their storage is closed, so they stop behaving usefully. Perhaps close() should also close all the Connections.

open(transaction_manager=None, serial='')

Return an IConnection object for use by application code.

transaction_manager: transaction manager to use. None means
use the default transaction manager.
serial: the serial (transaction id) of the database to open.
An empty string (the default) means to open it to the newest serial. Specifying a serial results in a read-only historical connection.

Note that the connection pool is managed as a stack, to increase the likelihood that the connection’s stack will include useful objects.

pack(t=None, days=0)

Pack the storage, deleting unused object revisions.

A pack is always performed relative to a particular time, by default the current time. All object revisions that are not reachable as of the pack time are deleted from the storage.

The cost of this operation varies by storage, but it is usually an expensive operation.

There are two optional arguments that can be used to set the pack time: t, pack time in seconds since the epcoh, and days, the number of days to subtract from t or from the current time if t is not specified.

interface ZODB.interfaces.IStorage

A storage is responsible for storing and retrieving data of objects.

When transactions are committed, a storage assigns monotonically increasing transaction identifiers (tids) to the transactions and to the object versions written by the transactions. ZODB relies on this to decide if data in object caches are up to date and to implement multi-version concurrency control.

There are methods in IStorage and in derived interfaces that provide information about the current revisions (tids) for objects or for the database as a whole. It is critical for the proper working of ZODB that the resulting tids are increasing with respect to the object identifier given or to the databases. That is, if there are 2 results for an object or for the database, R1 and R2, such that R1 is returned before R2, then the tid returned by R2 must be greater than or equal to the tid returned by R1. (When thinking about results for the database, think of these as results for all objects in the database.)

This implies some sort of locking strategy. The key method is tcp_finish, which causes new tids to be generated and also, through the callback passed to it, returns new current tids for the objects stored in a transaction and for the database as a whole.

The IStorage methods affected are lastTransaction, load, store, and tpc_finish. Derived interfaces may introduce additional methods.

load(oid, version)

Load data for an object id

The version argumement should always be an empty string. It exists soley for backward compatibility with older storage implementations.

A data record and serial are returned. The serial is a transaction identifier of the transaction that wrote the data record.

A POSKeyError is raised if there is no record for the object id.

lastTransaction()

Return the id of the last committed transaction.

If no transactions have been committed, return a string of 8 null (0) characters.

isReadOnly()

Test whether a storage allows committing new transactions

For a given storage instance, this method always returns the same value. Read-only-ness is a static property of a storage.

tpc_finish(transaction, func=<function <lambda> at 0x42a0320>)

Finish the transaction, making any transaction changes permanent.

Changes must be made permanent at this point.

This call raises a StorageTransactionError if the storage isn’t participating in two-phase commit or if it is committing a different transaction. Failure of this method is extremely serious.

The second argument is a call-back function that must be called while the storage transaction lock is held. It takes the new transaction id generated by the transaction.

getName()

The name of the storage

The format and interpretation of this name is storage dependent. It could be a file name, a database name, etc..

This is used soley for informational purposes.

loadBefore(oid, tid)

Load the object data written before a transaction id

If there isn’t data before the object before the given transaction, then None is returned, otherwise three values are returned:

  • The data record
  • The transaction id of the data record
  • The transaction id of the following revision, if any, or None.

If the object id isn’t in the storage, then POSKeyError is raised.

sortKey()

Sort key used to order distributed transactions

When a transaction involved multiple storages, 2-phase commit operations are applied in sort-key order. This must be unique among storages used in a transaction. Obviously, the storage can’t assure this, but it should construct the sort key so it has a reasonable chance of being unique.

The result must be a string.

registerDB(wrapper)

Register a storage wrapper IStorageWrapper.

The passed object is a wrapper object that provides an upcall interface to support composition.

Note that, for historical reasons, an implementation may require a second argument, however, if required, the None will be passed as the second argument.

Also, for historical reasons, this is called registerDB rather than register_wrapper.

getSize()

An approximate size of the database, in bytes.

This is used soley for informational purposes.

tpc_abort(transaction)

Abort the transaction.

Any changes made by the transaction are discarded.

This call is ignored is the storage is not participating in two-phase commit or if the given transaction is not the same as the transaction the storage is commiting.

tpc_vote(transaction)

Provide a storage with an opportunity to veto a transaction

This call raises a StorageTransactionError if the storage isn’t participating in two-phase commit or if it is commiting a different transaction.

If a transaction can be committed by a storage, then the method should return. If a transaction cannot be committed, then an exception should be raised. If this method returns without an error, then there must not be an error if tpc_finish or tpc_abort is called subsequently.

The return value can be either None or a sequence of object-id and serial pairs giving new serials for objects who’s ids were passed to previous store calls in the same transaction. After the tpc_vote call, new serials must have been returned, either from tpc_vote or store for objects passed to store.

A serial returned in a sequence of oid/serial pairs, may be the special value ZODB.ConflictResolution.ResolvedSerial to indicate that a conflict occured and that the object should be invalidated.

new_oid()

Allocate a new object id.

The object id returned is reserved at least as long as the storage is opened.

The return value is a string.

store(oid, serial, data, version, transaction)

Store data for the object id, oid.

Arguments:

oid
The object identifier. This is either a string consisting of 8 nulls or a string previously returned by new_oid.
serial
The serial of the data that was read when the object was loaded from the database. If the object was created in the current transaction this will be a string consisting of 8 nulls.
data
The data record. This is opaque to the storage.
version
This must be an empty string. It exists for backward compatibility.
transaction
A transaction object. This should match the current transaction for the storage, set by tpc_begin.

The new serial for the object is returned, but not necessarily immediately. It may be returned directly, or on a subsequent store or tpc_vote call.

The return value may be:

  • None, or
  • A new serial (string) for the object

If None is returned, then a new serial (or other special values) must ve returned in tpc_vote results.

A serial, returned as a string, may be the special value ZODB.ConflictResolution.ResolvedSerial to indicate that a conflict occured and that the object should be invalidated.

Several different exceptions may be raised when an error occurs.

ConflictError
is raised when serial does not match the most recent serial number for object oid and the conflict was not resolved by the storage.
StorageTransactionError
is raised when transaction does not match the current transaction.
StorageError or, more often, a subclass of it
is raised when an internal error occurs while the storage is handling the store() call.
tpc_begin(transaction)

Begin the two-phase commit process.

If storage is already participating in a two-phase commit using the same transaction, a StorageTransactionError is raised.

If the storage is already participating in a two-phase commit using a different transaction, the call blocks until the current transaction ends (commits or aborts).

close()

Close the storage.

Finalize the storage, releasing any external resources. The storage should not be used after this method is called.

loadSerial(oid, serial)

Load the object record for the give transaction id

If a matching data record can be found, it is returned, otherwise, POSKeyError is raised.

pack(pack_time, referencesf)

Pack the storage

It is up to the storage to interpret this call, however, the general idea is that the storage free space by:

  • discarding object revisions that were old and not current as of the given pack time.
  • garbage collecting objects that aren’t reachable from the root object via revisions remaining after discarding revisions that were not current as of the pack time.

The pack time is given as a UTC time in seconds since the epoch.

The second argument is a function that should be used to extract object references from database records. This is needed to determine which objects are referenced from object revisions.

__len__()

The approximate number of objects in the storage

This is used soley for informational purposes.

history(oid, size=1)

Return a sequence of history information dictionaries.

Up to size objects (including no objects) may be returned.

The information provides a log of the changes made to the object. Data are reported in reverse chronological order.

Each dictionary has the following keys:

time
UTC seconds since the epoch (as in time.time) that the object revision was committed.
tid
The transaction identifier of the transaction that committed the version.
serial
An alias for tid, which expected by older clients.
user_name
The user identifier, if any (or an empty string) of the user on whos behalf the revision was committed.
description
The transaction description for the transaction that committed the revision.
size
The size of the revision data record.

If the transaction had extension items, then these items are also included if they don’t conflict with the keys above.

interface ZODB.interfaces.IStorageCurrentRecordIteration

Extends: ZODB.interfaces.IStorage

record_iternext(next=None)

Iterate over the records in a storage

Use like this:

>>> next = None
>>> while 1:
...     oid, tid, data, next = storage.record_iternext(next)
...     # do things with oid, tid, and data
...     if next is None:
...         break
interface ZODB.interfaces.IStorageWrapper

Storage wrapper interface

This interface provides 3 facilities:

  • Out-of-band invalidation support

    A storage can notify it’s wrapper of object invalidations that don’t occur due to direct operations on the storage. Currently this is only used by ZEO client storages to pass invalidation messages sent from a server.

  • Record-reference extraction

    The references method can be used to extract referenced object IDs from a database record. This can be used by storages to provide more advanced garbage collection. A wrapper storage that transforms data will provide a references method that untransforms data passed to it and then pass the data to the layer above it.

  • Record transformation

    A storage wrapper may transform data, for example for compression or encryption. Methods are provided to transform or untransform data.

This interface may be implemented by storage adapters or other intermediaries. For example, a storage adapter that provides encryption and/or compresssion will apply record transformations in it’s references method.

invalidate(transaction_id, oids, version='')

Invalidate object ids committed by the given transaction

The oids argument is an iterable of object identifiers.

The version argument is provided for backward compatibility. If passed, it must be an empty string.

transform_record_data(data)

Return transformed data

invalidateCache()

Discard all cached data

This can be necessary if there have been major changes to stored data and it is either impractical to enumerate them or there would be so many that it would be inefficient to do so.

references(record, oids=None)

Scan the given record for object ids

A list of object ids is returned. If a list is passed in, then it will be used and augmented. Otherwise, a new list will be created and returned.

untransform_record_data(data)

Return untransformed data

interface ZODB.interfaces.IStorageIteration

API for iterating over the contents of a storage.

iterator(start=None, stop=None)

Return an IStorageTransactionInformation iterator.

If the start argument is not None, then iteration will start with the first transaction whose identifier is greater than or equal to start.

If the stop argument is not None, then iteration will end with the last transaction whose identifier is less than or equal to stop.

The iterator provides access to the data as available at the time when the iterator was retrieved.

interface ZODB.interfaces.IStorageRecordInformation

Provide information about a single storage record

data_txn

The previous transaction id

oid

The object id

version

The version id

tid

The transaction id

data

The data record

interface ZODB.interfaces.IStorageRestoreable

Extends: ZODB.interfaces.IStorage

Copying Transactions

The IStorageRestoreable interface supports copying already-committed transactions from one storage to another. This is typically done for replication or for moving data from one storage implementation to another.

tpc_begin(transaction, tid=None)

Begin the two-phase commit process.

If storage is already participating in a two-phase commit using the same transaction, the call is ignored.

If the storage is already participating in a two-phase commit using a different transaction, the call blocks until the current transaction ends (commits or aborts).

If a transaction id is given, then the transaction will use the given id rather than generating a new id. This is used when copying already committed transactions from another storage.

restore(oid, serial, data, version, prev_txn, transaction)

Write data already committed in a separate database

The restore method is used when copying data from one database to a replica of the database. It differs from store in that the data have already been committed, so there is no check for conflicts and no new transaction is is used for the data.

Arguments:

oid
The object id for the record
serial
The transaction identifier that originally committed this object.
data
The record data. This will be None if the transaction undid the creation of the object.
prev_txn
The identifier of a previous transaction that held the object data. The target storage can sometimes use this as a hint to save space.
transaction
The current transaction.

Nothing is returned.

interface ZODB.interfaces.IStorageTransactionInformation

Provide information about a storage transaction.

Can be iterated over to retrieve the records modified in the transaction.

status

Transaction Status

description

Transaction Description

extension

A dictionary carrying the transaction’s extension data

__iter__()

Iterate over the transaction’s records given as IStorageRecordInformation objects.

user

Transaction user

tid

Transaction id

interface ZODB.interfaces.IStorageUndoable

Extends: ZODB.interfaces.IStorage

A storage supporting transactional undo.

undoLog(first, last, filter=None)

Return a sequence of descriptions for undoable transactions.

Application code should call undoLog() on a DB instance instead of on the storage directly.

A transaction description is a mapping with at least these keys:

“time”: The time, as float seconds since the epoch, when
the transaction committed.
“user_name”: The value of the .user attribute on that
transaction.
“description”: The value of the .description attribute on
that transaction.
“id`” A string uniquely identifying the transaction to the
storage. If it’s desired to undo this transaction, this is the transaction_id to pass to undo().

In addition, if any name+value pairs were added to the transaction by setExtendedInfo(), those may be added to the transaction description mapping too (for example, FileStorage’s undoLog() does this).

filter is a callable, taking one argument. A transaction description mapping is passed to filter for each potentially undoable transaction. The sequence returned by undoLog() excludes descriptions for which filter returns a false value. By default, filter always returns a true value.

ZEO note: Arbitrary callables cannot be passed from a ZEO client to a ZEO server, and a ZEO client’s implementation of undoLog() ignores any filter argument that may be passed. ZEO clients should use the related undoInfo() method instead (if they want to do filtering).

Now picture a list containing descriptions of all undoable transactions that pass the filter, most recent transaction first (at index 0). The first and last arguments specify the slice of this (conceptual) list to be returned:

first: This is the index of the first transaction description
in the slice. It must be >= 0.
last: If >= 0, first:last acts like a Python slice, selecting
the descriptions at indices first, first+1, ..., up to but not including index last. At most last-first descriptions are in the slice, and last should be at least as large as first in this case. If last is less than 0, then abs(last) is taken to be the maximum number of descriptions in the slice (which still begins at index first). When last < 0, the same effect could be gotten by passing the positive first-last for last instead.
undoInfo(first=0, last=-20, specification=None)

Return a sequence of descriptions for undoable transactions.

This is like undoLog(), except for the specification argument. If given, specification is a dictionary, and undoInfo() synthesizes a filter function f for undoLog() such that f(desc) returns true for a transaction description mapping desc if and only if desc maps each key in specification to the same value specification maps that key to. In other words, only extensions (or supersets) of specification match.

ZEO note: undoInfo() passes the specification argument from a ZEO client to its ZEO server (while a ZEO client ignores any filter argument passed to undoLog()).

undo(transaction_id, transaction)

Undo the transaction corresponding to the given transaction id.

The transaction id is a value returned from undoInfo or undoLog, which may not be a stored transaction identifier as used elsewhere in the storage APIs.

This method must only be called in the first phase of two-phase commit (after tpc_begin but before tpc_vote). It returns a serial (transaction id) and a sequence of object ids for objects affected by the transaction.

supportsUndo()

Return True, indicating that the storage supports undo.

interface transaction.interfaces.IDataManager

Objects that manage transactional storage.

These objects may manage data for other objects, or they may manage non-object storages, such as relational databases. For example, a ZODB.Connection.

Note that when some data is modified, that data’s data manager should join a transaction so that data can be committed when the user commits the transaction.

tpc_finish(transaction)

Indicate confirmation that the transaction is done.

Make all changes to objects modified by this transaction persist.

transaction is the ITransaction instance associated with the transaction being committed.

This should never fail. If this raises an exception, the database is not expected to maintain consistency; it’s a serious error.

sortKey()

Return a key to use for ordering registered DataManagers.

In order to guarantee a total ordering, keys must be strings.

ZODB uses a global sort order to prevent deadlock when it commits transactions involving multiple resource managers. The resource manager must define a sortKey() method that provides a global ordering for resource managers.

tpc_abort(transaction)

Abort a transaction.

This is called by a transaction manager to end a two-phase commit on the data manager. Abandon all changes to objects modified by this transaction.

transaction is the ITransaction instance associated with the transaction being committed.

This should never fail.

abort(transaction)

Abort a transaction and forget all changes.

Abort must be called outside of a two-phase commit.

Abort is called by the transaction manager to abort transactions that are not yet in a two-phase commit. It may also be called when rolling back a savepoint made before the data manager joined the transaction.

In any case, after abort is called, the data manager is no longer participating in the transaction. If there are new changes, the data manager must rejoin the transaction.

transaction_manager

The transaction manager (TM) used by this data manager.

This is a public attribute, intended for read-only use. The value is an instance of ITransactionManager, typically set by the data manager’s constructor.

tpc_begin(transaction)

Begin commit of a transaction, starting the two-phase commit.

transaction is the ITransaction instance associated with the transaction being committed.

commit(transaction)

Commit modifications to registered objects.

Save changes to be made persistent if the transaction commits (if tpc_finish is called later). If tpc_abort is called later, changes must not persist.

This includes conflict detection and handling. If no conflicts or errors occur, the data manager should be prepared to make the changes persist when tpc_finish is called.

tpc_vote(transaction)

Verify that a data manager can commit the transaction.

This is the last chance for a data manager to vote ‘no’. A data manager votes ‘no’ by raising an exception.

transaction is the ITransaction instance associated with the transaction being committed.

interface transaction.interfaces.IDataManagerSavepoint

Savepoint for data-manager changes for use in transaction savepoints.

Datamanager savepoints are used by, and only by, transaction savepoints.

Note that data manager savepoints don’t have any notion of, or responsibility for, validity. It isn’t the responsibility of data-manager savepoints to prevent multiple rollbacks or rollbacks after transaction termination. Preventing invalid savepoint rollback is the responsibility of transaction rollbacks. Application code should never use data-manager savepoints.

rollback()

Rollback any work done since the savepoint.

interface transaction.interfaces.ISavepoint

A transaction savepoint.

valid

Boolean indicating whether the savepoint is valid

rollback()

Rollback any work done since the savepoint.

InvalidSavepointRollbackError is raised if the savepoint isn’t valid.

interface transaction.interfaces.ISavepointDataManager

Extends: transaction.interfaces.IDataManager

savepoint()

Return a data-manager savepoint (IDataManagerSavepoint).

interface transaction.interfaces.ISynchronizer

Objects that participate in the transaction-boundary notification API.

newTransaction(transaction)

Hook that is called at the start of a transaction.

This hook is called when, and only when, a transaction manager’s begin() method is called explictly.

afterCompletion(transaction)

Hook that is called by the transaction after completing a commit.

beforeCompletion(transaction)

Hook that is called by the transaction at the start of a commit.

interface transaction.interfaces.ITransaction

Object representing a running transaction.

Objects with this interface may represent different transactions during their lifetime (.begin() can be called to start a new transaction using the same instance, although that example is deprecated and will go away in ZODB 3.6).

join(datamanager)

Add a data manager to the transaction.

datamanager must provide the transactions.interfaces.IDataManager interface.

description

A textual description of the transaction.

The value is of Python type str. Method note() is the intended way to set the value. Storages record the description, as meta-data, when a transaction commits.

A storage may impose a limit on the size of the description; behavior is undefined if such a limit is exceeded (for example, a storage may raise an exception, or truncate the value).

addAfterCommitHook(hook, args=(), kws=None)

Register a hook to call after a transaction commit attempt.

The specified hook function will be called after the transaction commit succeeds or aborts. The first argument passed to the hook is a Boolean value, true if the commit succeeded, or false if the commit aborted. args specifies additional positional, and kws keyword, arguments to pass to the hook. args is a sequence of positional arguments to be passed, defaulting to an empty tuple (only the true/false success argument is passed). kws is a dictionary of keyword argument names and values to be passed, or the default None (no keyword arguments are passed).

Multiple hooks can be registered and will be called in the order they were registered (first registered, first called). This method can also be called from a hook: an executing hook can register more hooks. Applications should take care to avoid creating infinite loops by recursively registering hooks.

Hooks are called only for a top-level commit. A savepoint creation does not call any hooks. Calling a hook “consumes” its registration: hook registrations do not persist across transactions. If it’s desired to call the same hook on every transaction commit, then addAfterCommitHook() must be called with that hook during every transaction; in such a case consider registering a synchronizer object via a TransactionManager’s registerSynch() method instead.

getAfterCommitHooks()

Return iterable producing the registered addAfterCommit hooks.

A triple (hook, args, kws) is produced for each registered hook. The hooks are produced in the order in which they would be invoked by a top-level transaction commit.

savepoint(optimistic=False)

Create a savepoint.

If the optimistic argument is true, then data managers that don’t support savepoints can be used, but an error will be raised if the savepoint is rolled back.

An ISavepoint object is returned.

setExtendedInfo(name, value)

Add extension data to the transaction.

name is the name of the extension property to set, of Python type str; value must be picklable. Multiple calls may be made to set multiple extension properties, provided the names are distinct.

Storages record the extension data, as meta-data, when a transaction commits.

A storage may impose a limit on the size of extension data; behavior is undefined if such a limit is exceeded (for example, a storage may raise an exception, or remove <name, value> pairs).

beforeCommitHook(_ITransaction__hook, *args, **kws)

Register a hook to call before the transaction is committed.

THIS IS DEPRECATED IN ZODB 3.6. Use addBeforeCommitHook() instead.

The specified hook function will be called after the transaction’s commit method has been called, but before the commit process has been started. The hook will be passed the specified positional and keyword arguments.

Multiple hooks can be registered and will be called in the order they were registered (first registered, first called). This method can also be called from a hook: an executing hook can register more hooks. Applications should take care to avoid creating infinite loops by recursively registering hooks.

Hooks are called only for a top-level commit. A savepoint does not call any hooks. If the transaction is aborted, hooks are not called, and are discarded. Calling a hook “consumes” its registration too: hook registrations do not persist across transactions. If it’s desired to call the same hook on every transaction commit, then beforeCommitHook() must be called with that hook during every transaction; in such a case consider registering a synchronizer object via a TransactionManager’s registerSynch() method instead.

note(text)

Add text to the transaction description.

This modifies the .description attribute; see its docs for more detail. First surrounding whitespace is stripped from text. If .description is currently an empty string, then the stripped text becomes its value, else two newlines and the stripped text are appended to .description.

abort()

Abort the transaction.

This is called from the application. This can only be called before the two-phase commit protocol has been started.

user

A user name associated with the transaction.

The format of the user name is defined by the application. The value is of Python type str. Storages record the user value, as meta-data, when a transaction commits.

A storage may impose a limit on the size of the value; behavior is undefined if such a limit is exceeded (for example, a storage may raise an exception, or truncate the value).

setUser(user_name, path='/')

Set the user name.

path should be provided if needed to further qualify the identified user. This is a convenience method used by Zope. It sets the .user attribute to str(path) + ” ” + str(user_name). This sets the .user attribute; see its docs for more detail.

addBeforeCommitHook(hook, args=(), kws=None)

Register a hook to call before the transaction is committed.

The specified hook function will be called after the transaction’s commit method has been called, but before the commit process has been started. The hook will be passed the specified positional (args) and keyword (kws) arguments. args is a sequence of positional arguments to be passed, defaulting to an empty tuple (no positional arguments are passed). kws is a dictionary of keyword argument names and values to be passed, or the default None (no keyword arguments are passed).

Multiple hooks can be registered and will be called in the order they were registered (first registered, first called). This method can also be called from a hook: an executing hook can register more hooks. Applications should take care to avoid creating infinite loops by recursively registering hooks.

Hooks are called only for a top-level commit. A savepoint creation does not call any hooks. If the transaction is aborted, hooks are not called, and are discarded. Calling a hook “consumes” its registration too: hook registrations do not persist across transactions. If it’s desired to call the same hook on every transaction commit, then addBeforeCommitHook() must be called with that hook during every transaction; in such a case consider registering a synchronizer object via a TransactionManager’s registerSynch() method instead.

commit()

Finalize the transaction.

This executes the two-phase commit algorithm for all IDataManager objects associated with the transaction.

doom()

Doom the transaction.

Dooms the current transaction. This will cause DoomedTransactionException to be raised on any attempt to commit the transaction.

Otherwise the transaction will behave as if it was active.

getBeforeCommitHooks()

Return iterable producing the registered addBeforeCommit hooks.

A triple (hook, args, kws) is produced for each registered hook. The hooks are produced in the order in which they would be invoked by a top-level transaction commit.

interface transaction.interfaces.ITransactionDeprecated

Deprecated parts of the transaction API.

begin(info=None)

Begin a new transaction.

If the transaction is in progress, it is aborted and a new transaction is started using the same transaction object.

register(object)

Register the given object for transaction control.

interface transaction.interfaces.ITransactionManager

An object that manages a sequence of transactions.

Applications use transaction managers to establish transaction boundaries.

begin()

Begin a new transaction.

If an existing transaction is in progress, it will be aborted.

The newTransaction() method of registered synchronizers is called, passing the new transaction object.

registerSynch(synch)

Register an ISynchronizer.

Synchronizers are notified about some major events in a transaction’s life. See ISynchronizer for details.

get()

Get the current transaction.

unregisterSynch(synch)

Unregister an ISynchronizer.

Synchronizers are notified about some major events in a transaction’s life. See ISynchronizer for details.

savepoint(optimistic=False)

Create a savepoint from the current transaction.

If the optimistic argument is true, then data managers that don’t support savepoints can be used, but an error will be raised if the savepoint is rolled back.

An ISavepoint object is returned.

isDoomed()

Returns True if the current transaction is doomed, otherwise False.

abort()

Abort the current transaction.

commit()

Commit the current transaction.

doom()

Doom the current transaction.

blog comments powered by Disqus