drizzle-core 0.2.0

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
use crate::prelude::{Cow, Vec};
use crate::{
    ColumnRef, PaginationArg, SQL, SQLChunk, SQLSchemaType, SQLTable, ToSQL, Token, expr::Expr,
    traits::SQLParam, types::BooleanLike,
};

/// Helper function to create a SELECT statement with the given columns
/// The `LIMIT` MySQL renders before an `OFFSET` that has no limit of its own.
///
/// MySQL has no bare `OFFSET`. Its manual suggests `18446744073709551615`
/// (`u64::MAX`) for "every remaining row", but for a `UNION` MySQL adds the
/// offset to the limit, and `u64::MAX + offset` wraps: the query returns no
/// rows (MySQL 8.0 and 8.4). `i64::MAX` is just as unbounded in practice and
/// leaves room for any offset.
#[doc(hidden)]
pub const MYSQL_UNBOUNDED_LIMIT: &str = "9223372036854775807";

pub fn select<'a, Value, T>(columns: T) -> SQL<'a, Value>
where
    Value: SQLParam,
    T: ToSQL<'a, Value>,
{
    SQL::from(Token::SELECT).append(columns.into_sql())
}

/// Helper function to create a SELECT DISTINCT statement with the given columns
pub fn select_distinct<'a, Value, T>(columns: T) -> SQL<'a, Value>
where
    Value: SQLParam,
    T: ToSQL<'a, Value>,
{
    SQL::from_iter([Token::SELECT, Token::DISTINCT]).append(columns.into_sql())
}

/// Clauses found outside any parentheses of a query used as a set-operation
/// operand.
#[derive(Debug, Default, Clone, Copy)]
struct OperandShape {
    /// `ORDER BY`, `LIMIT`, `OFFSET` or a locking `FOR` clause, which would
    /// otherwise apply to the whole compound (or be rejected before it).
    has_tail: bool,
    /// A `UNION` or `EXCEPT` operator.
    has_union_or_except: bool,
    /// An `INTERSECT` operator.
    has_intersect: bool,
    /// The query opens with a `WITH` clause.
    starts_with_cte: bool,
}

impl OperandShape {
    fn of<V: SQLParam>(sql: &SQL<'_, V>) -> Self {
        let mut shape = Self::default();
        let mut depth = 0usize;
        let mut leading = true;

        for chunk in &sql.chunks {
            match chunk {
                // A sqlcommenter comment may precede the query.
                SQLChunk::Raw(text) if leading && text.trim_start().starts_with("/*") => {
                    continue;
                }
                SQLChunk::Token(Token::LPAREN) => depth += 1,
                SQLChunk::Token(Token::RPAREN) => depth = depth.saturating_sub(1),
                SQLChunk::Token(Token::WITH) if leading => shape.starts_with_cte = true,
                SQLChunk::Token(Token::ORDER | Token::LIMIT | Token::OFFSET | Token::FOR)
                    if depth == 0 =>
                {
                    shape.has_tail = true;
                }
                SQLChunk::Token(Token::UNION | Token::EXCEPT) if depth == 0 => {
                    shape.has_union_or_except = true;
                }
                SQLChunk::Token(Token::INTERSECT) if depth == 0 => shape.has_intersect = true,
                _ => {}
            }
            leading = false;
        }

        shape
    }

    const fn is_compound(self) -> bool {
        self.has_union_or_except || self.has_intersect
    }
}

/// Makes `operand` a single set-operation operand.
///
/// `PostgreSQL` and `MySQL` accept a parenthesized query there. `SQLite` does
/// not, so the operand becomes a derived table instead; its columns keep their
/// names and order.
fn group_set_operand<'a, V: SQLParam>(operand: SQL<'a, V>) -> SQL<'a, V> {
    match V::DIALECT {
        crate::Dialect::SQLite => {
            SQL::from_iter([Token::SELECT, Token::STAR, Token::FROM]).append(operand.parens())
        }
        crate::Dialect::PostgreSQL | crate::Dialect::MySQL => operand.parens(),
    }
}

