• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2022 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #ifndef NATIVE_RDB_SQLITE_CONNECTION_POOL_H
17 #define NATIVE_RDB_SQLITE_CONNECTION_POOL_H
18 
19 #include <condition_variable>
20 #include <mutex>
21 #include <vector>
22 #include <sstream>
23 #include <iostream>
24 #include <iterator>
25 #include <stack>
26 
27 #include "rdb_store_config.h"
28 #include "sqlite_config.h"
29 #include "sqlite_connection.h"
30 #include "base_transaction.h"
31 
32 namespace OHOS {
33 namespace NativeRdb {
34 
35 class SqliteConnectionPool {
36 public:
37     static SqliteConnectionPool *Create(const RdbStoreConfig &storeConfig, int &errCode);
38     ~SqliteConnectionPool();
39     SqliteConnection *AcquireConnection(bool isReadOnly);
40     void ReleaseConnection(SqliteConnection *connection);
41     int ChangeEncryptKey(const std::vector<uint8_t> &newKey);
42     int ReOpenAvailableReadConnections();
43     int ConfigLocale(const std::string localeStr);
44     int ChangeDbFileForRestore(const std::string newPath, const std::string backupPath,
45         const std::vector<uint8_t> &newKey);
46     std::stack<BaseTransaction> &getTransactionStack();
47 
48 private:
49     explicit SqliteConnectionPool(const RdbStoreConfig &storeConfig);
50     int Init();
51     void InitReadConnectionCount();
52     SqliteConnection *AcquireWriteConnection();
53     void ReleaseWriteConnection();
54     SqliteConnection *AcquireReadConnection();
55     void ReleaseReadConnection(SqliteConnection *connection);
56     void CloseAllConnections();
57     bool IsOverLength(const std::vector<uint8_t> &newKey);
58     int InnerReOpenReadConnections();
59 
60     SqliteConfig config;
61     SqliteConnection *writeConnection;
62     std::mutex writeMutex;
63     std::condition_variable writeCondition;
64     bool writeConnectionUsed;
65 
66     std::vector<SqliteConnection *> readConnections;
67     std::mutex readMutex;
68     std::mutex rdbMutex;
69     std::condition_variable readCondition;
70     int readConnectionCount;
71     int idleReadConnectionCount;
72     const static int LIMITATION = 1024;
73 
74     std::stack<BaseTransaction> transactionStack;
75 };
76 
77 } // namespace NativeRdb
78 } // namespace OHOS
79 #endif