class documentation

class FunctionElement(Executable, ColumnElement, FromClause, Generative):

Known subclasses: sqlalchemy.sql.functions.Function

View In Hierarchy

Base for SQL function-oriented constructs.

See Also

:ref:`coretutorial_functions` - in the Core tutorial

.Function - named SQL function.

.func - namespace which produces registered or ad-hoc .Function instances.

.GenericFunction - allows creation of registered function types.

Method __init__ Construct a .FunctionElement.
Method alias Produce a _expression.Alias construct against this .FunctionElement.
Method as​_comparison Interpret this expression as a boolean comparison between two values.
Method column​_valued Return this _functions.FunctionElement as a column expression that selects from itself as a FROM clause.
Method execute Execute this .FunctionElement against an embedded 'bind'.
Method filter Produce a FILTER clause against this function.
Method over Produce an OVER clause against this function.
Method scalar Execute this .FunctionElement against an embedded 'bind' and return a scalar value.
Method scalar​_table​_valued Return a column expression that's against this _functions.FunctionElement as a scalar table-valued expression.
Method select Produce a _expression.select construct against this .FunctionElement.
Method self​_group Apply a 'grouping' to this _expression.ClauseElement.
Method table​_valued Return a _sql.TableValuedAlias representation of this _functions.FunctionElement with table-valued expressions added.
Method within​_group Produce a WITHIN GROUP (ORDER BY expr) clause against this function.
Method 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 .WithinGroup construct.
Method ​_bind​_param Undocumented
Method ​_execute​_on​_connection Undocumented
Method clauses Return the underlying .ClauseList which contains the arguments for this .FunctionElement.
Class Variable ​_non​_anon​_label Undocumented
Class Variable ​_table​_value​_type Undocumented
Class Variable ​_traverse​_internals Undocumented
Class Variable ​_with​_ordinality Undocumented
Class Variable packagenames Undocumented
Instance Variable ​_has​_args Undocumented
Instance Variable clause​_expr Undocumented
Property ​_all​_selected​_columns A sequence of column expression objects that represents the "selected" columns of this _expression.ReturnsRows.
Property ​_from​_objects Undocumented
Property ​_proxy​_key Undocumented
Property columns The set of columns exported by this .FunctionElement.
Property entity​_namespace overrides FromClause.entity_namespace as functions are generally column expressions and not FromClauses.
Property exported​_columns A _expression.ColumnCollection that represents the "exported" columns of this _expression.Selectable.

Inherited from Executable:

Method ​_add​_context​_option Add a context option to this statement.
Method ​_set​_compile​_options Assign the compile options to a new value.
Method ​_update​_compile​_options update the _compile_options with new keys.
Method execution​_options Set non-SQL options for the statement which take effect during execution.
Method get​_execution​_options Get the non-SQL options which will take effect during execution.
Method options Apply options to this statement.
Class Variable ​_bind Undocumented
Class Variable ​_executable​_traverse​_internals Undocumented
Class Variable ​_with​_context​_options Undocumented
Class Variable ​_with​_options Undocumented
Class Variable is​_delete Undocumented
Class Variable is​_dml Undocumented
Class Variable is​_insert Undocumented
Class Variable is​_select Undocumented
Class Variable is​_text Undocumented
Class Variable is​_update Undocumented
Class Variable supports​_execution Undocumented
Instance Variable ​_compile​_options Undocumented
Instance Variable ​_execution​_options Undocumented
Property ​_effective​_plugin​_target Undocumented
Property bind Returns the _engine.Engine or _engine.Connection to which this .Executable is bound, or None if none found.

Inherited from StatementRole (via Executable):

Class Variable ​_propagate​_attrs Undocumented
Class Variable ​_role​_name Undocumented

Inherited from SQLRole (via Executable, StatementRole):

Class Variable allows​_lambda Undocumented
Class Variable uses​_inspection Undocumented

Inherited from Generative (via Executable):

Method ​_generate Undocumented

Inherited from FromClause:

