# SQLAlchemy 0.9 Documentation

Search:
Release: 0.9.3 | Release Date: February 19, 2014

# SQL and Generic Functions

SQL functions which are known to SQLAlchemy with regards to database-specific rendering, return types and argument behavior. Generic functions are invoked like all SQL functions, using the `func` attribute:

    select([func.count()]).select_from(sometable)

Note that any name not known to `func` generates the function name as is - there is no restriction on what SQL functions can be called, known or unknown to SQLAlchemy, built-in or user defined. The section here only describes those functions where SQLAlchemy already knows what argument and return types are in use.

SQL function API, factories, and built-in functions.

class `sqlalchemy.sql.functions.``AnsiFunction`(**kwargs)

  Bases: `sqlalchemy.sql.functions.GenericFunction`

  `identifier` = 'AnsiFunction'
  `name` = 'AnsiFunction'

class `sqlalchemy.sql.functions.``Function`(name, *clauses, **kw)

  Bases: `sqlalchemy.sql.functions.FunctionElement`

  Describe a named SQL function.

  See the superclass `FunctionElement` for a description of public methods.

  See also

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

  `GenericFunction` - allows creation of registered function types.

  `__init__`(name, *clauses, **kw)

    Construct a `Function`.

    The `func` construct is normally used to construct new `Function` instances.

