FMDatabase.h 33 KB

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