yang_base/database/schema_sync/
sync.rs1use super::super::DatabaseInitializer;
2use super::plan::{plan_locked, report_tables};
3use super::preflight::{format_violations, preflight_locked};
4use super::render::{normalize_definitions, schema_lock_name};
5use super::{SchemaPreflightReport, SchemaSyncChangeKind, SchemaSyncReport};
6use crate::error::BaseError;
7use crate::table::{SchemaColumn, SchemaValidationReport, TableDefinition};
8use sqlx::mysql::MySqlConnection;
9use sqlx::Executor;
10
11const SCHEMA_LOCK_TIMEOUT_SECONDS: i64 = 30;
12
13impl DatabaseInitializer {
14 pub async fn validate_table_definition(
18 &self,
19 table: &TableDefinition,
20 ) -> Result<SchemaValidationReport, BaseError> {
21 #[derive(sqlx::FromRow)]
22 struct ColumnRow {
23 column_name: String,
24 data_type: String,
25 column_type: String,
26 is_nullable: String,
27 character_maximum_length: Option<i64>,
28 column_default: Option<String>,
29 extra: String,
30 }
31
32 let rows: Vec<ColumnRow> = self
33 .db()
34 .query_with_params(
35 "SELECT CAST(COLUMN_NAME AS CHAR) AS column_name, CAST(DATA_TYPE AS CHAR) AS data_type, CAST(COLUMN_TYPE AS CHAR) AS column_type, CAST(IS_NULLABLE AS CHAR) AS is_nullable, CAST(CHARACTER_MAXIMUM_LENGTH AS SIGNED) AS character_maximum_length, CAST(COLUMN_DEFAULT AS CHAR) AS column_default, CAST(EXTRA AS CHAR) AS extra FROM information_schema.columns WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ? ORDER BY ORDINAL_POSITION",
36 vec![serde_json::Value::String(table.name().to_string())],
37 )
38 .await
39 .map_err(BaseError::DatabaseQueryFailed)?;
40 let columns = rows
41 .into_iter()
42 .map(|row| {
43 SchemaColumn::new(
44 row.column_name,
45 row.data_type,
46 row.column_type,
47 row.is_nullable.eq_ignore_ascii_case("YES"),
48 row.character_maximum_length
49 .and_then(|length| u64::try_from(length).ok()),
50 row.column_default,
51 )
52 .with_auto_increment(
53 row.extra
54 .split_whitespace()
55 .any(|part| part.eq_ignore_ascii_case("auto_increment")),
56 )
57 })
58 .collect::<Vec<_>>();
59 Ok(table.validate_schema(&columns))
60 }
61
62 pub async fn plan_table_definitions(
67 &self,
68 definitions: &[&TableDefinition],
69 ) -> Result<SchemaSyncReport, BaseError> {
70 let definitions = normalize_definitions(definitions)?;
71 if definitions.is_empty() {
72 return Ok(SchemaSyncReport::default());
73 }
74 let mut connection = self
75 .db()
76 .pool()
77 .acquire()
78 .await
79 .map_err(|error| BaseError::DatabaseConnectionDbError(error.into()))?;
80 let plans = plan_locked(&mut connection, &definitions).await?;
81 Ok(SchemaSyncReport {
82 tables: report_tables(&definitions),
83 changes: plans.into_iter().flat_map(|plan| plan.changes).collect(),
84 })
85 }
86
87 pub async fn preflight_table_definitions(
89 &self,
90 definitions: &[&TableDefinition],
91 ) -> Result<SchemaPreflightReport, BaseError> {
92 let definitions = normalize_definitions(definitions)?;
93 if definitions.is_empty() {
94 return Ok(SchemaPreflightReport::default());
95 }
96 let mut connection = self
97 .db()
98 .pool()
99 .acquire()
100 .await
101 .map_err(|error| BaseError::DatabaseConnectionDbError(error.into()))?;
102 let plans = plan_locked(&mut connection, &definitions).await?;
103 let violations = preflight_locked(&mut connection, &definitions, &plans).await?;
104 Ok(SchemaPreflightReport {
105 plan: SchemaSyncReport {
106 tables: report_tables(&definitions),
107 changes: plans
108 .iter()
109 .flat_map(|plan| plan.changes.iter().cloned())
110 .collect(),
111 },
112 violations,
113 })
114 }
115
116 pub async fn sync_table_definitions(
118 &self,
119 definitions: &[&TableDefinition],
120 ) -> Result<SchemaSyncReport, BaseError> {
121 let definitions = normalize_definitions(definitions)?;
122 if definitions.is_empty() {
123 return Ok(SchemaSyncReport::default());
124 }
125
126 let mut connection = self
127 .db()
128 .pool()
129 .acquire()
130 .await
131 .map_err(|error| BaseError::DatabaseConnectionDbError(error.into()))?;
132 let database_name: Option<String> = sqlx::query_scalar("SELECT DATABASE()")
133 .fetch_one(&mut *connection)
134 .await
135 .map_err(|error| BaseError::DatabaseQueryFailed(error.into()))?;
136 let database_name = database_name.ok_or_else(|| {
137 BaseError::DatabaseInitFailed("当前 MySQL 连接没有选定数据库".to_string())
138 })?;
139 let lock_name = schema_lock_name(&database_name);
140 let acquired: Option<i64> = sqlx::query_scalar("SELECT GET_LOCK(?, ?)")
141 .bind(&lock_name)
142 .bind(SCHEMA_LOCK_TIMEOUT_SECONDS)
143 .fetch_one(&mut *connection)
144 .await
145 .map_err(|error| BaseError::DatabaseQueryFailed(error.into()))?;
146 if acquired != Some(1) {
147 return Err(BaseError::DatabaseInitFailed(format!(
148 "等待 schema 同步锁超时: {lock_name}"
149 )));
150 }
151
152 let result = sync_locked(&mut connection, &definitions).await;
153 let release_result: Result<Option<i64>, sqlx::Error> =
154 sqlx::query_scalar("SELECT RELEASE_LOCK(?)")
155 .bind(&lock_name)
156 .fetch_one(&mut *connection)
157 .await;
158
159 match (result, release_result) {
160 (Err(error), _) => Err(error),
161 (Ok(_), Err(error)) => Err(BaseError::DatabaseQueryFailed(error.into())),
162 (Ok(report), Ok(Some(1))) => Ok(report),
163 (Ok(_), Ok(_)) => Err(BaseError::DatabaseInitFailed(format!(
164 "schema 同步锁释放失败: {lock_name}"
165 ))),
166 }
167 }
168}
169
170async fn sync_locked(
171 connection: &mut MySqlConnection,
172 definitions: &[&TableDefinition],
173) -> Result<SchemaSyncReport, BaseError> {
174 let mut report = SchemaSyncReport {
175 tables: report_tables(definitions),
176 changes: Vec::new(),
177 };
178
179 let plans = plan_locked(connection, definitions).await?;
180 let violations = preflight_locked(connection, definitions, &plans).await?;
181 if !violations.is_empty() {
182 return Err(BaseError::DatabaseInitFailed(format_violations(
183 &violations,
184 )));
185 }
186 for foreign_key_phase in [false, true] {
187 for plan in &plans {
188 for (statement, change) in plan.statements.iter().zip(&plan.changes) {
189 if (change.kind == SchemaSyncChangeKind::AddedForeignKey) != foreign_key_phase {
190 continue;
191 }
192 connection
193 .execute(sqlx::query(statement))
194 .await
195 .map_err(|error| BaseError::DatabaseExecuteFailed(error.into()))?;
196 tracing::info!(
197 table = %change.table,
198 object = %change.object,
199 kind = ?change.kind,
200 "数据库 schema 已同步"
201 );
202 report.changes.push(change.clone());
203 }
204 }
205 }
206
207 Ok(report)
208}