Skip to main content

rok_db_codegen/
ir.rs

1//! The schema model built from `.sql` files. It is also the snapshot
2//! (`schema.json`) that the next migration is computed against.
3
4use serde::{Deserialize, Serialize};
5
6/// Everything the `.sql` files declare, in a stable order.
7#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
8pub struct Schema {
9    /// `CREATE TYPE ... AS ENUM`.
10    pub enums: Vec<EnumType>,
11    /// `CREATE TABLE`, in file order.
12    pub tables: Vec<Table>,
13    /// `CREATE INDEX`.
14    pub indexes: Vec<Index>,
15    /// Other statements (extensions, views, functions, comments ...).
16    pub extras: Vec<Extra>,
17}
18
19/// A PostgreSQL enum type.
20#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
21pub struct EnumType {
22    /// Type name, possibly schema-qualified.
23    pub name: String,
24    /// Labels, in order.
25    pub values: Vec<String>,
26    /// Module (file stem) that declares it.
27    pub module: String,
28    /// Doc comment lines.
29    #[serde(default, skip_serializing_if = "Vec::is_empty")]
30    pub doc: Vec<String>,
31}
32
33/// A table.
34#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
35pub struct Table {
36    /// Table name, possibly schema-qualified.
37    pub name: String,
38    /// Module (file stem) that declares it.
39    pub module: String,
40    /// Doc comment lines.
41    #[serde(default, skip_serializing_if = "Vec::is_empty")]
42    pub doc: Vec<String>,
43    /// Columns, in order.
44    pub columns: Vec<Column>,
45    /// Primary key columns (empty: none).
46    pub primary_key: Vec<String>,
47    /// `UNIQUE` constraints.
48    #[serde(default, skip_serializing_if = "Vec::is_empty")]
49    pub uniques: Vec<Unique>,
50    /// `FOREIGN KEY` constraints.
51    #[serde(default, skip_serializing_if = "Vec::is_empty")]
52    pub foreign_keys: Vec<ForeignKey>,
53    /// `CHECK` constraints.
54    #[serde(default, skip_serializing_if = "Vec::is_empty")]
55    pub checks: Vec<Check>,
56}
57
58impl Table {
59    /// The column named `name`.
60    pub fn column(&self, name: &str) -> Option<&Column> {
61        self.columns.iter().find(|c| c.name == name)
62    }
63
64    /// Whether `columns` are covered by a single-column or composite unique
65    /// constraint (or are the primary key).
66    pub fn is_unique(&self, columns: &[String]) -> bool {
67        self.primary_key == columns || self.uniques.iter().any(|u| u.columns == columns)
68    }
69}
70
71/// A column.
72#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
73pub struct Column {
74    /// Column name.
75    pub name: String,
76    /// Canonical SQL type (`BIGINT`, `VARCHAR(255)`, `user_role`).
77    pub sql_type: String,
78    /// Whether `NULL` is allowed.
79    pub nullable: bool,
80    /// `DEFAULT` expression.
81    #[serde(default, skip_serializing_if = "Option::is_none")]
82    pub default: Option<String>,
83    /// `GENERATED ALWAYS AS (expr) STORED` expression.
84    #[serde(default, skip_serializing_if = "Option::is_none")]
85    pub generated: Option<String>,
86    /// `GENERATED { ALWAYS | BY DEFAULT } AS IDENTITY`.
87    #[serde(default, skip_serializing_if = "Option::is_none")]
88    pub identity: Option<String>,
89    /// Marked `-- rok:tenant`.
90    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
91    pub tenant: bool,
92    /// Doc comment lines.
93    #[serde(default, skip_serializing_if = "Vec::is_empty")]
94    pub doc: Vec<String>,
95}
96
97impl Column {
98    /// Whether the database fills the column in when it is not written.
99    pub fn has_database_value(&self) -> bool {
100        self.default.is_some()
101            || self.generated.is_some()
102            || self.identity.is_some()
103            || crate::types::is_serial(&self.sql_type)
104    }
105}
106
107/// A `UNIQUE` constraint.
108#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
109pub struct Unique {
110    /// Constraint name.
111    pub name: String,
112    /// Columns.
113    pub columns: Vec<String>,
114}
115
116/// A `FOREIGN KEY` constraint.
117#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
118pub struct ForeignKey {
119    /// Constraint name.
120    pub name: String,
121    /// Referencing columns.
122    pub columns: Vec<String>,
123    /// Referenced table.
124    pub ref_table: String,
125    /// Referenced columns.
126    pub ref_columns: Vec<String>,
127    /// `ON DELETE` action.
128    #[serde(default, skip_serializing_if = "Option::is_none")]
129    pub on_delete: Option<String>,
130    /// `ON UPDATE` action.
131    #[serde(default, skip_serializing_if = "Option::is_none")]
132    pub on_update: Option<String>,
133}
134
135/// A `CHECK` constraint.
136#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
137pub struct Check {
138    /// Constraint name.
139    pub name: String,
140    /// Boolean expression.
141    pub expr: String,
142}
143
144/// A `CREATE INDEX` statement.
145#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
146pub struct Index {
147    /// Index name.
148    pub name: String,
149    /// Indexed table.
150    pub table: String,
151    /// The statement, as written (normalized).
152    pub sql: String,
153}
154
155/// Any other statement, applied as written.
156#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
157pub struct Extra {
158    /// SQL that creates it.
159    pub up: String,
160    /// SQL that removes it (empty: can't be undone automatically).
161    pub down: String,
162    /// Runs before tables (extensions) rather than after them.
163    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
164    pub before_tables: bool,
165}
166
167/// What a query returns.
168#[derive(Debug, Clone, Copy, PartialEq, Eq)]
169pub enum QueryKind {
170    /// `:one`: `Option<T>`.
171    One,
172    /// `:one!`: `T`, an error when there is no row.
173    OneRequired,
174    /// `:many`: `Vec<T>`.
175    Many,
176    /// `:stream`: a stream of `T`.
177    Stream,
178    /// `:exec`: rows affected.
179    Exec,
180}
181
182impl QueryKind {
183    pub(crate) fn parse(s: &str) -> Option<Self> {
184        Some(match s {
185            ":one" => Self::One,
186            ":one!" => Self::OneRequired,
187            ":many" => Self::Many,
188            ":stream" => Self::Stream,
189            ":exec" => Self::Exec,
190            _ => return None,
191        })
192    }
193}
194
195/// An annotated query (`-- name: find_by_email :one`).
196#[derive(Debug, Clone, PartialEq, Eq)]
197pub struct Query {
198    /// Function name.
199    pub name: String,
200    /// Module (file stem) it belongs to.
201    pub module: String,
202    /// What it returns.
203    pub kind: QueryKind,
204    /// The SQL, as written.
205    pub sql: String,
206    /// Doc comment lines.
207    pub doc: Vec<String>,
208    /// `-- param: $2 limit` overrides: (position, name).
209    pub param_names: Vec<(usize, String)>,
210    /// Where it is, for messages (`db/user.sql:12`).
211    pub location: String,
212}