AWSFMDatabase

Objective-C

@interface AWSFMDatabase : NSObject  {
    
    NSString*           _databasePath;
    BOOL                _logsErrors;
    BOOL                _crashOnErrors;
    BOOL                _traceExecution;
    BOOL                _checkedOut;
    BOOL                _shouldCacheStatements;
    BOOL                _isExecutingStatement;
    BOOL                _inTransaction;
    NSTimeInterval      _maxBusyRetryTimeInterval;
    NSTimeInterval      _startBusyRetryTime;
    
    NSMutableDictionary *_cachedStatements;
    NSMutableSet        *_openResultSets;
    NSMutableSet        *_openFunctions;

    NSDateFormatter     *_dateFormat;
}

///-----------------
/// @name Properties
///-----------------

/** Whether should trace execution */

@property (atomic, assign) BOOL traceExecution;

/** Whether checked out or not */

@property (atomic, assign) BOOL checkedOut;

/** Crash on errors */

@property (atomic, assign) BOOL crashOnErrors;

/** Logs errors */

@property (atomic, assign) BOOL logsErrors;

/** Dictionary of cached statements */

@property (atomic, retain) NSMutableDictionary *cachedStatements;

///---------------------
/// @name Initialization
///---------------------

/** Create a `FMDatabase` object.
 
 An `FMDatabase` is created with a path to a SQLite database file.  This path can be one of these three:

 1. A file system path.  The file does not have to exist on disk.  If it does not exist, it is created for you.
 2. An empty string (`@""`).  An empty database is created at a temporary location.  This database is deleted with the `FMDatabase` connection is closed.
 3. `nil`.  An in-memory database is created.  This database will be destroyed with the `FMDatabase` connection is closed.

 For example, to create/open a database in your Mac OS X `tmp` folder:

    FMDatabase *db = [FMDatabase databaseWithPath:@"/tmp/tmp.db"];

 Or, in iOS, you might open a database in the app's `Documents` directory:

    NSString *docsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    NSString *dbPath   = [docsPath stringByAppendingPathComponent:@"test.db"];
    FMDatabase *db     = [FMDatabase databaseWithPath:dbPath];

 (For more information on temporary and in-memory databases, read the sqlite documentation on the subject: [http://www.sqlite.org/inmemorydb.html](http://www.sqlite.org/inmemorydb.html))

 @param inPath Path of database file

 @return `FMDatabase` object if successful; `nil` if failure.

 */

+ (instancetype)databaseWithPath:(NSString*)inPath;

/** Initialize a `FMDatabase` object.
 
 An `FMDatabase` is created with a path to a SQLite database file.  This path can be one of these three:

 1. A file system path.  The file does not have to exist on disk.  If it does not exist, it is created for you.
 2. An empty string (`@""`).  An empty database is created at a temporary location.  This database is deleted with the `FMDatabase` connection is closed.
 3. `nil`.  An in-memory database is created.  This database will be destroyed with the `FMDatabase` connection is closed.

 For example, to create/open a database in your Mac OS X `tmp` folder:

    FMDatabase *db = [FMDatabase databaseWithPath:@"/tmp/tmp.db"];

 Or, in iOS, you might open a database in the app's `Documents` directory:

    NSString *docsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    NSString *dbPath   = [docsPath stringByAppendingPathComponent:@"test.db"];
    FMDatabase *db     = [FMDatabase databaseWithPath:dbPath];

 (For more information on temporary and in-memory databases, read the sqlite documentation on the subject: [http://www.sqlite.org/inmemorydb.html](http://www.sqlite.org/inmemorydb.html))

 @param inPath Path of database file
 
 @return `FMDatabase` object if successful; `nil` if failure.

 */

- (instancetype)initWithPath:(NSString*)inPath;


///-----------------------------------
/// @name Opening and closing database
///-----------------------------------

/** Opening a new database connection
 
 The database is opened for reading and writing, and is created if it does not already exist.

 @return `YES` if successful, `NO` on error.

 @see [sqlite3_open()](http://sqlite.org/c3ref/open.html)
 @see openWithFlags:
 @see close
 */

- (BOOL)open;

/** Opening a new database connection with flags and an optional virtual file system (VFS)

 @param flags one of the following three values, optionally combined with the `SQLITE_OPEN_NOMUTEX`, `SQLITE_OPEN_FULLMUTEX`, `SQLITE_OPEN_SHAREDCACHE`, `SQLITE_OPEN_PRIVATECACHE`, and/or `SQLITE_OPEN_URI` flags:

 `SQLITE_OPEN_READONLY`

 The database is opened in read-only mode. If the database does not already exist, an error is returned.
 
 `SQLITE_OPEN_READWRITE`
 
 The database is opened for reading and writing if possible, or reading only if the file is write protected by the operating system. In either case the database must already exist, otherwise an error is returned.
 
 `SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE`
 
 The database is opened for reading and writing, and is created if it does not already exist. This is the behavior that is always used for `open` method.
 
 If vfs is given the value is passed to the vfs parameter of sqlite3_open_v2.
 
 @return `YES` if successful, `NO` on error.

 @see [sqlite3_open_v2()](http://sqlite.org/c3ref/open.html)
 @see open
 @see close
 
 @warning Requires SQLite 3.5
 */

- (BOOL)openWithFlags:(int)flags;
- (BOOL)openWithFlags:(int)flags vfs:(NSString *)vfsName;

/** Closing a database connection
 
 @return `YES` if success, `NO` on error.
 
 @see [sqlite3_close()](http://sqlite.org/c3ref/close.html)
 @see open
 @see openWithFlags:
 */

- (BOOL)close;

/** Test to see if we have a good connection to the database.
 
 This will confirm whether:
 
 - is database open
 - if open, it will try a simple SELECT statement and confirm that it succeeds.

 @return `YES` if everything succeeds, `NO` on failure.
 */

- (BOOL)goodConnection;


///----------------------
/// @name Perform updates
///----------------------

/** Execute single update statement
 
 This method executes a single SQL update statement (i.e. any SQL that does not return results, such as `UPDATE`, `INSERT`, or `DELETE`. This method employs [`sqlite3_prepare_v2`](http://sqlite.org/c3ref/prepare.html), [`sqlite3_bind`](http://sqlite.org/c3ref/bind_blob.html) to bind values to `?` placeholders in the SQL with the optional list of parameters, and [`sqlite_step`](http://sqlite.org/c3ref/step.html) to perform the update.

 The optional values provided to this method should be objects (e.g. `NSString`, `NSNumber`, `NSNull`, `NSDate`, and `NSData` objects), not fundamental data types (e.g. `int`, `long`, `NSInteger`, etc.). This method automatically handles the aforementioned object types, and all other object types will be interpreted as text values using the object's `description` method.

 @param sql The SQL to be performed, with optional `?` placeholders.
 
 @param outErr A reference to the `NSError` pointer to be updated with an auto released `NSError` object if an error if an error occurs. If `nil`, no `NSError` object will be returned.
 
 @param ... Optional parameters to bind to `?` placeholders in the SQL statement. These should be Objective-C objects (e.g. `NSString`, `NSNumber`, etc.), not fundamental C data types (e.g. `int`, `char *`, etc.).

 @return `YES` upon success; `NO` upon failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.

 @see lastError
 @see lastErrorCode
 @see lastErrorMessage
 @see [`sqlite3_bind`](http://sqlite.org/c3ref/bind_blob.html)
 */

- (BOOL)executeUpdate:(NSString*)sql withErrorAndBindings:(NSError**)outErr, ...;

/** Execute single update statement
 
 @see executeUpdate:withErrorAndBindings:
 
 @warning **Deprecated**: Please use `<executeUpdate:withErrorAndBindings>` instead.
 */

- (BOOL)update:(NSString*)sql withErrorAndBindings:(NSError**)outErr, ... __attribute__ ((deprecated));

/** Execute single update statement

 This method executes a single SQL update statement (i.e. any SQL that does not return results, such as `UPDATE`, `INSERT`, or `DELETE`. This method employs [`sqlite3_prepare_v2`](http://sqlite.org/c3ref/prepare.html), [`sqlite3_bind`](http://sqlite.org/c3ref/bind_blob.html) to bind values to `?` placeholders in the SQL with the optional list of parameters, and [`sqlite_step`](http://sqlite.org/c3ref/step.html) to perform the update.

 The optional values provided to this method should be objects (e.g. `NSString`, `NSNumber`, `NSNull`, `NSDate`, and `NSData` objects), not fundamental data types (e.g. `int`, `long`, `NSInteger`, etc.). This method automatically handles the aforementioned object types, and all other object types will be interpreted as text values using the object's `description` method.
 
 @param sql The SQL to be performed, with optional `?` placeholders.

 @param ... Optional parameters to bind to `?` placeholders in the SQL statement. These should be Objective-C objects (e.g. `NSString`, `NSNumber`, etc.), not fundamental C data types (e.g. `int`, `char *`, etc.).

 @return `YES` upon success; `NO` upon failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
 
 @see lastError
 @see lastErrorCode
 @see lastErrorMessage
 @see [`sqlite3_bind`](http://sqlite.org/c3ref/bind_blob.html)
 
 @note This technique supports the use of `?` placeholders in the SQL, automatically binding any supplied value parameters to those placeholders. This approach is more robust than techniques that entail using `stringWithFormat` to manually build SQL statements, which can be problematic if the values happened to include any characters that needed to be quoted.
 
 @note If you want to use this from Swift, please note that you must include `FMDatabaseVariadic.swift` in your project. Without that, you cannot use this method directly, and instead have to use methods such as `<executeUpdate:withArgumentsInArray:>`.
 */

- (BOOL)executeUpdate:(NSString*)sql, ...;

