Open History to see the last commit
1import * as Migrator from "effect/sql/Migrator";
2import * as Effect from "effect/Effect";
3import * as SqlClient from "effect/sql/SqlClient";
4import * as Option from "effect/Option";
5import * as Ref from "effect/Ref";
6import * as DatabaseMigrationProgress from "./DatabaseMigrationProgress.ts";
7import {
8 DATABASE_MIGRATION_PROGRESS_MESSAGE,
9 DATABASE_MIGRATIONS_FINISHED_MESSAGE,
10 DATABASE_MIGRATIONS_STARTED_MESSAGE,
11} from "@t3tools/shared/databaseMigrationLog";
12import { reconcileV2PreviewMigration } from "./reconcileV2PreviewMigration.ts";
13
14import Migration0001 from "./Migrations/001_OrchestrationEvents.ts";
15import Migration0002 from "./Migrations/002_OrchestrationCommandReceipts.ts";
16import Migration0003 from "./Migrations/003_CheckpointDiffBlobs.ts";
17import Migration0004 from "./Migrations/004_ProviderSessionRuntime.ts";
18import Migration0005 from "./Migrations/005_Projections.ts";
19import Migration0006 from "./Migrations/006_ProjectionThreadSessionRuntimeModeColumns.ts";
20import Migration0007 from "./Migrations/007_ProjectionThreadMessageAttachments.ts";
21import Migration0008 from "./Migrations/008_ProjectionThreadActivitySequence.ts";
22import Migration0009 from "./Migrations/009_ProviderSessionRuntimeMode.ts";
23import Migration0010 from "./Migrations/010_ProjectionThreadsRuntimeMode.ts";
24import Migration0011 from "./Migrations/011_OrchestrationThreadCreatedRuntimeMode.ts";
25import Migration0012 from "./Migrations/012_ProjectionThreadsInteractionMode.ts";
26import Migration0013 from "./Migrations/013_ProjectionThreadProposedPlans.ts";
27import Migration0014 from "./Migrations/014_ProjectionThreadProposedPlanImplementation.ts";
28import Migration0015 from "./Migrations/015_ProjectionTurnsSourceProposedPlan.ts";
29import Migration0016 from "./Migrations/016_CanonicalizeModelSelections.ts";
30import Migration0017 from "./Migrations/017_ProjectionThreadsArchivedAt.ts";
31import Migration0018 from "./Migrations/018_ProjectionThreadsArchivedAtIndex.ts";
32import Migration0019 from "./Migrations/019_ProjectionSnapshotLookupIndexes.ts";
33import Migration0020 from "./Migrations/020_AuthAccessManagement.ts";
34import Migration0021 from "./Migrations/021_AuthSessionClientMetadata.ts";
35import Migration0022 from "./Migrations/022_AuthSessionLastConnectedAt.ts";
36import Migration0023 from "./Migrations/023_ProjectionThreadShellSummary.ts";
37import Migration0024 from "./Migrations/024_BackfillProjectionThreadShellSummary.ts";
38import Migration0025 from "./Migrations/025_CleanupInvalidProjectionPendingApprovals.ts";
39import Migration0026 from "./Migrations/026_CanonicalizeModelSelectionOptions.ts";
40import Migration0027 from "./Migrations/027_ProviderSessionRuntimeInstanceId.ts";
41import Migration0028 from "./Migrations/028_ProjectionThreadSessionInstanceId.ts";
42import Migration0029 from "./Migrations/029_ProjectionThreadDetailOrderingIndexes.ts";
43import Migration0030 from "./Migrations/030_ProjectionThreadShellArchiveIndexes.ts";
44import Migration0031 from "./Migrations/031_AuthAuthorizationScopes.ts";
45import Migration0032 from "./Migrations/032_AuthPairingProofKeyThumbprint.ts";
46import Migration0033 from "./Migrations/033_ProjectionThreadsSettled.ts";
47import Migration0034 from "./Migrations/034_ProjectionThreadsSnoozed.ts";
48import Migration0035 from "./Migrations/035_ProjectionThreadTitleRegeneration.ts";
49import Migration0036 from "./Migrations/036_ProjectionThreadsPinned.ts";
50import Migration0037 from "./Migrations/037_ProjectionTurnsKeysetIndex.ts";
51import Migration0038 from "./Migrations/038_ProjectionThreadsPinOrderKey.ts";
52import Migration0039 from "./Migrations/039_ProjectionProjectsDefaultThreadEnvMode.ts";
53import Migration0040 from "./Migrations/040_ProjectionProjectFaviconPath.ts";
54import Migration0041 from "./Migrations/041_AuthSessionClientConnection.ts";
55import Migration0042 from "./Migrations/042_ProjectionThreadLinkedPullRequest.ts";
56import Migration0043 from "./Migrations/043_ProjectionThreadsUnsettledAt.ts";
57import Migration0044 from "./Migrations/044_ClearAutomaticProjectModelDefaults.ts";
58import Migration0045 from "./Migrations/045_ProjectionProjectsAutoPull.ts";
59import Migration0046 from "./Migrations/046_RepairAutomaticSettlementTimestamps.ts";
60import Migration0047 from "./Migrations/047_ProjectionProjectIcon.ts";
61import Migration0048 from "./Migrations/048_ProjectionThreadBranchPullRequest.ts";
62import Migration0049 from "./Migrations/049_ProjectionThreadsActiveOrderKey.ts";
63import Migration0050 from "./Migrations/050_ProjectionThreadPullRequests.ts";
64import Migration0051 from "./Migrations/051_ProjectionThreadMessageContext.ts";
65import Migration0052 from "./Migrations/052_ProjectionThreadTitleState.ts";
66import Migration0053 from "./Migrations/053_PullRequestFilesViewed.ts";
67import Migration0054 from "./Migrations/054_ProjectionThreadsAutoSettleDisabledAt.ts";
68import Migration0055 from "./Migrations/055_OrchestrationV2.ts";
69import Migration0056 from "./Migrations/056_RemoveRedundantProjectionIndexes.ts";
70import Migration0057 from "./Migrations/057_ScheduledTaskWebhooks.ts";
71import Migration0058 from "./Migrations/058_WebhookRelayDeliveries.ts";
72import Migration0059 from "./Migrations/059_McpAppModelContext.ts";
73import Migration0060 from "./Migrations/060_ThreadSnapshotWindowIndexes.ts";
74import Migration0061 from "./Migrations/061_PullRequestReviewGuides.ts";
75import Migration0062 from "./Migrations/062_ThreadFailureLookupIndex.ts";
76import Migration0063 from "./Migrations/063_DropUnusedV1Projections.ts";
77import Migration0064 from "./Migrations/064_CanonicalizeThreadPullRequestLinks.ts";
78import Migration0065 from "./Migrations/065_CodexUsageNativeTurnIndex.ts";
79import Migration0066 from "./Migrations/066_RepairClientSettlementTimestamps.ts";
80import Migration0067 from "./Migrations/067_WebhookDedupe.ts";
81import Migration0068 from "./Migrations/068_ShellStopRequestIndex.ts";
82import Migration0069 from "./Migrations/069_ThreadMessageSearch.ts";
83import Migration0070 from "./Migrations/070_PeerLinks.ts";
84import Migration0071 from "./Migrations/071_PeerLinkFence.ts";
85import Migration0072 from "./Migrations/072_WaitingLinkRequestIndex.ts";
86import Migration0073 from "./Migrations/073_ActiveTurnItemIndexes.ts";
87import Migration0074 from "./Migrations/074_ExcludeAttachmentPlaceholdersFromSearch.ts";
88import Migration0075 from "./Migrations/075_SubagentDeliveryState.ts";
89import Migration0076 from "./Migrations/076_ProjectionProjectsPinArchive.ts";
90import Migration0077 from "./Migrations/077_RepairBooleanSettledOverride.ts";
91import Migration0078 from "./Migrations/078_DropOrchestrationEventCorrelationIndex.ts";
92import Migration0079 from "./Migrations/079_DelegatedRecoveryIndexes.ts";
93import Migration0080 from "./Migrations/080_ScheduledTaskThreadMode.ts";
94import Migration0081 from "./Migrations/081_ProjectionMessageSearchText.ts";
95import Migration0082 from "./Migrations/082_TurnItemConversationIndex.ts";
96import Migration0083 from "./Migrations/083_CommandReadIndexes.ts";
97import Migration0084 from "./Migrations/084_LastExecutedRunIndex.ts";
98import Migration0085 from "./Migrations/085_TurnItemCounts.ts";
99import Migration0086 from "./Migrations/086_QueuedTurnInputIndex.ts";
100import Migration0087 from "./Migrations/087_ProjectionProjectsCustomTitle.ts";
101import Migration0088 from "./Migrations/088_TurnItemTypeStatusIndex.ts";
102import Migration0089 from "./Migrations/089_ShellThreadReadIndexes.ts";
103import Migration0090 from "./Migrations/090_AuthConnectDevices.ts";
104import Migration0091 from "./Migrations/091_AuthConnectDeniedRequests.ts";
105import Migration0092 from "./Migrations/092_QueuedTurnInputIndexJsonValid.ts";
106import Migration0093 from "./Migrations/093_ProviderTurnAttemptIndex.ts";
107import Migration0094 from "./Migrations/094_TurnItemMessageOrdinalIndex.ts";
108import Migration0095 from "./Migrations/095_TurnItemInlineWorkOutput.ts";
109import Migration0096 from "./Migrations/096_RepairStaleTitleRegeneration.ts";
110import Migration0097 from "./Migrations/097_IssueTrackerBindings.ts";
111import Migration0098 from "./Migrations/098_ActiveShellIndexIndexes.ts";
112import Migration0099 from "./Migrations/099_BackgroundRecoveryIndexes.ts";
113import Migration0100 from "./Migrations/100_TurnStartReadIndexes.ts";
114import Migration0101 from "./Migrations/101_DelegatedTaskReadIndexes.ts";
115import Migration0102 from "./Migrations/102_ThreadItemCounts.ts";
116import Migration0103 from "./Migrations/103_IssueTrackerAdditionalScopes.ts";
117import Migration0104 from "./Migrations/104_ProjectionProjectsTrackedFolders.ts";
118import Migration0105 from "./Migrations/105_TaskFolders.ts";
119import Migration0106 from "./Migrations/106_WorktreePathKeyIndex.ts";
120import Migration0107 from "./Migrations/107_DeferredSlashCommandIndex.ts";
121import Migration0108 from "./Migrations/108_AgentFeedback.ts";
122import Migration0109 from "./Migrations/109_IssueTrackerAccounts.ts";
123import Migration0110 from "./Migrations/110_Workflows.ts";
124import Migration0111 from "./Migrations/111_SupersededRunAttemptIndex.ts";
125import Migration0112 from "./Migrations/112_LayoutCommandApprovals.ts";
126import Migration0113 from "./Migrations/113_WorkflowSkippedRuns.ts";
127import Migration0114 from "./Migrations/114_WorkflowRunIndexes.ts";
128import Migration0115 from "./Migrations/115_WorkflowRunTags.ts";
129import Migration0116 from "./Migrations/116_ForkHistoryMembership.ts";
130import Migration0117 from "./Migrations/117_WorkflowMailSender.ts";
131import Migration0118 from "./Migrations/118_WorkflowPools.ts";
132import Migration0119 from "./Migrations/119_WorkflowRunSubject.ts";
133import Migration0120 from "./Migrations/120_PeerLinkReachabilityErrors.ts";
134import Migration0121 from "./Migrations/121_AgentFeedbackErrorCode.ts";
135import Migration0122 from "./Migrations/122_WorkflowOpenedRunReceipts.ts";
136import Migration0123 from "./Migrations/123_WorkflowRunTagIndex.ts";
137import Migration0124 from "./Migrations/124_PullRequestThreadIndex.ts";
138import Migration0125 from "./Migrations/125_WorkflowRunReferenceLookup.ts";
139import Migration0126 from "./Migrations/126_ScheduledTaskPendingOutcome.ts";
140import Migration0127 from "./Migrations/127_ScheduledRunPromptIndex.ts";
141
142const migrationEntries = [
143 [1, "OrchestrationEvents", Migration0001],
144 [2, "OrchestrationCommandReceipts", Migration0002],
145 [3, "CheckpointDiffBlobs", Migration0003],
146 [4, "ProviderSessionRuntime", Migration0004],
147 [5, "Projections", Migration0005],
148 [6, "ProjectionThreadSessionRuntimeModeColumns", Migration0006],
149 [7, "ProjectionThreadMessageAttachments", Migration0007],
150 [8, "ProjectionThreadActivitySequence", Migration0008],
151 [9, "ProviderSessionRuntimeMode", Migration0009],
152 [10, "ProjectionThreadsRuntimeMode", Migration0010],
153 [11, "OrchestrationThreadCreatedRuntimeMode", Migration0011],
154 [12, "ProjectionThreadsInteractionMode", Migration0012],
155 [13, "ProjectionThreadProposedPlans", Migration0013],
156 [14, "ProjectionThreadProposedPlanImplementation", Migration0014],
157 [15, "ProjectionTurnsSourceProposedPlan", Migration0015],
158 [16, "CanonicalizeModelSelections", Migration0016],
159 [17, "ProjectionThreadsArchivedAt", Migration0017],
160 [18, "ProjectionThreadsArchivedAtIndex", Migration0018],
161 [19, "ProjectionSnapshotLookupIndexes", Migration0019],
162 [20, "AuthAccessManagement", Migration0020],
163 [21, "AuthSessionClientMetadata", Migration0021],
164 [22, "AuthSessionLastConnectedAt", Migration0022],
165 [23, "ProjectionThreadShellSummary", Migration0023],
166 [24, "BackfillProjectionThreadShellSummary", Migration0024],
167 [25, "CleanupInvalidProjectionPendingApprovals", Migration0025],
168 [26, "CanonicalizeModelSelectionOptions", Migration0026],
169 [27, "ProviderSessionRuntimeInstanceId", Migration0027],
170 [28, "ProjectionThreadSessionInstanceId", Migration0028],
171 [29, "ProjectionThreadDetailOrderingIndexes", Migration0029],
172 [30, "ProjectionThreadShellArchiveIndexes", Migration0030],
173 [31, "AuthAuthorizationScopes", Migration0031],
174 [32, "AuthPairingProofKeyThumbprint", Migration0032],
175 [33, "ProjectionThreadsSettled", Migration0033],
176 [34, "ProjectionThreadsSnoozed", Migration0034],
177 [35, "ProjectionThreadTitleRegeneration", Migration0035],
178 [36, "ProjectionThreadsPinned", Migration0036],
179 [37, "ProjectionTurnsKeysetIndex", Migration0037],
180 [38, "ProjectionThreadsPinOrderKey", Migration0038],
181 [39, "ProjectionProjectsDefaultThreadEnvMode", Migration0039],
182 [40, "ProjectionProjectFaviconPath", Migration0040],
183 [41, "AuthSessionClientConnection", Migration0041],
184 [42, "ProjectionThreadLinkedPullRequest", Migration0042],
185 [43, "ProjectionThreadsUnsettledAt", Migration0043],
186 [44, "ClearAutomaticProjectModelDefaults", Migration0044],
187 [45, "ProjectionProjectsAutoPull", Migration0045],
188 [46, "RepairAutomaticSettlementTimestamps", Migration0046],
189 [47, "ProjectionProjectIcon", Migration0047],
190 [48, "ProjectionThreadBranchPullRequest", Migration0048],
191 [49, "ProjectionThreadsActiveOrderKey", Migration0049],
192 [50, "ProjectionThreadPullRequests", Migration0050],
193 [51, "ProjectionThreadMessageContext", Migration0051],
194 [52, "ProjectionThreadTitleState", Migration0052],
195 [53, "PullRequestFilesViewed", Migration0053],
196 [54, "ProjectionThreadsAutoSettleDisabledAt", Migration0054],
197 // Preserve this migration's schema. Future V2 schema changes need new migrations.
198 [55, "OrchestrationV2", Migration0055],
199 [56, "RemoveRedundantProjectionIndexes", Migration0056],
200 [57, "ScheduledTaskWebhooks", Migration0057],
201 [58, "WebhookRelayDeliveries", Migration0058],
202 [59, "McpAppModelContext", Migration0059],
203 [60, "ThreadSnapshotWindowIndexes", Migration0060],
204 [61, "PullRequestReviewGuides", Migration0061],
205 [62, "ThreadFailureLookupIndex", Migration0062],
206 [63, "DropUnusedV1Projections", Migration0063],
207 [64, "CanonicalizeThreadPullRequestLinks", Migration0064],
208 [65, "CodexUsageNativeTurnIndex", Migration0065],
209 [66, "RepairClientSettlementTimestamps", Migration0066],
210 [67, "WebhookDedupe", Migration0067],
211 [68, "ShellStopRequestIndex", Migration0068],
212 [69, "ThreadMessageSearch", Migration0069],
213 [70, "PeerLinks", Migration0070],
214 [71, "PeerLinkFence", Migration0071],
215 [72, "WaitingLinkRequestIndex", Migration0072],
216 [73, "ActiveTurnItemIndexes", Migration0073],
217 [74, "ExcludeAttachmentPlaceholdersFromSearch", Migration0074],
218 [75, "SubagentDeliveryState", Migration0075],
219 [76, "ProjectionProjectsPinArchive", Migration0076],
220 [77, "RepairBooleanSettledOverride", Migration0077],
221 [78, "DropOrchestrationEventCorrelationIndex", Migration0078],
222 [79, "DelegatedRecoveryIndexes", Migration0079],
223 [80, "ScheduledTaskThreadMode", Migration0080],
224 [81, "ProjectionMessageSearchText", Migration0081],
225 [82, "TurnItemConversationIndex", Migration0082],
226 [83, "CommandReadIndexes", Migration0083],
227 [84, "LastExecutedRunIndex", Migration0084],
228 [85, "TurnItemCounts", Migration0085],
229 [86, "QueuedTurnInputIndex", Migration0086],
230 [87, "ProjectionProjectsCustomTitle", Migration0087],
231 [88, "TurnItemTypeStatusIndex", Migration0088],
232 [89, "ShellThreadReadIndexes", Migration0089],
233 [90, "AuthConnectDevices", Migration0090],
234 [91, "AuthConnectDeniedRequests", Migration0091],
235 [92, "QueuedTurnInputIndexJsonValid", Migration0092],
236 [93, "ProviderTurnAttemptIndex", Migration0093],
237 [94, "TurnItemMessageOrdinalIndex", Migration0094],
238 [95, "TurnItemInlineWorkOutput", Migration0095],
239 [96, "RepairStaleTitleRegeneration", Migration0096],
240 [97, "IssueTrackerBindings", Migration0097],
241 [98, "ActiveShellIndexIndexes", Migration0098],
242 [99, "BackgroundRecoveryIndexes", Migration0099],
243 [100, "TurnStartReadIndexes", Migration0100],
244 [101, "DelegatedTaskReadIndexes", Migration0101],
245 [102, "ThreadItemCounts", Migration0102],
246 [103, "IssueTrackerAdditionalScopes", Migration0103],
247 [104, "ProjectionProjectsTrackedFolders", Migration0104],
248 [105, "TaskFolders", Migration0105],
249 [106, "WorktreePathKeyIndex", Migration0106],
250 [107, "DeferredSlashCommandIndex", Migration0107],
251 [108, "AgentFeedback", Migration0108],
252 [109, "IssueTrackerAccounts", Migration0109],
253 [110, "Workflows", Migration0110],
254 [111, "SupersededRunAttemptIndex", Migration0111],
255 [112, "LayoutCommandApprovals", Migration0112],
256 [113, "WorkflowSkippedRuns", Migration0113],
257 [114, "WorkflowRunIndexes", Migration0114],
258 [115, "WorkflowRunTags", Migration0115],
259 [116, "ForkHistoryMembership", Migration0116],
260 [117, "WorkflowMailSender", Migration0117],
261 [118, "WorkflowPools", Migration0118],
262 [119, "WorkflowRunSubject", Migration0119],
263 [120, "PeerLinkReachabilityErrors", Migration0120],
264 [121, "AgentFeedbackErrorCode", Migration0121],
265 [122, "WorkflowOpenedRunReceipts", Migration0122],
266 [123, "WorkflowRunTagIndex", Migration0123],
267 [124, "PullRequestThreadIndex", Migration0124],
268 [125, "WorkflowRunReferenceLookup", Migration0125],
269 [126, "ScheduledTaskPendingOutcome", Migration0126],
270 [127, "ScheduledRunPromptIndex", Migration0127],
271] as const;
272
273export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const);
274
275const makeMigrationLoader = (throughId?: number) =>
276 Migrator.fromRecord(
277 Object.fromEntries(
278 migrationEntries
279 .filter(([id]) => throughId === undefined || id <= throughId)
280 .map(([id, name, migration]) => [`${id}_${name}`, migration]),
281 ),
282 );
283
284const FIRST_V2_MIGRATION_ID = 55;
285
286export function skippedV2Migrations(
287 recorded: ReadonlyArray<{ readonly id: number; readonly name: string }>,
288 throughId?: number,
289): string[] {
290 const latestRecordedId = Math.max(0, ...recorded.map((row) => row.id));
291 const recordedNames = new Map(recorded.map((row) => [row.id, row.name]));
292 return migrationManifest.flatMap(([id, name]) => {
293 if (
294 id < FIRST_V2_MIGRATION_ID ||
295 id > latestRecordedId ||
296 (throughId !== undefined && id > throughId)
297 )
298 return [];
299 const recordedName = recordedNames.get(id);
300 return recordedName === name ? [] : [`${id}_${name} (recorded: ${recordedName ?? "nothing"})`];
301 });
302}
303
304// Migrators skip ids up to the highest recorded; reject collisions that would skip V2 schema.
305const assertV2MigrationsCanRun = Effect.fn("assertV2MigrationsCanRun")(function* (
306 throughId?: number,
307) {
308 const sql = yield* SqlClient.SqlClient;
309 const tables = yield* sql`
310 SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'effect_sql_migrations'
311 `;
312 if (tables.length === 0) return;
313 const recorded = yield* sql<{
314 readonly migration_id: number;
315 readonly name: string;
316 }>`SELECT migration_id, name FROM effect_sql_migrations`;
317 const skipped = skippedV2Migrations(
318 recorded.map((row) => ({ id: row.migration_id, name: row.name })),
319 throughId,
320 );
321 const latestRecordedId = Math.max(0, ...recorded.map((row) => row.migration_id));
322 if (skipped.length === 0) return;
323 return yield* new Migrator.MigrationError({
324 kind: "BadState",
325 message: `This database's migration history would skip required schema migrations: ${skipped.join(", ")}. The migrator skips every id up to the highest recorded id (${latestRecordedId}), regardless of name. It was probably written by a different build. Start the build that wrote it, or report this migration history so an upgrade path can be added.`,
326 });
327});
328
329const latestMigrationId = Math.max(...migrationEntries.map(([id]) => id));
330
331// Mirrors the Migrator, which runs only ids above the highest recorded, plus the V2-preview reconciliation.
332export const hasPendingMigrations = Effect.fn("hasPendingMigrations")(function* () {
333 const sql = yield* SqlClient.SqlClient;
334 const tables = yield* sql`
335 SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'effect_sql_migrations'
336 `;
337 if (tables.length === 0) return true;
338 const rows = yield* sql<{ readonly latestId: number | null; readonly previewRows: number }>`
339 SELECT
340 MAX(migration_id) AS latestId,
341 SUM(name = 'OrchestrationV2' AND migration_id IN (53, 54)) AS previewRows
342 FROM effect_sql_migrations
343 `;
344 const row = rows[0];
345 return (row?.latestId ?? 0) < latestMigrationId || (row?.previewRows ?? 0) > 0;
346});
347
348const run = Migrator.make({});
349
350export interface RunMigrationsOptions {
351 readonly toMigrationInclusive?: number | undefined;
352}
353
354export const runMigrations = Effect.fn("runMigrations")(function* ({
355 toMigrationInclusive,
356}: RunMigrationsOptions = {}) {
357 const progress = yield* Effect.serviceOption(DatabaseMigrationProgress.DatabaseMigrationProgress);
358 // The desktop waits past its readiness budget until the finished line follows this one.
359 const hasPending = yield* hasPendingMigrations();
360 if (hasPending) yield* Effect.log(DATABASE_MIGRATIONS_STARTED_MESSAGE);
361 const includesV2 =
362 toMigrationInclusive === undefined || toMigrationInclusive >= FIRST_V2_MIGRATION_ID;
363 // The reconcile takes the write lock; CLI startup must not contend with the server for a no-op.
364 const previewMigrations = includesV2 && hasPending ? yield* reconcileV2PreviewMigration() : [];
365 if (includesV2) {
366 yield* assertV2MigrationsCanRun(toMigrationInclusive);
367 }
368 const sql = yield* SqlClient.SqlClient;
369 const ledger = yield* sql`
370 SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'effect_sql_migrations'
371 `;
372 const [latest] =
373 ledger.length === 0
374 ? []
375 : yield* sql<{
376 readonly id: number | null;
377 }>`SELECT MAX(migration_id) AS id FROM effect_sql_migrations`;
378 const latestRecordedId = latest?.id ?? 0;
379 const pending = migrationEntries.filter(
380 ([id]) =>
381 id > latestRecordedId && (toMigrationInclusive === undefined || id <= toMigrationInclusive),
382 );
383 // One transaction per migration: an index build on a large database can take minutes, and a
384 // restart then resumes after the last finished migration instead of rolling all of them back.
385 const executedMigrations: Array<readonly [id: number, name: string]> = [...previewMigrations];
386 yield* Effect.gen(function* () {
387 for (const [index, [id, name]] of pending.entries()) {
388 if (Option.isSome(progress)) {
389 yield* Ref.set(progress.value.current, { current: index + 1, total: pending.length });
390 }
391 if (latestRecordedId > 0) {
392 yield* Effect.log(
393 `${DATABASE_MIGRATION_PROGRESS_MESSAGE} (${index + 1} of ${pending.length})`,
394 ).pipe(
395 Effect.annotateLogs({
396 migration: `${id}_${name}`,
397 progress: `${index + 1} of ${pending.length}`,
398 }),
399 );
400 }
401 executedMigrations.push(...(yield* run({ loader: makeMigrationLoader(id) })));
402 }
403 }).pipe(
404 Effect.ensuring(Option.isSome(progress) ? Ref.set(progress.value.current, null) : Effect.void),
405 );
406 const migrations = executedMigrations.map(([id, name]) => `${id}_${name}`);
407 yield* migrations.length === 0
408 ? Effect.logDebug("Database schema is current")
409 : Effect.log(DATABASE_MIGRATIONS_FINISHED_MESSAGE).pipe(Effect.annotateLogs({ migrations }));
410
411 const recorded = yield* sql<{
412 readonly migration_id: number;
413 readonly name: string;
414 }>`SELECT migration_id, name FROM effect_sql_migrations`;
415 const manifestNames = new Map<number, string>(migrationEntries.map(([id, name]) => [id, name]));
416 const divergent = recorded.flatMap((row) => {
417 const expected = manifestNames.get(row.migration_id);
418 if (expected === undefined) {
419 return [`${row.migration_id}:${row.name} (unknown to this build)`];
420 }
421 return expected === row.name
422 ? []
423 : [`${row.migration_id}:${row.name} (this build: ${expected})`];
424 });
425 if (divergent.length > 0) {
426 yield* Effect.logWarning(
427 "Database migration history diverges from this build; recorded migration ids are skipped, not reconciled by name.",
428 ).pipe(Effect.annotateLogs({ divergent }));
429 }
430 return executedMigrations;
431});