index
int64
0
731k
package
stringlengths
2
98
name
stringlengths
1
76
docstring
stringlengths
0
281k
code
stringlengths
4
1.07M
signature
stringlengths
2
42.8k
16,035
sqlalchemy.sql.elements
_dedupe_anon_label_idx
label to apply to a column that is anon labeled, but repeated in the SELECT, so that we have to make an "extra anon" label that disambiguates it from the previous appearance. these labels come out like "foo_bar_id__1" and have double underscores in them.
def _dedupe_anon_label_idx(self, idx: int) -> str: """label to apply to a column that is anon labeled, but repeated in the SELECT, so that we have to make an "extra anon" label that disambiguates it from the previous appearance. these labels come out like "foo_bar_id__1" and have double underscores in them. """ label = getattr(self, "name", None) # current convention is that if the element doesn't have a # ".name" (usually because it is not NamedColumn), we try to # use a "table qualified" form for the "dedupe anon" label, # based on the notion that a label like # "CAST(casttest.v1 AS DECIMAL) AS casttest_v1__1" looks better than # "CAST(casttest.v1 AS DECIMAL) AS anon__1" if label is None: return self._dedupe_anon_tq_label_idx(idx) else: return self._anon_label(label, add_hash=idx)
(self, idx: int) -> str
16,036
sqlalchemy.sql.elements
_dedupe_anon_tq_label_idx
null
def _dedupe_anon_tq_label_idx(self, idx: int) -> _anonymous_label: label = getattr(self, "_tq_label", None) or "anon" return self._anon_label(label, add_hash=idx)
(self, idx: int) -> sqlalchemy.sql.elements._anonymous_label
16,037
sqlalchemy.sql.functions
_execute_on_connection
null
def _execute_on_connection( self, connection: Connection, distilled_params: _CoreMultiExecuteParams, execution_options: CoreExecuteOptionsParameter, ) -> CursorResult[Any]: return connection._execute_function( self, distilled_params, execution_options )
(self, connection: 'Connection', distilled_params: '_CoreMultiExecuteParams', execution_options: 'CoreExecuteOptionsParameter') -> 'CursorResult[Any]'
16,038
sqlalchemy.sql.elements
_execute_on_scalar
an additional hook for subclasses to provide a different implementation for connection.scalar() vs. connection.execute(). .. versionadded:: 2.0
def _execute_on_scalar( self, connection: Connection, distilled_params: _CoreMultiExecuteParams, execution_options: CoreExecuteOptionsParameter, ) -> Any: """an additional hook for subclasses to provide a different implementation for connection.scalar() vs. connection.execute(). .. versionadded:: 2.0 """ return self._execute_on_connection( connection, distilled_params, execution_options ).scalar()
(self, connection: 'Connection', distilled_params: '_CoreMultiExecuteParams', execution_options: 'CoreExecuteOptionsParameter') -> 'Any'
16,039
sqlalchemy.sql.annotation
_gen_annotations_cache_key
null
def _gen_annotations_cache_key( self, anon_map: anon_map ) -> Tuple[Any, ...]: return ( "_annotations", tuple( ( key, ( value._gen_cache_key(anon_map, []) if isinstance(value, HasCacheKey) else value ), ) for key, value in [ (key, self._annotations[key]) for key in sorted(self._annotations) ] ), )
(self, anon_map: sqlalchemy.cyextension.util.cache_anon_map) -> Tuple[Any, ...]
16,040
sqlalchemy.sql.cache_key
_gen_cache_key
return an optional cache key. The cache key is a tuple which can contain any series of objects that are hashable and also identifies this object uniquely within the presence of a larger SQL expression or statement, for the purposes of caching the resulting query. The cache key should be based on the SQL compiled structure that would ultimately be produced. That is, two structures that are composed in exactly the same way should produce the same cache key; any difference in the structures that would affect the SQL string or the type handlers should result in a different cache key. If a structure cannot produce a useful cache key, the NO_CACHE symbol should be added to the anon_map and the method should return None.
@util.preload_module("sqlalchemy.sql.elements") def _gen_cache_key( self, anon_map: anon_map, bindparams: List[BindParameter[Any]] ) -> Optional[Tuple[Any, ...]]: """return an optional cache key. The cache key is a tuple which can contain any series of objects that are hashable and also identifies this object uniquely within the presence of a larger SQL expression or statement, for the purposes of caching the resulting query. The cache key should be based on the SQL compiled structure that would ultimately be produced. That is, two structures that are composed in exactly the same way should produce the same cache key; any difference in the structures that would affect the SQL string or the type handlers should result in a different cache key. If a structure cannot produce a useful cache key, the NO_CACHE symbol should be added to the anon_map and the method should return None. """ cls = self.__class__ id_, found = anon_map.get_anon(self) if found: return (id_, cls) dispatcher: Union[ Literal[CacheConst.NO_CACHE], _CacheKeyTraversalDispatchType, ] try: dispatcher = cls.__dict__["_generated_cache_key_traversal"] except KeyError: # traversals.py -> _preconfigure_traversals() # may be used to run these ahead of time, but # is not enabled right now. # this block will generate any remaining dispatchers. dispatcher = cls._generate_cache_attrs() if dispatcher is NO_CACHE: anon_map[NO_CACHE] = True return None result: Tuple[Any, ...] = (id_, cls) # inline of _cache_key_traversal_visitor.run_generated_dispatch() for attrname, obj, meth in dispatcher( self, _cache_key_traversal_visitor ): if obj is not None: # TODO: see if C code can help here as Python lacks an # efficient switch construct if meth is STATIC_CACHE_KEY: sck = obj._static_cache_key if sck is NO_CACHE: anon_map[NO_CACHE] = True return None result += (attrname, sck) elif meth is ANON_NAME: elements = util.preloaded.sql_elements if isinstance(obj, elements._anonymous_label): obj = obj.apply_map(anon_map) # type: ignore result += (attrname, obj) elif meth is CALL_GEN_CACHE_KEY: result += ( attrname, obj._gen_cache_key(anon_map, bindparams), ) # remaining cache functions are against # Python tuples, dicts, lists, etc. so we can skip # if they are empty elif obj: if meth is CACHE_IN_PLACE: result += (attrname, obj) elif meth is PROPAGATE_ATTRS: result += ( attrname, obj["compile_state_plugin"], ( obj["plugin_subject"]._gen_cache_key( anon_map, bindparams ) if obj["plugin_subject"] else None ), ) elif meth is InternalTraversal.dp_annotations_key: # obj is here is the _annotations dict. Table uses # a memoized version of it. however in other cases, # we generate it given anon_map as we may be from a # Join, Aliased, etc. # see #8790 if self._gen_static_annotations_cache_key: # type: ignore # noqa: E501 result += self._annotations_cache_key # type: ignore # noqa: E501 else: result += self._gen_annotations_cache_key(anon_map) # type: ignore # noqa: E501 elif ( meth is InternalTraversal.dp_clauseelement_list or meth is InternalTraversal.dp_clauseelement_tuple or meth is InternalTraversal.dp_memoized_select_entities ): result += ( attrname, tuple( [ elem._gen_cache_key(anon_map, bindparams) for elem in obj ] ), ) else: result += meth( # type: ignore attrname, obj, self, anon_map, bindparams ) return result
(self, anon_map: 'anon_map', bindparams: 'List[BindParameter[Any]]') -> 'Optional[Tuple[Any, ...]]'
16,041
sqlalchemy.sql.base
_generate
null
def _generate(self) -> Self: skip = self._memoized_keys cls = self.__class__ s = cls.__new__(cls) if skip: # ensure this iteration remains atomic s.__dict__ = { k: v for k, v in self.__dict__.copy().items() if k not in skip } else: s.__dict__ = self.__dict__.copy() return s
(self) -> typing_extensions.Self
16,043
sqlalchemy.sql.selectable
_generate_fromclause_column_proxies
null
def _generate_fromclause_column_proxies( self, fromclause: FromClause ) -> None: fromclause._columns._populate_separate_keys( col._make_proxy(fromclause) for col in self.c )
(self, fromclause: sqlalchemy.sql.selectable.FromClause) -> NoneType
16,044
sqlalchemy.sql.elements
_get_embedded_bindparams
Return the list of :class:`.BindParameter` objects embedded in the object. This accomplishes the same purpose as ``visitors.traverse()`` or similar would provide, however by making use of the cache key it takes advantage of memoization of the key to result in fewer net method calls, assuming the statement is also going to be executed.
def _get_embedded_bindparams(self) -> Sequence[BindParameter[Any]]: """Return the list of :class:`.BindParameter` objects embedded in the object. This accomplishes the same purpose as ``visitors.traverse()`` or similar would provide, however by making use of the cache key it takes advantage of memoization of the key to result in fewer net method calls, assuming the statement is also going to be executed. """ key = self._generate_cache_key() if key is None: bindparams: List[BindParameter[Any]] = [] traverse(self, {}, {"bindparam": bindparams.append}) return bindparams else: return key.bindparams
(self) -> Sequence[sqlalchemy.sql.elements.BindParameter[Any]]
16,045
sqlalchemy.sql.selectable
_init_collections
null
def _init_collections(self) -> None: assert "_columns" not in self.__dict__ assert "primary_key" not in self.__dict__ assert "foreign_keys" not in self.__dict__ self._columns = ColumnCollection() self.primary_key = ColumnSet() # type: ignore self.foreign_keys = set() # type: ignore
(self) -> NoneType
16,046
sqlalchemy.sql.selectable
_is_lexical_equivalent
Return ``True`` if this :class:`_expression.FromClause` and the other represent the same lexical identity. This tests if either one is a copy of the other, or if they are the same via annotation identity.
def _is_lexical_equivalent(self, other: FromClause) -> bool: """Return ``True`` if this :class:`_expression.FromClause` and the other represent the same lexical identity. This tests if either one is a copy of the other, or if they are the same via annotation identity. """ return bool(self._cloned_set.intersection(other._cloned_set))
(self, other: sqlalchemy.sql.selectable.FromClause) -> bool
16,047
sqlalchemy.sql.elements
_make_proxy
Create a new :class:`_expression.ColumnElement` representing this :class:`_expression.ColumnElement` as it appears in the select list of a descending selectable.
def _make_proxy( self, selectable: FromClause, *, name: Optional[str] = None, key: Optional[str] = None, name_is_truncatable: bool = False, compound_select_cols: Optional[Sequence[ColumnElement[Any]]] = None, **kw: Any, ) -> typing_Tuple[str, ColumnClause[_T]]: """Create a new :class:`_expression.ColumnElement` representing this :class:`_expression.ColumnElement` as it appears in the select list of a descending selectable. """ if name is None: name = self._anon_name_label if key is None: key = self._proxy_key else: key = name assert key is not None co: ColumnClause[_T] = ColumnClause( ( coercions.expect(roles.TruncatedLabelRole, name) if name_is_truncatable else name ), type_=getattr(self, "type", None), _selectable=selectable, ) co._propagate_attrs = selectable._propagate_attrs if compound_select_cols: co._proxies = list(compound_select_cols) else: co._proxies = [self] if selectable._is_clone_of is not None: co._is_clone_of = selectable._is_clone_of.columns.get(key) return key, co
(self, selectable: 'FromClause', *, name: 'Optional[str]' = None, key: 'Optional[str]' = None, name_is_truncatable: 'bool' = False, compound_select_cols: 'Optional[Sequence[ColumnElement[Any]]]' = None, **kw: 'Any') -> 'typing_Tuple[str, ColumnClause[_T]]'
16,048
sqlalchemy.sql.elements
_negate
null
def _negate(self) -> ColumnElement[Any]: if self.type._type_affinity is type_api.BOOLEANTYPE._type_affinity: return AsBoolean(self, operators.is_false, operators.is_true) else: grouped = self.self_group(against=operators.inv) assert isinstance(grouped, ColumnElement) return UnaryExpression( grouped, operator=operators.inv, wraps_column_expression=True )
(self) -> sqlalchemy.sql.elements.ColumnElement[typing.Any]
16,049
sqlalchemy.sql.elements
_negate_in_binary
a hook to allow the right side of a binary expression to respond to a negation of the binary expression. Used for the special case of expanding bind parameter with IN.
def _negate_in_binary(self, negated_op, original_op): """a hook to allow the right side of a binary expression to respond to a negation of the binary expression. Used for the special case of expanding bind parameter with IN. """ return self
(self, negated_op, original_op)
16,051
sqlalchemy.sql.selectable
_populate_column_collection
Called on subclasses to establish the .c collection. Each implementation has a different way of establishing this collection.
def _populate_column_collection(self) -> None: """Called on subclasses to establish the .c collection. Each implementation has a different way of establishing this collection. """
(self) -> NoneType
16,052
sqlalchemy.sql.operators
_rconcat
Implement an 'rconcat' operator. this is for internal use at the moment .. versionadded:: 1.4.40
def _rconcat(self, other: Any) -> ColumnOperators: """Implement an 'rconcat' operator. this is for internal use at the moment .. versionadded:: 1.4.40 """ return self.reverse_operate(concat_op, other)
(self, other: Any) -> sqlalchemy.sql.operators.ColumnOperators
16,053
sqlalchemy.sql.selectable
_refresh_for_new_column
Given a column added to the .c collection of an underlying selectable, produce the local version of that column, assuming this selectable ultimately should proxy this column. this is used to "ping" a derived selectable to add a new column to its .c. collection when a Column has been added to one of the Table objects it ultimately derives from. If the given selectable hasn't populated its .c. collection yet, it should at least pass on the message to the contained selectables, but it will return None. This method is currently used by Declarative to allow Table columns to be added to a partially constructed inheritance mapping that may have already produced joins. The method isn't public right now, as the full span of implications and/or caveats aren't yet clear. It's also possible that this functionality could be invoked by default via an event, which would require that selectables maintain a weak referencing collection of all derivations.
def _refresh_for_new_column(self, column: ColumnElement[Any]) -> None: """Given a column added to the .c collection of an underlying selectable, produce the local version of that column, assuming this selectable ultimately should proxy this column. this is used to "ping" a derived selectable to add a new column to its .c. collection when a Column has been added to one of the Table objects it ultimately derives from. If the given selectable hasn't populated its .c. collection yet, it should at least pass on the message to the contained selectables, but it will return None. This method is currently used by Declarative to allow Table columns to be added to a partially constructed inheritance mapping that may have already produced joins. The method isn't public right now, as the full span of implications and/or caveats aren't yet clear. It's also possible that this functionality could be invoked by default via an event, which would require that selectables maintain a weak referencing collection of all derivations. """ self._reset_column_collection()
(self, column: sqlalchemy.sql.elements.ColumnElement[typing.Any]) -> NoneType
16,054
sqlalchemy.sql.elements
_replace_params
null
def _replace_params( self, unique: bool, optionaldict: Optional[Mapping[str, Any]], kwargs: Dict[str, Any], ) -> Self: if optionaldict: kwargs.update(optionaldict) def visit_bindparam(bind: BindParameter[Any]) -> None: if bind.key in kwargs: bind.value = kwargs[bind.key] bind.required = False if unique: bind._convert_to_unique() return cloned_traverse( self, {"maintain_key": True, "detect_subquery_cols": True}, {"bindparam": visit_bindparam}, )
(self, unique: bool, optionaldict: Optional[Mapping[str, Any]], kwargs: Dict[str, Any]) -> typing_extensions.Self
16,055
sqlalchemy.sql.selectable
_reset_column_collection
Reset the attributes linked to the ``FromClause.c`` attribute. This collection is separate from all the other memoized things as it has shown to be sensitive to being cleared out in situations where enclosing code, typically in a replacement traversal scenario, has already established strong relationships with the exported columns. The collection is cleared for the case where a table is having a column added to it as well as within a Join during copy internals.
def _reset_column_collection(self) -> None: """Reset the attributes linked to the ``FromClause.c`` attribute. This collection is separate from all the other memoized things as it has shown to be sensitive to being cleared out in situations where enclosing code, typically in a replacement traversal scenario, has already established strong relationships with the exported columns. The collection is cleared for the case where a table is having a column added to it as well as within a Join during copy internals. """ for key in ["_columns", "columns", "c", "primary_key", "foreign_keys"]: self.__dict__.pop(key, None)
(self) -> NoneType
16,056
sqlalchemy.util.langhelpers
_reset_memoizations
null
def _reset_memoizations(self) -> None: for elem in self._memoized_keys: self.__dict__.pop(elem, None)
(self) -> NoneType
16,057
sqlalchemy.sql.base
_set_compile_options
Assign the compile options to a new value. :param compile_options: appropriate CacheableOptions structure
# sql/base.py # Copyright (C) 2005-2024 the SQLAlchemy authors and contributors # <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: https://www.opensource.org/licenses/mit-license.php # mypy: allow-untyped-defs, allow-untyped-calls """Foundational utilities common to many sql modules. """ from __future__ import annotations import collections from enum import Enum import itertools from itertools import zip_longest import operator import re from typing import Any from typing import Callable from typing import cast from typing import Dict from typing import FrozenSet from typing import Generic from typing import Iterable from typing import Iterator from typing import List from typing import Mapping from typing import MutableMapping from typing import NamedTuple from typing import NoReturn from typing import Optional from typing import overload from typing import Sequence from typing import Set from typing import Tuple from typing import Type from typing import TYPE_CHECKING from typing import TypeVar from typing import Union from . import roles from . import visitors from .cache_key import HasCacheKey # noqa from .cache_key import MemoizedHasCacheKey # noqa from .traversals import HasCopyInternals # noqa from .visitors import ClauseVisitor from .visitors import ExtendedInternalTraversal from .visitors import ExternallyTraversible from .visitors import InternalTraversal from .. import event from .. import exc from .. import util from ..util import HasMemoized as HasMemoized from ..util import hybridmethod from ..util import typing as compat_typing from ..util.typing import Protocol from ..util.typing import Self from ..util.typing import TypeGuard if TYPE_CHECKING: from . import coercions from . import elements from . import type_api from ._orm_types import DMLStrategyArgument from ._orm_types import SynchronizeSessionArgument from ._typing import _CLE from .elements import BindParameter from .elements import ClauseList from .elements import ColumnClause # noqa from .elements import ColumnElement from .elements import NamedColumn from .elements import SQLCoreOperations from .elements import TextClause from .schema import Column from .schema import DefaultGenerator from .selectable import _JoinTargetElement from .selectable import _SelectIterable from .selectable import FromClause from ..engine import Connection from ..engine import CursorResult from ..engine.interfaces import _CoreMultiExecuteParams from ..engine.interfaces import _ExecuteOptions from ..engine.interfaces import _ImmutableExecuteOptions from ..engine.interfaces import CacheStats from ..engine.interfaces import Compiled from ..engine.interfaces import CompiledCacheType from ..engine.interfaces import CoreExecuteOptionsParameter from ..engine.interfaces import Dialect from ..engine.interfaces import IsolationLevel from ..engine.interfaces import SchemaTranslateMapType from ..event import dispatcher if not TYPE_CHECKING: coercions = None # noqa elements = None # noqa type_api = None # noqa class _NoArg(Enum): NO_ARG = 0 def __repr__(self): return f"_NoArg.{self.name}"
(self, compile_options: sqlalchemy.sql.base.CacheableOptions) -> typing_extensions.Self
16,058
sqlalchemy.util.langhelpers
_set_memoized_attribute
null
def _set_memoized_attribute(self, key: str, value: Any) -> None: self.__dict__[key] = value self._memoized_keys |= {key}
(self, key: str, value: Any) -> NoneType
16,059
sqlalchemy.sql.elements
_set_propagate_attrs
null
def _set_propagate_attrs(self, values: Mapping[str, Any]) -> Self: # usually, self._propagate_attrs is empty here. one case where it's # not is a subquery against ORM select, that is then pulled as a # property of an aliased class. should all be good # assert not self._propagate_attrs self._propagate_attrs = util.immutabledict(values) return self
(self, values: Mapping[str, Any]) -> typing_extensions.Self
16,060
sqlalchemy.sql.elements
_uncached_proxy_list
An 'uncached' version of proxy set. This list includes annotated columns which perform very poorly in set operations.
def _uncached_proxy_list(self) -> List[ColumnElement[Any]]: """An 'uncached' version of proxy set. This list includes annotated columns which perform very poorly in set operations. """ return [self] + list( itertools.chain(*[c._uncached_proxy_list() for c in self._proxies]) )
(self) -> List[sqlalchemy.sql.elements.ColumnElement[Any]]
16,061
sqlalchemy.sql.elements
_ungroup
Return this :class:`_expression.ClauseElement` without any groupings.
def _ungroup(self) -> ClauseElement: """Return this :class:`_expression.ClauseElement` without any groupings. """ return self
(self) -> sqlalchemy.sql.elements.ClauseElement
16,062
sqlalchemy.sql.base
_update_compile_options
update the _compile_options with new keys.
# sql/base.py # Copyright (C) 2005-2024 the SQLAlchemy authors and contributors # <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: https://www.opensource.org/licenses/mit-license.php # mypy: allow-untyped-defs, allow-untyped-calls """Foundational utilities common to many sql modules. """ from __future__ import annotations import collections from enum import Enum import itertools from itertools import zip_longest import operator import re from typing import Any from typing import Callable from typing import cast from typing import Dict from typing import FrozenSet from typing import Generic from typing import Iterable from typing import Iterator from typing import List from typing import Mapping from typing import MutableMapping from typing import NamedTuple from typing import NoReturn from typing import Optional from typing import overload from typing import Sequence from typing import Set from typing import Tuple from typing import Type from typing import TYPE_CHECKING from typing import TypeVar from typing import Union from . import roles from . import visitors from .cache_key import HasCacheKey # noqa from .cache_key import MemoizedHasCacheKey # noqa from .traversals import HasCopyInternals # noqa from .visitors import ClauseVisitor from .visitors import ExtendedInternalTraversal from .visitors import ExternallyTraversible from .visitors import InternalTraversal from .. import event from .. import exc from .. import util from ..util import HasMemoized as HasMemoized from ..util import hybridmethod from ..util import typing as compat_typing from ..util.typing import Protocol from ..util.typing import Self from ..util.typing import TypeGuard if TYPE_CHECKING: from . import coercions from . import elements from . import type_api from ._orm_types import DMLStrategyArgument from ._orm_types import SynchronizeSessionArgument from ._typing import _CLE from .elements import BindParameter from .elements import ClauseList from .elements import ColumnClause # noqa from .elements import ColumnElement from .elements import NamedColumn from .elements import SQLCoreOperations from .elements import TextClause from .schema import Column from .schema import DefaultGenerator from .selectable import _JoinTargetElement from .selectable import _SelectIterable from .selectable import FromClause from ..engine import Connection from ..engine import CursorResult from ..engine.interfaces import _CoreMultiExecuteParams from ..engine.interfaces import _ExecuteOptions from ..engine.interfaces import _ImmutableExecuteOptions from ..engine.interfaces import CacheStats from ..engine.interfaces import Compiled from ..engine.interfaces import CompiledCacheType from ..engine.interfaces import CoreExecuteOptionsParameter from ..engine.interfaces import Dialect from ..engine.interfaces import IsolationLevel from ..engine.interfaces import SchemaTranslateMapType from ..event import dispatcher if not TYPE_CHECKING: coercions = None # noqa elements = None # noqa type_api = None # noqa class _NoArg(Enum): NO_ARG = 0 def __repr__(self): return f"_NoArg.{self.name}"
(self, options: sqlalchemy.sql.base.CacheableOptions) -> typing_extensions.Self
16,063
sqlalchemy.sql.annotation
_with_annotations
return a copy of this ClauseElement with annotations replaced by the given dictionary.
def _with_annotations(self, values: _AnnotationDict) -> Self: """return a copy of this ClauseElement with annotations replaced by the given dictionary. """ return Annotated._as_annotated_instance(self, values) # type: ignore
(self, values: Mapping[str, Any]) -> typing_extensions.Self
16,064
sqlalchemy.sql.elements
_with_binary_element_type
in the context of binary expression, convert the type of this object to the one given. applies only to :class:`_expression.ColumnElement` classes.
def _with_binary_element_type(self, type_): """in the context of binary expression, convert the type of this object to the one given. applies only to :class:`_expression.ColumnElement` classes. """ return self
(self, type_)
16,065
sqlalchemy.sql.functions
alias
Produce a :class:`_expression.Alias` construct against this :class:`.FunctionElement`. .. tip:: The :meth:`_functions.FunctionElement.alias` method is part of the mechanism by which "table valued" SQL functions are created. However, most use cases are covered by higher level methods on :class:`_functions.FunctionElement` including :meth:`_functions.FunctionElement.table_valued`, and :meth:`_functions.FunctionElement.column_valued`. This construct wraps the function in a named alias which is suitable for the FROM clause, in the style accepted for example by PostgreSQL. A column expression is also provided using the special ``.column`` attribute, which may be used to refer to the output of the function as a scalar value in the columns or where clause, for a backend such as PostgreSQL. For a full table-valued expression, use the :meth:`_functions.FunctionElement.table_valued` method first to establish named columns. e.g.: .. sourcecode:: pycon+sql >>> from sqlalchemy import func, select, column >>> data_view = func.unnest([1, 2, 3]).alias("data_view") >>> print(select(data_view.column)) {printsql}SELECT data_view FROM unnest(:unnest_1) AS data_view The :meth:`_functions.FunctionElement.column_valued` method provides a shortcut for the above pattern: .. sourcecode:: pycon+sql >>> data_view = func.unnest([1, 2, 3]).column_valued("data_view") >>> print(select(data_view)) {printsql}SELECT data_view FROM unnest(:unnest_1) AS data_view .. versionadded:: 1.4.0b2 Added the ``.column`` accessor :param name: alias name, will be rendered as ``AS <name>`` in the FROM clause :param joins_implicitly: when True, the table valued function may be used in the FROM clause without any explicit JOIN to other tables in the SQL query, and no "cartesian product" warning will be generated. May be useful for SQL functions such as ``func.json_each()``. .. versionadded:: 1.4.33 .. seealso:: :ref:`tutorial_functions_table_valued` - in the :ref:`unified_tutorial` :meth:`_functions.FunctionElement.table_valued` :meth:`_functions.FunctionElement.scalar_table_valued` :meth:`_functions.FunctionElement.column_valued`
def alias( self, name: Optional[str] = None, joins_implicitly: bool = False ) -> TableValuedAlias: r"""Produce a :class:`_expression.Alias` construct against this :class:`.FunctionElement`. .. tip:: The :meth:`_functions.FunctionElement.alias` method is part of the mechanism by which "table valued" SQL functions are created. However, most use cases are covered by higher level methods on :class:`_functions.FunctionElement` including :meth:`_functions.FunctionElement.table_valued`, and :meth:`_functions.FunctionElement.column_valued`. This construct wraps the function in a named alias which is suitable for the FROM clause, in the style accepted for example by PostgreSQL. A column expression is also provided using the special ``.column`` attribute, which may be used to refer to the output of the function as a scalar value in the columns or where clause, for a backend such as PostgreSQL. For a full table-valued expression, use the :meth:`_functions.FunctionElement.table_valued` method first to establish named columns. e.g.: .. sourcecode:: pycon+sql >>> from sqlalchemy import func, select, column >>> data_view = func.unnest([1, 2, 3]).alias("data_view") >>> print(select(data_view.column)) {printsql}SELECT data_view FROM unnest(:unnest_1) AS data_view The :meth:`_functions.FunctionElement.column_valued` method provides a shortcut for the above pattern: .. sourcecode:: pycon+sql >>> data_view = func.unnest([1, 2, 3]).column_valued("data_view") >>> print(select(data_view)) {printsql}SELECT data_view FROM unnest(:unnest_1) AS data_view .. versionadded:: 1.4.0b2 Added the ``.column`` accessor :param name: alias name, will be rendered as ``AS <name>`` in the FROM clause :param joins_implicitly: when True, the table valued function may be used in the FROM clause without any explicit JOIN to other tables in the SQL query, and no "cartesian product" warning will be generated. May be useful for SQL functions such as ``func.json_each()``. .. versionadded:: 1.4.33 .. seealso:: :ref:`tutorial_functions_table_valued` - in the :ref:`unified_tutorial` :meth:`_functions.FunctionElement.table_valued` :meth:`_functions.FunctionElement.scalar_table_valued` :meth:`_functions.FunctionElement.column_valued` """ return TableValuedAlias._construct( self, name=name, table_value_type=self.type, joins_implicitly=joins_implicitly, )
(self, name: Optional[str] = None, joins_implicitly: bool = False) -> sqlalchemy.sql.selectable.TableValuedAlias
16,066
sqlalchemy.sql.operators
all_
Produce an :func:`_expression.all_` clause against the parent object. See the documentation for :func:`_sql.all_` for examples. .. note:: be sure to not confuse the newer :meth:`_sql.ColumnOperators.all_` method with the **legacy** version of this method, the :meth:`_types.ARRAY.Comparator.all` method that's specific to :class:`_types.ARRAY`, which uses a different calling style.
def all_(self) -> ColumnOperators: """Produce an :func:`_expression.all_` clause against the parent object. See the documentation for :func:`_sql.all_` for examples. .. note:: be sure to not confuse the newer :meth:`_sql.ColumnOperators.all_` method with the **legacy** version of this method, the :meth:`_types.ARRAY.Comparator.all` method that's specific to :class:`_types.ARRAY`, which uses a different calling style. """ return self.operate(all_op)
(self) -> sqlalchemy.sql.operators.ColumnOperators
16,067
sqlalchemy.sql.operators
any_
Produce an :func:`_expression.any_` clause against the parent object. See the documentation for :func:`_sql.any_` for examples. .. note:: be sure to not confuse the newer :meth:`_sql.ColumnOperators.any_` method with the **legacy** version of this method, the :meth:`_types.ARRAY.Comparator.any` method that's specific to :class:`_types.ARRAY`, which uses a different calling style.
def any_(self) -> ColumnOperators: """Produce an :func:`_expression.any_` clause against the parent object. See the documentation for :func:`_sql.any_` for examples. .. note:: be sure to not confuse the newer :meth:`_sql.ColumnOperators.any_` method with the **legacy** version of this method, the :meth:`_types.ARRAY.Comparator.any` method that's specific to :class:`_types.ARRAY`, which uses a different calling style. """ return self.operate(any_op)
(self) -> sqlalchemy.sql.operators.ColumnOperators
16,068
sqlalchemy.sql.functions
as_comparison
Interpret this expression as a boolean comparison between two values. This method is used for an ORM use case described at :ref:`relationship_custom_operator_sql_function`. A hypothetical SQL function "is_equal()" which compares to values for equality would be written in the Core expression language as:: expr = func.is_equal("a", "b") If "is_equal()" above is comparing "a" and "b" for equality, the :meth:`.FunctionElement.as_comparison` method would be invoked as:: expr = func.is_equal("a", "b").as_comparison(1, 2) Where above, the integer value "1" refers to the first argument of the "is_equal()" function and the integer value "2" refers to the second. This would create a :class:`.BinaryExpression` that is equivalent to:: BinaryExpression("a", "b", operator=op.eq) However, at the SQL level it would still render as "is_equal('a', 'b')". The ORM, when it loads a related object or collection, needs to be able to manipulate the "left" and "right" sides of the ON clause of a JOIN expression. The purpose of this method is to provide a SQL function construct that can also supply this information to the ORM, when used with the :paramref:`_orm.relationship.primaryjoin` parameter. The return value is a containment object called :class:`.FunctionAsBinary`. An ORM example is as follows:: class Venue(Base): __tablename__ = 'venue' id = Column(Integer, primary_key=True) name = Column(String) descendants = relationship( "Venue", primaryjoin=func.instr( remote(foreign(name)), name + "/" ).as_comparison(1, 2) == 1, viewonly=True, order_by=name ) Above, the "Venue" class can load descendant "Venue" objects by determining if the name of the parent Venue is contained within the start of the hypothetical descendant value's name, e.g. "parent1" would match up to "parent1/child1", but not to "parent2/child1". Possible use cases include the "materialized path" example given above, as well as making use of special SQL functions such as geometric functions to create join conditions. :param left_index: the integer 1-based index of the function argument that serves as the "left" side of the expression. :param right_index: the integer 1-based index of the function argument that serves as the "right" side of the expression. .. versionadded:: 1.3 .. seealso:: :ref:`relationship_custom_operator_sql_function` - example use within the ORM
def as_comparison( self, left_index: int, right_index: int ) -> FunctionAsBinary: """Interpret this expression as a boolean comparison between two values. This method is used for an ORM use case described at :ref:`relationship_custom_operator_sql_function`. A hypothetical SQL function "is_equal()" which compares to values for equality would be written in the Core expression language as:: expr = func.is_equal("a", "b") If "is_equal()" above is comparing "a" and "b" for equality, the :meth:`.FunctionElement.as_comparison` method would be invoked as:: expr = func.is_equal("a", "b").as_comparison(1, 2) Where above, the integer value "1" refers to the first argument of the "is_equal()" function and the integer value "2" refers to the second. This would create a :class:`.BinaryExpression` that is equivalent to:: BinaryExpression("a", "b", operator=op.eq) However, at the SQL level it would still render as "is_equal('a', 'b')". The ORM, when it loads a related object or collection, needs to be able to manipulate the "left" and "right" sides of the ON clause of a JOIN expression. The purpose of this method is to provide a SQL function construct that can also supply this information to the ORM, when used with the :paramref:`_orm.relationship.primaryjoin` parameter. The return value is a containment object called :class:`.FunctionAsBinary`. An ORM example is as follows:: class Venue(Base): __tablename__ = 'venue' id = Column(Integer, primary_key=True) name = Column(String) descendants = relationship( "Venue", primaryjoin=func.instr( remote(foreign(name)), name + "/" ).as_comparison(1, 2) == 1, viewonly=True, order_by=name ) Above, the "Venue" class can load descendant "Venue" objects by determining if the name of the parent Venue is contained within the start of the hypothetical descendant value's name, e.g. "parent1" would match up to "parent1/child1", but not to "parent2/child1". Possible use cases include the "materialized path" example given above, as well as making use of special SQL functions such as geometric functions to create join conditions. :param left_index: the integer 1-based index of the function argument that serves as the "left" side of the expression. :param right_index: the integer 1-based index of the function argument that serves as the "right" side of the expression. .. versionadded:: 1.3 .. seealso:: :ref:`relationship_custom_operator_sql_function` - example use within the ORM """ return FunctionAsBinary(self, left_index, right_index)
(self, left_index: int, right_index: int) -> sqlalchemy.sql.functions.FunctionAsBinary
16,069
sqlalchemy.sql.operators
asc
Produce a :func:`_expression.asc` clause against the parent object.
def asc(self) -> ColumnOperators: """Produce a :func:`_expression.asc` clause against the parent object.""" return self.operate(asc_op)
(self) -> sqlalchemy.sql.operators.ColumnOperators
16,070
sqlalchemy.sql.operators
between
Produce a :func:`_expression.between` clause against the parent object, given the lower and upper range.
def between( self, cleft: Any, cright: Any, symmetric: bool = False ) -> ColumnOperators: """Produce a :func:`_expression.between` clause against the parent object, given the lower and upper range. """ return self.operate(between_op, cleft, cright, symmetric=symmetric)
(self, cleft: Any, cright: Any, symmetric: bool = False) -> sqlalchemy.sql.operators.ColumnOperators
16,071
sqlalchemy.sql.operators
bitwise_and
Produce a bitwise AND operation, typically via the ``&`` operator. .. versionadded:: 2.0.2 .. seealso:: :ref:`operators_bitwise`
def bitwise_and(self, other: Any) -> ColumnOperators: """Produce a bitwise AND operation, typically via the ``&`` operator. .. versionadded:: 2.0.2 .. seealso:: :ref:`operators_bitwise` """ return self.operate(bitwise_and_op, other)
(self, other: Any) -> sqlalchemy.sql.operators.ColumnOperators
16,072
sqlalchemy.sql.operators
bitwise_lshift
Produce a bitwise LSHIFT operation, typically via the ``<<`` operator. .. versionadded:: 2.0.2 .. seealso:: :ref:`operators_bitwise`
def bitwise_lshift(self, other: Any) -> ColumnOperators: """Produce a bitwise LSHIFT operation, typically via the ``<<`` operator. .. versionadded:: 2.0.2 .. seealso:: :ref:`operators_bitwise` """ return self.operate(bitwise_lshift_op, other)
(self, other: Any) -> sqlalchemy.sql.operators.ColumnOperators
16,073
sqlalchemy.sql.operators
bitwise_not
Produce a bitwise NOT operation, typically via the ``~`` operator. .. versionadded:: 2.0.2 .. seealso:: :ref:`operators_bitwise`
def bitwise_not(self) -> ColumnOperators: """Produce a bitwise NOT operation, typically via the ``~`` operator. .. versionadded:: 2.0.2 .. seealso:: :ref:`operators_bitwise` """ return self.operate(bitwise_not_op)
(self) -> sqlalchemy.sql.operators.ColumnOperators
16,074
sqlalchemy.sql.operators
bitwise_or
Produce a bitwise OR operation, typically via the ``|`` operator. .. versionadded:: 2.0.2 .. seealso:: :ref:`operators_bitwise`
def bitwise_or(self, other: Any) -> ColumnOperators: """Produce a bitwise OR operation, typically via the ``|`` operator. .. versionadded:: 2.0.2 .. seealso:: :ref:`operators_bitwise` """ return self.operate(bitwise_or_op, other)
(self, other: Any) -> sqlalchemy.sql.operators.ColumnOperators
16,075
sqlalchemy.sql.operators
bitwise_rshift
Produce a bitwise RSHIFT operation, typically via the ``>>`` operator. .. versionadded:: 2.0.2 .. seealso:: :ref:`operators_bitwise`
def bitwise_rshift(self, other: Any) -> ColumnOperators: """Produce a bitwise RSHIFT operation, typically via the ``>>`` operator. .. versionadded:: 2.0.2 .. seealso:: :ref:`operators_bitwise` """ return self.operate(bitwise_rshift_op, other)
(self, other: Any) -> sqlalchemy.sql.operators.ColumnOperators
16,076
sqlalchemy.sql.operators
bitwise_xor
Produce a bitwise XOR operation, typically via the ``^`` operator, or ``#`` for PostgreSQL. .. versionadded:: 2.0.2 .. seealso:: :ref:`operators_bitwise`
def bitwise_xor(self, other: Any) -> ColumnOperators: """Produce a bitwise XOR operation, typically via the ``^`` operator, or ``#`` for PostgreSQL. .. versionadded:: 2.0.2 .. seealso:: :ref:`operators_bitwise` """ return self.operate(bitwise_xor_op, other)
(self, other: Any) -> sqlalchemy.sql.operators.ColumnOperators
16,077
sqlalchemy.sql.operators
bool_op
Return a custom boolean operator. This method is shorthand for calling :meth:`.Operators.op` and passing the :paramref:`.Operators.op.is_comparison` flag with True. A key advantage to using :meth:`.Operators.bool_op` is that when using column constructs, the "boolean" nature of the returned expression will be present for :pep:`484` purposes. .. seealso:: :meth:`.Operators.op`
def bool_op( self, opstring: str, precedence: int = 0, python_impl: Optional[Callable[..., Any]] = None, ) -> Callable[[Any], Operators]: """Return a custom boolean operator. This method is shorthand for calling :meth:`.Operators.op` and passing the :paramref:`.Operators.op.is_comparison` flag with True. A key advantage to using :meth:`.Operators.bool_op` is that when using column constructs, the "boolean" nature of the returned expression will be present for :pep:`484` purposes. .. seealso:: :meth:`.Operators.op` """ return self.op( opstring, precedence=precedence, is_comparison=True, python_impl=python_impl, )
(self, opstring: str, precedence: int = 0, python_impl: Optional[Callable[..., Any]] = None) -> Callable[[Any], sqlalchemy.sql.operators.Operators]
16,078
sqlalchemy.sql.elements
cast
Produce a type cast, i.e. ``CAST(<expression> AS <type>)``. This is a shortcut to the :func:`_expression.cast` function. .. seealso:: :ref:`tutorial_casts` :func:`_expression.cast` :func:`_expression.type_coerce`
def cast(self, type_: _TypeEngineArgument[_OPT]) -> Cast[_OPT]: """Produce a type cast, i.e. ``CAST(<expression> AS <type>)``. This is a shortcut to the :func:`_expression.cast` function. .. seealso:: :ref:`tutorial_casts` :func:`_expression.cast` :func:`_expression.type_coerce` """ return Cast(self, type_)
(self, type_: '_TypeEngineArgument[_OPT]') -> 'Cast[_OPT]'
16,079
sqlalchemy.sql.operators
collate
Produce a :func:`_expression.collate` clause against the parent object, given the collation string. .. seealso:: :func:`_expression.collate`
def collate(self, collation: str) -> ColumnOperators: """Produce a :func:`_expression.collate` clause against the parent object, given the collation string. .. seealso:: :func:`_expression.collate` """ return self.operate(collate, collation)
(self, collation: str) -> sqlalchemy.sql.operators.ColumnOperators
16,080
sqlalchemy.sql.functions
column_valued
Return this :class:`_functions.FunctionElement` as a column expression that selects from itself as a FROM clause. E.g.: .. sourcecode:: pycon+sql >>> from sqlalchemy import select, func >>> gs = func.generate_series(1, 5, -1).column_valued() >>> print(select(gs)) {printsql}SELECT anon_1 FROM generate_series(:generate_series_1, :generate_series_2, :generate_series_3) AS anon_1 This is shorthand for:: gs = func.generate_series(1, 5, -1).alias().column :param name: optional name to assign to the alias name that's generated. If omitted, a unique anonymizing name is used. :param joins_implicitly: when True, the "table" portion of the column valued function may be a member of the FROM clause without any explicit JOIN to other tables in the SQL query, and no "cartesian product" warning will be generated. May be useful for SQL functions such as ``func.json_array_elements()``. .. versionadded:: 1.4.46 .. seealso:: :ref:`tutorial_functions_column_valued` - in the :ref:`unified_tutorial` :ref:`postgresql_column_valued` - in the :ref:`postgresql_toplevel` documentation :meth:`_functions.FunctionElement.table_valued`
def column_valued( self, name: Optional[str] = None, joins_implicitly: bool = False ) -> TableValuedColumn[_T]: """Return this :class:`_functions.FunctionElement` as a column expression that selects from itself as a FROM clause. E.g.: .. sourcecode:: pycon+sql >>> from sqlalchemy import select, func >>> gs = func.generate_series(1, 5, -1).column_valued() >>> print(select(gs)) {printsql}SELECT anon_1 FROM generate_series(:generate_series_1, :generate_series_2, :generate_series_3) AS anon_1 This is shorthand for:: gs = func.generate_series(1, 5, -1).alias().column :param name: optional name to assign to the alias name that's generated. If omitted, a unique anonymizing name is used. :param joins_implicitly: when True, the "table" portion of the column valued function may be a member of the FROM clause without any explicit JOIN to other tables in the SQL query, and no "cartesian product" warning will be generated. May be useful for SQL functions such as ``func.json_array_elements()``. .. versionadded:: 1.4.46 .. seealso:: :ref:`tutorial_functions_column_valued` - in the :ref:`unified_tutorial` :ref:`postgresql_column_valued` - in the :ref:`postgresql_toplevel` documentation :meth:`_functions.FunctionElement.table_valued` """ # noqa: 501 return self.alias(name=name, joins_implicitly=joins_implicitly).column
(self, name: 'Optional[str]' = None, joins_implicitly: 'bool' = False) -> 'TableValuedColumn[_T]'
16,081
sqlalchemy.sql.elements
compare
Compare this :class:`_expression.ClauseElement` to the given :class:`_expression.ClauseElement`. 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 :class:`_expression.ColumnElement`).
def compare(self, other: ClauseElement, **kw: Any) -> bool: r"""Compare this :class:`_expression.ClauseElement` to the given :class:`_expression.ClauseElement`. 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 :class:`_expression.ColumnElement`). """ return traversals.compare(self, other, **kw)
(self, other: sqlalchemy.sql.elements.ClauseElement, **kw: Any) -> bool
16,082
sqlalchemy.sql.elements
compile
Compile this SQL expression. The return value is a :class:`~.Compiled` object. Calling ``str()`` or ``unicode()`` on the returned value will yield a string representation of the result. The :class:`~.Compiled` object also can return a dictionary of bind parameter names and values using the ``params`` accessor. :param bind: An :class:`.Connection` or :class:`.Engine` which can provide a :class:`.Dialect` in order to generate a :class:`.Compiled` object. If the ``bind`` and ``dialect`` parameters are both omitted, a default SQL compiler is used. :param 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. :param dialect: A :class:`.Dialect` instance which can generate a :class:`.Compiled` object. This argument takes precedence over the ``bind`` argument. :param 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:: 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})) .. seealso:: :ref:`faq_sql_expression_string`
@util.preload_module("sqlalchemy.engine.default") @util.preload_module("sqlalchemy.engine.url") def compile( self, bind: Optional[_HasDialect] = None, dialect: Optional[Dialect] = None, **kw: Any, ) -> Compiled: """Compile this SQL expression. The return value is a :class:`~.Compiled` object. Calling ``str()`` or ``unicode()`` on the returned value will yield a string representation of the result. The :class:`~.Compiled` object also can return a dictionary of bind parameter names and values using the ``params`` accessor. :param bind: An :class:`.Connection` or :class:`.Engine` which can provide a :class:`.Dialect` in order to generate a :class:`.Compiled` object. If the ``bind`` and ``dialect`` parameters are both omitted, a default SQL compiler is used. :param 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. :param dialect: A :class:`.Dialect` instance which can generate a :class:`.Compiled` object. This argument takes precedence over the ``bind`` argument. :param 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:: 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})) .. seealso:: :ref:`faq_sql_expression_string` """ if dialect is None: if bind: dialect = bind.dialect elif self.stringify_dialect == "default": default = util.preloaded.engine_default dialect = default.StrCompileDialect() else: url = util.preloaded.engine_url dialect = url.URL.create( self.stringify_dialect ).get_dialect()() return self._compiler(dialect, **kw)
(self, bind: 'Optional[_HasDialect]' = None, dialect: 'Optional[Dialect]' = None, **kw: 'Any') -> 'Compiled'
16,083
sqlalchemy.sql.operators
concat
Implement the 'concat' operator. In a column context, produces the clause ``a || b``, or uses the ``concat()`` operator on MySQL.
def concat(self, other: Any) -> ColumnOperators: """Implement the 'concat' operator. In a column context, produces the clause ``a || b``, or uses the ``concat()`` operator on MySQL. """ return self.operate(concat_op, other)
(self, other: Any) -> sqlalchemy.sql.operators.ColumnOperators
16,084
sqlalchemy.sql.operators
contains
Implement the 'contains' operator. Produces a LIKE expression that tests against a match for the middle of a string value:: column LIKE '%' || <other> || '%' E.g.:: stmt = select(sometable).\ where(sometable.c.column.contains("foobar")) Since the operator uses ``LIKE``, wildcard characters ``"%"`` and ``"_"`` that are present inside the <other> expression will behave like wildcards as well. For literal string values, the :paramref:`.ColumnOperators.contains.autoescape` flag may be set to ``True`` to apply escaping to occurrences of these characters within the string value so that they match as themselves and not as wildcard characters. Alternatively, the :paramref:`.ColumnOperators.contains.escape` parameter will establish a given character as an escape character which can be of use when the target expression is not a literal string. :param other: expression to be compared. This is usually a plain string value, but can also be an arbitrary SQL expression. LIKE wildcard characters ``%`` and ``_`` are not escaped by default unless the :paramref:`.ColumnOperators.contains.autoescape` flag is set to True. :param autoescape: boolean; when True, establishes an escape character within the LIKE expression, then applies it to all occurrences of ``"%"``, ``"_"`` and the escape character itself within the comparison value, which is assumed to be a literal string and not a SQL expression. An expression such as:: somecolumn.contains("foo%bar", autoescape=True) Will render as:: somecolumn LIKE '%' || :param || '%' ESCAPE '/' With the value of ``:param`` as ``"foo/%bar"``. :param escape: a character which when given will render with the ``ESCAPE`` keyword to establish that character as the escape character. This character can then be placed preceding occurrences of ``%`` and ``_`` to allow them to act as themselves and not wildcard characters. An expression such as:: somecolumn.contains("foo/%bar", escape="^") Will render as:: somecolumn LIKE '%' || :param || '%' ESCAPE '^' The parameter may also be combined with :paramref:`.ColumnOperators.contains.autoescape`:: somecolumn.contains("foo%bar^bat", escape="^", autoescape=True) Where above, the given literal parameter will be converted to ``"foo^%bar^^bat"`` before being passed to the database. .. seealso:: :meth:`.ColumnOperators.startswith` :meth:`.ColumnOperators.endswith` :meth:`.ColumnOperators.like`
def contains(self, other: Any, **kw: Any) -> ColumnOperators: r"""Implement the 'contains' operator. Produces a LIKE expression that tests against a match for the middle of a string value:: column LIKE '%' || <other> || '%' E.g.:: stmt = select(sometable).\ where(sometable.c.column.contains("foobar")) Since the operator uses ``LIKE``, wildcard characters ``"%"`` and ``"_"`` that are present inside the <other> expression will behave like wildcards as well. For literal string values, the :paramref:`.ColumnOperators.contains.autoescape` flag may be set to ``True`` to apply escaping to occurrences of these characters within the string value so that they match as themselves and not as wildcard characters. Alternatively, the :paramref:`.ColumnOperators.contains.escape` parameter will establish a given character as an escape character which can be of use when the target expression is not a literal string. :param other: expression to be compared. This is usually a plain string value, but can also be an arbitrary SQL expression. LIKE wildcard characters ``%`` and ``_`` are not escaped by default unless the :paramref:`.ColumnOperators.contains.autoescape` flag is set to True. :param autoescape: boolean; when True, establishes an escape character within the LIKE expression, then applies it to all occurrences of ``"%"``, ``"_"`` and the escape character itself within the comparison value, which is assumed to be a literal string and not a SQL expression. An expression such as:: somecolumn.contains("foo%bar", autoescape=True) Will render as:: somecolumn LIKE '%' || :param || '%' ESCAPE '/' With the value of ``:param`` as ``"foo/%bar"``. :param escape: a character which when given will render with the ``ESCAPE`` keyword to establish that character as the escape character. This character can then be placed preceding occurrences of ``%`` and ``_`` to allow them to act as themselves and not wildcard characters. An expression such as:: somecolumn.contains("foo/%bar", escape="^") Will render as:: somecolumn LIKE '%' || :param || '%' ESCAPE '^' The parameter may also be combined with :paramref:`.ColumnOperators.contains.autoescape`:: somecolumn.contains("foo%bar^bat", escape="^", autoescape=True) Where above, the given literal parameter will be converted to ``"foo^%bar^^bat"`` before being passed to the database. .. seealso:: :meth:`.ColumnOperators.startswith` :meth:`.ColumnOperators.endswith` :meth:`.ColumnOperators.like` """ return self.operate(contains_op, other, **kw)
(self, other: Any, **kw: Any) -> sqlalchemy.sql.operators.ColumnOperators
16,085
sqlalchemy.sql.selectable
corresponding_column
Given a :class:`_expression.ColumnElement`, return the exported :class:`_expression.ColumnElement` object from the :attr:`_expression.Selectable.exported_columns` collection of this :class:`_expression.Selectable` which corresponds to that original :class:`_expression.ColumnElement` via a common ancestor column. :param column: the target :class:`_expression.ColumnElement` to be matched. :param require_embedded: only return corresponding columns for the given :class:`_expression.ColumnElement`, if the given :class:`_expression.ColumnElement` is actually present within a sub-element of this :class:`_expression.Selectable`. Normally the column will match if it merely shares a common ancestor with one of the exported columns of this :class:`_expression.Selectable`. .. seealso:: :attr:`_expression.Selectable.exported_columns` - the :class:`_expression.ColumnCollection` that is used for the operation. :meth:`_expression.ColumnCollection.corresponding_column` - implementation method.
def corresponding_column( self, column: KeyedColumnElement[Any], require_embedded: bool = False ) -> Optional[KeyedColumnElement[Any]]: """Given a :class:`_expression.ColumnElement`, return the exported :class:`_expression.ColumnElement` object from the :attr:`_expression.Selectable.exported_columns` collection of this :class:`_expression.Selectable` which corresponds to that original :class:`_expression.ColumnElement` via a common ancestor column. :param column: the target :class:`_expression.ColumnElement` to be matched. :param require_embedded: only return corresponding columns for the given :class:`_expression.ColumnElement`, if the given :class:`_expression.ColumnElement` is actually present within a sub-element of this :class:`_expression.Selectable`. Normally the column will match if it merely shares a common ancestor with one of the exported columns of this :class:`_expression.Selectable`. .. seealso:: :attr:`_expression.Selectable.exported_columns` - the :class:`_expression.ColumnCollection` that is used for the operation. :meth:`_expression.ColumnCollection.corresponding_column` - implementation method. """ return self.exported_columns.corresponding_column( column, require_embedded )
(self, column: 'KeyedColumnElement[Any]', require_embedded: 'bool' = False) -> 'Optional[KeyedColumnElement[Any]]'
16,086
sqlalchemy.sql.operators
desc
Produce a :func:`_expression.desc` clause against the parent object.
def desc(self) -> ColumnOperators: """Produce a :func:`_expression.desc` clause against the parent object.""" return self.operate(desc_op)
(self) -> sqlalchemy.sql.operators.ColumnOperators
16,087
sqlalchemy.sql.operators
distinct
Produce a :func:`_expression.distinct` clause against the parent object.
def distinct(self) -> ColumnOperators: """Produce a :func:`_expression.distinct` clause against the parent object. """ return self.operate(distinct_op)
(self) -> sqlalchemy.sql.operators.ColumnOperators
16,088
sqlalchemy.sql.operators
endswith
Implement the 'endswith' operator. Produces a LIKE expression that tests against a match for the end of a string value:: column LIKE '%' || <other> E.g.:: stmt = select(sometable).\ where(sometable.c.column.endswith("foobar")) Since the operator uses ``LIKE``, wildcard characters ``"%"`` and ``"_"`` that are present inside the <other> expression will behave like wildcards as well. For literal string values, the :paramref:`.ColumnOperators.endswith.autoescape` flag may be set to ``True`` to apply escaping to occurrences of these characters within the string value so that they match as themselves and not as wildcard characters. Alternatively, the :paramref:`.ColumnOperators.endswith.escape` parameter will establish a given character as an escape character which can be of use when the target expression is not a literal string. :param other: expression to be compared. This is usually a plain string value, but can also be an arbitrary SQL expression. LIKE wildcard characters ``%`` and ``_`` are not escaped by default unless the :paramref:`.ColumnOperators.endswith.autoescape` flag is set to True. :param autoescape: boolean; when True, establishes an escape character within the LIKE expression, then applies it to all occurrences of ``"%"``, ``"_"`` and the escape character itself within the comparison value, which is assumed to be a literal string and not a SQL expression. An expression such as:: somecolumn.endswith("foo%bar", autoescape=True) Will render as:: somecolumn LIKE '%' || :param ESCAPE '/' With the value of ``:param`` as ``"foo/%bar"``. :param escape: a character which when given will render with the ``ESCAPE`` keyword to establish that character as the escape character. This character can then be placed preceding occurrences of ``%`` and ``_`` to allow them to act as themselves and not wildcard characters. An expression such as:: somecolumn.endswith("foo/%bar", escape="^") Will render as:: somecolumn LIKE '%' || :param ESCAPE '^' The parameter may also be combined with :paramref:`.ColumnOperators.endswith.autoescape`:: somecolumn.endswith("foo%bar^bat", escape="^", autoescape=True) Where above, the given literal parameter will be converted to ``"foo^%bar^^bat"`` before being passed to the database. .. seealso:: :meth:`.ColumnOperators.startswith` :meth:`.ColumnOperators.contains` :meth:`.ColumnOperators.like`
def endswith( self, other: Any, escape: Optional[str] = None, autoescape: bool = False, ) -> ColumnOperators: r"""Implement the 'endswith' operator. Produces a LIKE expression that tests against a match for the end of a string value:: column LIKE '%' || <other> E.g.:: stmt = select(sometable).\ where(sometable.c.column.endswith("foobar")) Since the operator uses ``LIKE``, wildcard characters ``"%"`` and ``"_"`` that are present inside the <other> expression will behave like wildcards as well. For literal string values, the :paramref:`.ColumnOperators.endswith.autoescape` flag may be set to ``True`` to apply escaping to occurrences of these characters within the string value so that they match as themselves and not as wildcard characters. Alternatively, the :paramref:`.ColumnOperators.endswith.escape` parameter will establish a given character as an escape character which can be of use when the target expression is not a literal string. :param other: expression to be compared. This is usually a plain string value, but can also be an arbitrary SQL expression. LIKE wildcard characters ``%`` and ``_`` are not escaped by default unless the :paramref:`.ColumnOperators.endswith.autoescape` flag is set to True. :param autoescape: boolean; when True, establishes an escape character within the LIKE expression, then applies it to all occurrences of ``"%"``, ``"_"`` and the escape character itself within the comparison value, which is assumed to be a literal string and not a SQL expression. An expression such as:: somecolumn.endswith("foo%bar", autoescape=True) Will render as:: somecolumn LIKE '%' || :param ESCAPE '/' With the value of ``:param`` as ``"foo/%bar"``. :param escape: a character which when given will render with the ``ESCAPE`` keyword to establish that character as the escape character. This character can then be placed preceding occurrences of ``%`` and ``_`` to allow them to act as themselves and not wildcard characters. An expression such as:: somecolumn.endswith("foo/%bar", escape="^") Will render as:: somecolumn LIKE '%' || :param ESCAPE '^' The parameter may also be combined with :paramref:`.ColumnOperators.endswith.autoescape`:: somecolumn.endswith("foo%bar^bat", escape="^", autoescape=True) Where above, the given literal parameter will be converted to ``"foo^%bar^^bat"`` before being passed to the database. .. seealso:: :meth:`.ColumnOperators.startswith` :meth:`.ColumnOperators.contains` :meth:`.ColumnOperators.like` """ return self.operate( endswith_op, other, escape=escape, autoescape=autoescape )
(self, other: Any, escape: Optional[str] = None, autoescape: bool = False) -> sqlalchemy.sql.operators.ColumnOperators
16,089
sqlalchemy.sql.base
execution_options
Set non-SQL options for the statement which take effect during execution. Execution options can be set at many scopes, including per-statement, per-connection, or per execution, using methods such as :meth:`_engine.Connection.execution_options` and parameters which accept a dictionary of options such as :paramref:`_engine.Connection.execute.execution_options` and :paramref:`_orm.Session.execute.execution_options`. The primary characteristic of an execution option, as opposed to other kinds of options such as ORM loader options, is that **execution options never affect the compiled SQL of a query, only things that affect how the SQL statement itself is invoked or how results are fetched**. That is, execution options are not part of what's accommodated by SQL compilation nor are they considered part of the cached state of a statement. The :meth:`_sql.Executable.execution_options` method is :term:`generative`, as is the case for the method as applied to the :class:`_engine.Engine` and :class:`_orm.Query` objects, which means when the method is called, a copy of the object is returned, which applies the given parameters to that new copy, but leaves the original unchanged:: statement = select(table.c.x, table.c.y) new_statement = statement.execution_options(my_option=True) An exception to this behavior is the :class:`_engine.Connection` object, where the :meth:`_engine.Connection.execution_options` method is explicitly **not** generative. The kinds of options that may be passed to :meth:`_sql.Executable.execution_options` and other related methods and parameter dictionaries include parameters that are explicitly consumed by SQLAlchemy Core or ORM, as well as arbitrary keyword arguments not defined by SQLAlchemy, which means the methods and/or parameter dictionaries may be used for user-defined parameters that interact with custom code, which may access the parameters using methods such as :meth:`_sql.Executable.get_execution_options` and :meth:`_engine.Connection.get_execution_options`, or within selected event hooks using a dedicated ``execution_options`` event parameter such as :paramref:`_events.ConnectionEvents.before_execute.execution_options` or :attr:`_orm.ORMExecuteState.execution_options`, e.g.:: from sqlalchemy import event @event.listens_for(some_engine, "before_execute") def _process_opt(conn, statement, multiparams, params, execution_options): "run a SQL function before invoking a statement" if execution_options.get("do_special_thing", False): conn.exec_driver_sql("run_special_function()") Within the scope of options that are explicitly recognized by SQLAlchemy, most apply to specific classes of objects and not others. The most common execution options include: * :paramref:`_engine.Connection.execution_options.isolation_level` - sets the isolation level for a connection or a class of connections via an :class:`_engine.Engine`. This option is accepted only by :class:`_engine.Connection` or :class:`_engine.Engine`. * :paramref:`_engine.Connection.execution_options.stream_results` - indicates results should be fetched using a server side cursor; this option is accepted by :class:`_engine.Connection`, by the :paramref:`_engine.Connection.execute.execution_options` parameter on :meth:`_engine.Connection.execute`, and additionally by :meth:`_sql.Executable.execution_options` on a SQL statement object, as well as by ORM constructs like :meth:`_orm.Session.execute`. * :paramref:`_engine.Connection.execution_options.compiled_cache` - indicates a dictionary that will serve as the :ref:`SQL compilation cache <sql_caching>` for a :class:`_engine.Connection` or :class:`_engine.Engine`, as well as for ORM methods like :meth:`_orm.Session.execute`. Can be passed as ``None`` to disable caching for statements. This option is not accepted by :meth:`_sql.Executable.execution_options` as it is inadvisable to carry along a compilation cache within a statement object. * :paramref:`_engine.Connection.execution_options.schema_translate_map` - a mapping of schema names used by the :ref:`Schema Translate Map <schema_translating>` feature, accepted by :class:`_engine.Connection`, :class:`_engine.Engine`, :class:`_sql.Executable`, as well as by ORM constructs like :meth:`_orm.Session.execute`. .. seealso:: :meth:`_engine.Connection.execution_options` :paramref:`_engine.Connection.execute.execution_options` :paramref:`_orm.Session.execute.execution_options` :ref:`orm_queryguide_execution_options` - documentation on all ORM-specific execution options
# sql/base.py # Copyright (C) 2005-2024 the SQLAlchemy authors and contributors # <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: https://www.opensource.org/licenses/mit-license.php # mypy: allow-untyped-defs, allow-untyped-calls """Foundational utilities common to many sql modules. """ from __future__ import annotations import collections from enum import Enum import itertools from itertools import zip_longest import operator import re from typing import Any from typing import Callable from typing import cast from typing import Dict from typing import FrozenSet from typing import Generic from typing import Iterable from typing import Iterator from typing import List from typing import Mapping from typing import MutableMapping from typing import NamedTuple from typing import NoReturn from typing import Optional from typing import overload from typing import Sequence from typing import Set from typing import Tuple from typing import Type from typing import TYPE_CHECKING from typing import TypeVar from typing import Union from . import roles from . import visitors from .cache_key import HasCacheKey # noqa from .cache_key import MemoizedHasCacheKey # noqa from .traversals import HasCopyInternals # noqa from .visitors import ClauseVisitor from .visitors import ExtendedInternalTraversal from .visitors import ExternallyTraversible from .visitors import InternalTraversal from .. import event from .. import exc from .. import util from ..util import HasMemoized as HasMemoized from ..util import hybridmethod from ..util import typing as compat_typing from ..util.typing import Protocol from ..util.typing import Self from ..util.typing import TypeGuard if TYPE_CHECKING: from . import coercions from . import elements from . import type_api from ._orm_types import DMLStrategyArgument from ._orm_types import SynchronizeSessionArgument from ._typing import _CLE from .elements import BindParameter from .elements import ClauseList from .elements import ColumnClause # noqa from .elements import ColumnElement from .elements import NamedColumn from .elements import SQLCoreOperations from .elements import TextClause from .schema import Column from .schema import DefaultGenerator from .selectable import _JoinTargetElement from .selectable import _SelectIterable from .selectable import FromClause from ..engine import Connection from ..engine import CursorResult from ..engine.interfaces import _CoreMultiExecuteParams from ..engine.interfaces import _ExecuteOptions from ..engine.interfaces import _ImmutableExecuteOptions from ..engine.interfaces import CacheStats from ..engine.interfaces import Compiled from ..engine.interfaces import CompiledCacheType from ..engine.interfaces import CoreExecuteOptionsParameter from ..engine.interfaces import Dialect from ..engine.interfaces import IsolationLevel from ..engine.interfaces import SchemaTranslateMapType from ..event import dispatcher if not TYPE_CHECKING: coercions = None # noqa elements = None # noqa type_api = None # noqa class _NoArg(Enum): NO_ARG = 0 def __repr__(self): return f"_NoArg.{self.name}"
(self, **kw: Any) -> typing_extensions.Self
16,090
sqlalchemy.sql.functions
filter
Produce a FILTER clause against this function. Used against aggregate and window functions, for database backends that support the "FILTER" clause. The expression:: func.count(1).filter(True) is shorthand for:: from sqlalchemy import funcfilter funcfilter(func.count(1), True) .. seealso:: :ref:`tutorial_functions_within_group` - in the :ref:`unified_tutorial` :class:`.FunctionFilter` :func:`.funcfilter`
def filter( self, *criterion: _ColumnExpressionArgument[bool] ) -> Union[Self, FunctionFilter[_T]]: """Produce a FILTER clause against this function. Used against aggregate and window functions, for database backends that support the "FILTER" clause. The expression:: func.count(1).filter(True) is shorthand for:: from sqlalchemy import funcfilter funcfilter(func.count(1), True) .. seealso:: :ref:`tutorial_functions_within_group` - in the :ref:`unified_tutorial` :class:`.FunctionFilter` :func:`.funcfilter` """ if not criterion: return self return FunctionFilter(self, *criterion)
(self, *criterion: '_ColumnExpressionArgument[bool]') -> 'Union[Self, FunctionFilter[_T]]'
16,091
sqlalchemy.sql.visitors
get_children
Return immediate child :class:`.visitors.HasTraverseInternals` elements of this :class:`.visitors.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).
@util.preload_module("sqlalchemy.sql.traversals") def get_children( self, *, omit_attrs: Tuple[str, ...] = (), **kw: Any ) -> Iterable[HasTraverseInternals]: r"""Return immediate child :class:`.visitors.HasTraverseInternals` elements of this :class:`.visitors.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). """ traversals = util.preloaded.sql_traversals try: traverse_internals = self._traverse_internals except AttributeError: # user-defined classes may not have a _traverse_internals return [] dispatch = traversals._get_children.run_generated_dispatch return itertools.chain.from_iterable( meth(obj, **kw) for attrname, obj, meth in dispatch( self, traverse_internals, "_generated_get_children_traversal" ) if attrname not in omit_attrs and obj is not None )
(self, *, omit_attrs: Tuple[str, ...] = (), **kw: Any) -> Iterable[sqlalchemy.sql.visitors.HasTraverseInternals]
16,092
sqlalchemy.sql.base
get_execution_options
Get the non-SQL options which will take effect during execution. .. versionadded:: 1.3 .. seealso:: :meth:`.Executable.execution_options`
def get_execution_options(self) -> _ExecuteOptions: """Get the non-SQL options which will take effect during execution. .. versionadded:: 1.3 .. seealso:: :meth:`.Executable.execution_options` """ return self._execution_options
(self) -> '_ExecuteOptions'
16,093
sqlalchemy.sql.operators
icontains
Implement the ``icontains`` operator, e.g. case insensitive version of :meth:`.ColumnOperators.contains`. Produces a LIKE expression that tests against an insensitive match for the middle of a string value:: lower(column) LIKE '%' || lower(<other>) || '%' E.g.:: stmt = select(sometable).\ where(sometable.c.column.icontains("foobar")) Since the operator uses ``LIKE``, wildcard characters ``"%"`` and ``"_"`` that are present inside the <other> expression will behave like wildcards as well. For literal string values, the :paramref:`.ColumnOperators.icontains.autoescape` flag may be set to ``True`` to apply escaping to occurrences of these characters within the string value so that they match as themselves and not as wildcard characters. Alternatively, the :paramref:`.ColumnOperators.icontains.escape` parameter will establish a given character as an escape character which can be of use when the target expression is not a literal string. :param other: expression to be compared. This is usually a plain string value, but can also be an arbitrary SQL expression. LIKE wildcard characters ``%`` and ``_`` are not escaped by default unless the :paramref:`.ColumnOperators.icontains.autoescape` flag is set to True. :param autoescape: boolean; when True, establishes an escape character within the LIKE expression, then applies it to all occurrences of ``"%"``, ``"_"`` and the escape character itself within the comparison value, which is assumed to be a literal string and not a SQL expression. An expression such as:: somecolumn.icontains("foo%bar", autoescape=True) Will render as:: lower(somecolumn) LIKE '%' || lower(:param) || '%' ESCAPE '/' With the value of ``:param`` as ``"foo/%bar"``. :param escape: a character which when given will render with the ``ESCAPE`` keyword to establish that character as the escape character. This character can then be placed preceding occurrences of ``%`` and ``_`` to allow them to act as themselves and not wildcard characters. An expression such as:: somecolumn.icontains("foo/%bar", escape="^") Will render as:: lower(somecolumn) LIKE '%' || lower(:param) || '%' ESCAPE '^' The parameter may also be combined with :paramref:`.ColumnOperators.contains.autoescape`:: somecolumn.icontains("foo%bar^bat", escape="^", autoescape=True) Where above, the given literal parameter will be converted to ``"foo^%bar^^bat"`` before being passed to the database. .. seealso:: :meth:`.ColumnOperators.contains`
def icontains(self, other: Any, **kw: Any) -> ColumnOperators: r"""Implement the ``icontains`` operator, e.g. case insensitive version of :meth:`.ColumnOperators.contains`. Produces a LIKE expression that tests against an insensitive match for the middle of a string value:: lower(column) LIKE '%' || lower(<other>) || '%' E.g.:: stmt = select(sometable).\ where(sometable.c.column.icontains("foobar")) Since the operator uses ``LIKE``, wildcard characters ``"%"`` and ``"_"`` that are present inside the <other> expression will behave like wildcards as well. For literal string values, the :paramref:`.ColumnOperators.icontains.autoescape` flag may be set to ``True`` to apply escaping to occurrences of these characters within the string value so that they match as themselves and not as wildcard characters. Alternatively, the :paramref:`.ColumnOperators.icontains.escape` parameter will establish a given character as an escape character which can be of use when the target expression is not a literal string. :param other: expression to be compared. This is usually a plain string value, but can also be an arbitrary SQL expression. LIKE wildcard characters ``%`` and ``_`` are not escaped by default unless the :paramref:`.ColumnOperators.icontains.autoescape` flag is set to True. :param autoescape: boolean; when True, establishes an escape character within the LIKE expression, then applies it to all occurrences of ``"%"``, ``"_"`` and the escape character itself within the comparison value, which is assumed to be a literal string and not a SQL expression. An expression such as:: somecolumn.icontains("foo%bar", autoescape=True) Will render as:: lower(somecolumn) LIKE '%' || lower(:param) || '%' ESCAPE '/' With the value of ``:param`` as ``"foo/%bar"``. :param escape: a character which when given will render with the ``ESCAPE`` keyword to establish that character as the escape character. This character can then be placed preceding occurrences of ``%`` and ``_`` to allow them to act as themselves and not wildcard characters. An expression such as:: somecolumn.icontains("foo/%bar", escape="^") Will render as:: lower(somecolumn) LIKE '%' || lower(:param) || '%' ESCAPE '^' The parameter may also be combined with :paramref:`.ColumnOperators.contains.autoescape`:: somecolumn.icontains("foo%bar^bat", escape="^", autoescape=True) Where above, the given literal parameter will be converted to ``"foo^%bar^^bat"`` before being passed to the database. .. seealso:: :meth:`.ColumnOperators.contains` """ return self.operate(icontains_op, other, **kw)
(self, other: Any, **kw: Any) -> sqlalchemy.sql.operators.ColumnOperators
16,094
sqlalchemy.sql.operators
iendswith
Implement the ``iendswith`` operator, e.g. case insensitive version of :meth:`.ColumnOperators.endswith`. Produces a LIKE expression that tests against an insensitive match for the end of a string value:: lower(column) LIKE '%' || lower(<other>) E.g.:: stmt = select(sometable).\ where(sometable.c.column.iendswith("foobar")) Since the operator uses ``LIKE``, wildcard characters ``"%"`` and ``"_"`` that are present inside the <other> expression will behave like wildcards as well. For literal string values, the :paramref:`.ColumnOperators.iendswith.autoescape` flag may be set to ``True`` to apply escaping to occurrences of these characters within the string value so that they match as themselves and not as wildcard characters. Alternatively, the :paramref:`.ColumnOperators.iendswith.escape` parameter will establish a given character as an escape character which can be of use when the target expression is not a literal string. :param other: expression to be compared. This is usually a plain string value, but can also be an arbitrary SQL expression. LIKE wildcard characters ``%`` and ``_`` are not escaped by default unless the :paramref:`.ColumnOperators.iendswith.autoescape` flag is set to True. :param autoescape: boolean; when True, establishes an escape character within the LIKE expression, then applies it to all occurrences of ``"%"``, ``"_"`` and the escape character itself within the comparison value, which is assumed to be a literal string and not a SQL expression. An expression such as:: somecolumn.iendswith("foo%bar", autoescape=True) Will render as:: lower(somecolumn) LIKE '%' || lower(:param) ESCAPE '/' With the value of ``:param`` as ``"foo/%bar"``. :param escape: a character which when given will render with the ``ESCAPE`` keyword to establish that character as the escape character. This character can then be placed preceding occurrences of ``%`` and ``_`` to allow them to act as themselves and not wildcard characters. An expression such as:: somecolumn.iendswith("foo/%bar", escape="^") Will render as:: lower(somecolumn) LIKE '%' || lower(:param) ESCAPE '^' The parameter may also be combined with :paramref:`.ColumnOperators.iendswith.autoescape`:: somecolumn.endswith("foo%bar^bat", escape="^", autoescape=True) Where above, the given literal parameter will be converted to ``"foo^%bar^^bat"`` before being passed to the database. .. seealso:: :meth:`.ColumnOperators.endswith`
def iendswith( self, other: Any, escape: Optional[str] = None, autoescape: bool = False, ) -> ColumnOperators: r"""Implement the ``iendswith`` operator, e.g. case insensitive version of :meth:`.ColumnOperators.endswith`. Produces a LIKE expression that tests against an insensitive match for the end of a string value:: lower(column) LIKE '%' || lower(<other>) E.g.:: stmt = select(sometable).\ where(sometable.c.column.iendswith("foobar")) Since the operator uses ``LIKE``, wildcard characters ``"%"`` and ``"_"`` that are present inside the <other> expression will behave like wildcards as well. For literal string values, the :paramref:`.ColumnOperators.iendswith.autoescape` flag may be set to ``True`` to apply escaping to occurrences of these characters within the string value so that they match as themselves and not as wildcard characters. Alternatively, the :paramref:`.ColumnOperators.iendswith.escape` parameter will establish a given character as an escape character which can be of use when the target expression is not a literal string. :param other: expression to be compared. This is usually a plain string value, but can also be an arbitrary SQL expression. LIKE wildcard characters ``%`` and ``_`` are not escaped by default unless the :paramref:`.ColumnOperators.iendswith.autoescape` flag is set to True. :param autoescape: boolean; when True, establishes an escape character within the LIKE expression, then applies it to all occurrences of ``"%"``, ``"_"`` and the escape character itself within the comparison value, which is assumed to be a literal string and not a SQL expression. An expression such as:: somecolumn.iendswith("foo%bar", autoescape=True) Will render as:: lower(somecolumn) LIKE '%' || lower(:param) ESCAPE '/' With the value of ``:param`` as ``"foo/%bar"``. :param escape: a character which when given will render with the ``ESCAPE`` keyword to establish that character as the escape character. This character can then be placed preceding occurrences of ``%`` and ``_`` to allow them to act as themselves and not wildcard characters. An expression such as:: somecolumn.iendswith("foo/%bar", escape="^") Will render as:: lower(somecolumn) LIKE '%' || lower(:param) ESCAPE '^' The parameter may also be combined with :paramref:`.ColumnOperators.iendswith.autoescape`:: somecolumn.endswith("foo%bar^bat", escape="^", autoescape=True) Where above, the given literal parameter will be converted to ``"foo^%bar^^bat"`` before being passed to the database. .. seealso:: :meth:`.ColumnOperators.endswith` """ return self.operate( iendswith_op, other, escape=escape, autoescape=autoescape )
(self, other: Any, escape: Optional[str] = None, autoescape: bool = False) -> sqlalchemy.sql.operators.ColumnOperators
16,095
sqlalchemy.sql.operators
ilike
Implement the ``ilike`` operator, e.g. case insensitive LIKE. In a column context, produces an expression either of the form:: lower(a) LIKE lower(other) Or on backends that support the ILIKE operator:: a ILIKE other E.g.:: stmt = select(sometable).\ where(sometable.c.column.ilike("%foobar%")) :param other: expression to be compared :param escape: optional escape character, renders the ``ESCAPE`` keyword, e.g.:: somecolumn.ilike("foo/%bar", escape="/") .. seealso:: :meth:`.ColumnOperators.like`
def ilike( self, other: Any, escape: Optional[str] = None ) -> ColumnOperators: r"""Implement the ``ilike`` operator, e.g. case insensitive LIKE. In a column context, produces an expression either of the form:: lower(a) LIKE lower(other) Or on backends that support the ILIKE operator:: a ILIKE other E.g.:: stmt = select(sometable).\ where(sometable.c.column.ilike("%foobar%")) :param other: expression to be compared :param escape: optional escape character, renders the ``ESCAPE`` keyword, e.g.:: somecolumn.ilike("foo/%bar", escape="/") .. seealso:: :meth:`.ColumnOperators.like` """ return self.operate(ilike_op, other, escape=escape)
(self, other: Any, escape: Optional[str] = None) -> sqlalchemy.sql.operators.ColumnOperators
16,096
sqlalchemy.sql.operators
in_
Implement the ``in`` operator. In a column context, produces the clause ``column IN <other>``. The given parameter ``other`` may be: * A list of literal values, e.g.:: stmt.where(column.in_([1, 2, 3])) In this calling form, the list of items is converted to a set of bound parameters the same length as the list given:: WHERE COL IN (?, ?, ?) * A list of tuples may be provided if the comparison is against a :func:`.tuple_` containing multiple expressions:: from sqlalchemy import tuple_ stmt.where(tuple_(col1, col2).in_([(1, 10), (2, 20), (3, 30)])) * An empty list, e.g.:: stmt.where(column.in_([])) In this calling form, the expression renders an "empty set" expression. These expressions are tailored to individual backends and are generally trying to get an empty SELECT statement as a subquery. Such as on SQLite, the expression is:: WHERE col IN (SELECT 1 FROM (SELECT 1) WHERE 1!=1) .. versionchanged:: 1.4 empty IN expressions now use an execution-time generated SELECT subquery in all cases. * A bound parameter, e.g. :func:`.bindparam`, may be used if it includes the :paramref:`.bindparam.expanding` flag:: stmt.where(column.in_(bindparam('value', expanding=True))) In this calling form, the expression renders a special non-SQL placeholder expression that looks like:: WHERE COL IN ([EXPANDING_value]) This placeholder expression is intercepted at statement execution time to be converted into the variable number of bound parameter form illustrated earlier. If the statement were executed as:: connection.execute(stmt, {"value": [1, 2, 3]}) The database would be passed a bound parameter for each value:: WHERE COL IN (?, ?, ?) .. versionadded:: 1.2 added "expanding" bound parameters If an empty list is passed, a special "empty list" expression, which is specific to the database in use, is rendered. On SQLite this would be:: WHERE COL IN (SELECT 1 FROM (SELECT 1) WHERE 1!=1) .. versionadded:: 1.3 "expanding" bound parameters now support empty lists * a :func:`_expression.select` construct, which is usually a correlated scalar select:: stmt.where( column.in_( select(othertable.c.y). where(table.c.x == othertable.c.x) ) ) In this calling form, :meth:`.ColumnOperators.in_` renders as given:: WHERE COL IN (SELECT othertable.y FROM othertable WHERE othertable.x = table.x) :param other: a list of literals, a :func:`_expression.select` construct, or a :func:`.bindparam` construct that includes the :paramref:`.bindparam.expanding` flag set to True.
def in_(self, other: Any) -> ColumnOperators: """Implement the ``in`` operator. In a column context, produces the clause ``column IN <other>``. The given parameter ``other`` may be: * A list of literal values, e.g.:: stmt.where(column.in_([1, 2, 3])) In this calling form, the list of items is converted to a set of bound parameters the same length as the list given:: WHERE COL IN (?, ?, ?) * A list of tuples may be provided if the comparison is against a :func:`.tuple_` containing multiple expressions:: from sqlalchemy import tuple_ stmt.where(tuple_(col1, col2).in_([(1, 10), (2, 20), (3, 30)])) * An empty list, e.g.:: stmt.where(column.in_([])) In this calling form, the expression renders an "empty set" expression. These expressions are tailored to individual backends and are generally trying to get an empty SELECT statement as a subquery. Such as on SQLite, the expression is:: WHERE col IN (SELECT 1 FROM (SELECT 1) WHERE 1!=1) .. versionchanged:: 1.4 empty IN expressions now use an execution-time generated SELECT subquery in all cases. * A bound parameter, e.g. :func:`.bindparam`, may be used if it includes the :paramref:`.bindparam.expanding` flag:: stmt.where(column.in_(bindparam('value', expanding=True))) In this calling form, the expression renders a special non-SQL placeholder expression that looks like:: WHERE COL IN ([EXPANDING_value]) This placeholder expression is intercepted at statement execution time to be converted into the variable number of bound parameter form illustrated earlier. If the statement were executed as:: connection.execute(stmt, {"value": [1, 2, 3]}) The database would be passed a bound parameter for each value:: WHERE COL IN (?, ?, ?) .. versionadded:: 1.2 added "expanding" bound parameters If an empty list is passed, a special "empty list" expression, which is specific to the database in use, is rendered. On SQLite this would be:: WHERE COL IN (SELECT 1 FROM (SELECT 1) WHERE 1!=1) .. versionadded:: 1.3 "expanding" bound parameters now support empty lists * a :func:`_expression.select` construct, which is usually a correlated scalar select:: stmt.where( column.in_( select(othertable.c.y). where(table.c.x == othertable.c.x) ) ) In this calling form, :meth:`.ColumnOperators.in_` renders as given:: WHERE COL IN (SELECT othertable.y FROM othertable WHERE othertable.x = table.x) :param other: a list of literals, a :func:`_expression.select` construct, or a :func:`.bindparam` construct that includes the :paramref:`.bindparam.expanding` flag set to True. """ return self.operate(in_op, other)
(self, other: Any) -> sqlalchemy.sql.operators.ColumnOperators
16,097
sqlalchemy.sql.operators
is_
Implement the ``IS`` operator. Normally, ``IS`` is generated automatically when comparing to a value of ``None``, which resolves to ``NULL``. However, explicit usage of ``IS`` may be desirable if comparing to boolean values on certain platforms. .. seealso:: :meth:`.ColumnOperators.is_not`
def is_(self, other: Any) -> ColumnOperators: """Implement the ``IS`` operator. Normally, ``IS`` is generated automatically when comparing to a value of ``None``, which resolves to ``NULL``. However, explicit usage of ``IS`` may be desirable if comparing to boolean values on certain platforms. .. seealso:: :meth:`.ColumnOperators.is_not` """ return self.operate(is_, other)
(self, other: Any) -> sqlalchemy.sql.operators.ColumnOperators
16,098
sqlalchemy.sql.selectable
is_derived_from
Return ``True`` if this :class:`_expression.FromClause` is 'derived' from the given ``FromClause``. An example would be an Alias of a Table is derived from that Table.
def is_derived_from(self, fromclause: Optional[FromClause]) -> bool: """Return ``True`` if this :class:`_expression.FromClause` is 'derived' from the given ``FromClause``. An example would be an Alias of a Table is derived from that Table. """ # this is essentially an "identity" check in the base class. # Other constructs override this to traverse through # contained elements. return fromclause in self._cloned_set
(self, fromclause: Optional[sqlalchemy.sql.selectable.FromClause]) -> bool
16,099
sqlalchemy.sql.operators
is_distinct_from
Implement the ``IS DISTINCT FROM`` operator. Renders "a IS DISTINCT FROM b" on most platforms; on some such as SQLite may render "a IS NOT b".
def is_distinct_from(self, other: Any) -> ColumnOperators: """Implement the ``IS DISTINCT FROM`` operator. Renders "a IS DISTINCT FROM b" on most platforms; on some such as SQLite may render "a IS NOT b". """ return self.operate(is_distinct_from, other)
(self, other: Any) -> sqlalchemy.sql.operators.ColumnOperators
16,100
sqlalchemy.sql.operators
is_not
Implement the ``IS NOT`` operator. Normally, ``IS NOT`` is generated automatically when comparing to a value of ``None``, which resolves to ``NULL``. However, explicit usage of ``IS NOT`` may be desirable if comparing to boolean values on certain platforms. .. versionchanged:: 1.4 The ``is_not()`` operator is renamed from ``isnot()`` in previous releases. The previous name remains available for backwards compatibility. .. seealso:: :meth:`.ColumnOperators.is_`
def is_not(self, other: Any) -> ColumnOperators: """Implement the ``IS NOT`` operator. Normally, ``IS NOT`` is generated automatically when comparing to a value of ``None``, which resolves to ``NULL``. However, explicit usage of ``IS NOT`` may be desirable if comparing to boolean values on certain platforms. .. versionchanged:: 1.4 The ``is_not()`` operator is renamed from ``isnot()`` in previous releases. The previous name remains available for backwards compatibility. .. seealso:: :meth:`.ColumnOperators.is_` """ return self.operate(is_not, other)
(self, other: Any) -> sqlalchemy.sql.operators.ColumnOperators
16,101
sqlalchemy.sql.operators
is_not_distinct_from
Implement the ``IS NOT DISTINCT FROM`` operator. Renders "a IS NOT DISTINCT FROM b" on most platforms; on some such as SQLite may render "a IS b". .. versionchanged:: 1.4 The ``is_not_distinct_from()`` operator is renamed from ``isnot_distinct_from()`` in previous releases. The previous name remains available for backwards compatibility.
def is_not_distinct_from(self, other: Any) -> ColumnOperators: """Implement the ``IS NOT DISTINCT FROM`` operator. Renders "a IS NOT DISTINCT FROM b" on most platforms; on some such as SQLite may render "a IS b". .. versionchanged:: 1.4 The ``is_not_distinct_from()`` operator is renamed from ``isnot_distinct_from()`` in previous releases. The previous name remains available for backwards compatibility. """ return self.operate(is_not_distinct_from, other)
(self, other: Any) -> sqlalchemy.sql.operators.ColumnOperators
16,104
sqlalchemy.sql.operators
istartswith
Implement the ``istartswith`` operator, e.g. case insensitive version of :meth:`.ColumnOperators.startswith`. Produces a LIKE expression that tests against an insensitive match for the start of a string value:: lower(column) LIKE lower(<other>) || '%' E.g.:: stmt = select(sometable).\ where(sometable.c.column.istartswith("foobar")) Since the operator uses ``LIKE``, wildcard characters ``"%"`` and ``"_"`` that are present inside the <other> expression will behave like wildcards as well. For literal string values, the :paramref:`.ColumnOperators.istartswith.autoescape` flag may be set to ``True`` to apply escaping to occurrences of these characters within the string value so that they match as themselves and not as wildcard characters. Alternatively, the :paramref:`.ColumnOperators.istartswith.escape` parameter will establish a given character as an escape character which can be of use when the target expression is not a literal string. :param other: expression to be compared. This is usually a plain string value, but can also be an arbitrary SQL expression. LIKE wildcard characters ``%`` and ``_`` are not escaped by default unless the :paramref:`.ColumnOperators.istartswith.autoescape` flag is set to True. :param autoescape: boolean; when True, establishes an escape character within the LIKE expression, then applies it to all occurrences of ``"%"``, ``"_"`` and the escape character itself within the comparison value, which is assumed to be a literal string and not a SQL expression. An expression such as:: somecolumn.istartswith("foo%bar", autoescape=True) Will render as:: lower(somecolumn) LIKE lower(:param) || '%' ESCAPE '/' With the value of ``:param`` as ``"foo/%bar"``. :param escape: a character which when given will render with the ``ESCAPE`` keyword to establish that character as the escape character. This character can then be placed preceding occurrences of ``%`` and ``_`` to allow them to act as themselves and not wildcard characters. An expression such as:: somecolumn.istartswith("foo/%bar", escape="^") Will render as:: lower(somecolumn) LIKE lower(:param) || '%' ESCAPE '^' The parameter may also be combined with :paramref:`.ColumnOperators.istartswith.autoescape`:: somecolumn.istartswith("foo%bar^bat", escape="^", autoescape=True) Where above, the given literal parameter will be converted to ``"foo^%bar^^bat"`` before being passed to the database. .. seealso:: :meth:`.ColumnOperators.startswith`
def istartswith( self, other: Any, escape: Optional[str] = None, autoescape: bool = False, ) -> ColumnOperators: r"""Implement the ``istartswith`` operator, e.g. case insensitive version of :meth:`.ColumnOperators.startswith`. Produces a LIKE expression that tests against an insensitive match for the start of a string value:: lower(column) LIKE lower(<other>) || '%' E.g.:: stmt = select(sometable).\ where(sometable.c.column.istartswith("foobar")) Since the operator uses ``LIKE``, wildcard characters ``"%"`` and ``"_"`` that are present inside the <other> expression will behave like wildcards as well. For literal string values, the :paramref:`.ColumnOperators.istartswith.autoescape` flag may be set to ``True`` to apply escaping to occurrences of these characters within the string value so that they match as themselves and not as wildcard characters. Alternatively, the :paramref:`.ColumnOperators.istartswith.escape` parameter will establish a given character as an escape character which can be of use when the target expression is not a literal string. :param other: expression to be compared. This is usually a plain string value, but can also be an arbitrary SQL expression. LIKE wildcard characters ``%`` and ``_`` are not escaped by default unless the :paramref:`.ColumnOperators.istartswith.autoescape` flag is set to True. :param autoescape: boolean; when True, establishes an escape character within the LIKE expression, then applies it to all occurrences of ``"%"``, ``"_"`` and the escape character itself within the comparison value, which is assumed to be a literal string and not a SQL expression. An expression such as:: somecolumn.istartswith("foo%bar", autoescape=True) Will render as:: lower(somecolumn) LIKE lower(:param) || '%' ESCAPE '/' With the value of ``:param`` as ``"foo/%bar"``. :param escape: a character which when given will render with the ``ESCAPE`` keyword to establish that character as the escape character. This character can then be placed preceding occurrences of ``%`` and ``_`` to allow them to act as themselves and not wildcard characters. An expression such as:: somecolumn.istartswith("foo/%bar", escape="^") Will render as:: lower(somecolumn) LIKE lower(:param) || '%' ESCAPE '^' The parameter may also be combined with :paramref:`.ColumnOperators.istartswith.autoescape`:: somecolumn.istartswith("foo%bar^bat", escape="^", autoescape=True) Where above, the given literal parameter will be converted to ``"foo^%bar^^bat"`` before being passed to the database. .. seealso:: :meth:`.ColumnOperators.startswith` """ return self.operate( istartswith_op, other, escape=escape, autoescape=autoescape )
(self, other: Any, escape: Optional[str] = None, autoescape: bool = False) -> sqlalchemy.sql.operators.ColumnOperators
16,105
sqlalchemy.sql.selectable
join
Return a :class:`_expression.Join` from this :class:`_expression.FromClause` to another :class:`FromClause`. E.g.:: from sqlalchemy import join j = user_table.join(address_table, user_table.c.id == address_table.c.user_id) stmt = select(user_table).select_from(j) would emit SQL along the lines of:: SELECT user.id, user.name FROM user JOIN address ON user.id = address.user_id :param right: the right side of the join; this is any :class:`_expression.FromClause` object such as a :class:`_schema.Table` object, and may also be a selectable-compatible object such as an ORM-mapped class. :param onclause: a SQL expression representing the ON clause of the join. If left at ``None``, :meth:`_expression.FromClause.join` will attempt to join the two tables based on a foreign key relationship. :param isouter: if True, render a LEFT OUTER JOIN, instead of JOIN. :param full: if True, render a FULL OUTER JOIN, instead of LEFT OUTER JOIN. Implies :paramref:`.FromClause.join.isouter`. .. seealso:: :func:`_expression.join` - standalone function :class:`_expression.Join` - the type of object produced
def join( self, right: _FromClauseArgument, onclause: Optional[_ColumnExpressionArgument[bool]] = None, isouter: bool = False, full: bool = False, ) -> Join: """Return a :class:`_expression.Join` from this :class:`_expression.FromClause` to another :class:`FromClause`. E.g.:: from sqlalchemy import join j = user_table.join(address_table, user_table.c.id == address_table.c.user_id) stmt = select(user_table).select_from(j) would emit SQL along the lines of:: SELECT user.id, user.name FROM user JOIN address ON user.id = address.user_id :param right: the right side of the join; this is any :class:`_expression.FromClause` object such as a :class:`_schema.Table` object, and may also be a selectable-compatible object such as an ORM-mapped class. :param onclause: a SQL expression representing the ON clause of the join. If left at ``None``, :meth:`_expression.FromClause.join` will attempt to join the two tables based on a foreign key relationship. :param isouter: if True, render a LEFT OUTER JOIN, instead of JOIN. :param full: if True, render a FULL OUTER JOIN, instead of LEFT OUTER JOIN. Implies :paramref:`.FromClause.join.isouter`. .. seealso:: :func:`_expression.join` - standalone function :class:`_expression.Join` - the type of object produced """ return Join(self, right, onclause, isouter, full)
(self, right: '_FromClauseArgument', onclause: 'Optional[_ColumnExpressionArgument[bool]]' = None, isouter: 'bool' = False, full: 'bool' = False) -> 'Join'
16,106
sqlalchemy.sql.elements
label
Produce a column label, i.e. ``<columnname> AS <name>``. This is a shortcut to the :func:`_expression.label` function. If 'name' is ``None``, an anonymous label name will be generated.
def label(self, name: Optional[str]) -> Label[_T]: """Produce a column label, i.e. ``<columnname> AS <name>``. This is a shortcut to the :func:`_expression.label` function. If 'name' is ``None``, an anonymous label name will be generated. """ return Label(name, self, self.type)
(self, name: Optional[str]) -> sqlalchemy.sql.elements.Label[~_T]
16,107
sqlalchemy.sql.selectable
lateral
Return a LATERAL alias of this :class:`_expression.Selectable`. The return value is the :class:`_expression.Lateral` construct also provided by the top-level :func:`_expression.lateral` function. .. seealso:: :ref:`tutorial_lateral_correlation` - overview of usage.
def lateral(self, name: Optional[str] = None) -> LateralFromClause: """Return a LATERAL alias of this :class:`_expression.Selectable`. The return value is the :class:`_expression.Lateral` construct also provided by the top-level :func:`_expression.lateral` function. .. seealso:: :ref:`tutorial_lateral_correlation` - overview of usage. """ return Lateral._construct(self, name=name)
(self, name: Optional[str] = None) -> sqlalchemy.sql.selectable.LateralFromClause
16,108
sqlalchemy.sql.operators
like
Implement the ``like`` operator. In a column context, produces the expression:: a LIKE other E.g.:: stmt = select(sometable).\ where(sometable.c.column.like("%foobar%")) :param other: expression to be compared :param escape: optional escape character, renders the ``ESCAPE`` keyword, e.g.:: somecolumn.like("foo/%bar", escape="/") .. seealso:: :meth:`.ColumnOperators.ilike`
def like( self, other: Any, escape: Optional[str] = None ) -> ColumnOperators: r"""Implement the ``like`` operator. In a column context, produces the expression:: a LIKE other E.g.:: stmt = select(sometable).\ where(sometable.c.column.like("%foobar%")) :param other: expression to be compared :param escape: optional escape character, renders the ``ESCAPE`` keyword, e.g.:: somecolumn.like("foo/%bar", escape="/") .. seealso:: :meth:`.ColumnOperators.ilike` """ return self.operate(like_op, other, escape=escape)
(self, other: Any, escape: Optional[str] = None) -> sqlalchemy.sql.operators.ColumnOperators
16,109
sqlalchemy.sql.operators
match
Implements a database-specific 'match' operator. :meth:`_sql.ColumnOperators.match` attempts to resolve to a MATCH-like function or operator provided by the backend. Examples include: * PostgreSQL - renders ``x @@ plainto_tsquery(y)`` .. versionchanged:: 2.0 ``plainto_tsquery()`` is used instead of ``to_tsquery()`` for PostgreSQL now; for compatibility with other forms, see :ref:`postgresql_match`. * MySQL - renders ``MATCH (x) AGAINST (y IN BOOLEAN MODE)`` .. seealso:: :class:`_mysql.match` - MySQL specific construct with additional features. * Oracle - renders ``CONTAINS(x, y)`` * other backends may provide special implementations. * Backends without any special implementation will emit the operator as "MATCH". This is compatible with SQLite, for example.
def match(self, other: Any, **kwargs: Any) -> ColumnOperators: """Implements a database-specific 'match' operator. :meth:`_sql.ColumnOperators.match` attempts to resolve to a MATCH-like function or operator provided by the backend. Examples include: * PostgreSQL - renders ``x @@ plainto_tsquery(y)`` .. versionchanged:: 2.0 ``plainto_tsquery()`` is used instead of ``to_tsquery()`` for PostgreSQL now; for compatibility with other forms, see :ref:`postgresql_match`. * MySQL - renders ``MATCH (x) AGAINST (y IN BOOLEAN MODE)`` .. seealso:: :class:`_mysql.match` - MySQL specific construct with additional features. * Oracle - renders ``CONTAINS(x, y)`` * other backends may provide special implementations. * Backends without any special implementation will emit the operator as "MATCH". This is compatible with SQLite, for example. """ return self.operate(match_op, other, **kwargs)
(self, other: Any, **kwargs: Any) -> sqlalchemy.sql.operators.ColumnOperators
16,110
sqlalchemy.sql.operators
not_ilike
implement the ``NOT ILIKE`` operator. This is equivalent to using negation with :meth:`.ColumnOperators.ilike`, i.e. ``~x.ilike(y)``. .. versionchanged:: 1.4 The ``not_ilike()`` operator is renamed from ``notilike()`` in previous releases. The previous name remains available for backwards compatibility. .. seealso:: :meth:`.ColumnOperators.ilike`
def not_ilike( self, other: Any, escape: Optional[str] = None ) -> ColumnOperators: """implement the ``NOT ILIKE`` operator. This is equivalent to using negation with :meth:`.ColumnOperators.ilike`, i.e. ``~x.ilike(y)``. .. versionchanged:: 1.4 The ``not_ilike()`` operator is renamed from ``notilike()`` in previous releases. The previous name remains available for backwards compatibility. .. seealso:: :meth:`.ColumnOperators.ilike` """ return self.operate(not_ilike_op, other, escape=escape)
(self, other: Any, escape: Optional[str] = None) -> sqlalchemy.sql.operators.ColumnOperators
16,111
sqlalchemy.sql.operators
not_in
implement the ``NOT IN`` operator. This is equivalent to using negation with :meth:`.ColumnOperators.in_`, i.e. ``~x.in_(y)``. In the case that ``other`` is an empty sequence, the compiler produces an "empty not in" expression. This defaults to the expression "1 = 1" to produce true in all cases. The :paramref:`_sa.create_engine.empty_in_strategy` may be used to alter this behavior. .. versionchanged:: 1.4 The ``not_in()`` operator is renamed from ``notin_()`` in previous releases. The previous name remains available for backwards compatibility. .. versionchanged:: 1.2 The :meth:`.ColumnOperators.in_` and :meth:`.ColumnOperators.not_in` operators now produce a "static" expression for an empty IN sequence by default. .. seealso:: :meth:`.ColumnOperators.in_`
def not_in(self, other: Any) -> ColumnOperators: """implement the ``NOT IN`` operator. This is equivalent to using negation with :meth:`.ColumnOperators.in_`, i.e. ``~x.in_(y)``. In the case that ``other`` is an empty sequence, the compiler produces an "empty not in" expression. This defaults to the expression "1 = 1" to produce true in all cases. The :paramref:`_sa.create_engine.empty_in_strategy` may be used to alter this behavior. .. versionchanged:: 1.4 The ``not_in()`` operator is renamed from ``notin_()`` in previous releases. The previous name remains available for backwards compatibility. .. versionchanged:: 1.2 The :meth:`.ColumnOperators.in_` and :meth:`.ColumnOperators.not_in` operators now produce a "static" expression for an empty IN sequence by default. .. seealso:: :meth:`.ColumnOperators.in_` """ return self.operate(not_in_op, other)
(self, other: Any) -> sqlalchemy.sql.operators.ColumnOperators
16,112
sqlalchemy.sql.operators
not_like
implement the ``NOT LIKE`` operator. This is equivalent to using negation with :meth:`.ColumnOperators.like`, i.e. ``~x.like(y)``. .. versionchanged:: 1.4 The ``not_like()`` operator is renamed from ``notlike()`` in previous releases. The previous name remains available for backwards compatibility. .. seealso:: :meth:`.ColumnOperators.like`
def not_like( self, other: Any, escape: Optional[str] = None ) -> ColumnOperators: """implement the ``NOT LIKE`` operator. This is equivalent to using negation with :meth:`.ColumnOperators.like`, i.e. ``~x.like(y)``. .. versionchanged:: 1.4 The ``not_like()`` operator is renamed from ``notlike()`` in previous releases. The previous name remains available for backwards compatibility. .. seealso:: :meth:`.ColumnOperators.like` """ return self.operate(not_like_op, other, escape=escape)
(self, other: Any, escape: Optional[str] = None) -> sqlalchemy.sql.operators.ColumnOperators
16,116
sqlalchemy.sql.operators
nulls_first
Produce a :func:`_expression.nulls_first` clause against the parent object. .. versionchanged:: 1.4 The ``nulls_first()`` operator is renamed from ``nullsfirst()`` in previous releases. The previous name remains available for backwards compatibility.
def nulls_first(self) -> ColumnOperators: """Produce a :func:`_expression.nulls_first` clause against the parent object. .. versionchanged:: 1.4 The ``nulls_first()`` operator is renamed from ``nullsfirst()`` in previous releases. The previous name remains available for backwards compatibility. """ return self.operate(nulls_first_op)
(self) -> sqlalchemy.sql.operators.ColumnOperators
16,117
sqlalchemy.sql.operators
nulls_last
Produce a :func:`_expression.nulls_last` clause against the parent object. .. versionchanged:: 1.4 The ``nulls_last()`` operator is renamed from ``nullslast()`` in previous releases. The previous name remains available for backwards compatibility.
def nulls_last(self) -> ColumnOperators: """Produce a :func:`_expression.nulls_last` clause against the parent object. .. versionchanged:: 1.4 The ``nulls_last()`` operator is renamed from ``nullslast()`` in previous releases. The previous name remains available for backwards compatibility. """ return self.operate(nulls_last_op)
(self) -> sqlalchemy.sql.operators.ColumnOperators
16,120
sqlalchemy.sql.operators
op
Produce a generic operator function. e.g.:: somecolumn.op("*")(5) produces:: somecolumn * 5 This function can also be used to make bitwise operators explicit. For example:: somecolumn.op('&')(0xff) is a bitwise AND of the value in ``somecolumn``. :param opstring: a string which will be output as the infix operator between this element and the expression passed to the generated function. :param precedence: precedence which the database is expected to apply to the operator in SQL expressions. This integer value acts as a hint for the SQL compiler to know when explicit parenthesis should be rendered around a particular operation. A lower number will cause the expression to be parenthesized when applied against another operator with higher precedence. The default value of ``0`` is lower than all operators except for the comma (``,``) and ``AS`` operators. A value of 100 will be higher or equal to all operators, and -100 will be lower than or equal to all operators. .. seealso:: :ref:`faq_sql_expression_op_parenthesis` - detailed description of how the SQLAlchemy SQL compiler renders parenthesis :param is_comparison: legacy; if True, the operator will be considered as a "comparison" operator, that is which evaluates to a boolean true/false value, like ``==``, ``>``, etc. This flag is provided so that ORM relationships can establish that the operator is a comparison operator when used in a custom join condition. Using the ``is_comparison`` parameter is superseded by using the :meth:`.Operators.bool_op` method instead; this more succinct operator sets this parameter automatically, but also provides correct :pep:`484` typing support as the returned object will express a "boolean" datatype, i.e. ``BinaryExpression[bool]``. :param return_type: a :class:`.TypeEngine` class or object that will force the return type of an expression produced by this operator to be of that type. By default, operators that specify :paramref:`.Operators.op.is_comparison` will resolve to :class:`.Boolean`, and those that do not will be of the same type as the left-hand operand. :param python_impl: an optional Python function that can evaluate two Python values in the same way as this operator works when run on the database server. Useful for in-Python SQL expression evaluation functions, such as for ORM hybrid attributes, and the ORM "evaluator" used to match objects in a session after a multi-row update or delete. e.g.:: >>> expr = column('x').op('+', python_impl=lambda a, b: a + b)('y') The operator for the above expression will also work for non-SQL left and right objects:: >>> expr.operator(5, 10) 15 .. versionadded:: 2.0 .. seealso:: :meth:`.Operators.bool_op` :ref:`types_operators` :ref:`relationship_custom_operator`
def op( self, opstring: str, precedence: int = 0, is_comparison: bool = False, return_type: Optional[ Union[Type[TypeEngine[Any]], TypeEngine[Any]] ] = None, python_impl: Optional[Callable[..., Any]] = None, ) -> Callable[[Any], Operators]: """Produce a generic operator function. e.g.:: somecolumn.op("*")(5) produces:: somecolumn * 5 This function can also be used to make bitwise operators explicit. For example:: somecolumn.op('&')(0xff) is a bitwise AND of the value in ``somecolumn``. :param opstring: a string which will be output as the infix operator between this element and the expression passed to the generated function. :param precedence: precedence which the database is expected to apply to the operator in SQL expressions. This integer value acts as a hint for the SQL compiler to know when explicit parenthesis should be rendered around a particular operation. A lower number will cause the expression to be parenthesized when applied against another operator with higher precedence. The default value of ``0`` is lower than all operators except for the comma (``,``) and ``AS`` operators. A value of 100 will be higher or equal to all operators, and -100 will be lower than or equal to all operators. .. seealso:: :ref:`faq_sql_expression_op_parenthesis` - detailed description of how the SQLAlchemy SQL compiler renders parenthesis :param is_comparison: legacy; if True, the operator will be considered as a "comparison" operator, that is which evaluates to a boolean true/false value, like ``==``, ``>``, etc. This flag is provided so that ORM relationships can establish that the operator is a comparison operator when used in a custom join condition. Using the ``is_comparison`` parameter is superseded by using the :meth:`.Operators.bool_op` method instead; this more succinct operator sets this parameter automatically, but also provides correct :pep:`484` typing support as the returned object will express a "boolean" datatype, i.e. ``BinaryExpression[bool]``. :param return_type: a :class:`.TypeEngine` class or object that will force the return type of an expression produced by this operator to be of that type. By default, operators that specify :paramref:`.Operators.op.is_comparison` will resolve to :class:`.Boolean`, and those that do not will be of the same type as the left-hand operand. :param python_impl: an optional Python function that can evaluate two Python values in the same way as this operator works when run on the database server. Useful for in-Python SQL expression evaluation functions, such as for ORM hybrid attributes, and the ORM "evaluator" used to match objects in a session after a multi-row update or delete. e.g.:: >>> expr = column('x').op('+', python_impl=lambda a, b: a + b)('y') The operator for the above expression will also work for non-SQL left and right objects:: >>> expr.operator(5, 10) 15 .. versionadded:: 2.0 .. seealso:: :meth:`.Operators.bool_op` :ref:`types_operators` :ref:`relationship_custom_operator` """ operator = custom_op( opstring, precedence, is_comparison, return_type, python_impl=python_impl, ) def against(other: Any) -> Operators: return operator(self, other) return against
(self, opstring: 'str', precedence: 'int' = 0, is_comparison: 'bool' = False, return_type: 'Optional[Union[Type[TypeEngine[Any]], TypeEngine[Any]]]' = None, python_impl: 'Optional[Callable[..., Any]]' = None) -> 'Callable[[Any], Operators]'
16,121
sqlalchemy.sql.elements
operate
null
def operate( self, op: operators.OperatorType, *other: Any, **kwargs: Any, ) -> ColumnElement[Any]: return op(self.comparator, *other, **kwargs) # type: ignore[no-any-return] # noqa: E501
(self, op: sqlalchemy.sql.operators.OperatorType, *other: Any, **kwargs: Any) -> sqlalchemy.sql.elements.ColumnElement[typing.Any]
16,122
sqlalchemy.sql.base
options
Apply options to this statement. In the general sense, options are any kind of Python object that can be interpreted by the SQL compiler for the statement. These options can be consumed by specific dialects or specific kinds of compilers. The most commonly known kind of option are the ORM level options that apply "eager load" and other loading behaviors to an ORM query. However, options can theoretically be used for many other purposes. For background on specific kinds of options for specific kinds of statements, refer to the documentation for those option objects. .. versionchanged:: 1.4 - added :meth:`.Executable.options` to Core statement objects towards the goal of allowing unified Core / ORM querying capabilities. .. seealso:: :ref:`loading_columns` - refers to options specific to the usage of ORM queries :ref:`relationship_loader_options` - refers to options specific to the usage of ORM queries
# sql/base.py # Copyright (C) 2005-2024 the SQLAlchemy authors and contributors # <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: https://www.opensource.org/licenses/mit-license.php # mypy: allow-untyped-defs, allow-untyped-calls """Foundational utilities common to many sql modules. """ from __future__ import annotations import collections from enum import Enum import itertools from itertools import zip_longest import operator import re from typing import Any from typing import Callable from typing import cast from typing import Dict from typing import FrozenSet from typing import Generic from typing import Iterable from typing import Iterator from typing import List from typing import Mapping from typing import MutableMapping from typing import NamedTuple from typing import NoReturn from typing import Optional from typing import overload from typing import Sequence from typing import Set from typing import Tuple from typing import Type from typing import TYPE_CHECKING from typing import TypeVar from typing import Union from . import roles from . import visitors from .cache_key import HasCacheKey # noqa from .cache_key import MemoizedHasCacheKey # noqa from .traversals import HasCopyInternals # noqa from .visitors import ClauseVisitor from .visitors import ExtendedInternalTraversal from .visitors import ExternallyTraversible from .visitors import InternalTraversal from .. import event from .. import exc from .. import util from ..util import HasMemoized as HasMemoized from ..util import hybridmethod from ..util import typing as compat_typing from ..util.typing import Protocol from ..util.typing import Self from ..util.typing import TypeGuard if TYPE_CHECKING: from . import coercions from . import elements from . import type_api from ._orm_types import DMLStrategyArgument from ._orm_types import SynchronizeSessionArgument from ._typing import _CLE from .elements import BindParameter from .elements import ClauseList from .elements import ColumnClause # noqa from .elements import ColumnElement from .elements import NamedColumn from .elements import SQLCoreOperations from .elements import TextClause from .schema import Column from .schema import DefaultGenerator from .selectable import _JoinTargetElement from .selectable import _SelectIterable from .selectable import FromClause from ..engine import Connection from ..engine import CursorResult from ..engine.interfaces import _CoreMultiExecuteParams from ..engine.interfaces import _ExecuteOptions from ..engine.interfaces import _ImmutableExecuteOptions from ..engine.interfaces import CacheStats from ..engine.interfaces import Compiled from ..engine.interfaces import CompiledCacheType from ..engine.interfaces import CoreExecuteOptionsParameter from ..engine.interfaces import Dialect from ..engine.interfaces import IsolationLevel from ..engine.interfaces import SchemaTranslateMapType from ..event import dispatcher if not TYPE_CHECKING: coercions = None # noqa elements = None # noqa type_api = None # noqa class _NoArg(Enum): NO_ARG = 0 def __repr__(self): return f"_NoArg.{self.name}"
(self, *options: sqlalchemy.sql.base.ExecutableOption) -> typing_extensions.Self
16,123
sqlalchemy.sql.selectable
outerjoin
Return a :class:`_expression.Join` from this :class:`_expression.FromClause` to another :class:`FromClause`, with the "isouter" flag set to True. E.g.:: from sqlalchemy import outerjoin j = user_table.outerjoin(address_table, user_table.c.id == address_table.c.user_id) The above is equivalent to:: j = user_table.join( address_table, user_table.c.id == address_table.c.user_id, isouter=True) :param right: the right side of the join; this is any :class:`_expression.FromClause` object such as a :class:`_schema.Table` object, and may also be a selectable-compatible object such as an ORM-mapped class. :param onclause: a SQL expression representing the ON clause of the join. If left at ``None``, :meth:`_expression.FromClause.join` will attempt to join the two tables based on a foreign key relationship. :param full: if True, render a FULL OUTER JOIN, instead of LEFT OUTER JOIN. .. seealso:: :meth:`_expression.FromClause.join` :class:`_expression.Join`
def outerjoin( self, right: _FromClauseArgument, onclause: Optional[_ColumnExpressionArgument[bool]] = None, full: bool = False, ) -> Join: """Return a :class:`_expression.Join` from this :class:`_expression.FromClause` to another :class:`FromClause`, with the "isouter" flag set to True. E.g.:: from sqlalchemy import outerjoin j = user_table.outerjoin(address_table, user_table.c.id == address_table.c.user_id) The above is equivalent to:: j = user_table.join( address_table, user_table.c.id == address_table.c.user_id, isouter=True) :param right: the right side of the join; this is any :class:`_expression.FromClause` object such as a :class:`_schema.Table` object, and may also be a selectable-compatible object such as an ORM-mapped class. :param onclause: a SQL expression representing the ON clause of the join. If left at ``None``, :meth:`_expression.FromClause.join` will attempt to join the two tables based on a foreign key relationship. :param full: if True, render a FULL OUTER JOIN, instead of LEFT OUTER JOIN. .. seealso:: :meth:`_expression.FromClause.join` :class:`_expression.Join` """ return Join(self, right, onclause, True, full)
(self, right: '_FromClauseArgument', onclause: 'Optional[_ColumnExpressionArgument[bool]]' = None, full: 'bool' = False) -> 'Join'
16,124
sqlalchemy.sql.functions
over
Produce an OVER clause against this function. Used against aggregate or so-called "window" functions, for database backends that support window functions. The expression:: func.row_number().over(order_by='x') is shorthand for:: from sqlalchemy import over over(func.row_number(), order_by='x') See :func:`_expression.over` for a full description. .. seealso:: :func:`_expression.over` :ref:`tutorial_window_functions` - in the :ref:`unified_tutorial`
def over( self, *, partition_by: Optional[_ByArgument] = None, order_by: Optional[_ByArgument] = None, rows: Optional[Tuple[Optional[int], Optional[int]]] = None, range_: Optional[Tuple[Optional[int], Optional[int]]] = None, ) -> Over[_T]: """Produce an OVER clause against this function. Used against aggregate or so-called "window" functions, for database backends that support window functions. The expression:: func.row_number().over(order_by='x') is shorthand for:: from sqlalchemy import over over(func.row_number(), order_by='x') See :func:`_expression.over` for a full description. .. seealso:: :func:`_expression.over` :ref:`tutorial_window_functions` - in the :ref:`unified_tutorial` """ return Over( self, partition_by=partition_by, order_by=order_by, rows=rows, range_=range_, )
(self, *, partition_by: 'Optional[_ByArgument]' = None, order_by: 'Optional[_ByArgument]' = None, rows: 'Optional[Tuple[Optional[int], Optional[int]]]' = None, range_: 'Optional[Tuple[Optional[int], Optional[int]]]' = None) -> 'Over[_T]'
16,125
sqlalchemy.sql.elements
params
Return a copy with :func:`_expression.bindparam` elements replaced. Returns a copy of this ClauseElement with :func:`_expression.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}
def params( self, __optionaldict: Optional[Mapping[str, Any]] = None, **kwargs: Any, ) -> Self: """Return a copy with :func:`_expression.bindparam` elements replaced. Returns a copy of this ClauseElement with :func:`_expression.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} """ return self._replace_params(False, __optionaldict, kwargs)
(self, _ClauseElement__optionaldict: Optional[Mapping[str, Any]] = None, **kwargs: Any) -> typing_extensions.Self
16,126
sqlalchemy.sql.operators
regexp_match
Implements a database-specific 'regexp match' operator. E.g.:: stmt = select(table.c.some_column).where( table.c.some_column.regexp_match('^(b|c)') ) :meth:`_sql.ColumnOperators.regexp_match` attempts to resolve to a REGEXP-like function or operator provided by the backend, however the specific regular expression syntax and flags available are **not backend agnostic**. Examples include: * PostgreSQL - renders ``x ~ y`` or ``x !~ y`` when negated. * Oracle - renders ``REGEXP_LIKE(x, y)`` * SQLite - uses SQLite's ``REGEXP`` placeholder operator and calls into the Python ``re.match()`` builtin. * other backends may provide special implementations. * Backends without any special implementation will emit the operator as "REGEXP" or "NOT REGEXP". This is compatible with SQLite and MySQL, for example. Regular expression support is currently implemented for Oracle, PostgreSQL, MySQL and MariaDB. Partial support is available for SQLite. Support among third-party dialects may vary. :param pattern: The regular expression pattern string or column clause. :param flags: Any regular expression string flags to apply, passed as plain Python string only. These flags are backend specific. Some backends, like PostgreSQL and MariaDB, may alternatively specify the flags as part of the pattern. When using the ignore case flag 'i' in PostgreSQL, the ignore case regexp match operator ``~*`` or ``!~*`` will be used. .. versionadded:: 1.4 .. versionchanged:: 1.4.48, 2.0.18 Note that due to an implementation error, the "flags" parameter previously accepted SQL expression objects such as column expressions in addition to plain Python strings. This implementation did not work correctly with caching and was removed; strings only should be passed for the "flags" parameter, as these flags are rendered as literal inline values within SQL expressions. .. seealso:: :meth:`_sql.ColumnOperators.regexp_replace`
def regexp_match( self, pattern: Any, flags: Optional[str] = None ) -> ColumnOperators: """Implements a database-specific 'regexp match' operator. E.g.:: stmt = select(table.c.some_column).where( table.c.some_column.regexp_match('^(b|c)') ) :meth:`_sql.ColumnOperators.regexp_match` attempts to resolve to a REGEXP-like function or operator provided by the backend, however the specific regular expression syntax and flags available are **not backend agnostic**. Examples include: * PostgreSQL - renders ``x ~ y`` or ``x !~ y`` when negated. * Oracle - renders ``REGEXP_LIKE(x, y)`` * SQLite - uses SQLite's ``REGEXP`` placeholder operator and calls into the Python ``re.match()`` builtin. * other backends may provide special implementations. * Backends without any special implementation will emit the operator as "REGEXP" or "NOT REGEXP". This is compatible with SQLite and MySQL, for example. Regular expression support is currently implemented for Oracle, PostgreSQL, MySQL and MariaDB. Partial support is available for SQLite. Support among third-party dialects may vary. :param pattern: The regular expression pattern string or column clause. :param flags: Any regular expression string flags to apply, passed as plain Python string only. These flags are backend specific. Some backends, like PostgreSQL and MariaDB, may alternatively specify the flags as part of the pattern. When using the ignore case flag 'i' in PostgreSQL, the ignore case regexp match operator ``~*`` or ``!~*`` will be used. .. versionadded:: 1.4 .. versionchanged:: 1.4.48, 2.0.18 Note that due to an implementation error, the "flags" parameter previously accepted SQL expression objects such as column expressions in addition to plain Python strings. This implementation did not work correctly with caching and was removed; strings only should be passed for the "flags" parameter, as these flags are rendered as literal inline values within SQL expressions. .. seealso:: :meth:`_sql.ColumnOperators.regexp_replace` """ return self.operate(regexp_match_op, pattern, flags=flags)
(self, pattern: Any, flags: Optional[str] = None) -> sqlalchemy.sql.operators.ColumnOperators
16,127
sqlalchemy.sql.operators
regexp_replace
Implements a database-specific 'regexp replace' operator. E.g.:: stmt = select( table.c.some_column.regexp_replace( 'b(..)', 'XY', flags='g' ) ) :meth:`_sql.ColumnOperators.regexp_replace` attempts to resolve to a REGEXP_REPLACE-like function provided by the backend, that usually emit the function ``REGEXP_REPLACE()``. However, the specific regular expression syntax and flags available are **not backend agnostic**. Regular expression replacement support is currently implemented for Oracle, PostgreSQL, MySQL 8 or greater and MariaDB. Support among third-party dialects may vary. :param pattern: The regular expression pattern string or column clause. :param pattern: The replacement string or column clause. :param flags: Any regular expression string flags to apply, passed as plain Python string only. These flags are backend specific. Some backends, like PostgreSQL and MariaDB, may alternatively specify the flags as part of the pattern. .. versionadded:: 1.4 .. versionchanged:: 1.4.48, 2.0.18 Note that due to an implementation error, the "flags" parameter previously accepted SQL expression objects such as column expressions in addition to plain Python strings. This implementation did not work correctly with caching and was removed; strings only should be passed for the "flags" parameter, as these flags are rendered as literal inline values within SQL expressions. .. seealso:: :meth:`_sql.ColumnOperators.regexp_match`
def regexp_replace( self, pattern: Any, replacement: Any, flags: Optional[str] = None ) -> ColumnOperators: """Implements a database-specific 'regexp replace' operator. E.g.:: stmt = select( table.c.some_column.regexp_replace( 'b(..)', 'X\1Y', flags='g' ) ) :meth:`_sql.ColumnOperators.regexp_replace` attempts to resolve to a REGEXP_REPLACE-like function provided by the backend, that usually emit the function ``REGEXP_REPLACE()``. However, the specific regular expression syntax and flags available are **not backend agnostic**. Regular expression replacement support is currently implemented for Oracle, PostgreSQL, MySQL 8 or greater and MariaDB. Support among third-party dialects may vary. :param pattern: The regular expression pattern string or column clause. :param pattern: The replacement string or column clause. :param flags: Any regular expression string flags to apply, passed as plain Python string only. These flags are backend specific. Some backends, like PostgreSQL and MariaDB, may alternatively specify the flags as part of the pattern. .. versionadded:: 1.4 .. versionchanged:: 1.4.48, 2.0.18 Note that due to an implementation error, the "flags" parameter previously accepted SQL expression objects such as column expressions in addition to plain Python strings. This implementation did not work correctly with caching and was removed; strings only should be passed for the "flags" parameter, as these flags are rendered as literal inline values within SQL expressions. .. seealso:: :meth:`_sql.ColumnOperators.regexp_match` """ return self.operate( regexp_replace_op, pattern, replacement=replacement, flags=flags, )
(self, pattern: Any, replacement: Any, flags: Optional[str] = None) -> sqlalchemy.sql.operators.ColumnOperators
16,128
sqlalchemy.sql.selectable
replace_selectable
Replace all occurrences of :class:`_expression.FromClause` 'old' with the given :class:`_expression.Alias` object, returning a copy of this :class:`_expression.FromClause`. .. deprecated:: 1.4 The :meth:`.Selectable.replace_selectable` method is deprecated, and will be removed in a future release. Similar functionality is available via the sqlalchemy.sql.visitors module.
# sql/selectable.py # Copyright (C) 2005-2024 the SQLAlchemy authors and contributors # <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: https://www.opensource.org/licenses/mit-license.php """The :class:`_expression.FromClause` class of SQL expression elements, representing SQL tables and derived rowsets. """ from __future__ import annotations import collections from enum import Enum import itertools from typing import AbstractSet from typing import Any as TODO_Any from typing import Any from typing import Callable from typing import cast from typing import Dict from typing import Generic from typing import Iterable from typing import Iterator from typing import List from typing import NamedTuple from typing import NoReturn from typing import Optional from typing import overload from typing import Sequence from typing import Set from typing import Tuple from typing import Type from typing import TYPE_CHECKING from typing import TypeVar from typing import Union from . import cache_key from . import coercions from . import operators from . import roles from . import traversals from . import type_api from . import visitors from ._typing import _ColumnsClauseArgument from ._typing import _no_kw from ._typing import _TP from ._typing import is_column_element from ._typing import is_select_statement from ._typing import is_subquery from ._typing import is_table from ._typing import is_text_clause from .annotation import Annotated from .annotation import SupportsCloneAnnotations from .base import _clone from .base import _cloned_difference from .base import _cloned_intersection from .base import _entity_namespace_key from .base import _EntityNamespace from .base import _expand_cloned from .base import _from_objects from .base import _generative from .base import _never_select_column from .base import _NoArg from .base import _select_iterables from .base import CacheableOptions from .base import ColumnCollection from .base import ColumnSet from .base import CompileState from .base import DedupeColumnCollection from .base import Executable from .base import Generative from .base import HasCompileState from .base import HasMemoized from .base import Immutable from .coercions import _document_text_coercion from .elements import _anonymous_label from .elements import BindParameter from .elements import BooleanClauseList from .elements import ClauseElement from .elements import ClauseList from .elements import ColumnClause from .elements import ColumnElement from .elements import DQLDMLClauseElement from .elements import GroupedElement from .elements import literal_column from .elements import TableValuedColumn from .elements import UnaryExpression from .operators import OperatorType from .sqltypes import NULLTYPE from .visitors import _TraverseInternalsType from .visitors import InternalTraversal from .visitors import prefix_anon_map from .. import exc from .. import util from ..util import HasMemoized_ro_memoized_attribute from ..util.typing import Literal from ..util.typing import Protocol from ..util.typing import Self and_ = BooleanClauseList.and_ _T = TypeVar("_T", bound=Any) if TYPE_CHECKING: from ._typing import _ColumnExpressionArgument from ._typing import _ColumnExpressionOrStrLabelArgument from ._typing import _FromClauseArgument from ._typing import _JoinTargetArgument from ._typing import _LimitOffsetType from ._typing import _MAYBE_ENTITY from ._typing import _NOT_ENTITY from ._typing import _OnClauseArgument from ._typing import _SelectStatementForCompoundArgument from ._typing import _T0 from ._typing import _T1 from ._typing import _T2 from ._typing import _T3 from ._typing import _T4 from ._typing import _T5 from ._typing import _T6 from ._typing import _T7 from ._typing import _TextCoercedExpressionArgument from ._typing import _TypedColumnClauseArgument as _TCCA from ._typing import _TypeEngineArgument from .base import _AmbiguousTableNameMap from .base import ExecutableOption from .base import ReadOnlyColumnCollection from .cache_key import _CacheKeyTraversalType from .compiler import SQLCompiler from .dml import Delete from .dml import Update from .elements import BinaryExpression from .elements import KeyedColumnElement from .elements import Label from .elements import NamedColumn from .elements import TextClause from .functions import Function from .schema import ForeignKey from .schema import ForeignKeyConstraint from .sqltypes import TableValueType from .type_api import TypeEngine from .visitors import _CloneCallableType _ColumnsClauseElement = Union["FromClause", ColumnElement[Any], "TextClause"] _LabelConventionCallable = Callable[ [Union["ColumnElement[Any]", "TextClause"]], Optional[str] ] class _JoinTargetProtocol(Protocol): @util.ro_non_memoized_property def _from_objects(self) -> List[FromClause]: ... @util.ro_non_memoized_property def entity_namespace(self) -> _EntityNamespace: ...
(self, old: sqlalchemy.sql.selectable.FromClause, alias: sqlalchemy.sql.selectable.Alias) -> typing_extensions.Self
16,129
sqlalchemy.sql.elements
reverse_operate
null
def reverse_operate( self, op: operators.OperatorType, other: Any, **kwargs: Any ) -> ColumnElement[Any]: return op(other, self.comparator, **kwargs) # type: ignore[no-any-return] # noqa: E501
(self, op: sqlalchemy.sql.operators.OperatorType, other: Any, **kwargs: Any) -> sqlalchemy.sql.elements.ColumnElement[typing.Any]
16,130
sqlalchemy.sql.functions
scalar_table_valued
Return a column expression that's against this :class:`_functions.FunctionElement` as a scalar table-valued expression. The returned expression is similar to that returned by a single column accessed off of a :meth:`_functions.FunctionElement.table_valued` construct, except no FROM clause is generated; the function is rendered in the similar way as a scalar subquery. E.g.: .. sourcecode:: pycon+sql >>> from sqlalchemy import func, select >>> fn = func.jsonb_each("{'k', 'v'}").scalar_table_valued("key") >>> print(select(fn)) {printsql}SELECT (jsonb_each(:jsonb_each_1)).key .. versionadded:: 1.4.0b2 .. seealso:: :meth:`_functions.FunctionElement.table_valued` :meth:`_functions.FunctionElement.alias` :meth:`_functions.FunctionElement.column_valued`
def scalar_table_valued( self, name: str, type_: Optional[_TypeEngineArgument[_T]] = None ) -> ScalarFunctionColumn[_T]: """Return a column expression that's against this :class:`_functions.FunctionElement` as a scalar table-valued expression. The returned expression is similar to that returned by a single column accessed off of a :meth:`_functions.FunctionElement.table_valued` construct, except no FROM clause is generated; the function is rendered in the similar way as a scalar subquery. E.g.: .. sourcecode:: pycon+sql >>> from sqlalchemy import func, select >>> fn = func.jsonb_each("{'k', 'v'}").scalar_table_valued("key") >>> print(select(fn)) {printsql}SELECT (jsonb_each(:jsonb_each_1)).key .. versionadded:: 1.4.0b2 .. seealso:: :meth:`_functions.FunctionElement.table_valued` :meth:`_functions.FunctionElement.alias` :meth:`_functions.FunctionElement.column_valued` """ # noqa: E501 return ScalarFunctionColumn(self, name, type_)
(self, name: 'str', type_: 'Optional[_TypeEngineArgument[_T]]' = None) -> 'ScalarFunctionColumn[_T]'
16,131
sqlalchemy.sql.functions
select
Produce a :func:`_expression.select` construct against this :class:`.FunctionElement`. This is shorthand for:: s = select(function_element)
def select(self) -> Select[Tuple[_T]]: """Produce a :func:`_expression.select` construct against this :class:`.FunctionElement`. This is shorthand for:: s = select(function_element) """ s: Select[Any] = Select(self) if self._execution_options: s = s.execution_options(**self._execution_options) return s
(self) -> sqlalchemy.sql.selectable.Select
16,132
sqlalchemy.sql.functions
self_group
null
def self_group(self, against: Optional[OperatorType] = None) -> ClauseElement: # type: ignore[override] # noqa E501 # for the moment, we are parenthesizing all array-returning # expressions against getitem. This may need to be made # more portable if in the future we support other DBs # besides postgresql. if against is operators.getitem and isinstance( self.type, sqltypes.ARRAY ): return Grouping(self) else: return super().self_group(against=against)
(self, against: 'Optional[OperatorType]' = None) -> 'ClauseElement'
16,133
sqlalchemy.sql.elements
shares_lineage
Return True if the given :class:`_expression.ColumnElement` has a common ancestor to this :class:`_expression.ColumnElement`.
def shares_lineage(self, othercolumn: ColumnElement[Any]) -> bool: """Return True if the given :class:`_expression.ColumnElement` has a common ancestor to this :class:`_expression.ColumnElement`.""" return bool(self.proxy_set.intersection(othercolumn.proxy_set))
(self, othercolumn: sqlalchemy.sql.elements.ColumnElement[typing.Any]) -> bool
16,134
sqlalchemy.sql.operators
startswith
Implement the ``startswith`` operator. Produces a LIKE expression that tests against a match for the start of a string value:: column LIKE <other> || '%' E.g.:: stmt = select(sometable).\ where(sometable.c.column.startswith("foobar")) Since the operator uses ``LIKE``, wildcard characters ``"%"`` and ``"_"`` that are present inside the <other> expression will behave like wildcards as well. For literal string values, the :paramref:`.ColumnOperators.startswith.autoescape` flag may be set to ``True`` to apply escaping to occurrences of these characters within the string value so that they match as themselves and not as wildcard characters. Alternatively, the :paramref:`.ColumnOperators.startswith.escape` parameter will establish a given character as an escape character which can be of use when the target expression is not a literal string. :param other: expression to be compared. This is usually a plain string value, but can also be an arbitrary SQL expression. LIKE wildcard characters ``%`` and ``_`` are not escaped by default unless the :paramref:`.ColumnOperators.startswith.autoescape` flag is set to True. :param autoescape: boolean; when True, establishes an escape character within the LIKE expression, then applies it to all occurrences of ``"%"``, ``"_"`` and the escape character itself within the comparison value, which is assumed to be a literal string and not a SQL expression. An expression such as:: somecolumn.startswith("foo%bar", autoescape=True) Will render as:: somecolumn LIKE :param || '%' ESCAPE '/' With the value of ``:param`` as ``"foo/%bar"``. :param escape: a character which when given will render with the ``ESCAPE`` keyword to establish that character as the escape character. This character can then be placed preceding occurrences of ``%`` and ``_`` to allow them to act as themselves and not wildcard characters. An expression such as:: somecolumn.startswith("foo/%bar", escape="^") Will render as:: somecolumn LIKE :param || '%' ESCAPE '^' The parameter may also be combined with :paramref:`.ColumnOperators.startswith.autoescape`:: somecolumn.startswith("foo%bar^bat", escape="^", autoescape=True) Where above, the given literal parameter will be converted to ``"foo^%bar^^bat"`` before being passed to the database. .. seealso:: :meth:`.ColumnOperators.endswith` :meth:`.ColumnOperators.contains` :meth:`.ColumnOperators.like`
def startswith( self, other: Any, escape: Optional[str] = None, autoescape: bool = False, ) -> ColumnOperators: r"""Implement the ``startswith`` operator. Produces a LIKE expression that tests against a match for the start of a string value:: column LIKE <other> || '%' E.g.:: stmt = select(sometable).\ where(sometable.c.column.startswith("foobar")) Since the operator uses ``LIKE``, wildcard characters ``"%"`` and ``"_"`` that are present inside the <other> expression will behave like wildcards as well. For literal string values, the :paramref:`.ColumnOperators.startswith.autoescape` flag may be set to ``True`` to apply escaping to occurrences of these characters within the string value so that they match as themselves and not as wildcard characters. Alternatively, the :paramref:`.ColumnOperators.startswith.escape` parameter will establish a given character as an escape character which can be of use when the target expression is not a literal string. :param other: expression to be compared. This is usually a plain string value, but can also be an arbitrary SQL expression. LIKE wildcard characters ``%`` and ``_`` are not escaped by default unless the :paramref:`.ColumnOperators.startswith.autoescape` flag is set to True. :param autoescape: boolean; when True, establishes an escape character within the LIKE expression, then applies it to all occurrences of ``"%"``, ``"_"`` and the escape character itself within the comparison value, which is assumed to be a literal string and not a SQL expression. An expression such as:: somecolumn.startswith("foo%bar", autoescape=True) Will render as:: somecolumn LIKE :param || '%' ESCAPE '/' With the value of ``:param`` as ``"foo/%bar"``. :param escape: a character which when given will render with the ``ESCAPE`` keyword to establish that character as the escape character. This character can then be placed preceding occurrences of ``%`` and ``_`` to allow them to act as themselves and not wildcard characters. An expression such as:: somecolumn.startswith("foo/%bar", escape="^") Will render as:: somecolumn LIKE :param || '%' ESCAPE '^' The parameter may also be combined with :paramref:`.ColumnOperators.startswith.autoescape`:: somecolumn.startswith("foo%bar^bat", escape="^", autoescape=True) Where above, the given literal parameter will be converted to ``"foo^%bar^^bat"`` before being passed to the database. .. seealso:: :meth:`.ColumnOperators.endswith` :meth:`.ColumnOperators.contains` :meth:`.ColumnOperators.like` """ return self.operate( startswith_op, other, escape=escape, autoescape=autoescape )
(self, other: Any, escape: Optional[str] = None, autoescape: bool = False) -> sqlalchemy.sql.operators.ColumnOperators
16,135
sqlalchemy.sql.functions
table_valued
Return a :class:`_sql.TableValuedAlias` representation of this :class:`_functions.FunctionElement` with table-valued expressions added. e.g.: .. sourcecode:: pycon+sql >>> fn = ( ... func.generate_series(1, 5). ... table_valued("value", "start", "stop", "step") ... ) >>> print(select(fn)) {printsql}SELECT anon_1.value, anon_1.start, anon_1.stop, anon_1.step FROM generate_series(:generate_series_1, :generate_series_2) AS anon_1{stop} >>> print(select(fn.c.value, fn.c.stop).where(fn.c.value > 2)) {printsql}SELECT anon_1.value, anon_1.stop FROM generate_series(:generate_series_1, :generate_series_2) AS anon_1 WHERE anon_1.value > :value_1{stop} A WITH ORDINALITY expression may be generated by passing the keyword argument "with_ordinality": .. sourcecode:: pycon+sql >>> fn = func.generate_series(4, 1, -1).table_valued("gen", with_ordinality="ordinality") >>> print(select(fn)) {printsql}SELECT anon_1.gen, anon_1.ordinality FROM generate_series(:generate_series_1, :generate_series_2, :generate_series_3) WITH ORDINALITY AS anon_1 :param \*expr: A series of string column names that will be added to the ``.c`` collection of the resulting :class:`_sql.TableValuedAlias` construct as columns. :func:`_sql.column` objects with or without datatypes may also be used. :param name: optional name to assign to the alias name that's generated. If omitted, a unique anonymizing name is used. :param with_ordinality: string name that when present results in the ``WITH ORDINALITY`` clause being added to the alias, and the given string name will be added as a column to the .c collection of the resulting :class:`_sql.TableValuedAlias`. :param joins_implicitly: when True, the table valued function may be used in the FROM clause without any explicit JOIN to other tables in the SQL query, and no "cartesian product" warning will be generated. May be useful for SQL functions such as ``func.json_each()``. .. versionadded:: 1.4.33 .. versionadded:: 1.4.0b2 .. seealso:: :ref:`tutorial_functions_table_valued` - in the :ref:`unified_tutorial` :ref:`postgresql_table_valued` - in the :ref:`postgresql_toplevel` documentation :meth:`_functions.FunctionElement.scalar_table_valued` - variant of :meth:`_functions.FunctionElement.table_valued` which delivers the complete table valued expression as a scalar column expression :meth:`_functions.FunctionElement.column_valued` :meth:`_sql.TableValuedAlias.render_derived` - renders the alias using a derived column clause, e.g. ``AS name(col1, col2, ...)``
def table_valued( self, *expr: _ColumnExpressionOrStrLabelArgument[Any], **kw: Any ) -> TableValuedAlias: r"""Return a :class:`_sql.TableValuedAlias` representation of this :class:`_functions.FunctionElement` with table-valued expressions added. e.g.: .. sourcecode:: pycon+sql >>> fn = ( ... func.generate_series(1, 5). ... table_valued("value", "start", "stop", "step") ... ) >>> print(select(fn)) {printsql}SELECT anon_1.value, anon_1.start, anon_1.stop, anon_1.step FROM generate_series(:generate_series_1, :generate_series_2) AS anon_1{stop} >>> print(select(fn.c.value, fn.c.stop).where(fn.c.value > 2)) {printsql}SELECT anon_1.value, anon_1.stop FROM generate_series(:generate_series_1, :generate_series_2) AS anon_1 WHERE anon_1.value > :value_1{stop} A WITH ORDINALITY expression may be generated by passing the keyword argument "with_ordinality": .. sourcecode:: pycon+sql >>> fn = func.generate_series(4, 1, -1).table_valued("gen", with_ordinality="ordinality") >>> print(select(fn)) {printsql}SELECT anon_1.gen, anon_1.ordinality FROM generate_series(:generate_series_1, :generate_series_2, :generate_series_3) WITH ORDINALITY AS anon_1 :param \*expr: A series of string column names that will be added to the ``.c`` collection of the resulting :class:`_sql.TableValuedAlias` construct as columns. :func:`_sql.column` objects with or without datatypes may also be used. :param name: optional name to assign to the alias name that's generated. If omitted, a unique anonymizing name is used. :param with_ordinality: string name that when present results in the ``WITH ORDINALITY`` clause being added to the alias, and the given string name will be added as a column to the .c collection of the resulting :class:`_sql.TableValuedAlias`. :param joins_implicitly: when True, the table valued function may be used in the FROM clause without any explicit JOIN to other tables in the SQL query, and no "cartesian product" warning will be generated. May be useful for SQL functions such as ``func.json_each()``. .. versionadded:: 1.4.33 .. versionadded:: 1.4.0b2 .. seealso:: :ref:`tutorial_functions_table_valued` - in the :ref:`unified_tutorial` :ref:`postgresql_table_valued` - in the :ref:`postgresql_toplevel` documentation :meth:`_functions.FunctionElement.scalar_table_valued` - variant of :meth:`_functions.FunctionElement.table_valued` which delivers the complete table valued expression as a scalar column expression :meth:`_functions.FunctionElement.column_valued` :meth:`_sql.TableValuedAlias.render_derived` - renders the alias using a derived column clause, e.g. ``AS name(col1, col2, ...)`` """ # noqa: 501 new_func = self._generate() with_ordinality = kw.pop("with_ordinality", None) joins_implicitly = kw.pop("joins_implicitly", None) name = kw.pop("name", None) if with_ordinality: expr += (with_ordinality,) new_func._with_ordinality = True new_func.type = new_func._table_value_type = TableValueType(*expr) return new_func.alias(name=name, joins_implicitly=joins_implicitly)
(self, *expr: '_ColumnExpressionOrStrLabelArgument[Any]', **kw: 'Any') -> 'TableValuedAlias'
16,136
sqlalchemy.sql.selectable
tablesample
Return a TABLESAMPLE alias of this :class:`_expression.FromClause`. The return value is the :class:`_expression.TableSample` construct also provided by the top-level :func:`_expression.tablesample` function. .. seealso:: :func:`_expression.tablesample` - usage guidelines and parameters
def tablesample( self, sampling: Union[float, Function[Any]], name: Optional[str] = None, seed: Optional[roles.ExpressionElementRole[Any]] = None, ) -> TableSample: """Return a TABLESAMPLE alias of this :class:`_expression.FromClause`. The return value is the :class:`_expression.TableSample` construct also provided by the top-level :func:`_expression.tablesample` function. .. seealso:: :func:`_expression.tablesample` - usage guidelines and parameters """ return TableSample._construct( self, sampling=sampling, name=name, seed=seed )
(self, sampling: 'Union[float, Function[Any]]', name: 'Optional[str]' = None, seed: 'Optional[roles.ExpressionElementRole[Any]]' = None) -> 'TableSample'
16,137
sqlalchemy.sql.elements
unique_params
Return a copy with :func:`_expression.bindparam` elements replaced. Same functionality as :meth:`_expression.ClauseElement.params`, except adds `unique=True` to affected bind parameters so that multiple statements can be used.
def unique_params( self, __optionaldict: Optional[Dict[str, Any]] = None, **kwargs: Any, ) -> Self: """Return a copy with :func:`_expression.bindparam` elements replaced. Same functionality as :meth:`_expression.ClauseElement.params`, except adds `unique=True` to affected bind parameters so that multiple statements can be used. """ return self._replace_params(True, __optionaldict, kwargs)
(self, _ClauseElement__optionaldict: Optional[Dict[str, Any]] = None, **kwargs: Any) -> typing_extensions.Self
16,138
sqlalchemy.sql.functions
within_group
Produce a WITHIN GROUP (ORDER BY expr) clause against this function. Used against so-called "ordered set aggregate" and "hypothetical set aggregate" functions, including :class:`.percentile_cont`, :class:`.rank`, :class:`.dense_rank`, etc. See :func:`_expression.within_group` for a full description. .. seealso:: :ref:`tutorial_functions_within_group` - in the :ref:`unified_tutorial`
def within_group( self, *order_by: _ColumnExpressionArgument[Any] ) -> WithinGroup[_T]: """Produce a WITHIN GROUP (ORDER BY expr) clause against this function. Used against so-called "ordered set aggregate" and "hypothetical set aggregate" functions, including :class:`.percentile_cont`, :class:`.rank`, :class:`.dense_rank`, etc. See :func:`_expression.within_group` for a full description. .. seealso:: :ref:`tutorial_functions_within_group` - in the :ref:`unified_tutorial` """ return WithinGroup(self, *order_by)
(self, *order_by: '_ColumnExpressionArgument[Any]') -> 'WithinGroup[_T]'
16,139
sqlalchemy.sql.functions
within_group_type
For types that define their return type as based on the criteria within a WITHIN GROUP (ORDER BY) expression, called by the :class:`.WithinGroup` construct. Returns None by default, in which case the function's normal ``.type`` is used.
def within_group_type( self, within_group: WithinGroup[_S] ) -> Optional[TypeEngine[_S]]: """For types that define their return type as based on the criteria within a WITHIN GROUP (ORDER BY) expression, called by the :class:`.WithinGroup` construct. Returns None by default, in which case the function's normal ``.type`` is used. """ return None
(self, within_group: sqlalchemy.sql.elements.WithinGroup[~_S]) -> Optional[sqlalchemy.sql.type_api.TypeEngine]
16,142
spectral_sdk.abis
load_abis
null
def load_abis(): d = {} # Directory containing all the ABI files (change this to your specific path) dir_path = "/Users/maciej/dev/spectral/spectral-ai-sdk/spectral_sdk/abis" for root, dirs, files in os.walk(dir_path): for file in files: if file.endswith(".json"): full_file_path = os.path.join(root, file) abi_dict = load_abi(full_file_path) contract_name, _ = os.path.splitext(file) d[contract_name] = abi_dict return d
()
16,144
synchronicity.interface
Interface
An enumeration.
class Interface(enum.Enum): BLOCKING = enum.auto() ASYNC = enum.auto() # temporary internal type until we deprecate the old ASYNC type, # used for `function.aio` async callables accepting/returning BLOCKING types _ASYNC_WITH_BLOCKING_TYPES = enum.auto() AUTODETECT = enum.auto() # DEPRECATED
(value, names=None, *, module=None, qualname=None, type=None, start=1)
16,145
synchronicity.synchronizer
Synchronizer
Helps you offer a blocking (synchronous) interface to asynchronous code.
class Synchronizer: """Helps you offer a blocking (synchronous) interface to asynchronous code.""" def __init__( self, multiwrap_warning=False, async_leakage_warning=True, ): self._multiwrap_warning = multiwrap_warning self._async_leakage_warning = async_leakage_warning self._loop = None self._loop_creation_lock = threading.Lock() self._thread = None self._stopping = None if platform.system() == "Windows": # default event loop policy on windows spits out errors when # closing the event loop, so use WindowsSelectorEventLoopPolicy instead # https://stackoverflow.com/questions/45600579/asyncio-event-loop-is-closed-when-getting-loop asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy()) # Special attribute we use to go from wrapped <-> original self._wrapped_attr = "_sync_wrapped_%d" % id(self) self._original_attr = "_sync_original_%d" % id(self) # Special attribute to mark something as non-wrappable self._nowrap_attr = "_sync_nonwrap_%d" % id(self) self._input_translation_attr = "_sync_input_translation_%d" % id(self) self._output_translation_attr = "_sync_output_translation_%d" % id(self) # Prep a synchronized context manager in case one is returned and needs translation self._ctx_mgr_cls = contextlib._AsyncGeneratorContextManager self.create_async(self._ctx_mgr_cls) self.create_blocking(self._ctx_mgr_cls) atexit.register(self._close_loop) _PICKLE_ATTRS = [ "_multiwrap_warning", "_async_leakage_warning", ] def __getstate__(self): return dict([(attr, getattr(self, attr)) for attr in self._PICKLE_ATTRS]) def __setstate__(self, d): for attr in self._PICKLE_ATTRS: setattr(self, attr, d[attr]) def _start_loop(self): with self._loop_creation_lock: if self._loop and self._loop.is_running(): return self._loop is_ready = threading.Event() def thread_inner(): async def loop_inner(): self._loop = asyncio.get_running_loop() self._stopping = asyncio.Event() is_ready.set() await self._stopping.wait() # wait until told to stop try: asyncio.run(loop_inner()) except RuntimeError as exc: # Python 3.12 raises a RuntimeError when new threads are created at shutdown. # Swallowing it here is innocuous, but ideally we will revisit this after # refactoring the shutdown handlers that modal uses to avoid triggering it. if "can't create new thread at interpreter shutdown" not in str(exc): raise exc self._thread = threading.Thread(target=thread_inner, daemon=True) self._thread.start() is_ready.wait() # TODO: this might block for a very short time return self._loop def _close_loop(self): if self._thread is not None: if not self._loop.is_closed(): # This also serves the purpose of waking up an idle loop self._loop.call_soon_threadsafe(self._stopping.set) self._thread.join() self._thread = None def _get_loop(self, start=False): if self._loop is None and start: return self._start_loop() return self._loop def _get_running_loop(self): # TODO: delete this method try: return asyncio.get_running_loop() except RuntimeError: return def _is_inside_loop(self): loop = self._get_loop() if loop is None: return False if threading.current_thread() != self._thread: # gevent does something bad that causes asyncio.get_running_loop() to return self._loop return False current_loop = self._get_running_loop() return loop == current_loop def _wrap_check_async_leakage(self, coro): """Check if a coroutine returns another coroutine (or an async generator) and warn. The reason this is important to catch is that otherwise even synchronized code might end up "leaking" async code into the caller. """ if not self._async_leakage_warning: return coro async def coro_wrapped(): value = await coro # TODO: we should include the name of the original function here if inspect.iscoroutine(value): warnings.warn(f"Potential async leakage: coroutine returned a coroutine {value}.") elif inspect.isasyncgen(value): warnings.warn(f"Potential async leakage: Coroutine returned an async generator {value}.") return value return coro_wrapped() def _wrap_instance(self, obj, interface): # Takes an object and creates a new proxy object for it cls = obj.__class__ cls_dct = cls.__dict__ interfaces = cls_dct[self._wrapped_attr] if interface not in interfaces: raise RuntimeError(f"Class {cls} has not synchronized {interface}.") interface_cls = interfaces[interface] new_obj = interface_cls.__new__(interface_cls) # Store a reference to the original object new_obj.__dict__[self._original_attr] = obj new_obj.__dict__[SYNCHRONIZER_ATTR] = self new_obj.__dict__[TARGET_INTERFACE_ATTR] = interface return new_obj def _translate_scalar_in(self, obj): # If it's an external object, translate it to the internal type if hasattr(obj, "__dict__"): if inspect.isclass(obj): # TODO: functions? return obj.__dict__.get(self._original_attr, obj) else: return obj.__dict__.get(self._original_attr, obj) else: return obj def _translate_scalar_out(self, obj, interface): if interface == Interface._ASYNC_WITH_BLOCKING_TYPES: interface = Interface.BLOCKING # If it's an internal object, translate it to the external interface if inspect.isclass(obj): # TODO: functions? cls_dct = obj.__dict__ if self._wrapped_attr in cls_dct: return cls_dct[self._wrapped_attr][interface] else: return obj elif isinstance(obj, typing.TypeVar): if hasattr(obj, self._wrapped_attr): return getattr(obj, self._wrapped_attr)[interface] else: return obj else: cls_dct = obj.__class__.__dict__ if self._wrapped_attr in cls_dct: # This is an *instance* of a synchronized class, translate its type return self._wrap(obj, interface) else: return obj def _recurse_map(self, mapper, obj): if type(obj) == list: # noqa: E721 return list(self._recurse_map(mapper, item) for item in obj) elif type(obj) == tuple: # noqa: E721 return tuple(self._recurse_map(mapper, item) for item in obj) elif type(obj) == dict: # noqa: E721 return dict((key, self._recurse_map(mapper, item)) for key, item in obj.items()) else: return mapper(obj) def _translate_in(self, obj): return self._recurse_map(self._translate_scalar_in, obj) def _translate_out(self, obj, interface): return self._recurse_map(lambda scalar: self._translate_scalar_out(scalar, interface), obj) def _translate_coro_out(self, coro, interface, original_func): async def unwrap_coro(): res = await coro if getattr(original_func, self._output_translation_attr, True): return self._translate_out(res, interface) return res return unwrap_coro() def _run_function_sync(self, coro, interface, original_func): if self._is_inside_loop(): raise Exception("Deadlock detected: calling a sync function from the synchronizer loop") coro = wrap_coro_exception(coro) coro = self._wrap_check_async_leakage(coro) loop = self._get_loop(start=True) fut = asyncio.run_coroutine_threadsafe(coro, loop) value = fut.result() if getattr(original_func, self._output_translation_attr, True): return self._translate_out(value, interface) return value def _run_function_sync_future(self, coro, interface, original_func): coro = wrap_coro_exception(coro) coro = self._wrap_check_async_leakage(coro) loop = self._get_loop(start=True) # For futures, we unwrap the result at this point, not in f_wrapped coro = unwrap_coro_exception(coro) coro = self._translate_coro_out(coro, interface, original_func) return asyncio.run_coroutine_threadsafe(coro, loop) async def _run_function_async(self, coro, interface, original_func): coro = wrap_coro_exception(coro) coro = self._wrap_check_async_leakage(coro) loop = self._get_loop(start=True) if self._is_inside_loop(): value = await coro else: c_fut = asyncio.run_coroutine_threadsafe(coro, loop) a_fut = asyncio.wrap_future(c_fut) value = await a_fut if getattr(original_func, self._output_translation_attr, True): return self._translate_out(value, interface) return value def _run_generator_sync(self, gen, interface, original_func): value, is_exc = None, False while True: try: if is_exc: value = self._run_function_sync(gen.athrow(value), interface, original_func) else: value = self._run_function_sync(gen.asend(value), interface, original_func) except UserCodeException as uc_exc: raise uc_exc.exc from None except StopAsyncIteration: break try: value = yield value is_exc = False except BaseException as exc: value = exc is_exc = True async def _run_generator_async(self, gen, interface, original_func): value, is_exc = None, False while True: try: if is_exc: value = await self._run_function_async(gen.athrow(value), interface, original_func) else: value = await self._run_function_async(gen.asend(value), interface, original_func) except UserCodeException as uc_exc: raise uc_exc.exc from None except StopAsyncIteration: break try: value = yield value is_exc = False except BaseException as exc: value = exc is_exc = True def create_callback(self, f, interface): return Callback(self, f, interface) def _update_wrapper(self, f_wrapped, f, name=None, interface=None, target_module=None): """Very similar to functools.update_wrapper""" functools.update_wrapper(f_wrapped, f) if name is not None: f_wrapped.__name__ = name f_wrapped.__qualname__ = name if target_module is not None: f_wrapped.__module__ = target_module setattr(f_wrapped, SYNCHRONIZER_ATTR, self) setattr(f_wrapped, TARGET_INTERFACE_ATTR, interface) def _wrap_callable( self, f, interface, name=None, allow_futures=True, unwrap_user_excs=True, target_module=None, include_aio_interface=True, ): if hasattr(f, self._original_attr): if self._multiwrap_warning: warnings.warn(f"Function {f} is already wrapped, but getting wrapped again") return f if name is None: _name = _FUNCTION_PREFIXES[interface] + f.__name__ else: _name = name is_coroutinefunction = inspect.iscoroutinefunction(f) @wraps_by_interface(interface, f) def f_wrapped(*args, **kwargs): return_future = kwargs.pop(_RETURN_FUTURE_KWARG, False) # If this gets called with an argument that represents an external type, # translate it into an internal type if getattr(f, self._input_translation_attr, True): args = self._translate_in(args) kwargs = self._translate_in(kwargs) # Call the function res = f(*args, **kwargs) # Figure out if this is a coroutine or something is_coroutine = inspect.iscoroutine(res) is_asyncgen = inspect.isasyncgen(res) if return_future: if not allow_futures: raise Exception("Can not return future for this function") elif is_coroutine: return self._run_function_sync_future(res, interface, f) elif is_asyncgen: raise Exception("Can not return futures for generators") else: return res elif is_coroutine: if interface in (Interface.ASYNC, Interface._ASYNC_WITH_BLOCKING_TYPES): coro = self._run_function_async(res, interface, f) if not is_coroutinefunction: # If this is a non-async function that returns a coroutine, # then this is the exit point, and we need to unwrap any # wrapped exception here. Otherwise, the exit point is # in async_wrap.py coro = unwrap_coro_exception(coro) return coro elif interface == Interface.BLOCKING: # This is the exit point, so we need to unwrap the exception here try: return self._run_function_sync(res, interface, f) except StopAsyncIteration: # this is a special case for handling __next__ wrappers around # __anext__ that raises StopAsyncIteration raise StopIteration() except UserCodeException as uc_exc: # Used to skip a frame when called from `proxy_method`. if unwrap_user_excs and not (Interface.BLOCKING and include_aio_interface): raise uc_exc.exc from None else: raise uc_exc elif is_asyncgen: # Note that the _run_generator_* functions handle their own # unwrapping of exceptions (this happens during yielding) if interface in (Interface.ASYNC, Interface._ASYNC_WITH_BLOCKING_TYPES): return self._run_generator_async(res, interface, f) elif interface == Interface.BLOCKING: return self._run_generator_sync(res, interface, f) else: if inspect.isfunction(res) or isinstance(res, functools.partial): # TODO: HACKY HACK # TODO: this is needed for decorator wrappers that returns functions # Maybe a bit of a hacky special case that deserves its own decorator @wraps_by_interface(interface, res) def f_wrapped(*args, **kwargs): args = self._translate_in(args) kwargs = self._translate_in(kwargs) f_res = res(*args, **kwargs) if getattr(f, self._output_translation_attr, True): return self._translate_out(f_res, interface) else: return f_res return f_wrapped if getattr(f, self._output_translation_attr, True): return self._translate_out(res, interface) else: return res self._update_wrapper(f_wrapped, f, _name, interface, target_module=target_module) setattr(f_wrapped, self._original_attr, f) if interface == Interface.BLOCKING and include_aio_interface and should_have_aio_interface(f): # special async interface # this async interface returns *blocking* instances of wrapped objects, not async ones: async_interface = self._wrap_callable( f, interface=Interface._ASYNC_WITH_BLOCKING_TYPES, name=name, allow_futures=allow_futures, unwrap_user_excs=unwrap_user_excs, target_module=target_module, ) f_wrapped = FunctionWithAio(f_wrapped, async_interface, self) self._update_wrapper(f_wrapped, f, _name, interface, target_module=target_module) setattr(f_wrapped, self._original_attr, f) return f_wrapped def _wrap_proxy_method( synchronizer_self, method, interface, allow_futures=True, include_aio_interface=True, ): if getattr(method, synchronizer_self._nowrap_attr, None): # This method is marked as non-wrappable return method wrapped_method = synchronizer_self._wrap_callable( method, interface, allow_futures=allow_futures, unwrap_user_excs=False, ) @wraps_by_interface(interface, wrapped_method) def proxy_method(self, *args, **kwargs): instance = self.__dict__[synchronizer_self._original_attr] try: return wrapped_method(instance, *args, **kwargs) except UserCodeException as uc_exc: raise uc_exc.exc from None if interface == Interface.BLOCKING and include_aio_interface and should_have_aio_interface(method): async_proxy_method = synchronizer_self._wrap_proxy_method( method, Interface._ASYNC_WITH_BLOCKING_TYPES, allow_futures ) return MethodWithAio(proxy_method, async_proxy_method, synchronizer_self) return proxy_method def _wrap_proxy_staticmethod(self, method, interface): orig_function = method.__func__ method = self._wrap_callable(orig_function, interface) if isinstance(method, FunctionWithAio): return method # no need to wrap a FunctionWithAio in a staticmethod, as it won't get bound anyways return staticmethod(method) def _wrap_proxy_classmethod(self, orig_classmethod, interface): orig_func = orig_classmethod.__func__ method = self._wrap_callable(orig_func, interface, include_aio_interface=False) if interface == Interface.BLOCKING and should_have_aio_interface(orig_func): async_method = self._wrap_callable(orig_func, Interface._ASYNC_WITH_BLOCKING_TYPES) return MethodWithAio(method, async_method, self, is_classmethod=True) return classmethod(method) def _wrap_proxy_property(self, prop, interface): kwargs = {} for attr in ["fget", "fset", "fdel"]: if getattr(prop, attr): func = getattr(prop, attr) kwargs[attr] = self._wrap_proxy_method( func, interface, allow_futures=False, include_aio_interface=False ) return property(**kwargs) def _wrap_proxy_constructor(synchronizer_self, cls, interface): """Returns a custom __init__ for the subclass.""" def my_init(self, *args, **kwargs): # Create base instance args = synchronizer_self._translate_in(args) kwargs = synchronizer_self._translate_in(kwargs) instance = cls(*args, **kwargs) # Register self as the wrapped one interface_instances = {interface: self} instance.__dict__[synchronizer_self._wrapped_attr] = interface_instances # Store a reference to the original object self.__dict__[synchronizer_self._original_attr] = instance synchronizer_self._update_wrapper(my_init, cls.__init__, interface=interface) setattr(my_init, synchronizer_self._original_attr, cls.__init__) return my_init def _wrap_class(self, cls, interface, name, target_module=None): bases = tuple( self._wrap(base, interface, require_already_wrapped=(name is not None)) if base != object else object for base in cls.__bases__ ) new_dict = {self._original_attr: cls} if cls is not None: new_dict["__init__"] = self._wrap_proxy_constructor(cls, interface) for k, v in cls.__dict__.items(): if k in _BUILTIN_ASYNC_METHODS: k_sync = _BUILTIN_ASYNC_METHODS[k] if interface == Interface.BLOCKING: new_dict[k_sync] = self._wrap_proxy_method( v, interface, allow_futures=False, include_aio_interface=False, ) new_dict[k] = self._wrap_proxy_method( v, Interface._ASYNC_WITH_BLOCKING_TYPES, allow_futures=False, ) elif interface == Interface.ASYNC: new_dict[k] = self._wrap_proxy_method(v, interface, allow_futures=False) elif k in ("__new__", "__init__"): # Skip custom constructor in the wrapped class # Instead, delegate to the base class constructor and wrap it pass elif k in IGNORED_ATTRIBUTES: pass elif isinstance(v, staticmethod): # TODO(erikbern): this feels pretty hacky new_dict[k] = self._wrap_proxy_staticmethod(v, interface) elif isinstance(v, classmethod): new_dict[k] = self._wrap_proxy_classmethod(v, interface) elif isinstance(v, property): new_dict[k] = self._wrap_proxy_property(v, interface) elif isinstance(v, MethodWithAio): # if library defines its own "synchronicity-like" interface we transfer it "as is" to the wrapper new_dict[k] = v elif callable(v): new_dict[k] = self._wrap_proxy_method(v, interface) if name is None: name = _CLASS_PREFIXES[interface] + cls.__name__ new_cls = type.__new__(type, name, bases, new_dict) new_cls.__module__ = cls.__module__ if target_module is None else target_module new_cls.__doc__ = cls.__doc__ if "__annotations__" in cls.__dict__: new_cls.__annotations__ = cls.__annotations__ # transfer annotations setattr(new_cls, TARGET_INTERFACE_ATTR, interface) setattr(new_cls, SYNCHRONIZER_ATTR, self) return new_cls def _wrap( self, obj, interface, name=None, require_already_wrapped=False, target_module=None, ): # This method works for classes, functions, and instances # It wraps the object, and caches the wrapped object # Get the list of existing interfaces if hasattr(obj, "__dict__"): if self._wrapped_attr not in obj.__dict__: if isinstance(obj.__dict__, dict): # This works for instances obj.__dict__.setdefault(self._wrapped_attr, {}) else: # This works for classes & functions setattr(obj, self._wrapped_attr, {}) interfaces = obj.__dict__[self._wrapped_attr] else: # e.g., TypeVar in Python>=3.12 if not hasattr(obj, self._wrapped_attr): setattr(obj, self._wrapped_attr, {}) interfaces = getattr(obj, self._wrapped_attr) # If this is already wrapped, return the existing interface if interface in interfaces: if self._multiwrap_warning: warnings.warn(f"Object {obj} is already wrapped, but getting wrapped again") return interfaces[interface] if require_already_wrapped: # This happens if a class has a custom name but its base class doesn't raise RuntimeError(f"{obj} needs to be serialized explicitly with a custom name") # Wrap object (different cases based on the type) if inspect.isclass(obj): new_obj = self._wrap_class( obj, interface, name, target_module=target_module, ) elif inspect.isfunction(obj): new_obj = self._wrap_callable(obj, interface, name, target_module=target_module) elif isinstance(obj, typing.TypeVar): new_obj = self._wrap_type_var(obj, interface, name, target_module) elif self._wrapped_attr in obj.__class__.__dict__: new_obj = self._wrap_instance(obj, interface) else: raise Exception("Argument %s is not a class or a callable" % obj) # Store the interface on the obj and return interfaces[interface] = new_obj return new_obj def _wrap_type_var(self, obj, interface, name, target_module): # TypeVar translation is needed only for type stub generation, in case the # "bound" attribute refers to a translatable type. # Creates a new identical TypeVar, marked with synchronicity's special attributes # This lets type stubs "translate" the `bounds` attribute on emitted type vars # if picked up from module scope and in generics using the base implementation type # TODO(elias): Refactor - since this isn't used for live apps, move type stub generation into genstub new_obj = typing.TypeVar(name, bound=obj.__bound__) # noqa setattr(new_obj, self._original_attr, obj) setattr(new_obj, SYNCHRONIZER_ATTR, self) setattr(new_obj, TARGET_INTERFACE_ATTR, interface) new_obj.__module__ = target_module if not hasattr(obj, self._wrapped_attr): setattr(obj, self._wrapped_attr, {}) getattr(obj, self._wrapped_attr)[interface] = new_obj return new_obj def nowrap(self, obj): setattr(obj, self._nowrap_attr, True) return obj def no_input_translation(self, obj): setattr(obj, self._input_translation_attr, False) return obj def no_output_translation(self, obj): setattr(obj, self._output_translation_attr, False) return obj def no_io_translation(self, obj): return self.no_input_translation(self.no_output_translation(obj)) # New interface that (almost) doesn't mutate objects def create_blocking(self, obj, name: Optional[str] = None, target_module: Optional[str] = None): wrapped = self._wrap(obj, Interface.BLOCKING, name, target_module=target_module) return wrapped def create_async(self, obj, name: Optional[str] = None, target_module: Optional[str] = None): wrapped = self._wrap(obj, Interface.ASYNC, name, target_module=target_module) return wrapped def is_synchronized(self, obj): if inspect.isclass(obj) or inspect.isfunction(obj): return hasattr(obj, self._original_attr) else: return hasattr(obj.__class__, self._original_attr)
(multiwrap_warning=False, async_leakage_warning=True)
16,146
synchronicity.synchronizer
__getstate__
null
def __getstate__(self): return dict([(attr, getattr(self, attr)) for attr in self._PICKLE_ATTRS])
(self)