├── .gitignore ├── LICENSE ├── README.markdown ├── SMSQLiteMigration.xcodeproj ├── project.pbxproj └── project.xcworkspace │ └── contents.xcworkspacedata ├── SMSQLiteMigration ├── AppDelegate.h ├── AppDelegate.m ├── Assets.xcassets │ └── AppIcon.appiconset │ │ └── Contents.json ├── Base.lproj │ ├── LaunchScreen.storyboard │ └── Main.storyboard ├── DBMigration │ ├── Private │ │ ├── SMSQLiteMigrationColumn.h │ │ ├── SMSQLiteMigrationColumn.m │ │ ├── SMSQLiteMigrationContent.h │ │ ├── SMSQLiteMigrationContent.m │ │ ├── SMSQLiteMigrationIndex.h │ │ ├── SMSQLiteMigrationIndex.m │ │ ├── SMSQLiteMigrationTable.h │ │ ├── SMSQLiteMigrationTable.m │ │ ├── SMSQLiteMigrationTableTuple.h │ │ └── SMSQLiteMigrationTableTuple.m │ ├── SMSQLiteMigration.h │ └── SMSQLiteMigration.m ├── FMDatabase │ ├── FMDB.h │ ├── FMDatabase.h │ ├── FMDatabase.m │ ├── FMDatabaseAdditions.h │ ├── FMDatabaseAdditions.m │ ├── FMDatabasePool.h │ ├── FMDatabasePool.m │ ├── FMDatabaseQueue.h │ ├── FMDatabaseQueue.m │ ├── FMResultSet.h │ └── FMResultSet.m ├── Info.plist ├── TestDB.sqlite ├── TestDB_AddColumn.sqlite ├── TestDB_AddIndex.sqlite ├── TestDB_AddTable.sqlite ├── TestDB_DeleteIndex.sqlite ├── TestDB_DeleteTable.sqlite ├── TestDB_RenameTabel.sqlite ├── ViewController.h ├── ViewController.m └── main.m └── SMSQLiteMigrationTests ├── Info.plist └── SMSQLiteMigrationTests.m /.gitignore: -------------------------------------------------------------------------------- 1 | # Xcode 2 | # 3 | # gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore 4 | 5 | ## Build generated 6 | build/ 7 | DerivedData/ 8 | 9 | ## Various settings 10 | *.pbxuser 11 | !default.pbxuser 12 | *.mode1v3 13 | !default.mode1v3 14 | *.mode2v3 15 | !default.mode2v3 16 | *.perspectivev3 17 | !default.perspectivev3 18 | xcuserdata/ 19 | 20 | ## Other 21 | *.moved-aside 22 | *.xcuserstate 23 | 24 | ## Obj-C/Swift specific 25 | *.hmap 26 | *.ipa 27 | *.dSYM.zip 28 | *.dSYM 29 | 30 | # CocoaPods 31 | # 32 | # We recommend against adding the Pods directory to your .gitignore. However 33 | # you should judge for yourself, the pros and cons are mentioned at: 34 | # https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control 35 | # 36 | # Pods/ 37 | 38 | # Carthage 39 | # 40 | # Add this line if you want to avoid checking in source code from Carthage dependencies. 41 | # Carthage/Checkouts 42 | 43 | Carthage/Build 44 | 45 | # fastlane 46 | # 47 | # It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the 48 | # screenshots whenever they are needed. 49 | # For more information about the recommended setup visit: 50 | # https://github.com/fastlane/fastlane/blob/master/fastlane/docs/Gitignore.md 51 | 52 | fastlane/report.xml 53 | fastlane/screenshots 54 | 55 | #Code Injection 56 | # 57 | # After new code Injection tools there's a generated folder /iOSInjectionProject 58 | # https://github.com/johnno1962/injectionforxcode 59 | 60 | iOSInjectionProject/ 61 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 hyman 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.markdown: -------------------------------------------------------------------------------- 1 | A database upgrade tool that based on FMDB 2 | 3 | ## How does it work 4 | According to the different reference database and local database, upgrade the differences 5 | 6 | ## Support 7 | 1,Add new field(the new field of constraint only support: PK, DefaultValue, NOT NULL) 8 | 9 | 2,Add new table, Delete table, Rename table 10 | 11 | > Rename table must be in accordance with the following format to rename the table name:oldTableName_to_newTableName 12 | > 13 | >Migration, when recognition to the format of the table name, will extract the oldTableName and newTableName, and then judge whether the oldTableName exists in oldDB, if any, is renamed as newTableName;Otherwise, the oldTableName_to_newTableName will be treated as an ordinary table name 14 | > 15 | 16 | 3,Add new index, Delete index 17 | 18 | 4,Does not support this case: foreign key constraints exist in the database 19 | 20 | ## How to use 21 | First, create an empty DB in your project, which holds the latest table structure; that is, each time you upgrade the database, simply modify the corresponding table in the DB 22 | 23 | Use the following statement to determine if an upgrade is required: 24 | ```ObjC 25 | if ([SMSQLiteMigration versionForDB:self.db] < kCurrentVersion) { 26 | // upgrade ..... 27 | } 28 | ``` 29 | When the need to upgrade DB, execute the following statement: 30 | ```ObjC 31 | NSString *referDBPath = [[NSBundle mainBundle] pathForResource:@"TestDB" ofType:@"sqlite"]; 32 | FMDatabase *referDB = [[FMDatabase alloc] initWithPath:referDBPath]; 33 | if ([referDB open]) { 34 | BOOL success = [SMSQLiteMigration migrateLocalDB:self.db referDB:referDB toVersion:kCurrentVersion]; 35 | 36 | // .... 37 | } 38 | ``` 39 | -------------------------------------------------------------------------------- /SMSQLiteMigration.xcodeproj/project.pbxproj: -------------------------------------------------------------------------------- 1 | // !$*UTF8*$! 2 | { 3 | archiveVersion = 1; 4 | classes = { 5 | }; 6 | objectVersion = 46; 7 | objects = { 8 | 9 | /* Begin PBXBuildFile section */ 10 | 59099E631E235A660030B31C /* SMSQLiteMigrationIndex.m in Sources */ = {isa = PBXBuildFile; fileRef = 59099E621E235A660030B31C /* SMSQLiteMigrationIndex.m */; }; 11 | 59099E7B1E237E6D0030B31C /* TestDB_AddIndex.sqlite in Resources */ = {isa = PBXBuildFile; fileRef = 59099E7A1E237E6D0030B31C /* TestDB_AddIndex.sqlite */; }; 12 | 59099E7D1E237EC40030B31C /* TestDB_DeleteIndex.sqlite in Resources */ = {isa = PBXBuildFile; fileRef = 59099E7C1E237EC40030B31C /* TestDB_DeleteIndex.sqlite */; }; 13 | 5991BEBE1DEECA49002A07EC /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = 5991BEBD1DEECA49002A07EC /* main.m */; }; 14 | 5991BEC11DEECA49002A07EC /* AppDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = 5991BEC01DEECA49002A07EC /* AppDelegate.m */; }; 15 | 5991BEC41DEECA49002A07EC /* ViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 5991BEC31DEECA49002A07EC /* ViewController.m */; }; 16 | 5991BEC71DEECA49002A07EC /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 5991BEC51DEECA49002A07EC /* Main.storyboard */; }; 17 | 5991BEC91DEECA49002A07EC /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 5991BEC81DEECA49002A07EC /* Assets.xcassets */; }; 18 | 5991BECC1DEECA49002A07EC /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 5991BECA1DEECA49002A07EC /* LaunchScreen.storyboard */; }; 19 | 5991BED71DEECA49002A07EC /* SMSQLiteMigrationTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 5991BED61DEECA49002A07EC /* SMSQLiteMigrationTests.m */; }; 20 | 5991BF2B1DEECB1A002A07EC /* SMSQLiteMigrationColumn.m in Sources */ = {isa = PBXBuildFile; fileRef = 5991BF101DEECB1A002A07EC /* SMSQLiteMigrationColumn.m */; }; 21 | 5991BF2C1DEECB1A002A07EC /* SMSQLiteMigrationContent.m in Sources */ = {isa = PBXBuildFile; fileRef = 5991BF121DEECB1A002A07EC /* SMSQLiteMigrationContent.m */; }; 22 | 5991BF2D1DEECB1A002A07EC /* SMSQLiteMigrationTable.m in Sources */ = {isa = PBXBuildFile; fileRef = 5991BF141DEECB1A002A07EC /* SMSQLiteMigrationTable.m */; }; 23 | 5991BF2E1DEECB1A002A07EC /* SMSQLiteMigrationTableTuple.m in Sources */ = {isa = PBXBuildFile; fileRef = 5991BF161DEECB1A002A07EC /* SMSQLiteMigrationTableTuple.m */; }; 24 | 5991BF2F1DEECB1A002A07EC /* SMSQLiteMigration.m in Sources */ = {isa = PBXBuildFile; fileRef = 5991BF181DEECB1A002A07EC /* SMSQLiteMigration.m */; }; 25 | 5991BF301DEECB1A002A07EC /* FMDatabase.m in Sources */ = {isa = PBXBuildFile; fileRef = 5991BF1B1DEECB1A002A07EC /* FMDatabase.m */; }; 26 | 5991BF311DEECB1A002A07EC /* FMDatabaseAdditions.m in Sources */ = {isa = PBXBuildFile; fileRef = 5991BF1D1DEECB1A002A07EC /* FMDatabaseAdditions.m */; }; 27 | 5991BF321DEECB1A002A07EC /* FMDatabasePool.m in Sources */ = {isa = PBXBuildFile; fileRef = 5991BF1F1DEECB1A002A07EC /* FMDatabasePool.m */; }; 28 | 5991BF331DEECB1A002A07EC /* FMDatabaseQueue.m in Sources */ = {isa = PBXBuildFile; fileRef = 5991BF211DEECB1A002A07EC /* FMDatabaseQueue.m */; }; 29 | 5991BF341DEECB1A002A07EC /* FMResultSet.m in Sources */ = {isa = PBXBuildFile; fileRef = 5991BF241DEECB1A002A07EC /* FMResultSet.m */; }; 30 | 5991BF361DEECB1A002A07EC /* TestDB_AddColumn.sqlite in Resources */ = {isa = PBXBuildFile; fileRef = 5991BF261DEECB1A002A07EC /* TestDB_AddColumn.sqlite */; }; 31 | 5991BF371DEECB1A002A07EC /* TestDB_AddTable.sqlite in Resources */ = {isa = PBXBuildFile; fileRef = 5991BF271DEECB1A002A07EC /* TestDB_AddTable.sqlite */; }; 32 | 5991BF381DEECB1A002A07EC /* TestDB_DeleteTable.sqlite in Resources */ = {isa = PBXBuildFile; fileRef = 5991BF281DEECB1A002A07EC /* TestDB_DeleteTable.sqlite */; }; 33 | 5991BF391DEECB1A002A07EC /* TestDB_RenameTabel.sqlite in Resources */ = {isa = PBXBuildFile; fileRef = 5991BF291DEECB1A002A07EC /* TestDB_RenameTabel.sqlite */; }; 34 | 5991BF3A1DEECB1A002A07EC /* TestDB.sqlite in Resources */ = {isa = PBXBuildFile; fileRef = 5991BF2A1DEECB1A002A07EC /* TestDB.sqlite */; }; 35 | 5991BF9D1DEED6E2002A07EC /* libsqlite3.0.tbd in Frameworks */ = {isa = PBXBuildFile; fileRef = 5991BF9C1DEED6E2002A07EC /* libsqlite3.0.tbd */; }; 36 | /* End PBXBuildFile section */ 37 | 38 | /* Begin PBXContainerItemProxy section */ 39 | 5991BED31DEECA49002A07EC /* PBXContainerItemProxy */ = { 40 | isa = PBXContainerItemProxy; 41 | containerPortal = 5991BEB11DEECA49002A07EC /* Project object */; 42 | proxyType = 1; 43 | remoteGlobalIDString = 5991BEB81DEECA49002A07EC; 44 | remoteInfo = SMSQLiteMigration; 45 | }; 46 | /* End PBXContainerItemProxy section */ 47 | 48 | /* Begin PBXFileReference section */ 49 | 59099E611E235A660030B31C /* SMSQLiteMigrationIndex.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SMSQLiteMigrationIndex.h; sourceTree = ""; }; 50 | 59099E621E235A660030B31C /* SMSQLiteMigrationIndex.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SMSQLiteMigrationIndex.m; sourceTree = ""; }; 51 | 59099E7A1E237E6D0030B31C /* TestDB_AddIndex.sqlite */ = {isa = PBXFileReference; lastKnownFileType = file; path = TestDB_AddIndex.sqlite; sourceTree = ""; }; 52 | 59099E7C1E237EC40030B31C /* TestDB_DeleteIndex.sqlite */ = {isa = PBXFileReference; lastKnownFileType = file; path = TestDB_DeleteIndex.sqlite; sourceTree = ""; }; 53 | 5991BEB91DEECA49002A07EC /* SMSQLiteMigration.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = SMSQLiteMigration.app; sourceTree = BUILT_PRODUCTS_DIR; }; 54 | 5991BEBD1DEECA49002A07EC /* main.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = main.m; sourceTree = ""; }; 55 | 5991BEBF1DEECA49002A07EC /* AppDelegate.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = AppDelegate.h; sourceTree = ""; }; 56 | 5991BEC01DEECA49002A07EC /* AppDelegate.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = AppDelegate.m; sourceTree = ""; }; 57 | 5991BEC21DEECA49002A07EC /* ViewController.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = ViewController.h; sourceTree = ""; }; 58 | 5991BEC31DEECA49002A07EC /* ViewController.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = ViewController.m; sourceTree = ""; }; 59 | 5991BEC61DEECA49002A07EC /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; 60 | 5991BEC81DEECA49002A07EC /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; 61 | 5991BECB1DEECA49002A07EC /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; 62 | 5991BECD1DEECA49002A07EC /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; 63 | 5991BED21DEECA49002A07EC /* SMSQLiteMigrationTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = SMSQLiteMigrationTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; 64 | 5991BED61DEECA49002A07EC /* SMSQLiteMigrationTests.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = SMSQLiteMigrationTests.m; sourceTree = ""; }; 65 | 5991BED81DEECA49002A07EC /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; 66 | 5991BF0F1DEECB1A002A07EC /* SMSQLiteMigrationColumn.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SMSQLiteMigrationColumn.h; sourceTree = ""; }; 67 | 5991BF101DEECB1A002A07EC /* SMSQLiteMigrationColumn.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SMSQLiteMigrationColumn.m; sourceTree = ""; }; 68 | 5991BF111DEECB1A002A07EC /* SMSQLiteMigrationContent.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SMSQLiteMigrationContent.h; sourceTree = ""; }; 69 | 5991BF121DEECB1A002A07EC /* SMSQLiteMigrationContent.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SMSQLiteMigrationContent.m; sourceTree = ""; }; 70 | 5991BF131DEECB1A002A07EC /* SMSQLiteMigrationTable.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SMSQLiteMigrationTable.h; sourceTree = ""; }; 71 | 5991BF141DEECB1A002A07EC /* SMSQLiteMigrationTable.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SMSQLiteMigrationTable.m; sourceTree = ""; }; 72 | 5991BF151DEECB1A002A07EC /* SMSQLiteMigrationTableTuple.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SMSQLiteMigrationTableTuple.h; sourceTree = ""; }; 73 | 5991BF161DEECB1A002A07EC /* SMSQLiteMigrationTableTuple.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SMSQLiteMigrationTableTuple.m; sourceTree = ""; }; 74 | 5991BF171DEECB1A002A07EC /* SMSQLiteMigration.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SMSQLiteMigration.h; sourceTree = ""; }; 75 | 5991BF181DEECB1A002A07EC /* SMSQLiteMigration.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SMSQLiteMigration.m; sourceTree = ""; }; 76 | 5991BF1A1DEECB1A002A07EC /* FMDatabase.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = FMDatabase.h; sourceTree = ""; }; 77 | 5991BF1B1DEECB1A002A07EC /* FMDatabase.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = FMDatabase.m; sourceTree = ""; }; 78 | 5991BF1C1DEECB1A002A07EC /* FMDatabaseAdditions.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = FMDatabaseAdditions.h; sourceTree = ""; }; 79 | 5991BF1D1DEECB1A002A07EC /* FMDatabaseAdditions.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = FMDatabaseAdditions.m; sourceTree = ""; }; 80 | 5991BF1E1DEECB1A002A07EC /* FMDatabasePool.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = FMDatabasePool.h; sourceTree = ""; }; 81 | 5991BF1F1DEECB1A002A07EC /* FMDatabasePool.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = FMDatabasePool.m; sourceTree = ""; }; 82 | 5991BF201DEECB1A002A07EC /* FMDatabaseQueue.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = FMDatabaseQueue.h; sourceTree = ""; }; 83 | 5991BF211DEECB1A002A07EC /* FMDatabaseQueue.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = FMDatabaseQueue.m; sourceTree = ""; }; 84 | 5991BF221DEECB1A002A07EC /* FMDB.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = FMDB.h; sourceTree = ""; }; 85 | 5991BF231DEECB1A002A07EC /* FMResultSet.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = FMResultSet.h; sourceTree = ""; }; 86 | 5991BF241DEECB1A002A07EC /* FMResultSet.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = FMResultSet.m; sourceTree = ""; }; 87 | 5991BF261DEECB1A002A07EC /* TestDB_AddColumn.sqlite */ = {isa = PBXFileReference; lastKnownFileType = file; path = TestDB_AddColumn.sqlite; sourceTree = ""; }; 88 | 5991BF271DEECB1A002A07EC /* TestDB_AddTable.sqlite */ = {isa = PBXFileReference; lastKnownFileType = file; path = TestDB_AddTable.sqlite; sourceTree = ""; }; 89 | 5991BF281DEECB1A002A07EC /* TestDB_DeleteTable.sqlite */ = {isa = PBXFileReference; lastKnownFileType = file; path = TestDB_DeleteTable.sqlite; sourceTree = ""; }; 90 | 5991BF291DEECB1A002A07EC /* TestDB_RenameTabel.sqlite */ = {isa = PBXFileReference; lastKnownFileType = file; path = TestDB_RenameTabel.sqlite; sourceTree = ""; }; 91 | 5991BF2A1DEECB1A002A07EC /* TestDB.sqlite */ = {isa = PBXFileReference; lastKnownFileType = file; path = TestDB.sqlite; sourceTree = ""; }; 92 | 5991BF9C1DEED6E2002A07EC /* libsqlite3.0.tbd */ = {isa = PBXFileReference; lastKnownFileType = "sourcecode.text-based-dylib-definition"; name = libsqlite3.0.tbd; path = usr/lib/libsqlite3.0.tbd; sourceTree = SDKROOT; }; 93 | /* End PBXFileReference section */ 94 | 95 | /* Begin PBXFrameworksBuildPhase section */ 96 | 5991BEB61DEECA49002A07EC /* Frameworks */ = { 97 | isa = PBXFrameworksBuildPhase; 98 | buildActionMask = 2147483647; 99 | files = ( 100 | 5991BF9D1DEED6E2002A07EC /* libsqlite3.0.tbd in Frameworks */, 101 | ); 102 | runOnlyForDeploymentPostprocessing = 0; 103 | }; 104 | 5991BECF1DEECA49002A07EC /* Frameworks */ = { 105 | isa = PBXFrameworksBuildPhase; 106 | buildActionMask = 2147483647; 107 | files = ( 108 | ); 109 | runOnlyForDeploymentPostprocessing = 0; 110 | }; 111 | /* End PBXFrameworksBuildPhase section */ 112 | 113 | /* Begin PBXGroup section */ 114 | 5991BEB01DEECA49002A07EC = { 115 | isa = PBXGroup; 116 | children = ( 117 | 5991BEBB1DEECA49002A07EC /* SMSQLiteMigration */, 118 | 5991BED51DEECA49002A07EC /* SMSQLiteMigrationTests */, 119 | 5991BEBA1DEECA49002A07EC /* Products */, 120 | 5991BF9B1DEED6E2002A07EC /* Frameworks */, 121 | ); 122 | sourceTree = ""; 123 | }; 124 | 5991BEBA1DEECA49002A07EC /* Products */ = { 125 | isa = PBXGroup; 126 | children = ( 127 | 5991BEB91DEECA49002A07EC /* SMSQLiteMigration.app */, 128 | 5991BED21DEECA49002A07EC /* SMSQLiteMigrationTests.xctest */, 129 | ); 130 | name = Products; 131 | sourceTree = ""; 132 | }; 133 | 5991BEBB1DEECA49002A07EC /* SMSQLiteMigration */ = { 134 | isa = PBXGroup; 135 | children = ( 136 | 5991BF191DEECB1A002A07EC /* FMDatabase */, 137 | 5991BF0D1DEECB1A002A07EC /* DBMigration */, 138 | 5991BEBF1DEECA49002A07EC /* AppDelegate.h */, 139 | 5991BEC01DEECA49002A07EC /* AppDelegate.m */, 140 | 5991BEC21DEECA49002A07EC /* ViewController.h */, 141 | 5991BEC31DEECA49002A07EC /* ViewController.m */, 142 | 5991BF261DEECB1A002A07EC /* TestDB_AddColumn.sqlite */, 143 | 5991BF271DEECB1A002A07EC /* TestDB_AddTable.sqlite */, 144 | 5991BF281DEECB1A002A07EC /* TestDB_DeleteTable.sqlite */, 145 | 5991BF291DEECB1A002A07EC /* TestDB_RenameTabel.sqlite */, 146 | 59099E7A1E237E6D0030B31C /* TestDB_AddIndex.sqlite */, 147 | 59099E7C1E237EC40030B31C /* TestDB_DeleteIndex.sqlite */, 148 | 5991BF2A1DEECB1A002A07EC /* TestDB.sqlite */, 149 | 5991BEC51DEECA49002A07EC /* Main.storyboard */, 150 | 5991BEC81DEECA49002A07EC /* Assets.xcassets */, 151 | 5991BECA1DEECA49002A07EC /* LaunchScreen.storyboard */, 152 | 5991BECD1DEECA49002A07EC /* Info.plist */, 153 | 5991BEBC1DEECA49002A07EC /* Supporting Files */, 154 | ); 155 | path = SMSQLiteMigration; 156 | sourceTree = ""; 157 | }; 158 | 5991BEBC1DEECA49002A07EC /* Supporting Files */ = { 159 | isa = PBXGroup; 160 | children = ( 161 | 5991BEBD1DEECA49002A07EC /* main.m */, 162 | ); 163 | name = "Supporting Files"; 164 | sourceTree = ""; 165 | }; 166 | 5991BED51DEECA49002A07EC /* SMSQLiteMigrationTests */ = { 167 | isa = PBXGroup; 168 | children = ( 169 | 5991BED61DEECA49002A07EC /* SMSQLiteMigrationTests.m */, 170 | 5991BED81DEECA49002A07EC /* Info.plist */, 171 | ); 172 | path = SMSQLiteMigrationTests; 173 | sourceTree = ""; 174 | }; 175 | 5991BF0D1DEECB1A002A07EC /* DBMigration */ = { 176 | isa = PBXGroup; 177 | children = ( 178 | 5991BF0E1DEECB1A002A07EC /* Private */, 179 | 5991BF171DEECB1A002A07EC /* SMSQLiteMigration.h */, 180 | 5991BF181DEECB1A002A07EC /* SMSQLiteMigration.m */, 181 | ); 182 | path = DBMigration; 183 | sourceTree = ""; 184 | }; 185 | 5991BF0E1DEECB1A002A07EC /* Private */ = { 186 | isa = PBXGroup; 187 | children = ( 188 | 5991BF0F1DEECB1A002A07EC /* SMSQLiteMigrationColumn.h */, 189 | 5991BF101DEECB1A002A07EC /* SMSQLiteMigrationColumn.m */, 190 | 5991BF111DEECB1A002A07EC /* SMSQLiteMigrationContent.h */, 191 | 5991BF121DEECB1A002A07EC /* SMSQLiteMigrationContent.m */, 192 | 5991BF131DEECB1A002A07EC /* SMSQLiteMigrationTable.h */, 193 | 5991BF141DEECB1A002A07EC /* SMSQLiteMigrationTable.m */, 194 | 59099E611E235A660030B31C /* SMSQLiteMigrationIndex.h */, 195 | 59099E621E235A660030B31C /* SMSQLiteMigrationIndex.m */, 196 | 5991BF151DEECB1A002A07EC /* SMSQLiteMigrationTableTuple.h */, 197 | 5991BF161DEECB1A002A07EC /* SMSQLiteMigrationTableTuple.m */, 198 | ); 199 | path = Private; 200 | sourceTree = ""; 201 | }; 202 | 5991BF191DEECB1A002A07EC /* FMDatabase */ = { 203 | isa = PBXGroup; 204 | children = ( 205 | 5991BF1A1DEECB1A002A07EC /* FMDatabase.h */, 206 | 5991BF1B1DEECB1A002A07EC /* FMDatabase.m */, 207 | 5991BF1C1DEECB1A002A07EC /* FMDatabaseAdditions.h */, 208 | 5991BF1D1DEECB1A002A07EC /* FMDatabaseAdditions.m */, 209 | 5991BF1E1DEECB1A002A07EC /* FMDatabasePool.h */, 210 | 5991BF1F1DEECB1A002A07EC /* FMDatabasePool.m */, 211 | 5991BF201DEECB1A002A07EC /* FMDatabaseQueue.h */, 212 | 5991BF211DEECB1A002A07EC /* FMDatabaseQueue.m */, 213 | 5991BF221DEECB1A002A07EC /* FMDB.h */, 214 | 5991BF231DEECB1A002A07EC /* FMResultSet.h */, 215 | 5991BF241DEECB1A002A07EC /* FMResultSet.m */, 216 | ); 217 | path = FMDatabase; 218 | sourceTree = ""; 219 | }; 220 | 5991BF9B1DEED6E2002A07EC /* Frameworks */ = { 221 | isa = PBXGroup; 222 | children = ( 223 | 5991BF9C1DEED6E2002A07EC /* libsqlite3.0.tbd */, 224 | ); 225 | name = Frameworks; 226 | sourceTree = ""; 227 | }; 228 | /* End PBXGroup section */ 229 | 230 | /* Begin PBXNativeTarget section */ 231 | 5991BEB81DEECA49002A07EC /* SMSQLiteMigration */ = { 232 | isa = PBXNativeTarget; 233 | buildConfigurationList = 5991BEDB1DEECA49002A07EC /* Build configuration list for PBXNativeTarget "SMSQLiteMigration" */; 234 | buildPhases = ( 235 | 5991BEB51DEECA49002A07EC /* Sources */, 236 | 5991BEB61DEECA49002A07EC /* Frameworks */, 237 | 5991BEB71DEECA49002A07EC /* Resources */, 238 | ); 239 | buildRules = ( 240 | ); 241 | dependencies = ( 242 | ); 243 | name = SMSQLiteMigration; 244 | productName = SMSQLiteMigration; 245 | productReference = 5991BEB91DEECA49002A07EC /* SMSQLiteMigration.app */; 246 | productType = "com.apple.product-type.application"; 247 | }; 248 | 5991BED11DEECA49002A07EC /* SMSQLiteMigrationTests */ = { 249 | isa = PBXNativeTarget; 250 | buildConfigurationList = 5991BEDE1DEECA49002A07EC /* Build configuration list for PBXNativeTarget "SMSQLiteMigrationTests" */; 251 | buildPhases = ( 252 | 5991BECE1DEECA49002A07EC /* Sources */, 253 | 5991BECF1DEECA49002A07EC /* Frameworks */, 254 | 5991BED01DEECA49002A07EC /* Resources */, 255 | ); 256 | buildRules = ( 257 | ); 258 | dependencies = ( 259 | 5991BED41DEECA49002A07EC /* PBXTargetDependency */, 260 | ); 261 | name = SMSQLiteMigrationTests; 262 | productName = SMSQLiteMigrationTests; 263 | productReference = 5991BED21DEECA49002A07EC /* SMSQLiteMigrationTests.xctest */; 264 | productType = "com.apple.product-type.bundle.unit-test"; 265 | }; 266 | /* End PBXNativeTarget section */ 267 | 268 | /* Begin PBXProject section */ 269 | 5991BEB11DEECA49002A07EC /* Project object */ = { 270 | isa = PBXProject; 271 | attributes = { 272 | LastUpgradeCheck = 0820; 273 | ORGANIZATIONNAME = 00; 274 | TargetAttributes = { 275 | 5991BEB81DEECA49002A07EC = { 276 | CreatedOnToolsVersion = 8.1; 277 | ProvisioningStyle = Manual; 278 | }; 279 | 5991BED11DEECA49002A07EC = { 280 | CreatedOnToolsVersion = 8.1; 281 | ProvisioningStyle = Automatic; 282 | TestTargetID = 5991BEB81DEECA49002A07EC; 283 | }; 284 | }; 285 | }; 286 | buildConfigurationList = 5991BEB41DEECA49002A07EC /* Build configuration list for PBXProject "SMSQLiteMigration" */; 287 | compatibilityVersion = "Xcode 3.2"; 288 | developmentRegion = English; 289 | hasScannedForEncodings = 0; 290 | knownRegions = ( 291 | en, 292 | Base, 293 | ); 294 | mainGroup = 5991BEB01DEECA49002A07EC; 295 | productRefGroup = 5991BEBA1DEECA49002A07EC /* Products */; 296 | projectDirPath = ""; 297 | projectRoot = ""; 298 | targets = ( 299 | 5991BEB81DEECA49002A07EC /* SMSQLiteMigration */, 300 | 5991BED11DEECA49002A07EC /* SMSQLiteMigrationTests */, 301 | ); 302 | }; 303 | /* End PBXProject section */ 304 | 305 | /* Begin PBXResourcesBuildPhase section */ 306 | 5991BEB71DEECA49002A07EC /* Resources */ = { 307 | isa = PBXResourcesBuildPhase; 308 | buildActionMask = 2147483647; 309 | files = ( 310 | 59099E7B1E237E6D0030B31C /* TestDB_AddIndex.sqlite in Resources */, 311 | 5991BECC1DEECA49002A07EC /* LaunchScreen.storyboard in Resources */, 312 | 5991BF381DEECB1A002A07EC /* TestDB_DeleteTable.sqlite in Resources */, 313 | 5991BF371DEECB1A002A07EC /* TestDB_AddTable.sqlite in Resources */, 314 | 5991BF3A1DEECB1A002A07EC /* TestDB.sqlite in Resources */, 315 | 5991BEC91DEECA49002A07EC /* Assets.xcassets in Resources */, 316 | 5991BEC71DEECA49002A07EC /* Main.storyboard in Resources */, 317 | 5991BF391DEECB1A002A07EC /* TestDB_RenameTabel.sqlite in Resources */, 318 | 5991BF361DEECB1A002A07EC /* TestDB_AddColumn.sqlite in Resources */, 319 | 59099E7D1E237EC40030B31C /* TestDB_DeleteIndex.sqlite in Resources */, 320 | ); 321 | runOnlyForDeploymentPostprocessing = 0; 322 | }; 323 | 5991BED01DEECA49002A07EC /* Resources */ = { 324 | isa = PBXResourcesBuildPhase; 325 | buildActionMask = 2147483647; 326 | files = ( 327 | ); 328 | runOnlyForDeploymentPostprocessing = 0; 329 | }; 330 | /* End PBXResourcesBuildPhase section */ 331 | 332 | /* Begin PBXSourcesBuildPhase section */ 333 | 5991BEB51DEECA49002A07EC /* Sources */ = { 334 | isa = PBXSourcesBuildPhase; 335 | buildActionMask = 2147483647; 336 | files = ( 337 | 5991BEC41DEECA49002A07EC /* ViewController.m in Sources */, 338 | 5991BF2E1DEECB1A002A07EC /* SMSQLiteMigrationTableTuple.m in Sources */, 339 | 5991BF2F1DEECB1A002A07EC /* SMSQLiteMigration.m in Sources */, 340 | 5991BF301DEECB1A002A07EC /* FMDatabase.m in Sources */, 341 | 5991BEC11DEECA49002A07EC /* AppDelegate.m in Sources */, 342 | 5991BF331DEECB1A002A07EC /* FMDatabaseQueue.m in Sources */, 343 | 5991BF341DEECB1A002A07EC /* FMResultSet.m in Sources */, 344 | 5991BF321DEECB1A002A07EC /* FMDatabasePool.m in Sources */, 345 | 5991BF2B1DEECB1A002A07EC /* SMSQLiteMigrationColumn.m in Sources */, 346 | 5991BF2D1DEECB1A002A07EC /* SMSQLiteMigrationTable.m in Sources */, 347 | 5991BEBE1DEECA49002A07EC /* main.m in Sources */, 348 | 59099E631E235A660030B31C /* SMSQLiteMigrationIndex.m in Sources */, 349 | 5991BF2C1DEECB1A002A07EC /* SMSQLiteMigrationContent.m in Sources */, 350 | 5991BF311DEECB1A002A07EC /* FMDatabaseAdditions.m in Sources */, 351 | ); 352 | runOnlyForDeploymentPostprocessing = 0; 353 | }; 354 | 5991BECE1DEECA49002A07EC /* Sources */ = { 355 | isa = PBXSourcesBuildPhase; 356 | buildActionMask = 2147483647; 357 | files = ( 358 | 5991BED71DEECA49002A07EC /* SMSQLiteMigrationTests.m in Sources */, 359 | ); 360 | runOnlyForDeploymentPostprocessing = 0; 361 | }; 362 | /* End PBXSourcesBuildPhase section */ 363 | 364 | /* Begin PBXTargetDependency section */ 365 | 5991BED41DEECA49002A07EC /* PBXTargetDependency */ = { 366 | isa = PBXTargetDependency; 367 | target = 5991BEB81DEECA49002A07EC /* SMSQLiteMigration */; 368 | targetProxy = 5991BED31DEECA49002A07EC /* PBXContainerItemProxy */; 369 | }; 370 | /* End PBXTargetDependency section */ 371 | 372 | /* Begin PBXVariantGroup section */ 373 | 5991BEC51DEECA49002A07EC /* Main.storyboard */ = { 374 | isa = PBXVariantGroup; 375 | children = ( 376 | 5991BEC61DEECA49002A07EC /* Base */, 377 | ); 378 | name = Main.storyboard; 379 | sourceTree = ""; 380 | }; 381 | 5991BECA1DEECA49002A07EC /* LaunchScreen.storyboard */ = { 382 | isa = PBXVariantGroup; 383 | children = ( 384 | 5991BECB1DEECA49002A07EC /* Base */, 385 | ); 386 | name = LaunchScreen.storyboard; 387 | sourceTree = ""; 388 | }; 389 | /* End PBXVariantGroup section */ 390 | 391 | /* Begin XCBuildConfiguration section */ 392 | 5991BED91DEECA49002A07EC /* Debug */ = { 393 | isa = XCBuildConfiguration; 394 | buildSettings = { 395 | ALWAYS_SEARCH_USER_PATHS = NO; 396 | CLANG_ANALYZER_NONNULL = YES; 397 | CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; 398 | CLANG_CXX_LIBRARY = "libc++"; 399 | CLANG_ENABLE_MODULES = YES; 400 | CLANG_ENABLE_OBJC_ARC = YES; 401 | CLANG_WARN_BOOL_CONVERSION = YES; 402 | CLANG_WARN_CONSTANT_CONVERSION = YES; 403 | CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; 404 | CLANG_WARN_DOCUMENTATION_COMMENTS = YES; 405 | CLANG_WARN_EMPTY_BODY = YES; 406 | CLANG_WARN_ENUM_CONVERSION = YES; 407 | CLANG_WARN_INFINITE_RECURSION = YES; 408 | CLANG_WARN_INT_CONVERSION = YES; 409 | CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; 410 | CLANG_WARN_SUSPICIOUS_MOVE = YES; 411 | CLANG_WARN_SUSPICIOUS_MOVES = YES; 412 | CLANG_WARN_UNREACHABLE_CODE = YES; 413 | CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; 414 | "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; 415 | COPY_PHASE_STRIP = NO; 416 | DEBUG_INFORMATION_FORMAT = dwarf; 417 | ENABLE_STRICT_OBJC_MSGSEND = YES; 418 | ENABLE_TESTABILITY = YES; 419 | GCC_C_LANGUAGE_STANDARD = gnu99; 420 | GCC_DYNAMIC_NO_PIC = NO; 421 | GCC_NO_COMMON_BLOCKS = YES; 422 | GCC_OPTIMIZATION_LEVEL = 0; 423 | GCC_PREPROCESSOR_DEFINITIONS = ( 424 | "DEBUG=1", 425 | "$(inherited)", 426 | ); 427 | GCC_WARN_64_TO_32_BIT_CONVERSION = YES; 428 | GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; 429 | GCC_WARN_UNDECLARED_SELECTOR = YES; 430 | GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; 431 | GCC_WARN_UNUSED_FUNCTION = YES; 432 | GCC_WARN_UNUSED_VARIABLE = YES; 433 | IPHONEOS_DEPLOYMENT_TARGET = 10.1; 434 | MTL_ENABLE_DEBUG_INFO = YES; 435 | ONLY_ACTIVE_ARCH = YES; 436 | SDKROOT = iphoneos; 437 | TARGETED_DEVICE_FAMILY = "1,2"; 438 | }; 439 | name = Debug; 440 | }; 441 | 5991BEDA1DEECA49002A07EC /* Release */ = { 442 | isa = XCBuildConfiguration; 443 | buildSettings = { 444 | ALWAYS_SEARCH_USER_PATHS = NO; 445 | CLANG_ANALYZER_NONNULL = YES; 446 | CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; 447 | CLANG_CXX_LIBRARY = "libc++"; 448 | CLANG_ENABLE_MODULES = YES; 449 | CLANG_ENABLE_OBJC_ARC = YES; 450 | CLANG_WARN_BOOL_CONVERSION = YES; 451 | CLANG_WARN_CONSTANT_CONVERSION = YES; 452 | CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; 453 | CLANG_WARN_DOCUMENTATION_COMMENTS = YES; 454 | CLANG_WARN_EMPTY_BODY = YES; 455 | CLANG_WARN_ENUM_CONVERSION = YES; 456 | CLANG_WARN_INFINITE_RECURSION = YES; 457 | CLANG_WARN_INT_CONVERSION = YES; 458 | CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; 459 | CLANG_WARN_SUSPICIOUS_MOVE = YES; 460 | CLANG_WARN_SUSPICIOUS_MOVES = YES; 461 | CLANG_WARN_UNREACHABLE_CODE = YES; 462 | CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; 463 | "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; 464 | COPY_PHASE_STRIP = NO; 465 | DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; 466 | ENABLE_NS_ASSERTIONS = NO; 467 | ENABLE_STRICT_OBJC_MSGSEND = YES; 468 | GCC_C_LANGUAGE_STANDARD = gnu99; 469 | GCC_NO_COMMON_BLOCKS = YES; 470 | GCC_WARN_64_TO_32_BIT_CONVERSION = YES; 471 | GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; 472 | GCC_WARN_UNDECLARED_SELECTOR = YES; 473 | GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; 474 | GCC_WARN_UNUSED_FUNCTION = YES; 475 | GCC_WARN_UNUSED_VARIABLE = YES; 476 | IPHONEOS_DEPLOYMENT_TARGET = 10.1; 477 | MTL_ENABLE_DEBUG_INFO = NO; 478 | SDKROOT = iphoneos; 479 | TARGETED_DEVICE_FAMILY = "1,2"; 480 | VALIDATE_PRODUCT = YES; 481 | }; 482 | name = Release; 483 | }; 484 | 5991BEDC1DEECA49002A07EC /* Debug */ = { 485 | isa = XCBuildConfiguration; 486 | buildSettings = { 487 | ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; 488 | DEVELOPMENT_TEAM = ""; 489 | INFOPLIST_FILE = SMSQLiteMigration/Info.plist; 490 | LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; 491 | PRODUCT_BUNDLE_IDENTIFIER = "-0.SMSQLiteMigration"; 492 | PRODUCT_NAME = "$(TARGET_NAME)"; 493 | }; 494 | name = Debug; 495 | }; 496 | 5991BEDD1DEECA49002A07EC /* Release */ = { 497 | isa = XCBuildConfiguration; 498 | buildSettings = { 499 | ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; 500 | DEVELOPMENT_TEAM = ""; 501 | INFOPLIST_FILE = SMSQLiteMigration/Info.plist; 502 | LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; 503 | PRODUCT_BUNDLE_IDENTIFIER = "-0.SMSQLiteMigration"; 504 | PRODUCT_NAME = "$(TARGET_NAME)"; 505 | }; 506 | name = Release; 507 | }; 508 | 5991BEDF1DEECA49002A07EC /* Debug */ = { 509 | isa = XCBuildConfiguration; 510 | buildSettings = { 511 | BUNDLE_LOADER = "$(TEST_HOST)"; 512 | INFOPLIST_FILE = SMSQLiteMigrationTests/Info.plist; 513 | LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; 514 | PRODUCT_BUNDLE_IDENTIFIER = "-0.SMSQLiteMigrationTests"; 515 | PRODUCT_NAME = "$(TARGET_NAME)"; 516 | TEST_HOST = "$(BUILT_PRODUCTS_DIR)/SMSQLiteMigration.app/SMSQLiteMigration"; 517 | }; 518 | name = Debug; 519 | }; 520 | 5991BEE01DEECA49002A07EC /* Release */ = { 521 | isa = XCBuildConfiguration; 522 | buildSettings = { 523 | BUNDLE_LOADER = "$(TEST_HOST)"; 524 | INFOPLIST_FILE = SMSQLiteMigrationTests/Info.plist; 525 | LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; 526 | PRODUCT_BUNDLE_IDENTIFIER = "-0.SMSQLiteMigrationTests"; 527 | PRODUCT_NAME = "$(TARGET_NAME)"; 528 | TEST_HOST = "$(BUILT_PRODUCTS_DIR)/SMSQLiteMigration.app/SMSQLiteMigration"; 529 | }; 530 | name = Release; 531 | }; 532 | /* End XCBuildConfiguration section */ 533 | 534 | /* Begin XCConfigurationList section */ 535 | 5991BEB41DEECA49002A07EC /* Build configuration list for PBXProject "SMSQLiteMigration" */ = { 536 | isa = XCConfigurationList; 537 | buildConfigurations = ( 538 | 5991BED91DEECA49002A07EC /* Debug */, 539 | 5991BEDA1DEECA49002A07EC /* Release */, 540 | ); 541 | defaultConfigurationIsVisible = 0; 542 | defaultConfigurationName = Release; 543 | }; 544 | 5991BEDB1DEECA49002A07EC /* Build configuration list for PBXNativeTarget "SMSQLiteMigration" */ = { 545 | isa = XCConfigurationList; 546 | buildConfigurations = ( 547 | 5991BEDC1DEECA49002A07EC /* Debug */, 548 | 5991BEDD1DEECA49002A07EC /* Release */, 549 | ); 550 | defaultConfigurationIsVisible = 0; 551 | defaultConfigurationName = Release; 552 | }; 553 | 5991BEDE1DEECA49002A07EC /* Build configuration list for PBXNativeTarget "SMSQLiteMigrationTests" */ = { 554 | isa = XCConfigurationList; 555 | buildConfigurations = ( 556 | 5991BEDF1DEECA49002A07EC /* Debug */, 557 | 5991BEE01DEECA49002A07EC /* Release */, 558 | ); 559 | defaultConfigurationIsVisible = 0; 560 | defaultConfigurationName = Release; 561 | }; 562 | /* End XCConfigurationList section */ 563 | }; 564 | rootObject = 5991BEB11DEECA49002A07EC /* Project object */; 565 | } 566 | -------------------------------------------------------------------------------- /SMSQLiteMigration.xcodeproj/project.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /SMSQLiteMigration/AppDelegate.h: -------------------------------------------------------------------------------- 1 | // 2 | // AppDelegate.h 3 | // SMSQLiteMigration 4 | // 5 | // Created by 00 on 2016/11/30. 6 | // Copyright © 2016年 00. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface AppDelegate : UIResponder 12 | 13 | @property (strong, nonatomic) UIWindow *window; 14 | 15 | 16 | @end 17 | 18 | -------------------------------------------------------------------------------- /SMSQLiteMigration/AppDelegate.m: -------------------------------------------------------------------------------- 1 | // 2 | // AppDelegate.m 3 | // SMSQLiteMigration 4 | // 5 | // Created by 00 on 2016/11/30. 6 | // Copyright © 2016年 00. All rights reserved. 7 | // 8 | 9 | #import "AppDelegate.h" 10 | 11 | @interface AppDelegate () 12 | 13 | @end 14 | 15 | @implementation AppDelegate 16 | 17 | 18 | - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { 19 | // Override point for customization after application launch. 20 | return YES; 21 | } 22 | 23 | 24 | - (void)applicationWillResignActive:(UIApplication *)application { 25 | // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. 26 | // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. 27 | } 28 | 29 | 30 | - (void)applicationDidEnterBackground:(UIApplication *)application { 31 | // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 32 | // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. 33 | } 34 | 35 | 36 | - (void)applicationWillEnterForeground:(UIApplication *)application { 37 | // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. 38 | } 39 | 40 | 41 | - (void)applicationDidBecomeActive:(UIApplication *)application { 42 | // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. 43 | } 44 | 45 | 46 | - (void)applicationWillTerminate:(UIApplication *)application { 47 | // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. 48 | } 49 | 50 | 51 | @end 52 | -------------------------------------------------------------------------------- /SMSQLiteMigration/Assets.xcassets/AppIcon.appiconset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "images" : [ 3 | { 4 | "idiom" : "iphone", 5 | "size" : "20x20", 6 | "scale" : "2x" 7 | }, 8 | { 9 | "idiom" : "iphone", 10 | "size" : "20x20", 11 | "scale" : "3x" 12 | }, 13 | { 14 | "idiom" : "iphone", 15 | "size" : "29x29", 16 | "scale" : "2x" 17 | }, 18 | { 19 | "idiom" : "iphone", 20 | "size" : "29x29", 21 | "scale" : "3x" 22 | }, 23 | { 24 | "idiom" : "iphone", 25 | "size" : "40x40", 26 | "scale" : "2x" 27 | }, 28 | { 29 | "idiom" : "iphone", 30 | "size" : "40x40", 31 | "scale" : "3x" 32 | }, 33 | { 34 | "idiom" : "iphone", 35 | "size" : "60x60", 36 | "scale" : "2x" 37 | }, 38 | { 39 | "idiom" : "iphone", 40 | "size" : "60x60", 41 | "scale" : "3x" 42 | }, 43 | { 44 | "idiom" : "ipad", 45 | "size" : "20x20", 46 | "scale" : "1x" 47 | }, 48 | { 49 | "idiom" : "ipad", 50 | "size" : "20x20", 51 | "scale" : "2x" 52 | }, 53 | { 54 | "idiom" : "ipad", 55 | "size" : "29x29", 56 | "scale" : "1x" 57 | }, 58 | { 59 | "idiom" : "ipad", 60 | "size" : "29x29", 61 | "scale" : "2x" 62 | }, 63 | { 64 | "idiom" : "ipad", 65 | "size" : "40x40", 66 | "scale" : "1x" 67 | }, 68 | { 69 | "idiom" : "ipad", 70 | "size" : "40x40", 71 | "scale" : "2x" 72 | }, 73 | { 74 | "idiom" : "ipad", 75 | "size" : "76x76", 76 | "scale" : "1x" 77 | }, 78 | { 79 | "idiom" : "ipad", 80 | "size" : "76x76", 81 | "scale" : "2x" 82 | }, 83 | { 84 | "idiom" : "ipad", 85 | "size" : "83.5x83.5", 86 | "scale" : "2x" 87 | } 88 | ], 89 | "info" : { 90 | "version" : 1, 91 | "author" : "xcode" 92 | } 93 | } -------------------------------------------------------------------------------- /SMSQLiteMigration/Base.lproj/LaunchScreen.storyboard: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /SMSQLiteMigration/Base.lproj/Main.storyboard: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /SMSQLiteMigration/DBMigration/Private/SMSQLiteMigrationColumn.h: -------------------------------------------------------------------------------- 1 | // 2 | // SMSQLiteMigrationColumn.h 3 | // SMDBMigration 4 | // 5 | // Created by 00 on 2016/11/28. 6 | // Copyright © 2016年 hyman. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | /** 12 | * @note Two of the same object, that is, they have the same name. 13 | */ 14 | @interface SMSQLiteMigrationColumn : NSObject 15 | 16 | @property (nonatomic, strong) NSString *name; 17 | @property (nonatomic, strong) NSString *type; 18 | @property (nonatomic, assign) BOOL notNull; 19 | @property (nonatomic, assign) BOOL pk; 20 | @property (nonatomic, strong) NSString *defaultValue; 21 | 22 | @end 23 | -------------------------------------------------------------------------------- /SMSQLiteMigration/DBMigration/Private/SMSQLiteMigrationColumn.m: -------------------------------------------------------------------------------- 1 | // 2 | // SMSQLiteMigrationColumn.m 3 | // SMDBMigration 4 | // 5 | // Created by 00 on 2016/11/28. 6 | // Copyright © 2016年 hyman. All rights reserved. 7 | // 8 | 9 | #import "SMSQLiteMigrationColumn.h" 10 | 11 | @implementation SMSQLiteMigrationColumn 12 | 13 | - (NSUInteger)hash { 14 | return [self.name hash]; 15 | } 16 | 17 | - (BOOL)isEqual:(id)object { 18 | if (self == object) { 19 | return YES; 20 | } 21 | 22 | if ([object isKindOfClass:[SMSQLiteMigrationColumn class]] == NO) { 23 | return NO; 24 | } 25 | 26 | SMSQLiteMigrationColumn *target = object; 27 | return [self.name isEqualToString:target.name]; 28 | } 29 | 30 | @end 31 | -------------------------------------------------------------------------------- /SMSQLiteMigration/DBMigration/Private/SMSQLiteMigrationContent.h: -------------------------------------------------------------------------------- 1 | // 2 | // SMSQLiteMigrationContent.h 3 | // SMDBMigration 4 | // 5 | // Created by 00 on 2016/11/28. 6 | // Copyright © 2016年 hyman. All rights reserved. 7 | // 8 | 9 | #import 10 | #import "SMSQLiteMigrationTableTuple.h" 11 | #import "SMSQLiteMigrationTable.h" 12 | #import "SMSQLiteMigrationIndex.h" 13 | 14 | @interface SMSQLiteMigrationContent : NSObject 15 | 16 | @property (nonatomic, strong) NSArray *needDeleteTables; 17 | @property (nonatomic, strong) NSArray *needAddTables; 18 | @property (nonatomic, strong) NSArray *needModifyTuples; 19 | 20 | @property (nonatomic, strong) NSArray *needDeleteIndexes; 21 | @property (nonatomic, strong) NSArray *needAddIndexes; 22 | 23 | @end 24 | -------------------------------------------------------------------------------- /SMSQLiteMigration/DBMigration/Private/SMSQLiteMigrationContent.m: -------------------------------------------------------------------------------- 1 | // 2 | // SMSQLiteMigrationContent.m 3 | // SMDBMigration 4 | // 5 | // Created by 00 on 2016/11/28. 6 | // Copyright © 2016年 hyman. All rights reserved. 7 | // 8 | 9 | #import "SMSQLiteMigrationContent.h" 10 | 11 | @implementation SMSQLiteMigrationContent 12 | 13 | @end 14 | -------------------------------------------------------------------------------- /SMSQLiteMigration/DBMigration/Private/SMSQLiteMigrationIndex.h: -------------------------------------------------------------------------------- 1 | // 2 | // SMSQLiteMigrationIndex.h 3 | // SMSQLiteMigration 4 | // 5 | // Created by 00 on 2017/1/9. 6 | // Copyright © 2017年 00. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | /** 12 | * @note Two of the same object, that is, they have the same createSQL. 13 | */ 14 | @interface SMSQLiteMigrationIndex : NSObject 15 | 16 | @property (nonatomic, strong) NSString *name; 17 | @property (nonatomic, strong) NSString *createSQL; 18 | 19 | @end 20 | -------------------------------------------------------------------------------- /SMSQLiteMigration/DBMigration/Private/SMSQLiteMigrationIndex.m: -------------------------------------------------------------------------------- 1 | // 2 | // SMSQLiteMigrationIndex.m 3 | // SMSQLiteMigration 4 | // 5 | // Created by 00 on 2017/1/9. 6 | // Copyright © 2017年 00. All rights reserved. 7 | // 8 | 9 | #import "SMSQLiteMigrationIndex.h" 10 | 11 | @implementation SMSQLiteMigrationIndex 12 | 13 | - (NSUInteger)hash { 14 | return [self.createSQL hash]; 15 | } 16 | 17 | - (BOOL)isEqual:(id)object { 18 | if (self == object) { 19 | return YES; 20 | } 21 | 22 | if ([object isKindOfClass:[SMSQLiteMigrationIndex class]] == NO) { 23 | return NO; 24 | } 25 | 26 | SMSQLiteMigrationIndex *target = object; 27 | return [self.createSQL isEqualToString:target.createSQL]; 28 | } 29 | 30 | @end 31 | -------------------------------------------------------------------------------- /SMSQLiteMigration/DBMigration/Private/SMSQLiteMigrationTable.h: -------------------------------------------------------------------------------- 1 | // 2 | // SMSQLiteMigrationTable.h 3 | // SMDBMigration 4 | // 5 | // Created by 00 on 2016/11/28. 6 | // Copyright © 2016年 hyman. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @class SMSQLiteMigrationColumn; 12 | 13 | /** 14 | * @note Two of the same object, that is, they have the same createSQL. 15 | */ 16 | @interface SMSQLiteMigrationTable : NSObject 17 | 18 | @property (nonatomic, strong) NSString *name; 19 | @property (nonatomic, strong) NSString *createSQL; 20 | @property (nonatomic, strong) NSSet *columns; 21 | 22 | @end 23 | -------------------------------------------------------------------------------- /SMSQLiteMigration/DBMigration/Private/SMSQLiteMigrationTable.m: -------------------------------------------------------------------------------- 1 | // 2 | // SMSQLiteMigrationTable.m 3 | // SMDBMigration 4 | // 5 | // Created by 00 on 2016/11/28. 6 | // Copyright © 2016年 hyman. All rights reserved. 7 | // 8 | 9 | #import "SMSQLiteMigrationTable.h" 10 | 11 | @implementation SMSQLiteMigrationTable 12 | 13 | - (NSUInteger)hash { 14 | return [self.createSQL hash]; 15 | } 16 | 17 | - (BOOL)isEqual:(id)object { 18 | if (self == object) { 19 | return YES; 20 | } 21 | 22 | if ([object isKindOfClass:[SMSQLiteMigrationTable class]] == NO) { 23 | return NO; 24 | } 25 | 26 | SMSQLiteMigrationTable *target = object; 27 | return [self.createSQL isEqualToString:target.createSQL]; 28 | } 29 | 30 | @end 31 | -------------------------------------------------------------------------------- /SMSQLiteMigration/DBMigration/Private/SMSQLiteMigrationTableTuple.h: -------------------------------------------------------------------------------- 1 | // 2 | // SMSQLiteMigrationTableTuple.h 3 | // SMDBMigration 4 | // 5 | // Created by 00 on 2016/11/28. 6 | // Copyright © 2016年 hyman. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @class SMSQLiteMigrationTable; 12 | 13 | @interface SMSQLiteMigrationTableTuple : NSObject 14 | 15 | @property (nonatomic, strong) SMSQLiteMigrationTable *referTable; 16 | @property (nonatomic, strong) SMSQLiteMigrationTable *localTable; 17 | 18 | @end 19 | -------------------------------------------------------------------------------- /SMSQLiteMigration/DBMigration/Private/SMSQLiteMigrationTableTuple.m: -------------------------------------------------------------------------------- 1 | // 2 | // SMSQLiteMigrationTableTuple.m 3 | // SMDBMigration 4 | // 5 | // Created by 00 on 2016/11/28. 6 | // Copyright © 2016年 hyman. All rights reserved. 7 | // 8 | 9 | #import "SMSQLiteMigrationTableTuple.h" 10 | 11 | @implementation SMSQLiteMigrationTableTuple 12 | 13 | @end 14 | -------------------------------------------------------------------------------- /SMSQLiteMigration/DBMigration/SMSQLiteMigration.h: -------------------------------------------------------------------------------- 1 | // 2 | // SMSQLiteMigration.h 3 | // SMSQLiteMigration 4 | // 5 | // Created by hyman on 2016/11/27. 6 | // Copyright © 2016年 hyman. All rights reserved. 7 | // 8 | 9 | #import 10 | #import "FMDatabase.h" 11 | 12 | /** 13 | * According to the different reference database and local database, upgrade the differences 14 | * 15 | * Supports: 16 | * 17 | * 1,Add new field(the new field of constraint only support: PK, DefaultValue, NOT NULL) 18 | * 2,Add new table, Delete table, Rename table 19 | * 3,Upate index 20 | * 21 | * @note 22 | * 1,Rename table must be in accordance with the following format to rename the table name:oldTableName_to_newTableName 23 | * 24 | * (Migration, when recognition to the format of the table name, will extract the oldTableName and newTableName, and then judge whether the oldTableName exists in oldDB, if any, is renamed as newTableName;Otherwise, the oldTableName_to_newTableName will be treated as an ordinary table name) 25 | * 26 | * 2,Does not support this case: foreign key constraints exist in the database 27 | * 28 | */ 29 | @interface SMSQLiteMigration : NSObject 30 | 31 | /** 32 | the version of db 33 | 34 | @param db db 35 | 36 | @return the version of db. if error, return NSNotFound 37 | */ 38 | + (NSInteger)versionForDB:(FMDatabase *)db; 39 | 40 | /** 41 | set the db version 42 | 43 | @param version the new version 44 | @param db db 45 | */ 46 | + (BOOL)setVersion:(NSInteger)version forDB:(FMDatabase *)db; 47 | 48 | /** 49 | According to the reference database, migrate the old database.After successful migration, update oldDB version number into a new version number 50 | 51 | According to the different reference database and local database, upgrade the differences 52 | 53 | @param localDB need to migration 54 | @param referDB reference database 55 | @param newVersion the new version 56 | */ 57 | + (BOOL)migrateLocalDB:(FMDatabase *)localDB referDB:(FMDatabase *)referDB toVersion:(NSInteger)newVersion; 58 | 59 | /** 60 | Copy of the specified table data from origin DB to target DB 61 | 62 | @param tableNames need to copy 63 | @param originDB the database where the table to be copied resides 64 | @param targetDB the database where the table need to copy to 65 | 66 | @note 67 | If the corresponding table does not exist in targetDB, the method will copy the corresponding table to targetDB. 68 | Otherwise, only copy the field datas that also exists in the targetDB table 69 | */ 70 | + (BOOL)copyDataInTables:(NSArray *)tableNames fromDB:(FMDatabase *)originDB toDB:(FMDatabase *)targetDB; 71 | 72 | @end 73 | -------------------------------------------------------------------------------- /SMSQLiteMigration/DBMigration/SMSQLiteMigration.m: -------------------------------------------------------------------------------- 1 | // 2 | // SMSQLiteMigration.m 3 | // SMSQLiteMigration 4 | // 5 | // Created by hyman on 2016/11/27. 6 | // Copyright © 2016年 hyman. All rights reserved. 7 | // 8 | 9 | #import "SMSQLiteMigration.h" 10 | #import "FMDatabaseAdditions.h" 11 | #import "SMSQLiteMigrationContent.h" 12 | #import "SMSQLiteMigrationColumn.h" 13 | 14 | @implementation SMSQLiteMigration 15 | 16 | + (NSInteger)versionForDB:(FMDatabase *)db { 17 | return [db intForQuery:@"PRAGMA user_version"]; 18 | } 19 | 20 | + (BOOL)setVersion:(NSInteger)version forDB:(FMDatabase *)db { 21 | return [db executeUpdate:[NSString stringWithFormat:@"PRAGMA user_version = %ld", (unsigned long)version]]; 22 | } 23 | 24 | + (BOOL)migrateLocalDB:(FMDatabase *)localDB referDB:(FMDatabase *)referDB toVersion:(NSInteger)newVersion 25 | { 26 | if ([self versionForDB:localDB] >= newVersion) { 27 | NSLog(@"The current version of the database is UP-TO-DATE and does not require an upgrade."); 28 | return YES; 29 | } 30 | 31 | BOOL success = YES; 32 | @try { 33 | SMSQLiteMigrationContent *migrationContent = [self sm_getMigrationContentWithReferDB:referDB localDB:localDB]; 34 | 35 | [localDB beginTransaction]; 36 | 37 | if (migrationContent.needDeleteTables.count > 0) { 38 | success = [self sm_deleteTables:migrationContent.needDeleteTables inDatabase:localDB]; 39 | if (success == NO) { 40 | [self sm_printErrorInfo:[NSString stringWithFormat:@"SMSQLiteMigration---Fail to Delete table:%@", localDB.lastErrorMessage]]; 41 | } 42 | } 43 | 44 | if (success && migrationContent.needAddTables.count > 0) { 45 | success = [self sm_addTables:migrationContent.needAddTables inDatabase:localDB]; 46 | if (success == NO) { 47 | [self sm_printErrorInfo:[NSString stringWithFormat:@"SMSQLiteMigration---Fail to ADD table:%@", localDB.lastErrorMessage]]; 48 | } 49 | } 50 | 51 | if (success && migrationContent.needModifyTuples.count > 0) { 52 | success = [self sm_modifyTables:migrationContent.needModifyTuples inDatabase:localDB]; 53 | if (success == NO) { 54 | [self sm_printErrorInfo:[NSString stringWithFormat:@"SMSQLiteMigration---Fail to modify table:%@", localDB.lastErrorMessage]]; 55 | } 56 | } 57 | 58 | if (success && migrationContent.needDeleteIndexes.count > 0) { 59 | success = [self sm_deleteIndexes:migrationContent.needDeleteIndexes inDatabase:localDB]; 60 | if (success == NO) { 61 | [self sm_printErrorInfo:[NSString stringWithFormat:@"SMSQLiteMigration---Fail to Delete index:%@", localDB.lastErrorMessage]]; 62 | } 63 | } 64 | 65 | if (success && migrationContent.needAddIndexes.count > 0) { 66 | success = [self sm_addIndexes:migrationContent.needAddIndexes inDatabase:localDB]; 67 | if (success == NO) { 68 | [self sm_printErrorInfo:[NSString stringWithFormat:@"SMSQLiteMigration---Fail to ADD index:%@", localDB.lastErrorMessage]]; 69 | } 70 | } 71 | 72 | if (success) { 73 | [self setVersion:newVersion forDB:localDB]; 74 | success = [localDB commit]; 75 | } 76 | 77 | if (success == NO) { 78 | [localDB rollback]; 79 | } 80 | } @catch (NSException *exception) { 81 | success = NO; 82 | #if DEBUG 83 | @throw exception; 84 | #endif 85 | } 86 | 87 | [localDB close]; 88 | 89 | return success; 90 | } 91 | 92 | + (BOOL)copyDataInTables:(NSArray *)tableNames fromDB:(FMDatabase *)originDB toDB:(FMDatabase *)targetDB 93 | { 94 | if (tableNames.count == 0) { 95 | NSLog(@"No tables are specified for copying"); 96 | return YES; 97 | } 98 | 99 | BOOL success = YES; 100 | @try { 101 | [targetDB beginTransaction]; 102 | 103 | NSArray *originTables = [self sm_getAllTables:originDB]; 104 | success = originTables.count >= tableNames.count; 105 | if (success == NO) { 106 | [self sm_printErrorInfo:[NSString stringWithFormat:@"The total number of tables in originDB (%lu) < The number of tables to copy (%lu)", originTables.count, tableNames.count]]; 107 | } else { 108 | // Extract the tables to be copied 109 | NSMutableArray *needCopyTables = [NSMutableArray arrayWithCapacity:tableNames.count]; 110 | for (NSString *tableName in tableNames) { 111 | for (SMSQLiteMigrationTable *table in originTables) { 112 | if ([table.name isEqualToString:tableName]) { 113 | [needCopyTables addObject:table]; 114 | } 115 | } 116 | } 117 | 118 | // Start replication 119 | success = needCopyTables.count == tableNames.count; 120 | if (success == NO) { 121 | [self sm_printErrorInfo:[NSString stringWithFormat:@"The number of tables in the originDB that need to be copyed (%lu) < The number of tables to copy (%lu)", needCopyTables.count, tableNames.count]]; 122 | } else { 123 | success = [self sm_copyTables:needCopyTables fromDB:originDB toDB:targetDB]; 124 | if (success == NO) { 125 | [self sm_printErrorInfo:[NSString stringWithFormat:@"Fail to copy \nError of the original table:%@ \nError of the target table:%@", originDB.lastErrorMessage, targetDB.lastErrorMessage]]; 126 | } 127 | } 128 | } 129 | 130 | if (success) { 131 | success = [targetDB commit]; 132 | } 133 | 134 | if (success == NO) { 135 | [targetDB rollback]; 136 | } 137 | } @catch (NSException *exception) { 138 | success = NO; 139 | #if DEBUG 140 | @throw exception; 141 | #endif 142 | } 143 | 144 | [originDB close]; 145 | [targetDB close]; 146 | 147 | return success; 148 | } 149 | 150 | #pragma mark - Private 151 | + (void)sm_printErrorInfo:(NSString *)errorInfo { 152 | #if DEBUG 153 | @throw [NSException exceptionWithName:errorInfo reason:nil userInfo:nil]; 154 | #endif 155 | } 156 | 157 | #pragma mark -- Extract Diff 158 | + (SMSQLiteMigrationContent *)sm_getMigrationContentWithReferDB:(FMDatabase *)referDB 159 | localDB:(FMDatabase *)localDB 160 | { 161 | SMSQLiteMigrationContent *migrationContent = [SMSQLiteMigrationContent new]; 162 | 163 | [self sm_extractNeedMigrationTablesToContent:migrationContent 164 | withReferDB:referDB 165 | localDB:localDB]; 166 | 167 | [self sm_extractNeedMigrationIndexesToContent:migrationContent 168 | withReferDB:referDB 169 | localDB:localDB]; 170 | 171 | return migrationContent; 172 | } 173 | 174 | + (void)sm_extractNeedMigrationTablesToContent:(SMSQLiteMigrationContent *)migrationContent 175 | withReferDB:(FMDatabase *)referDB 176 | localDB:(FMDatabase *)localDB 177 | { 178 | NSMutableArray *localTables = [[self sm_getAllTables:localDB] mutableCopy]; 179 | NSMutableArray *referTables = [[self sm_getAllTables:referDB] mutableCopy]; 180 | 181 | /** 182 | * Remove tables without any changes (Two tables with the same createSQL are the same) 183 | */ 184 | NSMutableIndexSet *noChangedIndexesForRefer = [NSMutableIndexSet indexSet]; 185 | NSMutableIndexSet *noChangedIndexesForLocal = [NSMutableIndexSet indexSet]; 186 | [referTables enumerateObjectsUsingBlock:^(SMSQLiteMigrationTable *referTable, NSUInteger idx, BOOL * _Nonnull stop) { 187 | NSUInteger localNoChangeIndex = [localTables indexOfObject:referTable]; 188 | if (localNoChangeIndex != NSNotFound) { 189 | [noChangedIndexesForRefer addIndex:idx]; 190 | [noChangedIndexesForLocal addIndex:localNoChangeIndex]; 191 | } 192 | }]; 193 | [referTables removeObjectsAtIndexes:noChangedIndexesForRefer]; 194 | [localTables removeObjectsAtIndexes:noChangedIndexesForLocal]; 195 | 196 | /** 197 | * Extract the tables that need to add, delete, modify, rename 198 | */ 199 | NSMutableArray *addedTables = [NSMutableArray array]; 200 | NSMutableArray *modifiedTuples = [NSMutableArray array]; 201 | for (SMSQLiteMigrationTable *referTable in referTables) { 202 | 203 | // Extract the table to be renamed 204 | NSRange range = [[referTable.name lowercaseString] rangeOfString:@"_to_"]; 205 | if ((range.location != NSNotFound && range.location > 0) && (range.length + range.location <= referTable.name.length)) 206 | { 207 | NSString *oldTableName = [referTable.name substringToIndex:range.location]; 208 | NSString *newTableName = [referTable.name substringFromIndex:range.location + range.length]; 209 | NSInteger localTableIndex = [self sm_indexOfTableName:oldTableName inTables:localTables]; 210 | if (localTableIndex != NSNotFound) { 211 | referTable.name = newTableName; 212 | 213 | SMSQLiteMigrationTableTuple *tuple = [SMSQLiteMigrationTableTuple new]; 214 | tuple.referTable = referTable; 215 | tuple.localTable = localTables[localTableIndex]; 216 | [modifiedTuples addObject:tuple]; 217 | 218 | [localTables removeObjectAtIndex:localTableIndex]; 219 | continue; 220 | } 221 | } 222 | 223 | // Extract the table to be modifiyed, added, deleted 224 | NSInteger modifiedIndex = [self sm_indexOfTableName:referTable.name inTables:localTables]; 225 | if (modifiedIndex != NSNotFound) { 226 | SMSQLiteMigrationTableTuple *tuple = [SMSQLiteMigrationTableTuple new]; 227 | tuple.referTable = referTable; 228 | tuple.localTable = localTables[modifiedIndex]; 229 | [modifiedTuples addObject:tuple]; 230 | 231 | // Remove the table that need to be modified, the last remaining table is to be deleted table 232 | [localTables removeObjectAtIndex:modifiedIndex]; 233 | } else { 234 | [addedTables addObject:referTable]; 235 | } 236 | } 237 | 238 | 239 | migrationContent.needDeleteTables = localTables; 240 | migrationContent.needAddTables = addedTables; 241 | migrationContent.needModifyTuples = modifiedTuples; 242 | } 243 | 244 | + (void)sm_extractNeedMigrationIndexesToContent:(SMSQLiteMigrationContent *)migrationContent 245 | withReferDB:(FMDatabase *)referDB 246 | localDB:(FMDatabase *)localDB 247 | { 248 | NSArray *localIndexes = [self sm_getAllIndexes:localDB]; 249 | NSArray *referIndexes = [self sm_getAllIndexes:referDB]; 250 | 251 | NSMutableArray *needAddedIndexes = [NSMutableArray array]; 252 | NSMutableArray *needDeletedIndexes = [localIndexes mutableCopy]; 253 | for (SMSQLiteMigrationIndex *referIndex in referIndexes) { 254 | NSInteger indexOfLocalIndex = [self sm_indexOfIndexName:referIndex.name inIndexes:localIndexes]; 255 | if (indexOfLocalIndex == NSNotFound) { 256 | [needAddedIndexes addObject:referIndex]; 257 | } else { 258 | [needDeletedIndexes removeObjectAtIndex:indexOfLocalIndex]; 259 | } 260 | } 261 | 262 | migrationContent.needAddIndexes = needAddedIndexes; 263 | migrationContent.needDeleteIndexes = needDeletedIndexes; 264 | } 265 | 266 | + (NSArray *)sm_getAllTables:(FMDatabase *)database { 267 | NSMutableArray *tables = [@[] mutableCopy]; 268 | FMResultSet *tableResults = [database executeQuery:@"select name, sql from sqlite_master where type = 'table' and name != 'sqlite_sequence'"]; 269 | while ([tableResults next]) { 270 | SMSQLiteMigrationTable *table = [SMSQLiteMigrationTable new]; 271 | table.name = [[tableResults stringForColumn:@"name"] lowercaseString]; 272 | table.createSQL = [[tableResults stringForColumn:@"sql"] lowercaseString]; 273 | 274 | NSMutableSet *columns = [NSMutableSet set]; 275 | FMResultSet *columnResult = [database executeQuery:[NSString stringWithFormat:@"PRAGMA table_info(%@)", table.name]]; 276 | while ([columnResult next]) { 277 | SMSQLiteMigrationColumn *column = [SMSQLiteMigrationColumn new]; 278 | column.name = [[columnResult stringForColumn:@"name"] lowercaseString]; 279 | column.type = [[columnResult stringForColumn:@"type"] lowercaseString]; 280 | column.pk = [columnResult intForColumn:@"pk"] == 1; 281 | column.notNull = [columnResult intForColumn:@"notnull"] == 1; 282 | column.defaultValue = [columnResult stringForColumn:@"dflt_value"]; 283 | [columns addObject:column]; 284 | } 285 | table.columns = columns; 286 | 287 | [tables addObject:table]; 288 | } 289 | return tables; 290 | } 291 | 292 | + (NSArray *)sm_getAllIndexes:(FMDatabase *)database { 293 | NSMutableArray *indexes = [@[] mutableCopy]; 294 | FMResultSet *tableResults = [database executeQuery:@"select name, sql from sqlite_master where type = 'index' and sql is not null"]; 295 | while ([tableResults next]) { 296 | SMSQLiteMigrationIndex *index = [SMSQLiteMigrationIndex new]; 297 | index.name = [[tableResults stringForColumn:@"name"] lowercaseString]; 298 | index.createSQL = [[tableResults stringForColumn:@"sql"] lowercaseString]; 299 | [indexes addObject:index]; 300 | } 301 | return indexes; 302 | } 303 | 304 | + (NSInteger)sm_indexOfTableName:(NSString *)tableName inTables:(NSArray *)tables { 305 | NSInteger index = NSNotFound; 306 | for (NSInteger i = 0; i < tables.count; i++) { 307 | if ([tableName isEqualToString:tables[i].name]) { 308 | index = i; 309 | break; 310 | } 311 | } 312 | return index; 313 | } 314 | 315 | + (NSInteger)sm_indexOfIndexName:(NSString *)indexName inIndexes:(NSArray *)indexes 316 | { 317 | NSInteger index = NSNotFound; 318 | for (NSInteger i = 0; i < indexes.count; i++) { 319 | if ([indexName isEqualToString:indexes[i].name]) { 320 | index = i; 321 | break; 322 | } 323 | } 324 | return index; 325 | } 326 | 327 | #pragma mark -- Migration Operation 328 | + (BOOL)sm_deleteIndexes:(NSArray *)indexes inDatabase:(FMDatabase *)database { 329 | NSMutableString *SQL = [@"" mutableCopy]; 330 | for (SMSQLiteMigrationIndex *index in indexes) { 331 | NSString *deleteSQL = [NSString stringWithFormat:@"DROP INDEX %@", index.name]; 332 | [SQL appendFormat:@"%@;", deleteSQL]; 333 | } 334 | return [database executeStatements:SQL]; 335 | } 336 | 337 | + (BOOL)sm_addIndexes:(NSArray *)indexes inDatabase:(FMDatabase *)database { 338 | NSMutableString *SQL = [@"" mutableCopy]; 339 | for (SMSQLiteMigrationIndex *index in indexes) { 340 | [SQL appendFormat:@"%@;", index.createSQL]; 341 | } 342 | return [database executeStatements:SQL]; 343 | } 344 | 345 | + (BOOL)sm_deleteTables:(NSArray *)tables inDatabase:(FMDatabase *)database { 346 | NSMutableString *SQL = [@"" mutableCopy]; 347 | for (SMSQLiteMigrationTable *table in tables) { 348 | NSString *deleteSQL = [NSString stringWithFormat:@"DROP TABLE %@", table.name]; 349 | [SQL appendFormat:@"%@;", deleteSQL]; 350 | } 351 | return [database executeStatements:SQL]; 352 | } 353 | 354 | + (BOOL)sm_addTables:(NSArray *)tables inDatabase:(FMDatabase *)database { 355 | NSMutableString *SQL = [@"" mutableCopy]; 356 | for (SMSQLiteMigrationTable *table in tables) { 357 | [SQL appendFormat:@"%@;", table.createSQL]; 358 | } 359 | return [database executeStatements:SQL]; 360 | } 361 | 362 | + (BOOL)sm_modifyTables:(NSArray *)modifiedTuples inDatabase:(FMDatabase *)databse { 363 | BOOL success = YES; 364 | for (SMSQLiteMigrationTableTuple *tuple in modifiedTuples) { 365 | 366 | // Rename the table first 367 | if ([tuple.referTable.name isEqualToString:tuple.localTable.name] == NO) { 368 | success = [self sm_renameOldTable:tuple.localTable.name toNewTable:tuple.referTable.name inDatabase:databse]; 369 | if (success == NO) { 370 | break; 371 | } 372 | 373 | tuple.localTable.name = tuple.referTable.name; 374 | } 375 | 376 | // Processes new fields 377 | NSMutableSet *addedColumns = [tuple.referTable.columns mutableCopy]; 378 | [addedColumns minusSet:tuple.localTable.columns]; 379 | if (addedColumns.count > 0) { 380 | success = [self sm_addColumns:addedColumns inTable:tuple.localTable database:databse]; 381 | if (success == NO) { 382 | break; 383 | } 384 | } 385 | } 386 | return success; 387 | } 388 | 389 | + (BOOL)sm_renameOldTable:(NSString *)oldTableName toNewTable:(NSString *)newTableName inDatabase:(FMDatabase *)database 390 | { 391 | NSString *renameSQL = [NSString stringWithFormat:@"ALTER TABLE %@ RENAME TO %@", oldTableName, newTableName]; 392 | return [database executeUpdate:renameSQL]; 393 | } 394 | 395 | + (BOOL)sm_addColumns:(NSSet *)columns inTable:(SMSQLiteMigrationTable *)table database:(FMDatabase *)database 396 | { 397 | NSMutableString *SQL = [@"" mutableCopy]; 398 | for (SMSQLiteMigrationColumn *column in columns) { 399 | NSString *constraint = @""; 400 | if (column.pk) { 401 | constraint = [constraint stringByAppendingString:@" PRIMARY KEY"]; 402 | } 403 | if (column.notNull) { 404 | constraint = [constraint stringByAppendingString:@" NOT NULL"]; 405 | } 406 | 407 | // Put the default constraint to the end 408 | if (column.defaultValue.length > 0) { 409 | constraint = [constraint stringByAppendingFormat:@" DEFAULT %@", column.defaultValue]; 410 | } 411 | 412 | NSString *addColumnSQL = [NSString stringWithFormat:@"ALTER TABLE %@ ADD %@ %@%@", table.name, column.name, column.type, constraint]; 413 | [SQL appendFormat:@"%@;", addColumnSQL]; 414 | } 415 | return [database executeStatements:SQL]; 416 | } 417 | 418 | #pragma mark -- Copy Table 419 | + (BOOL)sm_copyTables:(NSArray *)needCopyTables fromDB:(FMDatabase *)originDB toDB:(FMDatabase *)targetDB 420 | { 421 | BOOL success = YES; 422 | 423 | NSArray *targetTables = [self sm_getAllTables:targetDB]; 424 | 425 | /** 426 | * 1,Copy the table structure 2,Migrate the data for the corresponding table 427 | */ 428 | for (SMSQLiteMigrationTable *table in needCopyTables) 429 | { 430 | // If the table does not exist in the targetDB then only copy the table structure 431 | if ([self sm_indexOfTableName:table.name inTables:targetTables] == NSNotFound) 432 | { 433 | success = [targetDB executeUpdate:table.createSQL]; 434 | if (success == NO) 435 | { 436 | [self sm_printErrorInfo:[NSString stringWithFormat:@"SMSQLiteMigration--Fail to copy the table structure:%@", targetDB.lastErrorMessage]]; 437 | break; 438 | } 439 | } 440 | 441 | long totalCount = [originDB longForQuery:[NSString stringWithFormat:@"SELECT count(*) FROM %@", table.name]]; 442 | if (totalCount <= 0) { 443 | continue; 444 | } 445 | 446 | // Migrate the datas 447 | long loadedCount = 0; 448 | int pageSize = 100; 449 | 450 | while (loadedCount < totalCount) { 451 | FMResultSet *fetchResult = [originDB executeQuery:[NSString stringWithFormat:@"SELECT * FROM %@ LIMIT %d OFFSET %ld", table.name, pageSize, loadedCount]]; 452 | while ([fetchResult next]) { 453 | NSMutableDictionary *parameters = [NSMutableDictionary dictionaryWithCapacity:table.columns.count]; 454 | 455 | NSMutableArray *keys = [NSMutableArray arrayWithCapacity:table.columns.count]; 456 | NSMutableArray *vals = [NSMutableArray arrayWithCapacity:table.columns.count]; 457 | for (SMSQLiteMigrationColumn *column in table.columns) { 458 | [keys addObject:column.name]; 459 | [vals addObject:[NSString stringWithFormat:@":%@", column.name]]; 460 | 461 | id obj = [fetchResult objectForColumnName:column.name]; 462 | parameters[column.name] = obj ?: [NSNull null]; 463 | } 464 | 465 | NSString *columnInfos = [keys componentsJoinedByString:@","]; 466 | NSString *valueInfos = [vals componentsJoinedByString:@","]; 467 | NSString *insertSQL = [NSString stringWithFormat:@"INSERT INTO %@ (%@) VALUES (%@)", table.name, columnInfos, valueInfos]; 468 | 469 | success = [targetDB executeUpdate:insertSQL withParameterDictionary:parameters]; 470 | if (success == NO) { 471 | [self sm_printErrorInfo:[NSString stringWithFormat:@"SMSQLiteMigration--Fail to migrate the datas:%@", targetDB.lastErrorMessage]]; 472 | goto END_COPY_LOOP; 473 | } 474 | } 475 | 476 | loadedCount += pageSize; 477 | } 478 | } 479 | 480 | END_COPY_LOOP: 481 | 482 | return success; 483 | } 484 | 485 | @end 486 | -------------------------------------------------------------------------------- /SMSQLiteMigration/FMDatabase/FMDB.h: -------------------------------------------------------------------------------- 1 | #import "FMDatabase.h" 2 | #import "FMResultSet.h" 3 | #import "FMDatabaseAdditions.h" 4 | #import "FMDatabaseQueue.h" 5 | #import "FMDatabasePool.h" 6 | -------------------------------------------------------------------------------- /SMSQLiteMigration/FMDatabase/FMDatabase.h: -------------------------------------------------------------------------------- 1 | #import 2 | #import "sqlite3.h" 3 | #import "FMResultSet.h" 4 | #import "FMDatabasePool.h" 5 | 6 | 7 | #if ! __has_feature(objc_arc) 8 | #define FMDBAutorelease(__v) ([__v autorelease]); 9 | #define FMDBReturnAutoreleased FMDBAutorelease 10 | 11 | #define FMDBRetain(__v) ([__v retain]); 12 | #define FMDBReturnRetained FMDBRetain 13 | 14 | #define FMDBRelease(__v) ([__v release]); 15 | 16 | #define FMDBDispatchQueueRelease(__v) (dispatch_release(__v)); 17 | #else 18 | // -fobjc-arc 19 | #define FMDBAutorelease(__v) 20 | #define FMDBReturnAutoreleased(__v) (__v) 21 | 22 | #define FMDBRetain(__v) 23 | #define FMDBReturnRetained(__v) (__v) 24 | 25 | #define FMDBRelease(__v) 26 | 27 | // If OS_OBJECT_USE_OBJC=1, then the dispatch objects will be treated like ObjC objects 28 | // and will participate in ARC. 29 | // See the section on "Dispatch Queues and Automatic Reference Counting" in "Grand Central Dispatch (GCD) Reference" for details. 30 | #if OS_OBJECT_USE_OBJC 31 | #define FMDBDispatchQueueRelease(__v) 32 | #else 33 | #define FMDBDispatchQueueRelease(__v) (dispatch_release(__v)); 34 | #endif 35 | #endif 36 | 37 | #if !__has_feature(objc_instancetype) 38 | #define instancetype id 39 | #endif 40 | 41 | 42 | typedef int(^FMDBExecuteStatementsCallbackBlock)(NSDictionary *resultsDictionary); 43 | 44 | 45 | /** A SQLite ([http://sqlite.org/](http://sqlite.org/)) Objective-C wrapper. 46 | 47 | ### Usage 48 | The three main classes in FMDB are: 49 | 50 | - `FMDatabase` - Represents a single SQLite database. Used for executing SQL statements. 51 | - `` - Represents the results of executing a query on an `FMDatabase`. 52 | - `` - If you want to perform queries and updates on multiple threads, you'll want to use this class. 53 | 54 | ### See also 55 | 56 | - `` - A pool of `FMDatabase` objects. 57 | - `` - A wrapper for `sqlite_stmt`. 58 | 59 | ### External links 60 | 61 | - [FMDB on GitHub](https://github.com/ccgus/fmdb) including introductory documentation 62 | - [SQLite web site](http://sqlite.org/) 63 | - [FMDB mailing list](http://groups.google.com/group/fmdb) 64 | - [SQLite FAQ](http://www.sqlite.org/faq.html) 65 | 66 | @warning Do not instantiate a single `FMDatabase` object and use it across multiple threads. Instead, use ``. 67 | 68 | */ 69 | 70 | #pragma clang diagnostic push 71 | #pragma clang diagnostic ignored "-Wobjc-interface-ivars" 72 | 73 | 74 | @interface FMDatabase : NSObject { 75 | 76 | sqlite3* _db; 77 | NSString* _databasePath; 78 | BOOL _logsErrors; 79 | BOOL _crashOnErrors; 80 | BOOL _traceExecution; 81 | BOOL _checkedOut; 82 | BOOL _shouldCacheStatements; 83 | BOOL _isExecutingStatement; 84 | BOOL _inTransaction; 85 | NSTimeInterval _maxBusyRetryTimeInterval; 86 | NSTimeInterval _startBusyRetryTime; 87 | 88 | NSMutableDictionary *_cachedStatements; 89 | NSMutableSet *_openResultSets; 90 | NSMutableSet *_openFunctions; 91 | 92 | NSDateFormatter *_dateFormat; 93 | } 94 | 95 | ///----------------- 96 | /// @name Properties 97 | ///----------------- 98 | 99 | /** Whether should trace execution */ 100 | 101 | @property (atomic, assign) BOOL traceExecution; 102 | 103 | /** Whether checked out or not */ 104 | 105 | @property (atomic, assign) BOOL checkedOut; 106 | 107 | /** Crash on errors */ 108 | 109 | @property (atomic, assign) BOOL crashOnErrors; 110 | 111 | /** Logs errors */ 112 | 113 | @property (atomic, assign) BOOL logsErrors; 114 | 115 | /** Dictionary of cached statements */ 116 | 117 | @property (atomic, retain) NSMutableDictionary *cachedStatements; 118 | 119 | ///--------------------- 120 | /// @name Initialization 121 | ///--------------------- 122 | 123 | /** Create a `FMDatabase` object. 124 | 125 | An `FMDatabase` is created with a path to a SQLite database file. This path can be one of these three: 126 | 127 | 1. A file system path. The file does not have to exist on disk. If it does not exist, it is created for you. 128 | 2. An empty string (`@""`). An empty database is created at a temporary location. This database is deleted with the `FMDatabase` connection is closed. 129 | 3. `nil`. An in-memory database is created. This database will be destroyed with the `FMDatabase` connection is closed. 130 | 131 | For example, to create/open a database in your Mac OS X `tmp` folder: 132 | 133 | FMDatabase *db = [FMDatabase databaseWithPath:@"/tmp/tmp.db"]; 134 | 135 | Or, in iOS, you might open a database in the app's `Documents` directory: 136 | 137 | NSString *docsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0]; 138 | NSString *dbPath = [docsPath stringByAppendingPathComponent:@"test.db"]; 139 | FMDatabase *db = [FMDatabase databaseWithPath:dbPath]; 140 | 141 | (For more information on temporary and in-memory databases, read the sqlite documentation on the subject: [http://www.sqlite.org/inmemorydb.html](http://www.sqlite.org/inmemorydb.html)) 142 | 143 | @param inPath Path of database file 144 | 145 | @return `FMDatabase` object if successful; `nil` if failure. 146 | 147 | */ 148 | 149 | + (instancetype)databaseWithPath:(NSString*)inPath; 150 | 151 | /** Initialize a `FMDatabase` object. 152 | 153 | An `FMDatabase` is created with a path to a SQLite database file. This path can be one of these three: 154 | 155 | 1. A file system path. The file does not have to exist on disk. If it does not exist, it is created for you. 156 | 2. An empty string (`@""`). An empty database is created at a temporary location. This database is deleted with the `FMDatabase` connection is closed. 157 | 3. `nil`. An in-memory database is created. This database will be destroyed with the `FMDatabase` connection is closed. 158 | 159 | For example, to create/open a database in your Mac OS X `tmp` folder: 160 | 161 | FMDatabase *db = [FMDatabase databaseWithPath:@"/tmp/tmp.db"]; 162 | 163 | Or, in iOS, you might open a database in the app's `Documents` directory: 164 | 165 | NSString *docsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0]; 166 | NSString *dbPath = [docsPath stringByAppendingPathComponent:@"test.db"]; 167 | FMDatabase *db = [FMDatabase databaseWithPath:dbPath]; 168 | 169 | (For more information on temporary and in-memory databases, read the sqlite documentation on the subject: [http://www.sqlite.org/inmemorydb.html](http://www.sqlite.org/inmemorydb.html)) 170 | 171 | @param inPath Path of database file 172 | 173 | @return `FMDatabase` object if successful; `nil` if failure. 174 | 175 | */ 176 | 177 | - (instancetype)initWithPath:(NSString*)inPath; 178 | 179 | 180 | ///----------------------------------- 181 | /// @name Opening and closing database 182 | ///----------------------------------- 183 | 184 | /** Opening a new database connection 185 | 186 | The database is opened for reading and writing, and is created if it does not already exist. 187 | 188 | @return `YES` if successful, `NO` on error. 189 | 190 | @see [sqlite3_open()](http://sqlite.org/c3ref/open.html) 191 | @see openWithFlags: 192 | @see close 193 | */ 194 | 195 | - (BOOL)open; 196 | 197 | /** Opening a new database connection with flags 198 | 199 | @param flags one of the following three values, optionally combined with the `SQLITE_OPEN_NOMUTEX`, `SQLITE_OPEN_FULLMUTEX`, `SQLITE_OPEN_SHAREDCACHE`, `SQLITE_OPEN_PRIVATECACHE`, and/or `SQLITE_OPEN_URI` flags: 200 | 201 | `SQLITE_OPEN_READONLY` 202 | 203 | The database is opened in read-only mode. If the database does not already exist, an error is returned. 204 | 205 | `SQLITE_OPEN_READWRITE` 206 | 207 | The database is opened for reading and writing if possible, or reading only if the file is write protected by the operating system. In either case the database must already exist, otherwise an error is returned. 208 | 209 | `SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE` 210 | 211 | The database is opened for reading and writing, and is created if it does not already exist. This is the behavior that is always used for `open` method. 212 | 213 | @return `YES` if successful, `NO` on error. 214 | 215 | @see [sqlite3_open_v2()](http://sqlite.org/c3ref/open.html) 216 | @see open 217 | @see close 218 | */ 219 | 220 | #if SQLITE_VERSION_NUMBER >= 3005000 221 | - (BOOL)openWithFlags:(int)flags; 222 | #endif 223 | 224 | /** Closing a database connection 225 | 226 | @return `YES` if success, `NO` on error. 227 | 228 | @see [sqlite3_close()](http://sqlite.org/c3ref/close.html) 229 | @see open 230 | @see openWithFlags: 231 | */ 232 | 233 | - (BOOL)close; 234 | 235 | /** Test to see if we have a good connection to the database. 236 | 237 | This will confirm whether: 238 | 239 | - is database open 240 | - if open, it will try a simple SELECT statement and confirm that it succeeds. 241 | 242 | @return `YES` if everything succeeds, `NO` on failure. 243 | */ 244 | 245 | - (BOOL)goodConnection; 246 | 247 | 248 | ///---------------------- 249 | /// @name Perform updates 250 | ///---------------------- 251 | 252 | /** Execute single update statement 253 | 254 | This method executes a single SQL update statement (i.e. any SQL that does not return results, such as `UPDATE`, `INSERT`, or `DELETE`. This method employs [`sqlite3_prepare_v2`](http://sqlite.org/c3ref/prepare.html), [`sqlite3_bind`](http://sqlite.org/c3ref/bind_blob.html) to bind values to `?` placeholders in the SQL with the optional list of parameters, and [`sqlite_step`](http://sqlite.org/c3ref/step.html) to perform the update. 255 | 256 | The optional values provided to this method should be objects (e.g. `NSString`, `NSNumber`, `NSNull`, `NSDate`, and `NSData` objects), not fundamental data types (e.g. `int`, `long`, `NSInteger`, etc.). This method automatically handles the aforementioned object types, and all other object types will be interpreted as text values using the object's `description` method. 257 | 258 | @param sql The SQL to be performed, with optional `?` placeholders. 259 | 260 | @param outErr A reference to the `NSError` pointer to be updated with an auto released `NSError` object if an error if an error occurs. If `nil`, no `NSError` object will be returned. 261 | 262 | @param ... Optional parameters to bind to `?` placeholders in the SQL statement. These should be Objective-C objects (e.g. `NSString`, `NSNumber`, etc.), not fundamental C data types (e.g. `int`, `char *`, etc.). 263 | 264 | @return `YES` upon success; `NO` upon failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. 265 | 266 | @see lastError 267 | @see lastErrorCode 268 | @see lastErrorMessage 269 | @see [`sqlite3_bind`](http://sqlite.org/c3ref/bind_blob.html) 270 | */ 271 | 272 | - (BOOL)executeUpdate:(NSString*)sql withErrorAndBindings:(NSError**)outErr, ...; 273 | 274 | /** Execute single update statement 275 | 276 | @see executeUpdate:withErrorAndBindings: 277 | 278 | @warning **Deprecated**: Please use `` instead. 279 | */ 280 | 281 | - (BOOL)update:(NSString*)sql withErrorAndBindings:(NSError**)outErr, ... __attribute__ ((deprecated)); 282 | 283 | /** Execute single update statement 284 | 285 | This method executes a single SQL update statement (i.e. any SQL that does not return results, such as `UPDATE`, `INSERT`, or `DELETE`. This method employs [`sqlite3_prepare_v2`](http://sqlite.org/c3ref/prepare.html), [`sqlite3_bind`](http://sqlite.org/c3ref/bind_blob.html) to bind values to `?` placeholders in the SQL with the optional list of parameters, and [`sqlite_step`](http://sqlite.org/c3ref/step.html) to perform the update. 286 | 287 | The optional values provided to this method should be objects (e.g. `NSString`, `NSNumber`, `NSNull`, `NSDate`, and `NSData` objects), not fundamental data types (e.g. `int`, `long`, `NSInteger`, etc.). This method automatically handles the aforementioned object types, and all other object types will be interpreted as text values using the object's `description` method. 288 | 289 | @param sql The SQL to be performed, with optional `?` placeholders. 290 | 291 | @param ... Optional parameters to bind to `?` placeholders in the SQL statement. These should be Objective-C objects (e.g. `NSString`, `NSNumber`, etc.), not fundamental C data types (e.g. `int`, `char *`, etc.). 292 | 293 | @return `YES` upon success; `NO` upon failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. 294 | 295 | @see lastError 296 | @see lastErrorCode 297 | @see lastErrorMessage 298 | @see [`sqlite3_bind`](http://sqlite.org/c3ref/bind_blob.html) 299 | 300 | @note This technique supports the use of `?` placeholders in the SQL, automatically binding any supplied value parameters to those placeholders. This approach is more robust than techniques that entail using `stringWithFormat` to manually build SQL statements, which can be problematic if the values happened to include any characters that needed to be quoted. 301 | 302 | @note If you want to use this from Swift, please note that you must include `FMDatabaseVariadic.swift` in your project. Without that, you cannot use this method directly, and instead have to use methods such as ``. 303 | */ 304 | 305 | - (BOOL)executeUpdate:(NSString*)sql, ...; 306 | 307 | /** Execute single update statement 308 | 309 | This method executes a single SQL update statement (i.e. any SQL that does not return results, such as `UPDATE`, `INSERT`, or `DELETE`. This method employs [`sqlite3_prepare_v2`](http://sqlite.org/c3ref/prepare.html) and [`sqlite_step`](http://sqlite.org/c3ref/step.html) to perform the update. Unlike the other `executeUpdate` methods, this uses printf-style formatters (e.g. `%s`, `%d`, etc.) to build the SQL. Do not use `?` placeholders in the SQL if you use this method. 310 | 311 | @param format The SQL to be performed, with `printf`-style escape sequences. 312 | 313 | @param ... Optional parameters to bind to use in conjunction with the `printf`-style escape sequences in the SQL statement. 314 | 315 | @return `YES` upon success; `NO` upon failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. 316 | 317 | @see executeUpdate: 318 | @see lastError 319 | @see lastErrorCode 320 | @see lastErrorMessage 321 | 322 | @note This method does not technically perform a traditional printf-style replacement. What this method actually does is replace the printf-style percent sequences with a SQLite `?` placeholder, and then bind values to that placeholder. Thus the following command 323 | 324 | [db executeUpdateWithFormat:@"INSERT INTO test (name) VALUES (%@)", @"Gus"]; 325 | 326 | is actually replacing the `%@` with `?` placeholder, and then performing something equivalent to `` 327 | 328 | [db executeUpdate:@"INSERT INTO test (name) VALUES (?)", @"Gus"]; 329 | 330 | There are two reasons why this distinction is important. First, the printf-style escape sequences can only be used where it is permissible to use a SQLite `?` placeholder. You can use it only for values in SQL statements, but not for table names or column names or any other non-value context. This method also cannot be used in conjunction with `pragma` statements and the like. Second, note the lack of quotation marks in the SQL. The `VALUES` clause was _not_ `VALUES ('%@')` (like you might have to do if you built a SQL statement using `NSString` method `stringWithFormat`), but rather simply `VALUES (%@)`. 331 | */ 332 | 333 | - (BOOL)executeUpdateWithFormat:(NSString *)format, ... NS_FORMAT_FUNCTION(1,2); 334 | 335 | /** Execute single update statement 336 | 337 | This method executes a single SQL update statement (i.e. any SQL that does not return results, such as `UPDATE`, `INSERT`, or `DELETE`. This method employs [`sqlite3_prepare_v2`](http://sqlite.org/c3ref/prepare.html) and [`sqlite3_bind`](http://sqlite.org/c3ref/bind_blob.html) binding any `?` placeholders in the SQL with the optional list of parameters. 338 | 339 | The optional values provided to this method should be objects (e.g. `NSString`, `NSNumber`, `NSNull`, `NSDate`, and `NSData` objects), not fundamental data types (e.g. `int`, `long`, `NSInteger`, etc.). This method automatically handles the aforementioned object types, and all other object types will be interpreted as text values using the object's `description` method. 340 | 341 | @param sql The SQL to be performed, with optional `?` placeholders. 342 | 343 | @param arguments A `NSArray` of objects to be used when binding values to the `?` placeholders in the SQL statement. 344 | 345 | @return `YES` upon success; `NO` upon failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. 346 | 347 | @see lastError 348 | @see lastErrorCode 349 | @see lastErrorMessage 350 | */ 351 | 352 | - (BOOL)executeUpdate:(NSString*)sql withArgumentsInArray:(NSArray *)arguments; 353 | 354 | /** Execute single update statement 355 | 356 | This method executes a single SQL update statement (i.e. any SQL that does not return results, such as `UPDATE`, `INSERT`, or `DELETE`. This method employs [`sqlite3_prepare_v2`](http://sqlite.org/c3ref/prepare.html) and [`sqlite_step`](http://sqlite.org/c3ref/step.html) to perform the update. Unlike the other `executeUpdate` methods, this uses printf-style formatters (e.g. `%s`, `%d`, etc.) to build the SQL. 357 | 358 | The optional values provided to this method should be objects (e.g. `NSString`, `NSNumber`, `NSNull`, `NSDate`, and `NSData` objects), not fundamental data types (e.g. `int`, `long`, `NSInteger`, etc.). This method automatically handles the aforementioned object types, and all other object types will be interpreted as text values using the object's `description` method. 359 | 360 | @param sql The SQL to be performed, with optional `?` placeholders. 361 | 362 | @param arguments A `NSDictionary` of objects keyed by column names that will be used when binding values to the `?` placeholders in the SQL statement. 363 | 364 | @return `YES` upon success; `NO` upon failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. 365 | 366 | @see lastError 367 | @see lastErrorCode 368 | @see lastErrorMessage 369 | */ 370 | 371 | - (BOOL)executeUpdate:(NSString*)sql withParameterDictionary:(NSDictionary *)arguments; 372 | 373 | 374 | /** Execute single update statement 375 | 376 | This method executes a single SQL update statement (i.e. any SQL that does not return results, such as `UPDATE`, `INSERT`, or `DELETE`. This method employs [`sqlite3_prepare_v2`](http://sqlite.org/c3ref/prepare.html) and [`sqlite_step`](http://sqlite.org/c3ref/step.html) to perform the update. Unlike the other `executeUpdate` methods, this uses printf-style formatters (e.g. `%s`, `%d`, etc.) to build the SQL. 377 | 378 | The optional values provided to this method should be objects (e.g. `NSString`, `NSNumber`, `NSNull`, `NSDate`, and `NSData` objects), not fundamental data types (e.g. `int`, `long`, `NSInteger`, etc.). This method automatically handles the aforementioned object types, and all other object types will be interpreted as text values using the object's `description` method. 379 | 380 | @param sql The SQL to be performed, with optional `?` placeholders. 381 | 382 | @param args A `va_list` of arguments. 383 | 384 | @return `YES` upon success; `NO` upon failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. 385 | 386 | @see lastError 387 | @see lastErrorCode 388 | @see lastErrorMessage 389 | */ 390 | 391 | - (BOOL)executeUpdate:(NSString*)sql withVAList: (va_list)args; 392 | 393 | /** Execute multiple SQL statements 394 | 395 | This executes a series of SQL statements that are combined in a single string (e.g. the SQL generated by the `sqlite3` command line `.dump` command). This accepts no value parameters, but rather simply expects a single string with multiple SQL statements, each terminated with a semicolon. This uses `sqlite3_exec`. 396 | 397 | @param sql The SQL to be performed 398 | 399 | @return `YES` upon success; `NO` upon failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. 400 | 401 | @see executeStatements:withResultBlock: 402 | @see [sqlite3_exec()](http://sqlite.org/c3ref/exec.html) 403 | 404 | */ 405 | 406 | - (BOOL)executeStatements:(NSString *)sql; 407 | 408 | /** Execute multiple SQL statements with callback handler 409 | 410 | This executes a series of SQL statements that are combined in a single string (e.g. the SQL generated by the `sqlite3` command line `.dump` command). This accepts no value parameters, but rather simply expects a single string with multiple SQL statements, each terminated with a semicolon. This uses `sqlite3_exec`. 411 | 412 | @param sql The SQL to be performed. 413 | @param block A block that will be called for any result sets returned by any SQL statements. 414 | Note, if you supply this block, it must return integer value, zero upon success (this would be a good opportunity to use SQLITE_OK), 415 | non-zero value upon failure (which will stop the bulk execution of the SQL). If a statement returns values, the block will be called with the results from the query in NSDictionary *resultsDictionary. 416 | This may be `nil` if you don't care to receive any results. 417 | 418 | @return `YES` upon success; `NO` upon failure. If failed, you can call ``, 419 | ``, or `` for diagnostic information regarding the failure. 420 | 421 | @see executeStatements: 422 | @see [sqlite3_exec()](http://sqlite.org/c3ref/exec.html) 423 | 424 | */ 425 | 426 | - (BOOL)executeStatements:(NSString *)sql withResultBlock:(FMDBExecuteStatementsCallbackBlock)block; 427 | 428 | /** Last insert rowid 429 | 430 | Each entry in an SQLite table has a unique 64-bit signed integer key called the "rowid". The rowid is always available as an undeclared column named `ROWID`, `OID`, or `_ROWID_` as long as those names are not also used by explicitly declared columns. If the table has a column of type `INTEGER PRIMARY KEY` then that column is another alias for the rowid. 431 | 432 | This routine returns the rowid of the most recent successful `INSERT` into the database from the database connection in the first argument. As of SQLite version 3.7.7, this routines records the last insert rowid of both ordinary tables and virtual tables. If no successful `INSERT`s have ever occurred on that database connection, zero is returned. 433 | 434 | @return The rowid of the last inserted row. 435 | 436 | @see [sqlite3_last_insert_rowid()](http://sqlite.org/c3ref/last_insert_rowid.html) 437 | 438 | */ 439 | 440 | - (sqlite_int64)lastInsertRowId; 441 | 442 | /** The number of rows changed by prior SQL statement. 443 | 444 | This function returns the number of database rows that were changed or inserted or deleted by the most recently completed SQL statement on the database connection specified by the first parameter. Only changes that are directly specified by the INSERT, UPDATE, or DELETE statement are counted. 445 | 446 | @return The number of rows changed by prior SQL statement. 447 | 448 | @see [sqlite3_changes()](http://sqlite.org/c3ref/changes.html) 449 | 450 | */ 451 | 452 | - (int)changes; 453 | 454 | 455 | ///------------------------- 456 | /// @name Retrieving results 457 | ///------------------------- 458 | 459 | /** Execute select statement 460 | 461 | Executing queries returns an `` object if successful, and `nil` upon failure. Like executing updates, there is a variant that accepts an `NSError **` parameter. Otherwise you should use the `` and `` methods to determine why a query failed. 462 | 463 | In order to iterate through the results of your query, you use a `while()` loop. You also need to "step" (via `<[FMResultSet next]>`) from one record to the other. 464 | 465 | This method employs [`sqlite3_bind`](http://sqlite.org/c3ref/bind_blob.html) for any optional value parameters. This properly escapes any characters that need escape sequences (e.g. quotation marks), which eliminates simple SQL errors as well as protects against SQL injection attacks. This method natively handles `NSString`, `NSNumber`, `NSNull`, `NSDate`, and `NSData` objects. All other object types will be interpreted as text values using the object's `description` method. 466 | 467 | @param sql The SELECT statement to be performed, with optional `?` placeholders. 468 | 469 | @param ... Optional parameters to bind to `?` placeholders in the SQL statement. These should be Objective-C objects (e.g. `NSString`, `NSNumber`, etc.), not fundamental C data types (e.g. `int`, `char *`, etc.). 470 | 471 | @return A `` for the result set upon success; `nil` upon failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. 472 | 473 | @see FMResultSet 474 | @see [`FMResultSet next`](<[FMResultSet next]>) 475 | @see [`sqlite3_bind`](http://sqlite.org/c3ref/bind_blob.html) 476 | */ 477 | 478 | - (FMResultSet *)executeQuery:(NSString*)sql, ...; 479 | 480 | /** Execute select statement 481 | 482 | Executing queries returns an `` object if successful, and `nil` upon failure. Like executing updates, there is a variant that accepts an `NSError **` parameter. Otherwise you should use the `` and `` methods to determine why a query failed. 483 | 484 | In order to iterate through the results of your query, you use a `while()` loop. You also need to "step" (via `<[FMResultSet next]>`) from one record to the other. 485 | 486 | @param format The SQL to be performed, with `printf`-style escape sequences. 487 | 488 | @param ... Optional parameters to bind to use in conjunction with the `printf`-style escape sequences in the SQL statement. 489 | 490 | @return A `` for the result set upon success; `nil` upon failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. 491 | 492 | @see executeQuery: 493 | @see FMResultSet 494 | @see [`FMResultSet next`](<[FMResultSet next]>) 495 | 496 | @note This method does not technically perform a traditional printf-style replacement. What this method actually does is replace the printf-style percent sequences with a SQLite `?` placeholder, and then bind values to that placeholder. Thus the following command 497 | 498 | [db executeQueryWithFormat:@"SELECT * FROM test WHERE name=%@", @"Gus"]; 499 | 500 | is actually replacing the `%@` with `?` placeholder, and then performing something equivalent to `` 501 | 502 | [db executeQuery:@"SELECT * FROM test WHERE name=?", @"Gus"]; 503 | 504 | There are two reasons why this distinction is important. First, the printf-style escape sequences can only be used where it is permissible to use a SQLite `?` placeholder. You can use it only for values in SQL statements, but not for table names or column names or any other non-value context. This method also cannot be used in conjunction with `pragma` statements and the like. Second, note the lack of quotation marks in the SQL. The `WHERE` clause was _not_ `WHERE name='%@'` (like you might have to do if you built a SQL statement using `NSString` method `stringWithFormat`), but rather simply `WHERE name=%@`. 505 | 506 | @note If you want to use this from Swift, please note that you must include `FMDatabaseVariadic.swift` in your project. Without that, you cannot use this method directly, and instead have to use methods such as ``. 507 | 508 | */ 509 | 510 | - (FMResultSet *)executeQueryWithFormat:(NSString*)format, ... NS_FORMAT_FUNCTION(1,2); 511 | 512 | /** Execute select statement 513 | 514 | Executing queries returns an `` object if successful, and `nil` upon failure. Like executing updates, there is a variant that accepts an `NSError **` parameter. Otherwise you should use the `` and `` methods to determine why a query failed. 515 | 516 | In order to iterate through the results of your query, you use a `while()` loop. You also need to "step" (via `<[FMResultSet next]>`) from one record to the other. 517 | 518 | @param sql The SELECT statement to be performed, with optional `?` placeholders. 519 | 520 | @param arguments A `NSArray` of objects to be used when binding values to the `?` placeholders in the SQL statement. 521 | 522 | @return A `` for the result set upon success; `nil` upon failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. 523 | 524 | @see FMResultSet 525 | @see [`FMResultSet next`](<[FMResultSet next]>) 526 | */ 527 | 528 | - (FMResultSet *)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray *)arguments; 529 | 530 | /** Execute select statement 531 | 532 | Executing queries returns an `` object if successful, and `nil` upon failure. Like executing updates, there is a variant that accepts an `NSError **` parameter. Otherwise you should use the `` and `` methods to determine why a query failed. 533 | 534 | In order to iterate through the results of your query, you use a `while()` loop. You also need to "step" (via `<[FMResultSet next]>`) from one record to the other. 535 | 536 | @param sql The SELECT statement to be performed, with optional `?` placeholders. 537 | 538 | @param arguments A `NSDictionary` of objects keyed by column names that will be used when binding values to the `?` placeholders in the SQL statement. 539 | 540 | @return A `` for the result set upon success; `nil` upon failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. 541 | 542 | @see FMResultSet 543 | @see [`FMResultSet next`](<[FMResultSet next]>) 544 | */ 545 | 546 | - (FMResultSet *)executeQuery:(NSString *)sql withParameterDictionary:(NSDictionary *)arguments; 547 | 548 | 549 | // Documentation forthcoming. 550 | - (FMResultSet *)executeQuery:(NSString*)sql withVAList: (va_list)args; 551 | 552 | ///------------------- 553 | /// @name Transactions 554 | ///------------------- 555 | 556 | /** Begin a transaction 557 | 558 | @return `YES` on success; `NO` on failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. 559 | 560 | @see commit 561 | @see rollback 562 | @see beginDeferredTransaction 563 | @see inTransaction 564 | */ 565 | 566 | - (BOOL)beginTransaction; 567 | 568 | /** Begin a deferred transaction 569 | 570 | @return `YES` on success; `NO` on failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. 571 | 572 | @see commit 573 | @see rollback 574 | @see beginTransaction 575 | @see inTransaction 576 | */ 577 | 578 | - (BOOL)beginDeferredTransaction; 579 | 580 | /** Commit a transaction 581 | 582 | Commit a transaction that was initiated with either `` or with ``. 583 | 584 | @return `YES` on success; `NO` on failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. 585 | 586 | @see beginTransaction 587 | @see beginDeferredTransaction 588 | @see rollback 589 | @see inTransaction 590 | */ 591 | 592 | - (BOOL)commit; 593 | 594 | /** Rollback a transaction 595 | 596 | Rollback a transaction that was initiated with either `` or with ``. 597 | 598 | @return `YES` on success; `NO` on failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. 599 | 600 | @see beginTransaction 601 | @see beginDeferredTransaction 602 | @see commit 603 | @see inTransaction 604 | */ 605 | 606 | - (BOOL)rollback; 607 | 608 | /** Identify whether currently in a transaction or not 609 | 610 | @return `YES` if currently within transaction; `NO` if not. 611 | 612 | @see beginTransaction 613 | @see beginDeferredTransaction 614 | @see commit 615 | @see rollback 616 | */ 617 | 618 | - (BOOL)inTransaction; 619 | 620 | 621 | ///---------------------------------------- 622 | /// @name Cached statements and result sets 623 | ///---------------------------------------- 624 | 625 | /** Clear cached statements */ 626 | 627 | - (void)clearCachedStatements; 628 | 629 | /** Close all open result sets */ 630 | 631 | - (void)closeOpenResultSets; 632 | 633 | /** Whether database has any open result sets 634 | 635 | @return `YES` if there are open result sets; `NO` if not. 636 | */ 637 | 638 | - (BOOL)hasOpenResultSets; 639 | 640 | /** Return whether should cache statements or not 641 | 642 | @return `YES` if should cache statements; `NO` if not. 643 | */ 644 | 645 | - (BOOL)shouldCacheStatements; 646 | 647 | /** Set whether should cache statements or not 648 | 649 | @param value `YES` if should cache statements; `NO` if not. 650 | */ 651 | 652 | - (void)setShouldCacheStatements:(BOOL)value; 653 | 654 | 655 | ///------------------------- 656 | /// @name Encryption methods 657 | ///------------------------- 658 | 659 | /** Set encryption key. 660 | 661 | @param key The key to be used. 662 | 663 | @return `YES` if success, `NO` on error. 664 | 665 | @see http://www.sqlite-encrypt.com/develop-guide.htm 666 | 667 | @warning You need to have purchased the sqlite encryption extensions for this method to work. 668 | */ 669 | 670 | - (BOOL)setKey:(NSString*)key; 671 | 672 | /** Reset encryption key 673 | 674 | @param key The key to be used. 675 | 676 | @return `YES` if success, `NO` on error. 677 | 678 | @see http://www.sqlite-encrypt.com/develop-guide.htm 679 | 680 | @warning You need to have purchased the sqlite encryption extensions for this method to work. 681 | */ 682 | 683 | - (BOOL)rekey:(NSString*)key; 684 | 685 | /** Set encryption key using `keyData`. 686 | 687 | @param keyData The `NSData` to be used. 688 | 689 | @return `YES` if success, `NO` on error. 690 | 691 | @see http://www.sqlite-encrypt.com/develop-guide.htm 692 | 693 | @warning You need to have purchased the sqlite encryption extensions for this method to work. 694 | */ 695 | 696 | - (BOOL)setKeyWithData:(NSData *)keyData; 697 | 698 | /** Reset encryption key using `keyData`. 699 | 700 | @param keyData The `NSData` to be used. 701 | 702 | @return `YES` if success, `NO` on error. 703 | 704 | @see http://www.sqlite-encrypt.com/develop-guide.htm 705 | 706 | @warning You need to have purchased the sqlite encryption extensions for this method to work. 707 | */ 708 | 709 | - (BOOL)rekeyWithData:(NSData *)keyData; 710 | 711 | 712 | ///------------------------------ 713 | /// @name General inquiry methods 714 | ///------------------------------ 715 | 716 | /** The path of the database file 717 | 718 | @return path of database. 719 | 720 | */ 721 | 722 | - (NSString *)databasePath; 723 | 724 | /** The underlying SQLite handle 725 | 726 | @return The `sqlite3` pointer. 727 | 728 | */ 729 | 730 | - (sqlite3*)sqliteHandle; 731 | 732 | 733 | ///----------------------------- 734 | /// @name Retrieving error codes 735 | ///----------------------------- 736 | 737 | /** Last error message 738 | 739 | Returns the English-language text that describes the most recent failed SQLite API call associated with a database connection. If a prior API call failed but the most recent API call succeeded, this return value is undefined. 740 | 741 | @return `NSString` of the last error message. 742 | 743 | @see [sqlite3_errmsg()](http://sqlite.org/c3ref/errcode.html) 744 | @see lastErrorCode 745 | @see lastError 746 | 747 | */ 748 | 749 | - (NSString*)lastErrorMessage; 750 | 751 | /** Last error code 752 | 753 | Returns the numeric result code or extended result code for the most recent failed SQLite API call associated with a database connection. If a prior API call failed but the most recent API call succeeded, this return value is undefined. 754 | 755 | @return Integer value of the last error code. 756 | 757 | @see [sqlite3_errcode()](http://sqlite.org/c3ref/errcode.html) 758 | @see lastErrorMessage 759 | @see lastError 760 | 761 | */ 762 | 763 | - (int)lastErrorCode; 764 | 765 | /** Had error 766 | 767 | @return `YES` if there was an error, `NO` if no error. 768 | 769 | @see lastError 770 | @see lastErrorCode 771 | @see lastErrorMessage 772 | 773 | */ 774 | 775 | - (BOOL)hadError; 776 | 777 | /** Last error 778 | 779 | @return `NSError` representing the last error. 780 | 781 | @see lastErrorCode 782 | @see lastErrorMessage 783 | 784 | */ 785 | 786 | - (NSError*)lastError; 787 | 788 | 789 | // description forthcoming 790 | - (void)setMaxBusyRetryTimeInterval:(NSTimeInterval)timeoutInSeconds; 791 | - (NSTimeInterval)maxBusyRetryTimeInterval; 792 | 793 | 794 | #if SQLITE_VERSION_NUMBER >= 3007000 795 | 796 | ///------------------ 797 | /// @name Save points 798 | ///------------------ 799 | 800 | /** Start save point 801 | 802 | @param name Name of save point. 803 | 804 | @param outErr A `NSError` object to receive any error object (if any). 805 | 806 | @return `YES` on success; `NO` on failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. 807 | 808 | @see releaseSavePointWithName:error: 809 | @see rollbackToSavePointWithName:error: 810 | */ 811 | 812 | - (BOOL)startSavePointWithName:(NSString*)name error:(NSError**)outErr; 813 | 814 | /** Release save point 815 | 816 | @param name Name of save point. 817 | 818 | @param outErr A `NSError` object to receive any error object (if any). 819 | 820 | @return `YES` on success; `NO` on failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. 821 | 822 | @see startSavePointWithName:error: 823 | @see rollbackToSavePointWithName:error: 824 | 825 | */ 826 | 827 | - (BOOL)releaseSavePointWithName:(NSString*)name error:(NSError**)outErr; 828 | 829 | /** Roll back to save point 830 | 831 | @param name Name of save point. 832 | @param outErr A `NSError` object to receive any error object (if any). 833 | 834 | @return `YES` on success; `NO` on failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. 835 | 836 | @see startSavePointWithName:error: 837 | @see releaseSavePointWithName:error: 838 | 839 | */ 840 | 841 | - (BOOL)rollbackToSavePointWithName:(NSString*)name error:(NSError**)outErr; 842 | 843 | /** Start save point 844 | 845 | @param block Block of code to perform from within save point. 846 | 847 | @return The NSError corresponding to the error, if any. If no error, returns `nil`. 848 | 849 | @see startSavePointWithName:error: 850 | @see releaseSavePointWithName:error: 851 | @see rollbackToSavePointWithName:error: 852 | 853 | */ 854 | 855 | - (NSError*)inSavePoint:(void (^)(BOOL *rollback))block; 856 | 857 | #endif 858 | 859 | ///---------------------------- 860 | /// @name SQLite library status 861 | ///---------------------------- 862 | 863 | /** Test to see if the library is threadsafe 864 | 865 | @return `NO` if and only if SQLite was compiled with mutexing code omitted due to the SQLITE_THREADSAFE compile-time option being set to 0. 866 | 867 | @see [sqlite3_threadsafe()](http://sqlite.org/c3ref/threadsafe.html) 868 | */ 869 | 870 | + (BOOL)isSQLiteThreadSafe; 871 | 872 | /** Run-time library version numbers 873 | 874 | @return The sqlite library version string. 875 | 876 | @see [sqlite3_libversion()](http://sqlite.org/c3ref/libversion.html) 877 | */ 878 | 879 | + (NSString*)sqliteLibVersion; 880 | 881 | 882 | + (NSString*)FMDBUserVersion; 883 | 884 | + (SInt32)FMDBVersion; 885 | 886 | 887 | ///------------------------ 888 | /// @name Make SQL function 889 | ///------------------------ 890 | 891 | /** Adds SQL functions or aggregates or to redefine the behavior of existing SQL functions or aggregates. 892 | 893 | For example: 894 | 895 | [queue inDatabase:^(FMDatabase *adb) { 896 | 897 | [adb executeUpdate:@"create table ftest (foo text)"]; 898 | [adb executeUpdate:@"insert into ftest values ('hello')"]; 899 | [adb executeUpdate:@"insert into ftest values ('hi')"]; 900 | [adb executeUpdate:@"insert into ftest values ('not h!')"]; 901 | [adb executeUpdate:@"insert into ftest values ('definitely not h!')"]; 902 | 903 | [adb makeFunctionNamed:@"StringStartsWithH" maximumArguments:1 withBlock:^(sqlite3_context *context, int aargc, sqlite3_value **aargv) { 904 | if (sqlite3_value_type(aargv[0]) == SQLITE_TEXT) { 905 | @autoreleasepool { 906 | const char *c = (const char *)sqlite3_value_text(aargv[0]); 907 | NSString *s = [NSString stringWithUTF8String:c]; 908 | sqlite3_result_int(context, [s hasPrefix:@"h"]); 909 | } 910 | } 911 | else { 912 | NSLog(@"Unknown formart for StringStartsWithH (%d) %s:%d", sqlite3_value_type(aargv[0]), __FUNCTION__, __LINE__); 913 | sqlite3_result_null(context); 914 | } 915 | }]; 916 | 917 | int rowCount = 0; 918 | FMResultSet *ars = [adb executeQuery:@"select * from ftest where StringStartsWithH(foo)"]; 919 | while ([ars next]) { 920 | rowCount++; 921 | NSLog(@"Does %@ start with 'h'?", [rs stringForColumnIndex:0]); 922 | } 923 | FMDBQuickCheck(rowCount == 2); 924 | }]; 925 | 926 | @param name Name of function 927 | 928 | @param count Maximum number of parameters 929 | 930 | @param block The block of code for the function 931 | 932 | @see [sqlite3_create_function()](http://sqlite.org/c3ref/create_function.html) 933 | */ 934 | 935 | - (void)makeFunctionNamed:(NSString*)name maximumArguments:(int)count withBlock:(void (^)(sqlite3_context *context, int argc, sqlite3_value **argv))block; 936 | 937 | 938 | ///--------------------- 939 | /// @name Date formatter 940 | ///--------------------- 941 | 942 | /** Generate an `NSDateFormatter` that won't be broken by permutations of timezones or locales. 943 | 944 | Use this method to generate values to set the dateFormat property. 945 | 946 | Example: 947 | 948 | myDB.dateFormat = [FMDatabase storeableDateFormat:@"yyyy-MM-dd HH:mm:ss"]; 949 | 950 | @param format A valid NSDateFormatter format string. 951 | 952 | @return A `NSDateFormatter` that can be used for converting dates to strings and vice versa. 953 | 954 | @see hasDateFormatter 955 | @see setDateFormat: 956 | @see dateFromString: 957 | @see stringFromDate: 958 | @see storeableDateFormat: 959 | 960 | @warning Note that `NSDateFormatter` is not thread-safe, so the formatter generated by this method should be assigned to only one FMDB instance and should not be used for other purposes. 961 | 962 | */ 963 | 964 | + (NSDateFormatter *)storeableDateFormat:(NSString *)format; 965 | 966 | /** Test whether the database has a date formatter assigned. 967 | 968 | @return `YES` if there is a date formatter; `NO` if not. 969 | 970 | @see hasDateFormatter 971 | @see setDateFormat: 972 | @see dateFromString: 973 | @see stringFromDate: 974 | @see storeableDateFormat: 975 | */ 976 | 977 | - (BOOL)hasDateFormatter; 978 | 979 | /** Set to a date formatter to use string dates with sqlite instead of the default UNIX timestamps. 980 | 981 | @param format Set to nil to use UNIX timestamps. Defaults to nil. Should be set using a formatter generated using FMDatabase::storeableDateFormat. 982 | 983 | @see hasDateFormatter 984 | @see setDateFormat: 985 | @see dateFromString: 986 | @see stringFromDate: 987 | @see storeableDateFormat: 988 | 989 | @warning Note there is no direct getter for the `NSDateFormatter`, and you should not use the formatter you pass to FMDB for other purposes, as `NSDateFormatter` is not thread-safe. 990 | */ 991 | 992 | - (void)setDateFormat:(NSDateFormatter *)format; 993 | 994 | /** Convert the supplied NSString to NSDate, using the current database formatter. 995 | 996 | @param s `NSString` to convert to `NSDate`. 997 | 998 | @return The `NSDate` object; or `nil` if no formatter is set. 999 | 1000 | @see hasDateFormatter 1001 | @see setDateFormat: 1002 | @see dateFromString: 1003 | @see stringFromDate: 1004 | @see storeableDateFormat: 1005 | */ 1006 | 1007 | - (NSDate *)dateFromString:(NSString *)s; 1008 | 1009 | /** Convert the supplied NSDate to NSString, using the current database formatter. 1010 | 1011 | @param date `NSDate` of date to convert to `NSString`. 1012 | 1013 | @return The `NSString` representation of the date; `nil` if no formatter is set. 1014 | 1015 | @see hasDateFormatter 1016 | @see setDateFormat: 1017 | @see dateFromString: 1018 | @see stringFromDate: 1019 | @see storeableDateFormat: 1020 | */ 1021 | 1022 | - (NSString *)stringFromDate:(NSDate *)date; 1023 | 1024 | @end 1025 | 1026 | 1027 | /** Objective-C wrapper for `sqlite3_stmt` 1028 | 1029 | This is a wrapper for a SQLite `sqlite3_stmt`. Generally when using FMDB you will not need to interact directly with `FMStatement`, but rather with `` and `` only. 1030 | 1031 | ### See also 1032 | 1033 | - `` 1034 | - `` 1035 | - [`sqlite3_stmt`](http://www.sqlite.org/c3ref/stmt.html) 1036 | */ 1037 | 1038 | @interface FMStatement : NSObject { 1039 | sqlite3_stmt *_statement; 1040 | NSString *_query; 1041 | long _useCount; 1042 | BOOL _inUse; 1043 | } 1044 | 1045 | ///----------------- 1046 | /// @name Properties 1047 | ///----------------- 1048 | 1049 | /** Usage count */ 1050 | 1051 | @property (atomic, assign) long useCount; 1052 | 1053 | /** SQL statement */ 1054 | 1055 | @property (atomic, retain) NSString *query; 1056 | 1057 | /** SQLite sqlite3_stmt 1058 | 1059 | @see [`sqlite3_stmt`](http://www.sqlite.org/c3ref/stmt.html) 1060 | */ 1061 | 1062 | @property (atomic, assign) sqlite3_stmt *statement; 1063 | 1064 | /** Indication of whether the statement is in use */ 1065 | 1066 | @property (atomic, assign) BOOL inUse; 1067 | 1068 | ///---------------------------- 1069 | /// @name Closing and Resetting 1070 | ///---------------------------- 1071 | 1072 | /** Close statement */ 1073 | 1074 | - (void)close; 1075 | 1076 | /** Reset statement */ 1077 | 1078 | - (void)reset; 1079 | 1080 | @end 1081 | 1082 | #pragma clang diagnostic pop 1083 | 1084 | -------------------------------------------------------------------------------- /SMSQLiteMigration/FMDatabase/FMDatabaseAdditions.h: -------------------------------------------------------------------------------- 1 | // 2 | // FMDatabaseAdditions.h 3 | // fmdb 4 | // 5 | // Created by August Mueller on 10/30/05. 6 | // Copyright 2005 Flying Meat Inc.. All rights reserved. 7 | // 8 | 9 | #import 10 | #import "FMDatabase.h" 11 | 12 | 13 | /** Category of additions for `` class. 14 | 15 | ### See also 16 | 17 | - `` 18 | */ 19 | 20 | @interface FMDatabase (FMDatabaseAdditions) 21 | 22 | ///---------------------------------------- 23 | /// @name Return results of SQL to variable 24 | ///---------------------------------------- 25 | 26 | /** Return `int` value for query 27 | 28 | @param query The SQL query to be performed. 29 | @param ... A list of parameters that will be bound to the `?` placeholders in the SQL query. 30 | 31 | @return `int` value. 32 | 33 | @note To use this method from Swift, you must include `FMDatabaseAdditionsVariadic.swift` in your project. 34 | */ 35 | 36 | - (int)intForQuery:(NSString*)query, ...; 37 | 38 | /** Return `long` value for query 39 | 40 | @param query The SQL query to be performed. 41 | @param ... A list of parameters that will be bound to the `?` placeholders in the SQL query. 42 | 43 | @return `long` value. 44 | 45 | @note To use this method from Swift, you must include `FMDatabaseAdditionsVariadic.swift` in your project. 46 | */ 47 | 48 | - (long)longForQuery:(NSString*)query, ...; 49 | 50 | /** Return `BOOL` value for query 51 | 52 | @param query The SQL query to be performed. 53 | @param ... A list of parameters that will be bound to the `?` placeholders in the SQL query. 54 | 55 | @return `BOOL` value. 56 | 57 | @note To use this method from Swift, you must include `FMDatabaseAdditionsVariadic.swift` in your project. 58 | */ 59 | 60 | - (BOOL)boolForQuery:(NSString*)query, ...; 61 | 62 | /** Return `double` value for query 63 | 64 | @param query The SQL query to be performed. 65 | @param ... A list of parameters that will be bound to the `?` placeholders in the SQL query. 66 | 67 | @return `double` value. 68 | 69 | @note To use this method from Swift, you must include `FMDatabaseAdditionsVariadic.swift` in your project. 70 | */ 71 | 72 | - (double)doubleForQuery:(NSString*)query, ...; 73 | 74 | /** Return `NSString` value for query 75 | 76 | @param query The SQL query to be performed. 77 | @param ... A list of parameters that will be bound to the `?` placeholders in the SQL query. 78 | 79 | @return `NSString` value. 80 | 81 | @note To use this method from Swift, you must include `FMDatabaseAdditionsVariadic.swift` in your project. 82 | */ 83 | 84 | - (NSString*)stringForQuery:(NSString*)query, ...; 85 | 86 | /** Return `NSData` value for query 87 | 88 | @param query The SQL query to be performed. 89 | @param ... A list of parameters that will be bound to the `?` placeholders in the SQL query. 90 | 91 | @return `NSData` value. 92 | 93 | @note To use this method from Swift, you must include `FMDatabaseAdditionsVariadic.swift` in your project. 94 | */ 95 | 96 | - (NSData*)dataForQuery:(NSString*)query, ...; 97 | 98 | /** Return `NSDate` value for query 99 | 100 | @param query The SQL query to be performed. 101 | @param ... A list of parameters that will be bound to the `?` placeholders in the SQL query. 102 | 103 | @return `NSDate` value. 104 | 105 | @note To use this method from Swift, you must include `FMDatabaseAdditionsVariadic.swift` in your project. 106 | */ 107 | 108 | - (NSDate*)dateForQuery:(NSString*)query, ...; 109 | 110 | 111 | // Notice that there's no dataNoCopyForQuery:. 112 | // That would be a bad idea, because we close out the result set, and then what 113 | // happens to the data that we just didn't copy? Who knows, not I. 114 | 115 | 116 | ///-------------------------------- 117 | /// @name Schema related operations 118 | ///-------------------------------- 119 | 120 | /** Does table exist in database? 121 | 122 | @param tableName The name of the table being looked for. 123 | 124 | @return `YES` if table found; `NO` if not found. 125 | */ 126 | 127 | - (BOOL)tableExists:(NSString*)tableName; 128 | 129 | /** The schema of the database. 130 | 131 | This will be the schema for the entire database. For each entity, each row of the result set will include the following fields: 132 | 133 | - `type` - The type of entity (e.g. table, index, view, or trigger) 134 | - `name` - The name of the object 135 | - `tbl_name` - The name of the table to which the object references 136 | - `rootpage` - The page number of the root b-tree page for tables and indices 137 | - `sql` - The SQL that created the entity 138 | 139 | @return `FMResultSet` of schema; `nil` on error. 140 | 141 | @see [SQLite File Format](http://www.sqlite.org/fileformat.html) 142 | */ 143 | 144 | - (FMResultSet*)getSchema; 145 | 146 | /** The schema of the database. 147 | 148 | This will be the schema for a particular table as report by SQLite `PRAGMA`, for example: 149 | 150 | PRAGMA table_info('employees') 151 | 152 | This will report: 153 | 154 | - `cid` - The column ID number 155 | - `name` - The name of the column 156 | - `type` - The data type specified for the column 157 | - `notnull` - whether the field is defined as NOT NULL (i.e. values required) 158 | - `dflt_value` - The default value for the column 159 | - `pk` - Whether the field is part of the primary key of the table 160 | 161 | @param tableName The name of the table for whom the schema will be returned. 162 | 163 | @return `FMResultSet` of schema; `nil` on error. 164 | 165 | @see [table_info](http://www.sqlite.org/pragma.html#pragma_table_info) 166 | */ 167 | 168 | - (FMResultSet*)getTableSchema:(NSString*)tableName; 169 | 170 | /** Test to see if particular column exists for particular table in database 171 | 172 | @param columnName The name of the column. 173 | 174 | @param tableName The name of the table. 175 | 176 | @return `YES` if column exists in table in question; `NO` otherwise. 177 | */ 178 | 179 | - (BOOL)columnExists:(NSString*)columnName inTableWithName:(NSString*)tableName; 180 | 181 | /** Test to see if particular column exists for particular table in database 182 | 183 | @param columnName The name of the column. 184 | 185 | @param tableName The name of the table. 186 | 187 | @return `YES` if column exists in table in question; `NO` otherwise. 188 | 189 | @see columnExists:inTableWithName: 190 | 191 | @warning Deprecated - use `` instead. 192 | */ 193 | 194 | - (BOOL)columnExists:(NSString*)tableName columnName:(NSString*)columnName __attribute__ ((deprecated)); 195 | 196 | 197 | /** Validate SQL statement 198 | 199 | This validates SQL statement by performing `sqlite3_prepare_v2`, but not returning the results, but instead immediately calling `sqlite3_finalize`. 200 | 201 | @param sql The SQL statement being validated. 202 | 203 | @param error This is a pointer to a `NSError` object that will receive the autoreleased `NSError` object if there was any error. If this is `nil`, no `NSError` result will be returned. 204 | 205 | @return `YES` if validation succeeded without incident; `NO` otherwise. 206 | 207 | */ 208 | 209 | - (BOOL)validateSQL:(NSString*)sql error:(NSError**)error; 210 | 211 | 212 | #if SQLITE_VERSION_NUMBER >= 3007017 213 | 214 | ///----------------------------------- 215 | /// @name Application identifier tasks 216 | ///----------------------------------- 217 | 218 | /** Retrieve application ID 219 | 220 | @return The `uint32_t` numeric value of the application ID. 221 | 222 | @see setApplicationID: 223 | */ 224 | 225 | - (uint32_t)applicationID; 226 | 227 | /** Set the application ID 228 | 229 | @param appID The `uint32_t` numeric value of the application ID. 230 | 231 | @see applicationID 232 | */ 233 | 234 | - (void)setApplicationID:(uint32_t)appID; 235 | 236 | #if TARGET_OS_MAC && !TARGET_OS_IPHONE 237 | /** Retrieve application ID string 238 | 239 | @return The `NSString` value of the application ID. 240 | 241 | @see setApplicationIDString: 242 | */ 243 | 244 | 245 | - (NSString*)applicationIDString; 246 | 247 | /** Set the application ID string 248 | 249 | @param string The `NSString` value of the application ID. 250 | 251 | @see applicationIDString 252 | */ 253 | 254 | - (void)setApplicationIDString:(NSString*)string; 255 | #endif 256 | 257 | #endif 258 | 259 | ///----------------------------------- 260 | /// @name user version identifier tasks 261 | ///----------------------------------- 262 | 263 | /** Retrieve user version 264 | 265 | @return The `uint32_t` numeric value of the user version. 266 | 267 | @see setUserVersion: 268 | */ 269 | 270 | - (uint32_t)userVersion; 271 | 272 | /** Set the user-version 273 | 274 | @param version The `uint32_t` numeric value of the user version. 275 | 276 | @see userVersion 277 | */ 278 | 279 | - (void)setUserVersion:(uint32_t)version; 280 | 281 | @end 282 | -------------------------------------------------------------------------------- /SMSQLiteMigration/FMDatabase/FMDatabaseAdditions.m: -------------------------------------------------------------------------------- 1 | // 2 | // FMDatabaseAdditions.m 3 | // fmdb 4 | // 5 | // Created by August Mueller on 10/30/05. 6 | // Copyright 2005 Flying Meat Inc.. All rights reserved. 7 | // 8 | 9 | #import "FMDatabase.h" 10 | #import "FMDatabaseAdditions.h" 11 | #import "TargetConditionals.h" 12 | 13 | @interface FMDatabase (PrivateStuff) 14 | - (FMResultSet *)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray*)arrayArgs orDictionary:(NSDictionary *)dictionaryArgs orVAList:(va_list)args; 15 | @end 16 | 17 | @implementation FMDatabase (FMDatabaseAdditions) 18 | 19 | #define RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(type, sel) \ 20 | va_list args; \ 21 | va_start(args, query); \ 22 | FMResultSet *resultSet = [self executeQuery:query withArgumentsInArray:0x00 orDictionary:0x00 orVAList:args]; \ 23 | va_end(args); \ 24 | if (![resultSet next]) { return (type)0; } \ 25 | type ret = [resultSet sel:0]; \ 26 | [resultSet close]; \ 27 | [resultSet setParentDB:nil]; \ 28 | return ret; 29 | 30 | 31 | - (NSString*)stringForQuery:(NSString*)query, ... { 32 | RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(NSString *, stringForColumnIndex); 33 | } 34 | 35 | - (int)intForQuery:(NSString*)query, ... { 36 | RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(int, intForColumnIndex); 37 | } 38 | 39 | - (long)longForQuery:(NSString*)query, ... { 40 | RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(long, longForColumnIndex); 41 | } 42 | 43 | - (BOOL)boolForQuery:(NSString*)query, ... { 44 | RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(BOOL, boolForColumnIndex); 45 | } 46 | 47 | - (double)doubleForQuery:(NSString*)query, ... { 48 | RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(double, doubleForColumnIndex); 49 | } 50 | 51 | - (NSData*)dataForQuery:(NSString*)query, ... { 52 | RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(NSData *, dataForColumnIndex); 53 | } 54 | 55 | - (NSDate*)dateForQuery:(NSString*)query, ... { 56 | RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(NSDate *, dateForColumnIndex); 57 | } 58 | 59 | 60 | - (BOOL)tableExists:(NSString*)tableName { 61 | 62 | tableName = [tableName lowercaseString]; 63 | 64 | FMResultSet *rs = [self executeQuery:@"select [sql] from sqlite_master where [type] = 'table' and lower(name) = ?", tableName]; 65 | 66 | //if at least one next exists, table exists 67 | BOOL returnBool = [rs next]; 68 | 69 | //close and free object 70 | [rs close]; 71 | 72 | return returnBool; 73 | } 74 | 75 | /* 76 | get table with list of tables: result colums: type[STRING], name[STRING],tbl_name[STRING],rootpage[INTEGER],sql[STRING] 77 | check if table exist in database (patch from OZLB) 78 | */ 79 | - (FMResultSet*)getSchema { 80 | 81 | //result colums: type[STRING], name[STRING],tbl_name[STRING],rootpage[INTEGER],sql[STRING] 82 | FMResultSet *rs = [self executeQuery:@"SELECT type, name, tbl_name, rootpage, sql FROM (SELECT * FROM sqlite_master UNION ALL SELECT * FROM sqlite_temp_master) WHERE type != 'meta' AND name NOT LIKE 'sqlite_%' ORDER BY tbl_name, type DESC, name"]; 83 | 84 | return rs; 85 | } 86 | 87 | /* 88 | get table schema: result colums: cid[INTEGER], name,type [STRING], notnull[INTEGER], dflt_value[],pk[INTEGER] 89 | */ 90 | - (FMResultSet*)getTableSchema:(NSString*)tableName { 91 | 92 | //result colums: cid[INTEGER], name,type [STRING], notnull[INTEGER], dflt_value[],pk[INTEGER] 93 | FMResultSet *rs = [self executeQuery:[NSString stringWithFormat: @"pragma table_info('%@')", tableName]]; 94 | 95 | return rs; 96 | } 97 | 98 | - (BOOL)columnExists:(NSString*)columnName inTableWithName:(NSString*)tableName { 99 | 100 | BOOL returnBool = NO; 101 | 102 | tableName = [tableName lowercaseString]; 103 | columnName = [columnName lowercaseString]; 104 | 105 | FMResultSet *rs = [self getTableSchema:tableName]; 106 | 107 | //check if column is present in table schema 108 | while ([rs next]) { 109 | if ([[[rs stringForColumn:@"name"] lowercaseString] isEqualToString:columnName]) { 110 | returnBool = YES; 111 | break; 112 | } 113 | } 114 | 115 | //If this is not done FMDatabase instance stays out of pool 116 | [rs close]; 117 | 118 | return returnBool; 119 | } 120 | 121 | 122 | #if SQLITE_VERSION_NUMBER >= 3007017 123 | 124 | - (uint32_t)applicationID { 125 | 126 | uint32_t r = 0; 127 | 128 | FMResultSet *rs = [self executeQuery:@"pragma application_id"]; 129 | 130 | if ([rs next]) { 131 | r = (uint32_t)[rs longLongIntForColumnIndex:0]; 132 | } 133 | 134 | [rs close]; 135 | 136 | return r; 137 | } 138 | 139 | - (void)setApplicationID:(uint32_t)appID { 140 | NSString *query = [NSString stringWithFormat:@"pragma application_id=%d", appID]; 141 | FMResultSet *rs = [self executeQuery:query]; 142 | [rs next]; 143 | [rs close]; 144 | } 145 | 146 | 147 | #if TARGET_OS_MAC && !TARGET_OS_IPHONE 148 | - (NSString*)applicationIDString { 149 | NSString *s = NSFileTypeForHFSTypeCode([self applicationID]); 150 | 151 | assert([s length] == 6); 152 | 153 | s = [s substringWithRange:NSMakeRange(1, 4)]; 154 | 155 | 156 | return s; 157 | 158 | } 159 | 160 | - (void)setApplicationIDString:(NSString*)s { 161 | 162 | if ([s length] != 4) { 163 | NSLog(@"setApplicationIDString: string passed is not exactly 4 chars long. (was %ld)", [s length]); 164 | } 165 | 166 | [self setApplicationID:NSHFSTypeCodeFromFileType([NSString stringWithFormat:@"'%@'", s])]; 167 | } 168 | 169 | 170 | #endif 171 | 172 | #endif 173 | 174 | - (uint32_t)userVersion { 175 | uint32_t r = 0; 176 | 177 | FMResultSet *rs = [self executeQuery:@"pragma user_version"]; 178 | 179 | if ([rs next]) { 180 | r = (uint32_t)[rs longLongIntForColumnIndex:0]; 181 | } 182 | 183 | [rs close]; 184 | return r; 185 | } 186 | 187 | - (void)setUserVersion:(uint32_t)version { 188 | NSString *query = [NSString stringWithFormat:@"pragma user_version = %d", version]; 189 | FMResultSet *rs = [self executeQuery:query]; 190 | [rs next]; 191 | [rs close]; 192 | } 193 | 194 | #pragma clang diagnostic push 195 | #pragma clang diagnostic ignored "-Wdeprecated-implementations" 196 | 197 | - (BOOL)columnExists:(NSString*)tableName columnName:(NSString*)columnName __attribute__ ((deprecated)) { 198 | return [self columnExists:columnName inTableWithName:tableName]; 199 | } 200 | 201 | #pragma clang diagnostic pop 202 | 203 | 204 | - (BOOL)validateSQL:(NSString*)sql error:(NSError**)error { 205 | sqlite3_stmt *pStmt = NULL; 206 | BOOL validationSucceeded = YES; 207 | 208 | int rc = sqlite3_prepare_v2(_db, [sql UTF8String], -1, &pStmt, 0); 209 | if (rc != SQLITE_OK) { 210 | validationSucceeded = NO; 211 | if (error) { 212 | *error = [NSError errorWithDomain:NSCocoaErrorDomain 213 | code:[self lastErrorCode] 214 | userInfo:[NSDictionary dictionaryWithObject:[self lastErrorMessage] 215 | forKey:NSLocalizedDescriptionKey]]; 216 | } 217 | } 218 | 219 | sqlite3_finalize(pStmt); 220 | 221 | return validationSucceeded; 222 | } 223 | 224 | @end 225 | -------------------------------------------------------------------------------- /SMSQLiteMigration/FMDatabase/FMDatabasePool.h: -------------------------------------------------------------------------------- 1 | // 2 | // FMDatabasePool.h 3 | // fmdb 4 | // 5 | // Created by August Mueller on 6/22/11. 6 | // Copyright 2011 Flying Meat Inc. All rights reserved. 7 | // 8 | 9 | #import 10 | #import "sqlite3.h" 11 | 12 | @class FMDatabase; 13 | 14 | /** Pool of `` objects. 15 | 16 | ### See also 17 | 18 | - `` 19 | - `` 20 | 21 | @warning Before using `FMDatabasePool`, please consider using `` instead. 22 | 23 | If you really really really know what you're doing and `FMDatabasePool` is what 24 | you really really need (ie, you're using a read only database), OK you can use 25 | it. But just be careful not to deadlock! 26 | 27 | For an example on deadlocking, search for: 28 | `ONLY_USE_THE_POOL_IF_YOU_ARE_DOING_READS_OTHERWISE_YOULL_DEADLOCK_USE_FMDATABASEQUEUE_INSTEAD` 29 | in the main.m file. 30 | */ 31 | 32 | @interface FMDatabasePool : NSObject { 33 | NSString *_path; 34 | 35 | dispatch_queue_t _lockQueue; 36 | 37 | NSMutableArray *_databaseInPool; 38 | NSMutableArray *_databaseOutPool; 39 | 40 | __unsafe_unretained id _delegate; 41 | 42 | NSUInteger _maximumNumberOfDatabasesToCreate; 43 | int _openFlags; 44 | } 45 | 46 | /** Database path */ 47 | 48 | @property (atomic, retain) NSString *path; 49 | 50 | /** Delegate object */ 51 | 52 | @property (atomic, assign) id delegate; 53 | 54 | /** Maximum number of databases to create */ 55 | 56 | @property (atomic, assign) NSUInteger maximumNumberOfDatabasesToCreate; 57 | 58 | /** Open flags */ 59 | 60 | @property (atomic, readonly) int openFlags; 61 | 62 | 63 | ///--------------------- 64 | /// @name Initialization 65 | ///--------------------- 66 | 67 | /** Create pool using path. 68 | 69 | @param aPath The file path of the database. 70 | 71 | @return The `FMDatabasePool` object. `nil` on error. 72 | */ 73 | 74 | + (instancetype)databasePoolWithPath:(NSString*)aPath; 75 | 76 | /** Create pool using path and specified flags 77 | 78 | @param aPath The file path of the database. 79 | @param openFlags Flags passed to the openWithFlags method of the database 80 | 81 | @return The `FMDatabasePool` object. `nil` on error. 82 | */ 83 | 84 | + (instancetype)databasePoolWithPath:(NSString*)aPath flags:(int)openFlags; 85 | 86 | /** Create pool using path. 87 | 88 | @param aPath The file path of the database. 89 | 90 | @return The `FMDatabasePool` object. `nil` on error. 91 | */ 92 | 93 | - (instancetype)initWithPath:(NSString*)aPath; 94 | 95 | /** Create pool using path and specified flags. 96 | 97 | @param aPath The file path of the database. 98 | @param openFlags Flags passed to the openWithFlags method of the database 99 | 100 | @return The `FMDatabasePool` object. `nil` on error. 101 | */ 102 | 103 | - (instancetype)initWithPath:(NSString*)aPath flags:(int)openFlags; 104 | 105 | ///------------------------------------------------ 106 | /// @name Keeping track of checked in/out databases 107 | ///------------------------------------------------ 108 | 109 | /** Number of checked-in databases in pool 110 | 111 | @returns Number of databases 112 | */ 113 | 114 | - (NSUInteger)countOfCheckedInDatabases; 115 | 116 | /** Number of checked-out databases in pool 117 | 118 | @returns Number of databases 119 | */ 120 | 121 | - (NSUInteger)countOfCheckedOutDatabases; 122 | 123 | /** Total number of databases in pool 124 | 125 | @returns Number of databases 126 | */ 127 | 128 | - (NSUInteger)countOfOpenDatabases; 129 | 130 | /** Release all databases in pool */ 131 | 132 | - (void)releaseAllDatabases; 133 | 134 | ///------------------------------------------ 135 | /// @name Perform database operations in pool 136 | ///------------------------------------------ 137 | 138 | /** Synchronously perform database operations in pool. 139 | 140 | @param block The code to be run on the `FMDatabasePool` pool. 141 | */ 142 | 143 | - (void)inDatabase:(void (^)(FMDatabase *db))block; 144 | 145 | /** Synchronously perform database operations in pool using transaction. 146 | 147 | @param block The code to be run on the `FMDatabasePool` pool. 148 | */ 149 | 150 | - (void)inTransaction:(void (^)(FMDatabase *db, BOOL *rollback))block; 151 | 152 | /** Synchronously perform database operations in pool using deferred transaction. 153 | 154 | @param block The code to be run on the `FMDatabasePool` pool. 155 | */ 156 | 157 | - (void)inDeferredTransaction:(void (^)(FMDatabase *db, BOOL *rollback))block; 158 | 159 | #if SQLITE_VERSION_NUMBER >= 3007000 160 | 161 | /** Synchronously perform database operations in pool using save point. 162 | 163 | @param block The code to be run on the `FMDatabasePool` pool. 164 | 165 | @return `NSError` object if error; `nil` if successful. 166 | 167 | @warning You can not nest these, since calling it will pull another database out of the pool and you'll get a deadlock. If you need to nest, use `<[FMDatabase startSavePointWithName:error:]>` instead. 168 | */ 169 | 170 | - (NSError*)inSavePoint:(void (^)(FMDatabase *db, BOOL *rollback))block; 171 | #endif 172 | 173 | @end 174 | 175 | 176 | /** FMDatabasePool delegate category 177 | 178 | This is a category that defines the protocol for the FMDatabasePool delegate 179 | */ 180 | 181 | @interface NSObject (FMDatabasePoolDelegate) 182 | 183 | /** Asks the delegate whether database should be added to the pool. 184 | 185 | @param pool The `FMDatabasePool` object. 186 | @param database The `FMDatabase` object. 187 | 188 | @return `YES` if it should add database to pool; `NO` if not. 189 | 190 | */ 191 | 192 | - (BOOL)databasePool:(FMDatabasePool*)pool shouldAddDatabaseToPool:(FMDatabase*)database; 193 | 194 | /** Tells the delegate that database was added to the pool. 195 | 196 | @param pool The `FMDatabasePool` object. 197 | @param database The `FMDatabase` object. 198 | 199 | */ 200 | 201 | - (void)databasePool:(FMDatabasePool*)pool didAddDatabase:(FMDatabase*)database; 202 | 203 | @end 204 | 205 | -------------------------------------------------------------------------------- /SMSQLiteMigration/FMDatabase/FMDatabasePool.m: -------------------------------------------------------------------------------- 1 | // 2 | // FMDatabasePool.m 3 | // fmdb 4 | // 5 | // Created by August Mueller on 6/22/11. 6 | // Copyright 2011 Flying Meat Inc. All rights reserved. 7 | // 8 | 9 | #import "FMDatabasePool.h" 10 | #import "FMDatabase.h" 11 | 12 | @interface FMDatabasePool() 13 | 14 | - (void)pushDatabaseBackInPool:(FMDatabase*)db; 15 | - (FMDatabase*)db; 16 | 17 | @end 18 | 19 | 20 | @implementation FMDatabasePool 21 | @synthesize path=_path; 22 | @synthesize delegate=_delegate; 23 | @synthesize maximumNumberOfDatabasesToCreate=_maximumNumberOfDatabasesToCreate; 24 | @synthesize openFlags=_openFlags; 25 | 26 | 27 | + (instancetype)databasePoolWithPath:(NSString*)aPath { 28 | return FMDBReturnAutoreleased([[self alloc] initWithPath:aPath]); 29 | } 30 | 31 | + (instancetype)databasePoolWithPath:(NSString*)aPath flags:(int)openFlags { 32 | return FMDBReturnAutoreleased([[self alloc] initWithPath:aPath flags:openFlags]); 33 | } 34 | 35 | - (instancetype)initWithPath:(NSString*)aPath flags:(int)openFlags { 36 | 37 | self = [super init]; 38 | 39 | if (self != nil) { 40 | _path = [aPath copy]; 41 | _lockQueue = dispatch_queue_create([[NSString stringWithFormat:@"fmdb.%@", self] UTF8String], NULL); 42 | _databaseInPool = FMDBReturnRetained([NSMutableArray array]); 43 | _databaseOutPool = FMDBReturnRetained([NSMutableArray array]); 44 | _openFlags = openFlags; 45 | } 46 | 47 | return self; 48 | } 49 | 50 | - (instancetype)initWithPath:(NSString*)aPath 51 | { 52 | // default flags for sqlite3_open 53 | return [self initWithPath:aPath flags:SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE]; 54 | } 55 | 56 | - (instancetype)init { 57 | return [self initWithPath:nil]; 58 | } 59 | 60 | 61 | - (void)dealloc { 62 | 63 | _delegate = 0x00; 64 | FMDBRelease(_path); 65 | FMDBRelease(_databaseInPool); 66 | FMDBRelease(_databaseOutPool); 67 | 68 | if (_lockQueue) { 69 | FMDBDispatchQueueRelease(_lockQueue); 70 | _lockQueue = 0x00; 71 | } 72 | #if ! __has_feature(objc_arc) 73 | [super dealloc]; 74 | #endif 75 | } 76 | 77 | 78 | - (void)executeLocked:(void (^)(void))aBlock { 79 | dispatch_sync(_lockQueue, aBlock); 80 | } 81 | 82 | - (void)pushDatabaseBackInPool:(FMDatabase*)db { 83 | 84 | if (!db) { // db can be null if we set an upper bound on the # of databases to create. 85 | return; 86 | } 87 | 88 | [self executeLocked:^() { 89 | 90 | if ([self->_databaseInPool containsObject:db]) { 91 | [[NSException exceptionWithName:@"Database already in pool" reason:@"The FMDatabase being put back into the pool is already present in the pool" userInfo:nil] raise]; 92 | } 93 | 94 | [self->_databaseInPool addObject:db]; 95 | [self->_databaseOutPool removeObject:db]; 96 | 97 | }]; 98 | } 99 | 100 | - (FMDatabase*)db { 101 | 102 | __block FMDatabase *db; 103 | 104 | 105 | [self executeLocked:^() { 106 | db = [self->_databaseInPool lastObject]; 107 | 108 | BOOL shouldNotifyDelegate = NO; 109 | 110 | if (db) { 111 | [self->_databaseOutPool addObject:db]; 112 | [self->_databaseInPool removeLastObject]; 113 | } 114 | else { 115 | 116 | if (self->_maximumNumberOfDatabasesToCreate) { 117 | NSUInteger currentCount = [self->_databaseOutPool count] + [self->_databaseInPool count]; 118 | 119 | if (currentCount >= self->_maximumNumberOfDatabasesToCreate) { 120 | NSLog(@"Maximum number of databases (%ld) has already been reached!", (long)currentCount); 121 | return; 122 | } 123 | } 124 | 125 | db = [FMDatabase databaseWithPath:self->_path]; 126 | shouldNotifyDelegate = YES; 127 | } 128 | 129 | //This ensures that the db is opened before returning 130 | #if SQLITE_VERSION_NUMBER >= 3005000 131 | BOOL success = [db openWithFlags:self->_openFlags]; 132 | #else 133 | BOOL success = [db open]; 134 | #endif 135 | if (success) { 136 | if ([self->_delegate respondsToSelector:@selector(databasePool:shouldAddDatabaseToPool:)] && ![self->_delegate databasePool:self shouldAddDatabaseToPool:db]) { 137 | [db close]; 138 | db = 0x00; 139 | } 140 | else { 141 | //It should not get added in the pool twice if lastObject was found 142 | if (![self->_databaseOutPool containsObject:db]) { 143 | [self->_databaseOutPool addObject:db]; 144 | 145 | if (shouldNotifyDelegate && [self->_delegate respondsToSelector:@selector(databasePool:didAddDatabase:)]) { 146 | [self->_delegate databasePool:self didAddDatabase:db]; 147 | } 148 | } 149 | } 150 | } 151 | else { 152 | NSLog(@"Could not open up the database at path %@", self->_path); 153 | db = 0x00; 154 | } 155 | }]; 156 | 157 | return db; 158 | } 159 | 160 | - (NSUInteger)countOfCheckedInDatabases { 161 | 162 | __block NSUInteger count; 163 | 164 | [self executeLocked:^() { 165 | count = [self->_databaseInPool count]; 166 | }]; 167 | 168 | return count; 169 | } 170 | 171 | - (NSUInteger)countOfCheckedOutDatabases { 172 | 173 | __block NSUInteger count; 174 | 175 | [self executeLocked:^() { 176 | count = [self->_databaseOutPool count]; 177 | }]; 178 | 179 | return count; 180 | } 181 | 182 | - (NSUInteger)countOfOpenDatabases { 183 | __block NSUInteger count; 184 | 185 | [self executeLocked:^() { 186 | count = [self->_databaseOutPool count] + [self->_databaseInPool count]; 187 | }]; 188 | 189 | return count; 190 | } 191 | 192 | - (void)releaseAllDatabases { 193 | [self executeLocked:^() { 194 | [self->_databaseOutPool removeAllObjects]; 195 | [self->_databaseInPool removeAllObjects]; 196 | }]; 197 | } 198 | 199 | - (void)inDatabase:(void (^)(FMDatabase *db))block { 200 | 201 | FMDatabase *db = [self db]; 202 | 203 | block(db); 204 | 205 | [self pushDatabaseBackInPool:db]; 206 | } 207 | 208 | - (void)beginTransaction:(BOOL)useDeferred withBlock:(void (^)(FMDatabase *db, BOOL *rollback))block { 209 | 210 | BOOL shouldRollback = NO; 211 | 212 | FMDatabase *db = [self db]; 213 | 214 | if (useDeferred) { 215 | [db beginDeferredTransaction]; 216 | } 217 | else { 218 | [db beginTransaction]; 219 | } 220 | 221 | 222 | block(db, &shouldRollback); 223 | 224 | if (shouldRollback) { 225 | [db rollback]; 226 | } 227 | else { 228 | [db commit]; 229 | } 230 | 231 | [self pushDatabaseBackInPool:db]; 232 | } 233 | 234 | - (void)inDeferredTransaction:(void (^)(FMDatabase *db, BOOL *rollback))block { 235 | [self beginTransaction:YES withBlock:block]; 236 | } 237 | 238 | - (void)inTransaction:(void (^)(FMDatabase *db, BOOL *rollback))block { 239 | [self beginTransaction:NO withBlock:block]; 240 | } 241 | #if SQLITE_VERSION_NUMBER >= 3007000 242 | - (NSError*)inSavePoint:(void (^)(FMDatabase *db, BOOL *rollback))block { 243 | 244 | static unsigned long savePointIdx = 0; 245 | 246 | NSString *name = [NSString stringWithFormat:@"savePoint%ld", savePointIdx++]; 247 | 248 | BOOL shouldRollback = NO; 249 | 250 | FMDatabase *db = [self db]; 251 | 252 | NSError *err = 0x00; 253 | 254 | if (![db startSavePointWithName:name error:&err]) { 255 | [self pushDatabaseBackInPool:db]; 256 | return err; 257 | } 258 | 259 | block(db, &shouldRollback); 260 | 261 | if (shouldRollback) { 262 | // We need to rollback and release this savepoint to remove it 263 | [db rollbackToSavePointWithName:name error:&err]; 264 | } 265 | [db releaseSavePointWithName:name error:&err]; 266 | 267 | [self pushDatabaseBackInPool:db]; 268 | 269 | return err; 270 | } 271 | #endif 272 | 273 | @end 274 | -------------------------------------------------------------------------------- /SMSQLiteMigration/FMDatabase/FMDatabaseQueue.h: -------------------------------------------------------------------------------- 1 | // 2 | // FMDatabaseQueue.h 3 | // fmdb 4 | // 5 | // Created by August Mueller on 6/22/11. 6 | // Copyright 2011 Flying Meat Inc. All rights reserved. 7 | // 8 | 9 | #import 10 | #import "sqlite3.h" 11 | 12 | @class FMDatabase; 13 | 14 | /** To perform queries and updates on multiple threads, you'll want to use `FMDatabaseQueue`. 15 | 16 | Using a single instance of `` from multiple threads at once is a bad idea. It has always been OK to make a `` object *per thread*. Just don't share a single instance across threads, and definitely not across multiple threads at the same time. 17 | 18 | Instead, use `FMDatabaseQueue`. Here's how to use it: 19 | 20 | First, make your queue. 21 | 22 | FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:aPath]; 23 | 24 | Then use it like so: 25 | 26 | [queue inDatabase:^(FMDatabase *db) { 27 | [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:1]]; 28 | [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:2]]; 29 | [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:3]]; 30 | 31 | FMResultSet *rs = [db executeQuery:@"select * from foo"]; 32 | while ([rs next]) { 33 | //… 34 | } 35 | }]; 36 | 37 | An easy way to wrap things up in a transaction can be done like this: 38 | 39 | [queue inTransaction:^(FMDatabase *db, BOOL *rollback) { 40 | [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:1]]; 41 | [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:2]]; 42 | [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:3]]; 43 | 44 | if (whoopsSomethingWrongHappened) { 45 | *rollback = YES; 46 | return; 47 | } 48 | // etc… 49 | [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:4]]; 50 | }]; 51 | 52 | `FMDatabaseQueue` will run the blocks on a serialized queue (hence the name of the class). So if you call `FMDatabaseQueue`'s methods from multiple threads at the same time, they will be executed in the order they are received. This way queries and updates won't step on each other's toes, and every one is happy. 53 | 54 | ### See also 55 | 56 | - `` 57 | 58 | @warning Do not instantiate a single `` object and use it across multiple threads. Use `FMDatabaseQueue` instead. 59 | 60 | @warning The calls to `FMDatabaseQueue`'s methods are blocking. So even though you are passing along blocks, they will **not** be run on another thread. 61 | 62 | */ 63 | 64 | @interface FMDatabaseQueue : NSObject { 65 | NSString *_path; 66 | dispatch_queue_t _queue; 67 | FMDatabase *_db; 68 | int _openFlags; 69 | } 70 | 71 | /** Path of database */ 72 | 73 | @property (atomic, retain) NSString *path; 74 | 75 | /** Open flags */ 76 | 77 | @property (atomic, readonly) int openFlags; 78 | 79 | ///---------------------------------------------------- 80 | /// @name Initialization, opening, and closing of queue 81 | ///---------------------------------------------------- 82 | 83 | /** Create queue using path. 84 | 85 | @param aPath The file path of the database. 86 | 87 | @return The `FMDatabaseQueue` object. `nil` on error. 88 | */ 89 | 90 | + (instancetype)databaseQueueWithPath:(NSString*)aPath; 91 | 92 | /** Create queue using path and specified flags. 93 | 94 | @param aPath The file path of the database. 95 | @param openFlags Flags passed to the openWithFlags method of the database 96 | 97 | @return The `FMDatabaseQueue` object. `nil` on error. 98 | */ 99 | + (instancetype)databaseQueueWithPath:(NSString*)aPath flags:(int)openFlags; 100 | 101 | /** Create queue using path. 102 | 103 | @param aPath The file path of the database. 104 | 105 | @return The `FMDatabaseQueue` object. `nil` on error. 106 | */ 107 | 108 | - (instancetype)initWithPath:(NSString*)aPath; 109 | 110 | /** Create queue using path and specified flags. 111 | 112 | @param aPath The file path of the database. 113 | @param openFlags Flags passed to the openWithFlags method of the database 114 | 115 | @return The `FMDatabaseQueue` object. `nil` on error. 116 | */ 117 | 118 | - (instancetype)initWithPath:(NSString*)aPath flags:(int)openFlags; 119 | 120 | /** Returns the Class of 'FMDatabase' subclass, that will be used to instantiate database object. 121 | 122 | Subclasses can override this method to return specified Class of 'FMDatabase' subclass. 123 | 124 | @return The Class of 'FMDatabase' subclass, that will be used to instantiate database object. 125 | */ 126 | 127 | + (Class)databaseClass; 128 | 129 | /** Close database used by queue. */ 130 | 131 | - (void)close; 132 | 133 | ///----------------------------------------------- 134 | /// @name Dispatching database operations to queue 135 | ///----------------------------------------------- 136 | 137 | /** Synchronously perform database operations on queue. 138 | 139 | @param block The code to be run on the queue of `FMDatabaseQueue` 140 | */ 141 | 142 | - (void)inDatabase:(void (^)(FMDatabase *db))block; 143 | 144 | /** Synchronously perform database operations on queue, using transactions. 145 | 146 | @param block The code to be run on the queue of `FMDatabaseQueue` 147 | */ 148 | 149 | - (void)inTransaction:(void (^)(FMDatabase *db, BOOL *rollback))block; 150 | 151 | /** Synchronously perform database operations on queue, using deferred transactions. 152 | 153 | @param block The code to be run on the queue of `FMDatabaseQueue` 154 | */ 155 | 156 | - (void)inDeferredTransaction:(void (^)(FMDatabase *db, BOOL *rollback))block; 157 | 158 | ///----------------------------------------------- 159 | /// @name Dispatching database operations to queue 160 | ///----------------------------------------------- 161 | 162 | /** Synchronously perform database operations using save point. 163 | 164 | @param block The code to be run on the queue of `FMDatabaseQueue` 165 | */ 166 | 167 | #if SQLITE_VERSION_NUMBER >= 3007000 168 | // NOTE: you can not nest these, since calling it will pull another database out of the pool and you'll get a deadlock. 169 | // If you need to nest, use FMDatabase's startSavePointWithName:error: instead. 170 | - (NSError*)inSavePoint:(void (^)(FMDatabase *db, BOOL *rollback))block; 171 | #endif 172 | 173 | @end 174 | 175 | -------------------------------------------------------------------------------- /SMSQLiteMigration/FMDatabase/FMDatabaseQueue.m: -------------------------------------------------------------------------------- 1 | // 2 | // FMDatabaseQueue.m 3 | // fmdb 4 | // 5 | // Created by August Mueller on 6/22/11. 6 | // Copyright 2011 Flying Meat Inc. All rights reserved. 7 | // 8 | 9 | #import "FMDatabaseQueue.h" 10 | #import "FMDatabase.h" 11 | 12 | /* 13 | 14 | Note: we call [self retain]; before using dispatch_sync, just incase 15 | FMDatabaseQueue is released on another thread and we're in the middle of doing 16 | something in dispatch_sync 17 | 18 | */ 19 | 20 | /* 21 | * A key used to associate the FMDatabaseQueue object with the dispatch_queue_t it uses. 22 | * This in turn is used for deadlock detection by seeing if inDatabase: is called on 23 | * the queue's dispatch queue, which should not happen and causes a deadlock. 24 | */ 25 | static const void * const kDispatchQueueSpecificKey = &kDispatchQueueSpecificKey; 26 | 27 | @implementation FMDatabaseQueue 28 | 29 | @synthesize path = _path; 30 | @synthesize openFlags = _openFlags; 31 | 32 | + (instancetype)databaseQueueWithPath:(NSString*)aPath { 33 | 34 | FMDatabaseQueue *q = [[self alloc] initWithPath:aPath]; 35 | 36 | FMDBAutorelease(q); 37 | 38 | return q; 39 | } 40 | 41 | + (instancetype)databaseQueueWithPath:(NSString*)aPath flags:(int)openFlags { 42 | 43 | FMDatabaseQueue *q = [[self alloc] initWithPath:aPath flags:openFlags]; 44 | 45 | FMDBAutorelease(q); 46 | 47 | return q; 48 | } 49 | 50 | + (Class)databaseClass { 51 | return [FMDatabase class]; 52 | } 53 | 54 | - (instancetype)initWithPath:(NSString*)aPath flags:(int)openFlags { 55 | 56 | self = [super init]; 57 | 58 | if (self != nil) { 59 | 60 | _db = [[[self class] databaseClass] databaseWithPath:aPath]; 61 | FMDBRetain(_db); 62 | 63 | #if SQLITE_VERSION_NUMBER >= 3005000 64 | BOOL success = [_db openWithFlags:openFlags]; 65 | #else 66 | BOOL success = [_db open]; 67 | #endif 68 | if (!success) { 69 | NSLog(@"Could not create database queue for path %@", aPath); 70 | FMDBRelease(self); 71 | return 0x00; 72 | } 73 | 74 | _path = FMDBReturnRetained(aPath); 75 | 76 | _queue = dispatch_queue_create([[NSString stringWithFormat:@"fmdb.%@", self] UTF8String], NULL); 77 | dispatch_queue_set_specific(_queue, kDispatchQueueSpecificKey, (__bridge void *)self, NULL); 78 | _openFlags = openFlags; 79 | } 80 | 81 | return self; 82 | } 83 | 84 | - (instancetype)initWithPath:(NSString*)aPath { 85 | 86 | // default flags for sqlite3_open 87 | return [self initWithPath:aPath flags:SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE]; 88 | } 89 | 90 | - (instancetype)init { 91 | return [self initWithPath:nil]; 92 | } 93 | 94 | 95 | - (void)dealloc { 96 | 97 | FMDBRelease(_db); 98 | FMDBRelease(_path); 99 | 100 | if (_queue) { 101 | FMDBDispatchQueueRelease(_queue); 102 | _queue = 0x00; 103 | } 104 | #if ! __has_feature(objc_arc) 105 | [super dealloc]; 106 | #endif 107 | } 108 | 109 | - (void)close { 110 | FMDBRetain(self); 111 | dispatch_sync(_queue, ^() { 112 | [self->_db close]; 113 | FMDBRelease(_db); 114 | self->_db = 0x00; 115 | }); 116 | FMDBRelease(self); 117 | } 118 | 119 | - (FMDatabase*)database { 120 | if (!_db) { 121 | _db = FMDBReturnRetained([FMDatabase databaseWithPath:_path]); 122 | 123 | #if SQLITE_VERSION_NUMBER >= 3005000 124 | BOOL success = [_db openWithFlags:_openFlags]; 125 | #else 126 | BOOL success = [_db open]; 127 | #endif 128 | if (!success) { 129 | NSLog(@"FMDatabaseQueue could not reopen database for path %@", _path); 130 | FMDBRelease(_db); 131 | _db = 0x00; 132 | return 0x00; 133 | } 134 | } 135 | 136 | return _db; 137 | } 138 | 139 | - (void)inDatabase:(void (^)(FMDatabase *db))block { 140 | /* Get the currently executing queue (which should probably be nil, but in theory could be another DB queue 141 | * and then check it against self to make sure we're not about to deadlock. */ 142 | FMDatabaseQueue *currentSyncQueue = (__bridge id)dispatch_get_specific(kDispatchQueueSpecificKey); 143 | assert(currentSyncQueue != self && "inDatabase: was called reentrantly on the same queue, which would lead to a deadlock"); 144 | 145 | FMDBRetain(self); 146 | 147 | dispatch_sync(_queue, ^() { 148 | 149 | FMDatabase *db = [self database]; 150 | block(db); 151 | 152 | if ([db hasOpenResultSets]) { 153 | NSLog(@"Warning: there is at least one open result set around after performing [FMDatabaseQueue inDatabase:]"); 154 | 155 | #if defined(DEBUG) && DEBUG 156 | NSSet *openSetCopy = FMDBReturnAutoreleased([[db valueForKey:@"_openResultSets"] copy]); 157 | for (NSValue *rsInWrappedInATastyValueMeal in openSetCopy) { 158 | FMResultSet *rs = (FMResultSet *)[rsInWrappedInATastyValueMeal pointerValue]; 159 | NSLog(@"query: '%@'", [rs query]); 160 | } 161 | #endif 162 | } 163 | }); 164 | 165 | FMDBRelease(self); 166 | } 167 | 168 | 169 | - (void)beginTransaction:(BOOL)useDeferred withBlock:(void (^)(FMDatabase *db, BOOL *rollback))block { 170 | FMDBRetain(self); 171 | dispatch_sync(_queue, ^() { 172 | 173 | BOOL shouldRollback = NO; 174 | 175 | if (useDeferred) { 176 | [[self database] beginDeferredTransaction]; 177 | } 178 | else { 179 | [[self database] beginTransaction]; 180 | } 181 | 182 | block([self database], &shouldRollback); 183 | 184 | if (shouldRollback) { 185 | [[self database] rollback]; 186 | } 187 | else { 188 | [[self database] commit]; 189 | } 190 | }); 191 | 192 | FMDBRelease(self); 193 | } 194 | 195 | - (void)inDeferredTransaction:(void (^)(FMDatabase *db, BOOL *rollback))block { 196 | [self beginTransaction:YES withBlock:block]; 197 | } 198 | 199 | - (void)inTransaction:(void (^)(FMDatabase *db, BOOL *rollback))block { 200 | [self beginTransaction:NO withBlock:block]; 201 | } 202 | 203 | #if SQLITE_VERSION_NUMBER >= 3007000 204 | - (NSError*)inSavePoint:(void (^)(FMDatabase *db, BOOL *rollback))block { 205 | 206 | static unsigned long savePointIdx = 0; 207 | __block NSError *err = 0x00; 208 | FMDBRetain(self); 209 | dispatch_sync(_queue, ^() { 210 | 211 | NSString *name = [NSString stringWithFormat:@"savePoint%ld", savePointIdx++]; 212 | 213 | BOOL shouldRollback = NO; 214 | 215 | if ([[self database] startSavePointWithName:name error:&err]) { 216 | 217 | block([self database], &shouldRollback); 218 | 219 | if (shouldRollback) { 220 | // We need to rollback and release this savepoint to remove it 221 | [[self database] rollbackToSavePointWithName:name error:&err]; 222 | } 223 | [[self database] releaseSavePointWithName:name error:&err]; 224 | 225 | } 226 | }); 227 | FMDBRelease(self); 228 | return err; 229 | } 230 | #endif 231 | 232 | @end 233 | -------------------------------------------------------------------------------- /SMSQLiteMigration/FMDatabase/FMResultSet.h: -------------------------------------------------------------------------------- 1 | #import 2 | #import "sqlite3.h" 3 | 4 | #ifndef __has_feature // Optional. 5 | #define __has_feature(x) 0 // Compatibility with non-clang compilers. 6 | #endif 7 | 8 | #ifndef NS_RETURNS_NOT_RETAINED 9 | #if __has_feature(attribute_ns_returns_not_retained) 10 | #define NS_RETURNS_NOT_RETAINED __attribute__((ns_returns_not_retained)) 11 | #else 12 | #define NS_RETURNS_NOT_RETAINED 13 | #endif 14 | #endif 15 | 16 | @class FMDatabase; 17 | @class FMStatement; 18 | 19 | /** Represents the results of executing a query on an ``. 20 | 21 | ### See also 22 | 23 | - `` 24 | */ 25 | 26 | @interface FMResultSet : NSObject { 27 | FMDatabase *_parentDB; 28 | FMStatement *_statement; 29 | 30 | NSString *_query; 31 | NSMutableDictionary *_columnNameToIndexMap; 32 | } 33 | 34 | ///----------------- 35 | /// @name Properties 36 | ///----------------- 37 | 38 | /** Executed query */ 39 | 40 | @property (atomic, retain) NSString *query; 41 | 42 | /** `NSMutableDictionary` mapping column names to numeric index */ 43 | 44 | @property (readonly) NSMutableDictionary *columnNameToIndexMap; 45 | 46 | /** `FMStatement` used by result set. */ 47 | 48 | @property (atomic, retain) FMStatement *statement; 49 | 50 | ///------------------------------------ 51 | /// @name Creating and closing database 52 | ///------------------------------------ 53 | 54 | /** Create result set from `` 55 | 56 | @param statement A `` to be performed 57 | 58 | @param aDB A `` to be used 59 | 60 | @return A `FMResultSet` on success; `nil` on failure 61 | */ 62 | 63 | + (instancetype)resultSetWithStatement:(FMStatement *)statement usingParentDatabase:(FMDatabase*)aDB; 64 | 65 | /** Close result set */ 66 | 67 | - (void)close; 68 | 69 | - (void)setParentDB:(FMDatabase *)newDb; 70 | 71 | ///--------------------------------------- 72 | /// @name Iterating through the result set 73 | ///--------------------------------------- 74 | 75 | /** Retrieve next row for result set. 76 | 77 | You must always invoke `next` or `nextWithError` before attempting to access the values returned in a query, even if you're only expecting one. 78 | 79 | @return `YES` if row successfully retrieved; `NO` if end of result set reached 80 | 81 | @see hasAnotherRow 82 | */ 83 | 84 | - (BOOL)next; 85 | 86 | /** Retrieve next row for result set. 87 | 88 | You must always invoke `next` or `nextWithError` before attempting to access the values returned in a query, even if you're only expecting one. 89 | 90 | @param outErr A 'NSError' object to receive any error object (if any). 91 | 92 | @return 'YES' if row successfully retrieved; 'NO' if end of result set reached 93 | 94 | @see hasAnotherRow 95 | */ 96 | 97 | - (BOOL)nextWithError:(NSError **)outErr; 98 | 99 | /** Did the last call to `` succeed in retrieving another row? 100 | 101 | @return `YES` if the last call to `` succeeded in retrieving another record; `NO` if not. 102 | 103 | @see next 104 | 105 | @warning The `hasAnotherRow` method must follow a call to ``. If the previous database interaction was something other than a call to `next`, then this method may return `NO`, whether there is another row of data or not. 106 | */ 107 | 108 | - (BOOL)hasAnotherRow; 109 | 110 | ///--------------------------------------------- 111 | /// @name Retrieving information from result set 112 | ///--------------------------------------------- 113 | 114 | /** How many columns in result set 115 | 116 | @return Integer value of the number of columns. 117 | */ 118 | 119 | - (int)columnCount; 120 | 121 | /** Column index for column name 122 | 123 | @param columnName `NSString` value of the name of the column. 124 | 125 | @return Zero-based index for column. 126 | */ 127 | 128 | - (int)columnIndexForName:(NSString*)columnName; 129 | 130 | /** Column name for column index 131 | 132 | @param columnIdx Zero-based index for column. 133 | 134 | @return columnName `NSString` value of the name of the column. 135 | */ 136 | 137 | - (NSString*)columnNameForIndex:(int)columnIdx; 138 | 139 | /** Result set integer value for column. 140 | 141 | @param columnName `NSString` value of the name of the column. 142 | 143 | @return `int` value of the result set's column. 144 | */ 145 | 146 | - (int)intForColumn:(NSString*)columnName; 147 | 148 | /** Result set integer value for column. 149 | 150 | @param columnIdx Zero-based index for column. 151 | 152 | @return `int` value of the result set's column. 153 | */ 154 | 155 | - (int)intForColumnIndex:(int)columnIdx; 156 | 157 | /** Result set `long` value for column. 158 | 159 | @param columnName `NSString` value of the name of the column. 160 | 161 | @return `long` value of the result set's column. 162 | */ 163 | 164 | - (long)longForColumn:(NSString*)columnName; 165 | 166 | /** Result set long value for column. 167 | 168 | @param columnIdx Zero-based index for column. 169 | 170 | @return `long` value of the result set's column. 171 | */ 172 | 173 | - (long)longForColumnIndex:(int)columnIdx; 174 | 175 | /** Result set `long long int` value for column. 176 | 177 | @param columnName `NSString` value of the name of the column. 178 | 179 | @return `long long int` value of the result set's column. 180 | */ 181 | 182 | - (long long int)longLongIntForColumn:(NSString*)columnName; 183 | 184 | /** Result set `long long int` value for column. 185 | 186 | @param columnIdx Zero-based index for column. 187 | 188 | @return `long long int` value of the result set's column. 189 | */ 190 | 191 | - (long long int)longLongIntForColumnIndex:(int)columnIdx; 192 | 193 | /** Result set `unsigned long long int` value for column. 194 | 195 | @param columnName `NSString` value of the name of the column. 196 | 197 | @return `unsigned long long int` value of the result set's column. 198 | */ 199 | 200 | - (unsigned long long int)unsignedLongLongIntForColumn:(NSString*)columnName; 201 | 202 | /** Result set `unsigned long long int` value for column. 203 | 204 | @param columnIdx Zero-based index for column. 205 | 206 | @return `unsigned long long int` value of the result set's column. 207 | */ 208 | 209 | - (unsigned long long int)unsignedLongLongIntForColumnIndex:(int)columnIdx; 210 | 211 | /** Result set `BOOL` value for column. 212 | 213 | @param columnName `NSString` value of the name of the column. 214 | 215 | @return `BOOL` value of the result set's column. 216 | */ 217 | 218 | - (BOOL)boolForColumn:(NSString*)columnName; 219 | 220 | /** Result set `BOOL` value for column. 221 | 222 | @param columnIdx Zero-based index for column. 223 | 224 | @return `BOOL` value of the result set's column. 225 | */ 226 | 227 | - (BOOL)boolForColumnIndex:(int)columnIdx; 228 | 229 | /** Result set `double` value for column. 230 | 231 | @param columnName `NSString` value of the name of the column. 232 | 233 | @return `double` value of the result set's column. 234 | 235 | */ 236 | 237 | - (double)doubleForColumn:(NSString*)columnName; 238 | 239 | /** Result set `double` value for column. 240 | 241 | @param columnIdx Zero-based index for column. 242 | 243 | @return `double` value of the result set's column. 244 | 245 | */ 246 | 247 | - (double)doubleForColumnIndex:(int)columnIdx; 248 | 249 | /** Result set `NSString` value for column. 250 | 251 | @param columnName `NSString` value of the name of the column. 252 | 253 | @return `NSString` value of the result set's column. 254 | 255 | */ 256 | 257 | - (NSString*)stringForColumn:(NSString*)columnName; 258 | 259 | /** Result set `NSString` value for column. 260 | 261 | @param columnIdx Zero-based index for column. 262 | 263 | @return `NSString` value of the result set's column. 264 | */ 265 | 266 | - (NSString*)stringForColumnIndex:(int)columnIdx; 267 | 268 | /** Result set `NSDate` value for column. 269 | 270 | @param columnName `NSString` value of the name of the column. 271 | 272 | @return `NSDate` value of the result set's column. 273 | */ 274 | 275 | - (NSDate*)dateForColumn:(NSString*)columnName; 276 | 277 | /** Result set `NSDate` value for column. 278 | 279 | @param columnIdx Zero-based index for column. 280 | 281 | @return `NSDate` value of the result set's column. 282 | 283 | */ 284 | 285 | - (NSDate*)dateForColumnIndex:(int)columnIdx; 286 | 287 | /** Result set `NSData` value for column. 288 | 289 | This is useful when storing binary data in table (such as image or the like). 290 | 291 | @param columnName `NSString` value of the name of the column. 292 | 293 | @return `NSData` value of the result set's column. 294 | 295 | */ 296 | 297 | - (NSData*)dataForColumn:(NSString*)columnName; 298 | 299 | /** Result set `NSData` value for column. 300 | 301 | @param columnIdx Zero-based index for column. 302 | 303 | @return `NSData` value of the result set's column. 304 | */ 305 | 306 | - (NSData*)dataForColumnIndex:(int)columnIdx; 307 | 308 | /** Result set `(const unsigned char *)` value for column. 309 | 310 | @param columnName `NSString` value of the name of the column. 311 | 312 | @return `(const unsigned char *)` value of the result set's column. 313 | */ 314 | 315 | - (const unsigned char *)UTF8StringForColumnName:(NSString*)columnName; 316 | 317 | /** Result set `(const unsigned char *)` value for column. 318 | 319 | @param columnIdx Zero-based index for column. 320 | 321 | @return `(const unsigned char *)` value of the result set's column. 322 | */ 323 | 324 | - (const unsigned char *)UTF8StringForColumnIndex:(int)columnIdx; 325 | 326 | /** Result set object for column. 327 | 328 | @param columnName `NSString` value of the name of the column. 329 | 330 | @return Either `NSNumber`, `NSString`, `NSData`, or `NSNull`. If the column was `NULL`, this returns `[NSNull null]` object. 331 | 332 | @see objectForKeyedSubscript: 333 | */ 334 | 335 | - (id)objectForColumnName:(NSString*)columnName; 336 | 337 | /** Result set object for column. 338 | 339 | @param columnIdx Zero-based index for column. 340 | 341 | @return Either `NSNumber`, `NSString`, `NSData`, or `NSNull`. If the column was `NULL`, this returns `[NSNull null]` object. 342 | 343 | @see objectAtIndexedSubscript: 344 | */ 345 | 346 | - (id)objectForColumnIndex:(int)columnIdx; 347 | 348 | /** Result set object for column. 349 | 350 | This method allows the use of the "boxed" syntax supported in Modern Objective-C. For example, by defining this method, the following syntax is now supported: 351 | 352 | id result = rs[@"employee_name"]; 353 | 354 | This simplified syntax is equivalent to calling: 355 | 356 | id result = [rs objectForKeyedSubscript:@"employee_name"]; 357 | 358 | which is, it turns out, equivalent to calling: 359 | 360 | id result = [rs objectForColumnName:@"employee_name"]; 361 | 362 | @param columnName `NSString` value of the name of the column. 363 | 364 | @return Either `NSNumber`, `NSString`, `NSData`, or `NSNull`. If the column was `NULL`, this returns `[NSNull null]` object. 365 | */ 366 | 367 | - (id)objectForKeyedSubscript:(NSString *)columnName; 368 | 369 | /** Result set object for column. 370 | 371 | This method allows the use of the "boxed" syntax supported in Modern Objective-C. For example, by defining this method, the following syntax is now supported: 372 | 373 | id result = rs[0]; 374 | 375 | This simplified syntax is equivalent to calling: 376 | 377 | id result = [rs objectForKeyedSubscript:0]; 378 | 379 | which is, it turns out, equivalent to calling: 380 | 381 | id result = [rs objectForColumnName:0]; 382 | 383 | @param columnIdx Zero-based index for column. 384 | 385 | @return Either `NSNumber`, `NSString`, `NSData`, or `NSNull`. If the column was `NULL`, this returns `[NSNull null]` object. 386 | */ 387 | 388 | - (id)objectAtIndexedSubscript:(int)columnIdx; 389 | 390 | /** Result set `NSData` value for column. 391 | 392 | @param columnName `NSString` value of the name of the column. 393 | 394 | @return `NSData` value of the result set's column. 395 | 396 | @warning If you are going to use this data after you iterate over the next row, or after you close the 397 | result set, make sure to make a copy of the data first (or just use ``/``) 398 | If you don't, you're going to be in a world of hurt when you try and use the data. 399 | 400 | */ 401 | 402 | - (NSData*)dataNoCopyForColumn:(NSString*)columnName NS_RETURNS_NOT_RETAINED; 403 | 404 | /** Result set `NSData` value for column. 405 | 406 | @param columnIdx Zero-based index for column. 407 | 408 | @return `NSData` value of the result set's column. 409 | 410 | @warning If you are going to use this data after you iterate over the next row, or after you close the 411 | result set, make sure to make a copy of the data first (or just use ``/``) 412 | If you don't, you're going to be in a world of hurt when you try and use the data. 413 | 414 | */ 415 | 416 | - (NSData*)dataNoCopyForColumnIndex:(int)columnIdx NS_RETURNS_NOT_RETAINED; 417 | 418 | /** Is the column `NULL`? 419 | 420 | @param columnIdx Zero-based index for column. 421 | 422 | @return `YES` if column is `NULL`; `NO` if not `NULL`. 423 | */ 424 | 425 | - (BOOL)columnIndexIsNull:(int)columnIdx; 426 | 427 | /** Is the column `NULL`? 428 | 429 | @param columnName `NSString` value of the name of the column. 430 | 431 | @return `YES` if column is `NULL`; `NO` if not `NULL`. 432 | */ 433 | 434 | - (BOOL)columnIsNull:(NSString*)columnName; 435 | 436 | 437 | /** Returns a dictionary of the row results mapped to case sensitive keys of the column names. 438 | 439 | @returns `NSDictionary` of the row results. 440 | 441 | @warning The keys to the dictionary are case sensitive of the column names. 442 | */ 443 | 444 | - (NSDictionary*)resultDictionary; 445 | 446 | /** Returns a dictionary of the row results 447 | 448 | @see resultDictionary 449 | 450 | @warning **Deprecated**: Please use `` instead. Also, beware that `` is case sensitive! 451 | */ 452 | 453 | - (NSDictionary*)resultDict __attribute__ ((deprecated)); 454 | 455 | ///----------------------------- 456 | /// @name Key value coding magic 457 | ///----------------------------- 458 | 459 | /** Performs `setValue` to yield support for key value observing. 460 | 461 | @param object The object for which the values will be set. This is the key-value-coding compliant object that you might, for example, observe. 462 | 463 | */ 464 | 465 | - (void)kvcMagic:(id)object; 466 | 467 | 468 | @end 469 | 470 | -------------------------------------------------------------------------------- /SMSQLiteMigration/FMDatabase/FMResultSet.m: -------------------------------------------------------------------------------- 1 | #import "FMResultSet.h" 2 | #import "FMDatabase.h" 3 | #import "unistd.h" 4 | 5 | @interface FMDatabase () 6 | - (void)resultSetDidClose:(FMResultSet *)resultSet; 7 | @end 8 | 9 | 10 | @implementation FMResultSet 11 | @synthesize query=_query; 12 | @synthesize statement=_statement; 13 | 14 | + (instancetype)resultSetWithStatement:(FMStatement *)statement usingParentDatabase:(FMDatabase*)aDB { 15 | 16 | FMResultSet *rs = [[FMResultSet alloc] init]; 17 | 18 | [rs setStatement:statement]; 19 | [rs setParentDB:aDB]; 20 | 21 | NSParameterAssert(![statement inUse]); 22 | [statement setInUse:YES]; // weak reference 23 | 24 | return FMDBReturnAutoreleased(rs); 25 | } 26 | 27 | - (void)finalize { 28 | [self close]; 29 | [super finalize]; 30 | } 31 | 32 | - (void)dealloc { 33 | [self close]; 34 | 35 | FMDBRelease(_query); 36 | _query = nil; 37 | 38 | FMDBRelease(_columnNameToIndexMap); 39 | _columnNameToIndexMap = nil; 40 | 41 | #if ! __has_feature(objc_arc) 42 | [super dealloc]; 43 | #endif 44 | } 45 | 46 | - (void)close { 47 | [_statement reset]; 48 | FMDBRelease(_statement); 49 | _statement = nil; 50 | 51 | // we don't need this anymore... (i think) 52 | //[_parentDB setInUse:NO]; 53 | [_parentDB resultSetDidClose:self]; 54 | _parentDB = nil; 55 | } 56 | 57 | - (int)columnCount { 58 | return sqlite3_column_count([_statement statement]); 59 | } 60 | 61 | - (NSMutableDictionary *)columnNameToIndexMap { 62 | if (!_columnNameToIndexMap) { 63 | int columnCount = sqlite3_column_count([_statement statement]); 64 | _columnNameToIndexMap = [[NSMutableDictionary alloc] initWithCapacity:(NSUInteger)columnCount]; 65 | int columnIdx = 0; 66 | for (columnIdx = 0; columnIdx < columnCount; columnIdx++) { 67 | [_columnNameToIndexMap setObject:[NSNumber numberWithInt:columnIdx] 68 | forKey:[[NSString stringWithUTF8String:sqlite3_column_name([_statement statement], columnIdx)] lowercaseString]]; 69 | } 70 | } 71 | return _columnNameToIndexMap; 72 | } 73 | 74 | - (void)kvcMagic:(id)object { 75 | 76 | int columnCount = sqlite3_column_count([_statement statement]); 77 | 78 | int columnIdx = 0; 79 | for (columnIdx = 0; columnIdx < columnCount; columnIdx++) { 80 | 81 | const char *c = (const char *)sqlite3_column_text([_statement statement], columnIdx); 82 | 83 | // check for a null row 84 | if (c) { 85 | NSString *s = [NSString stringWithUTF8String:c]; 86 | 87 | [object setValue:s forKey:[NSString stringWithUTF8String:sqlite3_column_name([_statement statement], columnIdx)]]; 88 | } 89 | } 90 | } 91 | 92 | #pragma clang diagnostic push 93 | #pragma clang diagnostic ignored "-Wdeprecated-implementations" 94 | 95 | - (NSDictionary*)resultDict { 96 | 97 | NSUInteger num_cols = (NSUInteger)sqlite3_data_count([_statement statement]); 98 | 99 | if (num_cols > 0) { 100 | NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:num_cols]; 101 | 102 | NSEnumerator *columnNames = [[self columnNameToIndexMap] keyEnumerator]; 103 | NSString *columnName = nil; 104 | while ((columnName = [columnNames nextObject])) { 105 | id objectValue = [self objectForColumnName:columnName]; 106 | [dict setObject:objectValue forKey:columnName]; 107 | } 108 | 109 | return FMDBReturnAutoreleased([dict copy]); 110 | } 111 | else { 112 | NSLog(@"Warning: There seem to be no columns in this set."); 113 | } 114 | 115 | return nil; 116 | } 117 | 118 | #pragma clang diagnostic pop 119 | 120 | - (NSDictionary*)resultDictionary { 121 | 122 | NSUInteger num_cols = (NSUInteger)sqlite3_data_count([_statement statement]); 123 | 124 | if (num_cols > 0) { 125 | NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:num_cols]; 126 | 127 | int columnCount = sqlite3_column_count([_statement statement]); 128 | 129 | int columnIdx = 0; 130 | for (columnIdx = 0; columnIdx < columnCount; columnIdx++) { 131 | 132 | NSString *columnName = [NSString stringWithUTF8String:sqlite3_column_name([_statement statement], columnIdx)]; 133 | id objectValue = [self objectForColumnIndex:columnIdx]; 134 | [dict setObject:objectValue forKey:columnName]; 135 | } 136 | 137 | return dict; 138 | } 139 | else { 140 | NSLog(@"Warning: There seem to be no columns in this set."); 141 | } 142 | 143 | return nil; 144 | } 145 | 146 | 147 | 148 | 149 | - (BOOL)next { 150 | return [self nextWithError:nil]; 151 | } 152 | 153 | - (BOOL)nextWithError:(NSError **)outErr { 154 | 155 | int rc = sqlite3_step([_statement statement]); 156 | 157 | if (SQLITE_BUSY == rc || SQLITE_LOCKED == rc) { 158 | NSLog(@"%s:%d Database busy (%@)", __FUNCTION__, __LINE__, [_parentDB databasePath]); 159 | NSLog(@"Database busy"); 160 | if (outErr) { 161 | *outErr = [_parentDB lastError]; 162 | } 163 | } 164 | else if (SQLITE_DONE == rc || SQLITE_ROW == rc) { 165 | // all is well, let's return. 166 | } 167 | else if (SQLITE_ERROR == rc) { 168 | NSLog(@"Error calling sqlite3_step (%d: %s) rs", rc, sqlite3_errmsg([_parentDB sqliteHandle])); 169 | if (outErr) { 170 | *outErr = [_parentDB lastError]; 171 | } 172 | } 173 | else if (SQLITE_MISUSE == rc) { 174 | // uh oh. 175 | NSLog(@"Error calling sqlite3_step (%d: %s) rs", rc, sqlite3_errmsg([_parentDB sqliteHandle])); 176 | if (outErr) { 177 | if (_parentDB) { 178 | *outErr = [_parentDB lastError]; 179 | } 180 | else { 181 | // If 'next' or 'nextWithError' is called after the result set is closed, 182 | // we need to return the appropriate error. 183 | NSDictionary* errorMessage = [NSDictionary dictionaryWithObject:@"parentDB does not exist" forKey:NSLocalizedDescriptionKey]; 184 | *outErr = [NSError errorWithDomain:@"FMDatabase" code:SQLITE_MISUSE userInfo:errorMessage]; 185 | } 186 | 187 | } 188 | } 189 | else { 190 | // wtf? 191 | NSLog(@"Unknown error calling sqlite3_step (%d: %s) rs", rc, sqlite3_errmsg([_parentDB sqliteHandle])); 192 | if (outErr) { 193 | *outErr = [_parentDB lastError]; 194 | } 195 | } 196 | 197 | 198 | if (rc != SQLITE_ROW) { 199 | [self close]; 200 | } 201 | 202 | return (rc == SQLITE_ROW); 203 | } 204 | 205 | - (BOOL)hasAnotherRow { 206 | return sqlite3_errcode([_parentDB sqliteHandle]) == SQLITE_ROW; 207 | } 208 | 209 | - (int)columnIndexForName:(NSString*)columnName { 210 | columnName = [columnName lowercaseString]; 211 | 212 | NSNumber *n = [[self columnNameToIndexMap] objectForKey:columnName]; 213 | 214 | if (n) { 215 | return [n intValue]; 216 | } 217 | 218 | NSLog(@"Warning: I could not find the column named '%@'.", columnName); 219 | 220 | return -1; 221 | } 222 | 223 | 224 | 225 | - (int)intForColumn:(NSString*)columnName { 226 | return [self intForColumnIndex:[self columnIndexForName:columnName]]; 227 | } 228 | 229 | - (int)intForColumnIndex:(int)columnIdx { 230 | return sqlite3_column_int([_statement statement], columnIdx); 231 | } 232 | 233 | - (long)longForColumn:(NSString*)columnName { 234 | return [self longForColumnIndex:[self columnIndexForName:columnName]]; 235 | } 236 | 237 | - (long)longForColumnIndex:(int)columnIdx { 238 | return (long)sqlite3_column_int64([_statement statement], columnIdx); 239 | } 240 | 241 | - (long long int)longLongIntForColumn:(NSString*)columnName { 242 | return [self longLongIntForColumnIndex:[self columnIndexForName:columnName]]; 243 | } 244 | 245 | - (long long int)longLongIntForColumnIndex:(int)columnIdx { 246 | return sqlite3_column_int64([_statement statement], columnIdx); 247 | } 248 | 249 | - (unsigned long long int)unsignedLongLongIntForColumn:(NSString*)columnName { 250 | return [self unsignedLongLongIntForColumnIndex:[self columnIndexForName:columnName]]; 251 | } 252 | 253 | - (unsigned long long int)unsignedLongLongIntForColumnIndex:(int)columnIdx { 254 | return (unsigned long long int)[self longLongIntForColumnIndex:columnIdx]; 255 | } 256 | 257 | - (BOOL)boolForColumn:(NSString*)columnName { 258 | return [self boolForColumnIndex:[self columnIndexForName:columnName]]; 259 | } 260 | 261 | - (BOOL)boolForColumnIndex:(int)columnIdx { 262 | return ([self intForColumnIndex:columnIdx] != 0); 263 | } 264 | 265 | - (double)doubleForColumn:(NSString*)columnName { 266 | return [self doubleForColumnIndex:[self columnIndexForName:columnName]]; 267 | } 268 | 269 | - (double)doubleForColumnIndex:(int)columnIdx { 270 | return sqlite3_column_double([_statement statement], columnIdx); 271 | } 272 | 273 | - (NSString*)stringForColumnIndex:(int)columnIdx { 274 | 275 | if (sqlite3_column_type([_statement statement], columnIdx) == SQLITE_NULL || (columnIdx < 0)) { 276 | return nil; 277 | } 278 | 279 | const char *c = (const char *)sqlite3_column_text([_statement statement], columnIdx); 280 | 281 | if (!c) { 282 | // null row. 283 | return nil; 284 | } 285 | 286 | return [NSString stringWithUTF8String:c]; 287 | } 288 | 289 | - (NSString*)stringForColumn:(NSString*)columnName { 290 | return [self stringForColumnIndex:[self columnIndexForName:columnName]]; 291 | } 292 | 293 | - (NSDate*)dateForColumn:(NSString*)columnName { 294 | return [self dateForColumnIndex:[self columnIndexForName:columnName]]; 295 | } 296 | 297 | - (NSDate*)dateForColumnIndex:(int)columnIdx { 298 | 299 | if (sqlite3_column_type([_statement statement], columnIdx) == SQLITE_NULL || (columnIdx < 0)) { 300 | return nil; 301 | } 302 | 303 | return [_parentDB hasDateFormatter] ? [_parentDB dateFromString:[self stringForColumnIndex:columnIdx]] : [NSDate dateWithTimeIntervalSince1970:[self doubleForColumnIndex:columnIdx]]; 304 | } 305 | 306 | 307 | - (NSData*)dataForColumn:(NSString*)columnName { 308 | return [self dataForColumnIndex:[self columnIndexForName:columnName]]; 309 | } 310 | 311 | - (NSData*)dataForColumnIndex:(int)columnIdx { 312 | 313 | if (sqlite3_column_type([_statement statement], columnIdx) == SQLITE_NULL || (columnIdx < 0)) { 314 | return nil; 315 | } 316 | 317 | const char *dataBuffer = sqlite3_column_blob([_statement statement], columnIdx); 318 | int dataSize = sqlite3_column_bytes([_statement statement], columnIdx); 319 | 320 | if (dataBuffer == NULL) { 321 | return nil; 322 | } 323 | 324 | return [NSData dataWithBytes:(const void *)dataBuffer length:(NSUInteger)dataSize]; 325 | } 326 | 327 | 328 | - (NSData*)dataNoCopyForColumn:(NSString*)columnName { 329 | return [self dataNoCopyForColumnIndex:[self columnIndexForName:columnName]]; 330 | } 331 | 332 | - (NSData*)dataNoCopyForColumnIndex:(int)columnIdx { 333 | 334 | if (sqlite3_column_type([_statement statement], columnIdx) == SQLITE_NULL || (columnIdx < 0)) { 335 | return nil; 336 | } 337 | 338 | const char *dataBuffer = sqlite3_column_blob([_statement statement], columnIdx); 339 | int dataSize = sqlite3_column_bytes([_statement statement], columnIdx); 340 | 341 | NSData *data = [NSData dataWithBytesNoCopy:(void *)dataBuffer length:(NSUInteger)dataSize freeWhenDone:NO]; 342 | 343 | return data; 344 | } 345 | 346 | 347 | - (BOOL)columnIndexIsNull:(int)columnIdx { 348 | return sqlite3_column_type([_statement statement], columnIdx) == SQLITE_NULL; 349 | } 350 | 351 | - (BOOL)columnIsNull:(NSString*)columnName { 352 | return [self columnIndexIsNull:[self columnIndexForName:columnName]]; 353 | } 354 | 355 | - (const unsigned char *)UTF8StringForColumnIndex:(int)columnIdx { 356 | 357 | if (sqlite3_column_type([_statement statement], columnIdx) == SQLITE_NULL || (columnIdx < 0)) { 358 | return nil; 359 | } 360 | 361 | return sqlite3_column_text([_statement statement], columnIdx); 362 | } 363 | 364 | - (const unsigned char *)UTF8StringForColumnName:(NSString*)columnName { 365 | return [self UTF8StringForColumnIndex:[self columnIndexForName:columnName]]; 366 | } 367 | 368 | - (id)objectForColumnIndex:(int)columnIdx { 369 | int columnType = sqlite3_column_type([_statement statement], columnIdx); 370 | 371 | id returnValue = nil; 372 | 373 | if (columnType == SQLITE_INTEGER) { 374 | returnValue = [NSNumber numberWithLongLong:[self longLongIntForColumnIndex:columnIdx]]; 375 | } 376 | else if (columnType == SQLITE_FLOAT) { 377 | returnValue = [NSNumber numberWithDouble:[self doubleForColumnIndex:columnIdx]]; 378 | } 379 | else if (columnType == SQLITE_BLOB) { 380 | returnValue = [self dataForColumnIndex:columnIdx]; 381 | } 382 | else { 383 | //default to a string for everything else 384 | returnValue = [self stringForColumnIndex:columnIdx]; 385 | } 386 | 387 | if (returnValue == nil) { 388 | returnValue = [NSNull null]; 389 | } 390 | 391 | return returnValue; 392 | } 393 | 394 | - (id)objectForColumnName:(NSString*)columnName { 395 | return [self objectForColumnIndex:[self columnIndexForName:columnName]]; 396 | } 397 | 398 | // returns autoreleased NSString containing the name of the column in the result set 399 | - (NSString*)columnNameForIndex:(int)columnIdx { 400 | return [NSString stringWithUTF8String: sqlite3_column_name([_statement statement], columnIdx)]; 401 | } 402 | 403 | - (void)setParentDB:(FMDatabase *)newDb { 404 | _parentDB = newDb; 405 | } 406 | 407 | - (id)objectAtIndexedSubscript:(int)columnIdx { 408 | return [self objectForColumnIndex:columnIdx]; 409 | } 410 | 411 | - (id)objectForKeyedSubscript:(NSString *)columnName { 412 | return [self objectForColumnName:columnName]; 413 | } 414 | 415 | 416 | @end 417 | -------------------------------------------------------------------------------- /SMSQLiteMigration/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | en 7 | CFBundleExecutable 8 | $(EXECUTABLE_NAME) 9 | CFBundleIdentifier 10 | $(PRODUCT_BUNDLE_IDENTIFIER) 11 | CFBundleInfoDictionaryVersion 12 | 6.0 13 | CFBundleName 14 | $(PRODUCT_NAME) 15 | CFBundlePackageType 16 | APPL 17 | CFBundleShortVersionString 18 | 1.0 19 | CFBundleVersion 20 | 1 21 | LSRequiresIPhoneOS 22 | 23 | UILaunchStoryboardName 24 | LaunchScreen 25 | UIMainStoryboardFile 26 | Main 27 | UIRequiredDeviceCapabilities 28 | 29 | armv7 30 | 31 | UISupportedInterfaceOrientations 32 | 33 | UIInterfaceOrientationPortrait 34 | UIInterfaceOrientationLandscapeLeft 35 | UIInterfaceOrientationLandscapeRight 36 | 37 | UISupportedInterfaceOrientations~ipad 38 | 39 | UIInterfaceOrientationPortrait 40 | UIInterfaceOrientationPortraitUpsideDown 41 | UIInterfaceOrientationLandscapeLeft 42 | UIInterfaceOrientationLandscapeRight 43 | 44 | 45 | 46 | -------------------------------------------------------------------------------- /SMSQLiteMigration/TestDB.sqlite: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Hyman00/SMSQLiteMigration/a3f4ec7a3720a89ae5bf21ece4b2d6abeb44cd16/SMSQLiteMigration/TestDB.sqlite -------------------------------------------------------------------------------- /SMSQLiteMigration/TestDB_AddColumn.sqlite: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Hyman00/SMSQLiteMigration/a3f4ec7a3720a89ae5bf21ece4b2d6abeb44cd16/SMSQLiteMigration/TestDB_AddColumn.sqlite -------------------------------------------------------------------------------- /SMSQLiteMigration/TestDB_AddIndex.sqlite: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Hyman00/SMSQLiteMigration/a3f4ec7a3720a89ae5bf21ece4b2d6abeb44cd16/SMSQLiteMigration/TestDB_AddIndex.sqlite -------------------------------------------------------------------------------- /SMSQLiteMigration/TestDB_AddTable.sqlite: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Hyman00/SMSQLiteMigration/a3f4ec7a3720a89ae5bf21ece4b2d6abeb44cd16/SMSQLiteMigration/TestDB_AddTable.sqlite -------------------------------------------------------------------------------- /SMSQLiteMigration/TestDB_DeleteIndex.sqlite: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Hyman00/SMSQLiteMigration/a3f4ec7a3720a89ae5bf21ece4b2d6abeb44cd16/SMSQLiteMigration/TestDB_DeleteIndex.sqlite -------------------------------------------------------------------------------- /SMSQLiteMigration/TestDB_DeleteTable.sqlite: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Hyman00/SMSQLiteMigration/a3f4ec7a3720a89ae5bf21ece4b2d6abeb44cd16/SMSQLiteMigration/TestDB_DeleteTable.sqlite -------------------------------------------------------------------------------- /SMSQLiteMigration/TestDB_RenameTabel.sqlite: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Hyman00/SMSQLiteMigration/a3f4ec7a3720a89ae5bf21ece4b2d6abeb44cd16/SMSQLiteMigration/TestDB_RenameTabel.sqlite -------------------------------------------------------------------------------- /SMSQLiteMigration/ViewController.h: -------------------------------------------------------------------------------- 1 | // 2 | // ViewController.h 3 | // SMSQLiteMigration 4 | // 5 | // Created by 00 on 2016/11/30. 6 | // Copyright © 2016年 00. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface ViewController : UIViewController 12 | 13 | 14 | @end 15 | 16 | -------------------------------------------------------------------------------- /SMSQLiteMigration/ViewController.m: -------------------------------------------------------------------------------- 1 | // 2 | // ViewController.m 3 | // SMSQLiteMigration 4 | // 5 | // Created by 00 on 2016/11/30. 6 | // Copyright © 2016年 00. All rights reserved. 7 | // 8 | 9 | #import "ViewController.h" 10 | 11 | @interface ViewController () 12 | 13 | @end 14 | 15 | @implementation ViewController 16 | 17 | - (void)viewDidLoad { 18 | [super viewDidLoad]; 19 | // Do any additional setup after loading the view, typically from a nib. 20 | } 21 | 22 | 23 | - (void)didReceiveMemoryWarning { 24 | [super didReceiveMemoryWarning]; 25 | // Dispose of any resources that can be recreated. 26 | } 27 | 28 | 29 | @end 30 | -------------------------------------------------------------------------------- /SMSQLiteMigration/main.m: -------------------------------------------------------------------------------- 1 | // 2 | // main.m 3 | // SMSQLiteMigration 4 | // 5 | // Created by 00 on 2016/11/30. 6 | // Copyright © 2016年 00. All rights reserved. 7 | // 8 | 9 | #import 10 | #import "AppDelegate.h" 11 | 12 | int main(int argc, char * argv[]) { 13 | @autoreleasepool { 14 | return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class])); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /SMSQLiteMigrationTests/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | en 7 | CFBundleExecutable 8 | $(EXECUTABLE_NAME) 9 | CFBundleIdentifier 10 | $(PRODUCT_BUNDLE_IDENTIFIER) 11 | CFBundleInfoDictionaryVersion 12 | 6.0 13 | CFBundleName 14 | $(PRODUCT_NAME) 15 | CFBundlePackageType 16 | BNDL 17 | CFBundleShortVersionString 18 | 1.0 19 | CFBundleVersion 20 | 1 21 | 22 | 23 | -------------------------------------------------------------------------------- /SMSQLiteMigrationTests/SMSQLiteMigrationTests.m: -------------------------------------------------------------------------------- 1 | // 2 | // SMSQLiteMigrationTests.m 3 | // SMSQLiteMigrationTests 4 | // 5 | // Created by 00 on 2016/11/30. 6 | // Copyright © 2016年 00. All rights reserved. 7 | // 8 | 9 | #import 10 | #import "FMDatabase.h" 11 | #import "SMSQLiteMigration.h" 12 | 13 | @interface SMSQLiteMigrationTests : XCTestCase 14 | @property (nonatomic, strong) FMDatabase *db; 15 | @property (nonatomic, strong) NSString *dbPath; 16 | @property (nonatomic, assign) NSInteger version; 17 | @end 18 | 19 | @implementation SMSQLiteMigrationTests 20 | 21 | - (void)setUp { 22 | [super setUp]; 23 | 24 | NSString *dbDir = [NSHomeDirectory() stringByAppendingPathComponent:@"TestDB"]; 25 | if ([[NSFileManager defaultManager] fileExistsAtPath:dbDir] == NO) { 26 | [[NSFileManager defaultManager] createDirectoryAtPath:dbDir withIntermediateDirectories:YES attributes:nil error:nil]; 27 | } 28 | 29 | NSString *dbPath = [dbDir stringByAppendingPathComponent:@"TestDB.sqlite"]; 30 | NSString *bundleDB = [[NSBundle mainBundle] pathForResource:@"TestDB" ofType:@"sqlite"]; 31 | 32 | if ([[NSFileManager defaultManager] fileExistsAtPath:dbPath] == NO) { 33 | [[NSFileManager defaultManager] copyItemAtPath:bundleDB toPath:dbPath error:nil]; 34 | } 35 | 36 | self.dbPath = dbPath; 37 | NSLog(@"dbPath: %@", dbPath); 38 | 39 | self.db = [[FMDatabase alloc] initWithPath:dbPath]; 40 | NSAssert([self.db open], @"Fail to open DB!!!"); 41 | 42 | self.version = [SMSQLiteMigration versionForDB:self.db]; 43 | self.version++; 44 | } 45 | 46 | - (void)tearDown { 47 | BOOL success = [self.db close]; 48 | NSAssert(success, @"Fail to close DB!!!"); 49 | } 50 | 51 | - (void)testAddColumn { 52 | NSLog(@">>>>>>>>>>>>>>>> testAddColumn >>>>>>>>>>>>>>>>>>"); 53 | 54 | for (int i = 1; i <= 10; i++) { 55 | NSString *tid = [NSString stringWithFormat:@"id_%d", i]; 56 | NSString *name = [NSString stringWithFormat:@"name_%d", i]; 57 | NSString *sql = [NSString stringWithFormat:@"insert into t1(id, name) values('%@', '%@')", tid, name]; 58 | BOOL success = [self.db executeUpdate:sql]; 59 | NSLog(@">>>>>>>>>>>>>> %d", success); 60 | } 61 | 62 | NSString *referDBPath = [[NSBundle mainBundle] pathForResource:@"TestDB_AddColumn" ofType:@"sqlite"]; 63 | FMDatabase *referDB = [[FMDatabase alloc] initWithPath:referDBPath]; 64 | NSAssert([referDB open], @"Fail to open the refer DB!!!"); 65 | 66 | BOOL success = [SMSQLiteMigration migrateLocalDB:self.db referDB:referDB toVersion:self.version]; 67 | NSAssert(success, @"Fail to add column!!!"); 68 | 69 | for (int i = 1; i <= 10; i++) { 70 | NSString *tid = [NSString stringWithFormat:@"A_id_%d", i]; 71 | NSString *name = [NSString stringWithFormat:@"A_name_%d", i]; 72 | NSString *new_column = [NSString stringWithFormat:@"new_column_%d", i]; 73 | NSString *new_column_notnull = [NSString stringWithFormat:@"new_column_notnull_%d", i]; 74 | NSString *new_column_dltv = [NSString stringWithFormat:@"new_column_dltv_%d", i]; 75 | NSString *sql = [NSString stringWithFormat:@"insert into t1(id, name, new_column, new_column_notnull, new_column_dltv) values('%@', '%@', '%@', '%@', '%@')", tid, name, new_column, new_column_notnull, new_column_dltv]; 76 | BOOL success = [self.db executeUpdate:sql]; 77 | NSLog(@"Afeter >>>>>>>>>>>>>> %d", success); 78 | } 79 | } 80 | 81 | - (void)testAddTable { 82 | NSLog(@">>>>>>>>>>>>>>>> testAddTable >>>>>>>>>>>>>>>>>>"); 83 | NSString *referDBPath = [[NSBundle mainBundle] pathForResource:@"TestDB_AddTable" ofType:@"sqlite"]; 84 | FMDatabase *referDB = [[FMDatabase alloc] initWithPath:referDBPath]; 85 | NSAssert([referDB open], @"Fail to open the refer DB!!!"); 86 | 87 | BOOL success = [SMSQLiteMigration migrateLocalDB:self.db referDB:referDB toVersion:self.version]; 88 | NSAssert(success, @"Fail to add table!!!"); 89 | 90 | for (int i = 1; i <= 10; i++) { 91 | NSString *tid = [NSString stringWithFormat:@"B_id_%d", i]; 92 | NSString *name = [NSString stringWithFormat:@"B_name_%d", i]; 93 | int num = i; 94 | NSString *sql = [NSString stringWithFormat:@"insert into t2(t2_id, t2_name, t2_num) values('%@', '%@', %d)", tid, name, num]; 95 | BOOL success = [self.db executeUpdate:sql]; 96 | NSLog(@">>>>>>>>>>>>>> %d", success); 97 | } 98 | } 99 | 100 | - (void)testDeleteTable { 101 | NSString *referDBPath = [[NSBundle mainBundle] pathForResource:@"TestDB_DeleteTable" ofType:@"sqlite"]; 102 | FMDatabase *referDB = [[FMDatabase alloc] initWithPath:referDBPath]; 103 | NSAssert([referDB open], @"Fail to open the refer DB!!!"); 104 | 105 | BOOL success = [SMSQLiteMigration migrateLocalDB:self.db referDB:referDB toVersion:self.version]; 106 | NSAssert(success, @"Fail to delete table!!!"); 107 | } 108 | 109 | - (void)testRenameTable { 110 | NSString *referDBPath = [[NSBundle mainBundle] pathForResource:@"TestDB_RenameTabel" ofType:@"sqlite"]; 111 | FMDatabase *referDB = [[FMDatabase alloc] initWithPath:referDBPath]; 112 | NSAssert([referDB open], @"Fail to open the refer DB!!!"); 113 | 114 | BOOL success = [SMSQLiteMigration migrateLocalDB:self.db referDB:referDB toVersion:self.version]; 115 | NSAssert(success, @"Fail to rename table!!!"); 116 | } 117 | 118 | - (void)testAddIndex { 119 | NSString *referDBPath = [[NSBundle mainBundle] pathForResource:@"TestDB_AddIndex" ofType:@"sqlite"]; 120 | FMDatabase *referDB = [[FMDatabase alloc] initWithPath:referDBPath]; 121 | NSAssert([referDB open], @"Fail to open the refer DB!!!"); 122 | 123 | BOOL success = [SMSQLiteMigration migrateLocalDB:self.db referDB:referDB toVersion:self.version]; 124 | NSAssert(success, @"Fail to add index!!!"); 125 | } 126 | 127 | - (void)testDeleteIndex { 128 | NSString *referDBPath = [[NSBundle mainBundle] pathForResource:@"TestDB_DeleteIndex" ofType:@"sqlite"]; 129 | FMDatabase *referDB = [[FMDatabase alloc] initWithPath:referDBPath]; 130 | NSAssert([referDB open], @"Fail to open the refer DB!!!"); 131 | 132 | BOOL success = [SMSQLiteMigration migrateLocalDB:self.db referDB:referDB toVersion:self.version]; 133 | NSAssert(success, @"Fail to delete index!!!"); 134 | } 135 | 136 | @end 137 | --------------------------------------------------------------------------------