Skip to content

SQLAlchemy Utilities

drizm_commons.sqla.encode

SQLAlchemy declarative compatible JSON encoder.

from drizm_commons.sqla.encode import *

SqlaDeclarativeEncoder

A custom JSON encoder for serializing SQLAlchemy declarative base instances.

Supports ISO8601 compliant datetime encoding.

default(self, o)

Implement this method in a subclass such that it returns a serializable object for o, or calls the base implementation (to raise a TypeError).

For example, to support arbitrary iterators, you could implement default like this::

def default(self, o):
    !!! try
        iterable = iter(o)
    except TypeError:
        pass
    !!! else
        return list(iterable)
    # Let the base class default method raise the TypeError
    return JSONEncoder.default(self, o)

dump(self, v)

Hook for custom object deserialization.

handle_failure(self, exc, value)

Can be overridden to provide handling for custom fields.

serialize_datetypes_to_iso(self, v)

Converts datetime formats to ISO8601 compliant strings.

drizm_commons.sqla.inspect

Introspection for various SQLAlchemy objects.

from drizm_commons.inspect import SQLAIntrospector

SQLAIntrospectorInterface

classname: str property readonly

Name of the Declarative Base class if available.

column_attrs: List[str] property readonly

Outputs all attributes of a mapped class, except for properties, dunders and methods, as well as some of the SQLAlchemy specific attributes.

This will include all columns that SQLAlchemy uses, but also attributes that the user has placed themselves.

foreign_keys(self, columns_only=False)

Retrieves the names and targets of foreign key columns on the table.

Parameters:

Name Type Description Default
columns_only bool

If True, this will only obtain the names of the columns.

False

Returns:

Type Description
Union[list, dict]

Either a list of column names or a dictionary of column names and Foreign key targets.

primary_keys(self, retrieve_constraint=False)

Return a list of the names of all primary key columns of the model.

Parameters:

Name Type Description Default
retrieve_constraint Optional[bool]

If set to True, the actual SQLA constraint objects will be returned as a list

False

unique_keys(self, include_pks=True)

Obtains all unique key column names of the object.

Parameters:

Name Type Description Default
include_pks Optional[bool]

If set False, this will not include primary-key columns in the selection.

True

Returns:

Type Description
List[str]

A list of column names, that have a unique constraint on them.

is_mapped_class(cls)

Check whether a given class has been mapped by SQLAlchemy.

Parameters:

Name Type Description Default
cls Type[sqlalchemy.ext.declarative.api.DeclarativeMeta]

The declarative class to be checked for mapping.

required

Returns:

Type Description
bool

True if the class is a mapped SQLAlchemy declarative class, else False.

SQLAIntrospector(o)

Factory returning a matching introspector class.

Parameters:

Name Type Description Default
o Union[sqlalchemy.ext.declarative.api.DeclarativeMeta, sqlalchemy.sql.schema.Table, Type[sqlalchemy.ext.declarative.api.DeclarativeMeta]]

Any applicable SQLAlchemy table representation, such as a Declarative- class, instance or a standard table object.

required

Returns:

Type Description
SQLAIntrospectorInterface

A matching introspector class for the provided object.

drizm_commons.sqla.conn.Database

A simplified connection interface for an SQLAlchemy engine.

create(self, base_override=None)

Creates all tables in the current Base

destroy(self, base_override=None)

Destroys all tables in the current Base

override_engine(self, uri, **kwargs)

Provides an option to manually override the auto-specced engine.

:param uri: Database URI :param kwargs: Normal kwargs as provided to the create_engine factory

Session(self)

Provides access to a scoped ORM Session