joist-orm 2.3.0-next.7 → 2.3.0-next.71

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 (104) hide show
  1. package/build/_virtual/_rolldown/runtime.cjs +23 -0
  2. package/build/_virtual/_rolldown/runtime.js +5 -0
  3. package/build/codegen.cjs +19 -0
  4. package/build/codegen.cjs.map +1 -0
  5. package/build/codegen.d.cts +1 -0
  6. package/build/codegen.d.mts +1 -0
  7. package/build/codegen.js +12 -28
  8. package/build/codegen.js.map +1 -1
  9. package/build/drivers/PostgresDriver.cjs +299 -0
  10. package/build/drivers/PostgresDriver.cjs.map +1 -0
  11. package/build/drivers/PostgresDriver.d.cts +81 -0
  12. package/build/drivers/PostgresDriver.d.cts.map +1 -0
  13. package/build/drivers/PostgresDriver.d.mts +81 -0
  14. package/build/drivers/PostgresDriver.d.mts.map +1 -0
  15. package/build/drivers/PostgresDriver.js +262 -274
  16. package/build/drivers/PostgresDriver.js.map +1 -1
  17. package/build/drivers/WireRowData.cjs +374 -0
  18. package/build/drivers/WireRowData.cjs.map +1 -0
  19. package/build/drivers/WireRowData.d.cts +111 -0
  20. package/build/drivers/WireRowData.d.cts.map +1 -0
  21. package/build/drivers/WireRowData.d.mts +111 -0
  22. package/build/drivers/WireRowData.d.mts.map +1 -0
  23. package/build/drivers/WireRowData.js +370 -0
  24. package/build/drivers/WireRowData.js.map +1 -0
  25. package/build/drivers/binaryParsers.cjs +422 -0
  26. package/build/drivers/binaryParsers.cjs.map +1 -0
  27. package/build/drivers/binaryParsers.d.cts +80 -0
  28. package/build/drivers/binaryParsers.d.cts.map +1 -0
  29. package/build/drivers/binaryParsers.d.mts +80 -0
  30. package/build/drivers/binaryParsers.d.mts.map +1 -0
  31. package/build/drivers/binaryParsers.js +412 -0
  32. package/build/drivers/binaryParsers.js.map +1 -0
  33. package/build/drivers/patchPgProtocol.cjs +255 -0
  34. package/build/drivers/patchPgProtocol.cjs.map +1 -0
  35. package/build/drivers/patchPgProtocol.d.cts +47 -0
  36. package/build/drivers/patchPgProtocol.d.cts.map +1 -0
  37. package/build/drivers/patchPgProtocol.d.mts +47 -0
  38. package/build/drivers/patchPgProtocol.d.mts.map +1 -0
  39. package/build/drivers/patchPgProtocol.js +253 -0
  40. package/build/drivers/patchPgProtocol.js.map +1 -0
  41. package/build/graphql-codegen-export.cjs +10 -0
  42. package/build/graphql-codegen-export.d.cts +1 -0
  43. package/build/graphql-codegen-export.d.mts +1 -0
  44. package/build/graphql-codegen-export.js +2 -19
  45. package/build/graphql-export.cjs +10 -0
  46. package/build/graphql-export.d.cts +1 -0
  47. package/build/graphql-export.d.mts +1 -0
  48. package/build/graphql-export.js +2 -19
  49. package/build/index.cjs +41 -0
  50. package/build/index.d.cts +3 -0
  51. package/build/index.d.mts +3 -0
  52. package/build/index.js +3 -27
  53. package/build/knex-export.cjs +10 -0
  54. package/build/knex-export.d.cts +1 -0
  55. package/build/knex-export.d.mts +1 -0
  56. package/build/knex-export.js +2 -19
  57. package/build/pg-export.cjs +13 -0
  58. package/build/pg-export.d.cts +4 -0
  59. package/build/pg-export.d.mts +4 -0
  60. package/build/pg-export.js +4 -9
  61. package/build/pg-migrate.cjs +22 -0
  62. package/build/pg-migrate.cjs.map +1 -0
  63. package/build/pg-migrate.d.cts +1 -0
  64. package/build/pg-migrate.d.mts +1 -0
  65. package/build/pg-migrate.js +14 -28
  66. package/build/pg-migrate.js.map +1 -1
  67. package/build/seed.cjs +49 -0
  68. package/build/seed.cjs.map +1 -0
  69. package/build/{seed.d.ts → seed.d.cts} +5 -2
  70. package/build/seed.d.cts.map +1 -0
  71. package/build/seed.d.mts +24 -0
  72. package/build/seed.d.mts.map +1 -0
  73. package/build/seed.js +39 -45
  74. package/build/seed.js.map +1 -1
  75. package/build/tests-export.cjs +10 -0
  76. package/build/tests-export.d.cts +1 -0
  77. package/build/tests-export.d.mts +1 -0
  78. package/build/tests-export.js +2 -19
  79. package/package.json +154 -38
  80. package/build/codegen.d.ts +0 -2
  81. package/build/codegen.d.ts.map +0 -1
  82. package/build/drivers/PostgresDriver.d.ts +0 -49
  83. package/build/drivers/PostgresDriver.d.ts.map +0 -1
  84. package/build/graphql-codegen-export.d.ts +0 -2
  85. package/build/graphql-codegen-export.d.ts.map +0 -1
  86. package/build/graphql-codegen-export.js.map +0 -1
  87. package/build/graphql-export.d.ts +0 -2
  88. package/build/graphql-export.d.ts.map +0 -1
  89. package/build/graphql-export.js.map +0 -1
  90. package/build/index.d.ts +0 -4
  91. package/build/index.d.ts.map +0 -1
  92. package/build/index.js.map +0 -1
  93. package/build/knex-export.d.ts +0 -2
  94. package/build/knex-export.d.ts.map +0 -1
  95. package/build/knex-export.js.map +0 -1
  96. package/build/pg-export.d.ts +0 -3
  97. package/build/pg-export.d.ts.map +0 -1
  98. package/build/pg-export.js.map +0 -1
  99. package/build/pg-migrate.d.ts +0 -2
  100. package/build/pg-migrate.d.ts.map +0 -1
  101. package/build/seed.d.ts.map +0 -1
  102. package/build/tests-export.d.ts +0 -2
  103. package/build/tests-export.d.ts.map +0 -1
  104. package/build/tests-export.js.map +0 -1