/// Joins two queries with a set operator, grouping an operand whenever it
/// would not otherwise parse as one operand of this operator:
///
/// - an operand with its own `ORDER BY` / `LIMIT` / `OFFSET`, which would
///   otherwise limit the whole compound or be rejected before the operator;
/// - a compound right operand, so `a.union(b.except(c))` is `A ∪ (B − C)`;
/// - a right operand that opens with `WITH`;
/// - on `PostgreSQL` and `MySQL`, a left `UNION` / `EXCEPT` compound joined by
///   `INTERSECT`, which binds tighter there, so chains apply left to right.
///
/// Plain operands and left-to-right chains render unchanged.
fn set_op<'a, Value, L, R>(left: L, op: Token, all: bool, right: R) -> SQL<'a, Value>
where
    Value: SQLParam,
    L: ToSQL<'a, Value>,
    R: ToSQL<'a, Value>,
{
    let left = left.into_sql();
    let right = right.into_sql();

    let left_shape = OperandShape::of(&left);
    let intersect_binds_tighter = !matches!(Value::DIALECT, crate::Dialect::SQLite);
    let left = if left_shape.has_tail
        || (intersect_binds_tighter
            && matches!(op, Token::INTERSECT)
            && left_shape.has_union_or_except)
    {
        group_set_operand(left)
    } else {
        left
    };

    let right_shape = OperandShape::of(&right);
    let right = if right_shape.has_tail || right_shape.is_compound() || right_shape.starts_with_cte
    {
        group_set_operand(right)
    } else {
        right
    };

    let op_sql = if all {
        SQL::from(op).push(Token::ALL)
    } else {
        SQL::from(op)
    };

    left.append(op_sql).append(right)
}

/// Helper function to create a UNION statement
pub fn union<'a, Value, L, R>(left: L, right: R) -> SQL<'a, Value>
where
    Value: SQLParam,
    L: ToSQL<'a, Value>,
    R: ToSQL<'a, Value>,
{
    set_op(left, Token::UNION, false, right)
}

/// Helper function to create a UNION ALL statement
pub fn union_all<'a, Value, L, R>(left: L, right: R) -> SQL<'a, Value>
where
    Value: SQLParam,
    L: ToSQL<'a, Value>,
    R: ToSQL<'a, Value>,
{
    set_op(left, Token::UNION, true, right)
}

/// Helper function to create an INTERSECT statement
pub fn intersect<'a, Value, L, R>(left: L, right: R) -> SQL<'a, Value>
where
    Value: SQLParam,
    L: ToSQL<'a, Value>,
    R: ToSQL<'a, Value>,
{
    set_op(left, Token::INTERSECT, false, right)
}

/// Helper function to create an INTERSECT ALL statement
pub fn intersect_all<'a, Value, L, R>(left: L, right: R) -> SQL<'a, Value>
where
    Value: SQLParam,
    L: ToSQL<'a, Value>,
    R: ToSQL<'a, Value>,
{
    set_op(left, Token::INTERSECT, true, right)
}

/// Helper function to create an EXCEPT statement
pub fn except<'a, Value, L, R>(left: L, right: R) -> SQL<'a, Value>
where
    Value: SQLParam,
    L: ToSQL<'a, Value>,
    R: ToSQL<'a, Value>,
{
    set_op(left, Token::EXCEPT, false, right)
}

/// Helper function to create an EXCEPT ALL statement
pub fn except_all<'a, Value, L, R>(left: L, right: R) -> SQL<'a, Value>
where
    Value: SQLParam,
    L: ToSQL<'a, Value>,
    R: ToSQL<'a, Value>,
{
    set_op(left, Token::EXCEPT, true, right)
}

/// Creates an INSERT INTO statement with the specified table
pub fn insert<'a, Table, Type, Value>(table: &Table) -> SQL<'a, Value>
where
    Type: SQLSchemaType,
    Value: SQLParam,
    Table: SQLTable<'a, Type, Value>,
{
    SQL::from_iter([Token::INSERT, Token::INTO]).append(table)
}

