rok-sqlc 0.6.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
//! SQL text rendering shared by every generated statement: identifier
//! quoting, table references, column lists, and embedding SQL in Rust
//! string literals.
//!
//! Only schema metadata and fixed generator-owned fragments ever reach these
//! functions; runtime values are always bound with `.bind`/`push_bind`.

use crate::schema::{Column, Table};

/// Renders a SQL identifier, quoting it only when PostgreSQL requires it:
/// when it is not a plain lowercase identifier, or when it is a keyword that
/// cannot be used bare as a column or table name.
pub fn ident(name: &str) -> String {
    if is_plain_identifier(name) && !is_restricted_keyword(name) {
        name.to_owned()
    } else {
        format!("\"{}\"", name.replace('"', "\"\""))
    }
}

/// Renders the table reference, keeping the schema qualifier when present.
pub fn table_ref(table: &Table) -> String {
    match &table.schema {
        Some(schema) => format!("{}.{}", ident(schema), ident(&table.sql_name)),
        None => ident(&table.sql_name),
    }
}

/// Every column of the table, in declaration order.
pub fn column_names(table: &Table) -> Vec<String> {
    table
        .columns
        .iter()
        .map(|column| ident(&column.sql_name))
        .collect()
}

/// A keyword followed by every column of the table, one per line:
/// `["SELECT", "    a,", "    b"]`.
pub fn column_clause(keyword: &str, table: &Table) -> Vec<String> {
    let names = column_names(table);
    let mut lines = vec![keyword.to_owned()];
    for (index, name) in names.iter().enumerate() {
        let separator = if index + 1 < names.len() { "," } else { "" };
        lines.push(format!("    {name}{separator}"));
    }
    lines
}

/// `a = $1 AND b = $2` over the given key columns, numbering from `first`.
pub fn key_predicate(keys: &[&Column], first: usize) -> String {
    keys.iter()
        .enumerate()
        .map(|(index, column)| format!("{} = ${}", ident(&column.sql_name), first + index))
        .collect::<Vec<_>>()
        .join(" AND ")
}

/// A column reference, qualified with `alias` when there is one: `a.col`.
fn column_ref(alias: Option<&str>, column: &str) -> String {
    match alias {
        Some(alias) => format!("{alias}.{}", ident(column)),
        None => ident(column),
    }
}

/// `[alias.]<soft-delete column> IS NULL`, the condition selecting live
/// rows, or `None` when the table has no soft-delete column.
pub fn live_condition(table: &Table, alias: Option<&str>) -> Option<String> {
    table
        .soft_delete_column
        .as_deref()
        .map(|column| format!("{} IS NULL", column_ref(alias, column)))
}

/// `[alias.]<tenant column> = $1` when the table has a tenant column: static
/// SQL always binds the tenant parameter first.
pub fn tenant_condition(table: &Table, alias: Option<&str>) -> Option<String> {
    table
        .tenant()
        .map(|tenant| format!("{} = $1", column_ref(alias, &tenant.sql_name)))
}

/// The placeholder of the first value bound after the tenant parameter:
/// `$2` on a table with a tenant column, `$1` otherwise.
pub fn first_placeholder(table: &Table) -> usize {
    1 + usize::from(table.tenant().is_some())
}

/// The tenant condition (when the table has a tenant column) followed by
/// `key_predicate` over `keys`, numbered after the tenant's placeholder.
pub fn scoped_key_predicate(table: &Table, keys: &[&Column]) -> String {
    let tenant = tenant_condition(table, None);
    let first = first_placeholder(table);
    tenant
        .into_iter()
        .chain((!keys.is_empty()).then(|| key_predicate(keys, first)))
        .collect::<Vec<_>>()
        .join(" AND ")
}

/// `scoped_key_predicate`, followed by `AND <soft-delete column> IS NULL`
/// when the table has one, so only a live row matches.
pub fn live_key_predicate(table: &Table, keys: &[&Column]) -> String {
    let predicate = scoped_key_predicate(table, keys);
    match live_condition(table, None) {
        Some(live) => format!("{predicate} AND {live}"),
        None => predicate,
    }
}

