Break the build. Continue switch to submodules. Remove local copy of RSDatabase.

This commit is contained in:
Brent Simmons 2018-06-18 16:59:22 -07:00
parent 72a89dd048
commit ecfee69fdf
83 changed files with 0 additions and 13731 deletions

View File

@ -109,8 +109,6 @@
84AD1EAA2031617300BC20B7 /* FolderPasteboardWriter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 84AD1EA92031617300BC20B7 /* FolderPasteboardWriter.swift */; };
84AD1EBA2031649C00BC20B7 /* SmartFeedPasteboardWriter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 84AD1EB92031649C00BC20B7 /* SmartFeedPasteboardWriter.swift */; };
84AD1EBC2032AF5C00BC20B7 /* SidebarOutlineDataSource.swift in Sources */ = {isa = PBXBuildFile; fileRef = 84AD1EBB2032AF5C00BC20B7 /* SidebarOutlineDataSource.swift */; };
84B06FB21ED37DBD00F0B54B /* RSDatabase.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 84B06F9D1ED37DA000F0B54B /* RSDatabase.framework */; };
84B06FB31ED37DBD00F0B54B /* RSDatabase.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 84B06F9D1ED37DA000F0B54B /* RSDatabase.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; };
84B06FCF1ED37F7D00F0B54B /* DB5.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 84B06FCC1ED37F7200F0B54B /* DB5.framework */; };
84B06FD01ED37F7D00F0B54B /* DB5.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 84B06FCC1ED37F7200F0B54B /* DB5.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; };
84B06FE91ED3803A00F0B54B /* RSFeedFinder.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 84B06FE61ED3803200F0B54B /* RSFeedFinder.framework */; };
@ -258,34 +256,6 @@
remoteGlobalIDString = 849C645F1ED37A5D003D8FC0;
remoteInfo = Evergreen;
};
84B06F9C1ED37DA000F0B54B /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 84B06F961ED37DA000F0B54B /* RSDatabase.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 84F22C551B52E0D9000060CE;
remoteInfo = RSDatabase;
};
84B06F9E1ED37DA000F0B54B /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 84B06F961ED37DA000F0B54B /* RSDatabase.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 84F22C5F1B52E0D9000060CE;
remoteInfo = RSDatabaseTests;
};
84B06FA01ED37DA000F0B54B /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 84B06F961ED37DA000F0B54B /* RSDatabase.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 8400ABF71E0CFBD800AA7C57;
remoteInfo = RSDatabaseiOS;
};
84B06FB41ED37DBD00F0B54B /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 84B06F961ED37DA000F0B54B /* RSDatabase.xcodeproj */;
proxyType = 1;
remoteGlobalIDString = 84F22C541B52E0D9000060CE;
remoteInfo = RSDatabase;
};
84B06FCB1ED37F7200F0B54B /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 84B06FC61ED37F7200F0B54B /* DB5.xcodeproj */;
@ -361,7 +331,6 @@
84BB4B781F11753300858766 /* Data.framework in Embed Frameworks */,
84FB9A301EDCD6C4003D53B9 /* Sparkle.framework in Embed Frameworks */,
846E77421F6EF6A100A165E2 /* Database.framework in Embed Frameworks */,
84B06FB31ED37DBD00F0B54B /* RSDatabase.framework in Embed Frameworks */,
84B06FEA1ED3803A00F0B54B /* RSFeedFinder.framework in Embed Frameworks */,
846E773E1F6EF67A00A165E2 /* Account.framework in Embed Frameworks */,
84B06FD01ED37F7D00F0B54B /* DB5.framework in Embed Frameworks */,
@ -512,7 +481,6 @@
84AD1EA92031617300BC20B7 /* FolderPasteboardWriter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FolderPasteboardWriter.swift; sourceTree = "<group>"; };
84AD1EB92031649C00BC20B7 /* SmartFeedPasteboardWriter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SmartFeedPasteboardWriter.swift; sourceTree = "<group>"; };
84AD1EBB2032AF5C00BC20B7 /* SidebarOutlineDataSource.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SidebarOutlineDataSource.swift; sourceTree = "<group>"; };
84B06F961ED37DA000F0B54B /* RSDatabase.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = RSDatabase.xcodeproj; path = Frameworks/RSDatabase/RSDatabase.xcodeproj; sourceTree = "<group>"; };
84B06FC61ED37F7200F0B54B /* DB5.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = DB5.xcodeproj; path = Frameworks/DB5/DB5.xcodeproj; sourceTree = "<group>"; };
84B06FE01ED3803200F0B54B /* RSFeedFinder.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = RSFeedFinder.xcodeproj; path = Frameworks/RSFeedFinder/RSFeedFinder.xcodeproj; sourceTree = "<group>"; };
84B7178B201E66580091657D /* SidebarViewController+ContextualMenus.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "SidebarViewController+ContextualMenus.swift"; sourceTree = "<group>"; };
@ -612,7 +580,6 @@
buildActionMask = 2147483647;
files = (
84BB4B771F11753300858766 /* Data.framework in Frameworks */,
84B06FB21ED37DBD00F0B54B /* RSDatabase.framework in Frameworks */,
846E77411F6EF6A100A165E2 /* Database.framework in Frameworks */,
84B06FE91ED3803A00F0B54B /* RSFeedFinder.framework in Frameworks */,
84B06FCF1ED37F7D00F0B54B /* DB5.framework in Frameworks */,
@ -1001,7 +968,6 @@
846E77161F6EF5D000A165E2 /* Database.xcodeproj */,
84BB4B611F1174D400858766 /* Data.xcodeproj */,
84B06FC61ED37F7200F0B54B /* DB5.xcodeproj */,
84B06F961ED37DA000F0B54B /* RSDatabase.xcodeproj */,
84B06FE01ED3803200F0B54B /* RSFeedFinder.xcodeproj */,
);
sourceTree = "<group>";
@ -1047,16 +1013,6 @@
path = Evergreen/Dinosaurs;
sourceTree = "<group>";
};
84B06F971ED37DA000F0B54B /* Products */ = {
isa = PBXGroup;
children = (
84B06F9D1ED37DA000F0B54B /* RSDatabase.framework */,
84B06F9F1ED37DA000F0B54B /* RSDatabaseTests.xctest */,
84B06FA11ED37DA000F0B54B /* RSDatabase.framework */,
);
name = Products;
sourceTree = "<group>";
};
84B06FC71ED37F7200F0B54B /* Products */ = {
isa = PBXGroup;
children = (
@ -1293,7 +1249,6 @@
buildRules = (
);
dependencies = (
84B06FB51ED37DBD00F0B54B /* PBXTargetDependency */,
84B06FD21ED37F7D00F0B54B /* PBXTargetDependency */,
84B06FEC1ED3803A00F0B54B /* PBXTargetDependency */,
84BB4B7A1F11753300858766 /* PBXTargetDependency */,
@ -1392,10 +1347,6 @@
ProductGroup = 84B06FC71ED37F7200F0B54B /* Products */;
ProjectRef = 84B06FC61ED37F7200F0B54B /* DB5.xcodeproj */;
},
{
ProductGroup = 84B06F971ED37DA000F0B54B /* Products */;
ProjectRef = 84B06F961ED37DA000F0B54B /* RSDatabase.xcodeproj */;
},
{
ProductGroup = 84B06FE11ED3803200F0B54B /* Products */;
ProjectRef = 84B06FE01ED3803200F0B54B /* RSFeedFinder.xcodeproj */;
@ -1441,27 +1392,6 @@
remoteRef = 846E773B1F6EF5D700A165E2 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
84B06F9D1ED37DA000F0B54B /* RSDatabase.framework */ = {
isa = PBXReferenceProxy;
fileType = wrapper.framework;
path = RSDatabase.framework;
remoteRef = 84B06F9C1ED37DA000F0B54B /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
84B06F9F1ED37DA000F0B54B /* RSDatabaseTests.xctest */ = {
isa = PBXReferenceProxy;
fileType = wrapper.cfbundle;
path = RSDatabaseTests.xctest;
remoteRef = 84B06F9E1ED37DA000F0B54B /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
84B06FA11ED37DA000F0B54B /* RSDatabase.framework */ = {
isa = PBXReferenceProxy;
fileType = wrapper.framework;
path = RSDatabase.framework;
remoteRef = 84B06FA01ED37DA000F0B54B /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
84B06FCC1ED37F7200F0B54B /* DB5.framework */ = {
isa = PBXReferenceProxy;
fileType = wrapper.framework;
@ -1780,11 +1710,6 @@
target = 849C645F1ED37A5D003D8FC0 /* Evergreen */;
targetProxy = 849C64721ED37A5D003D8FC0 /* PBXContainerItemProxy */;
};
84B06FB51ED37DBD00F0B54B /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
name = RSDatabase;
targetProxy = 84B06FB41ED37DBD00F0B54B /* PBXContainerItemProxy */;
};
84B06FD21ED37F7D00F0B54B /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
name = DB5;

View File

@ -1,60 +0,0 @@
# 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/

View File

@ -1,115 +0,0 @@
//
// DatabaseTable.swift
// RSDatabase
//
// Created by Brent Simmons on 7/16/17.
// Copyright © 2017 Ranchero Software, LLC. All rights reserved.
//
import Foundation
public protocol DatabaseTable {
var name: String { get }
}
public extension DatabaseTable {
// MARK: Fetching
public func selectRowsWhere(key: String, equals value: Any, in database: FMDatabase) -> FMResultSet? {
return database.rs_selectRowsWhereKey(key, equalsValue: value, tableName: name)
}
public func selectRowsWhere(key: String, inValues values: [Any], in database: FMDatabase) -> FMResultSet? {
if values.isEmpty {
return nil
}
return database.rs_selectRowsWhereKey(key, inValues: values, tableName: name)
}
// MARK: Deleting
public func deleteRowsWhere(key: String, equalsAnyValue values: [Any], in database: FMDatabase) {
if values.isEmpty {
return
}
database.rs_deleteRowsWhereKey(key, inValues: values, tableName: name)
}
// MARK: Updating
public func updateRowsWithValue(_ value: Any, valueKey: String, whereKey: String, matches: [Any], database: FMDatabase) {
let _ = database.rs_updateRows(withValue: value, valueKey: valueKey, whereKey: whereKey, inValues: matches, tableName: self.name)
}
public func updateRowsWithDictionary(_ dictionary: NSDictionary, whereKey: String, matches: Any, database: FMDatabase) {
let _ = database.rs_updateRows(with: dictionary as! [AnyHashable : Any], whereKey: whereKey, equalsValue: matches, tableName: self.name)
}
// MARK: Saving
public func insertRows(_ dictionaries: [NSDictionary], insertType: RSDatabaseInsertType, in database: FMDatabase) {
dictionaries.forEach { (oneDictionary) in
let _ = database.rs_insertRow(with: oneDictionary as [NSObject: AnyObject], insertType: insertType, tableName: self.name)
}
}
// MARK: Counting
func numberWithCountResultSet(_ resultSet: FMResultSet) -> Int {
guard resultSet.next() else {
return 0
}
return Int(resultSet.int(forColumnIndex: 0))
}
func numberWithSQLAndParameters(_ sql: String, _ parameters: [Any], in database: FMDatabase) -> Int {
if let resultSet = database.executeQuery(sql, withArgumentsIn: parameters) {
return numberWithCountResultSet(resultSet)
}
return 0
}
// MARK: Mapping
func mapResultSet<T>(_ resultSet: FMResultSet, _ callback: (_ resultSet: FMResultSet) -> T?) -> [T] {
var objects = [T]()
while resultSet.next() {
if let obj = callback(resultSet) {
objects += [obj]
}
}
return objects
}
}
public extension FMResultSet {
public func compactMap<T>(_ callback: (_ row: FMResultSet) -> T?) -> [T] {
var objects = [T]()
while next() {
if let obj = callback(self) {
objects += [obj]
}
}
close()
return objects
}
public func mapToSet<T>(_ callback: (_ row: FMResultSet) -> T?) -> Set<T> {
return Set(compactMap(callback))
}
}

View File

@ -1,13 +0,0 @@
//
// FMDB.h
// FMDB
//
// Created by Brent Simmons on 7/18/15.
// Copyright © 2015 Ranchero Software, LLC. All rights reserved.
//
@import Foundation;
#import <FMDB/FMDatabase.h>
#import <FMDB/FMResultSet.h>
#import <FMDB/FMDatabaseAdditions.h>

View File

@ -1,28 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>$(CURRENT_PROJECT_VERSION)</string>
<key>NSHumanReadableCopyright</key>
<string>Copyright © 2015 Ranchero Software, LLC. All rights reserved.</string>
<key>NSPrincipalClass</key>
<string></string>
</dict>
</plist>

View File

@ -1,8 +0,0 @@
.DS_Store
build
*.xcodeproj/*.pbxuser
*.xcodeproj/*.perspectivev3
*.xcodeproj/xcuserdata
fmdb.xcodeproj/*.mode1v3
*.xcodeproj/project.xcworkspace/xcuserdata/
fmdb.xcodeproj/project.xcworkspace

View File

@ -1,5 +0,0 @@
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/"

View File

@ -1,327 +0,0 @@
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. <https://github.com/ccgus/fmdb/pull/150>
- 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! <https://github.com/ccgus/fmdb/pull/135>
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

View File

@ -1,50 +0,0 @@
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!)

View File

@ -1,53 +0,0 @@
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

View File

@ -1,28 +0,0 @@
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.

View File

@ -1,369 +0,0 @@
# 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 `%%`.
<h2 id="threads">Using FMDatabaseQueue and Thread Safety.</h2>
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.)

View File

@ -1,24 +0,0 @@
//
// FMDBTempDBTests.h
// fmdb
//
// Created by Graham Dennis on 24/11/2013.
//
//
#import <XCTest/XCTest.h>
#import "FMDatabase.h"
@protocol FMDBTempDBTests <NSObject>
@optional
+ (void)populateDatabase:(FMDatabase *)database;
@end
@interface FMDBTempDBTests : XCTestCase <FMDBTempDBTests>
@property FMDatabase *db;
@property (readonly) NSString *databasePath;
@end

View File

@ -1,63 +0,0 @@
//
// 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

View File

@ -1,123 +0,0 @@
//
// FMDatabaseAdditionsTests.m
// fmdb
//
// Created by Graham Dennis on 24/11/2013.
//
//
#import <XCTest/XCTest.h>
#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

View File

@ -1,157 +0,0 @@
//
// 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 <FMTokenizerDelegate>
+ (instancetype)tokenizerWithBaseTokenizer:(id<FMTokenizerDelegate>)tokenizer;
@property (nonatomic, strong) id<FMTokenizerDelegate> m_baseTokenizer;
@end
static id<FMTokenizerDelegate> g_simpleTok = nil;
static id<FMTokenizerDelegate> 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<FMTokenizerDelegate>)tokenizer
{
return [[self alloc] initWithBaseTokenizer:tokenizer];
}
- (instancetype)initWithBaseTokenizer:(id<FMTokenizerDelegate>)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

View File

@ -1,83 +0,0 @@
//
// 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<FMTokenizerDelegate> 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

View File

@ -1,303 +0,0 @@
//
// FMDatabasePoolTests.m
// fmdb
//
// Created by Graham Dennis on 24/11/2013.
//
//
#import <XCTest/XCTest.h>
@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

View File

@ -1,176 +0,0 @@
//
// FMDatabaseQueueTests.m
// fmdb
//
// Created by Graham Dennis on 24/11/2013.
//
//
#import <XCTest/XCTest.h>
#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

View File

@ -1,902 +0,0 @@
//
// 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

View File

@ -1,91 +0,0 @@
//
// 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

View File

@ -1,83 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0500"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "EE4290EE12B42F870088BD94"
BuildableName = "libFMDB.a"
BlueprintName = "FMDB"
ReferencedContainer = "container:fmdb.xcodeproj">
</BuildableReference>
</BuildActionEntry>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "NO"
buildForArchiving = "NO"
buildForAnalyzing = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "BF5D041518416BB2008C5AA9"
BuildableName = "Tests.xctest"
BlueprintName = "Tests"
ReferencedContainer = "container:fmdb.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES"
buildConfiguration = "Debug">
<Testables>
<TestableReference
skipped = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "BF5D041518416BB2008C5AA9"
BuildableName = "Tests.xctest"
BlueprintName = "Tests"
ReferencedContainer = "container:fmdb.xcodeproj">
</BuildableReference>
</TestableReference>
</Testables>
</TestAction>
<LaunchAction
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
buildConfiguration = "Debug"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
allowLocationSimulation = "YES">
<AdditionalOptions>
</AdditionalOptions>
</LaunchAction>
<ProfileAction
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
buildConfiguration = "Release"
debugDocumentVersioning = "YES">
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>

View File

@ -1,22 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleExecutable</key>
<string>${EXECUTABLE_NAME}</string>
<key>CFBundleIdentifier</key>
<string>me.grahamdennis.${PRODUCT_NAME:rfc1034identifier}</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundlePackageType</key>
<string>BNDL</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>1</string>
</dict>
</plist>

View File

@ -1,11 +0,0 @@
//
// Prefix header
//
// The contents of this file are implicitly included at the beginning of every source file.
//
#ifdef __OBJC__
#import <Cocoa/Cocoa.h>
#import <XCTest/XCTest.h>
#import "FMDBTempDBTests.h"
#endif

View File

@ -1,2 +0,0 @@
/* Localized versions of Info.plist keys */

View File

@ -1,79 +0,0 @@
.\"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

View File

@ -1,856 +0,0 @@
// !$*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 = "<absolute>"; };
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 = "<group>"; };
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 = "<group>"; };
8314AF3218CD73D600EC0E25 /* FMDB.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = FMDB.h; path = src/fmdb/FMDB.h; sourceTree = "<group>"; };
831DE6FD175B7C9C001F7317 /* README.markdown */ = {isa = PBXFileReference; lastKnownFileType = text; path = README.markdown; sourceTree = "<group>"; };
832F502419EC4C6B0087DCBF /* FMDatabaseVariadic.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = FMDatabaseVariadic.swift; path = "src/extra/Swift extensions/FMDatabaseVariadic.swift"; sourceTree = "<group>"; };
8352D5AC1A73DCEA003A8E09 /* FMDatabaseAdditionsVariadic.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = FMDatabaseAdditionsVariadic.swift; path = "src/extra/Swift extensions/FMDatabaseAdditionsVariadic.swift"; sourceTree = "<group>"; };
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 = "<group>"; };
BF5D041E18416BB2008C5AA9 /* en */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = en; path = en.lproj/InfoPlist.strings; sourceTree = "<group>"; };
BF5D042018416BB2008C5AA9 /* FMDatabaseTests.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = FMDatabaseTests.m; sourceTree = "<group>"; };
BF5D042218416BB2008C5AA9 /* Tests-Prefix.pch */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Tests-Prefix.pch"; sourceTree = "<group>"; };
BF940F5A18417D490001E077 /* FMDBTempDBTests.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = FMDBTempDBTests.h; sourceTree = "<group>"; };
BF940F5B18417D490001E077 /* FMDBTempDBTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = FMDBTempDBTests.m; sourceTree = "<group>"; };
BF940F5D18417DEA0001E077 /* FMDatabaseAdditionsTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = FMDatabaseAdditionsTests.m; sourceTree = "<group>"; };
BFE55E121841C9A000CB3A63 /* FMDatabasePoolTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = FMDatabasePoolTests.m; sourceTree = "<group>"; };
BFE55E141841D38800CB3A63 /* FMDatabaseQueueTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = FMDatabaseQueueTests.m; sourceTree = "<group>"; };
C6859EA3029092ED04C91782 /* fmdb.1 */ = {isa = PBXFileReference; lastKnownFileType = text.man; path = fmdb.1; sourceTree = "<group>"; };
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 = "<group>"; };
CC7CE42718F5C04600938264 /* FMDatabase+InMemoryOnDiskIO.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = "FMDatabase+InMemoryOnDiskIO.m"; path = "src/extra/InMemoryOnDiskIO/FMDatabase+InMemoryOnDiskIO.m"; sourceTree = "<group>"; };
CC8C138A0E3135C400FBE1E7 /* CHANGES_AND_TODO_LIST.txt */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = CHANGES_AND_TODO_LIST.txt; sourceTree = "<group>"; };
CC8C138B0E3135C400FBE1E7 /* LICENSE.txt */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = LICENSE.txt; sourceTree = "<group>"; };
CC8C138C0E3135C400FBE1E7 /* CONTRIBUTORS.txt */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = CONTRIBUTORS.txt; sourceTree = "<group>"; };
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 = "<group>"; };
CCA66A2919C0CB1900EFDAC1 /* FMDatabase+FTS3.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = "FMDatabase+FTS3.m"; path = "src/extra/fts3/FMDatabase+FTS3.m"; sourceTree = "<group>"; };
CCA66A2A19C0CB1900EFDAC1 /* FMTokenizers.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = FMTokenizers.h; path = src/extra/fts3/FMTokenizers.h; sourceTree = "<group>"; };
CCA66A2B19C0CB1900EFDAC1 /* FMTokenizers.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = FMTokenizers.m; path = src/extra/fts3/FMTokenizers.m; sourceTree = "<group>"; };
CCA66A2C19C0CB1900EFDAC1 /* fts3_tokenizer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = fts3_tokenizer.h; path = src/extra/fts3/fts3_tokenizer.h; sourceTree = "<group>"; };
CCBE26C013B3BA8C006F6C37 /* AppKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = AppKit.framework; path = /System/Library/Frameworks/AppKit.framework; sourceTree = "<absolute>"; };
CCBEBDAB0DF5DE1A003DDD08 /* libsqlite3.dylib */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; name = libsqlite3.dylib; path = /usr/lib/libsqlite3.dylib; sourceTree = "<absolute>"; };
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 = "<group>"; };
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 = "<group>";
};
08FB7795FE84155DC02AAC07 /* Source */ = {
isa = PBXGroup;
children = (
8314AF3018CD737D00EC0E25 /* fmdb */,
CC7CE42518F5C02E00938264 /* optional extras */,
8314AF3118CD739500EC0E25 /* sample */,
);
name = Source;
sourceTree = "<group>";
};
08FB779DFE84155DC02AAC07 /* External Frameworks and Libraries */ = {
isa = PBXGroup;
children = (
CCBEBDAB0DF5DE1A003DDD08 /* libsqlite3.dylib */,
08FB779EFE84155DC02AAC07 /* Foundation.framework */,
CCBE26C013B3BA8C006F6C37 /* AppKit.framework */,
);
name = "External Frameworks and Libraries";
sourceTree = "<group>";
};
1AB674ADFE9D54B511CA2CBB /* Products */ = {
isa = PBXGroup;
children = (
8DD76FA10486AA7600D96B5E /* fmdb */,
EE4290EF12B42F870088BD94 /* libFMDB.a */,
BF5D041618416BB2008C5AA9 /* Tests.xctest */,
6290CBB5188FE836009790F8 /* libFMDB-IOS.a */,
);
name = Products;
sourceTree = "<group>";
};
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 = "<group>";
};
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 = "<group>";
};
8314AF3118CD739500EC0E25 /* sample */ = {
isa = PBXGroup;
children = (
CCC24EBE0A13E34D00A6D3E3 /* main.m */,
32A70AAB03705E1F00C91783 /* fmdb_Prefix.pch */,
);
name = sample;
sourceTree = "<group>";
};
832F502319EC4C4A0087DCBF /* Swift extensions */ = {
isa = PBXGroup;
children = (
832F502419EC4C6B0087DCBF /* FMDatabaseVariadic.swift */,
8352D5AC1A73DCEA003A8E09 /* FMDatabaseAdditionsVariadic.swift */,
);
name = "Swift extensions";
sourceTree = "<group>";
};
832F502519EC4CA20087DCBF /* InMemoryOnDiskIO */ = {
isa = PBXGroup;
children = (
CC7CE42618F5C04600938264 /* FMDatabase+InMemoryOnDiskIO.h */,
CC7CE42718F5C04600938264 /* FMDatabase+InMemoryOnDiskIO.m */,
);
name = InMemoryOnDiskIO;
sourceTree = "<group>";
};
BF5D041718416BB2008C5AA9 /* Frameworks */ = {
isa = PBXGroup;
children = (
BF5D041818416BB2008C5AA9 /* XCTest.framework */,
6290CBB6188FE836009790F8 /* Foundation.framework */,
6290CBC6188FE837009790F8 /* UIKit.framework */,
);
name = Frameworks;
sourceTree = "<group>";
};
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 = "<group>";
};
BF5D041B18416BB2008C5AA9 /* Supporting Files */ = {
isa = PBXGroup;
children = (
BF5D041C18416BB2008C5AA9 /* Tests-Info.plist */,
BF5D041D18416BB2008C5AA9 /* InfoPlist.strings */,
BF5D042218416BB2008C5AA9 /* Tests-Prefix.pch */,
);
name = "Supporting Files";
sourceTree = "<group>";
};
C6859EA2029092E104C91782 /* Documentation */ = {
isa = PBXGroup;
children = (
C6859EA3029092ED04C91782 /* fmdb.1 */,
);
name = Documentation;
sourceTree = "<group>";
};
CC7CE42518F5C02E00938264 /* optional extras */ = {
isa = PBXGroup;
children = (
832F502319EC4C4A0087DCBF /* Swift extensions */,
832F502519EC4CA20087DCBF /* InMemoryOnDiskIO */,
6767F81519AD13C300887DBC /* fts3 */,
);
name = "optional extras";
sourceTree = "<group>";
};
/* 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 = "<group>";
};
/* 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 */;
}

