Skip to main content

ruprizzle_dialect/
lib.rs

1//! SQL dialect abstraction.
2//!
3//! This crate is the seam between the dialect-agnostic [`Schema`] produced by the
4//! parser and the SQL that a specific database understands. It is used by both
5//! the migration engine (which needs DDL) and the codegen crate (which needs Rust
6//! types and dialect-specific warnings).
7//!
8//! # Design
9//!
10//! * The [`DbDialect`] trait is **object-safe** and the single interface the rest
11//!   of the workspace talks to.
12//! * Every DDL operation returns a [`Vec<Stmt>`] because one logical change can
13//!   require several physical statements, especially on SQLite.
14//! * [`Stmt`] carries `destructive` and `transactional` metadata so the migration
15//!   planner does not have to rediscover per-dialect quirks.
16//! * Helper functions such as [`full_create_table`] and [`full_alter_column`] take
17//!   a full [`Schema`] because generating correct foreign keys and table rebuilds
18//!   needs resolved relation information that a single [`Model`] does not carry.
19//!
20//! # Adding a dialect
21//!
22//! 1. Add a variant to [`Provider`](ruprizzle_core::ir::Provider) in `core`.
23//! 2. Implement [`DbDialect`] for a new type.
24//! 3. Add it to [`dialect_for`].
25//! 4. Add a row to the conformance suite so the new backend cannot rot.
26
27#![forbid(unsafe_code)]
28#![warn(missing_docs, clippy::pedantic)]
29#![allow(
30    clippy::doc_markdown,
31    clippy::struct_excessive_bools,
32    clippy::too_many_lines
33)]
34
35mod common;
36mod mysql;
37mod postgres;
38mod sqlite;
39
40use ruprizzle_core::ir::{
41    EnumDef, Field, IndexDef, Model, ResolvedRelation, ScalarType, Schema, UniqueDef,
42};
43
44pub use common::{
45    check_schema_capabilities, dialect_for, full_alter_column, full_alter_column_with_source,
46    full_create_table,
47};
48pub use mysql::MySqlDialect;
49pub use postgres::PostgresDialect;
50pub use sqlite::SqliteDialect;
51
52/// A single DDL statement plus metadata the migration planner needs.
53#[derive(Debug, Clone, PartialEq, Eq)]
54pub struct Stmt {
55    /// The SQL text to execute.
56    pub sql: String,
57    /// Whether the statement can silently delete user data.
58    pub destructive: bool,
59    /// Whether the statement must run inside a transaction.
60    pub transactional: bool,
61    /// A comment surfaced in the generated migration file.
62    pub note: Option<String>,
63}
64
65impl Stmt {
66    /// Creates a plain, transactional, non-destructive statement.
67    #[must_use]
68    pub fn new(sql: impl Into<String>) -> Self {
69        Self {
70            sql: sql.into(),
71            destructive: false,
72            transactional: true,
73            note: None,
74        }
75    }
76
77    /// Adds a note to the statement.
78    #[must_use]
79    pub fn with_note(mut self, note: impl Into<String>) -> Self {
80        self.note = Some(note.into());
81        self
82    }
83
84    /// Marks the statement as destructive.
85    #[must_use]
86    pub fn destructive(mut self) -> Self {
87        self.destructive = true;
88        self
89    }
90
91    /// Marks the statement as non-transactional.
92    #[must_use]
93    pub fn non_transactional(mut self) -> Self {
94        self.transactional = false;
95        self
96    }
97}
98
99/// What a dialect can and cannot do.
100#[derive(Debug, Clone, Copy, PartialEq, Eq)]
101pub struct Capabilities {
102    /// Native `CREATE TYPE` for enums.
103    pub native_enums: bool,
104    /// Native UUID storage.
105    pub native_uuid: bool,
106    /// `ALTER TABLE ... ALTER COLUMN` can change the type.
107    pub alter_column_type: bool,
108    /// `ALTER TABLE ... DROP COLUMN` is supported.
109    pub drop_column: bool,
110    /// Foreign keys can be added after the table is created.
111    pub add_fk_after_create: bool,
112    /// `RETURNING` is supported.
113    pub returning: bool,
114    /// Partial indexes (`WHERE ...`) are supported.
115    pub partial_indexes: bool,
116    /// `DEFERRABLE` foreign keys are supported.
117    pub deferrable_fks: bool,
118    /// How `Json` is stored.
119    pub json_type: JsonSupport,
120    /// Maximum number of bind parameters in a single statement.
121    pub max_query_params: u32,
122    /// PostGIS extension is enabled.
123    pub postgis: bool,
124    /// `ROW_NUMBER() OVER (PARTITION BY ...)` and friends are supported.
125    ///
126    /// The relation loader needs this to honour a per-parent `take` in a single
127    /// query. Without it the loader falls back to one query per parent, which is
128    /// correct but no longer bounded.
129    pub window_functions: bool,
130}
131
132/// How a dialect stores JSON.
133#[derive(Debug, Clone, Copy, PartialEq, Eq)]
134pub enum JsonSupport {
135    /// A native JSON type.
136    Native,
137    /// Stored as `TEXT` and parsed on read.
138    TextEncoded,
139    /// Not supported at all.
140    None,
141}
142
143/// The Rust type a column maps to, as seen by codegen.
144///
145/// In v1 this is the same for every dialect — the whole point of the abstraction
146/// is that application code does not change when you switch `provider`. The
147/// dialect reports this type so codegen does not have to hard-code the matrix.
148#[derive(Debug, Clone, PartialEq, Eq)]
149pub enum RustType {
150    /// `String`.
151    String,
152    /// `i32`.
153    Int,
154    /// `i64`.
155    BigInt,
156    /// `f64`.
157    Float,
158    /// `rust_decimal::Decimal`.
159    Decimal,
160    /// `bool`.
161    Boolean,
162    /// `chrono::DateTime<Utc>`.
163    DateTime,
164    /// `chrono::NaiveDate`.
165    Date,
166    /// `chrono::NaiveTime`.
167    Time,
168    /// `uuid::Uuid`.
169    Uuid,
170    /// `serde_json::Value`.
171    Json,
172    /// `Vec<u8>`.
173    Bytes,
174    /// `ruprizzle::Point`.
175    Point,
176    /// `ruprizzle::Polygon`.
177    Polygon,
178    /// `ruprizzle::MultiPolygon`.
179    MultiPolygon,
180    /// `ruprizzle::LineString`.
181    LineString,
182    /// A generated enum with the given name.
183    Enum(String),
184    /// `Option<T>`.
185    Option(Box<RustType>),
186    /// `Vec<T>` for scalar or enum lists.
187    Vec(Box<RustType>),
188}
189
190/// An error produced while turning an IR field into a SQL column.
191///
192/// `#[non_exhaustive]`: this is a diagnostic type, and new dialects and new
193/// unsupported-construct classes add variants without that being a breaking
194/// change. Match with a trailing `_ =>` arm.
195#[derive(Debug, thiserror::Error)]
196#[non_exhaustive]
197pub enum DialectError {
198    /// A `@db.*` native type is not supported by this dialect.
199    #[error("`@db.{name}` is not supported on {dialect}")]
200    UnsupportedNativeType {
201        /// The dialect that rejected the type.
202        dialect: String,
203        /// Name of the native type, e.g. `VarChar`.
204        name: String,
205        /// Physical column the type was applied to.
206        column: String,
207    },
208
209    /// A `@db.*` native type got an argument it does not accept.
210    #[error("`@db.{name}({args})` is not valid: {reason}")]
211    InvalidNativeArg {
212        /// Name of the native type.
213        name: String,
214        /// Arguments as written.
215        args: String,
216        /// Why it is wrong.
217        reason: String,
218    },
219}
220
221/// The SQL dialect abstraction.
222///
223/// The trait is object-safe: `&dyn DbDialect` can be passed around, and
224/// `dialect_for` returns a cheap `'static` reference. Implementations live in
225/// [`PostgresDialect`], [`MySqlDialect`], and [`SqliteDialect`].
226pub trait DbDialect: Send + Sync {
227    /// The canonical name of the dialect, e.g. `"postgres"`.
228    fn name(&self) -> &'static str;
229
230    // ---- identifiers & literals ----
231
232    /// Quote an identifier: `"users"` (PostgreSQL) / `` `users` `` (SQLite).
233    fn quote_ident(&self, s: &str) -> String;
234
235    /// Positional placeholder: `$1` (PostgreSQL) / `?` (SQLite).
236    fn placeholder(&self, index: usize) -> String;
237
238    // ---- type mapping ----
239
240    /// SQL type for a column, before nullability or defaults are added.
241    ///
242    /// # Errors
243    ///
244    /// Returns an error when a `@db.*` native type is unsupported by this dialect.
245    fn column_type(&self, f: &Field) -> Result<String, DialectError>;
246
247    /// Rust type for a column, used by codegen.
248    fn rust_type(&self, f: &Field) -> RustType;
249
250    // ---- DDL ----
251
252    /// `CREATE TABLE` for the body of a model.
253    ///
254    /// Foreign keys are intentionally emitted separately. For the full
255    /// statement that a new schema needs, use [`full_create_table`].
256    fn create_table(&self, schema: &Schema, m: &Model) -> Vec<Stmt>;
257
258    /// `DROP TABLE`.
259    fn drop_table(&self, table: &str) -> Vec<Stmt>;
260
261    /// `ALTER TABLE ... ADD COLUMN`.
262    fn add_column(&self, schema: &Schema, m: &Model, f: &Field) -> Vec<Stmt>;
263
264    /// `ALTER TABLE ... DROP COLUMN`.
265    fn drop_column(&self, table: &str, col: &str) -> Vec<Stmt>;
266
267    /// Change a column.
268    ///
269    /// On PostgreSQL this is a direct `ALTER TABLE`. On SQLite it is the
270    /// beginning of a table rebuild; for the complete rebuild sequence use
271    /// [`full_alter_column`].
272    fn alter_column(&self, schema: &Schema, m: &Model, from: &Field, to: &Field) -> Vec<Stmt>;
273
274    /// `CREATE INDEX`.
275    fn create_index(&self, m: &Model, ix: &IndexDef) -> Vec<Stmt>;
276
277    /// `DROP INDEX`.
278    fn drop_index(&self, table: &str, name: &str) -> Vec<Stmt>;
279
280    /// `CREATE UNIQUE INDEX` or `ALTER TABLE ... ADD CONSTRAINT ... UNIQUE`.
281    fn add_unique(&self, m: &Model, uq: &UniqueDef) -> Vec<Stmt>;
282
283    /// `DROP INDEX` or `ALTER TABLE ... DROP CONSTRAINT ...`.
284    fn drop_unique(&self, table: &str, name: &str) -> Vec<Stmt>;
285
286    /// Add a foreign key for a resolved relation.
287    ///
288    /// * PostgreSQL returns a standalone `ALTER TABLE ... ADD CONSTRAINT`.
289    /// * SQLite returns the inline `CONSTRAINT ... FOREIGN KEY` clause that
290    ///   must be embedded in `CREATE TABLE`.
291    fn add_foreign_key(&self, m: &Model, r: &ResolvedRelation) -> Vec<Stmt>;
292
293    /// `ALTER TABLE ... DROP CONSTRAINT` (PostgreSQL) or a no-op (SQLite).
294    fn drop_foreign_key(&self, m: &Model, r: &ResolvedRelation) -> Vec<Stmt>;
295
296    /// `CREATE TYPE ... AS ENUM` (PostgreSQL) or a no-op (SQLite).
297    fn create_enum(&self, e: &EnumDef) -> Vec<Stmt>;
298
299    /// Add a variant to an existing enum.
300    fn alter_enum_add_variant(&self, e: &EnumDef, v: &str) -> Vec<Stmt>;
301
302    // ---- DML fragments used by the query builder ----
303
304    /// Whether `RETURNING` is supported.
305    fn returning_supported(&self) -> bool;
306
307    /// The `ON CONFLICT` clause for an upsert.
308    fn upsert_clause(&self, conflict: &[String], update: &[String]) -> String;
309
310    /// The `LIMIT ... OFFSET ...` fragment.
311    fn limit_offset(&self, limit: Option<u64>, offset: Option<u64>) -> String;
312
313    /// Cast an expression to a scalar type.
314    fn cast_expr(&self, expr: &str, ty: ScalarType) -> String;
315
316    // ---- capabilities ----
317
318    /// The capabilities of this dialect.
319    fn capabilities(&self) -> Capabilities;
320
321    /// Whether `RIGHT JOIN` is supported.
322    fn supports_right_join(&self) -> bool {
323        true
324    }
325
326    /// Whether `FULL OUTER JOIN` is supported.
327    fn supports_full_join(&self) -> bool {
328        true
329    }
330
331    /// Whether `INTERSECT` is supported.
332    fn supports_intersect(&self) -> bool {
333        true
334    }
335
336    /// Whether `EXCEPT` is supported.
337    fn supports_except(&self) -> bool {
338        true
339    }
340}