1use super::column::{self, Column};
4use super::enums::{ColumnType, ParameterDirection, TriggerEvent, TriggerTiming};
5use super::feature;
6use super::table::{self, ForeignKey, Table};
7use super::{Schema, base};
8use crate::builder::{AnyBuilder, Executor, Statement};
9use crate::error::{Error, Result};
10
11#[derive(Clone, Default)]
42pub struct MySql {
43 executor: Option<Executor>,
44}
45
46impl std::fmt::Debug for MySql {
47 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
48 f.debug_struct("MySql").field("executor", &self.executor.is_some()).finish()
49 }
50}
51
52impl MySql {
53 pub fn new() -> Self {
57 MySql::default()
58 }
59
60 pub fn change_column(&self, table: &str, old_name: &str, new_name: &str, kind: &str) -> Result<Statement> {
65 base::plain(
66 self,
67 format!(
68 "ALTER TABLE {} CHANGE COLUMN {} {} {kind}",
69 self.quote(table)?,
70 self.quote_literal(old_name)?,
71 self.quote_literal(new_name)?
72 ),
73 )
74 }
75
76 pub fn modify_column(&self, table: &str, name: &str, kind: &str) -> Result<Statement> {
81 base::plain(self, format!("ALTER TABLE {} MODIFY {} {kind}", self.quote(table)?, self.quote_literal(name)?))
82 }
83}
84
85impl Schema for MySql {
86 fn executor(&self) -> Option<&Executor> {
87 self.executor.as_ref()
88 }
89
90 fn set_executor(&mut self, executor: Executor) -> &mut Self {
91 self.executor = Some(executor);
92 self
93 }
94
95 fn quote(&self, identifier: &str) -> Result<String> {
96 crate::quote(identifier, '`')
97 }
98
99 fn quote_literal(&self, identifier: &str) -> Result<String> {
100 crate::quote_literal(identifier, '`')
101 }
102
103 fn compile_column_type(&self, column: &Column<Self>) -> Result<String> {
104 let c = &column.def;
105 let srid = |kind: &str| match c.srid {
106 Some(srid) => format!("{kind} SRID {srid}"),
107 None => kind.to_owned(),
108 };
109 let precise = |kind: &str| match c.precision {
110 Some(p) if p != 0 => format!("{kind}({p})"),
111 _ => kind.to_owned(),
112 };
113 Ok(match c.kind {
114 ColumnType::String | ColumnType::Varchar | ColumnType::Relationship => {
115 format!("VARCHAR({})", c.length.unwrap_or(255))
116 }
117 ColumnType::Text => "TEXT".into(),
118 ColumnType::MediumText => "MEDIUMTEXT".into(),
119 ColumnType::LongText => "LONGTEXT".into(),
120 ColumnType::TinyInteger => "TINYINT".into(),
121 ColumnType::SmallInteger | ColumnType::SmallSerial => "SMALLINT".into(),
122 ColumnType::Integer | ColumnType::Serial => "INT".into(),
123 ColumnType::BigInteger | ColumnType::Id | ColumnType::BigSerial => "BIGINT".into(),
124 ColumnType::Float | ColumnType::Double => "DOUBLE".into(),
125 ColumnType::Decimal => format!("DECIMAL({}, {})", c.precision.unwrap_or(10), c.scale.unwrap_or(0)),
126 ColumnType::Boolean => "TINYINT(1)".into(),
127 ColumnType::Datetime => precise("DATETIME"),
128 ColumnType::Timestamp => precise("TIMESTAMP"),
129 ColumnType::Json | ColumnType::Object => "JSON".into(),
130 ColumnType::Binary => "BLOB".into(),
131 ColumnType::Enum => {
132 let values = c.enum_values.iter().map(|v| self.literal().quote(v)).collect::<Result<Vec<_>>>()?;
133 format!("ENUM({})", values.join(","))
134 }
135 ColumnType::Point => srid("POINT"),
136 ColumnType::Linestring => srid("LINESTRING"),
137 ColumnType::Polygon => srid("POLYGON"),
138 ColumnType::Uuid => "CHAR(36)".into(),
139 ColumnType::Uuid7 => "VARCHAR(36)".into(),
140 ColumnType::Vector => return Err(Error::Unsupported("Vector type is not supported in MySQL.".into())),
141 ColumnType::Array | ColumnType::Tuple => {
142 return Err(Error::Unsupported("Array/Tuple column types are not supported in MySQL.".into()));
143 }
144 })
145 }
146
147 fn compile_auto_increment(&self) -> &'static str {
148 "AUTO_INCREMENT"
149 }
150
151 fn compile_create_suffix(&self, table: &Table<Self>) -> String {
152 feature::Partitioning::compile_create_partitioning(self, table)
153 }
154}
155
156impl column::AutoIncrement for MySql {}
157impl column::Collation for MySql {}
158impl column::Comment for MySql {}
159impl column::Generated for MySql {}
160impl column::Positioning for MySql {}
161impl column::Srid for MySql {}
162impl column::Unique for MySql {}
163impl column::VirtualGenerated for MySql {}
164impl table::Serial for MySql {}
165impl table::Checks for MySql {}
166impl table::ColumnAlterations for MySql {}
167impl table::CompositePrimary for MySql {}
168impl table::InlineForeignKey for MySql {}
169impl table::ForeignKeys for MySql {}
170impl table::FulltextSpatialIndex for MySql {}
171impl table::StandardPartitioning for MySql {}
172
173impl feature::ForeignKeys for MySql {
174 fn add_foreign_key(&self, table: &str, name: &str, key: &ForeignKey) -> Result<Statement> {
175 base::add_foreign_key(self, table, name, key)
176 }
177
178 fn drop_foreign_key(&self, table: &str, name: &str) -> Result<Statement> {
179 base::plain(self, format!("ALTER TABLE {} DROP FOREIGN KEY {}", self.quote(table)?, self.quote(name)?))
180 }
181}
182
183impl feature::Procedures for MySql {
184 fn create_procedure(
185 &self,
186 name: &str,
187 params: &[(ParameterDirection, &str, &str)],
188 body: &str,
189 ) -> Result<Statement> {
190 base::create_procedure(self, name, params, body)
191 }
192
193 fn drop_procedure(&self, name: &str) -> Result<Statement> {
194 base::plain(self, format!("DROP PROCEDURE {}", self.quote(name)?))
195 }
196}
197
198impl feature::Triggers for MySql {
199 fn create_trigger(
200 &self,
201 name: &str,
202 table: &str,
203 timing: TriggerTiming,
204 event: TriggerEvent,
205 body: &str,
206 ) -> Result<Statement> {
207 base::create_trigger(self, name, table, timing, event, body)
208 }
209
210 fn drop_trigger(&self, name: &str, _table: Option<&str>) -> Result<Statement> {
211 base::plain(self, format!("DROP TRIGGER {}", self.quote(name)?))
212 }
213}
214
215impl feature::TableComments for MySql {
216 fn comment_on_table(&self, table: &str, comment: &str) -> Result<Statement> {
217 base::plain(self, format!("ALTER TABLE {} COMMENT = {}", self.quote(table)?, self.literal().quote(comment)?))
218 }
219}
220
221impl feature::CreatePartition for MySql {
222 fn create_partition(&self, parent: &str, name: &str, expression: &str) -> Result<Statement> {
223 base::plain(
224 self,
225 format!("ALTER TABLE {} ADD PARTITION (PARTITION {} {expression})", self.quote(parent)?, self.quote(name)?),
226 )
227 }
228}
229
230impl feature::DropPartition for MySql {
231 fn drop_partition(&self, table: &str, name: &str) -> Result<Statement> {
232 base::plain(self, format!("ALTER TABLE {} DROP PARTITION {}", self.quote(table)?, self.quote(name)?))
233 }
234}
235
236impl feature::Views for MySql {
237 fn create_view(&self, name: &str, query: &mut dyn AnyBuilder) -> Result<Statement> {
238 base::create_view(self, "CREATE VIEW", name, query)
239 }
240
241 fn drop_view(&self, name: &str) -> Result<Statement> {
242 base::plain(self, format!("DROP VIEW {}", self.quote(name)?))
243 }
244}
245
246impl feature::ReplaceView for MySql {
247 fn create_or_replace_view(&self, name: &str, query: &mut dyn AnyBuilder) -> Result<Statement> {
248 base::create_view(self, "CREATE OR REPLACE VIEW", name, query)
249 }
250}
251
252impl feature::Databases for MySql {
253 fn create_database(&self, name: &str) -> Result<Statement> {
254 base::plain(self, format!("CREATE DATABASE {} /*!40100 DEFAULT CHARACTER SET utf8mb4 */", self.quote(name)?))
255 }
256
257 fn drop_database(&self, name: &str) -> Result<Statement> {
258 base::plain(self, format!("DROP DATABASE {}", self.quote(name)?))
259 }
260}
261
262impl feature::RenameIndex for MySql {
263 fn rename_index(&self, table: &str, from: &str, to: &str) -> Result<Statement> {
264 base::plain(
265 self,
266 format!("ALTER TABLE {} RENAME INDEX {} TO {}", self.quote(table)?, self.quote(from)?, self.quote(to)?),
267 )
268 }
269}
270
271impl feature::AnalyzeTable for MySql {
272 fn analyze_table(&self, table: &str) -> Result<Statement> {
273 base::plain(self, format!("ANALYZE TABLE {}", self.quote(table)?))
274 }
275}
276
277impl feature::Partitioning for MySql {
278 fn compile_create_partitioning(&self, table: &Table<Self>) -> String {
279 base::partitioning(table, true)
280 }
281}