Core Internals

Some key internal constructs are listed here.

  • class sqlalchemy.engine.interfaces.Compiled(dialect, statement, bind=None, schema_translate_map=None, compile_kwargs={})
  • Represent a compiled SQL or DDL expression.

The str method of the Compiled object should producethe actual text of the statement. Compiled objects arespecific to their underlying database dialect, and also mayor may not be specific to the columns referenced within aparticular set of bind parameters. In no case should theCompiled object be dependent on the actual values of thosebind parameters, even though it may reference those values asdefaults.

  • init(dialect, statement, bind=None, schema_translate_map=None, compile_kwargs={})
  • Construct a new Compiled object.

    • Parameters
      • dialectDialect to compile against.

      • statementClauseElement to be compiled.

      • bind – Optional Engine or Connection to compile thisstatement against.

      • schema_translate_map

dictionary of schema names to betranslated when forming the resultant SQL

New in version 1.1.

See also

Translation of Schema Names

  1. -

compile_kwargs – additional kwargs that will bepassed to the initial call to Compiled.process().

  • compile()
  • Produce the internal string representation of this element.

Deprecated since version 0.7: The Compiled.compile() method is deprecated and will be removed in a future release. The Compiled object now runs its compilation within the constructor, and this method does nothing.

  • constructparams(_params=None)
  • Return the bind params for this compiled object.

    • Parameters
    • params – a dict of string/object pairs whose values willoverride bind values compiled in to thestatement.
  • execute(*multiparams, **params)

  • Execute this compiled object.

  • executionoptions = {}_

  • Execution options propagated from the statement. In some cases,sub-elements of the statement can modify these.

  • property params

  • Return the bind params for this compiled object.

  • scalar(*multiparams, **params)

  • Execute this compiled object and return the result’sscalar value.

  • property sql_compiler

  • Return a Compiled that is capable of processing SQL expressions.

If this compiler is one, it would likely just return ‘self’.

  • class sqlalchemy.sql.compiler.DDLCompiler(dialect, statement, bind=None, schema_translate_map=None, compile_kwargs={})
  • Bases: sqlalchemy.sql.compiler.Compiled

    • eq()

inherited from the eq() method of object

Return self==value.

  • init(dialect, statement, bind=None, schema_translate_map=None, compile_kwargs={})

inherited from the init() method of Compiled

Construct a new Compiled object.

  1. - Parameters
  2. -
  3. -

dialectDialect to compile against.

  1. -

statementClauseElement to be compiled.

  1. -

bind – Optional Engine or Connection to compile thisstatement against.

  1. -

schema_translate_map

dictionary of schema names to betranslated when forming the resultant SQL

New in version 1.1.

See also

Translation of Schema Names

  1. -

compile_kwargs – additional kwargs that will bepassed to the initial call to Compiled.process().

  • le()

inherited from the le() method of object

Return self<=value.

  • lt()

inherited from the lt() method of object

Return self

  • class sqlalchemy.engine.default.DefaultDialect(convert_unicode=False, encoding='utf-8', paramstyle=None, dbapi=None, implicit_returning=None, supports_right_nested_joins=None, case_sensitive=True, supports_native_boolean=None, empty_in_strategy='static', max_identifier_length=None, label_length=None, **kwargs)
  • Bases: sqlalchemy.engine.interfaces.Dialect

Default implementation of Dialect

  • eq()

inherited from the eq() method of object

Return self==value.

  • le()

inherited from the le() method of object

Return self<=value.

  • lt()

inherited from the lt() method of object

