prax-query 0.10.0

Type-safe query builder for the Prax ORM
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
//! Abstraction over SQL dialect differences.
//!
//! Different databases vary in placeholder syntax (`$N`, `?`, `?N`, `@PN`),
//! result-returning clauses (`RETURNING`, `OUTPUT INSERTED`), identifier
//! quoting, upsert syntax, and transaction control keywords. Operations in
//! `prax-query` compose SQL through a `&dyn SqlDialect`, obtained from their
//! bound `QueryEngine` via `engine.dialect()`, so a single `build_sql`
//! emission path serves every backend.

/// Sealed supertrait so only this crate can implement `SqlDialect`.
/// Prevents downstream crates from adding their own `SqlDialect`
/// impls; we reserve the right to add new required methods to the
/// trait without a SemVer break.
mod sealed {
    pub trait Sealed {}
    impl Sealed for super::Postgres {}
    impl Sealed for super::Sqlite {}
    impl Sealed for super::Mysql {}
    impl Sealed for super::Mssql {}
    impl Sealed for super::Cql {}
    impl Sealed for super::NotSql {}
}

/// Cross-dialect SQL emission helpers.
///
/// Implementations describe a single database backend's syntax choices.
/// Engines return `&dyn SqlDialect` from `QueryEngine::dialect()`.
pub trait SqlDialect: Send + Sync + sealed::Sealed {
    /// Emit the 1-indexed parameter placeholder for position `i`.
    fn placeholder(&self, i: usize) -> String;

    /// Emit the clause (leading space included) that requests the given
    /// columns be returned after an INSERT/UPDATE/DELETE. Postgres/SQLite/MySQL
    /// emit `RETURNING cols`; MSSQL emits `OUTPUT INSERTED.cols`.
    fn returning_clause(&self, cols: &str) -> String;

    /// Quote a table/column identifier for safe interpolation.
    fn quote_ident(&self, ident: &str) -> String;

    /// Whether the dialect supports `SELECT DISTINCT ON (cols)` (Postgres-only
    /// among our backends today).
    fn supports_distinct_on(&self) -> bool {
        false
    }

    /// Whether an INSERT statement can use the dialect's returning clause to
    /// retrieve inserted rows in-place.
    fn insert_has_returning(&self) -> bool {
        true
    }

    /// Emit the ON CONFLICT / ON DUPLICATE KEY clause (leading space
    /// included) that converts an INSERT into an upsert.
    ///
    /// **Identifier convention**: identifiers in `conflict_cols` MUST be
    /// passed **unquoted** (raw column names). Implementations are
    /// responsible for quoting them per dialect via `self.quote_ident`.
    fn upsert_clause(&self, conflict_cols: &[&str], update_set: &str) -> String;

    /// Whether this dialect supports SQL emission for upsert / nested-write
    /// generation. Returns `false` for document-store dialects (`NotSql`)
    /// that `unimplemented!()` on `quote_ident` / `placeholder` /
    /// `upsert_clause`. Callers must check this before issuing any SQL
    /// via the dialect.
    fn supports_sql_emission(&self) -> bool {
        true
    }

    /// True if this dialect's `upsert_clause` can produce a usable
    /// single-statement `INSERT ... ON CONFLICT/ON DUPLICATE` form, and
    /// (separately) if `placeholder` and `quote_ident` are real
    /// implementations. False for document-store/NotSql dialects whose
    /// SQL-emitting methods are `unimplemented!()`.
    fn supports_upsert(&self) -> bool {
        true
    }

    /// Emit a `DO NOTHING`/insert-ignore clause for the conflict target.
    /// Default empty (fallback dialects skip the single-statement path
    /// entirely). PG/SQLite/DuckDB return ` ON CONFLICT (...) DO NOTHING`;
    /// MySQL returns ` ON DUPLICATE KEY UPDATE id = id` (no-op self-assign).
    ///
    /// Inputs are raw identifiers; the dialect quotes them internally.
    fn upsert_do_nothing_clause(&self, _conflict_cols: &[&str]) -> String {
        String::new()
    }

    /// SQL keyword that begins a transaction. Defaults to `BEGIN`.
    fn begin_sql(&self) -> &'static str {
        "BEGIN"
    }

    /// SQL keyword that commits a transaction. Defaults to `COMMIT`.
    fn commit_sql(&self) -> &'static str {
        "COMMIT"
    }

    /// SQL keyword that rolls back a transaction. Defaults to `ROLLBACK`.
    fn rollback_sql(&self) -> &'static str {
        "ROLLBACK"
    }
}

