@nextlyhq/adapter-postgres 0.0.2-alpha.6 → 0.0.2-alpha.62

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
@@ -1,6 +1,7 @@
1
1
  import { DrizzleAdapter } from '@nextlyhq/adapter-drizzle';
2
2
  import { PostgresAdapterConfig, SqlParam, TransactionContext, TransactionOptions, DatabaseCapabilities, PoolStats, InsertOptions, DatabaseError } from '@nextlyhq/adapter-drizzle/types';
3
3
  export { AdapterLogger, PoolConfig as AdapterPoolConfig, BaseAdapterConfig, DatabaseCapabilities, DatabaseError, DatabaseErrorKind, DeleteOptions, InsertOptions, JoinSpec, OrderBySpec, PoolStats, PostgresAdapterConfig, SelectOptions, SqlParam, SslConfig, TransactionContext, TransactionOptions, UpdateOptions, UpsertOptions, WhereClause, WhereCondition, WhereOperator } from '@nextlyhq/adapter-drizzle/types';
4
+ import { AnyRelations } from 'drizzle-orm';
4
5
  import { NodePgDatabase } from 'drizzle-orm/node-postgres';
5
6
 
6
7
  /**
@@ -113,6 +114,8 @@ declare const VERSION = "0.1.0";
113
114
  * @public
114
115
  */
115
116
  declare class PostgresAdapter extends DrizzleAdapter {
117
+ private drizzleByRelations;
118
+ private drizzleBare;
116
119
  /**
117
120
  * The database dialect - always 'postgresql' for this adapter.
118
121
  */
@@ -190,11 +193,20 @@ declare class PostgresAdapter extends DrizzleAdapter {
190
193
  * Supports automatic retry for serialization failures (40001) and
191
194
  * deadlocks (40P01) when `retryCount` is specified in options.
192
195
  *
196
+ * An error carrying the Nextly application brand is neither retried nor
197
+ * classified: it is the application refusing the write, so it arrives at the
198
+ * caller as it was thrown. Retrying it would repeat work whose verdict has
199
+ * already been given. Every other error, including an unbranded one raised by
200
+ * the callback, is retried when it is a serialization failure or deadlock and
201
+ * classified on the way out.
202
+ *
193
203
  * @param callback - Function to execute within the transaction
194
204
  * @param options - Transaction options (isolation level, timeout, retry)
195
205
  * @returns The result of the callback
196
206
  *
197
- * @throws {DatabaseError} If transaction fails after all retries
207
+ * @throws {DatabaseError} If the transaction itself fails after all retries,
208
+ * or if the callback threw an error that does not carry the application brand
209
+ * @throws The callback's own error, unchanged, when it carries that brand
198
210
  */
199
211
  transaction<T>(callback: (ctx: TransactionContext) => Promise<T>, options?: TransactionOptions): Promise<T>;
200
212
  /**
@@ -233,7 +245,7 @@ declare class PostgresAdapter extends DrizzleAdapter {
233
245
  * @returns Drizzle ORM instance wrapping the pg pool connection
234
246
  * @throws {Error} If called in browser or not connected
235
247
  */
236
- getDrizzle<T = NodePgDatabase<any>>(schema?: Record<string, unknown>): T;
248
+ getDrizzle<T = NodePgDatabase<AnyRelations>>(relations?: AnyRelations): T;
237
249
  /**
238
250
  * Builds pg Pool configuration from adapter config.
239
251
  */
@@ -253,11 +265,7 @@ declare class PostgresAdapter extends DrizzleAdapter {
253
265
  * @param sql - SQL statement that caused the error (optional)
254
266
  * @returns DatabaseError with proper classification
255
267
  */
256
- private classifyError;
257
- /**
258
- * Override handleQueryError to use PostgreSQL-specific classification.
259
- */
260
- protected handleQueryError(error: unknown, operation: string, table: string): DatabaseError;
268
+ protected classifyError(error: unknown, sql?: string): DatabaseError;
261
269
  }
262
270
  /**
263
271
  * Creates a PostgreSQL database adapter instance.
package/dist/index.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import { DrizzleAdapter } from '@nextlyhq/adapter-drizzle';
2
2
  import { PostgresAdapterConfig, SqlParam, TransactionContext, TransactionOptions, DatabaseCapabilities, PoolStats, InsertOptions, DatabaseError } from '@nextlyhq/adapter-drizzle/types';
3
3
  export { AdapterLogger, PoolConfig as AdapterPoolConfig, BaseAdapterConfig, DatabaseCapabilities, DatabaseError, DatabaseErrorKind, DeleteOptions, InsertOptions, JoinSpec, OrderBySpec, PoolStats, PostgresAdapterConfig, SelectOptions, SqlParam, SslConfig, TransactionContext, TransactionOptions, UpdateOptions, UpsertOptions, WhereClause, WhereCondition, WhereOperator } from '@nextlyhq/adapter-drizzle/types';
4
+ import { AnyRelations } from 'drizzle-orm';
4
5
  import { NodePgDatabase } from 'drizzle-orm/node-postgres';
5
6
 
6
7
  /**
@@ -113,6 +114,8 @@ declare const VERSION = "0.1.0";
113
114
  * @public
114
115
  */
115
116
  declare class PostgresAdapter extends DrizzleAdapter {
117
+ private drizzleByRelations;
118
+ private drizzleBare;
116
119
  /**
117
120
  * The database dialect - always 'postgresql' for this adapter.
118
121
  */
@@ -190,11 +193,20 @@ declare class PostgresAdapter extends DrizzleAdapter {
190
193
  * Supports automatic retry for serialization failures (40001) and
191
194
  * deadlocks (40P01) when `retryCount` is specified in options.
192
195
  *
196
+ * An error carrying the Nextly application brand is neither retried nor
197
+ * classified: it is the application refusing the write, so it arrives at the
198
+ * caller as it was thrown. Retrying it would repeat work whose verdict has
199
+ * already been given. Every other error, including an unbranded one raised by
200
+ * the callback, is retried when it is a serialization failure or deadlock and
201
+ * classified on the way out.
202
+ *
193
203
  * @param callback - Function to execute within the transaction
194
204
  * @param options - Transaction options (isolation level, timeout, retry)
195
205
  * @returns The result of the callback
196
206
  *
197
- * @throws {DatabaseError} If transaction fails after all retries
207
+ * @throws {DatabaseError} If the transaction itself fails after all retries,
208
+ * or if the callback threw an error that does not carry the application brand
209
+ * @throws The callback's own error, unchanged, when it carries that brand
198
210
  */
199
211
  transaction<T>(callback: (ctx: TransactionContext) => Promise<T>, options?: TransactionOptions): Promise<T>;
200
212
  /**
@@ -233,7 +245,7 @@ declare class PostgresAdapter extends DrizzleAdapter {
233
245
  * @returns Drizzle ORM instance wrapping the pg pool connection
234
246
  * @throws {Error} If called in browser or not connected
235
247
  */
236
- getDrizzle<T = NodePgDatabase<any>>(schema?: Record<string, unknown>): T;
248
+ getDrizzle<T = NodePgDatabase<AnyRelations>>(relations?: AnyRelations): T;
237
249
  /**
238
250
  * Builds pg Pool configuration from adapter config.
239
251
  */
@@ -253,11 +265,7 @@ declare class PostgresAdapter extends DrizzleAdapter {
253
265
  * @param sql - SQL statement that caused the error (optional)
254
266
  * @returns DatabaseError with proper classification
255
267
  */
256
- private classifyError;
257
- /**
258
- * Override handleQueryError to use PostgreSQL-specific classification.
259
- */
260
- protected handleQueryError(error: unknown, operation: string, table: string): DatabaseError;
268
+ protected classifyError(error: unknown, sql?: string): DatabaseError;
261
269
  }
262
270
  /**
263
271
  * Creates a PostgreSQL database adapter instance.
package/dist/index.mjs CHANGED
@@ -1,5 +1,6 @@
1
+ import * as net from 'net';
1
2
  import { DrizzleAdapter } from '@nextlyhq/adapter-drizzle';
2
- import { createDatabaseError, isDatabaseError } from '@nextlyhq/adapter-drizzle/types';
3
+ import { isApplicationError, createDatabaseError, isDatabaseError } from '@nextlyhq/adapter-drizzle/types';
3
4
  import { checkDialectVersion } from '@nextlyhq/adapter-drizzle/version-check';
4
5
  import { drizzle } from 'drizzle-orm/node-postgres';
5
6
  import { Pool } from 'pg';
@@ -98,7 +99,30 @@ var PG_ERROR_CODES = {
98
99
  function delay(ms) {
99
100
  return new Promise((resolve) => setTimeout(resolve, ms));
100
101
  }
102
+ var HAPPY_EYEBALLS_MIN_TIMEOUT_MS = 5e3;
103
+ var happyEyeballsTimeoutApplied = false;
104
+ function applyHappyEyeballsTimeoutOnce() {
105
+ if (happyEyeballsTimeoutApplied) return;
106
+ happyEyeballsTimeoutApplied = true;
107
+ try {
108
+ const current = typeof net.getDefaultAutoSelectFamilyAttemptTimeout === "function" ? net.getDefaultAutoSelectFamilyAttemptTimeout() : 0;
109
+ if (current < HAPPY_EYEBALLS_MIN_TIMEOUT_MS) {
110
+ net.setDefaultAutoSelectFamilyAttemptTimeout(
111
+ HAPPY_EYEBALLS_MIN_TIMEOUT_MS
112
+ );
113
+ }
114
+ } catch {
115
+ }
116
+ }
101
117
  var PostgresAdapter = class extends DrizzleAdapter {
118
+ // getDrizzle memoization: drizzle v1's constructor builds a relational
119
+ // query builder per table in the relations config (~40 tables), and the
120
+ // service layer resolves an instance on every db access — construct once
121
+ // per relations object (identity-stable: the schema registry caches it
122
+ // and hands out a NEW object on invalidation, which naturally misses
123
+ // this cache and produces a fresh instance).
124
+ drizzleByRelations = /* @__PURE__ */ new WeakMap();
125
+ drizzleBare;
102
126
  /**
103
127
  * The database dialect - always 'postgresql' for this adapter.
104
128
  */
@@ -145,6 +169,7 @@ var PostgresAdapter = class extends DrizzleAdapter {
145
169
  * @throws {DatabaseError} If connection fails
146
170
  */
147
171
  async connect() {
172
+ applyHappyEyeballsTimeoutOnce();
148
173
  if (this.connected && this.pool) {
149
174
  return;
150
175
  }
@@ -232,16 +257,19 @@ var PostgresAdapter = class extends DrizzleAdapter {
232
257
  * It waits for all checked-out clients to be returned before shutting down.
233
258
  */
234
259
  async disconnect() {
235
- if (!this.pool) {
260
+ const pool = this.pool;
261
+ this.pool = null;
262
+ this.drizzleBare = void 0;
263
+ this.drizzleByRelations = /* @__PURE__ */ new WeakMap();
264
+ if (!pool) {
236
265
  return;
237
266
  }
238
267
  try {
239
- await this.pool.end();
268
+ await pool.end();
240
269
  if (this.config.logger?.info) {
241
270
  this.config.logger.info("PostgreSQL connection closed");
242
271
  }
243
272
  } finally {
244
- this.pool = null;
245
273
  this.connected = false;
246
274
  }
247
275
  }
@@ -305,11 +333,20 @@ var PostgresAdapter = class extends DrizzleAdapter {
305
333
  * Supports automatic retry for serialization failures (40001) and
306
334
  * deadlocks (40P01) when `retryCount` is specified in options.
307
335
  *
336
+ * An error carrying the Nextly application brand is neither retried nor
337
+ * classified: it is the application refusing the write, so it arrives at the
338
+ * caller as it was thrown. Retrying it would repeat work whose verdict has
339
+ * already been given. Every other error, including an unbranded one raised by
340
+ * the callback, is retried when it is a serialization failure or deadlock and
341
+ * classified on the way out.
342
+ *
308
343
  * @param callback - Function to execute within the transaction
309
344
  * @param options - Transaction options (isolation level, timeout, retry)
310
345
  * @returns The result of the callback
311
346
  *
312
- * @throws {DatabaseError} If transaction fails after all retries
347
+ * @throws {DatabaseError} If the transaction itself fails after all retries,
348
+ * or if the callback threw an error that does not carry the application brand
349
+ * @throws The callback's own error, unchanged, when it carries that brand
313
350
  */
314
351
  async transaction(callback, options) {
315
352
  const pool = this.ensurePool();
@@ -336,6 +373,7 @@ var PostgresAdapter = class extends DrizzleAdapter {
336
373
  await client.query("ROLLBACK").catch(() => {
337
374
  });
338
375
  lastError = error;
376
+ if (isApplicationError(error)) throw error;
339
377
  const pgError = error;
340
378
  const isRetryable = pgError.code === "40001" || // serialization_failure
341
379
  pgError.code === "40P01";
@@ -461,13 +499,21 @@ var PostgresAdapter = class extends DrizzleAdapter {
461
499
  * @returns Drizzle ORM instance wrapping the pg pool connection
462
500
  * @throws {Error} If called in browser or not connected
463
501
  */
464
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
465
- getDrizzle(schema) {
502
+ getDrizzle(relations) {
466
503
  if (typeof window !== "undefined") {
467
504
  throw new Error("getDrizzle() is server-only");
468
505
  }
469
506
  const pool = this.ensurePool();
470
- return schema ? drizzle(pool, { schema }) : drizzle(pool);
507
+ if (!relations) {
508
+ this.drizzleBare ??= drizzle({ client: pool });
509
+ return this.drizzleBare;
510
+ }
511
+ let cached = this.drizzleByRelations.get(relations);
512
+ if (!cached) {
513
+ cached = drizzle({ client: pool, relations });
514
+ this.drizzleByRelations.set(relations, cached);
515
+ }
516
+ return cached;
471
517
  }
472
518
  /**
473
519
  * Builds pg Pool configuration from adapter config.
@@ -511,8 +557,9 @@ var PostgresAdapter = class extends DrizzleAdapter {
511
557
  if (this.config.applicationName) {
512
558
  config.application_name = this.config.applicationName;
513
559
  }
514
- if (this.config.statementTimeout) {
515
- config.statement_timeout = this.config.statementTimeout;
560
+ const effectiveStatementTimeout = this.config.statementTimeout ?? this.providerDefaults.statementTimeoutMs;
561
+ if (effectiveStatementTimeout !== void 0) {
562
+ config.statement_timeout = effectiveStatementTimeout;
516
563
  }
517
564
  if (this.config.queryTimeout) {
518
565
  config.query_timeout = this.config.queryTimeout;
@@ -548,31 +595,60 @@ var PostgresAdapter = class extends DrizzleAdapter {
548
595
  * Creates a TransactionContext for the given client.
549
596
  */
550
597
  createTransactionContext(client) {
598
+ const buildTxExecutor = () => drizzle({ client });
599
+ let txExecutor;
600
+ const txDb = () => txExecutor ??= buildTxExecutor();
551
601
  return {
552
602
  execute: async (sql, params = []) => {
553
603
  const result = await client.query(sql, params);
554
604
  return result.rows;
555
605
  },
606
+ // Run on the transaction-bound Drizzle instance rather than the pool, so
607
+ // the statement is part of this transaction and sees its uncommitted rows.
608
+ runStatement: async (statement) => {
609
+ await txDb().execute(statement);
610
+ },
611
+ // node-postgres answers `{ rows }`; the transaction-bound instance keeps
612
+ // the read inside this transaction so it sees its uncommitted writes.
613
+ queryStatement: async (statement) => {
614
+ const result = await txDb().execute(statement);
615
+ return result.rows;
616
+ },
617
+ lockRow: async (table, id) => {
618
+ const idColumn = this.escapeIdentifier("id");
619
+ await client.query(
620
+ `SELECT ${idColumn} FROM ${this.escapeIdentifier(table)} WHERE ${idColumn} = $1 FOR UPDATE`,
621
+ [id]
622
+ );
623
+ },
556
624
  insert: async (table, data, options) => {
557
- const columns = Object.keys(data);
558
- const values = Object.values(data);
625
+ const mapped = this.mapRowToRawSql(this.getTableObject(table), data);
626
+ const columns = Object.keys(mapped);
627
+ const values = Object.values(mapped);
559
628
  const placeholders = values.map((_, i) => `$${i + 1}`).join(", ");
560
629
  let sql = `INSERT INTO ${this.escapeIdentifier(table)} (${columns.map((c) => this.escapeIdentifier(c)).join(", ")}) VALUES (${placeholders})`;
561
- if (options?.returning) {
562
- const returning = options.returning === "*" ? "*" : options.returning.map((col) => this.escapeIdentifier(col)).join(", ");
563
- sql += ` RETURNING ${returning}`;
564
- } else {
565
- sql += " RETURNING *";
630
+ const ret = options?.returning;
631
+ const returningEmpty = Array.isArray(ret) && ret.length === 0;
632
+ const tableObj = this.getTableObject(table);
633
+ const aliases = returningEmpty ? [] : this.dateWallClockAliases(tableObj, ret ?? "*");
634
+ if (!returningEmpty) {
635
+ 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(", ");
639
+ sql += ` RETURNING ${returning}${spelled ? `, ${spelled}` : ""}`;
566
640
  }
567
641
  const result = await client.query(sql, values);
568
- return result.rows[0];
642
+ return this.mapRowFromRawSql(tableObj, result.rows[0], aliases);
569
643
  },
570
644
  insertMany: async (table, data, options) => {
571
645
  if (data.length === 0) return [];
572
- const columns = Object.keys(data[0]);
646
+ const tableObj = this.getTableObject(table);
647
+ const mappedRecords = data.map((r) => this.mapRowToRawSql(tableObj, r));
648
+ const columns = Object.keys(mappedRecords[0]);
573
649
  const params = [];
574
650
  const valuesClauses = [];
575
- for (const record of data) {
651
+ for (const record of mappedRecords) {
576
652
  const placeholders = [];
577
653
  for (const col of columns) {
578
654
  params.push(record[col]);
@@ -581,33 +657,22 @@ var PostgresAdapter = class extends DrizzleAdapter {
581
657
  valuesClauses.push(`(${placeholders.join(", ")})`);
582
658
  }
583
659
  let sql = `INSERT INTO ${this.escapeIdentifier(table)} (${columns.map((c) => this.escapeIdentifier(c)).join(", ")}) VALUES ${valuesClauses.join(", ")}`;
584
- if (options?.returning) {
585
- const returning = options.returning === "*" ? "*" : options.returning.map((col) => this.escapeIdentifier(col)).join(", ");
586
- sql += ` RETURNING ${returning}`;
587
- } else {
588
- sql += " RETURNING *";
660
+ const ret = options?.returning;
661
+ const returningEmpty = Array.isArray(ret) && ret.length === 0;
662
+ const aliases = returningEmpty ? [] : this.dateWallClockAliases(tableObj, ret ?? "*");
663
+ if (!returningEmpty) {
664
+ 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(", ");
668
+ sql += ` RETURNING ${returning}${spelled ? `, ${spelled}` : ""}`;
589
669
  }
590
670
  const result = await client.query(sql, params);
591
- return result.rows;
592
- },
593
- // TransactionContext CRUD methods delegate to the adapter's CRUD
594
- // which uses Drizzle query API via the TableResolver.
595
- // The Drizzle transaction is handled at a higher level.
596
- select: async (table, options) => {
597
- return this.select(table, options);
598
- },
599
- selectOne: async (table, options) => {
600
- return this.selectOne(table, options);
601
- },
602
- update: async (table, data, where, options) => {
603
- return this.update(table, data, where, options);
604
- },
605
- delete: async (table, where, _options) => {
606
- return this.delete(table, where);
607
- },
608
- upsert: async (table, data, options) => {
609
- return this.upsert(table, data, options);
671
+ return result.rows.map(
672
+ (r) => this.mapRowFromRawSql(tableObj, r, aliases)
673
+ );
610
674
  },
675
+ ...this.createTransactionForwarders(txDb),
611
676
  savepoint: async (name) => {
612
677
  await client.query(`SAVEPOINT ${this.escapeIdentifier(name)}`);
613
678
  },
@@ -648,19 +713,6 @@ var PostgresAdapter = class extends DrizzleAdapter {
648
713
  cause: error instanceof Error ? error : void 0
649
714
  });
650
715
  }
651
- /**
652
- * Override handleQueryError to use PostgreSQL-specific classification.
653
- */
654
- handleQueryError(error, operation, table) {
655
- const dbError = this.classifyError(error);
656
- if (!dbError.message.includes(operation)) {
657
- dbError.message = `${operation} operation failed on table '${table}': ${dbError.message}`;
658
- }
659
- if (!dbError.table) {
660
- dbError.table = table;
661
- }
662
- return dbError;
663
- }
664
716
  };
665
717
  function createPostgresAdapter(config) {
666
718
  return new PostgresAdapter(config);