@@ -1,306 +1,294 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.PostgresDriver = void 0;
7
- exports.setupLatestPgTypes = setupLatestPgTypes;
8
- const joist_core_1 = require("joist-core");
9
- const pg_1 = __importDefault(require("pg"));
10
- const pg_types_1 = require("pg-types");
11
- const postgres_array_1 = __importDefault(require("postgres-array"));
1
+ import { registerDatabaseBinaryParsers, registerTemporalBinaryParsers } from "./binaryParsers.js";
2
+ import { ensureLazyDataRows } from "./patchPgProtocol.js";
3
+ import { executeRowDataQuery, isRowDataCapableClient } from "./WireRowData.js";
4
+ import { JoinRowOperation, PojoRowData, SequenceIdAssigner, buildRawQuery, cleanSql, driverAfterBegin, driverAfterCommit, driverBeforeBegin, driverBeforeCommit, ensureRectangularArraySizes, fail, generateOps, getRuntimeConfig, kq, kqDot, partition } from "joist-core";
5
+ import pg from "pg";
6
+ import { builtins, getTypeParser } from "pg-types";
7
+ import array from "postgres-array";
8
+ //#region src/drivers/PostgresDriver.ts
12
9
  /**
13
- * Implements the `Driver` interface for Postgres.
14
- *
15
- * This is the canonical driver implementation and leverages several aspects of
16
- * Postgres for the best performance, i.e.:
17
- *
18
- * - Deferred foreign key constraints are used to allow bulk inserting/updating
19
- * all entities without any topographic sorting/ordering issues.
20
- *
21
- * - Sequences are used to bulk-assign + then bulk-insert all entities, to again
22
- * avoid issues with ordering issues (cannot bulk insert A w/o knowing the id of B).
23
- *
24
- * - We use a pg-specific bulk update syntax.
25
- */
26
- class PostgresDriver {
27
- pool;
28
- #idAssigner;
29
- #preloadPlugin;
30
- #onQuery;
31
- constructor(pool, opts) {
32
- this.pool = pool;
33
- this.#idAssigner =
34
- opts?.idAssigner ??
35
- new joist_core_1.SequenceIdAssigner(async (sql) => {
36
- this.#onQuery?.(sql);
37
- return (await pool.query(sql)).rows;
38
- });
39
- this.#preloadPlugin = opts?.preloadPlugin;
40
- this.#onQuery = opts?.onQuery;
41
- setupLatestPgTypes((0, joist_core_1.getRuntimeConfig)().temporal);
42
- }
43
- async executeFind(em, parsed, settings) {
44
- const { sql, bindings } = (0, joist_core_1.buildRawQuery)(parsed, { limit: em.entityLimit, ...settings });
45
- return this.executeQuery(em, sql, bindings);
46
- }
47
- async executeQuery(em, sql, bindings) {
48
- const pgSql = toPgParams(sql);
49
- this.#onQuery?.(pgSql);
50
- const client = this.getMaybeInTxnClient(em);
51
- return client.query(pgSql, bindings).then((result) => result.rows);
52
- }
53
- async transaction(em, fn) {
54
- if (em.txn) {
55
- return fn(em.txn);
56
- }
57
- const client = await this.pool.connect();
58
- let result;
59
- try {
60
- await (0, joist_core_1.driverBeforeBegin)(em, client);
61
- this.#onQuery?.("BEGIN;");
62
- await client.query("BEGIN");
63
- em.txn = client;
64
- try {
65
- await (0, joist_core_1.driverAfterBegin)(em, client);
66
- result = await fn(client);
67
- await (0, joist_core_1.driverBeforeCommit)(em, client);
68
- this.#onQuery?.("COMMIT;");
69
- await client.query("COMMIT");
70
- }
71
- catch (e) {
72
- await client.query("ROLLBACK");
73
- throw e;
74
- }
75
- finally {
76
- em.txn = undefined;
77
- }
78
- await (0, joist_core_1.driverAfterCommit)(em, client);
79
- }
80
- finally {
81
- client.release();
82
- }
83
- return result;
84
- }
85
- async assignNewIds(_, todos) {
86
- return this.#idAssigner.assignNewIds(todos);
87
- }
88
- async flush(em, entityTodos, joinRows) {
89
- const client = (em.txn ?? (0, joist_core_1.fail)("Expected EntityManager.txn to be set"));
90
- await this.#idAssigner.assignNewIds(entityTodos);
91
- const ops = (0, joist_core_1.generateOps)(entityTodos);
92
- const onQuery = this.#onQuery;
93
- // Do INSERTs+UPDATEs first so that we avoid DELETE cascades invalidating oplocks
94
- // See https://github.com/joist-orm/joist-orm/issues/591
95
- await Promise.all([
96
- ...ops.inserts.map((op) => batchInsert(client, op, onQuery)),
97
- ...ops.updates.map((op) => batchUpdate(client, op, onQuery)),
98
- ...ops.deletes.map((op) => batchDelete(client, op, onQuery)),
99
- ...Object.entries(joinRows).flatMap(([joinTableName, todo]) => {
100
- return [
101
- m2mBatchInsert(client, joinTableName, todo, onQuery),
102
- m2mBatchDelete(client, joinTableName, todo, onQuery),
103
- ];
104
- }),
105
- ]);
106
- }
107
- get defaultPlugins() {
108
- return { preloadPlugin: this.#preloadPlugin };
109
- }
110
- getMaybeInTxnClient(em) {
111
- return em.txn || this.pool;
112
- }
113
- }
114
- exports.PostgresDriver = PostgresDriver;
10
+ * Implements the `Driver` interface for Postgres.
11
+ *
12
+ * This is the canonical driver implementation and leverages several aspects of
13
+ * Postgres for the best performance, i.e.:
14
+ *
15
+ * - Deferred foreign key constraints are used to allow bulk inserting/updating
16
+ * all entities without any topographic sorting/ordering issues.
17
+ *
18
+ * - Sequences are used to bulk-assign + then bulk-insert all entities, to again
19
+ * avoid issues with ordering issues (cannot bulk insert A w/o knowing the id of B).
20
+ *
21
+ * - We use a pg-specific bulk update syntax.
22
+ *
23
+ * Query pipelining is enabled for clients created after driver construction unless the pool was
24
+ * configured with `pipeline: false`.
25
+ */
26
+ var PostgresDriver = class {
27
+ pool;
28
+ #idAssigner;
29
+ #preloadPlugin;
30
+ #onQuery;
31
+ lazyRows;
32
+ /** Defined only when `lazyRows` is enabled; its presence is the capability signal the EM checks. */
33
+ executeFindRowData;
34
+ #databaseBinaryParsers = void 0;
35
+ constructor(pool, opts) {
36
+ this.pool = pool;
37
+ pool.options.pipeline ??= true;
38
+ this.#idAssigner = opts?.idAssigner ?? new SequenceIdAssigner(async (sql) => {
39
+ this.#onQuery?.(sql);
40
+ return (await pool.query(sql)).rows;
41
+ });
42
+ this.#preloadPlugin = opts?.preloadPlugin;
43
+ this.#onQuery = opts?.onQuery;
44
+ this.lazyRows = (opts?.lazyRows ?? false) && ensureLazyDataRows();
45
+ if (opts?.lazyRows && !this.lazyRows) console.warn("joist-orm: lazyRows was requested, but patching pg-protocol failed; using classic rows.");
46
+ this.executeFindRowData = this.lazyRows ? (em, parsed, settings) => this.#executeFindRowData(em, parsed, settings) : void 0;
47
+ setupLatestPgTypes(getRuntimeConfig().temporal);
48
+ }
49
+ async executeFind(em, parsed, settings) {
50
+ const { sql, bindings } = buildRawQuery(parsed, {
51
+ limit: em.entityLimit,
52
+ ...settings
53
+ });
54
+ return (await this.executeQuery(em, sql, bindings)).rows;
55
+ }
56
+ async #executeFindRowData(em, parsed, settings) {
57
+ await (this.#databaseBinaryParsers ??= registerDatabaseBinaryParsers(this.pool).catch((err) => {
58
+ this.#databaseBinaryParsers = void 0;
59
+ throw err;
60
+ }));
61
+ const { sql, bindings } = buildRawQuery(parsed, {
62
+ limit: em.entityLimit,
63
+ ...settings
64
+ });
65
+ const pgSql = toPgParams(sql);
66
+ this.#onQuery?.(pgSql);
67
+ const txnClient = em.txn;
68
+ const client = txnClient ?? await this.pool.connect();
69
+ try {
70
+ if (!isRowDataCapableClient(client)) {
71
+ warnUnsupportedClientOnce();
72
+ return new PojoRowData((await client.query(pgSql, bindings)).rows);
73
+ }
74
+ return await executeRowDataQuery(client, pgSql, bindings);
75
+ } finally {
76
+ if (!txnClient) client.release();
77
+ }
78
+ }
79
+ /** Returns PostgreSQL's native command count and raw rows, including null counts for DDL. */
80
+ async executeQuery(em, sql, bindings) {
81
+ const pgSql = toPgParams(sql);
82
+ this.#onQuery?.(pgSql);
83
+ const { rowCount, rows } = await this.getMaybeInTxnClient(em).query(pgSql, bindings);
84
+ return {
85
+ rowCount,
86
+ rows
87
+ };
88
+ }
89
+ async transaction(em, fn) {
90
+ if (em.txn) return fn(em.txn);
91
+ const client = await this.pool.connect();
92
+ let result;
93
+ try {
94
+ await driverBeforeBegin(em, client);
95
+ this.#onQuery?.("BEGIN;");
96
+ await client.query("BEGIN");
97
+ em.txn = client;
98
+ try {
99
+ await driverAfterBegin(em, client);
100
+ result = await fn(client);
101
+ await driverBeforeCommit(em, client);
102
+ this.#onQuery?.("COMMIT;");
103
+ await client.query("COMMIT");
104
+ } catch (e) {
105
+ await client.query("ROLLBACK");
106
+ throw e;
107
+ } finally {
108
+ em.txn = void 0;
109
+ }
110
+ await driverAfterCommit(em, client);
111
+ } finally {
112
+ client.release();
113
+ }
114
+ return result;
115
+ }
116
+ async assignNewIds(_, todos) {
117
+ return this.#idAssigner.assignNewIds(todos);
118
+ }
119
+ async flush(em, entityTodos, joinRows) {
120
+ const client = em.txn ?? fail("Expected EntityManager.txn to be set");
121
+ await this.#idAssigner.assignNewIds(entityTodos);
122
+ const ops = generateOps(entityTodos);
123
+ const onQuery = this.#onQuery;
124
+ await Promise.all([
125
+ ...ops.inserts.map((op) => batchInsert(client, op, onQuery)),
126
+ ...ops.updates.map((op) => batchUpdate(client, op, onQuery)),
127
+ ...ops.deletes.map((op) => batchDelete(client, op, onQuery)),
128
+ ...Object.entries(joinRows).flatMap(([joinTableName, todo]) => {
129
+ return [m2mBatchInsert(client, joinTableName, todo, onQuery), m2mBatchDelete(client, joinTableName, todo, onQuery)];
130
+ })
131
+ ]);
132
+ }
133
+ get defaultPlugins() {
134
+ return { preloadPlugin: this.#preloadPlugin };
135
+ }
136
+ getMaybeInTxnClient(em) {
137
+ return em.txn || this.pool;
138
+ }
139
+ };
115
140
  async function batchInsert(client, op, onQuery) {
116
- const { tableName, columns, columnValues } = op;
117
- const [cte, bindings] = buildUnnestCte("data", columns, columnValues);
118
- const sql = (0, joist_core_1.cleanSql)(`
141
+ const { tableName, columns, columnValues } = op;
142
+ const [cte, bindings] = buildUnnestCte("data", columns, columnValues);
143
+ const pgSql = toPgParams(cleanSql(`
119
144
  ${cte}
120
- INSERT INTO ${(0, joist_core_1.kq)(tableName)} (${columns.map((c) => (0, joist_core_1.kq)(c.columnName)).join(", ")})
145
+ INSERT INTO ${kq(tableName)} (${columns.map((c) => kq(c.columnName)).join(", ")})
121
146
  SELECT * FROM data
122
- `);
123
- const pgSql = toPgParams(sql);
124
- onQuery?.(pgSql);
125
- return client.query(pgSql, bindings);
147
+ `));
148
+ onQuery?.(pgSql);
149
+ return client.query(pgSql, bindings);
126
150
  }