/// `column` compared with the value bound at `$placeholder`: `col = $n`, or,
/// when `lowered`, ignoring case, the way a unique index's
/// `lower(<column>)` entry compares it: `lower(col) = lower($n)`.
pub fn equals(column: &Column, placeholder: usize, lowered: bool) -> String {
    let name = ident(&column.sql_name);
    if lowered {
        format!("lower({name}) = lower(${placeholder})")
    } else {
        format!("{name} = ${placeholder}")
    }
}

/// `live_key_predicate` over a unique key's `columns`, the one named
/// `lowered` (a case-insensitive key's) compared ignoring case.
pub fn live_lookup_predicate(table: &Table, columns: &[&Column], lowered: Option<&str>) -> String {
    let first = first_placeholder(table);
    let compared = columns.iter().enumerate().map(|(index, column)| {
        let ignoring_case = lowered == Some(column.sql_name.as_str());
        equals(column, first + index, ignoring_case)
    });
    tenant_condition(table, None)
        .into_iter()
        .chain(compared)
        .chain(live_condition(table, None))
        .collect::<Vec<_>>()
        .join(" AND ")
}

/// The condition selecting every row a whole-table read sees: the tenant's
/// rows (`$1`) that are live, or `None` when every row is visible.
pub fn scope_condition(table: &Table) -> Option<String> {
    let conditions: Vec<String> = tenant_condition(table, None)
        .into_iter()
        .chain(live_condition(table, None))
        .collect();
    (!conditions.is_empty()).then(|| conditions.join(" AND "))
}

/// `a, b` over the given key columns, for `ORDER BY`.
pub fn key_order(keys: &[&Column]) -> String {
    keys.iter()
        .map(|column| ident(&column.sql_name))
        .collect::<Vec<_>>()
        .join(", ")
}

/// Renders `text` as a Rust string literal: a plain literal when no escaping
/// is needed, otherwise a raw literal with enough `#`s to be unambiguous.
pub fn str_literal(text: &str) -> String {
    if text.contains(['"', '\\']) {
        let hashes = raw_hashes(text);
        format!("r{hashes}\"{text}\"{hashes}")
    } else {
        format!("\"{text}\"")
    }
}

/// The `#` delimiter a raw string literal around `text` needs: one more than
/// the longest `"#…` run inside it, and at least one.
pub fn raw_hashes(text: &str) -> String {
    let mut depth = 1;
    while text.contains(&format!("\"{}", "#".repeat(depth))) {
        depth += 1;
    }
    "#".repeat(depth)
}

/// Renders SQL lines as a multi-line raw string literal whose content and
/// delimiters sit at `indent` columns, matching rustfmt's layout for a
/// vertical call argument. No trailing comma is emitted.
pub fn raw_block(lines: &[String], indent: usize) -> String {
    let pad = " ".repeat(indent);
    let hashes = raw_hashes(&lines.join("\n"));
    let mut block = format!("{pad}r{hashes}\"\n");
    for line in lines {
        block.push_str(&format!("{pad}{line}\n"));
    }
    block.push_str(&format!("{pad}\"{hashes}"));
    block
}

fn is_plain_identifier(name: &str) -> bool {
    let mut characters = name.chars();
    matches!(characters.next(), Some('a'..='z' | '_'))
        && characters.all(|character| matches!(character, 'a'..='z' | '0'..='9' | '_'))
}

/// PostgreSQL keywords in the reserved, type/function-name, and column-name
/// categories (`pg_get_keywords()` catcodes R, T, and C). Quoting them
/// everywhere is always valid, and keeps the rule independent of the
/// position the identifier appears in.
fn is_restricted_keyword(name: &str) -> bool {
    RESTRICTED_KEYWORDS.binary_search(&name).is_ok()
}

