@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
@@ -101,7 +101,7 @@ export function parseTableUpdate(parameters) {
101
101
  if (!Array.isArray(outer) || outer.length !== 1 || typeof outer[0] !== "string" || outer[0].length > 128 * 1024)
102
102
  throw new Error();
103
103
  const update = JSON.parse(outer[0]);
104
- if (!update || !update.metadata || !["sqlite", "postgres", "mysql", "mongodb"].includes(update.metadata.driver) ||
104
+ if (!update?.metadata || !["sqlite", "postgres", "mysql", "mongodb"].includes(update.metadata.driver) ||
105
105
  !Array.isArray(update.metadata.columns) || update.metadata.columns.length > 100 ||
106
106
  !update.metadata.columns.every(column => typeof column.name === "string" && typeof column.type === "string" && typeof column.nullable === "boolean" && typeof column.generated === "boolean" && Number.isSafeInteger(column.key)) ||
107
107
  !update.original || !update.changes || typeof update.changes !== "object")
@@ -119,7 +119,7 @@ export function parseTableUpdates(parameters) {
119
119
  if (!Array.isArray(outer) || outer.length !== 1 || typeof outer[0] !== "string" || outer[0].length > 512 * 1024)
120
120
  throw new Error();
121
121
  const batch = JSON.parse(outer[0]);
122
- if (!batch || batch.version !== 1 || !Array.isArray(batch.updates) || batch.updates.length < 1 || batch.updates.length > 100)
122
+ if (batch?.version !== 1 || !Array.isArray(batch.updates) || batch.updates.length < 1 || batch.updates.length > 100)
123
123
  throw new Error();
124
124
  for (const update of batch.updates) {
125
125
  if (!update?.metadata || !["sqlite", "postgres", "mysql", "mongodb"].includes(update.metadata.driver) ||
@@ -0,0 +1,8 @@
1
+ import { type ActionResult, type Core } from "./core.js";
2
+ import type { SessionRecord } from "./store.js";
3
+ import type { CommitTransactionData, ExecutionOptions, RollbackTransactionData, TransactionData } from "./types.js";
4
+ export declare function beginTransaction(core: Core, session: SessionRecord, isolation: string | undefined): ActionResult<TransactionData>;
5
+ export declare function transactionStatus(core: Core, session: SessionRecord, id: string | undefined): ActionResult<TransactionData>;
6
+ /** Runs every staged write in one database transaction, then records the outcome. */
7
+ export declare function commitTransaction(core: Core, session: SessionRecord, id: string | undefined, options: ExecutionOptions): Promise<ActionResult<CommitTransactionData>>;
8
+ export declare function rollbackTransaction(core: Core, session: SessionRecord, id: string | undefined): ActionResult<RollbackTransactionData>;
@@ -0,0 +1,186 @@
1
+ import { version } from "./connection.js";
2
+ import { adapterOfKind, closeAdapterQuietly, safeCredentialErrorMessage, } from "./core.js";
3
+ import { StateQLError } from "./errors.js";
4
+ import { AdapterExecutionError, BatchWriteError, stoppedStateQLError, } from "./execution.js";
5
+ import { transactionData } from "./response-data.js";
6
+ import { storedMongoOperation } from "./writes.js";
7
+ const COMMIT_UNKNOWN_ACTION = "Inspect database state before issuing any replacement write.";
8
+ export function beginTransaction(core, session, isolation) {
9
+ const connection = core.requireConnection(session);
10
+ if (connection.driver === "redis") {
11
+ throw new StateQLError("UNSUPPORTED_DRIVER", "Redis does not support staged StateQL transactions; use redisPlan/apply for one guarded mutation.");
12
+ }
13
+ if (connection.read_only) {
14
+ throw new StateQLError("READ_ONLY_CONNECTION", "Cannot begin a write transaction on a read-only connection.");
15
+ }
16
+ if (session.active_transaction_id) {
17
+ throw new StateQLError("TRANSACTION_FAILED", `Transaction "${session.active_transaction_id}" is already active.`);
18
+ }
19
+ const transaction = core.store.createTransaction({
20
+ sessionId: session.id,
21
+ actorId: core.actorId,
22
+ connectionId: connection.id,
23
+ isolation: normalizeIsolation(isolation ?? (connection.driver === "mongodb" ? "snapshot" : "serializable"), connection.driver),
24
+ });
25
+ if (!transaction) {
26
+ throw new StateQLError("TRANSACTION_FAILED", "Another actor acquired the active transaction.");
27
+ }
28
+ return {
29
+ data: transactionData(transaction, 0),
30
+ handle: transaction.id,
31
+ executed: true,
32
+ stateVersion: transaction.start_version,
33
+ };
34
+ }
35
+ export function transactionStatus(core, session, id) {
36
+ const transactionId = id ?? session.active_transaction_id;
37
+ if (!transactionId) {
38
+ throw new StateQLError("TRANSACTION_NOT_FOUND", "No active transaction.");
39
+ }
40
+ const transaction = core.store.getTransaction(transactionId);
41
+ if (!transaction || transaction.session_id !== session.id) {
42
+ throw new StateQLError("TRANSACTION_NOT_FOUND", `Transaction "${transactionId}" was not found.`);
43
+ }
44
+ return {
45
+ data: transactionData(transaction, core.store.transactionOperations(transaction.id).length),
46
+ handle: transaction.id,
47
+ stateVersion: transaction.start_version,
48
+ };
49
+ }
50
+ /** Runs every staged write in one database transaction, then records the outcome. */
51
+ export async function commitTransaction(core, session, id, options) {
52
+ const transaction = core.requireActiveTransaction(session, id);
53
+ const connection = core.store.getConnection(transaction.connection_id);
54
+ if (!connection) {
55
+ throw new StateQLError("CONNECTION_NOT_FOUND", "Transaction connection was not found.");
56
+ }
57
+ if (version(connection) !== transaction.start_version) {
58
+ throw new StateQLError("TRANSACTION_FAILED", "Connection state changed after the transaction began.", { suggestedAction: "Roll back and begin a new transaction." });
59
+ }
60
+ // Validate durable payloads before opening a database adapter or changing the transaction state.
61
+ const operations = core.store.validatedTransactionOperations(transaction.id);
62
+ if (operations.some((operation) => operation.connection_id !== connection.id)) {
63
+ throw new StateQLError("TRANSACTION_FAILED", "Transaction contains writes staged for another connection.");
64
+ }
65
+ const mongoCommands = connection.driver === "mongodb"
66
+ ? operations.map(storedMongoOperation)
67
+ : undefined;
68
+ const sqlHasMongoWrites = !mongoCommands &&
69
+ operations.some((operation) => operation.statement_type.startsWith("mongo."));
70
+ if (sqlHasMongoWrites) {
71
+ throw new StateQLError("TRANSACTION_FAILED", "Transaction contains native MongoDB writes for a SQL connection.");
72
+ }
73
+ const context = core.executionContext(options);
74
+ const source = await core.resolveConnectionSource(connection, session, "transaction.commit", "write", context);
75
+ const adapter = await core.openAdapter(connection, context, source);
76
+ const markUnknown = () => markTransactionOutcomeUnknown(core.store, transaction.id, session.id, core.actorId);
77
+ const outcomeUnknown = (message) => new StateQLError("OUTCOME_UNKNOWN", message, {
78
+ executed: true,
79
+ suggestedAction: COMMIT_UNKNOWN_ACTION,
80
+ });
81
+ try {
82
+ if (!core.store.claimTransactionForCommit(transaction.id, session.id, core.actorId, operations)) {
83
+ throw new StateQLError("TRANSACTION_FAILED", "Transaction is no longer active.");
84
+ }
85
+ let results;
86
+ try {
87
+ results = mongoCommands
88
+ ? await adapterOfKind(adapter, "mongodb").writeBatch(mongoCommands, transaction.isolation_level)
89
+ : await adapterOfKind(adapter, "sql").writeBatch(operations, transaction.isolation_level);
90
+ }
91
+ catch (error) {
92
+ const definite = (error instanceof BatchWriteError || error instanceof AdapterExecutionError) &&
93
+ !error.outcomeUnknown;
94
+ if (!definite) {
95
+ markUnknown();
96
+ throw outcomeUnknown(safeCredentialErrorMessage(error, source));
97
+ }
98
+ core.store.finishTransaction(transaction.id, session.id, core.actorId, "failed");
99
+ if (error instanceof AdapterExecutionError)
100
+ throw stoppedStateQLError(error, false);
101
+ throw new StateQLError("TRANSACTION_FAILED", safeCredentialErrorMessage(error, source), { retryable: true });
102
+ }
103
+ if (results.length !== operations.length) {
104
+ markUnknown();
105
+ throw outcomeUnknown("Database returned an incomplete transaction result.");
106
+ }
107
+ let stateVersion;
108
+ try {
109
+ stateVersion = core.store.commitTransactionMetadata({
110
+ transactionId: transaction.id,
111
+ sessionId: session.id,
112
+ actorId: core.actorId,
113
+ connectionId: connection.id,
114
+ operations: operations.map((operation, index) => ({
115
+ id: operation.id,
116
+ affectedRows: results[index].affectedRows,
117
+ ...(results[index].outcome ? { outcome: results[index].outcome } : {}),
118
+ })),
119
+ });
120
+ }
121
+ catch (error) {
122
+ markUnknown();
123
+ throw outcomeUnknown(safeCredentialErrorMessage(error, source));
124
+ }
125
+ return {
126
+ data: {
127
+ transaction_id: transaction.id,
128
+ state: "committed",
129
+ statements_executed: operations.length,
130
+ affected_rows: results.reduce((total, result) => total + result.affectedRows, 0),
131
+ state_version: stateVersion,
132
+ },
133
+ handle: transaction.id,
134
+ executed: true,
135
+ stateVersion,
136
+ confidence: adapter.confidence,
137
+ };
138
+ }
139
+ finally {
140
+ await closeAdapterQuietly(adapter);
141
+ }
142
+ }
143
+ export function rollbackTransaction(core, session, id) {
144
+ const transaction = core.requireActiveTransaction(session, id);
145
+ const count = core.store.transactionOperations(transaction.id).length;
146
+ if (!core.store.finishTransaction(transaction.id, session.id, core.actorId, "rolled_back")) {
147
+ throw new StateQLError("TRANSACTION_FAILED", "Transaction is no longer active.");
148
+ }
149
+ return {
150
+ data: {
151
+ transaction_id: transaction.id,
152
+ state: "rolled_back",
153
+ discarded_statements: count,
154
+ },
155
+ handle: transaction.id,
156
+ executed: true,
157
+ stateVersion: transaction.start_version,
158
+ };
159
+ }
160
+ function markTransactionOutcomeUnknown(store, transactionId, sessionId, actorId) {
161
+ try {
162
+ store.markTransactionOutcomeUnknown(transactionId, sessionId, actorId);
163
+ }
164
+ catch {
165
+ // A stale committing transaction is recovered as unknown after five minutes.
166
+ }
167
+ }
168
+ function normalizeIsolation(isolation, driver) {
169
+ const normalized = isolation.trim().toLowerCase().replace(/[_-]+/g, " ").replace(/\s+/g, " ");
170
+ if (driver === "redis") {
171
+ throw new StateQLError("UNSUPPORTED_DRIVER", "Redis does not support staged SQL-style transactions.");
172
+ }
173
+ if (driver === "mongodb") {
174
+ if (normalized === "snapshot")
175
+ return normalized;
176
+ throw new StateQLError("INVALID_COMMAND", `MongoDB does not support isolation level "${normalized}".`);
177
+ }
178
+ const supported = new Set(["serializable", "repeatable read", "read committed", "read uncommitted"]);
179
+ if (!supported.has(normalized)) {
180
+ throw new StateQLError("INVALID_COMMAND", `Unsupported isolation level "${isolation}".`);
181
+ }
182
+ if (driver === "sqlite" && normalized !== "serializable") {
183
+ throw new StateQLError("INVALID_COMMAND", `SQLite does not support isolation level "${normalized}".`);
184
+ }
185
+ return normalized;
186
+ }
@@ -120,25 +120,11 @@ export interface StateQLSnapshot {
120
120
  database: string;
121
121
  read_only: boolean;
122
122
  } | null;
123
- transaction: {
124
- transaction_id: string;
125
- owner_actor_id: string;
126
- state: string;
127
- } | null;
123
+ transaction: TransactionReferenceData | null;
128
124
  state_version: string | null;
129
125
  state_confidence: StateConfidence | null;
130
- recent_results: Array<{
131
- alias: string | null;
132
- handle: string;
133
- rows: number;
134
- }>;
135
- recent_operations: Array<{
136
- handle: string;
137
- actor_id: string;
138
- type: string;
139
- affected_rows: number | null;
140
- status: string;
141
- }>;
126
+ recent_results: RecentResultData[];
127
+ recent_operations: RecentOperationData[];
142
128
  history: HistoryEntry[];
143
129
  }
144
130
  export type SqlParameters = unknown[] | Record<string, unknown>;
@@ -0,0 +1,48 @@
1
+ import type { DatabaseAdapter } from "./adapters.js";
2
+ import { type ActionResult, type Core } from "./core.js";
3
+ import { type AdapterContext } from "./execution.js";
4
+ import { type RedisPrecondition } from "./redis.js";
5
+ import type { ConnectionRecord, OperationRecord, SessionRecord } from "./store.js";
6
+ import type { compileTableUpdate, TableUpdate } from "./table-editor.js";
7
+ import type { ExecData, MongoWriteCommand, MongoWriteOutcome, SqlParameters } from "./types.js";
8
+ interface WriteOutput {
9
+ affectedRows: number;
10
+ outcome?: MongoWriteOutcome;
11
+ }
12
+ /** A validated write for one driver; runWrite does deduplication, staging, and outcome tracking. */
13
+ export interface WriteStatement {
14
+ descriptor: string;
15
+ parameters: SqlParameters;
16
+ statementType: string;
17
+ /** Duplicate-write protection compares this across versions; keep its input stable. */
18
+ fingerprint: string;
19
+ stagingError?: string;
20
+ conflictMessage: string;
21
+ unknownAction: string;
22
+ execute(adapter: DatabaseAdapter, operation: OperationRecord): Promise<WriteOutput>;
23
+ }
24
+ export interface WriteSafety {
25
+ allowUnbounded?: boolean;
26
+ allowDestructive?: boolean;
27
+ expectedRows?: 1;
28
+ }
29
+ export interface WriteOptions {
30
+ replay?: boolean;
31
+ idempotencyKey?: string;
32
+ }
33
+ /** A claimed plan that this write finishes; its source was resolved with write access. */
34
+ export interface PlanClaim {
35
+ planId: string;
36
+ claimToken: string;
37
+ source: string;
38
+ }
39
+ type CompiledTableUpdate = ReturnType<typeof compileTableUpdate>;
40
+ export declare function prepareSqlWrite(connection: ConnectionRecord, sql: string, parameters: SqlParameters, safety: WriteSafety): WriteStatement;
41
+ export declare function prepareMongoWrite(connection: ConnectionRecord, command: unknown, safety: WriteSafety): WriteStatement;
42
+ export declare function prepareRedisWrite(connection: ConnectionRecord, command: unknown, precondition?: RedisPrecondition): WriteStatement;
43
+ export declare function prepareTableBatch(connection: ConnectionRecord, planId: string, updates: TableUpdate[], compiled: CompiledTableUpdate[]): WriteStatement;
44
+ /** Reserves the write, stages it or runs it once, and records a definite or unknown outcome. */
45
+ export declare function runWrite(core: Core, session: SessionRecord, connection: ConnectionRecord, statement: WriteStatement, options: WriteOptions, context: AdapterContext, claim?: PlanClaim): Promise<ActionResult<ExecData>>;
46
+ export declare function storedMongoOperation(operation: OperationRecord): MongoWriteCommand;
47
+ export declare function storedMongoWrite(parameters: string, statementType: string, label: string, errorCode: string): MongoWriteCommand;
48
+ export {};
@@ -0,0 +1,320 @@
1
+ import { databaseIdentity, version } from "./connection.js";
2
+ import { adapterOfKind, closeAdapterQuietly, errorMessage, safeCredentialErrorMessage, } from "./core.js";
3
+ import { StateQLError } from "./errors.js";
4
+ import { AdapterExecutionError, AdapterWriteError, BatchWriteError, stoppedStateQLError, } from "./execution.js";
5
+ import { analyzeMongoWriteSafety, deserializeMongoWriteCommand, serializeMongoCommand, validateMongoWriteCommand, } from "./mongodb.js";
6
+ import { invalidCommand, mongoDescriptor, redisDescriptor, sqlParametersLength, } from "./reads.js";
7
+ import { serializeRedisCommand, validateRedisWriteCommand, } from "./redis.js";
8
+ import { operationData } from "./response-data.js";
9
+ import { analyzeSql } from "./sql.js";
10
+ import { hash } from "./util.js";
11
+ const REPLAY_ACTION = "Inspect database state, then use --replay only if another execution is safe.";
12
+ const FINALIZE_ACTION = "Inspect database state before issuing any replacement write.";
13
+ export function prepareSqlWrite(connection, sql, parameters, safety) {
14
+ const analysis = analyzeSql(sql, connection.driver);
15
+ if (analysis.read) {
16
+ throw new StateQLError("INVALID_SQL", "exec accepts write statements only; use query for reads.");
17
+ }
18
+ rejectUnsafeWrite(analysis.unboundedMutation, analysis.destructive, safety, "Mutation has no WHERE clause.", "Destructive operation requires an explicit override.");
19
+ const autocommitHasInputs = safety.expectedRows !== undefined || sqlParametersLength(parameters) > 0;
20
+ if (analysis.requiresAutocommit && autocommitHasInputs) {
21
+ throw new StateQLError("INVALID_SQL", "Autocommit maintenance statements do not accept StateQL parameters or row-count preconditions.");
22
+ }
23
+ const statementName = analysis.statementType.toUpperCase();
24
+ return {
25
+ descriptor: sql,
26
+ parameters,
27
+ statementType: analysis.statementType,
28
+ fingerprint: hash({
29
+ sql: analysis.normalized,
30
+ parameters,
31
+ database: databaseIdentity(connection),
32
+ }),
33
+ ...(analysis.requiresAutocommit
34
+ ? { stagingError: `${statementName} cannot be staged in a transaction.` }
35
+ : {}),
36
+ conflictMessage: "The row changed or no longer matches. Reload before editing.",
37
+ unknownAction: REPLAY_ACTION,
38
+ async execute(adapter) {
39
+ const sqlAdapter = adapterOfKind(adapter, "sql");
40
+ if (!analysis.requiresAutocommit)
41
+ return sqlAdapter.write(sql, parameters, safety.expectedRows);
42
+ if (!sqlAdapter.writeAutocommit) {
43
+ throw new AdapterWriteError(`${statementName} requires adapter autocommit execution.`, false);
44
+ }
45
+ return sqlAdapter.writeAutocommit(sql, parameters);
46
+ },
47
+ };
48
+ }
49
+ export function prepareMongoWrite(connection, command, safety) {
50
+ const value = invalidCommand(() => validateMongoWriteCommand(command));
51
+ const unsafe = analyzeMongoWriteSafety(value);
52
+ rejectUnsafeWrite(unsafe.unbounded, unsafe.destructive, safety, "MongoDB mutation has an empty filter.", "Destructive MongoDB operation requires an explicit override.");
53
+ const serialized = serializeMongoCommand(value);
54
+ return {
55
+ descriptor: mongoDescriptor(value.operation),
56
+ parameters: [serialized],
57
+ statementType: `mongo.${value.operation}`,
58
+ fingerprint: hash({ command: serialized, database: databaseIdentity(connection) }),
59
+ conflictMessage: "The document changed or was removed. Reload before editing.",
60
+ unknownAction: REPLAY_ACTION,
61
+ execute: (adapter) => adapterOfKind(adapter, "mongodb").write(value, safety.expectedRows),
62
+ };
63
+ }
64
+ export function prepareRedisWrite(connection, command, precondition) {
65
+ const value = invalidCommand(() => validateRedisWriteCommand(command));
66
+ const serialized = serializeRedisCommand(value);
67
+ return {
68
+ descriptor: redisDescriptor(value.command),
69
+ parameters: [serialized],
70
+ statementType: `redis.${value.command.toLowerCase()}`,
71
+ fingerprint: hash({ command: serialized, database: databaseIdentity(connection) }),
72
+ stagingError: "Redis writes cannot be staged in a transaction.",
73
+ conflictMessage: "The Redis key changed. Reload and plan again.",
74
+ unknownAction: "Inspect Redis state before issuing a replacement write.",
75
+ execute: (adapter) => adapterOfKind(adapter, "redis").write(value, precondition),
76
+ };
77
+ }
78
+ export function prepareTableBatch(connection, planId, updates, compiled) {
79
+ if (connection.driver === "redis") {
80
+ throw new StateQLError("UNSUPPORTED_DRIVER", "Redis does not support table edit batches.");
81
+ }
82
+ const mongoCommands = connection.driver === "mongodb"
83
+ ? compiled.map((item) => {
84
+ if (!item.mongo)
85
+ throw new StateQLError("STALE_PLAN", "Table edit batch contains mixed drivers.");
86
+ return item.mongo;
87
+ })
88
+ : undefined;
89
+ return {
90
+ descriptor: `Conditional table update batch (${updates.length} rows)`,
91
+ parameters: [JSON.stringify({ version: 1, updates })],
92
+ statementType: "table.updates",
93
+ fingerprint: hash({ plan: planId, updates }),
94
+ stagingError: "Table edit batches cannot be staged in a transaction.",
95
+ conflictMessage: "At least one row changed; the entire edit batch was rolled back.",
96
+ unknownAction: "Inspect every edited row before retrying.",
97
+ async execute(adapter, operation) {
98
+ const results = mongoCommands
99
+ ? await adapterOfKind(adapter, "mongodb").writeBatch(mongoCommands, "snapshot", true)
100
+ : await adapterOfKind(adapter, "sql").writeBatch(compiled.map((item, index) => ({
101
+ ...operation,
102
+ id: `${operation.id}:${index}`,
103
+ sql: item.sql,
104
+ parameters: JSON.stringify(item.params),
105
+ statement_type: "update",
106
+ expectedRows: 1,
107
+ })), "serializable");
108
+ return { affectedRows: results.reduce((sum, item) => sum + item.affectedRows, 0) };
109
+ },
110
+ };
111
+ }
112
+ /** Reserves the write, stages it or runs it once, and records a definite or unknown outcome. */
113
+ export async function runWrite(core, session, connection, statement, options, context, claim) {
114
+ if (options.idempotencyKey !== undefined && !options.idempotencyKey.trim()) {
115
+ throw new StateQLError("INVALID_COMMAND", "Idempotency key cannot be empty.");
116
+ }
117
+ const transactionId = session.active_transaction_id ?? undefined;
118
+ if (transactionId)
119
+ requireStagingTransaction(core, session, connection, statement, transactionId);
120
+ const reservation = core.store.reserveOperation({
121
+ sessionId: session.id,
122
+ actorId: core.actorId,
123
+ connectionId: connection.id,
124
+ fingerprint: statement.fingerprint,
125
+ sql: statement.descriptor,
126
+ parameters: statement.parameters,
127
+ statementType: statement.statementType,
128
+ status: transactionId ? "pending" : "executing",
129
+ transactionId,
130
+ replay: options.replay ?? false,
131
+ idempotencyKey: options.idempotencyKey,
132
+ stateVersionBefore: version(connection),
133
+ });
134
+ if (reservation.denied)
135
+ throw reservationDenied(core, session, reservation.denied);
136
+ const previous = reservation.previous;
137
+ const keyReused = previous !== undefined &&
138
+ options.idempotencyKey !== undefined &&
139
+ !options.replay &&
140
+ previous.fingerprint !== statement.fingerprint;
141
+ if (keyReused) {
142
+ throw new StateQLError("IDEMPOTENCY_CONFLICT", "Idempotency key was already used for a different write.", { extra: { previous_operation_id: previous.id } });
143
+ }
144
+ if (!reservation.operation)
145
+ return duplicateWrite(previous, options.idempotencyKey);
146
+ const operation = reservation.operation;
147
+ if (transactionId) {
148
+ return {
149
+ data: operationData(operation),
150
+ handle: operation.id,
151
+ executed: false,
152
+ stateVersion: version(connection),
153
+ };
154
+ }
155
+ let adapter;
156
+ let source;
157
+ try {
158
+ source = claim?.source ??
159
+ await core.resolveConnectionSource(connection, session, "exec", "write", context);
160
+ adapter = await core.openAdapter(connection, context, source);
161
+ }
162
+ catch (error) {
163
+ core.store.failOperation(operation.id);
164
+ if (error instanceof StateQLError)
165
+ throw error;
166
+ throw new StateQLError("CONNECTION_FAILED", "Database connection failed.", { retryable: true });
167
+ }
168
+ try {
169
+ const write = await statement.execute(adapter, operation);
170
+ const finalized = finishWrite(core, connection, operation, write, claim);
171
+ return {
172
+ data: {
173
+ ...operationData(finalized.operation),
174
+ duplicate: Boolean(previous),
175
+ duplicate_override: Boolean(previous),
176
+ },
177
+ handle: finalized.operation.id,
178
+ executed: true,
179
+ stateVersion: finalized.stateVersion,
180
+ confidence: adapter.confidence,
181
+ };
182
+ }
183
+ catch (error) {
184
+ throw writeFailure(core, operation, statement, error, source);
185
+ }
186
+ finally {
187
+ await closeAdapterQuietly(adapter);
188
+ }
189
+ }
190
+ function rejectUnsafeWrite(unbounded, destructive, safety, unboundedMessage, destructiveMessage) {
191
+ if (unbounded && !safety.allowUnbounded) {
192
+ throw new StateQLError("UNBOUNDED_MUTATION", unboundedMessage, {
193
+ extra: { override_flag: "--allow-unbounded" },
194
+ });
195
+ }
196
+ if (destructive && !safety.allowDestructive) {
197
+ throw new StateQLError("DESTRUCTIVE_OPERATION_BLOCKED", destructiveMessage, {
198
+ extra: { override_flag: "--allow-destructive" },
199
+ });
200
+ }
201
+ }
202
+ function requireStagingTransaction(core, session, connection, statement, transactionId) {
203
+ if (statement.stagingError) {
204
+ throw new StateQLError("TRANSACTION_FAILED", statement.stagingError, {
205
+ suggestedAction: "Roll back or commit the staged transaction, then run this statement separately.",
206
+ });
207
+ }
208
+ const transaction = core.store.getTransaction(transactionId);
209
+ const matches = transaction !== undefined &&
210
+ transaction.session_id === session.id &&
211
+ transaction.state === "active" &&
212
+ transaction.connection_id === connection.id;
213
+ if (!matches) {
214
+ throw new StateQLError("TRANSACTION_FAILED", "Active transaction does not match the active connection.");
215
+ }
216
+ if (transaction.owner_actor_id !== core.actorId) {
217
+ throw new StateQLError("PERMISSION_DENIED", "Only the transaction owner may stage writes.");
218
+ }
219
+ }
220
+ function reservationDenied(core, session, denied) {
221
+ if (denied === "membership") {
222
+ return new StateQLError("PERMISSION_DENIED", "Actor membership changed before the write was reserved.");
223
+ }
224
+ const active = core.store.getSession(session.id)?.active_transaction_id;
225
+ const transaction = active ? core.store.getTransaction(active) : undefined;
226
+ if (transaction && transaction.owner_actor_id !== core.actorId) {
227
+ return new StateQLError("PERMISSION_DENIED", "Only the transaction owner may stage writes.");
228
+ }
229
+ return new StateQLError("TRANSACTION_FAILED", "The active transaction changed before the write was reserved.");
230
+ }
231
+ function duplicateWrite(previous, idempotencyKey) {
232
+ if (previous.status === "executing" || previous.status === "outcome_unknown") {
233
+ throw new StateQLError("OUTCOME_UNKNOWN", "A matching write has an unknown outcome.", {
234
+ executed: true,
235
+ suggestedAction: REPLAY_ACTION,
236
+ extra: { previous_operation_id: previous.id },
237
+ });
238
+ }
239
+ if (!idempotencyKey) {
240
+ throw new StateQLError("POTENTIAL_DUPLICATE_WRITE", "An equivalent operation was previously applied.", { extra: { previous_operation_id: previous.id, replay_required: true } });
241
+ }
242
+ return {
243
+ data: {
244
+ ...operationData(previous),
245
+ duplicate: true,
246
+ duplicate_of: previous.id,
247
+ idempotency_key: idempotencyKey,
248
+ },
249
+ handle: previous.id,
250
+ cached: true,
251
+ stateVersion: previous.state_version_after ?? previous.state_version_before,
252
+ };
253
+ }
254
+ function finishWrite(core, connection, operation, write, claim) {
255
+ try {
256
+ if (claim) {
257
+ return core.store.finishPlannedOperation({
258
+ planId: claim.planId,
259
+ claimToken: claim.claimToken,
260
+ operationId: operation.id,
261
+ connectionId: connection.id,
262
+ affectedRows: write.affectedRows,
263
+ outcome: write.outcome,
264
+ });
265
+ }
266
+ const stateVersion = core.store.bumpVersion(connection.id);
267
+ return {
268
+ operation: core.store.finishOperation(operation.id, write.affectedRows, stateVersion, write.outcome),
269
+ stateVersion,
270
+ };
271
+ }
272
+ catch (error) {
273
+ core.store.markOperationOutcomeUnknown(operation.id);
274
+ throw new StateQLError("OUTCOME_UNKNOWN", errorMessage(error), {
275
+ executed: true,
276
+ suggestedAction: FINALIZE_ACTION,
277
+ });
278
+ }
279
+ }
280
+ function writeFailure(core, operation, statement, error, source) {
281
+ if (error instanceof StateQLError)
282
+ return error;
283
+ const definite = (error instanceof AdapterExecutionError ||
284
+ error instanceof AdapterWriteError ||
285
+ error instanceof BatchWriteError) &&
286
+ !error.outcomeUnknown;
287
+ if (!definite) {
288
+ core.store.markOperationOutcomeUnknown(operation.id);
289
+ return new StateQLError("OUTCOME_UNKNOWN", safeCredentialErrorMessage(error, source), { executed: true, suggestedAction: statement.unknownAction });
290
+ }
291
+ core.store.failOperation(operation.id);
292
+ if (error.message.startsWith("ROW_CONFLICT:")) {
293
+ return new StateQLError("ROW_CONFLICT", statement.conflictMessage);
294
+ }
295
+ if (error instanceof AdapterExecutionError)
296
+ return stoppedStateQLError(error, false);
297
+ return new StateQLError("QUERY_FAILED", safeCredentialErrorMessage(error, source), { executed: true });
298
+ }
299
+ export function storedMongoOperation(operation) {
300
+ if (!operation.statement_type.startsWith("mongo.")) {
301
+ throw new StateQLError("TRANSACTION_FAILED", "MongoDB transaction contains a mixed or corrupt native payload.");
302
+ }
303
+ return storedMongoWrite(operation.parameters, operation.statement_type, `operation "${operation.id}"`, "TRANSACTION_FAILED");
304
+ }
305
+ export function storedMongoWrite(parameters, statementType, label, errorCode) {
306
+ try {
307
+ const payload = JSON.parse(parameters);
308
+ if (!Array.isArray(payload) || payload.length !== 1 || typeof payload[0] !== "string") {
309
+ throw new Error("payload must contain one EJSON command string");
310
+ }
311
+ const command = deserializeMongoWriteCommand(payload[0]);
312
+ if (statementType !== `mongo.${command.operation}`) {
313
+ throw new Error("operation does not match its statement type");
314
+ }
315
+ return command;
316
+ }
317
+ catch {
318
+ throw new StateQLError(errorCode, `Stored MongoDB ${label} payload is invalid.`);
319
+ }
320
+ }
package/docs/databases.md CHANGED
@@ -17,7 +17,8 @@ covered under [write safety](writes.md).
17
17
  ## Driver notes
18
18
 
19
19
  - **SQLite:** use a filesystem path for direct connections or `sqlite:` for an
20
- environment-backed path.
20
+ environment-backed path. Reads run with `PRAGMA query_only`, also on
21
+ read-write connections, so a read cannot change the database.
21
22
  - **PostgreSQL:** StateQL preserves strict TLS verification by normalizing
22
23
  `sslmode=prefer`, `require`, and `verify-ca` to `verify-full` before opening
23
24
  the adapter. Use `sslmode=verify-full` explicitly for clarity. Setting
package/docs/results.md CHANGED
@@ -73,6 +73,11 @@ database, and SQLite sidecar files.
73
73
  return only those columns, in that order. Unknown column names fail with
74
74
  `INVALID_COMMAND` and a list of the available columns.
75
75
 
76
+ CSV exports put a `'` before text cells that start with `=`, `+`, `-`, or `@`
77
+ (after optional spaces or control characters), or with a tab or line break.
78
+ Spreadsheets then show these cells as text and do not run them as formulas.
79
+ Number values are not changed.
80
+
76
81
  `summarize` returns, for each column of a stored result, the null count, the
77
82
  distinct count, and the min and max. Min and max are computed only when all
78
83
  non-null values are numbers or all are strings. Numeric strings, such as
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fadhilp/stateql",
3
- "version": "0.17.0",
3
+ "version": "0.19.0",
4
4
  "description": "Stateful, agent-oriented database CLI for safe result reuse",
5
5
  "repository": {
6
6
  "type": "git",
@@ -26,8 +26,9 @@
26
26
  "LICENSE"
27
27
  ],
28
28
  "scripts": {
29
- "build": "tsc -p tsconfig.json",
30
- "test": "npm run build && node --test dist/test/cli.test.js dist/test/credential.test.js dist/test/import.test.js dist/test/mongodb.test.js dist/test/mysql.test.js dist/test/postgres.test.js dist/test/query.test.js dist/test/redis.test.js dist/test/sqlite.test.js dist/test/store.test.js dist/test/terminal.test.js dist/test/transaction.test.js dist/test/write.test.js dist/test/panel.test.js",
29
+ "build": "node -e \"require('node:fs').rmSync('dist', { recursive: true, force: true })\" && tsc -p tsconfig.json",
30
+ "test": "npm run build && node --test \"dist/test/*.test.js\"",
31
+ "lint": "biome lint",
31
32
  "release": "npm version",
32
33
  "version": "npm install",
33
34
  "prepack": "npm test"
@@ -56,6 +57,7 @@
56
57
  "pg": "^8.16.3"
57
58
  },
58
59
  "devDependencies": {
60
+ "@biomejs/biome": "2.5.15",
59
61
  "@types/node": "^24.0.0",
60
62
  "@types/pg": "^8.15.5",
61
63
  "node-pty": "^1.1.0",