rok-sqlc 0.2.0

Generate SQLx Rust database modules from SQL schema files
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
mod checks;
pub mod conventions;
mod db_mod;
mod emit;
mod joins;
pub mod keys;
pub mod models;
pub mod queries;
pub mod read;
pub mod relationships;
pub mod search;
pub mod session;
pub mod sql;
#[cfg(test)]
pub(crate) mod test_support;
pub mod types;
pub mod write;

#[cfg(test)]
use std::path::Path;
use std::path::PathBuf;

use crate::parser::Rejection;
use crate::queries::AnalyzedQuery;
use crate::schema::{BaseType, Column, EnumType, Table};
use crate::{Config, Conventions, Derive};

use self::checks::{check_imports, check_serde};
use self::emit::{CHAIN_WIDTH, FN_CALL_WIDTH, MAX_WIDTH};

pub use self::db_mod::{DbMod, render_db_mod, render_schema_snapshot};
pub use self::emit::{
    StaticQuery, doc_name, push_and_chain, push_build_and_fetch, push_chain, push_doc,
    push_fn_head, push_let_call, push_serde_derive, push_serde_snake_case, types_import, use_list,
    use_paths,
};

const HEADER: &str = "// @generated by rok-sqlc. Do not edit by hand.\n";

/// What happens to the `db::queries` module in a generation run.
#[derive(Debug, Clone, Copy)]
pub enum QueriesModule<'a> {
    /// No query file is involved.
    None,
    /// Generate `queries.rs` from these analyzed queries (one query file).
    Generate(&'a [AnalyzedQuery]),
    /// Generate `queries/<name>.rs` per query file, declared by a generated
    /// `queries/mod.rs`.
    GenerateModules(&'a [QueryModule]),
    /// A previous run generated `queries.rs` or `queries/mod.rs`; keep
    /// declaring it in `mod.rs`.
    Keep,
}

/// The analyzed queries of one query file, generated as `queries/<name>.rs`.
#[derive(Debug, Clone)]
pub struct QueryModule {
    /// The module name: the query file's stem.
    pub name: String,
    pub queries: Vec<AnalyzedQuery>,
}

/// Resource modules an earlier run generated for tables this run skips as
/// unsupported (ADR 0001). Their files are kept as they are, and the run
/// plans everything else as if these tables generated in their last good
/// shape: `mod.rs` declares them (and `UpdateOutcome` for a versioned one),
/// `types.rs` defines their enums, and the typed ids, relationships, and
/// filters of the other tables reach them as before.
#[derive(Debug, Clone, Default)]
pub struct KeptResources {
    /// The kept tables in their last good shape (see
    /// [`LastGood`](crate::parser::LastGood)).
    pub tables: Vec<Table>,
    /// Their value-list enums that no generated table defines.
    pub enums: Vec<EnumType>,
}

impl<'a> QueriesModule<'a> {
    fn is_declared(self) -> bool {
        !matches!(self, QueriesModule::None)
    }

    /// Every query this run generates, from every query file.
    fn analyzed(self) -> Vec<&'a AnalyzedQuery> {
        match self {
            QueriesModule::Generate(analyzed) => analyzed.iter().collect(),
            QueriesModule::GenerateModules(modules) => {
                modules.iter().flat_map(|module| &module.queries).collect()
            }
            QueriesModule::None | QueriesModule::Keep => Vec::new(),
        }
    }
}

#[cfg(test)]
fn plan_files(schema_sql: &str, tables: &[Table], output: &Path) -> Vec<(PathBuf, String)> {
    let config = Config {
        output: output.to_path_buf(),
        ..Config::default()
    };
    plan_files_with_queries(
        &config,
        schema_sql,
        tables,
        &[],
        QueriesModule::None,
        &KeptResources::default(),
    )
    .expect("the tables generate")
}

/// The model the renderers read, built in the one order the steps depend
/// on: typed ids first ([`keys::resolve`]), then the conventions (a tenant
/// column's foreign key is no relationship), then the typed id name check
/// ([`keys::check_names`]), then relationships with the `[relationships]`
/// changes applied.
pub fn prepare(
    tables: &[Table],
    conventions: &Conventions,
    changes: &relationships::Changes,
    scope: relationships::Scope,
) -> Result<Vec<Table>, String> {
    let mut prepared = keys::resolve(tables);
    conventions::apply(&mut prepared, conventions);
    keys::check_names(&prepared)?;
    relationships::infer(&mut prepared, changes, scope)?;
    Ok(prepared)
}

/// Why `table` cannot be generated under `config`'s conventions, found on
/// its model with the conventions [applied](conventions::apply) once: a
/// managed column with no source of values ([`conventions::unsourced`]), or
/// search names that collide ([`search::name_clash`]).
pub fn table_failures(table: &Table, config: &Config) -> Option<Rejection> {
    let mut applied = [table.clone()];
    conventions::apply(&mut applied, &config.conventions);
    let [table] = &applied;
    if let Some((column, reason)) = conventions::unsourced(table) {
        return Some(Rejection {
            reason,
            unsourced_column: Some(column.sql_name.clone()),
        });
    }
    search::name_clash(table).map(|reason| Rejection {
        reason,
        unsourced_column: None,
    })
}

