drizzle-mysql 0.4.3

A type-safe SQL query builder for Rust
Documentation
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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
//! Typed `MySQL` query builder.
//!
//! Start with [`QueryBuilder::new`]. Each statement has its own builder
//! alias with its clause order: [`SelectBuilder`], [`InsertBuilder`],
//! [`UpdateBuilder`] and [`DeleteBuilder`].
//!
//! Examples in this module use the `drizzle` crate and its macros, which
//! this crate cannot depend on, so they are shown but not compiled here.
//! The workspace's `tests/mysql/builder.rs` compiles and checks the same
//! kinds of query.

use crate::{common::MySQLSchemaType, traits::MySQLTable, values::MySQLValue};
use core::{fmt::Debug, marker::PhantomData};
use drizzle_core::{SQL, ToSQL, Token};

pub use drizzle_core::{BuilderInit, ExecutableState};

macro_rules! mutation_builder_methods {
    (
        $builder:ident,
        prepare: [$($prepare:ty),+ $(,)?],
        order_by: [$($order:ty),+ $(,)?] => $ordered:ty,
        limit: [$($limit:ty),+ $(,)?] => $limited:ty $(,)?
    ) => {
        $(
            impl<'a, S, T, M, R> $builder<'a, S, $prepare, T, M, R> {
                /// Renders this statement as a [`PreparedStatement`](drizzle_core::prepared::PreparedStatement)
                /// whose placeholders are bound in `MySQL`'s positional order.
                #[must_use]
                pub fn prepare(
                    &self,
                ) -> drizzle_core::prepared::PreparedStatement<'a, crate::values::MySQLValue<'a>> {
                    self.prepared_statement()
                }
            }
        )+

        $(
            impl<'a, S, T> $builder<'a, S, $order, T> {
                /// Adds ORDER BY, which sets the order rows are changed in.
                ///
                /// Mostly useful with `limit`. Only columns of the target
                /// table may be used.
                pub fn order_by<O, ScopeProof>(self, order: O) -> $builder<'a, S, $ordered, T>
                where
                    O: drizzle_core::ToSQL<'a, crate::values::MySQLValue<'a>>
                        + drizzle_core::expr::ExprSources,
                    O::Sources: drizzle_core::scope::SourcesIn<
                        drizzle_core::Cons<T, drizzle_core::Nil>,
                        ScopeProof,
                    >,
                {
                    $builder::from_sql(self.sql.append(crate::helpers::order_by(order)))
                }
            }
        )+

        $(
            impl<'a, S, T> $builder<'a, S, $limit, T> {
                /// Adds LIMIT, which caps how many rows are changed.
                ///
                /// # Panics
                ///
                /// Panics when a numeric argument is negative or does not
                /// fit in `usize`.
                #[track_caller]
                pub fn limit<P>(self, limit: P) -> $builder<'a, S, $limited, T>
                where
                    P: drizzle_core::PaginationArg<'a, crate::values::MySQLValue<'a>>,
                {
                    $builder::from_sql(self.sql.append(crate::helpers::limit(limit)))
                }
            }
        )+
    };
}

pub mod cte;
/// Typed MySQL `DELETE` statements.
pub mod delete;
/// Typed MySQL `INSERT` statements.
pub mod insert;
/// Typed MySQL `SELECT` statements.
pub mod select;
/// Typed MySQL `UPDATE` statements.
pub mod update;

pub use cte::{CTEDefinition, CTEView};
pub use delete::{DeleteBuilder, DeleteInitial, DeleteLimitSet, DeleteOrderSet, DeleteWhereSet};
pub use insert::{
    InsertBuilder, InsertColumnsSet, InsertIgnoreSet, InsertInitial, InsertOnDuplicateKeyUpdateSet,
    InsertValuesSet,
};
pub use select::{
    CompletedSelect, ForShare, ForUpdate, IntoSelectQuery, NoWait, SelectBuilder, SelectForSet,
    SelectFromSet, SelectGroupSet, SelectHavingSet, SelectIndexHintSet, SelectInitial,
    SelectJoinSet, SelectLimitSet, SelectOffsetSet, SelectOrderSet, SelectSetOpSet, SelectWhereSet,
    SkipLocked, Wait,
};
pub use update::{
    UpdateBuilder, UpdateInitial, UpdateLimitSet, UpdateOrderSet, UpdateSetClauseSet,
    UpdateWhereSet,
};

/// Builder state after [`QueryBuilder::with`]: the next call starts the
/// statement that uses the common table expressions.
#[derive(Debug, Clone)]
pub struct CTEInit;

