提交 bc5a2a8e authored 作者: Thomas Mueller's avatar Thomas Mueller

--no commit message

--no commit message
上级 f188e9dc
......@@ -7,6 +7,8 @@ package org.h2.test;
import java.sql.SQLException;
import java.util.Properties;
import org.h2.engine.Constants;
import org.h2.message.Message;
import org.h2.server.TcpServer;
import org.h2.test.jdbc.*;
import org.h2.test.jdbc.xa.TestXA;
......@@ -20,6 +22,7 @@ import org.h2.test.synth.TestKill;
import org.h2.test.synth.TestMulti;
import org.h2.test.synth.TestRandomSQL;
import org.h2.test.synth.TestSynth;
import org.h2.test.synth.TestTimer;
import org.h2.test.unit.TestBitField;
import org.h2.test.unit.TestCache;
import org.h2.test.unit.TestCompress;
......@@ -68,6 +71,9 @@ start cmd /k "java org.h2.test.TestAll random >testRandom.txt"
start cmd /k "java org.h2.test.TestAll btree >testBtree.txt"
start cmd /k "java org.h2.test.TestAll halt >testHalt.txt"
java org.h2.test.TestAll timer
Test for hot spots:
java -agentlib:yjpagent=sampling,noj2ee,dir=C:\temp\Snapshots org.h2.test.bench.TestPerformance -init -db 1
java -Xmx512m -Xrunhprof:cpu=samples,depth=8 org.h2.tools.RunScript -url jdbc:h2:test;TRACE_LEVEL_FILE=3;LOG=2;MAX_LOG_SIZE=1000;DATABASE_EVENT_LISTENER='org.h2.samples.ShowProgress' -user sa -script test.sql
......@@ -88,23 +94,32 @@ java -Xmx512m -Xrunhprof:cpu=samples,depth=8 org.h2.tools.RunScript -url jdbc:h2
TestAll test = new TestAll();
test.printSystem();
Constants.MAX_FILE_RETRY = 1;
/*
Before you ask support:
Query is slow
- Run ANALYSE (see documentation for details)
News: add H2 Database News
Email Subscription: If you like to get informed by email about new releases,
subscribe here. The email addresses of members are only used in this context.
Usually, only one mail every few weeks will be sent.
Email:
Negative dictionary:
Please note that
improve error message:
Table TEST not found. Possible reasons: typo; the table is in another database or schema; case mismatch (use double quotes) [42S02-46]
timer test
h2\src\docsrc\html\images\SQLInjection.txt
PostgreSQL:
--SET search_path = public, pg_catalog;
--id serial NOT NULL,
document rws / rwd
Mail http://sf.net/projects/samooha
christmas lights tests
java.lang.Exception: query was too quick; result: 0 time:968
at org.h2.test.TestBase.logError(TestBase.java:220)
at org.h2.test.db.TestCases$1.run(TestCases.java:170)
at java.lang.Thread.run(Thread.java:595)
h2\src\docsrc\html\images\SQLInjection.txt
D:\pictures\2007-email
......@@ -116,23 +131,6 @@ MySQL, PostgreSQL
http://semmle.com/
try out, find bugs
Session sess1 = DBConnection.openSession();
//Wenn Die Transaction erst nach sess2.close() gestartet wird, dann funktioniert es
Transaction t = sess1.beginTransaction();
Session sess2 = DBConnection.openSession();
//Wenn um den query eine Transaction gelegt wird, funktioniert es auch
// Transaction t2 = sess2.beginTransaction();
System.out.println("Number of animals " + sess2.createCriteria(Animal.class).list().size());
// t2.commit();
sess2.close();
Animal a = new Animal();
sess1.save(a);
sess1.flush();
t.commit();
sess1.close();
download/trace*.log
Mail P2P
DROP TABLE TEST;
......@@ -174,7 +172,8 @@ I will add this to the todo list.
Docs: Fix Quickstart
Dave Brewster (dbrewster at guidewire dot com): currency: Add a setting to allow BigDecimal extensions
Dave Brewster (dbrewster at guidewire dot com): currency:
Add a setting to allow BigDecimal extensions
Send SQL Injection solution proposal to PostgreSQL, MySQL, Derby, HSQLDB,...
......@@ -195,6 +194,8 @@ CREATE [ TEMPORARY | TEMP ] SEQUENCE name [ INCREMENT [ BY ] increment ]
[ MINVALUE minvalue | NO MINVALUE ] [ MAXVALUE maxvalue | NO MAXVALUE ]
[ START [ WITH ] start ] [ CACHE cache ] [ [ NO ] CYCLE ]
http://db.apache.org/ddlutils/ (write a H2 driver)
ant docs doesn't work
*/
/*
......@@ -365,6 +366,8 @@ SELECT COUNT(*) AS A FROM TEST GROUP BY ID HAVING A>0;
new TestMulti().runTest(test);
} else if("halt".equals(args[0])) {
new TestHaltApp().runTest(test);
} else if("timer".equals(args[0])) {
new TestTimer().runTest(test);
}
} else {
test.runTests();
......@@ -390,8 +393,6 @@ SELECT COUNT(*) AS A FROM TEST GROUP BY ID HAVING A>0;
// new TestSpeed().runTest(this);
// new TestSpeed().runTest(this);
// smallLog = big = networked = memory = ssl = textStorage = diskResult = deleteIndex = traceSystemOut = diskUndo = false;
// traceLevelFile = throttle = 0;
// big = true;
......
package org.h2.test.cases;
/*
* DatDb.java
*
* Created on 21 maggio 2007, 12.30
*
*/
//package com.impl.util;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.*;
import java.util.HashMap;
import java.util.Random;
/**
*
* @author fbi
*/
public class DatDb {
private static DatDb datdb;
static HashMap cP = new HashMap();
static Connection sharedCon ;
//private String url = "jdbc:h2:file:" + Constants.DAT_DB;
// private String url = "jdbc:h2:file:/temp/datdb;TRACE_LEVEL_FILE=3";
private String url = "jdbc:h2:file:/temp/datdb;DATABASE_EVENT_LISTENER='org.h2.samples.ShowProgress'";
/** Creates a new instance of DatDb */
protected DatDb() {
try {
long t1 = System.currentTimeMillis();
Class.forName("org.h2.Driver");
System.out.println (" getConnection --> ");
//This is a 'special' connection used only to execute select statements (no transactions)
sharedCon = DriverManager.getConnection(url, "sa", "");
System.out.println (" getConnection <-- " + (System.currentTimeMillis()- t1));
sharedCon.setReadOnly(true);
} catch (Exception e) {
//Util.logThrowable(e);
System.out.println(" error: " + e.getMessage());
}
}
public static synchronized DatDb getInstance() {
if (datdb == null) {
datdb = new DatDb();
}
return datdb;
}
public void init (String tableName) {
//String sc = ma.substring(ma.lastIndexOf("/")+1);
try {
Connection con = DriverManager.getConnection(url, "sa", "");
cP.put(tableName, con);
createTable(con, tableName);
} catch (Exception e) {
//Util.logThrowable(e);
}
}
public void save(String tableName, String key, String xml) {
Connection con = null;
//String tableName = ma.substring(ma.lastIndexOf("/")+1);
try {
con = (Connection) cP.get(tableName);
if (con == null) throw new RuntimeException ("Unable to find the connection");
con.setAutoCommit(false);
PreparedStatement stm = null;
stm = con.prepareStatement("delete from "+tableName+" where fname = ?");
stm.setString(1, key);
stm.executeUpdate();
stm.close();
stm = con.prepareStatement("insert into "+tableName+" (fname, gendate, dat) values(?,?,?)");
stm.setString(1, key);
stm.setLong(2, System.currentTimeMillis());
//--- original code ---->>>> stm.setObject(3, com.fw.util.Util.compressString(xml));
stm.setObject(3, xml);
stm.executeUpdate();
con.commit();
} catch (Exception e) {
try {
con.rollback();
} catch (SQLException ex) {
ex.printStackTrace();
}
// Util.logThrowable(e);
}
}
public long getGenDate (String tableName, String key) {
Connection con = null;
long gendate = 0;
PreparedStatement stm = null;
try {
stm = sharedCon.prepareStatement("select gendate from "+tableName+" where fname = ?");
stm.setString(1, key);
ResultSet rs = stm.executeQuery();
while (rs.next()) {
gendate = rs.getLong(1);
}
} catch (Exception e) {
//Util.logThrowable(e);
} finally {
try {
stm.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
//System.out.println ("getGenDate table "+tableName+" key "+key+" returns "+gendate);
return gendate;
}
public boolean containsKey(String tableName, String key) {
Connection con = null;
boolean b = false;
PreparedStatement stm = null;
try {
stm = sharedCon.prepareStatement("select fname from "+tableName+" where fname = ?");
stm.setString(1, key);
ResultSet rs = stm.executeQuery();
while (rs.next()) {
b = true;
}
} catch (Exception e) {
//Util.logThrowable(e);
} finally {
try {
stm.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
//System.out.println ("containsKey table "+tableName+" key "+key+" returns "+b);
return b;
}
public String getDat(String tableName, String key) {
String ret = null;
byte buf[] = null;
PreparedStatement stm = null;
try {
stm = sharedCon.prepareStatement("select dat from "+tableName+" where fname = ?");
stm.setString(1, key);
ResultSet rs = stm.executeQuery();
while (rs.next()) {
buf = rs.getBytes(1);
}
if (buf == null) {
//System.out.println (" NULL BUF for table "+tableName+" KEY "+ key);
return ret;
}
// ------->>>> Original code ------<<<< ret = Util.uncompressString(buf);
ret = new String(buf);
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
stm.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
return ret;
}
private void createTable(Connection con, String tableName) {
ResultSet rs = null;
try {
DatabaseMetaData dmd = con.getMetaData();
rs = dmd.getTables(null, null, null, null);
String temp = null;
while (rs.next()) {
temp = rs.getString(3);
if (temp.equalsIgnoreCase(tableName)) {
return;
}
}
} catch (Exception e) {
//Util.logThrowable(e);
}
try {
java.sql.Statement stm = con.createStatement();
stm.execute("CREATE TABLE "+tableName+" (fname varchar(80) primary key, gendate bigint, dat varchar) ");
System.out.println (" Table "+tableName+" created");
} catch (Exception e) {
// Util.logThrowable(e);
}
}
public void close(String tableName) {
Connection c = (Connection) cP.remove(tableName);
try {
c.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
//-------------------------------------- TEST START ------------------------
public static void main(String ar[]) {
System.out.println (" Starting ");
DatDb db = new DatDb();
db.go();
}
private void go () {
/*
* Please change the values as needed.
* The test I've made uses MAX_REC = 400000
* and MAX_TAB = 50,
* 20.000.000 records!
*/
int MAX_REC = 400000;
int MAX_TAB = 10;
String tableName = null;
long start = System.currentTimeMillis();
System.out.println(" Start test ");
long trec = 0;
for (int j = 0; j < MAX_TAB; j++) {
tableName = "n"+j;
try {
Connection con = DriverManager.getConnection(url, "sa","");
cP.put(tableName, con);
createTable(con, tableName);
} catch (Exception e ){ e.printStackTrace(); }
long t1 = System.currentTimeMillis();
trec = t1;
for (int k = 0; k < MAX_REC; k++ ){
this.save(tableName,"this_is_a_possible_key_value"+k, "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm");
if (k > 0 && (k % 10000) == 0) {
System.out.println(" added more 10000 records to "+tableName+" spent "+ (System.currentTimeMillis()-trec)+ " K "+k);
trec = System.currentTimeMillis();
}
}
close(tableName);
System.out.println(" TABLE "+tableName+" completed with "+MAX_REC +" millis "+ (System.currentTimeMillis() - t1));
}
// Now, try to get back some raws
int tkey = 0;
int rkey = 0;
Random rnd = new Random();
for (int l = 0; l < 100; l++) {
start = System.currentTimeMillis();
tkey = rnd.nextInt(MAX_TAB);
rkey = rnd.nextInt(MAX_REC);
this.getDat("n"+tkey, "questa_essere_la_chivae_numero_"+rkey);
// System.out.println ("estract dat key "+rkey+" from table n"+ tkey+" in millis "+ (System.currentTimeMillis() - start));
}
System.out.println (" exercise end" );
try {
sharedCon.close();
} catch (SQLException ex) {
ex.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.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.h2.tools.DeleteDbFiles;
/*
1) the trace has one function "Enabling the Trace Option at Runtime by
Manually Creating a File". how could I disable this function? I don't
want the user could use one file to trace my database info...
*/
/*
D:\data\h2\bin>java -Xrunhprof:cpu=samples,depth=8 org.h2.test.TestAll
Java: 1.5.0_10-b03, Java HotSpot(TM) Client VM, Sun Microsystems Inc.
Env: Windows XP, x86, 5.1, Service Pack 2, \ ; \r\n CH de Cp1252
time to connect: 984ms
h2.lobFilesInDirectories: true
h2.lobFilesPerDirectory: 256
writing 1000: 5688ms
writing 2000: 4062ms
writing 3000: 5766ms
writing 4000: 3531ms
writing 5000: 3860ms
writing 6000: 8734ms
writing 7000: 3703ms
writing 8000: 3906ms
writing 9000: 11250ms
writing 10000: 3813ms
time to complete writing: 54313ms
Dumping CPU usage by sampling running threads ... done.
h2.lobFilesInDirectories: false
time to complete writing: 49828ms
time to complete reading: 2953ms
time to connect: 984ms
h2.lobFilesInDirectories: true
h2.lobFilesPerDirectory: 256
time to complete writing: 98687ms
time to complete reading: 2625ms
time to connect: 47ms
FIXED:
h2.lobFilesPerDirectory: 256
time to complete writing: 45656ms
h2.lobFilesPerDirectory: 1024
time to complete writing: 158204ms
h2.lobFilesInDirectories: false
time to complete writing: 17187ms
h2.lobFilesInDirectories: true
h2.lobFilesPerDirectory: 16
writing 1000: 5610ms
writing 2000: 1984ms
writing 3000: 3000ms
writing 4000: 6844ms
writing 5000: 7734ms
writing 6000: 11578ms
writing 7000: 6407ms
writing 8000: 6812ms
writing 9000: 15344ms
writing 10000: 7375ms
time to complete writing: 72688ms
time to complete writing: 74578ms
time to complete reading: 2734ms
time to connect: 47ms
*/
public class TestBlobDir {
// Start h2 start parameters:
// -Dh2.lobFilesInDirectories=true -Dh2.lobFilesPerDirectory=16
public static void main(String[] args) throws Exception {
System.setProperty("h2.lobFilesInDirectories", "true");
System.setProperty("h2.lobFilesPerDirectory", "256");
TestBlobDir blobtest = new TestBlobDir();
DeleteDbFiles.execute(".", "testabc", true);
Connection conn = blobtest.getConnection();
long count;
count = 10000;
blobtest.printParameters(conn);
blobtest.insertBlobs(conn, 1, count, 500);
// blobtest.testBlobs(conn, 1, count);
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
// test time to build up a new connection
// conn = blobtest.getConnection();
// try {
// conn.close();
// } catch (SQLException e) {
// e.printStackTrace();
// }
}
public Connection getConnection() {
Connection conn = null;
try {
Class.forName("org.h2.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
// String url = "jdbc:h2:tcp://localhost:9092/test123456789012345678901234567890";
// String url = "jdbc:h2:test123456789012345678901234567890";
String url = "jdbc:h2:testabc";
Driver driver = DriverManager.getDriver(url);
driver.toString();
long start = System.currentTimeMillis();
conn = DriverManager.getConnection(url, "sa", "");
System.out.println("time to connect: " + (System.currentTimeMillis() - start + "ms"));
} catch (SQLException e) {
throw new RuntimeException(e);
}
return conn;
}
public void printParameters(Connection conn) {
String sqlStmt = "SELECT * FROM INFORMATION_SCHEMA.SETTINGS WHERE NAME LIKE 'h2.lob%';";
try {
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sqlStmt);
while (rs.next()) {
System.out.print(rs.getString("name") + ": ");
System.out.println(rs.getString("value"));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public void insertBlobs(Connection conn, long from, long to, int blobLength) {
byte[] byteblob = new byte[blobLength];
for (int i = 0; i < byteblob.length; i++) {
byteblob[i] = 'b';
}
// System.out.println("Inserting blobs of length " + blobLength + " from " + from + " to " + to);
String sqlStmt = "INSERT INTO blobtable" + " (count, blobtest) VALUES (?1, ?2)";
long startComulative = -1;
PreparedStatement prepStmt = null;
try {
conn.createStatement().execute("DROP TABLE blobtable IF EXISTS");
conn.createStatement().execute("CREATE TABLE blobtable(count INT4, blobtest BLOB, PRIMARY KEY (count))");
prepStmt = conn.prepareStatement(sqlStmt);
startComulative = System.currentTimeMillis();
long start = System.currentTimeMillis();
for (long i = 1; i <= to; i++) {
prepStmt.setLong(1, i);
InputStream blob = new ByteArrayInputStream(byteblob);
prepStmt.setBinaryStream(2, blob, -1);
prepStmt.execute();
if (i % 1000 == 0) {
System.out.println("writing " + i + ": " + (System.currentTimeMillis() - start + "ms"));
start = System.currentTimeMillis();
}
}
} catch (SQLException e) {
e.printStackTrace();
}
System.out.println("time to complete writing: " + (System.currentTimeMillis() - startComulative) + "ms");
if (prepStmt != null) {
try {
prepStmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public void testBlobs(Connection conn, long from, long to) {
// System.out.println("Reading blobs" + " from " + from + " to " + to);
ResultSet rs = null;
byte[] data;
BufferedInputStream imageInputStream = null;
String sqlStmt = "SELECT * FROM blobtable where count=?1";
long startComulative = -1;
PreparedStatement prepStmt = null;
try {
prepStmt = conn.prepareStatement(sqlStmt);
// long start = System.currentTimeMillis();
startComulative = System.currentTimeMillis();
for (long i = 1; i <= to; i++) {
prepStmt.setLong(1, i);
rs = prepStmt.executeQuery();
if (rs.next()) {
int size = (int) rs.getBlob("blobtest").length();
imageInputStream = new BufferedInputStream(rs.getBinaryStream("blobtest"));
try {
DataInputStream in = new DataInputStream(imageInputStream);
data = new byte[size];
in.readFully(data);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
} else {
System.out.println("error, no data");
}
// if (i % 1000 == 0) {
// System.out.println("reading " + i + ": " + (System.currentTimeMillis() - start + "ms"));
// start = System.currentTimeMillis();
// }
}
} catch (SQLException e) {
e.printStackTrace();
}
System.out.println("time to complete reading: " + (System.currentTimeMillis() - startComulative) + "ms");
return;
}
}
/*
* 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.*;
import java.text.*;
public class TestCalendar {
static Connection conn;
static Statement stat;
public static void main(String[] args) throws Exception {
// Firstly, demonstrate Java behaviour with 'illegal' times:
// Change default timezone...same as setting the Windows timezone in Control Panel.
// TimeZone.setDefault(TimeZone.getTimeZone("PST"));
TimeZone.setDefault(TimeZone.getTimeZone("Australia/Melbourne"));
// String s;
// Timestamp t;
//
// System.out.println("Watch carefully: this is what Java does with 'illegal' local times:");
//
// s = "2006-10-29 01:30:00"; // Valid
// t = Timestamp.valueOf(s);
// System.out.println("Instantiated: " + s + " Local: " + t.toString());
//
// s = "2006-10-29 01:59:59"; // Valid
// t = Timestamp.valueOf(s);
// System.out.println("Instantiated: " + s + " Output: " + t.toString());
//
// s = "2006-10-29 02:00:00"; // Illegal time...does not 'exist'
// t = Timestamp.valueOf(s);
// System.out.println("Instantiated: " + s + " Output: " + t.toString());
//
// s = "2006-10-29 02:30:00"; // Illegal time...does not 'exist'
// t = Timestamp.valueOf(s);
// System.out.println("Instantiated: " + s + " Output: " + t.toString());
//
// s = "2006-10-29 02:59:59"; // Illegal time...does not 'exist'
// t = Timestamp.valueOf(s);
// System.out.println("Instantiated: " + s + " Output: " + t.toString());
//
// s = "2006-10-29 03:00:00"; // Valid again
// t = Timestamp.valueOf(s);
// System.out.println("Instantiated: " + s + " Output: " + t.toString());
//
// System.out.println();
// System.out.println();
// String url = "jdbc:pervasive://maximus:1583/FILD602";
// String driver = "com.pervasive.jdbc.v2.Driver";
// String uid = "Master"; String pwd = "master";
// String createquery = "create table TT (RECID INTEGER, MYDATETIME DATETIME, PRIMARY KEY(RECID))";
// String insertquery = "insert into TT values(1, '2006-10-29 02:00:00')";
// String selectquery = "select MYDATETIME from TT";
// String url = "jdbc:h2:mem:";
// String driver = "org.h2.Driver";
// String user = "sa";
// String password = "sa";
String url = "jdbc:h2:mem:";
String driver = "org.h2.Driver";
String user = "sa";
String password = "sa";
testDb(driver, url, user, password);
testDb("org.postgresql.Driver", "jdbc:postgresql:jpox2", "sa", "sa");
// String url = "jdbc:sybase:Tds:atlas:2638/toptier";
// String driver = "com.sybase.jdbc3.jdbc.SybDriver";
// String uid = "dba"; String pwd = "sql";
// String createquery = "create table TT (RECID INTEGER, MYDATETIME DATETIME, PRIMARY KEY(RECID))";
// String insertquery = "insert into TT values(1, '2006-10-29 02:00:00')";
// String selectquery = "select MYDATETIME from TT";
}
private static void testDb(String driver, String url, String user, String password) throws Exception {
Class.forName(driver);
conn = DriverManager.getConnection(url, user, password);
stat = conn.createStatement();
String createquery = "create table TT (RECID INTEGER, MYDATETIME TIMESTAMP, PRIMARY KEY(RECID))";
// String insertquery = "insert into TT values(1, '2006-10-28T16:00:00')";
// String insertquery = "insert into TT values(1, '2006-10-28T16:00:00+00:00')";
// String insertquery = "insert into TT values(1, '2006-10-28T16:00:00')";
// String insertquery = "insert into TT values(1, '2006-01-28T16:00:00')";
String insertquery = "insert into TT values(1, '2006-01-20T16:00:00+11:00')";
// String insertquery = "insert into TT values(1, '2006-10-28T16:00:00+10:00')";
// String insertquery = "insert into TT values(1, '2006-10-28T16:00:00+09:00')";
String selectquery = "select MYDATETIME from TT";
try {
stat.execute("DROP TABLE TT");
} catch (SQLException e) {
// ignore
}
stat.execute(createquery);
stat.execute("delete from TT");
stat.execute(insertquery);
System.out.println("Database timestamp retrieval test.");
ResultSet results = stat.executeQuery(selectquery);
if (results != null) {
Calendar c = Calendar.getInstance();
DateFormat df;
c.setTimeZone(TimeZone.getTimeZone("UTC"));
while (results.next()) {
// Firstly exercise the default behaviours
// Because the value in the database is an 'illegal' local time in Melbourne
// we cannot expect Java to output it correctly. Java 1.5 adds an hour to it to make it a 'legal'
// time.
Timestamp t = results.getTimestamp(1);
System.out.println("Interpret db value as default tz: " + t.toString());
df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); // DateFormat.getDateTimeInstance();
System.out.println("Interpret db value as default: " + df.format(t) + " <<<Should display as UTC, not local");
// Second test: instruct the jdbc driver to
// interpret the time as a UTC time, in which case it IS legal.
// It should be output as the correct UTC value (i.e. same as what's in the database)
t = results.getTimestamp(1, c);
// df.setCalendar(c);
System.out.println("Interpret db value as UTC: " + df.format(t) + " <<<Should display as UTC, not local");
df.setCalendar(c);
System.out.println("Interpret db value as UTC: " + df.format(t) + " <<<Should display as UTC, not local");
}
}
stat.close();
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 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 stat = conn.createStatement();
stat.executeUpdate(
"DROP TABLE IF EXISTS test");
stat.executeUpdate(
"SET COLLATION OFF");
stat.executeUpdate(
"CREATE TABLE test (id INT IDENTITY, code VARCHAR(20) NOT NULL, parentId INT)");
stat.executeUpdate(
"CREATE INDEX test_code ON test(code)");
PreparedStatement prep2 = conn.prepareStatement(
"INSERT INTO test (code,parentId) VALUES (?,NULL)");
PreparedStatement prep3 = 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) {
prep2.setString(1, Integer.toBinaryString(i));
prep2.executeUpdate();
} else {
prep3.setString(1, Integer.toBinaryString(i));
prep3.setString(2, Integer.toBinaryString(i % 100 + 1));
prep3.executeUpdate();
}
}
System.out.println("INSERT w/o Collation: " + (System.currentTimeMillis()-time));
testWithCollation();
}
public void testWithCollation() throws Exception {
Statement stat = conn.createStatement();
stat.executeUpdate(
"DROP TABLE IF EXISTS test");
stat.executeUpdate(
"SET COLLATION ENGLISH STRENGTH PRIMARY");
stat.executeUpdate(
"CREATE TABLE test (id INT IDENTITY, code VARCHAR(20) NOT NULL, parentId INT)");
stat.executeUpdate(
"CREATE INDEX test_code ON test(code)");
PreparedStatement prep = conn.prepareStatement(
"INSERT INTO test (code,parentId) VALUES (?,NULL)");
PreparedStatement prep2 = 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) {
prep.setString(1, Integer.toBinaryString(i));
prep.executeUpdate();
} else {
prep2.setString(1, Integer.toBinaryString(i));
prep2.setString(2, Integer.toBinaryString(i % 100 + 1));
prep2.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 TestCompatibilityMySQL {
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.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
/*
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");
String url = "jdbc:h2:test";
Connection conn = DriverManager.getConnection(url, "sa", "sa");
PreparedStatement prep = conn.prepareStatement("SELECT CURRENT_TIMESTAMP()");
ResultSet rs = prep.executeQuery();
rs.next();
System.out.println(rs.getString(1));
Thread.sleep(50);
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.*;
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(TS TIMESTAMP)");
PreparedStatement prep = conn.prepareStatement(
"INSERT INTO ts_trial(TS) 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 TS FROM ts_trial");
rs.next();
System.out.println("Timestamp: " + rs.getTimestamp("TS"));
rs.next();
System.out.println("Date: " + rs.getTimestamp("TS"));
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.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import org.h2.tools.Server;
public class TestHibernateClob {
public static void main(String[] a) throws Exception {
mainClobSpeed();
mainClobSpeed();
mainClobSpeed();
}
static void mainClobSpeed() throws Exception {
System.out.println("starting test...");
org.h2.tools.DeleteDbFiles.execute(null, "test", true);
Server server = Server.createTcpServer(new String[0]);
server.start();
Connection conn = DriverManager.getConnection("jdbc:h2:tcp://localhost/test", "sa", "sa");
conn.createStatement().execute("CREATE TABLE TEST(C CLOB)");
PreparedStatement prep = conn.prepareStatement("INSERT INTO TEST VALUES(?)");
long time = System.currentTimeMillis();
for(int i=0; i<10000; i++) {
Reader r = new StringReader("Hello World");
prep.setCharacterStream(1, r, -1);
prep.execute();
}
time = System.currentTimeMillis() - time;
System.out.println("time: " + time);
conn.close();
server.stop();
// 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, 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 (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 c_.ID as ID0_0_, c_.DATA as S2, c_.CLOB_DATA as CLOB3_0_0_ from CLOB_ENTITY c_ where c_.ID=?");
// prep2.setLong(1, 1);
// ResultSet rs1 =
// prep2.executeQuery();
// rs1.next();
// System.out.println("s2: " + rs1.getCharacterStream("S2"));
// 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.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;
/**
* Destroyer application ;->
*
* @author Maciej Wegorkiewicz
*/
public class TestKiller {
public static void main(String[] args) throws Exception {
testWith("org.h2.Driver", "jdbc:h2:test", "sa", "sa");
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.apache.derby.jdbc.EmbeddedDriver", "jdbc:derby:test3;create=true", "sa", "sa");
}
public static class TestBigDecimal extends BigDecimal {
public TestBigDecimal(String s) {
super(s);
}
private static final long serialVersionUID = 6309132662083006892L;
public int compareTo(BigDecimal obj) {
return -super.compareTo(obj);
}
public String toString() {
throw new NullPointerException();
}
}
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);
try {
Statement stmt = conn.createStatement();
try {
conn.createStatement().execute("DROP TABLE TESTTAB");
} catch(SQLException e) {
// ignore
}
stmt.execute("CREATE TABLE TESTTAB(VL DECIMAL(16,6) PRIMARY KEY)");
stmt.close();
PreparedStatement prep = conn.prepareStatement("INSERT INTO TESTTAB VALUES (?)");
prep.setBigDecimal(1, new TestBigDecimal("1"));
prep.execute();
prep.setBigDecimal(1, new TestBigDecimal("2"));
prep.execute();
prep.setBigDecimal(1, new TestBigDecimal("3"));
prep.execute();
prep.close();
ResultSet rs = conn.createStatement().executeQuery("SELECT * FROM TESTTAB ORDER BY VL");
while(rs.next()) {
System.out.println("VL:" + rs.getString("VL"));
}
try {
conn.createStatement().executeQuery("SHUTDOWN");
} catch(SQLException e) {
// ignore
}
conn.close();
Class.forName(driver);
conn = DriverManager.getConnection(url, user, password);
rs = conn.createStatement().executeQuery("SELECT * FROM TESTTAB ORDER BY VL");
while(rs.next()) {
System.out.println("VL:" + rs.getString("VL"));
}
conn.close();
} catch(Throwable t) {
t.printStackTrace();
} finally {
if(conn != null) {
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.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 idx_id 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 idx_id on test(id)");
} else {
stat.execute("create unique index idx_id 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();
}
}
package org.h2.test.cases;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class TestMemoryDb {
public static void main(String[] args) throws Exception {
Class.forName("org.h2.Driver");
String url = "jdbc:h2:mem:EventDB";
String user = "sa";
String password = "sa";
Connection conn1 = DriverManager.getConnection(url, user, password);
Statement stat1 = conn1.createStatement();
stat1.execute("create table test(id int)");
Connection conn2 = DriverManager.getConnection(url, user, password);
Statement stat2 = conn2.createStatement();
stat2.executeQuery("select * from test");
conn1.close();
conn2.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 TestObject {
public static void main(String[] args) throws Exception {
testWith("org.hsqldb.jdbcDriver", "jdbc:hsqldb:test", "sa", "");
// 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");
}
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);
conn.setAutoCommit(true);
Statement st = conn.createStatement();
try {
st.executeUpdate("DROP TABLE test_object_table");
} catch (SQLException e) {
// ignore
}
// st.executeUpdate("CREATE TABLE test_object_table(id INTEGER NOT NULL, object0 JAVA_OBJECT NOT NULL, PRIMARY KEY(id))");
st.executeUpdate("CREATE TABLE test_object_table(id INTEGER NOT NULL, object0 OBJECT NOT NULL, PRIMARY KEY(id))");
// st.executeUpdate("CREATE TABLE test_object_table(id INTEGER NOT NULL, object0 OID NOT NULL, PRIMARY KEY(id))");
PreparedStatement ps = conn.prepareStatement("INSERT INTO test_object_table values(?, ?)");
ps.setInt(1, 1);
ps.setObject(2, new Integer(3));
ps.executeUpdate();
ResultSet rs = st.executeQuery("select * from test_object_table");
while (rs.next()) {
int id = rs.getInt("id");
Object object0 = rs.getObject("object0");
System.out.println("id = " + id + ", object0 = " + object0.getClass().getName() + " / " + object0);
}
rs.close();
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[] list = {
// 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 conn = DriverManager.getConnection("jdbc:h2:mem:", "sa", "");
conn.setAutoCommit(true);
conn.createStatement().executeUpdate("CREATE TABLE TestOtherJDBC (testData OTHER)");
System.out.println("table created");
PreparedStatement stmt = conn.prepareStatement("INSERT INTO TestOtherJDBC (testData) VALUES (?)");
for (int i = 0; i < list.length; i++) {
System.out.println(list[i].getClass().getName() + "\t" + list[i]);
stmt.setObject(1, list[i], Types.OTHER);
stmt.executeUpdate();
}
System.out.println("inserted");
ResultSet rs = conn.createStatement().executeQuery("SELECT testData 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 idx_data 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.cases;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import org.h2.tools.DeleteDbFiles;
public class TestWithRecursive {
public static void main(String[] args) throws Exception {
Class.forName("org.h2.Driver");
DeleteDbFiles.execute(".", "test", true);
String url = "jdbc:h2:test";
Connection conn = DriverManager.getConnection(url, "sa", "sa");
Statement stat = conn.createStatement();
stat.execute("create table parent(id int primary key, parent int)");
stat.execute("insert into parent values(1, null), (2, 1), (3, 1)");
ResultSet rs = stat.executeQuery(
"with test_view(id, parent) as \n"+
"select id, parent from parent where id = 1 \n"+
"union all select parent.id, parent.parent from test_view, parent \n"+
"where parent.parent = test_view.id \n" +
"select * from test_view");
System.out.println("query:");
while(rs.next()) {
System.out.println(rs.getString(1));
}
stat.execute("drop view if exists test_view");
System.out.println("prepared:");
PreparedStatement prep = conn.prepareStatement(
"with test_view(id, parent) as \n"+
"select id, parent from parent where id = ? \n"+
"union all select parent.id, parent.parent from test_view, parent \n"+
"where parent.parent = test_view.id \n" +
"select * from test_view");
prep.setInt(1, 1);
rs = prep.executeQuery();
while(rs.next()) {
System.out.println(rs.getString(1));
}
conn.close();
}
}
......@@ -15,6 +15,7 @@ import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.sql.Types;
import org.h2.test.TestBase;
......@@ -27,6 +28,7 @@ public class TestPreparedStatement extends TestBase {
deleteDb("preparedStatement");
Connection conn = getConnection("preparedStatement");
testDate(conn);
testArray(conn);
testUUIDGeneratedKeys(conn);
testSetObject(conn);
......@@ -95,6 +97,16 @@ public class TestPreparedStatement extends TestBase {
stat.execute("DROP TABLE TEST");
}
private void testDate(Connection conn) throws Exception {
PreparedStatement prep = conn.prepareStatement("SELECT ?");
Timestamp ts = Timestamp.valueOf("2001-02-03 04:05:06");
prep.setObject(1, new java.util.Date(ts.getTime()));
ResultSet rs = prep.executeQuery();
rs.next();
Timestamp ts2 = rs.getTimestamp(1);
check(ts.toString(), ts2.toString());
}
private void testPreparedSubquery(Connection conn) throws Exception {
Statement s = conn.createStatement();
s.executeUpdate("CREATE TABLE TEST(ID IDENTITY, FLAG BIT)");
......@@ -457,7 +469,7 @@ public class TestPreparedStatement extends TestBase {
check(rs.getObject(11).toString(), "04:05:06");
check(rs.getObject(11).equals(java.sql.Time.valueOf("04:05:06")));
check(rs.getObject(12).equals(java.sql.Timestamp.valueOf("2001-02-03 04:05:06.123456789")));
check(rs.getObject(13).equals(java.sql.Date.valueOf("2001-02-03")));
check(rs.getObject(13).equals(java.sql.Timestamp.valueOf("2001-02-03 00:00:00")));
check((byte[])rs.getObject(14), new byte[]{10, 20, 30});
check(rs.getObject(15).equals(new Character('a')));
check(rs.getObject(16).equals(java.sql.Date.valueOf("2001-01-02")));
......
/*
* 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.poweroff;
import java.io.File;
......
......@@ -166,7 +166,7 @@ public class RandomGen {
buff.append('-');
buff.append(getInt(12) + 1);
buff.append('-');
buff.append(getInt(29) + 1);
buff.append(getInt(28) + 1);
buff.append(' ');
buff.append(getInt(24));
buff.append(':');
......
......@@ -34,7 +34,8 @@ public abstract class TestHalt extends TestBase {
private int errorId;
private int sequenceId;
private static final String DATABASE_NAME = "halt";
private static final String TRACE_FILE_NAME = BASE_DIR + "/haltTrace.trace.db";
static final String DIR = "dataHalt";
private static final String TRACE_FILE_NAME = "haltTrace.trace.db";
abstract void testInit() throws Exception;
abstract void testCheckAfterCrash() throws Exception;
......@@ -106,7 +107,9 @@ public abstract class TestHalt extends TestBase {
protected void trace(String s, Exception e) {
FileWriter writer = null;
try {
writer = new FileWriter(TRACE_FILE_NAME, true);
File f = new File(BASE_DIR + "/" + TRACE_FILE_NAME);
f.getParentFile().mkdirs();
writer = new FileWriter(f, true);
PrintWriter w = new PrintWriter(writer);
s = dateFormat.format(new Date()) + ": " + s;
w.println(s);
......@@ -123,7 +126,7 @@ public abstract class TestHalt extends TestBase {
private void runTest() throws Exception {
traceOperation("delete database -----------------------------");
DeleteDbFiles.execute(BASE_DIR, DATABASE_NAME, true);
new File(TRACE_FILE_NAME).delete();
new File(BASE_DIR + "/" + TRACE_FILE_NAME).delete();
connect();
testInit();
......@@ -148,7 +151,7 @@ public abstract class TestHalt extends TestBase {
catcher.start();
String s = catcher.readLine(5000);
if(s == null) {
throw new IOException("No reply from process");
throw new IOException("No reply from process, command: " + command);
} else if(s.startsWith("READY")) {
traceOperation("got reply: " + s);
}
......@@ -296,7 +299,7 @@ public abstract class TestHalt extends TestBase {
public TestBase init(TestAll conf) throws Exception {
super.init(conf);
BASE_DIR = "dataHalt";
BASE_DIR = DIR;
return this;
}
......
......@@ -8,17 +8,13 @@ import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import org.h2.test.TestAll;
import org.h2.test.TestBase;
import org.h2.test.db.TestScript;
public class TestHaltApp extends TestHalt {
private int rowCount;
public static void main(String[] args) throws Exception {
BASE_DIR = TestHalt.DIR;
new TestHaltApp().start(args);
}
......
......@@ -28,6 +28,7 @@ public class CheckTextFiles {
boolean hasError;
void run() throws Exception {
System.out.println(getClass().getName());
String baseDir = "src";
check(new File(baseDir));
if(hasError) {
......
......@@ -17,7 +17,6 @@ import java.util.HashMap;
import org.h2.bnf.Bnf;
import org.h2.server.web.PageParser;
import org.h2.tools.indexer.Indexer;
import org.h2.util.IOUtils;
import org.h2.util.JdbcUtils;
import org.h2.util.StringUtils;
......@@ -35,6 +34,7 @@ public class GenerateDoc {
Bnf bnf;
void run(String[] args) throws Exception {
System.out.println(getClass().getName());
for(int i=0; i<args.length; i++) {
if(args[i].equals("-in")) {
inDir = args[++i];
......@@ -42,13 +42,10 @@ public class GenerateDoc {
outDir = args[++i];
}
}
Class.forName("org.h2.Driver");
conn = DriverManager.getConnection("jdbc:h2:.");
conn = DriverManager.getConnection("jdbc:h2:mem:");
new File(outDir).mkdirs();
bnf = Bnf.getInstance(null);
map("commands", "SELECT * FROM INFORMATION_SCHEMA.HELP WHERE SECTION LIKE 'Commands%' ORDER BY ID");
map("commandsDML", "SELECT * FROM INFORMATION_SCHEMA.HELP WHERE SECTION='Commands (DML)' ORDER BY ID");
map("commandsDDL", "SELECT * FROM INFORMATION_SCHEMA.HELP WHERE SECTION='Commands (DDL)' ORDER BY ID");
......@@ -61,14 +58,10 @@ public class GenerateDoc {
map("functionsSystem", "SELECT * FROM INFORMATION_SCHEMA.HELP WHERE SECTION = 'Functions (System)' ORDER BY ID");
map("functionsAll", "SELECT * FROM INFORMATION_SCHEMA.HELP WHERE SECTION LIKE 'Functions%' ORDER BY SECTION, ID");
map("dataTypes", "SELECT * FROM INFORMATION_SCHEMA.HELP WHERE SECTION LIKE 'Data Types%' ORDER BY SECTION, ID");
process("grammar");
process("functions");
process("datatypes");
conn.close();
Indexer.main(new String[0]);
}
void process(String fileName) throws Exception {
......
......@@ -443,6 +443,18 @@ unavailable repeating sponsored indonesian yuliantoro joko indonesia unlike
truncating ronni ptn avalon nielsen hammant picked sequoia continuent deebee paul
lister testa testb tar von
amazing timer allowing programmers pictures scramble portal bots tempted legacy
semicolons luckily involving die prevalent manipulating risks unmapped solutions
preventing prevented retry superfluous varying tend revolutions emit technically
excessive among lazy synchronous technique patented ability cycle difficult rejects
animal achieves touch produced smallest vulnerabilities descriptive verify thinks
potential lose novel handy filtering wonder story cool prevents animals wrote
tier seen young providing extreme images apple rpm thousand compromise
sandbox greatest whatever placeholder creative leak hacker benefits station
million prevention stuck titles fiche blogs showed widespread cut placeholders
graph prohibit confusing clever automated nutshell scriptella etl tamava semmle
googlegroups guidewire thecodist captcha brewster semmle ddlutils analyse dave
maxvalue samooha dbrewster minvalue darwin
### check those again:
populate slowly xacon inser maxbqualsize counter regards attaching official xatest
......
......@@ -35,6 +35,11 @@ public class Indexer {
private static final int MAX_RELATIONS = 20;
public static void main(String[] args) throws Exception {
new Indexer().run(args);
}
void run(String[] args) throws Exception {
System.out.println(getClass().getName());
String dir = "docs";
String destDir = "docs/html";
for(int i=0; i<args.length; i++) {
......@@ -44,12 +49,9 @@ public class Indexer {
destDir = args[++i];
}
}
Indexer app = new Indexer();
File file = new File(dir);
System.out.println("indexing " + file.getCanonicalPath());
// File file = new File("C:\\Programs\\selfhtml81");
// File file = new File("C:\\Programme\\selfhtml81");
app.setNoIndex(new String[] {
setNoIndex(new String[] {
"index.html",
"html/header.html",
"html/search.html",
......@@ -63,19 +65,19 @@ public class Indexer {
"javadoc/overview-summary.html",
"javadoc/serialized-form.html"
});
app.output = new PrintWriter(new FileWriter(destDir + "/index.js"));
app.readPages("", file, 0);
app.output.println("var pages=new Array();");
app.output.println("var ref=new Array();");
app.output.println("function Page(title, file) { this.title=title; this.file=file; }");
app.output.println("function load() {");
app.sortWords();
app.removeOverflowRelations();
app.sortPages();
app.listPages();
app.listWords();
app.output.println("}");
app.output.close();
output = new PrintWriter(new FileWriter(destDir + "/index.js"));
readPages("", file, 0);
output.println("var pages=new Array();");
output.println("var ref=new Array();");
output.println("function Page(title, file) { this.title=title; this.file=file; }");
output.println("function load() {");
sortWords();
removeOverflowRelations();
sortPages();
listPages();
listWords();
output.println("}");
output.close();
}
private void setNoIndex(String[] strings) {
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论