View File

@ -1,96 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0630"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "NO"
buildForArchiving = "NO"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "BF5D041518416BB2008C5AA9"
BuildableName = "Tests.xctest"
BlueprintName = "Tests"
ReferencedContainer = "container:fmdb.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES"
buildConfiguration = "Debug">
<Testables>
<TestableReference
skipped = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "BF5D041518416BB2008C5AA9"
BuildableName = "Tests.xctest"
BlueprintName = "Tests"
ReferencedContainer = "container:fmdb.xcodeproj">
</BuildableReference>
</TestableReference>
</Testables>
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "BF5D041518416BB2008C5AA9"
BuildableName = "Tests.xctest"
BlueprintName = "Tests"
ReferencedContainer = "container:fmdb.xcodeproj">
</BuildableReference>
</MacroExpansion>
</TestAction>
<LaunchAction
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
buildConfiguration = "Debug"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
allowLocationSimulation = "YES">
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "BF5D041518416BB2008C5AA9"
BuildableName = "Tests.xctest"
BlueprintName = "Tests"
ReferencedContainer = "container:fmdb.xcodeproj">
</BuildableReference>
</MacroExpansion>
<AdditionalOptions>
</AdditionalOptions>
</LaunchAction>
<ProfileAction
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
buildConfiguration = "Release"
debugDocumentVersioning = "YES">
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "BF5D041518416BB2008C5AA9"
BuildableName = "Tests.xctest"
BlueprintName = "Tests"
ReferencedContainer = "container:fmdb.xcodeproj">
</BuildableReference>
</MacroExpansion>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>

