ruststream-sqlx-dialect 0.7.0

SQL text generation for ruststream-sqlx: the statements its procedural macros and its runtime build for each database.
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
//! What a table's transactions open at: an isolation level, a SQLite mode, or the database's
//! default; and the levels a dialect opens, as types.

use crate::dialect::Dialect;
use crate::statement::StatementError;

/// The isolation level a transaction opens at, on Postgres, MySQL and MariaDB.
///
/// A table names one ([`TableSpec::isolation`](crate::TableSpec::isolation)), and the dialect's
/// [`begin`](Dialect::begin) opens the table's transactions at it. A database that runs a level
/// as a stronger one does not keep it, so its dialect refuses it: Postgres refuses
/// [`ReadUncommitted`](Self::ReadUncommitted).
///
/// # Examples
///
/// ```
/// # use std::num::NonZeroUsize;
/// # use ruststream_sqlx_dialect::TableName;
/// use ruststream_sqlx_dialect::{
///     Dialect, Isolation, Opening, Opens, Statement, StatementError, TableSpec, level,
/// };
///
/// /// SQL Server, a database without a built-in dialect.
/// #[derive(Debug)]
/// pub struct Mssql;
///
/// impl Dialect for Mssql {
///     fn name(&self) -> &'static str {
///         "mssql"
///     }
///
///     fn begin(&self, opening: Opening) -> Result<Option<&'static str>, StatementError> {
///         match opening {
///             Opening::Default | Opening::Isolation(Isolation::ReadCommitted) => Ok(Some(
///                 "SET TRANSACTION ISOLATION LEVEL READ COMMITTED; BEGIN TRANSACTION",
///             )),
///             Opening::Isolation(Isolation::RepeatableRead) => Ok(Some(
///                 "SET TRANSACTION ISOLATION LEVEL REPEATABLE READ; BEGIN TRANSACTION",
///             )),
///             // A refusal names the opening the table declares.
///             other => Err(StatementError::UnsupportedOpening {
///                 dialect: self.name(),
///                 opening: other.name(),
///             }),
///         }
///     }
/// #     fn quote_into(&self, ident: &str, out: &mut String) { out.push('['); out.push_str(&ident.replace(']', "]]")); out.push(']'); }
/// #     fn placeholder_into(&self, index: NonZeroUsize, out: &mut String) { out.push_str("@p"); out.push_str(&index.to_string()); }
/// #     fn fetch(&self, spec: &TableSpec<'_>) -> Result<Statement, StatementError> { Err(StatementError::UnsupportedFetch { dialect: self.name() }) }
/// #     fn ack(&self, spec: &TableSpec<'_>) -> Result<Statement, StatementError> { Err(StatementError::UnsupportedForm { dialect: self.name(), form: spec.form().name() }) }
/// #     fn retry(&self, spec: &TableSpec<'_>) -> Result<Option<Statement>, StatementError> { Err(StatementError::UnsupportedForm { dialect: self.name(), form: spec.form().name() }) }
/// #     fn retry_after(&self, spec: &TableSpec<'_>) -> Result<Statement, StatementError> { Err(StatementError::UnsupportedForm { dialect: self.name(), form: spec.form().name() }) }
/// #     fn discard(&self, spec: &TableSpec<'_>) -> Result<Statement, StatementError> { Err(StatementError::UnsupportedForm { dialect: self.name(), form: spec.form().name() }) }
/// #     fn dead_letter_group(&self, spec: &TableSpec<'_>) -> Result<Statement, StatementError> { Err(StatementError::UnsupportedForm { dialect: self.name(), form: spec.form().name() }) }
/// #     fn dead_letter_table(&self, spec: &TableSpec<'_>, target: TableName<'_>) -> Result<Vec<Statement>, StatementError> { Err(StatementError::UnsupportedForm { dialect: self.name(), form: spec.form().name() }) }
/// #     fn insert(&self, spec: &TableSpec<'_>) -> Result<Statement, StatementError> { Err(StatementError::UnsupportedForm { dialect: self.name(), form: spec.form().name() }) }
/// }
///
/// // A table at one of these levels mounts on `Mssql`.
/// impl Opens<level::ReadCommitted> for Mssql {}
/// impl Opens<level::RepeatableRead> for Mssql {}
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Isolation {
    /// A read may see what other transactions wrote and have not committed.
    ReadUncommitted,
    /// Each statement sees what was committed before it began.
    ReadCommitted,
    /// Every statement sees what was committed before the transaction's first one.
    RepeatableRead,
    /// Transactions take effect as if they ran one after another.
    Serializable,
}