/** Execute single update statement

 This method executes a single SQL update statement (i.e. any SQL that does not return results, such as `UPDATE`, `INSERT`, or `DELETE`. This method employs [`sqlite3_prepare_v2`](http://sqlite.org/c3ref/prepare.html) and [`sqlite_step`](http://sqlite.org/c3ref/step.html) to perform the update. Unlike the other `executeUpdate` methods, this uses printf-style formatters (e.g. `%s`, `%d`, etc.) to build the SQL. Do not use `?` placeholders in the SQL if you use this method.

 @param format The SQL to be performed, with `printf`-style escape sequences.

 @param ... Optional parameters to bind to use in conjunction with the `printf`-style escape sequences in the SQL statement.

 @return `YES` upon success; `NO` upon failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.

 @see executeUpdate:
 @see lastError
 @see lastErrorCode
 @see lastErrorMessage
 
 @note This method does not technically perform a traditional printf-style replacement. What this method actually does is replace the printf-style percent sequences with a SQLite `?` placeholder, and then bind values to that placeholder. Thus the following command

    [db executeUpdateWithFormat:@"INSERT INTO test (name) VALUES (%@)", @"Gus"];

 is actually replacing the `%@` with `?` placeholder, and then performing something equivalent to `<executeUpdate:>`

    [db executeUpdate:@"INSERT INTO test (name) VALUES (?)", @"Gus"];

 There are two reasons why this distinction is important. First, the printf-style escape sequences can only be used where it is permissible to use a SQLite `?` placeholder. You can use it only for values in SQL statements, but not for table names or column names or any other non-value context. This method also cannot be used in conjunction with `pragma` statements and the like. Second, note the lack of quotation marks in the SQL. The `VALUES` clause was _not_ `VALUES ('%@')` (like you might have to do if you built a SQL statement using `NSString` method `stringWithFormat`), but rather simply `VALUES (%@)`.
 */

- (BOOL)executeUpdateWithFormat:(NSString *)format, ... NS_FORMAT_FUNCTION(1,2);

/** Execute single update statement

 This method executes a single SQL update statement (i.e. any SQL that does not return results, such as `UPDATE`, `INSERT`, or `DELETE`. This method employs [`sqlite3_prepare_v2`](http://sqlite.org/c3ref/prepare.html) and [`sqlite3_bind`](http://sqlite.org/c3ref/bind_blob.html) binding any `?` placeholders in the SQL with the optional list of parameters.

 The optional values provided to this method should be objects (e.g. `NSString`, `NSNumber`, `NSNull`, `NSDate`, and `NSData` objects), not fundamental data types (e.g. `int`, `long`, `NSInteger`, etc.). This method automatically handles the aforementioned object types, and all other object types will be interpreted as text values using the object's `description` method.

 @param sql The SQL to be performed, with optional `?` placeholders.

 @param arguments A `NSArray` of objects to be used when binding values to the `?` placeholders in the SQL statement.

 @return `YES` upon success; `NO` upon failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.

 @see lastError
 @see lastErrorCode
 @see lastErrorMessage
 */

- (BOOL)executeUpdate:(NSString*)sql withArgumentsInArray:(NSArray *)arguments;

/** Execute single update statement

 This method executes a single SQL update statement (i.e. any SQL that does not return results, such as `UPDATE`, `INSERT`, or `DELETE`. This method employs [`sqlite3_prepare_v2`](http://sqlite.org/c3ref/prepare.html) and [`sqlite_step`](http://sqlite.org/c3ref/step.html) to perform the update. Unlike the other `executeUpdate` methods, this uses printf-style formatters (e.g. `%s`, `%d`, etc.) to build the SQL.

 The optional values provided to this method should be objects (e.g. `NSString`, `NSNumber`, `NSNull`, `NSDate`, and `NSData` objects), not fundamental data types (e.g. `int`, `long`, `NSInteger`, etc.). This method automatically handles the aforementioned object types, and all other object types will be interpreted as text values using the object's `description` method.

 @param sql The SQL to be performed, with optional `?` placeholders.

 @param arguments A `NSDictionary` of objects keyed by column names that will be used when binding values to the `?` placeholders in the SQL statement.

 @return `YES` upon success; `NO` upon failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.

 @see lastError
 @see lastErrorCode
 @see lastErrorMessage
*/

- (BOOL)executeUpdate:(NSString*)sql withParameterDictionary:(NSDictionary *)arguments;


/** Execute single update statement

 This method executes a single SQL update statement (i.e. any SQL that does not return results, such as `UPDATE`, `INSERT`, or `DELETE`. This method employs [`sqlite3_prepare_v2`](http://sqlite.org/c3ref/prepare.html) and [`sqlite_step`](http://sqlite.org/c3ref/step.html) to perform the update. Unlike the other `executeUpdate` methods, this uses printf-style formatters (e.g. `%s`, `%d`, etc.) to build the SQL.

 The optional values provided to this method should be objects (e.g. `NSString`, `NSNumber`, `NSNull`, `NSDate`, and `NSData` objects), not fundamental data types (e.g. `int`, `long`, `NSInteger`, etc.). This method automatically handles the aforementioned object types, and all other object types will be interpreted as text values using the object's `description` method.

 @param sql The SQL to be performed, with optional `?` placeholders.

 @param args A `va_list` of arguments.

 @return `YES` upon success; `NO` upon failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.

 @see lastError
 @see lastErrorCode
 @see lastErrorMessage
 */

- (BOOL)executeUpdate:(NSString*)sql withVAList: (va_list)args;

/** Execute multiple SQL statements
 
 This executes a series of SQL statements that are combined in a single string (e.g. the SQL generated by the `sqlite3` command line `.dump` command). This accepts no value parameters, but rather simply expects a single string with multiple SQL statements, each terminated with a semicolon. This uses `sqlite3_exec`. 

 @param  sql  The SQL to be performed
 
 @return      `YES` upon success; `NO` upon failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.

 @see executeStatements:withResultBlock:
 @see [sqlite3_exec()](http://sqlite.org/c3ref/exec.html)

 */

- (BOOL)executeStatements:(NSString *)sql;

/** Execute multiple SQL statements with callback handler
 
 This executes a series of SQL statements that are combined in a single string (e.g. the SQL generated by the `sqlite3` command line `.dump` command). This accepts no value parameters, but rather simply expects a single string with multiple SQL statements, each terminated with a semicolon. This uses `sqlite3_exec`.

 @param sql       The SQL to be performed.
 @param block     A block that will be called for any result sets returned by any SQL statements. 
                  Note, if you supply this block, it must return integer value, zero upon success (this would be a good opportunity to use SQLITE_OK),
                  non-zero value upon failure (which will stop the bulk execution of the SQL).  If a statement returns values, the block will be called with the results from the query in NSDictionary *resultsDictionary.
                  This may be `nil` if you don't care to receive any results.

 @return          `YES` upon success; `NO` upon failure. If failed, you can call `<lastError>`,
                  `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
 
 @see executeStatements:
 @see [sqlite3_exec()](http://sqlite.org/c3ref/exec.html)

 */

- (BOOL)executeStatements:(NSString *)sql withResultBlock:(AWSFMDBExecuteStatementsCallbackBlock)block;

/** Last insert rowid
 
 Each entry in an SQLite table has a unique 64-bit signed integer key called the "rowid". The rowid is always available as an undeclared column named `ROWID`, `OID`, or `_ROWID_` as long as those names are not also used by explicitly declared columns. If the table has a column of type `INTEGER PRIMARY KEY` then that column is another alias for the rowid.
 
 This routine returns the rowid of the most recent successful `INSERT` into the database from the database connection in the first argument. As of SQLite version 3.7.7, this routines records the last insert rowid of both ordinary tables and virtual tables. If no successful `INSERT`s have ever occurred on that database connection, zero is returned.
 
 @return The rowid of the last inserted row.
 
 @see [sqlite3_last_insert_rowid()](http://sqlite.org/c3ref/last_insert_rowid.html)

 */

- (long long int)lastInsertRowId;

/** The number of rows changed by prior SQL statement.
 
 This function returns the number of database rows that were changed or inserted or deleted by the most recently completed SQL statement on the database connection specified by the first parameter. Only changes that are directly specified by the INSERT, UPDATE, or DELETE statement are counted.
 
 @return The number of rows changed by prior SQL statement.
 
 @see [sqlite3_changes()](http://sqlite.org/c3ref/changes.html)
 
 */

- (int)changes;


///-------------------------
/// @name Retrieving results
///-------------------------

/** Execute select statement

 Executing queries returns an `<FMResultSet>` object if successful, and `nil` upon failure.  Like executing updates, there is a variant that accepts an `NSError **` parameter.  Otherwise you should use the `<lastErrorMessage>` and `<lastErrorMessage>` methods to determine why a query failed.
 
 In order to iterate through the results of your query, you use a `while()` loop.  You also need to "step" (via `<[FMResultSet next]>`) from one record to the other.
 
 This method employs [`sqlite3_bind`](http://sqlite.org/c3ref/bind_blob.html) for any optional value parameters. This  properly escapes any characters that need escape sequences (e.g. quotation marks), which eliminates simple SQL errors as well as protects against SQL injection attacks. This method natively handles `NSString`, `NSNumber`, `NSNull`, `NSDate`, and `NSData` objects. All other object types will be interpreted as text values using the object's `description` method.

 @param sql The SELECT statement to be performed, with optional `?` placeholders.

 @param ... Optional parameters to bind to `?` placeholders in the SQL statement. These should be Objective-C objects (e.g. `NSString`, `NSNumber`, etc.), not fundamental C data types (e.g. `int`, `char *`, etc.).

 @return A `<FMResultSet>` for the result set upon success; `nil` upon failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
 
 @see FMResultSet
 @see [`FMResultSet next`](<[FMResultSet next]>)
 @see [`sqlite3_bind`](http://sqlite.org/c3ref/bind_blob.html)
 
 @note If you want to use this from Swift, please note that you must include `FMDatabaseVariadic.swift` in your project. Without that, you cannot use this method directly, and instead have to use methods such as `<executeQuery:withArgumentsInArray:>`.
 */

- (AWSFMResultSet *)executeQuery:(NSString*)sql, ...;

