Files
ctms/backend/app/db/base_class.py
T
Cheng Zhou f40e979c53 refactor(db): 抽出 GUID 类型并兼容 SQLite 的 JSONB 字段
- base_class.py 内置 GUID(TypeDecorator),PostgreSQL 走原生 UUID,
  SQLite 走 CHAR(36),UUID 在绑定/读取时统一转换。
- study_setup_config 与 study_setup_config_version 改用 JSONB().with_variant
  以便测试库使用 JSON 字段,生产仍保留 JSONB。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-25 12:36:02 +08:00

46 lines
1.1 KiB
Python

from __future__ import annotations
import uuid
from sqlalchemy import String, TypeDecorator
from sqlalchemy.dialects.postgresql import UUID as PG_UUID
from sqlalchemy.orm import DeclarativeBase
class GUID(TypeDecorator):
"""Platform-independent UUID type.
PostgreSQL keeps native UUID columns; SQLite test databases store canonical
UUID strings so bind/result behavior stays consistent.
"""
impl = String
cache_ok = True
def load_dialect_impl(self, dialect):
if dialect.name == "sqlite":
return dialect.type_descriptor(String(36))
return dialect.type_descriptor(PG_UUID(as_uuid=True))
def process_bind_param(self, value, dialect):
if value is None:
return None
if dialect.name == "sqlite":
return str(value)
return value
def process_result_value(self, value, dialect):
if value is None:
return None
if dialect.name == "sqlite" and isinstance(value, str):
return uuid.UUID(value)
return value
class Base(DeclarativeBase):
type_annotation_map = {
uuid.UUID: GUID(),
}
pass