Debian Codegraph @

src/main/org/h2/mvstore/db/Store.java

raw
1 /*
2 * Copyright 2004-2023 H2 Group. Multiple-Licensed under the MPL 2.0,
3 * and the EPL 1.0 (https://h2database.com/html/license.html).
4 * Initial Developer: H2 Group
5 */
6 package org.h2.mvstore.db;
7
8 import java.util.ArrayList;
9 import java.util.BitSet;
10 import java.util.HashMap;
11 import java.util.List;
12 import java.util.Map;
13 import java.util.concurrent.ConcurrentHashMap;
14
15 import org.h2.api.ErrorCode;
16 import org.h2.command.ddl.CreateTableData;
17 import org.h2.engine.Constants;
18 import org.h2.engine.Database;
19 import org.h2.engine.SessionLocal;
20 import org.h2.message.DbException;
21 import org.h2.mvstore.DataUtils;
22 import org.h2.mvstore.FileStore;
23 import org.h2.mvstore.MVStore;
24 import org.h2.mvstore.MVStoreException;
25 import org.h2.mvstore.MVStoreTool;
26 import org.h2.mvstore.tx.Transaction;
27 import org.h2.mvstore.tx.TransactionStore;
28 import org.h2.mvstore.type.MetaType;
29 import org.h2.store.InDoubtTransaction;
30 import org.h2.store.fs.FileUtils;
31 import org.h2.util.HasSQL;
32 import org.h2.util.StringUtils;
33 import org.h2.util.Utils;
34 import org.h2.value.TypeInfo;
35 import org.h2.value.Typed;
36 import org.h2.value.Value;
37
38 /**
39 * A store with open tables.
40 */
41 public final class Store {
42
43 /**
44 * Convert password from byte[] to char[].
45 *
46 * @param key password as byte[]
47 * @return password as char[].
48 */
49 static char[] decodePassword(byte[] key) {
50 char[] password = new char[key.length / 2];
51 for (int i = 0; i < password.length; i++) {
52 password[i] = (char) (((key[i + i] & 255) << 16) | (key[i + i + 1] & 255));
53 }
54 return password;
55 }
56
57 /**
58 * The map of open tables.
59 * Key: the map name, value: the table.
60 */
61 private final ConcurrentHashMap<String, MVTable> tableMap = new ConcurrentHashMap<>();
62
63 /**
64 * The store.
65 */
66 private final MVStore mvStore;
67
68 /**
69 * The transaction store.
70 */
71 private final TransactionStore transactionStore;
72
73 private long statisticsStart;
74
75 private int temporaryMapId;
76
77 private final boolean encrypted;
78
79 private final String fileName;
80
81 /**
82 * Creates the store.
83 *
84 * @param db the database
85 * @param key for file encryption
86 */
87 public Store(Database db, byte[] key) {
88 String dbPath = db.getDatabasePath();
89 MVStore.Builder builder = new MVStore.Builder();
90 boolean encrypted = false;
91 if (dbPath != null) {
92 String fileName = dbPath + Constants.SUFFIX_MV_FILE;
93 this.fileName = fileName;
94 MVStoreTool.compactCleanUp(fileName);
95 builder.fileName(fileName);
96 builder.pageSplitSize(db.getPageSize());
97 if (db.isReadOnly()) {
98 builder.readOnly();
99 } else {
100 // possibly create the directory
101 boolean exists = FileUtils.exists(fileName);
102 if (exists && !FileUtils.canWrite(fileName)) {
103 // read only
104 } else {
105 String dir = FileUtils.getParent(fileName);
106 FileUtils.createDirectories(dir);
107 }
108 int autoCompactFillRate = db.getSettings().autoCompactFillRate;
109 if (autoCompactFillRate <= 100) {
110 builder.autoCompactFillRate(autoCompactFillRate);
111 }
112 }
113 if (key != null) {
114 encrypted = true;
115 builder.encryptionKey(decodePassword(key));
116 }
117 if (db.getSettings().compressData) {
118 builder.compress();
119 // use a larger page split size to improve the compression ratio
120 builder.pageSplitSize(64 * 1024);
121 }
122 builder.backgroundExceptionHandler((t, e) -> db.setBackgroundException(DbException.convert(e)));
123 // always start without background thread first, and if necessary,
124 // it will be set up later, after db has been fully started,
125 // otherwise background thread would compete for store lock
126 // with maps opening procedure
127 builder.autoCommitDisabled();
128 } else {
129 fileName = null;
130 }
131 this.encrypted = encrypted;
132 try {
133 this.mvStore = builder.open();
134 if (!db.getSettings().reuseSpace) {
135 mvStore.setReuseSpace(false);
136 }
137 mvStore.setVersionsToKeep(0);
138 this.transactionStore = new TransactionStore(mvStore,
139 new MetaType<>(db, mvStore.backgroundExceptionHandler), new ValueDataType(db, null),
140 db.getLockTimeout());
141 } catch (MVStoreException e) {
142 throw convertMVStoreException(e);
143 }
144 }
145
146 /**
147 * Convert a MVStoreException to the similar exception used
148 * for the table/sql layers.
149 *
150 * @param e the illegal state exception
151 * @return the database exception
152 */
153 DbException convertMVStoreException(MVStoreException e) {
154 switch (e.getErrorCode()) {
155 case DataUtils.ERROR_CLOSED:
156 throw DbException.get(ErrorCode.DATABASE_IS_CLOSED, e, fileName);
157 case DataUtils.ERROR_UNSUPPORTED_FORMAT:
158 throw DbException.get(ErrorCode.FILE_VERSION_ERROR_1, e, fileName);
159 case DataUtils.ERROR_FILE_CORRUPT:
160 if (encrypted) {
161 throw DbException.get(ErrorCode.FILE_ENCRYPTION_ERROR_1, e, fileName);
162 }
163 throw DbException.get(ErrorCode.FILE_CORRUPTED_1, e, fileName);
164 case DataUtils.ERROR_FILE_LOCKED:
165 throw DbException.get(ErrorCode.DATABASE_ALREADY_OPEN_1, e, fileName);
166 case DataUtils.ERROR_READING_FAILED:
167 case DataUtils.ERROR_WRITING_FAILED:
168 throw DbException.get(ErrorCode.IO_EXCEPTION_1, e, fileName);
169 default:
170 throw DbException.get(ErrorCode.GENERAL_ERROR_1, e, e.getMessage());
171 }
172 }
173
174 /**
175 * Gets a SQL exception meaning the type of expression is invalid or unknown.
176 *
177 * @param param the name of the parameter
178 * @param e the expression
179 * @return the exception
180 */
181 public static DbException getInvalidExpressionTypeException(String param, Typed e) {
182 TypeInfo type = e.getType();
183 if (type.getValueType() == Value.UNKNOWN) {
184 return DbException.get(ErrorCode.UNKNOWN_DATA_TYPE_1,
185 (e instanceof HasSQL ? (HasSQL) e : type).getTraceSQL());
186 }
187 return DbException.get(ErrorCode.INVALID_VALUE_2, type.getTraceSQL(), param);
188 }
189
190 public MVStore getMvStore() {
191 return mvStore;
192 }
193
194 public TransactionStore getTransactionStore() {
195 return transactionStore;
196 }
197
198 /**
199 * Get MVTable by table name.
200 *
201 * @param tableName table name
202 * @return MVTable
203 */
204 public MVTable getTable(String tableName) {
205 return tableMap.get(tableName);
206 }
207
208 /**
209 * Create a table.
210 *
211 * @param data CreateTableData
212 * @return table created
213 */
214 public MVTable createTable(CreateTableData data) {
215 try {
216 MVTable table = new MVTable(data, this);
217 tableMap.put(table.getMapName(), table);
218 return table;
219 } catch (MVStoreException e) {
220 throw convertMVStoreException(e);
221 }
222 }
223
224 /**
225 * Remove a table.
226 *
227 * @param table the table
228 */
229 public void removeTable(MVTable table) {
230 try {
231 tableMap.remove(table.getMapName());
232 } catch (MVStoreException e) {
233 throw convertMVStoreException(e);
234 }
235 }
236
237 /**
238 * Store all pending changes.
239 */
240 public void flush() {
241 if (mvStore.isPersistent() && !mvStore.isReadOnly()) {
242 mvStore.commit();
243 }
244 }
245
246 /**
247 * Close the store, without persisting changes.
248 */
249 public void closeImmediately() {
250 mvStore.closeImmediately();
251 }
252
253 /**
254 * Remove all temporary maps.
255 *
256 * @param objectIds the ids of the objects to keep
257 */
258 public void removeTemporaryMaps(BitSet objectIds) {
259 for (String mapName : mvStore.getMapNames()) {
260 if (mapName.startsWith("temp.")) {
261 mvStore.removeMap(mapName);
262 } else if (mapName.startsWith("table.") || mapName.startsWith("index.")) {
263 int id = StringUtils.parseUInt31(mapName, mapName.indexOf('.') + 1, mapName.length());
264 if (!objectIds.get(id)) {
265 mvStore.removeMap(mapName);
266 }
267 }
268 }
269 }
270
271 /**
272 * Get the name of the next available temporary map.
273 *
274 * @return the map name
275 */
276 public synchronized String nextTemporaryMapName() {
277 return "temp." + temporaryMapId++;
278 }
279
280 /**
281 * Prepare a transaction.
282 *
283 * @param session the session
284 * @param transactionName the transaction name (may be null)
285 */
286 public void prepareCommit(SessionLocal session, String transactionName) {
287 Transaction t = session.getTransaction();
288 t.setName(transactionName);
289 t.prepare();
290 mvStore.commit();
291 }
292
293 public ArrayList<InDoubtTransaction> getInDoubtTransactions() {
294 List<Transaction> list = transactionStore.getOpenTransactions();
295 ArrayList<InDoubtTransaction> result = Utils.newSmallArrayList();
296 for (Transaction t : list) {
297 if (t.getStatus() == Transaction.STATUS_PREPARED) {
298 result.add(new MVInDoubtTransaction(mvStore, t));
299 }
300 }
301 return result;
302 }
303
304 /**
305 * Set the maximum memory to be used by the cache.
306 *
307 * @param kb the maximum size in KB
308 */
309 public void setCacheSize(int kb) {
310 mvStore.setCacheSize(kb);
311 }
312
313 /**
314 * Force the changes to disk.
315 */
316 public void sync() {
317 flush();
318 mvStore.sync();
319 }
320
321 /**
322 * Compact the database file, that is, compact blocks that have a low
323 * fill rate, and move chunks next to each other. This will typically
324 * shrink the database file. Changes are flushed to the file, and old
325 * chunks are overwritten.
326 *
327 * @param maxCompactTime the maximum time in milliseconds to compact
328 */
329 @SuppressWarnings("unused")
330 public void compactFile(int maxCompactTime) {
331 mvStore.compactFile(maxCompactTime);
332 }
333
334 /**
335 * Close the store. Pending changes are persisted.
336 *
337 * @param allowedCompactionTime time (in milliseconds) allotted for store
338 * housekeeping activity, 0 means none,
339 * -1 means unlimited time (i.e.full compaction)
340 */
341 public void close(int allowedCompactionTime) {
342 try {
343 FileStore<?> fileStore = mvStore.getFileStore();
344 if (!mvStore.isClosed() && fileStore != null) {
345 boolean compactFully = allowedCompactionTime == -1;
346 if (fileStore.isReadOnly()) {
347 compactFully = false;
348 } else {
349 transactionStore.close();
350 }
351 if (compactFully) {
352 allowedCompactionTime = 0;
353 }
354
355 String fileName = null;
356 FileStore<?> targetFileStore = null;
357 if (compactFully) {
358 fileName = fileStore.getFileName();
359 String tempName = fileName + Constants.SUFFIX_MV_STORE_TEMP_FILE;
360 FileUtils.delete(tempName);
361 targetFileStore = fileStore.open(tempName, false);
362 }
363
364 mvStore.close(allowedCompactionTime);
365
366 if (compactFully && FileUtils.exists(fileName)) {
367 // the file could have been deleted concurrently,
368 // so only compact if the file still exists
369 compact(fileName, targetFileStore);
370 }
371 }
372 } catch (MVStoreException e) {
373 mvStore.closeImmediately();
374 throw DbException.get(ErrorCode.IO_EXCEPTION_1, e, "Closing");
375 }
376 }
377
378
379 private static void compact(String sourceFilename, FileStore<?> targetFileStore) {
380 MVStore.Builder targetBuilder = new MVStore.Builder().compress().adoptFileStore(targetFileStore);
381 try (MVStore targetMVStore = targetBuilder.open()) {
382 FileStore<?> sourceFileStore = targetFileStore.open(sourceFilename, true);
383 MVStore.Builder sourceBuilder = new MVStore.Builder();
384 sourceBuilder.readOnly().adoptFileStore(sourceFileStore);
385 try (MVStore sourceMVStore = sourceBuilder.open()) {
386 MVStoreTool.compact(sourceMVStore, targetMVStore);
387 }
388 }
389 MVStoreTool.moveAtomicReplace(targetFileStore.getFileName(), sourceFilename);
390 }
391
392 /**
393 * Start collecting statistics.
394 */
395 public void statisticsStart() {
396 FileStore<?> fs = mvStore.getFileStore();
397 statisticsStart = fs == null ? 0 : fs.getReadCount();
398 }
399
400 /**
401 * Stop collecting statistics.
402 *
403 * @return the statistics
404 */
405 public Map<String, Integer> statisticsEnd() {
406 HashMap<String, Integer> map = new HashMap<>();
407 FileStore<?> fs = mvStore.getFileStore();
408 int reads = fs == null ? 0 : (int) (fs.getReadCount() - statisticsStart);
409 map.put("reads", reads);
410 return map;
411 }
412
413 }