FMDatabase.m 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182
  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() != 0;
  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. - (const char*)sqlitePath {
  59. if (!_databasePath) {
  60. return ":memory:";
  61. }
  62. if ([_databasePath length] == 0) {
  63. return ""; // this creates a temporary database (it's an sqlite thing).
  64. }
  65. return [_databasePath fileSystemRepresentation];
  66. }
  67. - (BOOL)open {
  68. if (_db) {
  69. return YES;
  70. }
  71. int err = sqlite3_open([self sqlitePath], &_db );
  72. if(err != SQLITE_OK) {
  73. NSLog(@"error opening!: %d", err);
  74. return NO;
  75. }
  76. return YES;
  77. }
  78. #if SQLITE_VERSION_NUMBER >= 3005000
  79. - (BOOL)openWithFlags:(int)flags {
  80. int err = sqlite3_open_v2([self sqlitePath], &_db, flags, NULL /* Name of VFS module to use */);
  81. if(err != SQLITE_OK) {
  82. NSLog(@"error opening!: %d", err);
  83. return NO;
  84. }
  85. return YES;
  86. }
  87. #endif
  88. - (BOOL)close {
  89. [self clearCachedStatements];
  90. [self closeOpenResultSets];
  91. if (!_db) {
  92. return YES;
  93. }
  94. int rc;
  95. BOOL retry;
  96. int numberOfRetries = 0;
  97. BOOL triedFinalizingOpenStatements = NO;
  98. do {
  99. retry = NO;
  100. rc = sqlite3_close(_db);
  101. if (SQLITE_BUSY == rc || SQLITE_LOCKED == rc) {
  102. retry = YES;
  103. usleep(20);
  104. if (_busyRetryTimeout && (numberOfRetries++ > _busyRetryTimeout)) {
  105. NSLog(@"%s:%d", __FUNCTION__, __LINE__);
  106. NSLog(@"Database busy, unable to close");
  107. return NO;
  108. }
  109. if (!triedFinalizingOpenStatements) {
  110. triedFinalizingOpenStatements = YES;
  111. sqlite3_stmt *pStmt;
  112. while ((pStmt = sqlite3_next_stmt(_db, 0x00)) !=0) {
  113. NSLog(@"Closing leaked statement");
  114. sqlite3_finalize(pStmt);
  115. }
  116. }
  117. }
  118. else if (SQLITE_OK != rc) {
  119. NSLog(@"error closing!: %d", rc);
  120. }
  121. }
  122. while (retry);
  123. _db = nil;
  124. return YES;
  125. }
  126. - (void)clearCachedStatements {
  127. for (FMStatement *cachedStmt in [_cachedStatements objectEnumerator]) {
  128. [cachedStmt close];
  129. }
  130. [_cachedStatements removeAllObjects];
  131. }
  132. - (BOOL)hasOpenResultSets {
  133. return [_openResultSets count] > 0;
  134. }
  135. - (void)closeOpenResultSets {
  136. //Copy the set so we don't get mutation errors
  137. NSSet *openSetCopy = FMDBReturnAutoreleased([_openResultSets copy]);
  138. for (NSValue *rsInWrappedInATastyValueMeal in openSetCopy) {
  139. FMResultSet *rs = (FMResultSet *)[rsInWrappedInATastyValueMeal pointerValue];
  140. [rs setParentDB:nil];
  141. [rs close];
  142. [_openResultSets removeObject:rsInWrappedInATastyValueMeal];
  143. }
  144. }
  145. - (void)resultSetDidClose:(FMResultSet *)resultSet {
  146. NSValue *setValue = [NSValue valueWithNonretainedObject:resultSet];
  147. [_openResultSets removeObject:setValue];
  148. }
  149. - (FMStatement*)cachedStatementForQuery:(NSString*)query {
  150. return [_cachedStatements objectForKey:query];
  151. }
  152. - (void)setCachedStatement:(FMStatement*)statement forQuery:(NSString*)query {
  153. query = [query copy]; // in case we got handed in a mutable string...
  154. [statement setQuery:query];
  155. [_cachedStatements setObject:statement forKey:query];
  156. FMDBRelease(query);
  157. }
  158. - (BOOL)rekey:(NSString*)key {
  159. NSData *keyData = [NSData dataWithBytes:(void *)[key UTF8String] length:(int)strlen([key UTF8String])];
  160. return [self rekeyWithData:keyData];
  161. }
  162. - (BOOL)rekeyWithData:(NSData *)keyData {
  163. #ifdef SQLITE_HAS_CODEC
  164. if (!keyData) {
  165. return NO;
  166. }
  167. int rc = sqlite3_rekey(_db, [keyData bytes], (int)[keyData length]);
  168. if (rc != SQLITE_OK) {
  169. NSLog(@"error on rekey: %d", rc);
  170. NSLog(@"%@", [self lastErrorMessage]);
  171. }
  172. return (rc == SQLITE_OK);
  173. #else
  174. return NO;
  175. #endif
  176. }
  177. - (BOOL)setKey:(NSString*)key {
  178. NSData *keyData = [NSData dataWithBytes:[key UTF8String] length:(int)strlen([key UTF8String])];
  179. return [self setKeyWithData:keyData];
  180. }
  181. - (BOOL)setKeyWithData:(NSData *)keyData {
  182. #ifdef SQLITE_HAS_CODEC
  183. if (!keyData) {
  184. return NO;
  185. }
  186. int rc = sqlite3_key(_db, [keyData bytes], (int)[keyData length]);
  187. return (rc == SQLITE_OK);
  188. #else
  189. return NO;
  190. #endif
  191. }
  192. - (BOOL)goodConnection {
  193. if (!_db) {
  194. return NO;
  195. }
  196. FMResultSet *rs = [self executeQuery:@"select name from sqlite_master where type='table'"];
  197. if (rs) {
  198. [rs close];
  199. return YES;
  200. }
  201. return NO;
  202. }
  203. - (void)warnInUse {
  204. NSLog(@"The FMDatabase %@ is currently in use.", self);
  205. #ifndef NS_BLOCK_ASSERTIONS
  206. if (_crashOnErrors) {
  207. NSAssert1(false, @"The FMDatabase %@ is currently in use.", self);
  208. abort();
  209. }
  210. #endif
  211. }
  212. - (BOOL)databaseExists {
  213. if (!_db) {
  214. NSLog(@"The FMDatabase %@ is not open.", self);
  215. #ifndef NS_BLOCK_ASSERTIONS
  216. if (_crashOnErrors) {
  217. NSAssert1(false, @"The FMDatabase %@ is not open.", self);
  218. abort();
  219. }
  220. #endif
  221. return NO;
  222. }
  223. return YES;
  224. }
  225. - (NSString*)lastErrorMessage {
  226. return [NSString stringWithUTF8String:sqlite3_errmsg(_db)];
  227. }
  228. - (BOOL)hadError {
  229. int lastErrCode = [self lastErrorCode];
  230. return (lastErrCode > SQLITE_OK && lastErrCode < SQLITE_ROW);
  231. }
  232. - (int)lastErrorCode {
  233. return sqlite3_errcode(_db);
  234. }
  235. - (NSError*)errorWithMessage:(NSString*)message {
  236. NSDictionary* errorMessage = [NSDictionary dictionaryWithObject:message forKey:NSLocalizedDescriptionKey];
  237. return [NSError errorWithDomain:@"FMDatabase" code:sqlite3_errcode(_db) userInfo:errorMessage];
  238. }
  239. - (NSError*)lastError {
  240. return [self errorWithMessage:[self lastErrorMessage]];
  241. }
  242. - (sqlite_int64)lastInsertRowId {
  243. if (_isExecutingStatement) {
  244. [self warnInUse];
  245. return NO;
  246. }
  247. _isExecutingStatement = YES;
  248. sqlite_int64 ret = sqlite3_last_insert_rowid(_db);
  249. _isExecutingStatement = NO;
  250. return ret;
  251. }
  252. - (int)changes {
  253. if (_isExecutingStatement) {
  254. [self warnInUse];
  255. return 0;
  256. }
  257. _isExecutingStatement = YES;
  258. int ret = sqlite3_changes(_db);
  259. _isExecutingStatement = NO;
  260. return ret;
  261. }
  262. - (void)bindObject:(id)obj toColumn:(int)idx inStatement:(sqlite3_stmt*)pStmt {
  263. if ((!obj) || ((NSNull *)obj == [NSNull null])) {
  264. sqlite3_bind_null(pStmt, idx);
  265. }
  266. // FIXME - someday check the return codes on these binds.
  267. else if ([obj isKindOfClass:[NSData class]]) {
  268. const void *bytes = [obj bytes];
  269. if (!bytes) {
  270. // it's an empty NSData object, aka [NSData data].
  271. // Don't pass a NULL pointer, or sqlite will bind a SQL null instead of a blob.
  272. bytes = "";
  273. }
  274. sqlite3_bind_blob(pStmt, idx, bytes, (int)[obj length], SQLITE_STATIC);
  275. }
  276. else if ([obj isKindOfClass:[NSDate class]]) {
  277. sqlite3_bind_double(pStmt, idx, [obj timeIntervalSince1970]);
  278. }
  279. else if ([obj isKindOfClass:[NSNumber class]]) {
  280. if (strcmp([obj objCType], @encode(BOOL)) == 0) {
  281. sqlite3_bind_int(pStmt, idx, ([obj boolValue] ? 1 : 0));
  282. }
  283. else if (strcmp([obj objCType], @encode(int)) == 0) {
  284. sqlite3_bind_int64(pStmt, idx, [obj longValue]);
  285. }
  286. else if (strcmp([obj objCType], @encode(long)) == 0) {
  287. sqlite3_bind_int64(pStmt, idx, [obj longValue]);
  288. }
  289. else if (strcmp([obj objCType], @encode(long long)) == 0) {
  290. sqlite3_bind_int64(pStmt, idx, [obj longLongValue]);
  291. }
  292. else if (strcmp([obj objCType], @encode(unsigned long long)) == 0) {
  293. sqlite3_bind_int64(pStmt, idx, (long long)[obj unsignedLongLongValue]);
  294. }
  295. else if (strcmp([obj objCType], @encode(float)) == 0) {
  296. sqlite3_bind_double(pStmt, idx, [obj floatValue]);
  297. }
  298. else if (strcmp([obj objCType], @encode(double)) == 0) {
  299. sqlite3_bind_double(pStmt, idx, [obj doubleValue]);
  300. }
  301. else {
  302. sqlite3_bind_text(pStmt, idx, [[obj description] UTF8String], -1, SQLITE_STATIC);
  303. }
  304. }
  305. else {
  306. sqlite3_bind_text(pStmt, idx, [[obj description] UTF8String], -1, SQLITE_STATIC);
  307. }
  308. }
  309. - (void)extractSQL:(NSString *)sql argumentsList:(va_list)args intoString:(NSMutableString *)cleanedSQL arguments:(NSMutableArray *)arguments {
  310. NSUInteger length = [sql length];
  311. unichar last = '\0';
  312. for (NSUInteger i = 0; i < length; ++i) {
  313. id arg = nil;
  314. unichar current = [sql characterAtIndex:i];
  315. unichar add = current;
  316. if (last == '%') {
  317. switch (current) {
  318. case '@':
  319. arg = va_arg(args, id);
  320. break;
  321. case 'c':
  322. // warning: second argument to 'va_arg' is of promotable type 'char'; this va_arg has undefined behavior because arguments will be promoted to 'int'
  323. arg = [NSString stringWithFormat:@"%c", va_arg(args, int)];
  324. break;
  325. case 's':
  326. arg = [NSString stringWithUTF8String:va_arg(args, char*)];
  327. break;
  328. case 'd':
  329. case 'D':
  330. case 'i':
  331. arg = [NSNumber numberWithInt:va_arg(args, int)];
  332. break;
  333. case 'u':
  334. case 'U':
  335. arg = [NSNumber numberWithUnsignedInt:va_arg(args, unsigned int)];
  336. break;
  337. case 'h':
  338. i++;
  339. if (i < length && [sql characterAtIndex:i] == 'i') {
  340. // warning: second argument to 'va_arg' is of promotable type 'short'; this va_arg has undefined behavior because arguments will be promoted to 'int'
  341. arg = [NSNumber numberWithShort:(short)(va_arg(args, int))];
  342. }
  343. else if (i < length && [sql characterAtIndex:i] == 'u') {
  344. // 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'
  345. arg = [NSNumber numberWithUnsignedShort:(unsigned short)(va_arg(args, uint))];
  346. }
  347. else {
  348. i--;
  349. }
  350. break;
  351. case 'q':
  352. i++;
  353. if (i < length && [sql characterAtIndex:i] == 'i') {
  354. arg = [NSNumber numberWithLongLong:va_arg(args, long long)];
  355. }
  356. else if (i < length && [sql characterAtIndex:i] == 'u') {
  357. arg = [NSNumber numberWithUnsignedLongLong:va_arg(args, unsigned long long)];
  358. }
  359. else {
  360. i--;
  361. }
  362. break;
  363. case 'f':
  364. arg = [NSNumber numberWithDouble:va_arg(args, double)];
  365. break;
  366. case 'g':
  367. // warning: second argument to 'va_arg' is of promotable type 'float'; this va_arg has undefined behavior because arguments will be promoted to 'double'
  368. arg = [NSNumber numberWithFloat:(float)(va_arg(args, double))];
  369. break;
  370. case 'l':
  371. i++;
  372. if (i < length) {
  373. unichar next = [sql characterAtIndex:i];
  374. if (next == 'l') {
  375. i++;
  376. if (i < length && [sql characterAtIndex:i] == 'd') {
  377. //%lld
  378. arg = [NSNumber numberWithLongLong:va_arg(args, long long)];
  379. }
  380. else if (i < length && [sql characterAtIndex:i] == 'u') {
  381. //%llu
  382. arg = [NSNumber numberWithUnsignedLongLong:va_arg(args, unsigned long long)];
  383. }
  384. else {
  385. i--;
  386. }
  387. }
  388. else if (next == 'd') {
  389. //%ld
  390. arg = [NSNumber numberWithLong:va_arg(args, long)];
  391. }
  392. else if (next == 'u') {
  393. //%lu
  394. arg = [NSNumber numberWithUnsignedLong:va_arg(args, unsigned long)];
  395. }
  396. else {
  397. i--;
  398. }
  399. }
  400. else {
  401. i--;
  402. }
  403. break;
  404. default:
  405. // something else that we can't interpret. just pass it on through like normal
  406. break;
  407. }
  408. }
  409. else if (current == '%') {
  410. // percent sign; skip this character
  411. add = '\0';
  412. }
  413. if (arg != nil) {
  414. [cleanedSQL appendString:@"?"];
  415. [arguments addObject:arg];
  416. }
  417. else if (add != '\0') {
  418. [cleanedSQL appendFormat:@"%C", add];
  419. }
  420. last = current;
  421. }
  422. }
  423. - (FMResultSet *)executeQuery:(NSString *)sql withParameterDictionary:(NSDictionary *)arguments {
  424. return [self executeQuery:sql withArgumentsInArray:nil orDictionary:arguments orVAList:nil];
  425. }
  426. - (FMResultSet *)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray*)arrayArgs orDictionary:(NSDictionary *)dictionaryArgs orVAList:(va_list)args {
  427. if (![self databaseExists]) {
  428. return 0x00;
  429. }
  430. if (_isExecutingStatement) {
  431. [self warnInUse];
  432. return 0x00;
  433. }
  434. _isExecutingStatement = YES;
  435. int rc = 0x00;
  436. sqlite3_stmt *pStmt = 0x00;
  437. FMStatement *statement = 0x00;
  438. FMResultSet *rs = 0x00;
  439. if (_traceExecution && sql) {
  440. NSLog(@"%@ executeQuery: %@", self, sql);
  441. }
  442. if (_shouldCacheStatements) {
  443. statement = [self cachedStatementForQuery:sql];
  444. pStmt = statement ? [statement statement] : 0x00;
  445. [statement reset];
  446. }
  447. int numberOfRetries = 0;
  448. BOOL retry = NO;
  449. if (!pStmt) {
  450. do {
  451. retry = NO;
  452. rc = sqlite3_prepare_v2(_db, [sql UTF8String], -1, &pStmt, 0);
  453. if (SQLITE_BUSY == rc || SQLITE_LOCKED == rc) {
  454. retry = YES;
  455. usleep(20);
  456. if (_busyRetryTimeout && (numberOfRetries++ > _busyRetryTimeout)) {
  457. NSLog(@"%s:%d Database busy (%@)", __FUNCTION__, __LINE__, [self databasePath]);
  458. NSLog(@"Database busy");
  459. sqlite3_finalize(pStmt);
  460. _isExecutingStatement = NO;
  461. return nil;
  462. }
  463. }
  464. else if (SQLITE_OK != rc) {
  465. if (_logsErrors) {
  466. NSLog(@"DB Error: %d \"%@\"", [self lastErrorCode], [self lastErrorMessage]);
  467. NSLog(@"DB Query: %@", sql);
  468. NSLog(@"DB Path: %@", _databasePath);
  469. #ifndef NS_BLOCK_ASSERTIONS
  470. if (_crashOnErrors) {
  471. abort();
  472. NSAssert2(false, @"DB Error: %d \"%@\"", [self lastErrorCode], [self lastErrorMessage]);
  473. }
  474. #endif
  475. }
  476. sqlite3_finalize(pStmt);
  477. _isExecutingStatement = NO;
  478. return nil;
  479. }
  480. }
  481. while (retry);
  482. }
  483. id obj;
  484. int idx = 0;
  485. int queryCount = sqlite3_bind_parameter_count(pStmt); // pointed out by Dominic Yu (thanks!)
  486. // If dictionaryArgs is passed in, that means we are using sqlite's named parameter support
  487. if (dictionaryArgs) {
  488. for (NSString *dictionaryKey in [dictionaryArgs allKeys]) {
  489. // Prefix the key with a colon.
  490. NSString *parameterName = [[NSString alloc] initWithFormat:@":%@", dictionaryKey];
  491. // Get the index for the parameter name.
  492. int namedIdx = sqlite3_bind_parameter_index(pStmt, [parameterName UTF8String]);
  493. FMDBRelease(parameterName);
  494. if (namedIdx > 0) {
  495. // Standard binding from here.
  496. [self bindObject:[dictionaryArgs objectForKey:dictionaryKey] toColumn:namedIdx inStatement:pStmt];
  497. // increment the binding count, so our check below works out
  498. idx++;
  499. }
  500. else {
  501. NSLog(@"Could not find index for %@", dictionaryKey);
  502. }
  503. }
  504. }
  505. else {
  506. while (idx < queryCount) {
  507. if (arrayArgs && idx < [arrayArgs count]) {
  508. obj = [arrayArgs objectAtIndex:(NSUInteger)idx];
  509. }
  510. else if (args) {
  511. obj = va_arg(args, id);
  512. }
  513. else {
  514. //We ran out of arguments
  515. break;
  516. }
  517. if (_traceExecution) {
  518. NSLog(@"obj: %@", obj);
  519. }
  520. idx++;
  521. [self bindObject:obj toColumn:idx inStatement:pStmt];
  522. }
  523. }
  524. if (idx != queryCount) {
  525. NSLog(@"Error: the bind count is not correct for the # of variables (executeQuery)");
  526. sqlite3_finalize(pStmt);
  527. _isExecutingStatement = NO;
  528. return nil;
  529. }
  530. FMDBRetain(statement); // to balance the release below
  531. if (!statement) {
  532. statement = [[FMStatement alloc] init];
  533. [statement setStatement:pStmt];
  534. if (_shouldCacheStatements) {
  535. [self setCachedStatement:statement forQuery:sql];
  536. }
  537. }
  538. // the statement gets closed in rs's dealloc or [rs close];
  539. rs = [FMResultSet resultSetWithStatement:statement usingParentDatabase:self];
  540. [rs setQuery:sql];
  541. NSValue *openResultSet = [NSValue valueWithNonretainedObject:rs];
  542. [_openResultSets addObject:openResultSet];
  543. [statement setUseCount:[statement useCount] + 1];
  544. FMDBRelease(statement);
  545. _isExecutingStatement = NO;
  546. return rs;
  547. }
  548. - (FMResultSet *)executeQuery:(NSString*)sql, ... {
  549. va_list args;
  550. va_start(args, sql);
  551. id result = [self executeQuery:sql withArgumentsInArray:nil orDictionary:nil orVAList:args];
  552. va_end(args);
  553. return result;
  554. }
  555. - (FMResultSet *)executeQueryWithFormat:(NSString*)format, ... {
  556. va_list args;
  557. va_start(args, format);
  558. NSMutableString *sql = [NSMutableString stringWithCapacity:[format length]];
  559. NSMutableArray *arguments = [NSMutableArray array];
  560. [self extractSQL:format argumentsList:args intoString:sql arguments:arguments];
  561. va_end(args);
  562. return [self executeQuery:sql withArgumentsInArray:arguments];
  563. }
  564. - (FMResultSet *)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray *)arguments {
  565. return [self executeQuery:sql withArgumentsInArray:arguments orDictionary:nil orVAList:nil];
  566. }
  567. - (BOOL)executeUpdate:(NSString*)sql error:(NSError**)outErr withArgumentsInArray:(NSArray*)arrayArgs orDictionary:(NSDictionary *)dictionaryArgs orVAList:(va_list)args {
  568. if (![self databaseExists]) {
  569. return NO;
  570. }
  571. if (_isExecutingStatement) {
  572. [self warnInUse];
  573. return NO;
  574. }
  575. _isExecutingStatement = YES;
  576. int rc = 0x00;
  577. sqlite3_stmt *pStmt = 0x00;
  578. FMStatement *cachedStmt = 0x00;
  579. if (_traceExecution && sql) {
  580. NSLog(@"%@ executeUpdate: %@", self, sql);
  581. }
  582. if (_shouldCacheStatements) {
  583. cachedStmt = [self cachedStatementForQuery:sql];
  584. pStmt = cachedStmt ? [cachedStmt statement] : 0x00;
  585. [cachedStmt reset];
  586. }
  587. int numberOfRetries = 0;
  588. BOOL retry = NO;
  589. if (!pStmt) {
  590. do {
  591. retry = NO;
  592. rc = sqlite3_prepare_v2(_db, [sql UTF8String], -1, &pStmt, 0);
  593. if (SQLITE_BUSY == rc || SQLITE_LOCKED == rc) {
  594. retry = YES;
  595. usleep(20);
  596. if (_busyRetryTimeout && (numberOfRetries++ > _busyRetryTimeout)) {
  597. NSLog(@"%s:%d Database busy (%@)", __FUNCTION__, __LINE__, [self databasePath]);
  598. NSLog(@"Database busy");
  599. sqlite3_finalize(pStmt);
  600. _isExecutingStatement = NO;
  601. return NO;
  602. }
  603. }
  604. else if (SQLITE_OK != rc) {
  605. if (_logsErrors) {
  606. NSLog(@"DB Error: %d \"%@\"", [self lastErrorCode], [self lastErrorMessage]);
  607. NSLog(@"DB Query: %@", sql);
  608. NSLog(@"DB Path: %@", _databasePath);
  609. #ifndef NS_BLOCK_ASSERTIONS
  610. if (_crashOnErrors) {
  611. abort();
  612. NSAssert2(false, @"DB Error: %d \"%@\"", [self lastErrorCode], [self lastErrorMessage]);
  613. }
  614. #endif
  615. }
  616. sqlite3_finalize(pStmt);
  617. if (outErr) {
  618. *outErr = [self errorWithMessage:[NSString stringWithUTF8String:sqlite3_errmsg(_db)]];
  619. }
  620. _isExecutingStatement = NO;
  621. return NO;
  622. }
  623. }
  624. while (retry);
  625. }
  626. id obj;
  627. int idx = 0;
  628. int queryCount = sqlite3_bind_parameter_count(pStmt);
  629. // If dictionaryArgs is passed in, that means we are using sqlite's named parameter support
  630. if (dictionaryArgs) {
  631. for (NSString *dictionaryKey in [dictionaryArgs allKeys]) {
  632. // Prefix the key with a colon.
  633. NSString *parameterName = [[NSString alloc] initWithFormat:@":%@", dictionaryKey];
  634. // Get the index for the parameter name.
  635. int namedIdx = sqlite3_bind_parameter_index(pStmt, [parameterName UTF8String]);
  636. FMDBRelease(parameterName);
  637. if (namedIdx > 0) {
  638. // Standard binding from here.
  639. [self bindObject:[dictionaryArgs objectForKey:dictionaryKey] toColumn:namedIdx inStatement:pStmt];
  640. // increment the binding count, so our check below works out
  641. idx++;
  642. }
  643. else {
  644. NSLog(@"Could not find index for %@", dictionaryKey);
  645. }
  646. }
  647. }
  648. else {
  649. while (idx < queryCount) {
  650. if (arrayArgs && idx < [arrayArgs count]) {
  651. obj = [arrayArgs objectAtIndex:(NSUInteger)idx];
  652. }
  653. else if (args) {
  654. obj = va_arg(args, id);
  655. }
  656. else {
  657. //We ran out of arguments
  658. break;
  659. }
  660. if (_traceExecution) {
  661. NSLog(@"obj: %@", obj);
  662. }
  663. idx++;
  664. [self bindObject:obj toColumn:idx inStatement:pStmt];
  665. }
  666. }
  667. if (idx != queryCount) {
  668. NSLog(@"Error: the bind count (%d) is not correct for the # of variables in the query (%d) (%@) (executeUpdate)", idx, queryCount, sql);
  669. sqlite3_finalize(pStmt);
  670. _isExecutingStatement = NO;
  671. return NO;
  672. }
  673. /* Call sqlite3_step() to run the virtual machine. Since the SQL being
  674. ** executed is not a SELECT statement, we assume no data will be returned.
  675. */
  676. numberOfRetries = 0;
  677. do {
  678. rc = sqlite3_step(pStmt);
  679. retry = NO;
  680. if (SQLITE_BUSY == rc || SQLITE_LOCKED == rc) {
  681. // this will happen if the db is locked, like if we are doing an update or insert.
  682. // in that case, retry the step... and maybe wait just 10 milliseconds.
  683. retry = YES;
  684. if (SQLITE_LOCKED == rc) {
  685. rc = sqlite3_reset(pStmt);
  686. if (rc != SQLITE_LOCKED) {
  687. NSLog(@"Unexpected result from sqlite3_reset (%d) eu", rc);
  688. }
  689. }
  690. usleep(20);
  691. if (_busyRetryTimeout && (numberOfRetries++ > _busyRetryTimeout)) {
  692. NSLog(@"%s:%d Database busy (%@)", __FUNCTION__, __LINE__, [self databasePath]);
  693. NSLog(@"Database busy");
  694. retry = NO;
  695. }
  696. }
  697. else if (SQLITE_DONE == rc) {
  698. // all is well, let's return.
  699. }
  700. else if (SQLITE_ERROR == rc) {
  701. NSLog(@"Error calling sqlite3_step (%d: %s) SQLITE_ERROR", rc, sqlite3_errmsg(_db));
  702. NSLog(@"DB Query: %@", sql);
  703. }
  704. else if (SQLITE_MISUSE == rc) {
  705. // uh oh.
  706. NSLog(@"Error calling sqlite3_step (%d: %s) SQLITE_MISUSE", rc, sqlite3_errmsg(_db));
  707. NSLog(@"DB Query: %@", sql);
  708. }
  709. else {
  710. // wtf?
  711. NSLog(@"Unknown error calling sqlite3_step (%d: %s) eu", rc, sqlite3_errmsg(_db));
  712. NSLog(@"DB Query: %@", sql);
  713. }
  714. } while (retry);
  715. if (rc == SQLITE_ROW) {
  716. NSAssert1(NO, @"A executeUpdate is being called with a query string '%@'", sql);
  717. }
  718. if (_shouldCacheStatements && !cachedStmt) {
  719. cachedStmt = [[FMStatement alloc] init];
  720. [cachedStmt setStatement:pStmt];
  721. [self setCachedStatement:cachedStmt forQuery:sql];
  722. FMDBRelease(cachedStmt);
  723. }
  724. int closeErrorCode;
  725. if (cachedStmt) {
  726. [cachedStmt setUseCount:[cachedStmt useCount] + 1];
  727. closeErrorCode = sqlite3_reset(pStmt);
  728. }
  729. else {
  730. /* Finalize the virtual machine. This releases all memory and other
  731. ** resources allocated by the sqlite3_prepare() call above.
  732. */
  733. closeErrorCode = sqlite3_finalize(pStmt);
  734. }
  735. if (closeErrorCode != SQLITE_OK) {
  736. NSLog(@"Unknown error finalizing or resetting statement (%d: %s)", closeErrorCode, sqlite3_errmsg(_db));
  737. NSLog(@"DB Query: %@", sql);
  738. }
  739. _isExecutingStatement = NO;
  740. return (rc == SQLITE_DONE || rc == SQLITE_OK);
  741. }
  742. - (BOOL)executeUpdate:(NSString*)sql, ... {
  743. va_list args;
  744. va_start(args, sql);
  745. BOOL result = [self executeUpdate:sql error:nil withArgumentsInArray:nil orDictionary:nil orVAList:args];
  746. va_end(args);
  747. return result;
  748. }
  749. - (BOOL)executeUpdate:(NSString*)sql withArgumentsInArray:(NSArray *)arguments {
  750. return [self executeUpdate:sql error:nil withArgumentsInArray:arguments orDictionary:nil orVAList:nil];
  751. }
  752. - (BOOL)executeUpdate:(NSString*)sql withParameterDictionary:(NSDictionary *)arguments {
  753. return [self executeUpdate:sql error:nil withArgumentsInArray:nil orDictionary:arguments orVAList:nil];
  754. }
  755. - (BOOL)executeUpdateWithFormat:(NSString*)format, ... {
  756. va_list args;
  757. va_start(args, format);
  758. NSMutableString *sql = [NSMutableString stringWithCapacity:[format length]];
  759. NSMutableArray *arguments = [NSMutableArray array];
  760. [self extractSQL:format argumentsList:args intoString:sql arguments:arguments];
  761. va_end(args);
  762. return [self executeUpdate:sql withArgumentsInArray:arguments];
  763. }
  764. - (BOOL)update:(NSString*)sql withErrorAndBindings:(NSError**)outErr, ... {
  765. va_list args;
  766. va_start(args, outErr);
  767. BOOL result = [self executeUpdate:sql error:outErr withArgumentsInArray:nil orDictionary:nil orVAList:args];
  768. va_end(args);
  769. return result;
  770. }
  771. - (BOOL)rollback {
  772. BOOL b = [self executeUpdate:@"rollback transaction"];
  773. if (b) {
  774. _inTransaction = NO;
  775. }
  776. return b;
  777. }
  778. - (BOOL)commit {
  779. BOOL b = [self executeUpdate:@"commit transaction"];
  780. if (b) {
  781. _inTransaction = NO;
  782. }
  783. return b;
  784. }
  785. - (BOOL)beginDeferredTransaction {
  786. BOOL b = [self executeUpdate:@"begin deferred transaction"];
  787. if (b) {
  788. _inTransaction = YES;
  789. }
  790. return b;
  791. }
  792. - (BOOL)beginTransaction {
  793. BOOL b = [self executeUpdate:@"begin exclusive transaction"];
  794. if (b) {
  795. _inTransaction = YES;
  796. }
  797. return b;
  798. }
  799. - (BOOL)inTransaction {
  800. return _inTransaction;
  801. }
  802. #if SQLITE_VERSION_NUMBER >= 3007000
  803. - (BOOL)startSavePointWithName:(NSString*)name error:(NSError**)outErr {
  804. // FIXME: make sure the savepoint name doesn't have a ' in it.
  805. NSParameterAssert(name);
  806. if (![self executeUpdate:[NSString stringWithFormat:@"savepoint '%@';", name]]) {
  807. if (outErr) {
  808. *outErr = [self lastError];
  809. }
  810. return NO;
  811. }
  812. return YES;
  813. }
  814. - (BOOL)releaseSavePointWithName:(NSString*)name error:(NSError**)outErr {
  815. NSParameterAssert(name);
  816. BOOL worked = [self executeUpdate:[NSString stringWithFormat:@"release savepoint '%@';", name]];
  817. if (!worked && outErr) {
  818. *outErr = [self lastError];
  819. }
  820. return worked;
  821. }
  822. - (BOOL)rollbackToSavePointWithName:(NSString*)name error:(NSError**)outErr {
  823. NSParameterAssert(name);
  824. BOOL worked = [self executeUpdate:[NSString stringWithFormat:@"rollback transaction to savepoint '%@';", name]];
  825. if (!worked && *outErr) {
  826. *outErr = [self lastError];
  827. }
  828. return worked;
  829. }
  830. - (NSError*)inSavePoint:(void (^)(BOOL *rollback))block {
  831. static unsigned long savePointIdx = 0;
  832. NSString *name = [NSString stringWithFormat:@"dbSavePoint%ld", savePointIdx++];
  833. BOOL shouldRollback = NO;
  834. NSError *err = 0x00;
  835. if (![self startSavePointWithName:name error:&err]) {
  836. return err;
  837. }
  838. block(&shouldRollback);
  839. if (shouldRollback) {
  840. [self rollbackToSavePointWithName:name error:&err];
  841. }
  842. else {
  843. [self releaseSavePointWithName:name error:&err];
  844. }
  845. return err;
  846. }
  847. #endif
  848. - (BOOL)shouldCacheStatements {
  849. return _shouldCacheStatements;
  850. }
  851. - (void)setShouldCacheStatements:(BOOL)value {
  852. _shouldCacheStatements = value;
  853. if (_shouldCacheStatements && !_cachedStatements) {
  854. [self setCachedStatements:[NSMutableDictionary dictionary]];
  855. }
  856. if (!_shouldCacheStatements) {
  857. [self setCachedStatements:nil];
  858. }
  859. }
  860. void FMDBBlockSQLiteCallBackFunction(sqlite3_context *context, int argc, sqlite3_value **argv);
  861. void FMDBBlockSQLiteCallBackFunction(sqlite3_context *context, int argc, sqlite3_value **argv) {
  862. #if ! __has_feature(objc_arc)
  863. void (^block)(sqlite3_context *context, int argc, sqlite3_value **argv) = (id)sqlite3_user_data(context);
  864. #else
  865. void (^block)(sqlite3_context *context, int argc, sqlite3_value **argv) = (__bridge id)sqlite3_user_data(context);
  866. #endif
  867. block(context, argc, argv);
  868. }
  869. - (void)makeFunctionNamed:(NSString*)name maximumArguments:(int)count withBlock:(void (^)(sqlite3_context *context, int argc, sqlite3_value **argv))block {
  870. if (!_openFunctions) {
  871. _openFunctions = [NSMutableSet new];
  872. }
  873. id b = FMDBReturnAutoreleased([block copy]);
  874. [_openFunctions addObject:b];
  875. /* 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. */
  876. #if ! __has_feature(objc_arc)
  877. sqlite3_create_function([self sqliteHandle], [name UTF8String], count, SQLITE_UTF8, (void*)b, &FMDBBlockSQLiteCallBackFunction, 0x00, 0x00);
  878. #else
  879. sqlite3_create_function([self sqliteHandle], [name UTF8String], count, SQLITE_UTF8, (__bridge void*)b, &FMDBBlockSQLiteCallBackFunction, 0x00, 0x00);
  880. #endif
  881. }
  882. @end
  883. @implementation FMStatement
  884. @synthesize statement=_statement;
  885. @synthesize query=_query;
  886. @synthesize useCount=_useCount;
  887. - (void)finalize {
  888. [self close];
  889. [super finalize];
  890. }
  891. - (void)dealloc {
  892. [self close];
  893. FMDBRelease(_query);
  894. #if ! __has_feature(objc_arc)
  895. [super dealloc];
  896. #endif
  897. }
  898. - (void)close {
  899. if (_statement) {
  900. sqlite3_finalize(_statement);
  901. _statement = 0x00;
  902. }
  903. }
  904. - (void)reset {
  905. if (_statement) {
  906. sqlite3_reset(_statement);
  907. }
  908. }
  909. - (NSString*)description {
  910. return [NSString stringWithFormat:@"%@ %ld hit(s) for query %@", [super description], _useCount, _query];
  911. }
  912. @end