asyncpg_simpleorm package

Submodules

asyncpg_simpleorm.abstract module

class asyncpg_simpleorm.abstract.AsyncContextManagerABC[source]

Bases: object

Abstract representation of an async context manager.

Ensures a class has __aenter__ and __aexit__ methods.

class asyncpg_simpleorm.abstract.AsyncModelABC[source]

Bases: object

Abstract representation of an async database model.

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

Return an async context manager, that returns an asyncpg.Connection instance.

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

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

Return type:AsyncModelABC
abstractmethod classmethod tablename()[source]
Return type:str
class asyncpg_simpleorm.abstract.ModelABC[source]

Bases: object

Abstract reperesentation of a database model.

abstractmethod classmethod column_names()[source]
Return type:Iterable[str]
abstractmethod classmethod tablename()[source]
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.

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 get 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 from_record()[source]

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

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
class asyncpg_simpleorm.async_model.BaseModel(**kwargs)[source]

Bases: object

Implementation of ModelABC. 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 :class`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).

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

Example:

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

>>> User.ensured_column_name('_id')
'_id'
>>> User.ensured_column_name('id')
'_id'
Parameters:column_name – The attribute name to get the column name for.
Raises:ValueError – If no Column is found for that attribute name.
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.

class asyncpg_simpleorm.async_model.Column(key: str = 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.
  • default – 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 – 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
primary_key
class asyncpg_simpleorm.async_model.ModelMeta[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, **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.
  • 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[source]

Bases: Exception

The base exception class.

exception asyncpg_simpleorm.exceptions.ExecutionFailure[source]

Bases: asyncpg_simpleorm.exceptions.BaseException, ValueError

Raised if execution of a database statement fails.

exception asyncpg_simpleorm.exceptions.InvalidModel[source]

Bases: asyncpg_simpleorm.exceptions.BaseException, TypeError

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

Module contents

class asyncpg_simpleorm.AsyncModelABC[source]

Bases: object

Abstract representation of an async database model.

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

Return an async context manager, that returns an asyncpg.Connection instance.

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

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

Return type:AsyncModelABC
abstractmethod classmethod tablename()[source]
Return type:str
class asyncpg_simpleorm.AsyncContextManagerABC[source]

Bases: object

Abstract representation of an async context manager.

Ensures a class has __aenter__ and __aexit__ methods.

class asyncpg_simpleorm.ModelABC[source]

Bases: object

Abstract reperesentation of a database model.

abstractmethod classmethod column_names()[source]
Return type:Iterable[str]
abstractmethod classmethod tablename()[source]
Return type:str
class asyncpg_simpleorm.StatementABC[source]

Bases: object

Abstract representation of a database query statement.

model

Return the model 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.

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

Bases: asyncpg_simpleorm.async_model.BaseModel

Extends the BaseModel class to include helpful database queries.

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 get 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 from_record()[source]

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

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
class asyncpg_simpleorm.BaseModel(**kwargs)[source]

Bases: object

Implementation of ModelABC. 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 :class`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).

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

Example:

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

>>> User.ensured_column_name('_id')
'_id'
>>> User.ensured_column_name('id')
'_id'
Parameters:column_name – The attribute name to get the column name for.
Raises:ValueError – If no Column is found for that attribute name.
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.

class asyncpg_simpleorm.Column(key: str = 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.
  • default – 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 – 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
primary_key
class asyncpg_simpleorm.ConnectionManager(*args, **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.
  • 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: int = 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 ModelABC.

Raises:.exceptions.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: int = 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.
exception asyncpg_simpleorm.BaseException[source]

Bases: Exception

The base exception class.

exception asyncpg_simpleorm.ExecutionFailure[source]

Bases: asyncpg_simpleorm.exceptions.BaseException, ValueError

Raised if execution of a database statement fails.

exception asyncpg_simpleorm.InvalidModel[source]

Bases: asyncpg_simpleorm.exceptions.BaseException, TypeError

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