/// Type-safe SQL query builder for `MySQL`.
///
/// Start with [`QueryBuilder::new`], then call [`select`](Self::select),
/// [`insert`](Self::insert), [`update`](Self::update),
/// [`delete`](Self::delete) or [`with`](Self::with). Each method returns a
/// builder in a new state that only offers the clauses that may come next,
/// so an out-of-order query does not compile. Call [`ToSQL::to_sql`] for the
/// SQL text and parameters, or `prepare()` for a statement with
/// placeholders. It does not run queries; the `drizzle` crate's `MySQL`
/// drivers do.
///
/// # Type parameters
///
/// - `Schema`: the schema the query runs against.
/// - `State`: which clauses have been added so far.
/// - `Table`: the table the last FROM or JOIN added, or the target table of
///   an INSERT, UPDATE or DELETE.
/// - `Marker`: the selected columns and the tables in scope.
/// - `Row`: the Rust type of one result row.
/// - `Grouped`: the GROUP BY columns.
///
/// # Examples
///
/// ```rust
/// # let _ = r####"
/// use drizzle::core::expr::eq;
/// use drizzle::mysql::{builder::QueryBuilder, prelude::*};
///
/// #[MySQLTable(NAME = "users")]
/// struct Users {
///     #[column(PRIMARY, AUTO_INCREMENT)]
///     id: u64,
///     #[column(VARCHAR(255))]
///     name: String,
///     #[column(DEFAULT = true)]
///     active: bool,
/// }
///
/// #[derive(MySQLSchema)]
/// struct Schema {
///     users: Users,
/// }
///
/// let builder = QueryBuilder::new::<Schema>();
/// let Schema { users } = Schema::new();
/// let query = builder
///     .select(users.name)
///     .from(users)
///     .r#where(eq(users.active, true))
///     .order_by(asc(users.name))
///     .limit(10);
/// assert_eq!(
///     query.to_sql().sql(),
///     "SELECT `users`.`name` FROM `users` WHERE `users`.`active` = ? ORDER BY `users`.`name` ASC LIMIT ?"
/// );
/// # "####;
/// ```
#[derive(Debug, Clone)]
pub struct QueryBuilder<
    'a,
    Schema = (),
    State = (),
    Table = (),
    Marker = (),
    Row = (),
    Grouped = (),
> {
    pub(crate) sql: SQL<'a, MySQLValue<'a>>,
    pub(crate) schema: PhantomData<Schema>,
    pub(crate) state: PhantomData<State>,
    pub(crate) table: PhantomData<Table>,
    pub(crate) marker: PhantomData<Marker>,
    pub(crate) row: PhantomData<Row>,
    pub(crate) grouped: PhantomData<Grouped>,
}

impl<'a, Schema, State, Table, Marker, Row, Grouped> ToSQL<'a, MySQLValue<'a>>
    for QueryBuilder<'a, Schema, State, Table, Marker, Row, Grouped>
where
    State: ExecutableState,
{
    fn to_sql(&self) -> SQL<'a, MySQLValue<'a>> {
        self.sql.clone()
    }

    fn into_sql(self) -> SQL<'a, MySQLValue<'a>> {
        self.sql
    }
}

impl<'a, Schema, State, Table, Marker, Row, Grouped>
    QueryBuilder<'a, Schema, State, Table, Marker, Row, Grouped>
where
    State: ExecutableState,
{
    /// Prepends a [sqlcommenter](https://google.github.io/sqlcommenter/)
    /// comment (`/*...*/`) to the query.
    ///
    /// `/*` and `*/` inside `text` are broken up (`/ *`, `* /`) so the text
    /// cannot end the comment early. An empty `text` leaves the query
    /// unchanged.
    #[must_use]
    pub fn comment(mut self, text: impl AsRef<str>) -> Self {
        let fragment = drizzle_core::sql::comment::<MySQLValue<'a>>(text);
        if !fragment.chunks.is_empty() {
            let existing = core::mem::replace(&mut self.sql, fragment);
            self.sql.append_mut(existing);
        }
        self
    }

    /// Prepends a tag-style [sqlcommenter](https://google.github.io/sqlcommenter/)
    /// comment to the query.
    ///
    /// Each `(key, value)` pair is URL-encoded and written as `key='value'`.
    /// Pairs are sorted and joined with `,`. Pairs with an empty value are
    /// skipped; if none remain, the query is unchanged.
    #[must_use]
    pub fn comment_tags<I, K, V>(mut self, pairs: I) -> Self
    where
        I: IntoIterator<Item = (K, V)>,
        K: AsRef<str>,
        V: AsRef<str>,
    {
        let fragment = drizzle_core::sql::comment_tags::<MySQLValue<'a>, _, _, _>(pairs);
        if !fragment.chunks.is_empty() {
            let existing = core::mem::replace(&mut self.sql, fragment);
            self.sql.append_mut(existing);
        }
        self
    }
}

