@vrplatform/kysely 1.2.28 → 1.2.30
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/build/.data.tar +0 -0
- package/build/main/index.d.ts +14 -4
- package/build/main/index.js +44 -12
- package/build/main/index.js.map +1 -1
- package/build/main/local/generate.d.ts +3 -0
- package/build/main/{local.js → local/generate.js} +10 -12
- package/build/main/local/generate.js.map +1 -0
- package/build/main/local/index.d.ts +5 -0
- package/build/main/local/index.js +36 -0
- package/build/main/local/index.js.map +1 -0
- package/build/main/tsconfig.main.tsbuildinfo +1 -1
- package/build/module/index.d.ts +14 -4
- package/build/module/index.js +44 -12
- package/build/module/index.js.map +1 -1
- package/build/module/local/generate.d.ts +3 -0
- package/build/module/{local.js → local/generate.js} +9 -11
- package/build/module/local/generate.js.map +1 -0
- package/build/module/local/index.d.ts +5 -0
- package/build/module/local/index.js +32 -0
- package/build/module/local/index.js.map +1 -0
- package/build/module/tsconfig.esm.tsbuildinfo +1 -1
- package/package.json +3 -3
- package/src/index.ts +58 -19
- package/src/{local.ts → local/generate.ts} +9 -11
- package/src/local/index.ts +40 -0
- package/build/main/local.d.ts +0 -3
- package/build/main/local.js.map +0 -1
- package/build/main/v0.generated.d.ts +0 -1996
- package/build/main/v0.generated.js +0 -7
- package/build/main/v0.generated.js.map +0 -1
- package/build/module/local.d.ts +0 -3
- package/build/module/local.js.map +0 -1
- package/build/module/v0.generated.d.ts +0 -1996
- package/build/module/v0.generated.js +0 -6
- package/build/module/v0.generated.js.map +0 -1
package/build/.data.tar
CHANGED
|
Binary file
|
package/build/main/index.d.ts
CHANGED
|
@@ -6,15 +6,25 @@ export * from './v1.generated';
|
|
|
6
6
|
import type { DB } from './v1.generated';
|
|
7
7
|
export type Transaction = T<DB>;
|
|
8
8
|
export { sql } from 'kysely';
|
|
9
|
+
type PgOpt = {
|
|
10
|
+
forceDisableSSL?: boolean;
|
|
11
|
+
retries?: false | number;
|
|
12
|
+
};
|
|
9
13
|
export type Kysely = K<DB>;
|
|
10
14
|
export type Postgres = Sql;
|
|
15
|
+
/**
|
|
16
|
+
* @deprecated This method is deprecated in favor of the useAsyncKysely method.
|
|
17
|
+
*/
|
|
11
18
|
export declare function useKysely(postgres: Sql, options?: {
|
|
12
19
|
log?: boolean;
|
|
13
20
|
}): K<DB>;
|
|
14
|
-
export declare function useAsyncPostgres(connectionString: string,
|
|
15
|
-
export declare function useAsyncKysely(connectionString: string,
|
|
16
|
-
|
|
17
|
-
|
|
21
|
+
export declare function useAsyncPostgres(connectionString: string, opt?: PgOpt): Promise<postgres.Sql<{}>>;
|
|
22
|
+
export declare function useAsyncKysely(connectionString: string, opt?: PgOpt): Promise<K<DB>>;
|
|
23
|
+
/**
|
|
24
|
+
* @deprecated This method is deprecated in favor of the useAsyncKysely method.
|
|
25
|
+
*/
|
|
26
|
+
export declare function usePostgres(connectionString?: string, opt?: Pick<PgOpt, 'forceDisableSSL'>): postgres.Sql<{}>;
|
|
27
|
+
export declare function forceCloseAllPostgres(timeoutMs?: number): Promise<void>;
|
|
18
28
|
export declare class DatabaseError extends Error {
|
|
19
29
|
constructor(message: string, cause: any);
|
|
20
30
|
}
|
package/build/main/index.js
CHANGED
|
@@ -34,27 +34,55 @@ __exportStar(require("./v1.generated"), exports);
|
|
|
34
34
|
const node_path_1 = require("node:path");
|
|
35
35
|
var kysely_2 = require("kysely");
|
|
36
36
|
Object.defineProperty(exports, "sql", { enumerable: true, get: function () { return kysely_2.sql; } });
|
|
37
|
+
/**
|
|
38
|
+
* @deprecated This method is deprecated in favor of the useAsyncKysely method.
|
|
39
|
+
*/
|
|
37
40
|
function useKysely(postgres, options = {}) {
|
|
38
|
-
|
|
41
|
+
console.debug('Creating Kysely instance');
|
|
42
|
+
const kysely = new kysely_1.Kysely({
|
|
39
43
|
dialect: new kysely_postgres_js_1.PostgresJSDialect({
|
|
40
44
|
postgres,
|
|
41
45
|
}),
|
|
42
46
|
plugins: [new kysely_1.CamelCasePlugin()],
|
|
43
47
|
log: options?.log ? ['query', 'error'] : undefined,
|
|
44
48
|
});
|
|
49
|
+
const destroy = kysely.destroy;
|
|
50
|
+
kysely.destroy = async () => {
|
|
51
|
+
console.debug('Closing Kysely connection');
|
|
52
|
+
return destroy();
|
|
53
|
+
};
|
|
54
|
+
return kysely;
|
|
45
55
|
}
|
|
46
|
-
|
|
56
|
+
const _connections = [];
|
|
57
|
+
async function useAsyncPostgres(connectionString, opt) {
|
|
58
|
+
const delayMs = 2500;
|
|
59
|
+
const retries = opt?.retries === false ? 0 : opt?.retries || 3;
|
|
60
|
+
const ssl = opt?.forceDisableSSL !== true;
|
|
61
|
+
console.debug(`Creating Postgres connection with ${retries} retries and ssl=${ssl}`);
|
|
62
|
+
if (_connections.length > 0) {
|
|
63
|
+
console.warn(`We already have ${_connections.length} Postgres connections`);
|
|
64
|
+
}
|
|
47
65
|
for (let attempt = 1; attempt <= retries; attempt++) {
|
|
48
66
|
try {
|
|
49
67
|
const sql = (0, postgres_1.default)(connectionString, {
|
|
50
68
|
ssl: ssl ? 'require' : false,
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
69
|
+
// connect_timeout: 10
|
|
70
|
+
// idle_timeout: 10
|
|
71
|
+
// disable prepare statements since we use pgbouncer
|
|
54
72
|
prepare: false,
|
|
73
|
+
connect_timeout: 10,
|
|
74
|
+
idle_timeout: 60,
|
|
55
75
|
});
|
|
56
76
|
await sql `select 1`;
|
|
57
|
-
|
|
77
|
+
try {
|
|
78
|
+
// connect 30s, idle 60s, max lifetime 45min, statement 60s, lock 10s, log_min_duration 20s, log_lock_waits off
|
|
79
|
+
await sql `set statement_timeout to '30s';`;
|
|
80
|
+
await sql `set lock_timeout to '10s';`;
|
|
81
|
+
}
|
|
82
|
+
catch (e) {
|
|
83
|
+
console.warn('Failed to set statement timeout, continuing', e);
|
|
84
|
+
}
|
|
85
|
+
_connections.push(sql);
|
|
58
86
|
return sql;
|
|
59
87
|
}
|
|
60
88
|
catch (err) {
|
|
@@ -67,22 +95,26 @@ async function useAsyncPostgres(connectionString, ssl, retries = 5, delayMs = 25
|
|
|
67
95
|
}
|
|
68
96
|
throw new Error('Unable to connect to Postgres');
|
|
69
97
|
}
|
|
70
|
-
async function useAsyncKysely(connectionString,
|
|
71
|
-
const sql = await useAsyncPostgres(connectionString,
|
|
98
|
+
async function useAsyncKysely(connectionString, opt) {
|
|
99
|
+
const sql = await useAsyncPostgres(connectionString, opt);
|
|
72
100
|
return useKysely(sql);
|
|
73
101
|
}
|
|
74
|
-
|
|
75
|
-
|
|
102
|
+
/**
|
|
103
|
+
* @deprecated This method is deprecated in favor of the useAsyncKysely method.
|
|
104
|
+
*/
|
|
105
|
+
function usePostgres(connectionString, opt) {
|
|
76
106
|
if (!connectionString)
|
|
77
107
|
throw new Error('No connection string');
|
|
108
|
+
const ssl = opt?.forceDisableSSL !== true;
|
|
78
109
|
const pg = (0, postgres_1.default)(connectionString, {
|
|
79
110
|
ssl: ssl ? 'require' : false,
|
|
80
111
|
});
|
|
81
|
-
|
|
112
|
+
_connections.push(pg);
|
|
82
113
|
return pg;
|
|
83
114
|
}
|
|
84
115
|
async function forceCloseAllPostgres(timeoutMs = 5000) {
|
|
85
|
-
|
|
116
|
+
await Promise.all(_connections.map((pg) => pg.end({ timeout: timeoutMs }).catch(() => undefined)));
|
|
117
|
+
_connections.length = 0;
|
|
86
118
|
}
|
|
87
119
|
class DatabaseError extends Error {
|
|
88
120
|
constructor(message, cause) {
|
package/build/main/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"src/","sources":["index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"src/","sources":["index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;AAqCA,8BAiBC;AAGD,4CA6CC;AAED,wCAGC;AAKD,kCAWC;AAED,sDAOC;AAYD,8BA+BC;AA/K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CAAC,CAAC,CAAC;QACrC,OAAO,UAAU,CAAC,KAAK,CAAC;QACxB,KAAK,CAAC,KAAK,GAAG,UAAU,CAAC;QACzB,OAAO,CAAC,KAAK,CAAC,qBAAqB,SAAS,EAAE,EAAE,IAAA,sBAAc,EAAC,KAAK,CAAC,CAAC,CAAC;QACvE,OAAO,CAAC,GAAG,CACT,IAAI,SAAS,qBAAqB,IAAI,CAAC,KAAK,CAAC,WAAW,CAAC,GAAG,EAAE,GAAG,GAAG,CAAC,IAAI,CAC1E,CAAC;QACF,MAAM,KAAK,CAAC;IACd,CAAC;AACH,CAAC","sourcesContent":["import { serializeError } from '@finalytic/utils';\nimport { CamelCasePlugin, Kysely as K, type Transaction as T } from 'kysely';\nimport { PostgresJSDialect } from 'kysely-postgres-js';\nimport postgres, { type Sql } from 'postgres';\n\nexport type {\n ColumnType,\n Expression,\n ExpressionBuilder,\n ExpressionOrFactory,\n Generated,\n Insertable,\n JSONColumnType,\n OperandExpression,\n Selectable,\n SqlBool,\n Updateable,\n} from 'kysely';\nexport { jsonArrayFrom } from 'kysely/helpers/postgres';\nexport * from './v1.generated';\n\nimport { join, relative } from 'node:path';\nimport type { DB } from './v1.generated';\n\nexport type Transaction = T<DB>;\nexport { sql } from 'kysely';\n\ntype PgOpt = {\n forceDisableSSL?: boolean;\n retries?: false | number;\n};\n\nexport type Kysely = K<DB>;\nexport type Postgres = Sql;\n/**\n * @deprecated This method is deprecated in favor of the useAsyncKysely method.\n */\nexport function useKysely(postgres: Sql, options: { log?: boolean } = {}) {\n console.debug('Creating Kysely instance');\n const kysely = new K<DB>({\n dialect: new PostgresJSDialect({\n postgres,\n }),\n plugins: [new CamelCasePlugin()],\n log: options?.log ? ['query', 'error'] : undefined,\n });\n\n const destroy = kysely.destroy;\n kysely.destroy = async () => {\n console.debug('Closing Kysely connection');\n return destroy();\n };\n\n return kysely;\n}\n\nconst _connections: postgres.Sql[] = [];\nexport async function useAsyncPostgres(connectionString: string, opt?: PgOpt) {\n const delayMs = 2500;\n const retries = opt?.retries === false ? 0 : opt?.retries || 3;\n const ssl = opt?.forceDisableSSL !== true;\n\n console.debug(\n `Creating Postgres connection with ${retries} retries and ssl=${ssl}`\n );\n if (_connections.length > 0) {\n console.warn(`We already have ${_connections.length} Postgres connections`);\n }\n\n for (let attempt = 1; attempt <= retries; attempt++) {\n try {\n const sql = postgres(connectionString, {\n ssl: ssl ? 'require' : false,\n // connect_timeout: 10\n // idle_timeout: 10\n // disable prepare statements since we use pgbouncer\n prepare: false,\n connect_timeout: 10,\n idle_timeout: 60,\n });\n\n await sql`select 1`;\n try {\n // connect 30s, idle 60s, max lifetime 45min, statement 60s, lock 10s, log_min_duration 20s, log_lock_waits off\n await sql`set statement_timeout to '30s';`;\n await sql`set lock_timeout to '10s';`;\n } catch (e) {\n console.warn('Failed to set statement timeout, continuing', e);\n }\n\n _connections.push(sql);\n return sql;\n } catch (err) {\n if (attempt === retries) throw err;\n console.warn(\n `Postgres connection failed (attempt ${attempt}), retrying...`\n );\n console.error('error', err);\n await new Promise((res) => setTimeout(res, delayMs));\n }\n }\n throw new Error('Unable to connect to Postgres');\n}\n\nexport async function useAsyncKysely(connectionString: string, opt?: PgOpt) {\n const sql = await useAsyncPostgres(connectionString, opt);\n return useKysely(sql);\n}\n\n/**\n * @deprecated This method is deprecated in favor of the useAsyncKysely method.\n */\nexport function usePostgres(\n connectionString?: string,\n opt?: Pick<PgOpt, 'forceDisableSSL'>\n) {\n if (!connectionString) throw new Error('No connection string');\n const ssl = opt?.forceDisableSSL !== true;\n const pg = postgres(connectionString, {\n ssl: ssl ? 'require' : false,\n });\n _connections.push(pg);\n return pg;\n}\n\nexport async function forceCloseAllPostgres(timeoutMs = 5000) {\n await Promise.all(\n _connections.map((pg) =>\n pg.end({ timeout: timeoutMs }).catch(() => undefined)\n )\n );\n _connections.length = 0;\n}\n\nexport class DatabaseError extends Error {\n constructor(message: string, cause: any) {\n super(message);\n this.cause = cause;\n }\n}\n\nconst dirname =\n typeof __dirname === 'string' ? join(__dirname, '../../..') : '';\n\nexport async function withStack<T>(a: Promise<T>) {\n // skip if we can't get the stack, probably in a worker\n if (!dirname) return await a;\n\n const now = performance.now();\n const error = new DatabaseError('Error in execute', undefined);\n const stack = error.stack?.split('\\n').slice(3) || undefined;\n const firstLine =\n stack?.length && stack[0]?.includes('(') && dirname\n ? relative(dirname, stack[0].split('(')[1].split(')')[0])\n : undefined;\n try {\n const result = await a;\n console.log(\n `[${firstLine}] Execution time: ${Math.round(performance.now() - now)}ms`\n );\n return result;\n } catch (e: any) {\n if (stack) error.stack = stack.join('\\n').trim();\n else error.stack = e.stack;\n // error.cause = e;\n error.message = e.message;\n const serialized = serializeError(e);\n delete serialized.stack;\n error.cause = serialized;\n console.error(`Error in execute: ${firstLine}`, serializeError(error));\n console.log(\n `[${firstLine}] Execution time: ${Math.round(performance.now() - now)}ms`\n );\n throw error;\n }\n}\n"]}
|
|
@@ -36,7 +36,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
36
36
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
37
37
|
};
|
|
38
38
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
39
|
-
exports.
|
|
39
|
+
exports.createLocalKysely = createLocalKysely;
|
|
40
40
|
const node_fs_1 = require("node:fs");
|
|
41
41
|
const promises_1 = require("node:fs/promises");
|
|
42
42
|
const path = __importStar(require("node:path"));
|
|
@@ -45,15 +45,14 @@ const pglite_1 = require("@electric-sql/pglite");
|
|
|
45
45
|
const kysely_1 = require("kysely");
|
|
46
46
|
const kysely_codegen_1 = __importDefault(require("kysely-codegen"));
|
|
47
47
|
const kysely_pglite_1 = require("kysely-pglite");
|
|
48
|
-
|
|
49
|
-
async function migrate(client) {
|
|
48
|
+
async function migrate(root, client) {
|
|
50
49
|
console.log('migrating pglite ....');
|
|
51
50
|
const glob = new Bun.Glob('initial/*.sql');
|
|
52
51
|
for await (const migration of glob.scan(root)) {
|
|
53
52
|
await client.exec(await Bun.file((0, node_path_1.join)(root, migration)).text());
|
|
54
53
|
}
|
|
55
54
|
}
|
|
56
|
-
async function migrateKysely(kysely) {
|
|
55
|
+
async function migrateKysely(root, kysely) {
|
|
57
56
|
console.log('init migrating kysely ....');
|
|
58
57
|
const migrator = new kysely_1.Migrator({
|
|
59
58
|
db: kysely,
|
|
@@ -86,13 +85,12 @@ async function migrateKysely(kysely) {
|
|
|
86
85
|
process.exit(1);
|
|
87
86
|
}
|
|
88
87
|
}
|
|
89
|
-
|
|
90
|
-
const dumpFile = (async () => {
|
|
88
|
+
async function generateDump(root, dumpPath) {
|
|
91
89
|
const dataExists = await (0, promises_1.exists)(dumpPath).catch(() => false);
|
|
92
90
|
if (!dataExists) {
|
|
93
91
|
console.log('Creating initial dump');
|
|
94
92
|
const main = new pglite_1.PGlite();
|
|
95
|
-
await migrate(main).catch(async (err) => {
|
|
93
|
+
await migrate(root, main).catch(async (err) => {
|
|
96
94
|
console.error('failed to migrate initial dump');
|
|
97
95
|
await Bun.write('../logs/migrate-initial-dump.json', JSON.stringify(err, null, 2));
|
|
98
96
|
process.exit(1);
|
|
@@ -102,7 +100,7 @@ const dumpFile = (async () => {
|
|
|
102
100
|
dialect,
|
|
103
101
|
plugins: [new kysely_1.CamelCasePlugin()],
|
|
104
102
|
});
|
|
105
|
-
await migrateKysely(kysely).catch(() => {
|
|
103
|
+
await migrateKysely(root, kysely).catch(() => {
|
|
106
104
|
console.error('failed to migrate kysely');
|
|
107
105
|
process.exit(1);
|
|
108
106
|
});
|
|
@@ -129,11 +127,11 @@ const dumpFile = (async () => {
|
|
|
129
127
|
return content;
|
|
130
128
|
}
|
|
131
129
|
return Bun.file(dumpPath);
|
|
132
|
-
}
|
|
133
|
-
async function
|
|
130
|
+
}
|
|
131
|
+
async function createLocalKysely(root, dumpPath) {
|
|
134
132
|
let isDestroyed = false;
|
|
135
133
|
const now = performance.now();
|
|
136
|
-
const dump = await
|
|
134
|
+
const dump = await generateDump(root, dumpPath);
|
|
137
135
|
const pglite = new pglite_1.PGlite({ loadDataDir: dump });
|
|
138
136
|
// warm up
|
|
139
137
|
await pglite.sql `SELECT 1`;
|
|
@@ -155,4 +153,4 @@ async function useLocalKysely() {
|
|
|
155
153
|
console.log(`Database initialized: ${Math.round(performance.now() - now)}ms`);
|
|
156
154
|
return kysely;
|
|
157
155
|
}
|
|
158
|
-
//# sourceMappingURL=
|
|
156
|
+
//# sourceMappingURL=generate.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"generate.js","sourceRoot":"src/","sources":["local/generate.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0GA,8CA8BC;AAxID,qCAAyC;AACzC,+CAA0C;AAC1C,gDAAkC;AAClC,yCAAiC;AACjC,iDAA8C;AAC9C,mCAKgB;AAChB,oEAAqC;AACrC,iDAA6C;AAG7C,KAAK,UAAU,OAAO,CAAC,IAAY,EAAE,MAAc;IACjD,OAAO,CAAC,GAAG,CAAC,uBAAuB,CAAC,CAAC;IACrC,MAAM,IAAI,GAAG,IAAI,GAAG,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC;IAC3C,IAAI,KAAK,EAAE,MAAM,SAAS,IAAI,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;QAC9C,MAAM,MAAM,CAAC,IAAI,CAAC,MAAM,GAAG,CAAC,IAAI,CAAC,IAAA,gBAAI,EAAC,IAAI,EAAE,SAAS,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC;IAClE,CAAC;AACH,CAAC;AAED,KAAK,UAAU,aAAa,CAAC,IAAY,EAAE,MAAmB;IAC5D,OAAO,CAAC,GAAG,CAAC,4BAA4B,CAAC,CAAC;IAC1C,MAAM,QAAQ,GAAG,IAAI,iBAAQ,CAAC;QAC5B,EAAE,EAAE,MAAM;QACV,oBAAoB,EAAE,MAAM;QAC5B,kBAAkB,EAAE,kBAAkB;QACtC,sBAAsB,EAAE,u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AC1B,IAAI,WAAW;YAAE,OAAO;QACxB,WAAW,GAAG,IAAI,CAAC;QACnB,MAAM,WAAW,GAAG,WAAW,CAAC,GAAG,EAAE,CAAC;QACtC,MAAM,eAAe,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC;QAC/C,MAAM,MAAM,CAAC,KAAK,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC;QAC5C,OAAO,CAAC,GAAG,CACT,uBAAuB,IAAI,CAAC,KAAK,CAAC,WAAW,CAAC,GAAG,EAAE,GAAG,WAAW,CAAC,IAAI,CACvE,CAAC;IACJ,CAAC,CAAC;IAEF,OAAO,CAAC,GAAG,CAAC,yBAAyB,IAAI,CAAC,KAAK,CAAC,WAAW,CAAC,GAAG,EAAE,GAAG,GAAG,CAAC,IAAI,CAAC,CAAC;IAE9E,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import { promises as fs } from 'node:fs';\nimport { exists } from 'node:fs/promises';\nimport * as path from 'node:path';\nimport { join } from 'node:path';\nimport { PGlite } from '@electric-sql/pglite';\nimport {\n CamelCasePlugin,\n FileMigrationProvider,\n Kysely,\n Migrator,\n} from 'kysely';\nimport codegen from 'kysely-codegen';\nimport { KyselyPGlite } from 'kysely-pglite';\nimport type { DB } from '../v1.generated';\n\nasync function migrate(root: string, client: PGlite) {\n console.log('migrating pglite ....');\n const glob = new Bun.Glob('initial/*.sql');\n for await (const migration of glob.scan(root)) {\n await client.exec(await Bun.file(join(root, migration)).text());\n }\n}\n\nasync function migrateKysely(root: string, kysely: Kysely<any>) {\n console.log('init migrating kysely ....');\n const migrator = new Migrator({\n db: kysely,\n migrationTableSchema: 'core',\n migrationTableName: 'kysely_migration',\n migrationLockTableName: 'kysely_migration_lock',\n provider: new FileMigrationProvider({\n fs,\n path,\n // This needs to be an absolute path.\n migrationFolder: path.join(root, 'migrations'),\n }),\n });\n\n console.log('migrating kysely ....');\n const { error, results } = await migrator.migrateToLatest().catch(() => {\n console.error('failed to migrate');\n process.exit(1);\n });\n\n for (const it of results ?? []) {\n if (it.status === 'Success') {\n console.log(`migration \"${it.migrationName}\" was executed successfully`);\n } else if (it.status === 'Error') {\n console.error(`failed to execute migration \"${it.migrationName}\"`);\n }\n }\n\n if (error) {\n console.error('failed to migrate');\n console.error(error);\n process.exit(1);\n }\n}\n\nasync function generateDump(root: string, dumpPath: string) {\n const dataExists = await exists(dumpPath).catch(() => false);\n if (!dataExists) {\n console.log('Creating initial dump');\n const main = new PGlite();\n await migrate(root, main).catch(async (err) => {\n console.error('failed to migrate initial dump');\n await Bun.write(\n '../logs/migrate-initial-dump.json',\n JSON.stringify(err as any, null, 2)\n );\n process.exit(1);\n });\n const { dialect } = new KyselyPGlite(main);\n const kysely = new Kysely<DB>({\n dialect,\n plugins: [new CamelCasePlugin()],\n });\n await migrateKysely(root, kysely).catch(() => {\n console.error('failed to migrate kysely');\n process.exit(1);\n });\n await codegen\n .generate({\n db: kysely,\n outFile: path.join(root, 'src/v1.generated.ts'),\n defaultSchemas: ['xxx'],\n camelCase: true,\n dialect: codegen.getDialect('postgres'),\n })\n .catch(() => {\n console.error('failed to generate kysely');\n process.exit(1);\n });\n const content = await main.dumpDataDir('none').catch(() => {\n console.error('failed to dump data');\n process.exit(1);\n });\n await Bun.write(dumpPath, content).catch(() => {\n console.error('failed to write dump');\n process.exit(1);\n });\n return content;\n }\n return Bun.file(dumpPath);\n}\n\nexport async function createLocalKysely(root: string, dumpPath: string) {\n let isDestroyed = false;\n const now = performance.now();\n\n const dump = await generateDump(root, dumpPath);\n\n const pglite = new PGlite({ loadDataDir: dump });\n // warm up\n await pglite.sql`SELECT 1`;\n const { dialect } = new KyselyPGlite(pglite);\n const kysely = new Kysely<DB>({\n dialect,\n plugins: [new CamelCasePlugin()],\n });\n\n const originalDestroy = kysely.destroy.bind(kysely);\n kysely.destroy = async () => {\n if (isDestroyed) return;\n isDestroyed = true;\n const destroyTime = performance.now();\n await originalDestroy().catch(() => undefined);\n await pglite.close().catch(() => undefined);\n console.log(\n `Database destroyed: ${Math.round(performance.now() - destroyTime)}ms`\n );\n };\n\n console.log(`Database initialized: ${Math.round(performance.now() - now)}ms`);\n\n return kysely;\n}\n"]}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.dumpPath = exports.root = void 0;
|
|
4
|
+
exports.useLocalKysely = useLocalKysely;
|
|
5
|
+
const node_path_1 = require("node:path");
|
|
6
|
+
const pglite_1 = require("@electric-sql/pglite");
|
|
7
|
+
const kysely_1 = require("kysely");
|
|
8
|
+
const kysely_pglite_1 = require("kysely-pglite");
|
|
9
|
+
exports.root = (0, node_path_1.join)(__dirname, '../..');
|
|
10
|
+
exports.dumpPath = (0, node_path_1.join)(exports.root, '.data.tar');
|
|
11
|
+
async function useLocalKysely() {
|
|
12
|
+
let isDestroyed = false;
|
|
13
|
+
const now = performance.now();
|
|
14
|
+
const dump = Bun.file(exports.dumpPath);
|
|
15
|
+
const pglite = new pglite_1.PGlite({ loadDataDir: dump });
|
|
16
|
+
// warm up
|
|
17
|
+
await pglite.sql `SELECT 1`;
|
|
18
|
+
const { dialect } = new kysely_pglite_1.KyselyPGlite(pglite);
|
|
19
|
+
const kysely = new kysely_1.Kysely({
|
|
20
|
+
dialect,
|
|
21
|
+
plugins: [new kysely_1.CamelCasePlugin()],
|
|
22
|
+
});
|
|
23
|
+
const originalDestroy = kysely.destroy.bind(kysely);
|
|
24
|
+
kysely.destroy = async () => {
|
|
25
|
+
if (isDestroyed)
|
|
26
|
+
return;
|
|
27
|
+
isDestroyed = true;
|
|
28
|
+
const destroyTime = performance.now();
|
|
29
|
+
await originalDestroy().catch(() => undefined);
|
|
30
|
+
await pglite.close().catch(() => undefined);
|
|
31
|
+
console.log(`Database destroyed: ${Math.round(performance.now() - destroyTime)}ms`);
|
|
32
|
+
};
|
|
33
|
+
console.log(`Database initialized: ${Math.round(performance.now() - now)}ms`);
|
|
34
|
+
return kysely;
|
|
35
|
+
}
|
|
36
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"src/","sources":["local/index.ts"],"names":[],"mappings":";;;AASA,wCA8BC;AAvCD,yCAAiC;AACjC,iDAA8C;AAC9C,mCAAiD;AACjD,iDAA6C;AAGhC,QAAA,IAAI,GAAG,IAAA,gBAAI,EAAC,SAAS,EAAE,OAAO,CAAC,CAAC;AAChC,QAAA,QAAQ,GAAG,IAAA,gBAAI,EAAC,YAAI,EAAE,WAAW,CAAC,CAAC;AAEzC,KAAK,UAAU,cAAc;IAClC,IAAI,WAAW,GAAG,KAAK,CAAC;IACxB,MAAM,GAAG,GAAG,WAAW,CAAC,GAAG,EAAE,CAAC;IAE9B,MAAM,IAAI,GAAG,GAAG,CAAC,IAAI,CAAC,gBAAQ,CAAC,CAAC;IAEhC,MAAM,MAAM,GAAG,IAAI,eAAM,CAAC,EAAE,WAAW,EAAE,IAAI,EAAE,CAAC,CAAC;IACjD,UAAU;IACV,MAAM,MAAM,CAAC,GAAG,CAAA,UAAU,CAAC;IAC3B,MAAM,EAAE,OAAO,EAAE,GAAG,IAAI,4BAAY,CAAC,MAAM,CAAC,CAAC;IAC7C,MAAM,MAAM,GAAG,IAAI,eAAM,CAAK;QAC5B,OAAO;QACP,OAAO,EAAE,CAAC,IAAI,wBAAe,EAAE,CAAC;KACjC,CAAC,CAAC;IAEH,MAAM,eAAe,GAAG,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IACpD,MAAM,CAAC,OAAO,GAAG,KAAK,IAAI,EAAE;QAC1B,IAAI,WAAW;YAAE,OAAO;QACxB,WAAW,GAAG,IAAI,CAAC;QACnB,MAAM,WAAW,GAAG,WAAW,CAAC,GAAG,EAAE,CAAC;QACtC,MAAM,eAAe,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC;QAC/C,MAAM,MAAM,CAAC,KAAK,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC;QAC5C,OAAO,CAAC,GAAG,CACT,uBAAuB,IAAI,CAAC,KAAK,CAAC,WAAW,CAAC,GAAG,EAAE,GAAG,WAAW,CAAC,IAAI,CACvE,CAAC;IACJ,CAAC,CAAC;IAEF,OAAO,CAAC,GAAG,CAAC,yBAAyB,IAAI,CAAC,KAAK,CAAC,WAAW,CAAC,GAAG,EAAE,GAAG,GAAG,CAAC,IAAI,CAAC,CAAC;IAE9E,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import { join } from 'node:path';\nimport { PGlite } from '@electric-sql/pglite';\nimport { CamelCasePlugin, Kysely } from 'kysely';\nimport { KyselyPGlite } from 'kysely-pglite';\nimport type { DB } from '../v1.generated';\n\nexport const root = join(__dirname, '../..');\nexport const dumpPath = join(root, '.data.tar');\n\nexport async function useLocalKysely() {\n let isDestroyed = false;\n const now = performance.now();\n\n const dump = Bun.file(dumpPath);\n\n const pglite = new PGlite({ loadDataDir: dump });\n // warm up\n await pglite.sql`SELECT 1`;\n const { dialect } = new KyselyPGlite(pglite);\n const kysely = new Kysely<DB>({\n dialect,\n plugins: [new CamelCasePlugin()],\n });\n\n const originalDestroy = kysely.destroy.bind(kysely);\n kysely.destroy = async () => {\n if (isDestroyed) return;\n isDestroyed = true;\n const destroyTime = performance.now();\n await originalDestroy().catch(() => undefined);\n await pglite.close().catch(() => undefined);\n console.log(\n `Database destroyed: ${Math.round(performance.now() - destroyTime)}ms`\n );\n };\n\n console.log(`Database initialized: ${Math.round(performance.now() - now)}ms`);\n\n return kysely;\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"root":["../../src/index.ts","../../src/
|
|
1
|
+
{"root":["../../src/index.ts","../../src/test.ts","../../src/v1.generated.ts","../../src/local/generate.ts","../../src/local/index.ts"],"version":"5.9.3"}
|
package/build/module/index.d.ts
CHANGED
|
@@ -6,15 +6,25 @@ export * from './v1.generated';
|
|
|
6
6
|
import type { DB } from './v1.generated';
|
|
7
7
|
export type Transaction = T<DB>;
|
|
8
8
|
export { sql } from 'kysely';
|
|
9
|
+
type PgOpt = {
|
|
10
|
+
forceDisableSSL?: boolean;
|
|
11
|
+
retries?: false | number;
|
|
12
|
+
};
|
|
9
13
|
export type Kysely = K<DB>;
|
|
10
14
|
export type Postgres = Sql;
|
|
15
|
+
/**
|
|
16
|
+
* @deprecated This method is deprecated in favor of the useAsyncKysely method.
|
|
17
|
+
*/
|
|
11
18
|
export declare function useKysely(postgres: Sql, options?: {
|
|
12
19
|
log?: boolean;
|
|
13
20
|
}): K<DB>;
|
|
14
|
-
export declare function useAsyncPostgres(connectionString: string,
|
|
15
|
-
export declare function useAsyncKysely(connectionString: string,
|
|
16
|
-
|
|
17
|
-
|
|
21
|
+
export declare function useAsyncPostgres(connectionString: string, opt?: PgOpt): Promise<postgres.Sql<{}>>;
|
|
22
|
+
export declare function useAsyncKysely(connectionString: string, opt?: PgOpt): Promise<K<DB>>;
|
|
23
|
+
/**
|
|
24
|
+
* @deprecated This method is deprecated in favor of the useAsyncKysely method.
|
|
25
|
+
*/
|
|
26
|
+
export declare function usePostgres(connectionString?: string, opt?: Pick<PgOpt, 'forceDisableSSL'>): postgres.Sql<{}>;
|
|
27
|
+
export declare function forceCloseAllPostgres(timeoutMs?: number): Promise<void>;
|
|
18
28
|
export declare class DatabaseError extends Error {
|
|
19
29
|
constructor(message: string, cause: any);
|
|
20
30
|
}
|
package/build/module/index.js
CHANGED
|
@@ -6,27 +6,55 @@ export { jsonArrayFrom } from 'kysely/helpers/postgres';
|
|
|
6
6
|
export * from './v1.generated';
|
|
7
7
|
import { join, relative } from 'node:path';
|
|
8
8
|
export { sql } from 'kysely';
|
|
9
|
+
/**
|
|
10
|
+
* @deprecated This method is deprecated in favor of the useAsyncKysely method.
|
|
11
|
+
*/
|
|
9
12
|
export function useKysely(postgres, options = {}) {
|
|
10
|
-
|
|
13
|
+
console.debug('Creating Kysely instance');
|
|
14
|
+
const kysely = new K({
|
|
11
15
|
dialect: new PostgresJSDialect({
|
|
12
16
|
postgres,
|
|
13
17
|
}),
|
|
14
18
|
plugins: [new CamelCasePlugin()],
|
|
15
19
|
log: options?.log ? ['query', 'error'] : undefined,
|
|
16
20
|
});
|
|
21
|
+
const destroy = kysely.destroy;
|
|
22
|
+
kysely.destroy = async () => {
|
|
23
|
+
console.debug('Closing Kysely connection');
|
|
24
|
+
return destroy();
|
|
25
|
+
};
|
|
26
|
+
return kysely;
|
|
17
27
|
}
|
|
18
|
-
|
|
28
|
+
const _connections = [];
|
|
29
|
+
export async function useAsyncPostgres(connectionString, opt) {
|
|
30
|
+
const delayMs = 2500;
|
|
31
|
+
const retries = opt?.retries === false ? 0 : opt?.retries || 3;
|
|
32
|
+
const ssl = opt?.forceDisableSSL !== true;
|
|
33
|
+
console.debug(`Creating Postgres connection with ${retries} retries and ssl=${ssl}`);
|
|
34
|
+
if (_connections.length > 0) {
|
|
35
|
+
console.warn(`We already have ${_connections.length} Postgres connections`);
|
|
36
|
+
}
|
|
19
37
|
for (let attempt = 1; attempt <= retries; attempt++) {
|
|
20
38
|
try {
|
|
21
39
|
const sql = postgres(connectionString, {
|
|
22
40
|
ssl: ssl ? 'require' : false,
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
41
|
+
// connect_timeout: 10
|
|
42
|
+
// idle_timeout: 10
|
|
43
|
+
// disable prepare statements since we use pgbouncer
|
|
26
44
|
prepare: false,
|
|
45
|
+
connect_timeout: 10,
|
|
46
|
+
idle_timeout: 60,
|
|
27
47
|
});
|
|
28
48
|
await sql `select 1`;
|
|
29
|
-
|
|
49
|
+
try {
|
|
50
|
+
// connect 30s, idle 60s, max lifetime 45min, statement 60s, lock 10s, log_min_duration 20s, log_lock_waits off
|
|
51
|
+
await sql `set statement_timeout to '30s';`;
|
|
52
|
+
await sql `set lock_timeout to '10s';`;
|
|
53
|
+
}
|
|
54
|
+
catch (e) {
|
|
55
|
+
console.warn('Failed to set statement timeout, continuing', e);
|
|
56
|
+
}
|
|
57
|
+
_connections.push(sql);
|
|
30
58
|
return sql;
|
|
31
59
|
}
|
|
32
60
|
catch (err) {
|
|
@@ -39,22 +67,26 @@ export async function useAsyncPostgres(connectionString, ssl, retries = 5, delay
|
|
|
39
67
|
}
|
|
40
68
|
throw new Error('Unable to connect to Postgres');
|
|
41
69
|
}
|
|
42
|
-
export async function useAsyncKysely(connectionString,
|
|
43
|
-
const sql = await useAsyncPostgres(connectionString,
|
|
70
|
+
export async function useAsyncKysely(connectionString, opt) {
|
|
71
|
+
const sql = await useAsyncPostgres(connectionString, opt);
|
|
44
72
|
return useKysely(sql);
|
|
45
73
|
}
|
|
46
|
-
|
|
47
|
-
|
|
74
|
+
/**
|
|
75
|
+
* @deprecated This method is deprecated in favor of the useAsyncKysely method.
|
|
76
|
+
*/
|
|
77
|
+
export function usePostgres(connectionString, opt) {
|
|
48
78
|
if (!connectionString)
|
|
49
79
|
throw new Error('No connection string');
|
|
80
|
+
const ssl = opt?.forceDisableSSL !== true;
|
|
50
81
|
const pg = postgres(connectionString, {
|
|
51
82
|
ssl: ssl ? 'require' : false,
|
|
52
83
|
});
|
|
53
|
-
|
|
84
|
+
_connections.push(pg);
|
|
54
85
|
return pg;
|
|
55
86
|
}
|
|
56
87
|
export async function forceCloseAllPostgres(timeoutMs = 5000) {
|
|
57
|
-
|
|
88
|
+
await Promise.all(_connections.map((pg) => pg.end({ timeout: timeoutMs }).catch(() => undefined)));
|
|
89
|
+
_connections.length = 0;
|
|
58
90
|
}
|
|
59
91
|
export class DatabaseError extends Error {
|
|
60
92
|
constructor(message, cause) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"src/","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAClD,O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AC;QACF,OAAO,MAAM,CAAC;IAChB,CAAC;IAAC,OAAO,CAAM,EAAE,CAAC;QAChB,IAAI,KAAK;YAAE,KAAK,CAAC,KAAK,GAAG,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,CAAC;;YAC5C,KAAK,CAAC,KAAK,GAAG,CAAC,CAAC,KAAK,CAAC;QAC3B,mBAAmB;QACnB,KAAK,CAAC,OAAO,GAAG,CAAC,CAAC,OAAO,CAAC;QAC1B,MAAM,UAAU,GAAG,cAAc,CAAC,CAAC,CAAC,CAAC;QACrC,OAAO,UAAU,CAAC,KAAK,CAAC;QACxB,KAAK,CAAC,KAAK,GAAG,UAAU,CAAC;QACzB,OAAO,CAAC,KAAK,CAAC,qBAAqB,SAAS,EAAE,EAAE,cAAc,CAAC,KAAK,CAAC,CAAC,CAAC;QACvE,OAAO,CAAC,GAAG,CACT,IAAI,SAAS,qBAAqB,IAAI,CAAC,KAAK,CAAC,WAAW,CAAC,GAAG,EAAE,GAAG,GAAG,CAAC,IAAI,CAC1E,CAAC;QACF,MAAM,KAAK,CAAC;IACd,CAAC;AACH,CAAC","sourcesContent":["import { serializeError } from '@finalytic/utils';\nimport { CamelCasePlugin, Kysely as K, type Transaction as T } from 'kysely';\nimport { PostgresJSDialect } from 'kysely-postgres-js';\nimport postgres, { type Sql } from 'postgres';\n\nexport type {\n ColumnType,\n Expression,\n ExpressionBuilder,\n ExpressionOrFactory,\n Generated,\n Insertable,\n JSONColumnType,\n OperandExpression,\n Selectable,\n SqlBool,\n Updateable,\n} from 'kysely';\nexport { jsonArrayFrom } from 'kysely/helpers/postgres';\nexport * from './v1.generated';\n\nimport { join, relative } from 'node:path';\nimport type { DB } from './v1.generated';\n\nexport type Transaction = T<DB>;\nexport { sql } from 'kysely';\n\nexport type Kysely = K<DB>;\nexport type Postgres = Sql;\nexport function useKysely(postgres: Sql, options: { log?: boolean } = {}) {\n return new K<DB>({\n dialect: new PostgresJSDialect({\n postgres,\n }),\n plugins: [new CamelCasePlugin()],\n log: options?.log ? ['query', 'error'] : undefined,\n });\n}\n\nexport async function useAsyncPostgres(\n connectionString: string,\n ssl?: boolean,\n retries = 5,\n delayMs = 2500\n) {\n for (let attempt = 1; attempt <= retries; attempt++) {\n try {\n const sql = postgres(connectionString, {\n ssl: ssl ? 'require' : false,\n connection: {\n statement_timeout: 30_000,\n },\n prepare: false,\n });\n\n await sql`select 1`;\n\n connections.push(sql);\n\n return sql;\n } catch (err) {\n if (attempt === retries) throw err;\n console.warn(\n `Postgres connection failed (attempt ${attempt}), retrying...`\n );\n console.error('error', err);\n await new Promise((res) => setTimeout(res, delayMs));\n }\n }\n throw new Error('Unable to connect to Postgres');\n}\n\nexport async function useAsyncKysely(connectionString: string, ssl?: boolean) {\n const sql = await useAsyncPostgres(connectionString, ssl);\n return useKysely(sql);\n}\n\nconst connections: postgres.Sql<any>[] = [];\nexport function usePostgres(connectionString?: string, ssl?: boolean) {\n if (!connectionString) throw new Error('No connection string');\n const pg = postgres(connectionString, {\n ssl: ssl ? 'require' : false,\n });\n connections.push(pg);\n return pg;\n}\n\nexport async function forceCloseAllPostgres(timeoutMs = 5000) {\n return await Promise.all(\n connections.map((pg) =>\n pg.end({ timeout: timeoutMs }).catch(() => undefined)\n )\n );\n}\n\nexport class DatabaseError extends Error {\n constructor(message: string, cause: any) {\n super(message);\n this.cause = cause;\n }\n}\n\nconst dirname =\n typeof __dirname === 'string' ? join(__dirname, '../../..') : '';\n\nexport async function withStack<T>(a: Promise<T>) {\n // skip if we can't get the stack, probably in a worker\n if (!dirname) return await a;\n\n const now = performance.now();\n const error = new DatabaseError('Error in execute', undefined);\n const stack = error.stack?.split('\\n').slice(3) || undefined;\n const firstLine =\n stack?.length && stack[0]?.includes('(') && dirname\n ? relative(dirname, stack[0].split('(')[1].split(')')[0])\n : undefined;\n try {\n const result = await a;\n console.log(\n `[${firstLine}] Execution time: ${Math.round(performance.now() - now)}ms`\n );\n return result;\n } catch (e: any) {\n if (stack) error.stack = stack.join('\\n').trim();\n else error.stack = e.stack;\n // error.cause = e;\n error.message = e.message;\n const serialized = serializeError(e);\n delete serialized.stack;\n error.cause = serialized;\n console.error(`Error in execute: ${firstLine}`, serializeError(error));\n console.log(\n `[${firstLine}] Execution time: ${Math.round(performance.now() - now)}ms`\n );\n throw error;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"src/","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAClD,OAAO,EAAE,eAAe,EAAE,MAAM,IAAI,CAAC,EAAyB,MAAM,QAAQ,CAAC;AAC7E,OAAO,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AACvD,OAAO,QAAsB,MAAM,UAAU,CAAC;AAe9C,OAAO,EAAE,aAAa,EAAE,MAAM,yBAAyB,CAAC;AACxD,cAAc,gBAAgB,CAAC;AAE/B,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AAI3C,OAAO,EAAE,GAAG,EAAE,MAAM,QAAQ,CAAC;AAS7B;;GAEG;AACH,MAAM,UAAU,SAAS,CAAC,QAAa,EAAE,UAA6B,EAAE;IACtE,OAAO,CAAC,KAAK,CAAC,0BAA0B,CAAC,CAAC;IAC1C,MAAM,MAAM,GAAG,IAAI,CAAC,CAAK;QACvB,OAAO,EAAE,IAAI,iBAAiB,CAAC;YAC7B,QAAQ;SACT,CAAC;QACF,OAAO,EAAE,CAAC,IAAI,eAAe,EAAE,CAAC;QAChC,GAAG,EAAE,OAAO,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC,SAAS;KACnD,CAAC,CAAC;IAEH,MAAM,OAAO,GAAG,MAAM,CAAC,OAAO,CAAC;IAC/B,MAAM,CAAC,OAAO,GAAG,KAAK,IAAI,EAAE;QAC1B,OAAO,CAAC,KAAK,CAAC,2BAA2B,CA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,CAAC;IAChB,IAAI,CAAC;QACH,MAAM,MAAM,GAAG,MAAM,CAAC,CAAC;QACvB,OAAO,CAAC,GAAG,CACT,IAAI,SAAS,qBAAqB,IAAI,CAAC,KAAK,CAAC,WAAW,CAAC,GAAG,EAAE,GAAG,GAAG,CAAC,IAAI,CAC1E,CAAC;QACF,OAAO,MAAM,CAAC;IAChB,CAAC;IAAC,OAAO,CAAM,EAAE,CAAC;QAChB,IAAI,KAAK;YAAE,KAAK,CAAC,KAAK,GAAG,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,CAAC;;YAC5C,KAAK,CAAC,KAAK,GAAG,CAAC,CAAC,KAAK,CAAC;QAC3B,mBAAmB;QACnB,KAAK,CAAC,OAAO,GAAG,CAAC,CAAC,OAAO,CAAC;QAC1B,MAAM,UAAU,GAAG,cAAc,CAAC,CAAC,CAAC,CAAC;QACrC,OAAO,UAAU,CAAC,KAAK,CAAC;QACxB,KAAK,CAAC,KAAK,GAAG,UAAU,CAAC;QACzB,OAAO,CAAC,KAAK,CAAC,qBAAqB,SAAS,EAAE,EAAE,cAAc,CAAC,KAAK,CAAC,CAAC,CAAC;QACvE,OAAO,CAAC,GAAG,CACT,IAAI,SAAS,qBAAqB,IAAI,CAAC,KAAK,CAAC,WAAW,CAAC,GAAG,EAAE,GAAG,GAAG,CAAC,IAAI,CAC1E,CAAC;QACF,MAAM,KAAK,CAAC;IACd,CAAC;AACH,CAAC","sourcesContent":["import { serializeError } from '@finalytic/utils';\nimport { CamelCasePlugin, Kysely as K, type Transaction as T } from 'kysely';\nimport { PostgresJSDialect } from 'kysely-postgres-js';\nimport postgres, { type Sql } from 'postgres';\n\nexport type {\n ColumnType,\n Expression,\n ExpressionBuilder,\n ExpressionOrFactory,\n Generated,\n Insertable,\n JSONColumnType,\n OperandExpression,\n Selectable,\n SqlBool,\n Updateable,\n} from 'kysely';\nexport { jsonArrayFrom } from 'kysely/helpers/postgres';\nexport * from './v1.generated';\n\nimport { join, relative } from 'node:path';\nimport type { DB } from './v1.generated';\n\nexport type Transaction = T<DB>;\nexport { sql } from 'kysely';\n\ntype PgOpt = {\n forceDisableSSL?: boolean;\n retries?: false | number;\n};\n\nexport type Kysely = K<DB>;\nexport type Postgres = Sql;\n/**\n * @deprecated This method is deprecated in favor of the useAsyncKysely method.\n */\nexport function useKysely(postgres: Sql, options: { log?: boolean } = {}) {\n console.debug('Creating Kysely instance');\n const kysely = new K<DB>({\n dialect: new PostgresJSDialect({\n postgres,\n }),\n plugins: [new CamelCasePlugin()],\n log: options?.log ? ['query', 'error'] : undefined,\n });\n\n const destroy = kysely.destroy;\n kysely.destroy = async () => {\n console.debug('Closing Kysely connection');\n return destroy();\n };\n\n return kysely;\n}\n\nconst _connections: postgres.Sql[] = [];\nexport async function useAsyncPostgres(connectionString: string, opt?: PgOpt) {\n const delayMs = 2500;\n const retries = opt?.retries === false ? 0 : opt?.retries || 3;\n const ssl = opt?.forceDisableSSL !== true;\n\n console.debug(\n `Creating Postgres connection with ${retries} retries and ssl=${ssl}`\n );\n if (_connections.length > 0) {\n console.warn(`We already have ${_connections.length} Postgres connections`);\n }\n\n for (let attempt = 1; attempt <= retries; attempt++) {\n try {\n const sql = postgres(connectionString, {\n ssl: ssl ? 'require' : false,\n // connect_timeout: 10\n // idle_timeout: 10\n // disable prepare statements since we use pgbouncer\n prepare: false,\n connect_timeout: 10,\n idle_timeout: 60,\n });\n\n await sql`select 1`;\n try {\n // connect 30s, idle 60s, max lifetime 45min, statement 60s, lock 10s, log_min_duration 20s, log_lock_waits off\n await sql`set statement_timeout to '30s';`;\n await sql`set lock_timeout to '10s';`;\n } catch (e) {\n console.warn('Failed to set statement timeout, continuing', e);\n }\n\n _connections.push(sql);\n return sql;\n } catch (err) {\n if (attempt === retries) throw err;\n console.warn(\n `Postgres connection failed (attempt ${attempt}), retrying...`\n );\n console.error('error', err);\n await new Promise((res) => setTimeout(res, delayMs));\n }\n }\n throw new Error('Unable to connect to Postgres');\n}\n\nexport async function useAsyncKysely(connectionString: string, opt?: PgOpt) {\n const sql = await useAsyncPostgres(connectionString, opt);\n return useKysely(sql);\n}\n\n/**\n * @deprecated This method is deprecated in favor of the useAsyncKysely method.\n */\nexport function usePostgres(\n connectionString?: string,\n opt?: Pick<PgOpt, 'forceDisableSSL'>\n) {\n if (!connectionString) throw new Error('No connection string');\n const ssl = opt?.forceDisableSSL !== true;\n const pg = postgres(connectionString, {\n ssl: ssl ? 'require' : false,\n });\n _connections.push(pg);\n return pg;\n}\n\nexport async function forceCloseAllPostgres(timeoutMs = 5000) {\n await Promise.all(\n _connections.map((pg) =>\n pg.end({ timeout: timeoutMs }).catch(() => undefined)\n )\n );\n _connections.length = 0;\n}\n\nexport class DatabaseError extends Error {\n constructor(message: string, cause: any) {\n super(message);\n this.cause = cause;\n }\n}\n\nconst dirname =\n typeof __dirname === 'string' ? join(__dirname, '../../..') : '';\n\nexport async function withStack<T>(a: Promise<T>) {\n // skip if we can't get the stack, probably in a worker\n if (!dirname) return await a;\n\n const now = performance.now();\n const error = new DatabaseError('Error in execute', undefined);\n const stack = error.stack?.split('\\n').slice(3) || undefined;\n const firstLine =\n stack?.length && stack[0]?.includes('(') && dirname\n ? relative(dirname, stack[0].split('(')[1].split(')')[0])\n : undefined;\n try {\n const result = await a;\n console.log(\n `[${firstLine}] Execution time: ${Math.round(performance.now() - now)}ms`\n );\n return result;\n } catch (e: any) {\n if (stack) error.stack = stack.join('\\n').trim();\n else error.stack = e.stack;\n // error.cause = e;\n error.message = e.message;\n const serialized = serializeError(e);\n delete serialized.stack;\n error.cause = serialized;\n console.error(`Error in execute: ${firstLine}`, serializeError(error));\n console.log(\n `[${firstLine}] Execution time: ${Math.round(performance.now() - now)}ms`\n );\n throw error;\n }\n}\n"]}
|
|
@@ -6,15 +6,14 @@ import { PGlite } from '@electric-sql/pglite';
|
|
|
6
6
|
import { CamelCasePlugin, FileMigrationProvider, Kysely, Migrator, } from 'kysely';
|
|
7
7
|
import codegen from 'kysely-codegen';
|
|
8
8
|
import { KyselyPGlite } from 'kysely-pglite';
|
|
9
|
-
|
|
10
|
-
async function migrate(client) {
|
|
9
|
+
async function migrate(root, client) {
|
|
11
10
|
console.log('migrating pglite ....');
|
|
12
11
|
const glob = new Bun.Glob('initial/*.sql');
|
|
13
12
|
for await (const migration of glob.scan(root)) {
|
|
14
13
|
await client.exec(await Bun.file(join(root, migration)).text());
|
|
15
14
|
}
|
|
16
15
|
}
|
|
17
|
-
async function migrateKysely(kysely) {
|
|
16
|
+
async function migrateKysely(root, kysely) {
|
|
18
17
|
console.log('init migrating kysely ....');
|
|
19
18
|
const migrator = new Migrator({
|
|
20
19
|
db: kysely,
|
|
@@ -47,13 +46,12 @@ async function migrateKysely(kysely) {
|
|
|
47
46
|
process.exit(1);
|
|
48
47
|
}
|
|
49
48
|
}
|
|
50
|
-
|
|
51
|
-
const dumpFile = (async () => {
|
|
49
|
+
async function generateDump(root, dumpPath) {
|
|
52
50
|
const dataExists = await exists(dumpPath).catch(() => false);
|
|
53
51
|
if (!dataExists) {
|
|
54
52
|
console.log('Creating initial dump');
|
|
55
53
|
const main = new PGlite();
|
|
56
|
-
await migrate(main).catch(async (err) => {
|
|
54
|
+
await migrate(root, main).catch(async (err) => {
|
|
57
55
|
console.error('failed to migrate initial dump');
|
|
58
56
|
await Bun.write('../logs/migrate-initial-dump.json', JSON.stringify(err, null, 2));
|
|
59
57
|
process.exit(1);
|
|
@@ -63,7 +61,7 @@ const dumpFile = (async () => {
|
|
|
63
61
|
dialect,
|
|
64
62
|
plugins: [new CamelCasePlugin()],
|
|
65
63
|
});
|
|
66
|
-
await migrateKysely(kysely).catch(() => {
|
|
64
|
+
await migrateKysely(root, kysely).catch(() => {
|
|
67
65
|
console.error('failed to migrate kysely');
|
|
68
66
|
process.exit(1);
|
|
69
67
|
});
|
|
@@ -90,11 +88,11 @@ const dumpFile = (async () => {
|
|
|
90
88
|
return content;
|
|
91
89
|
}
|
|
92
90
|
return Bun.file(dumpPath);
|
|
93
|
-
}
|
|
94
|
-
export async function
|
|
91
|
+
}
|
|
92
|
+
export async function createLocalKysely(root, dumpPath) {
|
|
95
93
|
let isDestroyed = false;
|
|
96
94
|
const now = performance.now();
|
|
97
|
-
const dump = await
|
|
95
|
+
const dump = await generateDump(root, dumpPath);
|
|
98
96
|
const pglite = new PGlite({ loadDataDir: dump });
|
|
99
97
|
// warm up
|
|
100
98
|
await pglite.sql `SELECT 1`;
|
|
@@ -116,4 +114,4 @@ export async function useLocalKysely() {
|
|
|
116
114
|
console.log(`Database initialized: ${Math.round(performance.now() - now)}ms`);
|
|
117
115
|
return kysely;
|
|
118
116
|
}
|
|
119
|
-
//# sourceMappingURL=
|
|
117
|
+
//# sourceMappingURL=generate.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"generate.js","sourceRoot":"src/","sources":["local/generate.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,IAAI,EAAE,EAAE,MAAM,SAAS,CAAC;AACzC,OAAO,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAC1C,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AAClC,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,MAAM,EAAE,MAAM,sBAAsB,CAAC;AAC9C,OAAO,EACL,eAAe,EACf,qBAAqB,EACrB,MAAM,EACN,QAAQ,GACT,MAAM,QAAQ,CAAC;AAChB,OAAO,OAAO,MAAM,gBAAgB,CAAC;AACrC,OAAO,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAG7C,KAAK,UAAU,OAAO,CAAC,IAAY,EAAE,MAAc;IACjD,OAAO,CAAC,GAAG,CAAC,uBAAuB,CAAC,CAAC;IACrC,MAAM,IAAI,GAAG,IAAI,GAAG,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC;IAC3C,IAAI,KAAK,EAAE,MAAM,SAAS,IAAI,IAAI,CAAC,IAAI,CAAC,IAAI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,EAAE,IAAI,EAAE,CAAC,CAAC;IACjD,UAAU;IACV,MAAM,MAAM,CAAC,GAAG,CAAA,UAAU,CAAC;IAC3B,MAAM,EAAE,OAAO,EAAE,GAAG,IAAI,YAAY,CAAC,MAAM,CAAC,CAAC;IAC7C,MAAM,MAAM,GAAG,IAAI,MAAM,CAAK;QAC5B,OAAO;QACP,OAAO,EAAE,CAAC,IAAI,eAAe,EAAE,CAAC;KACjC,CAAC,CAAC;IAEH,MAAM,eAAe,GAAG,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IACpD,MAAM,CAAC,OAAO,GAAG,KAAK,IAAI,EAAE;QAC1B,IAAI,WAAW;YAAE,OAAO;QACxB,WAAW,GAAG,IAAI,CAAC;QACnB,MAAM,WAAW,GAAG,WAAW,CAAC,GAAG,EAAE,CAAC;QACtC,MAAM,eAAe,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC;QAC/C,MAAM,MAAM,CAAC,KAAK,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC;QAC5C,OAAO,CAAC,GAAG,CACT,uBAAuB,IAAI,CAAC,KAAK,CAAC,WAAW,CAAC,GAAG,EAAE,GAAG,WAAW,CAAC,IAAI,CACvE,CAAC;IACJ,CAAC,CAAC;IAEF,OAAO,CAAC,GAAG,CAAC,yBAAyB,IAAI,CAAC,KAAK,CAAC,WAAW,CAAC,GAAG,EAAE,GAAG,GAAG,CAAC,IAAI,CAAC,CAAC;IAE9E,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import { promises as fs } from 'node:fs';\nimport { exists } from 'node:fs/promises';\nimport * as path from 'node:path';\nimport { join } from 'node:path';\nimport { PGlite } from '@electric-sql/pglite';\nimport {\n CamelCasePlugin,\n FileMigrationProvider,\n Kysely,\n Migrator,\n} from 'kysely';\nimport codegen from 'kysely-codegen';\nimport { KyselyPGlite } from 'kysely-pglite';\nimport type { DB } from '../v1.generated';\n\nasync function migrate(root: string, client: PGlite) {\n console.log('migrating pglite ....');\n const glob = new Bun.Glob('initial/*.sql');\n for await (const migration of glob.scan(root)) {\n await client.exec(await Bun.file(join(root, migration)).text());\n }\n}\n\nasync function migrateKysely(root: string, kysely: Kysely<any>) {\n console.log('init migrating kysely ....');\n const migrator = new Migrator({\n db: kysely,\n migrationTableSchema: 'core',\n migrationTableName: 'kysely_migration',\n migrationLockTableName: 'kysely_migration_lock',\n provider: new FileMigrationProvider({\n fs,\n path,\n // This needs to be an absolute path.\n migrationFolder: path.join(root, 'migrations'),\n }),\n });\n\n console.log('migrating kysely ....');\n const { error, results } = await migrator.migrateToLatest().catch(() => {\n console.error('failed to migrate');\n process.exit(1);\n });\n\n for (const it of results ?? []) {\n if (it.status === 'Success') {\n console.log(`migration \"${it.migrationName}\" was executed successfully`);\n } else if (it.status === 'Error') {\n console.error(`failed to execute migration \"${it.migrationName}\"`);\n }\n }\n\n if (error) {\n console.error('failed to migrate');\n console.error(error);\n process.exit(1);\n }\n}\n\nasync function generateDump(root: string, dumpPath: string) {\n const dataExists = await exists(dumpPath).catch(() => false);\n if (!dataExists) {\n console.log('Creating initial dump');\n const main = new PGlite();\n await migrate(root, main).catch(async (err) => {\n console.error('failed to migrate initial dump');\n await Bun.write(\n '../logs/migrate-initial-dump.json',\n JSON.stringify(err as any, null, 2)\n );\n process.exit(1);\n });\n const { dialect } = new KyselyPGlite(main);\n const kysely = new Kysely<DB>({\n dialect,\n plugins: [new CamelCasePlugin()],\n });\n await migrateKysely(root, kysely).catch(() => {\n console.error('failed to migrate kysely');\n process.exit(1);\n });\n await codegen\n .generate({\n db: kysely,\n outFile: path.join(root, 'src/v1.generated.ts'),\n defaultSchemas: ['xxx'],\n camelCase: true,\n dialect: codegen.getDialect('postgres'),\n })\n .catch(() => {\n console.error('failed to generate kysely');\n process.exit(1);\n });\n const content = await main.dumpDataDir('none').catch(() => {\n console.error('failed to dump data');\n process.exit(1);\n });\n await Bun.write(dumpPath, content).catch(() => {\n console.error('failed to write dump');\n process.exit(1);\n });\n return content;\n }\n return Bun.file(dumpPath);\n}\n\nexport async function createLocalKysely(root: string, dumpPath: string) {\n let isDestroyed = false;\n const now = performance.now();\n\n const dump = await generateDump(root, dumpPath);\n\n const pglite = new PGlite({ loadDataDir: dump });\n // warm up\n await pglite.sql`SELECT 1`;\n const { dialect } = new KyselyPGlite(pglite);\n const kysely = new Kysely<DB>({\n dialect,\n plugins: [new CamelCasePlugin()],\n });\n\n const originalDestroy = kysely.destroy.bind(kysely);\n kysely.destroy = async () => {\n if (isDestroyed) return;\n isDestroyed = true;\n const destroyTime = performance.now();\n await originalDestroy().catch(() => undefined);\n await pglite.close().catch(() => undefined);\n console.log(\n `Database destroyed: ${Math.round(performance.now() - destroyTime)}ms`\n );\n };\n\n console.log(`Database initialized: ${Math.round(performance.now() - now)}ms`);\n\n return kysely;\n}\n"]}
|