/** Execute select statement

 Executing queries returns an `<FMResultSet>` object if successful, and `nil` upon failure.  Like executing updates, there is a variant that accepts an `NSError **` parameter.  Otherwise you should use the `<lastErrorMessage>` and `<lastErrorMessage>` methods to determine why a query failed.
 
 In order to iterate through the results of your query, you use a `while()` loop.  You also need to "step" (via `<[FMResultSet next]>`) from one record to the other.
 
 @param format The SQL to be performed, with `printf`-style escape sequences.

 @param ... Optional parameters to bind to use in conjunction with the `printf`-style escape sequences in the SQL statement.

 @return A `<FMResultSet>` for the result set upon success; `nil` upon failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.

 @see executeQuery:
 @see FMResultSet
 @see [`FMResultSet next`](<[FMResultSet next]>)

 @note This method does not technically perform a traditional printf-style replacement. What this method actually does is replace the printf-style percent sequences with a SQLite `?` placeholder, and then bind values to that placeholder. Thus the following command
 
    [db executeQueryWithFormat:@"SELECT * FROM test WHERE name=%@", @"Gus"];
 
 is actually replacing the `%@` with `?` placeholder, and then performing something equivalent to `<executeQuery:>`
 
    [db executeQuery:@"SELECT * FROM test WHERE name=?", @"Gus"];
 
 There are two reasons why this distinction is important. First, the printf-style escape sequences can only be used where it is permissible to use a SQLite `?` placeholder. You can use it only for values in SQL statements, but not for table names or column names or any other non-value context. This method also cannot be used in conjunction with `pragma` statements and the like. Second, note the lack of quotation marks in the SQL. The `WHERE` clause was _not_ `WHERE name='%@'` (like you might have to do if you built a SQL statement using `NSString` method `stringWithFormat`), but rather simply `WHERE name=%@`.
 
 */

- (AWSFMResultSet *)executeQueryWithFormat:(NSString*)format, ... NS_FORMAT_FUNCTION(1,2);

/** Execute select statement

 Executing queries returns an `<FMResultSet>` object if successful, and `nil` upon failure.  Like executing updates, there is a variant that accepts an `NSError **` parameter.  Otherwise you should use the `<lastErrorMessage>` and `<lastErrorMessage>` methods to determine why a query failed.
 
 In order to iterate through the results of your query, you use a `while()` loop.  You also need to "step" (via `<[FMResultSet next]>`) from one record to the other.
 
 @param sql The SELECT statement to be performed, with optional `?` placeholders.

 @param arguments A `NSArray` of objects to be used when binding values to the `?` placeholders in the SQL statement.

 @return A `<FMResultSet>` for the result set upon success; `nil` upon failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.

 @see FMResultSet
 @see [`FMResultSet next`](<[FMResultSet next]>)
 */

- (AWSFMResultSet *)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray *)arguments;

/** Execute select statement

 Executing queries returns an `<FMResultSet>` object if successful, and `nil` upon failure.  Like executing updates, there is a variant that accepts an `NSError **` parameter.  Otherwise you should use the `<lastErrorMessage>` and `<lastErrorMessage>` methods to determine why a query failed.
 
 In order to iterate through the results of your query, you use a `while()` loop.  You also need to "step" (via `<[FMResultSet next]>`) from one record to the other.
 
 @param sql The SELECT statement to be performed, with optional `?` placeholders.

 @param arguments A `NSDictionary` of objects keyed by column names that will be used when binding values to the `?` placeholders in the SQL statement.

 @return A `<FMResultSet>` for the result set upon success; `nil` upon failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.

 @see FMResultSet
 @see [`FMResultSet next`](<[FMResultSet next]>)
 */

- (AWSFMResultSet *)executeQuery:(NSString *)sql withParameterDictionary:(NSDictionary *)arguments;


// Documentation forthcoming.
- (AWSFMResultSet *)executeQuery:(NSString*)sql withVAList: (va_list)args;

///-------------------
/// @name Transactions
///-------------------

/** Begin a transaction
 
 @return `YES` on success; `NO` on failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
 
 @see commit
 @see rollback
 @see beginDeferredTransaction
 @see inTransaction
 */

- (BOOL)beginTransaction;

/** Begin a deferred transaction
 
 @return `YES` on success; `NO` on failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
 
 @see commit
 @see rollback
 @see beginTransaction
 @see inTransaction
 */

- (BOOL)beginDeferredTransaction;

/** Commit a transaction

 Commit a transaction that was initiated with either `<beginTransaction>` or with `<beginDeferredTransaction>`.
 
 @return `YES` on success; `NO` on failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
 
 @see beginTransaction
 @see beginDeferredTransaction
 @see rollback
 @see inTransaction
 */

- (BOOL)commit;

/** Rollback a transaction

 Rollback a transaction that was initiated with either `<beginTransaction>` or with `<beginDeferredTransaction>`.

 @return `YES` on success; `NO` on failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
 
 @see beginTransaction
 @see beginDeferredTransaction
 @see commit
 @see inTransaction
 */

- (BOOL)rollback;

/** Identify whether currently in a transaction or not
 
 @return `YES` if currently within transaction; `NO` if not.
 
 @see beginTransaction
 @see beginDeferredTransaction
 @see commit
 @see rollback
 */

- (BOOL)inTransaction;


///----------------------------------------
/// @name Cached statements and result sets
///----------------------------------------

/** Clear cached statements */

- (void)clearCachedStatements;

/** Close all open result sets */

- (void)closeOpenResultSets;

/** Whether database has any open result sets
 
 @return `YES` if there are open result sets; `NO` if not.
 */

- (BOOL)hasOpenResultSets;

/** Return whether should cache statements or not
 
 @return `YES` if should cache statements; `NO` if not.
 */

- (BOOL)shouldCacheStatements;

/** Set whether should cache statements or not
 
 @param value `YES` if should cache statements; `NO` if not.
 */

- (void)setShouldCacheStatements:(BOOL)value;


///-------------------------
/// @name Encryption methods
///-------------------------

/** Set encryption key.
 
 @param key The key to be used.

 @return `YES` if success, `NO` on error.

 @see http://www.sqlite-encrypt.com/develop-guide.htm
 
 @warning You need to have purchased the sqlite encryption extensions for this method to work.
 */

- (BOOL)setKey:(NSString*)key;

/** Reset encryption key

 @param key The key to be used.

 @return `YES` if success, `NO` on error.

 @see http://www.sqlite-encrypt.com/develop-guide.htm

 @warning You need to have purchased the sqlite encryption extensions for this method to work.
 */

- (BOOL)rekey:(NSString*)key;

/** Set encryption key using `keyData`.
 
 @param keyData The `NSData` to be used.

 @return `YES` if success, `NO` on error.

 @see http://www.sqlite-encrypt.com/develop-guide.htm
 
 @warning You need to have purchased the sqlite encryption extensions for this method to work.
 */

- (BOOL)setKeyWithData:(NSData *)keyData;

/** Reset encryption key using `keyData`.

 @param keyData The `NSData` to be used.

 @return `YES` if success, `NO` on error.

 @see http://www.sqlite-encrypt.com/develop-guide.htm

 @warning You need to have purchased the sqlite encryption extensions for this method to work.
 */

- (BOOL)rekeyWithData:(NSData *)keyData;


///------------------------------
/// @name General inquiry methods
///------------------------------

/** The path of the database file
 
 @return path of database.
 
 */

- (NSString *)databasePath;

/** The underlying SQLite handle 
 
 @return The `sqlite3` pointer.
 
 */

- (void*)sqliteHandle;


///-----------------------------
/// @name Retrieving error codes
///-----------------------------

/** Last error message
 
 Returns the English-language text that describes the most recent failed SQLite API call associated with a database connection. If a prior API call failed but the most recent API call succeeded, this return value is undefined.

 @return `NSString` of the last error message.
 
 @see [sqlite3_errmsg()](http://sqlite.org/c3ref/errcode.html)
 @see lastErrorCode
 @see lastError
 
 */

- (NSString*)lastErrorMessage;

/** Last error code
 
 Returns the numeric result code or extended result code for the most recent failed SQLite API call associated with a database connection. If a prior API call failed but the most recent API call succeeded, this return value is undefined.

 @return Integer value of the last error code.

 @see [sqlite3_errcode()](http://sqlite.org/c3ref/errcode.html)
 @see lastErrorMessage
 @see lastError

 */

- (int)lastErrorCode;

/** Had error

 @return `YES` if there was an error, `NO` if no error.
 
 @see lastError
 @see lastErrorCode
 @see lastErrorMessage
 
 */

- (BOOL)hadError;

/** Last error

 @return `NSError` representing the last error.
 
 @see lastErrorCode
 @see lastErrorMessage
 
 */

- (NSError*)lastError;


// description forthcoming
- (void)setMaxBusyRetryTimeInterval:(NSTimeInterval)timeoutInSeconds;
- (NSTimeInterval)maxBusyRetryTimeInterval;


///------------------
/// @name Save points
///------------------

/** Start save point
 
 @param name Name of save point.
 
 @param outErr A `NSError` object to receive any error object (if any).
 
 @return `YES` on success; `NO` on failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
 
 @see releaseSavePointWithName:error:
 @see rollbackToSavePointWithName:error:
 */

- (BOOL)startSavePointWithName:(NSString*)name error:(NSError**)outErr;

/** Release save point

 @param name Name of save point.
 
 @param outErr A `NSError` object to receive any error object (if any).
 
 @return `YES` on success; `NO` on failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.

 @see startSavePointWithName:error:
 @see rollbackToSavePointWithName:error:
 
 */

- (BOOL)releaseSavePointWithName:(NSString*)name error:(NSError**)outErr;

/** Roll back to save point

 @param name Name of save point.
 @param outErr A `NSError` object to receive any error object (if any).
 
 @return `YES` on success; `NO` on failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
 
 @see startSavePointWithName:error:
 @see releaseSavePointWithName:error:
 
 */

- (BOOL)rollbackToSavePointWithName:(NSString*)name error:(NSError**)outErr;

/** Start save point

 @param block Block of code to perform from within save point.
 
 @return The NSError corresponding to the error, if any. If no error, returns `nil`.

 @see startSavePointWithName:error:
 @see releaseSavePointWithName:error:
 @see rollbackToSavePointWithName:error:
 
 */

- (NSError*)inSavePoint:(void (^)(BOOL *rollback))block;


///----------------------------
/// @name SQLite library status
///----------------------------

/** Test to see if the library is threadsafe

 @return `NO` if and only if SQLite was compiled with mutexing code omitted due to the SQLITE_THREADSAFE compile-time option being set to 0.

 @see [sqlite3_threadsafe()](http://sqlite.org/c3ref/threadsafe.html)
 */