impl<'a> QueryBuilder<'a> {
    /// Creates a query builder for the schema `S`.
    #[must_use]
    pub const fn new<S>() -> QueryBuilder<'a, S, BuilderInit> {
        QueryBuilder {
            sql: SQL::empty(),
            schema: PhantomData,
            state: PhantomData,
            table: PhantomData,
            marker: PhantomData,
            row: PhantomData,
            grouped: PhantomData,
        }
    }
}

impl<'a, Schema> QueryBuilder<'a, Schema, BuilderInit> {
    /// Starts a `SELECT` with the given columns.
    ///
    /// Pass one column or expression, a tuple of them, or `()` to select
    /// every column of the FROM table (and of joined tables). Call
    /// [`from`](select::SelectBuilder::from) next.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # let _ = r####"
    /// # use drizzle::core::expr::eq;
    /// # use drizzle::mysql::{builder::QueryBuilder, prelude::*};
    /// #
    /// # #[MySQLTable(NAME = "users")]
    /// # struct Users {
    /// #     #[column(PRIMARY, AUTO_INCREMENT)]
    /// #     id: u64,
    /// #     #[column(VARCHAR(255))]
    /// #     name: String,
    /// #     #[column(DEFAULT = true)]
    /// #     active: bool,
    /// # }
    /// #
    /// # #[derive(MySQLSchema)]
    /// # struct Schema {
    /// #     users: Users,
    /// # }
    /// #
    /// # let builder = QueryBuilder::new::<Schema>();
    /// # let Schema { users } = Schema::new();
    /// let query = builder.select(()).from(users);
    /// assert_eq!(
    ///     query.to_sql().sql(),
    ///     "SELECT `users`.`id`, `users`.`name`, `users`.`active` FROM `users`"
    /// );
    /// # "####;
    /// ```
    pub fn select<T>(
        &self,
        columns: T,
    ) -> select::SelectBuilder<'a, Schema, select::SelectInitial, (), T::Marker>
    where
        T: ToSQL<'a, MySQLValue<'a>> + drizzle_core::IntoSelectTarget,
    {
        QueryBuilder::from_sql(crate::helpers::select(columns))
    }

    /// Starts a `SELECT DISTINCT`, which drops duplicate rows.
    pub fn select_distinct<T>(
        &self,
        columns: T,
    ) -> select::SelectBuilder<'a, Schema, select::SelectInitial, (), T::Marker>
    where
        T: ToSQL<'a, MySQLValue<'a>> + drizzle_core::IntoSelectTarget,
    {
        QueryBuilder::from_sql(crate::helpers::select_distinct(columns))
    }

    /// Starts an `INSERT` into `table`.
    ///
    /// Call [`values`](insert::InsertBuilder::values),
    /// [`select`](insert::InsertBuilder::select),
    /// [`columns`](insert::InsertBuilder::columns) or
    /// [`ignore`](insert::InsertBuilder::ignore) next.
    pub fn insert<Table>(
        &self,
        table: Table,
    ) -> insert::InsertBuilder<'a, Schema, insert::InsertInitial, Table>
    where
        Table: MySQLTable<'a>,
    {
        QueryBuilder::from_sql(drizzle_core::helpers::insert::<
            Table,
            MySQLSchemaType,
            MySQLValue<'a>,
        >(&table))
    }

    /// Starts an `UPDATE` of `table`. Call
    /// [`set`](update::UpdateBuilder::set) next.
    pub fn update<Table>(
        &self,
        table: Table,
    ) -> update::UpdateBuilder<'a, Schema, update::UpdateInitial, Table>
    where
        Table: MySQLTable<'a>,
    {
        QueryBuilder::from_sql(crate::helpers::update::<
            Table,
            MySQLSchemaType,
            MySQLValue<'a>,
        >(&table))
    }

    /// Starts a `DELETE` from `table`.
    ///
    /// Without `where`, the statement deletes every row.
    pub fn delete<Table>(
        &self,
        table: Table,
    ) -> delete::DeleteBuilder<'a, Schema, delete::DeleteInitial, Table>
    where
        Table: MySQLTable<'a>,
    {
        QueryBuilder::from_sql(crate::helpers::delete::<
            Table,
            MySQLSchemaType,
            MySQLValue<'a>,
        >(&table))
    }

