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. if (sqlite3_close(strongSelf->_database) != SQLITE_OK) {
  262. [self logDatabaseError];
  263. }
  264. strongSelf->_database = nil;
  265. NSFileManager *fileManager = [NSFileManager defaultManager];
  266. NSError *error;
  267. if (![fileManager removeItemAtPath:path error:&error]) {
  268. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000011",
  269. @"Failed to remove database at path %@ for error %@.", path, error);
  270. }
  271. });
  272. }
  273. - (void)removeDatabase:(NSString *)path {
  274. if (sqlite3_close(_database) != SQLITE_OK) {
  275. [self logDatabaseError];
  276. }
  277. _database = nil;
  278. NSFileManager *fileManager = [NSFileManager defaultManager];
  279. NSError *error;
  280. if (![fileManager removeItemAtPath:path error:&error]) {
  281. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000011",
  282. @"Failed to remove database at path %@ for error %@.", path, error);
  283. }
  284. }
  285. #pragma mark - execute
  286. - (BOOL)executeQuery:(const char *)SQL {
  287. RCN_MUST_NOT_BE_MAIN_THREAD();
  288. char *error;
  289. if (sqlite3_exec(_database, SQL, nil, nil, &error) != SQLITE_OK) {
  290. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000012", @"Failed to execute query with error %s.",
  291. error);
  292. return NO;
  293. }
  294. return YES;
  295. }
  296. #pragma mark - insert
  297. - (void)insertMetadataTableWithValues:(NSDictionary *)columnNameToValue
  298. completionHandler:(RCNDBCompletion)handler {
  299. __weak RCNConfigDBManager *weakSelf = self;
  300. dispatch_async(_databaseOperationQueue, ^{
  301. BOOL success = [weakSelf insertMetadataTableWithValues:columnNameToValue];
  302. if (handler) {
  303. dispatch_async(dispatch_get_main_queue(), ^{
  304. handler(success, nil);
  305. });
  306. }
  307. });
  308. }
  309. - (BOOL)insertMetadataTableWithValues:(NSDictionary *)columnNameToValue {
  310. RCN_MUST_NOT_BE_MAIN_THREAD();
  311. static const char *SQL =
  312. "INSERT INTO " RCNTableNameMetadata
  313. " (bundle_identifier, fetch_time, digest_per_ns, device_context, "
  314. "app_context, success_fetch_time, failure_fetch_time, last_fetch_status, "
  315. "last_fetch_error, last_apply_time, last_set_defaults_time) values (?, ?, ?, ?, ?, "
  316. "?, ?, ?, ?, ?, ?)";
  317. sqlite3_stmt *statement = [self prepareSQL:SQL];
  318. if (!statement) {
  319. [self logErrorWithSQL:SQL finalizeStatement:nil returnValue:NO];
  320. return NO;
  321. }
  322. NSArray *columns = RemoteConfigMetadataTableColumnsInOrder();
  323. int index = 0;
  324. for (NSString *columnName in columns) {
  325. if ([columnName isEqualToString:RCNKeyBundleIdentifier]) {
  326. NSString *value = columnNameToValue[columnName];
  327. if (![self bindStringToStatement:statement index:++index string:value]) {
  328. return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  329. }
  330. } else if ([columnName isEqualToString:RCNKeyFetchTime] ||
  331. [columnName isEqualToString:RCNKeyLastApplyTime] ||
  332. [columnName isEqualToString:RCNKeyLastSetDefaultsTime]) {
  333. double value = [columnNameToValue[columnName] doubleValue];
  334. if (sqlite3_bind_double(statement, ++index, value) != SQLITE_OK) {
  335. return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  336. }
  337. } else if ([columnName isEqualToString:RCNKeyLastFetchStatus] ||
  338. [columnName isEqualToString:RCNKeyLastFetchError]) {
  339. int value = [columnNameToValue[columnName] intValue];
  340. if (sqlite3_bind_int(statement, ++index, value) != SQLITE_OK) {
  341. return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  342. }
  343. } else {
  344. NSData *data = columnNameToValue[columnName];
  345. if (sqlite3_bind_blob(statement, ++index, data.bytes, (int)data.length, NULL) != SQLITE_OK) {
  346. return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  347. }
  348. }
  349. }
  350. if (sqlite3_step(statement) != SQLITE_DONE) {
  351. return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  352. }
  353. sqlite3_finalize(statement);
  354. return YES;
  355. }
  356. - (void)insertMainTableWithValues:(NSArray *)values
  357. fromSource:(RCNDBSource)source
  358. completionHandler:(RCNDBCompletion)handler {
  359. __weak RCNConfigDBManager *weakSelf = self;
  360. dispatch_async(_databaseOperationQueue, ^{
  361. BOOL success = [weakSelf insertMainTableWithValues:values fromSource:source];
  362. if (handler) {
  363. dispatch_async(dispatch_get_main_queue(), ^{
  364. handler(success, nil);
  365. });
  366. }
  367. });
  368. }
  369. - (BOOL)insertMainTableWithValues:(NSArray *)values fromSource:(RCNDBSource)source {
  370. RCN_MUST_NOT_BE_MAIN_THREAD();
  371. if (values.count != 4) {
  372. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000013",
  373. @"Failed to insert config record. Wrong number of give parameters, current "
  374. @"number is %ld, correct number is 4.",
  375. (long)values.count);
  376. return NO;
  377. }
  378. const char *SQL = "INSERT INTO " RCNTableNameMain
  379. " (bundle_identifier, namespace, key, value) values (?, ?, ?, ?)";
  380. if (source == RCNDBSourceDefault) {
  381. SQL = "INSERT INTO " RCNTableNameMainDefault
  382. " (bundle_identifier, namespace, key, value) values (?, ?, ?, ?)";
  383. } else if (source == RCNDBSourceActive) {
  384. SQL = "INSERT INTO " RCNTableNameMainActive
  385. " (bundle_identifier, namespace, key, value) values (?, ?, ?, ?)";
  386. }
  387. sqlite3_stmt *statement = [self prepareSQL:SQL];
  388. if (!statement) {
  389. return NO;
  390. }
  391. NSString *aString = values[0];
  392. if (![self bindStringToStatement:statement index:1 string:aString]) {
  393. return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  394. }
  395. aString = values[1];
  396. if (![self bindStringToStatement:statement index:2 string:aString]) {
  397. return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  398. }
  399. aString = values[2];
  400. if (![self bindStringToStatement:statement index:3 string:aString]) {
  401. return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  402. }
  403. NSData *blobData = values[3];
  404. if (sqlite3_bind_blob(statement, 4, blobData.bytes, (int)blobData.length, NULL) != SQLITE_OK) {
  405. return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  406. }
  407. if (sqlite3_step(statement) != SQLITE_DONE) {
  408. return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  409. }
  410. sqlite3_finalize(statement);
  411. return YES;
  412. }
  413. - (void)insertInternalMetadataTableWithValues:(NSArray *)values
  414. completionHandler:(RCNDBCompletion)handler {
  415. __weak RCNConfigDBManager *weakSelf = self;
  416. dispatch_async(_databaseOperationQueue, ^{
  417. BOOL success = [weakSelf insertInternalMetadataWithValues:values];
  418. if (handler) {
  419. dispatch_async(dispatch_get_main_queue(), ^{
  420. handler(success, nil);
  421. });
  422. }
  423. });
  424. }
  425. - (BOOL)insertInternalMetadataWithValues:(NSArray *)values {
  426. RCN_MUST_NOT_BE_MAIN_THREAD();
  427. if (values.count != 2) {
  428. return NO;
  429. }
  430. const char *SQL =
  431. "INSERT OR REPLACE INTO " RCNTableNameInternalMetadata " (key, value) values (?, ?)";
  432. sqlite3_stmt *statement = [self prepareSQL:SQL];
  433. if (!statement) {
  434. return NO;
  435. }
  436. NSString *aString = values[0];
  437. if (![self bindStringToStatement:statement index:1 string:aString]) {
  438. [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  439. return NO;
  440. }
  441. NSData *blobData = values[1];
  442. if (sqlite3_bind_blob(statement, 2, blobData.bytes, (int)blobData.length, NULL) != SQLITE_OK) {
  443. [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  444. return NO;
  445. }
  446. if (sqlite3_step(statement) != SQLITE_DONE) {
  447. [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  448. return NO;
  449. }
  450. sqlite3_finalize(statement);
  451. return YES;
  452. }
  453. - (void)insertExperimentTableWithKey:(NSString *)key
  454. value:(NSData *)serializedValue
  455. completionHandler:(RCNDBCompletion)handler {
  456. dispatch_async(_databaseOperationQueue, ^{
  457. BOOL success = [self insertExperimentTableWithKey:key value:serializedValue];
  458. if (handler) {
  459. dispatch_async(dispatch_get_main_queue(), ^{
  460. handler(success, nil);
  461. });
  462. }
  463. });
  464. }
  465. - (BOOL)insertExperimentTableWithKey:(NSString *)key value:(NSData *)dataValue {
  466. if ([key isEqualToString:@RCNExperimentTableKeyMetadata]) {
  467. return [self updateExperimentMetadata:dataValue];
  468. }
  469. RCN_MUST_NOT_BE_MAIN_THREAD();
  470. const char *SQL = "INSERT INTO " RCNTableNameExperiment " (key, value) values (?, ?)";
  471. sqlite3_stmt *statement = [self prepareSQL:SQL];
  472. if (!statement) {
  473. return NO;
  474. }
  475. if (![self bindStringToStatement:statement index:1 string:key]) {
  476. return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  477. }
  478. if (sqlite3_bind_blob(statement, 2, dataValue.bytes, (int)dataValue.length, NULL) != SQLITE_OK) {
  479. return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  480. }
  481. if (sqlite3_step(statement) != SQLITE_DONE) {
  482. return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  483. }
  484. sqlite3_finalize(statement);
  485. return YES;
  486. }
  487. - (BOOL)updateExperimentMetadata:(NSData *)dataValue {
  488. RCN_MUST_NOT_BE_MAIN_THREAD();
  489. const char *SQL = "INSERT OR REPLACE INTO " RCNTableNameExperiment
  490. " (_id, key, value) values ((SELECT _id from " RCNTableNameExperiment
  491. " WHERE key = ?), ?, ?)";
  492. sqlite3_stmt *statement = [self prepareSQL:SQL];
  493. if (!statement) {
  494. return NO;
  495. }
  496. if (![self bindStringToStatement:statement index:1 string:@RCNExperimentTableKeyMetadata]) {
  497. return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  498. }
  499. if (![self bindStringToStatement:statement index:2 string:@RCNExperimentTableKeyMetadata]) {
  500. return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  501. }
  502. if (sqlite3_bind_blob(statement, 3, dataValue.bytes, (int)dataValue.length, NULL) != SQLITE_OK) {
  503. return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  504. }
  505. if (sqlite3_step(statement) != SQLITE_DONE) {
  506. return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  507. }
  508. sqlite3_finalize(statement);
  509. return YES;
  510. }
  511. #pragma mark - update
  512. - (void)updateMetadataWithOption:(RCNUpdateOption)option
  513. values:(NSArray *)values
  514. completionHandler:(RCNDBCompletion)handler {
  515. dispatch_async(_databaseOperationQueue, ^{
  516. BOOL success = [self updateMetadataTableWithOption:option andValues:values];
  517. if (handler) {
  518. dispatch_async(dispatch_get_main_queue(), ^{
  519. handler(success, nil);
  520. });
  521. }
  522. });
  523. }
  524. - (BOOL)updateMetadataTableWithOption:(RCNUpdateOption)option andValues:(NSArray *)values {
  525. RCN_MUST_NOT_BE_MAIN_THREAD();
  526. static const char *SQL =
  527. "UPDATE " RCNTableNameMetadata " (last_fetch_status, last_fetch_error, last_apply_time, "
  528. "last_set_defaults_time) values (?, ?, ?, ?)";
  529. if (option == RCNUpdateOptionFetchStatus) {
  530. SQL = "UPDATE " RCNTableNameMetadata " SET last_fetch_status = ?, last_fetch_error = ?";
  531. } else if (option == RCNUpdateOptionApplyTime) {
  532. SQL = "UPDATE " RCNTableNameMetadata " SET last_apply_time = ?";
  533. } else if (option == RCNUpdateOptionDefaultTime) {
  534. SQL = "UPDATE " RCNTableNameMetadata " SET last_set_defaults_time = ?";
  535. } else {
  536. return NO;
  537. }
  538. sqlite3_stmt *statement = [self prepareSQL:SQL];
  539. if (!statement) {
  540. return NO;
  541. }
  542. int index = 0;
  543. if ((option == RCNUpdateOptionApplyTime || option == RCNUpdateOptionDefaultTime) &&
  544. values.count == 1) {
  545. double value = [values[0] doubleValue];
  546. if (sqlite3_bind_double(statement, ++index, value) != SQLITE_OK) {
  547. return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  548. }
  549. } else if (option == RCNUpdateOptionFetchStatus && values.count == 2) {
  550. int value = [values[0] intValue];
  551. if (sqlite3_bind_int(statement, ++index, value) != SQLITE_OK) {
  552. return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  553. }
  554. value = [values[1] intValue];
  555. if (sqlite3_bind_int(statement, ++index, value) != SQLITE_OK) {
  556. return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  557. }
  558. }
  559. if (sqlite3_step(statement) != SQLITE_DONE) {
  560. return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  561. }
  562. sqlite3_finalize(statement);
  563. return YES;
  564. }
  565. #pragma mark - read from DB
  566. - (NSDictionary *)loadMetadataWithBundleIdentifier:(NSString *)bundleIdentifier {
  567. __block NSDictionary *metadataTableResult;
  568. __weak RCNConfigDBManager *weakSelf = self;
  569. dispatch_sync(_databaseOperationQueue, ^{
  570. metadataTableResult = [weakSelf loadMetadataTableWithBundleIdentifier:bundleIdentifier];
  571. });
  572. if (metadataTableResult) {
  573. return metadataTableResult;
  574. }
  575. return [[NSDictionary alloc] init];
  576. }
  577. - (NSMutableDictionary *)loadMetadataTableWithBundleIdentifier:(NSString *)bundleIdentifier {
  578. NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
  579. const char *SQL =
  580. "SELECT bundle_identifier, fetch_time, digest_per_ns, device_context, app_context, "
  581. "success_fetch_time, failure_fetch_time , last_fetch_status, "
  582. "last_fetch_error, last_apply_time, last_set_defaults_time FROM " RCNTableNameMetadata
  583. " WHERE bundle_identifier = ?";
  584. sqlite3_stmt *statement = [self prepareSQL:SQL];
  585. if (!statement) {
  586. return nil;
  587. }
  588. NSArray *params = @[ bundleIdentifier ];
  589. [self bindStringsToStatement:statement stringArray:params];
  590. while (sqlite3_step(statement) == SQLITE_ROW) {
  591. NSString *dbBundleIdentifier =
  592. [[NSString alloc] initWithUTF8String:(char *)sqlite3_column_text(statement, 0)];
  593. if (dbBundleIdentifier && ![dbBundleIdentifier isEqualToString:bundleIdentifier]) {
  594. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000014",
  595. @"Load Metadata from table error: Wrong package name %@, should be %@.",
  596. dbBundleIdentifier, bundleIdentifier);
  597. return nil;
  598. }
  599. double fetchTime = sqlite3_column_double(statement, 1);
  600. NSData *digestPerNamespace = [NSData dataWithBytes:(char *)sqlite3_column_blob(statement, 2)
  601. length:sqlite3_column_bytes(statement, 2)];
  602. NSData *deviceContext = [NSData dataWithBytes:(char *)sqlite3_column_blob(statement, 3)
  603. length:sqlite3_column_bytes(statement, 3)];
  604. NSData *appContext = [NSData dataWithBytes:(char *)sqlite3_column_blob(statement, 4)
  605. length:sqlite3_column_bytes(statement, 4)];
  606. NSData *successTimeDigest = [NSData dataWithBytes:(char *)sqlite3_column_blob(statement, 5)
  607. length:sqlite3_column_bytes(statement, 5)];
  608. NSData *failureTimeDigest = [NSData dataWithBytes:(char *)sqlite3_column_blob(statement, 6)
  609. length:sqlite3_column_bytes(statement, 6)];
  610. int lastFetchStatus = sqlite3_column_int(statement, 7);
  611. int lastFetchFailReason = sqlite3_column_int(statement, 8);
  612. double lastApplyTimestamp = sqlite3_column_double(statement, 9);
  613. double lastSetDefaultsTimestamp = sqlite3_column_double(statement, 10);
  614. NSError *error;
  615. NSMutableDictionary *deviceContextDict = nil;
  616. if (deviceContext) {
  617. deviceContextDict = [NSJSONSerialization JSONObjectWithData:deviceContext
  618. options:NSJSONReadingMutableContainers
  619. error:&error];
  620. }
  621. NSMutableDictionary *appContextDict = nil;
  622. if (appContext) {
  623. appContextDict = [NSJSONSerialization JSONObjectWithData:appContext
  624. options:NSJSONReadingMutableContainers
  625. error:&error];
  626. }
  627. NSMutableDictionary<NSString *, id> *digestPerNamespaceDictionary = nil;
  628. if (digestPerNamespace) {
  629. digestPerNamespaceDictionary =
  630. [NSJSONSerialization JSONObjectWithData:digestPerNamespace
  631. options:NSJSONReadingMutableContainers
  632. error:&error];
  633. }
  634. NSMutableArray *successTimes = nil;
  635. if (successTimeDigest) {
  636. successTimes = [NSJSONSerialization JSONObjectWithData:successTimeDigest
  637. options:NSJSONReadingMutableContainers
  638. error:&error];
  639. }
  640. NSMutableArray *failureTimes = nil;
  641. if (failureTimeDigest) {
  642. failureTimes = [NSJSONSerialization JSONObjectWithData:failureTimeDigest
  643. options:NSJSONReadingMutableContainers
  644. error:&error];
  645. }
  646. dict[RCNKeyBundleIdentifier] = bundleIdentifier;
  647. dict[RCNKeyFetchTime] = @(fetchTime);
  648. dict[RCNKeyDigestPerNamespace] = digestPerNamespaceDictionary;
  649. dict[RCNKeyDeviceContext] = deviceContextDict;
  650. dict[RCNKeyAppContext] = appContextDict;
  651. dict[RCNKeySuccessFetchTime] = successTimes;
  652. dict[RCNKeyFailureFetchTime] = failureTimes;
  653. dict[RCNKeyLastFetchStatus] = @(lastFetchStatus);
  654. dict[RCNKeyLastFetchError] = @(lastFetchFailReason);
  655. dict[RCNKeyLastApplyTime] = @(lastApplyTimestamp);
  656. dict[RCNKeyLastSetDefaultsTime] = @(lastSetDefaultsTimestamp);
  657. break;
  658. }
  659. sqlite3_finalize(statement);
  660. return dict;
  661. }
  662. - (void)loadExperimentWithCompletionHandler:(RCNDBCompletion)handler {
  663. __weak RCNConfigDBManager *weakSelf = self;
  664. dispatch_async(_databaseOperationQueue, ^{
  665. RCNConfigDBManager *strongSelf = weakSelf;
  666. if (!strongSelf) {
  667. return;
  668. }
  669. NSMutableArray *experimentPayloads =
  670. [strongSelf loadExperimentTableFromKey:@RCNExperimentTableKeyPayload];
  671. if (!experimentPayloads) {
  672. experimentPayloads = [[NSMutableArray alloc] init];
  673. }
  674. NSMutableDictionary *experimentMetadata;
  675. NSMutableArray *experiments =
  676. [strongSelf loadExperimentTableFromKey:@RCNExperimentTableKeyMetadata];
  677. // There should be only one entry for experiment metadata.
  678. if (experiments.count > 0) {
  679. NSError *error;
  680. experimentMetadata = [NSJSONSerialization JSONObjectWithData:experiments[0]
  681. options:NSJSONReadingMutableContainers
  682. error:&error];
  683. }
  684. if (!experimentMetadata) {
  685. experimentMetadata = [[NSMutableDictionary alloc] init];
  686. }
  687. if (handler) {
  688. dispatch_async(dispatch_get_main_queue(), ^{
  689. handler(
  690. 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