API

Classes, methods and stuff.

Connections

class momoko.Pool(dsn, connection_factory=None, cursor_factory=None, size=1, max_size=None, ioloop=None, raise_connect_errors=True, reconnect_interval=500, setsession=(), auto_shrink=False, shrink_delay=datetime.timedelta(0, 120), shrink_period=datetime.timedelta(0, 120))

Asynchronous connection pool object. All its methods are asynchronous unless stated otherwide in method description.

Parameters:
  • dsn (string) –

    A Data Source Name string containing one of the following values:

    • dbname - the database name
    • user - user name used to authenticate
    • password - password used to authenticate
    • host - database host address (defaults to UNIX socket if not provided)
    • port - connection port number (defaults to 5432 if not provided)

    Or any other parameter supported by PostgreSQL. See the PostgreSQL documentation for a complete list of supported parameters.

  • connection_factory – The connection_factory argument can be used to create non-standard connections. The class returned should be a subclass of psycopg2.extensions.connection. See Connection and cursor factories for details. Defaults to None.
  • cursor_factory – The cursor_factory argument can be used to return non-standart cursor class The class returned should be a subclass of psycopg2.extensions.cursor. See Connection and cursor factories for details. Defaults to None.
  • size (int) – Minimal number of connections to maintain. size connections will be opened and maintained after calling momoko.Pool.connect().
  • max_size (int or None) – if not None, the pool size will dynamically grow on demand up to max_size open connections. By default the connections will still be maintained even if when the pool load decreases. See also auto_shrink parameter.
  • ioloop – Tornado IOloop instance to use. Defaults to Tornado’s IOLoop.instance().
  • raise_connect_errors (bool) – Whether to raise momoko.PartiallyConnectedError() when failing to connect to database during momoko.Pool.connect().
  • reconnect_interval (int) – If database server becomes unavailable, the pool will try to reestablish the connection. The attempt frequency is reconnect_interval milliseconds.
  • setsession (list) – List of intial sql commands to be executed once connection is established. If any of the commands fails, the connection will be closed. NOTE: The commands will be executed as one transaction block.
  • auto_shrink (bool) – Garbage-collect idle connections. Only applicable if max_size was specified. Nevertheless, the pool will mainatain at least size connections.
  • shrink_delay (datetime.timedelta()) – A connection is declared idle if it was not used for shrink_delay time period. Idle connections will be garbage-collected if auto_shrink is set to True.
  • shrink_period (datetime.timedelta()) – If auto_shink is enabled, this parameter defines how the pool will check for idle connections.
exception DatabaseNotAvailable

Raised when Pool can not connect to database server

callproc(*args, **kwargs)

Call a stored database procedure with the given name.

See momoko.Connection.callproc() for documentation about the parameters.

close()

Close the connection pool.

NOTE: This is a synchronous method.

connect()

Returns future that resolves to this Pool object.

If some connection failed to connect and self.raise_connect_errors is true, raises momoko.PartiallyConnectedError().

execute(*args, **kwargs)

Prepare and execute a database operation (query or command).

See momoko.Connection.execute() for documentation about the parameters.

getconn(ping=True)

Acquire connection from the pool.

You can then use this connection for subsequent queries. Just use connection.execute instead of Pool.execute.

Make sure to return connection to the pool by calling momoko.Pool.putconn(), otherwise the connection will remain forever busy and you’ll starve your pool.

Returns a future that resolves to the acquired connection object.

Parameters:ping (boolean) – Whether to ping the connection before returning it by executing momoko.Connection.ping().
manage(**kwds)

Context manager that automatically returns connection to the pool. You can use it instead of momoko.Pool.putconn():

connection = yield self.db.getconn()
with self.db.manage(connection):
    cursor = yield connection.execute("BEGIN")
    ...
mogrify(*args, **kwargs)

Return a query string after arguments binding.

NOTE: This is NOT a synchronous method (contary to momoko.Connection.mogrify) - it asynchronously waits for available connection. For performance reasons, its better to create dedicated momoko.Connection() object and use it directly for mogrification, this operation does not imply any real operation on the database server.

See momoko.Connection.mogrify() for documentation about the parameters.

ping()

Make sure this connection is alive by executing SELECT 1 statement - i.e. roundtrip to the database.

See momoko.Connection.ping() for documentation about the parameters.

putconn(connection)

Return busy connection back to the pool.

NOTE: This is a synchronous method.

Parameters:connection (Connection) – Connection object previously returned by momoko.Pool.getconn().
register_hstore(*args, **kwargs)

Register adapter and typecaster for dict-hstore conversions.

See momoko.Connection.register_hstore() for documentation about the parameters. This method has no globally parameter, because it already registers hstore to all the connections in the pool.

register_json(*args, **kwargs)

