Skip to main content

toolu_orm_core/
dialect.rs

1//! Dialect enum (Postgres/SQLite) and compile-time dispatch.
2
3/// SQL dialect for code generation.
4///
5/// Selected at compile time via the `postgres` feature flag.
6/// [`Dialect::CURRENT`] resolves to the active dialect.
7#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8pub enum Dialect {
9  Sqlite,
10  Postgres,
11}
12
13impl Dialect {
14  #[must_use]
15  pub const fn as_str(self) -> &'static str {
16    match self {
17      Self::Sqlite => "sqlite",
18      Self::Postgres => "postgres",
19    }
20  }
21
22  /// The dialect selected at compile time.
23  #[cfg(feature = "postgres")]
24  pub const CURRENT: Dialect = Dialect::Postgres;
25
26  /// The dialect selected at compile time.
27  #[cfg(not(feature = "postgres"))]
28  pub const CURRENT: Dialect = Dialect::Sqlite;
29
30  /// Positional parameter placeholder for this dialect.
31  ///
32  /// SQLite uses `?N`, Postgres uses `$N`.
33  pub fn param(self, index: usize) -> String {
34    match self {
35      Self::Sqlite => format!("?{index}"),
36      Self::Postgres => format!("${index}"),
37    }
38  }
39
40  /// Translate SQLite-specific default expressions to their Postgres equivalents.
41  ///
42  /// Unknown defaults pass through unchanged.
43  pub fn map_default(self, default: &str) -> String {
44    match self {
45      Self::Sqlite => default.to_owned(),
46      Self::Postgres => match default {
47        "unixepoch()" => "extract(epoch from now())::bigint".to_owned(),
48        "uuid4_str()" => "gen_random_uuid()".to_owned(),
49        other => other.to_owned(),
50      },
51    }
52  }
53
54  /// SQL expression for the current Unix epoch in seconds.
55  ///
56  /// Postgres: `extract(epoch from now())::bigint`; SQLite/libsql: `unixepoch()`.
57  /// Use this instead of hardcoding the Postgres form in raw SQL / `set_expr`.
58  #[must_use]
59  pub const fn now_epoch(self) -> &'static str {
60    match self {
61      Self::Sqlite => "unixepoch()",
62      Self::Postgres => "extract(epoch from now())::bigint",
63    }
64  }
65
66  /// Quote a SQL identifier (table name, column name).
67  ///
68  /// Both SQLite and Postgres use double quotes for identifiers.
69  pub fn quote_ident(self, ident: &str) -> String {
70    format!(r#""{ident}""#)
71  }
72}