@fadhilp/stateql 0.17.0 → 0.19.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 (43) hide show
  1. package/dist/src/adapters.d.ts +17 -25
  2. package/dist/src/adapters.js +15 -95
  3. package/dist/src/catalog.d.ts +6 -0
  4. package/dist/src/catalog.js +52 -0
  5. package/dist/src/cli.js +8 -3
  6. package/dist/src/connect.d.ts +16 -0
  7. package/dist/src/connect.js +205 -0
  8. package/dist/src/core.d.ts +78 -0
  9. package/dist/src/core.js +477 -0
  10. package/dist/src/execution.d.ts +27 -0
  11. package/dist/src/execution.js +87 -0
  12. package/dist/src/filter.js +3 -1
  13. package/dist/src/index.d.ts +2 -1
  14. package/dist/src/index.js +1 -0
  15. package/dist/src/migrations.d.ts +1 -1
  16. package/dist/src/mongodb.d.ts +4 -2
  17. package/dist/src/mongodb.js +5 -56
  18. package/dist/src/os-credentials.d.ts +6 -1
  19. package/dist/src/os-credentials.js +171 -10
  20. package/dist/src/panel.d.ts +64 -0
  21. package/dist/src/panel.js +316 -0
  22. package/dist/src/plans.d.ts +31 -0
  23. package/dist/src/plans.js +275 -0
  24. package/dist/src/reads.d.ts +35 -0
  25. package/dist/src/reads.js +184 -0
  26. package/dist/src/redis.d.ts +4 -2
  27. package/dist/src/redis.js +7 -33
  28. package/dist/src/response-data.d.ts +1 -0
  29. package/dist/src/response-data.js +13 -10
  30. package/dist/src/results.d.ts +10 -0
  31. package/dist/src/results.js +153 -0
  32. package/dist/src/sqlite-process.js +16 -9
  33. package/dist/src/stateql.d.ts +7 -58
  34. package/dist/src/stateql.js +150 -2663
  35. package/dist/src/table-editor.js +2 -2
  36. package/dist/src/transactions.d.ts +8 -0
  37. package/dist/src/transactions.js +186 -0
  38. package/dist/src/types.d.ts +3 -17
  39. package/dist/src/writes.d.ts +48 -0
  40. package/dist/src/writes.js +320 -0
  41. package/docs/databases.md +2 -1
  42. package/docs/results.md +5 -0
  43. package/package.json +5 -3
