"""Keeps an auto-increment counter ahead of ids that were inserted explicitly. SQLite, MySQL/MariaDB and SQL Server move their counter past an explicit id on their own. PostgreSQL's sequence doesn't, so the next insert without an id would reuse one already taken. """ from sqlalchemy import Column from sqlalchemy.ext.compiler import compiles from sqlalchemy.sql.expression import ClauseElement, Executable class SyncIdentity(Executable, ClauseElement): """Moves `column`'s sequence past the largest id stored in its table.""" inherit_cache = False def __init__(self, column: Column): self.column = column @compiles(SyncIdentity) def _already_in_sync(element, compiler, **kw): return "SELECT 1" @compiles(SyncIdentity, "postgresql") def _setval(element, compiler, **kw): table = compiler.preparer.format_table(element.column.table) column = compiler.preparer.format_column(element.column) return ( f"SELECT setval(pg_get_serial_sequence('{table}', '{element.column.name}'), " f"(SELECT COALESCE(MAX({column}), 0) + 1 FROM {table}), false)" )