| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
import copy |
| 14 |
|
| 15 |
from sqlalchemy import inspect |
| 16 |
from sqlalchemy import orm |
| 17 |
from sqlalchemy import sql |
| 18 |
from sqlalchemy import types as sqltypes |
| 19 |
|
| 20 |
from oslo_db.sqlalchemy import utils |
| 21 |
|
| 22 |
|
| 23 |
def update_on_match( |
| 24 |
query, |
| 25 |
specimen, |
| 26 |
surrogate_key, |
| 27 |
values=None, |
| 28 |
attempts=3, |
| 29 |
include_only=None, |
| 30 |
process_query=None, |
| 31 |
handle_failure=None |
| 32 |
): |
| 33 |
"""Emit an UPDATE statement matching the given specimen. |
| 34 |
|
| 35 |
E.g.:: |
| 36 |
|
| 37 |
with enginefacade.writer() as session: |
| 38 |
specimen = MyInstance( |
| 39 |
uuid='ccea54f', |
| 40 |
interface_id='ad33fea', |
| 41 |
vm_state='SOME_VM_STATE', |
| 42 |
) |
| 43 |
|
| 44 |
values = { |
| 45 |
'vm_state': 'SOME_NEW_VM_STATE' |
| 46 |
} |
| 47 |
|
| 48 |
base_query = model_query( |
| 49 |
context, models.Instance, |
| 50 |
project_only=True, session=session) |
| 51 |
|
| 52 |
hostname_query = model_query( |
| 53 |
context, models.Instance, session=session, |
| 54 |
read_deleted='no'). |
| 55 |
filter(func.lower(models.Instance.hostname) == 'SOMEHOSTNAME') |
| 56 |
|
| 57 |
surrogate_key = ('uuid', ) |
| 58 |
|
| 59 |
def process_query(query): |
| 60 |
return query.where(~exists(hostname_query)) |
| 61 |
|
| 62 |
def handle_failure(query): |
| 63 |
try: |
| 64 |
instance = base_query.one() |
| 65 |
except NoResultFound: |
| 66 |
raise exception.InstanceNotFound(instance_id=instance_uuid) |
| 67 |
|
| 68 |
if session.query(hostname_query.exists()).scalar(): |
| 69 |
raise exception.InstanceExists( |
| 70 |
name=values['hostname'].lower()) |
| 71 |
|
| 72 |
# try again |
| 73 |
return False |
| 74 |
|
| 75 |
persistent_instance = base_query.update_on_match( |
| 76 |
specimen, |
| 77 |
surrogate_key, |
| 78 |
values=values, |
| 79 |
process_query=process_query, |
| 80 |
handle_failure=handle_failure |
| 81 |
) |
| 82 |
|
| 83 |
The UPDATE statement is constructed against the given specimen |
| 84 |
using those values which are present to construct a WHERE clause. |
| 85 |
If the specimen contains additional values to be ignored, the |
| 86 |
``include_only`` parameter may be passed which indicates a sequence |
| 87 |
of attributes to use when constructing the WHERE. |
| 88 |
|
| 89 |
The UPDATE is performed against an ORM Query, which is created from |
| 90 |
the given ``Session``, or alternatively by passing the ```query`` |
| 91 |
parameter referring to an existing query. |
| 92 |
|
| 93 |
Before the query is invoked, it is also passed through the callable |
| 94 |
sent as ``process_query``, if present. This hook allows additional |
| 95 |
criteria to be added to the query after it is created but before |
| 96 |
invocation. |
| 97 |
|
| 98 |
The function will then invoke the UPDATE statement and check for |
| 99 |
"success" one or more times, up to a maximum of that passed as |
| 100 |
``attempts``. |
| 101 |
|
| 102 |
The initial check for "success" from the UPDATE statement is that the |
| 103 |
number of rows returned matches 1. If zero rows are matched, then |
| 104 |
the UPDATE statement is assumed to have "failed", and the failure handling |
| 105 |
phase begins. |
| 106 |
|
| 107 |
The failure handling phase involves invoking the given ``handle_failure`` |
| 108 |
function, if any. This handler can perform additional queries to attempt |
| 109 |
to figure out why the UPDATE didn't match any rows. The handler, |
| 110 |
upon detection of the exact failure condition, should throw an exception |
| 111 |
to exit; if it doesn't, it has the option of returning True or False, |
| 112 |
where False means the error was not handled, and True means that there |
| 113 |
was not in fact an error, and the function should return successfully. |
| 114 |
|
| 115 |
If the failure handler is not present, or returns False after ``attempts`` |
| 116 |
number of attempts, then the function overall raises CantUpdateException. |
| 117 |
If the handler returns True, then the function returns with no error. |
| 118 |
|
| 119 |
The return value of the function is a persistent version of the given |
| 120 |
specimen; this may be the specimen itself, if no matching object were |
| 121 |
already present in the session; otherwise, the existing object is |
| 122 |
returned, with the state of the specimen merged into it. The returned |
| 123 |
persistent object will have the given values populated into the object. |
| 124 |
|
| 125 |
The object is is returned as "persistent", meaning that it is |
| 126 |
associated with the given |
| 127 |
Session and has an identity key (that is, a real primary key |
| 128 |
value). |
| 129 |
|
| 130 |
In order to produce this identity key, a strategy must be used to |
| 131 |
determine it as efficiently and safely as possible: |
| 132 |
|
| 133 |
1. If the given specimen already contained its primary key attributes |
| 134 |
fully populated, then these attributes were used as criteria in the |
| 135 |
UPDATE, so we have the primary key value; it is populated directly. |
| 136 |
|
| 137 |
2. If the target backend supports RETURNING, then when the update() query |
| 138 |
is performed with a RETURNING clause so that the matching primary key |
| 139 |
is returned atomically. This currently includes Postgresql, Oracle |
| 140 |
and others (notably not MySQL or SQLite). |
| 141 |
|
| 142 |
3. If the target backend is MySQL, and the given model uses a |
| 143 |
single-column, AUTO_INCREMENT integer primary key value (as is |
| 144 |
the case for Nova), MySQL's recommended approach of making use |
| 145 |
of ``LAST_INSERT_ID(expr)`` is used to atomically acquire the |
| 146 |
matching primary key value within the scope of the UPDATE |
| 147 |
statement, then it fetched immediately following by using |
| 148 |
``SELECT LAST_INSERT_ID()``. |
| 149 |
http://dev.mysql.com/doc/refman/5.0/en/information-\ |
| 150 |
functions.html#function_last-insert-id |
| 151 |
|
| 152 |
4. Otherwise, for composite keys on MySQL or other backends such |
| 153 |
as SQLite, the row as UPDATED must be re-fetched in order to |
| 154 |
acquire the primary key value. The ``surrogate_key`` |
| 155 |
parameter is used for this in order to re-fetch the row; this |
| 156 |
is a column name with a known, unique value where |
| 157 |
the object can be fetched. |
| 158 |
|
| 159 |
|
| 160 |
""" |
| 161 |
|
| 162 |
if values is None: |
| 163 |
values = {} |
| 164 |
|
| 165 |
entity = inspect(specimen) |
| 166 |
mapper = entity.mapper |
| 167 |
if [desc['type'] for desc in query.column_descriptions] != \ |
| 168 |
[mapper.class_]: |
| 169 |
raise AssertionError("Query does not match given specimen") |
| 170 |
|
| 171 |
criteria = manufacture_entity_criteria( |
| 172 |
specimen, include_only=include_only, exclude=[surrogate_key]) |
| 173 |
|
| 174 |
query = query.filter(criteria) |
| 175 |
|
| 176 |
if process_query: |
| 177 |
query = process_query(query) |
| 178 |
|
| 179 |
surrogate_key_arg = ( |
| 180 |
surrogate_key, entity.attrs[surrogate_key].loaded_value) |
| 181 |
pk_value = None |
| 182 |
|
| 183 |
for attempt in range(attempts): |
| 184 |
try: |
| 185 |
pk_value = query.update_returning_pk(values, surrogate_key_arg) |
| 186 |
except MultiRowsMatched: |
| 187 |
raise |
| 188 |
except NoRowsMatched: |
| 189 |
if handle_failure and handle_failure(query): |
| 190 |
break |
| 191 |
else: |
| 192 |
break |
| 193 |
else: |
| 194 |
raise NoRowsMatched("Zero rows matched for %d attempts" % attempts) |
| 195 |
|
| 196 |
if pk_value is None: |
| 197 |
pk_value = entity.mapper.primary_key_from_instance(specimen) |
| 198 |
|
| 199 |
|
| 200 |
|
| 201 |
values = copy.copy(values) |
| 202 |
values[surrogate_key] = surrogate_key_arg[1] |
| 203 |
persistent_obj = manufacture_persistent_object( |
| 204 |
query.session, specimen.__class__(), values, pk_value) |
| 205 |
|
| 206 |
return persistent_obj |
| 207 |
|
| 208 |
|
| 209 |
def manufacture_persistent_object( |
| 210 |
session, specimen, values=None, primary_key=None): |
| 211 |
"""Make an ORM-mapped object persistent in a Session without SQL. |
| 212 |
|
| 213 |
The persistent object is returned. |
| 214 |
|
| 215 |
If a matching object is already present in the given session, the specimen |
| 216 |
is merged into it and the persistent object returned. Otherwise, the |
| 217 |
specimen itself is made persistent and is returned. |
| 218 |
|
| 219 |
The object must contain a full primary key, or provide it via the values or |
| 220 |
primary_key parameters. The object is peristed to the Session in a "clean" |
| 221 |
state with no pending changes. |
| 222 |
|
| 223 |
:param session: A Session object. |
| 224 |
|
| 225 |
:param specimen: a mapped object which is typically transient. |
| 226 |
|
| 227 |
:param values: a dictionary of values to be applied to the specimen, |
| 228 |
in addition to the state that's already on it. The attributes will be |
| 229 |
set such that no history is created; the object remains clean. |
| 230 |
|
| 231 |
:param primary_key: optional tuple-based primary key. This will also |
| 232 |
be applied to the instance if present. |
| 233 |
|
| 234 |
|
| 235 |
""" |
| 236 |
state = inspect(specimen) |
| 237 |
mapper = state.mapper |
| 238 |
|
| 239 |
for k, v in values.items(): |
| 240 |
orm.attributes.set_committed_value(specimen, k, v) |
| 241 |
|
| 242 |
pk_attrs = [ |
| 243 |
mapper.get_property_by_column(col).key |
| 244 |
for col in mapper.primary_key |
| 245 |
] |
| 246 |
|
| 247 |
if primary_key is not None: |
| 248 |
for key, value in zip(pk_attrs, primary_key): |
| 249 |
orm.attributes.set_committed_value( |
| 250 |
specimen, |
| 251 |
key, |
| 252 |
value |
| 253 |
) |
| 254 |
|
| 255 |
for key in pk_attrs: |
| 256 |
if state.attrs[key].loaded_value is orm.attributes.NO_VALUE: |
| 257 |
raise ValueError("full primary key must be present") |
| 258 |
|
| 259 |
orm.make_transient_to_detached(specimen) |
| 260 |
|
| 261 |
if state.key not in session.identity_map: |
| 262 |
session.add(specimen) |
| 263 |
return specimen |
| 264 |
else: |
| 265 |
return session.merge(specimen, load=False) |
| 266 |
|
| 267 |
|
| 268 |
def manufacture_entity_criteria(entity, include_only=None, exclude=None): |
| 269 |
"""Given a mapped instance, produce a WHERE clause. |
| 270 |
|
| 271 |
The attributes set upon the instance will be combined to produce |
| 272 |
a SQL expression using the mapped SQL expressions as the base |
| 273 |
of comparison. |
| 274 |
|
| 275 |
Values on the instance may be set as tuples in which case the |
| 276 |
criteria will produce an IN clause. None is also acceptable as a |
| 277 |
scalar or tuple entry, which will produce IS NULL that is properly |
| 278 |
joined with an OR against an IN expression if appropriate. |
| 279 |
|
| 280 |
:param entity: a mapped entity. |
| 281 |
|
| 282 |
:param include_only: optional sequence of keys to limit which |
| 283 |
keys are included. |
| 284 |
|
| 285 |
:param exclude: sequence of keys to exclude |
| 286 |
|
| 287 |
""" |
| 288 |
|
| 289 |
state = inspect(entity) |
| 290 |
exclude = set(exclude) if exclude is not None else set() |
| 291 |
|
| 292 |
existing = { |
| 293 |
attr.key: attr.loaded_value |
| 294 |
for attr in state.attrs |
| 295 |
if attr.loaded_value is not orm.attributes.NO_VALUE and |
| 296 |
attr.key not in exclude |
| 297 |
} |
| 298 |
if include_only: |
| 299 |
existing = { |
| 300 |
k: existing[k] |
| 301 |
for k in set(existing).intersection(include_only) |
| 302 |
} |
| 303 |
|
| 304 |
return manufacture_criteria(state.mapper, existing) |
| 305 |
|
| 306 |
|
| 307 |
def manufacture_criteria(mapped, values): |
| 308 |
"""Given a mapper/class and a namespace of values, produce a WHERE clause. |
| 309 |
|
| 310 |
The class should be a mapped class and the entries in the dictionary |
| 311 |
correspond to mapped attribute names on the class. |
| 312 |
|
| 313 |
A value may also be a tuple in which case that particular attribute |
| 314 |
will be compared to a tuple using IN. The scalar value or |
| 315 |
tuple can also contain None which translates to an IS NULL, that is |
| 316 |
properly joined with OR against an IN expression if appropriate. |
| 317 |
|
| 318 |
:param cls: a mapped class, or actual :class:`.Mapper` object. |
| 319 |
|
| 320 |
:param values: dictionary of values. |
| 321 |
|
| 322 |
""" |
| 323 |
|
| 324 |
mapper = inspect(mapped) |
| 325 |
|
| 326 |
|
| 327 |
value_keys = set(values) |
| 328 |
keys = [k for k in mapper.column_attrs.keys() if k in value_keys] |
| 329 |
return sql.and_(*[ |
| 330 |
_sql_crit(mapper.column_attrs[key].expression, values[key]) |
| 331 |
for key in keys |
| 332 |
]) |
| 333 |
|
| 334 |
|
| 335 |
def _sql_crit(expression, value): |
| 336 |
"""Produce an equality expression against the given value. |
| 337 |
|
| 338 |
This takes into account a value that is actually a collection |
| 339 |
of values, as well as a value of None or collection that contains |
| 340 |
None. |
| 341 |
|
| 342 |
""" |
| 343 |
|
| 344 |
values = utils.to_list(value, default=(None, )) |
| 345 |
if len(values) == 1: |
| 346 |
if values[0] is None: |
| 347 |
return expression == sql.null() |
| 348 |
else: |
| 349 |
return expression == values[0] |
| 350 |
elif _none_set.intersection(values): |
| 351 |
return sql.or_( |
| 352 |
expression == sql.null(), |
| 353 |
_sql_crit(expression, set(values).difference(_none_set)) |
| 354 |
) |
| 355 |
else: |
| 356 |
return expression.in_(values) |
| 357 |
|
| 358 |
|
| 359 |
def update_returning_pk(query, values, surrogate_key): |
| 360 |
"""Perform an UPDATE, returning the primary key of the matched row. |
| 361 |
|
| 362 |
The primary key is returned using a selection of strategies: |
| 363 |
|
| 364 |
* if the database supports RETURNING, RETURNING is used to retrieve |
| 365 |
the primary key values inline. |
| 366 |
|
| 367 |
* If the database is MySQL and the entity is mapped to a single integer |
| 368 |
primary key column, MySQL's last_insert_id() function is used |
| 369 |
inline within the UPDATE and then upon a second SELECT to get the |
| 370 |
value. |
| 371 |
|
| 372 |
* Otherwise, a "refetch" strategy is used, where a given "surrogate" |
| 373 |
key value (typically a UUID column on the entity) is used to run |
| 374 |
a new SELECT against that UUID. This UUID is also placed into |
| 375 |
the UPDATE query to ensure the row matches. |
| 376 |
|
| 377 |
:param query: a Query object with existing criterion, against a single |
| 378 |
entity. |
| 379 |
|
| 380 |
:param values: a dictionary of values to be updated on the row. |
| 381 |
|
| 382 |
:param surrogate_key: a tuple of (attrname, value), referring to a |
| 383 |
UNIQUE attribute that will also match the row. This attribute is used |
| 384 |
to retrieve the row via a SELECT when no optimized strategy exists. |
| 385 |
|
| 386 |
:return: the primary key, returned as a tuple. |
| 387 |
Is only returned if rows matched is one. Otherwise, CantUpdateException |
| 388 |
is raised. |
| 389 |
|
| 390 |
""" |
| 391 |
|
| 392 |
entity = query.column_descriptions[0]['type'] |
| 393 |
mapper = inspect(entity).mapper |
| 394 |
session = query.session |
| 395 |
|
| 396 |
bind = session.connection(bind_arguments=dict(mapper=mapper)) |
| 397 |
if bind.dialect.name == "postgresql": |
| 398 |
pk_strategy = _pk_strategy_returning |
| 399 |
elif bind.dialect.name == 'mysql' and \ |
| 400 |
len(mapper.primary_key) == 1 and \ |
| 401 |
isinstance( |
| 402 |
mapper.primary_key[0].type, sqltypes.Integer): |
| 403 |
pk_strategy = _pk_strategy_mysql_last_insert_id |
| 404 |
else: |
| 405 |
pk_strategy = _pk_strategy_refetch |
| 406 |
|
| 407 |
return pk_strategy(query, mapper, values, surrogate_key) |
| 408 |
|
| 409 |
|
| 410 |
def _assert_single_row(rows_updated): |
| 411 |
if rows_updated == 1: |
| 412 |
return rows_updated |
| 413 |
elif rows_updated > 1: |
| 414 |
raise MultiRowsMatched("%d rows matched; expected one" % rows_updated) |
| 415 |
else: |
| 416 |
raise NoRowsMatched("No rows matched the UPDATE") |
| 417 |
|
| 418 |
|
| 419 |
def _pk_strategy_refetch(query, mapper, values, surrogate_key): |
| 420 |
|
| 421 |
surrogate_key_name, surrogate_key_value = surrogate_key |
| 422 |
surrogate_key_col = mapper.attrs[surrogate_key_name].expression |
| 423 |
|
| 424 |
rowcount = query.\ |
| 425 |
filter(surrogate_key_col == surrogate_key_value).\ |
| 426 |
update(values, synchronize_session=False) |
| 427 |
|
| 428 |
_assert_single_row(rowcount) |
| 429 |
|
| 430 |
|
| 431 |
|
| 432 |
fetch_query = query.session.query( |
| 433 |
*mapper.primary_key).filter( |
| 434 |
surrogate_key_col == surrogate_key_value) |
| 435 |
|
| 436 |
primary_key = fetch_query.one() |
| 437 |
|
| 438 |
return primary_key |
| 439 |
|
| 440 |
|
| 441 |
def _pk_strategy_returning(query, mapper, values, surrogate_key): |
| 442 |
surrogate_key_name, surrogate_key_value = surrogate_key |
| 443 |
surrogate_key_col = mapper.attrs[surrogate_key_name].expression |
| 444 |
|
| 445 |
update_stmt = _update_stmt_from_query(mapper, query, values) |
| 446 |
update_stmt = update_stmt.where(surrogate_key_col == surrogate_key_value) |
| 447 |
update_stmt = update_stmt.returning(*mapper.primary_key) |
| 448 |
|
| 449 |
|
| 450 |
|
| 451 |
result = query.session.execute(update_stmt) |
| 452 |
rowcount = result.rowcount |
| 453 |
_assert_single_row(rowcount) |
| 454 |
primary_key = tuple(result.first()) |
| 455 |
|
| 456 |
return primary_key |
| 457 |
|
| 458 |
|
| 459 |
def _pk_strategy_mysql_last_insert_id(query, mapper, values, surrogate_key): |
| 460 |
|
| 461 |
surrogate_key_name, surrogate_key_value = surrogate_key |
| 462 |
surrogate_key_col = mapper.attrs[surrogate_key_name].expression |
| 463 |
|
| 464 |
surrogate_pk_col = mapper.primary_key[0] |
| 465 |
update_stmt = _update_stmt_from_query(mapper, query, values) |
| 466 |
update_stmt = update_stmt.where(surrogate_key_col == surrogate_key_value) |
| 467 |
update_stmt = update_stmt.values( |
| 468 |
{surrogate_pk_col: sql.func.last_insert_id(surrogate_pk_col)}) |
| 469 |
|
| 470 |
|
| 471 |
|
| 472 |
result = query.session.execute(update_stmt) |
| 473 |
rowcount = result.rowcount |
| 474 |
_assert_single_row(rowcount) |
| 475 |
|
| 476 |
primary_key = query.session.scalar(sql.func.last_insert_id()), |
| 477 |
|
| 478 |
return primary_key |
| 479 |
|
| 480 |
|
| 481 |
def _update_stmt_from_query(mapper, query, values): |
| 482 |
upd_values = { |
| 483 |
mapper.column_attrs[key]: value for key, value in values.items() |
| 484 |
} |
| 485 |
primary_table = inspect(query.column_descriptions[0]['entity']).local_table |
| 486 |
where_criteria = query.whereclause |
| 487 |
update_stmt = sql.update( |
| 488 |
primary_table, |
| 489 |
).where( |
| 490 |
where_criteria, |
| 491 |
).values(upd_values) |
| 492 |
return update_stmt |
| 493 |
|
| 494 |
|
| 495 |
_none_set = frozenset([None]) |
| 496 |
|
| 497 |
|
| 498 |
class CantUpdateException(Exception): |
| 499 |
pass |
| 500 |
|
| 501 |
|
| 502 |
class NoRowsMatched(CantUpdateException): |
| 503 |
pass |
| 504 |
|
| 505 |
|
| 506 |
class MultiRowsMatched(CantUpdateException): |
| 507 |
pass |