/// Renders the `(columns) VALUES (..), (..)` of a multi-row `INSERT` whose
/// rows set different columns.
///
/// The column list holds every column any row sets, in the order the rows
/// first name them, and a row that leaves one of those columns unset gets
/// `DEFAULT` in that cell: what omitting the column means for a single-row
/// insert. `PostgreSQL` and `MySQL` accept `DEFAULT` there; `SQLite` does not.
///
/// `rows` pairs each row's `SQLModel::columns()` with its `values()`, which
/// holds one value per column, joined by commas. Returns `None` when a row's
/// values do not split into one value per column.
#[doc(hidden)]
pub fn insert_values_with_defaults<'a, V: SQLParam>(
    rows: Vec<(Cow<'static, [ColumnRef]>, SQL<'a, V>)>,
) -> Option<SQL<'a, V>> {
    let mut columns: Vec<ColumnRef> = Vec::new();
    for (row_columns, _) in &rows {
        for column in row_columns.iter() {
            if !columns.contains(column) {
                columns.push(*column);
            }
        }
    }

    let mut values = SQL::with_capacity_chunks(rows.len().saturating_mul(columns.len() * 2 + 2));
    for (index, (row_columns, row_values)) in rows.into_iter().enumerate() {
        let mut cells = split_top_level_commas(row_values);
        if cells.len() != row_columns.len() {
            return None;
        }
        if index > 0 {
            values.push_mut(Token::COMMA);
        }
        values.push_mut(Token::LPAREN);
        for (position, column) in columns.iter().enumerate() {
            if position > 0 {
                values.push_mut(Token::COMMA);
            }
            match row_columns.iter().position(|set| set == column) {
                Some(cell) => values.append_mut(core::mem::take(&mut cells[cell])),
                None => values.push_mut(Token::DEFAULT),
            }
        }
        values.push_mut(Token::RPAREN);
    }

    Some(
        SQL::columns(&columns)
            .parens()
            .push(Token::VALUES)
            .append(values),
    )
}

/// Splits `sql` at the commas outside any parentheses.
fn split_top_level_commas<'a, V: SQLParam>(sql: SQL<'a, V>) -> Vec<SQL<'a, V>> {
    let mut parts = Vec::new();
    let mut current = SQL::empty();
    let mut depth = 0usize;
    for chunk in sql.chunks {
        match chunk {
            SQLChunk::Token(Token::LPAREN) => depth += 1,
            SQLChunk::Token(Token::RPAREN) => depth = depth.saturating_sub(1),
            SQLChunk::Token(Token::COMMA) if depth == 0 => {
                parts.push(core::mem::take(&mut current));
                continue;
            }
            _ => {}
        }
        current.chunks.push(chunk);
    }
    if !current.chunks.is_empty() || !parts.is_empty() {
        parts.push(current);
    }
    parts
}

/// Helper function to create a FROM clause
pub fn from<'a, T, Value>(query: T) -> SQL<'a, Value>
where
    T: ToSQL<'a, Value>,
    Value: SQLParam,
{
    SQL::from(Token::FROM).append(query.into_sql())
}

/// Helper function to create a WHERE clause
pub fn r#where<'a, V, E>(condition: E) -> SQL<'a, V>
where
    V: SQLParam + 'a,
    E: Expr<'a, V>,
    E::SQLType: BooleanLike,
{
    SQL::from(Token::WHERE).append(condition.into_expr_sql())
}

/// Helper function to create a GROUP BY clause
pub fn group_by<'a, V, I, T>(expressions: I) -> SQL<'a, V>
where
    V: SQLParam + 'a,
    I: IntoIterator<Item = T>,
    T: ToSQL<'a, V>,
{
    SQL::from_iter([Token::GROUP, Token::BY]).append(SQL::join(
        expressions.into_iter().map(ToSQL::into_sql),
        Token::COMMA,
    ))
}