Method is​_derived​_from Return True if this _expression.FromClause is 'derived' from the given FromClause.
Method join Return a _expression.Join from this _expression.FromClause to another FromClause.
Method outerjoin No summary
Method tablesample Return a TABLESAMPLE alias of this _expression.FromClause.
Class Variable c Undocumented
Class Variable schema Define the 'schema' attribute for this _expression.FromClause.
Instance Variable foreign​_keys Return the collection of _schema.ForeignKey marker objects which this FromClause references.
Instance Variable primary​_key Return the iterable collection of _schema.Column objects which comprise the primary key of this _selectable.FromClause.
Method ​_anonymous​_fromclause Undocumented
Method ​_generate​_fromclause​_column​_proxies Undocumented
Method ​_init​_collections Undocumented
Method ​_is​_lexical​_equivalent Return True if this _expression.FromClause and the other represent the same lexical identity.
Method ​_populate​_column​_collection Called on subclasses to establish the .c collection.
Method ​_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.
Method ​_reset​_column​_collection Reset the attributes linked to the FromClause.c attribute.
Class Variable __visit​_name__ Undocumented
Class Variable ​_hide​_froms Undocumented
Class Variable ​_is​_from​_clause Undocumented
Class Variable ​_is​_join Undocumented
Class Variable ​_select​_iterable Undocumented
Class Variable ​_use​_schema​_map Undocumented
Class Variable is​_selectable Undocumented
Class Variable named​_with​_column Undocumented
Instance Variable ​_columns Undocumented
Property ​_cols​_populated Undocumented
Property description A brief description of this _expression.FromClause.

Inherited from FromClauseRole (via FromClause, AnonymizedFromClauseRole, StrictFromClauseRole):

Class Variable ​_is​_subquery Undocumented
Class Variable ​_role​_name Undocumented

Inherited from AllowsLambdaRole (via FromClause, AnonymizedFromClauseRole, StrictFromClauseRole, FromClauseRole, ColumnsClauseRole):

Class Variable allows​_lambda Undocumented

Inherited from UsesInspection (via FromClause, AnonymizedFromClauseRole, StrictFromClauseRole, FromClauseRole, ColumnsClauseRole):

Class Variable ​_post​_inspect Undocumented
Class Variable uses​_inspection Undocumented

Inherited from SQLRole (via FromClause, AnonymizedFromClauseRole, StrictFromClauseRole, FromClauseRole, ColumnsClauseRole, ColumnListRole):

Class Variable allows​_lambda Undocumented
Class Variable uses​_inspection Undocumented

Inherited from AllowsLambdaRole (via FromClause, AnonymizedFromClauseRole, StrictFromClauseRole, FromClauseRole, JoinTargetRole):

Class Variable allows​_lambda Undocumented

Inherited from UsesInspection (via FromClause, AnonymizedFromClauseRole, StrictFromClauseRole, FromClauseRole, JoinTargetRole):

Class Variable ​_post​_inspect Undocumented
Class Variable uses​_inspection Undocumented

Inherited from SQLRole (via FromClause, AnonymizedFromClauseRole, StrictFromClauseRole, FromClauseRole, JoinTargetRole, StructuralRole):

Class Variable allows​_lambda Undocumented
Class Variable uses​_inspection Undocumented

Inherited from Selectable (via FromClause):

Method corresponding​_column No summary
Method lateral Return a LATERAL alias of this _expression.Selectable.
Method replace​_selectable Replace all occurrences of _expression.FromClause 'old' with the given _expression.Alias object, returning a copy of this _expression.FromClause.

Inherited from ReturnsRows (via FromClause, Selectable):

Class Variable ​_is​_lateral Undocumented
Class Variable ​_is​_returns​_rows Undocumented
Class Variable ​_is​_select​_statement Undocumented
Property selectable Undocumented

Inherited from ReturnsRowsRole (via FromClause, Selectable, ReturnsRows):

Class Variable ​_role​_name Undocumented

Inherited from SQLRole (via FromClause, Selectable, ReturnsRows, ReturnsRowsRole):

Class Variable allows​_lambda Undocumented
Class Variable uses​_inspection Undocumented

Inherited from ClauseElement (via FromClause, Selectable, ReturnsRows):