View File

@ -1,26 +0,0 @@
//
// 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

View File

@ -1,96 +0,0 @@
#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

View File

@ -1,117 +0,0 @@
//
// 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<T>(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) }
}
}

View File

@ -1,36 +0,0 @@
//
// 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]);
}
}

View File

@ -1,112 +0,0 @@
//
// 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<FMTokenizerDelegate>)tokenizer;
/**
Register a delegate implementation in the global table. The key should be used
as a parameter when creating the table.
*/
+ (void)registerTokenizer:(id<FMTokenizerDelegate>)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

View File

@ -1,283 +0,0 @@
//
// 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<FMTokenizerDelegate> __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<FMTokenizerDelegate>)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<FMTokenizerDelegate>)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

View File

@ -1,45 +0,0 @@
//
// FMTokenizers.h
// fmdb
//
// Created by Andrew on 4/9/14.
// Copyright (c) 2014 Andrew Goodale. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "FMDatabase+FTS3.h"
/**
This is the base tokenizer implementation, using a CFStringTokenizer to find words.
*/
@interface FMSimpleTokenizer : NSObject <FMTokenizerDelegate>
/**
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 <FMTokenizerDelegate>
@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<FMTokenizerDelegate>)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<FMTokenizerDelegate>)tokenizer;
@end

View File

@ -1,135 +0,0 @@
//
// 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<FMTokenizerDelegate> m_baseTokenizer;
}
@synthesize words = m_words;
+ (instancetype)tokenizerWithFileURL:(NSURL *)wordFileURL
baseTokenizer:(id<FMTokenizerDelegate>)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<FMTokenizerDelegate>)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

View File

@ -1,161 +0,0 @@
/*
** 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 <tokenizer-name> 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_ */

View File

@ -1,5 +0,0 @@
#import "FMDatabase.h"
#import "FMResultSet.h"
#import "FMDatabaseAdditions.h"
#import "FMDatabaseQueue.h"
#import "FMDatabasePool.h"

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1,281 +0,0 @@
//
// FMDatabaseAdditions.h
// fmdb
//
// Created by August Mueller on 10/30/05.
// Copyright 2005 Flying Meat Inc.. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "FMDatabase.h"
/** Category of additions for `<FMDatabase>` class.
### See also
- `<FMDatabase>`
*/
@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 `<columnExists:inTableWithName:>` 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

View File

@ -1,225 +0,0 @@
//
// 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

View File

@ -1,204 +0,0 @@
//
// FMDatabasePool.h
// fmdb
//
// Created by August Mueller on 6/22/11.
// Copyright 2011 Flying Meat Inc. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "sqlite3.h"
@class FMDatabase;
/** Pool of `<FMDatabase>` objects.
### See also
- `<FMDatabaseQueue>`
- `<FMDatabase>`
@warning Before using `FMDatabasePool`, please consider using `<FMDatabaseQueue>` 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

View File

@ -1,273 +0,0 @@
//
// 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

View File

@ -1,185 +0,0 @@
//
// FMDatabaseQueue.h
// fmdb
//
// Created by August Mueller on 6/22/11.
// Copyright 2011 Flying Meat Inc. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "sqlite3.h"
@class FMDatabase;
/** To perform queries and updates on multiple threads, you'll want to use `FMDatabaseQueue`.
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.
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
- `<FMDatabase>`
@warning Do not instantiate a single `<FMDatabase>` 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

View File

@ -1,236 +0,0 @@
//
// 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

View File

@ -1,469 +0,0 @@
#import <Foundation/Foundation.h>
//#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 `<FMDatabase>`.
### See also
- `<FMDatabase>`
*/
@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 `<FMStatement>`
@param statement A `<FMStatement>` to be performed
@param aDB A `<FMDatabase>` 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 `<next>` succeed in retrieving another row?
@return `YES` if the last call to `<next>` succeeded in retrieving another record; `NO` if not.
@see next
@warning The `hasAnotherRow` method must follow a call to `<next>`. 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 `<dataForColumn:>`/`<dataForColumnIndex:>`)
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 `<dataForColumn:>`/`<dataForColumnIndex:>`)
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 `<resultDictionary>` instead. Also, beware that `<resultDictionary>` 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

View File

@ -1,412 +0,0 @@
#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)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

View File

@ -1,7 +0,0 @@
//
// Prefix header for all source files of the 'fmdb' target in the 'fmdb' project.
//
#ifdef __OBJC__
#import <Foundation/Foundation.h>
#endif

File diff suppressed because it is too large Load Diff

View File

@ -1,21 +0,0 @@
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.

View File

