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 UpdatesDatabaseMigration6To7: UpdatesDatabaseMigration {
9   private(set) var filename: String = "expo-v6.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             "successful_launch_count"  INTEGER NOT NULL DEFAULT 0,
26             "failed_launch_count"  INTEGER NOT NULL DEFAULT 0,
27             PRIMARY KEY("id"),
28             FOREIGN KEY("launch_asset_id") REFERENCES "assets"("id") ON DELETE CASCADE
29           )
30         """)
31 
32         // insert `1` for successful_launch_count for all existing updates
33         // to make sure we don't roll back past them
34         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`, 1 AS `successful_launch_count`, 0 AS `failed_launch_count` FROM `updates`")
35 
36         try trx.safeExecOrRollback(sql: "DROP TABLE `updates`")
37         try trx.safeExecOrRollback(sql: "ALTER TABLE `new_updates` RENAME TO `updates`")
38         try trx.safeExecOrRollback(sql: """
39           CREATE UNIQUE INDEX "index_updates_scope_key_commit_time" ON "updates" ("scope_key", "commit_time")
40         """)
41         try trx.safeExecOrRollback(sql: """
42           CREATE INDEX "index_updates_launch_asset_id" ON "updates" ("launch_asset_id")
43         """)
44       }
45     }
46   }
47 }
48