FMDatabaseTests.m 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076
  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)testUpdateWithErrorAndBindings
  419. {
  420. XCTAssertTrue([self.db executeUpdate:@"create table t5 (a text, b int, c blob, d text, e text)"]);
  421. NSError *err = nil;
  422. BOOL result = [self.db executeUpdate:@"insert into t5 values (?, ?, ?, ?, ?)" withErrorAndBindings:&err, @"text", [NSNumber numberWithInt:42], @"BLOB", @"d", [NSNumber numberWithInt:0]];
  423. XCTAssertTrue(result);
  424. }
  425. - (void)testSelectWithEmptyArgumentsArray
  426. {
  427. FMResultSet *rs = [self.db executeQuery:@"select * from test where a=?" withArgumentsInArray:@[]];
  428. XCTAssertNil(rs);
  429. }
  430. - (void)testDatabaseAttach
  431. {
  432. NSFileManager *fileManager = [NSFileManager new];
  433. [fileManager removeItemAtPath:@"/tmp/attachme.db" error:nil];
  434. FMDatabase *dbB = [FMDatabase databaseWithPath:@"/tmp/attachme.db"];
  435. XCTAssertTrue([dbB open]);
  436. XCTAssertTrue([dbB executeUpdate:@"create table attached (a text)"]);
  437. XCTAssertTrue(([dbB executeUpdate:@"insert into attached values (?)", @"test"]));
  438. XCTAssertTrue([dbB close]);
  439. [self.db executeUpdate:@"attach database '/tmp/attachme.db' as attack"];
  440. FMResultSet *rs = [self.db executeQuery:@"select * from attack.attached"];
  441. XCTAssertNotNil(rs);
  442. XCTAssertTrue([rs next]);
  443. [rs close];
  444. }
  445. - (void)testNamedParameters
  446. {
  447. // -------------------------------------------------------------------------------
  448. // Named parameters.
  449. XCTAssertTrue([self.db executeUpdate:@"create table namedparamtest (a text, b text, c integer, d double)"]);
  450. NSMutableDictionary *dictionaryArgs = [NSMutableDictionary dictionary];
  451. [dictionaryArgs setObject:@"Text1" forKey:@"a"];
  452. [dictionaryArgs setObject:@"Text2" forKey:@"b"];
  453. [dictionaryArgs setObject:[NSNumber numberWithInt:1] forKey:@"c"];
  454. [dictionaryArgs setObject:[NSNumber numberWithDouble:2.0] forKey:@"d"];
  455. XCTAssertTrue([self.db executeUpdate:@"insert into namedparamtest values (:a, :b, :c, :d)" withParameterDictionary:dictionaryArgs]);
  456. FMResultSet *rs = [self.db executeQuery:@"select * from namedparamtest"];
  457. XCTAssertNotNil(rs);
  458. XCTAssertTrue([rs next]);
  459. XCTAssertEqualObjects([rs stringForColumn:@"a"], @"Text1");
  460. XCTAssertEqualObjects([rs stringForColumn:@"b"], @"Text2");
  461. XCTAssertEqual([rs intForColumn:@"c"], 1);
  462. XCTAssertEqual([rs doubleForColumn:@"d"], 2.0);
  463. [rs close];
  464. dictionaryArgs = [NSMutableDictionary dictionary];
  465. [dictionaryArgs setObject:@"Text2" forKey:@"blah"];
  466. rs = [self.db executeQuery:@"select * from namedparamtest where b = :blah" withParameterDictionary:dictionaryArgs];
  467. XCTAssertNotNil(rs);
  468. XCTAssertTrue([rs next]);
  469. XCTAssertEqualObjects([rs stringForColumn:@"b"], @"Text2");
  470. [rs close];
  471. }
  472. - (void)testPragmaDatabaseList
  473. {
  474. FMResultSet *rs = [self.db executeQuery:@"pragma database_list"];
  475. int counter = 0;
  476. while ([rs next]) {
  477. counter++;
  478. XCTAssertEqualObjects([rs stringForColumn:@"file"], self.databasePath);
  479. }
  480. XCTAssertEqual(counter, 1, @"Only one database should be attached");
  481. }
  482. - (void)testCachedStatementsInUse
  483. {
  484. [self.db setShouldCacheStatements:true];
  485. [self.db executeUpdate:@"CREATE TABLE testCacheStatements(key INTEGER PRIMARY KEY, value INTEGER)"];
  486. [self.db executeUpdate:@"INSERT INTO testCacheStatements (key, value) VALUES (1, 2)"];
  487. [self.db executeUpdate:@"INSERT INTO testCacheStatements (key, value) VALUES (2, 4)"];
  488. XCTAssertTrue([[self.db executeQuery:@"SELECT * FROM testCacheStatements WHERE key=1"] next]);
  489. XCTAssertTrue([[self.db executeQuery:@"SELECT * FROM testCacheStatements WHERE key=1"] next]);
  490. }
  491. - (void)testStatementCachingWorks
  492. {
  493. [self.db executeUpdate:@"CREATE TABLE testStatementCaching ( value INTEGER )"];
  494. [self.db executeUpdate:@"INSERT INTO testStatementCaching( value ) VALUES (1)"];
  495. [self.db executeUpdate:@"INSERT INTO testStatementCaching( value ) VALUES (1)"];
  496. [self.db executeUpdate:@"INSERT INTO testStatementCaching( value ) VALUES (2)"];
  497. [self.db setShouldCacheStatements:YES];
  498. // two iterations.
  499. // the first time through no statements will be from the cache.
  500. // the second time through all statements come from the cache.
  501. for (int i = 1; i <= 2; i++ ) {
  502. FMResultSet* rs1 = [self.db executeQuery: @"SELECT rowid, * FROM testStatementCaching WHERE value = ?", @1]; // results in 2 rows...
  503. XCTAssertNotNil(rs1);
  504. XCTAssertTrue([rs1 next]);
  505. // confirm that we're seeing the benefits of caching.
  506. XCTAssertEqual([[rs1 statement] useCount], (long)i);
  507. FMResultSet* rs2 = [self.db executeQuery:@"SELECT rowid, * FROM testStatementCaching WHERE value = ?", @2]; // results in 1 row
  508. XCTAssertNotNil(rs2);
  509. XCTAssertTrue([rs2 next]);
  510. XCTAssertEqual([[rs2 statement] useCount], (long)i);
  511. // 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.
  512. XCTAssertTrue([rs1 next]);
  513. [rs1 close];
  514. [rs2 close];
  515. }
  516. }
  517. /*
  518. Test the date format
  519. */
  520. - (void)testDateFormat
  521. {
  522. void (^testOneDateFormat)(FMDatabase *, NSDate *) = ^( FMDatabase *db, NSDate *testDate ){
  523. [db executeUpdate:@"DROP TABLE IF EXISTS test_format"];
  524. [db executeUpdate:@"CREATE TABLE test_format ( test TEXT )"];
  525. [db executeUpdate:@"INSERT INTO test_format(test) VALUES (?)", testDate];
  526. FMResultSet *rs = [db executeQuery:@"SELECT test FROM test_format"];
  527. XCTAssertNotNil(rs);
  528. XCTAssertTrue([rs next]);
  529. XCTAssertEqualObjects([rs dateForColumnIndex:0], testDate);
  530. [rs close];
  531. };
  532. NSDateFormatter *fmt = [FMDatabase storeableDateFormat:@"yyyy-MM-dd HH:mm:ss"];
  533. NSDate *testDate = [fmt dateFromString:@"2013-02-20 12:00:00"];
  534. // test timestamp dates (ensuring our change does not break those)
  535. testOneDateFormat(self.db,testDate);
  536. // now test the string-based timestamp
  537. [self.db setDateFormat:fmt];
  538. testOneDateFormat(self.db, testDate);
  539. }
  540. - (void)testColumnNameMap
  541. {
  542. XCTAssertTrue([self.db executeUpdate:@"create table colNameTest (a, b, c, d)"]);
  543. XCTAssertTrue([self.db executeUpdate:@"insert into colNameTest values (1, 2, 3, 4)"]);
  544. FMResultSet *ars = [self.db executeQuery:@"select * from colNameTest"];
  545. XCTAssertNotNil(ars);
  546. NSDictionary *d = [ars columnNameToIndexMap];
  547. XCTAssertEqual([d count], (NSUInteger)4);
  548. XCTAssertEqualObjects([d objectForKey:@"a"], @0);
  549. XCTAssertEqualObjects([d objectForKey:@"b"], @1);
  550. XCTAssertEqualObjects([d objectForKey:@"c"], @2);
  551. XCTAssertEqualObjects([d objectForKey:@"d"], @3);
  552. }
  553. - (void)testCustomFunction
  554. {
  555. [self.db executeUpdate:@"create table ftest (foo text)"];
  556. [self.db executeUpdate:@"insert into ftest values ('hello')"];
  557. [self.db executeUpdate:@"insert into ftest values ('hi')"];
  558. [self.db executeUpdate:@"insert into ftest values ('not h!')"];
  559. [self.db executeUpdate:@"insert into ftest values ('definitely not h!')"];
  560. [self.db makeFunctionNamed:@"StringStartsWithH" maximumArguments:1 withBlock:^(void *context, int aargc, void **aargv) {
  561. if (sqlite3_value_type(aargv[0]) == SQLITE_TEXT) {
  562. @autoreleasepool {
  563. const char *c = (const char *)sqlite3_value_text(aargv[0]);
  564. NSString *s = [NSString stringWithUTF8String:c];
  565. sqlite3_result_int(context, [s hasPrefix:@"h"]);
  566. }
  567. }
  568. else {
  569. XCTFail(@"Unknown format for StringStartsWithH (%d)", sqlite3_value_type(aargv[0]));
  570. sqlite3_result_null(context);
  571. }
  572. }];
  573. int rowCount = 0;
  574. FMResultSet *ars = [self.db executeQuery:@"select * from ftest where StringStartsWithH(foo)"];
  575. while ([ars next]) {
  576. rowCount++;
  577. }
  578. XCTAssertEqual(rowCount, 2);
  579. }
  580. - (void)testVersionNumber {
  581. XCTAssertTrue([FMDatabase FMDBVersion] == 0x0262); // this is going to break everytime we bump it.
  582. }
  583. - (void)testExecuteStatements
  584. {
  585. BOOL success;
  586. NSString *sql = @"create table bulktest1 (id integer primary key autoincrement, x text);"
  587. "create table bulktest2 (id integer primary key autoincrement, y text);"
  588. "create table bulktest3 (id integer primary key autoincrement, z text);"
  589. "insert into bulktest1 (x) values ('XXX');"
  590. "insert into bulktest2 (y) values ('YYY');"
  591. "insert into bulktest3 (z) values ('ZZZ');";
  592. success = [self.db executeStatements:sql];
  593. XCTAssertTrue(success, @"bulk create");
  594. sql = @"select count(*) as count from bulktest1;"
  595. "select count(*) as count from bulktest2;"
  596. "select count(*) as count from bulktest3;";
  597. success = [self.db executeStatements:sql withResultBlock:^int(NSDictionary *dictionary) {
  598. NSInteger count = [dictionary[@"count"] integerValue];
  599. XCTAssertEqual(count, 1, @"expected one record for dictionary %@", dictionary);
  600. return 0;
  601. }];
  602. XCTAssertTrue(success, @"bulk select");
  603. sql = @"drop table bulktest1;"
  604. "drop table bulktest2;"
  605. "drop table bulktest3;";
  606. success = [self.db executeStatements:sql];
  607. XCTAssertTrue(success, @"bulk drop");
  608. }
  609. - (void)testCharAndBoolTypes
  610. {
  611. XCTAssertTrue([self.db executeUpdate:@"create table charBoolTest (a, b, c)"]);
  612. BOOL success = [self.db executeUpdate:@"insert into charBoolTest values (?, ?, ?)", @YES, @NO, @('x')];
  613. XCTAssertTrue(success, @"Unable to insert values");
  614. FMResultSet *rs = [self.db executeQuery:@"select * from charBoolTest"];
  615. XCTAssertNotNil(rs);
  616. XCTAssertTrue([rs next], @"Did not return row");
  617. XCTAssertEqual([rs boolForColumn:@"a"], true);
  618. XCTAssertEqualObjects([rs objectForColumnName:@"a"], @YES);
  619. XCTAssertEqual([rs boolForColumn:@"b"], false);
  620. XCTAssertEqualObjects([rs objectForColumnName:@"b"], @NO);
  621. XCTAssertEqual([rs intForColumn:@"c"], 'x');
  622. XCTAssertEqualObjects([rs objectForColumnName:@"c"], @('x'));
  623. [rs close];
  624. XCTAssertTrue([self.db executeUpdate:@"drop table charBoolTest"], @"Did not drop table");
  625. }
  626. - (void)testSqliteLibVersion
  627. {
  628. NSString *version = [FMDatabase sqliteLibVersion];
  629. XCTAssert([version compare:@"3.7" options:NSNumericSearch] == NSOrderedDescending, @"earlier than 3.7");
  630. XCTAssert([version compare:@"4.0" options:NSNumericSearch] == NSOrderedAscending, @"not earlier than 4.0");
  631. }
  632. - (void)testIsThreadSafe
  633. {
  634. BOOL isThreadSafe = [FMDatabase isSQLiteThreadSafe];
  635. XCTAssert(isThreadSafe, @"not threadsafe");
  636. }
  637. - (void)testOpenNilPath
  638. {
  639. FMDatabase *db = [[FMDatabase alloc] init];
  640. XCTAssert([db open], @"open failed");
  641. XCTAssert([db executeUpdate:@"create table foo (bar text)"], @"create failed");
  642. NSString *value = @"baz";
  643. XCTAssert([db executeUpdate:@"insert into foo (bar) values (?)" withArgumentsInArray:@[value]], @"insert failed");
  644. NSString *retrievedValue = [db stringForQuery:@"select bar from foo"];
  645. XCTAssert([value compare:retrievedValue] == NSOrderedSame, @"values didn't match");
  646. }
  647. - (void)testOpenZeroLengthPath
  648. {
  649. FMDatabase *db = [[FMDatabase alloc] initWithPath:@""];
  650. XCTAssert([db open], @"open failed");
  651. XCTAssert([db executeUpdate:@"create table foo (bar text)"], @"create failed");
  652. NSString *value = @"baz";
  653. XCTAssert([db executeUpdate:@"insert into foo (bar) values (?)" withArgumentsInArray:@[value]], @"insert failed");
  654. NSString *retrievedValue = [db stringForQuery:@"select bar from foo"];
  655. XCTAssert([value compare:retrievedValue] == NSOrderedSame, @"values didn't match");
  656. }
  657. - (void)testOpenTwice
  658. {
  659. FMDatabase *db = [[FMDatabase alloc] init];
  660. [db open];
  661. XCTAssert([db open], @"Double open failed");
  662. }
  663. - (void)testInvalid
  664. {
  665. NSString *documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
  666. NSString *path = [documentsPath stringByAppendingPathComponent:@"nonexistentfolder/test.sqlite"];
  667. FMDatabase *db = [[FMDatabase alloc] initWithPath:path];
  668. XCTAssertFalse([db open], @"open did NOT fail");
  669. }
  670. - (void)testChangingMaxBusyRetryTimeInterval
  671. {
  672. FMDatabase *db = [[FMDatabase alloc] init];
  673. XCTAssert([db open], @"open failed");
  674. NSTimeInterval originalInterval = db.maxBusyRetryTimeInterval;
  675. NSTimeInterval updatedInterval = originalInterval > 0 ? originalInterval + 1 : 1;
  676. db.maxBusyRetryTimeInterval = updatedInterval;
  677. NSTimeInterval diff = fabs(db.maxBusyRetryTimeInterval - updatedInterval);
  678. XCTAssert(diff < 1e-5, @"interval should have changed %.1f", diff);
  679. }
  680. - (void)testChangingMaxBusyRetryTimeIntervalDatabaseNotOpened
  681. {
  682. FMDatabase *db = [[FMDatabase alloc] init];
  683. // XCTAssert([db open], @"open failed"); // deliberately not opened
  684. NSTimeInterval originalInterval = db.maxBusyRetryTimeInterval;
  685. NSTimeInterval updatedInterval = originalInterval > 0 ? originalInterval + 1 : 1;
  686. db.maxBusyRetryTimeInterval = updatedInterval;
  687. XCTAssertNotEqual(originalInterval, db.maxBusyRetryTimeInterval, @"interval should not have changed");
  688. }
  689. - (void)testZeroMaxBusyRetryTimeInterval
  690. {
  691. FMDatabase *db = [[FMDatabase alloc] init];
  692. XCTAssert([db open], @"open failed");
  693. NSTimeInterval updatedInterval = 0;
  694. db.maxBusyRetryTimeInterval = updatedInterval;
  695. XCTAssertEqual(db.maxBusyRetryTimeInterval, updatedInterval, @"busy handler not disabled");
  696. }
  697. - (void)testCloseOpenResultSets
  698. {
  699. FMDatabase *db = [[FMDatabase alloc] init];
  700. XCTAssert([db open], @"open failed");
  701. XCTAssert([db executeUpdate:@"create table foo (bar text)"], @"create failed");
  702. NSString *value = @"baz";
  703. XCTAssert([db executeUpdate:@"insert into foo (bar) values (?)" withArgumentsInArray:@[value]], @"insert failed");
  704. FMResultSet *rs = [db executeQuery:@"select bar from foo"];
  705. [db closeOpenResultSets];
  706. XCTAssertFalse([rs next], @"step should have failed");
  707. }
  708. - (void)testGoodConnection
  709. {
  710. FMDatabase *db = [[FMDatabase alloc] init];
  711. XCTAssert([db open], @"open failed");
  712. XCTAssert([db goodConnection], @"no good connection");
  713. }
  714. - (void)testBadConnection
  715. {
  716. FMDatabase *db = [[FMDatabase alloc] init];
  717. // XCTAssert([db open], @"open failed"); // deliberately did not open
  718. XCTAssertFalse([db goodConnection], @"no good connection");
  719. }
  720. - (void)testLastRowId
  721. {
  722. FMDatabase *db = [[FMDatabase alloc] init];
  723. XCTAssert([db open], @"open failed");
  724. XCTAssert([db executeUpdate:@"create table foo (foo_id integer primary key autoincrement, bar text)"], @"create failed");
  725. XCTAssert([db executeUpdate:@"insert into foo (bar) values (?)" withArgumentsInArray:@[@"baz"]], @"insert failed");
  726. sqlite3_int64 firstRowId = [db lastInsertRowId];
  727. XCTAssert([db executeUpdate:@"insert into foo (bar) values (?)" withArgumentsInArray:@[@"qux"]], @"insert failed");
  728. sqlite3_int64 secondRowId = [db lastInsertRowId];
  729. XCTAssertEqual(secondRowId - firstRowId, 1, @"rowid should have incremented");
  730. }
  731. - (void)testChanges
  732. {
  733. FMDatabase *db = [[FMDatabase alloc] init];
  734. XCTAssert([db open], @"open failed");
  735. XCTAssert([db executeUpdate:@"create table foo (foo_id integer primary key autoincrement, bar text)"], @"create failed");
  736. XCTAssert([db executeUpdate:@"insert into foo (bar) values (?)" withArgumentsInArray:@[@"baz"]], @"insert failed");
  737. XCTAssert([db executeUpdate:@"insert into foo (bar) values (?)" withArgumentsInArray:@[@"qux"]], @"insert failed");
  738. XCTAssert([db executeUpdate:@"update foo set bar = ?" withArgumentsInArray:@[@"xxx"]], @"insert failed");
  739. int changes = [db changes];
  740. XCTAssertEqual(changes, 2, @"two rows should have incremented \(%ld)", (long)changes);
  741. }
  742. - (void)testBind {
  743. FMDatabase *db = [[FMDatabase alloc] init];
  744. XCTAssert([db open], @"open failed");
  745. XCTAssert([db executeUpdate:@"create table foo (id integer primary key autoincrement, a numeric)"], @"create failed");
  746. NSNumber *insertedValue;
  747. NSNumber *retrievedValue;
  748. insertedValue = [NSNumber numberWithChar:51];
  749. XCTAssert([db executeUpdate:@"insert into foo (a) values (?)" withArgumentsInArray:@[insertedValue]], @"insert failed");
  750. retrievedValue = @([db intForQuery:@"select a from foo where id = ?", @([db lastInsertRowId])]);
  751. XCTAssertEqualObjects(insertedValue, retrievedValue, @"values don't match");
  752. insertedValue = [NSNumber numberWithUnsignedChar:52];
  753. XCTAssert([db executeUpdate:@"insert into foo (a) values (?)" withArgumentsInArray:@[insertedValue]], @"insert failed");
  754. retrievedValue = @([db intForQuery:@"select a from foo where id = ?", @([db lastInsertRowId])]);
  755. XCTAssertEqualObjects(insertedValue, retrievedValue, @"values don't match");
  756. insertedValue = [NSNumber numberWithShort:53];
  757. XCTAssert([db executeUpdate:@"insert into foo (a) values (?)" withArgumentsInArray:@[insertedValue]], @"insert failed");
  758. retrievedValue = @([db intForQuery:@"select a from foo where id = ?", @([db lastInsertRowId])]);
  759. XCTAssertEqualObjects(insertedValue, retrievedValue, @"values don't match");
  760. insertedValue = [NSNumber numberWithUnsignedShort:54];
  761. XCTAssert([db executeUpdate:@"insert into foo (a) values (?)" withArgumentsInArray:@[insertedValue]], @"insert failed");
  762. retrievedValue = @([db intForQuery:@"select a from foo where id = ?", @([db lastInsertRowId])]);
  763. XCTAssertEqualObjects(insertedValue, retrievedValue, @"values don't match");
  764. insertedValue = [NSNumber numberWithInt:54];
  765. XCTAssert([db executeUpdate:@"insert into foo (a) values (?)" withArgumentsInArray:@[insertedValue]], @"insert failed");
  766. retrievedValue = @([db intForQuery:@"select a from foo where id = ?", @([db lastInsertRowId])]);
  767. XCTAssertEqualObjects(insertedValue, retrievedValue, @"values don't match");
  768. insertedValue = [NSNumber numberWithUnsignedInt:55];
  769. XCTAssert([db executeUpdate:@"insert into foo (a) values (?)" withArgumentsInArray:@[insertedValue]], @"insert failed");
  770. retrievedValue = @([db intForQuery:@"select a from foo where id = ?", @([db lastInsertRowId])]);
  771. XCTAssertEqualObjects(insertedValue, retrievedValue, @"values don't match");
  772. insertedValue = [NSNumber numberWithLong:56];
  773. XCTAssert([db executeUpdate:@"insert into foo (a) values (?)" withArgumentsInArray:@[insertedValue]], @"insert failed");
  774. retrievedValue = @([db longForQuery:@"select a from foo where id = ?", @([db lastInsertRowId])]);
  775. XCTAssertEqualObjects(insertedValue, retrievedValue, @"values don't match");
  776. insertedValue = [NSNumber numberWithUnsignedLong:57];
  777. XCTAssert([db executeUpdate:@"insert into foo (a) values (?)" withArgumentsInArray:@[insertedValue]], @"insert failed");
  778. retrievedValue = @([db longForQuery:@"select a from foo where id = ?", @([db lastInsertRowId])]);
  779. XCTAssertEqualObjects(insertedValue, retrievedValue, @"values don't match");
  780. insertedValue = [NSNumber numberWithLongLong:56];
  781. XCTAssert([db executeUpdate:@"insert into foo (a) values (?)" withArgumentsInArray:@[insertedValue]], @"insert failed");
  782. retrievedValue = @([db longForQuery:@"select a from foo where id = ?", @([db lastInsertRowId])]);
  783. XCTAssertEqualObjects(insertedValue, retrievedValue, @"values don't match");
  784. insertedValue = [NSNumber numberWithUnsignedLongLong:57];
  785. XCTAssert([db executeUpdate:@"insert into foo (a) values (?)" withArgumentsInArray:@[insertedValue]], @"insert failed");
  786. retrievedValue = @([db longForQuery:@"select a from foo where id = ?", @([db lastInsertRowId])]);
  787. XCTAssertEqualObjects(insertedValue, retrievedValue, @"values don't match");
  788. insertedValue = [NSNumber numberWithFloat:58];
  789. XCTAssert([db executeUpdate:@"insert into foo (a) values (?)" withArgumentsInArray:@[insertedValue]], @"insert failed");
  790. retrievedValue = @([db doubleForQuery:@"select a from foo where id = ?", @([db lastInsertRowId])]);
  791. XCTAssertEqualObjects(insertedValue, retrievedValue, @"values don't match");
  792. insertedValue = [NSNumber numberWithDouble:59];
  793. XCTAssert([db executeUpdate:@"insert into foo (a) values (?)" withArgumentsInArray:@[insertedValue]], @"insert failed");
  794. retrievedValue = @([db doubleForQuery:@"select a from foo where id = ?", @([db lastInsertRowId])]);
  795. XCTAssertEqualObjects(insertedValue, retrievedValue, @"values don't match");
  796. insertedValue = @TRUE;
  797. XCTAssert([db executeUpdate:@"insert into foo (a) values (?)" withArgumentsInArray:@[insertedValue]], @"insert failed");
  798. retrievedValue = @([db boolForQuery:@"select a from foo where id = ?", @([db lastInsertRowId])]);
  799. XCTAssertEqualObjects(insertedValue, retrievedValue, @"values don't match");
  800. }
  801. - (void)testStepError {
  802. FMDatabase *db = [[FMDatabase alloc] init];
  803. XCTAssert([db open], @"open failed");
  804. XCTAssert([db executeUpdate:@"create table foo (id integer primary key)"], @"create failed");
  805. XCTAssert([db executeUpdate:@"insert into foo (id) values (?)" values:@[@1] error:nil], @"create failed");
  806. NSError *error;
  807. BOOL success = [db executeUpdate:@"insert into foo (id) values (?)" values:@[@1] error:&error];
  808. XCTAssertFalse(success, @"insert of duplicate key should have failed");
  809. XCTAssertNotNil(error, @"error object should have been generated");
  810. XCTAssertEqual(error.code, 19, @"error code 19 should have been generated");
  811. }
  812. @end