uql-orm 0.102.6 → 0.103.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/README.md +1 -1
  2. package/dist/browser/uql-browser.min.js +2 -2
  3. package/dist/browser/uql-browser.min.js.map +3 -3
  4. package/dist/bunSql/bunSqlQuerier.d.ts +9 -3
  5. package/dist/bunSql/bunSqlQuerier.js +7 -15
  6. package/dist/cockroachdb/crdbQuerierPool.d.ts +2 -2
  7. package/dist/context/context.d.ts +0 -6
  8. package/dist/context/context.js +1 -7
  9. package/dist/d1/d1Querier.d.ts +18 -14
  10. package/dist/d1/d1Querier.js +21 -8
  11. package/dist/d1/d1QuerierPool.d.ts +0 -1
  12. package/dist/d1/d1QuerierPool.js +0 -1
  13. package/dist/d1/d1SqliteDialect.d.ts +2 -0
  14. package/dist/d1/d1SqliteDialect.js +3 -0
  15. package/dist/dialect/abstractDialect.d.ts +3 -0
  16. package/dist/dialect/abstractDialect.js +6 -2
  17. package/dist/dialect/abstractSqlDialect.d.ts +26 -7
  18. package/dist/dialect/abstractSqlDialect.js +89 -60
  19. package/dist/dialect/mysqlLikeSqlDialect.js +6 -1
  20. package/dist/dialect/operators.d.ts +9 -3
  21. package/dist/dialect/operators.js +32 -9
  22. package/dist/dialect/vectorSqlDialect.js +2 -2
  23. package/dist/entity/metadata/definition.d.ts +11 -1
  24. package/dist/entity/metadata/definition.js +18 -0
  25. package/dist/mariadb/mariadbQuerier.d.ts +5 -2
  26. package/dist/mariadb/mariadbQuerier.js +5 -10
  27. package/dist/migrate/ddl/defaultSql.js +1 -1
  28. package/dist/migrate/ddl/indexDdl.d.ts +3 -3
  29. package/dist/migrate/ddl/indexDdl.js +7 -7
  30. package/dist/migrate/ddl/mysqlIndexDdl.js +2 -2
  31. package/dist/migrate/ddl/tableDdl.js +2 -2
  32. package/dist/migrate/indexPredicate.d.ts +4 -3
  33. package/dist/migrate/indexPredicate.js +5 -5
  34. package/dist/migrate/introspection/abstractSqlSchemaIntrospector.js +2 -6
  35. package/dist/migrate/schemaGenerator.js +1 -1
  36. package/dist/migrate/triggerSql.js +7 -5
  37. package/dist/mongodb/mongoDialect.js +17 -41
  38. package/dist/mongodb/mongoSchemaGenerator.js +12 -12
  39. package/dist/mongodb/mongodbQuerier.d.ts +4 -3
  40. package/dist/mongodb/mongodbQuerier.js +75 -102
  41. package/dist/mssql/mssqlDialect.js +4 -9
  42. package/dist/mssql/mssqlQuerier.d.ts +9 -3
  43. package/dist/mssql/mssqlQuerier.js +9 -11
  44. package/dist/mysql/mysql2Querier.d.ts +11 -2
  45. package/dist/mysql/mysql2Querier.js +4 -7
  46. package/dist/neon/index.d.ts +2 -0
  47. package/dist/neon/index.js +2 -0
  48. package/dist/neon/neonDialect.d.ts +7 -0
  49. package/dist/neon/neonDialect.js +8 -0
  50. package/dist/neon/neonQuerier.d.ts +26 -0
  51. package/dist/neon/neonQuerier.js +42 -0
  52. package/dist/neon/neonQuerierPool.d.ts +16 -6
  53. package/dist/neon/neonQuerierPool.js +48 -5
  54. package/dist/pglite/pgliteQuerier.d.ts +9 -5
  55. package/dist/pglite/pgliteQuerier.js +7 -11
  56. package/dist/postgres/abstractPgQuerierPool.d.ts +6 -6
  57. package/dist/postgres/pgExecution.d.ts +8 -0
  58. package/dist/postgres/pgExecution.js +3 -0
  59. package/dist/postgres/pgQuerier.d.ts +8 -11
  60. package/dist/postgres/pgQuerier.js +5 -9
  61. package/dist/postgres/pgQuerierPool.d.ts +2 -2
  62. package/dist/querier/abstractQuerier.d.ts +24 -20
  63. package/dist/querier/abstractQuerier.js +79 -58
  64. package/dist/querier/abstractQuerierPool.d.ts +2 -4
  65. package/dist/querier/abstractQuerierPool.js +2 -0
  66. package/dist/querier/abstractSqlQuerier.d.ts +46 -30
  67. package/dist/querier/abstractSqlQuerier.js +141 -119
  68. package/dist/querier/queryError.d.ts +2 -0
  69. package/dist/querier/queryError.js +9 -0
  70. package/dist/querier/transaction.js +3 -7
  71. package/dist/schema/canonicalType.d.ts +3 -3
  72. package/dist/schema/canonicalType.js +4 -10
  73. package/dist/sqlite/bindValues.d.ts +10 -0
  74. package/dist/sqlite/bindValues.js +8 -0
  75. package/dist/sqlite/hranaQuerier.d.ts +17 -11
  76. package/dist/sqlite/hranaQuerier.js +16 -5
  77. package/dist/sqlite/index.d.ts +1 -1
  78. package/dist/sqlite/index.js +0 -1
  79. package/dist/sqlite/localSqliteQuerierPool.js +19 -9
  80. package/dist/sqlite/sqliteQuerier.d.ts +9 -4
  81. package/dist/sqlite/sqliteQuerier.js +14 -8
  82. package/dist/turso/tursoQuerierPool.d.ts +0 -2
  83. package/dist/turso/tursoQuerierPool.js +0 -2
  84. package/dist/turso/tursoSessionQuerier.d.ts +19 -7
  85. package/dist/turso/tursoSessionQuerier.js +31 -20
  86. package/dist/type/dialect.d.ts +3 -0
  87. package/dist/type/querier.d.ts +12 -0
  88. package/dist/type/querier.js +10 -0
  89. package/dist/type/vector.d.ts +2 -1
  90. package/dist/type/vector.js +2 -2
  91. package/dist/util/asyncScope.d.ts +11 -0
  92. package/dist/util/asyncScope.js +29 -0
  93. package/dist/util/dialect.util.d.ts +21 -6
  94. package/dist/util/dialect.util.js +34 -9
  95. package/dist/util/filters.util.d.ts +5 -4
  96. package/dist/util/filters.util.js +4 -7
  97. package/dist/util/logger.js +2 -6
  98. package/dist/util/object.util.d.ts +7 -0
  99. package/dist/util/object.util.js +17 -0
  100. package/dist/util/query.util.d.ts +3 -2
  101. package/dist/util/sql.js +1 -1
  102. package/dist/util/sql.util.d.ts +18 -16
  103. package/dist/util/sql.util.js +8 -6
  104. package/package.json +5 -8
  105. package/skills/uql-orm/SKILL.md +4 -2
  106. package/dist/context/context.browser.d.ts +0 -12
  107. package/dist/context/context.browser.js +0 -33
  108. package/dist/sqlite/abstractSqliteQuerier.d.ts +0 -28
  109. package/dist/sqlite/abstractSqliteQuerier.js +0 -36
