Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
c131046
Implemenet DuckDB + partially maintenance with whatever is possible w…
nicoloesch Oct 14, 2026
83eb06f
Resolve cyclical and self-referential FKs, update CLI, fix bugs
nicoloesch Oct 15, 2026
9b54c4a
In transaction check, overwrite raw strings with core equivalents
nicoloesch Oct 15, 2026
077877f
Rectify Person to only include columns that are specified by CDM 5.4
nicoloesch Oct 15, 2026
c30664f
Remove psycopg3, small fixes, correct Dialect Strings, update docs
nicoloesch Oct 16, 2026
b3590fe
Fix postgres reflecting double as float
nicoloesch Oct 16, 2026
77cccf8
Pre-check for loading vocabs
nicoloesch Oct 16, 2026
0e88446
Correct place for checking + regression tests
nicoloesch Oct 16, 2026
47e31a3
Additional cyclical table loading fix
nicoloesch Oct 16, 2026
4509d1f
Have DuckDB backup and restore functionality
nicoloesch Oct 16, 2026
96a7f21
Update the ci for duckdb for new workflow
nicoloesch Oct 23, 2026
f109408
Resolve schema_claims-only tags in FK span checks
nicoloesch Oct 26, 2026
fe51fb3
Adapt to the orm-loader file pipeline: file wording, resolved passed …
nicoloesch Oct 29, 2026
9e235e2
Use relaxed_foreign_keys in the installation docs and the full-text test
nicoloesch Oct 29, 2026
aaf178e
Rename the insert_if_empty merge strategy to insert
nicoloesch Oct 30, 2026
c0a9a32
Restore inline rendering of use_alter foreign keys after each test
nicoloesch Oct 30, 2026
d5d468a
Report unenforced foreign keys, count only blocking issues, match Duc…
gkennos Nov 3, 2026
a33d8a6
Explain partial vocabulary loads and extend the vocabulary fixtures
gkennos Nov 3, 2026
a633215
Flush ORM inserts inside relaxed_foreign_keys in the installation docs
gkennos Nov 3, 2026
4e1c4da
bumping dependencies per orm-loader release
gkennos Nov 5, 2026
c8ab544
dependabot
gkennos Nov 5, 2026
6f7213c
ci/cd update
gkennos Nov 5, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@ jobs:
uses: AustralianCancerDataNetwork/cava-devops/.github/workflows/build-test.yml@main
with:
ty-src: omop_alchemy
build-test-duckdb:
uses: AustralianCancerDataNetwork/cava-devops/.github/workflows/build-test-duckdb.yml@main
with:
ty-src: omop_alchemy
build-test-postgres:
uses: AustralianCancerDataNetwork/cava-devops/.github/workflows/build-test-postgres-v2.yml@main
with:
Expand Down
89 changes: 63 additions & 26 deletions docs/advanced/backends.md
Original file line number Diff line number Diff line change
@@ -1,38 +1,75 @@
# Backend Compatibility

Every maintenance operation goes through a `Backend` (`PostgresBackend` or
`SQLiteBackend`). PostgreSQL implements the full `Backend` interface.
SQLite implements only what SQLite itself can do; everything else raises
Every maintenance operation goes through a `Backend`
(`PostgresBackend`, `SQLiteBackend`, or `DuckDBBackend`). PostgreSQL
implements the full `Backend` interface. SQLite and DuckDB each implement
only what their own engine can do; everything else raises
`FeatureNotSupportedError` at call time rather than failing silently or
producing a partial result.

| Feature | PostgreSQL | SQLite |
| --- | --- | --- |
| Index existence check | Yes | Yes |
| Drop index if exists | Yes | Yes (unqualified — no schema concept) |
| `ANALYZE` | Yes | Yes |
| `VACUUM ANALYZE` | Yes | No |
| FK trigger management / status | Yes | No |
| FK constraint violation counting | Yes | No |
| Table clustering (`CLUSTER`) | Yes | No |
| Cluster index inspection | Yes | No |
| Functional-index expression normalization | Yes | No (SQLite never reflects expression-based indexes) |
| `TRUNCATE ... RESTART IDENTITY / CASCADE` | Yes | No |
| Sequence lookup / reset | Yes | No (SQLite has no sequences) |
| Full-text search | Yes — see [PostgreSQL Full-Text Search](fulltext.md) | No |
| Database backup / restore | Yes | No |
producing a partial result. Run `omop-alchemy info` against your target
database to see the exact per-command support matrix, derived live from
which methods the resolved backend class overrides.

