RCNConfigDBManager.m 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185
  1. /*
  2. * Copyright 2019 Google
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #import <sqlite3.h>
  17. #import "FirebaseRemoteConfig/Sources/RCNConfigDBManager.h"
  18. #import "FirebaseRemoteConfig/Sources/RCNConfigDefines.h"
  19. #import "FirebaseRemoteConfig/Sources/RCNConfigValue_Internal.h"
  20. #import "FirebaseCore/Sources/Private/FirebaseCoreInternal.h"
  21. /// Using macro for securely preprocessing string concatenation in query before runtime.
  22. #define RCNTableNameMain "main"
  23. #define RCNTableNameMainActive "main_active"
  24. #define RCNTableNameMainDefault "main_default"
  25. #define 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() {
  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() {
  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_FILEPROTECTION_COMPLETE |
  197. SQLITE_OPEN_FULLMUTEX;
  198. if (sqlite3_open_v2(databasePath, &strongSelf->_database, flags, NULL) == SQLITE_OK) {
  199. // Always try to create table if not exists for backward compatibility.
  200. if (![strongSelf createTableSchema]) {
  201. // Remove database before fail.
  202. [strongSelf removeDatabase:dbPath];
  203. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000010", @"Failed to create table.");
  204. // Create a new database if existing database file is corrupted.
  205. if (!RemoteConfigCreateFilePathIfNotExist(dbPath)) {
  206. return;
  207. }
  208. if (sqlite3_open_v2(databasePath, &strongSelf->_database, flags, NULL) == SQLITE_OK) {
  209. if (![strongSelf createTableSchema]) {
  210. // Remove database before fail.
  211. [strongSelf removeDatabase:dbPath];
  212. // If it failed again, there's nothing we can do here.
  213. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000010", @"Failed to create table.");
  214. } else {
  215. // Exclude the app data used from iCloud backup.
  216. RemoteConfigAddSkipBackupAttributeToItemAtPath(dbPath);
  217. }
  218. } else {
  219. [strongSelf logDatabaseError];
  220. }
  221. } else {
  222. // DB file already exists. Migrate any V1 namespace column entries to V2 fully qualified
  223. // 'namespace:FIRApp' entries.
  224. [self migrateV1NamespaceToV2Namespace];
  225. // Exclude the app data used from iCloud backup.
  226. RemoteConfigAddSkipBackupAttributeToItemAtPath(dbPath);
  227. }
  228. } else {
  229. [strongSelf logDatabaseError];
  230. }
  231. });
  232. }
  233. - (BOOL)createTableSchema {
  234. RCN_MUST_NOT_BE_MAIN_THREAD();
  235. static const char *createTableMain =
  236. "create TABLE IF NOT EXISTS " RCNTableNameMain
  237. " (_id INTEGER PRIMARY KEY, bundle_identifier TEXT, namespace TEXT, key TEXT, value BLOB)";
  238. static const char *createTableMainActive =
  239. "create TABLE IF NOT EXISTS " RCNTableNameMainActive
  240. " (_id INTEGER PRIMARY KEY, bundle_identifier TEXT, namespace TEXT, key TEXT, value BLOB)";
  241. static const char *createTableMainDefault =
  242. "create TABLE IF NOT EXISTS " RCNTableNameMainDefault
  243. " (_id INTEGER PRIMARY KEY, bundle_identifier TEXT, namespace TEXT, key TEXT, value BLOB)";
  244. static const char *createTableMetadata =
  245. "create TABLE IF NOT EXISTS " RCNTableNameMetadata
  246. " (_id INTEGER PRIMARY KEY, bundle_identifier TEXT, namespace TEXT,"
  247. " fetch_time INTEGER, digest_per_ns BLOB, device_context BLOB, app_context BLOB, "
  248. "success_fetch_time BLOB, failure_fetch_time BLOB, last_fetch_status INTEGER, "
  249. "last_fetch_error INTEGER, last_apply_time INTEGER, last_set_defaults_time INTEGER)";
  250. static const char *createTableInternalMetadata =
  251. "create TABLE IF NOT EXISTS " RCNTableNameInternalMetadata
  252. " (_id INTEGER PRIMARY KEY, key TEXT, value BLOB)";
  253. static const char *createTableExperiment = "create TABLE IF NOT EXISTS " RCNTableNameExperiment
  254. " (_id INTEGER PRIMARY KEY, key TEXT, value BLOB)";
  255. static const char *createTablePersonalization =
  256. "create TABLE IF NOT EXISTS " RCNTableNamePersonalization
  257. " (_id INTEGER PRIMARY KEY, key INTEGER, value BLOB)";
  258. return [self executeQuery:createTableMain] && [self executeQuery:createTableMainActive] &&
  259. [self executeQuery:createTableMainDefault] && [self executeQuery:createTableMetadata] &&
  260. [self executeQuery:createTableInternalMetadata] &&
  261. [self executeQuery:createTableExperiment] &&
  262. [self executeQuery:createTablePersonalization];
  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)insertInternalMetadataTableWithValues:(NSArray *)values
  425. completionHandler:(RCNDBCompletion)handler {
  426. __weak RCNConfigDBManager *weakSelf = self;
  427. dispatch_async(_databaseOperationQueue, ^{
  428. BOOL success = [weakSelf insertInternalMetadataWithValues:values];
  429. if (handler) {
  430. dispatch_async(dispatch_get_main_queue(), ^{
  431. handler(success, nil);
  432. });
  433. }
  434. });
  435. }
  436. - (BOOL)insertInternalMetadataWithValues:(NSArray *)values {
  437. RCN_MUST_NOT_BE_MAIN_THREAD();
  438. if (values.count != 2) {
  439. return NO;
  440. }
  441. const char *SQL =
  442. "INSERT OR REPLACE INTO " RCNTableNameInternalMetadata " (key, value) values (?, ?)";
  443. sqlite3_stmt *statement = [self prepareSQL:SQL];
  444. if (!statement) {
  445. return NO;
  446. }
  447. NSString *aString = values[0];
  448. if (![self bindStringToStatement:statement index:1 string:aString]) {
  449. [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  450. return NO;
  451. }
  452. NSData *blobData = values[1];
  453. if (sqlite3_bind_blob(statement, 2, blobData.bytes, (int)blobData.length, NULL) != SQLITE_OK) {
  454. [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  455. return NO;
  456. }
  457. if (sqlite3_step(statement) != SQLITE_DONE) {
  458. [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  459. return NO;
  460. }
  461. sqlite3_finalize(statement);
  462. return YES;
  463. }
  464. - (void)insertExperimentTableWithKey:(NSString *)key
  465. value:(NSData *)serializedValue
  466. completionHandler:(RCNDBCompletion)handler {
  467. dispatch_async(_databaseOperationQueue, ^{
  468. BOOL success = [self insertExperimentTableWithKey:key value:serializedValue];
  469. if (handler) {
  470. dispatch_async(dispatch_get_main_queue(), ^{
  471. handler(success, nil);
  472. });
  473. }
  474. });
  475. }
  476. - (BOOL)insertExperimentTableWithKey:(NSString *)key value:(NSData *)dataValue {
  477. if ([key isEqualToString:@RCNExperimentTableKeyMetadata]) {
  478. return [self updateExperimentMetadata:dataValue];
  479. }
  480. RCN_MUST_NOT_BE_MAIN_THREAD();
  481. const char *SQL = "INSERT INTO " RCNTableNameExperiment " (key, value) values (?, ?)";
  482. sqlite3_stmt *statement = [self prepareSQL:SQL];
  483. if (!statement) {
  484. return NO;
  485. }
  486. if (![self bindStringToStatement:statement index:1 string:key]) {
  487. return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  488. }
  489. if (sqlite3_bind_blob(statement, 2, dataValue.bytes, (int)dataValue.length, NULL) != SQLITE_OK) {
  490. return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  491. }
  492. if (sqlite3_step(statement) != SQLITE_DONE) {
  493. return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  494. }
  495. sqlite3_finalize(statement);
  496. return YES;
  497. }
  498. - (BOOL)updateExperimentMetadata:(NSData *)dataValue {
  499. RCN_MUST_NOT_BE_MAIN_THREAD();
  500. const char *SQL = "INSERT OR REPLACE INTO " RCNTableNameExperiment
  501. " (_id, key, value) values ((SELECT _id from " RCNTableNameExperiment
  502. " WHERE key = ?), ?, ?)";
  503. sqlite3_stmt *statement = [self prepareSQL:SQL];
  504. if (!statement) {
  505. return NO;
  506. }
  507. if (![self bindStringToStatement:statement index:1 string:@RCNExperimentTableKeyMetadata]) {
  508. return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  509. }
  510. if (![self bindStringToStatement:statement index:2 string:@RCNExperimentTableKeyMetadata]) {
  511. return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  512. }
  513. if (sqlite3_bind_blob(statement, 3, dataValue.bytes, (int)dataValue.length, NULL) != SQLITE_OK) {
  514. return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  515. }
  516. if (sqlite3_step(statement) != SQLITE_DONE) {
  517. return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  518. }
  519. sqlite3_finalize(statement);
  520. return YES;
  521. }
  522. - (BOOL)insertOrUpdatePersonalizationConfig:(NSDictionary *)dataValue
  523. fromSource:(RCNDBSource)source {
  524. RCN_MUST_NOT_BE_MAIN_THREAD();
  525. NSError *error;
  526. NSData *JSONPayload = [NSJSONSerialization dataWithJSONObject:dataValue
  527. options:NSJSONWritingPrettyPrinted
  528. error:&error];
  529. if (!JSONPayload || error) {
  530. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000075",
  531. @"Invalid Personalization payload to be serialized.");
  532. }
  533. const char *SQL = "INSERT OR REPLACE INTO " RCNTableNamePersonalization
  534. " (_id, key, value) values ((SELECT _id from " RCNTableNamePersonalization
  535. " WHERE key = ?), ?, ?)";
  536. sqlite3_stmt *statement = [self prepareSQL:SQL];
  537. if (!statement) {
  538. return NO;
  539. }
  540. if (sqlite3_bind_int(statement, 1, (int)source) != SQLITE_OK) {
  541. return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  542. }
  543. if (sqlite3_bind_int(statement, 2, (int)source) != SQLITE_OK) {
  544. return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  545. }
  546. if (sqlite3_bind_blob(statement, 3, JSONPayload.bytes, (int)JSONPayload.length, NULL) !=
  547. SQLITE_OK) {
  548. return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  549. }
  550. if (sqlite3_step(statement) != SQLITE_DONE) {
  551. return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  552. }
  553. sqlite3_finalize(statement);
  554. return YES;
  555. }
  556. #pragma mark - update
  557. - (void)updateMetadataWithOption:(RCNUpdateOption)option
  558. namespace:(NSString *)namespace
  559. values:(NSArray *)values
  560. completionHandler:(RCNDBCompletion)handler {
  561. dispatch_async(_databaseOperationQueue, ^{
  562. BOOL success = [self updateMetadataTableWithOption:option namespace:namespace andValues:values];
  563. if (handler) {
  564. dispatch_async(dispatch_get_main_queue(), ^{
  565. handler(success, nil);
  566. });
  567. }
  568. });
  569. }
  570. - (BOOL)updateMetadataTableWithOption:(RCNUpdateOption)option
  571. namespace:(NSString *)namespace
  572. andValues:(NSArray *)values {
  573. RCN_MUST_NOT_BE_MAIN_THREAD();
  574. static const char *SQL =
  575. "UPDATE " RCNTableNameMetadata " (last_fetch_status, last_fetch_error, last_apply_time, "
  576. "last_set_defaults_time) values (?, ?, ?, ?) WHERE namespace = ?";
  577. if (option == RCNUpdateOptionFetchStatus) {
  578. SQL = "UPDATE " RCNTableNameMetadata
  579. " SET last_fetch_status = ?, last_fetch_error = ? WHERE namespace = ?";
  580. } else if (option == RCNUpdateOptionApplyTime) {
  581. SQL = "UPDATE " RCNTableNameMetadata " SET last_apply_time = ? WHERE namespace = ?";
  582. } else if (option == RCNUpdateOptionDefaultTime) {
  583. SQL = "UPDATE " RCNTableNameMetadata " SET last_set_defaults_time = ? WHERE namespace = ?";
  584. } else {
  585. return NO;
  586. }
  587. sqlite3_stmt *statement = [self prepareSQL:SQL];
  588. if (!statement) {
  589. return NO;
  590. }
  591. int index = 0;
  592. if ((option == RCNUpdateOptionApplyTime || option == RCNUpdateOptionDefaultTime) &&
  593. values.count == 1) {
  594. double value = [values[0] doubleValue];
  595. if (sqlite3_bind_double(statement, ++index, value) != SQLITE_OK) {
  596. return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  597. }
  598. } else if (option == RCNUpdateOptionFetchStatus && values.count == 2) {
  599. int value = [values[0] intValue];
  600. if (sqlite3_bind_int(statement, ++index, value) != SQLITE_OK) {
  601. return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  602. }
  603. value = [values[1] intValue];
  604. if (sqlite3_bind_int(statement, ++index, value) != SQLITE_OK) {
  605. return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  606. }
  607. }
  608. // bind namespace to query
  609. if (sqlite3_bind_text(statement, ++index, [namespace UTF8String], -1, SQLITE_TRANSIENT) !=
  610. SQLITE_OK) {
  611. return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  612. }
  613. if (sqlite3_step(statement) != SQLITE_DONE) {
  614. return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  615. }
  616. sqlite3_finalize(statement);
  617. return YES;
  618. }
  619. #pragma mark - read from DB
  620. - (NSDictionary *)loadMetadataWithBundleIdentifier:(NSString *)bundleIdentifier
  621. namespace:(NSString *)namespace {
  622. __block NSDictionary *metadataTableResult;
  623. __weak RCNConfigDBManager *weakSelf = self;
  624. dispatch_sync(_databaseOperationQueue, ^{
  625. metadataTableResult = [weakSelf loadMetadataTableWithBundleIdentifier:bundleIdentifier
  626. namespace:namespace];
  627. });
  628. if (metadataTableResult) {
  629. return metadataTableResult;
  630. }
  631. return [[NSDictionary alloc] init];
  632. }
  633. - (NSMutableDictionary *)loadMetadataTableWithBundleIdentifier:(NSString *)bundleIdentifier
  634. namespace:(NSString *)namespace {
  635. NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
  636. const char *SQL =
  637. "SELECT bundle_identifier, fetch_time, digest_per_ns, device_context, app_context, "
  638. "success_fetch_time, failure_fetch_time , last_fetch_status, "
  639. "last_fetch_error, last_apply_time, last_set_defaults_time FROM " RCNTableNameMetadata
  640. " WHERE bundle_identifier = ? and namespace = ?";
  641. sqlite3_stmt *statement = [self prepareSQL:SQL];
  642. if (!statement) {
  643. return nil;
  644. }
  645. NSArray *params = @[ bundleIdentifier, namespace ];
  646. [self bindStringsToStatement:statement stringArray:params];
  647. while (sqlite3_step(statement) == SQLITE_ROW) {
  648. NSString *dbBundleIdentifier =
  649. [[NSString alloc] initWithUTF8String:(char *)sqlite3_column_text(statement, 0)];
  650. if (dbBundleIdentifier && ![dbBundleIdentifier isEqualToString:bundleIdentifier]) {
  651. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000014",
  652. @"Load Metadata from table error: Wrong package name %@, should be %@.",
  653. dbBundleIdentifier, bundleIdentifier);
  654. return nil;
  655. }
  656. double fetchTime = sqlite3_column_double(statement, 1);
  657. NSData *digestPerNamespace = [NSData dataWithBytes:(char *)sqlite3_column_blob(statement, 2)
  658. length:sqlite3_column_bytes(statement, 2)];
  659. NSData *deviceContext = [NSData dataWithBytes:(char *)sqlite3_column_blob(statement, 3)
  660. length:sqlite3_column_bytes(statement, 3)];
  661. NSData *appContext = [NSData dataWithBytes:(char *)sqlite3_column_blob(statement, 4)
  662. length:sqlite3_column_bytes(statement, 4)];
  663. NSData *successTimeDigest = [NSData dataWithBytes:(char *)sqlite3_column_blob(statement, 5)
  664. length:sqlite3_column_bytes(statement, 5)];
  665. NSData *failureTimeDigest = [NSData dataWithBytes:(char *)sqlite3_column_blob(statement, 6)
  666. length:sqlite3_column_bytes(statement, 6)];
  667. int lastFetchStatus = sqlite3_column_int(statement, 7);
  668. int lastFetchFailReason = sqlite3_column_int(statement, 8);
  669. double lastApplyTimestamp = sqlite3_column_double(statement, 9);
  670. double lastSetDefaultsTimestamp = sqlite3_column_double(statement, 10);
  671. NSError *error;
  672. NSMutableDictionary *deviceContextDict = nil;
  673. if (deviceContext) {
  674. deviceContextDict = [NSJSONSerialization JSONObjectWithData:deviceContext
  675. options:NSJSONReadingMutableContainers
  676. error:&error];
  677. }
  678. NSMutableDictionary *appContextDict = nil;
  679. if (appContext) {
  680. appContextDict = [NSJSONSerialization JSONObjectWithData:appContext
  681. options:NSJSONReadingMutableContainers
  682. error:&error];
  683. }
  684. NSMutableDictionary<NSString *, id> *digestPerNamespaceDictionary = nil;
  685. if (digestPerNamespace) {
  686. digestPerNamespaceDictionary =
  687. [NSJSONSerialization JSONObjectWithData:digestPerNamespace
  688. options:NSJSONReadingMutableContainers
  689. error:&error];
  690. }
  691. NSMutableArray *successTimes = nil;
  692. if (successTimeDigest) {
  693. successTimes = [NSJSONSerialization JSONObjectWithData:successTimeDigest
  694. options:NSJSONReadingMutableContainers
  695. error:&error];
  696. }
  697. NSMutableArray *failureTimes = nil;
  698. if (failureTimeDigest) {
  699. failureTimes = [NSJSONSerialization JSONObjectWithData:failureTimeDigest
  700. options:NSJSONReadingMutableContainers
  701. error:&error];
  702. }
  703. dict[RCNKeyBundleIdentifier] = bundleIdentifier;
  704. dict[RCNKeyFetchTime] = @(fetchTime);
  705. dict[RCNKeyDigestPerNamespace] = digestPerNamespaceDictionary;
  706. dict[RCNKeyDeviceContext] = deviceContextDict;
  707. dict[RCNKeyAppContext] = appContextDict;
  708. dict[RCNKeySuccessFetchTime] = successTimes;
  709. dict[RCNKeyFailureFetchTime] = failureTimes;
  710. dict[RCNKeyLastFetchStatus] = @(lastFetchStatus);
  711. dict[RCNKeyLastFetchError] = @(lastFetchFailReason);
  712. dict[RCNKeyLastApplyTime] = @(lastApplyTimestamp);
  713. dict[RCNKeyLastSetDefaultsTime] = @(lastSetDefaultsTimestamp);
  714. break;
  715. }
  716. sqlite3_finalize(statement);
  717. return dict;
  718. }
  719. - (void)loadExperimentWithCompletionHandler:(RCNDBCompletion)handler {
  720. __weak RCNConfigDBManager *weakSelf = self;
  721. dispatch_async(_databaseOperationQueue, ^{
  722. RCNConfigDBManager *strongSelf = weakSelf;
  723. if (!strongSelf) {
  724. return;
  725. }
  726. NSMutableArray *experimentPayloads =
  727. [strongSelf loadExperimentTableFromKey:@RCNExperimentTableKeyPayload];
  728. if (!experimentPayloads) {
  729. experimentPayloads = [[NSMutableArray alloc] init];
  730. }
  731. NSMutableDictionary *experimentMetadata;
  732. NSMutableArray *experiments =
  733. [strongSelf loadExperimentTableFromKey:@RCNExperimentTableKeyMetadata];
  734. // There should be only one entry for experiment metadata.
  735. if (experiments.count > 0) {
  736. NSError *error;
  737. experimentMetadata = [NSJSONSerialization JSONObjectWithData:experiments[0]
  738. options:NSJSONReadingMutableContainers
  739. error:&error];
  740. }
  741. if (!experimentMetadata) {
  742. experimentMetadata = [[NSMutableDictionary alloc] init];
  743. }
  744. if (handler) {
  745. dispatch_async(dispatch_get_main_queue(), ^{
  746. handler(
  747. YES, @{
  748. @RCNExperimentTableKeyPayload : [experimentPayloads copy],
  749. @RCNExperimentTableKeyMetadata : [experimentMetadata copy]
  750. });
  751. });
  752. }
  753. });
  754. }
  755. - (NSMutableArray<NSData *> *)loadExperimentTableFromKey:(NSString *)key {
  756. RCN_MUST_NOT_BE_MAIN_THREAD();
  757. NSMutableArray *results = [[NSMutableArray alloc] init];
  758. const char *SQL = "SELECT value FROM " RCNTableNameExperiment " WHERE key = ?";
  759. sqlite3_stmt *statement = [self prepareSQL:SQL];
  760. if (!statement) {
  761. return nil;
  762. }
  763. NSArray *params = @[ key ];
  764. [self bindStringsToStatement:statement stringArray:params];
  765. NSData *experimentData;
  766. while (sqlite3_step(statement) == SQLITE_ROW) {
  767. experimentData = [NSData dataWithBytes:(char *)sqlite3_column_blob(statement, 0)
  768. length:sqlite3_column_bytes(statement, 0)];
  769. if (experimentData) {
  770. [results addObject:experimentData];
  771. }
  772. }
  773. sqlite3_finalize(statement);
  774. return results;
  775. }
  776. - (void)loadPersonalizationWithCompletionHandler:(RCNDBLoadCompletion)handler {
  777. __weak RCNConfigDBManager *weakSelf = self;
  778. dispatch_async(_databaseOperationQueue, ^{
  779. RCNConfigDBManager *strongSelf = weakSelf;
  780. if (!strongSelf) {
  781. return;
  782. }
  783. NSDictionary *activePersonalization;
  784. NSData *personalizationResult = [strongSelf loadPersonalizationTableFromKey:RCNDBSourceActive];
  785. // There should be only one entry for Personalization metadata.
  786. if (personalizationResult) {
  787. NSError *error;
  788. activePersonalization = [NSJSONSerialization JSONObjectWithData:personalizationResult
  789. options:0
  790. error:&error];
  791. }
  792. if (!activePersonalization) {
  793. activePersonalization = [[NSMutableDictionary alloc] init];
  794. }
  795. NSDictionary *fetchedPersonalization;
  796. personalizationResult = [strongSelf loadPersonalizationTableFromKey:RCNDBSourceFetched];
  797. // There should be only one entry for Personalization metadata.
  798. if (personalizationResult) {
  799. NSError *error;
  800. fetchedPersonalization = [NSJSONSerialization JSONObjectWithData:personalizationResult
  801. options:0
  802. error:&error];
  803. }
  804. if (!fetchedPersonalization) {
  805. fetchedPersonalization = [[NSMutableDictionary alloc] init];
  806. }
  807. if (handler) {
  808. dispatch_async(dispatch_get_main_queue(), ^{
  809. handler(YES, fetchedPersonalization, activePersonalization, nil);
  810. });
  811. }
  812. });
  813. }
  814. - (NSData *)loadPersonalizationTableFromKey:(int)key {
  815. RCN_MUST_NOT_BE_MAIN_THREAD();
  816. NSMutableArray *results = [[NSMutableArray alloc] init];
  817. const char *SQL = "SELECT value FROM " RCNTableNamePersonalization " WHERE key = ?";
  818. sqlite3_stmt *statement = [self prepareSQL:SQL];
  819. if (!statement) {
  820. return nil;
  821. }
  822. if (sqlite3_bind_int(statement, 1, key) != SQLITE_OK) {
  823. [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  824. return nil;
  825. }
  826. NSData *personalizationData;
  827. while (sqlite3_step(statement) == SQLITE_ROW) {
  828. personalizationData = [NSData dataWithBytes:(char *)sqlite3_column_blob(statement, 0)
  829. length:sqlite3_column_bytes(statement, 0)];
  830. if (personalizationData) {
  831. [results addObject:personalizationData];
  832. }
  833. }
  834. sqlite3_finalize(statement);
  835. // There should be only one entry in this table.
  836. if (results.count != 1) {
  837. return nil;
  838. }
  839. return results[0];
  840. }
  841. - (NSDictionary *)loadInternalMetadataTable {
  842. __block NSMutableDictionary *internalMetadataTableResult;
  843. __weak RCNConfigDBManager *weakSelf = self;
  844. dispatch_sync(_databaseOperationQueue, ^{
  845. internalMetadataTableResult = [weakSelf loadInternalMetadataTableInternal];
  846. });
  847. return internalMetadataTableResult;
  848. }
  849. - (NSMutableDictionary *)loadInternalMetadataTableInternal {
  850. NSMutableDictionary *internalMetadata = [[NSMutableDictionary alloc] init];
  851. const char *SQL = "SELECT key, value FROM " RCNTableNameInternalMetadata;
  852. sqlite3_stmt *statement = [self prepareSQL:SQL];
  853. if (!statement) {
  854. return nil;
  855. }
  856. while (sqlite3_step(statement) == SQLITE_ROW) {
  857. NSString *key = [[NSString alloc] initWithUTF8String:(char *)sqlite3_column_text(statement, 0)];
  858. NSData *dataValue = [NSData dataWithBytes:(char *)sqlite3_column_blob(statement, 1)
  859. length:sqlite3_column_bytes(statement, 1)];
  860. internalMetadata[key] = dataValue;
  861. }
  862. sqlite3_finalize(statement);
  863. return internalMetadata;
  864. }
  865. /// This method is only meant to be called at init time. The underlying logic will need to be
  866. /// revaluated if the assumption changes at a later time.
  867. - (void)loadMainWithBundleIdentifier:(NSString *)bundleIdentifier
  868. completionHandler:(RCNDBLoadCompletion)handler {
  869. __weak RCNConfigDBManager *weakSelf = self;
  870. dispatch_async(_databaseOperationQueue, ^{
  871. RCNConfigDBManager *strongSelf = weakSelf;
  872. if (!strongSelf) {
  873. return;
  874. }
  875. __block NSDictionary *fetchedConfig =
  876. [strongSelf loadMainTableWithBundleIdentifier:bundleIdentifier
  877. fromSource:RCNDBSourceFetched];
  878. __block NSDictionary *activeConfig =
  879. [strongSelf loadMainTableWithBundleIdentifier:bundleIdentifier
  880. fromSource:RCNDBSourceActive];
  881. __block NSDictionary *defaultConfig =
  882. [strongSelf loadMainTableWithBundleIdentifier:bundleIdentifier
  883. fromSource:RCNDBSourceDefault];
  884. if (handler) {
  885. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  886. fetchedConfig = fetchedConfig ? fetchedConfig : [[NSDictionary alloc] init];
  887. activeConfig = activeConfig ? activeConfig : [[NSDictionary alloc] init];
  888. defaultConfig = defaultConfig ? defaultConfig : [[NSDictionary alloc] init];
  889. handler(YES, fetchedConfig, activeConfig, defaultConfig);
  890. });
  891. }
  892. });
  893. }
  894. - (NSMutableDictionary *)loadMainTableWithBundleIdentifier:(NSString *)bundleIdentifier
  895. fromSource:(RCNDBSource)source {
  896. NSMutableDictionary *namespaceToConfig = [[NSMutableDictionary alloc] init];
  897. const char *SQL = "SELECT bundle_identifier, namespace, key, value FROM " RCNTableNameMain
  898. " WHERE bundle_identifier = ?";
  899. if (source == RCNDBSourceDefault) {
  900. SQL = "SELECT bundle_identifier, namespace, key, value FROM " RCNTableNameMainDefault
  901. " WHERE bundle_identifier = ?";
  902. } else if (source == RCNDBSourceActive) {
  903. SQL = "SELECT bundle_identifier, namespace, key, value FROM " RCNTableNameMainActive
  904. " WHERE bundle_identifier = ?";
  905. }
  906. NSArray *params = @[ bundleIdentifier ];
  907. sqlite3_stmt *statement = [self prepareSQL:SQL];
  908. if (!statement) {
  909. return nil;
  910. }
  911. [self bindStringsToStatement:statement stringArray:params];
  912. while (sqlite3_step(statement) == SQLITE_ROW) {
  913. NSString *configNamespace =
  914. [[NSString alloc] initWithUTF8String:(char *)sqlite3_column_text(statement, 1)];
  915. NSString *key = [[NSString alloc] initWithUTF8String:(char *)sqlite3_column_text(statement, 2)];
  916. NSData *value = [NSData dataWithBytes:(char *)sqlite3_column_blob(statement, 3)
  917. length:sqlite3_column_bytes(statement, 3)];
  918. if (!namespaceToConfig[configNamespace]) {
  919. namespaceToConfig[configNamespace] = [[NSMutableDictionary alloc] init];
  920. }
  921. if (source == RCNDBSourceDefault) {
  922. namespaceToConfig[configNamespace][key] =
  923. [[FIRRemoteConfigValue alloc] initWithData:value source:FIRRemoteConfigSourceDefault];
  924. } else {
  925. namespaceToConfig[configNamespace][key] =
  926. [[FIRRemoteConfigValue alloc] initWithData:value source:FIRRemoteConfigSourceRemote];
  927. }
  928. }
  929. sqlite3_finalize(statement);
  930. return namespaceToConfig;
  931. }
  932. #pragma mark - delete
  933. - (void)deleteRecordFromMainTableWithNamespace:(NSString *)namespace_p
  934. bundleIdentifier:(NSString *)bundleIdentifier
  935. fromSource:(RCNDBSource)source {
  936. __weak RCNConfigDBManager *weakSelf = self;
  937. dispatch_async(_databaseOperationQueue, ^{
  938. RCNConfigDBManager *strongSelf = weakSelf;
  939. if (!strongSelf) {
  940. return;
  941. }
  942. NSArray *params = @[ bundleIdentifier, namespace_p ];
  943. const char *SQL =
  944. "DELETE FROM " RCNTableNameMain " WHERE bundle_identifier = ? and namespace = ?";
  945. if (source == RCNDBSourceDefault) {
  946. SQL = "DELETE FROM " RCNTableNameMainDefault " WHERE bundle_identifier = ? and namespace = ?";
  947. } else if (source == RCNDBSourceActive) {
  948. SQL = "DELETE FROM " RCNTableNameMainActive " WHERE bundle_identifier = ? and namespace = ?";
  949. }
  950. [strongSelf executeQuery:SQL withParams:params];
  951. });
  952. }
  953. - (void)deleteRecordWithBundleIdentifier:(NSString *)bundleIdentifier
  954. namespace:(NSString *)namespace
  955. isInternalDB:(BOOL)isInternalDB {
  956. __weak RCNConfigDBManager *weakSelf = self;
  957. dispatch_async(_databaseOperationQueue, ^{
  958. RCNConfigDBManager *strongSelf = weakSelf;
  959. if (!strongSelf) {
  960. return;
  961. }
  962. const char *SQL = "DELETE FROM " RCNTableNameInternalMetadata " WHERE key LIKE ?";
  963. NSArray *params = @[ bundleIdentifier ];
  964. if (!isInternalDB) {
  965. SQL = "DELETE FROM " RCNTableNameMetadata " WHERE bundle_identifier = ? and namespace = ?";
  966. params = @[ bundleIdentifier, namespace ];
  967. }
  968. [strongSelf executeQuery:SQL withParams:params];
  969. });
  970. }
  971. - (void)deleteAllRecordsFromTableWithSource:(RCNDBSource)source {
  972. __weak RCNConfigDBManager *weakSelf = self;
  973. dispatch_async(_databaseOperationQueue, ^{
  974. RCNConfigDBManager *strongSelf = weakSelf;
  975. if (!strongSelf) {
  976. return;
  977. }
  978. const char *SQL = "DELETE FROM " RCNTableNameMain;
  979. if (source == RCNDBSourceDefault) {
  980. SQL = "DELETE FROM " RCNTableNameMainDefault;
  981. } else if (source == RCNDBSourceActive) {
  982. SQL = "DELETE FROM " RCNTableNameMainActive;
  983. }
  984. [strongSelf executeQuery:SQL];
  985. });
  986. }
  987. - (void)deleteExperimentTableForKey:(NSString *)key {
  988. __weak RCNConfigDBManager *weakSelf = self;
  989. dispatch_async(_databaseOperationQueue, ^{
  990. RCNConfigDBManager *strongSelf = weakSelf;
  991. if (!strongSelf) {
  992. return;
  993. }
  994. NSArray *params = @[ key ];
  995. const char *SQL = "DELETE FROM " RCNTableNameExperiment " WHERE key = ?";
  996. [strongSelf executeQuery:SQL withParams:params];
  997. });
  998. }
  999. #pragma mark - helper
  1000. - (BOOL)executeQuery:(const char *)SQL withParams:(NSArray *)params {
  1001. RCN_MUST_NOT_BE_MAIN_THREAD();
  1002. sqlite3_stmt *statement = [self prepareSQL:SQL];
  1003. if (!statement) {
  1004. return NO;
  1005. }
  1006. [self bindStringsToStatement:statement stringArray:params];
  1007. if (sqlite3_step(statement) != SQLITE_DONE) {
  1008. return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  1009. }
  1010. sqlite3_finalize(statement);
  1011. return YES;
  1012. }
  1013. /// Params only accept TEXT format string.
  1014. - (BOOL)bindStringsToStatement:(sqlite3_stmt *)statement stringArray:(NSArray *)array {
  1015. int index = 1;
  1016. for (NSString *param in array) {
  1017. if (![self bindStringToStatement:statement index:index string:param]) {
  1018. return [self logErrorWithSQL:nil finalizeStatement:statement returnValue:NO];
  1019. }
  1020. index++;
  1021. }
  1022. return YES;
  1023. }
  1024. - (BOOL)bindStringToStatement:(sqlite3_stmt *)statement index:(int)index string:(NSString *)value {
  1025. if (sqlite3_bind_text(statement, index, [value UTF8String], -1, SQLITE_TRANSIENT) != SQLITE_OK) {
  1026. return [self logErrorWithSQL:nil finalizeStatement:statement returnValue:NO];
  1027. }
  1028. return YES;
  1029. }
  1030. - (sqlite3_stmt *)prepareSQL:(const char *)SQL {
  1031. sqlite3_stmt *statement = nil;
  1032. if (sqlite3_prepare_v2(_database, SQL, -1, &statement, NULL) != SQLITE_OK) {
  1033. [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  1034. return nil;
  1035. }
  1036. return statement;
  1037. }
  1038. - (NSString *)errorMessage {
  1039. return [NSString stringWithFormat:@"%s", sqlite3_errmsg(_database)];
  1040. }
  1041. - (int)errorCode {
  1042. return sqlite3_errcode(_database);
  1043. }
  1044. - (void)logDatabaseError {
  1045. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000015", @"Error message: %@. Error code: %d.",
  1046. [self errorMessage], [self errorCode]);
  1047. }
  1048. - (BOOL)logErrorWithSQL:(const char *)SQL
  1049. finalizeStatement:(sqlite3_stmt *)statement
  1050. returnValue:(BOOL)returnValue {
  1051. if (SQL) {
  1052. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000016", @"Failed with SQL: %s.", SQL);
  1053. }
  1054. [self logDatabaseError];
  1055. if (statement) {
  1056. sqlite3_finalize(statement);
  1057. }
  1058. return returnValue;
  1059. }
  1060. - (BOOL)isNewDatabase {
  1061. return gIsNewDatabase;
  1062. }
  1063. @end