FMDatabaseTests.m 70 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742
  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. [db executeUpdate:@"create table test (a text, b text, c integer, d double, e double)"];
  21. [db beginTransaction];
  22. int i = 0;
  23. while (i++ < 20) {
  24. [db executeUpdate:@"insert into test (a, b, c, d, e) values (?, ?, ?, ?, ?)" ,
  25. @"hi'", // look! I put in a ', and I'm not escaping it!
  26. [NSString stringWithFormat:@"number %d", i],
  27. [NSNumber numberWithInt:i],
  28. [NSDate date],
  29. [NSNumber numberWithFloat:2.2f]];
  30. }
  31. [db commit];
  32. // do it again, just because
  33. [db beginTransaction];
  34. i = 0;
  35. while (i++ < 20) {
  36. [db executeUpdate:@"insert into test (a, b, c, d, e) values (?, ?, ?, ?, ?)" ,
  37. @"hi again'", // look! I put in a ', and I'm not escaping it!
  38. [NSString stringWithFormat:@"number %d", i],
  39. [NSNumber numberWithInt:i],
  40. [NSDate date],
  41. [NSNumber numberWithFloat:2.2f]];
  42. }
  43. [db commit];
  44. [db executeUpdate:@"create table t3 (a somevalue)"];
  45. [db beginTransaction];
  46. for (int i=0; i < 20; i++) {
  47. [db executeUpdate:@"insert into t3 (a) values (?)", [NSNumber numberWithInt:i]];
  48. }
  49. [db commit];
  50. }
  51. - (void)setUp{
  52. [super setUp];
  53. // Put setup code here. This method is called before the invocation of each test method in the class.
  54. }
  55. - (void)tearDown {
  56. // Put teardown code here. This method is called after the invocation of each test method in the class.
  57. [super tearDown];
  58. }
  59. - (void)testOpenWithVFS {
  60. // create custom vfs
  61. sqlite3_vfs vfs = *sqlite3_vfs_find(NULL);
  62. vfs.zName = "MyCustomVFS";
  63. XCTAssertEqual(SQLITE_OK, sqlite3_vfs_register(&vfs, 0));
  64. // use custom vfs to open a in memory database
  65. FMDatabase *db = [[FMDatabase alloc] initWithPath:@":memory:"];
  66. [db openWithFlags:SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE vfs:@"MyCustomVFS"];
  67. XCTAssertFalse([db hadError], @"Open with a custom VFS should have succeeded");
  68. XCTAssertEqual(SQLITE_OK, sqlite3_vfs_unregister(&vfs));
  69. }
  70. - (void)testURLOpen {
  71. NSURL *tempFolder = [NSURL fileURLWithPath:NSTemporaryDirectory()];
  72. NSURL *fileURL = [tempFolder URLByAppendingPathComponent:[[NSUUID UUID] UUIDString]];
  73. FMDatabase *db = [FMDatabase databaseWithURL:fileURL];
  74. XCTAssert(db, @"Database should be returned");
  75. XCTAssertTrue([db open], @"Open should succeed");
  76. XCTAssertEqualObjects([db databaseURL], fileURL);
  77. XCTAssertTrue([db close], @"close should succeed");
  78. [[NSFileManager defaultManager] removeItemAtURL:fileURL error:nil];
  79. }
  80. - (void)testFailOnOpenWithUnknownVFS {
  81. FMDatabase *db = [[FMDatabase alloc] initWithPath:@":memory:"];
  82. [db openWithFlags:SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE vfs:@"UnknownVFS"];
  83. XCTAssertTrue([db hadError], @"Should have failed");
  84. }
  85. - (void)testFailOnUnopenedDatabase {
  86. [self.db close];
  87. XCTAssertNil([self.db executeQuery:@"select * from table"], @"Shouldn't get results from an empty table");
  88. XCTAssertTrue([self.db hadError], @"Should have failed");
  89. }
  90. - (void)testFailOnBadStatement {
  91. XCTAssertFalse([self.db executeUpdate:@"blah blah blah"], @"Invalid statement should fail");
  92. XCTAssertTrue([self.db hadError], @"Should have failed");
  93. }
  94. - (void)testFailOnBadStatementWithError
  95. {
  96. NSError *error = nil;
  97. XCTAssertFalse([self.db executeUpdate:@"blah blah blah" withErrorAndBindings:&error], @"Invalid statement should fail");
  98. XCTAssertNotNil(error, @"Should have a non-nil NSError");
  99. XCTAssertEqual([error code], (NSInteger)SQLITE_ERROR, @"Error should be SQLITE_ERROR");
  100. }
  101. - (void)testPragmaJournalMode
  102. {
  103. FMResultSet *ps = [self.db executeQuery:@"pragma journal_mode=delete"];
  104. XCTAssertFalse([self.db hadError], @"pragma should have succeeded");
  105. XCTAssertNotNil(ps, @"Result set should be non-nil");
  106. XCTAssertTrue([ps next], @"Result set should have a next result");
  107. [ps close];
  108. }
  109. - (void)testPragmaPageSize
  110. {
  111. [self.db executeUpdate:@"PRAGMA page_size=2048"];
  112. XCTAssertFalse([self.db hadError], @"pragma should have succeeded");
  113. }
  114. - (void)testVacuum
  115. {
  116. [self.db executeUpdate:@"VACUUM"];
  117. XCTAssertFalse([self.db hadError], @"VACUUM should have succeeded");
  118. }
  119. - (void)testSelectULL
  120. {
  121. // Unsigned long long
  122. [self.db executeUpdate:@"create table ull (a integer)"];
  123. [self.db executeUpdate:@"insert into ull (a) values (?)", [NSNumber numberWithUnsignedLongLong:ULLONG_MAX]];
  124. XCTAssertFalse([self.db hadError], @"Shouldn't have any errors");
  125. FMResultSet *rs = [self.db executeQuery:@"select a from ull"];
  126. while ([rs next]) {
  127. XCTAssertEqual([rs unsignedLongLongIntForColumnIndex:0], ULLONG_MAX, @"Result should be ULLONG_MAX");
  128. XCTAssertEqual([rs unsignedLongLongIntForColumn:@"a"], ULLONG_MAX, @"Result should be ULLONG_MAX");
  129. }
  130. [rs close];
  131. XCTAssertFalse([self.db hasOpenResultSets], @"Shouldn't have any open result sets");
  132. XCTAssertFalse([self.db hadError], @"Shouldn't have any errors");
  133. }
  134. - (void)testSelectByColumnName
  135. {
  136. FMResultSet *rs = [self.db executeQuery:@"select rowid,* from test where a = ?", @"hi"];
  137. XCTAssertNotNil(rs, @"Should have a non-nil result set");
  138. while ([rs next]) {
  139. [rs intForColumn:@"c"];
  140. XCTAssertNotNil([rs stringForColumn:@"b"], @"Should have non-nil string for 'b'");
  141. XCTAssertNotNil([rs stringForColumn:@"a"], @"Should have non-nil string for 'a'");
  142. XCTAssertNotNil([rs stringForColumn:@"rowid"], @"Should have non-nil string for 'rowid'");
  143. XCTAssertNotNil([rs dateForColumn:@"d"], @"Should have non-nil date for 'd'");
  144. [rs doubleForColumn:@"d"];
  145. [rs doubleForColumn:@"e"];
  146. XCTAssertEqualObjects([rs columnNameForIndex:0], @"rowid", @"Wrong column name for result set column number");
  147. XCTAssertEqualObjects([rs columnNameForIndex:1], @"a", @"Wrong column name for result set column number");
  148. }
  149. [rs close];
  150. XCTAssertFalse([self.db hasOpenResultSets], @"Shouldn't have any open result sets");
  151. XCTAssertFalse([self.db hadError], @"Shouldn't have any errors");
  152. }
  153. - (void)testInvalidColumnNames
  154. {
  155. FMResultSet *rs = [self.db executeQuery:@"select rowid, a, b, c from test"];
  156. XCTAssertNotNil(rs, @"Should have a non-nil result set");
  157. NSString *invalidColumnName = @"foobar";
  158. while ([rs next]) {
  159. XCTAssertNil(rs[invalidColumnName], @"Invalid column name should return nil");
  160. XCTAssertNil([rs stringForColumn:invalidColumnName], @"Invalid column name should return nil");
  161. XCTAssertEqual([rs UTF8StringForColumn:invalidColumnName], (const unsigned char *)0, @"Invalid column name should return nil");
  162. XCTAssertNil([rs dateForColumn:invalidColumnName], @"Invalid column name should return nil");
  163. XCTAssertNil([rs dataForColumn:invalidColumnName], @"Invalid column name should return nil");
  164. XCTAssertNil([rs dataNoCopyForColumn:invalidColumnName], @"Invalid column name should return nil");
  165. XCTAssertNil([rs objectForColumn:invalidColumnName], @"Invalid column name should return nil");
  166. }
  167. [rs close];
  168. XCTAssertFalse([self.db hasOpenResultSets], @"Shouldn't have any open result sets");
  169. XCTAssertFalse([self.db hadError], @"Shouldn't have any errors");
  170. }
  171. - (void)testInvalidColumnIndexes
  172. {
  173. FMResultSet *rs = [self.db executeQuery:@"select rowid, a, b, c from test"];
  174. XCTAssertNotNil(rs, @"Should have a non-nil result set");
  175. int invalidColumnIndex = 999;
  176. while ([rs next]) {
  177. XCTAssertNil(rs[invalidColumnIndex], @"Invalid column name should return nil");
  178. XCTAssertNil([rs stringForColumnIndex:invalidColumnIndex], @"Invalid column name should return nil");
  179. XCTAssertEqual([rs UTF8StringForColumnIndex:invalidColumnIndex], (const unsigned char *)0, @"Invalid column name should return nil");
  180. XCTAssertNil([rs dateForColumnIndex:invalidColumnIndex], @"Invalid column name should return nil");
  181. XCTAssertNil([rs dataForColumnIndex:invalidColumnIndex], @"Invalid column name should return nil");
  182. XCTAssertNil([rs dataNoCopyForColumnIndex:invalidColumnIndex], @"Invalid column name should return nil");
  183. XCTAssertNil([rs objectForColumnIndex:invalidColumnIndex], @"Invalid column name should return nil");
  184. }
  185. [rs close];
  186. XCTAssertFalse([self.db hasOpenResultSets], @"Shouldn't have any open result sets");
  187. XCTAssertFalse([self.db hadError], @"Shouldn't have any errors");
  188. }
  189. - (void)testBusyRetryTimeout
  190. {
  191. [self.db executeUpdate:@"create table t1 (a integer)"];
  192. [self.db executeUpdate:@"insert into t1 values (?)", [NSNumber numberWithInt:5]];
  193. [self.db setMaxBusyRetryTimeInterval:2];
  194. FMDatabase *newDB = [FMDatabase databaseWithPath:self.databasePath];
  195. [newDB open];
  196. FMResultSet *rs = [newDB executeQuery:@"select rowid,* from test where a = ?", @"hi'"];
  197. [rs next]; // just grab one... which will keep the db locked
  198. XCTAssertFalse([self.db executeUpdate:@"insert into t1 values (5)"], @"Insert should fail because the db is locked by a read");
  199. XCTAssertEqual([self.db lastErrorCode], SQLITE_BUSY, @"SQLITE_BUSY should be the last error");
  200. [rs close];
  201. [newDB close];
  202. XCTAssertTrue([self.db executeUpdate:@"insert into t1 values (5)"], @"The database shouldn't be locked at this point");
  203. }
  204. - (void)testCaseSensitiveResultDictionary
  205. {
  206. // case sensitive result dictionary test
  207. [self.db executeUpdate:@"create table cs (aRowName integer, bRowName text)"];
  208. [self.db executeUpdate:@"insert into cs (aRowName, bRowName) values (?, ?)", [NSNumber numberWithInt:1], @"hello"];
  209. XCTAssertFalse([self.db hadError], @"Shouldn't have any errors");
  210. FMResultSet *rs = [self.db executeQuery:@"select * from cs"];
  211. while ([rs next]) {
  212. NSDictionary *d = [rs resultDictionary];
  213. XCTAssertNotNil([d objectForKey:@"aRowName"], @"aRowName should be non-nil");
  214. XCTAssertNil([d objectForKey:@"arowname"], @"arowname should be nil");
  215. XCTAssertNotNil([d objectForKey:@"bRowName"], @"bRowName should be non-nil");
  216. XCTAssertNil([d objectForKey:@"browname"], @"browname should be nil");
  217. }
  218. [rs close];
  219. XCTAssertFalse([self.db hasOpenResultSets], @"Shouldn't have any open result sets");
  220. XCTAssertFalse([self.db hadError], @"Shouldn't have any errors");
  221. }
  222. - (void)testBoolInsert
  223. {
  224. [self.db executeUpdate:@"create table btest (aRowName integer)"];
  225. [self.db executeUpdate:@"insert into btest (aRowName) values (?)", [NSNumber numberWithBool:YES]];
  226. XCTAssertFalse([self.db hadError], @"Shouldn't have any errors");
  227. FMResultSet *rs = [self.db executeQuery:@"select * from btest"];
  228. while ([rs next]) {
  229. XCTAssertTrue([rs boolForColumnIndex:0], @"first column should be true.");
  230. XCTAssertTrue([rs intForColumnIndex:0] == 1, @"first column should be equal to 1 - it was %d.", [rs intForColumnIndex:0]);
  231. }
  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. - (void)testNamedParametersCount
  237. {
  238. XCTAssertTrue([self.db executeUpdate:@"create table namedparamcounttest (a text, b text, c integer, d double)"]);
  239. NSMutableDictionary *dictionaryArgs = [NSMutableDictionary dictionary];
  240. [dictionaryArgs setObject:@"Text1" forKey:@"a"];
  241. [dictionaryArgs setObject:@"Text2" forKey:@"b"];
  242. [dictionaryArgs setObject:[NSNumber numberWithInt:1] forKey:@"c"];
  243. [dictionaryArgs setObject:[NSNumber numberWithDouble:2.0] forKey:@"d"];
  244. XCTAssertTrue([self.db executeUpdate:@"insert into namedparamcounttest values (:a, :b, :c, :d)" withParameterDictionary:dictionaryArgs]);
  245. FMResultSet *rs = [self.db executeQuery:@"select * from namedparamcounttest"];
  246. XCTAssertNotNil(rs);
  247. [rs next];
  248. XCTAssertEqualObjects([rs stringForColumn:@"a"], @"Text1");
  249. XCTAssertEqualObjects([rs stringForColumn:@"b"], @"Text2");
  250. XCTAssertEqual([rs intForColumn:@"c"], 1);
  251. XCTAssertEqual([rs doubleForColumn:@"d"], 2.0);
  252. [rs close];
  253. // note that at this point, dictionaryArgs has way more values than we need, but the query should still work since
  254. // a is in there, and that's all we need.
  255. rs = [self.db executeQuery:@"select * from namedparamcounttest where a = :a" withParameterDictionary:dictionaryArgs];
  256. XCTAssertNotNil(rs);
  257. XCTAssertTrue([rs next]);
  258. [rs close];
  259. // ***** Please note the following codes *****
  260. dictionaryArgs = [NSMutableDictionary dictionary];
  261. [dictionaryArgs setObject:@"NewText1" forKey:@"a"];
  262. [dictionaryArgs setObject:@"NewText2" forKey:@"b"];
  263. [dictionaryArgs setObject:@"OneMoreText" forKey:@"OneMore"];
  264. XCTAssertTrue([self.db executeUpdate:@"update namedparamcounttest set a = :a, b = :b where b = 'Text2'" withParameterDictionary:dictionaryArgs]);
  265. }
  266. - (void)testBlobs
  267. {
  268. [self.db executeUpdate:@"create table blobTable (a text, b blob)"];
  269. // let's read an image from safari's app bundle.
  270. NSData *safariCompass = [NSData dataWithContentsOfFile:@"/Applications/Safari.app/Contents/Resources/compass.icns"];
  271. if (safariCompass) {
  272. [self.db executeUpdate:@"insert into blobTable (a, b) values (?, ?)", @"safari's compass", safariCompass];
  273. FMResultSet *rs = [self.db executeQuery:@"select b from blobTable where a = ?", @"safari's compass"];
  274. XCTAssertTrue([rs next]);
  275. NSData *readData = [rs dataForColumn:@"b"];
  276. XCTAssertEqualObjects(readData, safariCompass);
  277. // ye shall read the header for this function, or suffer the consequences.
  278. NSData *readDataNoCopy = [rs dataNoCopyForColumn:@"b"];
  279. XCTAssertEqualObjects(readDataNoCopy, safariCompass);
  280. [rs close];
  281. XCTAssertFalse([self.db hasOpenResultSets], @"Shouldn't have any open result sets");
  282. XCTAssertFalse([self.db hadError], @"Shouldn't have any errors");
  283. }
  284. }
  285. - (void)testNullValues
  286. {
  287. [self.db executeUpdate:@"create table t2 (a integer, b integer)"];
  288. BOOL result = [self.db executeUpdate:@"insert into t2 values (?, ?)", nil, [NSNumber numberWithInt:5]];
  289. XCTAssertTrue(result, @"Failed to insert a nil value");
  290. FMResultSet *rs = [self.db executeQuery:@"select * from t2"];
  291. while ([rs next]) {
  292. XCTAssertNil([rs stringForColumnIndex:0], @"Wasn't able to retrieve a null string");
  293. XCTAssertEqualObjects([rs stringForColumnIndex:1], @"5");
  294. }
  295. [rs close];
  296. XCTAssertFalse([self.db hasOpenResultSets], @"Shouldn't have any open result sets");
  297. XCTAssertFalse([self.db hadError], @"Shouldn't have any errors");
  298. }
  299. - (void)testNestedResultSets
  300. {
  301. FMResultSet *rs = [self.db executeQuery:@"select * from t3"];
  302. while ([rs next]) {
  303. int foo = [rs intForColumnIndex:0];
  304. int newVal = foo + 100;
  305. [self.db executeUpdate:@"update t3 set a = ? where a = ?", [NSNumber numberWithInt:newVal], [NSNumber numberWithInt:foo]];
  306. FMResultSet *rs2 = [self.db executeQuery:@"select a from t3 where a = ?", [NSNumber numberWithInt:newVal]];
  307. [rs2 next];
  308. XCTAssertEqual([rs2 intForColumnIndex:0], newVal);
  309. [rs2 close];
  310. }
  311. [rs close];
  312. XCTAssertFalse([self.db hasOpenResultSets], @"Shouldn't have any open result sets");
  313. XCTAssertFalse([self.db hadError], @"Shouldn't have any errors");
  314. }
  315. - (void)testNSNullInsertion
  316. {
  317. [self.db executeUpdate:@"create table nulltest (a text, b text)"];
  318. [self.db executeUpdate:@"insert into nulltest (a, b) values (?, ?)", [NSNull null], @"a"];
  319. [self.db executeUpdate:@"insert into nulltest (a, b) values (?, ?)", nil, @"b"];
  320. FMResultSet *rs = [self.db executeQuery:@"select * from nulltest"];
  321. while ([rs next]) {
  322. XCTAssertNil([rs stringForColumnIndex:0]);
  323. XCTAssertNotNil([rs stringForColumnIndex:1]);
  324. }
  325. [rs close];
  326. XCTAssertFalse([self.db hasOpenResultSets], @"Shouldn't have any open result sets");
  327. XCTAssertFalse([self.db hadError], @"Shouldn't have any errors");
  328. }
  329. - (void)testNullDates
  330. {
  331. NSDate *date = [NSDate date];
  332. [self.db executeUpdate:@"create table datetest (a double, b double, c double)"];
  333. [self.db executeUpdate:@"insert into datetest (a, b, c) values (?, ?, 0)" , [NSNull null], date];
  334. FMResultSet *rs = [self.db executeQuery:@"select * from datetest"];
  335. XCTAssertNotNil(rs);
  336. while ([rs next]) {
  337. NSDate *b = [rs dateForColumnIndex:1];
  338. NSDate *c = [rs dateForColumnIndex:2];
  339. XCTAssertNil([rs dateForColumnIndex:0]);
  340. XCTAssertNotNil(c, @"zero date shouldn't be nil");
  341. XCTAssertEqualWithAccuracy([b timeIntervalSinceDate:date], 0.0, 1.0, @"Dates should be the same to within a second");
  342. XCTAssertEqualWithAccuracy([c timeIntervalSince1970], 0.0, 1.0, @"Dates should be the same to within a second");
  343. }
  344. [rs close];
  345. XCTAssertFalse([self.db hasOpenResultSets], @"Shouldn't have any open result sets");
  346. XCTAssertFalse([self.db hadError], @"Shouldn't have any errors");
  347. }
  348. - (void)testLotsOfNULLs
  349. {
  350. NSData *safariCompass = [NSData dataWithContentsOfFile:@"/Applications/Safari.app/Contents/Resources/compass.icns"];
  351. if (!safariCompass)
  352. return;
  353. [self.db executeUpdate:@"create table nulltest2 (s text, d data, i integer, f double, b integer)"];
  354. [self.db executeUpdate:@"insert into nulltest2 (s, d, i, f, b) values (?, ?, ?, ?, ?)" , @"Hi", safariCompass, [NSNumber numberWithInt:12], [NSNumber numberWithFloat:4.4f], [NSNumber numberWithBool:YES]];
  355. [self.db executeUpdate:@"insert into nulltest2 (s, d, i, f, b) values (?, ?, ?, ?, ?)" , nil, nil, nil, nil, [NSNull null]];
  356. FMResultSet *rs = [self.db executeQuery:@"select * from nulltest2"];
  357. while ([rs next]) {
  358. int i = [rs intForColumnIndex:2];
  359. if (i == 12) {
  360. // it's the first row we inserted.
  361. XCTAssertFalse([rs columnIndexIsNull:0]);
  362. XCTAssertFalse([rs columnIndexIsNull:1]);
  363. XCTAssertFalse([rs columnIndexIsNull:2]);
  364. XCTAssertFalse([rs columnIndexIsNull:3]);
  365. XCTAssertFalse([rs columnIndexIsNull:4]);
  366. XCTAssertTrue( [rs columnIndexIsNull:5]);
  367. XCTAssertEqualObjects([rs dataForColumn:@"d"], safariCompass);
  368. XCTAssertNil([rs dataForColumn:@"notthere"]);
  369. XCTAssertNil([rs stringForColumnIndex:-2], @"Negative columns should return nil results");
  370. XCTAssertTrue([rs boolForColumnIndex:4]);
  371. XCTAssertTrue([rs boolForColumn:@"b"]);
  372. XCTAssertEqualWithAccuracy(4.4, [rs doubleForColumn:@"f"], 0.0000001, @"Saving a float and returning it as a double shouldn't change the result much");
  373. XCTAssertEqual([rs intForColumn:@"i"], 12);
  374. XCTAssertEqual([rs intForColumnIndex:2], 12);
  375. XCTAssertEqual([rs intForColumnIndex:12], 0, @"Non-existent columns should return zero for ints");
  376. XCTAssertEqual([rs intForColumn:@"notthere"], 0, @"Non-existent columns should return zero for ints");
  377. XCTAssertEqual([rs longForColumn:@"i"], 12l);
  378. XCTAssertEqual([rs longLongIntForColumn:@"i"], 12ll);
  379. }
  380. else {
  381. // let's test various null things.
  382. XCTAssertTrue([rs columnIndexIsNull:0]);
  383. XCTAssertTrue([rs columnIndexIsNull:1]);
  384. XCTAssertTrue([rs columnIndexIsNull:2]);
  385. XCTAssertTrue([rs columnIndexIsNull:3]);
  386. XCTAssertTrue([rs columnIndexIsNull:4]);
  387. XCTAssertTrue([rs columnIndexIsNull:5]);
  388. XCTAssertNil([rs dataForColumn:@"d"]);
  389. }
  390. }
  391. [rs close];
  392. XCTAssertFalse([self.db hasOpenResultSets], @"Shouldn't have any open result sets");
  393. XCTAssertFalse([self.db hadError], @"Shouldn't have any errors");
  394. }
  395. - (void)testUTF8Strings
  396. {
  397. [self.db executeUpdate:@"create table utest (a text)"];
  398. [self.db executeUpdate:@"insert into utest values (?)", @"/übertest"];
  399. FMResultSet *rs = [self.db executeQuery:@"select * from utest where a = ?", @"/übertest"];
  400. XCTAssertTrue([rs next]);
  401. [rs close];
  402. XCTAssertFalse([self.db hasOpenResultSets], @"Shouldn't have any open result sets");
  403. XCTAssertFalse([self.db hadError], @"Shouldn't have any errors");
  404. }
  405. - (void)testArgumentsInArray
  406. {
  407. [self.db executeUpdate:@"create table testOneHundredTwelvePointTwo (a text, b integer)"];
  408. [self.db executeUpdate:@"insert into testOneHundredTwelvePointTwo values (?, ?)" withArgumentsInArray:[NSArray arrayWithObjects:@"one", [NSNumber numberWithInteger:2], nil]];
  409. [self.db executeUpdate:@"insert into testOneHundredTwelvePointTwo values (?, ?)" withArgumentsInArray:[NSArray arrayWithObjects:@"one", [NSNumber numberWithInteger:3], nil]];
  410. FMResultSet *rs = [self.db executeQuery:@"select * from testOneHundredTwelvePointTwo where b > ?" withArgumentsInArray:[NSArray arrayWithObject:[NSNumber numberWithInteger:1]]];
  411. XCTAssertTrue([rs next]);
  412. XCTAssertTrue([rs hasAnotherRow]);
  413. XCTAssertFalse([self.db hadError]);
  414. XCTAssertEqualObjects([rs stringForColumnIndex:0], @"one");
  415. XCTAssertEqual([rs intForColumnIndex:1], 2);
  416. XCTAssertTrue([rs next]);
  417. XCTAssertEqual([rs intForColumnIndex:1], 3);
  418. XCTAssertFalse([rs next]);
  419. XCTAssertFalse([rs hasAnotherRow]);
  420. }
  421. - (void)testColumnNamesContainingPeriods
  422. {
  423. XCTAssertTrue([self.db executeUpdate:@"create table t4 (a text, b text)"]);
  424. [self.db executeUpdate:@"insert into t4 (a, b) values (?, ?)", @"one", @"two"];
  425. FMResultSet *rs = [self.db executeQuery:@"select t4.a as 't4.a', t4.b from t4;"];
  426. XCTAssertNotNil(rs);
  427. XCTAssertTrue([rs next]);
  428. XCTAssertEqualObjects([rs stringForColumn:@"t4.a"], @"one");
  429. XCTAssertEqualObjects([rs stringForColumn:@"b"], @"two");
  430. XCTAssertEqual(strcmp((const char*)[rs UTF8StringForColumn:@"b"], "two"), 0, @"String comparison should return zero");
  431. [rs close];
  432. // let's try these again, with the withArgumentsInArray: variation
  433. XCTAssertTrue([self.db executeUpdate:@"drop table t4;" withArgumentsInArray:[NSArray array]]);
  434. XCTAssertTrue([self.db executeUpdate:@"create table t4 (a text, b text)" withArgumentsInArray:[NSArray array]]);
  435. [self.db executeUpdate:@"insert into t4 (a, b) values (?, ?)" withArgumentsInArray:[NSArray arrayWithObjects:@"one", @"two", nil]];
  436. rs = [self.db executeQuery:@"select t4.a as 't4.a', t4.b from t4;" withArgumentsInArray:[NSArray array]];
  437. XCTAssertNotNil(rs);
  438. XCTAssertTrue([rs next]);
  439. XCTAssertEqualObjects([rs stringForColumn:@"t4.a"], @"one");
  440. XCTAssertEqualObjects([rs stringForColumn:@"b"], @"two");
  441. XCTAssertEqual(strcmp((const char*)[rs UTF8StringForColumn:@"b"], "two"), 0, @"String comparison should return zero");
  442. [rs close];
  443. }
  444. - (void)testFormatStringParsing
  445. {
  446. XCTAssertTrue([self.db executeUpdate:@"create table t5 (a text, b int, c blob, d text, e text)"]);
  447. [self.db executeUpdateWithFormat:@"insert into t5 values (%s, %d, %@, %c, %lld)", "text", 42, @"BLOB", 'd', 12345678901234ll];
  448. FMResultSet *rs = [self.db executeQueryWithFormat:@"select * from t5 where a = %s and a = %@ and b = %d", "text", @"text", 42];
  449. XCTAssertNotNil(rs);
  450. XCTAssertTrue([rs next]);
  451. XCTAssertEqualObjects([rs stringForColumn:@"a"], @"text");
  452. XCTAssertEqual([rs intForColumn:@"b"], 42);
  453. XCTAssertEqualObjects([rs stringForColumn:@"c"], @"BLOB");
  454. XCTAssertEqualObjects([rs stringForColumn:@"d"], @"d");
  455. XCTAssertEqual([rs longLongIntForColumn:@"e"], 12345678901234ll);
  456. [rs close];
  457. }
  458. - (void)testFormatStringParsingWithSizePrefixes
  459. {
  460. XCTAssertTrue([self.db executeUpdate:@"create table t55 (a text, b int, c float)"]);
  461. short testShort = -4;
  462. float testFloat = 5.5;
  463. [self.db executeUpdateWithFormat:@"insert into t55 values (%c, %hi, %g)", 'a', testShort, testFloat];
  464. unsigned short testUShort = 6;
  465. [self.db executeUpdateWithFormat:@"insert into t55 values (%c, %hu, %g)", 'a', testUShort, testFloat];
  466. FMResultSet *rs = [self.db executeQueryWithFormat:@"select * from t55 where a = %s order by 2", "a"];
  467. XCTAssertNotNil(rs);
  468. XCTAssertTrue([rs next]);
  469. XCTAssertEqualObjects([rs stringForColumn:@"a"], @"a");
  470. XCTAssertEqual([rs intForColumn:@"b"], -4);
  471. XCTAssertEqualObjects([rs stringForColumn:@"c"], @"5.5");
  472. XCTAssertTrue([rs next]);
  473. XCTAssertEqualObjects([rs stringForColumn:@"a"], @"a");
  474. XCTAssertEqual([rs intForColumn:@"b"], 6);
  475. XCTAssertEqualObjects([rs stringForColumn:@"c"], @"5.5");
  476. [rs close];
  477. }
  478. - (void)testFormatStringParsingWithNilValue
  479. {
  480. XCTAssertTrue([self.db executeUpdate:@"create table tatwhat (a text)"]);
  481. BOOL worked = [self.db executeUpdateWithFormat:@"insert into tatwhat values(%@)", nil];
  482. XCTAssertTrue(worked);
  483. FMResultSet *rs = [self.db executeQueryWithFormat:@"select * from tatwhat"];
  484. XCTAssertNotNil(rs);
  485. XCTAssertTrue([rs next]);
  486. XCTAssertTrue([rs columnIndexIsNull:0]);
  487. XCTAssertFalse([rs next]);
  488. }
  489. - (void)testUpdateWithErrorAndBindings
  490. {
  491. XCTAssertTrue([self.db executeUpdate:@"create table t5 (a text, b int, c blob, d text, e text)"]);
  492. NSError *err = nil;
  493. BOOL result = [self.db executeUpdate:@"insert into t5 values (?, ?, ?, ?, ?)" withErrorAndBindings:&err, @"text", [NSNumber numberWithInt:42], @"BLOB", @"d", [NSNumber numberWithInt:0]];
  494. XCTAssertTrue(result);
  495. }
  496. - (void)testSelectWithEmptyArgumentsArray
  497. {
  498. FMResultSet *rs = [self.db executeQuery:@"select * from test where a=?" withArgumentsInArray:@[]];
  499. XCTAssertNil(rs);
  500. }
  501. - (void)testDatabaseAttach
  502. {
  503. NSFileManager *fileManager = [NSFileManager new];
  504. [fileManager removeItemAtPath:@"/tmp/attachme.db" error:nil];
  505. FMDatabase *dbB = [FMDatabase databaseWithPath:@"/tmp/attachme.db"];
  506. XCTAssertTrue([dbB open]);
  507. XCTAssertTrue([dbB executeUpdate:@"create table attached (a text)"]);
  508. XCTAssertTrue(([dbB executeUpdate:@"insert into attached values (?)", @"test"]));
  509. XCTAssertTrue([dbB close]);
  510. [self.db executeUpdate:@"attach database '/tmp/attachme.db' as attack"];
  511. FMResultSet *rs = [self.db executeQuery:@"select * from attack.attached"];
  512. XCTAssertNotNil(rs);
  513. XCTAssertTrue([rs next]);
  514. [rs close];
  515. }
  516. - (void)testNamedParameters
  517. {
  518. // -------------------------------------------------------------------------------
  519. // Named parameters.
  520. XCTAssertTrue([self.db executeUpdate:@"create table namedparamtest (a text, b text, c integer, d double)"]);
  521. NSMutableDictionary *dictionaryArgs = [NSMutableDictionary dictionary];
  522. [dictionaryArgs setObject:@"Text1" forKey:@"a"];
  523. [dictionaryArgs setObject:@"Text2" forKey:@"b"];
  524. [dictionaryArgs setObject:[NSNumber numberWithInt:1] forKey:@"c"];
  525. [dictionaryArgs setObject:[NSNumber numberWithDouble:2.0] forKey:@"d"];
  526. XCTAssertTrue([self.db executeUpdate:@"insert into namedparamtest values (:a, :b, :c, :d)" withParameterDictionary:dictionaryArgs]);
  527. FMResultSet *rs = [self.db executeQuery:@"select * from namedparamtest"];
  528. XCTAssertNotNil(rs);
  529. XCTAssertTrue([rs next]);
  530. XCTAssertEqualObjects([rs stringForColumn:@"a"], @"Text1");
  531. XCTAssertEqualObjects([rs stringForColumn:@"b"], @"Text2");
  532. XCTAssertEqual([rs intForColumn:@"c"], 1);
  533. XCTAssertEqual([rs doubleForColumn:@"d"], 2.0);
  534. [rs close];
  535. dictionaryArgs = [NSMutableDictionary dictionary];
  536. [dictionaryArgs setObject:@"Text2" forKey:@"blah"];
  537. rs = [self.db executeQuery:@"select * from namedparamtest where b = :blah" withParameterDictionary:dictionaryArgs];
  538. XCTAssertNotNil(rs);
  539. XCTAssertTrue([rs next]);
  540. XCTAssertEqualObjects([rs stringForColumn:@"b"], @"Text2");
  541. [rs close];
  542. }
  543. - (void)testPragmaDatabaseList
  544. {
  545. FMResultSet *rs = [self.db executeQuery:@"pragma database_list"];
  546. int counter = 0;
  547. while ([rs next]) {
  548. counter++;
  549. XCTAssertEqualObjects([rs stringForColumn:@"file"], self.databasePath);
  550. }
  551. XCTAssertEqual(counter, 1, @"Only one database should be attached");
  552. }
  553. - (void)testCachedStatementsInUse
  554. {
  555. [self.db setShouldCacheStatements:true];
  556. [self.db executeUpdate:@"CREATE TABLE testCacheStatements(key INTEGER PRIMARY KEY, value INTEGER)"];
  557. [self.db executeUpdate:@"INSERT INTO testCacheStatements (key, value) VALUES (1, 2)"];
  558. [self.db executeUpdate:@"INSERT INTO testCacheStatements (key, value) VALUES (2, 4)"];
  559. XCTAssertTrue([[self.db executeQuery:@"SELECT * FROM testCacheStatements WHERE key=1"] next]);
  560. XCTAssertTrue([[self.db executeQuery:@"SELECT * FROM testCacheStatements WHERE key=1"] next]);
  561. }
  562. - (void)testStatementCachingWorks
  563. {
  564. [self.db executeUpdate:@"CREATE TABLE testStatementCaching ( value INTEGER )"];
  565. [self.db executeUpdate:@"INSERT INTO testStatementCaching( value ) VALUES (1)"];
  566. [self.db executeUpdate:@"INSERT INTO testStatementCaching( value ) VALUES (1)"];
  567. [self.db executeUpdate:@"INSERT INTO testStatementCaching( value ) VALUES (2)"];
  568. [self.db setShouldCacheStatements:YES];
  569. // two iterations.
  570. // the first time through no statements will be from the cache.
  571. // the second time through all statements come from the cache.
  572. for (int i = 1; i <= 2; i++ ) {
  573. FMResultSet* rs1 = [self.db executeQuery: @"SELECT rowid, * FROM testStatementCaching WHERE value = ?", @1]; // results in 2 rows...
  574. XCTAssertNotNil(rs1);
  575. XCTAssertTrue([rs1 next]);
  576. // confirm that we're seeing the benefits of caching.
  577. XCTAssertEqual([[rs1 statement] useCount], (long)i);
  578. FMResultSet* rs2 = [self.db executeQuery:@"SELECT rowid, * FROM testStatementCaching WHERE value = ?", @2]; // results in 1 row
  579. XCTAssertNotNil(rs2);
  580. XCTAssertTrue([rs2 next]);
  581. XCTAssertEqual([[rs2 statement] useCount], (long)i);
  582. // 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.
  583. XCTAssertTrue([rs1 next]);
  584. [rs1 close];
  585. [rs2 close];
  586. }
  587. }
  588. /*
  589. Test the date format
  590. */
  591. - (void)testDateFormat
  592. {
  593. void (^testOneDateFormat)(FMDatabase *, NSDate *) = ^( FMDatabase *db, NSDate *testDate ){
  594. [db executeUpdate:@"DROP TABLE IF EXISTS test_format"];
  595. [db executeUpdate:@"CREATE TABLE test_format ( test TEXT )"];
  596. [db executeUpdate:@"INSERT INTO test_format(test) VALUES (?)", testDate];
  597. FMResultSet *rs = [db executeQuery:@"SELECT test FROM test_format"];
  598. XCTAssertNotNil(rs);
  599. XCTAssertTrue([rs next]);
  600. XCTAssertEqualObjects([rs dateForColumnIndex:0], testDate);
  601. [rs close];
  602. };
  603. NSDateFormatter *fmt = [FMDatabase storeableDateFormat:@"yyyy-MM-dd HH:mm:ss"];
  604. NSDate *testDate = [fmt dateFromString:@"2013-02-20 12:00:00"];
  605. // test timestamp dates (ensuring our change does not break those)
  606. testOneDateFormat(self.db,testDate);
  607. // now test the string-based timestamp
  608. [self.db setDateFormat:fmt];
  609. testOneDateFormat(self.db, testDate);
  610. }
  611. - (void)testColumnNameMap
  612. {
  613. XCTAssertTrue([self.db executeUpdate:@"create table colNameTest (a, b, c, d)"]);
  614. XCTAssertTrue([self.db executeUpdate:@"insert into colNameTest values (1, 2, 3, 4)"]);
  615. FMResultSet *ars = [self.db executeQuery:@"select * from colNameTest"];
  616. XCTAssertNotNil(ars);
  617. NSDictionary *d = [ars columnNameToIndexMap];
  618. XCTAssertEqual([d count], (NSUInteger)4);
  619. XCTAssertEqualObjects([d objectForKey:@"a"], @0);
  620. XCTAssertEqualObjects([d objectForKey:@"b"], @1);
  621. XCTAssertEqualObjects([d objectForKey:@"c"], @2);
  622. XCTAssertEqualObjects([d objectForKey:@"d"], @3);
  623. }
  624. - (void)testCustomStringFunction {
  625. [self createCustomFunctions];
  626. FMResultSet *ars = [self.db executeQuery:@"SELECT RemoveDiacritics(?)", @"José"];
  627. if (![ars next]) {
  628. XCTFail("Should have returned value");
  629. return;
  630. }
  631. NSString *result = [ars stringForColumnIndex:0];
  632. XCTAssertEqualObjects(result, @"Jose");
  633. }
  634. - (void)testFailCustomStringFunction {
  635. [self createCustomFunctions];
  636. FMResultSet *rs = [self.db executeQuery:@"SELECT RemoveDiacritics(?)", @(M_PI)];
  637. XCTAssert(rs, @"Prepare should have succeeded");
  638. NSError *error;
  639. BOOL success = [rs nextWithError:&error];
  640. XCTAssertFalse(success, @"'next' should have failed");
  641. XCTAssertEqualObjects(error.localizedDescription, @"Expected text");
  642. rs = [self.db executeQuery:@"SELECT RemoveDiacritics('jose','ortega')"];
  643. XCTAssertNil(rs);
  644. error = [self.db lastError];
  645. XCTAssert([error.localizedDescription containsString:@"wrong number of arguments"], @"Should get wrong number of arguments error, but got '%@'", error.localizedDescription);
  646. }
  647. - (void)testCustomDoubleFunction {
  648. [self createCustomFunctions];
  649. FMResultSet *rs = [self.db executeQuery:@"SELECT Hypotenuse(?, ?)", @(3.0), @(4.0)];
  650. if (![rs next]) {
  651. XCTFail("Should have returned value");
  652. return;
  653. }
  654. double value = [rs doubleForColumnIndex:0];
  655. XCTAssertEqual(value, 5.0);
  656. }
  657. - (void)testCustomIntFunction {
  658. [self createCustomFunctions];
  659. FMResultSet *rs = [self.db executeQuery:@"SELECT Hypotenuse(?, ?)", @(3), @(4)];
  660. if (![rs next]) {
  661. XCTFail("Should have returned value");
  662. return;
  663. }
  664. int value = [rs intForColumnIndex:0];
  665. XCTAssertEqual(value, 5);
  666. }
  667. - (void)testFailCustomNumericFunction {
  668. [self createCustomFunctions];
  669. FMResultSet *rs = [self.db executeQuery:@"SELECT Hypotenuse(?, ?)", @"foo", @"bar"];
  670. NSError *error;
  671. if ([rs nextWithError:&error]) {
  672. XCTFail("Should have failed");
  673. return;
  674. }
  675. XCTAssertEqualObjects(error.localizedDescription, @"Expected numeric");
  676. rs = [self.db executeQuery:@"SELECT Hypotenuse(?)", @(3.0)];
  677. XCTAssertNil(rs, @"Should fail for wrong number of arguments");
  678. error = [self.db lastError];
  679. XCTAssert([error.localizedDescription containsString:@"wrong number of arguments"], @"Should get wrong number of arguments error, but got '%@'", error.localizedDescription);
  680. }
  681. - (void)testCustomDataFunction {
  682. [self createCustomFunctions];
  683. NSMutableData *data = [NSMutableData data];
  684. for (NSInteger i = 0; i < 256; i++) {
  685. uint8_t byte = i;
  686. [data appendBytes:&byte length:1];
  687. }
  688. FMResultSet *rs = [self.db executeQuery:@"SELECT SetAlternatingByteToOne(?)", data];
  689. if (![rs next]) {
  690. XCTFail("Should have returned value");
  691. return;
  692. }
  693. NSData *result = [rs dataForColumnIndex:0];
  694. XCTAssert(result, @"should have result");
  695. XCTAssertEqual(result.length, (unsigned long)256);
  696. for (NSInteger i = 0; i < 256; i++) {
  697. uint8_t byte;
  698. [result getBytes:&byte range:NSMakeRange(i, 1)];
  699. if (i % 2 == 0) {
  700. XCTAssertEqual(byte, (uint8_t)1);
  701. } else {
  702. XCTAssertEqual(byte, (uint8_t)i);
  703. }
  704. }
  705. }
  706. - (void)testFailCustomDataFunction {
  707. [self createCustomFunctions];
  708. FMResultSet *rs = [self.db executeQuery:@"SELECT SetAlternatingByteToOne(?)", @"foo"];
  709. XCTAssert(rs, @"Query should succeed");
  710. NSError *error;
  711. BOOL success = [rs nextWithError:&error];
  712. XCTAssertFalse(success, @"Performing SetAlternatingByteToOne with string should fail");
  713. XCTAssertEqualObjects(error.localizedDescription, @"Expected blob");
  714. }
  715. - (void)testCustomFunctionNullValues {
  716. [self.db makeFunctionNamed:@"FunctionThatDoesntTestTypes" arguments:1 block:^(void *context, int argc, void **argv) {
  717. NSData *data = [self.db valueData:argv[0]];
  718. XCTAssertNil(data);
  719. NSString *string = [self.db valueString:argv[0]];
  720. XCTAssertNil(string);
  721. int intValue = [self.db valueInt:argv[0]];
  722. XCTAssertEqual(intValue, 0);
  723. long longValue = [self.db valueLong:argv[0]];
  724. XCTAssertEqual(longValue, 0L);
  725. double doubleValue = [self.db valueDouble:argv[0]];
  726. XCTAssertEqual(doubleValue, 0.0);
  727. [self.db resultInt:42 context:context];
  728. }];
  729. FMResultSet *rs = [self.db executeQuery:@"SELECT FunctionThatDoesntTestTypes(?)", [NSNull null]];
  730. XCTAssert(rs, @"Creating query should succeed");
  731. NSError *error = nil;
  732. if (rs) {
  733. BOOL success = [rs nextWithError:&error];
  734. XCTAssert(success, @"Performing query should succeed");
  735. }
  736. }
  737. - (void)testCustomFunctionIntResult {
  738. [self.db makeFunctionNamed:@"IntResultFunction" arguments:0 block:^(void *context, int argc, void **argv) {
  739. [self.db resultInt:42 context:context];
  740. }];
  741. FMResultSet *rs = [self.db executeQuery:@"SELECT IntResultFunction()"];
  742. XCTAssert(rs, @"Creating query should succeed");
  743. BOOL success = [rs next];
  744. XCTAssert(success, @"Performing query should succeed");
  745. XCTAssertEqual([rs intForColumnIndex:0], 42);
  746. }
  747. - (void)testCustomFunctionLongResult {
  748. [self.db makeFunctionNamed:@"LongResultFunction" arguments:0 block:^(void *context, int argc, void **argv) {
  749. [self.db resultLong:42 context:context];
  750. }];
  751. FMResultSet *rs = [self.db executeQuery:@"SELECT LongResultFunction()"];
  752. XCTAssert(rs, @"Creating query should succeed");
  753. BOOL success = [rs next];
  754. XCTAssert(success, @"Performing query should succeed");
  755. XCTAssertEqual([rs longForColumnIndex:0], (long)42);
  756. }
  757. - (void)testCustomFunctionDoubleResult {
  758. [self.db makeFunctionNamed:@"DoubleResultFunction" arguments:0 block:^(void *context, int argc, void **argv) {
  759. [self.db resultDouble:0.1 context:context];
  760. }];
  761. FMResultSet *rs = [self.db executeQuery:@"SELECT DoubleResultFunction()"];
  762. XCTAssert(rs, @"Creating query should succeed");
  763. BOOL success = [rs next];
  764. XCTAssert(success, @"Performing query should succeed");
  765. XCTAssertEqual([rs doubleForColumnIndex:0], 0.1);
  766. }
  767. - (void)testCustomFunctionNullResult {
  768. [self.db makeFunctionNamed:@"NullResultFunction" arguments:0 block:^(void *context, int argc, void **argv) {
  769. [self.db resultNullInContext:context];
  770. }];
  771. FMResultSet *rs = [self.db executeQuery:@"SELECT NullResultFunction()"];
  772. XCTAssert(rs, @"Creating query should succeed");
  773. BOOL success = [rs next];
  774. XCTAssert(success, @"Performing query should succeed");
  775. XCTAssertEqualObjects([rs objectForColumnIndex:0], [NSNull null]);
  776. }
  777. - (void)testCustomFunctionErrorResult {
  778. [self.db makeFunctionNamed:@"ErrorResultFunction" arguments:0 block:^(void *context, int argc, void **argv) {
  779. [self.db resultError:@"foo" context:context];
  780. [self.db resultErrorCode:42 context:context];
  781. }];
  782. FMResultSet *rs = [self.db executeQuery:@"SELECT ErrorResultFunction()"];
  783. XCTAssert(rs, @"Creating query should succeed");
  784. NSError *error = nil;
  785. BOOL success = [rs nextWithError:&error];
  786. XCTAssertFalse(success, @"Performing query should fail.");
  787. XCTAssertEqualObjects(error.localizedDescription, @"foo");
  788. XCTAssertEqual(error.code, 42);
  789. }
  790. - (void)testCustomFunctionTooBigErrorResult {
  791. [self.db makeFunctionNamed:@"TooBigErrorResultFunction" arguments:0 block:^(void *context, int argc, void **argv) {
  792. [self.db resultErrorTooBigInContext:context];
  793. }];
  794. FMResultSet *rs = [self.db executeQuery:@"SELECT TooBigErrorResultFunction()"];
  795. XCTAssert(rs, @"Creating query should succeed");
  796. NSError *error = nil;
  797. BOOL success = [rs nextWithError:&error];
  798. XCTAssertFalse(success, @"Performing query should fail.");
  799. XCTAssertEqualObjects(error.localizedDescription, @"string or blob too big");
  800. XCTAssertEqual(error.code, SQLITE_TOOBIG);
  801. }
  802. - (void)testCustomFunctionNoMemoryErrorResult {
  803. [self.db makeFunctionNamed:@"NoMemoryErrorResultFunction" arguments:0 block:^(void *context, int argc, void **argv) {
  804. [self.db resultErrorNoMemoryInContext:context];
  805. }];
  806. FMResultSet *rs = [self.db executeQuery:@"SELECT NoMemoryErrorResultFunction()"];
  807. XCTAssert(rs, @"Creating query should succeed");
  808. NSError *error = nil;
  809. BOOL success = [rs nextWithError:&error];
  810. XCTAssertFalse(success, @"Performing query should fail.");
  811. XCTAssertEqualObjects(error.localizedDescription, @"out of memory");
  812. XCTAssertEqual(error.code, SQLITE_NOMEM);
  813. }
  814. - (void)createCustomFunctions {
  815. [self.db makeFunctionNamed:@"RemoveDiacritics" arguments:1 block:^(void *context, int argc, void **argv) {
  816. SqliteValueType type = [self.db valueType:argv[0]];
  817. if (type == SqliteValueTypeNull) {
  818. [self.db resultNullInContext:context];
  819. return;
  820. }
  821. if (type != SqliteValueTypeText) {
  822. [self.db resultError:@"Expected text" context:context];
  823. return;
  824. }
  825. NSString *string = [self.db valueString:argv[0]];
  826. NSString *result = [string stringByFoldingWithOptions:NSDiacriticInsensitiveSearch locale:nil];
  827. [self.db resultString:result context:context];
  828. }];
  829. [self.db makeFunctionNamed:@"Hypotenuse" arguments:2 block:^(void *context, int argc, void **argv) {
  830. SqliteValueType type1 = [self.db valueType:argv[0]];
  831. SqliteValueType type2 = [self.db valueType:argv[1]];
  832. if (type1 != SqliteValueTypeFloat && type1 != SqliteValueTypeInteger && type2 != SqliteValueTypeFloat && type2 != SqliteValueTypeInteger) {
  833. [self.db resultError:@"Expected numeric" context:context];
  834. return;
  835. }
  836. double value1 = [self.db valueDouble:argv[0]];
  837. double value2 = [self.db valueDouble:argv[1]];
  838. [self.db resultDouble:hypot(value1, value2) context:context];
  839. }];
  840. [self.db makeFunctionNamed:@"SetAlternatingByteToOne" arguments:1 block:^(void *context, int argc, void **argv) {
  841. SqliteValueType type = [self.db valueType:argv[0]];
  842. if (type != SqliteValueTypeBlob) {
  843. [self.db resultError:@"Expected blob" context:context];
  844. return;
  845. }
  846. NSMutableData *data = [[self.db valueData:argv[0]] mutableCopy];
  847. uint8_t byte = 1;
  848. for (NSUInteger i = 0; i < data.length; i += 2) {
  849. [data replaceBytesInRange:NSMakeRange(i, 1) withBytes:&byte];
  850. }
  851. [self.db resultData:data context:context];
  852. }];
  853. }
  854. /* This is deprecated, and as such, should be excluded from tests
  855. *
  856. * - (void)testVersionNumber {
  857. * XCTAssertEqual([FMDatabase FMDBVersion], 0x0278); // this is going to break every time we bump it.
  858. * }
  859. *
  860. */
  861. - (void)testUserVersion {
  862. NSComparisonResult result = [[FMDatabase FMDBUserVersion] compare:@"2.7.12" options:NSNumericSearch];
  863. XCTAssertEqual(result, NSOrderedSame);
  864. }
  865. - (void)testVersionStringAboveRequired {
  866. NSComparisonResult result = [[FMDatabase FMDBUserVersion] compare:@"1.100.42" options:NSNumericSearch];
  867. XCTAssertEqual(result, NSOrderedDescending);
  868. }
  869. - (void)testVersionStringBelowRequired {
  870. NSComparisonResult result = [[FMDatabase FMDBUserVersion] compare:@"10.0.42" options:NSNumericSearch];
  871. XCTAssertEqual(result, NSOrderedAscending);
  872. }
  873. - (void)testExecuteStatements {
  874. BOOL success;
  875. NSString *sql = @"create table bulktest1 (id integer primary key autoincrement, x text);"
  876. "create table bulktest2 (id integer primary key autoincrement, y text);"
  877. "create table bulktest3 (id integer primary key autoincrement, z text);"
  878. "insert into bulktest1 (x) values ('XXX');"
  879. "insert into bulktest2 (y) values ('YYY');"
  880. "insert into bulktest3 (z) values ('ZZZ');";
  881. success = [self.db executeStatements:sql];
  882. XCTAssertTrue(success, @"bulk create");
  883. sql = @"select count(*) as count from bulktest1;"
  884. "select count(*) as count from bulktest2;"
  885. "select count(*) as count from bulktest3;";
  886. success = [self.db executeStatements:sql withResultBlock:^int(NSDictionary *dictionary) {
  887. NSInteger count = [dictionary[@"count"] integerValue];
  888. XCTAssertEqual(count, 1, @"expected one record for dictionary %@", dictionary);
  889. return 0;
  890. }];
  891. XCTAssertTrue(success, @"bulk select");
  892. // select blob type records
  893. [self.db executeUpdate:@"create table bulktest4 (id integer primary key autoincrement, b blob);"];
  894. NSData *blobData = [[NSData alloc] initWithContentsOfFile:@"/bin/bash"];
  895. [self.db executeUpdate:@"insert into bulktest4 (b) values (?)" values:@[blobData] error:nil];
  896. sql = @"select * from bulktest4";
  897. success = [self.db executeStatements:sql withResultBlock:^int(NSDictionary * _Nonnull resultsDictionary) {
  898. return 0;
  899. }];
  900. XCTAssertTrue(success, @"bulk select");
  901. sql = @"drop table bulktest1;"
  902. "drop table bulktest2;"
  903. "drop table bulktest3;"
  904. "drop table bulktest4";
  905. success = [self.db executeStatements:sql];
  906. XCTAssertTrue(success, @"bulk drop");
  907. }
  908. - (void)testCharAndBoolTypes
  909. {
  910. XCTAssertTrue([self.db executeUpdate:@"create table charBoolTest (a, b, c)"]);
  911. BOOL success = [self.db executeUpdate:@"insert into charBoolTest values (?, ?, ?)", @YES, @NO, @('x')];
  912. XCTAssertTrue(success, @"Unable to insert values");
  913. FMResultSet *rs = [self.db executeQuery:@"select * from charBoolTest"];
  914. XCTAssertNotNil(rs);
  915. XCTAssertTrue([rs next], @"Did not return row");
  916. XCTAssertEqual([rs boolForColumn:@"a"], true);
  917. XCTAssertEqualObjects([rs objectForColumn:@"a"], @YES);
  918. XCTAssertEqual([rs boolForColumn:@"b"], false);
  919. XCTAssertEqualObjects([rs objectForColumn:@"b"], @NO);
  920. XCTAssertEqual([rs intForColumn:@"c"], 'x');
  921. XCTAssertEqualObjects([rs objectForColumn:@"c"], @('x'));
  922. [rs close];
  923. XCTAssertTrue([self.db executeUpdate:@"drop table charBoolTest"], @"Did not drop table");
  924. }
  925. - (void)testSqliteLibVersion
  926. {
  927. NSString *version = [FMDatabase sqliteLibVersion];
  928. XCTAssert([version compare:@"3.7" options:NSNumericSearch] == NSOrderedDescending, @"earlier than 3.7");
  929. XCTAssert([version compare:@"4.0" options:NSNumericSearch] == NSOrderedAscending, @"not earlier than 4.0");
  930. }
  931. - (void)testIsThreadSafe
  932. {
  933. BOOL isThreadSafe = [FMDatabase isSQLiteThreadSafe];
  934. XCTAssert(isThreadSafe, @"not threadsafe");
  935. }
  936. - (void)testOpenNilPath
  937. {
  938. FMDatabase *db = [[FMDatabase alloc] init];
  939. XCTAssert([db open], @"open failed");
  940. XCTAssert([db executeUpdate:@"create table foo (bar text)"], @"create failed");
  941. NSString *value = @"baz";
  942. XCTAssert([db executeUpdate:@"insert into foo (bar) values (?)" withArgumentsInArray:@[value]], @"insert failed");
  943. NSString *retrievedValue = [db stringForQuery:@"select bar from foo"];
  944. XCTAssert([value compare:retrievedValue] == NSOrderedSame, @"values didn't match");
  945. }
  946. - (void)testOpenZeroLengthPath
  947. {
  948. FMDatabase *db = [[FMDatabase alloc] initWithPath:@""];
  949. XCTAssert([db open], @"open failed");
  950. XCTAssert([db executeUpdate:@"create table foo (bar text)"], @"create failed");
  951. NSString *value = @"baz";
  952. XCTAssert([db executeUpdate:@"insert into foo (bar) values (?)" withArgumentsInArray:@[value]], @"insert failed");
  953. NSString *retrievedValue = [db stringForQuery:@"select bar from foo"];
  954. XCTAssert([value compare:retrievedValue] == NSOrderedSame, @"values didn't match");
  955. }
  956. - (void)testOpenTwice
  957. {
  958. FMDatabase *db = [[FMDatabase alloc] init];
  959. [db open];
  960. XCTAssert([db open], @"Double open failed");
  961. }
  962. - (void)testInvalid
  963. {
  964. NSString *documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
  965. NSString *path = [documentsPath stringByAppendingPathComponent:@"nonexistentfolder/test.sqlite"];
  966. FMDatabase *db = [[FMDatabase alloc] initWithPath:path];
  967. XCTAssertFalse([db open], @"open did NOT fail");
  968. }
  969. - (void)testChangingMaxBusyRetryTimeInterval
  970. {
  971. FMDatabase *db = [[FMDatabase alloc] init];
  972. XCTAssert([db open], @"open failed");
  973. NSTimeInterval originalInterval = db.maxBusyRetryTimeInterval;
  974. NSTimeInterval updatedInterval = originalInterval > 0 ? originalInterval + 1 : 1;
  975. db.maxBusyRetryTimeInterval = updatedInterval;
  976. NSTimeInterval diff = fabs(db.maxBusyRetryTimeInterval - updatedInterval);
  977. XCTAssert(diff < 1e-5, @"interval should have changed %.1f", diff);
  978. }
  979. - (void)testChangingMaxBusyRetryTimeIntervalDatabaseNotOpened
  980. {
  981. FMDatabase *db = [[FMDatabase alloc] init];
  982. // XCTAssert([db open], @"open failed"); // deliberately not opened
  983. NSTimeInterval originalInterval = db.maxBusyRetryTimeInterval;
  984. NSTimeInterval updatedInterval = originalInterval > 0 ? originalInterval + 1 : 1;
  985. db.maxBusyRetryTimeInterval = updatedInterval;
  986. XCTAssertNotEqual(originalInterval, db.maxBusyRetryTimeInterval, @"interval should not have changed");
  987. }
  988. - (void)testZeroMaxBusyRetryTimeInterval
  989. {
  990. FMDatabase *db = [[FMDatabase alloc] init];
  991. XCTAssert([db open], @"open failed");
  992. NSTimeInterval updatedInterval = 0;
  993. db.maxBusyRetryTimeInterval = updatedInterval;
  994. XCTAssertEqual(db.maxBusyRetryTimeInterval, updatedInterval, @"busy handler not disabled");
  995. }
  996. - (void)testCloseOpenResultSets
  997. {
  998. FMDatabase *db = [[FMDatabase alloc] init];
  999. XCTAssert([db open], @"open failed");
  1000. XCTAssert([db executeUpdate:@"create table foo (bar text)"], @"create failed");
  1001. NSString *value = @"baz";
  1002. XCTAssert([db executeUpdate:@"insert into foo (bar) values (?)" withArgumentsInArray:@[value]], @"insert failed");
  1003. FMResultSet *rs = [db executeQuery:@"select bar from foo"];
  1004. [db closeOpenResultSets];
  1005. XCTAssertFalse([rs next], @"step should have failed");
  1006. }
  1007. - (void)testGoodConnection
  1008. {
  1009. FMDatabase *db = [[FMDatabase alloc] init];
  1010. XCTAssert([db open], @"open failed");
  1011. XCTAssert([db goodConnection], @"no good connection");
  1012. }
  1013. - (void)testBadConnection
  1014. {
  1015. FMDatabase *db = [[FMDatabase alloc] init];
  1016. // XCTAssert([db open], @"open failed"); // deliberately did not open
  1017. XCTAssertFalse([db goodConnection], @"no good connection");
  1018. }
  1019. - (void)testLastRowId
  1020. {
  1021. FMDatabase *db = [[FMDatabase alloc] init];
  1022. XCTAssert([db open], @"open failed");
  1023. XCTAssert([db executeUpdate:@"create table foo (foo_id integer primary key autoincrement, bar text)"], @"create failed");
  1024. XCTAssert([db executeUpdate:@"insert into foo (bar) values (?)" withArgumentsInArray:@[@"baz"]], @"insert failed");
  1025. sqlite3_int64 firstRowId = [db lastInsertRowId];
  1026. XCTAssert([db executeUpdate:@"insert into foo (bar) values (?)" withArgumentsInArray:@[@"qux"]], @"insert failed");
  1027. sqlite3_int64 secondRowId = [db lastInsertRowId];
  1028. XCTAssertEqual(secondRowId - firstRowId, 1, @"rowid should have incremented");
  1029. }
  1030. - (void)testChanges
  1031. {
  1032. FMDatabase *db = [[FMDatabase alloc] init];
  1033. XCTAssert([db open], @"open failed");
  1034. XCTAssert([db executeUpdate:@"create table foo (foo_id integer primary key autoincrement, bar text)"], @"create failed");
  1035. XCTAssert([db executeUpdate:@"insert into foo (bar) values (?)" withArgumentsInArray:@[@"baz"]], @"insert failed");
  1036. XCTAssert([db executeUpdate:@"insert into foo (bar) values (?)" withArgumentsInArray:@[@"qux"]], @"insert failed");
  1037. XCTAssert([db executeUpdate:@"update foo set bar = ?" withArgumentsInArray:@[@"xxx"]], @"insert failed");
  1038. int changes = [db changes];
  1039. XCTAssertEqual(changes, 2, @"two rows should have incremented \(%ld)", (long)changes);
  1040. }
  1041. - (void)testBind {
  1042. FMDatabase *db = [[FMDatabase alloc] init];
  1043. XCTAssert([db open], @"open failed");
  1044. XCTAssert([db executeUpdate:@"create table foo (id integer primary key autoincrement, a numeric)"], @"create failed");
  1045. NSNumber *insertedValue;
  1046. NSNumber *retrievedValue;
  1047. insertedValue = [NSNumber numberWithChar:51];
  1048. XCTAssert([db executeUpdate:@"insert into foo (a) values (?)" withArgumentsInArray:@[insertedValue]], @"insert failed");
  1049. retrievedValue = @([db intForQuery:@"select a from foo where id = ?", @([db lastInsertRowId])]);
  1050. XCTAssertEqualObjects(insertedValue, retrievedValue, @"values don't match");
  1051. insertedValue = [NSNumber numberWithUnsignedChar:52];
  1052. XCTAssert([db executeUpdate:@"insert into foo (a) values (?)" withArgumentsInArray:@[insertedValue]], @"insert failed");
  1053. retrievedValue = @([db intForQuery:@"select a from foo where id = ?", @([db lastInsertRowId])]);
  1054. XCTAssertEqualObjects(insertedValue, retrievedValue, @"values don't match");
  1055. insertedValue = [NSNumber numberWithShort:53];
  1056. XCTAssert([db executeUpdate:@"insert into foo (a) values (?)" withArgumentsInArray:@[insertedValue]], @"insert failed");
  1057. retrievedValue = @([db intForQuery:@"select a from foo where id = ?", @([db lastInsertRowId])]);
  1058. XCTAssertEqualObjects(insertedValue, retrievedValue, @"values don't match");
  1059. insertedValue = [NSNumber numberWithUnsignedShort:54];
  1060. XCTAssert([db executeUpdate:@"insert into foo (a) values (?)" withArgumentsInArray:@[insertedValue]], @"insert failed");
  1061. retrievedValue = @([db intForQuery:@"select a from foo where id = ?", @([db lastInsertRowId])]);
  1062. XCTAssertEqualObjects(insertedValue, retrievedValue, @"values don't match");
  1063. insertedValue = [NSNumber numberWithInt:54];
  1064. XCTAssert([db executeUpdate:@"insert into foo (a) values (?)" withArgumentsInArray:@[insertedValue]], @"insert failed");
  1065. retrievedValue = @([db intForQuery:@"select a from foo where id = ?", @([db lastInsertRowId])]);
  1066. XCTAssertEqualObjects(insertedValue, retrievedValue, @"values don't match");
  1067. insertedValue = [NSNumber numberWithUnsignedInt:55];
  1068. XCTAssert([db executeUpdate:@"insert into foo (a) values (?)" withArgumentsInArray:@[insertedValue]], @"insert failed");
  1069. retrievedValue = @([db intForQuery:@"select a from foo where id = ?", @([db lastInsertRowId])]);
  1070. XCTAssertEqualObjects(insertedValue, retrievedValue, @"values don't match");
  1071. insertedValue = [NSNumber numberWithLong:56];
  1072. XCTAssert([db executeUpdate:@"insert into foo (a) values (?)" withArgumentsInArray:@[insertedValue]], @"insert failed");
  1073. retrievedValue = @([db longForQuery:@"select a from foo where id = ?", @([db lastInsertRowId])]);
  1074. XCTAssertEqualObjects(insertedValue, retrievedValue, @"values don't match");
  1075. insertedValue = [NSNumber numberWithUnsignedLong:57];
  1076. XCTAssert([db executeUpdate:@"insert into foo (a) values (?)" withArgumentsInArray:@[insertedValue]], @"insert failed");
  1077. retrievedValue = @([db longForQuery:@"select a from foo where id = ?", @([db lastInsertRowId])]);
  1078. XCTAssertEqualObjects(insertedValue, retrievedValue, @"values don't match");
  1079. insertedValue = [NSNumber numberWithLongLong:56];
  1080. XCTAssert([db executeUpdate:@"insert into foo (a) values (?)" withArgumentsInArray:@[insertedValue]], @"insert failed");
  1081. retrievedValue = @([db longForQuery:@"select a from foo where id = ?", @([db lastInsertRowId])]);
  1082. XCTAssertEqualObjects(insertedValue, retrievedValue, @"values don't match");
  1083. insertedValue = [NSNumber numberWithUnsignedLongLong:57];
  1084. XCTAssert([db executeUpdate:@"insert into foo (a) values (?)" withArgumentsInArray:@[insertedValue]], @"insert failed");
  1085. retrievedValue = @([db longForQuery:@"select a from foo where id = ?", @([db lastInsertRowId])]);
  1086. XCTAssertEqualObjects(insertedValue, retrievedValue, @"values don't match");
  1087. insertedValue = [NSNumber numberWithFloat:58];
  1088. XCTAssert([db executeUpdate:@"insert into foo (a) values (?)" withArgumentsInArray:@[insertedValue]], @"insert failed");
  1089. retrievedValue = @([db doubleForQuery:@"select a from foo where id = ?", @([db lastInsertRowId])]);
  1090. XCTAssertEqualObjects(insertedValue, retrievedValue, @"values don't match");
  1091. insertedValue = [NSNumber numberWithDouble:59];
  1092. XCTAssert([db executeUpdate:@"insert into foo (a) values (?)" withArgumentsInArray:@[insertedValue]], @"insert failed");
  1093. retrievedValue = @([db doubleForQuery:@"select a from foo where id = ?", @([db lastInsertRowId])]);
  1094. XCTAssertEqualObjects(insertedValue, retrievedValue, @"values don't match");
  1095. insertedValue = @TRUE;
  1096. XCTAssert([db executeUpdate:@"insert into foo (a) values (?)" withArgumentsInArray:@[insertedValue]], @"insert failed");
  1097. retrievedValue = @([db boolForQuery:@"select a from foo where id = ?", @([db lastInsertRowId])]);
  1098. XCTAssertEqualObjects(insertedValue, retrievedValue, @"values don't match");
  1099. }
  1100. - (void)testFormatStrings {
  1101. FMDatabase *db = [[FMDatabase alloc] init];
  1102. XCTAssert([db open], @"open failed");
  1103. XCTAssert([db executeUpdate:@"create table foo (id integer primary key autoincrement, a numeric)"], @"create failed");
  1104. BOOL success;
  1105. char insertedChar = 'A';
  1106. success = [db executeUpdateWithFormat:@"insert into foo (a) values (%c)", insertedChar];
  1107. XCTAssert(success, @"insert failed");
  1108. const char *retrievedChar = [[db stringForQuery:@"select a from foo where id = ?", @([db lastInsertRowId])] UTF8String];
  1109. XCTAssertEqual(insertedChar, retrievedChar[0], @"values don't match");
  1110. const char *insertedString = "baz";
  1111. success = [db executeUpdateWithFormat:@"insert into foo (a) values (%s)", insertedString];
  1112. XCTAssert(success, @"insert failed");
  1113. const char *retrievedString = [[db stringForQuery:@"select a from foo where id = ?", @([db lastInsertRowId])] UTF8String];
  1114. XCTAssert(strcmp(insertedString, retrievedString) == 0, @"values don't match");
  1115. int insertedInt = 42;
  1116. success = [db executeUpdateWithFormat:@"insert into foo (a) values (%d)", insertedInt];
  1117. XCTAssert(success, @"insert failed");
  1118. int retrievedInt = [db intForQuery:@"select a from foo where id = ?", @([db lastInsertRowId])];
  1119. XCTAssertEqual(insertedInt, retrievedInt, @"values don't match");
  1120. char insertedUnsignedInt = 43;
  1121. success = [db executeUpdateWithFormat:@"insert into foo (a) values (%u)", insertedUnsignedInt];
  1122. XCTAssert(success, @"insert failed");
  1123. char retrievedUnsignedInt = [db intForQuery:@"select a from foo where id = ?", @([db lastInsertRowId])];
  1124. XCTAssertEqual(insertedUnsignedInt, retrievedUnsignedInt, @"values don't match");
  1125. float insertedFloat = 44;
  1126. success = [db executeUpdateWithFormat:@"insert into foo (a) values (%f)", insertedFloat];
  1127. XCTAssert(success, @"insert failed");
  1128. float retrievedFloat = [db doubleForQuery:@"select a from foo where id = ?", @([db lastInsertRowId])];
  1129. XCTAssertEqual(insertedFloat, retrievedFloat, @"values don't match");
  1130. unsigned long long insertedUnsignedLongLong = 45;
  1131. success = [db executeUpdateWithFormat:@"insert into foo (a) values (%llu)", insertedUnsignedLongLong];
  1132. XCTAssert(success, @"insert failed");
  1133. unsigned long long retrievedUnsignedLongLong = [db longForQuery:@"select a from foo where id = ?", @([db lastInsertRowId])];
  1134. XCTAssertEqual(insertedUnsignedLongLong, retrievedUnsignedLongLong, @"values don't match");
  1135. }
  1136. - (void)testStepError {
  1137. FMDatabase *db = [[FMDatabase alloc] init];
  1138. XCTAssert([db open], @"open failed");
  1139. XCTAssert([db executeUpdate:@"create table foo (id integer primary key)"], @"create failed");
  1140. XCTAssert([db executeUpdate:@"insert into foo (id) values (?)" values:@[@1] error:nil], @"create failed");
  1141. NSError *error;
  1142. BOOL success = [db executeUpdate:@"insert into foo (id) values (?)" values:@[@1] error:&error];
  1143. XCTAssertFalse(success, @"insert of duplicate key should have failed");
  1144. XCTAssertNotNil(error, @"error object should have been generated");
  1145. XCTAssertEqual(error.code, 19, @"error code 19 should have been generated");
  1146. }
  1147. - (void)testCheckpoint {
  1148. FMDatabase *db = [[FMDatabase alloc] init];
  1149. XCTAssertTrue([db open], @"open failed");
  1150. NSError *error = nil;
  1151. int frameCount = 0;
  1152. int checkpointCount = 0;
  1153. [db checkpoint:FMDBCheckpointModeTruncate name:NULL logFrameCount:&frameCount checkpointCount:&checkpointCount error:&error];
  1154. // Verify that we're calling the checkpoint interface, which is a decent scope for this test, without going so far as to verify what checkpoint does
  1155. XCTAssertEqual(frameCount, -1, @"frameCount should be -1 (means not using WAL mode) to verify that we're using the proper checkpoint interface");
  1156. XCTAssertEqual(checkpointCount, -1, @"checkpointCount should be -1 (means not using WAL mode) to verify that we're using the proper checkpoint interface");
  1157. }
  1158. - (void)testImmediateTransaction {
  1159. FMDatabase *db = [[FMDatabase alloc] init];
  1160. XCTAssertTrue([db open], @"open failed");
  1161. [db beginImmediateTransaction];
  1162. [db beginImmediateTransaction];
  1163. // Verify that beginImmediateTransaction behaves as advertised and starts a transaction
  1164. XCTAssertEqualObjects([db lastError].localizedDescription, @"cannot start a transaction within a transaction");
  1165. }
  1166. - (void)testOpenFailure {
  1167. NSURL *tempURL = [NSURL fileURLWithPath:NSTemporaryDirectory()];
  1168. NSURL *fileURL1 = [tempURL URLByAppendingPathComponent:[[NSUUID UUID] UUIDString]];
  1169. NSURL *fileURL2 = [tempURL URLByAppendingPathComponent:[[NSUUID UUID] UUIDString]];
  1170. NSFileManager *manager = [NSFileManager defaultManager];
  1171. // ok, first create one database
  1172. FMDatabase *db = [FMDatabase databaseWithURL:fileURL1];
  1173. BOOL success = [db open];
  1174. XCTAssert(success, @"Database not created correctly for purposes of test");
  1175. success = [db executeUpdate:@"create table if not exists foo (bar text)"];
  1176. XCTAssert(success, @"Table created correctly for purposes of test");
  1177. [db close];
  1178. // now, try to create open second database even though it doesn't exist
  1179. db = [FMDatabase databaseWithURL:fileURL2];
  1180. success = [db openWithFlags:SQLITE_OPEN_READWRITE];
  1181. XCTAssert(!success, @"Opening second database file that doesn't exist should not have succeeded");
  1182. // OK, everything so far is fine, opening a db without CREATE option above should have failed,
  1183. // but so fix the missing file issue and re-opening
  1184. success = [manager copyItemAtURL:fileURL1 toURL:fileURL2 error:nil];
  1185. XCTAssert(success, @"Copying of db should have succeeded");
  1186. // now let's try opening it again
  1187. success = [db openWithFlags:SQLITE_OPEN_READWRITE];
  1188. XCTAssert(success, @"Opening second database should now succeed");
  1189. // now let's try using it
  1190. FMResultSet *rs = [db executeQuery:@"select * from foo"];
  1191. XCTAssertNotNil(rs, @"Should successfully be able to use re-opened database");
  1192. // let's clean up
  1193. [rs close];
  1194. [db close];
  1195. [manager removeItemAtURL:fileURL1 error:nil];
  1196. [manager removeItemAtURL:fileURL2 error:nil];
  1197. }
  1198. // These three utility methods used by `testTransient`, to illustrate dangers of SQLITE_STATIC
  1199. - (BOOL)utility1ForTestTransient:(FMDatabase *)db withValue:(long)value {
  1200. @autoreleasepool {
  1201. NSString *string = [[NSString alloc] initWithFormat:@"value %@", @(value)];
  1202. return [db executeUpdate:@"INSERT INTO foo (bar) VALUES (?)", [string dataUsingEncoding:NSUTF8StringEncoding]];
  1203. }
  1204. }
  1205. - (FMResultSet *)utility2ForTestTransient:(FMDatabase *)db withValue:(long)value {
  1206. @autoreleasepool {
  1207. NSString *string = [[NSString alloc] initWithFormat:@"value %@", @(value)];
  1208. return [db executeQuery:@"SELECT * FROM foo WHERE bar = ?", [string dataUsingEncoding:NSUTF8StringEncoding]];
  1209. }
  1210. }
  1211. - (BOOL)utility3ForTestTransient:(FMResultSet *)rs withValue:(long)value {
  1212. @autoreleasepool {
  1213. NSString *string = [[NSString alloc] initWithFormat:@"xxxxx %@", @(value + 1)];
  1214. XCTAssertEqualObjects(string, @"xxxxx 43"); // Just to ensure the above isn't optimized out
  1215. return [rs next];
  1216. }
  1217. }
  1218. - (void)testTransient {
  1219. NSURL *tempURL = [NSURL fileURLWithPath:NSTemporaryDirectory()];
  1220. NSURL *fileURL = [tempURL URLByAppendingPathComponent:[[NSUUID UUID] UUIDString]];
  1221. NSFileManager *manager = [NSFileManager defaultManager];
  1222. // ok, first create one database
  1223. FMDatabase *db = [FMDatabase databaseWithURL:fileURL];
  1224. BOOL success = [db open];
  1225. XCTAssert(success, @"Database not created correctly for purposes of test");
  1226. success = [db executeUpdate:@"CREATE TABLE IF NOT EXISTS foo (bar BLOB)"];
  1227. XCTAssert(success, @"Table created correctly for purposes of test");
  1228. long value = 42;
  1229. success = [self utility1ForTestTransient:db withValue:value];
  1230. XCTAssert(success, @"INSERT failed");
  1231. FMResultSet *rs = [self utility2ForTestTransient:db withValue:value];
  1232. XCTAssert(rs, @"Creating SELECT failed");
  1233. // the following is the key test, namely if FMDB uses SQLITE_STATIC, the following may fail, but SQLITE_TRANSIENT ensures it will succeed
  1234. success = [self utility3ForTestTransient:rs withValue:value];
  1235. XCTAssert(success, @"Performing SELECT failed");
  1236. // let's clean up
  1237. [rs close];
  1238. [db close];
  1239. [manager removeItemAtURL:fileURL error:nil];
  1240. }
  1241. - (void)testBindFailure {
  1242. NSURL *tempURL = [NSURL fileURLWithPath:NSTemporaryDirectory()];
  1243. NSURL *fileURL = [tempURL URLByAppendingPathComponent:[[NSUUID UUID] UUIDString]];
  1244. NSFileManager *manager = [NSFileManager defaultManager];
  1245. // ok, first create one database
  1246. FMDatabase *db = [FMDatabase databaseWithURL:fileURL];
  1247. BOOL success = [db open];
  1248. XCTAssert(success, @"Database not created correctly for purposes of test");
  1249. success = [db executeUpdate:@"CREATE TABLE IF NOT EXISTS foo (bar BLOB)"];
  1250. XCTAssert(success, @"Table created correctly for purposes of test");
  1251. NSUInteger limit = (NSUInteger)[db limitFor:SQLITE_LIMIT_LENGTH value:-1] + 1;
  1252. NSLog(@"%lu", (unsigned long)limit);
  1253. NSData *data = [NSMutableData dataWithLength:limit];
  1254. success = [db executeUpdate:@"INSERT INTO foo (bar) VALUES (?)", data];
  1255. XCTAssertFalse(success, @"Table created correctly for purposes of test");
  1256. // let's clean up
  1257. [db close];
  1258. [manager removeItemAtURL:fileURL error:nil];
  1259. }
  1260. - (void)testRebindingWithDictionary {
  1261. NSURL *tempURL = [NSURL fileURLWithPath:NSTemporaryDirectory()];
  1262. NSURL *fileURL = [tempURL URLByAppendingPathComponent:[[NSUUID UUID] UUIDString]];
  1263. NSFileManager *manager = [NSFileManager defaultManager];
  1264. [manager removeItemAtURL:fileURL error:nil];
  1265. // ok, first create one database
  1266. FMDatabase *db = [FMDatabase databaseWithURL:fileURL];
  1267. BOOL success = [db open];
  1268. XCTAssert(success, @"Database not created correctly for purposes of test");
  1269. success = [db executeUpdate:@"CREATE TABLE IF NOT EXISTS foo (id INTEGER PRIMARY KEY, bar TEXT)"];
  1270. XCTAssert(success, @"Table created correctly for purposes of test");
  1271. FMResultSet *rs = [db prepare:@"INSERT INTO foo (bar) VALUES (:bar)"];
  1272. XCTAssert(rs, @"INSERT statement not prepared %@", [db lastErrorMessage]);
  1273. NSString *value1 = @"foo";
  1274. XCTAssert([rs bindWithDictionary:@{@"bar": value1}], @"Unable to bind");
  1275. XCTAssert([rs step], @"Performing query failed");
  1276. NSString *value2 = @"bar";
  1277. XCTAssert([rs bindWithDictionary:@{@"bar": value2}], @"Unable to bind");
  1278. XCTAssert([rs step], @"Performing query failed");
  1279. XCTAssert([rs bindWithDictionary:@{@"bar": value2}], @"Unable to bind");
  1280. XCTAssert([rs step], @"Performing query failed");
  1281. [rs close];
  1282. rs = [db prepare:@"SELECT bar FROM foo WHERE bar = :bar"];
  1283. XCTAssert([rs bindWithDictionary:@{@"bar": value1}], @"Unable to bind");
  1284. XCTAssert([rs next], @"No record found");
  1285. XCTAssertEqualObjects([rs stringForColumnIndex:0], value1);
  1286. XCTAssertFalse([rs next], @"There should have been only one record");
  1287. XCTAssert([rs bindWithDictionary:@{@"bar": value2}], @"Unable to bind");
  1288. XCTAssert([rs next], @"No record found");
  1289. XCTAssertEqualObjects([rs stringForColumnIndex:0], value2);
  1290. XCTAssert([rs next], @"No record found");
  1291. XCTAssertEqualObjects([rs stringForColumnIndex:0], value2);
  1292. XCTAssertFalse([rs next], @"There should have been only two records");
  1293. // let's clean up
  1294. [rs close];
  1295. [db close];
  1296. [manager removeItemAtURL:fileURL error:nil];
  1297. }
  1298. - (void)testRebindingWithArray {
  1299. NSURL *tempURL = [NSURL fileURLWithPath:NSTemporaryDirectory()];
  1300. NSURL *fileURL = [tempURL URLByAppendingPathComponent:[[NSUUID UUID] UUIDString]];
  1301. NSFileManager *manager = [NSFileManager defaultManager];
  1302. // ok, first create one database
  1303. FMDatabase *db = [FMDatabase databaseWithURL:fileURL];
  1304. BOOL success = [db open];
  1305. XCTAssert(success, @"Database not created correctly for purposes of test");
  1306. success = [db executeUpdate:@"CREATE TABLE IF NOT EXISTS foo (id INTEGER PRIMARY KEY, bar TEXT)"];
  1307. XCTAssert(success, @"Table created correctly for purposes of test");
  1308. FMResultSet *rs = [db prepare:@"INSERT INTO foo (bar) VALUES (?)"];
  1309. XCTAssert(rs, @"INSERT statement not prepared %@", [db lastErrorMessage]);
  1310. NSString *value1 = @"foo";
  1311. XCTAssert([rs bindWithArray:@[value1]], @"Unable to bind");
  1312. XCTAssert([rs step], @"Performing INSERT 1 failed");
  1313. NSString *value2 = @"bar";
  1314. XCTAssert([rs bindWithArray:@[value2]], @"Unable to bind");
  1315. XCTAssert([rs step], @"Performing INSERT 2 failed");
  1316. XCTAssert([rs bindWithArray:@[value2]], @"Unable to bind");
  1317. XCTAssert([rs step], @"Performing INSERT 2 failed");
  1318. [rs close];
  1319. rs = [db prepare:@"SELECT bar FROM foo WHERE bar = ?"];
  1320. XCTAssert([rs bindWithArray:@[value1]], @"Unable to bind");
  1321. XCTAssert([rs next], @"No record found");
  1322. XCTAssertEqualObjects([rs stringForColumnIndex:0], value1);
  1323. XCTAssertFalse([rs next], @"There should have been only one record");
  1324. XCTAssert([rs bindWithArray:@[value2]], @"Unable to bind");
  1325. XCTAssert([rs next], @"No record found");
  1326. XCTAssertEqualObjects([rs stringForColumnIndex:0], value2);
  1327. XCTAssert([rs next], @"No record found");
  1328. XCTAssertEqualObjects([rs stringForColumnIndex:0], value2);
  1329. XCTAssertFalse([rs next], @"There should have been only two records");
  1330. // let's clean up
  1331. [rs close];
  1332. [db close];
  1333. [manager removeItemAtURL:fileURL error:nil];
  1334. }
  1335. @end