Skip to main content

sql_builder/backend/mysql/
query.rs

1use super::*;
2
3/// One [`QueryBuilder`] impl for MySQL and for MariaDB, each passing the
4/// methods where its server differs.
5macro_rules! mysql_family_query_builder {
6    ($builder:ty { $($own:tt)* }) => {
7        impl QueryBuilder for $builder {
8            $($own)*
9
10            fn lexer_dialect(&self) -> crate::lexer::Dialect {
11                crate::lexer::Dialect::MySql
12            }
13
14            fn prepare_select_distinct(
15                &self,
16                select_distinct: &SelectDistinct,
17                sql: &mut impl SqlWriter,
18            ) -> Result<(), RenderError> {
19                match select_distinct {
20                    SelectDistinct::All => sql.write_str("ALL").unwrap(),
21                    SelectDistinct::Distinct => sql.write_str("DISTINCT").unwrap(),
22                    SelectDistinct::DistinctRow => sql.write_str("DISTINCTROW").unwrap(),
23                    SelectDistinct::DistinctOn(_) => {
24                        return Err(RenderError::Unsupported("MySQL has no DISTINCT ON".into()));
25                    }
26                };
27                Ok(())
28            }
29
30            fn prepare_function_filter(
31                &self,
32                _: &Condition,
33                _: &mut impl SqlWriter,
34            ) -> Result<(), RenderError> {
35                Err(RenderError::Unsupported(
36                    "MySQL and MariaDB have no FILTER on an aggregate; put a CASE WHEN in its argument".into(),
37                ))
38            }
39
40            fn prepare_select_into(
41                &self,
42                _: &SelectInto,
43                _: &mut impl SqlWriter,
44            ) -> Result<(), RenderError> {
45                Err(RenderError::Unsupported(
46                    "MySQL has no SELECT INTO a table".into(),
47                ))
48            }
49
50            fn prepare_with_query_clause_materialization(
51                &self,
52                _: &CommonTableExpression,
53                _: &mut impl SqlWriter,
54            ) -> Result<(), RenderError> {
55                // MySQL doesn't support declaring materialization in SQL for with query.
56                Ok(())
57            }
58
59            fn prepare_update_join(
60                &self,
61                from: &[TableRef],
62                condition: &ConditionHolder,
63                sql: &mut impl SqlWriter,
64            ) -> Result<(), RenderError> {
65                if from.is_empty() {
66                    return Ok(());
67                }
68
69                for table in from {
70                    sql.write_str(" JOIN ").unwrap();
71                    expressions::prepare_table_ref(self, table, sql)?;
72                }
73
74                conflict::prepare_condition(self, condition, "ON", sql)?;
75                Ok(())
76            }
77
78            fn prepare_update_from(
79                &self,
80                _: &[TableRef],
81                _: &mut impl SqlWriter,
82            ) -> Result<(), RenderError> {
83                Ok(())
84            }
85
86            fn prepare_update_column(
87                &self,
88                table: &Option<Box<TableRef>>,
89                from: &[TableRef],
90                column: &DynIden,
91                sql: &mut impl SqlWriter,
92            ) -> Result<(), RenderError> {
93                use std::ops::Deref;
94
95                // A joined table may share the column's name, so the target is named:
96                // by its alias when it has one, which then replaces its name.
97                if !from.is_empty()
98                    && let Some(table) = table
99                    && let TableRef::Table(name, alias) = table.deref()
100                {
101                    let target = match alias {
102                        Some(alias) => TableName(None, alias.clone()),
103                        None => name.clone(),
104                    };
105                    let column_name = ColumnName(Some(target), column.clone());
106                    expressions::prepare_column_ref(self, &ColumnRef::Column(column_name), sql)?;
107                    return Ok(());
108                }
109                self.prepare_iden(column, sql);
110                Ok(())
111            }
112
113            fn prepare_update_condition(
114                &self,
115                from: &[TableRef],
116                condition: &ConditionHolder,
117                sql: &mut impl SqlWriter,
118            ) -> Result<(), RenderError> {
119                if !from.is_empty() {
120                    return Ok(());
121                }
122                conflict::prepare_condition(self, condition, "WHERE", sql)?;
123                Ok(())
124            }
125
126            fn prepare_join_type(
127                &self,
128                join_type: &JoinType,
129                sql: &mut impl SqlWriter,
130            ) -> Result<(), RenderError> {
131                match join_type {
132                    JoinType::FullOuterJoin => {
133                        return Err(RenderError::Unsupported(
134                            "Mysql does not support FULL OUTER JOIN".into(),
135                        ));
136                    }
137                    JoinType::StraightJoin => sql.write_str("STRAIGHT_JOIN").unwrap(),
138                    _ => functions::prepare_join_type_common(self, join_type, sql)?,
139                }
140                Ok(())
141            }
142
143            fn prepare_order_expr(
144                &self,
145                order_expr: &OrderExpr,
146                sql: &mut impl SqlWriter,
147            ) -> Result<(), RenderError> {
148                match order_expr.nulls {
149                    None => (),
150                    Some(NullOrdering::Last) => {
151                        self.prepare_expr(&order_expr.expr, sql)?;
152                        sql.write_str(" IS NULL ASC, ").unwrap()
153                    }
154                    Some(NullOrdering::First) => {
155                        self.prepare_expr(&order_expr.expr, sql)?;
156                        sql.write_str(" IS NULL DESC, ").unwrap()
157                    }
158                }
159                if !matches!(order_expr.order, Order::Field(_)) {
160                    self.prepare_expr(&order_expr.expr, sql)?;
161                }
162                functions::prepare_order(self, order_expr, sql)?;
163                Ok(())
164            }
165
166            fn prepare_select_limit_offset(
167                &self,
168                select: &SelectStatement,
169                sql: &mut impl SqlWriter,
170            ) -> Result<(), RenderError> {
171                prepare_limit_offset(self, select, SqlDialect::open_limit(self), sql)
172            }
173
174            fn prepare_on_conflict_target(
175                &self,
176                _: &OnConflictTarget,
177                _: &mut impl SqlWriter,
178            ) -> Result<(), RenderError> {
179                // MySQL doesn't support declaring ON CONFLICT target.
180                Ok(())
181            }
182
183            fn prepare_on_conflict_action(
184                &self,
185                on_conflict_action: &Option<OnConflictAction>,
186                sql: &mut impl SqlWriter,
187            ) -> Result<(), RenderError> {
188                match on_conflict_action {
189                    Some(OnConflictAction::DoNothing(pk_cols)) => {
190                        if !pk_cols.is_empty() {
191                            self.prepare_on_conflict_do_update_keywords(sql)?;
192                            let mut pk_cols_iter = pk_cols.iter();
193                            join_io!(
194                                pk_cols_iter,
195                                pk_col,
196                                join {
197                                    sql.write_str(", ").unwrap();
198                                },
199                                do {
200                                    self.prepare_iden(pk_col, sql);
201                                    sql.write_str(" = ").unwrap();
202                                    self.prepare_iden(pk_col, sql);
203                                }
204                            );
205                        } else {
206                            return Err(RenderError::Unsupported(
207                                "MySQL has no ON DUPLICATE KEY DO NOTHING; name the key columns with do_nothing_on".into(),
208                            ));
209                        }
210                    }
211                    _ => conflict::prepare_on_conflict_action_common(self, on_conflict_action, sql)?,
212                }
213                Ok(())
214            }
215
216            fn prepare_on_conflict_keywords(&self, sql: &mut impl SqlWriter) -> Result<(), RenderError> {
217                sql.write_str(" ON DUPLICATE KEY").unwrap();
218                Ok(())
219            }
220
221            fn prepare_on_conflict_do_update_keywords(
222                &self,
223                sql: &mut impl SqlWriter,
224            ) -> Result<(), RenderError> {
225                sql.write_str(" UPDATE ").unwrap();
226                Ok(())
227            }
228
229            fn prepare_on_conflict_excluded_table(
230                &self,
231                col: &DynIden,
232                sql: &mut impl SqlWriter,
233            ) -> Result<(), RenderError> {
234                sql.write_str("VALUES(").unwrap();
235                self.prepare_iden(col, sql);
236                sql.write_str(")").unwrap();
237                Ok(())
238            }
239
240            fn prepare_on_conflict_condition(
241                &self,
242                _: &ConditionHolder,
243                _: &mut impl SqlWriter,
244            ) -> Result<(), RenderError> {
245                Ok(())
246            }
247
248            fn prepare_on_conflict_action_condition(
249                &self,
250                condition: &ConditionHolder,
251                _: &mut impl SqlWriter,
252            ) -> Result<(), RenderError> {
253                if condition.is_empty() {
254                    return Ok(());
255                }
256                Err(RenderError::Unsupported(
257                    "MySQL has no WHERE on ON DUPLICATE KEY UPDATE".into(),
258                ))
259            }
260
261            fn random_function(&self) -> &str {
262                "RAND"
263            }
264
265            fn insert_default_keyword(&self) -> &str {
266                "()"
267            }
268        }
269    };
270}
271
272mysql_family_query_builder!(MysqlQueryBuilder {
273    // A table value constructor's rows are `ROW(..)`, which MariaDB refuses.
274    fn values_list_tuple_prefix(&self) -> &str {
275        "ROW"
276    }
277
278    fn prepare_returning(
279        &self,
280        returning: &Option<ReturningClause>,
281        _: &mut impl SqlWriter,
282    ) -> Result<(), RenderError> {
283        match returning {
284            None => Ok(()),
285            Some(_) => Err(RenderError::Unsupported("MySQL has no RETURNING".into())),
286        }
287    }
288
289    // MariaDB orders and limits a joined UPDATE too.
290    fn prepare_update_order_limit(
291        &self,
292        from: &[TableRef],
293        orders: &[OrderExpr],
294        limit: &Option<Value>,
295        sql: &mut impl SqlWriter,
296    ) -> Result<(), RenderError> {
297        if !from.is_empty() && (!orders.is_empty() || limit.is_some()) {
298            return Err(RenderError::Unsupported(
299                "MySQL has no ORDER BY or LIMIT in an UPDATE that joins other tables".into(),
300            ));
301        }
302        self.prepare_mutation_order_limit(orders, limit, sql)
303    }
304
305    // A shared lock is `FOR SHARE`, the form that takes `OF`, `NOWAIT` and
306    // `SKIP LOCKED`; `LOCK IN SHARE MODE` takes none of them.
307    fn prepare_select_lock(
308        &self,
309        lock: &LockClause,
310        sql: &mut impl SqlWriter,
311    ) -> Result<(), RenderError> {
312        if matches!(lock.r#type, LockType::NoKeyUpdate | LockType::KeyShare) {
313            return Err(RenderError::Unsupported(
314                "MySQL has no FOR NO KEY UPDATE or FOR KEY SHARE lock".into(),
315            ));
316        }
317        expressions::prepare_select_lock(self, lock, sql)
318    }
319});
320
321mysql_family_query_builder!(MariaDbDialect {
322    // MariaDB has no `FOR SHARE` and no `OF`: a lock covers every table the
323    // SELECT reads.
324    fn prepare_select_lock(
325        &self,
326        lock: &LockClause,
327        sql: &mut impl SqlWriter,
328    ) -> Result<(), RenderError> {
329        if matches!(lock.r#type, LockType::NoKeyUpdate | LockType::KeyShare) {
330            return Err(RenderError::Unsupported(
331                "MariaDB has no FOR NO KEY UPDATE or FOR KEY SHARE lock".into(),
332            ));
333        }
334        if !lock.tables.is_empty() {
335            return Err(RenderError::Unsupported(
336                "MariaDB has no OF in a row lock; it locks every table the SELECT reads".into(),
337            ));
338        }
339        expressions::prepare_select_lock(self, lock, sql)
340    }
341
342    fn lock_phrase(&self, lock_type: LockType) -> &'static str {
343        match lock_type {
344            LockType::Update => "FOR UPDATE",
345            LockType::NoKeyUpdate => "FOR NO KEY UPDATE",
346            LockType::Share => "LOCK IN SHARE MODE",
347            LockType::KeyShare => "FOR KEY SHARE",
348        }
349    }
350});