@vrplatform/kysely 1.3.15 → 1.3.17

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.
Files changed (81) hide show
  1. package/build/.data.tar +0 -0
  2. package/build/main/camel-case/index.d.ts +8 -0
  3. package/build/main/camel-case/index.js +61 -0
  4. package/build/main/camel-case/index.js.map +1 -0
  5. package/build/main/error.d.ts +3 -0
  6. package/build/main/error.js +11 -0
  7. package/build/main/error.js.map +1 -0
  8. package/build/main/index.d.ts +3 -1
  9. package/build/main/index.js +7 -14
  10. package/build/main/index.js.map +1 -1
  11. package/build/main/local/digest.d.ts +1 -0
  12. package/build/main/local/digest.js +27 -0
  13. package/build/main/local/digest.js.map +1 -1
  14. package/build/main/local/generate.d.ts +1 -1
  15. package/build/main/local/generate.js +7 -6
  16. package/build/main/local/generate.js.map +1 -1
  17. package/build/main/local/index.d.ts +2 -3
  18. package/build/main/local/index.js +8 -12
  19. package/build/main/local/index.js.map +1 -1
  20. package/build/main/local.d.ts +3 -0
  21. package/build/main/local.js +158 -0
  22. package/build/main/local.js.map +1 -0
  23. package/build/main/plugins.d.ts +6 -0
  24. package/build/main/plugins.js +21 -0
  25. package/build/main/plugins.js.map +1 -0
  26. package/build/main/test/index.js +2 -1
  27. package/build/main/test/index.js.map +1 -1
  28. package/build/main/tsconfig.main.tsbuildinfo +1 -1
  29. package/build/main/v0.generated.d.ts +1996 -0
  30. package/build/main/v0.generated.js +7 -0
  31. package/build/main/v0.generated.js.map +1 -0
  32. package/build/main/v1.generated.d.ts +20 -1
  33. package/build/main/v1.generated.js.map +1 -1
  34. package/build/module/camel-case/index.d.ts +8 -0
  35. package/build/module/camel-case/index.js +57 -0
  36. package/build/module/camel-case/index.js.map +1 -0
  37. package/build/module/error.d.ts +3 -0
  38. package/build/module/error.js +7 -0
  39. package/build/module/error.js.map +1 -0
  40. package/build/module/index.d.ts +3 -1
  41. package/build/module/index.js +7 -14
  42. package/build/module/index.js.map +1 -1
  43. package/build/module/local/digest.d.ts +1 -0
  44. package/build/module/local/digest.js +26 -0
  45. package/build/module/local/digest.js.map +1 -1
  46. package/build/module/local/generate.d.ts +1 -1
  47. package/build/module/local/generate.js +8 -7
  48. package/build/module/local/generate.js.map +1 -1
  49. package/build/module/local/index.d.ts +2 -3
  50. package/build/module/local/index.js +9 -13
  51. package/build/module/local/index.js.map +1 -1
  52. package/build/module/local.d.ts +3 -0
  53. package/build/module/local.js +119 -0
  54. package/build/module/local.js.map +1 -0
  55. package/build/module/plugins.d.ts +6 -0
  56. package/build/module/plugins.js +18 -0
  57. package/build/module/plugins.js.map +1 -0
  58. package/build/module/test/index.js +2 -1
  59. package/build/module/test/index.js.map +1 -1
  60. package/build/module/tsconfig.esm.tsbuildinfo +1 -1
  61. package/build/module/v0.generated.d.ts +1996 -0
  62. package/build/module/v0.generated.js +6 -0
  63. package/build/module/v0.generated.js.map +1 -0
  64. package/build/module/v1.generated.d.ts +20 -1
  65. package/build/module/v1.generated.js.map +1 -1
  66. package/package.json +3 -3
  67. package/src/camel-case/index.ts +68 -0
  68. package/src/error.ts +6 -0
  69. package/src/index.ts +11 -21
  70. package/src/local/digest.ts +26 -0
  71. package/src/local/generate.ts +9 -13
  72. package/src/local/index.ts +10 -14
  73. package/src/plugins.ts +30 -0
  74. package/src/test/index.ts +2 -1
  75. package/src/v1.generated.ts +20 -1
  76. package/build/main/browser/index.d.ts +0 -17
  77. package/build/main/browser/index.js +0 -65
  78. package/build/main/browser/index.js.map +0 -1
  79. package/build/main/browser/worker.d.ts +0 -1
  80. package/build/main/browser/worker.js +0 -42
  81. package/build/main/browser/worker.js.map +0 -1
