uql-orm 0.102.7 → 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.
@@ -1,11 +1,11 @@
1
- import { Pool, type PoolClient, type PoolConfig } from 'pg';
1
+ import { Pool, type PoolConfig } from 'pg';
2
2
  import { AbstractPgQuerierPool } from '../postgres/abstractPgQuerierPool.js';
3
3
  import type { ExtraOptions } from '../type/index.js';
4
4
  import { CockroachDialect } from './cockroachDialect.js';
5
5
  /**
6
6
  * QuerierPool for CockroachDB using the `pg` driver Pool.
7
7
  */
8
- export declare class CrdbQuerierPool extends AbstractPgQuerierPool<PoolClient, CockroachDialect> {
8
+ export declare class CrdbQuerierPool extends AbstractPgQuerierPool<CockroachDialect> {
9
9
  readonly pool: Pool;
10
10
  constructor(opts: PoolConfig, extra?: ExtraOptions);
11
11
  }
@@ -1,12 +1,6 @@
1
1
  import type { UqlContext } from '../type/index.js';
2
- /** A value held for the active async flow, across `await`s: the browser build keeps it for synchronous callbacks only. */
3
- export declare function asyncScope<T>(): {
4
- run<R>(value: T, callback: () => R): R;
5
- get(): T | undefined;
6
- };
7
2
  /**
8
3
  * Runs `callback` with a {@link UqlContext} parameterized filters read, across `await`s and transactions.
9
- * The browser build keeps the API without `node:async_hooks`.
10
4
  * @example `await withContext({ tenantId }, () => querier.findMany(Invoice, {}))`
11
5
  */
12
6
  export declare function withContext<T>(context: UqlContext, callback: () => T): T;
@@ -1,14 +1,8 @@
1
- import { AsyncLocalStorage } from 'node:async_hooks';
2
- /** A value held for the active async flow, across `await`s: the browser build keeps it for synchronous callbacks only. */
3
- export function asyncScope() {
4
- const storage = new AsyncLocalStorage();
5
- return { run: (value, callback) => storage.run(value, callback), get: () => storage.getStore() };
6
- }
1
+ import { asyncScope } from '../util/asyncScope.js';
7
2
  /** Holds the current {@link UqlContext} for the active async flow (per request/transaction). */
8
3
  const contextScope = asyncScope();
9
4
  /**
10
5
  * Runs `callback` with a {@link UqlContext} parameterized filters read, across `await`s and transactions.
11
- * The browser build keeps the API without `node:async_hooks`.
12
6
  * @example `await withContext({ tenantId }, () => querier.findMany(Invoice, {}))`
13
7
  */
14
8
  export function withContext(context, callback) {
@@ -10,5 +10,4 @@ export declare class D1QuerierPool extends AbstractSqlQuerierPool<D1Querier, D1S
10
10
  readonly db: D1Queryable;
11
11
  constructor(db: D1Queryable, extra?: ExtraOptions);
12
12
  getQuerier(): Promise<D1Querier>;
13
- end(): Promise<void>;
14
13
  }
@@ -15,5 +15,4 @@ export class D1QuerierPool extends AbstractSqlQuerierPool {
15
15
  async getQuerier() {
16
16
  return new D1Querier(this.db, this.dialect, this.extra);
17
17
  }
18
- async end() { }
19
18
  }
@@ -160,7 +160,7 @@ export declare abstract class AbstractSqlDialect extends VectorSqlDialect implem
160
160
  */
161
161
  normalizeValue(value: unknown): unknown;
162
162
  placeholder(_index: number): string;
163
- /** `RETURNING <id column> id`, or nothing on a composite key, whose every column the payload already names. */
163
+ /** `RETURNING <id column>` as {@link RETURNED_ID}, or nothing on a composite key, whose every column the payload already names. */
164
164
  returningId<E>(meta: EntityMeta<E>): string;
165
165
  /**
166
166
  * ` RETURNING` the fields `keys` names, after an `UPDATE` or `DELETE` this context holds, projected and read as
@@ -169,7 +169,7 @@ export declare abstract class AbstractSqlDialect extends VectorSqlDialect implem
169
169
  returning<E>(ctx: QueryContext, entity: Type<E>, keys: readonly FieldKey<E>[]): readonly SelectTerm[];
170
170
  /** What the returned row is read off, for an engine that names it: SQL Server's `INSERTED.`. */
171
171
  protected readonly returnedRowPrefix: string;
172
- /** `<id column> AS id` on its own, for a statement composing a `RETURNING` list of several items. */
172
+ /** `<id column> AS` {@link RETURNED_ID} on its own, for a statement composing a `RETURNING` list of several items. */
173
173
  protected returningIdExpression<E>(meta: EntityMeta<E>): string;
174
174
  search<E>(ctx: QueryContext, entity: Type<E>, q?: Query<E>, opts?: ReadOptions, joins?: QueryJoins, order?: readonly SortRef[]): void;
175
175
  /**
@@ -3,7 +3,7 @@ import { soleId, valueFieldOf } from '../entity/metadata/definition.js';
3
3
  import { COUNT_RESULT_KEY, parseQueryLock, QuerySql, RAW_ALIAS, } from '../type/index.js';
4
4
  import { utcTimestamp } from '../util/date.js';
5
5
  import { ancestorPaths, isExactDecimal, isInlinedExpression, jsonPathKeys } from '../util/field.util.js';
6
- import { isAutoIncrement, isSelectList, assertNonNegativeInteger, assertNoUndefined, assertWhere, definedEntries, escapeSqlId, fillOnFields, filterFieldKeys, getInsertFieldKeys, getKeys, getRelationRequestSummary, deletionOf, hasKeys, idOnlyQuery, keySet, whereAnd, columnFamily, fieldFamily, countedRelations, fieldUpdateOf, fulltextIndexOver, fulltextWeights, isFieldUpdateOp, isJsonObject, isJsonUpdateOp, foldJson, writesKeys, isOperatorMap, isOperatorKey, isVectorSearch, normalizeScalarFieldSelection, parentJoins, rankedTextSearch, targetJoins, textSearchFields, textSortOf, textWeightSteps, parseGroupMap, parseRelationAtKey, parseRelationSize, parseSortDirection, populatesRelations, aggregateOf, sql, refs, columnRef, throwUnknownAggregateColumn, upsertAssigned, } from '../util/index.js';
6
+ import { isAutoIncrement, RETURNED_ID, isSelectList, assertNonNegativeInteger, assertNoUndefined, assertWhere, definedEntries, escapeSqlId, fillOnFields, filterFieldKeys, getInsertFieldKeys, getKeys, getRelationRequestSummary, deletionOf, hasKeys, idOnlyQuery, keySet, whereAnd, columnFamily, fieldFamily, countedRelations, fieldUpdateOf, fulltextIndexOver, fulltextWeights, isFieldUpdateOp, isJsonObject, isJsonUpdateOp, foldJson, writesKeys, isOperatorMap, isOperatorKey, isVectorSearch, normalizeScalarFieldSelection, parentJoins, rankedTextSearch, targetJoins, textSearchFields, textSortOf, textWeightSteps, parseGroupMap, parseRelationAtKey, parseRelationSize, parseSortDirection, populatesRelations, aggregateOf, sql, refs, columnRef, throwUnknownAggregateColumn, upsertAssigned, } from '../util/index.js';
7
7
  import { cachedIn, isJsonScalar } from '../util/object.util.js';
8
8
  import { escapeAnsiSqlLiteral } from '../util/sqlLiteral.js';
9
9
  import { kindOf, UqlUsageError } from '../util/uqlError.js';
@@ -207,7 +207,7 @@ export class AbstractSqlDialect extends VectorSqlDialect {
207
207
  placeholder(_index) {
208
208
  return '?';
209
209
  }
210
- /** `RETURNING <id column> id`, or nothing on a composite key, whose every column the payload already names. */
210
+ /** `RETURNING <id column>` as {@link RETURNED_ID}, or nothing on a composite key, whose every column the payload already names. */
211
211
  returningId(meta) {
212
212
  const expression = this.returningIdExpression(meta);
213
213
  return expression ? `RETURNING ${expression}` : '';
@@ -223,11 +223,11 @@ export class AbstractSqlDialect extends VectorSqlDialect {
223
223
  }
224
224
  /** What the returned row is read off, for an engine that names it: SQL Server's `INSERTED.`. */
225
225
  returnedRowPrefix = '';
226
- /** `<id column> AS id` on its own, for a statement composing a `RETURNING` list of several items. */
226
+ /** `<id column> AS` {@link RETURNED_ID} on its own, for a statement composing a `RETURNING` list of several items. */
227
227
  returningIdExpression(meta) {
228
228
  const [idKey] = meta.ids;
229
229
  return meta.ids.length === 1
230
- ? `${this.returnedRowPrefix}${this.escapedColumnName(meta, idKey)} ${this.escapeId('id')}`
230
+ ? `${this.returnedRowPrefix}${this.escapedColumnName(meta, idKey)} ${this.escapeId(RETURNED_ID)}`
231
231
  : '';
232
232
  }
233
233
  search(ctx, entity, q = {}, opts = {}, joins = NO_JOINS, order) {
@@ -10,7 +10,7 @@ import { QuerySql } from '../type/index.js';
10
10
  import { parseQueryLock } from '../type/index.js';
11
11
  import { bytesToHex } from '../util/bytes.js';
12
12
  import { isAutoIncrement, isExactDecimal, jsonPathKeys } from '../util/field.util.js';
13
- import { assertNonNegativeInteger, isOperatorMap } from '../util/index.js';
13
+ import { assertNonNegativeInteger, isOperatorMap, RETURNED_ID } from '../util/index.js';
14
14
  import { escapeSingleQuotes } from '../util/sqlLiteral.js';
15
15
  import { UqlUsageError } from '../util/uqlError.js';
16
16
  /** What SQL Server has. */
@@ -206,7 +206,7 @@ export class MsSqlDialect extends MergeSqlDialect {
206
206
  */
207
207
  writeRows(ctx, meta, payload, write) {
208
208
  const id = soleId(meta);
209
- const column = this.escapeId('id');
209
+ const column = this.escapeId(RETURNED_ID);
210
210
  const identity = this.identityInsertTarget(meta, payload);
211
211
  if (id) {
212
212
  ctx.append(`DECLARE ${OUTPUT_TABLE} TABLE (${column} ${canonicalToSql(resolveColumnCanonicalType(id.field), this)}); `);
@@ -1,21 +1,21 @@
1
- import type { CustomTypesConfig, NeonQueryFunction, PoolClient } from '@neondatabase/serverless';
2
- import { PgQuerier } from '../postgres/pgQuerier.js';
1
+ import { type PgAnyClient, PgQuerier } from '../postgres/pgQuerier.js';
3
2
  import type { BoundStatement } from '../querier/index.js';
4
3
  import type { ExtraOptions, TransactionOptions } from '../type/index.js';
5
4
  import type { SqlExecution } from '../util/sql.util.js';
6
5
  import type { NeonDialect } from './neonDialect.js';
7
- /** Neon's HTTP query function, answering each statement's whole result: what a statement goes through outside a session. */
8
- export type NeonHttp = NeonQueryFunction<false, true>;
6
+ /** Neon over HTTP, what a statement goes through outside a session: one statement, or a list as one transaction. */
7
+ export type NeonHttp = {
8
+ query(sql: string, values?: unknown[]): Promise<SqlExecution>;
9
+ transaction(statements: readonly BoundStatement[]): Promise<SqlExecution[]>;
10
+ };
9
11
  /**
10
12
  * Querier for Neon, over HTTP first: a statement is one request, and a list one request running it as a
11
- * transaction. A WebSocket session, taken from the pool for what one request cannot hold (a transaction a
12
- * callback runs in, a stream's loop), serves the querier until it is released. Every query passes the pool's
13
- * `types` itself, since `neon()` ignores them, so a row decodes as it does over the session.
13
+ * transaction. A WebSocket session, opened for what one request cannot hold (a transaction a callback runs in, a
14
+ * stream's loop), serves the querier until it is released.
14
15
  */
15
- export declare class NeonQuerier extends PgQuerier<PoolClient> {
16
+ export declare class NeonQuerier extends PgQuerier {
16
17
  private readonly http;
17
- private readonly types;
18
- constructor(http: NeonHttp, types: CustomTypesConfig, connect: () => Promise<PoolClient>, dialect: NeonDialect, extra?: ExtraOptions);
18
+ constructor(http: NeonHttp, connect: () => Promise<PgAnyClient>, dialect: NeonDialect, extra?: ExtraOptions);
19
19
  /** Connects nothing: a statement goes over HTTP until a session holds the connection. */
20
20
  protected lazyConnect(): Promise<void>;
21
21
  protected execute(sql: string, values?: unknown[]): Promise<SqlExecution>;
@@ -1,18 +1,14 @@
1
- import { pgExecution } from '../postgres/pgExecution.js';
2
1
  import { PgQuerier } from '../postgres/pgQuerier.js';
3
2
  /**
4
3
  * Querier for Neon, over HTTP first: a statement is one request, and a list one request running it as a
5
- * transaction. A WebSocket session, taken from the pool for what one request cannot hold (a transaction a
6
- * callback runs in, a stream's loop), serves the querier until it is released. Every query passes the pool's
7
- * `types` itself, since `neon()` ignores them, so a row decodes as it does over the session.
4
+ * transaction. A WebSocket session, opened for what one request cannot hold (a transaction a callback runs in, a
5
+ * stream's loop), serves the querier until it is released.
8
6
  */
9
7
  export class NeonQuerier extends PgQuerier {
10
8
  http;
11
- types;
12
- constructor(http, types, connect, dialect, extra) {
9
+ constructor(http, connect, dialect, extra) {
13
10
  super(connect, dialect, extra);
14
11
  this.http = http;
15
- this.types = types;
16
12
  }
17
13
  /** Connects nothing: a statement goes over HTTP until a session holds the connection. */
18
14
  async lazyConnect() {
@@ -22,7 +18,7 @@ export class NeonQuerier extends PgQuerier {
22
18
  if (this.conn) {
23
19
  return super.execute(sql, values);
24
20
  }
25
- return pgExecution(await this.http.query(sql, values, { types: this.types }));
21
+ return this.http.query(sql, values);
26
22
  }
27
23
  /** A list as one HTTP transaction, all or none; inside an open transaction, in turn on its session, which it joins. */
28
24
  async executeBatch(statements) {
@@ -33,8 +29,7 @@ export class NeonQuerier extends PgQuerier {
33
29
  }
34
30
  return results;
35
31
  }
36
- const results = await this.http.transaction(statements.map(({ sql, values }) => this.http.query(sql, values, { types: this.types })));
37
- return results.map(pgExecution);
32
+ return this.http.transaction(statements);
38
33
  }
39
34
  async openTransaction(opts) {
40
35
  await super.lazyConnect();
@@ -1,18 +1,18 @@
1
- import { Pool, type PoolClient, type PoolConfig } from '@neondatabase/serverless';
2
- import { AbstractPgQuerierPool } from '../postgres/abstractPgQuerierPool.js';
1
+ import { type ClientConfig } from '@neondatabase/serverless';
3
2
  import { PgQuerier } from '../postgres/pgQuerier.js';
3
+ import { AbstractSqlQuerierPool } from '../querier/index.js';
4
4
  import type { ExtraOptions } from '../type/index.js';
5
5
  import { NeonDialect } from './neonDialect.js';
6
6
  import { NeonQuerier } from './neonQuerier.js';
7
7
  /**
8
- * Pool for Neon, over HTTP first: its queriers send statements and lists over HTTP, taking a WebSocket session
9
- * from its `pool` only for a transaction or a stream. A migration runs on a session throughout, since its lock
10
- * is the session's. [The design](../../../../architecture/split-writes.md).
8
+ * Pool for Neon that holds no connection: its queriers send statements and lists over HTTP, and open a WebSocket
9
+ * session of their own only for a transaction or a stream, which their release ends. So one pool serves every
10
+ * request of an edge isolate. A migration runs on a session throughout, since its lock is the session's.
11
+ * [The design](../../../../architecture/split-writes.md).
11
12
  */
12
- export declare class NeonQuerierPool extends AbstractPgQuerierPool<PoolClient, NeonDialect> {
13
+ export declare class NeonQuerierPool extends AbstractSqlQuerierPool<PgQuerier, NeonDialect> {
13
14
  #private;
14
- readonly pool: Pool;
15
- constructor(opts: PoolConfig, extra?: ExtraOptions);
15
+ constructor(opts: ClientConfig, extra?: ExtraOptions);
16
16
  getQuerier(): Promise<NeonQuerier>;
17
- getMigrationQuerier(): Promise<PgQuerier<PoolClient>>;
17
+ getMigrationQuerier(): Promise<PgQuerier>;
18
18
  }
@@ -1,30 +1,54 @@
1
- import { neon, Pool, types } from '@neondatabase/serverless';
1
+ import { Client, neon, types } from '@neondatabase/serverless';
2
2
  import { dialectOptionsFrom } from '../dialect/abstractDialect.js';
3
- import { AbstractPgQuerierPool } from '../postgres/abstractPgQuerierPool.js';
3
+ import { pgExecution } from '../postgres/pgExecution.js';
4
4
  import { PgQuerier } from '../postgres/pgQuerier.js';
5
5
  import { wireTypes } from '../postgres/pgWireTypes.js';
6
+ import { AbstractSqlQuerierPool } from '../querier/index.js';
6
7
  import { NeonDialect } from './neonDialect.js';
7
8
  import { NeonQuerier } from './neonQuerier.js';
9
+ const ignoreError = () => { };
8
10
  /**
9
- * Pool for Neon, over HTTP first: its queriers send statements and lists over HTTP, taking a WebSocket session
10
- * from its `pool` only for a transaction or a stream. A migration runs on a session throughout, since its lock
11
- * is the session's. [The design](../../../../architecture/split-writes.md).
11
+ * A WebSocket session of one querier's own, ended where a pooled client would be handed back. A socket error while
12
+ * it closes is heard and dropped, as `pg-pool` hears one on a client it holds, rather than reaching no listener.
12
13
  */
13
- export class NeonQuerierPool extends AbstractPgQuerierPool {
14
+ class NeonSession extends Client {
15
+ release() {
16
+ this.on('error', ignoreError);
17
+ return this.end();
18
+ }
19
+ }
20
+ /**
21
+ * Pool for Neon that holds no connection: its queriers send statements and lists over HTTP, and open a WebSocket
22
+ * session of their own only for a transaction or a stream, which their release ends. So one pool serves every
23
+ * request of an edge isolate. A migration runs on a session throughout, since its lock is the session's.
24
+ * [The design](../../../../architecture/split-writes.md).
25
+ */
26
+ export class NeonQuerierPool extends AbstractSqlQuerierPool {
14
27
  #http;
15
- #types;
28
+ #config;
16
29
  constructor(opts, extra) {
30
+ super(new NeonDialect(dialectOptionsFrom(extra)), extra);
17
31
  // Neon's own `types`, not `pg`'s: this entry has to load on an edge runtime where `pg` is absent.
18
32
  const wire = opts.types ?? wireTypes(types);
19
- super(new NeonDialect(dialectOptionsFrom(extra)), new Pool({ ...opts, types: wire }), extra);
33
+ this.#config = { ...opts, types: wire };
20
34
  const { connectionString, host, port, user, password, database } = opts;
21
- this.#http = neon({ connectionString, host, port, user, password, database, fullResults: true });
22
- this.#types = wire;
35
+ const http = neon({ connectionString, host, port, user, password, database, fullResults: true });
36
+ // Each query passes the wire types itself, since `neon()` ignores them, so a row decodes as over a session.
37
+ const query = (sql, values) => http.query(sql, values, { types: wire });
38
+ this.#http = {
39
+ query: async (sql, values) => pgExecution(await query(sql, values)),
40
+ transaction: async (statements) => (await http.transaction(statements.map(({ sql, values }) => query(sql, values)))).map(pgExecution),
41
+ };
23
42
  }
24
43
  async getQuerier() {
25
- return new NeonQuerier(this.#http, this.#types, () => this.pool.connect(), this.dialect, this.extra);
44
+ return new NeonQuerier(this.#http, () => this.#session(), this.dialect, this.extra);
26
45
  }
27
46
  async getMigrationQuerier() {
28
- return new PgQuerier(() => this.pool.connect(), this.dialect, this.extra);
47
+ return new PgQuerier(() => this.#session(), this.dialect, this.extra);
48
+ }
49
+ async #session() {
50
+ const session = new NeonSession(this.#config);
51
+ await session.connect();
52
+ return session;
29
53
  }
30
54
  }
@@ -2,15 +2,15 @@ import type { AbstractSqlDialect } from '../dialect/index.js';
2
2
  import { AbstractSqlQuerierPool } from '../querier/index.js';
3
3
  import type { ExtraOptions } from '../type/index.js';
4
4
  import { type PgAnyClient, PgQuerier } from './pgQuerier.js';
5
- export interface PgAnyPool<C extends PgAnyClient> {
6
- connect: () => Promise<C>;
5
+ export interface PgAnyPool {
6
+ connect: () => Promise<PgAnyClient>;
7
7
  end: () => Promise<void>;
8
8
  on(event: 'error', listener: (err: Error) => void): unknown;
9
9
  }
10
10
  /** A Postgres-wire pool of {@link PgQuerier}s, attaching the error handler that keeps a dropped connection from crashing the process. */
11
- export declare abstract class AbstractPgQuerierPool<C extends PgAnyClient, D extends AbstractSqlDialect> extends AbstractSqlQuerierPool<PgQuerier<C>, D> {
12
- readonly pool: PgAnyPool<C>;
13
- constructor(dialect: D, pool: PgAnyPool<C>, extra?: ExtraOptions);
14
- getQuerier(): Promise<PgQuerier<C>>;
11
+ export declare abstract class AbstractPgQuerierPool<D extends AbstractSqlDialect> extends AbstractSqlQuerierPool<PgQuerier, D> {
12
+ readonly pool: PgAnyPool;
13
+ constructor(dialect: D, pool: PgAnyPool, extra?: ExtraOptions);
14
+ getQuerier(): Promise<PgQuerier>;
15
15
  end(): Promise<void>;
16
16
  }
@@ -11,15 +11,15 @@ export interface PgAnyClient {
11
11
  }
12
12
  /**
13
13
  * Querier for every client with node-postgres' API: `pg` itself, for Postgres and CockroachDB, and
14
- * Neon's serverless driver. Generic over the client alone - the dialect is whichever the pool built.
14
+ * Neon's serverless driver; the dialect is whichever the pool built.
15
15
  */
16
- export declare class PgQuerier<C extends PgAnyClient = PgAnyClient> extends AbstractPoolQuerier<C> {
16
+ export declare class PgQuerier extends AbstractPoolQuerier<PgAnyClient> {
17
17
  /**
18
18
  * A client the server drops while held emits `error` with no statement to report it to, which unheard ends
19
- * the process: the querier hears it while it holds the client, `pg-pool` while it idles, never both at once.
19
+ * the process: the querier hears it while it holds the client, and what it hands the client back to after it.
20
20
  */
21
- protected acquired(conn: C): C;
21
+ protected acquired(conn: PgAnyClient): PgAnyClient;
22
22
  protected execute(sql: string, values?: unknown[]): Promise<import("../util/sql.util.js").SqlExecution>;
23
23
  internalStream(query: string, values?: unknown[]): AsyncGenerator<RawRow, void, any>;
24
- protected releaseConn(conn: C, discard: boolean): Promise<void>;
24
+ protected releaseConn(conn: PgAnyClient, discard: boolean): Promise<void>;
25
25
  }
@@ -3,12 +3,12 @@ import { pgExecution } from './pgExecution.js';
3
3
  const ignoreError = () => { };
4
4
  /**
5
5
  * Querier for every client with node-postgres' API: `pg` itself, for Postgres and CockroachDB, and
6
- * Neon's serverless driver. Generic over the client alone - the dialect is whichever the pool built.
6
+ * Neon's serverless driver; the dialect is whichever the pool built.
7
7
  */
8
8
  export class PgQuerier extends AbstractPoolQuerier {
9
9
  /**
10
10
  * A client the server drops while held emits `error` with no statement to report it to, which unheard ends
11
- * the process: the querier hears it while it holds the client, `pg-pool` while it idles, never both at once.
11
+ * the process: the querier hears it while it holds the client, and what it hands the client back to after it.
12
12
  */
13
13
  acquired(conn) {
14
14
  conn.on('error', ignoreError);
@@ -1,8 +1,8 @@
1
- import { Pool, type PoolClient, type PoolConfig } from 'pg';
1
+ import { Pool, type PoolConfig } from 'pg';
2
2
  import type { ExtraOptions } from '../type/index.js';
3
3
  import { AbstractPgQuerierPool } from './abstractPgQuerierPool.js';
4
4
  import { PostgresDialect } from './postgresDialect.js';
5
- export declare class PgQuerierPool extends AbstractPgQuerierPool<PoolClient, PostgresDialect> {
5
+ export declare class PgQuerierPool extends AbstractPgQuerierPool<PostgresDialect> {
6
6
  readonly pool: Pool;
7
7
  constructor(opts: PoolConfig, extra?: ExtraOptions);
8
8
  }
@@ -50,8 +50,6 @@ export declare abstract class AbstractQuerierPool<Q extends Querier, D extends A
50
50
  readonly deleteMany: UniversalQuerier['deleteMany'];
51
51
  readonly restoreOneById: UniversalQuerier['restoreOneById'];
52
52
  readonly restoreMany: UniversalQuerier['restoreMany'];
53
- /**
54
- * end the pool.
55
- */
56
- abstract end(): Promise<void>;
53
+ /** Closes what the pool holds: nothing where each querier closes its own connection, or there is none to close. */
54
+ end(): Promise<void>;
57
55
  }
@@ -142,4 +142,6 @@ export class AbstractQuerierPool {
142
142
  deleteMany = (...args) => this.withQuerier((querier) => querier.deleteMany(...args));
143
143
  restoreOneById = (...args) => this.withQuerier((querier) => querier.restoreOneById(...args));
144
144
  restoreMany = (...args) => this.withQuerier((querier) => querier.restoreMany(...args));
145
+ /** Closes what the pool holds: nothing where each querier closes its own connection, or there is none to close. */
146
+ async end() { }
145
147
  }
@@ -55,12 +55,10 @@ export declare abstract class AbstractSqlQuerier extends AbstractQuerier impleme
55
55
  private rowsOf;
56
56
  /** What the write `build` writes reports. */
57
57
  private changesOf;
58
- /**
59
- * The `SET`s tuning an ANN index for the query, leading its read, refused where they would apply to nothing: a
60
- * `SET LOCAL` outside a transaction. None for a query with no vector search, or on a field with no ANN index,
61
- * which then demands no transaction either.
62
- */
58
+ /** The `SET`s tuning an ANN index for the query, leading its read: none without a vector search or an ANN index. */
63
59
  private vectorTuning;
60
+ /** Whether `tuning` applies only inside a transaction, as a `SET LOCAL` does: a read opens one, or joins the open one. */
61
+ private tunedInTransaction;
64
62
  protected internalFindMany<E extends object>(entity: Type<E>, q: Query<E>, opts?: QueryOptions): Promise<E[]>;
65
63
  /** Every row `q` matches past its page, deduplicated where it reads `$distinct`. */
66
64
  private countUnpaged;
@@ -70,13 +68,17 @@ export declare abstract class AbstractSqlQuerier extends AbstractQuerier impleme
70
68
  * so those count apart.
71
69
  */
72
70
  protected internalFindManyAndCount<E extends object>(entity: Type<E>, q: Query<E>, opts?: QueryOptions): Promise<[E[], number]>;
73
- /** The rows a read of `entity` matches, each as its statement reads it, the vector search's tuning leading it. */
71
+ /**
72
+ * The rows a read of `entity` matches, each as its statement reads it, the vector search's tuning leading it, in a
73
+ * transaction of its own where the tuning needs one and none is open.
74
+ */
74
75
  private selectRows;
75
76
  /** The rows of a statement the dialect builds, each as the terms it returns say, after the `leading` ones. */
76
77
  private readRows;
77
78
  /**
78
79
  * The one read not going through `runStatements`: it holds the connection for its loop, so it checks its budget
79
- * and connects on its own, its values going as the context holds them, each normalized as it was bound.
80
+ * and connects on its own, its values going as the context holds them, each normalized as it was bound. Tuning
81
+ * that needs a transaction is refused outside one, which would otherwise stay open for the whole loop.
80
82
  */
81
83
  protected internalFindManyStream<E extends object>(entity: Type<E>, q: Query<E>, opts?: QueryOptions): AsyncGenerator<Awaited<E>, void, unknown>;
82
84
  /**
@@ -153,20 +153,16 @@ export class AbstractSqlQuerier extends AbstractQuerier {
153
153
  const [result] = await this.runStatements([this.bound(build)]);
154
154
  return this.updateResultOf(result);
155
155
  }
156
- /**
157
- * The `SET`s tuning an ANN index for the query, leading its read, refused where they would apply to nothing: a
158
- * `SET LOCAL` outside a transaction. None for a query with no vector search, or on a field with no ANN index,
159
- * which then demands no transaction either.
160
- */
156
+ /** The `SET`s tuning an ANN index for the query, leading its read: none without a vector search or an ANN index. */
161
157
  vectorTuning(entity, q) {
162
158
  if (q.$candidates === undefined) {
163
159
  return [];
164
160
  }
165
- const statements = this.dialect.vectorTuningStatements(getMeta(entity), q);
166
- if (statements.length && this.dialect.features.vectorTuningNeedsTransaction && !this.scopeHere()) {
167
- throw new UqlUsageError(`$candidates requires an open transaction on ${this.dialect.engineName}; run the query inside pool.transaction(...)`);
168
- }
169
- return statements.map((sql) => ({ sql, values: [] }));
161
+ return this.dialect.vectorTuningStatements(getMeta(entity), q).map((sql) => ({ sql, values: [] }));
162
+ }
163
+ /** Whether `tuning` applies only inside a transaction, as a `SET LOCAL` does: a read opens one, or joins the open one. */
164
+ tunedInTransaction(tuning) {
165
+ return tuning.length > 0 && this.dialect.features.vectorTuningNeedsTransaction;
170
166
  }
171
167
  async internalFindMany(entity, q, opts) {
172
168
  return this.selectRows(entity, q, opts);
@@ -194,29 +190,37 @@ export class AbstractSqlQuerier extends AbstractQuerier {
194
190
  }
195
191
  return [rows, total];
196
192
  }
197
- /** The rows a read of `entity` matches, each as its statement reads it, the vector search's tuning leading it. */
193
+ /**
194
+ * The rows a read of `entity` matches, each as its statement reads it, the vector search's tuning leading it, in a
195
+ * transaction of its own where the tuning needs one and none is open.
196
+ */
198
197
  selectRows(entity, q, opts, totalAlias) {
199
198
  const tuning = this.vectorTuning(entity, q);
200
- return this.readRows((ctx) => this.dialect.find(ctx, entity, q, opts, totalAlias), tuning);
199
+ const build = (ctx) => this.dialect.find(ctx, entity, q, opts, totalAlias);
200
+ return this.readRows(build, tuning, this.tunedInTransaction(tuning));
201
201
  }
202
202
  /** The rows of a statement the dialect builds, each as the terms it returns say, after the `leading` ones. */
203
- async readRows(build, leading = []) {
203
+ async readRows(build, leading = [], atomic = false) {
204
204
  let terms = [];
205
205
  const statement = this.bound((ctx) => {
206
206
  terms = build(ctx);
207
207
  });
208
- const results = await this.runStatements([...leading, statement]);
208
+ const results = await this.runStatements([...leading, statement], atomic);
209
209
  return results[leading.length].rows.map(rowReader(terms));
210
210
  }
211
211
  /**
212
212
  * The one read not going through `runStatements`: it holds the connection for its loop, so it checks its budget
213
- * and connects on its own, its values going as the context holds them, each normalized as it was bound.
213
+ * and connects on its own, its values going as the context holds them, each normalized as it was bound. Tuning
214
+ * that needs a transaction is refused outside one, which would otherwise stay open for the whole loop.
214
215
  */
215
216
  async *internalFindManyStream(entity, q, opts) {
217
+ const tuning = this.vectorTuning(entity, q);
218
+ if (this.tunedInTransaction(tuning) && !this.scopeHere()) {
219
+ throw new UqlUsageError(`a streamed $candidates needs an open transaction on ${this.dialect.engineName}; run the stream inside pool.transaction(...)`);
220
+ }
216
221
  const ctx = this.dialect.createContext();
217
222
  const read = rowReader(this.dialect.find(ctx, entity, q, opts));
218
223
  this.assertBindBudget(ctx.values);
219
- const tuning = this.vectorTuning(entity, q);
220
224
  await this.lazyConnect();
221
225
  for (const { sql } of tuning) {
222
226
  await this.timed(sql, undefined, () => this.execute(sql));
@@ -288,7 +292,7 @@ export class AbstractSqlQuerier extends AbstractQuerier {
288
292
  results.forEach((result, at) => {
289
293
  const { indexes, idsReliable } = statements[at];
290
294
  if (idsReliable) {
291
- const { ids = [] } = this.updateResultOf(result);
295
+ const { ids } = this.updateResultOf(result);
292
296
  indexes.forEach((index, position) => {
293
297
  rows[index][idKey] ??= ids[position];
294
298
  });
@@ -296,7 +300,7 @@ export class AbstractSqlQuerier extends AbstractQuerier {
296
300
  });
297
301
  }
298
302
  async internalUpdateMany(entity, q, payload, opts) {
299
- const { changes = 0 } = await this.changesOf((ctx) => this.dialect.update(ctx, entity, q, payload, opts));
303
+ const { changes } = await this.changesOf((ctx) => this.dialect.update(ctx, entity, q, payload, opts));
300
304
  return changes;
301
305
  }
302
306
  /** `UPDATE` and `DELETE` with a `RETURNING` read as a read's rows are, where the engine has it. */
@@ -354,12 +358,12 @@ export class AbstractSqlQuerier extends AbstractQuerier {
354
358
  /** The ids an upsert reports of its rows: its `RETURNING` rows' in order, or its one row's in the header. */
355
359
  reportedIds(result) {
356
360
  if (result.rows.length) {
357
- return this.updateResultOf(result).ids ?? [];
361
+ return this.updateResultOf(result).ids;
358
362
  }
359
363
  return result.id ? [result.id] : [];
360
364
  }
361
365
  async internalDeleteMany(entity, q, opts) {
362
- const { changes = 0 } = await this.changesOf((ctx) => this.dialect.delete(ctx, entity, q, opts));
366
+ const { changes } = await this.changesOf((ctx) => this.dialect.delete(ctx, entity, q, opts));
363
367
  return changes;
364
368
  }
365
369
  async openTransaction(opts) {
@@ -1,4 +1,4 @@
1
- import { asyncScope } from '../context/context.js';
1
+ import { asyncScope } from '../util/asyncScope.js';
2
2
  import { cachedIn } from '../util/object.util.js';
3
3
  const slots = new WeakMap();
4
4
  /** The slot of `connection`, whichever querier on it asks. */
@@ -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
  }
@@ -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
+ }
@@ -54,6 +54,8 @@ export type SqlExecution = {
54
54
  readonly changes?: number | null;
55
55
  readonly id?: PrimaryKey;
56
56
  };
57
+ /** The column a `RETURNING` reports ids under: uql's own statements alias the key to it, and a raw `run()` names it so. */
58
+ export declare const RETURNED_ID = "id";
57
59
  /** A statement's result, and how its dialect reports inserted ids, to build a {@link QueryUpdateResult} from. */
58
60
  export type BuildUpdateResultPayload = SqlExecution & {
59
61
  readonly insertIdSource?: InsertIdSource;
@@ -65,10 +67,10 @@ export type BuildUpdateResultPayload = SqlExecution & {
65
67
  };
66
68
  /**
67
69
  * A driver's result as a {@link QueryUpdateResult}: a statement returning rows counts them, which a driver's own
68
- * count is not always (Hrana answers 0); `RETURNING` rows name their id `id`; a MySQL header's first id is extended
70
+ * count is not always (Hrana answers 0); `RETURNING` rows name their id {@link RETURNED_ID}; a MySQL header's first id is extended
69
71
  * by the increment, which holds only where auto-increment allocation is contiguous (`innodb_autoinc_lock_mode` 0, 1).
70
72
  */
71
- export declare function buildUpdateResult(payload: BuildUpdateResultPayload): QueryUpdateResult;
73
+ export declare function buildUpdateResult(payload: BuildUpdateResultPayload): Required<QueryUpdateResult>;
72
74
  /**
73
75
  * Checks if a value is of a primary key type (string, number, or bigint).
74
76
  */
@@ -112,9 +112,11 @@ export function escapeSqlId(val, escapeIdChar = '`', forbidQualified, addDot) {
112
112
  : `${escapeIdChar}${val.replaceAll(escapeIdChar, escapeIdChar + escapeIdChar)}${escapeIdChar}`;
113
113
  return addDot ? `${escaped}.` : escaped;
114
114
  }
115
+ /** The column a `RETURNING` reports ids under: uql's own statements alias the key to it, and a raw `run()` names it so. */
116
+ export const RETURNED_ID = 'id';
115
117
  /**
116
118
  * A driver's result as a {@link QueryUpdateResult}: a statement returning rows counts them, which a driver's own
117
- * count is not always (Hrana answers 0); `RETURNING` rows name their id `id`; a MySQL header's first id is extended
119
+ * count is not always (Hrana answers 0); `RETURNING` rows name their id {@link RETURNED_ID}; a MySQL header's first id is extended
118
120
  * by the increment, which holds only where auto-increment allocation is contiguous (`innodb_autoinc_lock_mode` 0, 1).
119
121
  */
120
122
  export function buildUpdateResult(payload) {
@@ -125,7 +127,7 @@ export function buildUpdateResult(payload) {
125
127
  // counts the rows (false for a MySQL upsert batch, whose querier reads ids back instead). `0` means none.
126
128
  let ids = [];
127
129
  if (rows.length) {
128
- ids = rows.map((r) => r['id']);
130
+ ids = rows.map((r) => r[RETURNED_ID]);
129
131
  }
130
132
  else if (insertIdSource !== 'returning' && isPrimaryKey(id) && id) {
131
133
  if (typeof id === 'string') {
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "homepage": "https://uql-orm.dev",
4
4
  "description": "JSON-native TypeScript ORM for Bun, Browsers, Edge, Node, Workers. Supports PostgreSQL, PGlite, MySQL, MariaDB, SQLite, CockroachDB, SQL Server, Turso, Neon, Cloudflare D1 and MongoDB. Queries are plain JSON, typed to the leaf.",
5
5
  "license": "MIT",
6
- "version": "0.102.7",
6
+ "version": "0.103.0",
7
7
  "type": "module",
8
8
  "engines": {
9
9
  "node": ">=22.18"
@@ -11,9 +11,6 @@
11
11
  "sideEffects": false,
12
12
  "main": "./dist/index.js",
13
13
  "types": "./dist/index.d.ts",
14
- "browser": {
15
- "./dist/context/context.js": "./dist/context/context.browser.js"
16
- },
17
14
  "bin": {
18
15
  "uql-migrate": "./dist/migrate/bin.js"
19
16
  },
@@ -1,12 +0,0 @@
1
- import type { UqlContext } from '../type/index.js';
2
- /** A value held for a synchronous callback. See `context.ts` for the server behavior. */
3
- export declare function asyncScope<T>(): {
4
- run<R>(value: T, callback: () => R): R;
5
- get(): T | undefined;
6
- };
7
- /** Runs `callback` with an ambient {@link UqlContext}. See `context.ts` for the server behavior. */
8
- export declare function withContext<T>(context: UqlContext, callback: () => T): T;
9
- /** The ambient context set by the nearest enclosing {@link withContext}, or `undefined`. */
10
- export declare function getContext(): UqlContext | undefined;
11
- /** Captures the current context and returns a runner that re-establishes it later. See `context.ts`. */
12
- export declare function captureContext(): <T>(callback: () => T) => T;
@@ -1,33 +0,0 @@
1
- // The browser's `context.ts`, without `node:async_hooks`. Filters never resolve in a browser, so this
2
- // only keeps the API; it does not carry a value across `await`s.
3
- /** A value held for a synchronous callback. See `context.ts` for the server behavior. */
4
- export function asyncScope() {
5
- let current;
6
- return {
7
- run: (value, callback) => {
8
- const previous = current;
9
- current = value;
10
- try {
11
- return callback();
12
- }
13
- finally {
14
- current = previous;
15
- }
16
- },
17
- get: () => current,
18
- };
19
- }
20
- const contextScope = asyncScope();
21
- /** Runs `callback` with an ambient {@link UqlContext}. See `context.ts` for the server behavior. */
22
- export function withContext(context, callback) {
23
- return contextScope.run(context, callback);
24
- }
25
- /** The ambient context set by the nearest enclosing {@link withContext}, or `undefined`. */
26
- export function getContext() {
27
- return contextScope.get();
28
- }
29
- /** Captures the current context and returns a runner that re-establishes it later. See `context.ts`. */
30
- export function captureContext() {
31
- const context = getContext();
32
- return (callback) => (context ? withContext(context, callback) : callback());
33
- }