@mountsqli/pg 0.1.0

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,326 @@
1
+ // src/pg-core/dialect.ts
2
+ import { Dialect, SQL } from "@mountsqli/core";
3
+ var PgDialect = class extends Dialect {
4
+ dialect = "pg";
5
+ escapeName(name) {
6
+ return `"${name}"`;
7
+ }
8
+ escapeParam(index) {
9
+ return `$${index}`;
10
+ }
11
+ // ---- SELECT ------------------------------------------------------------
12
+ buildSelectQuery(config) {
13
+ const parts = ["SELECT"];
14
+ if (config.distinct) parts.push("DISTINCT");
15
+ if (config.columns.length > 0) {
16
+ const colSqls = config.columns.map((col) => {
17
+ const tableName2 = col._.tableName || config.table?.[/* @__PURE__ */ Symbol.for("name")];
18
+ if (tableName2) {
19
+ return `${this.escapeName(tableName2)}.${this.escapeName(col.name)}`;
20
+ }
21
+ return this.escapeName(col.name);
22
+ });
23
+ parts.push(colSqls.join(", "));
24
+ } else {
25
+ parts.push("*");
26
+ }
27
+ const tableName = config.table?.[/* @__PURE__ */ Symbol.for("name")];
28
+ const schema = config.table?.[/* @__PURE__ */ Symbol.for("schema")];
29
+ if (schema) {
30
+ parts.push(`FROM ${this.escapeName(schema)}.${this.escapeName(tableName)}`);
31
+ } else {
32
+ parts.push(`FROM ${this.escapeName(tableName)}`);
33
+ }
34
+ if (config.joins && config.joins.length > 0) {
35
+ for (const join of config.joins) {
36
+ const joinTableName = join.table?.[/* @__PURE__ */ Symbol.for("name")];
37
+ const joinSchema = join.table?.[/* @__PURE__ */ Symbol.for("schema")];
38
+ const joinFullName = joinSchema ? `${this.escapeName(joinSchema)}.${this.escapeName(joinTableName)}` : this.escapeName(joinTableName);
39
+ const joinType = join.type.toUpperCase();
40
+ const onSql = join.on.toQuery(this.getBuildQueryConfig()).sql;
41
+ parts.push(`${joinType} JOIN ${joinFullName} ON ${onSql}`);
42
+ }
43
+ }
44
+ if (config.where) {
45
+ const whereSql = config.where.toQuery(this.getBuildQueryConfig()).sql;
46
+ parts.push(`WHERE ${whereSql}`);
47
+ }
48
+ if (config.groupBy && config.groupBy.length > 0) {
49
+ const groupSqls = config.groupBy.map((g) => g.toQuery(this.getBuildQueryConfig()).sql);
50
+ parts.push(`GROUP BY ${groupSqls.join(", ")}`);
51
+ }
52
+ if (config.having) {
53
+ const havingSql = config.having.toQuery(this.getBuildQueryConfig()).sql;
54
+ parts.push(`HAVING ${havingSql}`);
55
+ }
56
+ if (config.orderBy && config.orderBy.length > 0) {
57
+ const orderSqls = config.orderBy.map((o) => o.toQuery(this.getBuildQueryConfig()).sql);
58
+ parts.push(`ORDER BY ${orderSqls.join(", ")}`);
59
+ }
60
+ if (config.limit !== void 0) {
61
+ parts.push(`LIMIT ${config.limit}`);
62
+ }
63
+ if (config.offset !== void 0) {
64
+ parts.push(`OFFSET ${config.offset}`);
65
+ }
66
+ return new SQL([parts.join(" ")]);
67
+ }
68
+ // ---- INSERT ------------------------------------------------------------
69
+ buildInsertQuery(config) {
70
+ const tableName = config.table?.[/* @__PURE__ */ Symbol.for("name")];
71
+ const schema = config.table?.[/* @__PURE__ */ Symbol.for("schema")];
72
+ const tableRef = schema ? `${this.escapeName(schema)}.${this.escapeName(tableName)}` : this.escapeName(tableName);
73
+ const columns = Object.keys(config.values[0] ?? {});
74
+ const validColumns = Object.keys(config.table.columns ?? {});
75
+ if (validColumns.length > 0) {
76
+ const invalidColumns = columns.filter((c) => !validColumns.includes(c));
77
+ if (invalidColumns.length > 0) {
78
+ throw new Error(`Invalid column(s): ${invalidColumns.join(", ")}`);
79
+ }
80
+ }
81
+ const escapedCols = columns.map((c) => this.escapeName(c));
82
+ const valueSets = [];
83
+ let paramIdx = 1;
84
+ for (const _row of config.values) {
85
+ const placeholders = columns.map(() => `$${paramIdx++}`);
86
+ valueSets.push(`(${placeholders.join(", ")})`);
87
+ }
88
+ const params = [];
89
+ for (const row of config.values) {
90
+ for (const col of columns) {
91
+ params.push(row[col]);
92
+ }
93
+ }
94
+ let sql = `INSERT INTO ${tableRef} (${escapedCols.join(", ")}) VALUES ${valueSets.join(", ")}`;
95
+ if (config.onConflict) {
96
+ const conflictSql = config.onConflict.toQuery(this.getBuildQueryConfig()).sql;
97
+ sql += ` ${conflictSql}`;
98
+ }
99
+ if (config.returning && config.returning.length > 0) {
100
+ const retCols = config.returning.map((c) => {
101
+ const tn = c._.tableName || tableName;
102
+ return `${this.escapeName(tn)}.${this.escapeName(c.name)}`;
103
+ });
104
+ sql += ` RETURNING ${retCols.join(", ")}`;
105
+ } else {
106
+ sql += ` RETURNING *`;
107
+ }
108
+ return new SQL([sql]);
109
+ }
110
+ // ---- UPDATE ------------------------------------------------------------
111
+ buildUpdateQuery(config) {
112
+ const tableName = config.table?.[/* @__PURE__ */ Symbol.for("name")];
113
+ const schema = config.table?.[/* @__PURE__ */ Symbol.for("schema")];
114
+ const tableRef = schema ? `${this.escapeName(schema)}.${this.escapeName(tableName)}` : this.escapeName(tableName);
115
+ const setEntries = Object.entries(config.set);
116
+ let paramIdx = 1;
117
+ const setClauses = [];
118
+ const params = [];
119
+ for (const [col, value] of setEntries) {
120
+ setClauses.push(`${this.escapeName(col)} = $${paramIdx++}`);
121
+ params.push(value);
122
+ }
123
+ let sql = `UPDATE ${tableRef} SET ${setClauses.join(", ")}`;
124
+ if (config.where) {
125
+ const whereQuery = config.where.toQuery({
126
+ ...this.getBuildQueryConfig(),
127
+ paramStartIndex: { value: paramIdx }
128
+ });
129
+ sql += ` WHERE ${whereQuery.sql}`;
130
+ params.push(...whereQuery.params);
131
+ }
132
+ if (config.returning && config.returning.length > 0) {
133
+ const retCols = config.returning.map((c) => {
134
+ const tn = c._.tableName || tableName;
135
+ return `${this.escapeName(tn)}.${this.escapeName(c.name)}`;
136
+ });
137
+ sql += ` RETURNING ${retCols.join(", ")}`;
138
+ } else {
139
+ sql += ` RETURNING *`;
140
+ }
141
+ return new SQL([sql]);
142
+ }
143
+ // ---- DELETE ------------------------------------------------------------
144
+ buildDeleteQuery(config) {
145
+ const tableName = config.table?.[/* @__PURE__ */ Symbol.for("name")];
146
+ const schema = config.table?.[/* @__PURE__ */ Symbol.for("schema")];
147
+ const tableRef = schema ? `${this.escapeName(schema)}.${this.escapeName(tableName)}` : this.escapeName(tableName);
148
+ let sql = `DELETE FROM ${tableRef}`;
149
+ let params = [];
150
+ if (config.where) {
151
+ const whereQuery = config.where.toQuery(this.getBuildQueryConfig());
152
+ sql += ` WHERE ${whereQuery.sql}`;
153
+ params = whereQuery.params;
154
+ }
155
+ if (config.returning && config.returning.length > 0) {
156
+ const retCols = config.returning.map((c) => {
157
+ const tn = c._.tableName || tableName;
158
+ return `${this.escapeName(tn)}.${this.escapeName(c.name)}`;
159
+ });
160
+ sql += ` RETURNING ${retCols.join(", ")}`;
161
+ }
162
+ return new SQL([sql]);
163
+ }
164
+ // ---- DDL ---------------------------------------------------------------
165
+ buildCreateTable(config) {
166
+ const tableName = config.table?.[/* @__PURE__ */ Symbol.for("name")];
167
+ const schema = config.table?.[/* @__PURE__ */ Symbol.for("schema")];
168
+ const tableRef = schema ? `${this.escapeName(schema)}.${this.escapeName(tableName)}` : this.escapeName(tableName);
169
+ const ifNotExists = config.ifNotExists ? " IF NOT EXISTS" : "";
170
+ const columns = config.table.getSQLColumns();
171
+ const colDefs = Object.values(columns).map(
172
+ (col) => ` ${this.escapeName(col.name)} ${col.sqlType}`
173
+ );
174
+ const pkCols = [];
175
+ for (const [key, col] of Object.entries(config.table.columns)) {
176
+ if (col.isPrimaryKey) {
177
+ pkCols.push(this.escapeName(col.name));
178
+ }
179
+ }
180
+ if (pkCols.length > 0) {
181
+ colDefs.push(` PRIMARY KEY (${pkCols.join(", ")})`);
182
+ }
183
+ const sql = `CREATE TABLE${ifNotExists} ${tableRef} (
184
+ ${colDefs.join(",\n")}
185
+ )`;
186
+ return new SQL([sql]);
187
+ }
188
+ buildDropTable(config) {
189
+ const tableName = config.table?.[/* @__PURE__ */ Symbol.for("name")];
190
+ const schema = config.table?.[/* @__PURE__ */ Symbol.for("schema")];
191
+ const tableRef = schema ? `${this.escapeName(schema)}.${this.escapeName(tableName)}` : this.escapeName(tableName);
192
+ const ifExists = config.ifExists ? " IF EXISTS" : "";
193
+ return new SQL([`DROP TABLE${ifExists} ${tableRef}`]);
194
+ }
195
+ buildCreateIndex(config) {
196
+ const tableName = config.table?.[/* @__PURE__ */ Symbol.for("name")];
197
+ const schema = config.table?.[/* @__PURE__ */ Symbol.for("schema")];
198
+ const tableRef = schema ? `${this.escapeName(schema)}.${this.escapeName(tableName)}` : this.escapeName(tableName);
199
+ const unique = config.unique ? "UNIQUE " : "";
200
+ const concurrently = config.concurrently ? " CONCURRENTLY " : " ";
201
+ const colNames = config.columns.map((c) => this.escapeName(c.name)).join(", ");
202
+ return new SQL([
203
+ `CREATE${concurrently}INDEX ${this.escapeName(config.name)} ON ${tableRef} (${colNames})`
204
+ ]);
205
+ }
206
+ };
207
+
208
+ // src/pg-core/session.ts
209
+ import { Session } from "@mountsqli/core";
210
+ var PgPreparedQuery = class {
211
+ _query;
212
+ _client;
213
+ _name;
214
+ constructor(client, query, name) {
215
+ this._query = query;
216
+ this._client = client;
217
+ this._name = name;
218
+ }
219
+ async execute(params) {
220
+ return this._client.query(this._query.sql, this._query.params);
221
+ }
222
+ async all(params) {
223
+ const result = await this._client.query(this._query.sql, this._query.params);
224
+ return result.rows;
225
+ }
226
+ async values(params) {
227
+ const result = await this._client.query(this._query.sql, this._query.params);
228
+ return result.rows.map((row) => Object.values(row));
229
+ }
230
+ getQuery() {
231
+ return this._query;
232
+ }
233
+ };
234
+ var PgTransaction = class _PgTransaction extends Session {
235
+ _client;
236
+ _session;
237
+ constructor(client, session, logger) {
238
+ super(logger);
239
+ this._client = client;
240
+ this._session = session;
241
+ this.inTransaction = true;
242
+ }
243
+ async execute(query) {
244
+ return this._client.query(query.sql, query.params);
245
+ }
246
+ prepare(query, name) {
247
+ return new PgPreparedQuery(this._client, query, name);
248
+ }
249
+ async transaction(fn, config) {
250
+ const savepointName = `sp_${Date.now()}`;
251
+ await this._client.query(`SAVEPOINT ${savepointName}`);
252
+ try {
253
+ const tx = new _PgTransaction(this._client, this._session, this.logger);
254
+ const result = await fn(tx);
255
+ await this._client.query(`RELEASE SAVEPOINT ${savepointName}`);
256
+ return result;
257
+ } catch (err) {
258
+ await this._client.query(`ROLLBACK TO SAVEPOINT ${savepointName}`);
259
+ throw err;
260
+ }
261
+ }
262
+ async rollback() {
263
+ await this._client.query("ROLLBACK");
264
+ throw new Error("Transaction rolled back");
265
+ }
266
+ async commit() {
267
+ await this._client.query("COMMIT");
268
+ }
269
+ async setTransactionIsolation(level) {
270
+ await this._client.query(`SET TRANSACTION ISOLATION LEVEL ${level.toUpperCase()}`);
271
+ }
272
+ async dispose() {
273
+ this._client.release();
274
+ }
275
+ };
276
+ var PgSession = class extends Session {
277
+ _pool;
278
+ constructor(pool, logger) {
279
+ super(logger);
280
+ this._pool = pool;
281
+ }
282
+ async execute(query) {
283
+ return this._pool.query(query.sql, query.params);
284
+ }
285
+ prepare(query, name) {
286
+ return new PgPreparedQuery(this._pool, query, name);
287
+ }
288
+ async transaction(fn, config) {
289
+ const client = await this._pool.connect();
290
+ try {
291
+ if (config?.isolationLevel) {
292
+ await client.query(`BEGIN ISOLATION LEVEL ${config.isolationLevel.toUpperCase()}`);
293
+ } else {
294
+ await client.query("BEGIN");
295
+ }
296
+ this.inTransaction = true;
297
+ const tx = new PgTransaction(client, this, this.logger);
298
+ const result = await fn(tx);
299
+ await client.query("COMMIT");
300
+ return result;
301
+ } catch (err) {
302
+ await client.query("ROLLBACK");
303
+ throw err;
304
+ } finally {
305
+ client.release();
306
+ }
307
+ }
308
+ async dispose() {
309
+ await this._pool.end();
310
+ }
311
+ /** Get pool stats */
312
+ getPoolStats() {
313
+ return {
314
+ totalCount: this._pool.totalCount,
315
+ idleCount: this._pool.idleCount,
316
+ waitingCount: this._pool.waitingCount
317
+ };
318
+ }
319
+ };
320
+
321
+ export {
322
+ PgDialect,
323
+ PgPreparedQuery,
324
+ PgTransaction,
325
+ PgSession
326
+ };
@@ -0,0 +1,72 @@
1
+ import {
2
+ PgSession
3
+ } from "./chunk-MU3FLR2D.js";
4
+
5
+ // src/drivers/node-postgres/driver.ts
6
+ import { createLogger } from "@mountsqli/core";
7
+ var NodePostgresDriver = class {
8
+ dialect = "pg";
9
+ _config;
10
+ _pool = null;
11
+ _logger;
12
+ constructor(config) {
13
+ this._config = config;
14
+ this._logger = typeof config.logger === "boolean" ? createLogger({ enabled: config.logger }) : config.logger ?? createLogger({ enabled: false });
15
+ }
16
+ getPool() {
17
+ if (this._pool) return this._pool;
18
+ throw new Error("Driver not connected. Call driver.connect() first.");
19
+ }
20
+ createSession() {
21
+ return new PgSession(this.getPool(), this._logger);
22
+ }
23
+ async connect() {
24
+ const pg = await import("pg");
25
+ const { Pool } = pg;
26
+ if (typeof this._config.connection === "string") {
27
+ this._pool = new Pool({
28
+ connectionString: this._config.connection,
29
+ max: this._config.max ?? 20,
30
+ idleTimeoutMillis: this._config.idleTimeoutMillis ?? 3e4
31
+ });
32
+ } else {
33
+ this._pool = new Pool({
34
+ ...this._config.connection,
35
+ max: this._config.max ?? this._config.connection.max ?? 20,
36
+ idleTimeoutMillis: this._config.idleTimeoutMillis ?? this._config.connection.idleTimeoutMillis ?? 3e4
37
+ });
38
+ }
39
+ }
40
+ async disconnect() {
41
+ if (this._pool) {
42
+ await this._pool.end();
43
+ this._pool = null;
44
+ }
45
+ }
46
+ async ping() {
47
+ try {
48
+ const pool = this.getPool();
49
+ await pool.query("SELECT 1");
50
+ return true;
51
+ } catch {
52
+ return false;
53
+ }
54
+ }
55
+ /** Get pool stats */
56
+ getPoolStats() {
57
+ const pool = this.getPool();
58
+ return {
59
+ totalCount: pool.totalCount,
60
+ idleCount: pool.idleCount,
61
+ waitingCount: pool.waitingCount
62
+ };
63
+ }
64
+ };
65
+ function createNodePostgresDriver(config) {
66
+ return new NodePostgresDriver(config);
67
+ }
68
+
69
+ export {
70
+ NodePostgresDriver,
71
+ createNodePostgresDriver
72
+ };
@@ -0,0 +1,64 @@
1
+ import {
2
+ PgSession
3
+ } from "./chunk-MU3FLR2D.js";
4
+
5
+ // src/drivers/postgres-js/driver.ts
6
+ import { createLogger } from "@mountsqli/core";
7
+ var PostgresJsDriver = class {
8
+ dialect = "pg";
9
+ _config;
10
+ _client = null;
11
+ _logger;
12
+ constructor(config) {
13
+ this._config = config;
14
+ this._logger = typeof config.logger === "boolean" ? createLogger({ enabled: config.logger }) : config.logger ?? createLogger({ enabled: false });
15
+ }
16
+ getClient() {
17
+ if (this._client) return this._client;
18
+ throw new Error("Driver not connected. Call driver.connect() first.");
19
+ }
20
+ createSession() {
21
+ const client = this.getClient();
22
+ const pool = {
23
+ query: async (text, params) => {
24
+ const result = await client.unsafe(text, params ?? []);
25
+ return { rows: result, rowCount: result.length };
26
+ },
27
+ connect: async () => client,
28
+ end: async () => client.end(),
29
+ totalCount: 1,
30
+ idleCount: 1,
31
+ waitingCount: 0
32
+ };
33
+ return new PgSession(pool, this._logger);
34
+ }
35
+ async connect() {
36
+ const postgres = await import("postgres");
37
+ this._client = postgres.default(this._config.connection, {
38
+ max: this._config.max ?? 20
39
+ });
40
+ }
41
+ async disconnect() {
42
+ if (this._client) {
43
+ await this._client.end();
44
+ this._client = null;
45
+ }
46
+ }
47
+ async ping() {
48
+ try {
49
+ const client = this.getClient();
50
+ await client.unsafe("SELECT 1");
51
+ return true;
52
+ } catch {
53
+ return false;
54
+ }
55
+ }
56
+ };
57
+ function createPostgresJsDriver(config) {
58
+ return new PostgresJsDriver(config);
59
+ }
60
+
61
+ export {
62
+ PostgresJsDriver,
63
+ createPostgresJsDriver
64
+ };
@@ -0,0 +1,30 @@
1
+ import { Driver, Logger } from '@mountsqli/core';
2
+ import { P as PgSession } from './session-cHNTeFK8.js';
3
+
4
+ /**
5
+ * postgres.js driver — wraps the `postgres` package.
6
+ */
7
+
8
+ interface PostgresJsDriverConfig {
9
+ /** Connection string */
10
+ connection: string;
11
+ /** Logger */
12
+ logger?: Logger | boolean;
13
+ /** Max connections */
14
+ max?: number;
15
+ }
16
+ declare class PostgresJsDriver implements Driver {
17
+ readonly dialect: "pg";
18
+ private _config;
19
+ private _client;
20
+ private _logger;
21
+ constructor(config: PostgresJsDriverConfig);
22
+ private getClient;
23
+ createSession(): PgSession;
24
+ connect(): Promise<void>;
25
+ disconnect(): Promise<void>;
26
+ ping(): Promise<boolean>;
27
+ }
28
+ declare function createPostgresJsDriver(config: PostgresJsDriverConfig): PostgresJsDriver;
29
+
30
+ export { type PostgresJsDriverConfig as P, PostgresJsDriver as a, createPostgresJsDriver as c };
@@ -0,0 +1,51 @@
1
+ import { Driver, Logger } from '@mountsqli/core';
2
+ import { P as PgSession } from './session-cHNTeFK8.js';
3
+
4
+ /**
5
+ * node-postgres driver — wraps `pg` Pool/Client.
6
+ */
7
+
8
+ interface NodePostgresDriverConfig {
9
+ /** Connection string or pool config */
10
+ connection: string | PgPoolConfig;
11
+ /** Logger */
12
+ logger?: Logger | boolean;
13
+ /** Pool size (default 20) */
14
+ max?: number;
15
+ /** Idle timeout in ms */
16
+ idleTimeoutMillis?: number;
17
+ }
18
+ interface PgPoolConfig {
19
+ host?: string;
20
+ port?: number;
21
+ database?: string;
22
+ user?: string;
23
+ password?: string;
24
+ max?: number;
25
+ idleTimeoutMillis?: number;
26
+ connectionString?: string;
27
+ ssl?: boolean | {
28
+ rejectUnauthorized?: boolean;
29
+ };
30
+ }
31
+ declare class NodePostgresDriver implements Driver {
32
+ readonly dialect: "pg";
33
+ private _config;
34
+ private _pool;
35
+ private _logger;
36
+ constructor(config: NodePostgresDriverConfig);
37
+ private getPool;
38
+ createSession(): PgSession;
39
+ connect(): Promise<void>;
40
+ disconnect(): Promise<void>;
41
+ ping(): Promise<boolean>;
42
+ /** Get pool stats */
43
+ getPoolStats(): {
44
+ totalCount: number;
45
+ idleCount: number;
46
+ waitingCount: number;
47
+ };
48
+ }
49
+ declare function createNodePostgresDriver(config: NodePostgresDriverConfig): NodePostgresDriver;
50
+
51
+ export { type NodePostgresDriverConfig as N, NodePostgresDriver as a, createNodePostgresDriver as c };
@@ -0,0 +1,16 @@
1
+ import { DatabaseConfig, Database } from '@mountsqli/core';
2
+ import { N as NodePostgresDriverConfig } from '../../driver-CmcFDC6F.js';
3
+ export { a as NodePostgresDriver } from '../../driver-CmcFDC6F.js';
4
+ export { P as PgSession, a as PgTransaction } from '../../session-cHNTeFK8.js';
5
+
6
+ /**
7
+ * node-postgres driver entry point.
8
+ *
9
+ * Usage:
10
+ * import { mountsqli } from '@mountsqli/pg/node-postgres';
11
+ * const db = mountsqli('postgresql://user:pass@localhost:5432/mydb');
12
+ */
13
+
14
+ declare function mountsqli(connectionOrConfig: string | NodePostgresDriverConfig, options?: DatabaseConfig): Database;
15
+
16
+ export { NodePostgresDriverConfig, mountsqli };
@@ -0,0 +1,28 @@
1
+ import {
2
+ NodePostgresDriver
3
+ } from "../../chunk-NLTVBDSL.js";
4
+ import {
5
+ PgDialect,
6
+ PgSession,
7
+ PgTransaction
8
+ } from "../../chunk-MU3FLR2D.js";
9
+
10
+ // src/drivers/node-postgres/index.ts
11
+ import { Database, createLogger } from "@mountsqli/core";
12
+ function mountsqli(connectionOrConfig, options) {
13
+ const logger = typeof options?.logger === "boolean" ? createLogger({ enabled: options.logger }) : options?.logger ?? createLogger({ enabled: false });
14
+ const driverConfig = typeof connectionOrConfig === "string" ? { connection: connectionOrConfig, logger } : { ...connectionOrConfig, logger };
15
+ const driver = new NodePostgresDriver(driverConfig);
16
+ const dialect = new PgDialect();
17
+ const session = driver.createSession();
18
+ return new Database(session, dialect, {
19
+ ...options,
20
+ logger
21
+ });
22
+ }
23
+ export {
24
+ NodePostgresDriver,
25
+ PgSession,
26
+ PgTransaction,
27
+ mountsqli
28
+ };
@@ -0,0 +1,12 @@
1
+ import { DatabaseConfig, Database } from '@mountsqli/core';
2
+ import { P as PostgresJsDriverConfig } from '../../driver-BkwJwjPG.js';
3
+ export { a as PostgresJsDriver } from '../../driver-BkwJwjPG.js';
4
+ import '../../session-cHNTeFK8.js';
5
+
6
+ /**
7
+ * postgres.js driver entry point.
8
+ */
9
+
10
+ declare function mountsqli(connectionOrConfig: string | PostgresJsDriverConfig, options?: DatabaseConfig): Database;
11
+
12
+ export { PostgresJsDriverConfig, mountsqli };
@@ -0,0 +1,21 @@
1
+ import {
2
+ PostgresJsDriver
3
+ } from "../../chunk-ZXWSBMW5.js";
4
+ import {
5
+ PgDialect
6
+ } from "../../chunk-MU3FLR2D.js";
7
+
8
+ // src/drivers/postgres-js/index.ts
9
+ import { Database, createLogger } from "@mountsqli/core";
10
+ function mountsqli(connectionOrConfig, options) {
11
+ const logger = typeof options?.logger === "boolean" ? createLogger({ enabled: options.logger }) : options?.logger ?? createLogger({ enabled: false });
12
+ const driverConfig = typeof connectionOrConfig === "string" ? { connection: connectionOrConfig, logger } : { ...connectionOrConfig, logger };
13
+ const driver = new PostgresJsDriver(driverConfig);
14
+ const dialect = new PgDialect();
15
+ const session = driver.createSession();
16
+ return new Database(session, dialect, { ...options, logger });
17
+ }
18
+ export {
19
+ PostgresJsDriver,
20
+ mountsqli
21
+ };
@@ -0,0 +1,174 @@
1
+ import { Table, TableConfig, Column, boolean, doublePrecision, integer, json, numeric, real, serial, text, timestamp, uuid, AnyColumn, SQL, Dialect } from '@mountsqli/core';
2
+ export { Many, ManyConfig, One, OneConfig, TimestampConfig, bigSerial, boolean, doublePrecision, integer, json, numeric, real, relations, serial, text, timestamp, uuid } from '@mountsqli/core';
3
+ export { b as PgPreparedQuery, P as PgSession, a as PgTransaction } from './session-cHNTeFK8.js';
4
+ export { a as NodePostgresDriver, N as NodePostgresDriverConfig, c as createNodePostgresDriver } from './driver-CmcFDC6F.js';
5
+ export { a as PostgresJsDriver, P as PostgresJsDriverConfig, c as createPostgresJsDriver } from './driver-BkwJwjPG.js';
6
+
7
+ /**
8
+ * pgTable — factory function for defining PostgreSQL tables.
9
+ */
10
+
11
+ declare class PgTable extends Table<TableConfig & {
12
+ dialect: 'pg';
13
+ }> {
14
+ }
15
+ type PgTableColumns = Record<string, Column>;
16
+ declare function pgTable<TColumns extends PgTableColumns>(name: string, columns: TColumns, config?: {
17
+ schema?: string;
18
+ }): PgTable & {
19
+ columns: TColumns;
20
+ };
21
+
22
+ /**
23
+ * PostgreSQL-specific column types.
24
+ * Re-exports core columns and adds PG-only types.
25
+ */
26
+
27
+ declare const pgInteger: typeof integer;
28
+ declare const pgText: typeof text;
29
+ declare const pgBoolean: typeof boolean;
30
+ declare const pgUuid: typeof uuid;
31
+ declare const pgTimestamp: typeof timestamp;
32
+ declare const pgJson: typeof json;
33
+ declare const pgSerial: typeof serial;
34
+ declare const pgReal: typeof real;
35
+ declare const pgDoublePrecision: typeof doublePrecision;
36
+ declare const pgNumeric: typeof numeric;
37
+
38
+ /**
39
+ * Index builder — define indexes on PG tables.
40
+ */
41
+
42
+ interface PgIndexConfig {
43
+ name: string;
44
+ table: Table;
45
+ columns: AnyColumn[];
46
+ unique?: boolean;
47
+ concurrently?: boolean;
48
+ where?: string;
49
+ }
50
+ declare function pgIndex(name: string): {
51
+ on(table: Table): {
52
+ columns(...columns: AnyColumn[]): {
53
+ unique(): PgIndexConfig;
54
+ concurrently(): PgIndexConfig;
55
+ where(condition: string): PgIndexConfig;
56
+ build(): PgIndexConfig;
57
+ };
58
+ };
59
+ };
60
+ declare function pgUniqueIndex(name: string): {
61
+ on(table: Table): {
62
+ columns(...columns: AnyColumn[]): {
63
+ unique(): PgIndexConfig;
64
+ concurrently(): PgIndexConfig;
65
+ where(condition: string): PgIndexConfig;
66
+ build(): PgIndexConfig;
67
+ };
68
+ };
69
+ };
70
+
71
+ /**
72
+ * Foreign key builder — define FK constraints on PG tables.
73
+ */
74
+
75
+ interface PgForeignKeyConfig {
76
+ name?: string;
77
+ table: Table;
78
+ foreignColumns: AnyColumn[];
79
+ refTable: Table;
80
+ refColumns: AnyColumn[];
81
+ onDelete?: 'cascade' | 'restrict' | 'set null' | 'set default' | 'no action';
82
+ onUpdate?: 'cascade' | 'restrict' | 'set null' | 'set default' | 'no action';
83
+ }
84
+ declare function pgForeignKey(config: PgForeignKeyConfig): PgForeignKeyConfig;
85
+
86
+ /**
87
+ * CHECK constraint builder for PG tables.
88
+ */
89
+
90
+ interface PgCheckConfig {
91
+ name?: string;
92
+ table: Table;
93
+ expression: SQL;
94
+ }
95
+ declare function pgCheck(config: PgCheckConfig): PgCheckConfig;
96
+
97
+ /**
98
+ * View / Materialized View support for PostgreSQL.
99
+ */
100
+
101
+ declare class PgView extends Table<TableConfig & {
102
+ dialect: 'pg';
103
+ }> {
104
+ readonly query: SQL;
105
+ constructor(name: string, query: SQL, schema?: string);
106
+ }
107
+ declare function pgView(name: string, query: SQL, config?: {
108
+ schema?: string;
109
+ }): PgView;
110
+ declare class PgMaterializedView extends PgView {
111
+ }
112
+ declare function pgMaterializedView(name: string, query: SQL, config?: {
113
+ schema?: string;
114
+ }): PgMaterializedView;
115
+
116
+ /**
117
+ * PgDialect — SQL generation for PostgreSQL.
118
+ */
119
+
120
+ declare class PgDialect extends Dialect {
121
+ readonly dialect: "pg";
122
+ escapeName(name: string): string;
123
+ escapeParam(index: number): string;
124
+ buildSelectQuery(config: {
125
+ table: Table;
126
+ columns: AnyColumn[];
127
+ where?: SQL;
128
+ orderBy?: SQL[];
129
+ groupBy?: SQL[];
130
+ having?: SQL;
131
+ limit?: number;
132
+ offset?: number;
133
+ joins?: Array<{
134
+ table: Table;
135
+ on: SQL;
136
+ type: 'inner' | 'left' | 'right' | 'full';
137
+ }>;
138
+ distinct?: boolean;
139
+ }): SQL;
140
+ buildInsertQuery(config: {
141
+ table: Table;
142
+ values: Record<string, unknown>[];
143
+ onConflict?: SQL;
144
+ returning?: AnyColumn[];
145
+ }): SQL;
146
+ buildUpdateQuery(config: {
147
+ table: Table;
148
+ set: Record<string, unknown>;
149
+ where?: SQL;
150
+ returning?: AnyColumn[];
151
+ }): SQL;
152
+ buildDeleteQuery(config: {
153
+ table: Table;
154
+ where?: SQL;
155
+ returning?: AnyColumn[];
156
+ }): SQL;
157
+ buildCreateTable(config: {
158
+ table: Table;
159
+ ifNotExists?: boolean;
160
+ }): SQL;
161
+ buildDropTable(config: {
162
+ table: Table;
163
+ ifExists?: boolean;
164
+ }): SQL;
165
+ buildCreateIndex(config: {
166
+ name: string;
167
+ table: Table;
168
+ columns: AnyColumn[];
169
+ unique?: boolean;
170
+ concurrently?: boolean;
171
+ }): SQL;
172
+ }
173
+
174
+ export { type PgCheckConfig, PgDialect, type PgForeignKeyConfig, type PgIndexConfig, PgMaterializedView, PgTable, type PgTableColumns, PgView, pgBoolean, pgCheck, pgDoublePrecision, pgForeignKey, pgIndex, pgInteger, pgJson, pgMaterializedView, pgNumeric, pgReal, pgSerial, pgTable, pgText, pgTimestamp, pgUniqueIndex, pgUuid, pgView };
package/dist/index.js ADDED
@@ -0,0 +1,159 @@
1
+ import {
2
+ NodePostgresDriver,
3
+ createNodePostgresDriver
4
+ } from "./chunk-NLTVBDSL.js";
5
+ import {
6
+ PostgresJsDriver,
7
+ createPostgresJsDriver
8
+ } from "./chunk-ZXWSBMW5.js";
9
+ import {
10
+ PgDialect,
11
+ PgPreparedQuery,
12
+ PgSession,
13
+ PgTransaction
14
+ } from "./chunk-MU3FLR2D.js";
15
+
16
+ // src/pg-core/table.ts
17
+ import { Table } from "@mountsqli/core";
18
+ var PgTable = class extends Table {
19
+ };
20
+ function pgTable(name, columns, config) {
21
+ const table = new PgTable(
22
+ name,
23
+ config?.schema,
24
+ name
25
+ );
26
+ for (const [key, col] of Object.entries(columns)) {
27
+ table.columns[key] = col;
28
+ col.tableName = name;
29
+ }
30
+ const result = table;
31
+ result.columns = columns;
32
+ return result;
33
+ }
34
+
35
+ // src/pg-core/columns/index.ts
36
+ import {
37
+ integer as coreInteger,
38
+ text as coreText,
39
+ boolean as coreBoolean,
40
+ uuid as coreUuid,
41
+ timestamp as coreTimestamp,
42
+ json as coreJson,
43
+ serial as coreSerial,
44
+ real as coreReal,
45
+ doublePrecision as coreDoublePrecision,
46
+ numeric as coreNumeric
47
+ } from "@mountsqli/core";
48
+ import { bigSerial } from "@mountsqli/core";
49
+ var pgInteger = coreInteger;
50
+ var pgText = coreText;
51
+ var pgBoolean = coreBoolean;
52
+ var pgUuid = coreUuid;
53
+ var pgTimestamp = coreTimestamp;
54
+ var pgJson = coreJson;
55
+ var pgSerial = coreSerial;
56
+ var pgReal = coreReal;
57
+ var pgDoublePrecision = coreDoublePrecision;
58
+ var pgNumeric = coreNumeric;
59
+
60
+ // src/pg-core/relations.ts
61
+ import { relations } from "@mountsqli/core";
62
+
63
+ // src/pg-core/indexes.ts
64
+ function pgIndex(name) {
65
+ return {
66
+ on(table) {
67
+ return {
68
+ columns(...columns) {
69
+ return {
70
+ unique() {
71
+ return { name, table, columns, unique: true };
72
+ },
73
+ concurrently() {
74
+ return { name, table, columns, concurrently: true };
75
+ },
76
+ where(condition) {
77
+ return { name, table, columns, where: condition };
78
+ },
79
+ build() {
80
+ return { name, table, columns };
81
+ }
82
+ };
83
+ }
84
+ };
85
+ }
86
+ };
87
+ }
88
+ function pgUniqueIndex(name) {
89
+ return pgIndex(name);
90
+ }
91
+
92
+ // src/pg-core/foreign-keys.ts
93
+ function pgForeignKey(config) {
94
+ return config;
95
+ }
96
+
97
+ // src/pg-core/checks.ts
98
+ function pgCheck(config) {
99
+ return config;
100
+ }
101
+
102
+ // src/pg-core/views.ts
103
+ import { Table as Table2 } from "@mountsqli/core";
104
+ var PgView = class extends Table2 {
105
+ query;
106
+ constructor(name, query, schema) {
107
+ super(name, schema, name);
108
+ this.query = query;
109
+ }
110
+ };
111
+ function pgView(name, query, config) {
112
+ return new PgView(name, query, config?.schema);
113
+ }
114
+ var PgMaterializedView = class extends PgView {
115
+ };
116
+ function pgMaterializedView(name, query, config) {
117
+ return new PgMaterializedView(name, query, config?.schema);
118
+ }
119
+ export {
120
+ NodePostgresDriver,
121
+ PgDialect,
122
+ PgMaterializedView,
123
+ PgPreparedQuery,
124
+ PgSession,
125
+ PgTransaction,
126
+ PgView,
127
+ PostgresJsDriver,
128
+ bigSerial,
129
+ coreBoolean as boolean,
130
+ createNodePostgresDriver,
131
+ createPostgresJsDriver,
132
+ coreDoublePrecision as doublePrecision,
133
+ coreInteger as integer,
134
+ coreJson as json,
135
+ coreNumeric as numeric,
136
+ pgBoolean,
137
+ pgCheck,
138
+ pgDoublePrecision,
139
+ pgForeignKey,
140
+ pgIndex,
141
+ pgInteger,
142
+ pgJson,
143
+ pgMaterializedView,
144
+ pgNumeric,
145
+ pgReal,
146
+ pgSerial,
147
+ pgTable,
148
+ pgText,
149
+ pgTimestamp,
150
+ pgUniqueIndex,
151
+ pgUuid,
152
+ pgView,
153
+ coreReal as real,
154
+ relations,
155
+ coreSerial as serial,
156
+ coreText as text,
157
+ coreTimestamp as timestamp,
158
+ coreUuid as uuid
159
+ };
@@ -0,0 +1,63 @@
1
+ import { Session, Logger, QueryWithTypings, PreparedQuery, TransactionConfig } from '@mountsqli/core';
2
+
3
+ /**
4
+ * PgSession — PostgreSQL session implementation.
5
+ * Wraps a native pg Pool or Client and implements the Session interface.
6
+ */
7
+
8
+ interface PgPool {
9
+ query(text: string, params?: unknown[]): Promise<{
10
+ rows: any[];
11
+ rowCount: number;
12
+ }>;
13
+ connect(): Promise<PgClient>;
14
+ end(): Promise<void>;
15
+ totalCount: number;
16
+ idleCount: number;
17
+ waitingCount: number;
18
+ }
19
+ interface PgClient {
20
+ query(text: string, params?: unknown[]): Promise<{
21
+ rows: any[];
22
+ rowCount: number;
23
+ }>;
24
+ release(): void;
25
+ }
26
+ declare class PgPreparedQuery<T = any> implements PreparedQuery<T> {
27
+ private _query;
28
+ private _client;
29
+ private _name?;
30
+ constructor(client: PgPool | PgClient, query: QueryWithTypings, name?: string);
31
+ execute(params?: Record<string, unknown>): Promise<T>;
32
+ all(params?: Record<string, unknown>): Promise<T[]>;
33
+ values(params?: Record<string, unknown>): Promise<unknown[][]>;
34
+ getQuery(): QueryWithTypings;
35
+ }
36
+ declare class PgTransaction extends Session {
37
+ private _client;
38
+ private _session;
39
+ constructor(client: PgClient, session: PgSession, logger: Logger);
40
+ execute<T>(query: QueryWithTypings): Promise<T>;
41
+ prepare<T>(query: QueryWithTypings, name?: string): PreparedQuery<T>;
42
+ transaction<T>(fn: (tx: any) => Promise<T>, config?: TransactionConfig): Promise<T>;
43
+ rollback(): Promise<never>;
44
+ commit(): Promise<void>;
45
+ setTransactionIsolation(level: string): Promise<void>;
46
+ dispose(): Promise<void>;
47
+ }
48
+ declare class PgSession extends Session {
49
+ private _pool;
50
+ constructor(pool: PgPool, logger: Logger);
51
+ execute<T>(query: QueryWithTypings): Promise<T>;
52
+ prepare<T>(query: QueryWithTypings, name?: string): PreparedQuery<T>;
53
+ transaction<T>(fn: (tx: any) => Promise<T>, config?: TransactionConfig): Promise<T>;
54
+ dispose(): Promise<void>;
55
+ /** Get pool stats */
56
+ getPoolStats(): {
57
+ totalCount: number;
58
+ idleCount: number;
59
+ waitingCount: number;
60
+ };
61
+ }
62
+
63
+ export { PgSession as P, PgTransaction as a, PgPreparedQuery as b };
package/package.json ADDED
@@ -0,0 +1,45 @@
1
+ {
2
+ "name": "@mountsqli/pg",
3
+ "version": "0.1.0",
4
+ "type": "module",
5
+ "exports": {
6
+ ".": {
7
+ "import": "./dist/index.js",
8
+ "types": "./dist/index.d.ts"
9
+ },
10
+ "./node-postgres": {
11
+ "import": "./dist/drivers/node-postgres/index.js",
12
+ "types": "./dist/drivers/node-postgres/index.d.ts"
13
+ },
14
+ "./postgres-js": {
15
+ "import": "./dist/drivers/postgres-js/index.js",
16
+ "types": "./dist/drivers/postgres-js/index.d.ts"
17
+ }
18
+ },
19
+ "main": "./dist/index.js",
20
+ "types": "./dist/index.d.ts",
21
+ "sideEffects": false,
22
+ "files": ["dist", "LICENSE", "README.md"],
23
+ "scripts": {
24
+ "build": "tsup src/index.ts src/drivers/node-postgres/index.ts src/drivers/postgres-js/index.ts --format esm --dts --clean",
25
+ "dev": "tsup src/index.ts --format esm --dts --watch",
26
+ "clean": "rm -rf dist"
27
+ },
28
+ "dependencies": {
29
+ "@mountsqli/core": "workspace:*",
30
+ "@mountsqli/shared": "workspace:*"
31
+ },
32
+ "peerDependencies": {
33
+ "pg": "^8.0.0",
34
+ "postgres": "^3.0.0"
35
+ },
36
+ "peerDependenciesMeta": {
37
+ "pg": { "optional": true },
38
+ "postgres": { "optional": true }
39
+ },
40
+ "devDependencies": {
41
+ "typescript": "^5.7.0",
42
+ "tsup": "^8.0.0",
43
+ "vitest": "^3.0.0"
44
+ }
45
+ }