RCNConfigDBManager.m 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202
  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. /// Load activated experiments payload.
  746. NSMutableArray *activeExperimentPayloads =
  747. [strongSelf loadExperimentTableFromKey:@RCNExperimentTableKeyActivePayload];
  748. if (!activeExperimentPayloads) {
  749. activeExperimentPayloads = [[NSMutableArray alloc] init];
  750. }
  751. if (handler) {
  752. dispatch_async(dispatch_get_main_queue(), ^{
  753. handler(
  754. YES, @{
  755. @RCNExperimentTableKeyPayload : [experimentPayloads copy],
  756. @RCNExperimentTableKeyMetadata : [experimentMetadata copy],
  757. /// Activated experiments only need ExperimentsDescriptions data, which
  758. /// experimentPayloads contains.
  759. @RCNExperimentTableKeyActivePayload : [activeExperimentPayloads copy]
  760. });
  761. });
  762. }
  763. });
  764. }
  765. - (NSMutableArray<NSData *> *)loadExperimentTableFromKey:(NSString *)key {
  766. RCN_MUST_NOT_BE_MAIN_THREAD();
  767. NSMutableArray *results = [[NSMutableArray alloc] init];
  768. const char *SQL = "SELECT value FROM " RCNTableNameExperiment " WHERE key = ?";
  769. sqlite3_stmt *statement = [self prepareSQL:SQL];
  770. if (!statement) {
  771. return nil;
  772. }
  773. NSArray *params = @[ key ];
  774. [self bindStringsToStatement:statement stringArray:params];
  775. NSData *experimentData;
  776. while (sqlite3_step(statement) == SQLITE_ROW) {
  777. experimentData = [NSData dataWithBytes:(char *)sqlite3_column_blob(statement, 0)
  778. length:sqlite3_column_bytes(statement, 0)];
  779. if (experimentData) {
  780. [results addObject:experimentData];
  781. }
  782. }
  783. sqlite3_finalize(statement);
  784. return results;
  785. }
  786. - (void)loadPersonalizationWithCompletionHandler:(RCNDBLoadCompletion)handler {
  787. __weak RCNConfigDBManager *weakSelf = self;
  788. dispatch_async(_databaseOperationQueue, ^{
  789. RCNConfigDBManager *strongSelf = weakSelf;
  790. if (!strongSelf) {
  791. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  792. handler(NO, [NSMutableDictionary new], [NSMutableDictionary new], nil);
  793. });
  794. return;
  795. }
  796. NSDictionary *activePersonalization;
  797. NSData *personalizationResult = [strongSelf loadPersonalizationTableFromKey:RCNDBSourceActive];
  798. // There should be only one entry for Personalization metadata.
  799. if (personalizationResult) {
  800. NSError *error;
  801. activePersonalization = [NSJSONSerialization JSONObjectWithData:personalizationResult
  802. options:0
  803. error:&error];
  804. }
  805. if (!activePersonalization) {
  806. activePersonalization = [[NSMutableDictionary alloc] init];
  807. }
  808. NSDictionary *fetchedPersonalization;
  809. personalizationResult = [strongSelf loadPersonalizationTableFromKey:RCNDBSourceFetched];
  810. // There should be only one entry for Personalization metadata.
  811. if (personalizationResult) {
  812. NSError *error;
  813. fetchedPersonalization = [NSJSONSerialization JSONObjectWithData:personalizationResult
  814. options:0
  815. error:&error];
  816. }
  817. if (!fetchedPersonalization) {
  818. fetchedPersonalization = [[NSMutableDictionary alloc] init];
  819. }
  820. if (handler) {
  821. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  822. handler(YES, fetchedPersonalization, activePersonalization, nil);
  823. });
  824. }
  825. });
  826. }
  827. - (NSData *)loadPersonalizationTableFromKey:(int)key {
  828. RCN_MUST_NOT_BE_MAIN_THREAD();
  829. NSMutableArray *results = [[NSMutableArray alloc] init];
  830. const char *SQL = "SELECT value FROM " RCNTableNamePersonalization " WHERE key = ?";
  831. sqlite3_stmt *statement = [self prepareSQL:SQL];
  832. if (!statement) {
  833. return nil;
  834. }
  835. if (sqlite3_bind_int(statement, 1, key) != SQLITE_OK) {
  836. [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  837. return nil;
  838. }
  839. NSData *personalizationData;
  840. while (sqlite3_step(statement) == SQLITE_ROW) {
  841. personalizationData = [NSData dataWithBytes:(char *)sqlite3_column_blob(statement, 0)
  842. length:sqlite3_column_bytes(statement, 0)];
  843. if (personalizationData) {
  844. [results addObject:personalizationData];
  845. }
  846. }
  847. sqlite3_finalize(statement);
  848. // There should be only one entry in this table.
  849. if (results.count != 1) {
  850. return nil;
  851. }
  852. return results[0];
  853. }
  854. - (NSDictionary *)loadInternalMetadataTable {
  855. __block NSMutableDictionary *internalMetadataTableResult;
  856. __weak RCNConfigDBManager *weakSelf = self;
  857. dispatch_sync(_databaseOperationQueue, ^{
  858. internalMetadataTableResult = [weakSelf loadInternalMetadataTableInternal];
  859. });
  860. return internalMetadataTableResult;
  861. }
  862. - (NSMutableDictionary *)loadInternalMetadataTableInternal {
  863. NSMutableDictionary *internalMetadata = [[NSMutableDictionary alloc] init];
  864. const char *SQL = "SELECT key, value FROM " RCNTableNameInternalMetadata;
  865. sqlite3_stmt *statement = [self prepareSQL:SQL];
  866. if (!statement) {
  867. return nil;
  868. }
  869. while (sqlite3_step(statement) == SQLITE_ROW) {
  870. NSString *key = [[NSString alloc] initWithUTF8String:(char *)sqlite3_column_text(statement, 0)];
  871. NSData *dataValue = [NSData dataWithBytes:(char *)sqlite3_column_blob(statement, 1)
  872. length:sqlite3_column_bytes(statement, 1)];
  873. internalMetadata[key] = dataValue;
  874. }
  875. sqlite3_finalize(statement);
  876. return internalMetadata;
  877. }
  878. /// This method is only meant to be called at init time. The underlying logic will need to be
  879. /// revaluated if the assumption changes at a later time.
  880. - (void)loadMainWithBundleIdentifier:(NSString *)bundleIdentifier
  881. completionHandler:(RCNDBLoadCompletion)handler {
  882. __weak RCNConfigDBManager *weakSelf = self;
  883. dispatch_async(_databaseOperationQueue, ^{
  884. RCNConfigDBManager *strongSelf = weakSelf;
  885. if (!strongSelf) {
  886. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  887. handler(NO, [NSDictionary new], [NSDictionary new], [NSDictionary new]);
  888. });
  889. return;
  890. }
  891. __block NSDictionary *fetchedConfig =
  892. [strongSelf loadMainTableWithBundleIdentifier:bundleIdentifier
  893. fromSource:RCNDBSourceFetched];
  894. __block NSDictionary *activeConfig =
  895. [strongSelf loadMainTableWithBundleIdentifier:bundleIdentifier
  896. fromSource:RCNDBSourceActive];
  897. __block NSDictionary *defaultConfig =
  898. [strongSelf loadMainTableWithBundleIdentifier:bundleIdentifier
  899. fromSource:RCNDBSourceDefault];
  900. if (handler) {
  901. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  902. fetchedConfig = fetchedConfig ? fetchedConfig : [[NSDictionary alloc] init];
  903. activeConfig = activeConfig ? activeConfig : [[NSDictionary alloc] init];
  904. defaultConfig = defaultConfig ? defaultConfig : [[NSDictionary alloc] init];
  905. handler(YES, fetchedConfig, activeConfig, defaultConfig);
  906. });
  907. }
  908. });
  909. }
  910. - (NSMutableDictionary *)loadMainTableWithBundleIdentifier:(NSString *)bundleIdentifier
  911. fromSource:(RCNDBSource)source {
  912. NSMutableDictionary *namespaceToConfig = [[NSMutableDictionary alloc] init];
  913. const char *SQL = "SELECT bundle_identifier, namespace, key, value FROM " RCNTableNameMain
  914. " WHERE bundle_identifier = ?";
  915. if (source == RCNDBSourceDefault) {
  916. SQL = "SELECT bundle_identifier, namespace, key, value FROM " RCNTableNameMainDefault
  917. " WHERE bundle_identifier = ?";
  918. } else if (source == RCNDBSourceActive) {
  919. SQL = "SELECT bundle_identifier, namespace, key, value FROM " RCNTableNameMainActive
  920. " WHERE bundle_identifier = ?";
  921. }
  922. NSArray *params = @[ bundleIdentifier ];
  923. sqlite3_stmt *statement = [self prepareSQL:SQL];
  924. if (!statement) {
  925. return nil;
  926. }
  927. [self bindStringsToStatement:statement stringArray:params];
  928. while (sqlite3_step(statement) == SQLITE_ROW) {
  929. NSString *configNamespace =
  930. [[NSString alloc] initWithUTF8String:(char *)sqlite3_column_text(statement, 1)];
  931. NSString *key = [[NSString alloc] initWithUTF8String:(char *)sqlite3_column_text(statement, 2)];
  932. NSData *value = [NSData dataWithBytes:(char *)sqlite3_column_blob(statement, 3)
  933. length:sqlite3_column_bytes(statement, 3)];
  934. if (!namespaceToConfig[configNamespace]) {
  935. namespaceToConfig[configNamespace] = [[NSMutableDictionary alloc] init];
  936. }
  937. if (source == RCNDBSourceDefault) {
  938. namespaceToConfig[configNamespace][key] =
  939. [[FIRRemoteConfigValue alloc] initWithData:value source:FIRRemoteConfigSourceDefault];
  940. } else {
  941. namespaceToConfig[configNamespace][key] =
  942. [[FIRRemoteConfigValue alloc] initWithData:value source:FIRRemoteConfigSourceRemote];
  943. }
  944. }
  945. sqlite3_finalize(statement);
  946. return namespaceToConfig;
  947. }
  948. #pragma mark - delete
  949. - (void)deleteRecordFromMainTableWithNamespace:(NSString *)namespace_p
  950. bundleIdentifier:(NSString *)bundleIdentifier
  951. fromSource:(RCNDBSource)source {
  952. __weak RCNConfigDBManager *weakSelf = self;
  953. dispatch_async(_databaseOperationQueue, ^{
  954. RCNConfigDBManager *strongSelf = weakSelf;
  955. if (!strongSelf) {
  956. return;
  957. }
  958. NSArray *params = @[ bundleIdentifier, namespace_p ];
  959. const char *SQL =
  960. "DELETE FROM " RCNTableNameMain " WHERE bundle_identifier = ? and namespace = ?";
  961. if (source == RCNDBSourceDefault) {
  962. SQL = "DELETE FROM " RCNTableNameMainDefault " WHERE bundle_identifier = ? and namespace = ?";
  963. } else if (source == RCNDBSourceActive) {
  964. SQL = "DELETE FROM " RCNTableNameMainActive " WHERE bundle_identifier = ? and namespace = ?";
  965. }
  966. [strongSelf executeQuery:SQL withParams:params];
  967. });
  968. }
  969. - (void)deleteRecordWithBundleIdentifier:(NSString *)bundleIdentifier
  970. namespace:(NSString *)namespace
  971. isInternalDB:(BOOL)isInternalDB {
  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 " RCNTableNameInternalMetadata " WHERE key LIKE ?";
  979. NSArray *params = @[ bundleIdentifier ];
  980. if (!isInternalDB) {
  981. SQL = "DELETE FROM " RCNTableNameMetadata " WHERE bundle_identifier = ? and namespace = ?";
  982. params = @[ bundleIdentifier, namespace ];
  983. }
  984. [strongSelf executeQuery:SQL withParams:params];
  985. });
  986. }
  987. - (void)deleteAllRecordsFromTableWithSource:(RCNDBSource)source {
  988. __weak RCNConfigDBManager *weakSelf = self;
  989. dispatch_async(_databaseOperationQueue, ^{
  990. RCNConfigDBManager *strongSelf = weakSelf;
  991. if (!strongSelf) {
  992. return;
  993. }
  994. const char *SQL = "DELETE FROM " RCNTableNameMain;
  995. if (source == RCNDBSourceDefault) {
  996. SQL = "DELETE FROM " RCNTableNameMainDefault;
  997. } else if (source == RCNDBSourceActive) {
  998. SQL = "DELETE FROM " RCNTableNameMainActive;
  999. }
  1000. [strongSelf executeQuery:SQL];
  1001. });
  1002. }
  1003. - (void)deleteExperimentTableForKey:(NSString *)key {
  1004. __weak RCNConfigDBManager *weakSelf = self;
  1005. dispatch_async(_databaseOperationQueue, ^{
  1006. RCNConfigDBManager *strongSelf = weakSelf;
  1007. if (!strongSelf) {
  1008. return;
  1009. }
  1010. NSArray *params = @[ key ];
  1011. const char *SQL = "DELETE FROM " RCNTableNameExperiment " WHERE key = ?";
  1012. [strongSelf executeQuery:SQL withParams:params];
  1013. });
  1014. }
  1015. #pragma mark - helper
  1016. - (BOOL)executeQuery:(const char *)SQL withParams:(NSArray *)params {
  1017. RCN_MUST_NOT_BE_MAIN_THREAD();
  1018. sqlite3_stmt *statement = [self prepareSQL:SQL];
  1019. if (!statement) {
  1020. return NO;
  1021. }
  1022. [self bindStringsToStatement:statement stringArray:params];
  1023. if (sqlite3_step(statement) != SQLITE_DONE) {
  1024. return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  1025. }
  1026. sqlite3_finalize(statement);
  1027. return YES;
  1028. }
  1029. /// Params only accept TEXT format string.
  1030. - (BOOL)bindStringsToStatement:(sqlite3_stmt *)statement stringArray:(NSArray *)array {
  1031. int index = 1;
  1032. for (NSString *param in array) {
  1033. if (![self bindStringToStatement:statement index:index string:param]) {
  1034. return [self logErrorWithSQL:nil finalizeStatement:statement returnValue:NO];
  1035. }
  1036. index++;
  1037. }
  1038. return YES;
  1039. }
  1040. - (BOOL)bindStringToStatement:(sqlite3_stmt *)statement index:(int)index string:(NSString *)value {
  1041. if (sqlite3_bind_text(statement, index, [value UTF8String], -1, SQLITE_TRANSIENT) != SQLITE_OK) {
  1042. return [self logErrorWithSQL:nil finalizeStatement:statement returnValue:NO];
  1043. }
  1044. return YES;
  1045. }
  1046. - (sqlite3_stmt *)prepareSQL:(const char *)SQL {
  1047. sqlite3_stmt *statement = nil;
  1048. if (sqlite3_prepare_v2(_database, SQL, -1, &statement, NULL) != SQLITE_OK) {
  1049. [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  1050. return nil;
  1051. }
  1052. return statement;
  1053. }
  1054. - (NSString *)errorMessage {
  1055. return [NSString stringWithFormat:@"%s", sqlite3_errmsg(_database)];
  1056. }
  1057. - (int)errorCode {
  1058. return sqlite3_errcode(_database);
  1059. }
  1060. - (void)logDatabaseError {
  1061. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000015", @"Error message: %@. Error code: %d.",
  1062. [self errorMessage], [self errorCode]);
  1063. }
  1064. - (BOOL)logErrorWithSQL:(const char *)SQL
  1065. finalizeStatement:(sqlite3_stmt *)statement
  1066. returnValue:(BOOL)returnValue {
  1067. if (SQL) {
  1068. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000016", @"Failed with SQL: %s.", SQL);
  1069. }
  1070. [self logDatabaseError];
  1071. if (statement) {
  1072. sqlite3_finalize(statement);
  1073. }
  1074. return returnValue;
  1075. }
  1076. - (BOOL)isNewDatabase {
  1077. return gIsNewDatabase;
  1078. }
  1079. @end