SQLAlchemy 0.6.1 Documentation

Version: 0.6.1 Last Updated: 07/25/2016 21:14:41
API Reference | Index

Connections

Creating Engines

sqlalchemy.create_engine(*args, **kwargs)

Create a new Engine instance.

The standard method of specifying the engine is via URL as the first positional argument, to indicate the appropriate database dialect and connection arguments, with additional keyword arguments sent as options to the dialect and resulting Engine.

The URL is a string in the form dialect+driver://user:password@host/dbname[?key=value..], where dialect is a database name such as mysql, oracle, postgresql, etc., and driver the name of a DBAPI, such as psycopg2, pyodbc, cx_oracle, etc. Alternatively, the URL can be an instance of URL.

**kwargs takes a wide variety of options which are routed towards their appropriate components. Arguments may be specific to the Engine, the underlying Dialect, as well as the Pool. Specific dialects also accept keyword arguments that are unique to that dialect. Here, we describe the parameters that are common to most create_engine() usage.

Parameters:
  • assert_unicode – Deprecated. A warning is raised in all cases when a non-Unicode object is passed when SQLAlchemy would coerce into an encoding (note: but not when the DBAPI handles unicode objects natively). To suppress or raise this warning to an error, use the Python warnings filter documented at: http://docs.python.org/library/warnings.html
  • connect_args – a dictionary of options which will be passed directly to the DBAPI’s connect() method as additional keyword arguments.
  • convert_unicode=False – if set to True, all String/character based types will convert Unicode values to raw byte values going into the database, and all raw byte values to Python Unicode coming out in result sets. This is an engine-wide method to provide unicode conversion across the board. For unicode conversion on a column-by-column level, use the Unicode column type instead, described in types.
  • creator – a callable which returns a DBAPI connection. This creation function will be passed to the underlying connection pool and will be used to create all new database connections. Usage of this function causes connection parameters specified in the URL argument to be bypassed.
  • echo=False – if True, the Engine will log all statements as well as a repr() of their parameter lists to the engines logger, which defaults to sys.stdout. The echo attribute of Engine can be modified at any time to turn logging on and off. If set to the string "debug", result rows will be printed to the standard output as well. This flag ultimately controls a Python logger; see Configuring Logging for information on how to configure logging directly.
  • echo_pool=False – if True, the connection pool will log all checkouts/checkins to the logging stream, which defaults to sys.stdout. This flag ultimately controls a Python logger; see Configuring Logging for information on how to configure logging directly.
  • encoding=’utf-8’ – the encoding to use for all Unicode translations, both by engine-wide unicode conversion as well as the Unicode type object.
  • execution_options – Dictionary execution options which will be applied to all connections. See execution_options()
  • label_length=None – optional integer value which limits the size of dynamically generated column labels to that many characters. If less than 6, labels are generated as “_(counter)”. If None, the value of dialect.max_identifier_length is used instead.
  • listeners – A list of one or more PoolListener objects which will receive connection pool events.
  • logging_name – String identifier which will be used within the “name” field of logging records generated within the “sqlalchemy.engine” logger. Defaults to a hexstring of the object’s id.
  • max_overflow=10 – the number of connections to allow in connection pool “overflow”, that is connections that can be opened above and beyond the pool_size setting, which defaults to five. this is only used with QueuePool.
  • module=None – used by database implementations which support multiple DBAPI modules, this is a reference to a DBAPI2 module to be used instead of the engine’s default module. For PostgreSQL, the default is psycopg2. For Oracle, it’s cx_Oracle.
  • pool=None – an already-constructed instance of Pool, such as a QueuePool instance. If non-None, this pool will be used directly as the underlying connection pool for the engine, bypassing whatever connection parameters are present in the URL argument. For information on constructing connection pools manually, see pooling.
  • poolclass=None – a Pool subclass, which will be used to create a connection pool instance using the connection parameters given in the URL. Note this differs from pool in that you don’t actually instantiate the pool in this case, you just indicate what type of pool to be used.
  • pool_logging_name – String identifier which will be used within the “name” field of logging records generated within the “sqlalchemy.pool” logger. Defaults to a hexstring of the object’s id.
  • pool_size=5 – the number of connections to keep open inside the connection pool. This used with QueuePool as well as SingletonThreadPool.
  • pool_recycle=-1 – this setting causes the pool to recycle connections after the given number of seconds has passed. It defaults to -1, or no timeout. For example, setting to 3600 means connections will be recycled after one hour. Note that MySQL in particular will disconnect automatically if no activity is detected on a connection for eight hours (although this is configurable with the MySQLDB connection itself and the server configuration as well).
  • pool_timeout=30 – number of seconds to wait before giving up on getting a connection from the pool. This is only used with QueuePool.
  • strategy=’plain’ – used to invoke alternate implementations. Currently available is the threadlocal strategy, which is described in Using the Threadlocal Execution Strategy.
