use super::dialect::has_redundant_outer_parentheses;
use super::model::DesiredIndex;
use crate::error::BaseError;
use crate::table::{
CheckConfig, FieldConfig, FieldType, ForeignKeyConfig, TableConfig, MYSQL_MAX_VARCHAR_LENGTH,
};
pub(super) fn render_create_table(
table: &TableConfig,
include_foreign_keys: bool,
) -> Result<String, BaseError> {
let mut fields: Vec<&FieldConfig> = table.fields.values().collect();
fields.sort_by(|left, right| left.name.cmp(&right.name));
let mut definitions = fields
.into_iter()
.map(render_column)
.collect::<Result<Vec<_>, _>>()?;
if !table.primary_keys.is_empty() {
definitions.push(format!(
"PRIMARY KEY ({})",
table
.primary_keys
.iter()
.map(|name| quote_identifier(name))
.collect::<Result<Vec<_>, _>>()?
.join(", ")
));
}
for index in desired_indexes(table)? {
let columns = index
.columns
.iter()
.map(|column| quote_identifier(column))
.collect::<Result<Vec<_>, _>>()?
.join(", ");
let kind = if index.unique { "UNIQUE KEY" } else { "KEY" };
definitions.push(format!(
"{kind} {} ({columns})",
quote_identifier(&index.name)?
));
}
for check in &table.checks {
definitions.push(render_check(check)?);
}
if include_foreign_keys {
for foreign_key in &table.foreign_keys {
definitions.push(render_foreign_key(foreign_key)?);
}
}
Ok(format!(
"CREATE TABLE {} ({}) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci",
quote_identifier(&table.table_name)?,
definitions.join(", ")
))
}
pub(super) fn render_check(check: &CheckConfig) -> Result<String, BaseError> {
Ok(format!(
"CONSTRAINT {} CHECK ({})",
quote_identifier(&check.name)?,
check.expression
))
}
pub(super) fn render_foreign_key(foreign_key: &ForeignKeyConfig) -> Result<String, BaseError> {
let columns = foreign_key
.columns
.iter()
.map(|column| quote_identifier(column))
.collect::<Result<Vec<_>, _>>()?
.join(", ");
let referenced_columns = foreign_key
.referenced_columns
.iter()
.map(|column| quote_identifier(column))
.collect::<Result<Vec<_>, _>>()?
.join(", ");
Ok(format!(
"CONSTRAINT {} FOREIGN KEY ({columns}) REFERENCES {} ({referenced_columns})",
quote_identifier(&foreign_key.name)?,
quote_identifier(&foreign_key.referenced_table)?
))
}
pub(super) fn normalize_check_expression(expression: &str) -> String {
let mut decoded = expression.to_string();
loop {
let next = decoded.replace("\\\\", "\\").replace("\\'", "'");
if next == decoded {
break;
}
decoded = next;
}
let mut normalized = String::with_capacity(decoded.len());
let mut characters = decoded.char_indices().peekable();
while let Some((index, character)) = characters.next() {
if character == '\'' {
normalized.push(character);
let mut escaped = false;
while let Some((_, literal)) = characters.next() {
normalized.push(literal);
if escaped {
escaped = false;
continue;
}
match literal {
'\\' => escaped = true,
'\'' => {
if matches!(characters.peek(), Some((_, '\''))) {
continue;
}
break;
}
_ => {}
}
}
continue;
}
if character == '`' || character.is_ascii_whitespace() {
continue;
}
if character == '_' {
let rest = &decoded[index..];
if let Some(introducer) = ["_utf8mb4", "_utf8"].into_iter().find(|candidate| {
rest.get(..candidate.len())
.is_some_and(|prefix| prefix.eq_ignore_ascii_case(candidate))
&& rest
.get(candidate.len()..)
.is_some_and(|tail| tail.starts_with('\''))
}) {
for _ in 1..introducer.chars().count() {
characters.next();
}
continue;
}
}
normalized.extend(character.to_lowercase());
}
while has_redundant_outer_parentheses(&normalized) {
normalized = normalized[1..normalized.len() - 1].to_string();
}
normalized
}
pub(super) fn render_column(field: &FieldConfig) -> Result<String, BaseError> {
if let Some(type_name) = &field.native_enum {
return Err(BaseError::ConfigError(format!(
"字段 {} 声明了 PostgreSQL 原生枚举类型 {type_name},MySQL 方言不支持",
field.name
)));
}
let sql_type = match &field.field_type {
FieldType::String { max_length } if (1..=MYSQL_MAX_VARCHAR_LENGTH).contains(max_length) => {
format!("VARCHAR({max_length})")
}
FieldType::String { max_length } => {
return Err(BaseError::ConfigError(format!(
"字段 {} 的 VARCHAR 长度必须在 1..={MYSQL_MAX_VARCHAR_LENGTH}: {}",
field.name, max_length
)))
}
FieldType::Integer => "INT".to_string(),
FieldType::BigInt => "BIGINT".to_string(),
FieldType::Float => "FLOAT".to_string(),
FieldType::Double => "DOUBLE".to_string(),
FieldType::Decimal { precision, scale } => format!("DECIMAL({precision},{scale})"),
FieldType::Boolean => "TINYINT(1)".to_string(),
FieldType::Date => "DATE".to_string(),
FieldType::DateTime => "DATETIME".to_string(),
FieldType::Timestamp => "BIGINT".to_string(),
FieldType::Json => "JSON".to_string(),
FieldType::Text => "TEXT".to_string(),
FieldType::Enum { values } => {
if values.is_empty() || values.iter().any(|value| value.is_empty()) {
return Err(BaseError::ConfigError(format!(
"枚举字段 {} 必须声明非空值",
field.name
)));
}
let mut sorted = values.clone();
sorted.sort();
if sorted.windows(2).any(|pair| pair[0] == pair[1]) {
return Err(BaseError::ConfigError(format!(
"枚举字段 {} 包含重复值",
field.name
)));
}
format!(
"ENUM({})",
values
.iter()
.map(|value| quote_string(value))
.collect::<Vec<_>>()
.join(", ")
)
}
FieldType::Uuid => "CHAR(36)".to_string(),
FieldType::Bytes => "BLOB".to_string(),
FieldType::Array(_) => {
return Err(BaseError::ConfigError(format!(
"字段 {} 的类型 {} 在 MySQL 方言下不支持:MySQL 没有数组类型",
field.name,
field.field_type.display_name()
)))
}
};
let mut definition = format!(
"{} {sql_type} {}",
quote_identifier(&field.name)?,
if field.required { "NOT NULL" } else { "NULL" }
);
if field.auto_increment {
definition.push_str(" AUTO_INCREMENT");
}
if let Some(default) = &field.default_value {
if default.is_null() && field.required {
return Err(BaseError::ConfigError(format!(
"必填字段 {} 不能声明 NULL 默认值",
field.name
)));
}
if matches!(
field.field_type,
FieldType::Text | FieldType::Json | FieldType::Bytes | FieldType::Array(_)
) {
return Err(BaseError::ConfigError(format!(
"TEXT/JSON/BYTES/ARRAY 字段 {} 不自动生成数据库默认值",
field.name
)));
}
if !default.is_null() {
field.field_type.validate(&field.name, default)?;
}
definition.push_str(" DEFAULT ");
definition.push_str(&render_default(default)?);
}
Ok(definition)
}
fn render_default(value: &serde_json::Value) -> Result<String, BaseError> {
match value {
serde_json::Value::Null => Ok("NULL".to_string()),
serde_json::Value::Bool(value) => Ok(if *value { "1" } else { "0" }.to_string()),
serde_json::Value::Number(value) => Ok(value.to_string()),
serde_json::Value::String(value) => Ok(quote_string(value)),
serde_json::Value::Array(_) | serde_json::Value::Object(_) => Err(BaseError::ConfigError(
"数据库字段默认值只支持 null/bool/number/string".to_string(),
)),
}
}
pub(super) fn desired_indexes(table: &TableConfig) -> Result<Vec<DesiredIndex>, BaseError> {
let mut desired = Vec::new();
for (unique, indexes) in [
(true, table.unique_indexes.as_slice()),
(false, table.indexes.as_slice()),
] {
for index in indexes {
if index.nulls_not_distinct {
return Err(BaseError::ConfigError(format!(
"表 {} 的索引声明了 PostgreSQL 专属的 NULLS NOT DISTINCT,MySQL 不支持",
table.table_name
)));
}
if !index.expressions.is_empty() || index.predicate.is_some() {
return Err(BaseError::ConfigError(format!(
"表 {} 的索引声明了 PostgreSQL 专属的表达式键/部分索引谓词,MySQL 不支持",
table.table_name
)));
}
if index.fields.is_empty() {
return Err(BaseError::ConfigError(format!(
"表 {} 包含空索引",
table.table_name
)));
}
for field in &index.fields {
if !table.fields.contains_key(field) {
return Err(BaseError::ConfigError(format!(
"表 {} 的索引引用未声明字段: {}",
table.table_name, field
)));
}
}
let prefix = if unique { "uk" } else { "idx" };
let name = index.name.clone().unwrap_or_else(|| {
format!("{prefix}_{}_{}", table.table_name, index.fields.join("_"))
});
if name.len() > 64 {
return Err(BaseError::ConfigError(format!(
"索引名超过 MySQL 64 字符限制,请显式命名: {name}"
)));
}
quote_identifier(&name)?;
desired.push(DesiredIndex {
name,
unique,
columns: index.fields.clone(),
expressions: Vec::new(),
predicate: None,
nulls_not_distinct: false,
});
}
}
Ok(desired)
}
pub(super) fn quote_identifier(identifier: &str) -> Result<String, BaseError> {
yang_db::mysql::quote_identifier(identifier).map_err(|error| {
BaseError::ConfigError(format!("非法数据库标识符 {identifier:?}: {error}"))
})
}
pub(super) fn quote_string(value: &str) -> String {
format!("'{}'", value.replace('\\', "\\\\").replace('\'', "''"))
}