FMDatabaseTests.m 33 KB

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