API Referenece

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

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

Connection Manager’s

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

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]

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.

Column

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

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()

Column Types

The following ColumnType classes are used when creating table’s using the create_table() function.

These are used in conjunction with the Column class. They do not do any type checking or validation. They only generate column type strings during table creation.

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

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

Array Types

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

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]

Character / String Types

class asyncpg_simpleorm.String(n=None)[source]

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.FixedLengthString(n)[source]

Representation of postgres char type.

Parameters:n (int) – The number of characters.

Boolean Type

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

Representation of postgres bool type.

Numeric Types

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

Representation of postgres integer type.

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

Representation of postgres int8 type.

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

Representation of postgres int2 type.

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

Representation of postgres numeric type.

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

Representation of postgres float8 type.

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

Representation of postgres float4 type.

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

Representation of postgres money type.

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

Representation of postgres serial4 type.

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

Representation of postgres serial8 type.

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

Representation of postgres serial2 type.

Date and Time Types

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

Representation of postgres date type.

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

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]

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]

Representation of postgres interval type.

Geometric Types

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

Representation of postgres box type.

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

Representation of postgres circle type.

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

Representation of postgres line type.

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

Representation of postgres lseg type.

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

Representation of postgres path type.

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

Representation of postgres point type.

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

Representation of postgres polygon type.

JSON Types

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

Representation of postgres json type.

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

Representation of postgres jsonb type.

This is not supported by all postgres versions.

Binary Data Types

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

Representation of postgres bytea type.

Network Address Types

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

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]

Representation of postgres macaddr type.

Bit String Types

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

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

Text Search Types

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

Representation of postgres tsquery type.

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

Representation of postgres tsvector type.

UUID Type

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

Representation of postgres uuid type.

XML Type

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

Representation of postgres xml type.

Range Types

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

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]

Representation of postgres numrange type.

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

Representation of postgres daterange type.

Miscellaneous Types

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

Representation of postgres pg_lsn type.

This is not supported by all postgres versions.

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

Representation of postgres txid_snapshot type.

Table Utilities

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

Examples

Using the User model from the Usage section.

>>> import asyncpg_simpleorm as orm
>>> await orm.create_table(User)
>>> user = User(name='foo', email='foo@example.com')
>>> await user.save()
>>> await orm.truncate_table()  # keep the table schema, but delete all rows
>>> print(await User.get())
[]
>>> await orm.drop_table(User)
>>> print(await User.get())
Traceback (most recent call last):
...
asyncpg.exceptions.UndefinedTableError: relation "users" does not exist

Statements

Statements are a lower level concept, and most likely not needed by most consumers of this package, unless trying to implement some custom database query statement generators.

The main concept behind a statment is that given an AsyncModel, they should generate a query string (and possibly query args) to be used for database operations.

The statement classes when iterated over should return at minimum a string and possibly args. This allows a statement to be executed with connection.execute(*statement) syntax.

Example

Using the User class from the Usage section. And the update statement factory.

>>> user = User(id=123, name='foo', email='foo@example.com')
>>> stmt = update(user)
>>> q = stmt.query()  # Return's a tuple of ``(string, arg1, ...argn)``
>>> print(q[0])
UPDATE users SET (_id, name, email) = ($1, $2, $3)
WHERE users._id = $4
>>> print(q[1:])  # the ``args``.
(123, 'foo', 'foo@example.com', 123)

Execute the statement with an asyncpg.Connection

>>> response = await connection.execute(*stmt)
UPDATE 0 1
asyncpg_simpleorm.select(model)[source]

Select statement factory.

Parameters:model – A ModelABC subclass to create the statement for.
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.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.
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.
class asyncpg_simpleorm.Statement(model, kwargs={}, arg_count=1)[source]

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

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

Abstract and Base Classes

class asyncpg_simpleorm.BaseModel(**kwargs)[source]

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.BaseStatement(model, kwargs={}, arg_count=1)[source]

Implementation of the StatementABC.

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.AsyncModelABC(*args, **kwargs)[source]

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]

Abstract representation of an async context manager.

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

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

Abstract representation of a postgres column type.

pg_type_string

Return the postgres type string.

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

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.

Exceptions

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

The base exception class.

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

Raised if execution of a database statement fails.

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

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