127
151
  async function batchUpdate(client, op, onQuery) {
128
- const { tableName, columns, columnValues, updatedAt } = op;
129
- const [cte, bindings] = buildUnnestCte("data", columns, columnValues);
130
- // JS Dates only have millisecond-level precision, so we may have dropped/lost accuracy when
131
- // reading Postgres's microsecond-level `timestamptz` values; using `date_trunc` "downgrades"
132
- // the pg data to match what we have in the JS Date.
133
- //
134
- // ...but Temporal's types don't have this flaw.
135
- const truncateToMills = !(0, joist_core_1.getRuntimeConfig)().temporal;
136
- const maybeUpdatedAt = updatedAt && truncateToMills
137
- ? ` AND date_trunc('milliseconds', ${(0, joist_core_1.kqDot)(tableName, updatedAt)}) = data.__original_updated_at`
138
- : updatedAt
139
- ? ` AND ${(0, joist_core_1.kqDot)(tableName, updatedAt)} = data.__original_updated_at`
140
- : "";
141
- const sql = `
152
+ const { tableName, columns, columnValues, updatedAt } = op;
153
+ const [cte, bindings] = buildUnnestCte("data", columns, columnValues);
154
+ const truncateToMills = !getRuntimeConfig().temporal;
155
+ const maybeUpdatedAt = updatedAt && truncateToMills ? ` AND date_trunc('milliseconds', ${kqDot(tableName, updatedAt)}) = data.__original_updated_at` : updatedAt ? ` AND ${kqDot(tableName, updatedAt)} = data.__original_updated_at` : "";
156
+ const sql = `
142
157
  ${cte}
143
- UPDATE ${(0, joist_core_1.kq)(tableName)}
144
- SET ${columns
145
- .filter((c) => c.columnName !== "id" && c.columnName !== "__original_updated_at")
146
- .map((c) => `${(0, joist_core_1.kq)(c.columnName)} = data.${(0, joist_core_1.kq)(c.columnName)}`)
147
- .join(", ")}
158
+ UPDATE ${kq(tableName)}
159
+ SET ${columns.filter((c) => c.columnName !== "id" && c.columnName !== "__original_updated_at").map((c) => `${kq(c.columnName)} = data.${kq(c.columnName)}`).join(", ")}
148
160
  FROM data
149
- WHERE ${(0, joist_core_1.kq)(tableName)}.id = data.id ${maybeUpdatedAt}
150
- RETURNING ${(0, joist_core_1.kq)(tableName)}.id
161
+ WHERE ${kq(tableName)}.id = data.id ${maybeUpdatedAt}
162
+ RETURNING ${kq(tableName)}.id
151
163
  `;
152
- const pgSql = toPgParams((0, joist_core_1.cleanSql)(sql));
153
- onQuery?.(pgSql);
154
- const result = await client.query(pgSql, bindings);
155
- const results = result.rows;
156
- const ids = columnValues[0]; // assume id is the 1st column
157
- if (results.length !== ids.length) {
158
- const updated = new Set(results.map((r) => r.id));
159
- const missing = ids.filter((id) => !updated.has(id));
160
- throw new Error(`Oplock failure for ${tableName} rows ${missing.join(", ")}`);
161
- }
164
+ const pgSql = toPgParams(cleanSql(sql));
165
+ onQuery?.(pgSql);
166
+ const results = (await client.query(pgSql, bindings)).rows;
167
+ const ids = columnValues[0];
168
+ if (results.length !== ids.length) {
169
+ const updated = new Set(results.map((r) => r.id));
170
+ const missing = ids.filter((id) => !updated.has(id));
171
+ throw new Error(`Oplock failure for ${tableName} rows ${missing.join(", ")}`);
172
+ }
162
173
  }
163
174
  async function batchDelete(client, op, onQuery) {
164
- const { tableName, ids } = op;
165
- const pgSql = toPgParams(`DELETE FROM ${(0, joist_core_1.kq)(tableName)} WHERE id = ANY(?)`);
166
- onQuery?.(pgSql);
167
- await client.query(pgSql, [ids]);
175
+ const { tableName, ids } = op;
176
+ const pgSql = toPgParams(`DELETE FROM ${kq(tableName)} WHERE id = ANY(?)`);
177
+ onQuery?.(pgSql);
178
+ await client.query(pgSql, [ids]);
168
179
  }
169
180
  /** Creates a CTE named `tableName` that bulk-injects the `columnValues` into a SQL query. */
170
181
  function buildUnnestCte(tableName, columns, columnValues) {
171
- (0, joist_core_1.ensureRectangularArraySizes)(columns, columnValues);
172
- const selects = columns.map((c) => {
173
- if (c.dbType.endsWith("[]")) {
174
- if (c.isNullableArray) {
175
- return `unnest_arrays(?::${c.dbType}[], true) as ${(0, joist_core_1.kq)(c.columnName)}`;
176
- }
177
- else {
178
- return `unnest_arrays(?::${c.dbType}[]) as ${(0, joist_core_1.kq)(c.columnName)}`;
179
- }
180
- }
181
- else {
182
- return `unnest(?::${c.dbType}[]) as ${(0, joist_core_1.kq)(c.columnName)}`;
183
- }
184
- });
185
- const sql = `WITH ${tableName} AS (SELECT ${selects.join(", ")})`;
186
- return [sql, columnValues];
182
+ ensureRectangularArraySizes(columns, columnValues);
183
+ return [`WITH ${tableName} AS (SELECT ${columns.map((c) => {
184
+ if (c.dbType.endsWith("[]")) {
185
+ if (c.isNullableArray) return `unnest_arrays(?::${c.dbType}[], true) as ${kq(c.columnName)}`;
186
+ else return `unnest_arrays(?::${c.dbType}[]) as ${kq(c.columnName)}`;
187
+ } else return `unnest(?::${c.dbType}[]) as ${kq(c.columnName)}`;
188
+ }).join(", ")})`, columnValues];
187
189
  }
188
190
  async function m2mBatchInsert(client, joinTableName, todo, onQuery) {
189
- const { m2m, newRows } = todo;
190
- if (newRows.length === 0)
191
- return;
192
- const col1Values = newRows.map((row) => todo.dbValue(row, m2m.columnName));
193
- const col2Values = newRows.map((row) => todo.dbValue(row, m2m.otherColumnName));
194
- if (m2m.hasJoinTableId) {
195
- const sql = (0, joist_core_1.cleanSql)(`
196
- WITH data AS (SELECT unnest(?::int[]) as ${(0, joist_core_1.kq)(m2m.columnName)}, unnest(?::int[]) as ${(0, joist_core_1.kq)(m2m.otherColumnName)})
197
- INSERT INTO ${(0, joist_core_1.kq)(joinTableName)} (${(0, joist_core_1.kq)(m2m.columnName)}, ${(0, joist_core_1.kq)(m2m.otherColumnName)})
191
+ const { m2m, newRows } = todo;
192
+ if (newRows.length === 0) return;
193
+ const col1Values = newRows.map((row) => todo.dbValue(row, m2m.columnName));
194
+ const col2Values = newRows.map((row) => todo.dbValue(row, m2m.otherColumnName));
195
+ if (m2m.hasJoinTableId) {
196
+ const pgSql = toPgParams(cleanSql(`
197
+ WITH data AS (SELECT unnest(?::int[]) as ${kq(m2m.columnName)}, unnest(?::int[]) as ${kq(m2m.otherColumnName)})
198
+ INSERT INTO ${kq(joinTableName)} (${kq(m2m.columnName)}, ${kq(m2m.otherColumnName)})
198
199
  SELECT * FROM data
199
- ON CONFLICT (${(0, joist_core_1.kq)(m2m.columnName)}, ${(0, joist_core_1.kq)(m2m.otherColumnName)}) DO UPDATE SET id = ${(0, joist_core_1.kq)(joinTableName)}.id
200
+ ON CONFLICT (${kq(m2m.columnName)}, ${kq(m2m.otherColumnName)}) DO UPDATE SET id = ${kq(joinTableName)}.id
200
201
  RETURNING id;
201
- `);
202
- const pgSql = toPgParams(sql);
203
- onQuery?.(pgSql);
204
- const { rows } = await client.query(pgSql, [col1Values, col2Values]);
205
- for (let i = 0; i < rows.length; i++) {
206
- newRows[i].id = rows[i].id;
207
- newRows[i].op = joist_core_1.JoinRowOperation.Flushed;
208
- newRows[i].persisted = true;
209
- }
210
- }
211
- else {
212
- // Id-less join tables have no surrogate id to return; the FK pair is the PK, so just
213
- // insert and let any duplicate be a no-op.
214
- const sql = (0, joist_core_1.cleanSql)(`
215
- WITH data AS (SELECT unnest(?::int[]) as ${(0, joist_core_1.kq)(m2m.columnName)}, unnest(?::int[]) as ${(0, joist_core_1.kq)(m2m.otherColumnName)})
216
- INSERT INTO ${(0, joist_core_1.kq)(joinTableName)} (${(0, joist_core_1.kq)(m2m.columnName)}, ${(0, joist_core_1.kq)(m2m.otherColumnName)})
202
+ `));
203
+ onQuery?.(pgSql);
204
+ const { rows } = await client.query(pgSql, [col1Values, col2Values]);
205
+ for (let i = 0; i < rows.length; i++) {
206
+ newRows[i].id = rows[i].id;
207
+ newRows[i].op = JoinRowOperation.Flushed;
208
+ newRows[i].persisted = true;
209
+ }
210
+ } else {
211
+ const pgSql = toPgParams(cleanSql(`
212
+ WITH data AS (SELECT unnest(?::int[]) as ${kq(m2m.columnName)}, unnest(?::int[]) as ${kq(m2m.otherColumnName)})
213
+ INSERT INTO ${kq(joinTableName)} (${kq(m2m.columnName)}, ${kq(m2m.otherColumnName)})
217
214
  SELECT * FROM data
218
- ON CONFLICT (${(0, joist_core_1.kq)(m2m.columnName)}, ${(0, joist_core_1.kq)(m2m.otherColumnName)}) DO NOTHING;
219
- `);
220
- const pgSql = toPgParams(sql);
221
- onQuery?.(pgSql);
222
- await client.query(pgSql, [col1Values, col2Values]);
223
- for (const row of newRows) {
224
- row.op = joist_core_1.JoinRowOperation.Flushed;
225
- row.persisted = true;
226
- }
227
- }
215
+ ON CONFLICT (${kq(m2m.columnName)}, ${kq(m2m.otherColumnName)}) DO NOTHING;
216
+ `));
217
+ onQuery?.(pgSql);
218
+ await client.query(pgSql, [col1Values, col2Values]);
219
+ for (const row of newRows) {
220
+ row.op = JoinRowOperation.Flushed;
221
+ row.persisted = true;
222
+ }
223
+ }
228
224
  }
229
225
  async function m2mBatchDelete(client, joinTableName, todo, onQuery) {
230
- const { m2m, deletedRows } = todo;
231
- if (deletedRows.length === 0)
232
- return;
233
- // Rows with a surrogate id are deleted by id; rows without one — id-less tables, or `remove`s
234
- // done against an unloaded ManyToManyCollection — are deleted by their (col1, col2) composite.
235
- const [haveIds, noIds] = (0, joist_core_1.partition)(deletedRows, (r) => {
236
- // We used to use `id !== -1` as a marker for "row is/is-not persisted in the db" -- but when adding support
237
- // for id-column-less m2m tables, we couldn't use `id === -1` as this marker anymore, so now rely on a dedicated
238
- // `persisted` key instead.
239
- //
240
- // So, ideally, this `id !== -1` could go away _except_ that our internal verisoning plugin leverages this "m2m rows
241
- // with an id=-1 delete by their FK values" to handle our versioned m2m tables. And for now it's easier to
242
- // keep/restore this `id !== -1` than refactor that.
243
- return r.id !== undefined && r.id !== -1;
244
- });
245
- if (haveIds.length > 0) {
246
- const pgSql = toPgParams(`DELETE FROM ${(0, joist_core_1.kq)(joinTableName)} WHERE id = ANY(?)`);
247
- onQuery?.(pgSql);
248
- await client.query(pgSql, [haveIds.map((r) => r.id)]);
249
- }
250
- if (noIds.length > 0) {
251
- const data = noIds
252
- // Watch for m2m rows that got added-then-removed to entities that were themselves added-then-removed,
253
- // as the deTagId will be undefined for those, as we're skipping adding them to the database.
254
- .filter((row) => !todo.isNew(row, m2m.columnName) && !todo.isNew(row, m2m.otherColumnName))
255
- .map((row) => [todo.dbValue(row, m2m.columnName), todo.dbValue(row, m2m.otherColumnName)]);
256
- if (data.length > 0) {
257
- const pgSql = toPgParams(`
258
- DELETE FROM ${(0, joist_core_1.kq)(joinTableName)}
259
- WHERE (${(0, joist_core_1.kq)(m2m.columnName)}, ${(0, joist_core_1.kq)(m2m.otherColumnName)}) IN (
226
+ const { m2m, deletedRows } = todo;
227
+ if (deletedRows.length === 0) return;
228
+ const [haveIds, noIds] = partition(deletedRows, (r) => {
229
+ return r.id !== void 0 && r.id !== -1;
230
+ });
231
+ if (haveIds.length > 0) {
232
+ const pgSql = toPgParams(`DELETE FROM ${kq(joinTableName)} WHERE id = ANY(?)`);
233
+ onQuery?.(pgSql);
234
+ await client.query(pgSql, [haveIds.map((r) => r.id)]);
235
+ }
236
+ if (noIds.length > 0) {
237
+ const data = noIds.filter((row) => !todo.isNew(row, m2m.columnName) && !todo.isNew(row, m2m.otherColumnName)).map((row) => [todo.dbValue(row, m2m.columnName), todo.dbValue(row, m2m.otherColumnName)]);
238
+ if (data.length > 0) {
239
+ const pgSql = toPgParams(`
240
+ DELETE FROM ${kq(joinTableName)}
241
+ WHERE (${kq(m2m.columnName)}, ${kq(m2m.otherColumnName)}) IN (
260
242
  SELECT (data->>0)::int, (data->>1)::int FROM jsonb_array_elements(?) data
261
243
  )`);
262
- onQuery?.(pgSql);
263
- await client.query(pgSql, [JSON.stringify(data)]);
264
- }
265
- }
266
- deletedRows.forEach((row) => {
267
- row.id = undefined;
268
- row.persisted = false;
269
- row.op = joist_core_1.JoinRowOperation.Flushed;
270
- });
244
+ onQuery?.(pgSql);
245
+ await client.query(pgSql, [JSON.stringify(data)]);
246
+ }
247
+ }
248
+ deletedRows.forEach((row) => {
249
+ row.id = void 0;
250
+ row.persisted = false;
251
+ row.op = JoinRowOperation.Flushed;
252
+ });
271
253
  }