const RESTRICTED_KEYWORDS: &[&str] = &[
    "all",
    "analyse",
    "analyze",
    "and",
    "any",
    "array",
    "as",
    "asc",
    "asymmetric",
    "authorization",
    "between",
    "bigint",
    "binary",
    "bit",
    "boolean",
    "both",
    "case",
    "cast",
    "char",
    "character",
    "check",
    "coalesce",
    "collate",
    "collation",
    "column",
    "concurrently",
    "constraint",
    "create",
    "cross",
    "current_catalog",
    "current_date",
    "current_role",
    "current_schema",
    "current_time",
    "current_timestamp",
    "current_user",
    "dec",
    "decimal",
    "default",
    "deferrable",
    "desc",
    "distinct",
    "do",
    "else",
    "end",
    "except",
    "exists",
    "extract",
    "false",
    "fetch",
    "float",
    "for",
    "foreign",
    "freeze",
    "from",
    "full",
    "grant",
    "greatest",
    "group",
    "grouping",
    "having",
    "ilike",
    "in",
    "initially",
    "inner",
    "inout",
    "int",
    "integer",
    "intersect",
    "interval",
    "into",
    "is",
    "isnull",
    "join",
    "json",
    "json_array",
    "json_arrayagg",
    "json_exists",
    "json_object",
    "json_objectagg",
    "json_query",
    "json_scalar",
    "json_serialize",
    "json_table",
    "json_value",
    "lateral",
    "leading",
    "least",
    "left",
    "like",
    "limit",
    "localtime",
    "localtimestamp",
    "merge_action",
    "national",
    "natural",
    "nchar",
    "none",
    "normalize",
    "not",
    "notnull",
    "null",
    "nullif",
    "numeric",
    "offset",
    "on",
    "only",
    "or",
    "order",
    "out",
    "outer",
    "overlaps",
    "overlay",
    "placing",
    "position",
    "precision",
    "primary",
    "real",
    "references",
    "returning",
    "right",
    "row",
    "select",
    "session_user",
    "setof",
    "similar",
    "smallint",
    "some",
    "substring",
    "symmetric",
    "system_user",
    "table",
    "tablesample",
    "then",
    "time",
    "timestamp",
    "to",
    "trailing",
    "treat",
    "trim",
    "true",
    "union",
    "unique",
    "user",
    "using",
    "values",
    "varchar",
    "variadic",
    "verbose",
    "when",
    "where",
    "window",
    "with",
    "xmlattributes",
    "xmlconcat",
    "xmlelement",
    "xmlexists",
    "xmlforest",
    "xmlnamespaces",
    "xmlparse",
    "xmlpi",
    "xmlroot",
    "xmlserialize",
    "xmltable",
];

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn keyword_list_is_sorted_for_binary_search() {
        assert!(RESTRICTED_KEYWORDS.windows(2).all(|pair| pair[0] < pair[1]));
    }

    #[test]
    fn quotes_only_when_required() {
        assert_eq!(ident("price_cents"), "price_cents");
        assert_eq!(ident("_hidden"), "_hidden");
        assert_eq!(ident("type"), "type");
        assert_eq!(ident("name"), "name");
        assert_eq!(ident("select"), "\"select\"");
        assert_eq!(ident("user"), "\"user\"");
        assert_eq!(ident("time"), "\"time\"");
        assert_eq!(ident("Email"), "\"Email\"");
        assert_eq!(ident("Mixed Case"), "\"Mixed Case\"");
        assert_eq!(ident("1st"), "\"1st\"");
        assert_eq!(ident("say \"hi\""), "\"say \"\"hi\"\"\"");
    }

    #[test]
    fn literals_escape_only_when_needed() {
        assert_eq!(str_literal("price_cents"), "\"price_cents\"");
        assert_eq!(str_literal("\"select\""), "r#\"\"select\"\"#");
        assert_eq!(str_literal("\"#odd\""), "r##\"\"#odd\"\"##");
    }

    #[test]
    fn raw_block_picks_safe_delimiter() {
        let block = raw_block(&["SELECT \"#x\"".to_owned()], 4);
        assert_eq!(block, "    r##\"\n    SELECT \"#x\"\n    \"##");
    }
}