dsqlbase 0.1.6 → 0.2.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.
Files changed (208) hide show
  1. package/CHANGELOG.md +201 -0
  2. package/LICENSE +21 -0
  3. package/README.md +206 -2
  4. package/dist/client/create.d.ts +24 -4
  5. package/dist/client/create.d.ts.map +1 -1
  6. package/dist/client/create.js +21 -9
  7. package/dist/client/create.js.map +1 -1
  8. package/dist/client/database/base.d.ts +92 -1
  9. package/dist/client/database/base.d.ts.map +1 -1
  10. package/dist/client/database/base.js +196 -1
  11. package/dist/client/database/base.js.map +1 -1
  12. package/dist/client/database/client.d.ts +21 -5
  13. package/dist/client/database/client.d.ts.map +1 -1
  14. package/dist/client/database/client.js +39 -1
  15. package/dist/client/database/client.js.map +1 -1
  16. package/dist/client/database/index.d.ts +60 -4
  17. package/dist/client/database/index.d.ts.map +1 -1
  18. package/dist/client/database/index.js.map +1 -1
  19. package/dist/client/index.d.ts +4 -2
  20. package/dist/client/index.d.ts.map +1 -1
  21. package/dist/client/index.js +4 -2
  22. package/dist/client/index.js.map +1 -1
  23. package/dist/client/model/base.d.ts +553 -136
  24. package/dist/client/model/base.d.ts.map +1 -1
  25. package/dist/client/model/base.js +1 -6
  26. package/dist/client/model/base.js.map +1 -1
  27. package/dist/client/model/client.d.ts +45 -8
  28. package/dist/client/model/client.d.ts.map +1 -1
  29. package/dist/client/model/client.js +58 -2
  30. package/dist/client/model/client.js.map +1 -1
  31. package/dist/client/model/filters.d.ts +276 -0
  32. package/dist/client/model/filters.d.ts.map +1 -0
  33. package/dist/client/model/filters.js +470 -0
  34. package/dist/client/model/filters.js.map +1 -0
  35. package/dist/client/model/normalizer.d.ts +127 -3
  36. package/dist/client/model/normalizer.d.ts.map +1 -1
  37. package/dist/client/model/normalizer.js +526 -106
  38. package/dist/client/model/normalizer.js.map +1 -1
  39. package/dist/client/nodes.d.ts +62 -0
  40. package/dist/client/nodes.d.ts.map +1 -0
  41. package/dist/client/nodes.js +378 -0
  42. package/dist/client/nodes.js.map +1 -0
  43. package/dist/client/pagination/cursor.d.ts +40 -0
  44. package/dist/client/pagination/cursor.d.ts.map +1 -0
  45. package/dist/client/pagination/cursor.js +79 -0
  46. package/dist/client/pagination/cursor.js.map +1 -0
  47. package/dist/client/pagination/page.d.ts +23 -0
  48. package/dist/client/pagination/page.d.ts.map +1 -0
  49. package/dist/client/pagination/page.js +37 -0
  50. package/dist/client/pagination/page.js.map +1 -0
  51. package/dist/client/transaction/index.js.map +1 -1
  52. package/dist/client/transaction/occ-retry.d.ts +2 -2
  53. package/dist/client/transaction/occ-retry.d.ts.map +1 -1
  54. package/dist/client/transaction/occ-retry.js.map +1 -1
  55. package/dist/client/transaction/transaction-client.d.ts +4 -6
  56. package/dist/client/transaction/transaction-client.d.ts.map +1 -1
  57. package/dist/client/transaction/transaction-client.js +7 -18
  58. package/dist/client/transaction/transaction-client.js.map +1 -1
  59. package/dist/client/union/client.d.ts +55 -0
  60. package/dist/client/union/client.d.ts.map +1 -0
  61. package/dist/client/union/client.js +74 -0
  62. package/dist/client/union/client.js.map +1 -0
  63. package/dist/index.d.ts +5 -2
  64. package/dist/index.d.ts.map +1 -1
  65. package/dist/index.js +5 -2
  66. package/dist/index.js.map +1 -1
  67. package/dist/pg/index.d.ts +13 -1
  68. package/dist/pg/index.d.ts.map +1 -1
  69. package/dist/pg/index.js +52 -5
  70. package/dist/pg/index.js.map +1 -1
  71. package/dist/pglite/index.d.ts +7 -6
  72. package/dist/pglite/index.d.ts.map +1 -1
  73. package/dist/pglite/index.js +18 -4
  74. package/dist/pglite/index.js.map +1 -1
  75. package/dist/schema/columns/array.d.ts +12 -8
  76. package/dist/schema/columns/array.d.ts.map +1 -1
  77. package/dist/schema/columns/array.js +11 -14
  78. package/dist/schema/columns/array.js.map +1 -1
  79. package/dist/schema/columns/bigint.d.ts +1 -1
  80. package/dist/schema/columns/bigint.d.ts.map +1 -1
  81. package/dist/schema/columns/bigint.js +1 -0
  82. package/dist/schema/columns/bigint.js.map +1 -1
  83. package/dist/schema/columns/boolean.d.ts +1 -1
  84. package/dist/schema/columns/boolean.d.ts.map +1 -1
  85. package/dist/schema/columns/boolean.js +1 -0
  86. package/dist/schema/columns/boolean.js.map +1 -1
  87. package/dist/schema/columns/bytea.d.ts +1 -1
  88. package/dist/schema/columns/bytea.d.ts.map +1 -1
  89. package/dist/schema/columns/bytea.js +1 -0
  90. package/dist/schema/columns/bytea.js.map +1 -1
  91. package/dist/schema/columns/char.d.ts +1 -1
  92. package/dist/schema/columns/char.d.ts.map +1 -1
  93. package/dist/schema/columns/char.js +1 -0
  94. package/dist/schema/columns/char.js.map +1 -1
  95. package/dist/schema/columns/date.d.ts +3 -3
  96. package/dist/schema/columns/date.d.ts.map +1 -1
  97. package/dist/schema/columns/date.js +1 -0
  98. package/dist/schema/columns/date.js.map +1 -1
  99. package/dist/schema/columns/double.d.ts +1 -1
  100. package/dist/schema/columns/double.d.ts.map +1 -1
  101. package/dist/schema/columns/double.js +1 -0
  102. package/dist/schema/columns/double.js.map +1 -1
  103. package/dist/schema/columns/guid.d.ts +57 -0
  104. package/dist/schema/columns/guid.d.ts.map +1 -0
  105. package/dist/schema/columns/guid.js +53 -0
  106. package/dist/schema/columns/guid.js.map +1 -0
  107. package/dist/schema/columns/identity.d.ts +6 -6
  108. package/dist/schema/columns/identity.d.ts.map +1 -1
  109. package/dist/schema/columns/identity.js +2 -0
  110. package/dist/schema/columns/identity.js.map +1 -1
  111. package/dist/schema/columns/int.d.ts +1 -1
  112. package/dist/schema/columns/int.d.ts.map +1 -1
  113. package/dist/schema/columns/int.js +1 -0
  114. package/dist/schema/columns/int.js.map +1 -1
  115. package/dist/schema/columns/interval.d.ts +4 -3
  116. package/dist/schema/columns/interval.d.ts.map +1 -1
  117. package/dist/schema/columns/interval.js +1 -0
  118. package/dist/schema/columns/interval.js.map +1 -1
  119. package/dist/schema/columns/json.d.ts +79 -2
  120. package/dist/schema/columns/json.d.ts.map +1 -1
  121. package/dist/schema/columns/json.js +158 -8
  122. package/dist/schema/columns/json.js.map +1 -1
  123. package/dist/schema/columns/numeric.d.ts +20 -3
  124. package/dist/schema/columns/numeric.d.ts.map +1 -1
  125. package/dist/schema/columns/numeric.js +60 -4
  126. package/dist/schema/columns/numeric.js.map +1 -1
  127. package/dist/schema/columns/real.d.ts +1 -1
  128. package/dist/schema/columns/real.d.ts.map +1 -1
  129. package/dist/schema/columns/real.js +1 -0
  130. package/dist/schema/columns/real.js.map +1 -1
  131. package/dist/schema/columns/record.d.ts +20 -0
  132. package/dist/schema/columns/record.d.ts.map +1 -0
  133. package/dist/schema/columns/record.js +21 -0
  134. package/dist/schema/columns/record.js.map +1 -0
  135. package/dist/schema/columns/smallint.d.ts +1 -1
  136. package/dist/schema/columns/smallint.d.ts.map +1 -1
  137. package/dist/schema/columns/smallint.js +1 -0
  138. package/dist/schema/columns/smallint.js.map +1 -1
  139. package/dist/schema/columns/text.d.ts +1 -1
  140. package/dist/schema/columns/text.d.ts.map +1 -1
  141. package/dist/schema/columns/text.js +1 -0
  142. package/dist/schema/columns/text.js.map +1 -1
  143. package/dist/schema/columns/time.d.ts +3 -3
  144. package/dist/schema/columns/time.d.ts.map +1 -1
  145. package/dist/schema/columns/time.js +1 -0
  146. package/dist/schema/columns/time.js.map +1 -1
  147. package/dist/schema/columns/timestamp.d.ts +6 -6
  148. package/dist/schema/columns/timestamp.d.ts.map +1 -1
  149. package/dist/schema/columns/timestamp.js +1 -0
  150. package/dist/schema/columns/timestamp.js.map +1 -1
  151. package/dist/schema/columns/uuid.d.ts +1 -1
  152. package/dist/schema/columns/uuid.d.ts.map +1 -1
  153. package/dist/schema/columns/uuid.js +1 -0
  154. package/dist/schema/columns/uuid.js.map +1 -1
  155. package/dist/schema/columns/varchar.d.ts +1 -1
  156. package/dist/schema/columns/varchar.d.ts.map +1 -1
  157. package/dist/schema/columns/varchar.js +1 -0
  158. package/dist/schema/columns/varchar.js.map +1 -1
  159. package/dist/schema/domain.d.ts +2 -2
  160. package/dist/schema/domain.d.ts.map +1 -1
  161. package/dist/schema/domain.js +2 -0
  162. package/dist/schema/domain.js.map +1 -1
  163. package/dist/schema/embedded.d.ts +31 -0
  164. package/dist/schema/embedded.d.ts.map +1 -0
  165. package/dist/schema/embedded.js +33 -0
  166. package/dist/schema/embedded.js.map +1 -0
  167. package/dist/schema/index.d.ts +8 -1
  168. package/dist/schema/index.d.ts.map +1 -1
  169. package/dist/schema/index.js +6 -1
  170. package/dist/schema/index.js.map +1 -1
  171. package/dist/schema/namespace.js.map +1 -1
  172. package/dist/schema/relations.d.ts +17 -5
  173. package/dist/schema/relations.d.ts.map +1 -1
  174. package/dist/schema/relations.js +9 -0
  175. package/dist/schema/relations.js.map +1 -1
  176. package/dist/schema/sequence.js.map +1 -1
  177. package/dist/schema/table.d.ts +2 -2
  178. package/dist/schema/table.d.ts.map +1 -1
  179. package/dist/schema/table.js.map +1 -1
  180. package/dist/schema/tenant.d.ts +31 -0
  181. package/dist/schema/tenant.d.ts.map +1 -0
  182. package/dist/schema/tenant.js +33 -0
  183. package/dist/schema/tenant.js.map +1 -0
  184. package/dist/schema/union.d.ts +25 -0
  185. package/dist/schema/union.d.ts.map +1 -0
  186. package/dist/schema/union.js +27 -0
  187. package/dist/schema/union.js.map +1 -0
  188. package/dist/schema/utils/column-validation.d.ts +19 -0
  189. package/dist/schema/utils/column-validation.d.ts.map +1 -0
  190. package/dist/schema/utils/column-validation.js +37 -0
  191. package/dist/schema/utils/column-validation.js.map +1 -0
  192. package/dist/schema/utils/date.js.map +1 -1
  193. package/dist/schema/utils/duration.d.ts +2 -2
  194. package/dist/schema/utils/duration.d.ts.map +1 -1
  195. package/dist/schema/utils/duration.js.map +1 -1
  196. package/dist/schema/utils/global-id.d.ts +67 -0
  197. package/dist/schema/utils/global-id.d.ts.map +1 -0
  198. package/dist/schema/utils/global-id.js +99 -0
  199. package/dist/schema/utils/global-id.js.map +1 -0
  200. package/dist/schema/utils/standard-schema.d.ts +30 -0
  201. package/dist/schema/utils/standard-schema.d.ts.map +1 -0
  202. package/dist/schema/utils/standard-schema.js +2 -0
  203. package/dist/schema/utils/standard-schema.js.map +1 -0
  204. package/package.json +21 -16
  205. package/dist/schema/utils/json.d.ts +0 -2
  206. package/dist/schema/utils/json.d.ts.map +0 -1
  207. package/dist/schema/utils/json.js +0 -12
  208. package/dist/schema/utils/json.js.map +0 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,206 @@
