提交 24cd4aac authored 作者: Thomas Mueller's avatar Thomas Mueller

--no commit message

--no commit message
上级 7a8bcd54
/*
* Copyright 2004-2006 H2 Group. Licensed under the H2 License, Version 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.samples;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import org.h2.tools.Backup;
import org.h2.tools.DeleteDbFiles;
import org.h2.tools.RunScript;
public class Compact {
public static void main(String[] args) throws Exception {
DeleteDbFiles.execute(null, "test", true);
Class.forName("org.h2.Driver");
Connection conn = DriverManager.getConnection("jdbc:h2:test", "sa", "");
Statement stat = conn.createStatement();
stat.execute("CREATE TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR)");
stat.execute("INSERT INTO TEST VALUES(1, 'Hello'), (2, 'World');");
conn.close();
System.out.println("Compacting...");
compact(null, "test", "sa", "");
System.out.println("Done.");
}
public static void compact(String dir, String dbName, String user, String password) throws Exception {
String url = "jdbc:h2:" + dbName;
String script = "test.sql";
Backup.execute(url, user, password, script);
DeleteDbFiles.execute(dir, dbName, true);
RunScript.execute(url, user, password, script, null, false);
}
}
/*
* Copyright 2004-2006 H2 Group. Licensed under the H2 License, Version 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.samples;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Types;
import org.h2.tools.Csv;
import org.h2.tools.SimpleResultSet;
public class CsvSample {
public static void main(String[] args) throws Exception {
CsvSample.write();
CsvSample.read();
}
static void write() throws Exception {
SimpleResultSet rs = new SimpleResultSet();
rs.addColumn("NAME", Types.VARCHAR, 255, 0);
rs.addColumn("EMAIL", Types.VARCHAR, 255, 0);
rs.addColumn("PHONE", Types.VARCHAR, 255, 0);
rs.addRow(new String[] { "Bob Meier", "bob.meier@abcde.fgh", "+41123456789" });
rs.addRow(new String[] { "John Jones", "johnjones@abcde.fgh", "+41976543210" });
Csv.getInstance().write("test.csv", rs, null);
}
static void read() throws Exception {
ResultSet rs = Csv.getInstance().read("test.csv", null, null);
ResultSetMetaData meta = rs.getMetaData();
while (rs.next()) {
for (int i = 0; i < meta.getColumnCount(); i++) {
System.out.println(meta.getColumnLabel(i + 1) + ": " + rs.getString(i + 1));
}
System.out.println();
}
rs.close();
}
}
/*
* Copyright 2004-2006 H2 Group. Licensed under the H2 License, Version 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.samples;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class FileFunctions {
public static void main(String[] args) throws Exception {
Class.forName("org.h2.Driver");
Connection conn = DriverManager.getConnection("jdbc:h2:mem:", "sa", "");
Statement stat = conn.createStatement();
stat.execute("CREATE ALIAS READ_TEXT_FILE FOR \"org.h2.samples.FileFunctions.readTextFile\" ");
stat.execute("CREATE ALIAS READ_TEXT_FILE_WITH_ENCODING FOR \"org.h2.samples.FileFunctions.readTextFileWithEncoding\" ");
stat.execute("CREATE ALIAS READ_FILE FOR \"org.h2.samples.FileFunctions.readFile\" ");
ResultSet rs = stat.executeQuery("CALL READ_FILE('test.txt')");
rs.next();
byte[] data = rs.getBytes(1);
System.out.println("length: " + data.length);
rs = stat.executeQuery("CALL READ_TEXT_FILE('test.txt')");
rs.next();
String text = rs.getString(1);
System.out.println("text: " + text);
conn.close();
}
public static String readTextFile(String fileName) throws IOException {
byte[] buff = readFile(fileName);
String s = new String(buff);
return s;
}
public static String readTextFileWithEncoding(String fileName, String encoding) throws IOException {
byte[] buff = readFile(fileName);
String s = new String(buff, encoding);
return s;
}
public static byte[] readFile(String fileName) throws IOException {
RandomAccessFile file = new RandomAccessFile(fileName, "r");
try {
byte[] buff = new byte[(int)file.length()];
file.readFully(buff);
return buff;
} finally {
file.close();
}
}
}
/*
* Copyright 2004-2006 H2 Group. Licensed under the H2 License, Version 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.samples;
import java.math.BigInteger;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import org.h2.tools.SimpleResultSet;
public class Function {
public static void main(String[] args) throws Exception {
Class.forName("org.h2.Driver");
Connection conn = DriverManager.getConnection("jdbc:h2:mem:", "sa", "");
Statement stat = conn.createStatement();
stat.execute("CREATE ALIAS ISPRIME FOR \"org.h2.samples.Function.isPrime\" ");
ResultSet rs;
rs = stat.executeQuery("SELECT ISPRIME(X), X FROM SYSTEM_RANGE(1, 20) ORDER BY X");
while(rs.next()) {
boolean isPrime = rs.getBoolean(1);
if(isPrime) {
int x = rs.getInt(2);
System.out.println(x + " is prime");
}
}
conn.close();
}
public static boolean isPrime(int value) {
return new BigInteger(String.valueOf(value)).isProbablePrime(100);
}
public static ResultSet query(Connection conn, String sql) throws SQLException {
return conn.createStatement().executeQuery(sql);
}
public static ResultSet simpleResultSet() throws SQLException {
SimpleResultSet rs = new SimpleResultSet();
rs.addColumn("ID", Types.INTEGER, 10, 0);
rs.addColumn("NAME", Types.VARCHAR, 255, 0);
rs.addRow(new Object[] { new Integer(0), "Hello" });
return rs;
}
public static ResultSet getMatrix(Connection conn, Integer id) throws SQLException {
SimpleResultSet rs = new SimpleResultSet();
rs.addColumn("X", Types.INTEGER, 10, 0);
rs.addColumn("Y", Types.INTEGER, 10, 0);
if(id == null) {
return rs;
}
for(int x = 0; x < id.intValue(); x++) {
for(int y = 0; y < id.intValue(); y++) {
rs.addRow(new Object[] { new Integer(x), new Integer(y) });
}
}
return rs;
}
}
/*
* Copyright 2004-2006 H2 Group. Licensed under the H2 License, Version 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.samples;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import org.h2.tools.SimpleResultSet;
public class FunctionMultiReturn {
public static void main(String[] args) throws Exception {
Class.forName("org.h2.Driver");
Connection conn = DriverManager.getConnection("jdbc:h2:mem:", "sa", "");
Statement stat = conn.createStatement();
stat.execute("CREATE ALIAS P2C FOR \"org.h2.samples.FunctionMultiReturn.polar2Cartesian\" ");
PreparedStatement prep = conn.prepareStatement("SELECT X, Y FROM P2C(?, ?)");
prep.setDouble(1, 5.0);
prep.setDouble(2, 0.5);
ResultSet rs = prep.executeQuery();
while(rs.next()) {
double x = rs.getDouble(1);
double y = rs.getDouble(2);
System.out.println("result: (x=" + x + ", y="+y+")");
}
stat.execute("CREATE TABLE TEST(ID IDENTITY, R DOUBLE, A DOUBLE)");
stat.execute("INSERT INTO TEST(R, A) VALUES(5.0, 0.5), (10.0, 0.6)");
stat.execute("CREATE ALIAS P2C_SET FOR \"org.h2.samples.FunctionMultiReturn.polar2CartesianSet\" ");
rs = conn.createStatement().executeQuery("SELECT * FROM P2C_SET('SELECT * FROM TEST')");
while(rs.next()) {
double r = rs.getDouble("R");
double a = rs.getDouble("A");
double x = rs.getDouble("X");
double y = rs.getDouble("Y");
System.out.println("(r="+r+" a="+a+") : (x=" + x + ", y="+y+")");
}
stat.execute("CREATE ALIAS P2C_A FOR \"org.h2.samples.FunctionMultiReturn.polar2CartesianArray\" ");
rs = conn.createStatement().executeQuery("SELECT R, A, P2C_A(R, A) FROM TEST");
while(rs.next()) {
double r = rs.getDouble(1);
double a = rs.getDouble(2);
Object o = rs.getObject(3);
Object[] xy = (Object[]) o;
double x = ((Double)xy[0]).doubleValue();
double y = ((Double)xy[1]).doubleValue();
System.out.println("(r="+r+" a="+a+") : (x=" + x + ", y="+y+")");
}
rs = conn.createStatement().executeQuery("SELECT R, A, ARRAY_GET(E, 1), ARRAY_GET(E, 2) FROM (SELECT R, A, P2C_A(R, A) E FROM TEST)");
while(rs.next()) {
double r = rs.getDouble(1);
double a = rs.getDouble(2);
double x = rs.getDouble(3);
double y = rs.getDouble(4);
System.out.println("(r="+r+" a="+a+") : (x=" + x + ", y="+y+")");
}
conn.close();
}
/**
* The function may be called twice, once to retrieve the result columns (with null parameters),
* and the second time to return the data.
*/
public static ResultSet polar2Cartesian(Double r, Double alpha) throws SQLException {
SimpleResultSet rs = new SimpleResultSet();
rs.addColumn("X", Types.DOUBLE, 0, 0);
rs.addColumn("Y", Types.DOUBLE, 0, 0);
if(r != null && alpha != null) {
double x = r.doubleValue() * Math.cos(alpha.doubleValue());
double y = r.doubleValue() * Math.sin(alpha.doubleValue());
rs.addRow(new Object[] { new Double(x), new Double(y) });
}
return rs;
}
/**
* The function may be called twice, once to retrieve the result columns (with null parameters),
* and the second time to return the data.
*/
public static Object[] polar2CartesianArray(Double r, Double alpha) throws SQLException {
double x = r.doubleValue() * Math.cos(alpha.doubleValue());
double y = r.doubleValue() * Math.sin(alpha.doubleValue());
return new Object[]{new Double(x), new Double(y)};
}
public static ResultSet polar2CartesianSet(Connection conn, String query) throws SQLException {
SimpleResultSet result = new SimpleResultSet();
result.addColumn("R", Types.DOUBLE, 0, 0);
result.addColumn("A", Types.DOUBLE, 0, 0);
result.addColumn("X", Types.DOUBLE, 0, 0);
result.addColumn("Y", Types.DOUBLE, 0, 0);
if(query != null) {
ResultSet rs = conn.createStatement().executeQuery(query);
while(rs.next()) {
double r = rs.getDouble("R");
double alpha = rs.getDouble("A");
double x = r * Math.cos(alpha);
double y = r * Math.sin(alpha);
result.addRow(new Object[] { new Double(r), new Double(alpha), new Double(x), new Double(y) });
}
}
return result;
}
}
/*
* Copyright 2004-2006 H2 Group. Licensed under the H2 License, Version 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.samples;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import org.h2.tools.RunScript;
import org.h2.util.StringUtils;
public class Newsfeed {
public static void main(String[] args) throws Exception {
Class.forName("org.h2.Driver");
Connection conn = DriverManager.getConnection("jdbc:h2:mem:", "sa", "");
InputStream in = Newsfeed.class.getResourceAsStream("newsfeed.sql");
ResultSet rs = RunScript.execute(conn, new InputStreamReader(in, "ISO-8859-1"));
while(rs.next()) {
String file = rs.getString("FILE");
String content = rs.getString("CONTENT");
if(file.equals("-newsletter-")) {
System.out.println(convertHtml2Text(content));
} else {
FileOutputStream out = new FileOutputStream(file);
Writer writer = new OutputStreamWriter(out, "UTF-8");
writer.write(content);
writer.close();
out.close();
}
}
conn.close();
}
private static String convertHtml2Text(String html) {
String s = html;
s = StringUtils.replaceAll(s, "<b>", "");
s = StringUtils.replaceAll(s, "</b>", "");
s = StringUtils.replaceAll(s, "<ul>", "");
s = StringUtils.replaceAll(s, "</ul>", "");
s = StringUtils.replaceAll(s, "<li>", "- ");
s = StringUtils.replaceAll(s, "<a href=\"", "( ");
s = StringUtils.replaceAll(s, "\">", " ) ");
s = StringUtils.replaceAll(s, "</a>", "");
s = StringUtils.replaceAll(s, "<br/>", "");
if(s.indexOf('<') >= 0 || s.indexOf('>') >= 0) {
throw new Error("Unsupported HTML Tag: < or > in " + s);
}
return s;
}
}
/*
* Copyright 2004-2006 H2 Group. Licensed under the H2 License, Version 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.samples;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;
/**
* @author Thomas
*/
public class SecurePassword {
public static void main(String[] argv) throws Exception {
Class.forName("org.h2.Driver");
String url = "jdbc:h2:simple";
String user = "sam";
char[] password = {'t', 'i', 'a', 'E', 'T', 'r', 'p'};
// 'unsafe' way to connect
// the password may reside in the main memory for an undefined time
// or even written to disk (swap file)
// Connection conn = DriverManager.getConnection(url, user, new String(password));
// 'safe' way to connect
// the password is overwritten after use
Properties prop = new Properties();
prop.setProperty("user", user);
prop.put("password", password);
Connection conn = DriverManager.getConnection(url, prop);
Statement stat = conn.createStatement();
stat.execute("DROP TABLE IF EXISTS TEST");
stat.execute("CREATE TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR)");
stat.executeUpdate("INSERT INTO TEST VALUES(1, 'Hello')");
ResultSet rs = stat.executeQuery("SELECT * FROM TEST");
while(rs.next()) {
System.out.println(rs.getString("NAME"));
}
conn.close();
}
}
/*
* Copyright 2004-2006 H2 Group. Licensed under the H2 License, Version 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.samples;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import org.h2.api.DatabaseEventListener;
import org.h2.jdbc.JdbcConnection;
public class ShowProgress implements DatabaseEventListener {
private long last, start;
public ShowProgress() {
start = last = System.currentTimeMillis();
}
public static void main(String[] args) throws Exception {
new ShowProgress().test();
}
void test() throws Exception {
Class.forName("org.h2.Driver");
Connection conn = DriverManager.getConnection("jdbc:h2:test;LOG=2", "sa", "");
Statement stat = conn.createStatement();
stat.execute("DROP TABLE IF EXISTS TEST");
stat.execute("CREATE TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR)");
PreparedStatement prep = conn.prepareStatement("INSERT INTO TEST VALUES(?, 'Test' || SPACE(100))");
long time;
time = System.currentTimeMillis();
int len = 1000;
for(int i=0; i<len; i++) {
long last = System.currentTimeMillis();
if(last > time+1000) {
time = last;
System.out.println("Inserting " + (100L*i/len) + "%");
}
prep.setInt(1, i);
prep.execute();
}
boolean abnormalTermination = true;
if(abnormalTermination) {
((JdbcConnection)conn).setPowerOffCount(1);
try {
stat.execute("INSERT INTO TEST VALUES(-1, 'Test' || SPACE(100))");
} catch(SQLException e) {
}
} else {
conn.close();
}
System.out.println("Open connection...");
time = System.currentTimeMillis();
conn = DriverManager.getConnection("jdbc:h2:test;LOG=2;DATABASE_EVENT_LISTENER='" + getClass().getName() + "'", "sa", "");
time = System.currentTimeMillis() - time;
System.out.println("Done after " + time + " ms");
conn.close();
}
public void diskSpaceIsLow(long stillAvailable) throws SQLException {
System.out.println("diskSpaceIsLow stillAvailable="+stillAvailable);
}
public void exceptionThrown(SQLException e) {
e.printStackTrace();
}
public void setProgress(int state, String name, int current, int max) {
long time = System.currentTimeMillis();
if(time < last+5000) {
return;
}
last = time;
String stateName = "?";
switch(state) {
case STATE_SCAN_FILE:
stateName = "Scan " + name;
break;
case STATE_CREATE_INDEX:
stateName = "Create Index " + name;
break;
case STATE_RECOVER:
stateName = "Recover";
break;
}
try {
Thread.sleep(1);
} catch (InterruptedException e) {
}
System.out.println("State: " + stateName + " " + (100*current/max) + "% (" + current+" of " + max + ") " + (time-start)+" ms");
}
public void closingDatabase() {
System.out.println("Closing the database");
}
public void init(String url) {
System.out.println("Initializing the event listener for database " + url);
}
}
/*
* Copyright 2004-2006 H2 Group. Licensed under the H2 License, Version 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.samples;
public class ShutdownServer {
public static void main(String[] args) throws Exception {
org.h2.tools.Server.shutdownTcpServer("tcp://localhost:9094", "", false);
}
}
/*
* Copyright 2004-2006 H2 Group. Licensed under the H2 License, Version 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.samples;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.h2.api.Trigger;
public class TriggerSample {
public static void main(String[] args) throws Exception {
Class.forName("org.h2.Driver");
Connection conn = DriverManager.getConnection("jdbc:h2:mem:", "sa", "");
Statement stat = conn.createStatement();
stat.execute("CREATE TABLE INVOICE(ID INT PRIMARY KEY, AMOUNT DECIMAL)");
stat.execute("CREATE TABLE INVOICE_SUM(AMOUNT DECIMAL)");
stat.execute("INSERT INTO INVOICE_SUM VALUES(0.0)");
stat.execute("CREATE TRIGGER INV_INS AFTER INSERT ON INVOICE FOR EACH ROW CALL \"org.h2.samples.TriggerSample$MyTrigger\" ");
stat.execute("CREATE TRIGGER INV_UPD AFTER UPDATE ON INVOICE FOR EACH ROW CALL \"org.h2.samples.TriggerSample$MyTrigger\" ");
stat.execute("CREATE TRIGGER INV_DEL AFTER DELETE ON INVOICE FOR EACH ROW CALL \"org.h2.samples.TriggerSample$MyTrigger\" ");
stat.execute("INSERT INTO INVOICE VALUES(1, 10.0)");
stat.execute("INSERT INTO INVOICE VALUES(2, 19.95)");
stat.execute("UPDATE INVOICE SET AMOUNT=20.0 WHERE ID=2");
stat.execute("DELETE FROM INVOICE WHERE ID=1");
ResultSet rs;
rs = stat.executeQuery("SELECT AMOUNT FROM INVOICE_SUM");
rs.next();
System.out.println("The sum is " + rs.getBigDecimal(1));
conn.close();
}
public static class MyTrigger implements Trigger {
public void init(Connection conn, String schemaName, String triggerName, String tableName) {
// System.out.println("Initializing trigger " + triggerName + " for table " + tableName);
}
public void fire(Connection conn,
Object[] oldRow, Object[] newRow)
throws SQLException {
BigDecimal diff = null;
if(newRow != null) {
diff = (BigDecimal)newRow[1];
}
if(oldRow != null) {
BigDecimal m = (BigDecimal)oldRow[1];
diff = diff == null ? m.negate() : diff.subtract(m);
}
PreparedStatement prep = conn.prepareStatement(
"UPDATE INVOICE_SUM SET AMOUNT=AMOUNT+?");
prep.setBigDecimal(1, diff);
prep.execute();
}
}
}
/*
* Copyright 2004-2006 H2 Group. Licensed under the H2 License, Version 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
// Example using the 'native' fulltext search implementation
CREATE ALIAS IF NOT EXISTS FT_INIT FOR "org.h2.fulltext.FullText.init";
CALL FT_INIT();
DROP TABLE IF EXISTS TEST;
CREATE TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR);
INSERT INTO TEST VALUES(1, 'Hello World');
CALL FT_CREATE_INDEX('PUBLIC', 'TEST', NULL);
SELECT * FROM FT_SEARCH('Hello', 0, 0);
SELECT * FROM FT_SEARCH('Hallo', 0, 0);
INSERT INTO TEST VALUES(2, 'Hallo Welt');
SELECT * FROM FT_SEARCH('Hello', 0, 0);
SELECT * FROM FT_SEARCH('Hallo', 0, 0);
CALL FT_REINDEX();
SELECT * FROM FT_SEARCH('Hello', 0, 0);
SELECT * FROM FT_SEARCH('Hallo', 0, 0);
INSERT INTO TEST VALUES(3, 'Hello World');
INSERT INTO TEST VALUES(4, 'Hello World');
INSERT INTO TEST VALUES(5, 'Hello World');
SELECT * FROM FT_SEARCH('World', 0, 0);
SELECT * FROM FT_SEARCH('World', 1, 0);
SELECT * FROM FT_SEARCH('World', 0, 2);
SELECT * FROM FT_SEARCH('World', 2, 1);
SELECT * FROM FT_SEARCH('1');
CALL FT_DROP_ALL();
SELECT * FROM FT_SEARCH('World', 2, 1);
CALL FT_DROP_ALL();
// Example using the 'Lucene' fulltext search implementation
CREATE ALIAS IF NOT EXISTS FTL_INIT FOR "org.h2.fulltext.FullTextLucene.init";
CALL FTL_INIT();
DROP TABLE IF EXISTS TEST;
CREATE TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR);
INSERT INTO TEST VALUES(1, 'Hello World');
CALL FTL_CREATE_INDEX('PUBLIC', 'TEST', NULL);
SELECT * FROM FTL_SEARCH('Hello', 0, 0);
SELECT * FROM FTL_SEARCH('Hallo', 0, 0);
INSERT INTO TEST VALUES(2, 'Hallo Welt');
SELECT * FROM FTL_SEARCH('Hello', 0, 0);
SELECT * FROM FTL_SEARCH('Hallo', 0, 0);
CALL FTL_REINDEX();
SELECT * FROM FTL_SEARCH('Hello', 0, 0);
SELECT * FROM FTL_SEARCH('Hallo', 0, 0);
INSERT INTO TEST VALUES(3, 'Hello World');
INSERT INTO TEST VALUES(4, 'Hello World');
INSERT INTO TEST VALUES(5, 'Hello World');
SELECT * FROM FTL_SEARCH('World', 0, 0);
SELECT * FROM FTL_SEARCH('World', 1, 0);
SELECT * FROM FTL_SEARCH('World', 0, 2);
SELECT * FROM FTL_SEARCH('World', 2, 1);
SELECT * FROM FTL_SEARCH('1', 0, 0);
CALL FTL_DROP_ALL();
SELECT * FROM FTL_SEARCH('World', 2, 1);
CALL FTL_DROP_ALL();
差异被折叠。
<?xml version="1.0"?>
<rss version="2.0">
<channel>
<title>H2 Database Engine</title>
<link>http://www.h2database.com</link>
<description>H2 Database Engine</description>
<language>en-us</language>
<pubDate>Thu, 15 Jun 2006 05:59:06 GMT</pubDate>
<lastBuildDate>Thu, 15 Jun 2006 05:59:06 GMT</lastBuildDate>
<item>
<title>New version available: 0.9 Alpha / 2006-06-02</title>
<link>http://www.h2database.com</link>
<description>
<![CDATA[A new version of H2 is available for download at http://www.h2database.com
Changes and new functionality:
- The GCJ version for Windows is no longer included in the download.
It was not stable in this release.
- ORDER BY now uses an index if possible.
Queries with LIMIT with ORDER BY
are faster when the index can be used.
- Statements containing LIKE are now re-compiled when executed.
Depending on the data, an index on the column is used or not.
- New option to disable automatic closing of a database
when the virtual machine exits.
Database URL: jdbc:h2:test;db_close_on_exit=false
- New event: DatabaseEventListener.closingDatabase()
- Connection.getCatalog() now returns the database name
- The function DATABASE() now return the short name
- Automatic starting of a web browser for Mac OS X should work now.
Security:
- TCP Server: Can now specifiy a password (tcpPassword).
- New option -ifExists for the TCP and ODBC server
to disallow creating new databases.
Bugfixes:
- Issue #103: Shutdown of a TCP Server from command line
didn't always work.
- Issue #104: A HAVING condition on a column
that was not in the GROUP BY list didn't work.
- Issue #105: RUNSCRIPT (the command) didn't commit
after each command if autocommit was on.
- Issue #106: SET commands where not persisted
- Issue# 107: When executing scripts that contained inserts
with many columns, an OutOfMemory error could occur.
- Issue #108: There is a concurrency problem when multi threads
access the same database.
- Issue #109: ALTER TABLE ADD COLUMN can make
the database unusable.
For details see also the history. The plans for the next release are:
- Bugfixes, write more tests, more bugfixes, more tests
- Define which modules are alpha, beta and production quality
- Proposal for changed license (still pending...)
- For other plans, see the new 'Roadmap' part on the web site
]]>
</description>
</item>
</channel>
</rss>
\ No newline at end of file
差异被折叠。
差异被折叠。
/*
* Copyright 2004-2006 H2 Group. Licensed under the H2 License, Version 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.test.bench;
public interface Bench {
void init(Database db, int size) throws Exception;
void run() throws Exception;
String getName();
}
/*
* Copyright 2004-2006 H2 Group. Licensed under the H2 License, Version 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.test.bench;
import java.math.BigDecimal;
import java.sql.*;
import java.util.Random;
/**
* See also: http://www.tpc.org/tpca/spec/tpca_current.pdf
*/
public class BenchA implements Bench {
private Database db;
private int branches;
private int tellers = branches * 20;
private int accounts = branches * 100;
private int size;
private static final String FILLER = "abcdefghijklmnopqrstuvwxyz";
private static final int DELTA = 10000;
public void init(Database db, int size) throws Exception {
this.db = db;
this.size = size;
int scale = 1;
accounts = size * 50;
tellers = Math.max(accounts / 10, 1);
branches = Math.max(tellers / 10, 1);
db.start(this, "Init");
db.openConnection();
db.dropTable("BRANCHES");
db.dropTable("BRANCHES");
db.dropTable("TELLERS");
db.dropTable("ACCOUNTS");
db.dropTable("HISTORY");
String[] create = { "CREATE TABLE BRANCHES(BID INT NOT NULL PRIMARY KEY, BBALANCE DECIMAL(15,2), FILLER VARCHAR(88))",
"CREATE TABLE TELLERS(TID INT NOT NULL PRIMARY KEY, BID INT, TBALANCE DECIMAL(15,2), FILLER VARCHAR(84))",
"CREATE TABLE ACCOUNTS(AID INT NOT NULL PRIMARY KEY, BID INT, ABALANCE DECIMAL(15,2), FILLER VARCHAR(84))",
"CREATE TABLE HISTORY(TID INT, BID INT, AID INT, DELTA DECIMAL(15,2), HTIME DATETIME, FILLER VARCHAR(40))" };
for (int i = 0; i < create.length; i++) {
db.update(create[i]);
}
PreparedStatement prep;
db.setAutoCommit(false);
int commitEvery = 1000;
prep = db.prepare("INSERT INTO BRANCHES(BID,BBALANCE,FILLER) VALUES(?,10000.00,'" + FILLER + "')");
for (int i = 0; i < branches * scale; i++) {
prep.setInt(1, i);
db.update(prep);
if(i%commitEvery==0) {
db.commit();
}
}
db.commit();
prep = db.prepare("INSERT INTO TELLERS(TID,BID,TBALANCE,FILLER) VALUES(?,?,10000.00,'" + FILLER + "')");
for (int i = 0; i < tellers * scale; i++) {
prep.setInt(1, i);
prep.setInt(2, i / tellers);
db.update(prep);
if(i%commitEvery==0) {
db.commit();
}
}
db.commit();
int len = accounts * scale;
prep = db.prepare("INSERT INTO ACCOUNTS(AID,BID,ABALANCE,FILLER) VALUES(?,?,10000.00,'" + FILLER + "')");
for (int i = 0; i < len; i++) {
prep.setInt(1, i);
prep.setInt(2, i / accounts);
db.update(prep);
if(i%commitEvery==0) {
db.commit();
}
}
db.commit();
db.closeConnection();
db.end();
db.start(this, "Open/Close");
db.openConnection();
db.closeConnection();
db.end();
}
public void run() throws Exception {
db.start(this, "Transactions");
db.openConnection();
processTransactions();
db.closeConnection();
db.end();
db.openConnection();
processTransactions();
db.logMemory(this, "Memory Usage");
db.closeConnection();
}
private void processTransactions() throws Exception {
Random random = db.getRandom();
int branch = random.nextInt(branches);
int teller = random.nextInt(tellers);
int transactions = size * 30;
PreparedStatement updateAccount = db.prepare("UPDATE ACCOUNTS SET ABALANCE=ABALANCE+? WHERE AID=?");
PreparedStatement selectBalance = db.prepare("SELECT ABALANCE FROM ACCOUNTS WHERE AID=?");
PreparedStatement updateTeller = db.prepare("UPDATE TELLERS SET TBALANCE=TBALANCE+? WHERE TID=?");
PreparedStatement updateBranch = db.prepare("UPDATE BRANCHES SET BBALANCE=BBALANCE+? WHERE BID=?");
PreparedStatement insertHistory = db.prepare("INSERT INTO HISTORY(AID,TID,BID,DELTA,HTIME,FILLER) VALUES(?,?,?,?,?,?)");
int accountsPerBranch = accounts / branches;
db.setAutoCommit(false);
for (int i = 0; i < transactions; i++) {
int account;
if (random.nextInt(100) < 85) {
account = random.nextInt(accountsPerBranch) + branch * accountsPerBranch;
} else {
account = random.nextInt(accounts);
}
int max = BenchA.DELTA;
// delta: -max .. +max
BigDecimal delta = new BigDecimal("" + (random.nextInt(max * 2) - max));
long current = System.currentTimeMillis();
updateAccount.setBigDecimal(1, delta);
updateAccount.setInt(2, account);
db.update(updateAccount);
updateTeller.setBigDecimal(1, delta);
updateTeller.setInt(2, teller);
db.update(updateTeller);
updateBranch.setBigDecimal(1, delta);
updateBranch.setInt(2, branch);
db.update(updateBranch);
selectBalance.setInt(1, account);
db.queryReadResult(selectBalance);
insertHistory.setInt(1, account);
insertHistory.setInt(2, teller);
insertHistory.setInt(3, branch);
insertHistory.setBigDecimal(4, delta);
// TODO convert: should be able to convert date to timestamp (by using 0 for remaining fields)
// insertHistory.setDate(5, new java.sql.Date(current));
insertHistory.setTimestamp(5, new java.sql.Timestamp(current));
insertHistory.setString(6, BenchA.FILLER);
db.update(insertHistory);
db.commit();
}
updateAccount.close();
selectBalance.close();
updateTeller.close();
updateBranch.close();
insertHistory.close();
}
public String getName() {
return "BenchA";
}
}
差异被折叠。
/*
* Copyright 2004-2006 H2 Group. Licensed under the H2 License, Version 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.test.bench;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Random;
public class BenchCRandom {
private Random random = new Random(10);
int getNonUniform(int a, int min, int max) {
int c = 0;
return (((getInt(0, a) | getInt(min, max)) + c) % (max - min + 1))
+ min;
}
int getInt(int min, int max) {
return max <= min ? min : (random.nextInt(max - min) + min);
}
boolean[] getBoolean(int length, int trueCount) {
boolean[] data = new boolean[length];
for (int i = 0, pos; i < trueCount; i++) {
do {
pos = getInt(0, length);
} while (data[pos]);
data[pos] = true;
}
return data;
}
String replace(String text, String replacement) {
int pos = getInt(0, text.length() - replacement.length());
StringBuffer buffer = new StringBuffer(text);
buffer.replace(pos, pos + 7, replacement);
return buffer.toString();
}
String getNumberString(int min, int max) {
int len = getInt(min, max);
char[] buff = new char[len];
for (int i = 0; i < len; i++) {
buff[i] = (char) getInt('0', '9');
}
return new String(buff);
}
String[] getAddress() {
String str1 = getString(10, 20);
String str2 = getString(10, 20);
String city = getString(10, 20);
String state = getString(2);
String zip = getNumberString(9, 9);
return new String[] { str1, str2, city, state, zip };
}
String getString(int min, int max) {
return getString(getInt(min, max));
}
String getString(int len) {
char[] buff = new char[len];
for (int i = 0; i < len; i++) {
buff[i] = (char) getInt('A', 'Z');
}
return new String(buff);
}
int[] getPermutation(int length) {
int[] data = new int[length];
for (int i = 0; i < length; i++) {
data[i] = i;
}
for (int i = 0; i < length; i++) {
int j = getInt(0, length);
int temp = data[i];
data[i] = data[j];
data[j] = temp;
}
return data;
}
BigDecimal getBigDecimal(int value, int scale) {
return new BigDecimal(new BigInteger(String.valueOf(value)), scale);
}
String getLastname(int i) {
String[] n = { "BAR", "OUGHT", "ABLE", "PRI", "PRES", "ESE", "ANTI",
"CALLY", "ATION", "EING" };
StringBuffer buff = new StringBuffer();
buff.append(n[i / 100]);
buff.append(n[(i / 10) % 10]);
buff.append(n[i % 10]);
return buff.toString();
}
}
/*
* Copyright 2004-2006 H2 Group. Licensed under the H2 License, Version 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.test.bench;
import java.sql.PreparedStatement;
import java.util.Random;
public class BenchSimple implements Bench {
Database db;
int records;
public void init(Database db, int size) throws Exception {
this.db = db;
this.records = size * 60;
db.start(this, "Init");
db.openConnection();
db.dropTable("TEST");
db.setAutoCommit(false);
int commitEvery = 1000;
db.update("CREATE TABLE TEST(ID INT NOT NULL PRIMARY KEY, NAME VARCHAR(255))");
db.commit();
PreparedStatement prep = db.prepare("INSERT INTO TEST VALUES(?, ?)");
for(int i=0; i<records; i++) {
prep.setInt(1, i);
prep.setString(2, "Hello World " + i);
db.update(prep);
if(i%commitEvery==0) {
db.commit();
}
}
db.commit();
db.closeConnection();
db.end();
db.start(this, "Open/Close");
db.openConnection();
db.closeConnection();
db.end();
}
public void run() throws Exception {
PreparedStatement prep;
Random random = db.getRandom();
db.openConnection();
db.start(this, "Query (random)");
prep = db.prepare("SELECT * FROM TEST WHERE ID=?");
for(int i=0; i<records; i++) {
prep.setInt(1, random.nextInt(records));
db.queryReadResult(prep);
}
db.end();
db.start(this, "Query (sequential)");
prep = db.prepare("SELECT * FROM TEST WHERE ID=?");
for(int i=0; i<records; i++) {
prep.setInt(1, i);
db.queryReadResult(prep);
}
db.end();
db.start(this, "Update (random)");
prep = db.prepare("UPDATE TEST SET NAME=? WHERE ID=?");
for(int i=0; i<records; i++) {
prep.setString(1, "Hallo Welt");
prep.setInt(2, i);
db.update(prep);
}
db.end();
db.start(this, "Delete (sequential)");
prep = db.prepare("DELETE FROM TEST WHERE ID=?");
// delete only 50%
for(int i=0; i<records; i+=2) {
prep.setInt(1, i);
db.update(prep);
}
db.end();
db.closeConnection();
db.openConnection();
prep = db.prepare("SELECT * FROM TEST WHERE ID=?");
for(int i=0; i<records; i++) {
prep.setInt(1, random.nextInt(records));
db.queryReadResult(prep);
}
db.logMemory(this, "Memory Usage");
db.closeConnection();
}
public String getName() {
return "Simple";
}
}
/*
* Copyright 2004-2006 H2 Group. Licensed under the H2 License, Version 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.test.bench;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Properties;
import java.util.Random;
import java.util.StringTokenizer;
import org.h2.test.TestBase;
import org.h2.tools.Server;
import org.h2.util.StringUtils;
class Database {
private TestPerformance test;
private int id;
private String name, url, user, password;
private ArrayList replace = new ArrayList();
private String action;
private long startTime;
private Connection conn;
private Statement stat;
private boolean trace = true;
private long lastTrace;
private Random random = new Random(1);
private ArrayList results = new ArrayList();
private int totalTime;
private int executedStatements;
private Server serverH2;
private Object serverDerby;
private boolean serverHSQLDB;
String getName() {
return name;
}
int getTotalTime() {
return totalTime;
}
ArrayList getResults() {
return results;
}
Random getRandom() {
return random;
}
void startServer() throws Exception {
if(url.startsWith("jdbc:h2:tcp:")) {
serverH2 = Server.createTcpServer(new String[0]).start();
Thread.sleep(100);
} else if(url.startsWith("jdbc:derby://")) {
serverDerby = Class.forName("org.apache.derby.drda.NetworkServerControl").newInstance();
Method m = serverDerby.getClass().getMethod("start", new Class[]{PrintWriter.class});
m.invoke(serverDerby, new Object[]{null});
// serverDerby = new NetworkServerControl();
// serverDerby.start(null);
Thread.sleep(100);
} else if(url.startsWith("jdbc:hsqldb:hsql:")) {
if(!serverHSQLDB) {
Class c = Class.forName("org.hsqldb.Server");
Method m = c.getMethod("main", new Class[]{String[].class});
m.invoke(null, new Object[]{new String[]{"-database.0", "data/mydb;hsqldb.default_table_type=cached", "-dbname.0", "xdb"}});
// org.hsqldb.Server.main(new String[]{"-database.0", "mydb", "-dbname.0", "xdb"});
serverHSQLDB = true;
Thread.sleep(100);
}
}
}
void stopServer() throws Exception {
if(serverH2 != null) {
serverH2.stop();
serverH2 = null;
}
if(serverDerby != null) {
Method m = serverDerby.getClass().getMethod("shutdown", new Class[]{});
m.invoke(serverDerby, null);
// serverDerby.shutdown();
serverDerby = null;
} else if(serverHSQLDB) {
// can not shut down (shutdown calls System.exit)
// openConnection();
// update("SHUTDOWN");
// closeConnection();
// serverHSQLDB = false;
}
}
static Database parse(TestPerformance test, int id, String dbString) {
try {
StringTokenizer tokenizer = new StringTokenizer(dbString, ",");
Database db = new Database();
db.id = id;
db.test = test;
db.name = tokenizer.nextToken().trim();
String driver = tokenizer.nextToken().trim();
Class.forName(driver);
db.url = tokenizer.nextToken().trim();
db.user = tokenizer.nextToken().trim();
db.password = "";
if(tokenizer.hasMoreTokens()) {
db.password = tokenizer.nextToken().trim();
}
System.out.println("Loaded successfully: " + db.name);
return db;
} catch(Exception e) {
System.out.println("Cannot load database " + dbString +" :" + e.toString());
return null;
}
}
Connection getConnection() throws Exception {
Connection conn = DriverManager.getConnection(url, user, password);
if(url.startsWith("jdbc:derby:")) {
// Derby: use higher cache size
conn.createStatement().execute("CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY('derby.storage.pageSize', '8192')");
}
return conn;
}
void openConnection() throws Exception {
conn = DriverManager.getConnection(url, user, password);
stat = conn.createStatement();
}
void closeConnection() throws Exception {
// if(!serverHSQLDB && url.startsWith("jdbc:hsqldb:")) {
// stat.execute("SHUTDOWN");
// }
conn.close();
stat = null;
conn = null;
}
public void setTranslations(Properties prop) {
String id = url.substring("jdbc:".length());
id = id.substring(0, id.indexOf(':'));
for(Iterator it = prop.keySet().iterator(); it.hasNext(); ) {
String key = (String)it.next();
if(key.startsWith(id + ".")) {
String pattern = key.substring(id.length()+1);
pattern = StringUtils.replaceAll(pattern, "_", " ");
pattern = StringUtils.toUpperEnglish(pattern);
String replacement = prop.getProperty(key);
replace.add(new String[]{pattern, replacement});
}
}
}
PreparedStatement prepare(String sql) throws Exception {
sql = getSQL(sql);
return conn.prepareStatement(sql);
}
public String getSQL(String sql) {
for(int i=0; i<replace.size(); i++) {
String[] pair = (String[]) replace.get(i);
String pattern = pair[0];
String replace = pair[1];
sql = StringUtils.replaceAll(sql, pattern, replace);
}
return sql;
}
void start(Bench bench, String action) {
this.action = bench.getName() + ": " + action;
this.startTime = System.currentTimeMillis();
}
void end() {
long time = System.currentTimeMillis() - startTime;
log(action, "ms", (int)time);
if(test.collect) {
totalTime += time;
}
}
void dropTable(String table) {
try {
update("DROP TABLE " + table);
} catch (Exception e) {
// ignore - table may not exist
}
}
public void update(PreparedStatement prep) throws Exception {
prep.executeUpdate();
executedStatements++;
}
public void update(String sql) throws Exception {
sql = getSQL(sql);
if(sql.trim().length()>0) {
stat.execute(sql);
} else {
System.out.println("?");
}
executedStatements++;
}
public void setAutoCommit(boolean b) throws Exception {
conn.setAutoCommit(b);
}
public void commit() throws Exception {
conn.commit();
}
public void rollback() throws Exception {
conn.rollback();
}
void trace(String action, int i, int max) {
if (trace) {
long time = System.currentTimeMillis();
if (i == 0 || lastTrace == 0) {
lastTrace = time;
} else if (time > lastTrace + 1000) {
System.out.println(action + ": " + ((100 * i / max) + "%"));
lastTrace = time;
}
}
}
void logMemory(Bench bench, String action) {
log(bench.getName() + ": " + action, "MB", TestBase.getMemoryUsed());
}
void log(String action, String scale, int value) {
if(test.collect) {
results.add(new Object[]{action, scale, new Integer(value)});
}
}
public ResultSet query(PreparedStatement prep) throws Exception {
// long time = System.currentTimeMillis();
ResultSet rs = prep.executeQuery();
// time = System.currentTimeMillis() - time;
// if(time > 100) {
// new Error("time="+time).printStackTrace();
// }
executedStatements++;
return rs;
}
public void queryReadResult(PreparedStatement prep) throws Exception {
ResultSet rs = prep.executeQuery();
ResultSetMetaData meta = rs.getMetaData();
int columnCount = meta.getColumnCount();
while(rs.next()) {
for(int i=0; i<columnCount; i++) {
rs.getString(i+1);
}
}
}
int getExecutedStatements() {
return executedStatements;
}
public int getId() {
return id;
}
}
/*
* Copyright 2004-2006 H2 Group. Licensed under the H2 License, Version 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.test.bench;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Properties;
import org.h2.test.TestBase;
public class TestPerformance {
boolean collect;
public static void main(String[] args) throws Exception {
new TestPerformance().test(args);
}
private Connection getResultConnection() throws Exception {
Class.forName("org.h2.Driver");
return DriverManager.getConnection("jdbc:h2:data/results");
}
private void openResults(boolean init) throws Exception {
Connection conn = getResultConnection();
if(init) {
conn.createStatement().execute("DROP TABLE IF EXISTS RESULTS");
}
conn.createStatement().execute("CREATE TABLE IF NOT EXISTS RESULTS(TESTID INT, TEST VARCHAR, "
+ "UNIT VARCHAR, DBID INT, DB VARCHAR, RESULT VARCHAR)");
conn.close();
}
private void test(String[] args) throws Exception {
boolean init = false;
int dbId = -1;
String out = "benchmark.html";
for(int i=0; i<args.length; i++) {
if(args[i].equals("-db")) {
dbId = Integer.parseInt(args[++i]);
} else if(args[i].equals("-init")) {
init = true;
} else if(args[i].equals("-out")) {
out = args[++i];
}
}
openResults(init);
Properties prop = new Properties();
prop.load(getClass().getResourceAsStream("test.properties"));
int size = Integer.parseInt(prop.getProperty("size"));
ArrayList dbs = new ArrayList();
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 tests = new ArrayList();
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 results = ((Database)dbs.get(0)).getResults();
Connection conn = getResultConnection();
PreparedStatement prep = conn.prepareStatement(
"INSERT INTO RESULTS(TESTID, TEST, UNIT, DBID, DB, RESULT) VALUES(?, ?, ?, ?, ?, ?)");
for(int i=0; i<results.size(); i++) {
Object[] res = (Object[])results.get(i);
prep.setInt(1, i);
prep.setString(2, res[0].toString());
prep.setString(3, res[1].toString());
for(int j=0; j<dbs.size(); j++) {
Database db = (Database)dbs.get(j);
prep.setInt(4, db.getId());
prep.setString(5, db.getName());
ArrayList r = db.getResults();
Object[] v = (Object[])r.get(i);
prep.setString(6, v[2].toString());
prep.execute();
}
}
PrintWriter writer = new PrintWriter(new FileWriter(out));
ResultSet rs = conn.createStatement().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);
conn.close();
// 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>");
writer.close();
System.out.println("Test finished");
System.exit(0);
}
private void testAll(ArrayList dbs, ArrayList tests, int size) throws Exception {
for(int i=0; i<dbs.size(); i++) {
if(i>0) {
Thread.sleep(1000);
}
// calls garbage collection
TestBase.getMemoryUsed();
Database db = (Database)dbs.get(i);
System.out.println("testing " + db.getName());
db.startServer();
Connection conn = db.getConnection();
runDatabase(db, tests, 1);
runDatabase(db, tests, 1);
collect = true;
runDatabase(db, tests, size);
conn.close();
db.log("Executed Statements", "#", db.getExecutedStatements());
db.log("Total Time", "ms", db.getTotalTime());
db.log("Statement per Second", "#", db.getExecutedStatements()*1000/db.getTotalTime());
collect = false;
db.stopServer();
}
}
private void runDatabase(Database db, ArrayList tests, int size) throws Exception {
for(int j=0; j<tests.size(); j++) {
Bench bench = (Bench)tests.get(j);
runTest(db, bench, size);
}
}
private void runTest(Database db, Bench bench, int size) throws Exception {
bench.init(db, size);
bench.run();
}
}
db1 = H2, org.h2.Driver, jdbc:h2:data/test, sa, sa
db2 = HSQLDB, org.hsqldb.jdbcDriver, jdbc:hsqldb:data/test;hsqldb.default_table_type=cached, sa
db3 = Derby, org.apache.derby.jdbc.EmbeddedDriver, jdbc:derby:data/test;create=true, sa, sa
db4 = H2, org.h2.Driver, jdbc:h2:tcp://localhost/data/testServ, sa, sa
db5 = HSQLDB, org.hsqldb.jdbcDriver, jdbc:hsqldb:hsql://localhost/xdb, sa
db6 = Derby, org.apache.derby.jdbc.ClientDriver, jdbc:derby://localhost/data/testServ;create=true, sa, sa
db7 = PostgreSQL, org.postgresql.Driver, jdbc:postgresql:test, sa, sa
db8 = MySQL, com.mysql.jdbc.Driver, jdbc:mysql://localhost/test?jdbcCompliantTruncation=false, sa, sa
db9 = Firebird, org.firebirdsql.jdbc.FBDriver, jdbc:firebirdsql:localhost:c:/temp/firebird/test, sysdba, masterkey
xdb9 = OneDollarDB, in.co.daffodil.db.jdbc.DaffodilDBDriver, jdbc:daffodilDB_embedded:school;path=C:/temp;create=true, sa
xdb10 = Oracle, oracle.jdbc.driver.OracleDriver, jdbc:oracle:thin:@localhost:1521:test, scott, tiger
xdb11 = DB2, COM.ibm.db2.jdbc.net.DB2Driver, jdbc:db2://localhost/test, test, test
xdb12 = MSSQLServer, com.microsoft.jdbc.sqlserver.SQLServerDriver, jdbc:microsoft:sqlserver://127.0.0.1:1433;DatabaseName=test, test, test
firebirdsql.datetime = TIMESTAMP
postgresql.datetime = TIMESTAMP
derby.datetime = TIMESTAMP
test1 = org.h2.test.bench.BenchSimple
test2 = org.h2.test.bench.BenchA
test3 = org.h2.test.bench.BenchC
xsize = 500
xsize = 20
xsize=200
#bug with hsqldb (newest version) and size = 400
xsize = 200
#officialsize = 250
size = 400
MySQL
--------------------------------------------------------------------------------------------------------
ANSI mode can be set using SET GLOBAL sql_mode='ANSI'; 'TRADITIONAL' is default
SELECT @@global.sql_mode
Compare with NULL problem
drop table test;
create table test(id int);
insert into test values(1);
insert into test values(null);
-- 2 rows even in ANSI mode (correct is 1 row):
select * from test where id=id and 1=1;
PostgreSQL
--------------------------------------------------------------------------------------------------------
差异被折叠。
create schema testschema;
create table testschema.test(id int);
create sequence testschema.testseq;
select testschema.testseq.nextval;
> 1;
drop schema testschema;
create table test(id int);
create trigger testtrigger before insert on test call "org.h2.test.db.TestTriggersConstraints";
comment on trigger testtrigger is 'just testing';
select remarks from information_schema.triggers where trigger_name = 'TESTTRIGGER';
> just testing;
@reconnect;
select remarks from information_schema.triggers where trigger_name = 'TESTTRIGGER';
> just testing;
drop trigger testtrigger;
@reconnect;
create alias parselong for "java.lang.Long.parseLong";
comment on alias parselong is 'Parse a long with base';
select remarks from information_schema.function_aliases where alias_name = 'PARSELONG';
> Parse a long with base;
@reconnect;
select remarks from information_schema.function_aliases where alias_name = 'PARSELONG';
> Parse a long with base;
drop alias parselong;
@reconnect;
create role hr;
comment on role hr is 'Human Resources';
select remarks from information_schema.roles where name = 'HR';
> Human Resources;
@reconnect;
select remarks from information_schema.roles where name = 'HR';
> Human Resources;
create user abc password 'x';
grant hr to abc;
drop role hr;
@reconnect;
drop user abc;
create domain email as varchar(100) check instr(value, '@') > 0;
comment on domain email is 'must contain @';
select remarks from information_schema.domains where domain_name = 'EMAIL';
> must contain @;
@reconnect;
select remarks from information_schema.domains where domain_name = 'EMAIL';
> must contain @;
drop domain email;
@reconnect;
create schema tests;
set schema tests;
create sequence walk;
comment on schema tests is 'Test Schema';
comment on sequence walk is 'Walker';
select remarks from information_schema.schemata where schema_name = 'TESTS';
> Test Schema;
select remarks from information_schema.sequences where sequence_name = 'WALK';
> Walker;
@reconnect;
select remarks from information_schema.schemata where schema_name = 'TESTS';
> Test Schema;
select remarks from information_schema.sequences where sequence_name = 'WALK';
> Walker;
drop schema tests;
@reconnect;
create constant abc value 1;
comment on constant abc is 'One';
select remarks from information_schema.constants where constant_name = 'ABC';
> One;
@reconnect;
select remarks from information_schema.constants where constant_name = 'ABC';
> One;
drop constant abc;
drop table test;
@reconnect;
create table test(id int);
alter table test add constraint const1 unique(id);
create index idxid on test(id);
comment on constraint const1 is 'unique id';
comment on index idxid is 'idindex';
select remarks from information_schema.constraints where constraint_name = 'CONST1';
> unique id;
select remarks from information_schema.indexes where index_name = 'IDXID';
> idindex;
@reconnect;
select remarks from information_schema.constraints where constraint_name = 'CONST1';
> unique id;
select remarks from information_schema.indexes where index_name = 'IDXID';
> idindex;
drop table test;
@reconnect;
create user sales password '1';
comment on user sales is 'mr. money';
select remarks from information_schema.users where name = 'SALES';
> mr. money;
@reconnect;
select remarks from information_schema.users where name = 'SALES';
> mr. money;
alter user sales rename to salesuser;
select remarks from information_schema.users where name = 'SALESUSER';
> mr. money;
@reconnect;
select remarks from information_schema.users where name = 'SALESUSER';
> mr. money;
create table test(id int);
create linked table testlink('org.h2.Driver', 'jdbc:h2:mem:', 'sa', 'sa', 'DUAL');
comment on table testlink is '123';
select remarks from information_schema.tables where table_name = 'TESTLINK';
> 123;
@reconnect;
select remarks from information_schema.tables where table_name = 'TESTLINK';
> 123;
comment on table testlink is 'xyz';
select remarks from information_schema.tables where table_name = 'TESTLINK';
> xyz;
alter table testlink rename to testl;
select remarks from information_schema.tables where table_name = 'TESTL';
> xyz;
@reconnect;
select remarks from information_schema.tables where table_name = 'TESTL';
> xyz;
drop table test;
@reconnect;
create table test(id int);
create view testv as select * from test;
comment on table testv is 'abc';
select remarks from information_schema.tables where table_name = 'TESTV';
> abc;
@reconnect;
select remarks from information_schema.tables where table_name = 'TESTV';
> abc;
alter table testv rename to testview;
select remarks from information_schema.tables where table_name = 'TESTVIEW';
> abc;
@reconnect;
select remarks from information_schema.tables where table_name = 'TESTVIEW';
> abc;
drop table test;
@reconnect;
create table test(a int);
comment on table test is 'hi';
select remarks from information_schema.tables where table_name = 'TEST';
> hi;
alter table test add column b int;
select remarks from information_schema.tables where table_name = 'TEST';
> hi;
alter table test rename to test1;
select remarks from information_schema.tables where table_name = 'TEST1';
> hi;
@reconnect;
select remarks from information_schema.tables where table_name = 'TEST1';
> hi;
comment on table test1 is 'ho';
@reconnect;
select remarks from information_schema.tables where table_name = 'TEST1';
> ho;
drop table test1;
create table test(a int, b int);
comment on column test.b is 'test';
select remarks from information_schema.columns where table_name = 'TEST' and column_name = 'B';
> test;
@reconnect;
select remarks from information_schema.columns where table_name = 'TEST' and column_name = 'B';
> test;
alter table test drop column b;
@reconnect;
comment on column test.a is 'ho';
select remarks from information_schema.columns where table_name = 'TEST' and column_name = 'A';
> ho;
@reconnect;
select remarks from information_schema.columns where table_name = 'TEST' and column_name = 'A';
> ho;
drop table test;
@reconnect;
create table test(a int);
comment on column test.a is 'test';
alter table test rename to test2;
@reconnect;
select remarks from information_schema.columns where table_name = 'TEST2';
> test;
@reconnect;
select remarks from information_schema.columns where table_name = 'TEST2';
> test;
drop table test2;
@reconnect;
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论