/// PostgreSQL dialect: `$N` placeholders, `RETURNING`, `"ident"` quoting,
/// `ON CONFLICT (cols) DO UPDATE SET ...` upserts, `DISTINCT ON` support.
pub struct Postgres;

/// SQLite dialect: `?N` placeholders, `RETURNING`, `"ident"` quoting,
/// `ON CONFLICT (cols) DO UPDATE SET ...` upserts.
pub struct Sqlite;

/// MySQL dialect: `?` placeholders (positionless), no `RETURNING`
/// support (that's a MariaDB 10.5+ extension, not MySQL 8.0),
/// backtick-quoted identifiers, `ON DUPLICATE KEY UPDATE ...` upserts.
///
/// Because MySQL can't emit the inserted/updated row in-line, the
/// `MysqlEngine` compensates at the driver layer: inserts look up
/// `LAST_INSERT_ID()` and SELECT back, updates re-run the WHERE as a
/// SELECT. See `prax_mysql::MysqlEngine::execute_insert` /
/// `execute_update` for details.
pub struct Mysql;

/// Microsoft SQL Server dialect: `@PN` placeholders, `OUTPUT INSERTED.*`,
/// bracket-quoted identifiers, `BEGIN/COMMIT/ROLLBACK TRANSACTION`. Upserts
/// require MERGE, which the engine post-processes; the upsert clause emits
/// empty.
pub struct Mssql;

/// Cassandra Query Language dialect, used by `ScyllaEngine` and the
/// Cassandra driver. CQL overlaps with SQL for the basic
/// `SELECT/INSERT/UPDATE/DELETE ... WHERE` shapes the Client API emits,
/// but diverges on many details: no `RETURNING`, no cross-partition
/// joins, no traditional `ON CONFLICT` (use `IF NOT EXISTS` LWT
/// instead), no transactions, and `?` positional placeholders only.
/// The CQL dialect emits that subset safely; engine-level compensation
/// covers the RETURNING gap the way MySQL does.
pub struct Cql;

/// Inert dialect for engines that do not emit SQL (document stores such as
/// MongoDB). Every helper returns an empty or identity value. Calling these
/// methods is a bug — no SQL string built from this dialect would be valid
/// against any real database. The driver's own non-SQL operation path should
/// never reach these helpers.
pub struct NotSql;

impl SqlDialect for Postgres {
    fn placeholder(&self, i: usize) -> String {
        format!("${}", i)
    }
    fn returning_clause(&self, cols: &str) -> String {
        format!(" RETURNING {}", cols)
    }
    fn quote_ident(&self, i: &str) -> String {
        format!("\"{}\"", i.replace('"', "\"\""))
    }
    fn supports_distinct_on(&self) -> bool {
        true
    }
    fn upsert_clause(&self, c: &[&str], s: &str) -> String {
        let quoted: Vec<String> = c.iter().map(|col| self.quote_ident(col)).collect();
        format!(" ON CONFLICT ({}) DO UPDATE SET {}", quoted.join(", "), s)
    }
    fn upsert_do_nothing_clause(&self, c: &[&str]) -> String {
        let quoted: Vec<String> = c.iter().map(|col| self.quote_ident(col)).collect();
        format!(" ON CONFLICT ({}) DO NOTHING", quoted.join(", "))
    }
}

impl SqlDialect for Sqlite {
    fn placeholder(&self, i: usize) -> String {
        format!("?{}", i)
    }
    fn returning_clause(&self, cols: &str) -> String {
        format!(" RETURNING {}", cols)
    }
    fn quote_ident(&self, i: &str) -> String {
        format!("\"{}\"", i.replace('"', "\"\""))
    }
    fn upsert_clause(&self, c: &[&str], s: &str) -> String {
        let quoted: Vec<String> = c.iter().map(|col| self.quote_ident(col)).collect();
        format!(" ON CONFLICT ({}) DO UPDATE SET {}", quoted.join(", "), s)
    }
    fn upsert_do_nothing_clause(&self, c: &[&str]) -> String {
        let quoted: Vec<String> = c.iter().map(|col| self.quote_ident(col)).collect();
        format!(" ON CONFLICT ({}) DO NOTHING", quoted.join(", "))
    }
}

