Skip to content

Instantly share code, notes, and snippets.

@mrvaldes
Created November 14, 2018 07:38
Show Gist options
  • Save mrvaldes/6a6f286e1a48f00a0d5d143ed65ff880 to your computer and use it in GitHub Desktop.
Save mrvaldes/6a6f286e1a48f00a0d5d143ed65ff880 to your computer and use it in GitHub Desktop.
MySQL 8.0 SQLAlchemy suffix with SKIP LOCKED
# Use compiler extension to change SELECT FOR UPDATE with SKIP LOCKED, supported since MySQL 8.
# As of SQLAlchemy v1.2 SKIP LOCKED is only compiled for Oracle and PostgreSQL backends.
# ref:
# https://dev.mysql.com/doc/refman/8.0/en/innodb-locking-reads.html
# https://docs.sqlalchemy.org/en/latest/core/selectable.html#sqlalchemy.sql.expression.Select.with_for_update
from sqlalchemy.ext.compiler import compiles
from sqlalchemy.sql.expression import Select
from sqlalchemy.sql.selectable import ForUpdateArg
@compiles(Select)
def suffix_skip_locked(select, compiler, **kw):
for_update_clause = getattr(select, '_for_update_arg', None)
if isinstance(for_update_clause, ForUpdateArg) and for_update_clause.skip_locked:
return compiler.visit_select(select.suffix_with("SKIP LOCKED"), **kw)
return compiler.visit_select(select, **kw)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment