/fmdb/FMDatabase.m

http://github.com/petewarden/iPhoneTracker · Objective C · 815 lines · 615 code · 185 blank · 15 comment · 152 complexity · f9f130231a76d62b57bfad5f160f6dd7 MD5 · raw file

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