FMDatabase.h 41 KB

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