diff --git a/sqflite/darwin/Classes/SqfliteCursor.h b/sqflite/darwin/Classes/SqfliteCursor.h index a824df92..e1e9d097 100644 --- a/sqflite/darwin/Classes/SqfliteCursor.h +++ b/sqflite/darwin/Classes/SqfliteCursor.h @@ -8,12 +8,12 @@ #define SqfliteCursor_h // Cursor information -@class FMResultSet; +@class SqfliteDarwinResultSet; @interface SqfliteCursor : NSObject @property (atomic, retain) NSNumber* cursorId; @property (atomic, retain) NSNumber* pageSize; -@property (atomic, retain) FMResultSet *resultSet; +@property (atomic, retain) SqfliteDarwinResultSet *resultSet; @end diff --git a/sqflite/darwin/Classes/SqfliteCursor.m b/sqflite/darwin/Classes/SqfliteCursor.m index 59a879dd..65d11856 100644 --- a/sqflite/darwin/Classes/SqfliteCursor.m +++ b/sqflite/darwin/Classes/SqfliteCursor.m @@ -1,5 +1,5 @@ #import "SqfliteCursor.h" -#import "SqfliteFmdbImport.m" +#import "SqfliteDarwinImport.h" @implementation SqfliteCursor diff --git a/sqflite/darwin/Classes/SqfliteDarwinDB.h b/sqflite/darwin/Classes/SqfliteDarwinDB.h new file mode 100644 index 00000000..d872fe43 --- /dev/null +++ b/sqflite/darwin/Classes/SqfliteDarwinDB.h @@ -0,0 +1,9 @@ +#import + +FOUNDATION_EXPORT double SqfliteDarwinDBVersionNumber; +FOUNDATION_EXPORT const unsigned char SqfliteDarwinDBVersionString[]; + +#import "SqfliteDarwinDatabase.h" +#import "SqfliteDarwinResultSet.h" +#import "SqfliteDarwinDatabaseAdditions.h" +#import "SqfliteDarwinDatabaseQueue.h" diff --git a/sqflite/darwin/Classes/SqfliteDarwinDatabase.h b/sqflite/darwin/Classes/SqfliteDarwinDatabase.h new file mode 100644 index 00000000..08684dc9 --- /dev/null +++ b/sqflite/darwin/Classes/SqfliteDarwinDatabase.h @@ -0,0 +1,1493 @@ +#import +#import "SqfliteDarwinResultSet.h" + +NS_ASSUME_NONNULL_BEGIN + +#if ! __has_feature(objc_arc) + #define SqfliteDarwinDBAutorelease(__v) ([__v autorelease]); + #define SqfliteDarwinDBReturnAutoreleased SqfliteDarwinDBAutorelease + + #define SqfliteDarwinDBRetain(__v) ([__v retain]); + #define SqfliteDarwinDBReturnRetained SqfliteDarwinDBRetain + + #define SqfliteDarwinDBRelease(__v) ([__v release]); + + #define SqfliteDarwinDBDispatchQueueRelease(__v) (dispatch_release(__v)); +#else + // -fobjc-arc + #define SqfliteDarwinDBAutorelease(__v) + #define SqfliteDarwinDBReturnAutoreleased(__v) (__v) + + #define SqfliteDarwinDBRetain(__v) + #define SqfliteDarwinDBReturnRetained(__v) (__v) + + #define SqfliteDarwinDBRelease(__v) + +// If OS_OBJECT_USE_OBJC=1, then the dispatch objects will be treated like ObjC objects +// and will participate in ARC. +// See the section on "Dispatch Queues and Automatic Reference Counting" in "Grand Central Dispatch (GCD) Reference" for details. + #if OS_OBJECT_USE_OBJC + #define SqfliteDarwinDBDispatchQueueRelease(__v) + #else + #define SqfliteDarwinDBDispatchQueueRelease(__v) (dispatch_release(__v)); + #endif +#endif + +#if !__has_feature(objc_instancetype) + #define instancetype id +#endif + +/** + Callback block used by @c executeStatements:withResultBlock: + */ +typedef int(^SqfliteDarwinDBExecuteStatementsCallbackBlock)(NSDictionary *resultsDictionary); + +/** + Enumeration used in checkpoint methods. + */ +typedef NS_ENUM(int, SqfliteDarwinDBCheckpointMode) { + SqfliteDarwinDBCheckpointModePassive = 0, // SQLITE_CHECKPOINT_PASSIVE, + SqfliteDarwinDBCheckpointModeFull = 1, // SQLITE_CHECKPOINT_FULL, + SqfliteDarwinDBCheckpointModeRestart = 2, // SQLITE_CHECKPOINT_RESTART, + SqfliteDarwinDBCheckpointModeTruncate = 3 // SQLITE_CHECKPOINT_TRUNCATE +}; + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wobjc-interface-ivars" + +/** A SQLite ([https://sqlite.org/](https://sqlite.org/)) Objective-C wrapper. + + Usage + + The three main classes in SqfliteDarwinDB are: + + - @c SqfliteDarwinDatabase - Represents a single SQLite database. Used for executing SQL statements. + + - @c SqfliteDarwinResultSet - Represents the results of executing a query on an @c SqfliteDarwinDatabase . + + - @c SqfliteDarwinDatabaseQueue - If you want to perform queries and updates on multiple threads, you'll want to use this class. + + See also + + - @c SqfliteDarwinDatabasePool - A pool of @c SqfliteDarwinDatabase objects + + - @c SqfliteDarwinStatement - A wrapper for @c sqlite_stmt + + External links + + - [SqfliteDarwinDB on GitHub](https://github.com/ccgus/fmdb) including introductory documentation + - [SQLite web site](https://sqlite.org/) + - [SqfliteDarwinDB mailing list](http://groups.google.com/group/fmdb) + - [SQLite FAQ](https://sqlite.org/faq.html) + + @warning Do not instantiate a single @c SqfliteDarwinDatabase object and use it across multiple threads. Instead, use @c SqfliteDarwinDatabaseQueue . + + */ + +@interface SqfliteDarwinDatabase : NSObject + +///----------------- +/// @name Properties +///----------------- + +/** Whether should trace execution */ + +@property (atomic, assign) BOOL traceExecution; + +/** Whether checked out or not */ + +@property (atomic, assign) BOOL checkedOut; + +/** Crash on errors */ + +@property (atomic, assign) BOOL crashOnErrors; + +/** Logs errors */ + +@property (atomic, assign) BOOL logsErrors; + +/** Dictionary of cached statements */ + +@property (atomic, retain, nullable) NSMutableDictionary *cachedStatements; + +///--------------------- +/// @name Initialization +///--------------------- + +/** Create a @c SqfliteDarwinDatabase object. + + An @c SqfliteDarwinDatabase is created with a path to a SQLite database file. This path can be one of these three: + + 1. A file system path. The file does not have to exist on disk. If it does not exist, it is created for you. + + 2. An zero-length string. An empty database is created at a temporary location. This database is deleted with the @c SqfliteDarwinDatabase connection is closed. + + 3. @c nil . An in-memory database is created. This database will be destroyed with the @c SqfliteDarwinDatabase connection is closed. + + For example, to open a database in the app's “Application Support” directory: + +@code +NSURL *folder = [[NSFileManager defaultManager] URLForDirectory:NSApplicationSupportDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:true error:&error]; +NSURL *fileURL = [folder URLByAppendingPathComponent:@"test.db"]; +SqfliteDarwinDatabase *db = [SqfliteDarwinDatabase databaseWithPath:fileURL.path]; +@endcode + + (For more information on temporary and in-memory databases, read the sqlite documentation on the subject: [https://sqlite.org/inmemorydb.html](https://sqlite.org/inmemorydb.html)) + + @param inPath Path of database file + + @return @c SqfliteDarwinDatabase object if successful; @c nil if failure. + + */ + ++ (instancetype)databaseWithPath:(NSString * _Nullable)inPath; + +/** Create a @c SqfliteDarwinDatabase object. + + An @c SqfliteDarwinDatabase is created with a path to a SQLite database file. This path can be one of these three: + + 1. A file system URL. The file does not have to exist on disk. If it does not exist, it is created for you. + + 2. @c nil . An in-memory database is created. This database will be destroyed with the @c SqfliteDarwinDatabase connection is closed. + + For example, to open a database in the app's “Application Support” directory: + +@code +NSURL *folder = [[NSFileManager defaultManager] URLForDirectory:NSApplicationSupportDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:true error:&error]; +NSURL *fileURL = [folder URLByAppendingPathComponent:@"test.db"]; +SqfliteDarwinDatabase *db = [SqfliteDarwinDatabase databaseWithURL:fileURL]; +@endcode + + (For more information on temporary and in-memory databases, read the sqlite documentation on the subject: [https://sqlite.org/inmemorydb.html](https://sqlite.org/inmemorydb.html)) + + @param url The local file URL (not remote URL) of database file + + @return @c SqfliteDarwinDatabase object if successful; @c nil if failure. + + */ + ++ (instancetype)databaseWithURL:(NSURL * _Nullable)url; + +/** Initialize a @c SqfliteDarwinDatabase object. + + An @c SqfliteDarwinDatabase is created with a path to a SQLite database file. This path can be one of these three: + + 1. A file system path. The file does not have to exist on disk. If it does not exist, it is created for you. + + 2. A zero-length string. An empty database is created at a temporary location. This database is deleted with the @c SqfliteDarwinDatabase connection is closed. + + 3. @c nil . An in-memory database is created. This database will be destroyed with the @c SqfliteDarwinDatabase connection is closed. + + For example, to open a database in the app's “Application Support” directory: + + @code + NSURL *folder = [[NSFileManager defaultManager] URLForDirectory:NSApplicationSupportDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:true error:&error]; + NSURL *fileURL = [folder URLByAppendingPathComponent:@"test.db"]; + SqfliteDarwinDatabase *db = [[SqfliteDarwinDatabase alloc] initWithPath:fileURL.path]; + @endcode + + + (For more information on temporary and in-memory databases, read the sqlite documentation on the subject: [https://sqlite.org/inmemorydb.html](https://sqlite.org/inmemorydb.html)) + + @param path Path of database file. + + @return @c SqfliteDarwinDatabase object if successful; @c nil if failure. + + */ + +- (instancetype)initWithPath:(NSString * _Nullable)path; + +/** Initialize a @c SqfliteDarwinDatabase object. + + An @c SqfliteDarwinDatabase is created with a local file URL to a SQLite database file. This path can be one of these three: + + 1. A file system URL. The file does not have to exist on disk. If it does not exist, it is created for you. + + 2. @c nil . An in-memory database is created. This database will be destroyed with the @c SqfliteDarwinDatabase connection is closed. + + For example, to open a database in the app's “Application Support” directory: + + @code + NSURL *folder = [[NSFileManager defaultManager] URLForDirectory:NSApplicationSupportDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:true error:&error]; + NSURL *fileURL = [folder URLByAppendingPathComponent:@"test.db"]; + SqfliteDarwinDatabase *db = [[SqfliteDarwinDatabase alloc] initWithURL:fileURL]; + @endcode + + (For more information on temporary and in-memory databases, read the sqlite documentation on the subject: [https://sqlite.org/inmemorydb.html](https://sqlite.org/inmemorydb.html)) + + @param url The file @c NSURL of database file. + + @return @c SqfliteDarwinDatabase object if successful; @c nil if failure. + + */ + +- (instancetype)initWithURL:(NSURL * _Nullable)url; + +///----------------------------------- +/// @name Opening and closing database +///----------------------------------- + +/// Is the database open or not? + +@property (nonatomic) BOOL isOpen; + +/** Opening a new database connection + + The database is opened for reading and writing, and is created if it does not already exist. + + @return @c YES if successful, @c NO on error. + + @see [sqlite3_open()](https://sqlite.org/c3ref/open.html) + @see openWithFlags: + @see close + */ + +- (BOOL)open; + +/** Opening a new database connection with flags and an optional virtual file system (VFS) + + @param flags One of the following three values, optionally combined with the @c SQLITE_OPEN_NOMUTEX , @c SQLITE_OPEN_FULLMUTEX , @c SQLITE_OPEN_SHAREDCACHE , @c SQLITE_OPEN_PRIVATECACHE , and/or @c SQLITE_OPEN_URI flags: + +@code +SQLITE_OPEN_READONLY +@endcode + + The database is opened in read-only mode. If the database does not already exist, an error is returned. + +@code +SQLITE_OPEN_READWRITE +@endcode + + 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. + +@code +SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE +@endcode + + 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 @c open method. + + @return @c YES if successful, @c NO on error. + + @see [sqlite3_open_v2()](https://sqlite.org/c3ref/open.html) + @see open + @see close + */ + +- (BOOL)openWithFlags:(int)flags; + +/** Opening a new database connection with flags and an optional virtual file system (VFS) + + @param flags One of the following three values, optionally combined with the @c SQLITE_OPEN_NOMUTEX , `SQLITE_OPEN_FULLMUTEX`, `SQLITE_OPEN_SHAREDCACHE`, @c SQLITE_OPEN_PRIVATECACHE , and/or @c SQLITE_OPEN_URI flags: + +@code +SQLITE_OPEN_READONLY +@endcode + + The database is opened in read-only mode. If the database does not already exist, an error is returned. + +@code +SQLITE_OPEN_READWRITE +@endcode + + 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. + +@code +SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE +@endcode + + 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 @c open method. + + @param vfsName If vfs is given the value is passed to the vfs parameter of sqlite3_open_v2. + + @return @c YES if successful, @c NO on error. + + @see [sqlite3_open_v2()](https://sqlite.org/c3ref/open.html) + @see open + @see close + */ + +- (BOOL)openWithFlags:(int)flags vfs:(NSString * _Nullable)vfsName; + +/** Closing a database connection + + @return @c YES if success, @c NO on error. + + @see [sqlite3_close()](https://sqlite.org/c3ref/close.html) + @see open + @see openWithFlags: + */ + +- (BOOL)close; + +/** Test to see if we have a good connection to the database. + + This will confirm whether: + + - is database open + + - if open, it will try a simple @c SELECT statement and confirm that it succeeds. + + @return @c YES if everything succeeds, @c NO on failure. + */ + +@property (nonatomic, readonly) BOOL goodConnection; + + +///---------------------- +/// @name Perform updates +///---------------------- + +/** Execute single update statement + + This method executes a single SQL update statement (i.e. any SQL that does not return results, such as @c UPDATE , @c INSERT , or @c DELETE . This method employs [`sqlite3_prepare_v2`](https://sqlite.org/c3ref/prepare.html), [`sqlite3_bind`](https://sqlite.org/c3ref/bind_blob.html) to bind values to `?` placeholders in the SQL with the optional list of parameters, and [`sqlite_step`](https://sqlite.org/c3ref/step.html) to perform the update. + + The optional values provided to this method should be objects (e.g. @c NSString , @c NSNumber , @c NSNull , @c NSDate , and @c NSData objects), not fundamental data types (e.g. @c int , @c long , @c 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 @c description method. + + @param sql The SQL to be performed, with optional `?` placeholders. This can be followed by iptional parameters to bind to `?` placeholders in the SQL statement. These should be Objective-C objects (e.g. @c NSString , @c NSNumber , etc.), not fundamental C data types (e.g. @c int , etc.). + + @param outErr A reference to the @c NSError pointer to be updated with an auto released @c NSError object if an error if an error occurs. If @c nil , no @c NSError object will be returned. + + @return @c YES upon success; @c NO upon failure. If failed, you can call @c lastError , @c lastErrorCode , or @c lastErrorMessage for diagnostic information regarding the failure. + + @see lastError + @see lastErrorCode + @see lastErrorMessage + @see [`sqlite3_bind`](https://sqlite.org/c3ref/bind_blob.html) + */ + +- (BOOL)executeUpdate:(NSString*)sql withErrorAndBindings:(NSError * _Nullable __autoreleasing *)outErr, ...; + +/** Execute single update statement + + @see executeUpdate:withErrorAndBindings: + + @warning **Deprecated**: Please use `` instead. + */ + +- (BOOL)update:(NSString*)sql withErrorAndBindings:(NSError * _Nullable __autoreleasing *)outErr, ... __deprecated_msg("Use executeUpdate:withErrorAndBindings: instead");; + +/** Execute single update statement + + This method executes a single SQL update statement (i.e. any SQL that does not return results, such as @c UPDATE , @c INSERT , or @c DELETE . This method employs [`sqlite3_prepare_v2`](https://sqlite.org/c3ref/prepare.html), [`sqlite3_bind`](https://sqlite.org/c3ref/bind_blob.html) to bind values to `?` placeholders in the SQL with the optional list of parameters, and [`sqlite_step`](https://sqlite.org/c3ref/step.html) to perform the update. + + The optional values provided to this method should be objects (e.g. @c NSString , @c NSNumber , @c NSNull , @c NSDate , and @c NSData objects), not fundamental data types (e.g. @c int , @c long , @c 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 @c description method. + + @param sql The SQL to be performed, with optional `?` placeholders, followed by optional parameters to bind to `?` placeholders in the SQL statement. These should be Objective-C objects (e.g. @c NSString , @c NSNumber , etc.), not fundamental C data types (e.g. @c int , etc.). + + @return @c YES upon success; @c NO upon failure. If failed, you can call @c lastError , @c lastErrorCode , or @c lastErrorMessage for diagnostic information regarding the failure. + + @see lastError + @see lastErrorCode + @see lastErrorMessage + @see [`sqlite3_bind`](https://sqlite.org/c3ref/bind_blob.html) + + @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 @c stringWithFormat to manually build SQL statements, which can be problematic if the values happened to include any characters that needed to be quoted. + + @note You cannot use this method from Swift due to incompatibilities between Swift and Objective-C variadic implementations. Consider using `` instead. + */ + +- (BOOL)executeUpdate:(NSString*)sql, ...; + +/** Execute single update statement + + This method executes a single SQL update statement (i.e. any SQL that does not return results, such as @c UPDATE , @c INSERT , or @c DELETE . This method employs [`sqlite3_prepare_v2`](https://sqlite.org/c3ref/prepare.html) and [`sqlite_step`](https://sqlite.org/c3ref/step.html) to perform the update. Unlike the other @c 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. + + @param format The SQL to be performed, with `printf`-style escape sequences, followed by optional parameters to bind to use in conjunction with the `printf`-style escape sequences in the SQL statement. + + @return @c YES upon success; @c NO upon failure. If failed, you can call @c lastError , @c lastErrorCode , or @c lastErrorMessage for diagnostic information regarding the failure. + + @see executeUpdate: + @see lastError + @see lastErrorCode + @see lastErrorMessage + + @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 + +@code +[db executeUpdateWithFormat:@"INSERT INTO test (name) VALUES (%@)", @"Gus"]; +@endcode + + is actually replacing the `%@` with `?` placeholder, and then performing something equivalent to `` + +@code +[db executeUpdate:@"INSERT INTO test (name) VALUES (?)", @"Gus"]; +@endcode + + 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 @c NSString method @c stringWithFormat ), but rather simply `VALUES (%@)`. + */ + +- (BOOL)executeUpdateWithFormat:(NSString *)format, ... NS_FORMAT_FUNCTION(1,2); + +/** Execute single update statement + + This method executes a single SQL update statement (i.e. any SQL that does not return results, such as @c UPDATE , @c INSERT , or @c DELETE . This method employs [`sqlite3_prepare_v2`](https://sqlite.org/c3ref/prepare.html) and [`sqlite3_bind`](https://sqlite.org/c3ref/bind_blob.html) binding any `?` placeholders in the SQL with the optional list of parameters. + + The optional values provided to this method should be objects (e.g. @c NSString , @c NSNumber , @c NSNull , @c NSDate , and @c NSData objects), not fundamental data types (e.g. @c int , @c long , @c 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 @c description method. + + @param sql The SQL to be performed, with optional `?` placeholders. + + @param arguments A @c NSArray of objects to be used when binding values to the `?` placeholders in the SQL statement. + + @return @c YES upon success; @c NO upon failure. If failed, you can call @c lastError , @c lastErrorCode , or @c lastErrorMessage for diagnostic information regarding the failure. + + @see executeUpdate:values:error: + @see lastError + @see lastErrorCode + @see lastErrorMessage + */ + +- (BOOL)executeUpdate:(NSString*)sql withArgumentsInArray:(NSArray *)arguments; + +/** Execute single update statement + + This method executes a single SQL update statement (i.e. any SQL that does not return results, such as @c UPDATE , @c INSERT , or @c DELETE . This method employs [`sqlite3_prepare_v2`](https://sqlite.org/c3ref/prepare.html) and [`sqlite3_bind`](https://sqlite.org/c3ref/bind_blob.html) binding any `?` placeholders in the SQL with the optional list of parameters. + + The optional values provided to this method should be objects (e.g. @c NSString , @c NSNumber , @c NSNull , @c NSDate , and @c NSData objects), not fundamental data types (e.g. @c int , @c long , @c 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 @c description method. + + This is similar to @c executeUpdate:withArgumentsInArray: , except that this also accepts a pointer to a @c NSError pointer, so that errors can be returned. + + In Swift, this throws errors, as if it were defined as follows: + +@code +func executeUpdate(sql: String, values: [Any]?) throws -> Bool { } +@endcode + + @param sql The SQL to be performed, with optional `?` placeholders. + + @param values A @c NSArray of objects to be used when binding values to the `?` placeholders in the SQL statement. + + @param error A @c NSError object to receive any error object (if any). + + @return @c YES upon success; @c NO upon failure. If failed, you can call @c lastError , @c lastErrorCode , or @c lastErrorMessage for diagnostic information regarding the failure. + + @see lastError + @see lastErrorCode + @see lastErrorMessage + + */ + +- (BOOL)executeUpdate:(NSString*)sql values:(NSArray * _Nullable)values error:(NSError * _Nullable __autoreleasing *)error; + +/** Execute single update statement + + This method executes a single SQL update statement (i.e. any SQL that does not return results, such as @c UPDATE , @c INSERT , or @c DELETE . This method employs [`sqlite3_prepare_v2`](https://sqlite.org/c3ref/prepare.html) and [`sqlite_step`](https://sqlite.org/c3ref/step.html) to perform the update. Unlike the other @c executeUpdate methods, this uses printf-style formatters (e.g. `%s`, `%d`, etc.) to build the SQL. + + The optional values provided to this method should be objects (e.g. @c NSString , @c NSNumber , @c NSNull , @c NSDate , and @c NSData objects), not fundamental data types (e.g. @c int , @c long , @c 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 @c description method. + + @param sql The SQL to be performed, with optional `?` placeholders. + + @param arguments A @c NSDictionary of objects keyed by column names that will be used when binding values to the `?` placeholders in the SQL statement. + + @return @c YES upon success; @c NO upon failure. If failed, you can call @c lastError , @c lastErrorCode , or @c lastErrorMessage for diagnostic information regarding the failure. + + @see lastError + @see lastErrorCode + @see lastErrorMessage +*/ + +- (BOOL)executeUpdate:(NSString*)sql withParameterDictionary:(NSDictionary *)arguments; + + +/** Execute single update statement + + This method executes a single SQL update statement (i.e. any SQL that does not return results, such as @c UPDATE , @c INSERT , or @c DELETE . This method employs [`sqlite3_prepare_v2`](https://sqlite.org/c3ref/prepare.html) and [`sqlite_step`](https://sqlite.org/c3ref/step.html) to perform the update. Unlike the other @c executeUpdate methods, this uses printf-style formatters (e.g. `%s`, `%d`, etc.) to build the SQL. + + The optional values provided to this method should be objects (e.g. @c NSString , @c NSNumber , @c NSNull , @c NSDate , and @c NSData objects), not fundamental data types (e.g. @c int , @c long , @c 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 @c description method. + + @param sql The SQL to be performed, with optional `?` placeholders. + + @param args A `va_list` of arguments. + + @return @c YES upon success; @c NO upon failure. If failed, you can call @c lastError , @c lastErrorCode , or @c lastErrorMessage for diagnostic information regarding the failure. + + @see lastError + @see lastErrorCode + @see lastErrorMessage + */ + +- (BOOL)executeUpdate:(NSString*)sql withVAList: (va_list)args; + +/** Execute multiple SQL statements + + 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 @c sqlite3_exec . + + @param sql The SQL to be performed + + @return @c YES upon success; @c NO upon failure. If failed, you can call @c lastError , @c lastErrorCode , or @c lastErrorMessage for diagnostic information regarding the failure. + + @see executeStatements:withResultBlock: + @see [sqlite3_exec()](https://sqlite.org/c3ref/exec.html) + + */ + +- (BOOL)executeStatements:(NSString *)sql; + +/** Execute multiple SQL statements with callback handler + + 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`. + + @param sql The SQL to be performed. + @param block A block that will be called for any result sets returned by any SQL statements. + Note, if you supply this block, it must return integer value, zero upon success (this would be a good opportunity to use @c SQLITE_OK ), + 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. + This may be @c nil if you don't care to receive any results. + + @return @c YES upon success; @c NO upon failure. If failed, you can call @c lastError , + @c lastErrorCode , or @c lastErrorMessage for diagnostic information regarding the failure. + + @see executeStatements: + @see [sqlite3_exec()](https://sqlite.org/c3ref/exec.html) + + */ + +- (BOOL)executeStatements:(NSString *)sql withResultBlock:(__attribute__((noescape)) SqfliteDarwinDBExecuteStatementsCallbackBlock _Nullable)block; + +/** Last insert rowid + + 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. + + This routine returns the rowid of the most recent successful @c 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 @c INSERT statements have ever occurred on that database connection, zero is returned. + + @return The rowid of the last inserted row. + + @see [sqlite3_last_insert_rowid()](https://sqlite.org/c3ref/last_insert_rowid.html) + + */ + +@property (nonatomic, readonly) int64_t lastInsertRowId; + +/** The number of rows changed by prior SQL statement. + + 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 @c INSERT , @c UPDATE , or @c DELETE statement are counted. + + @return The number of rows changed by prior SQL statement. + + @see [sqlite3_changes()](https://sqlite.org/c3ref/changes.html) + + */ + +@property (nonatomic, readonly) int changes; + + +///------------------------- +/// @name Retrieving results +///------------------------- + +/** Execute select statement + + Executing queries returns an @c SqfliteDarwinResultSet object if successful, and @c nil upon failure. Like executing updates, there is a variant that accepts an `NSError **` parameter. Otherwise you should use the @c lastErrorMessage and @c lastErrorMessage methods to determine why a query failed. + + In order to iterate through the results of your query, you use a `while()` loop. You also need to "step" (via `<[SqfliteDarwinResultSet next]>`) from one record to the other. + + This method employs [`sqlite3_bind`](https://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 @c NSString , @c NSNumber , @c NSNull , @c NSDate , and @c NSData objects. All other object types will be interpreted as text values using the object's @c description method. + + @param sql The SELECT statement to be performed, with optional `?` placeholders, followed by optional parameters to bind to `?` placeholders in the SQL statement. These should be Objective-C objects (e.g. @c NSString , @c NSNumber , etc.), not fundamental C data types (e.g. @c int , etc.). + + @return A @c SqfliteDarwinResultSet for the result set upon success; @c nil upon failure. If failed, you can call @c lastError , @c lastErrorCode , or @c lastErrorMessage for diagnostic information regarding the failure. + + @see SqfliteDarwinResultSet + @see [`SqfliteDarwinResultSet next`](<[SqfliteDarwinResultSet next]>) + @see [`sqlite3_bind`](https://sqlite.org/c3ref/bind_blob.html) + + @note You cannot use this method from Swift due to incompatibilities between Swift and Objective-C variadic implementations. Consider using `` instead. + */ + +- (SqfliteDarwinResultSet * _Nullable)executeQuery:(NSString*)sql, ...; + +/** Execute select statement + + Executing queries returns an @c SqfliteDarwinResultSet object if successful, and @c nil upon failure. Like executing updates, there is a variant that accepts an `NSError **` parameter. Otherwise you should use the @c lastErrorMessage and @c lastErrorMessage methods to determine why a query failed. + + In order to iterate through the results of your query, you use a `while()` loop. You also need to "step" (via `<[SqfliteDarwinResultSet next]>`) from one record to the other. + + @param format The SQL to be performed, with `printf`-style escape sequences, followed by ptional parameters to bind to use in conjunction with the `printf`-style escape sequences in the SQL statement. + + @return A @c SqfliteDarwinResultSet for the result set upon success; @c nil upon failure. If failed, you can call @c lastError , @c lastErrorCode , or @c lastErrorMessage for diagnostic information regarding the failure. + + @see executeQuery: + @see SqfliteDarwinResultSet + @see [`SqfliteDarwinResultSet next`](<[SqfliteDarwinResultSet next]>) + + @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 + +@code +[db executeQueryWithFormat:@"SELECT * FROM test WHERE name=%@", @"Gus"]; +@endcode + + is actually replacing the `%@` with `?` placeholder, and then performing something equivalent to `` + +@code +[db executeQuery:@"SELECT * FROM test WHERE name=?", @"Gus"]; +@endcode + + 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 @c WHERE clause was _not_ `WHERE name='%@'` (like you might have to do if you built a SQL statement using @c NSString method @c stringWithFormat ), but rather simply `WHERE name=%@`. + + */ + +- (SqfliteDarwinResultSet * _Nullable)executeQueryWithFormat:(NSString*)format, ... NS_FORMAT_FUNCTION(1,2); + +/** Execute select statement + + Executing queries returns an @c SqfliteDarwinResultSet object if successful, and @c nil upon failure. Like executing updates, there is a variant that accepts an `NSError **` parameter. Otherwise you should use the @c lastErrorMessage and @c lastErrorMessage methods to determine why a query failed. + + In order to iterate through the results of your query, you use a `while()` loop. You also need to "step" (via `<[SqfliteDarwinResultSet next]>`) from one record to the other. + + @param sql The SELECT statement to be performed, with optional `?` placeholders. + + @param arguments A @c NSArray of objects to be used when binding values to the `?` placeholders in the SQL statement. + + @return A @c SqfliteDarwinResultSet for the result set upon success; @c nil upon failure. If failed, you can call @c lastError , @c lastErrorCode , or @c lastErrorMessage for diagnostic information regarding the failure. + + @see -executeQuery:values:error: + @see SqfliteDarwinResultSet + @see [`SqfliteDarwinResultSet next`](<[SqfliteDarwinResultSet next]>) + */ + +- (SqfliteDarwinResultSet * _Nullable)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray *)arguments; + +/** Execute select statement + + Executing queries returns an @c SqfliteDarwinResultSet object if successful, and @c nil upon failure. Like executing updates, there is a variant that accepts an `NSError **` parameter. Otherwise you should use the @c lastErrorMessage and @c lastErrorMessage methods to determine why a query failed. + + In order to iterate through the results of your query, you use a `while()` loop. You also need to "step" (via `<[SqfliteDarwinResultSet next]>`) from one record to the other. + + This is similar to ``, except that this also accepts a pointer to a @c NSError pointer, so that errors can be returned. + + In Swift, this throws errors, as if it were defined as follows: + + `func executeQuery(sql: String, values: [Any]?) throws -> SqfliteDarwinResultSet!` + + @param sql The SELECT statement to be performed, with optional `?` placeholders. + + @param values A @c NSArray of objects to be used when binding values to the `?` placeholders in the SQL statement. + + @param error A @c NSError object to receive any error object (if any). + + @return A @c SqfliteDarwinResultSet for the result set upon success; @c nil upon failure. If failed, you can call @c lastError , @c lastErrorCode , or @c lastErrorMessage for diagnostic information regarding the failure. + + @see SqfliteDarwinResultSet + @see [`SqfliteDarwinResultSet next`](<[SqfliteDarwinResultSet next]>) + + @note When called from Swift, only use the first two parameters, `sql` and `values`. This but throws the error. + + */ + +- (SqfliteDarwinResultSet * _Nullable)executeQuery:(NSString *)sql values:(NSArray * _Nullable)values error:(NSError * _Nullable __autoreleasing *)error; + +/** Execute select statement + + Executing queries returns an @c SqfliteDarwinResultSet object if successful, and @c nil upon failure. Like executing updates, there is a variant that accepts an `NSError **` parameter. Otherwise you should use the @c lastErrorMessage and @c lastErrorMessage methods to determine why a query failed. + + In order to iterate through the results of your query, you use a `while()` loop. You also need to "step" (via `<[SqfliteDarwinResultSet next]>`) from one record to the other. + + @param sql The SELECT statement to be performed, with optional `?` placeholders. + + @param arguments A @c NSDictionary of objects keyed by column names that will be used when binding values to the `?` placeholders in the SQL statement. + + @return A @c SqfliteDarwinResultSet for the result set upon success; @c nil upon failure. If failed, you can call @c lastError , @c lastErrorCode , or @c lastErrorMessage for diagnostic information regarding the failure. + + @see SqfliteDarwinResultSet + @see [`SqfliteDarwinResultSet next`](<[SqfliteDarwinResultSet next]>) + */ + +- (SqfliteDarwinResultSet * _Nullable)executeQuery:(NSString *)sql withParameterDictionary:(NSDictionary * _Nullable)arguments; + + +// Documentation forthcoming. +- (SqfliteDarwinResultSet * _Nullable)executeQuery:(NSString *)sql withVAList:(va_list)args; + +/// Prepare SQL statement. +/// +/// @param sql SQL statement to prepare, generally with `?` placeholders. + +- (SqfliteDarwinResultSet *)prepare:(NSString *)sql; + +///------------------- +/// @name Transactions +///------------------- + +/** Begin a transaction + + @return @c YES on success; @c NO on failure. If failed, you can call @c lastError , @c lastErrorCode , or @c lastErrorMessage for diagnostic information regarding the failure. + + @see commit + @see rollback + @see beginDeferredTransaction + @see isInTransaction + + @warning Unlike SQLite's `BEGIN TRANSACTION`, this method currently performs + an exclusive transaction, not a deferred transaction. This behavior + is likely to change in future versions of SqfliteDarwinDB, whereby this method + will likely eventually adopt standard SQLite behavior and perform + deferred transactions. If you really need exclusive tranaction, it is + recommended that you use @c beginExclusiveTransaction, instead, not + only to make your intent explicit, but also to future-proof your code. + + */ + +- (BOOL)beginTransaction; + +/** Begin a deferred transaction + + @return @c YES on success; @c NO on failure. If failed, you can call @c lastError , @c lastErrorCode , or @c lastErrorMessage for diagnostic information regarding the failure. + + @see commit + @see rollback + @see beginTransaction + @see isInTransaction + */ + +- (BOOL)beginDeferredTransaction; + +/** Begin an immediate transaction + + @return @c YES on success; @c NO on failure. If failed, you can call @c lastError , @c lastErrorCode , or @c lastErrorMessage for diagnostic information regarding the failure. + + @see commit + @see rollback + @see beginTransaction + @see isInTransaction + */ + +- (BOOL)beginImmediateTransaction; + +/** Begin an exclusive transaction + + @return @c YES on success; @c NO on failure. If failed, you can call @c lastError , @c lastErrorCode , or @c lastErrorMessage for diagnostic information regarding the failure. + + @see commit + @see rollback + @see beginTransaction + @see isInTransaction + */ + +- (BOOL)beginExclusiveTransaction; + +/** Commit a transaction + + Commit a transaction that was initiated with either `` or with ``. + + @return @c YES on success; @c NO on failure. If failed, you can call @c lastError , @c lastErrorCode , or @c lastErrorMessage for diagnostic information regarding the failure. + + @see beginTransaction + @see beginDeferredTransaction + @see rollback + @see isInTransaction + */ + +- (BOOL)commit; + +/** Rollback a transaction + + Rollback a transaction that was initiated with either `` or with ``. + + @return @c YES on success; @c NO on failure. If failed, you can call @c lastError , @c lastErrorCode , or @c lastErrorMessage for diagnostic information regarding the failure. + + @see beginTransaction + @see beginDeferredTransaction + @see commit + @see isInTransaction + */ + +- (BOOL)rollback; + +/** Identify whether currently in a transaction or not + + @see beginTransaction + @see beginDeferredTransaction + @see commit + @see rollback + */ + +@property (nonatomic, readonly) BOOL isInTransaction; + +- (BOOL)inTransaction __deprecated_msg("Use isInTransaction property instead"); + + +///---------------------------------------- +/// @name Cached statements and result sets +///---------------------------------------- + +/** Clear cached statements */ + +- (void)clearCachedStatements; + +/** Close all open result sets */ + +- (void)closeOpenResultSets; + +/** Whether database has any open result sets + + @return @c YES if there are open result sets; @c NO if not. + */ + +@property (nonatomic, readonly) BOOL hasOpenResultSets; + +/** Whether should cache statements or not + */ + +@property (nonatomic) BOOL shouldCacheStatements; + +/** Interupt pending database operation + + This method causes any pending database operation to abort and return at its earliest opportunity + + @return @c YES on success; @c NO on failure. If failed, you can call @c lastError , @c lastErrorCode , or @c lastErrorMessage for diagnostic information regarding the failure. + + */ + +- (BOOL)interrupt; + +///------------------------- +/// @name Encryption methods +///------------------------- + +/** Set encryption key. + + @param key The key to be used. + + @return @c YES if success, @c NO on error. + + @see https://www.zetetic.net/sqlcipher/ + + @warning You need to have purchased the sqlite encryption extensions for this method to work. + */ + +- (BOOL)setKey:(NSString*)key; + +/** Reset encryption key + + @param key The key to be used. + + @return @c YES if success, @c NO on error. + + @see https://www.zetetic.net/sqlcipher/ + + @warning You need to have purchased the sqlite encryption extensions for this method to work. + */ + +- (BOOL)rekey:(NSString*)key; + +/** Set encryption key using `keyData`. + + @param keyData The @c NSData to be used. + + @return @c YES if success, @c NO on error. + + @see https://www.zetetic.net/sqlcipher/ + + @warning You need to have purchased the sqlite encryption extensions for this method to work. + */ + +- (BOOL)setKeyWithData:(NSData *)keyData; + +/** Reset encryption key using `keyData`. + + @param keyData The @c NSData to be used. + + @return @c YES if success, @c NO on error. + + @see https://www.zetetic.net/sqlcipher/ + + @warning You need to have purchased the sqlite encryption extensions for this method to work. + */ + +- (BOOL)rekeyWithData:(NSData *)keyData; + + +///------------------------------ +/// @name General inquiry methods +///------------------------------ + +/** The path of the database file. + */ + +@property (nonatomic, readonly, nullable) NSString *databasePath; + +/** The file URL of the database file. + */ + +@property (nonatomic, readonly, nullable) NSURL *databaseURL; + +/** The underlying SQLite handle . + + @return The `sqlite3` pointer. + + */ + +@property (nonatomic, readonly) void *sqliteHandle; + + +///----------------------------- +/// @name Retrieving error codes +///----------------------------- + +/** Last error message + + 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. + + @return @c NSString of the last error message. + + @see [sqlite3_errmsg()](https://sqlite.org/c3ref/errcode.html) + @see lastErrorCode + @see lastError + + */ + +- (NSString*)lastErrorMessage; + +/** Last error code + + 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. + + @return Integer value of the last error code. + + @see [sqlite3_errcode()](https://sqlite.org/c3ref/errcode.html) + @see lastErrorMessage + @see lastError + + */ + +- (int)lastErrorCode; + +/** Last extended error code + + 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. + + @return Integer value of the last extended error code. + + @see [sqlite3_errcode()](https://sqlite.org/c3ref/errcode.html) + @see [2. Primary Result Codes versus Extended Result Codes](https://sqlite.org/rescode.html#primary_result_codes_versus_extended_result_codes) + @see [5. Extended Result Code List](https://sqlite.org/rescode.html#extrc) + @see lastErrorMessage + @see lastError + + */ + +- (int)lastExtendedErrorCode; + +/** Had error + + @return @c YES if there was an error, @c NO if no error. + + @see lastError + @see lastErrorCode + @see lastErrorMessage + + */ + +- (BOOL)hadError; + +/** Last error + + @return @c NSError representing the last error. + + @see lastErrorCode + @see lastErrorMessage + + */ + +- (NSError *)lastError; + + +// description forthcoming +@property (nonatomic) NSTimeInterval maxBusyRetryTimeInterval; + + +///------------------ +/// @name Save points +///------------------ + +/** Start save point + + @param name Name of save point. + + @param outErr A @c NSError object to receive any error object (if any). + + @return @c YES on success; @c NO on failure. If failed, you can call @c lastError , @c lastErrorCode , or @c lastErrorMessage for diagnostic information regarding the failure. + + @see releaseSavePointWithName:error: + @see rollbackToSavePointWithName:error: + */ + +- (BOOL)startSavePointWithName:(NSString*)name error:(NSError * _Nullable __autoreleasing *)outErr; + +/** Release save point + + @param name Name of save point. + + @param outErr A @c NSError object to receive any error object (if any). + + @return @c YES on success; @c NO on failure. If failed, you can call @c lastError , @c lastErrorCode , or @c lastErrorMessage for diagnostic information regarding the failure. + + @see startSavePointWithName:error: + @see rollbackToSavePointWithName:error: + + */ + +- (BOOL)releaseSavePointWithName:(NSString*)name error:(NSError * _Nullable __autoreleasing *)outErr; + +/** Roll back to save point + + @param name Name of save point. + @param outErr A @c NSError object to receive any error object (if any). + + @return @c YES on success; @c NO on failure. If failed, you can call @c lastError , @c lastErrorCode , or @c lastErrorMessage for diagnostic information regarding the failure. + + @see startSavePointWithName:error: + @see releaseSavePointWithName:error: + + */ + +- (BOOL)rollbackToSavePointWithName:(NSString*)name error:(NSError * _Nullable __autoreleasing *)outErr; + +/** Start save point + + @param block Block of code to perform from within save point. + + @return The NSError corresponding to the error, if any. If no error, returns @c nil . + + @see startSavePointWithName:error: + @see releaseSavePointWithName:error: + @see rollbackToSavePointWithName:error: + + */ + +- (NSError * _Nullable)inSavePoint:(__attribute__((noescape)) void (^)(BOOL *rollback))block; + + +///----------------- +/// @name Checkpoint +///----------------- + +/** Performs a WAL checkpoint + + @param checkpointMode The checkpoint mode for @c sqlite3_wal_checkpoint_v2 + @param error The @c NSError corresponding to the error, if any. + @return @c YES on success, otherwise @c NO . + */ +- (BOOL)checkpoint:(SqfliteDarwinDBCheckpointMode)checkpointMode error:(NSError * _Nullable *)error; + +/** Performs a WAL checkpoint + + @param checkpointMode The checkpoint mode for @c sqlite3_wal_checkpoint_v2 + @param name The db name for @c sqlite3_wal_checkpoint_v2 + @param error The @c NSError corresponding to the error, if any. + @return @c YES on success, otherwise @c NO . + */ +- (BOOL)checkpoint:(SqfliteDarwinDBCheckpointMode)checkpointMode name:(NSString * _Nullable)name error:(NSError * _Nullable *)error; + +/** Performs a WAL checkpoint + + @param checkpointMode The checkpoint mode for sqlite3_wal_checkpoint_v2 + @param name The db name for sqlite3_wal_checkpoint_v2 + @param error The NSError corresponding to the error, if any. + @param logFrameCount If not @c 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. + @param checkpointCount If not @c 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. + @return @c YES on success, otherwise @c NO . + */ +- (BOOL)checkpoint:(SqfliteDarwinDBCheckpointMode)checkpointMode name:(NSString * _Nullable)name logFrameCount:(int * _Nullable)logFrameCount checkpointCount:(int * _Nullable)checkpointCount error:(NSError * _Nullable *)error; + +///---------------------------- +/// @name SQLite library status +///---------------------------- + +/** Test to see if the library is threadsafe + + @return @c NO if and only if SQLite was compiled with mutexing code omitted due to the @c SQLITE_THREADSAFE compile-time option being set to 0. + + @see [sqlite3_threadsafe()](https://sqlite.org/c3ref/threadsafe.html) + */ + ++ (BOOL)isSQLiteThreadSafe; + +/** Examine/set limits + + @param type The type of limit. See https://sqlite.org/c3ref/c_limit_attached.html + @param newLimit The new limit value. Use -1 if you don't want to change the limit, but rather only want to check it. + + @return Regardless, returns previous value. + + @see [sqlite3_limit()](https://sqlite.org/c3ref/limit.html) +*/ + +- (int)limitFor:(int)type value:(int)newLimit; + +/** Run-time library version numbers + + @return The sqlite library version string. + + @see [sqlite3_libversion()](https://sqlite.org/c3ref/libversion.html) + */ + ++ (NSString*)sqliteLibVersion; + +/// The SqfliteDarwinDB version number as a string in the form of @c "2.7.8" . +/// +/// If you want to compare version number strings, you can use NSNumericSearch option: +/// +/// @code +/// NSComparisonResult result = [[SqfliteDarwinDatabase SqfliteDarwinDBUserVersion] compare:@"2.11.0" options:NSNumericSearch]; +/// @endcode +/// +/// @returns The version number string. + ++ (NSString*)SqfliteDarwinDBUserVersion; + +/** The SqfliteDarwinDB version + + This returns the SqfliteDarwinDB as hexadecimal value, e.g., @c 0x0243 for version 2.4.3. + + @warning This routine will not work if any component of the version number exceeds 15. + For example, if it is version @c 2.17.3 , this will max out at @c 0x2f3. + For this reason, we would recommend using @c SqfliteDarwinDBUserVersion and with @c NSNumericSearch option, e.g. + + @code + NSComparisonResult result = [[SqfliteDarwinDatabase SqfliteDarwinDBUserVersion] compare:@"2.11.0" options:NSNumericSearch]; + @endcode + + @returns The version number in hexadecimal, e.g., @c 0x0243 for version 2.4.3. If any component exceeds what can be + can be represented in four bits, we'll max it out at @c 0xf . + */ + ++ (SInt32)SqfliteDarwinDBVersion __deprecated_msg("Use SqfliteDarwinDBUserVersion instead"); + +///------------------------ +/// @name Make SQL function +///------------------------ + +/** Adds SQL functions or aggregates or to redefine the behavior of existing SQL functions or aggregates. + + For example: + +@code +[db makeFunctionNamed:@"RemoveDiacritics" arguments:1 block:^(void *context, int argc, void **argv) { + SqliteValueType type = [self.db valueType:argv[0]]; + if (type == SqliteValueTypeNull) { + [self.db resultNullInContext:context]; + return; + } + if (type != SqliteValueTypeText) { + [self.db resultError:@"Expected text" context:context]; + return; + } + NSString *string = [self.db valueString:argv[0]]; + NSString *result = [string stringByFoldingWithOptions:NSDiacriticInsensitiveSearch locale:nil]; + [self.db resultString:result context:context]; +}]; + +SqfliteDarwinResultSet *rs = [db executeQuery:@"SELECT * FROM employees WHERE RemoveDiacritics(first_name) LIKE 'jose'"]; +NSAssert(rs, @"Error %@", [db lastErrorMessage]); +@endcode + + @param name Name of function. + + @param arguments Maximum number of parameters. + + @param block The block of code for the function. + + @see [sqlite3_create_function()](https://sqlite.org/c3ref/create_function.html) + */ + +- (void)makeFunctionNamed:(NSString *)name arguments:(int)arguments block:(void (^)(void *context, int argc, void * _Nonnull * _Nonnull argv))block; + +- (void)makeFunctionNamed:(NSString *)name maximumArguments:(int)count withBlock:(void (^)(void *context, int argc, void * _Nonnull * _Nonnull argv))block __deprecated_msg("Use makeFunctionNamed:arguments:block:"); + +- (SqliteValueType)valueType:(void *)argv; + +/** + Get integer value of parameter in custom function. + + @param value The argument whose value to return. + @return The integer value. + + @see makeFunctionNamed:arguments:block: + */ +- (int)valueInt:(void *)value; + +/** + Get long value of parameter in custom function. + + @param value The argument whose value to return. + @return The long value. + + @see makeFunctionNamed:arguments:block: + */ +- (long long)valueLong:(void *)value; + +/** + Get double value of parameter in custom function. + + @param value The argument whose value to return. + @return The double value. + + @see makeFunctionNamed:arguments:block: + */ +- (double)valueDouble:(void *)value; + +/** + Get @c NSData value of parameter in custom function. + + @param value The argument whose value to return. + @return The data object. + + @see makeFunctionNamed:arguments:block: + */ +- (NSData * _Nullable)valueData:(void *)value; + +/** + Get string value of parameter in custom function. + + @param value The argument whose value to return. + @return The string value. + + @see makeFunctionNamed:arguments:block: + */ +- (NSString * _Nullable)valueString:(void *)value; + +/** + Return null value from custom function. + + @param context The context to which the null value will be returned. + + @see makeFunctionNamed:arguments:block: + */ +- (void)resultNullInContext:(void *)context NS_SWIFT_NAME(resultNull(context:)); + +/** + Return integer value from custom function. + + @param value The integer value to be returned. + @param context The context to which the value will be returned. + + @see makeFunctionNamed:arguments:block: + */ +- (void)resultInt:(int) value context:(void *)context; + +/** + Return long value from custom function. + + @param value The long value to be returned. + @param context The context to which the value will be returned. + + @see makeFunctionNamed:arguments:block: + */ +- (void)resultLong:(long long)value context:(void *)context; + +/** + Return double value from custom function. + + @param value The double value to be returned. + @param context The context to which the value will be returned. + + @see makeFunctionNamed:arguments:block: + */ +- (void)resultDouble:(double)value context:(void *)context; + +/** + Return @c NSData object from custom function. + + @param data The @c NSData object to be returned. + @param context The context to which the value will be returned. + + @see makeFunctionNamed:arguments:block: + */ +- (void)resultData:(NSData *)data context:(void *)context; + +/** + Return string value from custom function. + + @param value The string value to be returned. + @param context The context to which the value will be returned. + + @see makeFunctionNamed:arguments:block: + */ +- (void)resultString:(NSString *)value context:(void *)context; + +/** + Return error string from custom function. + + @param error The error string to be returned. + @param context The context to which the error will be returned. + + @see makeFunctionNamed:arguments:block: + */ +- (void)resultError:(NSString *)error context:(void *)context; + +/** + Return error code from custom function. + + @param errorCode The integer error code to be returned. + @param context The context to which the error will be returned. + + @see makeFunctionNamed:arguments:block: + */ +- (void)resultErrorCode:(int)errorCode context:(void *)context; + +/** + Report memory error in custom function. + + @param context The context to which the error will be returned. + + @see makeFunctionNamed:arguments:block: + */ +- (void)resultErrorNoMemoryInContext:(void *)context NS_SWIFT_NAME(resultErrorNoMemory(context:)); + +/** + Report that string or BLOB is too long to represent in custom function. + + @param context The context to which the error will be returned. + + @see makeFunctionNamed:arguments:block: + */ +- (void)resultErrorTooBigInContext:(void *)context NS_SWIFT_NAME(resultErrorTooBig(context:)); + +///--------------------- +/// @name Date formatter +///--------------------- + +/** Generate an @c NSDateFormatter that won't be broken by permutations of timezones or locales. + + Use this method to generate values to set the dateFormat property. + + Example: + +@code +myDB.dateFormat = [SqfliteDarwinDatabase storeableDateFormat:@"yyyy-MM-dd HH:mm:ss"]; +@endcode + + @param format A valid NSDateFormatter format string. + + @return A @c NSDateFormatter that can be used for converting dates to strings and vice versa. + + @see hasDateFormatter + @see setDateFormat: + @see dateFromString: + @see stringFromDate: + @see storeableDateFormat: + + @warning Note that @c NSDateFormatter is not thread-safe, so the formatter generated by this method should be assigned to only one SqfliteDarwinDB instance and should not be used for other purposes. + + */ + ++ (NSDateFormatter *)storeableDateFormat:(NSString *)format; + +/** Test whether the database has a date formatter assigned. + + @return @c YES if there is a date formatter; @c NO if not. + + @see hasDateFormatter + @see setDateFormat: + @see dateFromString: + @see stringFromDate: + @see storeableDateFormat: + */ + +- (BOOL)hasDateFormatter; + +/** Set to a date formatter to use string dates with sqlite instead of the default UNIX timestamps. + + @param format Set to nil to use UNIX timestamps. Defaults to nil. Should be set using a formatter generated using @c SqfliteDarwinDatabase:storeableDateFormat . + + @see hasDateFormatter + @see setDateFormat: + @see dateFromString: + @see stringFromDate: + @see storeableDateFormat: + + @warning Note there is no direct getter for the @c NSDateFormatter , and you should not use the formatter you pass to SqfliteDarwinDB for other purposes, as @c NSDateFormatter is not thread-safe. + */ + +- (void)setDateFormat:(NSDateFormatter * _Nullable)format; + +/** Convert the supplied NSString to NSDate, using the current database formatter. + + @param s @c NSString to convert to @c NSDate . + + @return The @c NSDate object; or @c nil if no formatter is set. + + @see hasDateFormatter + @see setDateFormat: + @see dateFromString: + @see stringFromDate: + @see storeableDateFormat: + */ + +- (NSDate * _Nullable)dateFromString:(NSString *)s; + +/** Convert the supplied NSDate to NSString, using the current database formatter. + + @param date @c NSDate of date to convert to @c NSString . + + @return The @c NSString representation of the date; @c nil if no formatter is set. + + @see hasDateFormatter + @see setDateFormat: + @see dateFromString: + @see stringFromDate: + @see storeableDateFormat: + */ + +- (NSString * _Nullable)stringFromDate:(NSDate *)date; + +@end + + +/** Objective-C wrapper for @c sqlite3_stmt + + This is a wrapper for a SQLite @c sqlite3_stmt . Generally when using SqfliteDarwinDB you will not need to interact directly with `SqfliteDarwinStatement`, but rather with @c SqfliteDarwinDatabase and @c SqfliteDarwinResultSet only. + + See also + + - @c SqfliteDarwinDatabase + - @c SqfliteDarwinResultSet + - [@c sqlite3_stmt ](https://sqlite.org/c3ref/stmt.html) + */ + +@interface SqfliteDarwinStatement : NSObject { + void *_statement; + NSString *_query; + long _useCount; + BOOL _inUse; +} + +///----------------- +/// @name Properties +///----------------- + +/** Usage count */ + +@property (atomic, assign) long useCount; + +/** SQL statement */ + +@property (atomic, retain) NSString *query; + +/** SQLite sqlite3_stmt + + @see [@c sqlite3_stmt ](https://sqlite.org/c3ref/stmt.html) + */ + +@property (atomic, assign) void *statement; + +/** Indication of whether the statement is in use */ + +@property (atomic, assign) BOOL inUse; + +///---------------------------- +/// @name Closing and Resetting +///---------------------------- + +/** Close statement */ + +- (void)close; + +/** Reset statement */ + +- (void)reset; + +@end + +#pragma clang diagnostic pop + +NS_ASSUME_NONNULL_END diff --git a/sqflite/darwin/Classes/SqfliteDarwinDatabase.m b/sqflite/darwin/Classes/SqfliteDarwinDatabase.m new file mode 100644 index 00000000..6394e0c2 --- /dev/null +++ b/sqflite/darwin/Classes/SqfliteDarwinDatabase.m @@ -0,0 +1,1529 @@ +#import "SqfliteDarwinDatabase.h" +#import +#import + +#if SqfliteDarwinDB_SQLITE_STANDALONE +#import +#else +#import +#endif + +// MARK: - SqfliteDarwinDatabase Private Extension + +NS_ASSUME_NONNULL_BEGIN + +@interface SqfliteDarwinDatabase () { + void* _db; + BOOL _isExecutingStatement; + NSTimeInterval _startBusyRetryTime; + + NSMutableSet *_openResultSets; + NSMutableSet *_openFunctions; + + NSDateFormatter *_dateFormat; +} + +- (SqfliteDarwinResultSet * _Nullable)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray * _Nullable)arrayArgs orDictionary:(NSDictionary * _Nullable)dictionaryArgs orVAList:(va_list)args shouldBind:(BOOL)shouldBind; +- (BOOL)executeUpdate:(NSString *)sql error:(NSError * _Nullable __autoreleasing *)outErr withArgumentsInArray:(NSArray * _Nullable)arrayArgs orDictionary:(NSDictionary * _Nullable)dictionaryArgs orVAList:(va_list)args; + +@end + +// MARK: - SqfliteDarwinResultSet Private Extension + +@interface SqfliteDarwinResultSet () + +- (int)internalStepWithError:(NSError * _Nullable __autoreleasing *)outErr; ++ (instancetype)resultSetWithStatement:(SqfliteDarwinStatement *)statement usingParentDatabase:(SqfliteDarwinDatabase*)aDB shouldAutoClose:(BOOL)shouldAutoClose; + +@end + +NS_ASSUME_NONNULL_END + +// MARK: - SqfliteDarwinDatabase + +@implementation SqfliteDarwinDatabase + +// Because these two properties have all of their accessor methods implemented, +// we have to synthesize them to get the corresponding ivars. The rest of the +// properties have their ivars synthesized automatically for us. + +@synthesize shouldCacheStatements = _shouldCacheStatements; +@synthesize maxBusyRetryTimeInterval = _maxBusyRetryTimeInterval; + +#pragma mark SqfliteDarwinDatabase instantiation and deallocation + ++ (instancetype)databaseWithPath:(NSString *)aPath { + return SqfliteDarwinDBReturnAutoreleased([[self alloc] initWithPath:aPath]); +} + ++ (instancetype)databaseWithURL:(NSURL *)url { + return SqfliteDarwinDBReturnAutoreleased([[self alloc] initWithURL:url]); +} + +- (instancetype)init { + return [self initWithPath:nil]; +} + +- (instancetype)initWithURL:(NSURL *)url { + return [self initWithPath:url.path]; +} + +- (instancetype)initWithPath:(NSString *)path { + + assert(sqlite3_threadsafe()); // whoa there big boy- gotta make sure sqlite it happy with what we're going to do. + + self = [super init]; + + if (self) { + _databasePath = [path copy]; + _openResultSets = [[NSMutableSet alloc] init]; + _db = nil; + _logsErrors = YES; + _crashOnErrors = NO; + _maxBusyRetryTimeInterval = 2; + _isOpen = NO; + } + + return self; +} + +#if ! __has_feature(objc_arc) +- (void)finalize { + [self close]; + [super finalize]; +} +#endif + +- (void)dealloc { + [self close]; + SqfliteDarwinDBRelease(_openResultSets); + SqfliteDarwinDBRelease(_cachedStatements); + SqfliteDarwinDBRelease(_dateFormat); + SqfliteDarwinDBRelease(_databasePath); + SqfliteDarwinDBRelease(_openFunctions); + +#if ! __has_feature(objc_arc) + [super dealloc]; +#endif +} + +- (NSURL *)databaseURL { + return _databasePath ? [NSURL fileURLWithPath:_databasePath] : nil; +} + ++ (NSString*)SqfliteDarwinDBUserVersion { + return @"2.7.8"; +} + ++ (SInt32)SqfliteDarwinDBVersion { + + // we go through these hoops so that we only have to change the version number in a single spot. + static dispatch_once_t once; + static SInt32 SqfliteDarwinDBVersionVal = 0; + + dispatch_once(&once, ^{ + NSString *prodVersion = [self SqfliteDarwinDBUserVersion]; + + while ([[prodVersion componentsSeparatedByString:@"."] count] < 3) { + prodVersion = [prodVersion stringByAppendingString:@".0"]; + } + + NSArray *components = [prodVersion componentsSeparatedByString:@"."]; + for (NSUInteger i = 0; i < 3; i++) { + SInt32 component = [components[i] intValue]; + if (component > 15) { + NSLog(@"SqfliteDarwinDBVersion is invalid: Please use SqfliteDarwinDBUserVersion instead."); + component = 15; + } + SqfliteDarwinDBVersionVal = SqfliteDarwinDBVersionVal << 4 | component; + } + }); + + return SqfliteDarwinDBVersionVal; +} + +#pragma mark SQLite information + ++ (NSString*)sqliteLibVersion { + return [NSString stringWithFormat:@"%s", sqlite3_libversion()]; +} + ++ (BOOL)isSQLiteThreadSafe { + // make sure to read the sqlite headers on this guy! + return sqlite3_threadsafe() != 0; +} + +- (void*)sqliteHandle { + return _db; +} + +- (const char*)sqlitePath { + + if (!_databasePath) { + return ":memory:"; + } + + if ([_databasePath length] == 0) { + return ""; // this creates a temporary database (it's an sqlite thing). + } + + return [_databasePath fileSystemRepresentation]; + +} + +- (int)limitFor:(int)type value:(int)newLimit { + return sqlite3_limit(_db, type, newLimit); +} + +#pragma mark Open and close database + +- (BOOL)open { + if (_isOpen) { + return YES; + } + + // if we previously tried to open and it failed, make sure to close it before we try again + + if (_db) { + [self close]; + } + + // now open database + + int err = sqlite3_open([self sqlitePath], (sqlite3**)&_db ); + if(err != SQLITE_OK) { + NSLog(@"error opening!: %d", err); + return NO; + } + + if (_maxBusyRetryTimeInterval > 0.0) { + // set the handler + [self setMaxBusyRetryTimeInterval:_maxBusyRetryTimeInterval]; + } + + _isOpen = YES; + + return YES; +} + +- (BOOL)openWithFlags:(int)flags { + return [self openWithFlags:flags vfs:nil]; +} + +- (BOOL)openWithFlags:(int)flags vfs:(NSString *)vfsName { +#if SQLITE_VERSION_NUMBER >= 3005000 + if (_isOpen) { + return YES; + } + + // if we previously tried to open and it failed, make sure to close it before we try again + + if (_db) { + [self close]; + } + + // now open database + + int err = sqlite3_open_v2([self sqlitePath], (sqlite3**)&_db, flags, [vfsName UTF8String]); + if(err != SQLITE_OK) { + NSLog(@"error opening!: %d", err); + return NO; + } + + if (_maxBusyRetryTimeInterval > 0.0) { + // set the handler + [self setMaxBusyRetryTimeInterval:_maxBusyRetryTimeInterval]; + } + + _isOpen = YES; + + return YES; +#else + NSLog(@"openWithFlags requires SQLite 3.5"); + return NO; +#endif +} + +- (BOOL)close { + + [self clearCachedStatements]; + [self closeOpenResultSets]; + + if (!_db) { + return YES; + } + + int rc; + BOOL retry; + BOOL triedFinalizingOpenStatements = NO; + + do { + retry = NO; + rc = sqlite3_close(_db); + if (SQLITE_BUSY == rc || SQLITE_LOCKED == rc) { + if (!triedFinalizingOpenStatements) { + triedFinalizingOpenStatements = YES; + sqlite3_stmt *pStmt; + while ((pStmt = sqlite3_next_stmt(_db, nil)) !=0) { + NSLog(@"Closing leaked statement"); + sqlite3_finalize(pStmt); + pStmt = 0x00; + retry = YES; + } + } + } + else if (SQLITE_OK != rc) { + NSLog(@"error closing!: %d", rc); + } + } + while (retry); + + _db = nil; + _isOpen = false; + + return YES; +} + +#pragma mark Busy handler routines + +// NOTE: appledoc seems to choke on this function for some reason; +// so when generating documentation, you might want to ignore the +// .m files so that it only documents the public interfaces outlined +// in the .h files. +// +// This is a known appledoc bug that it has problems with C functions +// within a class implementation, but for some reason, only this +// C function causes problems; the rest don't. Anyway, ignoring the .m +// files with appledoc will prevent this problem from occurring. + +static int SqfliteDarwinDBDatabaseBusyHandler(void *f, int count) { + SqfliteDarwinDatabase *self = (__bridge SqfliteDarwinDatabase*)f; + + if (count == 0) { + self->_startBusyRetryTime = [NSDate timeIntervalSinceReferenceDate]; + return 1; + } + + NSTimeInterval delta = [NSDate timeIntervalSinceReferenceDate] - (self->_startBusyRetryTime); + + if (delta < [self maxBusyRetryTimeInterval]) { + int requestedSleepInMillseconds = (int) arc4random_uniform(50) + 50; + int actualSleepInMilliseconds = sqlite3_sleep(requestedSleepInMillseconds); + if (actualSleepInMilliseconds != requestedSleepInMillseconds) { + NSLog(@"WARNING: Requested sleep of %i milliseconds, but SQLite returned %i. Maybe SQLite wasn't built with HAVE_USLEEP=1?", requestedSleepInMillseconds, actualSleepInMilliseconds); + } + return 1; + } + + return 0; +} + +- (void)setMaxBusyRetryTimeInterval:(NSTimeInterval)timeout { + + _maxBusyRetryTimeInterval = timeout; + + if (!_db) { + return; + } + + if (timeout > 0) { + sqlite3_busy_handler(_db, &SqfliteDarwinDBDatabaseBusyHandler, (__bridge void *)(self)); + } + else { + // turn it off otherwise + sqlite3_busy_handler(_db, nil, nil); + } +} + +- (NSTimeInterval)maxBusyRetryTimeInterval { + return _maxBusyRetryTimeInterval; +} + + +// we no longer make busyRetryTimeout public +// but for folks who don't bother noticing that the interface to SqfliteDarwinDatabase changed, +// we'll still implement the method so they don't get suprise crashes +- (int)busyRetryTimeout { + NSLog(@"%s:%d", __FUNCTION__, __LINE__); + NSLog(@"SqfliteDarwinDB: busyRetryTimeout no longer works, please use maxBusyRetryTimeInterval"); + return -1; +} + +- (void)setBusyRetryTimeout:(int)i { +#pragma unused(i) + NSLog(@"%s:%d", __FUNCTION__, __LINE__); + NSLog(@"SqfliteDarwinDB: setBusyRetryTimeout does nothing, please use setMaxBusyRetryTimeInterval:"); +} + +#pragma mark Result set functions + +- (BOOL)hasOpenResultSets { + return [_openResultSets count] > 0; +} + +- (void)closeOpenResultSets { + + //Copy the set so we don't get mutation errors + NSSet *openSetCopy = SqfliteDarwinDBReturnAutoreleased([_openResultSets copy]); + for (NSValue *rsInWrappedInATastyValueMeal in openSetCopy) { + SqfliteDarwinResultSet *rs = (SqfliteDarwinResultSet *)[rsInWrappedInATastyValueMeal pointerValue]; + + [rs setParentDB:nil]; + [rs close]; + + [_openResultSets removeObject:rsInWrappedInATastyValueMeal]; + } +} + +- (void)resultSetDidClose:(SqfliteDarwinResultSet *)resultSet { + NSValue *setValue = [NSValue valueWithNonretainedObject:resultSet]; + + [_openResultSets removeObject:setValue]; +} + +#pragma mark Cached statements + +- (void)clearCachedStatements { + + for (NSMutableSet *statements in [_cachedStatements objectEnumerator]) { + for (SqfliteDarwinStatement *statement in [statements allObjects]) { + [statement close]; + } + } + + [_cachedStatements removeAllObjects]; +} + +- (SqfliteDarwinStatement*)cachedStatementForQuery:(NSString*)query { + + NSMutableSet* statements = [_cachedStatements objectForKey:query]; + + return [[statements objectsPassingTest:^BOOL(SqfliteDarwinStatement* statement, BOOL *stop) { + + *stop = ![statement inUse]; + return *stop; + + }] anyObject]; +} + + +- (void)setCachedStatement:(SqfliteDarwinStatement*)statement forQuery:(NSString*)query { + NSParameterAssert(query); + if (!query) { + NSLog(@"API misuse, -[SqfliteDarwinDatabase setCachedStatement:forQuery:] query must not be nil"); + return; + } + + query = [query copy]; // in case we got handed in a mutable string... + [statement setQuery:query]; + + NSMutableSet* statements = [_cachedStatements objectForKey:query]; + if (!statements) { + statements = [NSMutableSet set]; + } + + [statements addObject:statement]; + + [_cachedStatements setObject:statements forKey:query]; + + SqfliteDarwinDBRelease(query); +} + +#pragma mark Key routines + +- (BOOL)rekey:(NSString*)key { + NSData *keyData = [NSData dataWithBytes:(void *)[key UTF8String] length:(NSUInteger)strlen([key UTF8String])]; + + return [self rekeyWithData:keyData]; +} + +- (BOOL)rekeyWithData:(NSData *)keyData { +#ifdef SQLITE_HAS_CODEC + if (!keyData) { + return NO; + } + + int rc = sqlite3_rekey(_db, [keyData bytes], (int)[keyData length]); + + if (rc != SQLITE_OK) { + NSLog(@"error on rekey: %d", rc); + NSLog(@"%@", [self lastErrorMessage]); + } + + return (rc == SQLITE_OK); +#else +#pragma unused(keyData) + return NO; +#endif +} + +- (BOOL)setKey:(NSString*)key { + NSData *keyData = [NSData dataWithBytes:[key UTF8String] length:(NSUInteger)strlen([key UTF8String])]; + + return [self setKeyWithData:keyData]; +} + +- (BOOL)setKeyWithData:(NSData *)keyData { +#ifdef SQLITE_HAS_CODEC + if (!keyData) { + return NO; + } + + int rc = sqlite3_key(_db, [keyData bytes], (int)[keyData length]); + + return (rc == SQLITE_OK); +#else +#pragma unused(keyData) + return NO; +#endif +} + +#pragma mark Date routines + ++ (NSDateFormatter *)storeableDateFormat:(NSString *)format { + + NSDateFormatter *result = SqfliteDarwinDBReturnAutoreleased([[NSDateFormatter alloc] init]); + result.dateFormat = format; + result.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0]; + result.locale = SqfliteDarwinDBReturnAutoreleased([[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]); + return result; +} + + +- (BOOL)hasDateFormatter { + return _dateFormat != nil; +} + +- (void)setDateFormat:(NSDateFormatter *)format { + SqfliteDarwinDBAutorelease(_dateFormat); + _dateFormat = SqfliteDarwinDBReturnRetained(format); +} + +- (NSDate *)dateFromString:(NSString *)s { + return [_dateFormat dateFromString:s]; +} + +- (NSString *)stringFromDate:(NSDate *)date { + return [_dateFormat stringFromDate:date]; +} + +#pragma mark State of database + +- (BOOL)goodConnection { + + if (!_isOpen) { + return NO; + } + +#ifdef SQLCIPHER_CRYPTO + // Starting with Xcode8 / iOS 10 we check to make sure we really are linked with + // SQLCipher because there is no longer a linker error if we accidently link + // with unencrypted sqlite library. + // + // https://discuss.zetetic.net/t/important-advisory-sqlcipher-with-xcode-8-and-new-sdks/1688 + + SqfliteDarwinResultSet *rs = [self executeQuery:@"PRAGMA cipher_version"]; + + if ([rs next]) { + NSLog(@"SQLCipher version: %@", rs.resultDictionary[@"cipher_version"]); + + [rs close]; + return YES; + } +#else + SqfliteDarwinResultSet *rs = [self executeQuery:@"select name from sqlite_master where type='table'"]; + + if (rs) { + [rs close]; + return YES; + } +#endif + + return NO; +} + +- (void)warnInUse { + NSLog(@"The SqfliteDarwinDatabase %@ is currently in use.", self); + +#ifndef NS_BLOCK_ASSERTIONS + if (_crashOnErrors) { + NSAssert(false, @"The SqfliteDarwinDatabase %@ is currently in use.", self); + abort(); + } +#endif +} + +- (BOOL)databaseExists { + + if (!_isOpen) { + + NSLog(@"The SqfliteDarwinDatabase %@ is not open.", self); + +#ifndef NS_BLOCK_ASSERTIONS + if (_crashOnErrors) { + NSAssert(false, @"The SqfliteDarwinDatabase %@ is not open.", self); + abort(); + } +#endif + + return NO; + } + + return YES; +} + +#pragma mark Error routines + +- (NSString *)lastErrorMessage { + return [NSString stringWithUTF8String:sqlite3_errmsg(_db)]; +} + +- (BOOL)hadError { + int lastErrCode = [self lastErrorCode]; + + return (lastErrCode > SQLITE_OK && lastErrCode < SQLITE_ROW); +} + +- (int)lastErrorCode { + return sqlite3_errcode(_db); +} + +- (int)lastExtendedErrorCode { + return sqlite3_extended_errcode(_db); +} + +- (NSError*)errorWithMessage:(NSString *)message { + NSDictionary* errorMessage = [NSDictionary dictionaryWithObject:message forKey:NSLocalizedDescriptionKey]; + + return [NSError errorWithDomain:@"SqfliteDarwinDatabase" code:sqlite3_errcode(_db) userInfo:errorMessage]; +} + +- (NSError*)lastError { + return [self errorWithMessage:[self lastErrorMessage]]; +} + +#pragma mark Update information routines + +- (sqlite_int64)lastInsertRowId { + + if (_isExecutingStatement) { + [self warnInUse]; + return NO; + } + + _isExecutingStatement = YES; + + sqlite_int64 ret = sqlite3_last_insert_rowid(_db); + + _isExecutingStatement = NO; + + return ret; +} + +- (int)changes { + if (_isExecutingStatement) { + [self warnInUse]; + return 0; + } + + _isExecutingStatement = YES; + + int ret = sqlite3_changes(_db); + + _isExecutingStatement = NO; + + return ret; +} + +#pragma mark SQL manipulation + +- (int)bindObject:(id)obj toColumn:(int)idx inStatement:(sqlite3_stmt*)pStmt { + + if ((!obj) || ((NSNull *)obj == [NSNull null])) { + return sqlite3_bind_null(pStmt, idx); + } + + // FIXME - someday check the return codes on these binds. + else if ([obj isKindOfClass:[NSData class]]) { + const void *bytes = [obj bytes]; + if (!bytes) { + // it's an empty NSData object, aka [NSData data]. + // Don't pass a NULL pointer, or sqlite will bind a SQL null instead of a blob. + bytes = ""; + } + return sqlite3_bind_blob(pStmt, idx, bytes, (int)[obj length], SQLITE_TRANSIENT); + } + else if ([obj isKindOfClass:[NSDate class]]) { + if (self.hasDateFormatter) + return sqlite3_bind_text(pStmt, idx, [[self stringFromDate:obj] UTF8String], -1, SQLITE_TRANSIENT); + else + return sqlite3_bind_double(pStmt, idx, [obj timeIntervalSince1970]); + } + else if ([obj isKindOfClass:[NSNumber class]]) { + + if (strcmp([obj objCType], @encode(char)) == 0) { + return sqlite3_bind_int(pStmt, idx, [obj charValue]); + } + else if (strcmp([obj objCType], @encode(unsigned char)) == 0) { + return sqlite3_bind_int(pStmt, idx, [obj unsignedCharValue]); + } + else if (strcmp([obj objCType], @encode(short)) == 0) { + return sqlite3_bind_int(pStmt, idx, [obj shortValue]); + } + else if (strcmp([obj objCType], @encode(unsigned short)) == 0) { + return sqlite3_bind_int(pStmt, idx, [obj unsignedShortValue]); + } + else if (strcmp([obj objCType], @encode(int)) == 0) { + return sqlite3_bind_int(pStmt, idx, [obj intValue]); + } + else if (strcmp([obj objCType], @encode(unsigned int)) == 0) { + return sqlite3_bind_int64(pStmt, idx, (long long)[obj unsignedIntValue]); + } + else if (strcmp([obj objCType], @encode(long)) == 0) { + return sqlite3_bind_int64(pStmt, idx, [obj longValue]); + } + else if (strcmp([obj objCType], @encode(unsigned long)) == 0) { + return sqlite3_bind_int64(pStmt, idx, (long long)[obj unsignedLongValue]); + } + else if (strcmp([obj objCType], @encode(long long)) == 0) { + return sqlite3_bind_int64(pStmt, idx, [obj longLongValue]); + } + else if (strcmp([obj objCType], @encode(unsigned long long)) == 0) { + return sqlite3_bind_int64(pStmt, idx, (long long)[obj unsignedLongLongValue]); + } + else if (strcmp([obj objCType], @encode(float)) == 0) { + return sqlite3_bind_double(pStmt, idx, [obj floatValue]); + } + else if (strcmp([obj objCType], @encode(double)) == 0) { + return sqlite3_bind_double(pStmt, idx, [obj doubleValue]); + } + else if (strcmp([obj objCType], @encode(BOOL)) == 0) { + return sqlite3_bind_int(pStmt, idx, ([obj boolValue] ? 1 : 0)); + } + else { + return sqlite3_bind_text(pStmt, idx, [[obj description] UTF8String], -1, SQLITE_TRANSIENT); + } + } + + return sqlite3_bind_text(pStmt, idx, [[obj description] UTF8String], -1, SQLITE_TRANSIENT); +} + +- (void)extractSQL:(NSString *)sql argumentsList:(va_list)args intoString:(NSMutableString *)cleanedSQL arguments:(NSMutableArray *)arguments { + + NSUInteger length = [sql length]; + unichar last = '\0'; + for (NSUInteger i = 0; i < length; ++i) { + id arg = nil; + unichar current = [sql characterAtIndex:i]; + unichar add = current; + if (last == '%') { + switch (current) { + case '@': + arg = va_arg(args, id); + break; + case 'c': + // warning: second argument to 'va_arg' is of promotable type 'char'; this va_arg has undefined behavior because arguments will be promoted to 'int' + arg = [NSString stringWithFormat:@"%c", va_arg(args, int)]; + break; + case 's': + arg = [NSString stringWithUTF8String:va_arg(args, char*)]; + break; + case 'd': + case 'D': + case 'i': + arg = [NSNumber numberWithInt:va_arg(args, int)]; + break; + case 'u': + case 'U': + arg = [NSNumber numberWithUnsignedInt:va_arg(args, unsigned int)]; + break; + case 'h': + i++; + if (i < length && [sql characterAtIndex:i] == 'i') { + // warning: second argument to 'va_arg' is of promotable type 'short'; this va_arg has undefined behavior because arguments will be promoted to 'int' + arg = [NSNumber numberWithShort:(short)(va_arg(args, int))]; + } + else if (i < length && [sql characterAtIndex:i] == 'u') { + // warning: second argument to 'va_arg' is of promotable type 'unsigned short'; this va_arg has undefined behavior because arguments will be promoted to 'int' + arg = [NSNumber numberWithUnsignedShort:(unsigned short)(va_arg(args, uint))]; + } + else { + i--; + } + break; + case 'q': + i++; + if (i < length && [sql characterAtIndex:i] == 'i') { + arg = [NSNumber numberWithLongLong:va_arg(args, long long)]; + } + else if (i < length && [sql characterAtIndex:i] == 'u') { + arg = [NSNumber numberWithUnsignedLongLong:va_arg(args, unsigned long long)]; + } + else { + i--; + } + break; + case 'f': + arg = [NSNumber numberWithDouble:va_arg(args, double)]; + break; + case 'g': + // warning: second argument to 'va_arg' is of promotable type 'float'; this va_arg has undefined behavior because arguments will be promoted to 'double' + arg = [NSNumber numberWithFloat:(float)(va_arg(args, double))]; + break; + case 'l': + i++; + if (i < length) { + unichar next = [sql characterAtIndex:i]; + if (next == 'l') { + i++; + if (i < length && [sql characterAtIndex:i] == 'd') { + //%lld + arg = [NSNumber numberWithLongLong:va_arg(args, long long)]; + } + else if (i < length && [sql characterAtIndex:i] == 'u') { + //%llu + arg = [NSNumber numberWithUnsignedLongLong:va_arg(args, unsigned long long)]; + } + else { + i--; + } + } + else if (next == 'd') { + //%ld + arg = [NSNumber numberWithLong:va_arg(args, long)]; + } + else if (next == 'u') { + //%lu + arg = [NSNumber numberWithUnsignedLong:va_arg(args, unsigned long)]; + } + else { + i--; + } + } + else { + i--; + } + break; + default: + // something else that we can't interpret. just pass it on through like normal + break; + } + } + else if (current == '%') { + // percent sign; skip this character + add = '\0'; + } + + if (arg != nil) { + [cleanedSQL appendString:@"?"]; + [arguments addObject:arg]; + } + else if (add == (unichar)'@' && last == (unichar) '%') { + [cleanedSQL appendFormat:@"NULL"]; + } + else if (add != '\0') { + [cleanedSQL appendFormat:@"%C", add]; + } + last = current; + } +} + +#pragma mark Execute queries + +- (SqfliteDarwinResultSet *)executeQuery:(NSString *)sql withParameterDictionary:(NSDictionary *)arguments { + return [self executeQuery:sql withArgumentsInArray:nil orDictionary:arguments orVAList:nil shouldBind:true]; +} + +- (SqfliteDarwinResultSet *)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray*)arrayArgs orDictionary:(NSDictionary *)dictionaryArgs orVAList:(va_list)args shouldBind:(BOOL)shouldBind { + if (![self databaseExists]) { + return 0x00; + } + + if (_isExecutingStatement) { + [self warnInUse]; + return 0x00; + } + + _isExecutingStatement = YES; + + int rc = 0x00; + sqlite3_stmt *pStmt = 0x00; + SqfliteDarwinStatement *statement = 0x00; + SqfliteDarwinResultSet *rs = 0x00; + + if (_traceExecution && sql) { + NSLog(@"%@ executeQuery: %@", self, sql); + } + + if (_shouldCacheStatements) { + statement = [self cachedStatementForQuery:sql]; + pStmt = statement ? [statement statement] : 0x00; + [statement reset]; + } + + if (!pStmt) { + rc = sqlite3_prepare_v2(_db, [sql UTF8String], -1, &pStmt, 0); + + if (SQLITE_OK != rc) { + if (_logsErrors) { + NSLog(@"DB Error: %d \"%@\"", [self lastErrorCode], [self lastErrorMessage]); + NSLog(@"DB Query: %@", sql); + NSLog(@"DB Path: %@", _databasePath); + } + + if (_crashOnErrors) { + NSAssert(false, @"DB Error: %d \"%@\"", [self lastErrorCode], [self lastErrorMessage]); + abort(); + } + + sqlite3_finalize(pStmt); + pStmt = 0x00; + _isExecutingStatement = NO; + return nil; + } + } + + if (shouldBind) { + BOOL success = [self bindStatement:pStmt WithArgumentsInArray:arrayArgs orDictionary:dictionaryArgs orVAList:args]; + if (!success) { + return nil; + } + } + + SqfliteDarwinDBRetain(statement); // to balance the release below + + if (!statement) { + statement = [[SqfliteDarwinStatement alloc] init]; + [statement setStatement:pStmt]; + + if (_shouldCacheStatements && sql) { + [self setCachedStatement:statement forQuery:sql]; + } + } + + // the statement gets closed in rs's dealloc or [rs close]; + // we should only autoclose if we're binding automatically when the statement is prepared + rs = [SqfliteDarwinResultSet resultSetWithStatement:statement usingParentDatabase:self shouldAutoClose:shouldBind]; + [rs setQuery:sql]; + + NSValue *openResultSet = [NSValue valueWithNonretainedObject:rs]; + [_openResultSets addObject:openResultSet]; + + [statement setUseCount:[statement useCount] + 1]; + + SqfliteDarwinDBRelease(statement); + + _isExecutingStatement = NO; + + return rs; +} + +- (BOOL)bindStatement:(sqlite3_stmt *)pStmt WithArgumentsInArray:(NSArray*)arrayArgs orDictionary:(NSDictionary *)dictionaryArgs orVAList:(va_list)args { + id obj; + int idx = 0; + int queryCount = sqlite3_bind_parameter_count(pStmt); // pointed out by Dominic Yu (thanks!) + + // If dictionaryArgs is passed in, that means we are using sqlite's named parameter support + if (dictionaryArgs) { + + for (NSString *dictionaryKey in [dictionaryArgs allKeys]) { + + // Prefix the key with a colon. + NSString *parameterName = [[NSString alloc] initWithFormat:@":%@", dictionaryKey]; + + if (_traceExecution) { + NSLog(@"%@ = %@", parameterName, [dictionaryArgs objectForKey:dictionaryKey]); + } + + // Get the index for the parameter name. + int namedIdx = sqlite3_bind_parameter_index(pStmt, [parameterName UTF8String]); + + SqfliteDarwinDBRelease(parameterName); + + if (namedIdx > 0) { + // Standard binding from here. + int rc = [self bindObject:[dictionaryArgs objectForKey:dictionaryKey] toColumn:namedIdx inStatement:pStmt]; + if (rc != SQLITE_OK) { + NSLog(@"Error: unable to bind (%d, %s", rc, sqlite3_errmsg(_db)); + sqlite3_finalize(pStmt); + pStmt = 0x00; + _isExecutingStatement = NO; + return false; + } + // increment the binding count, so our check below works out + idx++; + } + else { + NSLog(@"Could not find index for %@", dictionaryKey); + } + } + } + else { + while (idx < queryCount) { + if (arrayArgs && idx < (int)[arrayArgs count]) { + obj = [arrayArgs objectAtIndex:(NSUInteger)idx]; + } + else if (args) { + obj = va_arg(args, id); + } + else { + //We ran out of arguments + break; + } + + if (_traceExecution) { + if ([obj isKindOfClass:[NSData class]]) { + NSLog(@"data: %ld bytes", (unsigned long)[(NSData*)obj length]); + } + else { + NSLog(@"obj: %@", obj); + } + } + + idx++; + + int rc = [self bindObject:obj toColumn:idx inStatement:pStmt]; + if (rc != SQLITE_OK) { + NSLog(@"Error: unable to bind (%d, %s", rc, sqlite3_errmsg(_db)); + sqlite3_finalize(pStmt); + pStmt = 0x00; + _isExecutingStatement = NO; + return false; + } + } + } + + if (idx != queryCount) { + NSLog(@"Error: the bind count is not correct for the # of variables (executeQuery)"); + sqlite3_finalize(pStmt); + pStmt = 0x00; + _isExecutingStatement = NO; + return false; + } + + return true; +} + +- (SqfliteDarwinResultSet *)executeQuery:(NSString*)sql, ... { + va_list args; + va_start(args, sql); + + id result = [self executeQuery:sql withArgumentsInArray:nil orDictionary:nil orVAList:args shouldBind:true]; + + va_end(args); + return result; +} + +- (SqfliteDarwinResultSet *)executeQueryWithFormat:(NSString*)format, ... { + va_list args; + va_start(args, format); + + NSMutableString *sql = [NSMutableString stringWithCapacity:[format length]]; + NSMutableArray *arguments = [NSMutableArray array]; + [self extractSQL:format argumentsList:args intoString:sql arguments:arguments]; + + va_end(args); + + return [self executeQuery:sql withArgumentsInArray:arguments]; +} + +- (SqfliteDarwinResultSet *)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray *)arguments { + return [self executeQuery:sql withArgumentsInArray:arguments orDictionary:nil orVAList:nil shouldBind:true]; +} + +- (SqfliteDarwinResultSet *)executeQuery:(NSString *)sql values:(NSArray *)values error:(NSError * __autoreleasing *)error { + SqfliteDarwinResultSet *rs = [self executeQuery:sql withArgumentsInArray:values orDictionary:nil orVAList:nil shouldBind:true]; + if (!rs && error) { + *error = [self lastError]; + } + return rs; +} + +- (SqfliteDarwinResultSet *)executeQuery:(NSString*)sql withVAList:(va_list)args { + return [self executeQuery:sql withArgumentsInArray:nil orDictionary:nil orVAList:args shouldBind:true]; +} + +#pragma mark Execute updates + +- (BOOL)executeUpdate:(NSString*)sql error:(NSError * _Nullable __autoreleasing *)outErr withArgumentsInArray:(NSArray*)arrayArgs orDictionary:(NSDictionary *)dictionaryArgs orVAList:(va_list)args { + SqfliteDarwinResultSet *rs = [self executeQuery:sql withArgumentsInArray:arrayArgs orDictionary:dictionaryArgs orVAList:args shouldBind:true]; + if (!rs) { + if (outErr) { + *outErr = [self lastError]; + } + return false; + } + + return [rs internalStepWithError:outErr] == SQLITE_DONE; +} + +- (BOOL)executeUpdate:(NSString*)sql, ... { + va_list args; + va_start(args, sql); + + BOOL result = [self executeUpdate:sql error:nil withArgumentsInArray:nil orDictionary:nil orVAList:args]; + + va_end(args); + return result; +} + +- (BOOL)executeUpdate:(NSString*)sql withArgumentsInArray:(NSArray *)arguments { + return [self executeUpdate:sql error:nil withArgumentsInArray:arguments orDictionary:nil orVAList:nil]; +} + +- (BOOL)executeUpdate:(NSString*)sql values:(NSArray *)values error:(NSError * __autoreleasing *)error { + return [self executeUpdate:sql error:error withArgumentsInArray:values orDictionary:nil orVAList:nil]; +} + +- (BOOL)executeUpdate:(NSString*)sql withParameterDictionary:(NSDictionary *)arguments { + return [self executeUpdate:sql error:nil withArgumentsInArray:nil orDictionary:arguments orVAList:nil]; +} + +- (BOOL)executeUpdate:(NSString*)sql withVAList:(va_list)args { + return [self executeUpdate:sql error:nil withArgumentsInArray:nil orDictionary:nil orVAList:args]; +} + +- (BOOL)executeUpdateWithFormat:(NSString*)format, ... { + va_list args; + va_start(args, format); + + NSMutableString *sql = [NSMutableString stringWithCapacity:[format length]]; + NSMutableArray *arguments = [NSMutableArray array]; + + [self extractSQL:format argumentsList:args intoString:sql arguments:arguments]; + + va_end(args); + + return [self executeUpdate:sql withArgumentsInArray:arguments]; +} + + +int SqfliteDarwinDBExecuteBulkSQLCallback(void *theBlockAsVoid, int columns, char **values, char **names); // shhh clang. +int SqfliteDarwinDBExecuteBulkSQLCallback(void *theBlockAsVoid, int columns, char **values, char **names) { + + if (!theBlockAsVoid) { + return SQLITE_OK; + } + + int (^execCallbackBlock)(NSDictionary *resultsDictionary) = (__bridge int (^)(NSDictionary *__strong))(theBlockAsVoid); + + NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithCapacity:(NSUInteger)columns]; + + for (NSInteger i = 0; i < columns; i++) { + NSString *key = [NSString stringWithUTF8String:names[i]]; + id value = values[i] ? [NSString stringWithUTF8String:values[i]] : [NSNull null]; + value = value ? value : [NSNull null]; + [dictionary setObject:value forKey:key]; + } + + return execCallbackBlock(dictionary); +} + +- (BOOL)executeStatements:(NSString *)sql { + return [self executeStatements:sql withResultBlock:nil]; +} + +- (BOOL)executeStatements:(NSString *)sql withResultBlock:(__attribute__((noescape)) SqfliteDarwinDBExecuteStatementsCallbackBlock)block { + + int rc; + char *errmsg = nil; + + rc = sqlite3_exec([self sqliteHandle], [sql UTF8String], block ? SqfliteDarwinDBExecuteBulkSQLCallback : nil, (__bridge void *)(block), &errmsg); + + if (errmsg && [self logsErrors]) { + NSLog(@"Error inserting batch: %s", errmsg); + } + if (errmsg) { + sqlite3_free(errmsg); + } + + return (rc == SQLITE_OK); +} + +- (BOOL)executeUpdate:(NSString*)sql withErrorAndBindings:(NSError * _Nullable __autoreleasing *)outErr, ... { + + va_list args; + va_start(args, outErr); + + BOOL result = [self executeUpdate:sql error:outErr withArgumentsInArray:nil orDictionary:nil orVAList:args]; + + va_end(args); + return result; +} + + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-implementations" +- (BOOL)update:(NSString*)sql withErrorAndBindings:(NSError * _Nullable __autoreleasing *)outErr, ... { + va_list args; + va_start(args, outErr); + + BOOL result = [self executeUpdate:sql error:outErr withArgumentsInArray:nil orDictionary:nil orVAList:args]; + + va_end(args); + return result; +} + +#pragma clang diagnostic pop + +#pragma mark Prepare + +- (SqfliteDarwinResultSet *)prepare:(NSString *)sql { + return [self executeQuery:sql withArgumentsInArray:nil orDictionary:nil orVAList:nil shouldBind:false]; +} + +#pragma mark Transactions + +- (BOOL)rollback { + BOOL b = [self executeUpdate:@"rollback transaction"]; + + if (b) { + _isInTransaction = NO; + } + + return b; +} + +- (BOOL)commit { + BOOL b = [self executeUpdate:@"commit transaction"]; + + if (b) { + _isInTransaction = NO; + } + + return b; +} + +- (BOOL)beginTransaction { + + BOOL b = [self executeUpdate:@"begin exclusive transaction"]; + if (b) { + _isInTransaction = YES; + } + + return b; +} + +- (BOOL)beginDeferredTransaction { + + BOOL b = [self executeUpdate:@"begin deferred transaction"]; + if (b) { + _isInTransaction = YES; + } + + return b; +} + +- (BOOL)beginImmediateTransaction { + + BOOL b = [self executeUpdate:@"begin immediate transaction"]; + if (b) { + _isInTransaction = YES; + } + + return b; +} + +- (BOOL)beginExclusiveTransaction { + + BOOL b = [self executeUpdate:@"begin exclusive transaction"]; + if (b) { + _isInTransaction = YES; + } + + return b; +} + +- (BOOL)inTransaction { + return _isInTransaction; +} + +- (BOOL)interrupt +{ + if (_db) { + sqlite3_interrupt([self sqliteHandle]); + return YES; + } + return NO; +} + +static NSString *SqfliteDarwinDBEscapeSavePointName(NSString *savepointName) { + return [savepointName stringByReplacingOccurrencesOfString:@"'" withString:@"''"]; +} + +- (BOOL)startSavePointWithName:(NSString*)name error:(NSError * _Nullable __autoreleasing *)outErr { +#if SQLITE_VERSION_NUMBER >= 3007000 + NSParameterAssert(name); + + NSString *sql = [NSString stringWithFormat:@"savepoint '%@';", SqfliteDarwinDBEscapeSavePointName(name)]; + + return [self executeUpdate:sql error:outErr withArgumentsInArray:nil orDictionary:nil orVAList:nil]; +#else + NSString *errorMessage = NSLocalizedStringFromTable(@"Save point functions require SQLite 3.7", @"SqfliteDarwinDB", nil); + if (self.logsErrors) NSLog(@"%@", errorMessage); + return NO; +#endif +} + +- (BOOL)releaseSavePointWithName:(NSString*)name error:(NSError * _Nullable __autoreleasing *)outErr { +#if SQLITE_VERSION_NUMBER >= 3007000 + NSParameterAssert(name); + + NSString *sql = [NSString stringWithFormat:@"release savepoint '%@';", SqfliteDarwinDBEscapeSavePointName(name)]; + + return [self executeUpdate:sql error:outErr withArgumentsInArray:nil orDictionary:nil orVAList:nil]; +#else + NSString *errorMessage = NSLocalizedStringFromTable(@"Save point functions require SQLite 3.7", @"SqfliteDarwinDB", nil); + if (self.logsErrors) NSLog(@"%@", errorMessage); + return NO; +#endif +} + +- (BOOL)rollbackToSavePointWithName:(NSString*)name error:(NSError * _Nullable __autoreleasing *)outErr { +#if SQLITE_VERSION_NUMBER >= 3007000 + NSParameterAssert(name); + + NSString *sql = [NSString stringWithFormat:@"rollback transaction to savepoint '%@';", SqfliteDarwinDBEscapeSavePointName(name)]; + + return [self executeUpdate:sql error:outErr withArgumentsInArray:nil orDictionary:nil orVAList:nil]; +#else + NSString *errorMessage = NSLocalizedStringFromTable(@"Save point functions require SQLite 3.7", @"SqfliteDarwinDB", nil); + if (self.logsErrors) NSLog(@"%@", errorMessage); + return NO; +#endif +} + +- (NSError*)inSavePoint:(__attribute__((noescape)) void (^)(BOOL *rollback))block { +#if SQLITE_VERSION_NUMBER >= 3007000 + static unsigned long savePointIdx = 0; + + NSString *name = [NSString stringWithFormat:@"dbSavePoint%ld", savePointIdx++]; + + BOOL shouldRollback = NO; + + NSError *err = 0x00; + + if (![self startSavePointWithName:name error:&err]) { + return err; + } + + if (block) { + block(&shouldRollback); + } + + if (shouldRollback) { + // We need to rollback and release this savepoint to remove it + [self rollbackToSavePointWithName:name error:&err]; + } + [self releaseSavePointWithName:name error:&err]; + + return err; +#else + NSString *errorMessage = NSLocalizedStringFromTable(@"Save point functions require SQLite 3.7", @"SqfliteDarwinDB", nil); + if (self.logsErrors) NSLog(@"%@", errorMessage); + return [NSError errorWithDomain:@"SqfliteDarwinDatabase" code:0 userInfo:@{NSLocalizedDescriptionKey : errorMessage}]; +#endif +} + +- (BOOL)checkpoint:(SqfliteDarwinDBCheckpointMode)checkpointMode error:(NSError * __autoreleasing *)error { + return [self checkpoint:checkpointMode name:nil logFrameCount:NULL checkpointCount:NULL error:error]; +} + +- (BOOL)checkpoint:(SqfliteDarwinDBCheckpointMode)checkpointMode name:(NSString *)name error:(NSError * __autoreleasing *)error { + return [self checkpoint:checkpointMode name:name logFrameCount:NULL checkpointCount:NULL error:error]; +} + +- (BOOL)checkpoint:(SqfliteDarwinDBCheckpointMode)checkpointMode name:(NSString *)name logFrameCount:(int *)logFrameCount checkpointCount:(int *)checkpointCount error:(NSError * __autoreleasing *)error +{ + const char* dbName = [name UTF8String]; +#if SQLITE_VERSION_NUMBER >= 3007006 + int err = sqlite3_wal_checkpoint_v2(_db, dbName, checkpointMode, logFrameCount, checkpointCount); +#else + NSLog(@"sqlite3_wal_checkpoint_v2 unavailable before sqlite 3.7.6. Ignoring checkpoint mode: %d", mode); + int err = sqlite3_wal_checkpoint(_db, dbName); +#endif + if(err != SQLITE_OK) { + if (error) { + *error = [self lastError]; + } + if (self.logsErrors) NSLog(@"%@", [self lastErrorMessage]); + if (self.crashOnErrors) { + NSAssert(false, @"%@", [self lastErrorMessage]); + abort(); + } + return NO; + } else { + return YES; + } +} + +#pragma mark Cache statements + +- (BOOL)shouldCacheStatements { + return _shouldCacheStatements; +} + +- (void)setShouldCacheStatements:(BOOL)value { + + _shouldCacheStatements = value; + + if (_shouldCacheStatements && !_cachedStatements) { + [self setCachedStatements:[NSMutableDictionary dictionary]]; + } + + if (!_shouldCacheStatements) { + [self setCachedStatements:nil]; + } +} + +#pragma mark Callback function + +void SqfliteDarwinDBBlockSQLiteCallBackFunction(sqlite3_context *context, int argc, sqlite3_value **argv); // -Wmissing-prototypes +void SqfliteDarwinDBBlockSQLiteCallBackFunction(sqlite3_context *context, int argc, sqlite3_value **argv) { +#if ! __has_feature(objc_arc) + void (^block)(sqlite3_context *context, int argc, sqlite3_value **argv) = (id)sqlite3_user_data(context); +#else + void (^block)(sqlite3_context *context, int argc, sqlite3_value **argv) = (__bridge id)sqlite3_user_data(context); +#endif + if (block) { + @autoreleasepool { + block(context, argc, argv); + } + } +} + +// deprecated because "arguments" parameter is not maximum argument count, but actual argument count. + +- (void)makeFunctionNamed:(NSString *)name maximumArguments:(int)arguments withBlock:(void (^)(void *context, int argc, void **argv))block { + [self makeFunctionNamed:name arguments:arguments block:block]; +} + +- (void)makeFunctionNamed:(NSString *)name arguments:(int)arguments block:(void (^)(void *context, int argc, void **argv))block { + + if (!_openFunctions) { + _openFunctions = [NSMutableSet new]; + } + + id b = SqfliteDarwinDBReturnAutoreleased([block copy]); + + [_openFunctions addObject:b]; + + /* I tried adding custom functions to release the block when the connection is destroyed- but they seemed to never be called, so we use _openFunctions to store the values instead. */ +#if ! __has_feature(objc_arc) + sqlite3_create_function([self sqliteHandle], [name UTF8String], arguments, SQLITE_UTF8, (void*)b, &SqfliteDarwinDBBlockSQLiteCallBackFunction, 0x00, 0x00); +#else + sqlite3_create_function([self sqliteHandle], [name UTF8String], arguments, SQLITE_UTF8, (__bridge void*)b, &SqfliteDarwinDBBlockSQLiteCallBackFunction, 0x00, 0x00); +#endif +} + +- (SqliteValueType)valueType:(void *)value { + return sqlite3_value_type(value); +} + +- (int)valueInt:(void *)value { + return sqlite3_value_int(value); +} + +- (long long)valueLong:(void *)value { + return sqlite3_value_int64(value); +} + +- (double)valueDouble:(void *)value { + return sqlite3_value_double(value); +} + +- (NSData *)valueData:(void *)value { + const void *bytes = sqlite3_value_blob(value); + int length = sqlite3_value_bytes(value); + return bytes ? [NSData dataWithBytes:bytes length:(NSUInteger)length] : nil; +} + +- (NSString *)valueString:(void *)value { + const char *cString = (const char *)sqlite3_value_text(value); + return cString ? [NSString stringWithUTF8String:cString] : nil; +} + +- (void)resultNullInContext:(void *)context { + sqlite3_result_null(context); +} + +- (void)resultInt:(int) value context:(void *)context { + sqlite3_result_int(context, value); +} + +- (void)resultLong:(long long)value context:(void *)context { + sqlite3_result_int64(context, value); +} + +- (void)resultDouble:(double)value context:(void *)context { + sqlite3_result_double(context, value); +} + +- (void)resultData:(NSData *)data context:(void *)context { + sqlite3_result_blob(context, data.bytes, (int)data.length, SQLITE_TRANSIENT); +} + +- (void)resultString:(NSString *)value context:(void *)context { + sqlite3_result_text(context, [value UTF8String], -1, SQLITE_TRANSIENT); +} + +- (void)resultError:(NSString *)error context:(void *)context { + sqlite3_result_error(context, [error UTF8String], -1); +} + +- (void)resultErrorCode:(int)errorCode context:(void *)context { + sqlite3_result_error_code(context, errorCode); +} + +- (void)resultErrorNoMemoryInContext:(void *)context { + sqlite3_result_error_nomem(context); +} + +- (void)resultErrorTooBigInContext:(void *)context { + sqlite3_result_error_toobig(context); +} + +@end + +// MARK: - SqfliteDarwinStatement + +@implementation SqfliteDarwinStatement + +#if ! __has_feature(objc_arc) +- (void)finalize { + [self close]; + [super finalize]; +} +#endif + +- (void)dealloc { + [self close]; + SqfliteDarwinDBRelease(_query); +#if ! __has_feature(objc_arc) + [super dealloc]; +#endif +} + +- (void)close { + if (_statement) { + sqlite3_finalize(_statement); + _statement = 0x00; + } + + _inUse = NO; +} + +- (void)reset { + if (_statement) { + sqlite3_reset(_statement); + } + + _inUse = NO; +} + +- (NSString*)description { + return [NSString stringWithFormat:@"%@ %ld hit(s) for query %@", [super description], _useCount, _query]; +} + +@end + diff --git a/sqflite/darwin/Classes/SqfliteDarwinDatabaseAdditions.h b/sqflite/darwin/Classes/SqfliteDarwinDatabaseAdditions.h new file mode 100644 index 00000000..87871a94 --- /dev/null +++ b/sqflite/darwin/Classes/SqfliteDarwinDatabaseAdditions.h @@ -0,0 +1,243 @@ +// +// SqfliteDarwinDatabaseAdditions.h +// fmdb +// +// Created by August Mueller on 10/30/05. +// Copyright 2005 Flying Meat Inc.. All rights reserved. +// + +#import +#import "SqfliteDarwinDatabase.h" + +NS_ASSUME_NONNULL_BEGIN + +/** Category of additions for @c SqfliteDarwinDatabase class. + + See also + + - @c SqfliteDarwinDatabase + */ + +@interface SqfliteDarwinDatabase (SqfliteDarwinDatabaseAdditions) + +///---------------------------------------- +/// @name Return results of SQL to variable +///---------------------------------------- + +/** Return @c int value for query + + @param query The SQL query to be performed, followed by a list of parameters that will be bound to the `?` placeholders in the SQL query. + + @return @c int value. + + @note This is not available from Swift. + */ + +- (int)intForQuery:(NSString*)query, ...; + +/** Return @c long value for query + + @param query The SQL query to be performed, followed by a list of parameters that will be bound to the `?` placeholders in the SQL query. + + @return @c long value. + + @note This is not available from Swift. + */ + +- (long)longForQuery:(NSString*)query, ...; + +/** Return `BOOL` value for query + + @param query The SQL query to be performed, followed by a list of parameters that will be bound to the `?` placeholders in the SQL query. + + @return `BOOL` value. + + @note This is not available from Swift. + */ + +- (BOOL)boolForQuery:(NSString*)query, ...; + +/** Return `double` value for query + + @param query The SQL query to be performed, followed by a list of parameters that will be bound to the `?` placeholders in the SQL query. + + @return `double` value. + + @note This is not available from Swift. + */ + +- (double)doubleForQuery:(NSString*)query, ...; + +/** Return @c NSString value for query + + @param query The SQL query to be performed, followed by a list of parameters that will be bound to the `?` placeholders in the SQL query. + + @return @c NSString value. + + @note This is not available from Swift. + */ + +- (NSString * _Nullable)stringForQuery:(NSString*)query, ...; + +/** Return @c NSData value for query + + @param query The SQL query to be performed, followed by a list of parameters that will be bound to the `?` placeholders in the SQL query. + + @return @c NSData value. + + @note This is not available from Swift. + */ + +- (NSData * _Nullable)dataForQuery:(NSString*)query, ...; + +/** Return @c NSDate value for query + + @param query The SQL query to be performed, followed by a list of parameters that will be bound to the `?` placeholders in the SQL query. + + @return @c NSDate value. + + @note This is not available from Swift. + */ + +- (NSDate * _Nullable)dateForQuery:(NSString*)query, ...; + + +// Notice that there's no dataNoCopyForQuery:. +// That would be a bad idea, because we close out the result set, and then what +// happens to the data that we just didn't copy? Who knows, not I. + + +///-------------------------------- +/// @name Schema related operations +///-------------------------------- + +/** Does table exist in database? + + @param tableName The name of the table being looked for. + + @return @c YES if table found; @c NO if not found. + */ + +- (BOOL)tableExists:(NSString*)tableName; + +/** The schema of the database. + + This will be the schema for the entire database. For each entity, each row of the result set will include the following fields: + + - `type` - The type of entity (e.g. table, index, view, or trigger) + - `name` - The name of the object + - `tbl_name` - The name of the table to which the object references + - `rootpage` - The page number of the root b-tree page for tables and indices + - `sql` - The SQL that created the entity + + @return `SqfliteDarwinResultSet` of schema; @c nil on error. + + @see [SQLite File Format](https://sqlite.org/fileformat.html) + */ + +- (SqfliteDarwinResultSet * _Nullable)getSchema; + +/** The schema of the database. + + This will be the schema for a particular table as report by SQLite `PRAGMA`, for example: + + PRAGMA table_info('employees') + + This will report: + + - `cid` - The column ID number + - `name` - The name of the column + - `type` - The data type specified for the column + - `notnull` - whether the field is defined as NOT NULL (i.e. values required) + - `dflt_value` - The default value for the column + - `pk` - Whether the field is part of the primary key of the table + + @param tableName The name of the table for whom the schema will be returned. + + @return `SqfliteDarwinResultSet` of schema; @c nil on error. + + @see [table_info](https://sqlite.org/pragma.html#pragma_table_info) + */ + +- (SqfliteDarwinResultSet * _Nullable)getTableSchema:(NSString*)tableName; + +/** Test to see if particular column exists for particular table in database + + @param columnName The name of the column. + + @param tableName The name of the table. + + @return @c YES if column exists in table in question; @c NO otherwise. + */ + +- (BOOL)columnExists:(NSString*)columnName inTableWithName:(NSString*)tableName; + +/** Test to see if particular column exists for particular table in database + + @param columnName The name of the column. + + @param tableName The name of the table. + + @return @c YES if column exists in table in question; @c NO otherwise. + + @see columnExists:inTableWithName: + + @warning Deprecated - use `` instead. + */ + +- (BOOL)columnExists:(NSString*)tableName columnName:(NSString*)columnName __deprecated_msg("Use columnExists:inTableWithName: instead"); + + +/** Validate SQL statement + + This validates SQL statement by performing `sqlite3_prepare_v2`, but not returning the results, but instead immediately calling `sqlite3_finalize`. + + @param sql The SQL statement being validated. + + @param error This is a pointer to a @c NSError object that will receive the autoreleased @c NSError object if there was any error. If this is @c nil , no @c NSError result will be returned. + + @return @c YES if validation succeeded without incident; @c NO otherwise. + + */ + +- (BOOL)validateSQL:(NSString*)sql error:(NSError * _Nullable __autoreleasing *)error; + + +///----------------------------------- +/// @name Application identifier tasks +///----------------------------------- + +/** Retrieve application ID + + @return The `uint32_t` numeric value of the application ID. + + @see setApplicationID: + */ + +@property (nonatomic) uint32_t applicationID; + +#if TARGET_OS_MAC && !TARGET_OS_IPHONE + +/** Retrieve application ID string + + @see setApplicationIDString: + */ + +@property (nonatomic, retain) NSString *applicationIDString; + +#endif + +///----------------------------------- +/// @name user version identifier tasks +///----------------------------------- + +/** Retrieve user version + + @see setUserVersion: + */ + +@property (nonatomic) uint32_t userVersion; + +@end + +NS_ASSUME_NONNULL_END diff --git a/sqflite/darwin/Classes/SqfliteDarwinDatabaseAdditions.m b/sqflite/darwin/Classes/SqfliteDarwinDatabaseAdditions.m new file mode 100644 index 00000000..3021b63d --- /dev/null +++ b/sqflite/darwin/Classes/SqfliteDarwinDatabaseAdditions.m @@ -0,0 +1,245 @@ +// +// SqfliteDarwinDatabaseAdditions.m +// fmdb +// +// Created by August Mueller on 10/30/05. +// Copyright 2005 Flying Meat Inc.. All rights reserved. +// + +#import "SqfliteDarwinDatabase.h" +#import "SqfliteDarwinDatabaseAdditions.h" +#import "TargetConditionals.h" + +#if SqfliteDarwinDB_SQLITE_STANDALONE +#import +#else +#import +#endif + +@interface SqfliteDarwinDatabase (PrivateStuff) +- (SqfliteDarwinResultSet * _Nullable)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray * _Nullable)arrayArgs orDictionary:(NSDictionary * _Nullable)dictionaryArgs orVAList:(va_list)args shouldBind:(BOOL)shouldBind; +@end + +@implementation SqfliteDarwinDatabase (SqfliteDarwinDatabaseAdditions) + +#define RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(type, sel) \ +va_list args; \ +va_start(args, query); \ +SqfliteDarwinResultSet *resultSet = [self executeQuery:query withArgumentsInArray:0x00 orDictionary:0x00 orVAList:args shouldBind:true]; \ +va_end(args); \ +if (![resultSet next]) { return (type)0; } \ +type ret = [resultSet sel:0]; \ +[resultSet close]; \ +[resultSet setParentDB:nil]; \ +return ret; + + +- (NSString *)stringForQuery:(NSString*)query, ... { + RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(NSString *, stringForColumnIndex); +} + +- (int)intForQuery:(NSString*)query, ... { + RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(int, intForColumnIndex); +} + +- (long)longForQuery:(NSString*)query, ... { + RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(long, longForColumnIndex); +} + +- (BOOL)boolForQuery:(NSString*)query, ... { + RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(BOOL, boolForColumnIndex); +} + +- (double)doubleForQuery:(NSString*)query, ... { + RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(double, doubleForColumnIndex); +} + +- (NSData*)dataForQuery:(NSString*)query, ... { + RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(NSData *, dataForColumnIndex); +} + +- (NSDate*)dateForQuery:(NSString*)query, ... { + RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(NSDate *, dateForColumnIndex); +} + + +- (BOOL)tableExists:(NSString*)tableName { + + tableName = [tableName lowercaseString]; + + SqfliteDarwinResultSet *rs = [self executeQuery:@"select [sql] from sqlite_master where [type] = 'table' and lower(name) = ?", tableName]; + + //if at least one next exists, table exists + BOOL returnBool = [rs next]; + + //close and free object + [rs close]; + + return returnBool; +} + +/* + get table with list of tables: result colums: type[STRING], name[STRING],tbl_name[STRING],rootpage[INTEGER],sql[STRING] + check if table exist in database (patch from OZLB) +*/ +- (SqfliteDarwinResultSet * _Nullable)getSchema { + + //result colums: type[STRING], name[STRING],tbl_name[STRING],rootpage[INTEGER],sql[STRING] + SqfliteDarwinResultSet *rs = [self executeQuery:@"SELECT type, name, tbl_name, rootpage, sql FROM (SELECT * FROM sqlite_master UNION ALL SELECT * FROM sqlite_temp_master) WHERE type != 'meta' AND name NOT LIKE 'sqlite_%' ORDER BY tbl_name, type DESC, name"]; + + return rs; +} + +/* + get table schema: result colums: cid[INTEGER], name,type [STRING], notnull[INTEGER], dflt_value[],pk[INTEGER] +*/ +- (SqfliteDarwinResultSet * _Nullable)getTableSchema:(NSString*)tableName { + + //result colums: cid[INTEGER], name,type [STRING], notnull[INTEGER], dflt_value[],pk[INTEGER] + SqfliteDarwinResultSet *rs = [self executeQuery:[NSString stringWithFormat: @"pragma table_info('%@')", tableName]]; + + return rs; +} + +- (BOOL)columnExists:(NSString*)columnName inTableWithName:(NSString*)tableName { + + BOOL returnBool = NO; + + tableName = [tableName lowercaseString]; + columnName = [columnName lowercaseString]; + + SqfliteDarwinResultSet *rs = [self getTableSchema:tableName]; + + //check if column is present in table schema + while ([rs next]) { + if ([[[rs stringForColumn:@"name"] lowercaseString] isEqualToString:columnName]) { + returnBool = YES; + break; + } + } + + //If this is not done SqfliteDarwinDatabase instance stays out of pool + [rs close]; + + return returnBool; +} + + + +- (uint32_t)applicationID { +#if SQLITE_VERSION_NUMBER >= 3007017 + uint32_t r = 0; + + SqfliteDarwinResultSet *rs = [self executeQuery:@"pragma application_id"]; + + if ([rs next]) { + r = (uint32_t)[rs longLongIntForColumnIndex:0]; + } + + [rs close]; + + return r; +#else + NSString *errorMessage = NSLocalizedStringFromTable(@"Application ID functions require SQLite 3.7.17", @"SqfliteDarwinDB", nil); + if (self.logsErrors) NSLog(@"%@", errorMessage); + return 0; +#endif +} + +- (void)setApplicationID:(uint32_t)appID { +#if SQLITE_VERSION_NUMBER >= 3007017 + NSString *query = [NSString stringWithFormat:@"pragma application_id=%d", appID]; + SqfliteDarwinResultSet *rs = [self executeQuery:query]; + [rs next]; + [rs close]; +#else + NSString *errorMessage = NSLocalizedStringFromTable(@"Application ID functions require SQLite 3.7.17", @"SqfliteDarwinDB", nil); + if (self.logsErrors) NSLog(@"%@", errorMessage); +#endif +} + + +#if TARGET_OS_MAC && !TARGET_OS_IPHONE + +- (NSString*)applicationIDString { +#if SQLITE_VERSION_NUMBER >= 3007017 + NSString *s = NSFileTypeForHFSTypeCode([self applicationID]); + + assert([s length] == 6); + + s = [s substringWithRange:NSMakeRange(1, 4)]; + + + return s; +#else + NSString *errorMessage = NSLocalizedStringFromTable(@"Application ID functions require SQLite 3.7.17", @"SqfliteDarwinDB", nil); + if (self.logsErrors) NSLog(@"%@", errorMessage); + return nil; +#endif +} + +- (void)setApplicationIDString:(NSString*)s { +#if SQLITE_VERSION_NUMBER >= 3007017 + if ([s length] != 4) { + NSLog(@"setApplicationIDString: string passed is not exactly 4 chars long. (was %ld)", [s length]); + } + + [self setApplicationID:NSHFSTypeCodeFromFileType([NSString stringWithFormat:@"'%@'", s])]; +#else + NSString *errorMessage = NSLocalizedStringFromTable(@"Application ID functions require SQLite 3.7.17", @"SqfliteDarwinDB", nil); + if (self.logsErrors) NSLog(@"%@", errorMessage); +#endif +} + +#endif + +- (uint32_t)userVersion { + uint32_t r = 0; + + SqfliteDarwinResultSet *rs = [self executeQuery:@"pragma user_version"]; + + if ([rs next]) { + r = (uint32_t)[rs longLongIntForColumnIndex:0]; + } + + [rs close]; + return r; +} + +- (void)setUserVersion:(uint32_t)version { + NSString *query = [NSString stringWithFormat:@"pragma user_version = %d", version]; + SqfliteDarwinResultSet *rs = [self executeQuery:query]; + [rs next]; + [rs close]; +} + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-implementations" + +- (BOOL)columnExists:(NSString*)tableName columnName:(NSString*)columnName __attribute__ ((deprecated)) { + return [self columnExists:columnName inTableWithName:tableName]; +} + +#pragma clang diagnostic pop + +- (BOOL)validateSQL:(NSString*)sql error:(NSError * _Nullable __autoreleasing *)error { + sqlite3_stmt *pStmt = NULL; + BOOL validationSucceeded = YES; + + int rc = sqlite3_prepare_v2([self sqliteHandle], [sql UTF8String], -1, &pStmt, 0); + if (rc != SQLITE_OK) { + validationSucceeded = NO; + if (error) { + *error = [NSError errorWithDomain:NSCocoaErrorDomain + code:[self lastErrorCode] + userInfo:[NSDictionary dictionaryWithObject:[self lastErrorMessage] + forKey:NSLocalizedDescriptionKey]]; + } + } + + sqlite3_finalize(pStmt); + + return validationSucceeded; +} + +@end diff --git a/sqflite/darwin/Classes/SqfliteDarwinDatabaseQueue.h b/sqflite/darwin/Classes/SqfliteDarwinDatabaseQueue.h new file mode 100755 index 00000000..1ee249a4 --- /dev/null +++ b/sqflite/darwin/Classes/SqfliteDarwinDatabaseQueue.h @@ -0,0 +1,295 @@ +// +// SqfliteDarwinDatabaseQueue.h +// fmdb +// +// Created by August Mueller on 6/22/11. +// Copyright 2011 Flying Meat Inc. All rights reserved. +// + +#import +#import "SqfliteDarwinDatabase.h" + +NS_ASSUME_NONNULL_BEGIN + +/** To perform queries and updates on multiple threads, you'll want to use @c SqfliteDarwinDatabaseQueue . + + Using a single instance of @c SqfliteDarwinDatabase from multiple threads at once is a bad idea. It has always been OK to make a @c SqfliteDarwinDatabase object *per thread*. Just don't share a single instance across threads, and definitely not across multiple threads at the same time. + + Instead, use @c SqfliteDarwinDatabaseQueue . Here's how to use it: + + First, make your queue. + +@code +SqfliteDarwinDatabaseQueue *queue = [SqfliteDarwinDatabaseQueue databaseQueueWithPath:aPath]; +@endcode + + Then use it like so: + +@code +[queue inDatabase:^(SqfliteDarwinDatabase *db) { + [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:1]]; + [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:2]]; + [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:3]]; + + SqfliteDarwinResultSet *rs = [db executeQuery:@"select * from foo"]; + while ([rs next]) { + //… + } +}]; +@endcode + + An easy way to wrap things up in a transaction can be done like this: + +@code +[queue inTransaction:^(SqfliteDarwinDatabase *db, BOOL *rollback) { + [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:1]]; + [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:2]]; + [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:3]]; + + // if (whoopsSomethingWrongHappened) { + // *rollback = YES; + // return; + // } + + // etc… + [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:4]]; +}]; +@endcode + + @c SqfliteDarwinDatabaseQueue will run the blocks on a serialized queue (hence the name of the class). So if you call @c SqfliteDarwinDatabaseQueue 's methods from multiple threads at the same time, they will be executed in the order they are received. This way queries and updates won't step on each other's toes, and every one is happy. + + @warning Do not instantiate a single @c SqfliteDarwinDatabase object and use it across multiple threads. Use @c SqfliteDarwinDatabaseQueue instead. + + @warning The calls to @c SqfliteDarwinDatabaseQueue 's methods are blocking. So even though you are passing along blocks, they will **not** be run on another thread. + + @sa SqfliteDarwinDatabase + + */ + +@interface SqfliteDarwinDatabaseQueue : NSObject + +/** Path of database */ + +@property (atomic, retain, nullable) NSString *path; + +/** Open flags */ + +@property (atomic, readonly) int openFlags; + +/** Custom virtual file system name */ + +@property (atomic, copy, nullable) NSString *vfsName; + +///---------------------------------------------------- +/// @name Initialization, opening, and closing of queue +///---------------------------------------------------- + +/** Create queue using path. + + @param aPath The file path of the database. + + @return The @c SqfliteDarwinDatabaseQueue object. @c nil on error. + */ + ++ (nullable instancetype)databaseQueueWithPath:(NSString * _Nullable)aPath; + +/** Create queue using file URL. + + @param url The file @c NSURL of the database. + + @return The @c SqfliteDarwinDatabaseQueue object. @c nil on error. + */ + ++ (nullable instancetype)databaseQueueWithURL:(NSURL * _Nullable)url; + +/** Create queue using path and specified flags. + + @param aPath The file path of the database. + @param openFlags Flags passed to the openWithFlags method of the database. + + @return The @c SqfliteDarwinDatabaseQueue object. @c nil on error. + */ ++ (nullable instancetype)databaseQueueWithPath:(NSString * _Nullable)aPath flags:(int)openFlags; + +/** Create queue using file URL and specified flags. + + @param url The file @c NSURL of the database. + @param openFlags Flags passed to the openWithFlags method of the database. + + @return The @c SqfliteDarwinDatabaseQueue object. @c nil on error. + */ ++ (nullable instancetype)databaseQueueWithURL:(NSURL * _Nullable)url flags:(int)openFlags; + +/** Create queue using path. + + @param aPath The file path of the database. + + @return The @c SqfliteDarwinDatabaseQueue object. @c nil on error. + */ + +- (nullable instancetype)initWithPath:(NSString * _Nullable)aPath; + +/** Create queue using file URL. + + @param url The file `NSURL of the database. + + @return The @c SqfliteDarwinDatabaseQueue object. @c nil on error. + */ + +- (nullable instancetype)initWithURL:(NSURL * _Nullable)url; + +/** Create queue using path and specified flags. + + @param aPath The file path of the database. + @param openFlags Flags passed to the openWithFlags method of the database. + + @return The @c SqfliteDarwinDatabaseQueue object. @c nil on error. + */ + +- (nullable instancetype)initWithPath:(NSString * _Nullable)aPath flags:(int)openFlags; + +/** Create queue using file URL and specified flags. + + @param url The file path of the database. + @param openFlags Flags passed to the openWithFlags method of the database. + + @return The @c SqfliteDarwinDatabaseQueue object. @c nil on error. + */ + +- (nullable instancetype)initWithURL:(NSURL * _Nullable)url flags:(int)openFlags; + +/** Create queue using path and specified flags. + + @param aPath The file path of the database. + @param openFlags Flags passed to the openWithFlags method of the database + @param vfsName The name of a custom virtual file system + + @return The @c SqfliteDarwinDatabaseQueue object. @c nil on error. + */ + +- (nullable instancetype)initWithPath:(NSString * _Nullable)aPath flags:(int)openFlags vfs:(NSString * _Nullable)vfsName; + +/** Create queue using file URL and specified flags. + + @param url The file `NSURL of the database. + @param openFlags Flags passed to the openWithFlags method of the database + @param vfsName The name of a custom virtual file system + + @return The @c SqfliteDarwinDatabaseQueue object. @c nil on error. + */ + +- (nullable instancetype)initWithURL:(NSURL * _Nullable)url flags:(int)openFlags vfs:(NSString * _Nullable)vfsName; + +/** Returns the Class of 'SqfliteDarwinDatabase' subclass, that will be used to instantiate database object. + + Subclasses can override this method to return specified Class of 'SqfliteDarwinDatabase' subclass. + + @return The Class of 'SqfliteDarwinDatabase' subclass, that will be used to instantiate database object. + */ + ++ (Class)databaseClass; + +/** Close database used by queue. */ + +- (void)close; + +/** Interupt pending database operation. */ + +- (void)interrupt; + +///----------------------------------------------- +/// @name Dispatching database operations to queue +///----------------------------------------------- + +/** Synchronously perform database operations on queue. + + @param block The code to be run on the queue of @c SqfliteDarwinDatabaseQueue + */ + +- (void)inDatabase:(__attribute__((noescape)) void (^)(SqfliteDarwinDatabase *db))block; + +/** Synchronously perform database operations on queue, using transactions. + + @param block The code to be run on the queue of @c SqfliteDarwinDatabaseQueue + + @warning Unlike SQLite's `BEGIN TRANSACTION`, this method currently performs + an exclusive transaction, not a deferred transaction. This behavior + is likely to change in future versions of SqfliteDarwinDB, whereby this method + will likely eventually adopt standard SQLite behavior and perform + deferred transactions. If you really need exclusive tranaction, it is + recommended that you use `inExclusiveTransaction`, instead, not only + to make your intent explicit, but also to future-proof your code. + + */ + +- (void)inTransaction:(__attribute__((noescape)) void (^)(SqfliteDarwinDatabase *db, BOOL *rollback))block; + +/** Synchronously perform database operations on queue, using deferred transactions. + + @param block The code to be run on the queue of @c SqfliteDarwinDatabaseQueue + */ + +- (void)inDeferredTransaction:(__attribute__((noescape)) void (^)(SqfliteDarwinDatabase *db, BOOL *rollback))block; + +/** Synchronously perform database operations on queue, using exclusive transactions. + + @param block The code to be run on the queue of @c SqfliteDarwinDatabaseQueue + */ + +- (void)inExclusiveTransaction:(__attribute__((noescape)) void (^)(SqfliteDarwinDatabase *db, BOOL *rollback))block; + +/** Synchronously perform database operations on queue, using immediate transactions. + + @param block The code to be run on the queue of @c SqfliteDarwinDatabaseQueue + */ + +- (void)inImmediateTransaction:(__attribute__((noescape)) void (^)(SqfliteDarwinDatabase *db, BOOL *rollback))block; + +///----------------------------------------------- +/// @name Dispatching database operations to queue +///----------------------------------------------- + +/** Synchronously perform database operations using save point. + + @param block The code to be run on the queue of @c SqfliteDarwinDatabaseQueue + */ + +// NOTE: you can not nest these, since calling it will pull another database out of the pool and you'll get a deadlock. +// If you need to nest, use SqfliteDarwinDatabase's startSavePointWithName:error: instead. +- (NSError * _Nullable)inSavePoint:(__attribute__((noescape)) void (^)(SqfliteDarwinDatabase *db, BOOL *rollback))block; + +///----------------- +/// @name Checkpoint +///----------------- + +/** Performs a WAL checkpoint + + @param checkpointMode The checkpoint mode for sqlite3_wal_checkpoint_v2 + @param error The NSError corresponding to the error, if any. + @return YES on success, otherwise NO. + */ +- (BOOL)checkpoint:(SqfliteDarwinDBCheckpointMode)checkpointMode error:(NSError * _Nullable *)error; + +/** Performs a WAL checkpoint + + @param checkpointMode The checkpoint mode for sqlite3_wal_checkpoint_v2 + @param name The db name for sqlite3_wal_checkpoint_v2 + @param error The NSError corresponding to the error, if any. + @return YES on success, otherwise NO. + */ +- (BOOL)checkpoint:(SqfliteDarwinDBCheckpointMode)checkpointMode name:(NSString * _Nullable)name error:(NSError * _Nullable *)error; + +/** Performs a WAL checkpoint + + @param checkpointMode The checkpoint mode for sqlite3_wal_checkpoint_v2 + @param name The db name for sqlite3_wal_checkpoint_v2 + @param error The NSError corresponding to the error, if any. + @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. + @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. + @return YES on success, otherwise NO. + */ +- (BOOL)checkpoint:(SqfliteDarwinDBCheckpointMode)checkpointMode name:(NSString * _Nullable)name logFrameCount:(int * _Nullable)logFrameCount checkpointCount:(int * _Nullable)checkpointCount error:(NSError * _Nullable *)error; + +@end + +NS_ASSUME_NONNULL_END diff --git a/sqflite/darwin/Classes/SqfliteDarwinDatabaseQueue.m b/sqflite/darwin/Classes/SqfliteDarwinDatabaseQueue.m new file mode 100755 index 00000000..cb3bed43 --- /dev/null +++ b/sqflite/darwin/Classes/SqfliteDarwinDatabaseQueue.m @@ -0,0 +1,314 @@ +// +// SqfliteDarwinDatabaseQueue.m +// fmdb +// +// Created by August Mueller on 6/22/11. +// Copyright 2011 Flying Meat Inc. All rights reserved. +// + +#import "SqfliteDarwinDatabaseQueue.h" +#import "SqfliteDarwinDatabase.h" + +#if SqfliteDarwinDB_SQLITE_STANDALONE +#import +#else +#import +#endif + +typedef NS_ENUM(NSInteger, SqfliteDarwinDBTransaction) { + SqfliteDarwinDBTransactionExclusive, + SqfliteDarwinDBTransactionDeferred, + SqfliteDarwinDBTransactionImmediate, +}; + +/* + + Note: we call [self retain]; before using dispatch_sync, just incase + SqfliteDarwinDatabaseQueue is released on another thread and we're in the middle of doing + something in dispatch_sync + + */ + +/* + * A key used to associate the SqfliteDarwinDatabaseQueue object with the dispatch_queue_t it uses. + * This in turn is used for deadlock detection by seeing if inDatabase: is called on + * the queue's dispatch queue, which should not happen and causes a deadlock. + */ +static const void * const kDispatchQueueSpecificKey = &kDispatchQueueSpecificKey; + +@interface SqfliteDarwinDatabaseQueue () { + dispatch_queue_t _queue; + SqfliteDarwinDatabase *_db; +} +@end + +@implementation SqfliteDarwinDatabaseQueue + ++ (instancetype)databaseQueueWithPath:(NSString *)aPath { + SqfliteDarwinDatabaseQueue *q = [[self alloc] initWithPath:aPath]; + + SqfliteDarwinDBAutorelease(q); + + return q; +} + ++ (instancetype)databaseQueueWithURL:(NSURL *)url { + return [self databaseQueueWithPath:url.path]; +} + ++ (instancetype)databaseQueueWithPath:(NSString *)aPath flags:(int)openFlags { + SqfliteDarwinDatabaseQueue *q = [[self alloc] initWithPath:aPath flags:openFlags]; + + SqfliteDarwinDBAutorelease(q); + + return q; +} + ++ (instancetype)databaseQueueWithURL:(NSURL *)url flags:(int)openFlags { + return [self databaseQueueWithPath:url.path flags:openFlags]; +} + ++ (Class)databaseClass { + return [SqfliteDarwinDatabase class]; +} + +- (instancetype)initWithURL:(NSURL *)url flags:(int)openFlags vfs:(NSString *)vfsName { + return [self initWithPath:url.path flags:openFlags vfs:vfsName]; +} + +- (instancetype)initWithPath:(NSString*)aPath flags:(int)openFlags vfs:(NSString *)vfsName { + self = [super init]; + + if (self != nil) { + + _db = [[[self class] databaseClass] databaseWithPath:aPath]; + SqfliteDarwinDBRetain(_db); + +#if SQLITE_VERSION_NUMBER >= 3005000 + BOOL success = [_db openWithFlags:openFlags vfs:vfsName]; +#else + BOOL success = [_db open]; +#endif + if (!success) { + NSLog(@"Could not create database queue for path %@", aPath); + SqfliteDarwinDBRelease(self); + return 0x00; + } + + _path = SqfliteDarwinDBReturnRetained(aPath); + + _queue = dispatch_queue_create([[NSString stringWithFormat:@"fmdb.%@", self] UTF8String], NULL); + dispatch_queue_set_specific(_queue, kDispatchQueueSpecificKey, (__bridge void *)self, NULL); + _openFlags = openFlags; + _vfsName = [vfsName copy]; + } + + return self; +} + +- (instancetype)initWithPath:(NSString *)aPath flags:(int)openFlags { + return [self initWithPath:aPath flags:openFlags vfs:nil]; +} + +- (instancetype)initWithURL:(NSURL *)url flags:(int)openFlags { + return [self initWithPath:url.path flags:openFlags vfs:nil]; +} + +- (instancetype)initWithURL:(NSURL *)url { + return [self initWithPath:url.path]; +} + +- (instancetype)initWithPath:(NSString *)aPath { + // default flags for sqlite3_open + return [self initWithPath:aPath flags:SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE vfs:nil]; +} + +- (instancetype)init { + return [self initWithPath:nil]; +} + +- (void)dealloc { + SqfliteDarwinDBRelease(_db); + SqfliteDarwinDBRelease(_path); + SqfliteDarwinDBRelease(_vfsName); + + if (_queue) { + SqfliteDarwinDBDispatchQueueRelease(_queue); + _queue = 0x00; + } +#if ! __has_feature(objc_arc) + [super dealloc]; +#endif +} + +- (void)close { + SqfliteDarwinDBRetain(self); + dispatch_sync(_queue, ^() { + [self->_db close]; + SqfliteDarwinDBRelease(_db); + self->_db = 0x00; + }); + SqfliteDarwinDBRelease(self); +} + +- (void)interrupt { + [[self database] interrupt]; +} + +- (SqfliteDarwinDatabase*)database { + if (![_db isOpen]) { + if (!_db) { + _db = SqfliteDarwinDBReturnRetained([[[self class] databaseClass] databaseWithPath:_path]); + } + +#if SQLITE_VERSION_NUMBER >= 3005000 + BOOL success = [_db openWithFlags:_openFlags vfs:_vfsName]; +#else + BOOL success = [_db open]; +#endif + if (!success) { + NSLog(@"SqfliteDarwinDatabaseQueue could not reopen database for path %@", _path); + SqfliteDarwinDBRelease(_db); + _db = 0x00; + return 0x00; + } + } + + return _db; +} + +- (void)inDatabase:(__attribute__((noescape)) void (^)(SqfliteDarwinDatabase *db))block { +#ifndef NDEBUG + /* Get the currently executing queue (which should probably be nil, but in theory could be another DB queue + * and then check it against self to make sure we're not about to deadlock. */ + SqfliteDarwinDatabaseQueue *currentSyncQueue = (__bridge id)dispatch_get_specific(kDispatchQueueSpecificKey); + assert(currentSyncQueue != self && "inDatabase: was called reentrantly on the same queue, which would lead to a deadlock"); +#endif + + SqfliteDarwinDBRetain(self); + + dispatch_sync(_queue, ^() { + + SqfliteDarwinDatabase *db = [self database]; + + block(db); + + if ([db hasOpenResultSets]) { + NSLog(@"Warning: there is at least one open result set around after performing [SqfliteDarwinDatabaseQueue inDatabase:]"); + +#if defined(DEBUG) && DEBUG + NSSet *openSetCopy = SqfliteDarwinDBReturnAutoreleased([[db valueForKey:@"_openResultSets"] copy]); + for (NSValue *rsInWrappedInATastyValueMeal in openSetCopy) { + SqfliteDarwinResultSet *rs = (SqfliteDarwinResultSet *)[rsInWrappedInATastyValueMeal pointerValue]; + NSLog(@"query: '%@'", [rs query]); + } +#endif + } + }); + + SqfliteDarwinDBRelease(self); +} + +- (void)beginTransaction:(SqfliteDarwinDBTransaction)transaction withBlock:(void (^)(SqfliteDarwinDatabase *db, BOOL *rollback))block { + SqfliteDarwinDBRetain(self); + dispatch_sync(_queue, ^() { + + BOOL shouldRollback = NO; + + switch (transaction) { + case SqfliteDarwinDBTransactionExclusive: + [[self database] beginTransaction]; + break; + case SqfliteDarwinDBTransactionDeferred: + [[self database] beginDeferredTransaction]; + break; + case SqfliteDarwinDBTransactionImmediate: + [[self database] beginImmediateTransaction]; + break; + } + + block([self database], &shouldRollback); + + if (shouldRollback) { + [[self database] rollback]; + } + else { + [[self database] commit]; + } + }); + + SqfliteDarwinDBRelease(self); +} + +- (void)inTransaction:(__attribute__((noescape)) void (^)(SqfliteDarwinDatabase *db, BOOL *rollback))block { + [self beginTransaction:SqfliteDarwinDBTransactionExclusive withBlock:block]; +} + +- (void)inDeferredTransaction:(__attribute__((noescape)) void (^)(SqfliteDarwinDatabase *db, BOOL *rollback))block { + [self beginTransaction:SqfliteDarwinDBTransactionDeferred withBlock:block]; +} + +- (void)inExclusiveTransaction:(__attribute__((noescape)) void (^)(SqfliteDarwinDatabase *db, BOOL *rollback))block { + [self beginTransaction:SqfliteDarwinDBTransactionExclusive withBlock:block]; +} + +- (void)inImmediateTransaction:(__attribute__((noescape)) void (^)(SqfliteDarwinDatabase * _Nonnull, BOOL * _Nonnull))block { + [self beginTransaction:SqfliteDarwinDBTransactionImmediate withBlock:block]; +} + +- (NSError*)inSavePoint:(__attribute__((noescape)) void (^)(SqfliteDarwinDatabase *db, BOOL *rollback))block { +#if SQLITE_VERSION_NUMBER >= 3007000 + static unsigned long savePointIdx = 0; + __block NSError *err = 0x00; + SqfliteDarwinDBRetain(self); + dispatch_sync(_queue, ^() { + + NSString *name = [NSString stringWithFormat:@"savePoint%ld", savePointIdx++]; + + BOOL shouldRollback = NO; + + if ([[self database] startSavePointWithName:name error:&err]) { + + block([self database], &shouldRollback); + + if (shouldRollback) { + // We need to rollback and release this savepoint to remove it + [[self database] rollbackToSavePointWithName:name error:&err]; + } + [[self database] releaseSavePointWithName:name error:&err]; + + } + }); + SqfliteDarwinDBRelease(self); + return err; +#else + NSString *errorMessage = NSLocalizedStringFromTable(@"Save point functions require SQLite 3.7", @"SqfliteDarwinDB", nil); + if (_db.logsErrors) NSLog(@"%@", errorMessage); + return [NSError errorWithDomain:@"SqfliteDarwinDatabase" code:0 userInfo:@{NSLocalizedDescriptionKey : errorMessage}]; +#endif +} + +- (BOOL)checkpoint:(SqfliteDarwinDBCheckpointMode)mode error:(NSError * __autoreleasing *)error +{ + return [self checkpoint:mode name:nil logFrameCount:NULL checkpointCount:NULL error:error]; +} + +- (BOOL)checkpoint:(SqfliteDarwinDBCheckpointMode)mode name:(NSString *)name error:(NSError * __autoreleasing *)error +{ + return [self checkpoint:mode name:name logFrameCount:NULL checkpointCount:NULL error:error]; +} + +- (BOOL)checkpoint:(SqfliteDarwinDBCheckpointMode)mode name:(NSString *)name logFrameCount:(int * _Nullable)logFrameCount checkpointCount:(int * _Nullable)checkpointCount error:(NSError * __autoreleasing _Nullable * _Nullable)error +{ + __block BOOL result; + + SqfliteDarwinDBRetain(self); + dispatch_sync(_queue, ^() { + result = [self.database checkpoint:mode name:name logFrameCount:logFrameCount checkpointCount:checkpointCount error:error]; + }); + SqfliteDarwinDBRelease(self); + + return result; +} + +@end diff --git a/sqflite/darwin/Classes/SqfliteDarwinImport.h b/sqflite/darwin/Classes/SqfliteDarwinImport.h new file mode 100644 index 00000000..355175e8 --- /dev/null +++ b/sqflite/darwin/Classes/SqfliteDarwinImport.h @@ -0,0 +1,14 @@ +// +// SqfliteDarwinImport.h +// Shared import for SqfliteDarwinDB +// +// Not a header file as XCode might complain. +// +// Created by Alexandre Roux on 03/12/2022. +// +#ifndef SqfliteDarwinImport_h +#define SqfliteDarwinImport_h + +#import "SqfliteDarwinDB.h" + +#endif /* SqfliteDarwinImport_h */ diff --git a/sqflite/darwin/Classes/SqfliteDarwinResultSet.h b/sqflite/darwin/Classes/SqfliteDarwinResultSet.h new file mode 100644 index 00000000..d0a51758 --- /dev/null +++ b/sqflite/darwin/Classes/SqfliteDarwinResultSet.h @@ -0,0 +1,538 @@ +#import + +NS_ASSUME_NONNULL_BEGIN + +#ifndef __has_feature // Optional. +#define __has_feature(x) 0 // Compatibility with non-clang compilers. +#endif + +#ifndef NS_RETURNS_NOT_RETAINED +#if __has_feature(attribute_ns_returns_not_retained) +#define NS_RETURNS_NOT_RETAINED __attribute__((ns_returns_not_retained)) +#else +#define NS_RETURNS_NOT_RETAINED +#endif +#endif + +@class SqfliteDarwinDatabase; +@class SqfliteDarwinStatement; + +/** Types for columns in a result set. + */ +typedef NS_ENUM(int, SqliteValueType) { + SqliteValueTypeInteger = 1, + SqliteValueTypeFloat = 2, + SqliteValueTypeText = 3, + SqliteValueTypeBlob = 4, + SqliteValueTypeNull = 5 +}; + +/** Represents the results of executing a query on an @c SqfliteDarwinDatabase . + + See also + + - @c SqfliteDarwinDatabase + */ + +@interface SqfliteDarwinResultSet : NSObject + +@property (nonatomic, retain, nullable) SqfliteDarwinDatabase *parentDB; + +///----------------- +/// @name Properties +///----------------- + +/** Executed query */ + +@property (atomic, retain, nullable) NSString *query; + +/** `NSMutableDictionary` mapping column names to numeric index */ + +@property (readonly) NSMutableDictionary *columnNameToIndexMap; + +/** `SqfliteDarwinStatement` used by result set. */ + +@property (atomic, retain, nullable) SqfliteDarwinStatement *statement; + +///------------------------------------ +/// @name Creating and closing a result set +///------------------------------------ + +/** Close result set */ + +- (void)close; + +///--------------------------------------- +/// @name Iterating through the result set +///--------------------------------------- + +/** Retrieve next row for result set. + + You must always invoke `next` or `nextWithError` before attempting to access the values returned in a query, even if you're only expecting one. + + @return @c YES if row successfully retrieved; @c NO if end of result set reached + + @see hasAnotherRow + */ + +- (BOOL)next; + +/** Retrieve next row for result set. + + You must always invoke `next` or `nextWithError` before attempting to access the values returned in a query, even if you're only expecting one. + + @param outErr A 'NSError' object to receive any error object (if any). + + @return 'YES' if row successfully retrieved; 'NO' if end of result set reached + + @see hasAnotherRow + */ + +- (BOOL)nextWithError:(NSError * _Nullable __autoreleasing *)outErr; + +/** Perform SQL statement. + + @return 'YES' if successful; 'NO' if not. + + @see hasAnotherRow +*/ + +- (BOOL)step; + +/** Perform SQL statement. + + @param outErr A 'NSError' object to receive any error object (if any). + + @return 'YES' if successful; 'NO' if not. + + @see hasAnotherRow +*/ + +- (BOOL)stepWithError:(NSError * _Nullable __autoreleasing *)outErr; + +/** Did the last call to `` succeed in retrieving another row? + + @return 'YES' if there is another row; 'NO' if not. + + @see next + + @warning The `hasAnotherRow` method must follow a call to ``. If the previous database interaction was something other than a call to `next`, then this method may return @c NO, whether there is another row of data or not. + */ + +- (BOOL)hasAnotherRow; + +///--------------------------------------------- +/// @name Retrieving information from result set +///--------------------------------------------- + +/** How many columns in result set + + @return Integer value of the number of columns. + */ + +@property (nonatomic, readonly) int columnCount; + +/** Column index for column name + + @param columnName @c NSString value of the name of the column. + + @return Zero-based index for column. + */ + +- (int)columnIndexForName:(NSString*)columnName; + +/** Column name for column index + + @param columnIdx Zero-based index for column. + + @return columnName @c NSString value of the name of the column. + */ + +- (NSString * _Nullable)columnNameForIndex:(int)columnIdx; + +/** Result set integer value for column. + + @param columnName @c NSString value of the name of the column. + + @return @c int value of the result set's column. + */ + +- (int)intForColumn:(NSString*)columnName; + +/** Result set integer value for column. + + @param columnIdx Zero-based index for column. + + @return @c int value of the result set's column. + */ + +- (int)intForColumnIndex:(int)columnIdx; + +/** Result set @c long value for column. + + @param columnName @c NSString value of the name of the column. + + @return @c long value of the result set's column. + */ + +- (long)longForColumn:(NSString*)columnName; + +/** Result set long value for column. + + @param columnIdx Zero-based index for column. + + @return @c long value of the result set's column. + */ + +- (long)longForColumnIndex:(int)columnIdx; + +/** Result set `long long int` value for column. + + @param columnName @c NSString value of the name of the column. + + @return `long long int` value of the result set's column. + */ + +- (long long int)longLongIntForColumn:(NSString*)columnName; + +/** Result set `long long int` value for column. + + @param columnIdx Zero-based index for column. + + @return `long long int` value of the result set's column. + */ + +- (long long int)longLongIntForColumnIndex:(int)columnIdx; + +/** Result set `unsigned long long int` value for column. + + @param columnName @c NSString value of the name of the column. + + @return `unsigned long long int` value of the result set's column. + */ + +- (unsigned long long int)unsignedLongLongIntForColumn:(NSString*)columnName; + +/** Result set `unsigned long long int` value for column. + + @param columnIdx Zero-based index for column. + + @return `unsigned long long int` value of the result set's column. + */ + +- (unsigned long long int)unsignedLongLongIntForColumnIndex:(int)columnIdx; + +/** Result set `BOOL` value for column. + + @param columnName @c NSString value of the name of the column. + + @return `BOOL` value of the result set's column. + */ + +- (BOOL)boolForColumn:(NSString*)columnName; + +/** Result set `BOOL` value for column. + + @param columnIdx Zero-based index for column. + + @return `BOOL` value of the result set's column. + */ + +- (BOOL)boolForColumnIndex:(int)columnIdx; + +/** Result set `double` value for column. + + @param columnName @c NSString value of the name of the column. + + @return `double` value of the result set's column. + + */ + +- (double)doubleForColumn:(NSString*)columnName; + +/** Result set `double` value for column. + + @param columnIdx Zero-based index for column. + + @return `double` value of the result set's column. + + */ + +- (double)doubleForColumnIndex:(int)columnIdx; + +/** Result set @c NSString value for column. + + @param columnName @c NSString value of the name of the column. + + @return String value of the result set's column. + + */ + +- (NSString * _Nullable)stringForColumn:(NSString*)columnName; + +/** Result set @c NSString value for column. + + @param columnIdx Zero-based index for column. + + @return String value of the result set's column. + */ + +- (NSString * _Nullable)stringForColumnIndex:(int)columnIdx; + +/** Result set @c NSDate value for column. + + @param columnName @c NSString value of the name of the column. + + @return Date value of the result set's column. + */ + +- (NSDate * _Nullable)dateForColumn:(NSString*)columnName; + +/** Result set @c NSDate value for column. + + @param columnIdx Zero-based index for column. + + @return Date value of the result set's column. + + */ + +- (NSDate * _Nullable)dateForColumnIndex:(int)columnIdx; + +/** Result set @c NSData value for column. + + This is useful when storing binary data in table (such as image or the like). + + @param columnName @c NSString value of the name of the column. + + @return Data value of the result set's column. + + */ + +- (NSData * _Nullable)dataForColumn:(NSString*)columnName; + +/** Result set @c NSData value for column. + + @param columnIdx Zero-based index for column. + + @warning For zero length BLOBs, this will return `nil`. Use `typeForColumn` to determine whether this was really a zero + length BLOB or `NULL`. + + @return Data value of the result set's column. + */ + +- (NSData * _Nullable)dataForColumnIndex:(int)columnIdx; + +/** Result set `(const unsigned char *)` value for column. + + @param columnName @c NSString value of the name of the column. + + @warning For zero length BLOBs, this will return `nil`. Use `typeForColumnIndex` to determine whether this was really a zero + length BLOB or `NULL`. + + @return `(const unsigned char *)` value of the result set's column. + */ + +- (const unsigned char * _Nullable)UTF8StringForColumn:(NSString*)columnName; + +- (const unsigned char * _Nullable)UTF8StringForColumnName:(NSString*)columnName __deprecated_msg("Use UTF8StringForColumn instead"); + +/** Result set `(const unsigned char *)` value for column. + + @param columnIdx Zero-based index for column. + + @return `(const unsigned char *)` value of the result set's column. + */ + +- (const unsigned char * _Nullable)UTF8StringForColumnIndex:(int)columnIdx; + +/** Result set object for column. + + @param columnName Name of the column. + + @return Either @c NSNumber , @c NSString , @c NSData , or @c NSNull . If the column was @c NULL , this returns `[NSNull null]` object. + + @see objectForKeyedSubscript: + */ + +- (id _Nullable)objectForColumn:(NSString*)columnName; + +- (id _Nullable)objectForColumnName:(NSString*)columnName __deprecated_msg("Use objectForColumn instead"); + +/** Column type by column name. + + @param columnName Name of the column. + + @return The `SqliteValueType` of the value in this column. + */ + +- (SqliteValueType)typeForColumn:(NSString*)columnName; + +/** Column type by column index. + + @param columnIdx Index of the column. + + @return The `SqliteValueType` of the value in this column. + */ + +- (SqliteValueType)typeForColumnIndex:(int)columnIdx; + + +/** Result set object for column. + + @param columnIdx Zero-based index for column. + + @return Either @c NSNumber , @c NSString , @c NSData , or @c NSNull . If the column was @c NULL , this returns `[NSNull null]` object. + + @see objectAtIndexedSubscript: + */ + +- (id _Nullable)objectForColumnIndex:(int)columnIdx; + +/** Result set object for column. + + This method allows the use of the "boxed" syntax supported in Modern Objective-C. For example, by defining this method, the following syntax is now supported: + +@code +id result = rs[@"employee_name"]; +@endcode + + This simplified syntax is equivalent to calling: + +@code +id result = [rs objectForKeyedSubscript:@"employee_name"]; +@endcode + + which is, it turns out, equivalent to calling: + +@code +id result = [rs objectForColumnName:@"employee_name"]; +@endcode + + @param columnName @c NSString value of the name of the column. + + @return Either @c NSNumber , @c NSString , @c NSData , or @c NSNull . If the column was @c NULL , this returns `[NSNull null]` object. + */ + +- (id _Nullable)objectForKeyedSubscript:(NSString *)columnName; + +/** Result set object for column. + + This method allows the use of the "boxed" syntax supported in Modern Objective-C. For example, by defining this method, the following syntax is now supported: + +@code +id result = rs[0]; +@endcode + + This simplified syntax is equivalent to calling: + +@code +id result = [rs objectForKeyedSubscript:0]; +@endcode + + which is, it turns out, equivalent to calling: + +@code +id result = [rs objectForColumnName:0]; +@endcode + + @param columnIdx Zero-based index for column. + + @return Either @c NSNumber , @c NSString , @c NSData , or @c NSNull . If the column was @c NULL , this returns `[NSNull null]` object. + */ + +- (id _Nullable)objectAtIndexedSubscript:(int)columnIdx; + +/** Result set @c NSData value for column. + + @param columnName @c NSString value of the name of the column. + + @return Data value of the result set's column. + + @warning If you are going to use this data after you iterate over the next row, or after you close the +result set, make sure to make a copy of the data first (or just use ``/``) +If you don't, you're going to be in a world of hurt when you try and use the data. + + */ + +- (NSData * _Nullable)dataNoCopyForColumn:(NSString *)columnName NS_RETURNS_NOT_RETAINED; + +/** Result set @c NSData value for column. + + @param columnIdx Zero-based index for column. + + @return Data value of the result set's column. + + @warning If you are going to use this data after you iterate over the next row, or after you close the + result set, make sure to make a copy of the data first (or just use ``/``) + If you don't, you're going to be in a world of hurt when you try and use the data. + + */ + +- (NSData * _Nullable)dataNoCopyForColumnIndex:(int)columnIdx NS_RETURNS_NOT_RETAINED; + +/** Is the column @c NULL ? + + @param columnIdx Zero-based index for column. + + @return @c YES if column is @c NULL ; @c NO if not @c NULL . + */ + +- (BOOL)columnIndexIsNull:(int)columnIdx; + +/** Is the column @c NULL ? + + @param columnName @c NSString value of the name of the column. + + @return @c YES if column is @c NULL ; @c NO if not @c NULL . + */ + +- (BOOL)columnIsNull:(NSString*)columnName; + + +/** Returns a dictionary of the row results mapped to case sensitive keys of the column names. + + @warning The keys to the dictionary are case sensitive of the column names. + */ + +@property (nonatomic, readonly, nullable) NSDictionary *resultDictionary; + +/** Returns a dictionary of the row results + + @see resultDictionary + + @warning **Deprecated**: Please use `` instead. Also, beware that `` is case sensitive! + */ + +- (NSDictionary * _Nullable)resultDict __deprecated_msg("Use resultDictionary instead"); + +///----------------------------- +/// @name Key value coding magic +///----------------------------- + +/** Performs `setValue` to yield support for key value observing. + + @param object The object for which the values will be set. This is the key-value-coding compliant object that you might, for example, observe. + + */ + +- (void)kvcMagic:(id)object; + +///----------------------------- +/// @name Binding values +///----------------------------- + +/// Bind array of values to prepared statement. +/// +/// @param array Array of values to bind to SQL statement. + +- (BOOL)bindWithArray:(NSArray*)array; + +/// Bind dictionary of values to prepared statement. +/// +/// @param dictionary Dictionary of values to bind to SQL statement. + +- (BOOL)bindWithDictionary:(NSDictionary *)dictionary; + +@end + +NS_ASSUME_NONNULL_END diff --git a/sqflite/darwin/Classes/SqfliteDarwinResultSet.m b/sqflite/darwin/Classes/SqfliteDarwinResultSet.m new file mode 100644 index 00000000..501a52cc --- /dev/null +++ b/sqflite/darwin/Classes/SqfliteDarwinResultSet.m @@ -0,0 +1,471 @@ +#import "SqfliteDarwinResultSet.h" +#import "SqfliteDarwinDatabase.h" +#import + +#if SqfliteDarwinDB_SQLITE_STANDALONE +#import +#else +#import +#endif + +// MARK: - SqfliteDarwinDatabase Private Extension + +@interface SqfliteDarwinDatabase () +- (void)resultSetDidClose:(SqfliteDarwinResultSet *)resultSet; +- (BOOL)bindStatement:(sqlite3_stmt *)pStmt WithArgumentsInArray:(NSArray*)arrayArgs orDictionary:(NSDictionary *)dictionaryArgs orVAList:(va_list)args; +@end + +// MARK: - SqfliteDarwinResultSet Private Extension + +@interface SqfliteDarwinResultSet () { + NSMutableDictionary *_columnNameToIndexMap; +} +@property (nonatomic) BOOL shouldAutoClose; +@end + +// MARK: - SqfliteDarwinResultSet + +@implementation SqfliteDarwinResultSet + ++ (instancetype)resultSetWithStatement:(SqfliteDarwinStatement *)statement usingParentDatabase:(SqfliteDarwinDatabase*)aDB shouldAutoClose:(BOOL)shouldAutoClose { + SqfliteDarwinResultSet *rs = [[SqfliteDarwinResultSet alloc] init]; + + [rs setStatement:statement]; + [rs setParentDB:aDB]; + [rs setShouldAutoClose:shouldAutoClose]; + + NSParameterAssert(![statement inUse]); + [statement setInUse:YES]; // weak reference + + return SqfliteDarwinDBReturnAutoreleased(rs); +} + +#if ! __has_feature(objc_arc) +- (void)finalize { + [self close]; + [super finalize]; +} +#endif + +- (void)dealloc { + [self close]; + + SqfliteDarwinDBRelease(_query); + _query = nil; + + SqfliteDarwinDBRelease(_columnNameToIndexMap); + _columnNameToIndexMap = nil; + +#if ! __has_feature(objc_arc) + [super dealloc]; +#endif +} + +- (void)close { + [_statement reset]; + SqfliteDarwinDBRelease(_statement); + _statement = nil; + + // we don't need this anymore... (i think) + //[_parentDB setInUse:NO]; + [_parentDB resultSetDidClose:self]; + [self setParentDB:nil]; +} + +- (int)columnCount { + return sqlite3_column_count([_statement statement]); +} + +- (NSMutableDictionary *)columnNameToIndexMap { + if (!_columnNameToIndexMap) { + int columnCount = sqlite3_column_count([_statement statement]); + _columnNameToIndexMap = [[NSMutableDictionary alloc] initWithCapacity:(NSUInteger)columnCount]; + int columnIdx = 0; + for (columnIdx = 0; columnIdx < columnCount; columnIdx++) { + [_columnNameToIndexMap setObject:[NSNumber numberWithInt:columnIdx] + forKey:[[NSString stringWithUTF8String:sqlite3_column_name([_statement statement], columnIdx)] lowercaseString]]; + } + } + return _columnNameToIndexMap; +} + +- (void)kvcMagic:(id)object { + + int columnCount = sqlite3_column_count([_statement statement]); + + int columnIdx = 0; + for (columnIdx = 0; columnIdx < columnCount; columnIdx++) { + + const char *c = (const char *)sqlite3_column_text([_statement statement], columnIdx); + + // check for a null row + if (c) { + NSString *s = [NSString stringWithUTF8String:c]; + + [object setValue:s forKey:[NSString stringWithUTF8String:sqlite3_column_name([_statement statement], columnIdx)]]; + } + } +} + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-implementations" + +- (NSDictionary *)resultDict { + + NSUInteger num_cols = (NSUInteger)sqlite3_data_count([_statement statement]); + + if (num_cols > 0) { + NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:num_cols]; + + NSEnumerator *columnNames = [[self columnNameToIndexMap] keyEnumerator]; + NSString *columnName = nil; + while ((columnName = [columnNames nextObject])) { + id objectValue = [self objectForColumnName:columnName]; + [dict setObject:objectValue forKey:columnName]; + } + + return SqfliteDarwinDBReturnAutoreleased([dict copy]); + } + else { + NSLog(@"Warning: There seem to be no columns in this set."); + } + + return nil; +} + +#pragma clang diagnostic pop + +- (NSDictionary*)resultDictionary { + + NSUInteger num_cols = (NSUInteger)sqlite3_data_count([_statement statement]); + + if (num_cols > 0) { + NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:num_cols]; + + int columnCount = sqlite3_column_count([_statement statement]); + + int columnIdx = 0; + for (columnIdx = 0; columnIdx < columnCount; columnIdx++) { + + NSString *columnName = [NSString stringWithUTF8String:sqlite3_column_name([_statement statement], columnIdx)]; + id objectValue = [self objectForColumnIndex:columnIdx]; + [dict setObject:objectValue forKey:columnName]; + } + + return dict; + } + else { + NSLog(@"Warning: There seem to be no columns in this set."); + } + + return nil; +} + +- (BOOL)next { + return [self nextWithError:nil]; +} + +- (BOOL)nextWithError:(NSError * _Nullable __autoreleasing *)outErr { + int rc = [self internalStepWithError:outErr]; + return rc == SQLITE_ROW; +} + +- (BOOL)step { + return [self stepWithError:nil]; +} + +- (BOOL)stepWithError:(NSError * _Nullable __autoreleasing *)outErr { + int rc = [self internalStepWithError:outErr]; + return rc == SQLITE_DONE; +} + +- (int)internalStepWithError:(NSError * _Nullable __autoreleasing *)outErr { + int rc = sqlite3_step([_statement statement]); + + if (SQLITE_BUSY == rc || SQLITE_LOCKED == rc) { + NSLog(@"%s:%d Database busy (%@)", __FUNCTION__, __LINE__, [_parentDB databasePath]); + NSLog(@"Database busy"); + if (outErr) { + *outErr = [_parentDB lastError]; + } + } + else if (SQLITE_DONE == rc || SQLITE_ROW == rc) { + // all is well, let's return. + } + else if (SQLITE_ERROR == rc) { + NSLog(@"Error calling sqlite3_step (%d: %s) rs", rc, sqlite3_errmsg([_parentDB sqliteHandle])); + if (outErr) { + *outErr = [_parentDB lastError]; + } + } + else if (SQLITE_MISUSE == rc) { + // uh oh. + NSLog(@"Error calling sqlite3_step (%d: %s) rs", rc, sqlite3_errmsg([_parentDB sqliteHandle])); + if (outErr) { + if (_parentDB) { + *outErr = [_parentDB lastError]; + } + else { + // If 'next' or 'nextWithError' is called after the result set is closed, + // we need to return the appropriate error. + NSDictionary* errorMessage = [NSDictionary dictionaryWithObject:@"parentDB does not exist" forKey:NSLocalizedDescriptionKey]; + *outErr = [NSError errorWithDomain:@"SqfliteDarwinDatabase" code:SQLITE_MISUSE userInfo:errorMessage]; + } + + } + } + else { + // wtf? + NSLog(@"Unknown error calling sqlite3_step (%d: %s) rs", rc, sqlite3_errmsg([_parentDB sqliteHandle])); + if (outErr) { + *outErr = [_parentDB lastError]; + } + } + + if (rc != SQLITE_ROW && _shouldAutoClose) { + [self close]; + } + + return rc; +} + +- (BOOL)hasAnotherRow { + return sqlite3_errcode([_parentDB sqliteHandle]) == SQLITE_ROW; +} + +- (int)columnIndexForName:(NSString*)columnName { + columnName = [columnName lowercaseString]; + + NSNumber *n = [[self columnNameToIndexMap] objectForKey:columnName]; + + if (n != nil) { + return [n intValue]; + } + + NSLog(@"Warning: I could not find the column named '%@'.", columnName); + + return -1; +} + +- (int)intForColumn:(NSString*)columnName { + return [self intForColumnIndex:[self columnIndexForName:columnName]]; +} + +- (int)intForColumnIndex:(int)columnIdx { + return sqlite3_column_int([_statement statement], columnIdx); +} + +- (long)longForColumn:(NSString*)columnName { + return [self longForColumnIndex:[self columnIndexForName:columnName]]; +} + +- (long)longForColumnIndex:(int)columnIdx { + return (long)sqlite3_column_int64([_statement statement], columnIdx); +} + +- (long long int)longLongIntForColumn:(NSString*)columnName { + return [self longLongIntForColumnIndex:[self columnIndexForName:columnName]]; +} + +- (long long int)longLongIntForColumnIndex:(int)columnIdx { + return sqlite3_column_int64([_statement statement], columnIdx); +} + +- (unsigned long long int)unsignedLongLongIntForColumn:(NSString*)columnName { + return [self unsignedLongLongIntForColumnIndex:[self columnIndexForName:columnName]]; +} + +- (unsigned long long int)unsignedLongLongIntForColumnIndex:(int)columnIdx { + return (unsigned long long int)[self longLongIntForColumnIndex:columnIdx]; +} + +- (BOOL)boolForColumn:(NSString*)columnName { + return [self boolForColumnIndex:[self columnIndexForName:columnName]]; +} + +- (BOOL)boolForColumnIndex:(int)columnIdx { + return ([self intForColumnIndex:columnIdx] != 0); +} + +- (double)doubleForColumn:(NSString*)columnName { + return [self doubleForColumnIndex:[self columnIndexForName:columnName]]; +} + +- (double)doubleForColumnIndex:(int)columnIdx { + return sqlite3_column_double([_statement statement], columnIdx); +} + +- (NSString *)stringForColumnIndex:(int)columnIdx { + + if (sqlite3_column_type([_statement statement], columnIdx) == SQLITE_NULL || (columnIdx < 0) || columnIdx >= sqlite3_column_count([_statement statement])) { + return nil; + } + + const char *c = (const char *)sqlite3_column_text([_statement statement], columnIdx); + + if (!c) { + // null row. + return nil; + } + + return [NSString stringWithUTF8String:c]; +} + +- (NSString*)stringForColumn:(NSString*)columnName { + return [self stringForColumnIndex:[self columnIndexForName:columnName]]; +} + +- (NSDate*)dateForColumn:(NSString*)columnName { + return [self dateForColumnIndex:[self columnIndexForName:columnName]]; +} + +- (NSDate*)dateForColumnIndex:(int)columnIdx { + + if (sqlite3_column_type([_statement statement], columnIdx) == SQLITE_NULL || (columnIdx < 0) || columnIdx >= sqlite3_column_count([_statement statement])) { + return nil; + } + + return [_parentDB hasDateFormatter] ? [_parentDB dateFromString:[self stringForColumnIndex:columnIdx]] : [NSDate dateWithTimeIntervalSince1970:[self doubleForColumnIndex:columnIdx]]; +} + + +- (NSData*)dataForColumn:(NSString*)columnName { + return [self dataForColumnIndex:[self columnIndexForName:columnName]]; +} + +- (NSData*)dataForColumnIndex:(int)columnIdx { + + if (sqlite3_column_type([_statement statement], columnIdx) == SQLITE_NULL || (columnIdx < 0) || columnIdx >= sqlite3_column_count([_statement statement])) { + return nil; + } + + const char *dataBuffer = sqlite3_column_blob([_statement statement], columnIdx); + int dataSize = sqlite3_column_bytes([_statement statement], columnIdx); + + if (dataBuffer == NULL) { + return nil; + } + + return [NSData dataWithBytes:(const void *)dataBuffer length:(NSUInteger)dataSize]; +} + + +- (NSData*)dataNoCopyForColumn:(NSString*)columnName { + return [self dataNoCopyForColumnIndex:[self columnIndexForName:columnName]]; +} + +- (NSData*)dataNoCopyForColumnIndex:(int)columnIdx { + + if (sqlite3_column_type([_statement statement], columnIdx) == SQLITE_NULL || (columnIdx < 0) || columnIdx >= sqlite3_column_count([_statement statement])) { + return nil; + } + + const char *dataBuffer = sqlite3_column_blob([_statement statement], columnIdx); + int dataSize = sqlite3_column_bytes([_statement statement], columnIdx); + + NSData *data = [NSData dataWithBytesNoCopy:(void *)dataBuffer length:(NSUInteger)dataSize freeWhenDone:NO]; + + return data; +} + + +- (BOOL)columnIndexIsNull:(int)columnIdx { + return sqlite3_column_type([_statement statement], columnIdx) == SQLITE_NULL; +} + +- (BOOL)columnIsNull:(NSString*)columnName { + return [self columnIndexIsNull:[self columnIndexForName:columnName]]; +} + +- (const unsigned char *)UTF8StringForColumnIndex:(int)columnIdx { + + if (sqlite3_column_type([_statement statement], columnIdx) == SQLITE_NULL || (columnIdx < 0) || columnIdx >= sqlite3_column_count([_statement statement])) { + return nil; + } + + return sqlite3_column_text([_statement statement], columnIdx); +} + +- (const unsigned char *)UTF8StringForColumn:(NSString*)columnName { + return [self UTF8StringForColumnIndex:[self columnIndexForName:columnName]]; +} + +- (const unsigned char *)UTF8StringForColumnName:(NSString*)columnName { + return [self UTF8StringForColumn:columnName]; +} + +- (id)objectForColumnIndex:(int)columnIdx { + if (columnIdx < 0 || columnIdx >= sqlite3_column_count([_statement statement])) { + return nil; + } + + int columnType = sqlite3_column_type([_statement statement], columnIdx); + + id returnValue = nil; + + if (columnType == SQLITE_INTEGER) { + returnValue = [NSNumber numberWithLongLong:[self longLongIntForColumnIndex:columnIdx]]; + } + else if (columnType == SQLITE_FLOAT) { + returnValue = [NSNumber numberWithDouble:[self doubleForColumnIndex:columnIdx]]; + } + else if (columnType == SQLITE_BLOB) { + returnValue = [self dataForColumnIndex:columnIdx]; + } + else { + //default to a string for everything else + returnValue = [self stringForColumnIndex:columnIdx]; + } + + if (returnValue == nil) { + returnValue = [NSNull null]; + } + + return returnValue; +} + +- (id)objectForColumnName:(NSString*)columnName { + return [self objectForColumn:columnName]; +} + +- (id)objectForColumn:(NSString*)columnName { + return [self objectForColumnIndex:[self columnIndexForName:columnName]]; +} + +- (SqliteValueType)typeForColumn:(NSString*)columnName { + return sqlite3_column_type([_statement statement], [self columnIndexForName:columnName]); +} + +- (SqliteValueType)typeForColumnIndex:(int)columnIdx { + return sqlite3_column_type([_statement statement], columnIdx); +} + +// returns autoreleased NSString containing the name of the column in the result set +- (NSString*)columnNameForIndex:(int)columnIdx { + return [NSString stringWithUTF8String: sqlite3_column_name([_statement statement], columnIdx)]; +} + +- (id)objectAtIndexedSubscript:(int)columnIdx { + return [self objectForColumnIndex:columnIdx]; +} + +- (id)objectForKeyedSubscript:(NSString *)columnName { + return [self objectForColumn:columnName]; +} + +// MARK: Bind + +- (BOOL)bindWithArray:(NSArray*)array orDictionary:(NSDictionary *)dictionary orVAList:(va_list)args { + [_statement reset]; + return [_parentDB bindStatement:_statement.statement WithArgumentsInArray:array orDictionary:dictionary orVAList:args]; +} + +- (BOOL)bindWithArray:(NSArray*)array { + return [self bindWithArray:array orDictionary:nil orVAList:nil]; +} + +- (BOOL)bindWithDictionary:(NSDictionary *)dictionary { + return [self bindWithArray:nil orDictionary:dictionary orVAList:nil]; +} + +@end diff --git a/sqflite/darwin/Classes/SqfliteDatabase.h b/sqflite/darwin/Classes/SqfliteDatabase.h index 9c0cdcd6..f9985903 100644 --- a/sqflite/darwin/Classes/SqfliteDatabase.h +++ b/sqflite/darwin/Classes/SqfliteDatabase.h @@ -10,10 +10,10 @@ #import "SqfliteCursor.h" #import "SqfliteOperation.h" -@class FMDatabaseQueue,FMDatabase; +@class SqfliteDarwinDatabaseQueue,SqfliteDarwinDatabase; @interface SqfliteDatabase : NSObject -@property (atomic, retain) FMDatabaseQueue *fmDatabaseQueue; +@property (atomic, retain) SqfliteDarwinDatabaseQueue *fmDatabaseQueue; @property (atomic, retain) NSNumber *databaseId; @property (atomic, retain) NSString* path; @property (nonatomic) bool singleInstance; @@ -29,13 +29,13 @@ - (void)closeCursorById:(NSNumber*)cursorId; - (void)closeCursor:(SqfliteCursor*)cursor; -- (void)inDatabase:(void (^)(FMDatabase *db))block; -- (void)dbBatch:(FMDatabase*)db operation:(SqfliteMethodCallOperation*)mainOperation; -- (void)dbExecute:(FMDatabase*)db operation:(SqfliteOperation*)operation; -- (void)dbInsert:(FMDatabase*)db operation:(SqfliteOperation*)operation; -- (void)dbUpdate:(FMDatabase*)db operation:(SqfliteOperation*)operation; -- (void)dbQuery:(FMDatabase*)db operation:(SqfliteOperation*)operation; -- (void)dbQueryCursorNext:(FMDatabase*)db operation:(SqfliteOperation*)operation; +- (void)inDatabase:(void (^)(SqfliteDarwinDatabase *db))block; +- (void)dbBatch:(SqfliteDarwinDatabase*)db operation:(SqfliteMethodCallOperation*)mainOperation; +- (void)dbExecute:(SqfliteDarwinDatabase*)db operation:(SqfliteOperation*)operation; +- (void)dbInsert:(SqfliteDarwinDatabase*)db operation:(SqfliteOperation*)operation; +- (void)dbUpdate:(SqfliteDarwinDatabase*)db operation:(SqfliteOperation*)operation; +- (void)dbQuery:(SqfliteDarwinDatabase*)db operation:(SqfliteOperation*)operation; +- (void)dbQueryCursorNext:(SqfliteDarwinDatabase*)db operation:(SqfliteOperation*)operation; @end #endif // SqfliteDatabase_h diff --git a/sqflite/darwin/Classes/SqfliteDatabase.m b/sqflite/darwin/Classes/SqfliteDatabase.m index 772e9e6e..16733e33 100644 --- a/sqflite/darwin/Classes/SqfliteDatabase.m +++ b/sqflite/darwin/Classes/SqfliteDatabase.m @@ -1,6 +1,6 @@ #import "SqfliteDatabase.h" #import "SqflitePlugin.h" -#import "SqfliteFmdbImport.m" +#import "SqfliteDarwinImport.h" #import @@ -16,8 +16,8 @@ static int transactionIdForce = -1; // Import hidden method -@interface FMDatabase () -- (void)resultSetDidClose:(FMResultSet *)resultSet; +@interface SqfliteDarwinDatabase () +- (void)resultSetDidClose:(SqfliteDarwinResultSet *)resultSet; @end @implementation SqfliteDatabase @@ -37,20 +37,20 @@ - (instancetype)init { } -- (void)inDatabase:(void (^)(FMDatabase *db))block { +- (void)inDatabase:(void (^)(SqfliteDarwinDatabase *db))block { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ [self.fmDatabaseQueue inDatabase:block]; }); } -- (void)dbHandleError:(FMDatabase*)db result:(FlutterResult)result { +- (void)dbHandleError:(SqfliteDarwinDatabase*)db result:(FlutterResult)result { // handle error result([FlutterError errorWithCode:SqliteErrorCode message:[NSString stringWithFormat:@"%@", [db lastError]] details:nil]); } -- (void)dbHandleError:(FMDatabase*)db operation:(SqfliteOperation*)operation { +- (void)dbHandleError:(SqfliteDarwinDatabase*)db operation:(SqfliteOperation*)operation { NSMutableDictionary* details = nil; NSString* sql = [operation getSql]; if (sql != nil) { @@ -68,7 +68,7 @@ - (void)dbHandleError:(FMDatabase*)db operation:(SqfliteOperation*)operation { } -- (void)dbRunQueuedOperations:(FMDatabase*)db { +- (void)dbRunQueuedOperations:(SqfliteDarwinDatabase*)db { while (![SqflitePlugin arrayIsEmpy:noTransactionOperationQueue]) { if (currentTransactionId != nil) { break; @@ -79,7 +79,7 @@ - (void)dbRunQueuedOperations:(FMDatabase*)db { } } -- (void)wrapSqlOperationHandler:(FMDatabase*)db operation:(SqfliteOperation*)operation handler:(SqfliteOperationHandler)handler { +- (void)wrapSqlOperationHandler:(SqfliteDarwinDatabase*)db operation:(SqfliteOperation*)operation handler:(SqfliteOperationHandler)handler { NSNumber* transactionId = [operation getTransactionId]; if (currentTransactionId == nil) { // ignore @@ -98,7 +98,7 @@ - (void)wrapSqlOperationHandler:(FMDatabase*)db operation:(SqfliteOperation*)ope } } -- (bool)dbDoExecute:(FMDatabase*)db operation:(SqfliteOperation*)operation { +- (bool)dbDoExecute:(SqfliteDarwinDatabase*)db operation:(SqfliteOperation*)operation { if (![self dbExecuteOrError:db operation:operation]) { return false; } @@ -106,8 +106,8 @@ - (bool)dbDoExecute:(FMDatabase*)db operation:(SqfliteOperation*)operation { return true; } -- (void)dbExecute:(FMDatabase*)db operation:(SqfliteOperation*)operation { - [self wrapSqlOperationHandler:db operation:operation handler:^(FMDatabase* db, SqfliteOperation* operation) { +- (void)dbExecute:(SqfliteDarwinDatabase*)db operation:(SqfliteOperation*)operation { + [self wrapSqlOperationHandler:db operation:operation handler:^(SqfliteDarwinDatabase* db, SqfliteOperation* operation) { NSNumber* inTransactionChange = [operation getInTransactionChange]; bool hasNullTransactionId = [operation hasNullTransactionId]; bool enteringTransaction = [inTransactionChange boolValue] == true && hasNullTransactionId; @@ -136,7 +136,7 @@ - (void)dbExecute:(FMDatabase*)db operation:(SqfliteOperation*)operation { }]; } -- (bool)dbExecuteOrError:(FMDatabase*)db operation:(SqfliteOperation*)operation { +- (bool)dbExecuteOrError:(SqfliteDarwinDatabase*)db operation:(SqfliteOperation*)operation { NSString* sql = [operation getSql]; NSArray* sqlArguments = [operation getSqlArguments]; NSNumber* inTransaction = [operation getInTransactionChange]; @@ -186,12 +186,12 @@ - (bool)dbExecuteOrError:(FMDatabase*)db operation:(SqfliteOperation*)operation // // insert // -- (void)dbInsert:(FMDatabase*)db operation:(SqfliteOperation*)operation { - [self wrapSqlOperationHandler:db operation:operation handler:^(FMDatabase* db, SqfliteOperation* operation) { +- (void)dbInsert:(SqfliteDarwinDatabase*)db operation:(SqfliteOperation*)operation { + [self wrapSqlOperationHandler:db operation:operation handler:^(SqfliteDarwinDatabase* db, SqfliteOperation* operation) { [self dbDoInsert:db operation:operation]; }]; } -- (bool)dbDoInsert:(FMDatabase*)db operation:(SqfliteOperation*)operation { +- (bool)dbDoInsert:(SqfliteDarwinDatabase*)db operation:(SqfliteOperation*)operation { if (![self dbExecuteOrError:db operation:operation]) { return false; } @@ -217,12 +217,12 @@ - (bool)dbDoInsert:(FMDatabase*)db operation:(SqfliteOperation*)operation { return true; } -- (void)dbUpdate:(FMDatabase*)db operation:(SqfliteOperation*)operation { - [self wrapSqlOperationHandler:db operation:operation handler:^(FMDatabase* db, SqfliteOperation* operation) { +- (void)dbUpdate:(SqfliteDarwinDatabase*)db operation:(SqfliteOperation*)operation { + [self wrapSqlOperationHandler:db operation:operation handler:^(SqfliteDarwinDatabase* db, SqfliteOperation* operation) { [self dbDoUpdate:db operation:operation]; }]; } -- (bool)dbDoUpdate:(FMDatabase*)db operation:(SqfliteOperation*)operation { +- (bool)dbDoUpdate:(SqfliteDarwinDatabase*)db operation:(SqfliteOperation*)operation { if (![self dbExecuteOrError:db operation:operation]) { return false; } @@ -241,13 +241,13 @@ - (bool)dbDoUpdate:(FMDatabase*)db operation:(SqfliteOperation*)operation { // // query // -- (void)dbQuery:(FMDatabase*)db operation:(SqfliteOperation*)operation { - [self wrapSqlOperationHandler:db operation:operation handler:^(FMDatabase* db, SqfliteOperation* operation) { +- (void)dbQuery:(SqfliteDarwinDatabase*)db operation:(SqfliteOperation*)operation { + [self wrapSqlOperationHandler:db operation:operation handler:^(SqfliteDarwinDatabase* db, SqfliteOperation* operation) { [self dbDoQuery:db operation:operation]; }]; } -- (bool)dbDoQuery:(FMDatabase*)db operation:(SqfliteOperation*)operation { +- (bool)dbDoQuery:(SqfliteDarwinDatabase*)db operation:(SqfliteOperation*)operation { NSString* sql = [operation getSql]; NSArray* sqlArguments = [operation getSqlArguments]; bool argumentsEmpty = [SqflitePlugin arrayIsEmpy:sqlArguments]; @@ -258,7 +258,7 @@ - (bool)dbDoQuery:(FMDatabase*)db operation:(SqfliteOperation*)operation { NSLog(@"%@ %@", sql, argumentsEmpty ? @"" : sqlArguments); } - FMResultSet *resultSet; + SqfliteDarwinResultSet *resultSet; if (!argumentsEmpty) { resultSet = [db executeQuery:sql withArgumentsInArray:sqlArguments]; } else { @@ -287,7 +287,7 @@ - (bool)dbDoQuery:(FMDatabase*)db operation:(SqfliteOperation*)operation { self.cursorMap[cursorId] = cursor; // Notify cursor support in the result results[_paramCursorId] = cursorId; - // Prevent FMDB warning, we keep a result set open on purpose + // Prevent SqfliteDarwinDB warning, we keep a result set open on purpose [db resultSetDidClose:resultSet]; } } @@ -302,7 +302,7 @@ - (bool)dbDoQuery:(FMDatabase*)db operation:(SqfliteOperation*)operation { // query // -- (void)dbQueryCursorNext:(FMDatabase*)db operation:(SqfliteOperation*)operation { +- (void)dbQueryCursorNext:(SqfliteDarwinDatabase*)db operation:(SqfliteOperation*)operation { NSNumber* cursorId = [operation getArgument:_paramCursorId]; NSNumber* cancelValue = [operation getArgument:_paramCancel]; @@ -324,14 +324,14 @@ - (void)dbQueryCursorNext:(FMDatabase*)db operation:(SqfliteOperation*)operation details:nil]]; return; } - FMResultSet* resultSet = cursor.resultSet; + SqfliteDarwinResultSet* resultSet = cursor.resultSet; NSMutableDictionary* results = [SqflitePlugin resultSetToResults:resultSet cursorPageSize:cursor.pageSize]; bool cursorHasMoreData = [resultSet hasAnotherRow]; if (cursorHasMoreData) { // Keep the cursorId to specify that we have more data. results[_paramCursorId] = cursorId; - // Prevent FMDB warning, we keep a result set open on purpose + // Prevent SqfliteDarwinDB warning, we keep a result set open on purpose [db resultSetDidClose:resultSet]; } else { [self closeCursor:cursor]; @@ -343,7 +343,7 @@ - (void)dbQueryCursorNext:(FMDatabase*)db operation:(SqfliteOperation*)operation } -- (void)dbBatch:(FMDatabase*)db operation:(SqfliteMethodCallOperation*)mainOperation { +- (void)dbBatch:(SqfliteDarwinDatabase*)db operation:(SqfliteMethodCallOperation*)mainOperation { bool noResult = [mainOperation getNoResult]; bool continueOnError = [mainOperation getContinueOnError]; diff --git a/sqflite/darwin/Classes/SqfliteFmdbImport.m b/sqflite/darwin/Classes/SqfliteFmdbImport.m deleted file mode 100644 index e2bab053..00000000 --- a/sqflite/darwin/Classes/SqfliteFmdbImport.m +++ /dev/null @@ -1,18 +0,0 @@ -// -// SqfliteFmdbImport.m -// Shared import for FMDB -// -// Not a header file as XCode might complain. -// -// Created by Alexandre Roux on 03/12/2022. -// -#ifndef SqfliteFmdbImport_m -#define SqfliteFmdbImport_m - -#if __has_include() -#import -#else -@import FMDB; -#endif - -#endif /* SqfliteFmdbImport_m */ diff --git a/sqflite/darwin/Classes/SqfliteOperation.h b/sqflite/darwin/Classes/SqfliteOperation.h index 2ffd7193..d35180ec 100644 --- a/sqflite/darwin/Classes/SqfliteOperation.h +++ b/sqflite/darwin/Classes/SqfliteOperation.h @@ -9,7 +9,7 @@ #import "SqfliteImport.h" -@class FMDatabase; +@class SqfliteDarwinDatabase; @interface SqfliteOperation : NSObject - (NSString*)getMethod; @@ -51,7 +51,7 @@ @end -typedef void(^SqfliteOperationHandler)(FMDatabase* db, SqfliteOperation* operation); +typedef void(^SqfliteOperationHandler)(SqfliteDarwinDatabase* db, SqfliteOperation* operation); @interface SqfliteQueuedOperation : NSObject @property (atomic, retain) SqfliteOperation* operation; diff --git a/sqflite/darwin/Classes/SqfliteOperation.m b/sqflite/darwin/Classes/SqfliteOperation.m index 037d4ab1..d791055a 100644 --- a/sqflite/darwin/Classes/SqfliteOperation.m +++ b/sqflite/darwin/Classes/SqfliteOperation.m @@ -8,7 +8,7 @@ #import #import "SqfliteOperation.h" #import "SqflitePlugin.h" -#import "SqfliteFmdbImport.m" +#import "SqfliteDarwinImport.h" // Abstract @implementation SqfliteOperation diff --git a/sqflite/darwin/Classes/SqflitePlugin.h b/sqflite/darwin/Classes/SqflitePlugin.h index 26079c92..45ea9ae7 100644 --- a/sqflite/darwin/Classes/SqflitePlugin.h +++ b/sqflite/darwin/Classes/SqflitePlugin.h @@ -9,12 +9,12 @@ #import "SqfliteImport.h" -@class FMResultSet; +@class SqfliteDarwinResultSet; @interface SqflitePlugin : NSObject + (NSArray*)toSqlArguments:(NSArray*)rawArguments; + (bool)arrayIsEmpy:(NSArray*)array; -+ (NSMutableDictionary*)resultSetToResults:(FMResultSet*)resultSet cursorPageSize:(NSNumber*)cursorPageSize; ++ (NSMutableDictionary*)resultSetToResults:(SqfliteDarwinResultSet*)resultSet cursorPageSize:(NSNumber*)cursorPageSize; @end diff --git a/sqflite/darwin/Classes/SqflitePlugin.m b/sqflite/darwin/Classes/SqflitePlugin.m index 9dc79a44..b2948308 100644 --- a/sqflite/darwin/Classes/SqflitePlugin.m +++ b/sqflite/darwin/Classes/SqflitePlugin.m @@ -1,7 +1,7 @@ #import "SqflitePlugin.h" #import "SqfliteDatabase.h" #import "SqfliteOperation.h" -#import "SqfliteFmdbImport.m" +#import "SqfliteDarwinImport.h" #import @@ -79,8 +79,8 @@ NSString *const SqfliteSqlPragmaSqliteDefensiveOff = @"PRAGMA sqflite -- db_config_defensive_off"; // Import hidden method -@interface FMDatabase () -- (void)resultSetDidClose:(FMResultSet *)resultSet; +@interface SqfliteDarwinDatabase () +- (void)resultSetDidClose:(SqfliteDarwinResultSet *)resultSet; @end @interface SqflitePlugin () @@ -163,14 +163,14 @@ - (SqfliteDatabase *)getDatabaseOrError:(FlutterMethodCall*)call result:(Flutter return database; } -- (void)handleError:(FMDatabase*)db result:(FlutterResult)result { +- (void)handleError:(SqfliteDarwinDatabase*)db result:(FlutterResult)result { // handle error result([FlutterError errorWithCode:SqliteErrorCode message:[NSString stringWithFormat:@"%@", [db lastError]] details:nil]); } -- (void)handleError:(FMDatabase*)db operation:(SqfliteOperation*)operation { +- (void)handleError:(SqfliteDarwinDatabase*)db operation:(SqfliteOperation*)operation { NSMutableDictionary* details = nil; NSString* sql = [operation getSql]; if (sql != nil) { @@ -248,7 +248,7 @@ + (NSDictionary*)fromSqlDictionary:(NSDictionary*)sqlDictionary { } // TODO remove -- (bool)executeOrError:(SqfliteDatabase*)database fmdb:(FMDatabase*)db call:(FlutterMethodCall*)call result:(FlutterResult)result { +- (bool)executeOrError:(SqfliteDatabase*)database fmdb:(SqfliteDarwinDatabase*)db call:(FlutterMethodCall*)call result:(FlutterResult)result { NSString* sql = call.arguments[SqfliteParamSql]; NSArray* arguments = call.arguments[SqfliteParamSqlArguments]; NSArray* sqlArguments = [SqflitePlugin toSqlArguments:arguments]; @@ -273,7 +273,7 @@ - (bool)executeOrError:(SqfliteDatabase*)database fmdb:(FMDatabase*)db call:(Flu return true; } -- (bool)executeOrError:(SqfliteDatabase*)database fmdb:(FMDatabase*)db operation:(SqfliteOperation*)operation { +- (bool)executeOrError:(SqfliteDatabase*)database fmdb:(SqfliteDarwinDatabase*)db operation:(SqfliteOperation*)operation { NSString* sql = [operation getSql]; NSArray* sqlArguments = [operation getSqlArguments]; NSNumber* inTransaction = [operation getInTransactionChange]; @@ -320,11 +320,11 @@ - (bool)executeOrError:(SqfliteDatabase*)database fmdb:(FMDatabase*)db operation } // Rewrite to handle empty bloc reported as null -// refer to original FMResultSet.objectForColumnIndex, removed -// when fixed in FMDB +// refer to original SqfliteDarwinResultSet.objectForColumnIndex, removed +// when fixed in SqfliteDarwinDB // See https://github.com/ccgus/fmdb/issues/350 for information -+ (id)rsObjectForColumn:(FMResultSet*)rs index:(int)columnIdx { - FMStatement* _statement = [rs statement]; ++ (id)rsObjectForColumn:(SqfliteDarwinResultSet*)rs index:(int)columnIdx { + SqfliteDarwinStatement* _statement = [rs statement]; if (columnIdx < 0 || columnIdx >= sqlite3_column_count([_statement statement])) { return nil; } @@ -359,7 +359,7 @@ + (id)rsObjectForColumn:(FMResultSet*)rs index:(int)columnIdx { } // if cursorPageSize is not null, we limit the result count -+ (NSMutableDictionary*)resultSetToResults:(FMResultSet*)resultSet cursorPageSize:(NSNumber*)cursorPageSize { ++ (NSMutableDictionary*)resultSetToResults:(SqfliteDarwinResultSet*)resultSet cursorPageSize:(NSNumber*)cursorPageSize { NSMutableDictionary* results = [NSMutableDictionary new]; NSMutableArray* columns = nil; NSMutableArray* rows; @@ -394,7 +394,7 @@ + (NSMutableDictionary*)resultSetToResults:(FMResultSet*)resultSet cursorPageSiz // // query // -- (bool)query:(SqfliteDatabase*)database fmdb:(FMDatabase*)db operation:(SqfliteOperation*)operation { +- (bool)query:(SqfliteDatabase*)database fmdb:(SqfliteDarwinDatabase*)db operation:(SqfliteOperation*)operation { NSString* sql = [operation getSql]; NSArray* sqlArguments = [operation getSqlArguments]; bool argumentsEmpty = [SqflitePlugin arrayIsEmpy:sqlArguments]; @@ -405,7 +405,7 @@ - (bool)query:(SqfliteDatabase*)database fmdb:(FMDatabase*)db operation:(Sqflite NSLog(@"%@ %@", sql, argumentsEmpty ? @"" : sqlArguments); } - FMResultSet *resultSet; + SqfliteDarwinResultSet *resultSet; if (!argumentsEmpty) { resultSet = [db executeQuery:sql withArgumentsInArray:sqlArguments]; } else { @@ -434,7 +434,7 @@ - (bool)query:(SqfliteDatabase*)database fmdb:(FMDatabase*)db operation:(Sqflite database.cursorMap[cursorId] = cursor; // Notify cursor support in the result results[_paramCursorId] = cursorId; - // Prevent FMDB warning, we keep a result set open on purpose + // Prevent SqfliteDarwinDB warning, we keep a result set open on purpose [db resultSetDidClose:resultSet]; } } @@ -448,7 +448,7 @@ - (void)handleQueryCall:(FlutterMethodCall*)call result:(FlutterResult)result { if (database == nil) { return; } - [database inDatabase:^(FMDatabase *db) { + [database inDatabase:^(SqfliteDarwinDatabase *db) { SqfliteMethodCallOperation* operation = [SqfliteMethodCallOperation newWithCall:call result:result]; [database dbQuery:db operation:operation]; }]; @@ -461,7 +461,7 @@ - (void)handleQueryCursorNextCall:(FlutterMethodCall*)call result:(FlutterResult if (database == nil) { return; } - [database inDatabase:^(FMDatabase *db) { + [database inDatabase:^(SqfliteDarwinDatabase *db) { SqfliteMethodCallOperation* operation = [SqfliteMethodCallOperation newWithCall:call result:result]; [database dbQueryCursorNext:db operation:operation]; }]; @@ -474,7 +474,7 @@ - (void)handleInsertCall:(FlutterMethodCall*)call result:(FlutterResult)result { if (database == nil) { return; } - [database inDatabase:^(FMDatabase *db) { + [database inDatabase:^(SqfliteDarwinDatabase *db) { SqfliteMethodCallOperation* operation = [SqfliteMethodCallOperation newWithCall:call result:result]; [database dbInsert:db operation:operation]; }]; @@ -488,7 +488,7 @@ - (void)handleUpdateCall:(FlutterMethodCall*)call result:(FlutterResult)result { return; } - [database inDatabase:^(FMDatabase *db) { + [database inDatabase:^(SqfliteDarwinDatabase *db) { SqfliteMethodCallOperation* operation = [SqfliteMethodCallOperation newWithCall:call result:result]; [database dbUpdate:db operation:operation]; }]; @@ -502,7 +502,7 @@ - (void)handleExecuteCall:(FlutterMethodCall*)call result:(FlutterResult)result return; } - [database inDatabase:^(FMDatabase *db) { + [database inDatabase:^(SqfliteDarwinDatabase *db) { SqfliteMethodCallOperation* operation = [SqfliteMethodCallOperation newWithCall:call result:result]; [database dbExecute:db operation:operation]; }]; @@ -517,7 +517,7 @@ - (void)handleBatchCall:(FlutterMethodCall*)call result:(FlutterResult)result { return; } - [database inDatabase:^(FMDatabase *db) { + [database inDatabase:^(SqfliteDarwinDatabase *db) { SqfliteMethodCallOperation* mainOperation = [SqfliteMethodCallOperation newWithCall:call result:result]; [database dbBatch:db operation:mainOperation]; @@ -591,7 +591,7 @@ - (void)handleOpenDatabaseCall:(FlutterMethodCall*)call result:(FlutterResult)re // Ingore the error, it will break later during open } } - FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:path flags:(readOnly ? SQLITE_OPEN_READONLY : (SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE))]; + SqfliteDarwinDatabaseQueue *queue = [SqfliteDarwinDatabaseQueue databaseQueueWithPath:path flags:(readOnly ? SQLITE_OPEN_READONLY : (SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE))]; bool success = queue != nil; if (!success) { @@ -605,7 +605,7 @@ - (void)handleOpenDatabaseCall:(FlutterMethodCall*)call result:(FlutterResult)re // First call will be to prepare the database. // We turn on extended result code, allowing failure dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ - [queue inDatabase:^(FMDatabase *db) { + [queue inDatabase:^(SqfliteDarwinDatabase *db) { sqlite3_extended_result_codes(db.sqliteHandle, 1); }]; }); @@ -674,7 +674,7 @@ - (void)closeDatabase:(SqfliteDatabase*)database callback:(void(^)(void))callbac } } } - FMDatabaseQueue* queue = database.fmDatabaseQueue; + SqfliteDarwinDatabaseQueue* queue = database.fmDatabaseQueue; dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ // It is safe to call this from a background queue because the function // dispatches immediately to its queue synchronously. diff --git a/sqflite/darwin/README.md b/sqflite/darwin/README.md new file mode 100644 index 00000000..066a19ea --- /dev/null +++ b/sqflite/darwin/README.md @@ -0,0 +1,12 @@ +# Darwin implementation of sqflite plugin. + +Initial implementation was using a subset of FMDB available through Cocoapods. FMDB +cocoapod version has been stuck at 2.7.5 for a long time and my iOS/MacOS is limited +to propose a proper PR to FMDB and take ownership of the FMDB pod. + +As of 2024/01/27, I made the decision to fork/copy FMDB and use it directly in sqflite assuming [FMDB_LICENSE](FMDB_LICENSE.txt) +MIT license allows it. + +Only what is necessary has been copied and renamed to avoid name collision. (FMDB -> SqfliteDarwin) + +I hope everyone is OK with this decision. I'm open to any suggestion or bug report if I missed something. \ No newline at end of file diff --git a/sqflite/darwin/sqflite.podspec b/sqflite/darwin/sqflite.podspec index 0c903026..a5504afb 100644 --- a/sqflite/darwin/sqflite.podspec +++ b/sqflite/darwin/sqflite.podspec @@ -14,7 +14,6 @@ Access SQLite database. s.source = { :path => '.' } s.source_files = 'Classes/**/*' s.public_header_files = 'Classes/**/*.h' - s.dependency 'FMDB', '>= 2.7.5' s.ios.dependency 'Flutter' s.osx.dependency 'FlutterMacOS' s.ios.deployment_target = '12.0' diff --git a/sqflite/example/lib/exception_test_page.dart b/sqflite/example/lib/exception_test_page.dart index e360990f..505e6bfc 100644 --- a/sqflite/example/lib/exception_test_page.dart +++ b/sqflite/example/lib/exception_test_page.dart @@ -360,8 +360,8 @@ class ExceptionTestPage extends TestPage { await db.close(); }); - test('Bind no argument (no iOS)', () async { - if (!platform.isIOS) { + test('Bind no argument (no iOS/MacOS)', () async { + if (!platform.isIOS && !platform.isMacOS) { // await Sqflite.devSetDebugModeOn(true); final path = await initDeleteDb('bind_no_arg_failed.db'); final db = await openDatabase(path);