asyncpg_simpleorm package

Submodules

asyncpg_simpleorm.abstract module

class asyncpg_simpleorm.abstract.AsyncContextManagerABC(*args, **kwargs)[source]

Bases: object

Abstract representation of an async context manager.

Ensures a class has __aenter__() and __aexit__() methods.

class asyncpg_simpleorm.abstract.AsyncModelABC(*args, **kwargs)[source]

Bases: object

Abstract representation of an async database model.

Ensures that an object declares, column_names(), tablename(), connection(), from_record(), __init_subclass__() that allows a connection manager to be registered with subclasses.

abstractmethod classmethod column_names()[source]

Return the database column names.

Return type:Iterable[str]
abstractmethod classmethod connection()[source]

Return an async context manager, that returns an asyncpg.Connection instance when used in an async with block.

Return type:AsyncContextManagerABC
abstractmethod classmethod from_record()[source]

Return an instance of the class from an asyncpg.Record instance.

abstractmethod classmethod tablename()[source]

Return the database table name.

Return type:str

asyncpg_simpleorm.async_model module

class asyncpg_simpleorm.async_model.AsyncModel(**kwargs)[source]

Bases: asyncpg_simpleorm.async_model.BaseModel

Extends the BaseModel class to include helpful database queries. Implements the AsyncModelABC interface.

By default get() and get_one() methods return asyncpg.Record instances. This option can be toggled class wide, by setting a class attribute return_records to False on a subclass, or can be toggled during a single method call

See also

get() and get_one() methods for details.

This class uses the __init_subclass__() syntax new in python-3.6. That allows kwargs to be passed into the class declaration.

A user should subclass this providing a ConnectionManager or PoolManager to provide the database connection.

Raises:RuntimeError – If subclass does not provide a connection kwarg in the class declaration.

Example:

'''
The following example would be for a postgres table created by.

CREATE TABLE users (
  _id uuid PRIMARY KEY,
  name varchar(100) NOT NULL
)
'''

import uuid

DBURI = 'postgres://user:password@localhost:5432/database'

class User(AsyncModel, connection=ConnectionManager(DBURI)):
    __tablename__ = 'users'

    id = Column('_id', primary_key=True, default=uuid.uuid4)
    name = Column()

# Or using a ``PoolManager``.
class User(AsyncModel, connection=PoolManager(DBURI)):
    ...


# Create an instance using ``kwargs``
user = User(name='foo')

print(user)
# User(id=95ccbcd3-2ded-4ad8-9f68-d60f0b9590a9, name='foo')
classmethod connection()[source]

Obtain the connection manager that was registered with the subclass during creation.

This is typically used with async with to gain access to an asyncpg.Connection instance.

Example:

>>> async with User.connection() as conn:
        # do something with the connection.
Return type:Union[ConnectionManager, PoolManager]
await delete()[source]

Delete an instance from the database.

Raises:exceptions.ExecutionFailure – If no records were deleted from the database.
Return type:None
classmethod await execute(*args, **kwargs)[source]

Execute’s a database query inside a transaction block. This cuts down on the boiler plate nested async with statements to execute a query.

This is equivalent to:

>>> async with Model.connection() as conn:
...     async with conn.transaction():
...         return await conn.execute(*args, **kwargs)
classmethod from_record()[source]

Return an instance of the class from an asyncpg.Record object.

Parameters:record (Record) – An asyncpg.Record instance to create a database model instance from.
Return type:Any
classmethod await get(**kwargs)[source]

Get a list of the table items from the database.

Parameters:
  • records (Optional[bool]) – Optional bool. If True then we return asyncpg.Record’s. If False then we will return instances of the AsyncModel subclass. If None, then we default to what’s set on the subclass at the return_records attribute (default is True).
  • kwargs – Optional kwargs that are passed into a where clause.

Example:

>>> await User.get(records=False)
[User(id=95ccbcd3-2ded-4ad8-9f68-d60f0b9590a9, name='foo'), ...]