@@ -28,18 +28,28 @@ export function extendSqlite(db, extensions = []) {
28
28
  for (const extension of extensions) {
29
29
  db.loadExtension(extension);
30
30
  }
31
- db.function?.('regexp', { deterministic: true }, regexp);
31
+ db.function?.('regexp', { deterministic: true }, regexp());
32
32
  return db;
33
33
  }
34
34
  const CASELESS_FLAG = '(?i)';
35
- /** `value REGEXP pattern`: NULL where the value is, as an operator answers; a leading `(?i)` folds case, as other engines read it. */
36
- function regexp(pattern, value) {
37
- if (value === null) {
38
- return null;
39
- }
40
- const source = String(pattern);
41
- const caseless = source.startsWith(CASELESS_FLAG);
42
- return Number(new RegExp(caseless ? source.slice(CASELESS_FLAG.length) : source, caseless ? 'i' : '').test(String(value)));
35
+ /**
36
+ * `value REGEXP pattern`: NULL where the value is, as an operator answers; a leading `(?i)` folds case, as other
37
+ * engines read it. The last pattern stays compiled, since a statement tests every row against the same one.
38
+ */
39
+ function regexp() {
40
+ let last;
41
+ return (pattern, value) => {
42
+ if (value === null) {
43
+ return null;
44
+ }
45
+ const text = String(pattern);
46
+ if (last?.pattern !== text) {
47
+ const caseless = text.startsWith(CASELESS_FLAG);
48
+ const compiled = new RegExp(caseless ? text.slice(CASELESS_FLAG.length) : text, caseless ? 'i' : '');
49
+ last = { pattern: text, compiled };
50
+ }
51
+ return Number(last.compiled.test(String(value)));
52
+ };
43
53
  }
44
54
  /** A pool for a database file opened in this process, configured the same way whichever driver's {@link createDb} opens it. */
45
55
  export class AbstractLocalSqliteQuerierPool extends AbstractSharedHandleQuerierPool {
@@ -1,5 +1,6 @@
1
+ import { AbstractSqlQuerier } from '../querier/index.js';
1
2
  import type { ExtraOptions, RawRow } from '../type/index.js';
2
- import { AbstractSqliteQuerier, type SqliteBindValue } from './abstractSqliteQuerier.js';
3
+ import { type SqliteBindValue } from './bindValues.js';
3
4
  import type { SqliteDialect } from './sqliteDialect.js';
4
5
  /**
5
6
  * What uql reads of a driver's `run()`: the row count, which `node:sqlite` answers as a `bigint` once it
@@ -29,16 +30,20 @@ export type SqliteDatabase = {
29
30
  * and the embedded Turso engine. They differ only in whether preparing and stepping answer at once or
30
31
  * with a promise, which `await` and `for await` absorb.
31
32
  */
32
- export declare class SqliteQuerier extends AbstractSqliteQuerier {
33
+ export declare class SqliteQuerier extends AbstractSqlQuerier {
33
34
  readonly db: SqliteDatabase;
34
35
  readonly extra?: ExtraOptions | undefined;
35
36
  constructor(db: SqliteDatabase, dialect: SqliteDialect, extra?: ExtraOptions | undefined);
36
37
  /** Every querier of the pool is this one handle's session, so they share its transaction. */
37
38
  protected get connection(): object;
38
39
  /** `reader` picks the call: `run()` would discard the rows of a statement that reads, RETURNING included. */
39
- protected execute(query: string, values: SqliteBindValue[]): Promise<{
40
+ protected execute(sql: string, values?: unknown[]): Promise<{
41
+ changes?: undefined;
40
42
  rows: RawRow[];
43
+ } | {
44
+ rows: never[];
41
45
  changes: number;
42
46
  }>;
43
- protected iterate(query: string, values: SqliteBindValue[]): Promise<AsyncIterable<RawRow> | Iterable<RawRow>>;
47
+ /** Row by row, as the driver steps the statement. */
48
+ internalStream(sql: string, values?: unknown[]): AsyncGenerator<RawRow, void, unknown>;
44
49
  }
@@ -1,10 +1,12 @@
1
- import { AbstractSqliteQuerier } from './abstractSqliteQuerier.js';
1
+ import { AbstractSqlQuerier } from '../querier/index.js';
2
+ import { decodeBigInts } from '../util/wideNumber.js';
3
+ import { toBindValues } from './bindValues.js';
2
4
  /**
3
5
  * Querier for the SQLite drivers that prepare statements: `better-sqlite3`, `bun:sqlite`, `node:sqlite`
4
6
  * and the embedded Turso engine. They differ only in whether preparing and stepping answer at once or
5
7
  * with a promise, which `await` and `for await` absorb.
6
8
  */
7
- export class SqliteQuerier extends AbstractSqliteQuerier {
9
+ export class SqliteQuerier extends AbstractSqlQuerier {
8
10
  db;
9
11
  extra;
10
12
  constructor(db, dialect, extra) {
@@ -17,14 +19,18 @@ export class SqliteQuerier extends AbstractSqliteQuerier {
17
19
  return this.db;
18
20
  }
19
21
  /** `reader` picks the call: `run()` would discard the rows of a statement that reads, RETURNING included. */
20
- async execute(query, values) {
21
- const stmt = await this.db.prepare(query);
22
+ async execute(sql, values) {
23
+ const stmt = await this.db.prepare(sql);
22
24
  if (stmt.reader) {
23
- return { rows: (await stmt.all(...values)), changes: 0 };
25
+ return { rows: (await stmt.all(...toBindValues(values))).map(decodeBigInts) };
24
26
  }
25
- return { rows: [], changes: Number((await stmt.run(...values)).changes) };
27
+ return { rows: [], changes: Number((await stmt.run(...toBindValues(values))).changes) };
26
28
  }
27
- async iterate(query, values) {
28
- return (await this.db.prepare(query)).iterate(...values);
29
+ /** Row by row, as the driver steps the statement. */
30
+ async *internalStream(sql, values) {
31
+ const stmt = await this.db.prepare(sql);
32
+ for await (const row of stmt.iterate(...toBindValues(values))) {
33
+ yield decodeBigInts(row);
34
+ }
29
35
  }
30
36
  }
@@ -13,6 +13,4 @@ export declare class TursoQuerierPool extends AbstractSqlQuerierPool<TursoSessio
13
13
  private readonly conf;
14
14
  constructor(conf: TursoConfig, extra?: ExtraOptions);
15
15
  getQuerier(): Promise<TursoSessionQuerier>;
16
- /** Nothing to close: every querier closes its own session. */
17
- end(): Promise<void>;
18
16
  }
@@ -16,6 +16,4 @@ export class TursoQuerierPool extends AbstractSqlQuerierPool {
16
16
  const { Session } = await import('@tursodatabase/serverless');
17
17
  return new TursoSessionQuerier(new Session(this.conf), this.dialect, this.extra);
18
18
  }
19
- /** Nothing to close: every querier closes its own session. */
20
- async end() { }
21
19
  }
@@ -1,6 +1,8 @@
1
- import { AbstractSqliteQuerier, type SqliteBindValue } from '../sqlite/abstractSqliteQuerier.js';
1
+ import { AbstractSqlQuerier, type BoundStatement } from '../querier/index.js';
2
+ import { type SqliteBindValue } from '../sqlite/bindValues.js';
2
3
  import type { SqliteDialect } from '../sqlite/sqliteDialect.js';
3
4
  import type { ExtraOptions, RawRow } from '../type/index.js';
5
+ import type { SqlExecution } from '../util/sql.util.js';
4
6
  /** What a statement comes back with on a session: each row an array of its values, named by `columns`. */
5
7
  export type TursoResultSet = {
6
8
  columns: string[];
@@ -31,21 +33,31 @@ export type TursoCursorEntry = {
31
33
  */
32
34
  export type TursoSession = {
33
35
  execute(sql: string, args: SqliteBindValue[], safeIntegers: boolean): Promise<TursoResultSet>;
36
+ /**
37
+ * Runs `statements` as one request, stopping at the first failure; with a `mode` the request carries its own
38
+ * `BEGIN` and `COMMIT`, so it is all or none. `raw` answers each row as an array of its values.
39
+ */
40
+ batch(statements: {
41
+ sql: string;
42
+ args: SqliteBindValue[];
43
+ }[], mode: 'immediate' | undefined, queryOptions: undefined, safeIntegers: boolean, raw: boolean): Promise<TursoResultSet[]>;
34
44
  executeRaw(sql: string, args: SqliteBindValue[]): Promise<{
35
45
  entries: AsyncIterable<TursoCursorEntry>;
36
46
  }>;
37
47
  close(): Promise<void>;
38
48
  };
39
49
  /** A Turso Cloud querier on a stream of its own, which holds its transaction and which `release` closes. */
40
- export declare class TursoSessionQuerier extends AbstractSqliteQuerier {
50
+ export declare class TursoSessionQuerier extends AbstractSqlQuerier {
41
51
  readonly session: TursoSession;
42
52
  readonly extra?: ExtraOptions | undefined;
43
53
  constructor(session: TursoSession, dialect: SqliteDialect, extra?: ExtraOptions | undefined);
44
- protected execute(query: string, values: SqliteBindValue[]): Promise<{
45
- rows: RawRow[];
46
- changes: number;
47
- }>;
54
+ protected execute(sql: string, values?: unknown[]): Promise<SqlExecution>;
55
+ /**
56
+ * A list as one request, all or none: its own `BEGIN IMMEDIATE` and `COMMIT` in it, or, inside an open
57
+ * transaction, none, so it joins it.
58
+ */
59
+ protected executeBatch(statements: readonly BoundStatement[]): Promise<SqlExecution[]>;
48
60
  /** Row by row off the statement's cursor, as the server steps it, each decoded as `execute` decodes one. */
49
- protected iterate(query: string, values: SqliteBindValue[]): Promise<AsyncGenerator<RawRow, void, unknown>>;
61
+ internalStream(sql: string, values?: unknown[]): AsyncGenerator<RawRow, void, unknown>;
50
62
  internalRelease(): Promise<void>;
51
63
  }
@@ -1,6 +1,8 @@
1
- import { AbstractSqliteQuerier } from '../sqlite/abstractSqliteQuerier.js';
1
+ import { AbstractSqlQuerier } from '../querier/index.js';
2
+ import { sqliteStatements, toBindValues } from '../sqlite/bindValues.js';
3
+ import { decodeBigInts } from '../util/wideNumber.js';
2
4
  /** A Turso Cloud querier on a stream of its own, which holds its transaction and which `release` closes. */
3
- export class TursoSessionQuerier extends AbstractSqliteQuerier {
5
+ export class TursoSessionQuerier extends AbstractSqlQuerier {
4
6
  session;
5
7
  extra;
6
8
  constructor(session, dialect, extra) {
@@ -8,34 +10,43 @@ export class TursoSessionQuerier extends AbstractSqliteQuerier {
8
10
  this.session = session;
9
11
  this.extra = extra;
10
12
  }
11
- async execute(query, values) {
12
- const { columns, rows, rowsAffected } = await this.session.execute(query, values, true);
13
- return { rows: rows.map((row) => toRow(columns, row)), changes: rowsAffected };
13
+ async execute(sql, values) {
14
+ return executionOf(await this.session.execute(sql, toBindValues(values), true));
15
+ }
16
+ /**
17
+ * A list as one request, all or none: its own `BEGIN IMMEDIATE` and `COMMIT` in it, or, inside an open
18
+ * transaction, none, so it joins it.
19
+ */
20
+ async executeBatch(statements) {
21
+ const mode = this.hasOpenTransaction ? undefined : 'immediate';
22
+ const results = await this.session.batch(sqliteStatements(statements), mode, undefined, true, true);
23
+ return results.map(executionOf);
14
24
  }
15
25
  /** Row by row off the statement's cursor, as the server steps it, each decoded as `execute` decodes one. */
16
- async iterate(query, values) {
26
+ async *internalStream(sql, values) {
17
27
  const { DatabaseError, decodeValue } = await import('@tursodatabase/serverless');
18
- const { entries } = await this.session.executeRaw(query, values);
19
- async function* rows() {
20
- let columns = [];
21
- for await (const entry of entries) {
22
- if (entry.type === 'step_error' || entry.type === 'error') {
23
- throw new DatabaseError(entry.error?.message ?? 'SQL execution failed', entry.error?.code);
24
- }
25
- if (entry.cols) {
26
- columns = entry.cols.map(({ name }) => name);
27
- }
28
- if (entry.row) {
29
- yield toRow(columns, entry.row.map((value) => decodeValue(value, true)));
30
- }
28
+ const { entries } = await this.session.executeRaw(sql, toBindValues(values));
29
+ let columns = [];
30
+ for await (const entry of entries) {
31
+ if (entry.type === 'step_error' || entry.type === 'error') {
32
+ throw new DatabaseError(entry.error?.message ?? 'SQL execution failed', entry.error?.code);
33
+ }
34
+ if (entry.cols) {
35
+ columns = entry.cols.map(({ name }) => name);
36
+ }
37
+ if (entry.row) {
38
+ yield decodeBigInts(toRow(columns, entry.row.map((value) => decodeValue(value, true))));
31
39
  }
32
40
  }
33
- return rows();
34
41
  }
35
42
  async internalRelease() {
36
43
  await this.session.close();
37
44
  }
38
45
  }
46
+ /** A statement's result as the querier reads it, each row named by the statement's columns, wide integers decoded. */
47
+ function executionOf({ columns, rows, rowsAffected }) {
48
+ return { rows: rows.map((row) => decodeBigInts(toRow(columns, row))), changes: rowsAffected };
49
+ }
39
50
  /** A row the driver answers as an array of values, named by the statement's columns. */
40
51
  function toRow(columns, values) {
41
52
  return Object.fromEntries(columns.map((column, at) => [column, values[at]]));
@@ -1,4 +1,5 @@
1
1
  import type { EntityMeta, EntityPredicate, UpdatePayload } from './entity.js';
2
+ import type { EngineName } from './querier.js';
2
3
  import type { Query, QueryConflictPaths, QueryPage, QueryRenderOptions, QuerySearch, RelationQuery } from './query.js';
3
4
  import type { QueryAggMap, QueryAggregate, QueryAggregateOp, QueryGroupMap } from './queryAggregate.js';
4
5
  import type { QuerySqlRenderOptions } from './querySql.js';
@@ -311,6 +312,8 @@ export interface SqlQueryDialect {
311
312
  * declared once for a family rather than copied per member.
312
313
  */
313
314
  readonly dialectFamily: SqlDialectName;
315
+ /** The engine as a message names it. */
316
+ readonly engineName: EngineName;
314
317
  /**
315
318
  * the escape character for identifiers.
316
319
  */
@@ -29,6 +29,18 @@ export type TransactionOptions = {
29
29
  readonly readOnly?: boolean;
30
30
  };
31
31
  export type DialectName = SqlDialectName | 'mongodb';
32
+ /** Each engine as a message names it. Total, so a new engine says. */
33
+ export declare const ENGINE_NAMES: {
34
+ readonly postgres: 'PostgreSQL';
35
+ readonly cockroachdb: 'CockroachDB';
36
+ readonly mysql: 'MySQL';
37
+ readonly mariadb: 'MariaDB';
38
+ readonly mssql: 'SQL Server';
39
+ readonly sqlite: 'SQLite';
40
+ readonly mongodb: 'MongoDB';
41
+ };
42
+ /** An engine as a message names it: a dialect's, or a platform running one, as Cloudflare D1 runs SQLite and Neon Postgres. */
43
+ export type EngineName = (typeof ENGINE_NAMES)[DialectName] | 'Cloudflare D1' | 'Neon';
32
44
  /**
33
45
  * A projected read that takes the entity first or as the query's `$entity`. The `$entity` form comes
34
46
  * **first** on purpose: when no signature matches, TypeScript reports the error of the *last* one, so a
@@ -1,3 +1,13 @@
1
+ /** Each engine as a message names it. Total, so a new engine says. */
2
+ export const ENGINE_NAMES = {
3
+ postgres: 'PostgreSQL',
4
+ cockroachdb: 'CockroachDB',
5
+ mysql: 'MySQL',
6
+ mariadb: 'MariaDB',
7
+ mssql: 'SQL Server',
8
+ sqlite: 'SQLite',
9
+ mongodb: 'MongoDB',
10
+ };
1
11
  /**
2
12
  * Type guard to check if a querier supports raw SQL execution
3
13
  */
@@ -1,6 +1,7 @@
1
1
  import type { VectorCast } from '../dialect/vectorCast.js';
2
2
  import type { IndexType } from '../schema/types.js';
3
3
  import { UqlUsageError } from '../util/uqlError.js';
4
+ import type { EngineName } from './querier.js';
4
5
  /**
5
6
  * A vector search's metric: `cosine` (the default), `l2`, `inner` product or `l1`. No hamming: every
6
7
  * engine's takes a bit vector, which no field type maps to.
@@ -38,7 +39,7 @@ export type VectorMetric = {
38
39
  readonly index?: string;
39
40
  };
40
41
  /** The error every dialect throws for a metric it lacks. */
41
- export declare function unsupportedVectorMetric(dialectName: string, distance: VectorDistance, indexName?: string): UqlUsageError;
42
+ export declare function unsupportedVectorMetric(engine: EngineName, distance: VectorDistance, indexName?: string): UqlUsageError;
42
43
  /**
43
44
  * Vector-specific tuning options shared by `@Index` decorator, entity metadata, and migration schema.
44
45
  */
@@ -2,9 +2,9 @@ import { UqlUsageError } from '../util/uqlError.js';
2
2
  /** The keys that describe the search rather than bound it, so `$near`'s bounds are what is left. */
3
3
  export const VECTOR_QUERY_KEYS = ['$vector', '$distance'];
4
4
  /** The error every dialect throws for a metric it lacks. */
5
- export function unsupportedVectorMetric(dialectName, distance, indexName) {
5
+ export function unsupportedVectorMetric(engine, distance, indexName) {
6
6
  const where = indexName === undefined ? '' : ` (index "${indexName}")`;
7
- return new UqlUsageError(`${dialectName} does not support vector distance metric: ${distance}${where}`);
7
+ return new UqlUsageError(`${engine} does not support vector distance metric: ${distance}${where}`);
8
8
  }
9
9
  /** The metric a search or an index measures by where nothing names one: every engine with vectors has it. */
10
10
  export const DEFAULT_VECTOR_DISTANCE = 'cosine';
@@ -0,0 +1,11 @@
1
+ /** A value held for a flow: set for the length of a callback, read anywhere inside it. */
2
+ type Scope<T> = {
3
+ run<R>(value: T, callback: () => R): R;
4
+ get(): T | undefined;
5
+ };
6
+ /**
7
+ * A value held for the active async flow, across `await`s; in a browser, for a synchronous callback only, which
8
+ * is all it needs there, where filters never resolve.
9
+ */
10
+ export declare function asyncScope<T>(): Scope<T>;
11
+ export {};
@@ -0,0 +1,29 @@
1
+ /**
2
+ * The runtime's `AsyncLocalStorage`, read when the module loads rather than imported, so no bundler sees a Node
3
+ * builtin: Node, Bun, Deno and Workers (`nodejs_compat`) have it, a browser does not.
4
+ */
5
+ const RUNTIME_STORAGE = globalThis.process?.getBuiltinModule?.('node:async_hooks').AsyncLocalStorage;
6
+ /**
7
+ * A value held for the active async flow, across `await`s; in a browser, for a synchronous callback only, which
8
+ * is all it needs there, where filters never resolve.
9
+ */
10
+ export function asyncScope() {
11
+ if (RUNTIME_STORAGE) {
12
+ const store = new RUNTIME_STORAGE();
13
+ return { run: (value, callback) => store.run(value, callback), get: () => store.getStore() };
14
+ }
15
+ let current;
16
+ return {
17
+ run: (value, callback) => {
18
+ const previous = current;
19
+ current = value;
20
+ try {
21
+ return callback();
22
+ }
23
+ finally {
24
+ current = previous;
25
+ }
26
+ },
27
+ get: () => current,
28
+ };
29
+ }
@@ -1,5 +1,5 @@
1
1
  import type { IndexType } from '../schema/types.js';
2
- import { type AggregateCall, type CascadeType, type EntityData, type EntityIndexMeta, type EntityMeta, type FieldKey, type FieldOptions, type FieldUpdateOp, type JsonArrayUpdateOp, type JsonUpdateOp, type OnFieldCallback, type QueryAggMap, type QueryExclude, type QueryGroupMap, type QueryOptions, QuerySql, type QuerySearch, type QuerySelect, type QuerySelectValue, type QuerySortDirection, type QuerySizeComparisonOps, type QuerySortMap, type QueryTextSearchOptions, type QueryVectorQuery, type QueryVectorSearch, type QueryWhere, type RelationKey, type UpdatePayload, type VectorDistance } from '../type/index.js';
2
+ import { type AggregateCall, type CascadeType, type EntityData, type EntityIndexMeta, type EntityMeta, type FieldKey, type FieldOptions, type FieldUpdateOp, type JsonArrayUpdateOp, type JsonUpdateOp, type OnFieldCallback, type QueryAggMap, type QueryConflictPaths, type QueryExclude, type QueryGroupMap, type QueryOptions, QuerySql, type QuerySearch, type QuerySelect, type QuerySelectValue, type QuerySortDirection, type QuerySizeComparisonOps, type QuerySortMap, type QueryTextSearchOptions, type QueryVectorQuery, type QueryVectorSearch, type QueryWhere, type RelationKey, type UpdatePayload, type VectorDistance } from '../type/index.js';
3
3
  export type CallbackKey = keyof Pick<FieldOptions, 'onInsert' | 'onUpdate'>;
4
4
  /** The keys of `payload` a write persists as columns. */
5
5
  export declare function filterFieldKeys<E>(meta: EntityMeta<E>, payload: EntityData<E> | UpdatePayload<E>, callbackKey: CallbackKey): FieldKey<E>[];
@@ -15,11 +15,28 @@ export declare function insertShapeOf<E>(meta: EntityMeta<E>, record: EntityData
15
15
  */
16
16
  export declare function getInsertFieldKeys<E>(meta: EntityMeta<E>, payloads: EntityData<E>[]): FieldKey<E>[];
17
17
  export declare function getFieldCallbackValue(val: OnFieldCallback): string | number | bigint | boolean | Date | import("../type/utility.js").JsonBrand | QuerySql | readonly number[] | readonly import("../type/utility.js").JsonBrand[] | Uint8Array<ArrayBufferLike>;
18
+ /** A delete as {@link deletionOf} plans it. */
19
+ type Deletion<O> = {
20
+ readonly stamp?: {
21
+ readonly key: string;
22
+ readonly field: FieldOptions;
23
+ value(): unknown;
24
+ };
25
+ readonly opts: O;
26
+ };
27
+ /**
28
+ * How a delete of `meta` goes: a soft one stamps its field (`stamp`, whose `value()` the writer takes, so a
29
+ * callback runs only where a row is written), reading the rows as `opts` filters them; a hard one, asked for or on
30
+ * an entity with no soft-delete field, removes them, soft-deleted ones included.
31
+ */
32
+ export declare function deletionOf<E, O extends QueryOptions>(meta: EntityMeta<E>, opts: O): Deletion<O>;
33
+ /** What an upsert of `row` assigns a row it finds: the payload and the `onUpdate` fills, less its key and what it matched on. */
34
+ export declare function upsertAssigned<E>(meta: EntityMeta<E>, row: EntityData<E>, conflictPaths: QueryConflictPaths<E>): EntityData<E>;
18
35
  /**
19
- * Resolves the value stamped on the soft-delete field when deleting a row.
20
- * `true` stamps the current timestamp (`new Date()`); any other marker is an {@link OnFieldCallback}.
36
+ * Whether an upsert of `row` lands under the key it names: it names one and matches on it, so a row it finds
37
+ * has that key too. Elsewhere the key is the found row's, which the upsert reads back.
21
38
  */
22
- export declare function getSoftDeleteValue(field: FieldOptions): string | number | bigint | boolean | Date | import("../type/utility.js").JsonBrand | QuerySql | readonly number[] | readonly import("../type/utility.js").JsonBrand[] | Uint8Array<ArrayBufferLike>;
39
+ export declare function upsertKeepsOwnKey<E>(meta: EntityMeta<E>, conflictPaths: QueryConflictPaths<E>, row: E): boolean;
23
40
  /** Fills each field `callbackKey` generates on `payload` in place, where the caller left it unset. */
24
41
  export declare function fillOnFields<E, R extends EntityData<E> | UpdatePayload<E>>(meta: EntityMeta<E>, payload: R | R[], callbackKey: CallbackKey): R[];
25
42
  /** The relations a write cascades `action` to, in declaration order. */
@@ -100,8 +117,6 @@ export declare function isFieldUpdateOp(value: unknown): value is FieldUpdateOp;
100
117
  * reading one: their order would change the result, and an untyped payload is how both arrive.
101
118
  */
102
119
  export declare function fieldUpdateOf(key: string, value: FieldUpdateOp): [keyof FieldUpdateOp, number | bigint | QuerySql];
103
- /** Returns a `QueryOptions.filters` value with the built-in soft-delete filter disabled (used by hard delete). */
104
- export declare function withoutSoftDeleteFilter(filters: QueryOptions['filters']): QueryOptions['filters'];
105
120
  /**
106
121
  * `$where` with the entity's active filters merged in, against the ambient {@link UqlContext}. A convenience
107
122
  * filter yields to a `$where` on its key; a `security` one is always ANDed, from {@link securityConditions}.
@@ -1,8 +1,10 @@
1
1
  import { getContext } from '../context/context.js';
2
- import { QuerySql, resolveAggregateOp, SOFT_DELETE_FILTER, } from '../type/index.js';
2
+ import { namesKey } from '../entity/metadata/definition.js';
3
+ import { QuerySql, resolveAggregateOp, } from '../type/index.js';
3
4
  import { DEFAULT_VECTOR_DISTANCE, VECTOR_INDEX_TYPES } from '../type/vector.js';
4
5
  import { defaultReadKeys, fieldKeys, isDatabaseWritten, jsonKey, jsonPathKeys } from './field.util.js';
5
- import { entityName, getKeys, hasKeys, isJsonScalar, isOperatorObject, isRecord, someKey } from './object.util.js';
6
+ import { withDeleted } from './filters.util.js';
7
+ import { clone, entityName, getKeys, omitKeys, hasKeys, isJsonScalar, isOperatorObject, isRecord, someKey, } from './object.util.js';
6
8
  import { assertNoUndefined, whereAnd } from './query.util.js';
7
9
  import { UqlSecurityError, UqlUsageError } from './uqlError.js';
8
10
  /** The keys of `payload` a write persists as columns. */
@@ -56,12 +58,39 @@ export function getFieldCallbackValue(val) {
56
58
  return typeof val === 'function' ? val() : val;
57
59
  }
58
60
  /**
59
- * Resolves the value stamped on the soft-delete field when deleting a row.
60
- * `true` stamps the current timestamp (`new Date()`); any other marker is an {@link OnFieldCallback}.
61
+ * The value a soft delete stamps on `field`: `true` stamps the current timestamp (`new Date()`); any other marker
62
+ * is an {@link OnFieldCallback}.
61
63
  */
62
- export function getSoftDeleteValue(field) {
64
+ function softDeleteValue(field) {
63
65
  return field.softDelete === true ? new Date() : getFieldCallbackValue(field.softDelete);
64
66
  }
67
+ /**
68
+ * How a delete of `meta` goes: a soft one stamps its field (`stamp`, whose `value()` the writer takes, so a
69
+ * callback runs only where a row is written), reading the rows as `opts` filters them; a hard one, asked for or on
70
+ * an entity with no soft-delete field, removes them, soft-deleted ones included.
71
+ */
72
+ export function deletionOf(meta, opts) {
73
+ const key = opts.hardDelete ? undefined : meta.softDelete;
74
+ const field = key === undefined ? undefined : meta.fields[key];
75
+ if (key === undefined || !field) {
76
+ return { opts: withDeleted(opts) };
77
+ }
78
+ return { stamp: { key, field, value: () => softDeleteValue(field) }, opts };
79
+ }
80
+ /** What an upsert of `row` assigns a row it finds: the payload and the `onUpdate` fills, less its key and what it matched on. */
81
+ export function upsertAssigned(meta, row, conflictPaths) {
82
+ const [updated] = fillOnFields(meta, clone(row), 'onUpdate');
83
+ const kept = [...meta.ids, ...getKeys(conflictPaths)];
84
+ const assigned = filterFieldKeys(meta, updated, 'onUpdate');
85
+ return omitKeys(updated, getKeys(updated).filter((key) => kept.includes(key) || !assigned.includes(key)));
86
+ }
87
+ /**
88
+ * Whether an upsert of `row` lands under the key it names: it names one and matches on it, so a row it finds
89
+ * has that key too. Elsewhere the key is the found row's, which the upsert reads back.
90
+ */
91
+ export function upsertKeepsOwnKey(meta, conflictPaths, row) {
92
+ return namesKey(meta, row) && meta.ids.every((key) => Object.hasOwn(conflictPaths, key));
93
+ }
65
94
  /** Fills each field `callbackKey` generates on `payload` in place, where the caller left it unset. */
66
95
  export function fillOnFields(meta, payload, callbackKey) {
67
96
  const payloads = Array.isArray(payload) ? payload : [payload];
@@ -383,10 +412,6 @@ export function fieldUpdateOf(key, value) {
383
412
  }
384
413
  return value.$inc === undefined ? ['$mul', value.$mul] : ['$inc', value.$inc];
385
414
  }
386
- /** Returns a `QueryOptions.filters` value with the built-in soft-delete filter disabled (used by hard delete). */
387
- export function withoutSoftDeleteFilter(filters) {
388
- return filters === false ? false : { ...filters, [SOFT_DELETE_FILTER]: false };
389
- }
390
415
  /**
391
416
  * `$where` with the entity's active filters merged in, against the ambient {@link UqlContext}. A convenience
392
417
  * filter yields to a `$where` on its key; a `security` one is always ANDed, from {@link securityConditions}.
@@ -1,7 +1,8 @@
1
- import type { QueryOptions } from '../type/index.js';
1
+ import { type QueryOptions } from '../type/index.js';
2
2
  /**
3
- * Options including soft-deleted rows, server-side only. To list only deleted ones over the wire, filter
4
- * the field: `{ $where: { deletedAt: { $ne: null } } }`.
3
+ * `opts`, or none, reaching soft-deleted rows too, server-side only. To list only deleted ones over the wire,
4
+ * filter the field: `{ $where: { deletedAt: { $ne: null } } }`.
5
5
  * @example `querier.findMany(User, {}, withDeleted())`
6
6
  */
7
- export declare function withDeleted(): QueryOptions;
7
+ export declare function withDeleted<O extends QueryOptions>(opts: O): O;
8
+ export declare function withDeleted(opts?: QueryOptions): QueryOptions;
@@ -1,8 +1,5 @@
1
- /**
2
- * Options including soft-deleted rows, server-side only. To list only deleted ones over the wire, filter
3
- * the field: `{ $where: { deletedAt: { $ne: null } } }`.
4
- * @example `querier.findMany(User, {}, withDeleted())`
5
- */
6
- export function withDeleted() {
7
- return { filters: { softDelete: false } };
1
+ import { SOFT_DELETE_FILTER } from '../type/index.js';
2
+ export function withDeleted(opts = {}) {
3
+ const { filters } = opts;
4
+ return { ...opts, filters: filters === false ? false : { ...filters, [SOFT_DELETE_FILTER]: false } };
8
5
  }
@@ -1,3 +1,4 @@
1
+ import { cachedIn } from './object.util.js';
1
2
  const DEFAULT_LOG_LEVELS = [
2
3
  'query',
3
4
  'info',
@@ -147,12 +148,7 @@ export function queryLoggerFor(extra) {
147
148
  unconfigured ??= new LoggerWrapper();
148
149
  return unconfigured;
149
150
  }
150
- let wrapper = wrappersByOptions.get(extra);
151
- if (!wrapper) {
152
- wrapper = new LoggerWrapper(extra.logger, { logValues: extra.logValues, slowQuery: extra.slowQuery });
153
- wrappersByOptions.set(extra, wrapper);
154
- }
155
- return wrapper;
151
+ return cachedIn(wrappersByOptions, extra, () => new LoggerWrapper(extra.logger, { logValues: extra.logValues, slowQuery: extra.slowQuery }));
156
152
  }
157
153
  /**
158
154
  * Logs a pool's dropped connection, which some drivers would otherwise crash the process on, through
@@ -17,6 +17,13 @@ export declare function isOperatorKey(key: string): boolean;
17
17
  export declare function isOperatorObject(value: unknown): value is Record<string, unknown>;
18
18
  /** Whether `value` is an object that is not an array, whose keys can be read. */
19
19
  export declare function isRecord(value: unknown): value is Record<string, unknown>;
20
+ /** A shallow copy of `value` without `keys`. */
21
+ export declare function omitKeys<T extends object>(value: T, keys: Iterable<string>): T;
22
+ /** The value `cache` holds for `key`, computed and held the first time it is asked for. */
23
+ export declare function cachedIn<K, V>(cache: {
24
+ get(key: K): V | undefined;
25
+ set(key: K, value: V): unknown;
26
+ }, key: K, compute: () => V): V;
20
27
  export declare function getKeys<T extends object>(obj: T | null | undefined): (keyof T & string)[];
21
28
  /** The entries of `record` holding a value: a key declared but left `undefined` is no entry at all. */
22
29
  export declare function definedEntries<K extends string, V>(record: Partial<Record<K, V>>): [K, V][];
@@ -53,6 +53,23 @@ export function isOperatorObject(value) {
53
53
  export function isRecord(value) {
54
54
  return value !== null && typeof value === 'object' && !Array.isArray(value);
55
55
  }
56
+ /** A shallow copy of `value` without `keys`. */
57
+ export function omitKeys(value, keys) {
58
+ const copy = { ...value };
59
+ for (const key of keys) {
60
+ Reflect.deleteProperty(copy, key);
61
+ }
62
+ return copy;
63
+ }
64
+ /** The value `cache` holds for `key`, computed and held the first time it is asked for. */
65
+ export function cachedIn(cache, key, compute) {
66
+ let value = cache.get(key);
67
+ if (value === undefined) {
68
+ value = compute();
69
+ cache.set(key, value);
70
+ }
71
+ return value;
72
+ }
56
73
  export function getKeys(obj) {
57
74
  return obj ? Object.keys(obj) : [];
58
75
  }
@@ -1,4 +1,5 @@
1
- import type { EntityData, EntityId, EntityMeta, FieldKey, Query, QueryConflictPaths, QuerySearch, QuerySortDirection, QuerySortMap, QueryWhere, QueryWhereArray } from '../type/index.js';
1
+ import { type KeyedRow } from '../entity/metadata/definition.js';
2
+ import type { EntityId, EntityMeta, FieldKey, Query, QueryConflictPaths, QuerySearch, QuerySortDirection, QuerySortMap, QueryWhere, QueryWhereArray } from '../type/index.js';
2
3
  /**
3
4
  * Maps each of `keys` to `true`, the shape of a `$select` or conflict paths. This and the builders below hold
4
5
  * the casts generic code needs to build a statement: the compiler types these maps per entity, so it does not
@@ -10,7 +11,7 @@ export declare function whereWith<E>(key: FieldKey<E>, value: unknown, where?: Q
10
11
  export declare function whereEach<E>(keys: readonly FieldKey<E>[], valueOf: (key: FieldKey<E>) => unknown): QueryWhere<E>;
11
12
  export declare function whereAnyOf<E>(clauses: QueryWhereArray<E>): QueryWhere<E>;
12
13
  /** The rows matching one of `rows` on `keys`: one list where a single key names them, an alternative each where several do. */
13
- export declare function whereKeysIn<E>(keys: readonly FieldKey<E>[], rows: readonly EntityData<E>[]): QueryWhere<E>;
14
+ export declare function whereKeysIn<E>(keys: readonly FieldKey<E>[], rows: readonly KeyedRow<E>[]): QueryWhere<E>;
14
15
  /** A `$sort` from `[key, direction]` pairs, sorting by the keys in the order given. */
15
16
  export declare function sortOf<E>(entries: readonly (readonly [FieldKey<E>, QuerySortDirection])[]): QuerySortMap<E>;
16
17
  /**
package/dist/util/sql.js CHANGED
@@ -60,7 +60,7 @@ function sqlValue(name) {
60
60
  return sql(({ dialect }) => {
61
61
  const statement = dialect.sqlValues[name];
62
62
  if (statement === undefined) {
63
- throw new UqlUsageError(`${dialect.dialectName} has no ${name}; write it as raw SQL this engine accepts`);
63
+ throw new UqlUsageError(`${dialect.engineName} has no ${name}; write it as raw SQL this engine accepts`);
64
64
  }
65
65
  return statement;
66
66
  });