@nextlyhq/adapter-postgres 0.0.2-alpha.5 → 0.0.2-alpha.50
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.cjs +137 -33
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +14 -2
- package/dist/index.d.ts +14 -2
- package/dist/index.mjs +118 -34
- package/dist/index.mjs.map +1 -1
- package/package.json +11 -11
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<
|
|
248
|
+
getDrizzle<T = NodePgDatabase<AnyRelations>>(relations?: AnyRelations): T;
|
|
237
249
|
/**
|
|
238
250
|
* Builds pg Pool configuration from adapter config.
|
|
239
251
|
*/
|
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<
|
|
248
|
+
getDrizzle<T = NodePgDatabase<AnyRelations>>(relations?: AnyRelations): T;
|
|
237
249
|
/**
|
|
238
250
|
* Builds pg Pool configuration from adapter config.
|
|
239
251
|
*/
|
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
|
-
|
|
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
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
515
|
-
|
|
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,63 @@ 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
|
|
558
|
-
|
|
625
|
+
const mapped = this.mapKeysToSqlColumns(
|
|
626
|
+
this.getTableObject(table),
|
|
627
|
+
data
|
|
628
|
+
);
|
|
629
|
+
const columns = Object.keys(mapped);
|
|
630
|
+
const values = Object.values(mapped);
|
|
559
631
|
const placeholders = values.map((_, i) => `$${i + 1}`).join(", ");
|
|
560
632
|
let sql = `INSERT INTO ${this.escapeIdentifier(table)} (${columns.map((c) => this.escapeIdentifier(c)).join(", ")}) VALUES (${placeholders})`;
|
|
561
|
-
|
|
562
|
-
|
|
633
|
+
const ret = options?.returning;
|
|
634
|
+
const returningEmpty = Array.isArray(ret) && ret.length === 0;
|
|
635
|
+
if (!returningEmpty) {
|
|
636
|
+
const returning = !ret || ret === "*" ? "*" : this.mapColumnNamesToSql(this.getTableObject(table), ret).map((col) => this.escapeIdentifier(col)).join(", ");
|
|
563
637
|
sql += ` RETURNING ${returning}`;
|
|
564
|
-
} else {
|
|
565
|
-
sql += " RETURNING *";
|
|
566
638
|
}
|
|
567
639
|
const result = await client.query(sql, values);
|
|
568
|
-
return
|
|
640
|
+
return this.mapRowKeysToJs(
|
|
641
|
+
this.getTableObject(table),
|
|
642
|
+
result.rows[0]
|
|
643
|
+
);
|
|
569
644
|
},
|
|
570
645
|
insertMany: async (table, data, options) => {
|
|
571
646
|
if (data.length === 0) return [];
|
|
572
|
-
const
|
|
647
|
+
const tableObj = this.getTableObject(table);
|
|
648
|
+
const mappedRecords = data.map(
|
|
649
|
+
(r) => this.mapKeysToSqlColumns(tableObj, r)
|
|
650
|
+
);
|
|
651
|
+
const columns = Object.keys(mappedRecords[0]);
|
|
573
652
|
const params = [];
|
|
574
653
|
const valuesClauses = [];
|
|
575
|
-
for (const record of
|
|
654
|
+
for (const record of mappedRecords) {
|
|
576
655
|
const placeholders = [];
|
|
577
656
|
for (const col of columns) {
|
|
578
657
|
params.push(record[col]);
|
|
@@ -581,32 +660,32 @@ var PostgresAdapter = class extends DrizzleAdapter {
|
|
|
581
660
|
valuesClauses.push(`(${placeholders.join(", ")})`);
|
|
582
661
|
}
|
|
583
662
|
let sql = `INSERT INTO ${this.escapeIdentifier(table)} (${columns.map((c) => this.escapeIdentifier(c)).join(", ")}) VALUES ${valuesClauses.join(", ")}`;
|
|
584
|
-
|
|
585
|
-
|
|
663
|
+
const ret = options?.returning;
|
|
664
|
+
const returningEmpty = Array.isArray(ret) && ret.length === 0;
|
|
665
|
+
if (!returningEmpty) {
|
|
666
|
+
const returning = !ret || ret === "*" ? "*" : this.mapColumnNamesToSql(this.getTableObject(table), ret).map((col) => this.escapeIdentifier(col)).join(", ");
|
|
586
667
|
sql += ` RETURNING ${returning}`;
|
|
587
|
-
} else {
|
|
588
|
-
sql += " RETURNING *";
|
|
589
668
|
}
|
|
590
669
|
const result = await client.query(sql, params);
|
|
591
|
-
return result.rows;
|
|
670
|
+
return result.rows.map((r) => this.mapRowKeysToJs(tableObj, r));
|
|
592
671
|
},
|
|
593
|
-
// TransactionContext CRUD methods delegate to the adapter's CRUD
|
|
594
|
-
//
|
|
595
|
-
//
|
|
672
|
+
// TransactionContext CRUD methods delegate to the adapter's Drizzle CRUD
|
|
673
|
+
// but pass the transaction-bound executor so they run inside this
|
|
674
|
+
// transaction rather than on the pool.
|
|
596
675
|
select: async (table, options) => {
|
|
597
|
-
return this.select(table, options);
|
|
676
|
+
return this.select(table, options, txDb());
|
|
598
677
|
},
|
|
599
678
|
selectOne: async (table, options) => {
|
|
600
|
-
return this.selectOne(table, options);
|
|
679
|
+
return this.selectOne(table, options, txDb());
|
|
601
680
|
},
|
|
602
681
|
update: async (table, data, where, options) => {
|
|
603
|
-
return this.update(table, data, where, options);
|
|
682
|
+
return this.update(table, data, where, options, txDb());
|
|
604
683
|
},
|
|
605
|
-
delete: async (table, where,
|
|
606
|
-
return this.delete(table, where);
|
|
684
|
+
delete: async (table, where, options) => {
|
|
685
|
+
return this.delete(table, where, options, txDb());
|
|
607
686
|
},
|
|
608
687
|
upsert: async (table, data, options) => {
|
|
609
|
-
return this.upsert(table, data, options);
|
|
688
|
+
return this.upsert(table, data, options, txDb());
|
|
610
689
|
},
|
|
611
690
|
savepoint: async (name) => {
|
|
612
691
|
await client.query(`SAVEPOINT ${this.escapeIdentifier(name)}`);
|
|
@@ -618,7 +697,12 @@ var PostgresAdapter = class extends DrizzleAdapter {
|
|
|
618
697
|
},
|
|
619
698
|
releaseSavepoint: async (name) => {
|
|
620
699
|
await client.query(`RELEASE SAVEPOINT ${this.escapeIdentifier(name)}`);
|
|
621
|
-
}
|
|
700
|
+
},
|
|
701
|
+
// Expose the transaction-bound Drizzle instance so callers can run
|
|
702
|
+
// Drizzle sql templates inside this transaction (junction-table writes
|
|
703
|
+
// need this to be atomic with the entry write). Reuses the memoized
|
|
704
|
+
// txDb() built for the delegated CRUD methods.
|
|
705
|
+
getDrizzle: () => txDb()
|
|
622
706
|
};
|
|
623
707
|
}
|
|
624
708
|
/**
|