FMDatabase.h 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436
  1. #import <Foundation/Foundation.h>
  2. #import "FMResultSet.h"
  3. #import "FMDatabasePool.h"
  4. NS_ASSUME_NONNULL_BEGIN
  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. typedef NS_ENUM(int, FMDBCheckpointMode) {
  33. FMDBCheckpointModePassive = 0, // SQLITE_CHECKPOINT_PASSIVE,
  34. FMDBCheckpointModeFull = 1, // SQLITE_CHECKPOINT_FULL,
  35. FMDBCheckpointModeRestart = 2, // SQLITE_CHECKPOINT_RESTART,
  36. FMDBCheckpointModeTruncate = 3 // SQLITE_CHECKPOINT_TRUNCATE
  37. };
  38. /** A SQLite ([http://sqlite.org/](http://sqlite.org/)) Objective-C wrapper.
  39. ### Usage
  40. The three main classes in FMDB are:
  41. - `FMDatabase` - Represents a single SQLite database. Used for executing SQL statements.
  42. - `<FMResultSet>` - Represents the results of executing a query on an `FMDatabase`.
  43. - `<FMDatabaseQueue>` - If you want to perform queries and updates on multiple threads, you'll want to use this class.
  44. ### See also
  45. - `<FMDatabasePool>` - A pool of `FMDatabase` objects.
  46. - `<FMStatement>` - A wrapper for `sqlite_stmt`.
  47. ### External links
  48. - [FMDB on GitHub](https://github.com/ccgus/fmdb) including introductory documentation
  49. - [SQLite web site](http://sqlite.org/)
  50. - [FMDB mailing list](http://groups.google.com/group/fmdb)
  51. - [SQLite FAQ](http://www.sqlite.org/faq.html)
  52. @warning Do not instantiate a single `FMDatabase` object and use it across multiple threads. Instead, use `<FMDatabaseQueue>`.
  53. */
  54. #pragma clang diagnostic push
  55. #pragma clang diagnostic ignored "-Wobjc-interface-ivars"
  56. @interface FMDatabase : NSObject
  57. ///-----------------
  58. /// @name Properties
  59. ///-----------------
  60. /** Whether should trace execution */
  61. @property (atomic, assign) BOOL traceExecution;
  62. /** Whether checked out or not */
  63. @property (atomic, assign) BOOL checkedOut;
  64. /** Crash on errors */
  65. @property (atomic, assign) BOOL crashOnErrors;
  66. /** Logs errors */
  67. @property (atomic, assign) BOOL logsErrors;
  68. /** Dictionary of cached statements */
  69. @property (atomic, retain, nullable) NSMutableDictionary *cachedStatements;
  70. ///---------------------
  71. /// @name Initialization
  72. ///---------------------
  73. /** Create a `FMDatabase` object.
  74. An `FMDatabase` is created with a path to a SQLite database file. This path can be one of these three:
  75. 1. A file system path. The file does not have to exist on disk. If it does not exist, it is created for you.
  76. 2. An empty string (`@""`). An empty database is created at a temporary location. This database is deleted with the `FMDatabase` connection is closed.
  77. 3. `nil`. An in-memory database is created. This database will be destroyed with the `FMDatabase` connection is closed.
  78. For example, to create/open a database in your Mac OS X `tmp` folder:
  79. FMDatabase *db = [FMDatabase databaseWithPath:@"/tmp/tmp.db"];
  80. Or, in iOS, you might open a database in the app's `Documents` directory:
  81. NSString *docsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
  82. NSString *dbPath = [docsPath stringByAppendingPathComponent:@"test.db"];
  83. FMDatabase *db = [FMDatabase databaseWithPath:dbPath];
  84. (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))
  85. @param inPath Path of database file
  86. @return `FMDatabase` object if successful; `nil` if failure.
  87. */
  88. + (instancetype)databaseWithPath:(NSString * _Nullable)inPath;
  89. /** Create a `FMDatabase` object.
  90. An `FMDatabase` is created with a path to a SQLite database file. This path can be one of these three:
  91. 1. A file system URL. The file does not have to exist on disk. If it does not exist, it is created for you.
  92. 2. `nil`. An in-memory database is created. This database will be destroyed with the `FMDatabase` connection is closed.
  93. For example, to create/open a database in your Mac OS X `tmp` folder:
  94. FMDatabase *db = [FMDatabase databaseWithPath:@"/tmp/tmp.db"];
  95. Or, in iOS, you might open a database in the app's `Documents` directory:
  96. NSString *docsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
  97. NSString *dbPath = [docsPath stringByAppendingPathComponent:@"test.db"];
  98. FMDatabase *db = [FMDatabase databaseWithPath:dbPath];
  99. (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))
  100. @param url The local file URL (not remote URL) of database file
  101. @return `FMDatabase` object if successful; `nil` if failure.
  102. */
  103. + (instancetype)databaseWithURL:(NSURL * _Nullable)url;
  104. /** Initialize a `FMDatabase` object.
  105. An `FMDatabase` is created with a path to a SQLite database file. This path can be one of these three:
  106. 1. A file system path. The file does not have to exist on disk. If it does not exist, it is created for you.
  107. 2. An empty string (`@""`). An empty database is created at a temporary location. This database is deleted with the `FMDatabase` connection is closed.
  108. 3. `nil`. An in-memory database is created. This database will be destroyed with the `FMDatabase` connection is closed.
  109. For example, to create/open a database in your Mac OS X `tmp` folder:
  110. FMDatabase *db = [FMDatabase databaseWithPath:@"/tmp/tmp.db"];
  111. Or, in iOS, you might open a database in the app's `Documents` directory:
  112. NSString *docsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
  113. NSString *dbPath = [docsPath stringByAppendingPathComponent:@"test.db"];
  114. FMDatabase *db = [FMDatabase databaseWithPath:dbPath];
  115. (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))
  116. @param path Path of database file.
  117. @return `FMDatabase` object if successful; `nil` if failure.
  118. */
  119. - (instancetype)initWithPath:(NSString * _Nullable)path;
  120. /** Initialize a `FMDatabase` object.
  121. An `FMDatabase` is created with a local file URL to a SQLite database file. This path can be one of these three:
  122. 1. A file system URL. The file does not have to exist on disk. If it does not exist, it is created for you.
  123. 2. `nil`. An in-memory database is created. This database will be destroyed with the `FMDatabase` connection is closed.
  124. For example, to create/open a database in your Mac OS X `tmp` folder:
  125. FMDatabase *db = [FMDatabase databaseWithPath:@"/tmp/tmp.db"];
  126. Or, in iOS, you might open a database in the app's `Documents` directory:
  127. NSString *docsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
  128. NSString *dbPath = [docsPath stringByAppendingPathComponent:@"test.db"];
  129. FMDatabase *db = [FMDatabase databaseWithPath:dbPath];
  130. (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))
  131. @param url The file `NSURL` of database file.
  132. @return `FMDatabase` object if successful; `nil` if failure.
  133. */
  134. - (instancetype)initWithURL:(NSURL * _Nullable)url;
  135. ///-----------------------------------
  136. /// @name Opening and closing database
  137. ///-----------------------------------
  138. /// Is the database open or not?
  139. @property (nonatomic) BOOL isOpen;
  140. /** Opening a new database connection
  141. The database is opened for reading and writing, and is created if it does not already exist.
  142. @return `YES` if successful, `NO` on error.
  143. @see [sqlite3_open()](http://sqlite.org/c3ref/open.html)
  144. @see openWithFlags:
  145. @see close
  146. */
  147. - (BOOL)open;
  148. /** Opening a new database connection with flags and an optional virtual file system (VFS)
  149. @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:
  150. `SQLITE_OPEN_READONLY`
  151. The database is opened in read-only mode. If the database does not already exist, an error is returned.
  152. `SQLITE_OPEN_READWRITE`
  153. 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.
  154. `SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE`
  155. 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.
  156. @return `YES` if successful, `NO` on error.
  157. @see [sqlite3_open_v2()](http://sqlite.org/c3ref/open.html)
  158. @see open
  159. @see close
  160. */
  161. - (BOOL)openWithFlags:(int)flags;
  162. /** Opening a new database connection with flags and an optional virtual file system (VFS)
  163. @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:
  164. `SQLITE_OPEN_READONLY`
  165. The database is opened in read-only mode. If the database does not already exist, an error is returned.
  166. `SQLITE_OPEN_READWRITE`
  167. 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.
  168. `SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE`
  169. 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.
  170. @param vfsName If vfs is given the value is passed to the vfs parameter of sqlite3_open_v2.
  171. @return `YES` if successful, `NO` on error.
  172. @see [sqlite3_open_v2()](http://sqlite.org/c3ref/open.html)
  173. @see open
  174. @see close
  175. */
  176. - (BOOL)openWithFlags:(int)flags vfs:(NSString * _Nullable)vfsName;
  177. /** Closing a database connection
  178. @return `YES` if success, `NO` on error.
  179. @see [sqlite3_close()](http://sqlite.org/c3ref/close.html)
  180. @see open
  181. @see openWithFlags:
  182. */
  183. - (BOOL)close;
  184. /** Test to see if we have a good connection to the database.
  185. This will confirm whether:
  186. - is database open
  187. - if open, it will try a simple SELECT statement and confirm that it succeeds.
  188. @return `YES` if everything succeeds, `NO` on failure.
  189. */
  190. @property (nonatomic, readonly) BOOL goodConnection;
  191. ///----------------------
  192. /// @name Perform updates
  193. ///----------------------
  194. /** Execute single update statement
  195. 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.
  196. 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.
  197. @param sql The SQL to be performed, with optional `?` placeholders.
  198. @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.
  199. @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.).
  200. @return `YES` upon success; `NO` upon failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
  201. @see lastError
  202. @see lastErrorCode
  203. @see lastErrorMessage
  204. @see [`sqlite3_bind`](http://sqlite.org/c3ref/bind_blob.html)
  205. */
  206. - (BOOL)executeUpdate:(NSString*)sql withErrorAndBindings:(NSError * _Nullable *)outErr, ...;
  207. /** Execute single update statement
  208. @see executeUpdate:withErrorAndBindings:
  209. @warning **Deprecated**: Please use `<executeUpdate:withErrorAndBindings>` instead.
  210. */
  211. - (BOOL)update:(NSString*)sql withErrorAndBindings:(NSError * _Nullable*)outErr, ... __deprecated_msg("Use executeUpdate:withErrorAndBindings: instead");;
  212. /** Execute single update statement
  213. 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.
  214. 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.
  215. @param sql The SQL to be performed, with optional `?` placeholders.
  216. @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.).
  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. @see [`sqlite3_bind`](http://sqlite.org/c3ref/bind_blob.html)
  222. @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.
  223. @note You cannot use this method from Swift due to incompatibilities between Swift and Objective-C variadic implementations. Consider using `<executeUpdate:values:>` instead.
  224. */
  225. - (BOOL)executeUpdate:(NSString*)sql, ...;
  226. /** Execute single update statement
  227. 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.
  228. @param format The SQL to be performed, with `printf`-style escape sequences.
  229. @param ... Optional parameters to bind to use in conjunction with the `printf`-style escape sequences in the SQL statement.
  230. @return `YES` upon success; `NO` upon failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
  231. @see executeUpdate:
  232. @see lastError
  233. @see lastErrorCode
  234. @see lastErrorMessage
  235. @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
  236. [db executeUpdateWithFormat:@"INSERT INTO test (name) VALUES (%@)", @"Gus"];
  237. is actually replacing the `%@` with `?` placeholder, and then performing something equivalent to `<executeUpdate:>`
  238. [db executeUpdate:@"INSERT INTO test (name) VALUES (?)", @"Gus"];
  239. 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 (%@)`.
  240. */
  241. - (BOOL)executeUpdateWithFormat:(NSString *)format, ... NS_FORMAT_FUNCTION(1,2);
  242. /** Execute single update statement
  243. 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.
  244. 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.
  245. @param sql The SQL to be performed, with optional `?` placeholders.
  246. @param arguments A `NSArray` of objects to be used when binding values to the `?` placeholders in the SQL statement.
  247. @return `YES` upon success; `NO` upon failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
  248. @see executeUpdate:values:error:
  249. @see lastError
  250. @see lastErrorCode
  251. @see lastErrorMessage
  252. */
  253. - (BOOL)executeUpdate:(NSString*)sql withArgumentsInArray:(NSArray *)arguments;
  254. /** Execute single update statement
  255. 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.
  256. 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.
  257. This is similar to `<executeUpdate:withArgumentsInArray:>`, except that this also accepts a pointer to a `NSError` pointer, so that errors can be returned.
  258. In Swift, this throws errors, as if it were defined as follows:
  259. `func executeUpdate(sql: String, values: [Any]?) throws -> Bool`
  260. @param sql The SQL to be performed, with optional `?` placeholders.
  261. @param values A `NSArray` of objects to be used when binding values to the `?` placeholders in the SQL statement.
  262. @param error A `NSError` object to receive any error object (if any).
  263. @return `YES` upon success; `NO` upon failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
  264. @see lastError
  265. @see lastErrorCode
  266. @see lastErrorMessage
  267. */
  268. - (BOOL)executeUpdate:(NSString*)sql values:(NSArray * _Nullable)values error:(NSError * _Nullable __autoreleasing *)error;
  269. /** Execute single update statement
  270. 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.
  271. 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.
  272. @param sql The SQL to be performed, with optional `?` placeholders.
  273. @param arguments A `NSDictionary` of objects keyed by column names that will be used when binding values to the `?` placeholders in the SQL statement.
  274. @return `YES` upon success; `NO` upon failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
  275. @see lastError
  276. @see lastErrorCode
  277. @see lastErrorMessage
  278. */
  279. - (BOOL)executeUpdate:(NSString*)sql withParameterDictionary:(NSDictionary *)arguments;
  280. /** Execute single update statement
  281. 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.
  282. 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.
  283. @param sql The SQL to be performed, with optional `?` placeholders.
  284. @param args A `va_list` of arguments.
  285. @return `YES` upon success; `NO` upon failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
  286. @see lastError
  287. @see lastErrorCode
  288. @see lastErrorMessage
  289. */
  290. - (BOOL)executeUpdate:(NSString*)sql withVAList: (va_list)args;
  291. /** Execute multiple SQL statements
  292. 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`.
  293. @param sql The SQL to be performed
  294. @return `YES` upon success; `NO` upon failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
  295. @see executeStatements:withResultBlock:
  296. @see [sqlite3_exec()](http://sqlite.org/c3ref/exec.html)
  297. */
  298. - (BOOL)executeStatements:(NSString *)sql;
  299. /** Execute multiple SQL statements with callback handler
  300. 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`.
  301. @param sql The SQL to be performed.
  302. @param block A block that will be called for any result sets returned by any SQL statements.
  303. Note, if you supply this block, it must return integer value, zero upon success (this would be a good opportunity to use SQLITE_OK),
  304. 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.
  305. This may be `nil` if you don't care to receive any results.
  306. @return `YES` upon success; `NO` upon failure. If failed, you can call `<lastError>`,
  307. `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
  308. @see executeStatements:
  309. @see [sqlite3_exec()](http://sqlite.org/c3ref/exec.html)
  310. */
  311. - (BOOL)executeStatements:(NSString *)sql withResultBlock:(__attribute__((noescape)) FMDBExecuteStatementsCallbackBlock _Nullable)block;
  312. /** Last insert rowid
  313. 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.
  314. 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.
  315. @return The rowid of the last inserted row.
  316. @see [sqlite3_last_insert_rowid()](http://sqlite.org/c3ref/last_insert_rowid.html)
  317. */
  318. @property (nonatomic, readonly) int64_t lastInsertRowId;
  319. /** The number of rows changed by prior SQL statement.
  320. 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.
  321. @return The number of rows changed by prior SQL statement.
  322. @see [sqlite3_changes()](http://sqlite.org/c3ref/changes.html)
  323. */
  324. @property (nonatomic, readonly) int changes;
  325. ///-------------------------
  326. /// @name Retrieving results
  327. ///-------------------------
  328. /** Execute select statement
  329. 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.
  330. 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.
  331. 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.
  332. @param sql The SELECT statement to be performed, with optional `?` placeholders.
  333. @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.).
  334. @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.
  335. @see FMResultSet
  336. @see [`FMResultSet next`](<[FMResultSet next]>)
  337. @see [`sqlite3_bind`](http://sqlite.org/c3ref/bind_blob.html)
  338. @note You cannot use this method from Swift due to incompatibilities between Swift and Objective-C variadic implementations. Consider using `<executeQuery:values:>` instead.
  339. */
  340. - (FMResultSet * _Nullable)executeQuery:(NSString*)sql, ...;
  341. /** Execute select statement
  342. 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.
  343. 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.
  344. @param format The SQL to be performed, with `printf`-style escape sequences.
  345. @param ... Optional parameters to bind to use in conjunction with the `printf`-style escape sequences in the SQL statement.
  346. @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.
  347. @see executeQuery:
  348. @see FMResultSet
  349. @see [`FMResultSet next`](<[FMResultSet next]>)
  350. @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
  351. [db executeQueryWithFormat:@"SELECT * FROM test WHERE name=%@", @"Gus"];
  352. is actually replacing the `%@` with `?` placeholder, and then performing something equivalent to `<executeQuery:>`
  353. [db executeQuery:@"SELECT * FROM test WHERE name=?", @"Gus"];
  354. 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=%@`.
  355. */
  356. - (FMResultSet * _Nullable)executeQueryWithFormat:(NSString*)format, ... NS_FORMAT_FUNCTION(1,2);
  357. /** Execute select statement
  358. 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.
  359. 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.
  360. @param sql The SELECT statement to be performed, with optional `?` placeholders.
  361. @param arguments A `NSArray` of objects to be used when binding values to the `?` placeholders in the SQL statement.
  362. @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.
  363. @see -executeQuery:values:error:
  364. @see FMResultSet
  365. @see [`FMResultSet next`](<[FMResultSet next]>)
  366. */
  367. - (FMResultSet * _Nullable)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray *)arguments;
  368. /** Execute select statement
  369. 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.
  370. 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.
  371. This is similar to `<executeQuery:withArgumentsInArray:>`, except that this also accepts a pointer to a `NSError` pointer, so that errors can be returned.
  372. In Swift, this throws errors, as if it were defined as follows:
  373. `func executeQuery(sql: String, values: [Any]?) throws -> FMResultSet!`
  374. @param sql The SELECT statement to be performed, with optional `?` placeholders.
  375. @param values A `NSArray` of objects to be used when binding values to the `?` placeholders in the SQL statement.
  376. @param error A `NSError` object to receive any error object (if any).
  377. @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.
  378. @see FMResultSet
  379. @see [`FMResultSet next`](<[FMResultSet next]>)
  380. @note When called from Swift, only use the first two parameters, `sql` and `values`. This but throws the error.
  381. */
  382. - (FMResultSet * _Nullable)executeQuery:(NSString *)sql values:(NSArray * _Nullable)values error:(NSError * _Nullable __autoreleasing *)error;
  383. /** Execute select statement
  384. 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.
  385. 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.
  386. @param sql The SELECT statement to be performed, with optional `?` placeholders.
  387. @param arguments A `NSDictionary` of objects keyed by column names that will be used when binding values to the `?` placeholders in the SQL statement.
  388. @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.
  389. @see FMResultSet
  390. @see [`FMResultSet next`](<[FMResultSet next]>)
  391. */
  392. - (FMResultSet * _Nullable)executeQuery:(NSString *)sql withParameterDictionary:(NSDictionary * _Nullable)arguments;
  393. // Documentation forthcoming.
  394. - (FMResultSet * _Nullable)executeQuery:(NSString *)sql withVAList:(va_list)args;
  395. ///-------------------
  396. /// @name Transactions
  397. ///-------------------
  398. /** Begin a transaction
  399. @return `YES` on success; `NO` on failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
  400. @see commit
  401. @see rollback
  402. @see beginDeferredTransaction
  403. @see isInTransaction
  404. @warning Unlike SQLite's `BEGIN TRANSACTION`, this method currently performs
  405. an exclusive transaction, not a deferred transaction. This behavior
  406. is likely to change in future versions of FMDB, whereby this method
  407. will likely eventually adopt standard SQLite behavior and perform
  408. deferred transactions. If you really need exclusive tranaction, it is
  409. recommended that you use `beginExclusiveTransaction`, instead, not
  410. only to make your intent explicit, but also to future-proof your code.
  411. */
  412. - (BOOL)beginTransaction;
  413. /** Begin a deferred transaction
  414. @return `YES` on success; `NO` on failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
  415. @see commit
  416. @see rollback
  417. @see beginTransaction
  418. @see isInTransaction
  419. */
  420. - (BOOL)beginDeferredTransaction;
  421. /** Begin an immediate transaction
  422. @return `YES` on success; `NO` on failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
  423. @see commit
  424. @see rollback
  425. @see beginTransaction
  426. @see isInTransaction
  427. */
  428. - (BOOL)beginImmediateTransaction;
  429. /** Begin an exclusive transaction
  430. @return `YES` on success; `NO` on failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
  431. @see commit
  432. @see rollback
  433. @see beginTransaction
  434. @see isInTransaction
  435. */
  436. - (BOOL)beginExclusiveTransaction;
  437. /** Commit a transaction
  438. Commit a transaction that was initiated with either `<beginTransaction>` or with `<beginDeferredTransaction>`.
  439. @return `YES` on success; `NO` on failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
  440. @see beginTransaction
  441. @see beginDeferredTransaction
  442. @see rollback
  443. @see isInTransaction
  444. */
  445. - (BOOL)commit;
  446. /** Rollback a transaction
  447. Rollback a transaction that was initiated with either `<beginTransaction>` or with `<beginDeferredTransaction>`.
  448. @return `YES` on success; `NO` on failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
  449. @see beginTransaction
  450. @see beginDeferredTransaction
  451. @see commit
  452. @see isInTransaction
  453. */
  454. - (BOOL)rollback;
  455. /** Identify whether currently in a transaction or not
  456. @see beginTransaction
  457. @see beginDeferredTransaction
  458. @see commit
  459. @see rollback
  460. */
  461. @property (nonatomic, readonly) BOOL isInTransaction;
  462. - (BOOL)inTransaction __deprecated_msg("Use isInTransaction property instead");
  463. ///----------------------------------------
  464. /// @name Cached statements and result sets
  465. ///----------------------------------------
  466. /** Clear cached statements */
  467. - (void)clearCachedStatements;
  468. /** Close all open result sets */
  469. - (void)closeOpenResultSets;
  470. /** Whether database has any open result sets
  471. @return `YES` if there are open result sets; `NO` if not.
  472. */
  473. @property (nonatomic, readonly) BOOL hasOpenResultSets;
  474. /** Whether should cache statements or not
  475. */
  476. @property (nonatomic) BOOL shouldCacheStatements;
  477. /** Interupt pending database operation
  478. This method causes any pending database operation to abort and return at its earliest opportunity
  479. @return `YES` on success; `NO` on failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
  480. */
  481. - (BOOL)interrupt;
  482. ///-------------------------
  483. /// @name Encryption methods
  484. ///-------------------------
  485. /** Set encryption key.
  486. @param key The key to be used.
  487. @return `YES` if success, `NO` on error.
  488. @see https://www.zetetic.net/sqlcipher/
  489. @warning You need to have purchased the sqlite encryption extensions for this method to work.
  490. */
  491. - (BOOL)setKey:(NSString*)key;
  492. /** Reset encryption key
  493. @param key The key to be used.
  494. @return `YES` if success, `NO` on error.
  495. @see https://www.zetetic.net/sqlcipher/
  496. @warning You need to have purchased the sqlite encryption extensions for this method to work.
  497. */
  498. - (BOOL)rekey:(NSString*)key;
  499. /** Set encryption key using `keyData`.
  500. @param keyData The `NSData` to be used.
  501. @return `YES` if success, `NO` on error.
  502. @see https://www.zetetic.net/sqlcipher/
  503. @warning You need to have purchased the sqlite encryption extensions for this method to work.
  504. */
  505. - (BOOL)setKeyWithData:(NSData *)keyData;
  506. /** Reset encryption key using `keyData`.
  507. @param keyData The `NSData` to be used.
  508. @return `YES` if success, `NO` on error.
  509. @see https://www.zetetic.net/sqlcipher/
  510. @warning You need to have purchased the sqlite encryption extensions for this method to work.
  511. */
  512. - (BOOL)rekeyWithData:(NSData *)keyData;
  513. ///------------------------------
  514. /// @name General inquiry methods
  515. ///------------------------------
  516. /** The path of the database file
  517. */
  518. @property (nonatomic, readonly, nullable) NSString *databasePath;
  519. /** The file URL of the database file.
  520. */
  521. @property (nonatomic, readonly, nullable) NSURL *databaseURL;
  522. /** The underlying SQLite handle
  523. @return The `sqlite3` pointer.
  524. */
  525. @property (nonatomic, readonly) void *sqliteHandle;
  526. ///-----------------------------
  527. /// @name Retrieving error codes
  528. ///-----------------------------
  529. /** Last error message
  530. 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.
  531. @return `NSString` of the last error message.
  532. @see [sqlite3_errmsg()](http://sqlite.org/c3ref/errcode.html)
  533. @see lastErrorCode
  534. @see lastError
  535. */
  536. - (NSString*)lastErrorMessage;
  537. /** Last error code
  538. 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.
  539. @return Integer value of the last error code.
  540. @see [sqlite3_errcode()](http://sqlite.org/c3ref/errcode.html)
  541. @see lastErrorMessage
  542. @see lastError
  543. */
  544. - (int)lastErrorCode;
  545. /** Last extended error code
  546. Returns the numeric 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.
  547. @return Integer value of the last extended error code.
  548. @see [sqlite3_errcode()](http://sqlite.org/c3ref/errcode.html)
  549. @see [2. Primary Result Codes versus Extended Result Codes](http://sqlite.org/rescode.html#primary_result_codes_versus_extended_result_codes)
  550. @see [5. Extended Result Code List](http://sqlite.org/rescode.html#extrc)
  551. @see lastErrorMessage
  552. @see lastError
  553. */
  554. - (int)lastExtendedErrorCode;
  555. /** Had error
  556. @return `YES` if there was an error, `NO` if no error.
  557. @see lastError
  558. @see lastErrorCode
  559. @see lastErrorMessage
  560. */
  561. - (BOOL)hadError;
  562. /** Last error
  563. @return `NSError` representing the last error.
  564. @see lastErrorCode
  565. @see lastErrorMessage
  566. */
  567. - (NSError *)lastError;
  568. // description forthcoming
  569. @property (nonatomic) NSTimeInterval maxBusyRetryTimeInterval;
  570. ///------------------
  571. /// @name Save points
  572. ///------------------
  573. /** Start save point
  574. @param name Name of save point.
  575. @param outErr A `NSError` object to receive any error object (if any).
  576. @return `YES` on success; `NO` on failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
  577. @see releaseSavePointWithName:error:
  578. @see rollbackToSavePointWithName:error:
  579. */
  580. - (BOOL)startSavePointWithName:(NSString*)name error:(NSError * _Nullable *)outErr;
  581. /** Release save point
  582. @param name Name of save point.
  583. @param outErr A `NSError` object to receive any error object (if any).
  584. @return `YES` on success; `NO` on failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
  585. @see startSavePointWithName:error:
  586. @see rollbackToSavePointWithName:error:
  587. */
  588. - (BOOL)releaseSavePointWithName:(NSString*)name error:(NSError * _Nullable *)outErr;
  589. /** Roll back to save point
  590. @param name Name of save point.
  591. @param outErr A `NSError` object to receive any error object (if any).
  592. @return `YES` on success; `NO` on failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
  593. @see startSavePointWithName:error:
  594. @see releaseSavePointWithName:error:
  595. */
  596. - (BOOL)rollbackToSavePointWithName:(NSString*)name error:(NSError * _Nullable *)outErr;
  597. /** Start save point
  598. @param block Block of code to perform from within save point.
  599. @return The NSError corresponding to the error, if any. If no error, returns `nil`.
  600. @see startSavePointWithName:error:
  601. @see releaseSavePointWithName:error:
  602. @see rollbackToSavePointWithName:error:
  603. */
  604. - (NSError * _Nullable)inSavePoint:(__attribute__((noescape)) void (^)(BOOL *rollback))block;
  605. ///-----------------
  606. /// @name Checkpoint
  607. ///-----------------
  608. /** Performs a WAL checkpoint
  609. @param checkpointMode The checkpoint mode for sqlite3_wal_checkpoint_v2
  610. @param error The NSError corresponding to the error, if any.
  611. @return YES on success, otherwise NO.
  612. */
  613. - (BOOL)checkpoint:(FMDBCheckpointMode)checkpointMode error:(NSError * _Nullable *)error;
  614. /** Performs a WAL checkpoint
  615. @param checkpointMode The checkpoint mode for sqlite3_wal_checkpoint_v2
  616. @param name The db name for sqlite3_wal_checkpoint_v2
  617. @param error The NSError corresponding to the error, if any.
  618. @return YES on success, otherwise NO.
  619. */
  620. - (BOOL)checkpoint:(FMDBCheckpointMode)checkpointMode name:(NSString * _Nullable)name error:(NSError * _Nullable *)error;
  621. /** Performs a WAL checkpoint
  622. @param checkpointMode The checkpoint mode for sqlite3_wal_checkpoint_v2
  623. @param name The db name for sqlite3_wal_checkpoint_v2
  624. @param error The NSError corresponding to the error, if any.
  625. @param logFrameCount If not NULL, then this is set to the total number of frames in the log file or to -1 if the checkpoint could not run because of an error or because the database is not in WAL mode.
  626. @param checkpointCount If not NULL, then this is set to the total number of checkpointed frames in the log file (including any that were already checkpointed before the function was called) or to -1 if the checkpoint could not run due to an error or because the database is not in WAL mode.
  627. @return YES on success, otherwise NO.
  628. */
  629. - (BOOL)checkpoint:(FMDBCheckpointMode)checkpointMode name:(NSString * _Nullable)name logFrameCount:(int * _Nullable)logFrameCount checkpointCount:(int * _Nullable)checkpointCount error:(NSError * _Nullable *)error;
  630. ///----------------------------
  631. /// @name SQLite library status
  632. ///----------------------------
  633. /** Test to see if the library is threadsafe
  634. @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.
  635. @see [sqlite3_threadsafe()](http://sqlite.org/c3ref/threadsafe.html)
  636. */
  637. + (BOOL)isSQLiteThreadSafe;
  638. /** Run-time library version numbers
  639. @return The sqlite library version string.
  640. @see [sqlite3_libversion()](http://sqlite.org/c3ref/libversion.html)
  641. */
  642. + (NSString*)sqliteLibVersion;
  643. + (NSString*)FMDBUserVersion;
  644. + (SInt32)FMDBVersion;
  645. ///------------------------
  646. /// @name Make SQL function
  647. ///------------------------
  648. /** Adds SQL functions or aggregates or to redefine the behavior of existing SQL functions or aggregates.
  649. For example:
  650. [db makeFunctionNamed:@"RemoveDiacritics" arguments:1 block:^(void *context, int argc, void **argv) {
  651. SqliteValueType type = [self.db valueType:argv[0]];
  652. if (type == SqliteValueTypeNull) {
  653. [self.db resultNullInContext:context];
  654. return;
  655. }
  656. if (type != SqliteValueTypeText) {
  657. [self.db resultError:@"Expected text" context:context];
  658. return;
  659. }
  660. NSString *string = [self.db valueString:argv[0]];
  661. NSString *result = [string stringByFoldingWithOptions:NSDiacriticInsensitiveSearch locale:nil];
  662. [self.db resultString:result context:context];
  663. }];
  664. FMResultSet *rs = [db executeQuery:@"SELECT * FROM employees WHERE RemoveDiacritics(first_name) LIKE 'jose'"];
  665. NSAssert(rs, @"Error %@", [db lastErrorMessage]);
  666. @param name Name of function.
  667. @param arguments Maximum number of parameters.
  668. @param block The block of code for the function.
  669. @see [sqlite3_create_function()](http://sqlite.org/c3ref/create_function.html)
  670. */
  671. - (void)makeFunctionNamed:(NSString *)name arguments:(int)arguments block:(void (^)(void *context, int argc, void * _Nonnull * _Nonnull argv))block;
  672. - (void)makeFunctionNamed:(NSString *)name maximumArguments:(int)count withBlock:(void (^)(void *context, int argc, void * _Nonnull * _Nonnull argv))block __deprecated_msg("Use makeFunctionNamed:arguments:block:");
  673. typedef NS_ENUM(int, SqliteValueType) {
  674. SqliteValueTypeInteger = 1,
  675. SqliteValueTypeFloat = 2,
  676. SqliteValueTypeText = 3,
  677. SqliteValueTypeBlob = 4,
  678. SqliteValueTypeNull = 5
  679. };
  680. - (SqliteValueType)valueType:(void *)argv;
  681. /**
  682. Get integer value of parameter in custom function.
  683. @param value The argument whose value to return.
  684. @return The integer value.
  685. @see makeFunctionNamed:arguments:block:
  686. */
  687. - (int)valueInt:(void *)value;
  688. /**
  689. Get long value of parameter in custom function.
  690. @param value The argument whose value to return.
  691. @return The long value.
  692. @see makeFunctionNamed:arguments:block:
  693. */
  694. - (long long)valueLong:(void *)value;
  695. /**
  696. Get double value of parameter in custom function.
  697. @param value The argument whose value to return.
  698. @return The double value.
  699. @see makeFunctionNamed:arguments:block:
  700. */
  701. - (double)valueDouble:(void *)value;
  702. /**
  703. Get `NSData` value of parameter in custom function.
  704. @param value The argument whose value to return.
  705. @return The data object.
  706. @see makeFunctionNamed:arguments:block:
  707. */
  708. - (NSData * _Nullable)valueData:(void *)value;
  709. /**
  710. Get string value of parameter in custom function.
  711. @param value The argument whose value to return.
  712. @return The string value.
  713. @see makeFunctionNamed:arguments:block:
  714. */
  715. - (NSString * _Nullable)valueString:(void *)value;
  716. /**
  717. Return null value from custom function.
  718. @param context The context to which the null value will be returned.
  719. @see makeFunctionNamed:arguments:block:
  720. */
  721. - (void)resultNullInContext:(void *)context NS_SWIFT_NAME(resultNull(context:));
  722. /**
  723. Return integer value from custom function.
  724. @param value The integer value to be returned.
  725. @param context The context to which the value will be returned.
  726. @see makeFunctionNamed:arguments:block:
  727. */
  728. - (void)resultInt:(int) value context:(void *)context;
  729. /**
  730. Return long value from custom function.
  731. @param value The long value to be returned.
  732. @param context The context to which the value will be returned.
  733. @see makeFunctionNamed:arguments:block:
  734. */
  735. - (void)resultLong:(long long)value context:(void *)context;
  736. /**
  737. Return double value from custom function.
  738. @param value The double value to be returned.
  739. @param context The context to which the value will be returned.
  740. @see makeFunctionNamed:arguments:block:
  741. */
  742. - (void)resultDouble:(double)value context:(void *)context;
  743. /**
  744. Return `NSData` object from custom function.
  745. @param data The `NSData` object to be returned.
  746. @param context The context to which the value will be returned.
  747. @see makeFunctionNamed:arguments:block:
  748. */
  749. - (void)resultData:(NSData *)data context:(void *)context;
  750. /**
  751. Return string value from custom function.
  752. @param value The string value to be returned.
  753. @param context The context to which the value will be returned.
  754. @see makeFunctionNamed:arguments:block:
  755. */
  756. - (void)resultString:(NSString *)value context:(void *)context;
  757. /**
  758. Return error string from custom function.
  759. @param error The error string to be returned.
  760. @param context The context to which the error will be returned.
  761. @see makeFunctionNamed:arguments:block:
  762. */
  763. - (void)resultError:(NSString *)error context:(void *)context;
  764. /**
  765. Return error code from custom function.
  766. @param errorCode The integer error code to be returned.
  767. @param context The context to which the error will be returned.
  768. @see makeFunctionNamed:arguments:block:
  769. */
  770. - (void)resultErrorCode:(int)errorCode context:(void *)context;
  771. /**
  772. Report memory error in custom function.
  773. @param context The context to which the error will be returned.
  774. @see makeFunctionNamed:arguments:block:
  775. */
  776. - (void)resultErrorNoMemoryInContext:(void *)context NS_SWIFT_NAME(resultErrorNoMemory(context:));
  777. /**
  778. Report that string or BLOB is too long to represent in custom function.
  779. @param context The context to which the error will be returned.
  780. @see makeFunctionNamed:arguments:block:
  781. */
  782. - (void)resultErrorTooBigInContext:(void *)context NS_SWIFT_NAME(resultErrorTooBig(context:));
  783. ///---------------------
  784. /// @name Date formatter
  785. ///---------------------
  786. /** Generate an `NSDateFormatter` that won't be broken by permutations of timezones or locales.
  787. Use this method to generate values to set the dateFormat property.
  788. Example:
  789. myDB.dateFormat = [FMDatabase storeableDateFormat:@"yyyy-MM-dd HH:mm:ss"];
  790. @param format A valid NSDateFormatter format string.
  791. @return A `NSDateFormatter` that can be used for converting dates to strings and vice versa.
  792. @see hasDateFormatter
  793. @see setDateFormat:
  794. @see dateFromString:
  795. @see stringFromDate:
  796. @see storeableDateFormat:
  797. @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.
  798. */
  799. + (NSDateFormatter *)storeableDateFormat:(NSString *)format;
  800. /** Test whether the database has a date formatter assigned.
  801. @return `YES` if there is a date formatter; `NO` if not.
  802. @see hasDateFormatter
  803. @see setDateFormat:
  804. @see dateFromString:
  805. @see stringFromDate:
  806. @see storeableDateFormat:
  807. */
  808. - (BOOL)hasDateFormatter;
  809. /** Set to a date formatter to use string dates with sqlite instead of the default UNIX timestamps.
  810. @param format Set to nil to use UNIX timestamps. Defaults to nil. Should be set using a formatter generated using FMDatabase::storeableDateFormat.
  811. @see hasDateFormatter
  812. @see setDateFormat:
  813. @see dateFromString:
  814. @see stringFromDate:
  815. @see storeableDateFormat:
  816. @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.
  817. */
  818. - (void)setDateFormat:(NSDateFormatter * _Nullable)format;
  819. /** Convert the supplied NSString to NSDate, using the current database formatter.
  820. @param s `NSString` to convert to `NSDate`.
  821. @return The `NSDate` object; or `nil` if no formatter is set.
  822. @see hasDateFormatter
  823. @see setDateFormat:
  824. @see dateFromString:
  825. @see stringFromDate:
  826. @see storeableDateFormat:
  827. */
  828. - (NSDate * _Nullable)dateFromString:(NSString *)s;
  829. /** Convert the supplied NSDate to NSString, using the current database formatter.
  830. @param date `NSDate` of date to convert to `NSString`.
  831. @return The `NSString` representation of the date; `nil` if no formatter is set.
  832. @see hasDateFormatter
  833. @see setDateFormat:
  834. @see dateFromString:
  835. @see stringFromDate:
  836. @see storeableDateFormat:
  837. */
  838. - (NSString * _Nullable)stringFromDate:(NSDate *)date;
  839. @end
  840. /** Objective-C wrapper for `sqlite3_stmt`
  841. 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.
  842. ### See also
  843. - `<FMDatabase>`
  844. - `<FMResultSet>`
  845. - [`sqlite3_stmt`](http://www.sqlite.org/c3ref/stmt.html)
  846. */
  847. @interface FMStatement : NSObject {
  848. void *_statement;
  849. NSString *_query;
  850. long _useCount;
  851. BOOL _inUse;
  852. }
  853. ///-----------------
  854. /// @name Properties
  855. ///-----------------
  856. /** Usage count */
  857. @property (atomic, assign) long useCount;
  858. /** SQL statement */
  859. @property (atomic, retain) NSString *query;
  860. /** SQLite sqlite3_stmt
  861. @see [`sqlite3_stmt`](http://www.sqlite.org/c3ref/stmt.html)
  862. */
  863. @property (atomic, assign) void *statement;
  864. /** Indication of whether the statement is in use */
  865. @property (atomic, assign) BOOL inUse;
  866. ///----------------------------
  867. /// @name Closing and Resetting
  868. ///----------------------------
  869. /** Close statement */
  870. - (void)close;
  871. /** Reset statement */
  872. - (void)reset;
  873. @end
  874. #pragma clang diagnostic pop
  875. NS_ASSUME_NONNULL_END