@vrplatform/kysely 1.3.40 → 1.3.41-4244

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 (106) hide show
  1. package/build/.data.tar +0 -0
  2. package/build/main/camel-case/index.js.map +1 -1
  3. package/build/main/control-plane/index.d.ts +141 -0
  4. package/build/main/control-plane/index.js +3 -0
  5. package/build/main/control-plane/index.js.map +1 -0
  6. package/build/main/error.js.map +1 -1
  7. package/build/main/index.d.ts +6 -3
  8. package/build/main/index.js +8 -9
  9. package/build/main/index.js.map +1 -1
  10. package/build/main/isomorphic.d.ts +2 -1
  11. package/build/main/isomorphic.js +2 -2
  12. package/build/main/isomorphic.js.map +1 -1
  13. package/build/main/local/digest.js.map +1 -1
  14. package/build/main/local/generate.js +12 -0
  15. package/build/main/local/generate.js.map +1 -1
  16. package/build/main/local/index.d.ts +3 -2
  17. package/build/main/local/index.js +56 -3
  18. package/build/main/local/index.js.map +1 -1
  19. package/build/main/local/prune-pulled-schema.js.map +1 -1
  20. package/build/main/pganalyze-comment-plugin/comment-transformer.js +0 -1
  21. package/build/main/pganalyze-comment-plugin/comment-transformer.js.map +1 -1
  22. package/build/main/pganalyze-comment-plugin/index.js +16 -3
  23. package/build/main/pganalyze-comment-plugin/index.js.map +1 -1
  24. package/build/main/plugins.js.map +1 -1
  25. package/build/main/query/listing/status.d.ts +4 -4
  26. package/build/main/query/listing/status.js +19 -2
  27. package/build/main/query/listing/status.js.map +1 -1
  28. package/build/main/regional.d.ts +34 -0
  29. package/build/main/regional.js +145 -0
  30. package/build/main/regional.js.map +1 -0
  31. package/build/main/test/index.js.map +1 -1
  32. package/build/main/transaction.d.ts +7 -0
  33. package/build/main/transaction.js +32 -0
  34. package/build/main/transaction.js.map +1 -0
  35. package/build/main/v1.generated.d.ts +133 -2
  36. package/build/main/v1.generated.js.map +1 -1
  37. package/build/migrations/0000000000001-init.ts +5 -0
  38. package/build/migrations/0000000000009-drop-store-schema.ts +14 -0
  39. package/build/migrations/0000000000010-bank-rules.ts +190 -0
  40. package/build/migrations/0000000000011-bank-rule-line-adjustments.ts +65 -0
  41. package/build/migrations/0000000000012-bank-rule-conditions.ts +45 -0
  42. package/build/migrations/0000000000013-bank-rule-name-unique.ts +15 -0
  43. package/build/migrations/0000000000014-bank-rule-drop-legacy-conditions.ts +41 -0
  44. package/build/migrations/0000000000015-booking-channel-logo-dev-provider.ts +70 -0
  45. package/build/migrations/0000000000016-owner-statement-draft-status.ts +22 -0
  46. package/build/migrations/0000000000017-tenant-migration-markers.ts +18 -0
  47. package/build/migrations/0000000000018-security-deposits-payable-category.ts +63 -0
  48. package/build/migrations/0000000000019-tenant-app-settings.ts +76 -0
  49. package/build/migrations/0000000000020-operating-opening-trial-balance.ts +36 -0
  50. package/build/migrations/0000000000021-audit-foreign-key-indexes.ts +77 -0
  51. package/build/migrations/0000000000022-opening-trial-balance-combined-columns.ts +30 -0
  52. package/build/migrations/0000000000023-journal-entry-currency-mismatch-reason.ts +14 -0
  53. package/build/migrations/0000000000024-listing-parent.ts +37 -0
  54. package/build/migrations/0000000000025-journal-entry-parent-listing.ts +26 -0
  55. package/build/migrations/0000000000026-booking-channel-logo-slots.ts +89 -0
  56. package/build/migrations/0000000000027-list-browse-performance-indexes.ts +52 -0
  57. package/build/migrations/0000000000028-flow-setting-status-jsonb.ts +20 -0
  58. package/build/migrations/0000000000029-tenant-slug.ts +328 -0
  59. package/build/migrations/0000000000030-pms-accounting-windows.ts +50 -0
  60. package/build/migrations/0000000000031-owner-statement-projection-listing-revision.ts +20 -0
  61. package/build/migrations/0000000000032-flow-event-listening.ts +28 -0
  62. package/build/migrations/0000000000033-opening-trial-balance-transaction.ts +272 -0
  63. package/build/migrations/0000000000034-historic-general-ledger.ts +24 -0
  64. package/build/migrations/0000000000035-tenant-regional-placement.ts +37 -0
  65. package/build/migrations/0000000000036-control-plane-projection-events.ts +43 -0
  66. package/build/migrations/0000000000037-tenant-guide-onboarding.ts +21 -0
  67. package/build/migrations/0000000000038-ramp-staging-connect-params.ts +35 -0
  68. package/build/migrations/0000000000038-tracking-event-analytics-sink.ts +31 -0
  69. package/build/migrations/0000000000039-crunchy-region.ts +86 -0
  70. package/build/migrations/0000000000039-gl-pms-accounting-window-guard.ts +125 -0
  71. package/build/migrations/0000000000040-hostaway-region.ts +68 -0
  72. package/build/module/camel-case/index.js.map +1 -1
  73. package/build/module/control-plane/index.d.ts +141 -0
  74. package/build/module/control-plane/index.js +2 -0
  75. package/build/module/control-plane/index.js.map +1 -0
  76. package/build/module/error.js.map +1 -1
  77. package/build/module/index.d.ts +6 -3
  78. package/build/module/index.js +8 -9
  79. package/build/module/index.js.map +1 -1
  80. package/build/module/isomorphic.d.ts +2 -1
  81. package/build/module/isomorphic.js.map +1 -1
  82. package/build/module/local/digest.js.map +1 -1
  83. package/build/module/local/generate.js +12 -0
  84. package/build/module/local/generate.js.map +1 -1
  85. package/build/module/local/index.d.ts +3 -2
  86. package/build/module/local/index.js +23 -3
  87. package/build/module/local/index.js.map +1 -1
  88. package/build/module/local/prune-pulled-schema.js.map +1 -1
  89. package/build/module/pganalyze-comment-plugin/comment-transformer.js.map +1 -1
  90. package/build/module/pganalyze-comment-plugin/index.js.map +1 -1
  91. package/build/module/plugins.js.map +1 -1
  92. package/build/module/query/listing/status.d.ts +4 -4
  93. package/build/module/query/listing/status.js +19 -2
  94. package/build/module/query/listing/status.js.map +1 -1
  95. package/build/module/regional.d.ts +34 -0
  96. package/build/module/regional.js +103 -0
  97. package/build/module/regional.js.map +1 -0
  98. package/build/module/test/index.js.map +1 -1
  99. package/build/module/transaction.d.ts +7 -0
  100. package/build/module/transaction.js +25 -0
  101. package/build/module/transaction.js.map +1 -0
  102. package/build/module/v1.generated.d.ts +133 -2
  103. package/build/module/v1.generated.js.map +1 -1
  104. package/package.json +13 -4
  105. package/build/main/tsconfig.main.tsbuildinfo +0 -1
  106. package/build/module/tsconfig.esm.tsbuildinfo +0 -1
