提交 7a8bcd54 authored 作者: Thomas Mueller's avatar Thomas Mueller

--no commit message

--no commit message
上级 68bcd1cb
/*
* 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.cases;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import org.h2.tools.Csv;
public class TestCloseAtShutdown extends Thread {
Connection conn;
TestCloseAtShutdown() {
Csv csv = null;
csv.setFieldSeparatorWrite(";");
}
public void run() {
try {
Thread.sleep(100);
} catch(Exception e) {
// ignore
}
System.out.println("hook app");
try {
conn.getAutoCommit();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
Class.forName("org.h2.Driver");
TestCloseAtShutdown closer = new TestCloseAtShutdown();
Runtime.getRuntime().addShutdownHook(closer);
Connection conn = DriverManager.getConnection("jdbc:h2:test2;TRACE_LEVEL_FILE=3;DB_CLOSE_ON_EXIT=FALSE", "sa", "sa");
closer.conn = conn;
conn.getAutoCommit();
}
}
/*
* 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.cases;
import java.sql.*;
import java.util.Random;
public class TestCloseDelay {
private Connection conn;
public static void main(String[] args) throws Exception {
new TestCloseDelay().test();
new TestCloseDelay().test();
}
public void test() throws Exception {
Class.forName("org.h2.Driver");
conn = DriverManager.getConnection("jdbc:h2:test;DB_CLOSE_DELAY=-1");
Statement stat;
stat = conn.createStatement();
conn.setAutoCommit(false);
stat.execute("DROP TABLE TEST IF EXISTS");
stat.execute("CREATE TABLE TEST(ID IDENTITY, NAME VARCHAR)");
Random random = new Random();
for(int j=0; j<100; j++) {
System.out.println("j:" + j);
for(int i=0; i<1000; i++) {
switch(random.nextInt(10)) {
case 0:
conn.close();
conn = DriverManager.getConnection("jdbc:h2:test;DB_CLOSE_DELAY=-1");
stat = conn.createStatement();
conn.setAutoCommit(false);
break;
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
stat.execute("INSERT INTO TEST(NAME) VALUES('Hello')");
break;
case 7:
case 8:
case 9:
stat.execute("UPDATE TEST SET NAME='Hello World' WHERE ROWNUM < 10");
break;
}
if((i% 100) == 0) {
ResultSet rs = stat.executeQuery("SELECT * FROM TEST ORDER BY ID");
while(rs.next()) {
rs.getInt(1);
rs.getString(2);
}
}
}
stat.execute("SHUTDOWN");
conn.close();
conn = DriverManager.getConnection("jdbc:h2:test;DB_CLOSE_DELAY=-1");
stat = conn.createStatement();
ResultSet rs = stat.executeQuery("SELECT * FROM TEST ORDER BY ID");
while(rs.next()) {
rs.getInt(1);
rs.getString(2);
}
}
}
}
/*
* 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.cases;
import java.sql.*;
import org.h2.tools.DeleteDbFiles;
public class TestCollation {
private static final int TOTAL = 100000;
private static final int ROOT = 1000;
private Connection conn;
public static void main(String[] args) throws Exception {
new TestCollation().test();
new TestCollation().test();
}
public void test() throws Exception {
DeleteDbFiles.execute(null, "test", true);
Class.forName("org.h2.Driver");
Class.forName("org.postgresql.Driver");
Class.forName("com.mysql.jdbc.Driver");
Class.forName("org.hsqldb.jdbcDriver");
//
conn = DriverManager.getConnection("jdbc:h2:testColl", "sa", "sa");
// conn = DriverManager.getConnection("jdbc:hsqldb:testColl", "sa", "");
// conn = DriverManager.getConnection("jdbc:postgresql:jpox2", "sa", "sa");
// conn = DriverManager.getConnection("jdbc:mysql://localhost/test", "sa", "sa");
try {
conn.createStatement().execute("DROP TABLE TEST");
} catch(Exception e) {
// ignore
}
conn.createStatement().execute("CREATE TABLE TEST(ID INT)");
conn.createStatement().execute("INSERT INTO TEST VALUES(1)");
PreparedStatement prep = conn.prepareStatement("Select Case When ? >= ? Then 'Yes' Else 'No' End FROM TEST");
prep.setObject(1, new Integer(26));
prep.setObject(2, new Integer(26));
ResultSet rs = prep.executeQuery();
while(rs.next()) {
System.out.println("a:"+rs.getObject(1));
}
// /=====return 'No'
// but *****
prep = conn.prepareStatement("Select Case When ? >= Cast(? As Int) Then 'Yes' Else 'No' End FROM TEST");
prep.setObject(1, new Integer(26));
prep.setObject(2, new Integer(26));
rs = prep.executeQuery();
while (rs.next()) {
System.out.println("b:"+rs.getObject(1));
}
// /=====return 'Yes'
// This problem also happen if there are date parameters;
Statement stm = conn.createStatement();
stm.executeUpdate(
"DROP TABLE IF EXISTS test");
stm.executeUpdate(
"SET COLLATION OFF");
stm.executeUpdate(
"CREATE TABLE test (id INT IDENTITY, code VARCHAR(20) NOT NULL, parentId INT)");
stm.executeUpdate(
"CREATE INDEX test_code ON test(code)");
PreparedStatement pstm = conn.prepareStatement(
"INSERT INTO test (code,parentId) VALUES (?,NULL)");
PreparedStatement pstm2 = conn.prepareStatement(
"INSERT INTO test (code,parentId) SELECT ?,id FROM test WHERE code=?");
long time = System.currentTimeMillis();
for (int i = 1; i < TOTAL; ++i) {
if (i < ROOT) {
pstm.setString(1, Integer.toBinaryString(i));
pstm.executeUpdate();
} else {
pstm2.setString(1, Integer.toBinaryString(i));
pstm2.setString(2, Integer.toBinaryString(i % 100 + 1));
pstm2.executeUpdate();
}
}
System.out.println("INSERT w/o Collation: " + (System.currentTimeMillis()-time));
testWithCollation();
}
public void testWithCollation() throws Exception {
Statement stm = conn.createStatement();
stm.executeUpdate(
"DROP TABLE IF EXISTS test");
stm.executeUpdate(
"SET COLLATION ENGLISH STRENGTH PRIMARY");
stm.executeUpdate(
"CREATE TABLE test (id INT IDENTITY, code VARCHAR(20) NOT NULL, parentId INT)");
stm.executeUpdate(
"CREATE INDEX test_code ON test(code)");
PreparedStatement pstm = conn.prepareStatement(
"INSERT INTO test (code,parentId) VALUES (?,NULL)");
PreparedStatement pstm2 = conn.prepareStatement(
"INSERT INTO test (code,parentId) SELECT ?,id FROM test WHERE code=?");
long time = System.currentTimeMillis();
for (int i = 1; i < TOTAL; ++i) {
if (i < ROOT) {
pstm.setString(1, Integer.toBinaryString(i));
pstm.executeUpdate();
} else {
pstm2.setString(1, Integer.toBinaryString(i));
pstm2.setString(2, Integer.toBinaryString(i % 100 + 1));
pstm2.executeUpdate();
}
}
System.out.println("INSERT with Collation: " + (System.currentTimeMillis()-time));
}
}
/*
* 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.cases;
import java.sql.*;
public class TestCompatibiliyMySQL {
public static void main(String[] args) throws Exception {
testWith("org.postgresql.Driver", "jdbc:postgresql:jpox2", "sa", "sa");
testWith("com.mysql.jdbc.Driver", "jdbc:mysql://localhost/test", "sa", "sa");
testWith("org.hsqldb.jdbcDriver", "jdbc:hsqldb:test", "sa", "");
testWith("org.h2.Driver", "jdbc:h2:test", "sa", "sa");
}
static void testWith(String driver, String url, String user, String password)
throws Exception {
Class.forName(driver);
System.out.println("URL: " + url);
Connection connection = DriverManager.getConnection(url, user, password);
// Class.forName("com.mysql.jdbc.Driver");
// Connection connection = DriverManager.getConnection( "jdbc:mysql://localhost/test", "sa", "sa");
Statement statement = connection.createStatement();
try {
statement.execute("DROP TABLE PEOPLE");
} catch(SQLException e) {}
statement.execute("CREATE TABLE PEOPLE (ID BIGINT, NAME VARCHAR(32))");
statement.execute("INSERT INTO PEOPLE (ID, NAME) VALUES (1, 'Adam')");
ResultSet rs = statement.executeQuery("SELECT PEOPLE.NAME FROM PEOPLE");
rs.next();
assertEquals("Adam", rs.getString(1));
assertEquals("Adam", rs.getString("NAME"));
rs = statement.executeQuery("SELECT PEOPLE.NAME FROM PEOPLE");
rs.next();
// assertEquals( "Adam", rs.getString("PEOPLE.NAME"));
statement.executeQuery("SELECT PEOPLE.NAME FROM PEOPLE");
statement.executeQuery("SELECT PEOPLE.NAME FROM PEOPLE;");
statement.executeQuery("SELECT PEOPLE.NAME FROM PEOPLE /* comment */");
// try {
// connection.createStatement().executeQuery("SELECT PEOPLE.NAME FROM PEOPLE; /* comment */");
// throw new Error("error");
// } catch(SQLException e) {
// // expected
// }
connection.createStatement().executeQuery("SELECT PEOPLE.NAME FROM PEOPLE /* comment */ ;");
}
private static void assertEquals(String a, String b) {
if(!a.equals(b)) {
throw new Error("a=" + a + " b="+b);
}
}
}
/*
* 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.cases;
import java.sql.*;
import java.util.Random;
/*
del *.db
java -Xrunhprof:cpu=samples org.h2.test.cases.TestConnect
java org.h2.test.cases.TestConnect
*/
public class TestConnect {
public static void main(String[] args) throws Exception {
Class.forName("org.h2.Driver");
long time = System.currentTimeMillis();
String url = "jdbc:h2:test;LOG=2;STORAGE=TEXT;DATABASE_EVENT_LISTENER='org.h2.samples.ShowProgress'";
Connection conn = DriverManager.getConnection(url, "sa", "sa");
time = System.currentTimeMillis() - time;
System.out.println("connected in " + time);
ResultSet rs = conn.getMetaData().getTables(null, null, "TEST", null);
Random random = new Random(1);
if(!rs.next()) {
conn.createStatement().execute("CREATE TABLE TEST(ID IDENTITY, NAME VARCHAR)");
PreparedStatement prep = conn.prepareStatement("INSERT INTO TEST(NAME) VALUES(space(2000))");
// PreparedStatement prep = conn.prepareStatement("INSERT INTO TEST(NAME) VALUES(space(20000))");
int len = 5000;
for(int i=0; i<len; i++) {
long t2 = System.currentTimeMillis();
if(t2 - time > 1000) {
System.out.println("Inserting " + i + " of " + len);
time = t2;
}
prep.executeUpdate();
}
prep = conn.prepareStatement("UPDATE TEST SET NAME = space(2000) WHERE ID=?");
for(int i=0; i<len; i++) {
long t2 = System.currentTimeMillis();
if(t2 - time > 1000) {
System.out.println("Updating " + i + " of " + len);
time = t2;
}
prep.setInt(1, random.nextInt(len));
prep.executeUpdate();
}
// @LOOP 50000 UPDATE TEST SET NAME=space(20000) WHERE ID=?/*RND*/;
Thread.sleep(2000);
Runtime.getRuntime().halt(0);
}
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.test.cases;
import java.sql.*;
public class TestDate {
public static void main(String[] args) throws Exception {
testWith("org.postgresql.Driver", "jdbc:postgresql:jpox2", "sa", "sa");
testWith("com.mysql.jdbc.Driver", "jdbc:mysql://localhost/test", "sa", "sa");
testWith("org.h2.Driver", "jdbc:h2:test", "sa", "sa");
testWith("org.hsqldb.jdbcDriver", "jdbc:hsqldb:test", "sa", "");
}
static void testWith(String driver, String url, String user, String password)
throws Exception {
Class.forName(driver);
System.out.println("URL: " + url);
Connection conn = DriverManager.getConnection(url, user, password);
Statement stat = conn.createStatement();
try {
stat.execute("DROP TABLE ts_trial");
} catch (SQLException e) { }
stat.execute("CREATE TABLE ts_trial(myts TIMESTAMP)");
PreparedStatement prep = conn.prepareStatement(
"INSERT INTO ts_trial(myts) VALUES (?)");
prep.setTimestamp(1, new java.sql.Timestamp(System.currentTimeMillis()));
prep.execute();
prep.setDate(1, new java.sql.Date(System.currentTimeMillis()));
prep.execute();
ResultSet rs = stat.executeQuery("SELECT myts FROM ts_trial");
rs.next();
System.out.println("Timestamp: " + rs.getTimestamp("myts"));
rs.next();
System.out.println("Date: " + rs.getTimestamp("myts"));
System.out.println();
}
}
/*
* 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.cases;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Random;
import org.h2.tools.DeleteDbFiles;
public class TestFullTextSpeed {
private static final int RECORD_COUNT = 100;
private Connection conn;
// java -Xrunhprof:cpu=samples,depth=6 org.h2.test.cases.TestFullTextSpeed
public static void main(String[] args) throws Exception {
// new TestFullTextSpeed().test(true);
new TestFullTextSpeed().test(false);
// new TestFullTextSpeed().test(true);
new TestFullTextSpeed().test(false);
}
public void test(boolean lucene) throws Exception {
String type = lucene ? "FTL_" : "FT_";
String init = lucene ? "org.h2.fulltext.FullTextLucene.init" : "org.h2.fulltext.FullText.init";
System.out.println((lucene ? "Lucene" : "Native") + " full text search");
DeleteDbFiles.execute(null, "test", true);
Class.forName("org.h2.Driver");
conn = DriverManager.getConnection("jdbc:h2:test;ASSERT=FALSE;LOG=0", "sa", "sa");
Statement stat = conn.createStatement();
stat.execute("CREATE TABLE TEST(ID IDENTITY, NAME VARCHAR)");
PreparedStatement prep = conn.prepareStatement("INSERT INTO TEST(NAME) VALUES(?)");
Random random = new Random(0);
for(int i=0; i<RECORD_COUNT; i++) {
prep.setString(1, getRandomText(random));
prep.execute();
}
long time;
time = System.currentTimeMillis();
stat.execute("CREATE ALIAS IF NOT EXISTS "+type+"INIT FOR \""+init+"\"");
stat.execute("CALL "+type+"INIT()");
stat.execute("CALL "+type+"DROP_ALL()");
stat.execute("CALL "+type+"CREATE_INDEX('PUBLIC', 'TEST', NULL)");
System.out.println("index: " + (System.currentTimeMillis() - time));
prep = conn.prepareStatement("SELECT * FROM "+type+"SEARCH(?, 0, 0)");
time = System.currentTimeMillis();
int totalResults = 0;
for(int i=0; i<1000 * RECORD_COUNT; i++) {
prep.setString(1, getRandomWord(random));
ResultSet rs = prep.executeQuery();
while(rs.next()) {
rs.getString(1);
totalResults++;
}
}
System.out.println("query: " + (System.currentTimeMillis() - time) + " results: " + totalResults);
conn.close();
}
private String getRandomWord(Random random) {
return "" + (char)(random.nextInt('z'-'a') + 'a') + random.nextInt(RECORD_COUNT);
}
private String getRandomText(Random random) {
int words = random.nextInt(1000);
StringBuffer buff = new StringBuffer(words * 6);
for(int i=0; i<words; i++) {
buff.append(getRandomWord(random));
buff.append(' ');
}
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.cases;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.h2.tools.SimpleResultSet;
public class TestFunction {
public static ResultSet temp(Object[] values) throws SQLException{
SimpleResultSet result = new SimpleResultSet();
result.addColumn("TEMP1", java.sql.Types.INTEGER, 0, 0);
for(int i = 0; values != null && i < values.length; i++){
result.addRow(new Object[] {values[i]});
}
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.test.cases;
import java.io.Reader;
import java.io.StringReader;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
public class TestHibernateClob {
public static void main(String[] a) throws Exception {
System.out.println("starting test...");
org.h2.tools.DeleteDbFiles.execute(null, "test", true);
Class.forName("org.h2.Driver");
Connection conn = DriverManager.getConnection("jdbc:h2:mem:", "sa", "sa");
conn.createStatement().execute("CREATE TABLE IF NOT EXISTS TEST(ID INT)");
DatabaseMetaData meta = conn.getMetaData();
ResultSet rs = meta.getTables(null, null, "TEST", null);
while(rs.next()) {
String cat = rs.getString("TABLE_CAT");
String schema = rs.getString("TABLE_SCHEM");
String table = rs.getString("TABLE_NAME");
ResultSet rs2 = meta.getColumns(cat, schema, table, null);
while(rs2.next()) {
System.out.println(table + "." + rs2.getString("COLUMN_NAME"));
}
}
conn.getAutoCommit();
conn.setAutoCommit(false);
DatabaseMetaData dbMeta0 =
conn.getMetaData();
dbMeta0.getDatabaseProductName();
dbMeta0.getDatabaseMajorVersion();
dbMeta0.getDatabaseProductVersion();
dbMeta0.getDriverName();
dbMeta0.getDriverVersion();
dbMeta0.supportsResultSetType(1004);
dbMeta0.supportsBatchUpdates();
dbMeta0.dataDefinitionCausesTransactionCommit();
dbMeta0.dataDefinitionIgnoredInTransactions();
dbMeta0.supportsGetGeneratedKeys();
conn.getAutoCommit();
conn.getAutoCommit();
conn.commit();
conn.setAutoCommit(true);
Statement stat0 =
conn.createStatement();
stat0.executeUpdate("drop table CLOB_ENTITY if exists");
stat0.getWarnings();
stat0.executeUpdate("create table CLOB_ENTITY (ID bigint not null, SER_DATA clob, CLOB_DATA clob, primary key (ID))");
stat0.getWarnings();
stat0.close();
conn.getWarnings();
conn.clearWarnings();
conn.setAutoCommit(false);
conn.getAutoCommit();
conn.getAutoCommit();
PreparedStatement prep0 =
conn.prepareStatement("select max(ID) from CLOB_ENTITY");
ResultSet rs0 =
prep0.executeQuery();
rs0.next();
rs0.getLong(1);
rs0.wasNull();
rs0.close();
prep0.close();
conn.getAutoCommit();
PreparedStatement prep1 =
conn.prepareStatement("insert into CLOB_ENTITY (SER_DATA, CLOB_DATA, ID) values (?, ?, ?)");
prep1.setNull(1, 2005);
StringBuffer buff = new StringBuffer(20000);
for(int i=0; i<10000; i++) {
buff.append((char)('0' + (i%10)));
}
Reader x = new StringReader(buff.toString());
prep1.setCharacterStream(2, x, 10000);
prep1.setLong(3, 1);
prep1.addBatch();
prep1.executeBatch();
prep1.close();
conn.getAutoCommit();
conn.getAutoCommit();
conn.commit();
conn.isClosed();
conn.getWarnings();
conn.clearWarnings();
conn.getAutoCommit();
conn.getAutoCommit();
PreparedStatement prep2 =
conn.prepareStatement("select clobholdin0_.ID as ID0_0_, clobholdin0_.SER_DATA as SER2_0_0_, clobholdin0_.CLOB_DATA as CLOB3_0_0_ from CLOB_ENTITY clobholdin0_ where clobholdin0_.ID=?");
prep2.setLong(1, 1);
ResultSet rs1 =
prep2.executeQuery();
rs1.next();
System.out.println("ser: " + rs1.getCharacterStream("SER2_0_0_"));
Clob clob0 =
rs1.getClob("CLOB3_0_0_");
System.out.println("wasNull: " + rs1.wasNull());
rs1.next();
rs1.close();
prep2.getMaxRows();
prep2.getQueryTimeout();
prep2.close();
conn.getAutoCommit();
Reader r = clob0.getCharacterStream();
char[] chars = new char[(int)clob0.length()];
int read = r.read(chars);
System.out.println("read: " + read + " " + r);
for(int i=0; i<10000; i++) {
int ch = chars[i];
if(ch != ('0' + (i%10))) {
throw new Error("expected "+ (char)('0' + (i%10)) + " got: " + ch + " (" + (char)ch + ")");
}
}
int ch = r.read();
if(ch != -1) {
System.out.println("expected -1 got: " + ch );
}
conn.close();
System.out.println("done");
}
}
/*
* 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.cases;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class TestLimitOffset {
public static void main(String[] args) throws Exception {
Class.forName("org.h2.Driver");
Connection conn = DriverManager.getConnection("jdbc:h2:test", "sa", "sa");
Statement stat = conn.createStatement();
try {
stat.execute("DROP TABLE file");
} catch (SQLException e) {
//
}
stat.execute("create table IF NOT EXISTS file (id IDENTITY primary key, path nvarchar(1000) not null, name nvarchar(100), date timestamp not null, size int , is_dir char(1) not null, unique (path))");
PreparedStatement prep = conn.prepareStatement(" insert into file (path, is_dir, date) values(?, 'N', NOW()+? )");
for(int i=0; i<60000; i++) {
prep.setInt(1, i);
prep.setInt(2, i);
prep.execute();
}
ResultSet rs;
prep = conn.prepareStatement("select path from file where path like ? and is_dir <> 'Y' order by date desc LIMIT 25 OFFSET 0");
prep.setString(1, "%");
rs = prep.executeQuery();
rs.next();
System.out.println(rs.getString(1));
prep = conn.prepareStatement("select path from file where path like ? and is_dir <> 'Y' order by date desc LIMIT 25 OFFSET 25");
prep.setString(1, "%");
rs = prep.executeQuery();
rs.next();
System.out.println(rs.getString(1));
prep = conn.prepareStatement("select path from file where path like ? and is_dir <> 'Y' order by date desc LIMIT 25 OFFSET 50");
prep.setString(1, "%");
rs = prep.executeQuery();
rs.next();
System.out.println(rs.getString(1));
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.test.cases;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.Statement;
import java.util.Random;
import org.h2.tools.DeleteDbFiles;
import org.h2.util.MemoryUtils;
public class TestLinearIndex {
public static void main(String[] args) throws Exception {
Class.forName("org.h2.Driver");
// stat.execute("create unique index idxid on test(id)");
int len = 1000;
for(int a=0; ; a++) {
testLoop(true, len);
testLoop(false, len);
len += 1000;
}
// hash: 23156
// btree: 10250
}
private static void testLoop(boolean hashIndex, int len) throws Exception {
DeleteDbFiles.execute(".", "test", true);
String url = "jdbc:h2:test";
Connection conn = DriverManager.getConnection(url, "sa", "sa");
Statement stat = conn.createStatement();
stat.execute("drop table if exists test");
stat.execute("create table test(id int, name varchar)");
if(hashIndex) {
stat.execute("create unique hash index idxid on test(id)");
} else {
stat.execute("create unique index idxid on test(id)");
}
stat.execute("insert into test select x, 'Hello World' from system_range(1, "+len+")");
PreparedStatement prep = conn.prepareStatement("select * from test where id=?");
Random random = new Random(1);
long time = System.currentTimeMillis();
for(int i=0; i<len*50; i++) {
prep.setInt(1, random.nextInt(len));
prep.executeQuery();
}
time = System.currentTimeMillis() - time;
System.out.println("len: " + len + " hash: " + hashIndex + " time: " + time+" used: " + MemoryUtils.getMemoryUsed());
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.test.cases;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Types;
public class TestOther {
public static void main(String[] args) {
Object[] tos = {
// new int[] {1, 2, 3, 4, 5},
// new Integer(122), // Uncomment to see a "Hexadecimal string with odd number of characters"
new String[] {"hello", "world"}, // Uncomment to see a "Deserialization failed"
// new Integer(12) // Will save it somehow, but fails to retrieve
};
try {
Class.forName("org.h2.Driver");
Connection con = DriverManager.getConnection("jdbc:h2:mem:", "sa", "");
con.setAutoCommit(true);
con.createStatement().executeUpdate("CREATE TABLE TestOtherJDBC (tstData OTHER)");
System.out.println("table created");
PreparedStatement stmt = con.prepareStatement("INSERT INTO TestOtherJDBC (tstData) VALUES (?)");
for (int i = 0; i < tos.length; i++) {
System.out.println(tos[i].getClass().getName() + "\t" + tos[i]);
stmt.setObject(1, tos[i], Types.OTHER);
stmt.executeUpdate();
}
System.out.println("inserted");
ResultSet rs = con.createStatement().executeQuery("SELECT tstData FROM TestOtherJDBC");
while(rs.next()) {
Object obj = rs.getObject(1);
System.out.println(obj.getClass().getName() + "\t" + obj);
}
rs.close();
} catch (Throwable e) {
e.printStackTrace();
}
}
}
/*
* 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.cases;
import java.sql.*;
import java.util.Random;
import org.h2.tools.DeleteDbFiles;
import org.h2.util.MemoryUtils;
public class TestRebuildIndex {
public static void main (String[] args) throws Exception {
boolean init = false;
if(init) {
DeleteDbFiles.execute(".", "test", false);
}
Class.forName("org.h2.Driver");
Connection conn = DriverManager.getConnection("jdbc:h2:test;cache_type=lzf", "sa", "sa");
Statement stat = conn.createStatement();
if(init) {
stat.executeUpdate("DROP TABLE IF EXISTS TEST");
stat.executeUpdate("CREATE TABLE TEST(ID INT PRIMARY KEY, DATA INT)");
PreparedStatement prep = conn.prepareStatement("INSERT INTO TEST VALUES(?, ?)");
int max = 1000000;
Random random = new Random(10);
for(int i=0; i<max; i++) {
prep.setInt(1, i);
// prep.setInt(2, max - i);
prep.setInt(2, random.nextInt());
prep.execute();
}
} else {
long time = System.currentTimeMillis();
stat.execute("CREATE INDEX IDXDATA ON TEST(DATA)");
time = System.currentTimeMillis() - time;
System.out.println("time: " + time);
// lzf: 5688 / 11944 kb
// tq: 4875 ms / 12131 kb
System.out.println("mem: " + MemoryUtils.getMemoryUsed());
}
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.test.cases;
import java.sql.*;
import org.h2.tools.Server;
public class TestRemoteMetaData {
public static void main(String[] args) throws Exception {
Class.forName("org.h2.Driver");
Server server = org.h2.tools.Server.createTcpServer(new String[0]);
server.start();
String url = "jdbc:h2:tcp://localhost/test;TRACE_LEVEL_FILE=3";
Connection conn = DriverManager.getConnection(url, "sa", "sa");
DatabaseMetaData meta = conn.getMetaData();
ResultSet rsTables = meta.getTables(null, null, null, null);
while(rsTables.next()) {
if (rsTables.getString(4).equals("TABLE")) {
String name = rsTables.getString("TABLE_NAME");
meta.getExportedKeys(null, null, name);
meta.getImportedKeys(null, null, name);
}
}
server.stop();
}
}
/*
* 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.cases;
import java.sql.*;
class TestUpdatableResultSet {
Connection conn;
public static void main(String[] args) throws Exception {
new TestUpdatableResultSet().test();
}
int insertStudentUsingResultSet(String name) throws Exception {
Statement stmt = conn.createStatement(ResultSet.FETCH_FORWARD, ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery("SELECT * FROM students FOR UPDATE");
// rs.moveToInsertRow();
// rs.updateString("name", name);
// rs.insertRow();
int id = 0;
try {
rs.last();
id = rs.getInt("student_id");
} catch (Exception e) {
e.printStackTrace();
}
return id;
}
void test() throws Exception {
Class.forName("org.h2.Driver");
conn = DriverManager.getConnection("jdbc:h2:test", "sa", "sa");
// Class.forName("org.postgresql.Driver");
// conn = DriverManager.getConnection("jdbc:postgresql:jpox2", "sa", "sa");
// Class.forName("com.mysql.jdbc.Driver");
// conn = DriverManager.getConnection("jdbc:mysql://localhost/test", "sa", "sa");
try {
conn.createStatement().executeUpdate("DROP TABLE students");
} catch (SQLException e) {
//
}
// conn.createStatement().executeUpdate("CREATE TABLE students (student_id int PRIMARY KEY, name char(20))");
conn.createStatement().executeUpdate("CREATE TABLE students (student_id int AUTO_INCREMENT PRIMARY KEY, name char(20))");
System.out.println("student id: " + insertStudentUsingResultSet("name-1")); // output must be 1,it will print 0,
System.out.println("student id: " + insertStudentUsingResultSet("name-2")); // output must be 2, it will print 1
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.test.coverage;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.LineNumberReader;
/**
* The class used at runtime to measure the code usage and performance.
*/
public class Profile extends Thread {
public static final boolean LIST_UNVISITED = true;
public static final boolean FAST = false;
public static final boolean TRACE = false;
public static int current;
public static Profile main = new Profile();
private BufferedWriter trace;
public int[] count;
public int[] time;
boolean stop;
int maxIndex;
int lastIndex;
long lastTime;
static int top = 15;
static {
try {
String s = System.getProperty("profile.top");
if (s != null) {
top = Integer.parseInt(s);
}
} catch (Throwable e) {
// ignore SecurityExceptions
}
}
public static void visit(int i) {
if (FAST) {
current = i;
} else {
main.addVisit(i);
}
}
public void run() {
list();
}
public static void startCollecting() {
main.stop = false;
main.lastTime = System.currentTimeMillis();
}
public static void stopCollecting() {
main.stop = true;
}
public static void list() {
if (main.lastIndex == 0) {
// don't list anything if no statistics collected
return;
}
try {
main.listUnvisited();
main.listTop("MOST CALLED", main.count, top);
main.listTop("MOST TIME USED", main.time, top);
} catch (Exception e) {
e.printStackTrace();
}
}
Profile() {
try {
LineNumberReader r = new LineNumberReader(new FileReader(
"profile.txt"));
while (r.readLine() != null) {
// nothing
}
maxIndex = r.getLineNumber();
count = new int[maxIndex];
time = new int[maxIndex];
lastTime = System.currentTimeMillis();
Runtime.getRuntime().addShutdownHook(this);
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
void addVisit(int i) {
if (stop) {
return;
}
long now = System.currentTimeMillis();
if (TRACE && trace != null) {
int duration = (int) (now - lastTime);
try {
trace.write(i + "\t" + duration + "\r\n");
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
count[i]++;
time[lastIndex] += (int) (now - lastTime);
lastTime = now;
lastIndex = i;
}
void listUnvisited() throws Exception {
printLine('=');
print("NOT COVERED");
printLine('-');
LineNumberReader r = new LineNumberReader(new FileReader("profile.txt"));
BufferedWriter writer = new BufferedWriter(new FileWriter("notcovered.txt"));
int unvisited = 0;
int unvisitedthrow = 0;
for (int i = 0; i < maxIndex; i++) {
String line = r.readLine();
if (count[i] == 0) {
if (!line.endsWith("throw")) {
writer.write(line + "\r\n");
if(LIST_UNVISITED) {
print(line+"\r\n");
}
unvisited++;
} else {
unvisitedthrow++;
}
}
}
writer.close();
int percent = (100 * unvisited / maxIndex);
print("Not covered: " + percent + " % " + " (" + unvisited + " of "
+ maxIndex + "; throw=" + unvisitedthrow + ")");
}
void listTop(String title, int[] list, int max) throws Exception {
printLine('-');
int total = 0;
int totallines = 0;
for (int j = 0; j < maxIndex; j++) {
int l = list[j];
if (l > 0) {
total += list[j];
totallines++;
}
}
if (max == 0) {
max = totallines;
}
print(title);
print("Total: " + total);
printLine('-');
String[] text = new String[max];
int[] index = new int[max];
for (int i = 0; i < max; i++) {
int big = list[0];
int bigIndex = 0;
for (int j = 1; j < maxIndex; j++) {
int l = list[j];
if (l > big) {
big = l;
bigIndex = j;
}
}
list[bigIndex] = -(big + 1);
index[i] = bigIndex;
}
LineNumberReader r = new LineNumberReader(new FileReader("profile.txt"));
for (int i = 0; i < maxIndex; i++) {
String line = r.readLine();
int k = list[i];
if (k < 0) {
k = -(k + 1);
list[i] = k;
for (int j = 0; j < max; j++) {
if (index[j] == i) {
int percent = (100 * k / total);
text[j] = k + " " + percent + "%: " + line;
}
}
}
}
for (int i = 0; i < max; i++) {
print(text[i]);
}
}
void print(String s) {
System.out.println(s);
}
void printLine(char c) {
for (int i = 0; i < 60; i++) {
System.out.print(c);
}
print("");
}
}
/*
* 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.coverage;
import java.io.EOFException;
import java.io.IOException;
import java.io.Reader;
/**
* Helper class for the java file parser.
*/
public class Tokenizer {
private StringBuffer buffer;
private Reader reader;
private char[] buf = new char[20];
private int peekc;
private int line = 1;
private byte[] charTypes = new byte[256];
private static final byte WHITESPACE = 1;
private static final byte ALPHA = 4;
private static final byte QUOTE = 8;
private int type = TYPE_NOTHING;
public static final int TYPE_EOF = -1;
public static final int TYPE_WORD = -2;
private static final int TYPE_NOTHING = -3;
private String value;
private Tokenizer() {
wordChars('a', 'z');
wordChars('A', 'Z');
wordChars('0', '9');
wordChars('.', '.');
wordChars('+', '+');
wordChars('-', '-');
wordChars('_', '_');
wordChars(128 + 32, 255);
whitespaceChars(0, ' ');
charTypes['"'] = QUOTE;
charTypes['\''] = QUOTE;
}
public Tokenizer(Reader r) {
this();
reader = r;
}
public String getString() {
return value;
}
private void wordChars(int low, int hi) {
while (low <= hi) {
charTypes[low++] |= ALPHA;
}
}
private void whitespaceChars(int low, int hi) {
while (low <= hi) {
charTypes[low++] = WHITESPACE;
}
}
private int read() throws IOException {
int i = reader.read();
if (i != -1) {
append(i);
}
return i;
}
public void initToken() {
buffer = new StringBuffer();
}
public String getToken() {
buffer.setLength(buffer.length() - 1);
return buffer.toString();
}
private void append(int i) {
buffer.append((char) i);
}
public int nextToken() throws IOException {
byte[] ct = charTypes;
int c;
value = null;
if (type == TYPE_NOTHING) {
c = read();
if (c >= 0) {
type = c;
}
} else {
c = peekc;
if (c < 0) {
try {
c = read();
if (c >= 0) {
type = c;
}
} catch (EOFException e) {
c = -1;
}
}
}
if (c < 0) {
return type = TYPE_EOF;
}
int ctype = c < 256 ? ct[c] : ALPHA;
while ((ctype & WHITESPACE) != 0) {
if (c == '\r') {
line++;
c = read();
if (c == '\n') {
c = read();
}
} else {
if (c == '\n') {
line++;
}
c = read();
}
if (c < 0) {
return type = TYPE_EOF;
}
ctype = c < 256 ? ct[c] : ALPHA;
}
if ((ctype & ALPHA) != 0) {
initToken();
append(c);
int i = 0;
do {
if (i >= buf.length) {
char[] nb = new char[buf.length * 2];
System.arraycopy(buf, 0, nb, 0, buf.length);
buf = nb;
}
buf[i++] = (char) c;
c = read();
ctype = c < 0 ? WHITESPACE : c < 256 ? ct[c] : ALPHA;
} while ((ctype & ALPHA) != 0);
peekc = c;
value = String.copyValueOf(buf, 0, i);
return type = TYPE_WORD;
}
if ((ctype & QUOTE) != 0) {
initToken();
append(c);
type = c;
int i = 0;
// \octal needs a lookahead
peekc = read();
while (peekc >= 0 && peekc != type && peekc != '\n'
&& peekc != '\r') {
if (peekc == '\\') {
c = read();
int first = c; // to allow \377, but not \477
if (c >= '0' && c <= '7') {
c = c - '0';
int c2 = read();
if ('0' <= c2 && c2 <= '7') {
c = (c << 3) + (c2 - '0');
c2 = read();
if ('0' <= c2 && c2 <= '7' && first <= '3') {
c = (c << 3) + (c2 - '0');
peekc = read();
} else {
peekc = c2;
}
} else {
peekc = c2;
}
} else {
switch (c) {
case 'b':
c = '\b';
break;
case 'f':
c = '\f';
break;
case 'n':
c = '\n';
break;
case 'r':
c = '\r';
break;
case 't':
c = '\t';
break;
}
peekc = read();
}
} else {
c = peekc;
peekc = read();
}
if (i >= buf.length) {
char[] nb = new char[buf.length * 2];
System.arraycopy(buf, 0, nb, 0, buf.length);
buf = nb;
}
buf[i++] = (char) c;
}
if (peekc == type) {
// keep \n or \r intact in peekc
peekc = read();
}
value = String.copyValueOf(buf, 0, i);
return type;
}
if (c == '/') {
c = read();
if (c == '*') {
int prevc = 0;
while ((c = read()) != '/' || prevc != '*') {
if (c == '\r') {
line++;
c = read();
if (c == '\n') {
c = read();
}
} else {
if (c == '\n') {
line++;
c = read();
}
}
if (c < 0) {
return type = TYPE_EOF;
}
prevc = c;
}
peekc = read();
return nextToken();
} else if (c == '/') {
while ((c = read()) != '\n' && c != '\r' && c >= 0) {
// nothing
}
peekc = c;
return nextToken();
} else {
peekc = c;
return type = '/';
}
}
peekc = read();
return type = c;
}
public int getLine() {
return line;
}
}
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论