package org.h2.command.dml;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import org.h2.command.CommandInterface;
import org.h2.command.Prepared;
import org.h2.engine.Session;
import org.h2.message.DbException;
import org.h2.result.ResultInterface;
import org.h2.util.ScriptReader;
public class RunScriptCommand extends ScriptBase {
private static final char UTF8_BOM = '\uFEFF';
private Charset charset = StandardCharsets.UTF_8;
public RunScriptCommand(Session session) {
super(session);
}
@Override
public int update() {
session.getUser().checkAdmin();
int count = 0;
try {
openInput();
BufferedReader reader = new BufferedReader(new InputStreamReader(in, charset));
reader.mark(1);
if (reader.read() != UTF8_BOM) {
reader.reset();
}
ScriptReader r = new ScriptReader(reader);
while (true) {
String sql = r.readStatement();
if (sql == null) {
break;
}
execute(sql);
count++;
if ((count & 127) == 0) {
checkCanceled();
}
}
r.close();
} catch (IOException e) {
throw DbException.convertIOException(e, null);
} finally {
closeIO();
}
return count;
}
private void execute(String sql) {
try {
Prepared command = session.prepare(sql);
if (command.isQuery()) {
command.query(0);
} else {
command.update();
}
if (session.getAutoCommit()) {
session.commit(false);
}
} catch (DbException e) {
throw e.addSQL(sql);
}
}
public void setCharset(Charset charset) {
this.charset = charset;
}
@Override
public ResultInterface queryMeta() {
return null;
}
@Override
public int getType() {
return CommandInterface.RUNSCRIPT;
}
}