impl Isolation {
    /// The level as SQL names it: `READ COMMITTED`.
    ///
    /// # Examples
    ///
    /// ```
    /// # #[cfg(feature = "postgres")]
    /// # fn main() -> Result<(), ruststream_sqlx_dialect::StatementError> {
    /// use ruststream_sqlx_dialect::{Dialect, Isolation, Opening, Postgres};
    ///
    /// // A dialect's test: each level it serves opens a transaction at that level.
    /// for level in [Isolation::ReadCommitted, Isolation::RepeatableRead, Isolation::Serializable] {
    ///     let begin = Postgres.begin(Opening::Isolation(level))?;
    ///     assert_eq!(begin, Some(format!("BEGIN ISOLATION LEVEL {}", level.sql())).as_deref());
    /// }
    /// # Ok(())
    /// # }
    /// # #[cfg(not(feature = "postgres"))]
    /// # fn main() {}
    /// ```
    #[must_use]
    pub const fn sql(self) -> &'static str {
        match self {
            Self::ReadUncommitted => "READ UNCOMMITTED",
            Self::ReadCommitted => "READ COMMITTED",
            Self::RepeatableRead => "REPEATABLE READ",
            Self::Serializable => "SERIALIZABLE",
        }
    }

    /// The level as a table names it: `read_committed`.
    // The derives and the crate read it to parse and check a table; a service never names it.
    #[doc(hidden)]
    #[must_use]
    pub const fn attribute(self) -> &'static str {
        match self {
            Self::ReadUncommitted => "read_uncommitted",
            Self::ReadCommitted => "read_committed",
            Self::RepeatableRead => "repeatable_read",
            Self::Serializable => "serializable",
        }
    }
}