/// Plans every generated file under `config.output`: `tables` (the ones
/// this run generates), the shared modules, `enums` in `types.rs`, and the
/// queries module. The `kept` resources are planned with the rest but get no
/// files of their own. `schema_sql` is the schema snapshot. Uses the
/// configuration's conventions, derives, and relationship changes.
pub fn plan_files_with_queries(
    config: &Config,
    schema_sql: &str,
    tables: &[Table],
    enums: &[EnumType],
    queries: QueriesModule<'_>,
    kept: &KeptResources,
) -> Result<Vec<(PathBuf, String)>, String> {
    let (conventions, output) = (&config.conventions, config.output.as_path());
    let serde = config.derive.contains(&Derive::Serde);
    if serde {
        check_serde(tables, queries)?;
    }
    let mut files = Vec::new();
    let all: Vec<Table> = tables.iter().chain(&kept.tables).cloned().collect();
    let resolved = prepare(
        &all,
        conventions,
        &config.relationships,
        relationships::Scope::Run,
    )?;
    let tables = resolved.as_slice();
    let enums: Vec<EnumType> = enums.iter().chain(&kept.enums).cloned().collect();
    let is_kept = |table: &Table| {
        kept.tables
            .iter()
            .any(|kept| kept.module_name == table.module_name)
    };

    for table in tables.iter().filter(|table| !is_kept(table)) {
        let dir = output.join(&table.module_name);
        let filter = search::render_filter(table, tables, serde);
        let loaders = relationships::render(table, tables, serde);
        files.push((
            dir.join("mod.rs"),
            render_resource_mod(table, filter.is_some(), loaders.is_some()),
        ));
        files.push((dir.join("models.rs"), models::render(table, serde)));
        if let Some(filter) = filter {
            files.push((dir.join("filter.rs"), filter));
        }
        files.push((dir.join("read.rs"), read::render(table, tables)));
        if let Some(loaders) = loaders {
            files.push((dir.join("relationships.rs"), loaders));
        }
        files.push((dir.join("write.rs"), write::render(table)));
    }

    match queries {
        QueriesModule::Generate(analyzed) => {
            files.push((
                output.join("queries.rs"),
                queries::render(analyzed, tables, serde),
            ));
        }
        QueriesModule::GenerateModules(modules) => {
            let dir = output.join("queries");
            for module in modules {
                files.push((
                    dir.join(format!("{}.rs", module.name)),
                    queries::render_nested(&module.queries, tables, serde),
                ));
            }
            files.push((dir.join("mod.rs"), queries::render_mod(modules)));
        }
        QueriesModule::None | QueriesModule::Keep => {}
    }
    files.push((output.join("search.rs"), search::render_shared(serde)));
    if serde {
        files.push((output.join("nullable.rs"), models::render_nullable()));
    }
    if !enums.is_empty() {
        files.push((output.join("types.rs"), types::render(&enums, serde)));
    }
    let session = session::render(conventions);
    let db_mod = DbMod {
        has_types: !enums.is_empty(),
        has_session: session.is_some(),
        queries,
        serde,
    };
    if let Some(session) = session {
        files.push((output.join("session.rs"), session));
    }
    files.push((output.join("mod.rs"), render_db_mod(tables, &db_mod)));
    files.push((output.join("schema.rs"), render_schema_snapshot(schema_sql)));

    for (path, text) in &files {
        check_imports(output, path, text)?;
    }
    Ok(files)
}

fn render_resource_mod(table: &Table, has_filter: bool, has_relationships: bool) -> String {
    let mut output = format!("{HEADER}\n//! The `{}` table.\n\n", table.display_name());
    if has_filter {
        output.push_str("/// The `search` filter and sort keys.\npub mod filter;\n");
    }
    output.push_str(
        "/// The row type, its key, and the inputs `create` and `update` take.\n\
         pub mod models;\n\
         /// Lookups, listing, counting, and search.\n\
         pub mod read;\n",
    );
    if has_relationships {
        output.push_str(
            "/// Loaders fetching each relationship for many rows in one query.\n\
             pub mod relationships;\n",
        );
    }
    output.push_str("/// `create`, `update`, and `delete`.\npub mod write;\n");
    output
}

/// The insert-input field type: columns with a database default are wrapped
/// in `Option` so `None` can omit them. A nullable defaulted column therefore
/// becomes `Option<Option<T>>`.
pub fn insert_field_type(column: &Column) -> String {
    if column.is_omittable_on_insert() {
        format!("Option<{}>", column.field_type())
    } else {
        column.field_type()
    }
}

