# ORM helpers

## cast_if

`sqlalchemy_utils.functions.``cast_if`(expression, type_)

  Produce a CAST expression but only if given expression is not of given type already.

  Assume we have a model with two fields id (Integer) and name (String).

      import sqlalchemy as sa
      from sqlalchemy_utils import cast_if

      cast_if(User.id, sa.Integer)    # "user".id
      cast_if(User.name, sa.String)   # "user".name
      cast_if(User.id, sa.String)     # CAST("user".id AS TEXT)

  This function supports scalar values as well.

      cast_if(1, sa.Integer)          # 1
      cast_if('text', sa.String)      # 'text'
      cast_if(1, sa.String)           # CAST(1 AS TEXT)

  Parameters:

  - expression – A SQL expression, such as a ColumnElement expression or a Python string which will be coerced into a bound literal value.
  - type – A TypeEngine class or instance indicating the type to which the CAST should apply.

## escape_like

`sqlalchemy_utils.functions.``escape_like`(string, escape_char='*')

  Escape the string paremeter used in SQL LIKE expressions.

      from sqlalchemy_utils import escape_like

      query = session.query(User).filter(
          User.name.ilike(escape_like('John'))
      )

  Parameters:

  - string – a string to escape
  - escape_char – escape character

## get_bind

`sqlalchemy_utils.functions.``get_bind`(obj)

  Return the bind for given SQLAlchemy Engine / Connection / declarative model object.

  Parameters: | obj – SQLAlchemy Engine / Connection / declarative model object

      from sqlalchemy_utils import get_bind

      get_bind(session)  # Connection object

      get_bind(user)

## get_class_by_table

`sqlalchemy_utils.functions.``get_class_by_table`(base, table, data=None)

  Return declarative class associated with given table. If no class is found this function returns None. If multiple classes were found (polymorphic cases) additional data parameter can be given to hint which class to return.

      class User(Base):
          __tablename__ = 'entity'
          id = sa.Column(sa.Integer, primary_key=True)
          name = sa.Column(sa.String)

      get_class_by_table(Base, User.__table__)  # User class

  This function also supports models using single table inheritance. Additional data paratemer should be provided in these case.

      class Entity(Base):
          __tablename__ = 'entity'
          id = sa.Column(sa.Integer, primary_key=True)
          name = sa.Column(sa.String)
          type = sa.Column(sa.String)
          __mapper_args__ = {
              'polymorphic_on': type,
              'polymorphic_identity': 'entity'
          }

      class User(Entity):
          __mapper_args__ = {
              'polymorphic_identity': 'user'
          }

      # Entity class
      get_class_by_table(Base, Entity.__table__, {'type': 'entity'})

      # User class
      get_class_by_table(Base, Entity.__table__, {'type': 'user'})

  Parameters:

  - base – Declarative model base
  - table – SQLAlchemy Table object
  - data – Data row to determine the class in polymorphic scenarios

  Returns: | Declarative class or None.

## get_column_key

`sqlalchemy_utils.functions.``get_column_key`(model, column)

  Return the key for given column in given model.

  Parameters: | model – SQLAlchemy declarative model object

      class User(Base):
          __tablename__ = 'user'
          id = sa.Column(sa.Integer, primary_key=True)
          name = sa.Column('_name', sa.String)

      get_column_key(User, User.__table__.c._name)  # 'name'

## get_columns

`sqlalchemy_utils.functions.``get_columns`(mixed)

  Return a collection of all Column objects for given SQLAlchemy object.

  The type of the collection depends on the type of the object to return the columns from.

      get_columns(User)

      get_columns(User())

      get_columns(User.__table__)

      get_columns(User.__mapper__)

      get_columns(sa.orm.aliased(User))

      get_columns(sa.orm.alised(User.__table__))

  Parameters: | mixed – SA Table object, SA Mapper, SA declarative class, SA declarative class instance or an alias of any of these objects

## get_declarative_base

`sqlalchemy_utils.functions.``get_declarative_base`(model)

  Returns the declarative base for given model class.

  Parameters: | model – SQLAlchemy declarative model

## get_hybrid_properties

`sqlalchemy_utils.functions.``get_hybrid_properties`(model)

  Returns a dictionary of hybrid property keys and hybrid properties for given SQLAlchemy declarative model / mapper.

  Consider the following model

      from sqlalchemy.ext.hybrid import hybrid_property

      class Category(Base):
          __tablename__ = 'category'
          id = sa.Column(sa.Integer, primary_key=True)
          name = sa.Column(sa.Unicode(255))

          @hybrid_property
          def lowercase_name(self):
              return self.name.lower()

          @lowercase_name.expression
          def lowercase_name(cls):
              return sa.func.lower(cls.name)

  You can now easily get a list of all hybrid property names

      from sqlalchemy_utils import get_hybrid_properties

      get_hybrid_properties(Category).keys()  # ['lowercase_name']

  This function also supports aliased classes

      get_hybrid_properties(
          sa.orm.aliased(Category)
      ).keys()  # ['lowercase_name']

  Parameters: | model – SQLAlchemy declarative model or mapper