@ -1,12 +0,0 @@
# RSDatabase
This is utility code for using SQLite via FMDB. Its not a persistence framework — its lower-level.
It builds as a couple frameworks — one for Mac, one for iOS.
It has no additional dependencies, but thats because FMDB is actually included — you might want to instead make sure you have the [latest FMDB](https://github.com/ccgus/fmdb), which isnt 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 dont have to write as much SQL.

View File

@ -1,561 +0,0 @@
// !$*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, ); }; };
840405DB1F1C158C00DF0296 /* DatabaseTable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 840405DA1F1C158C00DF0296 /* DatabaseTable.swift */; };
840405DC1F1C15EA00DF0296 /* DatabaseTable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 840405DA1F1C158C00DF0296 /* DatabaseTable.swift */; };
84314F4A1F68ECC600F710B2 /* DatabaseObjectCache.swift in Sources */ = {isa = PBXBuildFile; fileRef = 84314F491F68ECC600F710B2 /* DatabaseObjectCache.swift */; };
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 */; };
844ECFB91F5B17F9005E405A /* DatabaseRelatedObjectsTable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 844ECFB81F5B17F9005E405A /* DatabaseRelatedObjectsTable.swift */; };
848E22541F6652990031D7C5 /* DatabaseRelatedObjectsTable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 844ECFB81F5B17F9005E405A /* DatabaseRelatedObjectsTable.swift */; };
848E22561F6652C70031D7C5 /* RelatedObjectsMap.swift in Sources */ = {isa = PBXBuildFile; fileRef = 848E22551F6652C70031D7C5 /* RelatedObjectsMap.swift */; };
848E22581F6653960031D7C5 /* RelatedObjectIDsMap.swift in Sources */ = {isa = PBXBuildFile; fileRef = 848E22571F6653960031D7C5 /* RelatedObjectIDsMap.swift */; };
849BF8C61C94FB8E0071D1DA /* libsqlite3.tbd in Frameworks */ = {isa = PBXBuildFile; fileRef = 849BF8C51C94FB8E0071D1DA /* libsqlite3.tbd */; };
84ABC1D11F364B07000DCC55 /* DatabaseLookupTable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 84ABC1D01F364B07000DCC55 /* DatabaseLookupTable.swift */; };
84ABC1D21F364B07000DCC55 /* DatabaseLookupTable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 84ABC1D01F364B07000DCC55 /* DatabaseLookupTable.swift */; };
84C6DD011F395C13009AFB47 /* DatabaseObject.swift in Sources */ = {isa = PBXBuildFile; fileRef = 84C6DD001F395C13009AFB47 /* DatabaseObject.swift */; };
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 */; };
D511EF2E20244E8900712EC3 /* DatabaseObjectCache.swift in Sources */ = {isa = PBXBuildFile; fileRef = 84314F491F68ECC600F710B2 /* DatabaseObjectCache.swift */; };
D511EF2F20244E9A00712EC3 /* DatabaseObject.swift in Sources */ = {isa = PBXBuildFile; fileRef = 84C6DD001F395C13009AFB47 /* DatabaseObject.swift */; };
D511EF3020244EA400712EC3 /* RelatedObjectsMap.swift in Sources */ = {isa = PBXBuildFile; fileRef = 848E22551F6652C70031D7C5 /* RelatedObjectsMap.swift */; };
D511EF3120244EAE00712EC3 /* RelatedObjectIDsMap.swift in Sources */ = {isa = PBXBuildFile; fileRef = 848E22571F6653960031D7C5 /* RelatedObjectIDsMap.swift */; };
/* 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 = "<group>"; };
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; };
840405DA1F1C158C00DF0296 /* DatabaseTable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseTable.swift; sourceTree = "<group>"; };
84314F491F68ECC600F710B2 /* DatabaseObjectCache.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = DatabaseObjectCache.swift; path = RSDatabase/DatabaseObjectCache.swift; sourceTree = "<group>"; };
84419AD41B5ABD6D00C26BB2 /* FMDatabase+RSExtras.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = "FMDatabase+RSExtras.h"; path = "RSDatabase/FMDatabase+RSExtras.h"; sourceTree = "<group>"; };
84419AD51B5ABD6D00C26BB2 /* FMDatabase+RSExtras.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = "FMDatabase+RSExtras.m"; path = "RSDatabase/FMDatabase+RSExtras.m"; sourceTree = "<group>"; };
84419AD81B5ABD7400C26BB2 /* NSString+RSDatabase.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = "NSString+RSDatabase.h"; path = "RSDatabase/NSString+RSDatabase.h"; sourceTree = "<group>"; };
84419AD91B5ABD7400C26BB2 /* NSString+RSDatabase.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = "NSString+RSDatabase.m"; path = "RSDatabase/NSString+RSDatabase.m"; sourceTree = "<group>"; };
84419ADC1B5ABD7F00C26BB2 /* RSDatabaseQueue.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = RSDatabaseQueue.h; path = RSDatabase/RSDatabaseQueue.h; sourceTree = "<group>"; };
84419ADD1B5ABD7F00C26BB2 /* RSDatabaseQueue.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = RSDatabaseQueue.m; path = RSDatabase/RSDatabaseQueue.m; sourceTree = "<group>"; };
84419B031B5ABFF700C26BB2 /* FMResultSet+RSExtras.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = "FMResultSet+RSExtras.h"; path = "RSDatabase/FMResultSet+RSExtras.h"; sourceTree = "<group>"; };
84419B041B5ABFF700C26BB2 /* FMResultSet+RSExtras.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = "FMResultSet+RSExtras.m"; path = "RSDatabase/FMResultSet+RSExtras.m"; sourceTree = "<group>"; };
844ECFB81F5B17F9005E405A /* DatabaseRelatedObjectsTable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseRelatedObjectsTable.swift; sourceTree = "<group>"; };
848E22551F6652C70031D7C5 /* RelatedObjectsMap.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RelatedObjectsMap.swift; sourceTree = "<group>"; };
848E22571F6653960031D7C5 /* RelatedObjectIDsMap.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RelatedObjectIDsMap.swift; sourceTree = "<group>"; };
849BF8C51C94FB8E0071D1DA /* libsqlite3.tbd */ = {isa = PBXFileReference; lastKnownFileType = "sourcecode.text-based-dylib-definition"; name = libsqlite3.tbd; path = usr/lib/libsqlite3.tbd; sourceTree = SDKROOT; };
84ABC1D01F364B07000DCC55 /* DatabaseLookupTable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseLookupTable.swift; sourceTree = "<group>"; };
84C6DD001F395C13009AFB47 /* DatabaseObject.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = DatabaseObject.swift; path = RSDatabase/DatabaseObject.swift; sourceTree = "<group>"; };
84DDF18B1C94FC45005E6CF5 /* FMDatabase.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = FMDatabase.h; sourceTree = "<group>"; };
84DDF18C1C94FC45005E6CF5 /* FMDatabase.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = FMDatabase.m; sourceTree = "<group>"; };
84DDF18D1C94FC45005E6CF5 /* FMDatabaseAdditions.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = FMDatabaseAdditions.h; sourceTree = "<group>"; };
84DDF18E1C94FC45005E6CF5 /* FMDatabaseAdditions.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = FMDatabaseAdditions.m; sourceTree = "<group>"; };
84DDF1941C94FC45005E6CF5 /* FMResultSet.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = FMResultSet.h; sourceTree = "<group>"; };
84DDF1951C94FC45005E6CF5 /* FMResultSet.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = FMResultSet.m; sourceTree = "<group>"; };
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 = "<group>"; };
84F22C5A1B52E0D9000060CE /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; name = Info.plist; path = RSDatabase/Info.plist; sourceTree = "<group>"; };
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 = "<group>"; };
84F22C661B52E0D9000060CE /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
D511EF0320242E6400712EC3 /* RSDatabase_project_release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = RSDatabase_project_release.xcconfig; sourceTree = "<group>"; };
D511EF0420242E6400712EC3 /* RSDatabaseTests_target.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = RSDatabaseTests_target.xcconfig; sourceTree = "<group>"; };
D511EF0520242E6400712EC3 /* RSDatabase_target.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = RSDatabase_target.xcconfig; sourceTree = "<group>"; };
D511EF0620242E6400712EC3 /* RSDatabase_project_debug.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = RSDatabase_project_debug.xcconfig; sourceTree = "<group>"; };
D511EF0720242E6400712EC3 /* RSDatabase_project.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = RSDatabase_project.xcconfig; sourceTree = "<group>"; };
D511EF28202444E000712EC3 /* RSDatabase_mac_target.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = RSDatabase_mac_target.xcconfig; sourceTree = "<group>"; };
D511EF29202444E000712EC3 /* RSDatabase_ios_target.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = RSDatabase_ios_target.xcconfig; sourceTree = "<group>"; };
D511EF2C20244AFF00712EC3 /* RSDatabase_ios_target_release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = RSDatabase_ios_target_release.xcconfig; sourceTree = "<group>"; };
D511EF2D20244B0000712EC3 /* RSDatabase_ios_target_debug.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = RSDatabase_ios_target_debug.xcconfig; sourceTree = "<group>"; };
/* 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 = "<group>";
};
8400AC0D1E0CFC5500AA7C57 /* Frameworks */ = {
isa = PBXGroup;
children = (
8400AC0E1E0CFC5600AA7C57 /* libsqlite3.tbd */,
);
name = Frameworks;
sourceTree = "<group>";
};
848E22531F66528C0031D7C5 /* Related Objects */ = {
isa = PBXGroup;
children = (
84ABC1D01F364B07000DCC55 /* DatabaseLookupTable.swift */,
848E22551F6652C70031D7C5 /* RelatedObjectsMap.swift */,
848E22571F6653960031D7C5 /* RelatedObjectIDsMap.swift */,
844ECFB81F5B17F9005E405A /* DatabaseRelatedObjectsTable.swift */,
);
path = "Related Objects";
sourceTree = "<group>";
};
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 = "<group>";
};
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 */,
84C6DD001F395C13009AFB47 /* DatabaseObject.swift */,
840405DA1F1C158C00DF0296 /* DatabaseTable.swift */,
84314F491F68ECC600F710B2 /* DatabaseObjectCache.swift */,
848E22531F66528C0031D7C5 /* Related Objects */,
84DDF18A1C94FC45005E6CF5 /* FMDB */,
84F22C5A1B52E0D9000060CE /* Info.plist */,
849BF8C51C94FB8E0071D1DA /* libsqlite3.tbd */,
84F22C631B52E0D9000060CE /* RSDatabaseTests */,
8400ABF81E0CFBD800AA7C57 /* RSDatabaseiOS */,
84F22C561B52E0D9000060CE /* Products */,
8400AC0D1E0CFC5500AA7C57 /* Frameworks */,
D511EF0220242E6400712EC3 /* xcconfig */,
);
sourceTree = "<group>";
};
84F22C561B52E0D9000060CE /* Products */ = {
isa = PBXGroup;
children = (
84F22C551B52E0D9000060CE /* RSDatabase.framework */,
84F22C5F1B52E0D9000060CE /* RSDatabaseTests.xctest */,
8400ABF71E0CFBD800AA7C57 /* RSDatabase.framework */,
);
name = Products;
sourceTree = "<group>";
};
84F22C631B52E0D9000060CE /* RSDatabaseTests */ = {
isa = PBXGroup;
children = (
84F22C641B52E0D9000060CE /* RSDatabaseTests.m */,
84F22C661B52E0D9000060CE /* Info.plist */,
);
path = RSDatabaseTests;
sourceTree = "<group>";
};
D511EF0220242E6400712EC3 /* xcconfig */ = {
isa = PBXGroup;
children = (
D511EF0720242E6400712EC3 /* RSDatabase_project.xcconfig */,
D511EF0620242E6400712EC3 /* RSDatabase_project_debug.xcconfig */,
D511EF0320242E6400712EC3 /* RSDatabase_project_release.xcconfig */,
D511EF0520242E6400712EC3 /* RSDatabase_target.xcconfig */,
D511EF29202444E000712EC3 /* RSDatabase_ios_target.xcconfig */,
D511EF2D20244B0000712EC3 /* RSDatabase_ios_target_debug.xcconfig */,
D511EF2C20244AFF00712EC3 /* RSDatabase_ios_target_release.xcconfig */,
D511EF28202444E000712EC3 /* RSDatabase_mac_target.xcconfig */,
D511EF0420242E6400712EC3 /* RSDatabaseTests_target.xcconfig */,
);
path = xcconfig;
sourceTree = "<group>";
};
/* 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 = 0930;
ORGANIZATIONNAME = "Ranchero Software, LLC";
TargetAttributes = {
8400ABF61E0CFBD800AA7C57 = {
CreatedOnToolsVersion = 8.2.1;
DevelopmentTeam = 9C84TZ7Q6Z;
ProvisioningStyle = Automatic;
};
84F22C541B52E0D9000060CE = {
CreatedOnToolsVersion = 7.0;
LastSwiftMigration = 0900;
};
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 = (
D511EF3120244EAE00712EC3 /* RelatedObjectIDsMap.swift in Sources */,
848E22541F6652990031D7C5 /* DatabaseRelatedObjectsTable.swift in Sources */,
8400AC001E0CFC0700AA7C57 /* RSDatabaseQueue.m in Sources */,
D511EF2E20244E8900712EC3 /* DatabaseObjectCache.swift in Sources */,
8400AC061E0CFC0700AA7C57 /* NSString+RSDatabase.m in Sources */,
D511EF3020244EA400712EC3 /* RelatedObjectsMap.swift in Sources */,
84ABC1D21F364B07000DCC55 /* DatabaseLookupTable.swift in Sources */,
8400AC0C1E0CFC3100AA7C57 /* FMResultSet.m in Sources */,
840405DC1F1C15EA00DF0296 /* DatabaseTable.swift in Sources */,
8400AC021E0CFC0700AA7C57 /* FMDatabase+RSExtras.m in Sources */,
8400AC081E0CFC2000AA7C57 /* FMDatabase.m in Sources */,
8400AC041E0CFC0700AA7C57 /* FMResultSet+RSExtras.m in Sources */,
8400AC0A1E0CFC2900AA7C57 /* FMDatabaseAdditions.m in Sources */,
D511EF2F20244E9A00712EC3 /* DatabaseObject.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
84F22C501B52E0D9000060CE /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
84419AE71B5ABD7F00C26BB2 /* RSDatabaseQueue.m in Sources */,
84419AD71B5ABD6D00C26BB2 /* FMDatabase+RSExtras.m in Sources */,
84314F4A1F68ECC600F710B2 /* DatabaseObjectCache.swift in Sources */,
84C6DD011F395C13009AFB47 /* DatabaseObject.swift in Sources */,
84419ADB1B5ABD7400C26BB2 /* NSString+RSDatabase.m in Sources */,
840405DB1F1C158C00DF0296 /* DatabaseTable.swift in Sources */,
84ABC1D11F364B07000DCC55 /* DatabaseLookupTable.swift in Sources */,
84DDF1971C94FC45005E6CF5 /* FMDatabase.m in Sources */,
84DDF1A01C94FC45005E6CF5 /* FMResultSet.m in Sources */,
844ECFB91F5B17F9005E405A /* DatabaseRelatedObjectsTable.swift in Sources */,
84419B061B5ABFF700C26BB2 /* FMResultSet+RSExtras.m in Sources */,
84DDF1991C94FC45005E6CF5 /* FMDatabaseAdditions.m in Sources */,
848E22581F6653960031D7C5 /* RelatedObjectIDsMap.swift in Sources */,
848E22561F6652C70031D7C5 /* RelatedObjectsMap.swift 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;
baseConfigurationReference = D511EF2D20244B0000712EC3 /* RSDatabase_ios_target_debug.xcconfig */;
buildSettings = {
};
name = Debug;
};
8400ABFD1E0CFBD800AA7C57 /* Release */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = D511EF2C20244AFF00712EC3 /* RSDatabase_ios_target_release.xcconfig */;
buildSettings = {
};
name = Release;
};
84F22C671B52E0D9000060CE /* Debug */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = D511EF0620242E6400712EC3 /* RSDatabase_project_debug.xcconfig */;
buildSettings = {
};
name = Debug;
};
84F22C681B52E0D9000060CE /* Release */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = D511EF0320242E6400712EC3 /* RSDatabase_project_release.xcconfig */;
buildSettings = {
};
name = Release;
};
84F22C6A1B52E0D9000060CE /* Debug */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = D511EF28202444E000712EC3 /* RSDatabase_mac_target.xcconfig */;
buildSettings = {
};
name = Debug;
};
84F22C6B1B52E0D9000060CE /* Release */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = D511EF28202444E000712EC3 /* RSDatabase_mac_target.xcconfig */;
buildSettings = {
};
name = Release;
};
84F22C6D1B52E0D9000060CE /* Debug */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = D511EF0420242E6400712EC3 /* RSDatabaseTests_target.xcconfig */;
buildSettings = {
};
name = Debug;
};
84F22C6E1B52E0D9000060CE /* Release */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = D511EF0420242E6400712EC3 /* RSDatabaseTests_target.xcconfig */;
buildSettings = {
};
name = Release;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
8400ABFE1E0CFBD800AA7C57 /* Build configuration list for PBXNativeTarget "RSDatabaseiOS" */ = {
isa = XCConfigurationList;
buildConfigurations = (
8400ABFC1E0CFBD800AA7C57 /* Debug */,
8400ABFD1E0CFBD800AA7C57 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
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 */;
}

View File

@ -1,7 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "self:RSDatabase.xcodeproj">
</FileRef>
</Workspace>

View File

@ -1,59 +0,0 @@
//
// DatabaseObject.swift
// RSDatabase
//
// Created by Brent Simmons on 8/7/17.
// Copyright © 2017 Ranchero Software, LLC. All rights reserved.
//
import Foundation
public protocol DatabaseObject {
var databaseID: String { get }
func databaseDictionary() -> NSDictionary?
func relatedObjectsWithName(_ name: String) -> [DatabaseObject]?
}
public extension DatabaseObject {
func relatedObjectsWithName(_ name: String) -> [DatabaseObject]? {
return nil
}
}
extension Array where Element == DatabaseObject {
func dictionary() -> [String: DatabaseObject] {
var d = [String: DatabaseObject]()
for object in self {
d[object.databaseID] = object
}
return d
}
func databaseIDs() -> Set<String> {
return Set(self.map { $0.databaseID })
}
func includesObjectWithDatabaseID(_ databaseID: String) -> Bool {
for object in self {
if object.databaseID == databaseID {
return true
}
}
return false
}
func databaseDictionaries() -> [NSDictionary]? {
let dictionaries = self.compactMap{ $0.databaseDictionary() }
return dictionaries.isEmpty ? nil : dictionaries
}
}

View File

@ -1,33 +0,0 @@
//
// DatabaseObjectCache.swift
// RSDatabase
//
// Created by Brent Simmons on 9/12/17.
// Copyright © 2017 Ranchero Software, LLC. All rights reserved.
//
import Foundation
public final class DatabaseObjectCache {
private var d = [String: DatabaseObject]()
public init() {
//
}
public func add(_ databaseObjects: [DatabaseObject]) {
for databaseObject in databaseObjects {
self[databaseObject.databaseID] = databaseObject
}
}
public subscript(_ databaseID: String) -> DatabaseObject? {
get {
return d[databaseID]
}
set {
d[databaseID] = newValue
}
}
}

View File

@ -1,25 +0,0 @@
//
// DatabaseRelatedObjectsTable.swift
// RSDatabase
//
// Created by Brent Simmons on 9/2/17.
// Copyright © 2017 Ranchero Software, LLC. All rights reserved.
//
import Foundation
public protocol DatabaseRelatedObjectsTable: DatabaseTable {
var databaseIDKey: String { get}
func fetchObjectsWithIDs(_ databaseIDs: Set<String>, in database: FMDatabase) -> [DatabaseObject]
func objectsWithResultSet(_ resultSet: FMResultSet) -> [DatabaseObject]
func objectWithRow(_ row: FMResultSet) -> DatabaseObject?
func save(_ objects: [DatabaseObject], in database: FMDatabase)
}
public extension DatabaseRelatedObjectsTable {
}

View File

@ -1,84 +0,0 @@
//
// 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 NS_ENUM(NSInteger, RSDatabaseInsertType) {
RSDatabaseInsertNormal,
RSDatabaseInsertOrReplace,
RSDatabaseInsertOrIgnore
};
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

