FMDatabase.m 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142
  1. #import "FMDatabase.h"
  2. #import "unistd.h"
  3. #import <objc/runtime.h>
  4. @interface FMDatabase ()
  5. - (FMResultSet *)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray*)arrayArgs orDictionary:(NSDictionary *)dictionaryArgs orVAList:(va_list)args;
  6. - (BOOL)executeUpdate:(NSString*)sql error:(NSError**)outErr withArgumentsInArray:(NSArray*)arrayArgs orDictionary:(NSDictionary *)dictionaryArgs orVAList:(va_list)args;
  7. @end
  8. @implementation FMDatabase
  9. @synthesize cachedStatements=_cachedStatements;
  10. @synthesize logsErrors=_logsErrors;
  11. @synthesize crashOnErrors=_crashOnErrors;
  12. @synthesize busyRetryTimeout=_busyRetryTimeout;
  13. @synthesize checkedOut=_checkedOut;
  14. @synthesize traceExecution=_traceExecution;
  15. + (id)databaseWithPath:(NSString*)aPath {
  16. return FMDBReturnAutoreleased([[self alloc] initWithPath:aPath]);
  17. }
  18. + (NSString*)sqliteLibVersion {
  19. return [NSString stringWithFormat:@"%s", sqlite3_libversion()];
  20. }
  21. + (BOOL)isSQLiteThreadSafe {
  22. // make sure to read the sqlite headers on this guy!
  23. return sqlite3_threadsafe();
  24. }
  25. - (id)initWithPath:(NSString*)aPath {
  26. assert(sqlite3_threadsafe()); // whoa there big boy- gotta make sure sqlite it happy with what we're going to do.
  27. self = [super init];
  28. if (self) {
  29. _databasePath = [aPath copy];
  30. _openResultSets = [[NSMutableSet alloc] init];
  31. _db = 0x00;
  32. _logsErrors = 0x00;
  33. _crashOnErrors = 0x00;
  34. _busyRetryTimeout = 0x00;
  35. }
  36. return self;
  37. }
  38. - (void)finalize {
  39. [self close];
  40. [super finalize];
  41. }
  42. - (void)dealloc {
  43. [self close];
  44. FMDBRelease(_openResultSets);
  45. FMDBRelease(_cachedStatements);
  46. FMDBRelease(_databasePath);
  47. FMDBRelease(_openFunctions);
  48. #if ! __has_feature(objc_arc)
  49. [super dealloc];
  50. #endif
  51. }
  52. - (NSString *)databasePath {
  53. return _databasePath;
  54. }
  55. - (sqlite3*)sqliteHandle {
  56. return _db;
  57. }
  58. - (BOOL)open {
  59. if (_db) {
  60. return YES;
  61. }
  62. int err = sqlite3_open((_databasePath ? [_databasePath fileSystemRepresentation] : ":memory:"), &_db );
  63. if(err != SQLITE_OK) {
  64. NSLog(@"error opening!: %d", err);
  65. return NO;
  66. }
  67. return YES;
  68. }
  69. #if SQLITE_VERSION_NUMBER >= 3005000
  70. - (BOOL)openWithFlags:(int)flags {
  71. int err = sqlite3_open_v2((_databasePath ? [_databasePath fileSystemRepresentation] : ":memory:"), &_db, flags, NULL /* Name of VFS module to use */);
  72. if(err != SQLITE_OK) {
  73. NSLog(@"error opening!: %d", err);
  74. return NO;
  75. }
  76. return YES;
  77. }
  78. #endif
  79. - (BOOL)close {
  80. [self clearCachedStatements];
  81. [self closeOpenResultSets];
  82. if (!_db) {
  83. return YES;
  84. }
  85. int rc;
  86. BOOL retry;
  87. int numberOfRetries = 0;
  88. BOOL triedFinalizingOpenStatements = NO;
  89. do {
  90. retry = NO;
  91. rc = sqlite3_close(_db);
  92. if (SQLITE_BUSY == rc || SQLITE_LOCKED == rc) {
  93. retry = YES;
  94. usleep(20);
  95. if (_busyRetryTimeout && (numberOfRetries++ > _busyRetryTimeout)) {
  96. NSLog(@"%s:%d", __FUNCTION__, __LINE__);
  97. NSLog(@"Database busy, unable to close");
  98. return NO;
  99. }
  100. if (!triedFinalizingOpenStatements) {
  101. triedFinalizingOpenStatements = YES;
  102. sqlite3_stmt *pStmt;
  103. while ((pStmt = sqlite3_next_stmt(_db, 0x00)) !=0) {
  104. NSLog(@"Closing leaked statement");
  105. sqlite3_finalize(pStmt);
  106. }
  107. }
  108. }
  109. else if (SQLITE_OK != rc) {
  110. NSLog(@"error closing!: %d", rc);
  111. }
  112. }
  113. while (retry);
  114. _db = nil;
  115. return YES;
  116. }
  117. - (void)clearCachedStatements {
  118. for (FMStatement *cachedStmt in [_cachedStatements objectEnumerator]) {
  119. [cachedStmt close];
  120. }
  121. [_cachedStatements removeAllObjects];
  122. }
  123. - (BOOL)hasOpenResultSets {
  124. return [_openResultSets count] > 0;
  125. }
  126. - (void)closeOpenResultSets {
  127. //Copy the set so we don't get mutation errors
  128. NSMutableSet *openSetCopy = FMDBReturnAutoreleased([_openResultSets copy]);
  129. for (NSValue *rsInWrappedInATastyValueMeal in openSetCopy) {
  130. FMResultSet *rs = (FMResultSet *)[rsInWrappedInATastyValueMeal pointerValue];
  131. [rs setParentDB:nil];
  132. [rs close];
  133. [_openResultSets removeObject:rsInWrappedInATastyValueMeal];
  134. }
  135. }
  136. - (void)resultSetDidClose:(FMResultSet *)resultSet {
  137. NSValue *setValue = [NSValue valueWithNonretainedObject:resultSet];
  138. [_openResultSets removeObject:setValue];
  139. }
  140. - (FMStatement*)cachedStatementForQuery:(NSString*)query {
  141. return [_cachedStatements objectForKey:query];
  142. }
  143. - (void)setCachedStatement:(FMStatement*)statement forQuery:(NSString*)query {
  144. query = [query copy]; // in case we got handed in a mutable string...
  145. [statement setQuery:query];
  146. [_cachedStatements setObject:statement forKey:query];
  147. FMDBRelease(query);
  148. }
  149. - (BOOL)rekey:(NSString*)key {
  150. #ifdef SQLITE_HAS_CODEC
  151. if (!key) {
  152. return NO;
  153. }
  154. int rc = sqlite3_rekey(_db, [key UTF8String], (int)strlen([key UTF8String]));
  155. if (rc != SQLITE_OK) {
  156. NSLog(@"error on rekey: %d", rc);
  157. NSLog(@"%@", [self lastErrorMessage]);
  158. }
  159. return (rc == SQLITE_OK);
  160. #else
  161. return NO;
  162. #endif
  163. }
  164. - (BOOL)setKey:(NSString*)key {
  165. #ifdef SQLITE_HAS_CODEC
  166. if (!key) {
  167. return NO;
  168. }
  169. int rc = sqlite3_key(_db, [key UTF8String], (int)strlen([key UTF8String]));
  170. return (rc == SQLITE_OK);
  171. #else
  172. return NO;
  173. #endif
  174. }
  175. - (BOOL)goodConnection {
  176. if (!_db) {
  177. return NO;
  178. }
  179. FMResultSet *rs = [self executeQuery:@"select name from sqlite_master where type='table'"];
  180. if (rs) {
  181. [rs close];
  182. return YES;
  183. }
  184. return NO;
  185. }
  186. - (void)warnInUse {
  187. NSLog(@"The FMDatabase %@ is currently in use.", self);
  188. #ifndef NS_BLOCK_ASSERTIONS
  189. if (_crashOnErrors) {
  190. abort();
  191. NSAssert1(false, @"The FMDatabase %@ is currently in use.", self);
  192. }
  193. #endif
  194. }
  195. - (BOOL)databaseExists {
  196. if (!_db) {
  197. NSLog(@"The FMDatabase %@ is not open.", self);
  198. #ifndef NS_BLOCK_ASSERTIONS
  199. if (_crashOnErrors) {
  200. abort();
  201. NSAssert1(false, @"The FMDatabase %@ is not open.", self);
  202. }
  203. #endif
  204. return NO;
  205. }
  206. return YES;
  207. }
  208. - (NSString*)lastErrorMessage {
  209. return [NSString stringWithUTF8String:sqlite3_errmsg(_db)];
  210. }
  211. - (BOOL)hadError {
  212. int lastErrCode = [self lastErrorCode];
  213. return (lastErrCode > SQLITE_OK && lastErrCode < SQLITE_ROW);
  214. }
  215. - (int)lastErrorCode {
  216. return sqlite3_errcode(_db);
  217. }
  218. -(NSError*)errorWithMessage:( NSString* )message_
  219. {
  220. NSDictionary* errorMessage_ = [ NSDictionary dictionaryWithObject: message_
  221. forKey: NSLocalizedDescriptionKey];
  222. return [NSError errorWithDomain:@"FMDatabase"
  223. code:sqlite3_errcode(_db)
  224. userInfo:errorMessage_];
  225. }
  226. -(NSError*)lastError
  227. {
  228. return [ self errorWithMessage: [ self lastErrorMessage ] ];
  229. }
  230. - (sqlite_int64)lastInsertRowId {
  231. if (_isExecutingStatement) {
  232. [self warnInUse];
  233. return NO;
  234. }
  235. _isExecutingStatement = YES;
  236. sqlite_int64 ret = sqlite3_last_insert_rowid(_db);
  237. _isExecutingStatement = NO;
  238. return ret;
  239. }
  240. - (int)changes {
  241. if (_isExecutingStatement) {
  242. [self warnInUse];
  243. return 0;
  244. }
  245. _isExecutingStatement = YES;
  246. int ret = sqlite3_changes(_db);
  247. _isExecutingStatement = NO;
  248. return ret;
  249. }
  250. - (void)bindObject:(id)obj toColumn:(int)idx inStatement:(sqlite3_stmt*)pStmt {
  251. if ((!obj) || ((NSNull *)obj == [NSNull null])) {
  252. sqlite3_bind_null(pStmt, idx);
  253. }
  254. // FIXME - someday check the return codes on these binds.
  255. else if ([obj isKindOfClass:[NSData class]]) {
  256. sqlite3_bind_blob(pStmt, idx, [obj bytes], (int)[obj length], SQLITE_STATIC);
  257. }
  258. else if ([obj isKindOfClass:[NSDate class]]) {
  259. sqlite3_bind_double(pStmt, idx, [obj timeIntervalSince1970]);
  260. }
  261. else if ([obj isKindOfClass:[NSNumber class]]) {
  262. if (strcmp([obj objCType], @encode(BOOL)) == 0) {
  263. sqlite3_bind_int(pStmt, idx, ([obj boolValue] ? 1 : 0));
  264. }
  265. else if (strcmp([obj objCType], @encode(int)) == 0) {
  266. sqlite3_bind_int64(pStmt, idx, [obj longValue]);
  267. }
  268. else if (strcmp([obj objCType], @encode(long)) == 0) {
  269. sqlite3_bind_int64(pStmt, idx, [obj longValue]);
  270. }
  271. else if (strcmp([obj objCType], @encode(long long)) == 0) {
  272. sqlite3_bind_int64(pStmt, idx, [obj longLongValue]);
  273. }
  274. else if (strcmp([obj objCType], @encode(unsigned long long)) == 0) {
  275. sqlite3_bind_int64(pStmt, idx, [obj unsignedLongLongValue]);
  276. }
  277. else if (strcmp([obj objCType], @encode(float)) == 0) {
  278. sqlite3_bind_double(pStmt, idx, [obj floatValue]);
  279. }
  280. else if (strcmp([obj objCType], @encode(double)) == 0) {
  281. sqlite3_bind_double(pStmt, idx, [obj doubleValue]);
  282. }
  283. else {
  284. sqlite3_bind_text(pStmt, idx, [[obj description] UTF8String], -1, SQLITE_STATIC);
  285. }
  286. }
  287. else {
  288. sqlite3_bind_text(pStmt, idx, [[obj description] UTF8String], -1, SQLITE_STATIC);
  289. }
  290. }
  291. - (void)extractSQL:(NSString *)sql argumentsList:(va_list)args intoString:(NSMutableString *)cleanedSQL arguments:(NSMutableArray *)arguments {
  292. NSUInteger length = [sql length];
  293. unichar last = '\0';
  294. for (NSUInteger i = 0; i < length; ++i) {
  295. id arg = nil;
  296. unichar current = [sql characterAtIndex:i];
  297. unichar add = current;
  298. if (last == '%') {
  299. switch (current) {
  300. case '@':
  301. arg = va_arg(args, id); break;
  302. case 'c':
  303. // warning: second argument to 'va_arg' is of promotable type 'char'; this va_arg has undefined behavior because arguments will be promoted to 'int'
  304. arg = [NSString stringWithFormat:@"%c", va_arg(args, int)]; break;
  305. case 's':
  306. arg = [NSString stringWithUTF8String:va_arg(args, char*)]; break;
  307. case 'd':
  308. case 'D':
  309. case 'i':
  310. arg = [NSNumber numberWithInt:va_arg(args, int)]; break;
  311. case 'u':
  312. case 'U':
  313. arg = [NSNumber numberWithUnsignedInt:va_arg(args, unsigned int)]; break;
  314. case 'h':
  315. i++;
  316. if (i < length && [sql characterAtIndex:i] == 'i') {
  317. // warning: second argument to 'va_arg' is of promotable type 'short'; this va_arg has undefined behavior because arguments will be promoted to 'int'
  318. arg = [NSNumber numberWithShort:va_arg(args, int)];
  319. }
  320. else if (i < length && [sql characterAtIndex:i] == 'u') {
  321. // 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'
  322. arg = [NSNumber numberWithUnsignedShort:va_arg(args, uint)];
  323. }
  324. else {
  325. i--;
  326. }
  327. break;
  328. case 'q':
  329. i++;
  330. if (i < length && [sql characterAtIndex:i] == 'i') {
  331. arg = [NSNumber numberWithLongLong:va_arg(args, long long)];
  332. }
  333. else if (i < length && [sql characterAtIndex:i] == 'u') {
  334. arg = [NSNumber numberWithUnsignedLongLong:va_arg(args, unsigned long long)];
  335. }
  336. else {
  337. i--;
  338. }
  339. break;
  340. case 'f':
  341. arg = [NSNumber numberWithDouble:va_arg(args, double)]; break;
  342. case 'g':
  343. // warning: second argument to 'va_arg' is of promotable type 'float'; this va_arg has undefined behavior because arguments will be promoted to 'double'
  344. arg = [NSNumber numberWithFloat:va_arg(args, double)]; break;
  345. case 'l':
  346. i++;
  347. if (i < length) {
  348. unichar next = [sql characterAtIndex:i];
  349. if (next == 'l') {
  350. i++;
  351. if (i < length && [sql characterAtIndex:i] == 'd') {
  352. //%lld
  353. arg = [NSNumber numberWithLongLong:va_arg(args, long long)];
  354. }
  355. else if (i < length && [sql characterAtIndex:i] == 'u') {
  356. //%llu
  357. arg = [NSNumber numberWithUnsignedLongLong:va_arg(args, unsigned long long)];
  358. }
  359. else {
  360. i--;
  361. }
  362. }
  363. else if (next == 'd') {
  364. //%ld
  365. arg = [NSNumber numberWithLong:va_arg(args, long)];
  366. }
  367. else if (next == 'u') {
  368. //%lu
  369. arg = [NSNumber numberWithUnsignedLong:va_arg(args, unsigned long)];
  370. }
  371. else {
  372. i--;
  373. }
  374. }
  375. else {
  376. i--;
  377. }
  378. break;
  379. default:
  380. // something else that we can't interpret. just pass it on through like normal
  381. break;
  382. }
  383. }
  384. else if (current == '%') {
  385. // percent sign; skip this character
  386. add = '\0';
  387. }
  388. if (arg != nil) {
  389. [cleanedSQL appendString:@"?"];
  390. [arguments addObject:arg];
  391. }
  392. else if (add != '\0') {
  393. [cleanedSQL appendFormat:@"%C", add];
  394. }
  395. last = current;
  396. }
  397. }
  398. - (FMResultSet *)executeQuery:(NSString *)sql withParameterDictionary:(NSDictionary *)arguments {
  399. return [self executeQuery:sql withArgumentsInArray:nil orDictionary:arguments orVAList:nil];
  400. }
  401. - (FMResultSet *)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray*)arrayArgs orDictionary:(NSDictionary *)dictionaryArgs orVAList:(va_list)args {
  402. if (![self databaseExists]) {
  403. return 0x00;
  404. }
  405. if (_isExecutingStatement) {
  406. [self warnInUse];
  407. return 0x00;
  408. }
  409. _isExecutingStatement = YES;
  410. int rc = 0x00;
  411. sqlite3_stmt *pStmt = 0x00;
  412. FMStatement *statement = 0x00;
  413. FMResultSet *rs = 0x00;
  414. if (_traceExecution && sql) {
  415. NSLog(@"%@ executeQuery: %@", self, sql);
  416. }
  417. if (_shouldCacheStatements) {
  418. statement = [self cachedStatementForQuery:sql];
  419. pStmt = statement ? [statement statement] : 0x00;
  420. }
  421. int numberOfRetries = 0;
  422. BOOL retry = NO;
  423. if (!pStmt) {
  424. do {
  425. retry = NO;
  426. rc = sqlite3_prepare_v2(_db, [sql UTF8String], -1, &pStmt, 0);
  427. if (SQLITE_BUSY == rc || SQLITE_LOCKED == rc) {
  428. retry = YES;
  429. usleep(20);
  430. if (_busyRetryTimeout && (numberOfRetries++ > _busyRetryTimeout)) {
  431. NSLog(@"%s:%d Database busy (%@)", __FUNCTION__, __LINE__, [self databasePath]);
  432. NSLog(@"Database busy");
  433. sqlite3_finalize(pStmt);
  434. _isExecutingStatement = NO;
  435. return nil;
  436. }
  437. }
  438. else if (SQLITE_OK != rc) {
  439. if (_logsErrors) {
  440. NSLog(@"DB Error: %d \"%@\"", [self lastErrorCode], [self lastErrorMessage]);
  441. NSLog(@"DB Query: %@", sql);
  442. NSLog(@"DB Path: %@", _databasePath);
  443. #ifndef NS_BLOCK_ASSERTIONS
  444. if (_crashOnErrors) {
  445. abort();
  446. NSAssert2(false, @"DB Error: %d \"%@\"", [self lastErrorCode], [self lastErrorMessage]);
  447. }
  448. #endif
  449. }
  450. sqlite3_finalize(pStmt);
  451. _isExecutingStatement = NO;
  452. return nil;
  453. }
  454. }
  455. while (retry);
  456. }
  457. id obj;
  458. int idx = 0;
  459. int queryCount = sqlite3_bind_parameter_count(pStmt); // pointed out by Dominic Yu (thanks!)
  460. // If dictionaryArgs is passed in, that means we are using sqlite's named parameter support
  461. if (dictionaryArgs) {
  462. for (NSString *dictionaryKey in [dictionaryArgs allKeys]) {
  463. // Prefix the key with a colon.
  464. NSString *parameterName = [[NSString alloc] initWithFormat:@":%@", dictionaryKey];
  465. // Get the index for the parameter name.
  466. int namedIdx = sqlite3_bind_parameter_index(pStmt, [parameterName UTF8String]);
  467. FMDBRelease(parameterName);
  468. if (namedIdx > 0) {
  469. // Standard binding from here.
  470. [self bindObject:[dictionaryArgs objectForKey:dictionaryKey] toColumn:namedIdx inStatement:pStmt];
  471. }
  472. else {
  473. NSLog(@"Could not find index for %@", dictionaryKey);
  474. }
  475. }
  476. // we need the count of params to avoid an error below.
  477. idx = (int) [[dictionaryArgs allKeys] count];
  478. }
  479. else {
  480. while (idx < queryCount) {
  481. if (arrayArgs) {
  482. obj = [arrayArgs objectAtIndex:idx];
  483. }
  484. else {
  485. obj = va_arg(args, id);
  486. }
  487. if (_traceExecution) {
  488. NSLog(@"obj: %@", obj);
  489. }
  490. idx++;
  491. [self bindObject:obj toColumn:idx inStatement:pStmt];
  492. }
  493. }
  494. if (idx != queryCount) {
  495. NSLog(@"Error: the bind count is not correct for the # of variables (executeQuery)");
  496. sqlite3_finalize(pStmt);
  497. _isExecutingStatement = NO;
  498. return nil;
  499. }
  500. FMDBRetain(statement); // to balance the release below
  501. if (!statement) {
  502. statement = [[FMStatement alloc] init];
  503. [statement setStatement:pStmt];
  504. if (_shouldCacheStatements) {
  505. [self setCachedStatement:statement forQuery:sql];
  506. }
  507. }
  508. // the statement gets closed in rs's dealloc or [rs close];
  509. rs = [FMResultSet resultSetWithStatement:statement usingParentDatabase:self];
  510. [rs setQuery:sql];
  511. NSValue *openResultSet = [NSValue valueWithNonretainedObject:rs];
  512. [_openResultSets addObject:openResultSet];
  513. [statement setUseCount:[statement useCount] + 1];
  514. FMDBRelease(statement);
  515. _isExecutingStatement = NO;
  516. return rs;
  517. }
  518. - (FMResultSet *)executeQuery:(NSString*)sql, ... {
  519. va_list args;
  520. va_start(args, sql);
  521. id result = [self executeQuery:sql withArgumentsInArray:nil orDictionary:nil orVAList:args];
  522. va_end(args);
  523. return result;
  524. }
  525. - (FMResultSet *)executeQueryWithFormat:(NSString*)format, ... {
  526. va_list args;
  527. va_start(args, format);
  528. NSMutableString *sql = [NSMutableString stringWithCapacity:[format length]];
  529. NSMutableArray *arguments = [NSMutableArray array];
  530. [self extractSQL:format argumentsList:args intoString:sql arguments:arguments];
  531. va_end(args);
  532. return [self executeQuery:sql withArgumentsInArray:arguments];
  533. }
  534. - (FMResultSet *)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray *)arguments {
  535. return [self executeQuery:sql withArgumentsInArray:arguments orDictionary:nil orVAList:nil];
  536. }
  537. - (BOOL)executeUpdate:(NSString*)sql error:(NSError**)outErr withArgumentsInArray:(NSArray*)arrayArgs orDictionary:(NSDictionary *)dictionaryArgs orVAList:(va_list)args {
  538. if (![self databaseExists]) {
  539. return NO;
  540. }
  541. if (_isExecutingStatement) {
  542. [self warnInUse];
  543. return NO;
  544. }
  545. _isExecutingStatement = YES;
  546. int rc = 0x00;
  547. sqlite3_stmt *pStmt = 0x00;
  548. FMStatement *cachedStmt = 0x00;
  549. if (_traceExecution && sql) {
  550. NSLog(@"%@ executeUpdate: %@", self, sql);
  551. }
  552. if (_shouldCacheStatements) {
  553. cachedStmt = [self cachedStatementForQuery:sql];
  554. pStmt = cachedStmt ? [cachedStmt statement] : 0x00;
  555. }
  556. int numberOfRetries = 0;
  557. BOOL retry = NO;
  558. if (!pStmt) {
  559. do {
  560. retry = NO;
  561. rc = sqlite3_prepare_v2(_db, [sql UTF8String], -1, &pStmt, 0);
  562. if (SQLITE_BUSY == rc || SQLITE_LOCKED == rc) {
  563. retry = YES;
  564. usleep(20);
  565. if (_busyRetryTimeout && (numberOfRetries++ > _busyRetryTimeout)) {
  566. NSLog(@"%s:%d Database busy (%@)", __FUNCTION__, __LINE__, [self databasePath]);
  567. NSLog(@"Database busy");
  568. sqlite3_finalize(pStmt);
  569. _isExecutingStatement = NO;
  570. return NO;
  571. }
  572. }
  573. else if (SQLITE_OK != rc) {
  574. if (_logsErrors) {
  575. NSLog(@"DB Error: %d \"%@\"", [self lastErrorCode], [self lastErrorMessage]);
  576. NSLog(@"DB Query: %@", sql);
  577. NSLog(@"DB Path: %@", _databasePath);
  578. #ifndef NS_BLOCK_ASSERTIONS
  579. if (_crashOnErrors) {
  580. abort();
  581. NSAssert2(false, @"DB Error: %d \"%@\"", [self lastErrorCode], [self lastErrorMessage]);
  582. }
  583. #endif
  584. }
  585. sqlite3_finalize(pStmt);
  586. if (outErr) {
  587. *outErr = [ self errorWithMessage: [NSString stringWithUTF8String:sqlite3_errmsg(_db)] ];
  588. }
  589. _isExecutingStatement = NO;
  590. return NO;
  591. }
  592. }
  593. while (retry);
  594. }
  595. id obj;
  596. int idx = 0;
  597. int queryCount = sqlite3_bind_parameter_count(pStmt);
  598. // If dictionaryArgs is passed in, that means we are using sqlite's named parameter support
  599. if (dictionaryArgs) {
  600. for (NSString *dictionaryKey in [dictionaryArgs allKeys]) {
  601. // Prefix the key with a colon.
  602. NSString *parameterName = [[NSString alloc] initWithFormat:@":%@", dictionaryKey];
  603. // Get the index for the parameter name.
  604. int namedIdx = sqlite3_bind_parameter_index(pStmt, [parameterName UTF8String]);
  605. FMDBRelease(parameterName);
  606. if (namedIdx > 0) {
  607. // Standard binding from here.
  608. [self bindObject:[dictionaryArgs objectForKey:dictionaryKey] toColumn:namedIdx inStatement:pStmt];
  609. }
  610. else {
  611. NSLog(@"Could not find index for %@", dictionaryKey);
  612. }
  613. }
  614. // we need the count of params to avoid an error below.
  615. idx = (int) [[dictionaryArgs allKeys] count];
  616. }
  617. else {
  618. while (idx < queryCount) {
  619. if (arrayArgs) {
  620. obj = [arrayArgs objectAtIndex:idx];
  621. }
  622. else {
  623. obj = va_arg(args, id);
  624. }
  625. if (_traceExecution) {
  626. NSLog(@"obj: %@", obj);
  627. }
  628. idx++;
  629. [self bindObject:obj toColumn:idx inStatement:pStmt];
  630. }
  631. }
  632. if (idx != queryCount) {
  633. NSLog(@"Error: the bind count is not correct for the # of variables (%@) (executeUpdate)", sql);
  634. sqlite3_finalize(pStmt);
  635. _isExecutingStatement = NO;
  636. return NO;
  637. }
  638. /* Call sqlite3_step() to run the virtual machine. Since the SQL being
  639. ** executed is not a SELECT statement, we assume no data will be returned.
  640. */
  641. numberOfRetries = 0;
  642. do {
  643. rc = sqlite3_step(pStmt);
  644. retry = NO;
  645. if (SQLITE_BUSY == rc || SQLITE_LOCKED == rc) {
  646. // this will happen if the db is locked, like if we are doing an update or insert.
  647. // in that case, retry the step... and maybe wait just 10 milliseconds.
  648. retry = YES;
  649. if (SQLITE_LOCKED == rc) {
  650. rc = sqlite3_reset(pStmt);
  651. if (rc != SQLITE_LOCKED) {
  652. NSLog(@"Unexpected result from sqlite3_reset (%d) eu", rc);
  653. }
  654. }
  655. usleep(20);
  656. if (_busyRetryTimeout && (numberOfRetries++ > _busyRetryTimeout)) {
  657. NSLog(@"%s:%d Database busy (%@)", __FUNCTION__, __LINE__, [self databasePath]);
  658. NSLog(@"Database busy");
  659. retry = NO;
  660. }
  661. }
  662. else if (SQLITE_DONE == rc) {
  663. // all is well, let's return.
  664. }
  665. else if (SQLITE_ERROR == rc) {
  666. NSLog(@"Error calling sqlite3_step (%d: %s) SQLITE_ERROR", rc, sqlite3_errmsg(_db));
  667. NSLog(@"DB Query: %@", sql);
  668. }
  669. else if (SQLITE_MISUSE == rc) {
  670. // uh oh.
  671. NSLog(@"Error calling sqlite3_step (%d: %s) SQLITE_MISUSE", rc, sqlite3_errmsg(_db));
  672. NSLog(@"DB Query: %@", sql);
  673. }
  674. else {
  675. // wtf?
  676. NSLog(@"Unknown error calling sqlite3_step (%d: %s) eu", rc, sqlite3_errmsg(_db));
  677. NSLog(@"DB Query: %@", sql);
  678. }
  679. } while (retry);
  680. if (rc == SQLITE_ROW) {
  681. NSAssert1(NO, @"A executeUpdate is being called with a query string '%@'", sql);
  682. }
  683. if (_shouldCacheStatements && !cachedStmt) {
  684. cachedStmt = [[FMStatement alloc] init];
  685. [cachedStmt setStatement:pStmt];
  686. [self setCachedStatement:cachedStmt forQuery:sql];
  687. FMDBRelease(cachedStmt);
  688. }
  689. int closeErrorCode;
  690. if (cachedStmt) {
  691. [cachedStmt setUseCount:[cachedStmt useCount] + 1];
  692. closeErrorCode = sqlite3_reset(pStmt);
  693. }
  694. else {
  695. /* Finalize the virtual machine. This releases all memory and other
  696. ** resources allocated by the sqlite3_prepare() call above.
  697. */
  698. closeErrorCode = sqlite3_finalize(pStmt);
  699. }
  700. if (closeErrorCode != SQLITE_OK) {
  701. NSLog(@"Unknown error finalizing or resetting statement (%d: %s)", closeErrorCode, sqlite3_errmsg(_db));
  702. NSLog(@"DB Query: %@", sql);
  703. }
  704. _isExecutingStatement = NO;
  705. return (rc == SQLITE_DONE || rc == SQLITE_OK);
  706. }
  707. - (BOOL)executeUpdate:(NSString*)sql, ... {
  708. va_list args;
  709. va_start(args, sql);
  710. BOOL result = [self executeUpdate:sql error:nil withArgumentsInArray:nil orDictionary:nil orVAList:args];
  711. va_end(args);
  712. return result;
  713. }
  714. - (BOOL)executeUpdate:(NSString*)sql withArgumentsInArray:(NSArray *)arguments {
  715. return [self executeUpdate:sql error:nil withArgumentsInArray:arguments orDictionary:nil orVAList:nil];
  716. }
  717. - (BOOL)executeUpdate:(NSString*)sql withParameterDictionary:(NSDictionary *)arguments {
  718. return [self executeUpdate:sql error:nil withArgumentsInArray:nil orDictionary:arguments orVAList:nil];
  719. }
  720. - (BOOL)executeUpdateWithFormat:(NSString*)format, ... {
  721. va_list args;
  722. va_start(args, format);
  723. NSMutableString *sql = [NSMutableString stringWithCapacity:[format length]];
  724. NSMutableArray *arguments = [NSMutableArray array];
  725. [self extractSQL:format argumentsList:args intoString:sql arguments:arguments];
  726. va_end(args);
  727. return [self executeUpdate:sql withArgumentsInArray:arguments];
  728. }
  729. - (BOOL)update:(NSString*)sql withErrorAndBindings:(NSError**)outErr, ... {
  730. va_list args;
  731. va_start(args, outErr);
  732. BOOL result = [self executeUpdate:sql error:outErr withArgumentsInArray:nil orDictionary:nil orVAList:args];
  733. va_end(args);
  734. return result;
  735. }
  736. - (BOOL)rollback {
  737. BOOL b = [self executeUpdate:@"rollback transaction"];
  738. if (b) {
  739. _inTransaction = NO;
  740. }
  741. return b;
  742. }
  743. - (BOOL)commit {
  744. BOOL b = [self executeUpdate:@"commit transaction"];
  745. if (b) {
  746. _inTransaction = NO;
  747. }
  748. return b;
  749. }
  750. - (BOOL)beginDeferredTransaction {
  751. BOOL b = [self executeUpdate:@"begin deferred transaction"];
  752. if (b) {
  753. _inTransaction = YES;
  754. }
  755. return b;
  756. }
  757. - (BOOL)beginTransaction {
  758. BOOL b = [self executeUpdate:@"begin exclusive transaction"];
  759. if (b) {
  760. _inTransaction = YES;
  761. }
  762. return b;
  763. }
  764. - (BOOL)inTransaction {
  765. return _inTransaction;
  766. }
  767. #if SQLITE_VERSION_NUMBER >= 3007000
  768. - (BOOL)startSavePointWithName:(NSString*)name error:(NSError**)outErr {
  769. // FIXME: make sure the savepoint name doesn't have a ' in it.
  770. NSParameterAssert(name);
  771. if (![self executeUpdate:[NSString stringWithFormat:@"savepoint '%@';", name]]) {
  772. if (*outErr) {
  773. *outErr = [self lastError];
  774. }
  775. return NO;
  776. }
  777. return YES;
  778. }
  779. - (BOOL)releaseSavePointWithName:(NSString*)name error:(NSError**)outErr {
  780. NSParameterAssert(name);
  781. BOOL worked = [self executeUpdate:[NSString stringWithFormat:@"release savepoint '%@';", name]];
  782. if (!worked && *outErr) {
  783. *outErr = [self lastError];
  784. }
  785. return worked;
  786. }
  787. - (BOOL)rollbackToSavePointWithName:(NSString*)name error:(NSError**)outErr {
  788. NSParameterAssert(name);
  789. BOOL worked = [self executeUpdate:[NSString stringWithFormat:@"rollback transaction to savepoint '%@';", name]];
  790. if (!worked && *outErr) {
  791. *outErr = [self lastError];
  792. }
  793. return worked;
  794. }
  795. - (NSError*)inSavePoint:(void (^)(BOOL *rollback))block {
  796. static unsigned long savePointIdx = 0;
  797. NSString *name = [NSString stringWithFormat:@"dbSavePoint%ld", savePointIdx++];
  798. BOOL shouldRollback = NO;
  799. NSError *err = 0x00;
  800. if (![self startSavePointWithName:name error:&err]) {
  801. return err;
  802. }
  803. block(&shouldRollback);
  804. if (shouldRollback) {
  805. [self rollbackToSavePointWithName:name error:&err];
  806. }
  807. else {
  808. [self releaseSavePointWithName:name error:&err];
  809. }
  810. return err;
  811. }
  812. #endif
  813. - (BOOL)shouldCacheStatements {
  814. return _shouldCacheStatements;
  815. }
  816. - (void)setShouldCacheStatements:(BOOL)value {
  817. _shouldCacheStatements = value;
  818. if (_shouldCacheStatements && !_cachedStatements) {
  819. [self setCachedStatements:[NSMutableDictionary dictionary]];
  820. }
  821. if (!_shouldCacheStatements) {
  822. [self setCachedStatements:nil];
  823. }
  824. }
  825. void FMDBBlockSQLiteCallBackFunction(sqlite3_context *context, int argc, sqlite3_value **argv);
  826. void FMDBBlockSQLiteCallBackFunction(sqlite3_context *context, int argc, sqlite3_value **argv) {
  827. #if ! __has_feature(objc_arc)
  828. void (^block)(sqlite3_context *context, int argc, sqlite3_value **argv) = (id)sqlite3_user_data(context);
  829. #else
  830. void (^block)(sqlite3_context *context, int argc, sqlite3_value **argv) = (__bridge id)sqlite3_user_data(context);
  831. #endif
  832. block(context, argc, argv);
  833. }
  834. - (void)makeFunctionNamed:(NSString*)name maximumArguments:(int)count withBlock:(void (^)(sqlite3_context *context, int argc, sqlite3_value **argv))block {
  835. if (!_openFunctions) {
  836. _openFunctions = [NSMutableSet new];
  837. }
  838. id b = FMDBReturnAutoreleased([block copy]);
  839. [_openFunctions addObject:b];
  840. /* 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. */
  841. #if ! __has_feature(objc_arc)
  842. sqlite3_create_function([self sqliteHandle], [name UTF8String], count, SQLITE_UTF8, (void*)b, &FMDBBlockSQLiteCallBackFunction, 0x00, 0x00);
  843. #else
  844. sqlite3_create_function([self sqliteHandle], [name UTF8String], count, SQLITE_UTF8, (__bridge void*)b, &FMDBBlockSQLiteCallBackFunction, 0x00, 0x00);
  845. #endif
  846. }
  847. @end
  848. @implementation FMStatement
  849. @synthesize statement=_statement;
  850. @synthesize query=_query;
  851. @synthesize useCount=_useCount;
  852. - (void)finalize {
  853. [self close];
  854. [super finalize];
  855. }
  856. - (void)dealloc {
  857. [self close];
  858. FMDBRelease(_query);
  859. #if ! __has_feature(objc_arc)
  860. [super dealloc];
  861. #endif
  862. }
  863. - (void)close {
  864. if (_statement) {
  865. sqlite3_finalize(_statement);
  866. _statement = 0x00;
  867. }
  868. }
  869. - (void)reset {
  870. if (_statement) {
  871. sqlite3_reset(_statement);
  872. }
  873. }
  874. - (NSString*)description {
  875. return [NSString stringWithFormat:@"%@ %ld hit(s) for query %@", [super description], _useCount, _query];
  876. }
  877. @end