首次提交

This commit is contained in:
启星
2025-08-08 11:05:33 +08:00
parent 1b3bb91b4a
commit adc1a2a25d
8803 changed files with 708874 additions and 0 deletions

28
Pods/FMDB/LICENSE.txt generated Normal file
View File

@@ -0,0 +1,28 @@
If you are using FMDB in your project, I'd love to hear about it. Let Gus know
by sending an email to gus@flyingmeat.com.
And if you happen to come across either Gus Mueller or Rob Ryan in a bar, you
might consider purchasing a drink of their choosing if FMDB has been useful to
you.
Finally, and shortly, this is the MIT License.
Copyright (c) 2008-2014 Flying Meat Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

546
Pods/FMDB/README.markdown generated Normal file
View File

@@ -0,0 +1,546 @@
# FMDB v2.7
<!--[![Platform](https://img.shields.io/cocoapods/p/FMDB.svg?style=flat)](http://cocoadocs.org/docsets/Alamofire)-->
[![CocoaPods Compatible](https://img.shields.io/cocoapods/v/FMDB.svg)](https://img.shields.io/cocoapods/v/FMDB.svg)
[![Carthage Compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage)
This is an Objective-C wrapper around [SQLite](https://sqlite.org/).
## The FMDB Mailing List:
https://groups.google.com/group/fmdb
## Read the SQLite FAQ:
https://www.sqlite.org/faq.html
Since FMDB is built on top of SQLite, you're going to want to read this page top to bottom at least once. And while you're there, make sure to bookmark the SQLite Documentation page: https://www.sqlite.org/docs.html
## Contributing
Do you have an awesome idea that deserves to be in FMDB? You might consider pinging ccgus first to make sure he hasn't already ruled it out for some reason. Otherwise pull requests are great, and make sure you stick to the local coding conventions. However, please be patient and if you haven't heard anything from ccgus for a week or more, you might want to send a note asking what's up.
## Installing
### CocoaPods
FMDB can be installed using [CocoaPods](https://cocoapods.org/).
If you haven't done so already, you might want to initialize the project, to have it produce a `Podfile` template for you:
```
$ pod init
```
Then, edit the `Podfile`, adding `FMDB`:
```ruby
# Uncomment the next line to define a global platform for your project
# platform :ios, '12.0'
target 'MyApp' do
# Comment the next line if you're not using Swift and don't want to use dynamic frameworks
use_frameworks!
# Pods for MyApp2
pod 'FMDB'
# pod 'FMDB/FTS' # FMDB with FTS
# pod 'FMDB/standalone' # FMDB with latest SQLite amalgamation source
# pod 'FMDB/standalone/FTS' # FMDB with latest SQLite amalgamation source and FTS
# pod 'FMDB/SQLCipher' # FMDB with SQLCipher
end
```
Then install the pods:
```
$ pod install
```
Then open the `.xcworkspace` rather than the `.xcodeproj`.
For more information on Cocoapods visit https://cocoapods.org.
**If using FMDB with [SQLCipher](https://www.zetetic.net/sqlcipher/) you must use the FMDB/SQLCipher subspec. The FMDB/SQLCipher subspec declares SQLCipher as a dependency, allowing FMDB to be compiled with the `-DSQLITE_HAS_CODEC` flag.**
### Carthage
Once you make sure you have [the latest version of Carthage](https://github.com/Carthage/Carthage/releases), you can open up a command line terminal, navigate to your project's main directory, and then do the following commands:
```
$ echo ' github "ccgus/fmdb" ' > ./Cartfile
$ carthage update
```
You can then configure your project as outlined in Carthage's [Getting Started](https://github.com/Carthage/Carthage#getting-started) (i.e. for iOS, adding the framework to the "Link Binary with Libraries" in your target and adding the `copy-frameworks` script; in macOS, adding the framework to the list of "Embedded Binaries").
### Swift Package Manager
Declare FMDB as a package dependency.
```swift
.package(
name: "FMDB",
url: "https://github.com/ccgus/fmdb",
.upToNextMinor(from: "2.7.12")),
```
Use FMDB in target dependencies
```swift
.product(name: "FMDB", package: "FMDB")
```
## FMDB Class Reference:
https://ccgus.github.io/fmdb/html/index.html
## Automatic Reference Counting (ARC) or Manual Memory Management?
You can use either style in your Cocoa project. FMDB will figure out which you are using at compile time and do the right thing.
## What's New in FMDB 2.7
FMDB 2.7 attempts to support a more natural interface. This represents a fairly significant change for Swift developers (audited for nullability; shifted to properties in external interfaces where possible rather than methods; etc.). For Objective-C developers, this should be a fairly seamless transition (unless you were using the ivars that were previously exposed in the public interface, which you shouldn't have been doing, anyway!).
### Nullability and Swift Optionals
FMDB 2.7 is largely the same as prior versions, but has been audited for nullability. For Objective-C users, this simply means that if you perform a static analysis of your FMDB-based project, you may receive more meaningful warnings as you review your project, but there are likely to be few, if any, changes necessary in your code.
For Swift users, this nullability audit results in changes that are not entirely backward compatible with FMDB 2.6, but is a little more Swifty. Before FMDB was audited for nullability, Swift was forced to defensively assume that variables were optional, but the library now more accurately knows which properties and method parameters are optional, and which are not.
This means, though, that Swift code written for FMDB 2.7 may require changes. For example, consider the following Swift 3/Swift 4 code for FMDB 2.6:
```swift
queue.inTransaction { db, rollback in
do {
guard let db == db else {
// handle error here
return
}
try db.executeUpdate("INSERT INTO foo (bar) VALUES (?)", values: [1])
try db.executeUpdate("INSERT INTO foo (bar) VALUES (?)", values: [2])
} catch {
rollback?.pointee = true
}
}
```
Because FMDB 2.6 was not audited for nullability, Swift inferred that `db` and `rollback` were optionals. But, now, in FMDB 2.7, Swift now knows that, for example, neither `db` nor `rollback` above can be `nil`, so they are no longer optionals. Thus it becomes:
```swift
queue.inTransaction { db, rollback in
do {
try db.executeUpdate("INSERT INTO foo (bar) VALUES (?)", values: [1])
try db.executeUpdate("INSERT INTO foo (bar) VALUES (?)", values: [2])
} catch {
rollback.pointee = true
}
}
```
### Custom Functions
In the past, when writing custom functions, you would have to generally include your own `@autoreleasepool` block to avoid problems when writing functions that scanned through a large table. Now, FMDB will automatically wrap it in an autorelease pool, so you don't have to.
Also, in the past, when retrieving the values passed to the function, you had to drop down to the SQLite C API and include your own `sqlite3_value_XXX` calls. There are now `FMDatabase` methods, `valueInt`, `valueString`, etc., so you can stay within Swift and/or Objective-C, without needing to call the C functions yourself. Likewise, when specifying the return values, you no longer need to call `sqlite3_result_XXX` C API, but rather you can use `FMDatabase` methods, `resultInt`, `resultString`, etc. There is a new `enum` for `valueType` called `SqliteValueType`, which can be used for checking the type of parameter passed to the custom function.
Thus, you can do something like (as of Swift 3):
```swift
db.makeFunctionNamed("RemoveDiacritics", arguments: 1) { context, argc, argv in
guard db.valueType(argv[0]) == .text || db.valueType(argv[0]) == .null else {
db.resultError("Expected string parameter", context: context)
return
}
if let string = db.valueString(argv[0])?.folding(options: .diacriticInsensitive, locale: nil) {
db.resultString(string, context: context)
} else {
db.resultNull(context: context)
}
}
```
And you can then use that function in your SQL (in this case, matching both "Jose" and "José"):
```sql
SELECT * FROM employees WHERE RemoveDiacritics(first_name) LIKE 'jose'
```
Note, the method `makeFunctionNamed:maximumArguments:withBlock:` has been renamed to `makeFunctionNamed:arguments:block:`, to more accurately reflect the functional intent of the second parameter.
### API Changes
In addition to the `makeFunctionNamed` noted above, there are a few other API changes. Specifically,
- To become consistent with the rest of the API, the methods `objectForColumnName` and `UTF8StringForColumnName` have been renamed to `objectForColumn` and `UTF8StringForColumn`.
- Note, the `objectForColumn` (and the associted subscript operator) now returns `nil` if an invalid column name/index is passed to it. It used to return `NSNull`.
- To avoid confusion with `FMDatabaseQueue` method `inTransaction`, which performs transactions, the `FMDatabase` method to determine whether you are in a transaction or not, `inTransaction`, has been replaced with a read-only property, `isInTransaction`.
- Several functions have been converted to properties, namely, `databasePath`, `maxBusyRetryTimeInterval`, `shouldCacheStatements`, `sqliteHandle`, `hasOpenResultSets`, `lastInsertRowId`, `changes`, `goodConnection`, `columnCount`, `resultDictionary`, `applicationID`, `applicationIDString`, `userVersion`, `countOfCheckedInDatabases`, `countOfCheckedOutDatabases`, and `countOfOpenDatabases`. For Objective-C users, this has little material impact, but for Swift users, it results in a slightly more natural interface. Note: For Objective-C developers, previously versions of FMDB exposed many ivars (but we hope you weren't using them directly, anyway!), but the implmentation details for these are no longer exposed.
### URL Methods
In keeping with Apple's shift from paths to URLs, there are now `NSURL` renditions of the various `init` methods, previously only accepting paths.
## Usage
There are three main classes in FMDB:
1. `FMDatabase` - Represents a single SQLite database. Used for executing SQL statements.
2. `FMResultSet` - Represents the results of executing a query on an `FMDatabase`.
3. `FMDatabaseQueue` - If you're wanting to perform queries and updates on multiple threads, you'll want to use this class. It's described in the "Thread Safety" section below.
### Database Creation
An `FMDatabase` is created with a path to a SQLite database file. This path can be one of these three:
1. A file system path. The file does not have to exist on disk. If it does not exist, it is created for you.
2. An empty string (`@""`). An empty database is created at a temporary location. This database is deleted when the `FMDatabase` connection is closed.
3. `NULL`. An in-memory database is created. This database will be destroyed when the `FMDatabase` connection is closed.
(For more information on temporary and in-memory databases, read the sqlite documentation on the subject: https://www.sqlite.org/inmemorydb.html)
```objc
NSString *path = [NSTemporaryDirectory() stringByAppendingPathComponent:@"tmp.db"];
FMDatabase *db = [FMDatabase databaseWithPath:path];
```
### Opening
Before you can interact with the database, it must be opened. Opening fails if there are insufficient resources or permissions to open and/or create the database.
```objc
if (![db open]) {
// [db release]; // uncomment this line in manual referencing code; in ARC, this is not necessary/permitted
db = nil;
return;
}
```
### Executing Updates
Any sort of SQL statement which is not a `SELECT` statement qualifies as an update. This includes `CREATE`, `UPDATE`, `INSERT`, `ALTER`, `COMMIT`, `BEGIN`, `DETACH`, `DELETE`, `DROP`, `END`, `EXPLAIN`, `VACUUM`, and `REPLACE` statements (plus many more). Basically, if your SQL statement does not begin with `SELECT`, it is an update statement.
Executing updates returns a single value, a `BOOL`. A return value of `YES` means the update was successfully executed, and a return value of `NO` means that some error was encountered. You may invoke the `-lastErrorMessage` and `-lastErrorCode` methods to retrieve more information.
### Executing Queries
A `SELECT` statement is a query and is executed via one of the `-executeQuery...` methods.
Executing queries returns an `FMResultSet` object if successful, and `nil` upon failure. You should use the `-lastErrorMessage` and `-lastErrorCode` methods to determine why a query failed.
In order to iterate through the results of your query, you use a `while()` loop. You also need to "step" from one record to the other. With FMDB, the easiest way to do that is like this:
```objc
FMResultSet *s = [db executeQuery:@"SELECT * FROM myTable"];
while ([s next]) {
//retrieve values for each record
}
```
You must always invoke `-[FMResultSet next]` before attempting to access the values returned in a query, even if you're only expecting one:
```objc
FMResultSet *s = [db executeQuery:@"SELECT COUNT(*) FROM myTable"];
if ([s next]) {
int totalCount = [s intForColumnIndex:0];
}
[s close]; // Call the -close method on the FMResultSet if you cannot confirm whether the result set is exhausted.
```
`FMResultSet` has many methods to retrieve data in an appropriate format:
- `intForColumn:`
- `longForColumn:`
- `longLongIntForColumn:`
- `boolForColumn:`
- `doubleForColumn:`
- `stringForColumn:`
- `dateForColumn:`
- `dataForColumn:`
- `dataNoCopyForColumn:`
- `UTF8StringForColumn:`
- `objectForColumn:`
Each of these methods also has a `{type}ForColumnIndex:` variant that is used to retrieve the data based on the position of the column in the results, as opposed to the column's name.
Typically, there's no need to `-close` an `FMResultSet` yourself, since that happens when either the result set is exhausted. However, if you only pull out a single request or any other number of requests which don't exhaust the result set, you will need to call the `-close` method on the `FMResultSet`.
### Closing
When you have finished executing queries and updates on the database, you should `-close` the `FMDatabase` connection so that SQLite will relinquish any resources it has acquired during the course of its operation.
```objc
[db close];
```
### Transactions
`FMDatabase` can begin and commit a transaction by invoking one of the appropriate methods or executing a begin/end transaction statement.
### Multiple Statements and Batch Stuff
You can use `FMDatabase`'s executeStatements:withResultBlock: to do multiple statements in a string:
```objc
NSString *sql = @"create table bulktest1 (id integer primary key autoincrement, x text);"
"create table bulktest2 (id integer primary key autoincrement, y text);"
"create table bulktest3 (id integer primary key autoincrement, z text);"
"insert into bulktest1 (x) values ('XXX');"
"insert into bulktest2 (y) values ('YYY');"
"insert into bulktest3 (z) values ('ZZZ');";
success = [db executeStatements:sql];
sql = @"select count(*) as count from bulktest1;"
"select count(*) as count from bulktest2;"
"select count(*) as count from bulktest3;";
success = [self.db executeStatements:sql withResultBlock:^int(NSDictionary *dictionary) {
NSInteger count = [dictionary[@"count"] integerValue];
XCTAssertEqual(count, 1, @"expected one record for dictionary %@", dictionary);
return 0;
}];
```
### Data Sanitization
When providing a SQL statement to FMDB, you should not attempt to "sanitize" any values before insertion. Instead, you should use the standard SQLite binding syntax:
```sql
INSERT INTO myTable VALUES (?, ?, ?, ?)
```
The `?` character is recognized by SQLite as a placeholder for a value to be inserted. The execution methods all accept a variable number of arguments (or a representation of those arguments, such as an `NSArray`, `NSDictionary`, or a `va_list`), which are properly escaped for you.
And, to use that SQL with the `?` placeholders from Objective-C:
```objc
NSInteger identifier = 42;
NSString *name = @"Liam O'Flaherty (\"the famous Irish author\")";
NSDate *date = [NSDate date];
NSString *comment = nil;
BOOL success = [db executeUpdate:@"INSERT INTO authors (identifier, name, date, comment) VALUES (?, ?, ?, ?)", @(identifier), name, date, comment ?: [NSNull null]];
if (!success) {
NSLog(@"error = %@", [db lastErrorMessage]);
}
```
> **Note:** Fundamental data types, like the `NSInteger` variable `identifier`, should be as a `NSNumber` objects, achieved by using the `@` syntax, shown above. Or you can use the `[NSNumber numberWithInt:identifier]` syntax, too.
>
> Likewise, SQL `NULL` values should be inserted as `[NSNull null]`. For example, in the case of `comment` which might be `nil` (and is in this example), you can use the `comment ?: [NSNull null]` syntax, which will insert the string if `comment` is not `nil`, but will insert `[NSNull null]` if it is `nil`.
In Swift, you would use `executeUpdate(values:)`, which not only is a concise Swift syntax, but also `throws` errors for proper error handling:
```swift
do {
let identifier = 42
let name = "Liam O'Flaherty (\"the famous Irish author\")"
let date = Date()
let comment: String? = nil
try db.executeUpdate("INSERT INTO authors (identifier, name, date, comment) VALUES (?, ?, ?, ?)", values: [identifier, name, date, comment ?? NSNull()])
} catch {
print("error = \(error)")
}
```
> **Note:** In Swift, you don't have to wrap fundamental numeric types like you do in Objective-C. But if you are going to insert an optional string, you would probably use the `comment ?? NSNull()` syntax (i.e., if it is `nil`, use `NSNull`, otherwise use the string).
Alternatively, you may use named parameters syntax:
```sql
INSERT INTO authors (identifier, name, date, comment) VALUES (:identifier, :name, :date, :comment)
```
The parameters *must* start with a colon. SQLite itself supports other characters, but internally the dictionary keys are prefixed with a colon, do **not** include the colon in your dictionary keys.
```objc
NSDictionary *arguments = @{@"identifier": @(identifier), @"name": name, @"date": date, @"comment": comment ?: [NSNull null]};
BOOL success = [db executeUpdate:@"INSERT INTO authors (identifier, name, date, comment) VALUES (:identifier, :name, :date, :comment)" withParameterDictionary:arguments];
if (!success) {
NSLog(@"error = %@", [db lastErrorMessage]);
}
```
The key point is that one should not use `NSString` method `stringWithFormat` to manually insert values into the SQL statement, itself. Nor should one Swift string interpolation to insert values into the SQL. Use `?` placeholders for values to be inserted into the database (or used in `WHERE` clauses in `SELECT` statements).
<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`. Instantiate a single `FMDatabaseQueue` and use it across multiple threads. The `FMDatabaseQueue` object will synchronize and coordinate access across the multiple threads. Here's how to use it:
First, make your queue.
```objc
FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:aPath];
```
Then use it like so:
```objc
[queue inDatabase:^(FMDatabase *db) {
[db executeUpdate:@"INSERT INTO myTable VALUES (?)", @1];
[db executeUpdate:@"INSERT INTO myTable VALUES (?)", @2];
[db executeUpdate:@"INSERT INTO myTable VALUES (?)", @3];
FMResultSet *rs = [db executeQuery:@"select * from foo"];
while ([rs next]) {
}
}];
```
An easy way to wrap things up in a transaction can be done like this:
```objc
[queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
[db executeUpdate:@"INSERT INTO myTable VALUES (?)", @1];
[db executeUpdate:@"INSERT INTO myTable VALUES (?)", @2];
[db executeUpdate:@"INSERT INTO myTable VALUES (?)", @3];
if (whoopsSomethingWrongHappened) {
*rollback = YES;
return;
}
// etc ...
}];
```
The Swift equivalent would be:
```swift
queue.inTransaction { db, rollback in
do {
try db.executeUpdate("INSERT INTO myTable VALUES (?)", values: [1])
try db.executeUpdate("INSERT INTO myTable VALUES (?)", values: [2])
try db.executeUpdate("INSERT INTO myTable VALUES (?)", values: [3])
if whoopsSomethingWrongHappened {
rollback.pointee = true
return
}
// etc ...
} catch {
rollback.pointee = true
print(error)
}
}
```
(Note, as of Swift 3, use `pointee`. But in Swift 2.3, use `memory` rather than `pointee`.)
`FMDatabaseQueue` will run the blocks on a serialized queue (hence the name of the class). So if you call `FMDatabaseQueue`'s methods from multiple threads at the same time, they will be executed in the order they are received. This way queries and updates won't step on each other's toes, and every one is happy.
**Note:** The calls to `FMDatabaseQueue`'s methods are blocking. So even though you are passing along blocks, they will **not** be run on another thread.
## Making custom sqlite functions, based on blocks.
You can do this! For an example, look for `-makeFunctionNamed:` in main.m
## Swift
You can use FMDB in Swift projects too.
To do this, you must:
1. Copy the relevant `.m` and `.h` files from the FMDB `src` folder into your project.
You can copy all of them (which is easiest), or only the ones you need. Likely you will need [`FMDatabase`](https://ccgus.github.io/fmdb/html/Classes/FMDatabase.html) and [`FMResultSet`](https://ccgus.github.io/fmdb/html/Classes/FMResultSet.html) at a minimum. [`FMDatabaseAdditions`](https://ccgus.github.io/fmdb/html/Categories/FMDatabase+FMDatabaseAdditions.html) provides some very useful convenience methods, so you will likely want that, too. If you are doing multithreaded access to a database, [`FMDatabaseQueue`](https://ccgus.github.io/fmdb/html/Classes/FMDatabaseQueue.html) is quite useful, too. If you choose to not copy all of the files from the `src` directory, though, you may want to update `FMDB.h` to only reference the files that you included in your project.
Note, if you're copying all of the files from the `src` folder into to your project (which is recommended), you may want to drag the individual files into your project, not the folder, itself, because if you drag the folder, you won't be prompted to add the bridging header (see next point).
2. If prompted to create a "bridging header", you should do so. If not prompted and if you don't already have a bridging header, add one.
For more information on bridging headers, see [Swift and Objective-C in the Same Project](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/BuildingCocoaApps/MixandMatch.html#//apple_ref/doc/uid/TP40014216-CH10-XID_76).
3. In your bridging header, add a line that says:
```objc
#import "FMDB.h"
```
4. Use the variations of `executeQuery` and `executeUpdate` with the `sql` and `values` parameters with `try` pattern, as shown below. These renditions of `executeQuery` and `executeUpdate` both `throw` errors in true Swift fashion.
If you do the above, you can then write Swift code that uses `FMDatabase`. For example, as of Swift 3:
```swift
let fileURL = try! FileManager.default
.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
.appendingPathComponent("test.sqlite")
let database = FMDatabase(url: fileURL)
guard database.open() else {
print("Unable to open database")
return
}
do {
try database.executeUpdate("create table test(x text, y text, z text)", values: nil)
try database.executeUpdate("insert into test (x, y, z) values (?, ?, ?)", values: ["a", "b", "c"])
try database.executeUpdate("insert into test (x, y, z) values (?, ?, ?)", values: ["e", "f", "g"])
let rs = try database.executeQuery("select x, y, z from test", values: nil)
while rs.next() {
if let x = rs.string(forColumn: "x"), let y = rs.string(forColumn: "y"), let z = rs.string(forColumn: "z") {
print("x = \(x); y = \(y); z = \(z)")
}
}
} catch {
print("failed: \(error.localizedDescription)")
}
database.close()
```
## History
The history and changes are availbe on its [GitHub page](https://github.com/ccgus/fmdb) and are summarized in the "CHANGES_AND_TODO_LIST.txt" file.
## Contributors
The contributors to FMDB are contained in the "Contributors.txt" file.
## Additional projects using FMDB, which might be interesting to the discerning developer.
* FMDBMigrationManager, A SQLite schema migration management system for FMDB: https://github.com/layerhq/FMDBMigrationManager
* FCModel, An alternative to Core Data for people who like having direct SQL access: https://github.com/marcoarment/FCModel
## Quick notes on FMDB's coding style
Spaces, not tabs. Square brackets, not dot notation. Look at what FMDB already does with curly brackets and such, and stick to that style.
## Reporting bugs
Reduce your bug down to the smallest amount of code possible. You want to make it super easy for the developers to see and reproduce your bug. If it helps, pretend that the person who can fix your bug is active on shipping 3 major products, works on a handful of open source projects, has a newborn baby, and is generally very very busy.
And we've even added a template function to main.m (FMDBReportABugFunction) in the FMDB distribution to help you out:
* Open up fmdb project in Xcode.
* Open up main.m and modify the FMDBReportABugFunction to reproduce your bug.
* Setup your table(s) in the code.
* Make your query or update(s).
* Add some assertions which demonstrate the bug.
Then you can bring it up on the FMDB mailing list by showing your nice and compact FMDBReportABugFunction, or you can report the bug via the github FMDB bug reporter.
**Optional:**
Figure out where the bug is, fix it, and send a patch in or bring that up on the mailing list. Make sure all the other tests run after your modifications.
## Support
The support channels for FMDB are the mailing list (see above), filing a bug here, or maybe on Stack Overflow. So that is to say, support is provided by the community and on a voluntary basis.
FMDB development is overseen by Gus Mueller of Flying Meat. If FMDB been helpful to you, consider purchasing an app from FM or telling all your friends about it.
## License
The license for FMDB is contained in the "License.txt" file.
If you happen to come across either Gus Mueller or Rob Ryan in a bar, you might consider purchasing a drink of their choosing if FMDB has been useful to you.
(The drink is for them of course, shame on you for trying to keep it.)

14
Pods/FMDB/privacy/PrivacyInfo.xcprivacy generated Normal file
View File

@@ -0,0 +1,14 @@
<?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>NSPrivacyTracking</key>
<false/>
<key>NSPrivacyTrackingDomains</key>
<array/>
<key>NSPrivacyCollectedDataTypes</key>
<array/>
<key>NSPrivacyAccessedAPITypes</key>
<array/>
</dict>
</plist>

10
Pods/FMDB/src/fmdb/FMDB.h generated Normal file
View File

@@ -0,0 +1,10 @@
#import <Foundation/Foundation.h>
FOUNDATION_EXPORT double FMDBVersionNumber;
FOUNDATION_EXPORT const unsigned char FMDBVersionString[];
#import "FMDatabase.h"
#import "FMResultSet.h"
#import "FMDatabaseAdditions.h"
#import "FMDatabaseQueue.h"
#import "FMDatabasePool.h"

1494
Pods/FMDB/src/fmdb/FMDatabase.h generated Normal file

File diff suppressed because it is too large Load Diff

1529
Pods/FMDB/src/fmdb/FMDatabase.m generated Normal file

File diff suppressed because it is too large Load Diff

243
Pods/FMDB/src/fmdb/FMDatabaseAdditions.h generated Normal file
View File

@@ -0,0 +1,243 @@
//
// 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"
NS_ASSUME_NONNULL_BEGIN
/** Category of additions for @c FMDatabase class.
See also
- @c FMDatabase
*/
@interface FMDatabase (FMDatabaseAdditions)
///----------------------------------------
/// @name Return results of SQL to variable
///----------------------------------------
/** Return @c int value for query
@param query The SQL query to be performed, followed by a list of parameters that will be bound to the `?` placeholders in the SQL query.
@return @c int value.
@note This is not available from Swift.
*/
- (int)intForQuery:(NSString*)query, ...;
/** Return @c long value for query
@param query The SQL query to be performed, followed by a list of parameters that will be bound to the `?` placeholders in the SQL query.
@return @c long value.
@note This is not available from Swift.
*/
- (long)longForQuery:(NSString*)query, ...;
/** Return `BOOL` value for query
@param query The SQL query to be performed, followed by a list of parameters that will be bound to the `?` placeholders in the SQL query.
@return `BOOL` value.
@note This is not available from Swift.
*/
- (BOOL)boolForQuery:(NSString*)query, ...;
/** Return `double` value for query
@param query The SQL query to be performed, followed by a list of parameters that will be bound to the `?` placeholders in the SQL query.
@return `double` value.
@note This is not available from Swift.
*/
- (double)doubleForQuery:(NSString*)query, ...;
/** Return @c NSString value for query
@param query The SQL query to be performed, followed by a list of parameters that will be bound to the `?` placeholders in the SQL query.
@return @c NSString value.
@note This is not available from Swift.
*/
- (NSString * _Nullable)stringForQuery:(NSString*)query, ...;
/** Return @c NSData value for query
@param query The SQL query to be performed, followed by a list of parameters that will be bound to the `?` placeholders in the SQL query.
@return @c NSData value.
@note This is not available from Swift.
*/
- (NSData * _Nullable)dataForQuery:(NSString*)query, ...;
/** Return @c NSDate value for query
@param query The SQL query to be performed, followed by a list of parameters that will be bound to the `?` placeholders in the SQL query.
@return @c NSDate value.
@note This is not available from Swift.
*/
- (NSDate * _Nullable)dateForQuery:(NSString*)query, ...;
// Notice that there's no dataNoCopyForQuery:.
// That would be a bad idea, because we close out the result set, and then what
// happens to the data that we just didn't copy? Who knows, not I.
///--------------------------------
/// @name Schema related operations
///--------------------------------
/** Does table exist in database?
@param tableName The name of the table being looked for.
@return @c YES if table found; @c NO if not found.
*/
- (BOOL)tableExists:(NSString*)tableName;
/** The schema of the database.
This will be the schema for the entire database. For each entity, each row of the result set will include the following fields:
- `type` - The type of entity (e.g. table, index, view, or trigger)
- `name` - The name of the object
- `tbl_name` - The name of the table to which the object references
- `rootpage` - The page number of the root b-tree page for tables and indices
- `sql` - The SQL that created the entity
@return `FMResultSet` of schema; @c nil on error.
@see [SQLite File Format](https://sqlite.org/fileformat.html)
*/
- (FMResultSet * _Nullable)getSchema;
/** The schema of the database.
This will be the schema for a particular table as report by SQLite `PRAGMA`, for example:
PRAGMA table_info('employees')
This will report:
- `cid` - The column ID number
- `name` - The name of the column
- `type` - The data type specified for the column
- `notnull` - whether the field is defined as NOT NULL (i.e. values required)
- `dflt_value` - The default value for the column
- `pk` - Whether the field is part of the primary key of the table
@param tableName The name of the table for whom the schema will be returned.
@return `FMResultSet` of schema; @c nil on error.
@see [table_info](https://sqlite.org/pragma.html#pragma_table_info)
*/
- (FMResultSet * _Nullable)getTableSchema:(NSString*)tableName;
/** Test to see if particular column exists for particular table in database
@param columnName The name of the column.
@param tableName The name of the table.
@return @c YES if column exists in table in question; @c NO otherwise.
*/
- (BOOL)columnExists:(NSString*)columnName inTableWithName:(NSString*)tableName;
/** Test to see if particular column exists for particular table in database
@param columnName The name of the column.
@param tableName The name of the table.
@return @c YES if column exists in table in question; @c NO otherwise.
@see columnExists:inTableWithName:
@warning Deprecated - use `<columnExists:inTableWithName:>` instead.
*/
- (BOOL)columnExists:(NSString*)tableName columnName:(NSString*)columnName __deprecated_msg("Use columnExists:inTableWithName: instead");
/** Validate SQL statement
This validates SQL statement by performing `sqlite3_prepare_v2`, but not returning the results, but instead immediately calling `sqlite3_finalize`.
@param sql The SQL statement being validated.
@param error This is a pointer to a @c NSError object that will receive the autoreleased @c NSError object if there was any error. If this is @c nil , no @c NSError result will be returned.
@return @c YES if validation succeeded without incident; @c NO otherwise.
*/
- (BOOL)validateSQL:(NSString*)sql error:(NSError * _Nullable __autoreleasing *)error;
///-----------------------------------
/// @name Application identifier tasks
///-----------------------------------
/** Retrieve application ID
@return The `uint32_t` numeric value of the application ID.
@see setApplicationID:
*/
@property (nonatomic) uint32_t applicationID;
#if TARGET_OS_MAC && !TARGET_OS_IPHONE
/** Retrieve application ID string
@see setApplicationIDString:
*/
@property (nonatomic, retain) NSString *applicationIDString;
#endif
///-----------------------------------
/// @name user version identifier tasks
///-----------------------------------
/** Retrieve user version
@see setUserVersion:
*/
@property (nonatomic) uint32_t userVersion;
@end
NS_ASSUME_NONNULL_END

245
Pods/FMDB/src/fmdb/FMDatabaseAdditions.m generated Normal file
View File

@@ -0,0 +1,245 @@
//
// FMDatabaseAdditions.m
// fmdb
//
// Created by August Mueller on 10/30/05.
// Copyright 2005 Flying Meat Inc.. All rights reserved.
//
#import "FMDatabase.h"
#import "FMDatabaseAdditions.h"
#import "TargetConditionals.h"
#if FMDB_SQLITE_STANDALONE
#import <sqlite3/sqlite3.h>
#else
#import <sqlite3.h>
#endif
@interface FMDatabase (PrivateStuff)
- (FMResultSet * _Nullable)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray * _Nullable)arrayArgs orDictionary:(NSDictionary * _Nullable)dictionaryArgs orVAList:(va_list)args shouldBind:(BOOL)shouldBind;
@end
@implementation FMDatabase (FMDatabaseAdditions)
#define RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(type, sel) \
va_list args; \
va_start(args, query); \
FMResultSet *resultSet = [self executeQuery:query withArgumentsInArray:0x00 orDictionary:0x00 orVAList:args shouldBind:true]; \
va_end(args); \
if (![resultSet next]) { return (type)0; } \
type ret = [resultSet sel:0]; \
[resultSet close]; \
[resultSet setParentDB:nil]; \
return ret;
- (NSString *)stringForQuery:(NSString*)query, ... {
RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(NSString *, stringForColumnIndex);
}
- (int)intForQuery:(NSString*)query, ... {
RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(int, intForColumnIndex);
}
- (long)longForQuery:(NSString*)query, ... {
RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(long, longForColumnIndex);
}
- (BOOL)boolForQuery:(NSString*)query, ... {
RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(BOOL, boolForColumnIndex);
}
- (double)doubleForQuery:(NSString*)query, ... {
RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(double, doubleForColumnIndex);
}
- (NSData*)dataForQuery:(NSString*)query, ... {
RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(NSData *, dataForColumnIndex);
}
- (NSDate*)dateForQuery:(NSString*)query, ... {
RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(NSDate *, dateForColumnIndex);
}
- (BOOL)tableExists:(NSString*)tableName {
tableName = [tableName lowercaseString];
FMResultSet *rs = [self executeQuery:@"select [sql] from sqlite_master where [type] = 'table' and lower(name) = ?", tableName];
//if at least one next exists, table exists
BOOL returnBool = [rs next];
//close and free object
[rs close];
return returnBool;
}
/*
get table with list of tables: result colums: type[STRING], name[STRING],tbl_name[STRING],rootpage[INTEGER],sql[STRING]
check if table exist in database (patch from OZLB)
*/
- (FMResultSet * _Nullable)getSchema {
//result colums: type[STRING], name[STRING],tbl_name[STRING],rootpage[INTEGER],sql[STRING]
FMResultSet *rs = [self executeQuery:@"SELECT type, name, tbl_name, rootpage, sql FROM (SELECT * FROM sqlite_master UNION ALL SELECT * FROM sqlite_temp_master) WHERE type != 'meta' AND name NOT LIKE 'sqlite_%' ORDER BY tbl_name, type DESC, name"];
return rs;
}
/*
get table schema: result colums: cid[INTEGER], name,type [STRING], notnull[INTEGER], dflt_value[],pk[INTEGER]
*/
- (FMResultSet * _Nullable)getTableSchema:(NSString*)tableName {
//result colums: cid[INTEGER], name,type [STRING], notnull[INTEGER], dflt_value[],pk[INTEGER]
FMResultSet *rs = [self executeQuery:[NSString stringWithFormat: @"pragma table_info('%@')", tableName]];
return rs;
}
- (BOOL)columnExists:(NSString*)columnName inTableWithName:(NSString*)tableName {
BOOL returnBool = NO;
tableName = [tableName lowercaseString];
columnName = [columnName lowercaseString];
FMResultSet *rs = [self getTableSchema:tableName];
//check if column is present in table schema
while ([rs next]) {
if ([[[rs stringForColumn:@"name"] lowercaseString] isEqualToString:columnName]) {
returnBool = YES;
break;
}
}
//If this is not done FMDatabase instance stays out of pool
[rs close];
return returnBool;
}
- (uint32_t)applicationID {
#if SQLITE_VERSION_NUMBER >= 3007017
uint32_t r = 0;
FMResultSet *rs = [self executeQuery:@"pragma application_id"];
if ([rs next]) {
r = (uint32_t)[rs longLongIntForColumnIndex:0];
}
[rs close];
return r;
#else
NSString *errorMessage = NSLocalizedStringFromTable(@"Application ID functions require SQLite 3.7.17", @"FMDB", nil);
if (self.logsErrors) NSLog(@"%@", errorMessage);
return 0;
#endif
}
- (void)setApplicationID:(uint32_t)appID {
#if SQLITE_VERSION_NUMBER >= 3007017
NSString *query = [NSString stringWithFormat:@"pragma application_id=%d", appID];
FMResultSet *rs = [self executeQuery:query];
[rs next];
[rs close];
#else
NSString *errorMessage = NSLocalizedStringFromTable(@"Application ID functions require SQLite 3.7.17", @"FMDB", nil);
if (self.logsErrors) NSLog(@"%@", errorMessage);
#endif
}
#if TARGET_OS_MAC && !TARGET_OS_IPHONE
- (NSString*)applicationIDString {
#if SQLITE_VERSION_NUMBER >= 3007017
NSString *s = NSFileTypeForHFSTypeCode([self applicationID]);
assert([s length] == 6);
s = [s substringWithRange:NSMakeRange(1, 4)];
return s;
#else
NSString *errorMessage = NSLocalizedStringFromTable(@"Application ID functions require SQLite 3.7.17", @"FMDB", nil);
if (self.logsErrors) NSLog(@"%@", errorMessage);
return nil;
#endif
}
- (void)setApplicationIDString:(NSString*)s {
#if SQLITE_VERSION_NUMBER >= 3007017
if ([s length] != 4) {
NSLog(@"setApplicationIDString: string passed is not exactly 4 chars long. (was %ld)", [s length]);
}
[self setApplicationID:NSHFSTypeCodeFromFileType([NSString stringWithFormat:@"'%@'", s])];
#else
NSString *errorMessage = NSLocalizedStringFromTable(@"Application ID functions require SQLite 3.7.17", @"FMDB", nil);
if (self.logsErrors) NSLog(@"%@", errorMessage);
#endif
}
#endif
- (uint32_t)userVersion {
uint32_t r = 0;
FMResultSet *rs = [self executeQuery:@"pragma user_version"];
if ([rs next]) {
r = (uint32_t)[rs longLongIntForColumnIndex:0];
}
[rs close];
return r;
}
- (void)setUserVersion:(uint32_t)version {
NSString *query = [NSString stringWithFormat:@"pragma user_version = %d", version];
FMResultSet *rs = [self executeQuery:query];
[rs next];
[rs close];
}
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-implementations"
- (BOOL)columnExists:(NSString*)tableName columnName:(NSString*)columnName __attribute__ ((deprecated)) {
return [self columnExists:columnName inTableWithName:tableName];
}
#pragma clang diagnostic pop
- (BOOL)validateSQL:(NSString*)sql error:(NSError * _Nullable __autoreleasing *)error {
sqlite3_stmt *pStmt = NULL;
BOOL validationSucceeded = YES;
int rc = sqlite3_prepare_v2([self sqliteHandle], [sql UTF8String], -1, &pStmt, 0);
if (rc != SQLITE_OK) {
validationSucceeded = NO;
if (error) {
*error = [NSError errorWithDomain:NSCocoaErrorDomain
code:[self lastErrorCode]
userInfo:[NSDictionary dictionaryWithObject:[self lastErrorMessage]
forKey:NSLocalizedDescriptionKey]];
}
}
sqlite3_finalize(pStmt);
return validationSucceeded;
}
@end

280
Pods/FMDB/src/fmdb/FMDatabasePool.h generated Executable file
View File

@@ -0,0 +1,280 @@
//
// FMDatabasePool.h
// fmdb
//
// Created by August Mueller on 6/22/11.
// Copyright 2011 Flying Meat Inc. All rights reserved.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@class FMDatabase;
/** Pool of @c FMDatabase objects.
See also
- @c FMDatabaseQueue
- @c FMDatabase
@warning Before using @c FMDatabasePool , please consider using @c FMDatabaseQueue instead.
If you really really really know what you're doing and @c FMDatabasePool is what
you really really need (ie, you're using a read only database), OK you can use
it. But just be careful not to deadlock!
For an example on deadlocking, search for:
`ONLY_USE_THE_POOL_IF_YOU_ARE_DOING_READS_OTHERWISE_YOULL_DEADLOCK_USE_FMDATABASEQUEUE_INSTEAD`
in the main.m file.
*/
@interface FMDatabasePool : NSObject
/** Database path */
@property (atomic, copy, nullable) NSString *path;
/** Delegate object */
@property (atomic, unsafe_unretained, nullable) id delegate;
/** Maximum number of databases to create */
@property (atomic, assign) NSUInteger maximumNumberOfDatabasesToCreate;
/** Open flags */
@property (atomic, readonly) int openFlags;
/** Custom virtual file system name */
@property (atomic, copy, nullable) NSString *vfsName;
///---------------------
/// @name Initialization
///---------------------
/** Create pool using path.
@param aPath The file path of the database.
@return The @c FMDatabasePool object. @c nil on error.
*/
+ (instancetype)databasePoolWithPath:(NSString * _Nullable)aPath;
/** Create pool using file URL.
@param url The file @c NSURL of the database.
@return The @c FMDatabasePool object. @c nil on error.
*/
+ (instancetype)databasePoolWithURL:(NSURL * _Nullable)url;
/** Create pool using path and specified flags
@param aPath The file path of the database.
@param openFlags Flags passed to the openWithFlags method of the database.
@return The @c FMDatabasePool object. @c nil on error.
*/
+ (instancetype)databasePoolWithPath:(NSString * _Nullable)aPath flags:(int)openFlags;
/** Create pool using file URL and specified flags
@param url The file @c NSURL of the database.
@param openFlags Flags passed to the openWithFlags method of the database.
@return The @c FMDatabasePool object. @c nil on error.
*/
+ (instancetype)databasePoolWithURL:(NSURL * _Nullable)url flags:(int)openFlags;
/** Create pool using path.
@param aPath The file path of the database.
@return The @c FMDatabasePool object. @c nil on error.
*/
- (instancetype)initWithPath:(NSString * _Nullable)aPath;
/** Create pool using file URL.
@param url The file `NSURL of the database.
@return The @c FMDatabasePool object. @c nil on error.
*/
- (instancetype)initWithURL:(NSURL * _Nullable)url;
/** Create pool using path and specified flags.
@param aPath The file path of the database.
@param openFlags Flags passed to the openWithFlags method of the database
@return The @c FMDatabasePool object. @c nil on error.
*/
- (instancetype)initWithPath:(NSString * _Nullable)aPath flags:(int)openFlags;
/** Create pool using file URL and specified flags.
@param url The file @c NSURL of the database.
@param openFlags Flags passed to the openWithFlags method of the database
@return The @c FMDatabasePool object. @c nil on error.
*/
- (instancetype)initWithURL:(NSURL * _Nullable)url flags:(int)openFlags;
/** Create pool using path and specified flags.
@param aPath The file path of the database.
@param openFlags Flags passed to the openWithFlags method of the database
@param vfsName The name of a custom virtual file system
@return The @c FMDatabasePool object. @c nil on error.
*/
- (instancetype)initWithPath:(NSString * _Nullable)aPath flags:(int)openFlags vfs:(NSString * _Nullable)vfsName;
/** Create pool using file URL and specified flags.
@param url The file @c NSURL of the database.
@param openFlags Flags passed to the openWithFlags method of the database
@param vfsName The name of a custom virtual file system
@return The @c FMDatabasePool object. @c nil on error.
*/
- (instancetype)initWithURL:(NSURL * _Nullable)url flags:(int)openFlags vfs:(NSString * _Nullable)vfsName;
/** Returns the Class of 'FMDatabase' subclass, that will be used to instantiate database object.
Subclasses can override this method to return specified Class of 'FMDatabase' subclass.
@return The Class of 'FMDatabase' subclass, that will be used to instantiate database object.
*/
+ (Class)databaseClass;
///------------------------------------------------
/// @name Keeping track of checked in/out databases
///------------------------------------------------
/** Number of checked-in databases in pool
*/
@property (nonatomic, readonly) NSUInteger countOfCheckedInDatabases;
/** Number of checked-out databases in pool
*/
@property (nonatomic, readonly) NSUInteger countOfCheckedOutDatabases;
/** Total number of databases in pool
*/
@property (nonatomic, readonly) NSUInteger countOfOpenDatabases;
/** Release all databases in pool */
- (void)releaseAllDatabases;
///------------------------------------------
/// @name Perform database operations in pool
///------------------------------------------
/** Synchronously perform database operations in pool.
@param block The code to be run on the @c FMDatabasePool pool.
*/
- (void)inDatabase:(__attribute__((noescape)) void (^)(FMDatabase *db))block;
/** Synchronously perform database operations in pool using transaction.
@param block The code to be run on the @c FMDatabasePool pool.
@warning Unlike SQLite's `BEGIN TRANSACTION`, this method currently performs
an exclusive transaction, not a deferred transaction. This behavior
is likely to change in future versions of FMDB, whereby this method
will likely eventually adopt standard SQLite behavior and perform
deferred transactions. If you really need exclusive tranaction, it is
recommended that you use `inExclusiveTransaction`, instead, not only
to make your intent explicit, but also to future-proof your code.
*/
- (void)inTransaction:(__attribute__((noescape)) void (^)(FMDatabase *db, BOOL *rollback))block;
/** Synchronously perform database operations in pool using exclusive transaction.
@param block The code to be run on the @c FMDatabasePool pool.
*/
- (void)inExclusiveTransaction:(__attribute__((noescape)) void (^)(FMDatabase *db, BOOL *rollback))block;
/** Synchronously perform database operations in pool using deferred transaction.
@param block The code to be run on the @c FMDatabasePool pool.
*/
- (void)inDeferredTransaction:(__attribute__((noescape)) void (^)(FMDatabase *db, BOOL *rollback))block;
/** Synchronously perform database operations on queue, using immediate transactions.
@param block The code to be run on the queue of @c FMDatabaseQueue
*/
- (void)inImmediateTransaction:(__attribute__((noescape)) void (^)(FMDatabase *db, BOOL *rollback))block;
/** Synchronously perform database operations in pool using save point.
@param block The code to be run on the @c FMDatabasePool pool.
@return @c NSError object if error; @c nil if successful.
@warning You can not nest these, since calling it will pull another database out of the pool and you'll get a deadlock. If you need to nest, use @c startSavePointWithName:error: instead.
*/
- (NSError * _Nullable)inSavePoint:(__attribute__((noescape)) void (^)(FMDatabase *db, BOOL *rollback))block;
@end
/** FMDatabasePool delegate category
This is a category that defines the protocol for the FMDatabasePool delegate
*/
@interface NSObject (FMDatabasePoolDelegate)
/** Asks the delegate whether database should be added to the pool.
@param pool The @c FMDatabasePool object.
@param database The @c FMDatabase object.
@return @c YES if it should add database to pool; @c NO if not.
*/
- (BOOL)databasePool:(FMDatabasePool*)pool shouldAddDatabaseToPool:(FMDatabase*)database;
/** Tells the delegate that database was added to the pool.
@param pool The @c FMDatabasePool object.
@param database The @c FMDatabase object.
*/
- (void)databasePool:(FMDatabasePool*)pool didAddDatabase:(FMDatabase*)database;
@end
NS_ASSUME_NONNULL_END

335
Pods/FMDB/src/fmdb/FMDatabasePool.m generated Executable file
View File

@@ -0,0 +1,335 @@
//
// FMDatabasePool.m
// fmdb
//
// Created by August Mueller on 6/22/11.
// Copyright 2011 Flying Meat Inc. All rights reserved.
//
#if FMDB_SQLITE_STANDALONE
#import <sqlite3/sqlite3.h>
#else
#import <sqlite3.h>
#endif
#import "FMDatabasePool.h"
#import "FMDatabase.h"
typedef NS_ENUM(NSInteger, FMDBTransaction) {
FMDBTransactionExclusive,
FMDBTransactionDeferred,
FMDBTransactionImmediate,
};
@interface FMDatabasePool () {
dispatch_queue_t _lockQueue;
NSMutableArray *_databaseInPool;
NSMutableArray *_databaseOutPool;
}
- (void)pushDatabaseBackInPool:(FMDatabase*)db;
- (FMDatabase*)db;
@end
@implementation FMDatabasePool
@synthesize path=_path;
@synthesize delegate=_delegate;
@synthesize maximumNumberOfDatabasesToCreate=_maximumNumberOfDatabasesToCreate;
@synthesize openFlags=_openFlags;
+ (instancetype)databasePoolWithPath:(NSString *)aPath {
return FMDBReturnAutoreleased([[self alloc] initWithPath:aPath]);
}
+ (instancetype)databasePoolWithURL:(NSURL *)url {
return FMDBReturnAutoreleased([[self alloc] initWithPath:url.path]);
}
+ (instancetype)databasePoolWithPath:(NSString *)aPath flags:(int)openFlags {
return FMDBReturnAutoreleased([[self alloc] initWithPath:aPath flags:openFlags]);
}
+ (instancetype)databasePoolWithURL:(NSURL *)url flags:(int)openFlags {
return FMDBReturnAutoreleased([[self alloc] initWithPath:url.path flags:openFlags]);
}
- (instancetype)initWithURL:(NSURL *)url flags:(int)openFlags vfs:(NSString *)vfsName {
return [self initWithPath:url.path flags:openFlags vfs:vfsName];
}
- (instancetype)initWithPath:(NSString*)aPath flags:(int)openFlags vfs:(NSString *)vfsName {
self = [super init];
if (self != nil) {
_path = [aPath copy];
_lockQueue = dispatch_queue_create([[NSString stringWithFormat:@"fmdb.%@", self] UTF8String], NULL);
_databaseInPool = FMDBReturnRetained([NSMutableArray array]);
_databaseOutPool = FMDBReturnRetained([NSMutableArray array]);
_openFlags = openFlags;
_vfsName = [vfsName copy];
}
return self;
}
- (instancetype)initWithPath:(NSString *)aPath flags:(int)openFlags {
return [self initWithPath:aPath flags:openFlags vfs:nil];
}
- (instancetype)initWithURL:(NSURL *)url flags:(int)openFlags {
return [self initWithPath:url.path flags:openFlags vfs:nil];
}
- (instancetype)initWithPath:(NSString*)aPath {
// default flags for sqlite3_open
return [self initWithPath:aPath flags:SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE];
}
- (instancetype)initWithURL:(NSURL *)url {
return [self initWithPath:url.path];
}
- (instancetype)init {
return [self initWithPath:nil];
}
+ (Class)databaseClass {
return [FMDatabase class];
}
- (void)dealloc {
_delegate = 0x00;
FMDBRelease(_path);
FMDBRelease(_databaseInPool);
FMDBRelease(_databaseOutPool);
FMDBRelease(_vfsName);
if (_lockQueue) {
FMDBDispatchQueueRelease(_lockQueue);
_lockQueue = 0x00;
}
#if ! __has_feature(objc_arc)
[super dealloc];
#endif
}
- (void)executeLocked:(void (^)(void))aBlock {
dispatch_sync(_lockQueue, aBlock);
}
- (void)pushDatabaseBackInPool:(FMDatabase*)db {
if (!db) { // db can be null if we set an upper bound on the # of databases to create.
return;
}
[self executeLocked:^() {
if ([self->_databaseInPool containsObject:db]) {
[[NSException exceptionWithName:@"Database already in pool" reason:@"The FMDatabase being put back into the pool is already present in the pool" userInfo:nil] raise];
}
[self->_databaseInPool addObject:db];
[self->_databaseOutPool removeObject:db];
}];
}
- (FMDatabase*)db {
__block FMDatabase *db;
[self executeLocked:^() {
db = [self->_databaseInPool lastObject];
BOOL shouldNotifyDelegate = NO;
if (db) {
[self->_databaseOutPool addObject:db];
[self->_databaseInPool removeLastObject];
}
else {
if (self->_maximumNumberOfDatabasesToCreate) {
NSUInteger currentCount = [self->_databaseOutPool count] + [self->_databaseInPool count];
if (currentCount >= self->_maximumNumberOfDatabasesToCreate) {
NSLog(@"Maximum number of databases (%ld) has already been reached!", (long)currentCount);
return;
}
}
db = [[[self class] databaseClass] databaseWithPath:self->_path];
shouldNotifyDelegate = YES;
}
//This ensures that the db is opened before returning
#if SQLITE_VERSION_NUMBER >= 3005000
BOOL success = [db openWithFlags:self->_openFlags vfs:self->_vfsName];
#else
BOOL success = [db open];
#endif
if (success) {
if ([self->_delegate respondsToSelector:@selector(databasePool:shouldAddDatabaseToPool:)] && ![self->_delegate databasePool:self shouldAddDatabaseToPool:db]) {
[db close];
db = 0x00;
}
else {
//It should not get added in the pool twice if lastObject was found
if (![self->_databaseOutPool containsObject:db]) {
[self->_databaseOutPool addObject:db];
if (shouldNotifyDelegate && [self->_delegate respondsToSelector:@selector(databasePool:didAddDatabase:)]) {
[self->_delegate databasePool:self didAddDatabase:db];
}
}
}
}
else {
NSLog(@"Could not open up the database at path %@", self->_path);
db = 0x00;
}
}];
return db;
}
- (NSUInteger)countOfCheckedInDatabases {
__block NSUInteger count;
[self executeLocked:^() {
count = [self->_databaseInPool count];
}];
return count;
}
- (NSUInteger)countOfCheckedOutDatabases {
__block NSUInteger count;
[self executeLocked:^() {
count = [self->_databaseOutPool count];
}];
return count;
}
- (NSUInteger)countOfOpenDatabases {
__block NSUInteger count;
[self executeLocked:^() {
count = [self->_databaseOutPool count] + [self->_databaseInPool count];
}];
return count;
}
- (void)releaseAllDatabases {
[self executeLocked:^() {
[self->_databaseOutPool removeAllObjects];
[self->_databaseInPool removeAllObjects];
}];
}
- (void)inDatabase:(__attribute__((noescape)) void (^)(FMDatabase *db))block {
FMDatabase *db = [self db];
block(db);
[self pushDatabaseBackInPool:db];
}
- (void)beginTransaction:(FMDBTransaction)transaction withBlock:(void (^)(FMDatabase *db, BOOL *rollback))block {
BOOL shouldRollback = NO;
FMDatabase *db = [self db];
switch (transaction) {
case FMDBTransactionExclusive:
[db beginTransaction];
break;
case FMDBTransactionDeferred:
[db beginDeferredTransaction];
break;
case FMDBTransactionImmediate:
[db beginImmediateTransaction];
break;
}
block(db, &shouldRollback);
if (shouldRollback) {
[db rollback];
}
else {
[db commit];
}
[self pushDatabaseBackInPool:db];
}
- (void)inTransaction:(__attribute__((noescape)) void (^)(FMDatabase *db, BOOL *rollback))block {
[self beginTransaction:FMDBTransactionExclusive withBlock:block];
}
- (void)inDeferredTransaction:(__attribute__((noescape)) void (^)(FMDatabase *db, BOOL *rollback))block {
[self beginTransaction:FMDBTransactionDeferred withBlock:block];
}
- (void)inExclusiveTransaction:(__attribute__((noescape)) void (^)(FMDatabase *db, BOOL *rollback))block {
[self beginTransaction:FMDBTransactionExclusive withBlock:block];
}
- (void)inImmediateTransaction:(__attribute__((noescape)) void (^)(FMDatabase *db, BOOL *rollback))block {
[self beginTransaction:FMDBTransactionImmediate withBlock:block];
}
- (NSError*)inSavePoint:(__attribute__((noescape)) void (^)(FMDatabase *db, BOOL *rollback))block {
#if SQLITE_VERSION_NUMBER >= 3007000
static unsigned long savePointIdx = 0;
NSString *name = [NSString stringWithFormat:@"savePoint%ld", savePointIdx++];
BOOL shouldRollback = NO;
FMDatabase *db = [self db];
NSError *err = 0x00;
if (![db startSavePointWithName:name error:&err]) {
[self pushDatabaseBackInPool:db];
return err;
}
block(db, &shouldRollback);
if (shouldRollback) {
// We need to rollback and release this savepoint to remove it
[db rollbackToSavePointWithName:name error:&err];
}
[db releaseSavePointWithName:name error:&err];
[self pushDatabaseBackInPool:db];
return err;
#else
NSString *errorMessage = NSLocalizedStringFromTable(@"Save point functions require SQLite 3.7", @"FMDB", nil);
if (self.logsErrors) NSLog(@"%@", errorMessage);
return [NSError errorWithDomain:@"FMDatabase" code:0 userInfo:@{NSLocalizedDescriptionKey : errorMessage}];
#endif
}
@end

295
Pods/FMDB/src/fmdb/FMDatabaseQueue.h generated Executable file
View File

@@ -0,0 +1,295 @@
//
// FMDatabaseQueue.h
// fmdb
//
// Created by August Mueller on 6/22/11.
// Copyright 2011 Flying Meat Inc. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "FMDatabase.h"
NS_ASSUME_NONNULL_BEGIN
/** To perform queries and updates on multiple threads, you'll want to use @c FMDatabaseQueue .
Using a single instance of @c FMDatabase from multiple threads at once is a bad idea. It has always been OK to make a @c FMDatabase object *per thread*. Just don't share a single instance across threads, and definitely not across multiple threads at the same time.
Instead, use @c FMDatabaseQueue . Here's how to use it:
First, make your queue.
@code
FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:aPath];
@endcode
Then use it like so:
@code
[queue inDatabase:^(FMDatabase *db) {
[db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:1]];
[db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:2]];
[db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:3]];
FMResultSet *rs = [db executeQuery:@"select * from foo"];
while ([rs next]) {
//…
}
}];
@endcode
An easy way to wrap things up in a transaction can be done like this:
@code
[queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
[db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:1]];
[db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:2]];
[db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:3]];
// if (whoopsSomethingWrongHappened) {
// *rollback = YES;
// return;
// }
// etc…
[db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:4]];
}];
@endcode
@c FMDatabaseQueue will run the blocks on a serialized queue (hence the name of the class). So if you call @c FMDatabaseQueue 's methods from multiple threads at the same time, they will be executed in the order they are received. This way queries and updates won't step on each other's toes, and every one is happy.
@warning Do not instantiate a single @c FMDatabase object and use it across multiple threads. Use @c FMDatabaseQueue instead.
@warning The calls to @c FMDatabaseQueue 's methods are blocking. So even though you are passing along blocks, they will **not** be run on another thread.
@sa FMDatabase
*/
@interface FMDatabaseQueue : NSObject
/** Path of database */
@property (atomic, retain, nullable) NSString *path;
/** Open flags */
@property (atomic, readonly) int openFlags;
/** Custom virtual file system name */
@property (atomic, copy, nullable) NSString *vfsName;
///----------------------------------------------------
/// @name Initialization, opening, and closing of queue
///----------------------------------------------------
/** Create queue using path.
@param aPath The file path of the database.
@return The @c FMDatabaseQueue object. @c nil on error.
*/
+ (nullable instancetype)databaseQueueWithPath:(NSString * _Nullable)aPath;
/** Create queue using file URL.
@param url The file @c NSURL of the database.
@return The @c FMDatabaseQueue object. @c nil on error.
*/
+ (nullable instancetype)databaseQueueWithURL:(NSURL * _Nullable)url;
/** Create queue using path and specified flags.
@param aPath The file path of the database.
@param openFlags Flags passed to the openWithFlags method of the database.
@return The @c FMDatabaseQueue object. @c nil on error.
*/
+ (nullable instancetype)databaseQueueWithPath:(NSString * _Nullable)aPath flags:(int)openFlags;
/** Create queue using file URL and specified flags.
@param url The file @c NSURL of the database.
@param openFlags Flags passed to the openWithFlags method of the database.
@return The @c FMDatabaseQueue object. @c nil on error.
*/
+ (nullable instancetype)databaseQueueWithURL:(NSURL * _Nullable)url flags:(int)openFlags;
/** Create queue using path.
@param aPath The file path of the database.
@return The @c FMDatabaseQueue object. @c nil on error.
*/
- (nullable instancetype)initWithPath:(NSString * _Nullable)aPath;
/** Create queue using file URL.
@param url The file `NSURL of the database.
@return The @c FMDatabaseQueue object. @c nil on error.
*/
- (nullable instancetype)initWithURL:(NSURL * _Nullable)url;
/** Create queue using path and specified flags.
@param aPath The file path of the database.
@param openFlags Flags passed to the openWithFlags method of the database.
@return The @c FMDatabaseQueue object. @c nil on error.
*/
- (nullable instancetype)initWithPath:(NSString * _Nullable)aPath flags:(int)openFlags;
/** Create queue using file URL and specified flags.
@param url The file path of the database.
@param openFlags Flags passed to the openWithFlags method of the database.
@return The @c FMDatabaseQueue object. @c nil on error.
*/
- (nullable instancetype)initWithURL:(NSURL * _Nullable)url flags:(int)openFlags;
/** Create queue using path and specified flags.
@param aPath The file path of the database.
@param openFlags Flags passed to the openWithFlags method of the database
@param vfsName The name of a custom virtual file system
@return The @c FMDatabaseQueue object. @c nil on error.
*/
- (nullable instancetype)initWithPath:(NSString * _Nullable)aPath flags:(int)openFlags vfs:(NSString * _Nullable)vfsName;
/** Create queue using file URL and specified flags.
@param url The file `NSURL of the database.
@param openFlags Flags passed to the openWithFlags method of the database
@param vfsName The name of a custom virtual file system
@return The @c FMDatabaseQueue object. @c nil on error.
*/
- (nullable instancetype)initWithURL:(NSURL * _Nullable)url flags:(int)openFlags vfs:(NSString * _Nullable)vfsName;
/** Returns the Class of 'FMDatabase' subclass, that will be used to instantiate database object.
Subclasses can override this method to return specified Class of 'FMDatabase' subclass.
@return The Class of 'FMDatabase' subclass, that will be used to instantiate database object.
*/
+ (Class)databaseClass;
/** Close database used by queue. */
- (void)close;
/** Interupt pending database operation. */
- (void)interrupt;
///-----------------------------------------------
/// @name Dispatching database operations to queue
///-----------------------------------------------
/** Synchronously perform database operations on queue.
@param block The code to be run on the queue of @c FMDatabaseQueue
*/
- (void)inDatabase:(__attribute__((noescape)) void (^)(FMDatabase *db))block;
/** Synchronously perform database operations on queue, using transactions.
@param block The code to be run on the queue of @c FMDatabaseQueue
@warning Unlike SQLite's `BEGIN TRANSACTION`, this method currently performs
an exclusive transaction, not a deferred transaction. This behavior
is likely to change in future versions of FMDB, whereby this method
will likely eventually adopt standard SQLite behavior and perform
deferred transactions. If you really need exclusive tranaction, it is
recommended that you use `inExclusiveTransaction`, instead, not only
to make your intent explicit, but also to future-proof your code.
*/
- (void)inTransaction:(__attribute__((noescape)) void (^)(FMDatabase *db, BOOL *rollback))block;
/** Synchronously perform database operations on queue, using deferred transactions.
@param block The code to be run on the queue of @c FMDatabaseQueue
*/
- (void)inDeferredTransaction:(__attribute__((noescape)) void (^)(FMDatabase *db, BOOL *rollback))block;
/** Synchronously perform database operations on queue, using exclusive transactions.
@param block The code to be run on the queue of @c FMDatabaseQueue
*/
- (void)inExclusiveTransaction:(__attribute__((noescape)) void (^)(FMDatabase *db, BOOL *rollback))block;
/** Synchronously perform database operations on queue, using immediate transactions.
@param block The code to be run on the queue of @c FMDatabaseQueue
*/
- (void)inImmediateTransaction:(__attribute__((noescape)) void (^)(FMDatabase *db, BOOL *rollback))block;
///-----------------------------------------------
/// @name Dispatching database operations to queue
///-----------------------------------------------
/** Synchronously perform database operations using save point.
@param block The code to be run on the queue of @c FMDatabaseQueue
*/
// NOTE: you can not nest these, since calling it will pull another database out of the pool and you'll get a deadlock.
// If you need to nest, use FMDatabase's startSavePointWithName:error: instead.
- (NSError * _Nullable)inSavePoint:(__attribute__((noescape)) void (^)(FMDatabase *db, BOOL *rollback))block;
///-----------------
/// @name Checkpoint
///-----------------
/** Performs a WAL checkpoint
@param checkpointMode The checkpoint mode for sqlite3_wal_checkpoint_v2
@param error The NSError corresponding to the error, if any.
@return YES on success, otherwise NO.
*/
- (BOOL)checkpoint:(FMDBCheckpointMode)checkpointMode error:(NSError * _Nullable *)error;
/** Performs a WAL checkpoint
@param checkpointMode The checkpoint mode for sqlite3_wal_checkpoint_v2
@param name The db name for sqlite3_wal_checkpoint_v2
@param error The NSError corresponding to the error, if any.
@return YES on success, otherwise NO.
*/
- (BOOL)checkpoint:(FMDBCheckpointMode)checkpointMode name:(NSString * _Nullable)name error:(NSError * _Nullable *)error;
/** Performs a WAL checkpoint
@param checkpointMode The checkpoint mode for sqlite3_wal_checkpoint_v2
@param name The db name for sqlite3_wal_checkpoint_v2
@param error The NSError corresponding to the error, if any.
@param logFrameCount If not NULL, then this is set to the total number of frames in the log file or to -1 if the checkpoint could not run because of an error or because the database is not in WAL mode.
@param checkpointCount If not NULL, then this is set to the total number of checkpointed frames in the log file (including any that were already checkpointed before the function was called) or to -1 if the checkpoint could not run due to an error or because the database is not in WAL mode.
@return YES on success, otherwise NO.
*/
- (BOOL)checkpoint:(FMDBCheckpointMode)checkpointMode name:(NSString * _Nullable)name logFrameCount:(int * _Nullable)logFrameCount checkpointCount:(int * _Nullable)checkpointCount error:(NSError * _Nullable *)error;
@end
NS_ASSUME_NONNULL_END

314
Pods/FMDB/src/fmdb/FMDatabaseQueue.m generated Executable file
View File

@@ -0,0 +1,314 @@
//
// FMDatabaseQueue.m
// fmdb
//
// Created by August Mueller on 6/22/11.
// Copyright 2011 Flying Meat Inc. All rights reserved.
//
#import "FMDatabaseQueue.h"
#import "FMDatabase.h"
#if FMDB_SQLITE_STANDALONE
#import <sqlite3/sqlite3.h>
#else
#import <sqlite3.h>
#endif
typedef NS_ENUM(NSInteger, FMDBTransaction) {
FMDBTransactionExclusive,
FMDBTransactionDeferred,
FMDBTransactionImmediate,
};
/*
Note: we call [self retain]; before using dispatch_sync, just incase
FMDatabaseQueue is released on another thread and we're in the middle of doing
something in dispatch_sync
*/
/*
* A key used to associate the FMDatabaseQueue object with the dispatch_queue_t it uses.
* This in turn is used for deadlock detection by seeing if inDatabase: is called on
* the queue's dispatch queue, which should not happen and causes a deadlock.
*/
static const void * const kDispatchQueueSpecificKey = &kDispatchQueueSpecificKey;
@interface FMDatabaseQueue () {
dispatch_queue_t _queue;
FMDatabase *_db;
}
@end
@implementation FMDatabaseQueue
+ (instancetype)databaseQueueWithPath:(NSString *)aPath {
FMDatabaseQueue *q = [[self alloc] initWithPath:aPath];
FMDBAutorelease(q);
return q;
}
+ (instancetype)databaseQueueWithURL:(NSURL *)url {
return [self databaseQueueWithPath:url.path];
}
+ (instancetype)databaseQueueWithPath:(NSString *)aPath flags:(int)openFlags {
FMDatabaseQueue *q = [[self alloc] initWithPath:aPath flags:openFlags];
FMDBAutorelease(q);
return q;
}
+ (instancetype)databaseQueueWithURL:(NSURL *)url flags:(int)openFlags {
return [self databaseQueueWithPath:url.path flags:openFlags];
}
+ (Class)databaseClass {
return [FMDatabase class];
}
- (instancetype)initWithURL:(NSURL *)url flags:(int)openFlags vfs:(NSString *)vfsName {
return [self initWithPath:url.path flags:openFlags vfs:vfsName];
}
- (instancetype)initWithPath:(NSString*)aPath flags:(int)openFlags vfs:(NSString *)vfsName {
self = [super init];
if (self != nil) {
_db = [[[self class] databaseClass] databaseWithPath:aPath];
FMDBRetain(_db);
#if SQLITE_VERSION_NUMBER >= 3005000
BOOL success = [_db openWithFlags:openFlags vfs:vfsName];
#else
BOOL success = [_db open];
#endif
if (!success) {
NSLog(@"Could not create database queue for path %@", aPath);
FMDBRelease(self);
return 0x00;
}
_path = FMDBReturnRetained(aPath);
_queue = dispatch_queue_create([[NSString stringWithFormat:@"fmdb.%@", self] UTF8String], NULL);
dispatch_queue_set_specific(_queue, kDispatchQueueSpecificKey, (__bridge void *)self, NULL);
_openFlags = openFlags;
_vfsName = [vfsName copy];
}
return self;
}
- (instancetype)initWithPath:(NSString *)aPath flags:(int)openFlags {
return [self initWithPath:aPath flags:openFlags vfs:nil];
}
- (instancetype)initWithURL:(NSURL *)url flags:(int)openFlags {
return [self initWithPath:url.path flags:openFlags vfs:nil];
}
- (instancetype)initWithURL:(NSURL *)url {
return [self initWithPath:url.path];
}
- (instancetype)initWithPath:(NSString *)aPath {
// default flags for sqlite3_open
return [self initWithPath:aPath flags:SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE vfs:nil];
}
- (instancetype)init {
return [self initWithPath:nil];
}
- (void)dealloc {
FMDBRelease(_db);
FMDBRelease(_path);
FMDBRelease(_vfsName);
if (_queue) {
FMDBDispatchQueueRelease(_queue);
_queue = 0x00;
}
#if ! __has_feature(objc_arc)
[super dealloc];
#endif
}
- (void)close {
FMDBRetain(self);
dispatch_sync(_queue, ^() {
[self->_db close];
FMDBRelease(_db);
self->_db = 0x00;
});
FMDBRelease(self);
}
- (void)interrupt {
[[self database] interrupt];
}
- (FMDatabase*)database {
if (![_db isOpen]) {
if (!_db) {
_db = FMDBReturnRetained([[[self class] databaseClass] databaseWithPath:_path]);
}
#if SQLITE_VERSION_NUMBER >= 3005000
BOOL success = [_db openWithFlags:_openFlags vfs:_vfsName];
#else
BOOL success = [_db open];
#endif
if (!success) {
NSLog(@"FMDatabaseQueue could not reopen database for path %@", _path);
FMDBRelease(_db);
_db = 0x00;
return 0x00;
}
}
return _db;
}
- (void)inDatabase:(__attribute__((noescape)) void (^)(FMDatabase *db))block {
#ifndef NDEBUG
/* Get the currently executing queue (which should probably be nil, but in theory could be another DB queue
* and then check it against self to make sure we're not about to deadlock. */
FMDatabaseQueue *currentSyncQueue = (__bridge id)dispatch_get_specific(kDispatchQueueSpecificKey);
assert(currentSyncQueue != self && "inDatabase: was called reentrantly on the same queue, which would lead to a deadlock");
#endif
FMDBRetain(self);
dispatch_sync(_queue, ^() {
FMDatabase *db = [self database];
block(db);
if ([db hasOpenResultSets]) {
NSLog(@"Warning: there is at least one open result set around after performing [FMDatabaseQueue inDatabase:]");
#if defined(DEBUG) && DEBUG
NSSet *openSetCopy = FMDBReturnAutoreleased([[db valueForKey:@"_openResultSets"] copy]);
for (NSValue *rsInWrappedInATastyValueMeal in openSetCopy) {
FMResultSet *rs = (FMResultSet *)[rsInWrappedInATastyValueMeal pointerValue];
NSLog(@"query: '%@'", [rs query]);
}
#endif
}
});
FMDBRelease(self);
}
- (void)beginTransaction:(FMDBTransaction)transaction withBlock:(void (^)(FMDatabase *db, BOOL *rollback))block {
FMDBRetain(self);
dispatch_sync(_queue, ^() {
BOOL shouldRollback = NO;
switch (transaction) {
case FMDBTransactionExclusive:
[[self database] beginTransaction];
break;
case FMDBTransactionDeferred:
[[self database] beginDeferredTransaction];
break;
case FMDBTransactionImmediate:
[[self database] beginImmediateTransaction];
break;
}
block([self database], &shouldRollback);
if (shouldRollback) {
[[self database] rollback];
}
else {
[[self database] commit];
}
});
FMDBRelease(self);
}
- (void)inTransaction:(__attribute__((noescape)) void (^)(FMDatabase *db, BOOL *rollback))block {
[self beginTransaction:FMDBTransactionExclusive withBlock:block];
}
- (void)inDeferredTransaction:(__attribute__((noescape)) void (^)(FMDatabase *db, BOOL *rollback))block {
[self beginTransaction:FMDBTransactionDeferred withBlock:block];
}
- (void)inExclusiveTransaction:(__attribute__((noescape)) void (^)(FMDatabase *db, BOOL *rollback))block {
[self beginTransaction:FMDBTransactionExclusive withBlock:block];
}
- (void)inImmediateTransaction:(__attribute__((noescape)) void (^)(FMDatabase * _Nonnull, BOOL * _Nonnull))block {
[self beginTransaction:FMDBTransactionImmediate withBlock:block];
}
- (NSError*)inSavePoint:(__attribute__((noescape)) void (^)(FMDatabase *db, BOOL *rollback))block {
#if SQLITE_VERSION_NUMBER >= 3007000
static unsigned long savePointIdx = 0;
__block NSError *err = 0x00;
FMDBRetain(self);
dispatch_sync(_queue, ^() {
NSString *name = [NSString stringWithFormat:@"savePoint%ld", savePointIdx++];
BOOL shouldRollback = NO;
if ([[self database] startSavePointWithName:name error:&err]) {
block([self database], &shouldRollback);
if (shouldRollback) {
// We need to rollback and release this savepoint to remove it
[[self database] rollbackToSavePointWithName:name error:&err];
}
[[self database] releaseSavePointWithName:name error:&err];
}
});
FMDBRelease(self);
return err;
#else
NSString *errorMessage = NSLocalizedStringFromTable(@"Save point functions require SQLite 3.7", @"FMDB", nil);
if (_db.logsErrors) NSLog(@"%@", errorMessage);
return [NSError errorWithDomain:@"FMDatabase" code:0 userInfo:@{NSLocalizedDescriptionKey : errorMessage}];
#endif
}
- (BOOL)checkpoint:(FMDBCheckpointMode)mode error:(NSError * __autoreleasing *)error
{
return [self checkpoint:mode name:nil logFrameCount:NULL checkpointCount:NULL error:error];
}
- (BOOL)checkpoint:(FMDBCheckpointMode)mode name:(NSString *)name error:(NSError * __autoreleasing *)error
{
return [self checkpoint:mode name:name logFrameCount:NULL checkpointCount:NULL error:error];
}
- (BOOL)checkpoint:(FMDBCheckpointMode)mode name:(NSString *)name logFrameCount:(int * _Nullable)logFrameCount checkpointCount:(int * _Nullable)checkpointCount error:(NSError * __autoreleasing _Nullable * _Nullable)error
{
__block BOOL result;
FMDBRetain(self);
dispatch_sync(_queue, ^() {
result = [self.database checkpoint:mode name:name logFrameCount:logFrameCount checkpointCount:checkpointCount error:error];
});
FMDBRelease(self);
return result;
}
@end

538
Pods/FMDB/src/fmdb/FMResultSet.h generated Normal file
View File

@@ -0,0 +1,538 @@
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
#ifndef __has_feature // Optional.
#define __has_feature(x) 0 // Compatibility with non-clang compilers.
#endif
#ifndef NS_RETURNS_NOT_RETAINED
#if __has_feature(attribute_ns_returns_not_retained)
#define NS_RETURNS_NOT_RETAINED __attribute__((ns_returns_not_retained))
#else
#define NS_RETURNS_NOT_RETAINED
#endif
#endif
@class FMDatabase;
@class FMStatement;
/** Types for columns in a result set.
*/
typedef NS_ENUM(int, SqliteValueType) {
SqliteValueTypeInteger = 1,
SqliteValueTypeFloat = 2,
SqliteValueTypeText = 3,
SqliteValueTypeBlob = 4,
SqliteValueTypeNull = 5
};
/** Represents the results of executing a query on an @c FMDatabase .
See also
- @c FMDatabase
*/
@interface FMResultSet : NSObject
@property (nonatomic, retain, nullable) FMDatabase *parentDB;
///-----------------
/// @name Properties
///-----------------
/** Executed query */
@property (atomic, retain, nullable) NSString *query;
/** `NSMutableDictionary` mapping column names to numeric index */
@property (readonly) NSMutableDictionary *columnNameToIndexMap;
/** `FMStatement` used by result set. */
@property (atomic, retain, nullable) FMStatement *statement;
///------------------------------------
/// @name Creating and closing a result set
///------------------------------------
/** Close result set */
- (void)close;
///---------------------------------------
/// @name Iterating through the result set
///---------------------------------------
/** Retrieve next row for result set.
You must always invoke `next` or `nextWithError` before attempting to access the values returned in a query, even if you're only expecting one.
@return @c YES if row successfully retrieved; @c NO if end of result set reached
@see hasAnotherRow
*/
- (BOOL)next;
/** Retrieve next row for result set.
You must always invoke `next` or `nextWithError` before attempting to access the values returned in a query, even if you're only expecting one.
@param outErr A 'NSError' object to receive any error object (if any).
@return 'YES' if row successfully retrieved; 'NO' if end of result set reached
@see hasAnotherRow
*/
- (BOOL)nextWithError:(NSError * _Nullable __autoreleasing *)outErr;
/** Perform SQL statement.
@return 'YES' if successful; 'NO' if not.
@see hasAnotherRow
*/
- (BOOL)step;
/** Perform SQL statement.
@param outErr A 'NSError' object to receive any error object (if any).
@return 'YES' if successful; 'NO' if not.
@see hasAnotherRow
*/
- (BOOL)stepWithError:(NSError * _Nullable __autoreleasing *)outErr;
/** Did the last call to `<next>` succeed in retrieving another row?
@return 'YES' if there is another row; 'NO' if not.
@see next
@warning The `hasAnotherRow` method must follow a call to `<next>`. If the previous database interaction was something other than a call to `next`, then this method may return @c NO, whether there is another row of data or not.
*/
- (BOOL)hasAnotherRow;
///---------------------------------------------
/// @name Retrieving information from result set
///---------------------------------------------
/** How many columns in result set
@return Integer value of the number of columns.
*/
@property (nonatomic, readonly) int columnCount;
/** Column index for column name
@param columnName @c NSString value of the name of the column.
@return Zero-based index for column.
*/
- (int)columnIndexForName:(NSString*)columnName;
/** Column name for column index
@param columnIdx Zero-based index for column.
@return columnName @c NSString value of the name of the column.
*/
- (NSString * _Nullable)columnNameForIndex:(int)columnIdx;
/** Result set integer value for column.
@param columnName @c NSString value of the name of the column.
@return @c int value of the result set's column.
*/
- (int)intForColumn:(NSString*)columnName;
/** Result set integer value for column.
@param columnIdx Zero-based index for column.
@return @c int value of the result set's column.
*/
- (int)intForColumnIndex:(int)columnIdx;
/** Result set @c long value for column.
@param columnName @c NSString value of the name of the column.
@return @c long value of the result set's column.
*/
- (long)longForColumn:(NSString*)columnName;
/** Result set long value for column.
@param columnIdx Zero-based index for column.
@return @c long value of the result set's column.
*/
- (long)longForColumnIndex:(int)columnIdx;
/** Result set `long long int` value for column.
@param columnName @c NSString value of the name of the column.
@return `long long int` value of the result set's column.
*/
- (long long int)longLongIntForColumn:(NSString*)columnName;
/** Result set `long long int` value for column.
@param columnIdx Zero-based index for column.
@return `long long int` value of the result set's column.
*/
- (long long int)longLongIntForColumnIndex:(int)columnIdx;
/** Result set `unsigned long long int` value for column.
@param columnName @c NSString value of the name of the column.
@return `unsigned long long int` value of the result set's column.
*/
- (unsigned long long int)unsignedLongLongIntForColumn:(NSString*)columnName;
/** Result set `unsigned long long int` value for column.
@param columnIdx Zero-based index for column.
@return `unsigned long long int` value of the result set's column.
*/
- (unsigned long long int)unsignedLongLongIntForColumnIndex:(int)columnIdx;
/** Result set `BOOL` value for column.
@param columnName @c NSString value of the name of the column.
@return `BOOL` value of the result set's column.
*/
- (BOOL)boolForColumn:(NSString*)columnName;
/** Result set `BOOL` value for column.
@param columnIdx Zero-based index for column.
@return `BOOL` value of the result set's column.
*/
- (BOOL)boolForColumnIndex:(int)columnIdx;
/** Result set `double` value for column.
@param columnName @c NSString value of the name of the column.
@return `double` value of the result set's column.
*/
- (double)doubleForColumn:(NSString*)columnName;
/** Result set `double` value for column.
@param columnIdx Zero-based index for column.
@return `double` value of the result set's column.
*/
- (double)doubleForColumnIndex:(int)columnIdx;
/** Result set @c NSString value for column.
@param columnName @c NSString value of the name of the column.
@return String value of the result set's column.
*/
- (NSString * _Nullable)stringForColumn:(NSString*)columnName;
/** Result set @c NSString value for column.
@param columnIdx Zero-based index for column.
@return String value of the result set's column.
*/
- (NSString * _Nullable)stringForColumnIndex:(int)columnIdx;
/** Result set @c NSDate value for column.
@param columnName @c NSString value of the name of the column.
@return Date value of the result set's column.
*/
- (NSDate * _Nullable)dateForColumn:(NSString*)columnName;
/** Result set @c NSDate value for column.
@param columnIdx Zero-based index for column.
@return Date value of the result set's column.
*/
- (NSDate * _Nullable)dateForColumnIndex:(int)columnIdx;
/** Result set @c NSData value for column.
This is useful when storing binary data in table (such as image or the like).
@param columnName @c NSString value of the name of the column.
@return Data value of the result set's column.
*/
- (NSData * _Nullable)dataForColumn:(NSString*)columnName;
/** Result set @c NSData value for column.
@param columnIdx Zero-based index for column.
@warning For zero length BLOBs, this will return `nil`. Use `typeForColumn` to determine whether this was really a zero
length BLOB or `NULL`.
@return Data value of the result set's column.
*/
- (NSData * _Nullable)dataForColumnIndex:(int)columnIdx;
/** Result set `(const unsigned char *)` value for column.
@param columnName @c NSString value of the name of the column.
@warning For zero length BLOBs, this will return `nil`. Use `typeForColumnIndex` to determine whether this was really a zero
length BLOB or `NULL`.
@return `(const unsigned char *)` value of the result set's column.
*/
- (const unsigned char * _Nullable)UTF8StringForColumn:(NSString*)columnName;
- (const unsigned char * _Nullable)UTF8StringForColumnName:(NSString*)columnName __deprecated_msg("Use UTF8StringForColumn instead");
/** Result set `(const unsigned char *)` value for column.
@param columnIdx Zero-based index for column.
@return `(const unsigned char *)` value of the result set's column.
*/
- (const unsigned char * _Nullable)UTF8StringForColumnIndex:(int)columnIdx;
/** Result set object for column.
@param columnName Name of the column.
@return Either @c NSNumber , @c NSString , @c NSData , or @c NSNull . If the column was @c NULL , this returns `[NSNull null]` object.
@see objectForKeyedSubscript:
*/
- (id _Nullable)objectForColumn:(NSString*)columnName;
- (id _Nullable)objectForColumnName:(NSString*)columnName __deprecated_msg("Use objectForColumn instead");
/** Column type by column name.
@param columnName Name of the column.
@return The `SqliteValueType` of the value in this column.
*/
- (SqliteValueType)typeForColumn:(NSString*)columnName;
/** Column type by column index.
@param columnIdx Index of the column.
@return The `SqliteValueType` of the value in this column.
*/
- (SqliteValueType)typeForColumnIndex:(int)columnIdx;
/** Result set object for column.
@param columnIdx Zero-based index for column.
@return Either @c NSNumber , @c NSString , @c NSData , or @c NSNull . If the column was @c NULL , this returns `[NSNull null]` object.
@see objectAtIndexedSubscript:
*/
- (id _Nullable)objectForColumnIndex:(int)columnIdx;
/** Result set object for column.
This method allows the use of the "boxed" syntax supported in Modern Objective-C. For example, by defining this method, the following syntax is now supported:
@code
id result = rs[@"employee_name"];
@endcode
This simplified syntax is equivalent to calling:
@code
id result = [rs objectForKeyedSubscript:@"employee_name"];
@endcode
which is, it turns out, equivalent to calling:
@code
id result = [rs objectForColumnName:@"employee_name"];
@endcode
@param columnName @c NSString value of the name of the column.
@return Either @c NSNumber , @c NSString , @c NSData , or @c NSNull . If the column was @c NULL , this returns `[NSNull null]` object.
*/
- (id _Nullable)objectForKeyedSubscript:(NSString *)columnName;
/** Result set object for column.
This method allows the use of the "boxed" syntax supported in Modern Objective-C. For example, by defining this method, the following syntax is now supported:
@code
id result = rs[0];
@endcode
This simplified syntax is equivalent to calling:
@code
id result = [rs objectForKeyedSubscript:0];
@endcode
which is, it turns out, equivalent to calling:
@code
id result = [rs objectForColumnName:0];
@endcode
@param columnIdx Zero-based index for column.
@return Either @c NSNumber , @c NSString , @c NSData , or @c NSNull . If the column was @c NULL , this returns `[NSNull null]` object.
*/
- (id _Nullable)objectAtIndexedSubscript:(int)columnIdx;
/** Result set @c NSData value for column.
@param columnName @c NSString value of the name of the column.
@return Data value of the result set's column.
@warning If you are going to use this data after you iterate over the next row, or after you close the
result set, make sure to make a copy of the data first (or just use `<dataForColumn:>`/`<dataForColumnIndex:>`)
If you don't, you're going to be in a world of hurt when you try and use the data.
*/
- (NSData * _Nullable)dataNoCopyForColumn:(NSString *)columnName NS_RETURNS_NOT_RETAINED;
/** Result set @c NSData value for column.
@param columnIdx Zero-based index for column.
@return Data value of the result set's column.
@warning If you are going to use this data after you iterate over the next row, or after you close the
result set, make sure to make a copy of the data first (or just use `<dataForColumn:>`/`<dataForColumnIndex:>`)
If you don't, you're going to be in a world of hurt when you try and use the data.
*/
- (NSData * _Nullable)dataNoCopyForColumnIndex:(int)columnIdx NS_RETURNS_NOT_RETAINED;
/** Is the column @c NULL ?
@param columnIdx Zero-based index for column.
@return @c YES if column is @c NULL ; @c NO if not @c NULL .
*/
- (BOOL)columnIndexIsNull:(int)columnIdx;
/** Is the column @c NULL ?
@param columnName @c NSString value of the name of the column.
@return @c YES if column is @c NULL ; @c NO if not @c NULL .
*/
- (BOOL)columnIsNull:(NSString*)columnName;
/** Returns a dictionary of the row results mapped to case sensitive keys of the column names.
@warning The keys to the dictionary are case sensitive of the column names.
*/
@property (nonatomic, readonly, nullable) NSDictionary *resultDictionary;
/** Returns a dictionary of the row results
@see resultDictionary
@warning **Deprecated**: Please use `<resultDictionary>` instead. Also, beware that `<resultDictionary>` is case sensitive!
*/
- (NSDictionary * _Nullable)resultDict __deprecated_msg("Use resultDictionary instead");
///-----------------------------
/// @name Key value coding magic
///-----------------------------
/** Performs `setValue` to yield support for key value observing.
@param object The object for which the values will be set. This is the key-value-coding compliant object that you might, for example, observe.
*/
- (void)kvcMagic:(id)object;
///-----------------------------
/// @name Binding values
///-----------------------------
/// Bind array of values to prepared statement.
///
/// @param array Array of values to bind to SQL statement.
- (BOOL)bindWithArray:(NSArray*)array;
/// Bind dictionary of values to prepared statement.
///
/// @param dictionary Dictionary of values to bind to SQL statement.
- (BOOL)bindWithDictionary:(NSDictionary *)dictionary;
@end
NS_ASSUME_NONNULL_END

471
Pods/FMDB/src/fmdb/FMResultSet.m generated Normal file
View File

@@ -0,0 +1,471 @@
#import "FMResultSet.h"
#import "FMDatabase.h"
#import <unistd.h>
#if FMDB_SQLITE_STANDALONE
#import <sqlite3/sqlite3.h>
#else
#import <sqlite3.h>
#endif
// MARK: - FMDatabase Private Extension
@interface FMDatabase ()
- (void)resultSetDidClose:(FMResultSet *)resultSet;
- (BOOL)bindStatement:(sqlite3_stmt *)pStmt WithArgumentsInArray:(NSArray*)arrayArgs orDictionary:(NSDictionary *)dictionaryArgs orVAList:(va_list)args;
@end
// MARK: - FMResultSet Private Extension
@interface FMResultSet () {
NSMutableDictionary *_columnNameToIndexMap;
}
@property (nonatomic) BOOL shouldAutoClose;
@end
// MARK: - FMResultSet
@implementation FMResultSet
+ (instancetype)resultSetWithStatement:(FMStatement *)statement usingParentDatabase:(FMDatabase*)aDB shouldAutoClose:(BOOL)shouldAutoClose {
FMResultSet *rs = [[FMResultSet alloc] init];
[rs setStatement:statement];
[rs setParentDB:aDB];
[rs setShouldAutoClose:shouldAutoClose];
NSParameterAssert(![statement inUse]);
[statement setInUse:YES]; // weak reference
return FMDBReturnAutoreleased(rs);
}
#if ! __has_feature(objc_arc)
- (void)finalize {
[self close];
[super finalize];
}
#endif
- (void)dealloc {
[self close];
FMDBRelease(_query);
_query = nil;
FMDBRelease(_columnNameToIndexMap);
_columnNameToIndexMap = nil;
#if ! __has_feature(objc_arc)
[super dealloc];
#endif
}
- (void)close {
[_statement reset];
FMDBRelease(_statement);
_statement = nil;
// we don't need this anymore... (i think)
//[_parentDB setInUse:NO];
[_parentDB resultSetDidClose:self];
[self setParentDB:nil];
}
- (int)columnCount {
return sqlite3_column_count([_statement statement]);
}
- (NSMutableDictionary *)columnNameToIndexMap {
if (!_columnNameToIndexMap) {
int columnCount = sqlite3_column_count([_statement statement]);
_columnNameToIndexMap = [[NSMutableDictionary alloc] initWithCapacity:(NSUInteger)columnCount];
int columnIdx = 0;
for (columnIdx = 0; columnIdx < columnCount; columnIdx++) {
[_columnNameToIndexMap setObject:[NSNumber numberWithInt:columnIdx]
forKey:[[NSString stringWithUTF8String:sqlite3_column_name([_statement statement], columnIdx)] lowercaseString]];
}
}
return _columnNameToIndexMap;
}
- (void)kvcMagic:(id)object {
int columnCount = sqlite3_column_count([_statement statement]);
int columnIdx = 0;
for (columnIdx = 0; columnIdx < columnCount; columnIdx++) {
const char *c = (const char *)sqlite3_column_text([_statement statement], columnIdx);
// check for a null row
if (c) {
NSString *s = [NSString stringWithUTF8String:c];
[object setValue:s forKey:[NSString stringWithUTF8String:sqlite3_column_name([_statement statement], columnIdx)]];
}
}
}
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-implementations"
- (NSDictionary *)resultDict {
NSUInteger num_cols = (NSUInteger)sqlite3_data_count([_statement statement]);
if (num_cols > 0) {
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:num_cols];
NSEnumerator *columnNames = [[self columnNameToIndexMap] keyEnumerator];
NSString *columnName = nil;
while ((columnName = [columnNames nextObject])) {
id objectValue = [self objectForColumnName:columnName];
[dict setObject:objectValue forKey:columnName];
}
return FMDBReturnAutoreleased([dict copy]);
}
else {
NSLog(@"Warning: There seem to be no columns in this set.");
}
return nil;
}
#pragma clang diagnostic pop
- (NSDictionary*)resultDictionary {
NSUInteger num_cols = (NSUInteger)sqlite3_data_count([_statement statement]);
if (num_cols > 0) {
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:num_cols];
int columnCount = sqlite3_column_count([_statement statement]);
int columnIdx = 0;
for (columnIdx = 0; columnIdx < columnCount; columnIdx++) {
NSString *columnName = [NSString stringWithUTF8String:sqlite3_column_name([_statement statement], columnIdx)];
id objectValue = [self objectForColumnIndex:columnIdx];
[dict setObject:objectValue forKey:columnName];
}
return dict;
}
else {
NSLog(@"Warning: There seem to be no columns in this set.");
}
return nil;
}
- (BOOL)next {
return [self nextWithError:nil];
}
- (BOOL)nextWithError:(NSError * _Nullable __autoreleasing *)outErr {
int rc = [self internalStepWithError:outErr];
return rc == SQLITE_ROW;
}
- (BOOL)step {
return [self stepWithError:nil];
}
- (BOOL)stepWithError:(NSError * _Nullable __autoreleasing *)outErr {
int rc = [self internalStepWithError:outErr];
return rc == SQLITE_DONE;
}
- (int)internalStepWithError:(NSError * _Nullable __autoreleasing *)outErr {
int rc = sqlite3_step([_statement statement]);
if (SQLITE_BUSY == rc || SQLITE_LOCKED == rc) {
NSLog(@"%s:%d Database busy (%@)", __FUNCTION__, __LINE__, [_parentDB databasePath]);
NSLog(@"Database busy");
if (outErr) {
*outErr = [_parentDB lastError];
}
}
else if (SQLITE_DONE == rc || SQLITE_ROW == rc) {
// all is well, let's return.
}
else if (SQLITE_ERROR == rc) {
NSLog(@"Error calling sqlite3_step (%d: %s) rs", rc, sqlite3_errmsg([_parentDB sqliteHandle]));
if (outErr) {
*outErr = [_parentDB lastError];
}
}
else if (SQLITE_MISUSE == rc) {
// uh oh.
NSLog(@"Error calling sqlite3_step (%d: %s) rs", rc, sqlite3_errmsg([_parentDB sqliteHandle]));
if (outErr) {
if (_parentDB) {
*outErr = [_parentDB lastError];
}
else {
// If 'next' or 'nextWithError' is called after the result set is closed,
// we need to return the appropriate error.
NSDictionary* errorMessage = [NSDictionary dictionaryWithObject:@"parentDB does not exist" forKey:NSLocalizedDescriptionKey];
*outErr = [NSError errorWithDomain:@"FMDatabase" code:SQLITE_MISUSE userInfo:errorMessage];
}
}
}
else {
// wtf?
NSLog(@"Unknown error calling sqlite3_step (%d: %s) rs", rc, sqlite3_errmsg([_parentDB sqliteHandle]));
if (outErr) {
*outErr = [_parentDB lastError];
}
}
if (rc != SQLITE_ROW && _shouldAutoClose) {
[self close];
}
return rc;
}
- (BOOL)hasAnotherRow {
return sqlite3_errcode([_parentDB sqliteHandle]) == SQLITE_ROW;
}
- (int)columnIndexForName:(NSString*)columnName {
columnName = [columnName lowercaseString];
NSNumber *n = [[self columnNameToIndexMap] objectForKey:columnName];
if (n != nil) {
return [n intValue];
}
NSLog(@"Warning: I could not find the column named '%@'.", columnName);
return -1;
}
- (int)intForColumn:(NSString*)columnName {
return [self intForColumnIndex:[self columnIndexForName:columnName]];
}
- (int)intForColumnIndex:(int)columnIdx {
return sqlite3_column_int([_statement statement], columnIdx);
}
- (long)longForColumn:(NSString*)columnName {
return [self longForColumnIndex:[self columnIndexForName:columnName]];
}
- (long)longForColumnIndex:(int)columnIdx {
return (long)sqlite3_column_int64([_statement statement], columnIdx);
}
- (long long int)longLongIntForColumn:(NSString*)columnName {
return [self longLongIntForColumnIndex:[self columnIndexForName:columnName]];
}
- (long long int)longLongIntForColumnIndex:(int)columnIdx {
return sqlite3_column_int64([_statement statement], columnIdx);
}
- (unsigned long long int)unsignedLongLongIntForColumn:(NSString*)columnName {
return [self unsignedLongLongIntForColumnIndex:[self columnIndexForName:columnName]];
}
- (unsigned long long int)unsignedLongLongIntForColumnIndex:(int)columnIdx {
return (unsigned long long int)[self longLongIntForColumnIndex:columnIdx];
}
- (BOOL)boolForColumn:(NSString*)columnName {
return [self boolForColumnIndex:[self columnIndexForName:columnName]];
}
- (BOOL)boolForColumnIndex:(int)columnIdx {
return ([self intForColumnIndex:columnIdx] != 0);
}
- (double)doubleForColumn:(NSString*)columnName {
return [self doubleForColumnIndex:[self columnIndexForName:columnName]];
}
- (double)doubleForColumnIndex:(int)columnIdx {
return sqlite3_column_double([_statement statement], columnIdx);
}
- (NSString *)stringForColumnIndex:(int)columnIdx {
if (sqlite3_column_type([_statement statement], columnIdx) == SQLITE_NULL || (columnIdx < 0) || columnIdx >= sqlite3_column_count([_statement statement])) {
return nil;
}
const char *c = (const char *)sqlite3_column_text([_statement statement], columnIdx);
if (!c) {
// null row.
return nil;
}
return [NSString stringWithUTF8String:c];
}
- (NSString*)stringForColumn:(NSString*)columnName {
return [self stringForColumnIndex:[self columnIndexForName:columnName]];
}
- (NSDate*)dateForColumn:(NSString*)columnName {
return [self dateForColumnIndex:[self columnIndexForName:columnName]];
}
- (NSDate*)dateForColumnIndex:(int)columnIdx {
if (sqlite3_column_type([_statement statement], columnIdx) == SQLITE_NULL || (columnIdx < 0) || columnIdx >= sqlite3_column_count([_statement statement])) {
return nil;
}
return [_parentDB hasDateFormatter] ? [_parentDB dateFromString:[self stringForColumnIndex:columnIdx]] : [NSDate dateWithTimeIntervalSince1970:[self doubleForColumnIndex:columnIdx]];
}
- (NSData*)dataForColumn:(NSString*)columnName {
return [self dataForColumnIndex:[self columnIndexForName:columnName]];
}
- (NSData*)dataForColumnIndex:(int)columnIdx {
if (sqlite3_column_type([_statement statement], columnIdx) == SQLITE_NULL || (columnIdx < 0) || columnIdx >= sqlite3_column_count([_statement statement])) {
return nil;
}
const char *dataBuffer = sqlite3_column_blob([_statement statement], columnIdx);
int dataSize = sqlite3_column_bytes([_statement statement], columnIdx);
if (dataBuffer == NULL) {
return nil;
}
return [NSData dataWithBytes:(const void *)dataBuffer length:(NSUInteger)dataSize];
}
- (NSData*)dataNoCopyForColumn:(NSString*)columnName {
return [self dataNoCopyForColumnIndex:[self columnIndexForName:columnName]];
}
- (NSData*)dataNoCopyForColumnIndex:(int)columnIdx {
if (sqlite3_column_type([_statement statement], columnIdx) == SQLITE_NULL || (columnIdx < 0) || columnIdx >= sqlite3_column_count([_statement statement])) {
return nil;
}
const char *dataBuffer = sqlite3_column_blob([_statement statement], columnIdx);
int dataSize = sqlite3_column_bytes([_statement statement], columnIdx);
NSData *data = [NSData dataWithBytesNoCopy:(void *)dataBuffer length:(NSUInteger)dataSize freeWhenDone:NO];
return data;
}
- (BOOL)columnIndexIsNull:(int)columnIdx {
return sqlite3_column_type([_statement statement], columnIdx) == SQLITE_NULL;
}
- (BOOL)columnIsNull:(NSString*)columnName {
return [self columnIndexIsNull:[self columnIndexForName:columnName]];
}
- (const unsigned char *)UTF8StringForColumnIndex:(int)columnIdx {
if (sqlite3_column_type([_statement statement], columnIdx) == SQLITE_NULL || (columnIdx < 0) || columnIdx >= sqlite3_column_count([_statement statement])) {
return nil;
}
return sqlite3_column_text([_statement statement], columnIdx);
}
- (const unsigned char *)UTF8StringForColumn:(NSString*)columnName {
return [self UTF8StringForColumnIndex:[self columnIndexForName:columnName]];
}
- (const unsigned char *)UTF8StringForColumnName:(NSString*)columnName {
return [self UTF8StringForColumn:columnName];
}
- (id)objectForColumnIndex:(int)columnIdx {
if (columnIdx < 0 || columnIdx >= sqlite3_column_count([_statement statement])) {
return nil;
}
int columnType = sqlite3_column_type([_statement statement], columnIdx);
id returnValue = nil;
if (columnType == SQLITE_INTEGER) {
returnValue = [NSNumber numberWithLongLong:[self longLongIntForColumnIndex:columnIdx]];
}
else if (columnType == SQLITE_FLOAT) {
returnValue = [NSNumber numberWithDouble:[self doubleForColumnIndex:columnIdx]];
}
else if (columnType == SQLITE_BLOB) {
returnValue = [self dataForColumnIndex:columnIdx];
}
else {
//default to a string for everything else
returnValue = [self stringForColumnIndex:columnIdx];
}
if (returnValue == nil) {
returnValue = [NSNull null];
}
return returnValue;
}
- (id)objectForColumnName:(NSString*)columnName {
return [self objectForColumn:columnName];
}
- (id)objectForColumn:(NSString*)columnName {
return [self objectForColumnIndex:[self columnIndexForName:columnName]];
}
- (SqliteValueType)typeForColumn:(NSString*)columnName {
return sqlite3_column_type([_statement statement], [self columnIndexForName:columnName]);
}
- (SqliteValueType)typeForColumnIndex:(int)columnIdx {
return sqlite3_column_type([_statement statement], columnIdx);
}
// returns autoreleased NSString containing the name of the column in the result set
- (NSString*)columnNameForIndex:(int)columnIdx {
return [NSString stringWithUTF8String: sqlite3_column_name([_statement statement], columnIdx)];
}
- (id)objectAtIndexedSubscript:(int)columnIdx {
return [self objectForColumnIndex:columnIdx];
}
- (id)objectForKeyedSubscript:(NSString *)columnName {
return [self objectForColumn:columnName];
}
// MARK: Bind
- (BOOL)bindWithArray:(NSArray*)array orDictionary:(NSDictionary *)dictionary orVAList:(va_list)args {
[_statement reset];
return [_parentDB bindStatement:_statement.statement WithArgumentsInArray:array orDictionary:dictionary orVAList:args];
}
- (BOOL)bindWithArray:(NSArray*)array {
return [self bindWithArray:array orDictionary:nil orVAList:nil];
}
- (BOOL)bindWithDictionary:(NSDictionary *)dictionary {
return [self bindWithArray:nil orDictionary:dictionary orVAList:nil];
}
@end