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 UpdatesDatabaseMigration5To6: UpdatesDatabaseMigration {
9   private(set) var filename: String = "expo-v5.db"
10 
11   func runMigration(onDatabase db: OpaquePointer) throws {
12     try db.withForeignKeysOff {
13       try db.withTransaction { trx in
14         try trx.safeExecOrRollback(sql: """
15           CREATE TABLE "new_updates" (
16             "id"  BLOB UNIQUE,
17             "scope_key"  TEXT NOT NULL,
18             "commit_time"  INTEGER NOT NULL,
19             "runtime_version"  TEXT NOT NULL,
20             "launch_asset_id" INTEGER,
21             "manifest"  TEXT,
22             "status"  INTEGER NOT NULL,
23             "keep"  INTEGER NOT NULL,
24             "last_accessed"  INTEGER NOT NULL,
25             PRIMARY KEY("id"),
26             FOREIGN KEY("launch_asset_id") REFERENCES "assets"("id") ON DELETE CASCADE
27           )
28         """)
29 
30         // insert current time as lastAccessed date for all existing updates
31         let currentTime = Date().timeIntervalSince1970 * 1000
32         try trx.safeExecOrRollback(
33           sql: "INSERT INTO `new_updates` (`id`, `scope_key`, `commit_time`, `runtime_version`, `launch_asset_id`, `manifest`, `status`, `keep`, `last_accessed`) SELECT `id`, `scope_key`, `commit_time`, `runtime_version`, `launch_asset_id`, `metadata` AS `manifest`, `status`, `keep`, ?1 AS `last_accessed` FROM `updates`",
34           args: [currentTime]
35         )
36 
37         try trx.safeExecOrRollback(sql: "DROP TABLE `updates`")
38         try trx.safeExecOrRollback(sql: "ALTER TABLE `new_updates` RENAME TO `updates`")
39         try trx.safeExecOrRollback(sql: """
40           CREATE UNIQUE INDEX "index_updates_scope_key_commit_time" ON "updates" ("scope_key", "commit_time")
41         """)
42         try trx.safeExecOrRollback(sql: """
43           CREATE INDEX "index_updates_launch_asset_id" ON "updates" ("launch_asset_id")
44         """)
45       }
46     }
47   }
48 }
49