FMDatabase.m 36 KB

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