Skip to main content

luxid_orm/
schema.rs

1//! Reading the live database's shape.
2//!
3//! `db:sync` needs to know what columns actually exist so generated factories
4//! and form requests can be refreshed from the schema rather than from a guess.
5//!
6//! Introspection is dialect-specific by nature — SQLite has `PRAGMA`, Postgres
7//! has `information_schema` — so the two are handled explicitly rather than
8//! through an abstraction that would hide which one ran.
9
10use luxid_core::error::{Error, Result};
11use sea_orm::{DatabaseBackend, FromQueryResult, Statement};
12
13use crate::db::Db;
14
15/// One column of a table.
16#[derive(Debug, Clone, PartialEq, Eq)]
17pub struct Column {
18    pub name: String,
19    /// The database's own spelling of the type, e.g. `INTEGER`, `text`.
20    pub sql_type: String,
21    pub nullable: bool,
22    pub primary_key: bool,
23}
24
25impl Column {
26    /// The Rust type this column deserializes into, as a best effort.
27    ///
28    /// Deliberately conservative: an unrecognised type becomes `String`, which
29    /// compiles and can be corrected, rather than a guess that does not.
30    pub fn rust_type(&self) -> &'static str {
31        let sql = self.sql_type.to_ascii_lowercase();
32
33        // Dates and unrecognised types both land on `String`. That is
34        // deliberate: a chrono type would need the right feature and the right
35        // import, and guessing wrong produces code that does not compile.
36        if sql.contains("smallint") {
37            "i16"
38        } else if sql.contains("int") && !sql.contains("point") {
39            "i64"
40        } else if sql.contains("bool") {
41            "bool"
42        } else if sql.contains("real") || sql.contains("double") || sql.contains("float") {
43            "f64"
44        } else if sql.contains("json") {
45            "serde_json::Value"
46        } else {
47            "String"
48        }
49    }
50
51    /// A plausible factory value for this column.
52    pub fn sample(&self) -> String {
53        match self.rust_type() {
54            "bool" => "Set(false)".to_owned(),
55            "i16" | "i64" => "Set(0)".to_owned(),
56            "f64" => "Set(0.0)".to_owned(),
57            "serde_json::Value" => "Set(serde_json::json!({}))".to_owned(),
58            _ => format!("Set(\"{}\".to_owned())", self.name),
59        }
60    }
61}
62
63#[derive(Debug, Clone, PartialEq, Eq)]
64pub struct Table {
65    pub name: String,
66    pub columns: Vec<Column>,
67}
68
69impl Table {
70    /// Columns a factory must supply: everything except nullable columns and
71    /// the auto-assigned primary key.
72    pub fn required_columns(&self) -> impl Iterator<Item = &Column> {
73        self.columns
74            .iter()
75            .filter(|column| !column.nullable && !column.primary_key)
76    }
77}
78
79#[derive(Debug, FromQueryResult)]
80struct SqliteTable {
81    name: String,
82}
83
84#[derive(Debug, FromQueryResult)]
85struct SqliteColumn {
86    name: String,
87    #[sea_orm(alias = "type")]
88    sql_type: String,
89    notnull: i32,
90    pk: i32,
91}
92
93#[derive(Debug, FromQueryResult)]
94struct PostgresColumn {
95    table_name: String,
96    column_name: String,
97    data_type: String,
98    is_nullable: String,
99    is_primary: bool,
100}
101
102impl Db {
103    /// Every user table in the database, with its columns.
104    ///
105    /// Migration bookkeeping tables are excluded — nobody wants a factory for
106    /// `seaql_migrations`.
107    pub async fn tables(&self) -> Result<Vec<Table>> {
108        match self.connection().get_database_backend() {
109            DatabaseBackend::Sqlite => self.sqlite_tables().await,
110            DatabaseBackend::Postgres => self.postgres_tables().await,
111            other => Err(Error::internal(format!(
112                "schema introspection is not implemented for {other:?}. \
113                 SQLite and Postgres are supported."
114            ))),
115        }
116    }
117
118    async fn sqlite_tables(&self) -> Result<Vec<Table>> {
119        let backend = DatabaseBackend::Sqlite;
120        let connection = self.connection();
121
122        let names = SqliteTable::find_by_statement(Statement::from_string(
123            backend,
124            "SELECT name FROM sqlite_master \
125             WHERE type = 'table' \
126               AND name NOT LIKE 'sqlite_%' \
127               AND name <> 'seaql_migrations' \
128             ORDER BY name",
129        ))
130        .all(connection)
131        .await
132        .map_err(introspection_failed)?;
133
134        let mut tables = Vec::with_capacity(names.len());
135
136        for table in names {
137            let columns = SqliteColumn::find_by_statement(Statement::from_string(
138                backend,
139                // The name is from sqlite_master, not from user input.
140                format!("PRAGMA table_info('{}')", table.name.replace('\'', "''")),
141            ))
142            .all(connection)
143            .await
144            .map_err(introspection_failed)?;
145
146            tables.push(Table {
147                name: table.name,
148                columns: columns
149                    .into_iter()
150                    .map(|column| Column {
151                        name: column.name,
152                        sql_type: column.sql_type,
153                        nullable: column.notnull == 0,
154                        primary_key: column.pk > 0,
155                    })
156                    .collect(),
157            });
158        }
159
160        Ok(tables)
161    }
162
163    async fn postgres_tables(&self) -> Result<Vec<Table>> {
164        let rows = PostgresColumn::find_by_statement(Statement::from_string(
165            DatabaseBackend::Postgres,
166            "SELECT c.table_name,
167                    c.column_name,
168                    c.data_type,
169                    c.is_nullable,
170                    COALESCE(pk.is_primary, false) AS is_primary
171               FROM information_schema.columns c
172               LEFT JOIN (
173                    SELECT kcu.table_name, kcu.column_name, true AS is_primary
174                      FROM information_schema.table_constraints tc
175                      JOIN information_schema.key_column_usage kcu
176                        ON kcu.constraint_name = tc.constraint_name
177                     WHERE tc.constraint_type = 'PRIMARY KEY'
178               ) pk ON pk.table_name = c.table_name AND pk.column_name = c.column_name
179              WHERE c.table_schema = 'current_schema'
180                 OR c.table_schema = ANY (current_schemas(false))
181                AND c.table_name <> 'seaql_migrations'
182              ORDER BY c.table_name, c.ordinal_position",
183        ))
184        .all(self.connection())
185        .await
186        .map_err(introspection_failed)?;
187
188        let mut tables: Vec<Table> = Vec::new();
189
190        for row in rows {
191            if row.table_name == "seaql_migrations" {
192                continue;
193            }
194
195            let column = Column {
196                name: row.column_name,
197                sql_type: row.data_type,
198                nullable: row.is_nullable.eq_ignore_ascii_case("yes"),
199                primary_key: row.is_primary,
200            };
201
202            match tables.last_mut() {
203                Some(table) if table.name == row.table_name => table.columns.push(column),
204                _ => tables.push(Table {
205                    name: row.table_name,
206                    columns: vec![column],
207                }),
208            }
209        }
210
211        Ok(tables)
212    }
213}
214
215fn introspection_failed(err: sea_orm::DbErr) -> Error {
216    Error::internal(format!("could not read the database schema: {err}"))
217}
218
219#[cfg(test)]
220mod tests {
221    use super::*;
222
223    fn column(name: &str, sql_type: &str, nullable: bool, primary_key: bool) -> Column {
224        Column {
225            name: name.to_owned(),
226            sql_type: sql_type.to_owned(),
227            nullable,
228            primary_key,
229        }
230    }
231
232    #[test]
233    fn maps_sql_types_conservatively() {
234        assert_eq!(column("id", "INTEGER", false, true).rust_type(), "i64");
235        assert_eq!(column("n", "bigint", false, false).rust_type(), "i64");
236        assert_eq!(column("ok", "BOOLEAN", false, false).rust_type(), "bool");
237        assert_eq!(
238            column("x", "double precision", false, false).rust_type(),
239            "f64"
240        );
241        assert_eq!(
242            column("meta", "jsonb", false, false).rust_type(),
243            "serde_json::Value"
244        );
245        assert_eq!(column("name", "TEXT", false, false).rust_type(), "String");
246
247        // Unknown types fall back to something that compiles.
248        assert_eq!(
249            column("weird", "geography", false, false).rust_type(),
250            "String"
251        );
252    }
253
254    #[test]
255    fn samples_match_their_type() {
256        assert_eq!(column("ok", "BOOLEAN", false, false).sample(), "Set(false)");
257        assert_eq!(column("n", "INTEGER", false, false).sample(), "Set(0)");
258        assert_eq!(
259            column("name", "TEXT", false, false).sample(),
260            "Set(\"name\".to_owned())"
261        );
262    }
263
264    #[test]
265    fn required_columns_skip_the_key_and_the_nullable() {
266        let table = Table {
267            name: "users".into(),
268            columns: vec![
269                column("id", "INTEGER", false, true),
270                column("name", "TEXT", false, false),
271                column("nickname", "TEXT", true, false),
272            ],
273        };
274
275        let required: Vec<_> = table.required_columns().map(|c| c.name.as_str()).collect();
276        assert_eq!(required, vec!["name"]);
277    }
278
279    #[tokio::test]
280    async fn reads_a_real_sqlite_schema() {
281        use sea_orm::ConnectionTrait;
282
283        let db = Db::in_memory().await.expect("opens");
284        db.connection()
285            .execute_unprepared(
286                "CREATE TABLE users (
287                    id       INTEGER PRIMARY KEY AUTOINCREMENT,
288                    name     TEXT NOT NULL,
289                    nickname TEXT,
290                    active   BOOLEAN NOT NULL
291                 );
292                 CREATE TABLE seaql_migrations (version TEXT PRIMARY KEY, applied_at BIGINT);",
293            )
294            .await
295            .expect("creates schema");
296
297        let tables = db.tables().await.expect("introspects");
298
299        assert_eq!(tables.len(), 1, "migration bookkeeping is excluded");
300
301        let users = &tables[0];
302        assert_eq!(users.name, "users");
303
304        let names: Vec<_> = users.columns.iter().map(|c| c.name.as_str()).collect();
305        assert_eq!(names, vec!["id", "name", "nickname", "active"]);
306
307        assert!(users.columns[0].primary_key);
308        assert!(!users.columns[1].nullable);
309        assert!(users.columns[2].nullable, "nickname has no NOT NULL");
310
311        let required: Vec<_> = users.required_columns().map(|c| c.name.as_str()).collect();
312        assert_eq!(required, vec!["name", "active"]);
313    }
314}