✨ feat: 数据库基线与通用 DTO(WP-01 第 3、4 步)

- 通用 DTO:Money(最小货币单位整数)、CursorPage 泛型、9 个平台 ID Annotated 类型(前缀+UUIDv7/v4 正则,与 openapi 契约对齐)
- db 基础:naming_convention Base(pk_/uq_/ix_/fk_,AGENTS 8.6)+ async engine + 事务作用域 session
- 首批 6 张表 typed mapping:user/personal_domain/session/service_account/audit_event/outbox_event;Session ID 为 CSPRNG opaque;审计与 Outbox 不可变
- Alembic async 迁移(含表注释);docker 起 hunjing-postgres 并 upgrade 验证:7 表、约束/索引命名全部符合约定
- 按 database-design skill 清单交叉检查:外键索引全覆盖(复合唯一最左前缀)、审计聚合时间线与 Outbox 投递扫描均为专用复合索引
- 集成测试 8 项(唯一约束、FK restrict/cascade、检查约束、同事务提交)连 PG 测试库运行;pytest 15 项、ruff、mypy strict 全绿
This commit is contained in:
chenxin committed 2026-09-10 10:00:17 +08:00
1 parent 3fbcd0437c
commit 28127949db
14 files changed
+822 -1

No files matched your search

+1
View File
@@ -0,0 +1 @@
Generic single-database configuration with an async dbapi.
+94
View File
@@ -0,0 +1,94 @@
import asyncio
from logging.config import fileConfig
from sqlalchemy import pool
from sqlalchemy.engine import Connection
from sqlalchemy.ext.asyncio import async_engine_from_config
from alembic import context
# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
# Interpret the config file for Python logging.
# This line sets up loggers basically.
if config.config_file_name is not None:
fileConfig(config.config_file_name)
# 模型元数据(autogenerate 真源);连接串来自环境(统一 PostgreSQL,ADR-024)
import os
from app import models # noqa: F401 确保模型注册到 metadata
from app.core.config import get_settings
from app.db.base import Base
target_metadata = Base.metadata
db_url = os.environ.get("DATABASE_URL", get_settings().database_url)
config.set_main_option("sqlalchemy.url", db_url)
# other values from the config, defined by the needs of env.py,
# can be acquired:
# my_important_option = config.get_main_option("my_important_option")
# ... etc.
def run_migrations_offline() -> None:
"""Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the
script output.
"""
url = config.get_main_option("sqlalchemy.url")
context.configure(
url=url,
target_metadata=target_metadata,
literal_binds=True,
dialect_opts={"paramstyle": "named"},
)
with context.begin_transaction():
context.run_migrations()
def do_run_migrations(connection: Connection) -> None:
context.configure(connection=connection, target_metadata=target_metadata)
with context.begin_transaction():
context.run_migrations()
async def run_async_migrations() -> None:
"""In this scenario we need to create an Engine
and associate a connection with the context.
"""
connectable = async_engine_from_config(
config.get_section(config.config_ini_section, {}),
prefix="sqlalchemy.",
poolclass=pool.NullPool,
)
async with connectable.connect() as connection:
await connection.run_sync(do_run_migrations)
await connectable.dispose()
def run_migrations_online() -> None:
"""Run migrations in 'online' mode."""
asyncio.run(run_async_migrations())
if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()
+28
View File
@@ -0,0 +1,28 @@
"""${message}
Revision ID: ${up_revision}
Revises: ${down_revision | comma,n}
Create Date: ${create_date}
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
${imports if imports else ""}
# revision identifiers, used by Alembic.
revision: str = ${repr(up_revision)}
down_revision: Union[str, Sequence[str], None] = ${repr(down_revision)}
branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}
def upgrade() -> None:
"""Upgrade schema."""
${upgrades if upgrades else "pass"}
def downgrade() -> None:
"""Downgrade schema."""
${downgrades if downgrades else "pass"}
@@ -0,0 +1,125 @@
"""初始基线:身份、会话、服务账号、审计与 Outbox
Revision ID: e16a40566b45
Revises:
Create Date: 2026-09-10 09:55:35.167917
"""
from collections.abc import Sequence
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
from alembic import op
# revision identifiers, used by Alembic.
revision: str = 'e16a40566b45'
down_revision: str | Sequence[str] | None = None
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None
def upgrade() -> None:
"""Upgrade schema."""
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('audit_event',
sa.Column('id', sa.String(), nullable=False),
sa.Column('occurred_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
sa.Column('actor_type', sa.String(), nullable=False),
sa.Column('actor_id', sa.String(), nullable=False),
sa.Column('action', sa.String(), nullable=False),
sa.Column('aggregate_type', sa.String(), nullable=False),
sa.Column('aggregate_id', sa.String(), nullable=False),
sa.Column('payload', postgresql.JSONB(astext_type=sa.Text()), nullable=True),
sa.Column('trace_id', sa.String(), nullable=True),
sa.PrimaryKeyConstraint('id', name=op.f('pk_audit_event'))
)
op.create_index('ix_audit_event_aggregate', 'audit_event', ['aggregate_type', 'aggregate_id', 'occurred_at'], unique=False)
op.create_index('ix_audit_event_occurred_at', 'audit_event', ['occurred_at'], unique=False)
op.create_table('outbox_event',
sa.Column('id', sa.String(), nullable=False),
sa.Column('occurred_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
sa.Column('aggregate_type', sa.String(), nullable=False),
sa.Column('aggregate_id', sa.String(), nullable=False),
sa.Column('event_type', sa.String(), nullable=False),
sa.Column('payload', postgresql.JSONB(astext_type=sa.Text()), nullable=False),
sa.Column('status', sa.String(), nullable=False),
sa.Column('attempts', sa.Integer(), nullable=False),
sa.Column('delivered_at', sa.DateTime(timezone=True), nullable=True),
sa.CheckConstraint("status IN ('pending', 'delivered', 'failed')", name=op.f('ck_outbox_event_status_values')),
sa.PrimaryKeyConstraint('id', name=op.f('pk_outbox_event'))
)
op.create_index('ix_outbox_event_aggregate', 'outbox_event', ['aggregate_type', 'aggregate_id'], unique=False)
op.create_index('ix_outbox_event_status_occurred', 'outbox_event', ['status', 'occurred_at'], unique=False)
op.create_table('user',
sa.Column('id', sa.String(), nullable=False),
sa.Column('email', sa.String(), nullable=False),
sa.Column('display_name', sa.String(), nullable=False),
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
sa.PrimaryKeyConstraint('id', name=op.f('pk_user')),
sa.UniqueConstraint('email', name=op.f('uq_user_email'))
)
op.create_table('personal_domain',
sa.Column('id', sa.String(), nullable=False),
sa.Column('user_id', sa.String(), nullable=False),
sa.Column('name', sa.String(), nullable=False),
sa.Column('data_region', sa.String(), nullable=False),
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
sa.ForeignKeyConstraint(['user_id'], ['user.id'], name=op.f('fk_personal_domain_user'), ondelete='restrict'),
sa.PrimaryKeyConstraint('id', name=op.f('pk_personal_domain'))
)
op.create_index(op.f('ix_personal_domain_user_id'), 'personal_domain', ['user_id'], unique=False)
op.create_table('session',
sa.Column('id', sa.String(), nullable=False),
sa.Column('user_id', sa.String(), nullable=False),
sa.Column('expires_at', sa.DateTime(timezone=True), nullable=False),
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
sa.Column('revoked_at', sa.DateTime(timezone=True), nullable=True),
sa.ForeignKeyConstraint(['user_id'], ['user.id'], name=op.f('fk_session_user'), ondelete='cascade'),
sa.PrimaryKeyConstraint('id', name=op.f('pk_session'))
)
op.create_index(op.f('ix_session_expires_at'), 'session', ['expires_at'], unique=False)
op.create_index(op.f('ix_session_user_id'), 'session', ['user_id'], unique=False)
op.create_table('service_account',
sa.Column('id', sa.String(), nullable=False),
sa.Column('domain_id', sa.String(), nullable=False),
sa.Column('name', sa.String(), nullable=False),
sa.Column('key_prefix', sa.String(), nullable=False),
sa.Column('key_hash', sa.String(), nullable=False),
sa.Column('scopes', postgresql.JSONB(astext_type=sa.Text()), nullable=False),
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
sa.Column('revoked_at', sa.DateTime(timezone=True), nullable=True),
sa.ForeignKeyConstraint(['domain_id'], ['personal_domain.id'], name=op.f('fk_service_account_personal_domain'), ondelete='cascade'),
sa.PrimaryKeyConstraint('id', name=op.f('pk_service_account'))
)
op.create_index(op.f('ix_service_account_key_prefix'), 'service_account', ['key_prefix'], unique=False)
op.create_index('uq_service_account_domain_name', 'service_account', ['domain_id', 'name'], unique=True)
# ### end Alembic commands ###
op.execute("COMMENT ON TABLE \"user\" IS '用户(WP-01):多凭证与账户根'")
op.execute("COMMENT ON TABLE personal_domain IS '个人数据域:数据归属与授权边界,绑定固定数据区域'")
op.execute("COMMENT ON TABLE session IS 'Web 会话:ID 为 CSPRNG opaque,仅存校验值'")
op.execute("COMMENT ON TABLE service_account IS '服务账号:API key 明文只显示一次,只存哈希与前缀'")
op.execute("COMMENT ON TABLE audit_event IS '不可变审计链:与权威状态、Outbox 同事务提交'")
op.execute("COMMENT ON TABLE outbox_event IS 'Transactional Outbox:已提交领域事实的可靠投递队列'")
def downgrade() -> None:
"""Downgrade schema."""
# ### commands auto generated by Alembic - please adjust! ###
op.drop_index('uq_service_account_domain_name', table_name='service_account')
op.drop_index(op.f('ix_service_account_key_prefix'), table_name='service_account')
op.drop_table('service_account')
op.drop_index(op.f('ix_session_user_id'), table_name='session')
op.drop_index(op.f('ix_session_expires_at'), table_name='session')
op.drop_table('session')
op.drop_index(op.f('ix_personal_domain_user_id'), table_name='personal_domain')
op.drop_table('personal_domain')
op.drop_table('user')
op.drop_index('ix_outbox_event_status_occurred', table_name='outbox_event')
op.drop_index('ix_outbox_event_aggregate', table_name='outbox_event')
op.drop_table('outbox_event')
op.drop_index('ix_audit_event_occurred_at', table_name='audit_event')
op.drop_index('ix_audit_event_aggregate', table_name='audit_event')
op.drop_table('audit_event')
# ### end Alembic commands ###