main.m 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611
  1. /* main.m
  2. *
  3. * Sample code to illustrate some of the basic FMDB classes and run them through their paces for illustrative purposes.
  4. */
  5. #import <Foundation/Foundation.h>
  6. #import "FMDB.h"
  7. #import "FMSQLStatementSplitter.h"
  8. #define FMDBQuickCheck(SomeBool) { if (!(SomeBool)) { NSLog(@"Failure on line %d", __LINE__); abort(); } }
  9. void testPool(NSString *dbPath);
  10. void testDateFormat();
  11. void FMDBReportABugFunction();
  12. void testStatementCaching();
  13. int main (int argc, const char * argv[]) {
  14. @autoreleasepool {
  15. FMDBReportABugFunction();
  16. NSString *dbPath = @"/tmp/tmp.db";
  17. // delete the old db.
  18. NSFileManager *fileManager = [NSFileManager defaultManager];
  19. [fileManager removeItemAtPath:dbPath error:nil];
  20. FMDatabase *db = [FMDatabase databaseWithPath:dbPath];
  21. NSLog(@"Is SQLite compiled with it's thread safe options turned on? %@!", [FMDatabase isSQLiteThreadSafe] ? @"Yes" : @"No");
  22. {
  23. // -------------------------------------------------------------------------------
  24. // Un-opened database check.
  25. FMDBQuickCheck([db executeQuery:@"select * from table"] == nil);
  26. NSLog(@"%d: %@", [db lastErrorCode], [db lastErrorMessage]);
  27. }
  28. if (![db open]) {
  29. NSLog(@"Could not open db.");
  30. return 0;
  31. }
  32. // kind of experimentalish.
  33. [db setShouldCacheStatements:YES];
  34. // create a bad statement, just to test the error code.
  35. [db executeUpdate:@"blah blah blah"];
  36. FMDBQuickCheck([db hadError]);
  37. if ([db hadError]) {
  38. NSLog(@"Err %d: %@", [db lastErrorCode], [db lastErrorMessage]);
  39. }
  40. NSError *err = 0x00;
  41. FMDBQuickCheck(![db executeUpdate:@"blah blah blah" withErrorAndBindings:&err]);
  42. FMDBQuickCheck(err != nil);
  43. FMDBQuickCheck([err code] == SQLITE_ERROR);
  44. NSLog(@"err: '%@'", err);
  45. // empty strings should still return a value.
  46. FMDBQuickCheck(([db boolForQuery:@"SELECT ? not null", @""]));
  47. // same with empty bits o' mutable data
  48. FMDBQuickCheck(([db boolForQuery:@"SELECT ? not null", [NSMutableData data]]));
  49. // same with empty bits o' data
  50. FMDBQuickCheck(([db boolForQuery:@"SELECT ? not null", [NSData data]]));
  51. // how do we do pragmas? Like so:
  52. FMResultSet *ps = [db executeQuery:@"pragma journal_mode=delete"];
  53. FMDBQuickCheck(![db hadError]);
  54. FMDBQuickCheck(ps);
  55. FMDBQuickCheck([ps next]);
  56. [ps close];
  57. // oh, but some pragmas require updates?
  58. [db executeUpdate:@"pragma page_size=2048"];
  59. FMDBQuickCheck(![db hadError]);
  60. // what about a vacuum?
  61. [db executeUpdate:@"vacuum"];
  62. FMDBQuickCheck(![db hadError]);
  63. // but of course, I don't bother checking the error codes below.
  64. // Bad programmer, no cookie.
  65. [db executeUpdate:@"create table test (a text, b text, c integer, d double, e double)"];
  66. [db beginTransaction];
  67. int i = 0;
  68. while (i++ < 20) {
  69. [db executeUpdate:@"insert into test (a, b, c, d, e) values (?, ?, ?, ?, ?)" ,
  70. @"hi'", // look! I put in a ', and I'm not escaping it!
  71. [NSString stringWithFormat:@"number %d", i],
  72. [NSNumber numberWithInt:i],
  73. [NSDate date],
  74. [NSNumber numberWithFloat:2.2f]];
  75. }
  76. [db commit];
  77. // do it again, just because
  78. [db beginTransaction];
  79. i = 0;
  80. while (i++ < 20) {
  81. [db executeUpdate:@"insert into test (a, b, c, d, e) values (?, ?, ?, ?, ?)" ,
  82. @"hi again'", // look! I put in a ', and I'm not escaping it!
  83. [NSString stringWithFormat:@"number %d", i],
  84. [NSNumber numberWithInt:i],
  85. [NSDate date],
  86. [NSNumber numberWithFloat:2.2f]];
  87. }
  88. [db commit];
  89. FMResultSet *rs = [db executeQuery:@"select rowid,* from test where a = ?", @"hi'"];
  90. while ([rs next]) {
  91. // just print out what we've got in a number of formats.
  92. NSLog(@"%d %@ %@ %@ %@ %f %f",
  93. [rs intForColumn:@"c"],
  94. [rs stringForColumn:@"b"],
  95. [rs stringForColumn:@"a"],
  96. [rs stringForColumn:@"rowid"],
  97. [rs dateForColumn:@"d"],
  98. [rs doubleForColumn:@"d"],
  99. [rs doubleForColumn:@"e"]);
  100. if (!([[rs columnNameForIndex:0] isEqualToString:@"rowid"] &&
  101. [[rs columnNameForIndex:1] isEqualToString:@"a"])
  102. ) {
  103. NSLog(@"WHOA THERE BUDDY, columnNameForIndex ISN'T WORKING!");
  104. return 7;
  105. }
  106. }
  107. // close the result set.
  108. // it'll also close when it's dealloc'd, but we're closing the database before
  109. // the autorelease pool closes, so sqlite will complain about it.
  110. [rs close];
  111. FMDBQuickCheck(![db hasOpenResultSets]);
  112. rs = [db executeQuery:@"select rowid, a, b, c from test"];
  113. while ([rs next]) {
  114. FMDBQuickCheck([rs[0] isEqual:rs[@"rowid"]]);
  115. FMDBQuickCheck([rs[1] isEqual:rs[@"a"]]);
  116. FMDBQuickCheck([rs[2] isEqual:rs[@"b"]]);
  117. FMDBQuickCheck([rs[3] isEqual:rs[@"c"]]);
  118. }
  119. [rs close];
  120. [db executeUpdate:@"create table ull (a integer)"];
  121. [db executeUpdate:@"insert into ull (a) values (?)" , [NSNumber numberWithUnsignedLongLong:ULLONG_MAX]];
  122. rs = [db executeQuery:@"select a from ull"];
  123. while ([rs next]) {
  124. unsigned long long a = [rs unsignedLongLongIntForColumnIndex:0];
  125. unsigned long long b = [rs unsignedLongLongIntForColumn:@"a"];
  126. FMDBQuickCheck(a == ULLONG_MAX);
  127. FMDBQuickCheck(b == ULLONG_MAX);
  128. }
  129. // check case sensitive result dictionary.
  130. [db executeUpdate:@"create table cs (aRowName integer, bRowName text)"];
  131. FMDBQuickCheck(![db hadError]);
  132. [db executeUpdate:@"insert into cs (aRowName, bRowName) values (?, ?)" , [NSNumber numberWithBool:1], @"hello"];
  133. FMDBQuickCheck(![db hadError]);
  134. rs = [db executeQuery:@"select * from cs"];
  135. while ([rs next]) {
  136. NSDictionary *d = [rs resultDictionary];
  137. FMDBQuickCheck([d objectForKey:@"aRowName"]);
  138. FMDBQuickCheck(![d objectForKey:@"arowname"]);
  139. FMDBQuickCheck([d objectForKey:@"bRowName"]);
  140. FMDBQuickCheck(![d objectForKey:@"browname"]);
  141. }
  142. // check funky table names + getTableSchema
  143. [db executeUpdate:@"create table '234 fds' (foo text)"];
  144. FMDBQuickCheck(![db hadError]);
  145. rs = [db getTableSchema:@"234 fds"];
  146. FMDBQuickCheck([rs next]);
  147. [rs close];
  148. #if SQLITE_VERSION_NUMBER >= 3007017
  149. {
  150. uint32_t appID = NSHFSTypeCodeFromFileType(NSFileTypeForHFSTypeCode('fmdb'));
  151. [db setApplicationID:appID];
  152. uint32_t rAppID = [db applicationID];
  153. NSLog(@"rAppID: %d", rAppID);
  154. FMDBQuickCheck(rAppID == appID);
  155. [db setApplicationIDString:@"acrn"];
  156. NSString *s = [db applicationIDString];
  157. NSLog(@"s: '%@'", s);
  158. FMDBQuickCheck([s isEqualToString:@"acrn"]);
  159. }
  160. #endif
  161. // -------------------------------------------------------------------------------
  162. // executeBulkSQL tests.
  163. {
  164. NSString *sql = @"create table if not exists test1 (id integer primary key autoincrement, x text);"
  165. "create table if not exists test2 (id integer primary key autoincrement, y text);"
  166. "create table if not exists test3 (id integer primary key autoincrement, z text);"
  167. "insert into test1 (x) values ('XXX');"
  168. "insert into test2 (y) values ('YYY');"
  169. "insert into test3 (z) values ('ZZZ');";
  170. FMDBQuickCheck([db executeBulkSQL:sql]);
  171. }
  172. {
  173. NSString *sql = @"select count(*) as count from test1;"
  174. "select count(*) as count from test2;"
  175. "select count(*) as count from test3;";
  176. FMDBQuickCheck([db executeBulkSQL:sql block:^int(NSDictionary *dictionary) {
  177. NSInteger count = [dictionary[@"count"] integerValue];
  178. if (count == 0) {
  179. NSLog(@"executeBulkSQL: error: was expecting non-zero number of records; dictionary = %@", dictionary);
  180. } else {
  181. NSLog(@"executeBulkSQL: everything ok: dictionary = %@", dictionary);
  182. }
  183. return 0;
  184. }]);
  185. }
  186. {
  187. NSString *sql = @"drop table test1;"
  188. "drop table test2;"
  189. "drop table test3;";
  190. FMDBQuickCheck([db executeBulkSQL:sql]);
  191. }
  192. {
  193. // -------------------------------------------------------------------------------
  194. // Named parameters count test.
  195. FMDBQuickCheck([db executeUpdate:@"create table namedparamcounttest (a text, b text, c integer, d double)"]);
  196. NSMutableDictionary *dictionaryArgs = [NSMutableDictionary dictionary];
  197. [dictionaryArgs setObject:@"Text1" forKey:@"a"];
  198. [dictionaryArgs setObject:@"Text2" forKey:@"b"];
  199. [dictionaryArgs setObject:[NSNumber numberWithInt:1] forKey:@"c"];
  200. [dictionaryArgs setObject:[NSNumber numberWithDouble:2.0] forKey:@"d"];
  201. FMDBQuickCheck([db executeUpdate:@"insert into namedparamcounttest values (:a, :b, :c, :d)" withParameterDictionary:dictionaryArgs]);
  202. rs = [db executeQuery:@"select * from namedparamcounttest"];
  203. FMDBQuickCheck((rs != nil));
  204. [rs next];
  205. FMDBQuickCheck([[rs stringForColumn:@"a"] isEqualToString:@"Text1"]);
  206. FMDBQuickCheck([[rs stringForColumn:@"b"] isEqualToString:@"Text2"]);
  207. FMDBQuickCheck([rs intForColumn:@"c"] == 1);
  208. FMDBQuickCheck([rs doubleForColumn:@"d"] == 2.0);
  209. [rs close];
  210. // note that at this point, dictionaryArgs has way more values than we need, but the query should still work since
  211. // a is in there, and that's all we need.
  212. rs = [db executeQuery:@"select * from namedparamcounttest where a = :a" withParameterDictionary:dictionaryArgs];
  213. FMDBQuickCheck((rs != nil));
  214. FMDBQuickCheck([rs next]);
  215. [rs close];
  216. // ***** Please note the following codes *****
  217. dictionaryArgs = [NSMutableDictionary dictionary];
  218. [dictionaryArgs setObject:@"NewText1" forKey:@"a"];
  219. [dictionaryArgs setObject:@"NewText2" forKey:@"b"];
  220. [dictionaryArgs setObject:@"OneMoreText" forKey:@"OneMore"];
  221. BOOL rc = [db executeUpdate:@"update namedparamcounttest set a = :a, b = :b where b = 'Text2'" withParameterDictionary:dictionaryArgs];
  222. FMDBQuickCheck(rc);
  223. if (!rc) {
  224. NSLog(@"ERROR: %d - %@", db.lastErrorCode, db.lastErrorMessage);
  225. }
  226. }
  227. // ----------------------------------------------------------------------------------------
  228. // blob support.
  229. [db executeUpdate:@"create table blobTable (a text, b blob)"];
  230. // let's read in an image from safari's app bundle.
  231. NSData *safariCompass = [NSData dataWithContentsOfFile:@"/Applications/Safari.app/Contents/Resources/compass.icns"];
  232. if (safariCompass) {
  233. [db executeUpdate:@"insert into blobTable (a, b) values (?,?)", @"safari's compass", safariCompass];
  234. rs = [db executeQuery:@"select b from blobTable where a = ?", @"safari's compass"];
  235. if ([rs next]) {
  236. safariCompass = [rs dataForColumn:@"b"];
  237. [safariCompass writeToFile:@"/tmp/compass.icns" atomically:NO];
  238. // let's look at our fancy image that we just wrote out..
  239. system("/usr/bin/open /tmp/compass.icns");
  240. // ye shall read the header for this function, or suffer the consequences.
  241. safariCompass = [rs dataNoCopyForColumn:@"b"];
  242. [safariCompass writeToFile:@"/tmp/compass_data_no_copy.icns" atomically:NO];
  243. system("/usr/bin/open /tmp/compass_data_no_copy.icns");
  244. }
  245. else {
  246. NSLog(@"Could not select image.");
  247. }
  248. [rs close];
  249. }
  250. else {
  251. NSLog(@"Can't find compass image..");
  252. }
  253. // test out the convenience methods in +Additions
  254. [db executeUpdate:@"create table t1 (a integer)"];
  255. [db executeUpdate:@"insert into t1 values (?)", [NSNumber numberWithInt:5]];
  256. NSLog(@"Count of changes (should be 1): %d", [db changes]);
  257. FMDBQuickCheck([db changes] == 1);
  258. int ia = [db intForQuery:@"select a from t1 where a = ?", [NSNumber numberWithInt:5]];
  259. if (ia != 5) {
  260. NSLog(@"intForQuery didn't work (a != 5)");
  261. }
  262. // test the busy rety timeout schtuff.
  263. [db setBusyTimeout:5];
  264. FMDatabase *newDb = [FMDatabase databaseWithPath:dbPath];
  265. [newDb open];
  266. rs = [newDb executeQuery:@"select rowid,* from test where a = ?", @"hi'"];
  267. [rs next]; // just grab one... which will keep the db locked.
  268. NSLog(@"Testing the busy timeout");
  269. NSTimeInterval startTime = [NSDate timeIntervalSinceReferenceDate];
  270. BOOL success = [db executeUpdate:@"insert into t1 values (5)"];
  271. if (success) {
  272. NSLog(@"Whoa- the database didn't stay locked!");
  273. return 7;
  274. }
  275. else {
  276. NSLog(@"Hurray, our timeout worked");
  277. }
  278. [rs close];
  279. [newDb close];
  280. success = [db executeUpdate:@"insert into t1 values (5)"];
  281. if (!success) {
  282. NSLog(@"Whoa- the database shouldn't be locked!");
  283. return 8;
  284. }
  285. else {
  286. NSLog(@"Hurray, we can insert again!");
  287. }
  288. NSTimeInterval end = [NSDate timeIntervalSinceReferenceDate] - startTime;
  289. NSLog(@"Took %f seconds for the timeout.", end);
  290. // test some nullness.
  291. [db executeUpdate:@"create table t2 (a integer, b integer)"];
  292. if (![db executeUpdate:@"insert into t2 values (?, ?)", nil, [NSNumber numberWithInt:5]]) {
  293. NSLog(@"UH OH, can't insert a nil value for some reason...");
  294. }
  295. rs = [db executeQuery:@"select * from t2"];
  296. while ([rs next]) {
  297. NSString *aa = [rs stringForColumnIndex:0];
  298. NSString *b = [rs stringForColumnIndex:1];
  299. if (aa != nil) {
  300. NSLog(@"%s:%d", __FUNCTION__, __LINE__);
  301. NSLog(@"OH OH, PROBLEMO!");
  302. return 10;
  303. }
  304. else {
  305. NSLog(@"YAY, NULL VALUES");
  306. }
  307. if (![b isEqualToString:@"5"]) {
  308. NSLog(@"%s:%d", __FUNCTION__, __LINE__);
  309. NSLog(@"OH OH, PROBLEMO!");
  310. return 10;
  311. }
  312. }
  313. // test some inner loop funkness.
  314. [db executeUpdate:@"create table t3 (a somevalue)"];
  315. // do it again, just because
  316. [db beginTransaction];
  317. i = 0;
  318. while (i++ < 20) {
  319. [db executeUpdate:@"insert into t3 (a) values (?)" , [NSNumber numberWithInt:i]];
  320. }
  321. [db commit];
  322. rs = [db executeQuery:@"select * from t3"];
  323. while ([rs next]) {
  324. int foo = [rs intForColumnIndex:0];
  325. int newVal = foo + 100;
  326. [db executeUpdate:@"update t3 set a = ? where a = ?" , [NSNumber numberWithInt:newVal], [NSNumber numberWithInt:foo]];
  327. FMResultSet *rs2 = [db executeQuery:@"select a from t3 where a = ?", [NSNumber numberWithInt:newVal]];
  328. [rs2 next];
  329. if ([rs2 intForColumnIndex:0] != newVal) {
  330. NSLog(@"Oh crap, our update didn't work out!");
  331. return 9;
  332. }
  333. [rs2 close];
  334. }
  335. // NSNull tests
  336. [db executeUpdate:@"create table nulltest (a text, b text)"];
  337. [db executeUpdate:@"insert into nulltest (a, b) values (?, ?)" , [NSNull null], @"a"];
  338. [db executeUpdate:@"insert into nulltest (a, b) values (?, ?)" , nil, @"b"];
  339. rs = [db executeQuery:@"select * from nulltest"];
  340. while ([rs next]) {
  341. NSString *a = [rs stringForColumnIndex:0];
  342. NSString *b = [rs stringForColumnIndex:1];
  343. if (!b) {
  344. NSLog(@"Oh crap, the nil / null inserts didn't work!");
  345. return 10;
  346. }
  347. if (a) {
  348. NSLog(@"Oh crap, the nil / null inserts didn't work (son of error message)!");
  349. return 11;
  350. }
  351. else {
  352. NSLog(@"HURRAH FOR NSNULL (and nil)!");
  353. }
  354. }
  355. FMDBQuickCheck([db columnExists:@"a" inTableWithName:@"nulltest"]);
  356. FMDBQuickCheck([db columnExists:@"b" inTableWithName:@"nulltest"]);
  357. FMDBQuickCheck(![db columnExists:@"c" inTableWithName:@"nulltest"]);
  358. // null dates
  359. NSDate *date = [NSDate date];
  360. [db executeUpdate:@"create table datetest (a double, b double, c double)"];
  361. [db executeUpdate:@"insert into datetest (a, b, c) values (?, ?, 0)" , [NSNull null], date];
  362. rs = [db executeQuery:@"select * from datetest"];
  363. while ([rs next]) {
  364. NSDate *a = [rs dateForColumnIndex:0];
  365. NSDate *b = [rs dateForColumnIndex:1];
  366. NSDate *c = [rs dateForColumnIndex:2];
  367. if (a) {
  368. NSLog(@"Oh crap, the null date insert didn't work!");
  369. return 12;
  370. }
  371. if (!c) {
  372. NSLog(@"Oh crap, the 0 date insert didn't work!");
  373. return 12;
  374. }
  375. NSTimeInterval dti = fabs([b timeIntervalSinceDate:date]);
  376. if (floor(dti) > 0.0) {
  377. NSLog(@"Date matches didn't really happen... time difference of %f", dti);
  378. return 13;
  379. }
  380. dti = fabs([c timeIntervalSinceDate:[NSDate dateWithTimeIntervalSince1970:0]]);
  381. if (floor(dti) > 0.0) {
  382. NSLog(@"Date matches didn't really happen... time difference of %f", dti);
  383. return 13;
  384. }
  385. }
  386. NSDate *foo = [db dateForQuery:@"select b from datetest where c = 0"];
  387. assert(foo);
  388. NSTimeInterval dti = fabs([foo timeIntervalSinceDate:date]);
  389. if (floor(dti) > 0.0) {
  390. NSLog(@"Date matches didn't really happen... time difference of %f", dti);
  391. return 14;
  392. }
  393. [db executeUpdate:@"create table nulltest2 (s text, d data, i integer, f double, b integer)"];
  394. // grab the data for this again, since we overwrote it with some memory that has since disapeared.
  395. safariCompass = [NSData dataWithContentsOfFile:@"/Applications/Safari.app/Contents/Resources/compass.icns"];
  396. [db executeUpdate:@"insert into nulltest2 (s, d, i, f, b) values (?, ?, ?, ?, ?)" , @"Hi", safariCompass, [NSNumber numberWithInt:12], [NSNumber numberWithFloat:4.4f], [NSNumber numberWithBool:YES]];
  397. [db executeUpdate:@"insert into nulltest2 (s, d, i, f, b) values (?, ?, ?, ?, ?)" , nil, nil, nil, nil, [NSNull null]];
  398. rs = [db executeQuery:@"select * from nulltest2"];
  399. while ([rs next]) {
  400. i = [rs intForColumnIndex:2];
  401. if (i == 12) {
  402. // it's the first row we inserted.
  403. FMDBQuickCheck(![rs columnIndexIsNull:0]);
  404. FMDBQuickCheck(![rs columnIndexIsNull:1]);
  405. FMDBQuickCheck(![rs columnIndexIsNull:2]);
  406. FMDBQuickCheck(![rs columnIndexIsNull:3]);
  407. FMDBQuickCheck(![rs columnIndexIsNull:4]);
  408. FMDBQuickCheck( [rs columnIndexIsNull:5]);
  409. FMDBQuickCheck([[rs dataForColumn:@"d"] length] == [safariCompass length]);
  410. FMDBQuickCheck(![rs dataForColumn:@"notthere"]);
  411. FMDBQuickCheck(![rs stringForColumnIndex:-2]);
  412. FMDBQuickCheck([rs boolForColumnIndex:4]);
  413. FMDBQuickCheck([rs boolForColumn:@"b"]);
  414. FMDBQuickCheck(fabs(4.4 - [rs doubleForColumn:@"f"]) < 0.0000001);
  415. FMDBQuickCheck(12 == [rs intForColumn:@"i"]);
  416. FMDBQuickCheck(12 == [rs intForColumnIndex:2]);
  417. FMDBQuickCheck(0 == [rs intForColumnIndex:12]); // there is no 12
  418. FMDBQuickCheck(0 == [rs intForColumn:@"notthere"]);
  419. FMDBQuickCheck(12 == [rs longForColumn:@"i"]);
  420. FMDBQuickCheck(12 == [rs longLongIntForColumn:@"i"]);
  421. }
  422. else {
  423. // let's test various null things.
  424. FMDBQuickCheck([rs columnIndexIsNull:0]);
  425. FMDBQuickCheck([rs columnIndexIsNull:1]);
  426. FMDBQuickCheck([rs columnIndexIsNull:2]);
  427. FMDBQuickCheck([rs columnIndexIsNull:3]);
  428. FMDBQuickCheck([rs columnIndexIsNull:4]);
  429. FMDBQuickCheck([rs columnIndexIsNull:5]);
  430. FMDBQuickCheck(![rs dataForColumn:@"d"]);
  431. }
  432. }
  433. {
  434. [db executeUpdate:@"create table utest (a text)"];
  435. [db executeUpdate:@"insert into utest values (?)", @"/übertest"];
  436. rs = [db executeQuery:@"select * from utest where a = ?", @"/übertest"];
  437. FMDBQuickCheck([rs next]);
  438. [rs close];
  439. }
  440. {
  441. [db executeUpdate:@"create table testOneHundredTwelvePointTwo (a text, b integer)"];
  442. [db executeUpdate:@"insert into testOneHundredTwelvePointTwo values (?, ?)" withArgumentsInArray:[NSArray arrayWithObjects:@"one", [NSNumber numberWithInteger:2], nil]];
  443. [db executeUpdate:@"insert into testOneHundredTwelvePointTwo values (?, ?)" withArgumentsInArray:[NSArray arrayWithObjects:@"one", [NSNumber numberWithInteger:3], nil]];
  444. rs = [db executeQuery:@"select * from testOneHundredTwelvePointTwo where b > ?" withArgumentsInArray:[NSArray arrayWithObject:[NSNumber numberWithInteger:1]]];
  445. FMDBQuickCheck([rs next]);
  446. FMDBQuickCheck([rs hasAnotherRow]);
  447. FMDBQuickCheck(![db hadError]);
  448. FMDBQuickCheck([[rs stringForColumnIndex:0] isEqualToString:@"one"]);
  449. FMDBQuickCheck([rs intForColumnIndex:1] == 2);
  450. FMDBQuickCheck([rs next]);
  451. FMDBQuickCheck([rs intForColumnIndex:1] == 3);
  452. FMDBQuickCheck(![rs next]);
  453. FMDBQuickCheck(![rs hasAnotherRow]);
  454. }
  455. {
  456. FMDBQuickCheck([db executeUpdate:@"create table t4 (a text, b text)"]);
  457. FMDBQuickCheck(([db executeUpdate:@"insert into t4 (a, b) values (?, ?)", @"one", @"two"]));
  458. rs = [db executeQuery:@"select t4.a as 't4.a', t4.b from t4;"];
  459. FMDBQuickCheck((rs != nil));
  460. [rs next];
  461. FMDBQuickCheck([[rs stringForColumn:@"t4.a"] isEqualToString:@"one"]);
  462. FMDBQuickCheck([[rs stringForColumn:@"b"] isEqualToString:@"two"]);
  463. FMDBQuickCheck(strcmp((const char*)[rs UTF8StringForColumnName:@"b"], "two") == 0);
  464. [rs close];
  465. // let's try these again, with the withArgumentsInArray: variation
  466. FMDBQuickCheck([db executeUpdate:@"drop table t4;" withArgumentsInArray:[NSArray array]]);
  467. FMDBQuickCheck([db executeUpdate:@"create table t4 (a text, b text)" withArgumentsInArray:[NSArray array]]);
  468. FMDBQuickCheck(([db executeUpdate:@"insert into t4 (a, b) values (?, ?)" withArgumentsInArray:[NSArray arrayWithObjects:@"one", @"two", nil]]));
  469. rs = [db executeQuery:@"select t4.a as 't4.a', t4.b from t4;" withArgumentsInArray:[NSArray array]];
  470. FMDBQuickCheck((rs != nil));
  471. [rs next];
  472. FMDBQuickCheck([[rs stringForColumn:@"t4.a"] isEqualToString:@"one"]);
  473. FMDBQuickCheck([[rs stringForColumn:@"b"] isEqualToString:@"two"]);
  474. FMDBQuickCheck(strcmp((const char*)[rs UTF8StringForColumnName:@"b"], "two") == 0);
  475. [rs close];
  476. }
  477. {
  478. FMDBQuickCheck([db tableExists:@"t4"]);
  479. FMDBQuickCheck(![db tableExists:@"thisdoesntexist"]);
  480. rs = [db getSchema];
  481. while ([rs next]) {
  482. FMDBQuickCheck([[rs stringForColumn:@"type"] isEqualToString:@"table"]);
  483. }
  484. }
  485. {
  486. FMDBQuickCheck([db executeUpdate:@"create table t5 (a text, b int, c blob, d text, e text)"]);
  487. FMDBQuickCheck(([db executeUpdateWithFormat:@"insert into t5 values (%s, %d, %@, %c, %lld)", "text", 42, @"BLOB", 'd', 12345678901234ll]));
  488. rs = [db executeQueryWithFormat:@"select * from t5 where a = %s and a = %@ and b = %d", "text", @"text", 42];
  489. FMDBQuickCheck((rs != nil));
  490. [rs next];
  491. FMDBQuickCheck([[rs stringForColumn:@"a"] isEqualToString:@"text"]);
  492. FMDBQuickCheck(([rs intForColumn:@"b"] == 42));
  493. FMDBQuickCheck([[rs stringForColumn:@"c"] isEqualToString:@"BLOB"]);
  494. FMDBQuickCheck([[rs stringForColumn:@"d"] isEqualToString:@"d"]);
  495. FMDBQuickCheck(([rs longLongIntForColumn:@"e"] == 12345678901234));
  496. [rs close];
  497. }
  498. {
  499. FMDBQuickCheck([db executeUpdate:@"create table t55 (a text, b int, c float)"]);
  500. short testShort = -4;
  501. float testFloat = 5.5;
  502. FMDBQuickCheck(([db executeUpdateWithFormat:@"insert into t55 values (%c, %hi, %g)", 'a', testShort, testFloat]));
  503. unsigned short testUShort = 6;
  504. FMDBQuickCheck(([db executeUpdateWithFormat:@"insert into t55 values (%c, %hu, %g)", 'a', testUShort, testFloat]));
  505. rs = [db executeQueryWithFormat:@"select * from t55 where a = %s order by 2", "a"];
  506. FMDBQuickCheck((rs != nil));
  507. [rs next];
  508. FMDBQuickCheck([[rs stringForColumn:@"a"] isEqualToString:@"a"]);
  509. FMDBQuickCheck(([rs intForColumn:@"b"] == -4));
  510. FMDBQuickCheck([[rs stringForColumn:@"c"] isEqualToString:@"5.5"]);
  511. [rs next];
  512. FMDBQuickCheck([[rs stringForColumn:@"a"] isEqualToString:@"a"]);
  513. FMDBQuickCheck(([rs intForColumn:@"b"] == 6));
  514. FMDBQuickCheck([[rs stringForColumn:@"c"] isEqualToString:@"5.5"]);
  515. [rs close];
  516. }
  517. {
  518. FMDBQuickCheck([db executeUpdate:@"create table tatwhat (a text)"]);
  519. BOOL worked = [db executeUpdateWithFormat:@"insert into tatwhat values(%@)", nil];
  520. FMDBQuickCheck(worked);
  521. rs = [db executeQueryWithFormat:@"select * from tatwhat"];
  522. FMDBQuickCheck((rs != nil));
  523. FMDBQuickCheck(([rs next]));
  524. FMDBQuickCheck([rs columnIndexIsNull:0]);
  525. FMDBQuickCheck((![rs next]));
  526. }
  527. {
  528. FMDBQuickCheck(([db executeUpdate:@"insert into t5 values (?, ?, ?, ?, ?)" withErrorAndBindings:&err, @"text", [NSNumber numberWithInt:42], @"BLOB", @"d", [NSNumber numberWithInt:0]]));
  529. }
  530. {
  531. rs = [db executeQuery:@"select * from t5 where a=?" withArgumentsInArray:@[]];
  532. FMDBQuickCheck((![rs next]));
  533. }
  534. // test attach for the heck of it.
  535. {
  536. //FMDatabase *dbA = [FMDatabase databaseWithPath:dbPath];
  537. [fileManager removeItemAtPath:@"/tmp/attachme.db" error:nil];
  538. FMDatabase *dbB = [FMDatabase databaseWithPath:@"/tmp/attachme.db"];
  539. FMDBQuickCheck([dbB open]);
  540. FMDBQuickCheck([dbB executeUpdate:@"create table attached (a text)"]);
  541. FMDBQuickCheck(([dbB executeUpdate:@"insert into attached values (?)", @"test"]));
  542. FMDBQuickCheck([dbB close]);
  543. [db executeUpdate:@"attach database '/tmp/attachme.db' as attack"];
  544. rs = [db executeQuery:@"select * from attack.attached"];
  545. FMDBQuickCheck([rs next]);
  546. [rs close];
  547. }
  548. {
  549. // -------------------------------------------------------------------------------
  550. // Named parameters.
  551. FMDBQuickCheck([db executeUpdate:@"create table namedparamtest (a text, b text, c integer, d double)"]);
  552. NSMutableDictionary *dictionaryArgs = [NSMutableDictionary dictionary];
  553. [dictionaryArgs setObject:@"Text1" forKey:@"a"];
  554. [dictionaryArgs setObject:@"Text2" forKey:@"b"];
  555. [dictionaryArgs setObject:[NSNumber numberWithInt:1] forKey:@"c"];
  556. [dictionaryArgs setObject:[NSNumber numberWithDouble:2.0] forKey:@"d"];
  557. FMDBQuickCheck([db executeUpdate:@"insert into namedparamtest values (:a, :b, :c, :d)" withParameterDictionary:dictionaryArgs]);
  558. rs = [db executeQuery:@"select * from namedparamtest"];
  559. FMDBQuickCheck((rs != nil));
  560. [rs next];
  561. FMDBQuickCheck([[rs stringForColumn:@"a"] isEqualToString:@"Text1"]);
  562. FMDBQuickCheck([[rs stringForColumn:@"b"] isEqualToString:@"Text2"]);
  563. FMDBQuickCheck([rs intForColumn:@"c"] == 1);
  564. FMDBQuickCheck([rs doubleForColumn:@"d"] == 2.0);
  565. [rs close];
  566. dictionaryArgs = [NSMutableDictionary dictionary];
  567. [dictionaryArgs setObject:@"Text2" forKey:@"blah"];
  568. rs = [db executeQuery:@"select * from namedparamtest where b = :blah" withParameterDictionary:dictionaryArgs];
  569. FMDBQuickCheck((rs != nil));
  570. FMDBQuickCheck([rs next]);
  571. FMDBQuickCheck([[rs stringForColumn:@"b"] isEqualToString:@"Text2"]);
  572. [rs close];
  573. }
  574. // just for fun.
  575. rs = [db executeQuery:@"pragma database_list"];
  576. while ([rs next]) {
  577. NSString *file = [rs stringForColumn:@"file"];
  578. NSLog(@"database_list: %@", file);
  579. }
  580. // print out some stats if we are using cached statements.
  581. if ([db shouldCacheStatements]) {
  582. NSEnumerator *e = [[db cachedStatements] objectEnumerator];;
  583. FMStatement *statement;
  584. while ((statement = [e nextObject])) {
  585. NSLog(@"%@", statement);
  586. }
  587. }
  588. [db setShouldCacheStatements:true];
  589. [db executeUpdate:@"CREATE TABLE testCacheStatements(key INTEGER PRIMARY KEY, value INTEGER)"];
  590. [db executeUpdate:@"INSERT INTO testCacheStatements (key, value) VALUES (1, 2)"];
  591. [db executeUpdate:@"INSERT INTO testCacheStatements (key, value) VALUES (2, 4)"];
  592. FMDBQuickCheck([[db executeQuery:@"SELECT * FROM testCacheStatements WHERE key=1"] next]);
  593. FMDBQuickCheck([[db executeQuery:@"SELECT * FROM testCacheStatements WHERE key=1"] next]);
  594. [db close];
  595. testPool(dbPath);
  596. testDateFormat();
  597. FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:dbPath];
  598. FMDBQuickCheck(queue);
  599. {
  600. [queue inDatabase:^(FMDatabase *adb) {
  601. [adb executeUpdate:@"create table qfoo (foo text)"];
  602. [adb executeUpdate:@"insert into qfoo values ('hi')"];
  603. [adb executeUpdate:@"insert into qfoo values ('hello')"];
  604. [adb executeUpdate:@"insert into qfoo values ('not')"];
  605. int count = 0;
  606. FMResultSet *rsl = [adb executeQuery:@"select * from qfoo where foo like 'h%'"];
  607. while ([rsl next]) {
  608. count++;
  609. }
  610. FMDBQuickCheck(count == 2);
  611. count = 0;
  612. rsl = [adb executeQuery:@"select * from qfoo where foo like ?", @"h%"];
  613. while ([rsl next]) {
  614. count++;
  615. }
  616. FMDBQuickCheck(count == 2);
  617. }];
  618. }
  619. FMDatabaseQueue *queue2 = [FMDatabaseQueue databaseQueueWithPath:dbPath flags:SQLITE_OPEN_READONLY];
  620. FMDBQuickCheck(queue2);
  621. {
  622. [queue2 inDatabase:^(FMDatabase *db2) {
  623. FMResultSet *rs1 = [db2 executeQuery:@"SELECT * FROM test"];
  624. FMDBQuickCheck(rs1 != nil);
  625. [rs1 close];
  626. BOOL ok = [db2 executeUpdate:@"insert into easy values (?)", [NSNumber numberWithInt:3]];
  627. FMDBQuickCheck(!ok);
  628. }];
  629. [queue2 close];
  630. [queue2 inDatabase:^(FMDatabase *db2) {
  631. FMResultSet *rs1 = [db2 executeQuery:@"SELECT * FROM test"];
  632. FMDBQuickCheck(rs1 != nil);
  633. [rs1 close];
  634. BOOL ok = [db2 executeUpdate:@"insert into easy values (?)", [NSNumber numberWithInt:3]];
  635. FMDBQuickCheck(!ok);
  636. }];
  637. }
  638. {
  639. // You should see pairs of numbers show up in stdout for this stuff:
  640. size_t ops = 16;
  641. dispatch_queue_t dqueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
  642. dispatch_apply(ops, dqueue, ^(size_t nby) {
  643. // just mix things up a bit for demonstration purposes.
  644. if (nby % 2 == 1) {
  645. [NSThread sleepForTimeInterval:.1];
  646. [queue inTransaction:^(FMDatabase *adb, BOOL *rollback) {
  647. NSLog(@"Starting query %ld", nby);
  648. FMResultSet *rsl = [adb executeQuery:@"select * from qfoo where foo like 'h%'"];
  649. while ([rsl next]) {
  650. ;// whatever.
  651. }
  652. NSLog(@"Ending query %ld", nby);
  653. }];
  654. }
  655. if (nby % 3 == 1) {
  656. [NSThread sleepForTimeInterval:.1];
  657. }
  658. [queue inTransaction:^(FMDatabase *adb, BOOL *rollback) {
  659. NSLog(@"Starting update %ld", nby);
  660. [adb executeUpdate:@"insert into qfoo values ('1')"];
  661. [adb executeUpdate:@"insert into qfoo values ('2')"];
  662. [adb executeUpdate:@"insert into qfoo values ('3')"];
  663. NSLog(@"Ending update %ld", nby);
  664. }];
  665. });
  666. [queue close];
  667. [queue inDatabase:^(FMDatabase *adb) {
  668. FMDBQuickCheck([adb executeUpdate:@"insert into qfoo values ('1')"]);
  669. }];
  670. }
  671. {
  672. [queue inDatabase:^(FMDatabase *adb) {
  673. [adb executeUpdate:@"create table colNameTest (a, b, c, d)"];
  674. FMDBQuickCheck([adb executeUpdate:@"insert into colNameTest values (1, 2, 3, 4)"]);
  675. FMResultSet *ars = [adb executeQuery:@"select * from colNameTest"];
  676. NSDictionary *d = [ars columnNameToIndexMap];
  677. FMDBQuickCheck([d count] == 4);
  678. FMDBQuickCheck([[d objectForKey:@"a"] intValue] == 0);
  679. FMDBQuickCheck([[d objectForKey:@"b"] intValue] == 1);
  680. FMDBQuickCheck([[d objectForKey:@"c"] intValue] == 2);
  681. FMDBQuickCheck([[d objectForKey:@"d"] intValue] == 3);
  682. [ars close];
  683. }];
  684. }
  685. {
  686. [queue inDatabase:^(FMDatabase *adb) {
  687. [adb executeUpdate:@"create table transtest (a integer)"];
  688. FMDBQuickCheck([adb executeUpdate:@"insert into transtest values (1)"]);
  689. FMDBQuickCheck([adb executeUpdate:@"insert into transtest values (2)"]);
  690. int rowCount = 0;
  691. FMResultSet *ars = [adb executeQuery:@"select * from transtest"];
  692. while ([ars next]) {
  693. rowCount++;
  694. }
  695. FMDBQuickCheck(rowCount == 2);
  696. }];
  697. [queue inTransaction:^(FMDatabase *adb, BOOL *rollback) {
  698. FMDBQuickCheck([adb executeUpdate:@"insert into transtest values (3)"]);
  699. if (YES) {
  700. // uh oh!, something went wrong (not really, this is just a test
  701. *rollback = YES;
  702. return;
  703. }
  704. FMDBQuickCheck([adb executeUpdate:@"insert into transtest values (4)"]);
  705. }];
  706. [queue inDatabase:^(FMDatabase *adb) {
  707. int rowCount = 0;
  708. FMResultSet *ars = [adb executeQuery:@"select * from transtest"];
  709. while ([ars next]) {
  710. rowCount++;
  711. }
  712. FMDBQuickCheck(![adb hasOpenResultSets]);
  713. NSLog(@"after rollback, rowCount is %d (should be 2)", rowCount);
  714. FMDBQuickCheck(rowCount == 2);
  715. }];
  716. }
  717. // hey, let's make a custom function!
  718. [queue inDatabase:^(FMDatabase *adb) {
  719. [adb executeUpdate:@"create table ftest (foo text)"];
  720. [adb executeUpdate:@"insert into ftest values ('hello')"];
  721. [adb executeUpdate:@"insert into ftest values ('hi')"];
  722. [adb executeUpdate:@"insert into ftest values ('not h!')"];
  723. [adb executeUpdate:@"insert into ftest values ('definitely not h!')"];
  724. [adb makeFunctionNamed:@"StringStartsWithH" maximumArguments:1 withBlock:^(sqlite3_context *context, int aargc, sqlite3_value **aargv) {
  725. if (sqlite3_value_type(aargv[0]) == SQLITE_TEXT) {
  726. @autoreleasepool {
  727. const char *c = (const char *)sqlite3_value_text(aargv[0]);
  728. NSString *s = [NSString stringWithUTF8String:c];
  729. sqlite3_result_int(context, [s hasPrefix:@"h"]);
  730. }
  731. }
  732. else {
  733. NSLog(@"Unknown formart for StringStartsWithH (%d) %s:%d", sqlite3_value_type(aargv[0]), __FUNCTION__, __LINE__);
  734. sqlite3_result_null(context);
  735. }
  736. }];
  737. int rowCount = 0;
  738. FMResultSet *ars = [adb executeQuery:@"select * from ftest where StringStartsWithH(foo)"];
  739. while ([ars next]) {
  740. rowCount++;
  741. NSLog(@"Does %@ start with 'h'?", [rs stringForColumnIndex:0]);
  742. }
  743. FMDBQuickCheck(rowCount == 2);
  744. testStatementCaching();
  745. }];
  746. //Example for splitting batch statement
  747. {
  748. NSArray *batchStringArray = @[@"insert into ftest values ('hello;');",
  749. @"insert into ftest values ('hi;');",
  750. @"insert into ftest values ('not h!\\\\');",
  751. @"insert into ftest values ('definitely not h!')"];
  752. NSMutableString *batchStatement = [NSMutableString string];
  753. for (NSString *str in batchStringArray)
  754. {
  755. [batchStatement appendString:str];
  756. }
  757. NSArray *statements = [[FMSQLStatementSplitter sharedInstance] statementsFromBatchSqlStatement:batchStatement];
  758. NSLog(@"Number of sqlitted statements is %lu (should be %lu)", (unsigned long)statements.count, (unsigned long)batchStringArray.count);
  759. if (statements.count == batchStringArray.count)
  760. {
  761. for (NSUInteger splittedIndex = 0; splittedIndex < statements.count; splittedIndex++)
  762. {
  763. NSString *originalStatement = batchStringArray[splittedIndex];
  764. NSString *splittedStatement = ((FMSplittedStatement *)statements[splittedIndex]).statementString;
  765. if (![originalStatement isEqualToString:splittedStatement])
  766. {
  767. NSLog(@"Splitter failed! Original batch string is %@", batchStatement);
  768. }
  769. }
  770. }
  771. [queue inDatabase:^(FMDatabase *adb) {
  772. for (FMSplittedStatement *sqlittedStatement in statements)
  773. {
  774. [adb executeUpdate:sqlittedStatement.statementString];
  775. }
  776. }];
  777. }
  778. NSLog(@"That was version %@ of sqlite", [FMDatabase sqliteLibVersion]);
  779. }// this is the end of our @autorelease pool.
  780. return 0;
  781. }
  782. /*
  783. Test statement caching
  784. This test checks the fixes that address https://github.com/ccgus/fmdb/issues/6
  785. */
  786. void testStatementCaching() {
  787. FMDatabase *db = [FMDatabase databaseWithPath:nil]; // use in-memory DB
  788. [db open];
  789. [db executeUpdate:@"DROP TABLE IF EXISTS testStatementCaching"];
  790. [db executeUpdate:@"CREATE TABLE testStatementCaching ( value INTEGER )"];
  791. [db executeUpdate:@"INSERT INTO testStatementCaching( value ) VALUES (1)"];
  792. [db executeUpdate:@"INSERT INTO testStatementCaching( value ) VALUES (1)"];
  793. [db executeUpdate:@"INSERT INTO testStatementCaching( value ) VALUES (2)"];
  794. [db setShouldCacheStatements:YES];
  795. // two iterations.
  796. // the first time through no statements will be from the cache.
  797. // the second time through all statements come from the cache.
  798. for (int i = 1; i <= 2; i++ ) {
  799. FMResultSet* rs1 = [db executeQuery: @"SELECT rowid, * FROM testStatementCaching WHERE value = ?", @1]; // results in 2 rows...
  800. FMDBQuickCheck([rs1 next]);
  801. // confirm that we're seeing the benefits of caching.
  802. FMDBQuickCheck([[rs1 statement] useCount] == i);
  803. FMResultSet* rs2 = [db executeQuery:@"SELECT rowid, * FROM testStatementCaching WHERE value = ?", @2]; // results in 1 row
  804. FMDBQuickCheck([rs2 next]);
  805. FMDBQuickCheck([[rs2 statement] useCount] == i);
  806. // This is the primary check - with the old implementation of statement caching, rs2 would have rejiggered the (cached) statement used by rs1, making this test fail to return the 2nd row in rs1.
  807. FMDBQuickCheck([rs1 next]);
  808. [rs1 close];
  809. [rs2 close];
  810. }
  811. [db close];
  812. }
  813. /*
  814. Test the various FMDatabasePool things.
  815. */
  816. void testPool(NSString *dbPath) {
  817. FMDatabasePool *dbPool = [FMDatabasePool databasePoolWithPath:dbPath];
  818. FMDBQuickCheck([dbPool countOfOpenDatabases] == 0);
  819. __block FMDatabase *db1;
  820. [dbPool inDatabase:^(FMDatabase *db) {
  821. FMDBQuickCheck([dbPool countOfOpenDatabases] == 1);
  822. FMDBQuickCheck([db tableExists:@"t4"]);
  823. db1 = db;
  824. }];
  825. [dbPool inDatabase:^(FMDatabase *db) {
  826. FMDBQuickCheck(db1 == db);
  827. [dbPool inDatabase:^(FMDatabase *db2) {
  828. FMDBQuickCheck(db2 != db);
  829. }];
  830. }];
  831. FMDBQuickCheck([dbPool countOfOpenDatabases] == 2);
  832. [dbPool inDatabase:^(FMDatabase *db) {
  833. [db executeUpdate:@"create table easy (a text)"];
  834. [db executeUpdate:@"create table easy2 (a text)"];
  835. }];
  836. FMDBQuickCheck([dbPool countOfOpenDatabases] == 2);
  837. [dbPool releaseAllDatabases];
  838. FMDBQuickCheck([dbPool countOfOpenDatabases] == 0);
  839. [dbPool inDatabase:^(FMDatabase *aDb) {
  840. FMDBQuickCheck([dbPool countOfCheckedInDatabases] == 0);
  841. FMDBQuickCheck([dbPool countOfCheckedOutDatabases] == 1);
  842. FMDBQuickCheck([aDb tableExists:@"t4"]);
  843. FMDBQuickCheck([dbPool countOfCheckedInDatabases] == 0);
  844. FMDBQuickCheck([dbPool countOfCheckedOutDatabases] == 1);
  845. FMDBQuickCheck(([aDb executeUpdate:@"insert into easy (a) values (?)", @"hi"]));
  846. // just for fun.
  847. FMResultSet *rs2 = [aDb executeQuery:@"select * from easy"];
  848. FMDBQuickCheck([rs2 next]);
  849. while ([rs2 next]) { ; } // whatevers.
  850. FMDBQuickCheck([dbPool countOfOpenDatabases] == 1);
  851. FMDBQuickCheck([dbPool countOfCheckedInDatabases] == 0);
  852. FMDBQuickCheck([dbPool countOfCheckedOutDatabases] == 1);
  853. }];
  854. FMDBQuickCheck([dbPool countOfOpenDatabases] == 1);
  855. {
  856. [dbPool inDatabase:^(FMDatabase *db) {
  857. [db executeUpdate:@"insert into easy values (?)", [NSNumber numberWithInt:1]];
  858. [db executeUpdate:@"insert into easy values (?)", [NSNumber numberWithInt:2]];
  859. [db executeUpdate:@"insert into easy values (?)", [NSNumber numberWithInt:3]];
  860. FMDBQuickCheck([dbPool countOfCheckedInDatabases] == 0);
  861. FMDBQuickCheck([dbPool countOfCheckedOutDatabases] == 1);
  862. }];
  863. }
  864. FMDBQuickCheck([dbPool countOfOpenDatabases] == 1);
  865. [dbPool setMaximumNumberOfDatabasesToCreate:2];
  866. [dbPool inDatabase:^(FMDatabase *db) {
  867. [dbPool inDatabase:^(FMDatabase *db2) {
  868. [dbPool inDatabase:^(FMDatabase *db3) {
  869. FMDBQuickCheck([dbPool countOfOpenDatabases] == 2);
  870. FMDBQuickCheck(!db3);
  871. }];
  872. }];
  873. }];
  874. [dbPool setMaximumNumberOfDatabasesToCreate:0];
  875. [dbPool releaseAllDatabases];
  876. FMDBQuickCheck([dbPool countOfOpenDatabases] == 0);
  877. [dbPool inDatabase:^(FMDatabase *db) {
  878. [db executeUpdate:@"insert into easy values (?)", [NSNumber numberWithInt:3]];
  879. }];
  880. FMDBQuickCheck([dbPool countOfOpenDatabases] == 1);
  881. [dbPool inTransaction:^(FMDatabase *adb, BOOL *rollback) {
  882. [adb executeUpdate:@"insert into easy values (?)", [NSNumber numberWithInt:1001]];
  883. [adb executeUpdate:@"insert into easy values (?)", [NSNumber numberWithInt:1002]];
  884. [adb executeUpdate:@"insert into easy values (?)", [NSNumber numberWithInt:1003]];
  885. FMDBQuickCheck([dbPool countOfOpenDatabases] == 1);
  886. FMDBQuickCheck([dbPool countOfCheckedInDatabases] == 0);
  887. FMDBQuickCheck([dbPool countOfCheckedOutDatabases] == 1);
  888. }];
  889. FMDBQuickCheck([dbPool countOfOpenDatabases] == 1);
  890. FMDBQuickCheck([dbPool countOfCheckedInDatabases] == 1);
  891. FMDBQuickCheck([dbPool countOfCheckedOutDatabases] == 0);
  892. [dbPool inDatabase:^(FMDatabase *db) {
  893. FMResultSet *rs2 = [db executeQuery:@"select * from easy where a = ?", [NSNumber numberWithInt:1001]];
  894. FMDBQuickCheck([rs2 next]);
  895. FMDBQuickCheck(![rs2 next]);
  896. }];
  897. [dbPool inDeferredTransaction:^(FMDatabase *adb, BOOL *rollback) {
  898. [adb executeUpdate:@"insert into easy values (?)", [NSNumber numberWithInt:1004]];
  899. [adb executeUpdate:@"insert into easy values (?)", [NSNumber numberWithInt:1005]];
  900. *rollback = YES;
  901. }];
  902. FMDBQuickCheck([dbPool countOfOpenDatabases] == 1);
  903. FMDBQuickCheck([dbPool countOfCheckedInDatabases] == 1);
  904. FMDBQuickCheck([dbPool countOfCheckedOutDatabases] == 0);
  905. NSError *err = [dbPool inSavePoint:^(FMDatabase *db, BOOL *rollback) {
  906. [db executeUpdate:@"insert into easy values (?)", [NSNumber numberWithInt:1006]];
  907. }];
  908. FMDBQuickCheck(!err);
  909. {
  910. err = [dbPool inSavePoint:^(FMDatabase *adb, BOOL *rollback) {
  911. FMDBQuickCheck(![adb hadError]);
  912. [adb executeUpdate:@"insert into easy values (?)", [NSNumber numberWithInt:1009]];
  913. [adb inSavePoint:^(BOOL *arollback) {
  914. FMDBQuickCheck(([adb executeUpdate:@"insert into easy values (?)", [NSNumber numberWithInt:1010]]));
  915. *arollback = YES;
  916. }];
  917. }];
  918. FMDBQuickCheck(!err);
  919. [dbPool inDatabase:^(FMDatabase *db) {
  920. FMResultSet *rs2 = [db executeQuery:@"select * from easy where a = ?", [NSNumber numberWithInt:1009]];
  921. FMDBQuickCheck([rs2 next]);
  922. FMDBQuickCheck(![rs2 next]); // close it out.
  923. rs2 = [db executeQuery:@"select * from easy where a = ?", [NSNumber numberWithInt:1010]];
  924. FMDBQuickCheck(![rs2 next]);
  925. }];
  926. }
  927. {
  928. [dbPool inDatabase:^(FMDatabase *db) {
  929. [db executeUpdate:@"create table likefoo (foo text)"];
  930. [db executeUpdate:@"insert into likefoo values ('hi')"];
  931. [db executeUpdate:@"insert into likefoo values ('hello')"];
  932. [db executeUpdate:@"insert into likefoo values ('not')"];
  933. int count = 0;
  934. FMResultSet *rsl = [db executeQuery:@"select * from likefoo where foo like 'h%'"];
  935. while ([rsl next]) {
  936. count++;
  937. }
  938. FMDBQuickCheck(count == 2);
  939. count = 0;
  940. rsl = [db executeQuery:@"select * from likefoo where foo like ?", @"h%"];
  941. while ([rsl next]) {
  942. count++;
  943. }
  944. FMDBQuickCheck(count == 2);
  945. }];
  946. }
  947. {
  948. size_t ops = 128;
  949. dispatch_queue_t dqueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
  950. dispatch_apply(ops, dqueue, ^(size_t nby) {
  951. // just mix things up a bit for demonstration purposes.
  952. if (nby % 2 == 1) {
  953. [NSThread sleepForTimeInterval:.1];
  954. }
  955. [dbPool inDatabase:^(FMDatabase *db) {
  956. NSLog(@"Starting query %ld", nby);
  957. FMResultSet *rsl = [db executeQuery:@"select * from likefoo where foo like 'h%'"];
  958. while ([rsl next]) {
  959. if (nby % 3 == 1) {
  960. [NSThread sleepForTimeInterval:.05];
  961. }
  962. }
  963. NSLog(@"Ending query %ld", nby);
  964. }];
  965. });
  966. NSLog(@"Number of open databases after crazy gcd stuff: %ld", [dbPool countOfOpenDatabases]);
  967. }
  968. FMDatabasePool *dbPool2 = [FMDatabasePool databasePoolWithPath:dbPath flags:SQLITE_OPEN_READONLY];
  969. FMDBQuickCheck(dbPool2);
  970. {
  971. [dbPool2 inDatabase:^(FMDatabase *db2) {
  972. FMResultSet *rs1 = [db2 executeQuery:@"SELECT * FROM test"];
  973. FMDBQuickCheck(rs1 != nil);
  974. [rs1 close];
  975. BOOL ok = [db2 executeUpdate:@"insert into easy values (?)", [NSNumber numberWithInt:3]];
  976. FMDBQuickCheck(!ok);
  977. }];
  978. }
  979. // if you want to see a deadlock, just uncomment this line and run:
  980. //#define ONLY_USE_THE_POOL_IF_YOU_ARE_DOING_READS_OTHERWISE_YOULL_DEADLOCK_USE_FMDATABASEQUEUE_INSTEAD 1
  981. #ifdef ONLY_USE_THE_POOL_IF_YOU_ARE_DOING_READS_OTHERWISE_YOULL_DEADLOCK_USE_FMDATABASEQUEUE_INSTEAD
  982. {
  983. int ops = 16;
  984. dispatch_queue_t dqueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
  985. dispatch_apply(ops, dqueue, ^(size_t nby) {
  986. // just mix things up a bit for demonstration purposes.
  987. if (nby % 2 == 1) {
  988. [NSThread sleepForTimeInterval:.1];
  989. [dbPool inTransaction:^(FMDatabase *db, BOOL *rollback) {
  990. NSLog(@"Starting query %ld", nby);
  991. FMResultSet *rsl = [db executeQuery:@"select * from likefoo where foo like 'h%'"];
  992. while ([rsl next]) {
  993. ;// whatever.
  994. }
  995. NSLog(@"Ending query %ld", nby);
  996. }];
  997. }
  998. if (nby % 3 == 1) {
  999. [NSThread sleepForTimeInterval:.1];
  1000. }
  1001. [dbPool inTransaction:^(FMDatabase *db, BOOL *rollback) {
  1002. NSLog(@"Starting update %ld", nby);
  1003. [db executeUpdate:@"insert into likefoo values ('1')"];
  1004. [db executeUpdate:@"insert into likefoo values ('2')"];
  1005. [db executeUpdate:@"insert into likefoo values ('3')"];
  1006. NSLog(@"Ending update %ld", nby);
  1007. }];
  1008. });
  1009. [dbPool releaseAllDatabases];
  1010. [dbPool inDatabase:^(FMDatabase *db) {
  1011. FMDBQuickCheck([db executeUpdate:@"insert into likefoo values ('1')"]);
  1012. }];
  1013. }
  1014. #endif
  1015. }
  1016. /*
  1017. Test the date format
  1018. */
  1019. void testOneDateFormat( FMDatabase *db, NSDate *testDate ) {
  1020. [db executeUpdate:@"DROP TABLE IF EXISTS test_format"];
  1021. [db executeUpdate:@"CREATE TABLE test_format ( test TEXT )"];
  1022. [db executeUpdate:@"INSERT INTO test_format(test) VALUES (?)", testDate];
  1023. FMResultSet *rs = [db executeQuery:@"SELECT test FROM test_format"];
  1024. if ([rs next]) {
  1025. NSDate *found = [rs dateForColumnIndex:0];
  1026. if (NSOrderedSame != [testDate compare:found]) {
  1027. NSLog(@"Did not get back what we stored.");
  1028. }
  1029. }
  1030. else {
  1031. NSLog(@"Insertion borked");
  1032. }
  1033. [rs close];
  1034. }
  1035. void testDateFormat() {
  1036. FMDatabase *db = [FMDatabase databaseWithPath:nil]; // use in-memory DB
  1037. [db open];
  1038. NSDateFormatter *fmt = [FMDatabase storeableDateFormat:@"yyyy-MM-dd HH:mm:ss"];
  1039. NSDate *testDate = [fmt dateFromString:@"2013-02-20 12:00:00"];
  1040. // test timestamp dates (ensuring our change does not break those)
  1041. testOneDateFormat(db,testDate);
  1042. // now test the string-based timestamp
  1043. [db setDateFormat:fmt];
  1044. testOneDateFormat(db, testDate);
  1045. [db close];
  1046. }
  1047. /*
  1048. What is this function for? Think of it as a template which a developer can use
  1049. to report bugs.
  1050. If you have a bug, make it reproduce in this function and then let the
  1051. developer(s) know either via the github bug reporter or the mailing list.
  1052. */
  1053. void FMDBReportABugFunction() {
  1054. NSString *dbPath = @"/tmp/bugreportsample.db";
  1055. // delete the old db if it exists
  1056. NSFileManager *fileManager = [NSFileManager defaultManager];
  1057. [fileManager removeItemAtPath:dbPath error:nil];
  1058. FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:dbPath];
  1059. [queue inDatabase:^(FMDatabase *db) {
  1060. /*
  1061. Change the contents of this block to suit your needs.
  1062. */
  1063. BOOL worked = [db executeUpdate:@"create table test (a text, b text, c integer, d double, e double)"];
  1064. FMDBQuickCheck(worked);
  1065. worked = [db executeUpdate:@"insert into test values ('a', 'b', 1, 2.2, 2.3)"];
  1066. FMDBQuickCheck(worked);
  1067. FMResultSet *rs = [db executeQuery:@"select * from test"];
  1068. FMDBQuickCheck([rs next]);
  1069. [rs close];
  1070. }];
  1071. [queue close];
  1072. // uncomment the following line if you don't want to run through all the other tests.
  1073. //exit(0);
  1074. }