Db(hostname=None, credentials=None, port=None)¶
Helper class for interacting with a CFME database using SQLAlchemy
- hostname – base url to be used (default is from current_appliance)
- credentials – name of credentials to use from
Provides convient attributes to common sqlalchemy objects related to this DB, as well as a Mapping interface to access and reflect database tables. Where possible, attributes are cached.
Db objects support getting tables by name via the mapping interface:
table = db['table_name']
# Usually used to query the DB for info, here's a common query for vm in db.session.query(db['vms']).all(): print(vm.name) print(vm.guid) # List comprehension to get all templates [(vm.name, vm.guid) for vm in session.query(db['vms']).all() if vm.template is True] # Use the transaction manager for write operations: with db.transaction: db.session.query(db['vms']).all().delete()
Creating a table object requires a call to the database so that SQLAlchemy can do reflection to determine the table’s structure (columns, keys, indices, etc). On a latent connection, this can be extremely slow, which will affect methods that return tables, like the mapping interface or
Copy this database instance, keeping the same credentials and hostname
The connection URL for this database, including credentials
Enginefor this database
It uses pessimistic disconnection handling, checking that the database is still connected before executing commands.
- table_name – Name of the table to get
- default – Default value to return if
table_nameis not found.
Returns: a table if
table_nameexists, otherwise ‘None’ or the passed-in default
Iterator of table names in this db
MetaDatafor this database
This can be used for introspection of reflected items.
Tables that haven’t been reflected won’t show up in metadata. To reflect a table, use
metadatawith information on a table
Parameters: table_name – The name of a table to reflect
This is used for database queries. For writing to the database, start a
This attribute is cached. In cases where a new session needs to be explicitly created, use
Base class for all tables returned by this database
This base class is created using
A sorted list of table names available in this database.
Context manager for simple transaction management
Sessions understand the concept of transactions, and provider context managers to handle conditionally committing or rolling back transactions as needed.
Sessions automatically commit transactions by default. For predictable results when writing to the database, use the transaction manager.
with db.transaction: db.session.do_something()
Iterator of tables in this db