272
254
  /**
273
- * Configures the `pg` driver with the best type parsers.
274
- *
275
- * In particular, pg's default `TIMESTAMPTZ` parser is very inefficient, and even just
276
- * pulling in the latest `pg-types` and installing the fixed parser makes a noticable
277
- * difference.
278
- */
255
+ * Configures the `pg` driver with the best type parsers.
256
+ *
257
+ * In particular, pg's default `TIMESTAMPTZ` parser is very inefficient, and even just
258
+ * pulling in the latest `pg-types` and installing the fixed parser makes a noticable
259
+ * difference.
260
+ */
279
261
  function setupLatestPgTypes(temporal) {
280
- if (temporal) {
281
- // Don't eagerly parse the strings, instead defer to the serde logic
282
- const noop = (s) => s;
283
- const noopArray = (s) => postgres_array_1.default.parse(s, noop);
284
- const { TIMESTAMP, TIMESTAMPTZ, DATE } = pg_1.default.types.builtins;
285
- pg_1.default.types.setTypeParser(DATE, noop);
286
- pg_1.default.types.setTypeParser(TIMESTAMP, noop);
287
- pg_1.default.types.setTypeParser(TIMESTAMPTZ, noop);
288
- // Use `as number` b/c the typings of shadowed pg-types from `pg` and `pg-types` top-level don't line up
289
- pg_1.default.types.setTypeParser(1182, noopArray); // date[]
290
- pg_1.default.types.setTypeParser(1115, noopArray); // timestamp[]
291
- pg_1.default.types.setTypeParser(1185, noopArray); // timestamptz[]
292
- }
293
- else {
294
- pg_1.default.types.setTypeParser(pg_1.default.types.builtins.TIMESTAMPTZ, (0, pg_types_1.getTypeParser)(pg_types_1.builtins.TIMESTAMPTZ));
295
- }
262
+ if (temporal) {
263
+ const noop = (s) => s;
264
+ const noopArray = (s) => array.parse(s, noop);
265
+ const { TIMESTAMP, TIMESTAMPTZ, DATE } = pg.types.builtins;
266
+ pg.types.setTypeParser(DATE, noop);
267
+ pg.types.setTypeParser(TIMESTAMP, noop);
268
+ pg.types.setTypeParser(TIMESTAMPTZ, noop);
269
+ pg.types.setTypeParser(1182, noopArray);
270
+ pg.types.setTypeParser(1115, noopArray);
271
+ pg.types.setTypeParser(1185, noopArray);
272
+ registerTemporalBinaryParsers();
273
+ } else pg.types.setTypeParser(pg.types.builtins.TIMESTAMPTZ, getTypeParser(builtins.TIMESTAMPTZ));
296
274
  }
297
275
  const questionMarks = /(?<!@)\?/g;
298
276
  /**
299
- * Converts our knex-style `?` placeholders to pg-native `$1, $2, ...` numbered parameters.
300
- *
301
- * We skipping postgres operators like `@?`. */
277
+ * Converts our knex-style `?` placeholders to pg-native `$1, $2, ...` numbered parameters.
278
+ *
279
+ * We skipping postgres operators like `@?`. */
302
280
  function toPgParams(sql) {
303
- let i = 0;
304
- return sql.replace(questionMarks, () => `$${++i}`);
281
+ let i = 0;
282
+ return sql.replace(questionMarks, () => `$${++i}`);
283
+ }
284
+ let warnedUnsupportedClient = false;
285
+ /** Warns once when lazyRows degrades to classic rows for an unsupported client, i.e. pg-native. */
286
+ function warnUnsupportedClientOnce() {
287
+ if (warnedUnsupportedClient) return;
288
+ warnedUnsupportedClient = true;
289
+ console.warn("joist-orm: lazyRows is enabled, but this client does not support it; using classic rows.");
305
290
  }
291
+ //#endregion
292
+ export { PostgresDriver, setupLatestPgTypes };
293
+
306
294
  //# sourceMappingURL=PostgresDriver.js.map