View File

@ -1,182 +0,0 @@
//
// 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

View File

@ -1,19 +0,0 @@
//
// 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

View File

@ -1,51 +0,0 @@
//
// 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

View File

@ -1,28 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>$(CURRENT_PROJECT_VERSION)</string>
<key>NSHumanReadableCopyright</key>
<string>Copyright © 2015 Ranchero Software, LLC. All rights reserved.</string>
<key>NSPrincipalClass</key>
<string></string>
</dict>
</plist>

View File

@ -1,33 +0,0 @@
//
// 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

View File

@ -1,120 +0,0 @@
//
// 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

View File

@ -1,26 +0,0 @@
//
// 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 <RSDatabase/FMDatabase.h>
#import <RSDatabase/FMDatabaseAdditions.h>
#import <RSDatabase/FMResultSet.h>
// Categories
#import <RSDatabase/FMDatabase+RSExtras.h>
#import <RSDatabase/FMResultSet+RSExtras.h>
#import <RSDatabase/NSString+RSDatabase.h>
// RSDatabase
#import <RSDatabase/RSDatabaseQueue.h>

View File

@ -1,57 +0,0 @@
//
// 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 <NSObject>
@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<RSDatabaseQueueDelegate> 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

View File

@ -1,182 +0,0 @@
//
// 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

View File

@ -1,24 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>BNDL</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>1</string>
</dict>
</plist>

View File

@ -1,42 +0,0 @@
//
// RSDatabaseTests.m
// RSDatabaseTests
//
// Created by Brent Simmons on 7/12/15.
// Copyright © 2015 Ranchero Software, LLC. All rights reserved.
//
#import <XCTest/XCTest.h>
@interface RSDatabaseTests : XCTestCase
@end
@implementation RSDatabaseTests
// Seems like there should be some tests here.
// And yet there arent 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

View File

@ -1,26 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleDisplayName</key>
<string>RSDatabase</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleVersion</key>
<string>$(CURRENT_PROJECT_VERSION)</string>
<key>NSPrincipalClass</key>
<string></string>
</dict>
</plist>

View File