sqlalchemy.engine_from_config(configuration, prefix='sqlalchemy.', **kwargs)

Create a new Engine instance using a configuration dictionary.

The dictionary is typically produced from a config file where keys are prefixed, such as sqlalchemy.url, sqlalchemy.echo, etc. The ‘prefix’ argument indicates the prefix to be searched for.

A select set of keyword arguments will be “coerced” to their expected type based on string values. In a future release, this functionality will be expanded and include dialect-specific arguments.

class sqlalchemy.engine.url.URL(drivername, username=None, password=None, host=None, port=None, database=None, query=None)

Represent the components of a URL used to connect to a database.

This object is suitable to be passed directly to a create_engine() call. The fields of the URL are parsed from a string by the module-level make_url() function. the string format of the URL is an RFC-1738-style string.

All initialization parameters are available as public attributes.

Parameters:
  • drivername – the name of the database backend. This name will correspond to a module in sqlalchemy/databases or a third party plug-in.
  • username – The user name.
  • password – database password.
  • host – The name of the host.
  • port – The port number.
  • database – The database name.
  • query – A dictionary of options to be passed to the dialect and/or the DBAPI upon connect.
__init__(drivername, username=None, password=None, host=None, port=None, database=None, query=None)
get_dialect()
Return the SQLAlchemy database dialect class corresponding to this URL’s driver name.
translate_connect_args(names=[], **kw)

Translate url attributes into a dictionary of connection arguments.

Returns attributes of this url (host, database, username, password, port) as a plain dictionary. The attribute names are used as the keys by default. Unset or false attributes are omitted from the final dictionary.

Parameters:
  • **kw – Optional, alternate key names for url attributes.
  • names – Deprecated. Same purpose as the keyword-based alternate names, but correlates the name to the original positionally.

Connectables

class sqlalchemy.engine.base.Engine(pool, dialect, url, logging_name=None, echo=None, proxy=None, execution_options=None)

Connects a Pool and Dialect together to provide a source of database connectivity and behavior.

An Engine object is instantiated publically using the create_engine() function.

__init__(pool, dialect, url, logging_name=None, echo=None, proxy=None, execution_options=None)
connect(**kwargs)
Return a newly allocated Connection object.
contextual_connect(close_with_result=False, **kwargs)

Return a Connection object which may be newly allocated, or may be part of some ongoing context.

This Connection is meant to be used by the various “auto-connecting” operations.

create(entity, connection=None, **kwargs)
Create a table or index within this engine’s database connection given a schema object.
dispose()

Dispose of the connection pool used by this Engine.

A new connection pool is created immediately after the old one has been disposed. This new pool, like all SQLAlchemy connection pools, does not make any actual connections to the database until one is first requested.

This method has two general use cases:

  • When a dropped connection is detected, it is assumed that all connections held by the pool are potentially dropped, and the entire pool is replaced.
  • An application may want to use dispose() within a test suite that is creating multiple engines.

It is critical to note that dispose() does not guarantee that the application will release all open database connections - only those connections that are checked into the pool are closed. Connections which remain checked out or have been detached from the engine are not affected.

driver
Driver name of the Dialect in use by this Engine.
drop(entity, connection=None, **kwargs)
Drop a table or index within this engine’s database connection given a schema object.
echo

When True, enable log output for this element.

