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
dialect –
Dialect
to compile against.statement –
ClauseElement
to be compiled.bind – Optional Engine or Connection to compile thisstatement against.
dictionary of schema names to betranslated when forming the resultant SQL
New in version 1.1.
See also
-
compile_kwargs – additional kwargs that will bepassed to the initial call to Compiled.process()
.
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.
Execute this compiled object.
Execution options propagated from the statement. In some cases,sub-elements of the statement can modify these.
Return the bind params for this compiled object.
Execute this compiled object and return the result’sscalar value.
- 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
inherited from the eq()
method of object
Return self==value.
inherited from the init()
method of Compiled
Construct a new Compiled
object.
- Parameters
-
-
dialect – Dialect
to compile against.
-
statement – ClauseElement
to be compiled.
-
bind – Optional Engine or Connection to compile thisstatement against.
-
dictionary of schema names to betranslated when forming the resultant SQL
New in version 1.1.
See also
-
compile_kwargs – additional kwargs that will bepassed to the initial call to Compiled.process()
.
inherited from the le()
method of object
Return self<=value.
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
inherited from the eq()
method of object
Return self==value.
inherited from the le()
method of object
Return self<=value.
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
str
types.encoding
type of encoding to use for unicode, usually defaults to‘utf-8’.
statement_compiler
a
Compiled
class used to compile SQL statementsddl_compiler
a
Compiled
class used to compile DDL statementsserver_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 executionexecute_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 supportsALTER 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 for
UPDATE
andDELETE
statements.supports_sane_multi_rowcount
Indicate whether the dialect properly implements rowcount for
UPDATE
andDELETE
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 supportedsupports_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.
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.
Given a URL
object, returns a tupleconsisting of a *args/**kwargs suitable to send directlyto the dbapi’s connect function.
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.
- Parameters
-
dbapi_connection – a DBAPI connection, typicallyproxied within a ConnectionFairy
.
dobegin_twophase
(_connection, xid)Begin a two phase transaction on the given connection.
- Parameters
connection – a
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.docommit_twophase
(_connection, xid, is_prepared=True, recover=False)Commit a two phase transaction on the given connection.
- Parameters
connection – a
Connection
.is_prepared – whether or not
TwoPhaseTransaction.prepare()
was called.
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)
.Prepare a two phase transaction on the given connection.
- Parameters
connection – a
Connection
.
Recover list of uncommitted prepared two phase transactionidentifiers on the given connection.
- Parameters
- connection – a
Connection
.
Release the named savepoint on a connection.
- Parameters
connection – a
Connection
.
Provide an implementation of
connection.rollback()
, givena DB-API connection.Rollback a connection to the named savepoint.
- Parameters
connection – a
Connection
.
dorollback_twophase
(_connection, xid, is_prepared=True, recover=False)Rollback a two phase transaction on the given connection.
- Parameters
connection – a
Connection
.is_prepared – whether or not
TwoPhaseTransaction.prepare()
was called.
Create a savepoint with the given name.
- Parameters
connection – a
Connection
.
- 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:
- name
-
the check constraint’s name
- sqltext
-
the check constraint’s SQL expression
- **kw
-
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:
- 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, ‘minvalue’: int,
-
‘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:
- 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 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:
- name
-
the index’s name
- column_names
-
list of column names in order
- unique
-
boolean
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:
- constrained_columns
-
a list of column names that make up the primary key
- name
-
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:
- text
-
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.
Return a list of temporary table names on the given connection,if supported by the underlying backend.
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:
- name
-
the unique constraint’s name
- column_names
-
list of column names in order
- **kw
-
other options passed to the dialect’s get_unique_constraints()method.
New in version 0.9.0.
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.
- 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.
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
- 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.
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 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
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 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
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.
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.
- Parameters
-
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_parameters
attribute.
See also
DefaultExecutionContext.current_parameters
Context-Sensitive Default Functions
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.
Return True if the last INSERT or UPDATE row containedinlined or database-side defaults.
- 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.
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’sTypeEngine
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.
- 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()
See ResultProxy.rowcount
for details on this.
handledbapi_exception
(_e)Receive a DBAPI exception which occurred upon execute, resultfetch, etc.
- 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
ConnectionEvents.dbapi_error()
lastrow_has_defaults
()Return True if the last INSERT or UPDATE row containedinlined or database-side defaults.
- 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.
If a compiled statement was passed to this ExecutionContext,the statement and parameters datamembers must beinitialized after this statement is complete.
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
inherited from the eq()
method of object
Return self==value.
inherited from the le()
method of object
Return self<=value.
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.
Prepare a quoted schema name.
Prepare a quoted table and schema name.
Format table name and schema as a tuple.
- 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.
- Parameters
-
-
-
unused
Deprecated since version 0.9: The IdentifierPreparer.quote.force
parameter 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
.
Subclasses should override this to provide database-dependentquoting behavior.
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.
- Parameters
-
-
-
unused
Deprecated since version 0.9: The IdentifierPreparer.quote_schema.force
parameter 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.
- 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
dialect –
Dialect
to be usedstatement –
ClauseElement
to be compiledcolumn_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.
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
- True if we’ve encountered bindparam(…, expanding=True).
These need to be converted before execution time against thestring statement.
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.allow dialects to customize how GROUP BY is rendered.
- 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
= Falseclass-level defaults which can be set at the instancelevel to define if this Compiled instance representsINSERT/UPDATE/DELETE
allow dialects to customize how ORDER BY is rendered.
Return the bind param dictionary embedded into thiscompiled object, for those values that are present.
- 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)
holds the “returning” collection of columns ifthe statement is CRUD and defines returning columnseither implicitly or explicitly
set to True classwide to generate RETURNINGclauses before the VALUES or WHERE clause (i.e. MSSQL)
- 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.
- class
sqlalchemy.sql.compiler.
StrSQLCompiler
(dialect, statement, column_keys=None, inline=False, **kwargs) - Bases:
sqlalchemy.sql.compiler.SQLCompiler
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.