Skip to main content

Minimal Zope/SQLAlchemy transaction integration

Project description

The aim of this package is to unify the plethora of existing packages integrating SQLAlchemy with Zope’s transaction management. As such it seeks only to provide a data manager and makes no attempt to define a zopeish way to configure engines.

You need to understand SQLAlchemy for this package and this README to make any sense. See http://sqlalchemy.org/docs/.

Running the tests

This package is distributed as a buildout. Using your desired python run:

$ python bootstrap.py

This will download the dependent packages and setup the test script, which may be run with:

$ ./bin/test

To enable testing with your own database set the TEST_DSN environment variable to your sqlalchemy database dsn. Two-phase commit behaviour may be tested by setting the TEST_TWOPHASE variable to a non empty string. e.g:

$ TEST_DSN=postgres://test:test@localhost/test TEST_TWOPHASE=True bin/test

Example

This example is lifted directly from the SQLAlchemy declarative documentation. First the necessary imports.

>>> from sqlalchemy import *
>>> from sqlalchemy.ext.declarative import declarative_base
>>> from sqlalchemy.orm import scoped_session, sessionmaker, relation
>>> from zope.sqlalchemy import ZopeTransactionExtension, invalidate
>>> import transaction

Now to define the mapper classes.

>>> Base = declarative_base()
>>> class User(Base):
...     __tablename__ = 'test_users'
...     id = Column('id', Integer, primary_key=True)
...     name = Column('name', String(50))
...     addresses = relation("Address", backref="user")
>>> class Address(Base):
...     __tablename__ = 'test_addresses'
...     id = Column('id', Integer, primary_key=True)
...     email = Column('email', String(50))
...     user_id = Column('user_id', Integer, ForeignKey('test_users.id'))

Create an engine and setup the tables. Note that for this example to work a recent version of sqlite/pysqlite is required. 3.4.0 seems to be sufficient.

>>> engine = create_engine(TEST_DSN, convert_unicode=True)
>>> Base.metadata.create_all(engine)

Now to create the session itself. As zope is a threaded web server we must use scoped sessions. Zope and SQLAlchemy sessions are tied together by using the ZopeTransactionExtension from this package.

>>> Session = scoped_session(sessionmaker(bind=engine, twophase=TEST_TWOPHASE,
... transactional=True, autoflush=True, extension=ZopeTransactionExtension()))

Call the scoped session factory to retrieve a session. You may call this as many times as you like within a transaction and you will always retrieve the same session. At present there are no users in the database.

>>> session = Session()
>>> session.query(User).all()
[]

We can now create a new user and commit the changes using Zope’s transaction machinary, just as Zope’s publisher would.

>>> session.save(User(name='bob'))
>>> transaction.commit()

Engine level connections are outside the scope of the transaction integration.

>>> engine.connect().execute('SELECT * FROM test_users').fetchall()
[(1, ...'bob')]

A new transaction requires a new session. Let’s add an address.

>>> session = Session()
>>> bob = session.query(User).all()[0]
>>> bob.name
u'bob'
>>> bob.addresses
[]
>>> bob.addresses.append(Address(email='bob@bob.bob'))
>>> transaction.commit()
>>> session = Session()
>>> bob = session.query(User).all()[0]
>>> bob.addresses
[<Address object at ...>]
>>> bob.addresses[0].email
u'bob@bob.bob'
>>> bob.addresses[0].email = 'wrong@wrong'

To rollback a transaction, use transaction.abort().

>>> transaction.abort()
>>> session = Session()
>>> bob = session.query(User).all()[0]
>>> bob.addresses[0].email
u'bob@bob.bob'
>>> transaction.abort()

By default, zope.sqlalchemy puts sessions in an ‘active’ state when they are first used. ORM write operations automatically move the session into an ‘invalidated’ state. This avoids unnecessary database commits. Sometimes it is necessary to interact with the database directly through SQL. It is not possible to guess whether such an operation is a read or a write. Therefore we must manually mark the session as invalidated when manual SQL statements write to the DB.

>>> session = Session()
>>> conn = session.connection()
>>> users = Base.metadata.tables['test_users']
>>> conn.execute(users.update(users.c.name=='bob'), name='ben')
<sqlalchemy.engine.base.ResultProxy object at ...>
>>> from zope.sqlalchemy import invalidate
>>> invalidate(session)
>>> transaction.commit()
>>> session = Session()
>>> session.query(User).all()[0].name
u'ben'
>>> transaction.abort()

If this is a problem you may tell the extension to place the session in the ‘invalidated’ state initially.

>>> Session.configure(extension=ZopeTransactionExtension('invalidated'))
>>> Session.remove()
>>> session = Session()
>>> conn = session.connection()
>>> conn.execute(users.update(users.c.name=='ben'), name='bob')
<sqlalchemy.engine.base.ResultProxy object at ...>
>>> transaction.commit()
>>> session = Session()
>>> session.query(User).all()[0].name
u'bob'
>>> transaction.abort()

SVN version.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

zope.sqlalchemy-0.1.tar.gz (10.3 kB view details)

Uploaded Source

Built Distributions

If you're not sure about the file name format, learn more about wheel file names.

zope.sqlalchemy-0.1-py2.5.egg (21.3 kB view details)

Uploaded Egg

zope.sqlalchemy-0.1-py2.4.egg (21.5 kB view details)

Uploaded Egg

File details

Details for the file zope.sqlalchemy-0.1.tar.gz.

File metadata

  • Download URL: zope.sqlalchemy-0.1.tar.gz
  • Upload date:
  • Size: 10.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No

File hashes

Hashes for zope.sqlalchemy-0.1.tar.gz
Algorithm Hash digest
SHA256 1098f49ab8a5aab453f252984eb492519fa1f595244f1a29d5d70cadffedac5c
MD5 417b56b931139e69ae084659674c6b9d
BLAKE2b-256 f4c02d9b30581da2f21043ee4a76074901eec3831cfb300b1e3d9b3ccc23318c

See more details on using hashes here.

File details

Details for the file zope.sqlalchemy-0.1-py2.5.egg.

File metadata

File hashes

Hashes for zope.sqlalchemy-0.1-py2.5.egg
Algorithm Hash digest
SHA256 5fcb160b7009bddeaad02dda090d4d11db53fdb790de2cc0fa1e0c9b2e34f0b2
MD5 fa6a82602dc5f6cef1d5cb492eb764ca
BLAKE2b-256 ce2c9a8cdcf62a2873a5ffe62727a1c76a4e1ef053426adb45869f527c9d90d3

See more details on using hashes here.

File details

Details for the file zope.sqlalchemy-0.1-py2.4.egg.

File metadata

File hashes

Hashes for zope.sqlalchemy-0.1-py2.4.egg
Algorithm Hash digest
SHA256 5ba801199deb91f12abe2b4a7f87e0a1d9710c1e5c37e7be36dd241b8f7c218c
MD5 365f8072798b3ce6f647b195e04f1b87
BLAKE2b-256 cc034441849bfaa31a9910f5f3a61a50d680598f1be329b160b7d78f5cfe55b8

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page