This has the effect of setting the Python logging level for the namespace of this element’s class and object reference. A value of boolean True indicates that the loglevel logging.INFO will be set for the logger, whereas the string value debug will set the loglevel to logging.DEBUG.

name
String name of the Dialect in use by this Engine.
raw_connection()
Return a DB-API connection.
reflecttable(table, connection=None, include_columns=None)
Given a Table object, reflects its columns and properties from the database.
table_names(schema=None, connection=None)

Return a list of all table names available in the database.

Parameters:
  • schema – Optional, retrieve names from a non-default schema.
  • connection – Optional, use a specified connection. Default is the contextual_connect for this Engine.
text(text, *args, **kwargs)
Return a sql.text() object for performing literal queries.
transaction(callable_, *args, **kwargs)

Execute the given function within a transaction boundary.

This is a shortcut for explicitly calling begin() and commit() and optionally rollback() when exceptions are raised. The given *args and **kwargs will be passed to the function.

The connection used is that of contextual_connect().

See also the similar method on Connection itself.

update_execution_options(**opt)

update the execution_options dictionary of this Engine.

For details on execution_options, see Connection.execution_options() as well as sqlalchemy.sql.expression.Executable.execution_options().

class sqlalchemy.engine.base.Connection(engine, connection=None, close_with_result=False, _branch=False, _execution_options=None)

Provides high-level functionality for a wrapped DB-API connection.

Provides execution support for string-based SQL statements as well as ClauseElement, Compiled and DefaultGenerator objects. Provides a begin() method to return Transaction objects.

The Connection object is not thread-safe.

__init__(engine, connection=None, close_with_result=False, _branch=False, _execution_options=None)

Construct a new Connection.

Connection objects are typically constructed by an Engine, see the connect() and contextual_connect() methods of Engine.

begin()

Begin a transaction and return a Transaction handle.

Repeated calls to begin on the same Connection will create a lightweight, emulated nested transaction. Only the outermost transaction may commit. Calls to commit on inner transactions are ignored. Any transaction in the hierarchy may rollback, however.

begin_nested()

Begin a nested transaction and return a Transaction handle.

Nested transactions require SAVEPOINT support in the underlying database. Any transaction in the hierarchy may commit and rollback, however the outermost transaction still controls the overall commit or rollback of the transaction of a whole.

begin_twophase(xid=None)

Begin a two-phase or XA transaction and return a Transaction handle.

Parameter:xid – the two phase transaction id. If not supplied, a random id will be generated.
close()
Close this Connection.
closed
Return True if this connection is closed.
connect()

Returns self.

This Connectable interface method returns self, allowing Connections to be used interchangably with Engines in most situations that require a bind.

connection
The underlying DB-API connection managed by this Connection.
contextual_connect(**kwargs)

Returns self.

This Connectable interface method returns self, allowing Connections to be used interchangably with Engines in most situations that require a bind.

create(entity, **kwargs)
Create a Table or Index given an appropriate Schema object.
detach()

Detach the underlying DB-API connection from its connection pool.

This Connection instance will remain useable. When closed, the DB-API connection will be literally closed and not returned to its pool. The pool will typically lazily create a new connection to replace the detached connection.

This method can be used to insulate the rest of an application from a modified state on a connection (such as a transaction isolation level or similar). Also see PoolListener for a mechanism to modify connection state when connections leave and return to their connection pool.

dialect
Dialect used by this Connection.
drop(entity, **kwargs)
Drop a Table or Index given an appropriate Schema object.
execute(object, *multiparams, **params)
Executes and returns a ResultProxy.
execution_options(**opt)

Set non-SQL options for the connection which take effect during execution.

The method returns a copy of this Connection which references the same underlying DBAPI connection, but also defines the given execution options which will take effect for a call to execute(). As the new Connection references the same underlying resource, it is probably best to ensure that the copies would be discarded immediately, which is implicit if used as in:

result = connection.execution_options(stream_results=True).                                execute(stmt)

The options are the same as those accepted by sqlalchemy.sql.expression.Executable.execution_options().

