use of org.h2.tools.Backup in project h2database by h2database.
the class TestCrashAPI method getConnection.
private Connection getConnection(int seed, boolean delete) throws SQLException {
openCount++;
if (delete) {
deleteDb();
}
// can not use FILE_LOCK=NO, otherwise something could be written into
// the database in the finalize method
String add = ";MAX_QUERY_TIMEOUT=10000";
// int testing;
// if(openCount >= 32) {
// int test;
// Runtime.getRuntime().halt(0);
// System.exit(1);
// }
// System.out.println("now open " + openCount);
// add += ";TRACE_LEVEL_FILE=3";
// config.logMode = 2;
// }
String dbName = "crashApi" + seed;
String url = getURL(DIR + "/" + dbName, true) + add;
// int test;
// url += ";DB_CLOSE_ON_EXIT=FALSE";
// int test;
// url += ";TRACE_LEVEL_FILE=3";
Connection conn = null;
String fileName = "temp/backup/db-" + uniqueId++ + ".zip";
Backup.execute(fileName, getBaseDir() + "/" + DIR, dbName, true);
// close databases earlier
System.gc();
try {
conn = DriverManager.getConnection(url, "sa", getPassword(""));
// delete the backup if opening was successful
FileUtils.delete(fileName);
} catch (SQLException e) {
if (e.getErrorCode() == ErrorCode.WRONG_USER_OR_PASSWORD) {
// delete if the password changed
FileUtils.delete(fileName);
}
throw e;
}
int len = random.getInt(50);
int first = random.getInt(statements.size() - len);
int end = first + len;
Statement stat = conn.createStatement();
stat.execute("SET LOCK_TIMEOUT 10");
stat.execute("SET WRITE_DELAY 0");
if (random.nextBoolean()) {
if (random.nextBoolean()) {
double g = random.nextGaussian();
int size = (int) Math.abs(10000 * g * g);
stat.execute("SET CACHE_SIZE " + size);
} else {
stat.execute("SET CACHE_SIZE 0");
}
}
stat.execute("SCRIPT NOPASSWORDS NOSETTINGS");
for (int i = first; i < end && i < statements.size() && !stopped; i++) {
try {
stat.execute("SELECT * FROM TEST WHERE ID=1");
} catch (Throwable t) {
printIfBad(seed, -i, -1, t);
}
try {
stat.execute("SELECT * FROM TEST WHERE ID=1 OR ID=1");
} catch (Throwable t) {
printIfBad(seed, -i, -1, t);
}
String sql = statements.get(i);
try {
// if(openCount == 32) {
// int test;
// System.out.println("stop!");
// }
stat.execute(sql);
} catch (Throwable t) {
printIfBad(seed, -i, -1, t);
}
}
if (random.nextBoolean()) {
try {
conn.commit();
} catch (Throwable t) {
printIfBad(seed, 0, -1, t);
}
}
return conn;
}
use of org.h2.tools.Backup in project h2database by h2database.
the class WebApp method tools.
private String tools() {
try {
String toolName = (String) attributes.get("tool");
session.put("tool", toolName);
String args = (String) attributes.get("args");
String[] argList = StringUtils.arraySplit(args, ',', false);
Tool tool = null;
if ("Backup".equals(toolName)) {
tool = new Backup();
} else if ("Restore".equals(toolName)) {
tool = new Restore();
} else if ("Recover".equals(toolName)) {
tool = new Recover();
} else if ("DeleteDbFiles".equals(toolName)) {
tool = new DeleteDbFiles();
} else if ("ChangeFileEncryption".equals(toolName)) {
tool = new ChangeFileEncryption();
} else if ("Script".equals(toolName)) {
tool = new Script();
} else if ("RunScript".equals(toolName)) {
tool = new RunScript();
} else if ("ConvertTraceFile".equals(toolName)) {
tool = new ConvertTraceFile();
} else if ("CreateCluster".equals(toolName)) {
tool = new CreateCluster();
} else {
throw DbException.throwInternalError(toolName);
}
ByteArrayOutputStream outBuff = new ByteArrayOutputStream();
PrintStream out = new PrintStream(outBuff, false, "UTF-8");
tool.setOut(out);
try {
tool.runTool(argList);
out.flush();
String o = new String(outBuff.toByteArray(), StandardCharsets.UTF_8);
String result = PageParser.escapeHtml(o);
session.put("toolResult", result);
} catch (Exception e) {
session.put("toolResult", getStackTrace(0, e, true));
}
} catch (Exception e) {
server.traceError(e);
}
return "tools.jsp";
}
use of org.h2.tools.Backup in project h2database by h2database.
the class Parser method readCondition.
private Expression readCondition() {
if (readIf("NOT")) {
return new ConditionNot(readCondition());
}
if (readIf("EXISTS")) {
read("(");
Query query = parseSelect();
// can not reduce expression because it might be a union except
// query with distinct
read(")");
return new ConditionExists(query);
}
if (readIf("INTERSECTS")) {
read("(");
Expression r1 = readConcat();
read(",");
Expression r2 = readConcat();
read(")");
return new Comparison(session, Comparison.SPATIAL_INTERSECTS, r1, r2);
}
Expression r = readConcat();
while (true) {
// special case: NOT NULL is not part of an expression (as in CREATE
// TABLE TEST(ID INT DEFAULT 0 NOT NULL))
int backup = parseIndex;
boolean not = false;
if (readIf("NOT")) {
not = true;
if (isToken("NULL")) {
// this really only works for NOT NULL!
parseIndex = backup;
currentToken = "NOT";
break;
}
}
if (readIf("LIKE")) {
Expression b = readConcat();
Expression esc = null;
if (readIf("ESCAPE")) {
esc = readConcat();
}
recompileAlways = true;
r = new CompareLike(database, r, b, esc, false);
} else if (readIf("ILIKE")) {
Function function = Function.getFunction(database, "CAST");
function.setDataType(new Column("X", Value.STRING_IGNORECASE));
function.setParameter(0, r);
r = function;
Expression b = readConcat();
Expression esc = null;
if (readIf("ESCAPE")) {
esc = readConcat();
}
recompileAlways = true;
r = new CompareLike(database, r, b, esc, false);
} else if (readIf("REGEXP")) {
Expression b = readConcat();
recompileAlways = true;
r = new CompareLike(database, r, b, null, true);
} else if (readIf("IS")) {
if (readIf("NOT")) {
if (readIf("NULL")) {
r = new Comparison(session, Comparison.IS_NOT_NULL, r, null);
} else if (readIf("DISTINCT")) {
read("FROM");
r = new Comparison(session, Comparison.EQUAL_NULL_SAFE, r, readConcat());
} else {
r = new Comparison(session, Comparison.NOT_EQUAL_NULL_SAFE, r, readConcat());
}
} else if (readIf("NULL")) {
r = new Comparison(session, Comparison.IS_NULL, r, null);
} else if (readIf("DISTINCT")) {
read("FROM");
r = new Comparison(session, Comparison.NOT_EQUAL_NULL_SAFE, r, readConcat());
} else {
r = new Comparison(session, Comparison.EQUAL_NULL_SAFE, r, readConcat());
}
} else if (readIf("IN")) {
read("(");
if (readIf(")")) {
if (database.getMode().prohibitEmptyInPredicate) {
throw getSyntaxError();
}
r = ValueExpression.get(ValueBoolean.FALSE);
} else {
if (isSelect()) {
Query query = parseSelect();
// can not be lazy because we have to call
// method ResultInterface.containsDistinct
// which is not supported for lazy execution
query.setNeverLazy(true);
r = new ConditionInSelect(database, r, query, false, Comparison.EQUAL);
} else {
ArrayList<Expression> v = New.arrayList();
Expression last;
do {
last = readExpression();
v.add(last);
} while (readIf(","));
if (v.size() == 1 && (last instanceof Subquery)) {
Subquery s = (Subquery) last;
Query q = s.getQuery();
r = new ConditionInSelect(database, r, q, false, Comparison.EQUAL);
} else {
r = new ConditionIn(database, r, v);
}
}
read(")");
}
} else if (readIf("BETWEEN")) {
Expression low = readConcat();
read("AND");
Expression high = readConcat();
Expression condLow = new Comparison(session, Comparison.SMALLER_EQUAL, low, r);
Expression condHigh = new Comparison(session, Comparison.BIGGER_EQUAL, high, r);
r = new ConditionAndOr(ConditionAndOr.AND, condLow, condHigh);
} else {
int compareType = getCompareType(currentTokenType);
if (compareType < 0) {
break;
}
read();
if (readIf("ALL")) {
read("(");
Query query = parseSelect();
r = new ConditionInSelect(database, r, query, true, compareType);
read(")");
} else if (readIf("ANY") || readIf("SOME")) {
read("(");
if (currentTokenType == PARAMETER && compareType == 0) {
Parameter p = readParameter();
r = new ConditionInParameter(database, r, p);
} else {
Query query = parseSelect();
r = new ConditionInSelect(database, r, query, false, compareType);
}
read(")");
} else {
Expression right = readConcat();
if (SysProperties.OLD_STYLE_OUTER_JOIN && readIf("(") && readIf("+") && readIf(")")) {
// join with (+)
if (r instanceof ExpressionColumn && right instanceof ExpressionColumn) {
ExpressionColumn leftCol = (ExpressionColumn) r;
ExpressionColumn rightCol = (ExpressionColumn) right;
ArrayList<TableFilter> filters = currentSelect.getTopFilters();
for (TableFilter f : filters) {
while (f != null) {
leftCol.mapColumns(f, 0);
rightCol.mapColumns(f, 0);
f = f.getJoin();
}
}
TableFilter leftFilter = leftCol.getTableFilter();
TableFilter rightFilter = rightCol.getTableFilter();
r = new Comparison(session, compareType, r, right);
if (leftFilter != null && rightFilter != null) {
int idx = filters.indexOf(rightFilter);
if (idx >= 0) {
filters.remove(idx);
leftFilter.addJoin(rightFilter, true, r);
} else {
rightFilter.mapAndAddFilter(r);
}
r = ValueExpression.get(ValueBoolean.TRUE);
}
}
} else {
r = new Comparison(session, compareType, r, right);
}
}
}
if (not) {
r = new ConditionNot(r);
}
}
return r;
}
use of org.h2.tools.Backup in project h2database by h2database.
the class DbUpgrade method upgrade.
private static void upgrade(ConnectionInfo ci, Properties info) throws SQLException {
String name = ci.getName();
String data = name + Constants.SUFFIX_OLD_DATABASE_FILE;
String index = name + ".index.db";
String lobs = name + ".lobs.db";
String backupData = data + ".backup";
String backupIndex = index + ".backup";
String backupLobs = lobs + ".backup";
String script = null;
try {
if (scriptInTempDir) {
new File(Utils.getProperty("java.io.tmpdir", ".")).mkdirs();
script = File.createTempFile("h2dbmigration", "backup.sql").getAbsolutePath();
} else {
script = name + ".script.sql";
}
String oldUrl = "jdbc:h2v1_1:" + name + ";UNDO_LOG=0;LOG=0;LOCK_MODE=0";
String cipher = ci.getProperty("CIPHER", null);
if (cipher != null) {
oldUrl += ";CIPHER=" + cipher;
}
Connection conn = DriverManager.getConnection(oldUrl, info);
Statement stat = conn.createStatement();
String uuid = UUID.randomUUID().toString();
if (cipher != null) {
stat.execute("script to '" + script + "' cipher aes password '" + uuid + "' --hide--");
} else {
stat.execute("script to '" + script + "'");
}
conn.close();
FileUtils.move(data, backupData);
FileUtils.move(index, backupIndex);
if (FileUtils.exists(lobs)) {
FileUtils.move(lobs, backupLobs);
}
ci.removeProperty("IFEXISTS", false);
conn = new JdbcConnection(ci, true);
stat = conn.createStatement();
if (cipher != null) {
stat.execute("runscript from '" + script + "' cipher aes password '" + uuid + "' --hide--");
} else {
stat.execute("runscript from '" + script + "'");
}
stat.execute("analyze");
stat.execute("shutdown compact");
stat.close();
conn.close();
if (deleteOldDb) {
FileUtils.delete(backupData);
FileUtils.delete(backupIndex);
FileUtils.deleteRecursive(backupLobs, false);
}
} catch (Exception e) {
if (FileUtils.exists(backupData)) {
FileUtils.move(backupData, data);
}
if (FileUtils.exists(backupIndex)) {
FileUtils.move(backupIndex, index);
}
if (FileUtils.exists(backupLobs)) {
FileUtils.move(backupLobs, lobs);
}
FileUtils.delete(name + ".h2.db");
throw DbException.toSQLException(e);
} finally {
if (script != null) {
FileUtils.delete(script);
}
}
}
use of org.h2.tools.Backup in project h2database by h2database.
the class TestBackup method testConcurrentBackup.
private void testConcurrentBackup() throws SQLException {
if (config.networked || !config.big) {
return;
}
deleteDb("backup");
String url = getURL("backup;multi_threaded=true", true);
Connection conn = getConnection(url);
final Statement stat = conn.createStatement();
stat.execute("create table test(id int primary key, name varchar)");
stat.execute("insert into test select x, 'Hello' from system_range(1, 2)");
conn.setAutoCommit(false);
Connection conn1;
conn1 = getConnection(url);
final AtomicLong updateEnd = new AtomicLong();
final Statement stat1 = conn.createStatement();
Task task = new Task() {
@Override
public void call() throws Exception {
while (!stop) {
if (System.nanoTime() < updateEnd.get()) {
stat.execute("update test set name = 'Hallo'");
stat1.execute("checkpoint");
stat.execute("update test set name = 'Hello'");
stat.execute("commit");
stat.execute("checkpoint");
} else {
Thread.sleep(10);
}
}
}
};
Connection conn2;
conn2 = getConnection(url + ";database_event_listener='" + BackupListener.class.getName() + "'");
Statement stat2 = conn2.createStatement();
task.execute();
for (int i = 0; i < 10; i++) {
updateEnd.set(System.nanoTime() + TimeUnit.SECONDS.toNanos(2));
stat2.execute("backup to '" + getBaseDir() + "/backup.zip'");
stat2.execute("checkpoint");
Restore.execute(getBaseDir() + "/backup.zip", getBaseDir() + "/t" + i, "backup");
Connection conn3 = getConnection("t" + i + "/backup");
Statement stat3 = conn3.createStatement();
stat3.execute("script");
ResultSet rs = stat3.executeQuery("select * from test where name='Hallo'");
while (rs.next()) {
fail();
}
conn3.close();
}
task.get();
conn2.close();
conn.close();
conn1.close();
}
Aggregations