/// How a SQLite transaction takes the database's write lock.
///
/// SQLite runs every transaction serializable, with one writer at a time, so a table on it names
/// the moment its transactions take the write lock ([`TableSpec::mode`](crate::TableSpec::mode))
/// instead of a level.
///
/// # Examples
///
/// A dialect for a database that takes SQLite's modes opens its transactions in them:
///
/// ```
/// # use std::num::NonZeroUsize;
/// # use ruststream_sqlx_dialect::TableName;
/// use ruststream_sqlx_dialect::{
///     Dialect, Mode, Opening, Opens, Statement, StatementError, TableSpec, level,
/// };
///
/// /// libSQL, a fork of SQLite served over the network, a database without a built-in dialect.
/// #[derive(Debug)]
/// pub struct Libsql;
///
/// impl Dialect for Libsql {
///     fn name(&self) -> &'static str {
///         "libsql"
///     }
///
///     fn begin(&self, opening: Opening) -> Result<Option<&'static str>, StatementError> {
///         match opening {
///             Opening::Default => Ok(None),
///             Opening::Mode(Mode::Deferred) => Ok(Some("BEGIN DEFERRED")),
///             Opening::Mode(Mode::Immediate) => Ok(Some("BEGIN IMMEDIATE")),
///             Opening::Mode(Mode::Exclusive) => Ok(Some("BEGIN EXCLUSIVE")),
///             // libSQL runs every transaction serializable, as SQLite does: it names no level.
///             other => Err(StatementError::UnsupportedOpening {
///                 dialect: self.name(),
///                 opening: other.name(),
///             }),
///         }
///     }
/// #     fn quote_into(&self, ident: &str, out: &mut String) { out.push('"'); out.push_str(&ident.replace('"', "\"\"")); out.push('"'); }
/// #     fn placeholder_into(&self, index: NonZeroUsize, out: &mut String) { out.push('?'); out.push_str(&index.to_string()); }
/// #     fn fetch(&self, spec: &TableSpec<'_>) -> Result<Statement, StatementError> { Err(StatementError::UnsupportedFetch { dialect: self.name() }) }
/// #     fn ack(&self, spec: &TableSpec<'_>) -> Result<Statement, StatementError> { Err(StatementError::UnsupportedForm { dialect: self.name(), form: spec.form().name() }) }
/// #     fn retry(&self, spec: &TableSpec<'_>) -> Result<Option<Statement>, StatementError> { Err(StatementError::UnsupportedForm { dialect: self.name(), form: spec.form().name() }) }
/// #     fn retry_after(&self, spec: &TableSpec<'_>) -> Result<Statement, StatementError> { Err(StatementError::UnsupportedForm { dialect: self.name(), form: spec.form().name() }) }
/// #     fn discard(&self, spec: &TableSpec<'_>) -> Result<Statement, StatementError> { Err(StatementError::UnsupportedForm { dialect: self.name(), form: spec.form().name() }) }
/// #     fn dead_letter_group(&self, spec: &TableSpec<'_>) -> Result<Statement, StatementError> { Err(StatementError::UnsupportedForm { dialect: self.name(), form: spec.form().name() }) }
/// #     fn dead_letter_table(&self, spec: &TableSpec<'_>, target: TableName<'_>) -> Result<Vec<Statement>, StatementError> { Err(StatementError::UnsupportedForm { dialect: self.name(), form: spec.form().name() }) }
/// #     fn insert(&self, spec: &TableSpec<'_>) -> Result<Statement, StatementError> { Err(StatementError::UnsupportedForm { dialect: self.name(), form: spec.form().name() }) }
/// }
///
/// // A table with `mode = deferred`, `immediate` or `exclusive` mounts on `Libsql`.
/// impl Opens<level::Deferred> for Libsql {}
/// impl Opens<level::Immediate> for Libsql {}
/// impl Opens<level::Exclusive> for Libsql {}
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Mode {
    /// The transaction takes no lock until it first reads or writes, as a plain `BEGIN` does.
    Deferred,
    /// The transaction takes the write lock when it begins, so no other writer comes between its
    /// reads and its writes.
    Immediate,
    /// The transaction takes the write lock when it begins and, outside WAL mode, keeps every
    /// other connection from reading until it ends.
    Exclusive,
}

impl Mode {
    /// The mode as SQL names it: `IMMEDIATE`.
    ///
    /// # Examples
    ///
    /// ```
    /// # #[cfg(feature = "sqlite")]
    /// # fn main() -> Result<(), ruststream_sqlx_dialect::StatementError> {
    /// use ruststream_sqlx_dialect::{Dialect, Mode, Opening, Sqlite};
    ///
    /// // A dialect's test: each mode opens a transaction in that mode.
    /// for mode in [Mode::Deferred, Mode::Immediate, Mode::Exclusive] {
    ///     let begin = Sqlite.begin(Opening::Mode(mode))?;
    ///     assert_eq!(begin, Some(format!("BEGIN {}", mode.sql())).as_deref());
    /// }
    /// # Ok(())
    /// # }
    /// # #[cfg(not(feature = "sqlite"))]
    /// # fn main() {}
    /// ```
    #[must_use]
    pub const fn sql(self) -> &'static str {
        match self {
            Self::Deferred => "DEFERRED",
            Self::Immediate => "IMMEDIATE",
            Self::Exclusive => "EXCLUSIVE",
        }
    }

    /// The mode as a table names it: `immediate`.
    // The derives and the crate read it to parse and check a table; a service never names it.
    #[doc(hidden)]
    #[must_use]
    pub const fn attribute(self) -> &'static str {
        match self {
            Self::Deferred => "deferred",
            Self::Immediate => "immediate",
            Self::Exclusive => "exclusive",
        }
    }
}

