Repository navigation
Feat: migrate script - #13976
Feat: migrate script#13976
Conversation
…o feat/migrate-script
📝 WalkthroughWalkthroughAdded two new migration stages to the MySQL migration script to migrate tenant data into Changes
Sequence Diagram(s)sequenceDiagram
actor User
participant CLI as CLI/Main
participant Config as MigrationConfig
participant DB as MigrationDatabase
participant StageMgr as Stage Manager
participant Stage as TenantModelInstance/ModelStage
User->>CLI: run (config, stages, mode)
CLI->>Config: load config
Config-->>CLI: DB credentials
CLI->>DB: connect
CLI->>StageMgr: select stage(s)
rect rgba(100,150,200,0.5)
Note over CLI,Stage: For each selected stage
CLI->>Stage: check()
Stage->>DB: table_exists(source/dependency/target)
DB-->>Stage: existence results
Stage-->>CLI: check result (proceed/skip)
alt proceed
CLI->>Stage: execute(dry_run / create-table-only / write)
opt create-table-only or write
Stage->>DB: CREATE TABLE IF NOT EXISTS target
DB-->>Stage: OK
end
alt write
Stage->>DB: INSERT ... SELECT (with dependency lookups)
DB-->>Stage: inserted rows
else dry-run
Stage-->>CLI: planned row counts / SQL preview
end
Stage-->>CLI: stage stats
end
end
CLI->>DB: close()
CLI-->>User: summary report
Estimated Code Review Effort🎯 4 (Complex) | ⏱️ ~45 minutes Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 inconclusive)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Comment |
There was a problem hiding this comment.
Actionable comments posted: 4
🧹 Nitpick comments (1)
tools/scripts/mysql_migration.py (1)
376-381: Consider extracting common helper methods to base class.
current_timestamp()andgenerate_uuid()are duplicated acrossTenantModelProviderStage,TenantModelInstanceStage, andTenantModelStage. Moving them toMigrationStagebase class would reduce duplication.♻️ Suggested refactor
class MigrationStage: """Base class for migration stages""" name = "base_stage" description = "Base migration stage" source_tables = [] target_tables = [] def __init__(self, db: MigrationDatabase, dry_run: bool = True, create_table_only: bool = False): self.db = db self.dry_run = dry_run self.create_table_only = create_table_only + + def current_timestamp(self) -> int: + return int(time.time()) + + def generate_uuid(self) -> str: + """Generate 32-character UUID1""" + return uuid.uuid1().hex🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@tools/scripts/mysql_migration.py` around lines 376 - 381, The helper methods current_timestamp() and generate_uuid() are duplicated in TenantModelProviderStage, TenantModelInstanceStage, and TenantModelStage—move them into the MigrationStage base class: add current_timestamp(self) -> int returning int(time.time()) and generate_uuid(self) -> str returning uuid.uuid1().hex to MigrationStage, remove the duplicate implementations from the three subclasses, and ensure any references still resolve; update imports (uuid, time) at the module top if needed and run tests to confirm nothing else relies on subclass-specific behavior.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@tools/scripts/mysql_migration.py`:
- Around line 675-683: The migration is inserting literal source-status values
(e.g., '0') into the target table, causing semantic mismatch; update the loop
that builds status_val (in the batch loop where generate_uuid() is called and
values.append is built) to map source statuses to target semantics (e.g., map
'0' => 'wasted', '1' => 'active', etc.) and always use the mapped string when
constructing values.append instead of the raw status; implement the mapping as a
small dict or conditional and reference status_val where currently set so the
inserted status matches the target table's DEFAULT semantics.
- Line 519: The migration creates tenant_llm.api_key as VARCHAR(512) NOT NULL
which can truncate long keys and forces NULL->"" conversion elsewhere; change
the target column definition in mysql_migration.py from VARCHAR(512) NOT NULL to
a TEXT (or LONGTEXT) that allows sufficient length and permits NULL, and update
the related conversion logic (the code that currently converts None to empty
string around the api_key handling) to preserve NULLs instead of coercing to ""
so stored NULLs remain NULL and long keys are not truncated.
- Around line 491-506: The current loop in mysql_migration.py builds VALUES via
f-strings (using generate_uuid, instance_name, api_key_escaped, status_val and
current_ts) and passes raw SQL to self.db.execute_sql, which risks SQL
injection; change this to use a parameterized batch insert: collect a list of
tuples for each row (id, instance_name, provider_id, api_key, status,
create_time, create_date, update_time, update_date), build an INSERT INTO
tenant_model_instance (...) VALUES (%s, %s, ..., %s) placeholder string for a
single row and execute the batch with a single parameterized call (or
executemany) through self.db.execute_sql (or the DB client’s batch/execute
method) instead of interpolating values, and apply the same fix pattern to the
similar TenantModelProviderStage code path.
- Line 705: The target schema in mysql_migration.py defines model_type as
VARCHAR(32) NOT NULL but the source tenant_llm.model_type is VARCHAR(128) and
nullable; update the CREATE TABLE/ALTER definition to model_type VARCHAR(128)
NULL (or VARCHAR(128) DEFAULT NULL) to match the source and avoid truncation,
and update the migration's execute method (the execute function that performs
the row inserts) to handle NULL values from source by permitting NULL/using
COALESCE/defaults before insert so NULL model_type values do not cause insert
failures.
---
Nitpick comments:
In `@tools/scripts/mysql_migration.py`:
- Around line 376-381: The helper methods current_timestamp() and
generate_uuid() are duplicated in TenantModelProviderStage,
TenantModelInstanceStage, and TenantModelStage—move them into the MigrationStage
base class: add current_timestamp(self) -> int returning int(time.time()) and
generate_uuid(self) -> str returning uuid.uuid1().hex to MigrationStage, remove
the duplicate implementations from the three subclasses, and ensure any
references still resolve; update imports (uuid, time) at the module top if
needed and run tests to confirm nothing else relies on subclass-specific
behavior.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 844a4f4c-660a-4565-bbb7-cd6a4f7a91e7
📒 Files selected for processing (1)
tools/scripts/mysql_migration.py
| for tenant_id, llm_factory, api_key, status, provider_id in batch: | ||
| record_id = self.generate_uuid() | ||
| instance_name = llm_factory.replace("'", "''") if llm_factory else "" | ||
| api_key_escaped = api_key.replace("'", "''") if api_key else "" | ||
| status_val = status if status else "active" | ||
| values.append(f"('{record_id}', '{instance_name}', '{provider_id}', " | ||
| f"'{api_key_escaped}', '{status_val}', " | ||
| f"{current_ts}, FROM_UNIXTIME({current_ts}), " | ||
| f"{current_ts}, FROM_UNIXTIME({current_ts}))") | ||
|
|
||
| insert_sql = f""" | ||
| INSERT INTO tenant_model_instance | ||
| (id, instance_name, provider_id, api_key, status, create_time, create_date, update_time, update_date) | ||
| VALUES {', '.join(values)} | ||
| """ | ||
| self.db.execute_sql(insert_sql) |
There was a problem hiding this comment.
SQL injection risk with string interpolation.
Values are directly interpolated into SQL using f-strings with only single-quote escaping. This doesn't protect against all injection vectors (e.g., backslash escaping in MySQL). Consider using parameterized queries via execute_sql() with placeholders.
This pattern exists in TenantModelProviderStage as well, but since these are migration scripts operating on internal data, the risk is somewhat mitigated. Still worth addressing for defense-in-depth.
🔒 Suggested safer approach using parameterized batch inserts
for i in range(0, len(records), batch_size):
batch = records[i:i + batch_size]
- values = []
for tenant_id, llm_factory, api_key, status, provider_id in batch:
record_id = self.generate_uuid()
- instance_name = llm_factory.replace("'", "''") if llm_factory else ""
- api_key_escaped = api_key.replace("'", "''") if api_key else ""
+ instance_name = llm_factory if llm_factory else ""
+ api_key_val = api_key if api_key else ""
status_val = status if status else "active"
- values.append(f"('{record_id}', '{instance_name}', '{provider_id}', "
- f"'{api_key_escaped}', '{status_val}', "
- f"{current_ts}, FROM_UNIXTIME({current_ts}), "
- f"{current_ts}, FROM_UNIXTIME({current_ts}))")
-
- insert_sql = f"""
- INSERT INTO tenant_model_instance
- (id, instance_name, provider_id, api_key, status, create_time, create_date, update_time, update_date)
- VALUES {', '.join(values)}
- """
- self.db.execute_sql(insert_sql)
+ self.db.execute_sql(
+ "INSERT INTO tenant_model_instance "
+ "(id, instance_name, provider_id, api_key, status, create_time, create_date, update_time, update_date) "
+ "VALUES (%s, %s, %s, %s, %s, %s, FROM_UNIXTIME(%s), %s, FROM_UNIXTIME(%s))",
+ (record_id, instance_name, provider_id, api_key_val, status_val,
+ current_ts, current_ts, current_ts, current_ts)
+ )🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@tools/scripts/mysql_migration.py` around lines 491 - 506, The current loop in
mysql_migration.py builds VALUES via f-strings (using generate_uuid,
instance_name, api_key_escaped, status_val and current_ts) and passes raw SQL to
self.db.execute_sql, which risks SQL injection; change this to use a
parameterized batch insert: collect a list of tuples for each row (id,
instance_name, provider_id, api_key, status, create_time, create_date,
update_time, update_date), build an INSERT INTO tenant_model_instance (...)
VALUES (%s, %s, ..., %s) placeholder string for a single row and execute the
batch with a single parameterized call (or executemany) through
self.db.execute_sql (or the DB client’s batch/execute method) instead of
interpolating values, and apply the same fix pattern to the similar
TenantModelProviderStage code path.
| id VARCHAR(32) NOT NULL PRIMARY KEY, | ||
| instance_name VARCHAR(128) NOT NULL, | ||
| provider_id VARCHAR(32) NOT NULL, | ||
| api_key VARCHAR(512) NOT NULL, |
There was a problem hiding this comment.
API key column size may cause truncation.
The source tenant_llm.api_key is TextField (LONGTEXT in MySQL, unlimited size), but the target column is VARCHAR(512). Some API keys (especially OAuth tokens or JWT-based keys) can exceed 512 characters, causing silent truncation and broken authentication.
Also, the source allows NULL values, but this column is NOT NULL. Line 494 converts None to empty string, which may not be the intended behavior.
🛠️ Suggested fix
- api_key VARCHAR(512) NOT NULL,
+ api_key TEXT,📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| api_key VARCHAR(512) NOT NULL, | |
| api_key TEXT, |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@tools/scripts/mysql_migration.py` at line 519, The migration creates
tenant_llm.api_key as VARCHAR(512) NOT NULL which can truncate long keys and
forces NULL->"" conversion elsewhere; change the target column definition in
mysql_migration.py from VARCHAR(512) NOT NULL to a TEXT (or LONGTEXT) that
allows sufficient length and permits NULL, and update the related conversion
logic (the code that currently converts None to empty string around the api_key
handling) to preserve NULLs instead of coercing to "" so stored NULLs remain
NULL and long keys are not truncated.
| for source_id, llm_name, provider_id, instance_id, model_type, status in batch: | ||
| record_id = self.generate_uuid() | ||
| model_name_escaped = llm_name.replace("'", "''") if llm_name else "" | ||
| model_type_escaped = model_type.replace("'", "''") if model_type else "" | ||
| status_val = status if status else "active" | ||
| values.append(f"('{record_id}', '{model_name_escaped}', '{provider_id}', " | ||
| f"'{instance_id}', '{model_type_escaped}', '{status_val}', " | ||
| f"{current_ts}, FROM_UNIXTIME({current_ts}), " | ||
| f"{current_ts}, FROM_UNIXTIME({current_ts}))") |
There was a problem hiding this comment.
Status value semantic mismatch.
The query filters for status='0' (meaning "wasted" in the source schema), but the target table appears to use semantic status values like 'active' (line 706 shows DEFAULT 'active'). The code stores the literal '0' value, which doesn't match the new schema's semantics.
The fallback status if status else "active" on line 679 is effectively dead code since the WHERE clause guarantees status='0'.
🛠️ Suggested fix - map status values
for source_id, llm_name, provider_id, instance_id, model_type, status in batch:
record_id = self.generate_uuid()
model_name_escaped = llm_name.replace("'", "''") if llm_name else ""
model_type_escaped = model_type.replace("'", "''") if model_type else ""
- status_val = status if status else "active"
+ # Map old status to new schema: '0'=wasted -> 'inactive', '1'=validate -> 'active'
+ status_val = "inactive" if status == "0" else "active"🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@tools/scripts/mysql_migration.py` around lines 675 - 683, The migration is
inserting literal source-status values (e.g., '0') into the target table,
causing semantic mismatch; update the loop that builds status_val (in the batch
loop where generate_uuid() is called and values.append is built) to map source
statuses to target semantics (e.g., map '0' => 'wasted', '1' => 'active', etc.)
and always use the mapped string when constructing values.append instead of the
raw status; implement the mapping as a small dict or conditional and reference
status_val where currently set so the inserted status matches the target table's
DEFAULT semantics.
| model_name VARCHAR(128), | ||
| provider_id VARCHAR(32) NOT NULL, | ||
| instance_id VARCHAR(32) NOT NULL, | ||
| model_type VARCHAR(32) NOT NULL, |
There was a problem hiding this comment.
model_type column constraints mismatch with source.
The source tenant_llm.model_type is VARCHAR(128) and allows NULL, but the target defines model_type VARCHAR(32) NOT NULL. This could cause:
- Truncation of model type names longer than 32 characters
- Insert failures if
model_typeisNULLin source data
🛠️ Suggested fix
- model_type VARCHAR(32) NOT NULL,
+ model_type VARCHAR(128),And add NULL handling in the execute method:
model_type_escaped = model_type.replace("'", "''") if model_type else ""
+ model_type_val = f"'{model_type_escaped}'" if model_type else "NULL"🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@tools/scripts/mysql_migration.py` at line 705, The target schema in
mysql_migration.py defines model_type as VARCHAR(32) NOT NULL but the source
tenant_llm.model_type is VARCHAR(128) and nullable; update the CREATE
TABLE/ALTER definition to model_type VARCHAR(128) NULL (or VARCHAR(128) DEFAULT
NULL) to match the source and avoid truncation, and update the migration's
execute method (the execute function that performs the row inserts) to handle
NULL values from source by permitting NULL/using COALESCE/defaults before insert
so NULL model_type values do not cause insert failures.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #13976 +/- ##
=======================================
Coverage 96.52% 96.52%
=======================================
Files 10 10
Lines 690 690
Branches 108 108
=======================================
Hits 666 666
Misses 8 8
Partials 16 16 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (2)
tools/scripts/README.md (2)
22-28: Add language specifiers to fenced code blocks.Five fenced code blocks are missing language specifiers, which reduces readability and violates markdown best practices.
📋 Proposed fixes
1. Dependency diagram (lines 22-28):
-``` +```text tenant_model_provider (no dependencies) ↓2. Command usage (lines 71-73):
-``` +```bash python mysql_migration.py [OPTIONS]3. Stage execution log (lines 148-152):
-``` +```text ============================================================4. Dry-run output (lines 162-166):
-``` +```text [DRY RUN] Would insert 150 records5. Migration summary (lines 172-184):
-``` +```text ============================================================As per static analysis, fenced code blocks should have a language specified (markdownlint MD040).
Also applies to: 71-73, 148-152, 162-166, 172-184
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@tools/scripts/README.md` around lines 22 - 28, Several fenced code blocks in README.md are missing language specifiers; update the five blocks by adding appropriate languages: mark the dependency diagram starting with "tenant_model_provider (no dependencies)" and both separator blocks showing "============================================================" and the migration summary block as ```text, and mark the command usage block containing "python mysql_migration.py [OPTIONS]" as ```bash and the dry-run output block containing "[DRY RUN] Would insert 150 records" as ```text so all fenced code blocks include a language specifier to satisfy markdownlint MD040.
36-36: Clarify UUID generation terminology.The term "Random 32-character UUID1" appears inconsistent. Standard UUIDs are typically 36 characters with hyphens (or 32 without). Consider clarifying whether this refers to:
- UUID v1 (time-based)
- UUID v4 (random)
- A custom 32-character random string
📝 Suggested clarification
If using UUID v4 (random), update to:
-| `id` | - | Random 32-character UUID1 | +| `id` | - | Random 32-character UUID (v4, no hyphens) |Or if it's a custom random string:
-| `id` | - | Random 32-character UUID1 | +| `id` | - | Random 32-character alphanumeric string |Also applies to: 46-46, 58-58
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@tools/scripts/README.md` at line 36, The README's `id` field description currently says "Random 32-character UUID1" and is ambiguous; update each `id` row to explicitly state the UUID version and format used (e.g., "UUID v4 (random) — 36-character with hyphens or 32-character without hyphens)" or "UUID v1 (time-based)" or explicitly say "custom 32-character random string" if not a standard UUID), and include the exact representation (with/without hyphens) so readers know how IDs are generated and validated; apply this clarification to all `id` table rows where that phrase appears.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@tools/scripts/README.md`:
- Line 191: Fix the spacing in the README table row that contains the message
string "[DRY RUN] Target table does not exist": add a space between
"`--create-table-only`" and "to" so the description reads "...use `--execute` or
`--create-table-only` to create"; update the row text accordingly in
tools/scripts/README.md where that table entry is defined.
---
Nitpick comments:
In `@tools/scripts/README.md`:
- Around line 22-28: Several fenced code blocks in README.md are missing
language specifiers; update the five blocks by adding appropriate languages:
mark the dependency diagram starting with "tenant_model_provider (no
dependencies)" and both separator blocks showing
"============================================================" and the migration
summary block as ```text, and mark the command usage block containing "python
mysql_migration.py [OPTIONS]" as ```bash and the dry-run output block containing
"[DRY RUN] Would insert 150 records" as ```text so all fenced code blocks
include a language specifier to satisfy markdownlint MD040.
- Line 36: The README's `id` field description currently says "Random
32-character UUID1" and is ambiguous; update each `id` row to explicitly state
the UUID version and format used (e.g., "UUID v4 (random) — 36-character with
hyphens or 32-character without hyphens)" or "UUID v1 (time-based)" or
explicitly say "custom 32-character random string" if not a standard UUID), and
include the exact representation (with/without hyphens) so readers know how IDs
are generated and validated; apply this clarification to all `id` table rows
where that phrase appears.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 2328452d-efca-4d40-ba9f-2a07afac716f
📒 Files selected for processing (1)
tools/scripts/README.md
| | Message | Meaning | | ||
| |---------|-------------------------------------------------------------------------| | ||
| | `No new data to migrate` | All records already exist in target table | | ||
| | `[DRY RUN] Target table does not exist` | Target table missing, use `--execute` or `--create-table-only`to create | |
There was a problem hiding this comment.
Fix spacing in documentation text.
Missing space before "to" in the message description.
✏️ Proposed fix
-| `[DRY RUN] Target table does not exist` | Target table missing, use `--execute` or `--create-table-only`to create |
+| `[DRY RUN] Target table does not exist` | Target table missing, use `--execute` or `--create-table-only` to create |📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| | `[DRY RUN] Target table does not exist` | Target table missing, use `--execute` or `--create-table-only`to create | | |
| | `[DRY RUN] Target table does not exist` | Target table missing, use `--execute` or `--create-table-only` to create | |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@tools/scripts/README.md` at line 191, Fix the spacing in the README table row
that contains the message string "[DRY RUN] Target table does not exist": add a
space between "`--create-table-only`" and "to" so the description reads "...use
`--execute` or `--create-table-only` to create"; update the row text accordingly
in tools/scripts/README.md where that table entry is defined.
### What problem does this PR solve? Add stage for migrate tenant_llm data into table tenant_model_instance and tenant_model. ### Type of change - [x] Other (please describe): tool script <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Chores** * Added two new migration stages to move tenant model and instance records into new target tables, with dry-run, full-execute, and "create table only" modes; migration skips already-migrated rows to avoid duplicates. * **Bug Fixes** * Cleaned up migration header logging for clearer output. * **Documentation** * Added usage guide describing stages, options, modes, config format, examples, and expected logs. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
Add stage for migrate tenant_llm data into table tenant_model_instance and tenant_model. - [x] Other (please describe): tool script <!-- This is an auto-generated comment: release notes by coderabbit.ai --> * **Chores** * Added two new migration stages to move tenant model and instance records into new target tables, with dry-run, full-execute, and "create table only" modes; migration skips already-migrated rows to avoid duplicates. * **Bug Fixes** * Cleaned up migration header logging for clearer output. * **Documentation** * Added usage guide describing stages, options, modes, config format, examples, and expected logs. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
Add stage for migrate tenant_llm data into table tenant_model_instance and tenant_model. - [x] Other (please describe): tool script <!-- This is an auto-generated comment: release notes by coderabbit.ai --> * **Chores** * Added two new migration stages to move tenant model and instance records into new target tables, with dry-run, full-execute, and "create table only" modes; migration skips already-migrated rows to avoid duplicates. * **Bug Fixes** * Cleaned up migration header logging for clearer output. * **Documentation** * Added usage guide describing stages, options, modes, config format, examples, and expected logs. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
### What problem does this PR solve? Add stage for migrate tenant_llm data into table tenant_model_instance and tenant_model. ### Type of change - [x] Other (please describe): tool script <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Chores** * Added two new migration stages to move tenant model and instance records into new target tables, with dry-run, full-execute, and "create table only" modes; migration skips already-migrated rows to avoid duplicates. * **Bug Fixes** * Cleaned up migration header logging for clearer output. * **Documentation** * Added usage guide describing stages, options, modes, config format, examples, and expected logs. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
What problem does this PR solve?
Add stage for migrate tenant_llm data into table tenant_model_instance and tenant_model.
Type of change
Summary by CodeRabbit