Method compare Compare this _expression.ClauseElement to the given _expression.ClauseElement.
Method compile Compile this SQL expression.
Method params Return a copy with _expression.bindparam elements replaced.
Method unique​_params Return a copy with _expression.bindparam elements replaced.
Method __bool__ Undocumented
Method __getstate__ Undocumented
Method __invert__ Undocumented
Method __repr__ Undocumented
Method __str__ Undocumented
Method ​_clone Create a shallow copy of this ClauseElement.
Method ​_cloned​_set Return the set consisting all cloned ancestors of this ClauseElement.
Method ​_compile​_w​_cache Undocumented
Method ​_compiler Return a compiler appropriate for this ClauseElement, given a Dialect.
Method ​_negate Undocumented
Method ​_negate​_in​_binary a hook to allow the right side of a binary expression to respond to a negation of the binary expression.
Method ​_replace​_params Undocumented
Method ​_set​_propagate​_attrs Undocumented
Method ​_ungroup Return this _expression.ClauseElement without any groupings.
Method ​_with​_binary​_element​_type in the context of binary expression, convert the type of this object to the one given.
Class Variable ​_cache​_key​_traversal Undocumented
Class Variable ​_is​_bind​_parameter Undocumented
Class Variable ​_is​_clause​_list Undocumented
Class Variable ​_is​_clone​_of Undocumented
Class Variable ​_is​_from​_container Undocumented
Class Variable ​_is​_immutable Undocumented
Class Variable ​_is​_lambda​_element Undocumented
Class Variable ​_is​_select​_container Undocumented
Class Variable ​_is​_singleton​_constant Undocumented
Class Variable ​_is​_text​_clause Undocumented
Class Variable ​_is​_textual Undocumented
Class Variable ​_order​_by​_label​_element Undocumented
Class Variable bind Undocumented
Class Variable is​_clause​_element Undocumented
Class Variable stringify​_dialect Undocumented
Class Variable supports​_execution Undocumented
Instance Variable ​_propagate​_attrs like annotations, however these propagate outwards liberally as SQL constructs are built, and are set up at construction time.
Property ​_constructor return the 'constructor' for this ClauseElement.

Inherited from SQLRole (via FromClause, Selectable, ReturnsRows, ClauseElement):

Class Variable allows​_lambda Undocumented
Class Variable uses​_inspection Undocumented

Inherited from SupportsWrappingAnnotations (via FromClause, Selectable, ReturnsRows, ClauseElement):

Method ​_annotate return a copy of this ClauseElement with annotations updated by the given dictionary.
Method ​_deannotate return a copy of this _expression.ClauseElement with annotations removed.
Method ​_with​_annotations return a copy of this ClauseElement with annotations replaced by the given dictionary.

Inherited from SupportsAnnotations (via FromClause, Selectable, ReturnsRows, ClauseElement, SupportsWrappingAnnotations):

Property ​_annotations​_cache​_key Undocumented

Inherited from MemoizedHasCacheKey (via FromClause, Selectable, ReturnsRows, ClauseElement):

Method ​_generate​_cache​_key return a cache key.

Inherited from HasCacheKey (via FromClause, Selectable, ReturnsRows, ClauseElement, MemoizedHasCacheKey):

Class Variable inherit​_cache Indicate if this .HasCacheKey instance should make use of the cache key generation scheme used by its immediate superclass.
Class Method ​_generate​_cache​_attrs generate cache key dispatcher for a new class.
Class Method ​_generate​_cache​_key​_for​_object Undocumented
Method ​_gen​_cache​_key return an optional cache key.
Class Variable __slots__ Undocumented
Class Variable ​_hierarchy​_supports​_caching private attribute which may be set to False to prevent the inherit_cache warning from being emitted for a hierarchy of subclasses.
Class Variable ​_is​_has​_cache​_key Undocumented

Inherited from HasCopyInternals (via FromClause, Selectable, ReturnsRows, ClauseElement):

Method ​_copy​_internals Reassign internal elements to be clones of themselves.

Inherited from Traversible (via FromClause, Selectable, ReturnsRows, ClauseElement):

Method get​_children Return immediate child .visitors.Traversible elements of this .visitors.Traversible.
Method __class​_getitem__ Undocumented

Inherited from Generative:

Method ​_generate Undocumented
def __init__(self, *clauses, **kwargs):

Construct a .FunctionElement.

See Also

.func

.Function

Parameters
*clauseslist of column expressions that form the arguments of the SQL function call.
**kwargsadditional kwargs are typically consumed by subclasses.
def alias(self, name=None):

Produce a _expression.Alias construct against this .FunctionElement.

Tip

The _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 _functions.FunctionElement including _functions.FunctionElement.table_valued, and _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 _function.FunctionElement.table_valued method first to establish named columns.

e.g.:

