okmodel 0.1.1 → 0.3.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 (228) hide show
  1. package/README.md +727 -37
  2. package/dist/adapters/capabilities.d.ts +34 -0
  3. package/dist/adapters/pg/bunsql-extra.d.ts +17 -0
  4. package/dist/adapters/pg/bunsql.d.ts +60 -0
  5. package/dist/adapters/pg/call.d.ts +2 -12
  6. package/dist/adapters/pg/nodepostgres-extra.d.ts +18 -0
  7. package/dist/adapters/pg/nodepostgres.d.ts +57 -0
  8. package/dist/adapters/pg/postgres-extra.d.ts +50 -1
  9. package/dist/adapters/pg/postgresjs.d.ts +0 -4
  10. package/dist/adapters/pg/session.d.ts +94 -0
  11. package/dist/adapters/pg/watch.d.ts +18 -0
  12. package/dist/contracts/catalog/enum.d.ts +31 -4
  13. package/dist/contracts/catalog/extension.d.ts +61 -0
  14. package/dist/contracts/catalog/object.d.ts +1 -0
  15. package/dist/contracts/catalog/privilege.d.ts +64 -0
  16. package/dist/contracts/catalog/routine.d.ts +56 -0
  17. package/dist/contracts/catalog/types.d.ts +179 -18
  18. package/dist/contracts/catalog/view.d.ts +73 -0
  19. package/dist/contracts/connection.d.ts +13 -0
  20. package/dist/contracts/driver.d.ts +18 -5
  21. package/dist/contracts/error.d.ts +17 -1
  22. package/dist/contracts/generator.d.ts +63 -0
  23. package/dist/contracts/index.d.ts +2 -2
  24. package/dist/contracts/index.js +1 -1
  25. package/dist/contracts/internal.js +11 -9
  26. package/dist/contracts/location.d.ts +24 -0
  27. package/dist/contracts/rows.d.ts +15 -0
  28. package/dist/dialects/pg/archive-bind.d.ts +22 -0
  29. package/dist/dialects/pg/column.d.ts +129 -10
  30. package/dist/dialects/pg/compile.d.ts +1 -0
  31. package/dist/dialects/pg/custom.d.ts +6 -0
  32. package/dist/dialects/pg/ddl.d.ts +65 -1
  33. package/dist/dialects/pg/enum.d.ts +10 -8
  34. package/dist/dialects/pg/ext/citext.d.ts +14 -0
  35. package/dist/dialects/pg/ext/citext.js +11 -0
  36. package/dist/dialects/pg/ext/index.d.ts +52 -0
  37. package/dist/dialects/pg/ext/index.js +6 -0
  38. package/dist/dialects/pg/ext/pg-trgm.d.ts +53 -0
  39. package/dist/dialects/pg/ext/pg-trgm.js +42 -0
  40. package/dist/dialects/pg/filter-parse.d.ts +19 -0
  41. package/dist/dialects/pg/filters.d.ts +19 -0
  42. package/dist/dialects/pg/fn/index.d.ts +107 -0
  43. package/dist/dialects/pg/fn/index.js +175 -0
  44. package/dist/dialects/pg/fn/touch.d.ts +14 -0
  45. package/dist/dialects/pg/index.d.ts +11 -2
  46. package/dist/dialects/pg/index.js +243 -1062
  47. package/dist/dialects/pg/introspect.d.ts +10 -1
  48. package/dist/dialects/pg/keys.d.ts +19 -3
  49. package/dist/dialects/pg/model.d.ts +223 -2
  50. package/dist/dialects/pg/operator-fit.d.ts +86 -0
  51. package/dist/dialects/pg/operators.d.ts +46 -1
  52. package/dist/dialects/pg/ops/arr-append.d.ts +9 -0
  53. package/dist/dialects/pg/ops/arr-ns.d.ts +7 -0
  54. package/dist/dialects/pg/ops/arr-remove.d.ts +9 -0
  55. package/dist/dialects/pg/ops/containedBy.d.ts +9 -0
  56. package/dist/dialects/pg/ops/contains.d.ts +8 -4
  57. package/dist/dialects/pg/ops/hasAnyKey.d.ts +8 -0
  58. package/dist/dialects/pg/ops/hasKey.d.ts +8 -0
  59. package/dist/dialects/pg/ops/json-ns.d.ts +6 -0
  60. package/dist/dialects/pg/ops/json-set.d.ts +12 -0
  61. package/dist/dialects/pg/ops/matches.d.ts +16 -0
  62. package/dist/dialects/pg/ops/overlaps.d.ts +9 -0
  63. package/dist/dialects/pg/ops/path.d.ts +13 -0
  64. package/dist/dialects/pg/preset.d.ts +76 -0
  65. package/dist/dialects/pg/relations.d.ts +59 -2
  66. package/dist/dialects/pg/role/check.d.ts +45 -0
  67. package/dist/dialects/pg/role/index.d.ts +50 -0
  68. package/dist/dialects/pg/role/sql.d.ts +44 -0
  69. package/dist/dialects/pg/schema.d.ts +109 -5
  70. package/dist/dialects/pg/table.d.ts +137 -11
  71. package/dist/dialects/pg/temporal.d.ts +9 -7
  72. package/dist/dialects/pg/tenancy.d.ts +103 -0
  73. package/dist/dialects/pg/through.d.ts +21 -0
  74. package/dist/dialects/pg/trait.d.ts +141 -0
  75. package/dist/dialects/pg/view/client.d.ts +30 -0
  76. package/dist/dialects/pg/view/depend.d.ts +35 -0
  77. package/dist/dialects/pg/view/index.d.ts +114 -0
  78. package/dist/dialects/pg/view/index.js +289 -0
  79. package/dist/dialects/pg/view/scratch.d.ts +21 -0
  80. package/dist/dialects/pg/where.d.ts +37 -0
  81. package/dist/runtime/aggregate.d.ts +25 -0
  82. package/dist/runtime/archive-handle.d.ts +18 -0
  83. package/dist/runtime/archive-rules.d.ts +12 -0
  84. package/dist/runtime/archive.d.ts +73 -0
  85. package/dist/runtime/batch.d.ts +20 -0
  86. package/dist/runtime/client.d.ts +114 -5
  87. package/dist/runtime/conflict.d.ts +2 -1
  88. package/dist/runtime/exposure.d.ts +27 -0
  89. package/dist/runtime/hookm.d.ts +39 -0
  90. package/dist/runtime/ids/index.d.ts +11 -0
  91. package/dist/runtime/ids/index.js +193 -0
  92. package/dist/runtime/ids/okid-extended.d.ts +19 -0
  93. package/dist/runtime/ids/okid-generator.d.ts +21 -0
  94. package/dist/runtime/ids/okid-shared.d.ts +89 -0
  95. package/dist/runtime/ids/okid.d.ts +24 -0
  96. package/dist/runtime/ids/uuid.d.ts +21 -0
  97. package/dist/runtime/lock.d.ts +22 -0
  98. package/dist/runtime/operator-sql.d.ts +8 -0
  99. package/dist/runtime/page.d.ts +25 -0
  100. package/dist/runtime/pg/bun.d.ts +30 -0
  101. package/dist/runtime/pg/bun.js +52 -0
  102. package/dist/runtime/pg/pg.d.ts +29 -0
  103. package/dist/runtime/pg/pg.js +52 -0
  104. package/dist/runtime/pg/pglite.js +16 -17
  105. package/dist/runtime/pg/postgresjs.js +14 -24
  106. package/dist/runtime/plan.d.ts +146 -7
  107. package/dist/runtime/preset-stack.d.ts +17 -0
  108. package/dist/runtime/presets.d.ts +48 -0
  109. package/dist/runtime/read-stream.d.ts +26 -0
  110. package/dist/runtime/safety/index.d.ts +159 -0
  111. package/dist/runtime/safety/index.js +294 -0
  112. package/dist/runtime/safety-hook.d.ts +42 -0
  113. package/dist/runtime/server-check.d.ts +34 -0
  114. package/dist/runtime/tenancy/index.d.ts +37 -0
  115. package/dist/runtime/tenancy/index.js +368 -0
  116. package/dist/runtime/trait-read.d.ts +30 -0
  117. package/dist/runtime/traits/index.d.ts +133 -0
  118. package/dist/runtime/traits/index.js +646 -0
  119. package/dist/runtime/transaction.d.ts +19 -0
  120. package/dist/runtime/tx.d.ts +22 -7
  121. package/dist/runtime/types.d.ts +376 -27
  122. package/dist/runtime/validate/bind.d.ts +11 -0
  123. package/dist/runtime/validate/closed.d.ts +16 -0
  124. package/dist/runtime/validate/engine.d.ts +41 -0
  125. package/dist/runtime/validate/hook.d.ts +17 -0
  126. package/dist/runtime/validate/index.d.ts +21 -0
  127. package/dist/runtime/validate/index.js +175 -0
  128. package/dist/runtime/validate/load.d.ts +13 -0
  129. package/dist/runtime/validate/places.d.ts +41 -0
  130. package/dist/runtime/validate/rules.d.ts +108 -0
  131. package/dist/runtime/validate/surface.d.ts +102 -0
  132. package/dist/runtime/write.d.ts +30 -5
  133. package/dist/shared/01yr20s5.js +149 -0
  134. package/dist/shared/0jc3ffzf.js +154 -0
  135. package/dist/shared/0v1g424p.js +26 -0
  136. package/dist/shared/1g0drakv.js +225 -0
  137. package/dist/shared/{kprcwaha.js → 1tfdfvhh.js} +5 -3
  138. package/dist/shared/{05w44d8g.js → 2ssqrv66.js} +767 -715
  139. package/dist/shared/3ekj9x92.js +210 -0
  140. package/dist/shared/49ypnfwt.js +1122 -0
  141. package/dist/shared/4e4c6vq2.js +62 -0
  142. package/dist/shared/4m9fn52z.js +70 -0
  143. package/dist/shared/{ycwz42az.js → 52szzakm.js} +6 -26
  144. package/dist/shared/5nmdenb6.js +1229 -0
  145. package/dist/shared/672t5vym.js +12 -0
  146. package/dist/shared/6bazvqwm.js +86 -0
  147. package/dist/shared/6w5j844a.js +201 -0
  148. package/dist/shared/{fgqgsb5z.js → 75xkjv0t.js} +2 -2
  149. package/dist/shared/7fvtrkwr.js +84 -0
  150. package/dist/shared/7m88x3e9.js +45 -0
  151. package/dist/shared/{mtkwv8wx.js → 7p2wbz7f.js} +1 -1
  152. package/dist/shared/83eaefwr.js +10 -0
  153. package/dist/shared/94ez8kzh.js +19 -0
  154. package/dist/shared/96ps4g1z.js +32 -0
  155. package/dist/shared/{xqbhg6cn.js → 999ade2q.js} +95 -10
  156. package/dist/shared/9m80mkac.js +158 -0
  157. package/dist/shared/9x25fxhc.js +150 -0
  158. package/dist/shared/a5sxz52y.js +13 -0
  159. package/dist/shared/axhk06q1.js +156 -0
  160. package/dist/shared/{dynq16vb.js → b066g80h.js} +8 -6
  161. package/dist/shared/bqha5cg6.js +229 -0
  162. package/dist/shared/bryqk9k9.js +31 -0
  163. package/dist/shared/c8aghh05.js +442 -0
  164. package/dist/shared/c9z5g0fm.js +309 -0
  165. package/dist/shared/{m3ypagh5.js → dbjej1tw.js} +124 -15
  166. package/dist/shared/dyj86cmj.js +69 -0
  167. package/dist/shared/e6wg00wd.js +164 -0
  168. package/dist/shared/{hadrfb9h.js → edwqqryd.js} +17 -14
  169. package/dist/shared/{qk3hxfja.js → fptpmvxp.js} +5 -5
  170. package/dist/shared/fs0ex00p.js +76 -0
  171. package/dist/shared/{jjb7yht9.js → g4f5kcx9.js} +3 -3
  172. package/dist/shared/gjthds9j.js +48 -0
  173. package/dist/shared/hcmdtwgh.js +102 -0
  174. package/dist/shared/{g5fhqmwe.js → jkc6ws1p.js} +6 -56
  175. package/dist/shared/{yd1kzwn2.js → jns2wx4t.js} +55 -12
  176. package/dist/shared/k34e0xf2.js +450 -0
  177. package/dist/shared/k3ted12y.js +33 -0
  178. package/dist/shared/k7dwkhvq.js +31 -0
  179. package/dist/shared/{8b04d28c.js → kgnc8grt.js} +2 -2
  180. package/dist/shared/{hd293j9g.js → kyxb62mc.js} +14 -2
  181. package/dist/shared/m78s7898.js +376 -0
  182. package/dist/shared/m9tv7xn7.js +404 -0
  183. package/dist/shared/meck53jv.js +99 -0
  184. package/dist/shared/mt5wswjz.js +90 -0
  185. package/dist/shared/n0dgs0pb.js +75 -0
  186. package/dist/shared/n442h54c.js +14 -0
  187. package/dist/shared/n4jqhpqz.js +27 -0
  188. package/dist/shared/n7mcc1gk.js +132 -0
  189. package/dist/shared/ne02ng5c.js +68 -0
  190. package/dist/shared/{mkjmqjv4.js → nfzc5z0w.js} +2 -104
  191. package/dist/shared/nsva2a6b.js +42 -0
  192. package/dist/shared/p24x2334.js +195 -0
  193. package/dist/shared/qbxzvwwc.js +88 -0
  194. package/dist/shared/{w8samvk1.js → qybh48nd.js} +1 -1
  195. package/dist/shared/r6nwkxnt.js +86 -0
  196. package/dist/shared/{xy79j5hq.js → rrstp3kb.js} +25 -36
  197. package/dist/shared/rwmrejjz.js +26 -0
  198. package/dist/shared/{zhc5vmgf.js → s6gqfn5j.js} +2 -2
  199. package/dist/shared/{523ft3e8.js → scwxrpx2.js} +7 -5
  200. package/dist/shared/{j5cn2963.js → t4tbsy9h.js} +13 -64
  201. package/dist/shared/{y9m15dfv.js → t616ynfn.js} +544 -32
  202. package/dist/shared/{ngk8gj61.js → tbszx8mz.js} +15 -1
  203. package/dist/shared/th14ygv2.js +69 -0
  204. package/dist/shared/tmbdywx0.js +178 -0
  205. package/dist/shared/ty3v3hfk.js +64 -0
  206. package/dist/shared/wekze34d.js +246 -0
  207. package/dist/shared/x6wysh83.js +1132 -0
  208. package/dist/shared/{rgs0st28.js → xrfnq5k8.js} +237 -434
  209. package/dist/shared/{x5x59srr.js → xva8v7qk.js} +416 -83
  210. package/dist/shared/{dkn3y60a.js → xw1d69vd.js} +76 -112
  211. package/dist/shared/y005b761.js +112 -0
  212. package/dist/shared/ydaz1sv3.js +55 -0
  213. package/dist/shared/{p0cbr3g2.js → zwmqxb0g.js} +1 -1
  214. package/dist/tooling/cli.js +40 -12
  215. package/dist/tooling/migrate/apply.d.ts +16 -0
  216. package/dist/tooling/migrate/commands.d.ts +12 -1
  217. package/dist/tooling/migrate/config.d.ts +8 -0
  218. package/dist/tooling/migrate/doctor.d.ts +25 -0
  219. package/dist/tooling/migrate/drift.d.ts +19 -0
  220. package/dist/tooling/migrate/engine.d.ts +36 -0
  221. package/dist/tooling/migrate/ext.d.ts +17 -0
  222. package/dist/tooling/migrate/extensions.d.ts +51 -0
  223. package/dist/tooling/migrate/managed.d.ts +17 -0
  224. package/dist/tooling/migrate/plan.d.ts +14 -1
  225. package/dist/tooling/migrate/project.d.ts +25 -1
  226. package/dist/tooling/migrate/type-name.d.ts +19 -0
  227. package/package.json +61 -4
  228. package/dist/shared/gk7cs7sp.js +0 -566