Return self

  • class sqlalchemy.engine.interfaces.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 variesbetween databases is defined under the general category of theDialect. The Dialect acts as a factory for otherdatabase-specific object implementations includingExecutionContext, 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 multipleparamstyles).

  • convert_unicode

  • True if Unicode conversion should be applied to all strtypes.

  • 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 istypically populated during the initial connection to the database.

  • default_schema_name

  • the name of the default schema. This value is only available forsupporting dialects, and is typically populated during theinitial 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 toquote 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 Pythonunicode strings

  • supports_unicode_binds

  • Indicate whether the DB-API can receive string bind parametersas Python unicode strings

  • supports_sane_rowcount

  • Indicate whether the dialect properly implements rowcount forUPDATE and DELETE statements.

  • supports_sane_multi_rowcount

  • Indicate whether the dialect properly implements rowcount forUPDATE and DELETE statements when executed viaexecutemany.

  • preexecute_autoincrement_sequences

  • True if ‘implicit’ primary key functions must be executed separatelyin order to get their value. This is currently oriented towardsPostgreSQL.

  • implicit_returning

  • use RETURNING or equivalent during INSERT execution in order to loadnewly 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_keywill not be available.

  • colspecs

  • A dictionary of TypeEngine classes from sqlalchemy.types mappedto subclasses that are specific to the dialect class. Thisdictionary is class-level only and is not accessed from thedialect instance itself.

  • supports_default_values

  • Indicates if the construct INSERT INTO tablename DEFAULTVALUES 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() constructshould signal to not generate a CREATE SEQUENCE. Applies only todialects that support sequences. Currently used only to allow PostgreSQLSERIAL to be used on a column that specifies Sequence() for usage onother backends.

  • supports_native_enum

  • Indicates if the dialect supports a native ENUM construct.This will prevent types.Enum from generating a CHECKconstraint 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 CHECKconstraint when that type is used.

  • dbapi_exception_translation_map

  • A dictionary of names that will contain as values the names ofpep-249 exceptions (“IntegrityError”, “OperationalError”, etc)keyed to alternate class names, to support the case where aDBAPI has exception classes that aren’t named as they arereferred to (e.g. IntegrityError = MyException). In the vastmajority of cases this dictionary is empty.

New in version 1.0.5.

  • connect()
  • return a callable which sets up a newly created DBAPI connection.

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

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

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

If None is returned, no listener will be generated.

  • createconnect_args(_url)
  • Build DB-API compatible connection arguments.