impl SqlDialect for Mysql {
    fn placeholder(&self, _i: usize) -> String {
        "?".into()
    }
    fn upsert_do_nothing_clause(&self, c: &[&str]) -> String {
        let col = c.first().copied().unwrap_or("id");
        format!(
            " ON DUPLICATE KEY UPDATE {} = {}",
            self.quote_ident(col),
            self.quote_ident(col)
        )
    }
    fn returning_clause(&self, _cols: &str) -> String {
        // MySQL 8.0 does NOT support `INSERT ... RETURNING` / `UPDATE ...
        // RETURNING` / `DELETE ... RETURNING`. That syntax only works on
        // MariaDB 10.5+. Emitting it here produces a 1064 syntax error
        // on every insert/update through a typed client.
        //
        // The `MysqlEngine`'s `execute_insert` / `execute_update`
        // implementations compensate by running the DML first, then
        // issuing a follow-up SELECT keyed on `LAST_INSERT_ID()` (for
        // inserts) or re-running the filter (for updates). Returning
        // an empty clause keeps the rest of the build_sql machinery
        // working without driver-specific branches.
        String::new()
    }
    fn insert_has_returning(&self) -> bool {
        false
    }
    fn quote_ident(&self, i: &str) -> String {
        format!("`{}`", i.replace('`', "``"))
    }
    fn upsert_clause(&self, _c: &[&str], s: &str) -> String {
        format!(" ON DUPLICATE KEY UPDATE {}", s)
    }
}

impl SqlDialect for Mssql {
    fn placeholder(&self, i: usize) -> String {
        format!("@P{}", i)
    }
    fn returning_clause(&self, cols: &str) -> String {
        if cols == "*" {
            // OUTPUT INSERTED.* is the only syntactic shortcut T-SQL accepts;
            // bare OUTPUT INSERTED.cols_with_commas would need per-column
            // prefixing, which this branch short-circuits.
            return " OUTPUT INSERTED.*".into();
        }
        let prefixed: Vec<String> = cols
            .split(',')
            .map(|c| format!("INSERTED.{}", c.trim()))
            .collect();
        format!(" OUTPUT {}", prefixed.join(", "))
    }
    fn quote_ident(&self, i: &str) -> String {
        format!("[{}]", i.replace(']', "]]"))
    }
    fn upsert_clause(&self, _c: &[&str], _s: &str) -> String {
        String::new()
    }
    fn begin_sql(&self) -> &'static str {
        "BEGIN TRANSACTION"
    }
    fn commit_sql(&self) -> &'static str {
        "COMMIT TRANSACTION"
    }
    fn rollback_sql(&self) -> &'static str {
        "ROLLBACK TRANSACTION"
    }
}

impl SqlDialect for Cql {
    fn placeholder(&self, _i: usize) -> String {
        "?".into()
    }
    fn returning_clause(&self, _cols: &str) -> String {
        // CQL has no RETURNING; the Cassandra/Scylla engine issues a
        // follow-up SELECT keyed on primary-key equality after every
        // INSERT/UPDATE. See prax-scylladb's execute_insert for details.
        String::new()
    }
    fn insert_has_returning(&self) -> bool {
        false
    }
    fn quote_ident(&self, i: &str) -> String {
        // CQL accepts double-quoted case-sensitive identifiers; without
        // quoting, identifiers are lowercased.
        format!("\"{}\"", i.replace('"', "\"\""))
    }
    fn upsert_clause(&self, _c: &[&str], _s: &str) -> String {
        // CQL has no ON CONFLICT. An INSERT is effectively an upsert
        // by default (last-write-wins). Callers that need strict
        // insert-or-fail should append `IF NOT EXISTS` via raw SQL.
        String::new()
    }
}