| Feature | PostgreSQL | SQLite | DuckDB |
| --- | --- | --- | --- |
| Index existence check | Yes | Yes | Yes |
| Drop index if exists | Yes | Yes (unqualified, no schema concept) | Yes |
| `ANALYZE` | Yes | Yes | Yes |
| `VACUUM ANALYZE` | Yes | No | Yes |
| FK trigger management / status | Yes | No | No (no trigger mechanism) |
| FK constraint violation counting | Yes | No | Yes (anti-join; also covers deferred FKs, see below) |
| Table clustering (`CLUSTER`) | Yes | No | No |
| Cluster index inspection | Yes | No | No |
| Functional-index expression normalization | Yes | No (SQLite never reflects expression-based indexes) | Yes |
| `TRUNCATE ... RESTART IDENTITY` | Yes | No | Yes |
| `TRUNCATE ... CASCADE` | Yes | No | No, see below |
| Sequence lookup / reset | Yes | No (SQLite has no sequences) | Yes |
| Full-text search | Yes, see [PostgreSQL Full-Text Search](fulltext.md) | No | No |
| Database backup / restore | Yes (`pg_dump`/`pg_restore`/`psql`) | No | Yes (in-process, no external tool) |

## What this means in practice

Maintenance CLI commands that rely on a not-supported feature raise
`FeatureNotSupportedError` on SQLite rather than doing nothing. In
particular, against a SQLite database:
A command that relies on a not-supported feature raises
`FeatureNotSupportedError` rather than doing nothing. Against SQLite:

- `indexes cluster` and the clustering step of `indexes enable`
are unavailable.
- `indexes cluster` and the clustering step of `indexes enable` are unavailable.
- `truncate-tables` cannot use `RESTART IDENTITY`/`CASCADE`.
- `fulltext install` is unavailable entirely.
- `backup-database`/`restore-database` are unavailable entirely.
- FK trigger toggling and FK violation counting are unavailable.

SQLite remains fully supported for the core ORM/CDM layer (models, queries, `create-missing-tables`, schema-drift detection at engine construction). These limitations are specific to the maintenance operations listed above, which assume a PostgreSQL-grade catalog.

## DuckDB specifics

- `fulltext install`, table clustering, and FK trigger toggling/status are
unavailable, same as SQLite.
- `truncate-tables --restart-identities` works; `--cascade` does not (see below).
- `reset-sequences` and `foreign-keys validate` both work, unlike on SQLite.
- `backup-database`/`restore-database` work: each occupied schema's tables are copied to/from one Parquet file each, scoped to that schema. Restore is data-only; target tables must already exist.

### Deferred foreign keys

DuckDB can create a foreign key inline at `CREATE TABLE` time, but cannot execute the deferred `ALTER TABLE ADD CONSTRAINT` a cyclic or self-referential foreign key otherwise needs.
Instead, we introduce a shim in oa-configurator that no-ops these statements. Marking specific columns with `use_alter=True` routes this into the deferred path:

- `domain.domain_concept_id`, `vocabulary.vocabulary_concept_id`, `concept_class.concept_class_concept_id`: break the real `concept`/`concept_class`/`domain`/`vocabulary` reference cycle. Load these four tables in that order (matches `ATHENA_LOAD_ORDER`).
- `relationship.reverse_relationship_id`, `episode.episode_parent_id`, `visit_occurrence.preceding_visit_occurrence_id`, `visit_detail.preceding_visit_detail_id`, `visit_detail.parent_visit_detail_id`: DuckDB would reject any bulk-load row inserted before its own self-referenced parent row exists, with no FK-toggle to relax that temporarily.

All FKs falling into this specification are never enforced at the database level on DuckDB. `DatabaseBackend.deferred_fk_constraints()`
- `orm-loader` is the single source of truth for which FKs this applies to: `reconcile-schema`,`foreign-keys validate`, and `doctor --deep` all consult it and run an anti-join check in its place.
- `load_vocab_source` validates every deferred FK automatically once the whole load completes, instead of per table: a deferred FK's referenced table can load after its referencer, so checking immediately would flag rows that are only temporarily unresolved.

### `relationship` must load after `concept`

`relationship.relationship_concept_id` is an ordinary enforced FK to `concept` since it isn't part of any reference cycle. Postgres and SQLite hide this because FK checks are disabled during a bulk load; DuckDB can't disable them, so `concept` must already be loaded first. `REQUIRED_VOCAB_MODELS` and `ATHENA_LOAD_ORDER` both order `Concept` before `Relationship` for this reason.

### `merge_strategy="replace"` fails on a table that's both referenced and owns its own FK

DuckDB's `replace` merge strategy updates matching rows in place, since it rejects deleting a still-referenced row outright with no FK-toggle or deferred-constraint escape hatch. That UPDATE also fails on any column that's part of one of the table's own FK constraints, whenever the row is currently referenced elsewhere, regardless of `index_strategy` (DuckDB's FK-column bookkeeping isn't a SQLAlchemy `Index` object `index_strategy` can drop). In the CDM this affects `concept`, `person`, `visit_occurrence`, `provider`, and `care_site`. `merge_replace` raises a clear error up front, before touching any data, naming the table; use `--merge-strategy upsert` instead, or reload into an empty database.

### `truncate-tables --cascade` is not supported

DuckDB's parser accepts `CASCADE` on a `TRUNCATE` statement but silently ignores it.Pass the real set of dependent tables explicitly instead; `truncate-tables` already orders whatever set you give it correctly regardless of input order.

## Why `supports_fast_load` is `False`

DuckDB's loader uses the same generic staged-merge path as SQLite rather than a native bulk-COPY equivalent. This is a deliberate choice as the generic path is fast enough at measured CDM-scale load volumes.
10 changes: 3 additions & 7 deletions docs/advanced/vocabulary_load_performance.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ Every table goes through two distinct phases:

| Phase | What happens | Relevant parameter |
|-------|--------------|--------------------|
| **1 — Staging load** | CSV is streamed into a temporary UNLOGGED staging table. On PostgreSQL the native `COPY` command is used (fast path); ORM/pandas chunked inserts are a fallback. | `--staging-chunk-size` *(fallback only)* |
| **1 — Staging load** | The file is read in batches, converted, and written to a temporary staging table with the fastest bulk interface of the backend (`COPY` on PostgreSQL). | none |
| **2 — Merge** | Rows are moved from staging → target. With `--bulk-mode`, indexes are already dropped and FK triggers disabled for the duration of the full load. | `--merge-batch-size` |

## Pagination and why it is disabled by default
Expand Down Expand Up @@ -104,20 +104,16 @@ Leave unset for the fastest load on a system with sufficient RAM. Set to a posit
--merge-batch-size 5_000_000 # ~11 batches for concept_relationship; adds ~15 min overhead
```

### `--staging-chunk-size`

Controls ORM/pandas batch size for the CSV → staging phase. **Irrelevant on PostgreSQL** when the `COPY` fast-path is active (the default for well-formed Athena CSVs). Only tune this if you see `COPY` errors in the load output. Default: 100,000.

## Recommended invocation

```bash
omop-alchemy load-vocab-source \
--athena-source /path/to/omop_vocab/ \
--merge-strategy insert_if_empty \
--merge-strategy insert \
--bulk-mode
```

`--merge-strategy insert_if_empty` is the fastest strategy for a fresh (empty) database — it skips the delete phase entirely. `--bulk-mode` drops all indexes and disables FK triggers globally before loading and rebuilds after, which is much faster than per-table management for a full reload.
`--merge-strategy insert` is the fastest strategy for a fresh (empty) database. It skips the delete phase and the key check, so a key that already exists fails. `--bulk-mode` drops all indexes and disables FK triggers globally before loading and rebuilds after, which is much faster than per-table management for a full reload.

Pass `-vv` **before** the subcommand to see detailed progress from the orm-loader internals:

Expand Down
4 changes: 2 additions & 2 deletions docs/api/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ The result is a system that is:

flowchart BT
subgraph L0["orm-loader"]
L0a["CSVLoadableTableInterface"]
L0a["FileLoadableTableInterface"]
L0b["SerialisableTableInterface"]
L0c["Bulk load & casting helpers"]
L0d["Materialized-view lifecycle"]
Expand Down Expand Up @@ -86,7 +86,7 @@ flowchart BT

| Layer | Purpose | Responsibilities | Boundary and examples |
| --- | --- | --- | --- |
| **orm-loader (L0)** | Ingestion and infrastructure | CSV loading; bulk inserts; type casting; serialization; materialized-view definition and lifecycle operations | Domain-agnostic: it does not understand OMOP concepts, vocabularies, or clinical meaning. OMOP Alchemy may provide a selectable and logical row identity, while applications own view collections, dependency policy, and deployment. [CSVLoadableTableInterface](https://australiancancerdatanetwork.github.io/orm-loader/loaders/)<br>[SerialisableTableInterface](https://australiancancerdatanetwork.github.io/orm-loader/tables/serialisable_table/)<br>[Materialized views](https://australiancancerdatanetwork.github.io/orm-loader/tables/mat_view/) |
| **orm-loader (L0)** | Ingestion and infrastructure | File loading; bulk inserts; type casting; serialization; materialized-view definition and lifecycle operations | Domain-agnostic: it does not understand OMOP concepts, vocabularies, or clinical meaning. OMOP Alchemy may provide a selectable and logical row identity, while applications own view collections, dependency policy, and deployment. [FileLoadableTableInterface](https://australiancancerdatanetwork.github.io/orm-loader/loaders/)<br>[SerialisableTableInterface](https://australiancancerdatanetwork.github.io/orm-loader/tables/serialisable_table/)<br>[Materialized views](https://australiancancerdatanetwork.github.io/orm-loader/tables/mat_view/) |
| **cdm.base (L1)** | Structural OMOP semantics | Common table structure; required and optional column patterns; reusable mixins; reference relationship mechanics; domain validation primitives | Defines OMOP’s shape, not its analytical meaning. Answers: “What does a valid OMOP table look like?” [CDMTableBase](./base.md); [PersonScoped](./columns.md); [ReferenceContext](./relationships.md) |
| **cdm.models (L2)** | Concrete OMOP tables | Actual CDM tables; exact column layouts; primary and foreign keys; official OMOP schemas | Safe for ETL and bulk loading; avoids eager relationships and analytical helpers. Example: [Person](../models/clinical/person.md) |
| **Views & Contexts (L3)** | Navigation and analysis | Reference relationships; derived properties; hybrid expressions; query-friendly helpers | Designed for interactive use, not ingestion: *tables are for pipelines; views are for people.* [PersonContext](../models/clinical/person.md); [PersonView](../models/clinical/person.md) |
Expand Down
4 changes: 2 additions & 2 deletions docs/api/base.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ In OMOP Alchemy, a *base table* is:

- a concrete SQLAlchemy declarative class
- representing a real OMOP CDM table
- safe to load from CSV
- safe to load from files
- safe to serialize
- safe to validate structurally

Expand All @@ -39,7 +39,7 @@ Those concerns live elsewhere.

Specifically, it inherits:

- `CSVLoadableTableInterface` — controlled CSV ingestion
- `FileLoadableTableInterface` — controlled file ingestion
- `SerialisableTableInterface` — safe object serialization

This separation is intentional:
Expand Down
4 changes: 2 additions & 2 deletions docs/cli/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@ omop-alchemy --help
| `indexes disable` / `enable` / `cluster` | Drop or recreate ORM-defined secondary indexes; physically cluster tables on their designated index |
| `foreign-keys disable` / `enable` / `status` / `validate` | Manage PostgreSQL RI trigger enforcement |
| `fulltext install` / `populate` / `drop` | Manage tsvector sidecar columns on vocabulary tables |
| `backup-database` | Create a pg_dump backup artifact |
| `restore-database` | Restore a pg_dump or psql backup artifact |
| `backup-database` | Create a backup artifact (pg_dump on PostgreSQL, in-process on DuckDB) |
| `restore-database` | Restore a backup artifact created by `backup-database` |

See the [Command Reference](reference.md) for full parameter details.

Expand Down
19 changes: 11 additions & 8 deletions docs/cli/reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,11 +75,10 @@ Load Athena vocabulary CSVs from the configured source path into the target data
|---|---|---|---|
| `--athena-source` | str (optional) | (saved default) | Path to the unzipped Athena vocabulary CSV directory. Falls back to the saved athena-source default. |
| `--table` | str (repeatable, optional) | (none — all tables) | Restrict the load to one or more vocabulary tables by name (e.g. `--table concept --table vocabulary`). Skips the all-required-files preflight; errors if the named CSV is absent from the source directory. |
| `--merge-strategy` | `replace` / `upsert` / `insert_if_empty` | `replace` | `replace` overwrites rows whose primary keys occur in the source but preserves source-absent rows. `upsert` preserves existing rows on primary-key conflicts. `insert_if_empty` is the fast path for a fresh empty target. Truncate first when the database must exactly mirror the export. |
| `--quote-mode` | `by_delimiter` / `auto` / `csv` / `literal` | `by_delimiter` | Interpret double-quotes according to the delimiter by default: literal data in tab-delimited Athena files, RFC-4180 quoting in comma-delimited files. Use `csv` or `literal` only to force a mode; `auto` samples file content. |
| `--staging-chunk-size` | int (optional) | `100000` | [Phase 1] Rows per ORM transaction when loading CSV → staging table. Ignored when the PostgreSQL COPY fast-path is active. Pass `0` to disable chunking. |
| `--merge-strategy` | `replace` / `upsert` / `insert` | `replace` | `replace` overwrites rows whose primary keys occur in the source but preserves source-absent rows. `upsert` preserves existing rows on primary-key conflicts. `insert` adds the rows without checking keys: the fast path for a fresh empty target, and an existing key fails. Truncate first when the database must exactly mirror the export. |
| `--quote-mode` | `by_delimiter` / `csv` / `literal` | `by_delimiter` | Interpret double-quotes according to the delimiter by default: literal data in tab-delimited Athena files, RFC-4180 quoting in comma-delimited files. Use `csv` or `literal` only to force a mode. |
| `--bulk-mode` / `--no-bulk-mode` | bool | `True` | Disable FK triggers and drop indexes globally before loading, then rebuild after. Much faster for a full vocabulary reload. Ignored on backends that do not support it. |
| `--merge-batch-size` | int (optional) | `None` | [Phase 2] Rows per transaction when merging staging → target table. Default: `None` (single INSERT per table, fastest for high-RAM systems). Set to a positive integer to enable paginated commits for memory-constrained systems; note that pagination adds a COUNT query and an index build on the staging table before the merge begins. |
| `--merge-batch-size` | int (optional) | `None` | [Phase 2] Rows per transaction when merging staging → target table. Default: `None` (single INSERT per table, fastest for high-RAM systems). Set to a positive integer to enable paginated commits for memory-constrained systems; note that pagination adds a COUNT query and an index build on the staging table before the merge begins. If the load fails, rows from earlier batches stay committed on PostgreSQL and DuckDB. |
| `--dry-run` | bool | `False` | Preview planned actions without applying any changes to the database. |

---
Expand Down Expand Up @@ -264,8 +263,8 @@ Create a database backup that can be restored with `restore-database`.

| Flag | Type / Choices | Default | Description |
|---|---|---|---|
| `--output-path` | str (optional) | timestamped file in cwd | Output path for the backup artifact. Defaults to a timestamped file in the current directory. |
| `--format` | `custom` / `plain` | `custom` | pg_dump output format. `custom` produces a binary `.dump` file. `plain` produces a plain SQL `.sql` file. |
| `--output-path` | str (optional) | timestamped path in cwd | Output path for the backup artifact (a directory on DuckDB). Defaults to a timestamped path in the current directory. |
| `--format` | `custom` / `plain` | `custom` | pg_dump output format on PostgreSQL. `custom` produces a binary `.dump` file. `plain` produces a plain SQL `.sql` file. Ignored on DuckDB, which always backs up to a Parquet directory. |
| `--dry-run` | bool | `False` | Preview planned actions without applying any changes to the database. |

---
Expand All @@ -276,10 +275,14 @@ Restore a database backup that was created with `backup-database`.

| Argument / Flag | Type / Choices | Default | Description |
|---|---|---|---|
| `PATH` (argument) | str | (required) | Path to the backup artifact (`.dump` or `.sql`) to restore. |
| `--format` | `custom` / `plain` | (required) | Format of the artifact to restore. Must match the format used when the backup was created. |
| `PATH` (argument) | str | (required) | Path to the backup artifact to restore (`.dump`/`.sql` file, or a Parquet directory on DuckDB). |
| `--format` | `custom` / `plain` | (required) | Format of the artifact to restore on PostgreSQL; must match the format used when the backup was created. Ignored on DuckDB. |
| `--dry-run` | bool | `False` | Preview planned actions without applying any changes to the database. |


!!! note
On DuckDB, each target table must already exist (e.g. via `create-missing-tables`); restore loads row data only and resets owned sequences afterward.

---

## Configuration
Expand Down
Loading
Loading