RCNConfigDBManager.m 47 KB

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