/// The update-patch field type: `None` leaves the column unchanged, so a
/// nullable column becomes `Option<Option<T>>` and `Some(None)` sets `NULL`.
pub fn update_field_type(column: &Column) -> String {
    format!("Option<{}>", column.field_type())
}

/// Names the generated functions use for their own parameters and locals.
/// A key column whose Rust name collides with one of these is renamed with a
/// `_key` suffix when it becomes a function parameter.
const RESERVED_LOCALS: &[&str] = &[
    "executor",
    "input",
    "query",
    "columns",
    "values",
    "assignments",
    "value",
    "result",
    "limit",
    "offset",
    "expected_version",
    "rows",
    "keys",
    "loaded",
    "related",
];

/// The function-parameter name for a key column.
pub fn param_name(column: &Column) -> String {
    if RESERVED_LOCALS.contains(&column.rust_name.as_str()) {
        format!("{}_key", column.rust_name)
    } else {
        column.rust_name.clone()
    }
}

/// The type a key or lookup parameter takes a column's value as: text and
/// bytes are borrowed (`&str` or `&` its typed id, `&[u8]`) because binding
/// them needs no ownership; every other value, `Copy` keys included, is
/// taken by value.
pub fn param_type(column: &Column) -> String {
    match column.base_type() {
        BaseType::Text => match &column.typed_id {
            Some(id) => format!("&{}", id.name),
            None => "&str".to_owned(),
        },
        BaseType::Bytes => "&[u8]".to_owned(),
        _ => column.value_type().to_owned(),
    }
}

#[cfg(test)]
mod tests {
    use super::test_support::{column, table};
    use super::*;

    #[test]
    fn plans_resource_and_root_files() {
        let tables = vec![table(vec![column("id", "i64")], &["id"])];
        let files = plan_files("CREATE TABLE users (id BIGINT);", &tables, Path::new("out"));

        let paths: Vec<_> = files.iter().map(|(p, _)| p.clone()).collect();
        assert!(paths.contains(&Path::new("out").join("users").join("mod.rs")));
        assert!(paths.contains(&Path::new("out").join("users").join("models.rs")));
        assert!(paths.contains(&Path::new("out").join("users").join("read.rs")));
        assert!(paths.contains(&Path::new("out").join("users").join("write.rs")));
        assert!(paths.contains(&Path::new("out").join("mod.rs")));
        assert!(paths.contains(&Path::new("out").join("schema.rs")));
    }

    /// `missing_docs` needs every module documented: each generated module
    /// file carries an inner doc, and a resource's submodules are documented
    /// where they are declared.
    #[test]
    fn module_files_are_documented() {
        let users = table(vec![column("id", "i64")], &["id"]);
        let files = plan_files(
            "CREATE TABLE users (id BIGINT);",
            &[users],
            Path::new("out"),
        );
        let file = |path: &[&str]| {
            let wanted = path
                .iter()
                .fold(Path::new("out").to_path_buf(), |p, s| p.join(s));
            files
                .iter()
                .find(|(p, _)| *p == wanted)
                .map(|(_, text)| text.clone())
                .unwrap()
        };
        assert!(file(&["mod.rs"]).contains("\n//! "));
        assert!(file(&["schema.rs"]).contains("\n//! "));
        assert!(file(&["schema.rs"]).contains("\n/// "));
        let resource = file(&["users", "mod.rs"]);
        assert!(resource.contains("//! The `users` table."), "{resource}");
        for module in ["filter", "models", "read", "write"] {
            let before = resource
                .split(&format!("pub mod {module};"))
                .next()
                .unwrap();
            let doc = before.trim_end().lines().last().unwrap();
            assert!(
                doc.starts_with("/// "),
                "`{module}` is undocumented:\n{resource}"
            );
        }
    }

    #[test]
    fn generated_query_functions_use_generic_executor_not_concrete_pool() {
        let table = table(
            vec![column("id", "i64"), column("email", "String")],
            &["id"],
        );
        for rendered in [
            read::render(&table, std::slice::from_ref(&table)),
            write::render(&table),
        ] {
            assert!(rendered.contains("E: sqlx::PgExecutor<'e>,"));
            assert!(!rendered.contains("PgPool"));
            assert!(!rendered.contains("PgConnection"));
        }
    }

    #[test]
    fn key_params_avoid_generated_local_names() {
        assert_eq!(param_name(&column("query", "i64")), "query_key");
        assert_eq!(param_name(&column("id", "i64")), "id");
    }

    #[test]
    fn output_is_deterministic() {
        let tables = vec![table(vec![column("id", "i64")], &["id"])];
        let first = plan_files("CREATE TABLE users (id BIGINT);", &tables, Path::new("out"));
        let second = plan_files("CREATE TABLE users (id BIGINT);", &tables, Path::new("out"));
        assert_eq!(first, second);
    }
}