第二步

This commit is contained in:
amb
2026-09-01 12:24:43 +08:00
parent 47bf6cc5ca
commit 1d8621717a
14 changed files with 815 additions and 9 deletions
+78
View File
@@ -0,0 +1,78 @@
"""Alembic 环境配置。
import app.models 以注册所有 ORM 模型到 Base.metadata
使 alembic revision --autogenerate 能检测模型变更。
"""
from logging.config import fileConfig
from alembic import context
from sqlalchemy import engine_from_config, pool
from app.core.config import get_settings
from app.models import Base # noqa: F401 — 触发全部模型注册
# this is the Alembic Config object
config = context.config
# 根据应用配置覆盖 sqlalchemy.url
settings = get_settings()
config.set_main_option("sqlalchemy.url", settings.database_url)
# Interpret the config file for Python logging.
if config.config_file_name is not None:
fileConfig(config.config_file_name)
# target metadata for autogenerate
target_metadata = Base.metadata
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 run_migrations_online() -> None:
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
connectable = engine_from_config(
config.get_section(config.config_ini_section, {}),
prefix="sqlalchemy.",
poolclass=pool.NullPool,
)
with connectable.connect() as connection:
context.configure(
connection=connection,
target_metadata=target_metadata,
)
with context.begin_transaction():
context.run_migrations()
if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()
+25
View File
@@ -0,0 +1,25 @@
"""${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, 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:
${upgrades if upgrades else "pass"}
def downgrade() -> None:
${downgrades if downgrades else "pass"}
View File
@@ -0,0 +1,142 @@
"""initial_schema
Revision ID: 5c27c8e31fde
Revises:
Create Date: 2026-09-01 12:22:22.337100
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = '5c27c8e31fde'
down_revision: Union[str, None] = None
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('plans',
sa.Column('code', sa.String(length=32), nullable=False, comment='套餐代码 (free/basic/pro)'),
sa.Column('name', sa.String(length=64), nullable=False, comment='套餐名称'),
sa.Column('storage_quota', sa.Integer(), nullable=False, comment='存储配额 (字节)'),
sa.Column('max_file_size', sa.Integer(), nullable=False, comment='单文件大小上限 (字节)'),
sa.Column('is_active', sa.Boolean(), nullable=False, comment='是否可用'),
sa.Column('id', sa.String(length=32), nullable=False, comment='UUID4 十六进制主键'),
sa.Column('created_at', sa.String(length=32), nullable=False, comment='创建时间 (ISO8601)'),
sa.Column('updated_at', sa.String(length=32), nullable=False, comment='更新时间 (ISO8601)'),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('code')
)
op.create_table('users',
sa.Column('username', sa.String(length=64), nullable=False, comment='用户名'),
sa.Column('email', sa.String(length=255), nullable=False, comment='邮箱'),
sa.Column('password_hash', sa.String(length=255), nullable=False, comment='Argon2id 密码哈希'),
sa.Column('status', sa.String(length=16), nullable=False, comment='状态 (active/disabled)'),
sa.Column('plan_id', sa.String(length=32), nullable=False, comment='套餐 ID'),
sa.Column('storage_used', sa.Integer(), nullable=False, comment='已用存储 (字节)'),
sa.Column('id', sa.String(length=32), nullable=False, comment='UUID4 十六进制主键'),
sa.Column('created_at', sa.String(length=32), nullable=False, comment='创建时间 (ISO8601)'),
sa.Column('updated_at', sa.String(length=32), nullable=False, comment='更新时间 (ISO8601)'),
sa.ForeignKeyConstraint(['plan_id'], ['plans.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_users_email'), 'users', ['email'], unique=True)
op.create_index(op.f('ix_users_username'), 'users', ['username'], unique=True)
op.create_table('knowledge_bases',
sa.Column('user_id', sa.String(length=32), nullable=False, comment='所有者用户 ID'),
sa.Column('name', sa.String(length=255), nullable=False, comment='知识库名称'),
sa.Column('description', sa.Text(), nullable=True, comment='知识库描述'),
sa.Column('enabled', sa.Boolean(), nullable=False, comment='是否启用'),
sa.Column('token_hash', sa.String(length=64), nullable=False, comment='SHA-256(secret_token) 十六进制'),
sa.Column('token_encrypted', sa.Text(), nullable=True, comment='Fernet 加密的 token 原文'),
sa.Column('token_hint', sa.String(length=16), nullable=True, comment='token 末 8 位明文,供后台识别'),
sa.Column('id', sa.String(length=32), nullable=False, comment='UUID4 十六进制主键'),
sa.Column('created_at', sa.String(length=32), nullable=False, comment='创建时间 (ISO8601)'),
sa.Column('updated_at', sa.String(length=32), nullable=False, comment='更新时间 (ISO8601)'),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_knowledge_bases_token_hash'), 'knowledge_bases', ['token_hash'], unique=True)
op.create_index(op.f('ix_knowledge_bases_user_id'), 'knowledge_bases', ['user_id'], unique=False)
op.create_table('document_categories',
sa.Column('knowledge_base_id', sa.String(length=32), nullable=False, comment='所属知识库 ID'),
sa.Column('name', sa.String(length=255), nullable=False, comment='分类名称'),
sa.Column('sort_order', sa.Integer(), nullable=False, comment='排序序号'),
sa.Column('id', sa.String(length=32), nullable=False, comment='UUID4 十六进制主键'),
sa.Column('created_at', sa.String(length=32), nullable=False, comment='创建时间 (ISO8601)'),
sa.Column('updated_at', sa.String(length=32), nullable=False, comment='更新时间 (ISO8601)'),
sa.ForeignKeyConstraint(['knowledge_base_id'], ['knowledge_bases.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_document_categories_knowledge_base_id'), 'document_categories', ['knowledge_base_id'], unique=False)
op.create_table('documents',
sa.Column('knowledge_base_id', sa.String(length=32), nullable=False, comment='所属知识库 ID'),
sa.Column('user_id', sa.String(length=32), nullable=False, comment='所有者用户 ID (冗余,便于隔离校验)'),
sa.Column('category_id', sa.String(length=32), nullable=True, comment='分类 ID'),
sa.Column('original_filename', sa.String(length=512), nullable=False, comment='原始文件名 (仅展示)'),
sa.Column('storage_path', sa.String(length=1024), nullable=False, comment='相对于 data/ 的物理存储路径'),
sa.Column('markdown_path', sa.String(length=1024), nullable=True, comment='相对于 data/ 的 Markdown 文件路径'),
sa.Column('file_size', sa.Integer(), nullable=False, comment='文件大小 (字节)'),
sa.Column('mime_type', sa.String(length=127), nullable=False, comment='MIME 类型'),
sa.Column('file_ext', sa.String(length=16), nullable=False, comment='文件扩展名 (.docx/.pdf)'),
sa.Column('sha256', sa.String(length=64), nullable=False, comment='文件 SHA-256 哈希'),
sa.Column('doc_token_hash', sa.String(length=64), nullable=True, comment='SHA-256(document_token) 十六进制'),
sa.Column('doc_token_encrypted', sa.Text(), nullable=True, comment='Fernet 加密的 document_token 原文'),
sa.Column('doc_token_hint', sa.String(length=16), nullable=True, comment='document_token 末 8 位明文'),
sa.Column('title', sa.String(length=512), nullable=True, comment='文档标题 (用户可改)'),
sa.Column('description', sa.Text(), nullable=True, comment='文档描述 (用户可改)'),
sa.Column('keywords', sa.Text(), nullable=True, comment='关键词 (逗号分隔)'),
sa.Column('content_summary', sa.Text(), nullable=True, comment='抽取式摘要 (~200字)'),
sa.Column('status', sa.String(length=16), nullable=False, comment='状态 (PENDING/PROCESSING/READY/FAILED/DELETED)'),
sa.Column('error_code', sa.String(length=64), nullable=True, comment='错误码 (如 SCANNED_PDF_NO_TEXT_LAYER)'),
sa.Column('id', sa.String(length=32), nullable=False, comment='UUID4 十六进制主键'),
sa.Column('created_at', sa.String(length=32), nullable=False, comment='创建时间 (ISO8601)'),
sa.Column('updated_at', sa.String(length=32), nullable=False, comment='更新时间 (ISO8601)'),
sa.ForeignKeyConstraint(['category_id'], ['document_categories.id'], ),
sa.ForeignKeyConstraint(['knowledge_base_id'], ['knowledge_bases.id'], ),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_documents_doc_token_hash'), 'documents', ['doc_token_hash'], unique=True)
op.create_index(op.f('ix_documents_knowledge_base_id'), 'documents', ['knowledge_base_id'], unique=False)
op.create_index(op.f('ix_documents_user_id'), 'documents', ['user_id'], unique=False)
op.create_table('access_logs',
sa.Column('knowledge_base_id', sa.String(length=32), nullable=False, comment='知识库 ID'),
sa.Column('document_id', sa.String(length=32), nullable=True, comment='文档 ID (可选)'),
sa.Column('path', sa.String(length=1024), nullable=False, comment='请求路径'),
sa.Column('accessed_at', sa.String(length=32), nullable=False, comment='访问时间 (ISO8601)'),
sa.Column('user_agent', sa.Text(), nullable=True, comment='User-Agent'),
sa.Column('request_type', sa.String(length=32), nullable=True, comment='请求类型 (html/md/txt/json/search)'),
sa.Column('id', sa.String(length=32), nullable=False, comment='UUID4 十六进制主键'),
sa.Column('created_at', sa.String(length=32), nullable=False, comment='创建时间 (ISO8601)'),
sa.Column('updated_at', sa.String(length=32), nullable=False, comment='更新时间 (ISO8601)'),
sa.ForeignKeyConstraint(['document_id'], ['documents.id'], ),
sa.ForeignKeyConstraint(['knowledge_base_id'], ['knowledge_bases.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_access_logs_knowledge_base_id'), 'access_logs', ['knowledge_base_id'], unique=False)
# ### end Alembic commands ###
def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.drop_index(op.f('ix_access_logs_knowledge_base_id'), table_name='access_logs')
op.drop_table('access_logs')
op.drop_index(op.f('ix_documents_user_id'), table_name='documents')
op.drop_index(op.f('ix_documents_knowledge_base_id'), table_name='documents')
op.drop_index(op.f('ix_documents_doc_token_hash'), table_name='documents')
op.drop_table('documents')
op.drop_index(op.f('ix_document_categories_knowledge_base_id'), table_name='document_categories')
op.drop_table('document_categories')
op.drop_index(op.f('ix_knowledge_bases_user_id'), table_name='knowledge_bases')
op.drop_index(op.f('ix_knowledge_bases_token_hash'), table_name='knowledge_bases')
op.drop_table('knowledge_bases')
op.drop_index(op.f('ix_users_username'), table_name='users')
op.drop_index(op.f('ix_users_email'), table_name='users')
op.drop_table('users')
op.drop_table('plans')
# ### end Alembic commands ###