prax-query 0.13.2

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
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
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
//! 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.

use crate::advanced::{LockStrength, LockWait, RowLock};
use crate::error::{QueryError, QueryResult};

/// 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 {}
}

/// Dialect-specific rendering of a row lock, split by where each piece
/// lands in a `SELECT`.
///
/// `table_hint` follows the table name (MSSQL `WITH (UPDLOCK, ...)`);
/// `suffix` goes at the very end of the statement (`FOR UPDATE ...`).
#[non_exhaustive]
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct RowLockSql {
    /// Hint rendered directly after the table name (without leading space).
    pub table_hint: Option<String>,
    /// Clause rendered at the end of the statement (without leading space).
    pub suffix: Option<String>,
}

impl RowLockSql {
    /// Append the table hint (if any), preceded by a space.
    pub(crate) fn push_table_hint(&self, sql: &mut String) {
        if let Some(hint) = &self.table_hint {
            sql.push(' ');
            sql.push_str(hint);
        }
    }

    /// Append the statement-final clause (if any), preceded by a space.
    pub(crate) fn push_suffix(&self, sql: &mut String) {
        if let Some(suffix) = &self.suffix {
            sql.push(' ');
            sql.push_str(suffix);
        }
    }
}

/// The ` NOWAIT` / ` SKIP LOCKED` tail shared by the `FOR ...` dialects.
fn wait_suffix(wait: LockWait) -> &'static str {
    match wait {
        LockWait::Wait => "",
        LockWait::NoWait => " NOWAIT",
        LockWait::SkipLocked => " SKIP LOCKED",
    }
}

/// 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;

    /// Render a row lock for this dialect, or fail if the dialect cannot
    /// express it faithfully. The default rejects every lock.
    fn row_lock_sql(&self, _lock: &RowLock) -> QueryResult<RowLockSql> {
        Err(QueryError::unsupported(
            "row locks are not supported by this dialect",
        ))
    }

    /// 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()
    }

    /// LIKE-pattern escape clause (leading space included) appended to
    /// `<col> LIKE <placeholder>` when the pattern carries backslash-escaped
    /// user input. Postgres/SQLite/MSSQL accept `ESCAPE '\'`; MySQL treats
    /// backslash as a string-literal escape character, so its spelling must
    /// double the backslash (`ESCAPE '\\'`) — the single-backslash form is
    /// an unterminated literal there.
    fn like_escape_clause(&self) -> &'static str {
        " ESCAPE '\\'"
    }

    /// 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"
    }

    /// Append the row-limiting clause for `take` / `skip`, leading space
    /// included; nothing is written when both are `None`.
    ///
    /// `has_order_by` says whether the statement already ends in an
    /// `ORDER BY`. The default is `LIMIT n OFFSET m`.
    fn write_limit_offset(
        &self,
        sql: &mut String,
        take: Option<u64>,
        skip: Option<u64>,
        has_order_by: bool,
    ) {
        let _ = has_order_by;
        if let Some(take) = take {
            sql.push_str(" LIMIT ");
            sql.push_str(&take.to_string());
        }
        if let Some(skip) = skip {
            sql.push_str(" OFFSET ");
            sql.push_str(&skip.to_string());
        }
    }
}

/// 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 row_lock_sql(&self, lock: &RowLock) -> QueryResult<RowLockSql> {
        let mut sql = String::from(match lock.strength {
            LockStrength::Update => "FOR UPDATE",
            LockStrength::NoKeyUpdate => "FOR NO KEY UPDATE",
            LockStrength::Share => "FOR SHARE",
            LockStrength::KeyShare => "FOR KEY SHARE",
        });
        if !lock.of_tables.is_empty() {
            // `OF` names must match how the query's FROM clause spells the
            // table, and FROM interpolates `Model::TABLE_NAME` unquoted. Emit
            // the same way, so only validated identifiers may reach here.
            for table in &lock.of_tables {
                if !crate::sql::is_valid_sql_identifier(table) {
                    return Err(QueryError::invalid_input(
                        "lock",
                        format!("invalid table name in OF clause: {table:?}"),
                    ));
                }
            }
            sql.push_str(" OF ");
            sql.push_str(&lock.of_tables.join(", "));
        }
        sql.push_str(wait_suffix(lock.wait));
        Ok(RowLockSql {
            table_hint: None,
            suffix: Some(sql),
        })
    }

    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 row_lock_sql(&self, lock: &RowLock) -> QueryResult<RowLockSql> {
        let mut sql = String::from(match lock.strength {
            LockStrength::Update => "FOR UPDATE",
            LockStrength::Share => "FOR SHARE",
            LockStrength::NoKeyUpdate | LockStrength::KeyShare => {
                return Err(QueryError::unsupported(
                    "MySQL row locks support only FOR UPDATE and FOR SHARE",
                ));
            }
        });
        if !lock.of_tables.is_empty() {
            return Err(QueryError::unsupported(
                "MySQL row locks do not support OF <tables>",
            ));
        }
        sql.push_str(wait_suffix(lock.wait));
        Ok(RowLockSql {
            table_hint: None,
            suffix: Some(sql),
        })
    }

    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)
    }
    fn like_escape_clause(&self) -> &'static str {
        // MySQL treats backslash as an escape character inside string
        // literals, so `ESCAPE '\'` is an unterminated literal (error
        // 1064). Doubling the backslash spells the escape character
        // correctly — the SQL text reads ESCAPE '\\'.
        " ESCAPE '\\\\'"
    }
}