>>> from sqlalchemy import func, select, column
>>> data_view = func.unnest([1, 2, 3]).alias("data_view")
>>> print(select(data_view.column))
SELECT data_view
FROM unnest(:unnest_1) AS data_view

The _functions.FunctionElement.column_valued method provides a shortcut for the above pattern:

>>> data_view = func.unnest([1, 2, 3]).column_valued("data_view")
>>> print(select(data_view))
SELECT data_view
FROM unnest(:unnest_1) AS data_view
New in version 1.4.0b2: Added the .column accessor

See Also

:ref:`tutorial_functions_table_valued` - in the :ref:`unified_tutorial`

_functions.FunctionElement.table_valued

_functions.FunctionElement.scalar_table_valued

_functions.FunctionElement.column_valued

def as_comparison(self, left_index, right_index):

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 .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 .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 .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.

New in version 1.3.

See Also

:ref:`relationship_custom_operator_sql_function` - example use within the ORM

Parameters
left​_indexthe integer 1-based index of the function argument that serves as the "left" side of the expression.
right​_indexthe integer 1-based index of the function argument that serves as the "right" side of the expression.
def column_valued(self, name=None):

Return this _functions.FunctionElement as a column expression that selects from itself as a FROM clause.

E.g.:

>>> from sqlalchemy import select, func
>>> gs = func.generate_series(1, 5, -1).column_valued()
>>> print(select(gs))
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

See Also

:ref:`tutorial_functions_column_valued` - in the :ref:`unified_tutorial`

:ref:`postgresql_column_valued` - in the :ref:`postgresql_toplevel` documentation

_functions.FunctionElement.table_valued

@util.deprecated_20(':meth:`.FunctionElement.execute`', alternative='All statement execution in SQLAlchemy 2.0 is performed by the :meth:`_engine.Connection.execute` method of :class:`_engine.Connection`, or in the ORM by the :meth:`.Session.execute` method of :class:`.Session`.')
def execute(self):

Execute this .FunctionElement against an embedded 'bind'.

This first calls ~.FunctionElement.select to produce a SELECT construct.

Note that .FunctionElement can be passed to the .Connectable.execute method of _engine.Connection or _engine.Engine.

def filter(self, *criterion):

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)
New in version 1.0.0.

See Also

:ref:`tutorial_functions_within_group` - in the :ref:`unified_tutorial`

.FunctionFilter

.funcfilter

def over(self, partition_by=None, order_by=None, rows=None, range_=None):

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 _expression.over for a full description.

See Also

_expression.over

:ref:`tutorial_window_functions` - in the :ref:`unified_tutorial`

@util.deprecated_20(':meth:`.FunctionElement.scalar`', alternative='Scalar execution in SQLAlchemy 2.0 is performed by the :meth:`_engine.Connection.scalar` method of :class:`_engine.Connection`, or in the ORM by the :meth:`.Session.scalar` method of :class:`.Session`.')
def scalar(self):

Execute this .FunctionElement against an embedded 'bind' and return a scalar value.

This first calls ~.FunctionElement.select to produce a SELECT construct.

Note that .FunctionElement can be passed to the .Connectable.scalar method of _engine.Connection or _engine.Engine.

def scalar_table_valued(self, name, type_=None):

Return a column expression that's against this _functions.FunctionElement as a scalar table-valued expression.

The returned expression is similar to that returned by a single column accessed off of a _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.:

>>> from sqlalchemy import func, select
>>> fn = func.jsonb_each("{'k', 'v'}").scalar_table_valued("key")
>>> print(select(fn))
SELECT (jsonb_each(:jsonb_each_1)).key
New in version 1.4.0b2.

See Also

_functions.FunctionElement.table_valued

_functions.FunctionElement.alias

_functions.FunctionElement.column_valued

def select(self):

Produce a _expression.select construct against this .FunctionElement.

This is shorthand for:

s = select(function_element)
def self_group(self, against=None):

Apply a 'grouping' to this _expression.ClauseElement.

This method is overridden by subclasses to return a "grouping" construct, i.e. parenthesis. In particular it's used by "binary" expressions to provide a grouping around themselves when placed into a larger expression, as well as by _expression.select constructs when placed into the FROM clause of another _expression.select. (Note that subqueries should be normally created using the _expression.Select.alias method, as many platforms require nested SELECT statements to be named).