in_transaction()
Return True if a transaction is in progress.
info
A collection of per-DB-API connection instance properties.
invalidate(exception=None)

Invalidate the underlying DBAPI connection associated with this Connection.

The underlying DB-API connection is literally closed (if possible), and is discarded. Its source connection pool will typically lazily create a new connection to replace it.

Upon the next usage, this Connection will attempt to reconnect to the pool with a new connection.

Transactions in progress remain in an “opened” state (even though the actual transaction is gone); these must be explicitly rolled back before a reconnect on this Connection can proceed. This is to prevent applications from accidentally continuing their transactional operations in a non-transactional state.

invalidated
Return True if this connection was invalidated.
reflecttable(table, include_columns=None)
Reflect the columns in the given string table name from the database.
scalar(object, *multiparams, **params)

Executes and returns the first column of the first row.

The underlying result/cursor is closed after execution.

transaction(callable_, *args, **kwargs)

Execute the given function within a transaction boundary.

This is a shortcut for explicitly calling begin() and commit() and optionally rollback() when exceptions are raised. The given *args and **kwargs will be passed to the function.

See also transaction() on engine.

class sqlalchemy.engine.base.Connectable

Interface for an object which supports execution of SQL constructs.

The two implementations of Connectable are Connection and Engine.

Connectable must also implement the ‘dialect’ member which references a Dialect instance.

contextual_connect()
Return a Connection object which may be part of an ongoing context.
create(entity, **kwargs)
Create a table or index given an appropriate schema object.
drop(entity, **kwargs)
Drop a table or index given an appropriate schema object.
execute(object, *multiparams, **params)

Result Objects

class sqlalchemy.engine.base.ResultProxy(context)

Wraps a DB-API cursor object to provide easier access to row columns.

Individual columns may be accessed by their integer position, case-insensitive column name, or by schema.Column object. e.g.:

row = fetchone()

col1 = row[0]    # access via integer position

col2 = row['col2']   # access via name

col3 = row[mytable.c.mycol] # access via Column object.

ResultProxy also handles post-processing of result column data using TypeEngine objects, which are referenced from the originating SQL statement that produced this result set.

__init__(context)
close(_autoclose_connection=True)

Close this ResultProxy.

Closes the underlying DBAPI cursor corresponding to the execution.

Note that any data cached within this ResultProxy is still available. For some types of results, this may include buffered rows.

If this ResultProxy was generated from an implicit execution, the underlying Connection will also be closed (returns the underlying DBAPI connection to the connection pool.)

This method is called automatically when:

  • all result rows are exhausted using the fetchXXX() methods.
  • cursor.description is None.
fetchall()
Fetch all rows, just like DB-API cursor.fetchall().
fetchmany(size=None)

Fetch many rows, just like DB-API cursor.fetchmany(size=cursor.arraysize).

If rows are present, the cursor remains open after this is called. Else the cursor is automatically closed and an empty list is returned.

fetchone()

Fetch one row, just like DB-API cursor.fetchone().

If a row is present, the cursor remains open after this is called. Else the cursor is automatically closed and None is returned.

first()

Fetch the first row and then close the result set unconditionally.

Returns None if no row is present.

keys()
Return the current set of string keys for rows.
last_inserted_ids()

deprecated. use inserted_primary_key.

Use inserted_primary_key

last_inserted_params()

Return last_inserted_params() from the underlying ExecutionContext.

See ExecutionContext for details.

last_updated_params()

Return last_updated_params() from the underlying ExecutionContext.

See ExecutionContext for details.

lastrow_has_defaults()

Return lastrow_has_defaults() from the underlying ExecutionContext.

See ExecutionContext for details.

lastrowid

return the ‘lastrowid’ accessor on the DBAPI cursor.

This is a DBAPI specific method and is only functional for those backends which support it, for statements where it is appropriate. It’s behavior is not consistent across backends.

Usage of this method is normally unnecessary; the inserted_primary_key method provides a tuple of primary key values for a newly inserted row, regardless of database backend.

postfetch_cols()

Return postfetch_cols() from the underlying ExecutionContext.

See ExecutionContext for details.

scalar()