    /// Starts a WITH clause with one common table expression.
    ///
    /// Build the CTE with [`into_cte`](select::SelectBuilder::into_cte). Add
    /// more with another `.with(..)`, then start a SELECT, UPDATE or DELETE.
    /// For `INSERT ... SELECT`, put the WITH on the inner SELECT instead.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # let _ = r####"
    /// # use drizzle::core::expr::eq;
    /// # use drizzle::mysql::{builder::QueryBuilder, prelude::*};
    /// #
    /// # #[MySQLTable(NAME = "users")]
    /// # struct Users {
    /// #     #[column(PRIMARY, AUTO_INCREMENT)]
    /// #     id: u64,
    /// #     #[column(VARCHAR(255))]
    /// #     name: String,
    /// #     #[column(DEFAULT = true)]
    /// #     active: bool,
    /// # }
    /// #
    /// # #[derive(MySQLSchema)]
    /// # struct Schema {
    /// #     users: Users,
    /// # }
    /// #
    /// # let builder = QueryBuilder::new::<Schema>();
    /// # let Schema { users } = Schema::new();
    /// struct Active;
    /// impl drizzle::core::Tag for Active {
    ///     const NAME: &'static str = "active";
    /// }
    ///
    /// let active = builder
    ///     .select((users.id, users.name))
    ///     .from(users)
    ///     .r#where(eq(users.active, true))
    ///     .into_cte::<Active>();
    /// let query = builder.with(&active).select(active.name).from(&active);
    /// // WITH `active` AS (SELECT ...) SELECT `active`.`name` FROM `active`
    /// # "####;
    /// ```
    pub fn with<C>(&self, cte: &C) -> QueryBuilder<'a, Schema, CTEInit>
    where
        C: CTEDefinition<'a>,
    {
        QueryBuilder::from_sql(SQL::from(Token::WITH).append(cte.cte_definition()))
    }
}

impl<'a, Schema> QueryBuilder<'a, Schema, CTEInit> {
    /// Starts a `SELECT` after the WITH clause.
    pub fn select<T>(
        &self,
        columns: T,
    ) -> select::SelectBuilder<'a, Schema, select::SelectInitial, (), T::Marker>
    where
        T: ToSQL<'a, MySQLValue<'a>> + drizzle_core::IntoSelectTarget,
    {
        QueryBuilder::from_sql(self.sql.clone().append(crate::helpers::select(columns)))
    }

    /// Starts a `SELECT DISTINCT` after the WITH clause.
    pub fn select_distinct<T>(
        &self,
        columns: T,
    ) -> select::SelectBuilder<'a, Schema, select::SelectInitial, (), T::Marker>
    where
        T: ToSQL<'a, MySQLValue<'a>> + drizzle_core::IntoSelectTarget,
    {
        QueryBuilder::from_sql(
            self.sql
                .clone()
                .append(crate::helpers::select_distinct(columns)),
        )
    }

    /// Starts an `UPDATE` after the WITH clause.
    pub fn update<Table>(
        &self,
        table: Table,
    ) -> update::UpdateBuilder<'a, Schema, update::UpdateInitial, Table>
    where
        Table: MySQLTable<'a>,
    {
        QueryBuilder::from_sql(self.sql.clone().append(crate::helpers::update::<
            Table,
            MySQLSchemaType,
            MySQLValue<'a>,
        >(&table)))
    }

    /// Starts a `DELETE` after the WITH clause.
    pub fn delete<Table>(
        &self,
        table: Table,
    ) -> delete::DeleteBuilder<'a, Schema, delete::DeleteInitial, Table>
    where
        Table: MySQLTable<'a>,
    {
        QueryBuilder::from_sql(self.sql.clone().append(crate::helpers::delete::<
            Table,
            MySQLSchemaType,
            MySQLValue<'a>,
        >(&table)))
    }

    #[must_use]
    /// Adds another common table expression to the WITH clause.
    pub fn with<C>(&self, cte: &C) -> Self
    where
        C: CTEDefinition<'a>,
    {
        QueryBuilder::from_sql(
            self.sql
                .clone()
                .push(Token::COMMA)
                .append(cte.cte_definition()),
        )
    }
}

impl<'a, S, State, T, M, R, G> QueryBuilder<'a, S, State, T, M, R, G> {
    pub(crate) fn from_sql(sql: SQL<'a, MySQLValue<'a>>) -> Self {
        Self {
            sql,
            schema: PhantomData,
            state: PhantomData,
            table: PhantomData,
            marker: PhantomData,
            row: PhantomData,
            grouped: PhantomData,
        }
    }

    pub(crate) fn prepared_statement(
        &self,
    ) -> drizzle_core::prepared::PreparedStatement<'a, MySQLValue<'a>> {
        drizzle_core::prepared::prepare_render(&self.sql)
    }
}