/// What a table's transactions open at: the dialect's default, an isolation level, or a SQLite
/// mode.
///
/// A table description carries one ([`TableSpec::opening`](crate::TableSpec::opening)), and the
/// dialect's [`begin`](Dialect::begin) gives the statement that opens a transaction at it, or
/// refuses an opening its database lacks.
///
/// # Examples
///
/// ```
/// # use std::num::NonZeroUsize;
/// # use ruststream_sqlx_dialect::TableName;
/// use ruststream_sqlx_dialect::{
///     Dialect, Isolation, Opening, Opens, Statement, StatementError, TableSpec, level,
/// };
///
/// /// SQL Server, a database without a built-in dialect.
/// #[derive(Debug)]
/// pub struct Mssql;
///
/// impl Dialect for Mssql {
///     fn name(&self) -> &'static str {
///         "mssql"
///     }
///
///     // SQL Server keeps a level set with `SET TRANSACTION ISOLATION LEVEL` for the rest of the
///     // session, so a table that names no level opens at READ COMMITTED by name rather than at
///     // the level the connection last ran.
///     fn begin(&self, opening: Opening) -> Result<Option<&'static str>, StatementError> {
///         match opening {
///             Opening::Default | Opening::Isolation(Isolation::ReadCommitted) => Ok(Some(
///                 "SET TRANSACTION ISOLATION LEVEL READ COMMITTED; BEGIN TRANSACTION",
///             )),
///             Opening::Isolation(Isolation::RepeatableRead) => Ok(Some(
///                 "SET TRANSACTION ISOLATION LEVEL REPEATABLE READ; BEGIN TRANSACTION",
///             )),
///             Opening::Isolation(Isolation::Serializable) => Ok(Some(
///                 "SET TRANSACTION ISOLATION LEVEL SERIALIZABLE; BEGIN TRANSACTION",
///             )),
///             // A SQLite mode, and the levels the service's claims do not run at.
///             other => Err(StatementError::UnsupportedOpening {
///                 dialect: self.name(),
///                 opening: other.name(),
///             }),
///         }
///     }
/// #     fn quote_into(&self, ident: &str, out: &mut String) { out.push('['); out.push_str(&ident.replace(']', "]]")); out.push(']'); }
/// #     fn placeholder_into(&self, index: NonZeroUsize, out: &mut String) { out.push_str("@p"); out.push_str(&index.to_string()); }
/// #     fn fetch(&self, spec: &TableSpec<'_>) -> Result<Statement, StatementError> { Err(StatementError::UnsupportedFetch { dialect: self.name() }) }
/// #     fn ack(&self, spec: &TableSpec<'_>) -> Result<Statement, StatementError> { Err(StatementError::UnsupportedForm { dialect: self.name(), form: spec.form().name() }) }
/// #     fn retry(&self, spec: &TableSpec<'_>) -> Result<Option<Statement>, StatementError> { Err(StatementError::UnsupportedForm { dialect: self.name(), form: spec.form().name() }) }
/// #     fn retry_after(&self, spec: &TableSpec<'_>) -> Result<Statement, StatementError> { Err(StatementError::UnsupportedForm { dialect: self.name(), form: spec.form().name() }) }
/// #     fn discard(&self, spec: &TableSpec<'_>) -> Result<Statement, StatementError> { Err(StatementError::UnsupportedForm { dialect: self.name(), form: spec.form().name() }) }
/// #     fn dead_letter_group(&self, spec: &TableSpec<'_>) -> Result<Statement, StatementError> { Err(StatementError::UnsupportedForm { dialect: self.name(), form: spec.form().name() }) }
/// #     fn dead_letter_table(&self, spec: &TableSpec<'_>, target: TableName<'_>) -> Result<Vec<Statement>, StatementError> { Err(StatementError::UnsupportedForm { dialect: self.name(), form: spec.form().name() }) }
/// #     fn insert(&self, spec: &TableSpec<'_>) -> Result<Statement, StatementError> { Err(StatementError::UnsupportedForm { dialect: self.name(), form: spec.form().name() }) }
/// }
///
/// impl Opens<level::ReadCommitted> for Mssql {}
/// impl Opens<level::RepeatableRead> for Mssql {}
/// impl Opens<level::Serializable> for Mssql {}
/// ```
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Opening {
    /// What the dialect opens a table's transactions at when the table names neither a level nor
    /// a mode: the database's own level on Postgres and SQLite, READ COMMITTED on MySQL and
    /// MariaDB.
    #[default]
    Default,
    /// An isolation level.
    Isolation(Isolation),
    /// A SQLite mode.
    Mode(Mode),
}

