/*
 * Copyright (c) 2025 Huawei Device, Inc. Ltd. and <马弓手>.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "SQLiteHarmonyDatabase.h"
#include "Application.h"
#include "bundle/native_interface_bundle.h"

void SQLiteHarmonyDatabase::open(std::string fileName)
{
    m_fileName = fileName;
    OH_NativeBundle_ApplicationInfo application = OH_NativeBundle_GetCurrentApplicationInfo();
    // 创建OH_Rdb_Config对象
    OH_Rdb_Config config;
    // 该路径为应用沙箱路径
    config.dataBaseDir = Application::g_databaseDir.c_str();
    // 数据库文件名
    config.storeName = fileName.c_str();
    // 应用包名
    config.bundleName = application.bundleName;
    // 应用模块名
    config.moduleName = application.bundleName;
    // 数据库文件安全等级
    config.securityLevel = OH_Rdb_SecurityLevel::S1;
    // 数据库是否加密
    config.isEncrypt = false;
    // config所占内存大小
    config.selfSize = sizeof(OH_Rdb_Config);
    // 数据库文件存放的安全区域
    config.area = RDB_SECURITY_AREA_EL1;

    int errCode = 0;
    // 获取获取OH_Rdb_Store实例
    m_store = OH_Rdb_GetOrOpen(&config, &errCode);
}

void SQLiteHarmonyDatabase::closeDatabaseNow()
{
    OH_Rdb_CloseStore(m_store);
}

void SQLiteHarmonyDatabase::bugWorkaround()
{
    closeDatabaseNow();
    open(m_fileName);
}