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
@@ -4,12 +4,13 @@ import { BYTES_PREFIX } from '../dialect/hydrateColumn.js';
4
4
  import { skippablePath, jsonArraySlotArgs, jsonPath, jsonSlotArgs, } from '../dialect/jsonSql.js';
5
5
  import { MergeSqlDialect } from '../dialect/mergeSqlDialect.js';
6
6
  import { getMeta } from '../entity/index.js';
7
+ import { soleId } from '../entity/metadata/definition.js';
7
8
  import { canonicalToSql, resolveColumnCanonicalType } from '../schema/canonicalType.js';
8
9
  import { QuerySql } from '../type/index.js';
9
10
  import { parseQueryLock } from '../type/index.js';
10
11
  import { bytesToHex } from '../util/bytes.js';
11
12
  import { isAutoIncrement, isExactDecimal, jsonPathKeys } from '../util/field.util.js';
12
- import { assertNonNegativeInteger, isOperatorMap } from '../util/index.js';
13
+ import { assertNonNegativeInteger, isOperatorMap, RETURNED_ID } from '../util/index.js';
13
14
  import { escapeSingleQuotes } from '../util/sqlLiteral.js';
14
15
  import { UqlUsageError } from '../util/uqlError.js';
15
16
  /** What SQL Server has. */
@@ -67,12 +68,6 @@ function openJsonType(value) {
67
68
  }
68
69
  return typeof value === 'boolean' ? OPENJSON_TYPE.boolean : OPENJSON_TYPE.string;
69
70
  }
70
- /** The one key column and its field, or nothing on a composite key. */
71
- function soleId(meta) {
72
- const [key] = meta.ids;
73
- const field = meta.ids.length === 1 ? meta.fields[key] : undefined;
74
- return field && { key, field };
75
- }
76
71
  /** Microsoft SQL Server 2017 and up. Identifiers are `"`-quoted, the ANSI spelling `tedious` enables. */