@@ -0,0 +1,125 @@
1
+ import type { Kysely } from 'kysely';
2
+ import { sql } from 'kysely';
3
+
4
+ export async function up(db: Kysely<any>): Promise<void> {
5
+ await sql`
6
+ create or replace function public.assert_gl_pms_accounting_window_for_tenant(
7
+ check_tenant_id uuid
8
+ )
9
+ returns void
10
+ language plpgsql
11
+ as $$
12
+ begin
13
+ if check_tenant_id is null then
14
+ return;
15
+ end if;
16
+
17
+ if exists (
18
+ select 1
19
+ from public.tenant as tenant
20
+ where tenant.id = check_tenant_id
21
+ and tenant.is_general_ledger is true
22
+ and exists (
23
+ select 1
24
+ from public.connection as connection
25
+ inner join public.app as app on app.id = connection.app_id
26
+ where connection.tenant_id = check_tenant_id
27
+ and connection.status = 'active'
28
+ and connection.accounting_start_at is null
29
+ and app.category = 'propertyManagementSystem'
30
+ )
31
+ and not exists (
32
+ select 1
33
+ from public.connection as connection
34
+ inner join public.app as app on app.id = connection.app_id
35
+ where connection.tenant_id = check_tenant_id
36
+ and connection.status = 'active'
37
+ and connection.accounting_start_at is not null
38
+ and connection.accounting_end_at is null
39
+ and app.category = 'propertyManagementSystem'
40
+ )
41
+ ) then
42
+ raise exception
43
+ 'Active GL PMS connection is missing accountingStartAt without an open PMS accounting source'
44
+ using errcode = '23514';
45
+ end if;
46
+ end;
47
+ $$;
48
+ `.execute(db);
49
+
50
+ await sql`
51
+ create or replace function public.assert_gl_pms_accounting_window_connection_trigger()
52
+ returns trigger
53
+ language plpgsql
54
+ as $$
55
+ begin
56
+ if tg_op = 'DELETE' then
57
+ perform public.assert_gl_pms_accounting_window_for_tenant(old.tenant_id);
58
+ return null;
59
+ end if;
60
+
61
+ if tg_op = 'UPDATE' and new.tenant_id is distinct from old.tenant_id then
62
+ perform public.assert_gl_pms_accounting_window_for_tenant(old.tenant_id);
63
+ end if;
64
+
65
+ perform public.assert_gl_pms_accounting_window_for_tenant(new.tenant_id);
66
+ return null;
67
+ end;
68
+ $$;
69
+ `.execute(db);
70
+
71
+ await sql`
72
+ create or replace function public.assert_gl_pms_accounting_window_tenant_trigger()
73
+ returns trigger
74
+ language plpgsql
75
+ as $$
76
+ begin
77
+ if new.is_general_ledger is true then
78
+ perform public.assert_gl_pms_accounting_window_for_tenant(new.id);
79
+ end if;
80
+
81
+ return null;
82
+ end;
83
+ $$;
84
+ `.execute(db);
85
+
86
+ await sql`
87
+ create constraint trigger connection_gl_pms_accounting_window_guard
88
+ after insert or update or delete on public.connection
89
+ deferrable initially deferred
90
+ for each row
91
+ execute function public.assert_gl_pms_accounting_window_connection_trigger();
92
+ `.execute(db);
93
+
94
+ await sql`
95
+ create constraint trigger tenant_gl_pms_accounting_window_guard
96
+ after insert or update on public.tenant
97
+ deferrable initially deferred
98
+ for each row
99
+ execute function public.assert_gl_pms_accounting_window_tenant_trigger();
100
+ `.execute(db);
101
+ }
102
+
103
+ export async function down(db: Kysely<any>): Promise<void> {
104
+ await sql`
105
+ drop trigger if exists tenant_gl_pms_accounting_window_guard
106
+ on public.tenant;
107
+ `.execute(db);
108
+
109
+ await sql`
110
+ drop trigger if exists connection_gl_pms_accounting_window_guard
111
+ on public.connection;
112
+ `.execute(db);
113
+
114
+ await sql`
115
+ drop function if exists public.assert_gl_pms_accounting_window_tenant_trigger();
116
+ `.execute(db);
117
+
118
+ await sql`
119
+ drop function if exists public.assert_gl_pms_accounting_window_connection_trigger();
120
+ `.execute(db);
121
+
122
+ await sql`
123
+ drop function if exists public.assert_gl_pms_accounting_window_for_tenant(uuid);
124
+ `.execute(db);
125
+ }
@@ -0,0 +1,68 @@
1
+ import type { Kysely } from 'kysely';
2
+ import { sql } from 'kysely';
3
+
4
+ // 'hostaway' is a partner-dedicated region: Hostaway-managed tenants get
5
+ // their own Neon cell so scaling issues never cross-impact other regions.
6
+ // Pure widening — no existing placement changes; the vrintegration pin to
7
+ // crunchy is unchanged.
8
+ export async function up(db: Kysely<any>): Promise<void> {
9
+ await sql`
10
+ alter table public.tenant
11
+ drop constraint tenant_data_region_check;
12
+ `.execute(db);
13
+
14
+ await sql`
15
+ alter table public.tenant
16
+ add constraint tenant_data_region_check
17
+ check (data_region in ('ap', 'crunchy', 'eu', 'hostaway', 'us'));
18
+ `.execute(db);
19
+
20
+ await sql`
21
+ alter table public.control_plane_projection_event
22
+ drop constraint control_plane_projection_event_region_check;
23
+ `.execute(db);
24
+
25
+ await sql`
26
+ alter table public.control_plane_projection_event
27
+ add constraint control_plane_projection_event_region_check
28
+ check (data_region in ('ap', 'crunchy', 'eu', 'hostaway', 'us'));
29
+ `.execute(db);
30
+ }
31
+
32
+ export async function down(db: Kysely<any>): Promise<void> {
33
+ await sql`
34
+ alter table public.control_plane_projection_event
35
+ drop constraint control_plane_projection_event_region_check;
36
+ `.execute(db);
37
+
38
+ // Rollback re-homes any hostaway placements to crunchy before narrowing,
39
+ // mirroring the crunchy migration's revert pattern.
40
+ await sql`
41
+ update public.control_plane_projection_event
42
+ set data_region = 'crunchy'
43
+ where data_region = 'hostaway';
44
+ `.execute(db);
45
+
46
+ await sql`
47
+ alter table public.control_plane_projection_event
48
+ add constraint control_plane_projection_event_region_check
49
+ check (data_region in ('ap', 'crunchy', 'eu', 'us'));
50
+ `.execute(db);
51
+
52
+ await sql`
53
+ alter table public.tenant
54
+ drop constraint tenant_data_region_check;
55
+ `.execute(db);
56
+
57
+ await sql`
58
+ update public.tenant
59
+ set data_region = 'crunchy'
60
+ where data_region = 'hostaway';
61
+ `.execute(db);
62
+
63
+ await sql`
64
+ alter table public.tenant
65
+ add constraint tenant_data_region_check
66
+ check (data_region in ('ap', 'crunchy', 'eu', 'us'));
67
+ `.execute(db);
68
+ }
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"src/","sources":["camel-case/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,eAAe,GAIhB,MAAM,QAAQ,CAAC;AAChB,OAAO,EAAE,WAAW,EAAE,MAAM,UAAU,CAAC;AAEvC,MAAM,OAAO,gBAAiB,SAAQ,eAAe;IACnD,kDAAkD;IAClD,cAAc;QACZ,KAAK,C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AG,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;IAAA,CACf;CACF","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"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"src/","sources":["camel-case/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,eAAe,GAIhB,MAAM,QAAQ,CAAC;AAChB,OAAO,EAAE,WAAW,EAAE,MAAM,UAAU,CAAC;AAEvC,MAAM,OAAO,gBAAiB,SAAQ,eAAe;IACnD,kDAAkD;IAClD;QACE,KAAK,CAAC;YACJ,wBAAwB,EAAE,IAAI;SAC/B,CAAC,CAAC;IACL,CAAC;IAED,eAAe,CAAC,IAAI;QAClB,OAAO,KAAK,CAAC,eAAe,CAAC,IAAI,CAAC,CAAC;IACrC,CAAC;IAED,cAAc,CAAC,IAAI;QACjB,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QAC5B,OAAO,KAAK,CAAC,cAAc,CAAC,IAAI,CAAC,CAAC;IACpC,CAAC;IAED,WAAW,CAAC,IAAqB;QAC/B,IAAI,CAAC,IAAI,EAAE,UAAU;YAAE,OAAO;QAE9B,KAAK,MAAM,CAAC,IAAI,IAAI,CAAC,UAAU,IAAI,EAAE,EAAE,CAAC;YACtC,MAAM,SAAS,GAAG,CAAC,CAAC,SAAsB,CAAC;YAC3C,IAAI,CAAC,SAAS,CAAC,KAAK;gBAAE,SAAS;YAC/B,MAAM,KAAK,GAAG,SAAS,CAAC,KAAuB,CAAC;YAEhD,0CAA0C;YAC1C,IAAI,SAAS,CAAC,IAAI,CA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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,141 @@
1
+ import type { ColumnType, Kysely as K } from 'kysely';
2
+ export type Generated<T> = T extends ColumnType<infer S, infer I, infer U> ? ColumnType<S, I | undefined, U> : ColumnType<T, T | undefined, T>;
3
+ export type Json = JsonValue;
4
+ export type JsonArray = JsonValue[];
5
+ export type JsonObject = {
6
+ [x: string]: JsonValue | undefined;
7
+ };
8
+ export type JsonPrimitive = boolean | number | string | null;
9
+ export type JsonValue = JsonArray | JsonObject | JsonPrimitive;
10
+ export type Timestamp = ColumnType<Date | string, Date | string, Date | string>;
11
+ export interface ControlPlaneApp {
12
+ authentication: Generated<Json>;
13
+ category: string | null;
14
+ color: string | null;
15
+ createdAt: Generated<Timestamp>;
16
+ icon: string | null;
17
+ iconRound: string | null;
18
+ id: Generated<string>;
19
+ info: Json | null;
20
+ name: string;
21
+ type: string;
22
+ version: Generated<number>;
23
+ }
24
+ export interface ControlPlaneBookingChannel {
25
+ channelRef: string | null;
26
+ color: string | null;
27
+ createdAt: Generated<Timestamp>;
28
+ icon: string | null;
29
+ iconProvider: string | null;
30
+ id: Generated<string>;
31
+ lastGenerateRun: Timestamp | null;
32
+ logo: string | null;
33
+ logoProvider: string | null;
34
+ selectedBookingChannelIconCandidateId: string | null;
35
+ selectedBookingChannelLogoCandidateId: string | null;
36
+ uniqueRef: string;
37
+ updatedAt: Generated<Timestamp>;
38
+ }
39
+ export interface ControlPlaneCurrency {
40
+ name: string;
41
+ }
42
+ export interface ControlPlaneConnectionRoute {
43
+ connectionId: string;
44
+ createdAt: Generated<Timestamp>;
45
+ tenantId: string;
46
+ updatedAt: Generated<Timestamp>;
47
+ }
48
+ export interface ControlPlaneFeature {
49
+ createdAt: Generated<Timestamp>;
50
+ description: string | null;
51
+ id: Generated<string>;
52
+ issueUrl: string | null;
53
+ requiredApprovals: Generated<Json | null>;
54
+ status: Generated<string | null>;
55
+ tenantId: string | null;
56
+ title: string;
57
+ updatedAt: Generated<Timestamp>;
58
+ url: string | null;
59
+ }
60
+ export interface ControlPlaneFeatureEnabledTeam {
61
+ createdAt: Generated<Timestamp>;
62
+ featureId: string;
63
+ id: Generated<string>;
64
+ status: Generated<string | null>;
65
+ tenantId: string;
66
+ updatedAt: Generated<Timestamp>;
67
+ }
68
+ export interface ControlPlaneOutbox {
69
+ aggregateId: string;
70
+ aggregateType: string;
71
+ attempts: Generated<number>;
72
+ createdAt: Generated<Timestamp>;
73
+ dataRegion: string | null;
74
+ eventType: string;
75
+ eventVersion: number;
76
+ id: Generated<string>;
77
+ lastError: string | null;
78
+ payload: Generated<Json>;
79
+ publishedAt: Timestamp | null;
80
+ }
81
+ export interface ControlPlaneTenant {
82
+ createdAt: Generated<Timestamp>;
83
+ dataRegion: Generated<string>;
84
+ id: Generated<string>;
85
+ name: string;
86
+ partnerId: string | null;
87
+ slug: string;
88
+ status: Generated<string | null>;
89
+ storageRealm: Generated<string>;
90
+ type: Generated<string | null>;
91
+ updatedAt: Generated<Timestamp | null>;
92
+ }
93
+ export interface ControlPlaneTenantUser {
94
+ createdAt: Generated<Timestamp | null>;
95
+ id: Generated<string>;
96
+ lastInvitedAt: Timestamp | null;
97
+ role: Generated<string | null>;
98
+ status: Generated<string | null>;
99
+ tenantId: string;
100
+ updatedAt: Generated<Timestamp | null>;
101
+ userId: string;
102
+ }
103
+ export interface ControlPlaneToken {
104
+ createdAt: Generated<Timestamp>;
105
+ expiresAt: Timestamp | null;
106
+ id: Generated<string>;
107
+ nanoId: Generated<string>;
108
+ payload: Generated<Json>;
109
+ tenantId: string | null;
110
+ type: string | null;
111
+ userId: string | null;
112
+ }
113
+ export interface ControlPlaneUser {
114
+ clerkId: string | null;
115
+ createdAt: Generated<Timestamp | null>;
116
+ email: string | null;
117
+ firstName: string | null;
118
+ id: Generated<string>;
119
+ isAdmin: Generated<boolean>;
120
+ lastName: string | null;
121
+ name: string | null;
122
+ partnerId: string | null;
123
+ status: Generated<string | null>;
124
+ sub: string | null;
125
+ type: Generated<string | null>;
126
+ updatedAt: Generated<Timestamp | null>;
127
+ }
128
+ export interface ControlPlaneDB {
129
+ 'public.app': ControlPlaneApp;
130
+ 'public.bookingChannel': ControlPlaneBookingChannel;
131
+ 'public.connectionRoute': ControlPlaneConnectionRoute;
132
+ 'public.currency': ControlPlaneCurrency;
133
+ 'public.feature': ControlPlaneFeature;
134
+ 'public.featureEnabledTeam': ControlPlaneFeatureEnabledTeam;
135
+ 'public.controlPlaneOutbox': ControlPlaneOutbox;
136
+ 'public.tenant': ControlPlaneTenant;
137
+ 'public.tenantUser': ControlPlaneTenantUser;
138
+ 'public.token': ControlPlaneToken;
139
+ 'public.user': ControlPlaneUser;
140
+ }
141
+ export type ControlPlaneKysely = K<ControlPlaneDB>;
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"src/","sources":["control-plane/index.ts"],"names":[],"mappings":"","sourcesContent":["import type { ColumnType, Kysely as K } from 'kysely';\n\nexport type Generated<T> =\n T extends ColumnType<infer S, infer I, infer U>\n ? ColumnType<S, I | undefined, U>\n : ColumnType<T, T | undefined, T>;\n\nexport type Json = JsonValue;\n\nexport type JsonArray = JsonValue[];\n\nexport type JsonObject = {\n [x: string]: JsonValue | undefined;\n};\n\nexport type JsonPrimitive = boolean | number | string | null;\n\nexport type JsonValue = JsonArray | JsonObject | JsonPrimitive;\n\nexport type Timestamp = ColumnType<Date | string, Date | string, Date | string>;\n\nexport interface ControlPlaneApp {\n authentication: Generated<Json>;\n category: string | null;\n color: string | null;\n createdAt: Generated<Timestamp>;\n icon: string | null;\n iconRound: string | null;\n id: Generated<string>;\n info: Json | null;\n name: string;\n type: string;\n version: Generated<number>;\n}\n\nexport interface ControlPlaneBookingChannel {\n channelRef: string | null;\n color: string | null;\n createdAt: Generated<Timestamp>;\n icon: string | null;\n iconProvider: string | null;\n id: Generated<string>;\n lastGenerateRun: Timestamp | null;\n logo: string | null;\n logoProvider: string | null;\n selectedBookingChannelIconCandidateId: string | null;\n selectedBookingChannelLogoCandidateId: string | null;\n uniqueRef: string;\n updatedAt: Generated<Timestamp>;\n}\n\nexport interface ControlPlaneCurrency {\n name: string;\n}\n\nexport interface ControlPlaneConnectionRoute {\n connectionId: string;\n createdAt: Generated<Timestamp>;\n tenantId: string;\n updatedAt: Generated<Timestamp>;\n}\n\nexport interface ControlPlaneFeature {\n createdAt: Generated<Timestamp>;\n description: string | null;\n id: Generated<string>;\n issueUrl: string | null;\n requiredApprovals: Generated<Json | null>;\n status: Generated<string | null>;\n tenantId: string | null;\n title: string;\n updatedAt: Generated<Timestamp>;\n url: string | null;\n}\n\nexport interface ControlPlaneFeatureEnabledTeam {\n createdAt: Generated<Timestamp>;\n featureId: string;\n id: Generated<string>;\n status: Generated<string | null>;\n tenantId: string;\n updatedAt: Generated<Timestamp>;\n}\n\nexport interface ControlPlaneOutbox {\n aggregateId: string;\n aggregateType: string;\n attempts: Generated<number>;\n createdAt: Generated<Timestamp>;\n dataRegion: string | null;\n eventType: string;\n eventVersion: number;\n id: Generated<string>;\n lastError: string | null;\n payload: Generated<Json>;\n publishedAt: Timestamp | null;\n}\n\nexport interface ControlPlaneTenant {\n createdAt: Generated<Timestamp>;\n dataRegion: Generated<string>;\n id: Generated<string>;\n name: string;\n partnerId: string | null;\n slug: string;\n status: Generated<string | null>;\n storageRealm: Generated<string>;\n type: Generated<string | null>;\n updatedAt: Generated<Timestamp | null>;\n}\n\nexport interface ControlPlaneTenantUser {\n createdAt: Generated<Timestamp | null>;\n id: Generated<string>;\n lastInvitedAt: Timestamp | null;\n role: Generated<string | null>;\n status: Generated<string | null>;\n tenantId: string;\n updatedAt: Generated<Timestamp | null>;\n userId: string;\n}\n\nexport interface ControlPlaneToken {\n createdAt: Generated<Timestamp>;\n expiresAt: Timestamp | null;\n id: Generated<string>;\n nanoId: Generated<string>;\n payload: Generated<Json>;\n tenantId: string | null;\n type: string | null;\n userId: string | null;\n}\n\nexport interface ControlPlaneUser {\n clerkId: string | null;\n createdAt: Generated<Timestamp | null>;\n email: string | null;\n firstName: string | null;\n id: Generated<string>;\n isAdmin: Generated<boolean>;\n lastName: string | null;\n name: string | null;\n partnerId: string | null;\n status: Generated<string | null>;\n sub: string | null;\n type: Generated<string | null>;\n updatedAt: Generated<Timestamp | null>;\n}\n\nexport interface ControlPlaneDB {\n 'public.app': ControlPlaneApp;\n 'public.bookingChannel': ControlPlaneBookingChannel;\n 'public.connectionRoute': ControlPlaneConnectionRoute;\n 'public.currency': ControlPlaneCurrency;\n 'public.feature': ControlPlaneFeature;\n 'public.featureEnabledTeam': ControlPlaneFeatureEnabledTeam;\n 'public.controlPlaneOutbox': ControlPlaneOutbox;\n 'public.tenant': ControlPlaneTenant;\n 'public.tenantUser': ControlPlaneTenantUser;\n 'public.token': ControlPlaneToken;\n 'public.user': ControlPlaneUser;\n}\n\nexport type ControlPlaneKysely = K<ControlPlaneDB>;\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"error.js","sourceRoot":"src/","sources":["error.ts"],"names":[],"mappings":"AAAA,MAAM,OAAO,WAAY,SAAQ,KAAK;IACpC,YAAY,OAAe,EAAE;QAC3B,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,aAAa,CAAC;IAAA,CAC3B;CACF","sourcesContent":["export class KyselyError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'KyselyError';\n }\n}\n"]}
1
+ {"version":3,"file":"error.js","sourceRoot":"src/","sources":["error.ts"],"names":[],"mappings":"AAAA,MAAM,OAAO,WAAY,SAAQ,KAAK;IACpC,YAAY,OAAe;QACzB,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,aAAa,CAAC;IAC5B,CAAC;CACF","sourcesContent":["export class KyselyError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'KyselyError';\n }\n}\n"]}
@@ -1,9 +1,11 @@
1
1
  import type { Kysely as K, LogConfig } from 'kysely';
2
- import { type Sql } from 'postgres';
2
+ import postgres, { type Sql } from 'postgres';
3
3
  export type { Insertable, LogEvent } from 'kysely';
4
4
  export * from './error';
5
5
  export * from './isomorphic';
6
6
  export * from './query';
7
+ export * from './regional';
8
+ export * from './transaction';
7
9
  import type { DB } from './v1.generated';
8
10
  type KyselyOpts = {
9
11
  repositoryName?: string;
@@ -11,6 +13,7 @@ type KyselyOpts = {
11
13
  };
12
14
  type PgOpt = {
13
15
  forceDisableSSL?: boolean;
16
+ probe?: false;
14
17
  retries?: false | number;
15
18
  };
16
19
  export type Kysely = K<DB>;
@@ -19,12 +22,12 @@ export type Postgres = Sql;
19
22
  * @deprecated This method is deprecated in favor of the useAsyncKysely method.
20
23
  */
21
24
  export declare function useKysely(postgres: Sql, options?: KyselyOpts): K<DB>;
22
- export declare function useAsyncPostgres(connectionString: string, opt?: PgOpt): Promise<Sql<{}>>;
25
+ export declare function useAsyncPostgres(connectionString: string, opt?: PgOpt): Promise<postgres.Sql<{}>>;
23
26
  export declare function useAsyncKysely(connectionString: string, opt?: PgOpt & KyselyOpts): Promise<K<DB>>;
24
27
  /**
25
28
  * @deprecated This method is deprecated in favor of the useAsyncKysely method.
26
29
  */
27
- export declare function usePostgres(connectionString?: string, opt?: Pick<PgOpt, 'forceDisableSSL'>): Sql<{}>;
30
+ export declare function usePostgres(connectionString?: string, opt?: Pick<PgOpt, 'forceDisableSSL'>): postgres.Sql<{}>;
28
31
  export declare function forceCloseAllPostgres(timeoutMs?: number): Promise<void>;
29
32
  export declare class DatabaseError extends Error {
30
33
  constructor(message: string, cause: any);
@@ -6,6 +6,8 @@ import { getKysely } from './plugins';
6
6
  export * from './error';
7
7
  export * from './isomorphic';
8
8
  export * from './query';
9
+ export * from './regional';
10
+ export * from './transaction';
9
11
  import { parseDuration } from '@vrplatform/utils';
10
12
  const retryableMessages = ['CONNECTION_CLOSED'];
11
13
  /**
@@ -49,7 +51,7 @@ export function useKysely(postgres, options) {
49
51
  let _connections = [];
50
52
  export async function useAsyncPostgres(connectionString, opt) {
51
53
  const delayMs = 2500;
52
- const retries = opt?.retries === false ? 0 : opt?.retries || 3;
54
+ const retries = opt?.probe === false ? 1 : opt?.retries === false ? 0 : opt?.retries || 3;
53
55
  const ssl = opt?.forceDisableSSL !== true;
54
56
  const url = new URL(connectionString);
55
57
  console.debug(`Creating Postgres connection with ${retries} retries and ssl=${ssl} and port=${url.port}`);
@@ -66,15 +68,12 @@ export async function useAsyncPostgres(connectionString, opt) {
66
68
  connect_timeout: 10,
67
69
  idle_timeout: 60,
68
70
  });
69
- await sql `select 1`;
70
- try {
71
- // connect 30s, idle 60s, max lifetime 45min, statement 60s, lock 10s, log_min_duration 20s, log_lock_waits off
72
- await sql `set statement_timeout to '30s';`;
73
- await sql `set lock_timeout to '10s';`;
74
- }
75
- catch (e) {
76
- console.warn('Failed to set statement timeout, continuing', e);
71
+ if (opt?.probe !== false) {
72
+ await sql `select 1`;
77
73
  }
74
+ // statement_timeout/lock_timeout are role-level settings on the cluster
75
+ // (ALTER ROLE application SET ...) so they cover every pooled
76
+ // connection; per-session SETs here only ever applied to one of them
78
77
  _connections.push(sql);
79
78
  return sql;
80
79
  }
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"src/","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,qBAAqB,CAAC;AAE9C,OAAO,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AACvD,OAAO,QAAsB,MAAM,UAAU,CAAC;AAC9C,OAAO,EAAE,WAAW,EAAE,MAAM,SAAS,CAAC;AACtC,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AAGtC,cAAc,SAAS,CAAC;AACxB,cAAc,cAAc,CAAC;AAC7B,cAAc,SAAS,CAAC;AAExB,OAAO,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAalD,MAAM,iBAAiB,GAAG,CAAC,mBAAmB,CAAC,CAAC;AAIhD;;GAEG;AACH,MAAM,UAAU,SAAS,CAAC,QAAa,EAAE,OAAoB,EAAE;IAC7D,OAAO,CAAC,KAAK,CAAC,0BAA0B,CAAC,CAAC;IAC1C,MAAM,MAAM,GAAG,SAAS,CACtB,IAAI,iBAAiB,CAAC;QACpB,QAAQ;QACR,mBAAmB,EAAE,KAAK,EAAE,UAAU,EAAE,EAAE,CAAC;YACzC,MAAM,YAAY,GAAG,UAAU,CAAC,YAAY,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;YAC9D,UAAU,CAAC,YAAY,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AAE,GAAG,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,KAAK;KAC7B,CAAC,CAAC;IACH,YAAY,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;IACtB,OAAO,EAAE,CAAC;AAAA,CACX;AAED,MAAM,CAAC,KAAK,UAAU,qBAAqB,CAAC,SAAS,GAAG,IAAI,EAAE;IAC5D,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;AAAA,CACnB;AAED,MAAM,OAAO,aAAc,SAAQ,KAAK;IACtC,YAAY,OAAe,EAAE,KAAU,EAAE;QACvC,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;IAAA,CACpB;CACF","sourcesContent":["import { backOff } from 'exponential-backoff';\nimport type { Kysely as K, LogConfig } from 'kysely';\nimport { PostgresJSDialect } from 'kysely-postgres-js';\nimport postgres, { type Sql } from 'postgres';\nimport { KyselyError } from './error';\nimport { getKysely } from './plugins';\n\nexport type { Insertable, LogEvent } from 'kysely';\nexport * from './error';\nexport * from './isomorphic';\nexport * from './query';\n\nimport { parseDuration } from '@vrplatform/utils';\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\nconst retryableMessages = ['CONNECTION_CLOSED'];\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 onReserveConnection: async (connection) => {\n const executeQuery = connection.executeQuery.bind(connection);\n connection.executeQuery = (arg) =>\n backOff(async () => await executeQuery(arg), {\n numOfAttempts: 3,\n startingDelay: parseDuration('1s'),\n maxDelay: parseDuration('5s'),\n retry: (error) => {\n const message =\n error instanceof Error ? error.message : String(error);\n if (retryableMessages.some((m) => message?.includes(m))) {\n return true;\n }\n return false;\n },\n });\n },\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 KyselyError('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 KyselyError('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":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,qBAAqB,CAAC;AAE9C,OAAO,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AACvD,OAAO,QAAsB,MAAM,UAAU,CAAC;AAC9C,OAAO,EAAE,WAAW,EAAE,MAAM,SAAS,CAAC;AACtC,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AAGtC,cAAc,SAAS,CAAC;AACxB,cAAc,cAAc,CAAC;AAC7B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":["import { backOff } from 'exponential-backoff';\nimport type { Kysely as K, LogConfig } from 'kysely';\nimport { PostgresJSDialect } from 'kysely-postgres-js';\nimport postgres, { type Sql } from 'postgres';\nimport { KyselyError } from './error';\nimport { getKysely } from './plugins';\n\nexport type { Insertable, LogEvent } from 'kysely';\nexport * from './error';\nexport * from './isomorphic';\nexport * from './query';\nexport * from './regional';\nexport * from './transaction';\n\nimport { parseDuration } from '@vrplatform/utils';\nimport type { DB } from './v1.generated';\n\ntype KyselyOpts = {\n repositoryName?: string;\n log?: true | LogConfig;\n};\n\ntype PgOpt = {\n forceDisableSSL?: boolean;\n probe?: false;\n retries?: false | number;\n};\n\nconst retryableMessages = ['CONNECTION_CLOSED'];\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 onReserveConnection: async (connection) => {\n const executeQuery = connection.executeQuery.bind(connection);\n connection.executeQuery = (arg) =>\n backOff(async () => await executeQuery(arg), {\n numOfAttempts: 3,\n startingDelay: parseDuration('1s'),\n maxDelay: parseDuration('5s'),\n retry: (error) => {\n const message =\n error instanceof Error ? error.message : String(error);\n if (retryableMessages.some((m) => message?.includes(m))) {\n return true;\n }\n return false;\n },\n });\n },\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 =\n opt?.probe === false ? 1 : 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 if (opt?.probe !== false) {\n await sql`select 1`;\n }\n // statement_timeout/lock_timeout are role-level settings on the cluster\n // (ALTER ROLE application SET ...) so they cover every pooled\n // connection; per-session SETs here only ever applied to one of them\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 KyselyError('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 KyselyError('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,9 +1,10 @@
1
- import type { Kysely as K, Transaction as T } from 'kysely';
1
+ import type { ControlledTransaction as CT, Kysely as K, Transaction as T } from 'kysely';
2
2
  export type { ColumnType, Expression, ExpressionBuilder, ExpressionOrFactory, Generated, Insertable, JSONColumnType, KyselyPlugin, Nullable, OperandExpression, PluginTransformQueryArgs, PluginTransformResultArgs, QueryResult, RootOperationNode, Selectable, SelectQueryBuilder, SqlBool, UnknownRow, Updateable, } from 'kysely';
3
3
  export { jsonArrayFrom } from 'kysely/helpers/postgres';
4
4
  export * from './v1.generated';
5
5
  import type { DB } from './v1.generated';
6
6
  export type Transaction = T<DB>;
7
+ export type ControlledTransaction<S extends string[] = string[]> = CT<DB, S>;
7
8
  export { sql } from 'kysely';
8
9
  export type Kysely = K<DB>;
9
10
  export declare class DatabaseError extends Error {
@@ -1 +1 @@
1
- {"version":3,"file":"isomorphic.js","sourceRoot":"src/","sources":["isomorphic.ts"],"names":[],"mappings":"AAuBA,OAAO,EAAE,aAAa,EAAE,MAAM,yBAAyB,CAAC;AACxD,cAAc,gBAAgB,CAAC;AAK/B,OAAO,EAAE,GAAG,EAAE,MAAM,QAAQ,CAAC;AAI7B,MAAM,OAAO,aAAc,SAAQ,KAAK;IACtC,YAAY,OAAe,EAAE,KAAU,EAAE;QACvC,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;IAAA,CACpB;CACF","sourcesContent":["import type { Kysely as K, Transaction as T } from 'kysely';\n\nexport type {\n ColumnType,\n Expression,\n ExpressionBuilder,\n ExpressionOrFactory,\n Generated,\n Insertable,\n JSONColumnType,\n KyselyPlugin,\n Nullable,\n OperandExpression,\n PluginTransformQueryArgs,\n PluginTransformResultArgs,\n QueryResult,\n RootOperationNode,\n Selectable,\n SelectQueryBuilder,\n SqlBool,\n UnknownRow,\n Updateable,\n} from 'kysely';\nexport { jsonArrayFrom } from 'kysely/helpers/postgres';\nexport * from './v1.generated';\n\nimport type { DB } from './v1.generated';\n\nexport type Transaction = T<DB>;\nexport { sql } from 'kysely';\n\nexport type Kysely = K<DB>;\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":"isomorphic.js","sourceRoot":"src/","sources":["isomorphic.ts"],"names":[],"mappings":"AA2BA,OAAO,EAAE,aAAa,EAAE,MAAM,yBAAyB,CAAC;AACxD,cAAc,gBAAgB,CAAC;AAM/B,OAAO,EAAE,GAAG,EAAE,MAAM,QAAQ,CAAC;AAI7B,MAAM,OAAO,aAAc,SAAQ,KAAK;IACtC,YAAY,OAAe,EAAE,KAAU;QACrC,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;IACrB,CAAC;CACF","sourcesContent":["import type {\n ControlledTransaction as CT,\n Kysely as K,\n Transaction as T,\n} from 'kysely';\n\nexport type {\n ColumnType,\n Expression,\n ExpressionBuilder,\n ExpressionOrFactory,\n Generated,\n Insertable,\n JSONColumnType,\n KyselyPlugin,\n Nullable,\n OperandExpression,\n PluginTransformQueryArgs,\n PluginTransformResultArgs,\n QueryResult,\n RootOperationNode,\n Selectable,\n SelectQueryBuilder,\n SqlBool,\n UnknownRow,\n Updateable,\n} from 'kysely';\nexport { jsonArrayFrom } from 'kysely/helpers/postgres';\nexport * from './v1.generated';\n\nimport type { DB } from './v1.generated';\n\nexport type Transaction = T<DB>;\nexport type ControlledTransaction<S extends string[] = string[]> = CT<DB, S>;\nexport { sql } from 'kysely';\n\nexport type Kysely = K<DB>;\n\nexport class DatabaseError extends Error {\n constructor(message: string, cause: any) {\n super(message);\n this.cause = cause;\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"digest.js","sourceRoot":"src/","sources":["local/digest.ts"],"names":[],"mappings":"AAAA,OAAO,EAAe,GAAG,EAAE,MAAM,eAAe,CAAC;AAEjD,MAAM,CAAC,KAAK,UAAU,oBAAoB,CAAC,MAAc,EAAE;IACzD,IAAI,CAAC;QACH,MAAM,GAAG,CAAA,6BAA6B,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;IACzD,CAAC;IAAC,MAAM,CAAC;QACP,MAAM,GAAG,CAAA;;;;;;;;;KASR,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;IACpB,CAAC;AAAA,CACF;AAED,MAAM,CAAC,KAAK,UAAU,4BAA4B,CAAC,MAAc,EAAE;IACjE,IAAI,CAAC;QACH,MAAM,GAAG,CAAA,4BAA4B,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;IACxD,CAAC;IAAC,MAAM,CAAC;QACP,MAAM,GAAG,CAAA;;;;;;;;;;;;;;;;;;KAkBR,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;IACpB,CAAC;AAAA,CACF","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
+ {"version":3,"file":"digest.js","sourceRoot":"src/","sources":["local/digest.ts"],"names":[],"mappings":"AAAA,OAAO,EAAe,GAAG,EAAE,MAAM,eAAe,CAAC;AAEjD,MAAM,CAAC,KAAK,UAAU,oBAAoB,CAAC,MAAc;IACvD,IAAI,CAAC;QACH,MAAM,GAAG,CAAA,6BAA6B,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;IACzD,CAAC;IAAC,MAAM,CAAC;QACP,MAAM,GAAG,CAAA;;;;;;;;;KASR,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;IACpB,CAAC;AACH,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,4BAA4B,CAAC,MAAc;IAC/D,IAAI,CAAC;QACH,MAAM,GAAG,CAAA,4BAA4B,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;IACxD,CAAC;IAAC,MAAM,CAAC;QACP,MAAM,GAAG,CAAA;;;;;;;;;;;;;;;;;;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"]}
@@ -7,6 +7,14 @@ import { FileMigrationProvider, Migrator } from 'kysely';
7
7
  import codegen from 'kysely-codegen';
8
8
  import { PGliteDialect } from 'kysely-pglite-dialect';
9
9
  import { getKysely } from '../plugins';
10
+ async function normalizeGeneratedTypes(root) {
11
+ const outFile = path.join(root, 'src/v1.generated.ts');
12
+ const current = await Bun.file(outFile).text();
13
+ const next = current.replace('export type Timestamp = ColumnType<Date, Date | string, Date | string>;', 'export type Timestamp = ColumnType<Date | string, Date | string, Date | string>;');
14
+ if (next !== current) {
15
+ await Bun.write(outFile, next);
16
+ }
17
+ }
10
18
  async function migrate(root, client) {
11
19
  console.log('migrating pglite ....');
12
20
  const glob = new Bun.Glob('initial/*.sql');
@@ -76,12 +84,16 @@ async function generateDump(root, dumpPath) {
76
84
  outFile: path.join(root, 'src/v1.generated.ts'),
77
85
  defaultSchemas: ['xxx'],
78
86
  camelCase: true,
87
+ typeMapping: {
88
+ date: 'string',
89
+ },
79
90
  dialect: codegen.getDialect('postgres'),
80
91
  })
81
92
  .catch(() => {
82
93
  console.error('failed to generate kysely');
83
94
  process.exit(1);
84
95
  });
96
+ await normalizeGeneratedTypes(root);
85
97
  const content = await main.dumpDataDir('none').catch(() => {
86
98
  console.error('failed to dump data');
87
99
  process.exit(1);
@@ -1 +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,EAAE,qBAAqB,EAAe,QAAQ,EAAE,MAAM,QAAQ,CAAC;AACtE,OAAO,OAAO,MAAM,gBAAgB,CAAC;AACrC,OAAO,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AACtD,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAGvC,KAAK,UAAU,OAAO,CAAC,IAAY,EAAE,MAAc,EAAE;IACnD,OAAO,CAAC,GAAG,CAAC,uBAAuB,CAAC,CAAC;IACrC,M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QAAQ,CAAC,CAAC;AAAA,CAC3B;AAED,MAAM,CAAC,KAAK,UAAU,iBAAiB,CAAC,IAAY,EAAE,QAAgB,EAAE;IACtE,IAAI,WAAW,GAAG,KAAK,CAAC;IACxB,gCAAgC;IAEhC,MAAM,IAAI,GAAG,MAAM,YAAY,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC;IAEhD,MAAM,MAAM,GAAG,IAAI,MAAM,CAAC,EAAE,WAAW,EAAE,IAAI,EAAE,CAAC,CAAC;IACjD,UAAU;IACV,MAAM,MAAM,CAAC,GAAG,CAAA,UAAU,CAAC;IAC3B,MAAM,OAAO,GAAG,IAAI,aAAa,CAAC,MAAM,CAAC,CAAC;IAC1C,MAAM,MAAM,GAAG,SAAS,CAAC,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,CAAC;QAC3B,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;IAHwC,CAI7C,CAAC;IAEF,iFAAiF;IAEjF,OAAO,MAAM,CAAC;AAAA,CACf","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 { PGliteDialect } from 'kysely-pglite-dialect';\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 PGliteDialect(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 PGliteDialect(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
+ {"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,EAAE,qBAAqB,EAAe,QAAQ,EAAE,MAAM,QAAQ,CAAC;AACtE,OAAO,OAAO,MAAM,gBAAgB,CAAC;AACrC,OAAO,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;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AC,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 { PGliteDialect } from 'kysely-pglite-dialect';\nimport { getKysely } from '../plugins';\nimport type { DB } from '../v1.generated';\n\nasync function normalizeGeneratedTypes(root: string) {\n const outFile = path.join(root, 'src/v1.generated.ts');\n const current = await Bun.file(outFile).text();\n const next = current.replace(\n 'export type Timestamp = ColumnType<Date, Date | string, Date | string>;',\n 'export type Timestamp = ColumnType<Date | string, Date | string, Date | string>;'\n );\n\n if (next !== current) {\n await Bun.write(outFile, next);\n }\n}\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 PGliteDialect(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 typeMapping: {\n date: 'string',\n },\n dialect: codegen.getDialect('postgres'),\n })\n .catch(() => {\n console.error('failed to generate kysely');\n process.exit(1);\n });\n await normalizeGeneratedTypes(root);\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 PGliteDialect(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,8 +1,9 @@
1
- import type { LogConfig } from 'kysely';
1
+ import { type LogConfig } from 'kysely';
2
+ import type { DB } from '../v1.generated';
2
3
  export declare const root: string;
3
4
  export declare const dumpPath: string;
4
5
  export type UseLocalKyselyOptions = {
5
6
  repositoryName?: string;
6
7
  log?: true | LogConfig;
7
8
  };
8
- export declare function useLocalKysely(args?: UseLocalKyselyOptions): Promise<import("kysely").Kysely<import("..").DB>>;
9
+ export declare function useLocalKysely(args?: UseLocalKyselyOptions): Promise<import("kysely").Kysely<DB>>;