1 //  Copyright © 2021 650 Industries. All rights reserved.
2 
3 // swiftlint:disable line_length
4 
5 import Foundation
6 import sqlite3
7 
8 internal final class UpdatesDatabaseMigration9To10: UpdatesDatabaseMigration {
9   private(set) var filename: String = "expo-v9.db"
10 
runMigrationnull11   func runMigration(onDatabase db: OpaquePointer) throws {
12     try db.withTransaction { trx in
13       try trx.safeExecOrRollback(sql: """
14         DELETE FROM "updates" WHERE "manifest" IS NULL
15       """)
16     }
17 
18     try db.withForeignKeysOff {
19       try db.withTransaction { trx in
20         try trx.safeExecOrRollback(sql: """
21           CREATE TABLE "new_updates" (
22             "id"  BLOB UNIQUE,
23             "scope_key"  TEXT NOT NULL,
24             "commit_time"  INTEGER NOT NULL,
25             "runtime_version"  TEXT NOT NULL,
26             "launch_asset_id" INTEGER,
27             "manifest"  TEXT NOT NULL,
28             "status"  INTEGER NOT NULL,
29             "keep"  INTEGER NOT NULL,
30             "last_accessed"  INTEGER NOT NULL,
31             "successful_launch_count"  INTEGER NOT NULL DEFAULT 0,
32             "failed_launch_count"  INTEGER NOT NULL DEFAULT 0,
33             PRIMARY KEY("id"),
34             FOREIGN KEY("launch_asset_id") REFERENCES "assets"("id") ON DELETE CASCADE
35           )
36         """)
37 
38         try trx.safeExecOrRollback(sql: "INSERT INTO `new_updates` (`id`, `scope_key`, `commit_time`, `runtime_version`, `launch_asset_id`, `manifest`, `status`, `keep`, `last_accessed`, `successful_launch_count`, `failed_launch_count`) SELECT `id`, `scope_key`, `commit_time`, `runtime_version`, `launch_asset_id`, `manifest`, `status`, `keep`, `last_accessed`, `successful_launch_count`, `failed_launch_count` FROM `updates` WHERE `manifest` IS NOT NULL")
39 
40         try trx.safeExecOrRollback(sql: "DROP TABLE `updates`")
41         try trx.safeExecOrRollback(sql: "ALTER TABLE `new_updates` RENAME TO `updates`")
42         try trx.safeExecOrRollback(sql: """
43           CREATE UNIQUE INDEX "index_updates_scope_key_commit_time" ON "updates" ("scope_key", "commit_time")
44         """)
45         try trx.safeExecOrRollback(sql: """
46           CREATE INDEX "index_updates_launch_asset_id" ON "updates" ("launch_asset_id")
47         """)
48       }
49     }
50   }
51 }
52