FMDatabase.m 18 KB

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