Bases: object
Provide dialect-specific functionality within distinct functions.
e.g.:
@dispatch_for_dialect("*")
def set_special_option(engine):
pass
@set_special_option.dispatch_for("sqlite")
def set_sqlite_special_option(engine):
return engine.execute("sqlite thing")
@set_special_option.dispatch_for("mysql+mysqldb")
def set_mysqldb_special_option(engine):
return engine.execute("mysqldb thing")
After the above registration, the set_special_option() function is now a dispatcher, given a SQLAlchemy Engine, Connection, URL string, or sqlalchemy.engine.URL object:
eng = create_engine('...')
result = set_special_option(eng)
The filter system supports two modes, “multiple” and “single”. The default is “single”, and requires that one and only one function match for a given backend. In this mode, the function may also have a return value, which will be returned by the top level call.
“multiple” mode, on the other hand, does not support return arguments, but allows for any number of matching functions, where each function will be called:
# the initial call sets this up as a "multiple" dispatcher
@dispatch_for_dialect("*", multiple=True)
def set_options(engine):
# set options that apply to *all* engines
@set_options.dispatch_for("postgresql")
def set_postgresql_options(engine):
# set options that apply to all Postgresql engines
@set_options.dispatch_for("postgresql+psycopg2")
def set_postgresql_psycopg2_options(engine):
# set options that apply only to "postgresql+psycopg2"
@set_options.dispatch_for("*+pyodbc")
def set_pyodbc_options(engine):
# set options that apply to all pyodbc backends
Note that in both modes, any number of additional arguments can be accepted by member functions. For example, to populate a dictionary of options, it may be passed in:
@dispatch_for_dialect("*", multiple=True)
def set_engine_options(url, opts):
pass
@set_engine_options.dispatch_for("mysql+mysqldb")
def _mysql_set_default_charset_to_utf8(url, opts):
opts.setdefault('charset', 'utf-8')
@set_engine_options.dispatch_for("sqlite")
def _set_sqlite_in_memory_check_same_thread(url, opts):
if url.database in (None, 'memory'):
opts['check_same_thread'] = False
opts = {}
set_engine_options(url, opts)
The driver specifiers are of the form: <database | *>[+<driver | *>]. That is, database name or “*”, followed by an optional + sign with driver or “*”. Omitting the driver name implies all drivers for that database.
Return a sub-dispatcher for the given drivername.
This provides a means of calling a different function, such as the “*” function, for a given target object that normally refers to a sub-function.
Bases: object
Form the base for INSERT INTO table (SELECT ... ) statement.
DEPRECATED: this class is deprecated and will be removed from oslo_db in a few releases. Use default SQLAlchemy insert from select implementation instead
Parameters: |
|
---|---|
Returns: | SQLAlchemy Insert object instance |
Usage:
select = sql.select(table_from)
insert = InsertFromSelect(table_to, select,
['id', 'name', 'insert_date'])
engine.execute(insert)
Bases: object
A Connectable substitute which rolls all operations back.
NonCommittingConnectable forms the basis of mock Engine and Connection objects within a test. It provides only that part of the API that should reasonably be used within a single-connection test environment (e.g. no engine.dispose(), connection.invalidate(), etc. ). The connection runs both within a transaction as well as a savepoint. The transaction is there so that any operations upon the connection can be rolled back. If the test calls begin(), a “pseduo” transaction is returned that won’t actually commit anything. The subtransaction is there to allow a test to successfully call rollback(), however, where all operations to that point will be rolled back and the operations can continue, simulating a real rollback while still remaining within a transaction external to the test.
Executes the given construct and returns a ResultProxy.
Executes and returns the first column of the first row.
Bases: oslo_db.sqlalchemy.utils.NonCommittingConnectable
Connection -specific non committing connectbale.
Close the ‘Connection’.
In this context, close() is a no-op.
Bases: oslo_db.sqlalchemy.utils.NonCommittingConnectable
Engine -specific non committing connectbale.
Bases: object
A wrapper for Transaction.
This is to accommodate being able to guaranteed start a new SAVEPOINT when a transaction is rolled back.
Create an index for given columns.
Parameters: |
|
---|
Change set of columns that are indexed by given index.
Parameters: |
|
---|
Check if table has given column.
Parameters: |
|
---|
Drop index with given name.
Parameters: |
|
---|
Drop all old rows having the same values for columns in uc_columns.
This method drop (or mark ad deleted if use_soft_delete is True) old duplicate rows form table with name table_name.
Parameters: |
|
---|
Get database connection
Try to get a connection with a very specific set of values, if we get these then we’ll run the tests, otherwise they are skipped
DEPRECATED: this function is deprecated and will be removed from oslo_db in a few releases. Please use the provisioning system for dealing with URLs and database provisioning.
Get a list of tables which don’t use InnoDB storage engine.
Parameters: |
|
---|
Returns an sqlalchemy table dynamically from db.
Needed because the models don’t work for us in migrations as models will be far out of sync with the current data.
Warning
Do not use this method when creating ForeignKeys in database migrations because sqlalchemy needs the same MetaData object to hold information about the parent table and the reference table in the ForeignKey. This method uses a unique MetaData object per table object so it won’t work with ForeignKey creation.
Check if given index exists.
Parameters: |
|
---|
Return True if the given backend is available.
DEPRECATED: this function is deprecated and will be removed from oslo_db in a few releases. Please use the provisioning system to access databases based on backend availability.
Query helper for db.sqlalchemy api methods.
This accounts for deleted and project_id fields.
Parameters: |
|
---|
Keyword arguments:
Parameters: |
|
---|
Usage:
from oslo_db.sqlalchemy import utils
def get_instance_by_uuid(uuid):
session = get_session()
with session.begin()
return (utils.model_query(models.Instance, session=session)
.filter(models.Instance.uuid == uuid)
.first())
def get_nodes_stat():
data = (Node.id, Node.cpu, Node.ram, Node.hdd)
session = get_session()
with session.begin()
return utils.model_query(Node, session=session, args=data).all()
Also you can create your own helper, based on utils.model_query(). For example, it can be useful if you plan to use project_id and deleted parameters from project’s context
from oslo_db.sqlalchemy import utils
def _model_query(context, model, session=None, args=None,
project_id=None, project_only=False,
read_deleted=None):
# We suppose, that functions ``_get_project_id()`` and
# ``_get_deleted()`` should handle passed parameters and
# context object (for example, decide, if we need to restrict a user
# to query his own entries by project_id or only allow admin to read
# deleted entries). For return values, we expect to get
# ``project_id`` and ``deleted``, which are suitable for the
# ``model_query()`` signature.
kwargs = {}
if project_id is not None:
kwargs['project_id'] = _get_project_id(context, project_id,
project_only)
if read_deleted is not None:
kwargs['deleted'] = _get_deleted_dict(context, read_deleted)
session = session or get_session()
with session.begin():
return utils.model_query(model, session=session,
args=args, **kwargs)
def get_instance_by_uuid(context, uuid):
return (_model_query(context, models.Instance, read_deleted='yes')
.filter(models.Instance.uuid == uuid)
.first())
def get_nodes_data(context, project_id, project_only='allow_none'):
data = (Node.id, Node.cpu, Node.ram, Node.hdd)
return (_model_query(context, Node, args=data, project_id=project_id,
project_only=project_only)
.all())
Returns a query with sorting / pagination criteria added.
Pagination works by requiring a unique sort_key, specified by sort_keys. (If sort_keys is not unique, then we risk looping through values.) We use the last row in the previous page as the ‘marker’ for pagination. So we must return values that follow the passed marker in the order. With a single-valued sort_key, this would be easy: sort_key > X. With a compound-values sort_key, (k1, k2, k3) we must do this to repeat the lexicographical ordering: (k1 > X1) or (k1 == X1 && k2 > X2) or (k1 == X1 && k2 == X2 && k3 > X3)
We also have to cope with different sort_directions.
Typically, the id of the last row is used as the client-facing pagination marker, then the actual marker object must be fetched from the db and passed in to us as marker.
Parameters: |
|
---|---|
Return type: | sqlalchemy.orm.query.Query |
Returns: | The query with sorting/pagination added. |