FMDatabaseTests.m 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489
  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 numberWithBool: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:12]];
  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. - (void)testVersionNumber {
  855. XCTAssertTrue([FMDatabase FMDBVersion] == 0x0274); // this is going to break everytime we bump it.
  856. }
  857. - (void)testExecuteStatements {
  858. BOOL success;
  859. NSString *sql = @"create table bulktest1 (id integer primary key autoincrement, x text);"
  860. "create table bulktest2 (id integer primary key autoincrement, y text);"
  861. "create table bulktest3 (id integer primary key autoincrement, z text);"
  862. "insert into bulktest1 (x) values ('XXX');"
  863. "insert into bulktest2 (y) values ('YYY');"
  864. "insert into bulktest3 (z) values ('ZZZ');";
  865. success = [self.db executeStatements:sql];
  866. XCTAssertTrue(success, @"bulk create");
  867. sql = @"select count(*) as count from bulktest1;"
  868. "select count(*) as count from bulktest2;"
  869. "select count(*) as count from bulktest3;";
  870. success = [self.db executeStatements:sql withResultBlock:^int(NSDictionary *dictionary) {
  871. NSInteger count = [dictionary[@"count"] integerValue];
  872. XCTAssertEqual(count, 1, @"expected one record for dictionary %@", dictionary);
  873. return 0;
  874. }];
  875. XCTAssertTrue(success, @"bulk select");
  876. sql = @"drop table bulktest1;"
  877. "drop table bulktest2;"
  878. "drop table bulktest3;";
  879. success = [self.db executeStatements:sql];
  880. XCTAssertTrue(success, @"bulk drop");
  881. }
  882. - (void)testCharAndBoolTypes
  883. {
  884. XCTAssertTrue([self.db executeUpdate:@"create table charBoolTest (a, b, c)"]);
  885. BOOL success = [self.db executeUpdate:@"insert into charBoolTest values (?, ?, ?)", @YES, @NO, @('x')];
  886. XCTAssertTrue(success, @"Unable to insert values");
  887. FMResultSet *rs = [self.db executeQuery:@"select * from charBoolTest"];
  888. XCTAssertNotNil(rs);
  889. XCTAssertTrue([rs next], @"Did not return row");
  890. XCTAssertEqual([rs boolForColumn:@"a"], true);
  891. XCTAssertEqualObjects([rs objectForColumn:@"a"], @YES);
  892. XCTAssertEqual([rs boolForColumn:@"b"], false);
  893. XCTAssertEqualObjects([rs objectForColumn:@"b"], @NO);
  894. XCTAssertEqual([rs intForColumn:@"c"], 'x');
  895. XCTAssertEqualObjects([rs objectForColumn:@"c"], @('x'));
  896. [rs close];
  897. XCTAssertTrue([self.db executeUpdate:@"drop table charBoolTest"], @"Did not drop table");
  898. }
  899. - (void)testSqliteLibVersion
  900. {
  901. NSString *version = [FMDatabase sqliteLibVersion];
  902. XCTAssert([version compare:@"3.7" options:NSNumericSearch] == NSOrderedDescending, @"earlier than 3.7");
  903. XCTAssert([version compare:@"4.0" options:NSNumericSearch] == NSOrderedAscending, @"not earlier than 4.0");
  904. }
  905. - (void)testIsThreadSafe
  906. {
  907. BOOL isThreadSafe = [FMDatabase isSQLiteThreadSafe];
  908. XCTAssert(isThreadSafe, @"not threadsafe");
  909. }
  910. - (void)testOpenNilPath
  911. {
  912. FMDatabase *db = [[FMDatabase alloc] init];
  913. XCTAssert([db open], @"open failed");
  914. XCTAssert([db executeUpdate:@"create table foo (bar text)"], @"create failed");
  915. NSString *value = @"baz";
  916. XCTAssert([db executeUpdate:@"insert into foo (bar) values (?)" withArgumentsInArray:@[value]], @"insert failed");
  917. NSString *retrievedValue = [db stringForQuery:@"select bar from foo"];
  918. XCTAssert([value compare:retrievedValue] == NSOrderedSame, @"values didn't match");
  919. }
  920. - (void)testOpenZeroLengthPath
  921. {
  922. FMDatabase *db = [[FMDatabase alloc] initWithPath:@""];
  923. XCTAssert([db open], @"open failed");
  924. XCTAssert([db executeUpdate:@"create table foo (bar text)"], @"create failed");
  925. NSString *value = @"baz";
  926. XCTAssert([db executeUpdate:@"insert into foo (bar) values (?)" withArgumentsInArray:@[value]], @"insert failed");
  927. NSString *retrievedValue = [db stringForQuery:@"select bar from foo"];
  928. XCTAssert([value compare:retrievedValue] == NSOrderedSame, @"values didn't match");
  929. }
  930. - (void)testOpenTwice
  931. {
  932. FMDatabase *db = [[FMDatabase alloc] init];
  933. [db open];
  934. XCTAssert([db open], @"Double open failed");
  935. }
  936. - (void)testInvalid
  937. {
  938. NSString *documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
  939. NSString *path = [documentsPath stringByAppendingPathComponent:@"nonexistentfolder/test.sqlite"];
  940. FMDatabase *db = [[FMDatabase alloc] initWithPath:path];
  941. XCTAssertFalse([db open], @"open did NOT fail");
  942. }
  943. - (void)testChangingMaxBusyRetryTimeInterval
  944. {
  945. FMDatabase *db = [[FMDatabase alloc] init];
  946. XCTAssert([db open], @"open failed");
  947. NSTimeInterval originalInterval = db.maxBusyRetryTimeInterval;
  948. NSTimeInterval updatedInterval = originalInterval > 0 ? originalInterval + 1 : 1;
  949. db.maxBusyRetryTimeInterval = updatedInterval;
  950. NSTimeInterval diff = fabs(db.maxBusyRetryTimeInterval - updatedInterval);
  951. XCTAssert(diff < 1e-5, @"interval should have changed %.1f", diff);
  952. }
  953. - (void)testChangingMaxBusyRetryTimeIntervalDatabaseNotOpened
  954. {
  955. FMDatabase *db = [[FMDatabase alloc] init];
  956. // XCTAssert([db open], @"open failed"); // deliberately not opened
  957. NSTimeInterval originalInterval = db.maxBusyRetryTimeInterval;
  958. NSTimeInterval updatedInterval = originalInterval > 0 ? originalInterval + 1 : 1;
  959. db.maxBusyRetryTimeInterval = updatedInterval;
  960. XCTAssertNotEqual(originalInterval, db.maxBusyRetryTimeInterval, @"interval should not have changed");
  961. }
  962. - (void)testZeroMaxBusyRetryTimeInterval
  963. {
  964. FMDatabase *db = [[FMDatabase alloc] init];
  965. XCTAssert([db open], @"open failed");
  966. NSTimeInterval updatedInterval = 0;
  967. db.maxBusyRetryTimeInterval = updatedInterval;
  968. XCTAssertEqual(db.maxBusyRetryTimeInterval, updatedInterval, @"busy handler not disabled");
  969. }
  970. - (void)testCloseOpenResultSets
  971. {
  972. FMDatabase *db = [[FMDatabase alloc] init];
  973. XCTAssert([db open], @"open failed");
  974. XCTAssert([db executeUpdate:@"create table foo (bar text)"], @"create failed");
  975. NSString *value = @"baz";
  976. XCTAssert([db executeUpdate:@"insert into foo (bar) values (?)" withArgumentsInArray:@[value]], @"insert failed");
  977. FMResultSet *rs = [db executeQuery:@"select bar from foo"];
  978. [db closeOpenResultSets];
  979. XCTAssertFalse([rs next], @"step should have failed");
  980. }
  981. - (void)testGoodConnection
  982. {
  983. FMDatabase *db = [[FMDatabase alloc] init];
  984. XCTAssert([db open], @"open failed");
  985. XCTAssert([db goodConnection], @"no good connection");
  986. }
  987. - (void)testBadConnection
  988. {
  989. FMDatabase *db = [[FMDatabase alloc] init];
  990. // XCTAssert([db open], @"open failed"); // deliberately did not open
  991. XCTAssertFalse([db goodConnection], @"no good connection");
  992. }
  993. - (void)testLastRowId
  994. {
  995. FMDatabase *db = [[FMDatabase alloc] init];
  996. XCTAssert([db open], @"open failed");
  997. XCTAssert([db executeUpdate:@"create table foo (foo_id integer primary key autoincrement, bar text)"], @"create failed");
  998. XCTAssert([db executeUpdate:@"insert into foo (bar) values (?)" withArgumentsInArray:@[@"baz"]], @"insert failed");
  999. sqlite3_int64 firstRowId = [db lastInsertRowId];
  1000. XCTAssert([db executeUpdate:@"insert into foo (bar) values (?)" withArgumentsInArray:@[@"qux"]], @"insert failed");
  1001. sqlite3_int64 secondRowId = [db lastInsertRowId];
  1002. XCTAssertEqual(secondRowId - firstRowId, 1, @"rowid should have incremented");
  1003. }
  1004. - (void)testChanges
  1005. {
  1006. FMDatabase *db = [[FMDatabase alloc] init];
  1007. XCTAssert([db open], @"open failed");
  1008. XCTAssert([db executeUpdate:@"create table foo (foo_id integer primary key autoincrement, bar text)"], @"create failed");
  1009. XCTAssert([db executeUpdate:@"insert into foo (bar) values (?)" withArgumentsInArray:@[@"baz"]], @"insert failed");
  1010. XCTAssert([db executeUpdate:@"insert into foo (bar) values (?)" withArgumentsInArray:@[@"qux"]], @"insert failed");
  1011. XCTAssert([db executeUpdate:@"update foo set bar = ?" withArgumentsInArray:@[@"xxx"]], @"insert failed");
  1012. int changes = [db changes];
  1013. XCTAssertEqual(changes, 2, @"two rows should have incremented \(%ld)", (long)changes);
  1014. }
  1015. - (void)testBind {
  1016. FMDatabase *db = [[FMDatabase alloc] init];
  1017. XCTAssert([db open], @"open failed");
  1018. XCTAssert([db executeUpdate:@"create table foo (id integer primary key autoincrement, a numeric)"], @"create failed");
  1019. NSNumber *insertedValue;
  1020. NSNumber *retrievedValue;
  1021. insertedValue = [NSNumber numberWithChar:51];
  1022. XCTAssert([db executeUpdate:@"insert into foo (a) values (?)" withArgumentsInArray:@[insertedValue]], @"insert failed");
  1023. retrievedValue = @([db intForQuery:@"select a from foo where id = ?", @([db lastInsertRowId])]);
  1024. XCTAssertEqualObjects(insertedValue, retrievedValue, @"values don't match");
  1025. insertedValue = [NSNumber numberWithUnsignedChar:52];
  1026. XCTAssert([db executeUpdate:@"insert into foo (a) values (?)" withArgumentsInArray:@[insertedValue]], @"insert failed");
  1027. retrievedValue = @([db intForQuery:@"select a from foo where id = ?", @([db lastInsertRowId])]);
  1028. XCTAssertEqualObjects(insertedValue, retrievedValue, @"values don't match");
  1029. insertedValue = [NSNumber numberWithShort:53];
  1030. XCTAssert([db executeUpdate:@"insert into foo (a) values (?)" withArgumentsInArray:@[insertedValue]], @"insert failed");
  1031. retrievedValue = @([db intForQuery:@"select a from foo where id = ?", @([db lastInsertRowId])]);
  1032. XCTAssertEqualObjects(insertedValue, retrievedValue, @"values don't match");
  1033. insertedValue = [NSNumber numberWithUnsignedShort:54];
  1034. XCTAssert([db executeUpdate:@"insert into foo (a) values (?)" withArgumentsInArray:@[insertedValue]], @"insert failed");
  1035. retrievedValue = @([db intForQuery:@"select a from foo where id = ?", @([db lastInsertRowId])]);
  1036. XCTAssertEqualObjects(insertedValue, retrievedValue, @"values don't match");
  1037. insertedValue = [NSNumber numberWithInt:54];
  1038. XCTAssert([db executeUpdate:@"insert into foo (a) values (?)" withArgumentsInArray:@[insertedValue]], @"insert failed");
  1039. retrievedValue = @([db intForQuery:@"select a from foo where id = ?", @([db lastInsertRowId])]);
  1040. XCTAssertEqualObjects(insertedValue, retrievedValue, @"values don't match");
  1041. insertedValue = [NSNumber numberWithUnsignedInt:55];
  1042. XCTAssert([db executeUpdate:@"insert into foo (a) values (?)" withArgumentsInArray:@[insertedValue]], @"insert failed");
  1043. retrievedValue = @([db intForQuery:@"select a from foo where id = ?", @([db lastInsertRowId])]);
  1044. XCTAssertEqualObjects(insertedValue, retrievedValue, @"values don't match");
  1045. insertedValue = [NSNumber numberWithLong:56];
  1046. XCTAssert([db executeUpdate:@"insert into foo (a) values (?)" withArgumentsInArray:@[insertedValue]], @"insert failed");
  1047. retrievedValue = @([db longForQuery:@"select a from foo where id = ?", @([db lastInsertRowId])]);
  1048. XCTAssertEqualObjects(insertedValue, retrievedValue, @"values don't match");
  1049. insertedValue = [NSNumber numberWithUnsignedLong:57];
  1050. XCTAssert([db executeUpdate:@"insert into foo (a) values (?)" withArgumentsInArray:@[insertedValue]], @"insert failed");
  1051. retrievedValue = @([db longForQuery:@"select a from foo where id = ?", @([db lastInsertRowId])]);
  1052. XCTAssertEqualObjects(insertedValue, retrievedValue, @"values don't match");
  1053. insertedValue = [NSNumber numberWithLongLong:56];
  1054. XCTAssert([db executeUpdate:@"insert into foo (a) values (?)" withArgumentsInArray:@[insertedValue]], @"insert failed");
  1055. retrievedValue = @([db longForQuery:@"select a from foo where id = ?", @([db lastInsertRowId])]);
  1056. XCTAssertEqualObjects(insertedValue, retrievedValue, @"values don't match");
  1057. insertedValue = [NSNumber numberWithUnsignedLongLong:57];
  1058. XCTAssert([db executeUpdate:@"insert into foo (a) values (?)" withArgumentsInArray:@[insertedValue]], @"insert failed");
  1059. retrievedValue = @([db longForQuery:@"select a from foo where id = ?", @([db lastInsertRowId])]);
  1060. XCTAssertEqualObjects(insertedValue, retrievedValue, @"values don't match");
  1061. insertedValue = [NSNumber numberWithFloat:58];
  1062. XCTAssert([db executeUpdate:@"insert into foo (a) values (?)" withArgumentsInArray:@[insertedValue]], @"insert failed");
  1063. retrievedValue = @([db doubleForQuery:@"select a from foo where id = ?", @([db lastInsertRowId])]);
  1064. XCTAssertEqualObjects(insertedValue, retrievedValue, @"values don't match");
  1065. insertedValue = [NSNumber numberWithDouble:59];
  1066. XCTAssert([db executeUpdate:@"insert into foo (a) values (?)" withArgumentsInArray:@[insertedValue]], @"insert failed");
  1067. retrievedValue = @([db doubleForQuery:@"select a from foo where id = ?", @([db lastInsertRowId])]);
  1068. XCTAssertEqualObjects(insertedValue, retrievedValue, @"values don't match");
  1069. insertedValue = @TRUE;
  1070. XCTAssert([db executeUpdate:@"insert into foo (a) values (?)" withArgumentsInArray:@[insertedValue]], @"insert failed");
  1071. retrievedValue = @([db boolForQuery:@"select a from foo where id = ?", @([db lastInsertRowId])]);
  1072. XCTAssertEqualObjects(insertedValue, retrievedValue, @"values don't match");
  1073. }
  1074. - (void)testFormatStrings {
  1075. FMDatabase *db = [[FMDatabase alloc] init];
  1076. XCTAssert([db open], @"open failed");
  1077. XCTAssert([db executeUpdate:@"create table foo (id integer primary key autoincrement, a numeric)"], @"create failed");
  1078. BOOL success;
  1079. char insertedChar = 'A';
  1080. success = [db executeUpdateWithFormat:@"insert into foo (a) values (%c)", insertedChar];
  1081. XCTAssert(success, @"insert failed");
  1082. const char *retrievedChar = [[db stringForQuery:@"select a from foo where id = ?", @([db lastInsertRowId])] UTF8String];
  1083. XCTAssertEqual(insertedChar, retrievedChar[0], @"values don't match");
  1084. const char *insertedString = "baz";
  1085. success = [db executeUpdateWithFormat:@"insert into foo (a) values (%s)", insertedString];
  1086. XCTAssert(success, @"insert failed");
  1087. const char *retrievedString = [[db stringForQuery:@"select a from foo where id = ?", @([db lastInsertRowId])] UTF8String];
  1088. XCTAssert(strcmp(insertedString, retrievedString) == 0, @"values don't match");
  1089. int insertedInt = 42;
  1090. success = [db executeUpdateWithFormat:@"insert into foo (a) values (%d)", insertedInt];
  1091. XCTAssert(success, @"insert failed");
  1092. int retrievedInt = [db intForQuery:@"select a from foo where id = ?", @([db lastInsertRowId])];
  1093. XCTAssertEqual(insertedInt, retrievedInt, @"values don't match");
  1094. char insertedUnsignedInt = 43;
  1095. success = [db executeUpdateWithFormat:@"insert into foo (a) values (%u)", insertedUnsignedInt];
  1096. XCTAssert(success, @"insert failed");
  1097. char retrievedUnsignedInt = [db intForQuery:@"select a from foo where id = ?", @([db lastInsertRowId])];
  1098. XCTAssertEqual(insertedUnsignedInt, retrievedUnsignedInt, @"values don't match");
  1099. float insertedFloat = 44;
  1100. success = [db executeUpdateWithFormat:@"insert into foo (a) values (%f)", insertedFloat];
  1101. XCTAssert(success, @"insert failed");
  1102. float retrievedFloat = [db doubleForQuery:@"select a from foo where id = ?", @([db lastInsertRowId])];
  1103. XCTAssertEqual(insertedFloat, retrievedFloat, @"values don't match");
  1104. unsigned long long insertedUnsignedLongLong = 45;
  1105. success = [db executeUpdateWithFormat:@"insert into foo (a) values (%llu)", insertedUnsignedLongLong];
  1106. XCTAssert(success, @"insert failed");
  1107. unsigned long long retrievedUnsignedLongLong = [db longForQuery:@"select a from foo where id = ?", @([db lastInsertRowId])];
  1108. XCTAssertEqual(insertedUnsignedLongLong, retrievedUnsignedLongLong, @"values don't match");
  1109. }
  1110. - (void)testStepError {
  1111. FMDatabase *db = [[FMDatabase alloc] init];
  1112. XCTAssert([db open], @"open failed");
  1113. XCTAssert([db executeUpdate:@"create table foo (id integer primary key)"], @"create failed");
  1114. XCTAssert([db executeUpdate:@"insert into foo (id) values (?)" values:@[@1] error:nil], @"create failed");
  1115. NSError *error;
  1116. BOOL success = [db executeUpdate:@"insert into foo (id) values (?)" values:@[@1] error:&error];
  1117. XCTAssertFalse(success, @"insert of duplicate key should have failed");
  1118. XCTAssertNotNil(error, @"error object should have been generated");
  1119. XCTAssertEqual(error.code, 19, @"error code 19 should have been generated");
  1120. }
  1121. - (void)testCheckpoint {
  1122. FMDatabase *db = [[FMDatabase alloc] init];
  1123. XCTAssertTrue([db open], @"open failed");
  1124. NSError *error = nil;
  1125. int frameCount = 0;
  1126. int checkpointCount = 0;
  1127. [db checkpoint:FMDBCheckpointModeTruncate name:NULL logFrameCount:&frameCount checkpointCount:&checkpointCount error:&error];
  1128. // 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
  1129. XCTAssertEqual(frameCount, -1, @"frameCount should be -1 (means not using WAL mode) to verify that we're using the proper checkpoint interface");
  1130. XCTAssertEqual(checkpointCount, -1, @"checkpointCount should be -1 (means not using WAL mode) to verify that we're using the proper checkpoint interface");
  1131. }
  1132. - (void)testImmediateTransaction {
  1133. FMDatabase *db = [[FMDatabase alloc] init];
  1134. XCTAssertTrue([db open], @"open failed");
  1135. [db beginImmediateTransaction];
  1136. [db beginImmediateTransaction];
  1137. // Verify that beginImmediateTransaction behaves as advertised and starts a transaction
  1138. XCTAssertEqualObjects([db lastError].localizedDescription, @"cannot start a transaction within a transaction");
  1139. }
  1140. @end