RCNConfigDBManager.m 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039
  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 = self;
  815. dispatch_async(_databaseOperationQueue, ^{
  816. RCNConfigDBManager *strongSelf = weakSelf;
  817. if (!strongSelf) {
  818. return;
  819. }
  820. NSArray *params = @[ bundleIdentifier, namespace_p ];
  821. const char *SQL =
  822. "DELETE FROM " RCNTableNameMain " WHERE bundle_identifier = ? and namespace = ?";
  823. if (source == RCNDBSourceDefault) {
  824. SQL = "DELETE FROM " RCNTableNameMainDefault " WHERE bundle_identifier = ? and namespace = ?";
  825. } else if (source == RCNDBSourceActive) {
  826. SQL = "DELETE FROM " RCNTableNameMainActive " WHERE bundle_identifier = ? and namespace = ?";
  827. }
  828. [strongSelf executeQuery:SQL withParams:params];
  829. });
  830. }
  831. - (void)deleteRecordWithBundleIdentifier:(NSString *)bundleIdentifier
  832. isInternalDB:(BOOL)isInternalDB {
  833. __weak RCNConfigDBManager *weakSelf = self;
  834. dispatch_async(_databaseOperationQueue, ^{
  835. RCNConfigDBManager *strongSelf = weakSelf;
  836. if (!strongSelf) {
  837. return;
  838. }
  839. const char *SQL = "DELETE FROM " RCNTableNameInternalMetadata " WHERE key LIKE ?";
  840. if (!isInternalDB) {
  841. SQL = "DELETE FROM " RCNTableNameMetadata " WHERE bundle_identifier = ?";
  842. }
  843. NSArray *params = @[ bundleIdentifier ];
  844. [strongSelf executeQuery:SQL withParams:params];
  845. });
  846. }
  847. - (void)deleteAllRecordsFromTableWithSource:(RCNDBSource)source {
  848. __weak RCNConfigDBManager *weakSelf = self;
  849. dispatch_async(_databaseOperationQueue, ^{
  850. RCNConfigDBManager *strongSelf = weakSelf;
  851. if (!strongSelf) {
  852. return;
  853. }
  854. const char *SQL = "DELETE FROM " RCNTableNameMain;
  855. if (source == RCNDBSourceDefault) {
  856. SQL = "DELETE FROM " RCNTableNameMainDefault;
  857. } else if (source == RCNDBSourceActive) {
  858. SQL = "DELETE FROM " RCNTableNameMainActive;
  859. }
  860. [strongSelf executeQuery:SQL];
  861. });
  862. }
  863. - (void)deleteExperimentTableForKey:(NSString *)key {
  864. __weak RCNConfigDBManager *weakSelf = self;
  865. dispatch_async(_databaseOperationQueue, ^{
  866. RCNConfigDBManager *strongSelf = weakSelf;
  867. if (!strongSelf) {
  868. return;
  869. }
  870. NSArray *params = @[ key ];
  871. const char *SQL = "DELETE FROM " RCNTableNameExperiment " WHERE key = ?";
  872. [strongSelf executeQuery:SQL withParams:params];
  873. });
  874. }
  875. #pragma mark - helper
  876. - (BOOL)executeQuery:(const char *)SQL withParams:(NSArray *)params {
  877. RCN_MUST_NOT_BE_MAIN_THREAD();
  878. sqlite3_stmt *statement = [self prepareSQL:SQL];
  879. if (!statement) {
  880. return NO;
  881. }
  882. [self bindStringsToStatement:statement stringArray:params];
  883. if (sqlite3_step(statement) != SQLITE_DONE) {
  884. return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  885. }
  886. sqlite3_finalize(statement);
  887. return YES;
  888. }
  889. /// Params only accept TEXT format string.
  890. - (BOOL)bindStringsToStatement:(sqlite3_stmt *)statement stringArray:(NSArray *)array {
  891. int index = 1;
  892. for (NSString *param in array) {
  893. if (![self bindStringToStatement:statement index:index string:param]) {
  894. return [self logErrorWithSQL:nil finalizeStatement:statement returnValue:NO];
  895. }
  896. index++;
  897. }
  898. return YES;
  899. }
  900. - (BOOL)bindStringToStatement:(sqlite3_stmt *)statement index:(int)index string:(NSString *)value {
  901. if (sqlite3_bind_text(statement, index, [value UTF8String], -1, SQLITE_TRANSIENT) != SQLITE_OK) {
  902. return [self logErrorWithSQL:nil finalizeStatement:statement returnValue:NO];
  903. }
  904. return YES;
  905. }
  906. - (sqlite3_stmt *)prepareSQL:(const char *)SQL {
  907. sqlite3_stmt *statement = nil;
  908. if (sqlite3_prepare_v2(_database, SQL, -1, &statement, NULL) != SQLITE_OK) {
  909. [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
  910. return nil;
  911. }
  912. return statement;
  913. }
  914. - (NSString *)errorMessage {
  915. return [NSString stringWithFormat:@"%s", sqlite3_errmsg(_database)];
  916. }
  917. - (int)errorCode {
  918. return sqlite3_errcode(_database);
  919. }
  920. - (void)logDatabaseError {
  921. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000015", @"Error message: %@. Error code: %d.",
  922. [self errorMessage], [self errorCode]);
  923. }
  924. - (BOOL)logErrorWithSQL:(const char *)SQL
  925. finalizeStatement:(sqlite3_stmt *)statement
  926. returnValue:(BOOL)returnValue {
  927. if (SQL) {
  928. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000016", @"Failed with SQL: %s.", SQL);
  929. }
  930. [self logDatabaseError];
  931. if (statement) {
  932. sqlite3_finalize(statement);
  933. }
  934. return returnValue;
  935. }
  936. @end