impl Opening {
    /// The opening as a message names it: `the database's default`, ``isolation `serializable` ``
    /// or ``mode `immediate` ``.
    ///
    /// # Examples
    ///
    /// ```
    /// # use std::num::NonZeroUsize;
    /// # use ruststream_sqlx_dialect::TableName;
    /// use ruststream_sqlx_dialect::{
    ///     Dialect, Isolation, Opening, Opens, Statement, StatementError, TableSpec, level,
    /// };
    ///
    /// /// SQL Server, a database without a built-in dialect.
    /// #[derive(Debug)]
    /// pub struct Mssql;
    ///
    /// impl Dialect for Mssql {
    ///     fn name(&self) -> &'static str {
    ///         "mssql"
    ///     }
    ///
    ///     fn begin(&self, opening: Opening) -> Result<Option<&'static str>, StatementError> {
    ///         match opening {
    ///             Opening::Default | Opening::Isolation(Isolation::ReadCommitted) => Ok(Some(
    ///                 "SET TRANSACTION ISOLATION LEVEL READ COMMITTED; BEGIN TRANSACTION",
    ///             )),
    ///             Opening::Isolation(Isolation::RepeatableRead) => Ok(Some(
    ///                 "SET TRANSACTION ISOLATION LEVEL REPEATABLE READ; BEGIN TRANSACTION",
    ///             )),
    ///             // A refusal names the opening the table declares.
    ///             other => Err(StatementError::UnsupportedOpening {
    ///                 dialect: self.name(),
    ///                 opening: other.name(),
    ///             }),
    ///         }
    ///     }
    /// #     fn quote_into(&self, ident: &str, out: &mut String) { out.push('['); out.push_str(&ident.replace(']', "]]")); out.push(']'); }
    /// #     fn placeholder_into(&self, index: NonZeroUsize, out: &mut String) { out.push_str("@p"); out.push_str(&index.to_string()); }
    /// #     fn fetch(&self, spec: &TableSpec<'_>) -> Result<Statement, StatementError> { Err(StatementError::UnsupportedFetch { dialect: self.name() }) }
    /// #     fn ack(&self, spec: &TableSpec<'_>) -> Result<Statement, StatementError> { Err(StatementError::UnsupportedForm { dialect: self.name(), form: spec.form().name() }) }
    /// #     fn retry(&self, spec: &TableSpec<'_>) -> Result<Option<Statement>, StatementError> { Err(StatementError::UnsupportedForm { dialect: self.name(), form: spec.form().name() }) }
    /// #     fn retry_after(&self, spec: &TableSpec<'_>) -> Result<Statement, StatementError> { Err(StatementError::UnsupportedForm { dialect: self.name(), form: spec.form().name() }) }
    /// #     fn discard(&self, spec: &TableSpec<'_>) -> Result<Statement, StatementError> { Err(StatementError::UnsupportedForm { dialect: self.name(), form: spec.form().name() }) }
    /// #     fn dead_letter_group(&self, spec: &TableSpec<'_>) -> Result<Statement, StatementError> { Err(StatementError::UnsupportedForm { dialect: self.name(), form: spec.form().name() }) }
    /// #     fn dead_letter_table(&self, spec: &TableSpec<'_>, target: TableName<'_>) -> Result<Vec<Statement>, StatementError> { Err(StatementError::UnsupportedForm { dialect: self.name(), form: spec.form().name() }) }
    /// #     fn insert(&self, spec: &TableSpec<'_>) -> Result<Statement, StatementError> { Err(StatementError::UnsupportedForm { dialect: self.name(), form: spec.form().name() }) }
    /// }
    ///
    /// // A table at one of these levels mounts on `Mssql`.
    /// impl Opens<level::ReadCommitted> for Mssql {}
    /// impl Opens<level::RepeatableRead> for Mssql {}
    /// ```
    #[must_use]
    pub const fn name(self) -> &'static str {
        match self {
            Self::Default => "the database's default",
            Self::Isolation(Isolation::ReadUncommitted) => "isolation `read_uncommitted`",
            Self::Isolation(Isolation::ReadCommitted) => "isolation `read_committed`",
            Self::Isolation(Isolation::RepeatableRead) => "isolation `repeatable_read`",
            Self::Isolation(Isolation::Serializable) => "isolation `serializable`",
            Self::Mode(Mode::Deferred) => "mode `deferred`",
            Self::Mode(Mode::Immediate) => "mode `immediate`",
            Self::Mode(Mode::Exclusive) => "mode `exclusive`",
        }
    }

    /// The refusal of the dialect named `dialect`, which opens no transaction at `self`.
    pub(crate) const fn refused(self, dialect: &'static str) -> StatementError {
        StatementError::UnsupportedOpening {
            dialect,
            opening: self.name(),
        }
    }
}

