PageRenderTime 48ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/SQLiteSample/Classes/FMDB/FMDatabase.m

https://gitlab.com/praveenvelanati/ios-demo
Objective C | 761 lines | 571 code | 176 blank | 14 comment | 137 complexity | 3bcd1892978e187dc2e861cc23ee5ae4 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. 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. #ifndef NS_BLOCK_ASSERTIONS
  137. if (crashOnErrors) {
  138. NSAssert1(false, @"The FMDatabase %@ is currently in use.", self);
  139. }
  140. #endif
  141. }
  142. - (NSString*)lastErrorMessage {
  143. return [NSString stringWithUTF8String:sqlite3_errmsg(db)];
  144. }
  145. - (BOOL)hadError {
  146. int lastErrCode = [self lastErrorCode];
  147. return (lastErrCode > SQLITE_OK && lastErrCode < SQLITE_ROW);
  148. }
  149. - (int)lastErrorCode {
  150. return sqlite3_errcode(db);
  151. }
  152. - (sqlite_int64)lastInsertRowId {
  153. if (inUse) {
  154. [self compainAboutInUse];
  155. return NO;
  156. }
  157. [self setInUse:YES];
  158. sqlite_int64 ret = sqlite3_last_insert_rowid(db);
  159. [self setInUse:NO];
  160. return ret;
  161. }
  162. - (void)bindObject:(id)obj toColumn:(int)idx inStatement:(sqlite3_stmt*)pStmt; {
  163. if ((!obj) || ((NSNull *)obj == [NSNull null])) {
  164. sqlite3_bind_null(pStmt, idx);
  165. }
  166. // FIXME - someday check the return codes on these binds.
  167. else if ([obj isKindOfClass:[NSData class]]) {
  168. sqlite3_bind_blob(pStmt, idx, [obj bytes], (int)[obj length], SQLITE_STATIC);
  169. }
  170. else if ([obj isKindOfClass:[NSDate class]]) {
  171. sqlite3_bind_double(pStmt, idx, [obj timeIntervalSince1970]);
  172. }
  173. else if ([obj isKindOfClass:[NSNumber class]]) {
  174. if (strcmp([obj objCType], @encode(BOOL)) == 0) {
  175. sqlite3_bind_int(pStmt, idx, ([obj boolValue] ? 1 : 0));
  176. }
  177. else if (strcmp([obj objCType], @encode(int)) == 0) {
  178. sqlite3_bind_int64(pStmt, idx, [obj longValue]);
  179. }
  180. else if (strcmp([obj objCType], @encode(long)) == 0) {
  181. sqlite3_bind_int64(pStmt, idx, [obj longValue]);
  182. }
  183. else if (strcmp([obj objCType], @encode(long long)) == 0) {
  184. sqlite3_bind_int64(pStmt, idx, [obj longLongValue]);
  185. }
  186. else if (strcmp([obj objCType], @encode(float)) == 0) {
  187. sqlite3_bind_double(pStmt, idx, [obj floatValue]);
  188. }
  189. else if (strcmp([obj objCType], @encode(double)) == 0) {
  190. sqlite3_bind_double(pStmt, idx, [obj doubleValue]);
  191. }
  192. else {
  193. sqlite3_bind_text(pStmt, idx, [[obj description] UTF8String], -1, SQLITE_STATIC);
  194. }
  195. }
  196. else {
  197. sqlite3_bind_text(pStmt, idx, [[obj description] UTF8String], -1, SQLITE_STATIC);
  198. }
  199. }
  200. - (FMResultSet *)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray*)arrayArgs orVAList:(va_list)args {
  201. if (inUse) {
  202. [self compainAboutInUse];
  203. return nil;
  204. }
  205. [self setInUse:YES];
  206. FMResultSet *rs = nil;
  207. int rc = 0x00;;
  208. sqlite3_stmt *pStmt = 0x00;;
  209. FMStatement *statement = 0x00;
  210. if (traceExecution && sql) {
  211. NSLog(@"%@ executeQuery: %@", self, sql);
  212. }
  213. if (shouldCacheStatements) {
  214. statement = [self cachedStatementForQuery:sql];
  215. pStmt = statement ? [statement statement] : 0x00;
  216. }
  217. int numberOfRetries = 0;
  218. BOOL retry = NO;
  219. if (!pStmt) {
  220. do {
  221. retry = NO;
  222. rc = sqlite3_prepare_v2(db, [sql UTF8String], -1, &pStmt, 0);
  223. if (SQLITE_BUSY == rc) {
  224. retry = YES;
  225. usleep(20);
  226. if (busyRetryTimeout && (numberOfRetries++ > busyRetryTimeout)) {
  227. NSLog(@"%s:%d Database busy (%@)", __FUNCTION__, __LINE__, [self databasePath]);
  228. NSLog(@"Database busy");
  229. sqlite3_finalize(pStmt);
  230. [self setInUse:NO];
  231. return nil;
  232. }
  233. }
  234. else if (SQLITE_OK != rc) {
  235. if (logsErrors) {
  236. NSLog(@"DB Error: %d \"%@\"", [self lastErrorCode], [self lastErrorMessage]);
  237. NSLog(@"DB Query: %@", sql);
  238. #ifndef NS_BLOCK_ASSERTIONS
  239. if (crashOnErrors) {
  240. NSAssert2(false, @"DB Error: %d \"%@\"", [self lastErrorCode], [self lastErrorMessage]);
  241. }
  242. #endif
  243. }
  244. sqlite3_finalize(pStmt);
  245. [self setInUse:NO];
  246. return nil;
  247. }
  248. }
  249. while (retry);
  250. }
  251. id obj;
  252. int idx = 0;
  253. int queryCount = sqlite3_bind_parameter_count(pStmt); // pointed out by Dominic Yu (thanks!)
  254. while (idx < queryCount) {
  255. if (arrayArgs) {
  256. obj = [arrayArgs objectAtIndex:idx];
  257. }
  258. else {
  259. obj = va_arg(args, id);
  260. }
  261. if (traceExecution) {
  262. NSLog(@"obj: %@", obj);
  263. }
  264. idx++;
  265. [self bindObject:obj toColumn:idx inStatement:pStmt];
  266. }
  267. if (idx != queryCount) {
  268. NSLog(@"Error: the bind count is not correct for the # of variables (executeQuery)");
  269. sqlite3_finalize(pStmt);
  270. [self setInUse:NO];
  271. return nil;
  272. }
  273. [statement retain]; // to balance the release below
  274. if (!statement) {
  275. statement = [[FMStatement alloc] init];
  276. [statement setStatement:pStmt];
  277. if (shouldCacheStatements) {
  278. [self setCachedStatement:statement forQuery:sql];
  279. }
  280. }
  281. // the statement gets close in rs's dealloc or [rs close];
  282. rs = [FMResultSet resultSetWithStatement:statement usingParentDatabase:self];
  283. [rs setQuery:sql];
  284. statement.useCount = statement.useCount + 1;
  285. [statement release];
  286. [self setInUse:NO];
  287. return rs;
  288. }
  289. - (FMResultSet *)executeQuery:(NSString*)sql, ... {
  290. va_list args;
  291. va_start(args, sql);
  292. id result = [self executeQuery:sql withArgumentsInArray:nil orVAList:args];
  293. va_end(args);
  294. return result;
  295. }
  296. - (FMResultSet *)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray *)arguments {
  297. return [self executeQuery:sql withArgumentsInArray:arguments orVAList:nil];
  298. }
  299. - (BOOL)executeUpdate:(NSString*)sql error:(NSError**)outErr withArgumentsInArray:(NSArray*)arrayArgs orVAList:(va_list)args {
  300. if (inUse) {
  301. [self compainAboutInUse];
  302. return NO;
  303. }
  304. [self setInUse:YES];
  305. int rc = 0x00;
  306. sqlite3_stmt *pStmt = 0x00;
  307. FMStatement *cachedStmt = 0x00;
  308. if (traceExecution && sql) {
  309. NSLog(@"%@ executeUpdate: %@", self, sql);
  310. }
  311. if (shouldCacheStatements) {
  312. cachedStmt = [self cachedStatementForQuery:sql];
  313. pStmt = cachedStmt ? [cachedStmt statement] : 0x00;
  314. }
  315. int numberOfRetries = 0;
  316. BOOL retry = NO;
  317. if (!pStmt) {
  318. do {
  319. retry = NO;
  320. rc = sqlite3_prepare_v2(db, [sql UTF8String], -1, &pStmt, 0);
  321. if (SQLITE_BUSY == rc) {
  322. retry = YES;
  323. usleep(20);
  324. if (busyRetryTimeout && (numberOfRetries++ > busyRetryTimeout)) {
  325. NSLog(@"%s:%d Database busy (%@)", __FUNCTION__, __LINE__, [self databasePath]);
  326. NSLog(@"Database busy");
  327. sqlite3_finalize(pStmt);
  328. [self setInUse:NO];
  329. return NO;
  330. }
  331. }
  332. else if (SQLITE_OK != rc) {
  333. if (logsErrors) {
  334. NSLog(@"DB Error: %d \"%@\"", [self lastErrorCode], [self lastErrorMessage]);
  335. NSLog(@"DB Query: %@", sql);
  336. #ifndef NS_BLOCK_ASSERTIONS
  337. if (crashOnErrors) {
  338. NSAssert2(false, @"DB Error: %d \"%@\"", [self lastErrorCode], [self lastErrorMessage]);
  339. }
  340. #endif
  341. }
  342. sqlite3_finalize(pStmt);
  343. [self setInUse:NO];
  344. if (outErr) {
  345. *outErr = [NSError errorWithDomain:[NSString stringWithUTF8String:sqlite3_errmsg(db)] code:rc userInfo:nil];
  346. }
  347. return NO;
  348. }
  349. }
  350. while (retry);
  351. }
  352. id obj;
  353. int idx = 0;
  354. int queryCount = sqlite3_bind_parameter_count(pStmt);
  355. while (idx < queryCount) {
  356. if (arrayArgs) {
  357. obj = [arrayArgs objectAtIndex:idx];
  358. }
  359. else {
  360. obj = va_arg(args, id);
  361. }
  362. if (traceExecution) {
  363. NSLog(@"obj: %@", obj);
  364. }
  365. idx++;
  366. [self bindObject:obj toColumn:idx inStatement:pStmt];
  367. }
  368. if (idx != queryCount) {
  369. NSLog(@"Error: the bind count is not correct for the # of variables (%@) (executeUpdate)", sql);
  370. sqlite3_finalize(pStmt);
  371. [self setInUse:NO];
  372. return NO;
  373. }
  374. /* Call sqlite3_step() to run the virtual machine. Since the SQL being
  375. ** executed is not a SELECT statement, we assume no data will be returned.
  376. */
  377. numberOfRetries = 0;
  378. do {
  379. rc = sqlite3_step(pStmt);
  380. retry = NO;
  381. if (SQLITE_BUSY == rc) {
  382. // this will happen if the db is locked, like if we are doing an update or insert.
  383. // in that case, retry the step... and maybe wait just 10 milliseconds.
  384. retry = YES;
  385. usleep(20);
  386. if (busyRetryTimeout && (numberOfRetries++ > busyRetryTimeout)) {
  387. NSLog(@"%s:%d Database busy (%@)", __FUNCTION__, __LINE__, [self databasePath]);
  388. NSLog(@"Database busy");
  389. retry = NO;
  390. }
  391. }
  392. else if (SQLITE_DONE == rc || SQLITE_ROW == rc) {
  393. // all is well, let's return.
  394. }
  395. else if (SQLITE_ERROR == rc) {
  396. NSLog(@"Error calling sqlite3_step (%d: %s) SQLITE_ERROR", rc, sqlite3_errmsg(db));
  397. NSLog(@"DB Query: %@", sql);
  398. }
  399. else if (SQLITE_MISUSE == rc) {
  400. // uh oh.
  401. NSLog(@"Error calling sqlite3_step (%d: %s) SQLITE_MISUSE", rc, sqlite3_errmsg(db));
  402. NSLog(@"DB Query: %@", sql);
  403. }
  404. else {
  405. // wtf?
  406. NSLog(@"Unknown error calling sqlite3_step (%d: %s) eu", rc, sqlite3_errmsg(db));
  407. NSLog(@"DB Query: %@", sql);
  408. }
  409. } while (retry);
  410. assert( rc!=SQLITE_ROW );
  411. if (shouldCacheStatements && !cachedStmt) {
  412. cachedStmt = [[FMStatement alloc] init];
  413. [cachedStmt setStatement:pStmt];
  414. [self setCachedStatement:cachedStmt forQuery:sql];
  415. [cachedStmt release];
  416. }
  417. if (cachedStmt) {
  418. cachedStmt.useCount = cachedStmt.useCount + 1;
  419. rc = sqlite3_reset(pStmt);
  420. }
  421. else {
  422. /* Finalize the virtual machine. This releases all memory and other
  423. ** resources allocated by the sqlite3_prepare() call above.
  424. */
  425. rc = sqlite3_finalize(pStmt);
  426. }
  427. [self setInUse:NO];
  428. return (rc == SQLITE_OK);
  429. }
  430. - (BOOL)executeUpdate:(NSString*)sql, ... {
  431. va_list args;
  432. va_start(args, sql);
  433. BOOL result = [self executeUpdate:sql error:nil withArgumentsInArray:nil orVAList:args];
  434. va_end(args);
  435. return result;
  436. }
  437. - (BOOL)executeUpdate:(NSString*)sql withArgumentsInArray:(NSArray *)arguments {
  438. return [self executeUpdate:sql error:nil withArgumentsInArray:arguments orVAList:nil];
  439. }
  440. - (BOOL)update:(NSString*)sql error:(NSError**)outErr bind:(id)bindArgs, ... {
  441. va_list args;
  442. va_start(args, bindArgs);
  443. BOOL result = [self executeUpdate:sql error:outErr withArgumentsInArray:nil orVAList:args];
  444. va_end(args);
  445. return result;
  446. }
  447. - (BOOL)rollback {
  448. BOOL b = [self executeUpdate:@"ROLLBACK TRANSACTION;"];
  449. if (b) {
  450. inTransaction = NO;
  451. }
  452. return b;
  453. }
  454. - (BOOL)commit {
  455. BOOL b = [self executeUpdate:@"COMMIT TRANSACTION;"];
  456. if (b) {
  457. inTransaction = NO;
  458. }
  459. return b;
  460. }
  461. - (BOOL)beginDeferredTransaction {
  462. BOOL b = [self executeUpdate:@"BEGIN DEFERRED TRANSACTION;"];
  463. if (b) {
  464. inTransaction = YES;
  465. }
  466. return b;
  467. }
  468. - (BOOL)beginTransaction {
  469. BOOL b = [self executeUpdate:@"BEGIN EXCLUSIVE TRANSACTION;"];
  470. if (b) {
  471. inTransaction = YES;
  472. }
  473. return b;
  474. }
  475. - (BOOL)logsErrors {
  476. return logsErrors;
  477. }
  478. - (void)setLogsErrors:(BOOL)flag {
  479. logsErrors = flag;
  480. }
  481. - (BOOL)crashOnErrors {
  482. return crashOnErrors;
  483. }
  484. - (void)setCrashOnErrors:(BOOL)flag {
  485. crashOnErrors = flag;
  486. }
  487. - (BOOL)inUse {
  488. return inUse || inTransaction;
  489. }
  490. - (void)setInUse:(BOOL)b {
  491. inUse = b;
  492. }
  493. - (BOOL)inTransaction {
  494. return inTransaction;
  495. }
  496. - (void)setInTransaction:(BOOL)flag {
  497. inTransaction = flag;
  498. }
  499. - (BOOL)traceExecution {
  500. return traceExecution;
  501. }
  502. - (void)setTraceExecution:(BOOL)flag {
  503. traceExecution = flag;
  504. }
  505. - (BOOL)checkedOut {
  506. return checkedOut;
  507. }
  508. - (void)setCheckedOut:(BOOL)flag {
  509. checkedOut = flag;
  510. }
  511. - (int)busyRetryTimeout {
  512. return busyRetryTimeout;
  513. }
  514. - (void)setBusyRetryTimeout:(int)newBusyRetryTimeout {
  515. busyRetryTimeout = newBusyRetryTimeout;
  516. }
  517. - (BOOL)shouldCacheStatements {
  518. return shouldCacheStatements;
  519. }
  520. - (void)setShouldCacheStatements:(BOOL)value {
  521. shouldCacheStatements = value;
  522. if (shouldCacheStatements && !cachedStatements) {
  523. [self setCachedStatements:[NSMutableDictionary dictionary]];
  524. }
  525. if (!shouldCacheStatements) {
  526. [self setCachedStatements:nil];
  527. }
  528. }
  529. - (NSMutableDictionary *) cachedStatements {
  530. return cachedStatements;
  531. }
  532. - (void)setCachedStatements:(NSMutableDictionary *)value {
  533. if (cachedStatements != value) {
  534. [cachedStatements release];
  535. cachedStatements = [value retain];
  536. }
  537. }
  538. - (int)changes {
  539. return(sqlite3_changes(db));
  540. }
  541. @end
  542. @implementation FMStatement
  543. - (void)dealloc {
  544. [self close];
  545. [query release];
  546. [super dealloc];
  547. }
  548. - (void)close {
  549. if (statement) {
  550. sqlite3_finalize(statement);
  551. statement = 0x00;
  552. }
  553. }
  554. - (void)reset {
  555. if (statement) {
  556. sqlite3_reset(statement);
  557. }
  558. }
  559. - (sqlite3_stmt *)statement {
  560. return statement;
  561. }
  562. - (void)setStatement:(sqlite3_stmt *)value {
  563. statement = value;
  564. }
  565. - (NSString *)query {
  566. return query;
  567. }
  568. - (void)setQuery:(NSString *)value {
  569. if (query != value) {
  570. [query release];
  571. query = [value retain];
  572. }
  573. }
  574. - (long)useCount {
  575. return useCount;
  576. }
  577. - (void)setUseCount:(long)value {
  578. if (useCount != value) {
  579. useCount = value;
  580. }
  581. }
  582. - (NSString*)description {
  583. return [NSString stringWithFormat:@"%@ %d hit(s) for query %@", [super description], useCount, query];
  584. }
  585. @end