/// Helper function to create a GROUP BY clause from a single `ToSQL` item.
///
/// Unlike [`group_by`], this takes a single expression (which may be a
/// column ZST or a tuple of columns whose `ToSQL` impl already produces
/// comma-separated SQL).
pub fn group_by_expr<'a, V, T>(expr: T) -> SQL<'a, V>
where
    V: SQLParam + 'a,
    T: ToSQL<'a, V>,
{
    SQL::from_iter([Token::GROUP, Token::BY]).append(expr.into_sql())
}

/// Helper function to create a HAVING clause
pub fn having<'a, V, E>(condition: E) -> SQL<'a, V>
where
    V: SQLParam + 'a,
    E: Expr<'a, V>,
    E::SQLType: BooleanLike,
{
    SQL::from(Token::HAVING).append(condition.into_expr_sql())
}

/// Helper function to create an ORDER BY clause
pub fn order_by<'a, T, V>(expressions: T) -> SQL<'a, V>
where
    T: ToSQL<'a, V>,
    V: SQLParam + 'a,
{
    SQL::from_iter([Token::ORDER, Token::BY]).append(expressions.into_sql())
}

/// ORDER BY for a compound query (`UNION`, `INTERSECT`, `EXCEPT`).
///
/// The combined result has no table scope, so PostgreSQL and turso reject
/// `ORDER BY "table"."column"` there; only output column names are legal.
/// Column references in `expressions` are rendered as bare identifiers.
pub fn set_order_by<'a, T, V>(expressions: T) -> SQL<'a, V>
where
    T: ToSQL<'a, V>,
    V: SQLParam + 'a,
{
    SQL::from_iter([Token::ORDER, Token::BY]).append(unqualified_columns(expressions.into_sql()))
}

/// Replace every column reference in `sql` with its unqualified column name.
pub fn unqualified_columns<'a, V>(mut sql: SQL<'a, V>) -> SQL<'a, V>
where
    V: SQLParam + 'a,
{
    for chunk in &mut sql.chunks {
        if let SQLChunk::Column(column) = chunk {
            *chunk = SQLChunk::ident_static(column.name);
        }
    }
    sql
}

/// Helper function to create a LIMIT clause
///
/// # Panics
///
/// Panics when a signed numeric argument is negative or a numeric value does
/// not fit in `usize`.
#[must_use]
#[track_caller]
pub fn limit<'a, V, P>(value: P) -> SQL<'a, V>
where
    V: SQLParam + 'a,
    P: PaginationArg<'a, V>,
{
    SQL::from(Token::LIMIT).append(value.into_pagination_sql())
}

/// Helper function to create an OFFSET clause
///
/// # Panics
///
/// Panics when a signed numeric argument is negative or a numeric value does
/// not fit in `usize`.
#[must_use]
#[track_caller]
pub fn offset<'a, V, P>(value: P) -> SQL<'a, V>
where
    V: SQLParam + 'a,
    P: PaginationArg<'a, V>,
{
    SQL::from(Token::OFFSET).append(value.into_pagination_sql())
}

/// Helper function to create an UPDATE statement
pub fn update<'a, Table, Type, Value>(table: &Table) -> SQL<'a, Value>
where
    Table: SQLTable<'a, Type, Value>,
    Type: SQLSchemaType,
    Value: SQLParam + 'a,
{
    SQL::from(Token::UPDATE).append(table)
}

/// Helper function to create a SET clause for UPDATE
pub fn set<'a, Table, Type, Value>(assignments: &Table::Update) -> SQL<'a, Value>
where
    Value: SQLParam + 'a,
    Table: SQLTable<'a, Type, Value>,
    Type: SQLSchemaType,
{
    SQL::from(Token::SET).append(assignments.to_sql())
}

/// Helper function to create a DELETE FROM statement
pub fn delete<'a, Table, Type, Value>(table: &Table) -> SQL<'a, Value>
where
    Table: SQLTable<'a, Type, Value>,
    Type: SQLSchemaType,
    Value: SQLParam + 'a,
{
    SQL::from_iter([Token::DELETE, Token::FROM]).append(table)
}