/// The isolation levels and SQLite modes as types: a table names one, and its dialect opens it
/// where it implements [`Opens`] for it.
///
/// A table that names a level carries it twice: as one of these types, which the bound on its
/// dialect checks when the service compiles, and as the [`Opening`] in its description, which
/// [`Dialect::begin`] turns into a statement.
///
/// # Examples
///
/// A dialect implements `Opens` for each level its `begin` opens:
///
/// ```
/// # use std::num::NonZeroUsize;
/// # use ruststream_sqlx_dialect::TableName;
/// use ruststream_sqlx_dialect::{
///     Dialect, Isolation, Opening, Opens, Statement, StatementError, TableSpec, level,
/// };
///
/// /// SQL Server, a database without a built-in dialect.
/// #[derive(Debug)]
/// pub struct Mssql;
///
/// impl Dialect for Mssql {
///     fn name(&self) -> &'static str {
///         "mssql"
///     }
///
///     fn begin(&self, opening: Opening) -> Result<Option<&'static str>, StatementError> {
///         match opening {
///             Opening::Default | Opening::Isolation(Isolation::ReadCommitted) => Ok(Some(
///                 "SET TRANSACTION ISOLATION LEVEL READ COMMITTED; BEGIN TRANSACTION",
///             )),
///             Opening::Isolation(Isolation::RepeatableRead) => Ok(Some(
///                 "SET TRANSACTION ISOLATION LEVEL REPEATABLE READ; BEGIN TRANSACTION",
///             )),
///             other => Err(StatementError::UnsupportedOpening {
///                 dialect: self.name(),
///                 opening: other.name(),
///             }),
///         }
///     }
/// #     fn quote_into(&self, ident: &str, out: &mut String) { out.push('['); out.push_str(&ident.replace(']', "]]")); out.push(']'); }
/// #     fn placeholder_into(&self, index: NonZeroUsize, out: &mut String) { out.push_str("@p"); out.push_str(&index.to_string()); }
/// #     fn fetch(&self, spec: &TableSpec<'_>) -> Result<Statement, StatementError> { Err(StatementError::UnsupportedFetch { dialect: self.name() }) }
/// #     fn ack(&self, spec: &TableSpec<'_>) -> Result<Statement, StatementError> { Err(StatementError::UnsupportedForm { dialect: self.name(), form: spec.form().name() }) }
/// #     fn retry(&self, spec: &TableSpec<'_>) -> Result<Option<Statement>, StatementError> { Err(StatementError::UnsupportedForm { dialect: self.name(), form: spec.form().name() }) }
/// #     fn retry_after(&self, spec: &TableSpec<'_>) -> Result<Statement, StatementError> { Err(StatementError::UnsupportedForm { dialect: self.name(), form: spec.form().name() }) }
/// #     fn discard(&self, spec: &TableSpec<'_>) -> Result<Statement, StatementError> { Err(StatementError::UnsupportedForm { dialect: self.name(), form: spec.form().name() }) }
/// #     fn dead_letter_group(&self, spec: &TableSpec<'_>) -> Result<Statement, StatementError> { Err(StatementError::UnsupportedForm { dialect: self.name(), form: spec.form().name() }) }
/// #     fn dead_letter_table(&self, spec: &TableSpec<'_>, target: TableName<'_>) -> Result<Vec<Statement>, StatementError> { Err(StatementError::UnsupportedForm { dialect: self.name(), form: spec.form().name() }) }
/// #     fn insert(&self, spec: &TableSpec<'_>) -> Result<Statement, StatementError> { Err(StatementError::UnsupportedForm { dialect: self.name(), form: spec.form().name() }) }
/// }
///
/// // A table at `read_committed` or `repeatable_read` mounts on `Mssql`.
/// impl Opens<level::ReadCommitted> for Mssql {}
/// impl Opens<level::RepeatableRead> for Mssql {}
/// ```
pub mod level;

