From 1ee94e89c4e1eda74db86fe89dcd304c40fe5f1c Mon Sep 17 00:00:00 2001 From: RockChinQ Date: Wed, 8 Apr 2026 23:45:54 +0800 Subject: [PATCH] docs: add database migration guide (zh/en/ja) Document Alembic migration usage for developers: - Migration file location and naming convention - How to create new migrations - Schema change and data migration patterns - Auto-run mechanism on startup - CI testing info --- en/develop/dev-config.mdx | 90 +++++++++++++++++++++++++++++++++++++++ ja/develop/dev-config.mdx | 90 +++++++++++++++++++++++++++++++++++++++ zh/develop/dev-config.mdx | 90 +++++++++++++++++++++++++++++++++++++++ 3 files changed, 270 insertions(+) diff --git a/en/develop/dev-config.mdx b/en/develop/dev-config.mdx index 20dafbae8..e60272db0 100644 --- a/en/develop/dev-config.mdx +++ b/en/develop/dev-config.mdx @@ -70,3 +70,93 @@ uv run pre-commit install ## API Documentation We will write API documentation in APIFox before developing each interface. Please refer to [API Documentation(Chinese)](https://ok52vhsenr.apifox.cn/). + +## Database Migrations + +LangBot uses [Alembic](https://alembic.sqlalchemy.org/) to manage database migrations, supporting both SQLite and PostgreSQL seamlessly without database-specific branching. + +### Migration File Location + +``` +src/langbot/pkg/persistence/alembic/versions/ +``` + +### Creating a New Migration + +Create a new Python file in the `versions/` directory following the naming convention `NNNN_description.py`: + +```python +"""Describe your migration + +Revision ID: 0003_add_bot_description +Revises: 0002_sample +Create Date: 2026-04-08 +""" +from alembic import op +import sqlalchemy as sa + +revision = '0003_add_bot_description' +down_revision = '0002_sample' # Points to the previous migration's revision +branch_labels = None +depends_on = None + + +def upgrade() -> None: + # Schema change (works on both SQLite and PostgreSQL) + op.add_column('bots', sa.Column('description', sa.String(512), server_default='')) + + +def downgrade() -> None: + op.drop_column('bots', 'description') +``` + +### Migration Patterns + + + +```python +def upgrade() -> None: + # Add a column + op.add_column('table_name', sa.Column('new_col', sa.String(255), server_default='')) + + # Create a new table + op.create_table( + 'new_table', + sa.Column('id', sa.Integer, primary_key=True, autoincrement=True), + sa.Column('name', sa.String(255), nullable=False), + ) +``` + + +`env.py` sets `render_as_batch=True`, which makes Alembic automatically handle SQLite's ALTER TABLE limitations (via temporary table rebuild). No need to branch on database type. + + + + +```python +import json + +def upgrade() -> None: + conn = op.get_bind() + rows = conn.execute(sa.text("SELECT uuid, config FROM pipelines")).fetchall() + for row in rows: + config = json.loads(row[1]) if isinstance(row[1], str) else row[1] + config.setdefault('ai', {})['new_key'] = 'default_value' + conn.execute( + sa.text("UPDATE pipelines SET config = :cfg WHERE uuid = :uuid"), + {"cfg": json.dumps(config), "uuid": row[0]} + ) +``` + + + +### How It Works + +Migrations run automatically when LangBot starts — no manual commands needed: + +1. On first startup, the baseline version is automatically stamped (marking the existing database) +2. On subsequent startups, all pending migrations are applied (`alembic upgrade head`) + +### CI Testing + +The repository includes a `test-migrations.yml` workflow that automatically tests migration scripts on both SQLite and PostgreSQL when `persistence/` related files change. diff --git a/ja/develop/dev-config.mdx b/ja/develop/dev-config.mdx index a44963680..7de30c7a4 100644 --- a/ja/develop/dev-config.mdx +++ b/ja/develop/dev-config.mdx @@ -70,3 +70,93 @@ uv run pre-commit install ## APIドキュメント 各インターフェースを開発する前に、APIFoxでAPIドキュメントを作成します。[APIドキュメント(中国語)](https://ok52vhsenr.apifox.cn/)を参照してください。 + +## データベースマイグレーション + +LangBotは[Alembic](https://alembic.sqlalchemy.org/)を使用してデータベースマイグレーションを管理しており、SQLiteとPostgreSQLの両方をシームレスにサポートします。データベース固有の分岐コードは不要です。 + +### マイグレーションファイルの場所 + +``` +src/langbot/pkg/persistence/alembic/versions/ +``` + +### 新しいマイグレーションの作成 + +`versions/` ディレクトリに `NNNN_description.py` の命名規則に従ってPythonファイルを作成します: + +```python +"""マイグレーションの説明 + +Revision ID: 0003_add_bot_description +Revises: 0002_sample +Create Date: 2026-04-08 +""" +from alembic import op +import sqlalchemy as sa + +revision = '0003_add_bot_description' +down_revision = '0002_sample' # 前のマイグレーションのrevisionを指定 +branch_labels = None +depends_on = None + + +def upgrade() -> None: + # スキーマ変更(SQLiteとPostgreSQLの両方で動作) + op.add_column('bots', sa.Column('description', sa.String(512), server_default='')) + + +def downgrade() -> None: + op.drop_column('bots', 'description') +``` + +### マイグレーションパターン + + + +```python +def upgrade() -> None: + # 列を追加 + op.add_column('table_name', sa.Column('new_col', sa.String(255), server_default='')) + + # 新しいテーブルを作成 + op.create_table( + 'new_table', + sa.Column('id', sa.Integer, primary_key=True, autoincrement=True), + sa.Column('name', sa.String(255), nullable=False), + ) +``` + + +`env.py`で`render_as_batch=True`が設定されているため、AlembicはSQLiteのALTER TABLE制限を自動的に処理します(一時テーブルによる再構築)。データベースタイプによる分岐は不要です。 + + + + +```python +import json + +def upgrade() -> None: + conn = op.get_bind() + rows = conn.execute(sa.text("SELECT uuid, config FROM pipelines")).fetchall() + for row in rows: + config = json.loads(row[1]) if isinstance(row[1], str) else row[1] + config.setdefault('ai', {})['new_key'] = 'default_value' + conn.execute( + sa.text("UPDATE pipelines SET config = :cfg WHERE uuid = :uuid"), + {"cfg": json.dumps(config), "uuid": row[0]} + ) +``` + + + +### 動作の仕組み + +マイグレーションはLangBot起動時に自動的に実行されます。手動コマンドは不要です: + +1. 初回起動時、ベースラインバージョンが自動的にスタンプされます(既存データベースのマーキング) +2. 以降の起動時、未適用のすべてのマイグレーションが適用されます(`alembic upgrade head`) + +### CIテスト + +リポジトリには`test-migrations.yml`ワークフローが含まれており、`persistence/`関連ファイルが変更された際に、SQLiteとPostgreSQLの両方でマイグレーションスクリプトが自動テストされます。 diff --git a/zh/develop/dev-config.mdx b/zh/develop/dev-config.mdx index 9ec47a2e7..dea820ff6 100644 --- a/zh/develop/dev-config.mdx +++ b/zh/develop/dev-config.mdx @@ -70,3 +70,93 @@ uv run pre-commit install ## API 文档 我们在开发每个接口之前都会先在 APIFox 中编写接口文档,请查看 [API 文档](https://ok52vhsenr.apifox.cn/)。 + +## 数据库迁移 + +LangBot 使用 [Alembic](https://alembic.sqlalchemy.org/) 管理数据库迁移,同时支持 SQLite 和 PostgreSQL,无需针对不同数据库编写不同的迁移代码。 + +### 迁移文件位置 + +``` +src/langbot/pkg/persistence/alembic/versions/ +``` + +### 创建新迁移 + +在 `versions/` 目录下新建 Python 文件,遵循命名规范 `NNNN_description.py`: + +```python +"""描述你的迁移 + +Revision ID: 0003_add_bot_description +Revises: 0002_sample +Create Date: 2026-04-08 +""" +from alembic import op +import sqlalchemy as sa + +revision = '0003_add_bot_description' +down_revision = '0002_sample' # 指向前一个迁移的 revision +branch_labels = None +depends_on = None + + +def upgrade() -> None: + # Schema 变更(SQLite 和 PostgreSQL 通用) + op.add_column('bots', sa.Column('description', sa.String(512), server_default='')) + + +def downgrade() -> None: + op.drop_column('bots', 'description') +``` + +### 迁移模式 + + + +```python +def upgrade() -> None: + # 添加列 + op.add_column('table_name', sa.Column('new_col', sa.String(255), server_default='')) + + # 新建表 + op.create_table( + 'new_table', + sa.Column('id', sa.Integer, primary_key=True, autoincrement=True), + sa.Column('name', sa.String(255), nullable=False), + ) +``` + + +`env.py` 中设置了 `render_as_batch=True`,Alembic 会自动处理 SQLite 的 ALTER TABLE 限制(通过临时表重建),无需手动区分数据库类型。 + + + + +```python +import json + +def upgrade() -> None: + conn = op.get_bind() + rows = conn.execute(sa.text("SELECT uuid, config FROM pipelines")).fetchall() + for row in rows: + config = json.loads(row[1]) if isinstance(row[1], str) else row[1] + config.setdefault('ai', {})['new_key'] = 'default_value' + conn.execute( + sa.text("UPDATE pipelines SET config = :cfg WHERE uuid = :uuid"), + {"cfg": json.dumps(config), "uuid": row[0]} + ) +``` + + + +### 运行机制 + +迁移在 LangBot 启动时自动执行,无需手动运行命令: + +1. 首次启动时,自动 stamp 基线版本(标记现有数据库) +2. 之后每次启动,自动执行所有未应用的迁移(`alembic upgrade head`) + +### CI 测试 + +仓库中包含 `test-migrations.yml` 工作流,当 `persistence/` 相关文件变更时会自动在 SQLite 和 PostgreSQL 上测试迁移脚本。