Create and register typecasters converting json type to Python objects.

See momoko.Connection.register_json() for documentation about the parameters. This method has no globally parameter, because it already registers json to all the connections in the pool.

transaction(*args, **kwargs)

Run a sequence of SQL queries in a database transaction.

See momoko.Connection.transaction() for documentation about the parameters.

class momoko.Connection(dsn, connection_factory=None, cursor_factory=None, ioloop=None, setsession=())

Asynchronous connection object. All its methods are asynchronous unless stated otherwide in method description.

Parameters:
  • dsn (string) –

    A Data Source Name string containing one of the following values:

    • dbname - the database name
    • user - user name used to authenticate
    • password - password used to authenticate
    • host - database host address (defaults to UNIX socket if not provided)
    • port - connection port number (defaults to 5432 if not provided)

    Or any other parameter supported by PostgreSQL. See the PostgreSQL documentation for a complete list of supported parameters.

  • connection_factory – The connection_factory argument can be used to create non-standard connections. The class returned should be a subclass of psycopg2.extensions.connection. See Connection and cursor factories for details. Defaults to None.
  • cursor_factory – The cursor_factory argument can be used to return non-standart cursor class The class returned should be a subclass of psycopg2.extensions.cursor. See Connection and cursor factories for details. Defaults to None.
  • setsession (list) – List of intial sql commands to be executed once connection is established. If any of the commands fails, the connection will be closed. NOTE: The commands will be executed as one transaction block.
callproc(procname, parameters=(), cursor_factory=None)

Call a stored database procedure with the given name.

The sequence of parameters must contain one entry for each argument that the procedure expects. The result of the call is returned as modified copy of the input sequence. Input parameters are left untouched, output and input/output parameters replaced with possibly new values.

The procedure may also provide a result set as output. This must then be made available through the standard fetch*() methods.

Parameters:

Returns future that resolves to cursor object containing result.

close()

Closes the connection.

NOTE: This is a synchronous method.

closed

Indicates whether the connection is closed or not.

connect()

Initiate asynchronous connect. Returns future that resolves to this connection object.

execute(operation, parameters=(), cursor_factory=None)

Prepare and execute a database operation (query or command).

Parameters:

Returns future that resolves to cursor object containing result.

mogrify(operation, parameters=())

Return a query string after arguments binding.

The string returned is exactly the one that would be sent to the database running the execute() method or similar.

NOTE: This is a synchronous method.

Parameters:
  • operation (string) – An SQL query.
  • parameters (tuple/list) – A list or tuple with query parameters. See Passing parameters to SQL queries for more information. Defaults to an empty tuple.
ping()

Make sure this connection is alive by executing SELECT 1 statement - i.e. roundtrip to the database.

Returns future. If it resolves sucessfully - the connection is alive (or dead otherwise).

register_hstore(globally=False, unicode=False)

Register adapter and typecaster for dict-hstore conversions.

More information on the hstore datatype can be found on the Psycopg2 documentation.

Parameters:
  • globally (boolean) – Register the adapter globally, not only on this connection.
  • unicode (boolean) – If True, keys and values returned from the database will be unicode instead of str. The option is not available on Python 3.

Returns future that resolves to None.

register_json(globally=False, loads=None)

Create and register typecasters converting json type to Python objects.

More information on the json datatype can be found on the Psycopg2 documentation.

Parameters:
  • globally (boolean) – Register the adapter globally, not only on this connection.
  • loads (function) – The function used to parse the data into a Python object. If None use json.loads(), where json is the module chosen according to the Python version. See psycopg2.extra docs.

Returns future that resolves to None.

transaction(statements, cursor_factory=None, auto_rollback=True)

Run a sequence of SQL queries in a database transaction.

Parameters:
  • statements (tuple/list) –

    List or tuple containing SQL queries with or without parameters. An item can be a string (SQL query without parameters) or a tuple/list with two items, an SQL query and a tuple/list/dict with parameters.

    See Passing parameters to SQL queries for more information.

  • cursor_factory – The cursor_factory argument can be used to create non-standard cursors. The class returned must be a subclass of psycopg2.extensions.cursor. See Connection and cursor factories for details. Defaults to None.
  • auto_rollback (bool) – If one of the transaction statements fails, try to automatically execute ROLLBACK to abort the transaction. If ROLLBACK fails, it would not be raised, but only logged.

Returns future that resolves to list of cursors. Each cursor contains the result of the corresponding transaction statement.

momoko.connect(*args, **kwargs)

Connection factory. See momoko.Connection() for documentation about the parameters.

Returns future that resolves to momoko.Connection() object or raises exception.

Exceptions

class momoko.PoolError

Raised when something goes wrong in the connection pool.

class momoko.PartiallyConnectedError

Raised when momoko.Pool() can not initialize all of the requested connections.