@@ -0,0 +1,316 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { version } from "./connection.js";
3
+ import { nonNegativeInteger, positiveInteger, } from "./core.js";
4
+ import { StateQLError } from "./errors.js";
5
+ import { runPlan } from "./plans.js";
6
+ import { csvCell } from "./response-data.js";
7
+ import { compileTableUpdate, editableRow, } from "./table-editor.js";
8
+ import { hash } from "./util.js";
9
+ const EDIT_TOKEN_TTL_MS = 10 * 60_000;
10
+ /** Bounded table browsing and row editing for host UIs, with in-memory row identities. */
11
+ export class Panel {
12
+ core;
13
+ host;
14
+ tableResults = new Map();
15
+ editTokens = new Map();
16
+ // ponytail: cache one bounded immutable result; use indexed result storage if larger results are needed.
17
+ panelRows;
18
+ constructor(core, host) {
19
+ this.core = core;
20
+ this.host = host;
21
+ }
22
+ clear() {
23
+ this.panelRows = undefined;
24
+ this.tableResults.clear();
25
+ this.editTokens.clear();
26
+ }
27
+ /** Owned, full-value pages for host UIs. Reading a page does not add a command to history. */
28
+ readMaterialized(id, options = {}) {
29
+ options.signal?.throwIfAborted();
30
+ const result = this.panelResult(id);
31
+ const offset = nonNegativeInteger(options.offset ?? 0, "offset");
32
+ const limit = positiveInteger(options.limit ?? 100, "limit");
33
+ if (limit > 100 || offset > 10_000)
34
+ throw new StateQLError("OUTPUT_LIMIT_EXCEEDED", "Page bounds exceeded.");
35
+ const all = this.fullResultRows(result);
36
+ const rows = [];
37
+ let bytes = 0;
38
+ for (const row of all.slice(offset, offset + limit)) {
39
+ const size = Buffer.byteLength(JSON.stringify(row), "utf8");
40
+ if (bytes + size > 200 * 1024) {
41
+ if (!rows.length)
42
+ throw new StateQLError("OUTPUT_LIMIT_EXCEEDED", "A row exceeds the browser page limit. Export this result instead.");
43
+ break;
44
+ }
45
+ rows.push(row);
46
+ bytes += size;
47
+ }
48
+ const next = offset + rows.length;
49
+ const metadata = this.tableResults.get(id);
50
+ const connection = this.core.store.activeConnection(this.core.store.ensureSession(this.core.sessionName));
51
+ const editable = metadata !== undefined &&
52
+ connection?.id === result.connection_id &&
53
+ !connection.read_only &&
54
+ version(connection) === result.state_version;
55
+ const rowTokens = rows.map((row) => editable && editableRow(metadata, row) ? this.issueEditToken(metadata, row, result) : null);
56
+ const writable = metadata?.driver === "mongodb"
57
+ ? [...new Set(rows.flatMap((row) => Object.keys(row)))].filter((name) => name !== "_id")
58
+ : metadata?.columns.filter((column) => !column.key && !column.generated).map((column) => column.name) ?? [];
59
+ return {
60
+ row_tokens: rowTokens,
61
+ writable_columns: writable,
62
+ ...(!metadata?.writable ? { editing_reason: metadata?.reason ?? "Query results are read-only." } : {}),
63
+ result_id: result.id,
64
+ offset,
65
+ limit,
66
+ rows: structuredClone(rows),
67
+ columns: this.core.store.resultColumns(result),
68
+ returned: rows.length,
69
+ total: all.length,
70
+ truncated: next < all.length,
71
+ next_offset: next < all.length ? next : null,
72
+ };
73
+ }
74
+ /** No caller-selected filesystem paths. The host delivers these bounded attachment bytes. */
75
+ async serializeResult(id, format, signal, origin = "api") {
76
+ return this.core.withCommandContext({ signal, origin }, () => this.core.run("export", async () => {
77
+ if (!["json", "jsonl", "csv"].includes(format))
78
+ throw new StateQLError("INVALID_COMMAND", "Unsupported export format.");
79
+ const result = this.panelResult(id);
80
+ const rows = this.fullResultRows(result);
81
+ const columns = this.core.store.resultColumns(result).map((column) => column.name);
82
+ const chunks = [];
83
+ let bytes = 0;
84
+ const append = (chunk) => {
85
+ bytes += Buffer.byteLength(chunk, "utf8");
86
+ if (bytes > 32 * 1024 * 1024)
87
+ throw new StateQLError("OUTPUT_LIMIT_EXCEEDED", "Export exceeds 32 MiB.");
88
+ chunks.push(chunk);
89
+ };
90
+ if (format === "json")
91
+ append("[");
92
+ if (format === "csv")
93
+ append(columns.map(csvCell).join(",") + "\n");
94
+ const deadline = Date.now() + 30_000;
95
+ for (let index = 0; index < rows.length; index++) {
96
+ if (index % 100 === 0) {
97
+ await new Promise((resolve) => setImmediate(resolve));
98
+ signal?.throwIfAborted();
99
+ this.core.signal?.throwIfAborted();
100
+ if (Date.now() > deadline)
101
+ throw new StateQLError("DEADLINE_EXCEEDED", "Export preparation timed out.");
102
+ }
103
+ const row = rows[index];
104
+ append(format === "csv"
105
+ ? columns.map((column) => csvCell(row[column])).join(",") + "\n"
106
+ : (format === "json" && index ? "," : "") + JSON.stringify(row) + (format === "jsonl" ? "\n" : ""));
107
+ }
108
+ signal?.throwIfAborted();
109
+ if (format === "json")
110
+ append("]\n");
111
+ this.panelResult(id);
112
+ return { data: { content: chunks.join(""), format, rows: rows.length }, handle: id };
113
+ }));
114
+ }
115
+ async readTable(table, limit = 1000, options = {}) {
116
+ const context = { signal: options.signal, origin: options.origin ?? "api", internal: true };
117
+ return this.core.withCommandContext(context, async () => {
118
+ if (!validTableName(table) || !Number.isSafeInteger(limit) || limit < 1 || limit > 10_000) {
119
+ throw new StateQLError("INVALID_COMMAND", "Invalid table or sample limit.");
120
+ }
121
+ const driver = this.host.snapshot({ historyLimit: 1 }).connection?.driver;
122
+ if (!driver)
123
+ throw new StateQLError("CONNECTION_NOT_FOUND", "Connect to a database first.");
124
+ if (driver === "sqlite" && table.schema && table.schema !== "main")
125
+ throw new StateQLError("INVALID_COMMAND", "Only the main SQLite schema is supported.");
126
+ if (driver === "mongodb" && table.schema)
127
+ throw new StateQLError("INVALID_COMMAND", "MongoDB collections do not accept a schema.");
128
+ if (driver === "redis")
129
+ throw new StateQLError("INVALID_COMMAND", "Redis keys are not SQL tables; use redisQuery and describeObject.");
130
+ const quote = (name) => driver === "mysql"
131
+ ? "`" + name.replaceAll("`", "``") + "`"
132
+ : '"' + name.replaceAll('"', '""') + '"';
133
+ const qualified = [table.schema, table.name]
134
+ .filter((part) => Boolean(part))
135
+ .map(quote)
136
+ .join(".");
137
+ const find = { operation: "find", collection: table.name, options: { limit } };
138
+ const query = driver === "mongodb"
139
+ ? JSON.stringify(find, null, 2)
140
+ : "SELECT * FROM " + qualified + " LIMIT " + limit;
141
+ const metadata = await this.editableMetadata(table, options);
142
+ const response = driver === "mongodb"
143
+ ? await this.host.mongoQuery(find, options)
144
+ : await this.host.query(query, options);
145
+ if (!response.ok)
146
+ return response;
147
+ if (this.tableResults.size >= 20)
148
+ this.tableResults.delete(this.tableResults.keys().next().value);
149
+ this.tableResults.set(response.data.result_id, metadata);
150
+ return { ...response, data: { ...response.data, table, sample_limit: limit, query } };
151
+ });
152
+ }
153
+ async planTableUpdate(token, changes, options = {}) {
154
+ return this.core.withCommandContext({ signal: options.signal, origin: options.origin ?? "api" }, () => this.core.run("table.plan", async (session) => {
155
+ this.core.rejectDuringStagedTransaction(session, "Table edits");
156
+ const connection = this.core.requireConnection(session);
157
+ const original = this.liveEditToken(token, session, connection);
158
+ if (!original)
159
+ throw new StateQLError("STALE_PLAN", "Row identity expired or the connection changed. Reload the row.");
160
+ if (connection.read_only)
161
+ throw new StateQLError("READ_ONLY_CONNECTION", "This connection is read-only.");
162
+ const metadata = await this.editableMetadata(original.metadata.table, options);
163
+ if (JSON.stringify(metadata) !== JSON.stringify(original.metadata))
164
+ throw new StateQLError("STALE_PLAN", "Table metadata changed. Reload the table.");
165
+ const update = { metadata, original: original.original, changes };
166
+ const compiled = compileTableUpdate(update);
167
+ return runPlan(this.core, session, connection, tableEditPlan(compiled.sql, JSON.stringify(update), "table.update", original.expires), options);
168
+ }));
169
+ }
170
+ async planTableUpdates(changes, options = {}) {
171
+ return this.core.withCommandContext({ signal: options.signal, origin: options.origin ?? "api" }, () => this.core.run("table.plan", async (session) => {
172
+ this.core.rejectDuringStagedTransaction(session, "Table edits");
173
+ const bounded = Array.isArray(changes) &&
174
+ changes.length >= 1 &&
175
+ changes.length <= 100 &&
176
+ Buffer.byteLength(JSON.stringify(changes), "utf8") <= 256 * 1024;
177
+ if (!bounded)
178
+ throw new StateQLError("INVALID_COMMAND", "Table edit batch must contain 1-100 bounded rows.");
179
+ const connection = this.core.requireConnection(session);
180
+ if (connection.read_only)
181
+ throw new StateQLError("READ_ONLY_CONNECTION", "This connection is read-only.");
182
+ if (connection.driver === "redis")
183
+ throw new StateQLError("UNSUPPORTED_DRIVER", "Redis does not support table edits.");
184
+ const tokens = new Set();
185
+ const identities = new Set();
186
+ const updates = [];
187
+ let expires = Number.MAX_SAFE_INTEGER;
188
+ const metadataByTable = new Map();
189
+ for (const item of changes) {
190
+ if (!item || typeof item.row_token !== "string" || tokens.has(item.row_token))
191
+ throw new StateQLError("INVALID_COMMAND", "Table edit row tokens must be unique.");
192
+ tokens.add(item.row_token);
193
+ const original = this.liveEditToken(item.row_token, session, connection);
194
+ if (!original)
195
+ throw new StateQLError("STALE_PLAN", "A row identity expired or the connection changed. Reload the rows.");
196
+ const tableKey = JSON.stringify(original.metadata.table);
197
+ let metadata = metadataByTable.get(tableKey);
198
+ if (!metadata) {
199
+ metadata = await this.editableMetadata(original.metadata.table, options);
200
+ metadataByTable.set(tableKey, metadata);
201
+ }
202
+ if (JSON.stringify(metadata) !== JSON.stringify(original.metadata))
203
+ throw new StateQLError("STALE_PLAN", "Table metadata changed. Reload the table.");
204
+ const identity = tableUpdateIdentity(metadata, original.original);
205
+ if (identities.has(identity))
206
+ throw new StateQLError("INVALID_COMMAND", "The same row cannot appear twice in one edit batch.");
207
+ identities.add(identity);
208
+ const update = { metadata, original: original.original, changes: item.changes };
209
+ compileTableUpdate(update);
210
+ updates.push(update);
211
+ expires = Math.min(expires, original.expires);
212
+ }
213
+ return runPlan(this.core, session, connection, tableEditPlan(`Conditional table update batch (${updates.length} rows)`, JSON.stringify({ version: 1, updates }), "table.updates", expires), options);
214
+ }));
215
+ }
216
+ async editableMetadata(table, options) {
217
+ const connection = this.host.snapshot({ historyLimit: 1 }).connection;
218
+ const driver = connection.driver;
219
+ const unavailable = { table, driver, columns: [], writable: false, reason: "This table or its values cannot be edited safely." };
220
+ // The legacy inspection API splits qualified names. Fail closed for ambiguous names.
221
+ if (table.name.includes(".") || table.schema?.includes("."))
222
+ return { ...unavailable, reason: "Editing identifiers containing dots is not supported." };
223
+ const name = driver === "sqlite" || driver === "mongodb" ? table.name : [table.schema, table.name].filter(Boolean).join(".");
224
+ const response = await this.host.inspect("editable", name, options);
225
+ if (!response.ok)
226
+ return { ...unavailable, reason: response.error.code };
227
+ const value = response.data;
228
+ if (!value || !Array.isArray(value.columns) || value.columns.length > 100)
229
+ return unavailable;
230
+ return {
231
+ table,
232
+ driver,
233
+ columns: value.columns,
234
+ writable: value.writable === true && !connection.read_only,
235
+ ...(value.writable ? {} : { reason: "Only ordinary tables with transactional writes and a primary key can be edited." }),
236
+ };
237
+ }
238
+ issueEditToken(metadata, row, result) {
239
+ const now = this.core.now().getTime();
240
+ for (const [key, entry] of this.editTokens)
241
+ if (entry.expires <= now)
242
+ this.editTokens.delete(key);
243
+ if (this.editTokens.size >= 1000)
244
+ this.editTokens.delete(this.editTokens.keys().next().value);
245
+ const token = randomUUID();
246
+ this.editTokens.set(token, {
247
+ metadata,
248
+ original: structuredClone(row),
249
+ sessionId: result.session_id,
250
+ connectionId: result.connection_id,
251
+ stateVersion: result.state_version,
252
+ expires: now + EDIT_TOKEN_TTL_MS,
253
+ });
254
+ return token;
255
+ }
256
+ liveEditToken(token, session, connection) {
257
+ const entry = this.editTokens.get(token);
258
+ const live = entry !== undefined &&
259
+ entry.sessionId === session.id &&
260
+ entry.connectionId === connection.id &&
261
+ entry.stateVersion === version(connection) &&
262
+ entry.expires > this.core.now().getTime();
263
+ return live ? entry : undefined;
264
+ }
265
+ panelResult(id) {
266
+ if (typeof id !== "string" || !id || id.length > 200)
267
+ throw new StateQLError("INVALID_COMMAND", "A result ID is required.");
268
+ const session = this.core.store.ensureSession(this.core.sessionName);
269
+ if (!this.core.store.isSessionMember(session.id, this.core.actorId))
270
+ this.core.throwMembershipDenied(session);
271
+ const result = this.core.requireResult(id, session);
272
+ if (result.id !== id)
273
+ throw new StateQLError("INVALID_COMMAND", "Use an immutable result ID, not an alias.");
274
+ if (Date.parse(result.expires_at) <= this.core.now().getTime())
275
+ throw new StateQLError("RESULT_EXPIRED", "Result expired. Run the query again.");
276
+ if (result.row_count > 10_000 || Buffer.byteLength(result.rows_json, "utf8") > 16 * 1024 * 1024) {
277
+ throw new StateQLError("OUTPUT_LIMIT_EXCEEDED", "Stored result exceeds browser limits.");
278
+ }
279
+ return result;
280
+ }
281
+ fullResultRows(result) {
282
+ if (this.panelRows?.id !== result.id || this.panelRows.json !== result.rows_json) {
283
+ this.panelRows = { id: result.id, json: result.rows_json, rows: this.core.store.resultRows(result) };
284
+ }
285
+ return this.panelRows.rows;
286
+ }
287
+ }
288
+ function tableEditPlan(descriptor, payload, statementType, expires) {
289
+ return {
290
+ descriptor,
291
+ parameters: [payload],
292
+ statementType,
293
+ destructive: false,
294
+ allowUnbounded: false,
295
+ allowDestructive: false,
296
+ requiredOverrides: [],
297
+ requiresConfirmation: true,
298
+ expiresAt: new Date(expires).toISOString(),
299
+ };
300
+ }
301
+ function validTableName(table) {
302
+ const validPart = (value) => typeof value === "string" && value.length > 0 && value.length <= 500 && !value.includes("\0");
303
+ return Boolean(table) && validPart(table.name) && (table.schema === undefined || validPart(table.schema));
304
+ }
305
+ function tableUpdateIdentity(metadata, row) {
306
+ const identity = metadata.driver === "mongodb"
307
+ ? { table: metadata.table, id: row._id }
308
+ : {
309
+ table: metadata.table,
310
+ keys: metadata.columns
311
+ .filter((column) => column.key > 0)
312
+ .sort((a, b) => a.key - b.key)
313
+ .map((column) => [column.name, row[column.name]]),
314
+ };
315
+ return hash(identity);
316
+ }
@@ -0,0 +1,31 @@
1
+ import type { DatabaseAdapter } from "./adapters.js";
2
+ import { type ActionResult, type Core } from "./core.js";
3
+ import type { ConnectionRecord, SessionRecord } from "./store.js";
4
+ import { type EditableTable, type TableIdentity } from "./table-editor.js";
5
+ import type { ApplyData, ExecutionOptions, PlanData, PlanOptions, MongoPlanOptions, SqlParameters } from "./types.js";
6
+ interface PlanMeasurement {
7
+ parameters?: SqlParameters;
8
+ estimatedRows?: number;
9
+ }
10
+ /** A validated plan for one driver; runPlan records it against the current database state. */
11
+ export interface PlanStatement {
12
+ descriptor: string;
13
+ parameters: SqlParameters;
14
+ statementType: string;
15
+ destructive: boolean;
16
+ allowUnbounded: boolean;
17
+ allowDestructive: boolean;
18
+ requiredOverrides: string[];
19
+ requiresConfirmation: boolean;
20
+ expiresAt?: string;
21
+ measure?(adapter: DatabaseAdapter): Promise<PlanMeasurement>;
22
+ }
23
+ export type EditableMetadata = (table: TableIdentity, options: ExecutionOptions) => Promise<EditableTable>;
24
+ export declare function prepareSqlPlan(connection: ConnectionRecord, sql: string, options: PlanOptions): PlanStatement;
25
+ export declare function prepareMongoPlan(command: unknown, options: MongoPlanOptions): PlanStatement;
26
+ export declare function prepareRedisPlan(command: unknown): PlanStatement;
27
+ /** Saves a plan bound to the current state version and database signature. */
28
+ export declare function runPlan(core: Core, session: SessionRecord, connection: ConnectionRecord, statement: PlanStatement, options: ExecutionOptions): Promise<ActionResult<PlanData>>;
29
+ /** Applies a plan once, only if the connection and database state still match it. */
30
+ export declare function applyPlan(core: Core, session: SessionRecord, planId: string, options: ExecutionOptions, editableMetadata: EditableMetadata, recordSql: (sql: string | undefined) => void): Promise<ActionResult<ApplyData>>;
31
+ export {};
@@ -0,0 +1,275 @@
1
+ import { version } from "./connection.js";
2
+ import { adapterOfKind, rejectSqlOnNativeConnection, } from "./core.js";
3
+ import { StateQLError } from "./errors.js";
4
+ import { AdapterExecutionError } from "./execution.js";
5
+ import { analyzeMongoWriteSafety, serializeMongoCommand, validateMongoWriteCommand } from "./mongodb.js";
6
+ import { invalidCommand, mongoDescriptor, redisDescriptor } from "./reads.js";
7
+ import { deserializeRedisCommand, serializeRedisCommand, validateRedisWriteCommand, } from "./redis.js";
8
+ import { analyzeSql, matchedRowsCount } from "./sql.js";
9
+ import { compileTableUpdate, parseTableUpdate, parseTableUpdates, } from "./table-editor.js";
10
+ import { isSqlParameters, parseJson } from "./util.js";
11
+ import { prepareMongoWrite, prepareRedisWrite, prepareSqlWrite, prepareTableBatch, runWrite, storedMongoWrite, } from "./writes.js";
12
+ const PLAN_TTL_MS = 10 * 60_000;
13
+ export function prepareSqlPlan(connection, sql, options) {
14
+ const analysis = analyzeSql(sql, connection.driver);
15
+ if (analysis.read) {
16
+ throw new StateQLError("INVALID_SQL", "plan accepts write statements only.");
17
+ }
18
+ const parameters = options.params ?? [];
19
+ return {
20
+ ...guardedPlan(analysis.unboundedMutation, analysis.destructive, options),
21
+ descriptor: sql,
22
+ parameters,
23
+ statementType: analysis.statementType,
24
+ async measure(adapter) {
25
+ const count = matchedRowsCount(analysis, parameters, connection.driver);
26
+ return { estimatedRows: await countMatchedRows(adapterOfKind(adapter, "sql"), count) };
27
+ },
28
+ };
29
+ }
30
+ export function prepareMongoPlan(command, options) {
31
+ const value = invalidCommand(() => validateMongoWriteCommand(command));
32
+ const unsafe = analyzeMongoWriteSafety(value);
33
+ return {
34
+ ...guardedPlan(unsafe.unbounded, unsafe.destructive, options),
35
+ descriptor: mongoDescriptor(value.operation),
36
+ parameters: [serializeMongoCommand(value)],
37
+ statementType: `mongo.${value.operation}`,
38
+ };
39
+ }
40
+ export function prepareRedisPlan(command) {
41
+ const value = invalidCommand(() => validateRedisWriteCommand(command));
42
+ return {
43
+ descriptor: redisDescriptor(value.command),
44
+ parameters: [],
45
+ statementType: `redis.${value.command.toLowerCase()}`,
46
+ destructive: value.command === "DEL",
47
+ allowUnbounded: false,
48
+ allowDestructive: true,
49
+ requiredOverrides: [],
50
+ requiresConfirmation: true,
51
+ async measure(adapter) {
52
+ const precondition = await adapterOfKind(adapter, "redis").precondition(value);
53
+ return { parameters: [JSON.stringify({ command: serializeRedisCommand(value), precondition })] };
54
+ },
55
+ };
56
+ }
57
+ /** Saves a plan bound to the current state version and database signature. */
58
+ export async function runPlan(core, session, connection, statement, options) {
59
+ const context = core.executionContext(options);
60
+ return core.withAdapter(session, connection, "plan", context, async (adapter) => {
61
+ const stateSignature = await adapter.signature();
62
+ const measured = await statement.measure?.(adapter) ?? {};
63
+ const plan = core.store.savePlan({
64
+ sessionId: session.id,
65
+ ownerActorId: core.actorId,
66
+ connectionId: connection.id,
67
+ sql: statement.descriptor,
68
+ parameters: measured.parameters ?? statement.parameters,
69
+ statementType: statement.statementType,
70
+ stateVersion: version(connection),
71
+ stateSignature,
72
+ destructive: statement.destructive,
73
+ allowUnbounded: statement.allowUnbounded,
74
+ allowDestructive: statement.allowDestructive,
75
+ expiresAt: statement.expiresAt ?? core.expiresAt(PLAN_TTL_MS),
76
+ });
77
+ return {
78
+ data: {
79
+ plan_id: plan.id,
80
+ statement_type: plan.statement_type,
81
+ destructive: Boolean(plan.destructive),
82
+ requires_confirmation: statement.requiresConfirmation,
83
+ required_overrides: statement.requiredOverrides,
84
+ state_version: plan.state_version,
85
+ owner_actor_id: plan.owner_actor_id,
86
+ expires_at: plan.expires_at,
87
+ ...(measured.estimatedRows === undefined ? {} : { estimated_rows: measured.estimatedRows }),
88
+ },
89
+ handle: plan.id,
90
+ executed: true,
91
+ stateVersion: plan.state_version,
92
+ confidence: adapter.confidence,
93
+ };
94
+ });
95
+ }
96
+ /** Applies a plan once, only if the connection and database state still match it. */
97
+ export async function applyPlan(core, session, planId, options, editableMetadata, recordSql) {
98
+ core.rejectDuringStagedTransaction(session, "Plans");
99
+ const plan = core.store.getPlan(planId);
100
+ if (!plan || plan.session_id !== session.id) {
101
+ throw new StateQLError("STALE_PLAN", `Plan "${planId}" was not found.`);
102
+ }
103
+ if (plan.owner_actor_id !== core.actorId) {
104
+ throw new StateQLError("PERMISSION_DENIED", "Only the actor that created this plan may apply it.");
105
+ }
106
+ if (plan.applied_operation_id) {
107
+ throw new StateQLError("STALE_PLAN", "Plan was already applied.", {
108
+ extra: { previous_operation_id: plan.applied_operation_id },
109
+ });
110
+ }
111
+ if (Date.parse(plan.expires_at) <= core.now().getTime()) {
112
+ throw new StateQLError("STALE_PLAN", "Plan has expired.");
113
+ }
114
+ const tableMetadata = storedTableMetadata(plan);
115
+ const stored = storedPlan(plan);
116
+ const targetDriver = tableMetadata[0]?.driver === "mongodb" || stored.kind === "mongo"
117
+ ? "mongodb"
118
+ : stored.kind === "redis" ? "redis" : "sql";
119
+ recordSql(stored.kind === "sql" ? plan.sql : undefined);
120
+ const claimToken = core.store.randomId("claim");
121
+ const claimed = core.store.claimPlan(plan.id, session.id, core.actorId, claimToken);
122
+ if (!claimed)
123
+ throw new StateQLError("STALE_PLAN", "Plan is already being applied.");
124
+ let retainClaim = false;
125
+ try {
126
+ const connection = core.requireConnection(session);
127
+ const stateChanged = connection.id !== claimed.connection_id || version(connection) !== claimed.state_version;
128
+ if (stateChanged) {
129
+ throw new StateQLError("STALE_PLAN", "Database state changed after this plan was created.");
130
+ }
131
+ if (targetDriver === "mongodb" && connection.driver !== "mongodb") {
132
+ throw new StateQLError("STALE_PLAN", "MongoDB plan is not attached to a MongoDB connection.");
133
+ }
134
+ if (targetDriver === "redis" && connection.driver !== "redis") {
135
+ throw new StateQLError("STALE_PLAN", "Redis plan is not attached to a Redis connection.");
136
+ }
137
+ if (targetDriver === "sql")
138
+ rejectSqlOnNativeConnection(connection, "plan");
139
+ for (const metadata of tableMetadata) {
140
+ const current = await editableMetadata(metadata.table, options);
141
+ if (JSON.stringify(current) !== JSON.stringify(metadata)) {
142
+ throw new StateQLError("STALE_PLAN", "Table metadata changed. Reload and plan again.");
143
+ }
144
+ }
145
+ const context = core.executionContext(options);
146
+ const source = await core.resolveConnectionSource(connection, session, "apply", "write", context);
147
+ await core.runOnAdapter(connection, context, source, async (adapter) => {
148
+ if ((await adapter.signature()) !== claimed.state_signature) {
149
+ throw new StateQLError("STALE_PLAN", "Database state changed after this plan was created.");
150
+ }
151
+ });
152
+ const statement = plannedWrite(connection, claimed, stored);
153
+ const result = await runWrite(core, session, connection, statement, { replay: stored.kind === "table-batch" }, context, { planId: claimed.id, claimToken, source });
154
+ return { ...result, data: { plan_id: claimed.id, ...result.data } };
155
+ }
156
+ catch (error) {
157
+ if (error instanceof StateQLError && error.details.code === "OUTCOME_UNKNOWN")
158
+ retainClaim = true;
159
+ throw error;
160
+ }
161
+ finally {
162
+ if (!retainClaim)
163
+ core.store.releasePlanClaim(plan.id, claimToken);
164
+ }
165
+ }
166
+ function guardedPlan(unbounded, destructive, options) {
167
+ const allowUnbounded = options.allowUnbounded ?? false;
168
+ const allowDestructive = options.allowDestructive ?? false;
169
+ const requiredOverrides = [
170
+ ...(unbounded && !allowUnbounded ? ["--allow-unbounded"] : []),
171
+ ...(destructive && !allowDestructive ? ["--allow-destructive"] : []),
172
+ ];
173
+ return {
174
+ destructive: destructive || unbounded,
175
+ allowUnbounded,
176
+ allowDestructive,
177
+ requiredOverrides,
178
+ requiresConfirmation: requiredOverrides.length > 0,
179
+ };
180
+ }
181
+ function storedTableMetadata(plan) {
182
+ if (plan.statement_type === "table.update")
183
+ return [parseTableUpdate(plan.parameters).metadata];
184
+ if (plan.statement_type === "table.updates")
185
+ return parseTableUpdates(plan.parameters).map((update) => update.metadata);
186
+ return [];
187
+ }
188
+ function storedPlan(plan) {
189
+ if (plan.statement_type === "table.updates") {
190
+ const updates = parseTableUpdates(plan.parameters);
191
+ return { kind: "table-batch", updates, compiled: updates.map(compileTableUpdate) };
192
+ }
193
+ if (plan.statement_type === "table.update") {
194
+ const compiled = compileTableUpdate(parseTableUpdate(plan.parameters));
195
+ if (compiled.sql !== plan.sql)
196
+ throw new StateQLError("STALE_PLAN", "Stored update does not match its plan.");
197
+ if (compiled.mongo)
198
+ return { kind: "mongo", command: compiled.mongo, expectedRows: 1 };
199
+ return { kind: "sql", sql: plan.sql, parameters: compiled.params, expectedRows: 1 };
200
+ }
201
+ if (plan.statement_type.startsWith("mongo.")) {
202
+ return {
203
+ kind: "mongo",
204
+ command: storedMongoWrite(plan.parameters, plan.statement_type, `plan "${plan.id}"`, "STALE_PLAN"),
205
+ };
206
+ }
207
+ if (plan.statement_type.startsWith("redis.")) {
208
+ return { kind: "redis", ...storedRedisPlan(plan.parameters, plan.statement_type, plan.id) };
209
+ }
210
+ return {
211
+ kind: "sql",
212
+ sql: plan.sql,
213
+ parameters: parseJson(plan.parameters, `plan "${plan.id}" parameters`, isSqlParameters),
214
+ };
215
+ }
216
+ function plannedWrite(connection, claimed, stored) {
217
+ const safety = {
218
+ allowUnbounded: Boolean(claimed.allow_unbounded),
219
+ allowDestructive: Boolean(claimed.allow_destructive),
220
+ };
221
+ switch (stored.kind) {
222
+ case "sql":
223
+ return prepareSqlWrite(connection, claimed.sql, stored.parameters, {
224
+ ...safety,
225
+ ...(stored.expectedRows ? { expectedRows: stored.expectedRows } : {}),
226
+ });
227
+ case "mongo":
228
+ return prepareMongoWrite(connection, stored.command, {
229
+ ...safety,
230
+ ...(stored.expectedRows ? { expectedRows: stored.expectedRows } : {}),
231
+ });
232
+ case "redis":
233
+ return prepareRedisWrite(connection, stored.command, stored.precondition);
234
+ case "table-batch":
235
+ return prepareTableBatch(connection, claimed.id, stored.updates, stored.compiled);
236
+ }
237
+ }
238
+ function storedRedisPlan(parameters, statementType, planId) {
239
+ try {
240
+ const outer = JSON.parse(parameters);
241
+ if (!Array.isArray(outer) || outer.length !== 1 || typeof outer[0] !== "string")
242
+ throw new Error();
243
+ const payload = JSON.parse(outer[0]);
244
+ if (typeof payload.command !== "string" || !payload.precondition || typeof payload.precondition !== "object")
245
+ throw new Error();
246
+ const command = deserializeRedisCommand(payload.command);
247
+ const precondition = payload.precondition;
248
+ const valid = typeof precondition.key === "string" &&
249
+ typeof precondition.fingerprint === "string" &&
250
+ typeof precondition.expiresAt === "number" &&
251
+ Number.isFinite(precondition.expiresAt) &&
252
+ statementType === `redis.${command.command.toLowerCase()}`;
253
+ if (!valid)
254
+ throw new Error();
255
+ return { command, precondition };
256
+ }
257
+ catch {
258
+ throw new StateQLError("STALE_PLAN", `Stored Redis plan "${planId}" payload is invalid.`);
259
+ }
260
+ }
261
+ async function countMatchedRows(adapter, count) {
262
+ if (!count)
263
+ return undefined;
264
+ try {
265
+ const { rows } = await adapter.read(count.sql, count.params);
266
+ const value = Number(Object.values(rows[0] ?? {})[0]);
267
+ return Number.isSafeInteger(value) ? value : undefined;
268
+ }
269
+ catch (error) {
270
+ if (error instanceof AdapterExecutionError)
271
+ throw error;
272
+ // The estimate is advisory; a count the parser cannot express must not block the plan.
273
+ return undefined;
274
+ }
275
+ }
@@ -0,0 +1,35 @@
1
+ import type { DatabaseAdapter } from "./adapters.js";
2
+ import { type ActionResult, type Core } from "./core.js";
3
+ import type { ConnectionRecord, SessionRecord } from "./store.js";
4
+ import type { Column, ExecutionOptions, ResultData, Row, SqlParameters, Warning } from "./types.js";
5
+ interface ReadOutput {
6
+ rows: Row[];
7
+ columns: Column[];
8
+ parameters?: SqlParameters;
9
+ }
10
+ /** A validated read for one driver; runRead does the caching, limits, and storage. */
11
+ export interface ReadStatement {
12
+ descriptor: string;
13
+ identity: Record<string, unknown>;
14
+ parameters: SqlParameters;
15
+ cacheable: boolean;
16
+ warnings: Warning[];
17
+ limitHint: string;
18
+ execute(adapter: DatabaseAdapter, fetchLimit: number): Promise<ReadOutput>;
19
+ }
20
+ export interface ReadOptions extends ExecutionOptions {
21
+ cache?: "auto" | "bypass" | "require";
22
+ previewRows?: number;
23
+ }
24
+ export declare function prepareSqlRead(connection: ConnectionRecord, sql: string, parameters: SqlParameters): ReadStatement;
25
+ export declare function prepareMongoRead(command: unknown): ReadStatement;
26
+ export declare function prepareRedisRead(command: unknown): ReadStatement;
27
+ /** Serves a valid cached result, or runs the read and stores the bounded result. */
28
+ export declare function runRead(core: Core, session: SessionRecord, connection: ConnectionRecord, statement: ReadStatement, options: ReadOptions): Promise<ActionResult<ResultData>>;
29
+ export declare function queryPreviewRows(value: number): number;
30
+ export declare function sqlParametersLength(parameters: SqlParameters): number;
31
+ export declare function mongoDescriptor(operation: string): string;
32
+ export declare function redisDescriptor(command: string): string;
33
+ /** Driver validators throw plain errors; callers see them as INVALID_COMMAND. */
34
+ export declare function invalidCommand<T>(validate: () => T): T;
35
+ export {};