77
72
  export class MsSqlDialect extends MergeSqlDialect {
78
73
  features = MSSQL_FEATURES;
@@ -211,7 +206,7 @@ export class MsSqlDialect extends MergeSqlDialect {
211
206
  */
212
207
  writeRows(ctx, meta, payload, write) {
213
208
  const id = soleId(meta);
214
- const column = this.escapeId('id');
209
+ const column = this.escapeId(RETURNED_ID);
215
210
  const identity = this.identityInsertTarget(meta, payload);
216
211
  if (id) {
217
212
  ctx.append(`DECLARE ${OUTPUT_TABLE} TABLE (${column} ${canonicalToSql(resolveColumnCanonicalType(id.field), this)}); `);
@@ -403,7 +398,7 @@ export class MsSqlDialect extends MergeSqlDialect {
403
398
  jsonSet(ctx, expr, set) {
404
399
  for (const [key, value] of Object.entries(set)) {
405
400
  if (value === null) {
406
- throw new UqlUsageError(`mssql cannot $set '${key}' to null: JSON_MODIFY deletes the key instead. Use $unset, or store a JSON null through a whole-column write.`);
401
+ throw new UqlUsageError(`SQL Server cannot $set '${key}' to null: JSON_MODIFY deletes the key instead. Use $unset, or store a JSON null through a whole-column write.`);
407
402
  }
408
403
  }
409
404
  return Object.entries(set).reduce((acc, [key, value]) => `JSON_MODIFY(${acc}, ${jsonPath(key)}, ${this.jsonWriteParam(ctx, value)})`, expr);
@@ -1,6 +1,6 @@
1
1
  import mssql from 'mssql';
2
2
  import { AbstractPoolQuerier } from '../querier/abstractPoolQuerier.js';
3
- import type { QueryUpdateResult, RawRow, TransactionOptions } from '../type/index.js';
3
+ import type { RawRow, TransactionOptions } from '../type/index.js';
4
4
  /** What `tedious` hands back for one statement, whichever shape it took. */
5
5
  type MsSqlResult = {
6
6
  recordset?: RawRow[] & {
@@ -42,8 +42,14 @@ export type MsSqlConnection = {
42
42
  */
43
43
  export declare class MsSqlQuerier extends AbstractPoolQuerier<MsSqlConnection> {
44
44
  #private;
45
- internalAll<T>(query: string, values?: unknown[]): Promise<T[]>;
46
- internalRun(query: string, values?: unknown[]): Promise<QueryUpdateResult>;
45
+ /**
46
+ * `rowsAffected` carries one entry per statement, and a write runs in a batch of several - the table variable
47
+ * its ids go through, the read handing them back uncounted - so the counts are summed.
48
+ */
49
+ protected execute(sql: string, values?: unknown[]): Promise<{
50
+ rows: RawRow[];
51
+ changes: number;
52
+ }>;
47
53
  /**
48
54
  * The driver's own stream over the request, which pauses the request while the loop is behind, so
49
55
  * rows arrive only as fast as they are read. A failure the driver reports through the promise alone
@@ -21,18 +21,16 @@ export class MsSqlQuerier extends AbstractPoolQuerier {
21
21
  });
22
22
  return request;
23
23
  }
24
- async internalAll(query, values) {
25
- const res = await this.#request(values).query(query);
26
- return decodeWireTypes(res.recordset, res.recordset?.columns);
27
- }
28
- async internalRun(query, values) {
29
- const res = await this.#request(values).query(query);
30
- return this.buildUpdateResult({
31
- // `rowsAffected` carries one entry per statement, and a write runs in a batch of several - the table
32
- // variable its ids go through, the read handing them back uncounted - so the counts are summed.
33
- changes: res.rowsAffected.reduce((total, count) => total + count, 0),
24
+ /**
25
+ * `rowsAffected` carries one entry per statement, and a write runs in a batch of several - the table variable
26
+ * its ids go through, the read handing them back uncounted - so the counts are summed.
27
+ */
28
+ async execute(sql, values) {
29
+ const res = await this.#request(values).query(sql);
30
+ return {
34
31
  rows: decodeWireTypes(res.recordset, res.recordset?.columns),
35
- });
32
+ changes: res.rowsAffected.reduce((total, count) => total + count, 0),
33
+ };
36
34
  }
37
35
  /**
38
36
  * The driver's own stream over the request, which pauses the request while the loop is behind, so
@@ -1,12 +1,21 @@
1
1
  import type { PoolConnection } from 'mysql2';
2
+ import type { RowDataPacket } from 'mysql2/promise';
2
3
  import { AbstractPoolQuerier } from '../querier/abstractPoolQuerier.js';
3
4
  /**
4
5
  * Holds the driver's own connection rather than its promise wrapper, whose types name the connection
5
6
  * inside it a promise one too: streaming is the own connection's alone.
6
7
  */
7
8
  export declare class MySql2Querier extends AbstractPoolQuerier<PoolConnection> {
8
- internalAll<T>(query: string, values?: unknown[]): Promise<T[]>;
9
- internalRun(query: string, values?: unknown[]): Promise<import("../index.js").QueryUpdateResult>;
9
+ /** A read answers its rows; a write, the header naming how many rows it changed and the first id it generated. */
10
+ protected execute(sql: string, values?: unknown[]): Promise<{
11
+ rows: RowDataPacket[];
12
+ changes?: undefined;
13
+ id?: undefined;
14
+ } | {
15
+ rows: never[];
16
+ changes: number;
17
+ id: number;
18
+ }>;
10
19
  internalStream(query: string, values?: unknown[]): AsyncGenerator<any, void, any>;
11
20
  protected releaseConn(conn: PoolConnection, discard: boolean): Promise<void>;
12
21
  }
@@ -4,13 +4,10 @@ import { AbstractPoolQuerier } from '../querier/abstractPoolQuerier.js';
4
4
  * inside it a promise one too: streaming is the own connection's alone.
5
5
  */
6
6
  export class MySql2Querier extends AbstractPoolQuerier {
7
- async internalAll(query, values) {
8
- const [res] = await this.getConn().promise().query(query, values);
9
- return res;
10
- }
11
- async internalRun(query, values) {
12
- const [res] = await this.getConn().promise().query(query, values);
13
- return this.buildUpdateResult({ changes: res.affectedRows, id: res.insertId });
7
+ /** A read answers its rows; a write, the header naming how many rows it changed and the first id it generated. */
8
+ async execute(sql, values) {
9
+ const [res] = await this.getConn().promise().query(sql, values);
10
+ return Array.isArray(res) ? { rows: res } : { rows: [], changes: res.affectedRows, id: res.insertId };
14
11
  }
15
12
  async *internalStream(query, values) {
16
13
  yield* this.getConn().query(query, values).stream();
@@ -1 +1,3 @@
1
+ export * from './neonDialect.js';
2
+ export * from './neonQuerier.js';
1
3
  export * from './neonQuerierPool.js';
@@ -1 +1,3 @@
1
+ export * from './neonDialect.js';
2
+ export * from './neonQuerier.js';
1
3
  export * from './neonQuerierPool.js';
@@ -0,0 +1,7 @@
1
+ import { PostgresDialect } from '../postgres/postgresDialect.js';
2
+ import type { EngineName } from '../type/querier.js';
3
+ /** Postgres as Neon serves it: its proxy binds at most 32,767 values a statement over HTTP, half what Postgres takes. */
4
+ export declare class NeonDialect extends PostgresDialect {
5
+ get engineName(): EngineName;
6
+ readonly maxBindValues: number;
7
+ }
@@ -0,0 +1,8 @@
1
+ import { PostgresDialect } from '../postgres/postgresDialect.js';
2
+ /** Postgres as Neon serves it: its proxy binds at most 32,767 values a statement over HTTP, half what Postgres takes. */
3
+ export class NeonDialect extends PostgresDialect {
4
+ get engineName() {
5
+ return 'Neon';
6
+ }
7
+ maxBindValues = 32_767;
8
+ }
@@ -0,0 +1,26 @@
1
+ import { type PgAnyClient, PgQuerier } from '../postgres/pgQuerier.js';
2
+ import type { BoundStatement } from '../querier/index.js';
3
+ import type { ExtraOptions, TransactionOptions } from '../type/index.js';
4
+ import type { SqlExecution } from '../util/sql.util.js';
5
+ import type { NeonDialect } from './neonDialect.js';
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
+ };
11
+ /**
12
+ * Querier for Neon, over HTTP first: a statement is one request, and a list one request running it as a
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.
15
+ */
16
+ export declare class NeonQuerier extends PgQuerier {
17
+ private readonly http;
18
+ constructor(http: NeonHttp, connect: () => Promise<PgAnyClient>, dialect: NeonDialect, extra?: ExtraOptions);
19
+ /** Connects nothing: a statement goes over HTTP until a session holds the connection. */
20
+ protected lazyConnect(): Promise<void>;
21
+ protected execute(sql: string, values?: unknown[]): Promise<SqlExecution>;
22
+ /** A list as one HTTP transaction, all or none; inside an open transaction, in turn on its session, which it joins. */
23
+ protected executeBatch(statements: readonly BoundStatement[]): Promise<SqlExecution[]>;
24
+ protected openTransaction(opts?: TransactionOptions): Promise<void>;
25
+ internalStream(query: string, values?: unknown[]): AsyncGenerator<import("../type/utility.js").RawRow, void, any>;
26
+ }
@@ -0,0 +1,42 @@
1
+ import { PgQuerier } from '../postgres/pgQuerier.js';
2
+ /**
3
+ * Querier for Neon, over HTTP first: a statement is one request, and a list one request running it as a
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.
6
+ */
7
+ export class NeonQuerier extends PgQuerier {
8
+ http;
9
+ constructor(http, connect, dialect, extra) {
10
+ super(connect, dialect, extra);
11
+ this.http = http;
12
+ }
13
+ /** Connects nothing: a statement goes over HTTP until a session holds the connection. */
14
+ async lazyConnect() {
15
+ this.assertActive();
16
+ }
17
+ async execute(sql, values) {
18
+ if (this.conn) {
19
+ return super.execute(sql, values);
20
+ }
21
+ return this.http.query(sql, values);
22
+ }
23
+ /** A list as one HTTP transaction, all or none; inside an open transaction, in turn on its session, which it joins. */
24
+ async executeBatch(statements) {
25
+ if (this.hasOpenTransaction) {
26
+ const results = [];
27
+ for (const { sql, values } of statements) {
28
+ results.push(await super.execute(sql, values));
29
+ }
30
+ return results;
31
+ }
32
+ return this.http.transaction(statements);
33
+ }
34
+ async openTransaction(opts) {
35
+ await super.lazyConnect();
36
+ await super.openTransaction(opts);
37
+ }
38
+ async *internalStream(query, values) {
39
+ await super.lazyConnect();
40
+ yield* super.internalStream(query, values);
41
+ }
42
+ }
@@ -1,8 +1,18 @@
1
- import { Pool, type PoolClient, type PoolConfig } from '@neondatabase/serverless';
2
- import { AbstractPgQuerierPool } from '../postgres/abstractPgQuerierPool.js';
3
- import { PostgresDialect } from '../postgres/postgresDialect.js';
1
+ import { type ClientConfig } from '@neondatabase/serverless';
2
+ import { PgQuerier } from '../postgres/pgQuerier.js';
3
+ import { AbstractSqlQuerierPool } from '../querier/index.js';
4
4
  import type { ExtraOptions } from '../type/index.js';
5
- export declare class NeonQuerierPool extends AbstractPgQuerierPool<PoolClient, PostgresDialect> {
6
- readonly pool: Pool;
7
- constructor(opts: PoolConfig, extra?: ExtraOptions);
5
+ import { NeonDialect } from './neonDialect.js';
6
+ import { NeonQuerier } from './neonQuerier.js';
7
+ /**
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).
12
+ */
13
+ export declare class NeonQuerierPool extends AbstractSqlQuerierPool<PgQuerier, NeonDialect> {
14
+ #private;
15
+ constructor(opts: ClientConfig, extra?: ExtraOptions);
16
+ getQuerier(): Promise<NeonQuerier>;
17
+ getMigrationQuerier(): Promise<PgQuerier>;
8
18
  }
@@ -1,11 +1,54 @@
1
- import { 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
+ import { PgQuerier } from '../postgres/pgQuerier.js';
4
5
  import { wireTypes } from '../postgres/pgWireTypes.js';
5
- import { PostgresDialect } from '../postgres/postgresDialect.js';
6
- export class NeonQuerierPool extends AbstractPgQuerierPool {
6
+ import { AbstractSqlQuerierPool } from '../querier/index.js';
7
+ import { NeonDialect } from './neonDialect.js';
8
+ import { NeonQuerier } from './neonQuerier.js';
9
+ const ignoreError = () => { };
10
+ /**
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.
13
+ */
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 {
27
+ #http;
28
+ #config;
7
29
  constructor(opts, extra) {
30
+ super(new NeonDialect(dialectOptionsFrom(extra)), extra);
8
31
  // Neon's own `types`, not `pg`'s: this entry has to load on an edge runtime where `pg` is absent.
9
- super(new PostgresDialect(dialectOptionsFrom(extra)), new Pool({ types: wireTypes(types), ...opts }), extra);
32
+ const wire = opts.types ?? wireTypes(types);
33
+ this.#config = { ...opts, types: wire };
34
+ const { connectionString, host, port, user, password, database } = opts;
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
+ };
42
+ }
43
+ async getQuerier() {
44
+ return new NeonQuerier(this.#http, () => this.#session(), this.dialect, this.extra);
45
+ }
46
+ async getMigrationQuerier() {
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;
10
53
  }
11
54
  }
@@ -1,5 +1,5 @@
1
1
  import { AbstractSqlQuerier } from '../querier/index.js';
2
- import type { ExtraOptions } from '../type/index.js';
2
+ import type { ExtraOptions, RawRow } from '../type/index.js';
3
3
  import type { PgliteDialect } from './pgliteDialect.js';
4
4
  /** The two methods uql uses of `@electric-sql/pglite`, stated so its published types do not depend on a pre-1.0 package. */
5
5
  export type PgliteDatabase = {
@@ -21,8 +21,12 @@ export declare class PgliteQuerier extends AbstractSqlQuerier {
21
21
  constructor(db: PgliteDatabase, dialect: PgliteDialect, extra?: ExtraOptions | undefined);
22
22
  /** Every querier of the pool is this one handle's session, so they share its transaction. */
23
23
  protected get connection(): object;
24
- internalAll<T>(query: string, values?: unknown[]): Promise<T[]>;
25
- internalRun(query: string, values?: unknown[]): Promise<import("../type/query.js").QueryUpdateResult>;
26
- /** The handle belongs to the pool, which hands out one querier per unit of work over it. */
27
- internalRelease(): Promise<void>;
24
+ /**
25
+ * `affectedRows`, not `rowCount`: PGlite derives the former from the command tag of a write only, where the
26
+ * latter also counts a `SELECT`'s rows and is absent altogether from a DDL tag.
27
+ */
28
+ protected execute(sql: string, values?: unknown[]): Promise<{
29
+ rows: RawRow[];
30
+ changes: number | undefined;
31
+ }>;
28
32
  }
@@ -17,16 +17,12 @@ export class PgliteQuerier extends AbstractSqlQuerier {
17
17
  get connection() {
18
18
  return this.db;
19
19
  }
20
- async internalAll(query, values) {
21
- const res = await this.db.query(query, values);
22
- return res.rows;
20
+ /**
21
+ * `affectedRows`, not `rowCount`: PGlite derives the former from the command tag of a write only, where the
22
+ * latter also counts a `SELECT`'s rows and is absent altogether from a DDL tag.
23
+ */
24
+ async execute(sql, values) {
25
+ const { rows, affectedRows } = await this.db.query(sql, values);
26
+ return { rows, changes: affectedRows };
23
27
  }
24
- async internalRun(query, values) {
25
- const res = await this.db.query(query, values);
26
- // `affectedRows`, not `rowCount`: PGlite derives the former from the command tag of a write only,
27
- // where the latter also counts a `SELECT`'s rows and is absent altogether from a DDL tag.
28
- return this.buildUpdateResult({ rows: res.rows, changes: res.affectedRows });
29
- }
30
- /** The handle belongs to the pool, which hands out one querier per unit of work over it. */
31
- async internalRelease() { }
32
28
  }
@@ -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
  }
@@ -0,0 +1,8 @@
1
+ import type { RawRow } from '../type/index.js';
2
+ import type { SqlExecution } from '../util/sql.util.js';
3
+ /** A node-postgres result as the querier reads it: its rows, and the rows it changed. */
4
+ export type PgResult = {
5
+ readonly rows: RawRow[];
6
+ readonly rowCount: number | null;
7
+ };
8
+ export declare function pgExecution({ rows, rowCount }: PgResult): SqlExecution;
@@ -0,0 +1,3 @@
1
+ export function pgExecution({ rows, rowCount }) {
2
+ return { rows, changes: rowCount };
3
+ }
@@ -1,10 +1,8 @@
1
1
  import { AbstractPoolQuerier } from '../querier/abstractPoolQuerier.js';
2
2
  import type { RawRow } from '../type/index.js';
3
+ import { type PgResult } from './pgExecution.js';
3
4
  export interface PgAnyClient {
4
- query(text: string, values?: unknown[]): Promise<{
5
- rows: RawRow[];
6
- rowCount: number | null;
7
- }>;
5
+ query(text: string, values?: unknown[]): Promise<PgResult>;
8
6
  query(stream: object): AsyncIterable<RawRow>;
9
7
  on(event: 'error', listener: (err: Error) => void): unknown;
10
8
  removeListener(event: 'error', listener: (err: Error) => void): unknown;
@@ -13,16 +11,15 @@ export interface PgAnyClient {
13
11
  }
14
12
  /**
15
13
  * Querier for every client with node-postgres' API: `pg` itself, for Postgres and CockroachDB, and
16
- * 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.
17
15
  */
18
- export declare class PgQuerier<C extends PgAnyClient = PgAnyClient> extends AbstractPoolQuerier<C> {
16
+ export declare class PgQuerier extends AbstractPoolQuerier<PgAnyClient> {
19
17
  /**
20
18
  * A client the server drops while held emits `error` with no statement to report it to, which unheard ends
21
- * 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.
22
20
  */
23
- protected acquired(conn: C): C;
24
- internalAll<T>(query: string, values?: unknown[]): Promise<T[]>;
25
- internalRun(query: string, values?: unknown[]): Promise<import("../type/query.js").QueryUpdateResult>;
21
+ protected acquired(conn: PgAnyClient): PgAnyClient;
22
+ protected execute(sql: string, values?: unknown[]): Promise<import("../util/sql.util.js").SqlExecution>;
26
23
  internalStream(query: string, values?: unknown[]): AsyncGenerator<RawRow, void, any>;
27
- protected releaseConn(conn: C, discard: boolean): Promise<void>;
24
+ protected releaseConn(conn: PgAnyClient, discard: boolean): Promise<void>;
28
25
  }
@@ -1,25 +1,21 @@
1
1
  import { AbstractPoolQuerier } from '../querier/abstractPoolQuerier.js';
2
+ import { pgExecution } from './pgExecution.js';
2
3
  const ignoreError = () => { };
3
4
  /**
4
5
  * Querier for every client with node-postgres' API: `pg` itself, for Postgres and CockroachDB, and
5
- * 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.
6
7
  */
7
8
  export class PgQuerier extends AbstractPoolQuerier {
8
9
  /**
9
10
  * A client the server drops while held emits `error` with no statement to report it to, which unheard ends
10
- * 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.
11
12
  */
12
13
  acquired(conn) {
13
14
  conn.on('error', ignoreError);
14
15
  return conn;
15
16
  }
16
- async internalAll(query, values) {
17
- const res = await this.getConn().query(query, values);
18
- return res.rows;
19
- }
20
- async internalRun(query, values) {
21
- const res = await this.getConn().query(query, values);
22
- return this.buildUpdateResult({ rows: res.rows, changes: res.rowCount ?? 0 });
17
+ async execute(sql, values) {
18
+ return pgExecution(await this.getConn().query(sql, values));
23
19
  }
24
20
  async *internalStream(query, values) {
25
21
  const { default: QueryStream } = await import('pg-query-stream');
@@ -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
  }
@@ -2,11 +2,6 @@ import type { AbstractDialect } from '../dialect/abstractDialect.js';
2
2
  import type { BooleanLike, CursorPage, EntityData, EntityId, EntityWrite, ExtraOptions, FieldKey, Querier, Query, QueryAggMap, QueryAggregate, QueryAggregateResult, QueryConflictPaths, QueryFilter, QueryFindResult, QueryGroupMap, QueryKeysetProjected, QueryOneProjected, QueryOptions, QueryPage, QueryProjected, QuerySearch, RelationKey, SavepointCommand, TransactionOptions, Type, UpdatePayload, UpdateWrite, ReturningResult, WriteOptions, PrimaryKey, WrittenId } from '../type/index.js';
3
3
  import { LoggerWrapper } from '../util/index.js';
4
4
  import { type TransactionScope } from './transaction.js';
5
- /**
6
- * Writes the key an upsert reported onto each row that named none - only the key, since an `onInsert`
7
- * value was never written to a row the upsert updated. A report aligns with the rows only when it
8
- * speaks for every one: a `firstId` dialect reports nothing for a batch.
9
- */
10
5
  /** What an upsert reports of a row: the value a driver answers for a lone key, or the key the read back names. */
11
6
  export type UpsertedId<E> = PrimaryKey | WrittenId<E>;
12
7
  /** An `UPDATE` and a `DELETE` of one statement each, reporting the rows they wrote with the fields `keys` names. */
@@ -20,14 +15,11 @@ export declare abstract class AbstractQuerier implements Querier {
20
15
  readonly extra?: ExtraOptions | undefined;
21
16
  /** The last task {@link serialize} queued, which the next one runs after. */
22
17
  private taskQueue;
23
- /**
24
- * A querier is one unit of work, so releasing ends it. Checked where each backend reaches for its
25
- * connection, on every driver and not just the pooled ones.
26
- */
27
- protected released: boolean;
28
18
  protected readonly logger: LoggerWrapper;
29
19
  abstract readonly dialect: AbstractDialect;
30
20
  constructor(extra?: ExtraOptions | undefined);
21
+ /** Refuses a call on a released querier: each backend calls it where it reaches for its connection. */
22
+ protected assertActive(): void;
31
23
  /**
32
24
  * What the transaction this querier opens belongs to: the querier itself, its own connection, unless every
33
25
  * querier of its pool is one session (SQLite, PGlite), whose queriers then name that handle and share it.
@@ -119,8 +111,11 @@ export declare abstract class AbstractQuerier implements Querier {
119
111
  * transaction with only the fields it lists.
120
112
  */
121
113
  private writeReturning;
122
- /** The rows `ids` names, in their order, each with only the fields `keys` names. */
123
- private readWritten;
114
+ /**
115
+ * The rows `ids` names, in their order, each with only the fields `keys` names: as written, whatever a filter
116
+ * says of them, since a soft-deleted row inserted is still written.
117
+ */
118
+ private readBack;
124
119
  /** What `returning` reports of `rows`: each through `afterLoad`, as a read's are, then only the fields `keys` names. */
125
120
  private returned;
126
121
  /**
@@ -206,8 +201,8 @@ export declare abstract class AbstractQuerier implements Querier {
206
201
  * architecture/security-filter-writes.md.
207
202
  */
208
203
  private readThenUpsert;
209
- /** Upserts `payload`, answering each row's key in payload order where the engine reports every one. */
210
- protected abstract internalUpsertMany<E extends object>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: E[], update?: UpdatePayload<E>): Promise<(UpsertedId<E> | undefined)[] | undefined>;
204
+ /** Upserts `payload`, answering each row's key in payload order, `undefined` for one the engine did not report. */
205
+ protected abstract internalUpsertMany<E extends object>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: E[], update?: UpdatePayload<E>): Promise<(UpsertedId<E> | undefined)[]>;
211
206
  deleteOneById<E extends object, const S extends FieldKey<E> = never, const V extends BooleanLike = true>(entity: Type<E>, id: EntityId<E>, opts?: QueryOptions & WriteOptions<E, S, V>): Promise<ReturningResult<S, number, QueryFindResult<E, S, V> | undefined>>;
212
207
  /** Delete records matching the query, the entity passed first or as `$entity`; soft-deletes unless `opts.hardDelete`. */
213
208
  deleteMany<E extends object>(q: QuerySearch<E> & {
@@ -315,12 +310,18 @@ export declare abstract class AbstractQuerier implements Querier {
315
310
  */
316
311
  private emitLoaded;
317
312
  /**
318
- * The ids of `rows`, read through the filters by the columns an upsert matches them on, and held as
319
- * {@link readForWrite} holds them: after a statement that could not report them in payload order, or before a
320
- * guarded upsert. A row that no read row matches, or that two do, keeps `undefined`: a missing id is honest
321
- * where a guessed one is not.
313
+ * The ids of `rows`, read by the columns an upsert matches them on, soft-deleted rows included since a unique key
314
+ * holds across both, each read held as {@link readForWrite} holds its rows. A row no found row matches, or two do,
315
+ * reads none, since a missing id is honest where a guessed one is not; a null key never conflicts, so is not read.
322
316
  */
323
317
  protected idsByConflict<E extends object>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, rows: EntityData<E>[]): Promise<(WrittenId<E> | undefined)[]>;
318
+ /**
319
+ * `ids` completed where an upsert reported no id for a row whose key it does not keep (`kept`, asked before the
320
+ * write fills one in): read back by the conflict columns.
321
+ */
322
+ protected withUnreportedIds<E extends object>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: EntityData<E>[], ids: (UpsertedId<E> | undefined)[], kept: readonly boolean[]): Promise<(UpsertedId<E> | undefined)[]>;
323
+ /** Reads of the rows matching one of `rows` on `keys`, as many per statement as a key list takes, selecting `select`. */
324
+ private keyedReads;
324
325
  /**
325
326
  * Runs `write` between the event's `before`/`after` pair. The before hooks get the caller's rows, so
326
327
  * what they assign is written; `write` and the after hooks get a copy, which by then carries what
@@ -363,6 +364,9 @@ export declare abstract class AbstractQuerier implements Querier {
363
364
  */
364
365
  release(): Promise<void>;
365
366
  [Symbol.asyncDispose](): Promise<void>;
366
- /** `discard` means the connection must not be reused; backends with a pool evict it instead. */
367
- protected abstract internalRelease(discard: boolean): Promise<void>;
367
+ /**
368
+ * Hands back what the querier holds, nothing where it holds no connection of its own. `discard` means the
369
+ * connection must not be reused; backends with a pool evict it instead.
370
+ */
371
+ protected internalRelease(_discard: boolean): Promise<void>;
368
372
  }