Database
Database class
class Database
The Database
object manages database connections using a connection pool. It is thread safe and can be shared between all threads in your application. The Database
object allows working with the database directly using SQL, but most of the time you will work with entities and let Pony generate SQL statements for making the corresponding changes in the database. You can work with several databases at the same time, having a separate Database
object for each database, but each entity always belongs to one database.
bind(provider, \args, **kwargs*)
bind(\args, **kwargs*)
Bind entities to a database.
Parameters
provider (str) – the name of the database provider. The database provider is a module which resides in the
pony.orm.dbproviders
package. It knows how to work with a particular database. After the database provider name you should specify parameters which will be passed to theconnect()
method of the corresponding DBAPI driver. Pony comes with the following providers: “sqlite”, “postgres”, “mysql”, “oracle”, “cockroachdb”. This parameter can be used as a keyword argument as well.args – parameters required by the database driver.
kwargs – parameters required by the database driver.
During the
bind()
call, Pony tries to establish a test connection to the database. If the specified parameters are not correct or the database is not available, an exception will be raised. After the connection to the database was established, Pony retrieves the version of the database and returns the connection to the connection pool.The method can be called only once for a database object. All consequent calls of this method on the same database will raise the
TypeError('Database object was already bound to ... provider')
exception.db.bind('sqlite', ':memory:')
db.bind('sqlite', 'filename', create_db=True)
db.bind('postgres', user='', password='', host='', database='')
db.bind('mysql', host='', user='', passwd='', db='')
db.bind('oracle', 'user/password@dsn')
db.bind('cockroach', user='', password='', host='',
database='', sslmode='disable')
Also you can use keyword arguments for passing the parameters:
db.bind(provider='sqlite', filename=':memory:')
db.bind(provider='sqlite', filename='db.sqlite', create_db=True)
db.bind(provider='postgres', user='', password='', host='', database='')
db.bind(provider='mysql', host='', user='', passwd='', db='')
db.bind(provider='oracle', user='', password='', dsn='')
db.bind(provider='cockroach', user='', password='', host='',
database='', sslmode='disable')
This allows keeping these parameters in a dict:
db_params = dict(provider='postgres', host='...', port=...,
user='...', password='...')
db.bind(**db_params)
commit()
Save all changes made within the current
db_session()
using theflush()
method and commits the transaction to the database.You can call
commit()
more than once within the samedb_session()
. In this case thedb_session()
cache keeps the cached objects after commits. The cache will be cleaned up when thedb_session()
is over or if the transaction will be rolled back.create_tables()
Check the existing mapping and create tables for entities if they don’t exist. Also, Pony checks if foreign keys and indexes exist and create them if they are missing.
This method can be useful if you need to create tables after they were deleted using the
drop_all_tables()
method. If you don’t delete tables, you probably don’t need this method, because Pony checks and creates tables duringgenerate_mapping()
call.disconnect()
Closes the database connection for the current thread if it was opened.
drop_all_tables(with_all_data=False)
Drop all tables which are related to the current mapping.
Parameters
with_all_data (bool) –
False
means Pony drops tables only if none of them contain any data. In case at least one of them is not empty, the method will raise theTableIsNotEmpty
exception without dropping any table. In order to drop tables with data you should setwith_all_data=True
.
drop_table(table_name, if_exists=False, with_all_data=False)
Drop the
table_name
table.If you need to delete a table which is mapped to an entity, you can use the class method
drop_table()
of an entity.Parameters
table_name (str) – the name of the table to be deleted, case sensitive.
if_exists (bool) – when
True
, it will not raise theTableDoesNotExist
exception if there is no such table in the database.with_all_data (bool) – if the table is not empty the method will raise the
TableIsNotEmpty
exception.
on_connect(provider=None)
Registers function that will be called each time new connection for given provider will establish. If provider not specified function will be called for every provider. The function should be registered before db.bind(…) call, also it should have 2 positional arguments:
Parameters
db (Database) – database object
connection (DBAPIConnection) – connection object
db = Database()
# entities declaration
@db.on_connect(provider='sqlite')
def sqlite_case_sensitivity(db, connection):
cursor = connection.cursor()
cursor.execute('PRAGMA case_sensitive_like = OFF')
db.bind(**options)
db.generate_mapping(create_tables=True)
(New in version 0.7.6)
Entity
This attribute represents the base class which should be inherited by all entities which are mapped to the particular database.
Example:
db = Database()
class Person(db.Entity):
name = Required(str)
age = Required(int)
execute(sql, globals=None, locals=None)
Execute SQL statement.
Before executing the provided SQL, Pony flushes all changes made within the current
db_session()
using theflush()
method.Parameters
sql (str) – the SQL statement text.
globals (dict) –
locals (dict) – optional parameters which can contain dicts with variables and its values, used within the query.
Returns
a DBAPI cursor.
Example:
cursor = db.execute("""create table Person (
id integer primary key autoincrement,
name text,
age integer
)""")
name, age = "Ben", 33
cursor = db.execute("insert into Person (name, age) values ($name, $age)")
See Raw SQL section for more info.
exists(sql, globals=None, locals=None)
Check if the database has at least one row which satisfies the query.
Before executing the provided SQL, Pony flushes all changes made within the current
db_session()
using theflush()
method.Parameters
sql (str) – the SQL statement text.
globals (dict) –
locals (dict) – optional parameters which can contain dicts with variables and its values, used within the query.
Return type
bool
Example:
name = 'John'
if db.exists("select * from Person where name = $name"):
print "Person exists in the database"
flush()
Save the changes accumulated in the
db_session()
cache to the database. You may never have a need to call this method manually, because it will be done on leaving thedb_session()
automatically.Pony always saves the changes accumulated in the cache automatically before executing the following methods:
get()
,exists()
,execute()
,commit()
,select()
.generate_mapping(check_tables=True, create_tables=False)
Map declared entities to the corresponding tables in the database. Creates tables, foreign key references and indexes if necessary.
Parameters
check_tables (bool) – when
True
, Pony makes a simple check that the table names and attribute names in the database correspond to entities declaration. It doesn’t catch situations when the table has extra columns or when the type of particular column doesn’t match. Set it toFalse
if you want to generate mapping and create tables for your entities later, using the methodcreate_tables()
.create_tables (bool) – create tables, foreign key references and indexes if they don’t exist. Pony generates the names of the database tables and columns automatically, but you can override this behavior if you want. See more details in the Mapping customization section.
get(sql, globals=None, locals=None)
Select one row or just one value from the database.
The
get()
method assumes that the query returns exactly one row. If the query returns nothing Pony raisesRowNotFound
exception. If the query returns more than one row, the exceptionMultipleRowsFound
will be raised.Before executing the provided SQL, Pony flushes all changes made within the current
db_session()
using theflush()
method.Parameters
sql (str) – the SQL statement text.
globals (dict) –
locals (dict) – optional parameters which can contain dicts with variables and its values, used within the query.
Returns
a tuple or a value. If your request returns a lot of columns you can assign the resulting tuple of the
get()
method to a variable and work with it the same way as it is described inselect()
method.
Example:
id = 1
age = db.get("select age from Person where id = $id")
name, age = db.get("select name, age from Person where id = $id")
get_connection()
Return the active database connection. It can be useful if you want to work with the DBAPI interface directly. This is the same connection which is used by the ORM itself. The connection will be reset and returned to the connection pool on leaving the
db_session()
context or when the database transaction rolls back. This connection can be used only within thedb_session()
scope where the connection was obtained.Returns
a DBAPI connection.
global_stats
This attribute keeps the dictionary where the statistics for executed SQL queries is aggregated from all threads. The key of this dictionary is the SQL statement and the value is an object of the
QueryStat
class.insert(table_name|entity, returning=None, \*kwargs*)
Insert new rows into a table. This command bypasses the identity map cache and can be used in order to increase the performance when you need to create lots of objects and not going to read them in the same transaction. Also you can use the
execute()
method for this purpose. If you need to work with those objects in the same transaction it is better to create instances of entities and have Pony to save them in the database.Parameters
table_name|entity (str) – the name of the table where the data will be inserted. The name is case-sensitive. Instead of the
table_name
you can use theentity
class. In this case Pony will insert into the table associated with theentity
.returning (str) – the name of the column that holds the automatically generated primary key. If you want the
insert()
method to return the value which is generated by the database, you should specify the name of the primary key column.kwargs (dict) – named parameters used within the query.
Example:
new_id = db.insert("Person", name="Ben", age=33, returning='id')
last_sql
Read-only attribute which keeps the text of the last SQL statement. It can be useful for debugging.
local_stats
This is a dictionary which keeps the SQL query statistics for the current thread. The key of this dictionary is the SQL statement and the value is an object of the
QueryStat
class.merge_local_stats()
Merge the statistics from the current thread into the global statistics. You can call this method at the end of the HTTP request processing.
When you call this method, the value of
local_stats
will be merged toglobal_stats
, andlocal_stats
will be cleared.In a web application, you can call this method on finishing processing an HTTP request. This way the
global_stats
attribute will contain the statistics for the whole application.rollback()
Rolls back the current transaction and clears the
db_session()
cache.select(sql, globals=None, locals=None)
Execute the SQL statement in the database and returns a list of tuples.
Parameters
sql (str) – the SQL statement text.
globals (dict) –
locals (dict) – optional parameters which can contain dicts with variables and its values, used within the query.
Returns
a list of tuples.
Example:
result = select("select * from Person")
If a query returns more than one column and the names of table columns are valid Python identifiers, then you can access them as attributes:
for row in db.select("name, age from Person"):
print row.name, row.age