1
1
  # dsqlbase
2
2
 
3
+ ## 0.2.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 2e0b361: Types and the model surface:
8
+ - **Relations split across several `relations()` blocks are typed;** a table with two blocks had no relation names at the type level, though its queries ran.
9
+ - **One model per table, under its schema alias.** A table exported as `members` but named `team_members` also appeared as `dsql.team_members` when the client was indexed dynamically; that duplicate is gone. `Table.alias` holds the alias.
10
+ - **Exported object types are `type` aliases,** so they can no longer be extended by declaration merging (`declare module "dsqlbase" { interface QueryArgs … }`).
11
+
12
+ **Breaking:** the two behaviour changes above.
13
+
14
+ Docs: docs/guide/relations.md, docs/internals/runtime-pipeline.md
15
+
16
+ - 2e0b361: Column writes:
17
+ - **`$onUpdate` runs on every update,** not only when the update also names its column, so `updatedAt.$onUpdate(() => new Date())` works on its own. A value the update sets still wins, and the hook's value is validated and encoded like any written value.
18
+ - **`numeric()` / `decimal()` take `{ precision, scale }`** and default to `numeric(18,6)` — what DSQL makes of a bare `numeric` — so Postgres and PGlite store the same type and DSQL no longer re-plans it. A value the column would round or overflow throws `ColumnValidationError` instead of being rounded silently.
19
+ - `identity(name, { sequenceName })` keeps the sequence name it is given.
20
+
21
+ **Breaking:** an update writes every column with an `$onUpdate` hook; a bare `numeric()` is `numeric(18,6)` on Postgres and PGlite; writes that would round a `numeric` now throw.
22
+
23
+ Docs: docs/guide/schema.md, docs/guide/dsql-notes.md
24
+
25
+ - 2e0b361: Embedded objects: `embedded({ amount, currency })` declares a reusable value object, and `.column("net_value")` places it in a table as a column group — one column per member (`net_value_amount`, …), each with its own type, codec, validator and `.notNull()`. Groups nest and take `.default(obj)`.
26
+ - **Reading:** a group reads as a nested object; `select` takes it as `true` or a map of its members. A group whose members are all nullable reads `null` when every column is `NULL`.
27
+ - **Writing:** `create` writes the members given, `update` only the members given, and `null` clears an all-nullable group.
28
+ - **Filtering and ordering:** a group takes `exists` and a nested `where` over its members; `orderBy` and `paginate` take a nested order per group.
29
+ - Constraint and index callbacks reach members as `c.netValue.amount`. Migrations see plain columns.
30
+
31
+ **Breaking,** for `@dsqlbase/core` callers: `Table.getColumn` returns a `Column` or a `ColumnGroup`, and table column maps accept groups.
32
+
33
+ Docs: docs/guide/embeddable-objects.md, docs/guide/schema.md, docs/guide/querying.md, docs/decisions/0013-embeddable-objects.md
34
+
35
+ - 2e0b361: Filters follow the column's type. Every column carries a runtime type — `string`, `uuid`, `number`, `bigint`, `boolean`, `date`, `interval`, `bytes`, `json`, `jsonb`, `array`, `object` — which decides the `where` operators it takes, whether a bare value means `eq`, and whether it can be an `orderBy` key. The types and the runtime follow the same table, so a refused operator also throws when the query is built, before any SQL runs.
36
+ - Several operators on one field all apply: `{ pages: { gte: 1, lte: 5 } }` used to keep only the first.
37
+ - Filter values go through the column's codec, as inserts and updates do, so a `Date`, a `bigint` or a `Duration` filters the way it is stored.
38
+ - `%` and `_` in `beginsWith`, `endsWith` and a string `contains` match themselves, not any text.
39
+ - `in: []` matches no row and `notIn: []` every row; both used to fail as SQL.
40
+ - An empty `where: {}`, an empty `and` / `or`, and an `or` with a `{}` branch filter nothing. `findOne`, `update` and `delete` refuse an empty `where`.
41
+
42
+ **Breaking:**
43
+ - `bytea` and `json` columns filter by `exists` only, and neither they nor `jsonb` columns can be ordered by; pattern operators are refused on non-string columns, and comparisons on `boolean`. These all built SQL Postgres rejects.
44
+ - An unknown operator throws, including an object naming only unknown ones (`{ assigneeId: { isNull: true } }`), which used to be compared as a value. A direction other than `"asc"` / `"desc"` in `orderBy` throws.
45
+ - A `%` or `_` in a pattern operator's value no longer acts as a wildcard.
46
+ - `@dsqlbase/core`: `ColumnConfig` and `DomainConfig` gain a `runtimeType` parameter. A custom `Session` now receives filter values encoded by the column's codec.
47
+
48
+ Docs: docs/guide/querying.md, docs/internals/codec-boundary.md
49
+
50
+ - 4433815: Global ids: an id that names its table as well as its row.
51
+ - **`guid(name, key?)`** (from `dsqlbase/schema`) is a `uuid` column whose values read back as `guid:<base64url>`. A table whose primary key is exactly one `guid()` column is a **node**, keyed by its schema alias. The second argument names the node a column points at — `guid("author_id", "authors")` makes `article.authorId` and `article.author.id` the same string. It serializes exactly as `uuid()`, so adopting it on an existing column changes no DDL.
52
+ - **Wrapped ids and raw uuids are both accepted** wherever the column is. An id naming another node throws `GlobalIdError("key_mismatch")` when the query is built.
53
+ - **`dsql.$findByGlobalId({ id, on? })`** reads the row an id names, or `null`. **`dsql.$listByGlobalId({ ids, on? })`** reads many — one query per table — in the order given, with `null` for a miss. Both go through the table's model client, so they carry the tenant predicate. Their rows carry a top-level `$$key` naming the node, which narrows the result type.
54
+ - `encodeGlobalId`, `decodeGlobalId`, `isGlobalId` and `GlobalIdError` are exported from the package root.
55
+
56
+ **Breaking:** `$$meta.key` is typed as the literal schema alias rather than `string`. Three schemas that used to build now throw when the client is created: two tables claiming one node key, a `guid()` column naming no node, and a relation whose two sides disagree about global ids.
57
+
58
+ Docs: docs/guide/global-ids.md, docs/guide/schema.md, docs/guide/relations.md, docs/decisions/0007-global-ids.md
59
+
60
+ - 2e0b361: JSON columns: `jsonb()`, `array()` and `record()`, validated by any Standard Schema.
61
+ - **`jsonb(name)`** holds any JSON value; `null` is SQL `NULL`. **`array(name)`** and **`record(name)`** are `jsonb` columns whose value must be an array or a plain object, checked on every write and read.
62
+ - **`.schema(s)`** on `json()`, `jsonb()`, `array()` and `record()` takes any Standard Schema (zod, valibot, arktype — none is a dependency). Writes validate and store the schema's output; reads validate and return it. A failure throws `ColumnValidationError` (`code`, `column`, `phase`, `issues`). `$type<T>()` types a column without validating.
63
+ - **Filters:** `jsonb`, `array` and `record` filter by `eq` / `neq` (whole documents), `contains` (`@>`, a fragment matched recursively; on an array, a list of item fragments) and `exists`; a record also by `hasKey` (`?`). `json` filters by `exists` only, as Postgres's `json` has no equality. `distinct` compares `jsonb`.
64
+ - **Validators** run beside a column's codec: `ColumnConfig.validator { write, read }` runs on every write (`.default()`, `$onCreate`, `$onUpdate` included) and every read; filter values are only encoded.
65
+ - **Fixed:** a JSON string such as `"123"` stored in a JSON column read back as the number `123`.
66
+
67
+ **Breaking:**
68
+ - `array()` is now `jsonb`, not comma-joined `text`, and untyped it reads as `unknown[]`. An existing `array()` column can't change type in place on DSQL; the migration refuses it.
69
+ - A custom `Session` must return `json` / `jsonb` columns parsed, as `pg` and PGlite do.
70
+ - `@dsqlbase/core`: `ColumnConfig` gains an `inputType` parameter; `.default()`, `$onCreate` and `$onUpdate` take the input type.
71
+
72
+ Docs: docs/guide/schema.md, docs/guide/querying.md, docs/internals/codec-boundary.md, docs/decisions/0011-json-columns.md, docs/decisions/0012-json-array-record.md
73
+
74
+ - 2e0b361: Rename and retire columns and tables without losing data.
75
+ - **`.renamedFrom("previous")`** on a column or a table makes the migration emit `RENAME` instead of a drop and an add. Constraints and indexes named after the old name are renamed with it. When both names exist, the rename is refused (`RENAME_CONFLICT`); once the database has the new name, the hint does nothing.
76
+ - **`.deprecated()`** on a column hides it from the client — results, filters, ordering and inputs, in the types and at runtime — and marks it in the database with the comment `dsqlbase:deprecated`, dropping its `NOT NULL` when it has no default. A table created with a column already deprecated gets the marker in the same run.
77
+ - **In a later release,** removing the column from the definition drops it as a **lossy** step, so it runs without `allow.destructive`.
78
+
79
+ A primary-key column or an embedded-object member can't be deprecated.
80
+
81
+ Docs: docs/guide/schema.md, docs/guide/migrations.md
82
+
83
+ - 2e0b361: Keyset pagination: `paginate()` and `count()` on every model.
84
+ - **`dsql.<model>.paginate({ select, where, orderBy, join, limit, after | before, count })`** reads one page under a total order — your `orderBy`, then every primary-key column you didn't name. It returns `{ items, hasNextPage, hasPreviousPage, startCursor, endCursor }`, each item's cursor at `$$meta.cursor`, and `totalCount` with `count: true`. A page read `before` a cursor comes back in forward order.
85
+ - **Order keys may be nullable.** Nulls sort where Postgres puts them by default — last ascending, first descending — and the `ORDER BY` states it, so pages don't depend on a server setting.
86
+ - **Cursors** carry each key as the database's own text, so microsecond timestamps and big integers page exactly. A cursor is valid only under the order it was taken with; anything else throws `InvalidCursorError` before any SQL runs.
87
+ - **`dsql.<model>.count({ where? })`** resolves to a number. Pages and counts go through the tenant predicate, so a cursor is never a way across tenants.
88
+ - **`createClient({ pagination: { defaultLimit, maxLimit } })`** — `defaultLimit` is 100; `maxLimit`, when set, refuses a larger `limit`. A `findMany` without `limit` still returns every row.
89
+ - **`$transaction([...])` accepts a counted page** (two statements) like any query. In `@dsqlbase/core`: `sql.keyset`, `Executable` and `CompositeQuery`.
90
+
91
+ Docs: docs/guide/pagination.md, docs/guide/querying.md, docs/decisions/0008-client-pagination.md
92
+
93
+ - 2e0b361: Polymorphic relations: `union()` of tables, relations to it, and reading it directly.
94
+ - **`union({ photos, videos })`** (from `dsqlbase/schema`) declares tables that can stand in for one another. `union.columns` holds their shared fields — those every member declares with the same type. A union produces no DDL.
95
+ - **Relations to a union.** `hasMany`, `hasOne` and `belongsTo` accept one. A join to it takes shared-field `select`, `where`, `orderBy`, `limit` and `offset`, applied to every member, plus a per-member `on: { alias: true | false | { select, where, join } }` — GraphQL's fragments. It runs as one `UNION ALL`, ordered and limited across all members in SQL.
96
+ - **`$$key`** on every union row names its member and narrows the result type. In a `where` it filters by member (`{ $$key: { in: types } }`), decided while the query is built, so a member that can't match adds no SQL; `orderBy: { $$key: "asc" }` sorts by it.
97
+ - **`belongsTo(union, { from, to, discriminator })`** joins the member the row's discriminator names. Its `from` column is a keyless `guid()`, which reads, writes and filters global ids keyed by that discriminator.
98
+ - **`dsql.<unionAlias>`** reads a union directly: `findOne`, `findMany`, `paginate` (cursors over `orderBy`, `$$key` and the primary key) and `count`. It is read-only; rows are written through their member's model.
99
+ - Every member passes the tenant predicate in its own branch. A union is on a client only when every member is.
100
+ - Relations to a union are validated when the client is created: members, column pairs, `to` lists, discriminators and global-id agreement.
101
+
102
+ **Breaking,** for `@dsqlbase/core` callers: a relation's `target` may be a union (`SchemaRegistry.getRelationTarget` returns `AnyTable | Union`), and `JoinParams` is `TableJoinParams | UnionJoinParams`. In `dsqlbase`, the `on` map of `$findByGlobalId` and `$listByGlobalId` takes `{ select, where, join }`.
103
+
104
+ Docs: docs/guide/polymorphic-relations.md, docs/guide/relations.md, docs/guide/querying.md, docs/decisions/0009-polymorphic-relations.md
105
+
106
+ - 2e0b361: Query fixes:
107
+ - **Self-relations and same-named tables in different schemas join correctly.** Every level of a select now has its own alias (`FROM "tasks" AS "__t0"`); before, a `tasks.parent → tasks` join matched each row against itself.
108
+ - **`bigint` values stay exact in joined rows and union rows,** which reach the client as JSON: `9007199254740993n` came back as `9007199254740992n`.
109
+ - **`$listByGlobalId` finds an id whose uuid is spelled differently** (upper case, braces, no hyphens), as `$findByGlobalId` does.
110
+ - **`$execute` refuses a `sql` template,** which it ran as nothing; pass one to `$query`, or call `.toQuery()`.
111
+
112
+ **Breaking:** the SQL text of every select changes (results don't), so tests asserting on generated SQL need updating. `@dsqlbase/core/sql/expressions`, an undocumented module duplicating the `sql` helpers, is removed: use `sql.eq`, `sql.and` and the rest.
113
+
114
+ **Known issue:** `update` and `delete` change every row their `where` matches but return only one of them. A fix is planned for the next release; until then, filter them by a unique key. See docs/guide/querying.md.
115
+
116
+ Docs: docs/guide/querying.md, docs/guide/global-ids.md, docs/internals/select-tree-aliasing.md, docs/internals/codec-boundary.md, docs/decisions/0003-select-tree-aliasing.md
117
+
118
+ - 0927824: `$$meta` on every row, and `table().meta()` to put your own data in it.
119
+
120
+ Every result row — from `findOne` / `findMany`, each joined level, and the rows `create` / `update` / `delete` return — carries `$$meta: { key, table, schema? }`: `key` is the schema alias (`members`), `table` the database name (`team_members`). `table("tasks", { … }).meta({ __typename: "Task" })` adds your own fields to it, typed. It is the first key of the row and survives `{ ...row }` and `JSON.stringify`.
121
+
122
+ **Breaking:** rows gain a property, so a whole-row `toEqual` needs `$$meta`. `$$meta` and `$$key` are reserved field names.
123
+
124
+ Docs: docs/guide/querying.md, docs/guide/schema.md, docs/decisions/0004-record-meta.md
125
+
126
+ - 6b80bf1: Relations in `select`: `select: { id: true, author: { name: true } }` reads exactly as `join: { author: { select: { name: true } } }` — same SQL, same result type. A relation takes `true` or a field map over its target, which may name the target's own relations. Filters, order and limits on a relation stay in `join`, and naming one relation in both throws.
127
+
128
+ No `select`, or one naming nothing as `true`, returns every column; naming columns returns those; naming only relations returns only the relations.
129
+
130
+ **Breaking:**
131
+ - The result type of `select: {}` (or an all-`false` select) is the full row, as the runtime already returned. A `join` key set to `false` is no longer in the result type.
132
+ - `@dsqlbase/core`: `SelectOperationArgs.select` is optional, and `[]` now means no column rather than every column.
133
+
134
+ Docs: docs/guide/querying.md, docs/guide/relations.md, docs/decisions/0010-relation-select.md
135
+
136
+ - 2e0b361: A schema that would build wrong queries or DDL now fails when it is declared or when the client is created, naming the problem:
137
+ - More than one primary key on a table (`MULTIPLE_PRIMARY_KEYS` in migration validation). A composite key is one constraint over several columns.
138
+ - Two fields mapped to one database column (`DUPLICATE_COLUMN_NAME`).
139
+ - A relation named like a column of its table: columns and relations share one field namespace.
140
+ - A relation whose column pairs differ in number or type, or name a column of the wrong table.
141
+ - An identity's explicit sequence name already used in its namespace (`DUPLICATE_SEQUENCE_NAME`).
142
+
143
+ `Table.primaryKey` and `Table.isCompositeKey` expose the key at runtime, wherever it was declared.
144
+
145
+ **Fixed:** `PrimaryKeyConstraintDefinition.include()` replaced the key columns with the included ones.
146
+
147
+ **Breaking:** each schema above used to build and failed later, or silently misbehaved.
148
+
149
+ Docs: docs/guide/schema.md, docs/guide/relations.md, docs/internals/migration-pipeline.md
150
+
151
+ - 2e0b361: Tenancy: declare a tenant boundary in the schema, and let the client enforce it. Aurora DSQL has no row-level security, so the client is the last place a multi-tenant application can be stopped from crossing tenants.
152
+ - **Declaring it.** `tenantScope(claims)` (from `dsqlbase/schema`) defines the claim columns every table in a boundary carries: `ws.table(name, columns)` merges them in, and `ws.columns()` spreads into any other table, a namespaced one included. Claim columns must be `notNull`; they are ordinary columns in the DDL.
153
+ - **Scoping a client.** `dsql.$identityClaims(claims)` derives a client for one request. Every read it builds carries the claim predicate ahead of your own `where`, at the root and at every joined level; every update and delete carries it too, and `create` fills the claim columns. A scoped client has no `$query`, `$execute` or `$identityClaims`, since raw SQL would bypass the predicate. `$transaction` inherits the scope.
154
+ - **Enforcing it.** By default a client without claims cannot reach a tenant table: it is absent from the client's type and throws `TenancyError` when a query is built, including through a join. `createClient({ tenancy: { enforce: false } })` lets an internal process run unscoped.
155
+ - **`.readOnly()`** marks a column as managed by something other than the caller. It reads like any column, but it is left out of `create`'s `data` and `update`'s `set`, in the types and at runtime. Claim columns are read-only.
156
+
157
+ **Breaking:**
158
+ - Adopting `tenantScope` takes those tables away from a default client until it is scoped — the point of `enforce: true`.
159
+ - A schema that gives one claim name two data types, or a claim column that is not `notNull`, now throws when the client is created.
160
+ - For direct `@dsqlbase/core` callers: an array `where` passed to `OperationsFactory` means all of its conditions (it used to keep only the first). Client queries never produce one.
161
+
162
+ Docs: docs/guide/tenancy.md, docs/guide/schema.md, docs/guide/querying.md, docs/decisions/0005-tenant-client-visibility.md, docs/decisions/0006-client-tenancy.md
163
+
164
+ ### Patch Changes
165
+
166
+ - 2e0b361: Documentation now lives in [`docs/`](https://github.com/slsdotdev/dsqlbase/tree/main/docs): a guide for using the packages, the internals for contributing, and a record of each design decision. The package READMEs point there, and `QueryArgs.limit` no longer claims a default limit that was never applied.
167
+
168
+ Docs: docs/README.md, docs/guide/README.md, docs/internals/README.md, docs/decisions/README.md
169
+
170
+ - 2e0b361: Packaging fixes for every published package:
171
+ - **The MIT `LICENSE` is now in each tarball.** It was listed as `../../LICENSE`, a path npm ignores, so no release shipped it.
172
+ - **`engines.node` is declared, `>=22`**, and CI runs every suite on Node 22 as well as 24.
173
+ - **In `exports`, `types` comes before `default`**, as TypeScript expects. It resolved before only because the `.d.ts` files sit next to the `.js` files. `publint` and `attw` now check every package in CI.
174
+ - **`homepage` points to the repository.**
175
+ - **Sourcemaps include their sources**, so stack traces and debuggers show the original TypeScript. This makes the packages larger.
176
+ - **The build starts from an empty `dist/`**, so a deleted module can't linger in a tarball.
177
+
178
+ Docs: docs/guide/install.md (Requirements), docs/internals/conventions.md (Packaging), docs/internals/architecture.md.
179
+
180
+ - 2e0b361: The `pg` session returns every transaction's connection to the pool exactly once. A failed `BEGIN`, `COMMIT` or `ROLLBACK` used to keep the connection checked out, so the pool ran dry one failure at a time. A broken connection is now destroyed rather than reused, and `rollback()` doesn't throw. `$transaction` always throws the error that caused the rollback, so a `40001` is still retried when the rollback fails too. The PGlite session waits for `BEGIN`. `TransactionSession` documents this contract for custom sessions.
181
+
182
+ Docs: docs/guide/sessions.md, docs/guide/transactions.md
183
+
184
+ - Updated dependencies [2e0b361]
185
+ - Updated dependencies [2e0b361]
186
+ - Updated dependencies [2e0b361]
187
+ - Updated dependencies [2e0b361]
188
+ - Updated dependencies [2e0b361]
189
+ - Updated dependencies [2e0b361]
190
+ - Updated dependencies [2e0b361]
191
+ - Updated dependencies [2e0b361]
192
+ - Updated dependencies [2e0b361]
193
+ - Updated dependencies [2e0b361]
194
+ - Updated dependencies [2e0b361]
195
+ - Updated dependencies [2e0b361]
196
+ - Updated dependencies [2e0b361]
197
+ - Updated dependencies [0927824]
198
+ - Updated dependencies [6b80bf1]
199
+ - Updated dependencies [2e0b361]
200
+ - Updated dependencies [2e0b361]
201
+ - Updated dependencies [2e0b361]
202
+ - @dsqlbase/core@0.2.0
203
+
3
204
  ## 0.1.6
4
205
 
5
206
  ### Patch Changes
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 sls.dev
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -9,7 +9,7 @@
9
9
  > dsqlbase is in early-stage development and not suited for production environments.
10
10
  > Features may change at any time, without prior notice.
11
11
 
12
- dsqlbase is an ORM and migration toolkit purpose-built for [Aurora DSQL](https://aws.amazon.com/rds/aurora/dsql/). It treats DSQL's distributed-database constraints (no foreign keys, no in-place column changes, async-only index builds, etc.) as first-class — refusing unsupported DDL up front and emitting DSQL-shaped SQL by default. See the [project README](https://github.com/slsdotdev/dsqlbase#readme) for the longer motivation.
12
+ dsqlbase is an ORM and migration toolkit purpose-built for [Aurora DSQL](https://aws.amazon.com/rds/aurora/dsql/). It treats DSQL's distributed-database constraints (async DDL, one DDL statement per transaction, restricted `ALTER TABLE`, optimistic concurrency) as first-class — refusing unsupported DDL up front and emitting DSQL-shaped SQL by default. See the [documentation](https://github.com/slsdotdev/dsqlbase/blob/main/docs/README.md) for the full guide.
13
13
 
14
14
  ## Install
15
15
 
@@ -71,11 +71,215 @@ const recent = await dsql.projects.findMany({
71
71
  limit: 10,
72
72
  join: { team: true },
73
73
  });
74
+
75
+ // A relation can be selected like a field; filters, order and limits on it go in `join`
76
+ const withTeams = await dsql.projects.findMany({ select: { name: true, team: { name: true } } });
77
+ const withProjects = await dsql.teams.findMany({
78
+ select: { name: true },
79
+ join: { projects: { orderBy: { name: "asc" }, limit: 5 } },
80
+ });
81
+ ```
82
+
83
+ ## Multi-tenant schemas
84
+
85
+ If rows belong to a workspace, organisation or account, declare that boundary once and let the
86
+ client apply it. Aurora DSQL has no row-level security, so this is the layer that enforces it.
87
+
88
+ ```ts
89
+ import { tenantScope, uuid } from "dsqlbase/schema";
90
+
91
+ const ws = tenantScope({ workspaceId: uuid("workspace_id").notNull() });
92
+
93
+ export const invoices = ws.table("invoices", {
94
+ id: uuid("id").primaryKey().defaultRandom(),
95
+ number: text("number").notNull(),
96
+ });
97
+
98
+ // Per request:
99
+ const db = dsql.$identityClaims({ workspaceId: claims.workspace_id });
100
+
101
+ await db.invoices.findMany({}); // … WHERE "workspace_id" = $1
102
+ await db.invoices.create({ data: { number: "INV-1" } }); // workspace_id filled from the claim
103
+ ```
104
+
105
+ The claim column is readable and filterable but never writable, the predicate applies to nested
106
+ joins as well as root queries, and a tenant table is absent from an unscoped client — in the
107
+ types and at runtime. See the [tenancy guide](https://github.com/slsdotdev/dsqlbase/blob/main/docs/guide/tenancy.md).
108
+
109
+ ## Global ids
110
+
111
+ If ids leave your process — a GraphQL `Node`, a webhook, a cursor — a bare `uuid` says which row
112
+ but not which table, so nothing can resolve one back or catch it being used against the wrong
113
+ table. `guid()` puts the table in the value:
114
+
115
+ ```ts
116
+ import { guid, table, text } from "dsqlbase/schema";
117
+
118
+ export const authors = table("authors", {
119
+ id: guid("id").primaryKey().defaultRandom(),
120
+ name: text("name").notNull(),
121
+ });
122
+
123
+ export const articles = table("articles", {
124
+ id: guid("id").primaryKey().defaultRandom(),
125
+ authorId: guid("author_id", "authors").notNull(), // points at the authors node
126
+ });
127
+ ```
128
+
129
+ ```ts
130
+ const article = await dsql.articles.findOne({ where: { id }, join: { author: true } });
131
+
132
+ article?.id; // "guid:WyJhcnRpY2xlcyIs…"
133
+ article?.authorId === article?.author?.id; // true
134
+
135
+ const record = await dsql.$findByGlobalId({ id });
136
+ if (record?.$$key === "articles") record.title;
137
+ ```
138
+
139
+ A raw uuid is still accepted on input; an id from another table throws rather than quietly
140
+ matching nothing. It serializes as a plain `uuid`, so adopting it produces no migration. See the
141
+ [global ids guide](https://github.com/slsdotdev/dsqlbase/blob/main/docs/guide/global-ids.md).
142
+
143
+ ## Pagination
144
+
145
+ `paginate` reads one page at a time from a cursor rather than an offset, ordered by your
146
+ `orderBy` and then the primary key, so no row is skipped or repeated between pages:
147
+
148
+ ```ts
149
+ const page = await dsql.tasks.paginate({
150
+ where: { status: "todo" },
151
+ orderBy: { createdAt: "desc" },
152
+ limit: 20,
153
+ after: previous?.endCursor,
154
+ count: true, // adds totalCount
155
+ });
156
+
157
+ page.items; // each with $$meta.cursor
158
+ page.hasNextPage;
159
+ page.endCursor;
160
+
161
+ const open = await dsql.tasks.count({ where: { status: "todo" } });
162
+ ```
163
+
164
+ See the [pagination guide](https://github.com/slsdotdev/dsqlbase/blob/main/docs/guide/pagination.md).
165
+
166
+ ## JSON columns
167
+
168
+ `jsonb()` holds any JSON value. `.schema()` takes any [Standard Schema](https://standardschema.dev)
169
+ — zod, valibot, arktype, none of them a dependency — and validates every write and every read:
170
+
171
+ ```ts
172
+ import { z } from "zod";
173
+ import { jsonb } from "dsqlbase/schema";
174
+
175
+ const Settings = z.object({
176
+ theme: z.enum(["light", "dark"]).default("light"),
177
+ since: z.coerce.date(),
178
+ });
179
+
180
+ export const users = table("users", {
181
+ id: uuid("id").primaryKey().defaultRandom(),
182
+ settings: jsonb("settings").schema(Settings),
183
+ });
184
+
185
+ await dsql.users.create({ data: { settings: { since: "2026-10-01" } } });
186
+ // stored: {"theme":"light","since":"2026-10-01T00:00:00.000Z"}
187
+ // read: { theme: "light", since: Date }
188
+ ```
189
+
190
+ A write stores the schema's output — defaults filled — and checks it reads back as itself, so a
191
+ transforming schema is refused on its first write. Filters, order and operators follow each
192
+ column's type: a `json` column filters by `exists`, and a `jsonb` column also by `eq`, `neq` and
193
+ `contains` — a fragment of the document, matched with `@>`. Filter values are never validated.
194
+
195
+ `array()` and `record()` are `jsonb` columns holding an array, or an object, checked on every
196
+ write and read:
197
+
198
+ ```ts
199
+ export const boards = table("boards", {
200
+ id: uuid("id").primaryKey().defaultRandom(),
201
+ tags: array("tags").$type<string>(), // string[]
202
+ limits: record("limits").schema(z.record(z.string(), z.number())),
203
+ });
204
+
205
+ await dsql.boards.findMany({ where: { tags: { contains: ["urgent"] } } });
206
+ await dsql.boards.findMany({ where: { limits: { hasKey: "cpu" } } });
74
207
  ```
75
208
 
209
+ See the
210
+ [schema guide](https://github.com/slsdotdev/dsqlbase/blob/main/docs/guide/schema.md#json-columns).
211
+
212
+ ## Embedded objects
213
+
214
+ `embedded()` declares a reusable value object; `.column(name)` places it in a table as real
215
+ columns, `<name>_<member>`, read and written as one nested object:
216
+
217
+ ```ts
218
+ import { embedded, numeric, table, text, uuid } from "dsqlbase/schema";
219
+
220
+ export const money = embedded({
221
+ amount: numeric("amount").notNull(),
222
+ currency: text("currency").notNull().default("EUR"),
223
+ });
224
+
225
+ export const invoices = table("invoices", {
226
+ id: uuid("id").primaryKey().defaultRandom(),
227
+ netValue: money.column("net_value"), // net_value_amount, net_value_currency
228
+ });
229
+
230
+ invoices.index("invoices_net_value_idx").columns((c) => [c.netValue.amount]);
231
+
232
+ await dsql.invoices.create({ data: { netValue: { amount: 120 } } });
233
+ await dsql.invoices.findMany({
234
+ where: { netValue: { where: { amount: { gt: 100 } } } },
235
+ orderBy: { netValue: { amount: "desc" } },
236
+ });
237
+ ```
238
+
239
+ A group whose members are all nullable reads `null` when all of them are. See the
240
+ [embedded objects guide](https://github.com/slsdotdev/dsqlbase/blob/main/docs/guide/embeddable-objects.md).
241
+
242
+ ## Polymorphic relations
243
+
244
+ `union()` groups tables that stand in for one another — a GraphQL union or interface — and
245
+ relations can point at it. The client reads it as one `UNION ALL`, ordered and limited across
246
+ members in SQL, and `$$key` on every row says which member it came from:
247
+
248
+ ```ts
249
+ import { union, relations, hasMany } from "dsqlbase/schema";
250
+
251
+ export const posts = union({ photos, videos });
252
+
253
+ export const authorRelations = relations(authors, {
254
+ posts: hasMany(posts, { from: [authors.columns.id], to: [posts.columns.authorId] }),
255
+ });
256
+
257
+ const author = await dsql.authors.findOne({
258
+ where: { id: { eq: authorId } },
259
+ join: {
260
+ posts: {
261
+ orderBy: { createdAt: "desc" },
262
+ limit: 20,
263
+ on: { photos: { select: { photoUrl: true } } }, // per-member fragment
264
+ },
265
+ },
266
+ });
267
+
268
+ for (const post of author?.posts ?? []) {
269
+ if (post.$$key === "photos") post.photoUrl;
270
+ }
271
+
272
+ const page = await dsql.posts.paginate({ where: { $$key: { in: types } }, limit: 20 });
273
+ ```
274
+
275
+ A `belongsTo(union, { ..., discriminator })` points one row at one of several tables. Its
276
+ `guid()` reads back keyed by whichever member the discriminator names. See the
277
+ [polymorphic relations guide](https://github.com/slsdotdev/dsqlbase/blob/main/docs/guide/polymorphic-relations.md).
278
+
76
279
  ## Links
77
280
 
78
- - [Repository & full docs](https://github.com/slsdotdev/dsqlbase#readme)
281
+ - [Guide](https://github.com/slsdotdev/dsqlbase/blob/main/docs/guide/README.md) — schema, querying, pagination, polymorphic relations, sessions, transactions, tenancy, global ids, migrations, DSQL notes
282
+ - [Repository](https://github.com/slsdotdev/dsqlbase)
79
283
  - [Issues](https://github.com/slsdotdev/dsqlbase/issues)
80
284
  - [Contributing](https://github.com/slsdotdev/dsqlbase/blob/main/CONTRIBUTING.md)
81
285
 
@@ -1,6 +1,6 @@
1
- import { DefinitionSchema, Session } from "@dsqlbase/core";
1
+ import { DefinitionSchema, PaginationOptions, Session } from "@dsqlbase/core";
2
2
  import { QueryClient } from "./database/index.js";
3
- export interface ClientOptions<TSchema extends DefinitionSchema> {
3
+ export type ClientOptions<TSchema extends DefinitionSchema, TEnforce extends boolean = true> = {
4
4
  /**
5
5
  * Definition schema for the database, including relations configuration.
6
6
  */
@@ -9,7 +9,27 @@ export interface ClientOptions<TSchema extends DefinitionSchema> {
9
9
  * Session object for managing database connections and transactions.
10
10
  */
11
11
  session: Session;
12
- }
12
+ /**
13
+ * How tables declared inside a `tenantScope()` behave on this client.
14
+ *
15
+ * With `enforce` on, which is the default, they are absent from the base client's type and
16
+ * refuse to build a query until the client is scoped with `$identityClaims`. Set it to
17
+ * `false` for a process that is meant to run unscoped — an internal worker rather than a
18
+ * request handler — and every tenant table becomes readable across tenants.
19
+ *
20
+ * It is decided here, per client, rather than per call: a per-call escape hatch is a thing to
21
+ * forget, and the processes that need one are separate deployments anyway. Inserting into a
22
+ * tenant table still requires claims in both modes.
23
+ */
24
+ tenancy?: {
25
+ enforce?: TEnforce;
26
+ };
27
+ /**
28
+ * Page sizes for `paginate`. `defaultLimit` is used when a call names no `limit` (100 when
29
+ * unset); `maxLimit`, when set, refuses any larger `limit` a call asks for.
30
+ */
31
+ pagination?: PaginationOptions;
32
+ };
13
33
  /**
14
34
  * Creates a new client instance for interacting with the database using the provided schema definition.
15
35
  *
@@ -69,5 +89,5 @@ export interface ClientOptions<TSchema extends DefinitionSchema> {
69
89
  * @see {@link ClientOptions} for more details on the configuration options.
70
90
  * @see {@link ModelClient} for information on the methods available for interacting with the database tables.
71
91
  */
72
- export declare function createClient<TSchema extends DefinitionSchema>(options: ClientOptions<TSchema>): QueryClient<TSchema>;
92
+ export declare function createClient<TSchema extends DefinitionSchema, TEnforce extends boolean = true>(options: ClientOptions<TSchema, TEnforce>): QueryClient<TSchema, TEnforce>;
73
93
  //# sourceMappingURL=create.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"create.d.ts","sourceRoot":"","sources":["../../src/client/create.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,gBAAgB,EAIhB,OAAO,EACR,MAAM,gBAAgB,CAAC;AAExB,OAAO,EAAkB,WAAW,EAAE,MAAM,qBAAqB,CAAC;AAElE,MAAM,WAAW,aAAa,CAAC,OAAO,SAAS,gBAAgB;IAC7D;;OAEG;IACH,MAAM,EAAE,OAAO,CAAC;IAEhB;;OAEG;IACH,OAAO,EAAE,OAAO,CAAC;CAClB;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA0DG;AAEH,wBAAgB,YAAY,CAAC,OAAO,SAAS,gBAAgB,EAC3D,OAAO,EAAE,aAAa,CAAC,OAAO,CAAC,GAC9B,WAAW,CAAC,OAAO,CAAC,CAuBtB"}
1
+ {"version":3,"file":"create.d.ts","sourceRoot":"","sources":["../../src/client/create.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,gBAAgB,EAEhB,iBAAiB,EAGjB,OAAO,EACR,MAAM,gBAAgB,CAAC;AAGxB,OAAO,EAAkB,WAAW,EAAE,MAAM,qBAAqB,CAAC;AAElE,MAAM,MAAM,aAAa,CACvB,OAAO,SAAS,gBAAgB,EAChC,QAAQ,SAAS,OAAO,GAAG,IAAI,IAC7B;IACF;;OAEG;IACH,MAAM,EAAE,OAAO,CAAC;IAEhB;;OAEG;IACH,OAAO,EAAE,OAAO,CAAC;IAEjB;;;;;;;;;;;OAWG;IACH,OAAO,CAAC,EAAE;QACR,OAAO,CAAC,EAAE,QAAQ,CAAC;KACpB,CAAC;IAEF;;;OAGG;IACH,UAAU,CAAC,EAAE,iBAAiB,CAAC;CAChC,CAAC;AAkBF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA0DG;AAEH,wBAAgB,YAAY,CAAC,OAAO,SAAS,gBAAgB,EAAE,QAAQ,SAAS,OAAO,GAAG,IAAI,EAC5F,OAAO,EAAE,aAAa,CAAC,OAAO,EAAE,QAAQ,CAAC,GACxC,WAAW,CAAC,OAAO,EAAE,QAAQ,CAAC,CAuBhC"}
@@ -1,6 +1,18 @@
1
1
  import { ExecutionContext, QueryBuilder, SchemaRegistry, } from "@dsqlbase/core";
2
- import { ModelClient } from "./model/client.js";
2
+ import { attachModels } from "./database/base.js";
3
+ import { registerNodes } from "./nodes.js";
3
4
  import { DatabaseClient } from "./database/index.js";
5
+ function assertPagination(options) {
6
+ for (const [name, value] of Object.entries(options ?? {})) {
7
+ if (value !== undefined && (!Number.isInteger(value) || value <= 0)) {
8
+ throw new Error(`pagination.${name} must be a positive integer (got ${String(value)}).`);
9
+ }
10
+ }
11
+ const { defaultLimit, maxLimit } = options ?? {};
12
+ if (defaultLimit !== undefined && maxLimit !== undefined && defaultLimit > maxLimit) {
13
+ throw new Error(`pagination.defaultLimit (${defaultLimit}) exceeds pagination.maxLimit (${maxLimit}).`);
14
+ }
15
+ }
4
16
  /**
5
17
  * Creates a new client instance for interacting with the database using the provided schema definition.
6
18
  *
@@ -61,22 +73,22 @@ import { DatabaseClient } from "./database/index.js";
61
73
  * @see {@link ModelClient} for information on the methods available for interacting with the database tables.
62
74
  */
63
75
  export function createClient(options) {
76
+ assertPagination(options.pagination);
64
77
  const schema = new SchemaRegistry(options.schema);
65
78
  const dialect = new QueryBuilder();
79
+ // Resolves every guid() column against the tables it can reach. Here rather than inside
80
+ // `SchemaRegistry`, because the shape of an id is a client concern: core sees a uuid
81
+ // column with a codec, the same way it sees an interval column with a Duration codec.
82
+ registerNodes(schema, options.schema);
66
83
  const context = new ExecutionContext({
67
84
  schema,
68
85
  dialect,
69
86
  session: options.session,
87
+ tenancy: options.tenancy,
88
+ pagination: options.pagination,
70
89
  });
71
90
  const dbClient = new DatabaseClient(context);
72
- for (const [tableName, table] of Object.entries(schema.getTables())) {
73
- const modelClient = new ModelClient(context, table);
74
- Object.defineProperty(dbClient, tableName, {
75
- value: modelClient,
76
- writable: false,
77
- enumerable: true,
78
- });
79
- }
91
+ attachModels(dbClient, context);
80
92
  return dbClient;
81
93
  }
82
94
  //# sourceMappingURL=create.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"create.js","sourceRoot":"","sources":["../../src/client/create.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,gBAAgB,EAChB,YAAY,EACZ,cAAc,GAEf,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,cAAc,EAAe,MAAM,qBAAqB,CAAC;AAclE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA0DG;AAEH,MAAM,UAAU,YAAY,CAC1B,OAA+B;IAE/B,MAAM,MAAM,GAAG,IAAI,cAAc,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;IAClD,MAAM,OAAO,GAAG,IAAI,YAAY,EAAE,CAAC;IAEnC,MAAM,OAAO,GAAG,IAAI,gBAAgB,CAAC;QACnC,MAAM;QACN,OAAO;QACP,OAAO,EAAE,OAAO,CAAC,OAAO;KACzB,CAAC,CAAC;IAEH,MAAM,QAAQ,GAAG,IAAI,cAAc,CAAC,OAAO,CAAC,CAAC;IAE7C,KAAK,MAAM,CAAC,SAAS,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAW,MAAM,CAAC,SAAS,EAAE,CAAC,EAAE,CAAC;QAC9E,MAAM,WAAW,GAAG,IAAI,WAAW,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;QAEpD,MAAM,CAAC,cAAc,CAAC,QAAQ,EAAE,SAAS,EAAE;YACzC,KAAK,EAAE,WAAW;YAClB,QAAQ,EAAE,KAAK;YACf,UAAU,EAAE,IAAI;SACjB,CAAC,CAAC;IACL,CAAC;IAED,OAAO,QAAgC,CAAC;AAC1C,CAAC"}
1
+ {"version":3,"file":"create.js","sourceRoot":"","sources":["../../src/client/create.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,gBAAgB,EAEhB,YAAY,EACZ,cAAc,GAEf,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAC3C,OAAO,EAAE,cAAc,EAAe,MAAM,qBAAqB,CAAC;AAuClE,SAAS,gBAAgB,CAAC,OAAsC;IAC9D,KAAK,MAAM,CAAC,IAAI,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,OAAO,IAAI,EAAE,CAAC,EAAE,CAAC;QAC1D,IAAI,KAAK,KAAK,SAAS,IAAI,CAAC,CAAC,MAAM,CAAC,SAAS,CAAC,KAAK,CAAC,IAAI,KAAK,IAAI,CAAC,CAAC,EAAE,CAAC;YACpE,MAAM,IAAI,KAAK,CAAC,cAAc,IAAI,oCAAoC,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;QAC3F,CAAC;IACH,CAAC;IAED,MAAM,EAAE,YAAY,EAAE,QAAQ,EAAE,GAAG,OAAO,IAAI,EAAE,CAAC;IAEjD,IAAI,YAAY,KAAK,SAAS,IAAI,QAAQ,KAAK,SAAS,IAAI,YAAY,GAAG,QAAQ,EAAE,CAAC;QACpF,MAAM,IAAI,KAAK,CACb,4BAA4B,YAAY,kCAAkC,QAAQ,IAAI,CACvF,CAAC;IACJ,CAAC;AACH,CAAC;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA0DG;AAEH,MAAM,UAAU,YAAY,CAC1B,OAAyC;IAEzC,gBAAgB,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC;IAErC,MAAM,MAAM,GAAG,IAAI,cAAc,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;IAClD,MAAM,OAAO,GAAG,IAAI,YAAY,EAAE,CAAC;IAEnC,wFAAwF;IACxF,qFAAqF;IACrF,sFAAsF;IACtF,aAAa,CAAC,MAAM,EAAE,OAAO,CAAC,MAAM,CAAC,CAAC;IAEtC,MAAM,OAAO,GAAG,IAAI,gBAAgB,CAAC;QACnC,MAAM;QACN,OAAO;QACP,OAAO,EAAE,OAAO,CAAC,OAAO;QACxB,OAAO,EAAE,OAAO,CAAC,OAAO;QACxB,UAAU,EAAE,OAAO,CAAC,UAAU;KAC/B,CAAC,CAAC;IAEH,MAAM,QAAQ,GAAG,IAAI,cAAc,CAAC,OAAO,CAAC,CAAC;IAC7C,YAAY,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAC;IAEhC,OAAO,QAAqD,CAAC;AAC/D,CAAC","sourcesContent":["import {\n DefinitionSchema,\n ExecutionContext,\n PaginationOptions,\n QueryBuilder,\n SchemaRegistry,\n Session,\n} from \"@dsqlbase/core\";\nimport { attachModels } from \"./database/base.js\";\nimport { registerNodes } from \"./nodes.js\";\nimport { DatabaseClient, QueryClient } from \"./database/index.js\";\n\nexport type ClientOptions<\n TSchema extends DefinitionSchema,\n TEnforce extends boolean = true,\n> = {\n /**\n * Definition schema for the database, including relations configuration.\n */\n schema: TSchema;\n\n /**\n * Session object for managing database connections and transactions.\n */\n session: Session;\n\n /**\n * How tables declared inside a `tenantScope()` behave on this client.\n *\n * With `enforce` on, which is the default, they are absent from the base client's type and\n * refuse to build a query until the client is scoped with `$identityClaims`. Set it to\n * `false` for a process that is meant to run unscoped — an internal worker rather than a\n * request handler — and every tenant table becomes readable across tenants.\n *\n * It is decided here, per client, rather than per call: a per-call escape hatch is a thing to\n * forget, and the processes that need one are separate deployments anyway. Inserting into a\n * tenant table still requires claims in both modes.\n */\n tenancy?: {\n enforce?: TEnforce;\n };\n\n /**\n * Page sizes for `paginate`. `defaultLimit` is used when a call names no `limit` (100 when\n * unset); `maxLimit`, when set, refuses any larger `limit` a call asks for.\n */\n pagination?: PaginationOptions;\n};\n\nfunction assertPagination(options: PaginationOptions | undefined) {\n for (const [name, value] of Object.entries(options ?? {})) {\n if (value !== undefined && (!Number.isInteger(value) || value <= 0)) {\n throw new Error(`pagination.${name} must be a positive integer (got ${String(value)}).`);\n }\n }\n\n const { defaultLimit, maxLimit } = options ?? {};\n\n if (defaultLimit !== undefined && maxLimit !== undefined && defaultLimit > maxLimit) {\n throw new Error(\n `pagination.defaultLimit (${defaultLimit}) exceeds pagination.maxLimit (${maxLimit}).`\n );\n }\n}\n\n/**\n * Creates a new client instance for interacting with the database using the provided schema definition.\n *\n * @example\n * ```ts\n * // schema.ts\n * import { table, text, uuid } from \"@dsqlbase/schema\";\n *\n * export const users = table(\"users\", {\n * id: uuid(\"id\").primaryKey().defaultRandom(),\n * firstName: text(\"first_name\").notNull(),\n * lastName: text(\"last_name\").notNull(),\n * emailAddress: text(\"email_address\").notNull().unique(),\n * });\n *\n * export const posts = table(\"posts\", {\n * id: uuid(\"id\").primaryKey().defaultRandom(),\n * title: text(\"title\").notNull(),\n * description: text(\"description\"),\n * content: text(\"content\").notNull(),\n * });\n *\n * export const userRelations = relations(users, {\n * posts: hasMany(posts, {\n * from: [users.columns.id],\n * to: [posts.columns.userId],\n * }),\n * });\n *\n * export const postRelations = relations(posts, {\n * owner: belongsTo(users, {\n * from: [posts.columns.userId],\n * to: [users.columns.id],\n * }),\n * });\n *\n * // client.ts\n * import { createClient } from \"dsqlbase\";\n * import * as schema from \"./schema\";\n *\n * export const dsql = createClient({ schema });\n *\n * // Example usage\n * import { dsql } from \"./client\";\n *\n * const newUser = await dsql.users.create({\n * data: {\n * firstName: \"John\",\n * lastName: \"Doe\",\n * emailAddress: \"john.doe@example.com\",\n * },\n * });\n * ```\n * @param options - Configuration options for the client, including the schema definition.\n * @returns A new instance of the DSQL client configured with the provided schema.\n * @throws Will throw an error if the schema definition is invalid or if there are issues initializing the client.\n * @see {@link ClientOptions} for more details on the configuration options.\n * @see {@link ModelClient} for information on the methods available for interacting with the database tables.\n */\n\nexport function createClient<TSchema extends DefinitionSchema, TEnforce extends boolean = true>(\n options: ClientOptions<TSchema, TEnforce>\n): QueryClient<TSchema, TEnforce> {\n assertPagination(options.pagination);\n\n const schema = new SchemaRegistry(options.schema);\n const dialect = new QueryBuilder();\n\n // Resolves every guid() column against the tables it can reach. Here rather than inside\n // `SchemaRegistry`, because the shape of an id is a client concern: core sees a uuid\n // column with a codec, the same way it sees an interval column with a Duration codec.\n registerNodes(schema, options.schema);\n\n const context = new ExecutionContext({\n schema,\n dialect,\n session: options.session,\n tenancy: options.tenancy,\n pagination: options.pagination,\n });\n\n const dbClient = new DatabaseClient(context);\n attachModels(dbClient, context);\n\n return dbClient as unknown as QueryClient<TSchema, TEnforce>;\n}\n"]}