FMDatabase.m 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885
  1. #import "FMDatabase.h"
  2. #import "unistd.h"
  3. @implementation FMDatabase
  4. @synthesize inTransaction;
  5. @synthesize cachedStatements;
  6. @synthesize logsErrors;
  7. @synthesize crashOnErrors;
  8. @synthesize busyRetryTimeout;
  9. @synthesize checkedOut;
  10. @synthesize traceExecution;
  11. + (id)databaseWithPath:(NSString*)aPath {
  12. return [[[self alloc] initWithPath:aPath] autorelease];
  13. }
  14. + (NSString*)sqliteLibVersion {
  15. return [NSString stringWithFormat:@"%s", sqlite3_libversion()];
  16. }
  17. + (BOOL)isThreadSafe {
  18. // make sure to read the sqlite headers on this guy!
  19. return sqlite3_threadsafe();
  20. }
  21. - (id)initWithPath:(NSString*)aPath {
  22. assert(sqlite3_threadsafe()); // whoa there big boy- gotta make sure sqlite it happy with what we're going to do.
  23. self = [super init];
  24. if (self) {
  25. databasePath = [aPath copy];
  26. openResultSets = [[NSMutableSet alloc] init];
  27. db = 0x00;
  28. logsErrors = 0x00;
  29. crashOnErrors = 0x00;
  30. busyRetryTimeout = 0x00;
  31. _lockQueue = dispatch_queue_create([[NSString stringWithFormat:@"fmdb.%@", self] UTF8String], NULL);
  32. }
  33. return self;
  34. }
  35. - (void)finalize {
  36. [self close];
  37. [super finalize];
  38. }
  39. - (void)dealloc {
  40. [self close];
  41. [openResultSets release];
  42. [cachedStatements release];
  43. [databasePath release];
  44. if (_lockQueue) {
  45. dispatch_release(_lockQueue);
  46. _lockQueue = 0x00;
  47. }
  48. [super dealloc];
  49. }
  50. - (void)executeLocked:(void (^)(void))aBlock {
  51. dispatch_sync(_lockQueue, aBlock);
  52. }
  53. - (NSString *)databasePath {
  54. return databasePath;
  55. }
  56. - (sqlite3*)sqliteHandle {
  57. return db;
  58. }
  59. - (BOOL)open {
  60. if (db) {
  61. return YES;
  62. }
  63. int err = sqlite3_open((databasePath ? [databasePath fileSystemRepresentation] : ":memory:"), &db );
  64. if(err != SQLITE_OK) {
  65. NSLog(@"error opening!: %d", err);
  66. return NO;
  67. }
  68. return YES;
  69. }
  70. #if SQLITE_VERSION_NUMBER >= 3005000
  71. - (BOOL)openWithFlags:(int)flags {
  72. int err = sqlite3_open_v2((databasePath ? [databasePath fileSystemRepresentation] : ":memory:"), &db, flags, NULL /* Name of VFS module to use */);
  73. if(err != SQLITE_OK) {
  74. NSLog(@"error opening!: %d", err);
  75. return NO;
  76. }
  77. return YES;
  78. }
  79. #endif
  80. - (BOOL)close {
  81. [self clearCachedStatements];
  82. [self closeOpenResultSets];
  83. if (!db) {
  84. return YES;
  85. }
  86. int rc;
  87. BOOL retry;
  88. int numberOfRetries = 0;
  89. BOOL triedFinalizingOpenStatements = NO;
  90. do {
  91. retry = NO;
  92. rc = sqlite3_close(db);
  93. if (SQLITE_BUSY == rc || SQLITE_LOCKED == rc) {
  94. retry = YES;
  95. usleep(20);
  96. if (busyRetryTimeout && (numberOfRetries++ > busyRetryTimeout)) {
  97. NSLog(@"%s:%d", __FUNCTION__, __LINE__);
  98. NSLog(@"Database busy, unable to close");
  99. return NO;
  100. }
  101. if (!triedFinalizingOpenStatements) {
  102. triedFinalizingOpenStatements = YES;
  103. sqlite3_stmt *pStmt;
  104. while ((pStmt = sqlite3_next_stmt(db, 0x00)) !=0) {
  105. NSLog(@"Closing leaked statement");
  106. sqlite3_finalize(pStmt);
  107. }
  108. }
  109. }
  110. else if (SQLITE_OK != rc) {
  111. NSLog(@"error closing!: %d", rc);
  112. }
  113. }
  114. while (retry);
  115. db = nil;
  116. return YES;
  117. }
  118. - (void)clearCachedStatements {
  119. [self executeLocked:^() {
  120. for (FMStatement *cachedStmt in [cachedStatements objectEnumerator]) {
  121. //NSLog(@"cachedStmt: '%@'", cachedStmt);
  122. [cachedStmt close];
  123. }
  124. [cachedStatements removeAllObjects];
  125. }];
  126. }
  127. - (void)closeOpenResultSets {
  128. [self executeLocked:^() {
  129. //Copy the set so we don't get mutation errors
  130. for (NSValue *rsInWrappedInATastyValueMeal in [[openResultSets copy] autorelease]) {
  131. FMResultSet *rs = (FMResultSet *)[rsInWrappedInATastyValueMeal pointerValue];
  132. [rs setParentDB:nil];
  133. [rs close];
  134. [openResultSets removeObject:rsInWrappedInATastyValueMeal];
  135. }
  136. }];
  137. }
  138. - (void)resultSetDidClose:(FMResultSet *)resultSet {
  139. NSValue *setValue = [NSValue valueWithNonretainedObject:resultSet];
  140. [self executeLocked:^() {
  141. [openResultSets removeObject:setValue];
  142. }];
  143. }
  144. - (FMStatement*)cachedStatementForQuery:(NSString*)query {
  145. return [cachedStatements objectForKey:query];
  146. }
  147. - (void)setCachedStatement:(FMStatement*)statement forQuery:(NSString*)query {
  148. //NSLog(@"setting query: %@", query);
  149. query = [query copy]; // in case we got handed in a mutable string...
  150. [statement setQuery:query];
  151. [self executeLocked:^() {
  152. [cachedStatements setObject:statement forKey:query];
  153. }];
  154. [query release];
  155. }
  156. - (BOOL)rekey:(NSString*)key {
  157. #ifdef SQLITE_HAS_CODEC
  158. if (!key) {
  159. return NO;
  160. }
  161. int rc = sqlite3_rekey(db, [key UTF8String], strlen([key UTF8String]));
  162. if (rc != SQLITE_OK) {
  163. NSLog(@"error on rekey: %d", rc);
  164. NSLog(@"%@", [self lastErrorMessage]);
  165. }
  166. return (rc == SQLITE_OK);
  167. #else
  168. return NO;
  169. #endif
  170. }
  171. - (BOOL)setKey:(NSString*)key {
  172. #ifdef SQLITE_HAS_CODEC
  173. if (!key) {
  174. return NO;
  175. }
  176. int rc = sqlite3_key(db, [key UTF8String], strlen([key UTF8String]));
  177. return (rc == SQLITE_OK);
  178. #else
  179. return NO;
  180. #endif
  181. }
  182. - (BOOL)goodConnection {
  183. if (!db) {
  184. return NO;
  185. }
  186. FMResultSet *rs = [self executeQuery:@"select name from sqlite_master where type='table'"];
  187. if (rs) {
  188. [rs close];
  189. return YES;
  190. }
  191. return NO;
  192. }
  193. - (void)warnInUse {
  194. NSLog(@"The FMDatabase %@ is currently in use.", self);
  195. #ifndef NS_BLOCK_ASSERTIONS
  196. if (crashOnErrors) {
  197. NSAssert1(false, @"The FMDatabase %@ is currently in use.", self);
  198. }
  199. #endif
  200. }
  201. - (BOOL)databaseExists {
  202. if (!db) {
  203. NSLog(@"The FMDatabase %@ is not open.", self);
  204. #ifndef NS_BLOCK_ASSERTIONS
  205. if (crashOnErrors) {
  206. NSAssert1(false, @"The FMDatabase %@ is not open.", self);
  207. }
  208. #endif
  209. return NO;
  210. }
  211. return YES;
  212. }
  213. - (NSString*)lastErrorMessage {
  214. return [NSString stringWithUTF8String:sqlite3_errmsg(db)];
  215. }
  216. - (BOOL)hadError {
  217. int lastErrCode = [self lastErrorCode];
  218. return (lastErrCode > SQLITE_OK && lastErrCode < SQLITE_ROW);
  219. }
  220. - (int)lastErrorCode {
  221. return sqlite3_errcode(db);
  222. }
  223. - (sqlite_int64)lastInsertRowId {
  224. return sqlite3_last_insert_rowid(db);
  225. }
  226. - (int)changes {
  227. return sqlite3_changes(db);
  228. }
  229. - (void)bindObject:(id)obj toColumn:(int)idx inStatement:(sqlite3_stmt*)pStmt {
  230. if ((!obj) || ((NSNull *)obj == [NSNull null])) {
  231. sqlite3_bind_null(pStmt, idx);
  232. }
  233. // FIXME - someday check the return codes on these binds.
  234. else if ([obj isKindOfClass:[NSData class]]) {
  235. sqlite3_bind_blob(pStmt, idx, [obj bytes], (int)[obj length], SQLITE_STATIC);
  236. }
  237. else if ([obj isKindOfClass:[NSDate class]]) {
  238. sqlite3_bind_double(pStmt, idx, [obj timeIntervalSince1970]);
  239. }
  240. else if ([obj isKindOfClass:[NSNumber class]]) {
  241. if (strcmp([obj objCType], @encode(BOOL)) == 0) {
  242. sqlite3_bind_int(pStmt, idx, ([obj boolValue] ? 1 : 0));
  243. }
  244. else if (strcmp([obj objCType], @encode(int)) == 0) {
  245. sqlite3_bind_int64(pStmt, idx, [obj longValue]);
  246. }
  247. else if (strcmp([obj objCType], @encode(long)) == 0) {
  248. sqlite3_bind_int64(pStmt, idx, [obj longValue]);
  249. }
  250. else if (strcmp([obj objCType], @encode(long long)) == 0) {
  251. sqlite3_bind_int64(pStmt, idx, [obj longLongValue]);
  252. }
  253. else if (strcmp([obj objCType], @encode(float)) == 0) {
  254. sqlite3_bind_double(pStmt, idx, [obj floatValue]);
  255. }
  256. else if (strcmp([obj objCType], @encode(double)) == 0) {
  257. sqlite3_bind_double(pStmt, idx, [obj doubleValue]);
  258. }
  259. else {
  260. sqlite3_bind_text(pStmt, idx, [[obj description] UTF8String], -1, SQLITE_STATIC);
  261. }
  262. }
  263. else {
  264. sqlite3_bind_text(pStmt, idx, [[obj description] UTF8String], -1, SQLITE_STATIC);
  265. }
  266. }
  267. - (void)_extractSQL:(NSString *)sql argumentsList:(va_list)args intoString:(NSMutableString *)cleanedSQL arguments:(NSMutableArray *)arguments {
  268. NSUInteger length = [sql length];
  269. unichar last = '\0';
  270. for (NSUInteger i = 0; i < length; ++i) {
  271. id arg = nil;
  272. unichar current = [sql characterAtIndex:i];
  273. unichar add = current;
  274. if (last == '%') {
  275. switch (current) {
  276. case '@':
  277. arg = va_arg(args, id); break;
  278. case 'c':
  279. arg = [NSString stringWithFormat:@"%c", va_arg(args, char)]; break;
  280. case 's':
  281. arg = [NSString stringWithUTF8String:va_arg(args, char*)]; break;
  282. case 'd':
  283. case 'D':
  284. case 'i':
  285. arg = [NSNumber numberWithInt:va_arg(args, int)]; break;
  286. case 'u':
  287. case 'U':
  288. arg = [NSNumber numberWithUnsignedInt:va_arg(args, unsigned int)]; break;
  289. case 'h':
  290. i++;
  291. if (i < length && [sql characterAtIndex:i] == 'i') {
  292. arg = [NSNumber numberWithShort:va_arg(args, short)];
  293. }
  294. else if (i < length && [sql characterAtIndex:i] == 'u') {
  295. arg = [NSNumber numberWithUnsignedShort:va_arg(args, unsigned short)];
  296. }
  297. else {
  298. i--;
  299. }
  300. break;
  301. case 'q':
  302. i++;
  303. if (i < length && [sql characterAtIndex:i] == 'i') {
  304. arg = [NSNumber numberWithLongLong:va_arg(args, long long)];
  305. }
  306. else if (i < length && [sql characterAtIndex:i] == 'u') {
  307. arg = [NSNumber numberWithUnsignedLongLong:va_arg(args, unsigned long long)];
  308. }
  309. else {
  310. i--;
  311. }
  312. break;
  313. case 'f':
  314. arg = [NSNumber numberWithDouble:va_arg(args, double)]; break;
  315. case 'g':
  316. arg = [NSNumber numberWithFloat:va_arg(args, float)]; break;
  317. case 'l':
  318. i++;
  319. if (i < length) {
  320. unichar next = [sql characterAtIndex:i];
  321. if (next == 'l') {
  322. i++;
  323. if (i < length && [sql characterAtIndex:i] == 'd') {
  324. //%lld
  325. arg = [NSNumber numberWithLongLong:va_arg(args, long long)];
  326. }
  327. else if (i < length && [sql characterAtIndex:i] == 'u') {
  328. //%llu
  329. arg = [NSNumber numberWithUnsignedLongLong:va_arg(args, unsigned long long)];
  330. }
  331. else {
  332. i--;
  333. }
  334. }
  335. else if (next == 'd') {
  336. //%ld
  337. arg = [NSNumber numberWithLong:va_arg(args, long)];
  338. }
  339. else if (next == 'u') {
  340. //%lu
  341. arg = [NSNumber numberWithUnsignedLong:va_arg(args, unsigned long)];
  342. }
  343. else {
  344. i--;
  345. }
  346. }
  347. else {
  348. i--;
  349. }
  350. break;
  351. default:
  352. // something else that we can't interpret. just pass it on through like normal
  353. break;
  354. }
  355. }
  356. else if (current == '%') {
  357. // percent sign; skip this character
  358. add = '\0';
  359. }
  360. if (arg != nil) {
  361. [cleanedSQL appendString:@"?"];
  362. [arguments addObject:arg];
  363. }
  364. else if (add != '\0') {
  365. [cleanedSQL appendFormat:@"%C", add];
  366. }
  367. last = current;
  368. }
  369. }
  370. - (FMResultSet *)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray*)arrayArgs orVAList:(va_list)args {
  371. if (![self databaseExists]) {
  372. return 0x00;
  373. }
  374. int rc = 0x00;
  375. sqlite3_stmt *pStmt = 0x00;
  376. FMStatement *statement = 0x00;
  377. FMResultSet *rs = 0x00;
  378. if (traceExecution && sql) {
  379. NSLog(@"%@ executeQuery: %@", self, sql);
  380. }
  381. if (shouldCacheStatements) {
  382. statement = [self cachedStatementForQuery:sql];
  383. pStmt = statement ? [statement statement] : 0x00;
  384. }
  385. int numberOfRetries = 0;
  386. BOOL retry = NO;
  387. if (!pStmt) {
  388. do {
  389. retry = NO;
  390. rc = sqlite3_prepare_v2(db, [sql UTF8String], -1, &pStmt, 0);
  391. if (SQLITE_BUSY == rc || SQLITE_LOCKED == rc) {
  392. retry = YES;
  393. usleep(20);
  394. if (busyRetryTimeout && (numberOfRetries++ > busyRetryTimeout)) {
  395. NSLog(@"%s:%d Database busy (%@)", __FUNCTION__, __LINE__, [self databasePath]);
  396. NSLog(@"Database busy");
  397. sqlite3_finalize(pStmt);
  398. return nil;
  399. }
  400. }
  401. else if (SQLITE_OK != rc) {
  402. if (logsErrors) {
  403. NSLog(@"DB Error: %d \"%@\"", [self lastErrorCode], [self lastErrorMessage]);
  404. NSLog(@"DB Query: %@", sql);
  405. #ifndef NS_BLOCK_ASSERTIONS
  406. if (crashOnErrors) {
  407. NSAssert2(false, @"DB Error: %d \"%@\"", [self lastErrorCode], [self lastErrorMessage]);
  408. }
  409. #endif
  410. }
  411. sqlite3_finalize(pStmt);
  412. return nil;
  413. }
  414. }
  415. while (retry);
  416. }
  417. id obj;
  418. int idx = 0;
  419. int queryCount = sqlite3_bind_parameter_count(pStmt); // pointed out by Dominic Yu (thanks!)
  420. while (idx < queryCount) {
  421. if (arrayArgs) {
  422. obj = [arrayArgs objectAtIndex:idx];
  423. }
  424. else {
  425. obj = va_arg(args, id);
  426. }
  427. if (traceExecution) {
  428. NSLog(@"obj: %@", obj);
  429. }
  430. idx++;
  431. [self bindObject:obj toColumn:idx inStatement:pStmt];
  432. }
  433. if (idx != queryCount) {
  434. NSLog(@"Error: the bind count is not correct for the # of variables (executeQuery)");
  435. sqlite3_finalize(pStmt);
  436. return nil;
  437. }
  438. [statement retain]; // to balance the release below
  439. if (!statement) {
  440. statement = [[FMStatement alloc] init];
  441. [statement setStatement:pStmt];
  442. if (shouldCacheStatements) {
  443. [self setCachedStatement:statement forQuery:sql];
  444. }
  445. }
  446. // the statement gets closed in rs's dealloc or [rs close];
  447. rs = [FMResultSet resultSetWithStatement:statement usingParentDatabase:self];
  448. [rs setQuery:sql];
  449. NSValue *openResultSet = [NSValue valueWithNonretainedObject:rs];
  450. [openResultSets addObject:openResultSet];
  451. [statement setUseCount:[statement useCount] + 1];
  452. [statement release];
  453. return rs;
  454. }
  455. - (FMResultSet *)executeQuery:(NSString*)sql, ... {
  456. va_list args;
  457. va_start(args, sql);
  458. id result = [self executeQuery:sql withArgumentsInArray:nil orVAList:args];
  459. va_end(args);
  460. return result;
  461. }
  462. - (FMResultSet *)executeQueryWithFormat:(NSString*)format, ... {
  463. va_list args;
  464. va_start(args, format);
  465. NSMutableString *sql = [NSMutableString stringWithCapacity:[format length]];
  466. NSMutableArray *arguments = [NSMutableArray array];
  467. [self _extractSQL:format argumentsList:args intoString:sql arguments:arguments];
  468. va_end(args);
  469. return [self executeQuery:sql withArgumentsInArray:arguments];
  470. }
  471. - (FMResultSet *)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray *)arguments {
  472. return [self executeQuery:sql withArgumentsInArray:arguments orVAList:nil];
  473. }
  474. - (BOOL)executeUpdate:(NSString*)sql error:(NSError**)outErr withArgumentsInArray:(NSArray*)arrayArgs orVAList:(va_list)args {
  475. if (![self databaseExists]) {
  476. return NO;
  477. }
  478. int rc = 0x00;
  479. sqlite3_stmt *pStmt = 0x00;
  480. FMStatement *cachedStmt = 0x00;
  481. if (traceExecution && sql) {
  482. NSLog(@"%@ executeUpdate: %@", self, sql);
  483. }
  484. if (shouldCacheStatements) {
  485. cachedStmt = [self cachedStatementForQuery:sql];
  486. pStmt = cachedStmt ? [cachedStmt statement] : 0x00;
  487. }
  488. int numberOfRetries = 0;
  489. BOOL retry = NO;
  490. if (!pStmt) {
  491. do {
  492. retry = NO;
  493. rc = sqlite3_prepare_v2(db, [sql UTF8String], -1, &pStmt, 0);
  494. if (SQLITE_BUSY == rc || SQLITE_LOCKED == rc) {
  495. retry = YES;
  496. usleep(20);
  497. if (busyRetryTimeout && (numberOfRetries++ > busyRetryTimeout)) {
  498. NSLog(@"%s:%d Database busy (%@)", __FUNCTION__, __LINE__, [self databasePath]);
  499. NSLog(@"Database busy");
  500. sqlite3_finalize(pStmt);
  501. return NO;
  502. }
  503. }
  504. else if (SQLITE_OK != rc) {
  505. if (logsErrors) {
  506. NSLog(@"DB Error: %d \"%@\"", [self lastErrorCode], [self lastErrorMessage]);
  507. NSLog(@"DB Query: %@", sql);
  508. #ifndef NS_BLOCK_ASSERTIONS
  509. if (crashOnErrors) {
  510. NSAssert2(false, @"DB Error: %d \"%@\"", [self lastErrorCode], [self lastErrorMessage]);
  511. }
  512. #endif
  513. }
  514. sqlite3_finalize(pStmt);
  515. if (outErr) {
  516. *outErr = [NSError errorWithDomain:[NSString stringWithUTF8String:sqlite3_errmsg(db)] code:rc userInfo:nil];
  517. }
  518. return NO;
  519. }
  520. }
  521. while (retry);
  522. }
  523. id obj;
  524. int idx = 0;
  525. int queryCount = sqlite3_bind_parameter_count(pStmt);
  526. while (idx < queryCount) {
  527. if (arrayArgs) {
  528. obj = [arrayArgs objectAtIndex:idx];
  529. }
  530. else {
  531. obj = va_arg(args, id);
  532. }
  533. if (traceExecution) {
  534. NSLog(@"obj: %@", obj);
  535. }
  536. idx++;
  537. [self bindObject:obj toColumn:idx inStatement:pStmt];
  538. }
  539. if (idx != queryCount) {
  540. NSLog(@"Error: the bind count is not correct for the # of variables (%@) (executeUpdate)", sql);
  541. sqlite3_finalize(pStmt);
  542. return NO;
  543. }
  544. /* Call sqlite3_step() to run the virtual machine. Since the SQL being
  545. ** executed is not a SELECT statement, we assume no data will be returned.
  546. */
  547. numberOfRetries = 0;
  548. do {
  549. rc = sqlite3_step(pStmt);
  550. retry = NO;
  551. if (SQLITE_BUSY == rc || SQLITE_LOCKED == rc) {
  552. // this will happen if the db is locked, like if we are doing an update or insert.
  553. // in that case, retry the step... and maybe wait just 10 milliseconds.
  554. retry = YES;
  555. if (SQLITE_LOCKED == rc) {
  556. rc = sqlite3_reset(pStmt);
  557. if (rc != SQLITE_LOCKED) {
  558. NSLog(@"Unexpected result from sqlite3_reset (%d) eu", rc);
  559. }
  560. }
  561. usleep(20);
  562. if (busyRetryTimeout && (numberOfRetries++ > busyRetryTimeout)) {
  563. NSLog(@"%s:%d Database busy (%@)", __FUNCTION__, __LINE__, [self databasePath]);
  564. NSLog(@"Database busy");
  565. retry = NO;
  566. }
  567. }
  568. else if (SQLITE_DONE == rc || SQLITE_ROW == rc) {
  569. // all is well, let's return.
  570. }
  571. else if (SQLITE_ERROR == rc) {
  572. NSLog(@"Error calling sqlite3_step (%d: %s) SQLITE_ERROR", rc, sqlite3_errmsg(db));
  573. NSLog(@"DB Query: %@", sql);
  574. }
  575. else if (SQLITE_MISUSE == rc) {
  576. // uh oh.
  577. NSLog(@"Error calling sqlite3_step (%d: %s) SQLITE_MISUSE", rc, sqlite3_errmsg(db));
  578. NSLog(@"DB Query: %@", sql);
  579. }
  580. else {
  581. // wtf?
  582. NSLog(@"Unknown error calling sqlite3_step (%d: %s) eu", rc, sqlite3_errmsg(db));
  583. NSLog(@"DB Query: %@", sql);
  584. }
  585. } while (retry);
  586. assert( rc!=SQLITE_ROW );
  587. if (shouldCacheStatements && !cachedStmt) {
  588. cachedStmt = [[FMStatement alloc] init];
  589. [cachedStmt setStatement:pStmt];
  590. [self setCachedStatement:cachedStmt forQuery:sql];
  591. [cachedStmt release];
  592. }
  593. if (cachedStmt) {
  594. [cachedStmt setUseCount:[cachedStmt useCount] + 1];
  595. rc = sqlite3_reset(pStmt);
  596. }
  597. else {
  598. /* Finalize the virtual machine. This releases all memory and other
  599. ** resources allocated by the sqlite3_prepare() call above.
  600. */
  601. rc = sqlite3_finalize(pStmt);
  602. }
  603. return (rc == SQLITE_OK);
  604. }
  605. - (BOOL)executeUpdate:(NSString*)sql, ... {
  606. va_list args;
  607. va_start(args, sql);
  608. BOOL result = [self executeUpdate:sql error:nil withArgumentsInArray:nil orVAList:args];
  609. va_end(args);
  610. return result;
  611. }
  612. - (BOOL)executeUpdate:(NSString*)sql withArgumentsInArray:(NSArray *)arguments {
  613. return [self executeUpdate:sql error:nil withArgumentsInArray:arguments orVAList:nil];
  614. }
  615. - (BOOL)executeUpdateWithFormat:(NSString*)format, ... {
  616. va_list args;
  617. va_start(args, format);
  618. NSMutableString *sql = [NSMutableString stringWithCapacity:[format length]];
  619. NSMutableArray *arguments = [NSMutableArray array];
  620. [self _extractSQL:format argumentsList:args intoString:sql arguments:arguments];
  621. va_end(args);
  622. return [self executeUpdate:sql withArgumentsInArray:arguments];
  623. }
  624. - (BOOL)update:(NSString*)sql error:(NSError**)outErr bind:(id)bindArgs, ... {
  625. va_list args;
  626. va_start(args, bindArgs);
  627. BOOL result = [self executeUpdate:sql error:outErr withArgumentsInArray:nil orVAList:args];
  628. va_end(args);
  629. return result;
  630. }
  631. - (BOOL)rollback {
  632. BOOL b = [self executeUpdate:@"ROLLBACK TRANSACTION;"];
  633. if (b) {
  634. inTransaction = NO;
  635. }
  636. return b;
  637. }
  638. - (BOOL)commit {
  639. BOOL b = [self executeUpdate:@"COMMIT TRANSACTION;"];
  640. if (b) {
  641. inTransaction = NO;
  642. }
  643. return b;
  644. }
  645. - (BOOL)beginDeferredTransaction {
  646. BOOL b = [self executeUpdate:@"BEGIN DEFERRED TRANSACTION;"];
  647. if (b) {
  648. inTransaction = YES;
  649. }
  650. return b;
  651. }
  652. - (BOOL)beginTransaction {
  653. BOOL b = [self executeUpdate:@"BEGIN EXCLUSIVE TRANSACTION;"];
  654. if (b) {
  655. inTransaction = YES;
  656. }
  657. return b;
  658. }
  659. - (BOOL)shouldCacheStatements {
  660. return shouldCacheStatements;
  661. }
  662. - (void)setShouldCacheStatements:(BOOL)value {
  663. shouldCacheStatements = value;
  664. if (shouldCacheStatements && !cachedStatements) {
  665. [self setCachedStatements:[NSMutableDictionary dictionary]];
  666. }
  667. if (!shouldCacheStatements) {
  668. [self setCachedStatements:nil];
  669. }
  670. }
  671. @end
  672. @implementation FMStatement
  673. @synthesize statement;
  674. @synthesize query;
  675. @synthesize useCount;
  676. - (void)finalize {
  677. [self close];
  678. [super finalize];
  679. }
  680. - (void)dealloc {
  681. [self close];
  682. [query release];
  683. [super dealloc];
  684. }
  685. - (void)close {
  686. if (statement) {
  687. sqlite3_finalize(statement);
  688. statement = 0x00;
  689. }
  690. }
  691. - (void)reset {
  692. if (statement) {
  693. sqlite3_reset(statement);
  694. }
  695. }
  696. - (NSString*)description {
  697. return [NSString stringWithFormat:@"%@ %d hit(s) for query %@", [super description], useCount, query];
  698. }
  699. @end