diff --git a/Evergreen.xcodeproj/project.pbxproj b/Evergreen.xcodeproj/project.pbxproj index 6bd659aa9..c650866d6 100644 --- a/Evergreen.xcodeproj/project.pbxproj +++ b/Evergreen.xcodeproj/project.pbxproj @@ -14,6 +14,8 @@ 849C64761ED37A5D003D8FC0 /* EvergreenTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 849C64751ED37A5D003D8FC0 /* EvergreenTests.swift */; }; 84B06F821ED37BDD00F0B54B /* RSXML.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 84B06F7D1ED37BCA00F0B54B /* RSXML.framework */; }; 84B06F831ED37BDD00F0B54B /* RSXML.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 84B06F7D1ED37BCA00F0B54B /* RSXML.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; + 84B06F921ED37CB300F0B54B /* RSDatabase.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 84B06F8D1ED37CA100F0B54B /* RSDatabase.framework */; }; + 84B06F931ED37CB300F0B54B /* RSDatabase.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 84B06F8D1ED37CA100F0B54B /* RSDatabase.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ @@ -52,6 +54,34 @@ remoteGlobalIDString = 84F22C0C1B52DDEA000060CE; remoteInfo = RSXML; }; + 84B06F8C1ED37CA100F0B54B /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 84B06F861ED37CA000F0B54B /* RSDatabase.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 84F22C551B52E0D9000060CE; + remoteInfo = RSDatabase; + }; + 84B06F8E1ED37CA100F0B54B /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 84B06F861ED37CA000F0B54B /* RSDatabase.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 84F22C5F1B52E0D9000060CE; + remoteInfo = RSDatabaseTests; + }; + 84B06F901ED37CA100F0B54B /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 84B06F861ED37CA000F0B54B /* RSDatabase.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 8400ABF71E0CFBD800AA7C57; + remoteInfo = RSDatabaseiOS; + }; + 84B06F941ED37CB300F0B54B /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 84B06F861ED37CA000F0B54B /* RSDatabase.xcodeproj */; + proxyType = 1; + remoteGlobalIDString = 84F22C541B52E0D9000060CE; + remoteInfo = RSDatabase; + }; /* End PBXContainerItemProxy section */ /* Begin PBXCopyFilesBuildPhase section */ @@ -61,6 +91,7 @@ dstPath = ""; dstSubfolderSpec = 10; files = ( + 84B06F931ED37CB300F0B54B /* RSDatabase.framework in Embed Frameworks */, 84B06F831ED37BDD00F0B54B /* RSXML.framework in Embed Frameworks */, ); name = "Embed Frameworks"; @@ -79,6 +110,7 @@ 849C64751ED37A5D003D8FC0 /* EvergreenTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = EvergreenTests.swift; sourceTree = ""; }; 849C64771ED37A5D003D8FC0 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; 84B06F761ED37BCA00F0B54B /* RSXML.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = RSXML.xcodeproj; path = Frameworks/RSXML/RSXML.xcodeproj; sourceTree = ""; }; + 84B06F861ED37CA000F0B54B /* RSDatabase.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = RSDatabase.xcodeproj; path = Frameworks/RSDatabase/RSDatabase.xcodeproj; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -86,6 +118,7 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( + 84B06F921ED37CB300F0B54B /* RSDatabase.framework in Frameworks */, 84B06F821ED37BDD00F0B54B /* RSXML.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; @@ -110,6 +143,7 @@ 849C646C1ED37A5D003D8FC0 /* Info.plist */, 849C64741ED37A5D003D8FC0 /* EvergreenTests */, 849C64611ED37A5D003D8FC0 /* Products */, + 84B06F861ED37CA000F0B54B /* RSDatabase.xcodeproj */, 84B06F761ED37BCA00F0B54B /* RSXML.xcodeproj */, ); sourceTree = ""; @@ -142,6 +176,16 @@ name = Products; sourceTree = ""; }; + 84B06F871ED37CA000F0B54B /* Products */ = { + isa = PBXGroup; + children = ( + 84B06F8D1ED37CA100F0B54B /* RSDatabase.framework */, + 84B06F8F1ED37CA100F0B54B /* RSDatabaseTests.xctest */, + 84B06F911ED37CA100F0B54B /* RSDatabase.framework */, + ); + name = Products; + sourceTree = ""; + }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ @@ -158,6 +202,7 @@ ); dependencies = ( 84B06F851ED37BDD00F0B54B /* PBXTargetDependency */, + 84B06F951ED37CB300F0B54B /* PBXTargetDependency */, ); name = Evergreen; productName = Evergreen; @@ -217,6 +262,10 @@ productRefGroup = 849C64611ED37A5D003D8FC0 /* Products */; projectDirPath = ""; projectReferences = ( + { + ProductGroup = 84B06F871ED37CA000F0B54B /* Products */; + ProjectRef = 84B06F861ED37CA000F0B54B /* RSDatabase.xcodeproj */; + }, { ProductGroup = 84B06F771ED37BCA00F0B54B /* Products */; ProjectRef = 84B06F761ED37BCA00F0B54B /* RSXML.xcodeproj */; @@ -252,6 +301,27 @@ remoteRef = 84B06F801ED37BCA00F0B54B /* PBXContainerItemProxy */; sourceTree = BUILT_PRODUCTS_DIR; }; + 84B06F8D1ED37CA100F0B54B /* RSDatabase.framework */ = { + isa = PBXReferenceProxy; + fileType = wrapper.framework; + path = RSDatabase.framework; + remoteRef = 84B06F8C1ED37CA100F0B54B /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 84B06F8F1ED37CA100F0B54B /* RSDatabaseTests.xctest */ = { + isa = PBXReferenceProxy; + fileType = wrapper.cfbundle; + path = RSDatabaseTests.xctest; + remoteRef = 84B06F8E1ED37CA100F0B54B /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 84B06F911ED37CA100F0B54B /* RSDatabase.framework */ = { + isa = PBXReferenceProxy; + fileType = wrapper.framework; + path = RSDatabase.framework; + remoteRef = 84B06F901ED37CA100F0B54B /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; /* End PBXReferenceProxy section */ /* Begin PBXResourcesBuildPhase section */ @@ -304,6 +374,11 @@ name = RSXML; targetProxy = 84B06F841ED37BDD00F0B54B /* PBXContainerItemProxy */; }; + 84B06F951ED37CB300F0B54B /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = RSDatabase; + targetProxy = 84B06F941ED37CB300F0B54B /* PBXContainerItemProxy */; + }; /* End PBXTargetDependency section */ /* Begin PBXVariantGroup section */ diff --git a/Frameworks/RSDatabase/.gitignore b/Frameworks/RSDatabase/.gitignore new file mode 100755 index 000000000..86f21d8e0 --- /dev/null +++ b/Frameworks/RSDatabase/.gitignore @@ -0,0 +1,60 @@ +# Xcode +# +# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore + +## Build generated +build/ +DerivedData/ + +## Various settings +*.pbxuser +!default.pbxuser +*.mode1v3 +!default.mode1v3 +*.mode2v3 +!default.mode2v3 +*.perspectivev3 +!default.perspectivev3 +xcuserdata/ + +## Other +*.moved-aside +*.xcuserstate + +## Obj-C/Swift specific +*.hmap +*.ipa +*.dSYM.zip +*.dSYM + +# CocoaPods +# +# We recommend against adding the Pods directory to your .gitignore. However +# you should judge for yourself, the pros and cons are mentioned at: +# https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control +# +# Pods/ + +# Carthage +# +# Add this line if you want to avoid checking in source code from Carthage dependencies. +# Carthage/Checkouts + +Carthage/Build + +# fastlane +# +# It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the +# screenshots whenever they are needed. +# For more information about the recommended setup visit: +# https://github.com/fastlane/fastlane/blob/master/fastlane/docs/Gitignore.md + +fastlane/report.xml +fastlane/screenshots + +#Code Injection +# +# After new code Injection tools there's a generated folder /iOSInjectionProject +# https://github.com/johnno1962/injectionforxcode + +iOSInjectionProject/ diff --git a/Frameworks/RSDatabase/FMDB/FMDB/FMDB.h b/Frameworks/RSDatabase/FMDB/FMDB/FMDB.h new file mode 100755 index 000000000..7f7ad9244 --- /dev/null +++ b/Frameworks/RSDatabase/FMDB/FMDB/FMDB.h @@ -0,0 +1,13 @@ +// +// FMDB.h +// FMDB +// +// Created by Brent Simmons on 7/18/15. +// Copyright © 2015 Ranchero Software, LLC. All rights reserved. +// + +@import Foundation; + +#import +#import +#import diff --git a/Frameworks/RSDatabase/FMDB/FMDB/Info.plist b/Frameworks/RSDatabase/FMDB/FMDB/Info.plist new file mode 100755 index 000000000..87b01750b --- /dev/null +++ b/Frameworks/RSDatabase/FMDB/FMDB/Info.plist @@ -0,0 +1,28 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.0 + CFBundleSignature + ???? + CFBundleVersion + $(CURRENT_PROJECT_VERSION) + NSHumanReadableCopyright + Copyright © 2015 Ranchero Software, LLC. All rights reserved. + NSPrincipalClass + + + diff --git a/Frameworks/RSDatabase/FMDB/fmdb-master/.gitignore b/Frameworks/RSDatabase/FMDB/fmdb-master/.gitignore new file mode 100755 index 000000000..838dbb6f0 --- /dev/null +++ b/Frameworks/RSDatabase/FMDB/fmdb-master/.gitignore @@ -0,0 +1,8 @@ +.DS_Store +build +*.xcodeproj/*.pbxuser +*.xcodeproj/*.perspectivev3 +*.xcodeproj/xcuserdata +fmdb.xcodeproj/*.mode1v3 +*.xcodeproj/project.xcworkspace/xcuserdata/ +fmdb.xcodeproj/project.xcworkspace diff --git a/Frameworks/RSDatabase/FMDB/fmdb-master/.travis.yml b/Frameworks/RSDatabase/FMDB/fmdb-master/.travis.yml new file mode 100755 index 000000000..7e21267e7 --- /dev/null +++ b/Frameworks/RSDatabase/FMDB/fmdb-master/.travis.yml @@ -0,0 +1,5 @@ +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/" diff --git a/Frameworks/RSDatabase/FMDB/fmdb-master/CHANGES_AND_TODO_LIST.txt b/Frameworks/RSDatabase/FMDB/fmdb-master/CHANGES_AND_TODO_LIST.txt new file mode 100755 index 000000000..44db7451a --- /dev/null +++ b/Frameworks/RSDatabase/FMDB/fmdb-master/CHANGES_AND_TODO_LIST.txt @@ -0,0 +1,327 @@ +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 a couple of tests for your new code to fmdb.m. 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. + +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: + +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 diff --git a/Frameworks/RSDatabase/FMDB/fmdb-master/CONTRIBUTORS.txt b/Frameworks/RSDatabase/FMDB/fmdb-master/CONTRIBUTORS.txt new file mode 100755 index 000000000..b61adf7fe --- /dev/null +++ b/Frameworks/RSDatabase/FMDB/fmdb-master/CONTRIBUTORS.txt @@ -0,0 +1,50 @@ +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 + +Aaaaannnd, Gus Mueller (that's me!) diff --git a/Frameworks/RSDatabase/FMDB/fmdb-master/FMDB.podspec b/Frameworks/RSDatabase/FMDB/fmdb-master/FMDB.podspec new file mode 100755 index 000000000..9790b3932 --- /dev/null +++ b/Frameworks/RSDatabase/FMDB/fmdb-master/FMDB.podspec @@ -0,0 +1,53 @@ +Pod::Spec.new do |s| + s.name = 'FMDB' + s.version = '2.5' + 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 => 'v2.5' } + s.requires_arc = true + + s.default_subspec = 'standard' + + s.subspec 'common' do |ss| + ss.source_files = 'src/fmdb/FM*.{h,m}' + ss.exclude_files = 'src/fmdb.m' + end + + # use the built-in library version of sqlite3 + s.subspec 'standard' do |ss| + ss.library = 'sqlite3' + ss.dependency 'FMDB/common' + end + + # use the built-in library version of sqlite3 with custom FTS tokenizer source files + s.subspec 'FTS' do |ss| + ss.source_files = 'src/extra/fts3/*.{h,m}' + ss.dependency 'FMDB/standard' + end + + # build the latest stable version of sqlite3 + s.subspec 'standalone' do |ss| + ss.default_subspec = 'default' + ss.dependency 'FMDB/common' + + ss.subspec 'default' do |sss| + sss.dependency 'sqlite3' + end + + # build with FTS support and custom FTS tokenizer source files + ss.subspec 'FTS' do |sss| + sss.source_files = 'src/extra/fts3/*.{h,m}' + sss.dependency 'sqlite3/fts' + end + end + + # use SQLCipher and enable -DSQLITE_HAS_CODEC flag + s.subspec 'SQLCipher' do |ss| + ss.dependency 'SQLCipher' + ss.dependency 'FMDB/common' + ss.xcconfig = { 'OTHER_CFLAGS' => '$(inherited) -DSQLITE_HAS_CODEC' } + end + +end diff --git a/Frameworks/RSDatabase/FMDB/fmdb-master/LICENSE.txt b/Frameworks/RSDatabase/FMDB/fmdb-master/LICENSE.txt new file mode 100755 index 000000000..addfc1ada --- /dev/null +++ b/Frameworks/RSDatabase/FMDB/fmdb-master/LICENSE.txt @@ -0,0 +1,28 @@ +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. \ No newline at end of file diff --git a/Frameworks/RSDatabase/FMDB/fmdb-master/README.markdown b/Frameworks/RSDatabase/FMDB/fmdb-master/README.markdown new file mode 100755 index 000000000..35550b58c --- /dev/null +++ b/Frameworks/RSDatabase/FMDB/fmdb-master/README.markdown @@ -0,0 +1,369 @@ +# FMDB v2.5 +This is an Objective-C wrapper around SQLite: http://sqlite.org/ + +## The FMDB Mailing List: +http://groups.google.com/group/fmdb + +## Read the SQLite FAQ: +http://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: http://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. + +## CocoaPods + +[![Dependency Status](https://www.versioneye.com/objective-c/fmdb/2.3/badge.svg?style=flat)](https://www.versioneye.com/objective-c/fmdb/2.3) +[![Reference Status](https://www.versioneye.com/objective-c/fmdb/reference_badge.svg?style=flat)](https://www.versioneye.com/objective-c/fmdb/references) + +FMDB can be installed using [CocoaPods](http://cocoapods.org/). + +``` +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 +``` + +**If using FMDB with [SQLCipher](http://sqlcipher.net/) 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.** + +## FMDB Class Reference: +http://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. + +## 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 with the `FMDatabase` connection is closed. +3. `NULL`. An in-memory database is created. This database will be destroyed with the `FMDatabase` connection is closed. + +(For more information on temporary and in-memory databases, read the sqlite documentation on the subject: http://www.sqlite.org/inmemorydb.html) + +```objc +FMDatabase *db = [FMDatabase databaseWithPath:@"/tmp/tmp.db"]; +``` + +### 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]; + 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]; +} +``` + +`FMResultSet` has many methods to retrieve data in an appropriate format: + +- `intForColumn:` +- `longForColumn:` +- `longLongIntForColumn:` +- `boolForColumn:` +- `doubleForColumn:` +- `stringForColumn:` +- `dateForColumn:` +- `dataForColumn:` +- `dataNoCopyForColumn:` +- `UTF8StringForColumnName:` +- `objectForColumnName:` + +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 deallocated, or the parent database is closed. + +### 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. + +Alternatively, you may use named parameters syntax: + +```sql +INSERT INTO myTable VALUES (:id, :name, :value) +``` + +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 *argsDict = [NSDictionary dictionaryWithObjectsAndKeys:@"My Name", @"name", nil]; +[db executeUpdate:@"INSERT INTO myTable (name) VALUES (:name)" withParameterDictionary:argsDict]; +``` + +Thus, you SHOULD NOT do this (or anything like this): + +```objc +[db executeUpdate:[NSString stringWithFormat:@"INSERT INTO myTable VALUES (%@)", @"this has \" lots of ' bizarre \" quotes '"]]; +``` +Instead, you SHOULD do: + +```objc +[db executeUpdate:@"INSERT INTO myTable VALUES (?)", @"this has \" lots of ' bizarre \" quotes '"]; +``` + +All arguments provided to the `-executeUpdate:` method (or any of the variants that accept a `va_list` as a parameter) must be objects. The following will not work (and will result in a crash): + +```objc +[db executeUpdate:@"INSERT INTO myTable VALUES (?)", 42]; +``` + +The proper way to insert a number is to box it in an `NSNumber` object: + +```objc +[db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:42]]; +``` + +Alternatively, you can use the `-execute*WithFormat:` variant to use `NSString`-style substitution: + +```objc +[db executeUpdateWithFormat:@"INSERT INTO myTable VALUES (%d)", 42]; +``` + +Internally, the `-execute*WithFormat:` methods are properly boxing things for you. The following percent modifiers are recognized: `%@`, `%c`, `%s`, `%d`, `%D`, `%i`, `%u`, `%U`, `%hi`, `%hu`, `%qi`, `%qu`, `%f`, `%g`, `%ld`, `%lu`, `%lld`, and `%llu`. Using a modifier other than those will have unpredictable results. If, for some reason, you need the `%` character to appear in your SQL statement, you should use `%%`. + + +

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. It's your friend and it's here to help. 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 (?)", [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]) { + … + } +}]; +``` + +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 (?)", [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]]; +}]; +``` + +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 FMDB `.m` and `.h` files into your project. + +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: + ```swift + #import "FMDB.h" + ``` + +4. Optionally, copy the `FMDatabaseVariadic.swift` from the "src/extra/Swift Extensions" folder into your project. This allows you to use `executeUpdate` and `executeQuery` with variadic parameters, rather than the `withArgumentsInArray` rendition. + +If you do the above, you can then write Swift code that uses FMDatabase. For example: + +```swift +let documentsFolder = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String +let path = documentsFolder.stringByAppendingPathComponent("test.sqlite") + +let database = FMDatabase(path: path) + +if !database.open() { + println("Unable to open database") + return +} + +if !database.executeUpdate("create table test(x text, y text, z text)", withArgumentsInArray: nil) { + println("create table failed: \(database.lastErrorMessage())") +} + +if !database.executeUpdate("insert into test (x, y, z) values (?, ?, ?)", withArgumentsInArray: ["a", "b", "c"]) { + println("insert 1 table failed: \(database.lastErrorMessage())") +} + +if !database.executeUpdate("insert into test (x, y, z) values (?, ?, ?)", withArgumentsInArray: ["e", "f", "g"]) { + println("insert 2 table failed: \(database.lastErrorMessage())") +} + +if let rs = database.executeQuery("select x, y, z from test", withArgumentsInArray: nil) { + while rs.next() { + let x = rs.stringForColumn("x") + let y = rs.stringForColumn("y") + let z = rs.stringForColumn("z") + println("x = \(x); y = \(y); z = \(z)") + } +} else { + println("select failed: \(database.lastErrorMessage())") +} + +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.) diff --git a/Frameworks/RSDatabase/FMDB/fmdb-master/Tests/FMDBTempDBTests.h b/Frameworks/RSDatabase/FMDB/fmdb-master/Tests/FMDBTempDBTests.h new file mode 100755 index 000000000..c84ab8fd9 --- /dev/null +++ b/Frameworks/RSDatabase/FMDB/fmdb-master/Tests/FMDBTempDBTests.h @@ -0,0 +1,24 @@ +// +// 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 diff --git a/Frameworks/RSDatabase/FMDB/fmdb-master/Tests/FMDBTempDBTests.m b/Frameworks/RSDatabase/FMDB/fmdb-master/Tests/FMDBTempDBTests.m new file mode 100755 index 000000000..bb759dffd --- /dev/null +++ b/Frameworks/RSDatabase/FMDB/fmdb-master/Tests/FMDBTempDBTests.m @@ -0,0 +1,63 @@ +// +// FMDBTempDBTests.m +// fmdb +// +// Created by Graham Dennis on 24/11/2013. +// +// + +#import "FMDBTempDBTests.h" + +static NSString *const testDatabasePath = @"/tmp/tmp.db"; +static NSString *const populatedDatabasePath = @"/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 diff --git a/Frameworks/RSDatabase/FMDB/fmdb-master/Tests/FMDatabaseAdditionsTests.m b/Frameworks/RSDatabase/FMDB/fmdb-master/Tests/FMDatabaseAdditionsTests.m new file mode 100755 index 000000000..b36d17320 --- /dev/null +++ b/Frameworks/RSDatabase/FMDB/fmdb-master/Tests/FMDatabaseAdditionsTests.m @@ -0,0 +1,123 @@ +// +// FMDatabaseAdditionsTests.m +// fmdb +// +// Created by Graham Dennis on 24/11/2013. +// +// + +#import +#import "FMDatabaseAdditions.h" + +@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)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); +} + +#if SQLITE_VERSION_NUMBER >= 3007017 +- (void)testApplicationID +{ + 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"); +} +#endif + +@end diff --git a/Frameworks/RSDatabase/FMDB/fmdb-master/Tests/FMDatabaseFTS3Tests.m b/Frameworks/RSDatabase/FMDB/fmdb-master/Tests/FMDatabaseFTS3Tests.m new file mode 100755 index 000000000..e8774121e --- /dev/null +++ b/Frameworks/RSDatabase/FMDB/fmdb-master/Tests/FMDatabaseFTS3Tests.m @@ -0,0 +1,157 @@ +// +// 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 diff --git a/Frameworks/RSDatabase/FMDB/fmdb-master/Tests/FMDatabaseFTS3WithModuleNameTests.m b/Frameworks/RSDatabase/FMDB/fmdb-master/Tests/FMDatabaseFTS3WithModuleNameTests.m new file mode 100755 index 000000000..f48cc1e21 --- /dev/null +++ b/Frameworks/RSDatabase/FMDB/fmdb-master/Tests/FMDatabaseFTS3WithModuleNameTests.m @@ -0,0 +1,83 @@ +// +// 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 diff --git a/Frameworks/RSDatabase/FMDB/fmdb-master/Tests/FMDatabasePoolTests.m b/Frameworks/RSDatabase/FMDB/fmdb-master/Tests/FMDatabasePoolTests.m new file mode 100755 index 000000000..03fb0866f --- /dev/null +++ b/Frameworks/RSDatabase/FMDB/fmdb-master/Tests/FMDatabasePoolTests.m @@ -0,0 +1,303 @@ +// +// FMDatabasePoolTests.m +// fmdb +// +// Created by Graham Dennis on 24/11/2013. +// +// + +#import + +@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)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 diff --git a/Frameworks/RSDatabase/FMDB/fmdb-master/Tests/FMDatabaseQueueTests.m b/Frameworks/RSDatabase/FMDB/fmdb-master/Tests/FMDatabaseQueueTests.m new file mode 100755 index 000000000..cd7fb92fa --- /dev/null +++ b/Frameworks/RSDatabase/FMDB/fmdb-master/Tests/FMDatabaseQueueTests.m @@ -0,0 +1,176 @@ +// +// FMDatabaseQueueTests.m +// fmdb +// +// Created by Graham Dennis on 24/11/2013. +// +// + +#import +#import "FMDatabaseQueue.h" + +@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)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); + }]; + +} + +@end diff --git a/Frameworks/RSDatabase/FMDB/fmdb-master/Tests/FMDatabaseTests.m b/Frameworks/RSDatabase/FMDB/fmdb-master/Tests/FMDatabaseTests.m new file mode 100755 index 000000000..461acbaff --- /dev/null +++ b/Frameworks/RSDatabase/FMDB/fmdb-master/Tests/FMDatabaseTests.m @@ -0,0 +1,902 @@ +// +// Tests.m +// Tests +// +// Created by Graham Dennis on 24/11/2013. +// +// + +#import "FMDBTempDBTests.h" +#import "FMDatabase.h" +#import "FMDatabaseAdditions.h" + +@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"); +} + +- (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)testSelectWithIndexedAndKeyedSubscript +{ + FMResultSet *rs = [self.db executeQuery:@"select rowid, a, b, c from test"]; + + XCTAssertNotNil(rs, @"Should have a non-nil result set"); + + while ([rs next]) { + XCTAssertEqualObjects(rs[0], rs[@"rowid"], @"Column zero should be equal to 'rowid'"); + XCTAssertEqualObjects(rs[1], rs[@"a"], @"Column 1 should be equal to 'a'"); + XCTAssertEqualObjects(rs[2], rs[@"b"], @"Column 2 should be equal to 'b'"); + XCTAssertEqualObjects(rs[3], rs[@"c"], @"Column 3 should be equal to 'c'"); + } + + [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 numberWithBool: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:12]]; + + 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 UTF8StringForColumnName:@"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 UTF8StringForColumnName:@"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)testCustomFunction +{ + [self.db executeUpdate:@"create table ftest (foo text)"]; + [self.db executeUpdate:@"insert into ftest values ('hello')"]; + [self.db executeUpdate:@"insert into ftest values ('hi')"]; + [self.db executeUpdate:@"insert into ftest values ('not h!')"]; + [self.db executeUpdate:@"insert into ftest values ('definitely not h!')"]; + + [self.db makeFunctionNamed:@"StringStartsWithH" maximumArguments:1 withBlock:^(sqlite3_context *context, int aargc, sqlite3_value **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 { + XCTFail(@"Unknown format for StringStartsWithH (%d)", sqlite3_value_type(aargv[0])); + sqlite3_result_null(context); + } + }]; + + int rowCount = 0; + FMResultSet *ars = [self.db executeQuery:@"select * from ftest where StringStartsWithH(foo)"]; + while ([ars next]) { + rowCount++; + + } + XCTAssertEqual(rowCount, 2); + +} + +- (void)testVersionNumber { + XCTAssertTrue([FMDatabase FMDBVersion] == 0x0250); // this is going to break everytime we bump it. +} + +- (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"); + + sql = @"drop table bulktest1;" + "drop table bulktest2;" + "drop table bulktest3;"; + + 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 objectForColumnName:@"a"], @YES); + + XCTAssertEqual([rs boolForColumn:@"b"], false); + XCTAssertEqualObjects([rs objectForColumnName:@"b"], @NO); + + XCTAssertEqual([rs intForColumn:@"c"], 'x'); + XCTAssertEqualObjects([rs objectForColumnName:@"c"], @('x')); + + [rs close]; + + XCTAssertTrue([self.db executeUpdate:@"drop table charBoolTest"], @"Did not drop table"); + +} + +@end diff --git a/Frameworks/RSDatabase/FMDB/fmdb-master/Tests/FMResultSetTests.m b/Frameworks/RSDatabase/FMDB/fmdb-master/Tests/FMResultSetTests.m new file mode 100755 index 000000000..b62eea3fd --- /dev/null +++ b/Frameworks/RSDatabase/FMDB/fmdb-master/Tests/FMResultSetTests.m @@ -0,0 +1,91 @@ +// +// FMResultSetTests.m +// fmdb +// +// Created by Muralidharan,Roshan on 10/6/14. +// +// + +#import "FMDBTempDBTests.h" +#import "FMDatabase.h" +#import "FMResultSet.h" + +@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 beginTransaction]; + 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"); +} + +@end diff --git a/Frameworks/RSDatabase/FMDB/fmdb-master/Tests/Schemes/Tests.xcscheme b/Frameworks/RSDatabase/FMDB/fmdb-master/Tests/Schemes/Tests.xcscheme new file mode 100755 index 000000000..3ccd45ad7 --- /dev/null +++ b/Frameworks/RSDatabase/FMDB/fmdb-master/Tests/Schemes/Tests.xcscheme @@ -0,0 +1,83 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Frameworks/RSDatabase/FMDB/fmdb-master/Tests/Tests-Info.plist b/Frameworks/RSDatabase/FMDB/fmdb-master/Tests/Tests-Info.plist new file mode 100755 index 000000000..30e7ee255 --- /dev/null +++ b/Frameworks/RSDatabase/FMDB/fmdb-master/Tests/Tests-Info.plist @@ -0,0 +1,22 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + me.grahamdennis.${PRODUCT_NAME:rfc1034identifier} + CFBundleInfoDictionaryVersion + 6.0 + CFBundlePackageType + BNDL + CFBundleShortVersionString + 1.0 + CFBundleSignature + ???? + CFBundleVersion + 1 + + diff --git a/Frameworks/RSDatabase/FMDB/fmdb-master/Tests/Tests-Prefix.pch b/Frameworks/RSDatabase/FMDB/fmdb-master/Tests/Tests-Prefix.pch new file mode 100755 index 000000000..930e2c9b9 --- /dev/null +++ b/Frameworks/RSDatabase/FMDB/fmdb-master/Tests/Tests-Prefix.pch @@ -0,0 +1,11 @@ +// +// 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 diff --git a/Frameworks/RSDatabase/FMDB/fmdb-master/Tests/en.lproj/InfoPlist.strings b/Frameworks/RSDatabase/FMDB/fmdb-master/Tests/en.lproj/InfoPlist.strings new file mode 100755 index 000000000..477b28ff8 --- /dev/null +++ b/Frameworks/RSDatabase/FMDB/fmdb-master/Tests/en.lproj/InfoPlist.strings @@ -0,0 +1,2 @@ +/* Localized versions of Info.plist keys */ + diff --git a/Frameworks/RSDatabase/FMDB/fmdb-master/fmdb.1 b/Frameworks/RSDatabase/FMDB/fmdb-master/fmdb.1 new file mode 100755 index 000000000..361887ece --- /dev/null +++ b/Frameworks/RSDatabase/FMDB/fmdb-master/fmdb.1 @@ -0,0 +1,79 @@ +.\"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 \ No newline at end of file diff --git a/Frameworks/RSDatabase/FMDB/fmdb-master/fmdb.xcodeproj/project.pbxproj b/Frameworks/RSDatabase/FMDB/fmdb-master/fmdb.xcodeproj/project.pbxproj new file mode 100755 index 000000000..37772d80b --- /dev/null +++ b/Frameworks/RSDatabase/FMDB/fmdb-master/fmdb.xcodeproj/project.pbxproj @@ -0,0 +1,856 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 46; + objects = { + +/* Begin PBXBuildFile section */ + 3354379C19E71096005661F3 /* FMResultSetTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 3354379B19E71096005661F3 /* 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 */; }; + 67CB1E3019AD27D000A3CA7F /* FMDatabaseFTS3Tests.m in Sources */ = {isa = PBXBuildFile; fileRef = 67CB1E2F19AD27D000A3CA7F /* FMDatabaseFTS3Tests.m */; }; + 8314AF3318CD73D600EC0E25 /* FMDB.h in Headers */ = {isa = PBXBuildFile; fileRef = 8314AF3218CD73D600EC0E25 /* FMDB.h */; }; + 8DD76F9C0486AA7600D96B5E /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 08FB779EFE84155DC02AAC07 /* Foundation.framework */; }; + 8DD76F9F0486AA7600D96B5E /* fmdb.1 in CopyFiles */ = {isa = PBXBuildFile; fileRef = C6859EA3029092ED04C91782 /* fmdb.1 */; }; + BF5D041918416BB2008C5AA9 /* XCTest.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = BF5D041818416BB2008C5AA9 /* XCTest.framework */; }; + BF5D041F18416BB2008C5AA9 /* InfoPlist.strings in Resources */ = {isa = PBXBuildFile; fileRef = BF5D041D18416BB2008C5AA9 /* InfoPlist.strings */; }; + BF5D042118416BB2008C5AA9 /* FMDatabaseTests.m in Sources */ = {isa = PBXBuildFile; fileRef = BF5D042018416BB2008C5AA9 /* FMDatabaseTests.m */; }; + BF5D04281841702E008C5AA9 /* libFMDB.a in Frameworks */ = {isa = PBXBuildFile; fileRef = EE4290EF12B42F870088BD94 /* libFMDB.a */; }; + BF5D042918417159008C5AA9 /* libsqlite3.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = EE42910C12B42FFA0088BD94 /* libsqlite3.dylib */; }; + BF940F5C18417D490001E077 /* FMDBTempDBTests.m in Sources */ = {isa = PBXBuildFile; fileRef = BF940F5B18417D490001E077 /* FMDBTempDBTests.m */; }; + BF940F5E18417DEA0001E077 /* FMDatabaseAdditionsTests.m in Sources */ = {isa = PBXBuildFile; fileRef = BF940F5D18417DEA0001E077 /* FMDatabaseAdditionsTests.m */; }; + BFC152B118417F0D00605DF7 /* FMDatabaseAdditions.m in Sources */ = {isa = PBXBuildFile; fileRef = CC50F2CB0DF9183600E4AAAE /* FMDatabaseAdditions.m */; }; + BFE55E131841C9A000CB3A63 /* FMDatabasePoolTests.m in Sources */ = {isa = PBXBuildFile; fileRef = BFE55E121841C9A000CB3A63 /* FMDatabasePoolTests.m */; }; + BFE55E151841D38800CB3A63 /* FMDatabaseQueueTests.m in Sources */ = {isa = PBXBuildFile; fileRef = BFE55E141841D38800CB3A63 /* FMDatabaseQueueTests.m */; }; + CC47A00F148581E9002CCDAB /* FMDatabaseQueue.h in Headers */ = {isa = PBXBuildFile; fileRef = CC47A00D148581E9002CCDAB /* FMDatabaseQueue.h */; }; + 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 */; }; + 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 */; }; + D4A740A21A7046330058EBEE /* FMDatabaseFTS3WithModuleNameTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4A740A11A7046330058EBEE /* FMDatabaseFTS3WithModuleNameTests.m */; }; + EE42910512B42FBC0088BD94 /* FMDatabaseAdditions.m in Sources */ = {isa = PBXBuildFile; fileRef = CC50F2CB0DF9183600E4AAAE /* FMDatabaseAdditions.m */; }; + EE42910612B42FC30088BD94 /* FMDatabaseAdditions.h in Headers */ = {isa = PBXBuildFile; fileRef = CC50F2CC0DF9183600E4AAAE /* FMDatabaseAdditions.h */; }; + EE42910712B42FC90088BD94 /* FMDatabase.h in Headers */ = {isa = PBXBuildFile; fileRef = CCC24EBA0A13E34D00A6D3E3 /* FMDatabase.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 */; }; + EE42910D12B42FFA0088BD94 /* libsqlite3.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = EE42910C12B42FFA0088BD94 /* libsqlite3.dylib */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + BF5D042318416BB2008C5AA9 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 08FB7793FE84155DC02AAC07 /* Project object */; + proxyType = 1; + remoteGlobalIDString = EE4290EE12B42F870088BD94; + remoteInfo = FMDB; + }; +/* 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 = ""; }; + 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; }; + 3354379B19E71096005661F3 /* FMResultSetTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = FMResultSetTests.m; 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; }; + 67CB1E2F19AD27D000A3CA7F /* FMDatabaseFTS3Tests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = FMDatabaseFTS3Tests.m; sourceTree = ""; }; + 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 = ""; }; + 832F502419EC4C6B0087DCBF /* FMDatabaseVariadic.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = FMDatabaseVariadic.swift; path = "src/extra/Swift extensions/FMDatabaseVariadic.swift"; sourceTree = ""; }; + 8352D5AC1A73DCEA003A8E09 /* FMDatabaseAdditionsVariadic.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = FMDatabaseAdditionsVariadic.swift; path = "src/extra/Swift extensions/FMDatabaseAdditionsVariadic.swift"; sourceTree = ""; }; + 8DD76FA10486AA7600D96B5E /* fmdb */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = fmdb; sourceTree = BUILT_PRODUCTS_DIR; }; + 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; }; + BF5D041C18416BB2008C5AA9 /* Tests-Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = "Tests-Info.plist"; sourceTree = ""; }; + BF5D041E18416BB2008C5AA9 /* en */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = en; path = en.lproj/InfoPlist.strings; sourceTree = ""; }; + BF5D042018416BB2008C5AA9 /* FMDatabaseTests.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = FMDatabaseTests.m; sourceTree = ""; }; + BF5D042218416BB2008C5AA9 /* Tests-Prefix.pch */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Tests-Prefix.pch"; sourceTree = ""; }; + BF940F5A18417D490001E077 /* FMDBTempDBTests.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = FMDBTempDBTests.h; sourceTree = ""; }; + BF940F5B18417D490001E077 /* FMDBTempDBTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = FMDBTempDBTests.m; sourceTree = ""; }; + BF940F5D18417DEA0001E077 /* FMDatabaseAdditionsTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = FMDatabaseAdditionsTests.m; sourceTree = ""; }; + BFE55E121841C9A000CB3A63 /* FMDatabasePoolTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = FMDatabasePoolTests.m; sourceTree = ""; }; + BFE55E141841D38800CB3A63 /* FMDatabaseQueueTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = FMDatabaseQueueTests.m; sourceTree = ""; }; + 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; }; + D4A740A11A7046330058EBEE /* FMDatabaseFTS3WithModuleNameTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = FMDatabaseFTS3WithModuleNameTests.m; sourceTree = ""; }; + EE4290EF12B42F870088BD94 /* libFMDB.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libFMDB.a; sourceTree = BUILT_PRODUCTS_DIR; }; + EE42910C12B42FFA0088BD94 /* libsqlite3.dylib */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; name = libsqlite3.dylib; path = usr/lib/libsqlite3.dylib; sourceTree = SDKROOT; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 6290CBB2188FE836009790F8 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 6290CBB7188FE836009790F8 /* Foundation.framework 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; + }; + BF5D041318416BB2008C5AA9 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + BF5D042918417159008C5AA9 /* libsqlite3.dylib in Frameworks */, + BF5D04281841702E008C5AA9 /* libFMDB.a in Frameworks */, + BF5D041918416BB2008C5AA9 /* XCTest.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + EE4290ED12B42F870088BD94 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + EE42910D12B42FFA0088BD94 /* libsqlite3.dylib in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 08FB7794FE84155DC02AAC07 /* fmdb */ = { + isa = PBXGroup; + children = ( + 831DE6FD175B7C9C001F7317 /* README.markdown */, + CC8C138B0E3135C400FBE1E7 /* LICENSE.txt */, + CC8C138A0E3135C400FBE1E7 /* CHANGES_AND_TODO_LIST.txt */, + CC8C138C0E3135C400FBE1E7 /* CONTRIBUTORS.txt */, + 08FB7795FE84155DC02AAC07 /* Source */, + C6859EA2029092E104C91782 /* Documentation */, + 08FB779DFE84155DC02AAC07 /* External Frameworks and Libraries */, + BF5D041A18416BB2008C5AA9 /* Tests */, + BF5D041718416BB2008C5AA9 /* Frameworks */, + 1AB674ADFE9D54B511CA2CBB /* Products */, + EE42910C12B42FFA0088BD94 /* libsqlite3.dylib */, + ); + 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 */, + ); + name = Products; + 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 */, + ); + name = fmdb; + sourceTree = ""; + }; + 8314AF3118CD739500EC0E25 /* sample */ = { + isa = PBXGroup; + children = ( + CCC24EBE0A13E34D00A6D3E3 /* main.m */, + 32A70AAB03705E1F00C91783 /* fmdb_Prefix.pch */, + ); + name = sample; + sourceTree = ""; + }; + 832F502319EC4C4A0087DCBF /* Swift extensions */ = { + isa = PBXGroup; + children = ( + 832F502419EC4C6B0087DCBF /* FMDatabaseVariadic.swift */, + 8352D5AC1A73DCEA003A8E09 /* FMDatabaseAdditionsVariadic.swift */, + ); + name = "Swift extensions"; + sourceTree = ""; + }; + 832F502519EC4CA20087DCBF /* InMemoryOnDiskIO */ = { + isa = PBXGroup; + children = ( + CC7CE42618F5C04600938264 /* FMDatabase+InMemoryOnDiskIO.h */, + CC7CE42718F5C04600938264 /* FMDatabase+InMemoryOnDiskIO.m */, + ); + name = InMemoryOnDiskIO; + sourceTree = ""; + }; + BF5D041718416BB2008C5AA9 /* Frameworks */ = { + isa = PBXGroup; + children = ( + BF5D041818416BB2008C5AA9 /* XCTest.framework */, + 6290CBB6188FE836009790F8 /* Foundation.framework */, + 6290CBC6188FE837009790F8 /* UIKit.framework */, + ); + name = Frameworks; + sourceTree = ""; + }; + BF5D041A18416BB2008C5AA9 /* Tests */ = { + isa = PBXGroup; + children = ( + BF940F5D18417DEA0001E077 /* FMDatabaseAdditionsTests.m */, + 67CB1E2F19AD27D000A3CA7F /* FMDatabaseFTS3Tests.m */, + D4A740A11A7046330058EBEE /* FMDatabaseFTS3WithModuleNameTests.m */, + BFE55E121841C9A000CB3A63 /* FMDatabasePoolTests.m */, + BFE55E141841D38800CB3A63 /* FMDatabaseQueueTests.m */, + BF5D042018416BB2008C5AA9 /* FMDatabaseTests.m */, + BF940F5A18417D490001E077 /* FMDBTempDBTests.h */, + BF940F5B18417D490001E077 /* FMDBTempDBTests.m */, + 3354379B19E71096005661F3 /* FMResultSetTests.m */, + BF5D041B18416BB2008C5AA9 /* Supporting Files */, + ); + path = Tests; + sourceTree = ""; + }; + BF5D041B18416BB2008C5AA9 /* Supporting Files */ = { + isa = PBXGroup; + children = ( + BF5D041C18416BB2008C5AA9 /* Tests-Info.plist */, + BF5D041D18416BB2008C5AA9 /* InfoPlist.strings */, + BF5D042218416BB2008C5AA9 /* Tests-Prefix.pch */, + ); + name = "Supporting Files"; + sourceTree = ""; + }; + C6859EA2029092E104C91782 /* Documentation */ = { + isa = PBXGroup; + children = ( + C6859EA3029092ED04C91782 /* fmdb.1 */, + ); + name = Documentation; + sourceTree = ""; + }; + CC7CE42518F5C02E00938264 /* optional extras */ = { + isa = PBXGroup; + children = ( + 832F502319EC4C4A0087DCBF /* Swift extensions */, + 832F502519EC4CA20087DCBF /* InMemoryOnDiskIO */, + 6767F81519AD13C300887DBC /* fts3 */, + ); + name = "optional extras"; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXHeadersBuildPhase section */ + EE4290EB12B42F870088BD94 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + EE42910712B42FC90088BD94 /* FMDatabase.h in Headers */, + EE42910612B42FC30088BD94 /* FMDatabaseAdditions.h in Headers */, + EE42910912B42FD00088BD94 /* FMResultSet.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 */ + 6290CBB4188FE836009790F8 /* FMDB-IOS */ = { + isa = PBXNativeTarget; + buildConfigurationList = 6290CBD7188FE837009790F8 /* Build configuration list for PBXNativeTarget "FMDB-IOS" */; + buildPhases = ( + 6290CBB1188FE836009790F8 /* Sources */, + 6290CBB2188FE836009790F8 /* Frameworks */, + 6290CBB3188FE836009790F8 /* CopyFiles */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = "FMDB-IOS"; + productName = "FMDB-IOS"; + productReference = 6290CBB5188FE836009790F8 /* libFMDB-IOS.a */; + productType = "com.apple.product-type.library.static"; + }; + 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"; + }; + BF5D041518416BB2008C5AA9 /* Tests */ = { + isa = PBXNativeTarget; + buildConfigurationList = BF5D042718416BB2008C5AA9 /* Build configuration list for PBXNativeTarget "Tests" */; + buildPhases = ( + BF5D041218416BB2008C5AA9 /* Sources */, + BF5D041318416BB2008C5AA9 /* Frameworks */, + BF5D041418416BB2008C5AA9 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + BF5D042418416BB2008C5AA9 /* 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 = 0610; + TargetAttributes = { + BF5D041518416BB2008C5AA9 = { + TestTargetID = EE4290EE12B42F870088BD94; + }; + }; + }; + buildConfigurationList = 1DEB927808733DD40010E9CD /* Build configuration list for PBXProject "fmdb" */; + compatibilityVersion = "Xcode 3.2"; + developmentRegion = English; + hasScannedForEncodings = 1; + knownRegions = ( + English, + Japanese, + French, + German, + en, + ); + mainGroup = 08FB7794FE84155DC02AAC07 /* fmdb */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 8DD76F960486AA7600D96B5E /* fmdb */, + EE4290EE12B42F870088BD94 /* FMDB */, + BF5D041518416BB2008C5AA9 /* Tests */, + 6290CBB4188FE836009790F8 /* FMDB-IOS */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + BF5D041418416BB2008C5AA9 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + BF5D041F18416BB2008C5AA9 /* InfoPlist.strings in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 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; + }; + 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; + }; + BF5D041218416BB2008C5AA9 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + BFC152B118417F0D00605DF7 /* FMDatabaseAdditions.m in Sources */, + CCA66A3019C0CB1900EFDAC1 /* FMTokenizers.m in Sources */, + BF940F5C18417D490001E077 /* FMDBTempDBTests.m in Sources */, + BF940F5E18417DEA0001E077 /* FMDatabaseAdditionsTests.m in Sources */, + 3354379C19E71096005661F3 /* FMResultSetTests.m in Sources */, + BF5D042118416BB2008C5AA9 /* FMDatabaseTests.m in Sources */, + 67CB1E3019AD27D000A3CA7F /* FMDatabaseFTS3Tests.m in Sources */, + BFE55E131841C9A000CB3A63 /* FMDatabasePoolTests.m in Sources */, + BFE55E151841D38800CB3A63 /* FMDatabaseQueueTests.m in Sources */, + D4A740A21A7046330058EBEE /* FMDatabaseFTS3WithModuleNameTests.m in Sources */, + CCA66A2E19C0CB1900EFDAC1 /* FMDatabase+FTS3.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 */ + BF5D042418416BB2008C5AA9 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = EE4290EE12B42F870088BD94 /* FMDB */; + targetProxy = BF5D042318416BB2008C5AA9 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin PBXVariantGroup section */ + BF5D041D18416BB2008C5AA9 /* InfoPlist.strings */ = { + isa = PBXVariantGroup; + children = ( + BF5D041E18416BB2008C5AA9 /* en */, + ); + name = InfoPlist.strings; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 1DEB927508733DD40010E9CD /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + CLANG_ENABLE_OBJC_ARC = 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; + 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_WARN_SHADOW = YES; + INSTALL_PATH = "$(HOME)/bin"; + LIBRARY_SEARCH_PATHS = "$(LIBRARY_SEARCH_PATHS)"; + PRODUCT_NAME = fmdb; + }; + name = Debug; + }; + 1DEB927608733DD40010E9CD /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + CLANG_ENABLE_OBJC_ARC = 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; + GCC_GENERATE_DEBUGGING_SYMBOLS = NO; + GCC_MODEL_TUNING = G5; + GCC_PRECOMPILE_PREFIX_HEADER = YES; + GCC_PREFIX_HEADER = src/sample/fmdb_Prefix.pch; + GCC_WARN_SHADOW = YES; + INSTALL_PATH = "$(HOME)/bin"; + LIBRARY_SEARCH_PATHS = "$(LIBRARY_SEARCH_PATHS)"; + PRODUCT_NAME = fmdb; + }; + name = Release; + }; + 1DEB927908733DD40010E9CD /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_C_LANGUAGE_STANDARD = c99; + 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_VARIABLE = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = macosx10.9; + }; + name = Debug; + }; + 1DEB927A08733DD40010E9CD /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_C_LANGUAGE_STANDARD = c99; + 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_VARIABLE = YES; + SDKROOT = macosx10.9; + }; + 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_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_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + IPHONEOS_DEPLOYMENT_TARGET = 7.0; + OTHER_LDFLAGS = "-ObjC"; + PRODUCT_NAME = "$(TARGET_NAME)"; + 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_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_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + IPHONEOS_DEPLOYMENT_TARGET = 7.0; + OTHER_LDFLAGS = "-ObjC"; + PRODUCT_NAME = "$(TARGET_NAME)"; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + VALIDATE_PRODUCT = YES; + }; + 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_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_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_PEDANTIC = NO; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNUSED_FUNCTION = YES; + INFOPLIST_FILE = "Tests/Tests-Info.plist"; + MACOSX_DEPLOYMENT_TARGET = 10.8; + ONLY_ACTIVE_ARCH = YES; + PRODUCT_NAME = "$(TARGET_NAME)"; + SDKROOT = macosx10.9; + 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_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_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNUSED_FUNCTION = YES; + INFOPLIST_FILE = "Tests/Tests-Info.plist"; + MACOSX_DEPLOYMENT_TARGET = 10.8; + PRODUCT_NAME = "$(TARGET_NAME)"; + SDKROOT = macosx10.9; + WRAPPER_EXTENSION = xctest; + }; + name = Release; + }; + EE4290F012B42F880088BD94 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + COMBINE_HIDPI_IMAGES = YES; + COPY_PHASE_STRIP = NO; + GCC_DYNAMIC_NO_PIC = NO; + GCC_OPTIMIZATION_LEVEL = 0; + PRODUCT_NAME = FMDB; + }; + name = Debug; + }; + EE4290F112B42F880088BD94 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + COMBINE_HIDPI_IMAGES = YES; + COPY_PHASE_STRIP = YES; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + PRODUCT_NAME = 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; + }; + 6290CBD7188FE837009790F8 /* Build configuration list for PBXNativeTarget "FMDB-IOS" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 6290CBD3188FE837009790F8 /* Debug */, + 6290CBD4188FE837009790F8 /* 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 */; +} diff --git a/Frameworks/RSDatabase/FMDB/fmdb-master/fmdb.xcodeproj/xcshareddata/xcschemes/Tests.xcscheme b/Frameworks/RSDatabase/FMDB/fmdb-master/fmdb.xcodeproj/xcshareddata/xcschemes/Tests.xcscheme new file mode 100755 index 000000000..23ed8cfa0 --- /dev/null +++ b/Frameworks/RSDatabase/FMDB/fmdb-master/fmdb.xcodeproj/xcshareddata/xcschemes/Tests.xcscheme @@ -0,0 +1,96 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Frameworks/RSDatabase/FMDB/fmdb-master/src/extra/InMemoryOnDiskIO/FMDatabase+InMemoryOnDiskIO.h b/Frameworks/RSDatabase/FMDB/fmdb-master/src/extra/InMemoryOnDiskIO/FMDatabase+InMemoryOnDiskIO.h new file mode 100755 index 000000000..84a87c07c --- /dev/null +++ b/Frameworks/RSDatabase/FMDB/fmdb-master/src/extra/InMemoryOnDiskIO/FMDatabase+InMemoryOnDiskIO.h @@ -0,0 +1,26 @@ +// +// 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. +// +// http://www.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 diff --git a/Frameworks/RSDatabase/FMDB/fmdb-master/src/extra/InMemoryOnDiskIO/FMDatabase+InMemoryOnDiskIO.m b/Frameworks/RSDatabase/FMDB/fmdb-master/src/extra/InMemoryOnDiskIO/FMDatabase+InMemoryOnDiskIO.m new file mode 100755 index 000000000..8966cc7a2 --- /dev/null +++ b/Frameworks/RSDatabase/FMDB/fmdb-master/src/extra/InMemoryOnDiskIO/FMDatabase+InMemoryOnDiskIO.m @@ -0,0 +1,96 @@ +#import "FMDatabase+InMemoryOnDiskIO.h" + +// http://www.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->_db == nil ) + { + NSLog(@"Invalid database connection." ); + return NO; + } + + return ( SQLITE_OK == loadOrSaveDb( self->_db, [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->_db == nil ) + { + NSLog(@"Invalid database connection." ); + return NO; + } + + // save the in-memory representation + return ( SQLITE_OK == loadOrSaveDb( self->_db, [filePath fileSystemRepresentation], true ) ); +} + +@end diff --git a/Frameworks/RSDatabase/FMDB/fmdb-master/src/extra/Swift extensions/FMDatabaseAdditionsVariadic.swift b/Frameworks/RSDatabase/FMDB/fmdb-master/src/extra/Swift extensions/FMDatabaseAdditionsVariadic.swift new file mode 100755 index 000000000..ebcdf9c56 --- /dev/null +++ b/Frameworks/RSDatabase/FMDB/fmdb-master/src/extra/Swift extensions/FMDatabaseAdditionsVariadic.swift @@ -0,0 +1,117 @@ +// +// FMDatabaseAdditionsVariadic.swift +// FMDB +// + +import Foundation + +extension FMDatabase { + + /// Private generic function used for the variadic renditions of the FMDatabaseAdditions methods + /// + /// :param: sql The SQL statement to be used. + /// :param: values The NSArray of the arguments to be bound to the ? placeholders in the SQL. + /// :param: completionHandler The closure to be used to call the appropriate FMDatabase method to return the desired value. + /// + /// :returns: This returns the T value if value is found. Returns nil if column is NULL or upon error. + + private func valueForQuery(sql: String, values: [AnyObject]?, completionHandler:(FMResultSet)->(T!)) -> T! { + var result: T! + + if let rs = executeQuery(sql, withArgumentsInArray: values) { + if rs.next() { + let obj: AnyObject! = rs.objectForColumnIndex(0) + if !(obj is NSNull) { + result = completionHandler(rs) + } + } + rs.close() + } + + return result + } + + /// This is a rendition of stringForQuery that handles Swift variadic parameters + /// for the values to be bound to the ? placeholders in the SQL. + /// + /// :param: sql The SQL statement to be used. + /// :param: values The values to be bound to the ? placeholders + /// + /// :returns: This returns string value if value is found. Returns nil if column is NULL or upon error. + + func stringForQuery(sql: String, _ values: AnyObject...) -> String! { + return valueForQuery(sql, values: values) { $0.stringForColumnIndex(0) } + } + + /// This is a rendition of intForQuery that handles Swift variadic parameters + /// for the values to be bound to the ? placeholders in the SQL. + /// + /// :param: sql The SQL statement to be used. + /// :param: values The values to be bound to the ? placeholders + /// + /// :returns: This returns integer value if value is found. Returns nil if column is NULL or upon error. + + func intForQuery(sql: String, _ values: AnyObject...) -> Int32! { + return valueForQuery(sql, values: values) { $0.intForColumnIndex(0) } + } + + /// This is a rendition of longForQuery that handles Swift variadic parameters + /// for the values to be bound to the ? placeholders in the SQL. + /// + /// :param: sql The SQL statement to be used. + /// :param: values The values to be bound to the ? placeholders + /// + /// :returns: This returns long value if value is found. Returns nil if column is NULL or upon error. + + func longForQuery(sql: String, _ values: AnyObject...) -> Int! { + return valueForQuery(sql, values: values) { $0.longForColumnIndex(0) } + } + + /// This is a rendition of boolForQuery that handles Swift variadic parameters + /// for the values to be bound to the ? placeholders in the SQL. + /// + /// :param: sql The SQL statement to be used. + /// :param: values The values to be bound to the ? placeholders + /// + /// :returns: This returns Bool value if value is found. Returns nil if column is NULL or upon error. + + func boolForQuery(sql: String, _ values: AnyObject...) -> Bool! { + return valueForQuery(sql, values: values) { $0.boolForColumnIndex(0) } + } + + /// This is a rendition of doubleForQuery that handles Swift variadic parameters + /// for the values to be bound to the ? placeholders in the SQL. + /// + /// :param: sql The SQL statement to be used. + /// :param: values The values to be bound to the ? placeholders + /// + /// :returns: This returns Double value if value is found. Returns nil if column is NULL or upon error. + + func doubleForQuery(sql: String, _ values: AnyObject...) -> Double! { + return valueForQuery(sql, values: values) { $0.doubleForColumnIndex(0) } + } + + /// This is a rendition of dateForQuery that handles Swift variadic parameters + /// for the values to be bound to the ? placeholders in the SQL. + /// + /// :param: sql The SQL statement to be used. + /// :param: values The values to be bound to the ? placeholders + /// + /// :returns: This returns NSDate value if value is found. Returns nil if column is NULL or upon error. + + func dateForQuery(sql: String, _ values: AnyObject...) -> NSDate! { + return valueForQuery(sql, values: values) { $0.dateForColumnIndex(0) } + } + + /// This is a rendition of dataForQuery that handles Swift variadic parameters + /// for the values to be bound to the ? placeholders in the SQL. + /// + /// :param: sql The SQL statement to be used. + /// :param: values The values to be bound to the ? placeholders + /// + /// :returns: This returns NSData value if value is found. Returns nil if column is NULL or upon error. + + func dataForQuery(sql: String, _ values: AnyObject...) -> NSData! { + return valueForQuery(sql, values: values) { $0.dataForColumnIndex(0) } + } +} \ No newline at end of file diff --git a/Frameworks/RSDatabase/FMDB/fmdb-master/src/extra/Swift extensions/FMDatabaseVariadic.swift b/Frameworks/RSDatabase/FMDB/fmdb-master/src/extra/Swift extensions/FMDatabaseVariadic.swift new file mode 100755 index 000000000..cc6ed06ed --- /dev/null +++ b/Frameworks/RSDatabase/FMDB/fmdb-master/src/extra/Swift extensions/FMDatabaseVariadic.swift @@ -0,0 +1,36 @@ +// +// FMDatabaseVariadic.swift +// FMDB +// + + +// This extension inspired by http://stackoverflow.com/a/24187932/1271826 + +import Foundation + +extension FMDatabase { + + /// This is a rendition of executeQuery that handles Swift variadic parameters + /// for the values to be bound to the ? placeholders in the SQL. + /// + /// :param: sql The SQL statement to be used. + /// :param: values The values to be bound to the ? placeholders + /// + /// :returns: This returns FMResultSet if successful. Returns nil upon error. + + func executeQuery(sql:String, _ values: AnyObject...) -> FMResultSet? { + return executeQuery(sql, withArgumentsInArray: values as [AnyObject]); + } + + /// This is a rendition of executeUpdate that handles Swift variadic parameters + /// for the values to be bound to the ? placeholders in the SQL. + /// + /// :param: sql The SQL statement to be used. + /// :param: values The values to be bound to the ? placeholders + /// + /// :returns: This returns true if successful. Returns false upon error. + + func executeUpdate(sql:String, _ values: AnyObject...) -> Bool { + return executeUpdate(sql, withArgumentsInArray: values as [AnyObject]); + } +} \ No newline at end of file diff --git a/Frameworks/RSDatabase/FMDB/fmdb-master/src/extra/fts3/FMDatabase+FTS3.h b/Frameworks/RSDatabase/FMDB/fmdb-master/src/extra/fts3/FMDatabase+FTS3.h new file mode 100755 index 000000000..97c9f4a07 --- /dev/null +++ b/Frameworks/RSDatabase/FMDB/fmdb-master/src/extra/fts3/FMDatabase+FTS3.h @@ -0,0 +1,112 @@ +// +// FMDatabase+FTS3.h +// fmdb +// +// Created by Andrew on 3/27/14. +// Copyright (c) 2014 Andrew Goodale. All rights reserved. +// + +#import "FMDatabase.h" + +/** + 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 `fts3_tokenizer()` function on this database, installing tokenizer module with the 'fmdb' name. + */ +- (BOOL)installTokenizerModule; + +/** + Calls the `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 offset 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 */ +} 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 `matchRange` is in UTF-8 byte positions, so it must be + modified to use with `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 `offsets()` function. Make sure the column index corresponds + to the column index in the SQL query. + + @param columnIdx Zero-based index for column. + + @return `FMTextOffsets` structure. + */ +- (FMTextOffsets *)offsetsForColumnIndex:(int)columnIdx; + +@end diff --git a/Frameworks/RSDatabase/FMDB/fmdb-master/src/extra/fts3/FMDatabase+FTS3.m b/Frameworks/RSDatabase/FMDB/fmdb-master/src/extra/fts3/FMDatabase+FTS3.m new file mode 100755 index 000000000..9755b558c --- /dev/null +++ b/Frameworks/RSDatabase/FMDB/fmdb-master/src/extra/fts3/FMDatabase+FTS3.m @@ -0,0 +1,283 @@ +// +// 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" + +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'; + + [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. + CFIndex startOffset, endOffset, newBytesUsed; + CFRange rangeToStartToken = CFRangeMake(0, cursor->currentRange.location); + CFRange newTokenRange = CFRangeMake(0, CFStringGetLength(cursor->tokenString)); + + // 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, &startOffset); + + // and how many UTF-8 bytes there are within the token in the original string + CFStringGetBytes(cursor->inputString, cursor->currentRange, kCFStringEncodingUTF8, '?', false, + NULL, 0, &endOffset); + + // Determine how many bytes the new token string uses + CFStringGetBytes(cursor->tokenString, newTokenRange, kCFStringEncodingUTF8, '?', false, + cursor->outputBuf, sizeof(cursor->outputBuf), &newBytesUsed); + + *pzToken = (char *) cursor->outputBuf; + *pnBytes = (int) newBytesUsed; + *piStartOffset = (int) startOffset; + *piEndOffset = (int) (startOffset + endOffset); + *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([_statement statement], columnIdx); + + return [[FMTextOffsets alloc] initWithDBOffsets:rawOffsets]; +} + +@end diff --git a/Frameworks/RSDatabase/FMDB/fmdb-master/src/extra/fts3/FMTokenizers.h b/Frameworks/RSDatabase/FMDB/fmdb-master/src/extra/fts3/FMTokenizers.h new file mode 100755 index 000000000..59bce9ca0 --- /dev/null +++ b/Frameworks/RSDatabase/FMDB/fmdb-master/src/extra/fts3/FMTokenizers.h @@ -0,0 +1,45 @@ +// +// FMTokenizers.h +// fmdb +// +// Created by Andrew on 4/9/14. +// Copyright (c) 2014 Andrew Goodale. All rights reserved. +// + +#import +#import "FMDatabase+FTS3.h" + +/** + 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. + The locale can be `NULL`, in which case the current locale will be used. + */ +- (instancetype)initWithLocale:(CFLocaleRef)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. + */ ++ (instancetype)tokenizerWithFileURL:(NSURL *)wordFileURL baseTokenizer:(id)tokenizer error:(NSError **)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. + */ +- (instancetype)initWithWords:(NSSet *)words baseTokenizer:(id)tokenizer; + +@end diff --git a/Frameworks/RSDatabase/FMDB/fmdb-master/src/extra/fts3/FMTokenizers.m b/Frameworks/RSDatabase/FMDB/fmdb-master/src/extra/fts3/FMTokenizers.m new file mode 100755 index 000000000..ab9339d28 --- /dev/null +++ b/Frameworks/RSDatabase/FMDB/fmdb-master/src/extra/fts3/FMTokenizers.m @@ -0,0 +1,135 @@ +// +// 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 \ No newline at end of file diff --git a/Frameworks/RSDatabase/FMDB/fmdb-master/src/extra/fts3/fts3_tokenizer.h b/Frameworks/RSDatabase/FMDB/fmdb-master/src/extra/fts3/fts3_tokenizer.h new file mode 100755 index 000000000..c91c7ed79 --- /dev/null +++ b/Frameworks/RSDatabase/FMDB/fmdb-master/src/extra/fts3/fts3_tokenizer.h @@ -0,0 +1,161 @@ +/* +** 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. +*/ +#include "sqlite3.h" + +/* +** 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_ */ diff --git a/Frameworks/RSDatabase/FMDB/fmdb-master/src/fmdb/FMDB.h b/Frameworks/RSDatabase/FMDB/fmdb-master/src/fmdb/FMDB.h new file mode 100755 index 000000000..39e2f4312 --- /dev/null +++ b/Frameworks/RSDatabase/FMDB/fmdb-master/src/fmdb/FMDB.h @@ -0,0 +1,5 @@ +#import "FMDatabase.h" +#import "FMResultSet.h" +#import "FMDatabaseAdditions.h" +#import "FMDatabaseQueue.h" +#import "FMDatabasePool.h" diff --git a/Frameworks/RSDatabase/FMDB/fmdb-master/src/fmdb/FMDatabase.h b/Frameworks/RSDatabase/FMDB/fmdb-master/src/fmdb/FMDatabase.h new file mode 100755 index 000000000..29faddb17 --- /dev/null +++ b/Frameworks/RSDatabase/FMDB/fmdb-master/src/fmdb/FMDatabase.h @@ -0,0 +1,1084 @@ +#import +//#import "sqlite3.h" +#import "FMResultSet.h" +//#import "FMDatabasePool.h" + + +#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 + + +typedef int(^FMDBExecuteStatementsCallbackBlock)(NSDictionary *resultsDictionary); + + +/** A SQLite ([http://sqlite.org/](http://sqlite.org/)) Objective-C wrapper. + + ### Usage + The three main classes in FMDB are: + + - `FMDatabase` - Represents a single SQLite database. Used for executing SQL statements. + - `` - Represents the results of executing a query on an `FMDatabase`. + - `` - If you want to perform queries and updates on multiple threads, you'll want to use this class. + + ### See also + + - `` - A pool of `FMDatabase` objects. + - `` - A wrapper for `sqlite_stmt`. + + ### External links + + - [FMDB on GitHub](https://github.com/ccgus/fmdb) including introductory documentation + - [SQLite web site](http://sqlite.org/) + - [FMDB mailing list](http://groups.google.com/group/fmdb) + - [SQLite FAQ](http://www.sqlite.org/faq.html) + + @warning Do not instantiate a single `FMDatabase` object and use it across multiple threads. Instead, use ``. + + */ + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wobjc-interface-ivars" + + +@interface FMDatabase : NSObject { + + NSString* _databasePath; + BOOL _logsErrors; + BOOL _crashOnErrors; + BOOL _traceExecution; + BOOL _checkedOut; + BOOL _shouldCacheStatements; + BOOL _isExecutingStatement; + BOOL _inTransaction; + NSTimeInterval _maxBusyRetryTimeInterval; + NSTimeInterval _startBusyRetryTime; + + NSMutableDictionary *_cachedStatements; + NSMutableSet *_openResultSets; + NSMutableSet *_openFunctions; + + NSDateFormatter *_dateFormat; +} + +///----------------- +/// @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) NSMutableDictionary *cachedStatements; + +///--------------------- +/// @name Initialization +///--------------------- + +/** Create a `FMDatabase` object. + + 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 with the `FMDatabase` connection is closed. + 3. `nil`. An in-memory database is created. This database will be destroyed with the `FMDatabase` connection is closed. + + For example, to create/open a database in your Mac OS X `tmp` folder: + + FMDatabase *db = [FMDatabase databaseWithPath:@"/tmp/tmp.db"]; + + Or, in iOS, you might open a database in the app's `Documents` directory: + + NSString *docsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0]; + NSString *dbPath = [docsPath stringByAppendingPathComponent:@"test.db"]; + FMDatabase *db = [FMDatabase databaseWithPath:dbPath]; + + (For more information on temporary and in-memory databases, read the sqlite documentation on the subject: [http://www.sqlite.org/inmemorydb.html](http://www.sqlite.org/inmemorydb.html)) + + @param inPath Path of database file + + @return `FMDatabase` object if successful; `nil` if failure. + + */ + ++ (instancetype)databaseWithPath:(NSString*)inPath; + +/** Initialize a `FMDatabase` object. + + 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 with the `FMDatabase` connection is closed. + 3. `nil`. An in-memory database is created. This database will be destroyed with the `FMDatabase` connection is closed. + + For example, to create/open a database in your Mac OS X `tmp` folder: + + FMDatabase *db = [FMDatabase databaseWithPath:@"/tmp/tmp.db"]; + + Or, in iOS, you might open a database in the app's `Documents` directory: + + NSString *docsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0]; + NSString *dbPath = [docsPath stringByAppendingPathComponent:@"test.db"]; + FMDatabase *db = [FMDatabase databaseWithPath:dbPath]; + + (For more information on temporary and in-memory databases, read the sqlite documentation on the subject: [http://www.sqlite.org/inmemorydb.html](http://www.sqlite.org/inmemorydb.html)) + + @param inPath Path of database file + + @return `FMDatabase` object if successful; `nil` if failure. + + */ + +- (instancetype)initWithPath:(NSString*)inPath; + + +///----------------------------------- +/// @name Opening and closing database +///----------------------------------- + +/** Opening a new database connection + + The database is opened for reading and writing, and is created if it does not already exist. + + @return `YES` if successful, `NO` on error. + + @see [sqlite3_open()](http://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 `SQLITE_OPEN_NOMUTEX`, `SQLITE_OPEN_FULLMUTEX`, `SQLITE_OPEN_SHAREDCACHE`, `SQLITE_OPEN_PRIVATECACHE`, and/or `SQLITE_OPEN_URI` flags: + + `SQLITE_OPEN_READONLY` + + The database is opened in read-only mode. If the database does not already exist, an error is returned. + + `SQLITE_OPEN_READWRITE` + + 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. + + `SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE` + + The database is opened for reading and writing, and is created if it does not already exist. This is the behavior that is always used for `open` method. + + If vfs is given the value is passed to the vfs parameter of sqlite3_open_v2. + + @return `YES` if successful, `NO` on error. + + @see [sqlite3_open_v2()](http://sqlite.org/c3ref/open.html) + @see open + @see close + */ + +#if SQLITE_VERSION_NUMBER >= 3005000 +- (BOOL)openWithFlags:(int)flags; +- (BOOL)openWithFlags:(int)flags vfs:(NSString *)vfsName; +#endif + +/** Closing a database connection + + @return `YES` if success, `NO` on error. + + @see [sqlite3_close()](http://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 SELECT statement and confirm that it succeeds. + + @return `YES` if everything succeeds, `NO` on failure. + */ + +- (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 `UPDATE`, `INSERT`, or `DELETE`. This method employs [`sqlite3_prepare_v2`](http://sqlite.org/c3ref/prepare.html), [`sqlite3_bind`](http://sqlite.org/c3ref/bind_blob.html) to bind values to `?` placeholders in the SQL with the optional list of parameters, and [`sqlite_step`](http://sqlite.org/c3ref/step.html) to perform the update. + + The optional values provided to this method should be objects (e.g. `NSString`, `NSNumber`, `NSNull`, `NSDate`, and `NSData` objects), not fundamental data types (e.g. `int`, `long`, `NSInteger`, etc.). This method automatically handles the aforementioned object types, and all other object types will be interpreted as text values using the object's `description` method. + + @param sql The SQL to be performed, with optional `?` placeholders. + + @param outErr A reference to the `NSError` pointer to be updated with an auto released `NSError` object if an error if an error occurs. If `nil`, no `NSError` object will be returned. + + @param ... Optional parameters to bind to `?` placeholders in the SQL statement. These should be Objective-C objects (e.g. `NSString`, `NSNumber`, etc.), not fundamental C data types (e.g. `int`, `char *`, etc.). + + @return `YES` upon success; `NO` upon failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. + + @see lastError + @see lastErrorCode + @see lastErrorMessage + @see [`sqlite3_bind`](http://sqlite.org/c3ref/bind_blob.html) + */ + +- (BOOL)executeUpdate:(NSString*)sql withErrorAndBindings:(NSError**)outErr, ...; + +/** Execute single update statement + + @see executeUpdate:withErrorAndBindings: + + @warning **Deprecated**: Please use `` instead. + */ + +- (BOOL)update:(NSString*)sql withErrorAndBindings:(NSError**)outErr, ... __attribute__ ((deprecated)); + +/** Execute single update statement + + This method executes a single SQL update statement (i.e. any SQL that does not return results, such as `UPDATE`, `INSERT`, or `DELETE`. This method employs [`sqlite3_prepare_v2`](http://sqlite.org/c3ref/prepare.html), [`sqlite3_bind`](http://sqlite.org/c3ref/bind_blob.html) to bind values to `?` placeholders in the SQL with the optional list of parameters, and [`sqlite_step`](http://sqlite.org/c3ref/step.html) to perform the update. + + The optional values provided to this method should be objects (e.g. `NSString`, `NSNumber`, `NSNull`, `NSDate`, and `NSData` objects), not fundamental data types (e.g. `int`, `long`, `NSInteger`, etc.). This method automatically handles the aforementioned object types, and all other object types will be interpreted as text values using the object's `description` method. + + @param sql The SQL to be performed, with optional `?` placeholders. + + @param ... Optional parameters to bind to `?` placeholders in the SQL statement. These should be Objective-C objects (e.g. `NSString`, `NSNumber`, etc.), not fundamental C data types (e.g. `int`, `char *`, etc.). + + @return `YES` upon success; `NO` upon failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. + + @see lastError + @see lastErrorCode + @see lastErrorMessage + @see [`sqlite3_bind`](http://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 `stringWithFormat` to manually build SQL statements, which can be problematic if the values happened to include any characters that needed to be quoted. + + @note If you want to use this from Swift, please note that you must include `FMDatabaseVariadic.swift` in your project. Without that, you cannot use this method directly, and instead have to use methods such as ``. + */ + +- (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 `UPDATE`, `INSERT`, or `DELETE`. This method employs [`sqlite3_prepare_v2`](http://sqlite.org/c3ref/prepare.html) and [`sqlite_step`](http://sqlite.org/c3ref/step.html) to perform the update. Unlike the other `executeUpdate` methods, this uses printf-style formatters (e.g. `%s`, `%d`, etc.) to build the SQL. Do not use `?` placeholders in the SQL if you use this method. + + @param format The SQL to be performed, with `printf`-style escape sequences. + + @param ... Optional parameters to bind to use in conjunction with the `printf`-style escape sequences in the SQL statement. + + @return `YES` upon success; `NO` upon failure. If failed, you can call ``, ``, or `` 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 + + [db executeUpdateWithFormat:@"INSERT INTO test (name) VALUES (%@)", @"Gus"]; + + is actually replacing the `%@` with `?` placeholder, and then performing something equivalent to `` + + [db executeUpdate:@"INSERT INTO test (name) VALUES (?)", @"Gus"]; + + There are two reasons why this distinction is important. First, the printf-style escape sequences can only be used where it is permissible to use a SQLite `?` placeholder. You can use it only for values in SQL statements, but not for table names or column names or any other non-value context. This method also cannot be used in conjunction with `pragma` statements and the like. Second, note the lack of quotation marks in the SQL. The `VALUES` clause was _not_ `VALUES ('%@')` (like you might have to do if you built a SQL statement using `NSString` method `stringWithFormat`), but rather simply `VALUES (%@)`. + */ + +- (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 `UPDATE`, `INSERT`, or `DELETE`. This method employs [`sqlite3_prepare_v2`](http://sqlite.org/c3ref/prepare.html) and [`sqlite3_bind`](http://sqlite.org/c3ref/bind_blob.html) binding any `?` placeholders in the SQL with the optional list of parameters. + + The optional values provided to this method should be objects (e.g. `NSString`, `NSNumber`, `NSNull`, `NSDate`, and `NSData` objects), not fundamental data types (e.g. `int`, `long`, `NSInteger`, etc.). This method automatically handles the aforementioned object types, and all other object types will be interpreted as text values using the object's `description` method. + + @param sql The SQL to be performed, with optional `?` placeholders. + + @param arguments A `NSArray` of objects to be used when binding values to the `?` placeholders in the SQL statement. + + @return `YES` upon success; `NO` upon failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. + + @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 `UPDATE`, `INSERT`, or `DELETE`. This method employs [`sqlite3_prepare_v2`](http://sqlite.org/c3ref/prepare.html) and [`sqlite_step`](http://sqlite.org/c3ref/step.html) to perform the update. Unlike the other `executeUpdate` methods, this uses printf-style formatters (e.g. `%s`, `%d`, etc.) to build the SQL. + + The optional values provided to this method should be objects (e.g. `NSString`, `NSNumber`, `NSNull`, `NSDate`, and `NSData` objects), not fundamental data types (e.g. `int`, `long`, `NSInteger`, etc.). This method automatically handles the aforementioned object types, and all other object types will be interpreted as text values using the object's `description` method. + + @param sql The SQL to be performed, with optional `?` placeholders. + + @param arguments A `NSDictionary` of objects keyed by column names that will be used when binding values to the `?` placeholders in the SQL statement. + + @return `YES` upon success; `NO` upon failure. If failed, you can call ``, ``, or `` 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 `UPDATE`, `INSERT`, or `DELETE`. This method employs [`sqlite3_prepare_v2`](http://sqlite.org/c3ref/prepare.html) and [`sqlite_step`](http://sqlite.org/c3ref/step.html) to perform the update. Unlike the other `executeUpdate` methods, this uses printf-style formatters (e.g. `%s`, `%d`, etc.) to build the SQL. + + The optional values provided to this method should be objects (e.g. `NSString`, `NSNumber`, `NSNull`, `NSDate`, and `NSData` objects), not fundamental data types (e.g. `int`, `long`, `NSInteger`, etc.). This method automatically handles the aforementioned object types, and all other object types will be interpreted as text values using the object's `description` method. + + @param sql The SQL to be performed, with optional `?` placeholders. + + @param args A `va_list` of arguments. + + @return `YES` upon success; `NO` upon failure. If failed, you can call ``, ``, or `` 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 `sqlite3_exec`. + + @param sql The SQL to be performed + + @return `YES` upon success; `NO` upon failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. + + @see executeStatements:withResultBlock: + @see [sqlite3_exec()](http://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 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 `nil` if you don't care to receive any results. + + @return `YES` upon success; `NO` upon failure. If failed, you can call ``, + ``, or `` for diagnostic information regarding the failure. + + @see executeStatements: + @see [sqlite3_exec()](http://sqlite.org/c3ref/exec.html) + + */ + +- (BOOL)executeStatements:(NSString *)sql withResultBlock:(FMDBExecuteStatementsCallbackBlock)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 `INSERT` into the database from the database connection in the first argument. As of SQLite version 3.7.7, this routines records the last insert rowid of both ordinary tables and virtual tables. If no successful `INSERT`s have ever occurred on that database connection, zero is returned. + + @return The rowid of the last inserted row. + + @see [sqlite3_last_insert_rowid()](http://sqlite.org/c3ref/last_insert_rowid.html) + + */ + +- (long long int)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 INSERT, UPDATE, or DELETE statement are counted. + + @return The number of rows changed by prior SQL statement. + + @see [sqlite3_changes()](http://sqlite.org/c3ref/changes.html) + + */ + +- (int)changes; + + +///------------------------- +/// @name Retrieving results +///------------------------- + +/** Execute select statement + + Executing queries returns an `` object if successful, and `nil` upon failure. Like executing updates, there is a variant that accepts an `NSError **` parameter. Otherwise you should use the `` and `` methods to determine why a query failed. + + 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`](http://sqlite.org/c3ref/bind_blob.html) for any optional value parameters. This properly escapes any characters that need escape sequences (e.g. quotation marks), which eliminates simple SQL errors as well as protects against SQL injection attacks. This method natively handles `NSString`, `NSNumber`, `NSNull`, `NSDate`, and `NSData` objects. All other object types will be interpreted as text values using the object's `description` method. + + @param sql The SELECT statement to be performed, with optional `?` placeholders. + + @param ... Optional parameters to bind to `?` placeholders in the SQL statement. These should be Objective-C objects (e.g. `NSString`, `NSNumber`, etc.), not fundamental C data types (e.g. `int`, `char *`, etc.). + + @return A `` for the result set upon success; `nil` upon failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. + + @see FMResultSet + @see [`FMResultSet next`](<[FMResultSet next]>) + @see [`sqlite3_bind`](http://sqlite.org/c3ref/bind_blob.html) + + @note If you want to use this from Swift, please note that you must include `FMDatabaseVariadic.swift` in your project. Without that, you cannot use this method directly, and instead have to use methods such as ``. + */ + +- (FMResultSet *)executeQuery:(NSString*)sql, ...; + +/** Execute select statement + + Executing queries returns an `` object if successful, and `nil` upon failure. Like executing updates, there is a variant that accepts an `NSError **` parameter. Otherwise you should use the `` and `` methods to determine why a query failed. + + 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. + + @param ... Optional parameters to bind to use in conjunction with the `printf`-style escape sequences in the SQL statement. + + @return A `` for the result set upon success; `nil` upon failure. If failed, you can call ``, ``, or `` 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 + + [db executeQueryWithFormat:@"SELECT * FROM test WHERE name=%@", @"Gus"]; + + is actually replacing the `%@` with `?` placeholder, and then performing something equivalent to `` + + [db executeQuery:@"SELECT * FROM test WHERE name=?", @"Gus"]; + + There are two reasons why this distinction is important. First, the printf-style escape sequences can only be used where it is permissible to use a SQLite `?` placeholder. You can use it only for values in SQL statements, but not for table names or column names or any other non-value context. This method also cannot be used in conjunction with `pragma` statements and the like. Second, note the lack of quotation marks in the SQL. The `WHERE` clause was _not_ `WHERE name='%@'` (like you might have to do if you built a SQL statement using `NSString` method `stringWithFormat`), but rather simply `WHERE name=%@`. + + */ + +- (FMResultSet *)executeQueryWithFormat:(NSString*)format, ... NS_FORMAT_FUNCTION(1,2); + +/** Execute select statement + + Executing queries returns an `` object if successful, and `nil` upon failure. Like executing updates, there is a variant that accepts an `NSError **` parameter. Otherwise you should use the `` and `` methods to determine why a query failed. + + 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 `NSArray` of objects to be used when binding values to the `?` placeholders in the SQL statement. + + @return A `` for the result set upon success; `nil` upon failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. + + @see FMResultSet + @see [`FMResultSet next`](<[FMResultSet next]>) + */ + +- (FMResultSet *)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray *)arguments; + +/** Execute select statement + + Executing queries returns an `` object if successful, and `nil` upon failure. Like executing updates, there is a variant that accepts an `NSError **` parameter. Otherwise you should use the `` and `` methods to determine why a query failed. + + 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 `NSDictionary` of objects keyed by column names that will be used when binding values to the `?` placeholders in the SQL statement. + + @return A `` for the result set upon success; `nil` upon failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. + + @see FMResultSet + @see [`FMResultSet next`](<[FMResultSet next]>) + */ + +- (FMResultSet *)executeQuery:(NSString *)sql withParameterDictionary:(NSDictionary *)arguments; + + +// Documentation forthcoming. +- (FMResultSet *)executeQuery:(NSString*)sql withVAList: (va_list)args; + +///------------------- +/// @name Transactions +///------------------- + +/** Begin a transaction + + @return `YES` on success; `NO` on failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. + + @see commit + @see rollback + @see beginDeferredTransaction + @see inTransaction + */ + +- (BOOL)beginTransaction; + +/** Begin a deferred transaction + + @return `YES` on success; `NO` on failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. + + @see commit + @see rollback + @see beginTransaction + @see inTransaction + */ + +- (BOOL)beginDeferredTransaction; + +/** Commit a transaction + + Commit a transaction that was initiated with either `` or with ``. + + @return `YES` on success; `NO` on failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. + + @see beginTransaction + @see beginDeferredTransaction + @see rollback + @see inTransaction + */ + +- (BOOL)commit; + +/** Rollback a transaction + + Rollback a transaction that was initiated with either `` or with ``. + + @return `YES` on success; `NO` on failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. + + @see beginTransaction + @see beginDeferredTransaction + @see commit + @see inTransaction + */ + +- (BOOL)rollback; + +/** Identify whether currently in a transaction or not + + @return `YES` if currently within transaction; `NO` if not. + + @see beginTransaction + @see beginDeferredTransaction + @see commit + @see rollback + */ + +- (BOOL)inTransaction; + + +///---------------------------------------- +/// @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 `YES` if there are open result sets; `NO` if not. + */ + +- (BOOL)hasOpenResultSets; + +/** Return whether should cache statements or not + + @return `YES` if should cache statements; `NO` if not. + */ + +- (BOOL)shouldCacheStatements; + +/** Set whether should cache statements or not + + @param value `YES` if should cache statements; `NO` if not. + */ + +- (void)setShouldCacheStatements:(BOOL)value; + + +///------------------------- +/// @name Encryption methods +///------------------------- + +/** Set encryption key. + + @param key The key to be used. + + @return `YES` if success, `NO` on error. + + @see http://www.sqlite-encrypt.com/develop-guide.htm + + @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 `YES` if success, `NO` on error. + + @see http://www.sqlite-encrypt.com/develop-guide.htm + + @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 `NSData` to be used. + + @return `YES` if success, `NO` on error. + + @see http://www.sqlite-encrypt.com/develop-guide.htm + + @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 `NSData` to be used. + + @return `YES` if success, `NO` on error. + + @see http://www.sqlite-encrypt.com/develop-guide.htm + + @warning You need to have purchased the sqlite encryption extensions for this method to work. + */ + +- (BOOL)rekeyWithData:(NSData *)keyData; + + +///------------------------------ +/// @name General inquiry methods +///------------------------------ + +/** The path of the database file + + @return path of database. + + */ + +- (NSString *)databasePath; + +/** The underlying SQLite handle + + @return The `sqlite3` pointer. + + */ + +- (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 `NSString` of the last error message. + + @see [sqlite3_errmsg()](http://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()](http://sqlite.org/c3ref/errcode.html) + @see lastErrorMessage + @see lastError + + */ + +- (int)lastErrorCode; + +/** Had error + + @return `YES` if there was an error, `NO` if no error. + + @see lastError + @see lastErrorCode + @see lastErrorMessage + + */ + +- (BOOL)hadError; + +/** Last error + + @return `NSError` representing the last error. + + @see lastErrorCode + @see lastErrorMessage + + */ + +- (NSError*)lastError; + + +// description forthcoming +- (void)setMaxBusyRetryTimeInterval:(NSTimeInterval)timeoutInSeconds; +- (NSTimeInterval)maxBusyRetryTimeInterval; + + +#if SQLITE_VERSION_NUMBER >= 3007000 + +///------------------ +/// @name Save points +///------------------ + +/** Start save point + + @param name Name of save point. + + @param outErr A `NSError` object to receive any error object (if any). + + @return `YES` on success; `NO` on failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. + + @see releaseSavePointWithName:error: + @see rollbackToSavePointWithName:error: + */ + +- (BOOL)startSavePointWithName:(NSString*)name error:(NSError**)outErr; + +/** Release save point + + @param name Name of save point. + + @param outErr A `NSError` object to receive any error object (if any). + + @return `YES` on success; `NO` on failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. + + @see startSavePointWithName:error: + @see rollbackToSavePointWithName:error: + + */ + +- (BOOL)releaseSavePointWithName:(NSString*)name error:(NSError**)outErr; + +/** Roll back to save point + + @param name Name of save point. + @param outErr A `NSError` object to receive any error object (if any). + + @return `YES` on success; `NO` on failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. + + @see startSavePointWithName:error: + @see releaseSavePointWithName:error: + + */ + +- (BOOL)rollbackToSavePointWithName:(NSString*)name error:(NSError**)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 `nil`. + + @see startSavePointWithName:error: + @see releaseSavePointWithName:error: + @see rollbackToSavePointWithName:error: + + */ + +- (NSError*)inSavePoint:(void (^)(BOOL *rollback))block; + +#endif + +///---------------------------- +/// @name SQLite library status +///---------------------------- + +/** Test to see if the library is threadsafe + + @return `NO` if and only if SQLite was compiled with mutexing code omitted due to the SQLITE_THREADSAFE compile-time option being set to 0. + + @see [sqlite3_threadsafe()](http://sqlite.org/c3ref/threadsafe.html) + */ + ++ (BOOL)isSQLiteThreadSafe; + +/** Run-time library version numbers + + @return The sqlite library version string. + + @see [sqlite3_libversion()](http://sqlite.org/c3ref/libversion.html) + */ + ++ (NSString*)sqliteLibVersion; + + ++ (NSString*)FMDBUserVersion; + ++ (SInt32)FMDBVersion; + + +///------------------------ +/// @name Make SQL function +///------------------------ + +/** Adds SQL functions or aggregates or to redefine the behavior of existing SQL functions or aggregates. + + For example: + + [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" maximumArguments:1 withBlock:^(sqlite3_context *context, int aargc, sqlite3_value **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); + }]; + + @param name Name of function + + @param count Maximum number of parameters + + @param block The block of code for the function + + @see [sqlite3_create_function()](http://sqlite.org/c3ref/create_function.html) + */ + +- (void)makeFunctionNamed:(NSString*)name maximumArguments:(int)count withBlock:(void (^)(void *context, int argc, void **argv))block; + + +///--------------------- +/// @name Date formatter +///--------------------- + +/** Generate an `NSDateFormatter` that won't be broken by permutations of timezones or locales. + + Use this method to generate values to set the dateFormat property. + + Example: + + myDB.dateFormat = [FMDatabase storeableDateFormat:@"yyyy-MM-dd HH:mm:ss"]; + + @param format A valid NSDateFormatter format string. + + @return A `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 `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 `YES` if there is a date formatter; `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 FMDatabase::storeableDateFormat. + + @see hasDateFormatter + @see setDateFormat: + @see dateFromString: + @see stringFromDate: + @see storeableDateFormat: + + @warning Note there is no direct getter for the `NSDateFormatter`, and you should not use the formatter you pass to FMDB for other purposes, as `NSDateFormatter` is not thread-safe. + */ + +- (void)setDateFormat:(NSDateFormatter *)format; + +/** Convert the supplied NSString to NSDate, using the current database formatter. + + @param s `NSString` to convert to `NSDate`. + + @return The `NSDate` object; or `nil` if no formatter is set. + + @see hasDateFormatter + @see setDateFormat: + @see dateFromString: + @see stringFromDate: + @see storeableDateFormat: + */ + +- (NSDate *)dateFromString:(NSString *)s; + +/** Convert the supplied NSDate to NSString, using the current database formatter. + + @param date `NSDate` of date to convert to `NSString`. + + @return The `NSString` representation of the date; `nil` if no formatter is set. + + @see hasDateFormatter + @see setDateFormat: + @see dateFromString: + @see stringFromDate: + @see storeableDateFormat: + */ + +- (NSString *)stringFromDate:(NSDate *)date; + +@end + + +/** Objective-C wrapper for `sqlite3_stmt` + + This is a wrapper for a SQLite `sqlite3_stmt`. Generally when using FMDB you will not need to interact directly with `FMStatement`, but rather with `` and `` only. + + ### See also + + - `` + - `` + - [`sqlite3_stmt`](http://www.sqlite.org/c3ref/stmt.html) + */ + +@interface FMStatement : NSObject { + 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 [`sqlite3_stmt`](http://www.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 + diff --git a/Frameworks/RSDatabase/FMDB/fmdb-master/src/fmdb/FMDatabase.m b/Frameworks/RSDatabase/FMDB/fmdb-master/src/fmdb/FMDatabase.m new file mode 100755 index 000000000..cd7bf8676 --- /dev/null +++ b/Frameworks/RSDatabase/FMDB/fmdb-master/src/fmdb/FMDatabase.m @@ -0,0 +1,1437 @@ +#import "FMDatabase.h" +#import "unistd.h" +#import +#import "sqlite3.h" + +@interface FMDatabase () { + sqlite3* _db; +} + +- (FMResultSet *)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray*)arrayArgs orDictionary:(NSDictionary *)dictionaryArgs orVAList:(va_list)args; +- (BOOL)executeUpdate:(NSString*)sql error:(NSError**)outErr withArgumentsInArray:(NSArray*)arrayArgs orDictionary:(NSDictionary *)dictionaryArgs orVAList:(va_list)args; + +@end + +@implementation FMDatabase +@synthesize cachedStatements=_cachedStatements; +@synthesize logsErrors=_logsErrors; +@synthesize crashOnErrors=_crashOnErrors; +@synthesize checkedOut=_checkedOut; +@synthesize traceExecution=_traceExecution; + +#pragma mark FMDatabase instantiation and deallocation + ++ (instancetype)databaseWithPath:(NSString*)aPath { + return FMDBReturnAutoreleased([[self alloc] initWithPath:aPath]); +} + +- (instancetype)init { + return [self initWithPath:nil]; +} + +- (instancetype)initWithPath:(NSString*)aPath { + + 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 = [aPath copy]; + _openResultSets = [[NSMutableSet alloc] init]; + _db = nil; + _logsErrors = YES; + _crashOnErrors = NO; + _maxBusyRetryTimeInterval = 2; + } + + return self; +} + +- (void)finalize { + [self close]; + [super finalize]; +} + +- (void)dealloc { + [self close]; + FMDBRelease(_openResultSets); + FMDBRelease(_cachedStatements); + FMDBRelease(_dateFormat); + FMDBRelease(_databasePath); + FMDBRelease(_openFunctions); + +#if ! __has_feature(objc_arc) + [super dealloc]; +#endif +} + +- (NSString *)databasePath { + return _databasePath; +} + ++ (NSString*)FMDBUserVersion { + return @"2.5"; +} + +// returns 0x0240 for version 2.4. This makes it super easy to do things like: +// /* need to make sure to do X with FMDB version 2.4 or later */ +// if ([FMDatabase FMDBVersion] >= 0x0240) { … } + ++ (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]; + + if ([[prodVersion componentsSeparatedByString:@"."] count] < 3) { + prodVersion = [prodVersion stringByAppendingString:@".0"]; + } + + NSString *junk = [prodVersion stringByReplacingOccurrencesOfString:@"." withString:@""]; + + char *e = nil; + FMDBVersionVal = (int) strtoul([junk UTF8String], &e, 16); + + }); + + + 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]; + +} + +#pragma mark Open and close database + +- (BOOL)open { + if (_db) { + return YES; + } + + int err = sqlite3_open([self sqlitePath], &_db ); + if(err != SQLITE_OK) { + NSLog(@"error opening!: %d", err); + return NO; + } + + if (_maxBusyRetryTimeInterval > 0.0) { + // set the handler + [self setMaxBusyRetryTimeInterval:_maxBusyRetryTimeInterval]; + } + + + return YES; +} + +#if SQLITE_VERSION_NUMBER >= 3005000 +- (BOOL)openWithFlags:(int)flags { + return [self openWithFlags:flags vfs:nil]; +} +- (BOOL)openWithFlags:(int)flags vfs:(NSString *)vfsName; { + if (_db) { + return YES; + } + + int err = sqlite3_open_v2([self sqlitePath], &_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]; + } + + return YES; +} +#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); + retry = YES; + } + } + } + else if (SQLITE_OK != rc) { + NSLog(@"error closing!: %d", rc); + } + } + while (retry); + + _db = nil; + 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 { + 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]) { + [statements makeObjectsPerformSelector:@selector(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 { + + 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 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(_db, [keyData bytes], (int)[keyData length]); + + if (rc != SQLITE_OK) { + NSLog(@"error on rekey: %d", rc); + NSLog(@"%@", [self lastErrorMessage]); + } + + return (rc == SQLITE_OK); +#else + 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(_db, [keyData bytes], (int)[keyData length]); + + return (rc == SQLITE_OK); +#else + return NO; +#endif +} + +#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 (!_db) { + return NO; + } + + FMResultSet *rs = [self executeQuery:@"select name from sqlite_master where type='table'"]; + + if (rs) { + [rs close]; + return YES; + } + + 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 (!_db) { + + 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); +} + +- (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 + +- (void)bindObject:(id)obj toColumn:(int)idx inStatement:(sqlite3_stmt*)pStmt { + + if ((!obj) || ((NSNull *)obj == [NSNull null])) { + 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 = ""; + } + sqlite3_bind_blob(pStmt, idx, bytes, (int)[obj length], SQLITE_STATIC); + } + else if ([obj isKindOfClass:[NSDate class]]) { + if (self.hasDateFormatter) + sqlite3_bind_text(pStmt, idx, [[self stringFromDate:obj] UTF8String], -1, SQLITE_STATIC); + else + sqlite3_bind_double(pStmt, idx, [obj timeIntervalSince1970]); + } + else if ([obj isKindOfClass:[NSNumber class]]) { + + if (strcmp([obj objCType], @encode(char)) == 0) { + sqlite3_bind_int(pStmt, idx, [obj charValue]); + } + else if (strcmp([obj objCType], @encode(unsigned char)) == 0) { + sqlite3_bind_int(pStmt, idx, [obj unsignedCharValue]); + } + else if (strcmp([obj objCType], @encode(short)) == 0) { + sqlite3_bind_int(pStmt, idx, [obj shortValue]); + } + else if (strcmp([obj objCType], @encode(unsigned short)) == 0) { + sqlite3_bind_int(pStmt, idx, [obj unsignedShortValue]); + } + else if (strcmp([obj objCType], @encode(int)) == 0) { + sqlite3_bind_int(pStmt, idx, [obj intValue]); + } + else if (strcmp([obj objCType], @encode(unsigned int)) == 0) { + sqlite3_bind_int64(pStmt, idx, (long long)[obj unsignedIntValue]); + } + else if (strcmp([obj objCType], @encode(long)) == 0) { + sqlite3_bind_int64(pStmt, idx, [obj longValue]); + } + else if (strcmp([obj objCType], @encode(unsigned long)) == 0) { + sqlite3_bind_int64(pStmt, idx, (long long)[obj unsignedLongValue]); + } + else if (strcmp([obj objCType], @encode(long long)) == 0) { + sqlite3_bind_int64(pStmt, idx, [obj longLongValue]); + } + else if (strcmp([obj objCType], @encode(unsigned long long)) == 0) { + sqlite3_bind_int64(pStmt, idx, (long long)[obj unsignedLongLongValue]); + } + else if (strcmp([obj objCType], @encode(float)) == 0) { + sqlite3_bind_double(pStmt, idx, [obj floatValue]); + } + else if (strcmp([obj objCType], @encode(double)) == 0) { + sqlite3_bind_double(pStmt, idx, [obj doubleValue]); + } + else if (strcmp([obj objCType], @encode(BOOL)) == 0) { + sqlite3_bind_int(pStmt, idx, ([obj boolValue] ? 1 : 0)); + } + else { + sqlite3_bind_text(pStmt, idx, [[obj description] UTF8String], -1, SQLITE_STATIC); + } + } + else { + sqlite3_bind_text(pStmt, idx, [[obj description] UTF8String], -1, SQLITE_STATIC); + } +} + +- (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]; +} + +- (FMResultSet *)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray*)arrayArgs orDictionary:(NSDictionary *)dictionaryArgs orVAList:(va_list)args { + + 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); + _isExecutingStatement = NO; + return nil; + } + } + + 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. + [self bindObject:[dictionaryArgs objectForKey:dictionaryKey] toColumn:namedIdx inStatement:pStmt]; + // 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++; + + [self bindObject:obj toColumn:idx inStatement:pStmt]; + } + } + + if (idx != queryCount) { + NSLog(@"Error: the bind count is not correct for the # of variables (executeQuery)"); + sqlite3_finalize(pStmt); + _isExecutingStatement = NO; + 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]; + rs = [FMResultSet resultSetWithStatement:statement usingParentDatabase:self]; + [rs setQuery:sql]; + + NSValue *openResultSet = [NSValue valueWithNonretainedObject:rs]; + [_openResultSets addObject:openResultSet]; + + [statement setUseCount:[statement useCount] + 1]; + + FMDBRelease(statement); + + _isExecutingStatement = NO; + + return rs; +} + +- (FMResultSet *)executeQuery:(NSString*)sql, ... { + va_list args; + va_start(args, sql); + + id result = [self executeQuery:sql withArgumentsInArray:nil orDictionary:nil orVAList:args]; + + 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]; +} + +- (FMResultSet *)executeQuery:(NSString*)sql withVAList:(va_list)args { + return [self executeQuery:sql withArgumentsInArray:nil orDictionary:nil orVAList:args]; +} + +#pragma mark Execute updates + +- (BOOL)executeUpdate:(NSString*)sql error:(NSError**)outErr withArgumentsInArray:(NSArray*)arrayArgs orDictionary:(NSDictionary *)dictionaryArgs orVAList:(va_list)args { + + if (![self databaseExists]) { + return NO; + } + + if (_isExecutingStatement) { + [self warnInUse]; + return NO; + } + + _isExecutingStatement = YES; + + int rc = 0x00; + sqlite3_stmt *pStmt = 0x00; + FMStatement *cachedStmt = 0x00; + + if (_traceExecution && sql) { + NSLog(@"%@ executeUpdate: %@", self, sql); + } + + if (_shouldCacheStatements) { + cachedStmt = [self cachedStatementForQuery:sql]; + pStmt = cachedStmt ? [cachedStmt statement] : 0x00; + [cachedStmt 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); + + if (outErr) { + *outErr = [self errorWithMessage:[NSString stringWithUTF8String:sqlite3_errmsg(_db)]]; + } + + _isExecutingStatement = NO; + return NO; + } + } + + id obj; + int idx = 0; + int queryCount = sqlite3_bind_parameter_count(pStmt); + + // 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. + [self bindObject:[dictionaryArgs objectForKey:dictionaryKey] toColumn:namedIdx inStatement:pStmt]; + + // 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++; + + [self bindObject:obj toColumn:idx inStatement:pStmt]; + } + } + + + if (idx != queryCount) { + NSLog(@"Error: the bind count (%d) is not correct for the # of variables in the query (%d) (%@) (executeUpdate)", idx, queryCount, sql); + sqlite3_finalize(pStmt); + _isExecutingStatement = NO; + return NO; + } + + /* Call sqlite3_step() to run the virtual machine. Since the SQL being + ** executed is not a SELECT statement, we assume no data will be returned. + */ + + rc = sqlite3_step(pStmt); + + if (SQLITE_DONE == rc) { + // all is well, let's return. + } + else if (SQLITE_ERROR == rc) { + if (_logsErrors) { + NSLog(@"Error calling sqlite3_step (%d: %s) SQLITE_ERROR", rc, sqlite3_errmsg(_db)); + NSLog(@"DB Query: %@", sql); + } + } + else if (SQLITE_MISUSE == rc) { + // uh oh. + if (_logsErrors) { + NSLog(@"Error calling sqlite3_step (%d: %s) SQLITE_MISUSE", rc, sqlite3_errmsg(_db)); + NSLog(@"DB Query: %@", sql); + } + } + else { + // wtf? + if (_logsErrors) { + NSLog(@"Unknown error calling sqlite3_step (%d: %s) eu", rc, sqlite3_errmsg(_db)); + NSLog(@"DB Query: %@", sql); + } + } + + if (rc == SQLITE_ROW) { + NSAssert(NO, @"A executeUpdate is being called with a query string '%@'", sql); + } + + if (_shouldCacheStatements && !cachedStmt) { + cachedStmt = [[FMStatement alloc] init]; + + [cachedStmt setStatement:pStmt]; + + [self setCachedStatement:cachedStmt forQuery:sql]; + + FMDBRelease(cachedStmt); + } + + int closeErrorCode; + + if (cachedStmt) { + [cachedStmt setUseCount:[cachedStmt useCount] + 1]; + closeErrorCode = sqlite3_reset(pStmt); + } + else { + /* Finalize the virtual machine. This releases all memory and other + ** resources allocated by the sqlite3_prepare() call above. + */ + closeErrorCode = sqlite3_finalize(pStmt); + } + + if (closeErrorCode != SQLITE_OK) { + if (_logsErrors) { + NSLog(@"Unknown error finalizing or resetting statement (%d: %s)", closeErrorCode, sqlite3_errmsg(_db)); + NSLog(@"DB Query: %@", sql); + } + } + + _isExecutingStatement = NO; + return (rc == SQLITE_DONE || rc == SQLITE_OK); +} + + +- (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 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]; + [dictionary setObject:value forKey:key]; + } + + return execCallbackBlock(dictionary); +} + +- (BOOL)executeStatements:(NSString *)sql { + return [self executeStatements:sql withResultBlock:nil]; +} + +- (BOOL)executeStatements:(NSString *)sql withResultBlock:(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); + sqlite3_free(errmsg); + } + + return (rc == SQLITE_OK); +} + +- (BOOL)executeUpdate:(NSString*)sql withErrorAndBindings:(NSError**)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**)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 Transactions + +- (BOOL)rollback { + BOOL b = [self executeUpdate:@"rollback transaction"]; + + if (b) { + _inTransaction = NO; + } + + return b; +} + +- (BOOL)commit { + BOOL b = [self executeUpdate:@"commit transaction"]; + + if (b) { + _inTransaction = NO; + } + + return b; +} + +- (BOOL)beginDeferredTransaction { + + BOOL b = [self executeUpdate:@"begin deferred transaction"]; + if (b) { + _inTransaction = YES; + } + + return b; +} + +- (BOOL)beginTransaction { + + BOOL b = [self executeUpdate:@"begin exclusive transaction"]; + if (b) { + _inTransaction = YES; + } + + return b; +} + +- (BOOL)inTransaction { + return _inTransaction; +} + +#if SQLITE_VERSION_NUMBER >= 3007000 + +static NSString *FMDBEscapeSavePointName(NSString *savepointName) { + return [savepointName stringByReplacingOccurrencesOfString:@"'" withString:@"''"]; +} + +- (BOOL)startSavePointWithName:(NSString*)name error:(NSError**)outErr { + + NSParameterAssert(name); + + NSString *sql = [NSString stringWithFormat:@"savepoint '%@';", FMDBEscapeSavePointName(name)]; + + if (![self executeUpdate:sql]) { + + if (outErr) { + *outErr = [self lastError]; + } + + return NO; + } + + return YES; +} + +- (BOOL)releaseSavePointWithName:(NSString*)name error:(NSError**)outErr { + + NSParameterAssert(name); + + NSString *sql = [NSString stringWithFormat:@"release savepoint '%@';", FMDBEscapeSavePointName(name)]; + BOOL worked = [self executeUpdate:sql]; + + if (!worked && outErr) { + *outErr = [self lastError]; + } + + return worked; +} + +- (BOOL)rollbackToSavePointWithName:(NSString*)name error:(NSError**)outErr { + + NSParameterAssert(name); + + NSString *sql = [NSString stringWithFormat:@"rollback transaction to savepoint '%@';", FMDBEscapeSavePointName(name)]; + BOOL worked = [self executeUpdate:sql]; + + if (!worked && outErr) { + *outErr = [self lastError]; + } + + return worked; +} + +- (NSError*)inSavePoint:(void (^)(BOOL *rollback))block { + 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; +} + +#endif + +#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) { + block(context, argc, argv); + } +} + + +- (void)makeFunctionNamed:(NSString*)name maximumArguments:(int)count withBlock:(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], count, SQLITE_UTF8, (void*)b, &FMDBBlockSQLiteCallBackFunction, 0x00, 0x00); +#else + sqlite3_create_function([self sqliteHandle], [name UTF8String], count, SQLITE_UTF8, (__bridge void*)b, &FMDBBlockSQLiteCallBackFunction, 0x00, 0x00); +#endif +} + +@end + + + +@implementation FMStatement { + sqlite3_stmt *_statement; +} + +@synthesize statement=_statement; +@synthesize query=_query; +@synthesize useCount=_useCount; +@synthesize inUse=_inUse; + +- (void)finalize { + [self close]; + [super finalize]; +} + +- (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 + diff --git a/Frameworks/RSDatabase/FMDB/fmdb-master/src/fmdb/FMDatabaseAdditions.h b/Frameworks/RSDatabase/FMDB/fmdb-master/src/fmdb/FMDatabaseAdditions.h new file mode 100755 index 000000000..85bb27782 --- /dev/null +++ b/Frameworks/RSDatabase/FMDB/fmdb-master/src/fmdb/FMDatabaseAdditions.h @@ -0,0 +1,281 @@ +// +// FMDatabaseAdditions.h +// fmdb +// +// Created by August Mueller on 10/30/05. +// Copyright 2005 Flying Meat Inc.. All rights reserved. +// + +#import +#import "FMDatabase.h" + + +/** Category of additions for `` class. + + ### See also + + - `` + */ + +@interface FMDatabase (FMDatabaseAdditions) + +///---------------------------------------- +/// @name Return results of SQL to variable +///---------------------------------------- + +/** Return `int` value for query + + @param query The SQL query to be performed. + @param ... A list of parameters that will be bound to the `?` placeholders in the SQL query. + + @return `int` value. + + @note To use this method from Swift, you must include `FMDatabaseAdditionsVariadic.swift` in your project. + */ + +- (int)intForQuery:(NSString*)query, ...; + +/** Return `long` value for query + + @param query The SQL query to be performed. + @param ... A list of parameters that will be bound to the `?` placeholders in the SQL query. + + @return `long` value. + + @note To use this method from Swift, you must include `FMDatabaseAdditionsVariadic.swift` in your project. + */ + +- (long)longForQuery:(NSString*)query, ...; + +/** Return `BOOL` value for query + + @param query The SQL query to be performed. + @param ... A list of parameters that will be bound to the `?` placeholders in the SQL query. + + @return `BOOL` value. + + @note To use this method from Swift, you must include `FMDatabaseAdditionsVariadic.swift` in your project. + */ + +- (BOOL)boolForQuery:(NSString*)query, ...; + +/** Return `double` value for query + + @param query The SQL query to be performed. + @param ... A list of parameters that will be bound to the `?` placeholders in the SQL query. + + @return `double` value. + + @note To use this method from Swift, you must include `FMDatabaseAdditionsVariadic.swift` in your project. + */ + +- (double)doubleForQuery:(NSString*)query, ...; + +/** Return `NSString` value for query + + @param query The SQL query to be performed. + @param ... A list of parameters that will be bound to the `?` placeholders in the SQL query. + + @return `NSString` value. + + @note To use this method from Swift, you must include `FMDatabaseAdditionsVariadic.swift` in your project. + */ + +- (NSString*)stringForQuery:(NSString*)query, ...; + +/** Return `NSData` value for query + + @param query The SQL query to be performed. + @param ... A list of parameters that will be bound to the `?` placeholders in the SQL query. + + @return `NSData` value. + + @note To use this method from Swift, you must include `FMDatabaseAdditionsVariadic.swift` in your project. + */ + +- (NSData*)dataForQuery:(NSString*)query, ...; + +/** Return `NSDate` value for query + + @param query The SQL query to be performed. + @param ... A list of parameters that will be bound to the `?` placeholders in the SQL query. + + @return `NSDate` value. + + @note To use this method from Swift, you must include `FMDatabaseAdditionsVariadic.swift` in your project. + */ + +- (NSDate*)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 `YES` if table found; `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; `nil` on error. + + @see [SQLite File Format](http://www.sqlite.org/fileformat.html) + */ + +- (FMResultSet*)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; `nil` on error. + + @see [table_info](http://www.sqlite.org/pragma.html#pragma_table_info) + */ + +- (FMResultSet*)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 `YES` if column exists in table in question; `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 `YES` if column exists in table in question; `NO` otherwise. + + @see columnExists:inTableWithName: + + @warning Deprecated - use `` instead. + */ + +- (BOOL)columnExists:(NSString*)tableName columnName:(NSString*)columnName __attribute__ ((deprecated)); + + +/** 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 `NSError` object that will receive the autoreleased `NSError` object if there was any error. If this is `nil`, no `NSError` result will be returned. + + @return `YES` if validation succeeded without incident; `NO` otherwise. + + */ + +- (BOOL)validateSQL:(NSString*)sql error:(NSError**)error; + + +#if SQLITE_VERSION_NUMBER >= 3007017 + +///----------------------------------- +/// @name Application identifier tasks +///----------------------------------- + +/** Retrieve application ID + + @return The `uint32_t` numeric value of the application ID. + + @see setApplicationID: + */ + +- (uint32_t)applicationID; + +/** Set the application ID + + @param appID The `uint32_t` numeric value of the application ID. + + @see applicationID + */ + +- (void)setApplicationID:(uint32_t)appID; + +#if TARGET_OS_MAC && !TARGET_OS_IPHONE +/** Retrieve application ID string + + @return The `NSString` value of the application ID. + + @see setApplicationIDString: + */ + + +- (NSString*)applicationIDString; + +/** Set the application ID string + + @param string The `NSString` value of the application ID. + + @see applicationIDString + */ + +- (void)setApplicationIDString:(NSString*)string; +#endif + +#endif + +///----------------------------------- +/// @name user version identifier tasks +///----------------------------------- + +/** Retrieve user version + + @return The `uint32_t` numeric value of the user version. + + @see setUserVersion: + */ + +- (uint32_t)userVersion; + +/** Set the user-version + + @param version The `uint32_t` numeric value of the user version. + + @see userVersion + */ + +- (void)setUserVersion:(uint32_t)version; + +@end diff --git a/Frameworks/RSDatabase/FMDB/fmdb-master/src/fmdb/FMDatabaseAdditions.m b/Frameworks/RSDatabase/FMDB/fmdb-master/src/fmdb/FMDatabaseAdditions.m new file mode 100755 index 000000000..fb5cbad40 --- /dev/null +++ b/Frameworks/RSDatabase/FMDB/fmdb-master/src/fmdb/FMDatabaseAdditions.m @@ -0,0 +1,225 @@ +// +// 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" +#import "sqlite3.h" + +@interface FMDatabase (PrivateStuff) +- (FMResultSet *)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray*)arrayArgs orDictionary:(NSDictionary *)dictionaryArgs orVAList:(va_list)args; +@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]; \ +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*)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*)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; +} + + +#if SQLITE_VERSION_NUMBER >= 3007017 + +- (uint32_t)applicationID { + + uint32_t r = 0; + + FMResultSet *rs = [self executeQuery:@"pragma application_id"]; + + if ([rs next]) { + r = (uint32_t)[rs longLongIntForColumnIndex:0]; + } + + [rs close]; + + return r; +} + +- (void)setApplicationID:(uint32_t)appID { + NSString *query = [NSString stringWithFormat:@"pragma application_id=%d", appID]; + FMResultSet *rs = [self executeQuery:query]; + [rs next]; + [rs close]; +} + + +#if TARGET_OS_MAC && !TARGET_OS_IPHONE +- (NSString*)applicationIDString { + NSString *s = NSFileTypeForHFSTypeCode([self applicationID]); + + assert([s length] == 6); + + s = [s substringWithRange:NSMakeRange(1, 4)]; + + + return s; + +} + +- (void)setApplicationIDString:(NSString*)s { + + if ([s length] != 4) { + NSLog(@"setApplicationIDString: string passed is not exactly 4 chars long. (was %ld)", [s length]); + } + + [self setApplicationID:NSHFSTypeCodeFromFileType([NSString stringWithFormat:@"'%@'", s])]; +} + + +#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**)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 diff --git a/Frameworks/RSDatabase/FMDB/fmdb-master/src/fmdb/FMDatabasePool.h b/Frameworks/RSDatabase/FMDB/fmdb-master/src/fmdb/FMDatabasePool.h new file mode 100755 index 000000000..692b8ae27 --- /dev/null +++ b/Frameworks/RSDatabase/FMDB/fmdb-master/src/fmdb/FMDatabasePool.h @@ -0,0 +1,204 @@ +// +// FMDatabasePool.h +// fmdb +// +// Created by August Mueller on 6/22/11. +// Copyright 2011 Flying Meat Inc. All rights reserved. +// + +#import +#import "sqlite3.h" + +@class FMDatabase; + +/** Pool of `` objects. + + ### See also + + - `` + - `` + + @warning Before using `FMDatabasePool`, please consider using `` instead. + + If you really really really know what you're doing and `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 { + NSString *_path; + + dispatch_queue_t _lockQueue; + + NSMutableArray *_databaseInPool; + NSMutableArray *_databaseOutPool; + + __unsafe_unretained id _delegate; + + NSUInteger _maximumNumberOfDatabasesToCreate; + int _openFlags; +} + +/** Database path */ + +@property (atomic, retain) NSString *path; + +/** Delegate object */ + +@property (atomic, assign) id delegate; + +/** Maximum number of databases to create */ + +@property (atomic, assign) NSUInteger maximumNumberOfDatabasesToCreate; + +/** Open flags */ + +@property (atomic, readonly) int openFlags; + + +///--------------------- +/// @name Initialization +///--------------------- + +/** Create pool using path. + + @param aPath The file path of the database. + + @return The `FMDatabasePool` object. `nil` on error. + */ + ++ (instancetype)databasePoolWithPath:(NSString*)aPath; + +/** 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 `FMDatabasePool` object. `nil` on error. + */ + ++ (instancetype)databasePoolWithPath:(NSString*)aPath flags:(int)openFlags; + +/** Create pool using path. + + @param aPath The file path of the database. + + @return The `FMDatabasePool` object. `nil` on error. + */ + +- (instancetype)initWithPath:(NSString*)aPath; + +/** 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 `FMDatabasePool` object. `nil` on error. + */ + +- (instancetype)initWithPath:(NSString*)aPath flags:(int)openFlags; + +///------------------------------------------------ +/// @name Keeping track of checked in/out databases +///------------------------------------------------ + +/** Number of checked-in databases in pool + + @returns Number of databases + */ + +- (NSUInteger)countOfCheckedInDatabases; + +/** Number of checked-out databases in pool + + @returns Number of databases + */ + +- (NSUInteger)countOfCheckedOutDatabases; + +/** Total number of databases in pool + + @returns Number of databases + */ + +- (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 `FMDatabasePool` pool. + */ + +- (void)inDatabase:(void (^)(FMDatabase *db))block; + +/** Synchronously perform database operations in pool using transaction. + + @param block The code to be run on the `FMDatabasePool` pool. + */ + +- (void)inTransaction:(void (^)(FMDatabase *db, BOOL *rollback))block; + +/** Synchronously perform database operations in pool using deferred transaction. + + @param block The code to be run on the `FMDatabasePool` pool. + */ + +- (void)inDeferredTransaction:(void (^)(FMDatabase *db, BOOL *rollback))block; + +#if SQLITE_VERSION_NUMBER >= 3007000 + +/** Synchronously perform database operations in pool using save point. + + @param block The code to be run on the `FMDatabasePool` pool. + + @return `NSError` object if error; `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 `<[FMDatabase startSavePointWithName:error:]>` instead. +*/ + +- (NSError*)inSavePoint:(void (^)(FMDatabase *db, BOOL *rollback))block; +#endif + +@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 `FMDatabasePool` object. + @param database The `FMDatabase` object. + + @return `YES` if it should add database to pool; `NO` if not. + + */ + +- (BOOL)databasePool:(FMDatabasePool*)pool shouldAddDatabaseToPool:(FMDatabase*)database; + +/** Tells the delegate that database was added to the pool. + + @param pool The `FMDatabasePool` object. + @param database The `FMDatabase` object. + + */ + +- (void)databasePool:(FMDatabasePool*)pool didAddDatabase:(FMDatabase*)database; + +@end + diff --git a/Frameworks/RSDatabase/FMDB/fmdb-master/src/fmdb/FMDatabasePool.m b/Frameworks/RSDatabase/FMDB/fmdb-master/src/fmdb/FMDatabasePool.m new file mode 100755 index 000000000..010e2920f --- /dev/null +++ b/Frameworks/RSDatabase/FMDB/fmdb-master/src/fmdb/FMDatabasePool.m @@ -0,0 +1,273 @@ +// +// FMDatabasePool.m +// fmdb +// +// Created by August Mueller on 6/22/11. +// Copyright 2011 Flying Meat Inc. All rights reserved. +// + +#import "FMDatabasePool.h" +#import "FMDatabase.h" + +@interface FMDatabasePool() + +- (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)databasePoolWithPath:(NSString*)aPath flags:(int)openFlags { + return FMDBReturnAutoreleased([[self alloc] initWithPath:aPath flags:openFlags]); +} + +- (instancetype)initWithPath:(NSString*)aPath flags:(int)openFlags { + + 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; + } + + return self; +} + +- (instancetype)initWithPath:(NSString*)aPath +{ + // default flags for sqlite3_open + return [self initWithPath:aPath flags:SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE]; +} + +- (instancetype)init { + return [self initWithPath:nil]; +} + + +- (void)dealloc { + + _delegate = 0x00; + FMDBRelease(_path); + FMDBRelease(_databaseInPool); + FMDBRelease(_databaseOutPool); + + 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 = [FMDatabase 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]; +#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:(void (^)(FMDatabase *db))block { + + FMDatabase *db = [self db]; + + block(db); + + [self pushDatabaseBackInPool:db]; +} + +- (void)beginTransaction:(BOOL)useDeferred withBlock:(void (^)(FMDatabase *db, BOOL *rollback))block { + + BOOL shouldRollback = NO; + + FMDatabase *db = [self db]; + + if (useDeferred) { + [db beginDeferredTransaction]; + } + else { + [db beginTransaction]; + } + + + block(db, &shouldRollback); + + if (shouldRollback) { + [db rollback]; + } + else { + [db commit]; + } + + [self pushDatabaseBackInPool:db]; +} + +- (void)inDeferredTransaction:(void (^)(FMDatabase *db, BOOL *rollback))block { + [self beginTransaction:YES withBlock:block]; +} + +- (void)inTransaction:(void (^)(FMDatabase *db, BOOL *rollback))block { + [self beginTransaction:NO withBlock:block]; +} +#if SQLITE_VERSION_NUMBER >= 3007000 +- (NSError*)inSavePoint:(void (^)(FMDatabase *db, BOOL *rollback))block { + + 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; +} +#endif + +@end diff --git a/Frameworks/RSDatabase/FMDB/fmdb-master/src/fmdb/FMDatabaseQueue.h b/Frameworks/RSDatabase/FMDB/fmdb-master/src/fmdb/FMDatabaseQueue.h new file mode 100755 index 000000000..82d458655 --- /dev/null +++ b/Frameworks/RSDatabase/FMDB/fmdb-master/src/fmdb/FMDatabaseQueue.h @@ -0,0 +1,185 @@ +// +// FMDatabaseQueue.h +// fmdb +// +// Created by August Mueller on 6/22/11. +// Copyright 2011 Flying Meat Inc. All rights reserved. +// + +#import +#import "sqlite3.h" + +@class FMDatabase; + +/** To perform queries and updates on multiple threads, you'll want to use `FMDatabaseQueue`. + + Using a single instance of `` from multiple threads at once is a bad idea. It has always been OK to make a `` object *per thread*. Just don't share a single instance across threads, and definitely not across multiple threads at the same time. + + Instead, use `FMDatabaseQueue`. Here's how to use it: + + First, make your queue. + + FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:aPath]; + + Then use it like so: + + [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]) { + //… + } + }]; + + An easy way to wrap things up in a transaction can be done like this: + + [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]]; + }]; + + `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. + + ### See also + + - `` + + @warning Do not instantiate a single `` object and use it across multiple threads. Use `FMDatabaseQueue` instead. + + @warning The calls to `FMDatabaseQueue`'s methods are blocking. So even though you are passing along blocks, they will **not** be run on another thread. + + */ + +@interface FMDatabaseQueue : NSObject { + NSString *_path; + dispatch_queue_t _queue; + FMDatabase *_db; + int _openFlags; +} + +/** Path of database */ + +@property (atomic, retain) NSString *path; + +/** Open flags */ + +@property (atomic, readonly) int openFlags; + +///---------------------------------------------------- +/// @name Initialization, opening, and closing of queue +///---------------------------------------------------- + +/** Create queue using path. + + @param aPath The file path of the database. + + @return The `FMDatabaseQueue` object. `nil` on error. + */ + ++ (instancetype)databaseQueueWithPath:(NSString*)aPath; + +/** 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 `FMDatabaseQueue` object. `nil` on error. + */ ++ (instancetype)databaseQueueWithPath:(NSString*)aPath flags:(int)openFlags; + +/** Create queue using path. + + @param aPath The file path of the database. + + @return The `FMDatabaseQueue` object. `nil` on error. + */ + +- (instancetype)initWithPath:(NSString*)aPath; + +/** 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 `FMDatabaseQueue` object. `nil` on error. + */ + +- (instancetype)initWithPath:(NSString*)aPath 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 `FMDatabaseQueue` object. `nil` on error. + */ + +- (instancetype)initWithPath:(NSString*)aPath flags:(int)openFlags vfs:(NSString *)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; + +///----------------------------------------------- +/// @name Dispatching database operations to queue +///----------------------------------------------- + +/** Synchronously perform database operations on queue. + + @param block The code to be run on the queue of `FMDatabaseQueue` + */ + +- (void)inDatabase:(void (^)(FMDatabase *db))block; + +/** Synchronously perform database operations on queue, using transactions. + + @param block The code to be run on the queue of `FMDatabaseQueue` + */ + +- (void)inTransaction:(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 `FMDatabaseQueue` + */ + +- (void)inDeferredTransaction:(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 `FMDatabaseQueue` + */ + +#if SQLITE_VERSION_NUMBER >= 3007000 +// 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*)inSavePoint:(void (^)(FMDatabase *db, BOOL *rollback))block; +#endif + +@end + diff --git a/Frameworks/RSDatabase/FMDB/fmdb-master/src/fmdb/FMDatabaseQueue.m b/Frameworks/RSDatabase/FMDB/fmdb-master/src/fmdb/FMDatabaseQueue.m new file mode 100755 index 000000000..3cdecdc3c --- /dev/null +++ b/Frameworks/RSDatabase/FMDB/fmdb-master/src/fmdb/FMDatabaseQueue.m @@ -0,0 +1,236 @@ +// +// 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" + +/* + + 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; + +@implementation FMDatabaseQueue + +@synthesize path = _path; +@synthesize openFlags = _openFlags; + ++ (instancetype)databaseQueueWithPath:(NSString*)aPath { + + FMDatabaseQueue *q = [[self alloc] initWithPath:aPath]; + + FMDBAutorelease(q); + + return q; +} + ++ (instancetype)databaseQueueWithPath:(NSString*)aPath flags:(int)openFlags { + + FMDatabaseQueue *q = [[self alloc] initWithPath:aPath flags:openFlags]; + + FMDBAutorelease(q); + + return q; +} + ++ (Class)databaseClass { + return [FMDatabase class]; +} + +- (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; + } + + return self; +} + +- (instancetype)initWithPath:(NSString*)aPath flags:(int)openFlags { + return [self initWithPath:aPath flags:openFlags vfs:nil]; +} + +- (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); + + 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); +} + +- (FMDatabase*)database { + if (!_db) { + _db = FMDBReturnRetained([FMDatabase databaseWithPath:_path]); + +#if SQLITE_VERSION_NUMBER >= 3005000 + BOOL success = [_db openWithFlags:_openFlags]; +#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:(void (^)(FMDatabase *db))block { + /* 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"); + + 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:(BOOL)useDeferred withBlock:(void (^)(FMDatabase *db, BOOL *rollback))block { + FMDBRetain(self); + dispatch_sync(_queue, ^() { + + BOOL shouldRollback = NO; + + if (useDeferred) { + [[self database] beginDeferredTransaction]; + } + else { + [[self database] beginTransaction]; + } + + block([self database], &shouldRollback); + + if (shouldRollback) { + [[self database] rollback]; + } + else { + [[self database] commit]; + } + }); + + FMDBRelease(self); +} + +- (void)inDeferredTransaction:(void (^)(FMDatabase *db, BOOL *rollback))block { + [self beginTransaction:YES withBlock:block]; +} + +- (void)inTransaction:(void (^)(FMDatabase *db, BOOL *rollback))block { + [self beginTransaction:NO withBlock:block]; +} + +#if SQLITE_VERSION_NUMBER >= 3007000 +- (NSError*)inSavePoint:(void (^)(FMDatabase *db, BOOL *rollback))block { + + 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; +} +#endif + +@end diff --git a/Frameworks/RSDatabase/FMDB/fmdb-master/src/fmdb/FMResultSet.h b/Frameworks/RSDatabase/FMDB/fmdb-master/src/fmdb/FMResultSet.h new file mode 100755 index 000000000..93a4a66ab --- /dev/null +++ b/Frameworks/RSDatabase/FMDB/fmdb-master/src/fmdb/FMResultSet.h @@ -0,0 +1,469 @@ +#import +//#import "sqlite3.h" + +#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; + +/** Represents the results of executing a query on an ``. + + ### See also + + - `` + */ + +@interface FMResultSet : NSObject { + FMDatabase *_parentDB; + FMStatement *_statement; + + NSString *_query; + NSMutableDictionary *_columnNameToIndexMap; +} + +///----------------- +/// @name Properties +///----------------- + +/** Executed query */ + +@property (atomic, retain) NSString *query; + +/** `NSMutableDictionary` mapping column names to numeric index */ + +@property (readonly) NSMutableDictionary *columnNameToIndexMap; + +/** `FMStatement` used by result set. */ + +@property (atomic, retain) FMStatement *statement; + +///------------------------------------ +/// @name Creating and closing database +///------------------------------------ + +/** Create result set from `` + + @param statement A `` to be performed + + @param aDB A `` to be used + + @return A `FMResultSet` on success; `nil` on failure + */ + ++ (instancetype)resultSetWithStatement:(FMStatement *)statement usingParentDatabase:(FMDatabase*)aDB; + +/** Close result set */ + +- (void)close; + +- (void)setParentDB:(FMDatabase *)newDb; + +///--------------------------------------- +/// @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 `YES` if row successfully retrieved; `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 **)outErr; + +/** Did the last call to `` succeed in retrieving another row? + + @return `YES` if the last call to `` succeeded in retrieving another record; `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 `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. + */ + +- (int)columnCount; + +/** Column index for column name + + @param columnName `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 `NSString` value of the name of the column. + */ + +- (NSString*)columnNameForIndex:(int)columnIdx; + +/** Result set integer value for column. + + @param columnName `NSString` value of the name of the column. + + @return `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 `int` value of the result set's column. + */ + +- (int)intForColumnIndex:(int)columnIdx; + +/** Result set `long` value for column. + + @param columnName `NSString` value of the name of the column. + + @return `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 `long` value of the result set's column. + */ + +- (long)longForColumnIndex:(int)columnIdx; + +/** Result set `long long int` value for column. + + @param columnName `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 `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 `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 `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 `NSString` value for column. + + @param columnName `NSString` value of the name of the column. + + @return `NSString` value of the result set's column. + + */ + +- (NSString*)stringForColumn:(NSString*)columnName; + +/** Result set `NSString` value for column. + + @param columnIdx Zero-based index for column. + + @return `NSString` value of the result set's column. + */ + +- (NSString*)stringForColumnIndex:(int)columnIdx; + +/** Result set `NSDate` value for column. + + @param columnName `NSString` value of the name of the column. + + @return `NSDate` value of the result set's column. + */ + +- (NSDate*)dateForColumn:(NSString*)columnName; + +/** Result set `NSDate` value for column. + + @param columnIdx Zero-based index for column. + + @return `NSDate` value of the result set's column. + + */ + +- (NSDate*)dateForColumnIndex:(int)columnIdx; + +/** Result set `NSData` value for column. + + This is useful when storing binary data in table (such as image or the like). + + @param columnName `NSString` value of the name of the column. + + @return `NSData` value of the result set's column. + + */ + +- (NSData*)dataForColumn:(NSString*)columnName; + +/** Result set `NSData` value for column. + + @param columnIdx Zero-based index for column. + + @return `NSData` value of the result set's column. + */ + +- (NSData*)dataForColumnIndex:(int)columnIdx; + +/** Result set `(const unsigned char *)` value for column. + + @param columnName `NSString` value of the name of the column. + + @return `(const unsigned char *)` value of the result set's column. + */ + +- (const unsigned char *)UTF8StringForColumnName:(NSString*)columnName; + +/** 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 *)UTF8StringForColumnIndex:(int)columnIdx; + +/** Result set object for column. + + @param columnName `NSString` value of the name of the column. + + @return Either `NSNumber`, `NSString`, `NSData`, or `NSNull`. If the column was `NULL`, this returns `[NSNull null]` object. + + @see objectForKeyedSubscript: + */ + +- (id)objectForColumnName:(NSString*)columnName; + +/** Result set object for column. + + @param columnIdx Zero-based index for column. + + @return Either `NSNumber`, `NSString`, `NSData`, or `NSNull`. If the column was `NULL`, this returns `[NSNull null]` object. + + @see objectAtIndexedSubscript: + */ + +- (id)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: + + id result = rs[@"employee_name"]; + + This simplified syntax is equivalent to calling: + + id result = [rs objectForKeyedSubscript:@"employee_name"]; + + which is, it turns out, equivalent to calling: + + id result = [rs objectForColumnName:@"employee_name"]; + + @param columnName `NSString` value of the name of the column. + + @return Either `NSNumber`, `NSString`, `NSData`, or `NSNull`. If the column was `NULL`, this returns `[NSNull null]` object. + */ + +- (id)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: + + id result = rs[0]; + + This simplified syntax is equivalent to calling: + + id result = [rs objectForKeyedSubscript:0]; + + which is, it turns out, equivalent to calling: + + id result = [rs objectForColumnName:0]; + + @param columnIdx Zero-based index for column. + + @return Either `NSNumber`, `NSString`, `NSData`, or `NSNull`. If the column was `NULL`, this returns `[NSNull null]` object. + */ + +- (id)objectAtIndexedSubscript:(int)columnIdx; + +/** Result set `NSData` value for column. + + @param columnName `NSString` value of the name of the column. + + @return `NSData` 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*)dataNoCopyForColumn:(NSString*)columnName NS_RETURNS_NOT_RETAINED; + +/** Result set `NSData` value for column. + + @param columnIdx Zero-based index for column. + + @return `NSData` 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*)dataNoCopyForColumnIndex:(int)columnIdx NS_RETURNS_NOT_RETAINED; + +/** Is the column `NULL`? + + @param columnIdx Zero-based index for column. + + @return `YES` if column is `NULL`; `NO` if not `NULL`. + */ + +- (BOOL)columnIndexIsNull:(int)columnIdx; + +/** Is the column `NULL`? + + @param columnName `NSString` value of the name of the column. + + @return `YES` if column is `NULL`; `NO` if not `NULL`. + */ + +- (BOOL)columnIsNull:(NSString*)columnName; + + +/** Returns a dictionary of the row results mapped to case sensitive keys of the column names. + + @returns `NSDictionary` of the row results. + + @warning The keys to the dictionary are case sensitive of the column names. + */ + +- (NSDictionary*)resultDictionary; + +/** Returns a dictionary of the row results + + @see resultDictionary + + @warning **Deprecated**: Please use `` instead. Also, beware that `` is case sensitive! + */ + +- (NSDictionary*)resultDict __attribute__ ((deprecated)); + +///----------------------------- +/// @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; + + +@end + diff --git a/Frameworks/RSDatabase/FMDB/fmdb-master/src/fmdb/FMResultSet.m b/Frameworks/RSDatabase/FMDB/fmdb-master/src/fmdb/FMResultSet.m new file mode 100755 index 000000000..e1949fd06 --- /dev/null +++ b/Frameworks/RSDatabase/FMDB/fmdb-master/src/fmdb/FMResultSet.m @@ -0,0 +1,417 @@ +#import "FMResultSet.h" +#import "FMDatabase.h" +#import "unistd.h" +#import "sqlite3.h" + +@interface FMDatabase () +- (void)resultSetDidClose:(FMResultSet *)resultSet; +@end + + +@implementation FMResultSet +@synthesize query=_query; +@synthesize statement=_statement; + ++ (instancetype)resultSetWithStatement:(FMStatement *)statement usingParentDatabase:(FMDatabase*)aDB { + + FMResultSet *rs = [[FMResultSet alloc] init]; + + [rs setStatement:statement]; + [rs setParentDB:aDB]; + + NSParameterAssert(![statement inUse]); + [statement setInUse:YES]; // weak reference + + return FMDBReturnAutoreleased(rs); +} + +- (void)finalize { + [self close]; + [super finalize]; +} + +- (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]; + _parentDB = 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 **)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) { + [self close]; + } + + return (rc == SQLITE_ROW); +} + +- (BOOL)hasAnotherRow { + return sqlite3_errcode([_parentDB sqliteHandle]) == SQLITE_ROW; +} + +- (int)columnIndexForName:(NSString*)columnName { + columnName = [columnName lowercaseString]; + + NSNumber *n = [[self columnNameToIndexMap] objectForKey:columnName]; + + if (n) { + 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)) { + 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)) { + 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)) { + 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)) { + 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)) { + return nil; + } + + return sqlite3_column_text([_statement statement], columnIdx); +} + +- (const unsigned char *)UTF8StringForColumnName:(NSString*)columnName { + return [self UTF8StringForColumnIndex:[self columnIndexForName:columnName]]; +} + +- (id)objectForColumnIndex:(int)columnIdx { + 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 objectForColumnIndex:[self columnIndexForName:columnName]]; +} + +// 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)]; +} + +- (void)setParentDB:(FMDatabase *)newDb { + _parentDB = newDb; +} + +- (id)objectAtIndexedSubscript:(int)columnIdx { + return [self objectForColumnIndex:columnIdx]; +} + +- (id)objectForKeyedSubscript:(NSString *)columnName { + return [self objectForColumnName:columnName]; +} + + +@end diff --git a/Frameworks/RSDatabase/FMDB/fmdb-master/src/sample/fmdb_Prefix.pch b/Frameworks/RSDatabase/FMDB/fmdb-master/src/sample/fmdb_Prefix.pch new file mode 100755 index 000000000..b8c83c339 --- /dev/null +++ b/Frameworks/RSDatabase/FMDB/fmdb-master/src/sample/fmdb_Prefix.pch @@ -0,0 +1,7 @@ +// +// Prefix header for all source files of the 'fmdb' target in the 'fmdb' project. +// + +#ifdef __OBJC__ + #import +#endif diff --git a/Frameworks/RSDatabase/FMDB/fmdb-master/src/sample/main.m b/Frameworks/RSDatabase/FMDB/fmdb-master/src/sample/main.m new file mode 100755 index 000000000..39bb47320 --- /dev/null +++ b/Frameworks/RSDatabase/FMDB/fmdb-master/src/sample/main.m @@ -0,0 +1,1537 @@ +/* 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" + +#define FMDBQuickCheck(SomeBool) { if (!(SomeBool)) { NSLog(@"Failure on line %d", __LINE__); abort(); } } + +void testPool(NSString *dbPath); +void testDateFormat(); +void FMDBReportABugFunction(); +void testStatementCaching(); + +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/compass.icns"]; + 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/compass.icns"]; + + [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 UTF8StringForColumnName:@"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 UTF8StringForColumnName:@"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" maximumArguments:1 withBlock:^(sqlite3_context *context, int aargc, sqlite3_value **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() { + + 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() { + + 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() { + + 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); + +} + + + + + diff --git a/Frameworks/RSDatabase/LICENSE b/Frameworks/RSDatabase/LICENSE new file mode 100755 index 000000000..d9348ee4e --- /dev/null +++ b/Frameworks/RSDatabase/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2016 brentsimmons + +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. diff --git a/Frameworks/RSDatabase/README.md b/Frameworks/RSDatabase/README.md new file mode 100755 index 000000000..93851536e --- /dev/null +++ b/Frameworks/RSDatabase/README.md @@ -0,0 +1,12 @@ +# RSDatabase +This is utility code for using SQLite via FMDB. It’s not a persistence framework — it’s lower-level. + +It builds as a couple frameworks — one for Mac, one for iOS. + +It has no additional dependencies, but that’s because FMDB is actually included — you might want to instead make sure you have the [latest FMDB](https://github.com/ccgus/fmdb), which isn’t necessarily included here. + +#### What to look at + +The main thing is `RSDatabaseQueue`, which allows you to talk to SQLite-via-FMDB using a serial queue. + +The second thing is `FMDatabase+RSExtras`, which provides methods for a bunch of common queries and updates, so you don’t have to write as much SQL. diff --git a/Frameworks/RSDatabase/RSDatabase.xcodeproj/project.pbxproj b/Frameworks/RSDatabase/RSDatabase.xcodeproj/project.pbxproj new file mode 100755 index 000000000..cc174e737 --- /dev/null +++ b/Frameworks/RSDatabase/RSDatabase.xcodeproj/project.pbxproj @@ -0,0 +1,630 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 46; + objects = { + +/* Begin PBXBuildFile section */ + 8400ABFF1E0CFC0700AA7C57 /* RSDatabaseQueue.h in Headers */ = {isa = PBXBuildFile; fileRef = 84419ADC1B5ABD7F00C26BB2 /* RSDatabaseQueue.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 8400AC001E0CFC0700AA7C57 /* RSDatabaseQueue.m in Sources */ = {isa = PBXBuildFile; fileRef = 84419ADD1B5ABD7F00C26BB2 /* RSDatabaseQueue.m */; }; + 8400AC011E0CFC0700AA7C57 /* FMDatabase+RSExtras.h in Headers */ = {isa = PBXBuildFile; fileRef = 84419AD41B5ABD6D00C26BB2 /* FMDatabase+RSExtras.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 8400AC021E0CFC0700AA7C57 /* FMDatabase+RSExtras.m in Sources */ = {isa = PBXBuildFile; fileRef = 84419AD51B5ABD6D00C26BB2 /* FMDatabase+RSExtras.m */; }; + 8400AC031E0CFC0700AA7C57 /* FMResultSet+RSExtras.h in Headers */ = {isa = PBXBuildFile; fileRef = 84419B031B5ABFF700C26BB2 /* FMResultSet+RSExtras.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 8400AC041E0CFC0700AA7C57 /* FMResultSet+RSExtras.m in Sources */ = {isa = PBXBuildFile; fileRef = 84419B041B5ABFF700C26BB2 /* FMResultSet+RSExtras.m */; }; + 8400AC051E0CFC0700AA7C57 /* NSString+RSDatabase.h in Headers */ = {isa = PBXBuildFile; fileRef = 84419AD81B5ABD7400C26BB2 /* NSString+RSDatabase.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 8400AC061E0CFC0700AA7C57 /* NSString+RSDatabase.m in Sources */ = {isa = PBXBuildFile; fileRef = 84419AD91B5ABD7400C26BB2 /* NSString+RSDatabase.m */; }; + 8400AC071E0CFC1C00AA7C57 /* FMDatabase.h in Headers */ = {isa = PBXBuildFile; fileRef = 84DDF18B1C94FC45005E6CF5 /* FMDatabase.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 8400AC081E0CFC2000AA7C57 /* FMDatabase.m in Sources */ = {isa = PBXBuildFile; fileRef = 84DDF18C1C94FC45005E6CF5 /* FMDatabase.m */; }; + 8400AC091E0CFC2500AA7C57 /* FMDatabaseAdditions.h in Headers */ = {isa = PBXBuildFile; fileRef = 84DDF18D1C94FC45005E6CF5 /* FMDatabaseAdditions.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 8400AC0A1E0CFC2900AA7C57 /* FMDatabaseAdditions.m in Sources */ = {isa = PBXBuildFile; fileRef = 84DDF18E1C94FC45005E6CF5 /* FMDatabaseAdditions.m */; }; + 8400AC0B1E0CFC2C00AA7C57 /* FMResultSet.h in Headers */ = {isa = PBXBuildFile; fileRef = 84DDF1941C94FC45005E6CF5 /* FMResultSet.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 8400AC0C1E0CFC3100AA7C57 /* FMResultSet.m in Sources */ = {isa = PBXBuildFile; fileRef = 84DDF1951C94FC45005E6CF5 /* FMResultSet.m */; }; + 8400AC0F1E0CFC5600AA7C57 /* libsqlite3.tbd in Frameworks */ = {isa = PBXBuildFile; fileRef = 8400AC0E1E0CFC5600AA7C57 /* libsqlite3.tbd */; }; + 8400AC101E0CFD6B00AA7C57 /* RSDatabase.h in Headers */ = {isa = PBXBuildFile; fileRef = 84F22C581B52E0D9000060CE /* RSDatabase.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 84419AD61B5ABD6D00C26BB2 /* FMDatabase+RSExtras.h in Headers */ = {isa = PBXBuildFile; fileRef = 84419AD41B5ABD6D00C26BB2 /* FMDatabase+RSExtras.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 84419AD71B5ABD6D00C26BB2 /* FMDatabase+RSExtras.m in Sources */ = {isa = PBXBuildFile; fileRef = 84419AD51B5ABD6D00C26BB2 /* FMDatabase+RSExtras.m */; }; + 84419ADA1B5ABD7400C26BB2 /* NSString+RSDatabase.h in Headers */ = {isa = PBXBuildFile; fileRef = 84419AD81B5ABD7400C26BB2 /* NSString+RSDatabase.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 84419ADB1B5ABD7400C26BB2 /* NSString+RSDatabase.m in Sources */ = {isa = PBXBuildFile; fileRef = 84419AD91B5ABD7400C26BB2 /* NSString+RSDatabase.m */; }; + 84419AE61B5ABD7F00C26BB2 /* RSDatabaseQueue.h in Headers */ = {isa = PBXBuildFile; fileRef = 84419ADC1B5ABD7F00C26BB2 /* RSDatabaseQueue.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 84419AE71B5ABD7F00C26BB2 /* RSDatabaseQueue.m in Sources */ = {isa = PBXBuildFile; fileRef = 84419ADD1B5ABD7F00C26BB2 /* RSDatabaseQueue.m */; }; + 84419B051B5ABFF700C26BB2 /* FMResultSet+RSExtras.h in Headers */ = {isa = PBXBuildFile; fileRef = 84419B031B5ABFF700C26BB2 /* FMResultSet+RSExtras.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 84419B061B5ABFF700C26BB2 /* FMResultSet+RSExtras.m in Sources */ = {isa = PBXBuildFile; fileRef = 84419B041B5ABFF700C26BB2 /* FMResultSet+RSExtras.m */; }; + 849BF8C61C94FB8E0071D1DA /* libsqlite3.tbd in Frameworks */ = {isa = PBXBuildFile; fileRef = 849BF8C51C94FB8E0071D1DA /* libsqlite3.tbd */; }; + 84DDF1961C94FC45005E6CF5 /* FMDatabase.h in Headers */ = {isa = PBXBuildFile; fileRef = 84DDF18B1C94FC45005E6CF5 /* FMDatabase.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 84DDF1971C94FC45005E6CF5 /* FMDatabase.m in Sources */ = {isa = PBXBuildFile; fileRef = 84DDF18C1C94FC45005E6CF5 /* FMDatabase.m */; }; + 84DDF1981C94FC45005E6CF5 /* FMDatabaseAdditions.h in Headers */ = {isa = PBXBuildFile; fileRef = 84DDF18D1C94FC45005E6CF5 /* FMDatabaseAdditions.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 84DDF1991C94FC45005E6CF5 /* FMDatabaseAdditions.m in Sources */ = {isa = PBXBuildFile; fileRef = 84DDF18E1C94FC45005E6CF5 /* FMDatabaseAdditions.m */; }; + 84DDF19F1C94FC45005E6CF5 /* FMResultSet.h in Headers */ = {isa = PBXBuildFile; fileRef = 84DDF1941C94FC45005E6CF5 /* FMResultSet.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 84DDF1A01C94FC45005E6CF5 /* FMResultSet.m in Sources */ = {isa = PBXBuildFile; fileRef = 84DDF1951C94FC45005E6CF5 /* FMResultSet.m */; }; + 84F22C591B52E0D9000060CE /* RSDatabase.h in Headers */ = {isa = PBXBuildFile; fileRef = 84F22C581B52E0D9000060CE /* RSDatabase.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 84F22C601B52E0D9000060CE /* RSDatabase.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 84F22C551B52E0D9000060CE /* RSDatabase.framework */; }; + 84F22C651B52E0D9000060CE /* RSDatabaseTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 84F22C641B52E0D9000060CE /* RSDatabaseTests.m */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 84F22C611B52E0D9000060CE /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 84F22C4C1B52E0D9000060CE /* Project object */; + proxyType = 1; + remoteGlobalIDString = 84F22C541B52E0D9000060CE; + remoteInfo = RSDatabase; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXFileReference section */ + 8400ABF71E0CFBD800AA7C57 /* RSDatabase.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = RSDatabase.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 8400ABFA1E0CFBD800AA7C57 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 8400AC0E1E0CFC5600AA7C57 /* libsqlite3.tbd */ = {isa = PBXFileReference; lastKnownFileType = "sourcecode.text-based-dylib-definition"; name = libsqlite3.tbd; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS10.2.sdk/usr/lib/libsqlite3.tbd; sourceTree = DEVELOPER_DIR; }; + 84419AD41B5ABD6D00C26BB2 /* FMDatabase+RSExtras.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = "FMDatabase+RSExtras.h"; path = "RSDatabase/FMDatabase+RSExtras.h"; sourceTree = ""; }; + 84419AD51B5ABD6D00C26BB2 /* FMDatabase+RSExtras.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = "FMDatabase+RSExtras.m"; path = "RSDatabase/FMDatabase+RSExtras.m"; sourceTree = ""; }; + 84419AD81B5ABD7400C26BB2 /* NSString+RSDatabase.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = "NSString+RSDatabase.h"; path = "RSDatabase/NSString+RSDatabase.h"; sourceTree = ""; }; + 84419AD91B5ABD7400C26BB2 /* NSString+RSDatabase.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = "NSString+RSDatabase.m"; path = "RSDatabase/NSString+RSDatabase.m"; sourceTree = ""; }; + 84419ADC1B5ABD7F00C26BB2 /* RSDatabaseQueue.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = RSDatabaseQueue.h; path = RSDatabase/RSDatabaseQueue.h; sourceTree = ""; }; + 84419ADD1B5ABD7F00C26BB2 /* RSDatabaseQueue.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = RSDatabaseQueue.m; path = RSDatabase/RSDatabaseQueue.m; sourceTree = ""; }; + 84419B031B5ABFF700C26BB2 /* FMResultSet+RSExtras.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = "FMResultSet+RSExtras.h"; path = "RSDatabase/FMResultSet+RSExtras.h"; sourceTree = ""; }; + 84419B041B5ABFF700C26BB2 /* FMResultSet+RSExtras.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = "FMResultSet+RSExtras.m"; path = "RSDatabase/FMResultSet+RSExtras.m"; sourceTree = ""; }; + 849BF8C51C94FB8E0071D1DA /* libsqlite3.tbd */ = {isa = PBXFileReference; lastKnownFileType = "sourcecode.text-based-dylib-definition"; name = libsqlite3.tbd; path = usr/lib/libsqlite3.tbd; sourceTree = SDKROOT; }; + 84DDF18B1C94FC45005E6CF5 /* FMDatabase.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = FMDatabase.h; sourceTree = ""; }; + 84DDF18C1C94FC45005E6CF5 /* FMDatabase.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = FMDatabase.m; sourceTree = ""; }; + 84DDF18D1C94FC45005E6CF5 /* FMDatabaseAdditions.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = FMDatabaseAdditions.h; sourceTree = ""; }; + 84DDF18E1C94FC45005E6CF5 /* FMDatabaseAdditions.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = FMDatabaseAdditions.m; sourceTree = ""; }; + 84DDF1941C94FC45005E6CF5 /* FMResultSet.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = FMResultSet.h; sourceTree = ""; }; + 84DDF1951C94FC45005E6CF5 /* FMResultSet.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = FMResultSet.m; sourceTree = ""; }; + 84F22C551B52E0D9000060CE /* RSDatabase.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = RSDatabase.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 84F22C581B52E0D9000060CE /* RSDatabase.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = RSDatabase.h; path = RSDatabase/RSDatabase.h; sourceTree = ""; }; + 84F22C5A1B52E0D9000060CE /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; name = Info.plist; path = RSDatabase/Info.plist; sourceTree = ""; }; + 84F22C5F1B52E0D9000060CE /* RSDatabaseTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RSDatabaseTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + 84F22C641B52E0D9000060CE /* RSDatabaseTests.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = RSDatabaseTests.m; sourceTree = ""; }; + 84F22C661B52E0D9000060CE /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 8400ABF31E0CFBD800AA7C57 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 8400AC0F1E0CFC5600AA7C57 /* libsqlite3.tbd in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 84F22C511B52E0D9000060CE /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 849BF8C61C94FB8E0071D1DA /* libsqlite3.tbd in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 84F22C5C1B52E0D9000060CE /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 84F22C601B52E0D9000060CE /* RSDatabase.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 8400ABF81E0CFBD800AA7C57 /* RSDatabaseiOS */ = { + isa = PBXGroup; + children = ( + 8400ABFA1E0CFBD800AA7C57 /* Info.plist */, + ); + path = RSDatabaseiOS; + sourceTree = ""; + }; + 8400AC0D1E0CFC5500AA7C57 /* Frameworks */ = { + isa = PBXGroup; + children = ( + 8400AC0E1E0CFC5600AA7C57 /* libsqlite3.tbd */, + ); + name = Frameworks; + sourceTree = ""; + }; + 84DDF18A1C94FC45005E6CF5 /* FMDB */ = { + isa = PBXGroup; + children = ( + 84DDF18B1C94FC45005E6CF5 /* FMDatabase.h */, + 84DDF18C1C94FC45005E6CF5 /* FMDatabase.m */, + 84DDF18D1C94FC45005E6CF5 /* FMDatabaseAdditions.h */, + 84DDF18E1C94FC45005E6CF5 /* FMDatabaseAdditions.m */, + 84DDF1941C94FC45005E6CF5 /* FMResultSet.h */, + 84DDF1951C94FC45005E6CF5 /* FMResultSet.m */, + ); + name = FMDB; + path = "FMDB/fmdb-master/src/fmdb"; + sourceTree = ""; + }; + 84F22C4B1B52E0D9000060CE = { + isa = PBXGroup; + children = ( + 84F22C581B52E0D9000060CE /* RSDatabase.h */, + 84419ADC1B5ABD7F00C26BB2 /* RSDatabaseQueue.h */, + 84419ADD1B5ABD7F00C26BB2 /* RSDatabaseQueue.m */, + 84419AD41B5ABD6D00C26BB2 /* FMDatabase+RSExtras.h */, + 84419AD51B5ABD6D00C26BB2 /* FMDatabase+RSExtras.m */, + 84419B031B5ABFF700C26BB2 /* FMResultSet+RSExtras.h */, + 84419B041B5ABFF700C26BB2 /* FMResultSet+RSExtras.m */, + 84419AD81B5ABD7400C26BB2 /* NSString+RSDatabase.h */, + 84419AD91B5ABD7400C26BB2 /* NSString+RSDatabase.m */, + 84DDF18A1C94FC45005E6CF5 /* FMDB */, + 84F22C5A1B52E0D9000060CE /* Info.plist */, + 849BF8C51C94FB8E0071D1DA /* libsqlite3.tbd */, + 84F22C631B52E0D9000060CE /* RSDatabaseTests */, + 8400ABF81E0CFBD800AA7C57 /* RSDatabaseiOS */, + 84F22C561B52E0D9000060CE /* Products */, + 8400AC0D1E0CFC5500AA7C57 /* Frameworks */, + ); + sourceTree = ""; + }; + 84F22C561B52E0D9000060CE /* Products */ = { + isa = PBXGroup; + children = ( + 84F22C551B52E0D9000060CE /* RSDatabase.framework */, + 84F22C5F1B52E0D9000060CE /* RSDatabaseTests.xctest */, + 8400ABF71E0CFBD800AA7C57 /* RSDatabase.framework */, + ); + name = Products; + sourceTree = ""; + }; + 84F22C631B52E0D9000060CE /* RSDatabaseTests */ = { + isa = PBXGroup; + children = ( + 84F22C641B52E0D9000060CE /* RSDatabaseTests.m */, + 84F22C661B52E0D9000060CE /* Info.plist */, + ); + path = RSDatabaseTests; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXHeadersBuildPhase section */ + 8400ABF41E0CFBD800AA7C57 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 8400ABFF1E0CFC0700AA7C57 /* RSDatabaseQueue.h in Headers */, + 8400AC0B1E0CFC2C00AA7C57 /* FMResultSet.h in Headers */, + 8400AC031E0CFC0700AA7C57 /* FMResultSet+RSExtras.h in Headers */, + 8400AC091E0CFC2500AA7C57 /* FMDatabaseAdditions.h in Headers */, + 8400AC101E0CFD6B00AA7C57 /* RSDatabase.h in Headers */, + 8400AC071E0CFC1C00AA7C57 /* FMDatabase.h in Headers */, + 8400AC011E0CFC0700AA7C57 /* FMDatabase+RSExtras.h in Headers */, + 8400AC051E0CFC0700AA7C57 /* NSString+RSDatabase.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 84F22C521B52E0D9000060CE /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 84419ADA1B5ABD7400C26BB2 /* NSString+RSDatabase.h in Headers */, + 84419AD61B5ABD6D00C26BB2 /* FMDatabase+RSExtras.h in Headers */, + 84DDF1981C94FC45005E6CF5 /* FMDatabaseAdditions.h in Headers */, + 84DDF1961C94FC45005E6CF5 /* FMDatabase.h in Headers */, + 84DDF19F1C94FC45005E6CF5 /* FMResultSet.h in Headers */, + 84419B051B5ABFF700C26BB2 /* FMResultSet+RSExtras.h in Headers */, + 84419AE61B5ABD7F00C26BB2 /* RSDatabaseQueue.h in Headers */, + 84F22C591B52E0D9000060CE /* RSDatabase.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXHeadersBuildPhase section */ + +/* Begin PBXNativeTarget section */ + 8400ABF61E0CFBD800AA7C57 /* RSDatabaseiOS */ = { + isa = PBXNativeTarget; + buildConfigurationList = 8400ABFE1E0CFBD800AA7C57 /* Build configuration list for PBXNativeTarget "RSDatabaseiOS" */; + buildPhases = ( + 8400ABF21E0CFBD800AA7C57 /* Sources */, + 8400ABF31E0CFBD800AA7C57 /* Frameworks */, + 8400ABF41E0CFBD800AA7C57 /* Headers */, + 8400ABF51E0CFBD800AA7C57 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = RSDatabaseiOS; + productName = RSDatabaseiOS; + productReference = 8400ABF71E0CFBD800AA7C57 /* RSDatabase.framework */; + productType = "com.apple.product-type.framework"; + }; + 84F22C541B52E0D9000060CE /* RSDatabase */ = { + isa = PBXNativeTarget; + buildConfigurationList = 84F22C691B52E0D9000060CE /* Build configuration list for PBXNativeTarget "RSDatabase" */; + buildPhases = ( + 84F22C501B52E0D9000060CE /* Sources */, + 84F22C511B52E0D9000060CE /* Frameworks */, + 84F22C521B52E0D9000060CE /* Headers */, + 84F22C531B52E0D9000060CE /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = RSDatabase; + productName = RSDatabase; + productReference = 84F22C551B52E0D9000060CE /* RSDatabase.framework */; + productType = "com.apple.product-type.framework"; + }; + 84F22C5E1B52E0D9000060CE /* RSDatabaseTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 84F22C6C1B52E0D9000060CE /* Build configuration list for PBXNativeTarget "RSDatabaseTests" */; + buildPhases = ( + 84F22C5B1B52E0D9000060CE /* Sources */, + 84F22C5C1B52E0D9000060CE /* Frameworks */, + 84F22C5D1B52E0D9000060CE /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 84F22C621B52E0D9000060CE /* PBXTargetDependency */, + ); + name = RSDatabaseTests; + productName = RSDatabaseTests; + productReference = 84F22C5F1B52E0D9000060CE /* RSDatabaseTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 84F22C4C1B52E0D9000060CE /* Project object */ = { + isa = PBXProject; + attributes = { + LastUpgradeCheck = 0700; + ORGANIZATIONNAME = "Ranchero Software, LLC"; + TargetAttributes = { + 8400ABF61E0CFBD800AA7C57 = { + CreatedOnToolsVersion = 8.2.1; + DevelopmentTeam = 9C84TZ7Q6Z; + ProvisioningStyle = Automatic; + }; + 84F22C541B52E0D9000060CE = { + CreatedOnToolsVersion = 7.0; + LastSwiftMigration = 0800; + }; + 84F22C5E1B52E0D9000060CE = { + CreatedOnToolsVersion = 7.0; + LastSwiftMigration = 0800; + }; + }; + }; + buildConfigurationList = 84F22C4F1B52E0D9000060CE /* Build configuration list for PBXProject "RSDatabase" */; + compatibilityVersion = "Xcode 3.2"; + developmentRegion = English; + hasScannedForEncodings = 0; + knownRegions = ( + en, + ); + mainGroup = 84F22C4B1B52E0D9000060CE; + productRefGroup = 84F22C561B52E0D9000060CE /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 84F22C541B52E0D9000060CE /* RSDatabase */, + 84F22C5E1B52E0D9000060CE /* RSDatabaseTests */, + 8400ABF61E0CFBD800AA7C57 /* RSDatabaseiOS */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 8400ABF51E0CFBD800AA7C57 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 84F22C531B52E0D9000060CE /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 84F22C5D1B52E0D9000060CE /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 8400ABF21E0CFBD800AA7C57 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 8400AC001E0CFC0700AA7C57 /* RSDatabaseQueue.m in Sources */, + 8400AC061E0CFC0700AA7C57 /* NSString+RSDatabase.m in Sources */, + 8400AC0C1E0CFC3100AA7C57 /* FMResultSet.m in Sources */, + 8400AC021E0CFC0700AA7C57 /* FMDatabase+RSExtras.m in Sources */, + 8400AC081E0CFC2000AA7C57 /* FMDatabase.m in Sources */, + 8400AC041E0CFC0700AA7C57 /* FMResultSet+RSExtras.m in Sources */, + 8400AC0A1E0CFC2900AA7C57 /* FMDatabaseAdditions.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 84F22C501B52E0D9000060CE /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 84419AE71B5ABD7F00C26BB2 /* RSDatabaseQueue.m in Sources */, + 84419AD71B5ABD6D00C26BB2 /* FMDatabase+RSExtras.m in Sources */, + 84419ADB1B5ABD7400C26BB2 /* NSString+RSDatabase.m in Sources */, + 84DDF1971C94FC45005E6CF5 /* FMDatabase.m in Sources */, + 84DDF1A01C94FC45005E6CF5 /* FMResultSet.m in Sources */, + 84419B061B5ABFF700C26BB2 /* FMResultSet+RSExtras.m in Sources */, + 84DDF1991C94FC45005E6CF5 /* FMDatabaseAdditions.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 84F22C5B1B52E0D9000060CE /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 84F22C651B52E0D9000060CE /* RSDatabaseTests.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 84F22C621B52E0D9000060CE /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 84F22C541B52E0D9000060CE /* RSDatabase */; + targetProxy = 84F22C611B52E0D9000060CE /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin XCBuildConfiguration section */ + 8400ABFC1E0CFBD800AA7C57 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + CLANG_ANALYZER_NONNULL = YES; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CODE_SIGN_IDENTITY = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + DEFINES_MODULE = YES; + DEVELOPMENT_TEAM = 9C84TZ7Q6Z; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + INFOPLIST_FILE = RSDatabaseiOS/Info.plist; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 10.2; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + PRODUCT_BUNDLE_IDENTIFIER = com.ranchero.RSDatabaseiOS; + PRODUCT_MODULE_NAME = RSDatabase; + PRODUCT_NAME = RSDatabase; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Debug; + }; + 8400ABFD1E0CFBD800AA7C57 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + CLANG_ANALYZER_NONNULL = YES; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CODE_SIGN_IDENTITY = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + DEFINES_MODULE = YES; + DEVELOPMENT_TEAM = 9C84TZ7Q6Z; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + INFOPLIST_FILE = RSDatabaseiOS/Info.plist; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 10.2; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + PRODUCT_BUNDLE_IDENTIFIER = com.ranchero.RSDatabaseiOS; + PRODUCT_MODULE_NAME = RSDatabase; + PRODUCT_NAME = RSDatabase; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + 84F22C671B52E0D9000060CE /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ALLOW_NON_MODULAR_INCLUDES_IN_FRAMEWORK_MODULES = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 10.11; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = macosx; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 84F22C681B52E0D9000060CE /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ALLOW_NON_MODULAR_INCLUDES_IN_FRAMEWORK_MODULES = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 10.11; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = macosx; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 84F22C6A1B52E0D9000060CE /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + COMBINE_HIDPI_IMAGES = YES; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + FRAMEWORK_VERSION = A; + INFOPLIST_FILE = RSDatabase/Info.plist; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/Frameworks"; + PRODUCT_BUNDLE_IDENTIFIER = com.ranchero.RSDatabase; + PRODUCT_NAME = "$(TARGET_NAME)"; + SKIP_INSTALL = YES; + SWIFT_VERSION = 3.0; + }; + name = Debug; + }; + 84F22C6B1B52E0D9000060CE /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + COMBINE_HIDPI_IMAGES = YES; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + FRAMEWORK_VERSION = A; + INFOPLIST_FILE = RSDatabase/Info.plist; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/Frameworks"; + PRODUCT_BUNDLE_IDENTIFIER = com.ranchero.RSDatabase; + PRODUCT_NAME = "$(TARGET_NAME)"; + SKIP_INSTALL = YES; + SWIFT_VERSION = 3.0; + }; + name = Release; + }; + 84F22C6D1B52E0D9000060CE /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + COMBINE_HIDPI_IMAGES = YES; + INFOPLIST_FILE = RSDatabaseTests/Info.plist; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/../Frameworks"; + PRODUCT_BUNDLE_IDENTIFIER = com.ranchero.RSDatabaseTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 3.0; + }; + name = Debug; + }; + 84F22C6E1B52E0D9000060CE /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + COMBINE_HIDPI_IMAGES = YES; + INFOPLIST_FILE = RSDatabaseTests/Info.plist; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/../Frameworks"; + PRODUCT_BUNDLE_IDENTIFIER = com.ranchero.RSDatabaseTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 3.0; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 8400ABFE1E0CFBD800AA7C57 /* Build configuration list for PBXNativeTarget "RSDatabaseiOS" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 8400ABFC1E0CFBD800AA7C57 /* Debug */, + 8400ABFD1E0CFBD800AA7C57 /* Release */, + ); + defaultConfigurationIsVisible = 0; + }; + 84F22C4F1B52E0D9000060CE /* Build configuration list for PBXProject "RSDatabase" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 84F22C671B52E0D9000060CE /* Debug */, + 84F22C681B52E0D9000060CE /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 84F22C691B52E0D9000060CE /* Build configuration list for PBXNativeTarget "RSDatabase" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 84F22C6A1B52E0D9000060CE /* Debug */, + 84F22C6B1B52E0D9000060CE /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 84F22C6C1B52E0D9000060CE /* Build configuration list for PBXNativeTarget "RSDatabaseTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 84F22C6D1B52E0D9000060CE /* Debug */, + 84F22C6E1B52E0D9000060CE /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 84F22C4C1B52E0D9000060CE /* Project object */; +} diff --git a/Frameworks/RSDatabase/RSDatabase.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/Frameworks/RSDatabase/RSDatabase.xcodeproj/project.xcworkspace/contents.xcworkspacedata new file mode 100755 index 000000000..fe2b5e83d --- /dev/null +++ b/Frameworks/RSDatabase/RSDatabase.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/Frameworks/RSDatabase/RSDatabase/FMDatabase+RSExtras.h b/Frameworks/RSDatabase/RSDatabase/FMDatabase+RSExtras.h new file mode 100755 index 000000000..13499faac --- /dev/null +++ b/Frameworks/RSDatabase/RSDatabase/FMDatabase+RSExtras.h @@ -0,0 +1,84 @@ +// +// FMDatabase+QSKit.h +// RSDatabase +// +// Created by Brent Simmons on 3/3/14. +// Copyright (c) 2014 Ranchero Software, LLC. All rights reserved. +// + +#import "FMDatabase.h" + +@import Foundation; + +typedef enum _RSDatabaseInsertType { + RSDatabaseInsert, + RSDatabaseInsertOrReplace, + RSDatabaseInsertOrIgnore +} RSDatabaseInsertType; + +NS_ASSUME_NONNULL_BEGIN + +@interface FMDatabase (RSExtras) + + +// Keys and table names are assumed to be trusted. Values are not. + + +// delete from tableName where key in (?, ?, ?) + +- (BOOL)rs_deleteRowsWhereKey:(NSString *)key inValues:(NSArray *)values tableName:(NSString *)tableName; + +// delete from tableName where key=? + +- (BOOL)rs_deleteRowsWhereKey:(NSString *)key equalsValue:(id)value tableName:(NSString *)tableName; + + +// select * from tableName where key in (?, ?, ?) + +- (FMResultSet * _Nullable)rs_selectRowsWhereKey:(NSString *)key inValues:(NSArray *)values tableName:(NSString *)tableName; + +// select * from tableName where key = ? + +- (FMResultSet * _Nullable)rs_selectRowsWhereKey:(NSString *)key equalsValue:(id)value tableName:(NSString *)tableName; + +// select * from tableName where key = ? limit 1 + +- (FMResultSet * _Nullable)rs_selectSingleRowWhereKey:(NSString *)key equalsValue:(id)value tableName:(NSString *)tableName; + +// select * from tableName + +- (FMResultSet * _Nullable)rs_selectAllRows:(NSString *)tableName; + +// select key from tableName; + +- (FMResultSet * _Nullable)rs_selectColumnWithKey:(NSString *)key tableName:(NSString *)tableName; + +// select 1 from tableName where key = value limit 1; + +- (BOOL)rs_rowExistsWithValue:(id)value forKey:(NSString *)key tableName:(NSString *)tableName; + +// select 1 from tableName limit 1; + +- (BOOL)rs_tableIsEmpty:(NSString *)tableName; + + +// update tableName set key1=?, key2=? where key = value + +- (BOOL)rs_updateRowsWithDictionary:(NSDictionary *)d whereKey:(NSString *)key equalsValue:(id)value tableName:(NSString *)tableName; + +// update tableName set key1=?, key2=? where key in (?, ?, ?) + +- (BOOL)rs_updateRowsWithDictionary:(NSDictionary *)d whereKey:(NSString *)key inValues:(NSArray *)keyValues tableName:(NSString *)tableName; + +// update tableName set valueKey=? where where key in (?, ?, ?) + +- (BOOL)rs_updateRowsWithValue:(id)value valueKey:(NSString *)valueKey whereKey:(NSString *)key inValues:(NSArray *)keyValues tableName:(NSString *)tableName; + +// insert (or replace, or ignore) into tablename (key1, key2) values (val1, val2) + +- (BOOL)rs_insertRowWithDictionary:(NSDictionary *)d insertType:(RSDatabaseInsertType)insertType tableName:(NSString *)tableName; + + +@end + +NS_ASSUME_NONNULL_END diff --git a/Frameworks/RSDatabase/RSDatabase/FMDatabase+RSExtras.m b/Frameworks/RSDatabase/RSDatabase/FMDatabase+RSExtras.m new file mode 100755 index 000000000..ad648900c --- /dev/null +++ b/Frameworks/RSDatabase/RSDatabase/FMDatabase+RSExtras.m @@ -0,0 +1,182 @@ +// +// FMDatabase+QSKit.m +// RSDatabase +// +// Created by Brent Simmons on 3/3/14. +// Copyright (c) 2014 Ranchero Software, LLC. All rights reserved. +// + +#import "FMDatabase+RSExtras.h" +#import "NSString+RSDatabase.h" + + +#define LOG_SQL 0 + +static void logSQL(NSString *sql) { +#if LOG_SQL + NSLog(@"sql: %@", sql); +#endif +} + + +@implementation FMDatabase (RSExtras) + + + +#pragma mark - Deleting + +- (BOOL)rs_deleteRowsWhereKey:(NSString *)key inValues:(NSArray *)values tableName:(NSString *)tableName { + + if ([values count] < 1) { + return YES; + } + + NSString *placeholders = [NSString rs_SQLValueListWithPlaceholders:values.count]; + NSString *sql = [NSString stringWithFormat:@"delete from %@ where %@ in %@", tableName, key, placeholders]; + logSQL(sql); + + return [self executeUpdate:sql withArgumentsInArray:values]; +} + + +- (BOOL)rs_deleteRowsWhereKey:(NSString *)key equalsValue:(id)value tableName:(NSString *)tableName { + + NSString *sql = [NSString stringWithFormat:@"delete from %@ where %@ = ?", tableName, key]; + logSQL(sql); + return [self executeUpdate:sql, value]; +} + + +#pragma mark - Selecting + +- (FMResultSet *)rs_selectRowsWhereKey:(NSString *)key inValues:(NSArray *)values tableName:(NSString *)tableName { + + NSMutableString *sql = [NSMutableString stringWithFormat:@"select * from %@ where %@ in ", tableName, key]; + NSString *placeholders = [NSString rs_SQLValueListWithPlaceholders:values.count]; + [sql appendString:placeholders]; + logSQL(sql); + + return [self executeQuery:sql withArgumentsInArray:values]; +} + + +- (FMResultSet *)rs_selectRowsWhereKey:(NSString *)key equalsValue:(id)value tableName:(NSString *)tableName { + + NSString *sql = [NSMutableString stringWithFormat:@"select * from %@ where %@ = ?", tableName, key]; + logSQL(sql); + return [self executeQuery:sql, value]; +} + + +- (FMResultSet *)rs_selectSingleRowWhereKey:(NSString *)key equalsValue:(id)value tableName:(NSString *)tableName { + + NSString *sql = [NSMutableString stringWithFormat:@"select * from %@ where %@ = ? limit 1", tableName, key]; + logSQL(sql); + return [self executeQuery:sql, value]; +} + + +- (FMResultSet *)rs_selectAllRows:(NSString *)tableName { + + NSString *sql = [NSString stringWithFormat:@"select * from %@", tableName]; + logSQL(sql); + return [self executeQuery:sql]; +} + + +- (FMResultSet *)rs_selectColumnWithKey:(NSString *)key tableName:(NSString *)tableName { + + NSString *sql = [NSString stringWithFormat:@"select %@ from %@", key, tableName]; + logSQL(sql); + return [self executeQuery:sql]; +} + + +- (BOOL)rs_rowExistsWithValue:(id)value forKey:(NSString *)key tableName:(NSString *)tableName { + + NSString *sql = [NSString stringWithFormat:@"select 1 from %@ where %@ = ? limit 1;", tableName, key]; + logSQL(sql); + FMResultSet *rs = [self executeQuery:sql, value]; + + return [rs next]; +} + + +- (BOOL)rs_tableIsEmpty:(NSString *)tableName { + + NSString *sql = [NSString stringWithFormat:@"select 1 from %@ limit 1;", tableName]; + logSQL(sql); + FMResultSet *rs = [self executeQuery:sql]; + + BOOL isEmpty = YES; + while ([rs next]) { + isEmpty = NO; + } + return isEmpty; +} + + +#pragma mark - Updating + +- (BOOL)rs_updateRowsWithDictionary:(NSDictionary *)d whereKey:(NSString *)key equalsValue:(id)value tableName:(NSString *)tableName { + + return [self rs_updateRowsWithDictionary:d whereKey:key inValues:@[value] tableName:tableName]; +} + + +- (BOOL)rs_updateRowsWithDictionary:(NSDictionary *)d whereKey:(NSString *)key inValues:(NSArray *)keyValues tableName:(NSString *)tableName { + + NSMutableArray *keys = [NSMutableArray new]; + NSMutableArray *values = [NSMutableArray new]; + + [d enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL * _Nonnull stop) { + [keys addObject:key]; + [values addObject:obj]; + }]; + + NSString *keyPlaceholders = [NSString rs_SQLKeyPlaceholderPairsWithKeys:keys]; + NSString *keyValuesPlaceholder = [NSString rs_SQLValueListWithPlaceholders:keyValues.count]; + NSString *sql = [NSString stringWithFormat:@"update %@ set %@ where %@ in %@", tableName, keyPlaceholders, key, keyValuesPlaceholder]; + + NSMutableArray *parameters = values; + [parameters addObjectsFromArray:keyValues]; + logSQL(sql); + + return [self executeUpdate:sql withArgumentsInArray:parameters]; +} + + +- (BOOL)rs_updateRowsWithValue:(id)value valueKey:(NSString *)valueKey whereKey:(NSString *)key inValues:(NSArray *)keyValues tableName:(NSString *)tableName { + + NSDictionary *d = @{valueKey: value}; + return [self rs_updateRowsWithDictionary:d whereKey:key inValues:keyValues tableName:tableName]; +} + + +#pragma mark - Saving + +- (BOOL)rs_insertRowWithDictionary:(NSDictionary *)d insertType:(RSDatabaseInsertType)insertType tableName:(NSString *)tableName { + + NSArray *keys = d.allKeys; + NSArray *values = [d objectsForKeys:keys notFoundMarker:[NSNull null]]; + + NSString *sqlKeysList = [NSString rs_SQLKeysListWithArray:keys]; + NSString *placeholders = [NSString rs_SQLValueListWithPlaceholders:values.count]; + + NSString *sqlBeginning = @"insert into "; + if (insertType == RSDatabaseInsertOrReplace) { + sqlBeginning = @"insert or replace into "; + } + else if (insertType == RSDatabaseInsertOrIgnore) { + sqlBeginning = @"insert or ignore into "; + } + + NSString *sql = [NSString stringWithFormat:@"%@ %@ %@ values %@", sqlBeginning, tableName, sqlKeysList, placeholders]; + logSQL(sql); + + return [self executeUpdate:sql withArgumentsInArray:values]; +} + + +@end + diff --git a/Frameworks/RSDatabase/RSDatabase/FMResultSet+RSExtras.h b/Frameworks/RSDatabase/RSDatabase/FMResultSet+RSExtras.h new file mode 100755 index 000000000..0d28430c8 --- /dev/null +++ b/Frameworks/RSDatabase/RSDatabase/FMResultSet+RSExtras.h @@ -0,0 +1,19 @@ +// +// FMResultSet+RSExtras.h +// RSDatabase +// +// Created by Brent Simmons on 2/19/13. +// Copyright (c) 2013 Ranchero Software, LLC. All rights reserved. +// + + +#import "FMResultSet.h" + +@interface FMResultSet (RSExtras) + + +- (NSArray *)rs_arrayForSingleColumnResultSet; // Doesn't handle dates. + +- (NSSet *)rs_setForSingleColumnResultSet; + +@end diff --git a/Frameworks/RSDatabase/RSDatabase/FMResultSet+RSExtras.m b/Frameworks/RSDatabase/RSDatabase/FMResultSet+RSExtras.m new file mode 100755 index 000000000..c440f03aa --- /dev/null +++ b/Frameworks/RSDatabase/RSDatabase/FMResultSet+RSExtras.m @@ -0,0 +1,51 @@ +// +// FMResultSet+RSExtras.m +// RSDatabase +// +// Created by Brent Simmons on 2/19/13. +// Copyright (c) 2013 Ranchero Software, LLC. All rights reserved. +// + +#import "FMResultSet+RSExtras.h" + + +@implementation FMResultSet (RSExtras) + + +- (id)valueForKey:(NSString *)key { + + if ([key containsString:@"Date"] || [key containsString:@"date"]) { + return [self dateForColumn:key]; + } + + return [self objectForColumnName:key]; +} + + +- (NSArray *)rs_arrayForSingleColumnResultSet { + + NSMutableArray *results = [NSMutableArray new]; + + while ([self next]) { + id oneObject = [self objectForColumnIndex:0]; + [results addObject:oneObject]; + } + + return [results copy]; +} + + +- (NSSet *)rs_setForSingleColumnResultSet { + + NSMutableSet *results = [NSMutableSet new]; + + while ([self next]) { + id oneObject = [self objectForColumnIndex:0]; + [results addObject:oneObject]; + } + + return [results copy]; +} + + +@end diff --git a/Frameworks/RSDatabase/RSDatabase/Info.plist b/Frameworks/RSDatabase/RSDatabase/Info.plist new file mode 100755 index 000000000..87b01750b --- /dev/null +++ b/Frameworks/RSDatabase/RSDatabase/Info.plist @@ -0,0 +1,28 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.0 + CFBundleSignature + ???? + CFBundleVersion + $(CURRENT_PROJECT_VERSION) + NSHumanReadableCopyright + Copyright © 2015 Ranchero Software, LLC. All rights reserved. + NSPrincipalClass + + + diff --git a/Frameworks/RSDatabase/RSDatabase/NSString+RSDatabase.h b/Frameworks/RSDatabase/RSDatabase/NSString+RSDatabase.h new file mode 100755 index 000000000..035edb982 --- /dev/null +++ b/Frameworks/RSDatabase/RSDatabase/NSString+RSDatabase.h @@ -0,0 +1,33 @@ +// +// NSString+RSDatabase.h +// RSDatabase +// +// Created by Brent Simmons on 3/27/15. +// Copyright (c) 2015 Ranchero Software, LLC. All rights reserved. +// + +@import Foundation; + + +@interface NSString (QSDatabase) + + +/*Returns @"(?, ?, ?)" -- where number of ? spots is specified by numberOfValues. + numberOfValues should be greater than 0. Triggers an NSParameterAssert if not.*/ + ++ (NSString *)rs_SQLValueListWithPlaceholders:(NSUInteger)numberOfValues; + + +/*Returns @"(someColumn, anotherColumm, thirdColumn)" -- using passed-in keys. + It's essential that you trust keys. They must not be user input. + Triggers an NSParameterAssert if keys are empty.*/ + ++ (NSString *)rs_SQLKeysListWithArray:(NSArray *)keys; + + +/*Returns @"key1=?, key2=?" using passed-in keys. Keys must be trusted.*/ + ++ (NSString *)rs_SQLKeyPlaceholderPairsWithKeys:(NSArray *)keys; + + +@end diff --git a/Frameworks/RSDatabase/RSDatabase/NSString+RSDatabase.m b/Frameworks/RSDatabase/RSDatabase/NSString+RSDatabase.m new file mode 100755 index 000000000..b82cbf723 --- /dev/null +++ b/Frameworks/RSDatabase/RSDatabase/NSString+RSDatabase.m @@ -0,0 +1,120 @@ +// +// NSString+RSDatabase.m +// RSDatabase +// +// Created by Brent Simmons on 3/27/15. +// Copyright (c) 2015 Ranchero Software, LLC. All rights reserved. +// + +#import "NSString+RSDatabase.h" + + +@implementation NSString (RSDatabase) + + ++ (NSString *)rs_SQLValueListWithPlaceholders:(NSUInteger)numberOfValues { + + // @"(?, ?, ?)" + + NSParameterAssert(numberOfValues > 0); + if (numberOfValues < 1) { + return nil; + } + + static NSMutableDictionary *cache = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + cache = [NSMutableDictionary new]; + }); + + NSNumber *cacheKey = @(numberOfValues); + NSString *cachedString = cache[cacheKey]; + if (cachedString) { + return cachedString; + } + + NSMutableString *s = [[NSMutableString alloc] initWithString:@"("]; + NSUInteger i = 0; + + for (i = 0; i < numberOfValues; i++) { + + [s appendString:@"?"]; + BOOL isLast = (i == (numberOfValues - 1)); + if (!isLast) { + [s appendString:@", "]; + } + } + + [s appendString:@")"]; + + cache[cacheKey] = s; + + return s; +} + + ++ (NSString *)rs_SQLKeysListWithArray:(NSArray *)keys { + + NSParameterAssert(keys.count > 0); + + static NSMutableDictionary *cache = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + cache = [NSMutableDictionary new]; + }); + + NSArray *cacheKey = keys; + NSString *cachedString = cache[cacheKey]; + if (cachedString) { + return cachedString; + } + + NSString *s = [NSString stringWithFormat:@"(%@)", [keys componentsJoinedByString:@", "]]; + + cache[cacheKey] = s; + + return s; +} + + ++ (NSString *)rs_SQLKeyPlaceholderPairsWithKeys:(NSArray *)keys { + + // key1=?, key2=? + + NSParameterAssert(keys.count > 0); + + static NSMutableDictionary *cache = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + cache = [NSMutableDictionary new]; + }); + + NSArray *cacheKey = keys; + NSString *cachedString = cache[cacheKey]; + if (cachedString) { + return cachedString; + } + + NSMutableString *s = [NSMutableString stringWithString:@""]; + + NSUInteger i = 0; + NSUInteger numberOfKeys = [keys count]; + + for (i = 0; i < numberOfKeys; i++) { + + NSString *oneKey = keys[i]; + [s appendString:oneKey]; + [s appendString:@"=?"]; + BOOL isLast = (i == (numberOfKeys - 1)); + if (!isLast) { + [s appendString:@", "]; + } + } + + cache[cacheKey] = s; + + return s; +} + + +@end diff --git a/Frameworks/RSDatabase/RSDatabase/RSDatabase.h b/Frameworks/RSDatabase/RSDatabase/RSDatabase.h new file mode 100755 index 000000000..8e053a947 --- /dev/null +++ b/Frameworks/RSDatabase/RSDatabase/RSDatabase.h @@ -0,0 +1,26 @@ +// +// RSDatabase.h +// RSDatabase +// +// Created by Brent Simmons on 7/12/15. +// Copyright © 2015 Ranchero Software, LLC. All rights reserved. +// + +@import Foundation; + +// FMDB - see https://github.com/ccgus/fmdb for the original. + +#import +#import +#import + +// Categories + +#import +#import +#import + +// RSDatabase + +#import + diff --git a/Frameworks/RSDatabase/RSDatabase/RSDatabaseQueue.h b/Frameworks/RSDatabase/RSDatabase/RSDatabaseQueue.h new file mode 100755 index 000000000..edfb2dd0e --- /dev/null +++ b/Frameworks/RSDatabase/RSDatabase/RSDatabaseQueue.h @@ -0,0 +1,57 @@ +// +// RSDatabaseQueue.h +// RSDatabase +// +// Created by Brent Simmons on 10/19/13. +// Copyright (c) 2013 Ranchero Software, LLC. All rights reserved. +// + +@import Foundation; +#import "FMDatabase.h" + +@class RSDatabaseQueue; + +NS_ASSUME_NONNULL_BEGIN + +@protocol RSDatabaseQueueDelegate + +@optional + +- (void)makeFunctionsForDatabase:(FMDatabase *)database queue:(RSDatabaseQueue *)queue; + +@end + + +// Everything runs on a serial queue. + +typedef void (^RSDatabaseBlock)(FMDatabase * __nonnull database); + + +@interface RSDatabaseQueue : NSObject + +@property (nonatomic, strong, readonly) NSString *databasePath; // For debugging use, so you can open the database in sqlite3. + +- (instancetype)initWithFilepath:(NSString *)filepath excludeFromBackup:(BOOL)excludeFromBackup; + +@property (nonatomic, weak) id delegate; + +// You can feed it the contents of a file that includes comments, etc. +// Lines that start with case-insensitive "create " are executed. +- (void)createTablesUsingStatements:(NSString *)createStatements; + +- (void)update:(RSDatabaseBlock)updateBlock; + +- (void)runInDatabase:(RSDatabaseBlock)databaseBlock; // Same as update, but no transaction. + +- (void)fetch:(RSDatabaseBlock)fetchBlock; +- (void)fetchSync:(RSDatabaseBlock)fetchBlock; + +- (void)vacuum; +- (void)vacuumIfNeeded; // defaultsKey = @"lastVacuumDate"; interval is 6 days. +- (void)vacuumIfNeeded:(NSString *)defaultsKey intervalBetweenVacuums:(NSTimeInterval)intervalBetweenVacuums; + +- (NSArray *)arrayWithSingleColumnResultSet:(FMResultSet *)rs; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Frameworks/RSDatabase/RSDatabase/RSDatabaseQueue.m b/Frameworks/RSDatabase/RSDatabase/RSDatabaseQueue.m new file mode 100755 index 000000000..5532d4265 --- /dev/null +++ b/Frameworks/RSDatabase/RSDatabase/RSDatabaseQueue.m @@ -0,0 +1,182 @@ +// +// RSDatabaseQueue.m +// RSDatabase +// +// Created by Brent Simmons on 10/19/13. +// Copyright (c) 2013 Ranchero Software, LLC. All rights reserved. +// + +#import "RSDatabaseQueue.h" + + +@interface RSDatabaseQueue () + +@property (nonatomic, strong, readwrite) NSString *databasePath; +@property (nonatomic, assign) BOOL excludeFromBackup; +@property (nonatomic, strong, readonly) dispatch_queue_t serialDispatchQueue; + +@end + + +@implementation RSDatabaseQueue + + +#pragma mark - Init + +- (instancetype)initWithFilepath:(NSString *)filepath excludeFromBackup:(BOOL)excludeFromBackup { + + self = [super init]; + if (self == nil) + return self; + + _databasePath = filepath; + + _serialDispatchQueue = dispatch_queue_create([[NSString stringWithFormat:@"RSDatabaseQueue serial queue - %@", filepath.lastPathComponent] UTF8String], DISPATCH_QUEUE_SERIAL); + + _excludeFromBackup = excludeFromBackup; + + return self; +} + + +#pragma mark - Database + +- (FMDatabase *)database { + + /*I've always done it this way -- kept a per-thread database in the threadDictionary -- and I know it's solid. Maybe it's not necessary with a serial queue, but my understanding was that SQLite wanted a different database per thread (and a serial queue may run on different threads).*/ + + NSMutableDictionary *threadDictionary = [[NSThread currentThread] threadDictionary]; + FMDatabase *database = threadDictionary[self.databasePath]; + + if (!database) { + + database = [FMDatabase databaseWithPath:self.databasePath]; + [database open]; + [database executeUpdate:@"PRAGMA synchronous = 1;"]; + [database setShouldCacheStatements:YES]; +// database.traceExecution = YES; + + if ([self.delegate respondsToSelector:@selector(makeFunctionsForDatabase:queue:)]) { + [self.delegate makeFunctionsForDatabase:database queue:self]; + } + + threadDictionary[self.databasePath] = database; + + if (self.excludeFromBackup) { + + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + NSURL *URL = [NSURL fileURLWithPath:self.databasePath isDirectory:NO]; + NSError *error = nil; + [URL setResourceValue:@YES forKey:NSURLIsExcludedFromBackupKey error:&error]; + }); + } + } + + return database; +} + + +#pragma mark - API + +- (void)createTablesUsingStatements:(NSString *)createStatements { + + [self runInDatabase:^(FMDatabase *database) { + + [createStatements enumerateLinesUsingBlock:^(NSString *line, BOOL *stop) { + if ([line.lowercaseString hasPrefix:@"create "]) { + [database executeUpdate:line]; + } + }]; + }]; +} + + +- (void)update:(RSDatabaseBlock)updateBlock { + + dispatch_async(self.serialDispatchQueue, ^{ + + @autoreleasepool { + FMDatabase *database = [self database]; + [database beginTransaction]; + updateBlock(database); + [database commit]; + } + }); +} + + +- (void)runInDatabase:(RSDatabaseBlock)databaseBlock { + + dispatch_async(self.serialDispatchQueue, ^{ + @autoreleasepool { + databaseBlock([self database]); + } + }); +} + + +- (void)fetch:(RSDatabaseBlock)fetchBlock { + + [self runInDatabase:fetchBlock]; +} + + +- (void)fetchSync:(RSDatabaseBlock)fetchBlock { + + dispatch_sync(self.serialDispatchQueue, ^{ + @autoreleasepool { + fetchBlock([self database]); + } + }); +} + + +- (void)vacuum { + + dispatch_async(self.serialDispatchQueue, ^{ + @autoreleasepool { + [[self database] executeUpdate:@"vacuum;"]; + } + }); +} + +- (void)vacuumIfNeeded { + + NSTimeInterval interval = (24 * 60 * 60) * 6; // 6 days + [self vacuumIfNeeded:@"lastVacuumDate" intervalBetweenVacuums:interval]; +} + + +- (void)vacuumIfNeeded:(NSString *)defaultsKey intervalBetweenVacuums:(NSTimeInterval)intervalBetweenVacuums { + + NSDate *lastVacuumDate = [[NSUserDefaults standardUserDefaults] objectForKey:defaultsKey]; + if (!lastVacuumDate || ![lastVacuumDate isKindOfClass:[NSDate class]]) { + [[NSUserDefaults standardUserDefaults] setObject:[NSDate date] forKey:defaultsKey]; + return; + } + + NSDate *cutoffDate = [[NSDate date] dateByAddingTimeInterval: -(intervalBetweenVacuums)]; + if ([cutoffDate earlierDate:lastVacuumDate] == lastVacuumDate) { + [[NSUserDefaults standardUserDefaults] setObject:[NSDate date] forKey:defaultsKey]; + [self vacuum]; + } +} + + +- (NSArray *)arrayWithSingleColumnResultSet:(FMResultSet *)rs { + + NSMutableArray *results = [NSMutableArray new]; + while ([rs next]) { + id oneObject = [rs objectForColumnIndex:0]; + if (oneObject) { + [results addObject:oneObject]; + } + } + + return [results copy]; +} + + +@end + diff --git a/Frameworks/RSDatabase/RSDatabaseTests/Info.plist b/Frameworks/RSDatabase/RSDatabaseTests/Info.plist new file mode 100755 index 000000000..ba72822e8 --- /dev/null +++ b/Frameworks/RSDatabase/RSDatabaseTests/Info.plist @@ -0,0 +1,24 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + BNDL + CFBundleShortVersionString + 1.0 + CFBundleSignature + ???? + CFBundleVersion + 1 + + diff --git a/Frameworks/RSDatabase/RSDatabaseTests/RSDatabaseTests.m b/Frameworks/RSDatabase/RSDatabaseTests/RSDatabaseTests.m new file mode 100755 index 000000000..68a4c412a --- /dev/null +++ b/Frameworks/RSDatabase/RSDatabaseTests/RSDatabaseTests.m @@ -0,0 +1,42 @@ +// +// RSDatabaseTests.m +// RSDatabaseTests +// +// Created by Brent Simmons on 7/12/15. +// Copyright © 2015 Ranchero Software, LLC. All rights reserved. +// + +#import + +@interface RSDatabaseTests : XCTestCase + +@end + +@implementation RSDatabaseTests + +// Seems like there should be some tests here. +// And yet there aren’t any. + +- (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)testExample { + // This is an example of a functional test case. + // Use XCTAssert and related functions to verify your tests produce the correct results. +} + +- (void)testPerformanceExample { + // This is an example of a performance test case. + [self measureBlock:^{ + // Put the code you want to measure the time of here. + }]; +} + +@end diff --git a/Frameworks/RSDatabase/RSDatabaseiOS/Info.plist b/Frameworks/RSDatabase/RSDatabaseiOS/Info.plist new file mode 100755 index 000000000..188a3f8de --- /dev/null +++ b/Frameworks/RSDatabase/RSDatabaseiOS/Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleDisplayName + RSDatabase + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.0 + CFBundleVersion + $(CURRENT_PROJECT_VERSION) + NSPrincipalClass + + +