FMDatabase.m 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670
  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.4";
  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. query = [query copy]; // in case we got handed in a mutable string...
  291. [statement setQuery:query];
  292. NSMutableSet* statements = [_cachedStatements objectForKey:query];
  293. if (!statements) {
  294. statements = [NSMutableSet set];
  295. }
  296. [statements addObject:statement];
  297. [_cachedStatements setObject:statements forKey:query];
  298. FMDBRelease(query);
  299. }
  300. #pragma mark Key routines
  301. - (BOOL)rekey:(NSString*)key {
  302. NSData *keyData = [NSData dataWithBytes:(void *)[key UTF8String] length:(NSUInteger)strlen([key UTF8String])];
  303. return [self rekeyWithData:keyData];
  304. }
  305. - (BOOL)rekeyWithData:(NSData *)keyData {
  306. #ifdef SQLITE_HAS_CODEC
  307. if (!keyData) {
  308. return NO;
  309. }
  310. int rc = sqlite3_rekey(_db, [keyData bytes], (int)[keyData length]);
  311. if (rc != SQLITE_OK) {
  312. NSLog(@"error on rekey: %d", rc);
  313. NSLog(@"%@", [self lastErrorMessage]);
  314. }
  315. return (rc == SQLITE_OK);
  316. #else
  317. #pragma unused(keyData)
  318. return NO;
  319. #endif
  320. }
  321. - (BOOL)setKey:(NSString*)key {
  322. NSData *keyData = [NSData dataWithBytes:[key UTF8String] length:(NSUInteger)strlen([key UTF8String])];
  323. return [self setKeyWithData:keyData];
  324. }
  325. - (BOOL)setKeyWithData:(NSData *)keyData {
  326. #ifdef SQLITE_HAS_CODEC
  327. if (!keyData) {
  328. return NO;
  329. }
  330. int rc = sqlite3_key(_db, [keyData bytes], (int)[keyData length]);
  331. return (rc == SQLITE_OK);
  332. #else
  333. #pragma unused(keyData)
  334. return NO;
  335. #endif
  336. }
  337. #pragma mark Date routines
  338. + (NSDateFormatter *)storeableDateFormat:(NSString *)format {
  339. NSDateFormatter *result = FMDBReturnAutoreleased([[NSDateFormatter alloc] init]);
  340. result.dateFormat = format;
  341. result.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
  342. result.locale = FMDBReturnAutoreleased([[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]);
  343. return result;
  344. }
  345. - (BOOL)hasDateFormatter {
  346. return _dateFormat != nil;
  347. }
  348. - (void)setDateFormat:(NSDateFormatter *)format {
  349. FMDBAutorelease(_dateFormat);
  350. _dateFormat = FMDBReturnRetained(format);
  351. }
  352. - (NSDate *)dateFromString:(NSString *)s {
  353. return [_dateFormat dateFromString:s];
  354. }
  355. - (NSString *)stringFromDate:(NSDate *)date {
  356. return [_dateFormat stringFromDate:date];
  357. }
  358. #pragma mark State of database
  359. - (BOOL)goodConnection {
  360. if (!_isOpen) {
  361. return NO;
  362. }
  363. FMResultSet *rs = [self executeQuery:@"select name from sqlite_master where type='table'"];
  364. if (rs) {
  365. [rs close];
  366. return YES;
  367. }
  368. return NO;
  369. }
  370. - (void)warnInUse {
  371. NSLog(@"The FMDatabase %@ is currently in use.", self);
  372. #ifndef NS_BLOCK_ASSERTIONS
  373. if (_crashOnErrors) {
  374. NSAssert(false, @"The FMDatabase %@ is currently in use.", self);
  375. abort();
  376. }
  377. #endif
  378. }
  379. - (BOOL)databaseExists {
  380. if (!_isOpen) {
  381. NSLog(@"The FMDatabase %@ is not open.", self);
  382. #ifndef NS_BLOCK_ASSERTIONS
  383. if (_crashOnErrors) {
  384. NSAssert(false, @"The FMDatabase %@ is not open.", self);
  385. abort();
  386. }
  387. #endif
  388. return NO;
  389. }
  390. return YES;
  391. }
  392. #pragma mark Error routines
  393. - (NSString *)lastErrorMessage {
  394. return [NSString stringWithUTF8String:sqlite3_errmsg(_db)];
  395. }
  396. - (BOOL)hadError {
  397. int lastErrCode = [self lastErrorCode];
  398. return (lastErrCode > SQLITE_OK && lastErrCode < SQLITE_ROW);
  399. }
  400. - (int)lastErrorCode {
  401. return sqlite3_errcode(_db);
  402. }
  403. - (int)lastExtendedErrorCode {
  404. return sqlite3_extended_errcode(_db);
  405. }
  406. - (NSError*)errorWithMessage:(NSString *)message {
  407. NSDictionary* errorMessage = [NSDictionary dictionaryWithObject:message forKey:NSLocalizedDescriptionKey];
  408. return [NSError errorWithDomain:@"FMDatabase" code:sqlite3_errcode(_db) userInfo:errorMessage];
  409. }
  410. - (NSError*)lastError {
  411. return [self errorWithMessage:[self lastErrorMessage]];
  412. }
  413. #pragma mark Update information routines
  414. - (sqlite_int64)lastInsertRowId {
  415. if (_isExecutingStatement) {
  416. [self warnInUse];
  417. return NO;
  418. }
  419. _isExecutingStatement = YES;
  420. sqlite_int64 ret = sqlite3_last_insert_rowid(_db);
  421. _isExecutingStatement = NO;
  422. return ret;
  423. }
  424. - (int)changes {
  425. if (_isExecutingStatement) {
  426. [self warnInUse];
  427. return 0;
  428. }
  429. _isExecutingStatement = YES;
  430. int ret = sqlite3_changes(_db);
  431. _isExecutingStatement = NO;
  432. return ret;
  433. }
  434. #pragma mark SQL manipulation
  435. - (void)bindObject:(id)obj toColumn:(int)idx inStatement:(sqlite3_stmt*)pStmt {
  436. if ((!obj) || ((NSNull *)obj == [NSNull null])) {
  437. sqlite3_bind_null(pStmt, idx);
  438. }
  439. // FIXME - someday check the return codes on these binds.
  440. else if ([obj isKindOfClass:[NSData class]]) {
  441. const void *bytes = [obj bytes];
  442. if (!bytes) {
  443. // it's an empty NSData object, aka [NSData data].
  444. // Don't pass a NULL pointer, or sqlite will bind a SQL null instead of a blob.
  445. bytes = "";
  446. }
  447. sqlite3_bind_blob(pStmt, idx, bytes, (int)[obj length], SQLITE_STATIC);
  448. }
  449. else if ([obj isKindOfClass:[NSDate class]]) {
  450. if (self.hasDateFormatter)
  451. sqlite3_bind_text(pStmt, idx, [[self stringFromDate:obj] UTF8String], -1, SQLITE_STATIC);
  452. else
  453. sqlite3_bind_double(pStmt, idx, [obj timeIntervalSince1970]);
  454. }
  455. else if ([obj isKindOfClass:[NSNumber class]]) {
  456. if (strcmp([obj objCType], @encode(char)) == 0) {
  457. sqlite3_bind_int(pStmt, idx, [obj charValue]);
  458. }
  459. else if (strcmp([obj objCType], @encode(unsigned char)) == 0) {
  460. sqlite3_bind_int(pStmt, idx, [obj unsignedCharValue]);
  461. }
  462. else if (strcmp([obj objCType], @encode(short)) == 0) {
  463. sqlite3_bind_int(pStmt, idx, [obj shortValue]);
  464. }
  465. else if (strcmp([obj objCType], @encode(unsigned short)) == 0) {
  466. sqlite3_bind_int(pStmt, idx, [obj unsignedShortValue]);
  467. }
  468. else if (strcmp([obj objCType], @encode(int)) == 0) {
  469. sqlite3_bind_int(pStmt, idx, [obj intValue]);
  470. }
  471. else if (strcmp([obj objCType], @encode(unsigned int)) == 0) {
  472. sqlite3_bind_int64(pStmt, idx, (long long)[obj unsignedIntValue]);
  473. }
  474. else if (strcmp([obj objCType], @encode(long)) == 0) {
  475. sqlite3_bind_int64(pStmt, idx, [obj longValue]);
  476. }
  477. else if (strcmp([obj objCType], @encode(unsigned long)) == 0) {
  478. sqlite3_bind_int64(pStmt, idx, (long long)[obj unsignedLongValue]);
  479. }
  480. else if (strcmp([obj objCType], @encode(long long)) == 0) {
  481. sqlite3_bind_int64(pStmt, idx, [obj longLongValue]);
  482. }
  483. else if (strcmp([obj objCType], @encode(unsigned long long)) == 0) {
  484. sqlite3_bind_int64(pStmt, idx, (long long)[obj unsignedLongLongValue]);
  485. }
  486. else if (strcmp([obj objCType], @encode(float)) == 0) {
  487. sqlite3_bind_double(pStmt, idx, [obj floatValue]);
  488. }
  489. else if (strcmp([obj objCType], @encode(double)) == 0) {
  490. sqlite3_bind_double(pStmt, idx, [obj doubleValue]);
  491. }
  492. else if (strcmp([obj objCType], @encode(BOOL)) == 0) {
  493. sqlite3_bind_int(pStmt, idx, ([obj boolValue] ? 1 : 0));
  494. }
  495. else {
  496. sqlite3_bind_text(pStmt, idx, [[obj description] UTF8String], -1, SQLITE_STATIC);
  497. }
  498. }
  499. else {
  500. sqlite3_bind_text(pStmt, idx, [[obj description] UTF8String], -1, SQLITE_STATIC);
  501. }
  502. }
  503. - (void)extractSQL:(NSString *)sql argumentsList:(va_list)args intoString:(NSMutableString *)cleanedSQL arguments:(NSMutableArray *)arguments {
  504. NSUInteger length = [sql length];
  505. unichar last = '\0';
  506. for (NSUInteger i = 0; i < length; ++i) {
  507. id arg = nil;
  508. unichar current = [sql characterAtIndex:i];
  509. unichar add = current;
  510. if (last == '%') {
  511. switch (current) {
  512. case '@':
  513. arg = va_arg(args, id);
  514. break;
  515. case 'c':
  516. // warning: second argument to 'va_arg' is of promotable type 'char'; this va_arg has undefined behavior because arguments will be promoted to 'int'
  517. arg = [NSString stringWithFormat:@"%c", va_arg(args, int)];
  518. break;
  519. case 's':
  520. arg = [NSString stringWithUTF8String:va_arg(args, char*)];
  521. break;
  522. case 'd':
  523. case 'D':
  524. case 'i':
  525. arg = [NSNumber numberWithInt:va_arg(args, int)];
  526. break;
  527. case 'u':
  528. case 'U':
  529. arg = [NSNumber numberWithUnsignedInt:va_arg(args, unsigned int)];
  530. break;
  531. case 'h':
  532. i++;
  533. if (i < length && [sql characterAtIndex:i] == 'i') {
  534. // warning: second argument to 'va_arg' is of promotable type 'short'; this va_arg has undefined behavior because arguments will be promoted to 'int'
  535. arg = [NSNumber numberWithShort:(short)(va_arg(args, int))];
  536. }
  537. else if (i < length && [sql characterAtIndex:i] == 'u') {
  538. // 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'
  539. arg = [NSNumber numberWithUnsignedShort:(unsigned short)(va_arg(args, uint))];
  540. }
  541. else {
  542. i--;
  543. }
  544. break;
  545. case 'q':
  546. i++;
  547. if (i < length && [sql characterAtIndex:i] == 'i') {
  548. arg = [NSNumber numberWithLongLong:va_arg(args, long long)];
  549. }
  550. else if (i < length && [sql characterAtIndex:i] == 'u') {
  551. arg = [NSNumber numberWithUnsignedLongLong:va_arg(args, unsigned long long)];
  552. }
  553. else {
  554. i--;
  555. }
  556. break;
  557. case 'f':
  558. arg = [NSNumber numberWithDouble:va_arg(args, double)];
  559. break;
  560. case 'g':
  561. // warning: second argument to 'va_arg' is of promotable type 'float'; this va_arg has undefined behavior because arguments will be promoted to 'double'
  562. arg = [NSNumber numberWithFloat:(float)(va_arg(args, double))];
  563. break;
  564. case 'l':
  565. i++;
  566. if (i < length) {
  567. unichar next = [sql characterAtIndex:i];
  568. if (next == 'l') {
  569. i++;
  570. if (i < length && [sql characterAtIndex:i] == 'd') {
  571. //%lld
  572. arg = [NSNumber numberWithLongLong:va_arg(args, long long)];
  573. }
  574. else if (i < length && [sql characterAtIndex:i] == 'u') {
  575. //%llu
  576. arg = [NSNumber numberWithUnsignedLongLong:va_arg(args, unsigned long long)];
  577. }
  578. else {
  579. i--;
  580. }
  581. }
  582. else if (next == 'd') {
  583. //%ld
  584. arg = [NSNumber numberWithLong:va_arg(args, long)];
  585. }
  586. else if (next == 'u') {
  587. //%lu
  588. arg = [NSNumber numberWithUnsignedLong:va_arg(args, unsigned long)];
  589. }
  590. else {
  591. i--;
  592. }
  593. }
  594. else {
  595. i--;
  596. }
  597. break;
  598. default:
  599. // something else that we can't interpret. just pass it on through like normal
  600. break;
  601. }
  602. }
  603. else if (current == '%') {
  604. // percent sign; skip this character
  605. add = '\0';
  606. }
  607. if (arg != nil) {
  608. [cleanedSQL appendString:@"?"];
  609. [arguments addObject:arg];
  610. }
  611. else if (add == (unichar)'@' && last == (unichar) '%') {
  612. [cleanedSQL appendFormat:@"NULL"];
  613. }
  614. else if (add != '\0') {
  615. [cleanedSQL appendFormat:@"%C", add];
  616. }
  617. last = current;
  618. }
  619. }
  620. #pragma mark Execute queries
  621. - (FMResultSet *)executeQuery:(NSString *)sql withParameterDictionary:(NSDictionary *)arguments {
  622. return [self executeQuery:sql withArgumentsInArray:nil orDictionary:arguments orVAList:nil];
  623. }
  624. - (FMResultSet *)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray*)arrayArgs orDictionary:(NSDictionary *)dictionaryArgs orVAList:(va_list)args {
  625. if (![self databaseExists]) {
  626. return 0x00;
  627. }
  628. if (_isExecutingStatement) {
  629. [self warnInUse];
  630. return 0x00;
  631. }
  632. _isExecutingStatement = YES;
  633. int rc = 0x00;
  634. sqlite3_stmt *pStmt = 0x00;
  635. FMStatement *statement = 0x00;
  636. FMResultSet *rs = 0x00;
  637. if (_traceExecution && sql) {
  638. NSLog(@"%@ executeQuery: %@", self, sql);
  639. }
  640. if (_shouldCacheStatements) {
  641. statement = [self cachedStatementForQuery:sql];
  642. pStmt = statement ? [statement statement] : 0x00;
  643. [statement reset];
  644. }
  645. if (!pStmt) {
  646. rc = sqlite3_prepare_v2(_db, [sql UTF8String], -1, &pStmt, 0);
  647. if (SQLITE_OK != rc) {
  648. if (_logsErrors) {
  649. NSLog(@"DB Error: %d \"%@\"", [self lastErrorCode], [self lastErrorMessage]);
  650. NSLog(@"DB Query: %@", sql);
  651. NSLog(@"DB Path: %@", _databasePath);
  652. }
  653. if (_crashOnErrors) {
  654. NSAssert(false, @"DB Error: %d \"%@\"", [self lastErrorCode], [self lastErrorMessage]);
  655. abort();
  656. }
  657. sqlite3_finalize(pStmt);
  658. _isExecutingStatement = NO;
  659. return nil;
  660. }
  661. }
  662. id obj;
  663. int idx = 0;
  664. int queryCount = sqlite3_bind_parameter_count(pStmt); // pointed out by Dominic Yu (thanks!)
  665. // If dictionaryArgs is passed in, that means we are using sqlite's named parameter support
  666. if (dictionaryArgs) {
  667. for (NSString *dictionaryKey in [dictionaryArgs allKeys]) {
  668. // Prefix the key with a colon.
  669. NSString *parameterName = [[NSString alloc] initWithFormat:@":%@", dictionaryKey];
  670. if (_traceExecution) {
  671. NSLog(@"%@ = %@", parameterName, [dictionaryArgs objectForKey:dictionaryKey]);
  672. }
  673. // Get the index for the parameter name.
  674. int namedIdx = sqlite3_bind_parameter_index(pStmt, [parameterName UTF8String]);
  675. FMDBRelease(parameterName);
  676. if (namedIdx > 0) {
  677. // Standard binding from here.
  678. [self bindObject:[dictionaryArgs objectForKey:dictionaryKey] toColumn:namedIdx inStatement:pStmt];
  679. // increment the binding count, so our check below works out
  680. idx++;
  681. }
  682. else {
  683. NSLog(@"Could not find index for %@", dictionaryKey);
  684. }
  685. }
  686. }
  687. else {
  688. while (idx < queryCount) {
  689. if (arrayArgs && idx < (int)[arrayArgs count]) {
  690. obj = [arrayArgs objectAtIndex:(NSUInteger)idx];
  691. }
  692. else if (args) {
  693. obj = va_arg(args, id);
  694. }
  695. else {
  696. //We ran out of arguments
  697. break;
  698. }
  699. if (_traceExecution) {
  700. if ([obj isKindOfClass:[NSData class]]) {
  701. NSLog(@"data: %ld bytes", (unsigned long)[(NSData*)obj length]);
  702. }
  703. else {
  704. NSLog(@"obj: %@", obj);
  705. }
  706. }
  707. idx++;
  708. [self bindObject:obj toColumn:idx inStatement:pStmt];
  709. }
  710. }
  711. if (idx != queryCount) {
  712. NSLog(@"Error: the bind count is not correct for the # of variables (executeQuery)");
  713. sqlite3_finalize(pStmt);
  714. _isExecutingStatement = NO;
  715. return nil;
  716. }
  717. FMDBRetain(statement); // to balance the release below
  718. if (!statement) {
  719. statement = [[FMStatement alloc] init];
  720. [statement setStatement:pStmt];
  721. if (_shouldCacheStatements && sql) {
  722. [self setCachedStatement:statement forQuery:sql];
  723. }
  724. }
  725. // the statement gets closed in rs's dealloc or [rs close];
  726. rs = [FMResultSet resultSetWithStatement:statement usingParentDatabase:self];
  727. [rs setQuery:sql];
  728. NSValue *openResultSet = [NSValue valueWithNonretainedObject:rs];
  729. [_openResultSets addObject:openResultSet];
  730. [statement setUseCount:[statement useCount] + 1];
  731. FMDBRelease(statement);
  732. _isExecutingStatement = NO;
  733. return rs;
  734. }
  735. - (FMResultSet *)executeQuery:(NSString*)sql, ... {
  736. va_list args;
  737. va_start(args, sql);
  738. id result = [self executeQuery:sql withArgumentsInArray:nil orDictionary:nil orVAList:args];
  739. va_end(args);
  740. return result;
  741. }
  742. - (FMResultSet *)executeQueryWithFormat:(NSString*)format, ... {
  743. va_list args;
  744. va_start(args, format);
  745. NSMutableString *sql = [NSMutableString stringWithCapacity:[format length]];
  746. NSMutableArray *arguments = [NSMutableArray array];
  747. [self extractSQL:format argumentsList:args intoString:sql arguments:arguments];
  748. va_end(args);
  749. return [self executeQuery:sql withArgumentsInArray:arguments];
  750. }
  751. - (FMResultSet *)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray *)arguments {
  752. return [self executeQuery:sql withArgumentsInArray:arguments orDictionary:nil orVAList:nil];
  753. }
  754. - (FMResultSet *)executeQuery:(NSString *)sql values:(NSArray *)values error:(NSError * __autoreleasing *)error {
  755. FMResultSet *rs = [self executeQuery:sql withArgumentsInArray:values orDictionary:nil orVAList:nil];
  756. if (!rs && error) {
  757. *error = [self lastError];
  758. }
  759. return rs;
  760. }
  761. - (FMResultSet *)executeQuery:(NSString*)sql withVAList:(va_list)args {
  762. return [self executeQuery:sql withArgumentsInArray:nil orDictionary:nil orVAList:args];
  763. }
  764. #pragma mark Execute updates
  765. - (BOOL)executeUpdate:(NSString*)sql error:(NSError**)outErr withArgumentsInArray:(NSArray*)arrayArgs orDictionary:(NSDictionary *)dictionaryArgs orVAList:(va_list)args {
  766. if (![self databaseExists]) {
  767. return NO;
  768. }
  769. if (_isExecutingStatement) {
  770. [self warnInUse];
  771. return NO;
  772. }
  773. _isExecutingStatement = YES;
  774. int rc = 0x00;
  775. sqlite3_stmt *pStmt = 0x00;
  776. FMStatement *cachedStmt = 0x00;
  777. if (_traceExecution && sql) {
  778. NSLog(@"%@ executeUpdate: %@", self, sql);
  779. }
  780. if (_shouldCacheStatements) {
  781. cachedStmt = [self cachedStatementForQuery:sql];
  782. pStmt = cachedStmt ? [cachedStmt statement] : 0x00;
  783. [cachedStmt reset];
  784. }
  785. if (!pStmt) {
  786. rc = sqlite3_prepare_v2(_db, [sql UTF8String], -1, &pStmt, 0);
  787. if (SQLITE_OK != rc) {
  788. if (_logsErrors) {
  789. NSLog(@"DB Error: %d \"%@\"", [self lastErrorCode], [self lastErrorMessage]);
  790. NSLog(@"DB Query: %@", sql);
  791. NSLog(@"DB Path: %@", _databasePath);
  792. }
  793. if (_crashOnErrors) {
  794. NSAssert(false, @"DB Error: %d \"%@\"", [self lastErrorCode], [self lastErrorMessage]);
  795. abort();
  796. }
  797. if (outErr) {
  798. *outErr = [self errorWithMessage:[NSString stringWithUTF8String:sqlite3_errmsg(_db)]];
  799. }
  800. sqlite3_finalize(pStmt);
  801. _isExecutingStatement = NO;
  802. return NO;
  803. }
  804. }
  805. id obj;
  806. int idx = 0;
  807. int queryCount = sqlite3_bind_parameter_count(pStmt);
  808. // If dictionaryArgs is passed in, that means we are using sqlite's named parameter support
  809. if (dictionaryArgs) {
  810. for (NSString *dictionaryKey in [dictionaryArgs allKeys]) {
  811. // Prefix the key with a colon.
  812. NSString *parameterName = [[NSString alloc] initWithFormat:@":%@", dictionaryKey];
  813. if (_traceExecution) {
  814. NSLog(@"%@ = %@", parameterName, [dictionaryArgs objectForKey:dictionaryKey]);
  815. }
  816. // Get the index for the parameter name.
  817. int namedIdx = sqlite3_bind_parameter_index(pStmt, [parameterName UTF8String]);
  818. FMDBRelease(parameterName);
  819. if (namedIdx > 0) {
  820. // Standard binding from here.
  821. [self bindObject:[dictionaryArgs objectForKey:dictionaryKey] toColumn:namedIdx inStatement:pStmt];
  822. // increment the binding count, so our check below works out
  823. idx++;
  824. }
  825. else {
  826. NSString *message = [NSString stringWithFormat:@"Could not find index for %@", dictionaryKey];
  827. if (_logsErrors) {
  828. NSLog(@"%@", message);
  829. }
  830. if (outErr) {
  831. *outErr = [self errorWithMessage:message];
  832. }
  833. }
  834. }
  835. }
  836. else {
  837. while (idx < queryCount) {
  838. if (arrayArgs && idx < (int)[arrayArgs count]) {
  839. obj = [arrayArgs objectAtIndex:(NSUInteger)idx];
  840. }
  841. else if (args) {
  842. obj = va_arg(args, id);
  843. }
  844. else {
  845. //We ran out of arguments
  846. break;
  847. }
  848. if (_traceExecution) {
  849. if ([obj isKindOfClass:[NSData class]]) {
  850. NSLog(@"data: %ld bytes", (unsigned long)[(NSData*)obj length]);
  851. }
  852. else {
  853. NSLog(@"obj: %@", obj);
  854. }
  855. }
  856. idx++;
  857. [self bindObject:obj toColumn:idx inStatement:pStmt];
  858. }
  859. }
  860. if (idx != queryCount) {
  861. NSString *message = [NSString stringWithFormat:@"Error: the bind count (%d) is not correct for the # of variables in the query (%d) (%@) (executeUpdate)", idx, queryCount, sql];
  862. if (_logsErrors) {
  863. NSLog(@"%@", message);
  864. }
  865. if (outErr) {
  866. *outErr = [self errorWithMessage:message];
  867. }
  868. sqlite3_finalize(pStmt);
  869. _isExecutingStatement = NO;
  870. return NO;
  871. }
  872. /* Call sqlite3_step() to run the virtual machine. Since the SQL being
  873. ** executed is not a SELECT statement, we assume no data will be returned.
  874. */
  875. rc = sqlite3_step(pStmt);
  876. if (SQLITE_DONE == rc) {
  877. // all is well, let's return.
  878. }
  879. else if (SQLITE_INTERRUPT == rc) {
  880. if (_logsErrors) {
  881. NSLog(@"Error calling sqlite3_step. Query was interrupted (%d: %s) SQLITE_INTERRUPT", rc, sqlite3_errmsg(_db));
  882. NSLog(@"DB Query: %@", sql);
  883. }
  884. }
  885. else if (rc == SQLITE_ROW) {
  886. NSString *message = [NSString stringWithFormat:@"A executeUpdate is being called with a query string '%@'", sql];
  887. if (_logsErrors) {
  888. NSLog(@"%@", message);
  889. NSLog(@"DB Query: %@", sql);
  890. }
  891. if (outErr) {
  892. *outErr = [self errorWithMessage:message];
  893. }
  894. }
  895. else {
  896. if (outErr) {
  897. *outErr = [self errorWithMessage:[NSString stringWithUTF8String:sqlite3_errmsg(_db)]];
  898. }
  899. if (SQLITE_ERROR == rc) {
  900. if (_logsErrors) {
  901. NSLog(@"Error calling sqlite3_step (%d: %s) SQLITE_ERROR", rc, sqlite3_errmsg(_db));
  902. NSLog(@"DB Query: %@", sql);
  903. }
  904. }
  905. else if (SQLITE_MISUSE == rc) {
  906. // uh oh.
  907. if (_logsErrors) {
  908. NSLog(@"Error calling sqlite3_step (%d: %s) SQLITE_MISUSE", rc, sqlite3_errmsg(_db));
  909. NSLog(@"DB Query: %@", sql);
  910. }
  911. }
  912. else {
  913. // wtf?
  914. if (_logsErrors) {
  915. NSLog(@"Unknown error calling sqlite3_step (%d: %s) eu", rc, sqlite3_errmsg(_db));
  916. NSLog(@"DB Query: %@", sql);
  917. }
  918. }
  919. }
  920. if (_shouldCacheStatements && !cachedStmt) {
  921. cachedStmt = [[FMStatement alloc] init];
  922. [cachedStmt setStatement:pStmt];
  923. [self setCachedStatement:cachedStmt forQuery:sql];
  924. FMDBRelease(cachedStmt);
  925. }
  926. int closeErrorCode;
  927. if (cachedStmt) {
  928. [cachedStmt setUseCount:[cachedStmt useCount] + 1];
  929. closeErrorCode = sqlite3_reset(pStmt);
  930. }
  931. else {
  932. /* Finalize the virtual machine. This releases all memory and other
  933. ** resources allocated by the sqlite3_prepare() call above.
  934. */
  935. closeErrorCode = sqlite3_finalize(pStmt);
  936. }
  937. if (closeErrorCode != SQLITE_OK) {
  938. if (_logsErrors) {
  939. NSLog(@"Unknown error finalizing or resetting statement (%d: %s)", closeErrorCode, sqlite3_errmsg(_db));
  940. NSLog(@"DB Query: %@", sql);
  941. }
  942. }
  943. _isExecutingStatement = NO;
  944. return (rc == SQLITE_DONE || rc == SQLITE_OK);
  945. }
  946. - (BOOL)executeUpdate:(NSString*)sql, ... {
  947. va_list args;
  948. va_start(args, sql);
  949. BOOL result = [self executeUpdate:sql error:nil withArgumentsInArray:nil orDictionary:nil orVAList:args];
  950. va_end(args);
  951. return result;
  952. }
  953. - (BOOL)executeUpdate:(NSString*)sql withArgumentsInArray:(NSArray *)arguments {
  954. return [self executeUpdate:sql error:nil withArgumentsInArray:arguments orDictionary:nil orVAList:nil];
  955. }
  956. - (BOOL)executeUpdate:(NSString*)sql values:(NSArray *)values error:(NSError * __autoreleasing *)error {
  957. return [self executeUpdate:sql error:error withArgumentsInArray:values orDictionary:nil orVAList:nil];
  958. }
  959. - (BOOL)executeUpdate:(NSString*)sql withParameterDictionary:(NSDictionary *)arguments {
  960. return [self executeUpdate:sql error:nil withArgumentsInArray:nil orDictionary:arguments orVAList:nil];
  961. }
  962. - (BOOL)executeUpdate:(NSString*)sql withVAList:(va_list)args {
  963. return [self executeUpdate:sql error:nil withArgumentsInArray:nil orDictionary:nil orVAList:args];
  964. }
  965. - (BOOL)executeUpdateWithFormat:(NSString*)format, ... {
  966. va_list args;
  967. va_start(args, format);
  968. NSMutableString *sql = [NSMutableString stringWithCapacity:[format length]];
  969. NSMutableArray *arguments = [NSMutableArray array];
  970. [self extractSQL:format argumentsList:args intoString:sql arguments:arguments];
  971. va_end(args);
  972. return [self executeUpdate:sql withArgumentsInArray:arguments];
  973. }
  974. int FMDBExecuteBulkSQLCallback(void *theBlockAsVoid, int columns, char **values, char **names); // shhh clang.
  975. int FMDBExecuteBulkSQLCallback(void *theBlockAsVoid, int columns, char **values, char **names) {
  976. if (!theBlockAsVoid) {
  977. return SQLITE_OK;
  978. }
  979. int (^execCallbackBlock)(NSDictionary *resultsDictionary) = (__bridge int (^)(NSDictionary *__strong))(theBlockAsVoid);
  980. NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithCapacity:(NSUInteger)columns];
  981. for (NSInteger i = 0; i < columns; i++) {
  982. NSString *key = [NSString stringWithUTF8String:names[i]];
  983. id value = values[i] ? [NSString stringWithUTF8String:values[i]] : [NSNull null];
  984. value = value ? value : [NSNull null];
  985. [dictionary setObject:value forKey:key];
  986. }
  987. return execCallbackBlock(dictionary);
  988. }
  989. - (BOOL)executeStatements:(NSString *)sql {
  990. return [self executeStatements:sql withResultBlock:nil];
  991. }
  992. - (BOOL)executeStatements:(NSString *)sql withResultBlock:(__attribute__((noescape)) FMDBExecuteStatementsCallbackBlock)block {
  993. int rc;
  994. char *errmsg = nil;
  995. rc = sqlite3_exec([self sqliteHandle], [sql UTF8String], block ? FMDBExecuteBulkSQLCallback : nil, (__bridge void *)(block), &errmsg);
  996. if (errmsg && [self logsErrors]) {
  997. NSLog(@"Error inserting batch: %s", errmsg);
  998. sqlite3_free(errmsg);
  999. }
  1000. return (rc == SQLITE_OK);
  1001. }
  1002. - (BOOL)executeUpdate:(NSString*)sql withErrorAndBindings:(NSError**)outErr, ... {
  1003. va_list args;
  1004. va_start(args, outErr);
  1005. BOOL result = [self executeUpdate:sql error:outErr withArgumentsInArray:nil orDictionary:nil orVAList:args];
  1006. va_end(args);
  1007. return result;
  1008. }
  1009. #pragma clang diagnostic push
  1010. #pragma clang diagnostic ignored "-Wdeprecated-implementations"
  1011. - (BOOL)update:(NSString*)sql withErrorAndBindings:(NSError**)outErr, ... {
  1012. va_list args;
  1013. va_start(args, outErr);
  1014. BOOL result = [self executeUpdate:sql error:outErr withArgumentsInArray:nil orDictionary:nil orVAList:args];
  1015. va_end(args);
  1016. return result;
  1017. }
  1018. #pragma clang diagnostic pop
  1019. #pragma mark Transactions
  1020. - (BOOL)rollback {
  1021. BOOL b = [self executeUpdate:@"rollback transaction"];
  1022. if (b) {
  1023. _isInTransaction = NO;
  1024. }
  1025. return b;
  1026. }
  1027. - (BOOL)commit {
  1028. BOOL b = [self executeUpdate:@"commit transaction"];
  1029. if (b) {
  1030. _isInTransaction = NO;
  1031. }
  1032. return b;
  1033. }
  1034. - (BOOL)beginTransaction {
  1035. BOOL b = [self executeUpdate:@"begin exclusive transaction"];
  1036. if (b) {
  1037. _isInTransaction = YES;
  1038. }
  1039. return b;
  1040. }
  1041. - (BOOL)beginDeferredTransaction {
  1042. BOOL b = [self executeUpdate:@"begin deferred transaction"];
  1043. if (b) {
  1044. _isInTransaction = YES;
  1045. }
  1046. return b;
  1047. }
  1048. - (BOOL)beginImmediateTransaction {
  1049. BOOL b = [self executeUpdate:@"begin immediate transaction"];
  1050. if (b) {
  1051. _isInTransaction = YES;
  1052. }
  1053. return b;
  1054. }
  1055. - (BOOL)beginExclusiveTransaction {
  1056. BOOL b = [self executeUpdate:@"begin exclusive transaction"];
  1057. if (b) {
  1058. _isInTransaction = YES;
  1059. }
  1060. return b;
  1061. }
  1062. - (BOOL)inTransaction {
  1063. return _isInTransaction;
  1064. }
  1065. - (BOOL)interrupt
  1066. {
  1067. if (_db) {
  1068. sqlite3_interrupt([self sqliteHandle]);
  1069. return YES;
  1070. }
  1071. return NO;
  1072. }
  1073. static NSString *FMDBEscapeSavePointName(NSString *savepointName) {
  1074. return [savepointName stringByReplacingOccurrencesOfString:@"'" withString:@"''"];
  1075. }
  1076. - (BOOL)startSavePointWithName:(NSString*)name error:(NSError**)outErr {
  1077. #if SQLITE_VERSION_NUMBER >= 3007000
  1078. NSParameterAssert(name);
  1079. NSString *sql = [NSString stringWithFormat:@"savepoint '%@';", FMDBEscapeSavePointName(name)];
  1080. return [self executeUpdate:sql error:outErr withArgumentsInArray:nil orDictionary:nil orVAList:nil];
  1081. #else
  1082. NSString *errorMessage = NSLocalizedString(@"Save point functions require SQLite 3.7", nil);
  1083. if (self.logsErrors) NSLog(@"%@", errorMessage);
  1084. return NO;
  1085. #endif
  1086. }
  1087. - (BOOL)releaseSavePointWithName:(NSString*)name error:(NSError**)outErr {
  1088. #if SQLITE_VERSION_NUMBER >= 3007000
  1089. NSParameterAssert(name);
  1090. NSString *sql = [NSString stringWithFormat:@"release savepoint '%@';", FMDBEscapeSavePointName(name)];
  1091. return [self executeUpdate:sql error:outErr withArgumentsInArray:nil orDictionary:nil orVAList:nil];
  1092. #else
  1093. NSString *errorMessage = NSLocalizedString(@"Save point functions require SQLite 3.7", nil);
  1094. if (self.logsErrors) NSLog(@"%@", errorMessage);
  1095. return NO;
  1096. #endif
  1097. }
  1098. - (BOOL)rollbackToSavePointWithName:(NSString*)name error:(NSError**)outErr {
  1099. #if SQLITE_VERSION_NUMBER >= 3007000
  1100. NSParameterAssert(name);
  1101. NSString *sql = [NSString stringWithFormat:@"rollback transaction to savepoint '%@';", FMDBEscapeSavePointName(name)];
  1102. return [self executeUpdate:sql error:outErr withArgumentsInArray:nil orDictionary:nil orVAList:nil];
  1103. #else
  1104. NSString *errorMessage = NSLocalizedString(@"Save point functions require SQLite 3.7", nil);
  1105. if (self.logsErrors) NSLog(@"%@", errorMessage);
  1106. return NO;
  1107. #endif
  1108. }
  1109. - (NSError*)inSavePoint:(__attribute__((noescape)) void (^)(BOOL *rollback))block {
  1110. #if SQLITE_VERSION_NUMBER >= 3007000
  1111. static unsigned long savePointIdx = 0;
  1112. NSString *name = [NSString stringWithFormat:@"dbSavePoint%ld", savePointIdx++];
  1113. BOOL shouldRollback = NO;
  1114. NSError *err = 0x00;
  1115. if (![self startSavePointWithName:name error:&err]) {
  1116. return err;
  1117. }
  1118. if (block) {
  1119. block(&shouldRollback);
  1120. }
  1121. if (shouldRollback) {
  1122. // We need to rollback and release this savepoint to remove it
  1123. [self rollbackToSavePointWithName:name error:&err];
  1124. }
  1125. [self releaseSavePointWithName:name error:&err];
  1126. return err;
  1127. #else
  1128. NSString *errorMessage = NSLocalizedString(@"Save point functions require SQLite 3.7", nil);
  1129. if (self.logsErrors) NSLog(@"%@", errorMessage);
  1130. return [NSError errorWithDomain:@"FMDatabase" code:0 userInfo:@{NSLocalizedDescriptionKey : errorMessage}];
  1131. #endif
  1132. }
  1133. - (BOOL)checkpoint:(FMDBCheckpointMode)checkpointMode error:(NSError * __autoreleasing *)error {
  1134. return [self checkpoint:checkpointMode name:nil logFrameCount:NULL checkpointCount:NULL error:error];
  1135. }
  1136. - (BOOL)checkpoint:(FMDBCheckpointMode)checkpointMode name:(NSString *)name error:(NSError * __autoreleasing *)error {
  1137. return [self checkpoint:checkpointMode name:name logFrameCount:NULL checkpointCount:NULL error:error];
  1138. }
  1139. - (BOOL)checkpoint:(FMDBCheckpointMode)checkpointMode name:(NSString *)name logFrameCount:(int *)logFrameCount checkpointCount:(int *)checkpointCount error:(NSError * __autoreleasing *)error
  1140. {
  1141. const char* dbName = [name UTF8String];
  1142. #if SQLITE_VERSION_NUMBER >= 3007006
  1143. int err = sqlite3_wal_checkpoint_v2(_db, dbName, checkpointMode, logFrameCount, checkpointCount);
  1144. #else
  1145. NSLog(@"sqlite3_wal_checkpoint_v2 unavailable before sqlite 3.7.6. Ignoring checkpoint mode: %d", mode);
  1146. int err = sqlite3_wal_checkpoint(_db, dbName);
  1147. #endif
  1148. if(err != SQLITE_OK) {
  1149. if (error) {
  1150. *error = [self lastError];
  1151. }
  1152. if (self.logsErrors) NSLog(@"%@", [self lastErrorMessage]);
  1153. if (self.crashOnErrors) {
  1154. NSAssert(false, @"%@", [self lastErrorMessage]);
  1155. abort();
  1156. }
  1157. return NO;
  1158. } else {
  1159. return YES;
  1160. }
  1161. }
  1162. #pragma mark Cache statements
  1163. - (BOOL)shouldCacheStatements {
  1164. return _shouldCacheStatements;
  1165. }
  1166. - (void)setShouldCacheStatements:(BOOL)value {
  1167. _shouldCacheStatements = value;
  1168. if (_shouldCacheStatements && !_cachedStatements) {
  1169. [self setCachedStatements:[NSMutableDictionary dictionary]];
  1170. }
  1171. if (!_shouldCacheStatements) {
  1172. [self setCachedStatements:nil];
  1173. }
  1174. }
  1175. #pragma mark Callback function
  1176. void FMDBBlockSQLiteCallBackFunction(sqlite3_context *context, int argc, sqlite3_value **argv); // -Wmissing-prototypes
  1177. void FMDBBlockSQLiteCallBackFunction(sqlite3_context *context, int argc, sqlite3_value **argv) {
  1178. #if ! __has_feature(objc_arc)
  1179. void (^block)(sqlite3_context *context, int argc, sqlite3_value **argv) = (id)sqlite3_user_data(context);
  1180. #else
  1181. void (^block)(sqlite3_context *context, int argc, sqlite3_value **argv) = (__bridge id)sqlite3_user_data(context);
  1182. #endif
  1183. if (block) {
  1184. @autoreleasepool {
  1185. block(context, argc, argv);
  1186. }
  1187. }
  1188. }
  1189. // deprecated because "arguments" parameter is not maximum argument count, but actual argument count.
  1190. - (void)makeFunctionNamed:(NSString *)name maximumArguments:(int)arguments withBlock:(void (^)(void *context, int argc, void **argv))block {
  1191. [self makeFunctionNamed:name arguments:arguments block:block];
  1192. }
  1193. - (void)makeFunctionNamed:(NSString *)name arguments:(int)arguments block:(void (^)(void *context, int argc, void **argv))block {
  1194. if (!_openFunctions) {
  1195. _openFunctions = [NSMutableSet new];
  1196. }
  1197. id b = FMDBReturnAutoreleased([block copy]);
  1198. [_openFunctions addObject:b];
  1199. /* 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. */
  1200. #if ! __has_feature(objc_arc)
  1201. sqlite3_create_function([self sqliteHandle], [name UTF8String], arguments, SQLITE_UTF8, (void*)b, &FMDBBlockSQLiteCallBackFunction, 0x00, 0x00);
  1202. #else
  1203. sqlite3_create_function([self sqliteHandle], [name UTF8String], arguments, SQLITE_UTF8, (__bridge void*)b, &FMDBBlockSQLiteCallBackFunction, 0x00, 0x00);
  1204. #endif
  1205. }
  1206. - (SqliteValueType)valueType:(void *)value {
  1207. return sqlite3_value_type(value);
  1208. }
  1209. - (int)valueInt:(void *)value {
  1210. return sqlite3_value_int(value);
  1211. }
  1212. - (long long)valueLong:(void *)value {
  1213. return sqlite3_value_int64(value);
  1214. }
  1215. - (double)valueDouble:(void *)value {
  1216. return sqlite3_value_double(value);
  1217. }
  1218. - (NSData *)valueData:(void *)value {
  1219. const void *bytes = sqlite3_value_blob(value);
  1220. int length = sqlite3_value_bytes(value);
  1221. return bytes ? [NSData dataWithBytes:bytes length:(NSUInteger)length] : nil;
  1222. }
  1223. - (NSString *)valueString:(void *)value {
  1224. const char *cString = (const char *)sqlite3_value_text(value);
  1225. return cString ? [NSString stringWithUTF8String:cString] : nil;
  1226. }
  1227. - (void)resultNullInContext:(void *)context {
  1228. sqlite3_result_null(context);
  1229. }
  1230. - (void)resultInt:(int) value context:(void *)context {
  1231. sqlite3_result_int(context, value);
  1232. }
  1233. - (void)resultLong:(long long)value context:(void *)context {
  1234. sqlite3_result_int64(context, value);
  1235. }
  1236. - (void)resultDouble:(double)value context:(void *)context {
  1237. sqlite3_result_double(context, value);
  1238. }
  1239. - (void)resultData:(NSData *)data context:(void *)context {
  1240. sqlite3_result_blob(context, data.bytes, (int)data.length, SQLITE_TRANSIENT);
  1241. }
  1242. - (void)resultString:(NSString *)value context:(void *)context {
  1243. sqlite3_result_text(context, [value UTF8String], -1, SQLITE_TRANSIENT);
  1244. }
  1245. - (void)resultError:(NSString *)error context:(void *)context {
  1246. sqlite3_result_error(context, [error UTF8String], -1);
  1247. }
  1248. - (void)resultErrorCode:(int)errorCode context:(void *)context {
  1249. sqlite3_result_error_code(context, errorCode);
  1250. }
  1251. - (void)resultErrorNoMemoryInContext:(void *)context {
  1252. sqlite3_result_error_nomem(context);
  1253. }
  1254. - (void)resultErrorTooBigInContext:(void *)context {
  1255. sqlite3_result_error_toobig(context);
  1256. }
  1257. @end
  1258. @implementation FMStatement
  1259. #if ! __has_feature(objc_arc)
  1260. - (void)finalize {
  1261. [self close];
  1262. [super finalize];
  1263. }
  1264. #endif
  1265. - (void)dealloc {
  1266. [self close];
  1267. FMDBRelease(_query);
  1268. #if ! __has_feature(objc_arc)
  1269. [super dealloc];
  1270. #endif
  1271. }
  1272. - (void)close {
  1273. if (_statement) {
  1274. sqlite3_finalize(_statement);
  1275. _statement = 0x00;
  1276. }
  1277. _inUse = NO;
  1278. }
  1279. - (void)reset {
  1280. if (_statement) {
  1281. sqlite3_reset(_statement);
  1282. }
  1283. _inUse = NO;
  1284. }
  1285. - (NSString*)description {
  1286. return [NSString stringWithFormat:@"%@ %ld hit(s) for query %@", [super description], _useCount, _query];
  1287. }
  1288. @end