class `sqlalchemy.sql.functions.``FunctionElement`(*clauses, **kwargs)

  Bases: `sqlalchemy.sql.expression.Executable`, `sqlalchemy.sql.expression.ColumnElement`, `sqlalchemy.sql.expression.FromClause`

  Base for SQL function-oriented constructs.

  See also

  `Function` - named SQL function.

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

  `GenericFunction` - allows creation of registered function types.

  `__init__`(*clauses, **kwargs)

    Construct a `FunctionElement`.

  `clauses`

    Return the underlying `ClauseList` which contains the arguments for this `FunctionElement`.

  `columns`

    Fulfill the ‘columns’ contract of `ColumnElement`.

    Returns a single-element list consisting of this object.

  `execute`()

    Execute this `FunctionElement` against an embedded ‘bind’.

    This first calls `select()` to produce a SELECT construct.

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

  `get_children`(**kwargs)
  `over`(partition_by=None, order_by=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 `over()` for a full description.

    New in version 0.7.

  `packagenames` = ()
  `scalar`()

    Execute this `FunctionElement` against an embedded ‘bind’ and return a scalar value.

    This first calls `select()` to produce a SELECT construct.

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

  `select`()

    Produce a `select()` construct against this `FunctionElement`.

    This is shorthand for:

        s = select([function_element])

class `sqlalchemy.sql.functions.``GenericFunction`(*args, **kwargs)

  Bases: `sqlalchemy.sql.functions.Function`

  Define a ‘generic’ function.

  A generic function is a pre-established `Function` class that is instantiated automatically when called by name from the `func` attribute. Note that calling any name from `func` has the effect that a new `Function` instance is created automatically, given that name. The primary use case for defining a `GenericFunction` class is so that a function of a particular name may be given a fixed return type. It can also include custom argument parsing schemes as well as additional methods.

  Subclasses of `GenericFunction` are automatically registered under the name of the class. For example, a user-defined function `as_utc()` would be available immediately:

      from sqlalchemy.sql.functions import GenericFunction
      from sqlalchemy.types import DateTime

      class as_utc(GenericFunction):
          type = DateTime

      print select([func.as_utc()])

  User-defined generic functions can be organized into packages by specifying the “package” attribute when defining `GenericFunction`. Third party libraries containing many functions may want to use this in order to avoid name conflicts with other systems. For example, if our `as_utc()` function were part of a package “time”:

      class as_utc(GenericFunction):
          type = DateTime
          package = "time"

  The above function would be available from `func` using the package name `time`:

      print select([func.time.as_utc()])

  A final option is to allow the function to be accessed from one name in `func` but to render as a different name. The `identifier` attribute will override the name used to access the function as loaded from `func`, but will retain the usage of `name` as the rendered name:

      class GeoBuffer(GenericFunction):
          type = Geometry
          package = "geo"
          name = "ST_Buffer"
          identifier = "buffer"

  The above function will render as follows:

      >>> print func.geo.buffer()
      ST_Buffer()

  New in version 0.8: `GenericFunction` now supports automatic registration of new functions as well as package and custom naming support.

  Changed in version 0.8: The attribute name `type` is used to specify the function’s return type at the class level. Previously, the name `__return_type__` was used. This name is still recognized for backwards-compatibility.

  `coerce_arguments` = True
  `identifier` = 'GenericFunction'
  `name` = 'GenericFunction'

class `sqlalchemy.sql.functions.``ReturnTypeFromArgs`(*args, **kwargs)

  Bases: `sqlalchemy.sql.functions.GenericFunction`

  Define a function whose return type is the same as its arguments.

  `identifier` = 'ReturnTypeFromArgs'
  `name` = 'ReturnTypeFromArgs'

class `sqlalchemy.sql.functions.``char_length`(arg, **kwargs)

  Bases: `sqlalchemy.sql.functions.GenericFunction`

  `identifier` = 'char_length'
  `name` = 'char_length'
  `type`

    alias of `Integer`

class `sqlalchemy.sql.functions.``coalesce`(*args, **kwargs)

  Bases: `sqlalchemy.sql.functions.ReturnTypeFromArgs`

  `identifier` = 'coalesce'
  `name` = 'coalesce'

class `sqlalchemy.sql.functions.``concat`(*args, **kwargs)

  Bases: `sqlalchemy.sql.functions.GenericFunction`

  `identifier` = 'concat'
  `name` = 'concat'
  `type`

    alias of `String`

class `sqlalchemy.sql.functions.``count`(expression=None, **kwargs)

  Bases: `sqlalchemy.sql.functions.GenericFunction`

  The ANSI COUNT aggregate function. With no arguments, emits COUNT *.

  `identifier` = 'count'
  `name` = 'count'
  `type`

    alias of `Integer`

class `sqlalchemy.sql.functions.``current_date`(**kwargs)

  Bases: `sqlalchemy.sql.functions.AnsiFunction`

  `identifier` = 'current_date'
  `name` = 'current_date'
  `type`

    alias of `Date`

class `sqlalchemy.sql.functions.``current_time`(**kwargs)

  Bases: `sqlalchemy.sql.functions.AnsiFunction`

  `identifier` = 'current_time'
  `name` = 'current_time'
  `type`

    alias of `Time`

class `sqlalchemy.sql.functions.``current_timestamp`(**kwargs)

  Bases: `sqlalchemy.sql.functions.AnsiFunction`

  `identifier` = 'current_timestamp'
  `name` = 'current_timestamp'
  `type`

    alias of `DateTime`

class `sqlalchemy.sql.functions.``current_user`(**kwargs)

  Bases: `sqlalchemy.sql.functions.AnsiFunction`

  `identifier` = 'current_user'
  `name` = 'current_user'
  `type`

    alias of `String`

`sqlalchemy.sql.functions.``func` = <sqlalchemy.sql.functions._FunctionGenerator object at 0x103880e10>

  Generate SQL function expressions.

  `func` is a special object instance which generates SQL functions based on name-based attributes, e.g.:

      >>> print func.count(1)
      count(:param_1)

  The element is a column-oriented SQL element like any other, and is used in that way:

      >>> print select([func.count(table.c.id)])
      SELECT count(sometable.id) FROM sometable

  Any name can be given to `func`. If the function name is unknown to SQLAlchemy, it will be rendered exactly as is. For common SQL functions which SQLAlchemy is aware of, the name may be interpreted as a generic function which will be compiled appropriately to the target database:

      >>> print func.current_timestamp()
      CURRENT_TIMESTAMP

  To call functions which are present in dot-separated packages, specify them in the same manner:

      >>> print func.stats.yield_curve(5, 10)
      stats.yield_curve(:yield_curve_1, :yield_curve_2)

  SQLAlchemy can be made aware of the return type of functions to enable type-specific lexical and result-based behavior. For example, to ensure that a string-based function returns a Unicode value and is similarly treated as a string in expressions, specify `Unicode` as the type:

      >>> print func.my_string(u'hi', type_=Unicode) + ' ' + \
      ... func.my_string(u'there', type_=Unicode)
      my_string(:my_string_1) || :my_string_2 || my_string(:my_string_3)

  The object returned by a `func` call is usually an instance of `Function`. This object meets the “column” interface, including comparison and labeling functions. The object can also be passed the `execute()` method of a `Connection` or `Engine`, where it will be wrapped inside of a SELECT statement first:

      print connection.execute(func.current_timestamp()).scalar()

  In a few exception cases, the `func` accessor will redirect a name to a built-in expression such as `cast()` or `extract()`, as these names have well-known meaning but are not exactly the same as “functions” from a SQLAlchemy perspective.

  New in version 0.8: `func` can return non-function expression constructs for common quasi-functional names like `cast()` and `extract()`.

  Functions which are interpreted as “generic” functions know how to calculate their return type automatically. For a listing of known generic functions, see SQL and Generic Functions.

class `sqlalchemy.sql.functions.``localtime`(**kwargs)

  Bases: `sqlalchemy.sql.functions.AnsiFunction`

  `identifier` = 'localtime'
  `name` = 'localtime'
  `type`

    alias of `DateTime`

class `sqlalchemy.sql.functions.``localtimestamp`(**kwargs)

  Bases: `sqlalchemy.sql.functions.AnsiFunction`

  `identifier` = 'localtimestamp'
  `name` = 'localtimestamp'
  `type`

    alias of `DateTime`

class `sqlalchemy.sql.functions.``max`(*args, **kwargs)

  Bases: `sqlalchemy.sql.functions.ReturnTypeFromArgs`

  `identifier` = 'max'
  `name` = 'max'

class `sqlalchemy.sql.functions.``min`(*args, **kwargs)

  Bases: `sqlalchemy.sql.functions.ReturnTypeFromArgs`

  `identifier` = 'min'
  `name` = 'min'

class `sqlalchemy.sql.functions.``next_value`(seq, **kw)

  Bases: `sqlalchemy.sql.functions.GenericFunction`

  Represent the ‘next value’, given a `Sequence` as it’s single argument.

  Compiles into the appropriate function on each backend, or will raise NotImplementedError if used on a backend that does not provide support for sequences.

  `identifier` = 'next_value'
  `name` = 'next_value'
  `type` = Integer()

class `sqlalchemy.sql.functions.``now`(*args, **kwargs)

  Bases: `sqlalchemy.sql.functions.GenericFunction`

  `identifier` = 'now'
  `name` = 'now'
  `type`

    alias of `DateTime`

class `sqlalchemy.sql.functions.``random`(*args, **kwargs)

  Bases: `sqlalchemy.sql.functions.GenericFunction`

  `identifier` = 'random'
  `name` = 'random'

`sqlalchemy.sql.functions.``register_function`(identifier, fn, package='_default')

  Associate a callable with a particular func. name.

  This is normally called by _GenericMeta, but is also available by itself so that a non-Function construct can be associated with the `func` accessor (i.e. CAST, EXTRACT).

class `sqlalchemy.sql.functions.``session_user`(**kwargs)

  Bases: `sqlalchemy.sql.functions.AnsiFunction`

  `identifier` = 'session_user'
  `name` = 'session_user'
  `type`

    alias of `String`

class `sqlalchemy.sql.functions.``sum`(*args, **kwargs)

  Bases: `sqlalchemy.sql.functions.ReturnTypeFromArgs`

  `identifier` = 'sum'
  `name` = 'sum'

class `sqlalchemy.sql.functions.``sysdate`(**kwargs)

  Bases: `sqlalchemy.sql.functions.AnsiFunction`

  `identifier` = 'sysdate'
  `name` = 'sysdate'
  `type`

    alias of `DateTime`

class `sqlalchemy.sql.functions.``user`(**kwargs)

  Bases: `sqlalchemy.sql.functions.AnsiFunction`

  `identifier` = 'user'
  `name` = 'user'
  `type`

    alias of `String`