@vrplatform/kysely 1.3.37 → 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.
- package/build/.data.tar +0 -0
- package/build/main/camel-case/index.js.map +1 -1
- package/build/main/control-plane/index.d.ts +141 -0
- package/build/main/control-plane/index.js +3 -0
- package/build/main/control-plane/index.js.map +1 -0
- package/build/main/error.js.map +1 -1
- package/build/main/index.d.ts +6 -3
- package/build/main/index.js +8 -9
- package/build/main/index.js.map +1 -1
- package/build/main/isomorphic.d.ts +2 -1
- package/build/main/isomorphic.js +2 -2
- package/build/main/isomorphic.js.map +1 -1
- package/build/main/local/digest.js.map +1 -1
- package/build/main/local/generate.js +12 -0
- package/build/main/local/generate.js.map +1 -1
- package/build/main/local/index.d.ts +3 -2
- package/build/main/local/index.js +56 -3
- package/build/main/local/index.js.map +1 -1
- package/build/main/local/prune-pulled-schema.js.map +1 -1
- package/build/main/pganalyze-comment-plugin/comment-transformer.js +0 -1
- package/build/main/pganalyze-comment-plugin/comment-transformer.js.map +1 -1
- package/build/main/pganalyze-comment-plugin/index.js +16 -3
- package/build/main/pganalyze-comment-plugin/index.js.map +1 -1
- package/build/main/plugins.js.map +1 -1
- package/build/main/query/listing/status.d.ts +4 -4
- package/build/main/query/listing/status.js +19 -2
- package/build/main/query/listing/status.js.map +1 -1
- package/build/main/regional.d.ts +34 -0
- package/build/main/regional.js +145 -0
- package/build/main/regional.js.map +1 -0
- package/build/main/test/index.js.map +1 -1
- package/build/main/transaction.d.ts +7 -0
- package/build/main/transaction.js +32 -0
- package/build/main/transaction.js.map +1 -0
- package/build/main/v1.generated.d.ts +133 -2
- package/build/main/v1.generated.js.map +1 -1
- package/build/migrations/0000000000001-init.ts +5 -0
- package/build/migrations/0000000000009-drop-store-schema.ts +14 -0
- package/build/migrations/0000000000010-bank-rules.ts +190 -0
- package/build/migrations/0000000000011-bank-rule-line-adjustments.ts +65 -0
- package/build/migrations/0000000000012-bank-rule-conditions.ts +45 -0
- package/build/migrations/0000000000013-bank-rule-name-unique.ts +15 -0
- package/build/migrations/0000000000014-bank-rule-drop-legacy-conditions.ts +41 -0
- package/build/migrations/0000000000015-booking-channel-logo-dev-provider.ts +70 -0
- package/build/migrations/0000000000016-owner-statement-draft-status.ts +22 -0
- package/build/migrations/0000000000017-tenant-migration-markers.ts +18 -0
- package/build/migrations/0000000000018-security-deposits-payable-category.ts +63 -0
- package/build/migrations/0000000000019-tenant-app-settings.ts +76 -0
- package/build/migrations/0000000000020-operating-opening-trial-balance.ts +36 -0
- package/build/migrations/0000000000021-audit-foreign-key-indexes.ts +77 -0
- package/build/migrations/0000000000022-opening-trial-balance-combined-columns.ts +30 -0
- package/build/migrations/0000000000023-journal-entry-currency-mismatch-reason.ts +14 -0
- package/build/migrations/0000000000024-listing-parent.ts +37 -0
- package/build/migrations/0000000000025-journal-entry-parent-listing.ts +26 -0
- package/build/migrations/0000000000026-booking-channel-logo-slots.ts +89 -0
- package/build/migrations/0000000000027-list-browse-performance-indexes.ts +52 -0
- package/build/migrations/0000000000028-flow-setting-status-jsonb.ts +20 -0
- package/build/migrations/0000000000029-tenant-slug.ts +328 -0
- package/build/migrations/0000000000030-pms-accounting-windows.ts +50 -0
- package/build/migrations/0000000000031-owner-statement-projection-listing-revision.ts +20 -0
- package/build/migrations/0000000000032-flow-event-listening.ts +28 -0
- package/build/migrations/0000000000033-opening-trial-balance-transaction.ts +272 -0
- package/build/migrations/0000000000034-historic-general-ledger.ts +24 -0
- package/build/migrations/0000000000035-tenant-regional-placement.ts +37 -0
- package/build/migrations/0000000000036-control-plane-projection-events.ts +43 -0
- package/build/migrations/0000000000037-tenant-guide-onboarding.ts +21 -0
- package/build/migrations/0000000000038-ramp-staging-connect-params.ts +35 -0
- package/build/migrations/0000000000038-tracking-event-analytics-sink.ts +31 -0
- package/build/migrations/0000000000039-crunchy-region.ts +86 -0
- package/build/migrations/0000000000039-gl-pms-accounting-window-guard.ts +125 -0
- package/build/migrations/0000000000040-hostaway-region.ts +68 -0
- package/build/module/camel-case/index.js.map +1 -1
- package/build/module/control-plane/index.d.ts +141 -0
- package/build/module/control-plane/index.js +2 -0
- package/build/module/control-plane/index.js.map +1 -0
- package/build/module/error.js.map +1 -1
- package/build/module/index.d.ts +6 -3
- package/build/module/index.js +8 -9
- package/build/module/index.js.map +1 -1
- package/build/module/isomorphic.d.ts +2 -1
- package/build/module/isomorphic.js.map +1 -1
- package/build/module/local/digest.js.map +1 -1
- package/build/module/local/generate.js +12 -0
- package/build/module/local/generate.js.map +1 -1
- package/build/module/local/index.d.ts +3 -2
- package/build/module/local/index.js +23 -3
- package/build/module/local/index.js.map +1 -1
- package/build/module/local/prune-pulled-schema.js.map +1 -1
- package/build/module/pganalyze-comment-plugin/comment-transformer.js.map +1 -1
- package/build/module/pganalyze-comment-plugin/index.js.map +1 -1
- package/build/module/plugins.js.map +1 -1
- package/build/module/query/listing/status.d.ts +4 -4
- package/build/module/query/listing/status.js +19 -2
- package/build/module/query/listing/status.js.map +1 -1
- package/build/module/regional.d.ts +34 -0
- package/build/module/regional.js +103 -0
- package/build/module/regional.js.map +1 -0
- package/build/module/test/index.js.map +1 -1
- package/build/module/transaction.d.ts +7 -0
- package/build/module/transaction.js +25 -0
- package/build/module/transaction.js.map +1 -0
- package/build/module/v1.generated.d.ts +133 -2
- package/build/module/v1.generated.js.map +1 -1
- package/package.json +25 -32
- package/build/main/local.d.ts +0 -3
- package/build/main/local.js +0 -158
- package/build/main/local.js.map +0 -1
- package/build/main/test.d.ts +0 -4
- package/build/main/test.js +0 -19
- package/build/main/test.js.map +0 -1
- package/build/main/tsconfig.main.tsbuildinfo +0 -1
- package/build/main/v0.generated.d.ts +0 -1996
- package/build/main/v0.generated.js +0 -7
- package/build/main/v0.generated.js.map +0 -1
- package/build/module/local.d.ts +0 -3
- package/build/module/local.js +0 -119
- package/build/module/local.js.map +0 -1
- package/build/module/test.d.ts +0 -4
- package/build/module/test.js +0 -16
- package/build/module/test.js.map +0 -1
- package/build/module/tsconfig.esm.tsbuildinfo +0 -1
- package/build/module/v0.generated.d.ts +0 -1996
- package/build/module/v0.generated.js +0 -6
- package/build/module/v0.generated.js.map +0 -1
- package/src/index.ts +0 -167
package/build/.data.tar
CHANGED
|
Binary file
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"src/","sources":["camel-case/index.ts"],"names":[],"mappings":";;;AAAA,mCAMgB;AAChB,oCAAuC;AAEvC,
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"src/","sources":["camel-case/index.ts"],"names":[],"mappings":";;;AAAA,mCAMgB;AAChB,oCAAuC;AAEvC,MAAa,gBAAiB,SAAQ,wBAAe;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,CAAC,IAAI,KAAK,SAAS,EAAE,CAAC;gBACtC,MAAM,OAAO,GAAG,SAAS,CAAC,IAAe,CAAC;gBAC1C,KAAK,MAAM,CAAC,IAAI,OAAO,CAAC,UAAU,IAAI,EAAE,EAAE,CAAC;oBACzC,IAAI,CAAC,CAAC,IAAI,KAAK,iBAAiB,EAAE,CAAC;wBACjC,MAAM,eAAe,GAAG,CAAoB,CAAC;wBAC7C,IAAI,CAAC,WAAW,CAAC,eAAe,CAAC,CAAC;oBACpC,CAAC;gBACH,CAAC;YACH,CAAC;YAED,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC,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,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 @@
|
|
|
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"]}
|
package/build/main/error.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"error.js","sourceRoot":"src/","sources":["error.ts"],"names":[],"mappings":";;;AAAA,
|
|
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"]}
|
package/build/main/index.d.ts
CHANGED
|
@@ -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);
|
package/build/main/index.js
CHANGED
|
@@ -31,6 +31,8 @@ const plugins_1 = require("./plugins");
|
|
|
31
31
|
__exportStar(require("./error"), exports);
|
|
32
32
|
__exportStar(require("./isomorphic"), exports);
|
|
33
33
|
__exportStar(require("./query"), exports);
|
|
34
|
+
__exportStar(require("./regional"), exports);
|
|
35
|
+
__exportStar(require("./transaction"), exports);
|
|
34
36
|
const utils_1 = require("@vrplatform/utils");
|
|
35
37
|
const retryableMessages = ['CONNECTION_CLOSED'];
|
|
36
38
|
/**
|
|
@@ -74,7 +76,7 @@ function useKysely(postgres, options) {
|
|
|
74
76
|
let _connections = [];
|
|
75
77
|
async function useAsyncPostgres(connectionString, opt) {
|
|
76
78
|
const delayMs = 2500;
|
|
77
|
-
const retries = opt?.retries === false ? 0 : opt?.retries || 3;
|
|
79
|
+
const retries = opt?.probe === false ? 1 : opt?.retries === false ? 0 : opt?.retries || 3;
|
|
78
80
|
const ssl = opt?.forceDisableSSL !== true;
|
|
79
81
|
const url = new URL(connectionString);
|
|
80
82
|
console.debug(`Creating Postgres connection with ${retries} retries and ssl=${ssl} and port=${url.port}`);
|
|
@@ -91,15 +93,12 @@ async function useAsyncPostgres(connectionString, opt) {
|
|
|
91
93
|
connect_timeout: 10,
|
|
92
94
|
idle_timeout: 60,
|
|
93
95
|
});
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
// connect 30s, idle 60s, max lifetime 45min, statement 60s, lock 10s, log_min_duration 20s, log_lock_waits off
|
|
97
|
-
await sql `set statement_timeout to '30s';`;
|
|
98
|
-
await sql `set lock_timeout to '10s';`;
|
|
99
|
-
}
|
|
100
|
-
catch (e) {
|
|
101
|
-
console.warn('Failed to set statement timeout, continuing', e);
|
|
96
|
+
if (opt?.probe !== false) {
|
|
97
|
+
await sql `select 1`;
|
|
102
98
|
}
|
|
99
|
+
// statement_timeout/lock_timeout are role-level settings on the cluster
|
|
100
|
+
// (ALTER ROLE application SET ...) so they cover every pooled
|
|
101
|
+
// connection; per-session SETs here only ever applied to one of them
|
|
103
102
|
_connections.push(sql);
|
|
104
103
|
return sql;
|
|
105
104
|
}
|
package/build/main/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"src/","sources":["index.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"src/","sources":["index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;AAmCA,8BAuCC;AAGD,4CA4CC;AAED,wCAMC;AAKD,kCAeC;AAED,sDAUC;AAjKD,6DAA8C;AAE9C,2DAAuD;AACvD,wDAA8C;AAC9C,mCAAsC;AACtC,uCAAsC;AAGtC,0CAAwB;AACxB,+CAA6B;AAC7B,0CAAwB;AACxB,6CAA2B;AAC3B,gDAA8B;AAE9B,6CAAkD;AAclD,MAAM,iBAAiB,GAAG,CAAC,mBAAmB,CAAC,CAAC;AAIhD;;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;QACR,mBAAmB,EAAE,KAAK,EAAE,UAAU,EAAE,EAAE;YACxC,MAAM,YAAY,GAAG,UAAU,CAAC,YAAY,CAA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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 { 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 {
|
package/build/main/isomorphic.js
CHANGED
|
@@ -15,10 +15,10 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
|
15
15
|
};
|
|
16
16
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
17
|
exports.DatabaseError = exports.sql = exports.jsonArrayFrom = void 0;
|
|
18
|
-
|
|
18
|
+
var postgres_1 = require("kysely/helpers/postgres");
|
|
19
19
|
Object.defineProperty(exports, "jsonArrayFrom", { enumerable: true, get: function () { return postgres_1.jsonArrayFrom; } });
|
|
20
20
|
__exportStar(require("./v1.generated"), exports);
|
|
21
|
-
|
|
21
|
+
var kysely_1 = require("kysely");
|
|
22
22
|
Object.defineProperty(exports, "sql", { enumerable: true, get: function () { return kysely_1.sql; } });
|
|
23
23
|
class DatabaseError extends Error {
|
|
24
24
|
constructor(message, cause) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"isomorphic.js","sourceRoot":"src/","sources":["isomorphic.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"isomorphic.js","sourceRoot":"src/","sources":["isomorphic.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AA2BA,oDAAwD;AAA/C,yGAAA,aAAa,OAAA;AACtB,iDAA+B;AAM/B,iCAA6B;AAApB,6FAAA,GAAG,OAAA;AAIZ,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 {\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":"
|
|
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"]}
|
|
@@ -46,6 +46,14 @@ const kysely_1 = require("kysely");
|
|
|
46
46
|
const kysely_codegen_1 = __importDefault(require("kysely-codegen"));
|
|
47
47
|
const kysely_pglite_dialect_1 = require("kysely-pglite-dialect");
|
|
48
48
|
const plugins_1 = require("../plugins");
|
|
49
|
+
async function normalizeGeneratedTypes(root) {
|
|
50
|
+
const outFile = path.join(root, 'src/v1.generated.ts');
|
|
51
|
+
const current = await Bun.file(outFile).text();
|
|
52
|
+
const next = current.replace('export type Timestamp = ColumnType<Date, Date | string, Date | string>;', 'export type Timestamp = ColumnType<Date | string, Date | string, Date | string>;');
|
|
53
|
+
if (next !== current) {
|
|
54
|
+
await Bun.write(outFile, next);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
49
57
|
async function migrate(root, client) {
|
|
50
58
|
console.log('migrating pglite ....');
|
|
51
59
|
const glob = new Bun.Glob('initial/*.sql');
|
|
@@ -115,12 +123,16 @@ async function generateDump(root, dumpPath) {
|
|
|
115
123
|
outFile: path.join(root, 'src/v1.generated.ts'),
|
|
116
124
|
defaultSchemas: ['xxx'],
|
|
117
125
|
camelCase: true,
|
|
126
|
+
typeMapping: {
|
|
127
|
+
date: 'string',
|
|
128
|
+
},
|
|
118
129
|
dialect: kysely_codegen_1.default.getDialect('postgres'),
|
|
119
130
|
})
|
|
120
131
|
.catch(() => {
|
|
121
132
|
console.error('failed to generate kysely');
|
|
122
133
|
process.exit(1);
|
|
123
134
|
});
|
|
135
|
+
await normalizeGeneratedTypes(root);
|
|
124
136
|
const content = await main.dumpDataDir('none').catch(() => {
|
|
125
137
|
console.error('failed to dump data');
|
|
126
138
|
process.exit(1);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generate.js","sourceRoot":"src/","sources":["local/generate.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"generate.js","sourceRoot":"src/","sources":["local/generate.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2HA,8CA8BC;AAzJD,qCAAyC;AACzC,+CAA0C;AAC1C,gDAAkC;AAClC,yCAAiC;AACjC,iDAA8C;AAC9C,mCAAsE;AACtE,oEAAqC;AACrC,iEAAsD;AACtD,wCAAuC;AAGvC,KAAK,UAAU,uBAAuB,CAAC,IAAY;IACjD,MAAM,OAAO,GAAG,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE,qBAAqB,CAAC,CAAC;IACvD,MAAM,OAAO,GAAG,MAAM,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,IAAI,EAAE,CAAC;IAC/C,MAAM,IAAI,GAAG,OAAO,CAAC,OAAO,CAC1B,yEAAyE,EACzE,kFAAkF,CACnF,CAAC;IAEF,IAAI,IAAI,KAAK,OAAO,EAAE,CAAC;QACrB,MAAM,GAAG,CAAC,KAAK,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;IACjC,CAAC;AACH,CAAC;AAED,KAAK,UAAU,OAAO,CAAC,IAAY,EAAE,MAAc;IACjD,OAAO,CAAC,GAAG,CAAC,uB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,CAAC,CAAC;QAClB,CAAC,CAAC,CAAC;QACH,OAAO,OAAO,CAAC;IACjB,CAAC;IACD,OAAO,GAAG,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;AAC5B,CAAC;AAEM,KAAK,UAAU,iBAAiB,CAAC,IAAY,EAAE,QAAgB;IACpE,IAAI,WAAW,GAAG,KAAK,CAAC;IACxB,gCAAgC;IAEhC,MAAM,IAAI,GAAG,MAAM,YAAY,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,OAAO,GAAG,IAAI,qCAAa,CAAC,MAAM,CAAC,CAAC;IAC1C,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 { 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
|
|
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<
|
|
9
|
+
export declare function useLocalKysely(args?: UseLocalKyselyOptions): Promise<import("kysely").Kysely<DB>>;
|
|
@@ -1,14 +1,66 @@
|
|
|
1
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
|
+
})();
|
|
2
35
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
36
|
exports.dumpPath = exports.root = void 0;
|
|
4
37
|
exports.useLocalKysely = useLocalKysely;
|
|
5
|
-
const
|
|
38
|
+
const node_fs_1 = require("node:fs");
|
|
39
|
+
const path = __importStar(require("node:path"));
|
|
6
40
|
const pglite_1 = require("@electric-sql/pglite");
|
|
41
|
+
const kysely_1 = require("kysely");
|
|
7
42
|
const kysely_pglite_dialect_1 = require("kysely-pglite-dialect");
|
|
8
43
|
const plugins_1 = require("../plugins");
|
|
9
44
|
const digest_1 = require("./digest");
|
|
10
|
-
exports.root =
|
|
11
|
-
exports.dumpPath =
|
|
45
|
+
exports.root = path.join(__dirname, '../..');
|
|
46
|
+
exports.dumpPath = path.join(exports.root, '.data.tar');
|
|
47
|
+
async function migrateToLatest(kysely) {
|
|
48
|
+
const migrator = new kysely_1.Migrator({
|
|
49
|
+
db: kysely,
|
|
50
|
+
migrationTableSchema: 'core',
|
|
51
|
+
migrationTableName: 'kysely_migration',
|
|
52
|
+
migrationLockTableName: 'kysely_migration_lock',
|
|
53
|
+
provider: new kysely_1.FileMigrationProvider({
|
|
54
|
+
fs: node_fs_1.promises,
|
|
55
|
+
path,
|
|
56
|
+
migrationFolder: path.join(exports.root, 'migrations'),
|
|
57
|
+
}),
|
|
58
|
+
});
|
|
59
|
+
const { error } = await migrator.migrateToLatest();
|
|
60
|
+
if (error) {
|
|
61
|
+
throw error;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
12
64
|
async function useLocalKysely(args = {}) {
|
|
13
65
|
let isDestroyed = false;
|
|
14
66
|
// const now = performance.now();
|
|
@@ -23,6 +75,7 @@ async function useLocalKysely(args = {}) {
|
|
|
23
75
|
});
|
|
24
76
|
await (0, digest_1.ensureDigestFunction)(kysely);
|
|
25
77
|
await (0, digest_1.ensureGenRandomBytesFunction)(kysely);
|
|
78
|
+
await migrateToLatest(kysely);
|
|
26
79
|
const originalDestroy = kysely.destroy.bind(kysely);
|
|
27
80
|
kysely.destroy = async () => {
|
|
28
81
|
if (isDestroyed)
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"src/","sources":["local/index.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"src/","sources":["local/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoCA,wCAiCC;AArED,qCAAyC;AACzC,gDAAkC;AAClC,iDAA8C;AAC9C,mCAAyE;AACzE,iEAAsD;AACtD,wCAAuC;AAEvC,qCAA8E;AAEjE,QAAA,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC;AACrC,QAAA,QAAQ,GAAG,IAAI,CAAC,IAAI,CAAC,YAAI,EAAE,WAAW,CAAC,CAAC;AAOrD,KAAK,UAAU,eAAe,CAAC,MAAmC;IAChE,MAAM,QAAQ,GAAG,IAAI,iBAAQ,CAAC;QAC5B,EAAE,EAAE,MAAM;QACV,oBAAoB,EAAE,MAAM;QAC5B,kBAAkB,EAAE,kBAAkB;QACtC,sBAAsB,EAAE,uBAAuB;QAC/C,QAAQ,EAAE,IAAI,8BAAqB,CAAC;YAClC,EAAE,EAAF,kBAAE;YACF,IAAI;YACJ,eAAe,EAAE,IAAI,CAAC,IAAI,CAAC,YAAI,EAAE,YAAY,CAAC;SAC/C,CAAC;KACH,CAAC,CAAC;IAEH,MAAM,EAAE,KAAK,EAAE,GAAG,MAAM,QAAQ,CAAC,eAAe,EAAE,CAAC;IACnD,IAAI,KAAK,EAAE,CAAC;QACV,MAAM,KAAK,CAAC;IACd,CAAC;AACH,CAAC;AAEM,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,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;IAC3C,MAAM,eAAe,CAAC,MAAqC,CAAC,CAAC;IAE7D,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 { promises as fs } from 'node:fs';\nimport * as path from 'node:path';\nimport { PGlite } from '@electric-sql/pglite';\nimport { FileMigrationProvider, type LogConfig, Migrator } from 'kysely';\nimport { PGliteDialect } from 'kysely-pglite-dialect';\nimport { getKysely } from '../plugins';\nimport type { DB } from '../v1.generated';\nimport { ensureDigestFunction, ensureGenRandomBytesFunction } from './digest';\n\nexport const root = path.join(__dirname, '../..');\nexport const dumpPath = path.join(root, '.data.tar');\n\nexport type UseLocalKyselyOptions = {\n repositoryName?: string;\n log?: true | LogConfig;\n};\n\nasync function migrateToLatest(kysely: import('kysely').Kysely<DB>) {\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 migrationFolder: path.join(root, 'migrations'),\n }),\n });\n\n const { error } = await migrator.migrateToLatest();\n if (error) {\n throw error;\n }\n}\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 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 await migrateToLatest(kysely as import('kysely').Kysely<DB>);\n\n const originalDestroy = kysely.destroy.bind(kysely);\n kysely.destroy = async () => {\n if (isDestroyed) return;\n isDestroyed = true;\n //const destroyTime = performance.now();\n await originalDestroy().catch(() => undefined);\n await pglite.close().catch(() => undefined);\n //console.log(\n // `Database destroyed: ${Math.round(performance.now() - destroyTime)}ms`\n //);\n };\n\n // console.log(`Database initialized: ${Math.round(performance.now() - now)}ms`);\n\n return kysely;\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prune-pulled-schema.js","sourceRoot":"src/","sources":["local/prune-pulled-schema.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"prune-pulled-schema.js","sourceRoot":"src/","sources":["local/prune-pulled-schema.ts"],"names":[],"mappings":";;;AAkFA,gEAcC;AAED,0CA0BC;AAED,sDAUC;A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,CAAC;AAED,CAAC,KAAK,IAAI,EAAE;IACV,IAAI,iBAAiB,EAAE,EAAE,CAAC;QACxB,MAAM,GAAG,EAAE,CAAC;IACd,CAAC;AACH,CAAC,CAAC,EAAE,CAAC","sourcesContent":["import { readFile, writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\n\nconst START_MARKER = '-- VRP legacy-column-prune:start';\nconst END_MARKER = '-- VRP legacy-column-prune:end';\n\nexport type LegacyColumnPrune = {\n table: `${string}.${string}`;\n column: string;\n issue: string;\n};\n\nconst hasuraAuditTriggerPattern =\n /^CREATE TRIGGER \"(notify_hasura_audit_[^\"]+)\" [\\s\\S]*? ON ([^\\s;]+) FOR EACH ROW EXECUTE FUNCTION hdb_catalog\\.\"notify_hasura_audit_[^\"]+\"\\(\\);$/gm;\n\nexport type HasuraAuditTrigger = {\n name: string;\n table: `${string}.${string}`;\n};\n\n/**\n * Active removals currently validated by runtime + type usage.\n * Add new entries here incrementally to surface compile/runtime callers.\n */\nexport const activeLegacyColumnPrunes: LegacyColumnPrune[] = [\n {\n issue: 'VRI-45',\n table: 'public.app',\n column: 'fly_app',\n },\n {\n issue: 'VRI-45',\n table: 'public.app',\n column: 'default_machine_size',\n },\n {\n issue: 'VRI-45',\n table: 'public.app',\n column: 'endpoint',\n },\n {\n issue: 'VRI-45',\n table: 'public.app',\n column: 'uid',\n },\n {\n issue: 'VRI-45',\n table: 'public.app',\n column: 'plugin_data',\n },\n {\n issue: 'VRI-45',\n table: 'public.app',\n column: 'config',\n },\n {\n issue: 'VRI-45',\n table: 'public.app',\n column: 'flows',\n },\n {\n issue: 'PRO-12855',\n table: 'public.owner_statement',\n column: 'cent_accounting_balance_start',\n },\n {\n issue: 'PRO-12855',\n table: 'public.owner_statement',\n column: 'cent_accounting_balance_end',\n },\n {\n issue: 'PRO-12855',\n table: 'accounting.contact',\n column: 'pms_status',\n },\n {\n issue: 'PRO-12855',\n table: 'public.owner',\n column: 'pms_status',\n },\n];\n\nexport function extractHasuraAuditTriggers(sql: string): HasuraAuditTrigger[] {\n const unique = new Map<string, HasuraAuditTrigger>();\n\n for (const match of sql.matchAll(hasuraAuditTriggerPattern)) {\n const name = match[1];\n const table = match[2] as `${string}.${string}`;\n const key = `${name}::${table}`;\n\n if (!unique.has(key)) {\n unique.set(key, { name, table });\n }\n }\n\n return [...unique.values()];\n}\n\nexport function buildPruneBlock(\n columns: readonly LegacyColumnPrune[],\n hasuraAuditTriggers: readonly HasuraAuditTrigger[] = []\n): string {\n const columnStatements = columns.map(\n (item) =>\n `ALTER TABLE ${item.table} DROP COLUMN IF EXISTS ${item.column}; -- ${item.issue}`\n );\n const triggerStatements = hasuraAuditTriggers.map(\n (trigger) =>\n `DROP TRIGGER IF EXISTS \"${trigger.name}\" ON ${trigger.table}; -- hasura-audit`\n );\n\n return [\n START_MARKER,\n '-- Managed by src/local/prune-pulled-schema.ts',\n ...columnStatements,\n ...(triggerStatements.length > 0\n ? [\n '',\n '-- Disable Hasura audit triggers in local bootstrap',\n ...triggerStatements,\n ]\n : []),\n END_MARKER,\n ].join('\\n');\n}\n\nexport function buildPruneReminderLog(columns: readonly LegacyColumnPrune[]) {\n const lines = [\n `[kysely] Legacy column prune reminder (${columns.length} columns). Remove these from production schema when ready:`,\n ];\n\n for (const item of columns) {\n lines.push(` - ${item.table}.${item.column} [${item.issue}]`);\n }\n\n return lines;\n}\n\nexport function applyPruneBlock(\n sql: string,\n columns: readonly LegacyColumnPrune[]\n): string {\n const hasuraAuditTriggers = extractHasuraAuditTriggers(sql);\n const startAt = sql.indexOf(START_MARKER);\n\n let base = sql;\n if (startAt !== -1) {\n const endAt = sql.indexOf(END_MARKER, startAt);\n if (endAt === -1) {\n throw new Error(\n `Malformed legacy prune block in initial SQL: missing \"${END_MARKER}\".`\n );\n }\n const tailStart = endAt + END_MARKER.length;\n const afterTail = sql.slice(tailStart).replace(/^\\s*\\n/, '');\n base = `${sql.slice(0, startAt).trimEnd()}\\n${afterTail}`;\n }\n\n const next = base.trimEnd();\n if (columns.length === 0) {\n return `${next}\\n`;\n }\n\n return `${next}\\n\\n${buildPruneBlock(columns, hasuraAuditTriggers)}\\n`;\n}\n\nexport async function prunePulledSchemaFile(filePath: string) {\n const original = await readFile(filePath, 'utf8');\n const updated = applyPruneBlock(original, activeLegacyColumnPrunes);\n const changed = updated !== original;\n if (changed) {\n await writeFile(filePath, updated, 'utf8');\n }\n\n const status = changed ? 'applied' : 'already up to date';\n console.log(`[kysely] Legacy column prune block ${status}.`);\n for (const line of buildPruneReminderLog(activeLegacyColumnPrunes)) {\n console.log(line);\n }\n}\n\nexport async function prunePulledSchema(root: string) {\n const filePath = join(root, 'initial/0000000000000-init.sql');\n await prunePulledSchemaFile(filePath);\n}\n\nasync function run() {\n await prunePulledSchema(process.cwd());\n}\n\nfunction isDirectExecution() {\n const entryPath = process.argv[1];\n if (!entryPath) {\n return false;\n }\n\n return (\n entryPath.endsWith('prune-pulled-schema.ts') ||\n entryPath.endsWith('prune-pulled-schema.js')\n );\n}\n\n(async () => {\n if (isDirectExecution()) {\n await run();\n }\n})();\n"]}
|