>>> await User.get()
[<Record(_id=UUID('95ccbcd3-2ded-4ad8-9f68-d60f0b9590a9'),
name='foo'>, ...]
Return type:Iterable[Any]
classmethod await get_one(**kwargs)[source]

Get a single item from the database.

Parameters:
  • record (Optional[bool]) – Optional bool. If True then we return asyncpg.Record’s. If False then we will return instances of the AsyncModel subclass. If None, then we default to what’s set on the subclass at the return_records attribute (default is True).
  • kwargs – Optional kwargs that are passed into a where clause.

Example:

>>> await User.get_one(name='foo')
<Record _id=UUID('95ccbcd3-2ded-4ad8-9f68-d60f0b9590a9'),
name='foo'>
>>> await User.get_one(record=False, name='foo')
User(id=456, name='bar')
Return type:Any
return_records = True
await save()[source]

Update or insert an instance to the database.

Raises:exceptions.ExecutionFailure – If no records were updated or saved to the database.

Example:

>>> user = User(name='foo')
>>> await user.save()
Return type:None
class asyncpg_simpleorm.async_model.BaseModel(**kwargs)[source]

Bases: object

Base class for AsyncModel. This class should typically not be used directly, unless building a custom statement generating class.

This class allows column instance values to be set either by the attribute name the column was declared as, or the database column name (which are not always the same).

Example:

>>> class User(BaseModel):
        id = Column('_id', primary_key=True)
        name = Column()

>>> u1 = User(id=123, name='foo')
>>> u2 = User(_id=456, name='bar')
>>> print(u1.id, u2.id)
(123, 456)
Parameters:kwargs – Key word args that are set on an instance. These would typically be the same keys as the declared Column’s on a subclass.
classmethod attr_name_for_column()[source]

Get the class attribute name for a given database column name.

This is used when setting instance values for Column’s, and allows access to the attribute name, whether the column_name was parsed using the actual database column name, or the attribute name (which can be different depending on the Column).

Parameters:column_name (str) – The database column name to get the attribute name for.
Raises:ValueError – If no Column is found for that column name.

Example:

>>> class User(BaseModel):
        id = Column('_id', primary_key=True)
        name = Column()

>>> User.attr_name_for_column('_id')
'id'
>>> User.attr_name_for_column('id')
'id'
Return type:str
classmethod column_names()[source]

Returns a tuple of the column names for the class.

Return type:Tuple[str]
classmethod ensured_column_name()[source]

This is helper to always return the database column name for the input.

This is essentially the opposite of attr_name_for_column().

Parameters:column_name – The attribute name to get the column name for.
Raises:ValueError – If no Column is found for that attribute name.

Example:

>>> class User(BaseModel):
        id = Column('_id', primary_key=True)
        name = Column()

>>> User.ensured_column_name('_id')
'_id'
>>> User.ensured_column_name('id')
'_id'
Return type:str
classmethod primary_keys()[source]

Returns a tuple of column names that are also primary keys.

Return type:Tuple[str]
classmethod tablename()[source]

Returns the tablename set for the class, if one is not set, then we default to the lowercase version of the class name + ‘s’.

class asyncpg_simpleorm.async_model.ModelMeta(*args, **kwargs)[source]

Bases: type

Meta class for BaseModel, which ensures the column’s keys for the model are set, or will default to the attribute name a Column was declared for.

This allows the key attribute of a Column to be optional.

Example:

>>> class User(BaseModel):
        id = Column('_id', primary_key=True)
        name = Column()

>>> User.id.key
'_id'
>>> User.name.key
'name'

asyncpg_simpleorm.connection_managers module

class asyncpg_simpleorm.connection_managers.ConnectionManager(*args, keep_alive=False, **kwargs)[source]

Bases: asyncpg_simpleorm.abstract.AsyncContextManagerABC

An async context manager that mimics the asyncpg.connect() function, used with subclasses of AsyncModel.

Parameters:
  • args – Passed to asyncpg.connect() function.
  • keep_alive (bool) – If True then the connection is kept alive for re-use. Else it is closed after use (default).
  • kwargs – Passed to asyncpg.connect() function.
class asyncpg_simpleorm.connection_managers.PoolManager(*args, **kwargs)[source]

Bases: asyncpg_simpleorm.abstract.AsyncContextManagerABC

An async context manager that mimics the asyncpg.create_pool() function, used with subclasses of AsyncModel.

Parameters:
  • args – Passed to asyncpg.create_pool() function.
  • kwargs – Passed to asyncpg.create_pool() function.

asyncpg_simpleorm.exceptions module

exception asyncpg_simpleorm.exceptions.BaseException(*args, **kwargs)[source]

Bases: Exception

The base exception class.

exception asyncpg_simpleorm.exceptions.ExecutionFailure(*args, **kwargs)[source]

Bases: asyncpg_simpleorm.exceptions.BaseException, ValueError

Raised if execution of a database statement fails.

exception asyncpg_simpleorm.exceptions.InvalidModel(*args, **kwargs)[source]

Bases: asyncpg_simpleorm.exceptions.BaseException, TypeError

Raised if a model does not pass an issubclass or isinstance check against ModelABC.

asyncpg_simpleorm.table_utils module

await asyncpg_simpleorm.table_utils.create_table(model)[source]

Create a database table.

Parameters:model – An AsyncModelABC subclass to drop the table for.
Return type:None
await asyncpg_simpleorm.table_utils.drop_table(model, cascade=False)[source]

Drop a database table.

Parameters:
  • model – An AsyncModelABC subclass to drop the table for.
  • cascade – If True then we add the CASCADE clause to the statement when executed.
Return type:

None

asyncpg_simpleorm.table_utils.ensure_model(fn)[source]

Decorator to ensure the first arg derives from AsyncModelABC.

await asyncpg_simpleorm.table_utils.truncate_table(model, cascade=False)[source]

Truncate a table, leaving the table schema intact.

Parameters:
  • model – An AsyncModelABC subclass to drop the table for.
  • cascade (bool) – If True then we add the CASCADE clause to the statement when executed.
Return type:

None

Module contents

class asyncpg_simpleorm.AsyncModelABC(*args, **kwargs)[source]

Bases: object

Abstract representation of an async database model.

Ensures that an object declares, column_names(), tablename(), connection(), from_record(), __init_subclass__() that allows a connection manager to be registered with subclasses.

abstractmethod classmethod column_names()[source]

Return the database column names.

Return type:Iterable[str]
abstractmethod classmethod connection()[source]

Return an async context manager, that returns an asyncpg.Connection instance when used in an async with block.

Return type:AsyncContextManagerABC
abstractmethod classmethod from_record()[source]

Return an instance of the class from an asyncpg.Record instance.

abstractmethod classmethod tablename()[source]

Return the database table name.

Return type:str
class asyncpg_simpleorm.AsyncContextManagerABC(*args, **kwargs)[source]

Bases: object

Abstract representation of an async context manager.

Ensures a class has __aenter__() and __aexit__() methods.

class asyncpg_simpleorm.StatementABC(*args, **kwargs)[source]

Bases: object

Abstract representation of a database query statement.

model

Return the AsyncModel set on an instance.

abstractmethod query()[source]

Return an iterable that can be used in an asyncpg query. The first value should be the query_string, followed by the flattened query args

An example return value:

('SELECT * FROM users WHERE name = $1 and email = $2', 'foo',
 'foo@example.com')
Return type:Iterable[Any]
abstractmethod query_args()[source]

Return the query arguments set on an instance.

Return type:Iterable[Any]
abstractmethod query_string(sep='n')[source]

Return the query string set on an instance.

Return type:str
abstractmethod set_statement(*args, **kwargs)[source]

Set the statement on the instance.

class asyncpg_simpleorm.ColumnTypeABC(*args, **kwargs)[source]

Bases: object

Abstract representation of a postgres column type.

pg_type_string

Return the postgres type string.

Return type:str
class asyncpg_simpleorm.AsyncModel(**kwargs)[source]

Bases: asyncpg_simpleorm.async_model.BaseModel

Extends the BaseModel class to include helpful database queries. Implements the AsyncModelABC interface.

By default get() and get_one() methods return asyncpg.Record instances. This option can be toggled class wide, by setting a class attribute return_records to False on a subclass, or can be toggled during a single method call

See also

get() and get_one() methods for details.

This class uses the __init_subclass__() syntax new in python-3.6. That allows kwargs to be passed into the class declaration.

A user should subclass this providing a ConnectionManager or PoolManager to provide the database connection.

Raises:RuntimeError – If subclass does not provide a connection kwarg in the class declaration.

Example:

'''
The following example would be for a postgres table created by.

CREATE TABLE users (
  _id uuid PRIMARY KEY,
  name varchar(100) NOT NULL
)
'''

import uuid

DBURI = 'postgres://user:password@localhost:5432/database'

class User(AsyncModel, connection=ConnectionManager(DBURI)):
    __tablename__ = 'users'

    id = Column('_id', primary_key=True, default=uuid.uuid4)
    name = Column()

# Or using a ``PoolManager``.
class User(AsyncModel, connection=PoolManager(DBURI)):
    ...


# Create an instance using ``kwargs``
user = User(name='foo')

print(user)
# User(id=95ccbcd3-2ded-4ad8-9f68-d60f0b9590a9, name='foo')
classmethod connection()[source]

Obtain the connection manager that was registered with the subclass during creation.

This is typically used with async with to gain access to an asyncpg.Connection instance.

Example:

>>> async with User.connection() as conn:
        # do something with the connection.
Return type:Union[ConnectionManager, PoolManager]
await delete()[source]

Delete an instance from the database.

Raises:exceptions.ExecutionFailure – If no records were deleted from the database.
Return type:None
classmethod await execute(*args, **kwargs)[source]

Execute’s a database query inside a transaction block. This cuts down on the boiler plate nested async with statements to execute a query.

This is equivalent to:

>>> async with Model.connection() as conn:
...     async with conn.transaction():
...         return await conn.execute(*args, **kwargs)
classmethod from_record()[source]

Return an instance of the class from an asyncpg.Record object.

Parameters:record (Record) – An asyncpg.Record instance to create a database model instance from.
Return type:Any
classmethod await get(**kwargs)[source]

Get a list of the table items from the database.

Parameters:
  • records (Optional[bool]) – Optional bool. If True then we return asyncpg.Record’s. If False then we will return instances of the AsyncModel subclass. If None, then we default to what’s set on the subclass at the return_records attribute (default is True).
  • kwargs – Optional kwargs that are passed into a where clause.

Example:

>>> await User.get(records=False)
[User(id=95ccbcd3-2ded-4ad8-9f68-d60f0b9590a9, name='foo'), ...]

>>> await User.get()
[<Record(_id=UUID('95ccbcd3-2ded-4ad8-9f68-d60f0b9590a9'),
name='foo'>, ...]
Return type:Iterable[Any]
classmethod await get_one(**kwargs)[source]

Get a single item from the database.

Parameters:
  • record (Optional[bool]) – Optional bool. If True then we return asyncpg.Record’s. If False then we will return instances of the AsyncModel subclass. If None, then we default to what’s set on the subclass at the return_records attribute (default is True).
  • kwargs – Optional kwargs that are passed into a where clause.

Example:

>>> await User.get_one(name='foo')
<Record _id=UUID('95ccbcd3-2ded-4ad8-9f68-d60f0b9590a9'),
name='foo'>
>>> await User.get_one(record=False, name='foo')
User(id=456, name='bar')
Return type:Any
return_records = True
await save()[source]

Update or insert an instance to the database.

Raises:exceptions.ExecutionFailure – If no records were updated or saved to the database.

Example:

>>> user = User(name='foo')
>>> await user.save()
Return type:None
class asyncpg_simpleorm.BaseModel(**kwargs)[source]

Bases: object

Base class for AsyncModel. This class should typically not be used directly, unless building a custom statement generating class.

This class allows column instance values to be set either by the attribute name the column was declared as, or the database column name (which are not always the same).

Example:

>>> class User(BaseModel):
        id = Column('_id', primary_key=True)
        name = Column()

>>> u1 = User(id=123, name='foo')
>>> u2 = User(_id=456, name='bar')
>>> print(u1.id, u2.id)
(123, 456)
Parameters:kwargs – Key word args that are set on an instance. These would typically be the same keys as the declared Column’s on a subclass.
classmethod attr_name_for_column()[source]

Get the class attribute name for a given database column name.

This is used when setting instance values for Column’s, and allows access to the attribute name, whether the column_name was parsed using the actual database column name, or the attribute name (which can be different depending on the Column).

Parameters:column_name (str) – The database column name to get the attribute name for.
Raises:ValueError – If no Column is found for that column name.

Example:

>>> class User(BaseModel):
        id = Column('_id', primary_key=True)
        name = Column()

>>> User.attr_name_for_column('_id')
'id'
>>> User.attr_name_for_column('id')
'id'
Return type:str
classmethod column_names()[source]

Returns a tuple of the column names for the class.

Return type:Tuple[str]
classmethod ensured_column_name()[source]

This is helper to always return the database column name for the input.

This is essentially the opposite of attr_name_for_column().

Parameters:column_name – The attribute name to get the column name for.
Raises:ValueError – If no Column is found for that attribute name.

Example:

>>> class User(BaseModel):
        id = Column('_id', primary_key=True)
        name = Column()

>>> User.ensured_column_name('_id')
'_id'
>>> User.ensured_column_name('id')
'_id'
Return type:str
classmethod primary_keys()[source]

Returns a tuple of column names that are also primary keys.

Return type:Tuple[str]
classmethod tablename()[source]

Returns the tablename set for the class, if one is not set, then we default to the lowercase version of the class name + ‘s’.

class asyncpg_simpleorm.Column(key=None, _type=None, *, default=None, primary_key=False)[source]

Bases: object

A descriptor class that represents a table column.

Parameters:
  • key (Optional[str]) – The table column name in the database. If not set, then this will be set to the attribute name used on the AsyncModel subclass the column was declared on.
  • type – The ColumnType subclass to use for the column.
  • default (Optional[Any]) – A value or callable that is used for a default value. If this is callable, then it should recieve no input and return a value when called.
  • primary_key (bool) – Set’s if the column is a primary key column. Primary key columns are used in certain query statements, such as AsyncModel.save()
default
key
pg_column_string
Return type:str
primary_key
class asyncpg_simpleorm.ColumnType(string=None)[source]

Bases: object

Implementation of ColumnTypeABC.

This can be used as a generic column type, by passing a string into the constructor. That string will be used, else we will use a value that’s passed into the class declaration at pg_type_string.

Parameters:string (Optional[str]) – An optional input string that will be used for the column type. This string is not checked or validated, so if it’s not valid errors will bubble up when trying to create the table.

Examples:

>>> str(ColumnType('text'))
'text'
>>> class Text(ColumnType, pg_type_string='text'): pass
>>> str(Text())
'text'

Custom subclasses should implement __slots__. If they don’t need to set any attributes on the class (which is typically the case) and they derive from ColumnType then the __slots__ will be automatically added to the subclass.

pg_type_string

Return’s the postgres column type string for an instance.

Raises:TypeError – If neither an input string was passed in or pg_type_string in the class declaration.
Return type:str
class asyncpg_simpleorm.String(n=None)[source]

Bases: asyncpg_simpleorm.column.base_column_type.ColumnType

Representation of postgres string column. Dependening on the context this will either produce a text column or varchar(n) column.

Parameters:n (Optional[int]) – An optional integer for the length of the string. If this is present then we use varchar(n), else we use text.
class asyncpg_simpleorm.UUID(string=None)[source]

Bases: asyncpg_simpleorm.column.base_column_type.ColumnType

Representation of postgres uuid type.

class asyncpg_simpleorm.Boolean(string=None)[source]

Bases: asyncpg_simpleorm.column.base_column_type.ColumnType

Representation of postgres bool type.

class asyncpg_simpleorm.Integer(string=None)[source]

Bases: asyncpg_simpleorm.column.base_column_type.ColumnType

Representation of postgres integer type.

class asyncpg_simpleorm.Number(string=None)[source]

Bases: asyncpg_simpleorm.column.base_column_type.ColumnType

Representation of postgres numeric type.

class asyncpg_simpleorm.Date(string=None)[source]

Bases: asyncpg_simpleorm.column.base_column_type.ColumnType

Representation of postgres date type.

class asyncpg_simpleorm.Time(with_timezone=False)[source]

Bases: asyncpg_simpleorm.column.base_column_type.ColumnType

Representation of postgres time or timetz type.

Parameters:with_timezone (bool) – If True then it is time with timezone. If False (default) then it time without timezone.
class asyncpg_simpleorm.Timestamp(with_timezone=False)[source]

Bases: asyncpg_simpleorm.column.base_column_type.ColumnType

Representation of postgres timestamp or timestamptz type.

Parameters:with_timezone (bool) – If True then it is timestamp with timezone type. If False (default) then it timestamp without timezone type.
class asyncpg_simpleorm.TimeInterval(string=None)[source]

Bases: asyncpg_simpleorm.column.base_column_type.ColumnType

Representation of postgres interval type.

class asyncpg_simpleorm.Array(_type, n=None, dimensions=None)[source]

Bases: asyncpg_simpleorm.column.base_column_type.ColumnType

Representation of postgres ARRAY type.

Parameters:
  • _type – The type of the elements in the array. This would be another ColumnType subclass.
  • n – An optional int, that will make a sized array.
  • dimensions – An optional int that will create a dimensional array.

Example:

>>> Array(Integer()).pg_type_string
integer ARRAY
>>> Array(Integer(), 3).pg_type_string
integer ARRAY[3]
>>> Array(Integer(), 3, 3).pg_type_string
integer [3][3][3]
class asyncpg_simpleorm.BigInteger(string=None)[source]

Bases: asyncpg_simpleorm.column.base_column_type.ColumnType

Representation of postgres int8 type.

class asyncpg_simpleorm.Bit(n, fixed_length=False)[source]

Bases: asyncpg_simpleorm.column.base_column_type.ColumnType

Representation of postgres bit or varbit type.

Parameters:
  • n – The number of bits.
  • fixed_length – An optional boolean. If True we will use bit(n). If False (default), we will use varbit(n).
class asyncpg_simpleorm.BigSerial(string=None)[source]

Bases: asyncpg_simpleorm.column.base_column_type.ColumnType

Representation of postgres serial8 type.

class asyncpg_simpleorm.Binary(string=None)[source]

Bases: asyncpg_simpleorm.column.base_column_type.ColumnType

Representation of postgres bytea type.

class asyncpg_simpleorm.FixedLengthString(n)[source]

Bases: asyncpg_simpleorm.column.base_column_type.ColumnType

Representation of postgres char type.

Parameters:n (int) – The number of characters.
class asyncpg_simpleorm.Money(string=None)[source]

Bases: asyncpg_simpleorm.column.base_column_type.ColumnType

Representation of postgres money type.

class asyncpg_simpleorm.IPAddress(inet=False)[source]

Bases: asyncpg_simpleorm.column.base_column_type.ColumnType

Representation of postgres cidr or inet types.

Parameters:inet – An optional bool. If True then we will use inet. If False (default) then we use cidr.
class asyncpg_simpleorm.MACAddress(string=None)[source]

Bases: asyncpg_simpleorm.column.base_column_type.ColumnType

Representation of postgres macaddr type.

class asyncpg_simpleorm.Box(string=None)[source]

Bases: asyncpg_simpleorm.column.base_column_type.ColumnType

Representation of postgres box type.

class asyncpg_simpleorm.Line(string=None)[source]

Bases: asyncpg_simpleorm.column.base_column_type.ColumnType

Representation of postgres line type.

class asyncpg_simpleorm.LineSegment(string=None)[source]

Bases: asyncpg_simpleorm.column.base_column_type.ColumnType

Representation of postgres lseg type.

class asyncpg_simpleorm.Circle(string=None)[source]

Bases: asyncpg_simpleorm.column.base_column_type.ColumnType

Representation of postgres circle type.

class asyncpg_simpleorm.Path(string=None)[source]

Bases: asyncpg_simpleorm.column.base_column_type.ColumnType

Representation of postgres path type.

class asyncpg_simpleorm.Point(string=None)[source]

Bases: asyncpg_simpleorm.column.base_column_type.ColumnType

Representation of postgres point type.

class asyncpg_simpleorm.Polygon(string=None)[source]

Bases: asyncpg_simpleorm.column.base_column_type.ColumnType

Representation of postgres polygon type.

class asyncpg_simpleorm.Double(string=None)[source]

Bases: asyncpg_simpleorm.column.base_column_type.ColumnType

Representation of postgres float8 type.

class asyncpg_simpleorm.Json(string=None)[source]

Bases: asyncpg_simpleorm.column.base_column_type.ColumnType

Representation of postgres json type.

class asyncpg_simpleorm.JsonB(string=None)[source]

Bases: asyncpg_simpleorm.column.base_column_type.ColumnType

Representation of postgres jsonb type.

This is not supported by all postgres versions.

class asyncpg_simpleorm.PGLogSequenceNumber(string=None)[source]

Bases: asyncpg_simpleorm.column.base_column_type.ColumnType

Representation of postgres pg_lsn type.

This is not supported by all postgres versions.

class asyncpg_simpleorm.Real(string=None)[source]

Bases: asyncpg_simpleorm.column.base_column_type.ColumnType

Representation of postgres float4 type.

class asyncpg_simpleorm.SmallInteger(string=None)[source]

Bases: asyncpg_simpleorm.column.base_column_type.ColumnType

Representation of postgres int2 type.

class asyncpg_simpleorm.SmallSerial(string=None)[source]

Bases: asyncpg_simpleorm.column.base_column_type.ColumnType

Representation of postgres serial2 type.

class asyncpg_simpleorm.Serial(string=None)[source]

Bases: asyncpg_simpleorm.column.base_column_type.ColumnType

Representation of postgres serial4 type.

class asyncpg_simpleorm.TextSearchQuery(string=None)[source]

Bases: asyncpg_simpleorm.column.base_column_type.ColumnType

Representation of postgres tsquery type.

class asyncpg_simpleorm.TextSearchVector(string=None)[source]

Bases: asyncpg_simpleorm.column.base_column_type.ColumnType

Representation of postgres tsvector type.

class asyncpg_simpleorm.TransactionID(string=None)[source]

Bases: asyncpg_simpleorm.column.base_column_type.ColumnType

Representation of postgres txid_snapshot type.

class asyncpg_simpleorm.XML(string=None)[source]

Bases: asyncpg_simpleorm.column.base_column_type.ColumnType

Representation of postgres xml type.

class asyncpg_simpleorm.IntegerRange(big=False)[source]

Bases: asyncpg_simpleorm.column.base_column_type.ColumnType

Representation of postgres int4range or int8range types.

Parameters:big – A boolean if True then will represent an int8range. If False (default) then we will use int4range.
class asyncpg_simpleorm.NumericRange(string=None)[source]

Bases: asyncpg_simpleorm.column.base_column_type.ColumnType

Representation of postgres numrange type.

class asyncpg_simpleorm.DateRange(string=None)[source]

Bases: asyncpg_simpleorm.column.base_column_type.ColumnType

Representation of postgres daterange type.

class asyncpg_simpleorm.ConnectionManager(*args, keep_alive=False, **kwargs)[source]

Bases: asyncpg_simpleorm.abstract.AsyncContextManagerABC

An async context manager that mimics the asyncpg.connect() function, used with subclasses of AsyncModel.

Parameters:
  • args – Passed to asyncpg.connect() function.
  • keep_alive (bool) – If True then the connection is kept alive for re-use. Else it is closed after use (default).
  • kwargs – Passed to asyncpg.connect() function.
class asyncpg_simpleorm.PoolManager(*args, **kwargs)[source]

Bases: asyncpg_simpleorm.abstract.AsyncContextManagerABC

An async context manager that mimics the asyncpg.create_pool() function, used with subclasses of AsyncModel.

Parameters:
  • args – Passed to asyncpg.create_pool() function.
  • kwargs – Passed to asyncpg.create_pool() function.
class asyncpg_simpleorm.BaseStatement(model, kwargs={}, arg_count=1)[source]

Bases: asyncpg_simpleorm.statements.abstract.StatementABC

Implementation of the StatementABC.

count
kwargs
model

Return the database model set on an instance. And ensures that the model is derived from AsyncModelABC.

Raises:asyncpg_simpleorm.InvalidModel – If trying to set an invalid model on an instance.
query()[source]

Returns the representation of the query set on the instance.

query_args()[source]

Get the query args set on the instance. This will return an empty tuple if no args have been set on the instance yet.

If args are set on the instance, then they will be returned in the order corresponding to their place holder in the query_string.

Return type:Iterable[Any]
query_string(sep='n')[source]

Get the query string set on the instance.

Parameters:sep – A seperator used to join the statement and the clauses. Defaults to ‘n’.
Raises:TypeError – If a statement has not yet been set on an instance.
Return type:str
set_count(count)[source]

Reset’s the counter for an instance.

Parameters:count (int) – The number to reset the counter to.
Return type:None
set_statement(key, query_string, args=None)[source]

Set the statement for an instance, and return self for method chaining.

Return type:BaseStatement
class asyncpg_simpleorm.Statement(model, kwargs={}, arg_count=1)[source]

Bases: asyncpg_simpleorm.statements.base_statement.BaseStatement

Extends the BaseStatement class. This class is normally not instantiated directly, but returned from one of the statement factory functions.

count
delete()[source]

Set’s the statement as a DELETE statement. This will automatically set a where statement, using the primary keys.

from_()[source]

Add’s the FROM clause string to the statement.

insert(**kwargs)[source]

Set’s the statement as an INSERT statement.

Parameters:kwargs – Values to use as (column names, query args) for the statement. These are probably not used much as you should normally just set the model to an instance of ModelABC for the column names and values.
kwargs
select()[source]

Set’s the statement as a SELECT statement.

update(**kwargs)[source]

Set’s the statement as an UPDATE statement. This will automatically set a where statement, using the primary keys.

Parameters:kwargs – Values to use as column names, query args for the statement. These are probably not used much as you should normally just set the model to an instance of ModelABC for the column names and values.
Raises:TypeError – If no args were able to be parsed for the statement.
where(primary_keys=False, safe_call=False, **kwargs)[source]

Add’s the where string to the statement.

Parameters:
  • primary_keys – If True, only parse primary keys for the where string and args. This is primarily an implementation detail used in conjunction with other statement callbacks, and typically not necessarily set by a caller.
  • safe_call – An optional boolean to suppress errors. Default is False.
  • kwargs – An optional mapping of column names and values to use for the where statement.
Raises:
  • ValueError – If not using the primary keys and the kwargs set on the instance include an invalid key.
  • TypeError – If nothing was able to be parsed.
asyncpg_simpleorm.delete(model, **kwargs)[source]

Delete statement factory.

Parameters:
  • model – A ModelABC subclass instance to create the statement for.
  • kwargs – Used for instance values, if the statement is created with a class, not an instance.
asyncpg_simpleorm.insert(model=None, **kwargs)[source]

Insert statement factory.

Parameters:
  • model – A ModelABC subclass instance to create the statement for.
  • kwargs – Used for instance values, if the statement is created with a class, not an instance.
asyncpg_simpleorm.select(model)[source]

Select statement factory.

Parameters:model – A ModelABC subclass to create the statement for.
asyncpg_simpleorm.update(model=None, **kwargs)[source]

Update statement factory.

Parameters:
  • model – A ModelABC subclass instance to create the statement for.
  • kwargs – Used for instance values, if the statement is created with a class, not an instance.
await asyncpg_simpleorm.create_table(model)[source]

Create a database table.

Parameters:model – An AsyncModelABC subclass to drop the table for.
Return type:None
await asyncpg_simpleorm.drop_table(model, cascade=False)[source]

Drop a database table.

Parameters:
  • model – An AsyncModelABC subclass to drop the table for.
  • cascade – If True then we add the CASCADE clause to the statement when executed.
Return type:

None

await asyncpg_simpleorm.truncate_table(model, cascade=False)[source]

Truncate a table, leaving the table schema intact.

Parameters:
  • model – An AsyncModelABC subclass to drop the table for.
  • cascade (bool) – If True then we add the CASCADE clause to the statement when executed.
Return type:

None

exception asyncpg_simpleorm.BaseException(*args, **kwargs)[source]

Bases: Exception

The base exception class.

exception asyncpg_simpleorm.ExecutionFailure(*args, **kwargs)[source]

Bases: asyncpg_simpleorm.exceptions.BaseException, ValueError

Raised if execution of a database statement fails.

exception asyncpg_simpleorm.InvalidModel(*args, **kwargs)[source]

Bases: asyncpg_simpleorm.exceptions.BaseException, TypeError

Raised if a model does not pass an issubclass or isinstance check against ModelABC.