impl SqlDialect for NotSql {
    fn placeholder(&self, _i: usize) -> String {
        unimplemented!(
            "NotSql dialect does not emit SQL; engines that return NotSql from \
             QueryEngine::dialect() must not route requests through the SQL \
             operation builders (FindManyOperation, CreateOperation, etc.). \
             Use a SQL-capable dialect (Postgres/Mysql/Sqlite/Mssql) or build \
             queries natively (e.g. BSON for MongoDB)."
        )
    }
    fn returning_clause(&self, _cols: &str) -> String {
        unimplemented!("NotSql::returning_clause — see NotSql::placeholder for details")
    }
    fn quote_ident(&self, _ident: &str) -> String {
        unimplemented!("NotSql::quote_ident — see NotSql::placeholder for details")
    }
    fn upsert_clause(&self, _c: &[&str], _s: &str) -> String {
        unimplemented!("NotSql::upsert_clause — see NotSql::placeholder for details")
    }
    fn supports_sql_emission(&self) -> bool {
        false
    }
    fn supports_upsert(&self) -> bool {
        false
    }
}

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

    #[test]
    fn placeholders_per_dialect() {
        assert_eq!(Postgres.placeholder(3), "$3");
        assert_eq!(Sqlite.placeholder(3), "?3");
        assert_eq!(Mysql.placeholder(3), "?");
        assert_eq!(Mssql.placeholder(3), "@P3");
    }

    #[test]
    fn returning_mssql_is_output_inserted() {
        assert_eq!(Mssql.returning_clause("*"), " OUTPUT INSERTED.*");
        assert_eq!(Mssql.returning_clause("id"), " OUTPUT INSERTED.id");
        assert_eq!(
            Mssql.returning_clause("id, email"),
            " OUTPUT INSERTED.id, INSERTED.email"
        );
        assert_eq!(
            Mssql.returning_clause("id,email,name"),
            " OUTPUT INSERTED.id, INSERTED.email, INSERTED.name"
        );
    }

    #[test]
    fn upsert_mysql_is_on_duplicate_key() {
        assert_eq!(
            Mysql.upsert_clause(&[], "x = 1"),
            " ON DUPLICATE KEY UPDATE x = 1"
        );
    }

    #[test]
    fn upsert_postgres_is_on_conflict() {
        // upsert_clause quotes the raw ident internally.
        assert_eq!(
            Postgres.upsert_clause(&["email"], "name = EXCLUDED.name"),
            " ON CONFLICT (\"email\") DO UPDATE SET name = EXCLUDED.name"
        );
    }

    #[test]
    fn quote_ident_backends_escape_the_embedded_quote() {
        assert_eq!(
            Postgres.quote_ident(r#"col"with"quote"#),
            r#""col""with""quote""#
        );
        assert_eq!(
            Sqlite.quote_ident(r#"col"with"quote"#),
            r#""col""with""quote""#
        );
        assert_eq!(Mysql.quote_ident("co`l"), "`co``l`");
        assert_eq!(Mssql.quote_ident("col]ident"), "[col]]ident]");
    }

    #[test]
    #[should_panic(expected = "NotSql dialect does not emit SQL")]
    fn not_sql_placeholder_panics() {
        let _ = NotSql.placeholder(1);
    }

    #[test]
    #[should_panic]
    fn not_sql_quote_ident_panics() {
        let _ = NotSql.quote_ident("col");
    }

    #[test]
    #[should_panic]
    fn not_sql_returning_clause_panics() {
        let _ = NotSql.returning_clause("*");
    }

    #[test]
    #[should_panic]
    fn not_sql_upsert_clause_panics() {
        let _ = NotSql.upsert_clause(&[], "x = 1");
    }

    #[test]
    fn mssql_transaction_keywords_are_distinct() {
        assert_eq!(Mssql.begin_sql(), "BEGIN TRANSACTION");
        assert_eq!(Mssql.commit_sql(), "COMMIT TRANSACTION");
        assert_eq!(Mssql.rollback_sql(), "ROLLBACK TRANSACTION");
    }

    #[test]
    fn distinct_on_support() {
        assert!(Postgres.supports_distinct_on());
        assert!(!Sqlite.supports_distinct_on());
        assert!(!Mysql.supports_distinct_on());
        assert!(!Mssql.supports_distinct_on());
        assert!(!NotSql.supports_distinct_on());
    }

    #[test]
    fn sealed_pattern_prevents_external_impl() {
        // The sealed supertrait means only types that impl sealed::Sealed
        // can impl SqlDialect. Downstream crates can't access
        // `sealed::Sealed` so they can't add new dialects. This test
        // merely documents the intent; the enforcement is the compiler
        // refusing to accept `impl SqlDialect for MyDialect` outside this
        // crate.
        use crate::dialect::{Postgres, SqlDialect};
        let _p: &dyn SqlDialect = &Postgres;
    }
}