@ -1,228 +0,0 @@
//
// DatabaseLookupTable.swift
// RSDatabase
//
// Created by Brent Simmons on 8/5/17.
// Copyright © 2017 Ranchero Software, LLC. All rights reserved.
//
import Foundation
// Implement a lookup table for a many-to-many relationship.
// Example: CREATE TABLE if not EXISTS authorLookup (authorID TEXT NOT NULL, articleID TEXT NOT NULL, PRIMARY KEY(authorID, articleID));
// articleID is objectID; authorID is relatedObjectID.
public final class DatabaseLookupTable {
private let name: String
private let objectIDKey: String
private let relatedObjectIDKey: String
private let relationshipName: String
private let relatedTable: DatabaseRelatedObjectsTable
private var objectIDsWithNoRelatedObjects = Set<String>()
public init(name: String, objectIDKey: String, relatedObjectIDKey: String, relatedTable: DatabaseRelatedObjectsTable, relationshipName: String) {
self.name = name
self.objectIDKey = objectIDKey
self.relatedObjectIDKey = relatedObjectIDKey
self.relatedTable = relatedTable
self.relationshipName = relationshipName
}
public func fetchRelatedObjects(for objectIDs: Set<String>, in database: FMDatabase) -> RelatedObjectsMap? {
let objectIDsThatMayHaveRelatedObjects = objectIDs.subtracting(objectIDsWithNoRelatedObjects)
if objectIDsThatMayHaveRelatedObjects.isEmpty {
return nil
}
guard let relatedObjectIDsMap = fetchRelatedObjectIDsMap(objectIDsThatMayHaveRelatedObjects, database) else {
objectIDsWithNoRelatedObjects.formUnion(objectIDsThatMayHaveRelatedObjects)
return nil
}
if let relatedObjects = fetchRelatedObjectsWithIDs(relatedObjectIDsMap.relatedObjectIDs(), database) {
let relatedObjectsMap = RelatedObjectsMap(relatedObjects: relatedObjects, relatedObjectIDsMap: relatedObjectIDsMap)
let objectIDsWithNoFetchedRelatedObjects = objectIDsThatMayHaveRelatedObjects.subtracting(relatedObjectsMap.objectIDs())
objectIDsWithNoRelatedObjects.formUnion(objectIDsWithNoFetchedRelatedObjects)
return relatedObjectsMap
}
return nil
}
public func saveRelatedObjects(for objects: [DatabaseObject], in database: FMDatabase) {
var objectsWithNoRelationships = [DatabaseObject]()
var objectsWithRelationships = [DatabaseObject]()
for object in objects {
if let relatedObjects = object.relatedObjectsWithName(relationshipName), !relatedObjects.isEmpty {
objectsWithRelationships += [object]
}
else {
objectsWithNoRelationships += [object]
}
}
removeRelationships(for: objectsWithNoRelationships, database)
updateRelationships(for: objectsWithRelationships, database)
objectIDsWithNoRelatedObjects.formUnion(objectsWithNoRelationships.databaseIDs())
objectIDsWithNoRelatedObjects.subtract(objectsWithRelationships.databaseIDs())
}
}
// MARK: - Private
private extension DatabaseLookupTable {
// MARK: Removing
func removeRelationships(for objects: [DatabaseObject], _ database: FMDatabase) {
let objectIDs = objects.databaseIDs()
let objectIDsToRemove = objectIDs.subtracting(objectIDsWithNoRelatedObjects)
if objectIDsToRemove.isEmpty {
return
}
database.rs_deleteRowsWhereKey(objectIDKey, inValues: Array(objectIDsToRemove), tableName: name)
}
func deleteLookups(for objectID: String, _ relatedObjectIDs: Set<String>, _ database: FMDatabase) {
guard !relatedObjectIDs.isEmpty else {
assertionFailure("deleteLookups: expected non-empty relatedObjectIDs")
return
}
// delete from authorLookup where articleID=? and authorID in (?,?,?)
let placeholders = NSString.rs_SQLValueList(withPlaceholders: UInt(relatedObjectIDs.count))!
let sql = "delete from \(name) where \(objectIDKey)=? and \(relatedObjectIDKey) in \(placeholders)"
let parameters: [Any] = [objectID] + Array(relatedObjectIDs)
let _ = database.executeUpdate(sql, withArgumentsIn: parameters)
}
// MARK: Saving/Updating
func updateRelationships(for objects: [DatabaseObject], _ database: FMDatabase) {
if objects.isEmpty {
return
}
if let lookupTable = fetchRelatedObjectIDsMap(objects.databaseIDs(), database) {
for object in objects {
syncRelatedObjectsAndLookupTable(object, lookupTable, database)
}
}
// Save the actual related objects.
let relatedObjectsToSave = uniqueArrayOfRelatedObjects(with: objects)
if relatedObjectsToSave.isEmpty {
assertionFailure("updateRelationships: expected relatedObjectsToSave would not be empty. This should be unreachable.")
return
}
relatedTable.save(relatedObjectsToSave, in: database)
}
func uniqueArrayOfRelatedObjects(with objects: [DatabaseObject]) -> [DatabaseObject] {
// Cant create a Set, because we cant make a Set<DatabaseObject>, because protocol-conforming objects cant be made Hashable or even Equatable.
// We still want the array to include only one copy of each object, but we have to do it the slow way. Instruments will tell us if this is a performance problem.
var relatedObjectsUniqueArray = [DatabaseObject]()
for object in objects {
guard let relatedObjects = object.relatedObjectsWithName(relationshipName) else {
assertionFailure("uniqueArrayOfRelatedObjects: expected every object to have related objects.")
continue
}
for relatedObject in relatedObjects {
if !relatedObjectsUniqueArray.includesObjectWithDatabaseID(relatedObject.databaseID) {
relatedObjectsUniqueArray += [relatedObject]
}
}
}
return relatedObjectsUniqueArray
}
func syncRelatedObjectsAndLookupTable(_ object: DatabaseObject, _ lookupTable: RelatedObjectIDsMap, _ database: FMDatabase) {
guard let relatedObjects = object.relatedObjectsWithName(relationshipName) else {
assertionFailure("syncRelatedObjectsAndLookupTable should be called only on objects with related objects.")
return
}
let relatedObjectIDs = relatedObjects.databaseIDs()
let lookupTableRelatedObjectIDs = lookupTable[object.databaseID] ?? Set<String>()
let relatedObjectIDsToDelete = lookupTableRelatedObjectIDs.subtracting(relatedObjectIDs)
if !relatedObjectIDsToDelete.isEmpty {
deleteLookups(for: object.databaseID, relatedObjectIDsToDelete, database)
}
let relatedObjectIDsToSave = relatedObjectIDs.subtracting(lookupTableRelatedObjectIDs)
if !relatedObjectIDsToSave.isEmpty {
saveLookups(for: object.databaseID, relatedObjectIDsToSave, database)
}
}
func saveLookups(for objectID: String, _ relatedObjectIDs: Set<String>, _ database: FMDatabase) {
for relatedObjectID in relatedObjectIDs {
let d: [NSObject: Any] = [(objectIDKey as NSString): objectID, (relatedObjectIDKey as NSString): relatedObjectID]
let _ = database.rs_insertRow(with: d, insertType: .orIgnore, tableName: name)
}
}
// MARK: Fetching
func fetchRelatedObjectsWithIDs(_ relatedObjectIDs: Set<String>, _ database: FMDatabase) -> [DatabaseObject]? {
guard let relatedObjects = relatedTable.fetchObjectsWithIDs(relatedObjectIDs, in: database), !relatedObjects.isEmpty else {
return nil
}
return relatedObjects
}
func fetchRelatedObjectIDsMap(_ objectIDs: Set<String>, _ database: FMDatabase) -> RelatedObjectIDsMap? {
guard let lookupValues = fetchLookupValues(objectIDs, database) else {
return nil
}
return RelatedObjectIDsMap(lookupValues: lookupValues)
}
func fetchLookupValues(_ objectIDs: Set<String>, _ database: FMDatabase) -> Set<LookupValue>? {
guard !objectIDs.isEmpty, let resultSet = database.rs_selectRowsWhereKey(objectIDKey, inValues: Array(objectIDs), tableName: name) else {
return nil
}
return lookupValuesWithResultSet(resultSet)
}
func lookupValuesWithResultSet(_ resultSet: FMResultSet) -> Set<LookupValue> {
return resultSet.mapToSet(lookupValueWithRow)
}
func lookupValueWithRow(_ row: FMResultSet) -> LookupValue? {
guard let objectID = row.string(forColumn: objectIDKey) else {
return nil
}
guard let relatedObjectID = row.string(forColumn: relatedObjectIDKey) else {
return nil
}
return LookupValue(objectID: objectID, relatedObjectID: relatedObjectID)
}
}

View File

@ -1,82 +0,0 @@
//
// DatabaseRelatedObjectsTable.swift
// RSDatabase
//
// Created by Brent Simmons on 9/2/17.
// Copyright © 2017 Ranchero Software, LLC. All rights reserved.
//
import Foundation
// Protocol for a database table for related objects  authors and attachments in Evergreen, for instance.
public protocol DatabaseRelatedObjectsTable: DatabaseTable {
var databaseIDKey: String { get}
var cache: DatabaseObjectCache { get }
func fetchObjectsWithIDs(_ databaseIDs: Set<String>, in database: FMDatabase) -> [DatabaseObject]?
func objectsWithResultSet(_ resultSet: FMResultSet) -> [DatabaseObject]
func objectWithRow(_ row: FMResultSet) -> DatabaseObject?
func save(_ objects: [DatabaseObject], in database: FMDatabase)
}
public extension DatabaseRelatedObjectsTable {
// MARK: Default implementations
func fetchObjectsWithIDs(_ databaseIDs: Set<String>, in database: FMDatabase) -> [DatabaseObject]? {
if databaseIDs.isEmpty {
return nil
}
var cachedObjects = [DatabaseObject]()
var databaseIDsToFetch = Set<String>()
for databaseID in databaseIDs {
if let cachedObject = cache[databaseID] {
cachedObjects += [cachedObject]
}
else {
databaseIDsToFetch.insert(databaseID)
}
}
if databaseIDsToFetch.isEmpty {
return cachedObjects
}
guard let resultSet = selectRowsWhere(key: databaseIDKey, inValues: Array(databaseIDsToFetch), in: database) else {
return cachedObjects
}
let fetchedDatabaseObjects = objectsWithResultSet(resultSet)
cache.add(fetchedDatabaseObjects)
return cachedObjects + fetchedDatabaseObjects
}
func objectsWithResultSet(_ resultSet: FMResultSet) -> [DatabaseObject] {
return resultSet.compactMap(objectWithRow)
}
func save(_ objects: [DatabaseObject], in database: FMDatabase) {
// Objects in cache must already exist in database. Filter them out.
let objectsToSave = objects.filter { (object) -> Bool in
if let _ = cache[object.databaseID] {
return false
}
return true
}
cache.add(objectsToSave)
if let databaseDictionaries = objectsToSave.databaseDictionaries() {
insertRows(databaseDictionaries, insertType: .orIgnore, in: database)
}
}
}

View File

