On Apr 18, 2013, at 4:22 PM, Philipp Kraus <philipp.kr...@flashpixx.de> wrote:

> Hello,
> 
> I try to use SQLAlchemy in buildscripts for SCons, so I run my SCons script 
> and depend on the data all tables are created.
> I'm new with SQLAlchemy and Python database access, so can I create a 
> transaction with SQLAlchemy for the create table
> statements and also the insert statements, so if one of them creates an 
> error, the full transaction is rollbacked ?
> 
> I think I need something like:
> try 
> start_transaction()
> metadata.drop_all
> metadata.create_all
> 
> metadata.insert
> insert.execute
> commit_transaction()
> except :
>     rollback_transaction()
> 
> Can anybody explain me please, in which case I can add a transaction around 
> the drop and create and the insert calls.

not every backend supports transactional DDL, which means that CREATE/DROP 
statements can be rolled back in a transaction.  The ones that do include 
Postgresql and Microsoft SQL Server, and do not include MySQL or SQLite (SQLite 
supports it by itself but the pysqlite DBAPI does not).

Assuming you're on a backend that supports transactional DDL, drop_all and 
create_all accept a source of connectivity which may be a Connection in a 
transaction:

engine = create_engine("postgresql://...")
with engine.begin() as conn:
    metadata.create_all(conn)

    conn.execute(table.insert()...)

The above block will emit a "commit()" automatically, and a "rollback()" if an 
exception is thrown.

More docs on using transactions at this level are at 
http://docs.sqlalchemy.org/en/rel_0_8/core/connections.html#using-transactions .

-- 
You received this message because you are subscribed to the Google Groups 
"sqlalchemy" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to sqlalchemy+unsubscr...@googlegroups.com.
To post to this group, send email to sqlalchemy@googlegroups.com.
Visit this group at http://groups.google.com/group/sqlalchemy?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.


Reply via email to