Created
May 22, 2020 21:27
-
-
Save alexa-infra/1a2488e4980e4e3c239aaf962eab06b6 to your computer and use it in GitHub Desktop.
Dialect-specific SQLAlchemy declarative Column defaults
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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