FMDatabaseTests.m 34 KB

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