package/build/.data.tar CHANGED
Binary file
@@ -0,0 +1,8 @@
1
+ import { CamelCasePlugin, type SelectQueryNode } from 'kysely';
2
+ export declare class CustomCasePlugin extends CamelCasePlugin {
3
+ constructor();
4
+ transformResult(args: any): Promise<import("kysely").QueryResult<import("kysely").UnknownRow>>;
5
+ transformQuery(args: any): import("kysely").RootOperationNode;
6
+ verifyAlias(node: SelectQueryNode): void;
7
+ protected mapRow(row: any): any;
8
+ }
@@ -0,0 +1,61 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CustomCasePlugin = void 0;
4
+ const kysely_1 = require("kysely");
5
+ const error_1 = require("../error");
6
+ class CustomCasePlugin extends kysely_1.CamelCasePlugin {
7
+ // _excludedColumns: Record<string, boolean> = {};
8
+ constructor() {
9
+ super({
10
+ maintainNestedObjectKeys: true,
11
+ });
12
+ }
13
+ transformResult(args) {
14
+ return super.transformResult(args);
15
+ }
16
+ transformQuery(args) {
17
+ this.verifyAlias(args.node);
18
+ return super.transformQuery(args);
19
+ }
20
+ verifyAlias(node) {
21
+ if (!node?.selections)
22
+ return;
23
+ for (const x of node.selections ?? []) {
24
+ const selection = x.selection;
25
+ if (!selection.alias)
26
+ continue;
27
+ const alias = selection.alias;
28
+ // alias can be a raw node (jsonArrayFrom)
29
+ if (selection.node.kind === 'RawNode') {
30
+ const rawNode = selection.node;
31
+ for (const x of rawNode.parameters ?? []) {
32
+ if (x.kind === 'SelectQueryNode') {
33
+ const selectQueryNode = x;
34
+ this.verifyAlias(selectQueryNode);
35
+ }
36
+ }
37
+ }
38
+ if (!alias.name.includes('_'))
39
+ continue;
40
+ throw new error_1.KyselyError(`Alias ${alias.name} contains underscore`);
41
+ }
42
+ }
43
+ mapRow(row) {
44
+ if (typeof row !== 'object' || !row)
45
+ return row;
46
+ const newRow = {};
47
+ // we camel case on first layer, and nested ONLY if in an array (jsonArrayFrom), NOT if it's an object (jsonb)
48
+ for (const key of Object.keys(row)) {
49
+ let value = row[key];
50
+ const newKey = super.camelCase(key);
51
+ // array CAN be non object, so we need to check the first element
52
+ if (Array.isArray(value)) {
53
+ value = value.map((it) => this.mapRow(it));
54
+ }
55
+ newRow[newKey] = value;
56
+ }
57
+ return newRow;
58
+ }
59
+ }
60
+ exports.CustomCasePlugin = CustomCasePlugin;
61
+ //# sourceMappingUR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C,GAAG,CAAC;gBAAE,SAAS;YAExC,MAAM,IAAI,mBAAW,CAAC,SAAS,KAAK,CAAC,IAAI,sBAAsB,CAAC,CAAC;QACnE,CAAC;IACH,CAAC;IAES,MAAM,CAAC,GAAG;QAClB,IAAI,OAAO,GAAG,KAAK,QAAQ,IAAI,CAAC,GAAG;YAAE,OAAO,GAAG,CAAC;QAEhD,MAAM,MAAM,GAAwB,EAAE,CAAC;QACvC,8GAA8G;QAC9G,KAAK,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC;YACnC,IAAI,KAAK,GAAG,GAAG,CAAC,GAAG,CAAC,CAAC;YACrB,MAAM,MAAM,GAAG,KAAK,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC;YACpC,iEAAiE;YACjE,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC;gBACzB,KAAK,GAAG,KAAK,CAAC,GAAG,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC,CAAC;YAC7C,CAAC;YACD,MAAM,CAAC,MAAM,CAAC,GAAG,KAAK,CAAC;QACzB,CAAC;QACD,OAAO,MAAM,CAAC;IAChB,CAAC;CACF;AA1DD,4CA0DC","sourcesContent":["import {\n type AliasNode,\n CamelCasePlugin,\n type IdentifierNode,\n type RawNode,\n type SelectQueryNode,\n} from 'kysely';\nimport { KyselyError } from '../error';\n\nexport class CustomCasePlugin extends CamelCasePlugin {\n // _excludedColumns: Record<string, boolean> = {};\n constructor() {\n super({\n maintainNestedObjectKeys: true,\n });\n }\n\n transformResult(args) {\n return super.transformResult(args);\n }\n\n transformQuery(args) {\n this.verifyAlias(args.node);\n return super.transformQuery(args);\n }\n\n verifyAlias(node: SelectQueryNode) {\n if (!node?.selections) return;\n\n for (const x of node.selections ?? []) {\n const selection = x.selection as AliasNode;\n if (!selection.alias) continue;\n const alias = selection.alias as IdentifierNode;\n\n // alias can be a raw node (jsonArrayFrom)\n if (selection.node.kind === 'RawNode') {\n const rawNode = selection.node as RawNode;\n for (const x of rawNode.parameters ?? []) {\n if (x.kind === 'SelectQueryNode') {\n const selectQueryNode = x as SelectQueryNode;\n this.verifyAlias(selectQueryNode);\n }\n }\n }\n\n if (!alias.name.includes('_')) continue;\n\n throw new KyselyError(`Alias ${alias.name} contains underscore`);\n }\n }\n\n protected mapRow(row) {\n if (typeof row !== 'object' || !row) return row;\n\n const newRow: Record<string, any> = {};\n // we camel case on first layer, and nested ONLY if in an array (jsonArrayFrom), NOT if it's an object (jsonb)\n for (const key of Object.keys(row)) {\n let value = row[key];\n const newKey = super.camelCase(key);\n // array CAN be non object, so we need to check the first element\n if (Array.isArray(value)) {\n value = value.map((it) => this.mapRow(it));\n }\n newRow[newKey] = value;\n }\n return newRow;\n }\n}\n"]}
@@ -0,0 +1,3 @@
1
+ export declare class KyselyError extends Error {
2
+ constructor(message: string);
3
+ }
@@ -0,0 +1,11 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.KyselyError = void 0;
4
+ class KyselyError extends Error {
5
+ constructor(message) {
6
+ super(message);
7
+ this.name = 'KyselyError';
8
+ }
9
+ }
10
+ exports.KyselyError = KyselyError;
11
+ //# sourceMappingURL=error.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"error.js","sourceRoot":"src/","sources":["error.ts"],"names":[],"mappings":";;;AAAA,MAAa,WAAY,SAAQ,KAAK;IACpC,YAAY,OAAe;QACzB,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,aAAa,CAAC;IAC5B,CAAC;CACF;AALD,kCAKC","sourcesContent":["export class KyselyError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'KyselyError';\n }\n}\n"]}
@@ -1,5 +1,7 @@
1
- import { Kysely as K, type LogConfig } from 'kysely';
1
+ import type { Kysely as K, LogConfig } from 'kysely';
2
2
  import postgres, { type Sql } from 'postgres';
3
+ export type { LogEvent } from 'kysely';
4
+ export * from './error';
3
5
  export * from './isomorphic';
4
6
  import type { DB } from './v1.generated';
