@holo-js/db-postgres 0.1.3

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.
@@ -0,0 +1,78 @@
1
+ import { PoolConfig, QueryResult } from 'pg';
2
+
3
+ interface DriverQueryResult<TRow extends Record<string, unknown> = Record<string, unknown>> {
4
+ rows: TRow[];
5
+ rowCount: number;
6
+ }
7
+ interface DriverExecutionResult {
8
+ affectedRows?: number;
9
+ lastInsertId?: number | string;
10
+ }
11
+ interface DriverAdapter {
12
+ initialize(): Promise<void>;
13
+ disconnect(): Promise<void>;
14
+ isConnected(): boolean;
15
+ runWithTransactionScope?<T>(callback: () => Promise<T>): Promise<T>;
16
+ query<TRow extends Record<string, unknown> = Record<string, unknown>>(sql: string, bindings?: readonly unknown[]): Promise<DriverQueryResult<TRow>>;
17
+ execute(sql: string, bindings?: readonly unknown[]): Promise<DriverExecutionResult>;
18
+ beginTransaction(): Promise<void>;
19
+ commit(): Promise<void>;
20
+ rollback(): Promise<void>;
21
+ createSavepoint?(name: string): Promise<void>;
22
+ rollbackToSavepoint?(name: string): Promise<void>;
23
+ releaseSavepoint?(name: string): Promise<void>;
24
+ }
25
+ interface PostgresQueryableLike {
26
+ query(sql: string, bindings?: readonly unknown[]): Promise<QueryResult<Record<string, unknown>> | {
27
+ rows: Record<string, unknown>[];
28
+ rowCount?: number | null;
29
+ }>;
30
+ }
31
+ interface PostgresClientLike extends PostgresQueryableLike {
32
+ release?(): void;
33
+ end?(): Promise<void>;
34
+ }
35
+ interface PostgresPoolLike extends PostgresQueryableLike {
36
+ connect(): Promise<PostgresClientLike>;
37
+ end(): Promise<void>;
38
+ }
39
+ interface PostgresAdapterOptions {
40
+ connectionString?: string;
41
+ config?: PoolConfig;
42
+ client?: PostgresClientLike;
43
+ pool?: PostgresPoolLike;
44
+ createPool?: (config?: PoolConfig) => PostgresPoolLike;
45
+ }
46
+ declare class PostgresAdapter implements DriverAdapter {
47
+ private pool?;
48
+ private readonly directClient?;
49
+ private readonly createPoolInstance?;
50
+ private readonly config?;
51
+ private connected;
52
+ private transactionClient?;
53
+ private leasedTransactionClient;
54
+ private readonly transactionScope;
55
+ constructor(options?: PostgresAdapterOptions);
56
+ initialize(): Promise<void>;
57
+ disconnect(): Promise<void>;
58
+ isConnected(): boolean;
59
+ runWithTransactionScope<T>(callback: () => Promise<T>): Promise<T>;
60
+ query<TRow extends Record<string, unknown> = Record<string, unknown>>(sql: string, bindings?: readonly unknown[]): Promise<DriverQueryResult<TRow>>;
61
+ introspect<TRow extends Record<string, unknown> = Record<string, unknown>>(sql: string, bindings?: readonly unknown[]): Promise<DriverQueryResult<TRow>>;
62
+ execute(sql: string, bindings?: readonly unknown[]): Promise<DriverExecutionResult>;
63
+ beginTransaction(): Promise<void>;
64
+ commit(): Promise<void>;
65
+ rollback(): Promise<void>;
66
+ createSavepoint(name: string): Promise<void>;
67
+ rollbackToSavepoint(name: string): Promise<void>;
68
+ releaseSavepoint(name: string): Promise<void>;
69
+ private getQueryable;
70
+ private leaseTransactionClient;
71
+ private requireTransactionClient;
72
+ private releaseTransactionClient;
73
+ private releaseScopedTransaction;
74
+ private normalizeSavepointName;
75
+ }
76
+ declare function createPostgresAdapter(options?: PostgresAdapterOptions): PostgresAdapter;
77
+
78
+ export { type DriverAdapter, type DriverExecutionResult, type DriverQueryResult, PostgresAdapter, type PostgresAdapterOptions, type PostgresClientLike, type PostgresPoolLike, type PostgresQueryableLike, createPostgresAdapter };
package/dist/index.mjs ADDED
@@ -0,0 +1,199 @@
1
+ // src/index.ts
2
+ import { AsyncLocalStorage } from "async_hooks";
3
+ import { Pool } from "pg";
4
+ var TransactionError = class extends Error {
5
+ };
6
+ var PostgresAdapter = class {
7
+ pool;
8
+ directClient;
9
+ createPoolInstance;
10
+ config;
11
+ connected;
12
+ transactionClient;
13
+ leasedTransactionClient = false;
14
+ transactionScope = new AsyncLocalStorage();
15
+ constructor(options = {}) {
16
+ this.directClient = options.client;
17
+ this.pool = options.pool;
18
+ this.createPoolInstance = options.createPool ?? (options.client || options.pool ? void 0 : (config) => new Pool(config));
19
+ this.config = options.config ?? (options.connectionString ? { connectionString: options.connectionString } : void 0);
20
+ this.connected = !!(options.client || options.pool);
21
+ }
22
+ async initialize() {
23
+ if (this.connected) {
24
+ return;
25
+ }
26
+ if (this.createPoolInstance) {
27
+ this.pool = this.createPoolInstance(this.config);
28
+ }
29
+ this.connected = true;
30
+ }
31
+ async disconnect() {
32
+ if (!this.connected) {
33
+ return;
34
+ }
35
+ if (this.transactionClient && this.leasedTransactionClient) {
36
+ this.transactionClient.release?.();
37
+ this.transactionClient = void 0;
38
+ this.leasedTransactionClient = false;
39
+ }
40
+ if (this.pool) {
41
+ await this.pool.end();
42
+ this.pool = void 0;
43
+ } else if (this.directClient?.end) {
44
+ await this.directClient.end();
45
+ }
46
+ this.connected = false;
47
+ }
48
+ isConnected() {
49
+ return this.connected;
50
+ }
51
+ async runWithTransactionScope(callback) {
52
+ const active = this.transactionScope.getStore();
53
+ if (active) {
54
+ return callback();
55
+ }
56
+ await this.initialize();
57
+ if (this.directClient) {
58
+ return this.transactionScope.run({
59
+ client: this.directClient,
60
+ leased: false,
61
+ released: false
62
+ }, callback);
63
+ }
64
+ if (!this.pool) {
65
+ throw new TransactionError("Postgres adapter is not initialized with a pool or client.");
66
+ }
67
+ const state = {
68
+ client: await this.pool.connect(),
69
+ leased: true,
70
+ released: false
71
+ };
72
+ return this.transactionScope.run(state, async () => {
73
+ try {
74
+ return await callback();
75
+ } finally {
76
+ this.releaseScopedTransaction(state);
77
+ }
78
+ });
79
+ }
80
+ async query(sql, bindings = []) {
81
+ const client = await this.getQueryable();
82
+ const result = await client.query(sql, bindings);
83
+ return {
84
+ rows: result.rows,
85
+ rowCount: result.rowCount ?? result.rows.length
86
+ };
87
+ }
88
+ async introspect(sql, bindings = []) {
89
+ return this.query(sql, bindings);
90
+ }
91
+ async execute(sql, bindings = []) {
92
+ const client = await this.getQueryable();
93
+ const result = await client.query(sql, bindings);
94
+ const firstRow = result.rows[0];
95
+ const firstValue = firstRow ? Object.values(firstRow)[0] : void 0;
96
+ return {
97
+ affectedRows: result.rowCount ?? 0,
98
+ ...typeof firstValue !== "undefined" ? { lastInsertId: firstValue } : {}
99
+ };
100
+ }
101
+ async beginTransaction() {
102
+ const client = await this.leaseTransactionClient();
103
+ await client.query("BEGIN");
104
+ }
105
+ async commit() {
106
+ const client = this.requireTransactionClient();
107
+ await client.query("COMMIT");
108
+ this.releaseTransactionClient();
109
+ }
110
+ async rollback() {
111
+ const client = this.requireTransactionClient();
112
+ await client.query("ROLLBACK");
113
+ this.releaseTransactionClient();
114
+ }
115
+ async createSavepoint(name) {
116
+ await this.requireTransactionClient().query(`SAVEPOINT ${this.normalizeSavepointName(name)}`);
117
+ }
118
+ async rollbackToSavepoint(name) {
119
+ await this.requireTransactionClient().query(`ROLLBACK TO SAVEPOINT ${this.normalizeSavepointName(name)}`);
120
+ }
121
+ async releaseSavepoint(name) {
122
+ await this.requireTransactionClient().query(`RELEASE SAVEPOINT ${this.normalizeSavepointName(name)}`);
123
+ }
124
+ async getQueryable() {
125
+ const scoped = this.transactionScope.getStore();
126
+ if (scoped) {
127
+ return scoped.client;
128
+ }
129
+ if (this.transactionClient) {
130
+ return this.transactionClient;
131
+ }
132
+ await this.initialize();
133
+ if (this.directClient) {
134
+ return this.directClient;
135
+ }
136
+ if (!this.pool) {
137
+ throw new TransactionError("Postgres adapter is not initialized with a pool or client.");
138
+ }
139
+ return this.pool;
140
+ }
141
+ async leaseTransactionClient() {
142
+ const scoped = this.transactionScope.getStore();
143
+ if (scoped) {
144
+ return scoped.client;
145
+ }
146
+ if (this.transactionClient) {
147
+ return this.transactionClient;
148
+ }
149
+ await this.initialize();
150
+ if (this.directClient) {
151
+ this.transactionClient = this.directClient;
152
+ this.leasedTransactionClient = false;
153
+ return this.transactionClient;
154
+ }
155
+ if (!this.pool) {
156
+ throw new TransactionError("Postgres adapter is not initialized with a pool or client.");
157
+ }
158
+ this.transactionClient = await this.pool.connect();
159
+ this.leasedTransactionClient = true;
160
+ return this.transactionClient;
161
+ }
162
+ requireTransactionClient() {
163
+ const scoped = this.transactionScope.getStore();
164
+ if (scoped) {
165
+ return scoped.client;
166
+ }
167
+ if (!this.transactionClient) {
168
+ throw new TransactionError("No active Postgres transaction client is available.");
169
+ }
170
+ return this.transactionClient;
171
+ }
172
+ releaseTransactionClient() {
173
+ if (this.transactionClient && this.leasedTransactionClient) {
174
+ this.transactionClient.release?.();
175
+ }
176
+ this.transactionClient = void 0;
177
+ this.leasedTransactionClient = false;
178
+ }
179
+ releaseScopedTransaction(state) {
180
+ if (!state.leased || state.released) {
181
+ return;
182
+ }
183
+ state.client.release?.();
184
+ state.released = true;
185
+ }
186
+ normalizeSavepointName(name) {
187
+ if (!/^[A-Z_]\w*$/i.test(name)) {
188
+ throw new TransactionError(`Invalid savepoint name "${name}".`);
189
+ }
190
+ return name;
191
+ }
192
+ };
193
+ function createPostgresAdapter(options = {}) {
194
+ return new PostgresAdapter(options);
195
+ }
196
+ export {
197
+ PostgresAdapter,
198
+ createPostgresAdapter
199
+ };
package/package.json ADDED
@@ -0,0 +1,38 @@
1
+ {
2
+ "name": "@holo-js/db-postgres",
3
+ "version": "0.1.3",
4
+ "description": "Holo-JS Framework - Postgres database adapter",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "exports": {
8
+ ".": {
9
+ "types": "./dist/index.d.ts",
10
+ "import": "./dist/index.mjs",
11
+ "default": "./dist/index.mjs"
12
+ }
13
+ },
14
+ "main": "./dist/index.mjs",
15
+ "types": "./dist/index.d.ts",
16
+ "files": [
17
+ "dist"
18
+ ],
19
+ "scripts": {
20
+ "build": "tsup",
21
+ "stub": "tsup --watch",
22
+ "typecheck": "tsc -p tsconfig.json --noEmit",
23
+ "test": "vitest --run"
24
+ },
25
+ "peerDependencies": {
26
+ "@holo-js/db": "^0.1.3"
27
+ },
28
+ "dependencies": {
29
+ "pg": "^8.13.0"
30
+ },
31
+ "devDependencies": {
32
+ "@holo-js/db": "workspace:*",
33
+ "@types/pg": "^8.11.0",
34
+ "tsup": "^8.3.5",
35
+ "typescript": "^5.7.2",
36
+ "vitest": "^2.1.8"
37
+ }
38
+ }