| 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.tools; |
| 7 |
|
| 8 |
import java.io.BufferedReader; |
| 9 |
import java.io.ByteArrayInputStream; |
| 10 |
import java.io.IOException; |
| 11 |
import java.io.InputStream; |
| 12 |
import java.io.InputStreamReader; |
| 13 |
import java.io.PrintWriter; |
| 14 |
import java.io.Reader; |
| 15 |
import java.io.SequenceInputStream; |
| 16 |
import java.nio.charset.StandardCharsets; |
| 17 |
import java.sql.Connection; |
| 18 |
import java.sql.PreparedStatement; |
| 19 |
import java.sql.ResultSet; |
| 20 |
import java.sql.SQLException; |
| 21 |
import java.util.ArrayList; |
| 22 |
import java.util.Collections; |
| 23 |
import java.util.Enumeration; |
| 24 |
import java.util.HashMap; |
| 25 |
import java.util.HashSet; |
| 26 |
import java.util.Iterator; |
| 27 |
import java.util.Map; |
| 28 |
import java.util.Map.Entry; |
| 29 |
import org.h2.engine.Constants; |
| 30 |
import org.h2.engine.DbObject; |
| 31 |
import org.h2.engine.MetaRecord; |
| 32 |
import org.h2.message.DbException; |
| 33 |
import org.h2.mvstore.MVMap; |
| 34 |
import org.h2.mvstore.MVStore; |
| 35 |
import org.h2.mvstore.MVStoreTool; |
| 36 |
import org.h2.mvstore.StreamStore; |
| 37 |
import org.h2.mvstore.db.LobStorageMap; |
| 38 |
import org.h2.mvstore.db.ValueDataType; |
| 39 |
import org.h2.mvstore.tx.TransactionMap; |
| 40 |
import org.h2.mvstore.tx.TransactionStore; |
| 41 |
import org.h2.mvstore.type.DataType; |
| 42 |
import org.h2.mvstore.type.MetaType; |
| 43 |
import org.h2.mvstore.type.StringDataType; |
| 44 |
import org.h2.result.Row; |
| 45 |
import org.h2.store.DataHandler; |
| 46 |
import org.h2.store.FileLister; |
| 47 |
import org.h2.store.FileStore; |
| 48 |
import org.h2.store.LobStorageFrontend; |
| 49 |
import org.h2.store.LobStorageInterface; |
| 50 |
import org.h2.store.fs.FileUtils; |
| 51 |
import org.h2.util.HasSQL; |
| 52 |
import org.h2.util.IOUtils; |
| 53 |
import org.h2.util.SmallLRUCache; |
| 54 |
import org.h2.util.StringUtils; |
| 55 |
import org.h2.util.TempFileDeleter; |
| 56 |
import org.h2.util.Tool; |
| 57 |
import org.h2.value.CompareMode; |
| 58 |
import org.h2.value.Value; |
| 59 |
import org.h2.value.ValueCollectionBase; |
| 60 |
import org.h2.value.ValueLob; |
| 61 |
import org.h2.value.lob.LobData; |
| 62 |
import org.h2.value.lob.LobDataDatabase; |
| 63 |
|
| 64 |
/** |
| 65 |
* Helps recovering a corrupted database. |
| 66 |
*/ |
| 67 |
public class Recover extends Tool implements DataHandler { |
| 68 |
|
| 69 |
private String databaseName; |
| 70 |
private int storageId; |
| 71 |
private String storageName; |
| 72 |
private int recordLength; |
| 73 |
private int valueId; |
| 74 |
private boolean trace; |
| 75 |
private ArrayList<MetaRecord> schema; |
| 76 |
private HashSet<Integer> objectIdSet; |
| 77 |
private HashMap<Integer, String> tableMap; |
| 78 |
private HashMap<String, String> columnTypeMap; |
| 79 |
private boolean lobMaps; |
| 80 |
|
| 81 |
/** |
| 82 |
* Options are case sensitive. |
| 83 |
* <table> |
| 84 |
* <caption>Supported options</caption> |
| 85 |
* <tr><td>[-help] or [-?]</td> |
| 86 |
* <td>Print the list of options</td></tr> |
| 87 |
* <tr><td>[-dir <dir>]</td> |
| 88 |
* <td>The directory (default: .)</td></tr> |
| 89 |
* <tr><td>[-db <database>]</td> |
| 90 |
* <td>The database name (all databases if not set)</td></tr> |
| 91 |
* <tr><td>[-trace]</td> |
| 92 |
* <td>Print additional trace information</td></tr> |
| 93 |
* <tr><td>[-transactionLog]</td> |
| 94 |
* <td>Print the transaction log</td></tr> |
| 95 |
* </table> |
| 96 |
* Encrypted databases need to be decrypted first. |
| 97 |
* |
| 98 |
* @param args the command line arguments |
| 99 |
* @throws SQLException on failure |
| 100 |
*/ |
| 101 |
public static void main(String... args) throws SQLException { |
| 102 |
new Recover().runTool(args); |
| 103 |
} |
| 104 |
|
| 105 |
/** |
| 106 |
* Dumps the contents of a database file to a human readable text file. This |
| 107 |
* text file can be used to recover most of the data. This tool does not |
| 108 |
* open the database and can be used even if the database files are |
| 109 |
* corrupted. A database can get corrupted if there is a bug in the database |
| 110 |
* engine or file system software, or if an application writes into the |
| 111 |
* database file that doesn't understand the file format, or if there is |
| 112 |
* a hardware problem. |
| 113 |
* |
| 114 |
* @param args the command line arguments |
| 115 |
* @throws SQLException on failure |
| 116 |
*/ |
| 117 |
@Override |
| 118 |
public void runTool(String... args) throws SQLException { |
| 119 |
String dir = "."; |
| 120 |
String db = null; |
| 121 |
for (int i = 0; args != null && i < args.length; i++) { |
| 122 |
String arg = args[i]; |
| 123 |
if ("-dir".equals(arg)) { |
| 124 |
dir = args[++i]; |
| 125 |
} else if ("-db".equals(arg)) { |
| 126 |
db = args[++i]; |
| 127 |
} else if ("-trace".equals(arg)) { |
| 128 |
trace = true; |
| 129 |
} else if (arg.equals("-help") || arg.equals("-?")) { |
| 130 |
showUsage(); |
| 131 |
return; |
| 132 |
} else { |
| 133 |
showUsageAndThrowUnsupportedOption(arg); |
| 134 |
} |
| 135 |
} |
| 136 |
process(dir, db); |
| 137 |
} |
| 138 |
|
| 139 |
/** |
| 140 |
* INTERNAL |
| 141 |
* @param conn to use |
| 142 |
* @param lobId id of the LOB stream |
| 143 |
* @param precision not used |
| 144 |
* @return InputStream to read LOB content from |
| 145 |
* @throws SQLException on failure |
| 146 |
*/ |
| 147 |
public static InputStream readBlobMap(Connection conn, long lobId, |
| 148 |
long precision) throws SQLException { |
| 149 |
final PreparedStatement prep = conn.prepareStatement( |
| 150 |
"SELECT DATA FROM INFORMATION_SCHEMA.LOB_BLOCKS " + |
| 151 |
"WHERE LOB_ID = ? AND SEQ = ? AND ? > 0"); |
| 152 |
prep.setLong(1, lobId); |
| 153 |
// precision is currently not really used, |
| 154 |
// it is just to improve readability of the script |
| 155 |
prep.setLong(3, precision); |
| 156 |
return new SequenceInputStream( |
| 157 |
new Enumeration<InputStream>() { |
| 158 |
|
| 159 |
private int seq; |
| 160 |
private byte[] data = fetch(); |
| 161 |
|
| 162 |
private byte[] fetch() { |
| 163 |
try { |
| 164 |
prep.setInt(2, seq++); |
| 165 |
ResultSet rs = prep.executeQuery(); |
| 166 |
if (rs.next()) { |
| 167 |
return rs.getBytes(1); |
| 168 |
} |
| 169 |
return null; |
| 170 |
} catch (SQLException e) { |
| 171 |
throw DbException.convert(e); |
| 172 |
} |
| 173 |
} |
| 174 |
|
| 175 |
@Override |
| 176 |
public boolean hasMoreElements() { |
| 177 |
return data != null; |
| 178 |
} |
| 179 |
|
| 180 |
@Override |
| 181 |
public InputStream nextElement() { |
| 182 |
ByteArrayInputStream in = new ByteArrayInputStream(data); |
| 183 |
data = fetch(); |
| 184 |
return in; |
| 185 |
} |
| 186 |
} |
| 187 |
); |
| 188 |
} |
| 189 |
|
| 190 |
/** |
| 191 |
* INTERNAL |
| 192 |
* @param conn to use |
| 193 |
* @param lobId id of the LOB stream |
| 194 |
* @param precision not used |
| 195 |
* @return Reader to read LOB content from |
| 196 |
* @throws SQLException on failure |
| 197 |
*/ |
| 198 |
public static Reader readClobMap(Connection conn, long lobId, long precision) |
| 199 |
throws Exception { |
| 200 |
InputStream in = readBlobMap(conn, lobId, precision); |
| 201 |
return new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8)); |
| 202 |
} |
| 203 |
|
| 204 |
private void trace(String message) { |
| 205 |
if (trace) { |
| 206 |
out.println(message); |
| 207 |
} |
| 208 |
} |
| 209 |
|
| 210 |
private void traceError(String message, Throwable t) { |
| 211 |
out.println(message + ": " + t.toString()); |
| 212 |
if (trace) { |
| 213 |
t.printStackTrace(out); |
| 214 |
} |
| 215 |
} |
| 216 |
|
| 217 |
/** |
| 218 |
* Dumps the contents of a database to a SQL script file. |
| 219 |
* |
| 220 |
* @param dir the directory |
| 221 |
* @param db the database name (null for all databases) |
| 222 |
* @throws SQLException on failure |
| 223 |
*/ |
| 224 |
public static void execute(String dir, String db) throws SQLException { |
| 225 |
try { |
| 226 |
new Recover().process(dir, db); |
| 227 |
} catch (DbException e) { |
| 228 |
throw DbException.toSQLException(e); |
| 229 |
} |
| 230 |
} |
| 231 |
|
| 232 |
private void process(String dir, String db) { |
| 233 |
ArrayList<String> list = FileLister.getDatabaseFiles(dir, db, true); |
| 234 |
if (list.isEmpty()) { |
| 235 |
printNoDatabaseFilesFound(dir, db); |
| 236 |
} |
| 237 |
for (String fileName : list) { |
| 238 |
if (fileName.endsWith(Constants.SUFFIX_MV_FILE)) { |
| 239 |
String f = fileName.substring(0, fileName.length() - |
| 240 |
Constants.SUFFIX_MV_FILE.length()); |
| 241 |
try (PrintWriter writer = getWriter(fileName, ".txt")) { |
| 242 |
MVStoreTool.dump(fileName, writer, true); |
| 243 |
MVStoreTool.info(fileName, writer); |
| 244 |
} |
| 245 |
try (PrintWriter writer = getWriter(f + ".h2.db", ".sql")) { |
| 246 |
dumpMVStoreFile(writer, fileName); |
| 247 |
} |
| 248 |
} |
| 249 |
} |
| 250 |
} |
| 251 |
|
| 252 |
private PrintWriter getWriter(String fileName, String suffix) { |
| 253 |
fileName = fileName.substring(0, fileName.length() - 3); |
| 254 |
String outputFile = fileName + suffix; |
| 255 |
trace("Created file: " + outputFile); |
| 256 |
try { |
| 257 |
return new PrintWriter(IOUtils.getBufferedWriter( |
| 258 |
FileUtils.newOutputStream(outputFile, false))); |
| 259 |
} catch (IOException e) { |
| 260 |
throw DbException.convertIOException(e, null); |
| 261 |
} |
| 262 |
} |
| 263 |
|
| 264 |
private void getSQL(StringBuilder builder, String column, Value v) { |
| 265 |
if (v instanceof ValueLob) { |
| 266 |
ValueLob lob = (ValueLob) v; |
| 267 |
LobData lobData = lob.getLobData(); |
| 268 |
if (lobData instanceof LobDataDatabase) { |
| 269 |
LobDataDatabase lobDataDatabase = (LobDataDatabase) lobData; |
| 270 |
int type = v.getValueType(); |
| 271 |
long id = lobDataDatabase.getLobId(); |
| 272 |
long precision; |
| 273 |
String columnType; |
| 274 |
if (type == Value.BLOB) { |
| 275 |
precision = lob.octetLength(); |
| 276 |
columnType = "BLOB"; |
| 277 |
builder.append("READ_BLOB"); |
| 278 |
} else { |
| 279 |
precision = lob.charLength(); |
| 280 |
columnType = "CLOB"; |
| 281 |
builder.append("READ_CLOB"); |
| 282 |
} |
| 283 |
if (lobMaps) { |
| 284 |
builder.append("_MAP"); |
| 285 |
} else { |
| 286 |
builder.append("_DB"); |
| 287 |
} |
| 288 |
columnTypeMap.put(column, columnType); |
| 289 |
builder.append('(').append(id).append(", ").append(precision).append(')'); |
| 290 |
return; |
| 291 |
} |
| 292 |
} |
| 293 |
v.getSQL(builder, HasSQL.NO_CASTS); |
| 294 |
} |
| 295 |
|
| 296 |
private void setDatabaseName(String name) { |
| 297 |
databaseName = name; |
| 298 |
} |
| 299 |
|
| 300 |
private void dumpMVStoreFile(PrintWriter writer, String fileName) { |
| 301 |
writer.println("-- MVStore"); |
| 302 |
String className = getClass().getName(); |
| 303 |
writer.println("CREATE ALIAS IF NOT EXISTS READ_BLOB_MAP FOR '" + className + ".readBlobMap';"); |
| 304 |
writer.println("CREATE ALIAS IF NOT EXISTS READ_CLOB_MAP FOR '" + className + ".readClobMap';"); |
| 305 |
resetSchema(); |
| 306 |
setDatabaseName(fileName.substring(0, fileName.length() - |
| 307 |
Constants.SUFFIX_MV_FILE.length())); |
| 308 |
try (MVStore mv = new MVStore.Builder(). |
| 309 |
fileName(fileName).recoveryMode().readOnly().open()) { |
| 310 |
dumpLobMaps(writer, mv); |
| 311 |
writer.println("-- Layout"); |
| 312 |
dumpLayout(writer, mv); |
| 313 |
writer.println("-- Meta"); |
| 314 |
dumpMeta(writer, mv); |
| 315 |
writer.println("-- Types"); |
| 316 |
dumpTypes(writer, mv); |
| 317 |
writer.println("-- Tables"); |
| 318 |
TransactionStore store = new TransactionStore(mv, new ValueDataType()); |
| 319 |
try { |
| 320 |
store.init(); |
| 321 |
} catch (Throwable e) { |
| 322 |
writeError(writer, e); |
| 323 |
} |
| 324 |
|
| 325 |
// extract the metadata so we can dump the settings |
| 326 |
for (String mapName : mv.getMapNames()) { |
| 327 |
if (!mapName.startsWith("table.")) { |
| 328 |
continue; |
| 329 |
} |
| 330 |
String tableId = mapName.substring("table.".length()); |
| 331 |
if (Integer.parseInt(tableId) == 0) { |
| 332 |
TransactionMap<Long, Row> dataMap = store.begin().openMap(mapName); |
| 333 |
Iterator<Long> dataIt = dataMap.keyIterator(null); |
| 334 |
while (dataIt.hasNext()) { |
| 335 |
Long rowId = dataIt.next(); |
| 336 |
Row row = dataMap.get(rowId); |
| 337 |
try { |
| 338 |
writeMetaRow(row); |
| 339 |
} catch (Throwable t) { |
| 340 |
writeError(writer, t); |
| 341 |
} |
| 342 |
} |
| 343 |
} |
| 344 |
} |
| 345 |
// Have to do these before the tables because settings like COLLATION may affect |
| 346 |
// some of them, and we can't change settings after we have created user tables |
| 347 |
writeSchemaSET(writer); |
| 348 |
writer.println("---- Table Data ----"); |
| 349 |
for (String mapName : mv.getMapNames()) { |
| 350 |
if (!mapName.startsWith("table.")) { |
| 351 |
continue; |
| 352 |
} |
| 353 |
String tableId = mapName.substring("table.".length()); |
| 354 |
if (Integer.parseInt(tableId) == 0) { |
| 355 |
continue; |
| 356 |
} |
| 357 |
TransactionMap<?,?> dataMap = store.begin().openMap(mapName); |
| 358 |
Iterator<?> dataIt = dataMap.keyIterator(null); |
| 359 |
boolean init = false; |
| 360 |
while (dataIt.hasNext()) { |
| 361 |
Object rowId = dataIt.next(); |
| 362 |
Object value = dataMap.get(rowId); |
| 363 |
Value[] values; |
| 364 |
if (value instanceof Row) { |
| 365 |
values = ((Row) value).getValueList(); |
| 366 |
recordLength = values.length; |
| 367 |
} else { |
| 368 |
values = ((ValueCollectionBase) value).getList(); |
| 369 |
recordLength = values.length - 1; |
| 370 |
} |
| 371 |
if (!init) { |
| 372 |
setStorage(Integer.parseInt(tableId)); |
| 373 |
// init the column types |
| 374 |
StringBuilder builder = new StringBuilder(); |
| 375 |
for (valueId = 0; valueId < recordLength; valueId++) { |
| 376 |
String columnName = storageName + "." + valueId; |
| 377 |
builder.setLength(0); |
| 378 |
getSQL(builder, columnName, values[valueId]); |
| 379 |
} |
| 380 |
createTemporaryTable(writer); |
| 381 |
init = true; |
| 382 |
} |
| 383 |
StringBuilder buff = new StringBuilder(); |
| 384 |
buff.append("INSERT INTO O_").append(tableId) |
| 385 |
.append(" VALUES("); |
| 386 |
for (valueId = 0; valueId < recordLength; valueId++) { |
| 387 |
if (valueId > 0) { |
| 388 |
buff.append(", "); |
| 389 |
} |
| 390 |
String columnName = storageName + "." + valueId; |
| 391 |
getSQL(buff, columnName, values[valueId]); |
| 392 |
} |
| 393 |
buff.append(");"); |
| 394 |
writer.println(buff.toString()); |
| 395 |
} |
| 396 |
} |
| 397 |
writeSchema(writer); |
| 398 |
writer.println("DROP ALIAS READ_BLOB_MAP;"); |
| 399 |
writer.println("DROP ALIAS READ_CLOB_MAP;"); |
| 400 |
writer.println("DROP TABLE IF EXISTS INFORMATION_SCHEMA.LOB_BLOCKS;"); |
| 401 |
} catch (Throwable e) { |
| 402 |
writeError(writer, e); |
| 403 |
} |
| 404 |
} |
| 405 |
|
| 406 |
private static void dumpLayout(PrintWriter writer, MVStore mv) { |
| 407 |
Map<String, String> layout = mv.getLayoutMap(); |
| 408 |
for (Entry<String, String> e : layout.entrySet()) { |
| 409 |
writer.println("-- " + e.getKey() + " = " + e.getValue()); |
| 410 |
} |
| 411 |
} |
| 412 |
|
| 413 |
private static void dumpMeta(PrintWriter writer, MVStore mv) { |
| 414 |
MVMap<String, String> meta = mv.getMetaMap(); |
| 415 |
for (Entry<String, String> e : meta.entrySet()) { |
| 416 |
writer.println("-- " + e.getKey() + " = " + e.getValue()); |
| 417 |
} |
| 418 |
} |
| 419 |
|
| 420 |
private static void dumpTypes(PrintWriter writer, MVStore mv) { |
| 421 |
MVMap.Builder<String, DataType<?>> builder = new MVMap.Builder<String, DataType<?>>() |
| 422 |
.keyType(StringDataType.INSTANCE) |
| 423 |
.valueType(new MetaType<>(null, null)); |
| 424 |
MVMap<String,DataType<?>> map = mv.openMap("_", builder); |
| 425 |
for (Entry<String,?> e : map.entrySet()) { |
| 426 |
writer.println("-- " + e.getKey() + " = " + e.getValue()); |
| 427 |
} |
| 428 |
} |
| 429 |
|
| 430 |
private void dumpLobMaps(PrintWriter writer, MVStore mv) { |
| 431 |
lobMaps = mv.hasMap("lobData"); |
| 432 |
if (!lobMaps) { |
| 433 |
return; |
| 434 |
} |
| 435 |
TransactionStore txStore = new TransactionStore(mv); |
| 436 |
MVMap<Long, byte[]> lobData = LobStorageMap.openLobDataMap(txStore); |
| 437 |
StreamStore streamStore = new StreamStore(lobData); |
| 438 |
MVMap<Long, LobStorageMap.BlobMeta> lobMap = LobStorageMap.openLobMap(txStore); |
| 439 |
writer.println("-- LOB"); |
| 440 |
writer.println("CREATE TABLE IF NOT EXISTS " + |
| 441 |
"INFORMATION_SCHEMA.LOB_BLOCKS(" + |
| 442 |
"LOB_ID BIGINT, SEQ INT, DATA VARBINARY, " + |
| 443 |
"PRIMARY KEY(LOB_ID, SEQ));"); |
| 444 |
boolean hasErrors = false; |
| 445 |
for (Entry<Long, LobStorageMap.BlobMeta> e : lobMap.entrySet()) { |
| 446 |
long lobId = e.getKey(); |
| 447 |
LobStorageMap.BlobMeta value = e.getValue(); |
| 448 |
byte[] streamStoreId = value.streamStoreId; |
| 449 |
InputStream in = streamStore.get(streamStoreId); |
| 450 |
int len = 8 * 1024; |
| 451 |
byte[] block = new byte[len]; |
| 452 |
try { |
| 453 |
for (int seq = 0;; seq++) { |
| 454 |
int l = IOUtils.readFully(in, block, block.length); |
| 455 |
if (l > 0) { |
| 456 |
writer.print("INSERT INTO INFORMATION_SCHEMA.LOB_BLOCKS " + |
| 457 |
"VALUES(" + lobId + ", " + seq + ", X'"); |
| 458 |
writer.print(StringUtils.convertBytesToHex(block, l)); |
| 459 |
writer.println("');"); |
| 460 |
} |
| 461 |
if (l != len) { |
| 462 |
break; |
| 463 |
} |
| 464 |
} |
| 465 |
} catch (IOException ex) { |
| 466 |
writeError(writer, ex); |
| 467 |
hasErrors = true; |
| 468 |
} |
| 469 |
} |
| 470 |
writer.println("-- lobMap.size: " + lobMap.sizeAsLong()); |
| 471 |
writer.println("-- lobData.size: " + lobData.sizeAsLong()); |
| 472 |
|
| 473 |
if (hasErrors) { |
| 474 |
writer.println("-- lobMap"); |
| 475 |
for (Long k : lobMap.keyList()) { |
| 476 |
LobStorageMap.BlobMeta value = lobMap.get(k); |
| 477 |
byte[] streamStoreId = value.streamStoreId; |
| 478 |
writer.println("-- " + k + " " + StreamStore.toString(streamStoreId)); |
| 479 |
} |
| 480 |
writer.println("-- lobData"); |
| 481 |
for (Long k : lobData.keyList()) { |
| 482 |
writer.println("-- " + k + " len " + lobData.get(k).length); |
| 483 |
} |
| 484 |
} |
| 485 |
} |
| 486 |
|
| 487 |
private String setStorage(int storageId) { |
| 488 |
this.storageId = storageId; |
| 489 |
this.storageName = "O_" + Integer.toString(storageId).replace('-', 'M'); |
| 490 |
return storageName; |
| 491 |
} |
| 492 |
|
| 493 |
private void writeMetaRow(Row r) { |
| 494 |
MetaRecord meta = new MetaRecord(r); |
| 495 |
int objectType = meta.getObjectType(); |
| 496 |
if (objectType == DbObject.INDEX && meta.getSQL().startsWith("CREATE PRIMARY KEY ")) { |
| 497 |
return; |
| 498 |
} |
| 499 |
schema.add(meta); |
| 500 |
if (objectType == DbObject.TABLE_OR_VIEW) { |
| 501 |
tableMap.put(meta.getId(), extractTableOrViewName(meta.getSQL())); |
| 502 |
} |
| 503 |
} |
| 504 |
|
| 505 |
private void resetSchema() { |
| 506 |
schema = new ArrayList<>(); |
| 507 |
objectIdSet = new HashSet<>(); |
| 508 |
tableMap = new HashMap<>(); |
| 509 |
columnTypeMap = new HashMap<>(); |
| 510 |
} |
| 511 |
|
| 512 |
private void writeSchemaSET(PrintWriter writer) { |
| 513 |
writer.println("---- Schema SET ----"); |
| 514 |
for (MetaRecord m : schema) { |
| 515 |
if (m.getObjectType() == DbObject.SETTING) { |
| 516 |
String sql = m.getSQL(); |
| 517 |
writer.println(sql + ";"); |
| 518 |
} |
| 519 |
} |
| 520 |
} |
| 521 |
|
| 522 |
private void writeSchema(PrintWriter writer) { |
| 523 |
writer.println("---- Schema ----"); |
| 524 |
Collections.sort(schema); |
| 525 |
for (MetaRecord m : schema) { |
| 526 |
if (m.getObjectType() != DbObject.SETTING |
| 527 |
&& !isSchemaObjectTypeDelayed(m)) { |
| 528 |
// create, but not referential integrity constraints and so on |
| 529 |
// because they could fail on duplicate keys |
| 530 |
String sql = m.getSQL(); |
| 531 |
writer.println(sql + ";"); |
| 532 |
} |
| 533 |
} |
| 534 |
// first, copy the lob storage (if there is any) |
| 535 |
// must occur before copying data, |
| 536 |
// otherwise the lob storage may be overwritten |
| 537 |
boolean deleteLobs = false; |
| 538 |
for (Map.Entry<Integer, String> entry : tableMap.entrySet()) { |
| 539 |
Integer objectId = entry.getKey(); |
| 540 |
String name = entry.getValue(); |
| 541 |
if (objectIdSet.contains(objectId)) { |
| 542 |
if (isLobTable(name)) { |
| 543 |
setStorage(objectId); |
| 544 |
writer.println("DELETE FROM " + name + ";"); |
| 545 |
writer.println("INSERT INTO " + name + " SELECT * FROM " + storageName + ";"); |
| 546 |
if (name.equals("INFORMATION_SCHEMA.LOBS") |
| 547 |
|| name.equalsIgnoreCase("\"INFORMATION_SCHEMA\".\"LOBS\"")) { |
| 548 |
writer.println("UPDATE " + name + " SET `TABLE` = " + |
| 549 |
LobStorageFrontend.TABLE_TEMP + ";"); |
| 550 |
deleteLobs = true; |
| 551 |
} |
| 552 |
} |
| 553 |
} |
| 554 |
} |
| 555 |
for (Map.Entry<Integer, String> entry : tableMap.entrySet()) { |
| 556 |
Integer objectId = entry.getKey(); |
| 557 |
String name = entry.getValue(); |
| 558 |
if (objectIdSet.contains(objectId)) { |
| 559 |
setStorage(objectId); |
| 560 |
if (isLobTable(name)) { |
| 561 |
continue; |
| 562 |
} |
| 563 |
writer.println("INSERT INTO " + name + " SELECT * FROM " + storageName + ";"); |
| 564 |
} |
| 565 |
} |
| 566 |
for (Integer objectId : objectIdSet) { |
| 567 |
setStorage(objectId); |
| 568 |
writer.println("DROP TABLE " + storageName + ";"); |
| 569 |
} |
| 570 |
if (deleteLobs) { |
| 571 |
writer.println("DELETE FROM INFORMATION_SCHEMA.LOBS WHERE `TABLE` = " + |
| 572 |
LobStorageFrontend.TABLE_TEMP + ";"); |
| 573 |
} |
| 574 |
ArrayList<String> referentialConstraints = new ArrayList<>(); |
| 575 |
for (MetaRecord m : schema) { |
| 576 |
if (isSchemaObjectTypeDelayed(m)) { |
| 577 |
String sql = m.getSQL(); |
| 578 |
// TODO parse SQL properly |
| 579 |
if (m.getObjectType() == DbObject.CONSTRAINT && sql.endsWith("NOCHECK") |
| 580 |
&& sql.contains(" FOREIGN KEY") && sql.contains("REFERENCES ")) { |
| 581 |
referentialConstraints.add(sql); |
| 582 |
} else { |
| 583 |
writer.println(sql + ';'); |
| 584 |
} |
| 585 |
} |
| 586 |
} |
| 587 |
for (String sql : referentialConstraints) { |
| 588 |
writer.println(sql + ';'); |
| 589 |
} |
| 590 |
} |
| 591 |
|
| 592 |
private static boolean isLobTable(String name) { |
| 593 |
return name.startsWith("INFORMATION_SCHEMA.LOB") || name.startsWith("\"INFORMATION_SCHEMA\".\"LOB") |
| 594 |
|| name.startsWith("\"information_schema\".\"lob"); |
| 595 |
} |
| 596 |
|
| 597 |
private static boolean isSchemaObjectTypeDelayed(MetaRecord m) { |
| 598 |
switch (m.getObjectType()) { |
| 599 |
case DbObject.INDEX: |
| 600 |
case DbObject.CONSTRAINT: |
| 601 |
case DbObject.TRIGGER: |
| 602 |
return true; |
| 603 |
} |
| 604 |
return false; |
| 605 |
} |
| 606 |
|
| 607 |
private void createTemporaryTable(PrintWriter writer) { |
| 608 |
if (!objectIdSet.contains(storageId)) { |
| 609 |
objectIdSet.add(storageId); |
| 610 |
writer.write("CREATE TABLE "); |
| 611 |
writer.write(storageName); |
| 612 |
writer.write('('); |
| 613 |
for (int i = 0; i < recordLength; i++) { |
| 614 |
if (i > 0) { |
| 615 |
writer.print(", "); |
| 616 |
} |
| 617 |
writer.write('C'); |
| 618 |
writer.print(i); |
| 619 |
writer.write(' '); |
| 620 |
String columnType = columnTypeMap.get(storageName + "." + i); |
| 621 |
writer.write(columnType == null ? "VARCHAR" : columnType); |
| 622 |
} |
| 623 |
writer.println(");"); |
| 624 |
writer.flush(); |
| 625 |
} |
| 626 |
} |
| 627 |
|
| 628 |
private static String extractTableOrViewName(String sql) { |
| 629 |
int indexTable = sql.indexOf(" TABLE "); |
| 630 |
int indexView = sql.indexOf(" VIEW "); |
| 631 |
if (indexTable > 0 && indexView > 0) { |
| 632 |
if (indexTable < indexView) { |
| 633 |
indexView = -1; |
| 634 |
} else { |
| 635 |
indexTable = -1; |
| 636 |
} |
| 637 |
} |
| 638 |
if (indexView > 0) { |
| 639 |
sql = sql.substring(indexView + " VIEW ".length()); |
| 640 |
} else if (indexTable > 0) { |
| 641 |
sql = sql.substring(indexTable + " TABLE ".length()); |
| 642 |
} else { |
| 643 |
return "UNKNOWN"; |
| 644 |
} |
| 645 |
if (sql.startsWith("IF NOT EXISTS ")) { |
| 646 |
sql = sql.substring("IF NOT EXISTS ".length()); |
| 647 |
} |
| 648 |
boolean ignore = false; |
| 649 |
// sql is modified in the loop |
| 650 |
for (int i = 0; i < sql.length(); i++) { |
| 651 |
char ch = sql.charAt(i); |
| 652 |
if (ch == '\"') { |
| 653 |
ignore = !ignore; |
| 654 |
} else if (!ignore && (ch <= ' ' || ch == '(')) { |
| 655 |
sql = sql.substring(0, i); |
| 656 |
return sql; |
| 657 |
} |
| 658 |
} |
| 659 |
return "UNKNOWN"; |
| 660 |
} |
| 661 |
|
| 662 |
|
| 663 |
private void writeError(PrintWriter writer, Throwable e) { |
| 664 |
if (writer != null) { |
| 665 |
writer.println("// error: " + e); |
| 666 |
} |
| 667 |
traceError("Error", e); |
| 668 |
} |
| 669 |
|
| 670 |
/** |
| 671 |
* INTERNAL |
| 672 |
*/ |
| 673 |
@Override |
| 674 |
public String getDatabasePath() { |
| 675 |
return databaseName; |
| 676 |
} |
| 677 |
|
| 678 |
/** |
| 679 |
* INTERNAL |
| 680 |
*/ |
| 681 |
@Override |
| 682 |
public FileStore openFile(String name, String mode, boolean mustExist) { |
| 683 |
return FileStore.open(this, name, "rw"); |
| 684 |
} |
| 685 |
|
| 686 |
/** |
| 687 |
* INTERNAL |
| 688 |
*/ |
| 689 |
@Override |
| 690 |
public void checkPowerOff() { |
| 691 |
// nothing to do |
| 692 |
} |
| 693 |
|
| 694 |
/** |
| 695 |
* INTERNAL |
| 696 |
*/ |
| 697 |
@Override |
| 698 |
public void checkWritingAllowed() { |
| 699 |
// nothing to do |
| 700 |
} |
| 701 |
|
| 702 |
/** |
| 703 |
* INTERNAL |
| 704 |
*/ |
| 705 |
@Override |
| 706 |
public int getMaxLengthInplaceLob() { |
| 707 |
throw DbException.getInternalError(); |
| 708 |
} |
| 709 |
|
| 710 |
/** |
| 711 |
* INTERNAL |
| 712 |
*/ |
| 713 |
@Override |
| 714 |
public Object getLobSyncObject() { |
| 715 |
return this; |
| 716 |
} |
| 717 |
|
| 718 |
/** |
| 719 |
* INTERNAL |
| 720 |
*/ |
| 721 |
@Override |
| 722 |
public SmallLRUCache<String, String[]> getLobFileListCache() { |
| 723 |
return null; |
| 724 |
} |
| 725 |
|
| 726 |
/** |
| 727 |
* INTERNAL |
| 728 |
*/ |
| 729 |
@Override |
| 730 |
public TempFileDeleter getTempFileDeleter() { |
| 731 |
return TempFileDeleter.getInstance(); |
| 732 |
} |
| 733 |
|
| 734 |
/** |
| 735 |
* INTERNAL |
| 736 |
*/ |
| 737 |
@Override |
| 738 |
public LobStorageInterface getLobStorage() { |
| 739 |
return null; |
| 740 |
} |
| 741 |
|
| 742 |
/** |
| 743 |
* INTERNAL |
| 744 |
*/ |
| 745 |
@Override |
| 746 |
public int readLob(long lobId, byte[] hmac, long offset, byte[] buff, int off, int length) { |
| 747 |
throw DbException.getInternalError(); |
| 748 |
} |
| 749 |
|
| 750 |
@Override |
| 751 |
public CompareMode getCompareMode() { |
| 752 |
return CompareMode.getInstance(null, 0); |
| 753 |
} |
| 754 |
} |