FMDatabase.h 52 KB

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