/// A dialect that opens transactions at `Level`: an isolation level or a SQLite mode as one of
/// the [`level`] types, or `()`, which a table that names neither carries.
///
/// A subscription requires `Opens<Level>` of its table's dialect, so a table that names a level
/// its dialect lacks does not compile. Every dialect opens `()`. A dialect implements
/// `Opens<Level>` for each level whose [`Opening`] its [`begin`](Dialect::begin) opens:
/// [`Postgres`](crate::Postgres) READ COMMITTED, REPEATABLE READ and SERIALIZABLE;
/// [`MySql`](crate::MySql) those and READ UNCOMMITTED; [`Sqlite`](crate::Sqlite) its three
/// modes.
///
/// # Examples
///
/// A dialect of the service's own opens the levels its `begin` opens:
///
/// ```
/// # use std::num::NonZeroUsize;
/// # use ruststream_sqlx_dialect::TableName;
/// use ruststream_sqlx_dialect::{
///     Dialect, Isolation, Opening, Opens, Statement, StatementError, TableSpec, level,
/// };
///
/// /// SQL Server, a database without a built-in dialect.
/// #[derive(Debug)]
/// pub struct Mssql;
///
/// impl Dialect for Mssql {
///     fn name(&self) -> &'static str {
///         "mssql"
///     }
///
///     fn begin(&self, opening: Opening) -> Result<Option<&'static str>, StatementError> {
///         match opening {
///             Opening::Default | Opening::Isolation(Isolation::ReadCommitted) => Ok(Some(
///                 "SET TRANSACTION ISOLATION LEVEL READ COMMITTED; BEGIN TRANSACTION",
///             )),
///             Opening::Isolation(Isolation::RepeatableRead) => Ok(Some(
///                 "SET TRANSACTION ISOLATION LEVEL REPEATABLE READ; BEGIN TRANSACTION",
///             )),
///             other => Err(StatementError::UnsupportedOpening {
///                 dialect: self.name(),
///                 opening: other.name(),
///             }),
///         }
///     }
/// #     fn quote_into(&self, ident: &str, out: &mut String) { out.push('['); out.push_str(&ident.replace(']', "]]")); out.push(']'); }
/// #     fn placeholder_into(&self, index: NonZeroUsize, out: &mut String) { out.push_str("@p"); out.push_str(&index.to_string()); }
/// #     fn fetch(&self, spec: &TableSpec<'_>) -> Result<Statement, StatementError> { Err(StatementError::UnsupportedFetch { dialect: self.name() }) }
/// #     fn ack(&self, spec: &TableSpec<'_>) -> Result<Statement, StatementError> { Err(StatementError::UnsupportedForm { dialect: self.name(), form: spec.form().name() }) }
/// #     fn retry(&self, spec: &TableSpec<'_>) -> Result<Option<Statement>, StatementError> { Err(StatementError::UnsupportedForm { dialect: self.name(), form: spec.form().name() }) }
/// #     fn retry_after(&self, spec: &TableSpec<'_>) -> Result<Statement, StatementError> { Err(StatementError::UnsupportedForm { dialect: self.name(), form: spec.form().name() }) }
/// #     fn discard(&self, spec: &TableSpec<'_>) -> Result<Statement, StatementError> { Err(StatementError::UnsupportedForm { dialect: self.name(), form: spec.form().name() }) }
/// #     fn dead_letter_group(&self, spec: &TableSpec<'_>) -> Result<Statement, StatementError> { Err(StatementError::UnsupportedForm { dialect: self.name(), form: spec.form().name() }) }
/// #     fn dead_letter_table(&self, spec: &TableSpec<'_>, target: TableName<'_>) -> Result<Vec<Statement>, StatementError> { Err(StatementError::UnsupportedForm { dialect: self.name(), form: spec.form().name() }) }
/// #     fn insert(&self, spec: &TableSpec<'_>) -> Result<Statement, StatementError> { Err(StatementError::UnsupportedForm { dialect: self.name(), form: spec.form().name() }) }
/// }
///
/// // A table at one of these levels mounts on `Mssql`; one at any other level does not compile.
/// impl Opens<level::ReadCommitted> for Mssql {}
/// impl Opens<level::RepeatableRead> for Mssql {}
/// ```
///
/// SQLite opens no transaction at an isolation level, so the same subscription on SQLite does
/// not compile:
///
/// ```compile_fail
/// # #[cfg(not(feature = "sqlite"))]
/// # compile_error!("the example needs the sqlite feature");
/// # #[cfg(feature = "sqlite")]
/// # mod demo {
/// use ruststream_sqlx_dialect::{Isolation, Opening, Opens, Sqlite, StatementError, level};
///
/// fn serializable<D: Opens<level::Serializable>>(
///     dialect: &D,
/// ) -> Result<Option<&'static str>, StatementError> {
///     dialect.begin(Opening::Isolation(Isolation::Serializable))
/// }
///
/// fn subscribe() -> Result<Option<&'static str>, StatementError> {
///     serializable(&Sqlite)
/// }
/// # }
/// # fn main() {}
/// ```
#[diagnostic::on_unimplemented(
    message = "the `{Self}` dialect opens no transaction at `{Level}`",
    label = "the table's `isolation` or `mode` names it",
    note = "Postgres opens `read_committed`, `repeatable_read` and `serializable`; MySQL and \
            MariaDB those and `read_uncommitted`; SQLite takes the modes `deferred`, \
            `immediate` and `exclusive`",
    note = "a dialect of the service's own opens a level by implementing `Opens<Level>` and \
            `Dialect::begin`"
)]
pub trait Opens<Level>: Dialect {}

