From b58cfefa13d30379293cd880892e3b3cdf9617ce Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 3 Oct 2017 08:40:44 +0200 Subject: [PATCH] Refactor database setup sample code so that database migrator can be tested --- .../GRDBDemoiOS.xcodeproj/project.pbxproj | 23 ++++++-- .../GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift | 57 +++++++++++++++++++ .../GRDBDemoiOS/GRDBDemoiOS/AppDelegate.swift | 14 +++++ .../GRDBDemoiOS/GRDBDemoiOS/Database.swift | 56 ------------------ README.md | 6 +- 5 files changed, 93 insertions(+), 63 deletions(-) create mode 100644 DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift delete mode 100644 DemoApps/GRDBDemoiOS/GRDBDemoiOS/Database.swift diff --git a/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/project.pbxproj b/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/project.pbxproj index 981a3b431..c4acc4319 100644 --- a/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/project.pbxproj +++ b/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/project.pbxproj @@ -20,7 +20,7 @@ 56B0360C1E8D9EBE003B6DA4 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 56B0360A1E8D9EBE003B6DA4 /* Main.storyboard */; }; 56B0360E1E8D9EBE003B6DA4 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 56B0360D1E8D9EBE003B6DA4 /* Assets.xcassets */; }; 56B036111E8D9EBE003B6DA4 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 56B0360F1E8D9EBE003B6DA4 /* LaunchScreen.storyboard */; }; - 56B0361B1E8D9F38003B6DA4 /* Database.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B036191E8D9F38003B6DA4 /* Database.swift */; }; + 56B0361B1E8D9F38003B6DA4 /* AppDatabase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B036191E8D9F38003B6DA4 /* AppDatabase.swift */; }; 56B0361C1E8D9F38003B6DA4 /* Person.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B0361A1E8D9F38003B6DA4 /* Person.swift */; }; 56B036221E8D9F4C003B6DA4 /* DemoViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B0361E1E8D9F4C003B6DA4 /* DemoViewController.swift */; }; 56B036231E8D9F4C003B6DA4 /* PersonEditionViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B0361F1E8D9F4C003B6DA4 /* PersonEditionViewController.swift */; }; @@ -31,6 +31,13 @@ /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ + 563BD2F01F8364C1006A5390 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 56439B501F4CA1DC0066043F; + remoteInfo = GRDBOSXPerformanceComparisonTests; + }; 568E5FCD1E926430002582E0 /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = 56B035FB1E8D9EBE003B6DA4 /* Project object */; @@ -257,7 +264,7 @@ 56B0360D1E8D9EBE003B6DA4 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; 56B036101E8D9EBE003B6DA4 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; 56B036121E8D9EBE003B6DA4 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; - 56B036191E8D9F38003B6DA4 /* Database.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Database.swift; sourceTree = ""; }; + 56B036191E8D9F38003B6DA4 /* AppDatabase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDatabase.swift; sourceTree = ""; }; 56B0361A1E8D9F38003B6DA4 /* Person.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Person.swift; sourceTree = ""; }; 56B0361E1E8D9F4C003B6DA4 /* DemoViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DemoViewController.swift; sourceTree = ""; }; 56B0361F1E8D9F4C003B6DA4 /* PersonEditionViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PersonEditionViewController.swift; sourceTree = ""; }; @@ -332,7 +339,7 @@ isa = PBXGroup; children = ( 56B036061E8D9EBE003B6DA4 /* AppDelegate.swift */, - 56B036191E8D9F38003B6DA4 /* Database.swift */, + 56B036191E8D9F38003B6DA4 /* AppDatabase.swift */, 56B0361A1E8D9F38003B6DA4 /* Person.swift */, 56B0361D1E8D9F3D003B6DA4 /* Controllers */, 56B0360A1E8D9EBE003B6DA4 /* Main.storyboard */, @@ -360,6 +367,7 @@ 56B0363B1E8D9F79003B6DA4 /* GRDB.framework */, 56B0363D1E8D9F79003B6DA4 /* GRDBOSXTests.xctest */, 56B0363F1E8D9F79003B6DA4 /* GRDBOSXPerformanceTests.xctest */, + 563BD2F11F8364C1006A5390 /* GRDBOSXPerformanceComparisonTests.xctest */, 56B036411E8D9F79003B6DA4 /* GRDBOSXCrashTests.xctest */, 56B036431E8D9F79003B6DA4 /* GRDBCipher.framework */, 56B036451E8D9F79003B6DA4 /* GRDBCipherOSXTests.xctest */, @@ -494,6 +502,13 @@ /* End PBXProject section */ /* Begin PBXReferenceProxy section */ + 563BD2F11F8364C1006A5390 /* GRDBOSXPerformanceComparisonTests.xctest */ = { + isa = PBXReferenceProxy; + fileType = wrapper.cfbundle; + path = GRDBOSXPerformanceComparisonTests.xctest; + remoteRef = 563BD2F01F8364C1006A5390 /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; 56B0363B1E8D9F79003B6DA4 /* GRDB.framework */ = { isa = PBXReferenceProxy; fileType = wrapper.framework; @@ -660,7 +675,7 @@ buildActionMask = 2147483647; files = ( 56B0361C1E8D9F38003B6DA4 /* Person.swift in Sources */, - 56B0361B1E8D9F38003B6DA4 /* Database.swift in Sources */, + 56B0361B1E8D9F38003B6DA4 /* AppDatabase.swift in Sources */, 56B036071E8D9EBE003B6DA4 /* AppDelegate.swift in Sources */, 56B036241E8D9F4C003B6DA4 /* PersonsViewController.swift in Sources */, 56B036231E8D9F4C003B6DA4 /* PersonEditionViewController.swift in Sources */, diff --git a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift new file mode 100644 index 000000000..aa51dbb34 --- /dev/null +++ b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift @@ -0,0 +1,57 @@ +import GRDB + +/// A type responsible for initializing the application database. +/// +/// See AppDelegate.setupDatabase() +struct AppDatabase { + + /// Creates a fully initialized database at path + static func openDatabase(atPath path: String) throws -> DatabaseQueue { + // Connect to the database + // See https://github.com/groue/GRDB.swift/#database-connections + dbQueue = try DatabaseQueue(path: path) + + // Use DatabaseMigrator to define the database schema + // See https://github.com/groue/GRDB.swift/#migrations + try migrator.migrate(dbQueue) + + return dbQueue + } + + /// The DatabaseMigrator that defines the database schema. + /// + /// This migrator is exposed so that migrations can be tested. + // See https://github.com/groue/GRDB.swift/#migrations + static var migrator: DatabaseMigrator { + var migrator = DatabaseMigrator() + + migrator.registerMigration("createPersons") { db in + // Create a table + // See https://github.com/groue/GRDB.swift#create-tables + try db.create(table: "persons") { t in + // An integer primary key auto-generates unique IDs + t.column("id", .integer).primaryKey() + + // Sort person names in a localized case insensitive fashion by default + // See https://github.com/groue/GRDB.swift/#unicode + t.column("name", .text).notNull().collate(.localizedCaseInsensitiveCompare) + + t.column("score", .integer).notNull() + } + } + + migrator.registerMigration("fixtures") { db in + // Populate the persons table with random data + for _ in 0..<8 { + try Person(name: Person.randomName(), score: Person.randomScore()).insert(db) + } + } + +// // Migrations for future application versions will be inserted here: +// migrator.registerMigration(...) { db in +// ... +// } + + return migrator + } +} diff --git a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDelegate.swift b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDelegate.swift index 996df925e..b73de43d2 100644 --- a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDelegate.swift +++ b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDelegate.swift @@ -1,4 +1,8 @@ import UIKit +import GRDB + +// The shared database queue +var dbQueue: DatabaseQueue! @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { @@ -8,4 +12,14 @@ class AppDelegate: UIResponder, UIApplicationDelegate { try! setupDatabase(application) return true } + + private func setupDatabase(_ application: UIApplication) throws { + let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! as NSString + let databasePath = documentsPath.appendingPathComponent("db.sqlite") + dbQueue = try AppDatabase.openDatabase(atPath: databasePath) + + // Be a nice iOS citizen, and don't consume too much memory + // See https://github.com/groue/GRDB.swift/#memory-management + dbQueue.setupMemoryManagement(in: application) + } } diff --git a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Database.swift b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Database.swift deleted file mode 100644 index 83f2c1216..000000000 --- a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Database.swift +++ /dev/null @@ -1,56 +0,0 @@ -import GRDB -import UIKit - -// The shared database queue -var dbQueue: DatabaseQueue! - -func setupDatabase(_ application: UIApplication) throws { - - // Connect to the database - // See https://github.com/groue/GRDB.swift/#database-connections - - let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! as NSString - let databasePath = documentsPath.appendingPathComponent("db.sqlite") - dbQueue = try DatabaseQueue(path: databasePath) - - - // Be a nice iOS citizen, and don't consume too much memory - // See https://github.com/groue/GRDB.swift/#memory-management - - dbQueue.setupMemoryManagement(in: application) - - - // Use DatabaseMigrator to setup the database - // See https://github.com/groue/GRDB.swift/#migrations - - var migrator = DatabaseMigrator() - - migrator.registerMigration("createPersons") { db in - - // Create a table - // See https://github.com/groue/GRDB.swift#create-tables - - try db.create(table: "persons") { t in - // An integer primary key auto-generates unique IDs - t.column("id", .integer).primaryKey() - - // Sort person names in a localized case insensitive fashion by default - // See https://github.com/groue/GRDB.swift/#unicode - t.column("name", .text).notNull().collate(.localizedCaseInsensitiveCompare) - - t.column("score", .integer).notNull() - } - - // Populate the persons table with random data - for _ in 0..<8 { - try Person(name: Person.randomName(), score: Person.randomScore()).insert(db) - } - } - -// // Migrations for future application versions will be inserted here: -// migrator.registerMigration(...) { db in -// ... -// } - - try migrator.migrate(dbQueue) -} diff --git a/README.md b/README.md index 65aae47c3..61545c763 100644 --- a/README.md +++ b/README.md @@ -363,7 +363,7 @@ let placeCount = try dbQueue.inDatabase { db in **A database queue needs your application to follow rules in order to deliver its safety guarantees.** Please refer to the [Concurrency](#concurrency) chapter. -See [DemoApps/GRDBDemoiOS/Database.swift](DemoApps/GRDBDemoiOS/GRDBDemoiOS/Database.swift) for a sample code that sets up a database queue on iOS. +See [DemoApps/GRDBDemoiOS/AppDatabase.swift](DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift) for a sample code that sets up a database queue on iOS. ### DatabaseQueue Configuration @@ -443,7 +443,7 @@ Database pools allow several threads to access the database at the same time: See [Advanced DatabasePool](#advanced-databasepool) for more DatabasePool hotness. -For a sample code that sets up a database pool on iOS, see [DemoApps/GRDBDemoiOS/Database.swift](DemoApps/GRDBDemoiOS/GRDBDemoiOS/Database.swift), and replace DatabaseQueue with DatabasePool. +For a sample code that sets up a database pool on iOS, see [DemoApps/GRDBDemoiOS/AppDatabase.swift](DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift), and replace DatabaseQueue with DatabasePool. ### DatabasePool Configuration @@ -5552,7 +5552,7 @@ Those guarantees hold as long as you follow three rules: This means that opening a new connection each time you access the database is probably a very bad idea. Do share a single connection instead. - See, for example, [DemoApps/GRDBDemoiOS/Database.swift](DemoApps/GRDBDemoiOS/GRDBDemoiOS/Database.swift) for a sample code that properly sets up a single database queue that is available throughout the application. + See, for example, [DemoApps/GRDBDemoiOS/AppDatabase.swift](DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift) for a sample code that properly sets up a single database queue that is available throughout the application. If there are several instances of database queues or pools that access the same database, a multi-threaded application will eventually face "database is locked" errors. See [Dealing with External Connections](#dealing-with-external-connections).