+ (BOOL)isSQLiteThreadSafe;

/** Run-time library version numbers
 
 @return The sqlite library version string.
 
 @see [sqlite3_libversion()](http://sqlite.org/c3ref/libversion.html)
 */

+ (NSString*)sqliteLibVersion;


+ (NSString*)AWSFMDBUserVersion;

+ (SInt32)AWSFMDBVersion;


///------------------------
/// @name Make SQL function
///------------------------

/** Adds SQL functions or aggregates or to redefine the behavior of existing SQL functions or aggregates.
 
 For example:
 
    [queue inDatabase:^(FMDatabase *adb) {

        [adb executeUpdate:@"create table ftest (foo text)"];
        [adb executeUpdate:@"insert into ftest values ('hello')"];
        [adb executeUpdate:@"insert into ftest values ('hi')"];
        [adb executeUpdate:@"insert into ftest values ('not h!')"];
        [adb executeUpdate:@"insert into ftest values ('definitely not h!')"];

        [adb makeFunctionNamed:@"StringStartsWithH" maximumArguments:1 withBlock:^(sqlite3_context *context, int aargc, sqlite3_value **aargv) {
            if (sqlite3_value_type(aargv[0]) == SQLITE_TEXT) {
                @autoreleasepool {
                    const char *c = (const char *)sqlite3_value_text(aargv[0]);
                    NSString *s = [NSString stringWithUTF8String:c];
                    sqlite3_result_int(context, [s hasPrefix:@"h"]);
                }
            }
            else {
                NSLog(@"Unknown formart for StringStartsWithH (%d) %s:%d", sqlite3_value_type(aargv[0]), __FUNCTION__, __LINE__);
                sqlite3_result_null(context);
            }
        }];

        int rowCount = 0;
        FMResultSet *ars = [adb executeQuery:@"select * from ftest where StringStartsWithH(foo)"];
        while ([ars next]) {
            rowCount++;
            NSLog(@"Does %@ start with 'h'?", [rs stringForColumnIndex:0]);
        }
        AWSFMDBQuickCheck(rowCount == 2);
    }];

 @param name Name of function

 @param count Maximum number of parameters

 @param block The block of code for the function

 @see [sqlite3_create_function()](http://sqlite.org/c3ref/create_function.html)
 */

- (void)makeFunctionNamed:(NSString*)name maximumArguments:(int)count withBlock:(void (^)(void *context, int argc, void **argv))block;


///---------------------
/// @name Date formatter
///---------------------

/** Generate an `NSDateFormatter` that won't be broken by permutations of timezones or locales.
 
 Use this method to generate values to set the dateFormat property.
 
 Example:

    myDB.dateFormat = [FMDatabase storeableDateFormat:@"yyyy-MM-dd HH:mm:ss"];

 @param format A valid NSDateFormatter format string.
 
 @return A `NSDateFormatter` that can be used for converting dates to strings and vice versa.
 
 @see hasDateFormatter
 @see setDateFormat:
 @see dateFromString:
 @see stringFromDate:
 @see storeableDateFormat:

 @warning Note that `NSDateFormatter` is not thread-safe, so the formatter generated by this method should be assigned to only one AWSFMDB instance and should not be used for other purposes.

 */

+ (NSDateFormatter *)storeableDateFormat:(NSString *)format;

/** Test whether the database has a date formatter assigned.
 
 @return `YES` if there is a date formatter; `NO` if not.
 
 @see hasDateFormatter
 @see setDateFormat:
 @see dateFromString:
 @see stringFromDate:
 @see storeableDateFormat:
 */

- (BOOL)hasDateFormatter;

/** Set to a date formatter to use string dates with sqlite instead of the default UNIX timestamps.
 
 @param format Set to nil to use UNIX timestamps. Defaults to nil. Should be set using a formatter generated using FMDatabase::storeableDateFormat.
 
 @see hasDateFormatter
 @see setDateFormat:
 @see dateFromString:
 @see stringFromDate:
 @see storeableDateFormat:
 
 @warning Note there is no direct getter for the `NSDateFormatter`, and you should not use the formatter you pass to AWSFMDB for other purposes, as `NSDateFormatter` is not thread-safe.
 */

- (void)setDateFormat:(NSDateFormatter *)format;

/** Convert the supplied NSString to NSDate, using the current database formatter.
 
 @param s `NSString` to convert to `NSDate`.
 
 @return The `NSDate` object; or `nil` if no formatter is set.
 
 @see hasDateFormatter
 @see setDateFormat:
 @see dateFromString:
 @see stringFromDate:
 @see storeableDateFormat:
 */

- (NSDate *)dateFromString:(NSString *)s;

/** Convert the supplied NSDate to NSString, using the current database formatter.
 
 @param date `NSDate` of date to convert to `NSString`.

 @return The `NSString` representation of the date; `nil` if no formatter is set.
 
 @see hasDateFormatter
 @see setDateFormat:
 @see dateFromString:
 @see stringFromDate:
 @see storeableDateFormat:
 */

- (NSString *)stringFromDate:(NSDate *)date;

@end

Swift

class AWSFMDatabase : NSObject

Undocumented

  • Undocumented

    Declaration

    Objective-C

    NSString*           _databasePath
  • Undocumented

    Declaration

    Objective-C

    BOOL                _logsErrors
  • Undocumented

    Declaration

    Objective-C

    BOOL                _crashOnErrors
  • Undocumented

    Declaration

    Objective-C

    BOOL                _traceExecution
  • Undocumented

    Declaration

    Objective-C

    BOOL                _checkedOut
  • Undocumented

    Declaration

    Objective-C

    BOOL                _shouldCacheStatements
  • Undocumented

    Declaration

    Objective-C

    BOOL                _isExecutingStatement
  • Undocumented

    Declaration

    Objective-C

    BOOL                _inTransaction
  • Undocumented

    Declaration

    Objective-C

    NSTimeInterval      _maxBusyRetryTimeInterval
  • Undocumented

    Declaration

    Objective-C

    NSTimeInterval      _startBusyRetryTime
  • Undocumented

    Declaration

    Objective-C

    NSMutableDictionary *_cachedStatements
  • Undocumented

    Declaration

    Objective-C

    NSMutableSet        *_openResultSets
  • Undocumented

    Declaration

    Objective-C

    NSMutableSet        *_openFunctions
  • Undocumented

    Declaration

    Objective-C

    NSDateFormatter     *_dateFormat

Properties

  • Whether should trace execution

    Declaration

    Objective-C

    @property BOOL traceExecution;

    Swift

    var traceExecution: Bool { get set }
  • Whether checked out or not

    Declaration

    Objective-C

    @property BOOL checkedOut;

    Swift

    var checkedOut: Bool { get set }
  • Crash on errors

    Declaration

    Objective-C

    @property BOOL crashOnErrors;

    Swift

    var crashOnErrors: Bool { get set }
  • Logs errors

    Declaration

    Objective-C

    @property BOOL logsErrors;

    Swift

    var logsErrors: Bool { get set }
  • Dictionary of cached statements

    Declaration

    Objective-C

    @property (retain) NSMutableDictionary *cachedStatements;

    Swift

    var cachedStatements: NSMutableDictionary! { get set }

