chore: initialize insar management system v2
This commit is contained in:
@@ -0,0 +1,87 @@
|
||||
"""
|
||||
Alembic 迁移环境配置。
|
||||
|
||||
使用说明:
|
||||
# 生成新迁移(自动检测模型变更)
|
||||
cd backend
|
||||
alembic revision --autogenerate -m "描述变更内容"
|
||||
|
||||
# 执行迁移
|
||||
alembic upgrade head
|
||||
|
||||
# 回滚一步
|
||||
alembic downgrade -1
|
||||
|
||||
# 标记当前数据库为最新(首次引入 Alembic 时使用)
|
||||
alembic stamp head
|
||||
|
||||
注意:首次使用时,由于数据库已由 create_all 创建,请先运行 `alembic stamp head`
|
||||
将当前状态标记为基线,之后再用 alembic 管理后续变更。
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
from logging.config import fileConfig
|
||||
|
||||
from alembic import context
|
||||
from dotenv import load_dotenv
|
||||
from sqlalchemy import engine_from_config, pool
|
||||
|
||||
# 将 backend 目录加入 sys.path,使 app 包可被导入
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
load_dotenv()
|
||||
|
||||
# 导入所有 ORM 模型,确保它们注册到 Base.metadata
|
||||
from app.database import Base # noqa: E402
|
||||
from app import models # noqa: E402, F401
|
||||
|
||||
config = context.config
|
||||
|
||||
# 从环境变量动态注入数据库 URL(将 asyncpg 驱动替换为 psycopg 同步驱动)
|
||||
_async_url = os.environ.get("DATABASE_URL", "")
|
||||
_sync_url = _async_url.replace("postgresql+asyncpg://", "postgresql+psycopg://")
|
||||
if not _sync_url:
|
||||
raise RuntimeError("DATABASE_URL 环境变量未设置,无法运行 Alembic 迁移。")
|
||||
config.set_main_option("sqlalchemy.url", _sync_url)
|
||||
|
||||
if config.config_file_name is not None:
|
||||
fileConfig(config.config_file_name)
|
||||
|
||||
target_metadata = Base.metadata
|
||||
|
||||
|
||||
def run_migrations_offline() -> None:
|
||||
"""离线模式:仅生成 SQL 脚本,不连接数据库。"""
|
||||
url = config.get_main_option("sqlalchemy.url")
|
||||
context.configure(
|
||||
url=url,
|
||||
target_metadata=target_metadata,
|
||||
literal_binds=True,
|
||||
dialect_opts={"paramstyle": "named"},
|
||||
compare_type=True,
|
||||
)
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
|
||||
def run_migrations_online() -> None:
|
||||
"""在线模式:连接数据库并执行迁移。"""
|
||||
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,
|
||||
compare_type=True,
|
||||
)
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
|
||||
if context.is_offline_mode():
|
||||
run_migrations_offline()
|
||||
else:
|
||||
run_migrations_online()
|
||||
@@ -0,0 +1,26 @@
|
||||
"""${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"}
|
||||
@@ -0,0 +1,30 @@
|
||||
"""baseline: 标记现有 schema 为 Alembic 管理起点
|
||||
|
||||
此迁移为空操作(no-op)。数据库表结构已由应用启动时的 create_all 创建。
|
||||
首次引入 Alembic 时,请执行以下命令将当前数据库标记为此基线:
|
||||
|
||||
cd backend
|
||||
alembic stamp head
|
||||
|
||||
之后所有 schema 变更均通过 alembic revision --autogenerate 管理。
|
||||
|
||||
Revision ID: 0001
|
||||
Revises:
|
||||
Create Date: 2026-02-19
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
|
||||
revision: str = "0001"
|
||||
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:
|
||||
# 基线迁移:数据库已由 create_all 初始化,此处无需操作。
|
||||
pass
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
# 基线无法回滚。
|
||||
pass
|
||||
@@ -0,0 +1,66 @@
|
||||
"""water_v2: 新增 sar_scene_geo 和 flood_detections 表
|
||||
|
||||
Revision ID: 0002
|
||||
Revises: 0001
|
||||
Create Date: 2026-02-25
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
revision: str = "0002"
|
||||
down_revision: Union[str, None] = "0001"
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
# 清理旧 water 表(如果存在)
|
||||
op.execute("DROP TABLE IF EXISTS flood_events CASCADE")
|
||||
op.execute("DROP TABLE IF EXISTS water_pairs CASCADE")
|
||||
op.execute("DROP TABLE IF EXISTS water_masks CASCADE")
|
||||
|
||||
op.create_table(
|
||||
"sar_scene_geo",
|
||||
sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
|
||||
sa.Column("radar_data_id", sa.Integer(), nullable=False),
|
||||
sa.Column("geo_path", sa.String(), nullable=True),
|
||||
sa.Column("pixel_size_m", sa.Float(), nullable=True),
|
||||
sa.Column("status", sa.String(), nullable=False, server_default="PENDING"),
|
||||
sa.Column("error_msg", sa.Text(), nullable=True),
|
||||
sa.Column("created_at", sa.DateTime(), server_default=sa.text("now()"), nullable=True),
|
||||
sa.Column("updated_at", sa.DateTime(), server_default=sa.text("now()"), nullable=True),
|
||||
sa.ForeignKeyConstraint(["radar_data_id"], ["radar_data.id"]),
|
||||
sa.PrimaryKeyConstraint("id"),
|
||||
sa.UniqueConstraint("radar_data_id", name="uq_sar_scene_geo_radar"),
|
||||
)
|
||||
op.create_index("ix_sar_scene_geo_radar_data_id", "sar_scene_geo", ["radar_data_id"])
|
||||
op.create_index("ix_sar_scene_geo_status", "sar_scene_geo", ["status"])
|
||||
|
||||
op.create_table(
|
||||
"flood_detections",
|
||||
sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
|
||||
sa.Column("pre_scene_id", sa.Integer(), nullable=False),
|
||||
sa.Column("post_scene_id", sa.Integer(), nullable=False),
|
||||
sa.Column("output_dir", sa.String(), nullable=True),
|
||||
sa.Column("classified_path", sa.String(), nullable=True),
|
||||
sa.Column("flood_area_km2", sa.Float(), nullable=True),
|
||||
sa.Column("stable_water_area_km2", sa.Float(), nullable=True),
|
||||
sa.Column("status", sa.String(), nullable=False, server_default="PENDING"),
|
||||
sa.Column("error_msg", sa.Text(), nullable=True),
|
||||
sa.Column("created_at", sa.DateTime(), server_default=sa.text("now()"), nullable=True),
|
||||
sa.Column("updated_at", sa.DateTime(), server_default=sa.text("now()"), nullable=True),
|
||||
sa.ForeignKeyConstraint(["pre_scene_id"], ["sar_scene_geo.id"]),
|
||||
sa.ForeignKeyConstraint(["post_scene_id"], ["sar_scene_geo.id"]),
|
||||
sa.PrimaryKeyConstraint("id"),
|
||||
sa.UniqueConstraint("pre_scene_id", "post_scene_id", name="uq_flood_detection_pair"),
|
||||
)
|
||||
op.create_index("ix_flood_detections_pre_scene_id", "flood_detections", ["pre_scene_id"])
|
||||
op.create_index("ix_flood_detections_post_scene_id", "flood_detections", ["post_scene_id"])
|
||||
op.create_index("ix_flood_detections_status", "flood_detections", ["status"])
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_table("flood_detections")
|
||||
op.drop_table("sar_scene_geo")
|
||||
Reference in New Issue
Block a user