@ -1,76 +0,0 @@
//
// RelatedObjectIDsMap.swift
// RSDatabase
//
// Created by Brent Simmons on 9/10/17.
// Copyright © 2017 Ranchero Software, LLC. All rights reserved.
//
import Foundation
// Maps objectIDs to Set<String> where the Strings are relatedObjectIDs.
struct RelatedObjectIDsMap {
private let dictionary: [String: Set<String>] // objectID: Set<relatedObjectID>
init(dictionary: [String: Set<String>]) {
self.dictionary = dictionary
}
init(lookupValues: Set<LookupValue>) {
var d = [String: Set<String>]()
for lookupValue in lookupValues {
let objectID = lookupValue.objectID
let relatedObjectID: String = lookupValue.relatedObjectID
if d[objectID] == nil {
d[objectID] = Set([relatedObjectID])
}
else {
d[objectID]!.insert(relatedObjectID)
}
}
self.init(dictionary: d)
}
func objectIDs() -> Set<String> {
return Set(dictionary.keys)
}
func relatedObjectIDs() -> Set<String> {
var ids = Set<String>()
for (_, relatedObjectIDs) in dictionary {
ids.formUnion(relatedObjectIDs)
}
return ids
}
subscript(_ objectID: String) -> Set<String>? {
return dictionary[objectID]
}
}
struct LookupValue: Hashable {
let objectID: String
let relatedObjectID: String
let hashValue: Int
init(objectID: String, relatedObjectID: String) {
self.objectID = objectID
self.relatedObjectID = relatedObjectID
self.hashValue = (objectID + relatedObjectID).hashValue
}
static func ==(lhs: LookupValue, rhs: LookupValue) -> Bool {
return lhs.objectID == rhs.objectID && lhs.relatedObjectID == rhs.relatedObjectID
}
}

View File

@ -1,44 +0,0 @@
//
// RelatedObjectsMap.swift
// RSDatabase
//
// Created by Brent Simmons on 9/10/17.
// Copyright © 2017 Ranchero Software, LLC. All rights reserved.
//
import Foundation
// Map objectID to [DatabaseObject] (related objects).
// Its used as the return value for DatabaseLookupTable.fetchRelatedObjects.
public struct RelatedObjectsMap {
private let dictionary: [String: [DatabaseObject]] // objectID: relatedObjects
init(relatedObjects: [DatabaseObject], relatedObjectIDsMap: RelatedObjectIDsMap) {
var d = [String: [DatabaseObject]]()
let relatedObjectsDictionary = relatedObjects.dictionary()
for objectID in relatedObjectIDsMap.objectIDs() {
if let relatedObjectIDs = relatedObjectIDsMap[objectID] {
let relatedObjects = relatedObjectIDs.compactMap{ relatedObjectsDictionary[$0] }
if !relatedObjects.isEmpty {
d[objectID] = relatedObjects
}
}
}
self.dictionary = d
}
public func objectIDs() -> Set<String> {
return Set(dictionary.keys)
}
public subscript(_ objectID: String) -> [DatabaseObject]? {
return dictionary[objectID]
}
}

View File

@ -1,18 +0,0 @@
ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES
LD_RUNPATH_SEARCH_PATHS = $(inherited) @executable_path/../Frameworks @loader_path/../Frameworks
INFOPLIST_FILE = RSDatabaseTests/Info.plist
PRODUCT_BUNDLE_IDENTIFIER = com.ranchero.RSDatabaseTests
PRODUCT_NAME = $(TARGET_NAME)
CLANG_ENABLE_OBJC_WEAK = YES
SWIFT_VERSION = 3.0

View File

@ -1,24 +0,0 @@
#include "./RSDatabase_target.xcconfig"
CODE_SIGN_IDENTITY =
DEVELOPMENT_TEAM = 9C84TZ7Q6Z
// See the notes in Evergreen_target.xcconfig on why the
// DeveloperSettings.xcconfig is #included here
// #include? "../../../SharedXcodeSettings/DeveloperSettings.xcconfig"
SDKROOT = iphoneos
TARGETED_DEVICE_FAMILY = 1,2
IPHONEOS_DEPLOYMENT_TARGET = 10.2
LD_RUNPATH_SEARCH_PATHS = $(inherited) @executable_path/Frameworks @loader_path/Frameworks
INFOPLIST_FILE = RSDatabaseiOS/Info.plist
PRODUCT_BUNDLE_IDENTIFIER = com.ranchero.RSDatabaseiOS
PRODUCT_MODULE_NAME = RSDatabase
PRODUCT_NAME = RSDatabase
CLANG_WARN_DOCUMENTATION_COMMENTS = YES
CLANG_WARN_INFINITE_RECURSION = YES
CLANG_WARN_SUSPICIOUS_MOVE = YES
CLANG_ANALYZER_NONNULL = YES

View File

@ -1,5 +0,0 @@
#include "./RSDatabase_ios_target.xcconfig"
VALIDATE_PRODUCT = NO

View File

@ -1,4 +0,0 @@
#include "./RSDatabase_ios_target.xcconfig"
VALIDATE_PRODUCT = YES

View File

@ -1,15 +0,0 @@
#include "./RSDatabase_target.xcconfig"
CODE_SIGN_IDENTITY =
DEVELOPMENT_TEAM = 9C84TZ7Q6Z
// See the notes in Evergreen_target.xcconfig on why the
// DeveloperSettings.xcconfig is #included here
#include? "../../../SharedXcodeSettings/DeveloperSettings.xcconfig"
INFOPLIST_FILE = RSDatabase/Info.plist
PRODUCT_BUNDLE_IDENTIFIER = com.ranchero.RSDatabase
OTHER_SWIFT_FLAGS = -Xfrontend -warn-long-function-bodies=300

View File

@ -1,49 +0,0 @@
SDKROOT = macosx
COPY_PHASE_STRIP = NO
MACOSX_DEPLOYMENT_TARGET = 10.13
ALWAYS_SEARCH_USER_PATHS = NO
CURRENT_PROJECT_VERSION = 1
VERSION_INFO_PREFIX =
VERSIONING_SYSTEM = apple-generic
GCC_NO_COMMON_BLOCKS = YES
GCC_C_LANGUAGE_STANDARD = gnu99
CLANG_CXX_LANGUAGE_STANDARD = gnu++0x
CLANG_CXX_LIBRARY = libc++
CLANG_ALLOW_NON_MODULAR_INCLUDES_IN_FRAMEWORK_MODULES = YES
CLANG_ENABLE_MODULES = YES
CLANG_ENABLE_OBJC_ARC = YES
ENABLE_STRICT_OBJC_MSGSEND = YES
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES
CLANG_WARN_EMPTY_BODY = YES
CLANG_WARN_BOOL_CONVERSION = YES
CLANG_WARN_CONSTANT_CONVERSION = YES
GCC_WARN_64_TO_32_BIT_CONVERSION = YES
CLANG_WARN_ENUM_CONVERSION = YES
CLANG_WARN_INT_CONVERSION = YES
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES
CLANG_WARN_INFINITE_RECURSION = YES
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR
CLANG_WARN_STRICT_PROTOTYPES = YES
CLANG_WARN_COMMA = YES
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE
CLANG_WARN_UNREACHABLE_CODE = YES
GCC_WARN_UNUSED_FUNCTION = YES
GCC_WARN_UNUSED_VARIABLE = YES
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES
CLANG_WARN_SUSPICIOUS_MOVE = YES
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES
GCC_WARN_UNDECLARED_SELECTOR = YES
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES
SWIFT_SWIFT3_OBJC_INFERENCE = Off
CLANG_ENABLE_OBJC_WEAK = YES
SWIFT_VERSION = 4.0
COMBINE_HIDPI_IMAGES = YES

View File

@ -1,15 +0,0 @@
#include "./RSDatabase_project.xcconfig"
DEBUG_INFORMATION_FORMAT = dwarf
ENABLE_TESTABILITY = YES
GCC_DYNAMIC_NO_PIC = NO
GCC_OPTIMIZATION_LEVEL = 0
GCC_PREPROCESSOR_DEFINITIONS = DEBUG=1 $(inherited)
GCC_TREAT_WARNINGS_AS_ERRORS = YES
MTL_ENABLE_DEBUG_INFO = YES
SWIFT_COMPILATION_MODE = singlefile
SWIFT_OPTIMIZATION_LEVEL = -Onone
ONLY_ACTIVE_ARCH = YES

View File

@ -1,9 +0,0 @@
#include "./RSDatabase_project.xcconfig"
DEBUG_INFORMATION_FORMAT = dwarf-with-dsym
ENABLE_NS_ASSERTIONS = NO
MTL_ENABLE_DEBUG_INFO = NO
SWIFT_OPTIMIZATION_LEVEL = -O
SWIFT_COMPILATION_MODE = wholemodule

View File

@ -1,12 +0,0 @@
INSTALL_PATH = $(LOCAL_LIBRARY_DIR)/Frameworks
SKIP_INSTALL = YES
DYLIB_COMPATIBILITY_VERSION = 1
DYLIB_CURRENT_VERSION = 1
DYLIB_INSTALL_NAME_BASE = @rpath
LD_RUNPATH_SEARCH_PATHS = $(inherited) @executable_path/../Frameworks @loader_path/Frameworks
DEFINES_MODULE = YES
FRAMEWORK_VERSION = A
PRODUCT_NAME = $(TARGET_NAME)
CLANG_ENABLE_MODULES = YES