As expressions are composed together, the application of self_group is automatic - end-user code should never need to use this method directly. Note that SQLAlchemy's clause constructs take operator precedence into account - so parenthesis might not be needed, for example, in an expression like x OR (y AND z) - AND takes precedence over OR.

The base self_group method of _expression.ClauseElement just returns self.

def table_valued(self, *expr, **kw):

Return a _sql.TableValuedAlias representation of this _functions.FunctionElement with table-valued expressions added.

e.g.:

>>> fn = (
...     func.generate_series(1, 5).
...     table_valued("value", "start", "stop", "step")
... )

>>> print(select(fn))
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

>>> print(select(fn.c.value, fn.c.stop).where(fn.c.value > 2))
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

A WITH ORDINALITY expression may be generated by passing the keyword argument "with_ordinality":

>>> fn = func.generate_series(4, 1, -1).table_valued("gen", with_ordinality="ordinality")
>>> print(select(fn))
SELECT anon_1.gen, anon_1.ordinality
FROM generate_series(:generate_series_1, :generate_series_2, :generate_series_3) WITH ORDINALITY AS anon_1
New in version 1.4.0b2.

See Also

:ref:`tutorial_functions_table_valued` - in the :ref:`unified_tutorial`

:ref:`postgresql_table_valued` - in the :ref:`postgresql_toplevel` documentation

_functions.FunctionElement.scalar_table_valued - variant of _functions.FunctionElement.table_valued which delivers the complete table valued expression as a scalar column expression

_functions.FunctionElement.column_valued

_sql.TableValuedAlias.render_derived - renders the alias using a derived column clause, e.g. AS name(col1, col2, ...)

Parameters
*exprA series of string column names that will be added to the .c collection of the resulting _sql.TableValuedAlias construct as columns. _sql.column objects with or without datatypes may also be used.
**kwUndocumented
nameoptional name to assign to the alias name that's generated. If omitted, a unique anonymizing name is used.
with​_ordinalitystring 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 _sql.TableValuedAlias.
def within_group(self, *order_by):

Produce a WITHIN GROUP (ORDER BY expr) clause against this function.

Used against so-called "ordered set aggregate" and "hypothetical set aggregate" functions, including .percentile_cont, .rank, .dense_rank, etc.

See _expression.within_group for a full description.

New in version 1.1.
def within_group_type(self, within_group):

For types that define their return type as based on the criteria within a WITHIN GROUP (ORDER BY) expression, called by the .WithinGroup construct.

Returns None by default, in which case the function's normal .type is used.

def _bind_param(self, operator, obj, type_=None, **kw):

Undocumented

def _execute_on_connection(self, connection, multiparams, params, execution_options):
@HasMemoized.memoized_attribute
def clauses(self):
Return the underlying .ClauseList which contains the arguments for this .FunctionElement.
_non_anon_label =

Undocumented

_table_value_type =

Undocumented

_traverse_internals =

Undocumented

_with_ordinality: bool =

Undocumented

packagenames: tuple =

Undocumented

_has_args =

Undocumented

clause_expr =

Undocumented

@property
_all_selected_columns =

A sequence of column expression objects that represents the "selected" columns of this _expression.ReturnsRows.

This is typically equivalent to .exported_columns except it is delivered in the form of a straight sequence and not keyed _expression.ColumnCollection.

@property
_from_objects =
@property
_proxy_key =

Undocumented

@property
columns =

The set of columns exported by this .FunctionElement.

This is a placeholder collection that allows the function to be placed in the FROM clause of a statement:

>>> from sqlalchemy import column, select, func
>>> stmt = select(column('x'), column('y')).select_from(func.myfunction())
>>> print(stmt)
SELECT x, y FROM myfunction()

The above form is a legacy feature that is now superseded by the fully capable _functions.FunctionElement.table_valued method; see that method for details.

See Also

_functions.FunctionElement.table_valued - generates table-valued SQL function expressions.

@property
entity_namespace =
overrides FromClause.entity_namespace as functions are generally column expressions and not FromClauses.
@property
exported_columns =

A _expression.ColumnCollection that represents the "exported" columns of this _expression.Selectable.

The "exported" columns for a _expression.FromClause object are synonymous with the _expression.FromClause.columns collection.

New in version 1.4.

See Also

_expression.Selectable.exported_columns

_expression.SelectBase.exported_columns