Fetch the first column of the first row, and close the result set.

Returns None if no row is present.

supports_sane_multi_rowcount()
Return supports_sane_multi_rowcount from the dialect.
supports_sane_rowcount()
Return supports_sane_rowcount from the dialect.
class sqlalchemy.engine.base.RowProxy(parent, row, processors, keymap)

Proxy values from a single cursor row.

Mostly follows “ordered dictionary” behavior, mapping result values to the string-based column name, the integer position of the result in the row, as well as Column instances which can be mapped to the original Columns that produced this result set (for results that correspond to constructed SQL expressions).

has_key(key)
Return True if this RowProxy contains the given key.
items()
Return a list of tuples, each tuple containing a key/value pair.
keys()
Return the list of keys as strings represented by this RowProxy.

Transactions

class sqlalchemy.engine.base.Transaction(connection, parent)

Represent a Transaction in progress.

The Transaction object is not threadsafe.

__init__(connection, parent)
close()

Close this transaction.

If this transaction is the base transaction in a begin/commit nesting, the transaction will rollback(). Otherwise, the method returns.

This is used to cancel a Transaction without affecting the scope of an enclosing transaction.

commit()
rollback()

Internals

sqlalchemy.engine.base.connection_memoize(key)

Decorator, memoize a function in a connection.info stash.

Only applicable to functions which take no arguments other than a connection. The memo will be stored in connection.info[key].

class sqlalchemy.engine.base.Dialect

Define the behavior of a specific database and DB-API combination.

Any aspect of metadata definition, SQL query generation, execution, result-set handling, or anything else which varies between databases is defined under the general category of the Dialect. The Dialect acts as a factory for other database-specific object implementations including ExecutionContext, Compiled, DefaultGenerator, and TypeEngine.

All Dialects implement the following attributes:

name
identifying name for the dialect from a DBAPI-neutral point of view (i.e. ‘sqlite’)
driver
identifying name for the dialect’s DBAPI
positional
True if the paramstyle for this Dialect is positional.
paramstyle
the paramstyle to be used (some DB-APIs support multiple paramstyles).
convert_unicode
True if Unicode conversion should be applied to all str types.
encoding
type of encoding to use for unicode, usually defaults to ‘utf-8’.
statement_compiler
a Compiled class used to compile SQL statements
ddl_compiler
a Compiled class used to compile DDL statements
server_version_info
a tuple containing a version number for the DB backend in use. This value is only available for supporting dialects, and is typically populated during the initial connection to the database.
default_schema_name
the name of the default schema. This value is only available for supporting dialects, and is typically populated during the initial connection to the database.
execution_ctx_cls
a ExecutionContext class used to handle statement execution
execute_sequence_format
either the ‘tuple’ or ‘list’ type, depending on what cursor.execute() accepts for the second argument (they vary).
preparer
a IdentifierPreparer class used to quote identifiers.
supports_alter
True if the database supports ALTER TABLE.
max_identifier_length
The maximum length of identifier names.
supports_unicode_statements
Indicate whether the DB-API can receive SQL statements as Python unicode strings
supports_unicode_binds
Indicate whether the DB-API can receive string bind parameters as Python unicode strings
supports_sane_rowcount
Indicate whether the dialect properly implements rowcount for UPDATE and DELETE statements.
supports_sane_multi_rowcount
Indicate whether the dialect properly implements rowcount for UPDATE and DELETE statements when executed via executemany.
preexecute_autoincrement_sequences
True if ‘implicit’ primary key functions must be executed separately in order to get their value. This is currently oriented towards Postgresql.
implicit_returning
use RETURNING or equivalent during INSERT execution in order to load newly generated primary keys and other column defaults in one execution, which are then available via inserted_primary_key. If an insert statement has returning() specified explicitly, the “implicit” functionality is not used and inserted_primary_key will not be available.
dbapi_type_map

A mapping of DB-API type objects present in this Dialect’s DB-API implementation mapped to TypeEngine implementations used by the dialect.

This is used to apply types to result sets based on the DB-API types present in cursor.description; it only takes effect for result sets against textual statements where no explicit typemap was present.

