FMDatabase.m 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230
  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. //NSLog(@"executeUpdate:(NSString*)sq = member_%@ %@",@"queryRoomId" ,sql);
  603. if (![self databaseExists]) {
  604. return NO;
  605. }
  606. if (_isExecutingStatement) {
  607. [self warnInUse];
  608. return NO;
  609. }
  610. _isExecutingStatement = YES;
  611. int rc = 0x00;
  612. sqlite3_stmt *pStmt = 0x00;
  613. FMStatement *cachedStmt = 0x00;
  614. if (_traceExecution && sql) {
  615. //NSLog(@"%@ executeUpdate: %@", self, sql);
  616. }
  617. if (_shouldCacheStatements) {
  618. cachedStmt = [self cachedStatementForQuery:sql];
  619. pStmt = cachedStmt ? [cachedStmt statement] : 0x00;
  620. [cachedStmt reset];
  621. }
  622. int numberOfRetries = 0;
  623. BOOL retry = NO;
  624. if (!pStmt) {
  625. do {
  626. retry = NO;
  627. rc = sqlite3_prepare_v2(_db, [sql UTF8String], -1, &pStmt, 0);
  628. if (SQLITE_BUSY == rc || SQLITE_LOCKED == rc) {
  629. retry = YES;
  630. usleep(20);
  631. if (_busyRetryTimeout && (numberOfRetries++ > _busyRetryTimeout)) {
  632. //NSLog(@"%s:%d Database busy (%@)", __FUNCTION__, __LINE__, [self databasePath]);
  633. //NSLog(@"Database busy");
  634. sqlite3_finalize(pStmt);
  635. _isExecutingStatement = NO;
  636. return NO;
  637. }
  638. }
  639. else if (SQLITE_OK != rc) {
  640. if (_logsErrors) {
  641. // NSLog(@"DB Error: %d \"%@\"", [self lastErrorCode], [self lastErrorMessage]);
  642. // NSLog(@"DB Query: %@", sql);
  643. //NSLog(@"DB Path: %@", _databasePath);
  644. #ifndef NS_BLOCK_ASSERTIONS
  645. if (_crashOnErrors) {
  646. abort();
  647. NSAssert2(false, @"DB Error: %d \"%@\"", [self lastErrorCode], [self lastErrorMessage]);
  648. }
  649. #endif
  650. }
  651. sqlite3_finalize(pStmt);
  652. if (outErr) {
  653. *outErr = [self errorWithMessage:[NSString stringWithUTF8String:sqlite3_errmsg(_db)]];
  654. }
  655. _isExecutingStatement = NO;
  656. return NO;
  657. }
  658. }
  659. while (retry);
  660. }
  661. id obj;
  662. int idx = 0;
  663. int queryCount = sqlite3_bind_parameter_count(pStmt);
  664. // If dictionaryArgs is passed in, that means we are using sqlite's named parameter support
  665. if (dictionaryArgs) {
  666. for (NSString *dictionaryKey in [dictionaryArgs allKeys]) {
  667. // Prefix the key with a colon.
  668. NSString *parameterName = [[NSString alloc] initWithFormat:@":%@", dictionaryKey];
  669. // Get the index for the parameter name.
  670. int namedIdx = sqlite3_bind_parameter_index(pStmt, [parameterName UTF8String]);
  671. FMDBRelease(parameterName);
  672. if (namedIdx > 0) {
  673. // Standard binding from here.
  674. [self bindObject:[dictionaryArgs objectForKey:dictionaryKey] toColumn:namedIdx inStatement:pStmt];
  675. // increment the binding count, so our check below works out
  676. idx++;
  677. }
  678. else {
  679. //NSLog(@"Could not find index for %@", dictionaryKey);
  680. }
  681. }
  682. }
  683. else {
  684. while (idx < queryCount) {
  685. if (arrayArgs && idx < (int)[arrayArgs count]) {
  686. obj = [arrayArgs objectAtIndex:(NSUInteger)idx];
  687. }
  688. else if (args) {
  689. obj = va_arg(args, id);
  690. }
  691. else {
  692. //We ran out of arguments
  693. break;
  694. }
  695. if (_traceExecution) {
  696. if ([obj isKindOfClass:[NSData class]]) {
  697. NSLog(@"data: %ld bytes", (unsigned long)[(NSData*)obj length]);
  698. }
  699. else {
  700. // NSLog(@"obj: %@", obj);
  701. }
  702. }
  703. idx++;
  704. [self bindObject:obj toColumn:idx inStatement:pStmt];
  705. }
  706. }
  707. if (idx != queryCount) {
  708. NSLog(@"Error: the bind count (%d) is not correct for the # of variables in the query (%d) (%@) (executeUpdate)", idx, queryCount, sql);
  709. sqlite3_finalize(pStmt);
  710. _isExecutingStatement = NO;
  711. return NO;
  712. }
  713. /* Call sqlite3_step() to run the virtual machine. Since the SQL being
  714. ** executed is not a SELECT statement, we assume no data will be returned.
  715. */
  716. numberOfRetries = 0;
  717. do {
  718. rc = sqlite3_step(pStmt);
  719. retry = NO;
  720. if (SQLITE_BUSY == rc || SQLITE_LOCKED == rc) {
  721. // this will happen if the db is locked, like if we are doing an update or insert.
  722. // in that case, retry the step... and maybe wait just 10 milliseconds.
  723. retry = YES;
  724. if (SQLITE_LOCKED == rc) {
  725. rc = sqlite3_reset(pStmt);
  726. if (rc != SQLITE_LOCKED) {
  727. // NSLog(@"Unexpected result from sqlite3_reset (%d) eu", rc);
  728. }
  729. }
  730. usleep(20);
  731. if (_busyRetryTimeout && (numberOfRetries++ > _busyRetryTimeout)) {
  732. NSLog(@"%s:%d Database busy (%@)", __FUNCTION__, __LINE__, [self databasePath]);
  733. //NSLog(@"Database busy");
  734. retry = NO;
  735. }
  736. }
  737. else if (SQLITE_DONE == rc) {
  738. // all is well, let's return.
  739. }
  740. else if (SQLITE_ERROR == rc) {
  741. NSLog(@"Error calling sqlite3_step (%d: %s) SQLITE_ERROR", rc, sqlite3_errmsg(_db));
  742. // NSLog(@"DB Query: %@", sql);
  743. }
  744. else if (SQLITE_MISUSE == rc) {
  745. // uh oh.
  746. // NSLog(@"Error calling sqlite3_step (%d: %s) SQLITE_MISUSE", rc, sqlite3_errmsg(_db));
  747. // NSLog(@"DB Query: %@", sql);
  748. }
  749. else {
  750. // wtf?
  751. // NSLog(@"Unknown error calling sqlite3_step (%d: %s) eu", rc, sqlite3_errmsg(_db));
  752. // NSLog(@"DB Query: %@", sql);
  753. }
  754. } while (retry);
  755. if (rc == SQLITE_ROW) {
  756. NSAssert1(NO, @"A executeUpdate is being called with a query string '%@'", sql);
  757. }
  758. if (_shouldCacheStatements && !cachedStmt) {
  759. cachedStmt = [[FMStatement alloc] init];
  760. [cachedStmt setStatement:pStmt];
  761. [self setCachedStatement:cachedStmt forQuery:sql];
  762. FMDBRelease(cachedStmt);
  763. }
  764. int closeErrorCode;
  765. if (cachedStmt) {
  766. [cachedStmt setUseCount:[cachedStmt useCount] + 1];
  767. closeErrorCode = sqlite3_reset(pStmt);
  768. }
  769. else {
  770. /* Finalize the virtual machine. This releases all memory and other
  771. ** resources allocated by the sqlite3_prepare() call above.
  772. */
  773. closeErrorCode = sqlite3_finalize(pStmt);
  774. }
  775. if (closeErrorCode != SQLITE_OK) {
  776. NSLog(@"Unknown error finalizing or resetting statement (%d: %s)", closeErrorCode, sqlite3_errmsg(_db));
  777. //NSLog(@"DB Query: %@", sql);
  778. }
  779. _isExecutingStatement = NO;
  780. return (rc == SQLITE_DONE || rc == SQLITE_OK);
  781. }
  782. - (BOOL)executeUpdate:(NSString*)sql, ... {
  783. va_list args;
  784. va_start(args, sql);
  785. BOOL result = [self executeUpdate:sql error:nil withArgumentsInArray:nil orDictionary:nil orVAList:args];
  786. va_end(args);
  787. return result;
  788. }
  789. - (BOOL)executeUpdate:(NSString*)sql withArgumentsInArray:(NSArray *)arguments {
  790. return [self executeUpdate:sql error:nil withArgumentsInArray:arguments orDictionary:nil orVAList:nil];
  791. }
  792. - (BOOL)executeUpdate:(NSString*)sql withParameterDictionary:(NSDictionary *)arguments {
  793. return [self executeUpdate:sql error:nil withArgumentsInArray:nil orDictionary:arguments orVAList:nil];
  794. }
  795. - (BOOL)executeUpdateWithFormat:(NSString*)format, ... {
  796. va_list args;
  797. va_start(args, format);
  798. NSMutableString *sql = [NSMutableString stringWithCapacity:[format length]];
  799. NSMutableArray *arguments = [NSMutableArray array];
  800. [self extractSQL:format argumentsList:args intoString:sql arguments:arguments];
  801. va_end(args);
  802. return [self executeUpdate:sql withArgumentsInArray:arguments];
  803. }
  804. - (BOOL)update:(NSString*)sql withErrorAndBindings:(NSError**)outErr, ... {
  805. va_list args;
  806. va_start(args, outErr);
  807. BOOL result = [self executeUpdate:sql error:outErr withArgumentsInArray:nil orDictionary:nil orVAList:args];
  808. va_end(args);
  809. return result;
  810. }
  811. - (BOOL)rollback {
  812. BOOL b = [self executeUpdate:@"rollback transaction"];
  813. if (b) {
  814. _inTransaction = NO;
  815. }
  816. return b;
  817. }
  818. - (BOOL)commit {
  819. BOOL b = [self executeUpdate:@"commit transaction"];
  820. if (b) {
  821. _inTransaction = NO;
  822. }
  823. return b;
  824. }
  825. - (BOOL)beginDeferredTransaction {
  826. BOOL b = [self executeUpdate:@"begin deferred transaction"];
  827. if (b) {
  828. _inTransaction = YES;
  829. }
  830. return b;
  831. }
  832. - (BOOL)beginTransaction {
  833. BOOL b = [self executeUpdate:@"begin exclusive transaction"];
  834. if (b) {
  835. _inTransaction = YES;
  836. }
  837. return b;
  838. }
  839. - (BOOL)inTransaction {
  840. return _inTransaction;
  841. }
  842. #if SQLITE_VERSION_NUMBER >= 3007000
  843. - (BOOL)startSavePointWithName:(NSString*)name error:(NSError**)outErr {
  844. // FIXME: make sure the savepoint name doesn't have a ' in it.
  845. NSParameterAssert(name);
  846. if (![self executeUpdate:[NSString stringWithFormat:@"savepoint '%@';", name]]) {
  847. if (outErr) {
  848. *outErr = [self lastError];
  849. }
  850. return NO;
  851. }
  852. return YES;
  853. }
  854. - (BOOL)releaseSavePointWithName:(NSString*)name error:(NSError**)outErr {
  855. NSParameterAssert(name);
  856. BOOL worked = [self executeUpdate:[NSString stringWithFormat:@"release savepoint '%@';", name]];
  857. if (!worked && outErr) {
  858. *outErr = [self lastError];
  859. }
  860. return worked;
  861. }
  862. - (BOOL)rollbackToSavePointWithName:(NSString*)name error:(NSError**)outErr {
  863. NSParameterAssert(name);
  864. BOOL worked = [self executeUpdate:[NSString stringWithFormat:@"rollback transaction to savepoint '%@';", name]];
  865. if (!worked && *outErr) {
  866. *outErr = [self lastError];
  867. }
  868. return worked;
  869. }
  870. - (NSError*)inSavePoint:(void (^)(BOOL *rollback))block {
  871. static unsigned long savePointIdx = 0;
  872. NSString *name = [NSString stringWithFormat:@"dbSavePoint%ld", savePointIdx++];
  873. BOOL shouldRollback = NO;
  874. NSError *err = 0x00;
  875. if (![self startSavePointWithName:name error:&err]) {
  876. return err;
  877. }
  878. block(&shouldRollback);
  879. if (shouldRollback) {
  880. [self rollbackToSavePointWithName:name error:&err];
  881. }
  882. else {
  883. [self releaseSavePointWithName:name error:&err];
  884. }
  885. return err;
  886. }
  887. #endif
  888. - (BOOL)shouldCacheStatements {
  889. return _shouldCacheStatements;
  890. }
  891. - (void)setShouldCacheStatements:(BOOL)value {
  892. _shouldCacheStatements = value;
  893. if (_shouldCacheStatements && !_cachedStatements) {
  894. [self setCachedStatements:[NSMutableDictionary dictionary]];
  895. }
  896. if (!_shouldCacheStatements) {
  897. [self setCachedStatements:nil];
  898. }
  899. }
  900. void FMDBBlockSQLiteCallBackFunction(sqlite3_context *context, int argc, sqlite3_value **argv);
  901. void FMDBBlockSQLiteCallBackFunction(sqlite3_context *context, int argc, sqlite3_value **argv) {
  902. #if ! __has_feature(objc_arc)
  903. void (^block)(sqlite3_context *context, int argc, sqlite3_value **argv) = (id)sqlite3_user_data(context);
  904. #else
  905. void (^block)(sqlite3_context *context, int argc, sqlite3_value **argv) = (__bridge id)sqlite3_user_data(context);
  906. #endif
  907. block(context, argc, argv);
  908. }
  909. - (void)makeFunctionNamed:(NSString*)name maximumArguments:(int)count withBlock:(void (^)(sqlite3_context *context, int argc, sqlite3_value **argv))block {
  910. if (!_openFunctions) {
  911. _openFunctions = [NSMutableSet new];
  912. }
  913. id b = FMDBReturnAutoreleased([block copy]);
  914. [_openFunctions addObject:b];
  915. /* 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. */
  916. #if ! __has_feature(objc_arc)
  917. sqlite3_create_function([self sqliteHandle], [name UTF8String], count, SQLITE_UTF8, (void*)b, &FMDBBlockSQLiteCallBackFunction, 0x00, 0x00);
  918. #else
  919. sqlite3_create_function([self sqliteHandle], [name UTF8String], count, SQLITE_UTF8, (__bridge void*)b, &FMDBBlockSQLiteCallBackFunction, 0x00, 0x00);
  920. #endif
  921. }
  922. @end
  923. @implementation FMStatement
  924. @synthesize statement=_statement;
  925. @synthesize query=_query;
  926. @synthesize useCount=_useCount;
  927. - (void)finalize {
  928. [self close];
  929. [super finalize];
  930. }
  931. - (void)dealloc {
  932. [self close];
  933. FMDBRelease(_query);
  934. #if ! __has_feature(objc_arc)
  935. [super dealloc];
  936. #endif
  937. }
  938. - (void)close {
  939. if (_statement) {
  940. sqlite3_finalize(_statement);
  941. _statement = 0x00;
  942. }
  943. }
  944. - (void)reset {
  945. if (_statement) {
  946. sqlite3_reset(_statement);
  947. }
  948. }
  949. - (NSString*)description {
  950. return [NSString stringWithFormat:@"%@ %ld hit(s) for query %@", [super description], _useCount, _query];
  951. }
  952. @end