@@ -1,16 +1,24 @@
1
+ import {
2
+ touchFields,
3
+ fieldSealed
4
+ } from "./7m88x3e9.js";
1
5
  import {
2
6
  projectExpr,
3
7
  quote,
4
8
  list,
5
9
  isRecord,
10
+ registerFailFix,
6
11
  fail
7
- } from "./rgs0st28.js";
12
+ } from "./xrfnq5k8.js";
8
13
  import {
9
14
  throwNamed2
10
- } from "./ycwz42az.js";
15
+ } from "./52szzakm.js";
11
16
 
12
17
  // src/runtime/conflict.ts
13
- function readConflict(table, value) {
18
+ registerFailFix("OKM1104", "Set on to the columns of a unique constraint or the primary key.");
19
+ registerFailFix("OKM1190", "Remove the guarded field. Input cannot set it.");
20
+ var NO_ALLOW = new Set;
21
+ function readConflict(table, value, allow = NO_ALLOW) {
14
22
  if (value === undefined || value === "error")
15
23
  return;
16
24
  if (value === "ignore")
@@ -33,7 +41,7 @@ function readConflict(table, value) {
33
41
  return {
34
42
  kind: "update",
35
43
  columns: uniqueColumns(table, value.on),
36
- update: updateColumns(table, update)
44
+ update: updateColumns(table, update, allow)
37
45
  };
38
46
  }
39
47
  fail("OKM1120", 'onConflict must be "error", "ignore", { on, update }, or { on, return: true }.');
@@ -44,9 +52,17 @@ function finishInsert(head, returning, params, plan, table, returningColumns, ke
44
52
  }
45
53
  const target = plan.columns.map((column) => quote(column.sql)).join(", ");
46
54
  if (plan.kind === "update") {
47
- const set = plan.update.map((column) => `${quote(column.sql)} = excluded.${quote(column.sql)}`).join(", ");
55
+ const assignments = plan.update.map((column) => `${quote(column.sql)} = excluded.${quote(column.sql)}`);
56
+ const touch = touchFields(table.model);
57
+ if (touch !== undefined) {
58
+ for (const field of touch) {
59
+ const column = table.columns.get(field);
60
+ if (column !== undefined)
61
+ assignments.push(`${quote(column.sql)} = now()`);
62
+ }
63
+ }
48
64
  return {
49
- text: `${head} on conflict (${target}) do update set ${set}${returning}`,
65
+ text: `${head} on conflict (${target})${conflictWhere(table, plan.columns)} do update set ${assignments.join(", ")}${returning}`,
50
66
  params: [...params]
51
67
  };
52
68
  }
@@ -71,9 +87,29 @@ function firstOrCreate(head, returning, params, keys, table, returningColumns, k
71
87
  const names = returningColumns.map((column) => quote(column.field)).join(", ");
72
88
  const fromTable = returningColumns.map((column) => projectExpr(`t.${quote(column.sql)}`, column.dataType)).join(", ");
73
89
  const match = keys.map((column) => `ins.${quote(column.field)} = t.${quote(column.sql)}`).join(" and ");
74
- const text = `with ins(${names}) as (${head} on conflict (${keyList}) do nothing${returning}) select ${names} from ins union all select ${fromTable} from ${quote(table.model.sql)} t where ${left} in (${tuples.join(", ")}) and not exists (select 1 from ins where ${match})`;
90
+ const text = `with ins(${names}) as (${head} on conflict (${keyList})${conflictWhere(table, keys)} do nothing${returning}) select ${names} from ins union all select ${fromTable} from ${quote(table.model.sql)} t where ${left} in (${tuples.join(", ")}) and not exists (select 1 from ins where ${match})`;
75
91
  return { text, params: next };
76
92
  }
93
+ function conflictWhere(table, columns) {
94
+ const archive = table.model.archive;
95
+ if (archive === undefined || samePrimary(table, columns))
96
+ return "";
97
+ return ` where ${quote(archive.at)} is null`;
98
+ }
99
+ function samePrimary(table, columns) {
100
+ const primary = table.model.primary;
101
+ if (columns.length !== primary.length)
102
+ return false;
103
+ for (const field of primary) {
104
+ let found = false;
105
+ for (const column of columns)
106
+ if (column.field === field)
107
+ found = true;
108
+ if (!found)
109
+ return false;
110
+ }
111
+ return true;
112
+ }
77
113
  function uniqueColumns(table, on) {
78
114
  const names = conflictNames(on);
79
115
  for (const unique of table.model.uniques) {
@@ -92,7 +128,7 @@ function uniqueColumns(table, on) {
92
128
  const accepted = table.model.uniques.map((fields) => fields.join(", "));
93
129
  throwNamed2("OKM1104", names.join(", "), accepted, `onConflict on ${table.model.name} names ${names.join(", ")}, which is not a unique constraint. Accepted: ${list(accepted)}.`);
94
130
  }
95
- function updateColumns(table, value) {
131
+ function updateColumns(table, value, allow) {
96
132
  if (!Array.isArray(value) || value.length === 0) {
97
133
  fail("OKM1120", "onConflict update must name at least one column.");
98
134
  }
@@ -104,8 +140,9 @@ function updateColumns(table, value) {
104
140
  if (column === undefined) {
105
141
  throwNamed2("OKM1120", name, table.names, `Field ${name} is not on ${table.model.name}. Accepted names: ${list(table.names)}.`);
106
142
  }
107
- if (!column.writable)
108
- refuseWrite(table.model.name, column);
143
+ if (fieldSealed(table.model, name) || column.guardUpdate || !column.writable && !(column.guarded && allow.has(name))) {
144
+ refuseWrite(table, column);
145
+ }
109
146
  columns.push(column);
110
147
  }
111
148
  return columns;
@@ -137,10 +174,16 @@ function rejectConflictKeys(keys, accepted) {
137
174
  }
138
175
  }
139
176
  function refuseWrite(table, column) {
177
+ if (fieldSealed(table.model, column.field)) {
178
+ fail("OKM1190", `Field ${table.model.name}.${column.field} is set by a trait. Input cannot set it.`);
179
+ }
180
+ if (column.guardUpdate) {
181
+ fail("OKM1190", `Field ${table.model.name}.${column.field} is a primary key. Input cannot change it.`);
182
+ }
140
183
  if (column.guarded) {
141
- fail("OKM1190", `Field ${table}.${column.field} is guarded. Input cannot set it.`);
184
+ fail("OKM1190", `Field ${table.model.name}.${column.field} is guarded. Input cannot set it.`);
142
185
  }
143
- fail("OKM1120", `Field ${table}.${column.field} cannot be written.`);
186
+ fail("OKM1120", `Field ${table.model.name}.${column.field} cannot be written.`);
144
187
  }
145
188
  export {
146
189
  finishInsert,
@@ -0,0 +1,450 @@
1
+ import {
2
+ archiveRules,
3
+ readOptionNames,
4
+ readNeedsOperatorSql,
5
+ bindCall,
6
+ compileCall,
7
+ decodeResult,
8
+ logicalIntent,
9
+ appliedRules
10
+ } from "./xrfnq5k8.js";
11
+ import {
12
+ OkmError2,
13
+ safe2,
14
+ throwNamed2
15
+ } from "./52szzakm.js";
16
+
17
+ // src/runtime/client.ts
18
+ var PLAN_LIMIT = 64;
19
+ var SINGLE_ENDPOINT = {
20
+ endpoint: "primary",
21
+ role: "primary",
22
+ reason: "single-endpoint"
23
+ };
24
+ function createClient(schema, pool, options) {
25
+ const connected = checkServer(pool, schema, options.http, options.requireMeta === true, callOptions(options), {
26
+ ...options.catalog !== undefined ? { catalog: options.catalog } : {},
27
+ ...options.catalogDir !== undefined ? { catalogDir: options.catalogDir } : {}
28
+ });
29
+ const session = {
30
+ schema,
31
+ pool,
32
+ ownsPool: options.ownsPool,
33
+ http: options.http,
34
+ includeValues: options.includeValues === true,
35
+ logger: options.logger,
36
+ connected,
37
+ cache: new Map,
38
+ generators: options.generators,
39
+ timeouts: options.timeouts,
40
+ hookm: options.hookm,
41
+ closing: { current: undefined }
42
+ };
43
+ return openClient(session);
44
+ }
45
+ function openClient(session) {
46
+ const names = Object.keys(session.schema.model);
47
+ const tables = {};
48
+ for (const name of names)
49
+ tables[name] = tableApi(session, name);
50
+ const close = () => {
51
+ if (!session.ownsPool)
52
+ return Promise.resolve();
53
+ session.closing.current ??= session.pool.close();
54
+ return session.closing.current;
55
+ };
56
+ const client = {
57
+ ...tables,
58
+ table(name) {
59
+ const found = tables[name];
60
+ if (found !== undefined)
61
+ return found;
62
+ try {
63
+ if (session.schema.model[name] !== undefined && session.schema.tenancy !== undefined && session.scope === undefined) {
64
+ session.schema.tenancy.missing(name);
65
+ }
66
+ throwNamed2("OKM1120", name, names, `Table ${name} is not in the schema. Accepted names: ${names.join(", ")}.`);
67
+ } catch (error) {
68
+ if (error instanceof OkmError2)
69
+ throw attachHttp(session.http, error);
70
+ throw error;
71
+ }
72
+ },
73
+ close,
74
+ connected: session.connected,
75
+ tx: (...args) => import("./m78s7898.js").then((mod) => mod.tx(session, args)),
76
+ batch: (ops, options) => batchHandle(session, ops, options),
77
+ ...session.tx?.extras
78
+ };
79
+ const hooks = session.schema.hooks;
80
+ if (hooks !== undefined) {
81
+ for (const hook of hooks) {
82
+ hook(client, {
83
+ names,
84
+ tables,
85
+ scoped: session.scope !== undefined,
86
+ open: (scope) => openClient({ ...session, scope })
87
+ });
88
+ }
89
+ }
90
+ attachAsyncDispose(client, close);
91
+ return client;
92
+ }
93
+ function attachAsyncDispose(client, close) {
94
+ const symbol = Symbol.asyncDispose;
95
+ if (typeof symbol !== "symbol")
96
+ return;
97
+ Object.defineProperty(client, symbol, {
98
+ configurable: true,
99
+ enumerable: false,
100
+ writable: true,
101
+ value: () => close()
102
+ });
103
+ }
104
+ function tableApi(session, table, view, uses) {
105
+ const base = { uses };
106
+ const mods = { archive: view, uses };
107
+ const api = {
108
+ find(options = {}) {
109
+ if ("lock" in options) {
110
+ return lazyRead(session, () => import("./ydaz1sv3.js"), table, options, base, view);
111
+ }
112
+ return start(session, "find", table, options, base, view);
113
+ },
114
+ one(options = {}) {
115
+ return start(session, "one", table, options, base, view);
116
+ },
117
+ count(options = {}) {
118
+ return start(session, "count", table, options, base, view);
119
+ },
120
+ exists(options = {}) {
121
+ return start(session, "exists", table, options, base, view);
122
+ },
123
+ page(options) {
124
+ return lazyRead(session, () => import("./p24x2334.js"), table, options, base, view);
125
+ },
126
+ aggregate(options = {}) {
127
+ return lazyRead(session, () => import("./3ekj9x92.js"), table, options, base, view);
128
+ },
129
+ insert(data, options = {}) {
130
+ return writeHandle(session, "insert", table, data, options, mods);
131
+ },
132
+ update(target, options = {}) {
133
+ return writeHandle(session, "update", table, target, options, mods);
134
+ },
135
+ delete(target, options = {}) {
136
+ return writeHandle(session, "delete", table, target, options, mods);
137
+ }
138
+ };
139
+ const hooks = session.schema.hooks;
140
+ if (hooks !== undefined) {
141
+ for (const hook of hooks) {
142
+ hook(api, {
143
+ table,
144
+ ...view !== undefined ? { view } : {},
145
+ uses,
146
+ reopen: (next) => tableApi(session, table, next, uses),
147
+ session
148
+ });
149
+ }
150
+ }
151
+ for (const name in session.schema.model[table]?.presets) {
152
+ api[name] = (...args) => tableApi(session, table, view, [uses, name, args]);
153
+ }
154
+ return api;
155
+ }
156
+ function batchHandle(session, ops, options, replica) {
157
+ return queryHandle(() => import("./mt5wswjz.js").then((mod) => mod.batch(session, ops, options, replica)), {
158
+ replica: () => batchHandle(session, ops, options, true)
159
+ });
160
+ }
161
+ var writers;
162
+ function loadWrite() {
163
+ writers ??= import("./xva8v7qk.js");
164
+ return writers;
165
+ }
166
+ function queryHandle(run, extra) {
167
+ let pending;
168
+ const once = () => {
169
+ pending ??= run();
170
+ return pending;
171
+ };
172
+ const self = {
173
+ then(onFulfilled, onRejected) {
174
+ return once().then(onFulfilled, onRejected);
175
+ },
176
+ catch(onRejected) {
177
+ return self.then(undefined, onRejected);
178
+ },
179
+ finally(fn) {
180
+ return self.then((value) => {
181
+ fn();
182
+ return value;
183
+ }, (error) => {
184
+ fn();
185
+ throw error;
186
+ });
187
+ },
188
+ safe() {
189
+ return safe2(once());
190
+ },
191
+ ...extra
192
+ };
193
+ return self;
194
+ }
195
+ function writeHandle(session, op, table, input, options, mods) {
196
+ return queryHandle(() => runWrite(session, op, table, input, options, mods), {
197
+ "~plan": () => runWrite(session, op, table, input, options, mods, true),
198
+ sql() {
199
+ return loadWrite().then((mod) => mod.explainWrite(session.schema, op, table, input, options, mods, session.generators, session.scope));
200
+ },
201
+ expect(count) {
202
+ return writeHandle(session, op, table, input, options, { ...mods, expect: count });
203
+ },
204
+ all(reason) {
205
+ return writeHandle(session, op, table, input, options, { ...mods, all: reason });
206
+ }
207
+ });
208
+ }
209
+ async function runWrite(session, op, table, input, options, mods, plan) {
210
+ await session.connected;
211
+ const mod = await loadWrite();
212
+ try {
213
+ return await mod.executeWrite(session, op, table, input, options, mods, session.scope, plan);
214
+ } catch (error) {
215
+ throw logged(session, await mapError(session, error));
216
+ }
217
+ }
218
+ function start(session, op, table, options, mods, view) {
219
+ const model = session.schema.model[table];
220
+ const call = readCall(op, table, options, mods.all, session.scope, model, session.schema, view);
221
+ return readHandle(session, table, call, mods, async (plan, rows) => {
222
+ const value = await decodeRows(plan, rows, table);
223
+ if (mods.required === true && value === null) {
224
+ throw new OkmError2("not_found", `one() on ${table} matched no row.`, withHttp(session.http, { kind: "not_found", table }));
225
+ }
226
+ return value;
227
+ }, (prepare) => ({
228
+ all(reason) {
229
+ return start(session, op, table, options, { ...mods, all: reason }, view);
230
+ },
231
+ required() {
232
+ return start(session, op, table, options, { ...mods, required: true }, view);
233
+ },
234
+ stream() {
235
+ return streamLazy(session, call, prepare);
236
+ }
237
+ }));
238
+ }
239
+ function lazyRead(session, load, table, options, mods, view) {
240
+ const read = () => load().then((mod) => ({ it: mod.build(session, table, options, mods, view) }));
241
+ return queryHandle(() => read().then((box) => box.it), {
242
+ inspect: () => read().then((box) => box.it.inspect()),
243
+ sql: () => read().then((box) => box.it.sql()),
244
+ all: (reason) => lazyRead(session, load, table, options, { ...mods, all: reason }, view)
245
+ });
246
+ }
247
+ async function decodeRows(plan, rows, table) {
248
+ return plan.outputs.includes.length === 0 ? decodeResult(plan, rows, table) : (await import("./edwqqryd.js")).decodeIncluded(plan, rows, table);
249
+ }
250
+ function readHandle(session, table, call, mods, decode, extra) {
251
+ let prepared;
252
+ const origin = call;
253
+ const prepare = async () => {
254
+ if (prepared !== undefined)
255
+ return prepared;
256
+ if (mods.uses !== undefined) {
257
+ call = (await import("./r6nwkxnt.js")).refine(session.schema, origin, mods.uses);
258
+ }
259
+ if (readNeedsOperatorSql(session.schema, call))
260
+ await loadOperatorSql();
261
+ const hooks = await hooksFor(call);
262
+ const bound = bindCall(session.schema, call, hooks);
263
+ let plan = session.cache.get(bound.key);
264
+ if (plan === undefined) {
265
+ plan = compileCall(session.schema, call, bound.key, hooks);
266
+ if (session.cache.size >= PLAN_LIMIT) {
267
+ const oldest = session.cache.keys().next().value;
268
+ if (oldest !== undefined)
269
+ session.cache.delete(oldest);
270
+ }
271
+ session.cache.set(bound.key, plan);
272
+ }
273
+ prepared = { plan, params: bound.params };
274
+ return prepared;
275
+ };
276
+ const sync = () => call.include === undefined && mods.uses === undefined && !readNeedsOperatorSql(session.schema, call);
277
+ const run = async () => {
278
+ await session.connected;
279
+ const { plan, params } = await prepare();
280
+ try {
281
+ const result = await session.pool.execute(plan.text, params, callOptions(call, session.timeouts?.statement));
282
+ if (session.hookm && result.notices.length) {
283
+ import("./96ps4g1z.js").then((mod) => mod.notices(session.hookm, result.notices));
284
+ }
285
+ return await decode(plan, result.rows);
286
+ } catch (error) {
287
+ const mapped = await mapError(session, error);
288
+ if (session.schema.model[table]?.conceal !== true)
289
+ throw logged(session, mapped);
290
+ const { scrubCall } = await import("./e6wg00wd.js");
291
+ throw logged(session, scrubCall(mapped, session.schema, call));
292
+ }
293
+ };
294
+ return queryHandle(run, {
295
+ inspect() {
296
+ const source = session.schema.model[table]?.source;
297
+ if (call.include === undefined && prepared !== undefined) {
298
+ return finish(session, inspection(prepared.plan, prepared.params, call, source), call);
299
+ }
300
+ if (sync()) {
301
+ const bound = bindNow(session.schema, call);
302
+ prepared = bound;
303
+ return finish(session, inspection(bound.plan, bound.params, call, source), call);
304
+ }
305
+ return prepare().then(({ plan, params }) => finish(session, inspection(plan, params, call, source), call));
306
+ },
307
+ sql() {
308
+ if (call.include === undefined && prepared !== undefined) {
309
+ return { text: prepared.plan.text, params: prepared.params };
310
+ }
311
+ if (sync()) {
312
+ const { plan, params } = bindNow(session.schema, call);
313
+ prepared = { plan, params };
314
+ return { text: plan.text, params };
315
+ }
316
+ return prepare().then(({ plan, params }) => ({ text: plan.text, params }));
317
+ },
318
+ ...extra?.(prepare)
319
+ });
320
+ }
321
+ function streamLazy(session, call, prepare) {
322
+ return async function* () {
323
+ const { streamRows } = await import("./bryqk9k9.js");
324
+ yield* streamRows(session, call, prepare, (error) => logged(session, error));
325
+ }();
326
+ }
327
+ function archiveRecord(model, view) {
328
+ if (model?.archive === undefined)
329
+ return;
330
+ const rules = archiveRules(model, view);
331
+ if (rules === undefined)
332
+ return;
333
+ return { ruleLines: rules };
334
+ }
335
+ function readCall(op, table, options, all, scope, model, schema, view) {
336
+ const record = options;
337
+ const accepted = readOptionNames(op);
338
+ for (const key of Object.keys(record)) {
339
+ if (!accepted.includes(key)) {
340
+ throwNamed2("OKM1120", key, accepted, `Option ${key} is not accepted by ${op}. Accepted options: ${accepted.join(", ")}.`);
341
+ }
342
+ }
343
+ return {
344
+ op,
345
+ table,
346
+ ...record.where !== undefined ? { where: record.where } : {},
347
+ ...record.select !== undefined ? { select: record.select } : {},
348
+ ...record.orderBy !== undefined ? { orderBy: record.orderBy } : {},
349
+ ...record.limit !== undefined ? { limit: record.limit } : {},
350
+ ...record.include !== undefined ? { include: record.include } : {},
351
+ ...callOptions(record),
352
+ ...all !== undefined ? { all } : {},
353
+ ...scope !== undefined ? { scope } : {},
354
+ ...schema.tenancy !== undefined && model !== undefined ? { tenancyRules: schema.tenancy.rules(table, model.source, scope) } : {},
355
+ ...view !== undefined ? { archive: view } : {},
356
+ ...archiveRecord(model, view)
357
+ };
358
+ }
359
+ async function checkServer(pool, schema, http, requireMeta, options, source) {
360
+ const server = await import("./ty3v3hfk.js");
361
+ let rows;
362
+ try {
363
+ const result = await pool.execute(server.versionQuery, undefined, options);
364
+ rows = result.rows;
365
+ } catch (error) {
366
+ const { mapPostgresError } = await import("./s6gqfn5j.js");
367
+ throw mapPostgresError(error, mapOptions(http, false));
368
+ }
369
+ await server.acceptServer(pool, schema, rows, http, requireMeta, options, source);
370
+ }
371
+ async function mapError(session, error) {
372
+ if (error instanceof OkmError2) {
373
+ return session.http === undefined ? error : new OkmError2(error.code, error.message, { ...errorFields(error), http: session.http });
374
+ }
375
+ const { mapPostgresError } = await import("./s6gqfn5j.js");
376
+ return mapPostgresError(error, mapOptions(session.http, session.includeValues));
377
+ }
378
+ function errorFields(error) {
379
+ return {
380
+ kind: error.kind,
381
+ ...error.table !== undefined ? { table: error.table } : {},
382
+ ...error.columns.length > 0 ? { columns: error.columns } : {},
383
+ fix: error.fix
384
+ };
385
+ }
386
+ var includeHooks;
387
+ var operatorSql;
388
+ function loadOperatorSql() {
389
+ operatorSql ??= import("./axhk06q1.js").then(() => {
390
+ return;
391
+ });
392
+ return operatorSql;
393
+ }
394
+ function hooksFor(call) {
395
+ if (call.include === undefined)
396
+ return Promise.resolve(undefined);
397
+ includeHooks ??= import("./edwqqryd.js").then((mod) => mod.includeHooks);
398
+ return includeHooks;
399
+ }
400
+ function bindNow(schema, call) {
401
+ const bound = bindCall(schema, call);
402
+ const plan = compileCall(schema, call, bound.key);
403
+ return { plan, params: bound.params };
404
+ }
405
+ function finish(session, view, call) {
406
+ if (session.schema.model[call.table]?.conceal !== true)
407
+ return view;
408
+ return import("./e6wg00wd.js").then((mod) => mod.redactView(session.schema, view, call));
409
+ }
410
+ function inspection(plan, params, call, source) {
411
+ return {
412
+ intent: logicalIntent(call),
413
+ rules: appliedRules(call, source),
414
+ plan: { strategy: "postgres:single-statement", statements: 1, fingerprint: plan.fingerprint },
415
+ sql: { text: plan.text, params },
416
+ routing: SINGLE_ENDPOINT
417
+ };
418
+ }
419
+ function withHttp(http, options) {
420
+ return http === undefined ? options : { ...options, http };
421
+ }
422
+ function attachHttp(http, error) {
423
+ if (http === undefined)
424
+ return error;
425
+ return new OkmError2(error.code, error.message, { ...errorFields(error), http });
426
+ }
427
+ function callOptions(input, statement) {
428
+ const timeout = input.timeout ?? statement;
429
+ if (input.signal === undefined && timeout === undefined)
430
+ return;
431
+ return {
432
+ ...input.signal !== undefined ? { signal: input.signal } : {},
433
+ ...timeout !== undefined ? { timeout } : {}
434
+ };
435
+ }
436
+ function mapOptions(http, includeValues) {
437
+ return {
438
+ ...http !== undefined ? { http } : {},
439
+ ...includeValues ? { includeValues: true } : {}
440
+ };
441
+ }
442
+ async function settleCall(session, error) {
443
+ throw logged(session, await mapError(session, error));
444
+ }
445
+ function logged(session, error) {
446
+ session.logger?.error?.({ code: error.code, summary: error.summary });
447
+ return error;
448
+ }
449
+
450
+ export { createClient, openClient, queryHandle, decodeRows, readHandle, readCall, withHttp, attachHttp, settleCall };
@@ -0,0 +1,33 @@
1
+ // src/adapters/pg/watch.ts
2
+ function openWatch(options) {
3
+ let kind;
4
+ const controller = new AbortController;
5
+ const onAbort = () => {
6
+ if (kind === undefined)
7
+ kind = "cancelled";
8
+ controller.abort();
9
+ };
10
+ options.signal?.addEventListener("abort", onAbort, { once: true });
11
+ let timer;
12
+ if (options.timeout !== undefined) {
13
+ timer = setTimeout(() => {
14
+ if (kind === undefined)
15
+ kind = "timeout";
16
+ controller.abort();
17
+ }, options.timeout);
18
+ }
19
+ return {
20
+ signal: controller.signal,
21
+ finish() {
22
+ if (timer !== undefined)
23
+ clearTimeout(timer);
24
+ options.signal?.removeEventListener("abort", onAbort);
25
+ },
26
+ reason() {
27
+ return kind;
28
+ }
29
+ };
30
+ }
31
+ export {
32
+ openWatch
33
+ };
@@ -0,0 +1,31 @@
1
+ // src/contracts/location.ts
2
+ function callerLocation(skip) {
3
+ const lines = new Error().stack?.split(`
4
+ `);
5
+ if (lines === undefined)
6
+ return;
7
+ let left = skip;
8
+ for (const line of lines) {
9
+ const slash = line.lastIndexOf("/");
10
+ if (slash < 0)
11
+ continue;
12
+ const tail = line.slice(slash + 1);
13
+ const colon = tail.indexOf(":");
14
+ if (colon < 1 || tail.startsWith("location."))
15
+ continue;
16
+ if (left > 0) {
17
+ left -= 1;
18
+ continue;
19
+ }
20
+ const end = tail.indexOf(":", colon + 1);
21
+ if (end < 0)
22
+ return;
23
+ return `${tail.slice(0, colon)}:${tail.slice(colon + 1, end)}`;
24
+ }
25
+ return;
26
+ }
27
+ function withLocation(message, source) {
28
+ return source === undefined ? message : `${message} (${source})`;
29
+ }
30
+
31
+ export { callerLocation, withLocation };
@@ -1,11 +1,11 @@
1
1
  import {
2
2
  open3
3
- } from "./fgqgsb5z.js";
3
+ } from "./75xkjv0t.js";
4
4
  import {
5
5
  PGLITE_CAPABILITIES,
6
6
  readCapability2,
7
7
  hasCapability2
8
- } from "./xy79j5hq.js";
8
+ } from "./rrstp3kb.js";
9
9
  export {
10
10
  PGLITE_CAPABILITIES as capabilities,
11
11
  hasCapability2 as hasCapability,
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  OkmError2
3
- } from "./ycwz42az.js";
3
+ } from "./52szzakm.js";
4
4
 
5
5
  // src/adapters/error.ts
6
6
  class DriverError2 extends Error {
@@ -57,6 +57,18 @@ function errorField2(error, key) {
57
57
  const value = Reflect.get(error, key);
58
58
  return typeof value === "string" && value.length > 0 ? value : undefined;
59
59
  }
60
+ function sqlstateOf(error) {
61
+ const code = errorField2(error, "code");
62
+ if (isSqlstate(code))
63
+ return code;
64
+ const errno = errorField2(error, "errno");
65
+ if (isSqlstate(errno))
66
+ return errno;
67
+ return errorField2(error, "sqlstate");
68
+ }
69
+ function isSqlstate(value) {
70
+ return value !== undefined && /^[0-9A-Z]{5}$/.test(value);
71
+ }
60
72
  function mapDriverError2(error, batchIndex) {
61
73
  if (error instanceof OkmError2)
62
74
  return error;
@@ -65,7 +77,7 @@ function mapDriverError2(error, batchIndex) {
65
77
  }
66
78
  const message = error instanceof Error ? error.message : "driver error";
67
79
  return new DriverError2(message, driverFields({
68
- sqlstate: errorField2(error, "code") ?? errorField2(error, "sqlstate"),
80
+ sqlstate: sqlstateOf(error),
69
81
  constraint: errorField2(error, "constraint_name") ?? errorField2(error, "constraint"),
70
82
  table: errorField2(error, "table_name") ?? errorField2(error, "table"),
71
83
  column: errorField2(error, "column_name") ?? errorField2(error, "column"),