Given a URL object, returns a tupleconsisting of a *args/**kwargs suitable to send directlyto 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 isunspecified.

  • denormalizename(_name)
  • convert the given name to a case insensitive identifierfor the backend if it is an all-lowercase name.

this method is only used if the dialect definesrequires_name_normalize=True.

  • dobegin(_dbapi_connection)
  • Provide an implementation of connection.begin(), given aDB-API connection.

The DBAPI has no dedicated “begin” method and it is expectedthat transactions are implicit. This hook is provided for thoseDBAPIs that might need additional help in this area.

Note that Dialect.do_begin() is not called unless aTransaction object is in use. TheDialect.do_autocommit()hook is provided for DBAPIs that need some extra commands emittedafter a commit in order to enter the next transaction, when theSQLAlchemy Connection is used in its default “autocommit”mode.

  1. - Parameters
  2. -

dbapi_connection – a DBAPI connection, typicallyproxied within a ConnectionFairy.

  • dobegin_twophase(_connection, xid)
  • Begin a two phase transaction on the given connection.

    • Parameters
  • doclose(_dbapi_connection)

  • Provide an implementation of connection.close(), given a DBAPIconnection.

This hook is called by the Pool when a connection has beendetached from the pool, or is being returned beyond the normalcapacity of the pool.

  • docommit(_dbapi_connection)
  • Provide an implementation of connection.commit(), given aDB-API connection.

    • Parameters
    • dbapi_connection – a DBAPI connection, typicallyproxied within a ConnectionFairy.
  • docommit_twophase(_connection, xid, is_prepared=True, recover=False)

  • Commit a two phase transaction on the given connection.

  • doexecute(_cursor, statement, parameters, context=None)

  • Provide an implementation of cursor.execute(statement,parameters).

  • doexecute_no_params(_cursor, statement, parameters, context=None)

  • Provide an implementation of cursor.execute(statement).

The parameter collection should not be sent.

  • doexecutemany(_cursor, statement, parameters, context=None)
  • Provide an implementation of cursor.executemany(statement,parameters).

  • doprepare_twophase(_connection, xid)

  • Prepare a two phase transaction on the given connection.

    • Parameters
  • dorecover_twophase(_connection)

  • Recover list of uncommitted prepared two phase transactionidentifiers on the given connection.

  • dorelease_savepoint(_connection, name)

  • Release the named savepoint on a connection.

    • Parameters
      • connection – a Connection.

      • name – savepoint name.

  • dorollback(_dbapi_connection)

  • Provide an implementation of connection.rollback(), givena DB-API connection.

    • Parameters
    • dbapi_connection – a DBAPI connection, typicallyproxied within a ConnectionFairy.
  • dorollback_to_savepoint(_connection, name)

  • Rollback a connection to the named savepoint.

    • Parameters
      • connection – a Connection.

      • name – savepoint name.

  • dorollback_twophase(_connection, xid, is_prepared=True, recover=False)

  • Rollback a two phase transaction on the given connection.

  • dosavepoint(_connection, name)

  • Create a savepoint with the given name.

    • Parameters
      • connection – a Connection.

      • name – savepoint name.

  • classmethod enginecreated(_engine)

  • A convenience hook called before returning the final Engine.

If the dialect returned a different class from theget_dialect_cls()method, then the hook is called on both classes, first onthe dialect class returned by the get_dialect_cls() method andthen on the class on which the method was called.

The hook should be used by dialects and/or wrappers to apply specialevents to the engine or its components. In particular, it allowsa dialect-wrapping class to apply dialect-level events.

New in version 1.0.3.

  • getcheck_constraints(_connection, table_name, schema=None, **kw)
  • Return information about check constraints in table_name.

Given a string table_name and an optional string schema, returncheck constraint information as a list of dicts with these keys:

  1. - name
  2. -

the check constraint’s name

  1. - sqltext
  2. -

the check constraint’s SQL expression

  1. - **kw
  2. -

other options passed to the dialect’s get_check_constraints()method.

New in version 1.1.0.

  • getcolumns(_connection, table_name, schema=None, **kw)
  • Return information about columns in table_name.

Given a Connection, a stringtable_name, and an optional string schema, return columninformation as a list of dictionaries with these keys:

  1. - name
  2. -

the column’s name

  1. - type
  2. -

[sqlalchemy.types#TypeEngine]

  1. - nullable
  2. -

boolean

  1. - default
  2. -

the column’s default value

  1. - autoincrement
  2. -

boolean

  1. - sequence
  2. -
  3. - a dictionary of the form
  4. -
  5. - {‘namestr, start :int, increment’: int, minvalue’: int,
  6. -

‘maxvalue’: int, ‘nominvalue’: bool, ‘nomaxvalue’: bool,‘cycle’: bool, ‘cache’: int, ‘order’: bool}

Additional column attributes may be present.

  • classmethod getdialect_cls(_url)
  • Given a URL, return the Dialect that will be used.

This is a hook that allows an external plugin to provide functionalityaround an existing dialect, by allowing the plugin to be loadedfrom the url based on an entrypoint, and then the plugin returnsthe actual dialect to be used.

By default this just returns the cls.

New in version 1.0.3.

  • getforeign_keys(_connection, table_name, schema=None, **kw)
  • Return information about foreignkeys in _table_name.

Given a Connection, a stringtable_name, and an optional string schema, return foreignkey information as a list of dicts with these keys:

  1. - name
  2. -

the constraint’s name

  1. - constrained_columns
  2. -

a list of column names that make up the foreign key

  1. - referred_schema
  2. -

the name of the referred schema

  1. - referred_table
  2. -

the name of the referred table

  1. - referred_columns
  2. -

a list of column names in the referred table that correspond toconstrained_columns

  • getindexes(_connection, table_name, schema=None, **kw)
  • Return information about indexes in table_name.

Given a Connection, a stringtable_name and an optional string schema, return indexinformation as a list of dictionaries with these keys:

  1. - name
  2. -

the index’s name

  1. - column_names
  2. -

list of column names in order

  1. - unique
  2. -

boolean

  • getisolation_level(_dbapi_conn)
  • Given a DBAPI connection, return its isolation level.

When working with a Connection object, the correspondingDBAPI connection may be procured using theConnection.connection accessor.

Note that this is a dialect-level method which is used as partof the implementation of the Connection andEngine isolation level facilities;these APIs should be preferred for most typical use cases.

See also

Connection.get_isolation_level() - view current level

Connection.default_isolation_level - view default level

Connection.execution_options.isolation_level -set per Connection isolation level

create_engine.isolation_level -set per Engine isolation level

  • getpk_constraint(_connection, table_name, schema=None, **kw)
  • Return information about the primary key constraint ontable_name`.

Given a Connection, a stringtable_name, and an optional string schema, return primarykey information as a dictionary with these keys:

  1. - constrained_columns
  2. -

a list of column names that make up the primary key

  1. - name
  2. -

optional name of the primary key constraint.

  • getprimary_keys(_connection, table_name, schema=None, **kw)
  • Return information about primary keys in table_name.

Deprecated since version 0.8: The Dialect.get_primary_keys() method is deprecated and will be removed in a future release. Please refer to the Dialect.get_pk_constraint() method.

  • gettable_comment(_connection, table_name, schema=None, **kw)
  • Return the “comment” for the table identified by table_name.

Given a string table_name and an optional string schema, returntable comment information as a dictionary with this key:

  1. - text
  2. -

text of the comment

Raises NotImplementedError for dialects that don’t supportcomments.

New in version 1.2.

  • gettable_names(_connection, schema=None, **kw)
  • Return a list of table names for schema.

  • gettemp_table_names(_connection, schema=None, **kw)

  • Return a list of temporary table names on the given connection,if supported by the underlying backend.

  • gettemp_view_names(_connection, schema=None, **kw)

  • Return a list of temporary view names on the given connection,if supported by the underlying backend.

  • getunique_constraints(_connection, table_name, schema=None, **kw)

  • Return information about unique constraints in table_name.

Given a string table_name and an optional string schema, returnunique constraint information as a list of dicts with these keys:

  1. - name
  2. -

the unique constraint’s name

  1. - column_names
  2. -

list of column names in order

  1. - **kw
  2. -

other options passed to the dialect’s get_unique_constraints()method.

New in version 0.9.0.

  • getview_definition(_connection, view_name, schema=None, **kw)
  • Return view definition.

Given a Connection, a stringview_name, and an optional string schema, return the viewdefinition.

  • getview_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.
  • hassequence(_connection, sequence_name, schema=None)

  • Check the existence of a particular sequence in the database.

Given a Connection object and a stringsequence_name, return True if the given sequence exists inthe database, False otherwise.

  • hastable(_connection, table_name, schema=None)
  • Check the existence of a particular table in the database.

Given a Connection object and a stringtable_name, return True if the given table (possibly withinthe specified schema) exists in the database, Falseotherwise.

  • initialize(connection)
  • Called during strategized creation of the dialect with aconnection.

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

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

The initialize() method of the base dialect should be called viasuper().

  • isdisconnect(_e, connection, cursor)
  • Return True if the given DB-API error indicates an invalidconnection

  • normalizename(_name)

  • convert the given name to lowercase if it is detected ascase insensitive.

this method is only used if the dialect definesrequires_name_normalize=True.

  • reflecttable(connection, table, include_columns, exclude_columns, resolve_fks)
  • Load table description from the database.

Given a Connection and aTable object, reflect its columns andproperties from the database.

The implementation of this method is provided byDefaultDialect.reflecttable(), which makes use ofInspector to retrieve column information.

Dialects should not seek to implement this method, and shouldinstead implement individual schema inspection operations such asDialect.get_columns(), Dialect.get_pk_constraint(),etc.

  • resetisolation_level(_dbapi_conn)
  • Given a DBAPI connection, revert its isolation to the default.

Note that this is a dialect-level method which is used as partof the implementation of the Connection andEngineisolation level facilities; these APIs should be preferred formost typical use cases.

See also

Connection.get_isolation_level() - view current level

Connection.default_isolation_level - view default level

Connection.execution_options.isolation_level -set per Connection isolation level

create_engine.isolation_level -set per Engine isolation level

  • setisolation_level(_dbapi_conn, level)
  • Given a DBAPI connection, set its isolation level.

Note that this is a dialect-level method which is used as partof the implementation of the Connection andEngineisolation level facilities; these APIs should be preferred formost typical use cases.

See also

Connection.get_isolation_level() - view current level

Connection.default_isolation_level - view default level

Connection.execution_options.isolation_level -set per Connection isolation level

create_engine.isolation_level -set per Engine isolation level

  • classmethod typedescriptor(_typeobj)
  • Transform a generic type to a dialect-specific type.

Dialect classes will usually use thetypes.adapt_type() function in the types module toaccomplish this.

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

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

  • currentparameters = None_
  • A dictionary of parameters applied to the current row.

This attribute is only available in the context of a user-defined defaultgeneration function, e.g. as described at Context-Sensitive Default Functions.It consists of a dictionary which includes entries for each column/valuepair that is to be part of the INSERT or UPDATE statement. The keys of thedictionary will be the key value of each Column, which is usuallysynonymous with the name.

Note that the DefaultExecutionContext.current_parameters attributedoes not accommodate for the “multi-values” feature of theInsert.values() method. TheDefaultExecutionContext.get_current_parameters() method should bepreferred.

See also

DefaultExecutionContext.get_current_parameters()

Context-Sensitive Default Functions

  • getcurrent_parameters(_isolate_multiinsert_groups=True)
  • Return a dictionary of parameters applied to the current row.

This method can only be used in the context of a user-defined defaultgeneration function, e.g. as described atContext-Sensitive Default Functions. When invoked, a dictionary isreturned which includes entries for each column/value pair that is partof the INSERT or UPDATE statement. The keys of the dictionary will bethe key value of each Column, which is usually synonymouswith the name.

  1. - Parameters
  2. -

isolate_multiinsert_groups=True – indicates that multi-valuedINSERT constructs created using Insert.values() should behandled by returning only the subset of parameters that are localto the current column default invocation. When False, theraw parameters of the statement are returned including thenaming convention used in the case of multi-valued INSERT.

New in version 1.2: addedDefaultExecutionContext.get_current_parameters()which provides more functionality over the existingDefaultExecutionContext.current_parametersattribute.

See also

DefaultExecutionContext.current_parameters

Context-Sensitive Default Functions

  • 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 wascalculated within post_exec().

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

The function is called once, directly afterpostexec() and before the transaction is committedor ResultProxy is generated. If the post_exec()method assigns a value to _self._lastrowid, thevalue is used in place of calling get_lastrowid().

Note that this method is not equivalent to thelastrowid method on ResultProxy, which is adirect proxy to the DBAPI lastrowid accessorin all cases.

  • getresultprocessor(type, _colname, coltype)
  • Return a ‘result processor’ for a given type as present incursor.description.

This has a default implementation that dialects can overridefor context-sensitive result type handling.

  • handledbapi_exception(_e)
  • Receive a DBAPI exception which occurred upon execute, resultfetch, etc.

  • lastrow_has_defaults()

  • Return True if the last INSERT or UPDATE row containedinlined 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 beinitialized after this statement is complete.

  • setinput_sizes(_translate=None, include_types=None, exclude_types=None)
  • Given a cursor and ClauseParameters, call the appropriatestyle of setinputsizes() on the cursor, using DB-API typesfrom the bind parameter’s TypeEngine objects.

This method only called by those dialects which require it,currently cx_oracle.

  • shouldautocommit_text(_statement)
  • Parse the given textual statement and return True if it refers toa “committable” statement
  • class sqlalchemy.engine.interfaces.ExecutionContext
  • A messenger object for a Dialect that corresponds to a singleexecution.

ExecutionContext should have these data members:

  • connection
  • Connection object which can be freely used by default valuegenerators to execute SQL. This Connection should reference thesame underlying connection/transactional resources ofroot_connection.

  • root_connection

  • Connection object which is the source of this ExecutionContext. ThisConnection may have close_with_result=True set, in which case it canonly 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 objectbeing executed,

  • statement

  • string version of the statement to be executed. Is eitherpassed to the constructor, or must be created from thesql.Compiled object by the time pre_exec() has completed.

  • parameters

  • bind parameters passed to the execute() method. For compiledstatements, this is a dictionary or list of dictionaries. Fortextual statements, it should be in a format suitable for thedialect’s paramstyle (i.e. dict or list of dicts for nonpositional, 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.

  • prefetch_cols

  • a list of Column objects for which a client-side defaultwas fired off. Applies to inserts and updates.

  • postfetch_cols

  • a list of Column objects for which a server-side default orinline SQL expression value was fired off. Applies to insertsand updates.

  • create_cursor()

  • Return a new cursor generated from this ExecutionContext’sconnection.

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

  • exception = None
  • A DBAPI-level exception that was caught when this ExecutionContextattempted to execute a statement.

This attribute is meaningful only within theConnectionEvents.dbapi_error() event.

New in version 0.9.7.

See also

ExecutionContext.is_disconnect

ConnectionEvents.dbapi_error()

  • get_rowcount()
  • Return the DBAPI cursor.rowcount value, or in somecases an interpreted value.

See ResultProxy.rowcount for details on this.

  • handledbapi_exception(_e)
  • Receive a DBAPI exception which occurred upon execute, resultfetch, etc.

  • isdisconnect = None_

  • Boolean flag set to True or False when a DBAPI-level exceptionis caught when this ExecutionContext attempted to execute a statement.

This attribute is meaningful only within theConnectionEvents.dbapi_error() event.

New in version 0.9.7.

See also

ExecutionContext.exception

ConnectionEvents.dbapi_error()

  • lastrow_has_defaults()
  • Return True if the last INSERT or UPDATE row containedinlined 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 beinitialized after this statement is complete.

  • result()
  • Return a result object corresponding to this ExecutionContext.

Returns a ResultProxy.

  • shouldautocommit_text(_statement)
  • Parse the given textual statement and return True if it refers toa “committable” statement
  • class sqlalchemy.sql.compiler.GenericTypeCompiler(dialect)
  • Bases: sqlalchemy.sql.compiler.TypeCompiler

    • eq()

inherited from the eq() method of object

Return self==value.

  • le()

inherited from the le() method of object

Return self<=value.

  • lt()

inherited from the lt() method of object

Return self

  • class sqlalchemy.log.Identified
  • class sqlalchemy.sql.compiler.IdentifierPreparer(dialect, initial_quote='"', final_quote=None, escape_quote='"', quote_case_sensitive_collations=True, omit_schema=False)
  • Handle quoting and case-folding of identifiers based on options.

    • init(dialect, initial_quote='"', final_quote=None, escape_quote='"', quote_case_sensitive_collations=True, omit_schema=False)
    • Construct a new IdentifierPreparer object.

      • initial_quote
      • Character that begins a delimited identifier.

      • final_quote

      • Character that ends a delimited identifier. Defaults toinitial_quote.

      • omit_schema

      • Prevent prepending schema name. Useful for databases that donot support schemae.
    • formatcolumn(_column, use_table=False, name=None, table_name=None, use_schema=False)

    • Prepare a quoted column name.

    • formatschema(_name)

    • Prepare a quoted schema name.

    • formattable(_table, use_schema=True, name=None)

    • Prepare a quoted table and schema name.

    • formattable_seq(_table, use_schema=True)

    • Format table name and schema as a tuple.

    • quote(ident, force=None)

    • Conditionally quote an identfier.

The identifier is quoted if it is a reserved word, containsquote-necessary characters, or is an instance ofquoted_name which includes quote set to True.

Subclasses can override this to provide database-dependentquoting behavior for identifier names.

  1. - Parameters
  2. -
  3. -

ident – string identifier

  1. -

force

unused

Deprecated since version 0.9: The IdentifierPreparer.quote.forceparameter is deprecated and will be removed in a futurerelease. This flag has no effect on the behavior of theIdentifierPreparer.quote() method; please refer toquoted_name.

  • quoteidentifier(_value)
  • Quote an identifier.

Subclasses should override this to provide database-dependentquoting behavior.

  • quoteschema(_schema, force=None)
  • Conditionally quote a schema name.

The name is quoted if it is a reserved word, contains quote-necessarycharacters, or is an instance of quoted_name which includesquote set to True.

Subclasses can override this to provide database-dependentquoting behavior for schema names.

  1. - Parameters
  2. -
  3. -

schema – string schema name

  1. -

force

unused

Deprecated since version 0.9: The IdentifierPreparer.quote_schema.forceparameter is deprecated and will be removed in a futurerelease. This flag has no effect on the behavior of theIdentifierPreparer.quote() method; please refer toquoted_name.

  • unformatidentifiers(_identifiers)
  • Unpack ‘schema.table.column’-like strings into components.

  • validatesql_phrase(_element, reg)

  • keyword sequence filter.

a filter for elements that are intended to represent keyword sequences,such as “INITIALLY”, “INITIALLY DEFERRED”, etc. no special charactersshould be present.

New in version 1.3.

  • class sqlalchemy.sql.compiler.SQLCompiler(dialect, statement, column_keys=None, inline=False, **kwargs)
  • Bases: sqlalchemy.sql.compiler.Compiled

Default implementation of Compiled.

Compiles ClauseElement objects into SQL strings.

  • init(dialect, statement, column_keys=None, inline=False, **kwargs)
  • Construct a new SQLCompiler object.

    • Parameters
      • dialectDialect to be used

      • statementClauseElement to be compiled

      • column_keys – a list of column names to be compiled into anINSERT or UPDATE statement.

      • inline – whether to generate INSERT statements as “inline”, e.g.not formatted to return any generated defaults

      • kwargs – additional keyword arguments to be consumed by thesuperclass.

  • ansibind_rules = False_

  • SQL 92 doesn’t allow bind parameters to be usedin the columns clause of a SELECT, nor does it allowambiguous expressions like “? = ?”. A compilersubclass can set this flag to False if the targetdriver/DB enforces this

  • constructparams(_params=None, groupnumber=None, check=True_)

  • return a dictionary of bind parameter keys and values

  • containsexpanding_parameters = False_

  • True if we’ve encountered bindparam(…, expanding=True).

These need to be converted before execution time against thestring statement.

  • default_from()
  • Called when a SELECT statement has no froms, and no FROM clause isto be appended.

Gives Oracle a chance to tack on a FROM DUAL to the string output.

  • deleteextra_from_clause(_update_stmt, from_table, extra_froms, from_hints, **kw)
  • Provide a hook to override the generation of anDELETE..FROM clause.

This can be used to implement DELETE..USING for example.

MySQL and MSSQL override this.

  • getselect_precolumns(_select, **kw)
  • Called when building a SELECT statement, position is justbefore column list.

  • groupby_clause(_select, **kw)

  • allow dialects to customize how GROUP BY is rendered.

  • insertsingle_values_expr = None_

  • When an INSERT is compiled with a single set of parameters insidea VALUES expression, the string is assigned here, where it can beused for insert batching schemes to rewrite the VALUES expression.

New in version 1.3.8.

  • isdelete = False
  • class-level defaults which can be set at the instancelevel to define if this Compiled instance representsINSERT/UPDATE/DELETE

  • orderby_clause(_select, **kw)

  • allow dialects to customize how ORDER BY is rendered.

  • property params

  • Return the bind param dictionary embedded into thiscompiled object, for those values that are present.

  • renderliteral_value(_value, type_)

  • Render the value of a bind parameter as a quoted literal.

This is used for statement sections that do not accept bind parameterson the target driver/database.

This should be implemented by subclasses using the quoting servicesof the DBAPI.

  • rendertable_with_column_in_update_from = False_
  • set to True classwide to indicate the SET clausein a multi-table UPDATE statement should qualifycolumns with the table name (i.e. MySQL only)

  • returning = None

  • holds the “returning” collection of columns ifthe statement is CRUD and defines returning columnseither implicitly or explicitly

  • returningprecedes_values = False_

  • set to True classwide to generate RETURNINGclauses before the VALUES or WHERE clause (i.e. MSSQL)

  • property sql_compiler

  • Return a Compiled that is capable of processing SQL expressions.

If this compiler is one, it would likely just return ‘self’.

  • updatefrom_clause(_update_stmt, from_table, extra_froms, from_hints, **kw)
  • Provide a hook to override the generation of anUPDATE..FROM clause.

MySQL and MSSQL override this.

  • updatelimit_clause(_update_stmt)
  • Provide a hook for MySQL to add LIMIT to the UPDATE

  • updatetables_clause(_update_stmt, from_table, extra_froms, **kw)

  • Provide a hook to override the initial table clausein an UPDATE statement.

MySQL overrides this.

A SQLCompiler subclass which allows a small selectionof non-standard SQL features to render into a string value.

The StrSQLCompiler is invoked whenever a Core expressionelement is directly stringified without calling upon theClauseElement.compile() method. It can render a limited setof non-standard SQL constructs to assist in basic stringification,however for more substantial custom or dialect-specific SQL constructs,it will be necessary to make use of ClauseElement.compile()directly.

See also

How do I render SQL expressions as strings, possibly with bound parameters inlined?

  • deleteextra_from_clause(_update_stmt, from_table, extra_froms, from_hints, **kw)
  • Provide a hook to override the generation of anDELETE..FROM clause.

This can be used to implement DELETE..USING for example.

MySQL and MSSQL override this.

  • updatefrom_clause(_update_stmt, from_table, extra_froms, from_hints, **kw)
  • Provide a hook to override the generation of anUPDATE..FROM clause.

MySQL and MSSQL override this.