API

Classes, methods and stuff.

Connections

class momoko.Pool(dsn, connection_factory=None, cursor_factory=None, size=1, max_size=None, callback=None, ioloop=None, raise_connect_errors=True, reconnect_interval=500, setsession=[])

Asynchronous connection pool.

The pool manages database connections and passes operations to connections.

See momoko.Connection for documentation about the dsn, connection_factory and cursor_factory parameters. These are used by the connection pool when a new connection is created.

Parameters:
  • size (integer) – Amount of connections created upon initialization. Defaults to 1.
  • max_size (integer) – Allow number of connection to grow under load up to given size. Defaults to size.
  • callback (callable) – A callable that’s called after all the connections are created. Defaults to None.
  • ioloop – An instance of Tornado’s IOLoop. Defaults to None, IOLoop.instance() will be used.
  • raise_connect_errors (bool) – Whether to raise exception if database connection fails. Set to False to enable automatic reconnection attempts. Defaults to True.
  • reconnect_interval (integer) – When using automatic reconnects, set minimum reconnect interval, in milliseconds, before retrying connection attempt. Don’t set this value too low to prevent “banging” the database server with connection attempts. Defaults to 500.
  • setsession (list) – List of intial sql commands to be executed once connection is established. If any of the commands failes, the connection will be closed. NOTE: The commands will be executed as one transaction block.
callproc(procname, parameters=(), cursor_factory=None, callback=None)

Call a stored database procedure with the given name.

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

close()

Close the connection pool.

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

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

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

getconn(ping=True, callback=None)

Acquire connection from the pool.

You can then use this connection for subsequest queries. Just supply, for example, connection.execute instead of Pool.execute to momoko.Op.

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

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

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

connection = yield momoko.Op(self.db.getconn)
with self.db.manage(connection):
    cursor = yield momoko.Op(connection.execute, "BEGIN")
    ...
mogrify(operation, parameters=(), callback=None)

Return a query string after arguments binding.

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

ping(connection, callback=None)

Ping given connection object to make sure its alive (involves roundtrip to the database server).

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

putconn(connection)

Retrun busy connection back to the pool.

Parameters:connection (Connection) – Connection object previously returned by momoko.Pool.getconn(). NOTE: This is a synchronous function
register_hstore(unicode=False, callback=None)

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(loads=None, callback=None)

Register adapter and typecaster for dict-json conversions.

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(statements, cursor_factory=None, callback=None)

Run a sequence of SQL queries in a database transaction.

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

class momoko.Connection

Initiate an asynchronous connect.

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.
  • callback (callable) – A callable that’s called after the connection is created. It accepts one paramater: an instance of momoko.Connection. Defaults to None.
  • ioloop – An instance of Tornado’s IOLoop. Defaults to None.
  • setsession (list) – List of intial sql commands to be executed once connection is established. If any of the commands failes, the connection will be closed. NOTE: The commands will be executed as one transaction block.
busy()

(Deprecated) Check if the connection is busy or not.

callproc(*args, **kwargs)

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:
  • procname (string) – The name of the database procedure.
  • parameters (tuple/list) – A list or tuple with query parameters. See Passing parameters to SQL queries for more information. Defaults to an empty tuple.
  • 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.
  • callback (callable) – A callable that is executed when the query has finished. It must accept two positional parameters. The first one being the cursor and the second one None or an instance of an exception if an error has occurred, in that case the first parameter will be None. Defaults to None. NOTE: callback should always passed as keyword argument
close()

Remove the connection from the IO loop and close it.

closed

Indicates whether the connection is closed or not.

execute(*args, **kwargs)

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

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.
  • 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.
  • callback (callable) – A callable that is executed when the query has finished. It must accept two positional parameters. The first one being the cursor and the second one None or an instance of an exception if an error has occurred, in that case the first parameter will be None. Defaults to None. NOTE: callback should always passed as keyword argument
mogrify(*args, **kwargs)

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.

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.
  • callback (callable) – A callable that is executed when the query has finished. It must accept two positional parameters. The first one being the resulting query as a byte string and the second one None or an instance of an exception if an error has occurred. Defaults to None. NOTE: callback should always passed as keyword argument
ping(*args, **kwargs)

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

NOTE: On the contrary to other methods, callback function signature is
callback(self, error) and not callback(cursor, error).

NOTE: callback should always passed as keyword argument

register_hstore(globally=False, unicode=False, callback=None)

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.

NOTE: callback should always passed as keyword argument

register_json(*args, **kwargs)

Register adapter and typecaster for dict-json conversions.

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.

NOTE: callback should always passed as keyword argument

transaction(statements, cursor_factory=None, callback=None)

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 wuth 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.
  • callback (callable) – A callable that is executed when the transaction has finished. It must accept two positional parameters. The first one being a list of cursors in the same order as the given statements and the second one None or an instance of an exception if an error has occurred, in that case the first parameter is an empty list. Defaults to None. NOTE: callback should always passed as keyword argument

Utilities

class momoko.Op(func, *args, **kwargs)

Run a single asynchronous operation.

Behaves like tornado.gen.Task, but raises an exception (one of Psycop2’s exceptions) when an error occurs related to Psycopg2 or PostgreSQL.

class momoko.WaitOp(key)

Return the argument passed to the result of a previous tornado.gen.Callback.

Behaves like tornado.gen.Wait, but raises an exception (one of Psycop2’s exceptions) when an error occurs related to Psycopg2 or PostgreSQL.

class momoko.WaitAllOps(keys)

Return the results of multiple previous tornado.gen.Callback.

Behaves like tornado.gen.WaitAll, but raises an exception (one of Psycop2’s exceptions) when an error occurs related to Psycopg2 or PostgreSQL.

Exceptions

class momoko.PoolError

The PoolError exception is raised when something goes wrong in the connection pool. When the maximum amount is exceeded for example.