Repository: ccgus/fmdb Branch: master Commit: d3abf748a278 Files: 55 Total size: 545.7 KB Directory structure: gitextract_7bzgmki1/ ├── .gitignore ├── .travis.yml ├── CHANGES_AND_TODO_LIST.txt ├── COCOAPODS.md ├── CONTRIBUTORS.txt ├── FMDB.podspec ├── LICENSE.txt ├── Package.swift ├── README.markdown ├── Tests/ │ ├── Base.lproj/ │ │ └── InfoPlist.strings │ ├── FMDBTempDBTests.h │ ├── FMDBTempDBTests.m │ ├── FMDatabaseAdditionsTests.m │ ├── FMDatabaseFTS3Tests.m │ ├── FMDatabaseFTS3WithModuleNameTests.m │ ├── FMDatabasePoolTests.m │ ├── FMDatabaseQueueTests.m │ ├── FMDatabaseTests.m │ ├── FMResultSetTests.m │ ├── Schemes/ │ │ └── Tests.xcscheme │ ├── Tests-Info.plist │ ├── Tests-Prefix.pch │ └── en.lproj/ │ └── InfoPlist.strings ├── fmdb.1 ├── fmdb.xcodeproj/ │ ├── project.pbxproj │ └── xcshareddata/ │ └── xcschemes/ │ ├── FMDB MacOS.xcscheme │ ├── FMDB iOS.xcscheme │ ├── FMDB watchOS.xcscheme │ └── FMDB xrOS.xcscheme ├── privacy/ │ ├── PrivacyInfo.xcprivacy │ └── README.md └── src/ ├── extra/ │ ├── InMemoryOnDiskIO/ │ │ ├── FMDatabase+InMemoryOnDiskIO.h │ │ └── FMDatabase+InMemoryOnDiskIO.m │ └── fts3/ │ ├── FMDatabase+FTS3.h │ ├── FMDatabase+FTS3.m │ ├── FMTokenizers.h │ ├── FMTokenizers.m │ └── fts3_tokenizer.h ├── fmdb/ │ ├── FMDB.h │ ├── FMDatabase+SQLCipher.h │ ├── FMDatabase+SQLCipher.m │ ├── FMDatabase.h │ ├── FMDatabase.m │ ├── FMDatabaseAdditions.h │ ├── FMDatabaseAdditions.m │ ├── FMDatabasePool.h │ ├── FMDatabasePool.m │ ├── FMDatabaseQueue.h │ ├── FMDatabaseQueue.m │ ├── FMResultSet.h │ ├── FMResultSet.m │ ├── Info.plist │ └── info-xrOS.plist └── sample/ ├── fmdb_Prefix.pch └── main.m ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ .DS_Store build *.xcodeproj/*.pbxuser *.xcodeproj/*.perspectivev3 *.xcodeproj/xcuserdata fmdb.xcodeproj/*.mode1v3 *.xcodeproj/project.xcworkspace/xcuserdata/ fmdb.xcodeproj/project.xcworkspace .swiftpm ================================================ FILE: .travis.yml ================================================ language: objective-c xcode_project: fmdb.xcodeproj xcode_scheme: Tests before_install: - mkdir -p "fmdb.xcodeproj/xcshareddata/xcschemes" && cp Tests/Schemes/*.xcscheme "fmdb.xcodeproj/xcshareddata/xcschemes/" ================================================ FILE: CHANGES_AND_TODO_LIST.txt ================================================ TODO: Zip, nada, zilch. Got any ideas? If you would like to contribute some code ... awesome! I just ask that you make it conform to the coding conventions already set in here, and to add the necessary of tests for your new code to tests target. And of course, the code should be of general use to more than just a couple of folks. Send your patches to gus@flyingmeat.com. 2024.05.29 Version 2.7.12 Fix Privacy Manifest resource bundling for CocoaPods and Swift Package Manager installation methods. 2023.02.08 - 2023.05.23 Versions 2.7.9 - 2.7.11 CocoaPods-related fixes and tweaks. 2020.03.25 Version 2.7.8 Add `valueForColumn` functions to expose `sqlite3_column_type`. Add comments to `dataForColumn` re SQL behavior of zero-length BLOBs. 2020.05.06 Version 2.7.7 Add `prepare` and `bind` methods so you can prepare a statement once and bind values repeatedly. 2020.04.23 Version 2.7.6 A new tag for the Swift Package Manager. 2018.10.23 Version 2.7.5 Xcode 10 support. Probably some other stuff over the past year as well. Added confidence inspiring release notes. Also the tests pass. 2017.10.23 Version 2.7.4 Added support for explicit transactions. Add warning that `beginTransaction` and `inTransaction` behavior is likely to change. 2017.10.20 Version 2.7.3 Added support for immediate transactions and checkpoint. (thanks to @benasher44) Updated nullability of `FMDatabaseQueue` initialization methods. (thanks to @robotive) In a related correction, we updated README to avoid confusing reference to nullability changes in 2.7. (In 2.7, as part of the nullability audit, I (@robertryan) accidentally declared a few `FMDatabaseQueue` initializers to be nonnull, but @robotive pointed out that they actually _were_ nullable. Most of that nullability audit stands as it was released in 2.7.0, but this fixes a few little errors. Minor correction to README, whereby Swift example code implicitly suggested using Documents folder for database, whereas with the advent of the new Files app, Apple suggests using the "Application Support" directory for files that are not documents for end-user interaction. Clearly, use whatever is appropriate in your case, but no longer assume that you should just place files in Documents folder, as that is often not the appropriate location. 2017.06.01 Version 2.7.2 Make blocks `nonescaping` (thanks to @benasher44) Update method documentation. 2017.06.01 Version 2.7.1 Adjust `valueLong` return type and `resultLong` parameter to suppress warning. Fix pointer comparison to avoid static analysis warning in `columnIndexForName`. 2017.05.26 Version 2.7 Audited library for nullability, offering informational warnings for Objective-C users during static analysis, but significantly changes interface for Swift users, more accurately representing parameters and return values as optional or non-optional, as appropriate. Renamed a number of methods, deprecating old names. Converted some methods to properties. Again, it should be largely transparent from Objective-C users, but Swift users will find they'll just have to remove some `()` in their code, lending itself to more logical looking code. The `objectForColumn` used to return `NSNull` if you supplied it an invalid subscript. It now returns `nil`, more customary for subscript operators. For more information, see https://github.com/ccgus/fmdb/pull/584. 2015.12.28 Removed `sqlite3.h` from the headers to simplify incorporation of FMDB into a framework. This eliminates the dreaded "non-modular headers" error in frameworks. To accomplish this, the few references to SQLite pointers have been changed to return `void` pointers. This means that if you have application code that used SQLite pointers exposed by FMDB, you may have to cast the pointer to the appropriate type when you use it (and `#import ` yourself). In general, we would advise against using SQLite pointers unless you absolutely need to. Also changed the `FMDatabaseVariadic.swift` to throw errors for Swift 2. 2015.10.29 Added renditions of `executeUpdate:values:error:` and `executeQuery:values:error:`, which in Swift 2 throw errors. 2015.01.23 Added Swift renditions of the variadic methods of `FMDatabaseAdditions`. 2014.10.19 Added a `nextWithError:` to `FMResultSet`. Thanks to Roshan Muralidharan for the patch. 2014.09.10 New classes for exposing SQLite's FTS features. Thanks to Andrew Goodale for the code. 2014.04.23 New executeStatements: method, which will take a single UTF-8 string with multiple statements in it. This is great for batch updates. There is also a executeStatements:withResultBlock: version which takes a callback block which will be used for any statements which return rows in the bulk statement. Thanks to Rob Ryan for contributing code for this. Deprecated `update:withErrorAndBindings:` in favor of `executeUpdate:withErrorAndBindings:` or `executeUpdate:values:error:`. 2014.04.09 Added back in busy handler code after a brief hiatus (check out the 2013.12.10 notes). But now doing so with sqlite3_busy_handler instead of while loops in the various execution places. Added some new optional classes that will help with doing batch updates - check out FMSQLStatementSplitter.h for more info. Thanks to Julius Scott for the patches. 2014.03.08 A few administrative changes: - Move FMDB source files into three subdirectories, either src/fmdb, src/sample, or src/extras. - Renamed fmdb.m to main.m and moved it into src/sample so that it's clear its a sample and it won't be included in project for those users who manually drag fmdb source into their projects. - Created FMDB.h for those users who would prefer to do a single #import and get all of the key headers. 2014.01.17 It's never been safe to reentrantly call -[FMDatabaseQueue inDatabase:], as it would block. Which can be kind of annoying - so now FMDB will crash instead (thanks to Mike Ash for the patch). 2013.12.10 Lots of little updates - new test targets, ARC simplification, and open flags to FMDatabaseQueue (thanks Graham Dennis), FMDatabaseQueue now has + (Class)databaseClass; which can return a new subclass of FMDatabase for custom stuff (thanks Timur Islamgulov), ## IMPORTANT## int busyRetryTimeout has been change to NSTimeInterval busyTimeout in FMDatabase. Instead of using it's homegrown "try again every so often if it's locked", we use sqlite's built in support for this. Why wasn't FMDatabase using it before? Because Gus didn't know about it. Thanks to Jens Alfke for pointing this out and providing some code to work with. 2013.10.21 Fixed a problem where having statement caching turned on would cause issues when trying to use two result sets with the same query but different binding parameters. Thanks to Nick Hodapp for the original patch. Fixed a problem where save points weren't being created with the correct names, and were not cleaned up properly. Thanks to Graham Dennis for the patches. 2013.10.16 Added methods that expose va_list arguments. Thanks to Ibrahim Ennafaa for the patch. 2013.09.26 Logs errors is now turned on by default. It's easy to turn off, and if you're seeing errors then you should probably fix those. 2013.06.26 Added `NS_FORMAT_FUNCTION` qualifier to `executeQueryWithFormat` and `executeUpdateWithFormat`. These methods take format strings and variable number of arguments and you will now receive compiler warnings if the types of your parameters dont match the format string. 2013.06.04 Merged in Robert Ryan's comments in .h header files. These comments hopefully make the .h more readable, but just as importantly, can be parsed by [`appledoc`](http://gentlebytes.com/appledoc/) to create HTML documentation or Xcode docsets. - To build that HTML documentation, once you've installed `appledoc`, you issue the command [note Jan 2015: the `no-create-docset` needed due to recent changes to `appledoc`]: appledoc --project-name FMDB --project-company ccgus --explicit-crossref --no-merge-categories --no-create-docset --output ../Documentation --ignore *.m . - If you want online help integrated right into Xcode (which is no longer needed because Xcode now automatically integrates documentation found in the .h files), you can issue the command: appledoc --project-name FMDB --project-company ccgus --explicit-crossref --merge-categories --install-docset --output --ignore *.m ../Documentation . 2013.05.24 Merged in Chris Wright's date format additions to FMDatabase. Fixed a problem where executeUpdateWithFormat: + %@ as a placeholder and the value was nil would cause a bad value to be inserted. Thanks to rustybox on github for the fix. Fixed a variable argument crash if an incorrect number of arguments are passed in - patch by Joshua Tessier. Baked in support for the new application_id pragma in SQLite version 3.7.17: - (uint32_t)applicationID; - (void)setApplicationID:(uint32_t)appID; - (NSString*)applicationIDString; - (void)setApplicationIDString:(NSString*)s; 2013.04.17 Added two new methods to FMDatabase for setting crypto keys, which take NSData objects. Thanks to Phillip Kast for the patch! 2013.02.19 Fixed potential dereference of NULL outErr argument in -startSavePointWithName:error: and -releaseSavePointWithName:error:. Thanks to Jim Correia for the patch! 2013.02.05 Added an "extra" folder which contains additional things which might be useful for programmers, but which I don't think should be part of the standard classes. At this time- there's only a single category in there which will load and save an on disk database to an in memory database. Thanks to Peter Carr who provided these additions! 2013.01.31 Lazy init of columnNameToIndexMap in FMResultSet, and you are now able to use it before asking for any rows first. Thanks to Daniel Dickison for the patch! 2012.12.17 Now resetting cached statements before executing a query on them (as well as resetting them at the close of a result set). There was an issue where if you used the same query twice without closing the result set of the first one, you would get results back from the previous query, or maybe an exhausted result set. Thanks to note173 on github for pointing out the problem. 2012.12.13 Changed up how the binding count is calculated when passing a dictionary for named parameter support. Thanks to Samuel Chen for pointing out the problem. 2012.11.23 Added keyed and indexed subscript support to FMResultSet- so you can do use the fancy boxed syntax against it (rs[@"foo"] & rs[0]). Thanks to Robert Ryan for the patches! 2012.08.08 Fixed some problems when compiling with ARC against the 10.8 SDK (patch from Geoffrey Foster!). 2012.05.29: Changed up the behavior of binding empty NSData objects ([NSData data]). It will now insert an empty value, rather than a null value- which is consistent with [NSMutableData data] and empty strings (see https://github.com/ccgus/fmdb/issues/73 for a discussion on this). Thanks to Jens Alfke for pointing this out! 2012.05.25: Deprecated columnExists:columnName: in favor of columnExists:inTableWithName: Remembered to update the changes notes. I've been forgetting to do this recently. 2012.03.22: Deprecated resultDict and replaced it with resultDictionary on FMResultSet. Slight change in behavior as well- resultDictionary will return case sensitive keys. Fixed a problem with getTableSchema: not working with table names that start with a number. 2012.02.10: Changed up FMDatabasePool so that you can't "pop" it from a pool anymore. I just consider this too risky- use the block based functions instead. Also provided a good reason in main.m for why you should use FMDatabaseQueue instead. Search for "ONLY_USE_THE_POOL_IF_YOU_ARE_DOING_READS". I consider this branch 2.0 at this point- I'll let it bake for a couple of days, then push it to the main repo. 2012.01.06: Added a new method to FMDatabase to make custom functions out of a block: - (void)makeFunctionNamed:(NSString*)name maximumArguments:(int)count withBlock:(void (^)(sqlite3_context *context, int argc, sqlite3_value **argv))block Check out the function "testSQLiteFunction" in main.m for an example. 2011.07.14: Added methods for named parameters, using keys from an NSDictionary (Thanks to Drarok Ithaqua for the patches!) Changed FMDatabase's "- (BOOL)update:(NSString*)sql error:(NSError**)outErr bind:(id)bindArgs, ... " to "- (BOOL)update:(NSString*)sql withErrorAndBindings:(NSError**)outErr, ..." as the previous method didn't actually work as advertised in the way it was written. Thanks to @jaekwon for pointing this out. 2011.06.22 Changed some methods to properties. Hello 2011. Added a warning when you try and use a database that wasn't opened. Hacked together based on patches from Drarok Ithaqua. Fixed a problem under GC where leaked statments were keeping a database from closing. Patch from Chris Dolan. Added + (BOOL)isThreadSafe to FMDatabase. It'll let you know if the version of SQLite you are running is compiled with it's thread safe options. THIS DOES NOT MEAN FMDATABASE IS THREAD SAFE. I haven't done a review of it for this case, so I'm just saying. 2011.04.09 Added a method to validate a SQL statement. Added a method to retrieve the number of columns in a result set. Added two methods to execute queries and updates with NSString-style format specifiers. Thanks to Dave DeLong for the patches! 2011.03.12 Added compatibility with garbage collection. When an FMDatabase is closed, all open FMResultSets pertaining to that database are also closed. Added: - (id) objectForColumnIndex:(int)columnIdx; - (id) objectForColumnName:(NSString*)columnName; Changes by Dave DeLong. 2011.02.05 The -(int)changes; method on FMDatabase is a bit more robust now, and there's a new static library target. And if a database path is nil, we now open up a :memory: database. Patch from Pascal Pfiffner! 2011.01.13 Happy New Year! Now checking for SQLITE_LOCKED along with SQLITE_BUSY when trying to perform a query. Patch from Jeff Meininger! 2010.12.28 Fixed some compiler warnings (thanks to Casey Fleser!) 2010.11.30 Added and updated some new methods to take NSError** params. Only execute the assertion macros if NS_BLOCK_ASSERTIONS is not set. Patch from David E. Wheeler! 2010.09.19 The signature for FMDatabase's executeQuery* methods now return FMResultSet instead if id. Patch from Augie Fackler! 2010.08.24: Added resultDict to FMResultSet, which returns a dictionary of column values. Thanks to Pascal Pfiffner for the patch! Cleaned up some formatting. 2010.06.21: Changed up FMDatabase's close method to return a boolean, and fixed a compiler warning when compiling in 64bit land. Thanks to Jens Alfke for the patches! 2010.04.04: Added: dateForQuery which works like the other fooForQuery methods. Thanks to Matt Stevens for the patch! 2009.10.18: Added: FMDB now checks for longLongValue in NSNumbers passed for selects or updates, and binds that value to an sqlite int64 Thanks for the patch from Brian Stern! Changed: renamed getDataBaseSchema: to getSchema. It didn't actually use the param. whooops. 2009.10.14: Reworked: - (id)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray *)arguments; - (BOOL) executeUpdate:(NSString*)sql withArgumentsInArray:(NSArray *)arguments; These two methods now point to: - (id) executeQuery:(NSString*)sql withArgumentsInArray:(NSArray*)arrayArgs orVAList:(va_list)args; - (BOOL) executeUpdate:(NSString*)sql withArgumentsInArray:(NSArray*)arrayArgs orVAList:(va_list)args; because the vargs were causing headaches in 64bit land, and on the iphone, and it's fragile n' stuff. Added: - (FMResultSet*) getTableSchema:(NSString*)tableName; - (BOOL) columnExists:(NSString*)tableName columnName:(NSString*)columnName; to FMDatabaseAdditions. Patch from OZLB 2009.09.22 Disabled the following FMDatabaseAdditions when compiled as 64 bit: - (id)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray *)arguments; and - (BOOL) executeUpdate:(NSString*)sql withArgumentsInArray:(NSArray *)arguments; Since they crash, I just print out a warning now. Got a patch to fix it? Send it to gus@flyingmeat.com Added: - (BOOL) tableExists:(NSString*)tableName; - (FMResultSet*) getDataBaseSchema:(NSString*)tableName; to FMDatabaseAdditions. Patch from OZLB 2009.09.1 Added: - (BOOL) openWithFlags:(int)flags; To FMDatabase, which allows you to open up the database with certain flags for sqlite 3.5+ Thanks to Dan Wright for the addition. 2009.07.17 Added: - (const unsigned char *) UTF8StringForColumnIndex:(int)columnIdx; - (const unsigned char *) UTF8StringForColumnName:(NSString*)columnName; to FMResultSet, patch from Nathan Stitt. 2009.05.23 Added: - (id)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray *)arguments; - (BOOL) executeUpdate:(NSString*)sql withArgumentsInArray:(NSArray *)arguments; thanks to code from Phong Long. Fix to FMResultSet's - (BOOL) hadError, as it was returning true for SQLITE_ROW & SQLITE_DONE, which aren't actually errors. Added: - (BOOL) hasAnotherRow; which lets you know if there is another row waiting in the result set. Thanks to code from Dave DeLong. 2009.05.10 replaced sqlite3_prepare calls with sqlite3_prepare_v2, since it's shiny and new. Now making sure not to call any assembly if on the iphone (asm{ trap }). Tested on 10.6. It works. Not that I didn't expect it not to- but you never know… 2009.05.05 stringForColumnIndex, stringForColumn, dataForColumnIndex, dataForColumn, dataNoCopyForColumnIndex, and dataNoCopyForColumn now return nil if a null value was inserted into its table row. dateForColumnIndex already did this. Also added the following methods to test if a column is null or not: - (BOOL) columnIndexIsNull:(int)columnIdx - (BOOL) columnIsNull:(NSString*)columnName And finally, just general code cleanup + refactoring. Happy Cinco de Mayo! 2009.04.27 added columnNameForIndex: to FMResultSet which returns the column name for the given index. 2009.04.12 dateForColumnIndex: now returns null, if a null value was inserted into its table row. Patch by Robbie Hanson. 2009.03.11 Now importing unistd.h, which the absence of was causing some problems on the iPhone. Reported by multiple people, but Hal Mueller actually got me to make the change. 2009.03.03 Added (int)changes; to FMDatabase. From the sqlite docs: "This function returns the number of database rows that were changed (or inserted or deleted) by the most recent SQL statement." Patch contributed by Tracy Harton 2009.01.02 HAPPY NEW YEAR WOOOO! Added dataNoCopyForColumn: and dataNoCopyForColumnIndex: to FMResultSet. If you are going to use this data after you iterate over the next row, or after you close the result set, make sure to make a copy of the data first (or just use dataForColumn/dataForColumnIndex) If you don't, you're going to be in a world of hurt when you try and use the data. 2008.12.29 Some changes to make Clang's static analysis happy (http://clang.llvm.org/StaticAnalysis.html). (patch provided by Matt Comi) 2008.12.14 Added longLongIntForColumn: and longLongIntForColumnIndex: to FMResultSet. (patch provided by Will Cosgrove) 2008.11.20 Added a check for NSNull in bindObject, which works just like passing nil does (patch provided by Robert Tolar Haining) 2008.11.02 Removed the block keeping you from performing updates or selects while going through a result set. 2008.10.30 Some bug fixes + warning fixes from Brian Stern (thanks again Brian!) 2008.10.03 Fixed a crasher in FMResultSet's close where if the parent DB was already released, the result set would be talking to a bad address and fmdb went boom. (thanks to Brian Stern for the patch) 2008.06.06 Thanks to Zach Wily for the return of FMDatabaseAdditions! 2008.06.03: Removed all exceptions, now you should use [db hadError] to check for an error. I hate (ns)exceptions, I'm not sure why I put them in. Moved to google code. Various little cleanup thingies. 2008.07.03 Thanks to Kris Markel for some extra trace outputs, and a fix where the database would be locked if it was too busy. 2008.07.10 Thanks to Daniel Pasco and Bil Moorehead for catching a problem where the column names lookup table was created on every row iteration. Doh! 2008.07.18 FMDatabase will now cache statements if you turn it on using shouldCacheStatements:YES. In theory, this should speed things up. Test it out, let me know if it makes things good for ya. Note: This is pretty new code, so it hasn't gone through a lot of testing... you've been warned. (seems to work though!) 2008.00.01 Fixed a problemo that kept it from compiling for the iPhone (Thanks to Sam Steele for the patch) questions? comments? patches? Send them to gus@flyingmeat.com ================================================ FILE: COCOAPODS.md ================================================ # CocoaPods release process 1. Update `s.version` in `FMDB.Podspec`. 2. Tag the release (`git tag x.y.z && git push --tags`). 3. Lint the podspec as a pre-check. - Run `pod spec lint` from within a clean working copy. - If you have any failures, address the errors mentioned. - Sometimes, errors are cryptic. A common problem is not having **all** of the supported simulators (macOS, iOS, watchOS, and tvOS) installed and updated. - You can narrow down the problem platform(s) with e.g. `pod spec lint --platforms=watchos` to see which pass and which fail. - You can also get a _lot_ more info with `pod spec lint --verbose`. 4. Push the podspec up to CocoaPods with `pod trunk push`. You will need access as well as an active session (`pod trunk me` / `pod trunk register`). 5. 🍻 ================================================ FILE: CONTRIBUTORS.txt ================================================ Thanks to the following folks for patches and other contributions: D. Richard Hipp (The author of SQLite) Dominic Yu Zach Wily Kris Markel Blackhole Media Daniel Pasco Bil Moorehead Sam Steele Brian Stern Robert Tolar Haining Will Cosgrove Matt Comi Tracy Harton Robbie Hanson Wouter F. Wessels Phong Long Nathan Stitt Dan Wright OZLB Matt Stevens Jens Alfke Pascal Pfiffner Augie Fackler David E. Wheeler Casey Fleser Jeff Meininger Pascal Pfiffner Dave DeLong Drarok Ithaqua Chris Dolan Sriram Patil Geoffrey Foster Robert Ryan Samuel Chen Daniel Dickison Peter Carr Jim Correia Phillip Kast Chris Wright Joshua Tessier Graham Dennis Nick Hodapp Xianliang Li (Oldman) David Hart Mike Ash Julius Scott Justin Miller Troy Stump Aaaaannnd, Gus Mueller (that's me!) ================================================ FILE: FMDB.podspec ================================================ Pod::Spec.new do |s| s.name = 'FMDB' s.version = '2.7.12' s.summary = 'A Cocoa / Objective-C wrapper around SQLite.' s.homepage = 'https://github.com/ccgus/fmdb' s.license = 'MIT' s.author = { 'August Mueller' => 'gus@flyingmeat.com' } s.source = { :git => 'https://github.com/ccgus/fmdb.git', :tag => "#{s.version}" } s.requires_arc = true s.ios.deployment_target = '12.0' s.osx.deployment_target = '10.13' s.watchos.deployment_target = '7.0' s.tvos.deployment_target = '12.0' s.cocoapods_version = '>= 1.12.0' s.default_subspec = 'standard' s.subspec 'Core' do |ss| ss.source_files = 'src/fmdb/FM*.{h,m}' ss.exclude_files = 'src/fmdb.m' ss.header_dir = 'fmdb' ss.resource_bundles = { 'FMDB_Privacy' => 'privacy/PrivacyInfo.xcprivacy' } end # use the built-in library version of sqlite3 s.subspec 'standard' do |ss| ss.dependency 'FMDB/Core' ss.library = 'sqlite3' end # use the built-in library version of sqlite3 with custom FTS tokenizer source files s.subspec 'FTS' do |ss| ss.dependency 'FMDB/standard' ss.source_files = 'src/extra/fts3/*.{h,m}' end # build the latest stable version of sqlite3 s.subspec 'standalone' do |ss| ss.dependency 'FMDB/Core' ss.dependency 'sqlite3', '~> 3.46' ss.xcconfig = { 'OTHER_CFLAGS' => '$(inherited) -DFMDB_SQLITE_STANDALONE' } end # build with FTS support and custom FTS tokenizer source files s.subspec 'standalone-fts' do |ss| ss.dependency 'FMDB/Core' ss.dependency 'sqlite3/fts', '~> 3.46' ss.xcconfig = { 'OTHER_CFLAGS' => '$(inherited) -DFMDB_SQLITE_STANDALONE' } ss.source_files = 'src/extra/fts3/*.{h,m}' end # use SQLCipher and enable -DSQLITE_HAS_CODEC flag s.subspec 'SQLCipher' do |ss| ss.dependency 'FMDB/Core' ss.dependency 'SQLCipher', '~> 4.6' ss.xcconfig = { 'OTHER_CFLAGS' => '$(inherited) -DSQLITE_HAS_CODEC -DHAVE_USLEEP=1 -DSQLCIPHER_CRYPTO', 'HEADER_SEARCH_PATHS' => 'SQLCipher' } end end ================================================ FILE: LICENSE.txt ================================================ If you are using FMDB in your project, I'd love to hear about it. Let Gus know by sending an email to gus@flyingmeat.com. And if you happen to come across either Gus Mueller or Rob Ryan in a bar, you might consider purchasing a drink of their choosing if FMDB has been useful to you. Finally, and shortly, this is the MIT License. Copyright (c) 2008-2014 Flying Meat Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: Package.swift ================================================ // swift-tools-version:6.1 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let applePlatforms: [PackageDescription.Platform] = [.iOS, .macOS, .watchOS, .tvOS, .visionOS] let sqlcipherTraitTargetCondition: TargetDependencyCondition? = .when(platforms: applePlatforms, traits: ["SQLCipher"]) let sqlcipherTraitBuildSettingCondition: BuildSettingCondition? = .when(platforms: applePlatforms, traits: ["SQLCipher"]) let package = Package( name: "FMDB", products: [ // Products define the executables and libraries produced by a package, and make them visible to other packages. .library(name: "FMDB", targets: ["FMDB"]), ], traits: [ .trait(name: "SQLCipher", description: "Enables SQLCipher encryption when a passphrase is supplied to FMDatabase") ], dependencies: [ .package(url:"https://github.com/sqlcipher/SQLCipher.swift", from: "4.11.0") ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. // Targets can depend on other targets in this package, and on products in packages which this package depends on. .target( name: "FMDB", dependencies: [ .product(name: "SQLCipher", package: "SQLCipher.swift", condition: sqlcipherTraitTargetCondition), ], path: "src/fmdb", resources: [.process("../../privacy/PrivacyInfo.xcprivacy")], publicHeadersPath: ".", cSettings: [ .define("SQLITE_HAS_CODEC", to: nil, sqlcipherTraitBuildSettingCondition), .define("SQLCIPHER_CRYPTO", to: nil, sqlcipherTraitBuildSettingCondition) ] ) ] ) ================================================ FILE: README.markdown ================================================ # FMDB v2.7 [![CocoaPods Compatible](https://img.shields.io/cocoapods/v/FMDB.svg)](https://img.shields.io/cocoapods/v/FMDB.svg) [![Carthage Compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) This is an Objective-C wrapper around [SQLite](https://sqlite.org/). ## The FMDB Mailing List: https://groups.google.com/group/fmdb ## Read the SQLite FAQ: https://www.sqlite.org/faq.html Since FMDB is built on top of SQLite, you're going to want to read this page top to bottom at least once. And while you're there, make sure to bookmark the SQLite Documentation page: https://www.sqlite.org/docs.html ## Contributing Do you have an awesome idea that deserves to be in FMDB? You might consider pinging ccgus first to make sure he hasn't already ruled it out for some reason. Otherwise pull requests are great, and make sure you stick to the local coding conventions. However, please be patient and if you haven't heard anything from ccgus for a week or more, you might want to send a note asking what's up. ## Installing ### CocoaPods FMDB can be installed using [CocoaPods](https://cocoapods.org/). If you haven't done so already, you might want to initialize the project, to have it produce a `Podfile` template for you: ``` $ pod init ``` Then, edit the `Podfile`, adding `FMDB`: ```ruby # Uncomment the next line to define a global platform for your project # platform :ios, '12.0' target 'MyApp' do # Comment the next line if you're not using Swift and don't want to use dynamic frameworks use_frameworks! # Pods for MyApp2 pod 'FMDB' # pod 'FMDB/FTS' # FMDB with FTS # pod 'FMDB/standalone' # FMDB with latest SQLite amalgamation source # pod 'FMDB/standalone/FTS' # FMDB with latest SQLite amalgamation source and FTS # pod 'FMDB/SQLCipher' # FMDB with SQLCipher end ``` Then install the pods: ``` $ pod install ``` Then open the `.xcworkspace` rather than the `.xcodeproj`. For more information on Cocoapods visit https://cocoapods.org. **If using FMDB with [SQLCipher](https://www.zetetic.net/sqlcipher/) you must use the FMDB/SQLCipher subspec. The FMDB/SQLCipher subspec declares SQLCipher as a dependency, allowing FMDB to be compiled with the `-DSQLITE_HAS_CODEC` flag.** ### Carthage Once you make sure you have [the latest version of Carthage](https://github.com/Carthage/Carthage/releases), you can open up a command line terminal, navigate to your project's main directory, and then do the following commands: ``` $ echo ' github "ccgus/fmdb" ' > ./Cartfile $ carthage update ``` You can then configure your project as outlined in Carthage's [Getting Started](https://github.com/Carthage/Carthage#getting-started) (i.e. for iOS, adding the framework to the "Link Binary with Libraries" in your target and adding the `copy-frameworks` script; in macOS, adding the framework to the list of "Embedded Binaries"). ### Swift Package Manager Declare FMDB as a package dependency. ```swift .package( name: "FMDB", url: "https://github.com/ccgus/fmdb", .upToNextMinor(from: "2.7.12")), ``` Use FMDB in target dependencies ```swift .product(name: "FMDB", package: "FMDB") ``` #### Swift Package Manager with SQLCipher Encryption If you want to use [SQLCipher](https://www.zetetic.net/sqlcipher/) with FMDB Swift Package you can specify the `SQLCipher` trait when consuming FMDB Swift Package. ```swift depedencies: [ .package(url: "https://github.com/ccgus/fmdb", from: "2.7.12", traits: ["SQLCipher"]) ] ``` As of Xcode 16.4 (16F6), there's no direct way in the Xcode UI to select trait variations so you'll need to use a local wrapper package to pull in the FMDB dependency with the `SQLCipher` trait enabled: ```swift // swift-tools-version: 6.1 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "AppDependencies", platforms: [ .macOS(.v10_14), .iOS(.v13), .macCatalyst(.v13), .watchOS(.v8), .tvOS(.v15), .visionOS(.v1) ], products: [ .library( name: "AppDependencies", targets: ["AppDependencies"]), ], dependencies: [ .package( url: "https://github.com/ccgus/fmdb", from: "2.7.12", traits: ["SQLCipher"]) ], targets: [ .target( name: "AppDependencies", dependencies: [ .product( name: "FMDB", package: "FMDB") ] ) ] ) ``` Within Xcode add your local `AppDependencies` wrapper package as a package dependency and FMDB with SQLCipher functionality will be accessible. Using the `SQLCipher` trait will cause FMDB to include a dependency on SQLCipher.swift and enable `FMDatabase+SQLCipher` methods to set the database key and encrypt a new database: ```swift import FMDB let db = FMDatabase(path: NSTemporaryDirectory().appending("tmp.db")) guard db.open() else { print("Unable to open datbase") return } db.setKey("sup3rs3cr3t") // perform database operations to read from/write to the encrypted database db.close() ``` To encrypt an existing database: ```swift // path to unencrypted db let plaintextDb = FMDatabase(path: NSTemporaryDirectory().appending("unencrypted.db")) guard plaintextDb.open() else { print("Unable to open database") return } // path to export encrypted db to (non-existent prior to export) let encryptedDbPath = NSTemporaryDirectory().appending("encrypted.db") // attach encrypted db using desired key try plaintextDb.executeUpdate("ATTACH DATABASE ? AS encrypted KEY ?", values: [encryptedDbPath, "encryptedPass"]) // sqlcipher_export providing the alias of the attached encrypted db plaintextDb.executeStatements("SELECT sqlcipher_export('encrypted');") // detach the encrypted db plaintextDb.executeStatements("DETACH DATABASE encrypted;") ``` ## FMDB Class Reference: https://ccgus.github.io/fmdb/html/index.html ## Automatic Reference Counting (ARC) or Manual Memory Management? You can use either style in your Cocoa project. FMDB will figure out which you are using at compile time and do the right thing. ## What's New in FMDB 2.7 FMDB 2.7 attempts to support a more natural interface. This represents a fairly significant change for Swift developers (audited for nullability; shifted to properties in external interfaces where possible rather than methods; etc.). For Objective-C developers, this should be a fairly seamless transition (unless you were using the ivars that were previously exposed in the public interface, which you shouldn't have been doing, anyway!). ### Nullability and Swift Optionals FMDB 2.7 is largely the same as prior versions, but has been audited for nullability. For Objective-C users, this simply means that if you perform a static analysis of your FMDB-based project, you may receive more meaningful warnings as you review your project, but there are likely to be few, if any, changes necessary in your code. For Swift users, this nullability audit results in changes that are not entirely backward compatible with FMDB 2.6, but is a little more Swifty. Before FMDB was audited for nullability, Swift was forced to defensively assume that variables were optional, but the library now more accurately knows which properties and method parameters are optional, and which are not. This means, though, that Swift code written for FMDB 2.7 may require changes. For example, consider the following Swift 3/Swift 4 code for FMDB 2.6: ```swift queue.inTransaction { db, rollback in do { guard let db == db else { // handle error here return } try db.executeUpdate("INSERT INTO foo (bar) VALUES (?)", values: [1]) try db.executeUpdate("INSERT INTO foo (bar) VALUES (?)", values: [2]) } catch { rollback?.pointee = true } } ``` Because FMDB 2.6 was not audited for nullability, Swift inferred that `db` and `rollback` were optionals. But, now, in FMDB 2.7, Swift now knows that, for example, neither `db` nor `rollback` above can be `nil`, so they are no longer optionals. Thus it becomes: ```swift queue.inTransaction { db, rollback in do { try db.executeUpdate("INSERT INTO foo (bar) VALUES (?)", values: [1]) try db.executeUpdate("INSERT INTO foo (bar) VALUES (?)", values: [2]) } catch { rollback.pointee = true } } ``` ### Custom Functions In the past, when writing custom functions, you would have to generally include your own `@autoreleasepool` block to avoid problems when writing functions that scanned through a large table. Now, FMDB will automatically wrap it in an autorelease pool, so you don't have to. Also, in the past, when retrieving the values passed to the function, you had to drop down to the SQLite C API and include your own `sqlite3_value_XXX` calls. There are now `FMDatabase` methods, `valueInt`, `valueString`, etc., so you can stay within Swift and/or Objective-C, without needing to call the C functions yourself. Likewise, when specifying the return values, you no longer need to call `sqlite3_result_XXX` C API, but rather you can use `FMDatabase` methods, `resultInt`, `resultString`, etc. There is a new `enum` for `valueType` called `SqliteValueType`, which can be used for checking the type of parameter passed to the custom function. Thus, you can do something like (as of Swift 3): ```swift db.makeFunctionNamed("RemoveDiacritics", arguments: 1) { context, argc, argv in guard db.valueType(argv[0]) == .text || db.valueType(argv[0]) == .null else { db.resultError("Expected string parameter", context: context) return } if let string = db.valueString(argv[0])?.folding(options: .diacriticInsensitive, locale: nil) { db.resultString(string, context: context) } else { db.resultNull(context: context) } } ``` And you can then use that function in your SQL (in this case, matching both "Jose" and "José"): ```sql SELECT * FROM employees WHERE RemoveDiacritics(first_name) LIKE 'jose' ``` Note, the method `makeFunctionNamed:maximumArguments:withBlock:` has been renamed to `makeFunctionNamed:arguments:block:`, to more accurately reflect the functional intent of the second parameter. ### API Changes In addition to the `makeFunctionNamed` noted above, there are a few other API changes. Specifically, - To become consistent with the rest of the API, the methods `objectForColumnName` and `UTF8StringForColumnName` have been renamed to `objectForColumn` and `UTF8StringForColumn`. - Note, the `objectForColumn` (and the associted subscript operator) now returns `nil` if an invalid column name/index is passed to it. It used to return `NSNull`. - To avoid confusion with `FMDatabaseQueue` method `inTransaction`, which performs transactions, the `FMDatabase` method to determine whether you are in a transaction or not, `inTransaction`, has been replaced with a read-only property, `isInTransaction`. - Several functions have been converted to properties, namely, `databasePath`, `maxBusyRetryTimeInterval`, `shouldCacheStatements`, `sqliteHandle`, `hasOpenResultSets`, `lastInsertRowId`, `changes`, `goodConnection`, `columnCount`, `resultDictionary`, `applicationID`, `applicationIDString`, `userVersion`, `countOfCheckedInDatabases`, `countOfCheckedOutDatabases`, and `countOfOpenDatabases`. For Objective-C users, this has little material impact, but for Swift users, it results in a slightly more natural interface. Note: For Objective-C developers, previously versions of FMDB exposed many ivars (but we hope you weren't using them directly, anyway!), but the implmentation details for these are no longer exposed. ### URL Methods In keeping with Apple's shift from paths to URLs, there are now `NSURL` renditions of the various `init` methods, previously only accepting paths. ## Usage There are three main classes in FMDB: 1. `FMDatabase` - Represents a single SQLite database. Used for executing SQL statements. 2. `FMResultSet` - Represents the results of executing a query on an `FMDatabase`. 3. `FMDatabaseQueue` - If you're wanting to perform queries and updates on multiple threads, you'll want to use this class. It's described in the "Thread Safety" section below. ### Database Creation An `FMDatabase` is created with a path to a SQLite database file. This path can be one of these three: 1. A file system path. The file does not have to exist on disk. If it does not exist, it is created for you. 2. An empty string (`@""`). An empty database is created at a temporary location. This database is deleted when the `FMDatabase` connection is closed. 3. `NULL`. An in-memory database is created. This database will be destroyed when the `FMDatabase` connection is closed. (For more information on temporary and in-memory databases, read the sqlite documentation on the subject: https://www.sqlite.org/inmemorydb.html) ```objc NSString *path = [NSTemporaryDirectory() stringByAppendingPathComponent:@"tmp.db"]; FMDatabase *db = [FMDatabase databaseWithPath:path]; ``` ### Opening Before you can interact with the database, it must be opened. Opening fails if there are insufficient resources or permissions to open and/or create the database. ```objc if (![db open]) { // [db release]; // uncomment this line in manual referencing code; in ARC, this is not necessary/permitted db = nil; return; } ``` ### Executing Updates Any sort of SQL statement which is not a `SELECT` statement qualifies as an update. This includes `CREATE`, `UPDATE`, `INSERT`, `ALTER`, `COMMIT`, `BEGIN`, `DETACH`, `DELETE`, `DROP`, `END`, `EXPLAIN`, `VACUUM`, and `REPLACE` statements (plus many more). Basically, if your SQL statement does not begin with `SELECT`, it is an update statement. Executing updates returns a single value, a `BOOL`. A return value of `YES` means the update was successfully executed, and a return value of `NO` means that some error was encountered. You may invoke the `-lastErrorMessage` and `-lastErrorCode` methods to retrieve more information. ### Executing Queries A `SELECT` statement is a query and is executed via one of the `-executeQuery...` methods. Executing queries returns an `FMResultSet` object if successful, and `nil` upon failure. You should use the `-lastErrorMessage` and `-lastErrorCode` methods to determine why a query failed. In order to iterate through the results of your query, you use a `while()` loop. You also need to "step" from one record to the other. With FMDB, the easiest way to do that is like this: ```objc FMResultSet *s = [db executeQuery:@"SELECT * FROM myTable"]; while ([s next]) { //retrieve values for each record } ``` You must always invoke `-[FMResultSet next]` before attempting to access the values returned in a query, even if you're only expecting one: ```objc FMResultSet *s = [db executeQuery:@"SELECT COUNT(*) FROM myTable"]; if ([s next]) { int totalCount = [s intForColumnIndex:0]; } [s close]; // Call the -close method on the FMResultSet if you cannot confirm whether the result set is exhausted. ``` `FMResultSet` has many methods to retrieve data in an appropriate format: - `intForColumn:` - `longForColumn:` - `longLongIntForColumn:` - `boolForColumn:` - `doubleForColumn:` - `stringForColumn:` - `dateForColumn:` - `dataForColumn:` - `dataNoCopyForColumn:` - `UTF8StringForColumn:` - `objectForColumn:` Each of these methods also has a `{type}ForColumnIndex:` variant that is used to retrieve the data based on the position of the column in the results, as opposed to the column's name. Typically, there's no need to `-close` an `FMResultSet` yourself, since that happens when either the result set is exhausted. However, if you only pull out a single request or any other number of requests which don't exhaust the result set, you will need to call the `-close` method on the `FMResultSet`. ### Closing When you have finished executing queries and updates on the database, you should `-close` the `FMDatabase` connection so that SQLite will relinquish any resources it has acquired during the course of its operation. ```objc [db close]; ``` ### Transactions `FMDatabase` can begin and commit a transaction by invoking one of the appropriate methods or executing a begin/end transaction statement. ### Multiple Statements and Batch Stuff You can use `FMDatabase`'s executeStatements:withResultBlock: to do multiple statements in a string: ```objc NSString *sql = @"create table bulktest1 (id integer primary key autoincrement, x text);" "create table bulktest2 (id integer primary key autoincrement, y text);" "create table bulktest3 (id integer primary key autoincrement, z text);" "insert into bulktest1 (x) values ('XXX');" "insert into bulktest2 (y) values ('YYY');" "insert into bulktest3 (z) values ('ZZZ');"; success = [db executeStatements:sql]; sql = @"select count(*) as count from bulktest1;" "select count(*) as count from bulktest2;" "select count(*) as count from bulktest3;"; success = [self.db executeStatements:sql withResultBlock:^int(NSDictionary *dictionary) { NSInteger count = [dictionary[@"count"] integerValue]; XCTAssertEqual(count, 1, @"expected one record for dictionary %@", dictionary); return 0; }]; ``` ### Data Sanitization When providing a SQL statement to FMDB, you should not attempt to "sanitize" any values before insertion. Instead, you should use the standard SQLite binding syntax: ```sql INSERT INTO myTable VALUES (?, ?, ?, ?) ``` The `?` character is recognized by SQLite as a placeholder for a value to be inserted. The execution methods all accept a variable number of arguments (or a representation of those arguments, such as an `NSArray`, `NSDictionary`, or a `va_list`), which are properly escaped for you. And, to use that SQL with the `?` placeholders from Objective-C: ```objc NSInteger identifier = 42; NSString *name = @"Liam O'Flaherty (\"the famous Irish author\")"; NSDate *date = [NSDate date]; NSString *comment = nil; BOOL success = [db executeUpdate:@"INSERT INTO authors (identifier, name, date, comment) VALUES (?, ?, ?, ?)", @(identifier), name, date, comment ?: [NSNull null]]; if (!success) { NSLog(@"error = %@", [db lastErrorMessage]); } ``` > **Note:** Fundamental data types, like the `NSInteger` variable `identifier`, should be as a `NSNumber` objects, achieved by using the `@` syntax, shown above. Or you can use the `[NSNumber numberWithInt:identifier]` syntax, too. > > Likewise, SQL `NULL` values should be inserted as `[NSNull null]`. For example, in the case of `comment` which might be `nil` (and is in this example), you can use the `comment ?: [NSNull null]` syntax, which will insert the string if `comment` is not `nil`, but will insert `[NSNull null]` if it is `nil`. In Swift, you would use `executeUpdate(values:)`, which not only is a concise Swift syntax, but also `throws` errors for proper error handling: ```swift do { let identifier = 42 let name = "Liam O'Flaherty (\"the famous Irish author\")" let date = Date() let comment: String? = nil try db.executeUpdate("INSERT INTO authors (identifier, name, date, comment) VALUES (?, ?, ?, ?)", values: [identifier, name, date, comment ?? NSNull()]) } catch { print("error = \(error)") } ``` > **Note:** In Swift, you don't have to wrap fundamental numeric types like you do in Objective-C. But if you are going to insert an optional string, you would probably use the `comment ?? NSNull()` syntax (i.e., if it is `nil`, use `NSNull`, otherwise use the string). Alternatively, you may use named parameters syntax: ```sql INSERT INTO authors (identifier, name, date, comment) VALUES (:identifier, :name, :date, :comment) ``` The parameters *must* start with a colon. SQLite itself supports other characters, but internally the dictionary keys are prefixed with a colon, do **not** include the colon in your dictionary keys. ```objc NSDictionary *arguments = @{@"identifier": @(identifier), @"name": name, @"date": date, @"comment": comment ?: [NSNull null]}; BOOL success = [db executeUpdate:@"INSERT INTO authors (identifier, name, date, comment) VALUES (:identifier, :name, :date, :comment)" withParameterDictionary:arguments]; if (!success) { NSLog(@"error = %@", [db lastErrorMessage]); } ``` The key point is that one should not use `NSString` method `stringWithFormat` to manually insert values into the SQL statement, itself. Nor should one Swift string interpolation to insert values into the SQL. Use `?` placeholders for values to be inserted into the database (or used in `WHERE` clauses in `SELECT` statements).

Using FMDatabaseQueue and Thread Safety.

Using a single instance of `FMDatabase` from multiple threads at once is a bad idea. It has always been OK to make a `FMDatabase` object *per thread*. Just don't share a single instance across threads, and definitely not across multiple threads at the same time. Bad things will eventually happen and you'll eventually get something to crash, or maybe get an exception, or maybe meteorites will fall out of the sky and hit your Mac Pro. *This would suck*. **So don't instantiate a single `FMDatabase` object and use it across multiple threads.** Instead, use `FMDatabaseQueue`. Instantiate a single `FMDatabaseQueue` and use it across multiple threads. The `FMDatabaseQueue` object will synchronize and coordinate access across the multiple threads. Here's how to use it: First, make your queue. ```objc FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:aPath]; ``` Then use it like so: ```objc [queue inDatabase:^(FMDatabase *db) { [db executeUpdate:@"INSERT INTO myTable VALUES (?)", @1]; [db executeUpdate:@"INSERT INTO myTable VALUES (?)", @2]; [db executeUpdate:@"INSERT INTO myTable VALUES (?)", @3]; FMResultSet *rs = [db executeQuery:@"select * from foo"]; while ([rs next]) { … } }]; ``` An easy way to wrap things up in a transaction can be done like this: ```objc [queue inTransaction:^(FMDatabase *db, BOOL *rollback) { [db executeUpdate:@"INSERT INTO myTable VALUES (?)", @1]; [db executeUpdate:@"INSERT INTO myTable VALUES (?)", @2]; [db executeUpdate:@"INSERT INTO myTable VALUES (?)", @3]; if (whoopsSomethingWrongHappened) { *rollback = YES; return; } // etc ... }]; ``` The Swift equivalent would be: ```swift queue.inTransaction { db, rollback in do { try db.executeUpdate("INSERT INTO myTable VALUES (?)", values: [1]) try db.executeUpdate("INSERT INTO myTable VALUES (?)", values: [2]) try db.executeUpdate("INSERT INTO myTable VALUES (?)", values: [3]) if whoopsSomethingWrongHappened { rollback.pointee = true return } // etc ... } catch { rollback.pointee = true print(error) } } ``` (Note, as of Swift 3, use `pointee`. But in Swift 2.3, use `memory` rather than `pointee`.) `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. **Note:** The calls to `FMDatabaseQueue`'s methods are blocking. So even though you are passing along blocks, they will **not** be run on another thread. ## Making custom sqlite functions, based on blocks. You can do this! For an example, look for `-makeFunctionNamed:` in main.m ## Swift You can use FMDB in Swift projects too. To do this, you must: 1. Copy the relevant `.m` and `.h` files from the FMDB `src` folder into your project. You can copy all of them (which is easiest), or only the ones you need. Likely you will need [`FMDatabase`](https://ccgus.github.io/fmdb/html/Classes/FMDatabase.html) and [`FMResultSet`](https://ccgus.github.io/fmdb/html/Classes/FMResultSet.html) at a minimum. [`FMDatabaseAdditions`](https://ccgus.github.io/fmdb/html/Categories/FMDatabase+FMDatabaseAdditions.html) provides some very useful convenience methods, so you will likely want that, too. If you are doing multithreaded access to a database, [`FMDatabaseQueue`](https://ccgus.github.io/fmdb/html/Classes/FMDatabaseQueue.html) is quite useful, too. If you choose to not copy all of the files from the `src` directory, though, you may want to update `FMDB.h` to only reference the files that you included in your project. Note, if you're copying all of the files from the `src` folder into to your project (which is recommended), you may want to drag the individual files into your project, not the folder, itself, because if you drag the folder, you won't be prompted to add the bridging header (see next point). 2. If prompted to create a "bridging header", you should do so. If not prompted and if you don't already have a bridging header, add one. For more information on bridging headers, see [Swift and Objective-C in the Same Project](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/BuildingCocoaApps/MixandMatch.html#//apple_ref/doc/uid/TP40014216-CH10-XID_76). 3. In your bridging header, add a line that says: ```objc #import "FMDB.h" ``` 4. Use the variations of `executeQuery` and `executeUpdate` with the `sql` and `values` parameters with `try` pattern, as shown below. These renditions of `executeQuery` and `executeUpdate` both `throw` errors in true Swift fashion. If you do the above, you can then write Swift code that uses `FMDatabase`. For example, as of Swift 3: ```swift let fileURL = try! FileManager.default .url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true) .appendingPathComponent("test.sqlite") let database = FMDatabase(url: fileURL) guard database.open() else { print("Unable to open database") return } do { try database.executeUpdate("create table test(x text, y text, z text)", values: nil) try database.executeUpdate("insert into test (x, y, z) values (?, ?, ?)", values: ["a", "b", "c"]) try database.executeUpdate("insert into test (x, y, z) values (?, ?, ?)", values: ["e", "f", "g"]) let rs = try database.executeQuery("select x, y, z from test", values: nil) while rs.next() { if let x = rs.string(forColumn: "x"), let y = rs.string(forColumn: "y"), let z = rs.string(forColumn: "z") { print("x = \(x); y = \(y); z = \(z)") } } } catch { print("failed: \(error.localizedDescription)") } database.close() ``` ## History The history and changes are availbe on its [GitHub page](https://github.com/ccgus/fmdb) and are summarized in the "CHANGES_AND_TODO_LIST.txt" file. ## Contributors The contributors to FMDB are contained in the "Contributors.txt" file. ## Additional projects using FMDB, which might be interesting to the discerning developer. * FMDBMigrationManager, A SQLite schema migration management system for FMDB: https://github.com/layerhq/FMDBMigrationManager * FCModel, An alternative to Core Data for people who like having direct SQL access: https://github.com/marcoarment/FCModel ## Quick notes on FMDB's coding style Spaces, not tabs. Square brackets, not dot notation. Look at what FMDB already does with curly brackets and such, and stick to that style. ## Reporting bugs Reduce your bug down to the smallest amount of code possible. You want to make it super easy for the developers to see and reproduce your bug. If it helps, pretend that the person who can fix your bug is active on shipping 3 major products, works on a handful of open source projects, has a newborn baby, and is generally very very busy. And we've even added a template function to main.m (FMDBReportABugFunction) in the FMDB distribution to help you out: * Open up fmdb project in Xcode. * Open up main.m and modify the FMDBReportABugFunction to reproduce your bug. * Setup your table(s) in the code. * Make your query or update(s). * Add some assertions which demonstrate the bug. Then you can bring it up on the FMDB mailing list by showing your nice and compact FMDBReportABugFunction, or you can report the bug via the github FMDB bug reporter. **Optional:** Figure out where the bug is, fix it, and send a patch in or bring that up on the mailing list. Make sure all the other tests run after your modifications. ## Support The support channels for FMDB are the mailing list (see above), filing a bug here, or maybe on Stack Overflow. So that is to say, support is provided by the community and on a voluntary basis. FMDB development is overseen by Gus Mueller of Flying Meat. If FMDB been helpful to you, consider purchasing an app from FM or telling all your friends about it. ## License The license for FMDB is contained in the "License.txt" file. If you happen to come across either Gus Mueller or Rob Ryan in a bar, you might consider purchasing a drink of their choosing if FMDB has been useful to you. (The drink is for them of course, shame on you for trying to keep it.) ================================================ FILE: Tests/Base.lproj/InfoPlist.strings ================================================ /* Localized versions of Info.plist keys */ ================================================ FILE: Tests/FMDBTempDBTests.h ================================================ // // FMDBTempDBTests.h // fmdb // // Created by Graham Dennis on 24/11/2013. // // #import #import "FMDatabase.h" @protocol FMDBTempDBTests @optional + (void)populateDatabase:(FMDatabase *)database; @end @interface FMDBTempDBTests : XCTestCase @property FMDatabase *db; @property (readonly) NSString *databasePath; @end ================================================ FILE: Tests/FMDBTempDBTests.m ================================================ // // FMDBTempDBTests.m // fmdb // // Created by Graham Dennis on 24/11/2013. // // #import "FMDBTempDBTests.h" static NSString *const testDatabasePath = @"/private/tmp/tmp.db"; static NSString *const populatedDatabasePath = @"/private/tmp/tmp-populated.db"; @implementation FMDBTempDBTests + (void)setUp { [super setUp]; // Delete old populated database NSFileManager *fileManager = [NSFileManager defaultManager]; [fileManager removeItemAtPath:populatedDatabasePath error:NULL]; if ([self respondsToSelector:@selector(populateDatabase:)]) { FMDatabase *db = [FMDatabase databaseWithPath:populatedDatabasePath]; [db open]; [self populateDatabase:db]; [db close]; } } - (void)setUp { [super setUp]; // Delete the old database NSFileManager *fileManager = [NSFileManager defaultManager]; [fileManager removeItemAtPath:testDatabasePath error:NULL]; if ([[self class] respondsToSelector:@selector(populateDatabase:)]) { [fileManager copyItemAtPath:populatedDatabasePath toPath:testDatabasePath error:NULL]; } self.db = [FMDatabase databaseWithPath:testDatabasePath]; XCTAssertTrue([self.db open], @"Wasn't able to open database"); [self.db setShouldCacheStatements:YES]; } - (void)tearDown { [super tearDown]; [self.db close]; } - (NSString *)databasePath { return testDatabasePath; } @end ================================================ FILE: Tests/FMDatabaseAdditionsTests.m ================================================ // // FMDatabaseAdditionsTests.m // fmdb // // Created by Graham Dennis on 24/11/2013. // // #import #import "FMDatabaseAdditions.h" #if FMDB_SQLITE_STANDALONE #import #elif SQLCIPHER_CRYPTO #import #else #import #endif @interface FMDatabaseAdditionsTests : FMDBTempDBTests @end @implementation FMDatabaseAdditionsTests - (void)setUp { [super setUp]; // Put setup code here. This method is called before the invocation of each test method in the class. } - (void)tearDown { // Put teardown code here. This method is called after the invocation of each test method in the class. [super tearDown]; } - (void)testFunkyTableNames { [self.db executeUpdate:@"create table '234 fds' (foo text)"]; XCTAssertFalse([self.db hadError], @"table creation should have succeeded"); FMResultSet *rs = [self.db getTableSchema:@"234 fds"]; XCTAssertTrue([rs next], @"Schema should have succeded"); [rs close]; XCTAssertFalse([self.db hadError], @"There shouldn't be any errors"); } - (void)testBoolForQuery { BOOL result = [self.db boolForQuery:@"SELECT ? not null", @""]; XCTAssertTrue(result, @"Empty strings should be considered true"); result = [self.db boolForQuery:@"SELECT ? not null", [NSMutableData data]]; XCTAssertTrue(result, @"Empty mutable data should be considered true"); result = [self.db boolForQuery:@"SELECT ? not null", [NSData data]]; XCTAssertTrue(result, @"Empty data should be considered true"); } - (void)testIntForQuery { [self.db executeUpdate:@"create table t1 (a integer)"]; [self.db executeUpdate:@"insert into t1 values (?)", [NSNumber numberWithInt:5]]; XCTAssertEqual([self.db changes], 1, @"There should only be one change"); int ia = [self.db intForQuery:@"select a from t1 where a = ?", [NSNumber numberWithInt:5]]; XCTAssertEqual(ia, 5, @"foo"); } - (void)testDateForQuery { NSDate *date = [NSDate date]; [self.db executeUpdate:@"create table datetest (a double, b double, c double)"]; [self.db executeUpdate:@"insert into datetest (a, b, c) values (?, ?, 0)" , [NSNull null], date]; NSDate *foo = [self.db dateForQuery:@"select b from datetest where c = 0"]; XCTAssertEqualWithAccuracy([foo timeIntervalSinceDate:date], 0.0, 1.0, @"Dates should be the same to within a second"); } - (void)testValidate { NSError *error; XCTAssert([self.db validateSQL:@"create table datetest (a double, b double, c double)" error:&error]); XCTAssertNil(error, @"There should be no error object"); } - (void)testFailValidate { NSError *error; XCTAssertFalse([self.db validateSQL:@"blah blah blah" error:&error]); XCTAssert(error, @"There should be no error object"); } - (void)testTableExists { XCTAssertTrue([self.db executeUpdate:@"create table t4 (a text, b text)"]); XCTAssertTrue([self.db tableExists:@"t4"]); XCTAssertFalse([self.db tableExists:@"thisdoesntexist"]); FMResultSet *rs = [self.db getSchema]; while ([rs next]) { XCTAssertEqualObjects([rs stringForColumn:@"type"], @"table"); } } - (void)testColumnExists { [self.db executeUpdate:@"create table nulltest (a text, b text)"]; XCTAssertTrue([self.db columnExists:@"a" inTableWithName:@"nulltest"]); XCTAssertTrue([self.db columnExists:@"b" inTableWithName:@"nulltest"]); XCTAssertFalse([self.db columnExists:@"c" inTableWithName:@"nulltest"]); } - (void)testUserVersion { [[self db] setUserVersion:12]; XCTAssertTrue([[self db] userVersion] == 12); } - (void)testApplicationID { #if SQLITE_VERSION_NUMBER >= 3007017 uint32_t appID = NSHFSTypeCodeFromFileType(NSFileTypeForHFSTypeCode('fmdb')); [self.db setApplicationID:appID]; uint32_t rAppID = [self.db applicationID]; XCTAssertEqual(rAppID, appID); [self.db setApplicationIDString:@"acrn"]; NSString *s = [self.db applicationIDString]; XCTAssertEqualObjects(s, @"acrn"); #else NSString *errorMessage = NSLocalizedStringFromTable(@"Application ID functions require SQLite 3.7.17", @"FMDB", nil); XCTFail("%@", errorMessage); if (self.db.logsErrors) NSLog(@"%@", errorMessage); #endif } @end ================================================ FILE: Tests/FMDatabaseFTS3Tests.m ================================================ // // FMDatabaseFTS3Tests.m // fmdb // // Created by Seaview Software on 8/26/14. // // #import "FMDBTempDBTests.h" #import "FMDatabase+FTS3.h" #import "FMTokenizers.h" @interface FMDatabaseFTS3Tests : FMDBTempDBTests @end /** This tokenizer extends the simple tokenizer to remove 's' from the end of each token if present. Used for testing of the tokenization system. */ @interface FMDepluralizerTokenizer : NSObject + (instancetype)tokenizerWithBaseTokenizer:(id)tokenizer; @property (nonatomic, strong) id m_baseTokenizer; @end static id g_simpleTok = nil; static id g_depluralizeTok = nil; @implementation FMDatabaseFTS3Tests + (void)populateDatabase:(FMDatabase *)db { [db executeUpdate:@"CREATE VIRTUAL TABLE mail USING fts3(subject, body)"]; [db executeUpdate:@"INSERT INTO mail VALUES('hello world', 'This message is a hello world message.')"]; [db executeUpdate:@"INSERT INTO mail VALUES('urgent: serious', 'This mail is seen as a more serious mail')"]; // Create a tokenizer instance that will not be de-allocated when the method finishes. g_simpleTok = [[FMSimpleTokenizer alloc] initWithLocale:NULL]; [FMDatabase registerTokenizer:g_simpleTok withKey:@"testTok"]; g_depluralizeTok = [FMDepluralizerTokenizer tokenizerWithBaseTokenizer:g_simpleTok]; [FMDatabase registerTokenizer:g_depluralizeTok withKey:@"depluralize"]; } - (void)setUp { [super setUp]; // Put setup code here. This method is called before the invocation of each test method in the class. } - (void)tearDown { // Put teardown code here. This method is called after the invocation of each test method in the class. [super tearDown]; } - (void)testOffsets { FMResultSet *results = [self.db executeQuery:@"SELECT offsets(mail) FROM mail WHERE mail MATCH 'world'"]; if ([results next]) { FMTextOffsets *offsets = [results offsetsForColumnIndex:0]; [offsets enumerateWithBlock:^(NSInteger columnNumber, NSInteger termNumber, NSRange matchRange) { if (columnNumber == 0) { XCTAssertEqual(termNumber, 0L); XCTAssertEqual(matchRange.location, 6UL); XCTAssertEqual(matchRange.length, 5UL); } else if (columnNumber == 1) { XCTAssertEqual(termNumber, 0L); XCTAssertEqual(matchRange.location, 24UL); XCTAssertEqual(matchRange.length, 5UL); } }]; } } - (void)testTokenizer { [self.db installTokenizerModule]; BOOL ok = [self.db executeUpdate:@"CREATE VIRTUAL TABLE simple USING fts3(tokenize=fmdb testTok)"]; XCTAssertTrue(ok, @"Failed to create virtual table: %@", [self.db lastErrorMessage]); // The FMSimpleTokenizer handles non-ASCII characters well, since it's based on CFStringTokenizer. NSString *text = @"I like the band Queensrÿche. They are really great musicians."; ok = [self.db executeUpdate:@"INSERT INTO simple VALUES(?)", text]; XCTAssertTrue(ok, @"Failed to insert data: %@", [self.db lastErrorMessage]); FMResultSet *results = [self.db executeQuery:@"SELECT * FROM simple WHERE simple MATCH ?", @"Queensrÿche"]; XCTAssertTrue([results next], @"Failed to find result"); ok = [self.db executeUpdate:@"CREATE VIRTUAL TABLE depluralize_t USING fts3(tokenize=fmdb depluralize)"]; XCTAssertTrue(ok, @"Failed to create virtual table with depluralize tokenizer: %@", [self.db lastErrorMessage]); ok = [self.db executeUpdate:@"INSERT INTO depluralize_t VALUES(?)", text]; XCTAssertTrue(ok, @"Failed to insert data: %@", [self.db lastErrorMessage]); //If depluralization is working, searching for 'bands' should still provide a match as 'band' is in the text results = [self.db executeQuery:@"SELECT * FROM depluralize_t WHERE depluralize_t MATCH ?", @"bands"]; XCTAssertTrue([results next], @"Failed to find result"); //Demonstrate that depluralization mattered; we should NOT find any results when searching the simple table as it does not use that tokenizer results = [self.db executeQuery:@"SELECT * FROM simple WHERE simple MATCH ?", @"bands"]; XCTAssertFalse([results next], @"Found a result where none should be found"); } @end #pragma mark - @implementation FMDepluralizerTokenizer + (instancetype)tokenizerWithBaseTokenizer:(id)tokenizer { return [[self alloc] initWithBaseTokenizer:tokenizer]; } - (instancetype)initWithBaseTokenizer:(id)tokenizer { NSParameterAssert(tokenizer); if ((self = [super init])) { self.m_baseTokenizer = tokenizer; } return self; } - (void)openTokenizerCursor:(FMTokenizerCursor *)cursor { [self.m_baseTokenizer openTokenizerCursor:cursor]; } - (BOOL)nextTokenForCursor:(FMTokenizerCursor *)cursor { BOOL done = [self.m_baseTokenizer nextTokenForCursor:cursor]; if (!done) { NSMutableString *tokenString = (__bridge NSMutableString *)(cursor->tokenString); if ([tokenString hasSuffix:@"s"]) [tokenString deleteCharactersInRange:NSMakeRange(tokenString.length-1, 1)]; } return done; } - (void)closeTokenizerCursor:(FMTokenizerCursor *)cursor { [self.m_baseTokenizer closeTokenizerCursor:cursor]; } @end ================================================ FILE: Tests/FMDatabaseFTS3WithModuleNameTests.m ================================================ // // FMDatabaseFTS3WithKeyTests.m // fmdb // // Created by Stephan Heilner on 1/21/15. // // #import "FMDBTempDBTests.h" #import "FMDatabase+FTS3.h" #import "FMTokenizers.h" @interface FMDatabaseFTS3WithModuleNameTests : FMDBTempDBTests @end static id g_testTok = nil; @implementation FMDatabaseFTS3WithModuleNameTests + (void)populateDatabase:(FMDatabase *)db { [db executeUpdate:@"CREATE VIRTUAL TABLE mail USING fts3(subject, body)"]; [db executeUpdate:@"INSERT INTO mail VALUES('hello world', 'This message is a hello world message.')"]; [db executeUpdate:@"INSERT INTO mail VALUES('urgent: serious', 'This mail is seen as a more serious mail')"]; // Create a tokenizer instance that will not be de-allocated when the method finishes. g_testTok = [[FMSimpleTokenizer alloc] initWithLocale:NULL]; [FMDatabase registerTokenizer:g_testTok]; } - (void)setUp { [super setUp]; // Put setup code here. This method is called before the invocation of each test method in the class. } - (void)tearDown { // Put teardown code here. This method is called after the invocation of each test method in the class. [super tearDown]; } - (void)testOffsets { FMResultSet *results = [self.db executeQuery:@"SELECT offsets(mail) FROM mail WHERE mail MATCH 'world'"]; if ([results next]) { FMTextOffsets *offsets = [results offsetsForColumnIndex:0]; [offsets enumerateWithBlock:^(NSInteger columnNumber, NSInteger termNumber, NSRange matchRange) { if (columnNumber == 0) { XCTAssertEqual(termNumber, 0L); XCTAssertEqual(matchRange.location, 6UL); XCTAssertEqual(matchRange.length, 5UL); } else if (columnNumber == 1) { XCTAssertEqual(termNumber, 0L); XCTAssertEqual(matchRange.location, 24UL); XCTAssertEqual(matchRange.length, 5UL); } }]; } } - (void)testTokenizer { [self.db installTokenizerModuleWithName:@"TestModuleName"]; BOOL ok = [self.db executeUpdate:@"CREATE VIRTUAL TABLE simple_fts USING fts3(tokenize=TestModuleName)"]; XCTAssertTrue(ok, @"Failed to create virtual table: %@", [self.db lastErrorMessage]); // The FMSimpleTokenizer handles non-ASCII characters well, since it's based on CFStringTokenizer. NSString *text = @"I like the band Queensrÿche. They are really great."; ok = [self.db executeUpdate:@"INSERT INTO simple_fts VALUES(?)", text]; XCTAssertTrue(ok, @"Failed to insert data: %@", [self.db lastErrorMessage]); FMResultSet *results = [self.db executeQuery:@"SELECT * FROM simple_fts WHERE simple_fts MATCH ?", @"Queensrÿche"]; XCTAssertTrue([results next], @"Failed to find result"); } @end ================================================ FILE: Tests/FMDatabasePoolTests.m ================================================ // // FMDatabasePoolTests.m // fmdb // // Created by Graham Dennis on 24/11/2013. // // #import #if FMDB_SQLITE_STANDALONE #import #elif SQLCIPHER_CRYPTO #import #else #import #endif @interface FMDatabasePoolTests : FMDBTempDBTests @property FMDatabasePool *pool; @end @implementation FMDatabasePoolTests + (void)populateDatabase:(FMDatabase *)db { [db executeUpdate:@"create table easy (a text)"]; [db executeUpdate:@"create table easy2 (a text)"]; [db executeUpdate:@"insert into easy values (?)", [NSNumber numberWithInt:1001]]; [db executeUpdate:@"insert into easy values (?)", [NSNumber numberWithInt:1002]]; [db executeUpdate:@"insert into easy values (?)", [NSNumber numberWithInt:1003]]; [db executeUpdate:@"create table likefoo (foo text)"]; [db executeUpdate:@"insert into likefoo values ('hi')"]; [db executeUpdate:@"insert into likefoo values ('hello')"]; [db executeUpdate:@"insert into likefoo values ('not')"]; } - (void)setUp { [super setUp]; // Put setup code here. This method is called before the invocation of each test method in the class. [self setPool:[FMDatabasePool databasePoolWithPath:self.databasePath]]; [[self pool] setDelegate:self]; } - (void)tearDown { // Put teardown code here. This method is called after the invocation of each test method in the class. [super tearDown]; } - (void)testURLOpenNoURL { FMDatabasePool *pool = [[FMDatabasePool alloc] initWithURL:nil]; XCTAssert(pool, @"Database pool should be returned"); pool = nil; } - (void)testURLOpen { NSURL *tempFolder = [NSURL fileURLWithPath:NSTemporaryDirectory()]; NSURL *fileURL = [tempFolder URLByAppendingPathComponent:[[NSUUID UUID] UUIDString]]; FMDatabasePool *pool = [FMDatabasePool databasePoolWithURL:fileURL]; XCTAssert(pool, @"Database pool should be returned"); pool = nil; [[NSFileManager defaultManager] removeItemAtURL:fileURL error:nil]; } - (void)testURLOpenInit { NSURL *tempFolder = [NSURL fileURLWithPath:NSTemporaryDirectory()]; NSURL *fileURL = [tempFolder URLByAppendingPathComponent:[[NSUUID UUID] UUIDString]]; FMDatabasePool *pool = [[FMDatabasePool alloc] initWithURL:fileURL]; XCTAssert(pool, @"Database pool should be returned"); pool = nil; [[NSFileManager defaultManager] removeItemAtURL:fileURL error:nil]; } - (void)testURLOpenWithOptions { NSURL *tempFolder = [NSURL fileURLWithPath:NSTemporaryDirectory()]; NSURL *fileURL = [tempFolder URLByAppendingPathComponent:[[NSUUID UUID] UUIDString]]; FMDatabasePool *pool = [FMDatabasePool databasePoolWithURL:fileURL flags:SQLITE_OPEN_READWRITE]; [pool inDatabase:^(FMDatabase * _Nonnull db) { XCTAssertNil(db, @"The database should not have been created"); }]; } - (void)testURLOpenInitWithOptions { NSURL *tempFolder = [NSURL fileURLWithPath:NSTemporaryDirectory()]; NSURL *fileURL = [tempFolder URLByAppendingPathComponent:[[NSUUID UUID] UUIDString]]; FMDatabasePool *pool = [[FMDatabasePool alloc] initWithURL:fileURL flags:SQLITE_OPEN_READWRITE]; [pool inDatabase:^(FMDatabase * _Nonnull db) { XCTAssertNil(db, @"The database should not have been created"); }]; pool = [[FMDatabasePool alloc] initWithURL:fileURL flags:SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE]; [pool inDatabase:^(FMDatabase * _Nonnull db) { XCTAssert(db, @"The database should have been created"); BOOL success = [db executeUpdate:@"CREATE TABLE foo (bar INT)"]; XCTAssert(success, @"Create failed"); success = [db executeUpdate:@"INSERT INTO foo (bar) VALUES (?)", @42]; XCTAssert(success, @"Insert failed"); }]; pool = [[FMDatabasePool alloc] initWithURL:fileURL flags:SQLITE_OPEN_READONLY]; [pool inDatabase:^(FMDatabase * _Nonnull db) { XCTAssert(db, @"Now database pool should open have been created"); BOOL success = [db executeUpdate:@"CREATE TABLE baz (qux INT)"]; XCTAssertFalse(success, @"But updates should fail on read only database"); }]; pool = nil; [[NSFileManager defaultManager] removeItemAtURL:fileURL error:nil]; } - (void)testURLOpenWithOptionsVfs { sqlite3_vfs vfs = *sqlite3_vfs_find(NULL); vfs.zName = "MyCustomVFS"; XCTAssertEqual(SQLITE_OK, sqlite3_vfs_register(&vfs, 0)); NSURL *tempFolder = [NSURL fileURLWithPath:NSTemporaryDirectory()]; NSURL *fileURL = [tempFolder URLByAppendingPathComponent:[[NSUUID UUID] UUIDString]]; FMDatabasePool *pool = [[FMDatabasePool alloc] initWithURL:fileURL flags:SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE vfs:@"MyCustomVFS"]; XCTAssert(pool, @"Database pool should not have been created"); pool = nil; XCTAssertEqual(SQLITE_OK, sqlite3_vfs_unregister(&vfs)); } - (void)testPoolIsInitiallyEmpty { XCTAssertEqual([self.pool countOfOpenDatabases], (NSUInteger)0, @"Pool should be empty on creation"); } - (void)testDatabaseCreation { __block FMDatabase *db1; [self.pool inDatabase:^(FMDatabase *db) { XCTAssertEqual([self.pool countOfOpenDatabases], (NSUInteger)1, @"Should only have one database at this point"); db1 = db; }]; [self.pool inDatabase:^(FMDatabase *db) { XCTAssertEqualObjects(db, db1, @"We should get the same database back because there was no need to create a new one"); [self.pool inDatabase:^(FMDatabase *db2) { XCTAssertNotEqualObjects(db2, db, @"We should get a different database because the first was in use."); }]; }]; XCTAssertEqual([self.pool countOfOpenDatabases], (NSUInteger)2); [self.pool releaseAllDatabases]; XCTAssertEqual([self.pool countOfOpenDatabases], (NSUInteger)0, @"We should be back to zero databases again"); } - (void)testCheckedInCheckoutOutCount { [self.pool inDatabase:^(FMDatabase *aDb) { XCTAssertEqual([self.pool countOfCheckedInDatabases], (NSUInteger)0); XCTAssertEqual([self.pool countOfCheckedOutDatabases], (NSUInteger)1); XCTAssertTrue(([aDb executeUpdate:@"insert into easy (a) values (?)", @"hi"])); // just for fun. FMResultSet *rs = [aDb executeQuery:@"select * from easy"]; XCTAssertNotNil(rs); XCTAssertTrue([rs next]); while ([rs next]) { ; } // whatevers. XCTAssertEqual([self.pool countOfOpenDatabases], (NSUInteger)1); XCTAssertEqual([self.pool countOfCheckedInDatabases], (NSUInteger)0); XCTAssertEqual([self.pool countOfCheckedOutDatabases], (NSUInteger)1); }]; XCTAssertEqual([self.pool countOfOpenDatabases], (NSUInteger)1); } - (void)testMaximumDatabaseLimit { [self.pool setMaximumNumberOfDatabasesToCreate:2]; [self.pool inDatabase:^(FMDatabase *db) { [self.pool inDatabase:^(FMDatabase *db2) { [self.pool inDatabase:^(FMDatabase *db3) { XCTAssertEqual([self.pool countOfOpenDatabases], (NSUInteger)2); XCTAssertNil(db3, @"The third database must be nil because we have a maximum of 2 databases in the pool"); }]; }]; }]; } - (void)testTransaction { [self.pool inTransaction:^(FMDatabase *adb, BOOL *rollback) { [adb executeUpdate:@"insert into easy values (?)", [NSNumber numberWithInt:1001]]; [adb executeUpdate:@"insert into easy values (?)", [NSNumber numberWithInt:1002]]; [adb executeUpdate:@"insert into easy values (?)", [NSNumber numberWithInt:1003]]; XCTAssertEqual([self.pool countOfOpenDatabases], (NSUInteger)1); XCTAssertEqual([self.pool countOfCheckedInDatabases], (NSUInteger)0); XCTAssertEqual([self.pool countOfCheckedOutDatabases], (NSUInteger)1); }]; XCTAssertEqual([self.pool countOfOpenDatabases], (NSUInteger)1); XCTAssertEqual([self.pool countOfCheckedInDatabases], (NSUInteger)1); XCTAssertEqual([self.pool countOfCheckedOutDatabases], (NSUInteger)0); } - (void)testSelect { [self.pool inDatabase:^(FMDatabase *db) { FMResultSet *rs = [db executeQuery:@"select * from easy where a = ?", [NSNumber numberWithInt:1001]]; XCTAssertNotNil(rs); XCTAssertTrue ([rs next]); XCTAssertFalse([rs next]); }]; } - (void)testTransactionRollback { [self.pool inDeferredTransaction:^(FMDatabase *adb, BOOL *rollback) { XCTAssertTrue(([adb executeUpdate:@"insert into easy values (?)", [NSNumber numberWithInt:1004]])); XCTAssertTrue(([adb executeUpdate:@"insert into easy values (?)", [NSNumber numberWithInt:1005]])); XCTAssertTrue([[adb executeQuery:@"select * from easy where a == '1004'"] next], @"1004 should be in database"); *rollback = YES; }]; [self.pool inDatabase:^(FMDatabase *db) { XCTAssertFalse([[db executeQuery:@"select * from easy where a == '1004'"] next], @"1004 should not be in database"); }]; XCTAssertEqual([self.pool countOfOpenDatabases], (NSUInteger)1); XCTAssertEqual([self.pool countOfCheckedInDatabases], (NSUInteger)1); XCTAssertEqual([self.pool countOfCheckedOutDatabases], (NSUInteger)0); } - (void)testSavepoint { NSError *err = [self.pool inSavePoint:^(FMDatabase *db, BOOL *rollback) { [db executeUpdate:@"insert into easy values (?)", [NSNumber numberWithInt:1006]]; }]; XCTAssertNil(err); } - (void)testNestedSavepointRollback { NSError *err = [self.pool inSavePoint:^(FMDatabase *adb, BOOL *rollback) { XCTAssertFalse([adb hadError]); XCTAssertTrue(([adb executeUpdate:@"insert into easy values (?)", [NSNumber numberWithInt:1009]])); [adb inSavePoint:^(BOOL *arollback) { XCTAssertTrue(([adb executeUpdate:@"insert into easy values (?)", [NSNumber numberWithInt:1010]])); *arollback = YES; }]; }]; XCTAssertNil(err); [self.pool inDatabase:^(FMDatabase *db) { FMResultSet *rs = [db executeQuery:@"select * from easy where a = ?", [NSNumber numberWithInt:1009]]; XCTAssertTrue ([rs next]); XCTAssertFalse([rs next]); // close it out. rs = [db executeQuery:@"select * from easy where a = ?", [NSNumber numberWithInt:1010]]; XCTAssertFalse([rs next]); }]; } - (void)testLikeStringQuery { [self.pool inDatabase:^(FMDatabase *db) { int count = 0; FMResultSet *rsl = [db executeQuery:@"select * from likefoo where foo like 'h%'"]; while ([rsl next]) { count++; } XCTAssertEqual(count, 2); count = 0; rsl = [db executeQuery:@"select * from likefoo where foo like ?", @"h%"]; while ([rsl next]) { count++; } XCTAssertEqual(count, 2); }]; } - (void)testStressTest { size_t ops = 128; dispatch_queue_t dqueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_apply(ops, dqueue, ^(size_t nby) { // just mix things up a bit for demonstration purposes. if (nby % 2 == 1) { [NSThread sleepForTimeInterval:.001]; } [self.pool inDatabase:^(FMDatabase *db) { FMResultSet *rsl = [db executeQuery:@"select * from likefoo where foo like 'h%'"]; XCTAssertNotNil(rsl); int i = 0; while ([rsl next]) { i++; if (nby % 3 == 1) { [NSThread sleepForTimeInterval:.0005]; } } XCTAssertEqual(i, 2); }]; }); XCTAssert([self.pool countOfOpenDatabases] < 64, @"There should be significantly less than 64 databases after that stress test"); } - (BOOL)databasePool:(FMDatabasePool*)pool shouldAddDatabaseToPool:(FMDatabase*)database { [database setMaxBusyRetryTimeInterval:10]; // [database setCrashOnErrors:YES]; return YES; } - (void)testReadWriteStressTest { int ops = 16; dispatch_queue_t dqueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_apply(ops, dqueue, ^(size_t nby) { // just mix things up a bit for demonstration purposes. if (nby % 2 == 1) { [NSThread sleepForTimeInterval:.01]; [self.pool inTransaction:^(FMDatabase *db, BOOL *rollback) { FMResultSet *rsl = [db executeQuery:@"select * from likefoo where foo like 'h%'"]; XCTAssertNotNil(rsl); while ([rsl next]) { ;// whatever. } }]; } if (nby % 3 == 1) { [NSThread sleepForTimeInterval:.01]; } [self.pool inTransaction:^(FMDatabase *db, BOOL *rollback) { XCTAssertTrue([db executeUpdate:@"insert into likefoo values ('1')"]); XCTAssertTrue([db executeUpdate:@"insert into likefoo values ('2')"]); XCTAssertTrue([db executeUpdate:@"insert into likefoo values ('3')"]); }]; }); [self.pool releaseAllDatabases]; [self.pool inDatabase:^(FMDatabase *db) { XCTAssertTrue([db executeUpdate:@"insert into likefoo values ('1')"]); }]; } @end ================================================ FILE: Tests/FMDatabaseQueueTests.m ================================================ // // FMDatabaseQueueTests.m // fmdb // // Created by Graham Dennis on 24/11/2013. // // #import #import "FMDatabaseQueue.h" #if FMDB_SQLITE_STANDALONE #import #elif SQLCIPHER_CRYPTO #import #else #import #endif @interface FMDatabaseQueueTests : FMDBTempDBTests @property FMDatabaseQueue *queue; @end @implementation FMDatabaseQueueTests + (void)populateDatabase:(FMDatabase *)db { [db executeUpdate:@"create table easy (a text)"]; [db executeUpdate:@"create table qfoo (foo text)"]; [db executeUpdate:@"insert into qfoo values ('hi')"]; [db executeUpdate:@"insert into qfoo values ('hello')"]; [db executeUpdate:@"insert into qfoo values ('not')"]; } - (void)setUp { [super setUp]; // Put setup code here. This method is called before the invocation of each test method in the class. self.queue = [FMDatabaseQueue databaseQueueWithPath:self.databasePath]; } - (void)tearDown { // Put teardown code here. This method is called after the invocation of each test method in the class. [super tearDown]; } - (void)testURLOpenNoPath { FMDatabaseQueue *queue = [[FMDatabaseQueue alloc] init]; XCTAssert(queue, @"Database queue should be returned"); queue = nil; } - (void)testURLOpenNoURL { FMDatabaseQueue *queue = [[FMDatabaseQueue alloc] initWithURL:nil]; XCTAssert(queue, @"Database queue should be returned"); queue = nil; } - (void)testInvalidURL { NSURL *tempFolder = [NSURL fileURLWithPath:NSTemporaryDirectory()]; NSURL *folderURL = [tempFolder URLByAppendingPathComponent:[[NSUUID UUID] UUIDString]]; NSURL *fileURL = [folderURL URLByAppendingPathComponent:@"test.sqlite"]; FMDatabaseQueue *queue = [[FMDatabaseQueue alloc] initWithURL:fileURL]; XCTAssertNil(queue, @"Database queue should not be returned for invalid path"); queue = nil; } - (void)testInvalidPath { NSURL *tempFolder = [NSURL fileURLWithPath:NSTemporaryDirectory()]; NSURL *folderURL = [tempFolder URLByAppendingPathComponent:[[NSUUID UUID] UUIDString]]; NSURL *fileURL = [folderURL URLByAppendingPathComponent:@"test.sqlite"]; FMDatabaseQueue *queue = [[FMDatabaseQueue alloc] initWithPath:fileURL.path]; XCTAssertNil(queue, @"Database queue should not be returned for invalid path"); queue = nil; } - (void)testReopenFailure { NSFileManager *manager = [NSFileManager defaultManager]; NSURL *tempFolder = [NSURL fileURLWithPath:NSTemporaryDirectory()]; NSURL *folderURL = [tempFolder URLByAppendingPathComponent:[[NSUUID UUID] UUIDString]]; BOOL success = [manager createDirectoryAtURL:folderURL withIntermediateDirectories:true attributes:nil error:nil]; NSAssert(success, @"Unable to create folder"); NSURL *fileURL = [folderURL URLByAppendingPathComponent:@"test.sqlite"]; FMDatabaseQueue *queue = [[FMDatabaseQueue alloc] initWithURL:fileURL]; XCTAssert(queue, @"Database queue was unable to be created"); [queue close]; success = [manager removeItemAtURL:fileURL error:nil]; XCTAssert(success, @"Unable to remove database"); success = [manager removeItemAtURL:folderURL error:nil]; XCTAssert(success, @"Unable to remove folder"); [queue inDatabase:^(FMDatabase *db) { XCTAssertNil(db, @"Should be `nil` or never have reached here because database couldn't be reopened"); }]; queue = nil; } - (void)testURLOpen { NSURL *tempFolder = [NSURL fileURLWithPath:NSTemporaryDirectory()]; NSURL *fileURL = [tempFolder URLByAppendingPathComponent:[[NSUUID UUID] UUIDString]]; FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithURL:fileURL]; XCTAssert(queue, @"Database queue should be returned"); queue = nil; [[NSFileManager defaultManager] removeItemAtURL:fileURL error:nil]; } - (void)testURLOpenInit { NSURL *tempFolder = [NSURL fileURLWithPath:NSTemporaryDirectory()]; NSURL *fileURL = [tempFolder URLByAppendingPathComponent:[[NSUUID UUID] UUIDString]]; FMDatabaseQueue *queue = [[FMDatabaseQueue alloc] initWithURL:fileURL]; XCTAssert(queue, @"Database queue should be returned"); queue = nil; [[NSFileManager defaultManager] removeItemAtURL:fileURL error:nil]; } - (void)testURLOpenWithOptions { NSURL *tempFolder = [NSURL fileURLWithPath:NSTemporaryDirectory()]; NSURL *fileURL = [tempFolder URLByAppendingPathComponent:[[NSUUID UUID] UUIDString]]; FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithURL:fileURL flags:SQLITE_OPEN_READWRITE]; XCTAssertNil(queue, @"Database queue should not have been created"); } - (void)testURLOpenInitWithOptions { NSURL *tempFolder = [NSURL fileURLWithPath:NSTemporaryDirectory()]; NSURL *fileURL = [tempFolder URLByAppendingPathComponent:[[NSUUID UUID] UUIDString]]; FMDatabaseQueue *queue = [[FMDatabaseQueue alloc] initWithURL:fileURL flags:SQLITE_OPEN_READWRITE]; XCTAssertNil(queue, @"Database queue should not have been created"); queue = [[FMDatabaseQueue alloc] initWithURL:fileURL flags:SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE]; XCTAssert(queue, @"Database queue should have been created"); [queue inDatabase:^(FMDatabase * _Nonnull db) { BOOL success = [db executeUpdate:@"CREATE TABLE foo (bar INT)"]; XCTAssert(success, @"Create failed"); success = [db executeUpdate:@"INSERT INTO foo (bar) VALUES (?)", @42]; XCTAssert(success, @"Insert failed"); }]; queue = nil; queue = [[FMDatabaseQueue alloc] initWithURL:fileURL flags:SQLITE_OPEN_READONLY]; XCTAssert(queue, @"Now database queue should open have been created"); [queue inDatabase:^(FMDatabase * _Nonnull db) { BOOL success = [db executeUpdate:@"CREATE TABLE baz (qux INT)"]; XCTAssertFalse(success, @"But updates should fail on read only database"); }]; queue = nil; [[NSFileManager defaultManager] removeItemAtURL:fileURL error:nil]; } - (void)testURLOpenWithOptionsVfs { sqlite3_vfs vfs = *sqlite3_vfs_find(NULL); vfs.zName = "MyCustomVFS"; XCTAssertEqual(SQLITE_OK, sqlite3_vfs_register(&vfs, 0)); NSURL *tempFolder = [NSURL fileURLWithPath:NSTemporaryDirectory()]; NSURL *fileURL = [tempFolder URLByAppendingPathComponent:[[NSUUID UUID] UUIDString]]; FMDatabaseQueue *queue = [[FMDatabaseQueue alloc] initWithURL:fileURL flags:SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE vfs:@"MyCustomVFS"]; XCTAssert(queue, @"Database queue should not have been created"); queue = nil; XCTAssertEqual(SQLITE_OK, sqlite3_vfs_unregister(&vfs)); } - (void)testQueueSelect { [self.queue inDatabase:^(FMDatabase *adb) { int count = 0; FMResultSet *rsl = [adb executeQuery:@"select * from qfoo where foo like 'h%'"]; while ([rsl next]) { count++; } XCTAssertEqual(count, 2); count = 0; rsl = [adb executeQuery:@"select * from qfoo where foo like ?", @"h%"]; while ([rsl next]) { count++; } XCTAssertEqual(count, 2); }]; } - (void)testReadOnlyQueue { FMDatabaseQueue *queue2 = [FMDatabaseQueue databaseQueueWithPath:self.databasePath flags:SQLITE_OPEN_READONLY]; XCTAssertNotNil(queue2); { [queue2 inDatabase:^(FMDatabase *db2) { FMResultSet *rs1 = [db2 executeQuery:@"SELECT * FROM qfoo"]; XCTAssertNotNil(rs1); [rs1 close]; XCTAssertFalse(([db2 executeUpdate:@"insert into easy values (?)", [NSNumber numberWithInt:3]]), @"Insert should fail because this is a read-only database"); }]; [queue2 close]; // Check that when we re-open the database, it's still read-only [queue2 inDatabase:^(FMDatabase *db2) { FMResultSet *rs1 = [db2 executeQuery:@"SELECT * FROM qfoo"]; XCTAssertNotNil(rs1); [rs1 close]; XCTAssertFalse(([db2 executeUpdate:@"insert into easy values (?)", [NSNumber numberWithInt:3]]), @"Insert should fail because this is a read-only database"); }]; } } - (void)testStressTest { size_t ops = 16; dispatch_queue_t dqueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_apply(ops, dqueue, ^(size_t nby) { // just mix things up a bit for demonstration purposes. if (nby % 2 == 1) { [NSThread sleepForTimeInterval:.01]; [self.queue inTransaction:^(FMDatabase *adb, BOOL *rollback) { FMResultSet *rsl = [adb executeQuery:@"select * from qfoo where foo like 'h%'"]; while ([rsl next]) { ;// whatever. } }]; } if (nby % 3 == 1) { [NSThread sleepForTimeInterval:.01]; } [self.queue inTransaction:^(FMDatabase *adb, BOOL *rollback) { XCTAssertTrue([adb executeUpdate:@"insert into qfoo values ('1')"]); XCTAssertTrue([adb executeUpdate:@"insert into qfoo values ('2')"]); XCTAssertTrue([adb executeUpdate:@"insert into qfoo values ('3')"]); }]; }); [self.queue close]; [self.queue inDatabase:^(FMDatabase *adb) { XCTAssertTrue([adb executeUpdate:@"insert into qfoo values ('1')"]); }]; } - (void)testTransaction { [self.queue inDatabase:^(FMDatabase *adb) { [adb executeUpdate:@"create table transtest (a integer)"]; XCTAssertTrue([adb executeUpdate:@"insert into transtest values (1)"]); XCTAssertTrue([adb executeUpdate:@"insert into transtest values (2)"]); int rowCount = 0; FMResultSet *ars = [adb executeQuery:@"select * from transtest"]; while ([ars next]) { rowCount++; } XCTAssertEqual(rowCount, 2); }]; [self.queue inTransaction:^(FMDatabase *adb, BOOL *rollback) { XCTAssertTrue([adb executeUpdate:@"insert into transtest values (3)"]); if (YES) { // uh oh!, something went wrong (not really, this is just a test *rollback = YES; return; } XCTFail(@"This shouldn't be reached"); }]; [self.queue inDatabase:^(FMDatabase *adb) { int rowCount = 0; FMResultSet *ars = [adb executeQuery:@"select * from transtest"]; while ([ars next]) { rowCount++; } XCTAssertFalse([adb hasOpenResultSets]); XCTAssertEqual(rowCount, 2); }]; } - (void)testSavePoint { [self.queue inDatabase:^(FMDatabase *adb) { [adb executeUpdate:@"create table transtest (a integer)"]; XCTAssertTrue([adb executeUpdate:@"insert into transtest values (1)"]); XCTAssertTrue([adb executeUpdate:@"insert into transtest values (2)"]); int rowCount = 0; FMResultSet *ars = [adb executeQuery:@"select * from transtest"]; while ([ars next]) { rowCount++; } XCTAssertEqual(rowCount, 2); }]; [self.queue inSavePoint:^(FMDatabase *adb, BOOL *rollback) { XCTAssertTrue([adb executeUpdate:@"insert into transtest values (3)"]); if (YES) { // uh oh!, something went wrong (not really, this is just a test *rollback = YES; return; } XCTFail(@"This shouldn't be reached"); }]; [self.queue inDatabase:^(FMDatabase *adb) { int rowCount = 0; FMResultSet *ars = [adb executeQuery:@"select * from transtest"]; while ([ars next]) { rowCount++; } XCTAssertFalse([adb hasOpenResultSets]); XCTAssertEqual(rowCount, 2); }]; } - (void)testClose { [self.queue inDatabase:^(FMDatabase *adb) { XCTAssertTrue([adb executeUpdate:@"CREATE TABLE close_test (a INTEGER)"]); XCTAssertTrue([adb executeUpdate:@"INSERT INTO close_test VALUES (1)"]); [adb close]; }]; [self.queue inDatabase:^(FMDatabase *adb) { FMResultSet *ars = [adb executeQuery:@"select * from close_test"]; XCTAssertNotNil(ars); }]; } @end ================================================ FILE: Tests/FMDatabaseTests.m ================================================ // // Tests.m // Tests // // Created by Graham Dennis on 24/11/2013. // // #import "FMDBTempDBTests.h" #import "FMDatabase.h" #import "FMDatabaseAdditions.h" #if FMDB_SQLITE_STANDALONE #import #elif SQLCIPHER_CRYPTO #import #else #import #endif @interface FMDatabaseTests : FMDBTempDBTests @end @implementation FMDatabaseTests + (void)populateDatabase:(FMDatabase *)db { [db executeUpdate:@"create table test (a text, b text, c integer, d double, e double)"]; [db beginTransaction]; int i = 0; while (i++ < 20) { [db executeUpdate:@"insert into test (a, b, c, d, e) values (?, ?, ?, ?, ?)" , @"hi'", // look! I put in a ', and I'm not escaping it! [NSString stringWithFormat:@"number %d", i], [NSNumber numberWithInt:i], [NSDate date], [NSNumber numberWithFloat:2.2f]]; } [db commit]; // do it again, just because [db beginTransaction]; i = 0; while (i++ < 20) { [db executeUpdate:@"insert into test (a, b, c, d, e) values (?, ?, ?, ?, ?)" , @"hi again'", // look! I put in a ', and I'm not escaping it! [NSString stringWithFormat:@"number %d", i], [NSNumber numberWithInt:i], [NSDate date], [NSNumber numberWithFloat:2.2f]]; } [db commit]; [db executeUpdate:@"create table t3 (a somevalue)"]; [db beginTransaction]; for (int i=0; i < 20; i++) { [db executeUpdate:@"insert into t3 (a) values (?)", [NSNumber numberWithInt:i]]; } [db commit]; } - (void)setUp{ [super setUp]; // Put setup code here. This method is called before the invocation of each test method in the class. } - (void)tearDown { // Put teardown code here. This method is called after the invocation of each test method in the class. [super tearDown]; } - (void)testOpenWithVFS { // create custom vfs sqlite3_vfs vfs = *sqlite3_vfs_find(NULL); vfs.zName = "MyCustomVFS"; XCTAssertEqual(SQLITE_OK, sqlite3_vfs_register(&vfs, 0)); // use custom vfs to open a in memory database FMDatabase *db = [[FMDatabase alloc] initWithPath:@":memory:"]; [db openWithFlags:SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE vfs:@"MyCustomVFS"]; XCTAssertFalse([db hadError], @"Open with a custom VFS should have succeeded"); XCTAssertEqual(SQLITE_OK, sqlite3_vfs_unregister(&vfs)); } - (void)testURLOpen { NSURL *tempFolder = [NSURL fileURLWithPath:NSTemporaryDirectory()]; NSURL *fileURL = [tempFolder URLByAppendingPathComponent:[[NSUUID UUID] UUIDString]]; FMDatabase *db = [FMDatabase databaseWithURL:fileURL]; XCTAssert(db, @"Database should be returned"); XCTAssertTrue([db open], @"Open should succeed"); XCTAssertEqualObjects([db databaseURL], fileURL); XCTAssertTrue([db close], @"close should succeed"); [[NSFileManager defaultManager] removeItemAtURL:fileURL error:nil]; } - (void)testFailOnOpenWithUnknownVFS { FMDatabase *db = [[FMDatabase alloc] initWithPath:@":memory:"]; [db openWithFlags:SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE vfs:@"UnknownVFS"]; XCTAssertTrue([db hadError], @"Should have failed"); } - (void)testFailOnUnopenedDatabase { [self.db close]; XCTAssertNil([self.db executeQuery:@"select * from table"], @"Shouldn't get results from an empty table"); XCTAssertTrue([self.db hadError], @"Should have failed"); } - (void)testFailOnBadStatement { XCTAssertFalse([self.db executeUpdate:@"blah blah blah"], @"Invalid statement should fail"); XCTAssertTrue([self.db hadError], @"Should have failed"); } - (void)testFailOnBadStatementWithError { NSError *error = nil; XCTAssertFalse([self.db executeUpdate:@"blah blah blah" withErrorAndBindings:&error], @"Invalid statement should fail"); XCTAssertNotNil(error, @"Should have a non-nil NSError"); XCTAssertEqual([error code], (NSInteger)SQLITE_ERROR, @"Error should be SQLITE_ERROR"); } - (void)testPragmaJournalMode { FMResultSet *ps = [self.db executeQuery:@"pragma journal_mode=delete"]; XCTAssertFalse([self.db hadError], @"pragma should have succeeded"); XCTAssertNotNil(ps, @"Result set should be non-nil"); XCTAssertTrue([ps next], @"Result set should have a next result"); [ps close]; } - (void)testPragmaPageSize { [self.db executeUpdate:@"PRAGMA page_size=2048"]; XCTAssertFalse([self.db hadError], @"pragma should have succeeded"); } - (void)testVacuum { [self.db executeUpdate:@"VACUUM"]; XCTAssertFalse([self.db hadError], @"VACUUM should have succeeded"); } - (void)testSelectULL { // Unsigned long long [self.db executeUpdate:@"create table ull (a integer)"]; [self.db executeUpdate:@"insert into ull (a) values (?)", [NSNumber numberWithUnsignedLongLong:ULLONG_MAX]]; XCTAssertFalse([self.db hadError], @"Shouldn't have any errors"); FMResultSet *rs = [self.db executeQuery:@"select a from ull"]; while ([rs next]) { XCTAssertEqual([rs unsignedLongLongIntForColumnIndex:0], ULLONG_MAX, @"Result should be ULLONG_MAX"); XCTAssertEqual([rs unsignedLongLongIntForColumn:@"a"], ULLONG_MAX, @"Result should be ULLONG_MAX"); } [rs close]; XCTAssertFalse([self.db hasOpenResultSets], @"Shouldn't have any open result sets"); XCTAssertFalse([self.db hadError], @"Shouldn't have any errors"); } - (void)testSelectByColumnName { FMResultSet *rs = [self.db executeQuery:@"select rowid,* from test where a = ?", @"hi"]; XCTAssertNotNil(rs, @"Should have a non-nil result set"); while ([rs next]) { [rs intForColumn:@"c"]; XCTAssertNotNil([rs stringForColumn:@"b"], @"Should have non-nil string for 'b'"); XCTAssertNotNil([rs stringForColumn:@"a"], @"Should have non-nil string for 'a'"); XCTAssertNotNil([rs stringForColumn:@"rowid"], @"Should have non-nil string for 'rowid'"); XCTAssertNotNil([rs dateForColumn:@"d"], @"Should have non-nil date for 'd'"); [rs doubleForColumn:@"d"]; [rs doubleForColumn:@"e"]; XCTAssertEqualObjects([rs columnNameForIndex:0], @"rowid", @"Wrong column name for result set column number"); XCTAssertEqualObjects([rs columnNameForIndex:1], @"a", @"Wrong column name for result set column number"); } [rs close]; XCTAssertFalse([self.db hasOpenResultSets], @"Shouldn't have any open result sets"); XCTAssertFalse([self.db hadError], @"Shouldn't have any errors"); } - (void)testInvalidColumnNames { FMResultSet *rs = [self.db executeQuery:@"select rowid, a, b, c from test"]; XCTAssertNotNil(rs, @"Should have a non-nil result set"); NSString *invalidColumnName = @"foobar"; while ([rs next]) { XCTAssertNil(rs[invalidColumnName], @"Invalid column name should return nil"); XCTAssertNil([rs stringForColumn:invalidColumnName], @"Invalid column name should return nil"); XCTAssertEqual([rs UTF8StringForColumn:invalidColumnName], (const unsigned char *)0, @"Invalid column name should return nil"); XCTAssertNil([rs dateForColumn:invalidColumnName], @"Invalid column name should return nil"); XCTAssertNil([rs dataForColumn:invalidColumnName], @"Invalid column name should return nil"); XCTAssertNil([rs dataNoCopyForColumn:invalidColumnName], @"Invalid column name should return nil"); XCTAssertNil([rs objectForColumn:invalidColumnName], @"Invalid column name should return nil"); } [rs close]; XCTAssertFalse([self.db hasOpenResultSets], @"Shouldn't have any open result sets"); XCTAssertFalse([self.db hadError], @"Shouldn't have any errors"); } - (void)testInvalidColumnIndexes { FMResultSet *rs = [self.db executeQuery:@"select rowid, a, b, c from test"]; XCTAssertNotNil(rs, @"Should have a non-nil result set"); int invalidColumnIndex = 999; while ([rs next]) { XCTAssertNil(rs[invalidColumnIndex], @"Invalid column name should return nil"); XCTAssertNil([rs stringForColumnIndex:invalidColumnIndex], @"Invalid column name should return nil"); XCTAssertEqual([rs UTF8StringForColumnIndex:invalidColumnIndex], (const unsigned char *)0, @"Invalid column name should return nil"); XCTAssertNil([rs dateForColumnIndex:invalidColumnIndex], @"Invalid column name should return nil"); XCTAssertNil([rs dataForColumnIndex:invalidColumnIndex], @"Invalid column name should return nil"); XCTAssertNil([rs dataNoCopyForColumnIndex:invalidColumnIndex], @"Invalid column name should return nil"); XCTAssertNil([rs objectForColumnIndex:invalidColumnIndex], @"Invalid column name should return nil"); } [rs close]; XCTAssertFalse([self.db hasOpenResultSets], @"Shouldn't have any open result sets"); XCTAssertFalse([self.db hadError], @"Shouldn't have any errors"); } - (void)testBusyRetryTimeout { [self.db executeUpdate:@"create table t1 (a integer)"]; [self.db executeUpdate:@"insert into t1 values (?)", [NSNumber numberWithInt:5]]; [self.db setMaxBusyRetryTimeInterval:2]; FMDatabase *newDB = [FMDatabase databaseWithPath:self.databasePath]; [newDB open]; FMResultSet *rs = [newDB executeQuery:@"select rowid,* from test where a = ?", @"hi'"]; [rs next]; // just grab one... which will keep the db locked XCTAssertFalse([self.db executeUpdate:@"insert into t1 values (5)"], @"Insert should fail because the db is locked by a read"); XCTAssertEqual([self.db lastErrorCode], SQLITE_BUSY, @"SQLITE_BUSY should be the last error"); [rs close]; [newDB close]; XCTAssertTrue([self.db executeUpdate:@"insert into t1 values (5)"], @"The database shouldn't be locked at this point"); } - (void)testCaseSensitiveResultDictionary { // case sensitive result dictionary test [self.db executeUpdate:@"create table cs (aRowName integer, bRowName text)"]; [self.db executeUpdate:@"insert into cs (aRowName, bRowName) values (?, ?)", [NSNumber numberWithInt:1], @"hello"]; XCTAssertFalse([self.db hadError], @"Shouldn't have any errors"); FMResultSet *rs = [self.db executeQuery:@"select * from cs"]; while ([rs next]) { NSDictionary *d = [rs resultDictionary]; XCTAssertNotNil([d objectForKey:@"aRowName"], @"aRowName should be non-nil"); XCTAssertNil([d objectForKey:@"arowname"], @"arowname should be nil"); XCTAssertNotNil([d objectForKey:@"bRowName"], @"bRowName should be non-nil"); XCTAssertNil([d objectForKey:@"browname"], @"browname should be nil"); } [rs close]; XCTAssertFalse([self.db hasOpenResultSets], @"Shouldn't have any open result sets"); XCTAssertFalse([self.db hadError], @"Shouldn't have any errors"); } - (void)testBoolInsert { [self.db executeUpdate:@"create table btest (aRowName integer)"]; [self.db executeUpdate:@"insert into btest (aRowName) values (?)", [NSNumber numberWithBool:YES]]; XCTAssertFalse([self.db hadError], @"Shouldn't have any errors"); FMResultSet *rs = [self.db executeQuery:@"select * from btest"]; while ([rs next]) { XCTAssertTrue([rs boolForColumnIndex:0], @"first column should be true."); XCTAssertTrue([rs intForColumnIndex:0] == 1, @"first column should be equal to 1 - it was %d.", [rs intForColumnIndex:0]); } [rs close]; XCTAssertFalse([self.db hasOpenResultSets], @"Shouldn't have any open result sets"); XCTAssertFalse([self.db hadError], @"Shouldn't have any errors"); } - (void)testNamedParametersCount { XCTAssertTrue([self.db executeUpdate:@"create table namedparamcounttest (a text, b text, c integer, d double)"]); NSMutableDictionary *dictionaryArgs = [NSMutableDictionary dictionary]; [dictionaryArgs setObject:@"Text1" forKey:@"a"]; [dictionaryArgs setObject:@"Text2" forKey:@"b"]; [dictionaryArgs setObject:[NSNumber numberWithInt:1] forKey:@"c"]; [dictionaryArgs setObject:[NSNumber numberWithDouble:2.0] forKey:@"d"]; XCTAssertTrue([self.db executeUpdate:@"insert into namedparamcounttest values (:a, :b, :c, :d)" withParameterDictionary:dictionaryArgs]); FMResultSet *rs = [self.db executeQuery:@"select * from namedparamcounttest"]; XCTAssertNotNil(rs); [rs next]; XCTAssertEqualObjects([rs stringForColumn:@"a"], @"Text1"); XCTAssertEqualObjects([rs stringForColumn:@"b"], @"Text2"); XCTAssertEqual([rs intForColumn:@"c"], 1); XCTAssertEqual([rs doubleForColumn:@"d"], 2.0); [rs close]; // note that at this point, dictionaryArgs has way more values than we need, but the query should still work since // a is in there, and that's all we need. rs = [self.db executeQuery:@"select * from namedparamcounttest where a = :a" withParameterDictionary:dictionaryArgs]; XCTAssertNotNil(rs); XCTAssertTrue([rs next]); [rs close]; // ***** Please note the following codes ***** dictionaryArgs = [NSMutableDictionary dictionary]; [dictionaryArgs setObject:@"NewText1" forKey:@"a"]; [dictionaryArgs setObject:@"NewText2" forKey:@"b"]; [dictionaryArgs setObject:@"OneMoreText" forKey:@"OneMore"]; XCTAssertTrue([self.db executeUpdate:@"update namedparamcounttest set a = :a, b = :b where b = 'Text2'" withParameterDictionary:dictionaryArgs]); } - (void)testBlobs { [self.db executeUpdate:@"create table blobTable (a text, b blob)"]; // let's read an image from safari's app bundle. NSData *safariCompass = [NSData dataWithContentsOfFile:@"/Applications/Safari.app/Contents/Resources/compass.icns"]; if (safariCompass) { [self.db executeUpdate:@"insert into blobTable (a, b) values (?, ?)", @"safari's compass", safariCompass]; FMResultSet *rs = [self.db executeQuery:@"select b from blobTable where a = ?", @"safari's compass"]; XCTAssertTrue([rs next]); NSData *readData = [rs dataForColumn:@"b"]; XCTAssertEqualObjects(readData, safariCompass); // ye shall read the header for this function, or suffer the consequences. NSData *readDataNoCopy = [rs dataNoCopyForColumn:@"b"]; XCTAssertEqualObjects(readDataNoCopy, safariCompass); [rs close]; XCTAssertFalse([self.db hasOpenResultSets], @"Shouldn't have any open result sets"); XCTAssertFalse([self.db hadError], @"Shouldn't have any errors"); } } - (void)testNullValues { [self.db executeUpdate:@"create table t2 (a integer, b integer)"]; BOOL result = [self.db executeUpdate:@"insert into t2 values (?, ?)", nil, [NSNumber numberWithInt:5]]; XCTAssertTrue(result, @"Failed to insert a nil value"); FMResultSet *rs = [self.db executeQuery:@"select * from t2"]; while ([rs next]) { XCTAssertNil([rs stringForColumnIndex:0], @"Wasn't able to retrieve a null string"); XCTAssertEqualObjects([rs stringForColumnIndex:1], @"5"); } [rs close]; XCTAssertFalse([self.db hasOpenResultSets], @"Shouldn't have any open result sets"); XCTAssertFalse([self.db hadError], @"Shouldn't have any errors"); } - (void)testNestedResultSets { FMResultSet *rs = [self.db executeQuery:@"select * from t3"]; while ([rs next]) { int foo = [rs intForColumnIndex:0]; int newVal = foo + 100; [self.db executeUpdate:@"update t3 set a = ? where a = ?", [NSNumber numberWithInt:newVal], [NSNumber numberWithInt:foo]]; FMResultSet *rs2 = [self.db executeQuery:@"select a from t3 where a = ?", [NSNumber numberWithInt:newVal]]; [rs2 next]; XCTAssertEqual([rs2 intForColumnIndex:0], newVal); [rs2 close]; } [rs close]; XCTAssertFalse([self.db hasOpenResultSets], @"Shouldn't have any open result sets"); XCTAssertFalse([self.db hadError], @"Shouldn't have any errors"); } - (void)testNSNullInsertion { [self.db executeUpdate:@"create table nulltest (a text, b text)"]; [self.db executeUpdate:@"insert into nulltest (a, b) values (?, ?)", [NSNull null], @"a"]; [self.db executeUpdate:@"insert into nulltest (a, b) values (?, ?)", nil, @"b"]; FMResultSet *rs = [self.db executeQuery:@"select * from nulltest"]; while ([rs next]) { XCTAssertNil([rs stringForColumnIndex:0]); XCTAssertNotNil([rs stringForColumnIndex:1]); } [rs close]; XCTAssertFalse([self.db hasOpenResultSets], @"Shouldn't have any open result sets"); XCTAssertFalse([self.db hadError], @"Shouldn't have any errors"); } - (void)testNullDates { NSDate *date = [NSDate date]; [self.db executeUpdate:@"create table datetest (a double, b double, c double)"]; [self.db executeUpdate:@"insert into datetest (a, b, c) values (?, ?, 0)" , [NSNull null], date]; FMResultSet *rs = [self.db executeQuery:@"select * from datetest"]; XCTAssertNotNil(rs); while ([rs next]) { NSDate *b = [rs dateForColumnIndex:1]; NSDate *c = [rs dateForColumnIndex:2]; XCTAssertNil([rs dateForColumnIndex:0]); XCTAssertNotNil(c, @"zero date shouldn't be nil"); XCTAssertEqualWithAccuracy([b timeIntervalSinceDate:date], 0.0, 1.0, @"Dates should be the same to within a second"); XCTAssertEqualWithAccuracy([c timeIntervalSince1970], 0.0, 1.0, @"Dates should be the same to within a second"); } [rs close]; XCTAssertFalse([self.db hasOpenResultSets], @"Shouldn't have any open result sets"); XCTAssertFalse([self.db hadError], @"Shouldn't have any errors"); } - (void)testLotsOfNULLs { NSData *safariCompass = [NSData dataWithContentsOfFile:@"/Applications/Safari.app/Contents/Resources/compass.icns"]; if (!safariCompass) return; [self.db executeUpdate:@"create table nulltest2 (s text, d data, i integer, f double, b integer)"]; [self.db executeUpdate:@"insert into nulltest2 (s, d, i, f, b) values (?, ?, ?, ?, ?)" , @"Hi", safariCompass, [NSNumber numberWithInt:12], [NSNumber numberWithFloat:4.4f], [NSNumber numberWithBool:YES]]; [self.db executeUpdate:@"insert into nulltest2 (s, d, i, f, b) values (?, ?, ?, ?, ?)" , nil, nil, nil, nil, [NSNull null]]; FMResultSet *rs = [self.db executeQuery:@"select * from nulltest2"]; while ([rs next]) { int i = [rs intForColumnIndex:2]; if (i == 12) { // it's the first row we inserted. XCTAssertFalse([rs columnIndexIsNull:0]); XCTAssertFalse([rs columnIndexIsNull:1]); XCTAssertFalse([rs columnIndexIsNull:2]); XCTAssertFalse([rs columnIndexIsNull:3]); XCTAssertFalse([rs columnIndexIsNull:4]); XCTAssertTrue( [rs columnIndexIsNull:5]); XCTAssertEqualObjects([rs dataForColumn:@"d"], safariCompass); XCTAssertNil([rs dataForColumn:@"notthere"]); XCTAssertNil([rs stringForColumnIndex:-2], @"Negative columns should return nil results"); XCTAssertTrue([rs boolForColumnIndex:4]); XCTAssertTrue([rs boolForColumn:@"b"]); XCTAssertEqualWithAccuracy(4.4, [rs doubleForColumn:@"f"], 0.0000001, @"Saving a float and returning it as a double shouldn't change the result much"); XCTAssertEqual([rs intForColumn:@"i"], 12); XCTAssertEqual([rs intForColumnIndex:2], 12); XCTAssertEqual([rs intForColumnIndex:12], 0, @"Non-existent columns should return zero for ints"); XCTAssertEqual([rs intForColumn:@"notthere"], 0, @"Non-existent columns should return zero for ints"); XCTAssertEqual([rs longForColumn:@"i"], 12l); XCTAssertEqual([rs longLongIntForColumn:@"i"], 12ll); } else { // let's test various null things. XCTAssertTrue([rs columnIndexIsNull:0]); XCTAssertTrue([rs columnIndexIsNull:1]); XCTAssertTrue([rs columnIndexIsNull:2]); XCTAssertTrue([rs columnIndexIsNull:3]); XCTAssertTrue([rs columnIndexIsNull:4]); XCTAssertTrue([rs columnIndexIsNull:5]); XCTAssertNil([rs dataForColumn:@"d"]); } } [rs close]; XCTAssertFalse([self.db hasOpenResultSets], @"Shouldn't have any open result sets"); XCTAssertFalse([self.db hadError], @"Shouldn't have any errors"); } - (void)testUTF8Strings { [self.db executeUpdate:@"create table utest (a text)"]; [self.db executeUpdate:@"insert into utest values (?)", @"/übertest"]; FMResultSet *rs = [self.db executeQuery:@"select * from utest where a = ?", @"/übertest"]; XCTAssertTrue([rs next]); [rs close]; XCTAssertFalse([self.db hasOpenResultSets], @"Shouldn't have any open result sets"); XCTAssertFalse([self.db hadError], @"Shouldn't have any errors"); } - (void)testArgumentsInArray { [self.db executeUpdate:@"create table testOneHundredTwelvePointTwo (a text, b integer)"]; [self.db executeUpdate:@"insert into testOneHundredTwelvePointTwo values (?, ?)" withArgumentsInArray:[NSArray arrayWithObjects:@"one", [NSNumber numberWithInteger:2], nil]]; [self.db executeUpdate:@"insert into testOneHundredTwelvePointTwo values (?, ?)" withArgumentsInArray:[NSArray arrayWithObjects:@"one", [NSNumber numberWithInteger:3], nil]]; FMResultSet *rs = [self.db executeQuery:@"select * from testOneHundredTwelvePointTwo where b > ?" withArgumentsInArray:[NSArray arrayWithObject:[NSNumber numberWithInteger:1]]]; XCTAssertTrue([rs next]); XCTAssertTrue([rs hasAnotherRow]); XCTAssertFalse([self.db hadError]); XCTAssertEqualObjects([rs stringForColumnIndex:0], @"one"); XCTAssertEqual([rs intForColumnIndex:1], 2); XCTAssertTrue([rs next]); XCTAssertEqual([rs intForColumnIndex:1], 3); XCTAssertFalse([rs next]); XCTAssertFalse([rs hasAnotherRow]); } - (void)testColumnNamesContainingPeriods { XCTAssertTrue([self.db executeUpdate:@"create table t4 (a text, b text)"]); [self.db executeUpdate:@"insert into t4 (a, b) values (?, ?)", @"one", @"two"]; FMResultSet *rs = [self.db executeQuery:@"select t4.a as 't4.a', t4.b from t4;"]; XCTAssertNotNil(rs); XCTAssertTrue([rs next]); XCTAssertEqualObjects([rs stringForColumn:@"t4.a"], @"one"); XCTAssertEqualObjects([rs stringForColumn:@"b"], @"two"); XCTAssertEqual(strcmp((const char*)[rs UTF8StringForColumn:@"b"], "two"), 0, @"String comparison should return zero"); [rs close]; // let's try these again, with the withArgumentsInArray: variation XCTAssertTrue([self.db executeUpdate:@"drop table t4;" withArgumentsInArray:[NSArray array]]); XCTAssertTrue([self.db executeUpdate:@"create table t4 (a text, b text)" withArgumentsInArray:[NSArray array]]); [self.db executeUpdate:@"insert into t4 (a, b) values (?, ?)" withArgumentsInArray:[NSArray arrayWithObjects:@"one", @"two", nil]]; rs = [self.db executeQuery:@"select t4.a as 't4.a', t4.b from t4;" withArgumentsInArray:[NSArray array]]; XCTAssertNotNil(rs); XCTAssertTrue([rs next]); XCTAssertEqualObjects([rs stringForColumn:@"t4.a"], @"one"); XCTAssertEqualObjects([rs stringForColumn:@"b"], @"two"); XCTAssertEqual(strcmp((const char*)[rs UTF8StringForColumn:@"b"], "two"), 0, @"String comparison should return zero"); [rs close]; } - (void)testFormatStringParsing { XCTAssertTrue([self.db executeUpdate:@"create table t5 (a text, b int, c blob, d text, e text)"]); [self.db executeUpdateWithFormat:@"insert into t5 values (%s, %d, %@, %c, %lld)", "text", 42, @"BLOB", 'd', 12345678901234ll]; FMResultSet *rs = [self.db executeQueryWithFormat:@"select * from t5 where a = %s and a = %@ and b = %d", "text", @"text", 42]; XCTAssertNotNil(rs); XCTAssertTrue([rs next]); XCTAssertEqualObjects([rs stringForColumn:@"a"], @"text"); XCTAssertEqual([rs intForColumn:@"b"], 42); XCTAssertEqualObjects([rs stringForColumn:@"c"], @"BLOB"); XCTAssertEqualObjects([rs stringForColumn:@"d"], @"d"); XCTAssertEqual([rs longLongIntForColumn:@"e"], 12345678901234ll); [rs close]; } - (void)testFormatStringParsingWithSizePrefixes { XCTAssertTrue([self.db executeUpdate:@"create table t55 (a text, b int, c float)"]); short testShort = -4; float testFloat = 5.5; [self.db executeUpdateWithFormat:@"insert into t55 values (%c, %hi, %g)", 'a', testShort, testFloat]; unsigned short testUShort = 6; [self.db executeUpdateWithFormat:@"insert into t55 values (%c, %hu, %g)", 'a', testUShort, testFloat]; FMResultSet *rs = [self.db executeQueryWithFormat:@"select * from t55 where a = %s order by 2", "a"]; XCTAssertNotNil(rs); XCTAssertTrue([rs next]); XCTAssertEqualObjects([rs stringForColumn:@"a"], @"a"); XCTAssertEqual([rs intForColumn:@"b"], -4); XCTAssertEqualObjects([rs stringForColumn:@"c"], @"5.5"); XCTAssertTrue([rs next]); XCTAssertEqualObjects([rs stringForColumn:@"a"], @"a"); XCTAssertEqual([rs intForColumn:@"b"], 6); XCTAssertEqualObjects([rs stringForColumn:@"c"], @"5.5"); [rs close]; } - (void)testFormatStringParsingWithNilValue { XCTAssertTrue([self.db executeUpdate:@"create table tatwhat (a text)"]); BOOL worked = [self.db executeUpdateWithFormat:@"insert into tatwhat values(%@)", nil]; XCTAssertTrue(worked); FMResultSet *rs = [self.db executeQueryWithFormat:@"select * from tatwhat"]; XCTAssertNotNil(rs); XCTAssertTrue([rs next]); XCTAssertTrue([rs columnIndexIsNull:0]); XCTAssertFalse([rs next]); } - (void)testUpdateWithErrorAndBindings { XCTAssertTrue([self.db executeUpdate:@"create table t5 (a text, b int, c blob, d text, e text)"]); NSError *err = nil; BOOL result = [self.db executeUpdate:@"insert into t5 values (?, ?, ?, ?, ?)" withErrorAndBindings:&err, @"text", [NSNumber numberWithInt:42], @"BLOB", @"d", [NSNumber numberWithInt:0]]; XCTAssertTrue(result); } - (void)testSelectWithEmptyArgumentsArray { FMResultSet *rs = [self.db executeQuery:@"select * from test where a=?" withArgumentsInArray:@[]]; XCTAssertNil(rs); } - (void)testDatabaseAttach { NSFileManager *fileManager = [NSFileManager new]; [fileManager removeItemAtPath:@"/tmp/attachme.db" error:nil]; FMDatabase *dbB = [FMDatabase databaseWithPath:@"/tmp/attachme.db"]; XCTAssertTrue([dbB open]); XCTAssertTrue([dbB executeUpdate:@"create table attached (a text)"]); XCTAssertTrue(([dbB executeUpdate:@"insert into attached values (?)", @"test"])); XCTAssertTrue([dbB close]); [self.db executeUpdate:@"attach database '/tmp/attachme.db' as attack"]; FMResultSet *rs = [self.db executeQuery:@"select * from attack.attached"]; XCTAssertNotNil(rs); XCTAssertTrue([rs next]); [rs close]; } - (void)testNamedParameters { // ------------------------------------------------------------------------------- // Named parameters. XCTAssertTrue([self.db executeUpdate:@"create table namedparamtest (a text, b text, c integer, d double)"]); NSMutableDictionary *dictionaryArgs = [NSMutableDictionary dictionary]; [dictionaryArgs setObject:@"Text1" forKey:@"a"]; [dictionaryArgs setObject:@"Text2" forKey:@"b"]; [dictionaryArgs setObject:[NSNumber numberWithInt:1] forKey:@"c"]; [dictionaryArgs setObject:[NSNumber numberWithDouble:2.0] forKey:@"d"]; XCTAssertTrue([self.db executeUpdate:@"insert into namedparamtest values (:a, :b, :c, :d)" withParameterDictionary:dictionaryArgs]); FMResultSet *rs = [self.db executeQuery:@"select * from namedparamtest"]; XCTAssertNotNil(rs); XCTAssertTrue([rs next]); XCTAssertEqualObjects([rs stringForColumn:@"a"], @"Text1"); XCTAssertEqualObjects([rs stringForColumn:@"b"], @"Text2"); XCTAssertEqual([rs intForColumn:@"c"], 1); XCTAssertEqual([rs doubleForColumn:@"d"], 2.0); [rs close]; dictionaryArgs = [NSMutableDictionary dictionary]; [dictionaryArgs setObject:@"Text2" forKey:@"blah"]; rs = [self.db executeQuery:@"select * from namedparamtest where b = :blah" withParameterDictionary:dictionaryArgs]; XCTAssertNotNil(rs); XCTAssertTrue([rs next]); XCTAssertEqualObjects([rs stringForColumn:@"b"], @"Text2"); [rs close]; } - (void)testPragmaDatabaseList { FMResultSet *rs = [self.db executeQuery:@"pragma database_list"]; int counter = 0; while ([rs next]) { counter++; XCTAssertEqualObjects([rs stringForColumn:@"file"], self.databasePath); } XCTAssertEqual(counter, 1, @"Only one database should be attached"); } - (void)testCachedStatementsInUse { [self.db setShouldCacheStatements:true]; [self.db executeUpdate:@"CREATE TABLE testCacheStatements(key INTEGER PRIMARY KEY, value INTEGER)"]; [self.db executeUpdate:@"INSERT INTO testCacheStatements (key, value) VALUES (1, 2)"]; [self.db executeUpdate:@"INSERT INTO testCacheStatements (key, value) VALUES (2, 4)"]; XCTAssertTrue([[self.db executeQuery:@"SELECT * FROM testCacheStatements WHERE key=1"] next]); XCTAssertTrue([[self.db executeQuery:@"SELECT * FROM testCacheStatements WHERE key=1"] next]); } - (void)testStatementCachingWorks { [self.db executeUpdate:@"CREATE TABLE testStatementCaching ( value INTEGER )"]; [self.db executeUpdate:@"INSERT INTO testStatementCaching( value ) VALUES (1)"]; [self.db executeUpdate:@"INSERT INTO testStatementCaching( value ) VALUES (1)"]; [self.db executeUpdate:@"INSERT INTO testStatementCaching( value ) VALUES (2)"]; [self.db setShouldCacheStatements:YES]; // two iterations. // the first time through no statements will be from the cache. // the second time through all statements come from the cache. for (int i = 1; i <= 2; i++ ) { FMResultSet* rs1 = [self.db executeQuery: @"SELECT rowid, * FROM testStatementCaching WHERE value = ?", @1]; // results in 2 rows... XCTAssertNotNil(rs1); XCTAssertTrue([rs1 next]); // confirm that we're seeing the benefits of caching. XCTAssertEqual([[rs1 statement] useCount], (long)i); FMResultSet* rs2 = [self.db executeQuery:@"SELECT rowid, * FROM testStatementCaching WHERE value = ?", @2]; // results in 1 row XCTAssertNotNil(rs2); XCTAssertTrue([rs2 next]); XCTAssertEqual([[rs2 statement] useCount], (long)i); // This is the primary check - with the old implementation of statement caching, rs2 would have rejiggered the (cached) statement used by rs1, making this test fail to return the 2nd row in rs1. XCTAssertTrue([rs1 next]); [rs1 close]; [rs2 close]; } } /* Test the date format */ - (void)testDateFormat { void (^testOneDateFormat)(FMDatabase *, NSDate *) = ^( FMDatabase *db, NSDate *testDate ){ [db executeUpdate:@"DROP TABLE IF EXISTS test_format"]; [db executeUpdate:@"CREATE TABLE test_format ( test TEXT )"]; [db executeUpdate:@"INSERT INTO test_format(test) VALUES (?)", testDate]; FMResultSet *rs = [db executeQuery:@"SELECT test FROM test_format"]; XCTAssertNotNil(rs); XCTAssertTrue([rs next]); XCTAssertEqualObjects([rs dateForColumnIndex:0], testDate); [rs close]; }; NSDateFormatter *fmt = [FMDatabase storeableDateFormat:@"yyyy-MM-dd HH:mm:ss"]; NSDate *testDate = [fmt dateFromString:@"2013-02-20 12:00:00"]; // test timestamp dates (ensuring our change does not break those) testOneDateFormat(self.db,testDate); // now test the string-based timestamp [self.db setDateFormat:fmt]; testOneDateFormat(self.db, testDate); } - (void)testColumnNameMap { XCTAssertTrue([self.db executeUpdate:@"create table colNameTest (a, b, c, d)"]); XCTAssertTrue([self.db executeUpdate:@"insert into colNameTest values (1, 2, 3, 4)"]); FMResultSet *ars = [self.db executeQuery:@"select * from colNameTest"]; XCTAssertNotNil(ars); NSDictionary *d = [ars columnNameToIndexMap]; XCTAssertEqual([d count], (NSUInteger)4); XCTAssertEqualObjects([d objectForKey:@"a"], @0); XCTAssertEqualObjects([d objectForKey:@"b"], @1); XCTAssertEqualObjects([d objectForKey:@"c"], @2); XCTAssertEqualObjects([d objectForKey:@"d"], @3); } - (void)testCustomStringFunction { [self createCustomFunctions]; FMResultSet *ars = [self.db executeQuery:@"SELECT RemoveDiacritics(?)", @"José"]; if (![ars next]) { XCTFail("Should have returned value"); return; } NSString *result = [ars stringForColumnIndex:0]; XCTAssertEqualObjects(result, @"Jose"); } - (void)testFailCustomStringFunction { [self createCustomFunctions]; FMResultSet *rs = [self.db executeQuery:@"SELECT RemoveDiacritics(?)", @(M_PI)]; XCTAssert(rs, @"Prepare should have succeeded"); NSError *error; BOOL success = [rs nextWithError:&error]; XCTAssertFalse(success, @"'next' should have failed"); XCTAssertEqualObjects(error.localizedDescription, @"Expected text"); rs = [self.db executeQuery:@"SELECT RemoveDiacritics('jose','ortega')"]; XCTAssertNil(rs); error = [self.db lastError]; XCTAssert([error.localizedDescription containsString:@"wrong number of arguments"], @"Should get wrong number of arguments error, but got '%@'", error.localizedDescription); } - (void)testCustomDoubleFunction { [self createCustomFunctions]; FMResultSet *rs = [self.db executeQuery:@"SELECT Hypotenuse(?, ?)", @(3.0), @(4.0)]; if (![rs next]) { XCTFail("Should have returned value"); return; } double value = [rs doubleForColumnIndex:0]; XCTAssertEqual(value, 5.0); } - (void)testCustomIntFunction { [self createCustomFunctions]; FMResultSet *rs = [self.db executeQuery:@"SELECT Hypotenuse(?, ?)", @(3), @(4)]; if (![rs next]) { XCTFail("Should have returned value"); return; } int value = [rs intForColumnIndex:0]; XCTAssertEqual(value, 5); } - (void)testFailCustomNumericFunction { [self createCustomFunctions]; FMResultSet *rs = [self.db executeQuery:@"SELECT Hypotenuse(?, ?)", @"foo", @"bar"]; NSError *error; if ([rs nextWithError:&error]) { XCTFail("Should have failed"); return; } XCTAssertEqualObjects(error.localizedDescription, @"Expected numeric"); rs = [self.db executeQuery:@"SELECT Hypotenuse(?)", @(3.0)]; XCTAssertNil(rs, @"Should fail for wrong number of arguments"); error = [self.db lastError]; XCTAssert([error.localizedDescription containsString:@"wrong number of arguments"], @"Should get wrong number of arguments error, but got '%@'", error.localizedDescription); } - (void)testCustomDataFunction { [self createCustomFunctions]; NSMutableData *data = [NSMutableData data]; for (NSInteger i = 0; i < 256; i++) { uint8_t byte = i; [data appendBytes:&byte length:1]; } FMResultSet *rs = [self.db executeQuery:@"SELECT SetAlternatingByteToOne(?)", data]; if (![rs next]) { XCTFail("Should have returned value"); return; } NSData *result = [rs dataForColumnIndex:0]; XCTAssert(result, @"should have result"); XCTAssertEqual(result.length, (unsigned long)256); for (NSInteger i = 0; i < 256; i++) { uint8_t byte; [result getBytes:&byte range:NSMakeRange(i, 1)]; if (i % 2 == 0) { XCTAssertEqual(byte, (uint8_t)1); } else { XCTAssertEqual(byte, (uint8_t)i); } } } - (void)testFailCustomDataFunction { [self createCustomFunctions]; FMResultSet *rs = [self.db executeQuery:@"SELECT SetAlternatingByteToOne(?)", @"foo"]; XCTAssert(rs, @"Query should succeed"); NSError *error; BOOL success = [rs nextWithError:&error]; XCTAssertFalse(success, @"Performing SetAlternatingByteToOne with string should fail"); XCTAssertEqualObjects(error.localizedDescription, @"Expected blob"); } - (void)testCustomFunctionNullValues { [self.db makeFunctionNamed:@"FunctionThatDoesntTestTypes" arguments:1 block:^(void *context, int argc, void **argv) { NSData *data = [self.db valueData:argv[0]]; XCTAssertNil(data); NSString *string = [self.db valueString:argv[0]]; XCTAssertNil(string); int intValue = [self.db valueInt:argv[0]]; XCTAssertEqual(intValue, 0); long longValue = [self.db valueLong:argv[0]]; XCTAssertEqual(longValue, 0L); double doubleValue = [self.db valueDouble:argv[0]]; XCTAssertEqual(doubleValue, 0.0); [self.db resultInt:42 context:context]; }]; FMResultSet *rs = [self.db executeQuery:@"SELECT FunctionThatDoesntTestTypes(?)", [NSNull null]]; XCTAssert(rs, @"Creating query should succeed"); NSError *error = nil; if (rs) { BOOL success = [rs nextWithError:&error]; XCTAssert(success, @"Performing query should succeed"); } } - (void)testCustomFunctionIntResult { [self.db makeFunctionNamed:@"IntResultFunction" arguments:0 block:^(void *context, int argc, void **argv) { [self.db resultInt:42 context:context]; }]; FMResultSet *rs = [self.db executeQuery:@"SELECT IntResultFunction()"]; XCTAssert(rs, @"Creating query should succeed"); BOOL success = [rs next]; XCTAssert(success, @"Performing query should succeed"); XCTAssertEqual([rs intForColumnIndex:0], 42); } - (void)testCustomFunctionLongResult { [self.db makeFunctionNamed:@"LongResultFunction" arguments:0 block:^(void *context, int argc, void **argv) { [self.db resultLong:42 context:context]; }]; FMResultSet *rs = [self.db executeQuery:@"SELECT LongResultFunction()"]; XCTAssert(rs, @"Creating query should succeed"); BOOL success = [rs next]; XCTAssert(success, @"Performing query should succeed"); XCTAssertEqual([rs longForColumnIndex:0], (long)42); } - (void)testCustomFunctionDoubleResult { [self.db makeFunctionNamed:@"DoubleResultFunction" arguments:0 block:^(void *context, int argc, void **argv) { [self.db resultDouble:0.1 context:context]; }]; FMResultSet *rs = [self.db executeQuery:@"SELECT DoubleResultFunction()"]; XCTAssert(rs, @"Creating query should succeed"); BOOL success = [rs next]; XCTAssert(success, @"Performing query should succeed"); XCTAssertEqual([rs doubleForColumnIndex:0], 0.1); } - (void)testCustomFunctionNullResult { [self.db makeFunctionNamed:@"NullResultFunction" arguments:0 block:^(void *context, int argc, void **argv) { [self.db resultNullInContext:context]; }]; FMResultSet *rs = [self.db executeQuery:@"SELECT NullResultFunction()"]; XCTAssert(rs, @"Creating query should succeed"); BOOL success = [rs next]; XCTAssert(success, @"Performing query should succeed"); XCTAssertEqualObjects([rs objectForColumnIndex:0], [NSNull null]); } - (void)testCustomFunctionErrorResult { [self.db makeFunctionNamed:@"ErrorResultFunction" arguments:0 block:^(void *context, int argc, void **argv) { [self.db resultError:@"foo" context:context]; [self.db resultErrorCode:42 context:context]; }]; FMResultSet *rs = [self.db executeQuery:@"SELECT ErrorResultFunction()"]; XCTAssert(rs, @"Creating query should succeed"); NSError *error = nil; BOOL success = [rs nextWithError:&error]; XCTAssertFalse(success, @"Performing query should fail."); XCTAssertEqualObjects(error.localizedDescription, @"foo"); XCTAssertEqual(error.code, 42); } - (void)testCustomFunctionTooBigErrorResult { [self.db makeFunctionNamed:@"TooBigErrorResultFunction" arguments:0 block:^(void *context, int argc, void **argv) { [self.db resultErrorTooBigInContext:context]; }]; FMResultSet *rs = [self.db executeQuery:@"SELECT TooBigErrorResultFunction()"]; XCTAssert(rs, @"Creating query should succeed"); NSError *error = nil; BOOL success = [rs nextWithError:&error]; XCTAssertFalse(success, @"Performing query should fail."); XCTAssertEqualObjects(error.localizedDescription, @"string or blob too big"); XCTAssertEqual(error.code, SQLITE_TOOBIG); } - (void)testCustomFunctionNoMemoryErrorResult { [self.db makeFunctionNamed:@"NoMemoryErrorResultFunction" arguments:0 block:^(void *context, int argc, void **argv) { [self.db resultErrorNoMemoryInContext:context]; }]; FMResultSet *rs = [self.db executeQuery:@"SELECT NoMemoryErrorResultFunction()"]; XCTAssert(rs, @"Creating query should succeed"); NSError *error = nil; BOOL success = [rs nextWithError:&error]; XCTAssertFalse(success, @"Performing query should fail."); XCTAssertEqualObjects(error.localizedDescription, @"out of memory"); XCTAssertEqual(error.code, SQLITE_NOMEM); } - (void)createCustomFunctions { [self.db makeFunctionNamed:@"RemoveDiacritics" arguments:1 block:^(void *context, int argc, void **argv) { SqliteValueType type = [self.db valueType:argv[0]]; if (type == SqliteValueTypeNull) { [self.db resultNullInContext:context]; return; } if (type != SqliteValueTypeText) { [self.db resultError:@"Expected text" context:context]; return; } NSString *string = [self.db valueString:argv[0]]; NSString *result = [string stringByFoldingWithOptions:NSDiacriticInsensitiveSearch locale:nil]; [self.db resultString:result context:context]; }]; [self.db makeFunctionNamed:@"Hypotenuse" arguments:2 block:^(void *context, int argc, void **argv) { SqliteValueType type1 = [self.db valueType:argv[0]]; SqliteValueType type2 = [self.db valueType:argv[1]]; if (type1 != SqliteValueTypeFloat && type1 != SqliteValueTypeInteger && type2 != SqliteValueTypeFloat && type2 != SqliteValueTypeInteger) { [self.db resultError:@"Expected numeric" context:context]; return; } double value1 = [self.db valueDouble:argv[0]]; double value2 = [self.db valueDouble:argv[1]]; [self.db resultDouble:hypot(value1, value2) context:context]; }]; [self.db makeFunctionNamed:@"SetAlternatingByteToOne" arguments:1 block:^(void *context, int argc, void **argv) { SqliteValueType type = [self.db valueType:argv[0]]; if (type != SqliteValueTypeBlob) { [self.db resultError:@"Expected blob" context:context]; return; } NSMutableData *data = [[self.db valueData:argv[0]] mutableCopy]; uint8_t byte = 1; for (NSUInteger i = 0; i < data.length; i += 2) { [data replaceBytesInRange:NSMakeRange(i, 1) withBytes:&byte]; } [self.db resultData:data context:context]; }]; } /* This is deprecated, and as such, should be excluded from tests * * - (void)testVersionNumber { * XCTAssertEqual([FMDatabase FMDBVersion], 0x0278); // this is going to break every time we bump it. * } * */ - (void)testUserVersion { NSComparisonResult result = [[FMDatabase FMDBUserVersion] compare:@"2.7.12" options:NSNumericSearch]; XCTAssertEqual(result, NSOrderedSame); } - (void)testVersionStringAboveRequired { NSComparisonResult result = [[FMDatabase FMDBUserVersion] compare:@"1.100.42" options:NSNumericSearch]; XCTAssertEqual(result, NSOrderedDescending); } - (void)testVersionStringBelowRequired { NSComparisonResult result = [[FMDatabase FMDBUserVersion] compare:@"10.0.42" options:NSNumericSearch]; XCTAssertEqual(result, NSOrderedAscending); } - (void)testExecuteStatements { BOOL success; NSString *sql = @"create table bulktest1 (id integer primary key autoincrement, x text);" "create table bulktest2 (id integer primary key autoincrement, y text);" "create table bulktest3 (id integer primary key autoincrement, z text);" "insert into bulktest1 (x) values ('XXX');" "insert into bulktest2 (y) values ('YYY');" "insert into bulktest3 (z) values ('ZZZ');"; success = [self.db executeStatements:sql]; XCTAssertTrue(success, @"bulk create"); sql = @"select count(*) as count from bulktest1;" "select count(*) as count from bulktest2;" "select count(*) as count from bulktest3;"; success = [self.db executeStatements:sql withResultBlock:^int(NSDictionary *dictionary) { NSInteger count = [dictionary[@"count"] integerValue]; XCTAssertEqual(count, 1, @"expected one record for dictionary %@", dictionary); return 0; }]; XCTAssertTrue(success, @"bulk select"); // select blob type records [self.db executeUpdate:@"create table bulktest4 (id integer primary key autoincrement, b blob);"]; NSData *blobData = [[NSData alloc] initWithContentsOfFile:@"/bin/bash"]; [self.db executeUpdate:@"insert into bulktest4 (b) values (?)" values:@[blobData] error:nil]; sql = @"select * from bulktest4"; success = [self.db executeStatements:sql withResultBlock:^int(NSDictionary * _Nonnull resultsDictionary) { return 0; }]; XCTAssertTrue(success, @"bulk select"); sql = @"drop table bulktest1;" "drop table bulktest2;" "drop table bulktest3;" "drop table bulktest4"; success = [self.db executeStatements:sql]; XCTAssertTrue(success, @"bulk drop"); } - (void)testCharAndBoolTypes { XCTAssertTrue([self.db executeUpdate:@"create table charBoolTest (a, b, c)"]); BOOL success = [self.db executeUpdate:@"insert into charBoolTest values (?, ?, ?)", @YES, @NO, @('x')]; XCTAssertTrue(success, @"Unable to insert values"); FMResultSet *rs = [self.db executeQuery:@"select * from charBoolTest"]; XCTAssertNotNil(rs); XCTAssertTrue([rs next], @"Did not return row"); XCTAssertEqual([rs boolForColumn:@"a"], true); XCTAssertEqualObjects([rs objectForColumn:@"a"], @YES); XCTAssertEqual([rs boolForColumn:@"b"], false); XCTAssertEqualObjects([rs objectForColumn:@"b"], @NO); XCTAssertEqual([rs intForColumn:@"c"], 'x'); XCTAssertEqualObjects([rs objectForColumn:@"c"], @('x')); [rs close]; XCTAssertTrue([self.db executeUpdate:@"drop table charBoolTest"], @"Did not drop table"); } - (void)testSqliteLibVersion { NSString *version = [FMDatabase sqliteLibVersion]; XCTAssert([version compare:@"3.7" options:NSNumericSearch] == NSOrderedDescending, @"earlier than 3.7"); XCTAssert([version compare:@"4.0" options:NSNumericSearch] == NSOrderedAscending, @"not earlier than 4.0"); } - (void)testIsThreadSafe { BOOL isThreadSafe = [FMDatabase isSQLiteThreadSafe]; XCTAssert(isThreadSafe, @"not threadsafe"); } - (void)testOpenNilPath { FMDatabase *db = [[FMDatabase alloc] init]; XCTAssert([db open], @"open failed"); XCTAssert([db executeUpdate:@"create table foo (bar text)"], @"create failed"); NSString *value = @"baz"; XCTAssert([db executeUpdate:@"insert into foo (bar) values (?)" withArgumentsInArray:@[value]], @"insert failed"); NSString *retrievedValue = [db stringForQuery:@"select bar from foo"]; XCTAssert([value compare:retrievedValue] == NSOrderedSame, @"values didn't match"); } - (void)testOpenZeroLengthPath { FMDatabase *db = [[FMDatabase alloc] initWithPath:@""]; XCTAssert([db open], @"open failed"); XCTAssert([db executeUpdate:@"create table foo (bar text)"], @"create failed"); NSString *value = @"baz"; XCTAssert([db executeUpdate:@"insert into foo (bar) values (?)" withArgumentsInArray:@[value]], @"insert failed"); NSString *retrievedValue = [db stringForQuery:@"select bar from foo"]; XCTAssert([value compare:retrievedValue] == NSOrderedSame, @"values didn't match"); } - (void)testOpenTwice { FMDatabase *db = [[FMDatabase alloc] init]; [db open]; XCTAssert([db open], @"Double open failed"); } - (void)testInvalid { NSString *documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0]; NSString *path = [documentsPath stringByAppendingPathComponent:@"nonexistentfolder/test.sqlite"]; FMDatabase *db = [[FMDatabase alloc] initWithPath:path]; XCTAssertFalse([db open], @"open did NOT fail"); } - (void)testChangingMaxBusyRetryTimeInterval { FMDatabase *db = [[FMDatabase alloc] init]; XCTAssert([db open], @"open failed"); NSTimeInterval originalInterval = db.maxBusyRetryTimeInterval; NSTimeInterval updatedInterval = originalInterval > 0 ? originalInterval + 1 : 1; db.maxBusyRetryTimeInterval = updatedInterval; NSTimeInterval diff = fabs(db.maxBusyRetryTimeInterval - updatedInterval); XCTAssert(diff < 1e-5, @"interval should have changed %.1f", diff); } - (void)testChangingMaxBusyRetryTimeIntervalDatabaseNotOpened { FMDatabase *db = [[FMDatabase alloc] init]; // XCTAssert([db open], @"open failed"); // deliberately not opened NSTimeInterval originalInterval = db.maxBusyRetryTimeInterval; NSTimeInterval updatedInterval = originalInterval > 0 ? originalInterval + 1 : 1; db.maxBusyRetryTimeInterval = updatedInterval; XCTAssertNotEqual(originalInterval, db.maxBusyRetryTimeInterval, @"interval should not have changed"); } - (void)testZeroMaxBusyRetryTimeInterval { FMDatabase *db = [[FMDatabase alloc] init]; XCTAssert([db open], @"open failed"); NSTimeInterval updatedInterval = 0; db.maxBusyRetryTimeInterval = updatedInterval; XCTAssertEqual(db.maxBusyRetryTimeInterval, updatedInterval, @"busy handler not disabled"); } - (void)testCloseOpenResultSets { FMDatabase *db = [[FMDatabase alloc] init]; XCTAssert([db open], @"open failed"); XCTAssert([db executeUpdate:@"create table foo (bar text)"], @"create failed"); NSString *value = @"baz"; XCTAssert([db executeUpdate:@"insert into foo (bar) values (?)" withArgumentsInArray:@[value]], @"insert failed"); FMResultSet *rs = [db executeQuery:@"select bar from foo"]; [db closeOpenResultSets]; XCTAssertFalse([rs next], @"step should have failed"); } - (void)testGoodConnection { FMDatabase *db = [[FMDatabase alloc] init]; XCTAssert([db open], @"open failed"); XCTAssert([db goodConnection], @"no good connection"); } - (void)testBadConnection { FMDatabase *db = [[FMDatabase alloc] init]; // XCTAssert([db open], @"open failed"); // deliberately did not open XCTAssertFalse([db goodConnection], @"no good connection"); } - (void)testLastRowId { FMDatabase *db = [[FMDatabase alloc] init]; XCTAssert([db open], @"open failed"); XCTAssert([db executeUpdate:@"create table foo (foo_id integer primary key autoincrement, bar text)"], @"create failed"); XCTAssert([db executeUpdate:@"insert into foo (bar) values (?)" withArgumentsInArray:@[@"baz"]], @"insert failed"); sqlite3_int64 firstRowId = [db lastInsertRowId]; XCTAssert([db executeUpdate:@"insert into foo (bar) values (?)" withArgumentsInArray:@[@"qux"]], @"insert failed"); sqlite3_int64 secondRowId = [db lastInsertRowId]; XCTAssertEqual(secondRowId - firstRowId, 1, @"rowid should have incremented"); } - (void)testChanges { FMDatabase *db = [[FMDatabase alloc] init]; XCTAssert([db open], @"open failed"); XCTAssert([db executeUpdate:@"create table foo (foo_id integer primary key autoincrement, bar text)"], @"create failed"); XCTAssert([db executeUpdate:@"insert into foo (bar) values (?)" withArgumentsInArray:@[@"baz"]], @"insert failed"); XCTAssert([db executeUpdate:@"insert into foo (bar) values (?)" withArgumentsInArray:@[@"qux"]], @"insert failed"); XCTAssert([db executeUpdate:@"update foo set bar = ?" withArgumentsInArray:@[@"xxx"]], @"insert failed"); int changes = [db changes]; XCTAssertEqual(changes, 2, @"two rows should have incremented \(%ld)", (long)changes); } - (void)testBind { FMDatabase *db = [[FMDatabase alloc] init]; XCTAssert([db open], @"open failed"); XCTAssert([db executeUpdate:@"create table foo (id integer primary key autoincrement, a numeric)"], @"create failed"); NSNumber *insertedValue; NSNumber *retrievedValue; insertedValue = [NSNumber numberWithChar:51]; XCTAssert([db executeUpdate:@"insert into foo (a) values (?)" withArgumentsInArray:@[insertedValue]], @"insert failed"); retrievedValue = @([db intForQuery:@"select a from foo where id = ?", @([db lastInsertRowId])]); XCTAssertEqualObjects(insertedValue, retrievedValue, @"values don't match"); insertedValue = [NSNumber numberWithUnsignedChar:52]; XCTAssert([db executeUpdate:@"insert into foo (a) values (?)" withArgumentsInArray:@[insertedValue]], @"insert failed"); retrievedValue = @([db intForQuery:@"select a from foo where id = ?", @([db lastInsertRowId])]); XCTAssertEqualObjects(insertedValue, retrievedValue, @"values don't match"); insertedValue = [NSNumber numberWithShort:53]; XCTAssert([db executeUpdate:@"insert into foo (a) values (?)" withArgumentsInArray:@[insertedValue]], @"insert failed"); retrievedValue = @([db intForQuery:@"select a from foo where id = ?", @([db lastInsertRowId])]); XCTAssertEqualObjects(insertedValue, retrievedValue, @"values don't match"); insertedValue = [NSNumber numberWithUnsignedShort:54]; XCTAssert([db executeUpdate:@"insert into foo (a) values (?)" withArgumentsInArray:@[insertedValue]], @"insert failed"); retrievedValue = @([db intForQuery:@"select a from foo where id = ?", @([db lastInsertRowId])]); XCTAssertEqualObjects(insertedValue, retrievedValue, @"values don't match"); insertedValue = [NSNumber numberWithInt:54]; XCTAssert([db executeUpdate:@"insert into foo (a) values (?)" withArgumentsInArray:@[insertedValue]], @"insert failed"); retrievedValue = @([db intForQuery:@"select a from foo where id = ?", @([db lastInsertRowId])]); XCTAssertEqualObjects(insertedValue, retrievedValue, @"values don't match"); insertedValue = [NSNumber numberWithUnsignedInt:55]; XCTAssert([db executeUpdate:@"insert into foo (a) values (?)" withArgumentsInArray:@[insertedValue]], @"insert failed"); retrievedValue = @([db intForQuery:@"select a from foo where id = ?", @([db lastInsertRowId])]); XCTAssertEqualObjects(insertedValue, retrievedValue, @"values don't match"); insertedValue = [NSNumber numberWithLong:56]; XCTAssert([db executeUpdate:@"insert into foo (a) values (?)" withArgumentsInArray:@[insertedValue]], @"insert failed"); retrievedValue = @([db longForQuery:@"select a from foo where id = ?", @([db lastInsertRowId])]); XCTAssertEqualObjects(insertedValue, retrievedValue, @"values don't match"); insertedValue = [NSNumber numberWithUnsignedLong:57]; XCTAssert([db executeUpdate:@"insert into foo (a) values (?)" withArgumentsInArray:@[insertedValue]], @"insert failed"); retrievedValue = @([db longForQuery:@"select a from foo where id = ?", @([db lastInsertRowId])]); XCTAssertEqualObjects(insertedValue, retrievedValue, @"values don't match"); insertedValue = [NSNumber numberWithLongLong:56]; XCTAssert([db executeUpdate:@"insert into foo (a) values (?)" withArgumentsInArray:@[insertedValue]], @"insert failed"); retrievedValue = @([db longForQuery:@"select a from foo where id = ?", @([db lastInsertRowId])]); XCTAssertEqualObjects(insertedValue, retrievedValue, @"values don't match"); insertedValue = [NSNumber numberWithUnsignedLongLong:57]; XCTAssert([db executeUpdate:@"insert into foo (a) values (?)" withArgumentsInArray:@[insertedValue]], @"insert failed"); retrievedValue = @([db longForQuery:@"select a from foo where id = ?", @([db lastInsertRowId])]); XCTAssertEqualObjects(insertedValue, retrievedValue, @"values don't match"); insertedValue = [NSNumber numberWithFloat:58]; XCTAssert([db executeUpdate:@"insert into foo (a) values (?)" withArgumentsInArray:@[insertedValue]], @"insert failed"); retrievedValue = @([db doubleForQuery:@"select a from foo where id = ?", @([db lastInsertRowId])]); XCTAssertEqualObjects(insertedValue, retrievedValue, @"values don't match"); insertedValue = [NSNumber numberWithDouble:59]; XCTAssert([db executeUpdate:@"insert into foo (a) values (?)" withArgumentsInArray:@[insertedValue]], @"insert failed"); retrievedValue = @([db doubleForQuery:@"select a from foo where id = ?", @([db lastInsertRowId])]); XCTAssertEqualObjects(insertedValue, retrievedValue, @"values don't match"); insertedValue = @TRUE; XCTAssert([db executeUpdate:@"insert into foo (a) values (?)" withArgumentsInArray:@[insertedValue]], @"insert failed"); retrievedValue = @([db boolForQuery:@"select a from foo where id = ?", @([db lastInsertRowId])]); XCTAssertEqualObjects(insertedValue, retrievedValue, @"values don't match"); } - (void)testFormatStrings { FMDatabase *db = [[FMDatabase alloc] init]; XCTAssert([db open], @"open failed"); XCTAssert([db executeUpdate:@"create table foo (id integer primary key autoincrement, a numeric)"], @"create failed"); BOOL success; char insertedChar = 'A'; success = [db executeUpdateWithFormat:@"insert into foo (a) values (%c)", insertedChar]; XCTAssert(success, @"insert failed"); const char *retrievedChar = [[db stringForQuery:@"select a from foo where id = ?", @([db lastInsertRowId])] UTF8String]; XCTAssertEqual(insertedChar, retrievedChar[0], @"values don't match"); const char *insertedString = "baz"; success = [db executeUpdateWithFormat:@"insert into foo (a) values (%s)", insertedString]; XCTAssert(success, @"insert failed"); const char *retrievedString = [[db stringForQuery:@"select a from foo where id = ?", @([db lastInsertRowId])] UTF8String]; XCTAssert(strcmp(insertedString, retrievedString) == 0, @"values don't match"); int insertedInt = 42; success = [db executeUpdateWithFormat:@"insert into foo (a) values (%d)", insertedInt]; XCTAssert(success, @"insert failed"); int retrievedInt = [db intForQuery:@"select a from foo where id = ?", @([db lastInsertRowId])]; XCTAssertEqual(insertedInt, retrievedInt, @"values don't match"); char insertedUnsignedInt = 43; success = [db executeUpdateWithFormat:@"insert into foo (a) values (%u)", insertedUnsignedInt]; XCTAssert(success, @"insert failed"); char retrievedUnsignedInt = [db intForQuery:@"select a from foo where id = ?", @([db lastInsertRowId])]; XCTAssertEqual(insertedUnsignedInt, retrievedUnsignedInt, @"values don't match"); float insertedFloat = 44; success = [db executeUpdateWithFormat:@"insert into foo (a) values (%f)", insertedFloat]; XCTAssert(success, @"insert failed"); float retrievedFloat = [db doubleForQuery:@"select a from foo where id = ?", @([db lastInsertRowId])]; XCTAssertEqual(insertedFloat, retrievedFloat, @"values don't match"); unsigned long long insertedUnsignedLongLong = 45; success = [db executeUpdateWithFormat:@"insert into foo (a) values (%llu)", insertedUnsignedLongLong]; XCTAssert(success, @"insert failed"); unsigned long long retrievedUnsignedLongLong = [db longForQuery:@"select a from foo where id = ?", @([db lastInsertRowId])]; XCTAssertEqual(insertedUnsignedLongLong, retrievedUnsignedLongLong, @"values don't match"); } - (void)testStepError { FMDatabase *db = [[FMDatabase alloc] init]; XCTAssert([db open], @"open failed"); XCTAssert([db executeUpdate:@"create table foo (id integer primary key)"], @"create failed"); XCTAssert([db executeUpdate:@"insert into foo (id) values (?)" values:@[@1] error:nil], @"create failed"); NSError *error; BOOL success = [db executeUpdate:@"insert into foo (id) values (?)" values:@[@1] error:&error]; XCTAssertFalse(success, @"insert of duplicate key should have failed"); XCTAssertNotNil(error, @"error object should have been generated"); XCTAssertEqual(error.code, 19, @"error code 19 should have been generated"); } - (void)testCheckpoint { FMDatabase *db = [[FMDatabase alloc] init]; XCTAssertTrue([db open], @"open failed"); NSError *error = nil; int frameCount = 0; int checkpointCount = 0; [db checkpoint:FMDBCheckpointModeTruncate name:NULL logFrameCount:&frameCount checkpointCount:&checkpointCount error:&error]; // Verify that we're calling the checkpoint interface, which is a decent scope for this test, without going so far as to verify what checkpoint does XCTAssertEqual(frameCount, -1, @"frameCount should be -1 (means not using WAL mode) to verify that we're using the proper checkpoint interface"); XCTAssertEqual(checkpointCount, -1, @"checkpointCount should be -1 (means not using WAL mode) to verify that we're using the proper checkpoint interface"); } - (void)testImmediateTransaction { FMDatabase *db = [[FMDatabase alloc] init]; XCTAssertTrue([db open], @"open failed"); [db beginImmediateTransaction]; [db beginImmediateTransaction]; // Verify that beginImmediateTransaction behaves as advertised and starts a transaction XCTAssertEqualObjects([db lastError].localizedDescription, @"cannot start a transaction within a transaction"); } - (void)testOpenFailure { NSURL *tempURL = [NSURL fileURLWithPath:NSTemporaryDirectory()]; NSURL *fileURL1 = [tempURL URLByAppendingPathComponent:[[NSUUID UUID] UUIDString]]; NSURL *fileURL2 = [tempURL URLByAppendingPathComponent:[[NSUUID UUID] UUIDString]]; NSFileManager *manager = [NSFileManager defaultManager]; // ok, first create one database FMDatabase *db = [FMDatabase databaseWithURL:fileURL1]; BOOL success = [db open]; XCTAssert(success, @"Database not created correctly for purposes of test"); success = [db executeUpdate:@"create table if not exists foo (bar text)"]; XCTAssert(success, @"Table created correctly for purposes of test"); [db close]; // now, try to create open second database even though it doesn't exist db = [FMDatabase databaseWithURL:fileURL2]; success = [db openWithFlags:SQLITE_OPEN_READWRITE]; XCTAssert(!success, @"Opening second database file that doesn't exist should not have succeeded"); // OK, everything so far is fine, opening a db without CREATE option above should have failed, // but so fix the missing file issue and re-opening success = [manager copyItemAtURL:fileURL1 toURL:fileURL2 error:nil]; XCTAssert(success, @"Copying of db should have succeeded"); // now let's try opening it again success = [db openWithFlags:SQLITE_OPEN_READWRITE]; XCTAssert(success, @"Opening second database should now succeed"); // now let's try using it FMResultSet *rs = [db executeQuery:@"select * from foo"]; XCTAssertNotNil(rs, @"Should successfully be able to use re-opened database"); // let's clean up [rs close]; [db close]; [manager removeItemAtURL:fileURL1 error:nil]; [manager removeItemAtURL:fileURL2 error:nil]; } // These three utility methods used by `testTransient`, to illustrate dangers of SQLITE_STATIC - (BOOL)utility1ForTestTransient:(FMDatabase *)db withValue:(long)value { @autoreleasepool { NSString *string = [[NSString alloc] initWithFormat:@"value %@", @(value)]; return [db executeUpdate:@"INSERT INTO foo (bar) VALUES (?)", [string dataUsingEncoding:NSUTF8StringEncoding]]; } } - (FMResultSet *)utility2ForTestTransient:(FMDatabase *)db withValue:(long)value { @autoreleasepool { NSString *string = [[NSString alloc] initWithFormat:@"value %@", @(value)]; return [db executeQuery:@"SELECT * FROM foo WHERE bar = ?", [string dataUsingEncoding:NSUTF8StringEncoding]]; } } - (BOOL)utility3ForTestTransient:(FMResultSet *)rs withValue:(long)value { @autoreleasepool { NSString *string = [[NSString alloc] initWithFormat:@"xxxxx %@", @(value + 1)]; XCTAssertEqualObjects(string, @"xxxxx 43"); // Just to ensure the above isn't optimized out return [rs next]; } } - (void)testTransient { NSURL *tempURL = [NSURL fileURLWithPath:NSTemporaryDirectory()]; NSURL *fileURL = [tempURL URLByAppendingPathComponent:[[NSUUID UUID] UUIDString]]; NSFileManager *manager = [NSFileManager defaultManager]; // ok, first create one database FMDatabase *db = [FMDatabase databaseWithURL:fileURL]; BOOL success = [db open]; XCTAssert(success, @"Database not created correctly for purposes of test"); success = [db executeUpdate:@"CREATE TABLE IF NOT EXISTS foo (bar BLOB)"]; XCTAssert(success, @"Table created correctly for purposes of test"); long value = 42; success = [self utility1ForTestTransient:db withValue:value]; XCTAssert(success, @"INSERT failed"); FMResultSet *rs = [self utility2ForTestTransient:db withValue:value]; XCTAssert(rs, @"Creating SELECT failed"); // the following is the key test, namely if FMDB uses SQLITE_STATIC, the following may fail, but SQLITE_TRANSIENT ensures it will succeed success = [self utility3ForTestTransient:rs withValue:value]; XCTAssert(success, @"Performing SELECT failed"); // let's clean up [rs close]; [db close]; [manager removeItemAtURL:fileURL error:nil]; } - (void)testBindFailure { NSURL *tempURL = [NSURL fileURLWithPath:NSTemporaryDirectory()]; NSURL *fileURL = [tempURL URLByAppendingPathComponent:[[NSUUID UUID] UUIDString]]; NSFileManager *manager = [NSFileManager defaultManager]; // ok, first create one database FMDatabase *db = [FMDatabase databaseWithURL:fileURL]; BOOL success = [db open]; XCTAssert(success, @"Database not created correctly for purposes of test"); success = [db executeUpdate:@"CREATE TABLE IF NOT EXISTS foo (bar BLOB)"]; XCTAssert(success, @"Table created correctly for purposes of test"); NSUInteger limit = (NSUInteger)[db limitFor:SQLITE_LIMIT_LENGTH value:-1] + 1; NSLog(@"%lu", (unsigned long)limit); NSData *data = [NSMutableData dataWithLength:limit]; success = [db executeUpdate:@"INSERT INTO foo (bar) VALUES (?)", data]; XCTAssertFalse(success, @"Table created correctly for purposes of test"); // let's clean up [db close]; [manager removeItemAtURL:fileURL error:nil]; } - (void)testRebindingWithDictionary { NSURL *tempURL = [NSURL fileURLWithPath:NSTemporaryDirectory()]; NSURL *fileURL = [tempURL URLByAppendingPathComponent:[[NSUUID UUID] UUIDString]]; NSFileManager *manager = [NSFileManager defaultManager]; [manager removeItemAtURL:fileURL error:nil]; // ok, first create one database FMDatabase *db = [FMDatabase databaseWithURL:fileURL]; BOOL success = [db open]; XCTAssert(success, @"Database not created correctly for purposes of test"); success = [db executeUpdate:@"CREATE TABLE IF NOT EXISTS foo (id INTEGER PRIMARY KEY, bar TEXT)"]; XCTAssert(success, @"Table created correctly for purposes of test"); FMResultSet *rs = [db prepare:@"INSERT INTO foo (bar) VALUES (:bar)"]; XCTAssert(rs, @"INSERT statement not prepared %@", [db lastErrorMessage]); NSString *value1 = @"foo"; XCTAssert([rs bindWithDictionary:@{@"bar": value1}], @"Unable to bind"); XCTAssert([rs step], @"Performing query failed"); NSString *value2 = @"bar"; XCTAssert([rs bindWithDictionary:@{@"bar": value2}], @"Unable to bind"); XCTAssert([rs step], @"Performing query failed"); XCTAssert([rs bindWithDictionary:@{@"bar": value2}], @"Unable to bind"); XCTAssert([rs step], @"Performing query failed"); [rs close]; rs = [db prepare:@"SELECT bar FROM foo WHERE bar = :bar"]; XCTAssert([rs bindWithDictionary:@{@"bar": value1}], @"Unable to bind"); XCTAssert([rs next], @"No record found"); XCTAssertEqualObjects([rs stringForColumnIndex:0], value1); XCTAssertFalse([rs next], @"There should have been only one record"); XCTAssert([rs bindWithDictionary:@{@"bar": value2}], @"Unable to bind"); XCTAssert([rs next], @"No record found"); XCTAssertEqualObjects([rs stringForColumnIndex:0], value2); XCTAssert([rs next], @"No record found"); XCTAssertEqualObjects([rs stringForColumnIndex:0], value2); XCTAssertFalse([rs next], @"There should have been only two records"); // let's clean up [rs close]; [db close]; [manager removeItemAtURL:fileURL error:nil]; } - (void)testRebindingWithArray { NSURL *tempURL = [NSURL fileURLWithPath:NSTemporaryDirectory()]; NSURL *fileURL = [tempURL URLByAppendingPathComponent:[[NSUUID UUID] UUIDString]]; NSFileManager *manager = [NSFileManager defaultManager]; // ok, first create one database FMDatabase *db = [FMDatabase databaseWithURL:fileURL]; BOOL success = [db open]; XCTAssert(success, @"Database not created correctly for purposes of test"); success = [db executeUpdate:@"CREATE TABLE IF NOT EXISTS foo (id INTEGER PRIMARY KEY, bar TEXT)"]; XCTAssert(success, @"Table created correctly for purposes of test"); FMResultSet *rs = [db prepare:@"INSERT INTO foo (bar) VALUES (?)"]; XCTAssert(rs, @"INSERT statement not prepared %@", [db lastErrorMessage]); NSString *value1 = @"foo"; XCTAssert([rs bindWithArray:@[value1]], @"Unable to bind"); XCTAssert([rs step], @"Performing INSERT 1 failed"); NSString *value2 = @"bar"; XCTAssert([rs bindWithArray:@[value2]], @"Unable to bind"); XCTAssert([rs step], @"Performing INSERT 2 failed"); XCTAssert([rs bindWithArray:@[value2]], @"Unable to bind"); XCTAssert([rs step], @"Performing INSERT 2 failed"); [rs close]; rs = [db prepare:@"SELECT bar FROM foo WHERE bar = ?"]; XCTAssert([rs bindWithArray:@[value1]], @"Unable to bind"); XCTAssert([rs next], @"No record found"); XCTAssertEqualObjects([rs stringForColumnIndex:0], value1); XCTAssertFalse([rs next], @"There should have been only one record"); XCTAssert([rs bindWithArray:@[value2]], @"Unable to bind"); XCTAssert([rs next], @"No record found"); XCTAssertEqualObjects([rs stringForColumnIndex:0], value2); XCTAssert([rs next], @"No record found"); XCTAssertEqualObjects([rs stringForColumnIndex:0], value2); XCTAssertFalse([rs next], @"There should have been only two records"); // let's clean up [rs close]; [db close]; [manager removeItemAtURL:fileURL error:nil]; } @end ================================================ FILE: Tests/FMResultSetTests.m ================================================ // // FMResultSetTests.m // fmdb // // Created by Muralidharan,Roshan on 10/6/14. // // #import "FMDBTempDBTests.h" #import "FMDatabase.h" #if FMDB_SQLITE_STANDALONE #import #elif SQLCIPHER_CRYPTO #import #else #import #endif @interface FMResultSetTests : FMDBTempDBTests @end @implementation FMResultSetTests + (void)populateDatabase:(FMDatabase *)db { [db executeUpdate:@"create table test (a text, b text, c integer, d double, e double)"]; [db beginTransaction]; int i = 0; while (i++ < 20) { [db executeUpdate:@"insert into test (a, b, c, d, e) values (?, ?, ?, ?, ?)" , @"hi'", [NSString stringWithFormat:@"number %d", i], [NSNumber numberWithInt:i], [NSDate date], [NSNumber numberWithFloat:2.2f]]; } [db commit]; } - (void)testNextWithError_WithoutError { [self.db executeUpdate:@"CREATE TABLE testTable(key INTEGER PRIMARY KEY, value INTEGER)"]; [self.db executeUpdate:@"INSERT INTO testTable (key, value) VALUES (1, 2)"]; [self.db executeUpdate:@"INSERT INTO testTable (key, value) VALUES (2, 4)"]; FMResultSet *resultSet = [self.db executeQuery:@"SELECT * FROM testTable WHERE key=1"]; XCTAssertNotNil(resultSet); NSError *error; XCTAssertTrue([resultSet nextWithError:&error]); XCTAssertNil(error); XCTAssertFalse([resultSet nextWithError:&error]); XCTAssertNil(error); [resultSet close]; } - (void)testNextWithError_WithBusyError { [self.db executeUpdate:@"CREATE TABLE testTable(key INTEGER PRIMARY KEY, value INTEGER)"]; [self.db executeUpdate:@"INSERT INTO testTable (key, value) VALUES (1, 2)"]; [self.db executeUpdate:@"INSERT INTO testTable (key, value) VALUES (2, 4)"]; FMResultSet *resultSet = [self.db executeQuery:@"SELECT * FROM testTable WHERE key=1"]; XCTAssertNotNil(resultSet); FMDatabase *newDB = [FMDatabase databaseWithPath:self.databasePath]; [newDB open]; [newDB beginExclusiveTransaction]; NSError *error; XCTAssertFalse([resultSet nextWithError:&error]); [newDB commit]; XCTAssertEqual(error.code, SQLITE_BUSY, @"SQLITE_BUSY should be the last error"); [resultSet close]; } - (void)testNextWithError_WithMisuseError { [self.db executeUpdate:@"CREATE TABLE testTable(key INTEGER PRIMARY KEY, value INTEGER)"]; [self.db executeUpdate:@"INSERT INTO testTable (key, value) VALUES (1, 2)"]; [self.db executeUpdate:@"INSERT INTO testTable (key, value) VALUES (2, 4)"]; FMResultSet *resultSet = [self.db executeQuery:@"SELECT * FROM testTable WHERE key=9"]; XCTAssertNotNil(resultSet); XCTAssertFalse([resultSet next]); NSError *error; XCTAssertFalse([resultSet nextWithError:&error]); XCTAssertEqual(error.code, SQLITE_MISUSE, @"SQLITE_MISUSE should be the last error"); } - (void)testColumnTypes { [self.db executeUpdate:@"CREATE TABLE testTable (intValue INTEGER, floatValue FLOAT, textValue TEXT, blobValue BLOB)"]; NSString *sql = @"INSERT INTO testTable (intValue, floatValue, textValue, blobValue) VALUES (?, ?, ?, ?)"; NSError *error; NSData *data = [@"foo" dataUsingEncoding:NSUTF8StringEncoding]; NSData *zeroLengthData = [NSData data]; NSNull *null = [NSNull null]; [self.db executeUpdate:sql values:@[@42, @M_PI, @"test", data] error:&error]; [self.db executeUpdate:sql values:@[null, null, null, null] error:&error]; [self.db executeUpdate:sql values:@[null, null, null, zeroLengthData] error:&error]; FMResultSet *resultSet = [self.db executeQuery:@"SELECT * FROM testTable"]; XCTAssertNotNil(resultSet); XCTAssertTrue([resultSet next]); XCTAssertEqual([resultSet typeForColumn:@"intValue"], SqliteValueTypeInteger); XCTAssertEqual([resultSet typeForColumn:@"floatValue"], SqliteValueTypeFloat); XCTAssertEqual([resultSet typeForColumn:@"textValue"], SqliteValueTypeText); XCTAssertEqual([resultSet typeForColumn:@"blobValue"], SqliteValueTypeBlob); XCTAssertNotNil([resultSet dataForColumn:@"blobValue"]); XCTAssertTrue([resultSet next]); XCTAssertEqual([resultSet typeForColumn:@"intValue"], SqliteValueTypeNull); XCTAssertEqual([resultSet typeForColumn:@"floatValue"], SqliteValueTypeNull); XCTAssertEqual([resultSet typeForColumn:@"textValue"], SqliteValueTypeNull); XCTAssertEqual([resultSet typeForColumn:@"blobValue"], SqliteValueTypeNull); XCTAssertNil([resultSet dataForColumn:@"blobValue"]); XCTAssertTrue([resultSet next]); XCTAssertEqual([resultSet typeForColumn:@"blobValue"], SqliteValueTypeBlob); XCTAssertNil([resultSet dataForColumn:@"blobValue"]); [resultSet close]; } @end ================================================ FILE: Tests/Schemes/Tests.xcscheme ================================================ ================================================ FILE: Tests/Tests-Info.plist ================================================ CFBundleDevelopmentRegion en CFBundleExecutable ${EXECUTABLE_NAME} CFBundleIdentifier $(PRODUCT_BUNDLE_IDENTIFIER) CFBundleInfoDictionaryVersion 6.0 CFBundlePackageType BNDL CFBundleShortVersionString 1.0 CFBundleSignature ???? CFBundleVersion 1 ================================================ FILE: Tests/Tests-Prefix.pch ================================================ // // Prefix header // // The contents of this file are implicitly included at the beginning of every source file. // #ifdef __OBJC__ #import #import #import "FMDBTempDBTests.h" #endif ================================================ FILE: Tests/en.lproj/InfoPlist.strings ================================================ /* Localized versions of Info.plist keys */ ================================================ FILE: fmdb.1 ================================================ .\"Modified from man(1) of FreeBSD, the NetBSD mdoc.template, and mdoc.samples. .\"See Also: .\"man mdoc.samples for a complete listing of options .\"man mdoc for the short list of editing options .\"/usr/share/misc/mdoc.template .Dd 5/11/06 \" DATE .Dt fmdb 1 \" Program name and manual section number .Os Darwin .Sh NAME \" Section Header - required - don't modify .Nm fmdb, .\" The following lines are read in generating the apropos(man -k) database. Use only key .\" words here as the database is built based on the words here and in the .ND line. .Nm Other_name_for_same_program(), .Nm Yet another name for the same program. .\" Use .Nm macro to designate other names for the documented program. .Nd This line parsed for whatis database. .Sh SYNOPSIS \" Section Header - required - don't modify .Nm .Op Fl abcd \" [-abcd] .Op Fl a Ar path \" [-a path] .Op Ar file \" [file] .Op Ar \" [file ...] .Ar arg0 \" Underlined argument - use .Ar anywhere to underline arg2 ... \" Arguments .Sh DESCRIPTION \" Section Header - required - don't modify Use the .Nm macro to refer to your program throughout the man page like such: .Nm Underlining is accomplished with the .Ar macro like this: .Ar underlined text . .Pp \" Inserts a space A list of items with descriptions: .Bl -tag -width -indent \" Begins a tagged list .It item a \" Each item preceded by .It macro Description of item a .It item b Description of item b .El \" Ends the list .Pp A list of flags and their descriptions: .Bl -tag -width -indent \" Differs from above in tag removed .It Fl a \"-a flag as a list item Description of -a flag .It Fl b Description of -b flag .El \" Ends the list .Pp .\" .Sh ENVIRONMENT \" May not be needed .\" .Bl -tag -width "ENV_VAR_1" -indent \" ENV_VAR_1 is width of the string ENV_VAR_1 .\" .It Ev ENV_VAR_1 .\" Description of ENV_VAR_1 .\" .It Ev ENV_VAR_2 .\" Description of ENV_VAR_2 .\" .El .Sh FILES \" File used or created by the topic of the man page .Bl -tag -width "/Users/joeuser/Library/really_long_file_name" -compact .It Pa /usr/share/file_name FILE_1 description .It Pa /Users/joeuser/Library/really_long_file_name FILE_2 description .El \" Ends the list .\" .Sh DIAGNOSTICS \" May not be needed .\" .Bl -diag .\" .It Diagnostic Tag .\" Diagnostic informtion here. .\" .It Diagnostic Tag .\" Diagnostic informtion here. .\" .El .Sh SEE ALSO .\" List links in ascending order by section, alphabetically within a section. .\" Please do not reference files that do not exist without filing a bug report .Xr a 1 , .Xr b 1 , .Xr c 1 , .Xr a 2 , .Xr b 2 , .Xr a 3 , .Xr b 3 .\" .Sh BUGS \" Document known, unremedied bugs .\" .Sh HISTORY \" Document history if command behaves in a unique manner ================================================ FILE: fmdb.xcodeproj/project.pbxproj ================================================ // !$*UTF8*$! { archiveVersion = 1; classes = { }; objectVersion = 54; objects = { /* Begin PBXBuildFile section */ 2CD2425B1FCC09CA00479FDE /* FMDatabase.m in Sources */ = {isa = PBXBuildFile; fileRef = CCC24EBB0A13E34D00A6D3E3 /* FMDatabase.m */; }; 2CD2425C1FCC09CA00479FDE /* FMResultSet.m in Sources */ = {isa = PBXBuildFile; fileRef = CCC24EC00A13E34D00A6D3E3 /* FMResultSet.m */; }; 2CD2425D1FCC09CA00479FDE /* FMDatabaseQueue.m in Sources */ = {isa = PBXBuildFile; fileRef = CC47A00E148581E9002CCDAB /* FMDatabaseQueue.m */; }; 2CD2425E1FCC09CA00479FDE /* FMDatabaseAdditions.m in Sources */ = {isa = PBXBuildFile; fileRef = CC50F2CB0DF9183600E4AAAE /* FMDatabaseAdditions.m */; }; 2CD2425F1FCC09CA00479FDE /* FMDatabasePool.m in Sources */ = {isa = PBXBuildFile; fileRef = CC9E4EB813B31188005F9210 /* FMDatabasePool.m */; }; 2CD242611FCC09CA00479FDE /* libsqlite3.tbd in Frameworks */ = {isa = PBXBuildFile; fileRef = 83C73F2B1C326CF400FFC730 /* libsqlite3.tbd */; }; 2CD242631FCC09CA00479FDE /* FMDB.h in Headers */ = {isa = PBXBuildFile; fileRef = 8314AF3218CD73D600EC0E25 /* FMDB.h */; settings = {ATTRIBUTES = (Public, ); }; }; 2CD242641FCC09CA00479FDE /* FMDatabase.h in Headers */ = {isa = PBXBuildFile; fileRef = CCC24EBA0A13E34D00A6D3E3 /* FMDatabase.h */; settings = {ATTRIBUTES = (Public, ); }; }; 2CD242651FCC09CA00479FDE /* FMResultSet.h in Headers */ = {isa = PBXBuildFile; fileRef = CCC24EBF0A13E34D00A6D3E3 /* FMResultSet.h */; settings = {ATTRIBUTES = (Public, ); }; }; 2CD242661FCC09CA00479FDE /* FMDatabaseQueue.h in Headers */ = {isa = PBXBuildFile; fileRef = CC47A00D148581E9002CCDAB /* FMDatabaseQueue.h */; settings = {ATTRIBUTES = (Public, ); }; }; 2CD242671FCC09CA00479FDE /* FMDatabaseAdditions.h in Headers */ = {isa = PBXBuildFile; fileRef = CC50F2CC0DF9183600E4AAAE /* FMDatabaseAdditions.h */; settings = {ATTRIBUTES = (Public, ); }; }; 2CD242681FCC09CA00479FDE /* FMDatabasePool.h in Headers */ = {isa = PBXBuildFile; fileRef = CC9E4EB713B31188005F9210 /* FMDatabasePool.h */; settings = {ATTRIBUTES = (Public, ); }; }; 40A145FE1BE5759400E5D35E /* FMDatabase.h in Headers */ = {isa = PBXBuildFile; fileRef = CCC24EBA0A13E34D00A6D3E3 /* FMDatabase.h */; settings = {ATTRIBUTES = (Public, ); }; }; 40A146001BE575D000E5D35E /* FMDatabase.h in Headers */ = {isa = PBXBuildFile; fileRef = CCC24EBA0A13E34D00A6D3E3 /* FMDatabase.h */; settings = {ATTRIBUTES = (Public, ); }; }; 40A146011BE575D600E5D35E /* FMResultSet.h in Headers */ = {isa = PBXBuildFile; fileRef = CCC24EBF0A13E34D00A6D3E3 /* FMResultSet.h */; settings = {ATTRIBUTES = (Public, ); }; }; 40A146021BE575DD00E5D35E /* FMDatabaseQueue.h in Headers */ = {isa = PBXBuildFile; fileRef = CC47A00D148581E9002CCDAB /* FMDatabaseQueue.h */; settings = {ATTRIBUTES = (Public, ); }; }; 40A146031BE575E400E5D35E /* FMDatabaseAdditions.h in Headers */ = {isa = PBXBuildFile; fileRef = CC50F2CC0DF9183600E4AAAE /* FMDatabaseAdditions.h */; settings = {ATTRIBUTES = (Public, ); }; }; 40A146041BE575EB00E5D35E /* FMDatabasePool.h in Headers */ = {isa = PBXBuildFile; fileRef = CC9E4EB713B31188005F9210 /* FMDatabasePool.h */; settings = {ATTRIBUTES = (Public, ); }; }; 40A146051BE6999800E5D35E /* FMDB.h in Headers */ = {isa = PBXBuildFile; fileRef = 8314AF3218CD73D600EC0E25 /* FMDB.h */; settings = {ATTRIBUTES = (Public, ); }; }; 4C740718215084110003C17E /* InfoPlist.strings in Resources */ = {isa = PBXBuildFile; fileRef = 4C74070E215083C40003C17E /* InfoPlist.strings */; }; 4C74071A2150845D0003C17E /* FMDatabaseTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 4C740716215083C40003C17E /* FMDatabaseTests.m */; }; 4C74071B2150845D0003C17E /* FMDatabaseAdditionsTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 4C74070A215083C40003C17E /* FMDatabaseAdditionsTests.m */; }; 4C74071C2150845D0003C17E /* FMDatabaseQueueTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 4C740711215083C40003C17E /* FMDatabaseQueueTests.m */; }; 4C74071D2150845D0003C17E /* FMDatabasePoolTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 4C74070D215083C40003C17E /* FMDatabasePoolTests.m */; }; 4C74071E2150845D0003C17E /* FMDatabaseFTS3Tests.m in Sources */ = {isa = PBXBuildFile; fileRef = 4C740713215083C40003C17E /* FMDatabaseFTS3Tests.m */; }; 4C74071F2150845D0003C17E /* FMDatabaseFTS3WithModuleNameTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 4C740712215083C40003C17E /* FMDatabaseFTS3WithModuleNameTests.m */; }; 4C7407202150845D0003C17E /* FMDBTempDBTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 4C74070C215083C40003C17E /* FMDBTempDBTests.m */; }; 4C7407212150845D0003C17E /* FMResultSetTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 4C740710215083C40003C17E /* FMResultSetTests.m */; }; 621721B21892BFE30006691F /* FMDatabase.m in Sources */ = {isa = PBXBuildFile; fileRef = CCC24EBB0A13E34D00A6D3E3 /* FMDatabase.m */; }; 621721B31892BFE30006691F /* FMResultSet.m in Sources */ = {isa = PBXBuildFile; fileRef = CCC24EC00A13E34D00A6D3E3 /* FMResultSet.m */; }; 621721B41892BFE30006691F /* FMDatabaseQueue.m in Sources */ = {isa = PBXBuildFile; fileRef = CC47A00E148581E9002CCDAB /* FMDatabaseQueue.m */; }; 621721B51892BFE30006691F /* FMDatabaseAdditions.m in Sources */ = {isa = PBXBuildFile; fileRef = CC50F2CB0DF9183600E4AAAE /* FMDatabaseAdditions.m */; }; 621721B61892BFE30006691F /* FMDatabasePool.m in Sources */ = {isa = PBXBuildFile; fileRef = CC9E4EB813B31188005F9210 /* FMDatabasePool.m */; }; 6290CBB7188FE836009790F8 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6290CBB6188FE836009790F8 /* Foundation.framework */; }; 8314AF3318CD73D600EC0E25 /* FMDB.h in Headers */ = {isa = PBXBuildFile; fileRef = 8314AF3218CD73D600EC0E25 /* FMDB.h */; settings = {ATTRIBUTES = (Public, ); }; }; 83C73F131C326B9400FFC730 /* FMDatabase.m in Sources */ = {isa = PBXBuildFile; fileRef = CCC24EBB0A13E34D00A6D3E3 /* FMDatabase.m */; }; 83C73F141C326B9400FFC730 /* FMResultSet.m in Sources */ = {isa = PBXBuildFile; fileRef = CCC24EC00A13E34D00A6D3E3 /* FMResultSet.m */; }; 83C73F151C326B9400FFC730 /* FMDatabaseQueue.m in Sources */ = {isa = PBXBuildFile; fileRef = CC47A00E148581E9002CCDAB /* FMDatabaseQueue.m */; }; 83C73F161C326B9400FFC730 /* FMDatabaseAdditions.m in Sources */ = {isa = PBXBuildFile; fileRef = CC50F2CB0DF9183600E4AAAE /* FMDatabaseAdditions.m */; }; 83C73F171C326B9400FFC730 /* FMDatabasePool.m in Sources */ = {isa = PBXBuildFile; fileRef = CC9E4EB813B31188005F9210 /* FMDatabasePool.m */; }; 83C73F181C326BAB00FFC730 /* FMDB.h in Headers */ = {isa = PBXBuildFile; fileRef = 8314AF3218CD73D600EC0E25 /* FMDB.h */; settings = {ATTRIBUTES = (Public, ); }; }; 83C73F191C326BAB00FFC730 /* FMDatabase.h in Headers */ = {isa = PBXBuildFile; fileRef = CCC24EBA0A13E34D00A6D3E3 /* FMDatabase.h */; settings = {ATTRIBUTES = (Public, ); }; }; 83C73F1A1C326BAB00FFC730 /* FMResultSet.h in Headers */ = {isa = PBXBuildFile; fileRef = CCC24EBF0A13E34D00A6D3E3 /* FMResultSet.h */; settings = {ATTRIBUTES = (Public, ); }; }; 83C73F1B1C326BAB00FFC730 /* FMDatabaseQueue.h in Headers */ = {isa = PBXBuildFile; fileRef = CC47A00D148581E9002CCDAB /* FMDatabaseQueue.h */; settings = {ATTRIBUTES = (Public, ); }; }; 83C73F1C1C326BAB00FFC730 /* FMDatabaseAdditions.h in Headers */ = {isa = PBXBuildFile; fileRef = CC50F2CC0DF9183600E4AAAE /* FMDatabaseAdditions.h */; settings = {ATTRIBUTES = (Public, ); }; }; 83C73F1D1C326BAB00FFC730 /* FMDatabasePool.h in Headers */ = {isa = PBXBuildFile; fileRef = CC9E4EB713B31188005F9210 /* FMDatabasePool.h */; settings = {ATTRIBUTES = (Public, ); }; }; 83C73F1E1C326BC100FFC730 /* FMDatabase.m in Sources */ = {isa = PBXBuildFile; fileRef = CCC24EBB0A13E34D00A6D3E3 /* FMDatabase.m */; }; 83C73F1F1C326BC100FFC730 /* FMResultSet.m in Sources */ = {isa = PBXBuildFile; fileRef = CCC24EC00A13E34D00A6D3E3 /* FMResultSet.m */; }; 83C73F201C326BC100FFC730 /* FMDatabaseQueue.m in Sources */ = {isa = PBXBuildFile; fileRef = CC47A00E148581E9002CCDAB /* FMDatabaseQueue.m */; }; 83C73F211C326BC100FFC730 /* FMDatabaseAdditions.m in Sources */ = {isa = PBXBuildFile; fileRef = CC50F2CB0DF9183600E4AAAE /* FMDatabaseAdditions.m */; }; 83C73F221C326BC100FFC730 /* FMDatabasePool.m in Sources */ = {isa = PBXBuildFile; fileRef = CC9E4EB813B31188005F9210 /* FMDatabasePool.m */; }; 83C73F231C326BD600FFC730 /* FMDB.h in Headers */ = {isa = PBXBuildFile; fileRef = 8314AF3218CD73D600EC0E25 /* FMDB.h */; settings = {ATTRIBUTES = (Public, ); }; }; 83C73F241C326BD600FFC730 /* FMDatabase.h in Headers */ = {isa = PBXBuildFile; fileRef = CCC24EBA0A13E34D00A6D3E3 /* FMDatabase.h */; settings = {ATTRIBUTES = (Public, ); }; }; 83C73F251C326BD600FFC730 /* FMResultSet.h in Headers */ = {isa = PBXBuildFile; fileRef = CCC24EBF0A13E34D00A6D3E3 /* FMResultSet.h */; settings = {ATTRIBUTES = (Public, ); }; }; 83C73F261C326BD600FFC730 /* FMDatabaseQueue.h in Headers */ = {isa = PBXBuildFile; fileRef = CC47A00D148581E9002CCDAB /* FMDatabaseQueue.h */; settings = {ATTRIBUTES = (Public, ); }; }; 83C73F271C326BD600FFC730 /* FMDatabaseAdditions.h in Headers */ = {isa = PBXBuildFile; fileRef = CC50F2CC0DF9183600E4AAAE /* FMDatabaseAdditions.h */; settings = {ATTRIBUTES = (Public, ); }; }; 83C73F281C326BD600FFC730 /* FMDatabasePool.h in Headers */ = {isa = PBXBuildFile; fileRef = CC9E4EB713B31188005F9210 /* FMDatabasePool.h */; settings = {ATTRIBUTES = (Public, ); }; }; 83C73F2A1C326CE800FFC730 /* libsqlite3.tbd in Frameworks */ = {isa = PBXBuildFile; fileRef = 83C73F291C326CE800FFC730 /* libsqlite3.tbd */; }; 83C73F2C1C326CF400FFC730 /* libsqlite3.tbd in Frameworks */ = {isa = PBXBuildFile; fileRef = 83C73F2B1C326CF400FFC730 /* libsqlite3.tbd */; }; 83C73F2F1C326D2F00FFC730 /* FMDB.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 83C73F0B1C326ADA00FFC730 /* FMDB.framework */; }; 8DD76F9C0486AA7600D96B5E /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 08FB779EFE84155DC02AAC07 /* Foundation.framework */; }; 8DD76F9F0486AA7600D96B5E /* fmdb.1 in CopyFiles */ = {isa = PBXBuildFile; fileRef = C6859EA3029092ED04C91782 /* fmdb.1 */; }; A08C6BA72AF0F5B1004F3F28 /* FMDatabase.m in Sources */ = {isa = PBXBuildFile; fileRef = CCC24EBB0A13E34D00A6D3E3 /* FMDatabase.m */; }; A08C6BA82AF0F5B1004F3F28 /* FMResultSet.m in Sources */ = {isa = PBXBuildFile; fileRef = CCC24EC00A13E34D00A6D3E3 /* FMResultSet.m */; }; A08C6BA92AF0F5B1004F3F28 /* FMDatabaseQueue.m in Sources */ = {isa = PBXBuildFile; fileRef = CC47A00E148581E9002CCDAB /* FMDatabaseQueue.m */; }; A08C6BAA2AF0F5B1004F3F28 /* FMDatabaseAdditions.m in Sources */ = {isa = PBXBuildFile; fileRef = CC50F2CB0DF9183600E4AAAE /* FMDatabaseAdditions.m */; }; A08C6BAB2AF0F5B1004F3F28 /* FMDatabasePool.m in Sources */ = {isa = PBXBuildFile; fileRef = CC9E4EB813B31188005F9210 /* FMDatabasePool.m */; }; A08C6BAD2AF0F5B1004F3F28 /* libsqlite3.tbd in Frameworks */ = {isa = PBXBuildFile; fileRef = 83C73F2B1C326CF400FFC730 /* libsqlite3.tbd */; }; A08C6BAF2AF0F5B1004F3F28 /* FMDB.h in Headers */ = {isa = PBXBuildFile; fileRef = 8314AF3218CD73D600EC0E25 /* FMDB.h */; settings = {ATTRIBUTES = (Public, ); }; }; A08C6BB02AF0F5B1004F3F28 /* FMDatabase.h in Headers */ = {isa = PBXBuildFile; fileRef = CCC24EBA0A13E34D00A6D3E3 /* FMDatabase.h */; settings = {ATTRIBUTES = (Public, ); }; }; A08C6BB12AF0F5B1004F3F28 /* FMResultSet.h in Headers */ = {isa = PBXBuildFile; fileRef = CCC24EBF0A13E34D00A6D3E3 /* FMResultSet.h */; settings = {ATTRIBUTES = (Public, ); }; }; A08C6BB22AF0F5B1004F3F28 /* FMDatabaseQueue.h in Headers */ = {isa = PBXBuildFile; fileRef = CC47A00D148581E9002CCDAB /* FMDatabaseQueue.h */; settings = {ATTRIBUTES = (Public, ); }; }; A08C6BB32AF0F5B1004F3F28 /* FMDatabaseAdditions.h in Headers */ = {isa = PBXBuildFile; fileRef = CC50F2CC0DF9183600E4AAAE /* FMDatabaseAdditions.h */; settings = {ATTRIBUTES = (Public, ); }; }; A08C6BB42AF0F5B1004F3F28 /* FMDatabasePool.h in Headers */ = {isa = PBXBuildFile; fileRef = CC9E4EB713B31188005F9210 /* FMDatabasePool.h */; settings = {ATTRIBUTES = (Public, ); }; }; BF5D041918416BB2008C5AA9 /* XCTest.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = BF5D041818416BB2008C5AA9 /* XCTest.framework */; }; BFC152B118417F0D00605DF7 /* FMDatabaseAdditions.m in Sources */ = {isa = PBXBuildFile; fileRef = CC50F2CB0DF9183600E4AAAE /* FMDatabaseAdditions.m */; }; CC47A00F148581E9002CCDAB /* FMDatabaseQueue.h in Headers */ = {isa = PBXBuildFile; fileRef = CC47A00D148581E9002CCDAB /* FMDatabaseQueue.h */; settings = {ATTRIBUTES = (Public, ); }; }; CC47A010148581E9002CCDAB /* FMDatabaseQueue.m in Sources */ = {isa = PBXBuildFile; fileRef = CC47A00E148581E9002CCDAB /* FMDatabaseQueue.m */; }; CC47A011148581E9002CCDAB /* FMDatabaseQueue.m in Sources */ = {isa = PBXBuildFile; fileRef = CC47A00E148581E9002CCDAB /* FMDatabaseQueue.m */; }; CC50F2CD0DF9183600E4AAAE /* FMDatabaseAdditions.m in Sources */ = {isa = PBXBuildFile; fileRef = CC50F2CB0DF9183600E4AAAE /* FMDatabaseAdditions.m */; }; CC7CE42818F5C04600938264 /* FMDatabase+InMemoryOnDiskIO.m in Sources */ = {isa = PBXBuildFile; fileRef = CC7CE42718F5C04600938264 /* FMDatabase+InMemoryOnDiskIO.m */; }; CC9E4EB913B31188005F9210 /* FMDatabasePool.m in Sources */ = {isa = PBXBuildFile; fileRef = CC9E4EB813B31188005F9210 /* FMDatabasePool.m */; }; CC9E4EBA13B31188005F9210 /* FMDatabasePool.h in Headers */ = {isa = PBXBuildFile; fileRef = CC9E4EB713B31188005F9210 /* FMDatabasePool.h */; settings = {ATTRIBUTES = (Public, ); }; }; CC9E4EBB13B31188005F9210 /* FMDatabasePool.m in Sources */ = {isa = PBXBuildFile; fileRef = CC9E4EB813B31188005F9210 /* FMDatabasePool.m */; }; CCA66A2D19C0CB1900EFDAC1 /* FMDatabase+FTS3.m in Sources */ = {isa = PBXBuildFile; fileRef = CCA66A2919C0CB1900EFDAC1 /* FMDatabase+FTS3.m */; }; CCA66A2E19C0CB1900EFDAC1 /* FMDatabase+FTS3.m in Sources */ = {isa = PBXBuildFile; fileRef = CCA66A2919C0CB1900EFDAC1 /* FMDatabase+FTS3.m */; }; CCA66A2F19C0CB1900EFDAC1 /* FMTokenizers.m in Sources */ = {isa = PBXBuildFile; fileRef = CCA66A2B19C0CB1900EFDAC1 /* FMTokenizers.m */; }; CCA66A3019C0CB1900EFDAC1 /* FMTokenizers.m in Sources */ = {isa = PBXBuildFile; fileRef = CCA66A2B19C0CB1900EFDAC1 /* FMTokenizers.m */; }; CCBE26C113B3BA8C006F6C37 /* AppKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = CCBE26C013B3BA8C006F6C37 /* AppKit.framework */; }; CCBEBDAC0DF5DE1A003DDD08 /* libsqlite3.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = CCBEBDAB0DF5DE1A003DDD08 /* libsqlite3.dylib */; }; CCC24EC20A13E34D00A6D3E3 /* FMDatabase.m in Sources */ = {isa = PBXBuildFile; fileRef = CCC24EBB0A13E34D00A6D3E3 /* FMDatabase.m */; }; CCC24EC50A13E34D00A6D3E3 /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = CCC24EBE0A13E34D00A6D3E3 /* main.m */; }; CCC24EC70A13E34D00A6D3E3 /* FMResultSet.m in Sources */ = {isa = PBXBuildFile; fileRef = CCC24EC00A13E34D00A6D3E3 /* FMResultSet.m */; }; D040ADBB2D5E317B00A1E6B3 /* PrivacyInfo.xcprivacy in Resources */ = {isa = PBXBuildFile; fileRef = CCF9B96E2B1539EE0023EB4C /* PrivacyInfo.xcprivacy */; }; EE42910512B42FBC0088BD94 /* FMDatabaseAdditions.m in Sources */ = {isa = PBXBuildFile; fileRef = CC50F2CB0DF9183600E4AAAE /* FMDatabaseAdditions.m */; }; EE42910612B42FC30088BD94 /* FMDatabaseAdditions.h in Headers */ = {isa = PBXBuildFile; fileRef = CC50F2CC0DF9183600E4AAAE /* FMDatabaseAdditions.h */; settings = {ATTRIBUTES = (Public, ); }; }; EE42910812B42FCC0088BD94 /* FMDatabase.m in Sources */ = {isa = PBXBuildFile; fileRef = CCC24EBB0A13E34D00A6D3E3 /* FMDatabase.m */; }; EE42910912B42FD00088BD94 /* FMResultSet.h in Headers */ = {isa = PBXBuildFile; fileRef = CCC24EBF0A13E34D00A6D3E3 /* FMResultSet.h */; settings = {ATTRIBUTES = (Public, ); }; }; EE42910A12B42FD20088BD94 /* FMResultSet.m in Sources */ = {isa = PBXBuildFile; fileRef = CCC24EC00A13E34D00A6D3E3 /* FMResultSet.m */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ 83C73F2D1C326D2000FFC730 /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = 08FB7793FE84155DC02AAC07 /* Project object */; proxyType = 1; remoteGlobalIDString = 83C73F0A1C326ADA00FFC730; remoteInfo = "FMDB MacOS"; }; /* End PBXContainerItemProxy section */ /* Begin PBXCopyFilesBuildPhase section */ 6290CBB3188FE836009790F8 /* CopyFiles */ = { isa = PBXCopyFilesBuildPhase; buildActionMask = 2147483647; dstPath = "include/$(PRODUCT_NAME)"; dstSubfolderSpec = 16; files = ( ); runOnlyForDeploymentPostprocessing = 0; }; 8DD76F9E0486AA7600D96B5E /* CopyFiles */ = { isa = PBXCopyFilesBuildPhase; buildActionMask = 8; dstPath = /usr/share/man/man1/; dstSubfolderSpec = 0; files = ( 8DD76F9F0486AA7600D96B5E /* fmdb.1 in CopyFiles */, ); runOnlyForDeploymentPostprocessing = 1; }; /* End PBXCopyFilesBuildPhase section */ /* Begin PBXFileReference section */ 08FB779EFE84155DC02AAC07 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = /System/Library/Frameworks/Foundation.framework; sourceTree = ""; }; 2CD2426D1FCC09CA00479FDE /* FMDB.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = FMDB.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 32A70AAB03705E1F00C91783 /* fmdb_Prefix.pch */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = fmdb_Prefix.pch; path = src/sample/fmdb_Prefix.pch; sourceTree = SOURCE_ROOT; }; 4C74070A215083C40003C17E /* FMDatabaseAdditionsTests.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = FMDatabaseAdditionsTests.m; sourceTree = ""; }; 4C74070B215083C40003C17E /* Tests-Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = "Tests-Info.plist"; sourceTree = ""; }; 4C74070C215083C40003C17E /* FMDBTempDBTests.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = FMDBTempDBTests.m; sourceTree = ""; }; 4C74070D215083C40003C17E /* FMDatabasePoolTests.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = FMDatabasePoolTests.m; sourceTree = ""; }; 4C74070F215083C40003C17E /* Base */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = Base; path = Base.lproj/InfoPlist.strings; sourceTree = ""; }; 4C740710215083C40003C17E /* FMResultSetTests.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = FMResultSetTests.m; sourceTree = ""; }; 4C740711215083C40003C17E /* FMDatabaseQueueTests.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = FMDatabaseQueueTests.m; sourceTree = ""; }; 4C740712215083C40003C17E /* FMDatabaseFTS3WithModuleNameTests.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = FMDatabaseFTS3WithModuleNameTests.m; sourceTree = ""; }; 4C740713215083C40003C17E /* FMDatabaseFTS3Tests.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = FMDatabaseFTS3Tests.m; sourceTree = ""; }; 4C740714215083C40003C17E /* Tests-Prefix.pch */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Tests-Prefix.pch"; sourceTree = ""; }; 4C740715215083C40003C17E /* FMDBTempDBTests.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = FMDBTempDBTests.h; sourceTree = ""; }; 4C740716215083C40003C17E /* FMDatabaseTests.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = FMDatabaseTests.m; sourceTree = ""; }; 4C740719215084250003C17E /* en */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = en; path = en.lproj/InfoPlist.strings; sourceTree = ""; }; 6290CBB5188FE836009790F8 /* libFMDB-IOS.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = "libFMDB-IOS.a"; sourceTree = BUILT_PRODUCTS_DIR; }; 6290CBB6188FE836009790F8 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = System/Library/Frameworks/Foundation.framework; sourceTree = SDKROOT; }; 6290CBC6188FE837009790F8 /* UIKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = UIKit.framework; path = Library/Frameworks/UIKit.framework; sourceTree = DEVELOPER_DIR; }; 8314AF3218CD73D600EC0E25 /* FMDB.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = FMDB.h; path = src/fmdb/FMDB.h; sourceTree = ""; }; 831DE6FD175B7C9C001F7317 /* README.markdown */ = {isa = PBXFileReference; lastKnownFileType = text; path = README.markdown; sourceTree = ""; }; 83C73EFE1C326AB000FFC730 /* FMDB.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = FMDB.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 83C73F0B1C326ADA00FFC730 /* FMDB.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = FMDB.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 83C73F291C326CE800FFC730 /* libsqlite3.tbd */ = {isa = PBXFileReference; lastKnownFileType = "sourcecode.text-based-dylib-definition"; name = libsqlite3.tbd; path = usr/lib/libsqlite3.tbd; sourceTree = SDKROOT; }; 83C73F2B1C326CF400FFC730 /* libsqlite3.tbd */ = {isa = PBXFileReference; lastKnownFileType = "sourcecode.text-based-dylib-definition"; name = libsqlite3.tbd; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS9.2.sdk/usr/lib/libsqlite3.tbd; sourceTree = DEVELOPER_DIR; }; 83C73F301C326D8600FFC730 /* FMDB.podspec */ = {isa = PBXFileReference; lastKnownFileType = text; path = FMDB.podspec; sourceTree = ""; }; 83C73F311C326FA600FFC730 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; name = Info.plist; path = src/fmdb/Info.plist; sourceTree = ""; }; 8DD76FA10486AA7600D96B5E /* fmdb */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = fmdb; sourceTree = BUILT_PRODUCTS_DIR; }; A08C6BB92AF0F5B1004F3F28 /* FMDB xrOS.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = "FMDB xrOS.framework"; sourceTree = BUILT_PRODUCTS_DIR; }; A08C6BBA2AF0F5B1004F3F28 /* FMDB iOS copy-Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; name = "FMDB iOS copy-Info.plist"; path = "/Users/mohamed.abida/Documents/workspace/fmdb/FMDB iOS copy-Info.plist"; sourceTree = ""; }; BF5D041618416BB2008C5AA9 /* Tests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = Tests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; BF5D041818416BB2008C5AA9 /* XCTest.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = XCTest.framework; path = Library/Frameworks/XCTest.framework; sourceTree = DEVELOPER_DIR; }; C6859EA3029092ED04C91782 /* fmdb.1 */ = {isa = PBXFileReference; lastKnownFileType = text.man; path = fmdb.1; sourceTree = ""; }; CC47A00D148581E9002CCDAB /* FMDatabaseQueue.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = FMDatabaseQueue.h; path = src/fmdb/FMDatabaseQueue.h; sourceTree = SOURCE_ROOT; }; CC47A00E148581E9002CCDAB /* FMDatabaseQueue.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = FMDatabaseQueue.m; path = src/fmdb/FMDatabaseQueue.m; sourceTree = SOURCE_ROOT; }; CC50F2CB0DF9183600E4AAAE /* FMDatabaseAdditions.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = FMDatabaseAdditions.m; path = src/fmdb/FMDatabaseAdditions.m; sourceTree = SOURCE_ROOT; }; CC50F2CC0DF9183600E4AAAE /* FMDatabaseAdditions.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = FMDatabaseAdditions.h; path = src/fmdb/FMDatabaseAdditions.h; sourceTree = SOURCE_ROOT; }; CC7CE42618F5C04600938264 /* FMDatabase+InMemoryOnDiskIO.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = "FMDatabase+InMemoryOnDiskIO.h"; path = "src/extra/InMemoryOnDiskIO/FMDatabase+InMemoryOnDiskIO.h"; sourceTree = ""; }; CC7CE42718F5C04600938264 /* FMDatabase+InMemoryOnDiskIO.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = "FMDatabase+InMemoryOnDiskIO.m"; path = "src/extra/InMemoryOnDiskIO/FMDatabase+InMemoryOnDiskIO.m"; sourceTree = ""; }; CC8C138A0E3135C400FBE1E7 /* CHANGES_AND_TODO_LIST.txt */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = CHANGES_AND_TODO_LIST.txt; sourceTree = ""; }; CC8C138B0E3135C400FBE1E7 /* LICENSE.txt */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = LICENSE.txt; sourceTree = ""; }; CC8C138C0E3135C400FBE1E7 /* CONTRIBUTORS.txt */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = CONTRIBUTORS.txt; sourceTree = ""; }; CC9E4EB713B31188005F9210 /* FMDatabasePool.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = FMDatabasePool.h; path = src/fmdb/FMDatabasePool.h; sourceTree = SOURCE_ROOT; }; CC9E4EB813B31188005F9210 /* FMDatabasePool.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = FMDatabasePool.m; path = src/fmdb/FMDatabasePool.m; sourceTree = SOURCE_ROOT; }; CCA66A2819C0CB1900EFDAC1 /* FMDatabase+FTS3.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = "FMDatabase+FTS3.h"; path = "src/extra/fts3/FMDatabase+FTS3.h"; sourceTree = ""; }; CCA66A2919C0CB1900EFDAC1 /* FMDatabase+FTS3.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = "FMDatabase+FTS3.m"; path = "src/extra/fts3/FMDatabase+FTS3.m"; sourceTree = ""; }; CCA66A2A19C0CB1900EFDAC1 /* FMTokenizers.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = FMTokenizers.h; path = src/extra/fts3/FMTokenizers.h; sourceTree = ""; }; CCA66A2B19C0CB1900EFDAC1 /* FMTokenizers.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = FMTokenizers.m; path = src/extra/fts3/FMTokenizers.m; sourceTree = ""; }; CCA66A2C19C0CB1900EFDAC1 /* fts3_tokenizer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = fts3_tokenizer.h; path = src/extra/fts3/fts3_tokenizer.h; sourceTree = ""; }; CCBE26C013B3BA8C006F6C37 /* AppKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = AppKit.framework; path = /System/Library/Frameworks/AppKit.framework; sourceTree = ""; }; CCBEBDAB0DF5DE1A003DDD08 /* libsqlite3.dylib */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; name = libsqlite3.dylib; path = /usr/lib/libsqlite3.dylib; sourceTree = ""; }; CCC24EBA0A13E34D00A6D3E3 /* FMDatabase.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = FMDatabase.h; path = src/fmdb/FMDatabase.h; sourceTree = SOURCE_ROOT; }; CCC24EBB0A13E34D00A6D3E3 /* FMDatabase.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = FMDatabase.m; path = src/fmdb/FMDatabase.m; sourceTree = SOURCE_ROOT; }; CCC24EBE0A13E34D00A6D3E3 /* main.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = main.m; path = src/sample/main.m; sourceTree = SOURCE_ROOT; }; CCC24EBF0A13E34D00A6D3E3 /* FMResultSet.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = FMResultSet.h; path = src/fmdb/FMResultSet.h; sourceTree = SOURCE_ROOT; }; CCC24EC00A13E34D00A6D3E3 /* FMResultSet.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = FMResultSet.m; path = src/fmdb/FMResultSet.m; sourceTree = SOURCE_ROOT; }; CCF9B96E2B1539EE0023EB4C /* PrivacyInfo.xcprivacy */ = {isa = PBXFileReference; lastKnownFileType = text.xml; name = PrivacyInfo.xcprivacy; path = privacy/PrivacyInfo.xcprivacy; sourceTree = ""; }; EE4290EF12B42F870088BD94 /* libFMDB.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libFMDB.a; sourceTree = BUILT_PRODUCTS_DIR; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ 2CD242601FCC09CA00479FDE /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( 2CD242611FCC09CA00479FDE /* libsqlite3.tbd in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; 6290CBB2188FE836009790F8 /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( 6290CBB7188FE836009790F8 /* Foundation.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; 83C73EFA1C326AB000FFC730 /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( 83C73F2C1C326CF400FFC730 /* libsqlite3.tbd in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; 83C73F071C326ADA00FFC730 /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( 83C73F2A1C326CE800FFC730 /* libsqlite3.tbd in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; 8DD76F9B0486AA7600D96B5E /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( 8DD76F9C0486AA7600D96B5E /* Foundation.framework in Frameworks */, CCBEBDAC0DF5DE1A003DDD08 /* libsqlite3.dylib in Frameworks */, CCBE26C113B3BA8C006F6C37 /* AppKit.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; A08C6BAC2AF0F5B1004F3F28 /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( A08C6BAD2AF0F5B1004F3F28 /* libsqlite3.tbd in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; BF5D041318416BB2008C5AA9 /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( 83C73F2F1C326D2F00FFC730 /* FMDB.framework in Frameworks */, BF5D041918416BB2008C5AA9 /* XCTest.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; EE4290ED12B42F870088BD94 /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ 08FB7794FE84155DC02AAC07 /* fmdb */ = { isa = PBXGroup; children = ( CCF9B96E2B1539EE0023EB4C /* PrivacyInfo.xcprivacy */, 83C73F301C326D8600FFC730 /* FMDB.podspec */, C6859EA2029092E104C91782 /* Documentation */, 08FB7795FE84155DC02AAC07 /* Source */, 08FB779DFE84155DC02AAC07 /* External Frameworks and Libraries */, 4C740707215083C40003C17E /* Tests */, BF5D041718416BB2008C5AA9 /* Frameworks */, 1AB674ADFE9D54B511CA2CBB /* Products */, A08C6BBA2AF0F5B1004F3F28 /* FMDB iOS copy-Info.plist */, ); name = fmdb; sourceTree = ""; }; 08FB7795FE84155DC02AAC07 /* Source */ = { isa = PBXGroup; children = ( 8314AF3018CD737D00EC0E25 /* fmdb */, CC7CE42518F5C02E00938264 /* optional extras */, 8314AF3118CD739500EC0E25 /* sample */, ); name = Source; sourceTree = ""; }; 08FB779DFE84155DC02AAC07 /* External Frameworks and Libraries */ = { isa = PBXGroup; children = ( CCBEBDAB0DF5DE1A003DDD08 /* libsqlite3.dylib */, 08FB779EFE84155DC02AAC07 /* Foundation.framework */, CCBE26C013B3BA8C006F6C37 /* AppKit.framework */, ); name = "External Frameworks and Libraries"; sourceTree = ""; }; 1AB674ADFE9D54B511CA2CBB /* Products */ = { isa = PBXGroup; children = ( 8DD76FA10486AA7600D96B5E /* fmdb */, EE4290EF12B42F870088BD94 /* libFMDB.a */, BF5D041618416BB2008C5AA9 /* Tests.xctest */, 6290CBB5188FE836009790F8 /* libFMDB-IOS.a */, 83C73EFE1C326AB000FFC730 /* FMDB.framework */, 83C73F0B1C326ADA00FFC730 /* FMDB.framework */, 2CD2426D1FCC09CA00479FDE /* FMDB.framework */, A08C6BB92AF0F5B1004F3F28 /* FMDB xrOS.framework */, ); name = Products; sourceTree = ""; }; 4C740707215083C40003C17E /* Tests */ = { isa = PBXGroup; children = ( 4C740716215083C40003C17E /* FMDatabaseTests.m */, 4C74070A215083C40003C17E /* FMDatabaseAdditionsTests.m */, 4C740711215083C40003C17E /* FMDatabaseQueueTests.m */, 4C74070D215083C40003C17E /* FMDatabasePoolTests.m */, 4C740713215083C40003C17E /* FMDatabaseFTS3Tests.m */, 4C740712215083C40003C17E /* FMDatabaseFTS3WithModuleNameTests.m */, 4C740715215083C40003C17E /* FMDBTempDBTests.h */, 4C74070C215083C40003C17E /* FMDBTempDBTests.m */, 4C740710215083C40003C17E /* FMResultSetTests.m */, 4C740717215083CF0003C17E /* Supporting Files */, ); path = Tests; sourceTree = ""; }; 4C740717215083CF0003C17E /* Supporting Files */ = { isa = PBXGroup; children = ( 4C74070E215083C40003C17E /* InfoPlist.strings */, 4C74070B215083C40003C17E /* Tests-Info.plist */, 4C740714215083C40003C17E /* Tests-Prefix.pch */, ); name = "Supporting Files"; sourceTree = ""; }; 6767F81519AD13C300887DBC /* fts3 */ = { isa = PBXGroup; children = ( CCA66A2819C0CB1900EFDAC1 /* FMDatabase+FTS3.h */, CCA66A2919C0CB1900EFDAC1 /* FMDatabase+FTS3.m */, CCA66A2A19C0CB1900EFDAC1 /* FMTokenizers.h */, CCA66A2B19C0CB1900EFDAC1 /* FMTokenizers.m */, CCA66A2C19C0CB1900EFDAC1 /* fts3_tokenizer.h */, ); name = fts3; sourceTree = ""; }; 8314AF3018CD737D00EC0E25 /* fmdb */ = { isa = PBXGroup; children = ( 8314AF3218CD73D600EC0E25 /* FMDB.h */, CCC24EBA0A13E34D00A6D3E3 /* FMDatabase.h */, CCC24EBB0A13E34D00A6D3E3 /* FMDatabase.m */, CCC24EBF0A13E34D00A6D3E3 /* FMResultSet.h */, CCC24EC00A13E34D00A6D3E3 /* FMResultSet.m */, CC47A00D148581E9002CCDAB /* FMDatabaseQueue.h */, CC47A00E148581E9002CCDAB /* FMDatabaseQueue.m */, CC50F2CC0DF9183600E4AAAE /* FMDatabaseAdditions.h */, CC50F2CB0DF9183600E4AAAE /* FMDatabaseAdditions.m */, CC9E4EB713B31188005F9210 /* FMDatabasePool.h */, CC9E4EB813B31188005F9210 /* FMDatabasePool.m */, 83C73F311C326FA600FFC730 /* Info.plist */, ); name = fmdb; sourceTree = ""; }; 8314AF3118CD739500EC0E25 /* sample */ = { isa = PBXGroup; children = ( CCC24EBE0A13E34D00A6D3E3 /* main.m */, 32A70AAB03705E1F00C91783 /* fmdb_Prefix.pch */, ); name = sample; sourceTree = ""; }; 832F502519EC4CA20087DCBF /* InMemoryOnDiskIO */ = { isa = PBXGroup; children = ( CC7CE42618F5C04600938264 /* FMDatabase+InMemoryOnDiskIO.h */, CC7CE42718F5C04600938264 /* FMDatabase+InMemoryOnDiskIO.m */, ); name = InMemoryOnDiskIO; sourceTree = ""; }; BF5D041718416BB2008C5AA9 /* Frameworks */ = { isa = PBXGroup; children = ( 83C73F2B1C326CF400FFC730 /* libsqlite3.tbd */, 83C73F291C326CE800FFC730 /* libsqlite3.tbd */, BF5D041818416BB2008C5AA9 /* XCTest.framework */, 6290CBB6188FE836009790F8 /* Foundation.framework */, 6290CBC6188FE837009790F8 /* UIKit.framework */, ); name = Frameworks; sourceTree = ""; }; C6859EA2029092E104C91782 /* Documentation */ = { isa = PBXGroup; children = ( 831DE6FD175B7C9C001F7317 /* README.markdown */, CC8C138B0E3135C400FBE1E7 /* LICENSE.txt */, CC8C138A0E3135C400FBE1E7 /* CHANGES_AND_TODO_LIST.txt */, CC8C138C0E3135C400FBE1E7 /* CONTRIBUTORS.txt */, C6859EA3029092ED04C91782 /* fmdb.1 */, ); name = Documentation; sourceTree = ""; }; CC7CE42518F5C02E00938264 /* optional extras */ = { isa = PBXGroup; children = ( 832F502519EC4CA20087DCBF /* InMemoryOnDiskIO */, 6767F81519AD13C300887DBC /* fts3 */, ); name = "optional extras"; sourceTree = ""; }; /* End PBXGroup section */ /* Begin PBXHeadersBuildPhase section */ 2CD242621FCC09CA00479FDE /* Headers */ = { isa = PBXHeadersBuildPhase; buildActionMask = 2147483647; files = ( 2CD242631FCC09CA00479FDE /* FMDB.h in Headers */, 2CD242641FCC09CA00479FDE /* FMDatabase.h in Headers */, 2CD242651FCC09CA00479FDE /* FMResultSet.h in Headers */, 2CD242661FCC09CA00479FDE /* FMDatabaseQueue.h in Headers */, 2CD242671FCC09CA00479FDE /* FMDatabaseAdditions.h in Headers */, 2CD242681FCC09CA00479FDE /* FMDatabasePool.h in Headers */, ); runOnlyForDeploymentPostprocessing = 0; }; 40A145FF1BE575BD00E5D35E /* Headers */ = { isa = PBXHeadersBuildPhase; buildActionMask = 2147483647; files = ( 40A146001BE575D000E5D35E /* FMDatabase.h in Headers */, 40A146011BE575D600E5D35E /* FMResultSet.h in Headers */, 40A146041BE575EB00E5D35E /* FMDatabasePool.h in Headers */, 40A146051BE6999800E5D35E /* FMDB.h in Headers */, 40A146031BE575E400E5D35E /* FMDatabaseAdditions.h in Headers */, 40A146021BE575DD00E5D35E /* FMDatabaseQueue.h in Headers */, ); runOnlyForDeploymentPostprocessing = 0; }; 83C73EFB1C326AB000FFC730 /* Headers */ = { isa = PBXHeadersBuildPhase; buildActionMask = 2147483647; files = ( 83C73F181C326BAB00FFC730 /* FMDB.h in Headers */, 83C73F191C326BAB00FFC730 /* FMDatabase.h in Headers */, 83C73F1A1C326BAB00FFC730 /* FMResultSet.h in Headers */, 83C73F1B1C326BAB00FFC730 /* FMDatabaseQueue.h in Headers */, 83C73F1C1C326BAB00FFC730 /* FMDatabaseAdditions.h in Headers */, 83C73F1D1C326BAB00FFC730 /* FMDatabasePool.h in Headers */, ); runOnlyForDeploymentPostprocessing = 0; }; 83C73F081C326ADA00FFC730 /* Headers */ = { isa = PBXHeadersBuildPhase; buildActionMask = 2147483647; files = ( 83C73F231C326BD600FFC730 /* FMDB.h in Headers */, 83C73F241C326BD600FFC730 /* FMDatabase.h in Headers */, 83C73F251C326BD600FFC730 /* FMResultSet.h in Headers */, 83C73F261C326BD600FFC730 /* FMDatabaseQueue.h in Headers */, 83C73F271C326BD600FFC730 /* FMDatabaseAdditions.h in Headers */, 83C73F281C326BD600FFC730 /* FMDatabasePool.h in Headers */, ); runOnlyForDeploymentPostprocessing = 0; }; A08C6BAE2AF0F5B1004F3F28 /* Headers */ = { isa = PBXHeadersBuildPhase; buildActionMask = 2147483647; files = ( A08C6BAF2AF0F5B1004F3F28 /* FMDB.h in Headers */, A08C6BB02AF0F5B1004F3F28 /* FMDatabase.h in Headers */, A08C6BB12AF0F5B1004F3F28 /* FMResultSet.h in Headers */, A08C6BB22AF0F5B1004F3F28 /* FMDatabaseQueue.h in Headers */, A08C6BB32AF0F5B1004F3F28 /* FMDatabaseAdditions.h in Headers */, A08C6BB42AF0F5B1004F3F28 /* FMDatabasePool.h in Headers */, ); runOnlyForDeploymentPostprocessing = 0; }; EE4290EB12B42F870088BD94 /* Headers */ = { isa = PBXHeadersBuildPhase; buildActionMask = 2147483647; files = ( EE42910612B42FC30088BD94 /* FMDatabaseAdditions.h in Headers */, EE42910912B42FD00088BD94 /* FMResultSet.h in Headers */, 40A145FE1BE5759400E5D35E /* FMDatabase.h in Headers */, 8314AF3318CD73D600EC0E25 /* FMDB.h in Headers */, CC9E4EBA13B31188005F9210 /* FMDatabasePool.h in Headers */, CC47A00F148581E9002CCDAB /* FMDatabaseQueue.h in Headers */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXHeadersBuildPhase section */ /* Begin PBXNativeTarget section */ 2CD242591FCC09CA00479FDE /* FMDB watchOS */ = { isa = PBXNativeTarget; buildConfigurationList = 2CD2426A1FCC09CA00479FDE /* Build configuration list for PBXNativeTarget "FMDB watchOS" */; buildPhases = ( 2CD2425A1FCC09CA00479FDE /* Sources */, 2CD242601FCC09CA00479FDE /* Frameworks */, 2CD242621FCC09CA00479FDE /* Headers */, 2CD242691FCC09CA00479FDE /* Resources */, ); buildRules = ( ); dependencies = ( ); name = "FMDB watchOS"; productName = "FMDB iOS"; productReference = 2CD2426D1FCC09CA00479FDE /* FMDB.framework */; productType = "com.apple.product-type.framework"; }; 6290CBB4188FE836009790F8 /* FMDB-IOS */ = { isa = PBXNativeTarget; buildConfigurationList = 6290CBD7188FE837009790F8 /* Build configuration list for PBXNativeTarget "FMDB-IOS" */; buildPhases = ( 6290CBB1188FE836009790F8 /* Sources */, 6290CBB2188FE836009790F8 /* Frameworks */, 6290CBB3188FE836009790F8 /* CopyFiles */, 40A145FF1BE575BD00E5D35E /* Headers */, ); buildRules = ( ); dependencies = ( ); name = "FMDB-IOS"; productName = "FMDB-IOS"; productReference = 6290CBB5188FE836009790F8 /* libFMDB-IOS.a */; productType = "com.apple.product-type.library.static"; }; 83C73EFD1C326AB000FFC730 /* FMDB iOS */ = { isa = PBXNativeTarget; buildConfigurationList = 83C73F051C326AB000FFC730 /* Build configuration list for PBXNativeTarget "FMDB iOS" */; buildPhases = ( 83C73EF91C326AB000FFC730 /* Sources */, 83C73EFA1C326AB000FFC730 /* Frameworks */, 83C73EFB1C326AB000FFC730 /* Headers */, 83C73EFC1C326AB000FFC730 /* Resources */, ); buildRules = ( ); dependencies = ( ); name = "FMDB iOS"; productName = "FMDB iOS"; productReference = 83C73EFE1C326AB000FFC730 /* FMDB.framework */; productType = "com.apple.product-type.framework"; }; 83C73F0A1C326ADA00FFC730 /* FMDB MacOS */ = { isa = PBXNativeTarget; buildConfigurationList = 83C73F101C326ADB00FFC730 /* Build configuration list for PBXNativeTarget "FMDB MacOS" */; buildPhases = ( 83C73F061C326ADA00FFC730 /* Sources */, 83C73F071C326ADA00FFC730 /* Frameworks */, 83C73F081C326ADA00FFC730 /* Headers */, 83C73F091C326ADA00FFC730 /* Resources */, ); buildRules = ( ); dependencies = ( ); name = "FMDB MacOS"; productName = "FMDB MacOS"; productReference = 83C73F0B1C326ADA00FFC730 /* FMDB.framework */; productType = "com.apple.product-type.framework"; }; 8DD76F960486AA7600D96B5E /* fmdb */ = { isa = PBXNativeTarget; buildConfigurationList = 1DEB927408733DD40010E9CD /* Build configuration list for PBXNativeTarget "fmdb" */; buildPhases = ( 8DD76F990486AA7600D96B5E /* Sources */, 8DD76F9B0486AA7600D96B5E /* Frameworks */, 8DD76F9E0486AA7600D96B5E /* CopyFiles */, ); buildRules = ( ); dependencies = ( ); name = fmdb; productInstallPath = "$(HOME)/bin"; productName = fmdb; productReference = 8DD76FA10486AA7600D96B5E /* fmdb */; productType = "com.apple.product-type.tool"; }; A08C6BA52AF0F5B1004F3F28 /* FMDB xrOS */ = { isa = PBXNativeTarget; buildConfigurationList = A08C6BB62AF0F5B1004F3F28 /* Build configuration list for PBXNativeTarget "FMDB xrOS" */; buildPhases = ( A08C6BA62AF0F5B1004F3F28 /* Sources */, A08C6BAC2AF0F5B1004F3F28 /* Frameworks */, A08C6BAE2AF0F5B1004F3F28 /* Headers */, A08C6BB52AF0F5B1004F3F28 /* Resources */, ); buildRules = ( ); dependencies = ( ); name = "FMDB xrOS"; productName = "FMDB iOS"; productReference = A08C6BB92AF0F5B1004F3F28 /* FMDB xrOS.framework */; productType = "com.apple.product-type.framework"; }; BF5D041518416BB2008C5AA9 /* Tests */ = { isa = PBXNativeTarget; buildConfigurationList = BF5D042718416BB2008C5AA9 /* Build configuration list for PBXNativeTarget "Tests" */; buildPhases = ( BF5D041218416BB2008C5AA9 /* Sources */, BF5D041318416BB2008C5AA9 /* Frameworks */, BF5D041418416BB2008C5AA9 /* Resources */, ); buildRules = ( ); dependencies = ( 83C73F2E1C326D2000FFC730 /* PBXTargetDependency */, ); name = Tests; productName = Tests; productReference = BF5D041618416BB2008C5AA9 /* Tests.xctest */; productType = "com.apple.product-type.bundle.unit-test"; }; EE4290EE12B42F870088BD94 /* FMDB */ = { isa = PBXNativeTarget; buildConfigurationList = EE42910012B42FA00088BD94 /* Build configuration list for PBXNativeTarget "FMDB" */; buildPhases = ( EE4290EB12B42F870088BD94 /* Headers */, EE4290EC12B42F870088BD94 /* Sources */, EE4290ED12B42F870088BD94 /* Frameworks */, ); buildRules = ( ); dependencies = ( ); name = FMDB; productName = FMDB; productReference = EE4290EF12B42F870088BD94 /* libFMDB.a */; productType = "com.apple.product-type.library.static"; }; /* End PBXNativeTarget section */ /* Begin PBXProject section */ 08FB7793FE84155DC02AAC07 /* Project object */ = { isa = PBXProject; attributes = { LastUpgradeCheck = 1240; TargetAttributes = { 83C73EFD1C326AB000FFC730 = { CreatedOnToolsVersion = 7.2; }; 83C73F0A1C326ADA00FFC730 = { CreatedOnToolsVersion = 7.2; }; BF5D041518416BB2008C5AA9 = { TestTargetID = EE4290EE12B42F870088BD94; }; }; }; buildConfigurationList = 1DEB927808733DD40010E9CD /* Build configuration list for PBXProject "fmdb" */; compatibilityVersion = "Xcode 12.0"; developmentRegion = en; hasScannedForEncodings = 1; knownRegions = ( Base, en, ); mainGroup = 08FB7794FE84155DC02AAC07 /* fmdb */; projectDirPath = ""; projectRoot = ""; targets = ( 8DD76F960486AA7600D96B5E /* fmdb */, EE4290EE12B42F870088BD94 /* FMDB */, BF5D041518416BB2008C5AA9 /* Tests */, 6290CBB4188FE836009790F8 /* FMDB-IOS */, 83C73EFD1C326AB000FFC730 /* FMDB iOS */, 83C73F0A1C326ADA00FFC730 /* FMDB MacOS */, 2CD242591FCC09CA00479FDE /* FMDB watchOS */, A08C6BA52AF0F5B1004F3F28 /* FMDB xrOS */, ); }; /* End PBXProject section */ /* Begin PBXResourcesBuildPhase section */ 2CD242691FCC09CA00479FDE /* Resources */ = { isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( ); runOnlyForDeploymentPostprocessing = 0; }; 83C73EFC1C326AB000FFC730 /* Resources */ = { isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( D040ADBB2D5E317B00A1E6B3 /* PrivacyInfo.xcprivacy in Resources */, ); runOnlyForDeploymentPostprocessing = 0; }; 83C73F091C326ADA00FFC730 /* Resources */ = { isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( ); runOnlyForDeploymentPostprocessing = 0; }; A08C6BB52AF0F5B1004F3F28 /* Resources */ = { isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( ); runOnlyForDeploymentPostprocessing = 0; }; BF5D041418416BB2008C5AA9 /* Resources */ = { isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( 4C740718215084110003C17E /* InfoPlist.strings in Resources */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXResourcesBuildPhase section */ /* Begin PBXSourcesBuildPhase section */ 2CD2425A1FCC09CA00479FDE /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( 2CD2425B1FCC09CA00479FDE /* FMDatabase.m in Sources */, 2CD2425C1FCC09CA00479FDE /* FMResultSet.m in Sources */, 2CD2425D1FCC09CA00479FDE /* FMDatabaseQueue.m in Sources */, 2CD2425E1FCC09CA00479FDE /* FMDatabaseAdditions.m in Sources */, 2CD2425F1FCC09CA00479FDE /* FMDatabasePool.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; 6290CBB1188FE836009790F8 /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( 621721B31892BFE30006691F /* FMResultSet.m in Sources */, 621721B21892BFE30006691F /* FMDatabase.m in Sources */, 621721B61892BFE30006691F /* FMDatabasePool.m in Sources */, 621721B41892BFE30006691F /* FMDatabaseQueue.m in Sources */, 621721B51892BFE30006691F /* FMDatabaseAdditions.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; 83C73EF91C326AB000FFC730 /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( 83C73F131C326B9400FFC730 /* FMDatabase.m in Sources */, 83C73F141C326B9400FFC730 /* FMResultSet.m in Sources */, 83C73F151C326B9400FFC730 /* FMDatabaseQueue.m in Sources */, 83C73F161C326B9400FFC730 /* FMDatabaseAdditions.m in Sources */, 83C73F171C326B9400FFC730 /* FMDatabasePool.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; 83C73F061C326ADA00FFC730 /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( 83C73F1E1C326BC100FFC730 /* FMDatabase.m in Sources */, 83C73F1F1C326BC100FFC730 /* FMResultSet.m in Sources */, 83C73F201C326BC100FFC730 /* FMDatabaseQueue.m in Sources */, 83C73F211C326BC100FFC730 /* FMDatabaseAdditions.m in Sources */, 83C73F221C326BC100FFC730 /* FMDatabasePool.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; 8DD76F990486AA7600D96B5E /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( CCC24EC20A13E34D00A6D3E3 /* FMDatabase.m in Sources */, CCA66A2F19C0CB1900EFDAC1 /* FMTokenizers.m in Sources */, CCC24EC50A13E34D00A6D3E3 /* main.m in Sources */, CCC24EC70A13E34D00A6D3E3 /* FMResultSet.m in Sources */, CC7CE42818F5C04600938264 /* FMDatabase+InMemoryOnDiskIO.m in Sources */, CC50F2CD0DF9183600E4AAAE /* FMDatabaseAdditions.m in Sources */, CC9E4EB913B31188005F9210 /* FMDatabasePool.m in Sources */, CC47A010148581E9002CCDAB /* FMDatabaseQueue.m in Sources */, CCA66A2D19C0CB1900EFDAC1 /* FMDatabase+FTS3.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; A08C6BA62AF0F5B1004F3F28 /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( A08C6BA72AF0F5B1004F3F28 /* FMDatabase.m in Sources */, A08C6BA82AF0F5B1004F3F28 /* FMResultSet.m in Sources */, A08C6BA92AF0F5B1004F3F28 /* FMDatabaseQueue.m in Sources */, A08C6BAA2AF0F5B1004F3F28 /* FMDatabaseAdditions.m in Sources */, A08C6BAB2AF0F5B1004F3F28 /* FMDatabasePool.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; BF5D041218416BB2008C5AA9 /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( 4C74071D2150845D0003C17E /* FMDatabasePoolTests.m in Sources */, BFC152B118417F0D00605DF7 /* FMDatabaseAdditions.m in Sources */, 4C7407212150845D0003C17E /* FMResultSetTests.m in Sources */, 4C74071F2150845D0003C17E /* FMDatabaseFTS3WithModuleNameTests.m in Sources */, 4C74071B2150845D0003C17E /* FMDatabaseAdditionsTests.m in Sources */, 4C7407202150845D0003C17E /* FMDBTempDBTests.m in Sources */, 4C74071E2150845D0003C17E /* FMDatabaseFTS3Tests.m in Sources */, CCA66A3019C0CB1900EFDAC1 /* FMTokenizers.m in Sources */, CCA66A2E19C0CB1900EFDAC1 /* FMDatabase+FTS3.m in Sources */, 4C74071A2150845D0003C17E /* FMDatabaseTests.m in Sources */, 4C74071C2150845D0003C17E /* FMDatabaseQueueTests.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; EE4290EC12B42F870088BD94 /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( EE42910812B42FCC0088BD94 /* FMDatabase.m in Sources */, EE42910512B42FBC0088BD94 /* FMDatabaseAdditions.m in Sources */, EE42910A12B42FD20088BD94 /* FMResultSet.m in Sources */, CC9E4EBB13B31188005F9210 /* FMDatabasePool.m in Sources */, CC47A011148581E9002CCDAB /* FMDatabaseQueue.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXSourcesBuildPhase section */ /* Begin PBXTargetDependency section */ 83C73F2E1C326D2000FFC730 /* PBXTargetDependency */ = { isa = PBXTargetDependency; target = 83C73F0A1C326ADA00FFC730 /* FMDB MacOS */; targetProxy = 83C73F2D1C326D2000FFC730 /* PBXContainerItemProxy */; }; /* End PBXTargetDependency section */ /* Begin PBXVariantGroup section */ 4C74070E215083C40003C17E /* InfoPlist.strings */ = { isa = PBXVariantGroup; children = ( 4C74070F215083C40003C17E /* Base */, 4C740719215084250003C17E /* en */, ); name = InfoPlist.strings; sourceTree = ""; }; /* End PBXVariantGroup section */ /* Begin XCBuildConfiguration section */ 1DEB927508733DD40010E9CD /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CLANG_ENABLE_OBJC_ARC = YES; CLANG_WARN_DOCUMENTATION_COMMENTS = YES; CLANG_WARN_IMPLICIT_SIGN_CONVERSION = YES; CLANG_WARN_OBJC_IMPLICIT_ATOMIC_PROPERTIES = YES; CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; CLANG_WARN_SUSPICIOUS_IMPLICIT_CONVERSION = YES; CODE_SIGN_IDENTITY = "-"; COPY_PHASE_STRIP = NO; GCC_DYNAMIC_NO_PIC = NO; GCC_OPTIMIZATION_LEVEL = 0; GCC_PRECOMPILE_PREFIX_HEADER = YES; GCC_PREFIX_HEADER = src/sample/fmdb_Prefix.pch; GCC_TREAT_WARNINGS_AS_ERRORS = YES; GCC_WARN_SHADOW = YES; GCC_WARN_UNUSED_PARAMETER = NO; INSTALL_PATH = "$(HOME)/bin"; LIBRARY_SEARCH_PATHS = "$(LIBRARY_SEARCH_PATHS)"; MACOSX_DEPLOYMENT_TARGET = 10.13; PRODUCT_NAME = fmdb; }; name = Debug; }; 1DEB927608733DD40010E9CD /* Release */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CLANG_ENABLE_OBJC_ARC = YES; CLANG_WARN_DOCUMENTATION_COMMENTS = YES; CLANG_WARN_IMPLICIT_SIGN_CONVERSION = YES; CLANG_WARN_OBJC_IMPLICIT_ATOMIC_PROPERTIES = YES; CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; CLANG_WARN_SUSPICIOUS_IMPLICIT_CONVERSION = YES; CODE_SIGN_IDENTITY = "-"; GCC_GENERATE_DEBUGGING_SYMBOLS = NO; GCC_MODEL_TUNING = G5; GCC_PRECOMPILE_PREFIX_HEADER = YES; GCC_PREFIX_HEADER = src/sample/fmdb_Prefix.pch; GCC_TREAT_WARNINGS_AS_ERRORS = YES; GCC_WARN_SHADOW = YES; GCC_WARN_UNUSED_PARAMETER = NO; INSTALL_PATH = "$(HOME)/bin"; LIBRARY_SEARCH_PATHS = "$(LIBRARY_SEARCH_PATHS)"; MACOSX_DEPLOYMENT_TARGET = 10.13; PRODUCT_NAME = fmdb; }; name = Release; }; 1DEB927908733DD40010E9CD /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES; CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; CLANG_WARN_BOOL_CONVERSION = YES; CLANG_WARN_COMMA = YES; CLANG_WARN_CONSTANT_CONVERSION = YES; CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; CLANG_WARN_OBJC_EXPLICIT_OWNERSHIP_TYPE = YES; CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; CLANG_WARN_STRICT_PROTOTYPES = YES; CLANG_WARN_SUSPICIOUS_MOVE = YES; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; ENABLE_STRICT_OBJC_MSGSEND = YES; ENABLE_TESTABILITY = YES; GCC_C_LANGUAGE_STANDARD = c99; GCC_NO_COMMON_BLOCKS = YES; GCC_VERSION = com.apple.compilers.llvm.clang.1_0; GCC_WARN_64_TO_32_BIT_CONVERSION = YES; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_MISSING_PARENTHESES = YES; GCC_WARN_PEDANTIC = YES; GCC_WARN_SIGN_COMPARE = YES; GCC_WARN_UNDECLARED_SELECTOR = YES; GCC_WARN_UNINITIALIZED_AUTOS = YES; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_PARAMETER = YES; GCC_WARN_UNUSED_VARIABLE = YES; IPHONEOS_DEPLOYMENT_TARGET = 9.0; MACOSX_DEPLOYMENT_TARGET = 10.11; ONLY_ACTIVE_ARCH = YES; SDKROOT = macosx; WATCHOS_DEPLOYMENT_TARGET = 2.0; XROS_DEPLOYMENT_TARGET = 1.0; }; name = Debug; }; 1DEB927A08733DD40010E9CD /* Release */ = { isa = XCBuildConfiguration; buildSettings = { CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES; CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; CLANG_WARN_BOOL_CONVERSION = YES; CLANG_WARN_COMMA = YES; CLANG_WARN_CONSTANT_CONVERSION = YES; CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; CLANG_WARN_OBJC_EXPLICIT_OWNERSHIP_TYPE = YES; CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; CLANG_WARN_STRICT_PROTOTYPES = YES; CLANG_WARN_SUSPICIOUS_MOVE = YES; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; ENABLE_STRICT_OBJC_MSGSEND = YES; GCC_C_LANGUAGE_STANDARD = c99; GCC_NO_COMMON_BLOCKS = YES; GCC_VERSION = com.apple.compilers.llvm.clang.1_0; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNDECLARED_SELECTOR = YES; GCC_WARN_UNINITIALIZED_AUTOS = YES; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_PARAMETER = YES; GCC_WARN_UNUSED_VARIABLE = YES; IPHONEOS_DEPLOYMENT_TARGET = 9.0; MACOSX_DEPLOYMENT_TARGET = 10.11; SDKROOT = macosx; WATCHOS_DEPLOYMENT_TARGET = 2.0; XROS_DEPLOYMENT_TARGET = 1.0; }; name = Release; }; 2CD2426B1FCC09CA00479FDE /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; APPLICATION_EXTENSION_API_ONLY = YES; CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_OBJC_ARC = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_DOCUMENTATION_COMMENTS = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; CODE_SIGN_IDENTITY = ""; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; COPY_PHASE_STRIP = NO; CURRENT_PROJECT_VERSION = 1; DEBUG_INFORMATION_FORMAT = dwarf; DEFINES_MODULE = YES; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_DYNAMIC_NO_PIC = NO; GCC_OPTIMIZATION_LEVEL = 0; GCC_PREPROCESSOR_DEFINITIONS = ( "DEBUG=1", "$(inherited)", ); GCC_TREAT_WARNINGS_AS_ERRORS = YES; GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; INFOPLIST_FILE = src/fmdb/Info.plist; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", "@loader_path/Frameworks", ); MTL_ENABLE_DEBUG_INFO = YES; PRODUCT_BUNDLE_IDENTIFIER = "com.flyingmeat.FMDB-watchOS"; PRODUCT_NAME = FMDB; SDKROOT = watchos; SKIP_INSTALL = YES; VERSIONING_SYSTEM = "apple-generic"; VERSION_INFO_PREFIX = ""; }; name = Debug; }; 2CD2426C1FCC09CA00479FDE /* Release */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; APPLICATION_EXTENSION_API_ONLY = YES; CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_OBJC_ARC = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_DOCUMENTATION_COMMENTS = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; CODE_SIGN_IDENTITY = ""; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; COPY_PHASE_STRIP = NO; CURRENT_PROJECT_VERSION = 1; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; DEFINES_MODULE = YES; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; ENABLE_NS_ASSERTIONS = NO; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_TREAT_WARNINGS_AS_ERRORS = YES; GCC_WARN_64_TO_32_BIT_CONVERSION = YES; GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; INFOPLIST_FILE = src/fmdb/Info.plist; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", "@loader_path/Frameworks", ); MTL_ENABLE_DEBUG_INFO = NO; PRODUCT_BUNDLE_IDENTIFIER = "com.flyingmeat.FMDB-watchOS"; PRODUCT_NAME = FMDB; SDKROOT = watchos; SKIP_INSTALL = YES; VALIDATE_PRODUCT = YES; VERSIONING_SYSTEM = "apple-generic"; VERSION_INFO_PREFIX = ""; }; name = Release; }; 6290CBD3188FE837009790F8 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_OBJC_ARC = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_DOCUMENTATION_COMMENTS = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; COPY_PHASE_STRIP = NO; DSTROOT = /tmp/FMDB_IOS.dst; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_DYNAMIC_NO_PIC = NO; GCC_OPTIMIZATION_LEVEL = 0; GCC_PRECOMPILE_PREFIX_HEADER = YES; GCC_PREPROCESSOR_DEFINITIONS = ( "DEBUG=1", "$(inherited)", ); GCC_SYMBOLS_PRIVATE_EXTERN = NO; GCC_TREAT_WARNINGS_AS_ERRORS = YES; GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; OTHER_LDFLAGS = "-ObjC"; PRODUCT_NAME = "$(TARGET_NAME)"; PUBLIC_HEADERS_FOLDER_PATH = include/FMDB; SDKROOT = iphoneos; SKIP_INSTALL = YES; }; name = Debug; }; 6290CBD4188FE837009790F8 /* Release */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_OBJC_ARC = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_DOCUMENTATION_COMMENTS = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; COPY_PHASE_STRIP = YES; DSTROOT = /tmp/FMDB_IOS.dst; ENABLE_NS_ASSERTIONS = NO; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_PRECOMPILE_PREFIX_HEADER = YES; GCC_TREAT_WARNINGS_AS_ERRORS = YES; GCC_WARN_64_TO_32_BIT_CONVERSION = YES; GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; OTHER_LDFLAGS = "-ObjC"; PRODUCT_NAME = "$(TARGET_NAME)"; PUBLIC_HEADERS_FOLDER_PATH = include/FMDB; SDKROOT = iphoneos; SKIP_INSTALL = YES; VALIDATE_PRODUCT = YES; }; name = Release; }; 83C73F031C326AB000FFC730 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; APPLICATION_EXTENSION_API_ONLY = YES; CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_OBJC_ARC = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_DOCUMENTATION_COMMENTS = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; COPY_PHASE_STRIP = NO; CURRENT_PROJECT_VERSION = 1; DEBUG_INFORMATION_FORMAT = dwarf; DEFINES_MODULE = YES; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_DYNAMIC_NO_PIC = NO; GCC_OPTIMIZATION_LEVEL = 0; GCC_PREPROCESSOR_DEFINITIONS = ( "DEBUG=1", "$(inherited)", ); GCC_TREAT_WARNINGS_AS_ERRORS = YES; GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; INFOPLIST_FILE = src/fmdb/Info.plist; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", "@loader_path/Frameworks", ); MARKETING_VERSION = 2.7.8; MTL_ENABLE_DEBUG_INFO = YES; PRODUCT_BUNDLE_IDENTIFIER = "com.flyingmeat.FMDB-iOS"; PRODUCT_NAME = FMDB; SDKROOT = iphoneos; SKIP_INSTALL = YES; TARGETED_DEVICE_FAMILY = "1,2"; VERSIONING_SYSTEM = "apple-generic"; VERSION_INFO_PREFIX = ""; }; name = Debug; }; 83C73F041C326AB000FFC730 /* Release */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; APPLICATION_EXTENSION_API_ONLY = YES; CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_OBJC_ARC = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_DOCUMENTATION_COMMENTS = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; COPY_PHASE_STRIP = NO; CURRENT_PROJECT_VERSION = 1; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; DEFINES_MODULE = YES; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; ENABLE_NS_ASSERTIONS = NO; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_TREAT_WARNINGS_AS_ERRORS = YES; GCC_WARN_64_TO_32_BIT_CONVERSION = YES; GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; INFOPLIST_FILE = src/fmdb/Info.plist; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", "@loader_path/Frameworks", ); MARKETING_VERSION = 2.7.8; MTL_ENABLE_DEBUG_INFO = NO; PRODUCT_BUNDLE_IDENTIFIER = "com.flyingmeat.FMDB-iOS"; PRODUCT_NAME = FMDB; SDKROOT = iphoneos; SKIP_INSTALL = YES; TARGETED_DEVICE_FAMILY = "1,2"; VALIDATE_PRODUCT = YES; VERSIONING_SYSTEM = "apple-generic"; VERSION_INFO_PREFIX = ""; }; name = Release; }; 83C73F111C326ADB00FFC730 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; APPLICATION_EXTENSION_API_ONLY = YES; CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_OBJC_ARC = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_DOCUMENTATION_COMMENTS = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; CODE_SIGN_IDENTITY = "-"; COMBINE_HIDPI_IMAGES = YES; COPY_PHASE_STRIP = NO; CURRENT_PROJECT_VERSION = 1; DEBUG_INFORMATION_FORMAT = dwarf; DEFINES_MODULE = YES; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; FRAMEWORK_VERSION = A; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_DYNAMIC_NO_PIC = NO; GCC_OPTIMIZATION_LEVEL = 0; GCC_PREPROCESSOR_DEFINITIONS = ( "DEBUG=1", "$(inherited)", ); GCC_TREAT_WARNINGS_AS_ERRORS = YES; GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; INFOPLIST_FILE = src/fmdb/Info.plist; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/../Frameworks", "@loader_path/Frameworks", ); MTL_ENABLE_DEBUG_INFO = YES; PRODUCT_BUNDLE_IDENTIFIER = "com.flyingmeat.FMDB-MacOS"; PRODUCT_NAME = FMDB; SKIP_INSTALL = YES; VERSIONING_SYSTEM = "apple-generic"; VERSION_INFO_PREFIX = ""; }; name = Debug; }; 83C73F121C326ADB00FFC730 /* Release */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; APPLICATION_EXTENSION_API_ONLY = YES; CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_OBJC_ARC = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_DOCUMENTATION_COMMENTS = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; CODE_SIGN_IDENTITY = "-"; COMBINE_HIDPI_IMAGES = YES; COPY_PHASE_STRIP = NO; CURRENT_PROJECT_VERSION = 1; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; DEFINES_MODULE = YES; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; ENABLE_NS_ASSERTIONS = NO; FRAMEWORK_VERSION = A; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_TREAT_WARNINGS_AS_ERRORS = YES; GCC_WARN_64_TO_32_BIT_CONVERSION = YES; GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; INFOPLIST_FILE = src/fmdb/Info.plist; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/../Frameworks", "@loader_path/Frameworks", ); MTL_ENABLE_DEBUG_INFO = NO; PRODUCT_BUNDLE_IDENTIFIER = "com.flyingmeat.FMDB-MacOS"; PRODUCT_NAME = FMDB; SKIP_INSTALL = YES; VERSIONING_SYSTEM = "apple-generic"; VERSION_INFO_PREFIX = ""; }; name = Release; }; A08C6BB72AF0F5B1004F3F28 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; APPLICATION_EXTENSION_API_ONLY = YES; CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_OBJC_ARC = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_DOCUMENTATION_COMMENTS = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; COPY_PHASE_STRIP = NO; CURRENT_PROJECT_VERSION = 1; DEBUG_INFORMATION_FORMAT = dwarf; DEFINES_MODULE = YES; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_DYNAMIC_NO_PIC = NO; GCC_OPTIMIZATION_LEVEL = 0; GCC_PREPROCESSOR_DEFINITIONS = ( "DEBUG=1", "$(inherited)", ); GCC_TREAT_WARNINGS_AS_ERRORS = YES; GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; INFOPLIST_FILE = "src/fmdb/info-xrOS.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", "@loader_path/Frameworks", ); MARKETING_VERSION = 2.7.8; MTL_ENABLE_DEBUG_INFO = YES; PRODUCT_BUNDLE_IDENTIFIER = "com.flyingmeat.FMDB-xrOS"; PRODUCT_NAME = "$(TARGET_NAME)"; SDKROOT = xros; SKIP_INSTALL = YES; SUPPORTED_PLATFORMS = "xros xrsimulator"; SUPPORTS_MACCATALYST = NO; SUPPORTS_MAC_DESIGNED_FOR_IPHONE_IPAD = NO; SUPPORTS_XR_DESIGNED_FOR_IPHONE_IPAD = NO; TARGETED_DEVICE_FAMILY = 7; VERSIONING_SYSTEM = "apple-generic"; VERSION_INFO_PREFIX = ""; }; name = Debug; }; A08C6BB82AF0F5B1004F3F28 /* Release */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; APPLICATION_EXTENSION_API_ONLY = YES; CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_OBJC_ARC = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_DOCUMENTATION_COMMENTS = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; COPY_PHASE_STRIP = NO; CURRENT_PROJECT_VERSION = 1; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; DEFINES_MODULE = YES; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; ENABLE_NS_ASSERTIONS = NO; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_TREAT_WARNINGS_AS_ERRORS = YES; GCC_WARN_64_TO_32_BIT_CONVERSION = YES; GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; INFOPLIST_FILE = "src/fmdb/info-xrOS.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", "@loader_path/Frameworks", ); MARKETING_VERSION = 2.7.8; MTL_ENABLE_DEBUG_INFO = NO; PRODUCT_BUNDLE_IDENTIFIER = "com.flyingmeat.FMDB-xrOS"; PRODUCT_NAME = "$(TARGET_NAME)"; SDKROOT = xros; SKIP_INSTALL = YES; SUPPORTED_PLATFORMS = "xros xrsimulator"; SUPPORTS_MACCATALYST = NO; SUPPORTS_MAC_DESIGNED_FOR_IPHONE_IPAD = NO; SUPPORTS_XR_DESIGNED_FOR_IPHONE_IPAD = NO; TARGETED_DEVICE_FAMILY = 7; VALIDATE_PRODUCT = YES; VERSIONING_SYSTEM = "apple-generic"; VERSION_INFO_PREFIX = ""; }; name = Release; }; BF5D042518416BB2008C5AA9 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_OBJC_ARC = YES; CLANG_WARN_BOOL_CONVERSION = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_DOCUMENTATION_COMMENTS = YES; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; COMBINE_HIDPI_IMAGES = YES; COPY_PHASE_STRIP = NO; FRAMEWORK_SEARCH_PATHS = ( "$(DEVELOPER_FRAMEWORKS_DIR)", "$(inherited)", ); GCC_C_LANGUAGE_STANDARD = gnu99; GCC_DYNAMIC_NO_PIC = NO; GCC_ENABLE_OBJC_EXCEPTIONS = YES; GCC_OPTIMIZATION_LEVEL = 0; GCC_PRECOMPILE_PREFIX_HEADER = YES; GCC_PREFIX_HEADER = "Tests/Tests-Prefix.pch"; GCC_PREPROCESSOR_DEFINITIONS = ( "DEBUG=1", "$(inherited)", ); GCC_SYMBOLS_PRIVATE_EXTERN = NO; GCC_TREAT_WARNINGS_AS_ERRORS = YES; GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; GCC_WARN_PEDANTIC = NO; GCC_WARN_UNDECLARED_SELECTOR = YES; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_PARAMETER = NO; INFOPLIST_FILE = "Tests/Tests-Info.plist"; ONLY_ACTIVE_ARCH = YES; OTHER_LDFLAGS = "-lsqlite3"; PRODUCT_BUNDLE_IDENTIFIER = "me.grahamdennis.${PRODUCT_NAME:rfc1034identifier}"; PRODUCT_NAME = "$(TARGET_NAME)"; SDKROOT = macosx; WRAPPER_EXTENSION = xctest; }; name = Debug; }; BF5D042618416BB2008C5AA9 /* Release */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_OBJC_ARC = YES; CLANG_WARN_BOOL_CONVERSION = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_DOCUMENTATION_COMMENTS = YES; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; COMBINE_HIDPI_IMAGES = YES; COPY_PHASE_STRIP = YES; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; ENABLE_NS_ASSERTIONS = NO; FRAMEWORK_SEARCH_PATHS = ( "$(DEVELOPER_FRAMEWORKS_DIR)", "$(inherited)", ); GCC_C_LANGUAGE_STANDARD = gnu99; GCC_ENABLE_OBJC_EXCEPTIONS = YES; GCC_PRECOMPILE_PREFIX_HEADER = YES; GCC_PREFIX_HEADER = "Tests/Tests-Prefix.pch"; GCC_TREAT_WARNINGS_AS_ERRORS = YES; GCC_WARN_64_TO_32_BIT_CONVERSION = YES; GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; GCC_WARN_UNDECLARED_SELECTOR = YES; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_PARAMETER = NO; INFOPLIST_FILE = "Tests/Tests-Info.plist"; OTHER_LDFLAGS = "-lsqlite3"; PRODUCT_BUNDLE_IDENTIFIER = "me.grahamdennis.${PRODUCT_NAME:rfc1034identifier}"; PRODUCT_NAME = "$(TARGET_NAME)"; SDKROOT = macosx; WRAPPER_EXTENSION = xctest; }; name = Release; }; EE4290F012B42F880088BD94 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CLANG_ENABLE_OBJC_ARC = YES; CLANG_ENABLE_OBJC_WEAK = YES; CLANG_WARN_DOCUMENTATION_COMMENTS = YES; COMBINE_HIDPI_IMAGES = YES; COPY_PHASE_STRIP = NO; GCC_DYNAMIC_NO_PIC = NO; GCC_OPTIMIZATION_LEVEL = 0; GCC_TREAT_WARNINGS_AS_ERRORS = YES; GCC_WARN_UNUSED_PARAMETER = YES; PRODUCT_NAME = FMDB; PUBLIC_HEADERS_FOLDER_PATH = include/FMDB; }; name = Debug; }; EE4290F112B42F880088BD94 /* Release */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CLANG_ENABLE_OBJC_ARC = YES; CLANG_ENABLE_OBJC_WEAK = YES; CLANG_WARN_DOCUMENTATION_COMMENTS = YES; COMBINE_HIDPI_IMAGES = YES; COPY_PHASE_STRIP = YES; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; GCC_TREAT_WARNINGS_AS_ERRORS = YES; GCC_WARN_UNUSED_PARAMETER = YES; PRODUCT_NAME = FMDB; PUBLIC_HEADERS_FOLDER_PATH = include/FMDB; ZERO_LINK = NO; }; name = Release; }; /* End XCBuildConfiguration section */ /* Begin XCConfigurationList section */ 1DEB927408733DD40010E9CD /* Build configuration list for PBXNativeTarget "fmdb" */ = { isa = XCConfigurationList; buildConfigurations = ( 1DEB927508733DD40010E9CD /* Debug */, 1DEB927608733DD40010E9CD /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; 1DEB927808733DD40010E9CD /* Build configuration list for PBXProject "fmdb" */ = { isa = XCConfigurationList; buildConfigurations = ( 1DEB927908733DD40010E9CD /* Debug */, 1DEB927A08733DD40010E9CD /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; 2CD2426A1FCC09CA00479FDE /* Build configuration list for PBXNativeTarget "FMDB watchOS" */ = { isa = XCConfigurationList; buildConfigurations = ( 2CD2426B1FCC09CA00479FDE /* Debug */, 2CD2426C1FCC09CA00479FDE /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; 6290CBD7188FE837009790F8 /* Build configuration list for PBXNativeTarget "FMDB-IOS" */ = { isa = XCConfigurationList; buildConfigurations = ( 6290CBD3188FE837009790F8 /* Debug */, 6290CBD4188FE837009790F8 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; 83C73F051C326AB000FFC730 /* Build configuration list for PBXNativeTarget "FMDB iOS" */ = { isa = XCConfigurationList; buildConfigurations = ( 83C73F031C326AB000FFC730 /* Debug */, 83C73F041C326AB000FFC730 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; 83C73F101C326ADB00FFC730 /* Build configuration list for PBXNativeTarget "FMDB MacOS" */ = { isa = XCConfigurationList; buildConfigurations = ( 83C73F111C326ADB00FFC730 /* Debug */, 83C73F121C326ADB00FFC730 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; A08C6BB62AF0F5B1004F3F28 /* Build configuration list for PBXNativeTarget "FMDB xrOS" */ = { isa = XCConfigurationList; buildConfigurations = ( A08C6BB72AF0F5B1004F3F28 /* Debug */, A08C6BB82AF0F5B1004F3F28 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; BF5D042718416BB2008C5AA9 /* Build configuration list for PBXNativeTarget "Tests" */ = { isa = XCConfigurationList; buildConfigurations = ( BF5D042518416BB2008C5AA9 /* Debug */, BF5D042618416BB2008C5AA9 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; EE42910012B42FA00088BD94 /* Build configuration list for PBXNativeTarget "FMDB" */ = { isa = XCConfigurationList; buildConfigurations = ( EE4290F012B42F880088BD94 /* Debug */, EE4290F112B42F880088BD94 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; /* End XCConfigurationList section */ }; rootObject = 08FB7793FE84155DC02AAC07 /* Project object */; } ================================================ FILE: fmdb.xcodeproj/xcshareddata/xcschemes/FMDB MacOS.xcscheme ================================================ ================================================ FILE: fmdb.xcodeproj/xcshareddata/xcschemes/FMDB iOS.xcscheme ================================================ ================================================ FILE: fmdb.xcodeproj/xcshareddata/xcschemes/FMDB watchOS.xcscheme ================================================ ================================================ FILE: fmdb.xcodeproj/xcshareddata/xcschemes/FMDB xrOS.xcscheme ================================================ ================================================ FILE: privacy/PrivacyInfo.xcprivacy ================================================ NSPrivacyTracking NSPrivacyTrackingDomains NSPrivacyCollectedDataTypes NSPrivacyAccessedAPITypes ================================================ FILE: privacy/README.md ================================================ # FMJS Privacy Practices
Contact Info
Name
Such as first or last name
  • Does not collect data
  • Email Address
    Including but not limited to a hashed email address
  • Does not collect data
  • Phone Number
    Including but not limited to a hashed phone number
  • Does not collect data
  • Physical Address
    Such as home address, physical address, or mailing address
  • Does not collect data
  • Other User Contact Info
    Any other information that can be used to contact the user outside the app
  • Does not collect data
  • Health and Fitness
    Health
    Health and medical data, including but not limited to from the Clinical Health Records API, HealthKit API, MovementDisorderAPIs, or health-related human subject research or any other user provided health or medical data
  • Does not collect data
  • Fitness
    Fitness and exercise data, including but not limited to the Motion and Fitness API
  • Does not collect data
  • Financial Info
    Payment Info
    Such as form of payment, payment card number, or bank account number. If your app uses a payment service, the payment information is entered outside your app, and you as the developer never have access to the payment information, it is not collected and does not need to be disclosed.
  • Does not collect data
  • Credit Info
    Such as credit score
  • Does not collect data
  • Other Financial Info
    Such as salary, income, assets, debts, or any other financial information
  • Does not collect data
  • Location
    Precise Location
    Information that describes the location of a user or device with the same or greater resolution as a latitude and longitude with three or more decimal places
  • Does not collect data
  • Coarse Location
    Information that describes the location of a user or device with lower resolution than a latitude and longitude with three or more decimal places, such as approximate location services
  • Does not collect data
  • Sensitive Info
    Sensitive Info
    Such as racial or ethnic data, sexual orientation, pregnancy or childbirth information, disability, religious or philosophical beliefs, trade union membership, political opinion, genetic information, or biometric data
  • Does not collect data
  • Contacts
    Contacts
    Such as a list of contacts in the user’s phone, address book, or social graph
  • Does not collect data
  • User Content
    Emails or Text Messages
    Including subject line, sender, recipients, and contents of the email or message
  • Does not collect data
  • Photos or Videos
    The user’s photos or videos
  • Does not collect data
  • Audio Data
    The user’s voice or sound recordings
  • Does not collect data
  • Gameplay Content
    Such as user-generated content in-game
  • Does not collect data
  • Customer Support
    Data generated by the user during a customer support request
  • Does not collect data
  • Other User Content
    Any other user-generated content
  • Does not collect data
  • Browsing History
    Browsing History
    Information about content the user has viewed that is not part of the app, such as websites
  • Does not collect data
  • Search History
    Search History
    Information about searches performed in the app
  • Does not collect data
  • Identifiers
    User ID
    Such as screen name, handle, account ID, assigned user ID, customer number, or other user- or account-level ID that can be used to identify a particular user or account
  • Does not collect data
  • Device ID
    Such as the device’s advertising identifier, or other device-level ID
  • Does not collect data
  • Purchases
    Purchase History
    An account’s or individual’s purchases or purchase tendencies
  • Does not collect data
  • Usage Data
    Product Interaction
    Such as app launches, taps, clicks, scrolling information, music listening data, video views, saved place in a game, video, or song, or other information about how the user interacts with the app
  • Does not collect data
  • Advertising Data
    Such as information about the advertisements the user has seen
  • Does not collect data
  • Other Usage Data
    Any other data about user activity in the app
  • Does not collect data
  • Diagnostics
    Crash Data
    Such as crash logs
  • Does not collect data
  • Performance Data
    Such as launch time, hang rate, or energy use
  • Does not collect data
  • Other Diagnostic Data
    Any other data collected for the purposes of measuring technical diagnostics related to the app
  • Does not collect data
  • Other Data
    Other Data Types
    Any other data types not mentioned
  • Does not collect data
  • ================================================ FILE: src/extra/InMemoryOnDiskIO/FMDatabase+InMemoryOnDiskIO.h ================================================ // // FMDatabase+InMemoryOnDiskIO.h // FMDB // // Created by Peter Carr on 6/12/12. // // I find there is a massive performance hit using an "on-disk" representation when // constantly reading from or writing to the DB. If your machine has sufficient memory, you // should get a significant performance boost using an "in-memory" representation. The FMDB // warpper does not contain methods to load an "on-disk" representation into memory and // similarly save an "in-memory" representation to disk. However, SQLite3 has built-in // support for this functionality via its "Backup" API. Here, we extend the FMBD wrapper // to include this functionality. // // https://sqlite.org/backup.html #import "FMDatabase.h" @interface FMDatabase (InMemoryOnDiskIO) // Loads an on-disk representation into memory. - (BOOL)readFromFile:(NSString*)filePath; // Saves an in-memory representation to disk - (BOOL)writeToFile:(NSString *)filePath; @end ================================================ FILE: src/extra/InMemoryOnDiskIO/FMDatabase+InMemoryOnDiskIO.m ================================================ #import "FMDatabase+InMemoryOnDiskIO.h" #import // https://sqlite.org/backup.html static int loadOrSaveDb(sqlite3 *pInMemory, const char *zFilename, int isSave) { int rc; /* Function return code */ sqlite3 *pFile; /* Database connection opened on zFilename */ sqlite3_backup *pBackup; /* Backup object used to copy data */ sqlite3 *pTo; /* Database to copy to (pFile or pInMemory) */ sqlite3 *pFrom; /* Database to copy from (pFile or pInMemory) */ /* Open the database file identified by zFilename. Exit early if this fails ** for any reason. */ rc = sqlite3_open(zFilename, &pFile); if( rc==SQLITE_OK ){ /* If this is a 'load' operation (isSave==0), then data is copied ** from the database file just opened to database pInMemory. ** Otherwise, if this is a 'save' operation (isSave==1), then data ** is copied from pInMemory to pFile. Set the variables pFrom and ** pTo accordingly. */ pFrom = (isSave ? pInMemory : pFile); pTo = (isSave ? pFile : pInMemory); /* Set up the backup procedure to copy from the "main" database of ** connection pFile to the main database of connection pInMemory. ** If something goes wrong, pBackup will be set to NULL and an error ** code and message left in connection pTo. ** ** If the backup object is successfully created, call backup_step() ** to copy data from pFile to pInMemory. Then call backup_finish() ** to release resources associated with the pBackup object. If an ** error occurred, then an error code and message will be left in ** connection pTo. If no error occurred, then the error code belonging ** to pTo is set to SQLITE_OK. */ pBackup = sqlite3_backup_init(pTo, "main", pFrom, "main"); if( pBackup ){ (void)sqlite3_backup_step(pBackup, -1); (void)sqlite3_backup_finish(pBackup); } rc = sqlite3_errcode(pTo); } /* Close the database connection opened on database file zFilename ** and return the result of this function. */ (void)sqlite3_close(pFile); return rc; } @implementation FMDatabase (InMemoryOnDiskIO) - (BOOL)readFromFile:(NSString*)filePath { // only attempt to load an on-disk representation for an in-memory database if ( [self databasePath] != nil ) { NSLog(@"Database is not an in-memory representation." ); return NO; } // and only if the database is open if ( [self sqliteHandle] == nil ) { NSLog(@"Invalid database connection." ); return NO; } return ( SQLITE_OK == loadOrSaveDb( [self sqliteHandle], [filePath fileSystemRepresentation], false ) ); } - (BOOL)writeToFile:(NSString *)filePath { // only attempt to save an on-disk representation for an in-memory database if ( [self databasePath] != nil ) { NSLog(@"Database is not an in-memory representation." ); return NO; } // and only if the database is open if ( [self sqliteHandle] == nil ) { NSLog(@"Invalid database connection." ); return NO; } // save the in-memory representation return ( SQLITE_OK == loadOrSaveDb( [self sqliteHandle], [filePath fileSystemRepresentation], true ) ); } @end ================================================ FILE: src/extra/fts3/FMDatabase+FTS3.h ================================================ // // FMDatabase+FTS3.h // fmdb // // Created by Andrew on 3/27/14. // Copyright (c) 2014 Andrew Goodale. All rights reserved. // #import /** Names of commands that can be issued against an FTS table. */ extern NSString *const kFTSCommandOptimize; // "optimize" extern NSString *const kFTSCommandRebuild; // "rebuild" extern NSString *const kFTSCommandIntegrityCheck; // "integrity-check" extern NSString *const kFTSCommandMerge; // "merge=%u,%u" extern NSString *const kFTSCommandAutoMerge; // "automerge=%u" @protocol FMTokenizerDelegate; /** This category provides methods to access the FTS3 extensions in SQLite. */ @interface FMDatabase (FTS3) /** Register a delegate implementation in the global table. This should be used when using a single tokenizer. */ + (void)registerTokenizer:(id)tokenizer; /** Register a delegate implementation in the global table. The key should be used as a parameter when creating the table. */ + (void)registerTokenizer:(id)tokenizer withKey:(NSString *)key; /** Calls the @c fts3_tokenizer function on this database, installing tokenizer module with the 'fmdb' name. */ - (BOOL)installTokenizerModule; /** Calls the @c fts3_tokenizer function on this database, installing the tokenizer module with specified name. */ - (BOOL)installTokenizerModuleWithName:(NSString *)name; /** Runs a "special command" for FTS3/FTS4 tables. */ - (BOOL)issueCommand:(NSString *)command forTable:(NSString *)tableName; @end #pragma mark /* Extend this structure with your own custom cursor data */ typedef struct FMTokenizerCursor { void *tokenizer; /* Internal SQLite reference */ CFStringRef inputString; /* The input text being tokenized */ CFRange currentRange; /* The current range within `inputString` */ CFStringRef tokenString; /* The contents of the current token */ CFTypeRef userObject; /* Additional state for the cursor */ int tokenIndex; /* Index of next token to be returned */ UInt8 outputBuf[128]; /* Result for SQLite */ CFRange previousRange; /* Cached range of previous token within `inputString` */ CFRange previousOffsetRange; /* Cached range of previous token as UTF-8 offset */ } FMTokenizerCursor; @protocol FMTokenizerDelegate - (void)openTokenizerCursor:(FMTokenizerCursor *)cursor; - (BOOL)nextTokenForCursor:(FMTokenizerCursor *)cursor; - (void)closeTokenizerCursor:(FMTokenizerCursor *)cursor; @end #pragma mark /** The container of offset information. */ @interface FMTextOffsets : NSObject - (instancetype)initWithDBOffsets:(const char *)offsets; /** Enumerate each set of offsets in the result. The column number can be turned into a column name using `[FMResultSet columnNameForIndex:]`. The @c matchRange is in UTF-8 byte positions, so it must be modified to use with @c NSString data. */ - (void)enumerateWithBlock:(void (^)(NSInteger columnNumber, NSInteger termNumber, NSRange matchRange))block; @end /** A category that adds support for the encoded data returned by FTS3 functions. */ @interface FMResultSet (FTS3) /** Returns a structure containing values from the @c offsets function. Make sure the column index corresponds to the column index in the SQL query. @param columnIdx Zero-based index for column. @return @c FMTextOffsets structure. */ - (FMTextOffsets *)offsetsForColumnIndex:(int)columnIdx; @end ================================================ FILE: src/extra/fts3/FMDatabase+FTS3.m ================================================ // // FMDatabase+FTS3.m // fmdb // // Created by Andrew on 3/27/14. // Copyright (c) 2014 Andrew Goodale. All rights reserved. // #import "FMDatabase+FTS3.h" #import "fts3_tokenizer.h" #include "sqlite3.h" NSString *const kFTSCommandOptimize = @"optimize"; NSString *const kFTSCommandRebuild = @"rebuild"; NSString *const kFTSCommandIntegrityCheck = @"integrity-check"; NSString *const kFTSCommandMerge = @"merge=%u,%u"; NSString *const kFTSCommandAutoMerge = @"automerge=%u"; /* I know this is an evil global, but we need to be able to map names to implementations. */ static NSMapTable *g_delegateMap = nil; static NSString *kDefaultTokenizerDelegateKey = @"DefaultTokenizerDelegateKey"; /* ** Class derived from sqlite3_tokenizer */ typedef struct FMDBTokenizer { sqlite3_tokenizer base; id __unsafe_unretained delegate; } FMDBTokenizer; /* ** Create a new tokenizer instance. */ static int FMDBTokenizerCreate(int argc, const char * const *argv, sqlite3_tokenizer **ppTokenizer) { FMDBTokenizer *tokenizer = (FMDBTokenizer *) sqlite3_malloc(sizeof(FMDBTokenizer)); if (tokenizer == NULL) { return SQLITE_NOMEM; } memset(tokenizer, 0, sizeof(*tokenizer)); NSString *key = kDefaultTokenizerDelegateKey; if (argc > 0) { key = [NSString stringWithUTF8String:argv[0]]; } tokenizer->delegate = [g_delegateMap objectForKey:key]; if (!tokenizer->delegate) { return SQLITE_ERROR; } *ppTokenizer = &tokenizer->base; return SQLITE_OK; } /* ** Destroy a tokenizer */ static int FMDBTokenizerDestroy(sqlite3_tokenizer *pTokenizer) { sqlite3_free(pTokenizer); return SQLITE_OK; } /* ** Prepare to begin tokenizing a particular string. The input ** string to be tokenized is zInput[0..nInput-1]. A cursor ** used to incrementally tokenize this string is returned in ** *ppCursor. */ static int FMDBTokenizerOpen(sqlite3_tokenizer *pTokenizer, /* The tokenizer */ const char *pInput, int nBytes, /* String to be tokenized */ sqlite3_tokenizer_cursor **ppCursor) /* OUT: Tokenization cursor */ { FMDBTokenizer *tokenizer = (FMDBTokenizer *)pTokenizer; FMTokenizerCursor *cursor = (FMTokenizerCursor *)sqlite3_malloc(sizeof(FMTokenizerCursor)); if (cursor == NULL) { return SQLITE_NOMEM; } if (pInput == NULL || pInput[0] == '\0') { cursor->inputString = CFRetain(CFSTR("")); } else { nBytes = (nBytes < 0) ? (int) strlen(pInput) : nBytes; cursor->inputString = CFStringCreateWithBytesNoCopy(NULL, (const UInt8 *)pInput, nBytes, kCFStringEncodingUTF8, false, kCFAllocatorNull); } cursor->currentRange = CFRangeMake(0, 0); cursor->tokenIndex = 0; cursor->tokenString = NULL; cursor->userObject = NULL; cursor->outputBuf[0] = '\0'; cursor->previousRange = CFRangeMake(0, 0); cursor->previousOffsetRange = CFRangeMake(0, 0); [tokenizer->delegate openTokenizerCursor:cursor]; *ppCursor = (sqlite3_tokenizer_cursor *)cursor; return SQLITE_OK; } /* ** Close a tokenization cursor previously opened by a call to ** FMDBTokenizerOpen() above. */ static int FMDBTokenizerClose(sqlite3_tokenizer_cursor *pCursor) { FMTokenizerCursor *cursor = (FMTokenizerCursor *)pCursor; FMDBTokenizer *tokenizer = (FMDBTokenizer *)cursor->tokenizer; [tokenizer->delegate closeTokenizerCursor:cursor]; if (cursor->userObject) { CFRelease(cursor->userObject); } if (cursor->tokenString) { CFRelease(cursor->tokenString); } CFRelease(cursor->inputString); sqlite3_free(cursor); return SQLITE_OK; } /* ** Extract the next token from a tokenization cursor. The cursor must ** have been opened by a prior call to FMDBTokenizerOpen(). */ static int FMDBTokenizerNext(sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by Open */ const char **pzToken, /* OUT: *pzToken is the token text */ int *pnBytes, /* OUT: Number of bytes in token */ int *piStartOffset, /* OUT: Starting offset of token */ int *piEndOffset, /* OUT: Ending offset of token */ int *piPosition) /* OUT: Position integer of token */ { FMTokenizerCursor *cursor = (FMTokenizerCursor *)pCursor; FMDBTokenizer *tokenizer = (FMDBTokenizer *)cursor->tokenizer; if ([tokenizer->delegate nextTokenForCursor:cursor]) { return SQLITE_DONE; } // The range from the tokenizer is in UTF-16 positions, we need give UTF-8 positions to SQLite // Conversion to bytes is very expensive on longer strings. In order to avoid processing the same data over and over again for each token, we cache the previousRange and previousOffsetRange // Not all tokenizers may process strings sequentially. Reset the cached ranges if necessary if (cursor->currentRange.location < cursor->previousRange.location + cursor->previousRange.length) { cursor->previousRange = CFRangeMake(0, 0); cursor->previousOffsetRange = CFRangeMake(0, 0); } // First calculate the offset of current token range in original string CFIndex locationOffset, lengthOffset; const CFRange rangeToStartToken = CFRangeMake((cursor->previousRange.location + cursor->previousRange.length), cursor->currentRange.location - (cursor->previousRange.location + cursor->previousRange.length)); // This will tell us how many UTF-8 bytes there are before the start of the token CFStringGetBytes(cursor->inputString, rangeToStartToken, kCFStringEncodingUTF8, '?', false, NULL, 0, &locationOffset); // and how many UTF-8 bytes there are within the token in the original string CFStringGetBytes(cursor->inputString, cursor->currentRange, kCFStringEncodingUTF8, '?', false, NULL, 0, &lengthOffset); // Update the location offset locationOffset += (cursor->previousOffsetRange.location + cursor->previousOffsetRange.length); // Cache the data to reuse on next token cursor->previousRange = cursor->currentRange; cursor->previousOffsetRange = CFRangeMake(locationOffset, lengthOffset); // Determine how many bytes the new token string uses CFIndex newBytesUsed; const CFRange newTokenRange = CFRangeMake(0, CFStringGetLength(cursor->tokenString)); CFStringGetBytes(cursor->tokenString, newTokenRange, kCFStringEncodingUTF8, '?', false, cursor->outputBuf, sizeof(cursor->outputBuf), &newBytesUsed); *pzToken = (char *) cursor->outputBuf; *pnBytes = (int) newBytesUsed; *piStartOffset = (int) locationOffset; *piEndOffset = (int) (locationOffset + lengthOffset); *piPosition = cursor->tokenIndex++; return SQLITE_OK; } /* ** The set of routines that bridge to the tokenizer delegate. */ static const sqlite3_tokenizer_module FMDBTokenizerModule = { 0, FMDBTokenizerCreate, FMDBTokenizerDestroy, FMDBTokenizerOpen, FMDBTokenizerClose, FMDBTokenizerNext }; #pragma mark @implementation FMDatabase (FTS3) + (void)registerTokenizer:(id)tokenizer withKey:(NSString *)key { NSParameterAssert(tokenizer); NSParameterAssert([key length]); static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ g_delegateMap = [NSMapTable mapTableWithKeyOptions:NSPointerFunctionsCopyIn valueOptions:NSPointerFunctionsWeakMemory]; }); [g_delegateMap setObject:tokenizer forKey:key]; } + (void)registerTokenizer:(id)tokenizer { [self registerTokenizer:tokenizer withKey:kDefaultTokenizerDelegateKey]; } - (BOOL)installTokenizerModuleWithName:(NSString *)name { const sqlite3_tokenizer_module *module = &FMDBTokenizerModule; NSData *tokenizerData = [NSData dataWithBytes:&module length:sizeof(module)]; FMResultSet *results = [self executeQuery:@"SELECT fts3_tokenizer(?, ?)", name, tokenizerData]; if ([results next]) { [results close]; return YES; } return NO; } - (BOOL)installTokenizerModule { return [self installTokenizerModuleWithName:@"fmdb"]; } - (BOOL)issueCommand:(NSString *)command forTable:(NSString *)tableName { NSString *sql = [NSString stringWithFormat:@"INSERT INTO %1$@(%1$@) VALUES (?)", tableName]; return [self executeUpdate:sql, command]; } @end #pragma mark @implementation FMTextOffsets { NSString *_rawOffsets; } - (instancetype)initWithDBOffsets:(const char *)rawOffsets { if ((self = [super init])) { _rawOffsets = [NSString stringWithUTF8String:rawOffsets]; } return self; } - (void)enumerateWithBlock:(void (^)(NSInteger, NSInteger, NSRange))block { const char *rawOffsets = [_rawOffsets UTF8String]; uint32_t offsetInt[4]; int charsRead = 0; while (sscanf(rawOffsets, "%u %u %u %u%n", &offsetInt[0], &offsetInt[1], &offsetInt[2], &offsetInt[3], &charsRead) == 4) { block(offsetInt[0], offsetInt[1], NSMakeRange(offsetInt[2], offsetInt[3])); rawOffsets += charsRead; } } @end @implementation FMResultSet (FTS3) - (FMTextOffsets *)offsetsForColumnIndex:(int)columnIdx { // The offsets() value is a space separated groups of 4 integers const char *rawOffsets = (const char *)sqlite3_column_text([self.statement statement], columnIdx); return [[FMTextOffsets alloc] initWithDBOffsets:rawOffsets]; } @end ================================================ FILE: src/extra/fts3/FMTokenizers.h ================================================ // // FMTokenizers.h // fmdb // // Created by Andrew on 4/9/14. // Copyright (c) 2014 Andrew Goodale. All rights reserved. // #import #import "FMDatabase+FTS3.h" NS_ASSUME_NONNULL_BEGIN /** This is the base tokenizer implementation, using a CFStringTokenizer to find words. */ @interface FMSimpleTokenizer : NSObject /** Create the tokenizer with a given locale. The locale will be used to initialize the string tokenizer and to lowercase the parsed word. @param locale The locale used by the simple tokenizer. The locale can be @c NULL , in which case the current locale will be used. */ - (instancetype)initWithLocale:(CFLocaleRef _Nullable)locale; @end #pragma mark /** This tokenizer extends the simple tokenizer with support for a stop word list. */ @interface FMStopWordTokenizer : NSObject @property (atomic, copy) NSSet *words; /** Load a stop-word tokenizer using a file containing words delimited by newlines. The file should be encoded in UTF-8. @param wordFileURL The file URL for the list of words. @param tokenizer The @c FMTokenizerDelegate . @param error The @c NSError if there was any error reading the file. */ + (instancetype)tokenizerWithFileURL:(NSURL *)wordFileURL baseTokenizer:(id)tokenizer error:(NSError * _Nullable *)error; /** Initialize an instance of the tokenizer using the set of words. The words should be lowercase if you're using the `FMSimpleTokenizer` as the base. @param words The @c NSSet of words. @param tokenizer The @c FMTokenizerDelegate . */ - (instancetype)initWithWords:(NSSet *)words baseTokenizer:(id)tokenizer; @end NS_ASSUME_NONNULL_END ================================================ FILE: src/extra/fts3/FMTokenizers.m ================================================ // // FMTokenizers.m // fmdb // // Created by Andrew on 4/9/14. // Copyright (c) 2014 Andrew Goodale. All rights reserved. // #import "FMTokenizers.h" @implementation FMSimpleTokenizer { CFLocaleRef m_locale; } - (id)initWithLocale:(CFLocaleRef)locale { if ((self = [super init])) { m_locale = (locale != NULL) ? CFRetain(locale) : CFLocaleCopyCurrent(); } return self; } - (void)dealloc { CFRelease(m_locale); } - (void)openTokenizerCursor:(FMTokenizerCursor *)cursor { cursor->tokenString = CFStringCreateMutable(NULL, 0); cursor->userObject = CFStringTokenizerCreate(NULL, cursor->inputString, CFRangeMake(0, CFStringGetLength(cursor->inputString)), kCFStringTokenizerUnitWord, m_locale); } - (BOOL)nextTokenForCursor:(FMTokenizerCursor *)cursor { CFStringTokenizerRef tokenizer = (CFStringTokenizerRef) cursor->userObject; CFMutableStringRef tokenString = (CFMutableStringRef) cursor->tokenString; CFStringTokenizerTokenType tokenType = CFStringTokenizerAdvanceToNextToken(tokenizer); if (tokenType == kCFStringTokenizerTokenNone) { // No more tokens, we are finished. return YES; } // Found a regular word. The token is the lowercase version of the word. cursor->currentRange = CFStringTokenizerGetCurrentTokenRange(tokenizer); // The inline buffer approach is faster and uses less memory than CFStringCreateWithSubstring() CFStringInlineBuffer inlineBuf; CFStringInitInlineBuffer(cursor->inputString, &inlineBuf, cursor->currentRange); CFStringDelete(tokenString, CFRangeMake(0, CFStringGetLength(tokenString))); for (int i = 0; i < cursor->currentRange.length; ++i) { UniChar nextChar = CFStringGetCharacterFromInlineBuffer(&inlineBuf, i); CFStringAppendCharacters(tokenString, &nextChar, 1); } CFStringLowercase(tokenString, m_locale); return NO; } - (void)closeTokenizerCursor:(FMTokenizerCursor *)cursor { // FMDatabase will CFRelease the tokenString and the userObject. } @end #pragma mark @implementation FMStopWordTokenizer { id m_baseTokenizer; } @synthesize words = m_words; + (instancetype)tokenizerWithFileURL:(NSURL *)wordFileURL baseTokenizer:(id)tokenizer error:(NSError *__autoreleasing *)error { NSParameterAssert(wordFileURL); NSString *contents = [NSString stringWithContentsOfURL:wordFileURL encoding:NSUTF8StringEncoding error:error]; NSArray *stopWords = [contents componentsSeparatedByString:@"\n"]; if (contents == nil) { return nil; } return [[self alloc] initWithWords:[NSSet setWithArray:stopWords] baseTokenizer:tokenizer]; } - (instancetype)initWithWords:(NSSet *)words baseTokenizer:(id)tokenizer { NSParameterAssert(tokenizer); if ((self = [super init])) { m_words = [words copy]; m_baseTokenizer = tokenizer; } return self; } - (void)openTokenizerCursor:(FMTokenizerCursor *)cursor { [m_baseTokenizer openTokenizerCursor:cursor]; } - (BOOL)nextTokenForCursor:(FMTokenizerCursor *)cursor { BOOL done = [m_baseTokenizer nextTokenForCursor:cursor]; // Don't use stop words for prefix queries since it's fine for the prefix to be in the stop list if (CFStringHasSuffix(cursor->inputString, CFSTR("*"))) { return done; } while (!done && [self.words containsObject:(__bridge id)(cursor->tokenString)]) { done = [m_baseTokenizer nextTokenForCursor:cursor]; } return done; } - (void)closeTokenizerCursor:(FMTokenizerCursor *)cursor { [m_baseTokenizer closeTokenizerCursor:cursor]; } @end ================================================ FILE: src/extra/fts3/fts3_tokenizer.h ================================================ /* ** 2006 July 10 ** ** The author disclaims copyright to this source code. ** ************************************************************************* ** Defines the interface to tokenizers used by fulltext-search. There ** are three basic components: ** ** sqlite3_tokenizer_module is a singleton defining the tokenizer ** interface functions. This is essentially the class structure for ** tokenizers. ** ** sqlite3_tokenizer is used to define a particular tokenizer, perhaps ** including customization information defined at creation time. ** ** sqlite3_tokenizer_cursor is generated by a tokenizer to generate ** tokens from a particular input. */ #ifndef _FTS3_TOKENIZER_H_ #define _FTS3_TOKENIZER_H_ /* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time. ** If tokenizers are to be allowed to call sqlite3_*() functions, then ** we will need a way to register the API consistently. */ /* ** Structures used by the tokenizer interface. When a new tokenizer ** implementation is registered, the caller provides a pointer to ** an sqlite3_tokenizer_module containing pointers to the callback ** functions that make up an implementation. ** ** When an fts3 table is created, it passes any arguments passed to ** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the ** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer ** implementation. The xCreate() function in turn returns an ** sqlite3_tokenizer structure representing the specific tokenizer to ** be used for the fts3 table (customized by the tokenizer clause arguments). ** ** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen() ** method is called. It returns an sqlite3_tokenizer_cursor object ** that may be used to tokenize a specific input buffer based on ** the tokenization rules supplied by a specific sqlite3_tokenizer ** object. */ typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module; typedef struct sqlite3_tokenizer sqlite3_tokenizer; typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor; struct sqlite3_tokenizer_module { /* ** Structure version. Should always be set to 0 or 1. */ int iVersion; /* ** Create a new tokenizer. The values in the argv[] array are the ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL ** TABLE statement that created the fts3 table. For example, if ** the following SQL is executed: ** ** CREATE .. USING fts3( ... , tokenizer arg1 arg2) ** ** then argc is set to 2, and the argv[] array contains pointers ** to the strings "arg1" and "arg2". ** ** This method should return either SQLITE_OK (0), or an SQLite error ** code. If SQLITE_OK is returned, then *ppTokenizer should be set ** to point at the newly created tokenizer structure. The generic ** sqlite3_tokenizer.pModule variable should not be initialised by ** this callback. The caller will do so. */ int (*xCreate)( int argc, /* Size of argv array */ const char *const*argv, /* Tokenizer argument strings */ sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */ ); /* ** Destroy an existing tokenizer. The fts3 module calls this method ** exactly once for each successful call to xCreate(). */ int (*xDestroy)(sqlite3_tokenizer *pTokenizer); /* ** Create a tokenizer cursor to tokenize an input buffer. The caller ** is responsible for ensuring that the input buffer remains valid ** until the cursor is closed (using the xClose() method). */ int (*xOpen)( sqlite3_tokenizer *pTokenizer, /* Tokenizer object */ const char *pInput, int nBytes, /* Input buffer */ sqlite3_tokenizer_cursor **ppCursor /* OUT: Created tokenizer cursor */ ); /* ** Destroy an existing tokenizer cursor. The fts3 module calls this ** method exactly once for each successful call to xOpen(). */ int (*xClose)(sqlite3_tokenizer_cursor *pCursor); /* ** Retrieve the next token from the tokenizer cursor pCursor. This ** method should either return SQLITE_OK and set the values of the ** "OUT" variables identified below, or SQLITE_DONE to indicate that ** the end of the buffer has been reached, or an SQLite error code. ** ** *ppToken should be set to point at a buffer containing the ** normalized version of the token (i.e. after any case-folding and/or ** stemming has been performed). *pnBytes should be set to the length ** of this buffer in bytes. The input text that generated the token is ** identified by the byte offsets returned in *piStartOffset and ** *piEndOffset. *piStartOffset should be set to the index of the first ** byte of the token in the input buffer. *piEndOffset should be set ** to the index of the first byte just past the end of the token in ** the input buffer. ** ** The buffer *ppToken is set to point at is managed by the tokenizer ** implementation. It is only required to be valid until the next call ** to xNext() or xClose(). */ /* TODO(shess) current implementation requires pInput to be ** nul-terminated. This should either be fixed, or pInput/nBytes ** should be converted to zInput. */ int (*xNext)( sqlite3_tokenizer_cursor *pCursor, /* Tokenizer cursor */ const char **ppToken, int *pnBytes, /* OUT: Normalized text for token */ int *piStartOffset, /* OUT: Byte offset of token in input buffer */ int *piEndOffset, /* OUT: Byte offset of end of token in input buffer */ int *piPosition /* OUT: Number of tokens returned before this one */ ); /*********************************************************************** ** Methods below this point are only available if iVersion>=1. */ /* ** Configure the language id of a tokenizer cursor. */ int (*xLanguageid)(sqlite3_tokenizer_cursor *pCsr, int iLangid); }; struct sqlite3_tokenizer { const sqlite3_tokenizer_module *pModule; /* The module for this tokenizer */ /* Tokenizer implementations will typically add additional fields */ }; struct sqlite3_tokenizer_cursor { sqlite3_tokenizer *pTokenizer; /* Tokenizer for this cursor. */ /* Tokenizer implementations will typically add additional fields */ }; int fts3_global_term_cnt(int iTerm, int iCol); int fts3_term_cnt(int iTerm, int iCol); #endif /* _FTS3_TOKENIZER_H_ */ ================================================ FILE: src/fmdb/FMDB.h ================================================ #import FOUNDATION_EXPORT double FMDBVersionNumber; FOUNDATION_EXPORT const unsigned char FMDBVersionString[]; #import "FMDatabase.h" #import "FMResultSet.h" #import "FMDatabaseAdditions.h" #import "FMDatabaseQueue.h" #import "FMDatabasePool.h" #import "FMDatabase+SQLCipher.h" ================================================ FILE: src/fmdb/FMDatabase+SQLCipher.h ================================================ // // FMDatabase+SQLCipher.h // FMDB // // Created by Micah T. Moore on 9/29/25. // #import "FMDatabase.h" NS_ASSUME_NONNULL_BEGIN typedef enum : NSUInteger { CipherLogLevelNone, CipherLogLevelError, CipherLogLevelWarn, CipherLogLevelInfo, CipherLogLevelDebug, CipherLogLevelTrace } CipherLogLevel; @interface FMDatabase (SQLCipher) /// - Returns: the SQLCipher version /// /// See https://www.zetetic.net/sqlcipher/sqlcipher-api/#cipher_version @property (readonly, strong, nullable) NSString *cipherVersion; /// - Returns: the SQLCipher fips status: 1 for fips mode, 0 for non-fips mode /// The FIPS status will not be initialized until the database connection has been keyed /// /// See https://www.zetetic.net/sqlcipher/sqlcipher-api/#cipher_fips_status @property (readonly, strong, nullable) NSString *cipherFipsStatus; /// - Returns: the SQLCipher fips status: 1 for fips mode, 0 for non-fips mode /// The FIPS status will not be initialized until the database connection has been keyed /// /// See https://www.zetetic.net/sqlcipher/sqlcipher-api/#cipher_fips_status @property (readonly, strong, nullable) NSString *cipherProvider; /// - Returns: the version number provided from the compiled crypto provider. /// This value, if known, is available only after the database has been keyed. /// /// See https://www.zetetic.net/sqlcipher/sqlcipher-api/#cipher_provider_version @property (readonly, strong, nullable) NSString *cipherProviderVersion; ///------------------------- /// @name Encryption methods ///------------------------- /** Set encryption key. @param key The key to be used. @return @c YES if success, @c NO on error. @see https://www.zetetic.net/sqlcipher/ @warning You need to have purchased the sqlite encryption extensions for this method to work. */ - (BOOL)setKey:(NSString*)key; /** Reset encryption key @param key The key to be used. @return @c YES if success, @c NO on error. @see https://www.zetetic.net/sqlcipher/ @warning You need to have purchased the sqlite encryption extensions for this method to work. */ - (BOOL)rekey:(NSString*)key; /** Set encryption key using `keyData`. @param keyData The @c NSData to be used. @return @c YES if success, @c NO on error. @see https://www.zetetic.net/sqlcipher/ @warning You need to have purchased the sqlite encryption extensions for this method to work. */ - (BOOL)setKeyWithData:(NSData *)keyData; /** Reset encryption key using `keyData`. @param keyData The @c NSData to be used. @return @c YES if success, @c NO on error. @see https://www.zetetic.net/sqlcipher/ @warning You need to have purchased the sqlite encryption extensions for this method to work. */ - (BOOL)rekeyWithData:(NSData *)keyData; /// When using Commercial or Enterprise SQLCipher packages you must call /// `PRAGMA cipher_license` with a valid license code prior to executing /// cryptographic operations on an encrypted database. /// Failure to provide a license code, or use of an expired trial code, /// will result in an `SQLITE_AUTH (23)` error code reported from the SQLite API /// License Codes will activate SQLCipher Commercial or Enterprise packages /// from Zetetic: https://www.zetetic.net/sqlcipher/buy/ /// 15-day free trials are available by request: https://www.zetetic.net/sqlcipher/trial/ /// /// See https://www.zetetic.net/sqlcipher/sqlcipher-api/#cipher_license /// - Parameter license: base64 SQLCipher license code to activate SQLCipher commercial /// - Return YES if success NO on error. - (BOOL)applyLicense:(NSString *)licenseCode; /// Instructs SQLCipher to log internal debugging and operational information /// to the sepecified log target (device) using `os_log` /// The supplied logLevel will determine the granularity of the logs output /// Available logLevel options are: NONE, ERROR, WARN, INFO, DEBUG, TRACE /// Note that each level is more verbose than the last, /// and particularly with DEBUG and TRACE the logging system will generate /// a significant log volume /// /// See https://www.zetetic.net/sqlcipher/sqlcipher-api/#cipher_log /// - Parameter logLevel: CipherLogLevel The granularity to use for the logging system /// - Return YES if success NO on error. - (BOOL)enableCipherLogging:(CipherLogLevel)logLevel; /// Instructs SQLCipher to disable logging internal debugging and operational information /// /// See https://www.zetetic.net/sqlcipher/sqlcipher-api/#cipher_log /// - Return YES if success NO on error. - (BOOL)disableCipherLogging; @end NS_ASSUME_NONNULL_END ================================================ FILE: src/fmdb/FMDatabase+SQLCipher.m ================================================ // // FMDatabase+SQLCipher.m // FMDB // // Created by Micah T. Moore on 9/29/25. // #import #import "FMDatabase+SQLCipher.h" #if SQLCIPHER_CRYPTO #import #endif @implementation FMDatabase (SQLCipher) @dynamic cipherVersion; @dynamic cipherFipsStatus; @dynamic cipherProvider; @dynamic cipherProviderVersion; - (NSString *)cipherVersion { NSString *ver = nil; #ifdef SQLITE_HAS_CODEC FMResultSet *rs = [self executeQuery:@"PRAGMA cipher_version;"]; if ([rs next]) { ver = rs.resultDictionary[@"cipher_version"]; [rs close]; } #endif return ver; } - (NSString *)cipherFipsStatus { NSString *fipsStatus = nil; #ifdef SQLITE_HAS_CODEC FMResultSet *rs = [self executeQuery:@"PRAGMA cipher_fips_status;"]; if ([rs next]) { fipsStatus = rs.resultDictionary[@"cipher_fips_status"]; [rs close]; } #endif return fipsStatus; } - (NSString *)cipherProvider { NSString *provider = nil; #ifdef SQLITE_HAS_CODEC FMResultSet *rs = [self executeQuery:@"PRAGMA cipher_provider;"]; if ([rs next]) { provider = rs.resultDictionary[@"cipher_provider"]; [rs close]; } #endif return provider; } - (NSString *)cipherProviderVersion { NSString *providerVer = nil; #ifdef SQLITE_HAS_CODEC FMResultSet *rs = [self executeQuery:@"PRAGMA cipher_provider_version;"]; if ([rs next]) { providerVer = rs.resultDictionary[@"cipher_provider_version"]; [rs close]; } #endif return providerVer; } #pragma mark Key routines - (BOOL)rekey:(NSString*)key { NSData *keyData = [NSData dataWithBytes:(void *)[key UTF8String] length:(NSUInteger)strlen([key UTF8String])]; return [self rekeyWithData:keyData]; } - (BOOL)rekeyWithData:(NSData *)keyData { #ifdef SQLITE_HAS_CODEC if (!keyData) { return NO; } int rc = sqlite3_rekey([self sqliteHandle], [keyData bytes], (int)[keyData length]); if (rc != SQLITE_OK) { NSLog(@"error on rekey: %d", rc); NSLog(@"%@", [self lastErrorMessage]); } return (rc == SQLITE_OK); #else #pragma unused(keyData) return NO; #endif } - (BOOL)setKey:(NSString*)key { NSData *keyData = [NSData dataWithBytes:[key UTF8String] length:(NSUInteger)strlen([key UTF8String])]; return [self setKeyWithData:keyData]; } - (BOOL)setKeyWithData:(NSData *)keyData { #ifdef SQLITE_HAS_CODEC if (!keyData) { return NO; } int rc = sqlite3_key([self sqliteHandle], [keyData bytes], (int)[keyData length]); return (rc == SQLITE_OK); #else #pragma unused(keyData) return NO; #endif } - (BOOL)applyLicense:(NSString *)licenseCode { BOOL execSuccess = NO; #ifdef SQLITE_HAS_CODEC if (licenseCode != nil && licenseCode.length > 0) { NSString *licensePragma = [NSString stringWithFormat:@"PRAGMA cipher_license = '%@';", licenseCode]; execSuccess = [self executeStatements:licensePragma]; } #endif return execSuccess; } - (BOOL)enableCipherLogging:(CipherLogLevel)logLevel { BOOL execSuccess = NO; #ifdef SQLITE_HAS_CODEC execSuccess = [self executeStatements:@"PRAGMA cipher_log = device;"]; NSString *logLevelString = [self _logLevelString:logLevel]; NSString *logLevelPragma = [NSString stringWithFormat:@"PRAGMA cipher_log_level = %@;", logLevelString]; execSuccess &= [self executeStatements:logLevelPragma]; #endif return execSuccess; } - (BOOL)disableCipherLogging { #ifdef SQLITE_HAS_CODEC return [self executeStatements:@"PRAGMA cipher_log_level = NONE;"]; #endif return NO; } - (NSString *)_logLevelString:(CipherLogLevel)logLevel { switch (logLevel) { case CipherLogLevelNone: return @"NONE"; case CipherLogLevelError: return @"ERROR"; case CipherLogLevelWarn: return @"WARN"; case CipherLogLevelInfo: return @"INFO"; case CipherLogLevelDebug: return @"DEBUG"; case CipherLogLevelTrace: return @"TRACE"; default: return @"NONE"; } } @end ================================================ FILE: src/fmdb/FMDatabase.h ================================================ #import #import "FMResultSet.h" #import "FMDatabasePool.h" NS_ASSUME_NONNULL_BEGIN #if ! __has_feature(objc_arc) #define FMDBAutorelease(__v) ([__v autorelease]); #define FMDBReturnAutoreleased FMDBAutorelease #define FMDBRetain(__v) ([__v retain]); #define FMDBReturnRetained FMDBRetain #define FMDBRelease(__v) ([__v release]); #define FMDBDispatchQueueRelease(__v) (dispatch_release(__v)); #else // -fobjc-arc #define FMDBAutorelease(__v) #define FMDBReturnAutoreleased(__v) (__v) #define FMDBRetain(__v) #define FMDBReturnRetained(__v) (__v) #define FMDBRelease(__v) // If OS_OBJECT_USE_OBJC=1, then the dispatch objects will be treated like ObjC objects // and will participate in ARC. // See the section on "Dispatch Queues and Automatic Reference Counting" in "Grand Central Dispatch (GCD) Reference" for details. #if OS_OBJECT_USE_OBJC #define FMDBDispatchQueueRelease(__v) #else #define FMDBDispatchQueueRelease(__v) (dispatch_release(__v)); #endif #endif #if !__has_feature(objc_instancetype) #define instancetype id #endif /** Callback block used by @c executeStatements:withResultBlock: */ typedef int(^FMDBExecuteStatementsCallbackBlock)(NSDictionary *resultsDictionary); /** Enumeration used in checkpoint methods. */ typedef NS_ENUM(int, FMDBCheckpointMode) { FMDBCheckpointModePassive = 0, // SQLITE_CHECKPOINT_PASSIVE, FMDBCheckpointModeFull = 1, // SQLITE_CHECKPOINT_FULL, FMDBCheckpointModeRestart = 2, // SQLITE_CHECKPOINT_RESTART, FMDBCheckpointModeTruncate = 3 // SQLITE_CHECKPOINT_TRUNCATE }; #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wobjc-interface-ivars" /** A SQLite ([https://sqlite.org/](https://sqlite.org/)) Objective-C wrapper. Usage The three main classes in FMDB are: - @c FMDatabase - Represents a single SQLite database. Used for executing SQL statements. - @c FMResultSet - Represents the results of executing a query on an @c FMDatabase . - @c FMDatabaseQueue - If you want to perform queries and updates on multiple threads, you'll want to use this class. See also - @c FMDatabasePool - A pool of @c FMDatabase objects - @c FMStatement - A wrapper for @c sqlite_stmt External links - [FMDB on GitHub](https://github.com/ccgus/fmdb) including introductory documentation - [SQLite web site](https://sqlite.org/) - [FMDB mailing list](http://groups.google.com/group/fmdb) - [SQLite FAQ](https://sqlite.org/faq.html) @warning Do not instantiate a single @c FMDatabase object and use it across multiple threads. Instead, use @c FMDatabaseQueue . */ @interface FMDatabase : NSObject ///----------------- /// @name Properties ///----------------- /** Whether should trace execution */ @property (atomic, assign) BOOL traceExecution; /** Whether checked out or not */ @property (atomic, assign) BOOL checkedOut; /** Crash on errors */ @property (atomic, assign) BOOL crashOnErrors; /** Logs errors */ @property (atomic, assign) BOOL logsErrors; /** Dictionary of cached statements */ @property (atomic, retain, nullable) NSMutableDictionary *cachedStatements; ///--------------------- /// @name Initialization ///--------------------- /** Create a @c FMDatabase object. An @c FMDatabase is created with a path to a SQLite database file. This path can be one of these three: 1. A file system path. The file does not have to exist on disk. If it does not exist, it is created for you. 2. An zero-length string. An empty database is created at a temporary location. This database is deleted with the @c FMDatabase connection is closed. 3. @c nil . An in-memory database is created. This database will be destroyed with the @c FMDatabase connection is closed. For example, to open a database in the app's “Application Support” directory: @code NSURL *folder = [[NSFileManager defaultManager] URLForDirectory:NSApplicationSupportDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:true error:&error]; NSURL *fileURL = [folder URLByAppendingPathComponent:@"test.db"]; FMDatabase *db = [FMDatabase databaseWithPath:fileURL.path]; @endcode (For more information on temporary and in-memory databases, read the sqlite documentation on the subject: [https://sqlite.org/inmemorydb.html](https://sqlite.org/inmemorydb.html)) @param inPath Path of database file @return @c FMDatabase object if successful; @c nil if failure. */ + (instancetype)databaseWithPath:(NSString * _Nullable)inPath; /** Create a @c FMDatabase object. An @c FMDatabase is created with a path to a SQLite database file. This path can be one of these three: 1. A file system URL. The file does not have to exist on disk. If it does not exist, it is created for you. 2. @c nil . An in-memory database is created. This database will be destroyed with the @c FMDatabase connection is closed. For example, to open a database in the app's “Application Support” directory: @code NSURL *folder = [[NSFileManager defaultManager] URLForDirectory:NSApplicationSupportDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:true error:&error]; NSURL *fileURL = [folder URLByAppendingPathComponent:@"test.db"]; FMDatabase *db = [FMDatabase databaseWithURL:fileURL]; @endcode (For more information on temporary and in-memory databases, read the sqlite documentation on the subject: [https://sqlite.org/inmemorydb.html](https://sqlite.org/inmemorydb.html)) @param url The local file URL (not remote URL) of database file @return @c FMDatabase object if successful; @c nil if failure. */ + (instancetype)databaseWithURL:(NSURL * _Nullable)url; /** Initialize a @c FMDatabase object. An @c FMDatabase is created with a path to a SQLite database file. This path can be one of these three: 1. A file system path. The file does not have to exist on disk. If it does not exist, it is created for you. 2. A zero-length string. An empty database is created at a temporary location. This database is deleted with the @c FMDatabase connection is closed. 3. @c nil . An in-memory database is created. This database will be destroyed with the @c FMDatabase connection is closed. For example, to open a database in the app's “Application Support” directory: @code NSURL *folder = [[NSFileManager defaultManager] URLForDirectory:NSApplicationSupportDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:true error:&error]; NSURL *fileURL = [folder URLByAppendingPathComponent:@"test.db"]; FMDatabase *db = [[FMDatabase alloc] initWithPath:fileURL.path]; @endcode (For more information on temporary and in-memory databases, read the sqlite documentation on the subject: [https://sqlite.org/inmemorydb.html](https://sqlite.org/inmemorydb.html)) @param path Path of database file. @return @c FMDatabase object if successful; @c nil if failure. */ - (instancetype)initWithPath:(NSString * _Nullable)path; /** Initialize a @c FMDatabase object. An @c FMDatabase is created with a local file URL to a SQLite database file. This path can be one of these three: 1. A file system URL. The file does not have to exist on disk. If it does not exist, it is created for you. 2. @c nil . An in-memory database is created. This database will be destroyed with the @c FMDatabase connection is closed. For example, to open a database in the app's “Application Support” directory: @code NSURL *folder = [[NSFileManager defaultManager] URLForDirectory:NSApplicationSupportDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:true error:&error]; NSURL *fileURL = [folder URLByAppendingPathComponent:@"test.db"]; FMDatabase *db = [[FMDatabase alloc] initWithURL:fileURL]; @endcode (For more information on temporary and in-memory databases, read the sqlite documentation on the subject: [https://sqlite.org/inmemorydb.html](https://sqlite.org/inmemorydb.html)) @param url The file @c NSURL of database file. @return @c FMDatabase object if successful; @c nil if failure. */ - (instancetype)initWithURL:(NSURL * _Nullable)url; ///----------------------------------- /// @name Opening and closing database ///----------------------------------- /// Is the database open or not? @property (nonatomic) BOOL isOpen; /** Opening a new database connection The database is opened for reading and writing, and is created if it does not already exist. @return @c YES if successful, @c NO on error. @see [sqlite3_open()](https://sqlite.org/c3ref/open.html) @see openWithFlags: @see close */ - (BOOL)open; /** Opening a new database connection with flags and an optional virtual file system (VFS) @param flags One of the following three values, optionally combined with the @c SQLITE_OPEN_NOMUTEX , @c SQLITE_OPEN_FULLMUTEX , @c SQLITE_OPEN_SHAREDCACHE , @c SQLITE_OPEN_PRIVATECACHE , and/or @c SQLITE_OPEN_URI flags: @code SQLITE_OPEN_READONLY @endcode The database is opened in read-only mode. If the database does not already exist, an error is returned. @code SQLITE_OPEN_READWRITE @endcode 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. @code SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE @endcode 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 @c open method. @return @c YES if successful, @c NO on error. @see [sqlite3_open_v2()](https://sqlite.org/c3ref/open.html) @see open @see close */ - (BOOL)openWithFlags:(int)flags; /** Opening a new database connection with flags and an optional virtual file system (VFS) @param flags One of the following three values, optionally combined with the @c SQLITE_OPEN_NOMUTEX , `SQLITE_OPEN_FULLMUTEX`, `SQLITE_OPEN_SHAREDCACHE`, @c SQLITE_OPEN_PRIVATECACHE , and/or @c SQLITE_OPEN_URI flags: @code SQLITE_OPEN_READONLY @endcode The database is opened in read-only mode. If the database does not already exist, an error is returned. @code SQLITE_OPEN_READWRITE @endcode 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. @code SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE @endcode 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 @c open method. @param vfsName If vfs is given the value is passed to the vfs parameter of sqlite3_open_v2. @return @c YES if successful, @c NO on error. @see [sqlite3_open_v2()](https://sqlite.org/c3ref/open.html) @see open @see close */ - (BOOL)openWithFlags:(int)flags vfs:(NSString * _Nullable)vfsName; /** Closing a database connection @return @c YES if success, @c NO on error. @see [sqlite3_close()](https://sqlite.org/c3ref/close.html) @see open @see openWithFlags: */ - (BOOL)close; /** Test to see if we have a good connection to the database. This will confirm whether: - is database open - if open, it will try a simple @c SELECT statement and confirm that it succeeds. @return @c YES if everything succeeds, @c NO on failure. */ @property (nonatomic, readonly) BOOL goodConnection; ///---------------------- /// @name Perform updates ///---------------------- /** Execute single update statement This method executes a single SQL update statement (i.e. any SQL that does not return results, such as @c UPDATE , @c INSERT , or @c DELETE . This method employs [`sqlite3_prepare_v2`](https://sqlite.org/c3ref/prepare.html), [`sqlite3_bind`](https://sqlite.org/c3ref/bind_blob.html) to bind values to `?` placeholders in the SQL with the optional list of parameters, and [`sqlite_step`](https://sqlite.org/c3ref/step.html) to perform the update. The optional values provided to this method should be objects (e.g. @c NSString , @c NSNumber , @c NSNull , @c NSDate , and @c NSData objects), not fundamental data types (e.g. @c int , @c long , @c 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 @c description method. @param sql The SQL to be performed, with optional `?` placeholders. This can be followed by iptional parameters to bind to `?` placeholders in the SQL statement. These should be Objective-C objects (e.g. @c NSString , @c NSNumber , etc.), not fundamental C data types (e.g. @c int , etc.). @param outErr A reference to the @c NSError pointer to be updated with an auto released @c NSError object if an error if an error occurs. If @c nil , no @c NSError object will be returned. @return @c YES upon success; @c NO upon failure. If failed, you can call @c lastError , @c lastErrorCode , or @c lastErrorMessage for diagnostic information regarding the failure. @see lastError @see lastErrorCode @see lastErrorMessage @see [`sqlite3_bind`](https://sqlite.org/c3ref/bind_blob.html) */ - (BOOL)executeUpdate:(NSString*)sql withErrorAndBindings:(NSError * _Nullable __autoreleasing *)outErr, ...; /** Execute single update statement @see executeUpdate:withErrorAndBindings: @warning **Deprecated**: Please use `` instead. */ - (BOOL)update:(NSString*)sql withErrorAndBindings:(NSError * _Nullable __autoreleasing *)outErr, ... __deprecated_msg("Use executeUpdate:withErrorAndBindings: instead");; /** Execute single update statement This method executes a single SQL update statement (i.e. any SQL that does not return results, such as @c UPDATE , @c INSERT , or @c DELETE . This method employs [`sqlite3_prepare_v2`](https://sqlite.org/c3ref/prepare.html), [`sqlite3_bind`](https://sqlite.org/c3ref/bind_blob.html) to bind values to `?` placeholders in the SQL with the optional list of parameters, and [`sqlite_step`](https://sqlite.org/c3ref/step.html) to perform the update. The optional values provided to this method should be objects (e.g. @c NSString , @c NSNumber , @c NSNull , @c NSDate , and @c NSData objects), not fundamental data types (e.g. @c int , @c long , @c 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 @c description method. @param sql The SQL to be performed, with optional `?` placeholders, followed by optional parameters to bind to `?` placeholders in the SQL statement. These should be Objective-C objects (e.g. @c NSString , @c NSNumber , etc.), not fundamental C data types (e.g. @c int , etc.). @return @c YES upon success; @c NO upon failure. If failed, you can call @c lastError , @c lastErrorCode , or @c lastErrorMessage for diagnostic information regarding the failure. @see lastError @see lastErrorCode @see lastErrorMessage @see [`sqlite3_bind`](https://sqlite.org/c3ref/bind_blob.html) @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 @c stringWithFormat to manually build SQL statements, which can be problematic if the values happened to include any characters that needed to be quoted. @note You cannot use this method from Swift due to incompatibilities between Swift and Objective-C variadic implementations. Consider using `` instead. */ - (BOOL)executeUpdate:(NSString*)sql, ...; /** Execute single update statement This method executes a single SQL update statement (i.e. any SQL that does not return results, such as @c UPDATE , @c INSERT , or @c DELETE . This method employs [`sqlite3_prepare_v2`](https://sqlite.org/c3ref/prepare.html) and [`sqlite_step`](https://sqlite.org/c3ref/step.html) to perform the update. Unlike the other @c 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. @param format The SQL to be performed, with `printf`-style escape sequences, followed by optional parameters to bind to use in conjunction with the `printf`-style escape sequences in the SQL statement. @return @c YES upon success; @c NO upon failure. If failed, you can call @c lastError , @c lastErrorCode , or @c lastErrorMessage for diagnostic information regarding the failure. @see executeUpdate: @see lastError @see lastErrorCode @see lastErrorMessage @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 @code [db executeUpdateWithFormat:@"INSERT INTO test (name) VALUES (%@)", @"Gus"]; @endcode is actually replacing the `%@` with `?` placeholder, and then performing something equivalent to `` @code [db executeUpdate:@"INSERT INTO test (name) VALUES (?)", @"Gus"]; @endcode 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 @c NSString method @c stringWithFormat ), but rather simply `VALUES (%@)`. */ - (BOOL)executeUpdateWithFormat:(NSString *)format, ... NS_FORMAT_FUNCTION(1,2); /** Execute single update statement This method executes a single SQL update statement (i.e. any SQL that does not return results, such as @c UPDATE , @c INSERT , or @c DELETE . This method employs [`sqlite3_prepare_v2`](https://sqlite.org/c3ref/prepare.html) and [`sqlite3_bind`](https://sqlite.org/c3ref/bind_blob.html) binding any `?` placeholders in the SQL with the optional list of parameters. The optional values provided to this method should be objects (e.g. @c NSString , @c NSNumber , @c NSNull , @c NSDate , and @c NSData objects), not fundamental data types (e.g. @c int , @c long , @c 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 @c description method. @param sql The SQL to be performed, with optional `?` placeholders. @param arguments A @c NSArray of objects to be used when binding values to the `?` placeholders in the SQL statement. @return @c YES upon success; @c NO upon failure. If failed, you can call @c lastError , @c lastErrorCode , or @c lastErrorMessage for diagnostic information regarding the failure. @see executeUpdate:values:error: @see lastError @see lastErrorCode @see lastErrorMessage */ - (BOOL)executeUpdate:(NSString*)sql withArgumentsInArray:(NSArray *)arguments; /** Execute single update statement This method executes a single SQL update statement (i.e. any SQL that does not return results, such as @c UPDATE , @c INSERT , or @c DELETE . This method employs [`sqlite3_prepare_v2`](https://sqlite.org/c3ref/prepare.html) and [`sqlite3_bind`](https://sqlite.org/c3ref/bind_blob.html) binding any `?` placeholders in the SQL with the optional list of parameters. The optional values provided to this method should be objects (e.g. @c NSString , @c NSNumber , @c NSNull , @c NSDate , and @c NSData objects), not fundamental data types (e.g. @c int , @c long , @c 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 @c description method. This is similar to @c executeUpdate:withArgumentsInArray: , except that this also accepts a pointer to a @c NSError pointer, so that errors can be returned. In Swift, this throws errors, as if it were defined as follows: @code func executeUpdate(sql: String, values: [Any]?) throws -> Bool { } @endcode @param sql The SQL to be performed, with optional `?` placeholders. @param values A @c NSArray of objects to be used when binding values to the `?` placeholders in the SQL statement. @param error A @c NSError object to receive any error object (if any). @return @c YES upon success; @c NO upon failure. If failed, you can call @c lastError , @c lastErrorCode , or @c lastErrorMessage for diagnostic information regarding the failure. @see lastError @see lastErrorCode @see lastErrorMessage */ - (BOOL)executeUpdate:(NSString*)sql values:(NSArray * _Nullable)values error:(NSError * _Nullable __autoreleasing *)error; /** Execute single update statement This method executes a single SQL update statement (i.e. any SQL that does not return results, such as @c UPDATE , @c INSERT , or @c DELETE . This method employs [`sqlite3_prepare_v2`](https://sqlite.org/c3ref/prepare.html) and [`sqlite_step`](https://sqlite.org/c3ref/step.html) to perform the update. Unlike the other @c executeUpdate methods, this uses printf-style formatters (e.g. `%s`, `%d`, etc.) to build the SQL. The optional values provided to this method should be objects (e.g. @c NSString , @c NSNumber , @c NSNull , @c NSDate , and @c NSData objects), not fundamental data types (e.g. @c int , @c long , @c 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 @c description method. @param sql The SQL to be performed, with optional `?` placeholders. @param arguments A @c NSDictionary of objects keyed by column names that will be used when binding values to the `?` placeholders in the SQL statement. @return @c YES upon success; @c NO upon failure. If failed, you can call @c lastError , @c lastErrorCode , or @c lastErrorMessage for diagnostic information regarding the failure. @see lastError @see lastErrorCode @see lastErrorMessage */ - (BOOL)executeUpdate:(NSString*)sql withParameterDictionary:(NSDictionary *)arguments; /** Execute single update statement This method executes a single SQL update statement (i.e. any SQL that does not return results, such as @c UPDATE , @c INSERT , or @c DELETE . This method employs [`sqlite3_prepare_v2`](https://sqlite.org/c3ref/prepare.html) and [`sqlite_step`](https://sqlite.org/c3ref/step.html) to perform the update. Unlike the other @c executeUpdate methods, this uses printf-style formatters (e.g. `%s`, `%d`, etc.) to build the SQL. The optional values provided to this method should be objects (e.g. @c NSString , @c NSNumber , @c NSNull , @c NSDate , and @c NSData objects), not fundamental data types (e.g. @c int , @c long , @c 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 @c description method. @param sql The SQL to be performed, with optional `?` placeholders. @param args A `va_list` of arguments. @return @c YES upon success; @c NO upon failure. If failed, you can call @c lastError , @c lastErrorCode , or @c lastErrorMessage for diagnostic information regarding the failure. @see lastError @see lastErrorCode @see lastErrorMessage */ - (BOOL)executeUpdate:(NSString*)sql withVAList: (va_list)args; /** Execute multiple SQL statements 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 @c sqlite3_exec . @param sql The SQL to be performed @return @c YES upon success; @c NO upon failure. If failed, you can call @c lastError , @c lastErrorCode , or @c lastErrorMessage for diagnostic information regarding the failure. @see executeStatements:withResultBlock: @see [sqlite3_exec()](https://sqlite.org/c3ref/exec.html) */ - (BOOL)executeStatements:(NSString *)sql; /** Execute multiple SQL statements with callback handler 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`. @param sql The SQL to be performed. @param block A block that will be called for any result sets returned by any SQL statements. Note, if you supply this block, it must return integer value, zero upon success (this would be a good opportunity to use @c SQLITE_OK ), 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. This may be @c nil if you don't care to receive any results. @return @c YES upon success; @c NO upon failure. If failed, you can call @c lastError , @c lastErrorCode , or @c lastErrorMessage for diagnostic information regarding the failure. @see executeStatements: @see [sqlite3_exec()](https://sqlite.org/c3ref/exec.html) */ - (BOOL)executeStatements:(NSString *)sql withResultBlock:(__attribute__((noescape)) FMDBExecuteStatementsCallbackBlock _Nullable)block; /** Last insert rowid 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. This routine returns the rowid of the most recent successful @c 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 @c INSERT statements have ever occurred on that database connection, zero is returned. @return The rowid of the last inserted row. @see [sqlite3_last_insert_rowid()](https://sqlite.org/c3ref/last_insert_rowid.html) */ @property (nonatomic, readonly) int64_t lastInsertRowId; /** The number of rows changed by prior SQL statement. 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 @c INSERT , @c UPDATE , or @c DELETE statement are counted. @return The number of rows changed by prior SQL statement. @see [sqlite3_changes()](https://sqlite.org/c3ref/changes.html) */ @property (nonatomic, readonly) int changes; ///------------------------- /// @name Retrieving results ///------------------------- /** Execute select statement Executing queries returns an @c FMResultSet object if successful, and @c nil upon failure. Like executing updates, there is a variant that accepts an `NSError **` parameter. Otherwise you should use the @c lastErrorMessage and @c lastErrorMessage methods to determine why a query failed. 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. This method employs [`sqlite3_bind`](https://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 @c NSString , @c NSNumber , @c NSNull , @c NSDate , and @c NSData objects. All other object types will be interpreted as text values using the object's @c description method. @param sql The SELECT statement to be performed, with optional `?` placeholders, followed by optional parameters to bind to `?` placeholders in the SQL statement. These should be Objective-C objects (e.g. @c NSString , @c NSNumber , etc.), not fundamental C data types (e.g. @c int , etc.). @return A @c FMResultSet for the result set upon success; @c nil upon failure. If failed, you can call @c lastError , @c lastErrorCode , or @c lastErrorMessage for diagnostic information regarding the failure. @see FMResultSet @see [`FMResultSet next`](<[FMResultSet next]>) @see [`sqlite3_bind`](https://sqlite.org/c3ref/bind_blob.html) @note You cannot use this method from Swift due to incompatibilities between Swift and Objective-C variadic implementations. Consider using `` instead. */ - (FMResultSet * _Nullable)executeQuery:(NSString*)sql, ...; /** Execute select statement Executing queries returns an @c FMResultSet object if successful, and @c nil upon failure. Like executing updates, there is a variant that accepts an `NSError **` parameter. Otherwise you should use the @c lastErrorMessage and @c lastErrorMessage methods to determine why a query failed. 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. @param format The SQL to be performed, with `printf`-style escape sequences, followed by ptional parameters to bind to use in conjunction with the `printf`-style escape sequences in the SQL statement. @return A @c FMResultSet for the result set upon success; @c nil upon failure. If failed, you can call @c lastError , @c lastErrorCode , or @c lastErrorMessage for diagnostic information regarding the failure. @see executeQuery: @see FMResultSet @see [`FMResultSet next`](<[FMResultSet next]>) @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 @code [db executeQueryWithFormat:@"SELECT * FROM test WHERE name=%@", @"Gus"]; @endcode is actually replacing the `%@` with `?` placeholder, and then performing something equivalent to `` @code [db executeQuery:@"SELECT * FROM test WHERE name=?", @"Gus"]; @endcode 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 @c WHERE clause was _not_ `WHERE name='%@'` (like you might have to do if you built a SQL statement using @c NSString method @c stringWithFormat ), but rather simply `WHERE name=%@`. */ - (FMResultSet * _Nullable)executeQueryWithFormat:(NSString*)format, ... NS_FORMAT_FUNCTION(1,2); /** Execute select statement Executing queries returns an @c FMResultSet object if successful, and @c nil upon failure. Like executing updates, there is a variant that accepts an `NSError **` parameter. Otherwise you should use the @c lastErrorMessage and @c lastErrorMessage methods to determine why a query failed. 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. @param sql The SELECT statement to be performed, with optional `?` placeholders. @param arguments A @c NSArray of objects to be used when binding values to the `?` placeholders in the SQL statement. @return A @c FMResultSet for the result set upon success; @c nil upon failure. If failed, you can call @c lastError , @c lastErrorCode , or @c lastErrorMessage for diagnostic information regarding the failure. @see -executeQuery:values:error: @see FMResultSet @see [`FMResultSet next`](<[FMResultSet next]>) */ - (FMResultSet * _Nullable)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray *)arguments; /** Execute select statement Executing queries returns an @c FMResultSet object if successful, and @c nil upon failure. Like executing updates, there is a variant that accepts an `NSError **` parameter. Otherwise you should use the @c lastErrorMessage and @c lastErrorMessage methods to determine why a query failed. 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. This is similar to ``, except that this also accepts a pointer to a @c NSError pointer, so that errors can be returned. In Swift, this throws errors, as if it were defined as follows: `func executeQuery(sql: String, values: [Any]?) throws -> FMResultSet!` @param sql The SELECT statement to be performed, with optional `?` placeholders. @param values A @c NSArray of objects to be used when binding values to the `?` placeholders in the SQL statement. @param error A @c NSError object to receive any error object (if any). @return A @c FMResultSet for the result set upon success; @c nil upon failure. If failed, you can call @c lastError , @c lastErrorCode , or @c lastErrorMessage for diagnostic information regarding the failure. @see FMResultSet @see [`FMResultSet next`](<[FMResultSet next]>) @note When called from Swift, only use the first two parameters, `sql` and `values`. This but throws the error. */ - (FMResultSet * _Nullable)executeQuery:(NSString *)sql values:(NSArray * _Nullable)values error:(NSError * _Nullable __autoreleasing *)error; /** Execute select statement Executing queries returns an @c FMResultSet object if successful, and @c nil upon failure. Like executing updates, there is a variant that accepts an `NSError **` parameter. Otherwise you should use the @c lastErrorMessage and @c lastErrorMessage methods to determine why a query failed. 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. @param sql The SELECT statement to be performed, with optional `?` placeholders. @param arguments A @c NSDictionary of objects keyed by column names that will be used when binding values to the `?` placeholders in the SQL statement. @return A @c FMResultSet for the result set upon success; @c nil upon failure. If failed, you can call @c lastError , @c lastErrorCode , or @c lastErrorMessage for diagnostic information regarding the failure. @see FMResultSet @see [`FMResultSet next`](<[FMResultSet next]>) */ - (FMResultSet * _Nullable)executeQuery:(NSString *)sql withParameterDictionary:(NSDictionary * _Nullable)arguments; // Documentation forthcoming. - (FMResultSet * _Nullable)executeQuery:(NSString *)sql withVAList:(va_list)args; /// Prepare SQL statement. /// /// @param sql SQL statement to prepare, generally with `?` placeholders. - (FMResultSet *)prepare:(NSString *)sql; ///------------------- /// @name Transactions ///------------------- /** Begin a transaction @return @c YES on success; @c NO on failure. If failed, you can call @c lastError , @c lastErrorCode , or @c lastErrorMessage for diagnostic information regarding the failure. @see commit @see rollback @see beginDeferredTransaction @see isInTransaction @warning Unlike SQLite's `BEGIN TRANSACTION`, this method currently performs an exclusive transaction, not a deferred transaction. This behavior is likely to change in future versions of FMDB, whereby this method will likely eventually adopt standard SQLite behavior and perform deferred transactions. If you really need exclusive tranaction, it is recommended that you use @c beginExclusiveTransaction, instead, not only to make your intent explicit, but also to future-proof your code. */ - (BOOL)beginTransaction; /** Begin a deferred transaction @return @c YES on success; @c NO on failure. If failed, you can call @c lastError , @c lastErrorCode , or @c lastErrorMessage for diagnostic information regarding the failure. @see commit @see rollback @see beginTransaction @see isInTransaction */ - (BOOL)beginDeferredTransaction; /** Begin an immediate transaction @return @c YES on success; @c NO on failure. If failed, you can call @c lastError , @c lastErrorCode , or @c lastErrorMessage for diagnostic information regarding the failure. @see commit @see rollback @see beginTransaction @see isInTransaction */ - (BOOL)beginImmediateTransaction; /** Begin an exclusive transaction @return @c YES on success; @c NO on failure. If failed, you can call @c lastError , @c lastErrorCode , or @c lastErrorMessage for diagnostic information regarding the failure. @see commit @see rollback @see beginTransaction @see isInTransaction */ - (BOOL)beginExclusiveTransaction; /** Commit a transaction Commit a transaction that was initiated with either `` or with ``. @return @c YES on success; @c NO on failure. If failed, you can call @c lastError , @c lastErrorCode , or @c lastErrorMessage for diagnostic information regarding the failure. @see beginTransaction @see beginDeferredTransaction @see rollback @see isInTransaction */ - (BOOL)commit; /** Rollback a transaction Rollback a transaction that was initiated with either `` or with ``. @return @c YES on success; @c NO on failure. If failed, you can call @c lastError , @c lastErrorCode , or @c lastErrorMessage for diagnostic information regarding the failure. @see beginTransaction @see beginDeferredTransaction @see commit @see isInTransaction */ - (BOOL)rollback; /** Identify whether currently in a transaction or not @see beginTransaction @see beginDeferredTransaction @see commit @see rollback */ @property (nonatomic, readonly) BOOL isInTransaction; - (BOOL)inTransaction __deprecated_msg("Use isInTransaction property instead"); ///---------------------------------------- /// @name Cached statements and result sets ///---------------------------------------- /** Clear cached statements */ - (void)clearCachedStatements; /** Close all open result sets */ - (void)closeOpenResultSets; /** Whether database has any open result sets @return @c YES if there are open result sets; @c NO if not. */ @property (nonatomic, readonly) BOOL hasOpenResultSets; /** Whether should cache statements or not */ @property (nonatomic) BOOL shouldCacheStatements; /** Interupt pending database operation This method causes any pending database operation to abort and return at its earliest opportunity @return @c YES on success; @c NO on failure. If failed, you can call @c lastError , @c lastErrorCode , or @c lastErrorMessage for diagnostic information regarding the failure. */ - (BOOL)interrupt; ///------------------------------ /// @name General inquiry methods ///------------------------------ /** The path of the database file. */ @property (nonatomic, readonly, nullable) NSString *databasePath; /** The file URL of the database file. */ @property (nonatomic, readonly, nullable) NSURL *databaseURL; /** The underlying SQLite handle . @return The `sqlite3` pointer. */ @property (nonatomic, readonly) void *sqliteHandle; ///----------------------------- /// @name Retrieving error codes ///----------------------------- /** Last error message 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. @return @c NSString of the last error message. @see [sqlite3_errmsg()](https://sqlite.org/c3ref/errcode.html) @see lastErrorCode @see lastError */ - (NSString*)lastErrorMessage; /** Last error code 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. @return Integer value of the last error code. @see [sqlite3_errcode()](https://sqlite.org/c3ref/errcode.html) @see lastErrorMessage @see lastError */ - (int)lastErrorCode; /** Last extended error code Returns the numeric 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. @return Integer value of the last extended error code. @see [sqlite3_errcode()](https://sqlite.org/c3ref/errcode.html) @see [2. Primary Result Codes versus Extended Result Codes](https://sqlite.org/rescode.html#primary_result_codes_versus_extended_result_codes) @see [5. Extended Result Code List](https://sqlite.org/rescode.html#extrc) @see lastErrorMessage @see lastError */ - (int)lastExtendedErrorCode; /** Had error @return @c YES if there was an error, @c NO if no error. @see lastError @see lastErrorCode @see lastErrorMessage */ - (BOOL)hadError; /** Last error @return @c NSError representing the last error. @see lastErrorCode @see lastErrorMessage */ - (NSError *)lastError; // description forthcoming @property (nonatomic) NSTimeInterval maxBusyRetryTimeInterval; ///------------------ /// @name Save points ///------------------ /** Start save point @param name Name of save point. @param outErr A @c NSError object to receive any error object (if any). @return @c YES on success; @c NO on failure. If failed, you can call @c lastError , @c lastErrorCode , or @c lastErrorMessage for diagnostic information regarding the failure. @see releaseSavePointWithName:error: @see rollbackToSavePointWithName:error: */ - (BOOL)startSavePointWithName:(NSString*)name error:(NSError * _Nullable __autoreleasing *)outErr; /** Release save point @param name Name of save point. @param outErr A @c NSError object to receive any error object (if any). @return @c YES on success; @c NO on failure. If failed, you can call @c lastError , @c lastErrorCode , or @c lastErrorMessage for diagnostic information regarding the failure. @see startSavePointWithName:error: @see rollbackToSavePointWithName:error: */ - (BOOL)releaseSavePointWithName:(NSString*)name error:(NSError * _Nullable __autoreleasing *)outErr; /** Roll back to save point @param name Name of save point. @param outErr A @c NSError object to receive any error object (if any). @return @c YES on success; @c NO on failure. If failed, you can call @c lastError , @c lastErrorCode , or @c lastErrorMessage for diagnostic information regarding the failure. @see startSavePointWithName:error: @see releaseSavePointWithName:error: */ - (BOOL)rollbackToSavePointWithName:(NSString*)name error:(NSError * _Nullable __autoreleasing *)outErr; /** Start save point @param block Block of code to perform from within save point. @return The NSError corresponding to the error, if any. If no error, returns @c nil . @see startSavePointWithName:error: @see releaseSavePointWithName:error: @see rollbackToSavePointWithName:error: */ - (NSError * _Nullable)inSavePoint:(__attribute__((noescape)) void (^)(BOOL *rollback))block; ///----------------- /// @name Checkpoint ///----------------- /** Performs a WAL checkpoint @param checkpointMode The checkpoint mode for @c sqlite3_wal_checkpoint_v2 @param error The @c NSError corresponding to the error, if any. @return @c YES on success, otherwise @c NO . */ - (BOOL)checkpoint:(FMDBCheckpointMode)checkpointMode error:(NSError * _Nullable *)error; /** Performs a WAL checkpoint @param checkpointMode The checkpoint mode for @c sqlite3_wal_checkpoint_v2 @param name The db name for @c sqlite3_wal_checkpoint_v2 @param error The @c NSError corresponding to the error, if any. @return @c YES on success, otherwise @c NO . */ - (BOOL)checkpoint:(FMDBCheckpointMode)checkpointMode name:(NSString * _Nullable)name error:(NSError * _Nullable *)error; /** Performs a WAL checkpoint @param checkpointMode The checkpoint mode for sqlite3_wal_checkpoint_v2 @param name The db name for sqlite3_wal_checkpoint_v2 @param error The NSError corresponding to the error, if any. @param logFrameCount If not @c NULL , then this is set to the total number of frames in the log file or to -1 if the checkpoint could not run because of an error or because the database is not in WAL mode. @param checkpointCount If not @c NULL , then this is set to the total number of checkpointed frames in the log file (including any that were already checkpointed before the function was called) or to -1 if the checkpoint could not run due to an error or because the database is not in WAL mode. @return @c YES on success, otherwise @c NO . */ - (BOOL)checkpoint:(FMDBCheckpointMode)checkpointMode name:(NSString * _Nullable)name logFrameCount:(int * _Nullable)logFrameCount checkpointCount:(int * _Nullable)checkpointCount error:(NSError * _Nullable *)error; ///---------------------------- /// @name SQLite library status ///---------------------------- /** Test to see if the library is threadsafe @return @c NO if and only if SQLite was compiled with mutexing code omitted due to the @c SQLITE_THREADSAFE compile-time option being set to 0. @see [sqlite3_threadsafe()](https://sqlite.org/c3ref/threadsafe.html) */ + (BOOL)isSQLiteThreadSafe; /** Examine/set limits @param type The type of limit. See https://sqlite.org/c3ref/c_limit_attached.html @param newLimit The new limit value. Use -1 if you don't want to change the limit, but rather only want to check it. @return Regardless, returns previous value. @see [sqlite3_limit()](https://sqlite.org/c3ref/limit.html) */ - (int)limitFor:(int)type value:(int)newLimit; /** Run-time library version numbers @return The sqlite library version string. @see [sqlite3_libversion()](https://sqlite.org/c3ref/libversion.html) */ + (NSString*)sqliteLibVersion; /// The FMDB version number as a string in the form of @c "2.7.12" . /// /// If you want to compare version number strings, you can use NSNumericSearch option: /// /// @code /// NSComparisonResult result = [[FMDatabase FMDBUserVersion] compare:@"2.11.0" options:NSNumericSearch]; /// @endcode /// /// @returns The version number string. + (NSString*)FMDBUserVersion; /** The FMDB version This returns the FMDB as hexadecimal value, e.g., @c 0x0243 for version 2.4.3. @warning This routine will not work if any component of the version number exceeds 15. For example, if it is version @c 2.17.3 , this will max out at @c 0x2f3. For this reason, we would recommend using @c FMDBUserVersion and with @c NSNumericSearch option, e.g. @code NSComparisonResult result = [[FMDatabase FMDBUserVersion] compare:@"2.11.0" options:NSNumericSearch]; @endcode @returns The version number in hexadecimal, e.g., @c 0x0243 for version 2.4.3. If any component exceeds what can be can be represented in four bits, we'll max it out at @c 0xf . */ + (SInt32)FMDBVersion __deprecated_msg("Use FMDBUserVersion instead"); ///------------------------ /// @name Make SQL function ///------------------------ /** Adds SQL functions or aggregates or to redefine the behavior of existing SQL functions or aggregates. For example: @code [db makeFunctionNamed:@"RemoveDiacritics" arguments:1 block:^(void *context, int argc, void **argv) { SqliteValueType type = [self.db valueType:argv[0]]; if (type == SqliteValueTypeNull) { [self.db resultNullInContext:context]; return; } if (type != SqliteValueTypeText) { [self.db resultError:@"Expected text" context:context]; return; } NSString *string = [self.db valueString:argv[0]]; NSString *result = [string stringByFoldingWithOptions:NSDiacriticInsensitiveSearch locale:nil]; [self.db resultString:result context:context]; }]; FMResultSet *rs = [db executeQuery:@"SELECT * FROM employees WHERE RemoveDiacritics(first_name) LIKE 'jose'"]; NSAssert(rs, @"Error %@", [db lastErrorMessage]); @endcode @param name Name of function. @param arguments Maximum number of parameters. @param block The block of code for the function. @see [sqlite3_create_function()](https://sqlite.org/c3ref/create_function.html) */ - (void)makeFunctionNamed:(NSString *)name arguments:(int)arguments block:(void (^)(void *context, int argc, void * _Nonnull * _Nonnull argv))block; - (void)makeFunctionNamed:(NSString *)name maximumArguments:(int)count withBlock:(void (^)(void *context, int argc, void * _Nonnull * _Nonnull argv))block __deprecated_msg("Use makeFunctionNamed:arguments:block:"); - (SqliteValueType)valueType:(void *)argv; /** Get integer value of parameter in custom function. @param value The argument whose value to return. @return The integer value. @see makeFunctionNamed:arguments:block: */ - (int)valueInt:(void *)value; /** Get long value of parameter in custom function. @param value The argument whose value to return. @return The long value. @see makeFunctionNamed:arguments:block: */ - (long long)valueLong:(void *)value; /** Get double value of parameter in custom function. @param value The argument whose value to return. @return The double value. @see makeFunctionNamed:arguments:block: */ - (double)valueDouble:(void *)value; /** Get @c NSData value of parameter in custom function. @param value The argument whose value to return. @return The data object. @see makeFunctionNamed:arguments:block: */ - (NSData * _Nullable)valueData:(void *)value; /** Get string value of parameter in custom function. @param value The argument whose value to return. @return The string value. @see makeFunctionNamed:arguments:block: */ - (NSString * _Nullable)valueString:(void *)value; /** Return null value from custom function. @param context The context to which the null value will be returned. @see makeFunctionNamed:arguments:block: */ - (void)resultNullInContext:(void *)context NS_SWIFT_NAME(resultNull(context:)); /** Return integer value from custom function. @param value The integer value to be returned. @param context The context to which the value will be returned. @see makeFunctionNamed:arguments:block: */ - (void)resultInt:(int) value context:(void *)context; /** Return long value from custom function. @param value The long value to be returned. @param context The context to which the value will be returned. @see makeFunctionNamed:arguments:block: */ - (void)resultLong:(long long)value context:(void *)context; /** Return double value from custom function. @param value The double value to be returned. @param context The context to which the value will be returned. @see makeFunctionNamed:arguments:block: */ - (void)resultDouble:(double)value context:(void *)context; /** Return @c NSData object from custom function. @param data The @c NSData object to be returned. @param context The context to which the value will be returned. @see makeFunctionNamed:arguments:block: */ - (void)resultData:(NSData *)data context:(void *)context; /** Return string value from custom function. @param value The string value to be returned. @param context The context to which the value will be returned. @see makeFunctionNamed:arguments:block: */ - (void)resultString:(NSString *)value context:(void *)context; /** Return error string from custom function. @param error The error string to be returned. @param context The context to which the error will be returned. @see makeFunctionNamed:arguments:block: */ - (void)resultError:(NSString *)error context:(void *)context; /** Return error code from custom function. @param errorCode The integer error code to be returned. @param context The context to which the error will be returned. @see makeFunctionNamed:arguments:block: */ - (void)resultErrorCode:(int)errorCode context:(void *)context; /** Report memory error in custom function. @param context The context to which the error will be returned. @see makeFunctionNamed:arguments:block: */ - (void)resultErrorNoMemoryInContext:(void *)context NS_SWIFT_NAME(resultErrorNoMemory(context:)); /** Report that string or BLOB is too long to represent in custom function. @param context The context to which the error will be returned. @see makeFunctionNamed:arguments:block: */ - (void)resultErrorTooBigInContext:(void *)context NS_SWIFT_NAME(resultErrorTooBig(context:)); ///--------------------- /// @name Date formatter ///--------------------- /** Generate an @c NSDateFormatter that won't be broken by permutations of timezones or locales. Use this method to generate values to set the dateFormat property. Example: @code myDB.dateFormat = [FMDatabase storeableDateFormat:@"yyyy-MM-dd HH:mm:ss"]; @endcode @param format A valid NSDateFormatter format string. @return A @c NSDateFormatter that can be used for converting dates to strings and vice versa. @see hasDateFormatter @see setDateFormat: @see dateFromString: @see stringFromDate: @see storeableDateFormat: @warning Note that @c 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. */ + (NSDateFormatter *)storeableDateFormat:(NSString *)format; /** Test whether the database has a date formatter assigned. @return @c YES if there is a date formatter; @c NO if not. @see hasDateFormatter @see setDateFormat: @see dateFromString: @see stringFromDate: @see storeableDateFormat: */ - (BOOL)hasDateFormatter; /** Set to a date formatter to use string dates with sqlite instead of the default UNIX timestamps. @param format Set to nil to use UNIX timestamps. Defaults to nil. Should be set using a formatter generated using @c FMDatabase:storeableDateFormat . @see hasDateFormatter @see setDateFormat: @see dateFromString: @see stringFromDate: @see storeableDateFormat: @warning Note there is no direct getter for the @c NSDateFormatter , and you should not use the formatter you pass to FMDB for other purposes, as @c NSDateFormatter is not thread-safe. */ - (void)setDateFormat:(NSDateFormatter * _Nullable)format; /** Convert the supplied NSString to NSDate, using the current database formatter. @param s @c NSString to convert to @c NSDate . @return The @c NSDate object; or @c nil if no formatter is set. @see hasDateFormatter @see setDateFormat: @see dateFromString: @see stringFromDate: @see storeableDateFormat: */ - (NSDate * _Nullable)dateFromString:(NSString *)s; /** Convert the supplied NSDate to NSString, using the current database formatter. @param date @c NSDate of date to convert to @c NSString . @return The @c NSString representation of the date; @c nil if no formatter is set. @see hasDateFormatter @see setDateFormat: @see dateFromString: @see stringFromDate: @see storeableDateFormat: */ - (NSString * _Nullable)stringFromDate:(NSDate *)date; @end /** Objective-C wrapper for @c sqlite3_stmt This is a wrapper for a SQLite @c sqlite3_stmt . Generally when using FMDB you will not need to interact directly with `FMStatement`, but rather with @c FMDatabase and @c FMResultSet only. See also - @c FMDatabase - @c FMResultSet - [@c sqlite3_stmt ](https://sqlite.org/c3ref/stmt.html) */ @interface FMStatement : NSObject { void *_statement; NSString *_query; long _useCount; BOOL _inUse; } ///----------------- /// @name Properties ///----------------- /** Usage count */ @property (atomic, assign) long useCount; /** SQL statement */ @property (atomic, retain) NSString *query; /** SQLite sqlite3_stmt @see [@c sqlite3_stmt ](https://sqlite.org/c3ref/stmt.html) */ @property (atomic, assign) void *statement; /** Indication of whether the statement is in use */ @property (atomic, assign) BOOL inUse; ///---------------------------- /// @name Closing and Resetting ///---------------------------- /** Close statement */ - (void)close; /** Reset statement */ - (void)reset; @end #pragma clang diagnostic pop NS_ASSUME_NONNULL_END ================================================ FILE: src/fmdb/FMDatabase.m ================================================ #import "FMDatabase.h" #import #import #if FMDB_SQLITE_STANDALONE #import #elif SQLCIPHER_CRYPTO #import #import "FMDatabase+SQLCipher.h" #else #import #endif // MARK: - FMDatabase Private Extension NS_ASSUME_NONNULL_BEGIN @interface FMDatabase () { void* _db; BOOL _isExecutingStatement; NSTimeInterval _startBusyRetryTime; NSMutableSet *_openResultSets; NSMutableSet *_openFunctions; NSDateFormatter *_dateFormat; } - (FMResultSet * _Nullable)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray * _Nullable)arrayArgs orDictionary:(NSDictionary * _Nullable)dictionaryArgs orVAList:(va_list)args shouldBind:(BOOL)shouldBind; - (BOOL)executeUpdate:(NSString *)sql error:(NSError * _Nullable __autoreleasing *)outErr withArgumentsInArray:(NSArray * _Nullable)arrayArgs orDictionary:(NSDictionary * _Nullable)dictionaryArgs orVAList:(va_list)args; @end // MARK: - FMResultSet Private Extension @interface FMResultSet () - (int)internalStepWithError:(NSError * _Nullable __autoreleasing *)outErr; + (instancetype)resultSetWithStatement:(FMStatement *)statement usingParentDatabase:(FMDatabase*)aDB shouldAutoClose:(BOOL)shouldAutoClose; @end NS_ASSUME_NONNULL_END // MARK: - FMDatabase @implementation FMDatabase // Because these two properties have all of their accessor methods implemented, // we have to synthesize them to get the corresponding ivars. The rest of the // properties have their ivars synthesized automatically for us. @synthesize shouldCacheStatements = _shouldCacheStatements; @synthesize maxBusyRetryTimeInterval = _maxBusyRetryTimeInterval; #pragma mark FMDatabase instantiation and deallocation + (instancetype)databaseWithPath:(NSString *)aPath { return FMDBReturnAutoreleased([[self alloc] initWithPath:aPath]); } + (instancetype)databaseWithURL:(NSURL *)url { return FMDBReturnAutoreleased([[self alloc] initWithURL:url]); } - (instancetype)init { return [self initWithPath:nil]; } - (instancetype)initWithURL:(NSURL *)url { return [self initWithPath:url.path]; } - (instancetype)initWithPath:(NSString *)path { assert(sqlite3_threadsafe()); // whoa there big boy- gotta make sure sqlite it happy with what we're going to do. self = [super init]; if (self) { _databasePath = [path copy]; _openResultSets = [[NSMutableSet alloc] init]; _db = nil; _logsErrors = YES; _crashOnErrors = NO; _maxBusyRetryTimeInterval = 2; _isOpen = NO; } return self; } #if ! __has_feature(objc_arc) - (void)finalize { [self close]; [super finalize]; } #endif - (void)dealloc { [self close]; FMDBRelease(_openResultSets); FMDBRelease(_cachedStatements); FMDBRelease(_dateFormat); FMDBRelease(_databasePath); FMDBRelease(_openFunctions); #if ! __has_feature(objc_arc) [super dealloc]; #endif } - (NSURL *)databaseURL { return _databasePath ? [NSURL fileURLWithPath:_databasePath] : nil; } + (NSString*)FMDBUserVersion { return @"2.7.12"; } + (SInt32)FMDBVersion { // we go through these hoops so that we only have to change the version number in a single spot. static dispatch_once_t once; static SInt32 FMDBVersionVal = 0; dispatch_once(&once, ^{ NSString *prodVersion = [self FMDBUserVersion]; while ([[prodVersion componentsSeparatedByString:@"."] count] < 3) { prodVersion = [prodVersion stringByAppendingString:@".0"]; } NSArray *components = [prodVersion componentsSeparatedByString:@"."]; for (NSUInteger i = 0; i < 3; i++) { SInt32 component = [components[i] intValue]; if (component > 15) { NSLog(@"FMDBVersion is invalid: Please use FMDBUserVersion instead."); component = 15; } FMDBVersionVal = FMDBVersionVal << 4 | component; } }); return FMDBVersionVal; } #pragma mark SQLite information + (NSString*)sqliteLibVersion { return [NSString stringWithFormat:@"%s", sqlite3_libversion()]; } + (BOOL)isSQLiteThreadSafe { // make sure to read the sqlite headers on this guy! return sqlite3_threadsafe() != 0; } - (void*)sqliteHandle { return _db; } - (const char*)sqlitePath { if (!_databasePath) { return ":memory:"; } if ([_databasePath length] == 0) { return ""; // this creates a temporary database (it's an sqlite thing). } return [_databasePath fileSystemRepresentation]; } - (int)limitFor:(int)type value:(int)newLimit { return sqlite3_limit(_db, type, newLimit); } #pragma mark Open and close database - (BOOL)open { if (_isOpen) { return YES; } // if we previously tried to open and it failed, make sure to close it before we try again if (_db) { [self close]; } // now open database int err = sqlite3_open([self sqlitePath], (sqlite3**)&_db ); if(err != SQLITE_OK) { NSLog(@"error opening!: %d", err); return NO; } if (_maxBusyRetryTimeInterval > 0.0) { // set the handler [self setMaxBusyRetryTimeInterval:_maxBusyRetryTimeInterval]; } _isOpen = YES; return YES; } - (BOOL)openWithFlags:(int)flags { return [self openWithFlags:flags vfs:nil]; } - (BOOL)openWithFlags:(int)flags vfs:(NSString *)vfsName { #if SQLITE_VERSION_NUMBER >= 3005000 if (_isOpen) { return YES; } // if we previously tried to open and it failed, make sure to close it before we try again if (_db) { [self close]; } // now open database int err = sqlite3_open_v2([self sqlitePath], (sqlite3**)&_db, flags, [vfsName UTF8String]); if(err != SQLITE_OK) { NSLog(@"error opening!: %d", err); return NO; } if (_maxBusyRetryTimeInterval > 0.0) { // set the handler [self setMaxBusyRetryTimeInterval:_maxBusyRetryTimeInterval]; } _isOpen = YES; return YES; #else NSLog(@"openWithFlags requires SQLite 3.5"); return NO; #endif } - (BOOL)close { [self clearCachedStatements]; [self closeOpenResultSets]; if (!_db) { return YES; } int rc; BOOL retry; BOOL triedFinalizingOpenStatements = NO; do { retry = NO; rc = sqlite3_close(_db); if (SQLITE_BUSY == rc || SQLITE_LOCKED == rc) { if (!triedFinalizingOpenStatements) { triedFinalizingOpenStatements = YES; sqlite3_stmt *pStmt; while ((pStmt = sqlite3_next_stmt(_db, nil)) !=0) { NSLog(@"Closing leaked statement"); sqlite3_finalize(pStmt); pStmt = 0x00; retry = YES; } } } else if (SQLITE_OK != rc) { NSLog(@"error closing!: %d", rc); } } while (retry); _db = nil; _isOpen = false; return YES; } #pragma mark Busy handler routines // NOTE: appledoc seems to choke on this function for some reason; // so when generating documentation, you might want to ignore the // .m files so that it only documents the public interfaces outlined // in the .h files. // // This is a known appledoc bug that it has problems with C functions // within a class implementation, but for some reason, only this // C function causes problems; the rest don't. Anyway, ignoring the .m // files with appledoc will prevent this problem from occurring. static int FMDBDatabaseBusyHandler(void *f, int count) { FMDatabase *self = (__bridge FMDatabase*)f; if (count == 0) { self->_startBusyRetryTime = [NSDate timeIntervalSinceReferenceDate]; return 1; } NSTimeInterval delta = [NSDate timeIntervalSinceReferenceDate] - (self->_startBusyRetryTime); if (delta < [self maxBusyRetryTimeInterval]) { int requestedSleepInMillseconds = (int) arc4random_uniform(50) + 50; int actualSleepInMilliseconds = sqlite3_sleep(requestedSleepInMillseconds); if (actualSleepInMilliseconds != requestedSleepInMillseconds) { NSLog(@"WARNING: Requested sleep of %i milliseconds, but SQLite returned %i. Maybe SQLite wasn't built with HAVE_USLEEP=1?", requestedSleepInMillseconds, actualSleepInMilliseconds); } return 1; } return 0; } - (void)setMaxBusyRetryTimeInterval:(NSTimeInterval)timeout { _maxBusyRetryTimeInterval = timeout; if (!_db) { return; } if (timeout > 0) { sqlite3_busy_handler(_db, &FMDBDatabaseBusyHandler, (__bridge void *)(self)); } else { // turn it off otherwise sqlite3_busy_handler(_db, nil, nil); } } - (NSTimeInterval)maxBusyRetryTimeInterval { return _maxBusyRetryTimeInterval; } // we no longer make busyRetryTimeout public // but for folks who don't bother noticing that the interface to FMDatabase changed, // we'll still implement the method so they don't get suprise crashes - (int)busyRetryTimeout { NSLog(@"%s:%d", __FUNCTION__, __LINE__); NSLog(@"FMDB: busyRetryTimeout no longer works, please use maxBusyRetryTimeInterval"); return -1; } - (void)setBusyRetryTimeout:(int)i { #pragma unused(i) NSLog(@"%s:%d", __FUNCTION__, __LINE__); NSLog(@"FMDB: setBusyRetryTimeout does nothing, please use setMaxBusyRetryTimeInterval:"); } #pragma mark Result set functions - (BOOL)hasOpenResultSets { return [_openResultSets count] > 0; } - (void)closeOpenResultSets { //Copy the set so we don't get mutation errors NSSet *openSetCopy = FMDBReturnAutoreleased([_openResultSets copy]); for (NSValue *rsInWrappedInATastyValueMeal in openSetCopy) { FMResultSet *rs = (FMResultSet *)[rsInWrappedInATastyValueMeal pointerValue]; [rs setParentDB:nil]; [rs close]; [_openResultSets removeObject:rsInWrappedInATastyValueMeal]; } } - (void)resultSetDidClose:(FMResultSet *)resultSet { NSValue *setValue = [NSValue valueWithNonretainedObject:resultSet]; [_openResultSets removeObject:setValue]; } #pragma mark Cached statements - (void)clearCachedStatements { for (NSMutableSet *statements in [_cachedStatements objectEnumerator]) { for (FMStatement *statement in [statements allObjects]) { [statement close]; } } [_cachedStatements removeAllObjects]; } - (FMStatement*)cachedStatementForQuery:(NSString*)query { NSMutableSet* statements = [_cachedStatements objectForKey:query]; return [[statements objectsPassingTest:^BOOL(FMStatement* statement, BOOL *stop) { *stop = ![statement inUse]; return *stop; }] anyObject]; } - (void)setCachedStatement:(FMStatement*)statement forQuery:(NSString*)query { NSParameterAssert(query); if (!query) { NSLog(@"API misuse, -[FMDatabase setCachedStatement:forQuery:] query must not be nil"); return; } query = [query copy]; // in case we got handed in a mutable string... [statement setQuery:query]; NSMutableSet* statements = [_cachedStatements objectForKey:query]; if (!statements) { statements = [NSMutableSet set]; } [statements addObject:statement]; [_cachedStatements setObject:statements forKey:query]; FMDBRelease(query); } #pragma mark Date routines + (NSDateFormatter *)storeableDateFormat:(NSString *)format { NSDateFormatter *result = FMDBReturnAutoreleased([[NSDateFormatter alloc] init]); result.dateFormat = format; result.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0]; result.locale = FMDBReturnAutoreleased([[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]); return result; } - (BOOL)hasDateFormatter { return _dateFormat != nil; } - (void)setDateFormat:(NSDateFormatter *)format { FMDBAutorelease(_dateFormat); _dateFormat = FMDBReturnRetained(format); } - (NSDate *)dateFromString:(NSString *)s { return [_dateFormat dateFromString:s]; } - (NSString *)stringFromDate:(NSDate *)date { return [_dateFormat stringFromDate:date]; } #pragma mark State of database - (BOOL)goodConnection { if (!_isOpen) { return NO; } #if SQLCIPHER_CRYPTO // Starting with Xcode8 / iOS 10 we check to make sure we really are linked with // SQLCipher because there is no longer a linker error if we accidently link // with unencrypted sqlite library. // // https://discuss.zetetic.net/t/important-advisory-sqlcipher-with-xcode-8-and-new-sdks/1688 NSString *cipherVersion = self.cipherVersion; if (cipherVersion) { NSLog(@"SQLCipher version: %@", cipherVersion); return YES; } #else FMResultSet *rs = [self executeQuery:@"select name from sqlite_master where type='table'"]; if (rs) { [rs close]; return YES; } #endif return NO; } - (void)warnInUse { NSLog(@"The FMDatabase %@ is currently in use.", self); #ifndef NS_BLOCK_ASSERTIONS if (_crashOnErrors) { NSAssert(false, @"The FMDatabase %@ is currently in use.", self); abort(); } #endif } - (BOOL)databaseExists { if (!_isOpen) { NSLog(@"The FMDatabase %@ is not open.", self); #ifndef NS_BLOCK_ASSERTIONS if (_crashOnErrors) { NSAssert(false, @"The FMDatabase %@ is not open.", self); abort(); } #endif return NO; } return YES; } #pragma mark Error routines - (NSString *)lastErrorMessage { return [NSString stringWithUTF8String:sqlite3_errmsg(_db)]; } - (BOOL)hadError { int lastErrCode = [self lastErrorCode]; return (lastErrCode > SQLITE_OK && lastErrCode < SQLITE_ROW); } - (int)lastErrorCode { return sqlite3_errcode(_db); } - (int)lastExtendedErrorCode { return sqlite3_extended_errcode(_db); } - (NSError*)errorWithMessage:(NSString *)message { NSDictionary* errorMessage = [NSDictionary dictionaryWithObject:message forKey:NSLocalizedDescriptionKey]; return [NSError errorWithDomain:@"FMDatabase" code:sqlite3_errcode(_db) userInfo:errorMessage]; } - (NSError*)lastError { return [self errorWithMessage:[self lastErrorMessage]]; } #pragma mark Update information routines - (sqlite_int64)lastInsertRowId { if (_isExecutingStatement) { [self warnInUse]; return NO; } _isExecutingStatement = YES; sqlite_int64 ret = sqlite3_last_insert_rowid(_db); _isExecutingStatement = NO; return ret; } - (int)changes { if (_isExecutingStatement) { [self warnInUse]; return 0; } _isExecutingStatement = YES; int ret = sqlite3_changes(_db); _isExecutingStatement = NO; return ret; } #pragma mark SQL manipulation - (int)bindObject:(id)obj toColumn:(int)idx inStatement:(sqlite3_stmt*)pStmt { if ((!obj) || ((NSNull *)obj == [NSNull null])) { return sqlite3_bind_null(pStmt, idx); } // FIXME - someday check the return codes on these binds. else if ([obj isKindOfClass:[NSData class]]) { const void *bytes = [obj bytes]; if (!bytes) { // it's an empty NSData object, aka [NSData data]. // Don't pass a NULL pointer, or sqlite will bind a SQL null instead of a blob. bytes = ""; } return sqlite3_bind_blob(pStmt, idx, bytes, (int)[obj length], SQLITE_TRANSIENT); } else if ([obj isKindOfClass:[NSDate class]]) { if (self.hasDateFormatter) return sqlite3_bind_text(pStmt, idx, [[self stringFromDate:obj] UTF8String], -1, SQLITE_TRANSIENT); else return sqlite3_bind_double(pStmt, idx, [obj timeIntervalSince1970]); } else if ([obj isKindOfClass:[NSNumber class]]) { if (strcmp([obj objCType], @encode(char)) == 0) { return sqlite3_bind_int(pStmt, idx, [obj charValue]); } else if (strcmp([obj objCType], @encode(unsigned char)) == 0) { return sqlite3_bind_int(pStmt, idx, [obj unsignedCharValue]); } else if (strcmp([obj objCType], @encode(short)) == 0) { return sqlite3_bind_int(pStmt, idx, [obj shortValue]); } else if (strcmp([obj objCType], @encode(unsigned short)) == 0) { return sqlite3_bind_int(pStmt, idx, [obj unsignedShortValue]); } else if (strcmp([obj objCType], @encode(int)) == 0) { return sqlite3_bind_int(pStmt, idx, [obj intValue]); } else if (strcmp([obj objCType], @encode(unsigned int)) == 0) { return sqlite3_bind_int64(pStmt, idx, (long long)[obj unsignedIntValue]); } else if (strcmp([obj objCType], @encode(long)) == 0) { return sqlite3_bind_int64(pStmt, idx, [obj longValue]); } else if (strcmp([obj objCType], @encode(unsigned long)) == 0) { return sqlite3_bind_int64(pStmt, idx, (long long)[obj unsignedLongValue]); } else if (strcmp([obj objCType], @encode(long long)) == 0) { return sqlite3_bind_int64(pStmt, idx, [obj longLongValue]); } else if (strcmp([obj objCType], @encode(unsigned long long)) == 0) { return sqlite3_bind_int64(pStmt, idx, (long long)[obj unsignedLongLongValue]); } else if (strcmp([obj objCType], @encode(float)) == 0) { return sqlite3_bind_double(pStmt, idx, [obj floatValue]); } else if (strcmp([obj objCType], @encode(double)) == 0) { return sqlite3_bind_double(pStmt, idx, [obj doubleValue]); } else if (strcmp([obj objCType], @encode(BOOL)) == 0) { return sqlite3_bind_int(pStmt, idx, ([obj boolValue] ? 1 : 0)); } else { return sqlite3_bind_text(pStmt, idx, [[obj description] UTF8String], -1, SQLITE_TRANSIENT); } } return sqlite3_bind_text(pStmt, idx, [[obj description] UTF8String], -1, SQLITE_TRANSIENT); } - (void)extractSQL:(NSString *)sql argumentsList:(va_list)args intoString:(NSMutableString *)cleanedSQL arguments:(NSMutableArray *)arguments { NSUInteger length = [sql length]; unichar last = '\0'; for (NSUInteger i = 0; i < length; ++i) { id arg = nil; unichar current = [sql characterAtIndex:i]; unichar add = current; if (last == '%') { switch (current) { case '@': arg = va_arg(args, id); break; case 'c': // warning: second argument to 'va_arg' is of promotable type 'char'; this va_arg has undefined behavior because arguments will be promoted to 'int' arg = [NSString stringWithFormat:@"%c", va_arg(args, int)]; break; case 's': arg = [NSString stringWithUTF8String:va_arg(args, char*)]; break; case 'd': case 'D': case 'i': arg = [NSNumber numberWithInt:va_arg(args, int)]; break; case 'u': case 'U': arg = [NSNumber numberWithUnsignedInt:va_arg(args, unsigned int)]; break; case 'h': i++; if (i < length && [sql characterAtIndex:i] == 'i') { // warning: second argument to 'va_arg' is of promotable type 'short'; this va_arg has undefined behavior because arguments will be promoted to 'int' arg = [NSNumber numberWithShort:(short)(va_arg(args, int))]; } else if (i < length && [sql characterAtIndex:i] == 'u') { // warning: second argument to 'va_arg' is of promotable type 'unsigned short'; this va_arg has undefined behavior because arguments will be promoted to 'int' arg = [NSNumber numberWithUnsignedShort:(unsigned short)(va_arg(args, uint))]; } else { i--; } break; case 'q': i++; if (i < length && [sql characterAtIndex:i] == 'i') { arg = [NSNumber numberWithLongLong:va_arg(args, long long)]; } else if (i < length && [sql characterAtIndex:i] == 'u') { arg = [NSNumber numberWithUnsignedLongLong:va_arg(args, unsigned long long)]; } else { i--; } break; case 'f': arg = [NSNumber numberWithDouble:va_arg(args, double)]; break; case 'g': // warning: second argument to 'va_arg' is of promotable type 'float'; this va_arg has undefined behavior because arguments will be promoted to 'double' arg = [NSNumber numberWithFloat:(float)(va_arg(args, double))]; break; case 'l': i++; if (i < length) { unichar next = [sql characterAtIndex:i]; if (next == 'l') { i++; if (i < length && [sql characterAtIndex:i] == 'd') { //%lld arg = [NSNumber numberWithLongLong:va_arg(args, long long)]; } else if (i < length && [sql characterAtIndex:i] == 'u') { //%llu arg = [NSNumber numberWithUnsignedLongLong:va_arg(args, unsigned long long)]; } else { i--; } } else if (next == 'd') { //%ld arg = [NSNumber numberWithLong:va_arg(args, long)]; } else if (next == 'u') { //%lu arg = [NSNumber numberWithUnsignedLong:va_arg(args, unsigned long)]; } else { i--; } } else { i--; } break; default: // something else that we can't interpret. just pass it on through like normal break; } } else if (current == '%') { // percent sign; skip this character add = '\0'; } if (arg != nil) { [cleanedSQL appendString:@"?"]; [arguments addObject:arg]; } else if (add == (unichar)'@' && last == (unichar) '%') { [cleanedSQL appendFormat:@"NULL"]; } else if (add != '\0') { [cleanedSQL appendFormat:@"%C", add]; } last = current; } } #pragma mark Execute queries - (FMResultSet *)executeQuery:(NSString *)sql withParameterDictionary:(NSDictionary *)arguments { return [self executeQuery:sql withArgumentsInArray:nil orDictionary:arguments orVAList:nil shouldBind:true]; } - (FMResultSet *)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray*)arrayArgs orDictionary:(NSDictionary *)dictionaryArgs orVAList:(va_list)args shouldBind:(BOOL)shouldBind { if (![self databaseExists]) { return 0x00; } if (_isExecutingStatement) { [self warnInUse]; return 0x00; } _isExecutingStatement = YES; int rc = 0x00; sqlite3_stmt *pStmt = 0x00; FMStatement *statement = 0x00; FMResultSet *rs = 0x00; if (_traceExecution && sql) { NSLog(@"%@ executeQuery: %@", self, sql); } if (_shouldCacheStatements) { statement = [self cachedStatementForQuery:sql]; pStmt = statement ? [statement statement] : 0x00; [statement reset]; } if (!pStmt) { rc = sqlite3_prepare_v2(_db, [sql UTF8String], -1, &pStmt, 0); if (SQLITE_OK != rc) { if (_logsErrors) { NSLog(@"DB Error: %d \"%@\"", [self lastErrorCode], [self lastErrorMessage]); NSLog(@"DB Query: %@", sql); NSLog(@"DB Path: %@", _databasePath); } if (_crashOnErrors) { NSAssert(false, @"DB Error: %d \"%@\"", [self lastErrorCode], [self lastErrorMessage]); abort(); } sqlite3_finalize(pStmt); pStmt = 0x00; _isExecutingStatement = NO; return nil; } } if (shouldBind) { BOOL success = [self bindStatement:pStmt WithArgumentsInArray:arrayArgs orDictionary:dictionaryArgs orVAList:args]; if (!success) { return nil; } } FMDBRetain(statement); // to balance the release below if (!statement) { statement = [[FMStatement alloc] init]; [statement setStatement:pStmt]; if (_shouldCacheStatements && sql) { [self setCachedStatement:statement forQuery:sql]; } } // the statement gets closed in rs's dealloc or [rs close]; // we should only autoclose if we're binding automatically when the statement is prepared rs = [FMResultSet resultSetWithStatement:statement usingParentDatabase:self shouldAutoClose:shouldBind]; [rs setQuery:sql]; NSValue *openResultSet = [NSValue valueWithNonretainedObject:rs]; [_openResultSets addObject:openResultSet]; [statement setUseCount:[statement useCount] + 1]; FMDBRelease(statement); _isExecutingStatement = NO; return rs; } - (BOOL)bindStatement:(sqlite3_stmt *)pStmt WithArgumentsInArray:(NSArray*)arrayArgs orDictionary:(NSDictionary *)dictionaryArgs orVAList:(va_list)args { id obj; int idx = 0; int queryCount = sqlite3_bind_parameter_count(pStmt); // pointed out by Dominic Yu (thanks!) // If dictionaryArgs is passed in, that means we are using sqlite's named parameter support if (dictionaryArgs) { for (NSString *dictionaryKey in [dictionaryArgs allKeys]) { // Prefix the key with a colon. NSString *parameterName = [[NSString alloc] initWithFormat:@":%@", dictionaryKey]; if (_traceExecution) { NSLog(@"%@ = %@", parameterName, [dictionaryArgs objectForKey:dictionaryKey]); } // Get the index for the parameter name. int namedIdx = sqlite3_bind_parameter_index(pStmt, [parameterName UTF8String]); FMDBRelease(parameterName); if (namedIdx > 0) { // Standard binding from here. int rc = [self bindObject:[dictionaryArgs objectForKey:dictionaryKey] toColumn:namedIdx inStatement:pStmt]; if (rc != SQLITE_OK) { NSLog(@"Error: unable to bind (%d, %s", rc, sqlite3_errmsg(_db)); sqlite3_finalize(pStmt); pStmt = 0x00; _isExecutingStatement = NO; return false; } // increment the binding count, so our check below works out idx++; } else { NSLog(@"Could not find index for %@", dictionaryKey); } } } else { while (idx < queryCount) { if (arrayArgs && idx < (int)[arrayArgs count]) { obj = [arrayArgs objectAtIndex:(NSUInteger)idx]; } else if (args) { obj = va_arg(args, id); } else { //We ran out of arguments break; } if (_traceExecution) { if ([obj isKindOfClass:[NSData class]]) { NSLog(@"data: %ld bytes", (unsigned long)[(NSData*)obj length]); } else { NSLog(@"obj: %@", obj); } } idx++; int rc = [self bindObject:obj toColumn:idx inStatement:pStmt]; if (rc != SQLITE_OK) { NSLog(@"Error: unable to bind (%d, %s", rc, sqlite3_errmsg(_db)); sqlite3_finalize(pStmt); pStmt = 0x00; _isExecutingStatement = NO; return false; } } } if (idx != queryCount) { NSLog(@"Error: the bind count is not correct for the # of variables (executeQuery)"); sqlite3_finalize(pStmt); pStmt = 0x00; _isExecutingStatement = NO; return false; } return true; } - (FMResultSet *)executeQuery:(NSString*)sql, ... { va_list args; va_start(args, sql); id result = [self executeQuery:sql withArgumentsInArray:nil orDictionary:nil orVAList:args shouldBind:true]; va_end(args); return result; } - (FMResultSet *)executeQueryWithFormat:(NSString*)format, ... { va_list args; va_start(args, format); NSMutableString *sql = [NSMutableString stringWithCapacity:[format length]]; NSMutableArray *arguments = [NSMutableArray array]; [self extractSQL:format argumentsList:args intoString:sql arguments:arguments]; va_end(args); return [self executeQuery:sql withArgumentsInArray:arguments]; } - (FMResultSet *)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray *)arguments { return [self executeQuery:sql withArgumentsInArray:arguments orDictionary:nil orVAList:nil shouldBind:true]; } - (FMResultSet *)executeQuery:(NSString *)sql values:(NSArray *)values error:(NSError * __autoreleasing *)error { FMResultSet *rs = [self executeQuery:sql withArgumentsInArray:values orDictionary:nil orVAList:nil shouldBind:true]; if (!rs && error) { *error = [self lastError]; } return rs; } - (FMResultSet *)executeQuery:(NSString*)sql withVAList:(va_list)args { return [self executeQuery:sql withArgumentsInArray:nil orDictionary:nil orVAList:args shouldBind:true]; } #pragma mark Execute updates - (BOOL)executeUpdate:(NSString*)sql error:(NSError * _Nullable __autoreleasing *)outErr withArgumentsInArray:(NSArray*)arrayArgs orDictionary:(NSDictionary *)dictionaryArgs orVAList:(va_list)args { FMResultSet *rs = [self executeQuery:sql withArgumentsInArray:arrayArgs orDictionary:dictionaryArgs orVAList:args shouldBind:true]; if (!rs) { if (outErr) { *outErr = [self lastError]; } return false; } return [rs internalStepWithError:outErr] == SQLITE_DONE; } - (BOOL)executeUpdate:(NSString*)sql, ... { va_list args; va_start(args, sql); BOOL result = [self executeUpdate:sql error:nil withArgumentsInArray:nil orDictionary:nil orVAList:args]; va_end(args); return result; } - (BOOL)executeUpdate:(NSString*)sql withArgumentsInArray:(NSArray *)arguments { return [self executeUpdate:sql error:nil withArgumentsInArray:arguments orDictionary:nil orVAList:nil]; } - (BOOL)executeUpdate:(NSString*)sql values:(NSArray *)values error:(NSError * __autoreleasing *)error { return [self executeUpdate:sql error:error withArgumentsInArray:values orDictionary:nil orVAList:nil]; } - (BOOL)executeUpdate:(NSString*)sql withParameterDictionary:(NSDictionary *)arguments { return [self executeUpdate:sql error:nil withArgumentsInArray:nil orDictionary:arguments orVAList:nil]; } - (BOOL)executeUpdate:(NSString*)sql withVAList:(va_list)args { return [self executeUpdate:sql error:nil withArgumentsInArray:nil orDictionary:nil orVAList:args]; } - (BOOL)executeUpdateWithFormat:(NSString*)format, ... { va_list args; va_start(args, format); NSMutableString *sql = [NSMutableString stringWithCapacity:[format length]]; NSMutableArray *arguments = [NSMutableArray array]; [self extractSQL:format argumentsList:args intoString:sql arguments:arguments]; va_end(args); return [self executeUpdate:sql withArgumentsInArray:arguments]; } int FMDBExecuteBulkSQLCallback(void *theBlockAsVoid, int columns, char **values, char **names); // shhh clang. int FMDBExecuteBulkSQLCallback(void *theBlockAsVoid, int columns, char **values, char **names) { if (!theBlockAsVoid) { return SQLITE_OK; } int (^execCallbackBlock)(NSDictionary *resultsDictionary) = (__bridge int (^)(NSDictionary *__strong))(theBlockAsVoid); NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithCapacity:(NSUInteger)columns]; for (NSInteger i = 0; i < columns; i++) { NSString *key = [NSString stringWithUTF8String:names[i]]; id value = values[i] ? [NSString stringWithUTF8String:values[i]] : [NSNull null]; value = value ? value : [NSNull null]; [dictionary setObject:value forKey:key]; } return execCallbackBlock(dictionary); } - (BOOL)executeStatements:(NSString *)sql { return [self executeStatements:sql withResultBlock:nil]; } - (BOOL)executeStatements:(NSString *)sql withResultBlock:(__attribute__((noescape)) FMDBExecuteStatementsCallbackBlock)block { int rc; char *errmsg = nil; rc = sqlite3_exec([self sqliteHandle], [sql UTF8String], block ? FMDBExecuteBulkSQLCallback : nil, (__bridge void *)(block), &errmsg); if (errmsg && [self logsErrors]) { NSLog(@"Error inserting batch: %s", errmsg); } if (errmsg) { sqlite3_free(errmsg); } return (rc == SQLITE_OK); } - (BOOL)executeUpdate:(NSString*)sql withErrorAndBindings:(NSError * _Nullable __autoreleasing *)outErr, ... { va_list args; va_start(args, outErr); BOOL result = [self executeUpdate:sql error:outErr withArgumentsInArray:nil orDictionary:nil orVAList:args]; va_end(args); return result; } #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-implementations" - (BOOL)update:(NSString*)sql withErrorAndBindings:(NSError * _Nullable __autoreleasing *)outErr, ... { va_list args; va_start(args, outErr); BOOL result = [self executeUpdate:sql error:outErr withArgumentsInArray:nil orDictionary:nil orVAList:args]; va_end(args); return result; } #pragma clang diagnostic pop #pragma mark Prepare - (FMResultSet *)prepare:(NSString *)sql { return [self executeQuery:sql withArgumentsInArray:nil orDictionary:nil orVAList:nil shouldBind:false]; } #pragma mark Transactions - (BOOL)rollback { BOOL b = [self executeUpdate:@"rollback transaction"]; if (b) { _isInTransaction = NO; } return b; } - (BOOL)commit { BOOL b = [self executeUpdate:@"commit transaction"]; if (b) { _isInTransaction = NO; } return b; } - (BOOL)beginTransaction { BOOL b = [self executeUpdate:@"begin exclusive transaction"]; if (b) { _isInTransaction = YES; } return b; } - (BOOL)beginDeferredTransaction { BOOL b = [self executeUpdate:@"begin deferred transaction"]; if (b) { _isInTransaction = YES; } return b; } - (BOOL)beginImmediateTransaction { BOOL b = [self executeUpdate:@"begin immediate transaction"]; if (b) { _isInTransaction = YES; } return b; } - (BOOL)beginExclusiveTransaction { BOOL b = [self executeUpdate:@"begin exclusive transaction"]; if (b) { _isInTransaction = YES; } return b; } - (BOOL)inTransaction { return _isInTransaction; } - (BOOL)interrupt { if (_db) { sqlite3_interrupt([self sqliteHandle]); return YES; } return NO; } static NSString *FMDBEscapeSavePointName(NSString *savepointName) { return [savepointName stringByReplacingOccurrencesOfString:@"'" withString:@"''"]; } - (BOOL)startSavePointWithName:(NSString*)name error:(NSError * _Nullable __autoreleasing *)outErr { #if SQLITE_VERSION_NUMBER >= 3007000 NSParameterAssert(name); NSString *sql = [NSString stringWithFormat:@"savepoint '%@';", FMDBEscapeSavePointName(name)]; return [self executeUpdate:sql error:outErr withArgumentsInArray:nil orDictionary:nil orVAList:nil]; #else NSString *errorMessage = NSLocalizedStringFromTable(@"Save point functions require SQLite 3.7", @"FMDB", nil); if (self.logsErrors) NSLog(@"%@", errorMessage); return NO; #endif } - (BOOL)releaseSavePointWithName:(NSString*)name error:(NSError * _Nullable __autoreleasing *)outErr { #if SQLITE_VERSION_NUMBER >= 3007000 NSParameterAssert(name); NSString *sql = [NSString stringWithFormat:@"release savepoint '%@';", FMDBEscapeSavePointName(name)]; return [self executeUpdate:sql error:outErr withArgumentsInArray:nil orDictionary:nil orVAList:nil]; #else NSString *errorMessage = NSLocalizedStringFromTable(@"Save point functions require SQLite 3.7", @"FMDB", nil); if (self.logsErrors) NSLog(@"%@", errorMessage); return NO; #endif } - (BOOL)rollbackToSavePointWithName:(NSString*)name error:(NSError * _Nullable __autoreleasing *)outErr { #if SQLITE_VERSION_NUMBER >= 3007000 NSParameterAssert(name); NSString *sql = [NSString stringWithFormat:@"rollback transaction to savepoint '%@';", FMDBEscapeSavePointName(name)]; return [self executeUpdate:sql error:outErr withArgumentsInArray:nil orDictionary:nil orVAList:nil]; #else NSString *errorMessage = NSLocalizedStringFromTable(@"Save point functions require SQLite 3.7", @"FMDB", nil); if (self.logsErrors) NSLog(@"%@", errorMessage); return NO; #endif } - (NSError*)inSavePoint:(__attribute__((noescape)) void (^)(BOOL *rollback))block { #if SQLITE_VERSION_NUMBER >= 3007000 static unsigned long savePointIdx = 0; NSString *name = [NSString stringWithFormat:@"dbSavePoint%ld", savePointIdx++]; BOOL shouldRollback = NO; NSError *err = 0x00; if (![self startSavePointWithName:name error:&err]) { return err; } if (block) { block(&shouldRollback); } if (shouldRollback) { // We need to rollback and release this savepoint to remove it [self rollbackToSavePointWithName:name error:&err]; } [self releaseSavePointWithName:name error:&err]; return err; #else NSString *errorMessage = NSLocalizedStringFromTable(@"Save point functions require SQLite 3.7", @"FMDB", nil); if (self.logsErrors) NSLog(@"%@", errorMessage); return [NSError errorWithDomain:@"FMDatabase" code:0 userInfo:@{NSLocalizedDescriptionKey : errorMessage}]; #endif } - (BOOL)checkpoint:(FMDBCheckpointMode)checkpointMode error:(NSError * __autoreleasing *)error { return [self checkpoint:checkpointMode name:nil logFrameCount:NULL checkpointCount:NULL error:error]; } - (BOOL)checkpoint:(FMDBCheckpointMode)checkpointMode name:(NSString *)name error:(NSError * __autoreleasing *)error { return [self checkpoint:checkpointMode name:name logFrameCount:NULL checkpointCount:NULL error:error]; } - (BOOL)checkpoint:(FMDBCheckpointMode)checkpointMode name:(NSString *)name logFrameCount:(int *)logFrameCount checkpointCount:(int *)checkpointCount error:(NSError * __autoreleasing *)error { const char* dbName = [name UTF8String]; #if SQLITE_VERSION_NUMBER >= 3007006 int err = sqlite3_wal_checkpoint_v2(_db, dbName, checkpointMode, logFrameCount, checkpointCount); #else NSLog(@"sqlite3_wal_checkpoint_v2 unavailable before sqlite 3.7.6. Ignoring checkpoint mode: %d", mode); int err = sqlite3_wal_checkpoint(_db, dbName); #endif if(err != SQLITE_OK) { if (error) { *error = [self lastError]; } if (self.logsErrors) NSLog(@"%@", [self lastErrorMessage]); if (self.crashOnErrors) { NSAssert(false, @"%@", [self lastErrorMessage]); abort(); } return NO; } else { return YES; } } #pragma mark Cache statements - (BOOL)shouldCacheStatements { return _shouldCacheStatements; } - (void)setShouldCacheStatements:(BOOL)value { _shouldCacheStatements = value; if (_shouldCacheStatements && !_cachedStatements) { [self setCachedStatements:[NSMutableDictionary dictionary]]; } if (!_shouldCacheStatements) { [self setCachedStatements:nil]; } } #pragma mark Callback function void FMDBBlockSQLiteCallBackFunction(sqlite3_context *context, int argc, sqlite3_value **argv); // -Wmissing-prototypes void FMDBBlockSQLiteCallBackFunction(sqlite3_context *context, int argc, sqlite3_value **argv) { #if ! __has_feature(objc_arc) void (^block)(sqlite3_context *context, int argc, sqlite3_value **argv) = (id)sqlite3_user_data(context); #else void (^block)(sqlite3_context *context, int argc, sqlite3_value **argv) = (__bridge id)sqlite3_user_data(context); #endif if (block) { @autoreleasepool { block(context, argc, argv); } } } // deprecated because "arguments" parameter is not maximum argument count, but actual argument count. - (void)makeFunctionNamed:(NSString *)name maximumArguments:(int)arguments withBlock:(void (^)(void *context, int argc, void **argv))block { [self makeFunctionNamed:name arguments:arguments block:block]; } - (void)makeFunctionNamed:(NSString *)name arguments:(int)arguments block:(void (^)(void *context, int argc, void **argv))block { if (!_openFunctions) { _openFunctions = [NSMutableSet new]; } id b = FMDBReturnAutoreleased([block copy]); [_openFunctions addObject:b]; /* I tried adding custom functions to release the block when the connection is destroyed- but they seemed to never be called, so we use _openFunctions to store the values instead. */ #if ! __has_feature(objc_arc) sqlite3_create_function([self sqliteHandle], [name UTF8String], arguments, SQLITE_UTF8, (void*)b, &FMDBBlockSQLiteCallBackFunction, 0x00, 0x00); #else sqlite3_create_function([self sqliteHandle], [name UTF8String], arguments, SQLITE_UTF8, (__bridge void*)b, &FMDBBlockSQLiteCallBackFunction, 0x00, 0x00); #endif } - (SqliteValueType)valueType:(void *)value { return sqlite3_value_type(value); } - (int)valueInt:(void *)value { return sqlite3_value_int(value); } - (long long)valueLong:(void *)value { return sqlite3_value_int64(value); } - (double)valueDouble:(void *)value { return sqlite3_value_double(value); } - (NSData *)valueData:(void *)value { const void *bytes = sqlite3_value_blob(value); int length = sqlite3_value_bytes(value); return bytes ? [NSData dataWithBytes:bytes length:(NSUInteger)length] : nil; } - (NSString *)valueString:(void *)value { const char *cString = (const char *)sqlite3_value_text(value); return cString ? [NSString stringWithUTF8String:cString] : nil; } - (void)resultNullInContext:(void *)context { sqlite3_result_null(context); } - (void)resultInt:(int) value context:(void *)context { sqlite3_result_int(context, value); } - (void)resultLong:(long long)value context:(void *)context { sqlite3_result_int64(context, value); } - (void)resultDouble:(double)value context:(void *)context { sqlite3_result_double(context, value); } - (void)resultData:(NSData *)data context:(void *)context { sqlite3_result_blob(context, data.bytes, (int)data.length, SQLITE_TRANSIENT); } - (void)resultString:(NSString *)value context:(void *)context { sqlite3_result_text(context, [value UTF8String], -1, SQLITE_TRANSIENT); } - (void)resultError:(NSString *)error context:(void *)context { sqlite3_result_error(context, [error UTF8String], -1); } - (void)resultErrorCode:(int)errorCode context:(void *)context { sqlite3_result_error_code(context, errorCode); } - (void)resultErrorNoMemoryInContext:(void *)context { sqlite3_result_error_nomem(context); } - (void)resultErrorTooBigInContext:(void *)context { sqlite3_result_error_toobig(context); } @end // MARK: - FMStatement @implementation FMStatement #if ! __has_feature(objc_arc) - (void)finalize { [self close]; [super finalize]; } #endif - (void)dealloc { [self close]; FMDBRelease(_query); #if ! __has_feature(objc_arc) [super dealloc]; #endif } - (void)close { if (_statement) { sqlite3_finalize(_statement); _statement = 0x00; } _inUse = NO; } - (void)reset { if (_statement) { sqlite3_reset(_statement); } _inUse = NO; } - (NSString*)description { return [NSString stringWithFormat:@"%@ %ld hit(s) for query %@", [super description], _useCount, _query]; } @end ================================================ FILE: src/fmdb/FMDatabaseAdditions.h ================================================ // // FMDatabaseAdditions.h // fmdb // // Created by August Mueller on 10/30/05. // Copyright 2005 Flying Meat Inc.. All rights reserved. // #import #import "FMDatabase.h" NS_ASSUME_NONNULL_BEGIN /** Category of additions for @c FMDatabase class. See also - @c FMDatabase */ @interface FMDatabase (FMDatabaseAdditions) ///---------------------------------------- /// @name Return results of SQL to variable ///---------------------------------------- /** Return @c int value for query @param query The SQL query to be performed, followed by a list of parameters that will be bound to the `?` placeholders in the SQL query. @return @c int value. @note This is not available from Swift. */ - (int)intForQuery:(NSString*)query, ...; /** Return @c long value for query @param query The SQL query to be performed, followed by a list of parameters that will be bound to the `?` placeholders in the SQL query. @return @c long value. @note This is not available from Swift. */ - (long)longForQuery:(NSString*)query, ...; /** Return `BOOL` value for query @param query The SQL query to be performed, followed by a list of parameters that will be bound to the `?` placeholders in the SQL query. @return `BOOL` value. @note This is not available from Swift. */ - (BOOL)boolForQuery:(NSString*)query, ...; /** Return `double` value for query @param query The SQL query to be performed, followed by a list of parameters that will be bound to the `?` placeholders in the SQL query. @return `double` value. @note This is not available from Swift. */ - (double)doubleForQuery:(NSString*)query, ...; /** Return @c NSString value for query @param query The SQL query to be performed, followed by a list of parameters that will be bound to the `?` placeholders in the SQL query. @return @c NSString value. @note This is not available from Swift. */ - (NSString * _Nullable)stringForQuery:(NSString*)query, ...; /** Return @c NSData value for query @param query The SQL query to be performed, followed by a list of parameters that will be bound to the `?` placeholders in the SQL query. @return @c NSData value. @note This is not available from Swift. */ - (NSData * _Nullable)dataForQuery:(NSString*)query, ...; /** Return @c NSDate value for query @param query The SQL query to be performed, followed by a list of parameters that will be bound to the `?` placeholders in the SQL query. @return @c NSDate value. @note This is not available from Swift. */ - (NSDate * _Nullable)dateForQuery:(NSString*)query, ...; // Notice that there's no dataNoCopyForQuery:. // That would be a bad idea, because we close out the result set, and then what // happens to the data that we just didn't copy? Who knows, not I. ///-------------------------------- /// @name Schema related operations ///-------------------------------- /** Does table exist in database? @param tableName The name of the table being looked for. @return @c YES if table found; @c NO if not found. */ - (BOOL)tableExists:(NSString*)tableName; /** The schema of the database. This will be the schema for the entire database. For each entity, each row of the result set will include the following fields: - `type` - The type of entity (e.g. table, index, view, or trigger) - `name` - The name of the object - `tbl_name` - The name of the table to which the object references - `rootpage` - The page number of the root b-tree page for tables and indices - `sql` - The SQL that created the entity @return `FMResultSet` of schema; @c nil on error. @see [SQLite File Format](https://sqlite.org/fileformat.html) */ - (FMResultSet * _Nullable)getSchema; /** The schema of the database. This will be the schema for a particular table as report by SQLite `PRAGMA`, for example: PRAGMA table_info('employees') This will report: - `cid` - The column ID number - `name` - The name of the column - `type` - The data type specified for the column - `notnull` - whether the field is defined as NOT NULL (i.e. values required) - `dflt_value` - The default value for the column - `pk` - Whether the field is part of the primary key of the table @param tableName The name of the table for whom the schema will be returned. @return `FMResultSet` of schema; @c nil on error. @see [table_info](https://sqlite.org/pragma.html#pragma_table_info) */ - (FMResultSet * _Nullable)getTableSchema:(NSString*)tableName; /** Test to see if particular column exists for particular table in database @param columnName The name of the column. @param tableName The name of the table. @return @c YES if column exists in table in question; @c NO otherwise. */ - (BOOL)columnExists:(NSString*)columnName inTableWithName:(NSString*)tableName; /** Test to see if particular column exists for particular table in database @param columnName The name of the column. @param tableName The name of the table. @return @c YES if column exists in table in question; @c NO otherwise. @see columnExists:inTableWithName: @warning Deprecated - use `` instead. */ - (BOOL)columnExists:(NSString*)tableName columnName:(NSString*)columnName __deprecated_msg("Use columnExists:inTableWithName: instead"); /** Validate SQL statement This validates SQL statement by performing `sqlite3_prepare_v2`, but not returning the results, but instead immediately calling `sqlite3_finalize`. @param sql The SQL statement being validated. @param error This is a pointer to a @c NSError object that will receive the autoreleased @c NSError object if there was any error. If this is @c nil , no @c NSError result will be returned. @return @c YES if validation succeeded without incident; @c NO otherwise. */ - (BOOL)validateSQL:(NSString*)sql error:(NSError * _Nullable __autoreleasing *)error; ///----------------------------------- /// @name Application identifier tasks ///----------------------------------- /** Retrieve application ID @return The `uint32_t` numeric value of the application ID. @see setApplicationID: */ @property (nonatomic) uint32_t applicationID; #if TARGET_OS_MAC && !TARGET_OS_IPHONE /** Retrieve application ID string @see setApplicationIDString: */ @property (nonatomic, retain) NSString *applicationIDString; #endif ///----------------------------------- /// @name user version identifier tasks ///----------------------------------- /** Retrieve user version @see setUserVersion: */ @property (nonatomic) uint32_t userVersion; @end NS_ASSUME_NONNULL_END ================================================ FILE: src/fmdb/FMDatabaseAdditions.m ================================================ // // FMDatabaseAdditions.m // fmdb // // Created by August Mueller on 10/30/05. // Copyright 2005 Flying Meat Inc.. All rights reserved. // #import "FMDatabase.h" #import "FMDatabaseAdditions.h" #import "TargetConditionals.h" #if FMDB_SQLITE_STANDALONE #import #elif SQLCIPHER_CRYPTO #import #else #import #endif @interface FMDatabase (PrivateStuff) - (FMResultSet * _Nullable)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray * _Nullable)arrayArgs orDictionary:(NSDictionary * _Nullable)dictionaryArgs orVAList:(va_list)args shouldBind:(BOOL)shouldBind; @end @implementation FMDatabase (FMDatabaseAdditions) #define RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(type, sel) \ va_list args; \ va_start(args, query); \ FMResultSet *resultSet = [self executeQuery:query withArgumentsInArray:0x00 orDictionary:0x00 orVAList:args shouldBind:true]; \ va_end(args); \ if (![resultSet next]) { return (type)0; } \ type ret = [resultSet sel:0]; \ [resultSet close]; \ [resultSet setParentDB:nil]; \ return ret; - (NSString *)stringForQuery:(NSString*)query, ... { RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(NSString *, stringForColumnIndex); } - (int)intForQuery:(NSString*)query, ... { RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(int, intForColumnIndex); } - (long)longForQuery:(NSString*)query, ... { RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(long, longForColumnIndex); } - (BOOL)boolForQuery:(NSString*)query, ... { RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(BOOL, boolForColumnIndex); } - (double)doubleForQuery:(NSString*)query, ... { RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(double, doubleForColumnIndex); } - (NSData*)dataForQuery:(NSString*)query, ... { RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(NSData *, dataForColumnIndex); } - (NSDate*)dateForQuery:(NSString*)query, ... { RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(NSDate *, dateForColumnIndex); } - (BOOL)tableExists:(NSString*)tableName { tableName = [tableName lowercaseString]; FMResultSet *rs = [self executeQuery:@"select [sql] from sqlite_master where [type] = 'table' and lower(name) = ?", tableName]; //if at least one next exists, table exists BOOL returnBool = [rs next]; //close and free object [rs close]; return returnBool; } /* get table with list of tables: result colums: type[STRING], name[STRING],tbl_name[STRING],rootpage[INTEGER],sql[STRING] check if table exist in database (patch from OZLB) */ - (FMResultSet * _Nullable)getSchema { //result colums: type[STRING], name[STRING],tbl_name[STRING],rootpage[INTEGER],sql[STRING] 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"]; return rs; } /* get table schema: result colums: cid[INTEGER], name,type [STRING], notnull[INTEGER], dflt_value[],pk[INTEGER] */ - (FMResultSet * _Nullable)getTableSchema:(NSString*)tableName { //result colums: cid[INTEGER], name,type [STRING], notnull[INTEGER], dflt_value[],pk[INTEGER] FMResultSet *rs = [self executeQuery:[NSString stringWithFormat: @"pragma table_info('%@')", tableName]]; return rs; } - (BOOL)columnExists:(NSString*)columnName inTableWithName:(NSString*)tableName { BOOL returnBool = NO; tableName = [tableName lowercaseString]; columnName = [columnName lowercaseString]; FMResultSet *rs = [self getTableSchema:tableName]; //check if column is present in table schema while ([rs next]) { if ([[[rs stringForColumn:@"name"] lowercaseString] isEqualToString:columnName]) { returnBool = YES; break; } } //If this is not done FMDatabase instance stays out of pool [rs close]; return returnBool; } - (uint32_t)applicationID { #if SQLITE_VERSION_NUMBER >= 3007017 uint32_t r = 0; FMResultSet *rs = [self executeQuery:@"pragma application_id"]; if ([rs next]) { r = (uint32_t)[rs longLongIntForColumnIndex:0]; } [rs close]; return r; #else NSString *errorMessage = NSLocalizedStringFromTable(@"Application ID functions require SQLite 3.7.17", @"FMDB", nil); if (self.logsErrors) NSLog(@"%@", errorMessage); return 0; #endif } - (void)setApplicationID:(uint32_t)appID { #if SQLITE_VERSION_NUMBER >= 3007017 NSString *query = [NSString stringWithFormat:@"pragma application_id=%d", appID]; FMResultSet *rs = [self executeQuery:query]; [rs next]; [rs close]; #else NSString *errorMessage = NSLocalizedStringFromTable(@"Application ID functions require SQLite 3.7.17", @"FMDB", nil); if (self.logsErrors) NSLog(@"%@", errorMessage); #endif } #if TARGET_OS_MAC && !TARGET_OS_IPHONE - (NSString*)applicationIDString { #if SQLITE_VERSION_NUMBER >= 3007017 NSString *s = NSFileTypeForHFSTypeCode([self applicationID]); assert([s length] == 6); s = [s substringWithRange:NSMakeRange(1, 4)]; return s; #else NSString *errorMessage = NSLocalizedStringFromTable(@"Application ID functions require SQLite 3.7.17", @"FMDB", nil); if (self.logsErrors) NSLog(@"%@", errorMessage); return nil; #endif } - (void)setApplicationIDString:(NSString*)s { #if SQLITE_VERSION_NUMBER >= 3007017 if ([s length] != 4) { NSLog(@"setApplicationIDString: string passed is not exactly 4 chars long. (was %ld)", [s length]); } [self setApplicationID:NSHFSTypeCodeFromFileType([NSString stringWithFormat:@"'%@'", s])]; #else NSString *errorMessage = NSLocalizedStringFromTable(@"Application ID functions require SQLite 3.7.17", @"FMDB", nil); if (self.logsErrors) NSLog(@"%@", errorMessage); #endif } #endif - (uint32_t)userVersion { uint32_t r = 0; FMResultSet *rs = [self executeQuery:@"pragma user_version"]; if ([rs next]) { r = (uint32_t)[rs longLongIntForColumnIndex:0]; } [rs close]; return r; } - (void)setUserVersion:(uint32_t)version { NSString *query = [NSString stringWithFormat:@"pragma user_version = %d", version]; FMResultSet *rs = [self executeQuery:query]; [rs next]; [rs close]; } #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-implementations" - (BOOL)columnExists:(NSString*)tableName columnName:(NSString*)columnName __attribute__ ((deprecated)) { return [self columnExists:columnName inTableWithName:tableName]; } #pragma clang diagnostic pop - (BOOL)validateSQL:(NSString*)sql error:(NSError * _Nullable __autoreleasing *)error { sqlite3_stmt *pStmt = NULL; BOOL validationSucceeded = YES; int rc = sqlite3_prepare_v2([self sqliteHandle], [sql UTF8String], -1, &pStmt, 0); if (rc != SQLITE_OK) { validationSucceeded = NO; if (error) { *error = [NSError errorWithDomain:NSCocoaErrorDomain code:[self lastErrorCode] userInfo:[NSDictionary dictionaryWithObject:[self lastErrorMessage] forKey:NSLocalizedDescriptionKey]]; } } sqlite3_finalize(pStmt); return validationSucceeded; } @end ================================================ FILE: src/fmdb/FMDatabasePool.h ================================================ // // FMDatabasePool.h // fmdb // // Created by August Mueller on 6/22/11. // Copyright 2011 Flying Meat Inc. All rights reserved. // #import NS_ASSUME_NONNULL_BEGIN @class FMDatabase; /** Pool of @c FMDatabase objects. See also - @c FMDatabaseQueue - @c FMDatabase @warning Before using @c FMDatabasePool , please consider using @c FMDatabaseQueue instead. If you really really really know what you're doing and @c FMDatabasePool is what you really really need (ie, you're using a read only database), OK you can use it. But just be careful not to deadlock! For an example on deadlocking, search for: `ONLY_USE_THE_POOL_IF_YOU_ARE_DOING_READS_OTHERWISE_YOULL_DEADLOCK_USE_FMDATABASEQUEUE_INSTEAD` in the main.m file. */ @interface FMDatabasePool : NSObject /** Database path */ @property (atomic, copy, nullable) NSString *path; /** Delegate object */ @property (atomic, unsafe_unretained, nullable) id delegate; /** Maximum number of databases to create */ @property (atomic, assign) NSUInteger maximumNumberOfDatabasesToCreate; /** Open flags */ @property (atomic, readonly) int openFlags; /** Custom virtual file system name */ @property (atomic, copy, nullable) NSString *vfsName; ///--------------------- /// @name Initialization ///--------------------- /** Create pool using path. @param aPath The file path of the database. @return The @c FMDatabasePool object. @c nil on error. */ + (instancetype)databasePoolWithPath:(NSString * _Nullable)aPath; /** Create pool using file URL. @param url The file @c NSURL of the database. @return The @c FMDatabasePool object. @c nil on error. */ + (instancetype)databasePoolWithURL:(NSURL * _Nullable)url; /** Create pool using path and specified flags @param aPath The file path of the database. @param openFlags Flags passed to the openWithFlags method of the database. @return The @c FMDatabasePool object. @c nil on error. */ + (instancetype)databasePoolWithPath:(NSString * _Nullable)aPath flags:(int)openFlags; /** Create pool using file URL and specified flags @param url The file @c NSURL of the database. @param openFlags Flags passed to the openWithFlags method of the database. @return The @c FMDatabasePool object. @c nil on error. */ + (instancetype)databasePoolWithURL:(NSURL * _Nullable)url flags:(int)openFlags; /** Create pool using path. @param aPath The file path of the database. @return The @c FMDatabasePool object. @c nil on error. */ - (instancetype)initWithPath:(NSString * _Nullable)aPath; /** Create pool using file URL. @param url The file `NSURL of the database. @return The @c FMDatabasePool object. @c nil on error. */ - (instancetype)initWithURL:(NSURL * _Nullable)url; /** Create pool using path and specified flags. @param aPath The file path of the database. @param openFlags Flags passed to the openWithFlags method of the database @return The @c FMDatabasePool object. @c nil on error. */ - (instancetype)initWithPath:(NSString * _Nullable)aPath flags:(int)openFlags; /** Create pool using file URL and specified flags. @param url The file @c NSURL of the database. @param openFlags Flags passed to the openWithFlags method of the database @return The @c FMDatabasePool object. @c nil on error. */ - (instancetype)initWithURL:(NSURL * _Nullable)url flags:(int)openFlags; /** Create pool using path and specified flags. @param aPath The file path of the database. @param openFlags Flags passed to the openWithFlags method of the database @param vfsName The name of a custom virtual file system @return The @c FMDatabasePool object. @c nil on error. */ - (instancetype)initWithPath:(NSString * _Nullable)aPath flags:(int)openFlags vfs:(NSString * _Nullable)vfsName; /** Create pool using file URL and specified flags. @param url The file @c NSURL of the database. @param openFlags Flags passed to the openWithFlags method of the database @param vfsName The name of a custom virtual file system @return The @c FMDatabasePool object. @c nil on error. */ - (instancetype)initWithURL:(NSURL * _Nullable)url flags:(int)openFlags vfs:(NSString * _Nullable)vfsName; /** Returns the Class of 'FMDatabase' subclass, that will be used to instantiate database object. Subclasses can override this method to return specified Class of 'FMDatabase' subclass. @return The Class of 'FMDatabase' subclass, that will be used to instantiate database object. */ + (Class)databaseClass; ///------------------------------------------------ /// @name Keeping track of checked in/out databases ///------------------------------------------------ /** Number of checked-in databases in pool */ @property (nonatomic, readonly) NSUInteger countOfCheckedInDatabases; /** Number of checked-out databases in pool */ @property (nonatomic, readonly) NSUInteger countOfCheckedOutDatabases; /** Total number of databases in pool */ @property (nonatomic, readonly) NSUInteger countOfOpenDatabases; /** Release all databases in pool */ - (void)releaseAllDatabases; ///------------------------------------------ /// @name Perform database operations in pool ///------------------------------------------ /** Synchronously perform database operations in pool. @param block The code to be run on the @c FMDatabasePool pool. */ - (void)inDatabase:(__attribute__((noescape)) void (^)(FMDatabase *db))block; /** Synchronously perform database operations in pool using transaction. @param block The code to be run on the @c FMDatabasePool pool. @warning Unlike SQLite's `BEGIN TRANSACTION`, this method currently performs an exclusive transaction, not a deferred transaction. This behavior is likely to change in future versions of FMDB, whereby this method will likely eventually adopt standard SQLite behavior and perform deferred transactions. If you really need exclusive tranaction, it is recommended that you use `inExclusiveTransaction`, instead, not only to make your intent explicit, but also to future-proof your code. */ - (void)inTransaction:(__attribute__((noescape)) void (^)(FMDatabase *db, BOOL *rollback))block; /** Synchronously perform database operations in pool using exclusive transaction. @param block The code to be run on the @c FMDatabasePool pool. */ - (void)inExclusiveTransaction:(__attribute__((noescape)) void (^)(FMDatabase *db, BOOL *rollback))block; /** Synchronously perform database operations in pool using deferred transaction. @param block The code to be run on the @c FMDatabasePool pool. */ - (void)inDeferredTransaction:(__attribute__((noescape)) void (^)(FMDatabase *db, BOOL *rollback))block; /** Synchronously perform database operations on queue, using immediate transactions. @param block The code to be run on the queue of @c FMDatabaseQueue */ - (void)inImmediateTransaction:(__attribute__((noescape)) void (^)(FMDatabase *db, BOOL *rollback))block; /** Synchronously perform database operations in pool using save point. @param block The code to be run on the @c FMDatabasePool pool. @return @c NSError object if error; @c nil if successful. @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 @c startSavePointWithName:error: instead. */ - (NSError * _Nullable)inSavePoint:(__attribute__((noescape)) void (^)(FMDatabase *db, BOOL *rollback))block; @end /** FMDatabasePool delegate category This is a category that defines the protocol for the FMDatabasePool delegate */ @interface NSObject (FMDatabasePoolDelegate) /** Asks the delegate whether database should be added to the pool. @param pool The @c FMDatabasePool object. @param database The @c FMDatabase object. @return @c YES if it should add database to pool; @c NO if not. */ - (BOOL)databasePool:(FMDatabasePool*)pool shouldAddDatabaseToPool:(FMDatabase*)database; /** Tells the delegate that database was added to the pool. @param pool The @c FMDatabasePool object. @param database The @c FMDatabase object. */ - (void)databasePool:(FMDatabasePool*)pool didAddDatabase:(FMDatabase*)database; @end NS_ASSUME_NONNULL_END ================================================ FILE: src/fmdb/FMDatabasePool.m ================================================ // // FMDatabasePool.m // fmdb // // Created by August Mueller on 6/22/11. // Copyright 2011 Flying Meat Inc. All rights reserved. // #if FMDB_SQLITE_STANDALONE #import #elif SQLCIPHER_CRYPTO #import #else #import #endif #import "FMDatabasePool.h" #import "FMDatabase.h" typedef NS_ENUM(NSInteger, FMDBTransaction) { FMDBTransactionExclusive, FMDBTransactionDeferred, FMDBTransactionImmediate, }; @interface FMDatabasePool () { dispatch_queue_t _lockQueue; NSMutableArray *_databaseInPool; NSMutableArray *_databaseOutPool; } - (void)pushDatabaseBackInPool:(FMDatabase*)db; - (FMDatabase*)db; @end @implementation FMDatabasePool @synthesize path=_path; @synthesize delegate=_delegate; @synthesize maximumNumberOfDatabasesToCreate=_maximumNumberOfDatabasesToCreate; @synthesize openFlags=_openFlags; + (instancetype)databasePoolWithPath:(NSString *)aPath { return FMDBReturnAutoreleased([[self alloc] initWithPath:aPath]); } + (instancetype)databasePoolWithURL:(NSURL *)url { return FMDBReturnAutoreleased([[self alloc] initWithPath:url.path]); } + (instancetype)databasePoolWithPath:(NSString *)aPath flags:(int)openFlags { return FMDBReturnAutoreleased([[self alloc] initWithPath:aPath flags:openFlags]); } + (instancetype)databasePoolWithURL:(NSURL *)url flags:(int)openFlags { return FMDBReturnAutoreleased([[self alloc] initWithPath:url.path flags:openFlags]); } - (instancetype)initWithURL:(NSURL *)url flags:(int)openFlags vfs:(NSString *)vfsName { return [self initWithPath:url.path flags:openFlags vfs:vfsName]; } - (instancetype)initWithPath:(NSString*)aPath flags:(int)openFlags vfs:(NSString *)vfsName { self = [super init]; if (self != nil) { _path = [aPath copy]; _lockQueue = dispatch_queue_create([[NSString stringWithFormat:@"fmdb.%@", self] UTF8String], NULL); _databaseInPool = FMDBReturnRetained([NSMutableArray array]); _databaseOutPool = FMDBReturnRetained([NSMutableArray array]); _openFlags = openFlags; _vfsName = [vfsName copy]; } return self; } - (instancetype)initWithPath:(NSString *)aPath flags:(int)openFlags { return [self initWithPath:aPath flags:openFlags vfs:nil]; } - (instancetype)initWithURL:(NSURL *)url flags:(int)openFlags { return [self initWithPath:url.path flags:openFlags vfs:nil]; } - (instancetype)initWithPath:(NSString*)aPath { // default flags for sqlite3_open return [self initWithPath:aPath flags:SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE]; } - (instancetype)initWithURL:(NSURL *)url { return [self initWithPath:url.path]; } - (instancetype)init { return [self initWithPath:nil]; } + (Class)databaseClass { return [FMDatabase class]; } - (void)dealloc { _delegate = 0x00; FMDBRelease(_path); FMDBRelease(_databaseInPool); FMDBRelease(_databaseOutPool); FMDBRelease(_vfsName); if (_lockQueue) { FMDBDispatchQueueRelease(_lockQueue); _lockQueue = 0x00; } #if ! __has_feature(objc_arc) [super dealloc]; #endif } - (void)executeLocked:(void (^)(void))aBlock { dispatch_sync(_lockQueue, aBlock); } - (void)pushDatabaseBackInPool:(FMDatabase*)db { if (!db) { // db can be null if we set an upper bound on the # of databases to create. return; } [self executeLocked:^() { if ([self->_databaseInPool containsObject:db]) { [[NSException exceptionWithName:@"Database already in pool" reason:@"The FMDatabase being put back into the pool is already present in the pool" userInfo:nil] raise]; } [self->_databaseInPool addObject:db]; [self->_databaseOutPool removeObject:db]; }]; } - (FMDatabase*)db { __block FMDatabase *db; [self executeLocked:^() { db = [self->_databaseInPool lastObject]; BOOL shouldNotifyDelegate = NO; if (db) { [self->_databaseOutPool addObject:db]; [self->_databaseInPool removeLastObject]; } else { if (self->_maximumNumberOfDatabasesToCreate) { NSUInteger currentCount = [self->_databaseOutPool count] + [self->_databaseInPool count]; if (currentCount >= self->_maximumNumberOfDatabasesToCreate) { NSLog(@"Maximum number of databases (%ld) has already been reached!", (long)currentCount); return; } } db = [[[self class] databaseClass] databaseWithPath:self->_path]; shouldNotifyDelegate = YES; } //This ensures that the db is opened before returning #if SQLITE_VERSION_NUMBER >= 3005000 BOOL success = [db openWithFlags:self->_openFlags vfs:self->_vfsName]; #else BOOL success = [db open]; #endif if (success) { if ([self->_delegate respondsToSelector:@selector(databasePool:shouldAddDatabaseToPool:)] && ![self->_delegate databasePool:self shouldAddDatabaseToPool:db]) { [db close]; db = 0x00; } else { //It should not get added in the pool twice if lastObject was found if (![self->_databaseOutPool containsObject:db]) { [self->_databaseOutPool addObject:db]; if (shouldNotifyDelegate && [self->_delegate respondsToSelector:@selector(databasePool:didAddDatabase:)]) { [self->_delegate databasePool:self didAddDatabase:db]; } } } } else { NSLog(@"Could not open up the database at path %@", self->_path); db = 0x00; } }]; return db; } - (NSUInteger)countOfCheckedInDatabases { __block NSUInteger count; [self executeLocked:^() { count = [self->_databaseInPool count]; }]; return count; } - (NSUInteger)countOfCheckedOutDatabases { __block NSUInteger count; [self executeLocked:^() { count = [self->_databaseOutPool count]; }]; return count; } - (NSUInteger)countOfOpenDatabases { __block NSUInteger count; [self executeLocked:^() { count = [self->_databaseOutPool count] + [self->_databaseInPool count]; }]; return count; } - (void)releaseAllDatabases { [self executeLocked:^() { [self->_databaseOutPool removeAllObjects]; [self->_databaseInPool removeAllObjects]; }]; } - (void)inDatabase:(__attribute__((noescape)) void (^)(FMDatabase *db))block { FMDatabase *db = [self db]; block(db); [self pushDatabaseBackInPool:db]; } - (void)beginTransaction:(FMDBTransaction)transaction withBlock:(void (^)(FMDatabase *db, BOOL *rollback))block { BOOL shouldRollback = NO; FMDatabase *db = [self db]; switch (transaction) { case FMDBTransactionExclusive: [db beginTransaction]; break; case FMDBTransactionDeferred: [db beginDeferredTransaction]; break; case FMDBTransactionImmediate: [db beginImmediateTransaction]; break; } block(db, &shouldRollback); if (shouldRollback) { [db rollback]; } else { [db commit]; } [self pushDatabaseBackInPool:db]; } - (void)inTransaction:(__attribute__((noescape)) void (^)(FMDatabase *db, BOOL *rollback))block { [self beginTransaction:FMDBTransactionExclusive withBlock:block]; } - (void)inDeferredTransaction:(__attribute__((noescape)) void (^)(FMDatabase *db, BOOL *rollback))block { [self beginTransaction:FMDBTransactionDeferred withBlock:block]; } - (void)inExclusiveTransaction:(__attribute__((noescape)) void (^)(FMDatabase *db, BOOL *rollback))block { [self beginTransaction:FMDBTransactionExclusive withBlock:block]; } - (void)inImmediateTransaction:(__attribute__((noescape)) void (^)(FMDatabase *db, BOOL *rollback))block { [self beginTransaction:FMDBTransactionImmediate withBlock:block]; } - (NSError*)inSavePoint:(__attribute__((noescape)) void (^)(FMDatabase *db, BOOL *rollback))block { #if SQLITE_VERSION_NUMBER >= 3007000 static unsigned long savePointIdx = 0; NSString *name = [NSString stringWithFormat:@"savePoint%ld", savePointIdx++]; BOOL shouldRollback = NO; FMDatabase *db = [self db]; NSError *err = 0x00; if (![db startSavePointWithName:name error:&err]) { [self pushDatabaseBackInPool:db]; return err; } block(db, &shouldRollback); if (shouldRollback) { // We need to rollback and release this savepoint to remove it [db rollbackToSavePointWithName:name error:&err]; } [db releaseSavePointWithName:name error:&err]; [self pushDatabaseBackInPool:db]; return err; #else NSString *errorMessage = NSLocalizedStringFromTable(@"Save point functions require SQLite 3.7", @"FMDB", nil); if (self.logsErrors) NSLog(@"%@", errorMessage); return [NSError errorWithDomain:@"FMDatabase" code:0 userInfo:@{NSLocalizedDescriptionKey : errorMessage}]; #endif } @end ================================================ FILE: src/fmdb/FMDatabaseQueue.h ================================================ // // FMDatabaseQueue.h // fmdb // // Created by August Mueller on 6/22/11. // Copyright 2011 Flying Meat Inc. All rights reserved. // #import #import "FMDatabase.h" NS_ASSUME_NONNULL_BEGIN /** To perform queries and updates on multiple threads, you'll want to use @c FMDatabaseQueue . Using a single instance of @c FMDatabase from multiple threads at once is a bad idea. It has always been OK to make a @c FMDatabase object *per thread*. Just don't share a single instance across threads, and definitely not across multiple threads at the same time. Instead, use @c FMDatabaseQueue . Here's how to use it: First, make your queue. @code FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:aPath]; @endcode Then use it like so: @code [queue inDatabase:^(FMDatabase *db) { [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:1]]; [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:2]]; [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:3]]; FMResultSet *rs = [db executeQuery:@"select * from foo"]; while ([rs next]) { //… } }]; @endcode An easy way to wrap things up in a transaction can be done like this: @code [queue inTransaction:^(FMDatabase *db, BOOL *rollback) { [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:1]]; [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:2]]; [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:3]]; // if (whoopsSomethingWrongHappened) { // *rollback = YES; // return; // } // etc… [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:4]]; }]; @endcode @c FMDatabaseQueue will run the blocks on a serialized queue (hence the name of the class). So if you call @c 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. @warning Do not instantiate a single @c FMDatabase object and use it across multiple threads. Use @c FMDatabaseQueue instead. @warning The calls to @c FMDatabaseQueue 's methods are blocking. So even though you are passing along blocks, they will **not** be run on another thread. @sa FMDatabase */ @interface FMDatabaseQueue : NSObject /** Path of database */ @property (atomic, retain, nullable) NSString *path; /** Open flags */ @property (atomic, readonly) int openFlags; /** Custom virtual file system name */ @property (atomic, copy, nullable) NSString *vfsName; ///---------------------------------------------------- /// @name Initialization, opening, and closing of queue ///---------------------------------------------------- /** Create queue using path. @param aPath The file path of the database. @return The @c FMDatabaseQueue object. @c nil on error. */ + (nullable instancetype)databaseQueueWithPath:(NSString * _Nullable)aPath; /** Create queue using file URL. @param url The file @c NSURL of the database. @return The @c FMDatabaseQueue object. @c nil on error. */ + (nullable instancetype)databaseQueueWithURL:(NSURL * _Nullable)url; /** Create queue using path and specified flags. @param aPath The file path of the database. @param openFlags Flags passed to the openWithFlags method of the database. @return The @c FMDatabaseQueue object. @c nil on error. */ + (nullable instancetype)databaseQueueWithPath:(NSString * _Nullable)aPath flags:(int)openFlags; /** Create queue using file URL and specified flags. @param url The file @c NSURL of the database. @param openFlags Flags passed to the openWithFlags method of the database. @return The @c FMDatabaseQueue object. @c nil on error. */ + (nullable instancetype)databaseQueueWithURL:(NSURL * _Nullable)url flags:(int)openFlags; /** Create queue using path. @param aPath The file path of the database. @return The @c FMDatabaseQueue object. @c nil on error. */ - (nullable instancetype)initWithPath:(NSString * _Nullable)aPath; /** Create queue using file URL. @param url The file `NSURL of the database. @return The @c FMDatabaseQueue object. @c nil on error. */ - (nullable instancetype)initWithURL:(NSURL * _Nullable)url; /** Create queue using path and specified flags. @param aPath The file path of the database. @param openFlags Flags passed to the openWithFlags method of the database. @return The @c FMDatabaseQueue object. @c nil on error. */ - (nullable instancetype)initWithPath:(NSString * _Nullable)aPath flags:(int)openFlags; /** Create queue using file URL and specified flags. @param url The file path of the database. @param openFlags Flags passed to the openWithFlags method of the database. @return The @c FMDatabaseQueue object. @c nil on error. */ - (nullable instancetype)initWithURL:(NSURL * _Nullable)url flags:(int)openFlags; /** Create queue using path and specified flags. @param aPath The file path of the database. @param openFlags Flags passed to the openWithFlags method of the database @param vfsName The name of a custom virtual file system @return The @c FMDatabaseQueue object. @c nil on error. */ - (nullable instancetype)initWithPath:(NSString * _Nullable)aPath flags:(int)openFlags vfs:(NSString * _Nullable)vfsName; /** Create queue using file URL and specified flags. @param url The file `NSURL of the database. @param openFlags Flags passed to the openWithFlags method of the database @param vfsName The name of a custom virtual file system @return The @c FMDatabaseQueue object. @c nil on error. */ - (nullable instancetype)initWithURL:(NSURL * _Nullable)url flags:(int)openFlags vfs:(NSString * _Nullable)vfsName; /** Returns the Class of 'FMDatabase' subclass, that will be used to instantiate database object. Subclasses can override this method to return specified Class of 'FMDatabase' subclass. @return The Class of 'FMDatabase' subclass, that will be used to instantiate database object. */ + (Class)databaseClass; /** Close database used by queue. */ - (void)close; /** Interupt pending database operation. */ - (void)interrupt; ///----------------------------------------------- /// @name Dispatching database operations to queue ///----------------------------------------------- /** Synchronously perform database operations on queue. @param block The code to be run on the queue of @c FMDatabaseQueue */ - (void)inDatabase:(__attribute__((noescape)) void (^)(FMDatabase *db))block; /** Synchronously perform database operations on queue, using transactions. @param block The code to be run on the queue of @c FMDatabaseQueue @warning Unlike SQLite's `BEGIN TRANSACTION`, this method currently performs an exclusive transaction, not a deferred transaction. This behavior is likely to change in future versions of FMDB, whereby this method will likely eventually adopt standard SQLite behavior and perform deferred transactions. If you really need exclusive tranaction, it is recommended that you use `inExclusiveTransaction`, instead, not only to make your intent explicit, but also to future-proof your code. */ - (void)inTransaction:(__attribute__((noescape)) void (^)(FMDatabase *db, BOOL *rollback))block; /** Synchronously perform database operations on queue, using deferred transactions. @param block The code to be run on the queue of @c FMDatabaseQueue */ - (void)inDeferredTransaction:(__attribute__((noescape)) void (^)(FMDatabase *db, BOOL *rollback))block; /** Synchronously perform database operations on queue, using exclusive transactions. @param block The code to be run on the queue of @c FMDatabaseQueue */ - (void)inExclusiveTransaction:(__attribute__((noescape)) void (^)(FMDatabase *db, BOOL *rollback))block; /** Synchronously perform database operations on queue, using immediate transactions. @param block The code to be run on the queue of @c FMDatabaseQueue */ - (void)inImmediateTransaction:(__attribute__((noescape)) void (^)(FMDatabase *db, BOOL *rollback))block; ///----------------------------------------------- /// @name Dispatching database operations to queue ///----------------------------------------------- /** Synchronously perform database operations using save point. @param block The code to be run on the queue of @c FMDatabaseQueue */ // NOTE: 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's startSavePointWithName:error: instead. - (NSError * _Nullable)inSavePoint:(__attribute__((noescape)) void (^)(FMDatabase *db, BOOL *rollback))block; ///----------------- /// @name Checkpoint ///----------------- /** Performs a WAL checkpoint @param checkpointMode The checkpoint mode for sqlite3_wal_checkpoint_v2 @param error The NSError corresponding to the error, if any. @return YES on success, otherwise NO. */ - (BOOL)checkpoint:(FMDBCheckpointMode)checkpointMode error:(NSError * _Nullable *)error; /** Performs a WAL checkpoint @param checkpointMode The checkpoint mode for sqlite3_wal_checkpoint_v2 @param name The db name for sqlite3_wal_checkpoint_v2 @param error The NSError corresponding to the error, if any. @return YES on success, otherwise NO. */ - (BOOL)checkpoint:(FMDBCheckpointMode)checkpointMode name:(NSString * _Nullable)name error:(NSError * _Nullable *)error; /** Performs a WAL checkpoint @param checkpointMode The checkpoint mode for sqlite3_wal_checkpoint_v2 @param name The db name for sqlite3_wal_checkpoint_v2 @param error The NSError corresponding to the error, if any. @param logFrameCount If not NULL, then this is set to the total number of frames in the log file or to -1 if the checkpoint could not run because of an error or because the database is not in WAL mode. @param checkpointCount If not NULL, then this is set to the total number of checkpointed frames in the log file (including any that were already checkpointed before the function was called) or to -1 if the checkpoint could not run due to an error or because the database is not in WAL mode. @return YES on success, otherwise NO. */ - (BOOL)checkpoint:(FMDBCheckpointMode)checkpointMode name:(NSString * _Nullable)name logFrameCount:(int * _Nullable)logFrameCount checkpointCount:(int * _Nullable)checkpointCount error:(NSError * _Nullable *)error; @end NS_ASSUME_NONNULL_END ================================================ FILE: src/fmdb/FMDatabaseQueue.m ================================================ // // FMDatabaseQueue.m // fmdb // // Created by August Mueller on 6/22/11. // Copyright 2011 Flying Meat Inc. All rights reserved. // #import "FMDatabaseQueue.h" #import "FMDatabase.h" #if FMDB_SQLITE_STANDALONE #import #elif SQLCIPHER_CRYPTO #import #else #import #endif typedef NS_ENUM(NSInteger, FMDBTransaction) { FMDBTransactionExclusive, FMDBTransactionDeferred, FMDBTransactionImmediate, }; /* Note: we call [self retain]; before using dispatch_sync, just incase FMDatabaseQueue is released on another thread and we're in the middle of doing something in dispatch_sync */ /* * A key used to associate the FMDatabaseQueue object with the dispatch_queue_t it uses. * This in turn is used for deadlock detection by seeing if inDatabase: is called on * the queue's dispatch queue, which should not happen and causes a deadlock. */ static const void * const kDispatchQueueSpecificKey = &kDispatchQueueSpecificKey; @interface FMDatabaseQueue () { dispatch_queue_t _queue; FMDatabase *_db; } @end @implementation FMDatabaseQueue + (instancetype)databaseQueueWithPath:(NSString *)aPath { FMDatabaseQueue *q = [[self alloc] initWithPath:aPath]; FMDBAutorelease(q); return q; } + (instancetype)databaseQueueWithURL:(NSURL *)url { return [self databaseQueueWithPath:url.path]; } + (instancetype)databaseQueueWithPath:(NSString *)aPath flags:(int)openFlags { FMDatabaseQueue *q = [[self alloc] initWithPath:aPath flags:openFlags]; FMDBAutorelease(q); return q; } + (instancetype)databaseQueueWithURL:(NSURL *)url flags:(int)openFlags { return [self databaseQueueWithPath:url.path flags:openFlags]; } + (Class)databaseClass { return [FMDatabase class]; } - (instancetype)initWithURL:(NSURL *)url flags:(int)openFlags vfs:(NSString *)vfsName { return [self initWithPath:url.path flags:openFlags vfs:vfsName]; } - (instancetype)initWithPath:(NSString*)aPath flags:(int)openFlags vfs:(NSString *)vfsName { self = [super init]; if (self != nil) { _db = [[[self class] databaseClass] databaseWithPath:aPath]; FMDBRetain(_db); #if SQLITE_VERSION_NUMBER >= 3005000 BOOL success = [_db openWithFlags:openFlags vfs:vfsName]; #else BOOL success = [_db open]; #endif if (!success) { NSLog(@"Could not create database queue for path %@", aPath); FMDBRelease(self); return 0x00; } _path = FMDBReturnRetained(aPath); _queue = dispatch_queue_create([[NSString stringWithFormat:@"fmdb.%@", self] UTF8String], NULL); dispatch_queue_set_specific(_queue, kDispatchQueueSpecificKey, (__bridge void *)self, NULL); _openFlags = openFlags; _vfsName = [vfsName copy]; } return self; } - (instancetype)initWithPath:(NSString *)aPath flags:(int)openFlags { return [self initWithPath:aPath flags:openFlags vfs:nil]; } - (instancetype)initWithURL:(NSURL *)url flags:(int)openFlags { return [self initWithPath:url.path flags:openFlags vfs:nil]; } - (instancetype)initWithURL:(NSURL *)url { return [self initWithPath:url.path]; } - (instancetype)initWithPath:(NSString *)aPath { // default flags for sqlite3_open return [self initWithPath:aPath flags:SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE vfs:nil]; } - (instancetype)init { return [self initWithPath:nil]; } - (void)dealloc { FMDBRelease(_db); FMDBRelease(_path); FMDBRelease(_vfsName); if (_queue) { FMDBDispatchQueueRelease(_queue); _queue = 0x00; } #if ! __has_feature(objc_arc) [super dealloc]; #endif } - (void)close { FMDBRetain(self); dispatch_sync(_queue, ^() { [self->_db close]; FMDBRelease(_db); self->_db = 0x00; }); FMDBRelease(self); } - (void)interrupt { [[self database] interrupt]; } - (FMDatabase*)database { if (![_db isOpen]) { if (!_db) { _db = FMDBReturnRetained([[[self class] databaseClass] databaseWithPath:_path]); } #if SQLITE_VERSION_NUMBER >= 3005000 BOOL success = [_db openWithFlags:_openFlags vfs:_vfsName]; #else BOOL success = [_db open]; #endif if (!success) { NSLog(@"FMDatabaseQueue could not reopen database for path %@", _path); FMDBRelease(_db); _db = 0x00; return 0x00; } } return _db; } - (void)inDatabase:(__attribute__((noescape)) void (^)(FMDatabase *db))block { #ifndef NDEBUG /* Get the currently executing queue (which should probably be nil, but in theory could be another DB queue * and then check it against self to make sure we're not about to deadlock. */ FMDatabaseQueue *currentSyncQueue = (__bridge id)dispatch_get_specific(kDispatchQueueSpecificKey); assert(currentSyncQueue != self && "inDatabase: was called reentrantly on the same queue, which would lead to a deadlock"); #endif FMDBRetain(self); dispatch_sync(_queue, ^() { FMDatabase *db = [self database]; block(db); if ([db hasOpenResultSets]) { NSLog(@"Warning: there is at least one open result set around after performing [FMDatabaseQueue inDatabase:]"); #if defined(DEBUG) && DEBUG NSSet *openSetCopy = FMDBReturnAutoreleased([[db valueForKey:@"_openResultSets"] copy]); for (NSValue *rsInWrappedInATastyValueMeal in openSetCopy) { FMResultSet *rs = (FMResultSet *)[rsInWrappedInATastyValueMeal pointerValue]; NSLog(@"query: '%@'", [rs query]); } #endif } }); FMDBRelease(self); } - (void)beginTransaction:(FMDBTransaction)transaction withBlock:(void (^)(FMDatabase *db, BOOL *rollback))block { FMDBRetain(self); dispatch_sync(_queue, ^() { BOOL shouldRollback = NO; switch (transaction) { case FMDBTransactionExclusive: [[self database] beginTransaction]; break; case FMDBTransactionDeferred: [[self database] beginDeferredTransaction]; break; case FMDBTransactionImmediate: [[self database] beginImmediateTransaction]; break; } block([self database], &shouldRollback); if (shouldRollback) { [[self database] rollback]; } else { [[self database] commit]; } }); FMDBRelease(self); } - (void)inTransaction:(__attribute__((noescape)) void (^)(FMDatabase *db, BOOL *rollback))block { [self beginTransaction:FMDBTransactionExclusive withBlock:block]; } - (void)inDeferredTransaction:(__attribute__((noescape)) void (^)(FMDatabase *db, BOOL *rollback))block { [self beginTransaction:FMDBTransactionDeferred withBlock:block]; } - (void)inExclusiveTransaction:(__attribute__((noescape)) void (^)(FMDatabase *db, BOOL *rollback))block { [self beginTransaction:FMDBTransactionExclusive withBlock:block]; } - (void)inImmediateTransaction:(__attribute__((noescape)) void (^)(FMDatabase * _Nonnull, BOOL * _Nonnull))block { [self beginTransaction:FMDBTransactionImmediate withBlock:block]; } - (NSError*)inSavePoint:(__attribute__((noescape)) void (^)(FMDatabase *db, BOOL *rollback))block { #if SQLITE_VERSION_NUMBER >= 3007000 static unsigned long savePointIdx = 0; __block NSError *err = 0x00; FMDBRetain(self); dispatch_sync(_queue, ^() { NSString *name = [NSString stringWithFormat:@"savePoint%ld", savePointIdx++]; BOOL shouldRollback = NO; if ([[self database] startSavePointWithName:name error:&err]) { block([self database], &shouldRollback); if (shouldRollback) { // We need to rollback and release this savepoint to remove it [[self database] rollbackToSavePointWithName:name error:&err]; } [[self database] releaseSavePointWithName:name error:&err]; } }); FMDBRelease(self); return err; #else NSString *errorMessage = NSLocalizedStringFromTable(@"Save point functions require SQLite 3.7", @"FMDB", nil); if (_db.logsErrors) NSLog(@"%@", errorMessage); return [NSError errorWithDomain:@"FMDatabase" code:0 userInfo:@{NSLocalizedDescriptionKey : errorMessage}]; #endif } - (BOOL)checkpoint:(FMDBCheckpointMode)mode error:(NSError * __autoreleasing *)error { return [self checkpoint:mode name:nil logFrameCount:NULL checkpointCount:NULL error:error]; } - (BOOL)checkpoint:(FMDBCheckpointMode)mode name:(NSString *)name error:(NSError * __autoreleasing *)error { return [self checkpoint:mode name:name logFrameCount:NULL checkpointCount:NULL error:error]; } - (BOOL)checkpoint:(FMDBCheckpointMode)mode name:(NSString *)name logFrameCount:(int * _Nullable)logFrameCount checkpointCount:(int * _Nullable)checkpointCount error:(NSError * __autoreleasing _Nullable * _Nullable)error { __block BOOL result; FMDBRetain(self); dispatch_sync(_queue, ^() { result = [self.database checkpoint:mode name:name logFrameCount:logFrameCount checkpointCount:checkpointCount error:error]; }); FMDBRelease(self); return result; } @end ================================================ FILE: src/fmdb/FMResultSet.h ================================================ #import NS_ASSUME_NONNULL_BEGIN #ifndef __has_feature // Optional. #define __has_feature(x) 0 // Compatibility with non-clang compilers. #endif #ifndef NS_RETURNS_NOT_RETAINED #if __has_feature(attribute_ns_returns_not_retained) #define NS_RETURNS_NOT_RETAINED __attribute__((ns_returns_not_retained)) #else #define NS_RETURNS_NOT_RETAINED #endif #endif @class FMDatabase; @class FMStatement; /** Types for columns in a result set. */ typedef NS_ENUM(int, SqliteValueType) { SqliteValueTypeInteger = 1, SqliteValueTypeFloat = 2, SqliteValueTypeText = 3, SqliteValueTypeBlob = 4, SqliteValueTypeNull = 5 }; /** Represents the results of executing a query on an @c FMDatabase . See also - @c FMDatabase */ @interface FMResultSet : NSObject @property (nonatomic, retain, nullable) FMDatabase *parentDB; ///----------------- /// @name Properties ///----------------- /** Executed query */ @property (atomic, retain, nullable) NSString *query; /** `NSMutableDictionary` mapping column names to numeric index */ @property (readonly) NSMutableDictionary *columnNameToIndexMap; /** `FMStatement` used by result set. */ @property (atomic, retain, nullable) FMStatement *statement; ///------------------------------------ /// @name Creating and closing a result set ///------------------------------------ /** Close result set */ - (void)close; ///--------------------------------------- /// @name Iterating through the result set ///--------------------------------------- /** Retrieve next row for result set. You must always invoke `next` or `nextWithError` before attempting to access the values returned in a query, even if you're only expecting one. @return @c YES if row successfully retrieved; @c NO if end of result set reached @see hasAnotherRow */ - (BOOL)next; /** Retrieve next row for result set. You must always invoke `next` or `nextWithError` before attempting to access the values returned in a query, even if you're only expecting one. @param outErr A 'NSError' object to receive any error object (if any). @return 'YES' if row successfully retrieved; 'NO' if end of result set reached @see hasAnotherRow */ - (BOOL)nextWithError:(NSError * _Nullable __autoreleasing *)outErr; /** Perform SQL statement. @return 'YES' if successful; 'NO' if not. @see hasAnotherRow */ - (BOOL)step; /** Perform SQL statement. @param outErr A 'NSError' object to receive any error object (if any). @return 'YES' if successful; 'NO' if not. @see hasAnotherRow */ - (BOOL)stepWithError:(NSError * _Nullable __autoreleasing *)outErr; /** Did the last call to `` succeed in retrieving another row? @return 'YES' if there is another row; 'NO' if not. @see next @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 @c NO, whether there is another row of data or not. */ - (BOOL)hasAnotherRow; ///--------------------------------------------- /// @name Retrieving information from result set ///--------------------------------------------- /** How many columns in result set @return Integer value of the number of columns. */ @property (nonatomic, readonly) int columnCount; /** Column index for column name @param columnName @c NSString value of the name of the column. @return Zero-based index for column. */ - (int)columnIndexForName:(NSString*)columnName; /** Column name for column index @param columnIdx Zero-based index for column. @return columnName @c NSString value of the name of the column. */ - (NSString * _Nullable)columnNameForIndex:(int)columnIdx; /** Result set integer value for column. @param columnName @c NSString value of the name of the column. @return @c int value of the result set's column. */ - (int)intForColumn:(NSString*)columnName; /** Result set integer value for column. @param columnIdx Zero-based index for column. @return @c int value of the result set's column. */ - (int)intForColumnIndex:(int)columnIdx; /** Result set @c long value for column. @param columnName @c NSString value of the name of the column. @return @c long value of the result set's column. */ - (long)longForColumn:(NSString*)columnName; /** Result set long value for column. @param columnIdx Zero-based index for column. @return @c long value of the result set's column. */ - (long)longForColumnIndex:(int)columnIdx; /** Result set `long long int` value for column. @param columnName @c NSString value of the name of the column. @return `long long int` value of the result set's column. */ - (long long int)longLongIntForColumn:(NSString*)columnName; /** Result set `long long int` value for column. @param columnIdx Zero-based index for column. @return `long long int` value of the result set's column. */ - (long long int)longLongIntForColumnIndex:(int)columnIdx; /** Result set `unsigned long long int` value for column. @param columnName @c NSString value of the name of the column. @return `unsigned long long int` value of the result set's column. */ - (unsigned long long int)unsignedLongLongIntForColumn:(NSString*)columnName; /** Result set `unsigned long long int` value for column. @param columnIdx Zero-based index for column. @return `unsigned long long int` value of the result set's column. */ - (unsigned long long int)unsignedLongLongIntForColumnIndex:(int)columnIdx; /** Result set `BOOL` value for column. @param columnName @c NSString value of the name of the column. @return `BOOL` value of the result set's column. */ - (BOOL)boolForColumn:(NSString*)columnName; /** Result set `BOOL` value for column. @param columnIdx Zero-based index for column. @return `BOOL` value of the result set's column. */ - (BOOL)boolForColumnIndex:(int)columnIdx; /** Result set `double` value for column. @param columnName @c NSString value of the name of the column. @return `double` value of the result set's column. */ - (double)doubleForColumn:(NSString*)columnName; /** Result set `double` value for column. @param columnIdx Zero-based index for column. @return `double` value of the result set's column. */ - (double)doubleForColumnIndex:(int)columnIdx; /** Result set @c NSString value for column. @param columnName @c NSString value of the name of the column. @return String value of the result set's column. */ - (NSString * _Nullable)stringForColumn:(NSString*)columnName; /** Result set @c NSString value for column. @param columnIdx Zero-based index for column. @return String value of the result set's column. */ - (NSString * _Nullable)stringForColumnIndex:(int)columnIdx; /** Result set @c NSDate value for column. @param columnName @c NSString value of the name of the column. @return Date value of the result set's column. */ - (NSDate * _Nullable)dateForColumn:(NSString*)columnName; /** Result set @c NSDate value for column. @param columnIdx Zero-based index for column. @return Date value of the result set's column. */ - (NSDate * _Nullable)dateForColumnIndex:(int)columnIdx; /** Result set @c NSData value for column. This is useful when storing binary data in table (such as image or the like). @param columnName @c NSString value of the name of the column. @return Data value of the result set's column. */ - (NSData * _Nullable)dataForColumn:(NSString*)columnName; /** Result set @c NSData value for column. @param columnIdx Zero-based index for column. @warning For zero length BLOBs, this will return `nil`. Use `typeForColumn` to determine whether this was really a zero length BLOB or `NULL`. @return Data value of the result set's column. */ - (NSData * _Nullable)dataForColumnIndex:(int)columnIdx; /** Result set `(const unsigned char *)` value for column. @param columnName @c NSString value of the name of the column. @warning For zero length BLOBs, this will return `nil`. Use `typeForColumnIndex` to determine whether this was really a zero length BLOB or `NULL`. @return `(const unsigned char *)` value of the result set's column. */ - (const unsigned char * _Nullable)UTF8StringForColumn:(NSString*)columnName; - (const unsigned char * _Nullable)UTF8StringForColumnName:(NSString*)columnName __deprecated_msg("Use UTF8StringForColumn instead"); /** Result set `(const unsigned char *)` value for column. @param columnIdx Zero-based index for column. @return `(const unsigned char *)` value of the result set's column. */ - (const unsigned char * _Nullable)UTF8StringForColumnIndex:(int)columnIdx; /** Result set object for column. @param columnName Name of the column. @return Either @c NSNumber , @c NSString , @c NSData , or @c NSNull . If the column was @c NULL , this returns `[NSNull null]` object. @see objectForKeyedSubscript: */ - (id _Nullable)objectForColumn:(NSString*)columnName; - (id _Nullable)objectForColumnName:(NSString*)columnName __deprecated_msg("Use objectForColumn instead"); /** Column type by column name. @param columnName Name of the column. @return The `SqliteValueType` of the value in this column. */ - (SqliteValueType)typeForColumn:(NSString*)columnName; /** Column type by column index. @param columnIdx Index of the column. @return The `SqliteValueType` of the value in this column. */ - (SqliteValueType)typeForColumnIndex:(int)columnIdx; /** Result set object for column. @param columnIdx Zero-based index for column. @return Either @c NSNumber , @c NSString , @c NSData , or @c NSNull . If the column was @c NULL , this returns `[NSNull null]` object. @see objectAtIndexedSubscript: */ - (id _Nullable)objectForColumnIndex:(int)columnIdx; /** Result set object for column. 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: @code id result = rs[@"employee_name"]; @endcode This simplified syntax is equivalent to calling: @code id result = [rs objectForKeyedSubscript:@"employee_name"]; @endcode which is, it turns out, equivalent to calling: @code id result = [rs objectForColumnName:@"employee_name"]; @endcode @param columnName @c NSString value of the name of the column. @return Either @c NSNumber , @c NSString , @c NSData , or @c NSNull . If the column was @c NULL , this returns `[NSNull null]` object. */ - (id _Nullable)objectForKeyedSubscript:(NSString *)columnName; /** Result set object for column. 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: @code id result = rs[0]; @endcode This simplified syntax is equivalent to calling: @code id result = [rs objectForKeyedSubscript:0]; @endcode which is, it turns out, equivalent to calling: @code id result = [rs objectForColumnName:0]; @endcode @param columnIdx Zero-based index for column. @return Either @c NSNumber , @c NSString , @c NSData , or @c NSNull . If the column was @c NULL , this returns `[NSNull null]` object. */ - (id _Nullable)objectAtIndexedSubscript:(int)columnIdx; /** Result set @c NSData value for column. @param columnName @c NSString value of the name of the column. @return Data value of the result set's column. @warning If you are going to use this data after you iterate over the next row, or after you close the result set, make sure to make a copy of the data first (or just use ``/``) If you don't, you're going to be in a world of hurt when you try and use the data. */ - (NSData * _Nullable)dataNoCopyForColumn:(NSString *)columnName NS_RETURNS_NOT_RETAINED; /** Result set @c NSData value for column. @param columnIdx Zero-based index for column. @return Data value of the result set's column. @warning If you are going to use this data after you iterate over the next row, or after you close the result set, make sure to make a copy of the data first (or just use ``/``) If you don't, you're going to be in a world of hurt when you try and use the data. */ - (NSData * _Nullable)dataNoCopyForColumnIndex:(int)columnIdx NS_RETURNS_NOT_RETAINED; /** Is the column @c NULL ? @param columnIdx Zero-based index for column. @return @c YES if column is @c NULL ; @c NO if not @c NULL . */ - (BOOL)columnIndexIsNull:(int)columnIdx; /** Is the column @c NULL ? @param columnName @c NSString value of the name of the column. @return @c YES if column is @c NULL ; @c NO if not @c NULL . */ - (BOOL)columnIsNull:(NSString*)columnName; /** Returns a dictionary of the row results mapped to case sensitive keys of the column names. @warning The keys to the dictionary are case sensitive of the column names. */ @property (nonatomic, readonly, nullable) NSDictionary *resultDictionary; /** Returns a dictionary of the row results @see resultDictionary @warning **Deprecated**: Please use `` instead. Also, beware that `` is case sensitive! */ - (NSDictionary * _Nullable)resultDict __deprecated_msg("Use resultDictionary instead"); ///----------------------------- /// @name Key value coding magic ///----------------------------- /** Performs `setValue` to yield support for key value observing. @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. */ - (void)kvcMagic:(id)object; ///----------------------------- /// @name Binding values ///----------------------------- /// Bind array of values to prepared statement. /// /// @param array Array of values to bind to SQL statement. - (BOOL)bindWithArray:(NSArray*)array; /// Bind dictionary of values to prepared statement. /// /// @param dictionary Dictionary of values to bind to SQL statement. - (BOOL)bindWithDictionary:(NSDictionary *)dictionary; @end NS_ASSUME_NONNULL_END ================================================ FILE: src/fmdb/FMResultSet.m ================================================ #import "FMResultSet.h" #import "FMDatabase.h" #import #if FMDB_SQLITE_STANDALONE #import #elif SQLCIPHER_CRYPTO #import #else #import #endif // MARK: - FMDatabase Private Extension @interface FMDatabase () - (void)resultSetDidClose:(FMResultSet *)resultSet; - (BOOL)bindStatement:(sqlite3_stmt *)pStmt WithArgumentsInArray:(NSArray*)arrayArgs orDictionary:(NSDictionary *)dictionaryArgs orVAList:(va_list)args; @end // MARK: - FMResultSet Private Extension @interface FMResultSet () { NSMutableDictionary *_columnNameToIndexMap; } @property (nonatomic) BOOL shouldAutoClose; @end // MARK: - FMResultSet @implementation FMResultSet + (instancetype)resultSetWithStatement:(FMStatement *)statement usingParentDatabase:(FMDatabase*)aDB shouldAutoClose:(BOOL)shouldAutoClose { FMResultSet *rs = [[FMResultSet alloc] init]; [rs setStatement:statement]; [rs setParentDB:aDB]; [rs setShouldAutoClose:shouldAutoClose]; NSParameterAssert(![statement inUse]); [statement setInUse:YES]; // weak reference return FMDBReturnAutoreleased(rs); } #if ! __has_feature(objc_arc) - (void)finalize { [self close]; [super finalize]; } #endif - (void)dealloc { [self close]; FMDBRelease(_query); _query = nil; FMDBRelease(_columnNameToIndexMap); _columnNameToIndexMap = nil; #if ! __has_feature(objc_arc) [super dealloc]; #endif } - (void)close { [_statement reset]; FMDBRelease(_statement); _statement = nil; // we don't need this anymore... (i think) //[_parentDB setInUse:NO]; [_parentDB resultSetDidClose:self]; [self setParentDB:nil]; } - (int)columnCount { return sqlite3_column_count([_statement statement]); } - (NSMutableDictionary *)columnNameToIndexMap { if (!_columnNameToIndexMap) { int columnCount = sqlite3_column_count([_statement statement]); _columnNameToIndexMap = [[NSMutableDictionary alloc] initWithCapacity:(NSUInteger)columnCount]; int columnIdx = 0; for (columnIdx = 0; columnIdx < columnCount; columnIdx++) { [_columnNameToIndexMap setObject:[NSNumber numberWithInt:columnIdx] forKey:[[NSString stringWithUTF8String:sqlite3_column_name([_statement statement], columnIdx)] lowercaseString]]; } } return _columnNameToIndexMap; } - (void)kvcMagic:(id)object { int columnCount = sqlite3_column_count([_statement statement]); int columnIdx = 0; for (columnIdx = 0; columnIdx < columnCount; columnIdx++) { const char *c = (const char *)sqlite3_column_text([_statement statement], columnIdx); // check for a null row if (c) { NSString *s = [NSString stringWithUTF8String:c]; [object setValue:s forKey:[NSString stringWithUTF8String:sqlite3_column_name([_statement statement], columnIdx)]]; } } } #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-implementations" - (NSDictionary *)resultDict { NSUInteger num_cols = (NSUInteger)sqlite3_data_count([_statement statement]); if (num_cols > 0) { NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:num_cols]; NSEnumerator *columnNames = [[self columnNameToIndexMap] keyEnumerator]; NSString *columnName = nil; while ((columnName = [columnNames nextObject])) { id objectValue = [self objectForColumnName:columnName]; [dict setObject:objectValue forKey:columnName]; } return FMDBReturnAutoreleased([dict copy]); } else { NSLog(@"Warning: There seem to be no columns in this set."); } return nil; } #pragma clang diagnostic pop - (NSDictionary*)resultDictionary { NSUInteger num_cols = (NSUInteger)sqlite3_data_count([_statement statement]); if (num_cols > 0) { NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:num_cols]; int columnCount = sqlite3_column_count([_statement statement]); int columnIdx = 0; for (columnIdx = 0; columnIdx < columnCount; columnIdx++) { NSString *columnName = [NSString stringWithUTF8String:sqlite3_column_name([_statement statement], columnIdx)]; id objectValue = [self objectForColumnIndex:columnIdx]; [dict setObject:objectValue forKey:columnName]; } return dict; } else { NSLog(@"Warning: There seem to be no columns in this set."); } return nil; } - (BOOL)next { return [self nextWithError:nil]; } - (BOOL)nextWithError:(NSError * _Nullable __autoreleasing *)outErr { int rc = [self internalStepWithError:outErr]; return rc == SQLITE_ROW; } - (BOOL)step { return [self stepWithError:nil]; } - (BOOL)stepWithError:(NSError * _Nullable __autoreleasing *)outErr { int rc = [self internalStepWithError:outErr]; return rc == SQLITE_DONE; } - (int)internalStepWithError:(NSError * _Nullable __autoreleasing *)outErr { int rc = sqlite3_step([_statement statement]); if (SQLITE_BUSY == rc || SQLITE_LOCKED == rc) { NSLog(@"%s:%d Database busy (%@)", __FUNCTION__, __LINE__, [_parentDB databasePath]); NSLog(@"Database busy"); if (outErr) { *outErr = [_parentDB lastError]; } } else if (SQLITE_DONE == rc || SQLITE_ROW == rc) { // all is well, let's return. } else if (SQLITE_ERROR == rc) { NSLog(@"Error calling sqlite3_step (%d: %s) rs", rc, sqlite3_errmsg([_parentDB sqliteHandle])); if (outErr) { *outErr = [_parentDB lastError]; } } else if (SQLITE_MISUSE == rc) { // uh oh. NSLog(@"Error calling sqlite3_step (%d: %s) rs", rc, sqlite3_errmsg([_parentDB sqliteHandle])); if (outErr) { if (_parentDB) { *outErr = [_parentDB lastError]; } else { // If 'next' or 'nextWithError' is called after the result set is closed, // we need to return the appropriate error. NSDictionary* errorMessage = [NSDictionary dictionaryWithObject:@"parentDB does not exist" forKey:NSLocalizedDescriptionKey]; *outErr = [NSError errorWithDomain:@"FMDatabase" code:SQLITE_MISUSE userInfo:errorMessage]; } } } else { // wtf? NSLog(@"Unknown error calling sqlite3_step (%d: %s) rs", rc, sqlite3_errmsg([_parentDB sqliteHandle])); if (outErr) { *outErr = [_parentDB lastError]; } } if (rc != SQLITE_ROW && _shouldAutoClose) { [self close]; } return rc; } - (BOOL)hasAnotherRow { return sqlite3_errcode([_parentDB sqliteHandle]) == SQLITE_ROW; } - (int)columnIndexForName:(NSString*)columnName { columnName = [columnName lowercaseString]; NSNumber *n = [[self columnNameToIndexMap] objectForKey:columnName]; if (n != nil) { return [n intValue]; } NSLog(@"Warning: I could not find the column named '%@'.", columnName); return -1; } - (int)intForColumn:(NSString*)columnName { return [self intForColumnIndex:[self columnIndexForName:columnName]]; } - (int)intForColumnIndex:(int)columnIdx { return sqlite3_column_int([_statement statement], columnIdx); } - (long)longForColumn:(NSString*)columnName { return [self longForColumnIndex:[self columnIndexForName:columnName]]; } - (long)longForColumnIndex:(int)columnIdx { return (long)sqlite3_column_int64([_statement statement], columnIdx); } - (long long int)longLongIntForColumn:(NSString*)columnName { return [self longLongIntForColumnIndex:[self columnIndexForName:columnName]]; } - (long long int)longLongIntForColumnIndex:(int)columnIdx { return sqlite3_column_int64([_statement statement], columnIdx); } - (unsigned long long int)unsignedLongLongIntForColumn:(NSString*)columnName { return [self unsignedLongLongIntForColumnIndex:[self columnIndexForName:columnName]]; } - (unsigned long long int)unsignedLongLongIntForColumnIndex:(int)columnIdx { return (unsigned long long int)[self longLongIntForColumnIndex:columnIdx]; } - (BOOL)boolForColumn:(NSString*)columnName { return [self boolForColumnIndex:[self columnIndexForName:columnName]]; } - (BOOL)boolForColumnIndex:(int)columnIdx { return ([self intForColumnIndex:columnIdx] != 0); } - (double)doubleForColumn:(NSString*)columnName { return [self doubleForColumnIndex:[self columnIndexForName:columnName]]; } - (double)doubleForColumnIndex:(int)columnIdx { return sqlite3_column_double([_statement statement], columnIdx); } - (NSString *)stringForColumnIndex:(int)columnIdx { if (sqlite3_column_type([_statement statement], columnIdx) == SQLITE_NULL || (columnIdx < 0) || columnIdx >= sqlite3_column_count([_statement statement])) { return nil; } const char *c = (const char *)sqlite3_column_text([_statement statement], columnIdx); if (!c) { // null row. return nil; } return [NSString stringWithUTF8String:c]; } - (NSString*)stringForColumn:(NSString*)columnName { return [self stringForColumnIndex:[self columnIndexForName:columnName]]; } - (NSDate*)dateForColumn:(NSString*)columnName { return [self dateForColumnIndex:[self columnIndexForName:columnName]]; } - (NSDate*)dateForColumnIndex:(int)columnIdx { if (sqlite3_column_type([_statement statement], columnIdx) == SQLITE_NULL || (columnIdx < 0) || columnIdx >= sqlite3_column_count([_statement statement])) { return nil; } return [_parentDB hasDateFormatter] ? [_parentDB dateFromString:[self stringForColumnIndex:columnIdx]] : [NSDate dateWithTimeIntervalSince1970:[self doubleForColumnIndex:columnIdx]]; } - (NSData*)dataForColumn:(NSString*)columnName { return [self dataForColumnIndex:[self columnIndexForName:columnName]]; } - (NSData*)dataForColumnIndex:(int)columnIdx { if (sqlite3_column_type([_statement statement], columnIdx) == SQLITE_NULL || (columnIdx < 0) || columnIdx >= sqlite3_column_count([_statement statement])) { return nil; } const char *dataBuffer = sqlite3_column_blob([_statement statement], columnIdx); int dataSize = sqlite3_column_bytes([_statement statement], columnIdx); if (dataBuffer == NULL) { return nil; } return [NSData dataWithBytes:(const void *)dataBuffer length:(NSUInteger)dataSize]; } - (NSData*)dataNoCopyForColumn:(NSString*)columnName { return [self dataNoCopyForColumnIndex:[self columnIndexForName:columnName]]; } - (NSData*)dataNoCopyForColumnIndex:(int)columnIdx { if (sqlite3_column_type([_statement statement], columnIdx) == SQLITE_NULL || (columnIdx < 0) || columnIdx >= sqlite3_column_count([_statement statement])) { return nil; } const char *dataBuffer = sqlite3_column_blob([_statement statement], columnIdx); int dataSize = sqlite3_column_bytes([_statement statement], columnIdx); NSData *data = [NSData dataWithBytesNoCopy:(void *)dataBuffer length:(NSUInteger)dataSize freeWhenDone:NO]; return data; } - (BOOL)columnIndexIsNull:(int)columnIdx { return sqlite3_column_type([_statement statement], columnIdx) == SQLITE_NULL; } - (BOOL)columnIsNull:(NSString*)columnName { return [self columnIndexIsNull:[self columnIndexForName:columnName]]; } - (const unsigned char *)UTF8StringForColumnIndex:(int)columnIdx { if (sqlite3_column_type([_statement statement], columnIdx) == SQLITE_NULL || (columnIdx < 0) || columnIdx >= sqlite3_column_count([_statement statement])) { return nil; } return sqlite3_column_text([_statement statement], columnIdx); } - (const unsigned char *)UTF8StringForColumn:(NSString*)columnName { return [self UTF8StringForColumnIndex:[self columnIndexForName:columnName]]; } - (const unsigned char *)UTF8StringForColumnName:(NSString*)columnName { return [self UTF8StringForColumn:columnName]; } - (id)objectForColumnIndex:(int)columnIdx { if (columnIdx < 0 || columnIdx >= sqlite3_column_count([_statement statement])) { return nil; } int columnType = sqlite3_column_type([_statement statement], columnIdx); id returnValue = nil; if (columnType == SQLITE_INTEGER) { returnValue = [NSNumber numberWithLongLong:[self longLongIntForColumnIndex:columnIdx]]; } else if (columnType == SQLITE_FLOAT) { returnValue = [NSNumber numberWithDouble:[self doubleForColumnIndex:columnIdx]]; } else if (columnType == SQLITE_BLOB) { returnValue = [self dataForColumnIndex:columnIdx]; } else { //default to a string for everything else returnValue = [self stringForColumnIndex:columnIdx]; } if (returnValue == nil) { returnValue = [NSNull null]; } return returnValue; } - (id)objectForColumnName:(NSString*)columnName { return [self objectForColumn:columnName]; } - (id)objectForColumn:(NSString*)columnName { return [self objectForColumnIndex:[self columnIndexForName:columnName]]; } - (SqliteValueType)typeForColumn:(NSString*)columnName { return sqlite3_column_type([_statement statement], [self columnIndexForName:columnName]); } - (SqliteValueType)typeForColumnIndex:(int)columnIdx { return sqlite3_column_type([_statement statement], columnIdx); } // returns autoreleased NSString containing the name of the column in the result set - (NSString*)columnNameForIndex:(int)columnIdx { return [NSString stringWithUTF8String: sqlite3_column_name([_statement statement], columnIdx)]; } - (id)objectAtIndexedSubscript:(int)columnIdx { return [self objectForColumnIndex:columnIdx]; } - (id)objectForKeyedSubscript:(NSString *)columnName { return [self objectForColumn:columnName]; } // MARK: Bind - (BOOL)bindWithArray:(NSArray*)array orDictionary:(NSDictionary *)dictionary orVAList:(va_list)args { [_statement reset]; return [_parentDB bindStatement:_statement.statement WithArgumentsInArray:array orDictionary:dictionary orVAList:args]; } - (BOOL)bindWithArray:(NSArray*)array { return [self bindWithArray:array orDictionary:nil orVAList:nil]; } - (BOOL)bindWithDictionary:(NSDictionary *)dictionary { return [self bindWithArray:nil orDictionary:dictionary orVAList:nil]; } @end ================================================ FILE: src/fmdb/Info.plist ================================================ CFBundleDevelopmentRegion en CFBundleExecutable $(EXECUTABLE_NAME) CFBundleIdentifier $(PRODUCT_BUNDLE_IDENTIFIER) CFBundleInfoDictionaryVersion 6.0 CFBundleName $(PRODUCT_NAME) CFBundlePackageType FMWK CFBundleShortVersionString $(MARKETING_VERSION) CFBundleSignature ???? CFBundleVersion $(CURRENT_PROJECT_VERSION) NSPrincipalClass ================================================ FILE: src/fmdb/info-xrOS.plist ================================================ CFBundleDevelopmentRegion en CFBundleExecutable $(EXECUTABLE_NAME) CFBundleIdentifier $(PRODUCT_BUNDLE_IDENTIFIER) CFBundleInfoDictionaryVersion 6.0 CFBundleName $(PRODUCT_NAME) CFBundlePackageType FMWK CFBundleShortVersionString $(MARKETING_VERSION) CFBundleSignature ???? CFBundleVersion $(CURRENT_PROJECT_VERSION) NSPrincipalClass ================================================ FILE: src/sample/fmdb_Prefix.pch ================================================ // // Prefix header for all source files of the 'fmdb' target in the 'fmdb' project. // #ifdef __OBJC__ #import #endif ================================================ FILE: src/sample/main.m ================================================ /* main.m * * Sample code to illustrate some of the basic FMDB classes and run them through their paces for illustrative purposes. */ #import #import "FMDB.h" #import #define FMDBQuickCheck(SomeBool) { if (!(SomeBool)) { NSLog(@"Failure on line %d", __LINE__); abort(); } } void testPool(NSString *dbPath); void testDateFormat(void); void FMDBReportABugFunction(void); void testStatementCaching(void); int main (int argc, const char * argv[]) { @autoreleasepool { FMDBReportABugFunction(); NSString *dbPath = @"/tmp/tmp.db"; // delete the old db. NSFileManager *fileManager = [NSFileManager defaultManager]; [fileManager removeItemAtPath:dbPath error:nil]; FMDatabase *db = [FMDatabase databaseWithPath:dbPath]; NSLog(@"Is SQLite compiled with it's thread safe options turned on? %@!", [FMDatabase isSQLiteThreadSafe] ? @"Yes" : @"No"); { // ------------------------------------------------------------------------------- // Un-opened database check. FMDBQuickCheck([db executeQuery:@"select * from table"] == nil); NSLog(@"%d: %@", [db lastErrorCode], [db lastErrorMessage]); } if (![db open]) { NSLog(@"Could not open db."); return 0; } // kind of experimentalish. [db setShouldCacheStatements:YES]; // create a bad statement, just to test the error code. [db executeUpdate:@"blah blah blah"]; FMDBQuickCheck([db hadError]); if ([db hadError]) { NSLog(@"Err %d: %@", [db lastErrorCode], [db lastErrorMessage]); } NSError *err = 0x00; FMDBQuickCheck(![db executeUpdate:@"blah blah blah" withErrorAndBindings:&err]); FMDBQuickCheck(err != nil); FMDBQuickCheck([err code] == SQLITE_ERROR); NSLog(@"err: '%@'", err); // empty strings should still return a value. FMDBQuickCheck(([db boolForQuery:@"SELECT ? not null", @""])); // same with empty bits o' mutable data FMDBQuickCheck(([db boolForQuery:@"SELECT ? not null", [NSMutableData data]])); // same with empty bits o' data FMDBQuickCheck(([db boolForQuery:@"SELECT ? not null", [NSData data]])); // how do we do pragmas? Like so: FMResultSet *ps = [db executeQuery:@"pragma journal_mode=delete"]; FMDBQuickCheck(![db hadError]); FMDBQuickCheck(ps); FMDBQuickCheck([ps next]); [ps close]; // oh, but some pragmas require updates? [db executeUpdate:@"pragma page_size=2048"]; FMDBQuickCheck(![db hadError]); // what about a vacuum? [db executeUpdate:@"vacuum"]; FMDBQuickCheck(![db hadError]); // but of course, I don't bother checking the error codes below. // Bad programmer, no cookie. [db executeUpdate:@"create table test (a text, b text, c integer, d double, e double)"]; [db beginTransaction]; int i = 0; while (i++ < 20) { [db executeUpdate:@"insert into test (a, b, c, d, e) values (?, ?, ?, ?, ?)" , @"hi'", // look! I put in a ', and I'm not escaping it! [NSString stringWithFormat:@"number %d", i], [NSNumber numberWithInt:i], [NSDate date], [NSNumber numberWithFloat:2.2f]]; } [db commit]; // do it again, just because [db beginTransaction]; i = 0; while (i++ < 20) { [db executeUpdate:@"insert into test (a, b, c, d, e) values (?, ?, ?, ?, ?)" , @"hi again'", // look! I put in a ', and I'm not escaping it! [NSString stringWithFormat:@"number %d", i], [NSNumber numberWithInt:i], [NSDate date], [NSNumber numberWithFloat:2.2f]]; } [db commit]; FMResultSet *rs = [db executeQuery:@"select rowid,* from test where a = ?", @"hi'"]; while ([rs next]) { // just print out what we've got in a number of formats. NSLog(@"%d %@ %@ %@ %@ %f %f", [rs intForColumn:@"c"], [rs stringForColumn:@"b"], [rs stringForColumn:@"a"], [rs stringForColumn:@"rowid"], [rs dateForColumn:@"d"], [rs doubleForColumn:@"d"], [rs doubleForColumn:@"e"]); if (!([[rs columnNameForIndex:0] isEqualToString:@"rowid"] && [[rs columnNameForIndex:1] isEqualToString:@"a"]) ) { NSLog(@"WHOA THERE BUDDY, columnNameForIndex ISN'T WORKING!"); return 7; } } // close the result set. // it'll also close when it's dealloc'd, but we're closing the database before // the autorelease pool closes, so sqlite will complain about it. [rs close]; FMDBQuickCheck(![db hasOpenResultSets]); rs = [db executeQuery:@"select rowid, a, b, c from test"]; while ([rs next]) { FMDBQuickCheck([rs[0] isEqual:rs[@"rowid"]]); FMDBQuickCheck([rs[1] isEqual:rs[@"a"]]); FMDBQuickCheck([rs[2] isEqual:rs[@"b"]]); FMDBQuickCheck([rs[3] isEqual:rs[@"c"]]); } [rs close]; [db executeUpdate:@"create table ull (a integer)"]; [db executeUpdate:@"insert into ull (a) values (?)" , [NSNumber numberWithUnsignedLongLong:ULLONG_MAX]]; rs = [db executeQuery:@"select a from ull"]; while ([rs next]) { unsigned long long a = [rs unsignedLongLongIntForColumnIndex:0]; unsigned long long b = [rs unsignedLongLongIntForColumn:@"a"]; FMDBQuickCheck(a == ULLONG_MAX); FMDBQuickCheck(b == ULLONG_MAX); } // check case sensitive result dictionary. [db executeUpdate:@"create table cs (aRowName integer, bRowName text)"]; FMDBQuickCheck(![db hadError]); [db executeUpdate:@"insert into cs (aRowName, bRowName) values (?, ?)" , [NSNumber numberWithBool:1], @"hello"]; FMDBQuickCheck(![db hadError]); rs = [db executeQuery:@"select * from cs"]; while ([rs next]) { NSDictionary *d = [rs resultDictionary]; FMDBQuickCheck([d objectForKey:@"aRowName"]); FMDBQuickCheck(![d objectForKey:@"arowname"]); FMDBQuickCheck([d objectForKey:@"bRowName"]); FMDBQuickCheck(![d objectForKey:@"browname"]); } // check funky table names + getTableSchema [db executeUpdate:@"create table '234 fds' (foo text)"]; FMDBQuickCheck(![db hadError]); rs = [db getTableSchema:@"234 fds"]; FMDBQuickCheck([rs next]); [rs close]; #if SQLITE_VERSION_NUMBER >= 3007017 { uint32_t appID = NSHFSTypeCodeFromFileType(NSFileTypeForHFSTypeCode('fmdb')); [db setApplicationID:appID]; uint32_t rAppID = [db applicationID]; NSLog(@"rAppID: %d", rAppID); FMDBQuickCheck(rAppID == appID); [db setApplicationIDString:@"acrn"]; NSString *s = [db applicationIDString]; NSLog(@"s: '%@'", s); FMDBQuickCheck([s isEqualToString:@"acrn"]); } #endif { // ------------------------------------------------------------------------------- // Named parameters count test. FMDBQuickCheck([db executeUpdate:@"create table namedparamcounttest (a text, b text, c integer, d double)"]); NSMutableDictionary *dictionaryArgs = [NSMutableDictionary dictionary]; [dictionaryArgs setObject:@"Text1" forKey:@"a"]; [dictionaryArgs setObject:@"Text2" forKey:@"b"]; [dictionaryArgs setObject:[NSNumber numberWithInt:1] forKey:@"c"]; [dictionaryArgs setObject:[NSNumber numberWithDouble:2.0] forKey:@"d"]; FMDBQuickCheck([db executeUpdate:@"insert into namedparamcounttest values (:a, :b, :c, :d)" withParameterDictionary:dictionaryArgs]); rs = [db executeQuery:@"select * from namedparamcounttest"]; FMDBQuickCheck((rs != nil)); [rs next]; FMDBQuickCheck([[rs stringForColumn:@"a"] isEqualToString:@"Text1"]); FMDBQuickCheck([[rs stringForColumn:@"b"] isEqualToString:@"Text2"]); FMDBQuickCheck([rs intForColumn:@"c"] == 1); FMDBQuickCheck([rs doubleForColumn:@"d"] == 2.0); [rs close]; // note that at this point, dictionaryArgs has way more values than we need, but the query should still work since // a is in there, and that's all we need. rs = [db executeQuery:@"select * from namedparamcounttest where a = :a" withParameterDictionary:dictionaryArgs]; FMDBQuickCheck((rs != nil)); FMDBQuickCheck([rs next]); [rs close]; // ***** Please note the following codes ***** dictionaryArgs = [NSMutableDictionary dictionary]; [dictionaryArgs setObject:@"NewText1" forKey:@"a"]; [dictionaryArgs setObject:@"NewText2" forKey:@"b"]; [dictionaryArgs setObject:@"OneMoreText" forKey:@"OneMore"]; BOOL rc = [db executeUpdate:@"update namedparamcounttest set a = :a, b = :b where b = 'Text2'" withParameterDictionary:dictionaryArgs]; FMDBQuickCheck(rc); if (!rc) { NSLog(@"ERROR: %d - %@", db.lastErrorCode, db.lastErrorMessage); } } // ---------------------------------------------------------------------------------------- // blob support. [db executeUpdate:@"create table blobTable (a text, b blob)"]; // let's read in an image from safari's app bundle. NSData *safariCompass = [NSData dataWithContentsOfFile:@"/Applications/Safari.app/Contents/Resources/AppIcon.icns"]; assert(safariCompass); if (safariCompass) { [db executeUpdate:@"insert into blobTable (a, b) values (?,?)", @"safari's compass", safariCompass]; rs = [db executeQuery:@"select b from blobTable where a = ?", @"safari's compass"]; if ([rs next]) { safariCompass = [rs dataForColumn:@"b"]; [safariCompass writeToFile:@"/tmp/compass.icns" atomically:NO]; // let's look at our fancy image that we just wrote out.. system("/usr/bin/open /tmp/compass.icns"); // ye shall read the header for this function, or suffer the consequences. safariCompass = [rs dataNoCopyForColumn:@"b"]; [safariCompass writeToFile:@"/tmp/compass_data_no_copy.icns" atomically:NO]; system("/usr/bin/open /tmp/compass_data_no_copy.icns"); } else { NSLog(@"Could not select image."); } [rs close]; } else { NSLog(@"Can't find compass image.."); } // test out the convenience methods in +Additions [db executeUpdate:@"create table t1 (a integer)"]; [db executeUpdate:@"insert into t1 values (?)", [NSNumber numberWithInt:5]]; NSLog(@"Count of changes (should be 1): %d", [db changes]); FMDBQuickCheck([db changes] == 1); int ia = [db intForQuery:@"select a from t1 where a = ?", [NSNumber numberWithInt:5]]; if (ia != 5) { NSLog(@"intForQuery didn't work (a != 5)"); } // test the busy rety timeout schtuff. [db setMaxBusyRetryTimeInterval:5]; FMDatabase *newDb = [FMDatabase databaseWithPath:dbPath]; [newDb open]; rs = [newDb executeQuery:@"select rowid,* from test where a = ?", @"hi'"]; [rs next]; // just grab one... which will keep the db locked. NSLog(@"Testing the busy timeout"); NSTimeInterval startTime = [NSDate timeIntervalSinceReferenceDate]; BOOL success = [db executeUpdate:@"insert into t1 values (5)"]; if (success) { NSLog(@"Whoa- the database didn't stay locked!"); return 7; } else { NSLog(@"Hurray, our timeout worked"); } [rs close]; [newDb close]; success = [db executeUpdate:@"insert into t1 values (5)"]; if (!success) { NSLog(@"Whoa- the database shouldn't be locked!"); return 8; } else { NSLog(@"Hurray, we can insert again!"); } NSTimeInterval end = [NSDate timeIntervalSinceReferenceDate] - startTime; NSLog(@"Took %f seconds for the timeout.", end); // test some nullness. [db executeUpdate:@"create table t2 (a integer, b integer)"]; if (![db executeUpdate:@"insert into t2 values (?, ?)", nil, [NSNumber numberWithInt:5]]) { NSLog(@"UH OH, can't insert a nil value for some reason..."); } rs = [db executeQuery:@"select * from t2"]; while ([rs next]) { NSString *aa = [rs stringForColumnIndex:0]; NSString *b = [rs stringForColumnIndex:1]; if (aa != nil) { NSLog(@"%s:%d", __FUNCTION__, __LINE__); NSLog(@"OH OH, PROBLEMO!"); return 10; } else { NSLog(@"YAY, NULL VALUES"); } if (![b isEqualToString:@"5"]) { NSLog(@"%s:%d", __FUNCTION__, __LINE__); NSLog(@"OH OH, PROBLEMO!"); return 10; } } // test some inner loop funkness. [db executeUpdate:@"create table t3 (a somevalue)"]; // do it again, just because [db beginTransaction]; i = 0; while (i++ < 20) { [db executeUpdate:@"insert into t3 (a) values (?)" , [NSNumber numberWithInt:i]]; } [db commit]; rs = [db executeQuery:@"select * from t3"]; while ([rs next]) { int foo = [rs intForColumnIndex:0]; int newVal = foo + 100; [db executeUpdate:@"update t3 set a = ? where a = ?" , [NSNumber numberWithInt:newVal], [NSNumber numberWithInt:foo]]; FMResultSet *rs2 = [db executeQuery:@"select a from t3 where a = ?", [NSNumber numberWithInt:newVal]]; [rs2 next]; if ([rs2 intForColumnIndex:0] != newVal) { NSLog(@"Oh crap, our update didn't work out!"); return 9; } [rs2 close]; } // NSNull tests [db executeUpdate:@"create table nulltest (a text, b text)"]; [db executeUpdate:@"insert into nulltest (a, b) values (?, ?)" , [NSNull null], @"a"]; [db executeUpdate:@"insert into nulltest (a, b) values (?, ?)" , nil, @"b"]; rs = [db executeQuery:@"select * from nulltest"]; while ([rs next]) { NSString *a = [rs stringForColumnIndex:0]; NSString *b = [rs stringForColumnIndex:1]; if (!b) { NSLog(@"Oh crap, the nil / null inserts didn't work!"); return 10; } if (a) { NSLog(@"Oh crap, the nil / null inserts didn't work (son of error message)!"); return 11; } else { NSLog(@"HURRAH FOR NSNULL (and nil)!"); } } FMDBQuickCheck([db columnExists:@"a" inTableWithName:@"nulltest"]); FMDBQuickCheck([db columnExists:@"b" inTableWithName:@"nulltest"]); FMDBQuickCheck(![db columnExists:@"c" inTableWithName:@"nulltest"]); // null dates NSDate *date = [NSDate date]; [db executeUpdate:@"create table datetest (a double, b double, c double)"]; [db executeUpdate:@"insert into datetest (a, b, c) values (?, ?, 0)" , [NSNull null], date]; rs = [db executeQuery:@"select * from datetest"]; while ([rs next]) { NSDate *a = [rs dateForColumnIndex:0]; NSDate *b = [rs dateForColumnIndex:1]; NSDate *c = [rs dateForColumnIndex:2]; if (a) { NSLog(@"Oh crap, the null date insert didn't work!"); return 12; } if (!c) { NSLog(@"Oh crap, the 0 date insert didn't work!"); return 12; } NSTimeInterval dti = fabs([b timeIntervalSinceDate:date]); if (floor(dti) > 0.0) { NSLog(@"Date matches didn't really happen... time difference of %f", dti); return 13; } dti = fabs([c timeIntervalSinceDate:[NSDate dateWithTimeIntervalSince1970:0]]); if (floor(dti) > 0.0) { NSLog(@"Date matches didn't really happen... time difference of %f", dti); return 13; } } NSDate *foo = [db dateForQuery:@"select b from datetest where c = 0"]; assert(foo); NSTimeInterval dti = fabs([foo timeIntervalSinceDate:date]); if (floor(dti) > 0.0) { NSLog(@"Date matches didn't really happen... time difference of %f", dti); return 14; } [db executeUpdate:@"create table nulltest2 (s text, d data, i integer, f double, b integer)"]; // grab the data for this again, since we overwrote it with some memory that has since disapeared. safariCompass = [NSData dataWithContentsOfFile:@"/Applications/Safari.app/Contents/Resources/AppIcon.icns"]; assert(safariCompass); [db executeUpdate:@"insert into nulltest2 (s, d, i, f, b) values (?, ?, ?, ?, ?)" , @"Hi", safariCompass, [NSNumber numberWithInt:12], [NSNumber numberWithFloat:4.4f], [NSNumber numberWithBool:YES]]; [db executeUpdate:@"insert into nulltest2 (s, d, i, f, b) values (?, ?, ?, ?, ?)" , nil, nil, nil, nil, [NSNull null]]; rs = [db executeQuery:@"select * from nulltest2"]; while ([rs next]) { i = [rs intForColumnIndex:2]; if (i == 12) { // it's the first row we inserted. FMDBQuickCheck(![rs columnIndexIsNull:0]); FMDBQuickCheck(![rs columnIndexIsNull:1]); FMDBQuickCheck(![rs columnIndexIsNull:2]); FMDBQuickCheck(![rs columnIndexIsNull:3]); FMDBQuickCheck(![rs columnIndexIsNull:4]); FMDBQuickCheck( [rs columnIndexIsNull:5]); FMDBQuickCheck([[rs dataForColumn:@"d"] length] == [safariCompass length]); FMDBQuickCheck(![rs dataForColumn:@"notthere"]); FMDBQuickCheck(![rs stringForColumnIndex:-2]); FMDBQuickCheck([rs boolForColumnIndex:4]); FMDBQuickCheck([rs boolForColumn:@"b"]); FMDBQuickCheck(fabs(4.4 - [rs doubleForColumn:@"f"]) < 0.0000001); FMDBQuickCheck(12 == [rs intForColumn:@"i"]); FMDBQuickCheck(12 == [rs intForColumnIndex:2]); FMDBQuickCheck(0 == [rs intForColumnIndex:12]); // there is no 12 FMDBQuickCheck(0 == [rs intForColumn:@"notthere"]); FMDBQuickCheck(12 == [rs longForColumn:@"i"]); FMDBQuickCheck(12 == [rs longLongIntForColumn:@"i"]); } else { // let's test various null things. FMDBQuickCheck([rs columnIndexIsNull:0]); FMDBQuickCheck([rs columnIndexIsNull:1]); FMDBQuickCheck([rs columnIndexIsNull:2]); FMDBQuickCheck([rs columnIndexIsNull:3]); FMDBQuickCheck([rs columnIndexIsNull:4]); FMDBQuickCheck([rs columnIndexIsNull:5]); FMDBQuickCheck(![rs dataForColumn:@"d"]); } } { [db executeUpdate:@"create table utest (a text)"]; [db executeUpdate:@"insert into utest values (?)", @"/übertest"]; rs = [db executeQuery:@"select * from utest where a = ?", @"/übertest"]; FMDBQuickCheck([rs next]); [rs close]; } { [db executeUpdate:@"create table testOneHundredTwelvePointTwo (a text, b integer)"]; [db executeUpdate:@"insert into testOneHundredTwelvePointTwo values (?, ?)" withArgumentsInArray:[NSArray arrayWithObjects:@"one", [NSNumber numberWithInteger:2], nil]]; [db executeUpdate:@"insert into testOneHundredTwelvePointTwo values (?, ?)" withArgumentsInArray:[NSArray arrayWithObjects:@"one", [NSNumber numberWithInteger:3], nil]]; rs = [db executeQuery:@"select * from testOneHundredTwelvePointTwo where b > ?" withArgumentsInArray:[NSArray arrayWithObject:[NSNumber numberWithInteger:1]]]; FMDBQuickCheck([rs next]); FMDBQuickCheck([rs hasAnotherRow]); FMDBQuickCheck(![db hadError]); FMDBQuickCheck([[rs stringForColumnIndex:0] isEqualToString:@"one"]); FMDBQuickCheck([rs intForColumnIndex:1] == 2); FMDBQuickCheck([rs next]); FMDBQuickCheck([rs intForColumnIndex:1] == 3); FMDBQuickCheck(![rs next]); FMDBQuickCheck(![rs hasAnotherRow]); } { FMDBQuickCheck([db executeUpdate:@"create table t4 (a text, b text)"]); FMDBQuickCheck(([db executeUpdate:@"insert into t4 (a, b) values (?, ?)", @"one", @"two"])); rs = [db executeQuery:@"select t4.a as 't4.a', t4.b from t4;"]; FMDBQuickCheck((rs != nil)); [rs next]; FMDBQuickCheck([[rs stringForColumn:@"t4.a"] isEqualToString:@"one"]); FMDBQuickCheck([[rs stringForColumn:@"b"] isEqualToString:@"two"]); FMDBQuickCheck(strcmp((const char*)[rs UTF8StringForColumn:@"b"], "two") == 0); [rs close]; // let's try these again, with the withArgumentsInArray: variation FMDBQuickCheck([db executeUpdate:@"drop table t4;" withArgumentsInArray:[NSArray array]]); FMDBQuickCheck([db executeUpdate:@"create table t4 (a text, b text)" withArgumentsInArray:[NSArray array]]); FMDBQuickCheck(([db executeUpdate:@"insert into t4 (a, b) values (?, ?)" withArgumentsInArray:[NSArray arrayWithObjects:@"one", @"two", nil]])); rs = [db executeQuery:@"select t4.a as 't4.a', t4.b from t4;" withArgumentsInArray:[NSArray array]]; FMDBQuickCheck((rs != nil)); [rs next]; FMDBQuickCheck([[rs stringForColumn:@"t4.a"] isEqualToString:@"one"]); FMDBQuickCheck([[rs stringForColumn:@"b"] isEqualToString:@"two"]); FMDBQuickCheck(strcmp((const char*)[rs UTF8StringForColumn:@"b"], "two") == 0); [rs close]; } { FMDBQuickCheck([db tableExists:@"t4"]); FMDBQuickCheck(![db tableExists:@"thisdoesntexist"]); rs = [db getSchema]; while ([rs next]) { FMDBQuickCheck([[rs stringForColumn:@"type"] isEqualToString:@"table"]); } } { FMDBQuickCheck([db executeUpdate:@"create table t5 (a text, b int, c blob, d text, e text)"]); FMDBQuickCheck(([db executeUpdateWithFormat:@"insert into t5 values (%s, %d, %@, %c, %lld)", "text", 42, @"BLOB", 'd', 12345678901234ll])); rs = [db executeQueryWithFormat:@"select * from t5 where a = %s and a = %@ and b = %d", "text", @"text", 42]; FMDBQuickCheck((rs != nil)); [rs next]; FMDBQuickCheck([[rs stringForColumn:@"a"] isEqualToString:@"text"]); FMDBQuickCheck(([rs intForColumn:@"b"] == 42)); FMDBQuickCheck([[rs stringForColumn:@"c"] isEqualToString:@"BLOB"]); FMDBQuickCheck([[rs stringForColumn:@"d"] isEqualToString:@"d"]); FMDBQuickCheck(([rs longLongIntForColumn:@"e"] == 12345678901234)); [rs close]; } { FMDBQuickCheck([db executeUpdate:@"create table t55 (a text, b int, c float)"]); short testShort = -4; float testFloat = 5.5; FMDBQuickCheck(([db executeUpdateWithFormat:@"insert into t55 values (%c, %hi, %g)", 'a', testShort, testFloat])); unsigned short testUShort = 6; FMDBQuickCheck(([db executeUpdateWithFormat:@"insert into t55 values (%c, %hu, %g)", 'a', testUShort, testFloat])); rs = [db executeQueryWithFormat:@"select * from t55 where a = %s order by 2", "a"]; FMDBQuickCheck((rs != nil)); [rs next]; FMDBQuickCheck([[rs stringForColumn:@"a"] isEqualToString:@"a"]); FMDBQuickCheck(([rs intForColumn:@"b"] == -4)); FMDBQuickCheck([[rs stringForColumn:@"c"] isEqualToString:@"5.5"]); [rs next]; FMDBQuickCheck([[rs stringForColumn:@"a"] isEqualToString:@"a"]); FMDBQuickCheck(([rs intForColumn:@"b"] == 6)); FMDBQuickCheck([[rs stringForColumn:@"c"] isEqualToString:@"5.5"]); [rs close]; } { FMDBQuickCheck([db executeUpdate:@"create table tatwhat (a text)"]); BOOL worked = [db executeUpdateWithFormat:@"insert into tatwhat values(%@)", nil]; FMDBQuickCheck(worked); rs = [db executeQueryWithFormat:@"select * from tatwhat"]; FMDBQuickCheck((rs != nil)); FMDBQuickCheck(([rs next])); FMDBQuickCheck([rs columnIndexIsNull:0]); FMDBQuickCheck((![rs next])); } { FMDBQuickCheck(([db executeUpdate:@"insert into t5 values (?, ?, ?, ?, ?)" withErrorAndBindings:&err, @"text", [NSNumber numberWithInt:42], @"BLOB", @"d", [NSNumber numberWithInt:0]])); } { rs = [db executeQuery:@"select * from t5 where a=?" withArgumentsInArray:@[]]; FMDBQuickCheck((![rs next])); } // test attach for the heck of it. { //FMDatabase *dbA = [FMDatabase databaseWithPath:dbPath]; [fileManager removeItemAtPath:@"/tmp/attachme.db" error:nil]; FMDatabase *dbB = [FMDatabase databaseWithPath:@"/tmp/attachme.db"]; FMDBQuickCheck([dbB open]); FMDBQuickCheck([dbB executeUpdate:@"create table attached (a text)"]); FMDBQuickCheck(([dbB executeUpdate:@"insert into attached values (?)", @"test"])); FMDBQuickCheck([dbB close]); [db executeUpdate:@"attach database '/tmp/attachme.db' as attack"]; rs = [db executeQuery:@"select * from attack.attached"]; FMDBQuickCheck([rs next]); [rs close]; } { // ------------------------------------------------------------------------------- // Named parameters. FMDBQuickCheck([db executeUpdate:@"create table namedparamtest (a text, b text, c integer, d double)"]); NSMutableDictionary *dictionaryArgs = [NSMutableDictionary dictionary]; [dictionaryArgs setObject:@"Text1" forKey:@"a"]; [dictionaryArgs setObject:@"Text2" forKey:@"b"]; [dictionaryArgs setObject:[NSNumber numberWithInt:1] forKey:@"c"]; [dictionaryArgs setObject:[NSNumber numberWithDouble:2.0] forKey:@"d"]; FMDBQuickCheck([db executeUpdate:@"insert into namedparamtest values (:a, :b, :c, :d)" withParameterDictionary:dictionaryArgs]); rs = [db executeQuery:@"select * from namedparamtest"]; FMDBQuickCheck((rs != nil)); [rs next]; FMDBQuickCheck([[rs stringForColumn:@"a"] isEqualToString:@"Text1"]); FMDBQuickCheck([[rs stringForColumn:@"b"] isEqualToString:@"Text2"]); FMDBQuickCheck([rs intForColumn:@"c"] == 1); FMDBQuickCheck([rs doubleForColumn:@"d"] == 2.0); [rs close]; dictionaryArgs = [NSMutableDictionary dictionary]; [dictionaryArgs setObject:@"Text2" forKey:@"blah"]; rs = [db executeQuery:@"select * from namedparamtest where b = :blah" withParameterDictionary:dictionaryArgs]; FMDBQuickCheck((rs != nil)); FMDBQuickCheck([rs next]); FMDBQuickCheck([[rs stringForColumn:@"b"] isEqualToString:@"Text2"]); [rs close]; } // just for fun. rs = [db executeQuery:@"pragma database_list"]; while ([rs next]) { NSString *file = [rs stringForColumn:@"file"]; NSLog(@"database_list: %@", file); } // print out some stats if we are using cached statements. if ([db shouldCacheStatements]) { NSEnumerator *e = [[db cachedStatements] objectEnumerator];; FMStatement *statement; while ((statement = [e nextObject])) { NSLog(@"%@", statement); } } [db setShouldCacheStatements:true]; [db executeUpdate:@"CREATE TABLE testCacheStatements(key INTEGER PRIMARY KEY, value INTEGER)"]; [db executeUpdate:@"INSERT INTO testCacheStatements (key, value) VALUES (1, 2)"]; [db executeUpdate:@"INSERT INTO testCacheStatements (key, value) VALUES (2, 4)"]; FMDBQuickCheck([[db executeQuery:@"SELECT * FROM testCacheStatements WHERE key=1"] next]); FMDBQuickCheck([[db executeQuery:@"SELECT * FROM testCacheStatements WHERE key=1"] next]); [db close]; testPool(dbPath); testDateFormat(); FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:dbPath]; FMDBQuickCheck(queue); { [queue inDatabase:^(FMDatabase *adb) { [adb executeUpdate:@"create table qfoo (foo text)"]; [adb executeUpdate:@"insert into qfoo values ('hi')"]; [adb executeUpdate:@"insert into qfoo values ('hello')"]; [adb executeUpdate:@"insert into qfoo values ('not')"]; int count = 0; FMResultSet *rsl = [adb executeQuery:@"select * from qfoo where foo like 'h%'"]; while ([rsl next]) { count++; } FMDBQuickCheck(count == 2); count = 0; rsl = [adb executeQuery:@"select * from qfoo where foo like ?", @"h%"]; while ([rsl next]) { count++; } FMDBQuickCheck(count == 2); }]; } FMDatabaseQueue *queue2 = [FMDatabaseQueue databaseQueueWithPath:dbPath flags:SQLITE_OPEN_READONLY]; FMDBQuickCheck(queue2); { [queue2 inDatabase:^(FMDatabase *db2) { FMResultSet *rs1 = [db2 executeQuery:@"SELECT * FROM test"]; FMDBQuickCheck(rs1 != nil); [rs1 close]; BOOL ok = [db2 executeUpdate:@"insert into easy values (?)", [NSNumber numberWithInt:3]]; FMDBQuickCheck(!ok); }]; [queue2 close]; [queue2 inDatabase:^(FMDatabase *db2) { FMResultSet *rs1 = [db2 executeQuery:@"SELECT * FROM test"]; FMDBQuickCheck(rs1 != nil); [rs1 close]; BOOL ok = [db2 executeUpdate:@"insert into easy values (?)", [NSNumber numberWithInt:3]]; FMDBQuickCheck(!ok); }]; } { // You should see pairs of numbers show up in stdout for this stuff: size_t ops = 16; dispatch_queue_t dqueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_apply(ops, dqueue, ^(size_t nby) { // just mix things up a bit for demonstration purposes. if (nby % 2 == 1) { [NSThread sleepForTimeInterval:.1]; [queue inTransaction:^(FMDatabase *adb, BOOL *rollback) { NSLog(@"Starting query %ld", nby); FMResultSet *rsl = [adb executeQuery:@"select * from qfoo where foo like 'h%'"]; while ([rsl next]) { ;// whatever. } NSLog(@"Ending query %ld", nby); }]; } if (nby % 3 == 1) { [NSThread sleepForTimeInterval:.1]; } [queue inTransaction:^(FMDatabase *adb, BOOL *rollback) { NSLog(@"Starting update %ld", nby); [adb executeUpdate:@"insert into qfoo values ('1')"]; [adb executeUpdate:@"insert into qfoo values ('2')"]; [adb executeUpdate:@"insert into qfoo values ('3')"]; NSLog(@"Ending update %ld", nby); }]; }); [queue close]; [queue inDatabase:^(FMDatabase *adb) { FMDBQuickCheck([adb executeUpdate:@"insert into qfoo values ('1')"]); }]; } { [queue inDatabase:^(FMDatabase *adb) { [adb executeUpdate:@"create table colNameTest (a, b, c, d)"]; FMDBQuickCheck([adb executeUpdate:@"insert into colNameTest values (1, 2, 3, 4)"]); FMResultSet *ars = [adb executeQuery:@"select * from colNameTest"]; NSDictionary *d = [ars columnNameToIndexMap]; FMDBQuickCheck([d count] == 4); FMDBQuickCheck([[d objectForKey:@"a"] intValue] == 0); FMDBQuickCheck([[d objectForKey:@"b"] intValue] == 1); FMDBQuickCheck([[d objectForKey:@"c"] intValue] == 2); FMDBQuickCheck([[d objectForKey:@"d"] intValue] == 3); [ars close]; }]; } { [queue inDatabase:^(FMDatabase *adb) { [adb executeUpdate:@"create table transtest (a integer)"]; FMDBQuickCheck([adb executeUpdate:@"insert into transtest values (1)"]); FMDBQuickCheck([adb executeUpdate:@"insert into transtest values (2)"]); int rowCount = 0; FMResultSet *ars = [adb executeQuery:@"select * from transtest"]; while ([ars next]) { rowCount++; } FMDBQuickCheck(rowCount == 2); }]; [queue inTransaction:^(FMDatabase *adb, BOOL *rollback) { FMDBQuickCheck([adb executeUpdate:@"insert into transtest values (3)"]); if (YES) { // uh oh!, something went wrong (not really, this is just a test *rollback = YES; return; } FMDBQuickCheck([adb executeUpdate:@"insert into transtest values (4)"]); }]; [queue inDatabase:^(FMDatabase *adb) { int rowCount = 0; FMResultSet *ars = [adb executeQuery:@"select * from transtest"]; while ([ars next]) { rowCount++; } FMDBQuickCheck(![adb hasOpenResultSets]); NSLog(@"after rollback, rowCount is %d (should be 2)", rowCount); FMDBQuickCheck(rowCount == 2); }]; } // hey, let's make a custom function! [queue inDatabase:^(FMDatabase *adb) { [adb executeUpdate:@"create table ftest (foo text)"]; [adb executeUpdate:@"insert into ftest values ('hello')"]; [adb executeUpdate:@"insert into ftest values ('hi')"]; [adb executeUpdate:@"insert into ftest values ('not h!')"]; [adb executeUpdate:@"insert into ftest values ('definitely not h!')"]; [adb makeFunctionNamed:@"StringStartsWithH" arguments:1 block:^(/*sqlite3_context*/ void *context, int aargc, /*sqlite3_value*/ void **aargv) { if (sqlite3_value_type(aargv[0]) == SQLITE_TEXT) { @autoreleasepool { const char *c = (const char *)sqlite3_value_text(aargv[0]); NSString *s = [NSString stringWithUTF8String:c]; sqlite3_result_int(context, [s hasPrefix:@"h"]); } } else { NSLog(@"Unknown formart for StringStartsWithH (%d) %s:%d", sqlite3_value_type(aargv[0]), __FUNCTION__, __LINE__); sqlite3_result_null(context); } }]; int rowCount = 0; FMResultSet *ars = [adb executeQuery:@"select * from ftest where StringStartsWithH(foo)"]; while ([ars next]) { rowCount++; NSLog(@"Does %@ start with 'h'?", [rs stringForColumnIndex:0]); } FMDBQuickCheck(rowCount == 2); testStatementCaching(); }]; NSLog(@"That was version %@ of sqlite", [FMDatabase sqliteLibVersion]); }// this is the end of our @autorelease pool. return 0; } /* Test statement caching This test checks the fixes that address https://github.com/ccgus/fmdb/issues/6 */ void testStatementCaching(void) { FMDatabase *db = [FMDatabase databaseWithPath:nil]; // use in-memory DB [db open]; [db executeUpdate:@"DROP TABLE IF EXISTS testStatementCaching"]; [db executeUpdate:@"CREATE TABLE testStatementCaching ( value INTEGER )"]; [db executeUpdate:@"INSERT INTO testStatementCaching( value ) VALUES (1)"]; [db executeUpdate:@"INSERT INTO testStatementCaching( value ) VALUES (1)"]; [db executeUpdate:@"INSERT INTO testStatementCaching( value ) VALUES (2)"]; [db setShouldCacheStatements:YES]; // two iterations. // the first time through no statements will be from the cache. // the second time through all statements come from the cache. for (int i = 1; i <= 2; i++ ) { FMResultSet* rs1 = [db executeQuery: @"SELECT rowid, * FROM testStatementCaching WHERE value = ?", @1]; // results in 2 rows... FMDBQuickCheck([rs1 next]); // confirm that we're seeing the benefits of caching. FMDBQuickCheck([[rs1 statement] useCount] == i); FMResultSet* rs2 = [db executeQuery:@"SELECT rowid, * FROM testStatementCaching WHERE value = ?", @2]; // results in 1 row FMDBQuickCheck([rs2 next]); FMDBQuickCheck([[rs2 statement] useCount] == i); // This is the primary check - with the old implementation of statement caching, rs2 would have rejiggered the (cached) statement used by rs1, making this test fail to return the 2nd row in rs1. FMDBQuickCheck([rs1 next]); [rs1 close]; [rs2 close]; } [db close]; } /* Test the various FMDatabasePool things. */ void testPool(NSString *dbPath) { FMDatabasePool *dbPool = [FMDatabasePool databasePoolWithPath:dbPath]; FMDBQuickCheck([dbPool countOfOpenDatabases] == 0); __block FMDatabase *db1; [dbPool inDatabase:^(FMDatabase *db) { FMDBQuickCheck([dbPool countOfOpenDatabases] == 1); FMDBQuickCheck([db tableExists:@"t4"]); db1 = db; }]; [dbPool inDatabase:^(FMDatabase *db) { FMDBQuickCheck(db1 == db); [dbPool inDatabase:^(FMDatabase *db2) { FMDBQuickCheck(db2 != db); }]; }]; FMDBQuickCheck([dbPool countOfOpenDatabases] == 2); [dbPool inDatabase:^(FMDatabase *db) { [db executeUpdate:@"create table easy (a text)"]; [db executeUpdate:@"create table easy2 (a text)"]; }]; FMDBQuickCheck([dbPool countOfOpenDatabases] == 2); [dbPool releaseAllDatabases]; FMDBQuickCheck([dbPool countOfOpenDatabases] == 0); [dbPool inDatabase:^(FMDatabase *aDb) { FMDBQuickCheck([dbPool countOfCheckedInDatabases] == 0); FMDBQuickCheck([dbPool countOfCheckedOutDatabases] == 1); FMDBQuickCheck([aDb tableExists:@"t4"]); FMDBQuickCheck([dbPool countOfCheckedInDatabases] == 0); FMDBQuickCheck([dbPool countOfCheckedOutDatabases] == 1); FMDBQuickCheck(([aDb executeUpdate:@"insert into easy (a) values (?)", @"hi"])); // just for fun. FMResultSet *rs2 = [aDb executeQuery:@"select * from easy"]; FMDBQuickCheck([rs2 next]); while ([rs2 next]) { ; } // whatevers. FMDBQuickCheck([dbPool countOfOpenDatabases] == 1); FMDBQuickCheck([dbPool countOfCheckedInDatabases] == 0); FMDBQuickCheck([dbPool countOfCheckedOutDatabases] == 1); }]; FMDBQuickCheck([dbPool countOfOpenDatabases] == 1); { [dbPool inDatabase:^(FMDatabase *db) { [db executeUpdate:@"insert into easy values (?)", [NSNumber numberWithInt:1]]; [db executeUpdate:@"insert into easy values (?)", [NSNumber numberWithInt:2]]; [db executeUpdate:@"insert into easy values (?)", [NSNumber numberWithInt:3]]; FMDBQuickCheck([dbPool countOfCheckedInDatabases] == 0); FMDBQuickCheck([dbPool countOfCheckedOutDatabases] == 1); }]; } FMDBQuickCheck([dbPool countOfOpenDatabases] == 1); [dbPool setMaximumNumberOfDatabasesToCreate:2]; [dbPool inDatabase:^(FMDatabase *db) { [dbPool inDatabase:^(FMDatabase *db2) { [dbPool inDatabase:^(FMDatabase *db3) { FMDBQuickCheck([dbPool countOfOpenDatabases] == 2); FMDBQuickCheck(!db3); }]; }]; }]; [dbPool setMaximumNumberOfDatabasesToCreate:0]; [dbPool releaseAllDatabases]; FMDBQuickCheck([dbPool countOfOpenDatabases] == 0); [dbPool inDatabase:^(FMDatabase *db) { [db executeUpdate:@"insert into easy values (?)", [NSNumber numberWithInt:3]]; }]; FMDBQuickCheck([dbPool countOfOpenDatabases] == 1); [dbPool inTransaction:^(FMDatabase *adb, BOOL *rollback) { [adb executeUpdate:@"insert into easy values (?)", [NSNumber numberWithInt:1001]]; [adb executeUpdate:@"insert into easy values (?)", [NSNumber numberWithInt:1002]]; [adb executeUpdate:@"insert into easy values (?)", [NSNumber numberWithInt:1003]]; FMDBQuickCheck([dbPool countOfOpenDatabases] == 1); FMDBQuickCheck([dbPool countOfCheckedInDatabases] == 0); FMDBQuickCheck([dbPool countOfCheckedOutDatabases] == 1); }]; FMDBQuickCheck([dbPool countOfOpenDatabases] == 1); FMDBQuickCheck([dbPool countOfCheckedInDatabases] == 1); FMDBQuickCheck([dbPool countOfCheckedOutDatabases] == 0); [dbPool inDatabase:^(FMDatabase *db) { FMResultSet *rs2 = [db executeQuery:@"select * from easy where a = ?", [NSNumber numberWithInt:1001]]; FMDBQuickCheck([rs2 next]); FMDBQuickCheck(![rs2 next]); }]; [dbPool inDeferredTransaction:^(FMDatabase *adb, BOOL *rollback) { [adb executeUpdate:@"insert into easy values (?)", [NSNumber numberWithInt:1004]]; [adb executeUpdate:@"insert into easy values (?)", [NSNumber numberWithInt:1005]]; *rollback = YES; }]; FMDBQuickCheck([dbPool countOfOpenDatabases] == 1); FMDBQuickCheck([dbPool countOfCheckedInDatabases] == 1); FMDBQuickCheck([dbPool countOfCheckedOutDatabases] == 0); NSError *err = [dbPool inSavePoint:^(FMDatabase *db, BOOL *rollback) { [db executeUpdate:@"insert into easy values (?)", [NSNumber numberWithInt:1006]]; }]; FMDBQuickCheck(!err); { err = [dbPool inSavePoint:^(FMDatabase *adb, BOOL *rollback) { FMDBQuickCheck(![adb hadError]); [adb executeUpdate:@"insert into easy values (?)", [NSNumber numberWithInt:1009]]; [adb inSavePoint:^(BOOL *arollback) { FMDBQuickCheck(([adb executeUpdate:@"insert into easy values (?)", [NSNumber numberWithInt:1010]])); *arollback = YES; }]; }]; FMDBQuickCheck(!err); [dbPool inDatabase:^(FMDatabase *db) { FMResultSet *rs2 = [db executeQuery:@"select * from easy where a = ?", [NSNumber numberWithInt:1009]]; FMDBQuickCheck([rs2 next]); FMDBQuickCheck(![rs2 next]); // close it out. rs2 = [db executeQuery:@"select * from easy where a = ?", [NSNumber numberWithInt:1010]]; FMDBQuickCheck(![rs2 next]); }]; } { [dbPool inDatabase:^(FMDatabase *db) { [db executeUpdate:@"create table likefoo (foo text)"]; [db executeUpdate:@"insert into likefoo values ('hi')"]; [db executeUpdate:@"insert into likefoo values ('hello')"]; [db executeUpdate:@"insert into likefoo values ('not')"]; int count = 0; FMResultSet *rsl = [db executeQuery:@"select * from likefoo where foo like 'h%'"]; while ([rsl next]) { count++; } FMDBQuickCheck(count == 2); count = 0; rsl = [db executeQuery:@"select * from likefoo where foo like ?", @"h%"]; while ([rsl next]) { count++; } FMDBQuickCheck(count == 2); }]; } { size_t ops = 128; dispatch_queue_t dqueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_apply(ops, dqueue, ^(size_t nby) { // just mix things up a bit for demonstration purposes. if (nby % 2 == 1) { [NSThread sleepForTimeInterval:.1]; } [dbPool inDatabase:^(FMDatabase *db) { NSLog(@"Starting query %ld", nby); FMResultSet *rsl = [db executeQuery:@"select * from likefoo where foo like 'h%'"]; while ([rsl next]) { if (nby % 3 == 1) { [NSThread sleepForTimeInterval:.05]; } } NSLog(@"Ending query %ld", nby); }]; }); NSLog(@"Number of open databases after crazy gcd stuff: %ld", [dbPool countOfOpenDatabases]); } FMDatabasePool *dbPool2 = [FMDatabasePool databasePoolWithPath:dbPath flags:SQLITE_OPEN_READONLY]; FMDBQuickCheck(dbPool2); { [dbPool2 inDatabase:^(FMDatabase *db2) { FMResultSet *rs1 = [db2 executeQuery:@"SELECT * FROM test"]; FMDBQuickCheck(rs1 != nil); [rs1 close]; BOOL ok = [db2 executeUpdate:@"insert into easy values (?)", [NSNumber numberWithInt:3]]; FMDBQuickCheck(!ok); }]; } // if you want to see a deadlock, just uncomment this line and run: //#define ONLY_USE_THE_POOL_IF_YOU_ARE_DOING_READS_OTHERWISE_YOULL_DEADLOCK_USE_FMDATABASEQUEUE_INSTEAD 1 #ifdef ONLY_USE_THE_POOL_IF_YOU_ARE_DOING_READS_OTHERWISE_YOULL_DEADLOCK_USE_FMDATABASEQUEUE_INSTEAD { int ops = 16; dispatch_queue_t dqueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_apply(ops, dqueue, ^(size_t nby) { // just mix things up a bit for demonstration purposes. if (nby % 2 == 1) { [NSThread sleepForTimeInterval:.1]; [dbPool inTransaction:^(FMDatabase *db, BOOL *rollback) { NSLog(@"Starting query %ld", nby); FMResultSet *rsl = [db executeQuery:@"select * from likefoo where foo like 'h%'"]; while ([rsl next]) { ;// whatever. } NSLog(@"Ending query %ld", nby); }]; } if (nby % 3 == 1) { [NSThread sleepForTimeInterval:.1]; } [dbPool inTransaction:^(FMDatabase *db, BOOL *rollback) { NSLog(@"Starting update %ld", nby); [db executeUpdate:@"insert into likefoo values ('1')"]; [db executeUpdate:@"insert into likefoo values ('2')"]; [db executeUpdate:@"insert into likefoo values ('3')"]; NSLog(@"Ending update %ld", nby); }]; }); [dbPool releaseAllDatabases]; [dbPool inDatabase:^(FMDatabase *db) { FMDBQuickCheck([db executeUpdate:@"insert into likefoo values ('1')"]); }]; } #endif } /* Test the date format */ void testOneDateFormat( FMDatabase *db, NSDate *testDate ) { [db executeUpdate:@"DROP TABLE IF EXISTS test_format"]; [db executeUpdate:@"CREATE TABLE test_format ( test TEXT )"]; [db executeUpdate:@"INSERT INTO test_format(test) VALUES (?)", testDate]; FMResultSet *rs = [db executeQuery:@"SELECT test FROM test_format"]; if ([rs next]) { NSDate *found = [rs dateForColumnIndex:0]; if (NSOrderedSame != [testDate compare:found]) { NSLog(@"Did not get back what we stored."); } } else { NSLog(@"Insertion borked"); } [rs close]; } void testDateFormat(void) { FMDatabase *db = [FMDatabase databaseWithPath:nil]; // use in-memory DB [db open]; NSDateFormatter *fmt = [FMDatabase storeableDateFormat:@"yyyy-MM-dd HH:mm:ss"]; NSDate *testDate = [fmt dateFromString:@"2013-02-20 12:00:00"]; // test timestamp dates (ensuring our change does not break those) testOneDateFormat(db,testDate); // now test the string-based timestamp [db setDateFormat:fmt]; testOneDateFormat(db, testDate); [db close]; } /* What is this function for? Think of it as a template which a developer can use to report bugs. If you have a bug, make it reproduce in this function and then let the developer(s) know either via the github bug reporter or the mailing list. */ void FMDBReportABugFunction(void) { NSString *dbPath = @"/tmp/bugreportsample.db"; // delete the old db if it exists NSFileManager *fileManager = [NSFileManager defaultManager]; [fileManager removeItemAtPath:dbPath error:nil]; FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:dbPath]; [queue inDatabase:^(FMDatabase *db) { /* Change the contents of this block to suit your needs. */ BOOL worked = [db executeUpdate:@"create table test (a text, b text, c integer, d double, e double)"]; FMDBQuickCheck(worked); worked = [db executeUpdate:@"insert into test values ('a', 'b', 1, 2.2, 2.3)"]; FMDBQuickCheck(worked); FMResultSet *rs = [db executeQuery:@"select * from test"]; FMDBQuickCheck([rs next]); [rs close]; }]; [queue close]; // uncomment the following line if you don't want to run through all the other tests. //exit(0); }