impl SqlDialect for Mssql {
    /// T-SQL has no `LIMIT`: `OFFSET m ROWS FETCH NEXT n ROWS ONLY`, which
    /// needs an `ORDER BY`, so an unordered statement gets
    /// `ORDER BY (SELECT NULL)` (no particular order, as with `LIMIT`).
    fn write_limit_offset(
        &self,
        sql: &mut String,
        take: Option<u64>,
        skip: Option<u64>,
        has_order_by: bool,
    ) {
        if take.is_none() && skip.is_none() {
            return;
        }
        if !has_order_by {
            sql.push_str(" ORDER BY (SELECT NULL)");
        }
        sql.push_str(" OFFSET ");
        sql.push_str(&skip.unwrap_or(0).to_string());
        sql.push_str(" ROWS");
        if let Some(take) = take {
            sql.push_str(" FETCH NEXT ");
            sql.push_str(&take.to_string());
            sql.push_str(" ROWS ONLY");
        }
    }

    fn row_lock_sql(&self, lock: &RowLock) -> QueryResult<RowLockSql> {
        if !lock.of_tables.is_empty() {
            return Err(QueryError::unsupported(
                "MSSQL row locks do not support OF <tables>",
            ));
        }
        let hint = match (lock.strength, lock.wait) {
            (LockStrength::Update, LockWait::Wait) => "WITH (UPDLOCK, ROWLOCK)",
            (LockStrength::Update, LockWait::SkipLocked) => "WITH (UPDLOCK, ROWLOCK, READPAST)",
            (LockStrength::Update, LockWait::NoWait) => "WITH (UPDLOCK, ROWLOCK, NOWAIT)",
            (LockStrength::Share, LockWait::Wait) => "WITH (HOLDLOCK, ROWLOCK)",
            (LockStrength::Share, LockWait::NoWait) => "WITH (HOLDLOCK, ROWLOCK, NOWAIT)",
            (LockStrength::Share, LockWait::SkipLocked) => {
                return Err(QueryError::unsupported(
                    "MSSQL cannot combine a shared row lock with SKIP LOCKED",
                ));
            }
            (LockStrength::NoKeyUpdate | LockStrength::KeyShare, _) => {
                return Err(QueryError::unsupported(
                    "MSSQL row locks support only FOR UPDATE and FOR SHARE",
                ));
            }
        };
        Ok(RowLockSql {
            table_hint: Some(hint.to_string()),
            suffix: None,
        })
    }

    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 like_escape_clause_per_dialect() {
        // Default: single-backslash escape character.
        assert_eq!(Postgres.like_escape_clause(), r" ESCAPE '\'");
        assert_eq!(Sqlite.like_escape_clause(), r" ESCAPE '\'");
        assert_eq!(Mssql.like_escape_clause(), r" ESCAPE '\'");
        assert_eq!(Cql.like_escape_clause(), r" ESCAPE '\'");
        // MySQL: backslash must be doubled inside the string literal.
        assert_eq!(Mysql.like_escape_clause(), r" ESCAPE '\\'");
    }

    #[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;
    }

    #[test]
    fn limit_offset_default_is_limit_offset() {
        use crate::dialect::{Postgres, SqlDialect};
        let mut sql = String::from("SELECT 1");
        Postgres.write_limit_offset(&mut sql, Some(20), Some(10), false);
        assert_eq!(sql, "SELECT 1 LIMIT 20 OFFSET 10");
        let mut sql = String::from("SELECT 1");
        Postgres.write_limit_offset(&mut sql, None, None, false);
        assert_eq!(sql, "SELECT 1");
    }

    #[test]
    fn limit_offset_mssql_uses_offset_fetch() {
        use crate::dialect::{Mssql, SqlDialect};
        let mut sql = String::from("SELECT * FROM t ORDER BY id");
        Mssql.write_limit_offset(&mut sql, Some(5), Some(10), true);
        assert_eq!(
            sql,
            "SELECT * FROM t ORDER BY id OFFSET 10 ROWS FETCH NEXT 5 ROWS ONLY"
        );
        // OFFSET .. FETCH requires ORDER BY.
        let mut sql = String::from("SELECT * FROM t");
        Mssql.write_limit_offset(&mut sql, Some(1), None, false);
        assert_eq!(
            sql,
            "SELECT * FROM t ORDER BY (SELECT NULL) OFFSET 0 ROWS FETCH NEXT 1 ROWS ONLY"
        );
        let mut sql = String::from("SELECT * FROM t ORDER BY id");
        Mssql.write_limit_offset(&mut sql, None, Some(3), true);
        assert_eq!(sql, "SELECT * FROM t ORDER BY id OFFSET 3 ROWS");
        let mut sql = String::from("SELECT 1");
        Mssql.write_limit_offset(&mut sql, None, None, false);
        assert_eq!(sql, "SELECT 1");
    }
}