SQLAlchemy 2.0 Documentation
SQLAlchemy Core
- SQL Statements and Expressions API
- Column Elements and Expressions
- Operator Reference
- SELECT and Related Constructs
- Insert, Updates, Deletes
- SQL and Generic Functions
- Custom SQL Constructs and Compilation Extension
- Expression Serializer Extension
- SQL Expression Language Foundational Constructs¶
- Visitor and Traversal Utilities
- Schema Definition Language
- SQL Datatype Objects
- Engine and Connection Use
- Core API Basics
Project Versions
SQL Expression Language Foundational Constructs¶
Base classes and mixins that are used to compose SQL Expression Language elements.
| Object Name | Description |
|---|---|
Establish the ability for a class to have dialect-specific arguments with defaults and constructor validation. | |
Mixin for objects which can produce a cache key. | |
- class sqlalchemy.sql.expression.CacheKey¶
inherits from
builtins.tupleThe key used to identify a SQL statement construct in the SQL compilation cache.
See also
Member Name Description Alias for field number 1
Alias for field number 0
Generate an “offline string” form of this
CacheKey- attribute
sqlalchemy.sql.expression.CacheKey.bindparams: Sequence[BindParameter[Any]]¶ Alias for field number 1
- attribute
sqlalchemy.sql.expression.CacheKey.key: Tuple[Any, ...]¶ Alias for field number 0
- method
sqlalchemy.sql.expression.CacheKey.to_offline_string(statement_cache: MutableMapping[Any, str], statement: ClauseElement, parameters: _CoreSingleExecuteParams) → str¶ Generate an “offline string” form of this
CacheKeyThe “offline string” is basically the string SQL for the statement plus a repr of the bound parameter values in series. Whereas the
CacheKeyobject is dependent on in-memory identities in order to work as a cache key, the “offline” version is suitable for a cache that will work for other processes as well.The given
statement_cacheis a dictionary-like object where the string form of the statement itself will be cached. This dictionary should be in a longer lived scope in order to reduce the time spent stringifying statements.
- attribute
- class sqlalchemy.sql.expression.ClauseElement¶
inherits from
sqlalchemy.sql.annotation.SupportsWrappingAnnotations,sqlalchemy.sql.cache_key.MemoizedHasCacheKey,sqlalchemy.sql.traversals.HasCopyInternals,sqlalchemy.sql.visitors.ExternallyTraversible,sqlalchemy.sql.expression.CompilerElementBase class for elements of a programmatically constructed SQL expression.
Member Name Description compare()
Compare this
ClauseElementto the givenClauseElement.compile()
Compile this SQL expression.
Return immediate child
HasTraverseInternalselements of thisHasTraverseInternals.Indicate if this
HasCacheKeyinstance should make use of the cache key generation scheme used by its immediate superclass.params()
Return a copy with
bindparam()elements replaced.Apply a ‘grouping’ to this
ClauseElement.Return a copy with
bindparam()elements replaced.- method
sqlalchemy.sql.expression.ClauseElement.compare(other: ClauseElement, **kw: Any) → bool¶ Compare this
ClauseElementto the givenClauseElement.Subclasses should override the default behavior, which is a straight identity comparison.
**kw are arguments consumed by subclass
compare()methods and may be used to modify the criteria for comparison (seeColumnElement).
- method
sqlalchemy.sql.expression.ClauseElement.compile(bind: _HasDialect | None = None, dialect: Dialect | None = None, **kw: Any) → Compiled¶ inherited from the
CompilerElement.compile()method ofCompilerElementCompile this SQL expression.
The return value is a
Compiledobject. Callingstr()orunicode()on the returned value will yield a string representation of the result. TheCompiledobject also can return a dictionary of bind parameter names and values using theparamsaccessor.- Parameters:
bind¶ – An
ConnectionorEnginewhich can provide aDialectin order to generate aCompiledobject. If thebindanddialectparameters are both omitted, a default SQL compiler is used.column_keys¶ – Used for INSERT and UPDATE statements, a list of column names which should be present in the VALUES clause of the compiled statement. If
None, all columns from the target table object are rendered.dialect¶ – A
Dialectinstance which can generate aCompiledobject. This argument takes precedence over thebindargument.compile_kwargs¶ –
optional dictionary of additional parameters that will be passed through to the compiler within all “visit” methods. This allows any custom flag to be passed through to a custom compilation construct, for example. It is also used for the case of passing the
literal_bindsflag through:from sqlalchemy.sql import table, column, select t = table("t", column("x")) s = select(t).where(t.c.x == 5) print(s.compile(compile_kwargs={"literal_binds": True}))
- method
sqlalchemy.sql.expression.ClauseElement.get_children(*, omit_attrs: Tuple[str, ...] = (), **kw: Any) → Iterable[HasTraverseInternals]¶ inherited from the
HasTraverseInternals.get_children()method ofHasTraverseInternalsReturn immediate child
HasTraverseInternalselements of thisHasTraverseInternals.This is used for visit traversal.
**kw may contain flags that change the collection that is returned, for example to return a subset of items in order to cut down on larger traversals, or to return child items from a different context (such as schema-level collections instead of clause-level).
- attribute
sqlalchemy.sql.expression.ClauseElement.inherit_cache: bool | None = None¶ inherited from the
HasCacheKey.inherit_cacheattribute ofHasCacheKeyIndicate if this
HasCacheKeyinstance should make use of the cache key generation scheme used by its immediate superclass.The attribute defaults to
None, which indicates that a construct has not yet taken into account whether or not its appropriate for it to participate in caching; this is functionally equivalent to setting the value toFalse, except that a warning is also emitted.This flag can be set to
Trueon a particular class, if the SQL that corresponds to the object does not change based on attributes which are local to this class, and not its superclass.See also
Enabling Caching Support for Custom Constructs - General guideslines for setting the
HasCacheKey.inherit_cacheattribute for third-party or user defined SQL constructs.
- method
sqlalchemy.sql.expression.ClauseElement.params(_ClauseElement__optionaldict: Mapping[str, Any] | None = None, **kwargs: Any) → Self¶ Return a copy with
bindparam()elements replaced.Returns a copy of this ClauseElement with
bindparam()elements replaced with values taken from the given dictionary:>>> clause = column("x") + bindparam("foo") >>> print(clause.compile().params) {'foo':None} >>> print(clause.params({"foo": 7}).compile().params) {'foo':7}
- method
sqlalchemy.sql.expression.ClauseElement.self_group(against: OperatorType | None = None) → ClauseElement¶ Apply a ‘grouping’ to this
ClauseElement.This method is overridden by subclasses to return a “grouping” construct, i.e. parenthesis. In particular it’s used by “binary” expressions to provide a grouping around themselves when placed into a larger expression, as well as by
select()constructs when placed into the FROM clause of anotherselect(). (Note that subqueries should be normally created using theSelect.alias()method, as many platforms require nested SELECT statements to be named).As expressions are composed together, the application of
self_group()is automatic - end-user code should never need to use this method directly. Note that SQLAlchemy’s clause constructs take operator precedence into account - so parenthesis might not be needed, for example, in an expression likex OR (y AND z)- AND takes precedence over OR.The base
self_group()method ofClauseElementjust returns self.
- method
sqlalchemy.sql.expression.ClauseElement.unique_params(_ClauseElement__optionaldict: Dict[str, Any] | None = None, **kwargs: Any) → Self¶ Return a copy with
bindparam()elements replaced.Same functionality as
ClauseElement.params(), except adds unique=True to affected bind parameters so that multiple statements can be used.
- method
- class sqlalchemy.sql.base.DialectKWArgs¶
Establish the ability for a class to have dialect-specific arguments with defaults and constructor validation.
The
DialectKWArgsinteracts with theDefaultDialect.construct_argumentspresent on a dialect.See also
Member Name Description Add a new kind of dialect-specific keyword argument for this class.
A collection of keyword arguments specified as dialect-specific options to this construct.
A collection of keyword arguments specified as dialect-specific options to this construct.
A synonym for
DialectKWArgs.dialect_kwargs.- classmethod
sqlalchemy.sql.base.DialectKWArgs.argument_for(dialect_name: str, argument_name: str, default: Any) → None¶ Add a new kind of dialect-specific keyword argument for this class.
E.g.:
Index.argument_for("mydialect", "length", None) some_index = Index("a", "b", mydialect_length=5)
The
DialectKWArgs.argument_for()method is a per-argument way adding extra arguments to theDefaultDialect.construct_argumentsdictionary. This dictionary provides a list of argument names accepted by various schema-level constructs on behalf of a dialect.New dialects should typically specify this dictionary all at once as a data member of the dialect class. The use case for ad-hoc addition of argument names is typically for end-user code that is also using a custom compilation scheme which consumes the additional arguments.
- Parameters:
dialect_name¶ – name of a dialect. The dialect must be locatable, else a
NoSuchModuleErroris raised. The dialect must also include an existingDefaultDialect.construct_argumentscollection, indicating that it participates in the keyword-argument validation and default system, elseArgumentErroris raised. If the dialect does not include this collection, then any keyword argument can be specified on behalf of this dialect already. All dialects packaged within SQLAlchemy include this collection, however for third party dialects, support may vary.argument_name¶ – name of the parameter.
default¶ – default value of the parameter.
- attribute
sqlalchemy.sql.base.DialectKWArgs.dialect_kwargs¶ A collection of keyword arguments specified as dialect-specific options to this construct.
The arguments are present here in their original
<dialect>_<kwarg>format. Only arguments that were actually passed are included; unlike theDialectKWArgs.dialect_optionscollection, which contains all options known by this dialect including defaults.The collection is also writable; keys are accepted of the form
<dialect>_<kwarg>where the value will be assembled into the list of options.See also
DialectKWArgs.dialect_options- nested dictionary form
- attribute
sqlalchemy.sql.base.DialectKWArgs.dialect_options¶ A collection of keyword arguments specified as dialect-specific options to this construct.
This is a two-level nested registry, keyed to
<dialect_name>and<argument_name>. For example, thepostgresql_whereargument would be locatable as:arg = my_object.dialect_options["postgresql"]["where"]
Added in version 0.9.2.
See also
DialectKWArgs.dialect_kwargs- flat dictionary form
- attribute
sqlalchemy.sql.base.DialectKWArgs.kwargs¶ A synonym for
DialectKWArgs.dialect_kwargs.
- classmethod
- class sqlalchemy.sql.traversals.HasCacheKey¶
Mixin for objects which can produce a cache key.
This class is usually in a hierarchy that starts with the
HasTraverseInternalsbase, but this is optional. Currently, the class should be able to work on its own without includingHasTraverseInternals.Member Name Description Indicate if this
HasCacheKeyinstance should make use of the cache key generation scheme used by its immediate superclass.- attribute
sqlalchemy.sql.traversals.HasCacheKey.inherit_cache: bool | None = None¶ Indicate if this
HasCacheKeyinstance should make use of the cache key generation scheme used by its immediate superclass.The attribute defaults to
None, which indicates that a construct has not yet taken into account whether or not its appropriate for it to participate in caching; this is functionally equivalent to setting the value toFalse, except that a warning is also emitted.This flag can be set to
Trueon a particular class, if the SQL that corresponds to the object does not change based on attributes which are local to this class, and not its superclass.See also
Enabling Caching Support for Custom Constructs - General guideslines for setting the
HasCacheKey.inherit_cacheattribute for third-party or user defined SQL constructs.
- attribute
- class sqlalchemy.sql.expression.LambdaElement¶
inherits from
sqlalchemy.sql.expression.ClauseElementA SQL construct where the state is stored as an un-invoked lambda.
The
LambdaElementis produced transparently whenever passing lambda expressions into SQL constructs, such as:stmt = select(table).where(lambda: table.c.col == parameter)
The
LambdaElementis the base of theStatementLambdaElementwhich represents a full statement within a lambda.Added in version 1.4.
- class sqlalchemy.sql.expression.StatementLambdaElement¶
inherits from
sqlalchemy.sql.roles.AllowsLambdaRole,sqlalchemy.sql.lambdas.LambdaElement,sqlalchemy.sql.expression.ExecutableRepresent a composable SQL statement as a
LambdaElement.The
StatementLambdaElementis constructed using thelambda_stmt()function:from sqlalchemy import lambda_stmt stmt = lambda_stmt(lambda: select(table))
Once constructed, additional criteria can be built onto the statement by adding subsequent lambdas, which accept the existing statement object as a single parameter:
stmt += lambda s: s.where(table.c.col == parameter)
Added in version 1.4.
Member Name Description Add new criteria to this
StatementLambdaElement.spoil()
Return a new
StatementLambdaElementthat will run all lambdas unconditionally each time.- method
sqlalchemy.sql.expression.StatementLambdaElement.add_criteria(other: Callable[[Any], Any], enable_tracking: bool = True, track_on: Any | None = None, track_closure_variables: bool = True, track_bound_values: bool = True) → StatementLambdaElement¶ Add new criteria to this
StatementLambdaElement.E.g.:
>>> def my_stmt(parameter): ... stmt = lambda_stmt( ... lambda: select(table.c.x, table.c.y), ... ) ... stmt = stmt.add_criteria(lambda: table.c.x > parameter) ... return stmt
The
StatementLambdaElement.add_criteria()method is equivalent to using the Python addition operator to add a new lambda, except that additional arguments may be added includingtrack_closure_valuesandtrack_on:>>> def my_stmt(self, foo): ... stmt = lambda_stmt( ... lambda: select(func.max(foo.x, foo.y)), ... track_closure_variables=False, ... ) ... stmt = stmt.add_criteria(lambda: self.where_criteria, track_on=[self]) ... return stmt
See
lambda_stmt()for a description of the parameters accepted.
- attribute
sqlalchemy.sql.expression.StatementLambdaElement.is_delete: bool¶
- attribute
sqlalchemy.sql.expression.StatementLambdaElement.is_dml: bool¶
- attribute
sqlalchemy.sql.expression.StatementLambdaElement.is_insert: bool¶
- attribute
sqlalchemy.sql.expression.StatementLambdaElement.is_select: bool¶
- attribute
sqlalchemy.sql.expression.StatementLambdaElement.is_text: bool¶
- attribute
sqlalchemy.sql.expression.StatementLambdaElement.is_update: bool¶
- method
sqlalchemy.sql.expression.StatementLambdaElement.spoil() → NullLambdaStatement¶ Return a new
StatementLambdaElementthat will run all lambdas unconditionally each time.
- method
flambé! the dragon and The Alchemist image designs created and generously donated by Rotem Yaari.
Created using Sphinx 8.2.3. Documentation last generated: Tue 21 Oct 2025 06:01:18 PM EDT