## get_mapper

`sqlalchemy_utils.functions.``get_mapper`(mixed)

  Return related SQLAlchemy Mapper for given SQLAlchemy object.

  Parameters: | mixed – SQLAlchemy Table / Alias / Mapper / declarative model object

      from sqlalchemy_utils import get_mapper

      get_mapper(User)

      get_mapper(User())

      get_mapper(User.__table__)

      get_mapper(User.__mapper__)

      get_mapper(sa.orm.aliased(User))

      get_mapper(sa.orm.aliased(User.__table__))

  Raises:
    ValueError: if multiple mappers were found for given argument

## get_query_entities

`sqlalchemy_utils.functions.``get_query_entities`(query)

  Return a list of all entities present in given SQLAlchemy query object.

  Examples:

      from sqlalchemy_utils import get_query_entities

      query = session.query(Category)

      get_query_entities(query)  # [<Category>]

      query = session.query(Category.id)

      get_query_entities(query)  # [<Category>]

  This function also supports queries with joins.

      query = session.query(Category).join(Article)

      get_query_entities(query)  # [<Category>, <Article>]

  Parameters: | query – SQLAlchemy Query object

## get_primary_keys

`sqlalchemy_utils.functions.``get_primary_keys`(mixed)

  Return an OrderedDict of all primary keys for given Table object, declarative class or declarative class instance.

  Parameters: | mixed – SA Table object, SA declarative class or SA declarative class instance

      get_primary_keys(User)

      get_primary_keys(User())

      get_primary_keys(User.__table__)

      get_primary_keys(User.__mapper__)

      get_primary_keys(sa.orm.aliased(User))

      get_primary_keys(sa.orm.aliased(User.__table__))

  See also

  `get_columns()`

## get_tables

`sqlalchemy_utils.functions.``get_tables`(mixed)

  Return a set of tables associated with given SQLAlchemy object.

  Let’s say we have three classes which use joined table inheritance TextItem, Article and BlogPost. Article and BlogPost inherit TextItem.

      get_tables(Article)  # set([Table('article', ...), Table('text_item')])

      get_tables(Article())

      get_tables(Article.__mapper__)

  If the TextItem entity is using with_polymorphic=’*’ then this function returns all child tables (article and blog_post) as well.

      get_tables(TextItem)  # set([Table('text_item', ...)], ...])

  Parameters: | mixed – SQLAlchemy Mapper, Declarative class, Column, InstrumentedAttribute or a SA Alias object wrapping any of these objects.

## get_type

`sqlalchemy_utils.functions.``get_type`(expr)

  Return the associated type with given Column, InstrumentedAttribute, ColumnProperty, RelationshipProperty or other similar SQLAlchemy construct.

  For constructs wrapping columns this is the column type. For relationships this function returns the relationship mapper class.

  Parameters: | expr – SQLAlchemy Column, InstrumentedAttribute, ColumnProperty or other similar SA construct.

      class User(Base):
          __tablename__ = 'user'
          id = sa.Column(sa.Integer, primary_key=True)
          name = sa.Column(sa.String)

      class Article(Base):
          __tablename__ = 'article'
          id = sa.Column(sa.Integer, primary_key=True)
          author_id = sa.Column(sa.Integer, sa.ForeignKey(User.id))
          author = sa.orm.relationship(User)

      get_type(User.__table__.c.name)  # sa.String()
      get_type(User.name)  # sa.String()
      get_type(User.name.property)  # sa.String()

      get_type(Article.author)  # User

## has_changes

`sqlalchemy_utils.functions.``has_changes`(obj, attrs=None, exclude=None)

  Simple shortcut function for checking if given attributes of given declarative model object have changed during the session. Without parameters this checks if given object has any modificiations. Additionally exclude parameter can be given to check if given object has any changes in any attributes other than the ones given in exclude.

      from sqlalchemy_utils import has_changes

      user = User()

      has_changes(user, 'name')  # False

      user.name = u'someone'

      has_changes(user, 'name')  # True

      has_changes(user)  # True

  You can check multiple attributes as well.

      has_changes(user, ['age'])  # True

      has_changes(user, ['name', 'age'])  # True

  This function also supports excluding certain attributes.

      has_changes(user, exclude=['name'])  # False

      has_changes(user, exclude=['age'])  # True

  Parameters:

  - obj – SQLAlchemy declarative model object
  - attrs – Names of the attributes
  - exclude – Names of the attributes to exclude

## identity

