FMDatabaseTests.m 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871
  1. //
  2. // Tests.m
  3. // Tests
  4. //
  5. // Created by Graham Dennis on 24/11/2013.
  6. //
  7. //
  8. #import "FMDBTempDBTests.h"
  9. #import "FMDatabase.h"
  10. @interface FMDatabaseTests : FMDBTempDBTests
  11. @end
  12. @implementation FMDatabaseTests
  13. + (void)populateDatabase:(FMDatabase *)db
  14. {
  15. [db executeUpdate:@"create table test (a text, b text, c integer, d double, e double)"];
  16. [db beginTransaction];
  17. int i = 0;
  18. while (i++ < 20) {
  19. [db executeUpdate:@"insert into test (a, b, c, d, e) values (?, ?, ?, ?, ?)" ,
  20. @"hi'", // look! I put in a ', and I'm not escaping it!
  21. [NSString stringWithFormat:@"number %d", i],
  22. [NSNumber numberWithInt:i],
  23. [NSDate date],
  24. [NSNumber numberWithFloat:2.2f]];
  25. }
  26. [db commit];
  27. // do it again, just because
  28. [db beginTransaction];
  29. i = 0;
  30. while (i++ < 20) {
  31. [db executeUpdate:@"insert into test (a, b, c, d, e) values (?, ?, ?, ?, ?)" ,
  32. @"hi again'", // look! I put in a ', and I'm not escaping it!
  33. [NSString stringWithFormat:@"number %d", i],
  34. [NSNumber numberWithInt:i],
  35. [NSDate date],
  36. [NSNumber numberWithFloat:2.2f]];
  37. }
  38. [db commit];
  39. [db executeUpdate:@"create table t3 (a somevalue)"];
  40. [db beginTransaction];
  41. for (int i=0; i < 20; i++) {
  42. [db executeUpdate:@"insert into t3 (a) values (?)", [NSNumber numberWithInt:i]];
  43. }
  44. [db commit];
  45. }
  46. - (void)setUp
  47. {
  48. [super setUp];
  49. // Put setup code here. This method is called before the invocation of each test method in the class.
  50. }
  51. - (void)tearDown
  52. {
  53. // Put teardown code here. This method is called after the invocation of each test method in the class.
  54. [super tearDown];
  55. }
  56. - (void)testFailOnUnopenedDatabase
  57. {
  58. [self.db close];
  59. XCTAssertNil([self.db executeQuery:@"select * from table"], @"Shouldn't get results from an empty table");
  60. XCTAssertTrue([self.db hadError], @"Should have failed");
  61. }
  62. - (void)testFailOnBadStatement
  63. {
  64. XCTAssertFalse([self.db executeUpdate:@"blah blah blah"], @"Invalid statement should fail");
  65. XCTAssertTrue([self.db hadError], @"Should have failed");
  66. }
  67. - (void)testFailOnBadStatementWithError
  68. {
  69. NSError *error = nil;
  70. XCTAssertFalse([self.db executeUpdate:@"blah blah blah" withErrorAndBindings:&error], @"Invalid statement should fail");
  71. XCTAssertNotNil(error, @"Should have a non-nil NSError");
  72. XCTAssertEqual([error code], (NSInteger)SQLITE_ERROR, @"Error should be SQLITE_ERROR");
  73. }
  74. - (void)testPragmaJournalMode
  75. {
  76. FMResultSet *ps = [self.db executeQuery:@"pragma journal_mode=delete"];
  77. XCTAssertFalse([self.db hadError], @"pragma should have succeeded");
  78. XCTAssertNotNil(ps, @"Result set should be non-nil");
  79. XCTAssertTrue([ps next], @"Result set should have a next result");
  80. [ps close];
  81. }
  82. - (void)testPragmaPageSize
  83. {
  84. [self.db executeUpdate:@"PRAGMA page_size=2048"];
  85. XCTAssertFalse([self.db hadError], @"pragma should have succeeded");
  86. }
  87. - (void)testVacuum
  88. {
  89. [self.db executeUpdate:@"VACUUM"];
  90. XCTAssertFalse([self.db hadError], @"VACUUM should have succeeded");
  91. }
  92. - (void)testSelectULL
  93. {
  94. // Unsigned long long
  95. [self.db executeUpdate:@"create table ull (a integer)"];
  96. [self.db executeUpdate:@"insert into ull (a) values (?)", [NSNumber numberWithUnsignedLongLong:ULLONG_MAX]];
  97. XCTAssertFalse([self.db hadError], @"Shouldn't have any errors");
  98. FMResultSet *rs = [self.db executeQuery:@"select a from ull"];
  99. while ([rs next]) {
  100. XCTAssertEqual([rs unsignedLongLongIntForColumnIndex:0], ULLONG_MAX, @"Result should be ULLONG_MAX");
  101. XCTAssertEqual([rs unsignedLongLongIntForColumn:@"a"], ULLONG_MAX, @"Result should be ULLONG_MAX");
  102. }
  103. [rs close];
  104. XCTAssertFalse([self.db hasOpenResultSets], @"Shouldn't have any open result sets");
  105. XCTAssertFalse([self.db hadError], @"Shouldn't have any errors");
  106. }
  107. - (void)testSelectByColumnName
  108. {
  109. FMResultSet *rs = [self.db executeQuery:@"select rowid,* from test where a = ?", @"hi"];
  110. XCTAssertNotNil(rs, @"Should have a non-nil result set");
  111. while ([rs next]) {
  112. [rs intForColumn:@"c"];
  113. XCTAssertNotNil([rs stringForColumn:@"b"], @"Should have non-nil string for 'b'");
  114. XCTAssertNotNil([rs stringForColumn:@"a"], @"Should have non-nil string for 'a'");
  115. XCTAssertNotNil([rs stringForColumn:@"rowid"], @"Should have non-nil string for 'rowid'");
  116. XCTAssertNotNil([rs dateForColumn:@"d"], @"Should have non-nil date for 'd'");
  117. [rs doubleForColumn:@"d"];
  118. [rs doubleForColumn:@"e"];
  119. XCTAssertEqualObjects([rs columnNameForIndex:0], @"rowid", @"Wrong column name for result set column number");
  120. XCTAssertEqualObjects([rs columnNameForIndex:1], @"a", @"Wrong column name for result set column number");
  121. }
  122. [rs close];
  123. XCTAssertFalse([self.db hasOpenResultSets], @"Shouldn't have any open result sets");
  124. XCTAssertFalse([self.db hadError], @"Shouldn't have any errors");
  125. }
  126. - (void)testSelectWithIndexedAndKeyedSubscript
  127. {
  128. FMResultSet *rs = [self.db executeQuery:@"select rowid, a, b, c from test"];
  129. XCTAssertNotNil(rs, @"Should have a non-nil result set");
  130. while ([rs next]) {
  131. XCTAssertEqualObjects(rs[0], rs[@"rowid"], @"Column zero should be equal to 'rowid'");
  132. XCTAssertEqualObjects(rs[1], rs[@"a"], @"Column 1 should be equal to 'a'");
  133. XCTAssertEqualObjects(rs[2], rs[@"b"], @"Column 2 should be equal to 'b'");
  134. XCTAssertEqualObjects(rs[3], rs[@"c"], @"Column 3 should be equal to 'c'");
  135. }
  136. [rs close];
  137. XCTAssertFalse([self.db hasOpenResultSets], @"Shouldn't have any open result sets");
  138. XCTAssertFalse([self.db hadError], @"Shouldn't have any errors");
  139. }
  140. - (void)testBusyRetryTimeout
  141. {
  142. [self.db executeUpdate:@"create table t1 (a integer)"];
  143. [self.db executeUpdate:@"insert into t1 values (?)", [NSNumber numberWithInt:5]];
  144. [self.db setMaxBusyRetryTimeInterval:2];
  145. FMDatabase *newDB = [FMDatabase databaseWithPath:self.databasePath];
  146. [newDB open];
  147. FMResultSet *rs = [newDB executeQuery:@"select rowid,* from test where a = ?", @"hi'"];
  148. [rs next]; // just grab one... which will keep the db locked
  149. XCTAssertFalse([self.db executeUpdate:@"insert into t1 values (5)"], @"Insert should fail because the db is locked by a read");
  150. XCTAssertEqual([self.db lastErrorCode], SQLITE_BUSY, @"SQLITE_BUSY should be the last error");
  151. [rs close];
  152. [newDB close];
  153. XCTAssertTrue([self.db executeUpdate:@"insert into t1 values (5)"], @"The database shouldn't be locked at this point");
  154. }
  155. - (void)testCaseSensitiveResultDictionary
  156. {
  157. // case sensitive result dictionary test
  158. [self.db executeUpdate:@"create table cs (aRowName integer, bRowName text)"];
  159. [self.db executeUpdate:@"insert into cs (aRowName, bRowName) values (?, ?)", [NSNumber numberWithBool:1], @"hello"];
  160. XCTAssertFalse([self.db hadError], @"Shouldn't have any errors");
  161. FMResultSet *rs = [self.db executeQuery:@"select * from cs"];
  162. while ([rs next]) {
  163. NSDictionary *d = [rs resultDictionary];
  164. XCTAssertNotNil([d objectForKey:@"aRowName"], @"aRowName should be non-nil");
  165. XCTAssertNil([d objectForKey:@"arowname"], @"arowname should be nil");
  166. XCTAssertNotNil([d objectForKey:@"bRowName"], @"bRowName should be non-nil");
  167. XCTAssertNil([d objectForKey:@"browname"], @"browname should be nil");
  168. }
  169. [rs close];
  170. XCTAssertFalse([self.db hasOpenResultSets], @"Shouldn't have any open result sets");
  171. XCTAssertFalse([self.db hadError], @"Shouldn't have any errors");
  172. }
  173. - (void)testBoolInsert
  174. {
  175. [self.db executeUpdate:@"create table btest (aRowName integer)"];
  176. [self.db executeUpdate:@"insert into btest (aRowName) values (?)", [NSNumber numberWithBool:12]];
  177. XCTAssertFalse([self.db hadError], @"Shouldn't have any errors");
  178. FMResultSet *rs = [self.db executeQuery:@"select * from btest"];
  179. while ([rs next]) {
  180. XCTAssertTrue([rs boolForColumnIndex:0], @"first column should be true.");
  181. XCTAssertTrue([rs intForColumnIndex:0] == 1, @"first column should be equal to 1 - it was %d.", [rs intForColumnIndex:0]);
  182. }
  183. [rs close];
  184. XCTAssertFalse([self.db hasOpenResultSets], @"Shouldn't have any open result sets");
  185. XCTAssertFalse([self.db hadError], @"Shouldn't have any errors");
  186. }
  187. - (void)testNamedParametersCount
  188. {
  189. XCTAssertTrue([self.db executeUpdate:@"create table namedparamcounttest (a text, b text, c integer, d double)"]);
  190. NSMutableDictionary *dictionaryArgs = [NSMutableDictionary dictionary];
  191. [dictionaryArgs setObject:@"Text1" forKey:@"a"];
  192. [dictionaryArgs setObject:@"Text2" forKey:@"b"];
  193. [dictionaryArgs setObject:[NSNumber numberWithInt:1] forKey:@"c"];
  194. [dictionaryArgs setObject:[NSNumber numberWithDouble:2.0] forKey:@"d"];
  195. XCTAssertTrue([self.db executeUpdate:@"insert into namedparamcounttest values (:a, :b, :c, :d)" withParameterDictionary:dictionaryArgs]);
  196. FMResultSet *rs = [self.db executeQuery:@"select * from namedparamcounttest"];
  197. XCTAssertNotNil(rs);
  198. [rs next];
  199. XCTAssertEqualObjects([rs stringForColumn:@"a"], @"Text1");
  200. XCTAssertEqualObjects([rs stringForColumn:@"b"], @"Text2");
  201. XCTAssertEqual([rs intForColumn:@"c"], 1);
  202. XCTAssertEqual([rs doubleForColumn:@"d"], 2.0);
  203. [rs close];
  204. // note that at this point, dictionaryArgs has way more values than we need, but the query should still work since
  205. // a is in there, and that's all we need.
  206. rs = [self.db executeQuery:@"select * from namedparamcounttest where a = :a" withParameterDictionary:dictionaryArgs];
  207. XCTAssertNotNil(rs);
  208. XCTAssertTrue([rs next]);
  209. [rs close];
  210. // ***** Please note the following codes *****
  211. dictionaryArgs = [NSMutableDictionary dictionary];
  212. [dictionaryArgs setObject:@"NewText1" forKey:@"a"];
  213. [dictionaryArgs setObject:@"NewText2" forKey:@"b"];
  214. [dictionaryArgs setObject:@"OneMoreText" forKey:@"OneMore"];
  215. XCTAssertTrue([self.db executeUpdate:@"update namedparamcounttest set a = :a, b = :b where b = 'Text2'" withParameterDictionary:dictionaryArgs]);
  216. }
  217. - (void)testBlobs
  218. {
  219. [self.db executeUpdate:@"create table blobTable (a text, b blob)"];
  220. // let's read an image from safari's app bundle.
  221. NSData *safariCompass = [NSData dataWithContentsOfFile:@"/Applications/Safari.app/Contents/Resources/compass.icns"];
  222. if (safariCompass) {
  223. [self.db executeUpdate:@"insert into blobTable (a, b) values (?, ?)", @"safari's compass", safariCompass];
  224. FMResultSet *rs = [self.db executeQuery:@"select b from blobTable where a = ?", @"safari's compass"];
  225. XCTAssertTrue([rs next]);
  226. NSData *readData = [rs dataForColumn:@"b"];
  227. XCTAssertEqualObjects(readData, safariCompass);
  228. // ye shall read the header for this function, or suffer the consequences.
  229. NSData *readDataNoCopy = [rs dataNoCopyForColumn:@"b"];
  230. XCTAssertEqualObjects(readDataNoCopy, safariCompass);
  231. [rs close];
  232. XCTAssertFalse([self.db hasOpenResultSets], @"Shouldn't have any open result sets");
  233. XCTAssertFalse([self.db hadError], @"Shouldn't have any errors");
  234. }
  235. }
  236. - (void)testNullValues
  237. {
  238. [self.db executeUpdate:@"create table t2 (a integer, b integer)"];
  239. BOOL result = [self.db executeUpdate:@"insert into t2 values (?, ?)", nil, [NSNumber numberWithInt:5]];
  240. XCTAssertTrue(result, @"Failed to insert a nil value");
  241. FMResultSet *rs = [self.db executeQuery:@"select * from t2"];
  242. while ([rs next]) {
  243. XCTAssertNil([rs stringForColumnIndex:0], @"Wasn't able to retrieve a null string");
  244. XCTAssertEqualObjects([rs stringForColumnIndex:1], @"5");
  245. }
  246. [rs close];
  247. XCTAssertFalse([self.db hasOpenResultSets], @"Shouldn't have any open result sets");
  248. XCTAssertFalse([self.db hadError], @"Shouldn't have any errors");
  249. }
  250. - (void)testNestedResultSets
  251. {
  252. FMResultSet *rs = [self.db executeQuery:@"select * from t3"];
  253. while ([rs next]) {
  254. int foo = [rs intForColumnIndex:0];
  255. int newVal = foo + 100;
  256. [self.db executeUpdate:@"update t3 set a = ? where a = ?", [NSNumber numberWithInt:newVal], [NSNumber numberWithInt:foo]];
  257. FMResultSet *rs2 = [self.db executeQuery:@"select a from t3 where a = ?", [NSNumber numberWithInt:newVal]];
  258. [rs2 next];
  259. XCTAssertEqual([rs2 intForColumnIndex:0], newVal);
  260. [rs2 close];
  261. }
  262. [rs close];
  263. XCTAssertFalse([self.db hasOpenResultSets], @"Shouldn't have any open result sets");
  264. XCTAssertFalse([self.db hadError], @"Shouldn't have any errors");
  265. }
  266. - (void)testNSNullInsertion
  267. {
  268. [self.db executeUpdate:@"create table nulltest (a text, b text)"];
  269. [self.db executeUpdate:@"insert into nulltest (a, b) values (?, ?)", [NSNull null], @"a"];
  270. [self.db executeUpdate:@"insert into nulltest (a, b) values (?, ?)", nil, @"b"];
  271. FMResultSet *rs = [self.db executeQuery:@"select * from nulltest"];
  272. while ([rs next]) {
  273. XCTAssertNil([rs stringForColumnIndex:0]);
  274. XCTAssertNotNil([rs stringForColumnIndex:1]);
  275. }
  276. [rs close];
  277. XCTAssertFalse([self.db hasOpenResultSets], @"Shouldn't have any open result sets");
  278. XCTAssertFalse([self.db hadError], @"Shouldn't have any errors");
  279. }
  280. - (void)testNullDates
  281. {
  282. NSDate *date = [NSDate date];
  283. [self.db executeUpdate:@"create table datetest (a double, b double, c double)"];
  284. [self.db executeUpdate:@"insert into datetest (a, b, c) values (?, ?, 0)" , [NSNull null], date];
  285. FMResultSet *rs = [self.db executeQuery:@"select * from datetest"];
  286. XCTAssertNotNil(rs);
  287. while ([rs next]) {
  288. NSDate *b = [rs dateForColumnIndex:1];
  289. NSDate *c = [rs dateForColumnIndex:2];
  290. XCTAssertNil([rs dateForColumnIndex:0]);
  291. XCTAssertNotNil(c, @"zero date shouldn't be nil");
  292. XCTAssertEqualWithAccuracy([b timeIntervalSinceDate:date], 0.0, 1.0, @"Dates should be the same to within a second");
  293. XCTAssertEqualWithAccuracy([c timeIntervalSince1970], 0.0, 1.0, @"Dates should be the same to within a second");
  294. }
  295. [rs close];
  296. XCTAssertFalse([self.db hasOpenResultSets], @"Shouldn't have any open result sets");
  297. XCTAssertFalse([self.db hadError], @"Shouldn't have any errors");
  298. }
  299. - (void)testLotsOfNULLs
  300. {
  301. NSData *safariCompass = [NSData dataWithContentsOfFile:@"/Applications/Safari.app/Contents/Resources/compass.icns"];
  302. if (!safariCompass)
  303. return;
  304. [self.db executeUpdate:@"create table nulltest2 (s text, d data, i integer, f double, b integer)"];
  305. [self.db executeUpdate:@"insert into nulltest2 (s, d, i, f, b) values (?, ?, ?, ?, ?)" , @"Hi", safariCompass, [NSNumber numberWithInt:12], [NSNumber numberWithFloat:4.4f], [NSNumber numberWithBool:YES]];
  306. [self.db executeUpdate:@"insert into nulltest2 (s, d, i, f, b) values (?, ?, ?, ?, ?)" , nil, nil, nil, nil, [NSNull null]];
  307. FMResultSet *rs = [self.db executeQuery:@"select * from nulltest2"];
  308. while ([rs next]) {
  309. int i = [rs intForColumnIndex:2];
  310. if (i == 12) {
  311. // it's the first row we inserted.
  312. XCTAssertFalse([rs columnIndexIsNull:0]);
  313. XCTAssertFalse([rs columnIndexIsNull:1]);
  314. XCTAssertFalse([rs columnIndexIsNull:2]);
  315. XCTAssertFalse([rs columnIndexIsNull:3]);
  316. XCTAssertFalse([rs columnIndexIsNull:4]);
  317. XCTAssertTrue( [rs columnIndexIsNull:5]);
  318. XCTAssertEqualObjects([rs dataForColumn:@"d"], safariCompass);
  319. XCTAssertNil([rs dataForColumn:@"notthere"]);
  320. XCTAssertNil([rs stringForColumnIndex:-2], @"Negative columns should return nil results");
  321. XCTAssertTrue([rs boolForColumnIndex:4]);
  322. XCTAssertTrue([rs boolForColumn:@"b"]);
  323. XCTAssertEqualWithAccuracy(4.4, [rs doubleForColumn:@"f"], 0.0000001, @"Saving a float and returning it as a double shouldn't change the result much");
  324. XCTAssertEqual([rs intForColumn:@"i"], 12);
  325. XCTAssertEqual([rs intForColumnIndex:2], 12);
  326. XCTAssertEqual([rs intForColumnIndex:12], 0, @"Non-existent columns should return zero for ints");
  327. XCTAssertEqual([rs intForColumn:@"notthere"], 0, @"Non-existent columns should return zero for ints");
  328. XCTAssertEqual([rs longForColumn:@"i"], 12l);
  329. XCTAssertEqual([rs longLongIntForColumn:@"i"], 12ll);
  330. }
  331. else {
  332. // let's test various null things.
  333. XCTAssertTrue([rs columnIndexIsNull:0]);
  334. XCTAssertTrue([rs columnIndexIsNull:1]);
  335. XCTAssertTrue([rs columnIndexIsNull:2]);
  336. XCTAssertTrue([rs columnIndexIsNull:3]);
  337. XCTAssertTrue([rs columnIndexIsNull:4]);
  338. XCTAssertTrue([rs columnIndexIsNull:5]);
  339. XCTAssertNil([rs dataForColumn:@"d"]);
  340. }
  341. }
  342. [rs close];
  343. XCTAssertFalse([self.db hasOpenResultSets], @"Shouldn't have any open result sets");
  344. XCTAssertFalse([self.db hadError], @"Shouldn't have any errors");
  345. }
  346. - (void)testUTF8Strings
  347. {
  348. [self.db executeUpdate:@"create table utest (a text)"];
  349. [self.db executeUpdate:@"insert into utest values (?)", @"/übertest"];
  350. FMResultSet *rs = [self.db executeQuery:@"select * from utest where a = ?", @"/übertest"];
  351. XCTAssertTrue([rs next]);
  352. [rs close];
  353. XCTAssertFalse([self.db hasOpenResultSets], @"Shouldn't have any open result sets");
  354. XCTAssertFalse([self.db hadError], @"Shouldn't have any errors");
  355. }
  356. - (void)testArgumentsInArray
  357. {
  358. [self.db executeUpdate:@"create table testOneHundredTwelvePointTwo (a text, b integer)"];
  359. [self.db executeUpdate:@"insert into testOneHundredTwelvePointTwo values (?, ?)" withArgumentsInArray:[NSArray arrayWithObjects:@"one", [NSNumber numberWithInteger:2], nil]];
  360. [self.db executeUpdate:@"insert into testOneHundredTwelvePointTwo values (?, ?)" withArgumentsInArray:[NSArray arrayWithObjects:@"one", [NSNumber numberWithInteger:3], nil]];
  361. FMResultSet *rs = [self.db executeQuery:@"select * from testOneHundredTwelvePointTwo where b > ?" withArgumentsInArray:[NSArray arrayWithObject:[NSNumber numberWithInteger:1]]];
  362. XCTAssertTrue([rs next]);
  363. XCTAssertTrue([rs hasAnotherRow]);
  364. XCTAssertFalse([self.db hadError]);
  365. XCTAssertEqualObjects([rs stringForColumnIndex:0], @"one");
  366. XCTAssertEqual([rs intForColumnIndex:1], 2);
  367. XCTAssertTrue([rs next]);
  368. XCTAssertEqual([rs intForColumnIndex:1], 3);
  369. XCTAssertFalse([rs next]);
  370. XCTAssertFalse([rs hasAnotherRow]);
  371. }
  372. - (void)testColumnNamesContainingPeriods
  373. {
  374. XCTAssertTrue([self.db executeUpdate:@"create table t4 (a text, b text)"]);
  375. [self.db executeUpdate:@"insert into t4 (a, b) values (?, ?)", @"one", @"two"];
  376. FMResultSet *rs = [self.db executeQuery:@"select t4.a as 't4.a', t4.b from t4;"];
  377. XCTAssertNotNil(rs);
  378. XCTAssertTrue([rs next]);
  379. XCTAssertEqualObjects([rs stringForColumn:@"t4.a"], @"one");
  380. XCTAssertEqualObjects([rs stringForColumn:@"b"], @"two");
  381. XCTAssertEqual(strcmp((const char*)[rs UTF8StringForColumnName:@"b"], "two"), 0, @"String comparison should return zero");
  382. [rs close];
  383. // let's try these again, with the withArgumentsInArray: variation
  384. XCTAssertTrue([self.db executeUpdate:@"drop table t4;" withArgumentsInArray:[NSArray array]]);
  385. XCTAssertTrue([self.db executeUpdate:@"create table t4 (a text, b text)" withArgumentsInArray:[NSArray array]]);
  386. [self.db executeUpdate:@"insert into t4 (a, b) values (?, ?)" withArgumentsInArray:[NSArray arrayWithObjects:@"one", @"two", nil]];
  387. rs = [self.db executeQuery:@"select t4.a as 't4.a', t4.b from t4;" withArgumentsInArray:[NSArray array]];
  388. XCTAssertNotNil(rs);
  389. XCTAssertTrue([rs next]);
  390. XCTAssertEqualObjects([rs stringForColumn:@"t4.a"], @"one");
  391. XCTAssertEqualObjects([rs stringForColumn:@"b"], @"two");
  392. XCTAssertEqual(strcmp((const char*)[rs UTF8StringForColumnName:@"b"], "two"), 0, @"String comparison should return zero");
  393. [rs close];
  394. }
  395. - (void)testFormatStringParsing
  396. {
  397. XCTAssertTrue([self.db executeUpdate:@"create table t5 (a text, b int, c blob, d text, e text)"]);
  398. [self.db executeUpdateWithFormat:@"insert into t5 values (%s, %d, %@, %c, %lld)", "text", 42, @"BLOB", 'd', 12345678901234ll];
  399. FMResultSet *rs = [self.db executeQueryWithFormat:@"select * from t5 where a = %s and a = %@ and b = %d", "text", @"text", 42];
  400. XCTAssertNotNil(rs);
  401. XCTAssertTrue([rs next]);
  402. XCTAssertEqualObjects([rs stringForColumn:@"a"], @"text");
  403. XCTAssertEqual([rs intForColumn:@"b"], 42);
  404. XCTAssertEqualObjects([rs stringForColumn:@"c"], @"BLOB");
  405. XCTAssertEqualObjects([rs stringForColumn:@"d"], @"d");
  406. XCTAssertEqual([rs longLongIntForColumn:@"e"], 12345678901234ll);
  407. [rs close];
  408. }
  409. - (void)testFormatStringParsingWithSizePrefixes
  410. {
  411. XCTAssertTrue([self.db executeUpdate:@"create table t55 (a text, b int, c float)"]);
  412. short testShort = -4;
  413. float testFloat = 5.5;
  414. [self.db executeUpdateWithFormat:@"insert into t55 values (%c, %hi, %g)", 'a', testShort, testFloat];
  415. unsigned short testUShort = 6;
  416. [self.db executeUpdateWithFormat:@"insert into t55 values (%c, %hu, %g)", 'a', testUShort, testFloat];
  417. FMResultSet *rs = [self.db executeQueryWithFormat:@"select * from t55 where a = %s order by 2", "a"];
  418. XCTAssertNotNil(rs);
  419. XCTAssertTrue([rs next]);
  420. XCTAssertEqualObjects([rs stringForColumn:@"a"], @"a");
  421. XCTAssertEqual([rs intForColumn:@"b"], -4);
  422. XCTAssertEqualObjects([rs stringForColumn:@"c"], @"5.5");
  423. XCTAssertTrue([rs next]);
  424. XCTAssertEqualObjects([rs stringForColumn:@"a"], @"a");
  425. XCTAssertEqual([rs intForColumn:@"b"], 6);
  426. XCTAssertEqualObjects([rs stringForColumn:@"c"], @"5.5");
  427. [rs close];
  428. }
  429. - (void)testFormatStringParsingWithNilValue
  430. {
  431. XCTAssertTrue([self.db executeUpdate:@"create table tatwhat (a text)"]);
  432. BOOL worked = [self.db executeUpdateWithFormat:@"insert into tatwhat values(%@)", nil];
  433. XCTAssertTrue(worked);
  434. FMResultSet *rs = [self.db executeQueryWithFormat:@"select * from tatwhat"];
  435. XCTAssertNotNil(rs);
  436. XCTAssertTrue([rs next]);
  437. XCTAssertTrue([rs columnIndexIsNull:0]);
  438. XCTAssertFalse([rs next]);
  439. }
  440. - (void)testUpdateWithErrorAndBindings
  441. {
  442. XCTAssertTrue([self.db executeUpdate:@"create table t5 (a text, b int, c blob, d text, e text)"]);
  443. NSError *err = nil;
  444. BOOL result = [self.db executeUpdate:@"insert into t5 values (?, ?, ?, ?, ?)" withErrorAndBindings:&err, @"text", [NSNumber numberWithInt:42], @"BLOB", @"d", [NSNumber numberWithInt:0]];
  445. XCTAssertTrue(result);
  446. }
  447. - (void)testSelectWithEmptyArgumentsArray
  448. {
  449. FMResultSet *rs = [self.db executeQuery:@"select * from test where a=?" withArgumentsInArray:@[]];
  450. XCTAssertNil(rs);
  451. }
  452. - (void)testDatabaseAttach
  453. {
  454. NSFileManager *fileManager = [NSFileManager new];
  455. [fileManager removeItemAtPath:@"/tmp/attachme.db" error:nil];
  456. FMDatabase *dbB = [FMDatabase databaseWithPath:@"/tmp/attachme.db"];
  457. XCTAssertTrue([dbB open]);
  458. XCTAssertTrue([dbB executeUpdate:@"create table attached (a text)"]);
  459. XCTAssertTrue(([dbB executeUpdate:@"insert into attached values (?)", @"test"]));
  460. XCTAssertTrue([dbB close]);
  461. [self.db executeUpdate:@"attach database '/tmp/attachme.db' as attack"];
  462. FMResultSet *rs = [self.db executeQuery:@"select * from attack.attached"];
  463. XCTAssertNotNil(rs);
  464. XCTAssertTrue([rs next]);
  465. [rs close];
  466. }
  467. - (void)testNamedParameters
  468. {
  469. // -------------------------------------------------------------------------------
  470. // Named parameters.
  471. XCTAssertTrue([self.db executeUpdate:@"create table namedparamtest (a text, b text, c integer, d double)"]);
  472. NSMutableDictionary *dictionaryArgs = [NSMutableDictionary dictionary];
  473. [dictionaryArgs setObject:@"Text1" forKey:@"a"];
  474. [dictionaryArgs setObject:@"Text2" forKey:@"b"];
  475. [dictionaryArgs setObject:[NSNumber numberWithInt:1] forKey:@"c"];
  476. [dictionaryArgs setObject:[NSNumber numberWithDouble:2.0] forKey:@"d"];
  477. XCTAssertTrue([self.db executeUpdate:@"insert into namedparamtest values (:a, :b, :c, :d)" withParameterDictionary:dictionaryArgs]);
  478. FMResultSet *rs = [self.db executeQuery:@"select * from namedparamtest"];
  479. XCTAssertNotNil(rs);
  480. XCTAssertTrue([rs next]);
  481. XCTAssertEqualObjects([rs stringForColumn:@"a"], @"Text1");
  482. XCTAssertEqualObjects([rs stringForColumn:@"b"], @"Text2");
  483. XCTAssertEqual([rs intForColumn:@"c"], 1);
  484. XCTAssertEqual([rs doubleForColumn:@"d"], 2.0);
  485. [rs close];
  486. dictionaryArgs = [NSMutableDictionary dictionary];
  487. [dictionaryArgs setObject:@"Text2" forKey:@"blah"];
  488. rs = [self.db executeQuery:@"select * from namedparamtest where b = :blah" withParameterDictionary:dictionaryArgs];
  489. XCTAssertNotNil(rs);
  490. XCTAssertTrue([rs next]);
  491. XCTAssertEqualObjects([rs stringForColumn:@"b"], @"Text2");
  492. [rs close];
  493. }
  494. - (void)testPragmaDatabaseList
  495. {
  496. FMResultSet *rs = [self.db executeQuery:@"pragma database_list"];
  497. int counter = 0;
  498. while ([rs next]) {
  499. counter++;
  500. XCTAssertEqualObjects([rs stringForColumn:@"file"], self.databasePath);
  501. }
  502. XCTAssertEqual(counter, 1, @"Only one database should be attached");
  503. }
  504. - (void)testCachedStatementsInUse
  505. {
  506. [self.db setShouldCacheStatements:true];
  507. [self.db executeUpdate:@"CREATE TABLE testCacheStatements(key INTEGER PRIMARY KEY, value INTEGER)"];
  508. [self.db executeUpdate:@"INSERT INTO testCacheStatements (key, value) VALUES (1, 2)"];
  509. [self.db executeUpdate:@"INSERT INTO testCacheStatements (key, value) VALUES (2, 4)"];
  510. XCTAssertTrue([[self.db executeQuery:@"SELECT * FROM testCacheStatements WHERE key=1"] next]);
  511. XCTAssertTrue([[self.db executeQuery:@"SELECT * FROM testCacheStatements WHERE key=1"] next]);
  512. }
  513. - (void)testStatementCachingWorks
  514. {
  515. [self.db executeUpdate:@"CREATE TABLE testStatementCaching ( value INTEGER )"];
  516. [self.db executeUpdate:@"INSERT INTO testStatementCaching( value ) VALUES (1)"];
  517. [self.db executeUpdate:@"INSERT INTO testStatementCaching( value ) VALUES (1)"];
  518. [self.db executeUpdate:@"INSERT INTO testStatementCaching( value ) VALUES (2)"];
  519. [self.db setShouldCacheStatements:YES];
  520. // two iterations.
  521. // the first time through no statements will be from the cache.
  522. // the second time through all statements come from the cache.
  523. for (int i = 1; i <= 2; i++ ) {
  524. FMResultSet* rs1 = [self.db executeQuery: @"SELECT rowid, * FROM testStatementCaching WHERE value = ?", @1]; // results in 2 rows...
  525. XCTAssertNotNil(rs1);
  526. XCTAssertTrue([rs1 next]);
  527. // confirm that we're seeing the benefits of caching.
  528. XCTAssertEqual([[rs1 statement] useCount], (long)i);
  529. FMResultSet* rs2 = [self.db executeQuery:@"SELECT rowid, * FROM testStatementCaching WHERE value = ?", @2]; // results in 1 row
  530. XCTAssertNotNil(rs2);
  531. XCTAssertTrue([rs2 next]);
  532. XCTAssertEqual([[rs2 statement] useCount], (long)i);
  533. // 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.
  534. XCTAssertTrue([rs1 next]);
  535. [rs1 close];
  536. [rs2 close];
  537. }
  538. }
  539. /*
  540. Test the date format
  541. */
  542. - (void)testDateFormat
  543. {
  544. void (^testOneDateFormat)(FMDatabase *, NSDate *) = ^( FMDatabase *db, NSDate *testDate ){
  545. [db executeUpdate:@"DROP TABLE IF EXISTS test_format"];
  546. [db executeUpdate:@"CREATE TABLE test_format ( test TEXT )"];
  547. [db executeUpdate:@"INSERT INTO test_format(test) VALUES (?)", testDate];
  548. FMResultSet *rs = [db executeQuery:@"SELECT test FROM test_format"];
  549. XCTAssertNotNil(rs);
  550. XCTAssertTrue([rs next]);
  551. XCTAssertEqualObjects([rs dateForColumnIndex:0], testDate);
  552. [rs close];
  553. };
  554. NSDateFormatter *fmt = [FMDatabase storeableDateFormat:@"yyyy-MM-dd HH:mm:ss"];
  555. NSDate *testDate = [fmt dateFromString:@"2013-02-20 12:00:00"];
  556. // test timestamp dates (ensuring our change does not break those)
  557. testOneDateFormat(self.db,testDate);
  558. // now test the string-based timestamp
  559. [self.db setDateFormat:fmt];
  560. testOneDateFormat(self.db, testDate);
  561. }
  562. - (void)testColumnNameMap
  563. {
  564. XCTAssertTrue([self.db executeUpdate:@"create table colNameTest (a, b, c, d)"]);
  565. XCTAssertTrue([self.db executeUpdate:@"insert into colNameTest values (1, 2, 3, 4)"]);
  566. FMResultSet *ars = [self.db executeQuery:@"select * from colNameTest"];
  567. XCTAssertNotNil(ars);
  568. NSDictionary *d = [ars columnNameToIndexMap];
  569. XCTAssertEqual([d count], (NSUInteger)4);
  570. XCTAssertEqualObjects([d objectForKey:@"a"], @0);
  571. XCTAssertEqualObjects([d objectForKey:@"b"], @1);
  572. XCTAssertEqualObjects([d objectForKey:@"c"], @2);
  573. XCTAssertEqualObjects([d objectForKey:@"d"], @3);
  574. }
  575. - (void)testCustomFunction
  576. {
  577. [self.db executeUpdate:@"create table ftest (foo text)"];
  578. [self.db executeUpdate:@"insert into ftest values ('hello')"];
  579. [self.db executeUpdate:@"insert into ftest values ('hi')"];
  580. [self.db executeUpdate:@"insert into ftest values ('not h!')"];
  581. [self.db executeUpdate:@"insert into ftest values ('definitely not h!')"];
  582. [self.db makeFunctionNamed:@"StringStartsWithH" maximumArguments:1 withBlock:^(sqlite3_context *context, int aargc, sqlite3_value **aargv) {
  583. if (sqlite3_value_type(aargv[0]) == SQLITE_TEXT) {
  584. @autoreleasepool {
  585. const char *c = (const char *)sqlite3_value_text(aargv[0]);
  586. NSString *s = [NSString stringWithUTF8String:c];
  587. sqlite3_result_int(context, [s hasPrefix:@"h"]);
  588. }
  589. }
  590. else {
  591. XCTFail(@"Unknown format for StringStartsWithH (%d)", sqlite3_value_type(aargv[0]));
  592. sqlite3_result_null(context);
  593. }
  594. }];
  595. int rowCount = 0;
  596. FMResultSet *ars = [self.db executeQuery:@"select * from ftest where StringStartsWithH(foo)"];
  597. while ([ars next]) {
  598. rowCount++;
  599. }
  600. XCTAssertEqual(rowCount, 2);
  601. }
  602. #if SQLITE_VERSION_NUMBER >= 3007017
  603. - (void)testApplicationID
  604. {
  605. uint32_t appID = NSHFSTypeCodeFromFileType(NSFileTypeForHFSTypeCode('fmdb'));
  606. [self.db setApplicationID:appID];
  607. uint32_t rAppID = [self.db applicationID];
  608. XCTAssertEqual(rAppID, appID);
  609. [self.db setApplicationIDString:@"acrn"];
  610. NSString *s = [self.db applicationIDString];
  611. XCTAssertEqualObjects(s, @"acrn");
  612. }
  613. #endif
  614. - (void)testBulkSQL
  615. {
  616. BOOL success;
  617. NSString *sql = @"create table bulktest1 (id integer primary key autoincrement, x text);"
  618. "create table bulktest2 (id integer primary key autoincrement, y text);"
  619. "create table bulktest3 (id integer primary key autoincrement, z text);"
  620. "insert into bulktest1 (x) values ('XXX');"
  621. "insert into bulktest2 (y) values ('YYY');"
  622. "insert into bulktest3 (z) values ('ZZZ');";
  623. success = [self.db executeBulkSQL:sql];
  624. XCTAssertTrue(success, @"bulk create");
  625. sql = @"select count(*) as count from bulktest1;"
  626. "select count(*) as count from bulktest2;"
  627. "select count(*) as count from bulktest3;";
  628. success = [self.db executeBulkSQL:sql block:^int(NSDictionary *dictionary) {
  629. NSInteger count = [dictionary[@"count"] integerValue];
  630. XCTAssertEqual(count, 1, @"expected one record for dictionary %@", dictionary);
  631. return 0;
  632. }];
  633. XCTAssertTrue(success, @"bulk select");
  634. sql = @"drop table bulktest1;"
  635. "drop table bulktest2;"
  636. "drop table bulktest3;";
  637. success = [self.db executeBulkSQL:sql];
  638. XCTAssertTrue(success, @"bulk drop");
  639. }
  640. @end