@nextlyhq/adapter-postgres 0.0.2-alpha.65 → 0.0.2-alpha.67

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.
package/dist/index.d.cts CHANGED
@@ -209,6 +209,8 @@ declare class PostgresAdapter extends DrizzleAdapter {
209
209
  * @throws The callback's own error, unchanged, when it carries that brand
210
210
  */
211
211
  transaction<T>(callback: (ctx: TransactionContext) => Promise<T>, options?: TransactionOptions): Promise<T>;
212
+ /** The attempts `transaction` makes, each on a connection of its own. */
213
+ private runTransactionAttempts;
212
214
  /**
213
215
  * Returns the database capabilities for PostgreSQL.
214
216
  *
@@ -217,6 +219,18 @@ declare class PostgresAdapter extends DrizzleAdapter {
217
219
  * databases, including JSONB, arrays, full-text search, and more.
218
220
  */
219
221
  getCapabilities(): DatabaseCapabilities;
222
+ /**
223
+ * The schema set as `search_path` on every pooled connection.
224
+ *
225
+ * @remarks
226
+ * Answers with the same test `buildPoolConfig` applies, so an empty string
227
+ * reports `undefined` exactly as it sets no `search_path`: the value
228
+ * reported is the one the connections actually use.
229
+ *
230
+ * @returns The configured schema, or `undefined` when the server's default
231
+ * `search_path` applies
232
+ */
233
+ getConfiguredSchema(): string | undefined;
220
234
  /**
221
235
  * Returns connection pool statistics.
222
236
  *
@@ -246,6 +260,16 @@ declare class PostgresAdapter extends DrizzleAdapter {
246
260
  * @throws {Error} If called in browser or not connected
247
261
  */
248
262
  getDrizzle<T = NodePgDatabase<AnyRelations>>(relations?: AnyRelations): T;
263
+ /**
264
+ * A Drizzle handle on the pool, for `getDrizzle`.
265
+ *
266
+ * Its `transaction` runs on a client this adapter checks out and returns
267
+ * itself (`pinDrizzleTransactions`): node-postgres destroys a client
268
+ * released with `true`, which is what happens when no ROLLBACK could be
269
+ * confirmed on it. And it counts for `transactionOpenInFlow`, as the
270
+ * adapter's does.
271
+ */
272
+ private poolDrizzle;
249
273
  /**
250
274
  * Builds pg Pool configuration from adapter config.
251
275
  */
@@ -257,6 +281,15 @@ declare class PostgresAdapter extends DrizzleAdapter {
257
281
  /**
258
282
  * Creates a TransactionContext for the given client.
259
283
  */
284
+ /**
285
+ * The RETURNING entries that spell each date column's wall clock out as
286
+ * text, one per alias `dateWallClockAliases` chose. `to_char` renders the
287
+ * stored value without a zone, which is the only form node-postgres cannot
288
+ * shift on the way back.
289
+ */
290
+ private wallClockSpelling;
291
+ /** A table-level `primaryKey({ columns })`, read through the PostgreSQL table config. */
292
+ protected compositePrimaryKey(tableObj: Record<string, unknown>): object[];
260
293
  private createTransactionContext;
261
294
  /**
262
295
  * Classifies a PostgreSQL error into a DatabaseError.
package/dist/index.d.ts CHANGED
@@ -209,6 +209,8 @@ declare class PostgresAdapter extends DrizzleAdapter {
209
209
  * @throws The callback's own error, unchanged, when it carries that brand
210
210
  */
211
211
  transaction<T>(callback: (ctx: TransactionContext) => Promise<T>, options?: TransactionOptions): Promise<T>;
212
+ /** The attempts `transaction` makes, each on a connection of its own. */
213
+ private runTransactionAttempts;
212
214
  /**
213
215
  * Returns the database capabilities for PostgreSQL.
214
216
  *
@@ -217,6 +219,18 @@ declare class PostgresAdapter extends DrizzleAdapter {
217
219
  * databases, including JSONB, arrays, full-text search, and more.
218
220
  */
219
221
  getCapabilities(): DatabaseCapabilities;
222
+ /**
223
+ * The schema set as `search_path` on every pooled connection.
224
+ *
225
+ * @remarks
226
+ * Answers with the same test `buildPoolConfig` applies, so an empty string
227
+ * reports `undefined` exactly as it sets no `search_path`: the value
228
+ * reported is the one the connections actually use.
229
+ *
230
+ * @returns The configured schema, or `undefined` when the server's default
231
+ * `search_path` applies
232
+ */
233
+ getConfiguredSchema(): string | undefined;
220
234
  /**
221
235
  * Returns connection pool statistics.
222
236
  *
@@ -246,6 +260,16 @@ declare class PostgresAdapter extends DrizzleAdapter {
246
260
  * @throws {Error} If called in browser or not connected
247
261
  */
248
262
  getDrizzle<T = NodePgDatabase<AnyRelations>>(relations?: AnyRelations): T;
263
+ /**
264
+ * A Drizzle handle on the pool, for `getDrizzle`.
265
+ *
266
+ * Its `transaction` runs on a client this adapter checks out and returns
267
+ * itself (`pinDrizzleTransactions`): node-postgres destroys a client
268
+ * released with `true`, which is what happens when no ROLLBACK could be
269
+ * confirmed on it. And it counts for `transactionOpenInFlow`, as the
270
+ * adapter's does.
271
+ */
272
+ private poolDrizzle;
249
273
  /**
250
274
  * Builds pg Pool configuration from adapter config.
251
275
  */
@@ -257,6 +281,15 @@ declare class PostgresAdapter extends DrizzleAdapter {
257
281
  /**
258
282
  * Creates a TransactionContext for the given client.
259
283
  */
284
+ /**
285
+ * The RETURNING entries that spell each date column's wall clock out as
286
+ * text, one per alias `dateWallClockAliases` chose. `to_char` renders the
287
+ * stored value without a zone, which is the only form node-postgres cannot
288
+ * shift on the way back.
289
+ */
290
+ private wallClockSpelling;
291
+ /** A table-level `primaryKey({ columns })`, read through the PostgreSQL table config. */
292
+ protected compositePrimaryKey(tableObj: Record<string, unknown>): object[];
260
293
  private createTransactionContext;
261
294
  /**
262
295
  * Classifies a PostgreSQL error into a DatabaseError.
package/dist/index.mjs CHANGED
@@ -1,8 +1,10 @@
1
1
  import * as net from 'net';
2
2
  import { DrizzleAdapter } from '@nextlyhq/adapter-drizzle';
3
+ import { assertSchemaName } from '@nextlyhq/adapter-drizzle/schema-name';
3
4
  import { isApplicationError, createDatabaseError, isDatabaseError } from '@nextlyhq/adapter-drizzle/types';
4
5
  import { checkDialectVersion } from '@nextlyhq/adapter-drizzle/version-check';
5
6
  import { drizzle } from 'drizzle-orm/node-postgres';
7
+ import { getTableConfig } from 'drizzle-orm/pg-core';
6
8
  import { Pool } from 'pg';
7
9
 
8
10
  // src/index.ts
@@ -96,6 +98,15 @@ var PG_ERROR_CODES = {
96
98
  "57P02": "connection",
97
99
  "57P03": "connection"
98
100
  };
101
+ async function ensureSchemaExists(client, schema) {
102
+ const name = assertSchemaName(schema);
103
+ const existing = await client.query(
104
+ "SELECT 1 FROM pg_namespace WHERE nspname = $1",
105
+ [name]
106
+ );
107
+ if (existing.rows.length > 0) return;
108
+ await client.query(`CREATE SCHEMA IF NOT EXISTS ${name}`);
109
+ }
99
110
  function delay(ms) {
100
111
  return new Promise((resolve) => setTimeout(resolve, ms));
101
112
  }
@@ -114,6 +125,7 @@ function applyHappyEyeballsTimeoutOnce() {
114
125
  } catch {
115
126
  }
116
127
  }
128
+ var PG_WALL_CLOCK_FORMAT = 'YYYY-MM-DD"T"HH24:MI:SS.MS';
117
129
  var PostgresAdapter = class extends DrizzleAdapter {
118
130
  // getDrizzle memoization: drizzle v1's constructor builds a relational
119
131
  // query builder per table in the relations config (~40 tables), and the
@@ -209,6 +221,9 @@ var PostgresAdapter = class extends DrizzleAdapter {
209
221
  const client = await this.pool.connect();
210
222
  try {
211
223
  await client.query("SELECT 1");
224
+ if (this.config.schema) {
225
+ await ensureSchemaExists(client, this.config.schema);
226
+ }
212
227
  await checkDialectVersion(client, "postgresql", {
213
228
  // Why: route any future variant warnings through the adapter's
214
229
  // logger. PG has no recognized variants today, but this keeps
@@ -349,6 +364,12 @@ var PostgresAdapter = class extends DrizzleAdapter {
349
364
  * @throws The callback's own error, unchanged, when it carries that brand
350
365
  */
351
366
  async transaction(callback, options) {
367
+ return this.runInFlowTransaction(
368
+ () => this.runTransactionAttempts(callback, options)
369
+ );
370
+ }
371
+ /** The attempts `transaction` makes, each on a connection of its own. */
372
+ async runTransactionAttempts(callback, options) {
352
373
  const pool = this.ensurePool();
353
374
  const maxAttempts = (options?.retryCount ?? 0) + 1;
354
375
  const retryDelayMs = options?.retryDelayMs ?? 100;
@@ -356,6 +377,7 @@ var PostgresAdapter = class extends DrizzleAdapter {
356
377
  for (let attempt = 1; attempt <= maxAttempts; attempt++) {
357
378
  const client = await pool.connect();
358
379
  const startTime = Date.now();
380
+ let discard;
359
381
  try {
360
382
  await this.beginTransaction(client, options);
361
383
  const ctx = this.createTransactionContext(client);
@@ -370,7 +392,8 @@ var PostgresAdapter = class extends DrizzleAdapter {
370
392
  }
371
393
  return result;
372
394
  } catch (error) {
373
- await client.query("ROLLBACK").catch(() => {
395
+ await client.query("ROLLBACK").catch((rollbackError) => {
396
+ discard = rollbackError instanceof Error ? rollbackError : true;
374
397
  });
375
398
  lastError = error;
376
399
  if (isApplicationError(error)) throw error;
@@ -389,7 +412,7 @@ var PostgresAdapter = class extends DrizzleAdapter {
389
412
  }
390
413
  throw this.classifyError(error);
391
414
  } finally {
392
- client.release();
415
+ client.release(discard);
393
416
  }
394
417
  }
395
418
  throw this.classifyError(lastError);
@@ -419,6 +442,20 @@ var PostgresAdapter = class extends DrizzleAdapter {
419
442
  // PostgreSQL default
420
443
  };
421
444
  }
445
+ /**
446
+ * The schema set as `search_path` on every pooled connection.
447
+ *
448
+ * @remarks
449
+ * Answers with the same test `buildPoolConfig` applies, so an empty string
450
+ * reports `undefined` exactly as it sets no `search_path`: the value
451
+ * reported is the one the connections actually use.
452
+ *
453
+ * @returns The configured schema, or `undefined` when the server's default
454
+ * `search_path` applies
455
+ */
456
+ getConfiguredSchema() {
457
+ return this.config.schema ? this.config.schema : void 0;
458
+ }
422
459
  /**
423
460
  * Returns connection pool statistics.
424
461
  *
@@ -505,16 +542,38 @@ var PostgresAdapter = class extends DrizzleAdapter {
505
542
  }
506
543
  const pool = this.ensurePool();
507
544
  if (!relations) {
508
- this.drizzleBare ??= drizzle({ client: pool });
545
+ this.drizzleBare ??= this.poolDrizzle(pool);
509
546
  return this.drizzleBare;
510
547
  }
511
548
  let cached = this.drizzleByRelations.get(relations);
512
549
  if (!cached) {
513
- cached = drizzle({ client: pool, relations });
550
+ cached = this.poolDrizzle(pool, relations);
514
551
  this.drizzleByRelations.set(relations, cached);
515
552
  }
516
553
  return cached;
517
554
  }
555
+ /**
556
+ * A Drizzle handle on the pool, for `getDrizzle`.
557
+ *
558
+ * Its `transaction` runs on a client this adapter checks out and returns
559
+ * itself (`pinDrizzleTransactions`): node-postgres destroys a client
560
+ * released with `true`, which is what happens when no ROLLBACK could be
561
+ * confirmed on it. And it counts for `transactionOpenInFlow`, as the
562
+ * adapter's does.
563
+ */
564
+ poolDrizzle(pool, relations) {
565
+ const onClient = (client) => relations ? drizzle({ client, relations }) : drizzle({ client });
566
+ return this.trackFlowTransactions(
567
+ this.pinDrizzleTransactions(onClient(pool), async () => {
568
+ const client = await pool.connect();
569
+ return {
570
+ drizzle: onClient(client),
571
+ rollback: () => client.query("ROLLBACK"),
572
+ release: (dirty) => client.release(dirty)
573
+ };
574
+ })
575
+ );
576
+ }
518
577
  /**
519
578
  * Builds pg Pool configuration from adapter config.
520
579
  */
@@ -557,6 +616,9 @@ var PostgresAdapter = class extends DrizzleAdapter {
557
616
  if (this.config.applicationName) {
558
617
  config.application_name = this.config.applicationName;
559
618
  }
619
+ if (this.config.schema) {
620
+ config.options = `-c search_path=${assertSchemaName(this.config.schema)}`;
621
+ }
560
622
  const effectiveStatementTimeout = this.config.statementTimeout ?? this.providerDefaults.statementTimeoutMs;
561
623
  if (effectiveStatementTimeout !== void 0) {
562
624
  config.statement_timeout = effectiveStatementTimeout;
@@ -594,11 +656,30 @@ var PostgresAdapter = class extends DrizzleAdapter {
594
656
  /**
595
657
  * Creates a TransactionContext for the given client.
596
658
  */
659
+ /**
660
+ * The RETURNING entries that spell each date column's wall clock out as
661
+ * text, one per alias `dateWallClockAliases` chose. `to_char` renders the
662
+ * stored value without a zone, which is the only form node-postgres cannot
663
+ * shift on the way back.
664
+ */
665
+ wallClockSpelling(aliases) {
666
+ return aliases.map(
667
+ (a) => `to_char(${this.escapeIdentifier(a.sqlName)}, '${PG_WALL_CLOCK_FORMAT}') AS ${this.escapeIdentifier(a.alias)}`
668
+ ).join(", ");
669
+ }
670
+ /** A table-level `primaryKey({ columns })`, read through the PostgreSQL table config. */
671
+ compositePrimaryKey(tableObj) {
672
+ return getTableConfig(tableObj).primaryKeys.flatMap(
673
+ (key) => key.columns
674
+ );
675
+ }
597
676
  createTransactionContext(client) {
598
- const buildTxExecutor = () => drizzle({ client });
599
- let txExecutor;
600
- const txDb = () => txExecutor ??= buildTxExecutor();
677
+ const txHandles = this.transactionDrizzleHandles(
678
+ (relations) => relations ? drizzle({ client, relations }) : drizzle({ client })
679
+ );
680
+ const txDb = txHandles.bare;
601
681
  return {
682
+ drizzleWithRelations: txHandles.withRelations,
602
683
  execute: async (sql, params = []) => {
603
684
  const result = await client.query(sql, params);
604
685
  return result.rows;
@@ -633,9 +714,7 @@ var PostgresAdapter = class extends DrizzleAdapter {
633
714
  const aliases = returningEmpty ? [] : this.dateWallClockAliases(tableObj, ret ?? "*");
634
715
  if (!returningEmpty) {
635
716
  const returning = !ret || ret === "*" ? "*" : this.mapColumnNamesToSql(tableObj, ret).map((col) => this.escapeIdentifier(col)).join(", ");
636
- const spelled = aliases.map(
637
- (a) => `to_char(${this.escapeIdentifier(a.sqlName)}, 'YYYY-MM-DD"T"HH24:MI:SS.MS') AS ${this.escapeIdentifier(a.alias)}`
638
- ).join(", ");
717
+ const spelled = this.wallClockSpelling(aliases);
639
718
  sql += ` RETURNING ${returning}${spelled ? `, ${spelled}` : ""}`;
640
719
  }
641
720
  const result = await client.query(sql, values);
@@ -662,9 +741,7 @@ var PostgresAdapter = class extends DrizzleAdapter {
662
741
  const aliases = returningEmpty ? [] : this.dateWallClockAliases(tableObj, ret ?? "*");
663
742
  if (!returningEmpty) {
664
743
  const returning = !ret || ret === "*" ? "*" : this.mapColumnNamesToSql(tableObj, ret).map((col) => this.escapeIdentifier(col)).join(", ");
665
- const spelled = aliases.map(
666
- (a) => `to_char(${this.escapeIdentifier(a.sqlName)}, 'YYYY-MM-DD"T"HH24:MI:SS.MS') AS ${this.escapeIdentifier(a.alias)}`
667
- ).join(", ");
744
+ const spelled = this.wallClockSpelling(aliases);
668
745
  sql += ` RETURNING ${returning}${spelled ? `, ${spelled}` : ""}`;
669
746
  }
670
747
  const result = await client.query(sql, params);
@@ -672,6 +749,16 @@ var PostgresAdapter = class extends DrizzleAdapter {
672
749
  (r) => this.mapRowFromRawSql(tableObj, r, aliases)
673
750
  );
674
751
  },
752
+ // Adapter-built, as `insert` above is; `transactionUpdate` says why.
753
+ // A column the model does not declare binds natively, as every value
754
+ // on this path's insert does.
755
+ update: this.transactionUpdate(
756
+ txDb,
757
+ async (statement) => (await txDb().execute(statement)).rows,
758
+ // Structured values as JSON text: node-postgres would spell an array
759
+ // as a PostgreSQL array literal, which no JSON column accepts.
760
+ (value) => this.bindUnmodeledStructuredAsJson(value)
761
+ ),
675
762
  ...this.createTransactionForwarders(txDb),
676
763
  savepoint: async (name) => {
677
764
  await client.query(`SAVEPOINT ${this.escapeIdentifier(name)}`);
@@ -695,7 +782,10 @@ var PostgresAdapter = class extends DrizzleAdapter {
695
782
  */
696
783
  classifyError(error, sql) {
697
784
  if (isDatabaseError(error)) return error;
698
- const pgError = error;
785
+ const pgError = this.driverErrorIn(
786
+ error,
787
+ (candidate) => typeof candidate.code === "string" && candidate.code !== ""
788
+ );
699
789
  const kind = pgError.code && PG_ERROR_CODES[pgError.code] || "unknown";
700
790
  let message = pgError.message ?? String(error);
701
791
  if (sql && kind === "query") {