RCNConfigDBManager.m 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045
  1. /*
  2. * Copyright 2019 Google
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #import <sqlite3.h>
  17. #import "FirebaseRemoteConfig/Sources/RCNConfigDBManager.h"
  18. #import "FirebaseRemoteConfig/Sources/RCNConfigDefines.h"
  19. #import "FirebaseRemoteConfig/Sources/RCNConfigValue_Internal.h"
  20. #import "FirebaseCore/Sources/Private/FirebaseCoreInternal.h"
  21. /// Using macro for securely preprocessing string concatenation in query before runtime.
  22. #define RCNTableNameMain "main"
  23. #define RCNTableNameMainActive "main_active"
  24. #define RCNTableNameMainDefault "main_default"
  25. #define RCNTableNameMetadata "fetch_metadata"
  26. #define RCNTableNameInternalMetadata "internal_metadata"
  27. #define RCNTableNameExperiment "experiment"
  28. static BOOL gIsNewDatabase;
  29. /// SQLite file name in versions 0, 1 and 2.
  30. static NSString *const RCNDatabaseName = @"RemoteConfig.sqlite3";
  31. /// The application support sub-directory that the Remote Config database resides in.
  32. static NSString *const RCNRemoteConfigApplicationSupportSubDirectory = @"Google/RemoteConfig";
  33. /// Remote Config database path for deprecated V0 version.
  34. static NSString *RemoteConfigPathForOldDatabaseV0() {
  35. NSArray *dirPaths =
  36. NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  37. NSString *docPath = dirPaths.firstObject;
  38. return [docPath stringByAppendingPathComponent:RCNDatabaseName];
  39. }
  40. /// Remote Config database path for current database.
  41. static NSString *RemoteConfigPathForDatabase(void) {
  42. NSArray *dirPaths =
  43. NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
  44. NSString *appSupportPath = dirPaths.firstObject;
  45. NSArray *components =
  46. @[ appSupportPath, RCNRemoteConfigApplicationSupportSubDirectory, RCNDatabaseName ];
  47. return [NSString pathWithComponents:components];
  48. }
  49. static BOOL RemoteConfigAddSkipBackupAttributeToItemAtPath(NSString *filePathString) {
  50. NSURL *URL = [NSURL fileURLWithPath:filePathString];
  51. assert([[NSFileManager defaultManager] fileExistsAtPath:[URL path]]);
  52. NSError *error = nil;
  53. BOOL success = [URL setResourceValue:[NSNumber numberWithBool:YES]
  54. forKey:NSURLIsExcludedFromBackupKey
  55. error:&error];
  56. if (!success) {
  57. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000017", @"Error excluding %@ from backup %@.",
  58. [URL lastPathComponent], error);
  59. }
  60. return success;
  61. }
  62. static BOOL RemoteConfigCreateFilePathIfNotExist(NSString *filePath) {
  63. if (!filePath || !filePath.length) {
  64. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000018",
  65. @"Failed to create subdirectory for an empty file path.");
  66. return NO;
  67. }
  68. NSFileManager *fileManager = [NSFileManager defaultManager];
  69. if (![fileManager fileExistsAtPath:filePath]) {
  70. gIsNewDatabase = YES;
  71. NSError *error;
  72. [fileManager createDirectoryAtPath:[filePath stringByDeletingLastPathComponent]
  73. withIntermediateDirectories:YES
  74. attributes:nil
  75. error:&error];
  76. if (error) {
  77. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000019",
  78. @"Failed to create subdirectory for database file: %@.", error);
  79. return NO;
  80. }
  81. }
  82. return YES;
  83. }
  84. static NSArray *RemoteConfigMetadataTableColumnsInOrder() {
  85. return @[
  86. RCNKeyBundleIdentifier, RCNKeyFetchTime, RCNKeyDigestPerNamespace, RCNKeyDeviceContext,
  87. RCNKeyAppContext, RCNKeySuccessFetchTime, RCNKeyFailureFetchTime, RCNKeyLastFetchStatus,
  88. RCNKeyLastFetchError, RCNKeyLastApplyTime, RCNKeyLastSetDefaultsTime
  89. ];
  90. }
  91. @interface RCNConfigDBManager () {
  92. /// Database storing all the config information.
  93. sqlite3 *_database;
  94. /// Serial queue for database read/write operations.
  95. dispatch_queue_t _databaseOperationQueue;
  96. }
  97. @end
  98. @implementation RCNConfigDBManager
  99. + (instancetype)sharedInstance {
  100. static dispatch_once_t onceToken;
  101. static RCNConfigDBManager *sharedInstance;
  102. dispatch_once(&onceToken, ^{
  103. sharedInstance = [[RCNConfigDBManager alloc] init];
  104. });
  105. return sharedInstance;
  106. }
  107. /// Returns the current version of the Remote Config database.
  108. + (NSString *)remoteConfigPathForDatabase {
  109. return RemoteConfigPathForDatabase();
  110. }
  111. - (instancetype)init {
  112. self = [super init];
  113. if (self) {
  114. _databaseOperationQueue =
  115. dispatch_queue_create("com.google.GoogleConfigService.database", DISPATCH_QUEUE_SERIAL);
  116. [self createOrOpenDatabase];
  117. }
  118. return self;
  119. }
  120. #pragma mark - database
  121. - (void)migrateV1NamespaceToV2Namespace {
  122. for (int table = 0; table < 3; table++) {
  123. NSString *tableName = @"" RCNTableNameMain;
  124. switch (table) {
  125. case 1:
  126. tableName = @"" RCNTableNameMainActive;
  127. break;
  128. case 2:
  129. tableName = @"" RCNTableNameMainDefault;
  130. break;
  131. default:
  132. break;
  133. }
  134. NSString *SQLString = [NSString
  135. stringWithFormat:@"SELECT namespace FROM %@ WHERE namespace NOT LIKE '%%:%%'", tableName];
  136. const char *SQL = [SQLString UTF8String];
  137. sqlite3_stmt *statement = [self prepareSQL:SQL];
  138. if (!statement) {
  139. return;
  140. }
  141. NSMutableArray<NSString *> *namespaceArray = [[NSMutableArray alloc] init];
  142. while (sqlite3_step(statement) == SQLITE_ROW) {
  143. NSString *configNamespace =
  144. [[NSString alloc] initWithUTF8String:(char *)sqlite3_column_text(statement, 0)];
  145. [namespaceArray addObject:configNamespace];
  146. }
  147. sqlite3_finalize(statement);
  148. // Update.
  149. for (NSString *namespaceToUpdate in namespaceArray) {
  150. NSString *newNamespace =
  151. [NSString stringWithFormat:@"%@:%@", namespaceToUpdate, kFIRDefaultAppName];
  152. NSString *updateSQLString =
  153. [NSString stringWithFormat:@"UPDATE %@ SET namespace = ? WHERE namespace = ?", tableName];
  154. const char *updateSQL = [updateSQLString UTF8String];
  155. sqlite3_stmt *updateStatement = [self prepareSQL:updateSQL];
  156. if (!updateStatement) {
  157. return;
  158. }
  159. NSArray<NSString *> *updateParams = @[ newNamespace, namespaceToUpdate ];
  160. [self bindStringsToStatement:updateStatement stringArray:updateParams];
  161. int result = sqlite3_step(updateStatement);
  162. if (result != SQLITE_DONE) {
  163. [self logErrorWithSQL:SQL finalizeStatement:updateStatement returnValue:NO];
  164. return;
  165. }
  166. sqlite3_finalize(updateStatement);
  167. }
  168. }
  169. }
  170. - (void)createOrOpenDatabase {
  171. __weak RCNConfigDBManager *weakSelf = self;
  172. dispatch_async(_databaseOperationQueue, ^{
  173. RCNConfigDBManager *strongSelf = weakSelf;
  174. if (!strongSelf) {
  175. return;
  176. }
  177. NSString *oldV0DBPath = RemoteConfigPathForOldDatabaseV0();
  178. // Backward Compatibility
  179. if ([[NSFileManager defaultManager] fileExistsAtPath:oldV0DBPath]) {
  180. FIRLogInfo(kFIRLoggerRemoteConfig, @"I-RCN000009",
  181. @"Old database V0 exists, removed it and replace with the new one.");
  182. [strongSelf removeDatabase:oldV0DBPath];
  183. }
  184. NSString *dbPath = [RCNConfigDBManager remoteConfigPathForDatabase];
  185. FIRLogInfo(kFIRLoggerRemoteConfig, @"I-RCN000062", @"Loading database at path %@", dbPath);
  186. const char *databasePath = dbPath.UTF8String;
  187. // Create or open database path.
  188. if (!RemoteConfigCreateFilePathIfNotExist(dbPath)) {
  189. return;
  190. }
  191. int flags = SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE | SQLITE_OPEN_FILEPROTECTION_COMPLETE |
  192. SQLITE_OPEN_FULLMUTEX;
  193. if (sqlite3_open_v2(databasePath, &strongSelf->_database, flags, NULL) == SQLITE_OK) {
  194. // Always try to create table if not exists for backward compatibility.
  195. if (![strongSelf createTableSchema]) {
  196. // Remove database before fail.
  197. [strongSelf removeDatabase:dbPath];
  198. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000010", @"Failed to create table.");
  199. // Create a new database if existing database file is corrupted.
  200. if (!RemoteConfigCreateFilePathIfNotExist(dbPath)) {
  201. return;
  202. }
  203. if (sqlite3_open_v2(databasePath, &strongSelf->_database, flags, NULL) == SQLITE_OK) {
  204. if (![strongSelf createTableSchema]) {
  205. // Remove database before fail.
  206. [strongSelf removeDatabase:dbPath];
  207. // If it failed again, there's nothing we can do here.
  208. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000010", @"Failed to create table.");
  209. } else {
  210. // Exclude the app data used from iCloud backup.
  211. RemoteConfigAddSkipBackupAttributeToItemAtPath(dbPath);
  212. }
  213. } else {
  214. [strongSelf logDatabaseError];
  215. }
  216. } else {
  217. // DB file already exists. Migrate any V1 namespace column entries to V2 fully qualified
  218. // 'namespace:FIRApp' entries.
  219. [self migrateV1NamespaceToV2Namespace];
  220. // Exclude the app data used from iCloud backup.
  221. RemoteConfigAddSkipBackupAttributeToItemAtPath(dbPath);
  222. }
  223. } else {
  224. [strongSelf logDatabaseError];
  225. }
  226. });
  227. }
  228. - (BOOL)createTableSchema {
  229. RCN_MUST_NOT_BE_MAIN_THREAD();
  230. static const char *createTableMain =
  231. "create TABLE IF NOT EXISTS " RCNTableNameMain
  232. " (_id INTEGER PRIMARY KEY, bundle_identifier TEXT, namespace TEXT, key TEXT, value BLOB)";
  233. static const char *createTableMainActive =
  234. "create TABLE IF NOT EXISTS " RCNTableNameMainActive
  235. " (_id INTEGER PRIMARY KEY, bundle_identifier TEXT, namespace TEXT, key TEXT, value BLOB)";
  236. static const char *createTableMainDefault =
  237. "create TABLE IF NOT EXISTS " RCNTableNameMainDefault
  238. " (_id INTEGER PRIMARY KEY, bundle_identifier TEXT, namespace TEXT, key TEXT, value BLOB)";
  239. static const char *createTableMetadata =
  240. "create TABLE IF NOT EXISTS " RCNTableNameMetadata
  241. " (_id INTEGER PRIMARY KEY, bundle_identifier"
  242. " TEXT, fetch_time INTEGER, digest_per_ns BLOB, device_context BLOB, app_context BLOB, "
  243. "success_fetch_time BLOB, failure_fetch_time BLOB, last_fetch_status INTEGER, "
  244. "last_fetch_error INTEGER, last_apply_time INTEGER, last_set_defaults_time INTEGER)";
  245. static const char *createTableInternalMetadata =
  246. "create TABLE IF NOT EXISTS " RCNTableNameInternalMetadata
  247. " (_id INTEGER PRIMARY KEY, key TEXT, value BLOB)";
  248. static const char *createTableExperiment = "create TABLE IF NOT EXISTS " RCNTableNameExperiment
  249. " (_id INTEGER PRIMARY KEY, key TEXT, value BLOB)";
  250. return [self executeQuery:createTableMain] && [self executeQuery:createTableMainActive] &&
  251. [self executeQuery:createTableMainDefault] && [self executeQuery:createTableMetadata] &&
  252. [self executeQuery:createTableInternalMetadata] &&
  253. [self executeQuery:createTableExperiment];
  254. }
  255. - (void)removeDatabaseOnDatabaseQueueAtPath:(NSString *)path {
  256. __weak RCNConfigDBManager *weakSelf = self;
  257. dispatch_sync(_databaseOperationQueue, ^{
  258. RCNConfigDBManager *strongSelf = weakSelf;
  259. if (!strongSelf) {
  260. return;
  261. }
  262. if (sqlite3_close(strongSelf->_database) != SQLITE_OK) {
  263. [self logDatabaseError];
  264. }
  265. strongSelf->_database = nil;
  266. NSFileManager *fileManager = [NSFileManager defaultManager];
  267. NSError *error;
  268. if (![fileManager removeItemAtPath:path error:&error]) {
  269. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000011",
  270. @"Failed to remove database at path %@ for error %@.", path, error);
  271. }
  272. });
  273. }
  274. - (void)removeDatabase:(NSString *)path {
  275. if (sqlite3_close(_database) != SQLITE_OK) {
  276. [self logDatabaseError];
  277. }
  278. _database = nil;
  279. NSFileManager *fileManager = [NSFileManager defaultManager];
  280. NSError *error;
  281. if (![fileManager removeItemAtPath:path error:&error]) {
  282. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000011",
  283. @"Failed to remove database at path %@ for error %@.", path, error);
  284. }
  285. }
  286. #pragma mark - execute
  287. - (BOOL)executeQuery:(const char *)SQL {
  288. RCN_MUST_NOT_BE_MAIN_THREAD();
  289. char *error;
  290. if (sqlite3_exec(_database, SQL, nil, nil, &error) != SQLITE_OK) {
  291. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000012", @"Failed to execute query with error %s.",
  292. error);
  293. return NO;
  294. }
  295. return YES;
  296. }
  297. #pragma mark - insert
  298. - (void)insertMetadataTableWithValues:(NSDictionary *)columnNameToValue
  299. completionHandler:(RCNDBCompletion)handler {
  300. __weak RCNConfigDBManager *weakSelf = self;
  301. dispatch_async(_databaseOperationQueue, ^{
  302. BOOL success = [weakSelf insertMetadataTableWithValues:columnNameToValue];
  303. if (handler) {
  304. dispatch_async(dispatch_get_main_queue(), ^{
  305. handler(success, nil);
  306. });
  307. }
  308. });
  309. }
  310. - (BOOL)insertMetadataTableWithValues:(NSDictionary *)columnNameToValue {
  311. RCN_MUST_NOT_BE_MAIN_THREAD();
  312. static const char *SQL =
  313. "INSERT INTO " RCNTableNameMetadata
  314. " (bundle_identifier, fetch_time, digest_per_ns, device_context, "
  315. "app_context, success_fetch_time, failure_fetch_time, last_fetch_status, "
  316. "last_fetch_error, last_apply_time, last_set_defaults_time) values (?, ?, ?, ?, ?, "
  317. "?, ?, ?, ?, ?, ?)";
  318. sqlite3_stmt *statement = [self prepareSQL:SQL];
  319. if (!statement) {
  320. [self logErrorWithSQL:SQL finalizeStatement:nil returnValue:NO];
  321. return NO;
  322. }
  323. NSArray *columns = RemoteConfigMetadataTableColumnsInOrder();
  324. int index = 0;
  325. for (NSString *columnName in columns) {
  326. if ([columnName isEqualToString:RCNKeyBundleIdentifier]) {
  327. NSString *value = columnNameToValue[columnName];
  328. if (![self bindStringToStatement:statement index:++index string:value]) {
  329. return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  330. }
  331. } else if ([columnName isEqualToString:RCNKeyFetchTime] ||
  332. [columnName isEqualToString:RCNKeyLastApplyTime] ||
  333. [columnName isEqualToString:RCNKeyLastSetDefaultsTime]) {
  334. double value = [columnNameToValue[columnName] doubleValue];
  335. if (sqlite3_bind_double(statement, ++index, value) != SQLITE_OK) {
  336. return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  337. }
  338. } else if ([columnName isEqualToString:RCNKeyLastFetchStatus] ||
  339. [columnName isEqualToString:RCNKeyLastFetchError]) {
  340. int value = [columnNameToValue[columnName] intValue];
  341. if (sqlite3_bind_int(statement, ++index, value) != SQLITE_OK) {
  342. return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  343. }
  344. } else {
  345. NSData *data = columnNameToValue[columnName];
  346. if (sqlite3_bind_blob(statement, ++index, data.bytes, (int)data.length, NULL) != SQLITE_OK) {
  347. return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  348. }
  349. }
  350. }
  351. if (sqlite3_step(statement) != SQLITE_DONE) {
  352. return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  353. }
  354. sqlite3_finalize(statement);
  355. return YES;
  356. }
  357. - (void)insertMainTableWithValues:(NSArray *)values
  358. fromSource:(RCNDBSource)source
  359. completionHandler:(RCNDBCompletion)handler {
  360. __weak RCNConfigDBManager *weakSelf = self;
  361. dispatch_async(_databaseOperationQueue, ^{
  362. BOOL success = [weakSelf insertMainTableWithValues:values fromSource:source];
  363. if (handler) {
  364. dispatch_async(dispatch_get_main_queue(), ^{
  365. handler(success, nil);
  366. });
  367. }
  368. });
  369. }
  370. - (BOOL)insertMainTableWithValues:(NSArray *)values fromSource:(RCNDBSource)source {
  371. RCN_MUST_NOT_BE_MAIN_THREAD();
  372. if (values.count != 4) {
  373. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000013",
  374. @"Failed to insert config record. Wrong number of give parameters, current "
  375. @"number is %ld, correct number is 4.",
  376. (long)values.count);
  377. return NO;
  378. }
  379. const char *SQL = "INSERT INTO " RCNTableNameMain
  380. " (bundle_identifier, namespace, key, value) values (?, ?, ?, ?)";
  381. if (source == RCNDBSourceDefault) {
  382. SQL = "INSERT INTO " RCNTableNameMainDefault
  383. " (bundle_identifier, namespace, key, value) values (?, ?, ?, ?)";
  384. } else if (source == RCNDBSourceActive) {
  385. SQL = "INSERT INTO " RCNTableNameMainActive
  386. " (bundle_identifier, namespace, key, value) values (?, ?, ?, ?)";
  387. }
  388. sqlite3_stmt *statement = [self prepareSQL:SQL];
  389. if (!statement) {
  390. return NO;
  391. }
  392. NSString *aString = values[0];
  393. if (![self bindStringToStatement:statement index:1 string:aString]) {
  394. return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  395. }
  396. aString = values[1];
  397. if (![self bindStringToStatement:statement index:2 string:aString]) {
  398. return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  399. }
  400. aString = values[2];
  401. if (![self bindStringToStatement:statement index:3 string:aString]) {
  402. return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  403. }
  404. NSData *blobData = values[3];
  405. if (sqlite3_bind_blob(statement, 4, blobData.bytes, (int)blobData.length, NULL) != SQLITE_OK) {
  406. return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  407. }
  408. if (sqlite3_step(statement) != SQLITE_DONE) {
  409. return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  410. }
  411. sqlite3_finalize(statement);
  412. return YES;
  413. }
  414. - (void)insertInternalMetadataTableWithValues:(NSArray *)values
  415. completionHandler:(RCNDBCompletion)handler {
  416. __weak RCNConfigDBManager *weakSelf = self;
  417. dispatch_async(_databaseOperationQueue, ^{
  418. BOOL success = [weakSelf insertInternalMetadataWithValues:values];
  419. if (handler) {
  420. dispatch_async(dispatch_get_main_queue(), ^{
  421. handler(success, nil);
  422. });
  423. }
  424. });
  425. }
  426. - (BOOL)insertInternalMetadataWithValues:(NSArray *)values {
  427. RCN_MUST_NOT_BE_MAIN_THREAD();
  428. if (values.count != 2) {
  429. return NO;
  430. }
  431. const char *SQL =
  432. "INSERT OR REPLACE INTO " RCNTableNameInternalMetadata " (key, value) values (?, ?)";
  433. sqlite3_stmt *statement = [self prepareSQL:SQL];
  434. if (!statement) {
  435. return NO;
  436. }
  437. NSString *aString = values[0];
  438. if (![self bindStringToStatement:statement index:1 string:aString]) {
  439. [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  440. return NO;
  441. }
  442. NSData *blobData = values[1];
  443. if (sqlite3_bind_blob(statement, 2, blobData.bytes, (int)blobData.length, NULL) != SQLITE_OK) {
  444. [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  445. return NO;
  446. }
  447. if (sqlite3_step(statement) != SQLITE_DONE) {
  448. [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  449. return NO;
  450. }
  451. sqlite3_finalize(statement);
  452. return YES;
  453. }
  454. - (void)insertExperimentTableWithKey:(NSString *)key
  455. value:(NSData *)serializedValue
  456. completionHandler:(RCNDBCompletion)handler {
  457. dispatch_async(_databaseOperationQueue, ^{
  458. BOOL success = [self insertExperimentTableWithKey:key value:serializedValue];
  459. if (handler) {
  460. dispatch_async(dispatch_get_main_queue(), ^{
  461. handler(success, nil);
  462. });
  463. }
  464. });
  465. }
  466. - (BOOL)insertExperimentTableWithKey:(NSString *)key value:(NSData *)dataValue {
  467. if ([key isEqualToString:@RCNExperimentTableKeyMetadata]) {
  468. return [self updateExperimentMetadata:dataValue];
  469. }
  470. RCN_MUST_NOT_BE_MAIN_THREAD();
  471. const char *SQL = "INSERT INTO " RCNTableNameExperiment " (key, value) values (?, ?)";
  472. sqlite3_stmt *statement = [self prepareSQL:SQL];
  473. if (!statement) {
  474. return NO;
  475. }
  476. if (![self bindStringToStatement:statement index:1 string:key]) {
  477. return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  478. }
  479. if (sqlite3_bind_blob(statement, 2, dataValue.bytes, (int)dataValue.length, NULL) != SQLITE_OK) {
  480. return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  481. }
  482. if (sqlite3_step(statement) != SQLITE_DONE) {
  483. return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  484. }
  485. sqlite3_finalize(statement);
  486. return YES;
  487. }
  488. - (BOOL)updateExperimentMetadata:(NSData *)dataValue {
  489. RCN_MUST_NOT_BE_MAIN_THREAD();
  490. const char *SQL = "INSERT OR REPLACE INTO " RCNTableNameExperiment
  491. " (_id, key, value) values ((SELECT _id from " RCNTableNameExperiment
  492. " WHERE key = ?), ?, ?)";
  493. sqlite3_stmt *statement = [self prepareSQL:SQL];
  494. if (!statement) {
  495. return NO;
  496. }
  497. if (![self bindStringToStatement:statement index:1 string:@RCNExperimentTableKeyMetadata]) {
  498. return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  499. }
  500. if (![self bindStringToStatement:statement index:2 string:@RCNExperimentTableKeyMetadata]) {
  501. return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  502. }
  503. if (sqlite3_bind_blob(statement, 3, dataValue.bytes, (int)dataValue.length, NULL) != SQLITE_OK) {
  504. return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  505. }
  506. if (sqlite3_step(statement) != SQLITE_DONE) {
  507. return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  508. }
  509. sqlite3_finalize(statement);
  510. return YES;
  511. }
  512. #pragma mark - update
  513. - (void)updateMetadataWithOption:(RCNUpdateOption)option
  514. values:(NSArray *)values
  515. completionHandler:(RCNDBCompletion)handler {
  516. dispatch_async(_databaseOperationQueue, ^{
  517. BOOL success = [self updateMetadataTableWithOption:option andValues:values];
  518. if (handler) {
  519. dispatch_async(dispatch_get_main_queue(), ^{
  520. handler(success, nil);
  521. });
  522. }
  523. });
  524. }
  525. - (BOOL)updateMetadataTableWithOption:(RCNUpdateOption)option andValues:(NSArray *)values {
  526. RCN_MUST_NOT_BE_MAIN_THREAD();
  527. static const char *SQL =
  528. "UPDATE " RCNTableNameMetadata " (last_fetch_status, last_fetch_error, last_apply_time, "
  529. "last_set_defaults_time) values (?, ?, ?, ?)";
  530. if (option == RCNUpdateOptionFetchStatus) {
  531. SQL = "UPDATE " RCNTableNameMetadata " SET last_fetch_status = ?, last_fetch_error = ?";
  532. } else if (option == RCNUpdateOptionApplyTime) {
  533. SQL = "UPDATE " RCNTableNameMetadata " SET last_apply_time = ?";
  534. } else if (option == RCNUpdateOptionDefaultTime) {
  535. SQL = "UPDATE " RCNTableNameMetadata " SET last_set_defaults_time = ?";
  536. } else {
  537. return NO;
  538. }
  539. sqlite3_stmt *statement = [self prepareSQL:SQL];
  540. if (!statement) {
  541. return NO;
  542. }
  543. int index = 0;
  544. if ((option == RCNUpdateOptionApplyTime || option == RCNUpdateOptionDefaultTime) &&
  545. values.count == 1) {
  546. double value = [values[0] doubleValue];
  547. if (sqlite3_bind_double(statement, ++index, value) != SQLITE_OK) {
  548. return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  549. }
  550. } else if (option == RCNUpdateOptionFetchStatus && values.count == 2) {
  551. int value = [values[0] intValue];
  552. if (sqlite3_bind_int(statement, ++index, value) != SQLITE_OK) {
  553. return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  554. }
  555. value = [values[1] intValue];
  556. if (sqlite3_bind_int(statement, ++index, value) != SQLITE_OK) {
  557. return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  558. }
  559. }
  560. if (sqlite3_step(statement) != SQLITE_DONE) {
  561. return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  562. }
  563. sqlite3_finalize(statement);
  564. return YES;
  565. }
  566. #pragma mark - read from DB
  567. - (NSDictionary *)loadMetadataWithBundleIdentifier:(NSString *)bundleIdentifier {
  568. __block NSDictionary *metadataTableResult;
  569. __weak RCNConfigDBManager *weakSelf = self;
  570. dispatch_sync(_databaseOperationQueue, ^{
  571. metadataTableResult = [weakSelf loadMetadataTableWithBundleIdentifier:bundleIdentifier];
  572. });
  573. if (metadataTableResult) {
  574. return metadataTableResult;
  575. }
  576. return [[NSDictionary alloc] init];
  577. }
  578. - (NSMutableDictionary *)loadMetadataTableWithBundleIdentifier:(NSString *)bundleIdentifier {
  579. NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
  580. const char *SQL =
  581. "SELECT bundle_identifier, fetch_time, digest_per_ns, device_context, app_context, "
  582. "success_fetch_time, failure_fetch_time , last_fetch_status, "
  583. "last_fetch_error, last_apply_time, last_set_defaults_time FROM " RCNTableNameMetadata
  584. " WHERE bundle_identifier = ?";
  585. sqlite3_stmt *statement = [self prepareSQL:SQL];
  586. if (!statement) {
  587. return nil;
  588. }
  589. NSArray *params = @[ bundleIdentifier ];
  590. [self bindStringsToStatement:statement stringArray:params];
  591. while (sqlite3_step(statement) == SQLITE_ROW) {
  592. NSString *dbBundleIdentifier =
  593. [[NSString alloc] initWithUTF8String:(char *)sqlite3_column_text(statement, 0)];
  594. if (dbBundleIdentifier && ![dbBundleIdentifier isEqualToString:bundleIdentifier]) {
  595. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000014",
  596. @"Load Metadata from table error: Wrong package name %@, should be %@.",
  597. dbBundleIdentifier, bundleIdentifier);
  598. return nil;
  599. }
  600. double fetchTime = sqlite3_column_double(statement, 1);
  601. NSData *digestPerNamespace = [NSData dataWithBytes:(char *)sqlite3_column_blob(statement, 2)
  602. length:sqlite3_column_bytes(statement, 2)];
  603. NSData *deviceContext = [NSData dataWithBytes:(char *)sqlite3_column_blob(statement, 3)
  604. length:sqlite3_column_bytes(statement, 3)];
  605. NSData *appContext = [NSData dataWithBytes:(char *)sqlite3_column_blob(statement, 4)
  606. length:sqlite3_column_bytes(statement, 4)];
  607. NSData *successTimeDigest = [NSData dataWithBytes:(char *)sqlite3_column_blob(statement, 5)
  608. length:sqlite3_column_bytes(statement, 5)];
  609. NSData *failureTimeDigest = [NSData dataWithBytes:(char *)sqlite3_column_blob(statement, 6)
  610. length:sqlite3_column_bytes(statement, 6)];
  611. int lastFetchStatus = sqlite3_column_int(statement, 7);
  612. int lastFetchFailReason = sqlite3_column_int(statement, 8);
  613. double lastApplyTimestamp = sqlite3_column_double(statement, 9);
  614. double lastSetDefaultsTimestamp = sqlite3_column_double(statement, 10);
  615. NSError *error;
  616. NSMutableDictionary *deviceContextDict = nil;
  617. if (deviceContext) {
  618. deviceContextDict = [NSJSONSerialization JSONObjectWithData:deviceContext
  619. options:NSJSONReadingMutableContainers
  620. error:&error];
  621. }
  622. NSMutableDictionary *appContextDict = nil;
  623. if (appContext) {
  624. appContextDict = [NSJSONSerialization JSONObjectWithData:appContext
  625. options:NSJSONReadingMutableContainers
  626. error:&error];
  627. }
  628. NSMutableDictionary<NSString *, id> *digestPerNamespaceDictionary = nil;
  629. if (digestPerNamespace) {
  630. digestPerNamespaceDictionary =
  631. [NSJSONSerialization JSONObjectWithData:digestPerNamespace
  632. options:NSJSONReadingMutableContainers
  633. error:&error];
  634. }
  635. NSMutableArray *successTimes = nil;
  636. if (successTimeDigest) {
  637. successTimes = [NSJSONSerialization JSONObjectWithData:successTimeDigest
  638. options:NSJSONReadingMutableContainers
  639. error:&error];
  640. }
  641. NSMutableArray *failureTimes = nil;
  642. if (failureTimeDigest) {
  643. failureTimes = [NSJSONSerialization JSONObjectWithData:failureTimeDigest
  644. options:NSJSONReadingMutableContainers
  645. error:&error];
  646. }
  647. dict[RCNKeyBundleIdentifier] = bundleIdentifier;
  648. dict[RCNKeyFetchTime] = @(fetchTime);
  649. dict[RCNKeyDigestPerNamespace] = digestPerNamespaceDictionary;
  650. dict[RCNKeyDeviceContext] = deviceContextDict;
  651. dict[RCNKeyAppContext] = appContextDict;
  652. dict[RCNKeySuccessFetchTime] = successTimes;
  653. dict[RCNKeyFailureFetchTime] = failureTimes;
  654. dict[RCNKeyLastFetchStatus] = @(lastFetchStatus);
  655. dict[RCNKeyLastFetchError] = @(lastFetchFailReason);
  656. dict[RCNKeyLastApplyTime] = @(lastApplyTimestamp);
  657. dict[RCNKeyLastSetDefaultsTime] = @(lastSetDefaultsTimestamp);
  658. break;
  659. }
  660. sqlite3_finalize(statement);
  661. return dict;
  662. }
  663. - (void)loadExperimentWithCompletionHandler:(RCNDBCompletion)handler {
  664. __weak RCNConfigDBManager *weakSelf = self;
  665. dispatch_async(_databaseOperationQueue, ^{
  666. RCNConfigDBManager *strongSelf = weakSelf;
  667. if (!strongSelf) {
  668. return;
  669. }
  670. NSMutableArray *experimentPayloads =
  671. [strongSelf loadExperimentTableFromKey:@RCNExperimentTableKeyPayload];
  672. if (!experimentPayloads) {
  673. experimentPayloads = [[NSMutableArray alloc] init];
  674. }
  675. NSMutableDictionary *experimentMetadata;
  676. NSMutableArray *experiments =
  677. [strongSelf loadExperimentTableFromKey:@RCNExperimentTableKeyMetadata];
  678. // There should be only one entry for experiment metadata.
  679. if (experiments.count > 0) {
  680. NSError *error;
  681. experimentMetadata = [NSJSONSerialization JSONObjectWithData:experiments[0]
  682. options:NSJSONReadingMutableContainers
  683. error:&error];
  684. }
  685. if (!experimentMetadata) {
  686. experimentMetadata = [[NSMutableDictionary alloc] init];
  687. }
  688. if (handler) {
  689. dispatch_async(dispatch_get_main_queue(), ^{
  690. handler(
  691. YES, @{
  692. @RCNExperimentTableKeyPayload : [experimentPayloads copy],
  693. @RCNExperimentTableKeyMetadata : [experimentMetadata copy]
  694. });
  695. });
  696. }
  697. });
  698. }
  699. - (NSMutableArray<NSData *> *)loadExperimentTableFromKey:(NSString *)key {
  700. RCN_MUST_NOT_BE_MAIN_THREAD();
  701. NSMutableArray *results = [[NSMutableArray alloc] init];
  702. const char *SQL = "SELECT value FROM " RCNTableNameExperiment " WHERE key = ?";
  703. sqlite3_stmt *statement = [self prepareSQL:SQL];
  704. if (!statement) {
  705. return nil;
  706. }
  707. NSArray *params = @[ key ];
  708. [self bindStringsToStatement:statement stringArray:params];
  709. NSData *experimentData;
  710. while (sqlite3_step(statement) == SQLITE_ROW) {
  711. experimentData = [NSData dataWithBytes:(char *)sqlite3_column_blob(statement, 0)
  712. length:sqlite3_column_bytes(statement, 0)];
  713. if (experimentData) {
  714. [results addObject:experimentData];
  715. }
  716. }
  717. sqlite3_finalize(statement);
  718. return results;
  719. }
  720. - (NSDictionary *)loadInternalMetadataTable {
  721. __block NSMutableDictionary *internalMetadataTableResult;
  722. __weak RCNConfigDBManager *weakSelf = self;
  723. dispatch_sync(_databaseOperationQueue, ^{
  724. internalMetadataTableResult = [weakSelf loadInternalMetadataTableInternal];
  725. });
  726. return internalMetadataTableResult;
  727. }
  728. - (NSMutableDictionary *)loadInternalMetadataTableInternal {
  729. NSMutableDictionary *internalMetadata = [[NSMutableDictionary alloc] init];
  730. const char *SQL = "SELECT key, value FROM " RCNTableNameInternalMetadata;
  731. sqlite3_stmt *statement = [self prepareSQL:SQL];
  732. if (!statement) {
  733. return nil;
  734. }
  735. while (sqlite3_step(statement) == SQLITE_ROW) {
  736. NSString *key = [[NSString alloc] initWithUTF8String:(char *)sqlite3_column_text(statement, 0)];
  737. NSData *dataValue = [NSData dataWithBytes:(char *)sqlite3_column_blob(statement, 1)
  738. length:sqlite3_column_bytes(statement, 1)];
  739. internalMetadata[key] = dataValue;
  740. }
  741. sqlite3_finalize(statement);
  742. return internalMetadata;
  743. }
  744. /// This method is only meant to be called at init time. The underlying logic will need to be
  745. /// revaluated if the assumption changes at a later time.
  746. - (void)loadMainWithBundleIdentifier:(NSString *)bundleIdentifier
  747. completionHandler:(RCNDBLoadCompletion)handler {
  748. __weak RCNConfigDBManager *weakSelf = self;
  749. dispatch_async(_databaseOperationQueue, ^{
  750. RCNConfigDBManager *strongSelf = weakSelf;
  751. if (!strongSelf) {
  752. return;
  753. }
  754. __block NSDictionary *fetchedConfig =
  755. [strongSelf loadMainTableWithBundleIdentifier:bundleIdentifier
  756. fromSource:RCNDBSourceFetched];
  757. __block NSDictionary *activeConfig =
  758. [strongSelf loadMainTableWithBundleIdentifier:bundleIdentifier
  759. fromSource:RCNDBSourceActive];
  760. __block NSDictionary *defaultConfig =
  761. [strongSelf loadMainTableWithBundleIdentifier:bundleIdentifier
  762. fromSource:RCNDBSourceDefault];
  763. if (handler) {
  764. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  765. fetchedConfig = fetchedConfig ? fetchedConfig : [[NSDictionary alloc] init];
  766. activeConfig = activeConfig ? activeConfig : [[NSDictionary alloc] init];
  767. defaultConfig = defaultConfig ? defaultConfig : [[NSDictionary alloc] init];
  768. handler(YES, fetchedConfig, activeConfig, defaultConfig);
  769. });
  770. }
  771. });
  772. }
  773. - (NSMutableDictionary *)loadMainTableWithBundleIdentifier:(NSString *)bundleIdentifier
  774. fromSource:(RCNDBSource)source {
  775. NSMutableDictionary *namespaceToConfig = [[NSMutableDictionary alloc] init];
  776. const char *SQL = "SELECT bundle_identifier, namespace, key, value FROM " RCNTableNameMain
  777. " WHERE bundle_identifier = ?";
  778. if (source == RCNDBSourceDefault) {
  779. SQL = "SELECT bundle_identifier, namespace, key, value FROM " RCNTableNameMainDefault
  780. " WHERE bundle_identifier = ?";
  781. } else if (source == RCNDBSourceActive) {
  782. SQL = "SELECT bundle_identifier, namespace, key, value FROM " RCNTableNameMainActive
  783. " WHERE bundle_identifier = ?";
  784. }
  785. NSArray *params = @[ bundleIdentifier ];
  786. sqlite3_stmt *statement = [self prepareSQL:SQL];
  787. if (!statement) {
  788. return nil;
  789. }
  790. [self bindStringsToStatement:statement stringArray:params];
  791. while (sqlite3_step(statement) == SQLITE_ROW) {
  792. NSString *configNamespace =
  793. [[NSString alloc] initWithUTF8String:(char *)sqlite3_column_text(statement, 1)];
  794. NSString *key = [[NSString alloc] initWithUTF8String:(char *)sqlite3_column_text(statement, 2)];
  795. NSData *value = [NSData dataWithBytes:(char *)sqlite3_column_blob(statement, 3)
  796. length:sqlite3_column_bytes(statement, 3)];
  797. if (!namespaceToConfig[configNamespace]) {
  798. namespaceToConfig[configNamespace] = [[NSMutableDictionary alloc] init];
  799. }
  800. if (source == RCNDBSourceDefault) {
  801. namespaceToConfig[configNamespace][key] =
  802. [[FIRRemoteConfigValue alloc] initWithData:value source:FIRRemoteConfigSourceDefault];
  803. } else {
  804. namespaceToConfig[configNamespace][key] =
  805. [[FIRRemoteConfigValue alloc] initWithData:value source:FIRRemoteConfigSourceRemote];
  806. }
  807. }
  808. sqlite3_finalize(statement);
  809. return namespaceToConfig;
  810. }
  811. #pragma mark - delete
  812. - (void)deleteRecordFromMainTableWithNamespace:(NSString *)namespace_p
  813. bundleIdentifier:(NSString *)bundleIdentifier
  814. fromSource:(RCNDBSource)source {
  815. __weak RCNConfigDBManager *weakSelf = self;
  816. dispatch_async(_databaseOperationQueue, ^{
  817. RCNConfigDBManager *strongSelf = weakSelf;
  818. if (!strongSelf) {
  819. return;
  820. }
  821. NSArray *params = @[ bundleIdentifier, namespace_p ];
  822. const char *SQL =
  823. "DELETE FROM " RCNTableNameMain " WHERE bundle_identifier = ? and namespace = ?";
  824. if (source == RCNDBSourceDefault) {
  825. SQL = "DELETE FROM " RCNTableNameMainDefault " WHERE bundle_identifier = ? and namespace = ?";
  826. } else if (source == RCNDBSourceActive) {
  827. SQL = "DELETE FROM " RCNTableNameMainActive " WHERE bundle_identifier = ? and namespace = ?";
  828. }
  829. [strongSelf executeQuery:SQL withParams:params];
  830. });
  831. }
  832. - (void)deleteRecordWithBundleIdentifier:(NSString *)bundleIdentifier
  833. isInternalDB:(BOOL)isInternalDB {
  834. __weak RCNConfigDBManager *weakSelf = self;
  835. dispatch_async(_databaseOperationQueue, ^{
  836. RCNConfigDBManager *strongSelf = weakSelf;
  837. if (!strongSelf) {
  838. return;
  839. }
  840. const char *SQL = "DELETE FROM " RCNTableNameInternalMetadata " WHERE key LIKE ?";
  841. if (!isInternalDB) {
  842. SQL = "DELETE FROM " RCNTableNameMetadata " WHERE bundle_identifier = ?";
  843. }
  844. NSArray *params = @[ bundleIdentifier ];
  845. [strongSelf executeQuery:SQL withParams:params];
  846. });
  847. }
  848. - (void)deleteAllRecordsFromTableWithSource:(RCNDBSource)source {
  849. __weak RCNConfigDBManager *weakSelf = self;
  850. dispatch_async(_databaseOperationQueue, ^{
  851. RCNConfigDBManager *strongSelf = weakSelf;
  852. if (!strongSelf) {
  853. return;
  854. }
  855. const char *SQL = "DELETE FROM " RCNTableNameMain;
  856. if (source == RCNDBSourceDefault) {
  857. SQL = "DELETE FROM " RCNTableNameMainDefault;
  858. } else if (source == RCNDBSourceActive) {
  859. SQL = "DELETE FROM " RCNTableNameMainActive;
  860. }
  861. [strongSelf executeQuery:SQL];
  862. });
  863. }
  864. - (void)deleteExperimentTableForKey:(NSString *)key {
  865. __weak RCNConfigDBManager *weakSelf = self;
  866. dispatch_async(_databaseOperationQueue, ^{
  867. RCNConfigDBManager *strongSelf = weakSelf;
  868. if (!strongSelf) {
  869. return;
  870. }
  871. NSArray *params = @[ key ];
  872. const char *SQL = "DELETE FROM " RCNTableNameExperiment " WHERE key = ?";
  873. [strongSelf executeQuery:SQL withParams:params];
  874. });
  875. }
  876. #pragma mark - helper
  877. - (BOOL)executeQuery:(const char *)SQL withParams:(NSArray *)params {
  878. RCN_MUST_NOT_BE_MAIN_THREAD();
  879. sqlite3_stmt *statement = [self prepareSQL:SQL];
  880. if (!statement) {
  881. return NO;
  882. }
  883. [self bindStringsToStatement:statement stringArray:params];
  884. if (sqlite3_step(statement) != SQLITE_DONE) {
  885. return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  886. }
  887. sqlite3_finalize(statement);
  888. return YES;
  889. }
  890. /// Params only accept TEXT format string.
  891. - (BOOL)bindStringsToStatement:(sqlite3_stmt *)statement stringArray:(NSArray *)array {
  892. int index = 1;
  893. for (NSString *param in array) {
  894. if (![self bindStringToStatement:statement index:index string:param]) {
  895. return [self logErrorWithSQL:nil finalizeStatement:statement returnValue:NO];
  896. }
  897. index++;
  898. }
  899. return YES;
  900. }
  901. - (BOOL)bindStringToStatement:(sqlite3_stmt *)statement index:(int)index string:(NSString *)value {
  902. if (sqlite3_bind_text(statement, index, [value UTF8String], -1, SQLITE_TRANSIENT) != SQLITE_OK) {
  903. return [self logErrorWithSQL:nil finalizeStatement:statement returnValue:NO];
  904. }
  905. return YES;
  906. }
  907. - (sqlite3_stmt *)prepareSQL:(const char *)SQL {
  908. sqlite3_stmt *statement = nil;
  909. if (sqlite3_prepare_v2(_database, SQL, -1, &statement, NULL) != SQLITE_OK) {
  910. [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  911. return nil;
  912. }
  913. return statement;
  914. }
  915. - (NSString *)errorMessage {
  916. return [NSString stringWithFormat:@"%s", sqlite3_errmsg(_database)];
  917. }
  918. - (int)errorCode {
  919. return sqlite3_errcode(_database);
  920. }
  921. - (void)logDatabaseError {
  922. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000015", @"Error message: %@. Error code: %d.",
  923. [self errorMessage], [self errorCode]);
  924. }
  925. - (BOOL)logErrorWithSQL:(const char *)SQL
  926. finalizeStatement:(sqlite3_stmt *)statement
  927. returnValue:(BOOL)returnValue {
  928. if (SQL) {
  929. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000016", @"Failed with SQL: %s.", SQL);
  930. }
  931. [self logDatabaseError];
  932. if (statement) {
  933. sqlite3_finalize(statement);
  934. }
  935. return returnValue;
  936. }
  937. - (BOOL)isNewDatabase {
  938. return gIsNewDatabase;
  939. }
  940. @end