Repository navigation
Refa: refine mysql migration version workflow - #15549
Conversation
📝 WalkthroughWalkthroughThis PR refactors MySQL migration versioning from per-stage markers to a centralized database version system. Four separate migration calls are consolidated into single invocations, and version gating prevents redundant migration runs when the database is already current. ChangesDatabase Version Gating Refactor
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Suggested labels
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 3❌ Failed checks (1 warning, 2 inconclusive)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (4)
tools/scripts/mysql_migration.py (4)
582-604:⚠️ Potential issue | 🟠 Major | 🏗️ Heavy liftSQL injection risk: use parameterized queries instead of string interpolation.
This stage uses manual quote escaping (
replace("'", "''")), whileTenantModelProviderStagecorrectly uses parameterized queries with placeholders. Manual escaping is fragile and doesn't handle all edge cases (e.g., backslash escapes in certain MySQL modes).Refactor to use parameterized queries consistent with
TenantModelProviderStage(lines 414-437).🔒 Proposed fix using parameterized queries
# Insert records in batches batch_size = 100 for i in range(0, len(records), batch_size): batch = records[i:i + batch_size] - values = [] + placeholders = [] + params = [] for tenant_id, llm_factory, api_key, status, provider_id in batch: record_id = self.generate_uuid() instance_name = "default" - api_key_escaped = api_key.replace("'", "''") if api_key else "" status_val = "active" if status in ["1", "active", "enable"] else "inactive" - values.append(f"('{record_id}', '{instance_name}', '{provider_id}', " - f"'{api_key_escaped}', '{status_val}', " - f"{current_ts * 1000}, FROM_UNIXTIME({current_ts}), " - f"{current_ts * 1000}, FROM_UNIXTIME({current_ts}))") - - insert_sql = f""" + placeholders.append("(%s, %s, %s, %s, %s, %s, FROM_UNIXTIME(%s), %s, FROM_UNIXTIME(%s))") + params.extend([ + record_id, + instance_name, + provider_id, + api_key or "", + status_val, + current_ts * 1000, + current_ts, + current_ts * 1000, + current_ts, + ]) + insert_sql = """ 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) + VALUES """ + ', '.join(placeholders) + self.db.execute_sql(insert_sql, params) rows_inserted += len(batch) logger.info(f"Inserted batch {i // batch_size + 1}: {len(batch)} records")🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@tools/scripts/mysql_migration.py` around lines 582 - 604, The batch INSERT builds SQL via string interpolation (in the for loop that calls self.generate_uuid() and constructs values) which risks SQL injection; refactor the insertion in the loop that populates values for tenant_model_instance to use parameterized queries like TenantModelProviderStage does: build a single INSERT statement with parameter placeholders for each row, accumulate a flat params list (id, instance_name, provider_id, api_key, status, create_time, create_date, update_time, update_date) for every record in the batch, and call self.db.execute_sql(insert_sql, params) (or the equivalent paramized execute method) instead of formatting values into the SQL string and manually escaping quotes.
795-818:⚠️ Potential issue | 🟠 Major | 🏗️ Heavy liftSQL injection risk: same issue as
TenantModelInstanceStage.Apply parameterized queries here as well.
🔒 Proposed fix using parameterized queries
# Insert records in batches batch_size = 100 for i in range(0, len(records), batch_size): batch = records[i:i + batch_size] - values = [] + placeholders = [] + params = [] 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 = "active" if status in ["1", "active", "enable"] else "inactive" - values.append(f"('{record_id}', '{model_name_escaped}', '{provider_id}', " - f"'{instance_id}', '{model_type_escaped}', '{status_val}', " - f"{current_ts * 1000}, FROM_UNIXTIME({current_ts}), " - f"{current_ts * 1000}, FROM_UNIXTIME({current_ts}))") - - insert_sql = f""" + placeholders.append("(%s, %s, %s, %s, %s, %s, %s, FROM_UNIXTIME(%s), %s, FROM_UNIXTIME(%s))") + params.extend([ + record_id, + llm_name or "", + provider_id, + instance_id, + model_type or "", + status_val, + current_ts * 1000, + current_ts, + current_ts * 1000, + current_ts, + ]) + insert_sql = """ INSERT INTO tenant_model (id, model_name, provider_id, instance_id, model_type, status, create_time, create_date, update_time, update_date) - VALUES {', '.join(values)} - """ - self.db.execute_sql(insert_sql) + VALUES """ + ', '.join(placeholders) + self.db.execute_sql(insert_sql, params) rows_inserted += len(batch) logger.info(f"Inserted batch {i // batch_size + 1}: {len(batch)} records")🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@tools/scripts/mysql_migration.py` around lines 795 - 818, The batch INSERT currently builds SQL via string interpolation (in the block that generates values using self.generate_uuid(), model_name_escaped, model_type_escaped and then calls self.db.execute_sql(insert_sql)), which is vulnerable to SQL injection; change this to use parameterized queries: build the INSERT with placeholders for each column (id, model_name, provider_id, instance_id, model_type, status, create_time, create_date, update_time, update_date) and pass a list of parameter tuples for the batch to a safe execute_many/execute method on self.db instead of concatenating values into the SQL string, and remove manual quote-escaping (model_name_escaped/model_type_escaped) so values are bound as parameters.
822-841:⚠️ Potential issue | 🔴 Critical | ⚡ Quick winSQL syntax error: trailing comma before closing parenthesis.
Line 838 has a trailing comma after the last index definition, which will cause a MySQL syntax error when creating the table.
🐛 Proposed fix
INDEX idx_instance_id (instance_id), - ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 + INDEX idx_instance_id (instance_id) + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@tools/scripts/mysql_migration.py` around lines 822 - 841, The CREATE TABLE in create_target_table defines tenant_model with a trailing comma after the last index definition which causes a MySQL syntax error; open the create_sql string in create_target_table and remove the extra comma after "INDEX idx_instance_id (instance_id)," so the closing parenthesis follows the last definition directly, then keep the rest of the SQL intact and rerun the migration.
1144-1189:⚠️ Potential issue | 🟠 Major | 🏗️ Heavy liftVersion marker may be set even when stages fail due to missing dependencies.
all_stages_completedis only set toFalsefor unknown stage names (line 1154). However, stages likeTenantModelInstanceStageandTenantModelStagereturn(0, [])when dependency tables are missing (e.g., lines 532-536), which doesn't mark the run as incomplete.This could result in the database version being marked as migrated even though no actual migration occurred due to missing prerequisites.
Consider tracking whether each stage's
execute()returned successfully with expected results, or whether it returned early due to a precondition failure.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@tools/scripts/mysql_migration.py` around lines 1144 - 1189, The code only flips all_stages_completed for unknown stages but not when a stage ran but effectively did nothing due to missing dependencies; update the migration loop that calls stage.check() / stage.execute() (and the MIGRATION_STAGES entries like TenantModelInstanceStage and TenantModelStage) so you can detect and mark failed/skipped executions: either (preferred) change execute() to return a third success flag (rows, tables, success) and set all_stages_completed = False when success is False, or (if you cannot change signatures) treat a post-check execute() result of rows == 0 and tables == [] (when stage.check() was True and not create_table_only) as an incomplete stage and set all_stages_completed = False before accumulating stats; ensure this logic is applied before calling db.set_database_version and references stage.check(), stage.execute(), all_stages_completed, mark_database_version_on_success, and db.set_database_version.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Outside diff comments:
In `@tools/scripts/mysql_migration.py`:
- Around line 582-604: The batch INSERT builds SQL via string interpolation (in
the for loop that calls self.generate_uuid() and constructs values) which risks
SQL injection; refactor the insertion in the loop that populates values for
tenant_model_instance to use parameterized queries like TenantModelProviderStage
does: build a single INSERT statement with parameter placeholders for each row,
accumulate a flat params list (id, instance_name, provider_id, api_key, status,
create_time, create_date, update_time, update_date) for every record in the
batch, and call self.db.execute_sql(insert_sql, params) (or the equivalent
paramized execute method) instead of formatting values into the SQL string and
manually escaping quotes.
- Around line 795-818: The batch INSERT currently builds SQL via string
interpolation (in the block that generates values using self.generate_uuid(),
model_name_escaped, model_type_escaped and then calls
self.db.execute_sql(insert_sql)), which is vulnerable to SQL injection; change
this to use parameterized queries: build the INSERT with placeholders for each
column (id, model_name, provider_id, instance_id, model_type, status,
create_time, create_date, update_time, update_date) and pass a list of parameter
tuples for the batch to a safe execute_many/execute method on self.db instead of
concatenating values into the SQL string, and remove manual quote-escaping
(model_name_escaped/model_type_escaped) so values are bound as parameters.
- Around line 822-841: The CREATE TABLE in create_target_table defines
tenant_model with a trailing comma after the last index definition which causes
a MySQL syntax error; open the create_sql string in create_target_table and
remove the extra comma after "INDEX idx_instance_id (instance_id)," so the
closing parenthesis follows the last definition directly, then keep the rest of
the SQL intact and rerun the migration.
- Around line 1144-1189: The code only flips all_stages_completed for unknown
stages but not when a stage ran but effectively did nothing due to missing
dependencies; update the migration loop that calls stage.check() /
stage.execute() (and the MIGRATION_STAGES entries like TenantModelInstanceStage
and TenantModelStage) so you can detect and mark failed/skipped executions:
either (preferred) change execute() to return a third success flag (rows,
tables, success) and set all_stages_completed = False when success is False, or
(if you cannot change signatures) treat a post-check execute() result of rows ==
0 and tables == [] (when stage.check() was True and not create_table_only) as an
incomplete stage and set all_stages_completed = False before accumulating stats;
ensure this logic is applied before calling db.set_database_version and
references stage.check(), stage.execute(), all_stages_completed,
mark_database_version_on_success, and db.set_database_version.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 8659c93f-c50f-40af-aa3c-9719a5005944
📒 Files selected for processing (3)
docker/entrypoint.shdocker/launch_backend_service.shtools/scripts/mysql_migration.py
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #15549 +/- ##
=======================================
Coverage 93.16% 93.16%
=======================================
Files 10 10
Lines 717 717
Branches 118 118
=======================================
Hits 668 668
Misses 29 29
Partials 20 20 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
What problem does this PR solve?
refine mysql migration version workflow
Type of change