interaqt 2.0.0 → 2.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -0
- package/agent/agentspace/knowledge/generator/api-reference.md +28 -5
- package/agent/agentspace/knowledge/generator/computation-implementation.md +61 -14
- package/agent/agentspace/knowledge/usage/00-mindset-shift.md +2 -0
- package/agent/agentspace/knowledge/usage/04-reactive-computations.md +158 -101
- package/agent/agentspace/knowledge/usage/05-interactions.md +67 -22
- package/agent/agentspace/knowledge/usage/08-activities.md +10 -0
- package/agent/agentspace/knowledge/usage/09-filtered-entities.md +1 -0
- package/agent/agentspace/knowledge/usage/13-testing.md +52 -99
- package/agent/agentspace/knowledge/usage/14-api-reference.md +22 -5
- package/agent/agentspace/knowledge/usage/15-entity-crud-patterns.md +89 -28
- package/agent/agentspace/knowledge/usage/18-api-exports-reference.md +10 -8
- package/agent/agentspace/knowledge/usage/19-common-anti-patterns.md +11 -2
- package/dist/builtins/interaction/Action.d.ts.map +1 -1
- package/dist/builtins/interaction/Activity.d.ts.map +1 -1
- package/dist/builtins/interaction/Attributive.d.ts.map +1 -1
- package/dist/builtins/interaction/Condition.d.ts.map +1 -1
- package/dist/builtins/interaction/Conditions.d.ts.map +1 -1
- package/dist/builtins/interaction/Data.d.ts.map +1 -1
- package/dist/builtins/interaction/Event.d.ts.map +1 -1
- package/dist/builtins/interaction/Gateway.d.ts.map +1 -1
- package/dist/builtins/interaction/Interaction.d.ts.map +1 -1
- package/dist/builtins/interaction/Payload.d.ts.map +1 -1
- package/dist/builtins/interaction/PayloadItem.d.ts.map +1 -1
- package/dist/builtins/interaction/activity/ActivityCall.d.ts.map +1 -1
- package/dist/core/Entity.d.ts.map +1 -1
- package/dist/core/EventSource.d.ts +37 -0
- package/dist/core/EventSource.d.ts.map +1 -1
- package/dist/core/Relation.d.ts.map +1 -1
- package/dist/core/init.d.ts.map +1 -1
- package/dist/core/utils.d.ts.map +1 -1
- package/dist/drivers/Mysql.d.ts +4 -3
- package/dist/drivers/Mysql.d.ts.map +1 -1
- package/dist/drivers/PGLite.d.ts +2 -2
- package/dist/drivers/PGLite.d.ts.map +1 -1
- package/dist/drivers/PostgreSQL.d.ts +2 -2
- package/dist/drivers/PostgreSQL.d.ts.map +1 -1
- package/dist/drivers/SQLite.d.ts +3 -3
- package/dist/drivers/SQLite.d.ts.map +1 -1
- package/dist/drivers.d.ts +2 -0
- package/dist/drivers.js +984 -0
- package/dist/drivers.js.map +1 -0
- package/dist/index.js +5930 -5736
- package/dist/index.js.map +1 -1
- package/dist/runtime/ComputationSourceMap.d.ts +11 -0
- package/dist/runtime/ComputationSourceMap.d.ts.map +1 -1
- package/dist/runtime/Controller.d.ts.map +1 -1
- package/dist/runtime/Scheduler.d.ts +21 -3
- package/dist/runtime/Scheduler.d.ts.map +1 -1
- package/dist/runtime/System.d.ts +1 -0
- package/dist/runtime/System.d.ts.map +1 -1
- package/dist/runtime/computations/Any.d.ts +17 -52
- package/dist/runtime/computations/Any.d.ts.map +1 -1
- package/dist/runtime/computations/Average.d.ts +15 -49
- package/dist/runtime/computations/Average.d.ts.map +1 -1
- package/dist/runtime/computations/Computation.d.ts +8 -0
- package/dist/runtime/computations/Computation.d.ts.map +1 -1
- package/dist/runtime/computations/Count.d.ts +21 -64
- package/dist/runtime/computations/Count.d.ts.map +1 -1
- package/dist/runtime/computations/Custom.d.ts.map +1 -1
- package/dist/runtime/computations/Every.d.ts +18 -52
- package/dist/runtime/computations/Every.d.ts.map +1 -1
- package/dist/runtime/computations/StateMachine.d.ts +2 -2
- package/dist/runtime/computations/StateMachine.d.ts.map +1 -1
- package/dist/runtime/computations/Summation.d.ts +15 -49
- package/dist/runtime/computations/Summation.d.ts.map +1 -1
- package/dist/runtime/computations/Transform.d.ts.map +1 -1
- package/dist/runtime/computations/WeightedSummation.d.ts +18 -60
- package/dist/runtime/computations/WeightedSummation.d.ts.map +1 -1
- package/dist/runtime/computations/aggregationTemplate.d.ts +163 -0
- package/dist/runtime/computations/aggregationTemplate.d.ts.map +1 -0
- package/dist/runtime/migration.d.ts.map +1 -1
- package/dist/storage/erstorage/AttributeQuery.d.ts.map +1 -1
- package/dist/storage/erstorage/CreationExecutor.d.ts.map +1 -1
- package/dist/storage/erstorage/DeletionExecutor.d.ts.map +1 -1
- package/dist/storage/erstorage/EntityQueryHandle.d.ts +13 -0
- package/dist/storage/erstorage/EntityQueryHandle.d.ts.map +1 -1
- package/dist/storage/erstorage/EntityToTableMap.d.ts +2 -0
- package/dist/storage/erstorage/EntityToTableMap.d.ts.map +1 -1
- package/dist/storage/erstorage/LinkInfo.d.ts +1 -0
- package/dist/storage/erstorage/LinkInfo.d.ts.map +1 -1
- package/dist/storage/erstorage/MatchExp.d.ts +3 -2
- package/dist/storage/erstorage/MatchExp.d.ts.map +1 -1
- package/dist/storage/erstorage/MergedItemProcessor.d.ts +12 -0
- package/dist/storage/erstorage/MergedItemProcessor.d.ts.map +1 -1
- package/dist/storage/erstorage/NewRecordData.d.ts +1 -0
- package/dist/storage/erstorage/NewRecordData.d.ts.map +1 -1
- package/dist/storage/erstorage/QueryExecutor.d.ts.map +1 -1
- package/dist/storage/erstorage/RecordQueryAgent.d.ts +11 -0
- package/dist/storage/erstorage/RecordQueryAgent.d.ts.map +1 -1
- package/dist/storage/erstorage/Setup.d.ts +25 -0
- package/dist/storage/erstorage/Setup.d.ts.map +1 -1
- package/dist/storage/erstorage/UpdateExecutor.d.ts.map +1 -1
- package/package.json +5 -1
package/dist/drivers.js
ADDED
|
@@ -0,0 +1,984 @@
|
|
|
1
|
+
import m from "better-sqlite3";
|
|
2
|
+
import { sqliteEncodeLiteral as N, dbConsoleLogger as g, asyncInteractionContext as l, ROW_ID_ATTR as p, defaultEncodeLiteral as S, RequireSerializableRetry as I } from "interaqt";
|
|
3
|
+
import { AsyncLocalStorage as b } from "node:async_hooks";
|
|
4
|
+
import { createHash as A } from "node:crypto";
|
|
5
|
+
import L from "pg";
|
|
6
|
+
import { PGlite as R } from "@electric-sql/pglite";
|
|
7
|
+
import E from "mysql2/promise";
|
|
8
|
+
let w = class {
|
|
9
|
+
constructor(e) {
|
|
10
|
+
this.db = e;
|
|
11
|
+
}
|
|
12
|
+
async setup() {
|
|
13
|
+
await this.db.scheme("CREATE Table IF NOT EXISTS _IDS_ (last INTEGER, name TEXT)"), await this.db.scheme('CREATE UNIQUE INDEX IF NOT EXISTS "_IDS__name_unique" ON _IDS_ (name)');
|
|
14
|
+
}
|
|
15
|
+
async getAutoId(e) {
|
|
16
|
+
return (await this.db.query(
|
|
17
|
+
`INSERT INTO _IDS_ (name, last) VALUES (?, 1)
|
|
18
|
+
ON CONFLICT(name) DO UPDATE SET last = last + 1
|
|
19
|
+
RETURNING last`,
|
|
20
|
+
[e],
|
|
21
|
+
`allocate next id for ${e}`
|
|
22
|
+
))[0].last;
|
|
23
|
+
}
|
|
24
|
+
};
|
|
25
|
+
class K {
|
|
26
|
+
constructor(e = ":memory:", t) {
|
|
27
|
+
this.file = e, this.options = t, this.supportsSelectForUpdate = !1, this.maxQueryParams = 32e3, this.transactionCapability = {
|
|
28
|
+
transactions: !0,
|
|
29
|
+
isolationLevels: ["READ COMMITTED", "SERIALIZABLE"],
|
|
30
|
+
transactionBoundConnection: !1,
|
|
31
|
+
concurrentTransactions: "unsupported",
|
|
32
|
+
nestedStrategy: "reuse",
|
|
33
|
+
notes: [
|
|
34
|
+
"SQLite uses MonoStorage fallback transaction metadata for retry paths and does not provide PostgreSQL-level concurrent dispatch isolation."
|
|
35
|
+
]
|
|
36
|
+
}, this.atomicSequenceCapability = {
|
|
37
|
+
requiresActiveTransaction: !0,
|
|
38
|
+
transactional: !0,
|
|
39
|
+
crossConnection: !1,
|
|
40
|
+
crossProcess: !1,
|
|
41
|
+
returning: !0,
|
|
42
|
+
productionSafe: !1
|
|
43
|
+
}, this.schemaDialect = {
|
|
44
|
+
name: "sqlite",
|
|
45
|
+
maxIdentifierLength: 63,
|
|
46
|
+
supportsCreateIndexIfNotExists: !0,
|
|
47
|
+
encodeLiteral: N,
|
|
48
|
+
constraints: { unique: !0, filteredUnique: !0, nonNull: !1 }
|
|
49
|
+
}, this.idSystem = new w(this), this.logger = this.options?.logger || g;
|
|
50
|
+
}
|
|
51
|
+
async open() {
|
|
52
|
+
this.db = new m(this.file, this.options), await this.idSystem.setup();
|
|
53
|
+
}
|
|
54
|
+
async openForSchemaRead() {
|
|
55
|
+
this.db = new m(this.file, this.options);
|
|
56
|
+
}
|
|
57
|
+
async setupInternalComputationState() {
|
|
58
|
+
await this.scheme(`
|
|
59
|
+
CREATE TABLE IF NOT EXISTS "_ComputationState_" (
|
|
60
|
+
"key" TEXT PRIMARY KEY,
|
|
61
|
+
"numberValue" NUMERIC NULL,
|
|
62
|
+
"booleanValue" BOOLEAN NULL,
|
|
63
|
+
"stringValue" TEXT NULL,
|
|
64
|
+
"jsonValue" JSON NULL
|
|
65
|
+
)`, "setup computation state table");
|
|
66
|
+
}
|
|
67
|
+
async setupScopedSequenceState() {
|
|
68
|
+
await this.scheme(`
|
|
69
|
+
CREATE TABLE IF NOT EXISTS "_ScopedSequence_" (
|
|
70
|
+
"sequenceName" TEXT NOT NULL,
|
|
71
|
+
"scopeKey" TEXT NOT NULL,
|
|
72
|
+
"scope" JSON NOT NULL,
|
|
73
|
+
"lastValue" NUMERIC NOT NULL,
|
|
74
|
+
PRIMARY KEY ("sequenceName", "scopeKey")
|
|
75
|
+
)`, "setup scoped sequence table");
|
|
76
|
+
}
|
|
77
|
+
async query(e, t = [], s = "") {
|
|
78
|
+
const r = l.getStore(), n = this.logger.child(r?.logContext || {}), i = t.map((o) => o === !1 ? 0 : o === !0 ? 1 : o);
|
|
79
|
+
return n.info({
|
|
80
|
+
type: "query",
|
|
81
|
+
name: s,
|
|
82
|
+
sql: e,
|
|
83
|
+
params: i
|
|
84
|
+
}), this.db.prepare(e).all(...i);
|
|
85
|
+
}
|
|
86
|
+
async update(e, t, s, r = "") {
|
|
87
|
+
const n = l.getStore(), i = this.logger.child(n?.logContext || {}), o = `${e} ${s ? `RETURNING ${s} AS id` : ""}`, a = t.map((c) => typeof c == "object" && c !== null ? JSON.stringify(c) : c === !1 ? 0 : c === !0 ? 1 : c);
|
|
88
|
+
return i.info({
|
|
89
|
+
type: "update",
|
|
90
|
+
name: r,
|
|
91
|
+
sql: o,
|
|
92
|
+
params: a
|
|
93
|
+
}), s ? this.db.prepare(o).all(...a) : this.db.prepare(o).run(...a);
|
|
94
|
+
}
|
|
95
|
+
async insert(e, t, s = "") {
|
|
96
|
+
const r = l.getStore(), n = this.logger.child(r?.logContext || {}), i = t.map((a) => typeof a == "object" && a !== null ? JSON.stringify(a) : a === !1 ? 0 : a === !0 ? 1 : a);
|
|
97
|
+
return n.info({
|
|
98
|
+
type: "insert",
|
|
99
|
+
name: s,
|
|
100
|
+
sql: e,
|
|
101
|
+
params: i
|
|
102
|
+
}), this.db.prepare(`${e} RETURNING ${p}`).all(...i)[0];
|
|
103
|
+
}
|
|
104
|
+
async delete(e, t, s = "") {
|
|
105
|
+
const r = l.getStore(), n = this.logger.child(r?.logContext || {}), i = t.map((o) => o === !1 ? 0 : o === !0 ? 1 : o);
|
|
106
|
+
return n.info({
|
|
107
|
+
type: "delete",
|
|
108
|
+
name: s,
|
|
109
|
+
sql: e,
|
|
110
|
+
params: i
|
|
111
|
+
}), this.db.prepare(e).run(...i);
|
|
112
|
+
}
|
|
113
|
+
async scheme(e, t = "") {
|
|
114
|
+
const s = l.getStore();
|
|
115
|
+
return this.logger.child(s?.logContext || {}).info({
|
|
116
|
+
type: "scheme",
|
|
117
|
+
name: t,
|
|
118
|
+
sql: e
|
|
119
|
+
}), this.db.prepare(e).run();
|
|
120
|
+
}
|
|
121
|
+
async close() {
|
|
122
|
+
this.db.close();
|
|
123
|
+
}
|
|
124
|
+
async getAutoId(e) {
|
|
125
|
+
return this.idSystem.getAutoId(e);
|
|
126
|
+
}
|
|
127
|
+
parseMatchExpression(e, t, s, r, n, i, o) {
|
|
128
|
+
if (r === "JSON" && t[0].toLowerCase() === "contains")
|
|
129
|
+
return {
|
|
130
|
+
fieldValue: `NOT NULL AND EXISTS (
|
|
131
|
+
SELECT 1
|
|
132
|
+
FROM json_each(${s})
|
|
133
|
+
WHERE json_each.value = ${o()}
|
|
134
|
+
)`,
|
|
135
|
+
fieldParams: [t[1]]
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
mapToDBFieldType(e, t) {
|
|
139
|
+
return e === "pk" ? "INTEGER PRIMARY KEY" : e === "id" ? "INT" : t || e === "object" || e === "json" ? "JSON" : e === "string" ? "TEXT" : e === "boolean" ? "INT(2)" : e === "number" || e === "timestamp" ? "INT" : e;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
const { Client: d, Pool: C } = L;
|
|
143
|
+
let O = class {
|
|
144
|
+
constructor(e) {
|
|
145
|
+
this.db = e, this.initialized = /* @__PURE__ */ new Set(), this.recordToSequenceName = /* @__PURE__ */ new Map();
|
|
146
|
+
}
|
|
147
|
+
setup() {
|
|
148
|
+
return this.db.scheme('CREATE Table IF NOT EXISTS "_IDS_" (last INTEGER, name TEXT)');
|
|
149
|
+
}
|
|
150
|
+
sanitizeIdentifierPart(e) {
|
|
151
|
+
return (e.replace(/[^a-zA-Z0-9_]/g, "_").replace(/^_+/, "") || "record").slice(0, 32);
|
|
152
|
+
}
|
|
153
|
+
sequenceName(e) {
|
|
154
|
+
return this.sequenceNameForKey(e, e);
|
|
155
|
+
}
|
|
156
|
+
sequenceNameForKey(e, t) {
|
|
157
|
+
return `seq_${A("sha1").update(e).digest("hex").slice(0, 12)}_${this.sanitizeIdentifierPart(t)}`.slice(0, 63);
|
|
158
|
+
}
|
|
159
|
+
quoteIdentifier(e) {
|
|
160
|
+
return `"${e.replace(/"/g, '""')}"`;
|
|
161
|
+
}
|
|
162
|
+
async setupSequences(e) {
|
|
163
|
+
const t = (await this.db.query(
|
|
164
|
+
"SELECT to_regclass($1) AS exists",
|
|
165
|
+
['"_IDS_"'],
|
|
166
|
+
"check legacy id table"
|
|
167
|
+
))[0]?.exists, s = /* @__PURE__ */ new Map();
|
|
168
|
+
for (const r of e) {
|
|
169
|
+
const n = this.sequenceNameForKey(`${r.tableName}.${r.idField}`, r.tableName);
|
|
170
|
+
this.recordToSequenceName.set(r.recordName, n);
|
|
171
|
+
const i = this.quoteIdentifier(n);
|
|
172
|
+
await this.db.scheme(`CREATE SEQUENCE IF NOT EXISTS ${i} START WITH 1`, `create sequence ${r.recordName}`);
|
|
173
|
+
const o = await this.db.query(
|
|
174
|
+
`SELECT COALESCE(MAX("${r.idField}"), 0) AS max FROM ${this.quoteIdentifier(r.tableName)}`,
|
|
175
|
+
[],
|
|
176
|
+
`read max id for ${r.recordName}`
|
|
177
|
+
);
|
|
178
|
+
let a = 0;
|
|
179
|
+
if (t) {
|
|
180
|
+
const T = await this.db.query(
|
|
181
|
+
'SELECT COALESCE(MAX("last"), 0) AS last FROM "_IDS_" WHERE "name" = $1',
|
|
182
|
+
[r.recordName],
|
|
183
|
+
`read legacy id for ${r.recordName}`
|
|
184
|
+
);
|
|
185
|
+
a = Number(T[0]?.last ?? 0);
|
|
186
|
+
}
|
|
187
|
+
const c = Math.max(Number(o[0]?.max ?? 0), a);
|
|
188
|
+
s.set(i, Math.max(s.get(i) ?? 0, c)), this.initialized.add(r.recordName);
|
|
189
|
+
}
|
|
190
|
+
for (const [r, n] of s)
|
|
191
|
+
n >= 1 && await this.db.query(
|
|
192
|
+
`SELECT setval($1::regclass, $2, true) FROM ${r} WHERE NOT is_called OR last_value < $2`,
|
|
193
|
+
[r, n],
|
|
194
|
+
`advance sequence ${r}`
|
|
195
|
+
);
|
|
196
|
+
}
|
|
197
|
+
async getAutoId(e) {
|
|
198
|
+
if (!this.initialized.has(e))
|
|
199
|
+
throw new Error(`PostgreSQL sequence for ${e} is not initialized. Run storage setup before creating records.`);
|
|
200
|
+
const t = this.recordToSequenceName.get(e) ?? this.sequenceName(e);
|
|
201
|
+
return (await this.db.query(
|
|
202
|
+
"SELECT nextval($1::regclass) AS id",
|
|
203
|
+
[this.quoteIdentifier(t)],
|
|
204
|
+
`next id for ${e}`
|
|
205
|
+
))[0].id;
|
|
206
|
+
}
|
|
207
|
+
};
|
|
208
|
+
class W {
|
|
209
|
+
constructor(e, t = {}) {
|
|
210
|
+
this.database = e, this.options = t, this.transactionContext = new b(), this.supportsSelectForUpdate = !0, this.maxQueryParams = 65e3, this.transactionCapability = {
|
|
211
|
+
transactions: !0,
|
|
212
|
+
isolationLevels: ["READ COMMITTED", "SERIALIZABLE"],
|
|
213
|
+
transactionBoundConnection: !0,
|
|
214
|
+
concurrentTransactions: "database",
|
|
215
|
+
nestedStrategy: "reuse"
|
|
216
|
+
}, this.atomicSequenceCapability = {
|
|
217
|
+
requiresActiveTransaction: !0,
|
|
218
|
+
transactional: !0,
|
|
219
|
+
crossConnection: !0,
|
|
220
|
+
crossProcess: !0,
|
|
221
|
+
returning: !0,
|
|
222
|
+
productionSafe: !0
|
|
223
|
+
}, this.schemaDialect = {
|
|
224
|
+
name: "postgres",
|
|
225
|
+
maxIdentifierLength: 63,
|
|
226
|
+
supportsCreateIndexIfNotExists: !0,
|
|
227
|
+
encodeLiteral: S,
|
|
228
|
+
constraints: { unique: !0, filteredUnique: !0, nonNull: !0 }
|
|
229
|
+
}, this.idSystem = new O(this), this.logger = this.options?.logger || g, this.db = new d({ ...t });
|
|
230
|
+
}
|
|
231
|
+
async open(e = !1) {
|
|
232
|
+
this.pool && e && (await this.pool.end(), this.pool = void 0);
|
|
233
|
+
const t = new d({
|
|
234
|
+
...this.options
|
|
235
|
+
});
|
|
236
|
+
await t.connect(), (await t.query("SELECT FROM pg_database WHERE datname = $1", [this.database])).rows.length === 0 ? await t.query(`CREATE DATABASE "${this.database}"`) : e && (await t.query(`DROP DATABASE "${this.database}" WITH (FORCE)`), await t.query(`CREATE DATABASE "${this.database}"`)), await t.end(), this.pool || (this.pool = this.createPool(), this.db = new d({
|
|
237
|
+
...this.options,
|
|
238
|
+
database: this.database
|
|
239
|
+
}));
|
|
240
|
+
}
|
|
241
|
+
async openForSchemaRead() {
|
|
242
|
+
this.pool || (this.pool = this.createPool(), this.db = new d({
|
|
243
|
+
...this.options,
|
|
244
|
+
database: this.database
|
|
245
|
+
}));
|
|
246
|
+
}
|
|
247
|
+
createPool() {
|
|
248
|
+
const e = new C({
|
|
249
|
+
...this.options,
|
|
250
|
+
database: this.database
|
|
251
|
+
});
|
|
252
|
+
return e.on("error", (t) => {
|
|
253
|
+
this.logger.error({
|
|
254
|
+
type: "pool",
|
|
255
|
+
name: "idle client error",
|
|
256
|
+
sql: "",
|
|
257
|
+
error: t instanceof Error ? t.message : String(t)
|
|
258
|
+
});
|
|
259
|
+
}), e;
|
|
260
|
+
}
|
|
261
|
+
getQueryable() {
|
|
262
|
+
const e = this.transactionContext.getStore();
|
|
263
|
+
if (e && e.depth > 0) return e.client;
|
|
264
|
+
if (!this.pool)
|
|
265
|
+
throw new Error("PostgreSQL pool is not initialized. Call open() before querying.");
|
|
266
|
+
return this.pool;
|
|
267
|
+
}
|
|
268
|
+
async runInTransaction(e, t) {
|
|
269
|
+
const s = this.transactionContext.getStore();
|
|
270
|
+
if (s && s.depth > 0) {
|
|
271
|
+
if (s.isolation !== "SERIALIZABLE" && (e.isolation ?? "READ COMMITTED") === "SERIALIZABLE")
|
|
272
|
+
throw new I(`${e.name || "nested transaction"} requires SERIALIZABLE isolation`);
|
|
273
|
+
s.depth++;
|
|
274
|
+
try {
|
|
275
|
+
return await t();
|
|
276
|
+
} finally {
|
|
277
|
+
s.depth--;
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
if (!this.pool)
|
|
281
|
+
throw new Error("PostgreSQL pool is not initialized. Call open() before starting a transaction.");
|
|
282
|
+
const r = e.isolation ?? "READ COMMITTED", n = await this.pool.connect(), i = { client: n, depth: 1, isolation: r };
|
|
283
|
+
let o = !1;
|
|
284
|
+
try {
|
|
285
|
+
await n.query(`BEGIN ISOLATION LEVEL ${r}`);
|
|
286
|
+
const a = await this.transactionContext.run(i, t);
|
|
287
|
+
return await n.query("COMMIT"), a;
|
|
288
|
+
} catch (a) {
|
|
289
|
+
try {
|
|
290
|
+
await n.query("ROLLBACK");
|
|
291
|
+
} finally {
|
|
292
|
+
n.release(), o = !0;
|
|
293
|
+
}
|
|
294
|
+
throw a;
|
|
295
|
+
} finally {
|
|
296
|
+
o || n.release();
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
async setupInternalComputationState() {
|
|
300
|
+
await this.scheme(`
|
|
301
|
+
CREATE TABLE IF NOT EXISTS "_ComputationState_" (
|
|
302
|
+
"key" TEXT PRIMARY KEY,
|
|
303
|
+
"numberValue" NUMERIC NULL,
|
|
304
|
+
"booleanValue" BOOLEAN NULL,
|
|
305
|
+
"stringValue" TEXT NULL,
|
|
306
|
+
"jsonValue" JSONB NULL
|
|
307
|
+
)`, "setup computation state table");
|
|
308
|
+
}
|
|
309
|
+
async setupScopedSequenceState() {
|
|
310
|
+
await this.scheme(`
|
|
311
|
+
CREATE TABLE IF NOT EXISTS "_ScopedSequence_" (
|
|
312
|
+
"sequenceName" TEXT NOT NULL,
|
|
313
|
+
"scopeKey" TEXT NOT NULL,
|
|
314
|
+
"scope" JSONB NOT NULL,
|
|
315
|
+
"lastValue" NUMERIC NOT NULL,
|
|
316
|
+
PRIMARY KEY ("sequenceName", "scopeKey")
|
|
317
|
+
)`, "setup scoped sequence table");
|
|
318
|
+
}
|
|
319
|
+
async query(e, t = [], s = "") {
|
|
320
|
+
const r = l.getStore(), n = this.logger.child(r?.logContext || {}), i = t;
|
|
321
|
+
return n.info({
|
|
322
|
+
type: "query",
|
|
323
|
+
name: s,
|
|
324
|
+
sql: e,
|
|
325
|
+
params: i
|
|
326
|
+
}), (await this.getQueryable().query(e, i)).rows;
|
|
327
|
+
}
|
|
328
|
+
async update(e, t, s, r = "") {
|
|
329
|
+
const n = l.getStore(), i = this.logger.child(n?.logContext || {}), o = `${e} ${s ? `RETURNING "${s}" AS id` : ""}`, a = t.map((c) => typeof c == "object" && c !== null ? JSON.stringify(c) : c);
|
|
330
|
+
return i.info({
|
|
331
|
+
type: "update",
|
|
332
|
+
name: r,
|
|
333
|
+
sql: o,
|
|
334
|
+
params: a
|
|
335
|
+
}), (await this.getQueryable().query(o, a)).rows;
|
|
336
|
+
}
|
|
337
|
+
async insert(e, t, s = "") {
|
|
338
|
+
const r = l.getStore(), n = this.logger.child(r?.logContext || {}), i = t.map((a) => typeof a == "object" && a !== null ? JSON.stringify(a) : a);
|
|
339
|
+
n.info({
|
|
340
|
+
type: "insert",
|
|
341
|
+
name: s,
|
|
342
|
+
sql: e,
|
|
343
|
+
params: i
|
|
344
|
+
});
|
|
345
|
+
const o = `${e} RETURNING "${p}"`;
|
|
346
|
+
return (await this.getQueryable().query(o, i)).rows[0];
|
|
347
|
+
}
|
|
348
|
+
async delete(e, t, s = "") {
|
|
349
|
+
const r = l.getStore(), n = this.logger.child(r?.logContext || {}), i = t;
|
|
350
|
+
return n.info({
|
|
351
|
+
type: "delete",
|
|
352
|
+
name: s,
|
|
353
|
+
sql: e,
|
|
354
|
+
params: i
|
|
355
|
+
}), (await this.getQueryable().query(e, i)).rows;
|
|
356
|
+
}
|
|
357
|
+
async scheme(e, t = "") {
|
|
358
|
+
const s = l.getStore();
|
|
359
|
+
return this.logger.child(s?.logContext || {}).info({
|
|
360
|
+
type: "scheme",
|
|
361
|
+
name: t,
|
|
362
|
+
sql: e
|
|
363
|
+
}), await this.getQueryable().query(e);
|
|
364
|
+
}
|
|
365
|
+
close() {
|
|
366
|
+
return this.pool ? this.pool.end() : this.db.end();
|
|
367
|
+
}
|
|
368
|
+
async getAutoId(e) {
|
|
369
|
+
return this.idSystem.getAutoId(e);
|
|
370
|
+
}
|
|
371
|
+
setupRecordSequences(e) {
|
|
372
|
+
return this.idSystem.setupSequences(e);
|
|
373
|
+
}
|
|
374
|
+
parseMatchExpression(e, t, s, r, n, i, o) {
|
|
375
|
+
if (r === "JSON") {
|
|
376
|
+
if (t[0].toLowerCase() === "contains") {
|
|
377
|
+
const a = s.split(".").map((c) => `"${c}"`).join(".");
|
|
378
|
+
return {
|
|
379
|
+
fieldValue: `IS NOT NULL AND ${o()} = ANY (SELECT json_array_elements_text(${a}))`,
|
|
380
|
+
fieldParams: [t[1]]
|
|
381
|
+
};
|
|
382
|
+
}
|
|
383
|
+
if (t[0] === "=" || t[0] === "!=")
|
|
384
|
+
return {
|
|
385
|
+
fieldValue: `IS NOT NULL AND ${s.split(".").map((c) => `"${c}"`).join(".")}::jsonb ${t[0]} ${o()}::jsonb`,
|
|
386
|
+
fieldParams: [JSON.stringify(t[1])]
|
|
387
|
+
};
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
getPlaceholder() {
|
|
391
|
+
let e = 0;
|
|
392
|
+
return () => (e++, `$${e}`);
|
|
393
|
+
}
|
|
394
|
+
mapToDBFieldType(e, t) {
|
|
395
|
+
return e === "pk" ? "INT GENERATED ALWAYS AS IDENTITY" : e === "id" ? "INT" : t || e === "object" ? "JSON" : e === "string" ? "TEXT" : e === "boolean" ? "BOOLEAN" : e === "number" ? "DOUBLE PRECISION" : e === "timestamp" ? "TIMESTAMP" : e;
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
const f = "0123456789abcdef";
|
|
399
|
+
class h {
|
|
400
|
+
/** @param bytes - The 16-byte byte array representation. */
|
|
401
|
+
constructor(e) {
|
|
402
|
+
this.bytes = e;
|
|
403
|
+
}
|
|
404
|
+
/**
|
|
405
|
+
* Creates an object from the internal representation, a 16-byte byte array
|
|
406
|
+
* containing the binary UUID representation in the big-endian byte order.
|
|
407
|
+
*
|
|
408
|
+
* This method does NOT shallow-copy the argument, and thus the created object
|
|
409
|
+
* holds the reference to the underlying buffer.
|
|
410
|
+
*
|
|
411
|
+
* @throws TypeError if the length of the argument is not 16.
|
|
412
|
+
*/
|
|
413
|
+
static ofInner(e) {
|
|
414
|
+
if (e.length !== 16)
|
|
415
|
+
throw new TypeError("not 128-bit length");
|
|
416
|
+
return new h(e);
|
|
417
|
+
}
|
|
418
|
+
/**
|
|
419
|
+
* Builds a byte array from UUIDv7 field values.
|
|
420
|
+
*
|
|
421
|
+
* @param unixTsMs - A 48-bit `unix_ts_ms` field value.
|
|
422
|
+
* @param randA - A 12-bit `rand_a` field value.
|
|
423
|
+
* @param randBHi - The higher 30 bits of 62-bit `rand_b` field value.
|
|
424
|
+
* @param randBLo - The lower 32 bits of 62-bit `rand_b` field value.
|
|
425
|
+
* @throws RangeError if any field value is out of the specified range.
|
|
426
|
+
*/
|
|
427
|
+
static fromFieldsV7(e, t, s, r) {
|
|
428
|
+
if (!Number.isInteger(e) || !Number.isInteger(t) || !Number.isInteger(s) || !Number.isInteger(r) || e < 0 || t < 0 || s < 0 || r < 0 || e > 281474976710655 || t > 4095 || s > 1073741823 || r > 4294967295)
|
|
429
|
+
throw new RangeError("invalid field value");
|
|
430
|
+
const n = new Uint8Array(16);
|
|
431
|
+
return n[0] = e / 2 ** 40, n[1] = e / 2 ** 32, n[2] = e / 2 ** 24, n[3] = e / 2 ** 16, n[4] = e / 2 ** 8, n[5] = e, n[6] = 112 | t >>> 8, n[7] = t, n[8] = 128 | s >>> 24, n[9] = s >>> 16, n[10] = s >>> 8, n[11] = s, n[12] = r >>> 24, n[13] = r >>> 16, n[14] = r >>> 8, n[15] = r, new h(n);
|
|
432
|
+
}
|
|
433
|
+
/**
|
|
434
|
+
* Builds a byte array from a string representation.
|
|
435
|
+
*
|
|
436
|
+
* This method accepts the following formats:
|
|
437
|
+
*
|
|
438
|
+
* - 32-digit hexadecimal format without hyphens: `0189dcd553117d408db09496a2eef37b`
|
|
439
|
+
* - 8-4-4-4-12 hyphenated format: `0189dcd5-5311-7d40-8db0-9496a2eef37b`
|
|
440
|
+
* - Hyphenated format with surrounding braces: `{0189dcd5-5311-7d40-8db0-9496a2eef37b}`
|
|
441
|
+
* - RFC 9562 URN format: `urn:uuid:0189dcd5-5311-7d40-8db0-9496a2eef37b`
|
|
442
|
+
*
|
|
443
|
+
* Leading and trailing whitespaces represents an error.
|
|
444
|
+
*
|
|
445
|
+
* @throws SyntaxError if the argument could not parse as a valid UUID string.
|
|
446
|
+
*/
|
|
447
|
+
static parse(e) {
|
|
448
|
+
var t, s, r, n;
|
|
449
|
+
let i;
|
|
450
|
+
switch (e.length) {
|
|
451
|
+
case 32:
|
|
452
|
+
i = (t = /^[0-9a-f]{32}$/i.exec(e)) === null || t === void 0 ? void 0 : t[0];
|
|
453
|
+
break;
|
|
454
|
+
case 36:
|
|
455
|
+
i = (s = /^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(e)) === null || s === void 0 ? void 0 : s.slice(1, 6).join("");
|
|
456
|
+
break;
|
|
457
|
+
case 38:
|
|
458
|
+
i = (r = /^\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\}$/i.exec(e)) === null || r === void 0 ? void 0 : r.slice(1, 6).join("");
|
|
459
|
+
break;
|
|
460
|
+
case 45:
|
|
461
|
+
i = (n = /^urn:uuid:([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(e)) === null || n === void 0 ? void 0 : n.slice(1, 6).join("");
|
|
462
|
+
break;
|
|
463
|
+
}
|
|
464
|
+
if (i) {
|
|
465
|
+
const o = new Uint8Array(16);
|
|
466
|
+
for (let a = 0; a < 16; a += 4) {
|
|
467
|
+
const c = parseInt(i.substring(2 * a, 2 * a + 8), 16);
|
|
468
|
+
o[a + 0] = c >>> 24, o[a + 1] = c >>> 16, o[a + 2] = c >>> 8, o[a + 3] = c;
|
|
469
|
+
}
|
|
470
|
+
return new h(o);
|
|
471
|
+
} else
|
|
472
|
+
throw new SyntaxError("could not parse UUID string");
|
|
473
|
+
}
|
|
474
|
+
/**
|
|
475
|
+
* @returns The 8-4-4-4-12 canonical hexadecimal string representation
|
|
476
|
+
* (`0189dcd5-5311-7d40-8db0-9496a2eef37b`).
|
|
477
|
+
*/
|
|
478
|
+
toString() {
|
|
479
|
+
let e = "";
|
|
480
|
+
for (let t = 0; t < this.bytes.length; t++)
|
|
481
|
+
e += f.charAt(this.bytes[t] >>> 4), e += f.charAt(this.bytes[t] & 15), (t === 3 || t === 5 || t === 7 || t === 9) && (e += "-");
|
|
482
|
+
return e;
|
|
483
|
+
}
|
|
484
|
+
/**
|
|
485
|
+
* @returns The 32-digit hexadecimal representation without hyphens
|
|
486
|
+
* (`0189dcd553117d408db09496a2eef37b`).
|
|
487
|
+
*/
|
|
488
|
+
toHex() {
|
|
489
|
+
let e = "";
|
|
490
|
+
for (let t = 0; t < this.bytes.length; t++)
|
|
491
|
+
e += f.charAt(this.bytes[t] >>> 4), e += f.charAt(this.bytes[t] & 15);
|
|
492
|
+
return e;
|
|
493
|
+
}
|
|
494
|
+
/** @returns The 8-4-4-4-12 canonical hexadecimal string representation. */
|
|
495
|
+
toJSON() {
|
|
496
|
+
return this.toString();
|
|
497
|
+
}
|
|
498
|
+
/**
|
|
499
|
+
* Reports the variant field value of the UUID or, if appropriate, "NIL" or
|
|
500
|
+
* "MAX".
|
|
501
|
+
*
|
|
502
|
+
* For convenience, this method reports "NIL" or "MAX" if `this` represents
|
|
503
|
+
* the Nil or Max UUID, although the Nil and Max UUIDs are technically
|
|
504
|
+
* subsumed under the variants `0b0` and `0b111`, respectively.
|
|
505
|
+
*/
|
|
506
|
+
getVariant() {
|
|
507
|
+
const e = this.bytes[8] >>> 4;
|
|
508
|
+
if (e < 0)
|
|
509
|
+
throw new Error("unreachable");
|
|
510
|
+
if (e <= 7)
|
|
511
|
+
return this.bytes.every((t) => t === 0) ? "NIL" : "VAR_0";
|
|
512
|
+
if (e <= 11)
|
|
513
|
+
return "VAR_10";
|
|
514
|
+
if (e <= 13)
|
|
515
|
+
return "VAR_110";
|
|
516
|
+
if (e <= 15)
|
|
517
|
+
return this.bytes.every((t) => t === 255) ? "MAX" : "VAR_RESERVED";
|
|
518
|
+
throw new Error("unreachable");
|
|
519
|
+
}
|
|
520
|
+
/**
|
|
521
|
+
* Returns the version field value of the UUID or `undefined` if the UUID does
|
|
522
|
+
* not have the variant field value of `0b10`.
|
|
523
|
+
*/
|
|
524
|
+
getVersion() {
|
|
525
|
+
return this.getVariant() === "VAR_10" ? this.bytes[6] >>> 4 : void 0;
|
|
526
|
+
}
|
|
527
|
+
/** Creates an object from `this`. */
|
|
528
|
+
clone() {
|
|
529
|
+
return new h(this.bytes.slice(0));
|
|
530
|
+
}
|
|
531
|
+
/** Returns true if `this` is equivalent to `other`. */
|
|
532
|
+
equals(e) {
|
|
533
|
+
return this.compareTo(e) === 0;
|
|
534
|
+
}
|
|
535
|
+
/**
|
|
536
|
+
* Returns a negative integer, zero, or positive integer if `this` is less
|
|
537
|
+
* than, equal to, or greater than `other`, respectively.
|
|
538
|
+
*/
|
|
539
|
+
compareTo(e) {
|
|
540
|
+
for (let t = 0; t < 16; t++) {
|
|
541
|
+
const s = this.bytes[t] - e.bytes[t];
|
|
542
|
+
if (s !== 0)
|
|
543
|
+
return Math.sign(s);
|
|
544
|
+
}
|
|
545
|
+
return 0;
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
class q {
|
|
549
|
+
/**
|
|
550
|
+
* Creates a generator object with the default random number generator, or
|
|
551
|
+
* with the specified one if passed as an argument. The specified random
|
|
552
|
+
* number generator should be cryptographically strong and securely seeded.
|
|
553
|
+
*/
|
|
554
|
+
constructor(e) {
|
|
555
|
+
this.timestamp = 0, this.counter = 0, this.random = e ?? _();
|
|
556
|
+
}
|
|
557
|
+
/**
|
|
558
|
+
* Generates a new UUIDv7 object from the current timestamp, or resets the
|
|
559
|
+
* generator upon significant timestamp rollback.
|
|
560
|
+
*
|
|
561
|
+
* This method returns a monotonically increasing UUID by reusing the previous
|
|
562
|
+
* timestamp even if the up-to-date timestamp is smaller than the immediately
|
|
563
|
+
* preceding UUID's. However, when such a clock rollback is considered
|
|
564
|
+
* significant (i.e., by more than ten seconds), this method resets the
|
|
565
|
+
* generator and returns a new UUID based on the given timestamp, breaking the
|
|
566
|
+
* increasing order of UUIDs.
|
|
567
|
+
*
|
|
568
|
+
* See {@link generateOrAbort} for the other mode of generation and
|
|
569
|
+
* {@link generateOrResetCore} for the low-level primitive.
|
|
570
|
+
*/
|
|
571
|
+
generate() {
|
|
572
|
+
return this.generateOrResetCore(Date.now(), 1e4);
|
|
573
|
+
}
|
|
574
|
+
/**
|
|
575
|
+
* Generates a new UUIDv7 object from the current timestamp, or returns
|
|
576
|
+
* `undefined` upon significant timestamp rollback.
|
|
577
|
+
*
|
|
578
|
+
* This method returns a monotonically increasing UUID by reusing the previous
|
|
579
|
+
* timestamp even if the up-to-date timestamp is smaller than the immediately
|
|
580
|
+
* preceding UUID's. However, when such a clock rollback is considered
|
|
581
|
+
* significant (i.e., by more than ten seconds), this method aborts and
|
|
582
|
+
* returns `undefined` immediately.
|
|
583
|
+
*
|
|
584
|
+
* See {@link generate} for the other mode of generation and
|
|
585
|
+
* {@link generateOrAbortCore} for the low-level primitive.
|
|
586
|
+
*/
|
|
587
|
+
generateOrAbort() {
|
|
588
|
+
return this.generateOrAbortCore(Date.now(), 1e4);
|
|
589
|
+
}
|
|
590
|
+
/**
|
|
591
|
+
* Generates a new UUIDv7 object from the `unixTsMs` passed, or resets the
|
|
592
|
+
* generator upon significant timestamp rollback.
|
|
593
|
+
*
|
|
594
|
+
* This method is equivalent to {@link generate} except that it takes a custom
|
|
595
|
+
* timestamp and clock rollback allowance.
|
|
596
|
+
*
|
|
597
|
+
* @param rollbackAllowance - The amount of `unixTsMs` rollback that is
|
|
598
|
+
* considered significant. A suggested value is `10_000` (milliseconds).
|
|
599
|
+
* @throws RangeError if `unixTsMs` is not a 48-bit positive integer.
|
|
600
|
+
*/
|
|
601
|
+
generateOrResetCore(e, t) {
|
|
602
|
+
let s = this.generateOrAbortCore(e, t);
|
|
603
|
+
return s === void 0 && (this.timestamp = 0, s = this.generateOrAbortCore(e, t)), s;
|
|
604
|
+
}
|
|
605
|
+
/**
|
|
606
|
+
* Generates a new UUIDv7 object from the `unixTsMs` passed, or returns
|
|
607
|
+
* `undefined` upon significant timestamp rollback.
|
|
608
|
+
*
|
|
609
|
+
* This method is equivalent to {@link generateOrAbort} except that it takes a
|
|
610
|
+
* custom timestamp and clock rollback allowance.
|
|
611
|
+
*
|
|
612
|
+
* @param rollbackAllowance - The amount of `unixTsMs` rollback that is
|
|
613
|
+
* considered significant. A suggested value is `10_000` (milliseconds).
|
|
614
|
+
* @throws RangeError if `unixTsMs` is not a 48-bit positive integer.
|
|
615
|
+
*/
|
|
616
|
+
generateOrAbortCore(e, t) {
|
|
617
|
+
if (!Number.isInteger(e) || e < 0 || e > 281474976710655)
|
|
618
|
+
throw new RangeError(`\`unixTsMs\` must be a 48-bit positive integer, got ${e}`);
|
|
619
|
+
if (t < 0 || t > 281474976710655)
|
|
620
|
+
throw new RangeError(`\`rollbackAllowance\` out of reasonable range, got ${t}`);
|
|
621
|
+
if (e > this.timestamp)
|
|
622
|
+
this.timestamp = e, this.resetCounter();
|
|
623
|
+
else if (e + t >= this.timestamp)
|
|
624
|
+
this.counter++, this.counter > 4398046511103 && (this.timestamp++, this.resetCounter());
|
|
625
|
+
else
|
|
626
|
+
return;
|
|
627
|
+
return h.fromFieldsV7(this.timestamp, Math.trunc(this.counter / 2 ** 30), this.counter & 2 ** 30 - 1, this.random.nextUint32());
|
|
628
|
+
}
|
|
629
|
+
/** Initializes the counter at a 42-bit random integer. */
|
|
630
|
+
resetCounter() {
|
|
631
|
+
this.counter = this.random.nextUint32() * 1024 + (this.random.nextUint32() & 1023);
|
|
632
|
+
}
|
|
633
|
+
/**
|
|
634
|
+
* Generates a new UUIDv4 object utilizing the random number generator inside.
|
|
635
|
+
*
|
|
636
|
+
* @internal
|
|
637
|
+
*/
|
|
638
|
+
generateV4() {
|
|
639
|
+
const e = new Uint8Array(Uint32Array.of(this.random.nextUint32(), this.random.nextUint32(), this.random.nextUint32(), this.random.nextUint32()).buffer);
|
|
640
|
+
return e[6] = 64 | e[6] >>> 4, e[8] = 128 | e[8] >>> 2, h.ofInner(e);
|
|
641
|
+
}
|
|
642
|
+
}
|
|
643
|
+
const _ = () => {
|
|
644
|
+
if (typeof crypto < "u" && typeof crypto.getRandomValues < "u")
|
|
645
|
+
return new D();
|
|
646
|
+
if (typeof UUIDV7_DENY_WEAK_RNG < "u" && UUIDV7_DENY_WEAK_RNG)
|
|
647
|
+
throw new Error("no cryptographically strong RNG available");
|
|
648
|
+
return {
|
|
649
|
+
nextUint32: () => Math.trunc(Math.random() * 65536) * 65536 + Math.trunc(Math.random() * 65536)
|
|
650
|
+
};
|
|
651
|
+
};
|
|
652
|
+
class D {
|
|
653
|
+
constructor() {
|
|
654
|
+
this.buffer = new Uint32Array(8), this.cursor = 65535;
|
|
655
|
+
}
|
|
656
|
+
nextUint32() {
|
|
657
|
+
return this.cursor >= this.buffer.length && (crypto.getRandomValues(this.buffer), this.cursor = 0), this.buffer[this.cursor++];
|
|
658
|
+
}
|
|
659
|
+
}
|
|
660
|
+
let y;
|
|
661
|
+
const $ = () => U().toString(), U = () => (y || (y = new q())).generate();
|
|
662
|
+
let x = class {
|
|
663
|
+
constructor(e) {
|
|
664
|
+
this.db = e;
|
|
665
|
+
}
|
|
666
|
+
setup() {
|
|
667
|
+
return this.db.scheme('CREATE Table IF NOT EXISTS "_IDS_" (last INTEGER, name TEXT)');
|
|
668
|
+
}
|
|
669
|
+
async getAutoId(e) {
|
|
670
|
+
return $();
|
|
671
|
+
}
|
|
672
|
+
};
|
|
673
|
+
class v {
|
|
674
|
+
constructor(e, t = {}) {
|
|
675
|
+
this.database = e, this.options = t, this.supportsSelectForUpdate = !0, this.maxQueryParams = 65e3, this.transactionCapability = {
|
|
676
|
+
transactions: !0,
|
|
677
|
+
isolationLevels: ["READ COMMITTED", "SERIALIZABLE"],
|
|
678
|
+
transactionBoundConnection: !1,
|
|
679
|
+
concurrentTransactions: "unsupported",
|
|
680
|
+
nestedStrategy: "reuse",
|
|
681
|
+
notes: [
|
|
682
|
+
"PGLite uses MonoStorage fallback BEGIN/COMMIT; SERIALIZABLE is framework metadata for retry-path tests, not a production PostgreSQL isolation guarantee."
|
|
683
|
+
]
|
|
684
|
+
}, this.atomicSequenceCapability = {
|
|
685
|
+
requiresActiveTransaction: !0,
|
|
686
|
+
transactional: !0,
|
|
687
|
+
crossConnection: !1,
|
|
688
|
+
crossProcess: !1,
|
|
689
|
+
returning: !0,
|
|
690
|
+
productionSafe: !1
|
|
691
|
+
}, this.schemaDialect = {
|
|
692
|
+
name: "postgres",
|
|
693
|
+
maxIdentifierLength: 63,
|
|
694
|
+
supportsCreateIndexIfNotExists: !0,
|
|
695
|
+
encodeLiteral: S,
|
|
696
|
+
constraints: { unique: !0, filteredUnique: !0, nonNull: !0 }
|
|
697
|
+
}, this.idSystem = new x(this), this.logger = this.options?.logger || g, this.db = new R(this.database);
|
|
698
|
+
}
|
|
699
|
+
async open(e = !1) {
|
|
700
|
+
if (e) {
|
|
701
|
+
const t = await this.db.query(`
|
|
702
|
+
SELECT tablename FROM pg_tables
|
|
703
|
+
WHERE schemaname = 'public'
|
|
704
|
+
AND tablename NOT LIKE 'pg_%'
|
|
705
|
+
AND tablename NOT LIKE 'sql_%'
|
|
706
|
+
`);
|
|
707
|
+
for (const s of t.rows)
|
|
708
|
+
await this.db.query(`DROP TABLE IF EXISTS "${s.tablename}" CASCADE`);
|
|
709
|
+
}
|
|
710
|
+
await this.idSystem.setup();
|
|
711
|
+
}
|
|
712
|
+
async openForSchemaRead() {
|
|
713
|
+
}
|
|
714
|
+
async setupInternalComputationState() {
|
|
715
|
+
await this.scheme(`
|
|
716
|
+
CREATE TABLE IF NOT EXISTS "_ComputationState_" (
|
|
717
|
+
"key" TEXT PRIMARY KEY,
|
|
718
|
+
"numberValue" NUMERIC NULL,
|
|
719
|
+
"booleanValue" BOOLEAN NULL,
|
|
720
|
+
"stringValue" TEXT NULL,
|
|
721
|
+
"jsonValue" JSON NULL
|
|
722
|
+
)`, "setup computation state table");
|
|
723
|
+
}
|
|
724
|
+
async setupScopedSequenceState() {
|
|
725
|
+
await this.scheme(`
|
|
726
|
+
CREATE TABLE IF NOT EXISTS "_ScopedSequence_" (
|
|
727
|
+
"sequenceName" TEXT NOT NULL,
|
|
728
|
+
"scopeKey" TEXT NOT NULL,
|
|
729
|
+
"scope" JSONB NOT NULL,
|
|
730
|
+
"lastValue" NUMERIC NOT NULL,
|
|
731
|
+
PRIMARY KEY ("sequenceName", "scopeKey")
|
|
732
|
+
)`, "setup scoped sequence table");
|
|
733
|
+
}
|
|
734
|
+
async query(e, t = [], s = "") {
|
|
735
|
+
const r = l.getStore(), n = this.logger.child(r?.logContext || {});
|
|
736
|
+
n.info({
|
|
737
|
+
type: "query",
|
|
738
|
+
name: s,
|
|
739
|
+
sql: e,
|
|
740
|
+
params: t
|
|
741
|
+
});
|
|
742
|
+
try {
|
|
743
|
+
return (await this.db.query(e, t)).rows;
|
|
744
|
+
} catch (i) {
|
|
745
|
+
throw n.error({
|
|
746
|
+
type: "query",
|
|
747
|
+
name: s,
|
|
748
|
+
sql: e,
|
|
749
|
+
params: t,
|
|
750
|
+
error: i instanceof Error ? i.message : String(i)
|
|
751
|
+
}), i;
|
|
752
|
+
}
|
|
753
|
+
}
|
|
754
|
+
async update(e, t, s, r = "") {
|
|
755
|
+
const n = l.getStore(), i = this.logger.child(n?.logContext || {}), o = `${e} ${s ? `RETURNING "${s}" AS id` : ""}`, a = t.map((c) => typeof c == "object" && c !== null ? JSON.stringify(c) : c);
|
|
756
|
+
return i.info({
|
|
757
|
+
type: "update",
|
|
758
|
+
name: r,
|
|
759
|
+
sql: o,
|
|
760
|
+
params: a
|
|
761
|
+
}), (await this.db.query(o, a)).rows;
|
|
762
|
+
}
|
|
763
|
+
async insert(e, t, s = "") {
|
|
764
|
+
const r = l.getStore(), n = this.logger.child(r?.logContext || {}), i = t.map((a) => typeof a == "object" && a !== null ? JSON.stringify(a) : a);
|
|
765
|
+
n.info({
|
|
766
|
+
type: "insert",
|
|
767
|
+
name: s,
|
|
768
|
+
sql: e,
|
|
769
|
+
params: i
|
|
770
|
+
});
|
|
771
|
+
const o = `${e} RETURNING "${p}"`;
|
|
772
|
+
try {
|
|
773
|
+
return (await this.db.query(o, i)).rows[0];
|
|
774
|
+
} catch (a) {
|
|
775
|
+
throw n.error({
|
|
776
|
+
type: "insert",
|
|
777
|
+
name: s,
|
|
778
|
+
sql: o,
|
|
779
|
+
params: i,
|
|
780
|
+
error: a instanceof Error ? a.message : String(a)
|
|
781
|
+
}), a;
|
|
782
|
+
}
|
|
783
|
+
}
|
|
784
|
+
async delete(e, t, s = "") {
|
|
785
|
+
const r = l.getStore();
|
|
786
|
+
return this.logger.child(r?.logContext || {}).info({
|
|
787
|
+
type: "delete",
|
|
788
|
+
name: s,
|
|
789
|
+
sql: e,
|
|
790
|
+
params: t
|
|
791
|
+
}), (await this.db.query(e, t)).rows;
|
|
792
|
+
}
|
|
793
|
+
async scheme(e, t = "") {
|
|
794
|
+
const s = l.getStore(), r = this.logger.child(s?.logContext || {});
|
|
795
|
+
r.info({
|
|
796
|
+
type: "scheme",
|
|
797
|
+
name: t,
|
|
798
|
+
sql: e
|
|
799
|
+
});
|
|
800
|
+
try {
|
|
801
|
+
return await this.db.query(e);
|
|
802
|
+
} catch (n) {
|
|
803
|
+
throw r.error({
|
|
804
|
+
type: "scheme",
|
|
805
|
+
name: t,
|
|
806
|
+
sql: e,
|
|
807
|
+
error: n instanceof Error ? n.message : String(n)
|
|
808
|
+
}), n;
|
|
809
|
+
}
|
|
810
|
+
}
|
|
811
|
+
close() {
|
|
812
|
+
return this.db.close();
|
|
813
|
+
}
|
|
814
|
+
async getAutoId(e) {
|
|
815
|
+
return this.idSystem.getAutoId(e);
|
|
816
|
+
}
|
|
817
|
+
parseMatchExpression(e, t, s, r, n, i, o) {
|
|
818
|
+
if (r.toLowerCase() === "json") {
|
|
819
|
+
if (t[0].toLowerCase() === "contains") {
|
|
820
|
+
const a = s.split(".").map((c) => `"${c}"`).join(".");
|
|
821
|
+
return {
|
|
822
|
+
fieldValue: `IS NOT NULL AND ${o()} = ANY (SELECT json_array_elements_text(${a}))`,
|
|
823
|
+
fieldParams: [t[1]]
|
|
824
|
+
};
|
|
825
|
+
}
|
|
826
|
+
if (t[0] === "=" || t[0] === "!=")
|
|
827
|
+
return {
|
|
828
|
+
fieldValue: `IS NOT NULL AND ${s.split(".").map((c) => `"${c}"`).join(".")}::jsonb ${t[0]} ${o()}::jsonb`,
|
|
829
|
+
fieldParams: [JSON.stringify(t[1])]
|
|
830
|
+
};
|
|
831
|
+
}
|
|
832
|
+
}
|
|
833
|
+
getPlaceholder() {
|
|
834
|
+
let e = 0;
|
|
835
|
+
return () => (e++, `$${e}`);
|
|
836
|
+
}
|
|
837
|
+
mapToDBFieldType(e, t) {
|
|
838
|
+
return e === "pk" ? "SERIAL PRIMARY KEY" : e === "id" ? "UUID" : t || e === "object" ? "JSON" : e === "string" ? "TEXT" : e === "boolean" ? "BOOL" : e === "number" ? "DOUBLE PRECISION" : e === "timestamp" ? "TIMESTAMP" : e;
|
|
839
|
+
}
|
|
840
|
+
}
|
|
841
|
+
class M {
|
|
842
|
+
constructor(e) {
|
|
843
|
+
this.db = e, this.allocating = Promise.resolve();
|
|
844
|
+
}
|
|
845
|
+
async setup() {
|
|
846
|
+
await this.db.scheme('CREATE Table IF NOT EXISTS "_IDS_" (last INTEGER, name VARCHAR(191), PRIMARY KEY (name))'), (await this.db.query(
|
|
847
|
+
"SELECT COUNT(1) AS cnt FROM information_schema.statistics WHERE table_schema = DATABASE() AND table_name = '_IDS_' AND index_name = 'PRIMARY'",
|
|
848
|
+
[],
|
|
849
|
+
"check _IDS_ primary key"
|
|
850
|
+
))[0]?.cnt || await this.db.scheme('ALTER TABLE "_IDS_" MODIFY name VARCHAR(191), ADD PRIMARY KEY (name)');
|
|
851
|
+
}
|
|
852
|
+
async getAutoId(e) {
|
|
853
|
+
const t = this.allocating.then(async () => (await this.db.update(
|
|
854
|
+
`INSERT INTO "_IDS_" (name, last) VALUES (?, LAST_INSERT_ID(1))
|
|
855
|
+
ON DUPLICATE KEY UPDATE last = LAST_INSERT_ID(last + 1)`,
|
|
856
|
+
[e],
|
|
857
|
+
void 0,
|
|
858
|
+
`allocate next id for ${e}`
|
|
859
|
+
), (await this.db.query("SELECT LAST_INSERT_ID() AS id", [], `read allocated id for ${e}`))[0].id));
|
|
860
|
+
return this.allocating = t.catch(() => {
|
|
861
|
+
}), t;
|
|
862
|
+
}
|
|
863
|
+
}
|
|
864
|
+
class k {
|
|
865
|
+
constructor(e, t = {}) {
|
|
866
|
+
this.database = e, this.options = t, this.supportsSelectForUpdate = !0, this.maxQueryParams = 65e3, this.transactionCapability = {
|
|
867
|
+
transactions: !1,
|
|
868
|
+
isolationLevels: [],
|
|
869
|
+
transactionBoundConnection: !1,
|
|
870
|
+
concurrentTransactions: "unsupported",
|
|
871
|
+
nestedStrategy: "unsupported",
|
|
872
|
+
notes: [
|
|
873
|
+
"The current MySQL driver has no transaction-bound connection implementation; strong dispatch transactions are unsupported."
|
|
874
|
+
]
|
|
875
|
+
}, this.schemaDialect = {
|
|
876
|
+
name: "mysql",
|
|
877
|
+
maxIdentifierLength: 64,
|
|
878
|
+
supportsCreateIndexIfNotExists: !1,
|
|
879
|
+
encodeLiteral: S,
|
|
880
|
+
constraints: { unique: !1, filteredUnique: !1, nonNull: !1 }
|
|
881
|
+
}, this.idSystem = new M(this), this.logger = this.options?.logger || g;
|
|
882
|
+
}
|
|
883
|
+
async open(e = !1) {
|
|
884
|
+
const t = await E.createConnection({
|
|
885
|
+
...this.options
|
|
886
|
+
});
|
|
887
|
+
await t.connect();
|
|
888
|
+
try {
|
|
889
|
+
const s = `\`${this.database.replace(/`/g, "``")}\``, [r] = await t.query("SHOW DATABASES LIKE ?", [this.database]);
|
|
890
|
+
r.length === 0 ? await t.query(`CREATE DATABASE ${s}`) : e && (await t.query(`DROP DATABASE ${s}`), await t.query(`CREATE DATABASE ${s}`));
|
|
891
|
+
} finally {
|
|
892
|
+
await t.end();
|
|
893
|
+
}
|
|
894
|
+
this.db = await E.createConnection({
|
|
895
|
+
...this.options,
|
|
896
|
+
database: this.database
|
|
897
|
+
}), await this.db.connect(), await this.db.query("SET sql_mode='ANSI_QUOTES'"), await this.idSystem.setup();
|
|
898
|
+
}
|
|
899
|
+
async openForSchemaRead() {
|
|
900
|
+
this.db || (this.db = await E.createConnection({
|
|
901
|
+
...this.options,
|
|
902
|
+
database: this.database
|
|
903
|
+
}), await this.db.connect(), await this.db.query("SET sql_mode='ANSI_QUOTES'"));
|
|
904
|
+
}
|
|
905
|
+
async query(e, t = [], s = "") {
|
|
906
|
+
const r = l.getStore(), n = this.logger.child(r?.logContext || {}), i = t.map((o) => o === !1 ? 0 : o === !0 ? 1 : o);
|
|
907
|
+
return n.info({
|
|
908
|
+
type: "query",
|
|
909
|
+
name: s,
|
|
910
|
+
sql: e,
|
|
911
|
+
params: i
|
|
912
|
+
}), (await this.db.query(e, i))[0];
|
|
913
|
+
}
|
|
914
|
+
async update(e, t, s, r = "") {
|
|
915
|
+
const n = l.getStore(), i = this.logger.child(n?.logContext || {}), o = t.map((a) => typeof a == "object" && a !== null ? JSON.stringify(a) : a === !1 ? 0 : a === !0 ? 1 : a);
|
|
916
|
+
return i.info({
|
|
917
|
+
type: "update",
|
|
918
|
+
name: r,
|
|
919
|
+
sql: e,
|
|
920
|
+
params: o
|
|
921
|
+
}), (await this.db.query(e, o))[0];
|
|
922
|
+
}
|
|
923
|
+
async insert(e, t, s = "") {
|
|
924
|
+
const r = l.getStore(), n = this.logger.child(r?.logContext || {}), i = t.map((c) => typeof c == "object" && c !== null ? JSON.stringify(c) : c === !1 ? 0 : c === !0 ? 1 : c);
|
|
925
|
+
n.info({
|
|
926
|
+
type: "insert",
|
|
927
|
+
name: s,
|
|
928
|
+
sql: e,
|
|
929
|
+
params: i
|
|
930
|
+
}), await this.db.query(e, i);
|
|
931
|
+
const [o] = await this.db.query("SELECT LAST_INSERT_ID();");
|
|
932
|
+
return { id: o[0]["LAST_INSERT_ID()"] };
|
|
933
|
+
}
|
|
934
|
+
async delete(e, t, s = "") {
|
|
935
|
+
const r = l.getStore(), n = this.logger.child(r?.logContext || {}), i = t.map((o) => o === !1 ? 0 : o === !0 ? 1 : o);
|
|
936
|
+
return n.info({
|
|
937
|
+
type: "delete",
|
|
938
|
+
name: s,
|
|
939
|
+
sql: e,
|
|
940
|
+
params: i
|
|
941
|
+
}), (await this.db.query(e, i))[0];
|
|
942
|
+
}
|
|
943
|
+
async scheme(e, t = "") {
|
|
944
|
+
const s = l.getStore();
|
|
945
|
+
return this.logger.child(s?.logContext || {}).info({
|
|
946
|
+
type: "scheme",
|
|
947
|
+
name: t,
|
|
948
|
+
sql: e
|
|
949
|
+
}), await this.db.query(e);
|
|
950
|
+
}
|
|
951
|
+
close() {
|
|
952
|
+
return this.db.end();
|
|
953
|
+
}
|
|
954
|
+
async getAutoId(e) {
|
|
955
|
+
return this.idSystem.getAutoId(e);
|
|
956
|
+
}
|
|
957
|
+
parseMatchExpression(e, t, s, r, n, i, o) {
|
|
958
|
+
if (r === "JSON") {
|
|
959
|
+
if (t[0].toLowerCase() === "contains")
|
|
960
|
+
return {
|
|
961
|
+
fieldValue: `IS NOT NULL AND JSON_CONTAINS(${s.split(".").map((c) => `"${c}"`).join(".")}, ${o()}, '$')`,
|
|
962
|
+
fieldParams: [JSON.stringify(t[1])]
|
|
963
|
+
};
|
|
964
|
+
if (t[0] === "=" || t[0] === "!=")
|
|
965
|
+
return {
|
|
966
|
+
fieldValue: `IS NOT NULL AND ${s.split(".").map((c) => `"${c}"`).join(".")} ${t[0]} CAST(${o()} AS JSON)`,
|
|
967
|
+
fieldParams: [JSON.stringify(t[1])]
|
|
968
|
+
};
|
|
969
|
+
}
|
|
970
|
+
}
|
|
971
|
+
getPlaceholder() {
|
|
972
|
+
return () => "?";
|
|
973
|
+
}
|
|
974
|
+
mapToDBFieldType(e, t) {
|
|
975
|
+
return e === "pk" ? "INT AUTO_INCREMENT PRIMARY KEY" : e === "id" ? "INT" : t || e === "object" ? "JSON" : e === "string" ? "TEXT" : e === "boolean" ? "INT(2)" : e === "number" ? "DOUBLE" : e === "timestamp" ? "TIMESTAMP" : e;
|
|
976
|
+
}
|
|
977
|
+
}
|
|
978
|
+
export {
|
|
979
|
+
k as MysqlDB,
|
|
980
|
+
v as PGLiteDB,
|
|
981
|
+
W as PostgreSQLDB,
|
|
982
|
+
K as SQLiteDB
|
|
983
|
+
};
|
|
984
|
+
//# sourceMappingURL=drivers.js.map
|