RCNConfigDBManager.m 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192
  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 RCNTableNameInternalMetadata "internal_metadata"
  28. #define RCNTableNameExperiment "experiment"
  29. #define RCNTableNamePersonalization "personalization"
  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 |
  197. SQLITE_OPEN_FILEPROTECTION_COMPLETEUNTILFIRSTUSERAUTHENTICATION |
  198. SQLITE_OPEN_FULLMUTEX;
  199. if (sqlite3_open_v2(databasePath, &strongSelf->_database, flags, NULL) == SQLITE_OK) {
  200. // Always try to create table if not exists for backward compatibility.
  201. if (![strongSelf createTableSchema]) {
  202. // Remove database before fail.
  203. [strongSelf removeDatabase:dbPath];
  204. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000010", @"Failed to create table.");
  205. // Create a new database if existing database file is corrupted.
  206. if (!RemoteConfigCreateFilePathIfNotExist(dbPath)) {
  207. return;
  208. }
  209. if (sqlite3_open_v2(databasePath, &strongSelf->_database, flags, NULL) == SQLITE_OK) {
  210. if (![strongSelf createTableSchema]) {
  211. // Remove database before fail.
  212. [strongSelf removeDatabase:dbPath];
  213. // If it failed again, there's nothing we can do here.
  214. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000010", @"Failed to create table.");
  215. } else {
  216. // Exclude the app data used from iCloud backup.
  217. RemoteConfigAddSkipBackupAttributeToItemAtPath(dbPath);
  218. }
  219. } else {
  220. [strongSelf logDatabaseError];
  221. }
  222. } else {
  223. // DB file already exists. Migrate any V1 namespace column entries to V2 fully qualified
  224. // 'namespace:FIRApp' entries.
  225. [self migrateV1NamespaceToV2Namespace];
  226. // Exclude the app data used from iCloud backup.
  227. RemoteConfigAddSkipBackupAttributeToItemAtPath(dbPath);
  228. }
  229. } else {
  230. [strongSelf logDatabaseError];
  231. }
  232. });
  233. }
  234. - (BOOL)createTableSchema {
  235. RCN_MUST_NOT_BE_MAIN_THREAD();
  236. static const char *createTableMain =
  237. "create TABLE IF NOT EXISTS " RCNTableNameMain
  238. " (_id INTEGER PRIMARY KEY, bundle_identifier TEXT, namespace TEXT, key TEXT, value BLOB)";
  239. static const char *createTableMainActive =
  240. "create TABLE IF NOT EXISTS " RCNTableNameMainActive
  241. " (_id INTEGER PRIMARY KEY, bundle_identifier TEXT, namespace TEXT, key TEXT, value BLOB)";
  242. static const char *createTableMainDefault =
  243. "create TABLE IF NOT EXISTS " RCNTableNameMainDefault
  244. " (_id INTEGER PRIMARY KEY, bundle_identifier TEXT, namespace TEXT, key TEXT, value BLOB)";
  245. static const char *createTableMetadata =
  246. "create TABLE IF NOT EXISTS " RCNTableNameMetadata
  247. " (_id INTEGER PRIMARY KEY, bundle_identifier TEXT, namespace TEXT,"
  248. " fetch_time INTEGER, digest_per_ns BLOB, device_context BLOB, app_context BLOB, "
  249. "success_fetch_time BLOB, failure_fetch_time BLOB, last_fetch_status INTEGER, "
  250. "last_fetch_error INTEGER, last_apply_time INTEGER, last_set_defaults_time INTEGER)";
  251. static const char *createTableInternalMetadata =
  252. "create TABLE IF NOT EXISTS " RCNTableNameInternalMetadata
  253. " (_id INTEGER PRIMARY KEY, key TEXT, value BLOB)";
  254. static const char *createTableExperiment = "create TABLE IF NOT EXISTS " RCNTableNameExperiment
  255. " (_id INTEGER PRIMARY KEY, key TEXT, value BLOB)";
  256. static const char *createTablePersonalization =
  257. "create TABLE IF NOT EXISTS " RCNTableNamePersonalization
  258. " (_id INTEGER PRIMARY KEY, key INTEGER, value BLOB)";
  259. return [self executeQuery:createTableMain] && [self executeQuery:createTableMainActive] &&
  260. [self executeQuery:createTableMainDefault] && [self executeQuery:createTableMetadata] &&
  261. [self executeQuery:createTableInternalMetadata] &&
  262. [self executeQuery:createTableExperiment] &&
  263. [self executeQuery:createTablePersonalization];
  264. }
  265. - (void)removeDatabaseOnDatabaseQueueAtPath:(NSString *)path {
  266. __weak RCNConfigDBManager *weakSelf = self;
  267. dispatch_sync(_databaseOperationQueue, ^{
  268. RCNConfigDBManager *strongSelf = weakSelf;
  269. if (!strongSelf) {
  270. return;
  271. }
  272. if (sqlite3_close(strongSelf->_database) != SQLITE_OK) {
  273. [self logDatabaseError];
  274. }
  275. strongSelf->_database = nil;
  276. NSFileManager *fileManager = [NSFileManager defaultManager];
  277. NSError *error;
  278. if (![fileManager removeItemAtPath:path error:&error]) {
  279. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000011",
  280. @"Failed to remove database at path %@ for error %@.", path, error);
  281. }
  282. });
  283. }
  284. - (void)removeDatabase:(NSString *)path {
  285. if (sqlite3_close(_database) != SQLITE_OK) {
  286. [self logDatabaseError];
  287. }
  288. _database = nil;
  289. NSFileManager *fileManager = [NSFileManager defaultManager];
  290. NSError *error;
  291. if (![fileManager removeItemAtPath:path error:&error]) {
  292. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000011",
  293. @"Failed to remove database at path %@ for error %@.", path, error);
  294. }
  295. }
  296. #pragma mark - execute
  297. - (BOOL)executeQuery:(const char *)SQL {
  298. RCN_MUST_NOT_BE_MAIN_THREAD();
  299. char *error;
  300. if (sqlite3_exec(_database, SQL, nil, nil, &error) != SQLITE_OK) {
  301. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000012", @"Failed to execute query with error %s.",
  302. error);
  303. return NO;
  304. }
  305. return YES;
  306. }
  307. #pragma mark - insert
  308. - (void)insertMetadataTableWithValues:(NSDictionary *)columnNameToValue
  309. completionHandler:(RCNDBCompletion)handler {
  310. __weak RCNConfigDBManager *weakSelf = self;
  311. dispatch_async(_databaseOperationQueue, ^{
  312. BOOL success = [weakSelf insertMetadataTableWithValues:columnNameToValue];
  313. if (handler) {
  314. dispatch_async(dispatch_get_main_queue(), ^{
  315. handler(success, nil);
  316. });
  317. }
  318. });
  319. }
  320. - (BOOL)insertMetadataTableWithValues:(NSDictionary *)columnNameToValue {
  321. RCN_MUST_NOT_BE_MAIN_THREAD();
  322. static const char *SQL =
  323. "INSERT INTO " RCNTableNameMetadata
  324. " (bundle_identifier, namespace, fetch_time, digest_per_ns, device_context, "
  325. "app_context, success_fetch_time, failure_fetch_time, last_fetch_status, "
  326. "last_fetch_error, last_apply_time, last_set_defaults_time) values (?, ?, ?, ?, ?, ?, "
  327. "?, ?, ?, ?, ?, ?)";
  328. sqlite3_stmt *statement = [self prepareSQL:SQL];
  329. if (!statement) {
  330. [self logErrorWithSQL:SQL finalizeStatement:nil returnValue:NO];
  331. return NO;
  332. }
  333. NSArray *columns = RemoteConfigMetadataTableColumnsInOrder();
  334. int index = 0;
  335. for (NSString *columnName in columns) {
  336. if ([columnName isEqualToString:RCNKeyBundleIdentifier] ||
  337. [columnName isEqualToString:RCNKeyNamespace]) {
  338. NSString *value = columnNameToValue[columnName];
  339. if (![self bindStringToStatement:statement index:++index string:value]) {
  340. return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  341. }
  342. } else if ([columnName isEqualToString:RCNKeyFetchTime] ||
  343. [columnName isEqualToString:RCNKeyLastApplyTime] ||
  344. [columnName isEqualToString:RCNKeyLastSetDefaultsTime]) {
  345. double value = [columnNameToValue[columnName] doubleValue];
  346. if (sqlite3_bind_double(statement, ++index, value) != SQLITE_OK) {
  347. return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  348. }
  349. } else if ([columnName isEqualToString:RCNKeyLastFetchStatus] ||
  350. [columnName isEqualToString:RCNKeyLastFetchError]) {
  351. int value = [columnNameToValue[columnName] intValue];
  352. if (sqlite3_bind_int(statement, ++index, value) != SQLITE_OK) {
  353. return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  354. }
  355. } else {
  356. NSData *data = columnNameToValue[columnName];
  357. if (sqlite3_bind_blob(statement, ++index, data.bytes, (int)data.length, NULL) != SQLITE_OK) {
  358. return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  359. }
  360. }
  361. }
  362. if (sqlite3_step(statement) != SQLITE_DONE) {
  363. return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  364. }
  365. sqlite3_finalize(statement);
  366. return YES;
  367. }
  368. - (void)insertMainTableWithValues:(NSArray *)values
  369. fromSource:(RCNDBSource)source
  370. completionHandler:(RCNDBCompletion)handler {
  371. __weak RCNConfigDBManager *weakSelf = self;
  372. dispatch_async(_databaseOperationQueue, ^{
  373. BOOL success = [weakSelf insertMainTableWithValues:values fromSource:source];
  374. if (handler) {
  375. dispatch_async(dispatch_get_main_queue(), ^{
  376. handler(success, nil);
  377. });
  378. }
  379. });
  380. }
  381. - (BOOL)insertMainTableWithValues:(NSArray *)values fromSource:(RCNDBSource)source {
  382. RCN_MUST_NOT_BE_MAIN_THREAD();
  383. if (values.count != 4) {
  384. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000013",
  385. @"Failed to insert config record. Wrong number of give parameters, current "
  386. @"number is %ld, correct number is 4.",
  387. (long)values.count);
  388. return NO;
  389. }
  390. const char *SQL = "INSERT INTO " RCNTableNameMain
  391. " (bundle_identifier, namespace, key, value) values (?, ?, ?, ?)";
  392. if (source == RCNDBSourceDefault) {
  393. SQL = "INSERT INTO " RCNTableNameMainDefault
  394. " (bundle_identifier, namespace, key, value) values (?, ?, ?, ?)";
  395. } else if (source == RCNDBSourceActive) {
  396. SQL = "INSERT INTO " RCNTableNameMainActive
  397. " (bundle_identifier, namespace, key, value) values (?, ?, ?, ?)";
  398. }
  399. sqlite3_stmt *statement = [self prepareSQL:SQL];
  400. if (!statement) {
  401. return NO;
  402. }
  403. NSString *aString = values[0];
  404. if (![self bindStringToStatement:statement index:1 string:aString]) {
  405. return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  406. }
  407. aString = values[1];
  408. if (![self bindStringToStatement:statement index:2 string:aString]) {
  409. return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  410. }
  411. aString = values[2];
  412. if (![self bindStringToStatement:statement index:3 string:aString]) {
  413. return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  414. }
  415. NSData *blobData = values[3];
  416. if (sqlite3_bind_blob(statement, 4, blobData.bytes, (int)blobData.length, NULL) != SQLITE_OK) {
  417. return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  418. }
  419. if (sqlite3_step(statement) != SQLITE_DONE) {
  420. return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  421. }
  422. sqlite3_finalize(statement);
  423. return YES;
  424. }
  425. - (void)insertInternalMetadataTableWithValues:(NSArray *)values
  426. completionHandler:(RCNDBCompletion)handler {
  427. __weak RCNConfigDBManager *weakSelf = self;
  428. dispatch_async(_databaseOperationQueue, ^{
  429. BOOL success = [weakSelf insertInternalMetadataWithValues:values];
  430. if (handler) {
  431. dispatch_async(dispatch_get_main_queue(), ^{
  432. handler(success, nil);
  433. });
  434. }
  435. });
  436. }
  437. - (BOOL)insertInternalMetadataWithValues:(NSArray *)values {
  438. RCN_MUST_NOT_BE_MAIN_THREAD();
  439. if (values.count != 2) {
  440. return NO;
  441. }
  442. const char *SQL =
  443. "INSERT OR REPLACE INTO " RCNTableNameInternalMetadata " (key, value) values (?, ?)";
  444. sqlite3_stmt *statement = [self prepareSQL:SQL];
  445. if (!statement) {
  446. return NO;
  447. }
  448. NSString *aString = values[0];
  449. if (![self bindStringToStatement:statement index:1 string:aString]) {
  450. [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  451. return NO;
  452. }
  453. NSData *blobData = values[1];
  454. if (sqlite3_bind_blob(statement, 2, blobData.bytes, (int)blobData.length, NULL) != SQLITE_OK) {
  455. [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  456. return NO;
  457. }
  458. if (sqlite3_step(statement) != SQLITE_DONE) {
  459. [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  460. return NO;
  461. }
  462. sqlite3_finalize(statement);
  463. return YES;
  464. }
  465. - (void)insertExperimentTableWithKey:(NSString *)key
  466. value:(NSData *)serializedValue
  467. completionHandler:(RCNDBCompletion)handler {
  468. dispatch_async(_databaseOperationQueue, ^{
  469. BOOL success = [self insertExperimentTableWithKey:key value:serializedValue];
  470. if (handler) {
  471. dispatch_async(dispatch_get_main_queue(), ^{
  472. handler(success, nil);
  473. });
  474. }
  475. });
  476. }
  477. - (BOOL)insertExperimentTableWithKey:(NSString *)key value:(NSData *)dataValue {
  478. if ([key isEqualToString:@RCNExperimentTableKeyMetadata]) {
  479. return [self updateExperimentMetadata:dataValue];
  480. }
  481. RCN_MUST_NOT_BE_MAIN_THREAD();
  482. const char *SQL = "INSERT INTO " RCNTableNameExperiment " (key, value) values (?, ?)";
  483. sqlite3_stmt *statement = [self prepareSQL:SQL];
  484. if (!statement) {
  485. return NO;
  486. }
  487. if (![self bindStringToStatement:statement index:1 string:key]) {
  488. return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  489. }
  490. if (sqlite3_bind_blob(statement, 2, dataValue.bytes, (int)dataValue.length, NULL) != SQLITE_OK) {
  491. return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  492. }
  493. if (sqlite3_step(statement) != SQLITE_DONE) {
  494. return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  495. }
  496. sqlite3_finalize(statement);
  497. return YES;
  498. }
  499. - (BOOL)updateExperimentMetadata:(NSData *)dataValue {
  500. RCN_MUST_NOT_BE_MAIN_THREAD();
  501. const char *SQL = "INSERT OR REPLACE INTO " RCNTableNameExperiment
  502. " (_id, key, value) values ((SELECT _id from " RCNTableNameExperiment
  503. " WHERE key = ?), ?, ?)";
  504. sqlite3_stmt *statement = [self prepareSQL:SQL];
  505. if (!statement) {
  506. return NO;
  507. }
  508. if (![self bindStringToStatement:statement index:1 string:@RCNExperimentTableKeyMetadata]) {
  509. return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  510. }
  511. if (![self bindStringToStatement:statement index:2 string:@RCNExperimentTableKeyMetadata]) {
  512. return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  513. }
  514. if (sqlite3_bind_blob(statement, 3, dataValue.bytes, (int)dataValue.length, NULL) != SQLITE_OK) {
  515. return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  516. }
  517. if (sqlite3_step(statement) != SQLITE_DONE) {
  518. return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  519. }
  520. sqlite3_finalize(statement);
  521. return YES;
  522. }
  523. - (BOOL)insertOrUpdatePersonalizationConfig:(NSDictionary *)dataValue
  524. fromSource:(RCNDBSource)source {
  525. RCN_MUST_NOT_BE_MAIN_THREAD();
  526. NSError *error;
  527. NSData *JSONPayload = [NSJSONSerialization dataWithJSONObject:dataValue
  528. options:NSJSONWritingPrettyPrinted
  529. error:&error];
  530. if (!JSONPayload || error) {
  531. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000075",
  532. @"Invalid Personalization payload to be serialized.");
  533. }
  534. const char *SQL = "INSERT OR REPLACE INTO " RCNTableNamePersonalization
  535. " (_id, key, value) values ((SELECT _id from " RCNTableNamePersonalization
  536. " WHERE key = ?), ?, ?)";
  537. sqlite3_stmt *statement = [self prepareSQL:SQL];
  538. if (!statement) {
  539. return NO;
  540. }
  541. if (sqlite3_bind_int(statement, 1, (int)source) != SQLITE_OK) {
  542. return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  543. }
  544. if (sqlite3_bind_int(statement, 2, (int)source) != SQLITE_OK) {
  545. return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  546. }
  547. if (sqlite3_bind_blob(statement, 3, JSONPayload.bytes, (int)JSONPayload.length, NULL) !=
  548. 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. if (handler) {
  746. dispatch_async(dispatch_get_main_queue(), ^{
  747. handler(
  748. YES, @{
  749. @RCNExperimentTableKeyPayload : [experimentPayloads copy],
  750. @RCNExperimentTableKeyMetadata : [experimentMetadata copy]
  751. });
  752. });
  753. }
  754. });
  755. }
  756. - (NSMutableArray<NSData *> *)loadExperimentTableFromKey:(NSString *)key {
  757. RCN_MUST_NOT_BE_MAIN_THREAD();
  758. NSMutableArray *results = [[NSMutableArray alloc] init];
  759. const char *SQL = "SELECT value FROM " RCNTableNameExperiment " WHERE key = ?";
  760. sqlite3_stmt *statement = [self prepareSQL:SQL];
  761. if (!statement) {
  762. return nil;
  763. }
  764. NSArray *params = @[ key ];
  765. [self bindStringsToStatement:statement stringArray:params];
  766. NSData *experimentData;
  767. while (sqlite3_step(statement) == SQLITE_ROW) {
  768. experimentData = [NSData dataWithBytes:(char *)sqlite3_column_blob(statement, 0)
  769. length:sqlite3_column_bytes(statement, 0)];
  770. if (experimentData) {
  771. [results addObject:experimentData];
  772. }
  773. }
  774. sqlite3_finalize(statement);
  775. return results;
  776. }
  777. - (void)loadPersonalizationWithCompletionHandler:(RCNDBLoadCompletion)handler {
  778. __weak RCNConfigDBManager *weakSelf = self;
  779. dispatch_async(_databaseOperationQueue, ^{
  780. RCNConfigDBManager *strongSelf = weakSelf;
  781. if (!strongSelf) {
  782. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  783. handler(NO, [NSMutableDictionary new], [NSMutableDictionary new], nil);
  784. });
  785. return;
  786. }
  787. NSDictionary *activePersonalization;
  788. NSData *personalizationResult = [strongSelf loadPersonalizationTableFromKey:RCNDBSourceActive];
  789. // There should be only one entry for Personalization metadata.
  790. if (personalizationResult) {
  791. NSError *error;
  792. activePersonalization = [NSJSONSerialization JSONObjectWithData:personalizationResult
  793. options:0
  794. error:&error];
  795. }
  796. if (!activePersonalization) {
  797. activePersonalization = [[NSMutableDictionary alloc] init];
  798. }
  799. NSDictionary *fetchedPersonalization;
  800. personalizationResult = [strongSelf loadPersonalizationTableFromKey:RCNDBSourceFetched];
  801. // There should be only one entry for Personalization metadata.
  802. if (personalizationResult) {
  803. NSError *error;
  804. fetchedPersonalization = [NSJSONSerialization JSONObjectWithData:personalizationResult
  805. options:0
  806. error:&error];
  807. }
  808. if (!fetchedPersonalization) {
  809. fetchedPersonalization = [[NSMutableDictionary alloc] init];
  810. }
  811. if (handler) {
  812. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  813. handler(YES, fetchedPersonalization, activePersonalization, nil);
  814. });
  815. }
  816. });
  817. }
  818. - (NSData *)loadPersonalizationTableFromKey:(int)key {
  819. RCN_MUST_NOT_BE_MAIN_THREAD();
  820. NSMutableArray *results = [[NSMutableArray alloc] init];
  821. const char *SQL = "SELECT value FROM " RCNTableNamePersonalization " WHERE key = ?";
  822. sqlite3_stmt *statement = [self prepareSQL:SQL];
  823. if (!statement) {
  824. return nil;
  825. }
  826. if (sqlite3_bind_int(statement, 1, key) != SQLITE_OK) {
  827. [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  828. return nil;
  829. }
  830. NSData *personalizationData;
  831. while (sqlite3_step(statement) == SQLITE_ROW) {
  832. personalizationData = [NSData dataWithBytes:(char *)sqlite3_column_blob(statement, 0)
  833. length:sqlite3_column_bytes(statement, 0)];
  834. if (personalizationData) {
  835. [results addObject:personalizationData];
  836. }
  837. }
  838. sqlite3_finalize(statement);
  839. // There should be only one entry in this table.
  840. if (results.count != 1) {
  841. return nil;
  842. }
  843. return results[0];
  844. }
  845. - (NSDictionary *)loadInternalMetadataTable {
  846. __block NSMutableDictionary *internalMetadataTableResult;
  847. __weak RCNConfigDBManager *weakSelf = self;
  848. dispatch_sync(_databaseOperationQueue, ^{
  849. internalMetadataTableResult = [weakSelf loadInternalMetadataTableInternal];
  850. });
  851. return internalMetadataTableResult;
  852. }
  853. - (NSMutableDictionary *)loadInternalMetadataTableInternal {
  854. NSMutableDictionary *internalMetadata = [[NSMutableDictionary alloc] init];
  855. const char *SQL = "SELECT key, value FROM " RCNTableNameInternalMetadata;
  856. sqlite3_stmt *statement = [self prepareSQL:SQL];
  857. if (!statement) {
  858. return nil;
  859. }
  860. while (sqlite3_step(statement) == SQLITE_ROW) {
  861. NSString *key = [[NSString alloc] initWithUTF8String:(char *)sqlite3_column_text(statement, 0)];
  862. NSData *dataValue = [NSData dataWithBytes:(char *)sqlite3_column_blob(statement, 1)
  863. length:sqlite3_column_bytes(statement, 1)];
  864. internalMetadata[key] = dataValue;
  865. }
  866. sqlite3_finalize(statement);
  867. return internalMetadata;
  868. }
  869. /// This method is only meant to be called at init time. The underlying logic will need to be
  870. /// revaluated if the assumption changes at a later time.
  871. - (void)loadMainWithBundleIdentifier:(NSString *)bundleIdentifier
  872. completionHandler:(RCNDBLoadCompletion)handler {
  873. __weak RCNConfigDBManager *weakSelf = self;
  874. dispatch_async(_databaseOperationQueue, ^{
  875. RCNConfigDBManager *strongSelf = weakSelf;
  876. if (!strongSelf) {
  877. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  878. handler(NO, [NSDictionary new], [NSDictionary new], [NSDictionary new]);
  879. });
  880. return;
  881. }
  882. __block NSDictionary *fetchedConfig =
  883. [strongSelf loadMainTableWithBundleIdentifier:bundleIdentifier
  884. fromSource:RCNDBSourceFetched];
  885. __block NSDictionary *activeConfig =
  886. [strongSelf loadMainTableWithBundleIdentifier:bundleIdentifier
  887. fromSource:RCNDBSourceActive];
  888. __block NSDictionary *defaultConfig =
  889. [strongSelf loadMainTableWithBundleIdentifier:bundleIdentifier
  890. fromSource:RCNDBSourceDefault];
  891. if (handler) {
  892. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  893. fetchedConfig = fetchedConfig ? fetchedConfig : [[NSDictionary alloc] init];
  894. activeConfig = activeConfig ? activeConfig : [[NSDictionary alloc] init];
  895. defaultConfig = defaultConfig ? defaultConfig : [[NSDictionary alloc] init];
  896. handler(YES, fetchedConfig, activeConfig, defaultConfig);
  897. });
  898. }
  899. });
  900. }
  901. - (NSMutableDictionary *)loadMainTableWithBundleIdentifier:(NSString *)bundleIdentifier
  902. fromSource:(RCNDBSource)source {
  903. NSMutableDictionary *namespaceToConfig = [[NSMutableDictionary alloc] init];
  904. const char *SQL = "SELECT bundle_identifier, namespace, key, value FROM " RCNTableNameMain
  905. " WHERE bundle_identifier = ?";
  906. if (source == RCNDBSourceDefault) {
  907. SQL = "SELECT bundle_identifier, namespace, key, value FROM " RCNTableNameMainDefault
  908. " WHERE bundle_identifier = ?";
  909. } else if (source == RCNDBSourceActive) {
  910. SQL = "SELECT bundle_identifier, namespace, key, value FROM " RCNTableNameMainActive
  911. " WHERE bundle_identifier = ?";
  912. }
  913. NSArray *params = @[ bundleIdentifier ];
  914. sqlite3_stmt *statement = [self prepareSQL:SQL];
  915. if (!statement) {
  916. return nil;
  917. }
  918. [self bindStringsToStatement:statement stringArray:params];
  919. while (sqlite3_step(statement) == SQLITE_ROW) {
  920. NSString *configNamespace =
  921. [[NSString alloc] initWithUTF8String:(char *)sqlite3_column_text(statement, 1)];
  922. NSString *key = [[NSString alloc] initWithUTF8String:(char *)sqlite3_column_text(statement, 2)];
  923. NSData *value = [NSData dataWithBytes:(char *)sqlite3_column_blob(statement, 3)
  924. length:sqlite3_column_bytes(statement, 3)];
  925. if (!namespaceToConfig[configNamespace]) {
  926. namespaceToConfig[configNamespace] = [[NSMutableDictionary alloc] init];
  927. }
  928. if (source == RCNDBSourceDefault) {
  929. namespaceToConfig[configNamespace][key] =
  930. [[FIRRemoteConfigValue alloc] initWithData:value source:FIRRemoteConfigSourceDefault];
  931. } else {
  932. namespaceToConfig[configNamespace][key] =
  933. [[FIRRemoteConfigValue alloc] initWithData:value source:FIRRemoteConfigSourceRemote];
  934. }
  935. }
  936. sqlite3_finalize(statement);
  937. return namespaceToConfig;
  938. }
  939. #pragma mark - delete
  940. - (void)deleteRecordFromMainTableWithNamespace:(NSString *)namespace_p
  941. bundleIdentifier:(NSString *)bundleIdentifier
  942. fromSource:(RCNDBSource)source {
  943. __weak RCNConfigDBManager *weakSelf = self;
  944. dispatch_async(_databaseOperationQueue, ^{
  945. RCNConfigDBManager *strongSelf = weakSelf;
  946. if (!strongSelf) {
  947. return;
  948. }
  949. NSArray *params = @[ bundleIdentifier, namespace_p ];
  950. const char *SQL =
  951. "DELETE FROM " RCNTableNameMain " WHERE bundle_identifier = ? and namespace = ?";
  952. if (source == RCNDBSourceDefault) {
  953. SQL = "DELETE FROM " RCNTableNameMainDefault " WHERE bundle_identifier = ? and namespace = ?";
  954. } else if (source == RCNDBSourceActive) {
  955. SQL = "DELETE FROM " RCNTableNameMainActive " WHERE bundle_identifier = ? and namespace = ?";
  956. }
  957. [strongSelf executeQuery:SQL withParams:params];
  958. });
  959. }
  960. - (void)deleteRecordWithBundleIdentifier:(NSString *)bundleIdentifier
  961. namespace:(NSString *)namespace
  962. isInternalDB:(BOOL)isInternalDB {
  963. __weak RCNConfigDBManager *weakSelf = self;
  964. dispatch_async(_databaseOperationQueue, ^{
  965. RCNConfigDBManager *strongSelf = weakSelf;
  966. if (!strongSelf) {
  967. return;
  968. }
  969. const char *SQL = "DELETE FROM " RCNTableNameInternalMetadata " WHERE key LIKE ?";
  970. NSArray *params = @[ bundleIdentifier ];
  971. if (!isInternalDB) {
  972. SQL = "DELETE FROM " RCNTableNameMetadata " WHERE bundle_identifier = ? and namespace = ?";
  973. params = @[ bundleIdentifier, namespace ];
  974. }
  975. [strongSelf executeQuery:SQL withParams:params];
  976. });
  977. }
  978. - (void)deleteAllRecordsFromTableWithSource:(RCNDBSource)source {
  979. __weak RCNConfigDBManager *weakSelf = self;
  980. dispatch_async(_databaseOperationQueue, ^{
  981. RCNConfigDBManager *strongSelf = weakSelf;
  982. if (!strongSelf) {
  983. return;
  984. }
  985. const char *SQL = "DELETE FROM " RCNTableNameMain;
  986. if (source == RCNDBSourceDefault) {
  987. SQL = "DELETE FROM " RCNTableNameMainDefault;
  988. } else if (source == RCNDBSourceActive) {
  989. SQL = "DELETE FROM " RCNTableNameMainActive;
  990. }
  991. [strongSelf executeQuery:SQL];
  992. });
  993. }
  994. - (void)deleteExperimentTableForKey:(NSString *)key {
  995. __weak RCNConfigDBManager *weakSelf = self;
  996. dispatch_async(_databaseOperationQueue, ^{
  997. RCNConfigDBManager *strongSelf = weakSelf;
  998. if (!strongSelf) {
  999. return;
  1000. }
  1001. NSArray *params = @[ key ];
  1002. const char *SQL = "DELETE FROM " RCNTableNameExperiment " WHERE key = ?";
  1003. [strongSelf executeQuery:SQL withParams:params];
  1004. });
  1005. }
  1006. #pragma mark - helper
  1007. - (BOOL)executeQuery:(const char *)SQL withParams:(NSArray *)params {
  1008. RCN_MUST_NOT_BE_MAIN_THREAD();
  1009. sqlite3_stmt *statement = [self prepareSQL:SQL];
  1010. if (!statement) {
  1011. return NO;
  1012. }
  1013. [self bindStringsToStatement:statement stringArray:params];
  1014. if (sqlite3_step(statement) != SQLITE_DONE) {
  1015. return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  1016. }
  1017. sqlite3_finalize(statement);
  1018. return YES;
  1019. }
  1020. /// Params only accept TEXT format string.
  1021. - (BOOL)bindStringsToStatement:(sqlite3_stmt *)statement stringArray:(NSArray *)array {
  1022. int index = 1;
  1023. for (NSString *param in array) {
  1024. if (![self bindStringToStatement:statement index:index string:param]) {
  1025. return [self logErrorWithSQL:nil finalizeStatement:statement returnValue:NO];
  1026. }
  1027. index++;
  1028. }
  1029. return YES;
  1030. }
  1031. - (BOOL)bindStringToStatement:(sqlite3_stmt *)statement index:(int)index string:(NSString *)value {
  1032. if (sqlite3_bind_text(statement, index, [value UTF8String], -1, SQLITE_TRANSIENT) != SQLITE_OK) {
  1033. return [self logErrorWithSQL:nil finalizeStatement:statement returnValue:NO];
  1034. }
  1035. return YES;
  1036. }
  1037. - (sqlite3_stmt *)prepareSQL:(const char *)SQL {
  1038. sqlite3_stmt *statement = nil;
  1039. if (sqlite3_prepare_v2(_database, SQL, -1, &statement, NULL) != SQLITE_OK) {
  1040. [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  1041. return nil;
  1042. }
  1043. return statement;
  1044. }
  1045. - (NSString *)errorMessage {
  1046. return [NSString stringWithFormat:@"%s", sqlite3_errmsg(_database)];
  1047. }
  1048. - (int)errorCode {
  1049. return sqlite3_errcode(_database);
  1050. }
  1051. - (void)logDatabaseError {
  1052. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000015", @"Error message: %@. Error code: %d.",
  1053. [self errorMessage], [self errorCode]);
  1054. }
  1055. - (BOOL)logErrorWithSQL:(const char *)SQL
  1056. finalizeStatement:(sqlite3_stmt *)statement
  1057. returnValue:(BOOL)returnValue {
  1058. if (SQL) {
  1059. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000016", @"Failed with SQL: %s.", SQL);
  1060. }
  1061. [self logDatabaseError];
  1062. if (statement) {
  1063. sqlite3_finalize(statement);
  1064. }
  1065. return returnValue;
  1066. }
  1067. - (BOOL)isNewDatabase {
  1068. return gIsNewDatabase;
  1069. }
  1070. @end