colspecs
A dictionary of TypeEngine classes from sqlalchemy.types mapped to subclasses that are specific to the dialect class. This dictionary is class-level only and is not accessed from the dialect instance itself.
supports_default_values
Indicates if the construct INSERT INTO tablename DEFAULT VALUES is supported
supports_sequences
Indicates if the dialect supports CREATE SEQUENCE or similar.
sequences_optional
If True, indicates if the “optional” flag on the Sequence() construct should signal to not generate a CREATE SEQUENCE. Applies only to dialects that support sequences. Currently used only to allow Postgresql SERIAL to be used on a column that specifies Sequence() for usage on other backends.
supports_native_enum
Indicates if the dialect supports a native ENUM construct. This will prevent types.Enum from generating a CHECK constraint when that type is used.
supports_native_boolean
Indicates if the dialect supports a native boolean construct. This will prevent types.Boolean from generating a CHECK constraint when that type is used.
create_connect_args(url)

Build DB-API compatible connection arguments.

Given a URL object, returns a tuple consisting of a *args/**kwargs suitable to send directly to the dbapi’s connect function.

create_xid()

Create a two-phase transaction ID.

This id will be passed to do_begin_twophase(), do_rollback_twophase(), do_commit_twophase(). Its format is unspecified.

denormalize_name(name)

convert the given name to a case insensitive identifier for the backend if it is an all-lowercase name.

this method is only used if the dialect defines requires_name_normalize=True.

do_begin(connection)
Provide an implementation of connection.begin(), given a DB-API connection.
do_begin_twophase(connection, xid)
Begin a two phase transaction on the given connection.
do_commit(connection)
Provide an implementation of connection.commit(), given a DB-API connection.
do_commit_twophase(connection, xid, is_prepared=True, recover=False)
Commit a two phase transaction on the given connection.
do_execute(cursor, statement, parameters, context=None)
Provide an implementation of cursor.execute(statement, parameters).
do_executemany(cursor, statement, parameters, context=None)
Provide an implementation of cursor.executemany(statement, parameters).
do_prepare_twophase(connection, xid)
Prepare a two phase transaction on the given connection.
do_recover_twophase(connection)
Recover list of uncommited prepared two phase transaction identifiers on the given connection.
do_release_savepoint(connection, name)
Release the named savepoint on a SQL Alchemy connection.
do_rollback(connection)
Provide an implementation of connection.rollback(), given a DB-API connection.
do_rollback_to_savepoint(connection, name)
Rollback a SQL Alchemy connection to the named savepoint.
do_rollback_twophase(connection, xid, is_prepared=True, recover=False)
Rollback a two phase transaction on the given connection.
do_savepoint(connection, name)
Create a savepoint with the given name on a SQLAlchemy connection.
get_columns(connection, table_name, schema=None, **kw)

Return information about columns in table_name.

Given a Connection, a string table_name, and an optional string schema, return column information as a list of dictionaries with these keys:

name
the column’s name
type
[sqlalchemy.types#TypeEngine]
nullable
boolean
default
the column’s default value
autoincrement
boolean
sequence
a dictionary of the form
{‘name’ : str, ‘start’ :int, ‘increment’: int}

Additional column attributes may be present.

get_foreign_keys(connection, table_name, schema=None, **kw)

Return information about foreign_keys in table_name.

Given a Connection, a string table_name, and an optional string schema, return foreign key information as a list of dicts with these keys:

name
the constraint’s name
constrained_columns
a list of column names that make up the foreign key
referred_schema
the name of the referred schema
referred_table
the name of the referred table
referred_columns
a list of column names in the referred table that correspond to constrained_columns
get_indexes(connection, table_name, schema=None, **kw)

Return information about indexes in table_name.

Given a Connection, a string table_name and an optional string schema, return index information as a list of dictionaries with these keys:

name
the index’s name
column_names
list of column names in order
unique
boolean
get_pk_constraint(table_name, schema=None, **kw)

Return information about the primary key constraint on table_name`.

Given a string table_name, and an optional string schema, return primary key information as a dictionary with these keys:

constrained_columns
a list of column names that make up the primary key
name
optional name of the primary key constraint.
get_primary_keys(connection, table_name, schema=None, **kw)

Return information about primary keys in table_name.

Given a Connection, a string table_name, and an optional string schema, return primary key information as a list of column names.

get_table_names(connection, schema=None, **kw)
Return a list of table names for schema.
get_view_definition(connection, view_name, schema=None, **kw)

Return view definition.

Given a Connection, a string view_name, and an optional string schema, return the view definition.

get_view_names(connection, schema=None, **kw)

Return a list of all view names available in the database.

schema:
Optional, retrieve names from a non-default schema.
has_sequence(connection, sequence_name, schema=None)

Check the existence of a particular sequence in the database.

Given a Connection object and a string sequence_name, return True if the given sequence exists in the database, False otherwise.

has_table(connection, table_name, schema=None)

Check the existence of a particular table in the database.

Given a Connection object and a string table_name, return True if the given table (possibly within the specified schema) exists in the database, False otherwise.

initialize(connection)

Called during strategized creation of the dialect with a connection.

Allows dialects to configure options based on server version info or other properties.

The connection passed here is a SQLAlchemy Connection object, with full capabilities.

The initalize() method of the base dialect should be called via super().

is_disconnect(e)
Return True if the given DB-API error indicates an invalid connection
normalize_name(name)

convert the given name to lowercase if it is detected as case insensitive.

this method is only used if the dialect defines requires_name_normalize=True.

on_connect()

return a callable which sets up a newly created DBAPI connection.

The callable accepts a single argument “conn” which is the DBAPI connection itself. It has no return value.

This is used to set dialect-wide per-connection options such as isolation modes, unicode modes, etc.

If a callable is returned, it will be assembled into a pool listener that receives the direct DBAPI connection, with all wrappers removed.

If None is returned, no listener will be generated.

reflecttable(connection, table, include_columns=None)

Load table description from the database.

Given a Connection and a Table object, reflect its columns and properties from the database. If include_columns (a list or set) is specified, limit the autoload to the given column names.

The default implementation uses the Inspector interface to provide the output, building upon the granular table/column/ constraint etc. methods of Dialect.

classmethod type_descriptor(typeobj)

Transform a generic type to a dialect-specific type.

Dialect classes will usually use the adapt_type() function in the types module to make this job easy.

The returned result is cached per dialect class so can contain no dialect-instance state.

class sqlalchemy.engine.default.DefaultDialect(convert_unicode=False, assert_unicode=False, encoding='utf-8', paramstyle=None, dbapi=None, implicit_returning=None, label_length=None, **kwargs)

Bases: sqlalchemy.engine.base.Dialect

Default implementation of Dialect

__init__(convert_unicode=False, assert_unicode=False, encoding='utf-8', paramstyle=None, dbapi=None, implicit_returning=None, label_length=None, **kwargs)
create_xid()

Create a random two-phase transaction ID.

This id will be passed to do_begin_twophase(), do_rollback_twophase(), do_commit_twophase(). Its format is unspecified.

do_begin(connection)
Implementations might want to put logic here for turning autocommit on/off, etc.
do_commit(connection)
Implementations might want to put logic here for turning autocommit on/off, etc.
do_rollback(connection)
Implementations might want to put logic here for turning autocommit on/off, etc.
execute_sequence_format
alias of tuple
get_pk_constraint(conn, table_name, schema=None, **kw)
Compatiblity method, adapts the result of get_primary_keys() for those dialects which don’t implement get_pk_constraint().
on_connect()

return a callable which sets up a newly created DBAPI connection.

This is used to set dialect-wide per-connection options such as isolation modes, unicode modes, etc.

If a callable is returned, it will be assembled into a pool listener that receives the direct DBAPI connection, with all wrappers removed.

If None is returned, no listener will be generated.

preparer
alias of IdentifierPreparer
statement_compiler
alias of SQLCompiler
type_descriptor(typeobj)

Provide a database-specific TypeEngine object, given the generic object which comes from the types module.

This method looks for a dictionary called colspecs as a class or instance-level variable, and passes on to types.adapt_type().

class sqlalchemy.engine.default.DefaultExecutionContext(dialect, connection, compiled_sql=None, compiled_ddl=None, statement=None, parameters=None)

Bases: sqlalchemy.engine.base.ExecutionContext

__init__(dialect, connection, compiled_sql=None, compiled_ddl=None, statement=None, parameters=None)
get_lastrowid()

return self.cursor.lastrowid, or equivalent, after an INSERT.

This may involve calling special cursor functions, issuing a new SELECT on the cursor (or a new one), or returning a stored value that was calculated within post_exec().

This function will only be called for dialects which support “implicit” primary key generation, keep preexecute_autoincrement_sequences set to False, and when no explicit id value was bound to the statement.

The function is called once, directly after post_exec() and before the transaction is committed or ResultProxy is generated. If the post_exec() method assigns a value to self._lastrowid, the value is used in place of calling get_lastrowid().

Note that this method is not equivalent to the lastrowid method on ResultProxy, which is a direct proxy to the DBAPI lastrowid accessor in all cases.

set_input_sizes(translate=None, exclude_types=None)
Given a cursor and ClauseParameters, call the appropriate style of setinputsizes() on the cursor, using DB-API types from the bind parameter’s TypeEngine objects.
class sqlalchemy.engine.base.ExecutionContext

A messenger object for a Dialect that corresponds to a single execution.

ExecutionContext should have these data members:

connection
Connection object which can be freely used by default value generators to execute SQL. This Connection should reference the same underlying connection/transactional resources of root_connection.
root_connection
Connection object which is the source of this ExecutionContext. This Connection may have close_with_result=True set, in which case it can only be used once.
dialect
dialect which created this ExecutionContext.
cursor
DB-API cursor procured from the connection,
compiled
if passed to constructor, sqlalchemy.engine.base.Compiled object being executed,
statement
string version of the statement to be executed. Is either passed to the constructor, or must be created from the sql.Compiled object by the time pre_exec() has completed.
parameters
bind parameters passed to the execute() method. For compiled statements, this is a dictionary or list of dictionaries. For textual statements, it should be in a format suitable for the dialect’s paramstyle (i.e. dict or list of dicts for non positional, list or list of lists/tuples for positional).
isinsert
True if the statement is an INSERT.
isupdate
True if the statement is an UPDATE.
should_autocommit
True if the statement is a “committable” statement.
postfetch_cols
a list of Column objects for which a server-side default or inline SQL expression value was fired off. Applies to inserts and updates.
create_cursor()

Return a new cursor generated from this ExecutionContext’s connection.

Some dialects may wish to change the behavior of connection.cursor(), such as postgresql which may return a PG “server side” cursor.

get_rowcount()

Return the number of rows produced (by a SELECT query) or affected (by an INSERT/UPDATE/DELETE statement).

Note that this row count may not be properly implemented in some dialects; this is indicated by the supports_sane_rowcount and supports_sane_multi_rowcount dialect attributes.

handle_dbapi_exception(e)
Receive a DBAPI exception which occured upon execute, result fetch, etc.
last_inserted_params()

Return a dictionary of the full parameter dictionary for the last compiled INSERT statement.

Includes any ColumnDefaults or Sequences that were pre-executed.

last_updated_params()

Return a dictionary of the full parameter dictionary for the last compiled UPDATE statement.

Includes any ColumnDefaults that were pre-executed.

lastrow_has_defaults()
Return True if the last INSERT or UPDATE row contained inlined or database-side defaults.
post_exec()

Called after the execution of a compiled statement.

If a compiled statement was passed to this ExecutionContext, the last_insert_ids, last_inserted_params, etc. datamembers should be available after this method completes.

pre_exec()

Called before an execution of a compiled statement.

If a compiled statement was passed to this ExecutionContext, the statement and parameters datamembers must be initialized after this statement is complete.

result()

Return a result object corresponding to this ExecutionContext.

Returns a ResultProxy.

should_autocommit_text(statement)
Parse the given textual statement and return True if it refers to a “committable” statement
Previous: sqlalchemy Next: Connection Pooling