oxide-sql-core 0.2.0

Type-safe SQL parser and builder with compile-time validation
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
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
//! SQL statement AST types.

use core::fmt;

use super::expression::Expr;

/// Order direction for ORDER BY.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum OrderDirection {
    /// Ascending order (default).
    #[default]
    Asc,
    /// Descending order.
    Desc,
}

impl OrderDirection {
    /// Returns the SQL representation.
    #[must_use]
    pub const fn as_str(&self) -> &'static str {
        match self {
            Self::Asc => "ASC",
            Self::Desc => "DESC",
        }
    }
}

impl fmt::Display for OrderDirection {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// Null ordering for ORDER BY.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NullOrdering {
    /// NULLs come first.
    First,
    /// NULLs come last.
    Last,
}

impl NullOrdering {
    /// Returns the SQL representation.
    #[must_use]
    pub const fn as_str(&self) -> &'static str {
        match self {
            Self::First => "NULLS FIRST",
            Self::Last => "NULLS LAST",
        }
    }
}

impl fmt::Display for NullOrdering {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// An ORDER BY clause entry.
#[derive(Debug, Clone, PartialEq)]
pub struct OrderBy {
    /// The expression to order by.
    pub expr: Expr,
    /// The direction (ASC or DESC).
    pub direction: OrderDirection,
    /// Null ordering (optional).
    pub nulls: Option<NullOrdering>,
}

/// Join type.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum JoinType {
    /// INNER JOIN.
    Inner,
    /// LEFT OUTER JOIN.
    Left,
    /// RIGHT OUTER JOIN.
    Right,
    /// FULL OUTER JOIN.
    Full,
    /// CROSS JOIN.
    Cross,
}

impl JoinType {
    /// Returns the SQL representation.
    #[must_use]
    pub const fn as_str(&self) -> &'static str {
        match self {
            Self::Inner => "INNER JOIN",
            Self::Left => "LEFT JOIN",
            Self::Right => "RIGHT JOIN",
            Self::Full => "FULL JOIN",
            Self::Cross => "CROSS JOIN",
        }
    }
}

impl fmt::Display for JoinType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// A JOIN clause.
#[derive(Debug, Clone, PartialEq)]
pub struct JoinClause {
    /// The type of join.
    pub join_type: JoinType,
    /// The table to join.
    pub table: TableRef,
    /// The join condition (for non-CROSS joins).
    pub on: Option<Expr>,
    /// USING columns (alternative to ON).
    pub using: Vec<String>,
}

/// A table reference in FROM clause.
#[derive(Debug, Clone, PartialEq)]
pub enum TableRef {
    /// A simple table name.
    Table {
        /// Schema name (optional).
        schema: Option<String>,
        /// Table name.
        name: String,
        /// Alias.
        alias: Option<String>,
    },
    /// A subquery.
    Subquery {
        /// The subquery.
        query: Box<SelectStatement>,
        /// Alias (required for subqueries).
        alias: String,
    },
    /// A joined table.
    Join {
        /// Left side of the join.
        left: Box<TableRef>,
        /// The join clause.
        join: Box<JoinClause>,
    },
}

impl TableRef {
    /// Creates a simple table reference.
    #[must_use]
    pub fn table(name: impl Into<String>) -> Self {
        Self::Table {
            schema: None,
            name: name.into(),
            alias: None,
        }
    }

    /// Creates a table reference with schema.
    #[must_use]
    pub fn with_schema(schema: impl Into<String>, name: impl Into<String>) -> Self {
        Self::Table {
            schema: Some(schema.into()),
            name: name.into(),
            alias: None,
        }
    }

    /// Adds an alias to this table reference.
    #[must_use]
    pub fn alias(self, alias: impl Into<String>) -> Self {
        match self {
            Self::Table { schema, name, .. } => Self::Table {
                schema,
                name,
                alias: Some(alias.into()),
            },
            Self::Subquery { query, .. } => Self::Subquery {
                query,
                alias: alias.into(),
            },
            Self::Join { left, join } => Self::Join {
                left: Box::new((*left).alias(alias)),
                join,
            },
        }
    }
}

/// A SELECT statement.
#[derive(Debug, Clone, PartialEq)]
pub struct SelectStatement {
    /// Whether to select DISTINCT values.
    pub distinct: bool,
    /// The columns to select.
    pub columns: Vec<SelectColumn>,
    /// The FROM clause.
    pub from: Option<TableRef>,
    /// The WHERE clause.
    pub where_clause: Option<Expr>,
    /// GROUP BY expressions.
    pub group_by: Vec<Expr>,
    /// HAVING clause.
    pub having: Option<Expr>,
    /// ORDER BY clauses.
    pub order_by: Vec<OrderBy>,
    /// LIMIT clause.
    pub limit: Option<Expr>,
    /// OFFSET clause.
    pub offset: Option<Expr>,
}

/// A column in SELECT clause.
#[derive(Debug, Clone, PartialEq)]
pub struct SelectColumn {
    /// The expression.
    pub expr: Expr,
    /// Column alias.
    pub alias: Option<String>,
}