Initialization

  • Create a FMDatabase object.

    An FMDatabase is created with a path to a SQLite database file. This path can be one of these three:

    1. A file system path. The file does not have to exist on disk. If it does not exist, it is created for you.
    2. An empty string (@""). An empty database is created at a temporary location. This database is deleted with the FMDatabase connection is closed.
    3. nil. An in-memory database is created. This database will be destroyed with the FMDatabase connection is closed.

    For example, to create/open a database in your Mac OS X tmp folder:

    FMDatabase *db = [FMDatabase databaseWithPath:@"/tmp/tmp.db"];
    

    Or, in iOS, you might open a database in the app’s Documents directory:

    NSString *docsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    NSString *dbPath   = [docsPath stringByAppendingPathComponent:@"test.db"];
    FMDatabase *db     = [FMDatabase databaseWithPath:dbPath];
    

    (For more information on temporary and in-memory databases, read the sqlite documentation on the subject: http://www.sqlite.org/inmemorydb.html)

    Declaration

    Objective-C

    + (instancetype)databaseWithPath:(NSString *)inPath;

    Parameters

    inPath

    Path of database file

    Return Value

    FMDatabase object if successful; nil if failure.

  • Initialize a FMDatabase object.

    An FMDatabase is created with a path to a SQLite database file. This path can be one of these three:

    1. A file system path. The file does not have to exist on disk. If it does not exist, it is created for you.
    2. An empty string (@""). An empty database is created at a temporary location. This database is deleted with the FMDatabase connection is closed.
    3. nil. An in-memory database is created. This database will be destroyed with the FMDatabase connection is closed.

    For example, to create/open a database in your Mac OS X tmp folder:

    FMDatabase *db = [FMDatabase databaseWithPath:@"/tmp/tmp.db"];
    

    Or, in iOS, you might open a database in the app’s Documents directory:

    NSString *docsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    NSString *dbPath   = [docsPath stringByAppendingPathComponent:@"test.db"];
    FMDatabase *db     = [FMDatabase databaseWithPath:dbPath];
    

    (For more information on temporary and in-memory databases, read the sqlite documentation on the subject: http://www.sqlite.org/inmemorydb.html)

    Declaration

    Objective-C

    - (instancetype)initWithPath:(NSString *)inPath;

    Swift

    init!(path inPath: String!)

    Parameters

    inPath

    Path of database file

    Return Value

    FMDatabase object if successful; nil if failure.

Opening and closing database

  • Opening a new database connection

    The database is opened for reading and writing, and is created if it does not already exist.

    See

    openWithFlags:

    See

    close

    Declaration

    Objective-C

    - (BOOL)open;

    Swift

    func open() -> Bool

    Return Value

    YES if successful, NO on error.

  • Opening a new database connection with flags and an optional virtual file system (VFS)

    SQLITE_OPEN_READONLY

    The database is opened in read-only mode. If the database does not already exist, an error is returned.

    SQLITE_OPEN_READWRITE

    The database is opened for reading and writing if possible, or reading only if the file is write protected by the operating system. In either case the database must already exist, otherwise an error is returned.

    SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE

    The database is opened for reading and writing, and is created if it does not already exist. This is the behavior that is always used for open method.

    If vfs is given the value is passed to the vfs parameter of sqlite3_open_v2.

    See

    open

    See

    close

    Warning

    Requires SQLite 3.5

    Declaration

    Objective-C

    - (BOOL)openWithFlags:(int)flags;

    Swift

    func open(withFlags flags: Int32) -> Bool

    Parameters

    flags

    one of the following three values, optionally combined with the SQLITE_OPEN_NOMUTEX, SQLITE_OPEN_FULLMUTEX, SQLITE_OPEN_SHAREDCACHE, SQLITE_OPEN_PRIVATECACHE, and/or SQLITE_OPEN_URI flags:

    Return Value

    YES if successful, NO on error.

  • Undocumented

    Declaration

    Objective-C

    - (BOOL)openWithFlags:(int)flags vfs:(NSString *)vfsName;

    Swift

    func open(withFlags flags: Int32, vfs vfsName: String!) -> Bool
  • Closing a database connection

    See

    open

    See

    openWithFlags:

    Declaration

    Objective-C

    - (BOOL)close;

    Swift

    func close() -> Bool

    Return Value

    YES if success, NO on error.

  • Test to see if we have a good connection to the database.

    This will confirm whether:

    • is database open
    • if open, it will try a simple SELECT statement and confirm that it succeeds.

    Declaration

    Objective-C

    - (BOOL)goodConnection;

    Swift

    func goodConnection() -> Bool

    Return Value

    YES if everything succeeds, NO on failure.

Perform updates

  • Execute single update statement

    This method executes a single SQL update statement (i.e. any SQL that does not return results, such as UPDATE, INSERT, or DELETE. This method employs sqlite3_prepare_v2, sqlite3_bind to bind values to ? placeholders in the SQL with the optional list of parameters, and sqlite_step to perform the update.

    The optional values provided to this method should be objects (e.g. NSString, NSNumber, NSNull, NSDate, and NSData objects), not fundamental data types (e.g. int, long, NSInteger, etc.). This method automatically handles the aforementioned object types, and all other object types will be interpreted as text values using the object’s description method.

    See

    lastError

    See

    lastErrorCode

    See

    lastErrorMessage

    Declaration

    Objective-C

    - (BOOL)executeUpdate:(NSString *)sql
        withErrorAndBindings:(NSError **)outErr, ...;

    Parameters

    sql

    The SQL to be performed, with optional ? placeholders.

    outErr

    A reference to the NSError pointer to be updated with an auto released NSError object if an error if an error occurs. If nil, no NSError object will be returned.

    ...

    Optional parameters to bind to ? placeholders in the SQL statement. These should be Objective-C objects (e.g. NSString, NSNumber, etc.), not fundamental C data types (e.g. int, char *, etc.).

    Return Value

    YES upon success; NO upon failure. If failed, you can call <lastError>, <lastErrorCode>, or <lastErrorMessage> for diagnostic information regarding the failure.

  • Deprecated

    Execute single update statement

    See

    executeUpdate:withErrorAndBindings:

    Warning

    Deprecated: Please use <executeUpdate:withErrorAndBindings> instead.

    Declaration

    Objective-C

    - (BOOL)update:(NSString *)sql withErrorAndBindings:(NSError **)outErr, ...;
  • Execute single update statement

    This method executes a single SQL update statement (i.e. any SQL that does not return results, such as UPDATE, INSERT, or DELETE. This method employs sqlite3_prepare_v2, sqlite3_bind to bind values to ? placeholders in the SQL with the optional list of parameters, and sqlite_step to perform the update.

    The optional values provided to this method should be objects (e.g. NSString, NSNumber, NSNull, NSDate, and NSData objects), not fundamental data types (e.g. int, long, NSInteger, etc.). This method automatically handles the aforementioned object types, and all other object types will be interpreted as text values using the object’s description method.

    See

    lastError

    See

    lastErrorCode

    See

    lastErrorMessage

    Note

    This technique supports the use of ? placeholders in the SQL, automatically binding any supplied value parameters to those placeholders. This approach is more robust than techniques that entail using stringWithFormat to manually build SQL statements, which can be problematic if the values happened to include any characters that needed to be quoted.

    Note

    If you want to use this from Swift, please note that you must include FMDatabaseVariadic.swift in your project. Without that, you cannot use this method directly, and instead have to use methods such as <executeUpdate:withArgumentsInArray:>.

    Declaration

    Objective-C

    - (BOOL)executeUpdate:(NSString *)sql, ...;

    Parameters

    sql

    The SQL to be performed, with optional ? placeholders.

    ...

    Optional parameters to bind to ? placeholders in the SQL statement. These should be Objective-C objects (e.g. NSString, NSNumber, etc.), not fundamental C data types (e.g. int, char *, etc.).

    Return Value

    YES upon success; NO upon failure. If failed, you can call <lastError>, <lastErrorCode>, or <lastErrorMessage> for diagnostic information regarding the failure.

  • Execute single update statement

    This method executes a single SQL update statement (i.e. any SQL that does not return results, such as UPDATE, INSERT, or DELETE. This method employs sqlite3_prepare_v2 and sqlite_step to perform the update. Unlike the other executeUpdate methods, this uses printf-style formatters (e.g. %s, %d, etc.) to build the SQL. Do not use ? placeholders in the SQL if you use this method.

    See

    executeUpdate:

    See

    lastError

    See

    lastErrorCode

    See

    lastErrorMessage

    Note

    This method does not technically perform a traditional printf-style replacement. What this method actually does is replace the printf-style percent sequences with a SQLite ? placeholder, and then bind values to that placeholder. Thus the following command

    [db executeUpdateWithFormat:@“INSERT INTO test (name) VALUES (%@)”, @“Gus”];

    is actually replacing the %@ with ? placeholder, and then performing something equivalent to <executeUpdate:>

    [db executeUpdate:@"INSERT INTO test (name) VALUES (?)", @"Gus"];
    

    There are two reasons why this distinction is important. First, the printf-style escape sequences can only be used where it is permissible to use a SQLite ? placeholder. You can use it only for values in SQL statements, but not for table names or column names or any other non-value context. This method also cannot be used in conjunction with pragma statements and the like. Second, note the lack of quotation marks in the SQL. The VALUES clause was not VALUES ('%@') (like you might have to do if you built a SQL statement using NSString method stringWithFormat), but rather simply VALUES (%@).

    Declaration

    Objective-C

    - (BOOL)executeUpdateWithFormat:(NSString *)format, ...;

    Parameters

    format

    The SQL to be performed, with printf-style escape sequences.

    ...

    Optional parameters to bind to use in conjunction with the printf-style escape sequences in the SQL statement.

    Return Value

    YES upon success; NO upon failure. If failed, you can call <lastError>, <lastErrorCode>, or <lastErrorMessage> for diagnostic information regarding the failure.

  • Execute single update statement

    This method executes a single SQL update statement (i.e. any SQL that does not return results, such as UPDATE, INSERT, or DELETE. This method employs sqlite3_prepare_v2 and sqlite3_bind binding any ? placeholders in the SQL with the optional list of parameters.

    The optional values provided to this method should be objects (e.g. NSString, NSNumber, NSNull, NSDate, and NSData objects), not fundamental data types (e.g. int, long, NSInteger, etc.). This method automatically handles the aforementioned object types, and all other object types will be interpreted as text values using the object’s description method.

    See

    lastError

    See

    lastErrorCode

    See

    lastErrorMessage

    Declaration

    Objective-C

    - (BOOL)executeUpdate:(NSString *)sql withArgumentsInArray:(NSArray *)arguments;

    Swift

    func executeUpdate(_ sql: String!, withArgumentsIn arguments: [Any]!) -> Bool

    Parameters

    sql

    The SQL to be performed, with optional ? placeholders.

    arguments

    A NSArray of objects to be used when binding values to the ? placeholders in the SQL statement.

    Return Value

    YES upon success; NO upon failure. If failed, you can call <lastError>, <lastErrorCode>, or <lastErrorMessage> for diagnostic information regarding the failure.

  • Execute single update statement

    This method executes a single SQL update statement (i.e. any SQL that does not return results, such as UPDATE, INSERT, or DELETE. This method employs sqlite3_prepare_v2 and sqlite_step to perform the update. Unlike the other executeUpdate methods, this uses printf-style formatters (e.g. %s, %d, etc.) to build the SQL.

    The optional values provided to this method should be objects (e.g. NSString, NSNumber, NSNull, NSDate, and NSData objects), not fundamental data types (e.g. int, long, NSInteger, etc.). This method automatically handles the aforementioned object types, and all other object types will be interpreted as text values using the object’s description method.

    See

    lastError

    See

    lastErrorCode

    See

    lastErrorMessage

    Declaration

    Objective-C

    - (BOOL)executeUpdate:(NSString *)sql
        withParameterDictionary:(NSDictionary *)arguments;

    Swift

    func executeUpdate(_ sql: String!, withParameterDictionary arguments: [AnyHashable : Any]!) -> Bool

    Parameters

    sql

    The SQL to be performed, with optional ? placeholders.

    arguments

    A NSDictionary of objects keyed by column names that will be used when binding values to the ? placeholders in the SQL statement.

    Return Value

    YES upon success; NO upon failure. If failed, you can call <lastError>, <lastErrorCode>, or <lastErrorMessage> for diagnostic information regarding the failure.

  • Execute single update statement

    This method executes a single SQL update statement (i.e. any SQL that does not return results, such as UPDATE, INSERT, or DELETE. This method employs sqlite3_prepare_v2 and sqlite_step to perform the update. Unlike the other executeUpdate methods, this uses printf-style formatters (e.g. %s, %d, etc.) to build the SQL.

    The optional values provided to this method should be objects (e.g. NSString, NSNumber, NSNull, NSDate, and NSData objects), not fundamental data types (e.g. int, long, NSInteger, etc.). This method automatically handles the aforementioned object types, and all other object types will be interpreted as text values using the object’s description method.

    See

    lastError

    See

    lastErrorCode

    See

    lastErrorMessage

    Declaration

    Objective-C

    - (BOOL)executeUpdate:(NSString *)sql withVAList:(struct __va_list_tag *)args;

    Swift

    func executeUpdate(_ sql: String!, withVAList args: CVaListPointer) -> Bool

    Parameters

    sql

    The SQL to be performed, with optional ? placeholders.

    args

    A va_list of arguments.

    Return Value

    YES upon success; NO upon failure. If failed, you can call <lastError>, <lastErrorCode>, or <lastErrorMessage> for diagnostic information regarding the failure.

  • Execute multiple SQL statements

    This executes a series of SQL statements that are combined in a single string (e.g. the SQL generated by the sqlite3 command line .dump command). This accepts no value parameters, but rather simply expects a single string with multiple SQL statements, each terminated with a semicolon. This uses sqlite3_exec.

    See

    executeStatements:withResultBlock:

    Declaration

    Objective-C

    - (BOOL)executeStatements:(NSString *)sql;

    Swift

    func executeStatements(_ sql: String!) -> Bool

    Parameters

    sql

    The SQL to be performed

    Return Value

    YES upon success; NO upon failure. If failed, you can call <lastError>, <lastErrorCode>, or <lastErrorMessage> for diagnostic information regarding the failure.

  • Execute multiple SQL statements with callback handler

    This executes a series of SQL statements that are combined in a single string (e.g. the SQL generated by the sqlite3 command line .dump command). This accepts no value parameters, but rather simply expects a single string with multiple SQL statements, each terminated with a semicolon. This uses sqlite3_exec.

    See

    executeStatements:

    Declaration

    Objective-C

    - (BOOL)executeStatements:(NSString *)sql
              withResultBlock:(AWSFMDBExecuteStatementsCallbackBlock)block;

    Swift

    func executeStatements(_ sql: String!, withResultBlock block: AWSFMDBExecuteStatementsCallbackBlock!) -> Bool

    Parameters

    sql

    The SQL to be performed.

    block

    A block that will be called for any result sets returned by any SQL statements. Note, if you supply this block, it must return integer value, zero upon success (this would be a good opportunity to use SQLITE_OK), non-zero value upon failure (which will stop the bulk execution of the SQL). If a statement returns values, the block will be called with the results from the query in NSDictionary *resultsDictionary. This may be nil if you don’t care to receive any results.

    Return Value

    YES upon success; NO upon failure. If failed, you can call <lastError>, <lastErrorCode>, or <lastErrorMessage> for diagnostic information regarding the failure.

  • Last insert rowid

    Each entry in an SQLite table has a unique 64-bit signed integer key called the “rowid”. The rowid is always available as an undeclared column named ROWID, OID, or _ROWID_ as long as those names are not also used by explicitly declared columns. If the table has a column of type INTEGER PRIMARY KEY then that column is another alias for the rowid.

    This routine returns the rowid of the most recent successful INSERT into the database from the database connection in the first argument. As of SQLite version 3.7.7, this routines records the last insert rowid of both ordinary tables and virtual tables. If no successful INSERTs have ever occurred on that database connection, zero is returned.

    Declaration

    Objective-C

    - (long long)lastInsertRowId;

    Swift

    func lastInsertRowId() -> Int64

    Return Value

    The rowid of the last inserted row.

  • The number of rows changed by prior SQL statement.

    This function returns the number of database rows that were changed or inserted or deleted by the most recently completed SQL statement on the database connection specified by the first parameter. Only changes that are directly specified by the INSERT, UPDATE, or DELETE statement are counted.

    Declaration

    Objective-C

    - (int)changes;

    Swift

    func changes() -> Int32

    Return Value

    The number of rows changed by prior SQL statement.

Retrieving results

  • Execute select statement

    Executing queries returns an <FMResultSet> object if successful, and nil upon failure. Like executing updates, there is a variant that accepts an NSError ** parameter. Otherwise you should use the <lastErrorMessage> and <lastErrorMessage> methods to determine why a query failed.

    In order to iterate through the results of your query, you use a while() loop. You also need to “step” (via <[FMResultSet next]>) from one record to the other.

    This method employs sqlite3_bind for any optional value parameters. This properly escapes any characters that need escape sequences (e.g. quotation marks), which eliminates simple SQL errors as well as protects against SQL injection attacks. This method natively handles NSString, NSNumber, NSNull, NSDate, and NSData objects. All other object types will be interpreted as text values using the object’s description method.

    See

    FMResultSet

    Note

    If you want to use this from Swift, please note that you must include FMDatabaseVariadic.swift in your project. Without that, you cannot use this method directly, and instead have to use methods such as <executeQuery:withArgumentsInArray:>.

    Declaration

    Objective-C

    - (AWSFMResultSet *)executeQuery:(NSString *)sql, ...;

    Parameters

    sql

    The SELECT statement to be performed, with optional ? placeholders.

    ...

    Optional parameters to bind to ? placeholders in the SQL statement. These should be Objective-C objects (e.g. NSString, NSNumber, etc.), not fundamental C data types (e.g. int, char *, etc.).

    Return Value

    A <FMResultSet> for the result set upon success; nil upon failure. If failed, you can call <lastError>, <lastErrorCode>, or <lastErrorMessage> for diagnostic information regarding the failure.

  • Execute select statement

    Executing queries returns an <FMResultSet> object if successful, and nil upon failure. Like executing updates, there is a variant that accepts an NSError ** parameter. Otherwise you should use the <lastErrorMessage> and <lastErrorMessage> methods to determine why a query failed.

    In order to iterate through the results of your query, you use a while() loop. You also need to “step” (via <[FMResultSet next]>) from one record to the other.

    See

    executeQuery:

    See

    FMResultSet

    Note

    This method does not technically perform a traditional printf-style replacement. What this method actually does is replace the printf-style percent sequences with a SQLite ? placeholder, and then bind values to that placeholder. Thus the following command

    [db executeQueryWithFormat:@“SELECT * FROM test WHERE name=%@”, @“Gus”];

    is actually replacing the %@ with ? placeholder, and then performing something equivalent to <executeQuery:>

    [db executeQuery:@"SELECT * FROM test WHERE name=?", @"Gus"];
    

    There are two reasons why this distinction is important. First, the printf-style escape sequences can only be used where it is permissible to use a SQLite ? placeholder. You can use it only for values in SQL statements, but not for table names or column names or any other non-value context. This method also cannot be used in conjunction with pragma statements and the like. Second, note the lack of quotation marks in the SQL. The WHERE clause was not WHERE name='%@' (like you might have to do if you built a SQL statement using NSString method stringWithFormat), but rather simply WHERE name=%@.

    Declaration

    Objective-C

    - (AWSFMResultSet *)executeQueryWithFormat:(NSString *)format, ...;

    Parameters

    format

    The SQL to be performed, with printf-style escape sequences.

    ...

    Optional parameters to bind to use in conjunction with the printf-style escape sequences in the SQL statement.

    Return Value

    A <FMResultSet> for the result set upon success; nil upon failure. If failed, you can call <lastError>, <lastErrorCode>, or <lastErrorMessage> for diagnostic information regarding the failure.

  • Execute select statement

    Executing queries returns an <FMResultSet> object if successful, and nil upon failure. Like executing updates, there is a variant that accepts an NSError ** parameter. Otherwise you should use the <lastErrorMessage> and <lastErrorMessage> methods to determine why a query failed.

    In order to iterate through the results of your query, you use a while() loop. You also need to “step” (via <[FMResultSet next]>) from one record to the other.

    See

    FMResultSet

    Declaration

    Objective-C

    - (AWSFMResultSet *)executeQuery:(NSString *)sql
                withArgumentsInArray:(NSArray *)arguments;

    Swift

    func executeQuery(_ sql: String!, withArgumentsIn arguments: [Any]!) -> AWSFMResultSet!

    Parameters

    sql

    The SELECT statement to be performed, with optional ? placeholders.

    arguments

    A NSArray of objects to be used when binding values to the ? placeholders in the SQL statement.

    Return Value

    A <FMResultSet> for the result set upon success; nil upon failure. If failed, you can call <lastError>, <lastErrorCode>, or <lastErrorMessage> for diagnostic information regarding the failure.

  • Execute select statement

    Executing queries returns an <FMResultSet> object if successful, and nil upon failure. Like executing updates, there is a variant that accepts an NSError ** parameter. Otherwise you should use the <lastErrorMessage> and <lastErrorMessage> methods to determine why a query failed.

    In order to iterate through the results of your query, you use a while() loop. You also need to “step” (via <[FMResultSet next]>) from one record to the other.

    See

    FMResultSet

    Declaration

    Objective-C

    - (AWSFMResultSet *)executeQuery:(NSString *)sql
             withParameterDictionary:(NSDictionary *)arguments;

    Swift

    func executeQuery(_ sql: String!, withParameterDictionary arguments: [AnyHashable : Any]!) -> AWSFMResultSet!

    Parameters

    sql

    The SELECT statement to be performed, with optional ? placeholders.

    arguments

    A NSDictionary of objects keyed by column names that will be used when binding values to the ? placeholders in the SQL statement.

    Return Value

    A <FMResultSet> for the result set upon success; nil upon failure. If failed, you can call <lastError>, <lastErrorCode>, or <lastErrorMessage> for diagnostic information regarding the failure.

  • Undocumented

    Declaration

    Objective-C

    - (AWSFMResultSet *)executeQuery:(NSString*)sql withVAList: (va_list)args;

    Swift

    func executeQuery(_ sql: String!, withVAList args: CVaListPointer) -> AWSFMResultSet!

Transactions

  • Begin a transaction

    See

    commit

    See

    rollback

    See

    beginDeferredTransaction

    See

    inTransaction

    Declaration

    Objective-C

    - (BOOL)beginTransaction;

    Swift

    func beginTransaction() -> Bool

    Return Value

    YES on success; NO on failure. If failed, you can call <lastError>, <lastErrorCode>, or <lastErrorMessage> for diagnostic information regarding the failure.

  • Begin a deferred transaction

    See

    commit

    See

    rollback

    See

    beginTransaction

    See

    inTransaction

    Declaration

    Objective-C

    - (BOOL)beginDeferredTransaction;

    Swift

    func beginDeferredTransaction() -> Bool

    Return Value

    YES on success; NO on failure. If failed, you can call <lastError>, <lastErrorCode>, or <lastErrorMessage> for diagnostic information regarding the failure.

  • Commit a transaction

    Commit a transaction that was initiated with either <beginTransaction> or with <beginDeferredTransaction>.

    See

    beginTransaction

    See

    beginDeferredTransaction

    See

    rollback

    See

    inTransaction

    Declaration

    Objective-C

    - (BOOL)commit;

    Swift

    func commit() -> Bool

    Return Value

    YES on success; NO on failure. If failed, you can call <lastError>, <lastErrorCode>, or <lastErrorMessage> for diagnostic information regarding the failure.

  • Rollback a transaction

    Rollback a transaction that was initiated with either <beginTransaction> or with <beginDeferredTransaction>.

    See

    beginTransaction

    See

    beginDeferredTransaction

    See

    commit

    See

    inTransaction

    Declaration

    Objective-C

    - (BOOL)rollback;

    Swift

    func rollback() -> Bool

    Return Value

    YES on success; NO on failure. If failed, you can call <lastError>, <lastErrorCode>, or <lastErrorMessage> for diagnostic information regarding the failure.

  • Identify whether currently in a transaction or not

    See

    beginTransaction

    See

    beginDeferredTransaction

    See

    commit

    See

    rollback

    Declaration

    Objective-C

    - (BOOL)inTransaction;

    Swift

    func inTransaction() -> Bool

    Return Value

    YES if currently within transaction; NO if not.

Cached statements and result sets

  • Clear cached statements

    Declaration

    Objective-C

    - (void)clearCachedStatements;

    Swift

    func clearCachedStatements()
  • Close all open result sets

    Declaration

    Objective-C

    - (void)closeOpenResultSets;

    Swift

    func closeOpenResultSets()
  • Whether database has any open result sets

    Declaration

    Objective-C

    - (BOOL)hasOpenResultSets;

    Swift

    func hasOpenResultSets() -> Bool

    Return Value

    YES if there are open result sets; NO if not.

  • Return whether should cache statements or not

    Declaration

    Objective-C

    - (BOOL)shouldCacheStatements;

    Swift

    func shouldCacheStatements() -> Bool

    Return Value

    YES if should cache statements; NO if not.

  • Set whether should cache statements or not

    Declaration

    Objective-C

    - (void)setShouldCacheStatements:(BOOL)value;

    Swift

    func setShouldCacheStatements(_ value: Bool)

    Parameters

    value

    YES if should cache statements; NO if not.

Encryption methods

  • Set encryption key.

    Warning

    You need to have purchased the sqlite encryption extensions for this method to work.

    Declaration

    Objective-C

    - (BOOL)setKey:(NSString *)key;

    Swift

    func setKey(_ key: String!) -> Bool

    Parameters

    key

    The key to be used.

    Return Value

    YES if success, NO on error.

  • Reset encryption key

    Warning

    You need to have purchased the sqlite encryption extensions for this method to work.

    Declaration

    Objective-C

    - (BOOL)rekey:(NSString *)key;

    Swift

    func rekey(_ key: String!) -> Bool

    Parameters

    key

    The key to be used.

    Return Value

    YES if success, NO on error.

  • Set encryption key using keyData.

    Warning

    You need to have purchased the sqlite encryption extensions for this method to work.

    Declaration

    Objective-C

    - (BOOL)setKeyWithData:(NSData *)keyData;

    Swift

    func setKeyWith(_ keyData: Data!) -> Bool

    Parameters

    keyData

    The NSData to be used.

    Return Value

    YES if success, NO on error.

  • Reset encryption key using keyData.

    Warning

    You need to have purchased the sqlite encryption extensions for this method to work.

    Declaration

    Objective-C

    - (BOOL)rekeyWithData:(NSData *)keyData;

    Swift

    func rekey(with keyData: Data!) -> Bool

    Parameters

    keyData

    The NSData to be used.

    Return Value

    YES if success, NO on error.

General inquiry methods

  • The path of the database file

    Declaration

    Objective-C

    - (NSString *)databasePath;

    Swift

    func databasePath() -> String!

    Return Value

    path of database.

  • The underlying SQLite handle

    Declaration

    Objective-C

    - (void *)sqliteHandle;

    Swift

    func sqliteHandle() -> UnsafeMutableRawPointer!

    Return Value

    The sqlite3 pointer.

Retrieving error codes

  • Last error message

    Returns the English-language text that describes the most recent failed SQLite API call associated with a database connection. If a prior API call failed but the most recent API call succeeded, this return value is undefined.

    See

    lastErrorCode

    See

    lastError

    Declaration

    Objective-C

    - (NSString *)lastErrorMessage;

    Swift

    func lastErrorMessage() -> String!

    Return Value

    NSString of the last error message.

  • Last error code

    Returns the numeric result code or extended result code for the most recent failed SQLite API call associated with a database connection. If a prior API call failed but the most recent API call succeeded, this return value is undefined.

    See

    lastErrorMessage

    See

    lastError

    Declaration

    Objective-C

    - (int)lastErrorCode;

    Swift

    func lastErrorCode() -> Int32

    Return Value

    Integer value of the last error code.

  • Had error

    See

    lastError

    See

    lastErrorCode

    See

    lastErrorMessage

    Declaration

    Objective-C

    - (BOOL)hadError;

    Swift

    func hadError() -> Bool

    Return Value

    YES if there was an error, NO if no error.

  • Last error

    See

    lastErrorCode

    See

    lastErrorMessage

    Declaration

    Objective-C

    - (NSError *)lastError;

    Swift

    func lastError() -> Error!

    Return Value

    NSError representing the last error.

  • Undocumented

    Declaration

    Objective-C

    - (void)setMaxBusyRetryTimeInterval:(NSTimeInterval)timeoutInSeconds;

    Swift

    func setMaxBusyRetryTimeInterval(_ timeoutInSeconds: TimeInterval)
  • Undocumented

    Declaration

    Objective-C

    - (NSTimeInterval)maxBusyRetryTimeInterval;

    Swift

    func maxBusyRetryTimeInterval() -> TimeInterval

Save points

  • Start save point

    See

    releaseSavePointWithName:error:

    See

    rollbackToSavePointWithName:error:

    Declaration

    Objective-C

    - (BOOL)startSavePointWithName:(NSString *)name error:(NSError **)outErr;

    Swift

    func startSavePoint(withName name: String!) throws

    Parameters

    name

    Name of save point.

    outErr

    A NSError object to receive any error object (if any).

    Return Value

    YES on success; NO on failure. If failed, you can call <lastError>, <lastErrorCode>, or <lastErrorMessage> for diagnostic information regarding the failure.

  • Release save point

    See

    startSavePointWithName:error:

    See

    rollbackToSavePointWithName:error:

    Declaration

    Objective-C

    - (BOOL)releaseSavePointWithName:(NSString *)name error:(NSError **)outErr;

    Swift

    func releaseSavePoint(withName name: String!) throws

    Parameters

    name

    Name of save point.

    outErr

    A NSError object to receive any error object (if any).

    Return Value

    YES on success; NO on failure. If failed, you can call <lastError>, <lastErrorCode>, or <lastErrorMessage> for diagnostic information regarding the failure.

  • Roll back to save point

    See

    startSavePointWithName:error:

    See

    releaseSavePointWithName:error:

    Declaration

    Objective-C

    - (BOOL)rollbackToSavePointWithName:(NSString *)name error:(NSError **)outErr;

    Swift

    func rollbackToSavePoint(withName name: String!) throws

    Parameters

    name

    Name of save point.

    outErr

    A NSError object to receive any error object (if any).

    Return Value

    YES on success; NO on failure. If failed, you can call <lastError>, <lastErrorCode>, or <lastErrorMessage> for diagnostic information regarding the failure.

  • Start save point

    See

    startSavePointWithName:error:

    See

    releaseSavePointWithName:error:

    See

    rollbackToSavePointWithName:error:

    Declaration

    Objective-C

    - (NSError *)inSavePoint:(void (^)(BOOL *))block;

    Swift

    func inSavePoint(_ block: ((UnsafeMutablePointer<ObjCBool>?) -> Void)!) -> Error!

    Parameters

    block

    Block of code to perform from within save point.

    Return Value

    The NSError corresponding to the error, if any. If no error, returns nil.

SQLite library status

  • Test to see if the library is threadsafe

    Declaration

    Objective-C

    + (BOOL)isSQLiteThreadSafe;

    Swift

    class func isSQLiteThreadSafe() -> Bool

    Return Value

    NO if and only if SQLite was compiled with mutexing code omitted due to the SQLITE_THREADSAFE compile-time option being set to 0.

  • Run-time library version numbers

    Declaration

    Objective-C

    + (NSString *)sqliteLibVersion;

    Swift

    class func sqliteLibVersion() -> String!

    Return Value

    The sqlite library version string.

  • Undocumented

    Declaration

    Objective-C

    + (NSString*)AWSFMDBUserVersion;

    Swift

    class func awsfmdbUserVersion() -> String!
  • Undocumented

    Declaration

    Objective-C

    + (SInt32)AWSFMDBVersion;

    Swift

    class func awsfmdbVersion() -> Int32

Make SQL function

  • Adds SQL functions or aggregates or to redefine the behavior of existing SQL functions or aggregates.

    For example:

    [queue inDatabase:^(FMDatabase *adb) {
    
        [adb executeUpdate:@"create table ftest (foo text)"];
        [adb executeUpdate:@"insert into ftest values ('hello')"];
        [adb executeUpdate:@"insert into ftest values ('hi')"];
        [adb executeUpdate:@"insert into ftest values ('not h!')"];
        [adb executeUpdate:@"insert into ftest values ('definitely not h!')"];
    
        [adb makeFunctionNamed:@"StringStartsWithH" maximumArguments:1 withBlock:^(sqlite3_context *context, int aargc, sqlite3_value **aargv) {
            if (sqlite3_value_type(aargv[0]) == SQLITE_TEXT) {
                @autoreleasepool {
                    const char *c = (const char *)sqlite3_value_text(aargv[0]);
                    NSString *s = [NSString stringWithUTF8String:c];
                    sqlite3_result_int(context, [s hasPrefix:@"h"]);
                }
            }
            else {
                NSLog(@"Unknown formart for StringStartsWithH (%d) %s:%d", sqlite3_value_type(aargv[0]), __FUNCTION__, __LINE__);
                sqlite3_result_null(context);
            }
        }];
    
        int rowCount = 0;
        FMResultSet *ars = [adb executeQuery:@"select * from ftest where StringStartsWithH(foo)"];
        while ([ars next]) {
            rowCount++;
            NSLog(@"Does %@ start with 'h'?", [rs stringForColumnIndex:0]);
        }
        AWSFMDBQuickCheck(rowCount == 2);
    }];
    

    Declaration

    Objective-C

    - (void)makeFunctionNamed:(NSString *)name
             maximumArguments:(int)count
                    withBlock:(void (^)(void *, int, void **))block;

    Swift

    func makeFunctionNamed(_ name: String!, maximumArguments count: Int32, with block: ((UnsafeMutableRawPointer?, Int32, UnsafeMutablePointer<UnsafeMutableRawPointer?>?) -> Void)!)

    Parameters

    name

    Name of function

    count

    Maximum number of parameters

    block

    The block of code for the function

Date formatter

  • Generate an NSDateFormatter that won’t be broken by permutations of timezones or locales.

    Use this method to generate values to set the dateFormat property.

    Example:

    myDB.dateFormat = [FMDatabase storeableDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    

    See

    hasDateFormatter

    See

    setDateFormat:

    See

    dateFromString:

    See

    stringFromDate:

    See

    storeableDateFormat:

    Warning

    Note that NSDateFormatter is not thread-safe, so the formatter generated by this method should be assigned to only one AWSFMDB instance and should not be used for other purposes.

    Declaration

    Objective-C

    + (NSDateFormatter *)storeableDateFormat:(NSString *)format;

    Swift

    class func storeableDateFormat(_ format: String!) -> DateFormatter!

    Parameters

    format

    A valid NSDateFormatter format string.

    Return Value

    A NSDateFormatter that can be used for converting dates to strings and vice versa.

  • Test whether the database has a date formatter assigned.

    See

    hasDateFormatter

    See

    setDateFormat:

    See

    dateFromString:

    See

    stringFromDate:

    See

    storeableDateFormat:

    Declaration

    Objective-C

    - (BOOL)hasDateFormatter;

    Swift

    func hasDateFormatter() -> Bool

    Return Value

    YES if there is a date formatter; NO if not.

  • Set to a date formatter to use string dates with sqlite instead of the default UNIX timestamps.

    See

    hasDateFormatter

    See

    setDateFormat:

    See

    dateFromString:

    See

    stringFromDate:

    See

    storeableDateFormat:

    Warning

    Note there is no direct getter for the NSDateFormatter, and you should not use the formatter you pass to AWSFMDB for other purposes, as NSDateFormatter is not thread-safe.

    Declaration

    Objective-C

    - (void)setDateFormat:(NSDateFormatter *)format;

    Swift

    func setDateFormat(_ format: DateFormatter!)

    Parameters

    format

    Set to nil to use UNIX timestamps. Defaults to nil. Should be set using a formatter generated using FMDatabase::storeableDateFormat.

  • Convert the supplied NSString to NSDate, using the current database formatter.

    See

    hasDateFormatter

    See

    setDateFormat:

    See

    dateFromString:

    See

    stringFromDate:

    See

    storeableDateFormat:

    Declaration

    Objective-C

    - (NSDate *)dateFromString:(NSString *)s;

    Swift

    func date(from s: String!) -> Date!

    Parameters

    s

    NSString to convert to NSDate.

    Return Value

    The NSDate object; or nil if no formatter is set.

  • Convert the supplied NSDate to NSString, using the current database formatter.

    See

    hasDateFormatter

    See

    setDateFormat:

    See

    dateFromString:

    See

    stringFromDate:

    See

    storeableDateFormat:

    Declaration

    Objective-C

    - (NSString *)stringFromDate:(NSDate *)date;

    Swift

    func string(from date: Date!) -> String!

    Parameters

    date

    NSDate of date to convert to NSString.

    Return Value

    The NSString representation of the date; nil if no formatter is set.

Return results of SQL to variable

  • Return int value for query

    Note

    To use this method from Swift, you must include FMDatabaseAdditionsVariadic.swift in your project.

    Declaration

    Objective-C

    - (int)intForQuery:(NSString *)query, ...;

    Parameters

    query

    The SQL query to be performed.

    ...

    A list of parameters that will be bound to the ? placeholders in the SQL query.

    Return Value

    int value.

  • Return long value for query

    Note

    To use this method from Swift, you must include FMDatabaseAdditionsVariadic.swift in your project.

    Declaration

    Objective-C

    - (long)longForQuery:(NSString *)query, ...;

    Parameters

    query

    The SQL query to be performed.

    ...

    A list of parameters that will be bound to the ? placeholders in the SQL query.

    Return Value

    long value.

  • Return BOOL value for query

    Note

    To use this method from Swift, you must include FMDatabaseAdditionsVariadic.swift in your project.

    Declaration

    Objective-C

    - (BOOL)boolForQuery:(NSString *)query, ...;

    Parameters

    query

    The SQL query to be performed.

    ...

    A list of parameters that will be bound to the ? placeholders in the SQL query.

    Return Value

    BOOL value.

  • Return double value for query

    Note

    To use this method from Swift, you must include FMDatabaseAdditionsVariadic.swift in your project.

    Declaration

    Objective-C

    - (double)doubleForQuery:(NSString *)query, ...;

    Parameters

    query

    The SQL query to be performed.

    ...

    A list of parameters that will be bound to the ? placeholders in the SQL query.

    Return Value

    double value.

  • Return NSString value for query

    Note

    To use this method from Swift, you must include FMDatabaseAdditionsVariadic.swift in your project.

    Declaration

    Objective-C

    - (NSString *)stringForQuery:(NSString *)query, ...;

    Parameters

    query

    The SQL query to be performed.

    ...

    A list of parameters that will be bound to the ? placeholders in the SQL query.

    Return Value

    NSString value.

  • Return NSData value for query

    Note

    To use this method from Swift, you must include FMDatabaseAdditionsVariadic.swift in your project.

    Declaration

    Objective-C

    - (NSData *)dataForQuery:(NSString *)query, ...;

    Parameters

    query

    The SQL query to be performed.

    ...

    A list of parameters that will be bound to the ? placeholders in the SQL query.

    Return Value

    NSData value.

  • Return NSDate value for query

    Note

    To use this method from Swift, you must include FMDatabaseAdditionsVariadic.swift in your project.

    Declaration

    Objective-C

    - (NSDate *)dateForQuery:(NSString *)query, ...;

    Parameters

    query

    The SQL query to be performed.

    ...

    A list of parameters that will be bound to the ? placeholders in the SQL query.

    Return Value

    NSDate value.

Schema related operations

  • Does table exist in database?

    Declaration

    Objective-C

    - (BOOL)tableExists:(NSString *)tableName;

    Swift

    func tableExists(_ tableName: String!) -> Bool

    Parameters

    tableName

    The name of the table being looked for.

    Return Value

    YES if table found; NO if not found.

  • 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

    Declaration

    Objective-C

    - (AWSFMResultSet *)getSchema;

    Swift

    func getSchema() -> AWSFMResultSet!

    Return Value

    FMResultSet of schema; nil on error.

  • 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

    Declaration

    Objective-C

    - (AWSFMResultSet *)getTableSchema:(NSString *)tableName;

    Swift

    func getTableSchema(_ tableName: String!) -> AWSFMResultSet!

    Parameters

    tableName

    The name of the table for whom the schema will be returned.

    Return Value

    FMResultSet of schema; nil on error.

  • Test to see if particular column exists for particular table in database

    Declaration

    Objective-C

    - (BOOL)columnExists:(NSString *)columnName
         inTableWithName:(NSString *)tableName;

    Swift

    func columnExists(_ columnName: String!, inTableWithName tableName: String!) -> Bool

    Parameters

    columnName

    The name of the column.

    tableName

    The name of the table.

    Return Value

    YES if column exists in table in question; NO otherwise.

  • Deprecated

    Test to see if particular column exists for particular table in database

    See

    columnExists:inTableWithName:

    Warning

    Deprecated - use <columnExists:inTableWithName:> instead.

    Declaration

    Objective-C

    - (BOOL)columnExists:(NSString *)tableName columnName:(NSString *)columnName;

    Swift

    func columnExists(_ tableName: String!, columnName: String!) -> Bool

    Parameters

    columnName

    The name of the column.

    tableName

    The name of the table.

    Return Value

    YES if column exists in table in question; NO otherwise.

  • Validate SQL statement

    This validates SQL statement by performing sqlite3_prepare_v2, but not returning the results, but instead immediately calling sqlite3_finalize.

    Declaration

    Objective-C

    - (BOOL)validateSQL:(NSString *)sql error:(NSError **)error;

    Swift

    func validateSQL(_ sql: String!) throws

    Parameters

    sql

    The SQL statement being validated.

    error

    This is a pointer to a NSError object that will receive the autoreleased NSError object if there was any error. If this is nil, no NSError result will be returned.

    Return Value

    YES if validation succeeded without incident; NO otherwise.

Application identifier tasks

  • Retrieve application ID

    See

    setApplicationID:

    Declaration

    Objective-C

    - (uint32_t)applicationID;

    Swift

    func applicationID() -> UInt32

    Return Value

    The uint32_t numeric value of the application ID.

  • Set the application ID

    See

    applicationID

    Declaration

    Objective-C

    - (void)setApplicationID:(uint32_t)appID;

    Swift

    func setApplicationID(_ appID: UInt32)

    Parameters

    appID

    The uint32_t numeric value of the application ID.

user version identifier tasks

  • Retrieve user version

    See

    setUserVersion:

    Declaration

    Objective-C

    - (uint32_t)userVersion;

    Swift

    func userVersion() -> UInt32

    Return Value

    The uint32_t numeric value of the user version.

  • Set the user-version

    See

    userVersion

    Declaration

    Objective-C

    - (void)setUserVersion:(uint32_t)version;

    Swift

    func setUserVersion(_ version: UInt32)

    Parameters

    version

    The uint32_t numeric value of the user version.