FMDatabase.m 36 KB

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