@b2y/ai-service 0.0.0-stage → 1.0.1

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.
@@ -0,0 +1,483 @@
1
+ import { z } from "zod";
2
+ import { AiServiceError, ErrorCodes, summarizeZodError } from "../core/Errors.js";
3
+ import { SQL_AGGREGATE_FUNCTIONS, SQL_COLUMN_TYPES, SQL_DIALECTS, SQL_SAFE_FUNCTIONS, SQL_SAFE_WINDOW_FUNCTIONS } from "../constants/SqlConstants.js";
4
+ export { SQL_SAFE_FUNCTIONS, SQL_SAFE_WINDOW_FUNCTIONS } from "../constants/SqlConstants.js";
5
+
6
+ /**
7
+ * @typedef {Object} SqlColumnInfo
8
+ * @property {string} table
9
+ * @property {string} name
10
+ * @property {SqlColumnType} type
11
+ * @property {readonly string[] | null} allowedValues
12
+ */
13
+
14
+ /**
15
+ * A schema and policy checked against each other, frozen. Only defineSqlPolicy() creates one.
16
+ * @typedef {Object} SqlPolicy
17
+ * @property {SqlDialect} dialect
18
+ * @property {SqlSchema} schema
19
+ * @property {ReadonlyMap<string, ReadonlyMap<string, SqlColumnInfo>>} tables
20
+ * @property {ReadonlySet<string>} functions
21
+ * @property {ReadonlySet<string>} aggregates
22
+ * @property {ReadonlySet<string>} relationships - Unordered "a.x=b.y" keys for declared relationships.
23
+ * @property {"none" | "declared"} allowJoins
24
+ * @property {boolean} allowSubqueries
25
+ * @property {boolean} allowSetOperations
26
+ * @property {boolean} allowWindowFunctions
27
+ * @property {boolean} requireAggregation
28
+ * @property {number} maxRows
29
+ * @property {number} timeoutMs
30
+ * @property {number} maxSqlChars
31
+ * @property {number} maxSchemaChars
32
+ * @property {number} maxRepairAttempts
33
+ * @property {number} maxResultBytes
34
+ * @property {number} maxResultColumns
35
+ * @property {number} maxLiteralChars
36
+ * @property {number} maxOffset
37
+ * @property {number} maxAstNodes
38
+ * @property {number} maxAstDepth
39
+ */
40
+
41
+ /** Unquoted or quoted identifier as written in SQL (mixed case must be double-quoted in queries). */
42
+ const identifierSchema = z.string().regex(/^[A-Za-z_][A-Za-z0-9_]{0,62}$/, "must be a plain SQL identifier");
43
+ const columnPathSchema = z.string().regex(/^[A-Za-z_][A-Za-z0-9_]{0,62}\.[A-Za-z_][A-Za-z0-9_]{0,62}$/, "must be table.column");
44
+
45
+ export const sqlSchemaSchema = z.strictObject({
46
+ tables: z
47
+ .array(
48
+ z.strictObject({
49
+ name: identifierSchema,
50
+ description: z.string().min(1).max(500).optional(),
51
+ columns: z
52
+ .array(
53
+ z.strictObject({
54
+ name: identifierSchema,
55
+ type: z.enum(SQL_COLUMN_TYPES),
56
+ description: z.string().min(1).max(300).optional(),
57
+ /** Exact values a filter on this column may use. Supplied by the application, never sampled. */
58
+ allowedValues: z.array(z.string().min(1).max(100)).min(1).max(100).optional(),
59
+ role: z.enum(["dimension", "measure", "time", "identifier"]).optional(),
60
+ }),
61
+ )
62
+ .min(1)
63
+ .max(200),
64
+ }),
65
+ )
66
+ .min(1)
67
+ .max(50),
68
+ relationships: z
69
+ .array(z.strictObject({ from: columnPathSchema, to: columnPathSchema }))
70
+ .max(50)
71
+ .default([]),
72
+ });
73
+
74
+ export const sqlPolicySchema = z.strictObject({
75
+ allowedTables: z.array(identifierSchema).min(1).max(50),
76
+ /** Per table, the columns queries may reference anywhere (select, filter, group, order, join). */
77
+ allowedColumns: z.record(identifierSchema, z.array(identifierSchema).min(1).max(200)),
78
+ /** Subset of SQL_SAFE_FUNCTIONS (and SQL_SAFE_WINDOW_FUNCTIONS). Defaults to all of SQL_SAFE_FUNCTIONS. */
79
+ allowedFunctions: z
80
+ .array(z.string().regex(/^[a-z_][a-z0-9_]{0,62}$/))
81
+ .max(100)
82
+ .optional(),
83
+ /** "declared": only JOIN ... ON equality over schema.relationships. "none": single-table queries. */
84
+ allowJoins: z.enum(["none", "declared"]).default("declared"),
85
+ allowSubqueries: z.boolean().default(true),
86
+ allowSetOperations: z.boolean().default(false),
87
+ allowWindowFunctions: z.boolean().default(false),
88
+ /** Every output column must be an aggregate or a GROUP BY key (no row-level results). */
89
+ requireAggregation: z.boolean().default(false),
90
+ /** Hard row cap. The query is limited to maxRows + 1 rows so truncation can be detected. */
91
+ maxRows: z.number().int().min(1).max(10_000),
92
+ /** Passed to the application's executor, which must enforce it in the database. */
93
+ timeoutMs: z.number().int().min(100).max(120_000),
94
+ maxSqlChars: z.number().int().min(100).max(20_000).default(4000),
95
+ /** Cap on the schema description sent to the model (see buildSchemaContext). */
96
+ maxSchemaChars: z.number().int().min(500).max(100_000).default(16_000),
97
+ /** Regenerations after a validation rejection, shown only the rejection code and reason. */
98
+ maxRepairAttempts: z.number().int().min(0).max(1).default(1),
99
+ maxResultBytes: z
100
+ .number()
101
+ .int()
102
+ .min(1024)
103
+ .max(10_000_000)
104
+ .default(256 * 1024),
105
+ maxResultColumns: z.number().int().min(1).max(200).default(50),
106
+ maxLiteralChars: z.number().int().min(1).max(1000).default(200),
107
+ maxOffset: z.number().int().min(0).max(1_000_000).default(10_000),
108
+ /** Bounds on parse-tree size and nesting, against pathological queries. */
109
+ maxAstNodes: z.number().int().min(50).max(50_000).default(3000),
110
+ maxAstDepth: z.number().int().min(10).max(500).default(100),
111
+ });
112
+
113
+ /** A schema and policy checked against each other, frozen. Only defineSqlPolicy() creates one. */
114
+
115
+ const definedPolicies = new WeakSet();
116
+
117
+ export function isSqlPolicy(value) {
118
+ return typeof value === "object" && value !== null && definedPolicies.has(value);
119
+ }
120
+
121
+ export function relationshipKey(a, b) {
122
+ return a < b ? `${a}=${b}` : `${b}=${a}`;
123
+ }
124
+
125
+ function configError(message, detail) {
126
+ return new AiServiceError(
127
+ ErrorCodes.CONFIG_INVALID,
128
+ message,
129
+ detail === undefined ? {} : { details: { reason: detail.slice(0, 120) } },
130
+ );
131
+ }
132
+
133
+ /**
134
+ * Validates the schema the model may see and the policy queries must satisfy, and checks them against each
135
+ * other: every allowed table and column must exist in the schema, every allowed function must be in the
136
+ * curated safe list, and every declared relationship must join allowed columns.
137
+ */
138
+ export function defineSqlPolicy(input) {
139
+ if (!SQL_DIALECTS.includes(input.dialect)) throw configError("Unsupported SQL dialect");
140
+ const schemaResult = sqlSchemaSchema.safeParse(input.schema);
141
+ if (!schemaResult.success) {
142
+ throw new AiServiceError(ErrorCodes.CONFIG_INVALID, "SQL schema is invalid", {
143
+ details: summarizeZodError(schemaResult.error, sqlSchemaSchema),
144
+ });
145
+ }
146
+ const policyResult = sqlPolicySchema.safeParse(input.policy);
147
+ if (!policyResult.success) {
148
+ throw new AiServiceError(ErrorCodes.CONFIG_INVALID, "SQL policy is invalid", {
149
+ details: summarizeZodError(policyResult.error, sqlPolicySchema),
150
+ });
151
+ }
152
+ const schema = schemaResult.data;
153
+ const policy = policyResult.data;
154
+
155
+ const schemaTables = new Map(schema.tables.map((table) => [table.name, table]));
156
+ if (schemaTables.size !== schema.tables.length) throw configError("SQL schema lists a table twice");
157
+
158
+ const tables = new Map();
159
+ for (const tableName of policy.allowedTables) {
160
+ const table = schemaTables.get(tableName);
161
+ if (table === undefined) throw configError("An allowed table is not in the schema", tableName);
162
+ const allowed = policy.allowedColumns[tableName];
163
+ if (allowed === undefined) throw configError("An allowed table has no allowed columns", tableName);
164
+ const columns = new Map();
165
+ for (const columnName of allowed) {
166
+ const column = table.columns.find((candidate) => candidate.name === columnName);
167
+ if (column === undefined) throw configError("An allowed column is not in the schema", `${tableName}.${columnName}`);
168
+ columns.set(
169
+ columnName,
170
+ Object.freeze({
171
+ table: tableName,
172
+ name: columnName,
173
+ type: column.type,
174
+ allowedValues: column.allowedValues ? Object.freeze([...column.allowedValues]) : null,
175
+ }),
176
+ );
177
+ }
178
+ tables.set(tableName, columns);
179
+ }
180
+ for (const tableName of Object.keys(policy.allowedColumns)) {
181
+ if (!tables.has(tableName)) throw configError("Allowed columns are listed for a table that is not allowed", tableName);
182
+ }
183
+
184
+ const safe = new Set([...SQL_SAFE_FUNCTIONS, ...(policy.allowWindowFunctions ? SQL_SAFE_WINDOW_FUNCTIONS : [])]);
185
+ const functions = new Set(policy.allowedFunctions ?? SQL_SAFE_FUNCTIONS);
186
+ for (const name of functions) {
187
+ if (!safe.has(name)) throw configError("An allowed function is not in the safe function list", name);
188
+ }
189
+
190
+ const relationships = new Set();
191
+ for (const { from, to } of schema.relationships) {
192
+ for (const path of [from, to]) {
193
+ const [table = "", column = ""] = path.split(".");
194
+ if (tables.get(table)?.has(column) !== true) throw configError("A relationship uses a column that is not allowed", path);
195
+ }
196
+ relationships.add(relationshipKey(from, to));
197
+ }
198
+
199
+ const result = Object.freeze({
200
+ dialect: input.dialect,
201
+ schema,
202
+ tables,
203
+ functions,
204
+ aggregates: new Set(SQL_AGGREGATE_FUNCTIONS.filter((name) => functions.has(name))),
205
+ relationships,
206
+ allowJoins: policy.allowJoins,
207
+ allowSubqueries: policy.allowSubqueries,
208
+ allowSetOperations: policy.allowSetOperations,
209
+ allowWindowFunctions: policy.allowWindowFunctions,
210
+ requireAggregation: policy.requireAggregation,
211
+ maxRows: policy.maxRows,
212
+ timeoutMs: policy.timeoutMs,
213
+ maxSqlChars: policy.maxSqlChars,
214
+ maxSchemaChars: policy.maxSchemaChars,
215
+ maxRepairAttempts: policy.maxRepairAttempts,
216
+ maxResultBytes: policy.maxResultBytes,
217
+ maxResultColumns: policy.maxResultColumns,
218
+ maxLiteralChars: policy.maxLiteralChars,
219
+ maxOffset: policy.maxOffset,
220
+ maxAstNodes: policy.maxAstNodes,
221
+ maxAstDepth: policy.maxAstDepth,
222
+ });
223
+ definedPolicies.add(result);
224
+ return result;
225
+ }
226
+
227
+ /**
228
+ * @typedef {Object} SqlRejection
229
+ * @property {false} ok
230
+ * @property {SqlValidationCode} code
231
+ * @property {string} reason - Short, safe to show to the model in a repair prompt and to log: no literal values.
232
+ */
233
+
234
+ /**
235
+ * @typedef {string | number | boolean | null} SqlParam
236
+ */
237
+
238
+ /**
239
+ * A statement that passed validation and rewriting: user-facing values are bind parameters ($1, $2, ...) and the row limit is enforced. Only this package creates one (see isValidatedQuery); executors should refuse anything else.
240
+ * @typedef {Object} ValidatedQuery
241
+ * @property {SqlDialect} dialect
242
+ * @property {string} sql
243
+ * @property {readonly SqlParam[]} params
244
+ * @property {readonly string[]} tables - Tables and "table.column" paths the statement reads, sorted.
245
+ * @property {readonly string[]} columns
246
+ * @property {number} limit - The LIMIT applied (maxRows + 1 unless the query asked for fewer).
247
+ * @property {number} maxRows
248
+ * @property {number} timeoutMs
249
+ * @property {string} fingerprint - sha256 of the parameterised SQL: lets logs identify a query without its text or values.
250
+ */
251
+
252
+ /**
253
+ * @typedef {{ readonly ok: true; readonly query: ValidatedQuery } | SqlRejection} SqlValidationOutcome
254
+ */
255
+
256
+ /**
257
+ * What the agent needs from a dialect validator (for example createPostgresSqlValidator).
258
+ * @typedef {Object} SqlValidator
259
+ * @property {SqlDialect} dialect
260
+ * @property {SqlPolicy} policy
261
+ * @property {(sql: string) => Promise<SqlValidationOutcome>} validate
262
+ */
263
+
264
+ /** Why a statement or result was refused. Reasons name identifiers at most, never literal values. */
265
+ export const SqlValidationCodes = {
266
+ SQL_EMPTY: "SQL_EMPTY",
267
+ SQL_TOO_LONG: "SQL_TOO_LONG",
268
+ SQL_INVALID_CHARACTERS: "SQL_INVALID_CHARACTERS",
269
+ SQL_COMMENT_NOT_ALLOWED: "SQL_COMMENT_NOT_ALLOWED",
270
+ SQL_PARSE_FAILED: "SQL_PARSE_FAILED",
271
+ SQL_NOT_SINGLE_SELECT: "SQL_NOT_SINGLE_SELECT",
272
+ SQL_TABLE_NOT_ALLOWED: "SQL_TABLE_NOT_ALLOWED",
273
+ SQL_COLUMN_NOT_ALLOWED: "SQL_COLUMN_NOT_ALLOWED",
274
+ SQL_FUNCTION_NOT_ALLOWED: "SQL_FUNCTION_NOT_ALLOWED",
275
+ SQL_TYPE_NOT_ALLOWED: "SQL_TYPE_NOT_ALLOWED",
276
+ SQL_FEATURE_NOT_ALLOWED: "SQL_FEATURE_NOT_ALLOWED",
277
+ SQL_JOIN_NOT_ALLOWED: "SQL_JOIN_NOT_ALLOWED",
278
+ SQL_LITERAL_INVALID: "SQL_LITERAL_INVALID",
279
+ SQL_AGGREGATION_REQUIRED: "SQL_AGGREGATION_REQUIRED",
280
+ SQL_LIMIT_INVALID: "SQL_LIMIT_INVALID",
281
+ SQL_TOO_COMPLEX: "SQL_TOO_COMPLEX",
282
+ SQL_REWRITE_FAILED: "SQL_REWRITE_FAILED",
283
+ RESULT_SHAPE_INVALID: "RESULT_SHAPE_INVALID",
284
+ RESULT_TOO_LARGE: "RESULT_TOO_LARGE",
285
+ };
286
+
287
+ export function reject(code, reason) {
288
+ return Object.freeze({ ok: false, code, reason: reason.slice(0, 200) });
289
+ }
290
+
291
+ /**
292
+ * A statement that passed validation and rewriting: user-facing values are bind parameters ($1, $2, ...) and
293
+ * the row limit is enforced.
294
+ */
295
+
296
+ /** What the agent needs from a dialect validator (for example createPostgresSqlValidator). */
297
+
298
+ const validatedQueries = new WeakSet();
299
+
300
+ export function brandValidatedQuery(query) {
301
+ const frozen = Object.freeze({
302
+ ...query,
303
+ params: Object.freeze([...query.params]),
304
+ tables: Object.freeze([...query.tables]),
305
+ columns: Object.freeze([...query.columns]),
306
+ });
307
+ validatedQueries.add(frozen);
308
+ return frozen;
309
+ }
310
+
311
+ /** True only for queries produced by a validator in this package (not for look-alike objects). */
312
+ export function isValidatedQuery(value) {
313
+ return typeof value === "object" && value !== null && validatedQueries.has(value);
314
+ }
315
+
316
+ const PLAIN_IDENTIFIER = /^[a-z_][a-z0-9_]*$/;
317
+
318
+ /** How a name must be written in PostgreSQL: bare when lower-case, double-quoted otherwise. */
319
+ export function sqlIdentifier(name) {
320
+ return PLAIN_IDENTIFIER.test(name) ? name : `"${name}"`;
321
+ }
322
+
323
+ function oneLine(text) {
324
+ return text.replace(/\s+/g, " ").trim();
325
+ }
326
+
327
+ /**
328
+ * The only description of the database the model receives, built from the policy rather than the full schema:
329
+ * tables and columns that are not allowed are never mentioned, so the model cannot learn they exist.
330
+ */
331
+ export function buildSchemaContext(policy) {
332
+ const lines = [];
333
+ for (const table of policy.schema.tables) {
334
+ const allowed = policy.tables.get(table.name);
335
+ if (allowed === undefined) continue;
336
+ lines.push(`TABLE ${sqlIdentifier(table.name)}${table.description === undefined ? "" : ` (${oneLine(table.description)})`}`);
337
+ for (const column of table.columns) {
338
+ if (!allowed.has(column.name)) continue;
339
+ const notes = [column.type];
340
+ if (column.role !== undefined) notes.push(column.role);
341
+ if (column.description !== undefined) notes.push(oneLine(column.description));
342
+ if (column.allowedValues !== undefined)
343
+ notes.push(`values: ${column.allowedValues.map((value) => `'${value.replaceAll("'", "''")}'`).join(", ")}`);
344
+ lines.push(` ${sqlIdentifier(column.name)}: ${notes.join("; ")}`);
345
+ }
346
+ }
347
+ const joins = policy.schema.relationships.map(({ from, to }) => {
348
+ const [fromTable = "", fromColumn = ""] = from.split(".");
349
+ const [toTable = "", toColumn = ""] = to.split(".");
350
+ return ` ${sqlIdentifier(fromTable)}.${sqlIdentifier(fromColumn)} = ${sqlIdentifier(toTable)}.${sqlIdentifier(toColumn)}`;
351
+ });
352
+ if (joins.length > 0 && policy.allowJoins === "declared") lines.push("JOINS (the only allowed join conditions)", ...joins);
353
+
354
+ const context = lines.join("\n");
355
+ if (context.length > policy.maxSchemaChars) {
356
+ throw new AiServiceError(ErrorCodes.CONFIG_INVALID, "Schema context exceeds maxSchemaChars", {
357
+ details: { chars: context.length, limit: policy.maxSchemaChars },
358
+ });
359
+ }
360
+ return context;
361
+ }
362
+
363
+ /** The policy rules the model is told about (the validator enforces them regardless). */
364
+ export function describePolicyRules(policy) {
365
+ const rules = [
366
+ `Return at most ${String(policy.maxRows)} rows.`,
367
+ `Allowed functions: ${[...policy.functions].sort().join(", ")}; plus CURRENT_DATE, CURRENT_TIMESTAMP, CASE, COALESCE, NULLIF, GREATEST, LEAST, EXTRACT and AT TIME ZONE.`,
368
+ policy.allowJoins === "declared"
369
+ ? "Joins: only JOIN ... ON with the listed join conditions."
370
+ : "Joins: not allowed; query one table.",
371
+ policy.allowSubqueries ? "Subqueries and WITH are allowed." : "Subqueries and WITH are not allowed.",
372
+ policy.allowSetOperations ? "UNION, INTERSECT and EXCEPT are allowed." : "UNION, INTERSECT and EXCEPT are not allowed.",
373
+ policy.allowWindowFunctions ? "Window functions are allowed." : "Window functions (OVER) are not allowed.",
374
+ ];
375
+ if (policy.requireAggregation)
376
+ rules.push("Every output column must be an aggregate or a GROUP BY key: never return individual rows.");
377
+ return rules;
378
+ }
379
+
380
+ /**
381
+ * @typedef {string | number | boolean | null} SqlCell
382
+ */
383
+
384
+ /**
385
+ * @typedef {Object} ExecutorColumn
386
+ * @property {string} name
387
+ * @property {string} [type]
388
+ */
389
+
390
+ /**
391
+ * What an application's executor returns: column names and rows as arrays in column order.
392
+ * @typedef {Object} ExecutorResult
393
+ * @property {readonly ExecutorColumn[]} columns
394
+ * @property {readonly (readonly unknown[])[]} rows
395
+ */
396
+
397
+ /**
398
+ * @typedef {Object} CheckedResult
399
+ * @property {true} ok
400
+ * @property {readonly ExecutorColumn[]} columns
401
+ * @property {readonly (readonly SqlCell[])[]} rows
402
+ * @property {boolean} truncated - True when the database returned more than maxRows rows (only maxRows are kept).
403
+ */
404
+
405
+ /**
406
+ * @typedef {Object} ResultLimits
407
+ * @property {number} maxRows
408
+ * @property {number} maxResultBytes
409
+ * @property {number} maxResultColumns
410
+ */
411
+
412
+ /** What an application's executor returns: column names and rows as arrays in column order. */
413
+
414
+ function isColumnName(name) {
415
+ for (let index = 0; index < name.length; index += 1) {
416
+ if (name.charCodeAt(index) < 32) return false;
417
+ }
418
+ return name.length > 0 && name.length <= 128;
419
+ }
420
+
421
+ /** Normalises one value from a database driver. */
422
+ function toCell(value) {
423
+ if (value === null || typeof value === "string" || typeof value === "boolean") return value;
424
+ if (typeof value === "number") return Number.isFinite(value) ? value : undefined;
425
+ if (typeof value === "bigint") return value.toString();
426
+ if (value instanceof Date) return Number.isNaN(value.getTime()) ? undefined : value.toISOString();
427
+ return undefined;
428
+ }
429
+
430
+ /**
431
+ * Checks what the application's executor returned before anything is shown or summarised: the declared shape,
432
+ * scalar values only, at most maxResultColumns columns, at most maxRows rows (one extra row means the result
433
+ * was truncated) and at most maxResultBytes of JSON.
434
+ */
435
+ export function checkQueryResult(result, limits) {
436
+ const candidate = result;
437
+ if (
438
+ typeof candidate !== "object" ||
439
+ candidate === null ||
440
+ !Array.isArray(candidate.columns) ||
441
+ !Array.isArray(candidate.rows)
442
+ ) {
443
+ return reject(SqlValidationCodes.RESULT_SHAPE_INVALID, "Executor result must have columns and rows arrays");
444
+ }
445
+ const columns = [];
446
+ for (const column of candidate.columns) {
447
+ const entry = column;
448
+ if (typeof entry !== "object" || entry === null || typeof entry.name !== "string" || !isColumnName(entry.name)) {
449
+ return reject(SqlValidationCodes.RESULT_SHAPE_INVALID, "Executor result has an invalid column");
450
+ }
451
+ columns.push(
452
+ Object.freeze(entry.type === undefined ? { name: entry.name } : { name: entry.name, type: entry.type.slice(0, 64) }),
453
+ );
454
+ }
455
+ if (columns.length === 0) return reject(SqlValidationCodes.RESULT_SHAPE_INVALID, "Executor result has no columns");
456
+ if (columns.length > limits.maxResultColumns)
457
+ return reject(SqlValidationCodes.RESULT_TOO_LARGE, `Result has more than ${String(limits.maxResultColumns)} columns`);
458
+
459
+ const sourceRows = candidate.rows;
460
+ // The query asks for maxRows + 1 rows; anything beyond that means the executor ignored the limit.
461
+ if (sourceRows.length > limits.maxRows + 1)
462
+ return reject(SqlValidationCodes.RESULT_TOO_LARGE, "Executor returned more rows than the query limit");
463
+ const truncated = sourceRows.length > limits.maxRows;
464
+ const rows = [];
465
+ let bytes = 2;
466
+ for (const sourceRow of sourceRows.slice(0, limits.maxRows)) {
467
+ if (!Array.isArray(sourceRow) || sourceRow.length !== columns.length) {
468
+ return reject(SqlValidationCodes.RESULT_SHAPE_INVALID, "Executor result row does not match its columns");
469
+ }
470
+ const row = [];
471
+ for (const value of sourceRow) {
472
+ const cell = toCell(value);
473
+ if (cell === undefined)
474
+ return reject(SqlValidationCodes.RESULT_SHAPE_INVALID, "Executor result contains a non-scalar value");
475
+ row.push(cell);
476
+ }
477
+ bytes += Buffer.byteLength(JSON.stringify(row), "utf8") + 1;
478
+ if (bytes > limits.maxResultBytes)
479
+ return reject(SqlValidationCodes.RESULT_TOO_LARGE, `Result exceeds ${String(limits.maxResultBytes)} bytes`);
480
+ rows.push(Object.freeze(row));
481
+ }
482
+ return Object.freeze({ ok: true, columns: Object.freeze(columns), rows: Object.freeze(rows), truncated });
483
+ }