FMDatabase.m 42 KB

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