@vrplatform/kysely 1.3.45-stage.4896 → 1.3.45-stage.490
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 +1 -1
- package/build/main/camel-case/index.js.map +1 -1
- package/build/main/control-plane/index.d.ts +344 -16
- package/build/main/control-plane/index.js +61 -0
- package/build/main/control-plane/index.js.map +1 -1
- package/build/main/domain.d.ts +4 -0
- package/build/main/domain.js +3 -0
- package/build/main/domain.js.map +1 -0
- package/build/main/error.d.ts +2 -1
- package/build/main/error.js +2 -1
- package/build/main/error.js.map +1 -1
- package/build/main/index.d.ts +19 -14
- package/build/main/index.js +235 -59
- package/build/main/index.js.map +1 -1
- package/build/main/isomorphic.d.ts +5 -5
- package/build/main/isomorphic.js +2 -8
- package/build/main/isomorphic.js.map +1 -1
- package/build/main/local/digest.d.ts +3 -3
- package/build/main/local/digest.js.map +1 -1
- package/build/main/local/generate.js +10 -8
- package/build/main/local/generate.js.map +1 -1
- package/build/main/local/index.d.ts +5 -1
- package/build/main/local/index.js +321 -10
- package/build/main/local/index.js.map +1 -1
- package/build/main/local/prune-pulled-schema.js +4 -1
- package/build/main/local/prune-pulled-schema.js.map +1 -1
- package/build/main/migration.d.ts +7 -0
- package/build/main/migration.js +11 -0
- package/build/main/migration.js.map +1 -0
- package/build/main/plugins.d.ts +2 -2
- package/build/main/plugins.js.map +1 -1
- package/build/main/postgres-error.d.ts +3 -3
- package/build/main/postgres-error.js +4 -3
- package/build/main/postgres-error.js.map +1 -1
- package/build/main/query/listing/status.d.ts +0 -10
- package/build/main/query/listing/status.js +2 -14
- package/build/main/query/listing/status.js.map +1 -1
- package/build/main/query/tenant/status.d.ts +5 -8
- package/build/main/query/tenant/status.js +18 -21
- package/build/main/query/tenant/status.js.map +1 -1
- package/build/main/regional.d.ts +7 -1
- package/build/main/regional.js +30 -17
- package/build/main/regional.js.map +1 -1
- package/build/main/test/index.d.ts +23 -11
- package/build/main/test/index.js +31 -23
- package/build/main/test/index.js.map +1 -1
- package/build/main/transaction.d.ts +3 -3
- package/build/main/transaction.js.map +1 -1
- package/build/main/v1.generated.d.ts +771 -139
- package/build/main/v1.generated.js.map +1 -1
- package/build/migrations-v2/0000000000000-baseline.ts +5 -0
- package/build/migrations-v2/0000000000001-public-audit-events-v2.ts +137 -0
- package/build/migrations-v2/0000000000002-audit-recovery-watermarks.ts +30 -0
- package/build/migrations-v2/0000000000003-audit-effect-recovery-watermark.ts +13 -0
- package/build/migrations-v2/0000000000004-audit-event-projected-at.ts +15 -0
- package/build/migrations-v2/0000000000005-audit-recovery-indexes.ts +63 -0
- package/build/migrations-v2/0000000000006-audit-action-public-event-projected-at.ts +22 -0
- package/build/migrations-v2/0000000000007-audit-action-public-event-projected-at-backfill.ts +35 -0
- package/build/migrations-v2/0000000000008-global-user-attribution.ts +33 -0
- package/build/migrations-v2/0000000000008-team-issue-rule-state.ts +52 -0
- package/build/migrations-v2/0000000000009-reservation-issue-projections.ts +45 -0
- package/build/migrations-v2/0000000000010-bank-rule-application-bank-record-delete-cascade.ts +26 -0
- package/build/migrations-v2/0000000000011-guest-balance-journal-entry-lookup-index.ts +25 -0
- package/build/migrations-v2/0000000000012-trial-free-analytics-billing-status.ts +72 -0
- package/build/migrations-v2/0000000000013-ui-permission-bundles.ts +45 -0
- package/build/migrations-v2/0000000000014-ui-permission-bundle-top-up.ts +32 -0
- package/build/migrations-v2/0000000000015-durable-flow-events.ts +163 -0
- package/build/migrations-v2/0000000000016-billing-listing-facts.ts +539 -0
- package/build/migrations-v2/0000000000016-managed-team-access.ts +34 -0
- package/build/migrations-v2/0000000000017-drop-trial-until.ts +42 -0
- package/build/migrations-v2/0000000000017-webhook-secret-reencryption-failures.ts +18 -0
- package/build/migrations-v2/0000000000018-accounting-integrity-monitoring.ts +276 -0
- package/build/migrations-v2/0000000000018-durable-flow-event-sensitive-input.ts +28 -0
- package/build/migrations-v2/0000000000019-accounting-integrity-run-shards.ts +26 -0
- package/build/migrations-v2/0000000000019-asynchronous-operations.ts +736 -0
- package/build/migrations-v2/0000000000020-accounting-integrity-case-classification.ts +52 -0
- package/build/migrations-v2/0000000000021-payment-line-classification-monitor-indexes.ts +31 -0
- package/build/migrations-v2/0000000000022-accounting-integrity-controlled-repairs.ts +281 -0
- package/build/migrations-v2/0000000000023-line-classification-usage.ts +325 -0
- package/build/migrations-v2/0000000000024-tenant-region-migration.ts +108 -0
- package/build/migrations-v2/0000000000025-partner-ach-denial-default.ts +30 -0
- package/build/migrations-v2/0000000000026-line-classification-usage-capture.ts +399 -0
- package/build/migrations-v2/0000000000027-payout-replacement-chain.ts +27 -0
- package/build/migrations-v2/0000000000028-accounting-integrity-operator-workflow.ts +108 -0
- package/build/migrations-v2/0000000000029-accounting-integrity-definition-artifacts.ts +40 -0
- package/build/migrations-v2/0000000000030-accounting-integrity-review-metadata-compatibility.ts +49 -0
- package/build/migrations-v2/0000000000031-ui-permission-role-simplification.ts +70 -0
- package/build/migrations-v2/0000000000032-tenant-delete-ownership-cascades.ts +44 -0
- package/build/migrations-v2/0000000000033-reservation-issue-seed-bucket-index.ts +19 -0
- package/build/migrations-v2/0000000000034-retire-recent-classification-indexes.ts +29 -0
- package/build/migrations-v2/0000000000035-core-change-autovacuum.ts +24 -0
- package/build/migrations-v2/0000000000036-journal-entry-inactive-reason-constraint.ts +33 -0
- package/build/migrations-v2/0000000000037-journal-entry-inactive-reasons.ts +19 -0
- package/build/{migrations/0000000000023-journal-entry-currency-mismatch-reason.ts → migrations-v2/0000000000038-journal-entry-group-inactive-reason.ts} +4 -4
- package/build/migrations-v2/0000000000039-reservation-guest-breakdown.ts +19 -0
- package/build/migrations-v2/0000000000040-csv-import-source-identity-index.ts +23 -0
- package/build/migrations-v2/0000000000041-payment-returns.ts +38 -0
- package/build/migrations-v2/0000000000042-operation-resource-types.ts +609 -0
- package/build/migrations-v2/0000000000043-reservation-journal-freshness.ts +149 -0
- package/build/migrations-v2/0000000000044-reservation-journal-freshness-backfill.ts +254 -0
- package/build/migrations-v2/0000000000045-reservation-journal-freshness-revision-repair.ts +83 -0
- package/build/migrations-v2/0000000000046-materialized-reservation-journal-operations.ts +709 -0
- package/build/migrations-v2/0000000000047-public-audit-completion.ts +77 -0
- package/build/migrations-v2/0000000000048-reservation-journal-full-refresh-repair.ts +136 -0
- package/build/migrations-v2/0000000000049-queued-journal-operation-failures.ts +60 -0
- package/build/migrations-v2/0000000000050-connection-oauth-state.ts +43 -0
- package/build/module/camel-case/index.js +1 -1
- package/build/module/camel-case/index.js.map +1 -1
- package/build/module/control-plane/index.d.ts +344 -16
- package/build/module/control-plane/index.js +49 -1
- package/build/module/control-plane/index.js.map +1 -1
- package/build/module/domain.d.ts +4 -0
- package/build/module/domain.js +2 -0
- package/build/module/domain.js.map +1 -0
- package/build/module/error.d.ts +2 -1
- package/build/module/error.js +3 -1
- package/build/module/error.js.map +1 -1
- package/build/module/index.d.ts +19 -14
- package/build/module/index.js +236 -57
- package/build/module/index.js.map +1 -1
- package/build/module/isomorphic.d.ts +5 -5
- package/build/module/isomorphic.js +1 -6
- package/build/module/isomorphic.js.map +1 -1
- package/build/module/local/digest.d.ts +3 -3
- package/build/module/local/digest.js.map +1 -1
- package/build/module/local/generate.js +10 -8
- package/build/module/local/generate.js.map +1 -1
- package/build/module/local/index.d.ts +5 -1
- package/build/module/local/index.js +322 -11
- package/build/module/local/index.js.map +1 -1
- package/build/module/local/prune-pulled-schema.js +4 -1
- package/build/module/local/prune-pulled-schema.js.map +1 -1
- package/build/module/migration.d.ts +7 -0
- package/build/module/migration.js +8 -0
- package/build/module/migration.js.map +1 -0
- package/build/module/plugins.d.ts +2 -2
- package/build/module/plugins.js.map +1 -1
- package/build/module/postgres-error.d.ts +3 -3
- package/build/module/postgres-error.js +4 -3
- package/build/module/postgres-error.js.map +1 -1
- package/build/module/query/listing/status.d.ts +0 -10
- package/build/module/query/listing/status.js +2 -12
- package/build/module/query/listing/status.js.map +1 -1
- package/build/module/query/tenant/status.d.ts +5 -8
- package/build/module/query/tenant/status.js +18 -21
- package/build/module/query/tenant/status.js.map +1 -1
- package/build/module/regional.d.ts +7 -1
- package/build/module/regional.js +30 -17
- package/build/module/regional.js.map +1 -1
- package/build/module/test/index.d.ts +23 -11
- package/build/module/test/index.js +31 -23
- package/build/module/test/index.js.map +1 -1
- package/build/module/transaction.d.ts +3 -3
- package/build/module/transaction.js.map +1 -1
- package/build/module/v1.generated.d.ts +771 -139
- package/build/module/v1.generated.js.map +1 -1
- package/package.json +5 -4
- package/build/migrations/0000000000001-init.ts +0 -5
- package/build/migrations/0000000000009-drop-store-schema.ts +0 -14
- package/build/migrations/0000000000010-bank-rules.ts +0 -190
- package/build/migrations/0000000000011-bank-rule-line-adjustments.ts +0 -65
- package/build/migrations/0000000000012-bank-rule-conditions.ts +0 -45
- package/build/migrations/0000000000013-bank-rule-name-unique.ts +0 -15
- package/build/migrations/0000000000014-bank-rule-drop-legacy-conditions.ts +0 -41
- package/build/migrations/0000000000015-booking-channel-logo-dev-provider.ts +0 -70
- package/build/migrations/0000000000016-owner-statement-draft-status.ts +0 -22
- package/build/migrations/0000000000017-tenant-migration-markers.ts +0 -18
- package/build/migrations/0000000000018-security-deposits-payable-category.ts +0 -63
- package/build/migrations/0000000000019-tenant-app-settings.ts +0 -76
- package/build/migrations/0000000000020-operating-opening-trial-balance.ts +0 -36
- package/build/migrations/0000000000021-audit-foreign-key-indexes.ts +0 -77
- package/build/migrations/0000000000022-opening-trial-balance-combined-columns.ts +0 -30
- package/build/migrations/0000000000024-listing-parent.ts +0 -37
- package/build/migrations/0000000000025-journal-entry-parent-listing.ts +0 -26
- package/build/migrations/0000000000026-booking-channel-logo-slots.ts +0 -89
- package/build/migrations/0000000000027-list-browse-performance-indexes.ts +0 -52
- package/build/migrations/0000000000028-flow-setting-status-jsonb.ts +0 -20
- package/build/migrations/0000000000029-tenant-slug.ts +0 -328
- package/build/migrations/0000000000030-pms-accounting-windows.ts +0 -50
- package/build/migrations/0000000000031-owner-statement-projection-listing-revision.ts +0 -20
- package/build/migrations/0000000000032-flow-event-listening.ts +0 -28
- package/build/migrations/0000000000033-opening-trial-balance-transaction.ts +0 -272
- package/build/migrations/0000000000034-historic-general-ledger.ts +0 -24
- package/build/migrations/0000000000035-tenant-regional-placement.ts +0 -37
- package/build/migrations/0000000000036-control-plane-projection-events.ts +0 -43
- package/build/migrations/0000000000037-tenant-guide-onboarding.ts +0 -21
- package/build/migrations/0000000000038-tracking-event-analytics-sink.ts +0 -31
- package/build/migrations/0000000000039-crunchy-region.ts +0 -86
- package/build/migrations/0000000000040-hostaway-region.ts +0 -72
- package/build/migrations/0000000000041-audit-tenant-fk.ts +0 -66
- package/build/migrations/0000000000042-ramp-staging-connect-params.ts +0 -35
- package/build/migrations/0000000000043-gl-pms-accounting-window-guard.ts +0 -125
- package/build/migrations/0000000000044-tenant-cross-region-fks.ts +0 -45
- package/build/migrations/0000000000045-cloudflare-region-env.ts +0 -100
- package/build/migrations/0000000000046-control-plane-outbox-alias.ts +0 -46
- package/build/migrations/0000000000047-ramp-contact-last-4-digits.ts +0 -16
- package/build/migrations/0000000000047-tenant-status-backfill.ts +0 -40
- package/build/migrations/0000000000048-tenant-status-constraint.ts +0 -24
- package/build/migrations/0000000000049-health-tenant-issues.ts +0 -69
- package/build/migrations/0000000000050-partner-webhooks.ts +0 -135
- package/build/migrations/0000000000051-health-webhook-runtime-grants.ts +0 -42
- package/build/migrations/0000000000052-feature-approval-team-enablement.ts +0 -13
- package/build/migrations/0000000000053-health-webhook-enums.ts +0 -296
- package/build/migrations/0000000000054-user-secondary-emails-jsonb.ts +0 -25
- package/build/migrations/0000000000055-outbound-webhooks-v1.ts +0 -221
- package/build/migrations/0000000000056-connection-webhook-version.ts +0 -18
- package/build/migrations/0000000000057-sync-webhook-version.ts +0 -18
- package/build/migrations/0000000000058-reservation-webhook-version.ts +0 -18
- package/build/migrations/0000000000059-listing-webhook-version.ts +0 -18
- package/build/migrations/0000000000060-owner-statement-webhook-version.ts +0 -19
- package/build/migrations/0000000000061-transaction-webhook-version.ts +0 -18
- package/build/migrations/0000000000062-plaid-connect-session.ts +0 -102
- package/build/migrations/0000000000063-pgcrypto.ts +0 -27
- package/build/migrations/0000000000064-partner-api-foundation.ts +0 -36
- package/build/migrations/0000000000065-canonical-jsonb-shapes.ts +0 -231
- package/build/migrations/0000000000066-source-delete-fk-indexes.ts +0 -20
- package/build/migrations/0000000000067-remove-opening-trial-balance-account-columns.ts +0 -34
- package/build/migrations/0000000000068-bank-record-account-delete-cascade.ts +0 -26
package/build/main/error.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"error.js","sourceRoot":"src/","sources":["error.ts"],"names":[],"mappings":";;;AAAA,MAAa,WAAY,SAAQ,KAAK;IACpC,
|
|
1
|
+
{"version":3,"file":"error.js","sourceRoot":"src/","sources":["error.ts"],"names":[],"mappings":";;;AAAA,MAAa,WAAY,SAAQ,KAAK;IACpC,YACE,OAAe,EACC,OAAiB;QAEjC,KAAK,CAAC,OAAO,CAAC,CAAC;QAFC,YAAO,GAAP,OAAO,CAAU;QAGjC,IAAI,CAAC,IAAI,GAAG,aAAa,CAAC;IAC5B,CAAC;CACF;AARD,kCAQC","sourcesContent":["export class KyselyError extends Error {\n constructor(\n message: string,\n public readonly details?: unknown\n ) {\n super(message);\n this.name = 'KyselyError';\n }\n}\n"]}
|
package/build/main/index.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import type { Kysely as K, LogConfig } from 'kysely';
|
|
1
|
+
import type { Kysely as K, LogConfig, Transaction as T } from 'kysely';
|
|
2
2
|
import postgres, { type Sql } from 'postgres';
|
|
3
|
+
import { type ControlPlaneDB } from './control-plane';
|
|
3
4
|
export type { Insertable, LogEvent } from 'kysely';
|
|
4
5
|
export * from './error';
|
|
5
6
|
export * from './isomorphic';
|
|
@@ -7,29 +8,33 @@ export * from './postgres-error';
|
|
|
7
8
|
export * from './query';
|
|
8
9
|
export * from './regional';
|
|
9
10
|
export * from './transaction';
|
|
11
|
+
import type { TenantDataRegion } from './regional';
|
|
10
12
|
import type { DB } from './v1.generated';
|
|
11
13
|
type KyselyOpts = {
|
|
14
|
+
dataRegion?: TenantDataRegion;
|
|
15
|
+
hyperdrive?: true;
|
|
16
|
+
onRetryDiagnostic?: (diagnostic: PostgresRetryDiagnostic) => void;
|
|
12
17
|
repositoryName?: string;
|
|
13
18
|
log?: true | LogConfig;
|
|
14
19
|
};
|
|
20
|
+
type PostgresRetryDiagnostic = {
|
|
21
|
+
attemptCount: number;
|
|
22
|
+
dataRegion?: TenantDataRegion;
|
|
23
|
+
operationKind: 'acquisition' | 'mutation' | 'select' | 'transaction';
|
|
24
|
+
outcome: 'exhausted' | 'notRetryable' | 'retrying';
|
|
25
|
+
repositoryName?: string;
|
|
26
|
+
};
|
|
15
27
|
type PgOpt = {
|
|
16
28
|
forceDisableSSL?: boolean;
|
|
17
29
|
probe?: true;
|
|
18
30
|
retries?: false | number;
|
|
19
|
-
}
|
|
31
|
+
} & Pick<KyselyOpts, 'hyperdrive'>;
|
|
20
32
|
export type Kysely = K<DB>;
|
|
21
|
-
export type
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
*/
|
|
25
|
-
export declare function useKysely(postgres: Sql, options?: KyselyOpts): K<DB>;
|
|
33
|
+
export type ControlPlaneKysely = K<ControlPlaneDB>;
|
|
34
|
+
export type ControlPlaneTransaction = T<ControlPlaneDB>;
|
|
35
|
+
export declare function useKysely<Database = DB>(postgres: Sql, options?: KyselyOpts): K<Database>;
|
|
26
36
|
export declare function useAsyncPostgres(connectionString: string, opt?: PgOpt): Promise<postgres.Sql<{}>>;
|
|
27
37
|
export declare function useAsyncKysely(connectionString: string, opt?: PgOpt & KyselyOpts): Promise<K<DB>>;
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
*/
|
|
31
|
-
export declare function usePostgres(connectionString?: string, opt?: Pick<PgOpt, 'forceDisableSSL'>): postgres.Sql<{}>;
|
|
38
|
+
export declare function useAsyncNeonWebSocketKysely(connectionString: string, opt?: Pick<PgOpt, 'probe'> & KyselyOpts): Promise<K<DB>>;
|
|
39
|
+
export declare function useAsyncControlPlaneKysely(connectionString: string, opt?: PgOpt & KyselyOpts): Promise<K<ControlPlaneDB>>;
|
|
32
40
|
export declare function forceCloseAllPostgres(timeoutMs?: number): Promise<void>;
|
|
33
|
-
export declare class DatabaseError extends Error {
|
|
34
|
-
constructor(message: string, cause: any);
|
|
35
|
-
}
|
package/build/main/index.js
CHANGED
|
@@ -17,15 +17,18 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
17
17
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
18
18
|
};
|
|
19
19
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
20
|
-
exports.DatabaseError = void 0;
|
|
21
20
|
exports.useKysely = useKysely;
|
|
22
21
|
exports.useAsyncPostgres = useAsyncPostgres;
|
|
23
22
|
exports.useAsyncKysely = useAsyncKysely;
|
|
24
|
-
exports.
|
|
23
|
+
exports.useAsyncNeonWebSocketKysely = useAsyncNeonWebSocketKysely;
|
|
24
|
+
exports.useAsyncControlPlaneKysely = useAsyncControlPlaneKysely;
|
|
25
25
|
exports.forceCloseAllPostgres = forceCloseAllPostgres;
|
|
26
26
|
const exponential_backoff_1 = require("exponential-backoff");
|
|
27
|
+
const serverless_1 = require("@neondatabase/serverless");
|
|
28
|
+
const kysely_1 = require("kysely");
|
|
27
29
|
const kysely_postgres_js_1 = require("kysely-postgres-js");
|
|
28
30
|
const postgres_1 = __importDefault(require("postgres"));
|
|
31
|
+
const control_plane_1 = require("./control-plane");
|
|
29
32
|
const error_1 = require("./error");
|
|
30
33
|
const plugins_1 = require("./plugins");
|
|
31
34
|
__exportStar(require("./error"), exports);
|
|
@@ -39,43 +42,214 @@ const retryableMessages = [
|
|
|
39
42
|
'CONNECTION_CLOSED',
|
|
40
43
|
'CONNECT_TIMEOUT',
|
|
41
44
|
'Idle connection closed by Hyperdrive.',
|
|
45
|
+
'server_login_retry',
|
|
42
46
|
];
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
47
|
+
const postgresRetryAttempts = 3;
|
|
48
|
+
function isRetryableConnectionError(error) {
|
|
49
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
50
|
+
return retryableMessages.some((retryable) => message.includes(retryable));
|
|
51
|
+
}
|
|
52
|
+
function isConnectionReset(error) {
|
|
53
|
+
return (error instanceof Error && 'code' in error && error.code === 'ECONNRESET');
|
|
54
|
+
}
|
|
55
|
+
function isQueryRetryDiagnosticError(error) {
|
|
56
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
57
|
+
return (isRetryableConnectionError(error) ||
|
|
58
|
+
isConnectionReset(error) ||
|
|
59
|
+
message === 'Egress connection severed outside of Hyperdrive' ||
|
|
60
|
+
message === 'Network connection lost.' ||
|
|
61
|
+
message === 'Node shutting down' ||
|
|
62
|
+
message === 'Node shutting down.');
|
|
63
|
+
}
|
|
64
|
+
async function retryPostgres(operation, retry, diagnostic) {
|
|
65
|
+
let attemptCount = 0;
|
|
66
|
+
let retried = false;
|
|
67
|
+
const emitDiagnostic = (outcome) => {
|
|
68
|
+
if (!diagnostic)
|
|
69
|
+
return;
|
|
70
|
+
diagnostic.emit({
|
|
71
|
+
attemptCount,
|
|
72
|
+
dataRegion: diagnostic.dataRegion,
|
|
73
|
+
operationKind: diagnostic.operationKind,
|
|
74
|
+
outcome,
|
|
75
|
+
repositoryName: diagnostic.repositoryName,
|
|
76
|
+
});
|
|
77
|
+
};
|
|
78
|
+
try {
|
|
79
|
+
return await (0, exponential_backoff_1.backOff)(async () => {
|
|
80
|
+
attemptCount++;
|
|
81
|
+
return await operation();
|
|
82
|
+
}, {
|
|
83
|
+
numOfAttempts: postgresRetryAttempts,
|
|
84
|
+
startingDelay: (0, utils_1.parseDuration)('1s'),
|
|
85
|
+
maxDelay: (0, utils_1.parseDuration)('5s'),
|
|
86
|
+
async retry(error, attemptNumber) {
|
|
87
|
+
const shouldRetry = attemptNumber < postgresRetryAttempts &&
|
|
88
|
+
(await retry(error, attemptNumber));
|
|
89
|
+
if (shouldRetry && diagnostic) {
|
|
90
|
+
retried = true;
|
|
91
|
+
emitDiagnostic('retrying');
|
|
92
|
+
}
|
|
93
|
+
return shouldRetry;
|
|
94
|
+
},
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
catch (error) {
|
|
98
|
+
if (diagnostic?.shouldEmit(error)) {
|
|
99
|
+
emitDiagnostic(retried && attemptCount === postgresRetryAttempts
|
|
100
|
+
? 'exhausted'
|
|
101
|
+
: 'notRetryable');
|
|
102
|
+
}
|
|
103
|
+
throw error;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
class RetryingPostgresJSDialect extends kysely_postgres_js_1.PostgresJSDialect {
|
|
107
|
+
constructor(config, retryDiagnostic) {
|
|
108
|
+
super(config);
|
|
109
|
+
this.config = config;
|
|
110
|
+
this.retryDiagnostic = retryDiagnostic;
|
|
111
|
+
}
|
|
112
|
+
createDriver() {
|
|
113
|
+
const driver = new kysely_postgres_js_1.PostgresJSDriver(this.config);
|
|
114
|
+
const connections = new WeakMap();
|
|
115
|
+
const getConnection = (connection) => {
|
|
116
|
+
const state = connections.get(connection);
|
|
117
|
+
if (!state)
|
|
118
|
+
throw new Error('Postgres connection state is unavailable');
|
|
119
|
+
return state;
|
|
120
|
+
};
|
|
121
|
+
return {
|
|
122
|
+
init: () => driver.init(),
|
|
123
|
+
acquireConnection: async () => {
|
|
124
|
+
const state = {
|
|
125
|
+
connection: await driver.acquireConnection(),
|
|
126
|
+
inTransaction: false,
|
|
127
|
+
};
|
|
128
|
+
const connection = {
|
|
129
|
+
executeQuery: (compiledQuery) => {
|
|
130
|
+
const operationKind = state.inTransaction
|
|
131
|
+
? 'transaction'
|
|
132
|
+
: compiledQuery.query.kind === 'SelectQueryNode'
|
|
133
|
+
? 'select'
|
|
134
|
+
: 'mutation';
|
|
135
|
+
return retryPostgres(() => state.connection.executeQuery(compiledQuery), async (error) => {
|
|
136
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
137
|
+
if (state.inTransaction ||
|
|
138
|
+
(!isRetryableConnectionError(error) &&
|
|
139
|
+
(compiledQuery.query.kind !== 'SelectQueryNode' ||
|
|
140
|
+
(!isConnectionReset(error) &&
|
|
141
|
+
message !==
|
|
142
|
+
'Egress connection severed outside of Hyperdrive' &&
|
|
143
|
+
message !== 'Network connection lost.' &&
|
|
144
|
+
message !== 'Node shutting down' &&
|
|
145
|
+
message !== 'Node shutting down.')))) {
|
|
146
|
+
return false;
|
|
147
|
+
}
|
|
148
|
+
// Postgres.js already ejects a severed reserved connection.
|
|
149
|
+
// Acquire a new reservation before replaying the safe read.
|
|
150
|
+
state.connection = await driver.acquireConnection();
|
|
151
|
+
return true;
|
|
152
|
+
}, this.retryDiagnostic
|
|
153
|
+
? {
|
|
154
|
+
...this.retryDiagnostic,
|
|
155
|
+
operationKind,
|
|
156
|
+
shouldEmit: isQueryRetryDiagnosticError,
|
|
157
|
+
}
|
|
158
|
+
: undefined);
|
|
159
|
+
},
|
|
160
|
+
streamQuery: (compiledQuery, chunkSize) => {
|
|
161
|
+
if (chunkSize === undefined) {
|
|
162
|
+
throw new Error('Postgres stream chunk size is required');
|
|
163
|
+
}
|
|
164
|
+
return state.connection.streamQuery(compiledQuery, chunkSize);
|
|
165
|
+
},
|
|
166
|
+
};
|
|
167
|
+
connections.set(connection, state);
|
|
168
|
+
return connection;
|
|
169
|
+
},
|
|
170
|
+
beginTransaction: async (connection, settings) => {
|
|
171
|
+
const state = getConnection(connection);
|
|
172
|
+
state.inTransaction = true;
|
|
173
|
+
try {
|
|
174
|
+
await driver.beginTransaction(state.connection, settings);
|
|
175
|
+
}
|
|
176
|
+
catch (error) {
|
|
177
|
+
state.inTransaction = false;
|
|
178
|
+
throw error;
|
|
179
|
+
}
|
|
180
|
+
},
|
|
181
|
+
commitTransaction: async (connection) => {
|
|
182
|
+
const state = getConnection(connection);
|
|
183
|
+
try {
|
|
184
|
+
await driver.commitTransaction(state.connection);
|
|
185
|
+
}
|
|
186
|
+
finally {
|
|
187
|
+
state.inTransaction = false;
|
|
188
|
+
}
|
|
189
|
+
},
|
|
190
|
+
rollbackTransaction: async (connection) => {
|
|
191
|
+
const state = getConnection(connection);
|
|
192
|
+
try {
|
|
193
|
+
await driver.rollbackTransaction(state.connection);
|
|
194
|
+
}
|
|
195
|
+
finally {
|
|
196
|
+
state.inTransaction = false;
|
|
197
|
+
}
|
|
198
|
+
},
|
|
199
|
+
savepoint: (connection, savepointName, compileQuery) => driver.savepoint(getConnection(connection).connection, savepointName, compileQuery),
|
|
200
|
+
rollbackToSavepoint: (connection, savepointName, compileQuery) => driver.rollbackToSavepoint(getConnection(connection).connection, savepointName, compileQuery),
|
|
201
|
+
releaseSavepoint: (connection, savepointName, compileQuery) => driver.releaseSavepoint(getConnection(connection).connection, savepointName, compileQuery),
|
|
202
|
+
releaseConnection: async (connection) => {
|
|
203
|
+
await driver.releaseConnection(getConnection(connection).connection);
|
|
204
|
+
connections.delete(connection);
|
|
205
|
+
},
|
|
206
|
+
destroy: () => driver.destroy(),
|
|
207
|
+
};
|
|
208
|
+
}
|
|
209
|
+
}
|
|
46
210
|
function useKysely(postgres, options) {
|
|
47
211
|
console.debug('Creating Kysely instance');
|
|
48
|
-
const
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
|
|
212
|
+
const emitRetryDiagnostic = options?.onRetryDiagnostic ??
|
|
213
|
+
(options?.repositoryName
|
|
214
|
+
? (diagnostic) => console.warn('Postgres operation retry diagnostic', diagnostic)
|
|
215
|
+
: undefined);
|
|
216
|
+
const reserveConnection = postgres.reserve.bind(postgres);
|
|
217
|
+
postgres.reserve = async () => {
|
|
218
|
+
const connection = await retryPostgres(reserveConnection, (error) => isRetryableConnectionError(error) ||
|
|
219
|
+
isConnectionReset(error) ||
|
|
220
|
+
(error instanceof Error &&
|
|
221
|
+
error.message === 'connection attempt failed'), emitRetryDiagnostic
|
|
222
|
+
? {
|
|
223
|
+
dataRegion: options?.dataRegion,
|
|
224
|
+
emit: emitRetryDiagnostic,
|
|
225
|
+
operationKind: 'acquisition',
|
|
226
|
+
repositoryName: options?.repositoryName,
|
|
227
|
+
shouldEmit: (error) => isRetryableConnectionError(error) ||
|
|
228
|
+
isConnectionReset(error) ||
|
|
229
|
+
(error instanceof Error &&
|
|
230
|
+
error.message === 'connection attempt failed'),
|
|
231
|
+
}
|
|
232
|
+
: undefined);
|
|
233
|
+
if (options?.hyperdrive) {
|
|
234
|
+
const unsafe = connection.unsafe;
|
|
235
|
+
connection.unsafe = (query, parameters, queryOptions) => unsafe(query, parameters, { ...queryOptions, prepare: true });
|
|
236
|
+
}
|
|
237
|
+
return connection;
|
|
238
|
+
};
|
|
239
|
+
const kysely = (0, plugins_1.getKysely)(new RetryingPostgresJSDialect({ postgres }, emitRetryDiagnostic
|
|
240
|
+
? {
|
|
241
|
+
dataRegion: options?.dataRegion,
|
|
242
|
+
emit: emitRetryDiagnostic,
|
|
243
|
+
repositoryName: options?.repositoryName,
|
|
244
|
+
shouldEmit: isQueryRetryDiagnosticError,
|
|
245
|
+
}
|
|
246
|
+
: undefined), {
|
|
70
247
|
repositoryName: options?.repositoryName,
|
|
71
248
|
log: options?.log,
|
|
72
249
|
});
|
|
73
250
|
kysely.destroy = async () => {
|
|
74
251
|
console.debug('Closing Kysely connection');
|
|
75
|
-
await
|
|
76
|
-
postgres.end({ timeout: 5000 }).catch(() => undefined),
|
|
77
|
-
new Promise((res) => setTimeout(res, 6000)),
|
|
78
|
-
]);
|
|
252
|
+
await postgres.end({ timeout: 5 }).catch(() => undefined);
|
|
79
253
|
const index = _connections.indexOf(postgres);
|
|
80
254
|
if (index !== -1)
|
|
81
255
|
_connections.splice(index, 1);
|
|
@@ -87,21 +261,29 @@ async function useAsyncPostgres(connectionString, opt) {
|
|
|
87
261
|
const delayMs = 2500;
|
|
88
262
|
const probe = opt?.probe === true;
|
|
89
263
|
const retries = probe ? (opt?.retries === false ? 0 : opt?.retries || 3) : 1;
|
|
90
|
-
const ssl = opt?.forceDisableSSL !== true;
|
|
264
|
+
const ssl = opt?.forceDisableSSL !== true && opt?.hyperdrive !== true;
|
|
91
265
|
const url = new URL(connectionString);
|
|
92
266
|
console.debug(`Creating Postgres connection with probe=${probe}, ${retries} attempts, ssl=${ssl}, and port=${url.port}`);
|
|
93
267
|
if (_connections.length > 0)
|
|
94
268
|
console.warn(`We already have ${_connections.length} Postgres connections`);
|
|
95
269
|
for (let attempt = 1; attempt <= retries; attempt++) {
|
|
270
|
+
let sql;
|
|
96
271
|
try {
|
|
97
|
-
|
|
272
|
+
sql = (0, postgres_1.default)(connectionString, {
|
|
98
273
|
ssl: ssl ? 'require' : false,
|
|
99
|
-
|
|
100
|
-
// idle_timeout: 10
|
|
274
|
+
target_session_attrs: 'read-write',
|
|
101
275
|
// enable prepare statements, pgbouncer on crunchy allows for prepared statements
|
|
102
276
|
prepare: true,
|
|
103
|
-
|
|
104
|
-
|
|
277
|
+
...(opt?.hyperdrive
|
|
278
|
+
? {
|
|
279
|
+
max: 5,
|
|
280
|
+
// Retire idle clients before Hyperdrive can close them asynchronously.
|
|
281
|
+
idle_timeout: 10,
|
|
282
|
+
}
|
|
283
|
+
: {
|
|
284
|
+
connect_timeout: 10,
|
|
285
|
+
idle_timeout: 60,
|
|
286
|
+
}),
|
|
105
287
|
});
|
|
106
288
|
if (probe) {
|
|
107
289
|
await sql `select 1`;
|
|
@@ -113,6 +295,7 @@ async function useAsyncPostgres(connectionString, opt) {
|
|
|
113
295
|
return sql;
|
|
114
296
|
}
|
|
115
297
|
catch (err) {
|
|
298
|
+
await sql?.end({ timeout: 0 }).catch(() => undefined);
|
|
116
299
|
if (attempt === retries)
|
|
117
300
|
throw err;
|
|
118
301
|
console.warn(`Postgres connection failed (attempt ${attempt}), retrying...`);
|
|
@@ -126,33 +309,26 @@ async function useAsyncKysely(connectionString, opt) {
|
|
|
126
309
|
const sql = await useAsyncPostgres(connectionString, opt);
|
|
127
310
|
return useKysely(sql, opt);
|
|
128
311
|
}
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
return
|
|
312
|
+
async function useAsyncNeonWebSocketKysely(connectionString, opt) {
|
|
313
|
+
const pool = new serverless_1.Pool({ connectionString, max: 5 });
|
|
314
|
+
const kysely = (0, plugins_1.getKysely)(new kysely_1.PostgresDialect({ pool }), opt ?? {});
|
|
315
|
+
kysely.destroy = async () => {
|
|
316
|
+
console.debug('Closing Neon WebSocket Kysely connection');
|
|
317
|
+
await pool.end();
|
|
318
|
+
};
|
|
319
|
+
if (opt?.probe)
|
|
320
|
+
await pool.query('select 1');
|
|
321
|
+
return kysely;
|
|
322
|
+
}
|
|
323
|
+
async function useAsyncControlPlaneKysely(connectionString, opt) {
|
|
324
|
+
const sql = await useAsyncPostgres(connectionString, opt);
|
|
325
|
+
return (0, control_plane_1.withControlPlaneSchema)(useKysely(sql, opt), 'public');
|
|
143
326
|
}
|
|
144
327
|
async function forceCloseAllPostgres(timeoutMs = 5000) {
|
|
145
328
|
await Promise.race([
|
|
146
|
-
Promise.all(_connections.map((pg) => pg.end({ timeout: timeoutMs }).catch(() => undefined))),
|
|
329
|
+
Promise.all(_connections.map((pg) => pg.end({ timeout: timeoutMs / 1000 }).catch(() => undefined))),
|
|
147
330
|
new Promise((res) => setTimeout(res, timeoutMs + 1000)),
|
|
148
331
|
]);
|
|
149
332
|
_connections = [];
|
|
150
333
|
}
|
|
151
|
-
class DatabaseError extends Error {
|
|
152
|
-
constructor(message, cause) {
|
|
153
|
-
super(message);
|
|
154
|
-
this.cause = cause;
|
|
155
|
-
}
|
|
156
|
-
}
|
|
157
|
-
exports.DatabaseError = DatabaseError;
|
|
158
334
|
//# sourceMappingURL=index.js.map
|
package/build/main/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"src/","sources":["index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;AAwCA,8BA6CC;AAGD,4CA4CC;AAED,wCAMC;AAKD,kCAeC;AAED,sDAUC;AA5KD,6DAA8C;AAE9C,2DAAuD;AACvD,wDAA8C;AAC9C,mCAAsC;AACtC,uCAAsC;AAGtC,0CAAwB;AACxB,+CAA6B;AAC7B,mDAAiC;AACjC,0CAAwB;AACxB,6CAA2B;AAC3B,gDAA8B;AAE9B,6CAAkD;AAclD,MAAM,iBAAiB,GAAG;IACxB,mBAAmB;IACnB,iBAAiB;IACjB,uCAAuC;CACxC,CAAC;AAIF;;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,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;YAC9D,UAAU,CAAC,YAAY,GAAG,CAAC,GAAG,EAAE,EAAE,CAChC,IAAA,6BAAO,EAAC,KAAK,IAAI,EAAE,CAAC,MAAM,YAAY,CAAC,GAAG,CAAC,EAAE;gBAC3C,aAAa,EAAE,CAAC;gBAChB,aAAa,EAAE,IAAA,qBAAa,EAAC,IA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ACH,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 './postgres-error';\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?: true;\n retries?: false | number;\n};\n\nconst retryableMessages = [\n 'CONNECTION_CLOSED',\n 'CONNECT_TIMEOUT',\n 'Idle connection closed by Hyperdrive.',\n];\n\nexport type Kysely = K<DB>;\nexport type Postgres = Sql;\n/**\n * @deprecated This method is deprecated in favor of the useAsyncKysely method.\n */\nexport function useKysely(postgres: Sql, options?: KyselyOpts) {\n console.debug('Creating Kysely instance');\n const kysely = getKysely(\n new PostgresJSDialect({\n postgres,\n 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 (\n retryableMessages.some((m) => message?.includes(m)) ||\n (arg.query.kind === 'SelectQueryNode' &&\n (message ===\n 'Egress connection severed outside of Hyperdrive' ||\n message === 'Network connection lost.'))\n ) {\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 probe = opt?.probe === true;\n const retries = probe ? (opt?.retries === false ? 0 : opt?.retries || 3) : 1;\n const ssl = opt?.forceDisableSSL !== true;\n const url = new URL(connectionString);\n\n console.debug(\n `Creating Postgres connection with probe=${probe}, ${retries} attempts, 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 (probe) {\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
|
+
{"version":3,"file":"index.js","sourceRoot":"src/","sources":["index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;AAsRA,8BA+DC;AAGD,4CAqDC;AAED,wCAMC;AAED,kEAYC;AAED,gEAMC;AAED,sDAUC;AAvbD,6DAA8C;AAC9C,yDAAgD;AAQhD,mCAAyC;AACzC,2DAI4B;AAC5B,wDAA8C;AAC9C,mDAA8E;AAC9E,mCA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AI,wBAAe,CAAC,EAAE,IAAI,EAAE,CAAC,EAAE,GAAG,IAAI,EAAE,CAAC,CAAC;IACvE,MAAM,CAAC,OAAO,GAAG,KAAK,IAAI,EAAE;QAC1B,OAAO,CAAC,KAAK,CAAC,0CAA0C,CAAC,CAAC;QAC1D,MAAM,IAAI,CAAC,GAAG,EAAE,CAAC;IACnB,CAAC,CAAC;IACF,IAAI,GAAG,EAAE,KAAK;QAAE,MAAM,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC;IAC7C,OAAO,MAAM,CAAC;AAChB,CAAC;AAEM,KAAK,UAAU,0BAA0B,CAC9C,gBAAwB,EACxB,GAAwB;IAExB,MAAM,GAAG,GAAG,MAAM,gBAAgB,CAAC,gBAAgB,EAAE,GAAG,CAAC,CAAC;IAC1D,OAAO,IAAA,sCAAsB,EAAC,SAAS,CAAiB,GAAG,EAAE,GAAG,CAAC,EAAE,QAAQ,CAAC,CAAC;AAC/E,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,GAAG,IAAI,EAAE,CAAC,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAC7D,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","sourcesContent":["import { backOff } from 'exponential-backoff';\nimport { Pool } from '@neondatabase/serverless';\nimport type {\n DatabaseConnection,\n Driver,\n Kysely as K,\n LogConfig,\n Transaction as T,\n} from 'kysely';\nimport { PostgresDialect } from 'kysely';\nimport {\n PostgresJSDialect,\n type PostgresJSDialectConfig,\n PostgresJSDriver,\n} from 'kysely-postgres-js';\nimport postgres, { type Sql } from 'postgres';\nimport { type ControlPlaneDB, withControlPlaneSchema } from './control-plane';\nimport { KyselyError } from './error';\nimport { getKysely } from './plugins';\n\nexport type { Insertable, LogEvent } from 'kysely';\nexport * from './error';\nexport * from './isomorphic';\nexport * from './postgres-error';\nexport * from './query';\nexport * from './regional';\nexport * from './transaction';\n\nimport { parseDuration } from '@vrplatform/utils';\nimport type { TenantDataRegion } from './regional';\nimport type { DB } from './v1.generated';\n\ntype KyselyOpts = {\n dataRegion?: TenantDataRegion;\n hyperdrive?: true;\n onRetryDiagnostic?: (diagnostic: PostgresRetryDiagnostic) => void;\n repositoryName?: string;\n log?: true | LogConfig;\n};\n\ntype PostgresRetryDiagnostic = {\n attemptCount: number;\n dataRegion?: TenantDataRegion;\n operationKind: 'acquisition' | 'mutation' | 'select' | 'transaction';\n outcome: 'exhausted' | 'notRetryable' | 'retrying';\n repositoryName?: string;\n};\n\ntype PgOpt = {\n forceDisableSSL?: boolean;\n probe?: true;\n retries?: false | number;\n} & Pick<KyselyOpts, 'hyperdrive'>;\n\nconst retryableMessages = [\n 'CONNECTION_CLOSED',\n 'CONNECT_TIMEOUT',\n 'Idle connection closed by Hyperdrive.',\n 'server_login_retry',\n];\nconst postgresRetryAttempts = 3;\n\nfunction isRetryableConnectionError(error: unknown) {\n const message = error instanceof Error ? error.message : String(error);\n return retryableMessages.some((retryable) => message.includes(retryable));\n}\n\nfunction isConnectionReset(error: unknown) {\n return (\n error instanceof Error && 'code' in error && error.code === 'ECONNRESET'\n );\n}\n\nfunction isQueryRetryDiagnosticError(error: unknown) {\n const message = error instanceof Error ? error.message : String(error);\n return (\n isRetryableConnectionError(error) ||\n isConnectionReset(error) ||\n message === 'Egress connection severed outside of Hyperdrive' ||\n message === 'Network connection lost.' ||\n message === 'Node shutting down' ||\n message === 'Node shutting down.'\n );\n}\n\nasync function retryPostgres<T>(\n operation: () => Promise<T>,\n retry: (error: unknown, attemptNumber: number) => boolean | Promise<boolean>,\n diagnostic?: Omit<PostgresRetryDiagnostic, 'attemptCount' | 'outcome'> & {\n emit: (diagnostic: PostgresRetryDiagnostic) => void;\n shouldEmit: (error: unknown) => boolean;\n }\n) {\n let attemptCount = 0;\n let retried = false;\n const emitDiagnostic = (outcome: PostgresRetryDiagnostic['outcome']) => {\n if (!diagnostic) return;\n diagnostic.emit({\n attemptCount,\n dataRegion: diagnostic.dataRegion,\n operationKind: diagnostic.operationKind,\n outcome,\n repositoryName: diagnostic.repositoryName,\n });\n };\n try {\n return await backOff(\n async () => {\n attemptCount++;\n return await operation();\n },\n {\n numOfAttempts: postgresRetryAttempts,\n startingDelay: parseDuration('1s'),\n maxDelay: parseDuration('5s'),\n async retry(error, attemptNumber) {\n const shouldRetry =\n attemptNumber < postgresRetryAttempts &&\n (await retry(error, attemptNumber));\n if (shouldRetry && diagnostic) {\n retried = true;\n emitDiagnostic('retrying');\n }\n return shouldRetry;\n },\n }\n );\n } catch (error) {\n if (diagnostic?.shouldEmit(error)) {\n emitDiagnostic(\n retried && attemptCount === postgresRetryAttempts\n ? 'exhausted'\n : 'notRetryable'\n );\n }\n throw error;\n }\n}\n\nclass RetryingPostgresJSDialect extends PostgresJSDialect {\n constructor(\n private readonly config: PostgresJSDialectConfig,\n private readonly retryDiagnostic?: Omit<\n PostgresRetryDiagnostic,\n 'attemptCount' | 'operationKind' | 'outcome'\n > & {\n emit: (diagnostic: PostgresRetryDiagnostic) => void;\n shouldEmit: (error: unknown) => boolean;\n }\n ) {\n super(config);\n }\n\n override createDriver(): Driver {\n const driver = new PostgresJSDriver(this.config);\n const connections = new WeakMap<\n DatabaseConnection,\n { connection: DatabaseConnection; inTransaction: boolean }\n >();\n const getConnection = (connection: DatabaseConnection) => {\n const state = connections.get(connection);\n if (!state) throw new Error('Postgres connection state is unavailable');\n return state;\n };\n\n return {\n init: () => driver.init(),\n acquireConnection: async () => {\n const state = {\n connection: await driver.acquireConnection(),\n inTransaction: false,\n };\n const connection: DatabaseConnection = {\n executeQuery: (compiledQuery) => {\n const operationKind = state.inTransaction\n ? 'transaction'\n : compiledQuery.query.kind === 'SelectQueryNode'\n ? 'select'\n : 'mutation';\n return retryPostgres(\n () => state.connection.executeQuery(compiledQuery),\n async (error) => {\n const message =\n error instanceof Error ? error.message : String(error);\n if (\n state.inTransaction ||\n (!isRetryableConnectionError(error) &&\n (compiledQuery.query.kind !== 'SelectQueryNode' ||\n (!isConnectionReset(error) &&\n message !==\n 'Egress connection severed outside of Hyperdrive' &&\n message !== 'Network connection lost.' &&\n message !== 'Node shutting down' &&\n message !== 'Node shutting down.')))\n ) {\n return false;\n }\n\n // Postgres.js already ejects a severed reserved connection.\n // Acquire a new reservation before replaying the safe read.\n state.connection = await driver.acquireConnection();\n return true;\n },\n this.retryDiagnostic\n ? {\n ...this.retryDiagnostic,\n operationKind,\n shouldEmit: isQueryRetryDiagnosticError,\n }\n : undefined\n );\n },\n streamQuery: (compiledQuery, chunkSize) => {\n if (chunkSize === undefined) {\n throw new Error('Postgres stream chunk size is required');\n }\n return state.connection.streamQuery(compiledQuery, chunkSize);\n },\n };\n connections.set(connection, state);\n return connection;\n },\n beginTransaction: async (connection, settings) => {\n const state = getConnection(connection);\n state.inTransaction = true;\n try {\n await driver.beginTransaction(state.connection, settings);\n } catch (error) {\n state.inTransaction = false;\n throw error;\n }\n },\n commitTransaction: async (connection) => {\n const state = getConnection(connection);\n try {\n await driver.commitTransaction(state.connection);\n } finally {\n state.inTransaction = false;\n }\n },\n rollbackTransaction: async (connection) => {\n const state = getConnection(connection);\n try {\n await driver.rollbackTransaction(state.connection);\n } finally {\n state.inTransaction = false;\n }\n },\n savepoint: (connection, savepointName, compileQuery) =>\n driver.savepoint(\n getConnection(connection).connection,\n savepointName,\n compileQuery\n ),\n rollbackToSavepoint: (connection, savepointName, compileQuery) =>\n driver.rollbackToSavepoint(\n getConnection(connection).connection,\n savepointName,\n compileQuery\n ),\n releaseSavepoint: (connection, savepointName, compileQuery) =>\n driver.releaseSavepoint(\n getConnection(connection).connection,\n savepointName,\n compileQuery\n ),\n releaseConnection: async (connection) => {\n await driver.releaseConnection(getConnection(connection).connection);\n connections.delete(connection);\n },\n destroy: () => driver.destroy(),\n };\n }\n}\n\nexport type Kysely = K<DB>;\nexport type ControlPlaneKysely = K<ControlPlaneDB>;\nexport type ControlPlaneTransaction = T<ControlPlaneDB>;\nexport function useKysely<Database = DB>(postgres: Sql, options?: KyselyOpts) {\n console.debug('Creating Kysely instance');\n const emitRetryDiagnostic =\n options?.onRetryDiagnostic ??\n (options?.repositoryName\n ? (diagnostic: PostgresRetryDiagnostic) =>\n console.warn('Postgres operation retry diagnostic', diagnostic)\n : undefined);\n const reserveConnection = postgres.reserve.bind(postgres);\n postgres.reserve = async () => {\n const connection = await retryPostgres(\n reserveConnection,\n (error) =>\n isRetryableConnectionError(error) ||\n isConnectionReset(error) ||\n (error instanceof Error &&\n error.message === 'connection attempt failed'),\n emitRetryDiagnostic\n ? {\n dataRegion: options?.dataRegion,\n emit: emitRetryDiagnostic,\n operationKind: 'acquisition',\n repositoryName: options?.repositoryName,\n shouldEmit: (error) =>\n isRetryableConnectionError(error) ||\n isConnectionReset(error) ||\n (error instanceof Error &&\n error.message === 'connection attempt failed'),\n }\n : undefined\n );\n if (options?.hyperdrive) {\n const unsafe = connection.unsafe;\n connection.unsafe = (query, parameters, queryOptions) =>\n unsafe(query, parameters, { ...queryOptions, prepare: true });\n }\n return connection;\n };\n const kysely = getKysely<Database>(\n new RetryingPostgresJSDialect(\n { postgres },\n emitRetryDiagnostic\n ? {\n dataRegion: options?.dataRegion,\n emit: emitRetryDiagnostic,\n repositoryName: options?.repositoryName,\n shouldEmit: isQueryRetryDiagnosticError,\n }\n : undefined\n ),\n {\n repositoryName: options?.repositoryName,\n log: options?.log,\n }\n );\n kysely.destroy = async () => {\n console.debug('Closing Kysely connection');\n await postgres.end({ timeout: 5 }).catch(() => undefined);\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 probe = opt?.probe === true;\n const retries = probe ? (opt?.retries === false ? 0 : opt?.retries || 3) : 1;\n const ssl = opt?.forceDisableSSL !== true && opt?.hyperdrive !== true;\n const url = new URL(connectionString);\n\n console.debug(\n `Creating Postgres connection with probe=${probe}, ${retries} attempts, 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 let sql: Sql | undefined;\n try {\n sql = postgres(connectionString, {\n ssl: ssl ? 'require' : false,\n target_session_attrs: 'read-write',\n // enable prepare statements, pgbouncer on crunchy allows for prepared statements\n prepare: true,\n ...(opt?.hyperdrive\n ? {\n max: 5,\n // Retire idle clients before Hyperdrive can close them asynchronously.\n idle_timeout: 10,\n }\n : {\n connect_timeout: 10,\n idle_timeout: 60,\n }),\n });\n\n if (probe) {\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 await sql?.end({ timeout: 0 }).catch(() => undefined);\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\nexport async function useAsyncNeonWebSocketKysely(\n connectionString: string,\n opt?: Pick<PgOpt, 'probe'> & KyselyOpts\n) {\n const pool = new Pool({ connectionString, max: 5 });\n const kysely = getKysely<DB>(new PostgresDialect({ pool }), opt ?? {});\n kysely.destroy = async () => {\n console.debug('Closing Neon WebSocket Kysely connection');\n await pool.end();\n };\n if (opt?.probe) await pool.query('select 1');\n return kysely;\n}\n\nexport async function useAsyncControlPlaneKysely(\n connectionString: string,\n opt?: PgOpt & KyselyOpts\n) {\n const sql = await useAsyncPostgres(connectionString, opt);\n return withControlPlaneSchema(useKysely<ControlPlaneDB>(sql, opt), 'public');\n}\n\nexport async function forceCloseAllPostgres(timeoutMs = 5000) {\n await Promise.race([\n Promise.all(\n _connections.map((pg) =>\n pg.end({ timeout: timeoutMs / 1000 }).catch(() => undefined)\n )\n ),\n new Promise((res) => setTimeout(res, timeoutMs + 1000)),\n ]);\n _connections = [];\n}\n"]}
|
|
@@ -1,12 +1,12 @@
|
|
|
1
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
|
+
export * from './domain';
|
|
4
5
|
export * from './v1.generated';
|
|
5
6
|
import type { DB } from './v1.generated';
|
|
6
|
-
export type
|
|
7
|
+
export type DatabaseKysely<Database> = K<Database>;
|
|
8
|
+
export type DatabaseTransaction<Database> = T<Database>;
|
|
9
|
+
export type Transaction = DatabaseTransaction<DB>;
|
|
7
10
|
export type ControlledTransaction<S extends string[] = string[]> = CT<DB, S>;
|
|
8
11
|
export { sql } from 'kysely';
|
|
9
|
-
export type Kysely =
|
|
10
|
-
export declare class DatabaseError extends Error {
|
|
11
|
-
constructor(message: string, cause: any);
|
|
12
|
-
}
|
|
12
|
+
export type Kysely = DatabaseKysely<DB>;
|
package/build/main/isomorphic.js
CHANGED
|
@@ -14,17 +14,11 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
|
14
14
|
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
15
|
};
|
|
16
16
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
-
exports.
|
|
17
|
+
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
|
+
__exportStar(require("./domain"), exports);
|
|
20
21
|
__exportStar(require("./v1.generated"), exports);
|
|
21
22
|
var kysely_1 = require("kysely");
|
|
22
23
|
Object.defineProperty(exports, "sql", { enumerable: true, get: function () { return kysely_1.sql; } });
|
|
23
|
-
class DatabaseError extends Error {
|
|
24
|
-
constructor(message, cause) {
|
|
25
|
-
super(message);
|
|
26
|
-
this.cause = cause;
|
|
27
|
-
}
|
|
28
|
-
}
|
|
29
|
-
exports.DatabaseError = DatabaseError;
|
|
30
24
|
//# sourceMappingURL=isomorphic.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"isomorphic.js","sourceRoot":"src/","sources":["isomorphic.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AA2BA,oDAAwD;AAA/C,yGAAA,aAAa,OAAA;AACtB,iDAA+B;
|
|
1
|
+
{"version":3,"file":"isomorphic.js","sourceRoot":"src/","sources":["isomorphic.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AA2BA,oDAAwD;AAA/C,yGAAA,aAAa,OAAA;AACtB,2CAAyB;AACzB,iDAA+B;AAQ/B,iCAA6B;AAApB,6FAAA,GAAG,OAAA","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 './domain';\nexport * from './v1.generated';\n\nimport type { DB } from './v1.generated';\n\nexport type DatabaseKysely<Database> = K<Database>;\nexport type DatabaseTransaction<Database> = T<Database>;\nexport type Transaction = DatabaseTransaction<DB>;\nexport type ControlledTransaction<S extends string[] = string[]> = CT<DB, S>;\nexport { sql } from 'kysely';\n\nexport type Kysely = DatabaseKysely<DB>;\n"]}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { type
|
|
2
|
-
export declare function ensureDigestFunction(kysely:
|
|
3
|
-
export declare function ensureGenRandomBytesFunction(kysely:
|
|
1
|
+
import { type DatabaseKysely } from '../isomorphic';
|
|
2
|
+
export declare function ensureDigestFunction<Database>(kysely: DatabaseKysely<Database>): Promise<void>;
|
|
3
|
+
export declare function ensureGenRandomBytesFunction<Database>(kysely: DatabaseKysely<Database>): Promise<void>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"digest.js","sourceRoot":"src/","sources":["local/digest.ts"],"names":[],"mappings":";;AAEA,
|
|
1
|
+
{"version":3,"file":"digest.js","sourceRoot":"src/","sources":["local/digest.ts"],"names":[],"mappings":";;AAEA,oDAiBC;AAED,oEA0BC;AA/CD,8CAAyD;AAElD,KAAK,UAAU,oBAAoB,CACxC,MAAgC;IAEhC,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,CAChD,MAAgC;IAEhC,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 DatabaseKysely, sql } from '../isomorphic';\n\nexport async function ensureDigestFunction<Database>(\n kysely: DatabaseKysely<Database>\n) {\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<Database>(\n kysely: DatabaseKysely<Database>\n) {\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"]}
|
|
@@ -45,11 +45,15 @@ const pglite_1 = require("@electric-sql/pglite");
|
|
|
45
45
|
const kysely_1 = require("kysely");
|
|
46
46
|
const kysely_codegen_1 = __importDefault(require("kysely-codegen"));
|
|
47
47
|
const kysely_pglite_dialect_1 = require("kysely-pglite-dialect");
|
|
48
|
+
const migration_1 = require("../migration");
|
|
48
49
|
const plugins_1 = require("../plugins");
|
|
49
50
|
async function normalizeGeneratedTypes(root) {
|
|
50
51
|
const outFile = path.join(root, 'src/v1.generated.ts');
|
|
51
52
|
const current = await Bun.file(outFile).text();
|
|
52
|
-
const next = current
|
|
53
|
+
const next = current
|
|
54
|
+
.replace('export type Timestamp = ColumnType<Date, Date | string, Date | string>;', 'export type Timestamp = ColumnType<Date | string, Date | string, Date | string>;')
|
|
55
|
+
.replace(' managedTeamAccess: Generated<string>;\n', ' managedTeamAccess: Generated<"all" | "assigned">;\n')
|
|
56
|
+
.replace(' slug: string;\n', ' slug: Generated<string>;\n');
|
|
53
57
|
if (next !== current) {
|
|
54
58
|
await Bun.write(outFile, next);
|
|
55
59
|
}
|
|
@@ -68,15 +72,16 @@ async function migrate(root, client) {
|
|
|
68
72
|
async function migrateKysely(root, kysely) {
|
|
69
73
|
console.log('init migrating kysely ....');
|
|
70
74
|
const migrator = new kysely_1.Migrator({
|
|
75
|
+
allowUnorderedMigrations: true,
|
|
71
76
|
db: kysely,
|
|
72
|
-
migrationTableSchema:
|
|
73
|
-
migrationTableName:
|
|
74
|
-
migrationLockTableName:
|
|
77
|
+
migrationTableSchema: migration_1.appMigrationEpoch.tableSchema,
|
|
78
|
+
migrationTableName: migration_1.appMigrationEpoch.tableName,
|
|
79
|
+
migrationLockTableName: migration_1.appMigrationEpoch.lockTableName,
|
|
75
80
|
provider: new kysely_1.FileMigrationProvider({
|
|
76
81
|
fs: node_fs_1.promises,
|
|
77
82
|
path,
|
|
78
83
|
// This needs to be an absolute path.
|
|
79
|
-
migrationFolder: path.join(root,
|
|
84
|
+
migrationFolder: path.join(root, migration_1.appMigrationEpoch.folder),
|
|
80
85
|
}),
|
|
81
86
|
});
|
|
82
87
|
console.log('migrating kysely ....');
|
|
@@ -123,9 +128,6 @@ async function generateDump(root, dumpPath) {
|
|
|
123
128
|
outFile: path.join(root, 'src/v1.generated.ts'),
|
|
124
129
|
defaultSchemas: ['xxx'],
|
|
125
130
|
camelCase: true,
|
|
126
|
-
typeMapping: {
|
|
127
|
-
date: 'string',
|
|
128
|
-
},
|
|
129
131
|
dialect: kysely_codegen_1.default.getDialect('postgres'),
|
|
130
132
|
})
|
|
131
133
|
.catch(() => {
|