impl SelectColumn {
    /// Creates a new select column.
    #[must_use]
    pub fn new(expr: Expr) -> Self {
        Self { expr, alias: None }
    }

    /// Creates a select column with an alias.
    #[must_use]
    pub fn with_alias(expr: Expr, alias: impl Into<String>) -> Self {
        Self {
            expr,
            alias: Some(alias.into()),
        }
    }
}

/// An INSERT statement.
#[derive(Debug, Clone, PartialEq)]
pub struct InsertStatement {
    /// Schema name.
    pub schema: Option<String>,
    /// Table name.
    pub table: String,
    /// Column names (optional).
    pub columns: Vec<String>,
    /// Values to insert.
    pub values: InsertSource,
    /// ON CONFLICT clause (for UPSERT).
    pub on_conflict: Option<OnConflict>,
}

/// Source of data for INSERT.
#[derive(Debug, Clone, PartialEq)]
pub enum InsertSource {
    /// VALUES (...), (...), ...
    Values(Vec<Vec<Expr>>),
    /// SELECT ...
    Query(Box<SelectStatement>),
    /// DEFAULT VALUES
    DefaultValues,
}

/// ON CONFLICT clause for UPSERT.
#[derive(Debug, Clone, PartialEq)]
pub struct OnConflict {
    /// Conflict target columns.
    pub columns: Vec<String>,
    /// Action to take on conflict.
    pub action: ConflictAction,
}

/// Action to take on conflict.
#[derive(Debug, Clone, PartialEq)]
pub enum ConflictAction {
    /// DO NOTHING
    DoNothing,
    /// DO UPDATE SET ...
    DoUpdate(Vec<UpdateAssignment>),
}

/// An UPDATE statement.
#[derive(Debug, Clone, PartialEq)]
pub struct UpdateStatement {
    /// Schema name.
    pub schema: Option<String>,
    /// Table name.
    pub table: String,
    /// Alias.
    pub alias: Option<String>,
    /// SET assignments.
    pub assignments: Vec<UpdateAssignment>,
    /// FROM clause (for joins in UPDATE).
    pub from: Option<TableRef>,
    /// WHERE clause.
    pub where_clause: Option<Expr>,
}

/// An assignment in UPDATE SET.
#[derive(Debug, Clone, PartialEq)]
pub struct UpdateAssignment {
    /// Column name.
    pub column: String,
    /// Value expression.
    pub value: Expr,
}

/// A DELETE statement.
#[derive(Debug, Clone, PartialEq)]
pub struct DeleteStatement {
    /// Schema name.
    pub schema: Option<String>,
    /// Table name.
    pub table: String,
    /// Alias.
    pub alias: Option<String>,
    /// WHERE clause.
    pub where_clause: Option<Expr>,
}

/// A SQL statement.
#[derive(Debug, Clone, PartialEq)]
pub enum Statement {
    /// SELECT statement.
    Select(SelectStatement),
    /// INSERT statement.
    Insert(InsertStatement),
    /// UPDATE statement.
    Update(UpdateStatement),
    /// DELETE statement.
    Delete(DeleteStatement),
}

// ===================================================================
// Display implementations
// ===================================================================

impl fmt::Display for OrderBy {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{} {}", self.expr, self.direction)?;
        if let Some(nulls) = &self.nulls {
            write!(f, " {nulls}")?;
        }
        Ok(())
    }
}

impl fmt::Display for JoinClause {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{} {}", self.join_type, self.table)?;
        if let Some(on) = &self.on {
            write!(f, " ON {on}")?;
        }
        if !self.using.is_empty() {
            write!(f, " USING (")?;
            for (i, col) in self.using.iter().enumerate() {
                if i > 0 {
                    write!(f, ", ")?;
                }
                write!(f, "{col}")?;
            }
            write!(f, ")")?;
        }
        Ok(())
    }
}

impl fmt::Display for TableRef {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Table {
                schema,
                name,
                alias,
            } => {
                if let Some(s) = schema {
                    write!(f, "{s}.")?;
                }
                write!(f, "{name}")?;
                if let Some(a) = alias {
                    write!(f, " AS {a}")?;
                }
                Ok(())
            }
            Self::Subquery { query, alias } => {
                write!(f, "({query}) AS {alias}")
            }
            Self::Join { left, join } => {
                write!(f, "{left} {join}")
            }
        }
    }
}

impl fmt::Display for SelectColumn {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.expr)?;
        if let Some(a) = &self.alias {
            write!(f, " AS {a}")?;
        }
        Ok(())
    }
}

