use of org.h2.bnf.context.DbContents in project h2database by h2database.
the class WebApp method tables.
private String tables() {
DbContents contents = session.getContents();
boolean isH2 = false;
try {
String url = (String) session.get("url");
Connection conn = session.getConnection();
contents.readContents(url, conn);
session.loadBnf();
isH2 = contents.isH2();
StringBuilder buff = new StringBuilder().append("setNode(0, 0, 0, 'database', '").append(PageParser.escapeJavaScript(url)).append("', null);\n");
int treeIndex = 1;
DbSchema defaultSchema = contents.getDefaultSchema();
treeIndex = addTablesAndViews(defaultSchema, true, buff, treeIndex);
DbSchema[] schemas = contents.getSchemas();
for (DbSchema schema : schemas) {
if (schema == defaultSchema || schema == null) {
continue;
}
buff.append("setNode(").append(treeIndex).append(", 0, 1, 'folder', '").append(PageParser.escapeJavaScript(schema.name)).append("', null);\n");
treeIndex++;
treeIndex = addTablesAndViews(schema, false, buff, treeIndex);
}
if (isH2) {
try (Statement stat = conn.createStatement()) {
ResultSet rs = stat.executeQuery("SELECT * FROM " + "INFORMATION_SCHEMA.SEQUENCES ORDER BY SEQUENCE_NAME");
for (int i = 0; rs.next(); i++) {
if (i == 0) {
buff.append("setNode(").append(treeIndex).append(", 0, 1, 'sequences', '${text.tree.sequences}', null);\n");
treeIndex++;
}
String name = rs.getString("SEQUENCE_NAME");
String current = rs.getString("CURRENT_VALUE");
String increment = rs.getString("INCREMENT");
buff.append("setNode(").append(treeIndex).append(", 1, 1, 'sequence', '").append(PageParser.escapeJavaScript(name)).append("', null);\n");
treeIndex++;
buff.append("setNode(").append(treeIndex).append(", 2, 2, 'type', '${text.tree.current}: ").append(PageParser.escapeJavaScript(current)).append("', null);\n");
treeIndex++;
if (!"1".equals(increment)) {
buff.append("setNode(").append(treeIndex).append(", 2, 2, 'type', '${text.tree.increment}: ").append(PageParser.escapeJavaScript(increment)).append("', null);\n");
treeIndex++;
}
}
rs.close();
rs = stat.executeQuery("SELECT * FROM " + "INFORMATION_SCHEMA.USERS ORDER BY NAME");
for (int i = 0; rs.next(); i++) {
if (i == 0) {
buff.append("setNode(").append(treeIndex).append(", 0, 1, 'users', '${text.tree.users}', null);\n");
treeIndex++;
}
String name = rs.getString("NAME");
String admin = rs.getString("ADMIN");
buff.append("setNode(").append(treeIndex).append(", 1, 1, 'user', '").append(PageParser.escapeJavaScript(name)).append("', null);\n");
treeIndex++;
if (admin.equalsIgnoreCase("TRUE")) {
buff.append("setNode(").append(treeIndex).append(", 2, 2, 'type', '${text.tree.admin}', null);\n");
treeIndex++;
}
}
rs.close();
}
}
DatabaseMetaData meta = session.getMetaData();
String version = meta.getDatabaseProductName() + " " + meta.getDatabaseProductVersion();
buff.append("setNode(").append(treeIndex).append(", 0, 0, 'info', '").append(PageParser.escapeJavaScript(version)).append("', null);\n").append("refreshQueryTables();");
session.put("tree", buff.toString());
} catch (Exception e) {
session.put("tree", "");
session.put("error", getStackTrace(0, e, isH2));
}
return "tables.jsp";
}
use of org.h2.bnf.context.DbContents in project h2database by h2database.
the class WebSession method setConnection.
void setConnection(Connection conn) throws SQLException {
this.conn = conn;
if (conn == null) {
meta = null;
} else {
meta = conn.getMetaData();
}
contents = new DbContents();
}
use of org.h2.bnf.context.DbContents in project h2database by h2database.
the class TestBnf method testProcedures.
private void testProcedures(Connection conn, boolean isMySQLMode) throws Exception {
// Register a procedure and check if it is present in DbContents
conn.createStatement().execute("DROP ALIAS IF EXISTS CUSTOM_PRINT");
conn.createStatement().execute("CREATE ALIAS CUSTOM_PRINT " + "AS $$ void print(String s) { System.out.println(s); } $$");
conn.createStatement().execute("DROP TABLE IF EXISTS " + "TABLE_WITH_STRING_FIELD");
conn.createStatement().execute("CREATE TABLE " + "TABLE_WITH_STRING_FIELD (STRING_FIELD VARCHAR(50), INT_FIELD integer)");
DbContents dbContents = new DbContents();
dbContents.readContents("jdbc:h2:test", conn);
assertTrue(dbContents.isH2());
assertFalse(dbContents.isDerby());
assertFalse(dbContents.isFirebird());
assertEquals(null, dbContents.quoteIdentifier(null));
if (isMySQLMode) {
assertTrue(dbContents.isH2ModeMySQL());
assertEquals("TEST", dbContents.quoteIdentifier("TEST"));
assertEquals("TEST", dbContents.quoteIdentifier("Test"));
assertEquals("TEST", dbContents.quoteIdentifier("test"));
} else {
assertFalse(dbContents.isH2ModeMySQL());
assertEquals("TEST", dbContents.quoteIdentifier("TEST"));
assertEquals("\"Test\"", dbContents.quoteIdentifier("Test"));
assertEquals("\"test\"", dbContents.quoteIdentifier("test"));
}
assertFalse(dbContents.isMSSQLServer());
assertFalse(dbContents.isMySQL());
assertFalse(dbContents.isOracle());
assertFalse(dbContents.isPostgreSQL());
assertFalse(dbContents.isSQLite());
DbSchema defaultSchema = dbContents.getDefaultSchema();
DbProcedure[] procedures = defaultSchema.getProcedures();
Set<String> procedureName = new HashSet<>(procedures.length);
for (DbProcedure procedure : procedures) {
assertTrue(defaultSchema == procedure.getSchema());
procedureName.add(procedure.getName());
}
if (isMySQLMode) {
assertTrue(procedureName.contains("custom_print"));
} else {
assertTrue(procedureName.contains("CUSTOM_PRINT"));
}
if (isMySQLMode) {
return;
}
// Test completion
Bnf bnf = Bnf.getInstance(null);
DbContextRule columnRule = new DbContextRule(dbContents, DbContextRule.COLUMN);
bnf.updateTopic("column_name", columnRule);
bnf.updateTopic("user_defined_function_name", new DbContextRule(dbContents, DbContextRule.PROCEDURE));
bnf.linkStatements();
// Test partial
Map<String, String> tokens;
tokens = bnf.getNextTokenList("SELECT CUSTOM_PR");
assertTrue(tokens.values().contains("INT"));
// Test identifiers are working
tokens = bnf.getNextTokenList("create table \"test\" as s" + "el");
assertTrue(tokens.values().contains("E" + "CT"));
tokens = bnf.getNextTokenList("create table test as s" + "el");
assertTrue(tokens.values().contains("E" + "CT"));
// Test || with and without spaces
tokens = bnf.getNextTokenList("select 1||f");
assertFalse(tokens.values().contains("R" + "OM"));
tokens = bnf.getNextTokenList("select 1 || f");
assertFalse(tokens.values().contains("R" + "OM"));
tokens = bnf.getNextTokenList("select 1 || 2 ");
assertTrue(tokens.values().contains("FROM"));
tokens = bnf.getNextTokenList("select 1||2");
assertTrue(tokens.values().contains("FROM"));
tokens = bnf.getNextTokenList("select 1 || 2");
assertTrue(tokens.values().contains("FROM"));
// Test keyword
tokens = bnf.getNextTokenList("SELECT LE" + "AS");
assertTrue(tokens.values().contains("T"));
// Test parameters
tokens = bnf.getNextTokenList("SELECT CUSTOM_PRINT(");
assertTrue(tokens.values().contains("STRING_FIELD"));
assertFalse(tokens.values().contains("INT_FIELD"));
// Test parameters with spaces
tokens = bnf.getNextTokenList("SELECT CUSTOM_PRINT ( ");
assertTrue(tokens.values().contains("STRING_FIELD"));
assertFalse(tokens.values().contains("INT_FIELD"));
// Test parameters with close bracket
tokens = bnf.getNextTokenList("SELECT CUSTOM_PRINT ( STRING_FIELD");
assertTrue(tokens.values().contains(")"));
}
use of org.h2.bnf.context.DbContents in project h2database by h2database.
the class WebApp method getResult.
private String getResult(Connection conn, int id, String sql, boolean allowEdit, boolean forceEdit) {
try {
sql = sql.trim();
StringBuilder buff = new StringBuilder();
String sqlUpper = StringUtils.toUpperEnglish(sql);
if (sqlUpper.contains("CREATE") || sqlUpper.contains("DROP") || sqlUpper.contains("ALTER") || sqlUpper.contains("RUNSCRIPT")) {
String sessionId = attributes.getProperty("jsessionid");
buff.append("<script type=\"text/javascript\">parent['h2menu'].location='tables.do?jsessionid=").append(sessionId).append("';</script>");
}
Statement stat;
DbContents contents = session.getContents();
if (forceEdit || (allowEdit && contents.isH2())) {
stat = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
} else {
stat = conn.createStatement();
}
ResultSet rs;
long time = System.currentTimeMillis();
boolean metadata = false;
int generatedKeys = Statement.NO_GENERATED_KEYS;
boolean edit = false;
boolean list = false;
if (isBuiltIn(sql, "@autocommit_true")) {
conn.setAutoCommit(true);
return "${text.result.autoCommitOn}";
} else if (isBuiltIn(sql, "@autocommit_false")) {
conn.setAutoCommit(false);
return "${text.result.autoCommitOff}";
} else if (isBuiltIn(sql, "@cancel")) {
stat = session.executingStatement;
if (stat != null) {
stat.cancel();
buff.append("${text.result.statementWasCanceled}");
} else {
buff.append("${text.result.noRunningStatement}");
}
return buff.toString();
} else if (isBuiltIn(sql, "@edit")) {
edit = true;
sql = sql.substring("@edit".length()).trim();
session.put("resultSetSQL", sql);
}
if (isBuiltIn(sql, "@list")) {
list = true;
sql = sql.substring("@list".length()).trim();
}
if (isBuiltIn(sql, "@meta")) {
metadata = true;
sql = sql.substring("@meta".length()).trim();
}
if (isBuiltIn(sql, "@generated")) {
generatedKeys = Statement.RETURN_GENERATED_KEYS;
sql = sql.substring("@generated".length()).trim();
} else if (isBuiltIn(sql, "@history")) {
buff.append(getCommandHistoryString());
return buff.toString();
} else if (isBuiltIn(sql, "@loop")) {
sql = sql.substring("@loop".length()).trim();
int idx = sql.indexOf(' ');
int count = Integer.decode(sql.substring(0, idx));
sql = sql.substring(idx).trim();
return executeLoop(conn, count, sql);
} else if (isBuiltIn(sql, "@maxrows")) {
int maxrows = (int) Double.parseDouble(sql.substring("@maxrows".length()).trim());
session.put("maxrows", "" + maxrows);
return "${text.result.maxrowsSet}";
} else if (isBuiltIn(sql, "@parameter_meta")) {
sql = sql.substring("@parameter_meta".length()).trim();
PreparedStatement prep = conn.prepareStatement(sql);
buff.append(getParameterResultSet(prep.getParameterMetaData()));
return buff.toString();
} else if (isBuiltIn(sql, "@password_hash")) {
sql = sql.substring("@password_hash".length()).trim();
String[] p = split(sql);
return StringUtils.convertBytesToHex(SHA256.getKeyPasswordHash(p[0], p[1].toCharArray()));
} else if (isBuiltIn(sql, "@prof_start")) {
if (profiler != null) {
profiler.stopCollecting();
}
profiler = new Profiler();
profiler.startCollecting();
return "Ok";
} else if (isBuiltIn(sql, "@sleep")) {
String s = sql.substring("@sleep".length()).trim();
int sleep = 1;
if (s.length() > 0) {
sleep = Integer.parseInt(s);
}
Thread.sleep(sleep * 1000);
return "Ok";
} else if (isBuiltIn(sql, "@transaction_isolation")) {
String s = sql.substring("@transaction_isolation".length()).trim();
if (s.length() > 0) {
int level = Integer.parseInt(s);
conn.setTransactionIsolation(level);
}
buff.append("Transaction Isolation: ").append(conn.getTransactionIsolation()).append("<br />");
buff.append(Connection.TRANSACTION_READ_UNCOMMITTED).append(": read_uncommitted<br />");
buff.append(Connection.TRANSACTION_READ_COMMITTED).append(": read_committed<br />");
buff.append(Connection.TRANSACTION_REPEATABLE_READ).append(": repeatable_read<br />");
buff.append(Connection.TRANSACTION_SERIALIZABLE).append(": serializable");
}
if (sql.startsWith("@")) {
rs = getMetaResultSet(conn, sql);
if (rs == null) {
buff.append("?: ").append(sql);
return buff.toString();
}
} else {
int maxrows = getMaxrows();
stat.setMaxRows(maxrows);
session.executingStatement = stat;
boolean isResultSet = stat.execute(sql, generatedKeys);
session.addCommand(sql);
if (generatedKeys == Statement.RETURN_GENERATED_KEYS) {
rs = null;
rs = stat.getGeneratedKeys();
} else {
if (!isResultSet) {
buff.append("${text.result.updateCount}: ").append(stat.getUpdateCount());
time = System.currentTimeMillis() - time;
buff.append("<br />(").append(time).append(" ms)");
stat.close();
return buff.toString();
}
rs = stat.getResultSet();
}
}
time = System.currentTimeMillis() - time;
buff.append(getResultSet(sql, rs, metadata, list, edit, time, allowEdit));
// }
if (!edit) {
stat.close();
}
return buff.toString();
} catch (Throwable e) {
// throwable: including OutOfMemoryError and so on
return getStackTrace(id, e, session.getContents().isH2());
} finally {
session.executingStatement = null;
}
}
use of org.h2.bnf.context.DbContents in project h2database by h2database.
the class TestBnf method testModes.
private void testModes(Connection conn) throws Exception {
DbContents dbContents;
dbContents = new DbContents();
dbContents.readContents("jdbc:h2:test", conn);
assertTrue(dbContents.isH2());
dbContents = new DbContents();
dbContents.readContents("jdbc:derby:test", conn);
assertTrue(dbContents.isDerby());
dbContents = new DbContents();
dbContents.readContents("jdbc:firebirdsql:test", conn);
assertTrue(dbContents.isFirebird());
dbContents = new DbContents();
dbContents.readContents("jdbc:sqlserver:test", conn);
assertTrue(dbContents.isMSSQLServer());
dbContents = new DbContents();
dbContents.readContents("jdbc:mysql:test", conn);
assertTrue(dbContents.isMySQL());
dbContents = new DbContents();
dbContents.readContents("jdbc:oracle:test", conn);
assertTrue(dbContents.isOracle());
dbContents = new DbContents();
dbContents.readContents("jdbc:postgresql:test", conn);
assertTrue(dbContents.isPostgreSQL());
dbContents = new DbContents();
dbContents.readContents("jdbc:sqlite:test", conn);
assertTrue(dbContents.isSQLite());
}
Aggregations