@fadhilp/stateql 0.16.0 → 0.18.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.
- package/dist/src/adapters.d.ts +17 -25
- package/dist/src/adapters.js +15 -95
- package/dist/src/agent-response.js +6 -1
- package/dist/src/catalog.d.ts +6 -0
- package/dist/src/catalog.js +52 -0
- package/dist/src/cli.js +76 -25
- package/dist/src/connect.d.ts +16 -0
- package/dist/src/connect.js +205 -0
- package/dist/src/core.d.ts +78 -0
- package/dist/src/core.js +477 -0
- package/dist/src/execution.d.ts +27 -0
- package/dist/src/execution.js +87 -0
- package/dist/src/filter.js +3 -1
- package/dist/src/index.d.ts +1 -1
- package/dist/src/migrations.d.ts +1 -1
- package/dist/src/mongodb.d.ts +4 -2
- package/dist/src/mongodb.js +5 -56
- package/dist/src/panel.d.ts +64 -0
- package/dist/src/panel.js +316 -0
- package/dist/src/plans.d.ts +31 -0
- package/dist/src/plans.js +275 -0
- package/dist/src/reads.d.ts +35 -0
- package/dist/src/reads.js +184 -0
- package/dist/src/redis.d.ts +4 -2
- package/dist/src/redis.js +7 -33
- package/dist/src/response-data.d.ts +1 -0
- package/dist/src/response-data.js +13 -10
- package/dist/src/results.d.ts +10 -0
- package/dist/src/results.js +153 -0
- package/dist/src/sql.d.ts +7 -1
- package/dist/src/sql.js +88 -8
- package/dist/src/sqlite-process.js +16 -9
- package/dist/src/stateql.d.ts +9 -59
- package/dist/src/stateql.js +170 -2597
- package/dist/src/table-editor.js +2 -2
- package/dist/src/transactions.d.ts +8 -0
- package/dist/src/transactions.js +186 -0
- package/dist/src/types.d.ts +20 -18
- package/dist/src/util.d.ts +1 -0
- package/dist/src/util.js +1 -1
- package/dist/src/writes.d.ts +48 -0
- package/dist/src/writes.js +320 -0
- package/docs/batch.md +2 -1
- package/docs/cli.md +15 -9
- package/docs/databases.md +4 -3
- package/docs/library.md +3 -1
- package/docs/results.md +17 -0
- package/docs/writes.md +6 -0
- package/package.json +5 -3
- package/skills/stateql/SKILL.md +14 -6
- package/skills/stateql/reference/writes.md +4 -1
package/dist/src/adapters.d.ts
CHANGED
|
@@ -1,5 +1,9 @@
|
|
|
1
|
+
import { type AdapterContext } from "./execution.js";
|
|
2
|
+
import { MongoAdapter } from "./mongodb.js";
|
|
3
|
+
import { RedisAdapter } from "./redis.js";
|
|
1
4
|
import type { CatalogObject, DescribeObjectData, ListObjectsData, ListObjectsFilter, Column, Row, SqlParameters, StateConfidence } from "./types.js";
|
|
2
5
|
import type { ConnectionRecord, OperationRecord } from "./store.js";
|
|
6
|
+
export { AdapterExecutionError, AdapterWriteError, BatchWriteError, createAdapterContext, type AdapterContext, } from "./execution.js";
|
|
3
7
|
export interface ReadResult {
|
|
4
8
|
rows: Row[];
|
|
5
9
|
columns: Column[];
|
|
@@ -10,40 +14,28 @@ export interface WriteResult {
|
|
|
10
14
|
export type BatchWriteOperation = OperationRecord & {
|
|
11
15
|
expectedRows?: 1;
|
|
12
16
|
};
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
timeoutMs?: number;
|
|
16
|
-
signal?: AbortSignal;
|
|
17
|
-
}
|
|
18
|
-
export declare class AdapterExecutionError extends Error {
|
|
19
|
-
readonly reason: "timeout" | "aborted";
|
|
20
|
-
readonly outcomeUnknown: boolean;
|
|
21
|
-
constructor(message: string, reason: "timeout" | "aborted", outcomeUnknown: boolean);
|
|
22
|
-
}
|
|
23
|
-
export declare class BatchWriteError extends Error {
|
|
24
|
-
readonly outcomeUnknown: boolean;
|
|
25
|
-
constructor(message: string, outcomeUnknown: boolean);
|
|
26
|
-
}
|
|
27
|
-
export declare class AdapterWriteError extends Error {
|
|
28
|
-
readonly outcomeUnknown: boolean;
|
|
29
|
-
constructor(message: string, outcomeUnknown: boolean);
|
|
30
|
-
}
|
|
31
|
-
export interface Adapter {
|
|
17
|
+
/** What every database adapter offers, whatever its command language. */
|
|
18
|
+
export interface BaseAdapter {
|
|
32
19
|
readonly confidence: StateConfidence;
|
|
33
20
|
ping(): Promise<void>;
|
|
21
|
+
signature(): Promise<string>;
|
|
22
|
+
listObjects(filter: ListObjectsFilter): Promise<ListObjectsData>;
|
|
23
|
+
describeObject(object: CatalogObject): Promise<DescribeObjectData>;
|
|
24
|
+
close(): Promise<void>;
|
|
25
|
+
}
|
|
26
|
+
export interface SqlAdapter extends BaseAdapter {
|
|
27
|
+
readonly kind: "sql";
|
|
34
28
|
read(sql: string, params: SqlParameters): Promise<ReadResult>;
|
|
35
29
|
readAutocommit?(sql: string, params: SqlParameters): Promise<ReadResult>;
|
|
36
30
|
write(sql: string, params: SqlParameters, expectedRows?: 1): Promise<WriteResult>;
|
|
37
31
|
writeAutocommit?(sql: string, params: SqlParameters): Promise<WriteResult>;
|
|
38
32
|
writeBatch(operations: BatchWriteOperation[], isolation: string): Promise<WriteResult[]>;
|
|
39
|
-
signature(): Promise<string>;
|
|
40
33
|
inspect(kind: string, table?: string): Promise<unknown>;
|
|
41
|
-
listObjects(filter: ListObjectsFilter): Promise<ListObjectsData>;
|
|
42
|
-
describeObject(object: CatalogObject): Promise<DescribeObjectData>;
|
|
43
|
-
close(): Promise<void>;
|
|
44
34
|
}
|
|
45
|
-
export
|
|
35
|
+
export type DatabaseAdapter = SqlAdapter | MongoAdapter | RedisAdapter;
|
|
36
|
+
/** Opens the adapter for any supported driver; this is the only place that maps drivers to adapters. */
|
|
37
|
+
export declare function openAdapter(connection: ConnectionRecord, context: AdapterContext, source: string): Promise<DatabaseAdapter>;
|
|
46
38
|
export declare function createAdapter(connection: ConnectionRecord, context: AdapterContext, input: {
|
|
47
39
|
source: string;
|
|
48
|
-
}): Promise<
|
|
40
|
+
}): Promise<SqlAdapter>;
|
|
49
41
|
export declare function normalizePostgresConnectionString(source: string): string;
|
package/dist/src/adapters.js
CHANGED
|
@@ -1,44 +1,23 @@
|
|
|
1
1
|
import { fork } from "node:child_process";
|
|
2
2
|
import { createRequire } from "node:module";
|
|
3
3
|
import { StateQLError } from "./errors.js";
|
|
4
|
+
import { AdapterExecutionError, AdapterWriteError, BatchWriteError, remainingMilliseconds, stoppedError, throwIfStopped, withContext, } from "./execution.js";
|
|
5
|
+
import { MongoAdapter } from "./mongodb.js";
|
|
6
|
+
import { RedisAdapter } from "./redis.js";
|
|
4
7
|
import { isSqlParameters, parseJson, toJsonSafe } from "./util.js";
|
|
8
|
+
export { AdapterExecutionError, AdapterWriteError, BatchWriteError, createAdapterContext, } from "./execution.js";
|
|
5
9
|
const require = createRequire(import.meta.url);
|
|
6
10
|
let mysqlModule;
|
|
7
11
|
let postgresModule;
|
|
8
12
|
const mysql = () => (mysqlModule ??= require("mysql2"));
|
|
9
13
|
const postgres = () => (postgresModule ??= require("pg"));
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
this.name = "AdapterExecutionError";
|
|
18
|
-
}
|
|
19
|
-
}
|
|
20
|
-
export class BatchWriteError extends Error {
|
|
21
|
-
outcomeUnknown;
|
|
22
|
-
constructor(message, outcomeUnknown) {
|
|
23
|
-
super(message);
|
|
24
|
-
this.outcomeUnknown = outcomeUnknown;
|
|
25
|
-
this.name = "BatchWriteError";
|
|
26
|
-
}
|
|
27
|
-
}
|
|
28
|
-
export class AdapterWriteError extends Error {
|
|
29
|
-
outcomeUnknown;
|
|
30
|
-
constructor(message, outcomeUnknown) {
|
|
31
|
-
super(message);
|
|
32
|
-
this.outcomeUnknown = outcomeUnknown;
|
|
33
|
-
this.name = "AdapterWriteError";
|
|
34
|
-
}
|
|
35
|
-
}
|
|
36
|
-
export function createAdapterContext(timeoutMs, signal) {
|
|
37
|
-
return {
|
|
38
|
-
deadline: Date.now() + timeoutMs,
|
|
39
|
-
timeoutMs,
|
|
40
|
-
...(signal ? { signal } : {}),
|
|
41
|
-
};
|
|
14
|
+
/** Opens the adapter for any supported driver; this is the only place that maps drivers to adapters. */
|
|
15
|
+
export async function openAdapter(connection, context, source) {
|
|
16
|
+
if (connection.driver === "mongodb")
|
|
17
|
+
return new MongoAdapter(connection, context, { source });
|
|
18
|
+
if (connection.driver === "redis")
|
|
19
|
+
return new RedisAdapter(source, Boolean(connection.read_only), context);
|
|
20
|
+
return createAdapter(connection, context, { source });
|
|
42
21
|
}
|
|
43
22
|
export async function createAdapter(connection, context, input) {
|
|
44
23
|
const { source } = input;
|
|
@@ -60,6 +39,7 @@ class SQLiteAdapter {
|
|
|
60
39
|
source;
|
|
61
40
|
readOnly;
|
|
62
41
|
context;
|
|
42
|
+
kind = "sql";
|
|
63
43
|
confidence = "database_reported";
|
|
64
44
|
child;
|
|
65
45
|
pending = new Map();
|
|
@@ -239,6 +219,7 @@ const POSTGRES_AUTOCOMMIT_STATEMENTS = new Set([
|
|
|
239
219
|
class PostgresAdapter {
|
|
240
220
|
readOnly;
|
|
241
221
|
context;
|
|
222
|
+
kind = "sql";
|
|
242
223
|
confidence = "ttl_based";
|
|
243
224
|
client;
|
|
244
225
|
pgTypes;
|
|
@@ -249,7 +230,7 @@ class PostgresAdapter {
|
|
|
249
230
|
this.context = context;
|
|
250
231
|
const { Client, types } = postgres();
|
|
251
232
|
this.pgTypes = types;
|
|
252
|
-
const timeout =
|
|
233
|
+
const timeout = remainingMilliseconds(context);
|
|
253
234
|
this.client = new Client({
|
|
254
235
|
connectionString: normalizePostgresConnectionString(source),
|
|
255
236
|
connectionTimeoutMillis: timeout,
|
|
@@ -574,6 +555,7 @@ class MySqlAdapter {
|
|
|
574
555
|
source;
|
|
575
556
|
readOnly;
|
|
576
557
|
context;
|
|
558
|
+
kind = "sql";
|
|
577
559
|
confidence = "ttl_based";
|
|
578
560
|
rawClient;
|
|
579
561
|
client;
|
|
@@ -1052,68 +1034,6 @@ function postgresCatalogFilter(filter) {
|
|
|
1052
1034
|
}
|
|
1053
1035
|
return { where: predicates.length ? `WHERE ${predicates.join(" AND ")}` : "", params };
|
|
1054
1036
|
}
|
|
1055
|
-
function remainingMilliseconds(context) {
|
|
1056
|
-
return Math.max(1, Math.ceil(context.deadline - Date.now()));
|
|
1057
|
-
}
|
|
1058
|
-
function throwIfStopped(context, outcomeUnknown) {
|
|
1059
|
-
if (context.signal?.aborted || context.deadline <= Date.now()) {
|
|
1060
|
-
throw stoppedError(context, outcomeUnknown);
|
|
1061
|
-
}
|
|
1062
|
-
}
|
|
1063
|
-
function stoppedError(context, outcomeUnknown) {
|
|
1064
|
-
const aborted = context.signal?.aborted ?? false;
|
|
1065
|
-
return new AdapterExecutionError(aborted ? "Database operation cancelled." : "Database operation timed out.", aborted ? "aborted" : "timeout", outcomeUnknown);
|
|
1066
|
-
}
|
|
1067
|
-
function withContext(promise, context, onStop, outcomeUnknown) {
|
|
1068
|
-
try {
|
|
1069
|
-
throwIfStopped(context, outcomeUnknown);
|
|
1070
|
-
}
|
|
1071
|
-
catch (error) {
|
|
1072
|
-
try {
|
|
1073
|
-
onStop();
|
|
1074
|
-
}
|
|
1075
|
-
catch {
|
|
1076
|
-
// Preserve deadline/cancellation error.
|
|
1077
|
-
}
|
|
1078
|
-
return Promise.reject(error);
|
|
1079
|
-
}
|
|
1080
|
-
return new Promise((resolve, reject) => {
|
|
1081
|
-
let settled = false;
|
|
1082
|
-
const finish = (action) => {
|
|
1083
|
-
if (settled)
|
|
1084
|
-
return;
|
|
1085
|
-
settled = true;
|
|
1086
|
-
clearTimeout(timer);
|
|
1087
|
-
context.signal?.removeEventListener("abort", stop);
|
|
1088
|
-
action();
|
|
1089
|
-
};
|
|
1090
|
-
const stop = () => {
|
|
1091
|
-
finish(() => {
|
|
1092
|
-
try {
|
|
1093
|
-
onStop();
|
|
1094
|
-
}
|
|
1095
|
-
catch {
|
|
1096
|
-
// Preserve deadline/cancellation error.
|
|
1097
|
-
}
|
|
1098
|
-
reject(stoppedError(context, outcomeUnknown));
|
|
1099
|
-
});
|
|
1100
|
-
};
|
|
1101
|
-
const stopped = () => Boolean(context.signal?.aborted) || context.deadline <= Date.now();
|
|
1102
|
-
const timer = setTimeout(stop, remainingMilliseconds(context));
|
|
1103
|
-
context.signal?.addEventListener("abort", stop, { once: true });
|
|
1104
|
-
promise.then((value) => {
|
|
1105
|
-
if (stopped())
|
|
1106
|
-
stop();
|
|
1107
|
-
else
|
|
1108
|
-
finish(() => resolve(value));
|
|
1109
|
-
}, (error) => {
|
|
1110
|
-
if (stopped())
|
|
1111
|
-
stop();
|
|
1112
|
-
else
|
|
1113
|
-
finish(() => reject(error));
|
|
1114
|
-
});
|
|
1115
|
-
});
|
|
1116
|
-
}
|
|
1117
1037
|
function postgresErrorCode(error) {
|
|
1118
1038
|
if (!error || typeof error !== "object")
|
|
1119
1039
|
return undefined;
|
|
@@ -3,7 +3,7 @@ const RESULT_COMMANDS = new Set(["query", "mongo.query", "redis.query", "filter"
|
|
|
3
3
|
const FALSE_DEFAULT_KEYS = ["cached", "duplicate", "duplicate_override"];
|
|
4
4
|
const SHARED_HISTORY_KEYS = ["session_id", "actor_id", "actor_name", "origin"];
|
|
5
5
|
// The caller already holds the handle it passed to these commands.
|
|
6
|
-
const HANDLE_ECHO_COMMANDS = new Set(["rows", "count", "columns"]);
|
|
6
|
+
const HANDLE_ECHO_COMMANDS = new Set(["rows", "count", "columns", "summarize"]);
|
|
7
7
|
const WRITE_COMMANDS = new Set(["exec", "mongo.exec", "redis.exec", "apply"]);
|
|
8
8
|
const COMMAND_ALIASES = {
|
|
9
9
|
"objects.list": "objects",
|
|
@@ -55,6 +55,10 @@ export function agentResponse(result, commandName) {
|
|
|
55
55
|
data.total = data.rows;
|
|
56
56
|
delete data.rows;
|
|
57
57
|
}
|
|
58
|
+
else if (currentCommand === "summarize" && Array.isArray(data.columns)) {
|
|
59
|
+
const table = columnarRows(data.columns, undefined);
|
|
60
|
+
Object.assign(data, { columns: table.columns, rows: table.rows });
|
|
61
|
+
}
|
|
58
62
|
else if (WRITE_COMMANDS.has(currentCommand)) {
|
|
59
63
|
delete data.actor_id;
|
|
60
64
|
delete data.plan_id;
|
|
@@ -187,6 +191,7 @@ function primaryHandleKey(currentCommand) {
|
|
|
187
191
|
rows: "result_id",
|
|
188
192
|
count: "result_id",
|
|
189
193
|
columns: "result_id",
|
|
194
|
+
summarize: "result_id",
|
|
190
195
|
export: "result_id",
|
|
191
196
|
alias: "result_id",
|
|
192
197
|
"alias.set": "result_id",
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { type ActionResult, type Core } from "./core.js";
|
|
2
|
+
import type { SessionRecord } from "./store.js";
|
|
3
|
+
import type { CatalogObject, DescribeObjectData, ExecutionOptions, ListObjectsData, ListObjectsFilter } from "./types.js";
|
|
4
|
+
export declare function inspectSchema(core: Core, session: SessionRecord, kind: string, table: string | undefined, options: ExecutionOptions): Promise<ActionResult<unknown>>;
|
|
5
|
+
export declare function listObjects(core: Core, session: SessionRecord, filter: ListObjectsFilter, options: ExecutionOptions): Promise<ActionResult<ListObjectsData>>;
|
|
6
|
+
export declare function describeObject(core: Core, session: SessionRecord, object: CatalogObject, options: ExecutionOptions): Promise<ActionResult<DescribeObjectData>>;
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { version } from "./connection.js";
|
|
2
|
+
import { adapterOfKind } from "./core.js";
|
|
3
|
+
import { StateQLError } from "./errors.js";
|
|
4
|
+
const OBJECT_KINDS = ["table", "view", "collection", "function", "trigger", "enum", "key"];
|
|
5
|
+
export async function inspectSchema(core, session, kind, table, options) {
|
|
6
|
+
const connection = core.requireConnection(session);
|
|
7
|
+
core.rejectDuringStagedTransaction(session, "Schema inspection");
|
|
8
|
+
if (connection.driver === "redis") {
|
|
9
|
+
throw new StateQLError("INVALID_COMMAND", "Legacy inspect is not supported for Redis; use listObjects or describeObject.");
|
|
10
|
+
}
|
|
11
|
+
return catalogRead(core, session, connection, options, (adapter) => adapter.kind === "mongodb"
|
|
12
|
+
? adapter.inspect(kind, table)
|
|
13
|
+
: adapterOfKind(adapter, "sql").inspect(kind, table));
|
|
14
|
+
}
|
|
15
|
+
export async function listObjects(core, session, filter, options) {
|
|
16
|
+
validateCatalogFilter(filter);
|
|
17
|
+
const connection = core.requireConnection(session);
|
|
18
|
+
core.rejectDuringStagedTransaction(session, "Catalog discovery");
|
|
19
|
+
return catalogRead(core, session, connection, options, (adapter) => adapter.listObjects(filter));
|
|
20
|
+
}
|
|
21
|
+
export async function describeObject(core, session, object, options) {
|
|
22
|
+
validateCatalogObject(object);
|
|
23
|
+
const connection = core.requireConnection(session);
|
|
24
|
+
core.rejectDuringStagedTransaction(session, "Catalog description");
|
|
25
|
+
return catalogRead(core, session, connection, options, (adapter) => adapter.describeObject(object));
|
|
26
|
+
}
|
|
27
|
+
async function catalogRead(core, session, connection, options, read) {
|
|
28
|
+
const context = core.executionContext(options);
|
|
29
|
+
return core.withAdapter(session, connection, "inspect", context, async (adapter) => ({
|
|
30
|
+
data: await read(adapter),
|
|
31
|
+
executed: true,
|
|
32
|
+
stateVersion: version(connection),
|
|
33
|
+
confidence: adapter.confidence,
|
|
34
|
+
}));
|
|
35
|
+
}
|
|
36
|
+
function validateCatalogFilter(filter) {
|
|
37
|
+
if (!filter || typeof filter !== "object" || Array.isArray(filter) || Object.keys(filter).some((key) => !["kind", "schema", "search", "offset", "limit"].includes(key)))
|
|
38
|
+
throw new StateQLError("INVALID_COMMAND", "Catalog filter contains unknown fields.");
|
|
39
|
+
if (filter.kind !== undefined && !OBJECT_KINDS.includes(filter.kind))
|
|
40
|
+
throw new StateQLError("INVALID_COMMAND", "Unknown catalog object kind.");
|
|
41
|
+
for (const [name, value] of [["schema", filter.schema], ["search", filter.search]])
|
|
42
|
+
if (value !== undefined && (typeof value !== "string" || !value || value.length > 200 || value.includes("\0")))
|
|
43
|
+
throw new StateQLError("INVALID_COMMAND", `Catalog ${name} is invalid.`);
|
|
44
|
+
if (filter.offset !== undefined && !((typeof filter.offset === "number" && Number.isSafeInteger(filter.offset) && filter.offset >= 0) || (typeof filter.offset === "string" && /^\d+$/.test(filter.offset))))
|
|
45
|
+
throw new StateQLError("INVALID_COMMAND", "Catalog offset is invalid.");
|
|
46
|
+
if (filter.limit !== undefined && (!Number.isSafeInteger(filter.limit) || filter.limit < 1 || filter.limit > 200))
|
|
47
|
+
throw new StateQLError("INVALID_COMMAND", "Catalog limit must be 1-200.");
|
|
48
|
+
}
|
|
49
|
+
function validateCatalogObject(object) {
|
|
50
|
+
if (!object || typeof object !== "object" || Array.isArray(object) || !OBJECT_KINDS.includes(object.kind) || typeof object.name !== "string" || !object.name || object.name.length > 500 || object.name.includes("\0") || (object.schema !== undefined && (typeof object.schema !== "string" || !object.schema || object.schema.length > 500 || object.schema.includes("\0"))) || (object.identity !== undefined && (typeof object.identity !== "string" || !object.identity || object.identity.length > 1000 || object.identity.includes("\0"))))
|
|
51
|
+
throw new StateQLError("INVALID_COMMAND", "Catalog object identity is invalid.");
|
|
52
|
+
}
|
package/dist/src/cli.js
CHANGED
|
@@ -8,6 +8,41 @@ import { exitCodeFor } from "./errors.js";
|
|
|
8
8
|
import { StateQL } from "./stateql.js";
|
|
9
9
|
import { agentResponse } from "./agent-response.js";
|
|
10
10
|
import { askPassword, cliCredentialResolver, deleteOsPassword, saveOsPassword } from "./os-credentials.js";
|
|
11
|
+
const USAGE = `stql connect <target> [--name NAME] [--read-only|--read-write]
|
|
12
|
+
stql connect --env ENV | --credential-ref REF | --profile NAME [--name NAME] [--read-only|--read-write]
|
|
13
|
+
stql disconnect|status
|
|
14
|
+
stql actor show | set-name <display-name>
|
|
15
|
+
stql profile add|update NAME [TARGET [--ask-password] | --env ENV | --credential-ref REF]
|
|
16
|
+
[--read-only|--read-write]
|
|
17
|
+
stql profile list|show|remove NAME
|
|
18
|
+
stql session start|list|show|summary|close
|
|
19
|
+
stql query <sql> | --file FILE [--params JSON | --param VALUE... | --params-file FILE]
|
|
20
|
+
[--cache auto|bypass|require] [--preview-rows 0..200]
|
|
21
|
+
stql filter <result-handle> <predicate> [--params JSON | --param VALUE...]
|
|
22
|
+
stql exec <sql> | --file FILE [--params JSON | --param VALUE...] [--idempotency-key KEY]
|
|
23
|
+
[--replay] [--allow-unbounded] [--allow-destructive]
|
|
24
|
+
stql plan <sql> | --file FILE [--params JSON | --param VALUE...] [--allow-unbounded]
|
|
25
|
+
[--allow-destructive]
|
|
26
|
+
stql apply <plan-handle>
|
|
27
|
+
stql mongo query|exec|plan '<EJSON command>' | --file FILE [--cache MODE] [--idempotency-key KEY]
|
|
28
|
+
[--replay] [--allow-unbounded] [--allow-destructive]
|
|
29
|
+
stql redis query|exec|plan '<JSON command>' | --file FILE [--cache MODE] [--idempotency-key KEY]
|
|
30
|
+
[--replay]
|
|
31
|
+
stql show|count|columns|summarize <result-handle>
|
|
32
|
+
stql rows <result-handle> [--offset N] [--limit N] [--columns a,b]
|
|
33
|
+
stql alias set <name> <result-handle>
|
|
34
|
+
stql export <result-handle> --output FILE [--format json|jsonl|csv] [--columns a,b]
|
|
35
|
+
stql inspect schema|table|collection|collections|columns|indexes|constraints [name]
|
|
36
|
+
stql objects [KIND] [--schema NAME] [--search TEXT] [--offset N|--cursor CURSOR] [--limit N]
|
|
37
|
+
stql object KIND NAME [IDENTITY] [--schema NAME]
|
|
38
|
+
stql transaction begin|status|commit|rollback [--isolation LEVEL]
|
|
39
|
+
stql history [--limit N] [--offset N] [--category statement|introspection|management]
|
|
40
|
+
[--internal|--external]
|
|
41
|
+
stql receipt <operation-handle>
|
|
42
|
+
stql doctor|capabilities
|
|
43
|
+
stql purge [expired|results|history|all]
|
|
44
|
+
stql batch [commands.json|commands.jsonl|-] [--continue-on-error]
|
|
45
|
+
stql pipe [--continue-on-error]`;
|
|
11
46
|
const parsed = parseArgs({
|
|
12
47
|
allowPositionals: true,
|
|
13
48
|
strict: true,
|
|
@@ -22,6 +57,8 @@ const parsed = parseArgs({
|
|
|
22
57
|
params: { type: "string" },
|
|
23
58
|
param: { type: "string", multiple: true },
|
|
24
59
|
"params-file": { type: "string" },
|
|
60
|
+
file: { type: "string" },
|
|
61
|
+
columns: { type: "string" },
|
|
25
62
|
cache: { type: "string" },
|
|
26
63
|
"preview-rows": { type: "string" },
|
|
27
64
|
"max-cell-characters": { type: "string" },
|
|
@@ -56,7 +93,13 @@ if (values.version) {
|
|
|
56
93
|
process.exit(0);
|
|
57
94
|
}
|
|
58
95
|
if (values.help || !command || command === "help") {
|
|
59
|
-
|
|
96
|
+
const topic = command === "help" ? subcommand : command;
|
|
97
|
+
const usage = topic ? commandUsage(topic) : helpText();
|
|
98
|
+
if (usage === undefined) {
|
|
99
|
+
console.error(`Unknown command "${topic}". Run "stql help" to list commands.`);
|
|
100
|
+
process.exit(exitCodeFor("INVALID_COMMAND"));
|
|
101
|
+
}
|
|
102
|
+
console.log(usage);
|
|
60
103
|
process.exit(0);
|
|
61
104
|
}
|
|
62
105
|
const abortController = new AbortController();
|
|
@@ -147,7 +190,7 @@ async function runBatch() {
|
|
|
147
190
|
}
|
|
148
191
|
async function dispatch() {
|
|
149
192
|
const params = parseParameters(values.params, values.param, values["params-file"]);
|
|
150
|
-
const sql = [subcommand, ...rest]
|
|
193
|
+
const sql = () => statementText([subcommand, ...rest]);
|
|
151
194
|
switch (command) {
|
|
152
195
|
case "connect": {
|
|
153
196
|
if (values["read-only"] && values["read-write"]) {
|
|
@@ -183,7 +226,7 @@ async function dispatch() {
|
|
|
183
226
|
case "redis":
|
|
184
227
|
return dispatchRedis(subcommand, rest);
|
|
185
228
|
case "query":
|
|
186
|
-
return stateql.query(sql, {
|
|
229
|
+
return stateql.query(sql(), {
|
|
187
230
|
params,
|
|
188
231
|
cache: cacheMode(values.cache),
|
|
189
232
|
...(values["preview-rows"] === undefined
|
|
@@ -193,7 +236,7 @@ async function dispatch() {
|
|
|
193
236
|
case "filter":
|
|
194
237
|
return stateql.filter(requireValue(subcommand, "result handle"), requireValue(rest.join(" ").trim(), "filter predicate"), { params });
|
|
195
238
|
case "exec":
|
|
196
|
-
return stateql.exec(sql, {
|
|
239
|
+
return stateql.exec(sql(), {
|
|
197
240
|
params,
|
|
198
241
|
replay: values.replay ?? false,
|
|
199
242
|
...(values["idempotency-key"]
|
|
@@ -208,13 +251,16 @@ async function dispatch() {
|
|
|
208
251
|
return stateql.rows(requireValue(subcommand, "result handle"), {
|
|
209
252
|
offset: numberOption(values.offset, 0),
|
|
210
253
|
limit: numberOption(values.limit, 20),
|
|
254
|
+
...(values.columns === undefined ? {} : { columns: columnList(values.columns) }),
|
|
211
255
|
});
|
|
212
256
|
case "count":
|
|
213
257
|
return stateql.count(requireValue(subcommand, "result handle"));
|
|
214
258
|
case "columns":
|
|
215
259
|
return stateql.columns(requireValue(subcommand, "result handle"));
|
|
260
|
+
case "summarize":
|
|
261
|
+
return stateql.summarize(requireValue(subcommand, "result handle"));
|
|
216
262
|
case "export":
|
|
217
|
-
return stateql.exportResult(requireValue(subcommand, "result handle"), requireValue(values.output, "--output"), exportFormat(values.format));
|
|
263
|
+
return stateql.exportResult(requireValue(subcommand, "result handle"), requireValue(values.output, "--output"), exportFormat(values.format), values.columns === undefined ? undefined : columnList(values.columns));
|
|
218
264
|
case "alias":
|
|
219
265
|
if (subcommand !== "set")
|
|
220
266
|
throw new Error("Expected: alias set NAME RESULT");
|
|
@@ -241,7 +287,7 @@ async function dispatch() {
|
|
|
241
287
|
case "transaction":
|
|
242
288
|
return dispatchTransaction(subcommand, rest[0]);
|
|
243
289
|
case "plan":
|
|
244
|
-
return stateql.plan(sql, {
|
|
290
|
+
return stateql.plan(sql(), {
|
|
245
291
|
params,
|
|
246
292
|
allowUnbounded: values["allow-unbounded"] ?? false,
|
|
247
293
|
...(values["allow-destructive"]
|
|
@@ -271,7 +317,7 @@ async function dispatch() {
|
|
|
271
317
|
}
|
|
272
318
|
}
|
|
273
319
|
async function dispatchMongo(action, args) {
|
|
274
|
-
const payload = requireValue(args
|
|
320
|
+
const payload = requireValue(statementText(args), "MongoDB EJSON command");
|
|
275
321
|
switch (action) {
|
|
276
322
|
case "query":
|
|
277
323
|
return stateql.mongoQuery(parseMongoCommand(payload), {
|
|
@@ -298,7 +344,7 @@ async function dispatchMongo(action, args) {
|
|
|
298
344
|
}
|
|
299
345
|
}
|
|
300
346
|
async function dispatchRedis(action, args) {
|
|
301
|
-
const payload = parseRedisCommand(requireValue(args
|
|
347
|
+
const payload = parseRedisCommand(requireValue(statementText(args), "Redis JSON command"));
|
|
302
348
|
switch (action) {
|
|
303
349
|
case "query": return stateql.redisQuery(payload, { cache: cacheMode(values.cache) });
|
|
304
350
|
case "exec": return stateql.redisExec(payload, { replay: values.replay ?? false, ...(values["idempotency-key"] ? { idempotencyKey: values["idempotency-key"] } : {}) });
|
|
@@ -453,6 +499,21 @@ function parseParameters(value, values, file) {
|
|
|
453
499
|
}
|
|
454
500
|
return parsedValue;
|
|
455
501
|
}
|
|
502
|
+
function statementText(args) {
|
|
503
|
+
const inline = args.filter(Boolean).join(" ").trim();
|
|
504
|
+
const file = values.file;
|
|
505
|
+
if (file === undefined)
|
|
506
|
+
return inline;
|
|
507
|
+
if (inline)
|
|
508
|
+
throw new Error("Use either inline text or --file, not both.");
|
|
509
|
+
if (file === "-" && values["params-file"] === "-") {
|
|
510
|
+
throw new Error("--file and --params-file cannot both read standard input.");
|
|
511
|
+
}
|
|
512
|
+
return withoutBom(readFileSync(file === "-" ? 0 : resolve(file), "utf8")).trim();
|
|
513
|
+
}
|
|
514
|
+
function columnList(value) {
|
|
515
|
+
return value.split(",").map((name) => name.trim()).filter(Boolean);
|
|
516
|
+
}
|
|
456
517
|
function parseParameter(value) {
|
|
457
518
|
try {
|
|
458
519
|
return JSON.parse(value);
|
|
@@ -606,30 +667,20 @@ function extractHandle(data) {
|
|
|
606
667
|
}
|
|
607
668
|
return undefined;
|
|
608
669
|
}
|
|
670
|
+
function commandUsage(name) {
|
|
671
|
+
const entries = USAGE.split(/\n(?=stql )/).filter((entry) => entry.slice("stql ".length).split(" ")[0].split("|").includes(name));
|
|
672
|
+
return entries.length > 0 ? entries.join("\n") : undefined;
|
|
673
|
+
}
|
|
609
674
|
function helpText() {
|
|
610
675
|
return `StateQL ${packageVersion()}
|
|
611
676
|
|
|
612
677
|
Usage: stql <command> [arguments] [options]
|
|
613
678
|
|
|
614
|
-
Commands:
|
|
615
|
-
|
|
616
|
-
disconnect, status
|
|
617
|
-
actor show | set-name NAME
|
|
618
|
-
profile add|update NAME [TARGET [--ask-password] | --env ENV | --credential-ref REF]
|
|
619
|
-
profile list|show|remove
|
|
620
|
-
query, filter, exec, show, rows, count, columns, export
|
|
621
|
-
mongo query|exec|plan '<EJSON command>'
|
|
622
|
-
redis query|exec|plan '<JSON command>'
|
|
623
|
-
alias set
|
|
624
|
-
inspect schema|table|collection|collections|columns|indexes|constraints
|
|
625
|
-
objects [KIND] [--schema NAME] [--search TEXT] [--offset N|--cursor CURSOR]
|
|
626
|
-
object KIND NAME [IDENTITY] [--schema NAME]
|
|
627
|
-
transaction begin|status|commit|rollback
|
|
628
|
-
plan, apply, history [--category CATEGORY] [--internal|--external], receipt, doctor, purge, capabilities
|
|
629
|
-
batch [file.json|file.jsonl|-]
|
|
630
|
-
pipe
|
|
679
|
+
Commands (stql help COMMAND shows one):
|
|
680
|
+
${USAGE}
|
|
631
681
|
|
|
632
682
|
SQL parameters: --params JSON, repeated --param VALUE, or --params-file FILE.
|
|
683
|
+
Long SQL or native commands: --file FILE (- reads standard input) instead of inline text.
|
|
633
684
|
Query preview: --preview-rows N (default: 5, maximum: 200).
|
|
634
685
|
Long cells: --max-cell-characters N (default: 200); use export for full values.
|
|
635
686
|
Deadline: --timeout-ms N (default: 30000). Ctrl+C cancels database work.
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { type ActionResult, type Core } from "./core.js";
|
|
2
|
+
import type { SessionRecord } from "./store.js";
|
|
3
|
+
import type { ConnectionData, ConnectOptions } from "./types.js";
|
|
4
|
+
/** Resolves the target, pings the database, and stores the connection as active. */
|
|
5
|
+
export declare function connect(core: Core, session: SessionRecord, target: string | undefined, options: ConnectOptions): Promise<ActionResult<ConnectionData>>;
|
|
6
|
+
export declare function validatedProfileSource(input: {
|
|
7
|
+
target?: string;
|
|
8
|
+
secretEnv?: string;
|
|
9
|
+
credentialRef?: string;
|
|
10
|
+
passwordRef?: string;
|
|
11
|
+
}): {
|
|
12
|
+
target: string | null;
|
|
13
|
+
secretEnv: string | null;
|
|
14
|
+
credentialRef: string | null;
|
|
15
|
+
passwordRef: string | null;
|
|
16
|
+
};
|