RCNConfigDBManager.m 39 KB

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