1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
use std::io;
use easy_sqlx_utils::ternary;
use crate::sql::schema::{column::Column, index::Index};
use crate::sql::utils::quote::{ always_reserve, Quoter};
const DEFAULT_SCHEMA: &str = "public";
pub struct Context {
default_schema: String,
pub quoter: Quoter,
}
impl Default for Context {
fn default() -> Self {
Self {
default_schema: DEFAULT_SCHEMA.to_owned(),
#[cfg(feature = "postgres")]
quoter: Quoter::new(b'\"', b'\"', always_reserve),
}
}
}
impl Context {
pub fn new(schema: String) -> Self {
let mut s = Self::default();
if !schema.is_empty() {
s.default_schema = schema;
}
s
}
// pub fn with_schema(default_schema: String) -> Self {
// let mut ctx = Self::default();
// ctx.default_schema = default_schema;
// ctx
// }
pub fn quote(&self, str: &String) -> String {
self.quoter.quote(str)
}
pub fn get_default_schema(&self) -> String {
self.default_schema.clone()
}
pub fn table_name_with_schema(&self, name: &String) -> String {
if !self.default_schema.is_empty() && !name.contains(".") {
return format!("{}.{}", self.default_schema, name);
}
name.clone()
}
pub fn is_table_name_equal(&self, table1: &String, table2: &String) -> bool {
self.table_name_with_schema(table1).to_uppercase()
== self.table_name_with_schema(table2).to_uppercase()
}
pub fn sql_column(
&self,
col: &Column,
inline_pk: bool,
auto_incr_str: Option<&str>,
fn_sql_type: fn(col: &Column) -> String,
) -> String {
let mut sql = String::new();
// 字段名称
self.quoter.quote_to(&mut sql, &col.get_column_name());
// if err := bd.Quoter().QuoteTo(&sql, col.FieldName()); err != nil {
// return "", err
// }
sql.push(' ');
// if err := sql.WriteByte(' '); err != nil {
// return "", err
// }
// 数据类型
let sql_type = fn_sql_type(col);
sql.push_str(&sql_type);
sql.push(' ');
// sqlType := bd.SQLType(col)
// if _, err := sql.WriteString(sqlType); err != nil {
// return "", err
// }
// if err := sql.WriteByte(' '); err != nil {
// return "", err
// }
if inline_pk && col.pk {
// 只有一个字段是主键,且该字段是主键
sql.push_str("PRIMARY KEY ");
// if _, err := sql.WriteString("PRIMARY KEY "); err != nil {
// return "", err
// }
// if col.IsAutoIncrement {
// if _, err := sql.WriteString(bd.AutoIncrStr()); err != nil {
// return "", err
// }
// if err := sql.WriteByte(' '); err != nil {
// return "", err
// }
// }
}
if col.autoincr {
// 该字段是自增类型
if let Some(incr) = auto_incr_str {
sql.push_str(incr);
sql.push(' ');
}
}
if let Some(def) = &col.default {
sql.push_str("DEFAULT ");
sql.push_str(&def.to_string());
sql.push_str(" ");
// if col.typ.name == sql_types::VARCHAR
// || (col.typ.name == sql_types::CHAR && col.typ.fixed_len.is_none())
// || col.typ.name == sql_types::TEXT
// {
// // 文本类型
// // 这里需要改代码
// sql.push_str("DEFAULT ('') ");
// } else {
// sql.push_str("DEFAULT ");
// sql.push_str(&def.to_string());
// sql.push_str(" ");
// }
}
// else if col.Default != "" {
// if _, err := sql.WriteString("DEFAULT "); err != nil {
// return "", err
// }
// if _, err := sql.WriteString(col.Default); err != nil {
// return "", err
// }
// if err := sql.WriteByte(' '); err != nil {
// return "", err
// }
// }
if col.nullable {
sql.push_str("NULL ");
} else {
sql.push_str("NOT NULL ");
}
// if col.Nullable {
// if _, err := sql.WriteString("NULL "); err != nil {
// return "", err
// }
// } else {
// if _, err := sql.WriteString("NOT NULL "); err != nil {
// return "", err
// }
// }
sql
// return sql.String(), nil
}
pub fn sql_add_column(
&self,
table_name: &String,
column: &Column,
auto_incr_str: Option<&str>,
fn_sql_type: fn(col: &Column) -> String,
) -> String {
let col_def = self.sql_column(column, false, auto_incr_str, fn_sql_type);
format!(
"ALTER TABLE {} ADD COLUMN {col_def}",
self.quote(&self.table_name_with_schema(table_name))
)
}
pub fn sql_drop_column(&self, table_name: &String, column_name: &String) -> String {
format!(
"ALTER TABLE {} DROP COLUMN IF EXISTS {}",
self.quote(&self.table_name_with_schema(table_name)),
self.quote(column_name)
)
}
pub fn sql_alter_column(
&self,
table_name: &String,
old: &Column,
new: &Column,
fn_sql_type: fn(col: &Column) -> String,
ignore_default: bool,
) -> io::Result<Vec<String>> {
let table = self.quote(&self.table_name_with_schema(table_name));
let column = old.get_column_name();
let mut sqls = vec![];
if fn_sql_type(old) != fn_sql_type(new) {
// 类型发生变化
if new.typ.name == old.typ.name {
// 类型名称没有变化,大概是字符串长度发生变化
// ALTER TABLE table_name ALTER COLUMN column_name TYPE character_type(length);
if let Some(len) = new.typ.len {
sqls.push(format!(
"ALTER TABLE {table} ALTER COLUMN {column} TYPE character_type({len})"
));
} else {
return Err(io::Error::new(
io::ErrorKind::Other,
format!("字符字段必须有长度: {column} on {table}"),
));
}
} else {
// ALTER TABLE table_name ALTER COLUMN column_name TYPE new_data_type;
let sql_type = fn_sql_type(new);
sqls.push(format!(
"ALTER TABLE {table} ALTER COLUMN {column} TYPE {sql_type}"
));
}
}
if !ignore_default {
if old.default != new.default {
if let Some(def) = &new.default {
// ALTER TABLE table_name ALTER COLUMN column_name SET DEFAULT default_value;
sqls.push(format!(
"ALTER TABLE {table} ALTER COLUMN {column} SET DEFAULT {def}"
));
} else {
// ALTER TABLE table_name ALTER COLUMN column_name DROP DEFAULT;
sqls.push(format!(
"ALTER TABLE {table} ALTER COLUMN {column} DROP DEFAULT"
));
}
}
}
if old.nullable != new.nullable {
if new.nullable {
// ALTER TABLE table_name ALTER COLUMN column_name DROP NOT NULL;
sqls.push(format!(
"ALTER TABLE {table} ALTER COLUMN {column} DROP NOT NULL"
));
} else {
// ALTER TABLE table_name ALTER COLUMN column_name SET NOT NULL;
sqls.push(format!(
"ALTER TABLE {table} ALTER COLUMN {column} SET NOT NULL"
));
}
}
// let col_def = self.sql_column(column, false, auto_incr_str);
// format!(
// "ALTER TABLE {} ALTER COLUMN {col_def}",
// self.quote(&self.table_name_with_schema(table_name))
// )
Ok(sqls)
}
pub fn sql_drop_table(&self, table_name: &String) -> String {
format!(
"DROP TABLE IF EXISTS {}",
self.quote(&self.table_name_with_schema(table_name))
)
}
pub fn sql_create_index(&self, table_name: &String, index: &Index) -> Option<String> {
if index.columns.is_empty() {
return None;
}
let unique = ternary!(index.unique, " UNIQUE", ""); // if index.unique { " UNIQUE" } else { "" };
Some(format!(
"CREATE{unique} INDEX {} ON {} ({})",
self.quote(&index.name),
self.quote(&self.table_name_with_schema(table_name)),
index.columns.join(",")
))
}
pub fn sql_drop_index(&self, index_name_with_schema: &String) -> String {
format!(
"DROP INDEX IF EXISTS {}",
self.quote(&self.table_name_with_schema(index_name_with_schema))
)
}
}