@zhin.js/core 1.6.0 → 1.7.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.
@@ -1,11 +1,13 @@
1
1
  import { mkdir } from 'node:fs/promises';
2
2
  import { dirname, join } from 'node:path';
3
3
  import { isDeepStrictEqual } from 'node:util';
4
- import { Registry, assertInstanceTable, ensureDatabaseColumns, GatewayOwnedTableError, isGatewayOwnedTable, referencesGatewayOwnedTable } from '@zhin.js/database';
4
+ import { Registry, assertInstanceTable, ensureDatabaseColumns, GatewayOwnedTableError, isGatewayOwnedTable, referencesGatewayOwnedTable, RelatedModel, consoleConnectionOptions, probeConsoleCredential, refreshConsoleGrants, splitMysqlAccount } from '@zhin.js/database';
5
5
  import { formatCompact, getLogger } from '@zhin.js/logger';
6
6
  import { guardTransactionModel, databaseHostToken, databaseRootHostToken, PluginDatabaseHost, rootPluginId, } from '@zhin.js/plugin-runtime';
7
7
  import { normalizeDatabaseHostConfig, } from './database-config.js';
8
8
  import { createDatabaseState } from './database-state.js';
9
+ import { ConsoleSqlRefusal, isProtectedConsoleTable, readOnlyConsoleStatement, redactConsoleSql, writeConsoleStatements, } from './database-console-sql.js';
10
+ import { ConsoleSchemaRefusal, introspectConsoleTable, listPhysicalTables, planConsoleSchemaChange, readMysqlColumnDefinition, } from './database-console-schema.js';
9
11
  const logger = getLogger('Database');
10
12
  function wrapModel(model, db, tableName) {
11
13
  return {
@@ -65,8 +67,17 @@ function wrapModel(model, db, tableName) {
65
67
  },
66
68
  };
67
69
  }
