| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
import collections |
| 20 |
from collections import abc |
| 21 |
import itertools |
| 22 |
import logging |
| 23 |
import re |
| 24 |
|
| 25 |
from oslo_utils import timeutils |
| 26 |
import sqlalchemy |
| 27 |
from sqlalchemy import Boolean |
| 28 |
from sqlalchemy.engine import Connectable |
| 29 |
from sqlalchemy.engine import url as sa_url |
| 30 |
from sqlalchemy import exc |
| 31 |
from sqlalchemy import func |
| 32 |
from sqlalchemy import Index |
| 33 |
from sqlalchemy import inspect |
| 34 |
from sqlalchemy import Integer |
| 35 |
from sqlalchemy import MetaData |
| 36 |
from sqlalchemy.sql.expression import cast |
| 37 |
from sqlalchemy.sql.expression import literal_column |
| 38 |
from sqlalchemy.sql import text |
| 39 |
from sqlalchemy import Table |
| 40 |
|
| 41 |
from oslo_db._i18n import _ |
| 42 |
from oslo_db import exception |
| 43 |
from oslo_db.sqlalchemy import models |
| 44 |
|
| 45 |
|
| 46 |
InvalidSortKey = exception.InvalidSortKey |
| 47 |
ColumnError = exception.ColumnError |
| 48 |
|
| 49 |
LOG = logging.getLogger(__name__) |
| 50 |
|
| 51 |
_DBURL_REGEX = re.compile(r"[^:]+://([^:]+):([^@]+)@.+") |
| 52 |
|
| 53 |
_VALID_SORT_DIR = [ |
| 54 |
"-".join(x) for x in itertools.product(["asc", "desc"], |
| 55 |
["nullsfirst", "nullslast"])] |
| 56 |
|
| 57 |
|
| 58 |
def sanitize_db_url(url): |
| 59 |
match = _DBURL_REGEX.match(url) |
| 60 |
if match: |
| 61 |
return f'{url[:match.start(1)]}****:****{url[match.end(2):]}' |
| 62 |
return url |
| 63 |
|
| 64 |
|
| 65 |
def get_unique_keys(model): |
| 66 |
"""Get a list of sets of unique model keys. |
| 67 |
|
| 68 |
:param model: the ORM model class |
| 69 |
:rtype: list of sets of strings |
| 70 |
:return: unique model keys or None if unable to find them |
| 71 |
""" |
| 72 |
|
| 73 |
try: |
| 74 |
mapper = inspect(model) |
| 75 |
except exc.NoInspectionAvailable: |
| 76 |
return None |
| 77 |
else: |
| 78 |
local_table = mapper.local_table |
| 79 |
base_table = mapper.base_mapper.local_table |
| 80 |
|
| 81 |
if local_table is None: |
| 82 |
return None |
| 83 |
|
| 84 |
|
| 85 |
has_info = hasattr(local_table, 'info') |
| 86 |
if has_info: |
| 87 |
info = local_table.info |
| 88 |
if 'oslodb_unique_keys' in info: |
| 89 |
return info['oslodb_unique_keys'] |
| 90 |
|
| 91 |
res = [] |
| 92 |
try: |
| 93 |
constraints = base_table.constraints |
| 94 |
except AttributeError: |
| 95 |
constraints = [] |
| 96 |
for constraint in constraints: |
| 97 |
|
| 98 |
if isinstance(constraint, (sqlalchemy.UniqueConstraint, |
| 99 |
sqlalchemy.PrimaryKeyConstraint)): |
| 100 |
res.append({c.name for c in constraint.columns}) |
| 101 |
try: |
| 102 |
indexes = base_table.indexes |
| 103 |
except AttributeError: |
| 104 |
indexes = [] |
| 105 |
for index in indexes: |
| 106 |
if index.unique: |
| 107 |
res.append({c.name for c in index.columns}) |
| 108 |
|
| 109 |
if has_info: |
| 110 |
info['oslodb_unique_keys'] = res |
| 111 |
return res |
| 112 |
|
| 113 |
|
| 114 |
def _stable_sorting_order(model, sort_keys): |
| 115 |
"""Check whether the sorting order is stable. |
| 116 |
|
| 117 |
:return: True if it is stable, False if it's not, None if it's impossible |
| 118 |
to determine. |
| 119 |
""" |
| 120 |
keys = get_unique_keys(model) |
| 121 |
if keys is None: |
| 122 |
return None |
| 123 |
sort_keys_set = set(sort_keys) |
| 124 |
for unique_keys in keys: |
| 125 |
if unique_keys.issubset(sort_keys_set): |
| 126 |
return True |
| 127 |
return False |
| 128 |
|
| 129 |
|
| 130 |
|
| 131 |
def paginate_query(query, model, limit, sort_keys, marker=None, |
| 132 |
sort_dir=None, sort_dirs=None): |
| 133 |
"""Returns a query with sorting / pagination criteria added. |
| 134 |
|
| 135 |
Pagination works by requiring a unique sort_key, specified by sort_keys. |
| 136 |
(If sort_keys is not unique, then we risk looping through values.) |
| 137 |
We use the last row in the previous page as the 'marker' for pagination. |
| 138 |
So we must return values that follow the passed marker in the order. |
| 139 |
With a single-valued sort_key, this would be easy: sort_key > X. |
| 140 |
With a compound-values sort_key, (k1, k2, k3) we must do this to repeat |
| 141 |
the lexicographical ordering: |
| 142 |
(k1 > X1) or (k1 == X1 && k2 > X2) or (k1 == X1 && k2 == X2 && k3 > X3) |
| 143 |
|
| 144 |
We also have to cope with different sort_directions and cases where k2, |
| 145 |
k3, ... are nullable. |
| 146 |
|
| 147 |
Typically, the id of the last row is used as the client-facing pagination |
| 148 |
marker, then the actual marker object must be fetched from the db and |
| 149 |
passed in to us as marker. |
| 150 |
|
| 151 |
The "offset" parameter is intentionally avoided. As offset requires a |
| 152 |
full scan through the preceding results each time, criteria-based |
| 153 |
pagination is preferred. See http://use-the-index-luke.com/no-offset |
| 154 |
for further background. |
| 155 |
|
| 156 |
:param query: the query object to which we should add paging/sorting |
| 157 |
:param model: the ORM model class |
| 158 |
:param limit: maximum number of items to return |
| 159 |
:param sort_keys: array of attributes by which results should be sorted |
| 160 |
:param marker: the last item of the previous page; we returns the next |
| 161 |
results after this value. |
| 162 |
:param sort_dir: direction in which results should be sorted (asc, desc) |
| 163 |
suffix -nullsfirst, -nullslast can be added to defined |
| 164 |
the ordering of null values |
| 165 |
:param sort_dirs: per-column array of sort_dirs, corresponding to sort_keys |
| 166 |
|
| 167 |
:rtype: sqlalchemy.orm.query.Query |
| 168 |
:return: The query with sorting/pagination added. |
| 169 |
""" |
| 170 |
if _stable_sorting_order(model, sort_keys) is False: |
| 171 |
LOG.warning('Unique keys not in sort_keys. ' |
| 172 |
'The sorting order may be unstable.') |
| 173 |
|
| 174 |
if sort_dir and sort_dirs: |
| 175 |
raise AssertionError('Disallow set sort_dir and ' |
| 176 |
'sort_dirs at the same time.') |
| 177 |
|
| 178 |
|
| 179 |
if sort_dirs is None and sort_dir is None: |
| 180 |
sort_dir = 'asc' |
| 181 |
|
| 182 |
|
| 183 |
if sort_dirs is None: |
| 184 |
sort_dirs = [sort_dir for _sort_key in sort_keys] |
| 185 |
|
| 186 |
if len(sort_dirs) != len(sort_keys): |
| 187 |
raise AssertionError('sort_dirs and sort_keys must have same length.') |
| 188 |
|
| 189 |
|
| 190 |
for current_sort_key, current_sort_dir in zip(sort_keys, sort_dirs): |
| 191 |
try: |
| 192 |
inspect(model).all_orm_descriptors[current_sort_key] |
| 193 |
except KeyError: |
| 194 |
raise exception.InvalidSortKey(current_sort_key) |
| 195 |
else: |
| 196 |
sort_key_attr = getattr(model, current_sort_key) |
| 197 |
|
| 198 |
try: |
| 199 |
main_sort_dir, __, null_sort_dir = current_sort_dir.partition("-") |
| 200 |
sort_dir_func = { |
| 201 |
'asc': sqlalchemy.asc, |
| 202 |
'desc': sqlalchemy.desc, |
| 203 |
}[main_sort_dir] |
| 204 |
|
| 205 |
null_order_by_stmt = { |
| 206 |
"": None, |
| 207 |
"nullsfirst": sort_key_attr.is_(None), |
| 208 |
"nullslast": sort_key_attr.is_not(None), |
| 209 |
}[null_sort_dir] |
| 210 |
except KeyError: |
| 211 |
raise ValueError(_("Unknown sort direction, " |
| 212 |
"must be one of: %s") % |
| 213 |
", ".join(_VALID_SORT_DIR)) |
| 214 |
|
| 215 |
if null_order_by_stmt is not None: |
| 216 |
query = query.order_by(sqlalchemy.desc(null_order_by_stmt)) |
| 217 |
query = query.order_by(sort_dir_func(sort_key_attr)) |
| 218 |
|
| 219 |
|
| 220 |
if marker is not None: |
| 221 |
marker_values = [] |
| 222 |
for sort_key in sort_keys: |
| 223 |
v = getattr(marker, sort_key) |
| 224 |
marker_values.append(v) |
| 225 |
|
| 226 |
|
| 227 |
criteria_list = [] |
| 228 |
for i in range(len(sort_keys)): |
| 229 |
crit_attrs = [] |
| 230 |
|
| 231 |
|
| 232 |
|
| 233 |
|
| 234 |
|
| 235 |
if marker_values[i] is not None: |
| 236 |
for j in range(i): |
| 237 |
model_attr = getattr(model, sort_keys[j]) |
| 238 |
if marker_values[j] is not None: |
| 239 |
crit_attrs.append(model_attr == marker_values[j]) |
| 240 |
|
| 241 |
model_attr = getattr(model, sort_keys[i]) |
| 242 |
val = marker_values[i] |
| 243 |
|
| 244 |
if isinstance(model_attr.type, Boolean): |
| 245 |
val = int(val) |
| 246 |
model_attr = cast(model_attr, Integer) |
| 247 |
if sort_dirs[i].startswith('desc'): |
| 248 |
crit_attr = (model_attr < val) |
| 249 |
if sort_dirs[i].endswith('nullsfirst'): |
| 250 |
crit_attr = sqlalchemy.sql.or_(crit_attr, |
| 251 |
model_attr.is_(None)) |
| 252 |
else: |
| 253 |
crit_attr = (model_attr > val) |
| 254 |
if sort_dirs[i].endswith('nullslast'): |
| 255 |
crit_attr = sqlalchemy.sql.or_(crit_attr, |
| 256 |
model_attr.is_(None)) |
| 257 |
crit_attrs.append(crit_attr) |
| 258 |
criteria = sqlalchemy.sql.and_(*crit_attrs) |
| 259 |
criteria_list.append(criteria) |
| 260 |
|
| 261 |
f = sqlalchemy.sql.or_(*criteria_list) |
| 262 |
query = query.filter(f) |
| 263 |
|
| 264 |
if limit is not None: |
| 265 |
query = query.limit(limit) |
| 266 |
|
| 267 |
return query |
| 268 |
|
| 269 |
|
| 270 |
def to_list(x, default=None): |
| 271 |
if x is None: |
| 272 |
return default |
| 273 |
if not isinstance(x, abc.Iterable) or isinstance(x, str): |
| 274 |
return [x] |
| 275 |
elif isinstance(x, list): |
| 276 |
return x |
| 277 |
else: |
| 278 |
return list(x) |
| 279 |
|
| 280 |
|
| 281 |
def _read_deleted_filter(query, db_model, deleted): |
| 282 |
if 'deleted' not in db_model.__table__.columns: |
| 283 |
raise ValueError(_("There is no `deleted` column in `%s` table. " |
| 284 |
"Project doesn't use soft-deleted feature.") |
| 285 |
% db_model.__name__) |
| 286 |
|
| 287 |
default_deleted_value = db_model.__table__.c.deleted.default.arg |
| 288 |
if deleted: |
| 289 |
query = query.filter(db_model.deleted != default_deleted_value) |
| 290 |
else: |
| 291 |
query = query.filter(db_model.deleted == default_deleted_value) |
| 292 |
return query |
| 293 |
|
| 294 |
|
| 295 |
def _project_filter(query, db_model, project_id): |
| 296 |
if 'project_id' not in db_model.__table__.columns: |
| 297 |
raise ValueError(_("There is no `project_id` column in `%s` table.") |
| 298 |
% db_model.__name__) |
| 299 |
|
| 300 |
if isinstance(project_id, (list, tuple, set)): |
| 301 |
query = query.filter(db_model.project_id.in_(project_id)) |
| 302 |
else: |
| 303 |
query = query.filter(db_model.project_id == project_id) |
| 304 |
|
| 305 |
return query |
| 306 |
|
| 307 |
|
| 308 |
def model_query(model, session, args=None, **kwargs): |
| 309 |
"""Query helper for db.sqlalchemy api methods. |
| 310 |
|
| 311 |
This accounts for `deleted` and `project_id` fields. |
| 312 |
|
| 313 |
:param model: Model to query. Must be a subclass of ModelBase. |
| 314 |
:type model: models.ModelBase |
| 315 |
|
| 316 |
:param session: The session to use. |
| 317 |
:type session: sqlalchemy.orm.session.Session |
| 318 |
|
| 319 |
:param args: Arguments to query. If None - model is used. |
| 320 |
:type args: tuple |
| 321 |
|
| 322 |
Keyword arguments: |
| 323 |
|
| 324 |
:keyword project_id: If present, allows filtering by project_id(s). |
| 325 |
Can be either a project_id value, or an iterable of |
| 326 |
project_id values, or None. If an iterable is passed, |
| 327 |
only rows whose project_id column value is on the |
| 328 |
`project_id` list will be returned. If None is passed, |
| 329 |
only rows which are not bound to any project, will be |
| 330 |
returned. |
| 331 |
:type project_id: iterable, |
| 332 |
model.__table__.columns.project_id.type, |
| 333 |
None type |
| 334 |
|
| 335 |
:keyword deleted: If present, allows filtering by deleted field. |
| 336 |
If True is passed, only deleted entries will be |
| 337 |
returned, if False - only existing entries. |
| 338 |
:type deleted: bool |
| 339 |
|
| 340 |
|
| 341 |
Usage: |
| 342 |
|
| 343 |
.. code-block:: python |
| 344 |
|
| 345 |
from oslo_db.sqlalchemy import utils |
| 346 |
|
| 347 |
|
| 348 |
def get_instance_by_uuid(uuid): |
| 349 |
session = get_session() |
| 350 |
with session.begin() |
| 351 |
return (utils.model_query(models.Instance, session=session) |
| 352 |
.filter(models.Instance.uuid == uuid) |
| 353 |
.first()) |
| 354 |
|
| 355 |
def get_nodes_stat(): |
| 356 |
data = (Node.id, Node.cpu, Node.ram, Node.hdd) |
| 357 |
|
| 358 |
session = get_session() |
| 359 |
with session.begin() |
| 360 |
return utils.model_query(Node, session=session, args=data).all() |
| 361 |
|
| 362 |
Also you can create your own helper, based on ``utils.model_query()``. |
| 363 |
For example, it can be useful if you plan to use ``project_id`` and |
| 364 |
``deleted`` parameters from project's ``context`` |
| 365 |
|
| 366 |
.. code-block:: python |
| 367 |
|
| 368 |
from oslo_db.sqlalchemy import utils |
| 369 |
|
| 370 |
|
| 371 |
def _model_query(context, model, session=None, args=None, |
| 372 |
project_id=None, project_only=False, |
| 373 |
read_deleted=None): |
| 374 |
|
| 375 |
# We suppose, that functions ``_get_project_id()`` and |
| 376 |
# ``_get_deleted()`` should handle passed parameters and |
| 377 |
# context object (for example, decide, if we need to restrict a user |
| 378 |
# to query his own entries by project_id or only allow admin to read |
| 379 |
# deleted entries). For return values, we expect to get |
| 380 |
# ``project_id`` and ``deleted``, which are suitable for the |
| 381 |
# ``model_query()`` signature. |
| 382 |
kwargs = {} |
| 383 |
if project_id is not None: |
| 384 |
kwargs['project_id'] = _get_project_id(context, project_id, |
| 385 |
project_only) |
| 386 |
if read_deleted is not None: |
| 387 |
kwargs['deleted'] = _get_deleted_dict(context, read_deleted) |
| 388 |
session = session or get_session() |
| 389 |
|
| 390 |
with session.begin(): |
| 391 |
return utils.model_query(model, session=session, |
| 392 |
args=args, **kwargs) |
| 393 |
|
| 394 |
def get_instance_by_uuid(context, uuid): |
| 395 |
return (_model_query(context, models.Instance, read_deleted='yes') |
| 396 |
.filter(models.Instance.uuid == uuid) |
| 397 |
.first()) |
| 398 |
|
| 399 |
def get_nodes_data(context, project_id, project_only='allow_none'): |
| 400 |
data = (Node.id, Node.cpu, Node.ram, Node.hdd) |
| 401 |
|
| 402 |
return (_model_query(context, Node, args=data, project_id=project_id, |
| 403 |
project_only=project_only) |
| 404 |
.all()) |
| 405 |
|
| 406 |
""" |
| 407 |
|
| 408 |
if not issubclass(model, models.ModelBase): |
| 409 |
raise TypeError(_("model should be a subclass of ModelBase")) |
| 410 |
|
| 411 |
query = session.query(model) if not args else session.query(*args) |
| 412 |
if 'deleted' in kwargs: |
| 413 |
query = _read_deleted_filter(query, model, kwargs['deleted']) |
| 414 |
if 'project_id' in kwargs: |
| 415 |
query = _project_filter(query, model, kwargs['project_id']) |
| 416 |
|
| 417 |
return query |
| 418 |
|
| 419 |
|
| 420 |
def get_table(engine, name): |
| 421 |
"""Returns an sqlalchemy table dynamically from db. |
| 422 |
|
| 423 |
Needed because the models don't work for us in migrations |
| 424 |
as models will be far out of sync with the current data. |
| 425 |
|
| 426 |
.. warning:: |
| 427 |
|
| 428 |
Do not use this method when creating ForeignKeys in database migrations |
| 429 |
because sqlalchemy needs the same MetaData object to hold information |
| 430 |
about the parent table and the reference table in the ForeignKey. This |
| 431 |
method uses a unique MetaData object per table object so it won't work |
| 432 |
with ForeignKey creation. |
| 433 |
""" |
| 434 |
metadata = MetaData() |
| 435 |
return Table(name, metadata, autoload_with=engine) |
| 436 |
|
| 437 |
|
| 438 |
def drop_old_duplicate_entries_from_table(engine, table_name, |
| 439 |
use_soft_delete, *uc_column_names): |
| 440 |
"""Drop all old rows having the same values for columns in uc_columns. |
| 441 |
|
| 442 |
This method drop (or mark ad `deleted` if use_soft_delete is True) old |
| 443 |
duplicate rows form table with name `table_name`. |
| 444 |
|
| 445 |
:param engine: Sqlalchemy engine |
| 446 |
:param table_name: Table with duplicates |
| 447 |
:param use_soft_delete: If True - values will be marked as `deleted`, |
| 448 |
if False - values will be removed from table |
| 449 |
:param uc_column_names: Unique constraint columns |
| 450 |
""" |
| 451 |
meta = MetaData() |
| 452 |
|
| 453 |
table = Table(table_name, meta, autoload_with=engine) |
| 454 |
columns_for_group_by = [table.c[name] for name in uc_column_names] |
| 455 |
|
| 456 |
columns_for_select = [func.max(table.c.id)] |
| 457 |
columns_for_select.extend(columns_for_group_by) |
| 458 |
|
| 459 |
duplicated_rows_select = sqlalchemy.sql.select( |
| 460 |
*columns_for_select, |
| 461 |
).group_by( |
| 462 |
*columns_for_group_by |
| 463 |
).having( |
| 464 |
func.count(table.c.id) > 1 |
| 465 |
) |
| 466 |
|
| 467 |
with engine.connect() as conn, conn.begin(): |
| 468 |
for row in conn.execute(duplicated_rows_select).fetchall(): |
| 469 |
|
| 470 |
delete_condition = table.c.id != row[0] |
| 471 |
is_none = None |
| 472 |
delete_condition &= table.c.deleted_at == is_none |
| 473 |
for name in uc_column_names: |
| 474 |
delete_condition &= table.c[name] == row._mapping[name] |
| 475 |
|
| 476 |
rows_to_delete_select = sqlalchemy.sql.select( |
| 477 |
table.c.id, |
| 478 |
).where(delete_condition) |
| 479 |
for row in conn.execute(rows_to_delete_select).fetchall(): |
| 480 |
LOG.info( |
| 481 |
"Deleting duplicated row with id: %(id)s from table: " |
| 482 |
"%(table)s", dict(id=row[0], table=table_name)) |
| 483 |
|
| 484 |
if use_soft_delete: |
| 485 |
delete_statement = table.update().\ |
| 486 |
where(delete_condition).\ |
| 487 |
values({ |
| 488 |
'deleted': literal_column('id'), |
| 489 |
'updated_at': literal_column('updated_at'), |
| 490 |
'deleted_at': timeutils.utcnow() |
| 491 |
}) |
| 492 |
else: |
| 493 |
delete_statement = table.delete().where(delete_condition) |
| 494 |
conn.execute(delete_statement) |
| 495 |
|
| 496 |
|
| 497 |
def get_db_connection_info(conn_pieces): |
| 498 |
database = conn_pieces.path.strip('/') |
| 499 |
loc_pieces = conn_pieces.netloc.split('@') |
| 500 |
host = loc_pieces[1] |
| 501 |
|
| 502 |
auth_pieces = loc_pieces[0].split(':') |
| 503 |
user = auth_pieces[0] |
| 504 |
password = "" |
| 505 |
if len(auth_pieces) > 1: |
| 506 |
password = auth_pieces[1].strip() |
| 507 |
|
| 508 |
return (user, password, database, host) |
| 509 |
|
| 510 |
|
| 511 |
def get_indexes(engine, table_name): |
| 512 |
"""Get all index list from a given table. |
| 513 |
|
| 514 |
:param engine: sqlalchemy engine |
| 515 |
:param table_name: name of the table |
| 516 |
""" |
| 517 |
|
| 518 |
inspector = sqlalchemy.inspect(engine) |
| 519 |
indexes = inspector.get_indexes(table_name) |
| 520 |
return indexes |
| 521 |
|
| 522 |
|
| 523 |
def index_exists(engine, table_name, index_name): |
| 524 |
"""Check if given index exists. |
| 525 |
|
| 526 |
:param engine: sqlalchemy engine |
| 527 |
:param table_name: name of the table |
| 528 |
:param index_name: name of the index |
| 529 |
""" |
| 530 |
indexes = get_indexes(engine, table_name) |
| 531 |
index_names = [index['name'] for index in indexes] |
| 532 |
return index_name in index_names |
| 533 |
|
| 534 |
|
| 535 |
def index_exists_on_columns(engine, table_name, columns): |
| 536 |
"""Check if an index on given columns exists. |
| 537 |
|
| 538 |
:param engine: sqlalchemy engine |
| 539 |
:param table_name: name of the table |
| 540 |
:param columns: a list type of columns that will be checked |
| 541 |
""" |
| 542 |
if not isinstance(columns, list): |
| 543 |
columns = list(columns) |
| 544 |
for index in get_indexes(engine, table_name): |
| 545 |
if index['column_names'] == columns: |
| 546 |
return True |
| 547 |
return False |
| 548 |
|
| 549 |
|
| 550 |
def add_index(engine, table_name, index_name, idx_columns): |
| 551 |
"""Create an index for given columns. |
| 552 |
|
| 553 |
:param engine: sqlalchemy engine |
| 554 |
:param table_name: name of the table |
| 555 |
:param index_name: name of the index |
| 556 |
:param idx_columns: tuple with names of columns that will be indexed |
| 557 |
""" |
| 558 |
table = get_table(engine, table_name) |
| 559 |
if not index_exists(engine, table_name, index_name): |
| 560 |
index = Index( |
| 561 |
index_name, *[getattr(table.c, col) for col in idx_columns] |
| 562 |
) |
| 563 |
index.create(engine) |
| 564 |
else: |
| 565 |
raise ValueError("Index '%s' already exists!" % index_name) |
| 566 |
|
| 567 |
|
| 568 |
def drop_index(engine, table_name, index_name): |
| 569 |
"""Drop index with given name. |
| 570 |
|
| 571 |
:param engine: sqlalchemy engine |
| 572 |
:param table_name: name of the table |
| 573 |
:param index_name: name of the index |
| 574 |
""" |
| 575 |
table = get_table(engine, table_name) |
| 576 |
for index in table.indexes: |
| 577 |
if index.name == index_name: |
| 578 |
index.drop(engine) |
| 579 |
break |
| 580 |
else: |
| 581 |
raise ValueError("Index '%s' not found!" % index_name) |
| 582 |
|
| 583 |
|
| 584 |
def change_index_columns(engine, table_name, index_name, new_columns): |
| 585 |
"""Change set of columns that are indexed by given index. |
| 586 |
|
| 587 |
:param engine: sqlalchemy engine |
| 588 |
:param table_name: name of the table |
| 589 |
:param index_name: name of the index |
| 590 |
:param new_columns: tuple with names of columns that will be indexed |
| 591 |
""" |
| 592 |
drop_index(engine, table_name, index_name) |
| 593 |
add_index(engine, table_name, index_name, new_columns) |
| 594 |
|
| 595 |
|
| 596 |
def column_exists(engine, table_name, column): |
| 597 |
"""Check if table has given column. |
| 598 |
|
| 599 |
:param engine: sqlalchemy engine |
| 600 |
:param table_name: name of the table |
| 601 |
:param column: name of the colmn |
| 602 |
""" |
| 603 |
t = get_table(engine, table_name) |
| 604 |
return column in t.c |
| 605 |
|
| 606 |
|
| 607 |
class DialectFunctionDispatcher: |
| 608 |
@classmethod |
| 609 |
def dispatch_for_dialect(cls, expr, multiple=False): |
| 610 |
"""Provide dialect-specific functionality within distinct functions. |
| 611 |
|
| 612 |
e.g.:: |
| 613 |
|
| 614 |
@dispatch_for_dialect("*") |
| 615 |
def set_special_option(engine): |
| 616 |
pass |
| 617 |
|
| 618 |
@set_special_option.dispatch_for("sqlite") |
| 619 |
def set_sqlite_special_option(engine): |
| 620 |
return engine.execute("sqlite thing") |
| 621 |
|
| 622 |
@set_special_option.dispatch_for("mysql+mysqldb") |
| 623 |
def set_mysqldb_special_option(engine): |
| 624 |
return engine.execute("mysqldb thing") |
| 625 |
|
| 626 |
After the above registration, the ``set_special_option()`` function |
| 627 |
is now a dispatcher, given a SQLAlchemy ``Engine``, ``Connection``, |
| 628 |
URL string, or ``sqlalchemy.engine.URL`` object:: |
| 629 |
|
| 630 |
eng = create_engine('...') |
| 631 |
result = set_special_option(eng) |
| 632 |
|
| 633 |
The filter system supports two modes, "multiple" and "single". |
| 634 |
The default is "single", and requires that one and only one function |
| 635 |
match for a given backend. In this mode, the function may also |
| 636 |
have a return value, which will be returned by the top level |
| 637 |
call. |
| 638 |
|
| 639 |
"multiple" mode, on the other hand, does not support return |
| 640 |
arguments, but allows for any number of matching functions, where |
| 641 |
each function will be called:: |
| 642 |
|
| 643 |
# the initial call sets this up as a "multiple" dispatcher |
| 644 |
@dispatch_for_dialect("*", multiple=True) |
| 645 |
def set_options(engine): |
| 646 |
# set options that apply to *all* engines |
| 647 |
|
| 648 |
@set_options.dispatch_for("postgresql") |
| 649 |
def set_postgresql_options(engine): |
| 650 |
# set options that apply to all Postgresql engines |
| 651 |
|
| 652 |
@set_options.dispatch_for("postgresql+psycopg2") |
| 653 |
def set_postgresql_psycopg2_options(engine): |
| 654 |
# set options that apply only to "postgresql+psycopg2" |
| 655 |
|
| 656 |
@set_options.dispatch_for("*+pyodbc") |
| 657 |
def set_pyodbc_options(engine): |
| 658 |
# set options that apply to all pyodbc backends |
| 659 |
|
| 660 |
Note that in both modes, any number of additional arguments can be |
| 661 |
accepted by member functions. For example, to populate a dictionary of |
| 662 |
options, it may be passed in:: |
| 663 |
|
| 664 |
@dispatch_for_dialect("*", multiple=True) |
| 665 |
def set_engine_options(url, opts): |
| 666 |
pass |
| 667 |
|
| 668 |
@set_engine_options.dispatch_for("mysql+mysqldb") |
| 669 |
def _mysql_set_default_charset_to_utf8(url, opts): |
| 670 |
opts.setdefault('charset', 'utf-8') |
| 671 |
|
| 672 |
@set_engine_options.dispatch_for("sqlite") |
| 673 |
def _set_sqlite_in_memory_check_same_thread(url, opts): |
| 674 |
if url.database in (None, 'memory'): |
| 675 |
opts['check_same_thread'] = False |
| 676 |
|
| 677 |
opts = {} |
| 678 |
set_engine_options(url, opts) |
| 679 |
|
| 680 |
The driver specifiers are of the form: |
| 681 |
``<database | *>[+<driver | *>]``. That is, database name or "*", |
| 682 |
followed by an optional ``+`` sign with driver or "*". Omitting |
| 683 |
the driver name implies all drivers for that database. |
| 684 |
|
| 685 |
""" |
| 686 |
if multiple: |
| 687 |
cls = DialectMultiFunctionDispatcher |
| 688 |
else: |
| 689 |
cls = DialectSingleFunctionDispatcher |
| 690 |
return cls().dispatch_for(expr) |
| 691 |
|
| 692 |
_db_plus_driver_reg = re.compile(r'([^+]+?)(?:\+(.+))?$') |
| 693 |
|
| 694 |
def dispatch_for(self, expr): |
| 695 |
def decorate(fn): |
| 696 |
dbname, driver = self._parse_dispatch(expr) |
| 697 |
if fn is self: |
| 698 |
fn = fn._last |
| 699 |
self._last = fn |
| 700 |
self._register(expr, dbname, driver, fn) |
| 701 |
return self |
| 702 |
return decorate |
| 703 |
|
| 704 |
def _parse_dispatch(self, text): |
| 705 |
m = self._db_plus_driver_reg.match(text) |
| 706 |
if not m: |
| 707 |
raise ValueError("Couldn't parse database[+driver]: %r" % text) |
| 708 |
return m.group(1) or '*', m.group(2) or '*' |
| 709 |
|
| 710 |
def __call__(self, *arg, **kw): |
| 711 |
target = arg[0] |
| 712 |
return self._dispatch_on( |
| 713 |
self._url_from_target(target), target, arg, kw) |
| 714 |
|
| 715 |
def _url_from_target(self, target): |
| 716 |
if isinstance(target, Connectable): |
| 717 |
return target.engine.url |
| 718 |
elif isinstance(target, str): |
| 719 |
if "://" not in target: |
| 720 |
target_url = sa_url.make_url("%s://" % target) |
| 721 |
else: |
| 722 |
target_url = sa_url.make_url(target) |
| 723 |
return target_url |
| 724 |
elif isinstance(target, sa_url.URL): |
| 725 |
return target |
| 726 |
else: |
| 727 |
raise ValueError("Invalid target type: %r" % target) |
| 728 |
|
| 729 |
def dispatch_on_drivername(self, drivername): |
| 730 |
"""Return a sub-dispatcher for the given drivername. |
| 731 |
|
| 732 |
This provides a means of calling a different function, such as the |
| 733 |
"*" function, for a given target object that normally refers |
| 734 |
to a sub-function. |
| 735 |
|
| 736 |
""" |
| 737 |
dbname, driver = self._db_plus_driver_reg.match(drivername).group(1, 2) |
| 738 |
|
| 739 |
def go(*arg, **kw): |
| 740 |
return self._dispatch_on_db_driver(dbname, "*", arg, kw) |
| 741 |
|
| 742 |
return go |
| 743 |
|
| 744 |
def _dispatch_on(self, url, target, arg, kw): |
| 745 |
dbname, driver = self._db_plus_driver_reg.match( |
| 746 |
url.drivername).group(1, 2) |
| 747 |
if not driver: |
| 748 |
driver = url.get_dialect().driver |
| 749 |
|
| 750 |
return self._dispatch_on_db_driver(dbname, driver, arg, kw) |
| 751 |
|
| 752 |
def _invoke_fn(self, fn, arg, kw): |
| 753 |
return fn(*arg, **kw) |
| 754 |
|
| 755 |
|
| 756 |
class DialectSingleFunctionDispatcher(DialectFunctionDispatcher): |
| 757 |
def __init__(self): |
| 758 |
self.reg = collections.defaultdict(dict) |
| 759 |
|
| 760 |
def _register(self, expr, dbname, driver, fn): |
| 761 |
fn_dict = self.reg[dbname] |
| 762 |
if driver in fn_dict: |
| 763 |
raise TypeError("Multiple functions for expression %r" % expr) |
| 764 |
fn_dict[driver] = fn |
| 765 |
|
| 766 |
def _matches(self, dbname, driver): |
| 767 |
for db in (dbname, '*'): |
| 768 |
subdict = self.reg[db] |
| 769 |
for drv in (driver, '*'): |
| 770 |
if drv in subdict: |
| 771 |
return subdict[drv] |
| 772 |
else: |
| 773 |
raise ValueError( |
| 774 |
"No default function found for driver: %r" % |
| 775 |
(f"{dbname}+{driver}")) |
| 776 |
|
| 777 |
def _dispatch_on_db_driver(self, dbname, driver, arg, kw): |
| 778 |
fn = self._matches(dbname, driver) |
| 779 |
return self._invoke_fn(fn, arg, kw) |
| 780 |
|
| 781 |
|
| 782 |
class DialectMultiFunctionDispatcher(DialectFunctionDispatcher): |
| 783 |
def __init__(self): |
| 784 |
self.reg = collections.defaultdict( |
| 785 |
lambda: collections.defaultdict(list)) |
| 786 |
|
| 787 |
def _register(self, expr, dbname, driver, fn): |
| 788 |
self.reg[dbname][driver].append(fn) |
| 789 |
|
| 790 |
def _matches(self, dbname, driver): |
| 791 |
if driver != '*': |
| 792 |
drivers = (driver, '*') |
| 793 |
else: |
| 794 |
drivers = ('*', ) |
| 795 |
|
| 796 |
for db in (dbname, '*'): |
| 797 |
subdict = self.reg[db] |
| 798 |
for drv in drivers: |
| 799 |
yield from subdict[drv] |
| 800 |
|
| 801 |
def _dispatch_on_db_driver(self, dbname, driver, arg, kw): |
| 802 |
for fn in self._matches(dbname, driver): |
| 803 |
if self._invoke_fn(fn, arg, kw) is not None: |
| 804 |
raise TypeError( |
| 805 |
"Return value not allowed for " |
| 806 |
"multiple filtered function") |
| 807 |
|
| 808 |
|
| 809 |
dispatch_for_dialect = DialectFunctionDispatcher.dispatch_for_dialect |
| 810 |
|
| 811 |
|
| 812 |
def get_non_innodb_tables(connectable, skip_tables=('migrate_version', |
| 813 |
'alembic_version')): |
| 814 |
"""Get a list of tables which don't use InnoDB storage engine. |
| 815 |
|
| 816 |
:param connectable: a SQLAlchemy Engine or a Connection instance |
| 817 |
:param skip_tables: a list of tables which might have a different |
| 818 |
storage engine |
| 819 |
""" |
| 820 |
query_str = """ |
| 821 |
SELECT table_name |
| 822 |
FROM information_schema.tables |
| 823 |
WHERE table_schema = :database AND |
| 824 |
engine != 'InnoDB' |
| 825 |
""" |
| 826 |
|
| 827 |
params = {} |
| 828 |
if skip_tables: |
| 829 |
params = { |
| 830 |
'skip_%s' % i: table_name |
| 831 |
for i, table_name in enumerate(skip_tables) |
| 832 |
} |
| 833 |
|
| 834 |
placeholders = ', '.join(':' + p for p in params) |
| 835 |
query_str += ' AND table_name NOT IN (%s)' % placeholders |
| 836 |
|
| 837 |
params['database'] = connectable.engine.url.database |
| 838 |
query = text(query_str) |
| 839 |
|
| 840 |
with connectable.connect() as conn, conn.begin(): |
| 841 |
noninnodb = conn.execute(query, params) |
| 842 |
return [i[0] for i in noninnodb] |
| 843 |
|
| 844 |
|
| 845 |
def get_foreign_key_constraint_name(engine, table_name, column_name): |
| 846 |
"""Find the name of foreign key in a table, given constrained column name. |
| 847 |
|
| 848 |
:param engine: a SQLAlchemy engine (or connection) |
| 849 |
|
| 850 |
:param table_name: name of table which contains the constraint |
| 851 |
|
| 852 |
:param column_name: name of column that is constrained by the foreign key. |
| 853 |
|
| 854 |
:return: the name of the first foreign key constraint which constrains |
| 855 |
the given column in the given table. |
| 856 |
|
| 857 |
""" |
| 858 |
insp = inspect(engine) |
| 859 |
for fk in insp.get_foreign_keys(table_name): |
| 860 |
if column_name in fk['constrained_columns']: |
| 861 |
return fk['name'] |
| 862 |
|
| 863 |
|
| 864 |
def make_url(target): |
| 865 |
"""Return a ``url.URL`` object""" |
| 866 |
if isinstance(target, (str, sa_url.URL)): |
| 867 |
return sa_url.make_url(target) |
| 868 |
else: |
| 869 |
return sa_url.make_url(str(target)) |