dialect.rs 4.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. //! The SQL dialect seam: the one place the SQLite/PostgreSQL divergence lives.
  2. //!
  3. //! Resolved once at construction from the pool's connection URL (no query), so
  4. //! the write paths read a plain enum instead of re-probing the backend. A third
  5. //! backend becomes a new variant here, not edits across every `impl`.
  6. use sqlx::{Any, Pool};
  7. /// Which SQL backend a [`SqlStore`](crate::SqlStore) is talking to.
  8. #[derive(Clone, Copy, Debug, PartialEq, Eq)]
  9. pub(crate) enum Dialect {
  10. /// PostgreSQL: supports `SELECT ... FOR UPDATE` row locking.
  11. Postgres,
  12. /// SQLite: no `FOR UPDATE`; it serializes writers itself.
  13. Sqlite,
  14. }
  15. impl Dialect {
  16. /// Resolve the dialect from the pool's connection URL scheme. Synchronous
  17. /// and issues no query. Anything that is not `sqlite` is treated as
  18. /// PostgreSQL, matching the prior runtime probe (which classified any
  19. /// non-SQLite backend as Postgres).
  20. pub(crate) fn from_pool(pool: &Pool<Any>) -> Self {
  21. match pool.connect_options().database_url.scheme() {
  22. "sqlite" => Self::Sqlite,
  23. _ => Self::Postgres,
  24. }
  25. }
  26. /// The placeholder for binding an amount, as it must appear in the SQL.
  27. ///
  28. /// PostgreSQL stores amounts as `NUMERIC(39,0)` and the value arrives as
  29. /// text (the `Any` driver has no numeric kind), so the cast is required
  30. /// rather than cosmetic: `text` to `numeric` is explicit-only in `pg_cast`,
  31. /// and a bare placeholder is rejected. SQLite binds the 16-byte encoding
  32. /// straight into a `BLOB`.
  33. pub(crate) fn money_bind(self, n: u32) -> String {
  34. match self {
  35. Self::Postgres => format!("CAST(${n} AS NUMERIC)"),
  36. Self::Sqlite => format!("${n}"),
  37. }
  38. }
  39. /// How an amount column must be named in a `SELECT` list.
  40. ///
  41. /// The cast is mandatory on PostgreSQL, and not only so the value can be
  42. /// parsed: `AnyRow` converts every column's type before any of them is
  43. /// read, and it has no mapping for `NUMERIC`, so one uncast amount fails
  44. /// the whole row even when nothing reads it.
  45. pub(crate) fn money_read(self, col: &str) -> String {
  46. match self {
  47. Self::Postgres => format!("CAST({col} AS TEXT) AS {col}"),
  48. Self::Sqlite => col.to_string(),
  49. }
  50. }
  51. /// An exact sum over an amount column, as a `SELECT` list entry.
  52. ///
  53. /// Both sides are exact and neither wraps: `NUMERIC` is arbitrary
  54. /// precision, and `kuatia_i128_sum` accumulates with `i128::checked_add`
  55. /// and raises rather than overflowing. `COALESCE` and the aggregate's
  56. /// zero-for-no-rows make an empty group a real row, so callers never have
  57. /// to special-case `NULL`.
  58. pub(crate) fn money_sum(self, col: &str) -> String {
  59. match self {
  60. Self::Postgres => format!("CAST(COALESCE(SUM({col}), 0) AS TEXT)"),
  61. Self::Sqlite => format!("kuatia_i128_sum({col})"),
  62. }
  63. }
  64. /// The `SELECT` list [`row_to_posting`](crate::row::row_to_posting) reads.
  65. /// Spelled out rather than `*` because the amount column needs
  66. /// [`money_read`](Self::money_read); the six columns are shared by
  67. /// `postings` and `live_postings`.
  68. /// The explicit column list for a posting read, including the asset
  69. /// definition joined from the registry: a posting carries an amount, and an
  70. /// amount carries its asset. Pair it with [`joined`](crate::posting::joined).
  71. pub(crate) fn posting_columns(self) -> String {
  72. format!(
  73. "transfer_id, idx, owner, subaccount, asset, assets.data AS asset_def, {}",
  74. self.money_read("value")
  75. )
  76. }
  77. /// Row-locking clause appended to a `SELECT` that takes a pessimistic lock:
  78. /// ` FOR UPDATE` on Postgres, empty on SQLite (which has no such clause and
  79. /// serializes writers itself).
  80. pub(crate) fn lock_clause(self) -> &'static str {
  81. match self {
  82. Self::Postgres => " FOR UPDATE",
  83. Self::Sqlite => "",
  84. }
  85. }
  86. }