68
- export function createDatabaseHost(config) {
69
- const { dialect, ...connectionConfig } = config;
70
+ /** How long a failed restricted-account probe is kept before the next try. */
71
+ export const CONSOLE_CREDENTIAL_RETRY_MS = 5 * 60_000;
72
+ /** How long a successful probe is trusted (raw SQL probes again after this, and after any error). */
73
+ export const CONSOLE_CREDENTIAL_TTL_MS = 60_000;
74
+ /** Minimum time between error-triggered re-probes. */
75
+ export const CONSOLE_CREDENTIAL_STALE_MIN_MS = 30_000;
76
+ /** Why raw SQL is off on PostgreSQL / MySQL without a restricted account. */
77
+ export const CONSOLE_ROLE_MISSING_REASON = 'Raw SQL on PostgreSQL / MySQL runs only on a restricted database account: run `zhin db console-role` (or `zhin doctor --fix`; `--print-sql` for a DBA) and restart';
78
+ export function createDatabaseHost(config, internal = {}) {
79
+ // `console` (the restricted Console account) never reaches the main connection's driver.
80
+ const { dialect, console: consoleCredential, ...connectionConfig } = config;
70
81
  const db = Registry.create(dialect, connectionConfig);
71
82
  let started = false;
72
83
  const state = createDatabaseState(db, config.dialect, () => started);
@@ -75,8 +86,13 @@ export function createDatabaseHost(config) {
75
86
  const definitions = new Map();
76
87
  const additions = new Map();
77
88
  let rawGuard;
78
- let gatewayView;
79
- const consolePort = createDatabaseConsole(db, config.dialect, () => started, definedTables, definitions);
89
+ const { port: consolePort, refreshDiscovered, refreshRawSql, stopConsoleSql } = createDatabaseConsole(db, config.dialect, () => started, definedTables, definitions, {
90
+ textGuard: internal.textGuard !== false,
91
+ restricted: restrictedConsoleConnection(config.dialect, connectionConfig, consoleCredential, internal.openConsoleConnection),
92
+ retryMs: internal.consoleProbeIntervalMs ?? CONSOLE_CREDENTIAL_RETRY_MS,
93
+ ttlMs: internal.consoleProbeTtlMs ?? CONSOLE_CREDENTIAL_TTL_MS,
94
+ now: internal.now ?? Date.now,
95
+ });
80
96
  const modelOf = (name) => {
81
97
  if (!started)
82
98
  return undefined;
@@ -147,19 +163,6 @@ export function createDatabaseHost(config) {
147
163
  return isGatewayOwnedTable(name) ? undefined : modelOf(name);
148
164
  },
149
165
  },
150
- gatewayTableHost() {
151
- return gatewayView ??= Object.freeze({
152
- get dialect() { return config.dialect; },
153
- get started() { return started; },
154
- define(name, definition) {
155
- if (!isGatewayOwnedTable(name))
156
- throw new Error(`Table '${name}' is not a gateway table`);
157
- defineTable(name, definition);
158
- },
159
- tables: () => [...definedTables].filter(isGatewayOwnedTable),
160
- models: Object.freeze({ get: (name) => (isGatewayOwnedTable(name) ? modelOf(name) : undefined) }),
161
- });
162
- },
163
166
  async transaction(callback) {
164
167
  if (!started)
165
168
  throw new Error('Database is not connected');
@@ -218,6 +221,10 @@ export function createDatabaseHost(config) {
218
221
  }
219
222
  started = true;
220
223
  wrapped.clear();
224
+ await refreshDiscovered().catch((error) => {
225
+ logger.debug(formatCompact({ op: 'database_discover_failed', error: error instanceof Error ? error.message : String(error) }));
226
+ });
227
+ await refreshRawSql();
221
228
  logger.debug(formatCompact({ op: 'database_start', dialect: config.dialect }));
222
229
  }
223
230
  catch (error) {
@@ -228,14 +235,89 @@ export function createDatabaseHost(config) {
228
235
  async stop() {
229
236
  if (!started)
230
237
  return;
238
+ await stopConsoleSql();
231
239
  await db.stop();
232
240
  started = false;
233
241
  wrapped.clear();
234
242
  },
235
243
  };
236
244
  }
237
- function createDatabaseConsole(db, configuredDialect, isStarted, tableNames, definitions) {
245
+ const SQL_DIALECTS = new Set(['sqlite', 'mysql', 'pg']);
246
+ const FILTER_OPERATORS = Object.freeze(['$eq', '$ne', '$gt', '$gte', '$lt', '$lte', '$like', '$nlike', '$in', '$nin']);
247
+ const FILTER_OPERATOR_SET = new Set(FILTER_OPERATORS);
248
+ /** Row cap and statement timeout of the Console SQL editor. */
249
+ export const CONSOLE_QUERY_MAX_ROWS = 1000;
250
+ export const CONSOLE_QUERY_TIMEOUT_MS = 10_000;
251
+ const DML = /^\(*\s*(?:insert|update|delete|replace)\b/;
252
+ /** Read kinds PostgreSQL can run behind a cursor (`DECLARE … CURSOR FOR`). */
253
+ const PG_CURSOR_KINDS = new Set(['select', 'with', 'values']);
254
+ const PG_CONSOLE_CURSOR = 'zhin_console_cursor';
255
+ function cappedRows(result, maxRows) {
256
+ const all = Array.isArray(result) ? result : [];
257
+ const flagged = result?.truncated === true;
258
+ return { rows: all.slice(0, maxRows), truncated: flagged || all.length > maxRows };
259
+ }
260
+ /** Thrown for a malformed `where` / `orderBy` of `db:select`. */
261
+ export class ConsoleSelectRefusal extends Error {
262
+ code = 'invalid';
263
+ constructor(message) {
264
+ super(message);
265
+ this.name = 'ConsoleSelectRefusal';
266
+ }
267
+ }
268
+ /**
269
+ * PostgreSQL / MySQL: a lazily opened pool (at most 2 connections, session reset on release) that
270
+ * logs in as `database.console.user`, built by `consoleConnectionOptions` (`@zhin.js/database`):
271
+ * nothing of the main account's credentials — fields, connection string, URI query — reaches it;
272
+ * MySQL connections refuse `LOAD DATA LOCAL` and multiple statements.
273
+ */
274
+ function restrictedConsoleConnection(dialect, connection, credential, openConnection) {
275
+ if (dialect !== 'pg' && dialect !== 'mysql')
276
+ return undefined;
277
+ if (!credential || typeof credential !== 'object')
278
+ return undefined;
279
+ const { user, password } = credential;
280
+ if (typeof user !== 'string' || !user || typeof password !== 'string' || !password)
281
+ return undefined;
282
+ return Object.freeze({
283
+ user,
284
+ open: () => {
285
+ const options = Object.freeze(consoleConnectionOptions(dialect, connection, { user, password }));
286
+ if (openConnection)
287
+ return openConnection(dialect, options);
288
+ return Registry.create(dialect, options);
289
+ },
290
+ });
291
+ }
292
+ /** Why a MySQL restricted connection is unsafe after connecting (the driver's merged config), or undefined. */
293
+ function mysqlConnectionProblem(candidate) {
294
+ const safety = candidate.dialect?.connectionSafety?.();
295
+ if (!safety)
296
+ return undefined;
297
+ if (safety.localFiles)
298
+ return 'the restricted MySQL connection would allow LOAD DATA LOCAL';
299
+ if (safety.multipleStatements)
300
+ return 'the restricted MySQL connection would allow multiple statements';
301
+ return undefined;
302
+ }
303
+ function createDatabaseConsole(db, configuredDialect, isStarted, tableNames, definitions, sqlOptions) {
238
304
  const type = databaseType(configuredDialect);
305
+ const sqlDialect = type === 'related' && SQL_DIALECTS.has(configuredDialect)
306
+ ? configuredDialect
307
+ : undefined;
308
+ const sqlIsolation = sqlDialect === 'sqlite' ? 'separate-store' : sqlDialect ? 'restricted-credential' : undefined;
309
+ /** Physical tables no code declared (created from the Console, left by removed plugins). */
310
+ const discovered = new Map();
311
+ const capabilities = Object.freeze({
312
+ sort: type !== 'keyvalue',
313
+ filterOperators: type === 'keyvalue' ? Object.freeze([]) : FILTER_OPERATORS,
314
+ sql: !!sqlDialect,
315
+ schema: !!sqlDialect,
316
+ ...(sqlIsolation ? { sqlIsolation } : {}),
317
+ ...(sqlDialect ? {} : { reason: `SQL and schema editing need SQLite, MySQL or PostgreSQL (current: ${configuredDialect})` }),
318
+ });
319
+ const listed = () => [...tableNames, ...[...discovered.keys()].filter(name => !tableNames.has(name))]
320
+ .filter(name => !isGatewayOwnedTable(name));
239
321
  const requireModel = (table) => {
240
322
  // Gateway tables (console_users, sessions, tokens, audit) are never reachable from here.
241
323
  assertInstanceTable(table);
@@ -246,18 +328,298 @@ function createDatabaseConsole(db, configuredDialect, isStarted, tableNames, def
246
328
  throw new Error(`Table '${table}' not found`);
247
329
  return model;
248
330
  };
331
+ const requireSql = () => {
332
+ if (!isStarted())
333
+ throw new Error('Database is not connected');
334
+ if (!sqlDialect)
335
+ throw new ConsoleSqlRefusal('unsupported', capabilities.reason ?? 'SQL is not supported by this database');
336
+ return sqlDialect;
337
+ };
338
+ /** Why raw SQL (`db:query` / `db:execute`) is off on this connection, if it is. */
339
+ let rawSqlProblem;
340
+ // ---- the restricted account (PostgreSQL / MySQL, ADR 0059 §4)
341
+ let restrictedDb;
342
+ /** Why the restricted account cannot be used (undefined once probed ok). */
343
+ let accessProblem = sqlDialect && sqlDialect !== 'sqlite'
344
+ ? (sqlOptions.restricted ? 'The restricted Console database account has not been checked yet' : CONSOLE_ROLE_MISSING_REASON)
345
+ : undefined;
346
+ let lastProbeAt;
347
+ /** Set after an error on the restricted connection: probe again before the next use. */
348
+ let probeStale = false;
349
+ /** Why raw SQL is off, as a code the Console can act on. */
350
+ let accessProblemCode = sqlDialect && sqlDialect !== 'sqlite'
351
+ ? (sqlOptions.restricted ? 'console-role-invalid' : 'console-role-missing')
352
+ : undefined;
353
+ const closeRestricted = async () => {
354
+ const current = restrictedDb;
355
+ restrictedDb = undefined;
356
+ await current?.stop().catch(() => undefined);
357
+ };
358
+ /**
359
+ * Opens and probes the restricted account (and, on PostgreSQL, refreshes its grants with the
360
+ * main account first — instance tables granted, `console_*` / marker grants revoked). A healthy
361
+ * account is probed again on its own connection after `ttlMs` and after any error; a failure
362
+ * keeps raw SQL off and is retried at most every `retryMs`.
363
+ */
364
+ const refreshConsoleAccess = async (force = false) => {
365
+ if (!sqlDialect || sqlDialect === 'sqlite' || !sqlOptions.restricted || !isStarted())
366
+ return;
367
+ const now = sqlOptions.now();
368
+ const healthy = restrictedDb !== undefined && accessProblem === undefined;
369
+ // After an error the next use probes again, but not more often than every 30 s (a burst of
370
+ // failing statements does not turn into a burst of probes and grant refreshes).
371
+ if (!force && healthy && lastProbeAt !== undefined && now - lastProbeAt < (probeStale ? CONSOLE_CREDENTIAL_STALE_MIN_MS : sqlOptions.ttlMs))
372
+ return;
373
+ if (!force && !healthy && lastProbeAt !== undefined && now - lastProbeAt < sqlOptions.retryMs)
374
+ return;
375
+ lastProbeAt = now;
376
+ probeStale = false;
377
+ const restricted = sqlOptions.restricted;
378
+ try {
379
+ const mainUser = await mainAccount(sqlDialect, sql => db.query(sql));
380
+ if (sqlDialect === 'pg') {
381
+ await refreshConsoleGrants((sql, params) => db.query(sql, params), { role: restricted.user }).catch((error) => {
382
+ logger.warn(formatCompact({ op: 'database_console_grants_failed', error: error instanceof Error ? error.message : String(error) }));
383
+ });
384
+ }
385
+ let candidate = healthy ? restrictedDb : undefined;
386
+ if (!candidate) {
387
+ await closeRestricted();
388
+ candidate = restricted.open();
389
+ await candidate.start();
390
+ }
391
+ const opened = candidate;
392
+ const unsafe = sqlDialect === 'mysql' ? mysqlConnectionProblem(opened) : undefined;
393
+ const probe = unsafe ? { ok: false, problems: [unsafe] } : await probeConsoleCredential((sql, params) => opened.query(sql, params), {
394
+ dialect: sqlDialect, expectedUser: restricted.user, ...(mainUser ? { mainUser } : {}),
395
+ }).catch(async (error) => {
396
+ await opened.stop().catch(() => undefined);
397
+ if (restrictedDb === opened)
398
+ restrictedDb = undefined;
399
+ throw error;
400
+ });
401
+ if (!probe.ok) {
402
+ await opened.stop().catch(() => undefined);
403
+ if (restrictedDb === opened)
404
+ restrictedDb = undefined;
405
+ accessProblem = `The restricted Console database account is not restricted enough: ${probe.problems.join('; ')}`;
406
+ // Object names (e.g. SECURITY DEFINER functions) go to the log only, never into sqlReason.
407
+ const details = probe.details;
408
+ if (details?.length)
409
+ logger.warn(formatCompact({ op: 'database_console_role_details', details: details.join('; ') }));
410
+ accessProblemCode = 'console-role-invalid';
411
+ }
412
+ else {
413
+ restrictedDb = opened;
414
+ accessProblem = undefined;
415
+ accessProblemCode = undefined;
416
+ }
417
+ }
418
+ catch (error) {
419
+ accessProblem = `The restricted Console database account cannot be used: ${error instanceof Error ? error.message : String(error)}`;
420
+ accessProblemCode = 'console-role-invalid';
421
+ }
422
+ if (accessProblem)
423
+ logger.warn(formatCompact({ op: 'database_console_role_unusable', reason: accessProblem }));
424
+ };
425
+ /** Marks the restricted account for a fresh probe after an error on it. */
426
+ const onRestrictedError = (work) => (sqlDialect === 'sqlite' ? work : work.catch((error) => {
427
+ probeStale = true;
428
+ throw error;
429
+ }));
430
+ /** The connection raw Console SQL runs on. */
431
+ const executor = () => {
432
+ if (sqlDialect === 'sqlite')
433
+ return db;
434
+ return accessProblem ? undefined : restrictedDb;
435
+ };
436
+ /** Code of `rawSqlProblem` (Console: `console-role-*` asks for `zhin db console-role`). */
437
+ let rawSqlProblemCode;
438
+ const refreshRawSql = async () => {
439
+ if (!sqlDialect || !isStarted())
440
+ return;
441
+ await refreshConsoleAccess();
442
+ const target = executor();
443
+ if (!target) {
444
+ rawSqlProblem = accessProblem;
445
+ rawSqlProblemCode = accessProblemCode;
446
+ return;
447
+ }
448
+ rawSqlProblemCode = sqlDialect === 'sqlite' ? 'sqlite-isolation' : 'text-compatibility';
449
+ rawSqlProblem = await rawSqlCompatibilityProblem(sqlDialect, {
450
+ query: (sql) => target.query(sql),
451
+ isolatedReads: () => db.dialect.supportsIsolatedReads?.() === true,
452
+ }).catch((error) => `Cannot check how the server reads SQL text: ${error instanceof Error ? error.message : String(error)}`);
453
+ };
454
+ const requireExecutor = () => {
455
+ const target = executor();
456
+ if (!target)
457
+ throw new ConsoleSqlRefusal('unsupported', accessProblem ?? 'Raw SQL is unavailable');
458
+ return target;
459
+ };
460
+ /** Raw SQL needs the server to read text as the Console lexer does (checked again on every run). */
461
+ const requireRawSql = async () => {
462
+ const dialect = requireSql();
463
+ await refreshRawSql();
464
+ if (rawSqlProblem)
465
+ throw new ConsoleSqlRefusal('unsupported', rawSqlProblem);
466
+ return dialect;
467
+ };
468
+ const currentCapabilities = () => (rawSqlProblem && sqlDialect
469
+ ? Object.freeze({ ...capabilities, sql: false, sqlReason: rawSqlProblem, ...(rawSqlProblemCode ? { sqlReasonCode: rawSqlProblemCode } : {}), reason: rawSqlProblem })
470
+ : capabilities);
471
+ const describe = async (table) => {
472
+ assertInstanceTable(table);
473
+ const dialect = requireSql();
474
+ const schema = await introspectConsoleTable(dialect, (sql, params) => db.query(sql, params), table);
475
+ if (!schema.columns.length)
476
+ throw new ConsoleSchemaRefusal('not_found', `Table '${table}' not found`);
477
+ return schema;
478
+ };
479
+ const columnsOf = async (table) => {
480
+ const declared = definitions.get(table) ?? discovered.get(table);
481
+ if (declared)
482
+ return Object.keys(declared);
483
+ if (sqlDialect)
484
+ return (await describe(table)).columns.map(column => column.name);
485
+ return undefined;
486
+ };
487
+ const refreshDiscovered = async () => {
488
+ if (!sqlDialect || !isStarted())
489
+ return;
490
+ const physical = await listPhysicalTables(sqlDialect, (sql, params) => db.query(sql, params));
491
+ const present = new Set(physical);
492
+ for (const name of [...discovered.keys()])
493
+ if (!present.has(name))
494
+ discovered.delete(name);
495
+ for (const name of physical) {
496
+ if (tableNames.has(name) || isProtectedConsoleTable(name))
497
+ continue;
498
+ const schema = await introspectConsoleTable(sqlDialect, (sql, params) => db.query(sql, params), name);
499
+ discovered.set(name, Object.fromEntries(schema.columns.map(column => [column.name, {
500
+ type: column.type,
501
+ ...(column.primary ? { primary: true } : {}),
502
+ ...(column.nullable ? {} : { nullable: false }),
503
+ }])));
504
+ if (!db.models.has(name))
505
+ db.models.set(name, new RelatedModel(db, name));
506
+ }
507
+ };
508
+ /** MariaDB has no `max_execution_time`; its statement limit is `max_statement_time` (seconds). Read once. */
509
+ let mysqlIsMariaDb;
510
+ const mysqlTimeout = async (run, timeoutMs) => {
511
+ if (mysqlIsMariaDb === undefined) {
512
+ const rows = await run('SELECT VERSION() AS v');
513
+ mysqlIsMariaDb = /mariadb/iu.test(String(rows?.[0]?.v ?? ''));
514
+ }
515
+ if (timeoutMs === 'DEFAULT')
516
+ return mysqlIsMariaDb ? 'SET SESSION max_statement_time = DEFAULT' : 'SET SESSION max_execution_time = DEFAULT';
517
+ return mysqlIsMariaDb ? `SET SESSION max_statement_time = ${(timeoutMs / 1000).toFixed(3)}` : `SET SESSION max_execution_time = ${timeoutMs}`;
518
+ };
519
+ /** Runs `body` in one transaction; `rollback` discards it after collecting the result. */
520
+ const inTransaction = async (body, options, on = db) => {
521
+ const dialect = requireSql();
522
+ const discard = Symbol('rollback');
523
+ let result;
524
+ try {
525
+ await on.transaction(async (trx) => {
526
+ const run = (sql) => trx.query(sql);
527
+ const statement = (sql, statementOptions) => {
528
+ if (!trx.queryStatement)
529
+ throw new Error('This database driver cannot run single statements');
530
+ return trx.queryStatement(sql, statementOptions);
531
+ };
532
+ const timeout = Math.max(1, Math.floor(options.timeoutMs ?? CONSOLE_QUERY_TIMEOUT_MS));
533
+ // SET LOCAL ends with the transaction; Console SQL cannot lift it (SET / set_config are refused).
534
+ if (dialect === 'pg')
535
+ await run(`SET LOCAL statement_timeout = ${timeout}`);
536
+ if (dialect === 'mysql' && options.readOnly)
537
+ await run(await mysqlTimeout(run, timeout));
538
+ try {
539
+ result = await body({ run, statement });
540
+ }
541
+ finally {
542
+ if (dialect === 'mysql' && options.readOnly)
543
+ await run(await mysqlTimeout(run, 'DEFAULT')).catch(() => undefined);
544
+ }
545
+ if (options.rollback)
546
+ throw discard;
547
+ }, options.readOnly ? { readOnly: true } : undefined);
548
+ }
549
+ catch (error) {
550
+ if (error === discard)
551
+ return result;
552
+ // Probe the restricted account again before its next use (it may have changed).
553
+ if (on !== db)
554
+ probeStale = true;
555
+ throw error;
556
+ }
557
+ return result;
558
+ };
559
+ const syncAfterSchemaChange = async (change) => {
560
+ if (change.kind === 'create-table') {
561
+ discovered.set(change.table, Object.fromEntries(change.columns.map(column => [column.name, { ...column, name: undefined }])
562
+ .map(([name, column]) => [name, Object.fromEntries(Object.entries(column).filter(([key, value]) => key !== 'name' && value !== undefined))])));
563
+ if (!db.models.has(change.table))
564
+ db.models.set(change.table, new RelatedModel(db, change.table));
565
+ return;
566
+ }
567
+ const declared = definitions.get(change.table);
568
+ if (!declared) {
569
+ await refreshDiscovered();
570
+ return;
571
+ }
572
+ // Keep the declared definition (its Zhin types) in step with the physical table.
573
+ const next = { ...declared };
574
+ if (change.kind === 'add-column') {
575
+ const { name, ...column } = change.column;
576
+ next[name] = column;
577
+ }
578
+ else if (change.kind === 'alter-column') {
579
+ const previous = (next[change.column] ?? {});
580
+ const merged = { ...previous };
581
+ if (change.type)
582
+ merged.type = change.type;
583
+ if (change.nullable !== undefined)
584
+ merged.nullable = change.nullable;
585
+ if (change.default !== undefined)
586
+ merged.default = change.default;
587
+ if (change.dropDefault)
588
+ delete merged.default;
589
+ next[change.column] = merged;
590
+ }
591
+ else {
592
+ return;
593
+ }
594
+ definitions.set(change.table, next);
595
+ db.definitions.set(change.table, next);
596
+ };
597
+ const plan = async (change) => {
598
+ const dialect = requireSql();
599
+ await refreshDiscovered();
600
+ return planConsoleSchemaChange(change, {
601
+ dialect,
602
+ host: db.dialect,
603
+ hasTable: table => tableNames.has(table) || discovered.has(table),
604
+ isDeclared: table => tableNames.has(table),
605
+ describe,
606
+ ...(dialect === 'mysql' ? { mysqlColumn: (table, column) => readMysqlColumnDefinition((sql, params) => db.query(sql, params), table, column) } : {}),
607
+ });
608
+ };
249
609
  const port = {
250
610
  info: () => ({
251
611
  dialect: configuredDialect,
252
612
  type,
253
- tables: [...tableNames].filter(name => !isGatewayOwnedTable(name)),
613
+ tables: listed(),
254
614
  connected: isStarted(),
615
+ capabilities: currentCapabilities(),
255
616
  }),
256
- tables: () => [...tableNames].filter(name => !isGatewayOwnedTable(name)).map((name) => ({
617
+ tables: () => listed().map((name) => ({
257
618
  name,
258
- columns: definitions.get(name),
619
+ columns: definitions.get(name) ?? discovered.get(name),
620
+ ...(tableNames.has(name) ? {} : { discovered: true }),
259
621
  })),
260
- async select(table, page, pageSize, where) {
622
+ async select(table, page, pageSize, where, orderBy) {
261
623
  const model = requireModel(table);
262
624
  if (type === 'keyvalue') {
263
625
  if (!model.entries)
@@ -272,6 +634,9 @@ function createDatabaseConsole(db, configuredDialect, isStarted, tableNames, def
272
634
  };
273
635
  }
274
636
  const filter = where ?? {};
637
+ const columns = type === 'related' ? await columnsOf(table) : undefined;
638
+ validateWhere(filter, columns, 0);
639
+ const order = orderBy ? validateOrderBy(orderBy, columns) : undefined;
275
640
  let total;
276
641
  try {
277
642
  const counted = await db.aggregate(table).count('*', 'total').where(filter);
@@ -284,8 +649,15 @@ function createDatabaseConsole(db, configuredDialect, isStarted, tableNames, def
284
649
  let selection = model.select();
285
650
  if (Object.keys(filter).length > 0)
286
651
  selection = selection.where(filter);
652
+ if (order) {
653
+ selection = selection.orderBy(order.column, order.direction === 'desc' ? 'DESC' : 'ASC');
654
+ // A unique tie-breaker keeps pages stable when many rows share the sorted value.
655
+ const tieBreaker = primaryKeyOf(definitions.get(table) ?? discovered.get(table)) ?? (type === 'document' ? '_id' : undefined);
656
+ if (tieBreaker && tieBreaker !== order.column)
657
+ selection = selection.orderBy(tieBreaker, 'ASC');
658
+ }
287
659
  const rows = await selection.limit(pageSize).offset((page - 1) * pageSize);
288
- return { rows, total, page, pageSize };
660
+ return { rows, total, page, pageSize, ...(order ? { orderBy: order } : {}) };
289
661
  },
290
662
  async insert(table, row) {
291
663
  const model = requireModel(table);
@@ -334,6 +706,7 @@ function createDatabaseConsole(db, configuredDialect, isStarted, tableNames, def
334
706
  db.definitions.delete(table);
335
707
  tableNames.delete(table);
336
708
  definitions.delete(table);
709
+ discovered.delete(table);
337
710
  },
338
711
  async kvGet(table, key) {
339
712
  const model = requireModel(table);
@@ -359,36 +732,387 @@ function createDatabaseConsole(db, configuredDialect, isStarted, tableNames, def
359
732
  throw new Error(`Table '${table}' is not a key-value bucket`);
360
733
  return (await model.entries()).map(([key, value]) => ({ key, value }));
361
734
  },
735
+ async query(sql, options) {
736
+ const dialect = await requireRawSql();
737
+ const on = requireExecutor();
738
+ const statement = sqlOptions.textGuard ? readOnlyConsoleStatement(sql, dialect) : { text: sql, kind: 'unchecked' };
739
+ const maxRows = Math.min(Math.max(1, Math.floor(options?.maxRows ?? CONSOLE_QUERY_MAX_ROWS)), CONSOLE_QUERY_MAX_ROWS);
740
+ const timeoutMs = Math.max(1, Math.floor(options?.timeoutMs ?? CONSOLE_QUERY_TIMEOUT_MS));
741
+ const started = Date.now();
742
+ let read;
743
+ if (dialect === 'sqlite' && db.dialect.supportsIsolatedReads?.() && db.dialect.queryReadOnlyIsolated) {
744
+ // node:sqlite cannot interrupt a statement: run it in a child process, killed at the budget.
745
+ read = await db.dialect.queryReadOnlyIsolated(statement.text, { maxRows, timeoutMs });
746
+ }
747
+ else {
748
+ read = await inTransaction(async (trx) => {
749
+ if (dialect === 'pg' && PG_CURSOR_KINDS.has(statement.kind)) {
750
+ // A cursor reads only the rows the cap keeps instead of the whole result.
751
+ await trx.statement(`DECLARE ${PG_CONSOLE_CURSOR} NO SCROLL CURSOR FOR\n${statement.text}\n`);
752
+ return cappedRows(await trx.statement(`FETCH FORWARD ${maxRows + 1} FROM ${PG_CONSOLE_CURSOR}`), maxRows);
753
+ }
754
+ return cappedRows(await trx.statement(statement.text, { maxRows }), maxRows);
755
+ }, { readOnly: true, rollback: true, timeoutMs }, on);
756
+ }
757
+ const rows = read.rows.map(jsonSafeRow);
758
+ const columns = read.columns?.length ? [...read.columns] : [...new Set(rows.flatMap(row => Object.keys(row)))];
759
+ return Object.freeze({ columns, rows, rowCount: rows.length, truncated: read.truncated, durationMs: Date.now() - started });
760
+ },
761
+ async execute(sql, options) {
762
+ const dialect = await requireRawSql();
763
+ const on = requireExecutor();
764
+ const statements = sqlOptions.textGuard ? writeConsoleStatements(sql, dialect) : [{ text: sql, code: sql.trim().toLowerCase() }];
765
+ const dryRun = options?.dryRun === true;
766
+ const started = Date.now();
767
+ const runAll = async (run) => {
768
+ const results = [];
769
+ for (const statement of statements)
770
+ results.push(statementResult(statement.text, await run(statement.text)));
771
+ return results;
772
+ };
773
+ // Every statement goes through the single-statement protocol, so a COMMIT the lexer missed
774
+ // cannot ride along (and transaction control is refused): a dry run always rolls back.
775
+ // MySQL commits DDL implicitly: only all-DML batches run in a transaction (and can be dry-run).
776
+ const transactional = dialect !== 'mysql' || statements.every(statement => DML.test(statement.code));
777
+ if (!transactional && dryRun) {
778
+ return Object.freeze({ statements: statements.map(statement => ({ sql: statement.text })), dryRun, estimateUnavailable: true, durationMs: 0 });
779
+ }
780
+ const results = transactional
781
+ ? await inTransaction(trx => runAll(text => trx.statement(text)), { rollback: dryRun, ...(options?.timeoutMs ? { timeoutMs: options.timeoutMs } : {}) }, on)
782
+ // MySQL DDL: dialect queries are prepared statements (one statement each).
783
+ : await runAll(text => onRestrictedError(on.query(text)));
784
+ if (!dryRun)
785
+ await refreshDiscovered().catch(() => undefined);
786
+ return Object.freeze({ statements: Object.freeze(results), dryRun, durationMs: Date.now() - started });
787
+ },
788
+ redactSql: (sql) => redactConsoleSql(sql, sqlDialect ?? 'mysql'),
789
+ describe,
790
+ previewSchema: plan,
791
+ async applySchema(change, confirm) {
792
+ const dialect = requireSql();
793
+ const planned = await plan(change);
794
+ // The planned DDL travels with a failure too, so the audit log records what was attempted.
795
+ const attempted = (error) => {
796
+ if (error && typeof error === 'object' && !Object.isFrozen(error)) {
797
+ Object.defineProperty(error, 'statements', { value: planned.statements, enumerable: false, configurable: true });
798
+ }
799
+ return error;
800
+ };
801
+ if (planned.destructive && confirm !== planned.confirm) {
802
+ throw attempted(new ConsoleSchemaRefusal('confirm_required', `Type '${planned.confirm}' to confirm this change`));
803
+ }
804
+ try {
805
+ if (dialect === 'mysql') {
806
+ for (const statement of planned.statements)
807
+ await db.query(statement);
808
+ }
809
+ else {
810
+ await inTransaction(async (trx) => { for (const statement of planned.statements)
811
+ await trx.run(statement); }, {});
812
+ }
813
+ }
814
+ catch (error) {
815
+ throw attempted(error);
816
+ }
817
+ await syncAfterSchemaChange(planned.change);
818
+ return planned;
819
+ },
362
820
  };
363
- return Object.freeze(port);
821
+ return { port: Object.freeze(port), refreshDiscovered, refreshRawSql, stopConsoleSql: closeRestricted };
822
+ }
823
+ /** The main account's name (PostgreSQL `current_user`, MySQL user part of `CURRENT_USER()`). */
824
+ async function mainAccount(dialect, query) {
825
+ const rows = await query(dialect === 'pg' ? 'SELECT current_user AS account' : 'SELECT CURRENT_USER() AS account');
826
+ const account = rows?.[0]?.account;
827
+ if (typeof account !== 'string')
828
+ return undefined;
829
+ return dialect === 'mysql' ? splitMysqlAccount(account).user : account;
830
+ }
831
+ /**
832
+ * Why the Console must not run raw SQL on this connection, or undefined. The Console lexer reads
833
+ * strings the way the server does by default; a server that treats backslashes (MySQL
834
+ * `NO_BACKSLASH_ESCAPES`, PostgreSQL `standard_conforming_strings = off`) or double quotes (MySQL
835
+ * `ANSI_QUOTES`) differently would split and classify statements differently. SQLite needs a file
836
+ * database: only a separate connection can be stopped at the time limit.
837
+ */
838
+ export async function rawSqlCompatibilityProblem(dialect, probe) {
839
+ if (dialect === 'sqlite') {
840
+ return probe.isolatedReads() ? undefined : 'The SQL console is unsupported for an in-memory SQLite database (a query could not be stopped at the time limit)';
841
+ }
842
+ if (dialect === 'pg') {
843
+ const rows = await probe.query('SELECT current_setting(\'standard_conforming_strings\') AS value');
844
+ const value = String(rows?.[0]?.value ?? '').toLowerCase();
845
+ return value === 'on' ? undefined : `The SQL console needs standard_conforming_strings = on (the server reports '${value || 'unknown'}'), so that it reads string literals as the server does`;
846
+ }
847
+ const rows = await probe.query('SELECT @@SESSION.sql_mode AS mode');
848
+ const modes = String(rows?.[0]?.mode ?? '').toUpperCase().split(',').map(mode => mode.trim());
849
+ const conflicting = modes.filter(mode => mode === 'NO_BACKSLASH_ESCAPES' || mode === 'ANSI_QUOTES' || mode === 'ANSI');
850
+ return conflicting.length ? `The SQL console is off while sql_mode contains ${conflicting.join(', ')}: the server would read string literals differently from the Console` : undefined;
851
+ }
852
+ function primaryKeyOf(definition) {
853
+ if (!definition)
854
+ return undefined;
855
+ return Object.entries(definition).find(([, column]) => column && typeof column === 'object' && column.primary === true)?.[0];
856
+ }
857
+ function validateOrderBy(orderBy, columns) {
858
+ const column = typeof orderBy?.column === 'string' ? orderBy.column : '';
859
+ if (!column || column.startsWith('$') || (columns && !columns.includes(column)))
860
+ throw new ConsoleSelectRefusal(`Unknown sort column '${column}'`);
861
+ if (orderBy.direction !== 'asc' && orderBy.direction !== 'desc')
862
+ throw new ConsoleSelectRefusal('Sort direction must be asc or desc');
863
+ return Object.freeze({ column, direction: orderBy.direction });
864
+ }
865
+ function isScalar(value) {
866
+ return value === null || typeof value === 'string' || typeof value === 'boolean' || (typeof value === 'number' && Number.isFinite(value));
867
+ }
868
+ /**
869
+ * `where` of `db:select`: known columns (related tables), allow-listed operators, scalar values.
870
+ * Column names are checked because the query builder quotes identifiers without escaping.
871
+ */
872
+ function validateWhere(where, columns, depth) {
873
+ if (depth > 4)
874
+ throw new ConsoleSelectRefusal('Filter is nested too deeply');
875
+ const keys = Object.keys(where);
876
+ if (keys.length > 50)
877
+ throw new ConsoleSelectRefusal('Too many filter conditions');
878
+ for (const key of keys) {
879
+ const value = where[key];
880
+ if (key === '$and' || key === '$or') {
881
+ if (!Array.isArray(value) || !value.length || value.length > 50)
882
+ throw new ConsoleSelectRefusal(`${key} needs a non-empty array of conditions`);
883
+ for (const entry of value) {
884
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry) || !Object.keys(entry).length)
885
+ throw new ConsoleSelectRefusal(`${key} needs a non-empty array of conditions`);
886
+ validateWhere(entry, columns, depth + 1);
887
+ }
888
+ continue;
889
+ }
890
+ if (key === '$not') {
891
+ if (!value || typeof value !== 'object' || Array.isArray(value) || !Object.keys(value).length)
892
+ throw new ConsoleSelectRefusal('$not needs a condition');
893
+ validateWhere(value, columns, depth + 1);
894
+ continue;
895
+ }
896
+ if (key.startsWith('$') || (columns && !columns.includes(key)))
897
+ throw new ConsoleSelectRefusal(`Unknown filter column '${key}'`);
898
+ if (isScalar(value))
899
+ continue;
900
+ if (!value || typeof value !== 'object' || Array.isArray(value))
901
+ throw new ConsoleSelectRefusal(`Unsupported filter value for '${key}'`);
902
+ const operators = Object.entries(value);
903
+ // `{}` would compile to no condition (or invalid SQL) instead of filtering.
904
+ if (!operators.length)
905
+ throw new ConsoleSelectRefusal(`Filter on '${key}' needs an operator`);
906
+ for (const [operator, operand] of operators) {
907
+ if (!FILTER_OPERATOR_SET.has(operator))
908
+ throw new ConsoleSelectRefusal(`Unsupported filter operator '${operator}'`);
909
+ const ok = operator === '$in' || operator === '$nin'
910
+ ? Array.isArray(operand) && operand.length > 0 && operand.length <= 500 && operand.every(isScalar)
911
+ : operator === '$like' || operator === '$nlike' ? typeof operand === 'string' : isScalar(operand);
912
+ if (!ok)
913
+ throw new ConsoleSelectRefusal(`Unsupported value for ${operator} on '${key}'`);
914
+ }
915
+ }
916
+ }
917
+ function statementResult(sql, result) {
918
+ if (typeof result === 'number')
919
+ return Object.freeze({ sql, affected: result });
920
+ if (Array.isArray(result)) {
921
+ const info = result;
922
+ if (typeof info.rowCount === 'number' && /^(?:INSERT|UPDATE|DELETE|MERGE)$/.test(String(info.command))) {
923
+ return Object.freeze({ sql, affected: info.rowCount });
924
+ }
925
+ return Object.freeze({ sql, ...(result.length ? { rows: result.length } : {}) });
926
+ }
927
+ if (result && typeof result === 'object') {
928
+ const record = result;
929
+ const affected = typeof record.changes === 'number' ? record.changes : typeof record.affectedRows === 'number' ? record.affectedRows : undefined;
930
+ return Object.freeze({ sql, ...(affected !== undefined ? { affected } : {}) });
931
+ }
932
+ return Object.freeze({ sql });
933
+ }
934
+ /** JSON-safe cell values for the RPC reply (bigint, binary, dates). */
935
+ function jsonSafeRow(row) {
936
+ const out = {};
937
+ for (const [key, value] of Object.entries(row ?? {})) {
938
+ if (typeof value === 'bigint')
939
+ out[key] = Number.isSafeInteger(Number(value)) ? Number(value) : value.toString();
940
+ else if (value instanceof Date)
941
+ out[key] = value.toISOString();
942
+ else if (value instanceof Uint8Array)
943
+ out[key] = `<binary ${value.byteLength} bytes>`;
944
+ else
945
+ out[key] = value;
946
+ }
947
+ return out;
364
948
  }
365
949
  /**
366
950
  * Root-only raw registry with the gateway's tables cut off: raw SQL naming them and table-name
367
951
  * arguments (`model`, `define`, `select`, …) are refused. Methods run on the real registry.
368
952
  */
369
- function guardRawDatabase(db) {
370
- const wrapped = new Map();
371
- return new Proxy(db, {
372
- get(target, property, receiver) {
373
- const value = Reflect.get(target, property, receiver);
374
- if (typeof value !== 'function')
375
- return value;
376
- const cached = wrapped.get(property);
377
- if (cached)
378
- return cached;
379
- const guarded = function (...args) {
380
- const [first] = args;
381
- if (property === 'query' && typeof first === 'string' && referencesGatewayOwnedTable(first)) {
382
- throw new GatewayOwnedTableError();
383
- }
384
- if (typeof first === 'string')
385
- assertInstanceTable(first);
386
- return value.apply(target, args);
953
+ /** Kinds of values a facade passes through unchanged (data, not handles). */
954
+ function isPlainData(value) {
955
+ if (value === null || typeof value !== 'object')
956
+ return true;
957
+ if (Array.isArray(value) || value instanceof Date || value instanceof Uint8Array || value instanceof RegExp || value instanceof Error)
958
+ return true;
959
+ const proto = Object.getPrototypeOf(value);
960
+ return proto === Object.prototype || proto === null;
961
+ }
962
+ /** Properties a facade never exposes, whatever object it wraps. */
963
+ const FACADE_HIDDEN = new Set(['constructor', 'dialect', 'database', 'db', 'config', 'transactionContext', 'connection', 'pool']);
964
+ /**
965
+ * A frozen object exposing only the methods (and primitive-valued fields) of `target`. Every result
966
+ * that is itself a handle (a model, a query builder, a transaction context, a Map of models) is
967
+ * wrapped the same way; function arguments (callbacks) receive wrapped values. Methods are looked
968
+ * up on `target` at call time, so instrumenting the real object (tests spy on `host.db`) still
969
+ * works, while nothing reachable from the facade leads back to the dialect, its config or the
970
+ * driver handle — and the facade itself cannot be modified.
971
+ */
972
+ function methodFacade(target, guard, cache) {
973
+ const cached = cache.get(target);
974
+ if (cached)
975
+ return cached;
976
+ const facade = Object.create(null);
977
+ cache.set(target, facade);
978
+ const wrapValue = (value) => {
979
+ if (value === target)
980
+ return facade;
981
+ if (value instanceof Promise)
982
+ return value.then(wrapValue);
983
+ if (value instanceof Map)
984
+ return mapFacade(value, guard, cache);
985
+ if (typeof value === 'function')
986
+ return (...args) => wrapValue(value(...args.map(wrapValue)));
987
+ if (isPlainData(value))
988
+ return value;
989
+ return methodFacade(value, guard, cache);
990
+ };
991
+ const names = new Set();
992
+ for (let level = target; level && level !== Object.prototype; level = Object.getPrototypeOf(level)) {
993
+ for (const name of Object.getOwnPropertyNames(level))
994
+ names.add(name);
995
+ }
996
+ for (const name of names) {
997
+ if (FACADE_HIDDEN.has(name) || name.startsWith('_') || name.startsWith('#'))
998
+ continue;
999
+ let probe;
1000
+ try {
1001
+ probe = Reflect.get(target, name, target);
1002
+ }
1003
+ catch {
1004
+ continue;
1005
+ }
1006
+ if (typeof probe === 'function') {
1007
+ facade[name] = (...args) => {
1008
+ const checked = guard(name, args) ?? args;
1009
+ const method = Reflect.get(target, name, target);
1010
+ // Callbacks (transactions, `then`) receive wrapped handles.
1011
+ const passed = checked.map(arg => (typeof arg === 'function' ? (...inner) => arg(...inner.map(wrapValue)) : arg));
1012
+ return wrapValue(method.apply(target, passed));
387
1013
  };
388
- wrapped.set(property, guarded);
389
- return guarded;
390
- },
1014
+ }
1015
+ else if (probe instanceof Map) {
1016
+ Object.defineProperty(facade, name, { enumerable: true, get: () => mapFacade(Reflect.get(target, name, target), guard, cache) });
1017
+ }
1018
+ else if (probe === undefined || probe === null || typeof probe !== 'object') {
1019
+ Object.defineProperty(facade, name, { enumerable: true, get: () => { const value = Reflect.get(target, name, target); return value !== null && typeof value === 'object' ? undefined : value; } });
1020
+ }
1021
+ }
1022
+ return Object.freeze(facade);
1023
+ }
1024
+ /** Read-only, fully wrapped view of a Map (every way of reading it: get, iteration, forEach). */
1025
+ function mapFacade(map, guard, cache) {
1026
+ const cached = cache.get(map);
1027
+ if (cached)
1028
+ return cached;
1029
+ const wrap = (value) => (isPlainData(value) || typeof value !== 'object' ? value : methodFacade(value, guard, cache));
1030
+ const entries = function* () { for (const [key, value] of map)
1031
+ yield [key, wrap(value)]; };
1032
+ const view = Object.freeze({
1033
+ get: (key) => { guard('get', [key]); return wrap(map.get(key)); },
1034
+ has: (key) => map.has(key),
1035
+ get size() { return map.size; },
1036
+ keys: () => map.keys(),
1037
+ values: function* () { for (const [, value] of entries())
1038
+ yield value; },
1039
+ entries,
1040
+ forEach: (callback) => { for (const [key, value] of entries())
1041
+ callback(value, key, view); },
1042
+ [Symbol.iterator]: entries,
1043
+ [Symbol.toStringTag]: 'Map',
391
1044
  });
1045
+ cache.set(map, view);
1046
+ return view;
1047
+ }
1048
+ /**
1049
+ * The raw registry as plugins get it (`getRawDatabase()`): an explicit facade of its methods
1050
+ * (`query`, `transaction` with a wrapped transaction context, `model` / `models` with every Map
1051
+ * read wrapped, `select` / `insert` / `update` / `delete` / … returning wrapped builders), frozen,
1052
+ * with no `dialect`, `database`, `config` or driver handle anywhere behind it. Gateway tables are
1053
+ * refused: raw SQL naming them and table-name arguments. Plugins are trusted code in the same
1054
+ * process and user (ADR 0059 §1): this keeps accidental and Console / Agent-driven access off the
1055
+ * gateway's data; it does not contain a malicious plugin.
1056
+ */
1057
+ function guardRawDatabase(db) {
1058
+ const guard = (_method, args) => {
1059
+ // Every method, every argument (not by method name: `query`, `queryStatement`, `$raw`
1060
+ // conditions, …): each string anywhere in the arguments is SQL text as far as this check
1061
+ // knows. Data that literally names a gateway table is refused as well (fail closed).
1062
+ const checked = args.map(arg => checkedSqlArgument(arg, 0));
1063
+ const [first] = checked;
1064
+ if (typeof first === 'string')
1065
+ assertInstanceTable(first);
1066
+ return checked;
1067
+ };
1068
+ return methodFacade(db, guard, new WeakMap());
1069
+ }
1070
+ const SQL_ARGUMENT_MAX_DEPTH = 16;
1071
+ /**
1072
+ * Checks one raw-handle argument for gateway table names, at any depth of arrays and plain
1073
+ * objects, and returns the checked copy that goes to the driver: arrays and plain objects are
1074
+ * copied (each element / property read once), string-like values (`new String(…)`, objects with
1075
+ * their own `toString` / `valueOf` / `Symbol.toPrimitive`) are converted once. Nothing can read
1076
+ * differently at check and at use (a getter, a `toString` answering differently the second time).
1077
+ */
1078
+ function checkedSqlArgument(value, depth) {
1079
+ if (typeof value === 'string') {
1080
+ if (referencesGatewayOwnedTable(value))
1081
+ throw new GatewayOwnedTableError();
1082
+ return value;
1083
+ }
1084
+ if (value === null || typeof value !== 'object')
1085
+ return value;
1086
+ if (depth >= SQL_ARGUMENT_MAX_DEPTH)
1087
+ throw new TypeError('Raw database argument is nested too deeply');
1088
+ if (value instanceof String)
1089
+ return checkedSqlArgument(String.prototype.valueOf.call(value), depth + 1);
1090
+ if (value instanceof Date || ArrayBuffer.isView(value) || value instanceof ArrayBuffer)
1091
+ return value;
1092
+ if (Array.isArray(value))
1093
+ return Array.from(value, item => checkedSqlArgument(item, depth + 1));
1094
+ const proto = Object.getPrototypeOf(value);
1095
+ if (proto === Object.prototype || proto === null) {
1096
+ if (stringConvertible(value))
1097
+ return checkedSqlArgument(String(value), depth + 1);
1098
+ const copy = Object.create(proto);
1099
+ for (const [key, item] of Object.entries(value)) {
1100
+ if (referencesGatewayOwnedTable(key))
1101
+ throw new GatewayOwnedTableError();
1102
+ Object.defineProperty(copy, key, { value: checkedSqlArgument(item, depth + 1), enumerable: true, writable: true, configurable: true });
1103
+ }
1104
+ return copy;
1105
+ }
1106
+ // Other class instances: string-convertible ones are what a driver would stringify.
1107
+ return stringConvertible(value) ? checkedSqlArgument(String(value), depth + 1) : value;
1108
+ }
1109
+ /** An object whose string conversion is its own code (`toString`, `valueOf`, `Symbol.toPrimitive`). */
1110
+ function stringConvertible(value) {
1111
+ const own = (name) => {
1112
+ const method = value[name];
1113
+ return typeof method === 'function' && method !== Object.prototype[name];
1114
+ };
1115
+ return typeof value[Symbol.toPrimitive] === 'function' || own('toString') || own('valueOf');
392
1116
  }
393
1117
  function databaseType(dialect) {
394
1118
  if (dialect === 'mongodb')