5
7
  type KyselyOpts = {
@@ -23,28 +23,21 @@ exports.useAsyncPostgres = useAsyncPostgres;
23
23
  exports.useAsyncKysely = useAsyncKysely;
24
24
  exports.usePostgres = usePostgres;
25
25
  exports.forceCloseAllPostgres = forceCloseAllPostgres;
26
- const kysely_1 = require("kysely");
27
26
  const kysely_postgres_js_1 = require("kysely-postgres-js");
28
27
  const postgres_1 = __importDefault(require("postgres"));
28
+ const plugins_1 = require("./plugins");
29
+ __exportStar(require("./error"), exports);
29
30
  __exportStar(require("./isomorphic"), exports);
30
- const pganalyze_comment_plugin_1 = require("./pganalyze-comment-plugin");
31
31
  /**
32
32
  * @deprecated This method is deprecated in favor of the useAsyncKysely method.
33
33
  */
34
34
  function useKysely(postgres, options) {
35
35
  console.debug('Creating Kysely instance');
36
- const plugins = [new kysely_1.CamelCasePlugin()];
37
- if (options?.repositoryName) {
38
- plugins.push(new pganalyze_comment_plugin_1.KyselyPganalyzeCommentPlugin({
39
- repository: options.repositoryName,
40
- }));
41
- }
42
- const kysely = new kysely_1.Kysely({
43
- dialect: new kysely_postgres_js_1.PostgresJSDialect({
44
- postgres,
45
- }),
46
- plugins,
47
- log: options?.log === true ? ['query', 'error'] : options?.log,
36
+ const kysely = (0, plugins_1.getKysely)(new kysely_postgres_js_1.PostgresJSDialect({
37
+ postgres,
38
+ }), {
39
+ repositoryName: options?.repositoryName,
40
+ log: options?.log,
48
41
  });
49
42
  kysely.destroy = async () => {
50
43
  console.debug('Closing Kysely connection');
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"src/","sources":["index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;AA6BA,8BA6BC;AAGD,4CA6CC;AAED,wCAMC;AAKD,kCAeC;AAED,sDAUC;AAlJD,mCAKgB;AAChB,2DAAuD;AACvD,wDAA8C;AAE9C,+CAA6B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EAAE,CAAC;AACZ,CAAC;AAEM,KAAK,UAAU,qBAAqB,CAAC,SAAS,GAAG,IAAI;IAC1D,MAAM,OAAO,CAAC,IAAI,CAAC;QACjB,OAAO,CAAC,GAAG,CACT,YAAY,CAAC,GAAG,CAAC,CAAC,EAAE,EAAE,EAAE,CACtB,EAAE,CAAC,GAAG,CAAC,EAAE,OAAO,EAAE,SAAS,EAAE,CAAC,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CACtD,CACF;QACD,IAAI,OAAO,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,UAAU,CAAC,GAAG,EAAE,SAAS,GAAG,IAAI,CAAC,CAAC;KACxD,CAAC,CAAC;IACH,YAAY,GAAG,EAAE,CAAC;AACpB,CAAC;AAED,MAAa,aAAc,SAAQ,KAAK;IACtC,YAAY,OAAe,EAAE,KAAU;QACrC,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;IACrB,CAAC;CACF;AALD,sCAKC","sourcesContent":["import {\n CamelCasePlugin,\n Kysely as K,\n type KyselyPlugin,\n type LogConfig,\n} from 'kysely';\nimport { PostgresJSDialect } from 'kysely-postgres-js';\nimport postgres, { type Sql } from 'postgres';\n\nexport * from './isomorphic';\n\nimport { KyselyPganalyzeCommentPlugin } from './pganalyze-comment-plugin';\nimport type { DB } from './v1.generated';\n\ntype KyselyOpts = {\n repositoryName?: string;\n log?: true | LogConfig;\n};\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?: KyselyOpts) {\n console.debug('Creating Kysely instance');\n const plugins: KyselyPlugin[] = [new CamelCasePlugin()];\n if (options?.repositoryName) {\n plugins.push(\n new KyselyPganalyzeCommentPlugin({\n repository: options.repositoryName,\n })\n );\n }\n const kysely = new K<DB>({\n dialect: new PostgresJSDialect({\n postgres,\n }),\n plugins,\n log: options?.log === true ? ['query', 'error'] : options?.log,\n });\n\n kysely.destroy = async () => {\n console.debug('Closing Kysely connection');\n await Promise.race([\n postgres.end({ timeout: 5000 }).catch(() => undefined),\n new Promise((res) => setTimeout(res, 6000)),\n ]);\n const index = _connections.indexOf(postgres);\n if (index !== -1) _connections.splice(index, 1);\n };\n\n return kysely;\n}\n\nlet _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 const url = new URL(connectionString);\n\n console.debug(\n `Creating Postgres connection with ${retries} retries and ssl=${ssl} and port=${url.port}`\n );\n if (_connections.length > 0)\n console.warn(`We already have ${_connections.length} Postgres connections`);\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 // enable prepare statements, pgbouncer on crunchy allows for prepared statements\n prepare: true,\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(\n connectionString: string,\n opt?: PgOpt & KyselyOpts\n) {\n const sql = await useAsyncPostgres(connectionString, opt);\n return useKysely(sql, opt);\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 url = new URL(connectionString);\n console.debug(\n `Creating sync Postgres connection with ssl=${ssl} and port=${url.port}`\n );\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.race([\n Promise.all(\n _connections.map((pg) =>\n pg.end({ timeout: timeoutMs }).catch(() => undefined)\n )\n ),\n new Promise((res) => setTimeout(res, timeoutMs + 1000)),\n ]);\n _connections = [];\n}\n\nexport class DatabaseError extends Error {\n constructor(message: string, cause: any) {\n super(message);\n this.cause = cause;\n }\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"src/","sources":["index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;AA0BA,8BAsBC;AAGD,4CA6CC;AAED,wCAMC;AAKD,kCAeC;AAED,sDAUC;AAvID,2DAAuD;AACvD,wDAA8C;AAC9C,uCAAsC;AAGtC,0CAAwB;AACxB,+CAA6B;AAgB7B;;GAEG;AACH,SAAgB,SAAS,CAAC,QAAa,EAAE,OAAoB;IAC3D,OAAO,CAAC,KAAK,CAAC,0BAA0B,CAAC,CAAC;IAC1C,MAAM,MAAM,GAAG,IAAA,mBAAS,EACtB,IAAI,sCAAiB,CAAC;QACpB,QAAQ;KACT,CAAC,EACF;QACE,cAAc,EAAE,OAAO,EAAE,cAAc;QACvC,GAAG,EAAE,OAAO,EAAE,GAAG;KAClB,CACF,CAAC;IACF,MAAM,CAAC,OAAO,GAAG,KAAK,IAAI,EAAE;QAC1B,OAAO,CAAC,KAAK,CAAC,2BAA2B,CAAC,CAAC;QAC3C,MAAM,OAAO,CAAC,IAAI,CAAC;YACjB,QAAQ,CAAC,GAAG,CAAC,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC,KAAK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G,GAAG,EAAE,eAAe,KAAK,IAAI,CAAC;IAC1C,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,gBAAgB,CAAC,CAAC;IACtC,OAAO,CAAC,KAAK,CACX,8CAA8C,GAAG,aAAa,GAAG,CAAC,IAAI,EAAE,CACzE,CAAC;IACF,MAAM,EAAE,GAAG,IAAA,kBAAQ,EAAC,gBAAgB,EAAE;QACpC,GAAG,EAAE,GAAG,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,KAAK;KAC7B,CAAC,CAAC;IACH,YAAY,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;IACtB,OAAO,EAAE,CAAC;AACZ,CAAC;AAEM,KAAK,UAAU,qBAAqB,CAAC,SAAS,GAAG,IAAI;IAC1D,MAAM,OAAO,CAAC,IAAI,CAAC;QACjB,OAAO,CAAC,GAAG,CACT,YAAY,CAAC,GAAG,CAAC,CAAC,EAAE,EAAE,EAAE,CACtB,EAAE,CAAC,GAAG,CAAC,EAAE,OAAO,EAAE,SAAS,EAAE,CAAC,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CACtD,CACF;QACD,IAAI,OAAO,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,UAAU,CAAC,GAAG,EAAE,SAAS,GAAG,IAAI,CAAC,CAAC;KACxD,CAAC,CAAC;IACH,YAAY,GAAG,EAAE,CAAC;AACpB,CAAC;AAED,MAAa,aAAc,SAAQ,KAAK;IACtC,YAAY,OAAe,EAAE,KAAU;QACrC,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;IACrB,CAAC;CACF;AALD,sCAKC","sourcesContent":["import type { Kysely as K, LogConfig } from 'kysely';\nimport { PostgresJSDialect } from 'kysely-postgres-js';\nimport postgres, { type Sql } from 'postgres';\nimport { getKysely } from './plugins';\n\nexport type { LogEvent } from 'kysely';\nexport * from './error';\nexport * from './isomorphic';\n\nimport type { DB } from './v1.generated';\n\ntype KyselyOpts = {\n repositoryName?: string;\n log?: true | LogConfig;\n};\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?: KyselyOpts) {\n console.debug('Creating Kysely instance');\n const kysely = getKysely(\n new PostgresJSDialect({\n postgres,\n }),\n {\n repositoryName: options?.repositoryName,\n log: options?.log,\n }\n );\n kysely.destroy = async () => {\n console.debug('Closing Kysely connection');\n await Promise.race([\n postgres.end({ timeout: 5000 }).catch(() => undefined),\n new Promise((res) => setTimeout(res, 6000)),\n ]);\n const index = _connections.indexOf(postgres);\n if (index !== -1) _connections.splice(index, 1);\n };\n\n return kysely;\n}\n\nlet _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 const url = new URL(connectionString);\n\n console.debug(\n `Creating Postgres connection with ${retries} retries and ssl=${ssl} and port=${url.port}`\n );\n if (_connections.length > 0)\n console.warn(`We already have ${_connections.length} Postgres connections`);\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 // enable prepare statements, pgbouncer on crunchy allows for prepared statements\n prepare: true,\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(\n connectionString: string,\n opt?: PgOpt & KyselyOpts\n) {\n const sql = await useAsyncPostgres(connectionString, opt);\n return useKysely(sql, opt);\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 url = new URL(connectionString);\n console.debug(\n `Creating sync Postgres connection with ssl=${ssl} and port=${url.port}`\n );\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.race([\n Promise.all(\n _connections.map((pg) =>\n pg.end({ timeout: timeoutMs }).catch(() => undefined)\n )\n ),\n new Promise((res) => setTimeout(res, timeoutMs + 1000)),\n ]);\n _connections = [];\n}\n\nexport class DatabaseError extends Error {\n constructor(message: string, cause: any) {\n super(message);\n this.cause = cause;\n }\n}\n"]}
@@ -1,2 +1,3 @@
1
1
  import { type Kysely } from '../isomorphic';
2
2
  export declare function ensureDigestFunction(kysely: Kysely): Promise<void>;
3
+ export declare function ensureGenRandomBytesFunction(kysely: Kysely): Promise<void>;
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.ensureDigestFunction = ensureDigestFunction;
4
+ exports.ensureGenRandomBytesFunction = ensureGenRandomBytesFunction;
4
5
  const isomorphic_1 = require("../isomorphic");
5
6
  async function ensureDigestFunction(kysely) {
6
7
  try {
@@ -19,4 +20,30 @@ async function ensureDigestFunction(kysely) {
19
20
  `.execute(kysely);
20
21
  }
21
22
  }
23
+ async function ensureGenRandomBytesFunction(kysely) {
24
+ try {
25
+ await (0, isomorphic_1.sql) `select gen_random_bytes(1)`.execute(kysely);
26
+ }
27
+ catch {
28
+ await (0, isomorphic_1.sql) `
29
+ create or replace function gen_random_bytes(p_len integer)
30
+ returns bytea
31
+ language sql
32
+ stable
33
+ strict
34
+ as $$
35
+ select substring(
36
+ decode(
37
+ repeat(
38
+ md5(random()::text || now()::text),
39
+ ((p_len + 15) / 16)
40
+ ),
41
+ 'hex'
42
+ )
43
+ from 1 for p_len
44
+ );
45
+ $$;
46
+ `.execute(kysely);
47
+ }
48
+ }
22
49
  //# sourceMappingURL=digest.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"digest.js","sourceRoot":"src/","sources":["local/digest.ts"],"names":[],"mappings":";;AAEA,oDAeC;AAjBD,8CAAiD;AAE1C,KAAK,UAAU,oBAAoB,CAAC,MAAc;IACvD,IAAI,CAAC;QACH,MAAM,IAAA,gBAAG,EAAA,6BAA6B,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;IACzD,CAAC;IAAC,MAAM,CAAC;QACP,MAAM,IAAA,gBAAG,EAAA;;;;;;;;;KASR,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;IACpB,CAAC;AACH,CAAC","sourcesContent":["import { type Kysely, sql } from '../isomorphic';\n\nexport async function ensureDigestFunction(kysely: Kysely) {\n try {\n await sql`select digest('', 'sha256')`.execute(kysely);\n } catch {\n await sql`\n create or replace function digest(input text, algo text)\n returns bytea\n language sql\n immutable\n strict\n as $$\n select '\\\\x0000000000000000000000000000000000000000000000000000000000000000'::bytea;\n $$;\n `.execute(kysely);\n }\n}\n"]}
1
+ {"version":3,"file":"digest.js","sourceRoot":"src/","sources":["local/digest.ts"],"names":[],"mappings":";;AAEA,oDAeC;AAED,oEAwBC;AA3CD,8CAAiD;AAE1C,KAAK,UAAU,oBAAoB,CAAC,MAAc;IACvD,IAAI,CAAC;QACH,MAAM,IAAA,gBAAG,EAAA,6BAA6B,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;IACzD,CAAC;IAAC,MAAM,CAAC;QACP,MAAM,IAAA,gBAAG,EAAA;;;;;;;;;KASR,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;IACpB,CAAC;AACH,CAAC;AAEM,KAAK,UAAU,4BAA4B,CAAC,MAAc;IAC/D,IAAI,CAAC;QACH,MAAM,IAAA,gBAAG,EAAA,4BAA4B,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;IACxD,CAAC;IAAC,MAAM,CAAC;QACP,MAAM,IAAA,gBAAG,EAAA;;;;;;;;;;;;;;;;;;KAkBR,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;IACpB,CAAC;AACH,CAAC","sourcesContent":["import { type Kysely, sql } from '../isomorphic';\n\nexport async function ensureDigestFunction(kysely: Kysely) {\n try {\n await sql`select digest('', 'sha256')`.execute(kysely);\n } catch {\n await sql`\n create or replace function digest(input text, algo text)\n returns bytea\n language sql\n immutable\n strict\n as $$\n select '\\\\x0000000000000000000000000000000000000000000000000000000000000000'::bytea;\n $$;\n `.execute(kysely);\n }\n}\n\nexport async function ensureGenRandomBytesFunction(kysely: Kysely) {\n try {\n await sql`select gen_random_bytes(1)`.execute(kysely);\n } catch {\n await sql`\n create or replace function gen_random_bytes(p_len integer)\n returns bytea\n language sql\n stable\n strict\n as $$\n select substring(\n decode(\n repeat(\n md5(random()::text || now()::text),\n ((p_len + 15) / 16)\n ),\n 'hex'\n )\n from 1 for p_len\n );\n $$;\n `.execute(kysely);\n }\n}\n"]}
@@ -1,3 +1,3 @@
1
- import { Kysely } from 'kysely';
1
+ import { type Kysely } from 'kysely';
2
2
  import type { DB } from '../v1.generated';
3
3
  export declare function createLocalKysely(root: string, dumpPath: string): Promise<Kysely<DB>>;
@@ -45,6 +45,7 @@ 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
+ const plugins_1 = require("../plugins");
48
49
  async function migrate(root, client) {
49
50
  console.log('migrating pglite ....');
50
51
  const glob = new Bun.Glob('initial/*.sql');
@@ -100,9 +101,9 @@ async function generateDump(root, dumpPath) {
100
101
  process.exit(1);
101
102
  });
102
103
  const { dialect } = new kysely_pglite_1.KyselyPGlite(main);
103
- const kysely = new kysely_1.Kysely({
104
- dialect,
105
- plugins: [new kysely_1.CamelCasePlugin()],
104
+ const kysely = (0, plugins_1.getKysely)(dialect, {
105
+ repositoryName: 'localTesting',
106
+ log: undefined,
106
107
  });
107
108
  await migrateKysely(root, kysely).catch(() => {
108
109
  console.error('failed to migrate kysely');
@@ -140,9 +141,9 @@ async function createLocalKysely(root, dumpPath) {
140
141
  // warm up
141
142
  await pglite.sql `SELECT 1`;
142
143
  const { dialect } = new kysely_pglite_1.KyselyPGlite(pglite);
143
- const kysely = new kysely_1.Kysely({
144
- dialect,
145
- plugins: [new kysely_1.CamelCasePlugin()],
144
+ const kysely = (0, plugins_1.getKysely)(dialect, {
145
+ repositoryName: 'localTesting',
146
+ log: undefined,
146
147
  });
147
148
  const originalDestroy = kysely.destroy.bind(kysely);
148
149
  kysely.destroy = async () => {
@@ -1 +1 @@
1
- {"version":3,"file":"generate.js","sourceRoot":"src/","sources":["local/generate.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8GA,8CA8BC;AA5ID,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,GAAG,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CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC;IAEhD,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,yCAAyC;QACzC,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,cAAc;QACd,0EAA0E;QAC1E,IAAI;IACN,CAAC,CAAC;IAEF,iFAAiF;IAEjF,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 const raw = await Bun.file(join(root, migration)).text();\n // `pg_dump` (v17+) prepends `\\restrict`/`\\unrestrict` psql meta commands\n // which PostgreSQL-compatible parsers (like PGlite) cannot execute.\n const sanitized = raw.replace(/^\\s*\\\\(?:un)?restrict.*$/gim, '');\n await client.exec(sanitized);\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"]}
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,mCAAsE;AACtE,oEAAqC;AACrC,iDAA6C;AAC7C,wCAAuC;AAGvC,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,GAAG,GAAG,MAAM,GAAG,CAAC,IAAI,CAAC,IAAA,gBAAI,EAAC,IAAI,EAAE,SAAS,CAAC,CAAC,CAAC,IAAI,E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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,IAAA,mBAAS,EAAC,OAAO,EAAE;QAChC,cAAc,EAAE,cAAc;QAC9B,GAAG,EAAE,SAAS;KACf,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,yCAAyC;QACzC,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,cAAc;QACd,0EAA0E;QAC1E,IAAI;IACN,CAAC,CAAC;IAEF,iFAAiF;IAEjF,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 { FileMigrationProvider, type Kysely, Migrator } from 'kysely';\nimport codegen from 'kysely-codegen';\nimport { KyselyPGlite } from 'kysely-pglite';\nimport { getKysely } from '../plugins';\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 const raw = await Bun.file(join(root, migration)).text();\n // `pg_dump` (v17+) prepends `\\restrict`/`\\unrestrict` psql meta commands\n // which PostgreSQL-compatible parsers (like PGlite) cannot execute.\n const sanitized = raw.replace(/^\\s*\\\\(?:un)?restrict.*$/gim, '');\n await client.exec(sanitized);\n }\n}\n\nasync function migrateKysely(root: string, kysely: Kysely<DB>) {\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 = getKysely(dialect, {\n repositoryName: 'localTesting',\n log: undefined,\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 = getKysely(dialect, {\n repositoryName: 'localTesting',\n log: undefined,\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,9 +1,8 @@
1
- import { Kysely, type LogConfig } from 'kysely';
2
- import type { DB } from '../v1.generated';
1
+ import type { LogConfig } from 'kysely';
3
2
  export declare const root: string;
4
3
  export declare const dumpPath: string;
5
4
  export type UseLocalKyselyOptions = {
6
5
  repositoryName?: string;
7
6
  log?: true | LogConfig;
8
7
  };
9
- export declare function useLocalKysely(args?: UseLocalKyselyOptions): Promise<Kysely<DB>>;
8
+ export declare function useLocalKysely(args?: UseLocalKyselyOptions): Promise<import("kysely").Kysely<import("..").DB>>;
@@ -4,9 +4,8 @@ exports.dumpPath = exports.root = void 0;
4
4
  exports.useLocalKysely = useLocalKysely;
5
5
  const node_path_1 = require("node:path");
6
6
  const pglite_1 = require("@electric-sql/pglite");
7
- const kysely_1 = require("kysely");
8
7
  const kysely_pglite_dialect_1 = require("kysely-pglite-dialect");
9
- const pganalyze_comment_plugin_1 = require("../pganalyze-comment-plugin");
8
+ const plugins_1 = require("../plugins");
10
9
  const digest_1 = require("./digest");
11
10
  exports.root = (0, node_path_1.join)(__dirname, '../..');
12
11
  exports.dumpPath = (0, node_path_1.join)(exports.root, '.data.tar');
@@ -14,20 +13,17 @@ async function useLocalKysely(args = {}) {
14
13
  let isDestroyed = false;
15
14
  // const now = performance.now();
16
15
  const dump = Bun.file(exports.dumpPath);
17
- const pglite = new pglite_1.PGlite({ loadDataDir: dump });
16
+ const pglite = new pglite_1.PGlite({
17
+ loadDataDir: dump,
18
+ });
18
19
  // warm up
19
20
  const dialect = new kysely_pglite_dialect_1.PGliteDialect(pglite);
20
- const kysely = new kysely_1.Kysely({
21
- dialect,
22
- log: args.log === true ? ['query', 'error'] : args.log,
23
- plugins: [
24
- new kysely_1.CamelCasePlugin(),
25
- new pganalyze_comment_plugin_1.KyselyPganalyzeCommentPlugin({
26
- repository: args.repositoryName ?? 'localTesting',
27
- }),
28
- ],
21
+ const kysely = (0, plugins_1.getKysely)(dialect, {
22
+ repositoryName: args?.repositoryName ?? 'localTesting',
23
+ log: args?.log,
29
24
  });
30
25
  await (0, digest_1.ensureDigestFunction)(kysely);
26
+ await (0, digest_1.ensureGenRandomBytesFunction)(kysely);
31
27
  const originalDestroy = kysely.destroy.bind(kysely);
32
28
  kysely.destroy = async () => {
33
29
  if (isDestroyed)
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"src/","sources":["local/index.ts"],"names":[],"mappings":";;;AAeA,wCAoCC;AAnDD,yCAAiC;AACjC,iDAA8C;AAC9C,mCAAiE;AACjE,iEAAsD;AACtD,0EAA2E;AAE3E,qCAAgD;AAEnC,QAAA,IAAI,GAAG,IAAA,gBAAI,EAAC,SAAS,EAAE,OAAO,CAAC,CAAC;AAChC,QAAA,QAAQ,GAAG,IAAA,gBAAI,EAAC,YAAI,EAAE,WAAW,CAAC,CAAC;AAMzC,KAAK,UAAU,cAAc,CAAC,OAA8B,EAAE;IACnE,IAAI,WAAW,GAAG,KAAK,CAAC;IACxB,iCAAiC;IAEjC,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,OAAO,GAAG,IAAI,qCAAa,CAAC,MAAM,CAAC,CAAC;IAC1C,MAAM,MAAM,GAAG,IAAI,eAAM,CAAK;QAC5B,OAAO;QACP,GAAG,EAAE,IAAI,CAAC,GAAG,KAAK,IAAI,CAAC,CAAC,CAAC,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG;QACtD,OAAO,EAAE;YACP,IAAI,wBAAe,EAAE;YACrB,IAAI,uDAA4B,CAAC;gBAC/B,UAAU,EAAE,IAAI,CAAC,cAAc,IAAI,cAAc;aAClD,CAAC;SACH;KACF,CAAC,CAAC;IACH,MAAM,IAAA,6BAAoB,EAAC,MAAM,CAAC,CAAC;IAEnC,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,wCAAwC;QACxC,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,cAAc;QACd,0EAA0E;QAC1E,IAAI;IACN,CAAC,CAAC;IAEF,iFAAiF;IAEjF,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import { join } from 'node:path';\nimport { PGlite } from '@electric-sql/pglite';\nimport { CamelCasePlugin, Kysely, type LogConfig } from 'kysely';\nimport { PGliteDialect } from 'kysely-pglite-dialect';\nimport { KyselyPganalyzeCommentPlugin } from '../pganalyze-comment-plugin';\nimport type { DB } from '../v1.generated';\nimport { ensureDigestFunction } from './digest';\n\nexport const root = join(__dirname, '../..');\nexport const dumpPath = join(root, '.data.tar');\n\nexport type UseLocalKyselyOptions = {\n repositoryName?: string;\n log?: true | LogConfig;\n};\nexport async function useLocalKysely(args: UseLocalKyselyOptions = {}) {\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 const dialect = new PGliteDialect(pglite);\n const kysely = new Kysely<DB>({\n dialect,\n log: args.log === true ? ['query', 'error'] : args.log,\n plugins: [\n new CamelCasePlugin(),\n new KyselyPganalyzeCommentPlugin({\n repository: args.repositoryName ?? 'localTesting',\n }),\n ],\n });\n await ensureDigestFunction(kysely);\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
+ {"version":3,"file":"index.js","sourceRoot":"src/","sources":["local/index.ts"],"names":[],"mappings":";;;AAcA,wCAiCC;AA/CD,yCAAiC;AACjC,iDAA8C;AAE9C,iEAAsD;AACtD,wCAAuC;AACvC,qCAA8E;AAEjE,QAAA,IAAI,GAAG,IAAA,gBAAI,EAAC,SAAS,EAAE,OAAO,CAAC,CAAC;AAChC,QAAA,QAAQ,GAAG,IAAA,gBAAI,EAAC,YAAI,EAAE,WAAW,CAAC,CAAC;AAMzC,KAAK,UAAU,cAAc,CAAC,OAA8B,EAAE;IACnE,IAAI,WAAW,GAAG,KAAK,CAAC;IACxB,iCAAiC;IAEjC,MAAM,IAAI,GAAG,GAAG,CAAC,IAAI,CAAC,gBAAQ,CAAC,CAAC;IAEhC,MAAM,MAAM,GAAG,IAAI,eAAM,CAAC;QACxB,WAAW,EAAE,IAAI;KAClB,CAAC,CAAC;IACH,UAAU;IACV,MAAM,OAAO,GAAG,IAAI,qCAAa,CAAC,MAAM,CAAC,CAAC;IAC1C,MAAM,MAAM,GAAG,IAAA,mBAAS,EAAC,OAAO,EAAE;QAChC,cAAc,EAAE,IAAI,EAAE,cAAc,IAAI,cAAc;QACtD,GAAG,EAAE,IAAI,EAAE,GAAG;KACf,CAAC,CAAC;IACH,MAAM,IAAA,6BAAoB,EAAC,MAAM,CAAC,CAAC;IACnC,MAAM,IAAA,qCAA4B,EAAC,MAAM,CAAC,CAAC;IAE3C,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,wCAAwC;QACxC,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,cAAc;QACd,0EAA0E;QAC1E,IAAI;IACN,CAAC,CAAC;IAEF,iFAAiF;IAEjF,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import { join } from 'node:path';\nimport { PGlite } from '@electric-sql/pglite';\nimport type { LogConfig } from 'kysely';\nimport { PGliteDialect } from 'kysely-pglite-dialect';\nimport { getKysely } from '../plugins';\nimport { ensureDigestFunction, ensureGenRandomBytesFunction } from './digest';\n\nexport const root = join(__dirname, '../..');\nexport const dumpPath = join(root, '.data.tar');\n\nexport type UseLocalKyselyOptions = {\n repositoryName?: string;\n log?: true | LogConfig;\n};\nexport async function useLocalKysely(args: UseLocalKyselyOptions = {}) {\n let isDestroyed = false;\n // const now = performance.now();\n\n const dump = Bun.file(dumpPath);\n\n const pglite = new PGlite({\n loadDataDir: dump,\n });\n // warm up\n const dialect = new PGliteDialect(pglite);\n const kysely = getKysely(dialect, {\n repositoryName: args?.repositoryName ?? 'localTesting',\n log: args?.log,\n });\n await ensureDigestFunction(kysely);\n await ensureGenRandomBytesFunction(kysely);\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,3 @@
1
+ import { Kysely } from 'kysely';
2
+ import type { DB } from './v1.generated';
3
+ export declare function useLocalKysely(): Promise<Kysely<DB>>;
@@ -0,0 +1,158 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ var __importDefault = (this && this.__importDefault) || function (mod) {
36
+ return (mod && mod.__esModule) ? mod : { "default": mod };
37
+ };
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.useLocalKysely = useLocalKysely;
40
+ const node_fs_1 = require("node:fs");
41
+ const promises_1 = require("node:fs/promises");
42
+ const path = __importStar(require("node:path"));
43
+ const node_path_1 = require("node:path");
44
+ const pglite_1 = require("@electric-sql/pglite");
45
+ const kysely_1 = require("kysely");
46
+ const kysely_codegen_1 = __importDefault(require("kysely-codegen"));
47
+ const kysely_pglite_1 = require("kysely-pglite");
48
+ const root = (0, node_path_1.join)(__dirname, '..');
49
+ async function migrate(client) {
50
+ console.log('migrating pglite ....');
51
+ const glob = new Bun.Glob('initial/*.sql');
52
+ for await (const migration of glob.scan(root)) {
53
+ await client.exec(await Bun.file((0, node_path_1.join)(root, migration)).text());
54
+ }
55
+ }
56
+ async function migrateKysely(kysely) {
57
+ console.log('init migrating kysely ....');
58
+ const migrator = new kysely_1.Migrator({
59
+ db: kysely,
60
+ migrationTableSchema: 'core',
61
+ migrationTableName: 'kysely_migration',
62
+ migrationLockTableName: 'kysely_migration_lock',
63
+ provider: new kysely_1.FileMigrationProvider({
64
+ fs: node_fs_1.promises,
65
+ path,
66
+ // This needs to be an absolute path.
67
+ migrationFolder: path.join(root, 'migrations'),
68
+ }),
69
+ });
70
+ console.log('migrating kysely ....');
71
+ const { error, results } = await migrator.migrateToLatest().catch(() => {
72
+ console.error('failed to migrate');
73
+ process.exit(1);
74
+ });
75
+ for (const it of results ?? []) {
76
+ if (it.status === 'Success') {
77
+ console.log(`migration "${it.migrationName}" was executed successfully`);
78
+ }
79
+ else if (it.status === 'Error') {
80
+ console.error(`failed to execute migration "${it.migrationName}"`);
81
+ }
82
+ }
83
+ if (error) {
84
+ console.error('failed to migrate');
85
+ console.error(error);
86
+ process.exit(1);
87
+ }
88
+ }
89
+ const dumpPath = (0, node_path_1.join)(root, '.data.tar');
90
+ const dumpFile = (async () => {
91
+ const dataExists = await (0, promises_1.exists)(dumpPath).catch(() => false);
92
+ if (!dataExists) {
93
+ console.log('Creating initial dump');
94
+ const main = new pglite_1.PGlite();
95
+ await migrate(main).catch(async (err) => {
96
+ console.error('failed to migrate initial dump');
97
+ await Bun.write('../logs/migrate-initial-dump.json', JSON.stringify(err, null, 2));
98
+ process.exit(1);
99
+ });
100
+ const { dialect } = new kysely_pglite_1.KyselyPGlite(main);
101
+ const kysely = new kysely_1.Kysely({
102
+ dialect,
103
+ plugins: [new kysely_1.CamelCasePlugin()],
104
+ });
105
+ await migrateKysely(kysely).catch(() => {
106
+ console.error('failed to migrate kysely');
107
+ process.exit(1);
108
+ });
109
+ await kysely_codegen_1.default
110
+ .generate({
111
+ db: kysely,
112
+ outFile: path.join(root, 'src/v1.generated.ts'),
113
+ defaultSchemas: ['xxx'],
114
+ camelCase: true,
115
+ dialect: kysely_codegen_1.default.getDialect('postgres'),
116
+ })
117
+ .catch(() => {
118
+ console.error('failed to generate kysely');
119
+ process.exit(1);
120
+ });
121
+ const content = await main.dumpDataDir('none').catch(() => {
122
+ console.error('failed to dump data');
123
+ process.exit(1);
124
+ });
125
+ await Bun.write(dumpPath, content).catch(() => {
126
+ console.error('failed to write dump');
127
+ process.exit(1);
128
+ });
129
+ return content;
130
+ }
131
+ return Bun.file(dumpPath);
132
+ })();
133
+ async function useLocalKysely() {
134
+ let isDestroyed = false;
135
+ const now = performance.now();
136
+ const dump = await dumpFile;
137
+ const pglite = new pglite_1.PGlite({ loadDataDir: dump });
138
+ // warm up
139
+ await pglite.sql `SELECT 1`;
140
+ const { dialect } = new kysely_pglite_1.KyselyPGlite(pglite);
141
+ const kysely = new kysely_1.Kysely({
142
+ dialect,
143
+ plugins: [new kysely_1.CamelCasePlugin()],
144
+ });
145
+ const originalDestroy = kysely.destroy.bind(kysely);
146
+ kysely.destroy = async () => {
147
+ if (isDestroyed)
148
+ return;
149
+ isDestroyed = true;
150
+ const destroyTime = performance.now();
151
+ await originalDestroy().catch(() => undefined);
152
+ await pglite.close().catch(() => undefined);
153
+ console.log(`Database destroyed: ${Math.round(performance.now() - destroyTime)}ms`);
154
+ };
155
+ console.log(`Database initialized: ${Math.round(performance.now() - now)}ms`);
156
+ return kysely;
157
+ }
158
+ //# sourceMappingURL=local.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"local.js","sourceRoot":"src/","sources":["local.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4GA,wCA8BC;AA1ID,qCAAyC;AACzC,+CAA0C;AAC1C,gDAAkC;AAClC,yCAAiC;AACjC,iDAA8C;AAC9C,mCAKgB;AAChB,oEAAqC;AACrC,iDAA6C;AAG7C,MAAM,IAAI,GAAG,IAAA,gBAAI,EAAC,SAAS,EAAE,IAAI,CAAC,CAAC;AACnC,KAAK,UAAU,OAAO,CAAC,MAAc;IACnC,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,MAAmB;IAC9C,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,sBAAs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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\nconst root = join(__dirname, '..');\nasync function migrate(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(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\nconst dumpPath = join(root, '.data.tar');\nconst dumpFile = (async () => {\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(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(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 useLocalKysely() {\n let isDestroyed = false;\n const now = performance.now();\n\n const dump = await dumpFile;\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,6 @@
1
+ import { type Dialect, Kysely as K, type LogConfig } from 'kysely';
2
+ import type { DB } from './v1.generated';
3
+ export declare function getKysely(dialect: Dialect, options: {
4
+ repositoryName?: string;
5
+ log?: true | LogConfig;
6
+ }): K<DB>;
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getKysely = getKysely;
4
+ const kysely_1 = require("kysely");
5
+ const camel_case_1 = require("./camel-case");
6
+ const pganalyze_comment_plugin_1 = require("./pganalyze-comment-plugin");
7
+ function getKysely(dialect, options) {
8
+ const plugins = [new camel_case_1.CustomCasePlugin()];
9
+ if (options?.repositoryName) {
10
+ plugins.push(new pganalyze_comment_plugin_1.KyselyPganalyzeCommentPlugin({
11
+ repository: options.repositoryName,
12
+ }));
13
+ }
14
+ const kysely = new kysely_1.Kysely({
15
+ dialect,
16
+ plugins,
17
+ log: options?.log === true ? ['query', 'error'] : options?.log,
18
+ });
19
+ return kysely;
20
+ }
21
+ //# sourceMappingURL=plugins.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"plugins.js","sourceRoot":"src/","sources":["plugins.ts"],"names":[],"mappings":";;AAUA,8BAmBC;AA7BD,mCAKgB;AAChB,6CAAgD;AAChD,yEAA0E;AAG1E,SAAgB,SAAS,CACvB,OAAgB,EAChB,OAA4D;IAE5D,MAAM,OAAO,GAAmB,CAAC,IAAI,6BAAgB,EAAE,CAAC,CAAC;IAEzD,IAAI,OAAO,EAAE,cAAc,EAAE,CAAC;QAC5B,OAAO,CAAC,IAAI,CACV,IAAI,uDAA4B,CAAC;YAC/B,UAAU,EAAE,OAAO,CAAC,cAAc;SACnC,CAAC,CACH,CAAC;IACJ,CAAC;IACD,MAAM,MAAM,GAAG,IAAI,eAAC,CAAK;QACvB,OAAO;QACP,OAAO;QACP,GAAG,EAAE,OAAO,EAAE,GAAG,KAAK,IAAI,CAAC,CAAC,CAAC,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC,OAAO,EAAE,GAAG;KAC/D,CAAC,CAAC;IACH,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import {\n type Dialect,\n Kysely as K,\n type KyselyPlugin,\n type LogConfig,\n} from 'kysely';\nimport { CustomCasePlugin } from './camel-case';\nimport { KyselyPganalyzeCommentPlugin } from './pganalyze-comment-plugin';\nimport type { DB } from './v1.generated';\n\nexport function getKysely(\n dialect: Dialect,\n options: { repositoryName?: string; log?: true | LogConfig }\n) {\n const plugins: KyselyPlugin[] = [new CustomCasePlugin()];\n\n if (options?.repositoryName) {\n plugins.push(\n new KyselyPganalyzeCommentPlugin({\n repository: options.repositoryName,\n })\n );\n }\n const kysely = new K<DB>({\n dialect,\n plugins,\n log: options?.log === true ? ['query', 'error'] : options?.log,\n });\n return kysely;\n}\n"]}