No Description

AWSFMDatabase.m 42KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446
  1. #import "AWSFMDatabase.h"
  2. #import "unistd.h"
  3. #import <objc/runtime.h>
  4. #import "AWSFMDatabase+Private.h"
  5. @interface AWSFMDatabase ()
  6. @property (nonatomic, assign) sqlite3 *db;
  7. - (AWSFMResultSet *)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray*)arrayArgs orDictionary:(NSDictionary *)dictionaryArgs orVAList:(va_list)args;
  8. - (BOOL)executeUpdate:(NSString*)sql error:(NSError**)outErr withArgumentsInArray:(NSArray*)arrayArgs orDictionary:(NSDictionary *)dictionaryArgs orVAList:(va_list)args;
  9. @end
  10. @implementation AWSFMDatabase
  11. @synthesize cachedStatements=_cachedStatements;
  12. @synthesize logsErrors=_logsErrors;
  13. @synthesize crashOnErrors=_crashOnErrors;
  14. @synthesize checkedOut=_checkedOut;
  15. @synthesize traceExecution=_traceExecution;
  16. #pragma mark FMDatabase instantiation and deallocation
  17. + (instancetype)databaseWithPath:(NSString*)aPath {
  18. return AWSFMDBReturnAutoreleased([[self alloc] initWithPath:aPath]);
  19. }
  20. - (instancetype)init {
  21. return [self initWithPath:nil];
  22. }
  23. - (instancetype)initWithPath:(NSString*)aPath {
  24. assert(sqlite3_threadsafe()); // whoa there big boy- gotta make sure sqlite it happy with what we're going to do.
  25. self = [super init];
  26. if (self) {
  27. _databasePath = [aPath copy];
  28. _openResultSets = [[NSMutableSet alloc] init];
  29. _db = nil;
  30. _logsErrors = YES;
  31. _crashOnErrors = NO;
  32. _maxBusyRetryTimeInterval = 2;
  33. }
  34. return self;
  35. }
  36. #if ! __has_feature(objc_arc)
  37. - (void)finalize {
  38. [self close];
  39. [super finalize];
  40. }
  41. #endif
  42. - (void)dealloc {
  43. [self close];
  44. AWSFMDBRelease(_openResultSets);
  45. AWSFMDBRelease(_cachedStatements);
  46. AWSFMDBRelease(_dateFormat);
  47. AWSFMDBRelease(_databasePath);
  48. AWSFMDBRelease(_openFunctions);
  49. #if ! __has_feature(objc_arc)
  50. [super dealloc];
  51. #endif
  52. }
  53. - (NSString *)databasePath {
  54. return _databasePath;
  55. }
  56. + (NSString*)AWSFMDBUserVersion {
  57. return @"2.5";
  58. }
  59. // returns 0x0240 for version 2.4. This makes it super easy to do things like:
  60. // /* need to make sure to do X with AWSFMDB version 2.4 or later */
  61. // if ([FMDatabase AWSFMDBVersion] >= 0x0240) { … }
  62. + (SInt32)AWSFMDBVersion {
  63. // we go through these hoops so that we only have to change the version number in a single spot.
  64. static dispatch_once_t once;
  65. static SInt32 AWSFMDBVersionVal = 0;
  66. dispatch_once(&once, ^{
  67. NSString *prodVersion = [self AWSFMDBUserVersion];
  68. if ([[prodVersion componentsSeparatedByString:@"."] count] < 3) {
  69. prodVersion = [prodVersion stringByAppendingString:@".0"];
  70. }
  71. NSString *junk = [prodVersion stringByReplacingOccurrencesOfString:@"." withString:@""];
  72. char *e = nil;
  73. AWSFMDBVersionVal = (int) strtoul([junk UTF8String], &e, 16);
  74. });
  75. return AWSFMDBVersionVal;
  76. }
  77. #pragma mark SQLite information
  78. + (NSString*)sqliteLibVersion {
  79. return [NSString stringWithFormat:@"%s", sqlite3_libversion()];
  80. }
  81. + (BOOL)isSQLiteThreadSafe {
  82. // make sure to read the sqlite headers on this guy!
  83. return sqlite3_threadsafe() != 0;
  84. }
  85. - (void*)sqliteHandle {
  86. return _db;
  87. }
  88. - (const char*)sqlitePath {
  89. if (!_databasePath) {
  90. return ":memory:";
  91. }
  92. if ([_databasePath length] == 0) {
  93. return ""; // this creates a temporary database (it's an sqlite thing).
  94. }
  95. return [_databasePath fileSystemRepresentation];
  96. }
  97. #pragma mark Open and close database
  98. - (BOOL)open {
  99. if (_db) {
  100. return YES;
  101. }
  102. int err = sqlite3_open([self sqlitePath], &_db );
  103. if(err != SQLITE_OK) {
  104. NSLog(@"error opening!: %d", err);
  105. return NO;
  106. }
  107. if (_maxBusyRetryTimeInterval > 0.0) {
  108. // set the handler
  109. [self setMaxBusyRetryTimeInterval:_maxBusyRetryTimeInterval];
  110. }
  111. return YES;
  112. }
  113. - (BOOL)openWithFlags:(int)flags {
  114. return [self openWithFlags:flags vfs:nil];
  115. }
  116. - (BOOL)openWithFlags:(int)flags vfs:(NSString *)vfsName; {
  117. #if SQLITE_VERSION_NUMBER >= 3005000
  118. if (_db) {
  119. return YES;
  120. }
  121. int err = sqlite3_open_v2([self sqlitePath], &_db, flags, [vfsName UTF8String]);
  122. if(err != SQLITE_OK) {
  123. NSLog(@"error opening!: %d", err);
  124. return NO;
  125. }
  126. if (_maxBusyRetryTimeInterval > 0.0) {
  127. // set the handler
  128. [self setMaxBusyRetryTimeInterval:_maxBusyRetryTimeInterval];
  129. }
  130. return YES;
  131. #else
  132. NSLog(@"Requires SQLite 3.5; will just open");
  133. return [self open];
  134. #endif
  135. }
  136. - (BOOL)close {
  137. [self clearCachedStatements];
  138. [self closeOpenResultSets];
  139. if (!_db) {
  140. return YES;
  141. }
  142. int rc;
  143. BOOL retry;
  144. BOOL triedFinalizingOpenStatements = NO;
  145. do {
  146. retry = NO;
  147. rc = sqlite3_close(_db);
  148. if (SQLITE_BUSY == rc || SQLITE_LOCKED == rc) {
  149. if (!triedFinalizingOpenStatements) {
  150. triedFinalizingOpenStatements = YES;
  151. sqlite3_stmt *pStmt;
  152. while ((pStmt = sqlite3_next_stmt(_db, nil)) !=0) {
  153. NSLog(@"Closing leaked statement");
  154. sqlite3_finalize(pStmt);
  155. retry = YES;
  156. }
  157. }
  158. }
  159. else if (SQLITE_OK != rc) {
  160. NSLog(@"error closing!: %d", rc);
  161. }
  162. }
  163. while (retry);
  164. _db = nil;
  165. return YES;
  166. }
  167. #pragma mark Busy handler routines
  168. // NOTE: appledoc seems to choke on this function for some reason;
  169. // so when generating documentation, you might want to ignore the
  170. // .m files so that it only documents the public interfaces outlined
  171. // in the .h files.
  172. //
  173. // This is a known appledoc bug that it has problems with C functions
  174. // within a class implementation, but for some reason, only this
  175. // C function causes problems; the rest don't. Anyway, ignoring the .m
  176. // files with appledoc will prevent this problem from occurring.
  177. static int AWSFMDBDatabaseBusyHandler(void *f, int count) {
  178. AWSFMDatabase *self = (__bridge AWSFMDatabase*)f;
  179. if (count == 0) {
  180. self->_startBusyRetryTime = [NSDate timeIntervalSinceReferenceDate];
  181. return 1;
  182. }
  183. NSTimeInterval delta = [NSDate timeIntervalSinceReferenceDate] - (self->_startBusyRetryTime);
  184. if (delta < [self maxBusyRetryTimeInterval]) {
  185. int requestedSleepInMillseconds = (int) arc4random_uniform(50) + 50;
  186. int actualSleepInMilliseconds = sqlite3_sleep(requestedSleepInMillseconds);
  187. if (actualSleepInMilliseconds != requestedSleepInMillseconds) {
  188. NSLog(@"WARNING: Requested sleep of %i milliseconds, but SQLite returned %i. Maybe SQLite wasn't built with HAVE_USLEEP=1?", requestedSleepInMillseconds, actualSleepInMilliseconds);
  189. }
  190. return 1;
  191. }
  192. return 0;
  193. }
  194. - (void)setMaxBusyRetryTimeInterval:(NSTimeInterval)timeout {
  195. _maxBusyRetryTimeInterval = timeout;
  196. if (!_db) {
  197. return;
  198. }
  199. if (timeout > 0) {
  200. sqlite3_busy_handler(_db, &AWSFMDBDatabaseBusyHandler, (__bridge void *)(self));
  201. }
  202. else {
  203. // turn it off otherwise
  204. sqlite3_busy_handler(_db, nil, nil);
  205. }
  206. }
  207. - (NSTimeInterval)maxBusyRetryTimeInterval {
  208. return _maxBusyRetryTimeInterval;
  209. }
  210. // we no longer make busyRetryTimeout public
  211. // but for folks who don't bother noticing that the interface to FMDatabase changed,
  212. // we'll still implement the method so they don't get suprise crashes
  213. - (int)busyRetryTimeout {
  214. NSLog(@"%s:%d", __FUNCTION__, __LINE__);
  215. NSLog(@"AWSFMDB: busyRetryTimeout no longer works, please use maxBusyRetryTimeInterval");
  216. return -1;
  217. }
  218. - (void)setBusyRetryTimeout:(int)i {
  219. NSLog(@"%s:%d", __FUNCTION__, __LINE__);
  220. NSLog(@"AWSFMDB: setBusyRetryTimeout does nothing, please use setMaxBusyRetryTimeInterval:");
  221. }
  222. #pragma mark Result set functions
  223. - (BOOL)hasOpenResultSets {
  224. return [_openResultSets count] > 0;
  225. }
  226. - (void)closeOpenResultSets {
  227. //Copy the set so we don't get mutation errors
  228. NSSet *openSetCopy = AWSFMDBReturnAutoreleased([_openResultSets copy]);
  229. for (NSValue *rsInWrappedInATastyValueMeal in openSetCopy) {
  230. AWSFMResultSet *rs = (AWSFMResultSet *)[rsInWrappedInATastyValueMeal pointerValue];
  231. [rs setParentDB:nil];
  232. [rs close];
  233. [_openResultSets removeObject:rsInWrappedInATastyValueMeal];
  234. }
  235. }
  236. - (void)resultSetDidClose:(AWSFMResultSet *)resultSet {
  237. NSValue *setValue = [NSValue valueWithNonretainedObject:resultSet];
  238. [_openResultSets removeObject:setValue];
  239. }
  240. #pragma mark Cached statements
  241. - (void)clearCachedStatements {
  242. for (NSMutableSet *statements in [_cachedStatements objectEnumerator]) {
  243. [statements makeObjectsPerformSelector:@selector(close)];
  244. }
  245. [_cachedStatements removeAllObjects];
  246. }
  247. - (AWSFMStatement*)cachedStatementForQuery:(NSString*)query {
  248. NSMutableSet* statements = [_cachedStatements objectForKey:query];
  249. return [[statements objectsPassingTest:^BOOL(AWSFMStatement* statement, BOOL *stop) {
  250. *stop = ![statement inUse];
  251. return *stop;
  252. }] anyObject];
  253. }
  254. - (void)setCachedStatement:(AWSFMStatement*)statement forQuery:(nonnull NSString*)query {
  255. query = [query copy]; // in case we got handed in a mutable string...
  256. [statement setQuery:query];
  257. NSMutableSet* statements = [_cachedStatements objectForKey:query];
  258. if (!statements) {
  259. statements = [NSMutableSet set];
  260. }
  261. [statements addObject:statement];
  262. [_cachedStatements setObject:statements forKey:query];
  263. AWSFMDBRelease(query);
  264. }
  265. #pragma mark Key routines
  266. - (BOOL)rekey:(NSString*)key {
  267. NSData *keyData = [NSData dataWithBytes:(void *)[key UTF8String] length:(NSUInteger)strlen([key UTF8String])];
  268. return [self rekeyWithData:keyData];
  269. }
  270. - (BOOL)rekeyWithData:(NSData *)keyData {
  271. #ifdef SQLITE_HAS_CODEC
  272. if (!keyData) {
  273. return NO;
  274. }
  275. int rc = sqlite3_rekey(_db, [keyData bytes], (int)[keyData length]);
  276. if (rc != SQLITE_OK) {
  277. NSLog(@"error on rekey: %d", rc);
  278. NSLog(@"%@", [self lastErrorMessage]);
  279. }
  280. return (rc == SQLITE_OK);
  281. #else
  282. return NO;
  283. #endif
  284. }
  285. - (BOOL)setKey:(NSString*)key {
  286. NSData *keyData = [NSData dataWithBytes:[key UTF8String] length:(NSUInteger)strlen([key UTF8String])];
  287. return [self setKeyWithData:keyData];
  288. }
  289. - (BOOL)setKeyWithData:(NSData *)keyData {
  290. #ifdef SQLITE_HAS_CODEC
  291. if (!keyData) {
  292. return NO;
  293. }
  294. int rc = sqlite3_key(_db, [keyData bytes], (int)[keyData length]);
  295. return (rc == SQLITE_OK);
  296. #else
  297. return NO;
  298. #endif
  299. }
  300. #pragma mark Date routines
  301. + (NSDateFormatter *)storeableDateFormat:(NSString *)format {
  302. NSDateFormatter *result = AWSFMDBReturnAutoreleased([[NSDateFormatter alloc] init]);
  303. result.dateFormat = format;
  304. result.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
  305. result.locale = AWSFMDBReturnAutoreleased([[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]);
  306. return result;
  307. }
  308. - (BOOL)hasDateFormatter {
  309. return _dateFormat != nil;
  310. }
  311. - (void)setDateFormat:(NSDateFormatter *)format {
  312. AWSFMDBAutorelease(_dateFormat);
  313. _dateFormat = AWSFMDBReturnRetained(format);
  314. }
  315. - (NSDate *)dateFromString:(NSString *)s {
  316. return [_dateFormat dateFromString:s];
  317. }
  318. - (NSString *)stringFromDate:(NSDate *)date {
  319. return [_dateFormat stringFromDate:date];
  320. }
  321. #pragma mark State of database
  322. - (BOOL)goodConnection {
  323. if (!_db) {
  324. return NO;
  325. }
  326. AWSFMResultSet *rs = [self executeQuery:@"select name from sqlite_master where type='table'"];
  327. if (rs) {
  328. [rs close];
  329. return YES;
  330. }
  331. return NO;
  332. }
  333. - (void)warnInUse {
  334. NSLog(@"The FMDatabase %@ is currently in use.", self);
  335. #ifndef NS_BLOCK_ASSERTIONS
  336. if (_crashOnErrors) {
  337. NSAssert(false, @"The FMDatabase %@ is currently in use.", self);
  338. abort();
  339. }
  340. #endif
  341. }
  342. - (BOOL)databaseExists {
  343. if (!_db) {
  344. NSLog(@"The FMDatabase %@ is not open.", self);
  345. #ifndef NS_BLOCK_ASSERTIONS
  346. if (_crashOnErrors) {
  347. NSAssert(false, @"The FMDatabase %@ is not open.", self);
  348. abort();
  349. }
  350. #endif
  351. return NO;
  352. }
  353. return YES;
  354. }
  355. #pragma mark Error routines
  356. - (NSString*)lastErrorMessage {
  357. return [NSString stringWithUTF8String:sqlite3_errmsg(_db)];
  358. }
  359. - (BOOL)hadError {
  360. int lastErrCode = [self lastErrorCode];
  361. return (lastErrCode > SQLITE_OK && lastErrCode < SQLITE_ROW);
  362. }
  363. - (int)lastErrorCode {
  364. return sqlite3_errcode(_db);
  365. }
  366. - (NSError*)errorWithMessage:(NSString*)message {
  367. NSDictionary* errorMessage = [NSDictionary dictionaryWithObject:message forKey:NSLocalizedDescriptionKey];
  368. return [NSError errorWithDomain:@"AWSFMDatabase" code:sqlite3_errcode(_db) userInfo:errorMessage];
  369. }
  370. - (NSError*)lastError {
  371. return [self errorWithMessage:[self lastErrorMessage]];
  372. }
  373. #pragma mark Update information routines
  374. - (sqlite_int64)lastInsertRowId {
  375. if (_isExecutingStatement) {
  376. [self warnInUse];
  377. return NO;
  378. }
  379. _isExecutingStatement = YES;
  380. sqlite_int64 ret = sqlite3_last_insert_rowid(_db);
  381. _isExecutingStatement = NO;
  382. return ret;
  383. }
  384. - (int)changes {
  385. if (_isExecutingStatement) {
  386. [self warnInUse];
  387. return 0;
  388. }
  389. _isExecutingStatement = YES;
  390. int ret = sqlite3_changes(_db);
  391. _isExecutingStatement = NO;
  392. return ret;
  393. }
  394. #pragma mark SQL manipulation
  395. - (void)bindObject:(id)obj toColumn:(int)idx inStatement:(sqlite3_stmt*)pStmt {
  396. if ((!obj) || ((NSNull *)obj == [NSNull null])) {
  397. sqlite3_bind_null(pStmt, idx);
  398. }
  399. // FIXME - someday check the return codes on these binds.
  400. else if ([obj isKindOfClass:[NSData class]]) {
  401. const void *bytes = [obj bytes];
  402. if (!bytes) {
  403. // it's an empty NSData object, aka [NSData data].
  404. // Don't pass a NULL pointer, or sqlite will bind a SQL null instead of a blob.
  405. bytes = "";
  406. }
  407. sqlite3_bind_blob(pStmt, idx, bytes, (int)[obj length], SQLITE_STATIC);
  408. }
  409. else if ([obj isKindOfClass:[NSDate class]]) {
  410. if (self.hasDateFormatter)
  411. sqlite3_bind_text(pStmt, idx, [[self stringFromDate:obj] UTF8String], -1, SQLITE_STATIC);
  412. else
  413. sqlite3_bind_double(pStmt, idx, [obj timeIntervalSince1970]);
  414. }
  415. else if ([obj isKindOfClass:[NSNumber class]]) {
  416. if (strcmp([obj objCType], @encode(char)) == 0) {
  417. sqlite3_bind_int(pStmt, idx, [obj charValue]);
  418. }
  419. else if (strcmp([obj objCType], @encode(unsigned char)) == 0) {
  420. sqlite3_bind_int(pStmt, idx, [obj unsignedCharValue]);
  421. }
  422. else if (strcmp([obj objCType], @encode(short)) == 0) {
  423. sqlite3_bind_int(pStmt, idx, [obj shortValue]);
  424. }
  425. else if (strcmp([obj objCType], @encode(unsigned short)) == 0) {
  426. sqlite3_bind_int(pStmt, idx, [obj unsignedShortValue]);
  427. }
  428. else if (strcmp([obj objCType], @encode(int)) == 0) {
  429. sqlite3_bind_int(pStmt, idx, [obj intValue]);
  430. }
  431. else if (strcmp([obj objCType], @encode(unsigned int)) == 0) {
  432. sqlite3_bind_int64(pStmt, idx, (long long)[obj unsignedIntValue]);
  433. }
  434. else if (strcmp([obj objCType], @encode(long)) == 0) {
  435. sqlite3_bind_int64(pStmt, idx, [obj longValue]);
  436. }
  437. else if (strcmp([obj objCType], @encode(unsigned long)) == 0) {
  438. sqlite3_bind_int64(pStmt, idx, (long long)[obj unsignedLongValue]);
  439. }
  440. else if (strcmp([obj objCType], @encode(long long)) == 0) {
  441. sqlite3_bind_int64(pStmt, idx, [obj longLongValue]);
  442. }
  443. else if (strcmp([obj objCType], @encode(unsigned long long)) == 0) {
  444. sqlite3_bind_int64(pStmt, idx, (long long)[obj unsignedLongLongValue]);
  445. }
  446. else if (strcmp([obj objCType], @encode(float)) == 0) {
  447. sqlite3_bind_double(pStmt, idx, [obj floatValue]);
  448. }
  449. else if (strcmp([obj objCType], @encode(double)) == 0) {
  450. sqlite3_bind_double(pStmt, idx, [obj doubleValue]);
  451. }
  452. else if (strcmp([obj objCType], @encode(BOOL)) == 0) {
  453. sqlite3_bind_int(pStmt, idx, ([obj boolValue] ? 1 : 0));
  454. }
  455. else {
  456. sqlite3_bind_text(pStmt, idx, [[obj description] UTF8String], -1, SQLITE_STATIC);
  457. }
  458. }
  459. else {
  460. sqlite3_bind_text(pStmt, idx, [[obj description] UTF8String], -1, SQLITE_STATIC);
  461. }
  462. }
  463. - (void)extractSQL:(NSString *)sql argumentsList:(va_list)args intoString:(NSMutableString *)cleanedSQL arguments:(NSMutableArray *)arguments {
  464. NSUInteger length = [sql length];
  465. unichar last = '\0';
  466. for (NSUInteger i = 0; i < length; ++i) {
  467. id arg = nil;
  468. unichar current = [sql characterAtIndex:i];
  469. unichar add = current;
  470. if (last == '%') {
  471. switch (current) {
  472. case '@':
  473. arg = va_arg(args, id);
  474. break;
  475. case 'c':
  476. // warning: second argument to 'va_arg' is of promotable type 'char'; this va_arg has undefined behavior because arguments will be promoted to 'int'
  477. arg = [NSString stringWithFormat:@"%c", va_arg(args, int)];
  478. break;
  479. case 's':
  480. arg = [NSString stringWithUTF8String:va_arg(args, char*)];
  481. break;
  482. case 'd':
  483. case 'D':
  484. case 'i':
  485. arg = [NSNumber numberWithInt:va_arg(args, int)];
  486. break;
  487. case 'u':
  488. case 'U':
  489. arg = [NSNumber numberWithUnsignedInt:va_arg(args, unsigned int)];
  490. break;
  491. case 'h':
  492. i++;
  493. if (i < length && [sql characterAtIndex:i] == 'i') {
  494. // warning: second argument to 'va_arg' is of promotable type 'short'; this va_arg has undefined behavior because arguments will be promoted to 'int'
  495. arg = [NSNumber numberWithShort:(short)(va_arg(args, int))];
  496. }
  497. else if (i < length && [sql characterAtIndex:i] == 'u') {
  498. // 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'
  499. arg = [NSNumber numberWithUnsignedShort:(unsigned short)(va_arg(args, uint))];
  500. }
  501. else {
  502. i--;
  503. }
  504. break;
  505. case 'q':
  506. i++;
  507. if (i < length && [sql characterAtIndex:i] == 'i') {
  508. arg = [NSNumber numberWithLongLong:va_arg(args, long long)];
  509. }
  510. else if (i < length && [sql characterAtIndex:i] == 'u') {
  511. arg = [NSNumber numberWithUnsignedLongLong:va_arg(args, unsigned long long)];
  512. }
  513. else {
  514. i--;
  515. }
  516. break;
  517. case 'f':
  518. arg = [NSNumber numberWithDouble:va_arg(args, double)];
  519. break;
  520. case 'g':
  521. // warning: second argument to 'va_arg' is of promotable type 'float'; this va_arg has undefined behavior because arguments will be promoted to 'double'
  522. arg = [NSNumber numberWithFloat:(float)(va_arg(args, double))];
  523. break;
  524. case 'l':
  525. i++;
  526. if (i < length) {
  527. unichar next = [sql characterAtIndex:i];
  528. if (next == 'l') {
  529. i++;
  530. if (i < length && [sql characterAtIndex:i] == 'd') {
  531. //%lld
  532. arg = [NSNumber numberWithLongLong:va_arg(args, long long)];
  533. }
  534. else if (i < length && [sql characterAtIndex:i] == 'u') {
  535. //%llu
  536. arg = [NSNumber numberWithUnsignedLongLong:va_arg(args, unsigned long long)];
  537. }
  538. else {
  539. i--;
  540. }
  541. }
  542. else if (next == 'd') {
  543. //%ld
  544. arg = [NSNumber numberWithLong:va_arg(args, long)];
  545. }
  546. else if (next == 'u') {
  547. //%lu
  548. arg = [NSNumber numberWithUnsignedLong:va_arg(args, unsigned long)];
  549. }
  550. else {
  551. i--;
  552. }
  553. }
  554. else {
  555. i--;
  556. }
  557. break;
  558. default:
  559. // something else that we can't interpret. just pass it on through like normal
  560. break;
  561. }
  562. }
  563. else if (current == '%') {
  564. // percent sign; skip this character
  565. add = '\0';
  566. }
  567. if (arg != nil) {
  568. [cleanedSQL appendString:@"?"];
  569. [arguments addObject:arg];
  570. }
  571. else if (add == (unichar)'@' && last == (unichar) '%') {
  572. [cleanedSQL appendFormat:@"NULL"];
  573. }
  574. else if (add != '\0') {
  575. [cleanedSQL appendFormat:@"%C", add];
  576. }
  577. last = current;
  578. }
  579. }
  580. #pragma mark Execute queries
  581. - (AWSFMResultSet *)executeQuery:(NSString *)sql withParameterDictionary:(NSDictionary *)arguments {
  582. return [self executeQuery:sql withArgumentsInArray:nil orDictionary:arguments orVAList:nil];
  583. }
  584. - (AWSFMResultSet *)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray*)arrayArgs orDictionary:(NSDictionary *)dictionaryArgs orVAList:(va_list)args {
  585. if (![self databaseExists]) {
  586. return 0x00;
  587. }
  588. if (_isExecutingStatement) {
  589. [self warnInUse];
  590. return 0x00;
  591. }
  592. _isExecutingStatement = YES;
  593. int rc = 0x00;
  594. sqlite3_stmt *pStmt = 0x00;
  595. AWSFMStatement *statement = 0x00;
  596. AWSFMResultSet *rs = 0x00;
  597. if (_traceExecution && sql) {
  598. NSLog(@"%@ executeQuery: %@", self, sql);
  599. }
  600. if (_shouldCacheStatements) {
  601. statement = [self cachedStatementForQuery:sql];
  602. pStmt = statement ? [statement statement] : 0x00;
  603. [statement reset];
  604. }
  605. if (!pStmt) {
  606. rc = sqlite3_prepare_v2(_db, [sql UTF8String], -1, &pStmt, 0);
  607. if (SQLITE_OK != rc) {
  608. if (_logsErrors) {
  609. NSLog(@"DB Error: %d \"%@\"", [self lastErrorCode], [self lastErrorMessage]);
  610. NSLog(@"DB Query: %@", sql);
  611. NSLog(@"DB Path: %@", _databasePath);
  612. }
  613. if (_crashOnErrors) {
  614. NSAssert(false, @"DB Error: %d \"%@\"", [self lastErrorCode], [self lastErrorMessage]);
  615. abort();
  616. }
  617. sqlite3_finalize(pStmt);
  618. _isExecutingStatement = NO;
  619. return nil;
  620. }
  621. }
  622. id obj;
  623. int idx = 0;
  624. int queryCount = sqlite3_bind_parameter_count(pStmt); // pointed out by Dominic Yu (thanks!)
  625. // If dictionaryArgs is passed in, that means we are using sqlite's named parameter support
  626. if (dictionaryArgs) {
  627. for (NSString *dictionaryKey in [dictionaryArgs allKeys]) {
  628. // Prefix the key with a colon.
  629. NSString *parameterName = [[NSString alloc] initWithFormat:@":%@", dictionaryKey];
  630. if (_traceExecution) {
  631. NSLog(@"%@ = %@", parameterName, [dictionaryArgs objectForKey:dictionaryKey]);
  632. }
  633. // Get the index for the parameter name.
  634. int namedIdx = sqlite3_bind_parameter_index(pStmt, [parameterName UTF8String]);
  635. AWSFMDBRelease(parameterName);
  636. if (namedIdx > 0) {
  637. // Standard binding from here.
  638. [self bindObject:[dictionaryArgs objectForKey:dictionaryKey] toColumn:namedIdx inStatement:pStmt];
  639. // increment the binding count, so our check below works out
  640. idx++;
  641. }
  642. else {
  643. NSLog(@"Could not find index for %@", dictionaryKey);
  644. }
  645. }
  646. }
  647. else {
  648. while (idx < queryCount) {
  649. if (arrayArgs && idx < (int)[arrayArgs count]) {
  650. obj = [arrayArgs objectAtIndex:(NSUInteger)idx];
  651. }
  652. else if (args) {
  653. obj = va_arg(args, id);
  654. }
  655. else {
  656. //We ran out of arguments
  657. break;
  658. }
  659. if (_traceExecution) {
  660. if ([obj isKindOfClass:[NSData class]]) {
  661. NSLog(@"data: %ld bytes", (unsigned long)[(NSData*)obj length]);
  662. }
  663. else {
  664. NSLog(@"obj: %@", obj);
  665. }
  666. }
  667. idx++;
  668. [self bindObject:obj toColumn:idx inStatement:pStmt];
  669. }
  670. }
  671. if (idx != queryCount) {
  672. NSLog(@"Error: the bind count is not correct for the # of variables (executeQuery)");
  673. sqlite3_finalize(pStmt);
  674. _isExecutingStatement = NO;
  675. return nil;
  676. }
  677. AWSFMDBRetain(statement); // to balance the release below
  678. if (!statement) {
  679. statement = [[AWSFMStatement alloc] init];
  680. [statement setStatement:pStmt];
  681. if (_shouldCacheStatements && sql) {
  682. [self setCachedStatement:statement forQuery:sql];
  683. }
  684. }
  685. // the statement gets closed in rs's dealloc or [rs close];
  686. rs = [AWSFMResultSet resultSetWithStatement:statement usingParentDatabase:self];
  687. [rs setQuery:sql];
  688. NSValue *openResultSet = [NSValue valueWithNonretainedObject:rs];
  689. [_openResultSets addObject:openResultSet];
  690. [statement setUseCount:[statement useCount] + 1];
  691. AWSFMDBRelease(statement);
  692. _isExecutingStatement = NO;
  693. return rs;
  694. }
  695. - (AWSFMResultSet *)executeQuery:(NSString*)sql, ... {
  696. va_list args;
  697. va_start(args, sql);
  698. id result = [self executeQuery:sql withArgumentsInArray:nil orDictionary:nil orVAList:args];
  699. va_end(args);
  700. return result;
  701. }
  702. - (AWSFMResultSet *)executeQueryWithFormat:(NSString*)format, ... {
  703. va_list args;
  704. va_start(args, format);
  705. NSMutableString *sql = [NSMutableString stringWithCapacity:[format length]];
  706. NSMutableArray *arguments = [NSMutableArray array];
  707. [self extractSQL:format argumentsList:args intoString:sql arguments:arguments];
  708. va_end(args);
  709. return [self executeQuery:sql withArgumentsInArray:arguments];
  710. }
  711. - (AWSFMResultSet *)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray *)arguments {
  712. return [self executeQuery:sql withArgumentsInArray:arguments orDictionary:nil orVAList:nil];
  713. }
  714. - (AWSFMResultSet *)executeQuery:(NSString*)sql withVAList:(va_list)args {
  715. return [self executeQuery:sql withArgumentsInArray:nil orDictionary:nil orVAList:args];
  716. }
  717. #pragma mark Execute updates
  718. - (BOOL)executeUpdate:(NSString*)sql error:(NSError**)outErr withArgumentsInArray:(NSArray*)arrayArgs orDictionary:(NSDictionary *)dictionaryArgs orVAList:(va_list)args {
  719. if (!sql) {
  720. return YES;
  721. }
  722. if (![self databaseExists]) {
  723. return NO;
  724. }
  725. if (_isExecutingStatement) {
  726. [self warnInUse];
  727. return NO;
  728. }
  729. _isExecutingStatement = YES;
  730. int rc = 0x00;
  731. sqlite3_stmt *pStmt = 0x00;
  732. AWSFMStatement *cachedStmt = 0x00;
  733. if (_traceExecution && sql) {
  734. NSLog(@"%@ executeUpdate: %@", self, sql);
  735. }
  736. if (_shouldCacheStatements) {
  737. cachedStmt = [self cachedStatementForQuery:sql];
  738. pStmt = cachedStmt ? [cachedStmt statement] : 0x00;
  739. [cachedStmt reset];
  740. }
  741. if (!pStmt) {
  742. rc = sqlite3_prepare_v2(_db, [sql UTF8String], -1, &pStmt, 0);
  743. if (SQLITE_OK != rc) {
  744. if (_logsErrors) {
  745. NSLog(@"DB Error: %d \"%@\"", [self lastErrorCode], [self lastErrorMessage]);
  746. NSLog(@"DB Query: %@", sql);
  747. NSLog(@"DB Path: %@", _databasePath);
  748. }
  749. if (_crashOnErrors) {
  750. NSAssert(false, @"DB Error: %d \"%@\"", [self lastErrorCode], [self lastErrorMessage]);
  751. abort();
  752. }
  753. sqlite3_finalize(pStmt);
  754. if (outErr) {
  755. *outErr = [self errorWithMessage:[NSString stringWithUTF8String:sqlite3_errmsg(_db)]];
  756. }
  757. _isExecutingStatement = NO;
  758. return NO;
  759. }
  760. }
  761. id obj;
  762. int idx = 0;
  763. int queryCount = sqlite3_bind_parameter_count(pStmt);
  764. // If dictionaryArgs is passed in, that means we are using sqlite's named parameter support
  765. if (dictionaryArgs) {
  766. for (NSString *dictionaryKey in [dictionaryArgs allKeys]) {
  767. // Prefix the key with a colon.
  768. NSString *parameterName = [[NSString alloc] initWithFormat:@":%@", dictionaryKey];
  769. if (_traceExecution) {
  770. NSLog(@"%@ = %@", parameterName, [dictionaryArgs objectForKey:dictionaryKey]);
  771. }
  772. // Get the index for the parameter name.
  773. int namedIdx = sqlite3_bind_parameter_index(pStmt, [parameterName UTF8String]);
  774. AWSFMDBRelease(parameterName);
  775. if (namedIdx > 0) {
  776. // Standard binding from here.
  777. [self bindObject:[dictionaryArgs objectForKey:dictionaryKey] toColumn:namedIdx inStatement:pStmt];
  778. // increment the binding count, so our check below works out
  779. idx++;
  780. }
  781. else {
  782. NSLog(@"Could not find index for %@", dictionaryKey);
  783. }
  784. }
  785. }
  786. else {
  787. while (idx < queryCount) {
  788. if (arrayArgs && idx < (int)[arrayArgs count]) {
  789. obj = [arrayArgs objectAtIndex:(NSUInteger)idx];
  790. }
  791. else if (args) {
  792. obj = va_arg(args, id);
  793. }
  794. else {
  795. //We ran out of arguments
  796. break;
  797. }
  798. if (_traceExecution) {
  799. if ([obj isKindOfClass:[NSData class]]) {
  800. NSLog(@"data: %ld bytes", (unsigned long)[(NSData*)obj length]);
  801. }
  802. else {
  803. NSLog(@"obj: %@", obj);
  804. }
  805. }
  806. idx++;
  807. [self bindObject:obj toColumn:idx inStatement:pStmt];
  808. }
  809. }
  810. if (idx != queryCount) {
  811. NSLog(@"Error: the bind count (%d) is not correct for the # of variables in the query (%d) (%@) (executeUpdate)", idx, queryCount, sql);
  812. sqlite3_finalize(pStmt);
  813. _isExecutingStatement = NO;
  814. return NO;
  815. }
  816. /* Call sqlite3_step() to run the virtual machine. Since the SQL being
  817. ** executed is not a SELECT statement, we assume no data will be returned.
  818. */
  819. rc = sqlite3_step(pStmt);
  820. if (SQLITE_DONE == rc) {
  821. // all is well, let's return.
  822. }
  823. else if (SQLITE_ERROR == rc) {
  824. if (_logsErrors) {
  825. NSLog(@"Error calling sqlite3_step (%d: %s) SQLITE_ERROR", rc, sqlite3_errmsg(_db));
  826. NSLog(@"DB Query: %@", sql);
  827. }
  828. }
  829. else if (SQLITE_MISUSE == rc) {
  830. // uh oh.
  831. if (_logsErrors) {
  832. NSLog(@"Error calling sqlite3_step (%d: %s) SQLITE_MISUSE", rc, sqlite3_errmsg(_db));
  833. NSLog(@"DB Query: %@", sql);
  834. }
  835. }
  836. else {
  837. // wtf?
  838. if (_logsErrors) {
  839. NSLog(@"Unknown error calling sqlite3_step (%d: %s) eu", rc, sqlite3_errmsg(_db));
  840. NSLog(@"DB Query: %@", sql);
  841. }
  842. }
  843. if (rc == SQLITE_ROW) {
  844. NSAssert(NO, @"A executeUpdate is being called with a query string '%@'", sql);
  845. }
  846. if (_shouldCacheStatements && !cachedStmt) {
  847. cachedStmt = [[AWSFMStatement alloc] init];
  848. [cachedStmt setStatement:pStmt];
  849. [self setCachedStatement:cachedStmt forQuery:sql];
  850. AWSFMDBRelease(cachedStmt);
  851. }
  852. int closeErrorCode;
  853. if (cachedStmt) {
  854. [cachedStmt setUseCount:[cachedStmt useCount] + 1];
  855. closeErrorCode = sqlite3_reset(pStmt);
  856. }
  857. else {
  858. /* Finalize the virtual machine. This releases all memory and other
  859. ** resources allocated by the sqlite3_prepare() call above.
  860. */
  861. closeErrorCode = sqlite3_finalize(pStmt);
  862. }
  863. if (closeErrorCode != SQLITE_OK) {
  864. if (_logsErrors) {
  865. NSLog(@"Unknown error finalizing or resetting statement (%d: %s)", closeErrorCode, sqlite3_errmsg(_db));
  866. NSLog(@"DB Query: %@", sql);
  867. }
  868. }
  869. _isExecutingStatement = NO;
  870. return (rc == SQLITE_DONE || rc == SQLITE_OK);
  871. }
  872. - (BOOL)executeUpdate:(NSString*)sql, ... {
  873. va_list args;
  874. va_start(args, sql);
  875. BOOL result = [self executeUpdate:sql error:nil withArgumentsInArray:nil orDictionary:nil orVAList:args];
  876. va_end(args);
  877. return result;
  878. }
  879. - (BOOL)executeUpdate:(NSString*)sql withArgumentsInArray:(NSArray *)arguments {
  880. return [self executeUpdate:sql error:nil withArgumentsInArray:arguments orDictionary:nil orVAList:nil];
  881. }
  882. - (BOOL)executeUpdate:(NSString*)sql withParameterDictionary:(NSDictionary *)arguments {
  883. return [self executeUpdate:sql error:nil withArgumentsInArray:nil orDictionary:arguments orVAList:nil];
  884. }
  885. - (BOOL)executeUpdate:(NSString*)sql withVAList:(va_list)args {
  886. return [self executeUpdate:sql error:nil withArgumentsInArray:nil orDictionary:nil orVAList:args];
  887. }
  888. - (BOOL)executeUpdateWithFormat:(NSString*)format, ... {
  889. va_list args;
  890. va_start(args, format);
  891. NSMutableString *sql = [NSMutableString stringWithCapacity:[format length]];
  892. NSMutableArray *arguments = [NSMutableArray array];
  893. [self extractSQL:format argumentsList:args intoString:sql arguments:arguments];
  894. va_end(args);
  895. return [self executeUpdate:sql withArgumentsInArray:arguments];
  896. }
  897. int AWSFMDBExecuteBulkSQLCallback(void *theBlockAsVoid, int columns, char **values, char **names); // shhh clang.
  898. int AWSFMDBExecuteBulkSQLCallback(void *theBlockAsVoid, int columns, char **values, char **names) {
  899. if (!theBlockAsVoid) {
  900. return SQLITE_OK;
  901. }
  902. int (^execCallbackBlock)(NSDictionary *resultsDictionary) = (__bridge int (^)(NSDictionary *__strong))(theBlockAsVoid);
  903. NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithCapacity:(NSUInteger)columns];
  904. for (NSInteger i = 0; i < columns; i++) {
  905. NSString *key = [NSString stringWithUTF8String:names[i]];
  906. id value = values[i] ? [NSString stringWithUTF8String:values[i]] : [NSNull null];
  907. [dictionary setObject:value forKey:key];
  908. }
  909. return execCallbackBlock(dictionary);
  910. }
  911. - (BOOL)executeStatements:(NSString *)sql {
  912. return [self executeStatements:sql withResultBlock:nil];
  913. }
  914. - (BOOL)executeStatements:(NSString *)sql withResultBlock:(AWSFMDBExecuteStatementsCallbackBlock)block {
  915. int rc;
  916. char *errmsg = nil;
  917. rc = sqlite3_exec([self sqliteHandle], [sql UTF8String], block ? AWSFMDBExecuteBulkSQLCallback : nil, (__bridge void *)(block), &errmsg);
  918. if (errmsg && [self logsErrors]) {
  919. NSLog(@"Error inserting batch: %s", errmsg);
  920. sqlite3_free(errmsg);
  921. }
  922. return (rc == SQLITE_OK);
  923. }
  924. - (BOOL)executeUpdate:(NSString*)sql withErrorAndBindings:(NSError**)outErr, ... {
  925. va_list args;
  926. va_start(args, outErr);
  927. BOOL result = [self executeUpdate:sql error:outErr withArgumentsInArray:nil orDictionary:nil orVAList:args];
  928. va_end(args);
  929. return result;
  930. }
  931. #pragma clang diagnostic push
  932. #pragma clang diagnostic ignored "-Wdeprecated-implementations"
  933. - (BOOL)update:(NSString*)sql withErrorAndBindings:(NSError**)outErr, ... {
  934. va_list args;
  935. va_start(args, outErr);
  936. BOOL result = [self executeUpdate:sql error:outErr withArgumentsInArray:nil orDictionary:nil orVAList:args];
  937. va_end(args);
  938. return result;
  939. }
  940. #pragma clang diagnostic pop
  941. #pragma mark Transactions
  942. - (BOOL)rollback {
  943. BOOL b = [self executeUpdate:@"rollback transaction"];
  944. if (b) {
  945. _inTransaction = NO;
  946. }
  947. return b;
  948. }
  949. - (BOOL)commit {
  950. BOOL b = [self executeUpdate:@"commit transaction"];
  951. if (b) {
  952. _inTransaction = NO;
  953. }
  954. return b;
  955. }
  956. - (BOOL)beginDeferredTransaction {
  957. BOOL b = [self executeUpdate:@"begin deferred transaction"];
  958. if (b) {
  959. _inTransaction = YES;
  960. }
  961. return b;
  962. }
  963. - (BOOL)beginTransaction {
  964. BOOL b = [self executeUpdate:@"begin exclusive transaction"];
  965. if (b) {
  966. _inTransaction = YES;
  967. }
  968. return b;
  969. }
  970. - (BOOL)inTransaction {
  971. return _inTransaction;
  972. }
  973. #if SQLITE_VERSION_NUMBER >= 3007000
  974. static NSString *AWSFMDBEscapeSavePointName(NSString *savepointName) {
  975. return [savepointName stringByReplacingOccurrencesOfString:@"'" withString:@"''"];
  976. }
  977. - (BOOL)startSavePointWithName:(NSString*)name error:(NSError**)outErr {
  978. NSParameterAssert(name);
  979. NSString *sql = [NSString stringWithFormat:@"savepoint '%@';", AWSFMDBEscapeSavePointName(name)];
  980. if (![self executeUpdate:sql]) {
  981. if (outErr) {
  982. *outErr = [self lastError];
  983. }
  984. return NO;
  985. }
  986. return YES;
  987. }
  988. - (BOOL)releaseSavePointWithName:(NSString*)name error:(NSError**)outErr {
  989. NSParameterAssert(name);
  990. NSString *sql = [NSString stringWithFormat:@"release savepoint '%@';", AWSFMDBEscapeSavePointName(name)];
  991. BOOL worked = [self executeUpdate:sql];
  992. if (!worked && outErr) {
  993. *outErr = [self lastError];
  994. }
  995. return worked;
  996. }
  997. - (BOOL)rollbackToSavePointWithName:(NSString*)name error:(NSError**)outErr {
  998. NSParameterAssert(name);
  999. NSString *sql = [NSString stringWithFormat:@"rollback transaction to savepoint '%@';", AWSFMDBEscapeSavePointName(name)];
  1000. BOOL worked = [self executeUpdate:sql];
  1001. if (!worked && outErr) {
  1002. *outErr = [self lastError];
  1003. }
  1004. return worked;
  1005. }
  1006. - (NSError*)inSavePoint:(void (^)(BOOL *rollback))block {
  1007. static unsigned long savePointIdx = 0;
  1008. NSString *name = [NSString stringWithFormat:@"dbSavePoint%ld", savePointIdx++];
  1009. BOOL shouldRollback = NO;
  1010. NSError *err = 0x00;
  1011. if (![self startSavePointWithName:name error:&err]) {
  1012. return err;
  1013. }
  1014. if (block) {
  1015. block(&shouldRollback);
  1016. }
  1017. if (shouldRollback) {
  1018. // We need to rollback and release this savepoint to remove it
  1019. [self rollbackToSavePointWithName:name error:&err];
  1020. }
  1021. [self releaseSavePointWithName:name error:&err];
  1022. return err;
  1023. }
  1024. #endif
  1025. #pragma mark Cache statements
  1026. - (BOOL)shouldCacheStatements {
  1027. return _shouldCacheStatements;
  1028. }
  1029. - (void)setShouldCacheStatements:(BOOL)value {
  1030. _shouldCacheStatements = value;
  1031. if (_shouldCacheStatements && !_cachedStatements) {
  1032. [self setCachedStatements:[NSMutableDictionary dictionary]];
  1033. }
  1034. if (!_shouldCacheStatements) {
  1035. [self setCachedStatements:nil];
  1036. }
  1037. }
  1038. #pragma mark Callback function
  1039. void AWSFMDBBlockSQLiteCallBackFunction(sqlite3_context *context, int argc, sqlite3_value **argv); // -Wmissing-prototypes
  1040. void AWSFMDBBlockSQLiteCallBackFunction(sqlite3_context *context, int argc, sqlite3_value **argv) {
  1041. #if ! __has_feature(objc_arc)
  1042. void (^block)(sqlite3_context *context, int argc, sqlite3_value **argv) = (id)sqlite3_user_data(context);
  1043. #else
  1044. void (^block)(sqlite3_context *context, int argc, sqlite3_value **argv) = (__bridge id)sqlite3_user_data(context);
  1045. #endif
  1046. if (block) {
  1047. block(context, argc, argv);
  1048. }
  1049. }
  1050. - (void)makeFunctionNamed:(NSString*)name maximumArguments:(int)count withBlock:(void (^)(void *context, int argc, void **argv))block {
  1051. if (!_openFunctions) {
  1052. _openFunctions = [NSMutableSet new];
  1053. }
  1054. id b = AWSFMDBReturnAutoreleased([block copy]);
  1055. [_openFunctions addObject:b];
  1056. /* 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. */
  1057. #if ! __has_feature(objc_arc)
  1058. sqlite3_create_function([self sqliteHandle], [name UTF8String], count, SQLITE_UTF8, (void*)b, &AWSFMDBBlockSQLiteCallBackFunction, 0x00, 0x00);
  1059. #else
  1060. sqlite3_create_function([self sqliteHandle], [name UTF8String], count, SQLITE_UTF8, (__bridge void*)b, &AWSFMDBBlockSQLiteCallBackFunction, 0x00, 0x00);
  1061. #endif
  1062. }
  1063. @end
  1064. @implementation AWSFMStatement
  1065. @synthesize statement=_statement;
  1066. @synthesize query=_query;
  1067. @synthesize useCount=_useCount;
  1068. @synthesize inUse=_inUse;
  1069. #if ! __has_feature(objc_arc)
  1070. - (void)finalize {
  1071. [self close];
  1072. [super finalize];
  1073. }
  1074. #endif
  1075. - (void)dealloc {
  1076. [self close];
  1077. AWSFMDBRelease(_query);
  1078. #if ! __has_feature(objc_arc)
  1079. [super dealloc];
  1080. #endif
  1081. }
  1082. - (void)close {
  1083. if (_statement) {
  1084. sqlite3_finalize(_statement);
  1085. _statement = 0x00;
  1086. }
  1087. _inUse = NO;
  1088. }
  1089. - (void)reset {
  1090. if (_statement) {
  1091. sqlite3_reset(_statement);
  1092. }
  1093. _inUse = NO;
  1094. }
  1095. - (NSString*)description {
  1096. return [NSString stringWithFormat:@"%@ %ld hit(s) for query %@", [super description], _useCount, _query];
  1097. }
  1098. @end