SQL Expression Language Foundational Constructs

    class sqlalchemy.sql.expression.CacheKey

    The key used to identify a SQL statement construct in the SQL compilation cache.

    See also

    SQL Compilation Caching

    Members

    , key,

    Class signature

    class sqlalchemy.sql.expression.CacheKey ()

    • attribute bindparams: Sequence[[Any]]

      Alias for field number 1

    • attribute sqlalchemy.sql.expression.CacheKey.key: [Any, …]

      Alias for field number 0

    • method sqlalchemy.sql.expression.CacheKey.to_offline_string(statement_cache: MutableMapping[Any, str], statement: , parameters: _CoreSingleExecuteParams) → str

      Generate an “offline string” form of this CacheKey

      The “offline string” is basically the string SQL for the statement plus a repr of the bound parameter values in series. Whereas the object 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_cache is 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.

    class sqlalchemy.sql.expression.ClauseElement

    Base class for elements of a programmatically constructed SQL expression.

    Members

    compare(), , get_children(), , params(), , unique_params()

    Class signature

    class (sqlalchemy.sql.annotation.SupportsWrappingAnnotations, sqlalchemy.sql.cache_key.MemoizedHasCacheKey, sqlalchemy.sql.traversals.HasCopyInternals, sqlalchemy.sql.visitors.ExternallyTraversible, sqlalchemy.sql.expression.CompilerElement)

    • method sqlalchemy.sql.expression.ClauseElement.compare(other: , **kw: Any) → bool

      Compare this ClauseElement to the given .

      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 (see ColumnElement).

    • method compile(bind: Optional[Union[Engine, ]] = None, dialect: Optional[Dialect] = None, **kw: Any) →

      inherited from the CompilerElement.compile() method of CompilerElement

      Compile this SQL expression.

      The return value is a Compiled object. Calling str() or unicode() on the returned value will yield a string representation of the result. The object also can return a dictionary of bind parameter names and values using the params accessor.

      • Parameters:

        • bind – An Connection or which can provide a Dialect in order to generate a object. If the bind and dialect parameters 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 Dialect instance which can generate a object. This argument takes precedence over the bind argument.

        • 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_binds flag through:

          New in version 0.9.0.

    1. See also
    2. [How do I render SQL expressions as strings, possibly with bound parameters inlined?]($e9fd44a49fe37bbb.md#faq-sql-expression-string)
    • inherited from the method of HasTraverseInternals

      Return immediate child HasTraverseInternals elements of this HasTraverseInternals.

      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: Optional[bool] = None

      inherited from the HasCacheKey.inherit_cache attribute of

      Indicate if this HasCacheKey instance 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 to False, except that a warning is also emitted.

      This flag can be set to True on 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

      - General guideslines for setting the HasCacheKey.inherit_cache attribute for third-party or user defined SQL constructs.

    • method params(_ClauseElement\_optionaldict: Optional[Mapping[str, Any]] = None, **kwargs: Any_) → SelfClauseElement

      Return a copy with bindparam() elements replaced.

      Returns a copy of this ClauseElement with elements replaced with values taken from the given dictionary:

      1. >>> clause = column('x') + bindparam('foo')
      2. >>> print(clause.compile().params)
      3. >>> print(clause.params({'foo':7}).compile().params)
      4. {'foo':7}
    • method sqlalchemy.sql.expression.ClauseElement.self_group(against: Optional[OperatorType] = None) →

      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 constructs when placed into the FROM clause of another select(). (Note that subqueries should be normally created using the 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 like x OR (y AND z) - AND takes precedence over OR.

      The base method of ClauseElement just returns self.

    • method unique_params(_ClauseElement\_optionaldict: Optional[Dict[str, Any]] = None, **kwargs: Any_) → SelfClauseElement

      Return a copy with bindparam() elements replaced.

      Same functionality as , except adds unique=True to affected bind parameters so that multiple statements can be used.

    class sqlalchemy.sql.base.DialectKWArgs

    Establish the ability for a class to have dialect-specific arguments with defaults and constructor validation.

    The DialectKWArgs interacts with the present on a dialect.

    Members

    argument_for(), , dialect_options,

    See also

    DefaultDialect.construct_arguments

    • classmethod argument_for(dialect_name, argument_name, default)

      Add a new kind of dialect-specific keyword argument for this class.

      E.g.:

      The DialectKWArgs.argument_for() method is a per-argument way adding extra arguments to the dictionary. 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 NoSuchModuleError is raised. The dialect must also include an existing collection, indicating that it participates in the keyword-argument validation and default system, else ArgumentError is 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.

    1. New in version 0.9.4.
    • attribute 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 the DialectKWArgs.dialect_options collection, 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.

      New in version 0.9.2.

      Changed in version 0.9.4: The collection is now writable.

      See also

      DialectKWArgs.dialect_options - nested dictionary form

    • attribute 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, the postgresql_where argument would be locatable as:

      1. arg = my_object.dialect_options['postgresql']['where']

      See also

      DialectKWArgs.dialect_kwargs - flat dictionary form

    • attribute kwargs

      A synonym for DialectKWArgs.dialect_kwargs.

    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 base, but this is optional. Currently, the class should be able to work on its own without including HasTraverseInternals.

    Members

    See also

    CacheKey

    • attribute sqlalchemy.sql.traversals.HasCacheKey.inherit_cache: Optional[bool] = None

      Indicate if this instance 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 to False, except that a warning is also emitted.

      This flag can be set to True on 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 attribute for third-party or user defined SQL constructs.

    class sqlalchemy.sql.expression.LambdaElement

    A SQL construct where the state is stored as an un-invoked lambda.

    The LambdaElement is produced transparently whenever passing lambda expressions into SQL constructs, such as:

    The is the base of the StatementLambdaElement which represents a full statement within a lambda.

    New in version 1.4.

    See also

    Class signature

    class sqlalchemy.sql.expression.LambdaElement ()

    class sqlalchemy.sql.expression.StatementLambdaElement

    Represent a composable SQL statement as a LambdaElement.

    The is constructed using the lambda_stmt() function:

    1. from sqlalchemy import lambda_stmt
    2. 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:

      New in version 1.4.

      See also

      Members

      add_criteria(), , is_dml, , is_select, , is_update,

      Class signature

      class sqlalchemy.sql.expression.StatementLambdaElement (sqlalchemy.sql.roles.AllowsLambdaRole, , sqlalchemy.sql.expression.Executable)