Debian Codegraph @

oslo_db/sqlalchemy/exc_filters.py

raw symbols SCIP
1 # Licensed under the Apache License, Version 2.0 (the "License"); you may
2 # not use this file except in compliance with the License. You may obtain
3 # a copy of the License at
4 #
5 # http://www.apache.org/licenses/LICENSE-2.0
6 #
7 # Unless required by applicable law or agreed to in writing, software
8 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
9 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
10 # License for the specific language governing permissions and limitations
11 # under the License.
12 """Define exception redefinitions for SQLAlchemy DBAPI exceptions."""
13
14 import collections
15 import logging
16 import re
17 import sys
18
19 from sqlalchemy import event
20 from sqlalchemy import exc as sqla_exc
21
22 from oslo_db import exception
23
24 LOG = logging.getLogger(__name__)
25
26
27 _registry = collections.defaultdict(
28 lambda: collections.defaultdict(
29 list
30 )
31 )
32
33
34 def filters(dbname, exception_type, regex):
35 """Mark a function as receiving a filtered exception.
36
37 :param dbname: string database name, e.g. 'mysql'
38 :param exception_type: a SQLAlchemy database exception class, which
39 extends from :class:`sqlalchemy.exc.DBAPIError`.
40 :param regex: a string, or a tuple of strings, that will be processed
41 as matching regular expressions.
42
43 """
44 def _receive(fn):
45 _registry[dbname][exception_type].extend(
46 (fn, re.compile(reg, re.DOTALL))
47 for reg in
48 ((regex,) if not isinstance(regex, tuple) else regex)
49 )
50 return fn
51 return _receive
52
53
54 # NOTE(zzzeek) - for Postgresql, catch both OperationalError, as the
55 # actual error is
56 # psycopg2.extensions.TransactionRollbackError(OperationalError),
57 # as well as sqlalchemy.exc.DBAPIError, as SQLAlchemy will reraise it
58 # as this until issue #3075 is fixed.
59 @filters("mysql", sqla_exc.OperationalError, r"^.*\b1213\b.*Deadlock found.*")
60 @filters("mysql", sqla_exc.DatabaseError,
61 r"^.*\b1205\b.*Lock wait timeout exceeded.*")
62 @filters("mysql", sqla_exc.InternalError, r"^.*\b1213\b.*Deadlock found.*")
63 @filters("mysql", sqla_exc.InternalError,
64 r"^.*\b1213\b.*detected deadlock/conflict.*")
65 @filters("mysql", sqla_exc.InternalError,
66 r"^.*\b1213\b.*Deadlock: wsrep aborted.*")
67 @filters("mysql", sqla_exc.OperationalError,
68 r"^.*\b1213\b.*Deadlock: wsrep aborted.*")
69 @filters("postgresql", sqla_exc.OperationalError, r"^.*deadlock detected.*")
70 @filters("postgresql", sqla_exc.DBAPIError, r"^.*deadlock detected.*")
71 def _deadlock_error(operational_error, match, engine_name, is_disconnect):
72 """Filter for MySQL or Postgresql deadlock error.
73
74 NOTE(comstud): In current versions of DB backends, Deadlock violation
75 messages follow the structure:
76
77 mysql+mysqldb::
78
79 (OperationalError) (1213, 'Deadlock found when trying to get lock; '
80 'try restarting transaction') <query_str> <query_args>
81
82 mysql+mysqlconnector::
83
84 (InternalError) 1213 (40001): Deadlock found when trying to get lock;
85 try restarting transaction
86
87 postgresql::
88
89 (TransactionRollbackError) deadlock detected <deadlock_details>
90 """
91 raise exception.DBDeadlock(operational_error)
92
93
94 @filters("mysql", sqla_exc.OperationalError,
95 r"^.*\b1020\b.*Record has changed since last read.*")
96 def _mariadb_consistency_error(operational_error, match, engine_name,
97 is_disconnect):
98 """Filter for MariaDB consistency error.
99
100 MariaDB under REPEATABLE-READ isolation level can raise error 1020
101 when it detects that a row has changed since it was last read in the
102 current transaction. This is part of MariaDB's transaction validation
103 model and typically indicates a transient condition that can be resolved
104 by retrying the transaction.
105
106 Example error message:
107 (OperationalError) (pymysql.err.OperationalError) (1020,
108 "Record has changed since last read in table 'table_name'")
109 """
110 raise exception.DBConsistencyError(operational_error)
111
112
113 @filters("mysql", sqla_exc.IntegrityError,
114 r"^.*\b1062\b.*Duplicate entry '(?P<value>.*)'"
115 r" for key '(?P<columns>[^']+)'.*$")
116 # NOTE(jd) For binary types
117 @filters("mysql", sqla_exc.IntegrityError,
118 r"^.*\b1062\b.*Duplicate entry \\'(?P<value>.*)\\'"
119 r" for key \\'(?P<columns>.+)\\'.*$")
120 # NOTE(pkholkin): the first regex is suitable only for PostgreSQL 9.x versions
121 # the second regex is suitable for PostgreSQL 8.x versions
122 @filters("postgresql", sqla_exc.IntegrityError,
123 (r'^.*duplicate\s+key.*"(?P<columns>[^"]+)"\s*\n.*'
124 r'Key\s+\((?P<key>.*)\)=\((?P<value>.*)\)\s+already\s+exists.*$',
125 r"^.*duplicate\s+key.*\"(?P<columns>[^\"]+)\"\s*\n.*$"))
126 def _default_dupe_key_error(integrity_error, match, engine_name,
127 is_disconnect):
128 """Filter for MySQL or Postgresql duplicate key error.
129
130 note(boris-42): In current versions of DB backends unique constraint
131 violation messages follow the structure:
132
133 postgres:
134 1 column - (IntegrityError) duplicate key value violates unique
135 constraint "users_c1_key"
136 N columns - (IntegrityError) duplicate key value violates unique
137 constraint "name_of_our_constraint"
138
139 mysql since 8.0.19:
140 1 column - (IntegrityError) (1062, "Duplicate entry 'value_of_c1' for key
141 'table_name.c1'")
142 N columns - (IntegrityError) (1062, "Duplicate entry 'values joined
143 with -' for key 'table_name.name_of_our_constraint'")
144
145 mysql+mysqldb:
146 1 column - (IntegrityError) (1062, "Duplicate entry 'value_of_c1' for key
147 'c1'")
148 N columns - (IntegrityError) (1062, "Duplicate entry 'values joined
149 with -' for key 'name_of_our_constraint'")
150
151 mysql+mysqlconnector:
152 1 column - (IntegrityError) 1062 (23000): Duplicate entry 'value_of_c1' for
153 key 'c1'
154 N columns - (IntegrityError) 1062 (23000): Duplicate entry 'values
155 joined with -' for key 'name_of_our_constraint'
156 """
157
158 columns = match.group('columns')
159
160 # note(vsergeyev): UniqueConstraint name convention: "uniq_t0c10c2"
161 # where `t` it is table name and columns `c1`, `c2`
162 # are in UniqueConstraint.
163 uniqbase = "uniq_"
164 if not columns.startswith(uniqbase):
165 if engine_name == "postgresql":
166 columns = [columns[columns.index("_") + 1:columns.rindex("_")]]
167 elif (engine_name == "mysql") and \
168 (uniqbase in str(columns.split("0")[:1])):
169 columns = columns.split("0")[1:]
170 else:
171 columns = [columns]
172 else:
173 columns = columns[len(uniqbase):].split("0")[1:]
174
175 value = match.groupdict().get('value')
176
177 raise exception.DBDuplicateEntry(columns, integrity_error, value)
178
179
180 @filters("sqlite", sqla_exc.IntegrityError,
181 (r"^.*columns?(?P<columns>[^)]+)(is|are)\s+not\s+unique$",
182 r"^.*UNIQUE\s+constraint\s+failed:\s+(?P<columns>.+)$",
183 r"^.*PRIMARY\s+KEY\s+must\s+be\s+unique.*$"))
184 def _sqlite_dupe_key_error(integrity_error, match, engine_name, is_disconnect):
185 """Filter for SQLite duplicate key error.
186
187 note(boris-42): In current versions of DB backends unique constraint
188 violation messages follow the structure:
189
190 sqlite:
191 1 column - (IntegrityError) column c1 is not unique
192 N columns - (IntegrityError) column c1, c2, ..., N are not unique
193
194 sqlite since 3.7.16:
195 1 column - (IntegrityError) UNIQUE constraint failed: tbl.k1
196 N columns - (IntegrityError) UNIQUE constraint failed: tbl.k1, tbl.k2
197
198 sqlite since 3.8.2:
199 (IntegrityError) PRIMARY KEY must be unique
200 """
201 columns = []
202 # NOTE(ochuprykov): We can get here by last filter in which there are no
203 # groups. Trying to access the substring that matched by
204 # the group will lead to IndexError. In this case just
205 # pass empty list to exception.DBDuplicateEntry
206 try:
207 columns = match.group('columns')
208 columns = [c.split('.')[-1] for c in columns.strip().split(", ")]
209 except IndexError:
210 pass
211
212 raise exception.DBDuplicateEntry(columns, integrity_error)
213
214
215 @filters("sqlite", sqla_exc.IntegrityError,
216 r"(?i).*foreign key constraint failed")
217 @filters("postgresql", sqla_exc.IntegrityError,
218 r".*on table \"(?P<table>[^\"]+)\" violates "
219 r"foreign key constraint \"(?P<constraint>[^\"]+)\".*\n"
220 r"DETAIL: Key \((?P<key>.+)\)=\(.+\) "
221 r"is (not present in|still referenced from) table "
222 r"\"(?P<key_table>[^\"]+)\".")
223 @filters(
224 "mysql", sqla_exc.IntegrityError,
225 r".*Cannot (add|delete) or update a (child|parent) row: "
226 r'a foreign key constraint fails \([`"].+[`"]\.[`"](?P<table>.+)[`"], '
227 r'CONSTRAINT [`"](?P<constraint>.+)[`"] FOREIGN KEY '
228 r'\([`"](?P<key>.+)[`"]\) REFERENCES [`"](?P<key_table>.+)[`"] ')
229 def _foreign_key_error(integrity_error, match, engine_name, is_disconnect):
230 """Filter for foreign key errors."""
231
232 try:
233 table = match.group("table")
234 except IndexError:
235 table = None
236 try:
237 constraint = match.group("constraint")
238 except IndexError:
239 constraint = None
240 try:
241 key = match.group("key")
242 except IndexError:
243 key = None
244 try:
245 key_table = match.group("key_table")
246 except IndexError:
247 key_table = None
248
249 raise exception.DBReferenceError(table, constraint, key, key_table,
250 integrity_error)
251
252
253 @filters("postgresql", sqla_exc.IntegrityError,
254 r".*new row for relation \"(?P<table>.+)\" "
255 "violates check constraint "
256 "\"(?P<check_name>.+)\"")
257 def _check_constraint_error(
258 integrity_error, match, engine_name, is_disconnect):
259 """Filter for check constraint errors."""
260
261 try:
262 table = match.group("table")
263 except IndexError:
264 table = None
265 try:
266 check_name = match.group("check_name")
267 except IndexError:
268 check_name = None
269
270 raise exception.DBConstraintError(table, check_name, integrity_error)
271
272
273 @filters("postgresql", sqla_exc.ProgrammingError,
274 r".* constraint \"(?P<constraint>.+)\" "
275 "of relation "
276 "\"(?P<relation>.+)\" does not exist")
277 @filters("mysql", sqla_exc.InternalError,
278 r".*1091,.*Can't DROP (?:FOREIGN KEY )?['`](?P<constraint>.+)['`]; "
279 "check that .* exists")
280 @filters("mysql", sqla_exc.OperationalError,
281 r".*1091,.*Can't DROP (?:FOREIGN KEY )?['`](?P<constraint>.+)['`]; "
282 "check that .* exists")
283 @filters("mysql", sqla_exc.InternalError,
284 r".*1025,.*Error on rename of '.+/(?P<relation>.+)' to ")
285 def _check_constraint_non_existing(
286 programming_error, match, engine_name, is_disconnect):
287 """Filter for constraint non existing errors."""
288
289 try:
290 relation = match.group("relation")
291 except IndexError:
292 relation = None
293
294 try:
295 constraint = match.group("constraint")
296 except IndexError:
297 constraint = None
298
299 raise exception.DBNonExistentConstraint(relation,
300 constraint,
301 programming_error)
302
303
304 @filters("sqlite", sqla_exc.OperationalError,
305 r".* no such table: (?P<table>.+)")
306 @filters("mysql", sqla_exc.InternalError,
307 r".*1051,.*Unknown table '(.+\.)?(?P<table>.+)'\"")
308 @filters("mysql", sqla_exc.OperationalError,
309 r".*1051,.*Unknown table '(.+\.)?(?P<table>.+)'\"")
310 @filters("postgresql", sqla_exc.ProgrammingError,
311 r".* table \"(?P<table>.+)\" does not exist")
312 def _check_table_non_existing(
313 programming_error, match, engine_name, is_disconnect):
314 """Filter for table non existing errors."""
315 raise exception.DBNonExistentTable(match.group("table"), programming_error)
316
317
318 @filters("mysql", sqla_exc.InternalError,
319 r".*1049,.*Unknown database '(?P<database>.+)'\"")
320 @filters("mysql", sqla_exc.OperationalError,
321 r".*1049,.*Unknown database '(?P<database>.+)'\"")
322 @filters("postgresql", sqla_exc.OperationalError,
323 r".*database \"(?P<database>.+)\" does not exist")
324 @filters("sqlite", sqla_exc.OperationalError,
325 ".*unable to open database file.*")
326 def _check_database_non_existing(
327 error, match, engine_name, is_disconnect):
328 try:
329 database = match.group("database")
330 except IndexError:
331 database = None
332
333 raise exception.DBNonExistentDatabase(database, error)
334
335
336 @filters("mysql", sqla_exc.DBAPIError, r".*\b1146\b")
337 def _raise_mysql_table_doesnt_exist_asis(
338 error, match, engine_name, is_disconnect):
339 """Raise MySQL error 1146 as is.
340
341 Raise MySQL error 1146 as is, so that it does not conflict with
342 the MySQL dialect's checking a table not existing.
343 """
344
345 raise error
346
347
348 @filters("mysql", sqla_exc.OperationalError,
349 r".*(1292|1366).*Incorrect \w+ value.*")
350 @filters("mysql", sqla_exc.DataError,
351 r".*1265.*Data truncated for column.*")
352 @filters("mysql", sqla_exc.DataError,
353 r".*1264.*Out of range value for column.*")
354 @filters("mysql", sqla_exc.InternalError,
355 r"^.*1366.*Incorrect string value:*")
356 @filters("sqlite", sqla_exc.ProgrammingError,
357 r"(?i).*You must not use 8-bit bytestrings*")
358 @filters("mysql", sqla_exc.DataError,
359 r".*1406.*Data too long for column.*")
360 def _raise_data_error(error, match, engine_name, is_disconnect):
361 """Raise DBDataError exception for different data errors."""
362
363 raise exception.DBDataError(error)
364
365
366 @filters("mysql", sqla_exc.OperationalError,
367 r".*\(1305,\s+\'SAVEPOINT\s+(.+)\s+does not exist\'\)")
368 def _raise_savepoints_as_dberrors(error, match, engine_name, is_disconnect):
369 # NOTE(rpodolyaka): this is a special case of an OperationalError that used
370 # to be an InternalError. It's expected to be wrapped into oslo.db error.
371 raise exception.DBError(error)
372
373
374 @filters("*", sqla_exc.OperationalError, r".*")
375 def _raise_operational_errors_directly_filter(operational_error,
376 match, engine_name,
377 is_disconnect):
378 """Filter for all remaining OperationalError classes and apply.
379
380 Filter for all remaining OperationalError classes and apply
381 special rules.
382 """
383 if is_disconnect:
384 # operational errors that represent disconnect
385 # should be wrapped
386 raise exception.DBConnectionError(operational_error)
387 else:
388 # NOTE(comstud): A lot of code is checking for OperationalError
389 # so let's not wrap it for now.
390 raise operational_error
391
392
393 @filters("mysql", sqla_exc.OperationalError, r".*\(.*(?:2002|2003|2006|2013|1047)") # noqa
394 @filters("mysql", sqla_exc.InternalError, r".*\(.*(?:1927)") # noqa
395 @filters("mysql", sqla_exc.InternalError, r".*Packet sequence number wrong") # noqa
396 @filters("postgresql", sqla_exc.OperationalError, r".*could not connect to server") # noqa
397 def _is_db_connection_error(operational_error, match, engine_name,
398 is_disconnect):
399 """Detect the exception as indicating a recoverable error on connect."""
400
401 raise exception.DBConnectionError(operational_error)
402
403
404 @filters("*", sqla_exc.NotSupportedError, r".*")
405 def _raise_for_NotSupportedError(error, match, engine_name, is_disconnect):
406 raise exception.DBNotSupportedError(error)
407
408
409 @filters("*", sqla_exc.DBAPIError, r".*")
410 def _raise_for_remaining_DBAPIError(error, match, engine_name, is_disconnect):
411 """Filter for remaining DBAPIErrors.
412
413 Filter for remaining DBAPIErrors and wrap if they represent
414 a disconnect error.
415 """
416 if is_disconnect:
417 raise exception.DBConnectionError(error)
418 else:
419 LOG.warning('DBAPIError exception wrapped.', exc_info=True)
420 raise exception.DBError(error)
421
422
423 @filters('*', UnicodeEncodeError, r".*")
424 def _raise_for_unicode_encode(error, match, engine_name, is_disconnect):
425 raise exception.DBInvalidUnicodeParameter()
426
427
428 @filters("*", Exception, r".*")
429 def _raise_for_all_others(error, match, engine_name, is_disconnect):
430 LOG.warning('DB exception wrapped.', exc_info=True)
431 raise exception.DBError(error)
432
433
434 ROLLBACK_CAUSE_KEY = 'oslo.db.sp_rollback_cause'
435
436
437 def handler(context):
438 """Iterate through available filters and invoke those which match.
439
440 The first one which raises wins. The order in which the filters
441 are attempted is sorted by specificity - dialect name or "*",
442 exception class per method resolution order (``__mro__``).
443 Method resolution order is used so that filter rules indicating a
444 more specific exception class are attempted first.
445
446 """
447 def _dialect_registries(dialect):
448 if dialect.name in _registry:
449 yield _registry[dialect.name]
450 if '*' in _registry:
451 yield _registry['*']
452
453 # do not reraise for our own exceptions
454 # https://github.com/sqlalchemy/sqlalchemy/issues/10116
455 if isinstance(context.original_exception, exception.DBError):
456 return
457
458 for per_dialect in _dialect_registries(context.dialect):
459 for exc in (context.sqlalchemy_exception, context.original_exception):
460 for super_ in exc.__class__.__mro__:
461 if super_ not in per_dialect:
462 continue
463
464 regexp_reg = per_dialect[super_]
465 for fn, regexp in regexp_reg:
466 match = regexp.match(exc.args[0])
467 if not match:
468 continue
469
470 try:
471 fn(
472 exc,
473 match,
474 context.dialect.name,
475 context.is_disconnect,
476 )
477 except exception.DBError as dbe:
478 if (
479 context.connection is not None and
480 not context.connection.closed and
481 not context.connection.invalidated and
482 ROLLBACK_CAUSE_KEY in context.connection.info
483 ):
484 dbe.cause = context.connection.info.pop(
485 ROLLBACK_CAUSE_KEY,
486 )
487
488 if isinstance(dbe, exception.DBConnectionError):
489 context.is_disconnect = True
490
491 # new in 2.0.5
492 if (
493 hasattr(context, "is_pre_ping") and
494 context.is_pre_ping
495 ):
496 # if this is a pre-ping, need to
497 # integrate with the built
498 # in pre-ping handler that doesnt know
499 # about DBConnectionError, just needs
500 # the updated status
501 return None
502
503 return dbe
504
505
506 def register_engine(engine):
507 event.listen(engine, "handle_error", handler, retval=True)
508
509 @event.listens_for(engine, "rollback_savepoint")
510 def rollback_savepoint(conn, name, context):
511 exc_info = sys.exc_info()
512 if exc_info[1]:
513 # NOTE(zzzeek) accessing conn.info on an invalidated
514 # connection causes it to reconnect, which we don't
515 # want to do inside a rollback handler
516 if not conn.invalidated:
517 conn.info[ROLLBACK_CAUSE_KEY] = exc_info[1]
518 # NOTE(zzzeek) this eliminates a reference cycle between tracebacks
519 # that would occur in Python 3 only, which has been shown to occur if
520 # this function were in fact part of the traceback. That's not the
521 # case here however this is left as a defensive measure.
522 del exc_info
523
524 # try to clear the "cause" ASAP outside of savepoints,
525 # by grabbing the end of transaction events...
526 @event.listens_for(engine, "rollback")
527 @event.listens_for(engine, "commit")
528 def pop_exc_tx(conn):
529 # NOTE(zzzeek) accessing conn.info on an invalidated
530 # connection causes it to reconnect, which we don't
531 # want to do inside a rollback handler
532 if not conn.invalidated:
533 conn.info.pop(ROLLBACK_CAUSE_KEY, None)
534
535 # .. as well as connection pool checkin (just in case).
536 # the .info dictionary lasts as long as the DBAPI connection itself
537 # and is cleared out when the connection is recycled or closed
538 # due to invalidate etc.
539 @event.listens_for(engine, "checkin")
540 def pop_exc_checkin(dbapi_conn, connection_record):
541 connection_record.info.pop(ROLLBACK_CAUSE_KEY, None)