rok-sqlc 0.3.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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
# rok-sqlc


Write SQL, get typed Rust. rok-sqlc reads your PostgreSQL migrations and
annotated query files and generates plain [SQLx](https://github.com/launchbadge/sqlx)
code: row structs, typed ids, CRUD, typed search, relationship loaders, and
one function per query you write. The generated code is ordinary Rust you
commit and read. There is no runtime crate and no macro magic, and you don't
need a database to generate it.

**SQL in:**

<!-- source: docs/examples/quickstart/queries.sql -->

```sql
-- name: ActiveProductsInCategory :many
SELECT id, sku, name, price
FROM products
WHERE category_id = $1 AND status = 'active'
ORDER BY name, id;
```

**Rust out** (in `src/db/queries.rs`):

<!-- source: docs/examples/quickstart/src/db/queries.rs -->

```rust
/// A row returned by `active_products_in_category`.
#[derive(Debug, Clone, PartialEq, sqlx::FromRow)]

pub struct ActiveProductsInCategoryRow {
    /// The `id` column.
    pub id: ProductId,
    /// The `sku` column.
    pub sku: String,
    /// The `name` column.
    pub name: String,
    /// The `price` column.
    pub price: rust_decimal::Decimal,
}

/// Runs the `ActiveProductsInCategory` query (`:many`).
pub async fn active_products_in_category<'e, E>(
    executor: E,
    category_id: CategoryId,
) -> Result<Vec<ActiveProductsInCategoryRow>, sqlx::Error>
where
    E: sqlx::PgExecutor<'e>,
```

From the schema alone, every table also gets a typed `get_by_id`, unique-key
lookups, `list`, `count`, `create`, partial `update`, `delete`, a typed
`search` with keyset pagination, and loaders for the relationships its
foreign keys imply.

Every code sample in this README was generated by rok-sqlc from the example
crates in [`docs/examples/`](docs/examples/), and a test keeps the two in
sync.

> **Status:** 0.3.0, PostgreSQL and SQLx 0.9 only.
> See [Limitations and roadmap]#limitations-and-roadmap.

## Contents


- [Install]#install
- [Quickstart]#quickstart
- [What gets generated]#what-gets-generated
- [Writing query files]#writing-query-files
- [Conventions and the `rok` preset]#conventions-and-the-rok-preset
- [Validated bodies and HTTP extractors]#validated-bodies-and-http-extractors
- [Configuration]#configuration
- [Using it from `build.rs`]#using-it-from-buildrs
- [CI with `--check`]#ci-with---check
- [Supported SQL and type mapping]#supported-sql-and-type-mapping
- [Limitations and roadmap]#limitations-and-roadmap
- [Contributing]#contributing
- [License]#license

## Install


Prebuilt binaries for Linux, macOS, and Windows (x86_64 and ARM64) are
attached to every [GitHub release](https://github.com/ateeq1999/rok-sqlc/releases).
The install scripts pick the right one, check its SHA-256 checksum, and put
`rok-sqlc` on your machine.

**Linux and macOS** (installs to `~/.local/bin`):

```sh
curl -fsSL https://raw.githubusercontent.com/ateeq1999/rok-sqlc/main/install.sh | sh
```

**Windows** (PowerShell; installs to `~\.rok-sqlc\bin` and adds it to your
user `PATH`):

```powershell
irm https://raw.githubusercontent.com/ateeq1999/rok-sqlc/main/install.ps1 | iex
```

To pin a release or choose the directory, pass
`sh -s -- --version v0.3.0 --to /usr/local/bin` to `install.sh`, or set
`ROK_SQLC_VERSION` and `ROK_SQLC_INSTALL_DIR` (both scripts read them).
The Linux binaries are statically linked against musl, so they run on any
distribution.

**From source** with Cargo:

```sh
cargo install rok-sqlc
```

To track unreleased changes, install from the repository instead:
`cargo install --git https://github.com/ateeq1999/rok-sqlc rok-sqlc`.

There are two Rust version floors:

- **The tool** needs Rust 1.88 or newer.
- **The generated code** targets SQLx 0.9, so the crate that uses it needs
  Rust 1.94 or newer (SQLx 0.9's minimum).

The generated `db/mod.rs` lists the dependencies your crate needs. It names
only the SQLx features and crates the schema actually uses:

<!-- source: docs/examples/quickstart/src/db/mod.rs -->

```rust
// The generated code requires these dependencies in the consuming crate
// (SQLx 0.9 needs Rust 1.94 or newer):
//   sqlx = { version = "0.9", features = ["runtime-tokio", "postgres", "derive", "uuid", "chrono", "rust_decimal"] }
//   uuid = "1"
//   chrono = "0.4"
//   rust_decimal = "1"
```

So the quickstart crate's `Cargo.toml` has:

<!-- source: docs/examples/quickstart/Cargo.toml -->

```toml
[dependencies]
sqlx = { version = "0.9", features = ["runtime-tokio", "postgres", "derive", "uuid", "chrono", "rust_decimal"] }
uuid = "1"
chrono = "0.4"
rust_decimal = "1"
```

`serde_json` (for `JSON`/`JSONB` columns) and `serde` (with
[`derive = ["serde"]`](#configuration)) show up in the list when they are
needed.

## Quickstart


The complete crate is in [`docs/examples/quickstart`](docs/examples/quickstart).

**1. Write migrations.** A directory of migrations is read in filename order,
and `*.down.sql` files are skipped. Later migrations can `ALTER` earlier
tables:

<!-- source: docs/examples/quickstart/migrations/0001_catalog.sql -->

```sql
CREATE TYPE product_status AS ENUM ('draft', 'active', 'archived');

CREATE TABLE categories (
    id         BIGSERIAL PRIMARY KEY,
    name       TEXT NOT NULL UNIQUE,
    created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE TABLE products (
    id          UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    category_id BIGINT NOT NULL REFERENCES categories (id),
    sku         TEXT NOT NULL UNIQUE,
    name        TEXT NOT NULL,
    price       NUMERIC(12, 2) NOT NULL,
    status      product_status NOT NULL DEFAULT 'draft',
    tags        TEXT[] NOT NULL DEFAULT '{}',
    created_at  TIMESTAMPTZ NOT NULL DEFAULT now()
);
```

<!-- source: docs/examples/quickstart/migrations/0002_product_description.sql -->

```sql
ALTER TABLE products ADD COLUMN description TEXT;
```

rok-sqlc never runs your migrations. Apply them with whatever tool you
already use, such as `sqlx migrate run` or `psql`.

**2. Write queries** for anything the generated CRUD doesn't cover. See
[`queries.sql`](docs/examples/quickstart/queries.sql) and
[Writing query files](#writing-query-files).

**3. Point rok-sqlc at them** with a `rok-sqlc.toml` (optional; flags work too):

<!-- source: docs/examples/quickstart/rok-sqlc.toml -->

```toml
schema  = ["migrations/"]
queries = ["queries.sql"]
output  = "src/db"
```

**4. Generate:**

```sh
rok-sqlc g
```

That is the same as
`rok-sqlc generate --schema migrations/ --queries queries.sql --output src/db`.
It writes:

<!-- tree: docs/examples/quickstart/src/db -->

```text
db/
├── categories/
│   ├── filter.rs
│   ├── mod.rs
│   ├── models.rs
│   ├── read.rs
│   ├── relationships.rs
│   └── write.rs
├── mod.rs
├── products/
│   ├── filter.rs
│   ├── mod.rs
│   ├── models.rs
│   ├── read.rs
│   ├── relationships.rs
│   └── write.rs
├── queries.rs
├── schema.rs
├── search.rs
└── types.rs
```

**5. Call it.** Declare the module (`pub mod db;`) and pass an executor
first: `&pool`, or `&mut *tx` to run several calls in one transaction. The
transaction boundary is always yours.

<!-- source: docs/examples/quickstart/src/lib.rs -->

```rust
    // Every generated function takes an executor first: here, the pool.
    let tools = db::categories::write::create(
        pool,
        NewCategory {
            name: "Tools".into(),
            created_at: None,
        },
    )
    .await?;

    // Several calls in one transaction: pass `&mut *tx` instead.
    let mut tx = pool.begin().await?;
    let hammer = db::products::write::create(
        &mut *tx,
        NewProduct {
            id: None,
            category_id: tools.id,
            sku: "HAM-1".into(),
            name: "Claw hammer".into(),
            price: Decimal::new(1999, 2),
            status: Some(ProductStatus::Active),
            tags: None,
            created_at: None,
            description: None,
        },
    )
    .await?;
    let patch = UpdateProduct {
        price: Some(Decimal::new(1799, 2)),
        description: Some(Some("16 oz, fibreglass handle".into())),
        ..UpdateProduct::default()
    };
    db::products::write::update(&mut *tx, hammer.id, patch).await?;
    tx.commit().await?;
```

Commit the generated code. Regenerate whenever a migration or query file
changes, and check for drift in CI (see [CI with `--check`](#ci-with---check)).

## What gets generated


Each generated file starts with `// @generated by rok-sqlc. Do not edit by hand.`
rok-sqlc overwrites only files that carry that header. It refuses to replace
any other file unless you pass `-f/--force`. When a table, query file or
other source disappears, a later run removes its generated files (the stale
files). A table that is still in the schema but skipped by `--lenient` is not
gone: its files stay as they are.

### Per table: a resource module `db/<table>/`


| File | Contents |
|---|---|
| `models.rs` | The typed id (`ProductId`) or key struct, the row struct (`Product`), the create input (`NewProduct`), and the update patch (`UpdateProduct`). |
| `read.rs` | `get_by_id`, `exists_by_id`, a `get_by_<columns>` lookup per unique key, `list` and `list_page` (ordered by primary key), `count`, `search`, `search_after`. |
| `write.rs` | `create`, `update`, `delete` (and `restore`/`delete_permanently` with soft delete, `attach`/`detach`/`sync` on join tables). |
| `filter.rs` | The search filter (`ProductFilter`) and sort keys (`ProductSortKey`). |
| `relationships.rs` | A `load_<name>` loader per relationship, and `get_with_<name>` joined reads for to-one relationships. |

A table without a primary key gets `create`, `list` and `count` only. `search`
needs at least one sortable column, and `search_after` needs a primary key.
`filter.rs` exists only when one of them does, and `relationships.rs` only
when the table has relationships.

**Typed ids.** A single-column primary key gets its own type, which is used
for that column, for every foreign key that references it, and by every
function that takes the key. Passing a `CategoryId` where a `ProductId` is
expected is a compile error:

<!-- source: docs/examples/quickstart/src/db/products/models.rs -->

```rust
/// A row of the `products` table.
#[derive(Debug, Clone, PartialEq, sqlx::FromRow)]

pub struct Product {
    /// The `id` column.
    pub id: ProductId,
    /// The `category_id` column.
    pub category_id: CategoryId,
    /// The `sku` column.
    pub sku: String,
    /// The `name` column.
    pub name: String,
    /// The `price` column.
    pub price: rust_decimal::Decimal,
    /// The `status` column.
    pub status: types::ProductStatus,
    /// The `tags` column.
    pub tags: Vec<String>,
    /// The `created_at` column.
    pub created_at: chrono::DateTime<chrono::Utc>,
    /// The `description` column.
    pub description: Option<String>,
}
```

A composite primary key gets a key struct instead (`OrderItemKey`, with a
`key()` accessor on the row). A foreign key to a table outside the run keeps
its raw type. An enum primary key's typed id wraps the enum
(`PriorityNoteId(pub types::TicketPriority)`). Like the enum, it is neither
`Ord` nor `Display`. Two tables whose struct names agree (`user` and `users`)
both define `UserId`. A file that would import both, or an imported id named
like one of the file's own items, fails the run. So does any other pair of
imported items of one name, such as the row structs and filters of `category`
and `categories`. Rename one table under [`[modules]`](#rok-sqlctoml), or
rename or opt out the relationship that needs the import under
[`[relationships]`](#rok-sqlctoml).

**Create inputs and update patches.** `NewProduct` leaves out generated
columns (serial, identity, `GENERATED`); a serial column is `NOT NULL` in the
row, on or off the primary key. A column with a default becomes an
`Option`, and `None` lets the database default apply. `UpdateProduct` makes
every column optional: `None` leaves the column unchanged, and for a
nullable column `Some(None)` sets it to `NULL`. An empty patch issues no
`UPDATE` and returns the current row.

<!-- source: docs/examples/quickstart/src/db/products/write.rs -->

```rust
pub async fn update<'e, E>(
    executor: E,
    id: ProductId,
    input: UpdateProduct,
) -> Result<Option<Product>, sqlx::Error>
where
    E: sqlx::PgExecutor<'e>,
```

**Lookups.** Each unique key (a unique constraint, or a unique index on plain
columns) gets a lookup. Text keys are borrowed:

<!-- source: docs/examples/quickstart/src/db/products/read.rs -->

```rust
pub async fn get_by_sku<'e, E>(executor: E, sku: &str) -> Result<Option<Product>, sqlx::Error>
where
    E: sqlx::PgExecutor<'e>,
```

**Typed search.** The filter has a list of typed conditions per column, and
they are combined with `AND`. Numbers, decimals, dates, times and typed ids
take `Ordered<T>` (`Eq`, `Ne`, `Lt`, `Le`, `Gt`, `Ge`, `Between`, `In`,
`NotIn`). Text columns take `Text` (`Eq`, `Ne`, `In`, `NotIn`, `Contains`,
`StartsWith`, `EndsWith`, matched literally). Booleans, UUIDs and enums take
`Equality<T>`. Each nullable column also gets an `*_is_null` check. Sorting
goes through the `ProductSortKey` allowlist, and every value is bound, so no
caller string ever reaches the SQL text:

<!-- source: docs/examples/quickstart/src/lib.rs -->

```rust
    let filter = ProductFilter {
        price: vec![Ordered::Lt(Decimal::new(5000, 2))],
        name: vec![Text::Contains("hammer".into())],
        ..ProductFilter::default()
    };
    let cheap = db::products::read::search(
        pool,
        filter,
        Sort::asc(ProductSortKey::Price),
        Page::first(20),
    )
    .await?;
```

`search` breaks ties by primary key, so pages are stable. `Page` and `Limit`
clamp page sizes to `1..=MAX_PAGE_SIZE` (500). `search_after(executor, filter,
after, limit)` does keyset pagination in primary-key order: pass the last key
you saw.

**Relationships.** Each foreign key between two tables generated together
gives a belongs-to on the child (`category_id` gives `category`) and a has-many
on the parent, named after the child module (`products`). If the foreign key
column is unique, the parent gets a has-one instead. A `parent_id`
self-reference gives `parent` and `children`. A join table (two `NOT NULL`
foreign keys that together form a unique key) relates its two tables
many-to-many, and its `write.rs` gains `attach`, `detach` and `sync`.

A loader takes rows you already fetched and loads one relationship for all of
them in a single `= ANY($1)` query, which avoids the N+1 pattern:

<!-- source: docs/examples/quickstart/src/db/products/relationships.rs -->

```rust
pub async fn load_category<'e, E>(
    executor: E,
    rows: &[Product],
) -> Result<HashMap<CategoryId, Category>, sqlx::Error>
```

<!-- source: docs/examples/quickstart/src/lib.rs -->

```rust
    let categories = db::products::relationships::load_category(pool, &cheap).await?;
    for product in &cheap {
        let category = &categories[&product.category_id];
        println!("{} ({})", product.name, category.name);
    }
```

To-many loaders return a `Vec` for every input key, empty when nothing is
related. A to-one relationship also gets a joined read that fetches the row
and its related row in one query:

<!-- source: docs/examples/quickstart/src/db/products/relationships.rs -->

```rust
pub async fn get_with_category<'e, E>(
    executor: E,
    id: ProductId,
) -> Result<Option<ProductWithCategory>, sqlx::Error>
```

The search filter gets a field per relationship, which is rendered as an
`EXISTS` subquery, so rows never repeat. For a to-many relationship it means
"at least one related row matches":

<!-- source: docs/examples/quickstart/src/db/categories/filter.rs -->

```rust
    /// Matches rows with at least one of their `products` (`products` rows) matching this filter.
    pub products: Option<Box<ProductFilter>>,
```

To rename or opt out of an inferred relationship, use
[`[relationships]`](#configuration). Two relationships of one table with the
same name fail generation, and the error names both.

### Shared modules


| File | Contents |
|---|---|
| `mod.rs` | Declares every module and lists the dependencies to add. Holds `UpdateOutcome` when a table has a version column. |
| `schema.rs` | `SCHEMA_SQL`: a verbatim snapshot of the input schema. It is never executed. |
| `search.rs` | `Page`, `Limit`, `Sort`, `Direction`, the condition types, and `MAX_RELATIONSHIP_DEPTH`. |
| `types.rs` | A Rust enum for each enum type and each value-list column, keeping its exact database labels. |
| `session.rs` | `set_tenant` and `set_user`, when the conventions name a setting. |
| `queries.rs` or `queries/` | One function per annotated query. |
| `http/` | With `extractors`: `BodyRejection`, the error envelope, and a `ValidatedJson<T>` per framework (`axum.rs`, `actix_web.rs`). |

<!-- source: docs/examples/quickstart/src/db/types.rs -->

```rust
/// The `product_status` enum type.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, sqlx::Type)]

#[sqlx(type_name = "product_status")]

pub enum ProductStatus {
```

`nullable`, `schema`, `search`, `session` and `types` are reserved module
names, as are `queries` when you pass query files and `http` when you set
`extractors`. A table that would generate one of those modules fails with an
error that says so.

**Code quality.** Every public item is documented. Generated code passes
`#![deny(missing_docs)]`, `cargo clippy -- -D warnings` and a fixed set of
pedantic lints (see [ADR 0013](docs/adr/0013-generated-code-quality-bar.md)),
and it is rustfmt-clean. It never forces your crate to relax its lints.

**Serde.** With `derive = ["serde"]` (or `-d serde`), rows, typed ids
(transparent), key structs, enums (by database label), inputs, patches,
joined-read structs (`ProductWithCategory`), query rows and parameters,
filters (`ProductFilter`), sort keys, and the `db::search` conditions and
`Sort` derive `Serialize` and `Deserialize`, so an API can take a search as
JSON. In a patch, an absent field leaves the column alone and `null` sets it
to `NULL` (`{"note": null}` is `note: Some(None)`); serializing skips the
absent fields. A filter field left out of the JSON adds no condition, and
condition, direction, and sort-key variants are snake_case
(`{"price_cents": [{"ge": 400}]}`, `{"key": "price_cents", "direction": "desc"}`). Without
`derive`, generated code doesn't mention serde. SQLx's `PgInterval` and
`PgTimeTz` implement no serde traits, so with serde a table with an
`INTERVAL` or `TIME WITH TIME ZONE` column (which would also reach its
filter), or a query row or parameter struct holding one, fails the run with
an error naming it.

**Validation.** `derive = ["serde", "validate"]` (or `-d serde -d validate`)
adds `validator::Validate` to create inputs and update patches, with rules
taken from the schema, and `extractors = ["axum", "actix_web"]` (or
`-e axum`) generates a `ValidatedJson<T>` extractor per framework
(see [Validated bodies and HTTP extractors](#validated-bodies-and-http-extractors)).
`validate` without `serde`, or `extractors` without `validate`, fails the run.

## Writing query files


A query file holds SQL statements, each starting with a `-- name:` line:

```text
-- name: <Name> :<mode>
-- param: $<n> <name> <RustType>     (optional, repeatable)
-- column: <name> <RustType>        (optional, repeatable)
<one SQL statement>
```

The name becomes the function name in snake_case. Other full-line comments
are dropped.

| Return mode | Runs | Returns |
|---|---|---|
| `:one` | `fetch_one` | the row; no row is `sqlx::Error::RowNotFound` |
| `:maybe_one` | `fetch_optional` | `Option<row>` |
| `:many` | `fetch_all` | `Vec<row>` |
| `:exec` | `execute` | `()` |
| `:execrows` | `execute` | `u64`, the number of affected rows |

**Parameter types are inferred only from positions that settle them.** These
are:

- a comparison, `IN`, `BETWEEN` or `LIKE` against a known column;
- `= ANY($n)`, which takes a slice;
- an `INSERT … VALUES` position, an `UPDATE … SET` target, or
  `ON CONFLICT … DO UPDATE SET`;
- `LIMIT`/`OFFSET` (`i64`);
- an explicit cast to a supported type, including an enum type
  (`$1::product_status` takes `types::ProductStatus`, and
  `$1::product_status[]` a slice of them).

A placeholder anywhere else fails generation. The error names the fix, a
`-- param:` override.

**Keys keep their typed ids.** A parameter typed by a primary key or foreign
key column takes that table's typed id, and so does a result column taken
straight from one, as in `ActiveProductsInCategory` at the top
(`category_id: CategoryId`, `id: ProductId`). A parameter compared with two
different ids falls back to the plain type, and so does any computed
expression.

Text parameters are taken as `&str` (`&CurrencyId` for a text key) and
arrays as slices. A query with more than three parameters takes a
`{Name}Params` struct instead:

<!-- source: docs/examples/quickstart/queries.sql -->

```sql
-- name: UpsertProductPrice :one
INSERT INTO products (category_id, sku, name, price)
VALUES ($1, $2, $3, $4)
ON CONFLICT (sku) DO UPDATE SET price = EXCLUDED.price
RETURNING *;
```

<!-- source: docs/examples/quickstart/src/db/queries.rs -->

```rust
pub async fn upsert_product_price<'e, E>(
    executor: E,
    params: UpsertProductPriceParams,
) -> Result<super::products::models::Product, sqlx::Error>
```

**Result columns are resolved against the schema.** rok-sqlc infers `*`,
`t.*`, plain and qualified columns, aliases, and `COUNT(…)` (`i64`). The
outer side of a `LEFT`/`RIGHT`/`FULL` join becomes `Option`. A result that is
exactly a table's columns, such as the `RETURNING *` above, reuses that
table's row struct. A single column decodes as a scalar. Anything else gets
a `{Name}Row` struct.

Any other expression needs an alias and a `-- column:` override, and a
parameter rok-sqlc can't type needs a `-- param:` override:

<!-- source: docs/examples/quickstart/queries.sql -->

```sql
-- name: SearchProductNames :many
-- param: $1 pattern String
-- column: display_name String
SELECT sku, upper(name) AS display_name
FROM products
WHERE lower(name) LIKE lower($1)
ORDER BY sku;
```

<!-- source: docs/examples/quickstart/src/db/queries.rs -->

```rust
pub async fn search_product_names<'e, E>(
    executor: E,
    pattern: &str,
) -> Result<Vec<SearchProductNamesRow>, sqlx::Error>
```

**More rules:**

- `WITH` queries work: each CTE is treated as a table.
- An `ON CONFLICT (cols)` target must be one of the table's unique keys, and
  `ON CONFLICT ON CONSTRAINT name` must name its primary key or a unique
  constraint: the declared name, or PostgreSQL's default for an unnamed one
  (`products_pkey`, `products_sku_key`). Like PostgreSQL, a default name
  another relation of the schema already takes (a table, a constraint, an
  index, a sequence, or a view) gets a number (`products_pkey1`). A unique
  index is no constraint, so PostgreSQL doesn't accept its name there.
- A query is exactly one statement. To run several, call several functions
  on `&mut *tx`.
- The SQL is embedded verbatim and bound positionally. It is not checked
  against a database.
- One query file generates `db/queries.rs`. A directory (its `*.sql` files)
  or several `--queries` inputs generate `db/queries/<file stem>.rs`, one
  module per file. Stems must be snake_case Rust identifiers.
- Conventions never rewrite query files: your SQL runs exactly as written.

## Conventions and the `rok` preset


A convention says what a column means in every table that has it. All
conventions are **off by default**. Turn them on in the `[conventions]`
section of `rok-sqlc.toml` or the JSON payload; they have no flags. The
complete example is in [`docs/examples/conventions`](docs/examples/conventions):

<!-- source: docs/examples/conventions/rok-sqlc.toml -->

```toml
[conventions]
preset = "rok"
```

| Key | `rok` preset | Effect on tables that have the column |
|---|---|---|
| `tenant_column` | `organization_id` | Every function takes the tenant right after the executor and adds `organization_id = $tenant` to every statement. The column is left out of inputs, patches, search filters, and sort keys. |
| `tenant_setting` | `app.organization_id` | Generates `db::session::set_tenant`, for row-level security policies. |
| `user_setting` | `app.user_id` | Generates `db::session::set_user`, for audit triggers. |
| `soft_delete_column` | `deleted_at` | `delete` sets it, `restore` clears it, and `delete_permanently` removes the row. Reads skip deleted rows, and filters get `include_deleted`. It must be a nullable `TIMESTAMP`/`TIMESTAMPTZ`. |
| `managed_columns` | `["updated_at", "row_version"]` | Left out of create inputs and update patches, but kept in rows. The database maintains them. |
| `version_column` | `row_version` | `update` takes `expected_version` and returns `UpdateOutcome` (optimistic concurrency). The column is always managed. |
| `primary_key_ids` | off | `"uuid_v4"`, `"uuid_v7"` or `"ulid"`: the generated code makes new primary keys (see below). |

Each explicit key overrides the preset's value. An empty string turns a
single-column convention off (`version_column = ""`), and
`primary_key_ids = "none"` turns key generation off.

`primary_key_ids` applies to tables whose primary key is one `UUID` column,
or with `"ulid"` also one text column. Their typed id gets a constructor
(`EventId::generate()`), and `create` takes the id as an `Option`. `None`
inserts a new id made in Rust, even when the column has a database default:

| Value | Key type | Value made | Dependency |
|---|---|---|---|
| `uuid_v4` | `UUID` | `uuid::Uuid::new_v4()` | `uuid` with its `v4` feature |
| `uuid_v7` | `UUID` | `uuid::Uuid::now_v7()`, ordered by creation time | `uuid` with its `v7` feature |
| `ulid` | `UUID` | `uuid::Uuid::from(ulid::Ulid::new())` | `ulid` with its `uuid` feature |
| `ulid` | text | `ulid::Ulid::new().to_string()`, 26 characters | `ulid` |

The generated `mod.rs` lists these dependencies too.

With the preset, the inputs leave out the tenant, managed and soft-delete
columns:

<!-- source: docs/examples/conventions/src/db/invoices/models.rs -->

```rust
pub struct NewInvoice {
    /// The `id` column.
    /// `None` applies the column default.
    pub id: Option<InvoiceId>,
    /// The `number` column.
    pub number: String,
    /// The `total` column.
    pub total: rust_decimal::Decimal,
    /// The `status` column.
    /// `None` applies the column default.
    pub status: Option<types::InvoiceStatus>,
}
```

`update` is scoped to the tenant and versioned:

<!-- source: docs/examples/conventions/src/db/invoices/write.rs -->

```rust
pub async fn update<'e, E>(
    executor: E,
    organization_id: OrganizationId,
    id: InvoiceId,
    expected_version: i64,
    input: UpdateInvoice,
) -> Result<UpdateOutcome<Invoice>, sqlx::Error>
```

<!-- source: docs/examples/conventions/src/lib.rs -->

```rust
    let mut tx = pool.begin().await?;
    // For row-level security policies and audit triggers.
    db::session::set_tenant(&mut tx, org).await?;
    db::session::set_user(&mut tx, user).await?;

    // The tenant comes right after the executor, on every function.
    let invoice = db::invoices::write::create(
        &mut *tx,
        org,
        NewInvoice {
            id: None,
            number: "INV-001".into(),
            total: Decimal::new(25_000, 2),
            status: None,
        },
    )
    .await?;

    // Optimistic concurrency: the update applies only at the version read.
    let patch = UpdateInvoice {
        status: Some(InvoiceStatus::Paid),
        ..UpdateInvoice::default()
    };
    let outcome =
        db::invoices::write::update(&mut *tx, org, invoice.id, invoice.row_version, patch).await?;
    match outcome {
        UpdateOutcome::Updated(paid) => assert_eq!(paid.row_version, invoice.row_version + 1),
        UpdateOutcome::NotFound => println!("deleted meanwhile"),
        UpdateOutcome::VersionConflict => println!("changed meanwhile; reload and retry"),
    }

    // Soft delete: reads skip the row until it is restored.
    db::invoices::write::delete(&mut *tx, org, invoice.id).await?;
    let hidden = db::invoices::read::get_by_number(&mut *tx, org, "INV-001").await?;
    assert!(hidden.is_none());
    db::invoices::write::restore(&mut *tx, org, invoice.id).await?;
    tx.commit().await
```

The database keeps managed columns up to date: in the example, a
[trigger](docs/examples/conventions/migrations/0002_touch_row.sql) sets
`updated_at` and bumps `row_version`. A managed column that is `NOT NULL` with
no `DEFAULT` (and not identity or generated) needs a `BEFORE INSERT` trigger
on its table, since inserts leave it out; without one, the table fails with a
`path:line` error. Trigger function bodies are not read.

A unique key that includes the tenant
column drops it from the lookup's name, so `UNIQUE (organization_id, number)`
gives `get_by_number`. A tenant column's foreign key is never treated as a
relationship.

## Validated bodies and HTTP extractors


An API takes create inputs and update patches as JSON, and should reject a
bad body before any statement runs. Two opt-in keys do that with the rules
the schema already holds
(see [Validated bodies and HTTP extractors](#validated-bodies-and-http-extractors)).

<!-- source: docs/examples/validated-api/rok-sqlc.toml -->

```toml
derive = ["serde", "validate"]
extractors = ["axum", "actix_web"]
```

`validate` derives `validator::Validate` (validator 0.21) on every create
input and update patch, with a rule for each column the schema constrains.
From this table:

<!-- source: docs/examples/validated-api/migrations/0001_members.sql -->

```sql
CREATE TABLE members (
    id BIGSERIAL PRIMARY KEY,
    name VARCHAR(80) NOT NULL CHECK (char_length(name) >= 1),
    handle VARCHAR(30) NOT NULL UNIQUE,
    age INTEGER CHECK (age BETWEEN 13 AND 130),
    balance NUMERIC(12, 2) NOT NULL DEFAULT 0 CHECK (balance >= 0),
    bio TEXT
);
```

the create input gets:

<!-- source: docs/examples/validated-api/src/db/members/models.rs -->

```rust
pub struct NewMember {
    /// The `name` column.
    #[validate(length(
        min = 1,
        max = 80,
        message = "name must be between 1 and 80 characters"
    ))]
    pub name: String,
    /// The `handle` column.
    #[validate(length(max = 30, message = "handle must be at most 30 characters"))]
    pub handle: String,
    /// The `age` column.
    #[validate(range(min = 13, max = 130, message = "age must be between 13 and 130"))]
    pub age: Option<i32>,
```

| Schema | Rule |
|---|---|
| `VARCHAR(n)`, `CHAR(n)` (and `CHARACTER [VARYING](n)`) | `length(max = n)`, counted in characters as PostgreSQL counts them |
| `CHECK (char_length(col) >= n)`, with `character_length` or `length`, any comparison | `length(min = n)` (or `max`); with a declared length, the tighter bounds, and `equal` when they meet |
| `CHECK (col >= n)`, `>`, `<=`, `<`, the literal on either side, `BETWEEN a AND b`, an `AND` of these, on an integer or float column | `range(...)`. A strict bound on an integer becomes inclusive (`> 0` is `min = 1`); on a float it stays strict (`exclusive_min`) |
| the same on a `NUMERIC` column (`Decimal`, which `range` can't compare, and which the orphan rule keeps from implementing validator's `ValidateRange`) | `custom(function = "<field>_in_range", code = "range")`, a function generated next to the input, whose error carries `range`'s `min`/`max` params |
| a typed id over text | `impl validator::ValidateLength<u64>` on the id, so a length rule applies through it, also on foreign keys |
| a typed id over an integer | `impl validator::ValidateRange<i64>` (the id's integer type) on the id, so a range rule applies through it, also on foreign keys |

Each rule has an English message naming the column and validator's code
(`length` or `range`). A patch field is checked only when it is present, so
an absent field or `null` passes. Every other `CHECK`, `NOT NULL`, enums and
value lists are not rules: the database or deserialization already enforces
them. A typed id over `NUMERIC` gets no range rule.

`extractors` (which needs `validate`) generates `db/http/`: `mod.rs` holds
the shared `BodyRejection` and the error envelope, and `axum.rs` and
`actix_web.rs` each hold a `ValidatedJson<T>` extractor for any
`T: DeserializeOwned + Validate`, a generated input or patch or a
hand-written request type. The handler runs only for a validated body:

<!-- source: docs/examples/validated-api/src/lib.rs -->

```rust
    async fn create_member(
        State(pool): State<PgPool>,
        ValidatedJson(input): ValidatedJson<NewMember>,
    ) -> Result<Json<Member>, StatusCode> {
        let member = crate::db::members::write::create(&pool, input)
            .await
            .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
        Ok(Json(member))
    }
```

The actix-web handler is the same, with `crate::db::http::actix_web::ValidatedJson`,
and needs no `JsonConfig` error handler:

<!-- source: docs/examples/validated-api/src/lib.rs -->

```rust
    async fn create_member(
        pool: web::Data<PgPool>,
        ValidatedJson(input): ValidatedJson<NewMember>,
    ) -> actix_web::Result<web::Json<Member>> {
        let member = crate::db::members::write::create(pool.get_ref(), input)
            .await
            .map_err(ErrorInternalServerError)?;
        Ok(web::Json(member))
    }
```

Any other body is answered in the Rok error envelope, the same on both
frameworks:

| The body | Status | `code` | `details` |
|---|---|---|---|
| no JSON `Content-Type`, bad JSON syntax, or unreadable | `400` | `MALFORMED_BODY` | none |
| over the framework's size limit | `413` | `PAYLOAD_TOO_LARGE` | none |
| JSON that doesn't fit the type (a missing field, a wrong type, an unknown label) | `422` | `VALIDATION_FAILED`, with serde's message | none |
| breaks a validation rule | `422` | `VALIDATION_FAILED` | validator's errors by field |

`{"name": "", "handle": "ada", "age": 7}` is answered `422` with:

<!-- source: docs/examples/validated-api/tests/envelope.rs -->

```json
{
  "success": false,
  "error": {
    "message": "the request body failed validation",
    "code": "VALIDATION_FAILED",
    "details": {
      "name": [
        {
          "code": "length",
          "message": "name must be between 1 and 80 characters",
          "params": { "min": 1, "max": 80, "value": "" }
        }
      ],
      "age": [
        {
          "code": "range",
          "message": "age must be between 13 and 130",
          "params": { "min": 13, "max": 130, "value": 7 }
        }
      ]
    }
  }
}
```

The extractors read the body through `axum::Json` and `web::Json`, so each
framework's settings apply: axum's `DefaultBodyLimit`, and actix-web's
`JsonConfig` limit and `Content-Type` predicate (actix-web's `PayloadConfig`
limit does not apply to JSON). Both limits default to 2 MiB (axum 0.8,
actix-web 4); set the same limit on both to answer a large body the same way.
A body over it gets `413` and `"the request body is over the size limit"`
from either. A parse error's message is serde's own, taken from inside each
framework's rejection, never the framework's text (axum's adds a field
path), so both frameworks give the same messages. What counts as a JSON
`Content-Type` is still each framework's call: axum takes
`application/json` and `application/*+json`, actix-web also `text/json` and
anything its `JsonConfig` predicate allows. `BodyRejection`
(`Malformed { message }`, `TooLarge` or
`ValidationFailure(validator::ValidationErrors)`) is public, with `status()`
and `body()`, so an app that wants another response can match on it;
`BodyRejection::from_serde` and `db::http::validated(body)` apply the same
rules outside a handler. Only JSON bodies are covered: query strings, forms,
and query-file parameters are not validated. `db/mod.rs` names the
`validator`, `axum`, `serde_path_to_error` (axum wraps serde's error in it)
and `actix-web` dependencies to add. The complete crate is in
[`docs/examples/validated-api`](docs/examples/validated-api).

## Configuration


Options come from four layers. The most specific wins:
**flags > JSON payload (`-j`) > `rok-sqlc.toml` > defaults**. A list (such as
`schema`, `queries`, `derive` or `extractors`) replaces the lower layer's list whole and is
never appended to. `[conventions]` keys, `[relationships]` entries and
`[modules]` entries merge one by one.

### `rok-sqlc.toml`


Without `-c`, rok-sqlc looks for `rok-sqlc.toml` in the current directory and
then in each parent, like Cargo does. Paths in the file are relative to the
file. Unknown keys are errors, so a typo can't silently do nothing. This is
every key:

<!-- config-reference -->

```toml
schema   = ["migrations/"]   # a path or a list: SQL files or migration directories
queries  = ["queries/"]      # a path or a list: query files or directories
output   = "src/db"          # the default
resource = "products"        # add this table to the generated ones; rarely useful in a file
derive   = ["serde", "validate"]  # extra derives for generated types; "validate" needs "serde"
extractors = ["axum", "actix_web"]  # validated-body extractors to generate; need "validate"

[conventions]                # all off unless set; see "Conventions"
preset             = "rok"
tenant_column      = "organization_id"
tenant_setting     = "app.organization_id"
user_setting       = "app.user_id"
soft_delete_column = "deleted_at"
managed_columns    = ["updated_at", "row_version"]
version_column     = "row_version"
primary_key_ids    = "uuid_v7"   # or "uuid_v4", "ulid", "none"

[relationships.invoices]     # by table, then by inferred relationship name
created_by_user  = "author"  # rename: load_author, get_with_author, filter field author
approved_by_user = false     # opt out, together with the other side

[modules]                    # by table: generate it as another module
"audit.users" = "audit_users"  # db::audit_users, with AuditUser and AuditUserId
```

`[modules]` renames a table's module, and its row struct, typed id and key
struct follow the new name. That's how same-named tables of two schemas
(`core.users` and `audit.users`) both generate. A key is the table's
schema-qualified name or its SQL name. A key that names no table, or a name
that isn't a snake_case Rust identifier, fails the run.

`[relationships]` entries are checked against the whole schema. An unknown
table or relationship, an invalid name, or a rename that collides fails with
the entry's name (`relationships.invoices.created_by_user`). `true` is an
error, not a no-op.

### JSON payload


`-j/--json` takes the same keys as JSON. Pass it inline
(`-j '{"output":"src/db"}'`), from a file (`-j @config.json`), or from stdin
(`-j -`). Its paths are relative to the current directory. The payload
layers over `rok-sqlc.toml` and doesn't turn discovery off.

```json
{
  "schema": ["migrations/"],
  "output": "src/db",
  "derive": ["serde", "validate"],
  "extractors": ["axum"],
  "conventions": { "preset": "rok", "version_column": "" }
}
```

### Flags


The command is `generate`, or `g` for short (`rok-sqlc g`). The `help`
command prints the help (`rok-sqlc help generate`).

| Flag | Meaning |
|---|---|
| `-s`, `--schema <PATH>` | A schema file, or a directory of migrations read in filename order (`*.down.sql` skipped). Repeat it to combine inputs. |
| `-q`, `--queries <PATH>` | A query file (`db/queries.rs`) or a directory (`db/queries/<stem>.rs`). Repeatable. |
| `-o`, `--output <DIR>` | The output directory. Default: `src/db`. |
| `-r`, `--resource <TABLE>` | Generate this table (SQL or module name) and regenerate every resource already generated in the output directory, so they and `db/mod.rs` stay current. Tables not generated yet stay ungenerated. |
| `-c`, `--config <FILE>` | Read this config file instead of discovering `rok-sqlc.toml`. |
| `-j`, `--json <PAYLOAD>` | The JSON payload: inline, `@FILE`, or `-` for stdin. |
| `-d`, `--derive <NAME>` | Add a derive to generated types (`serde`, or `validate`, which needs `serde`). Repeatable. |
| `-e`, `--extractor <FRAMEWORK>` | Generate a validated-body extractor for `axum` or `actix_web` (needs `validate`). Repeatable. |
| `-n`, `--dry-run` | Print what would be written, removed or refused, and touch nothing. |
| `-k`, `--check` | Write nothing. List missing, changed and stale files, and exit 1 if there are any. |
| `-f`, `--force` | Overwrite existing files that rok-sqlc did not generate. |
| `-l`, `--lenient` | Skip unsupported tables and queries with warnings instead of failing. |
| `-h`, `--help` | Print help and exit 0. |
| `-V`, `--version` | Print the version and exit 0. |

`--dry-run`, `--check`, `--force` and `--lenient` are flags only, because
they describe a run rather than a project. A run with no schema (no
`--schema` and no `schema` key) is a usage error. Errors exit with code 1.

## Using it from `build.rs`


The library runs exactly what the CLI runs: `rok_sqlc::generate(&Config) ->
Result<Report>`. Add `rok-sqlc` under `[build-dependencies]`:

<!-- source: examples/build_script.rs -->

```rust
fn main() -> Result<(), Box<dyn Error>> {
    println!("cargo::rerun-if-changed=migrations");
    println!("cargo::rerun-if-changed=queries.sql");

    // Paths are relative to the package root, where Cargo runs build scripts.
    let mut config = rok_sqlc::Config::default();
    config.schema = vec!["migrations".into()];
    config.queries = vec!["queries.sql".into()];
    config.output = "src/db".into();

    match rok_sqlc::generate(&config) {
        Ok(_report) => Ok(()),
        Err(error) => {
            // The report says which tables and queries failed, and where.
            for failure in &error.report().table_failures {
                println!("cargo::warning={failure}");
            }
            for failure in &error.report().query_failures {
                println!("cargo::warning={failure}");
            }
            Err(error.into())
        }
    }
}
```

The library never reads `rok-sqlc.toml` and never prints: a build script gets
exactly the `Config` it built. Set `config.conventions`
(`rok_sqlc::Conventions::rok()`), `config.derive`
(`rok_sqlc::Derive::Serde`), `config.extractors` (`rok_sqlc::Extractor`),
`config.relationships`
(`rok_sqlc::RelationshipChange`) and `config.modules` to match the config
file's sections.
`Config` is `#[non_exhaustive]`, so start from `Config::default()` and set
fields. The `Report` lists written, unchanged, refused and stale files and
any skipped tables or queries.

The stable library API is `generate`, `Config`, `Conventions`, `Derive`,
`Extractor`, `IdGeneration`, `RelationshipChange`, `Report` (with `RefusedFile`, `TableFailure` and
`QueryFailure`), and `Error`. Changing the *generated* API counts as a
breaking change too (see [ADR 0012](docs/adr/0012-library-api-and-stability.md)).

## CI with `--check`


`--check` regenerates in memory and compares the result with the files on
disk. It exits 1 and lists every missing, changed or stale file when they
differ, and it writes nothing:

```sh
rok-sqlc g --check
```

Run it in CI after installing rok-sqlc to catch migrations or queries that
were changed without regenerating.

Line endings don't count as drift. rok-sqlc reads migrations and query
files with CRLF as LF and writes `\n`, and it compares generated files the
same way. A checkout with CRLF line endings (Windows, `core.autocrlf`)
therefore generates the same code and passes `--check`.

## Supported SQL and type mapping


rok-sqlc reads PostgreSQL DDL with a SQL parser. It never connects to a
database.

| PostgreSQL | Rust |
|---|---|
| `SMALLINT`, `INT2`, `SMALLSERIAL` | `i16` |
| `INTEGER`, `INT`, `INT4`, `SERIAL` | `i32` |
| `BIGINT`, `INT8`, `BIGSERIAL` | `i64` |
| `REAL`, `FLOAT4` | `f32` |
| `DOUBLE PRECISION`, `FLOAT8`, `FLOAT` | `f64` |
| `BOOLEAN` | `bool` |
| `TEXT`, `VARCHAR`, `CHAR` | `String` (`&str` for parameters) |
| `UUID` | `uuid::Uuid` |
| `DATE` | `chrono::NaiveDate` |
| `TIME` | `chrono::NaiveTime` |
| `TIMESTAMP` | `chrono::NaiveDateTime` |
| `TIMESTAMPTZ` | `chrono::DateTime<chrono::Utc>` |
| `TIME WITH TIME ZONE`, `TIMETZ` | `sqlx::postgres::types::PgTimeTz` |
| `INTERVAL` | `sqlx::postgres::types::PgInterval` |
| `BYTEA` | `Vec<u8>` (`&[u8]` for parameters) |
| `NUMERIC`, `DECIMAL` (at most 28 digits) | `rust_decimal::Decimal` |
| `MONEY` | `sqlx::postgres::types::PgMoney` |
| `INT4RANGE`, `INT8RANGE` | `sqlx::postgres::types::PgRange<i32>`, `PgRange<i64>` |
| `NUMRANGE` | `sqlx::postgres::types::PgRange<rust_decimal::Decimal>` |
| `DATERANGE`, `TSRANGE`, `TSTZRANGE` | `sqlx::postgres::types::PgRange<T>` of the `chrono` type above |
| `INET`, `CIDR` | `ipnetwork::IpNetwork` (SQLx's `ipnetwork` feature) |
| `MACADDR` | `mac_address::MacAddress` (SQLx's `mac_address` feature) |
| `JSON`, `JSONB` | `serde_json::Value` |
| `T[]` | `Vec<T>` |
| `CREATE TYPE … AS ENUM` | an enum in `db::types` |
| text column with `CHECK (col IN ('a', …))` | an enum in `db::types` (`InvoiceStatus`) |

A nullable column is wrapped in `Option`, and a primary key column uses its
typed id. SQLx implements no `PartialOrd` for `PgInterval`, `PgTimeTz`,
`PgMoney` or `PgRange`, so those columns get equality filters, as `BYTEA`
and network columns do. `PgTimeTz` holds
`chrono` types, or the `time` crate's types when SQLx's `time` feature is on.
SQLx decodes `INTERVAL` only from prepared statements, which is what the
generated code uses.

**Statements rok-sqlc reads:**

- `CREATE TABLE`: columns, `DEFAULT`, identity and `GENERATED` columns,
  inline and table-level `PRIMARY KEY`, `UNIQUE`, `REFERENCES`/`FOREIGN KEY`,
  and value-list `CHECK`s. Other `CHECK`s are ignored.
- `ALTER TABLE`: `ADD COLUMN`, `DROP COLUMN`, `RENAME COLUMN`,
  `ADD CONSTRAINT` (primary key, unique, foreign key, value-list check;
  other `CHECK`s are ignored, as in `CREATE TABLE`),
  `ENABLE`/`DISABLE ROW LEVEL SECURITY`, and `ALTER COLUMN` with
  `[SET DATA] TYPE` (with or without `USING`), `SET`/`DROP NOT NULL`,
  `SET`/`DROP DEFAULT`, and `ADD GENERATED … AS IDENTITY`. The column ends up
  in its final shape, and its keys follow a type change. `DROP IDENTITY` and
  `DROP EXPRESSION` act like `DROP DEFAULT`, and `TYPE … COLLATE` like
  `TYPE`. `RENAME CONSTRAINT` renames a primary key or unique constraint.
- `ALTER TABLE` clauses that leave the model as it is: `SET STATISTICS`,
  `SET STORAGE`, `SET COMPRESSION`, `SET`/`RESET (…)`, `SET GENERATED`,
  `RESTART` and other identity options on a column; `SET`/`RESET (…)`,
  `CLUSTER ON`, `SET WITHOUT CLUSTER`, `SET TABLESPACE`, `SET [UN]LOGGED`,
  `[NO] FORCE ROW LEVEL SECURITY`, `REPLICA IDENTITY`, `OWNER TO`,
  `ENABLE`/`DISABLE TRIGGER`/`RULE`, `VALIDATE CONSTRAINT` and
  `ALTER CONSTRAINT` on the table.
- `ALTER INDEX`, `ALTER SEQUENCE`, `ALTER VIEW` and `ALTER MATERIALIZED
  VIEW … RENAME TO`, for the names PostgreSQL gives unnamed constraints.
  Renaming a key constraint's index renames the constraint.
- `CREATE UNIQUE INDEX` on plain columns, which becomes a unique key with a
  lookup. A partial index over live rows (`WHERE deleted_at IS NULL`) counts
  under the soft-delete convention. Expression indexes are ignored.
- `CREATE TYPE … AS ENUM`, and `ALTER TYPE … ADD VALUE`/`RENAME VALUE`/
  `RENAME TO`. A renamed enum takes the Rust name of its new name, and the
  columns using it follow.
- `DROP TABLE`, which removes the table, so its generated files become stale
  and are removed. Foreign keys other tables hold to it go too, as with
  `CASCADE`: those columns keep their raw type and lose the relationship.
- `DROP TYPE` of an enum. With `CASCADE`, the columns using it are dropped.
  Without it, a table that still uses the type fails.

All other statements (functions, triggers, policies, views, grants, and so
on) are skipped without comment, including functions and procedures with a
`BEGIN ATOMIC` body and `DO` blocks. Schema qualifiers are
kept (`catalog.products`), and `public.` is the same as no qualifier.

**What is rejected, and why.** Generation is strict by default
([ADR 0001](docs/adr/0001-strict-generation-by-default.md)): if a table or
query can't be generated correctly, the run writes nothing and exits 1, and
the error is reported as `path:line:`. A silently incomplete `db` module is a
worse failure than a loud one. `--lenient` skips the offending tables and
queries with warnings instead. A skipped table keeps the files an earlier run
generated for it, unchanged and still declared in `mod.rs`; they are not
stale, so `--check` reports the warning but no drift. The rest is generated
against the table's last good shape (before the migration that broke it), so
its enums, typed ids, and relationships stay and the crate still compiles.
A table that fails at its own `CREATE TABLE` has no such shape, and its old
files are removed as stale. If every table is unsupported, the run still
fails. With `--resource`, only that table's problems count.

| Rejected | Why |
|---|---|
| Column types not in the table above (`POINT`, `XML`, `MACADDR8`, multiranges, …) | There is no chosen Rust mapping yet, and rok-sqlc doesn't guess one. |
| `INTERVAL`, `TIME WITH TIME ZONE`, `MONEY` and range types with `derive = ["serde"]` | SQLx's `PgInterval`, `PgTimeTz`, `PgMoney` and `PgRange` implement no serde traits, so the serde derives wouldn't compile. The whole run fails, even with `--lenient`. |
| `NUMERIC(p, s)` with `p` > 28 | `rust_decimal` holds 28 significant digits, so the value would fail to decode at runtime. |
| Other `ALTER TABLE` clauses (`RENAME TO`, `ALTER COLUMN … TYPE` to an unsupported type, `DROP NOT NULL` on a primary key column, …) | The table's shape after the change is unknown, so the table fails. |
| An `ALTER TYPE` that can't be applied (an existing label or type name, an unknown label) | The tables that use the type fail. |
| A table whose module name is reserved or already taken | Its module would collide with a generated one. Rename it in `[modules]`. |
| Two typed ids of one name imported into one file, or an imported id named like one of the file's own items | The generated code wouldn't compile. Rename a module in `[modules]`. |
| Columns whose filter or sort-key names collide (`weight` next to `weight_is_null`) | The generated code wouldn't compile. |
| Two relationships of one table with the same name, or a relationship named like a filter field | Rename one in `[relationships]`. |
| A soft-delete column that is not a nullable timestamp | `delete` couldn't record the time. |
| A query placeholder or result expression rok-sqlc can't type | Add a `-- param:` or `-- column:` override. |
| Unknown tables or columns in a query, more than one statement, `UNION` outside a recursive CTE, data-modifying CTEs | They can't be analyzed (yet). |
| A recursive CTE whose recursive term returns other columns than its anchor | The CTE's columns come from the anchor. |
| An `ON CONFLICT (cols)` target that is not a unique key | It would fail at runtime. The error lists the table's unique keys. A partial unique index counts when the target repeats its condition: `ON CONFLICT (email) WHERE deleted_at IS NULL`. |
| An `ON CONFLICT ON CONSTRAINT name` that names no primary key or unique constraint | It would fail at runtime. The error lists the table's constraint names. |

## Limitations and roadmap


**Known limitations:**

- Types outside the type table (`POINT`, `XML`, `MACADDR8`, multiranges, …)
  are unsupported, in tables and in query casts (`$1::point`).
- `INTERVAL`, `TIME WITH TIME ZONE`, `MONEY` and range columns can't be
  generated with `derive = ["serde"]`.
- A partial-index `ON CONFLICT` target must repeat the index's condition
  exactly. PostgreSQL also infers a partial index from a condition that
  implies it, which rok-sqlc doesn't check.
- Relationship filters nest at most `MAX_RELATIONSHIP_DEPTH` (4) deep. Deeper
  filters make `search` fail with `sqlx::Error::InvalidArgument`.
- Keyset pagination (`search_after`) follows primary-key order only. Array
  and JSON columns get only null checks in filters.
- `UNION` is read only as the body of a recursive CTE, and data-modifying
  CTEs are rejected in query files.
- `ALTER TABLE … RENAME TO`, `SET SCHEMA`, partitioning (`ATTACH`/`DETACH
  PARTITION`), `DROP CONSTRAINT`, and other `ALTER TABLE` forms that change
  the model in ways rok-sqlc doesn't follow fail the table they alter, at
  their `path:line` (`--lenient` skips it). Any other statement the parser
  can't read stops the run at its `path:line`, unless it is a function,
  procedure, `DO` block, or `ALTER` of an index, sequence or view.
- Triggers are followed through `CREATE` and `DROP TRIGGER` only:
  `DISABLE TRIGGER` doesn't take a managed column's source of values away.
- Typed ids and relationships cover only the tables generated together. A
  foreign key into another migration set keeps its raw type and makes no
  relationship.
- A table `--lenient` skips is kept only with a last good shape: its model
  before the statement that broke it, which matches its kept files when
  the run that wrote them saw the migrations up to that statement. A table
  that fails at its own `CREATE TABLE` (an edited migration, say) has none,
  so its earlier files are removed as stale.
- Default constraint names follow renamed indexes, sequences, views and key
  constraints, but foreign key and check constraint names aren't tracked.
- A versioned `update` of a row that a concurrent transaction deletes while
  the `UPDATE` waits for its lock reports `VersionConflict`. A retry reports
  `NotFound`.

**Not planned** (possible later):

- Full-text search, pgvector, and embedding persistence.
- A compile-time-checked `query!` mode.
- Declared has-many-through and polymorphic relationships, beyond renaming
  and opting out of inferred ones.
- Nested writes (creating a row together with its children).
- Machine-readable output (`--format json`).
- SQLx versions other than 0.9, a user-facing module-directory input layout,
  and databases other than PostgreSQL.
- JSONB operators in typed filters.

## Contributing


```sh
cargo test                                   # unit, CLI, and generated-code suites
cargo clippy --all-targets -- -D warnings
cargo fmt --all -- --check
```

- **Two toolchains.** The tool builds on Rust 1.88 (so no `if let` guards in
  `match`, for example). The suites that compile generated code
  (`tests/fixture_compile.rs`, `tests/module_fixtures/`, and
  `the_examples_compile` in `tests/readme.rs`) need Rust 1.94. Below that,
  they print a skip notice and pass. CI runs 1.88, 1.94 and stable.
- **PostgreSQL suite.** Set `ROK_SQLC_TEST_DATABASE_URL` to a throwaway
  database (for example `postgres://postgres:postgres@localhost:5432/postgres`)
  to run the generated code in `tests/fixture-app` against PostgreSQL and to
  smoke-run the module fixtures in `modules/`. The module run creates
  databases, so the role needs `CREATEDB`. Without the variable, those tests
  print "skipping".
- **This README.** `tests/readme.rs` checks that every flag, alias and config
  key in the code appears here (and nothing else does), that every config
  sample is accepted, and that every code sample is copied verbatim from
  [`docs/examples/`]docs/examples/. It also checks that those examples have
  no drift and that they compile. After changing the generator, run
  `rok-sqlc g` in each example directory and update the samples here.
- **Decisions** are recorded as ADRs in [`docs/adr/`]docs/adr/. Read the
  ones for the area you touch, and add one for a decision that is hard to
  reverse. [`docs/design.md`]docs/design.md is the original design
  walkthrough, kept as historical background.
- **Terms** follow [`GLOSSARY.md`]GLOSSARY.md: table vs. resource, query
  file, return mode, query override, convention, and so on.
- **Changes** go in [`CHANGELOG.md`]CHANGELOG.md. Changes to the generated
  API count as breaking.
- **Releases.** Bump `version` in `Cargo.toml`, move CHANGELOG's Unreleased
  entries under `## [X.Y.Z]`, and push the tag `vX.Y.Z`. The
  [Release workflow].github/workflows/release.yml checks the tag matches
  `Cargo.toml`, builds the binaries, publishes the GitHub release with that
  CHANGELOG section as its notes, and then installs it with both install
  scripts. To build a tag that predates the workflow, run it by hand with the
  tag. Publishing to crates.io stays a manual `cargo publish`.

## License


Licensed under either of [Apache License, Version 2.0](LICENSE-APACHE) or
[MIT license](LICENSE-MIT), at your option.