FMDatabase.m 50 KB

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