impl fmt::Display for SelectStatement {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "SELECT")?;
        if self.distinct {
            write!(f, " DISTINCT")?;
        }
        for (i, col) in self.columns.iter().enumerate() {
            if i > 0 {
                write!(f, ",")?;
            }
            write!(f, " {col}")?;
        }
        if let Some(from) = &self.from {
            write!(f, " FROM {from}")?;
        }
        if let Some(w) = &self.where_clause {
            write!(f, " WHERE {w}")?;
        }
        if !self.group_by.is_empty() {
            write!(f, " GROUP BY")?;
            for (i, g) in self.group_by.iter().enumerate() {
                if i > 0 {
                    write!(f, ",")?;
                }
                write!(f, " {g}")?;
            }
        }
        if let Some(h) = &self.having {
            write!(f, " HAVING {h}")?;
        }
        if !self.order_by.is_empty() {
            write!(f, " ORDER BY")?;
            for (i, o) in self.order_by.iter().enumerate() {
                if i > 0 {
                    write!(f, ",")?;
                }
                write!(f, " {o}")?;
            }
        }
        if let Some(l) = &self.limit {
            write!(f, " LIMIT {l}")?;
        }
        if let Some(o) = &self.offset {
            write!(f, " OFFSET {o}")?;
        }
        Ok(())
    }
}

impl fmt::Display for InsertSource {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Values(rows) => {
                write!(f, "VALUES")?;
                for (i, row) in rows.iter().enumerate() {
                    if i > 0 {
                        write!(f, ",")?;
                    }
                    write!(f, " (")?;
                    for (j, val) in row.iter().enumerate() {
                        if j > 0 {
                            write!(f, ", ")?;
                        }
                        write!(f, "{val}")?;
                    }
                    write!(f, ")")?;
                }
                Ok(())
            }
            Self::Query(q) => write!(f, "{q}"),
            Self::DefaultValues => write!(f, "DEFAULT VALUES"),
        }
    }
}

impl fmt::Display for OnConflict {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "ON CONFLICT (")?;
        for (i, col) in self.columns.iter().enumerate() {
            if i > 0 {
                write!(f, ", ")?;
            }
            write!(f, "{col}")?;
        }
        write!(f, ") {}", self.action)
    }
}

impl fmt::Display for ConflictAction {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::DoNothing => write!(f, "DO NOTHING"),
            Self::DoUpdate(assignments) => {
                write!(f, "DO UPDATE SET")?;
                for (i, a) in assignments.iter().enumerate() {
                    if i > 0 {
                        write!(f, ",")?;
                    }
                    write!(f, " {a}")?;
                }
                Ok(())
            }
        }
    }
}

impl fmt::Display for InsertStatement {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "INSERT INTO ")?;
        if let Some(s) = &self.schema {
            write!(f, "{s}.")?;
        }
        write!(f, "{}", self.table)?;
        if !self.columns.is_empty() {
            write!(f, " (")?;
            for (i, col) in self.columns.iter().enumerate() {
                if i > 0 {
                    write!(f, ", ")?;
                }
                write!(f, "{col}")?;
            }
            write!(f, ")")?;
        }
        write!(f, " {}", self.values)?;
        if let Some(oc) = &self.on_conflict {
            write!(f, " {oc}")?;
        }
        Ok(())
    }
}

impl fmt::Display for UpdateAssignment {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{} = {}", self.column, self.value)
    }
}

impl fmt::Display for UpdateStatement {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "UPDATE ")?;
        if let Some(s) = &self.schema {
            write!(f, "{s}.")?;
        }
        write!(f, "{}", self.table)?;
        if let Some(a) = &self.alias {
            write!(f, " AS {a}")?;
        }
        write!(f, " SET")?;
        for (i, a) in self.assignments.iter().enumerate() {
            if i > 0 {
                write!(f, ",")?;
            }
            write!(f, " {a}")?;
        }
        if let Some(from) = &self.from {
            write!(f, " FROM {from}")?;
        }
        if let Some(w) = &self.where_clause {
            write!(f, " WHERE {w}")?;
        }
        Ok(())
    }
}

impl fmt::Display for DeleteStatement {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "DELETE FROM ")?;
        if let Some(s) = &self.schema {
            write!(f, "{s}.")?;
        }
        write!(f, "{}", self.table)?;
        if let Some(a) = &self.alias {
            write!(f, " AS {a}")?;
        }
        if let Some(w) = &self.where_clause {
            write!(f, " WHERE {w}")?;
        }
        Ok(())
    }
}

impl fmt::Display for Statement {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Select(s) => write!(f, "{s}"),
            Self::Insert(i) => write!(f, "{i}"),
            Self::Update(u) => write!(f, "{u}"),
            Self::Delete(d) => write!(f, "{d}"),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_order_direction() {
        assert_eq!(OrderDirection::Asc.as_str(), "ASC");
        assert_eq!(OrderDirection::Desc.as_str(), "DESC");
    }

    #[test]
    fn test_join_type() {
        assert_eq!(JoinType::Inner.as_str(), "INNER JOIN");
        assert_eq!(JoinType::Left.as_str(), "LEFT JOIN");
    }

    #[test]
    fn test_table_ref_builder() {
        let table = TableRef::table("users").alias("u");
        assert!(
            matches!(table, TableRef::Table { name, alias, .. } if name == "users" && alias == Some(String::from("u")))
        );
    }
}