Skip to content

Instantly share code, notes, and snippets.

@alexa-infra
Created May 22, 2020 21:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexa-infra/1a2488e4980e4e3c239aaf962eab06b6 to your computer and use it in GitHub Desktop.
Save alexa-infra/1a2488e4980e4e3c239aaf962eab06b6 to your computer and use it in GitHub Desktop.
Dialect-specific SQLAlchemy declarative Column defaults
class Table1(Base):
__tablename__ = 'table1'
id = sa.Column(UUID, primary_key=True, server_default=sa.text("uuid_generate_v4()"))
class Table2(Base):
__tablename__ = 'table2'
id = sa.Column(UUID, primary_key=True, default=uuid.uuid4)
import uuid
from sqlalchemy import text
from sqlalchemy.schema import ColumnDefault, DefaultClause
from sqlalchemy.ext.compiler import compiles
@compiles(UUID, "sqlite")
def compile_uuid_sqlite(type_, compiler, **kwargs):
expr = kwargs.get("type_expression")
if expr is not None and expr.primary_key and expr.server_default and not expr.default:
expr.server_default = None
expr.default = ColumnDefault(uuid.uuid4)
return compiler.visit_CHAR(type_, **kwargs)
@compiles(UUID, "postgresql")
def compile_uuid_postgresql(type_, compiler, **kwargs):
expr = kwargs.get("type_expression")
if expr is not None and expr.primary_key and expr.default and not expr.server_default:
expr.server_default = DefaultClause(text("uuid_generate_v4()"))
expr.default = None
return compiler.visit_UUID(type_, **kwargs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment