@assemora/database 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Assemora
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
202
+
package/README.md ADDED
@@ -0,0 +1,163 @@
1
+ # `@assemora/database`
2
+
3
+ Abstract database adapter contracts and Query AST execution.
4
+
5
+ **Implementation phase:** 3 — shipped early, in phase 2.
6
+
7
+ The Query AST (SPEC.md §30) and the adapter contract (SPEC.md §31) live here. They
8
+ are the stable boundary between the data layer, database adapters, the policy layer
9
+ and the AI query layer, and nothing in this package is specific to any engine.
10
+
11
+ ```ts
12
+ const adapter = createMemoryAdapter({ users: [{ id: 'u1', active: true }] })
13
+
14
+ await adapter.execute(
15
+ { model: 'users', operation: 'select', where: [comparison('active', '=', true)], order: [], with: [] },
16
+ { table: usersDescriptor },
17
+ )
18
+ ```
19
+
20
+ The in-memory adapter implements the same contract as `@assemora/database-postgres`,
21
+ so a query proven in a unit test runs unchanged against PostgreSQL. It is for tests
22
+ and development only — nothing it holds is durable.
23
+
24
+ Every relation kind is loaded in batches, `belongsToMany` included: one pass over the
25
+ join table and one over the target, however many rows are being loaded for, and the
26
+ same again per nested hop. `adapter.diagnostics.scanCount()` counts those passes — one
27
+ per table, the way `statementCount()` counts statements on the PostgreSQL adapter — so
28
+ an N+1 fails a test rather than waiting for a review (SPEC.md §89). What the two
29
+ adapters have to agree the load *means* is settled in
30
+ `tests/integration/adapter-conformance.test.ts` (ADR-0013).
31
+
32
+ A `belongsToMany` arrives ordered by the target's key, ascending, in both adapters. A
33
+ join table has no order of its own, so without a stated one the same query answers with
34
+ the same rows in different orders and `user.roles[0]` means one thing in a unit test and
35
+ another in production. Every other kind carries whatever order its rows came back in;
36
+ `order` in the Query AST sorts the rows a query selects, not the rows hanging off them.
37
+
38
+ ## Join tables
39
+
40
+ `belongsToMany` is the one relation that stores nothing on either table it links: the
41
+ pairs live in a third table no model declares (SPEC.md §23). The data layer writes to
42
+ it, the DDL creates it and the diff has to notice it arriving — so it is derived once,
43
+ here, as an ordinary `TableDescriptor`.
44
+
45
+ ```ts
46
+ joinTableDescriptor(User.descriptor, roles, Role.descriptor)
47
+ // name: 'roles_users'
48
+ // columns: roleId, userId — both required, neither unique on its own
49
+ // uniqueTogether: [['roleId', 'userId']]
50
+ // relations: a belongsTo per side, so the table is created with real foreign keys
51
+ ```
52
+
53
+ The name comes from `through` when the relation declares one, and from the two table
54
+ names, sorted, when it does not. The columns are derived the way a `hasMany` foreign
55
+ key is — `users` gives `userId` — and `foreignPivotKey` / `relatedPivotKey` name them
56
+ where that does not fit. Everything is sorted before it is written down, so both
57
+ declarations of a mutual relation describe the *same* table, down to the order of the
58
+ columns: `users.roles` and `roles.users` are one join table, not two that disagree.
59
+
60
+ A relation whose target is its own table has to name both columns, because `userId`
61
+ twice is not a link; it is refused with an error that says so.
62
+
63
+ `withJoinTables(tables)` is the schema those tables really have — the declared ones
64
+ plus a join table per `belongsToMany`. It is idempotent, so expanding an expanded
65
+ schema adds nothing.
66
+
67
+ A model declared for a table a relation derives is **refused**, with an error naming
68
+ the relation and the table. Only the DDL would ever read such a model: the pivot verbs
69
+ of SPEC.md §24 write the two derived columns and nothing else, so a pivot carrying a
70
+ surrogate key or a `joinedAt` is a table `attach` cannot fill, and one carrying exactly
71
+ the two keys is a second descriptor for a name the adapter already builds. A pivot with
72
+ columns of its own is a model like any other — declare it with two `belongsTo`
73
+ relations and address it as an ordinary table, rather than pointing `through` at it.
74
+
75
+ ```ts
76
+ // Refused: `assemora_user_roles` is derived, and `grantedAt` is a column no verb writes.
77
+ roles: belongsToMany(() => Role, { through: 'assemora_user_roles' })
78
+ ```
79
+
80
+ `pivotAddress(owner, relation, row)` is how the data layer addresses the table for one
81
+ row. It answers with the join table, the two column names and the owner's key value —
82
+ enough to write the pivot verbs of SPEC.md §24 as ordinary Query AST, with no
83
+ operation and no adapter method of their own.
84
+
85
+ ```ts
86
+ const pivot = pivotAddress(User.descriptor, roles, user.toJSON(), Role.descriptor)
87
+
88
+ // attach
89
+ await adapter.execute(
90
+ {
91
+ ...emptyQuery(pivot.table.name, 'insert'),
92
+ data: { [pivot.ownerColumn]: pivot.ownerValue, [pivot.relatedColumn]: roleId },
93
+ },
94
+ { table: pivot.table },
95
+ )
96
+
97
+ // detach
98
+ await adapter.execute(
99
+ {
100
+ ...emptyQuery(pivot.table.name, 'delete'),
101
+ where: [
102
+ comparison(pivot.ownerColumn, '=', pivot.ownerValue),
103
+ comparison(pivot.relatedColumn, '=', roleId),
104
+ ],
105
+ },
106
+ { table: pivot.table },
107
+ )
108
+ ```
109
+
110
+ A join table has no key of its own — the pair is its identity — so its `primaryKey` is
111
+ empty and `uniqueTogether` carries the constraint. That is the one thing a generator
112
+ has to read that a model table never sets.
113
+
114
+ ## Schema diffing
115
+
116
+ `diffSchema(before, after)` says what has to happen for one set of table descriptors
117
+ to become another (SPEC.md §34). It is pure, it holds no SQL and it knows no dialect:
118
+ whether a column can still hold what it held is a property of the types, so the answer
119
+ belongs beside the descriptors every adapter already shares.
120
+
121
+ ```ts
122
+ // Both sides are descriptors the framework produced: the snapshot of the last
123
+ // generated schema, and the model registry as it stands now (ADR-0021).
124
+ const diff = diffSchema(snapshot.tables, declaredTables)
125
+
126
+ if (isDestructive(diff)) {
127
+ for (const change of diff.changes) {
128
+ if (change.destructive) console.warn(describeChange(change)) // "drops column articles.subtitle"
129
+ }
130
+ }
131
+ ```
132
+
133
+ Both sides are expanded with `withJoinTables` first, so a model that gains a
134
+ `belongsToMany` gains a table in the diff and one that loses it loses the table —
135
+ `db:generate` writes the join table without knowing what a join table is. The
136
+ expansion is idempotent, so a snapshot that already holds one still compares clean.
137
+
138
+ `SchemaChange` is a discriminated union a generator exhausts with a `switch` and no
139
+ default case, so a new kind of change is a compile error everywhere it has to be
140
+ handled. Every change carries `before`, `after` or both — enough to write the up and
141
+ the down migration without reading the descriptors again — and answers the two risk
142
+ questions `isDestructive` and `mayFailOnExistingRows` ask over the whole diff.
143
+
144
+ The two questions are different ones. `isDestructive` asks whether applying the diff
145
+ may lose data no later migration can bring back; `mayFailOnExistingRows` asks whether
146
+ a table that already holds rows may refuse it — an `add column ... not null`, a
147
+ narrowing that a stored value does not fit, a unique constraint the rows already
148
+ break. A model default does not answer the second: defaults are applied by the data
149
+ layer on insert and never reach the schema (ADR-0011), so a required column arrives
150
+ with nothing to put in the rows that are already there.
151
+
152
+ **`introspect()` is not a `before`.** A diff is taken against the generated snapshot
153
+ rather than the live database (ADR-0021), and today it has to be: `introspect()`
154
+ reports `relations: []` and maps an enum column back to the `text` PostgreSQL stores
155
+ it as, so comparing it with the registry reports a foreign key added and a
156
+ `text -> enum` change for every relation and every enum column, on every run. Drift
157
+ against a real database belongs in `assemora db:status`, and needs an introspection
158
+ that reads constraints first.
159
+
160
+ ## Workspace dependencies
161
+
162
+ - `@assemora/schema`
163
+ - `@assemora/core`
@@ -0,0 +1,133 @@
1
+ /**
2
+ * The database contract (SPEC.md §31).
3
+ *
4
+ * Nothing PostgreSQL-specific appears here. `@assemora/database-postgres` implements
5
+ * these interfaces with Drizzle inside, and no other package ever learns that
6
+ * (SPEC.md §32, §125.1).
7
+ */
8
+ import type { AssemoraContext } from '@assemora/core';
9
+ import type { QueryAst } from './query-ast.js';
10
+ export type ColumnType = 'uuid' | 'string' | 'text' | 'integer' | 'bigint' | 'number' | 'decimal' | 'boolean' | 'date' | 'timestamp' | 'json' | 'enum' | 'binary';
11
+ export type ColumnDescriptor = {
12
+ readonly name: string;
13
+ readonly type: ColumnType;
14
+ readonly isPrimary: boolean;
15
+ readonly isNullable: boolean;
16
+ readonly isUnique: boolean;
17
+ readonly isIndexed: boolean;
18
+ readonly hasDefault: boolean;
19
+ readonly enumValues?: readonly string[];
20
+ };
21
+ export type RelationKind = 'belongsTo' | 'hasOne' | 'hasMany' | 'belongsToMany';
22
+ export type RelationDescriptor = {
23
+ readonly name: string;
24
+ readonly kind: RelationKind;
25
+ /** The table on the other side. */
26
+ readonly target: string;
27
+ /**
28
+ * The column holding the reference: on this table for `belongsTo`, on the target's
29
+ * for `hasOne` and `hasMany`. A `belongsToMany` stores no reference on either table
30
+ * — its two columns live in the join table and are named below.
31
+ */
32
+ readonly foreignKey: string;
33
+ /** The column the reference points at: the owner's key, except for `belongsTo`. */
34
+ readonly ownerKey: string;
35
+ /** Join table, for `belongsToMany` only. Derived from the two table names when omitted. */
36
+ readonly through?: string;
37
+ /**
38
+ * The join table column holding this side's key, for `belongsToMany` only.
39
+ * Derived from this table's name when omitted (`joinTableDescriptor`).
40
+ */
41
+ readonly foreignPivotKey?: string;
42
+ /** The join table column holding the target's key, for `belongsToMany` only. */
43
+ readonly relatedPivotKey?: string;
44
+ };
45
+ export type TableDescriptor = {
46
+ readonly name: string;
47
+ readonly columns: readonly ColumnDescriptor[];
48
+ /**
49
+ * The single column that identifies a row, or empty where nothing does. A join
50
+ * table is identified by its pair of keys, and `uniqueTogether` is what says so.
51
+ */
52
+ readonly primaryKey: string;
53
+ readonly relations: readonly RelationDescriptor[];
54
+ readonly softDeleteColumn?: string;
55
+ /**
56
+ * Groups of columns unique together, one constraint each.
57
+ *
58
+ * A different claim from `ColumnDescriptor.isUnique`, which says a column is unique
59
+ * on its own: a join table's two keys each repeat freely and only the pair may not
60
+ * (SPEC.md §24).
61
+ */
62
+ readonly uniqueTogether?: readonly (readonly string[])[];
63
+ /**
64
+ * Whether this table holds one row per language (SPEC.md §131).
65
+ *
66
+ * Carried on the descriptor rather than inferred from the presence of a `locale`
67
+ * column, because a column called `locale` is a perfectly ordinary thing for an
68
+ * application to declare — a log of what language somebody chose, say — and a read
69
+ * silently scoped to it would be a filter nobody wrote.
70
+ */
71
+ readonly translatable?: boolean;
72
+ /**
73
+ * The column a write stamps with the time, where the model declares one.
74
+ *
75
+ * Carried like `softDeleteColumn`, and for a reader rather than for a writer: the data
76
+ * layer already knows which column `timestamp().updated()` made, and this is how a
77
+ * layer above finds out. It is what makes "this translation is older than the entry it
78
+ * translates" answerable without a column of its own (SPEC.md §131).
79
+ */
80
+ readonly updatedAtColumn?: string;
81
+ };
82
+ /**
83
+ * The two columns a translatable model carries (SPEC.md §131).
84
+ *
85
+ * Named here rather than spelled out in each layer that has to recognise them: the data
86
+ * layer declares them, the schema diff has to know that a table gaining `locale` is a
87
+ * table becoming translatable, and the SQL writer has to know what to backfill it with.
88
+ * Three spellings of one name is how the three come to disagree.
89
+ */
90
+ export declare const LOCALE_COLUMN = "locale";
91
+ export declare const TRANSLATION_OF_COLUMN = "translationOf";
92
+ /**
93
+ * What `locale` holds on a row written by a deployment that names no languages.
94
+ *
95
+ * A translatable model has to work in an application that serves one language — the
96
+ * framework ships one, `assemora_pages`, and SPEC.md §9 and §124 both write out the
97
+ * whole configuration of an application without a word about locales. So the column
98
+ * cannot demand a code nobody has chosen.
99
+ *
100
+ * The empty string says exactly that: this row is in the deployment's own language,
101
+ * whichever that turns out to be. Which is why a read of the *default* language matches
102
+ * it too — a page written before a site had languages belongs to the language it was
103
+ * written in, and that is the default. Without that rule, configuring locales on an
104
+ * existing project would make every row disappear.
105
+ */
106
+ export declare const UNSPECIFIED_LOCALE = "";
107
+ export type DatabaseSchema = {
108
+ readonly tables: readonly TableDescriptor[];
109
+ };
110
+ export type DatabaseContext = {
111
+ readonly table: TableDescriptor;
112
+ /** The ambient application context, for logging and auditing (SPEC.md §12). */
113
+ readonly context?: AssemoraContext;
114
+ /** Tables the query loads relations from, keyed by table name. */
115
+ readonly related?: Readonly<Record<string, TableDescriptor>>;
116
+ };
117
+ export type DatabaseAdapter = {
118
+ /**
119
+ * Runs a query.
120
+ *
121
+ * One failure is part of the contract rather than left to the engine: a query
122
+ * against a table that has not been created yet must reject with
123
+ * `schemaNotApplied()` from `./errors.js`, distinct from every other refusal. An
124
+ * application has to be able to boot against an unapplied schema — that is what
125
+ * `assemora db:generate` does to read the registry (ADR-0021) — and the boot hook
126
+ * that survives it may not depend on this package, let alone on an engine, to tell
127
+ * a missing table from a database that refused it.
128
+ */
129
+ execute<T>(query: QueryAst, context: DatabaseContext): Promise<T>;
130
+ transaction<T>(callback: () => Promise<T>): Promise<T>;
131
+ introspect(): Promise<DatabaseSchema>;
132
+ };
133
+ //# sourceMappingURL=adapter.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"adapter.d.ts","sourceRoot":"","sources":["../src/adapter.ts"],"names":[],"mappings":"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"}
@@ -0,0 +1,26 @@
1
+ /**
2
+ * The two columns a translatable model carries (SPEC.md §131).
3
+ *
4
+ * Named here rather than spelled out in each layer that has to recognise them: the data
5
+ * layer declares them, the schema diff has to know that a table gaining `locale` is a
6
+ * table becoming translatable, and the SQL writer has to know what to backfill it with.
7
+ * Three spellings of one name is how the three come to disagree.
8
+ */
9
+ export const LOCALE_COLUMN = 'locale';
10
+ export const TRANSLATION_OF_COLUMN = 'translationOf';
11
+ /**
12
+ * What `locale` holds on a row written by a deployment that names no languages.
13
+ *
14
+ * A translatable model has to work in an application that serves one language — the
15
+ * framework ships one, `assemora_pages`, and SPEC.md §9 and §124 both write out the
16
+ * whole configuration of an application without a word about locales. So the column
17
+ * cannot demand a code nobody has chosen.
18
+ *
19
+ * The empty string says exactly that: this row is in the deployment's own language,
20
+ * whichever that turns out to be. Which is why a read of the *default* language matches
21
+ * it too — a page written before a site had languages belongs to the language it was
22
+ * written in, and that is the default. Without that rule, configuring locales on an
23
+ * existing project would make every row disappear.
24
+ */
25
+ export const UNSPECIFIED_LOCALE = '';
26
+ //# sourceMappingURL=adapter.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"adapter.js","sourceRoot":"","sources":["../src/adapter.ts"],"names":[],"mappings":"AAqGA;;;;;;;GAOG;AACH,MAAM,CAAC,MAAM,aAAa,GAAG,QAAQ,CAAA;AACrC,MAAM,CAAC,MAAM,qBAAqB,GAAG,eAAe,CAAA;AAEpD;;;;;;;;;;;;;GAaG;AACH,MAAM,CAAC,MAAM,kBAAkB,GAAG,EAAE,CAAA"}
@@ -0,0 +1,48 @@
1
+ /**
2
+ * The one database failure a caller above is allowed to survive (SPEC.md §31, §83).
3
+ *
4
+ * A unique violation, a bad value, a deadlock: those are things a caller did, and an
5
+ * adapter reports each of them under a code of its own so the layer above can say
6
+ * whose mistake it was. This file is for the failure nobody made — the table is not
7
+ * there yet, because the migrations have not been run.
8
+ *
9
+ * It has to be told apart from every other way a database can refuse, because an
10
+ * application must be able to boot against a schema that is not applied yet: that is
11
+ * exactly what `assemora db:generate` does when it imports the project's application
12
+ * to read its registry (ADR-0021), and a boot hook that reads a table would otherwise
13
+ * need the table its own migration is about to create. "The table does not exist",
14
+ * "the database refused the connection" and "permission denied" arriving as one code
15
+ * would make that boot indistinguishable from a broken deployment.
16
+ *
17
+ * The distinction lives here rather than in an adapter because it is part of the
18
+ * adapter *contract*: the caller that survives it is `@assemora/resources`, which may
19
+ * not learn PostgreSQL to ask the question (SPEC.md §8), and an adapter that reported
20
+ * a missing table the way it reports a refused connection would make the invariant
21
+ * unimplementable for everybody above.
22
+ */
23
+ import { AssemoraError } from '@assemora/core';
24
+ /**
25
+ * The code every adapter must report a missing table under.
26
+ *
27
+ * Exported as a constant because an `AssemoraError` code is a public contract — it
28
+ * travels to a REST client through `toPayload()` — and a caller too far up the
29
+ * dependency graph to import this file compares the string instead.
30
+ */
31
+ export declare const SCHEMA_NOT_APPLIED = "SCHEMA_NOT_APPLIED";
32
+ /**
33
+ * "This table has not been created yet", with the remedy in the sentence.
34
+ *
35
+ * 503 rather than 500: nothing went wrong handling the request, the deployment is
36
+ * unfinished. It is still an incident — SPEC.md §88 reports everything at 500 and
37
+ * above — because an application serving in this state answers nothing correctly.
38
+ */
39
+ export declare const schemaNotApplied: (table: string | undefined, cause?: unknown) => AssemoraError;
40
+ /**
41
+ * Whether a failure was a missing table and nothing else.
42
+ *
43
+ * The one question a boot hook is allowed to ask before carrying on. Everything else
44
+ * — a refused connection, a database that does not exist, a privilege the user was
45
+ * never granted — answers `false` here and stops the boot, which is the point.
46
+ */
47
+ export declare const isSchemaNotApplied: (error: unknown) => error is AssemoraError;
48
+ //# sourceMappingURL=errors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,OAAO,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAA;AAE9C;;;;;;GAMG;AACH,eAAO,MAAM,kBAAkB,uBAAuB,CAAA;AAEtD;;;;;;GAMG;AACH,eAAO,MAAM,gBAAgB,UAAW,MAAM,GAAG,SAAS,UAAU,OAAO,KAAG,aAW3E,CAAA;AAEH;;;;;;GAMG;AACH,eAAO,MAAM,kBAAkB,UAAW,OAAO,KAAG,KAAK,IAAI,aACQ,CAAA"}
package/dist/errors.js ADDED
@@ -0,0 +1,54 @@
1
+ /**
2
+ * The one database failure a caller above is allowed to survive (SPEC.md §31, §83).
3
+ *
4
+ * A unique violation, a bad value, a deadlock: those are things a caller did, and an
5
+ * adapter reports each of them under a code of its own so the layer above can say
6
+ * whose mistake it was. This file is for the failure nobody made — the table is not
7
+ * there yet, because the migrations have not been run.
8
+ *
9
+ * It has to be told apart from every other way a database can refuse, because an
10
+ * application must be able to boot against a schema that is not applied yet: that is
11
+ * exactly what `assemora db:generate` does when it imports the project's application
12
+ * to read its registry (ADR-0021), and a boot hook that reads a table would otherwise
13
+ * need the table its own migration is about to create. "The table does not exist",
14
+ * "the database refused the connection" and "permission denied" arriving as one code
15
+ * would make that boot indistinguishable from a broken deployment.
16
+ *
17
+ * The distinction lives here rather than in an adapter because it is part of the
18
+ * adapter *contract*: the caller that survives it is `@assemora/resources`, which may
19
+ * not learn PostgreSQL to ask the question (SPEC.md §8), and an adapter that reported
20
+ * a missing table the way it reports a refused connection would make the invariant
21
+ * unimplementable for everybody above.
22
+ */
23
+ import { AssemoraError } from '@assemora/core';
24
+ /**
25
+ * The code every adapter must report a missing table under.
26
+ *
27
+ * Exported as a constant because an `AssemoraError` code is a public contract — it
28
+ * travels to a REST client through `toPayload()` — and a caller too far up the
29
+ * dependency graph to import this file compares the string instead.
30
+ */
31
+ export const SCHEMA_NOT_APPLIED = 'SCHEMA_NOT_APPLIED';
32
+ /**
33
+ * "This table has not been created yet", with the remedy in the sentence.
34
+ *
35
+ * 503 rather than 500: nothing went wrong handling the request, the deployment is
36
+ * unfinished. It is still an incident — SPEC.md §88 reports everything at 500 and
37
+ * above — because an application serving in this state answers nothing correctly.
38
+ */
39
+ export const schemaNotApplied = (table, cause) => new AssemoraError(SCHEMA_NOT_APPLIED, table === undefined
40
+ ? 'A table this application needs does not exist. Run "assemora db:migrate" to apply the migrations for this project.'
41
+ : `The table "${table}" does not exist. Run "assemora db:migrate" to apply the migrations for this project.`, {
42
+ status: 503,
43
+ ...(table === undefined ? {} : { details: { table } }),
44
+ cause,
45
+ });
46
+ /**
47
+ * Whether a failure was a missing table and nothing else.
48
+ *
49
+ * The one question a boot hook is allowed to ask before carrying on. Everything else
50
+ * — a refused connection, a database that does not exist, a privilege the user was
51
+ * never granted — answers `false` here and stops the boot, which is the point.
52
+ */
53
+ export const isSchemaNotApplied = (error) => error instanceof AssemoraError && error.code === SCHEMA_NOT_APPLIED;
54
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.js","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,OAAO,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAA;AAE9C;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,kBAAkB,GAAG,oBAAoB,CAAA;AAEtD;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAAC,KAAyB,EAAE,KAAe,EAAiB,EAAE,CAC5F,IAAI,aAAa,CACf,kBAAkB,EAClB,KAAK,KAAK,SAAS;IACjB,CAAC,CAAC,oHAAoH;IACtH,CAAC,CAAC,cAAc,KAAK,uFAAuF,EAC9G;IACE,MAAM,EAAE,GAAG;IACX,GAAG,CAAC,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,EAAE,KAAK,EAAE,EAAE,CAAC;IACtD,KAAK;CACN,CACF,CAAA;AAEH;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,kBAAkB,GAAG,CAAC,KAAc,EAA0B,EAAE,CAC3E,KAAK,YAAY,aAAa,IAAI,KAAK,CAAC,IAAI,KAAK,kBAAkB,CAAA"}