FMDatabase.m 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127
  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*)lastError {
  219. return [NSError errorWithDomain:@"FMDatabase" code:sqlite3_errcode(_db) userInfo:[NSDictionary dictionaryWithObject:[self lastErrorMessage] forKey:NSLocalizedDescriptionKey]];
  220. }
  221. - (sqlite_int64)lastInsertRowId {
  222. if (_isExecutingStatement) {
  223. [self warnInUse];
  224. return NO;
  225. }
  226. _isExecutingStatement = YES;
  227. sqlite_int64 ret = sqlite3_last_insert_rowid(_db);
  228. _isExecutingStatement = NO;
  229. return ret;
  230. }
  231. - (int)changes {
  232. if (_isExecutingStatement) {
  233. [self warnInUse];
  234. return 0;
  235. }
  236. _isExecutingStatement = YES;
  237. int ret = sqlite3_changes(_db);
  238. _isExecutingStatement = NO;
  239. return ret;
  240. }
  241. - (void)bindObject:(id)obj toColumn:(int)idx inStatement:(sqlite3_stmt*)pStmt {
  242. if ((!obj) || ((NSNull *)obj == [NSNull null])) {
  243. sqlite3_bind_null(pStmt, idx);
  244. }
  245. // FIXME - someday check the return codes on these binds.
  246. else if ([obj isKindOfClass:[NSData class]]) {
  247. sqlite3_bind_blob(pStmt, idx, [obj bytes], (int)[obj length], SQLITE_STATIC);
  248. }
  249. else if ([obj isKindOfClass:[NSDate class]]) {
  250. sqlite3_bind_double(pStmt, idx, [obj timeIntervalSince1970]);
  251. }
  252. else if ([obj isKindOfClass:[NSNumber class]]) {
  253. if (strcmp([obj objCType], @encode(BOOL)) == 0) {
  254. sqlite3_bind_int(pStmt, idx, ([obj boolValue] ? 1 : 0));
  255. }
  256. else if (strcmp([obj objCType], @encode(int)) == 0) {
  257. sqlite3_bind_int64(pStmt, idx, [obj longValue]);
  258. }
  259. else if (strcmp([obj objCType], @encode(long)) == 0) {
  260. sqlite3_bind_int64(pStmt, idx, [obj longValue]);
  261. }
  262. else if (strcmp([obj objCType], @encode(long long)) == 0) {
  263. sqlite3_bind_int64(pStmt, idx, [obj longLongValue]);
  264. }
  265. else if (strcmp([obj objCType], @encode(unsigned long long)) == 0) {
  266. sqlite3_bind_int64(pStmt, idx, [obj unsignedLongLongValue]);
  267. }
  268. else if (strcmp([obj objCType], @encode(float)) == 0) {
  269. sqlite3_bind_double(pStmt, idx, [obj floatValue]);
  270. }
  271. else if (strcmp([obj objCType], @encode(double)) == 0) {
  272. sqlite3_bind_double(pStmt, idx, [obj doubleValue]);
  273. }
  274. else {
  275. sqlite3_bind_text(pStmt, idx, [[obj description] UTF8String], -1, SQLITE_STATIC);
  276. }
  277. }
  278. else {
  279. sqlite3_bind_text(pStmt, idx, [[obj description] UTF8String], -1, SQLITE_STATIC);
  280. }
  281. }
  282. - (void)extractSQL:(NSString *)sql argumentsList:(va_list)args intoString:(NSMutableString *)cleanedSQL arguments:(NSMutableArray *)arguments {
  283. NSUInteger length = [sql length];
  284. unichar last = '\0';
  285. for (NSUInteger i = 0; i < length; ++i) {
  286. id arg = nil;
  287. unichar current = [sql characterAtIndex:i];
  288. unichar add = current;
  289. if (last == '%') {
  290. switch (current) {
  291. case '@':
  292. arg = va_arg(args, id); break;
  293. case 'c':
  294. // warning: second argument to 'va_arg' is of promotable type 'char'; this va_arg has undefined behavior because arguments will be promoted to 'int'
  295. arg = [NSString stringWithFormat:@"%c", va_arg(args, int)]; break;
  296. case 's':
  297. arg = [NSString stringWithUTF8String:va_arg(args, char*)]; break;
  298. case 'd':
  299. case 'D':
  300. case 'i':
  301. arg = [NSNumber numberWithInt:va_arg(args, int)]; break;
  302. case 'u':
  303. case 'U':
  304. arg = [NSNumber numberWithUnsignedInt:va_arg(args, unsigned int)]; break;
  305. case 'h':
  306. i++;
  307. if (i < length && [sql characterAtIndex:i] == 'i') {
  308. // warning: second argument to 'va_arg' is of promotable type 'short'; this va_arg has undefined behavior because arguments will be promoted to 'int'
  309. arg = [NSNumber numberWithShort:va_arg(args, int)];
  310. }
  311. else if (i < length && [sql characterAtIndex:i] == 'u') {
  312. // 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'
  313. arg = [NSNumber numberWithUnsignedShort:va_arg(args, uint)];
  314. }
  315. else {
  316. i--;
  317. }
  318. break;
  319. case 'q':
  320. i++;
  321. if (i < length && [sql characterAtIndex:i] == 'i') {
  322. arg = [NSNumber numberWithLongLong:va_arg(args, long long)];
  323. }
  324. else if (i < length && [sql characterAtIndex:i] == 'u') {
  325. arg = [NSNumber numberWithUnsignedLongLong:va_arg(args, unsigned long long)];
  326. }
  327. else {
  328. i--;
  329. }
  330. break;
  331. case 'f':
  332. arg = [NSNumber numberWithDouble:va_arg(args, double)]; break;
  333. case 'g':
  334. // warning: second argument to 'va_arg' is of promotable type 'float'; this va_arg has undefined behavior because arguments will be promoted to 'double'
  335. arg = [NSNumber numberWithFloat:va_arg(args, double)]; break;
  336. case 'l':
  337. i++;
  338. if (i < length) {
  339. unichar next = [sql characterAtIndex:i];
  340. if (next == 'l') {
  341. i++;
  342. if (i < length && [sql characterAtIndex:i] == 'd') {
  343. //%lld
  344. arg = [NSNumber numberWithLongLong:va_arg(args, long long)];
  345. }
  346. else if (i < length && [sql characterAtIndex:i] == 'u') {
  347. //%llu
  348. arg = [NSNumber numberWithUnsignedLongLong:va_arg(args, unsigned long long)];
  349. }
  350. else {
  351. i--;
  352. }
  353. }
  354. else if (next == 'd') {
  355. //%ld
  356. arg = [NSNumber numberWithLong:va_arg(args, long)];
  357. }
  358. else if (next == 'u') {
  359. //%lu
  360. arg = [NSNumber numberWithUnsignedLong:va_arg(args, unsigned long)];
  361. }
  362. else {
  363. i--;
  364. }
  365. }
  366. else {
  367. i--;
  368. }
  369. break;
  370. default:
  371. // something else that we can't interpret. just pass it on through like normal
  372. break;
  373. }
  374. }
  375. else if (current == '%') {
  376. // percent sign; skip this character
  377. add = '\0';
  378. }
  379. if (arg != nil) {
  380. [cleanedSQL appendString:@"?"];
  381. [arguments addObject:arg];
  382. }
  383. else if (add != '\0') {
  384. [cleanedSQL appendFormat:@"%C", add];
  385. }
  386. last = current;
  387. }
  388. }
  389. - (FMResultSet *)executeQuery:(NSString *)sql withParameterDictionary:(NSDictionary *)arguments {
  390. return [self executeQuery:sql withArgumentsInArray:nil orDictionary:arguments orVAList:nil];
  391. }
  392. - (FMResultSet *)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray*)arrayArgs orDictionary:(NSDictionary *)dictionaryArgs orVAList:(va_list)args {
  393. if (![self databaseExists]) {
  394. return 0x00;
  395. }
  396. if (_isExecutingStatement) {
  397. [self warnInUse];
  398. return 0x00;
  399. }
  400. _isExecutingStatement = YES;
  401. int rc = 0x00;
  402. sqlite3_stmt *pStmt = 0x00;
  403. FMStatement *statement = 0x00;
  404. FMResultSet *rs = 0x00;
  405. if (_traceExecution && sql) {
  406. NSLog(@"%@ executeQuery: %@", self, sql);
  407. }
  408. if (_shouldCacheStatements) {
  409. statement = [self cachedStatementForQuery:sql];
  410. pStmt = statement ? [statement statement] : 0x00;
  411. }
  412. int numberOfRetries = 0;
  413. BOOL retry = NO;
  414. if (!pStmt) {
  415. do {
  416. retry = NO;
  417. rc = sqlite3_prepare_v2(_db, [sql UTF8String], -1, &pStmt, 0);
  418. if (SQLITE_BUSY == rc || SQLITE_LOCKED == rc) {
  419. retry = YES;
  420. usleep(20);
  421. if (_busyRetryTimeout && (numberOfRetries++ > _busyRetryTimeout)) {
  422. NSLog(@"%s:%d Database busy (%@)", __FUNCTION__, __LINE__, [self databasePath]);
  423. NSLog(@"Database busy");
  424. sqlite3_finalize(pStmt);
  425. _isExecutingStatement = NO;
  426. return nil;
  427. }
  428. }
  429. else if (SQLITE_OK != rc) {
  430. if (_logsErrors) {
  431. NSLog(@"DB Error: %d \"%@\"", [self lastErrorCode], [self lastErrorMessage]);
  432. NSLog(@"DB Query: %@", sql);
  433. NSLog(@"DB Path: %@", _databasePath);
  434. #ifndef NS_BLOCK_ASSERTIONS
  435. if (_crashOnErrors) {
  436. abort();
  437. NSAssert2(false, @"DB Error: %d \"%@\"", [self lastErrorCode], [self lastErrorMessage]);
  438. }
  439. #endif
  440. }
  441. sqlite3_finalize(pStmt);
  442. _isExecutingStatement = NO;
  443. return nil;
  444. }
  445. }
  446. while (retry);
  447. }
  448. id obj;
  449. int idx = 0;
  450. int queryCount = sqlite3_bind_parameter_count(pStmt); // pointed out by Dominic Yu (thanks!)
  451. // If dictionaryArgs is passed in, that means we are using sqlite's named parameter support
  452. if (dictionaryArgs) {
  453. for (NSString *dictionaryKey in [dictionaryArgs allKeys]) {
  454. // Prefix the key with a colon.
  455. NSString *parameterName = [[NSString alloc] initWithFormat:@":%@", dictionaryKey];
  456. // Get the index for the parameter name.
  457. int namedIdx = sqlite3_bind_parameter_index(pStmt, [parameterName UTF8String]);
  458. FMDBRelease(parameterName);
  459. if (namedIdx > 0) {
  460. // Standard binding from here.
  461. [self bindObject:[dictionaryArgs objectForKey:dictionaryKey] toColumn:namedIdx inStatement:pStmt];
  462. }
  463. else {
  464. NSLog(@"Could not find index for %@", dictionaryKey);
  465. }
  466. }
  467. // we need the count of params to avoid an error below.
  468. idx = (int) [[dictionaryArgs allKeys] count];
  469. }
  470. else {
  471. while (idx < queryCount) {
  472. if (arrayArgs) {
  473. obj = [arrayArgs objectAtIndex:idx];
  474. }
  475. else {
  476. obj = va_arg(args, id);
  477. }
  478. if (_traceExecution) {
  479. NSLog(@"obj: %@", obj);
  480. }
  481. idx++;
  482. [self bindObject:obj toColumn:idx inStatement:pStmt];
  483. }
  484. }
  485. if (idx != queryCount) {
  486. NSLog(@"Error: the bind count is not correct for the # of variables (executeQuery)");
  487. sqlite3_finalize(pStmt);
  488. _isExecutingStatement = NO;
  489. return nil;
  490. }
  491. FMDBRetain(statement); // to balance the release below
  492. if (!statement) {
  493. statement = [[FMStatement alloc] init];
  494. [statement setStatement:pStmt];
  495. if (_shouldCacheStatements) {
  496. [self setCachedStatement:statement forQuery:sql];
  497. }
  498. }
  499. // the statement gets closed in rs's dealloc or [rs close];
  500. rs = [FMResultSet resultSetWithStatement:statement usingParentDatabase:self];
  501. [rs setQuery:sql];
  502. NSValue *openResultSet = [NSValue valueWithNonretainedObject:rs];
  503. [_openResultSets addObject:openResultSet];
  504. [statement setUseCount:[statement useCount] + 1];
  505. FMDBRelease(statement);
  506. _isExecutingStatement = NO;
  507. return rs;
  508. }
  509. - (FMResultSet *)executeQuery:(NSString*)sql, ... {
  510. va_list args;
  511. va_start(args, sql);
  512. id result = [self executeQuery:sql withArgumentsInArray:nil orDictionary:nil orVAList:args];
  513. va_end(args);
  514. return result;
  515. }
  516. - (FMResultSet *)executeQueryWithFormat:(NSString*)format, ... {
  517. va_list args;
  518. va_start(args, format);
  519. NSMutableString *sql = [NSMutableString stringWithCapacity:[format length]];
  520. NSMutableArray *arguments = [NSMutableArray array];
  521. [self extractSQL:format argumentsList:args intoString:sql arguments:arguments];
  522. va_end(args);
  523. return [self executeQuery:sql withArgumentsInArray:arguments];
  524. }
  525. - (FMResultSet *)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray *)arguments {
  526. return [self executeQuery:sql withArgumentsInArray:arguments orDictionary:nil orVAList:nil];
  527. }
  528. - (BOOL)executeUpdate:(NSString*)sql error:(NSError**)outErr withArgumentsInArray:(NSArray*)arrayArgs orDictionary:(NSDictionary *)dictionaryArgs orVAList:(va_list)args {
  529. if (![self databaseExists]) {
  530. return NO;
  531. }
  532. if (_isExecutingStatement) {
  533. [self warnInUse];
  534. return NO;
  535. }
  536. _isExecutingStatement = YES;
  537. int rc = 0x00;
  538. sqlite3_stmt *pStmt = 0x00;
  539. FMStatement *cachedStmt = 0x00;
  540. if (_traceExecution && sql) {
  541. NSLog(@"%@ executeUpdate: %@", self, sql);
  542. }
  543. if (_shouldCacheStatements) {
  544. cachedStmt = [self cachedStatementForQuery:sql];
  545. pStmt = cachedStmt ? [cachedStmt statement] : 0x00;
  546. }
  547. int numberOfRetries = 0;
  548. BOOL retry = NO;
  549. if (!pStmt) {
  550. do {
  551. retry = NO;
  552. rc = sqlite3_prepare_v2(_db, [sql UTF8String], -1, &pStmt, 0);
  553. if (SQLITE_BUSY == rc || SQLITE_LOCKED == rc) {
  554. retry = YES;
  555. usleep(20);
  556. if (_busyRetryTimeout && (numberOfRetries++ > _busyRetryTimeout)) {
  557. NSLog(@"%s:%d Database busy (%@)", __FUNCTION__, __LINE__, [self databasePath]);
  558. NSLog(@"Database busy");
  559. sqlite3_finalize(pStmt);
  560. _isExecutingStatement = NO;
  561. return NO;
  562. }
  563. }
  564. else if (SQLITE_OK != rc) {
  565. if (_logsErrors) {
  566. NSLog(@"DB Error: %d \"%@\"", [self lastErrorCode], [self lastErrorMessage]);
  567. NSLog(@"DB Query: %@", sql);
  568. NSLog(@"DB Path: %@", _databasePath);
  569. #ifndef NS_BLOCK_ASSERTIONS
  570. if (_crashOnErrors) {
  571. abort();
  572. NSAssert2(false, @"DB Error: %d \"%@\"", [self lastErrorCode], [self lastErrorMessage]);
  573. }
  574. #endif
  575. }
  576. sqlite3_finalize(pStmt);
  577. if (outErr) {
  578. *outErr = [NSError errorWithDomain:[NSString stringWithUTF8String:sqlite3_errmsg(_db)] code:rc userInfo:nil];
  579. }
  580. _isExecutingStatement = NO;
  581. return NO;
  582. }
  583. }
  584. while (retry);
  585. }
  586. id obj;
  587. int idx = 0;
  588. int queryCount = sqlite3_bind_parameter_count(pStmt);
  589. // If dictionaryArgs is passed in, that means we are using sqlite's named parameter support
  590. if (dictionaryArgs) {
  591. for (NSString *dictionaryKey in [dictionaryArgs allKeys]) {
  592. // Prefix the key with a colon.
  593. NSString *parameterName = [[NSString alloc] initWithFormat:@":%@", dictionaryKey];
  594. // Get the index for the parameter name.
  595. int namedIdx = sqlite3_bind_parameter_index(pStmt, [parameterName UTF8String]);
  596. FMDBRelease(parameterName);
  597. if (namedIdx > 0) {
  598. // Standard binding from here.
  599. [self bindObject:[dictionaryArgs objectForKey:dictionaryKey] toColumn:namedIdx inStatement:pStmt];
  600. }
  601. else {
  602. NSLog(@"Could not find index for %@", dictionaryKey);
  603. }
  604. }
  605. // we need the count of params to avoid an error below.
  606. idx = (int) [[dictionaryArgs allKeys] count];
  607. }
  608. else {
  609. while (idx < queryCount) {
  610. if (arrayArgs) {
  611. obj = [arrayArgs objectAtIndex:idx];
  612. }
  613. else {
  614. obj = va_arg(args, id);
  615. }
  616. if (_traceExecution) {
  617. NSLog(@"obj: %@", obj);
  618. }
  619. idx++;
  620. [self bindObject:obj toColumn:idx inStatement:pStmt];
  621. }
  622. }
  623. if (idx != queryCount) {
  624. NSLog(@"Error: the bind count is not correct for the # of variables (%@) (executeUpdate)", sql);
  625. sqlite3_finalize(pStmt);
  626. _isExecutingStatement = NO;
  627. return NO;
  628. }
  629. /* Call sqlite3_step() to run the virtual machine. Since the SQL being
  630. ** executed is not a SELECT statement, we assume no data will be returned.
  631. */
  632. numberOfRetries = 0;
  633. do {
  634. rc = sqlite3_step(pStmt);
  635. retry = NO;
  636. if (SQLITE_BUSY == rc || SQLITE_LOCKED == rc) {
  637. // this will happen if the db is locked, like if we are doing an update or insert.
  638. // in that case, retry the step... and maybe wait just 10 milliseconds.
  639. retry = YES;
  640. if (SQLITE_LOCKED == rc) {
  641. rc = sqlite3_reset(pStmt);
  642. if (rc != SQLITE_LOCKED) {
  643. NSLog(@"Unexpected result from sqlite3_reset (%d) eu", rc);
  644. }
  645. }
  646. usleep(20);
  647. if (_busyRetryTimeout && (numberOfRetries++ > _busyRetryTimeout)) {
  648. NSLog(@"%s:%d Database busy (%@)", __FUNCTION__, __LINE__, [self databasePath]);
  649. NSLog(@"Database busy");
  650. retry = NO;
  651. }
  652. }
  653. else if (SQLITE_DONE == rc) {
  654. // all is well, let's return.
  655. }
  656. else if (SQLITE_ERROR == rc) {
  657. NSLog(@"Error calling sqlite3_step (%d: %s) SQLITE_ERROR", rc, sqlite3_errmsg(_db));
  658. NSLog(@"DB Query: %@", sql);
  659. }
  660. else if (SQLITE_MISUSE == rc) {
  661. // uh oh.
  662. NSLog(@"Error calling sqlite3_step (%d: %s) SQLITE_MISUSE", rc, sqlite3_errmsg(_db));
  663. NSLog(@"DB Query: %@", sql);
  664. }
  665. else {
  666. // wtf?
  667. NSLog(@"Unknown error calling sqlite3_step (%d: %s) eu", rc, sqlite3_errmsg(_db));
  668. NSLog(@"DB Query: %@", sql);
  669. }
  670. } while (retry);
  671. if (rc == SQLITE_ROW) {
  672. NSAssert1(NO, @"A executeUpdate is being called with a query string '%@'", sql);
  673. }
  674. if (_shouldCacheStatements && !cachedStmt) {
  675. cachedStmt = [[FMStatement alloc] init];
  676. [cachedStmt setStatement:pStmt];
  677. [self setCachedStatement:cachedStmt forQuery:sql];
  678. FMDBRelease(cachedStmt);
  679. }
  680. int closeErrorCode;
  681. if (cachedStmt) {
  682. [cachedStmt setUseCount:[cachedStmt useCount] + 1];
  683. closeErrorCode = sqlite3_reset(pStmt);
  684. }
  685. else {
  686. /* Finalize the virtual machine. This releases all memory and other
  687. ** resources allocated by the sqlite3_prepare() call above.
  688. */
  689. closeErrorCode = sqlite3_finalize(pStmt);
  690. }
  691. if (closeErrorCode != SQLITE_OK) {
  692. NSLog(@"Unknown error finalizing or resetting statement (%d: %s)", closeErrorCode, sqlite3_errmsg(_db));
  693. NSLog(@"DB Query: %@", sql);
  694. }
  695. _isExecutingStatement = NO;
  696. return (rc == SQLITE_DONE || rc == SQLITE_OK);
  697. }
  698. - (BOOL)executeUpdate:(NSString*)sql, ... {
  699. va_list args;
  700. va_start(args, sql);
  701. BOOL result = [self executeUpdate:sql error:nil withArgumentsInArray:nil orDictionary:nil orVAList:args];
  702. va_end(args);
  703. return result;
  704. }
  705. - (BOOL)executeUpdate:(NSString*)sql withArgumentsInArray:(NSArray *)arguments {
  706. return [self executeUpdate:sql error:nil withArgumentsInArray:arguments orDictionary:nil orVAList:nil];
  707. }
  708. - (BOOL)executeUpdate:(NSString*)sql withParameterDictionary:(NSDictionary *)arguments {
  709. return [self executeUpdate:sql error:nil withArgumentsInArray:nil orDictionary:arguments orVAList:nil];
  710. }
  711. - (BOOL)executeUpdateWithFormat:(NSString*)format, ... {
  712. va_list args;
  713. va_start(args, format);
  714. NSMutableString *sql = [NSMutableString stringWithCapacity:[format length]];
  715. NSMutableArray *arguments = [NSMutableArray array];
  716. [self extractSQL:format argumentsList:args intoString:sql arguments:arguments];
  717. va_end(args);
  718. return [self executeUpdate:sql withArgumentsInArray:arguments];
  719. }
  720. - (BOOL)update:(NSString*)sql withErrorAndBindings:(NSError**)outErr, ... {
  721. va_list args;
  722. va_start(args, outErr);
  723. BOOL result = [self executeUpdate:sql error:outErr withArgumentsInArray:nil orDictionary:nil orVAList:args];
  724. va_end(args);
  725. return result;
  726. }
  727. - (BOOL)rollback {
  728. BOOL b = [self executeUpdate:@"rollback transaction"];
  729. if (b) {
  730. _inTransaction = NO;
  731. }
  732. return b;
  733. }
  734. - (BOOL)commit {
  735. BOOL b = [self executeUpdate:@"commit transaction"];
  736. if (b) {
  737. _inTransaction = NO;
  738. }
  739. return b;
  740. }
  741. - (BOOL)beginDeferredTransaction {
  742. BOOL b = [self executeUpdate:@"begin deferred transaction"];
  743. if (b) {
  744. _inTransaction = YES;
  745. }
  746. return b;
  747. }
  748. - (BOOL)beginTransaction {
  749. BOOL b = [self executeUpdate:@"begin exclusive transaction"];
  750. if (b) {
  751. _inTransaction = YES;
  752. }
  753. return b;
  754. }
  755. - (BOOL)inTransaction {
  756. return _inTransaction;
  757. }
  758. #if SQLITE_VERSION_NUMBER >= 3007000
  759. - (BOOL)startSavePointWithName:(NSString*)name error:(NSError**)outErr {
  760. // FIXME: make sure the savepoint name doesn't have a ' in it.
  761. NSParameterAssert(name);
  762. if (![self executeUpdate:[NSString stringWithFormat:@"savepoint '%@';", name]]) {
  763. if (*outErr) {
  764. *outErr = [self lastError];
  765. }
  766. return NO;
  767. }
  768. return YES;
  769. }
  770. - (BOOL)releaseSavePointWithName:(NSString*)name error:(NSError**)outErr {
  771. NSParameterAssert(name);
  772. BOOL worked = [self executeUpdate:[NSString stringWithFormat:@"release savepoint '%@';", name]];
  773. if (!worked && *outErr) {
  774. *outErr = [self lastError];
  775. }
  776. return worked;
  777. }
  778. - (BOOL)rollbackToSavePointWithName:(NSString*)name error:(NSError**)outErr {
  779. NSParameterAssert(name);
  780. BOOL worked = [self executeUpdate:[NSString stringWithFormat:@"rollback transaction to savepoint '%@';", name]];
  781. if (!worked && *outErr) {
  782. *outErr = [self lastError];
  783. }
  784. return worked;
  785. }
  786. - (NSError*)inSavePoint:(void (^)(BOOL *rollback))block {
  787. static unsigned long savePointIdx = 0;
  788. NSString *name = [NSString stringWithFormat:@"dbSavePoint%ld", savePointIdx++];
  789. BOOL shouldRollback = NO;
  790. NSError *err = 0x00;
  791. if (![self startSavePointWithName:name error:&err]) {
  792. return err;
  793. }
  794. block(&shouldRollback);
  795. if (shouldRollback) {
  796. [self rollbackToSavePointWithName:name error:&err];
  797. }
  798. else {
  799. [self releaseSavePointWithName:name error:&err];
  800. }
  801. return err;
  802. }
  803. #endif
  804. - (BOOL)shouldCacheStatements {
  805. return _shouldCacheStatements;
  806. }
  807. - (void)setShouldCacheStatements:(BOOL)value {
  808. _shouldCacheStatements = value;
  809. if (_shouldCacheStatements && !_cachedStatements) {
  810. [self setCachedStatements:[NSMutableDictionary dictionary]];
  811. }
  812. if (!_shouldCacheStatements) {
  813. [self setCachedStatements:nil];
  814. }
  815. }
  816. void FMDBBlockSQLiteCallBackFunction(sqlite3_context *context, int argc, sqlite3_value **argv);
  817. void FMDBBlockSQLiteCallBackFunction(sqlite3_context *context, int argc, sqlite3_value **argv) {
  818. #if ! __has_feature(objc_arc)
  819. void (^block)(sqlite3_context *context, int argc, sqlite3_value **argv) = (id)sqlite3_user_data(context);
  820. #else
  821. void (^block)(sqlite3_context *context, int argc, sqlite3_value **argv) = (__bridge id)sqlite3_user_data(context);
  822. #endif
  823. block(context, argc, argv);
  824. }
  825. - (void)makeFunctionNamed:(NSString*)name maximumArguments:(int)count withBlock:(void (^)(sqlite3_context *context, int argc, sqlite3_value **argv))block {
  826. if (!_openFunctions) {
  827. _openFunctions = [NSMutableSet new];
  828. }
  829. id b = FMDBReturnAutoreleased([block copy]);
  830. [_openFunctions addObject:b];
  831. /* 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. */
  832. #if ! __has_feature(objc_arc)
  833. sqlite3_create_function([self sqliteHandle], [name UTF8String], count, SQLITE_UTF8, (void*)b, &FMDBBlockSQLiteCallBackFunction, 0x00, 0x00);
  834. #else
  835. sqlite3_create_function([self sqliteHandle], [name UTF8String], count, SQLITE_UTF8, (__bridge void*)b, &FMDBBlockSQLiteCallBackFunction, 0x00, 0x00);
  836. #endif
  837. }
  838. @end
  839. @implementation FMStatement
  840. @synthesize statement=_statement;
  841. @synthesize query=_query;
  842. @synthesize useCount=_useCount;
  843. - (void)finalize {
  844. [self close];
  845. [super finalize];
  846. }
  847. - (void)dealloc {
  848. [self close];
  849. FMDBRelease(_query);
  850. #if ! __has_feature(objc_arc)
  851. [super dealloc];
  852. #endif
  853. }
  854. - (void)close {
  855. if (_statement) {
  856. sqlite3_finalize(_statement);
  857. _statement = 0x00;
  858. }
  859. }
  860. - (void)reset {
  861. if (_statement) {
  862. sqlite3_reset(_statement);
  863. }
  864. }
  865. - (NSString*)description {
  866. return [NSString stringWithFormat:@"%@ %ld hit(s) for query %@", [super description], _useCount, _query];
  867. }
  868. @end