Skip to main content

toasty_sql/serializer/
dialect.rs

1use super::Serializer;
2
3use toasty_core::{
4    driver::{Dialect, SqlPlaceholder},
5    schema::db,
6};
7
8impl<'a> Serializer<'a> {
9    /// Creates a serializer for `dialect` with the standard `BEGIN` for
10    /// [`TransactionMode::Default`].
11    pub fn new(dialect: Dialect, schema: &'a db::Schema) -> Self {
12        Serializer {
13            schema,
14            dialect,
15            sqlite_default_begin: "BEGIN",
16        }
17    }
18
19    /// Creates a serializer that emits SQLite SQL.
20    pub fn sqlite(schema: &'a db::Schema) -> Self {
21        Self::new(Dialect::Sqlite, schema)
22    }
23
24    /// Creates a SQLite-dialect serializer with a custom SQL string for
25    /// [`TransactionMode::Default`].
26    ///
27    /// Used by SQLite-compatible engines whose preferred "no opinion" BEGIN
28    /// is not the classic deferred form — e.g. Turso with
29    /// `concurrent_writes()` enabled, where `Default` means `BEGIN
30    /// CONCURRENT`. The non-`Default` modes (`Deferred`, `Immediate`,
31    /// `Exclusive`) still map to their standard SQLite SQL.
32    pub fn sqlite_with_default_begin(schema: &'a db::Schema, default_begin: &'static str) -> Self {
33        Serializer {
34            schema,
35            dialect: Dialect::Sqlite,
36            sqlite_default_begin: default_begin,
37        }
38    }
39
40    /// Returns `true` if this serializer targets SQLite.
41    pub fn is_sqlite(&self) -> bool {
42        matches!(self.dialect, Dialect::Sqlite)
43    }
44
45    /// Creates a serializer that emits PostgreSQL SQL.
46    pub fn postgresql(schema: &'a db::Schema) -> Self {
47        Self::new(Dialect::Postgresql, schema)
48    }
49
50    /// Creates a serializer that emits MySQL SQL.
51    pub fn mysql(schema: &'a db::Schema) -> Self {
52        Self::new(Dialect::Mysql, schema)
53    }
54
55    /// Creates a serializer that emits MariaDB SQL.
56    pub fn mariadb(schema: &'a db::Schema) -> Self {
57        Self::new(Dialect::MariaDb, schema)
58    }
59
60    /// Returns `true` for both MySQL and MariaDB.
61    ///
62    /// Most rendering is shared; the places that are not match on
63    /// [`Dialect`] directly.
64    pub(super) fn is_mysql(&self) -> bool {
65        matches!(self.dialect, Dialect::Mysql | Dialect::MariaDb)
66    }
67}
68
69/// The placeholder syntax a dialect's bind layer accepts.
70pub(super) fn sql_placeholder(dialect: Dialect) -> SqlPlaceholder {
71    match dialect {
72        Dialect::Postgresql => SqlPlaceholder::DollarNumber,
73        Dialect::Sqlite => SqlPlaceholder::NumberedQuestionMark,
74        Dialect::Mysql | Dialect::MariaDb => SqlPlaceholder::QuestionMark,
75    }
76}