No Description

AWSFMDatabase.h 41KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080
  1. #import <Foundation/Foundation.h>
  2. #import "AWSFMResultSet.h"
  3. #import "AWSFMDatabasePool.h"
  4. #if ! __has_feature(objc_arc)
  5. #define AWSFMDBAutorelease(__v) ([__v autorelease]);
  6. #define AWSFMDBReturnAutoreleased AWSFMDBAutorelease
  7. #define AWSFMDBRetain(__v) ([__v retain]);
  8. #define AWSFMDBReturnRetained AWSFMDBRetain
  9. #define AWSFMDBRelease(__v) ([__v release]);
  10. #define AWSFMDBDispatchQueueRelease(__v) (dispatch_release(__v));
  11. #else
  12. // -fobjc-arc
  13. #define AWSFMDBAutorelease(__v)
  14. #define AWSFMDBReturnAutoreleased(__v) (__v)
  15. #define AWSFMDBRetain(__v)
  16. #define AWSFMDBReturnRetained(__v) (__v)
  17. #define AWSFMDBRelease(__v)
  18. // If OS_OBJECT_USE_OBJC=1, then the dispatch objects will be treated like ObjC objects
  19. // and will participate in ARC.
  20. // See the section on "Dispatch Queues and Automatic Reference Counting" in "Grand Central Dispatch (GCD) Reference" for details.
  21. #if OS_OBJECT_USE_OBJC
  22. #define AWSFMDBDispatchQueueRelease(__v)
  23. #else
  24. #define AWSFMDBDispatchQueueRelease(__v) (dispatch_release(__v));
  25. #endif
  26. #endif
  27. #if !__has_feature(objc_instancetype)
  28. #define instancetype id
  29. #endif
  30. typedef int(^AWSFMDBExecuteStatementsCallbackBlock)(NSDictionary *resultsDictionary);
  31. /** A SQLite ([http://sqlite.org/](http://sqlite.org/)) Objective-C wrapper.
  32. ### Usage
  33. The three main classes in AWSFMDB are:
  34. - `FMDatabase` - Represents a single SQLite database. Used for executing SQL statements.
  35. - `<FMResultSet>` - Represents the results of executing a query on an `FMDatabase`.
  36. - `<FMDatabaseQueue>` - If you want to perform queries and updates on multiple threads, you'll want to use this class.
  37. ### See also
  38. - `<FMDatabasePool>` - A pool of `FMDatabase` objects.
  39. - `<FMStatement>` - A wrapper for `sqlite_stmt`.
  40. ### External links
  41. - [AWSFMDB on GitHub](https://github.com/ccgus/fmdb) including introductory documentation
  42. - [SQLite web site](http://sqlite.org/)
  43. - [AWSFMDB mailing list](http://groups.google.com/group/fmdb)
  44. - [SQLite FAQ](http://www.sqlite.org/faq.html)
  45. @warning Do not instantiate a single `FMDatabase` object and use it across multiple threads. Instead, use `<FMDatabaseQueue>`.
  46. */
  47. #pragma clang diagnostic push
  48. #pragma clang diagnostic ignored "-Wobjc-interface-ivars"
  49. @interface AWSFMDatabase : NSObject {
  50. NSString* _databasePath;
  51. BOOL _logsErrors;
  52. BOOL _crashOnErrors;
  53. BOOL _traceExecution;
  54. BOOL _checkedOut;
  55. BOOL _shouldCacheStatements;
  56. BOOL _isExecutingStatement;
  57. BOOL _inTransaction;
  58. NSTimeInterval _maxBusyRetryTimeInterval;
  59. NSTimeInterval _startBusyRetryTime;
  60. NSMutableDictionary *_cachedStatements;
  61. NSMutableSet *_openResultSets;
  62. NSMutableSet *_openFunctions;
  63. NSDateFormatter *_dateFormat;
  64. }
  65. ///-----------------
  66. /// @name Properties
  67. ///-----------------
  68. /** Whether should trace execution */
  69. @property (atomic, assign) BOOL traceExecution;
  70. /** Whether checked out or not */
  71. @property (atomic, assign) BOOL checkedOut;
  72. /** Crash on errors */
  73. @property (atomic, assign) BOOL crashOnErrors;
  74. /** Logs errors */
  75. @property (atomic, assign) BOOL logsErrors;
  76. /** Dictionary of cached statements */
  77. @property (atomic, retain) NSMutableDictionary *cachedStatements;
  78. ///---------------------
  79. /// @name Initialization
  80. ///---------------------
  81. /** Create a `FMDatabase` object.
  82. An `FMDatabase` is created with a path to a SQLite database file. This path can be one of these three:
  83. 1. A file system path. The file does not have to exist on disk. If it does not exist, it is created for you.
  84. 2. An empty string (`@""`). An empty database is created at a temporary location. This database is deleted with the `FMDatabase` connection is closed.
  85. 3. `nil`. An in-memory database is created. This database will be destroyed with the `FMDatabase` connection is closed.
  86. For example, to create/open a database in your Mac OS X `tmp` folder:
  87. FMDatabase *db = [FMDatabase databaseWithPath:@"/tmp/tmp.db"];
  88. Or, in iOS, you might open a database in the app's `Documents` directory:
  89. NSString *docsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
  90. NSString *dbPath = [docsPath stringByAppendingPathComponent:@"test.db"];
  91. FMDatabase *db = [FMDatabase databaseWithPath:dbPath];
  92. (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))
  93. @param inPath Path of database file
  94. @return `FMDatabase` object if successful; `nil` if failure.
  95. */
  96. + (instancetype)databaseWithPath:(NSString*)inPath;
  97. /** Initialize a `FMDatabase` object.
  98. An `FMDatabase` is created with a path to a SQLite database file. This path can be one of these three:
  99. 1. A file system path. The file does not have to exist on disk. If it does not exist, it is created for you.
  100. 2. An empty string (`@""`). An empty database is created at a temporary location. This database is deleted with the `FMDatabase` connection is closed.
  101. 3. `nil`. An in-memory database is created. This database will be destroyed with the `FMDatabase` connection is closed.
  102. For example, to create/open a database in your Mac OS X `tmp` folder:
  103. FMDatabase *db = [FMDatabase databaseWithPath:@"/tmp/tmp.db"];
  104. Or, in iOS, you might open a database in the app's `Documents` directory:
  105. NSString *docsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
  106. NSString *dbPath = [docsPath stringByAppendingPathComponent:@"test.db"];
  107. FMDatabase *db = [FMDatabase databaseWithPath:dbPath];
  108. (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))
  109. @param inPath Path of database file
  110. @return `FMDatabase` object if successful; `nil` if failure.
  111. */
  112. - (instancetype)initWithPath:(NSString*)inPath;
  113. ///-----------------------------------
  114. /// @name Opening and closing database
  115. ///-----------------------------------
  116. /** Opening a new database connection
  117. The database is opened for reading and writing, and is created if it does not already exist.
  118. @return `YES` if successful, `NO` on error.
  119. @see [sqlite3_open()](http://sqlite.org/c3ref/open.html)
  120. @see openWithFlags:
  121. @see close
  122. */
  123. - (BOOL)open;
  124. /** Opening a new database connection with flags and an optional virtual file system (VFS)
  125. @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:
  126. `SQLITE_OPEN_READONLY`
  127. The database is opened in read-only mode. If the database does not already exist, an error is returned.
  128. `SQLITE_OPEN_READWRITE`
  129. 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.
  130. `SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE`
  131. 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.
  132. If vfs is given the value is passed to the vfs parameter of sqlite3_open_v2.
  133. @return `YES` if successful, `NO` on error.
  134. @see [sqlite3_open_v2()](http://sqlite.org/c3ref/open.html)
  135. @see open
  136. @see close
  137. @warning Requires SQLite 3.5
  138. */
  139. - (BOOL)openWithFlags:(int)flags;
  140. - (BOOL)openWithFlags:(int)flags vfs:(NSString *)vfsName;
  141. /** Closing a database connection
  142. @return `YES` if success, `NO` on error.
  143. @see [sqlite3_close()](http://sqlite.org/c3ref/close.html)
  144. @see open
  145. @see openWithFlags:
  146. */
  147. - (BOOL)close;
  148. /** Test to see if we have a good connection to the database.
  149. This will confirm whether:
  150. - is database open
  151. - if open, it will try a simple SELECT statement and confirm that it succeeds.
  152. @return `YES` if everything succeeds, `NO` on failure.
  153. */
  154. - (BOOL)goodConnection;
  155. ///----------------------
  156. /// @name Perform updates
  157. ///----------------------
  158. /** Execute single update statement
  159. 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.
  160. 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.
  161. @param sql The SQL to be performed, with optional `?` placeholders.
  162. @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.
  163. @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.).
  164. @return `YES` upon success; `NO` upon failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
  165. @see lastError
  166. @see lastErrorCode
  167. @see lastErrorMessage
  168. @see [`sqlite3_bind`](http://sqlite.org/c3ref/bind_blob.html)
  169. */
  170. - (BOOL)executeUpdate:(NSString*)sql withErrorAndBindings:(NSError**)outErr, ...;
  171. /** Execute single update statement
  172. @see executeUpdate:withErrorAndBindings:
  173. @warning **Deprecated**: Please use `<executeUpdate:withErrorAndBindings>` instead.
  174. */
  175. - (BOOL)update:(NSString*)sql withErrorAndBindings:(NSError**)outErr, ... __attribute__ ((deprecated));
  176. /** Execute single update statement
  177. 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.
  178. 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.
  179. @param sql The SQL to be performed, with optional `?` placeholders.
  180. @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.).
  181. @return `YES` upon success; `NO` upon failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
  182. @see lastError
  183. @see lastErrorCode
  184. @see lastErrorMessage
  185. @see [`sqlite3_bind`](http://sqlite.org/c3ref/bind_blob.html)
  186. @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.
  187. @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:>`.
  188. */
  189. - (BOOL)executeUpdate:(NSString*)sql, ...;
  190. /** Execute single update statement
  191. 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.
  192. @param format The SQL to be performed, with `printf`-style escape sequences.
  193. @param ... Optional parameters to bind to use in conjunction with the `printf`-style escape sequences in the SQL statement.
  194. @return `YES` upon success; `NO` upon failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
  195. @see executeUpdate:
  196. @see lastError
  197. @see lastErrorCode
  198. @see lastErrorMessage
  199. @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
  200. [db executeUpdateWithFormat:@"INSERT INTO test (name) VALUES (%@)", @"Gus"];
  201. is actually replacing the `%@` with `?` placeholder, and then performing something equivalent to `<executeUpdate:>`
  202. [db executeUpdate:@"INSERT INTO test (name) VALUES (?)", @"Gus"];
  203. 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 (%@)`.
  204. */
  205. - (BOOL)executeUpdateWithFormat:(NSString *)format, ... NS_FORMAT_FUNCTION(1,2);
  206. /** Execute single update statement
  207. 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.
  208. 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.
  209. @param sql The SQL to be performed, with optional `?` placeholders.
  210. @param arguments A `NSArray` of objects to be used when binding values to the `?` placeholders in the SQL statement.
  211. @return `YES` upon success; `NO` upon failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
  212. @see lastError
  213. @see lastErrorCode
  214. @see lastErrorMessage
  215. */
  216. - (BOOL)executeUpdate:(NSString*)sql withArgumentsInArray:(NSArray *)arguments;
  217. /** Execute single update statement
  218. 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.
  219. 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.
  220. @param sql The SQL to be performed, with optional `?` placeholders.
  221. @param arguments A `NSDictionary` of objects keyed by column names that will be used when binding values to the `?` placeholders in the SQL statement.
  222. @return `YES` upon success; `NO` upon failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
  223. @see lastError
  224. @see lastErrorCode
  225. @see lastErrorMessage
  226. */
  227. - (BOOL)executeUpdate:(NSString*)sql withParameterDictionary:(NSDictionary *)arguments;
  228. /** Execute single update statement
  229. 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.
  230. 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.
  231. @param sql The SQL to be performed, with optional `?` placeholders.
  232. @param args A `va_list` of arguments.
  233. @return `YES` upon success; `NO` upon failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
  234. @see lastError
  235. @see lastErrorCode
  236. @see lastErrorMessage
  237. */
  238. - (BOOL)executeUpdate:(NSString*)sql withVAList: (va_list)args;
  239. /** Execute multiple SQL statements
  240. 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`.
  241. @param sql The SQL to be performed
  242. @return `YES` upon success; `NO` upon failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
  243. @see executeStatements:withResultBlock:
  244. @see [sqlite3_exec()](http://sqlite.org/c3ref/exec.html)
  245. */
  246. - (BOOL)executeStatements:(NSString *)sql;
  247. /** Execute multiple SQL statements with callback handler
  248. 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`.
  249. @param sql The SQL to be performed.
  250. @param block A block that will be called for any result sets returned by any SQL statements.
  251. Note, if you supply this block, it must return integer value, zero upon success (this would be a good opportunity to use SQLITE_OK),
  252. 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.
  253. This may be `nil` if you don't care to receive any results.
  254. @return `YES` upon success; `NO` upon failure. If failed, you can call `<lastError>`,
  255. `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
  256. @see executeStatements:
  257. @see [sqlite3_exec()](http://sqlite.org/c3ref/exec.html)
  258. */
  259. - (BOOL)executeStatements:(NSString *)sql withResultBlock:(AWSFMDBExecuteStatementsCallbackBlock)block;
  260. /** Last insert rowid
  261. 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.
  262. 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.
  263. @return The rowid of the last inserted row.
  264. @see [sqlite3_last_insert_rowid()](http://sqlite.org/c3ref/last_insert_rowid.html)
  265. */
  266. - (long long int)lastInsertRowId;
  267. /** The number of rows changed by prior SQL statement.
  268. 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.
  269. @return The number of rows changed by prior SQL statement.
  270. @see [sqlite3_changes()](http://sqlite.org/c3ref/changes.html)
  271. */
  272. - (int)changes;
  273. ///-------------------------
  274. /// @name Retrieving results
  275. ///-------------------------
  276. /** Execute select statement
  277. 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.
  278. 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.
  279. 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.
  280. @param sql The SELECT statement to be performed, with optional `?` placeholders.
  281. @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.).
  282. @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.
  283. @see FMResultSet
  284. @see [`FMResultSet next`](<[FMResultSet next]>)
  285. @see [`sqlite3_bind`](http://sqlite.org/c3ref/bind_blob.html)
  286. @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:>`.
  287. */
  288. - (AWSFMResultSet *)executeQuery:(NSString*)sql, ...;
  289. /** Execute select statement
  290. 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.
  291. 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.
  292. @param format The SQL to be performed, with `printf`-style escape sequences.
  293. @param ... Optional parameters to bind to use in conjunction with the `printf`-style escape sequences in the SQL statement.
  294. @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.
  295. @see executeQuery:
  296. @see FMResultSet
  297. @see [`FMResultSet next`](<[FMResultSet next]>)
  298. @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
  299. [db executeQueryWithFormat:@"SELECT * FROM test WHERE name=%@", @"Gus"];
  300. is actually replacing the `%@` with `?` placeholder, and then performing something equivalent to `<executeQuery:>`
  301. [db executeQuery:@"SELECT * FROM test WHERE name=?", @"Gus"];
  302. 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=%@`.
  303. */
  304. - (AWSFMResultSet *)executeQueryWithFormat:(NSString*)format, ... NS_FORMAT_FUNCTION(1,2);
  305. /** Execute select statement
  306. 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.
  307. 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.
  308. @param sql The SELECT statement to be performed, with optional `?` placeholders.
  309. @param arguments A `NSArray` of objects to be used when binding values to the `?` placeholders in the SQL statement.
  310. @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.
  311. @see FMResultSet
  312. @see [`FMResultSet next`](<[FMResultSet next]>)
  313. */
  314. - (AWSFMResultSet *)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray *)arguments;
  315. /** Execute select statement
  316. 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.
  317. 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.
  318. @param sql The SELECT statement to be performed, with optional `?` placeholders.
  319. @param arguments A `NSDictionary` of objects keyed by column names that will be used when binding values to the `?` placeholders in the SQL statement.
  320. @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.
  321. @see FMResultSet
  322. @see [`FMResultSet next`](<[FMResultSet next]>)
  323. */
  324. - (AWSFMResultSet *)executeQuery:(NSString *)sql withParameterDictionary:(NSDictionary *)arguments;
  325. // Documentation forthcoming.
  326. - (AWSFMResultSet *)executeQuery:(NSString*)sql withVAList: (va_list)args;
  327. ///-------------------
  328. /// @name Transactions
  329. ///-------------------
  330. /** Begin a transaction
  331. @return `YES` on success; `NO` on failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
  332. @see commit
  333. @see rollback
  334. @see beginDeferredTransaction
  335. @see inTransaction
  336. */
  337. - (BOOL)beginTransaction;
  338. /** Begin a deferred transaction
  339. @return `YES` on success; `NO` on failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
  340. @see commit
  341. @see rollback
  342. @see beginTransaction
  343. @see inTransaction
  344. */
  345. - (BOOL)beginDeferredTransaction;
  346. /** Commit a transaction
  347. Commit a transaction that was initiated with either `<beginTransaction>` or with `<beginDeferredTransaction>`.
  348. @return `YES` on success; `NO` on failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
  349. @see beginTransaction
  350. @see beginDeferredTransaction
  351. @see rollback
  352. @see inTransaction
  353. */
  354. - (BOOL)commit;
  355. /** Rollback a transaction
  356. Rollback a transaction that was initiated with either `<beginTransaction>` or with `<beginDeferredTransaction>`.
  357. @return `YES` on success; `NO` on failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
  358. @see beginTransaction
  359. @see beginDeferredTransaction
  360. @see commit
  361. @see inTransaction
  362. */
  363. - (BOOL)rollback;
  364. /** Identify whether currently in a transaction or not
  365. @return `YES` if currently within transaction; `NO` if not.
  366. @see beginTransaction
  367. @see beginDeferredTransaction
  368. @see commit
  369. @see rollback
  370. */
  371. - (BOOL)inTransaction;
  372. ///----------------------------------------
  373. /// @name Cached statements and result sets
  374. ///----------------------------------------
  375. /** Clear cached statements */
  376. - (void)clearCachedStatements;
  377. /** Close all open result sets */
  378. - (void)closeOpenResultSets;
  379. /** Whether database has any open result sets
  380. @return `YES` if there are open result sets; `NO` if not.
  381. */
  382. - (BOOL)hasOpenResultSets;
  383. /** Return whether should cache statements or not
  384. @return `YES` if should cache statements; `NO` if not.
  385. */
  386. - (BOOL)shouldCacheStatements;
  387. /** Set whether should cache statements or not
  388. @param value `YES` if should cache statements; `NO` if not.
  389. */
  390. - (void)setShouldCacheStatements:(BOOL)value;
  391. ///-------------------------
  392. /// @name Encryption methods
  393. ///-------------------------
  394. /** Set encryption key.
  395. @param key The key to be used.
  396. @return `YES` if success, `NO` on error.
  397. @see http://www.sqlite-encrypt.com/develop-guide.htm
  398. @warning You need to have purchased the sqlite encryption extensions for this method to work.
  399. */
  400. - (BOOL)setKey:(NSString*)key;
  401. /** Reset encryption key
  402. @param key The key to be used.
  403. @return `YES` if success, `NO` on error.
  404. @see http://www.sqlite-encrypt.com/develop-guide.htm
  405. @warning You need to have purchased the sqlite encryption extensions for this method to work.
  406. */
  407. - (BOOL)rekey:(NSString*)key;
  408. /** Set encryption key using `keyData`.
  409. @param keyData The `NSData` to be used.
  410. @return `YES` if success, `NO` on error.
  411. @see http://www.sqlite-encrypt.com/develop-guide.htm
  412. @warning You need to have purchased the sqlite encryption extensions for this method to work.
  413. */
  414. - (BOOL)setKeyWithData:(NSData *)keyData;
  415. /** Reset encryption key using `keyData`.
  416. @param keyData The `NSData` to be used.
  417. @return `YES` if success, `NO` on error.
  418. @see http://www.sqlite-encrypt.com/develop-guide.htm
  419. @warning You need to have purchased the sqlite encryption extensions for this method to work.
  420. */
  421. - (BOOL)rekeyWithData:(NSData *)keyData;
  422. ///------------------------------
  423. /// @name General inquiry methods
  424. ///------------------------------
  425. /** The path of the database file
  426. @return path of database.
  427. */
  428. - (NSString *)databasePath;
  429. /** The underlying SQLite handle
  430. @return The `sqlite3` pointer.
  431. */
  432. - (void*)sqliteHandle;
  433. ///-----------------------------
  434. /// @name Retrieving error codes
  435. ///-----------------------------
  436. /** Last error message
  437. 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.
  438. @return `NSString` of the last error message.
  439. @see [sqlite3_errmsg()](http://sqlite.org/c3ref/errcode.html)
  440. @see lastErrorCode
  441. @see lastError
  442. */
  443. - (NSString*)lastErrorMessage;
  444. /** Last error code
  445. 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.
  446. @return Integer value of the last error code.
  447. @see [sqlite3_errcode()](http://sqlite.org/c3ref/errcode.html)
  448. @see lastErrorMessage
  449. @see lastError
  450. */
  451. - (int)lastErrorCode;
  452. /** Had error
  453. @return `YES` if there was an error, `NO` if no error.
  454. @see lastError
  455. @see lastErrorCode
  456. @see lastErrorMessage
  457. */
  458. - (BOOL)hadError;
  459. /** Last error
  460. @return `NSError` representing the last error.
  461. @see lastErrorCode
  462. @see lastErrorMessage
  463. */
  464. - (NSError*)lastError;
  465. // description forthcoming
  466. - (void)setMaxBusyRetryTimeInterval:(NSTimeInterval)timeoutInSeconds;
  467. - (NSTimeInterval)maxBusyRetryTimeInterval;
  468. ///------------------
  469. /// @name Save points
  470. ///------------------
  471. /** Start save point
  472. @param name Name of save point.
  473. @param outErr A `NSError` object to receive any error object (if any).
  474. @return `YES` on success; `NO` on failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
  475. @see releaseSavePointWithName:error:
  476. @see rollbackToSavePointWithName:error:
  477. */
  478. - (BOOL)startSavePointWithName:(NSString*)name error:(NSError**)outErr;
  479. /** Release save point
  480. @param name Name of save point.
  481. @param outErr A `NSError` object to receive any error object (if any).
  482. @return `YES` on success; `NO` on failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
  483. @see startSavePointWithName:error:
  484. @see rollbackToSavePointWithName:error:
  485. */
  486. - (BOOL)releaseSavePointWithName:(NSString*)name error:(NSError**)outErr;
  487. /** Roll back to save point
  488. @param name Name of save point.
  489. @param outErr A `NSError` object to receive any error object (if any).
  490. @return `YES` on success; `NO` on failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
  491. @see startSavePointWithName:error:
  492. @see releaseSavePointWithName:error:
  493. */
  494. - (BOOL)rollbackToSavePointWithName:(NSString*)name error:(NSError**)outErr;
  495. /** Start save point
  496. @param block Block of code to perform from within save point.
  497. @return The NSError corresponding to the error, if any. If no error, returns `nil`.
  498. @see startSavePointWithName:error:
  499. @see releaseSavePointWithName:error:
  500. @see rollbackToSavePointWithName:error:
  501. */
  502. - (NSError*)inSavePoint:(void (^)(BOOL *rollback))block;
  503. ///----------------------------
  504. /// @name SQLite library status
  505. ///----------------------------
  506. /** Test to see if the library is threadsafe
  507. @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.
  508. @see [sqlite3_threadsafe()](http://sqlite.org/c3ref/threadsafe.html)
  509. */
  510. + (BOOL)isSQLiteThreadSafe;
  511. /** Run-time library version numbers
  512. @return The sqlite library version string.
  513. @see [sqlite3_libversion()](http://sqlite.org/c3ref/libversion.html)
  514. */
  515. + (NSString*)sqliteLibVersion;
  516. + (NSString*)AWSFMDBUserVersion;
  517. + (SInt32)AWSFMDBVersion;
  518. ///------------------------
  519. /// @name Make SQL function
  520. ///------------------------
  521. /** Adds SQL functions or aggregates or to redefine the behavior of existing SQL functions or aggregates.
  522. For example:
  523. [queue inDatabase:^(FMDatabase *adb) {
  524. [adb executeUpdate:@"create table ftest (foo text)"];
  525. [adb executeUpdate:@"insert into ftest values ('hello')"];
  526. [adb executeUpdate:@"insert into ftest values ('hi')"];
  527. [adb executeUpdate:@"insert into ftest values ('not h!')"];
  528. [adb executeUpdate:@"insert into ftest values ('definitely not h!')"];
  529. [adb makeFunctionNamed:@"StringStartsWithH" maximumArguments:1 withBlock:^(sqlite3_context *context, int aargc, sqlite3_value **aargv) {
  530. if (sqlite3_value_type(aargv[0]) == SQLITE_TEXT) {
  531. @autoreleasepool {
  532. const char *c = (const char *)sqlite3_value_text(aargv[0]);
  533. NSString *s = [NSString stringWithUTF8String:c];
  534. sqlite3_result_int(context, [s hasPrefix:@"h"]);
  535. }
  536. }
  537. else {
  538. NSLog(@"Unknown formart for StringStartsWithH (%d) %s:%d", sqlite3_value_type(aargv[0]), __FUNCTION__, __LINE__);
  539. sqlite3_result_null(context);
  540. }
  541. }];
  542. int rowCount = 0;
  543. FMResultSet *ars = [adb executeQuery:@"select * from ftest where StringStartsWithH(foo)"];
  544. while ([ars next]) {
  545. rowCount++;
  546. NSLog(@"Does %@ start with 'h'?", [rs stringForColumnIndex:0]);
  547. }
  548. AWSFMDBQuickCheck(rowCount == 2);
  549. }];
  550. @param name Name of function
  551. @param count Maximum number of parameters
  552. @param block The block of code for the function
  553. @see [sqlite3_create_function()](http://sqlite.org/c3ref/create_function.html)
  554. */
  555. - (void)makeFunctionNamed:(NSString*)name maximumArguments:(int)count withBlock:(void (^)(void *context, int argc, void **argv))block;
  556. ///---------------------
  557. /// @name Date formatter
  558. ///---------------------
  559. /** Generate an `NSDateFormatter` that won't be broken by permutations of timezones or locales.
  560. Use this method to generate values to set the dateFormat property.
  561. Example:
  562. myDB.dateFormat = [FMDatabase storeableDateFormat:@"yyyy-MM-dd HH:mm:ss"];
  563. @param format A valid NSDateFormatter format string.
  564. @return A `NSDateFormatter` that can be used for converting dates to strings and vice versa.
  565. @see hasDateFormatter
  566. @see setDateFormat:
  567. @see dateFromString:
  568. @see stringFromDate:
  569. @see storeableDateFormat:
  570. @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.
  571. */
  572. + (NSDateFormatter *)storeableDateFormat:(NSString *)format;
  573. /** Test whether the database has a date formatter assigned.
  574. @return `YES` if there is a date formatter; `NO` if not.
  575. @see hasDateFormatter
  576. @see setDateFormat:
  577. @see dateFromString:
  578. @see stringFromDate:
  579. @see storeableDateFormat:
  580. */
  581. - (BOOL)hasDateFormatter;
  582. /** Set to a date formatter to use string dates with sqlite instead of the default UNIX timestamps.
  583. @param format Set to nil to use UNIX timestamps. Defaults to nil. Should be set using a formatter generated using FMDatabase::storeableDateFormat.
  584. @see hasDateFormatter
  585. @see setDateFormat:
  586. @see dateFromString:
  587. @see stringFromDate:
  588. @see storeableDateFormat:
  589. @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.
  590. */
  591. - (void)setDateFormat:(NSDateFormatter *)format;
  592. /** Convert the supplied NSString to NSDate, using the current database formatter.
  593. @param s `NSString` to convert to `NSDate`.
  594. @return The `NSDate` object; or `nil` if no formatter is set.
  595. @see hasDateFormatter
  596. @see setDateFormat:
  597. @see dateFromString:
  598. @see stringFromDate:
  599. @see storeableDateFormat:
  600. */
  601. - (NSDate *)dateFromString:(NSString *)s;
  602. /** Convert the supplied NSDate to NSString, using the current database formatter.
  603. @param date `NSDate` of date to convert to `NSString`.
  604. @return The `NSString` representation of the date; `nil` if no formatter is set.
  605. @see hasDateFormatter
  606. @see setDateFormat:
  607. @see dateFromString:
  608. @see stringFromDate:
  609. @see storeableDateFormat:
  610. */
  611. - (NSString *)stringFromDate:(NSDate *)date;
  612. @end
  613. /** Objective-C wrapper for `sqlite3_stmt`
  614. This is a wrapper for a SQLite `sqlite3_stmt`. Generally when using AWSFMDB you will not need to interact directly with `FMStatement`, but rather with `<FMDatabase>` and `<FMResultSet>` only.
  615. ### See also
  616. - `<FMDatabase>`
  617. - `<FMResultSet>`
  618. - [`sqlite3_stmt`](http://www.sqlite.org/c3ref/stmt.html)
  619. */
  620. @interface AWSFMStatement : NSObject {
  621. NSString *_query;
  622. long _useCount;
  623. BOOL _inUse;
  624. }
  625. ///-----------------
  626. /// @name Properties
  627. ///-----------------
  628. /** Usage count */
  629. @property (atomic, assign) long useCount;
  630. /** SQL statement */
  631. @property (atomic, retain) NSString *query;
  632. /** SQLite sqlite3_stmt
  633. @see [`sqlite3_stmt`](http://www.sqlite.org/c3ref/stmt.html)
  634. */
  635. @property (atomic, assign) void *statement;
  636. /** Indication of whether the statement is in use */
  637. @property (atomic, assign) BOOL inUse;
  638. ///----------------------------
  639. /// @name Closing and Resetting
  640. ///----------------------------
  641. /** Close statement */
  642. - (void)close;
  643. /** Reset statement */
  644. - (void)reset;
  645. @end
  646. #pragma clang diagnostic pop