impl<D: Dialect> Opens<()> for D {}

#[cfg(test)]
mod tests {
    use super::{Isolation, Mode, Opening};
    use crate::statement::StatementError;

    #[test]
    fn a_level_names_itself_in_sql_and_as_a_table_does() {
        let levels = [
            Isolation::ReadUncommitted,
            Isolation::ReadCommitted,
            Isolation::RepeatableRead,
            Isolation::Serializable,
        ];
        assert_eq!(
            levels.map(Isolation::sql),
            [
                "READ UNCOMMITTED",
                "READ COMMITTED",
                "REPEATABLE READ",
                "SERIALIZABLE"
            ]
        );
        assert_eq!(
            levels.map(Isolation::attribute),
            [
                "read_uncommitted",
                "read_committed",
                "repeatable_read",
                "serializable"
            ]
        );
    }

    #[test]
    fn a_mode_names_itself_in_sql_and_as_a_table_does() {
        let modes = [Mode::Deferred, Mode::Immediate, Mode::Exclusive];
        assert_eq!(modes.map(Mode::sql), ["DEFERRED", "IMMEDIATE", "EXCLUSIVE"]);
        assert_eq!(
            modes.map(Mode::attribute),
            ["deferred", "immediate", "exclusive"]
        );
    }

    #[test]
    fn an_opening_names_itself_for_messages() {
        let openings = [
            Opening::default(),
            Opening::Isolation(Isolation::ReadUncommitted),
            Opening::Isolation(Isolation::ReadCommitted),
            Opening::Isolation(Isolation::RepeatableRead),
            Opening::Isolation(Isolation::Serializable),
            Opening::Mode(Mode::Deferred),
            Opening::Mode(Mode::Immediate),
            Opening::Mode(Mode::Exclusive),
        ];
        assert_eq!(
            openings.map(Opening::name),
            [
                "the database's default",
                "isolation `read_uncommitted`",
                "isolation `read_committed`",
                "isolation `repeatable_read`",
                "isolation `serializable`",
                "mode `deferred`",
                "mode `immediate`",
                "mode `exclusive`",
            ]
        );
    }

    #[test]
    fn a_refusal_names_the_dialect_and_the_opening() {
        assert_eq!(
            Opening::Mode(Mode::Exclusive).refused("postgres"),
            StatementError::UnsupportedOpening {
                dialect: "postgres",
                opening: "mode `exclusive`",
            }
        );
    }
}