`sqlalchemy_utils.functions.``identity`(obj_or_class)

  Return the identity of given sqlalchemy declarative model class or instance as a tuple. This differs from obj._sa_instance_state.identity in a way that it always returns the identity even if object is still in transient state ( new object that is not yet persisted into database). Also for classes it returns the identity attributes.

      from sqlalchemy import inspect
      from sqlalchemy_utils import identity

      user = User(name=u'John Matrix')
      session.add(user)
      identity(user)  # None
      inspect(user).identity  # None

      session.flush()  # User now has id but is still in transient state

      identity(user)  # (1,)
      inspect(user).identity  # None

      session.commit()

      identity(user)  # (1,)
      inspect(user).identity  # (1, )

  You can also use identity for classes:

      identity(User)  # (User.id, )

  Parameters: | obj – SQLAlchemy declarative model object

## is_loaded

`sqlalchemy_utils.functions.``is_loaded`(obj, prop)

  Return whether or not given property of given object has been loaded.

      class Article(Base):
          __tablename__ = 'article'
          id = sa.Column(sa.Integer, primary_key=True)
          name = sa.Column(sa.String)
          content = sa.orm.deferred(sa.Column(sa.String))

      article = session.query(Article).get(5)

      # name gets loaded since its not a deferred property
      assert is_loaded(article, 'name')

      # content has not yet been loaded since its a deferred property
      assert not is_loaded(article, 'content')

  Parameters:

  - obj – SQLAlchemy declarative model object
  - prop – Name of the property or InstrumentedAttribute

## make_order_by_deterministic

`sqlalchemy_utils.functions.``make_order_by_deterministic`(query)

  Make query order by deterministic (if it isn’t already). Order by is considered deterministic if it contains column that is unique index ( either it is a primary key or has a unique index). Many times it is design flaw to order by queries in nondeterministic manner.

  Consider a User model with three fields: id (primary key), favorite color and email (unique).:

      from sqlalchemy_utils import make_order_by_deterministic

      query = session.query(User).order_by(User.favorite_color)

      query = make_order_by_deterministic(query)
      print query  # 'SELECT ... ORDER BY "user".favorite_color, "user".id'

      query = session.query(User).order_by(User.email)

      query = make_order_by_deterministic(query)
      print query  # 'SELECT ... ORDER BY "user".email'

      query = session.query(User).order_by(User.id)

      query = make_order_by_deterministic(query)
      print query  # 'SELECT ... ORDER BY "user".id'

## naturally_equivalent

`sqlalchemy_utils.functions.``naturally_equivalent`(obj, obj2)

  Returns whether or not two given SQLAlchemy declarative instances are naturally equivalent (all their non primary key properties are equivalent).

      from sqlalchemy_utils import naturally_equivalent

      user = User(name=u'someone')
      user2 = User(name=u'someone')

      user == user2  # False

      naturally_equivalent(user, user2)  # True

  Parameters:

  - obj – SQLAlchemy declarative model object
  - obj2 – SQLAlchemy declarative model object to compare with obj

## quote

`sqlalchemy_utils.functions.``quote`(mixed, ident)

  Conditionally quote an identifier.

      from sqlalchemy_utils import quote

      engine = create_engine('sqlite:///:memory:')

      quote(engine, 'order')
      # '"order"'

      quote(engine, 'some_other_identifier')
      # 'some_other_identifier'

  Parameters:

  - mixed – SQLAlchemy Session / Connection / Engine / Dialect object.
  - ident – identifier to conditionally quote

## sort_query

`sqlalchemy_utils.functions.``sort_query`(query, *args, **kwargs)

  Applies an sql ORDER BY for given query. This function can be easily used with user-defined sorting.

  The examples use the following model definition:

      import sqlalchemy as sa
      from sqlalchemy import create_engine
      from sqlalchemy.orm import sessionmaker
      from sqlalchemy.ext.declarative import declarative_base
      from sqlalchemy_utils import sort_query

      engine = create_engine(
          'sqlite:///'
      )
      Base = declarative_base()
      Session = sessionmaker(bind=engine)
      session = Session()

      class Category(Base):
          __tablename__ = 'category'
          id = sa.Column(sa.Integer, primary_key=True)
          name = sa.Column(sa.Unicode(255))

      class Article(Base):
          __tablename__ = 'article'
          id = sa.Column(sa.Integer, primary_key=True)
          name = sa.Column(sa.Unicode(255))
          category_id = sa.Column(sa.Integer, sa.ForeignKey(Category.id))

          category = sa.orm.relationship(
              Category, primaryjoin=category_id == Category.id
          )

  1. Applying simple ascending sort

      query = session.query(Article)
      query = sort_query(query, 'name')

  2. Applying descending sort

      query = sort_query(query, '-name')

  3. Applying sort to custom calculated label

      query = session.query(
          Category, sa.func.count(Article.id).label('articles')
      )
      query = sort_query(query, 'articles')

  4. Applying sort to joined table column

      query = session.query(Article).join(Article.category)
      query = sort_query(query, 'category-name')

  Parameters:

  - query – query to be modified
  - sort – string that defines the label or column to sort the query by
  - silent – Whether or not to raise exceptions if unknown sort column is passed. By default this is True indicating that no errors should be raised for unknown columns.