@SuppressWarnings("unchecked") private <X> List<X> selectSimple(X x, boolean distinct) { SQLStatement stat = getSelectStatement(distinct); appendSQL(stat, x); appendFromWhere(stat); ResultSet rs = stat.executeQuery(); List<X> result = New.arrayList(); Statement s = null; try { s = rs.getStatement(); while (rs.next()) { try { X value; Object o = rs.getObject(1); int convertHereIsProbablyWrong; if (Clob.class.isAssignableFrom(o.getClass())) { value = (X) ClassUtils.convert(o, String.class); } else { value = (X) o; } result.add(value); } catch (Exception e) { throw new RuntimeException(e); } } } catch (SQLException e) { throw new RuntimeException(e); } finally { JdbcUtils.closeSilently(rs); JdbcUtils.closeSilently(s); } return result; }
private static void openResults() throws SQLException { Connection conn = null; Statement stat = null; try { conn = getResultConnection(); stat = conn.createStatement(); stat.execute( "CREATE TABLE IF NOT EXISTS RESULTS(TESTID INT, TEST VARCHAR, " + "UNIT VARCHAR, DBID INT, DB VARCHAR, RESULT VARCHAR)"); } finally { JdbcUtils.closeSilently(stat); JdbcUtils.closeSilently(conn); } }
public static Db open(String url, String user, String password) { try { Connection conn = JdbcUtils.getConnection(null, url, user, password); return new Db(conn); } catch (SQLException e) { throw convert(e); } }
public long selectCount() { SQLStatement stat = getSelectStatement(false); stat.appendSQL("COUNT(*) "); appendFromWhere(stat); ResultSet rs = stat.executeQuery(); Statement s = null; try { s = rs.getStatement(); rs.next(); long value = rs.getLong(1); return value; } catch (SQLException e) { throw new RuntimeException(e); } finally { JdbcUtils.closeSilently(rs); JdbcUtils.closeSilently(s); } }
public static Db open(String url, String user, char[] password) { try { Properties prop = new Properties(); prop.setProperty("user", user); prop.put("password", password); Connection conn = JdbcUtils.getConnection(null, url, prop); return new Db(conn); } catch (SQLException e) { throw convert(e); } }
private List<T> select(boolean distinct) { List<T> result = New.arrayList(); TableDefinition<T> def = from.getAliasDefinition(); SQLStatement stat = getSelectStatement(distinct); def.appendSelectList(stat); appendFromWhere(stat); ResultSet rs = stat.executeQuery(); Statement s = null; try { s = rs.getStatement(); while (rs.next()) { T item = from.newObject(); from.getAliasDefinition().readRow(item, rs); result.add(item); } } catch (SQLException e) { throw new RuntimeException(e); } finally { JdbcUtils.closeSilently(rs); JdbcUtils.closeSilently(s); } return result; }
private <X> List<X> select(Class<X> clazz, X x, boolean distinct) { List<X> result = New.arrayList(); TableDefinition<X> def = db.define(clazz); SQLStatement stat = getSelectStatement(distinct); def.appendSelectList(stat, this, x); appendFromWhere(stat); ResultSet rs = stat.executeQuery(); Statement s = null; try { s = rs.getStatement(); while (rs.next()) { X row = ClassUtils.newObject(clazz); def.readRow(row, rs); result.add(row); } } catch (SQLException e) { throw new RuntimeException(e); } finally { JdbcUtils.closeSilently(rs); JdbcUtils.closeSilently(s); } return result; }
@Override public void opened() { if (databaseUrl.toUpperCase().indexOf("CIPHER") >= 0) { return; } Connection conn = null; try { conn = DriverManager.getConnection(databaseUrl, getUser(), getPassword()); conn.createStatement().execute("CREATE TABLE IF NOT EXISTS TEST2(ID INT)"); conn.close(); } catch (SQLException e) { e.printStackTrace(); } finally { JdbcUtils.closeSilently(conn); } }
public static synchronized FileSystemDatabase register(String url) { Connection conn; try { if (url.startsWith("jdbc:h2:")) { // avoid using DriverManager if possible conn = Driver.load().connect(url, new Properties()); } else { conn = JdbcUtils.getConnection(null, url, new Properties()); } boolean log = url.toUpperCase().indexOf("TRACE_") >= 0; FileSystemDatabase fs = new FileSystemDatabase(url, conn, log); FileSystem.register(fs); return fs; } catch (SQLException e) { throw new RuntimeException(e); } }
private void initJavaObjectSerializer() { if (javaObjectSerializerInitialized) { return; } synchronized (this) { if (javaObjectSerializerInitialized) { return; } String serializerFQN = readSerializationSettings(); if (serializerFQN != null) { serializerFQN = serializerFQN.trim(); if (!serializerFQN.isEmpty() && !serializerFQN.equals("null")) { try { javaObjectSerializer = (JavaObjectSerializer) JdbcUtils.loadUserClass(serializerFQN).newInstance(); } catch (Exception e) { throw DbException.convert(e); } } } javaObjectSerializerInitialized = true; } }
private void test(String... args) throws Exception { int dbId = -1; boolean exit = false; String out = "benchmark.html"; for (int i = 0; i < args.length; i++) { String arg = args[i]; if ("-db".equals(arg)) { dbId = Integer.parseInt(args[++i]); } else if ("-init".equals(arg)) { FileUtils.deleteRecursive("data", true); } else if ("-out".equals(arg)) { out = args[++i]; } else if ("-trace".equals(arg)) { trace = true; } else if ("-exit".equals(arg)) { exit = true; } } Properties prop = new Properties(); InputStream in = getClass().getResourceAsStream("test.properties"); prop.load(in); in.close(); int size = Integer.parseInt(prop.getProperty("size")); ArrayList<Database> dbs = new ArrayList<Database>(); for (int i = 0; i < 100; i++) { if (dbId != -1 && i != dbId) { continue; } String dbString = prop.getProperty("db" + i); if (dbString != null) { Database db = Database.parse(this, i, dbString); if (db != null) { db.setTranslations(prop); dbs.add(db); } } } ArrayList<Bench> tests = new ArrayList<Bench>(); for (int i = 0; i < 100; i++) { String testString = prop.getProperty("test" + i); if (testString != null) { Bench bench = (Bench) Class.forName(testString).newInstance(); tests.add(bench); } } testAll(dbs, tests, size); collect = false; if (dbs.size() == 0) { return; } ArrayList<Object[]> results = dbs.get(0).getResults(); Connection conn = null; PreparedStatement prep = null; Statement stat = null; PrintWriter writer = null; try { openResults(); conn = getResultConnection(); stat = conn.createStatement(); prep = conn.prepareStatement( "INSERT INTO RESULTS(TESTID, TEST, UNIT, DBID, DB, RESULT) VALUES(?, ?, ?, ?, ?, ?)"); for (int i = 0; i < results.size(); i++) { Object[] res = results.get(i); prep.setInt(1, i); prep.setString(2, res[0].toString()); prep.setString(3, res[1].toString()); for (Database db : dbs) { prep.setInt(4, db.getId()); prep.setString(5, db.getName()); Object[] v = db.getResults().get(i); prep.setString(6, v[2].toString()); prep.execute(); } } writer = new PrintWriter(new FileWriter(out)); ResultSet rs = stat.executeQuery( "CALL '<table><tr><th>Test Case</th><th>Unit</th>' " + "|| SELECT GROUP_CONCAT('<th>' || DB || '</th>' ORDER BY DBID SEPARATOR '') FROM " + "(SELECT DISTINCT DBID, DB FROM RESULTS)" + "|| '</tr>' || CHAR(10) " + "|| SELECT GROUP_CONCAT('<tr><td>' || TEST || '</td><td>' || UNIT || '</td>' || ( " + "SELECT GROUP_CONCAT('<td>' || RESULT || '</td>' ORDER BY DBID SEPARATOR '') FROM RESULTS R2 WHERE " + "R2.TESTID = R1.TESTID) || '</tr>' ORDER BY TESTID SEPARATOR CHAR(10)) FROM " + "(SELECT DISTINCT TESTID, TEST, UNIT FROM RESULTS) R1" + "|| '</table>'"); rs.next(); String result = rs.getString(1); writer.println(result); } finally { JdbcUtils.closeSilently(prep); JdbcUtils.closeSilently(stat); JdbcUtils.closeSilently(conn); IOUtils.closeSilently(writer); } // ResultSet rsDbs = conn.createStatement().executeQuery( // "SELECT DB RESULTS GROUP BY DBID, DB ORDER BY DBID"); // while(rsDbs.next()) { // writer.println("<th>" + rsDbs.getString(1) + "</th>"); // } // ResultSet rs = conn.createStatement().executeQuery( // "SELECT TEST, UNIT FROM RESULTS " + // "GROUP BY TESTID, TEST, UNIT ORDER BY TESTID"); // while(rs.next()) { // writer.println("<tr><td>" + rs.getString(1) + "</td>"); // writer.println("<td>" + rs.getString(2) + "</td>"); // ResultSet rsRes = conn.createStatement().executeQuery( // "SELECT RESULT FROM RESULTS WHERE TESTID=? ORDER BY DBID"); // // // } // PrintWriter writer = // new PrintWriter(new FileWriter("benchmark.html")); // writer.println("<table><tr><th>Test Case</th><th>Unit</th>"); // for(int j=0; j<dbs.size(); j++) { // Database db = (Database)dbs.get(j); // writer.println("<th>" + db.getName() + "</th>"); // } // writer.println("</tr>"); // for(int i=0; i<results.size(); i++) { // Object[] res = (Object[])results.get(i); // writer.println("<tr><td>" + res[0] + "</td>"); // writer.println("<td>" + res[1] + "</td>"); // for(int j=0; j<dbs.size(); j++) { // Database db = (Database)dbs.get(j); // ArrayList r = db.getResults(); // Object[] v = (Object[])r.get(i); // writer.println( // "<td style=\"text-align: right\">" + v[2] + "</td>"); // } // writer.println("</tr>"); // } // writer.println("</table>"); if (exit) { System.exit(0); } }
/** Close the underlying database and unregister the file system. */ public void unregister() { JdbcUtils.closeSilently(conn); FileSystem.unregister(this); }
private void testCreateClusterAtRuntime() throws SQLException { if (config.memory || config.networked || config.cipher != null) { return; } int port1 = 9191, port2 = 9192; String serverList = "localhost:" + port1 + ",localhost:" + port2; deleteFiles(); org.h2.Driver.load(); String user = getUser(), password = getPassword(); Connection conn; Statement stat; String url1 = "jdbc:h2:tcp://localhost:" + port1 + "/test"; String url2 = "jdbc:h2:tcp://localhost:" + port2 + "/test"; String urlCluster = "jdbc:h2:tcp://" + serverList + "/test"; int len = 10; // initialize the database Server n1 = org.h2.tools.Server.createTcpServer( "-tcpPort", "" + port1, "-baseDir", getBaseDir() + "/node1") .start(); conn = DriverManager.getConnection(url1, user, password); stat = conn.createStatement(); stat.execute( "create table test(id int primary key, name varchar) as " + "select x, 'Data' || x from system_range(0, " + (len - 1) + ")"); stat.execute("create user test password 'test'"); stat.execute("grant all on test to test"); // start the second server Server n2 = org.h2.tools.Server.createTcpServer( "-tcpPort", "" + port2, "-baseDir", getBaseDir() + "/node2") .start(); // copy the database and initialize the cluster CreateCluster.main( "-urlSource", url1, "-urlTarget", url2, "-user", user, "-password", password, "-serverList", serverList); // check the original connection is closed try { stat.execute("select * from test"); fail(); } catch (SQLException e) { // expected JdbcUtils.closeSilently(conn); } // test the cluster connection Connection connApp = DriverManager.getConnection(urlCluster + ";AUTO_RECONNECT=TRUE", user, password); check(connApp, len, "'" + serverList + "'"); // delete the rows, but don't commit connApp.setAutoCommit(false); connApp.createStatement().execute("delete from test"); // stop server 2, and test if only one server is available n2.stop(); // rollback the transaction connApp.createStatement().executeQuery("select count(*) from test"); connApp.rollback(); check(connApp, len, "''"); connApp.setAutoCommit(true); // re-create the cluster n2 = org.h2.tools.Server.createTcpServer( "-tcpPort", "" + port2, "-baseDir", getBaseDir() + "/node2") .start(); CreateCluster.main( "-urlSource", url1, "-urlTarget", url2, "-user", user, "-password", password, "-serverList", serverList); // test the cluster connection check(connApp, len, "'" + serverList + "'"); // test a non-admin user String user2 = "test", password2 = getPassword("test"); connApp = DriverManager.getConnection(urlCluster, user2, password2); check(connApp, len, "'" + serverList + "'"); n1.stop(); // test non-admin cluster connection if only one server runs Connection connApp2 = DriverManager.getConnection(urlCluster + ";AUTO_RECONNECT=TRUE", user2, password2); check(connApp2, len, "''"); connApp2.close(); // test non-admin cluster connection if only one server runs connApp2 = DriverManager.getConnection(urlCluster + ";AUTO_RECONNECT=TRUE", user2, password2); check(connApp2, len, "''"); connApp2.close(); n2.stop(); deleteFiles(); }
private void connectServer(ConnectionInfo ci) { String name = ci.getName(); if (name.startsWith("//")) { name = name.substring("//".length()); } int idx = name.indexOf('/'); if (idx < 0) { throw ci.getFormatException(); } databaseName = name.substring(idx + 1); String server = name.substring(0, idx); traceSystem = new TraceSystem(null); String traceLevelFile = ci.getProperty(SetTypes.TRACE_LEVEL_FILE, null); if (traceLevelFile != null) { int level = Integer.parseInt(traceLevelFile); String prefix = getFilePrefix(SysProperties.CLIENT_TRACE_DIRECTORY); try { traceSystem.setLevelFile(level); if (level > 0 && level < 4) { String file = FileUtils.createTempFile(prefix, Constants.SUFFIX_TRACE_FILE, false, false); traceSystem.setFileName(file); } } catch (IOException e) { throw DbException.convertIOException(e, prefix); } } String traceLevelSystemOut = ci.getProperty(SetTypes.TRACE_LEVEL_SYSTEM_OUT, null); if (traceLevelSystemOut != null) { int level = Integer.parseInt(traceLevelSystemOut); traceSystem.setLevelSystemOut(level); } trace = traceSystem.getTrace(Trace.JDBC); String serverList = null; if (server.indexOf(',') >= 0) { serverList = StringUtils.quoteStringSQL(server); ci.setProperty("CLUSTER", Constants.CLUSTERING_ENABLED); } autoReconnect = Boolean.parseBoolean(ci.getProperty("AUTO_RECONNECT", "false")); // AUTO_SERVER implies AUTO_RECONNECT boolean autoServer = Boolean.parseBoolean(ci.getProperty("AUTO_SERVER", "false")); if (autoServer && serverList != null) { throw DbException.getUnsupportedException("autoServer && serverList != null"); } autoReconnect |= autoServer; if (autoReconnect) { String className = ci.getProperty("DATABASE_EVENT_LISTENER"); if (className != null) { className = StringUtils.trim(className, true, true, "'"); try { eventListener = (DatabaseEventListener) JdbcUtils.loadUserClass(className).newInstance(); } catch (Throwable e) { throw DbException.convert(e); } } } cipher = ci.getProperty("CIPHER"); if (cipher != null) { fileEncryptionKey = MathUtils.secureRandomBytes(32); } String[] servers = StringUtils.arraySplit(server, ',', true); int len = servers.length; transferList.clear(); sessionId = StringUtils.convertBytesToHex(MathUtils.secureRandomBytes(32)); // TODO cluster: support more than 2 connections boolean switchOffCluster = false; try { for (int i = 0; i < len; i++) { String s = servers[i]; try { Transfer trans = initTransfer(ci, databaseName, s); transferList.add(trans); } catch (IOException e) { if (len == 1) { throw DbException.get(ErrorCode.CONNECTION_BROKEN_1, e, e + ": " + s); } switchOffCluster = true; } } checkClosed(); if (switchOffCluster) { switchOffCluster(); } checkClusterDisableAutoCommit(serverList); } catch (DbException e) { traceSystem.close(); throw e; } }