提交 3e2897c4 authored 作者: Thomas Mueller's avatar Thomas Mueller

--no commit message

--no commit message
上级 7db34fd8
/*
* 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.db;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import org.h2.test.TestBase;
public class TestAutoRecompile extends TestBase {
public void test() throws Exception {
deleteDb("autoRecompile");
Connection conn=getConnection("autoRecompile");
Statement stat = conn.createStatement();
stat.execute("CREATE TABLE TEST(ID INT PRIMARY KEY)");
PreparedStatement prep = conn.prepareStatement("SELECT * FROM TEST");
check(prep.executeQuery().getMetaData().getColumnCount(), 1);
stat.execute("ALTER TABLE TEST ADD COLUMN NAME VARCHAR(255)");
check(prep.executeQuery().getMetaData().getColumnCount(), 2);
stat.execute("DROP TABLE TEST");
stat.execute("CREATE TABLE TEST(ID INT PRIMARY KEY, X INT, Y INT)");
check(prep.executeQuery().getMetaData().getColumnCount(), 3);
// TODO test auto-recompile with insert..select, views and so on
prep = conn.prepareStatement("INSERT INTO TEST VALUES(1, 2, 3)");
stat.execute("ALTER TABLE TEST ADD COLUMN Z INT");
try {
prep.execute();
error("must fail");
} catch(SQLException e) {
checkNotGeneralException(e);
}
try {
prep.execute();
error("must fail");
} catch(SQLException e) {
checkNotGeneralException(e);
}
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.db;
import java.sql.*;
import org.h2.test.TestBase;
public class TestBatchUpdates extends TestBase {
static final String COFFEE_UPDATE = "UPDATE TEST SET PRICE=PRICE*20 WHERE TYPE_ID=?";
static final String COFFEE_SELECT = "SELECT PRICE FROM TEST WHERE KEY_ID=?";
static final String COFFEE_QUERY = "SELECT COF_NAME,PRICE FROM TEST WHERE TYPE_ID=?";
static final String COFFEE_DELETE = "DELETE FROM TEST WHERE KEY_ID=?";
static final String COFFEE_INSERT1 = "INSERT INTO TEST VALUES(9,'COFFEE-9',9.0,5)";
static final String COFFEE_DELETE1 = "DELETE FROM TEST WHERE KEY_ID=9";
static final String COFFEE_UPDATE1 = "UPDATE TEST SET PRICE=PRICE*20 WHERE TYPE_ID=1";
static final String COFFEE_SELECT1 = "SELECT PRICE FROM TEST WHERE KEY_ID>4";
static final String COFFEE_UPDATE_SET = "UPDATE TEST SET KEY_ID=?, COF_NAME=? WHERE COF_NAME=?";
static final String COFFEE_SELECT_CONTINUED = "SELECT COUNT(*) FROM TEST WHERE COF_NAME='Continue-1'";
int coffeeSize = 10;
int coffeeType = 11;
Connection conn;
Statement stat;
PreparedStatement prep;
public void test() throws Exception {
deleteDb("batchUpdates");
this.conn = getConnection("batchUpdates");
stat = conn.createStatement();
DatabaseMetaData meta = conn.getMetaData();
if (!meta.supportsBatchUpdates()) {
error("does not support BatchUpdates");
}
stat.executeUpdate("CREATE TABLE TEST(KEY_ID INT PRIMARY KEY,"
+ "COF_NAME VARCHAR(255),PRICE DECIMAL(20,2),TYPE_ID INT)");
String newName = null;
float newPrice = 0;
int newType = 0;
prep = conn.prepareStatement("INSERT INTO TEST VALUES(?,?,?,?)");
int newKey = 1;
for (int i = 1; i <= coffeeType && newKey <= coffeeSize; i++) {
for (int j = 1; j <= i && newKey <= coffeeSize; j++) {
newName = "COFFEE-" + newKey;
newPrice = newKey + (float) .00;
newType = i;
prep.setInt(1, newKey);
prep.setString(2, newName);
prep.setFloat(3, newPrice);
prep.setInt(4, newType);
prep.execute();
newKey = newKey + 1;
}
}
trace("Inserted the Rows ");
testAddBatch01();
testAddBatch02();
testClearBatch01();
testClearBatch02();
testExecuteBatch01();
testExecuteBatch02();
testExecuteBatch03();
testExecuteBatch04();
testExecuteBatch05();
testExecuteBatch06();
testExecuteBatch07();
testContinueBatch01();
conn.close();
}
public void testAddBatch01() throws Exception {
trace("testAddBatch01");
int i = 0;
int[] retValue = { 0, 0, 0};
String s = COFFEE_UPDATE;
trace("Prepared Statement String:" + s);
prep = conn.prepareStatement(s);
prep.setInt(1, 2);
prep.addBatch();
prep.setInt(1, 3);
prep.addBatch();
prep.setInt(1, 4);
prep.addBatch();
int[] updateCount = prep.executeBatch();
int updateCountlen = updateCount.length;
// PreparedStatement p;
// p = conn.prepareStatement(COFFEE_UPDATE);
// p.setInt(1,2);
// System.out.println("upc="+p.executeUpdate());
// p.setInt(1,3);
// System.out.println("upc="+p.executeUpdate());
// p.setInt(1,4);
// System.out.println("upc="+p.executeUpdate());
trace("updateCount length:" + updateCountlen);
if (updateCountlen != 3) {
error("addBatch");
} else {
trace("addBatch add the SQL statements to Batch ");
}
String query1 = "SELECT COUNT(*) FROM TEST WHERE TYPE_ID=2";
String query2 = "SELECT COUNT(*) FROM TEST WHERE TYPE_ID=3";
String query3 = "SELECT COUNT(*) FROM TEST WHERE TYPE_ID=4";
ResultSet rs = stat.executeQuery(query1);
rs.next();
retValue[i++] = rs.getInt(1);
rs = stat.executeQuery(query2);
rs.next();
retValue[i++] = rs.getInt(1);
rs = stat.executeQuery(query3);
rs.next();
retValue[i++] = rs.getInt(1);
for (int j = 0; j < updateCount.length; j++) {
trace("UpdateCount:" + updateCount[j]);
check(updateCount[j], retValue[j]);
}
}
public void testAddBatch02() throws Exception {
trace("testAddBatch02");
int i = 0;
int[] retValue = { 0, 0, 0};
int updCountLength = 0;
String sUpdCoffee = COFFEE_UPDATE1;
String sDelCoffee = COFFEE_DELETE1;
String sInsCoffee = COFFEE_INSERT1;
stat.addBatch(sUpdCoffee);
stat.addBatch(sDelCoffee);
stat.addBatch(sInsCoffee);
int[] updateCount = stat.executeBatch();
updCountLength = updateCount.length;
trace("updateCount Length:" + updCountLength);
if (updCountLength != 3) {
error("addBatch");
} else {
trace("addBatch add the SQL statements to Batch ");
}
String query1 = "SELECT COUNT(*) FROM TEST WHERE TYPE_ID=1";
ResultSet rs = stat.executeQuery(query1);
rs.next();
retValue[i++] = rs.getInt(1);
// 1 as delete Statement will delete only one row
retValue[i++] = 1;
// 1 as insert Statement will insert only one row
retValue[i++] = 1;
trace("ReturnValue count : " + retValue.length);
for (int j = 0; j < updateCount.length; j++) {
trace("Update Count:" + updateCount[j]);
trace("Returned Value : " + retValue[j]);
if (updateCount[j] != retValue[j]) {
error("j=" + j + " right:" + retValue[j]);
}
}
}
public void testClearBatch01() throws Exception {
trace("testClearBatch01");
String sPrepStmt = COFFEE_UPDATE;
trace("Prepared Statement String:" + sPrepStmt);
prep = conn.prepareStatement(sPrepStmt);
prep.setInt(1, 2);
prep.addBatch();
prep.setInt(1, 3);
prep.addBatch();
prep.setInt(1, 4);
prep.addBatch();
prep.clearBatch();
int[] updateCount = prep.executeBatch();
int updCountLength = updateCount.length;
if (updCountLength == 0) {
trace("clearBatch Method clears the current Batch ");
} else {
error("clearBatch");
}
}
public void testClearBatch02() throws Exception {
trace("testClearBatch02");
int updCountLength = 0;
String sUpdCoffee = COFFEE_UPDATE1;
String sInsCoffee = COFFEE_INSERT1;
String sDelCoffee = COFFEE_DELETE1;
stat.addBatch(sUpdCoffee);
stat.addBatch(sDelCoffee);
stat.addBatch(sInsCoffee);
stat.clearBatch();
int[] updateCount = stat.executeBatch();
updCountLength = updateCount.length;
trace("updateCount Length:" + updCountLength);
if (updCountLength == 0) {
trace("clearBatch Method clears the current Batch ");
} else {
error("clearBatch");
}
}
public void testExecuteBatch01() throws Exception {
trace("testExecuteBatch01");
int i = 0;
int[] retValue = { 0, 0, 0};
int updCountLength = 0;
String sPrepStmt = COFFEE_UPDATE;
trace("Prepared Statement String:" + sPrepStmt);
// get the PreparedStatement object
prep = conn.prepareStatement(sPrepStmt);
prep.setInt(1, 1);
prep.addBatch();
prep.setInt(1, 2);
prep.addBatch();
prep.setInt(1, 3);
prep.addBatch();
int[] updateCount = prep.executeBatch();
updCountLength = updateCount.length;
trace("Successfully Updated");
trace("updateCount Length:" + updCountLength);
if (updCountLength != 3) {
error("executeBatch");
} else {
trace("executeBatch executes the Batch of SQL statements");
}
//1 is the number that is set First for Type Id in Prepared Statement
String query1 = "SELECT COUNT(*) FROM TEST WHERE TYPE_ID=1";
//2 is the number that is set second for Type id in Prepared Statement
String query2 = "SELECT COUNT(*) FROM TEST WHERE TYPE_ID=2";
// 3 is the number that is set Third for Type id in Prepared Statement
String query3 = "SELECT COUNT(*) FROM TEST WHERE TYPE_ID=3";
ResultSet rs = stat.executeQuery(query1);
rs.next();
retValue[i++] = rs.getInt(1);
rs = stat.executeQuery(query2);
rs.next();
retValue[i++] = rs.getInt(1);
rs = stat.executeQuery(query3);
rs.next();
retValue[i++] = rs.getInt(1);
trace("retvalue length : " + retValue.length);
for (int j = 0; j < updateCount.length; j++) {
trace("UpdateCount Value:" + updateCount[j]);
trace("Retvalue : " + retValue[j]);
if (updateCount[j] != retValue[j]) {
error("j=" + j + " right:" + retValue[j]);
}
}
}
public void testExecuteBatch02() throws Exception {
trace("testExecuteBatch02");
String sPrepStmt = COFFEE_UPDATE;
trace("Prepared Statement String:" + sPrepStmt);
prep = conn.prepareStatement(sPrepStmt);
prep.setInt(1, 1);
prep.setInt(1, 2);
prep.setInt(1, 3);
int[] updateCount = prep.executeBatch();
int updCountLength = updateCount.length;
trace("UpdateCount Length : " + updCountLength);
if (updCountLength == 0) {
trace("executeBatch does not execute Empty Batch");
} else {
error("executeBatch");
}
}
public void testExecuteBatch03() throws Exception {
trace("testExecuteBatch03");
boolean bexpflag = false;
String sPrepStmt = COFFEE_SELECT;
trace("Prepared Statement String :" + sPrepStmt);
prep = conn.prepareStatement(sPrepStmt);
prep.setInt(1, 1);
prep.addBatch();
try {
int[] updateCount = prep.executeBatch();
trace("Update Count" + updateCount.length);
} catch (BatchUpdateException b) {
bexpflag = true;
}
if (bexpflag) {
trace("select not allowed; correct");
} else {
error("executeBatch select");
}
}
public void testExecuteBatch04() throws Exception {
trace("testExecuteBatch04");
int i = 0;
int[] retValue = { 0, 0, 0};
int updCountLength = 0;
String sUpdCoffee = COFFEE_UPDATE1;
String sInsCoffee = COFFEE_INSERT1;
String sDelCoffee = COFFEE_DELETE1;
stat.addBatch(sUpdCoffee);
stat.addBatch(sDelCoffee);
stat.addBatch(sInsCoffee);
int[] updateCount = stat.executeBatch();
updCountLength = updateCount.length;
trace("Successfully Updated");
trace("updateCount Length:" + updCountLength);
if (updCountLength != 3) {
error("executeBatch");
} else {
trace("executeBatch executes the Batch of SQL statements");
}
String query1 = "SELECT COUNT(*) FROM TEST WHERE TYPE_ID=1";
ResultSet rs = stat.executeQuery(query1);
rs.next();
retValue[i++] = rs.getInt(1);
// 1 as Delete Statement will delete only one row
retValue[i++] = 1;
// 1 as Insert Statement will insert only one row
retValue[i++] = 1;
for (int j = 0; j < updateCount.length; j++) {
trace("Update Count : " + updateCount[j]);
if (updateCount[j] != retValue[j]) {
error("j=" + j + " right:" + retValue[j]);
}
}
}
public void testExecuteBatch05() throws Exception {
trace("testExecuteBatch05");
int updCountLength = 0;
int[] updateCount = stat.executeBatch();
updCountLength = updateCount.length;
trace("updateCount Length:" + updCountLength);
if (updCountLength == 0) {
trace("executeBatch Method does not execute the Empty Batch ");
} else {
error("executeBatch 0!=" + updCountLength);
}
}
public void testExecuteBatch06() throws Exception {
trace("testExecuteBatch06");
boolean bexpflag = false;
//Insert a row which is already Present
String sInsCoffee = COFFEE_INSERT1;
String sDelCoffee = COFFEE_DELETE1;
stat.addBatch(sInsCoffee);
stat.addBatch(sInsCoffee);
stat.addBatch(sDelCoffee);
try {
stat.executeBatch();
} catch (BatchUpdateException b) {
bexpflag = true;
int[] updCounts = b.getUpdateCounts();
for (int i = 0; i < updCounts.length; i++) {
trace("Update counts:" + updCounts[i]);
}
}
if (bexpflag) {
trace("executeBatch insert duplicate; correct");
} else {
error("executeBatch");
}
}
public void testExecuteBatch07() throws Exception {
trace("testExecuteBatch07");
boolean bexpflag = false;
String sSelCoffee = COFFEE_SELECT1;
trace("sSelCoffee = " + sSelCoffee);
Statement stmt = conn.createStatement();
stmt.addBatch(sSelCoffee);
try {
int[] updateCount = stmt.executeBatch();
trace("updateCount Length : " + updateCount.length);
} catch (BatchUpdateException be) {
bexpflag = true;
}
if (bexpflag) {
trace("executeBatch select");
} else {
error("executeBatch");
}
}
public void testContinueBatch01() throws Exception {
trace("testContinueBatch01");
int[] batchUpdates = { 0, 0, 0};
int buCountlen = 0;
try {
String sPrepStmt = COFFEE_UPDATE_SET;
trace("Prepared Statement String:" + sPrepStmt);
prep = conn.prepareStatement(sPrepStmt);
// Now add a legal update to the batch
prep.setInt(1, 1);
prep.setString(2, "Continue-1");
prep.setString(3, "COFFEE-1");
prep.addBatch();
// Now add an illegal update to the batch by
// forcing a unique constraint violation
// Try changing the key_id of row 3 to 1.
prep.setInt(1, 1);
prep.setString(2, "Invalid");
prep.setString(3, "COFFEE-3");
prep.addBatch();
// Now add a second legal update to the batch
// which will be processed ONLY if the driver supports
// continued batch processing according to 6.2.2.3
// of the J2EE platform spec.
prep.setInt(1, 2);
prep.setString(2, "Continue-2");
prep.setString(3, "COFFEE-2");
prep.addBatch();
// The executeBatch() method will result in a
// BatchUpdateException
prep.executeBatch();
} catch (BatchUpdateException b) {
trace("expected BatchUpdateException");
batchUpdates = b.getUpdateCounts();
buCountlen = batchUpdates.length;
}
if (buCountlen == 1) {
trace("no continued updates - OK");
return;
} else if (buCountlen == 3) {
trace("Driver supports continued updates.");
// Check to see if the third row from the batch was added
String query = COFFEE_SELECT_CONTINUED;
trace("Query is: " + query);
ResultSet rs = stat.executeQuery(query);
rs.next();
int count = rs.getInt(1);
rs.close();
stat.close();
trace("Count val is: " + count);
// Make sure that we have the correct error code for
// the failed update.
if (!(batchUpdates[1] == -3 && count == 1)) {
error("insert failed");
}
}
}
}
/*
* 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.db;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import org.h2.test.TestBase;
import org.h2.util.MemoryUtils;
public class TestBigDb extends TestBase {
public void test() throws Exception {
if(config.memory) {
return;
}
if(config.networked && config.big) {
return;
}
testLargeTable();
testInsert();
testLeftSummary();
}
private void testLargeTable() throws Exception {
deleteDb("bigDb");
Connection conn = getConnection("bigDb");
Statement stat = conn.createStatement();
stat.execute(
"CREATE CACHED TABLE PAB_ARTLEV("+
"MUTATIECODE CHAR(1) DEFAULT CAST(RAND()*9 AS INT),"+
"PRDCODE CHAR(20) DEFAULT SECURE_RAND(10),"+
"ORGCODESUPPLIER CHAR(13) DEFAULT SECURE_RAND(6),"+
"PRDCODEGTIN CHAR(14) DEFAULT SECURE_RAND(7),"+
"PRDCODEMF CHAR(20) DEFAULT SECURE_RAND(10),"+
"ORGCODEMF CHAR(13) DEFAULT SECURE_RAND(6),"+
"SUBSTITUTEDBY CHAR(20) DEFAULT SECURE_RAND(10),"+
"SUBSTITUTEDBYGTIN CHAR(14) DEFAULT SECURE_RAND(7),"+
"SUBSTITUTIONFOR CHAR(20) DEFAULT SECURE_RAND(10),"+
"SUBSTITUTIONFORGTIN CHAR(14) DEFAULT SECURE_RAND(7),"+
"VERWERKBAAR CHAR(2) DEFAULT SECURE_RAND(1),"+
"BESTELBAAR CHAR(2) DEFAULT SECURE_RAND(1),"+
"AANTALGEBRUIKSEENHEDEN DECIMAL(7,2) DEFAULT RAND(),"+
"PRIMARYUNITCODE CHAR(3) DEFAULT SECURE_RAND(1),"+
"RATEPRICEORDERUNIT DECIMAL(9,3) DEFAULT RAND(),"+
"ORDERUNITCODE CHAR(3) DEFAULT SECURE_RAND(1),"+
"ORDERQTYMIN DECIMAL(6,1) DEFAULT RAND(),"+
"ORDERQTYLOTSIZE DECIMAL(6,1) DEFAULT RAND(),"+
"ORDERUNITCODE2 CHAR(3) DEFAULT SECURE_RAND(1),"+
"PRICEGROUP CHAR(20) DEFAULT SECURE_RAND(10),"+
"LEADTIME INTEGER DEFAULT RAND(),"+
"LEADTIMEUNITCODE CHAR(3) DEFAULT SECURE_RAND(1),"+
"PRDGROUP CHAR(10) DEFAULT SECURE_RAND(5),"+
"WEIGHTGROSS DECIMAL(7,3) DEFAULT RAND(),"+
"WEIGHTUNITCODE CHAR(3) DEFAULT SECURE_RAND(1),"+
"PACKUNITCODE CHAR(3) DEFAULT SECURE_RAND(1),"+
"PACKLENGTH DECIMAL(7,3) DEFAULT RAND(),"+
"PACKWIDTH DECIMAL(7,3) DEFAULT RAND(),"+
"PACKHEIGHT DECIMAL(7,3) DEFAULT RAND(),"+
"SIZEUNITCODE CHAR(3) DEFAULT SECURE_RAND(1),"+
"STATUCCODE CHAR(3) DEFAULT SECURE_RAND(1),"+
"INTRASTATCODE CHAR(12) DEFAULT SECURE_RAND(6),"+
"PRDTITLE CHAR(50) DEFAULT SECURE_RAND(25),"+
"VALIDFROM DATE DEFAULT NOW(),"+
"MUTATIEDATUM DATE DEFAULT NOW())");
int len = getSize(10, 50000);
try {
PreparedStatement prep = conn.prepareStatement("INSERT INTO PAB_ARTLEV(PRDCODE) VALUES('abc' || ?)");
long time = System.currentTimeMillis();
for(int i=0; i<len; i++) {
if((i % 1000) == 0) {
long t = System.currentTimeMillis();
if(t-time > 1000) {
time = t;
int free = MemoryUtils.getMemoryFree();
System.out.println("i: " + i + " free: " + free + " used: " + MemoryUtils.getMemoryUsed());
}
}
prep.setInt(1, i);
prep.execute();
}
stat.execute("CREATE INDEX IDX_PAB_ARTLEV_PRDCODE ON PAB_ARTLEV(PRDCODE)");
ResultSet rs = stat.executeQuery("SELECT * FROM PAB_ARTLEV");
int columns = rs.getMetaData().getColumnCount();
while(rs.next()) {
for(int i=0; i<columns; i++) {
rs.getString(i+1);
}
}
} catch(OutOfMemoryError e) {
e.printStackTrace();
conn.close();
throw e;
}
conn.close();
}
private void testLeftSummary() throws Exception {
deleteDb("bigDb");
Connection conn = getConnection("bigDb");
Statement stat = conn.createStatement();
stat.execute("CREATE TABLE TEST(ID INT, NEG INT AS -ID, NAME VARCHAR, PRIMARY KEY(ID, NAME))");
stat.execute("CREATE INDEX IDXNEG ON TEST(NEG, NAME)");
PreparedStatement prep = conn.prepareStatement("INSERT INTO TEST(ID, NAME) VALUES(?, '1234567890')");
int len = getSize(10, 1000);
int block = getSize(3, 10);
int left, x = 0;
for(int i=0; i<len; i++) {
left = x+block/2;
for(int j=0; j<block; j++) {
prep.setInt(1, x++);
prep.execute();
}
stat.execute("DELETE FROM TEST WHERE ID>" + left);
ResultSet rs = stat.executeQuery("SELECT COUNT(*) FROM TEST");
rs.next();
int count = rs.getInt(1);
trace("count: " + count);
}
conn.close();
}
private void testInsert() throws Exception {
deleteDb("bigDb");
Connection conn = getConnection("bigDb");
Statement stat = conn.createStatement();
stat.execute("CREATE TABLE TEST(ID IDENTITY, NAME VARCHAR)");
PreparedStatement prep = conn.prepareStatement("INSERT INTO TEST(NAME) VALUES('Hello World')");
int len = getSize(1000, 10000);
long time = System.currentTimeMillis();
for(int i=0; i<len; i++) {
if(i % 1000 == 0) {
long t = System.currentTimeMillis();
time = t;
trace("rows:" + i + " time:" + (t-time));
Thread.yield();
}
prep.execute();
}
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.db;
import java.sql.*;
import org.h2.test.TestBase;
public class TestBigResult extends TestBase {
public void test() throws Exception {
if(config.memory) {
return;
}
testLimitBufferedResult();
testOrderGroup();
}
private void testLimitBufferedResult() throws Exception {
deleteDb("bigResult");
Connection conn = getConnection("bigResult");
Statement stat = conn.createStatement();
stat.execute("DROP TABLE IF EXISTS TEST");
stat.execute("CREATE TABLE TEST(ID INT)");
for(int i=0; i<200; i++) {
stat.execute("INSERT INTO TEST(ID) VALUES("+i+")");
}
stat.execute("SET MAX_MEMORY_ROWS 100");
ResultSet rs;
rs = stat.executeQuery("select id from test order by id limit 10 offset 85");
for(int i=85; rs.next(); i++) {
check(i, rs.getInt(1));
}
rs = stat.executeQuery("select id from test order by id limit 10 offset 95");
for(int i=95; rs.next(); i++) {
check(i, rs.getInt(1));
}
rs = stat.executeQuery("select id from test order by id limit 10 offset 105");
for(int i=105; rs.next(); i++) {
check(i, rs.getInt(1));
}
conn.close();
}
private void testOrderGroup() throws Exception {
deleteDb("bigResult");
Connection conn = getConnection("bigResult");
Statement stat = conn.createStatement();
stat.execute("DROP TABLE IF EXISTS TEST");
stat.execute("CREATE TABLE TEST(" + "ID INT PRIMARY KEY, "
+ "Name VARCHAR(255), "
+ "FirstName VARCHAR(255), "
+ "Points INT,"
+ "LicenseID INT)");
int len = getSize(10, 5000);
PreparedStatement prep = conn.prepareStatement("INSERT INTO TEST VALUES(?, ?, ?, ?, ?)");
for(int i=0; i<len; i++) {
prep.setInt(1, i);
prep.setString(2, "Name " + i);
prep.setString(3, "First Name " + i);
prep.setInt(4, i*10);
prep.setInt(5, i*i);
prep.execute();
}
conn.close();
conn = getConnection("bigResult");
stat = conn.createStatement();
stat.setMaxRows(len + 1);
ResultSet rs = stat.executeQuery("SELECT * FROM TEST ORDER BY ID");
for(int i=0; i<len; i++) {
rs.next();
check(i, rs.getInt(1));
check("Name " + i, rs.getString(2));
check("First Name " + i, rs.getString(3));
check(i*10, rs.getInt(4));
check(i*i, rs.getInt(5));
}
stat.setMaxRows(len + 1);
rs = stat.executeQuery("SELECT * FROM TEST WHERE ID >= 1000 ORDER BY ID");
for(int i=1000; i<len; i++) {
rs.next();
check(i, rs.getInt(1));
check("Name " + i, rs.getString(2));
check("First Name " + i, rs.getString(3));
check(i*10, rs.getInt(4));
check(i*i, rs.getInt(5));
}
stat.execute("SET MAX_MEMORY_ROWS 2");
rs = stat.executeQuery("SELECT Name, SUM(ID) FROM TEST GROUP BY NAME");
while(rs.next()) {
rs.getString(1);
rs.getInt(2);
}
conn.setAutoCommit(false);
stat.setMaxRows(0);
stat.execute("SET MAX_MEMORY_ROWS 0");
stat.execute("CREATE TABLE DATA(ID INT, NAME VARCHAR_IGNORECASE(255))");
prep = conn.prepareStatement("INSERT INTO DATA VALUES(?, ?)");
for(int i=0; i<len; i++) {
prep.setInt(1, i);
prep.setString(2, ""+i/200);
prep.execute();
}
Statement s2 = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
rs = s2.executeQuery("SELECT NAME FROM DATA");
rs.last();
conn.setAutoCommit(true);
rs = s2.executeQuery("SELECT NAME FROM DATA ORDER BY ID");
while(rs.next()) {
// do nothing
}
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.db;
import java.io.File;
import java.io.StringReader;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.Random;
import org.h2.test.TestBase;
public class TestCases extends TestBase {
public void test() throws Exception {
testDisconnect();
testExecuteTrace();
if(config.memory || config.logMode == 0) {
return;
}
testSpecialSQL();
testUpperCaseLowerCaseDatabase();
testManualCommitSet();
testSchemaIdentityReconnect();
testAlterTableReconnect();
testPersistentSettings();
testInsertSelectUnion();
testViewReconnect();
testDefaultQueryReconnect();
testBigString();
testRenameReconnect();
testAllSizes();
testCreateDrop();
testPolePos();
testQuick();
testMutableObjects();
testSelectForUpdate();
testDoubleRecovery();
testConstraintReconnect();
testCollation();
}
private void testSpecialSQL() throws Exception {
deleteDb("cases");
Connection conn=getConnection("cases");
Statement stat = conn.createStatement();
stat.execute("SET AUTOCOMMIT OFF; \n//create sequence if not exists object_id;\n");
stat.execute("SET AUTOCOMMIT OFF;\n//create sequence if not exists object_id;\n");
stat.execute("SET AUTOCOMMIT OFF; //create sequence if not exists object_id;");
stat.execute("SET AUTOCOMMIT OFF;//create sequence if not exists object_id;");
stat.execute("SET AUTOCOMMIT OFF \n//create sequence if not exists object_id;");
stat.execute("SET AUTOCOMMIT OFF\n//create sequence if not exists object_id;");
stat.execute("SET AUTOCOMMIT OFF //create sequence if not exists object_id;");
stat.execute("SET AUTOCOMMIT OFF//create sequence if not exists object_id;");
stat.execute("SET AUTOCOMMIT OFF; \n///create sequence if not exists object_id;");
stat.execute("SET AUTOCOMMIT OFF;\n///create sequence if not exists object_id;");
stat.execute("SET AUTOCOMMIT OFF; ///create sequence if not exists object_id;");
stat.execute("SET AUTOCOMMIT OFF;///create sequence if not exists object_id;");
stat.execute("SET AUTOCOMMIT OFF \n///create sequence if not exists object_id;");
stat.execute("SET AUTOCOMMIT OFF\n///create sequence if not exists object_id;");
stat.execute("SET AUTOCOMMIT OFF ///create sequence if not exists object_id;");
stat.execute("SET AUTOCOMMIT OFF///create sequence if not exists object_id;");
conn.close();
}
private void testUpperCaseLowerCaseDatabase() throws Exception {
if(File.separatorChar != '\\') {
return;
}
deleteDb("cases");
deleteDb("CaSeS");
Connection conn, conn2;
ResultSet rs;
conn=getConnection("cases");
Statement stat = conn.createStatement();
stat.execute("CHECKPOINT");
stat.execute("CREATE TABLE TEST(ID INT)");
stat.execute("INSERT INTO TEST VALUES(1)");
stat.execute("CHECKPOINT");
conn2=getConnection("CaSeS");
rs = conn.createStatement().executeQuery("SELECT * FROM TEST");
check(rs.next());
conn2.close();
conn.close();
conn=getConnection("cases");
rs = conn.createStatement().executeQuery("SELECT * FROM TEST");
check(rs.next());
conn.close();
conn=getConnection("CaSeS");
rs = conn.createStatement().executeQuery("SELECT * FROM TEST");
check(rs.next());
conn.close();
deleteDb("cases");
deleteDb("CaSeS");
}
private void testManualCommitSet() throws Exception {
deleteDb("cases");
Connection conn=getConnection("cases");
Connection conn2=getConnection("cases");
conn.setAutoCommit(false);
conn2.setAutoCommit(false);
conn.createStatement().execute("SET MODE REGULAR");
conn2.createStatement().execute("SET MODE REGULAR");
conn.close();
conn2.close();
}
private void testSchemaIdentityReconnect() throws Exception {
deleteDb("cases");
Connection conn=getConnection("cases");
Statement stat = conn.createStatement();
stat.execute("create schema s authorization sa");
stat.execute("create table s.test(id identity)");
conn.close();
conn=getConnection("cases");
ResultSet rs = conn.createStatement().executeQuery("SELECT * FROM S.TEST");
while(rs.next()) {
// ignore
}
conn.close();
}
private void testDisconnect() throws Exception {
if(config.networked) {
return;
}
deleteDb("cases");
Connection conn=getConnection("cases");
final Statement stat = conn.createStatement();
stat.execute("CREATE TABLE TEST(ID IDENTITY)");
for(int i=0; i<1000; i++) {
stat.execute("INSERT INTO TEST() VALUES()");
}
final boolean[] stopped = new boolean[1];
Thread t = new Thread(new Runnable() {
public void run() {
try {
ResultSet rs = stat.executeQuery("SELECT MAX(T.ID) FROM TEST T, TEST, TEST, TEST, TEST, TEST, TEST, TEST, TEST, TEST, TEST");
rs.next();
new Error("query was too quick; result: " + rs.getInt(1)).printStackTrace();
} catch(SQLException e) {
// ok
}
stopped[0] = true;
}
});
t.start();
Thread.sleep(500);
long time = System.currentTimeMillis();
conn.close();
Thread.sleep(500);
if(!stopped[0]) {
error("query still running");
}
time = System.currentTimeMillis() - time;
if(time > 1000) {
error("closing took " + time);
}
deleteDb("cases");
}
private void testExecuteTrace() throws Exception {
deleteDb("cases");
Connection conn=getConnection("cases");
Statement stat = conn.createStatement();
ResultSet rs = stat.executeQuery("SELECT ? FROM DUAL {1: 'Hello'}");
rs.next();
check("Hello", rs.getString(1));
checkFalse(rs.next());
rs = stat.executeQuery("SELECT ? FROM DUAL UNION ALL SELECT ? FROM DUAL {1: 'Hello', 2:'World' }");
rs.next();
check("Hello", rs.getString(1));
rs.next();
check("World", rs.getString(1));
checkFalse(rs.next());
conn.close();
}
private void testAlterTableReconnect() throws Exception {
deleteDb("cases");
Connection conn=getConnection("cases");
Statement stat = conn.createStatement();
stat.execute("create table test(id identity);");
stat.execute("insert into test values(1);");
try {
stat.execute("alter table test add column name varchar not null;");
error("shouldn't work");
} catch(SQLException e) {
checkNotGeneralException(e);
}
conn.close();
conn=getConnection("cases");
ResultSet rs = conn.createStatement().executeQuery("SELECT * FROM TEST");
rs.next();
check(rs.getString(1), "1");
checkFalse(rs.next());
stat = conn.createStatement();
stat.execute("drop table test");
stat.execute("create table test(id identity)");
stat.execute("insert into test values(1)");
stat.execute("alter table test alter column id set default 'x'");
conn.close();
conn=getConnection("cases");
stat = conn.createStatement();
rs = conn.createStatement().executeQuery("SELECT * FROM TEST");
rs.next();
check(rs.getString(1), "1");
checkFalse(rs.next());
stat.execute("drop table test");
stat.execute("create table test(id identity)");
stat.execute("insert into test values(1)");
try {
stat.execute("alter table test alter column id date");
error("shouldn't work");
} catch(SQLException e) {
checkNotGeneralException(e);
}
conn.close();
conn=getConnection("cases");
rs = conn.createStatement().executeQuery("SELECT * FROM TEST");
rs.next();
check(rs.getString(1), "1");
checkFalse(rs.next());
conn.close();
}
private void testCollation() throws Exception {
deleteDb("cases");
Connection conn=getConnection("cases");
Statement stat = conn.createStatement();
stat.execute("SET COLLATION ENGLISH STRENGTH PRIMARY");
stat.execute("CREATE TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR(255))");
stat.execute("INSERT INTO TEST VALUES(1, 'Hello'), (2, 'World'), (3, 'WORLD'), (4, 'HELLO')");
stat.execute("create index idxname on test(name)");
ResultSet rs;
rs = stat.executeQuery("select name from test order by name");
rs.next();
check(rs.getString(1), "Hello");
rs.next();
check(rs.getString(1), "HELLO");
rs.next();
check(rs.getString(1), "World");
rs.next();
check(rs.getString(1), "WORLD");
rs = stat.executeQuery("select name from test where name like 'He%'");
rs.next();
check(rs.getString(1), "Hello");
rs.next();
check(rs.getString(1), "HELLO");
conn.close();
}
private void testPersistentSettings() throws Exception {
deleteDb("cases");
Connection conn=getConnection("cases");
Statement stat = conn.createStatement();
stat.execute("SET COLLATION de_DE");
stat.execute("CREATE TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR)");
stat.execute("CREATE INDEX IDXNAME ON TEST(NAME)");
// \u00f6 = oe
stat.execute("INSERT INTO TEST VALUES(1, 'B\u00f6hlen'), (2, 'Bach'), (3, 'Bucher')");
conn.close();
conn=getConnection("cases");
ResultSet rs = conn.createStatement().executeQuery("SELECT NAME FROM TEST ORDER BY NAME");
rs.next();
check(rs.getString(1), "Bach");
rs.next();
check(rs.getString(1), "B\u00f6hlen");
rs.next();
check(rs.getString(1), "Bucher");
conn.close();
}
private void testInsertSelectUnion() throws Exception {
deleteDb("cases");
Connection conn=getConnection("cases");
Statement stat = conn.createStatement();
stat.execute("CREATE TABLE TEST(ORDER_ID INT PRIMARY KEY, ORDER_DATE DATETIME, USER_ID INT ,"
+"DESCRIPTION VARCHAR, STATE VARCHAR, TRACKING_ID VARCHAR)");
Timestamp orderDate = Timestamp.valueOf("2005-05-21 17:46:00");
String sql = "insert into TEST (ORDER_ID,ORDER_DATE,USER_ID,DESCRIPTION,STATE,TRACKING_ID) "
+"select cast(? as int),cast(? as date),cast(? as int),cast(? as varchar),cast(? as varchar),cast(? as varchar) union all select ?,?,?,?,?,?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, 5555);
ps.setTimestamp(2, orderDate);
ps.setInt(3, 2222);
ps.setString(4, "test desc");
ps.setString(5, "teststate");
ps.setString(6, "testid");
ps.setInt(7, 5556);
ps.setTimestamp(8, orderDate);
ps.setInt(9, 2222);
ps.setString(10, "test desc");
ps.setString(11, "teststate");
ps.setString(12, "testid");
check(ps.executeUpdate(), 2);
ps.close();
conn.close();
}
private void testViewReconnect() throws Exception {
trace("testViewReconnect");
deleteDb("cases");
Connection conn=getConnection("cases");
Statement stat = conn.createStatement();
stat.execute("create table test(id int)");
stat.execute("create view abc as select * from test");
stat.execute("drop table test");
conn.close();
conn = getConnection("cases");
stat = conn.createStatement();
try {
stat.execute("select * from abc");
error("abc should be deleted");
} catch(SQLException e) {
checkNotGeneralException(e);
}
conn.close();
}
private void testDefaultQueryReconnect() throws Exception {
trace("testDefaultQueryReconnect");
deleteDb("cases");
Connection conn=getConnection("cases");
Statement stat = conn.createStatement();
stat.execute("create table parent(id int)");
stat.execute("insert into parent values(1)");
stat.execute("create table test(id int default (select max(id) from parent), name varchar)");
conn.close();
conn = getConnection("cases");
stat = conn.createStatement();
conn.setAutoCommit(false);
stat.execute("insert into parent values(2)");
stat.execute("insert into test(name) values('test')");
ResultSet rs = stat.executeQuery("select * from test");
rs.next();
check(rs.getInt(1), 2);
checkFalse(rs.next());
conn.close();
}
private void testBigString() throws Exception {
trace("testBigString");
deleteDb("cases");
Connection conn=getConnection("cases");
Statement stat = conn.createStatement();
stat.execute("DROP TABLE IF EXISTS TEST");
stat.execute("CREATE TABLE TEST(ID INT, TEXT VARCHAR, TEXT_C CLOB)");
PreparedStatement prep = conn.prepareStatement("INSERT INTO TEST VALUES(?, ?, ?)");
int len = getSize(1000, 66000);
char[] buff = new char[len];
// The UCS code values 0xd800-0xdfff (UTF-16 surrogates)
// as well as 0xfffe and 0xffff (UCS non-characters)
// should not appear in conforming UTF-8 streams.
// (String.getBytes("UTF-8") only returns 1 byte for 0xd800-0xdfff)
Random random = new Random();
random.setSeed(1);
for(int i=0; i<len; i++) {
char c;
do {
c = (char)random.nextInt();
} while(c >= 0xd800 && c <= 0xdfff);
buff[i] = c;
}
String big = new String(buff);
prep.setInt(1, 1);
prep.setString(2, big);
prep.setString(3, big);
prep.execute();
prep.setInt(1, 2);
prep.setCharacterStream(2, new StringReader(big), 0);
prep.setCharacterStream(3, new StringReader(big), 0);
prep.execute();
ResultSet rs = stat.executeQuery("SELECT * FROM TEST ORDER BY ID");
rs.next();
check(rs.getInt(1), 1);
check(rs.getString(2), big);
check(readString(rs.getCharacterStream(2)), big);
check(rs.getString(3), big);
check(readString(rs.getCharacterStream(3)), big);
rs.next();
check(rs.getInt(1), 2);
check(rs.getString(2), big);
check(readString(rs.getCharacterStream(2)), big);
check(rs.getString(3), big);
check(readString(rs.getCharacterStream(3)), big);
rs.next();
checkFalse(rs.next());
conn.close();
}
private void testConstraintReconnect() throws Exception {
trace("testConstraintReconnect");
deleteDb("cases");
Connection conn=getConnection("cases");
Statement stat = conn.createStatement();
stat.execute("drop table if exists parent");
stat.execute("drop table if exists child");
stat.execute("create table parent(id int)");
stat.execute("create table child(c_id int, p_id int, foreign key(p_id) references parent(id))");
stat.execute("insert into parent values(1), (2)");
stat.execute("insert into child values(1, 1)");
stat.execute("insert into child values(2, 2)");
stat.execute("insert into child values(3, 2)");
stat.execute("delete from child");
conn.close();
conn=getConnection("cases");
conn.close();
}
private void testDoubleRecovery() throws Exception {
if(config.networked) {
return;
}
trace("testDoubleRecovery");
deleteDb("cases");
Connection conn=getConnection("cases");
deleteDb("twoPhaseCommit");
Statement stat = conn.createStatement();
stat.execute("SET WRITE_DELAY 0");
stat.execute("DROP TABLE IF EXISTS TEST");
stat.execute("CREATE TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR(255))");
stat.execute("INSERT INTO TEST VALUES(1, 'Hello')");
conn.setAutoCommit(false);
stat.execute("INSERT INTO TEST VALUES(2, 'World')");
crash(conn);
conn=getConnection("cases");
stat = conn.createStatement();
stat.execute("SET WRITE_DELAY 0");
stat.execute("INSERT INTO TEST VALUES(3, 'Break')");
crash(conn);
conn=getConnection("cases");
stat = conn.createStatement();
ResultSet rs = stat.executeQuery("SELECT * FROM TEST ORDER BY ID");
rs.next();
check(rs.getInt(1), 1);
check(rs.getString(2), "Hello");
rs.next();
check(rs.getInt(1), 3);
check(rs.getString(2), "Break");
conn.close();
}
private void testRenameReconnect() throws Exception {
trace("testRenameReconnect");
deleteDb("cases");
Connection conn=getConnection("cases");
conn.createStatement().execute("CREATE TABLE TEST_SEQ(ID INT IDENTITY, NAME VARCHAR(255))");
conn.createStatement().execute("CREATE TABLE TEST(ID INT PRIMARY KEY)");
conn.createStatement().execute("ALTER TABLE TEST RENAME TO TEST2");
conn.createStatement().execute("CREATE TABLE TEST_B(ID INT PRIMARY KEY, NAME VARCHAR, UNIQUE(NAME));");
conn.close();
conn=getConnection("cases");
conn.createStatement().execute("INSERT INTO TEST_SEQ(NAME) VALUES('Hi')");
ResultSet rs = conn.createStatement().executeQuery("CALL IDENTITY()");
rs.next();
check(rs.getInt(1), 1);
conn.createStatement().execute("SELECT * FROM TEST2");
conn.createStatement().execute("SELECT * FROM TEST_B");
conn.createStatement().execute("ALTER TABLE TEST_B RENAME TO TEST_B2");
conn.close();
conn=getConnection("cases");
conn.createStatement().execute("SELECT * FROM TEST_B2");
conn.createStatement().execute("INSERT INTO TEST_SEQ(NAME) VALUES('World')");
rs = conn.createStatement().executeQuery("CALL IDENTITY()");
rs.next();
check(rs.getInt(1), 2);
conn.close();
}
private void testAllSizes() throws Exception {
trace("testAllSizes");
deleteDb("cases");
Connection conn=getConnection("cases");
Statement stat = conn.createStatement();
stat.execute("CREATE TABLE TEST(A INT, B INT, C INT, DATA VARCHAR)");
int increment = getSize(100, 1);
for(int i=1; i<500; i+=increment) {
StringBuffer buff = new StringBuffer();
buff.append("CREATE TABLE TEST");
for(int j=0; j<i; j++) {
buff.append('a');
}
buff.append("(ID INT)");
String sql = buff.toString();
stat.execute(sql);
stat.execute("INSERT INTO TEST VALUES("+i+", 0, 0, '"+sql+"')");
}
conn.close();
conn=getConnection("cases");
stat = conn.createStatement();
ResultSet rs = stat.executeQuery("SELECT * FROM TEST");
while(rs.next()) {
int id=rs.getInt(1);
String s = rs.getString("DATA");
if(!s.endsWith(")")) {
error("id="+id);
}
}
conn.close();
}
private void testSelectForUpdate() throws Exception {
trace("testSelectForUpdate");
deleteDb("cases");
Connection conn1=getConnection("cases");
Statement stat1 = conn1.createStatement();
stat1.execute("CREATE TABLE TEST(ID INT)");
stat1.execute("INSERT INTO TEST VALUES(1)");
conn1.setAutoCommit(false);
stat1.execute("SELECT * FROM TEST FOR UPDATE");
Connection conn2=getConnection("cases");
Statement stat2 = conn2.createStatement();
try {
stat2.execute("UPDATE TEST SET ID=2");
error("must fail");
} catch(SQLException e) {
checkNotGeneralException(e);
}
conn1.commit();
stat2.execute("UPDATE TEST SET ID=2");
conn1.close();
conn2.close();
}
private void testMutableObjects() throws Exception {
trace("testMutableObjects");
deleteDb("cases");
Connection conn=getConnection("cases");
Statement stat = conn.createStatement();
stat.execute("CREATE TABLE TEST(ID INT, D DATE, T TIME, TS TIMESTAMP)");
stat.execute("INSERT INTO TEST VALUES(1, '2001-01-01', '20:00:00', '2002-02-02 22:22:22.2')");
stat.execute("INSERT INTO TEST VALUES(1, '2001-01-01', '20:00:00', '2002-02-02 22:22:22.2')");
ResultSet rs = stat.executeQuery("SELECT * FROM TEST");
rs.next();
Date d1 = rs.getDate("D");
Time t1 = rs.getTime("T");
Timestamp ts1 = rs.getTimestamp("TS");
rs.next();
Date d2 = rs.getDate("D");
Time t2 = rs.getTime("T");
Timestamp ts2 = rs.getTimestamp("TS");
check(ts1 != ts2);
check(d1 != d2);
check(t1 != t2);
check(t2 != rs.getObject("T"));
check(d2 != rs.getObject("D"));
check(ts2 != rs.getObject("TS"));
checkFalse(rs.next());
conn.close();
}
private void testCreateDrop() throws Exception {
trace("testCreateDrop");
deleteDb("cases");
Connection conn=getConnection("cases");
Statement stat = conn.createStatement();
stat.execute(
"create table employee(id int, "
+"firstname VARCHAR(50), "
+"salary decimal(10, 2), "
+"superior_id int, "
+"CONSTRAINT PK_employee PRIMARY KEY (id), "
+"CONSTRAINT FK_superior FOREIGN KEY (superior_id) "
+"REFERENCES employee(ID))");
stat.execute("DROP TABLE employee");
conn.close();
conn=getConnection("cases");
conn.close();
}
private void testPolePos() throws Exception {
trace("testPolePos");
// poleposition-0.20
Connection c0=getConnection("cases");
c0.createStatement().executeUpdate("SET AUTOCOMMIT FALSE");
c0.createStatement().executeUpdate("create table australia (ID INTEGER NOT NULL, Name VARCHAR(100), FirstName VARCHAR(100), Points INTEGER, LicenseID INTEGER, PRIMARY KEY(ID))");
c0.createStatement().executeUpdate("COMMIT");
c0.close();
c0=getConnection("cases");
c0.createStatement().executeUpdate("SET AUTOCOMMIT FALSE");
PreparedStatement p15=c0.prepareStatement("insert into australia (id,Name,FirstName,Points,LicenseID) values (?,?,?,?,?)");
int len = getSize(1, 1000);
for(int i=0; i<len; i++) {
p15.setInt(1, i); p15.setString(2, "Pilot_"+i); p15.setString(3, "Herkules"); p15.setInt(4, i); p15.setInt(5, i); p15.executeUpdate();
}
c0.createStatement().executeUpdate("COMMIT");
c0.close();
// c0=getConnection("cases");
// c0.createStatement().executeUpdate("SET AUTOCOMMIT FALSE");
// c0.createStatement().executeQuery("select * from australia");
// c0.createStatement().executeQuery("select * from australia");
// c0.close();
// c0=getConnection("cases");
// c0.createStatement().executeUpdate("SET AUTOCOMMIT FALSE");
// c0.createStatement().executeUpdate("COMMIT");
// c0.createStatement().executeUpdate("delete from australia");
// c0.createStatement().executeUpdate("COMMIT");
// c0.close();
c0=getConnection("cases");
c0.createStatement().executeUpdate("SET AUTOCOMMIT FALSE");
c0.createStatement().executeUpdate("drop table australia");
c0.createStatement().executeUpdate("create table australia (ID INTEGER NOT NULL, Name VARCHAR(100), FirstName VARCHAR(100), Points INTEGER, LicenseID INTEGER, PRIMARY KEY(ID))");
c0.createStatement().executeUpdate("COMMIT");
c0.close();
c0=getConnection("cases");
c0.createStatement().executeUpdate("SET AUTOCOMMIT FALSE");
PreparedStatement p65=c0.prepareStatement("insert into australia (id,Name,FirstName,Points,LicenseID) values (?,?,?,?,?)");
len = getSize(1, 1000);
for(int i=0; i<len; i++) {
p65.setInt(1, i); p65.setString(2, "Pilot_"+i); p65.setString(3, "Herkules"); p65.setInt(4, i); p65.setInt(5, i); p65.executeUpdate();
}
c0.createStatement().executeUpdate("COMMIT");
c0.createStatement().executeUpdate("COMMIT");
c0.createStatement().executeUpdate("COMMIT");
c0.close();
c0=getConnection("cases");
c0.close();
}
private void testQuick() throws Exception {
trace("testQuick");
deleteDb("cases");
Connection c0=getConnection("cases");
c0.createStatement().executeUpdate("create table test (ID int PRIMARY KEY)");
c0.createStatement().executeUpdate("insert into test values(1)");
c0.createStatement().executeUpdate("drop table test");
c0.createStatement().executeUpdate("create table test (ID int PRIMARY KEY)");
c0.close();
c0=getConnection("cases");
c0.createStatement().executeUpdate("insert into test values(1)");
c0.close();
c0=getConnection("cases");
c0.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.db;
import java.sql.*;
import org.h2.test.TestBase;
public class TestCheckpoint extends TestBase {
public void test() throws Exception {
// TODO test checkpoint with rollback, not only just run the command
deleteDb("checkpoint");
Connection c0 = getConnection("checkpoint");
Statement s0 = c0.createStatement();
Connection c1 = getConnection("checkpoint");
Statement s1 = c1.createStatement();
s1.execute("CREATE TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR(255))");
s1.execute("INSERT INTO TEST VALUES(1, 'Hello')");
s0.execute("CHECKPOINT");
s1.execute("INSERT INTO TEST VALUES(2, 'World')");
c1.setAutoCommit(false);
s1.execute("INSERT INTO TEST VALUES(3, 'Maybe')");
s0.execute("CHECKPOINT");
s1.execute("INSERT INTO TEST VALUES(4, 'Or not')");
s0.execute("CHECKPOINT");
s1.execute("INSERT INTO TEST VALUES(5, 'ok yes')");
s1.execute("COMMIT");
s0.execute("CHECKPOINT");
c0.close();
c1.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.db;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.h2.test.TestBase;
import org.h2.tools.CreateCluster;
import org.h2.tools.DeleteDbFiles;
import org.h2.tools.Server;
public class TestCluster extends TestBase {
public void test() throws Exception {
if(config.memory || config.networked) {
return;
}
DeleteDbFiles.main(new String[]{"-dir", BASE_DIR + "/node1", "-quiet"});
DeleteDbFiles.main(new String[]{"-dir", BASE_DIR + "/node2", "-quiet"});
// create the master database
Connection conn;
Class.forName("org.h2.Driver");
conn = DriverManager.getConnection("jdbc:h2:file:" + BASE_DIR + "/node1/test", "sa", "");
Statement stat;
stat = conn.createStatement();
stat.execute("DROP TABLE IF EXISTS TEST");
stat.execute("CREATE TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR(255))");
PreparedStatement prep = conn.prepareStatement("INSERT INTO TEST VALUES(?, ?)");
int len = getSize(10, 1000);
for(int i=0; i<len; i++) {
prep.setInt(1, i);
prep.setString(2, "Data" + i);
prep.executeUpdate();
}
conn.close();
CreateCluster.main(new String[]{
"-urlSource", "jdbc:h2:file:"+ BASE_DIR + "/node1/test",
"-urlTarget", "jdbc:h2:file:"+BASE_DIR + "/node2/test",
"-user", "sa",
"-serverlist", "localhost:9091,localhost:9092"
});
Server n1 = org.h2.tools.Server.createTcpServer(new String[]{"-tcpPort", "9091", "-baseDir", BASE_DIR + "/node1"}).start();
Server n2 = org.h2.tools.Server.createTcpServer(new String[]{"-tcpPort", "9092", "-baseDir", BASE_DIR + "/node2"}).start();
try {
conn = DriverManager.getConnection("jdbc:h2:tcp://localhost:9091/test", "sa", "");
error("should not be able to connect in standalone mode");
} catch(SQLException e) {
checkNotGeneralException(e);
}
try {
conn = DriverManager.getConnection("jdbc:h2:tcp://localhost:9092/test", "sa", "");
error("should not be able to connect in standalone mode");
} catch(SQLException e) {
checkNotGeneralException(e);
}
conn = DriverManager.getConnection("jdbc:h2:tcp://localhost:9091,localhost:9092/test", "sa", "");
stat = conn.createStatement();
check(conn, len);
conn.close();
// n1.stop();
// n2.stop();
// n1 = org.h2.tools.Server.startTcpServer(new String[]{"-tcpPort", "9091", "-baseDir", BASE_DIR + "/node1"});
conn = DriverManager.getConnection("jdbc:h2:tcp://localhost:9091/test;CLUSTER=''", "sa", "");
check(conn, len);
conn.close();
n1.stop();
// n2 = org.h2.tools.Server.startTcpServer(new String[]{"-tcpPort", "9092", "-baseDir", BASE_DIR + "/node2"});
conn = DriverManager.getConnection("jdbc:h2:tcp://localhost:9092/test;CLUSTER=''", "sa", "");
check(conn, len);
conn.close();
n2.stop();
}
void check(Connection conn, int len) throws Exception {
PreparedStatement prep = conn.prepareStatement("SELECT * FROM TEST WHERE ID=?");
for(int i=0; i<len; i++) {
prep.setInt(1, i);
ResultSet rs = prep.executeQuery();
rs.next();
check(rs.getString(2), "Data"+i);
checkFalse(rs.next());
}
}
}
/*
* 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.db;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.Statement;
import org.h2.test.TestBase;
public class TestCompatibility extends TestBase {
private Connection conn;
public void test() throws Exception {
deleteDb("compatibility");
conn = getConnection("compatibility");
testHsqlDb();
testMySQL();
conn.close();
}
private void testHsqlDb() throws Exception {
Statement stat = conn.createStatement();
stat.execute("DROP TABLE TEST IF EXISTS; CREATE TABLE TEST(ID INT PRIMARY KEY); ");
stat.execute("CALL CURRENT_TIME");
stat.execute("CALL CURRENT_TIMESTAMP");
stat.execute("CALL CURRENT_DATE");
stat.execute("CALL SYSDATE");
stat.execute("CALL TODAY");
stat.execute("DROP TABLE TEST IF EXISTS");
stat.execute("CREATE TABLE TEST(ID INT)");
stat.execute("INSERT INTO TEST VALUES(1)");
PreparedStatement prep = conn.prepareStatement(
"SELECT LIMIT ? 1 ID FROM TEST"
);
prep.setInt(1, 2);
prep.executeQuery();
stat.execute("DROP TABLE TEST IF EXISTS");
}
private void testMySQL() throws Exception {
Statement stat = conn.createStatement();
stat.execute("SELECT 1");
stat.execute("DROP TABLE IF EXISTS TEST");
stat.execute("CREATE TABLE TEST(ID INT, NAME VARCHAR)");
stat.execute("INSERT INTO TEST VALUES(1, 'Hello'), (2, 'World')");
}
}
/*
* 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.db;
import java.io.File;
import java.io.RandomAccessFile;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import org.h2.test.TestBase;
import org.h2.tools.Csv;
public class TestCsv extends TestBase {
public void test() throws Exception {
testAsTable();
testWriteRead();
testRead();
}
private void testAsTable() throws Exception {
deleteDb("csv");
Connection conn = getConnection("csv");
Statement stat = conn.createStatement();
stat.execute("call csvwrite('test.csv', 'select 1 id, ''Hello'' name')");
ResultSet rs = stat.executeQuery("select name from csvread('test.csv')");
check(rs.next());
check(rs.getString(1), "Hello");
checkFalse(rs.next());
rs = stat.executeQuery("call csvread('test.csv')");
check(rs.next());
check(rs.getInt(1), 1);
check(rs.getString(2), "Hello");
checkFalse(rs.next());
new File("test.csv").delete();
conn.close();
}
public void testRead() throws Exception {
File f = new File(BASE_DIR + "/test.csv");
f.delete();
RandomAccessFile file = new RandomAccessFile(f, "rw");
file.write("a,b,c,d\n201,-2,0,18\n, \"abc\"\"\" ,,\"\"\n 1 ,2 , 3, 4 \n5, 6, 7, 8".getBytes());
file.close();
ResultSet rs = Csv.getInstance().read(BASE_DIR + "/test.csv", null, "UTF8");
ResultSetMetaData meta = rs.getMetaData();
check(meta.getColumnCount(), 4);
check(meta.getColumnLabel(1), "a");
check(meta.getColumnLabel(2), "b");
check(meta.getColumnLabel(3), "c");
check(meta.getColumnLabel(4), "d");
check(rs.next());
check(rs.getString(1), "201");
check(rs.getString(2), "-2");
check(rs.getString(3), "0");
check(rs.getString(4), "18");
check(rs.next());
check(rs.getString(1), null);
check(rs.getString(2), "abc\"");
check(rs.getString(3), null);
check(rs.getString(4), "");
check(rs.next());
check(rs.getString(1), "1");
check(rs.getString(2), "2");
check(rs.getString(3), "3");
check(rs.getString(4), "4");
check(rs.next());
check(rs.getString(1), "5");
check(rs.getString(2), "6");
check(rs.getString(3), "7");
check(rs.getString(4), "8");
checkFalse(rs.next());
// a,b,c,d
// 201,-2,0,18
// 201,2,0,18
// 201,2,0,18
// 201,2,0,18
// 201,2,0,18
// 201,2,0,18
}
public void testWriteRead() throws Exception {
deleteDb("csv");
Connection conn = getConnection("csv");
Statement stat = conn.createStatement();
stat.execute("CREATE TABLE TEST(ID IDENTITY, NAME VARCHAR)");
int len = 100;
for(int i=0; i<len; i++) {
stat.execute("INSERT INTO TEST(NAME) VALUES('Ruebezahl')");
}
Csv.getInstance().write(conn, BASE_DIR + "/test.csv", "SELECT * FROM TEST", "UTF8");
ResultSet rs = Csv.getInstance().read(BASE_DIR + "/test.csv", null, "UTF8");
// stat.execute("CREATE ALIAS CSVREAD FOR \"org.h2.tools.Csv.read\"");
ResultSetMetaData meta = rs.getMetaData();
check(2, meta.getColumnCount());
for(int i=0; i<len; i++) {
rs.next();
check(rs.getString("ID"), "" + (i+1));
check(rs.getString("NAME"), "Ruebezahl");
}
checkFalse(rs.next());
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.db;
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import org.h2.test.TestBase;
import org.h2.tools.SimpleResultSet;
public class TestFunctions extends TestBase {
Statement stat;
public void test() throws Exception {
deleteDb("functions");
Connection conn = getConnection("functions");
stat = conn.createStatement();
test("abs(null)", null);
test("abs(1)", "1");
test("abs(1)", "1");
stat.execute("CREATE TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR)");
stat.execute("CREATE ALIAS ADDROW FOR \"" + getClass().getName() + ".addRow\"");
ResultSet rs;
rs = stat.executeQuery("CALL ADDROW(1, 'Hello')");
rs.next();
check(rs.getInt(1), 1);
rs = stat.executeQuery("SELECT * FROM TEST");
rs.next();
check(rs.getInt(1), 1);
check(rs.getString(2), "Hello");
checkFalse(rs.next());
rs = stat.executeQuery("CALL ADDROW(2, 'World')");
stat.execute("CREATE ALIAS SEL FOR \"" + getClass().getName() + ".select\"");
rs = stat.executeQuery("CALL SEL('SELECT * FROM TEST ORDER BY ID')");
check(rs.getMetaData().getColumnCount(), 2);
rs.next();
check(rs.getInt(1), 1);
check(rs.getString(2), "Hello");
rs.next();
check(rs.getInt(1), 2);
check(rs.getString(2), "World");
checkFalse(rs.next());
rs = stat.executeQuery("SELECT NAME FROM SEL('SELECT * FROM TEST ORDER BY NAME') ORDER BY NAME DESC");
check(rs.getMetaData().getColumnCount(), 1);
rs.next();
check(rs.getString(1), "World");
rs.next();
check(rs.getString(1), "Hello");
checkFalse(rs.next());
rs = stat.executeQuery("SELECT SEL('SELECT * FROM TEST WHERE ID=' || ID) FROM TEST ORDER BY ID");
check(rs.getMetaData().getColumnCount(), 1);
rs.next();
check("((1, Hello))", rs.getString(1));
rs.next();
check("((2, World))", rs.getString(1));
checkFalse(rs.next());
rs = stat.executeQuery("SELECT SEL('SELECT * FROM TEST ORDER BY ID') FROM DUAL");
check(rs.getMetaData().getColumnCount(), 1);
rs.next();
check("((1, Hello), (2, World))", rs.getString(1));
checkFalse(rs.next());
try {
rs = stat.executeQuery("CALL SEL('ERROR')");
error("expected error");
} catch (SQLException e) {
check("42001", e.getSQLState());
}
stat.execute("CREATE ALIAS SIMPLE FOR \"" + getClass().getName() + ".simpleResultSet\"");
rs = stat.executeQuery("CALL SIMPLE(2, 1,1,1,1,1,1,1)");
check(rs.getMetaData().getColumnCount(), 2);
rs.next();
check(rs.getInt(1), 0);
check(rs.getString(2), "Hello");
rs.next();
check(rs.getInt(1), 1);
check(rs.getString(2), "World");
checkFalse(rs.next());
rs = stat.executeQuery("SELECT * FROM SIMPLE(1, 1,1,1,1,1,1,1)");
check(rs.getMetaData().getColumnCount(), 2);
rs.next();
check(rs.getInt(1), 0);
check(rs.getString(2), "Hello");
checkFalse(rs.next());
stat.execute("CREATE ALIAS ARRAY FOR \"" + getClass().getName() + ".getArray\"");
rs = stat.executeQuery("CALL ARRAY()");
check(rs.getMetaData().getColumnCount(), 2);
rs.next();
check(rs.getInt(1), 0);
check(rs.getString(2), "Hello");
checkFalse(rs.next());
stat.execute("CREATE ALIAS ROOT FOR \"" + getClass().getName() + ".root\"");
rs = stat.executeQuery("CALL ROOT(9)");
rs.next();
check(rs.getInt(1), 3);
checkFalse(rs.next());
stat.execute("CREATE ALIAS MAXID FOR \"" + getClass().getName() + ".selectMaxId\"");
rs = stat.executeQuery("CALL MAXID()");
rs.next();
check(rs.getInt(1), 2);
checkFalse(rs.next());
rs = stat.executeQuery("SELECT * FROM MAXID()");
rs.next();
check(rs.getInt(1), 2);
checkFalse(rs.next());
rs = stat.executeQuery("CALL CASE WHEN -9 < 0 THEN 0 ELSE ROOT(-9) END");
rs.next();
check(rs.getInt(1), 0);
checkFalse(rs.next());
stat.execute("CREATE ALIAS blob2stream FOR \"" + getClass().getName() + ".blob2stream\"");
stat.execute("CREATE ALIAS stream2stream FOR \"" + getClass().getName() + ".stream2stream\"");
stat.execute("CREATE TABLE TEST_BLOB(ID INT PRIMARY KEY, VALUE BLOB)");
stat.execute("INSERT INTO TEST_BLOB VALUES(0, null)");
stat.execute("INSERT INTO TEST_BLOB VALUES(1, 'edd1f011edd1f011edd1f011')");
rs = stat.executeQuery("SELECT blob2stream(VALUE) FROM TEST_BLOB");
while(rs.next()) {
}
rs.close();
rs = stat.executeQuery("SELECT stream2stream(VALUE) FROM TEST_BLOB");
while(rs.next()) {
// ignore
}
stat.execute("CREATE ALIAS NULLRESULT FOR \"" + getClass().getName() + ".nullResultSet\"");
rs = stat.executeQuery("CALL NULLRESULT()");
check(rs.getMetaData().getColumnCount(), 1);
rs.next();
check(rs.getString(1), null);
checkFalse(rs.next());
conn.close();
}
void test(String sql, String value) throws Exception {
ResultSet rs = stat.executeQuery("CALL " + sql);
rs.next();
String s = rs.getString(1);
check(value, s);
}
public static BufferedInputStream blob2stream(Blob value) throws SQLException {
if(value == null) {
return null;
}
BufferedInputStream bufferedInStream = new BufferedInputStream(value.getBinaryStream());
return bufferedInStream;
}
public static BufferedInputStream stream2stream(InputStream value) throws SQLException {
if(value == null) {
return null;
}
BufferedInputStream bufferedInStream = new BufferedInputStream(value);
return bufferedInStream;
}
public static int addRow(Connection conn, int id, String name) throws SQLException {
conn.createStatement().execute("INSERT INTO TEST VALUES(" + id + ", '" + name + "')");
ResultSet rs = conn.createStatement().executeQuery("SELECT COUNT(*) FROM TEST");
rs.next();
int result = rs.getInt(1);
rs.close();
return result;
}
public static ResultSet select(Connection conn, String sql) throws SQLException {
return conn.createStatement().executeQuery(sql);
}
public static ResultSet selectMaxId(Connection conn) throws SQLException {
return conn.createStatement().executeQuery("SELECT MAX(ID) FROM TEST");
}
public static Object[] getArray() {
return new Object[] { new Integer(0), "Hello" };
}
public static ResultSet nullResultSet(Connection conn) throws SQLException {
PreparedStatement statement = conn.prepareStatement("select null from system_range(1,1)");
return statement.executeQuery();
}
public static ResultSet simpleResultSet(Integer count, int ip, boolean bp, float fp, double dp, long lp, byte byp, short sp) throws SQLException {
SimpleResultSet rs = new SimpleResultSet();
rs.addColumn("ID", Types.INTEGER, 10, 0);
rs.addColumn("NAME", Types.VARCHAR, 255, 0);
if (count == null) {
if (ip != 0 || bp || fp != 0.0 || dp != 0.0 || sp != 0 || lp != 0 || byp != 0) {
throw new Error("params not 0/false");
}
}
if (count != null) {
if (ip != 1 || !bp || fp != 1.0 || dp != 1.0 || sp != 1 || lp != 1 || byp != 1) {
throw new Error("params not 1/true");
}
if (count.intValue() >= 1) {
rs.addRow(new Object[] { new Integer(0), "Hello" });
}
if (count.intValue() >= 2) {
rs.addRow(new Object[] { new Integer(1), "World" });
}
}
return rs;
}
public static int root(int value) {
if (value < 0) {
new Exception("function called but should not").printStackTrace();
}
return (int) Math.sqrt(value);
}
}
/*
* 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.db;
import java.sql.*;
import java.util.Random;
import org.h2.test.TestBase;
public class TestIndex extends TestBase {
Connection conn;
Statement stat;
Random random = new Random();
private void reconnect() throws Exception {
if(conn != null) {
conn.close();
conn = null;
}
conn = getConnection("index");
stat = conn.createStatement();
}
public void test() throws Exception {
if(config.networked && config.big) {
return;
}
random.setSeed(100);
deleteDb("index");
testWideIndex(147);
testWideIndex(313);
testWideIndex(979);
testWideIndex(1200);
testWideIndex(2400);
if(config.big && config.logMode == 2) {
for(int i=0; i<2000; i++) {
if((i%100)==0) {
System.out.println("width: " + i);
}
testWideIndex(i);
}
}
testLike();
reconnect();
testConstraint();
testLargeIndex();
testMultiColumnIndex();
//long time;
//time = System.currentTimeMillis();
testHashIndex(true, false);
testHashIndex(false, false);
//System.out.println("btree="+(System.currentTimeMillis()-time));
//time = System.currentTimeMillis();
testHashIndex(true, true);
testHashIndex(false, true);
//System.out.println("hash="+(System.currentTimeMillis()-time));
testMultiColumnHashIndex();
conn.close();
}
String getRandomString(int len) {
StringBuffer buff = new StringBuffer();
for(int i = 0; i<len; i++) {
buff.append((char)('a' + random.nextInt(26)));
}
return buff.toString();
}
void testWideIndex(int length) throws Exception {
reconnect();
stat.execute("CREATE TABLE TEST(ID INT, NAME VARCHAR)");
stat.execute("CREATE INDEX IDXNAME ON TEST(NAME)");
for(int i=0; i<100; i++) {
stat.execute("INSERT INTO TEST VALUES("+i+", SPACE("+length+") || "+i+" )");
}
ResultSet rs = stat.executeQuery("SELECT * FROM TEST ORDER BY NAME");
while(rs.next()) {
int id = rs.getInt("ID");
String name = rs.getString("NAME");
check(""+id, name.trim());
}
if(!config.memory) {
reconnect();
rs = stat.executeQuery("SELECT * FROM TEST ORDER BY NAME");
while(rs.next()) {
int id = rs.getInt("ID");
String name = rs.getString("NAME");
check(""+id, name.trim());
}
}
stat.execute("DROP TABLE TEST");
}
void testLike() throws Exception {
reconnect();
stat.execute("CREATE TABLE ABC(ID INT, NAME VARCHAR)");
stat.execute("INSERT INTO ABC VALUES(1, 'Hello')");
PreparedStatement prep = conn.prepareStatement("SELECT * FROM ABC WHERE NAME LIKE CAST(? AS VARCHAR)");
prep.setString(1, "Hi%");
prep.execute();
stat.execute("DROP TABLE ABC");
}
void testConstraint() throws Exception {
if(config.memory) {
return;
}
stat.execute("CREATE TABLE PARENT(ID INT PRIMARY KEY)");
stat.execute("CREATE TABLE CHILD(ID INT PRIMARY KEY, PID INT, FOREIGN KEY(PID) REFERENCES PARENT(ID))");
reconnect();
stat.execute("DROP TABLE PARENT");
stat.execute("DROP TABLE CHILD");
}
void testLargeIndex() throws Exception {
random.setSeed(10);
for(int i=1; i<100; i += getSize(1000, 3)) {
stat.execute("DROP TABLE IF EXISTS TEST");
stat.execute("CREATE TABLE TEST(NAME VARCHAR("+i+"))");
stat.execute("CREATE INDEX IDXNAME ON TEST(NAME)");
PreparedStatement prep = conn.prepareStatement("INSERT INTO TEST VALUES(?)");
for(int j=0; j<getSize(2, 5); j++) {
prep.setString(1, getRandomString(i));
prep.execute();
}
if(!config.memory) {
conn.close();
conn = getConnection("index");
stat = conn.createStatement();
}
ResultSet rs = stat.executeQuery("SELECT COUNT(*) FROM TEST WHERE NAME > 'mdd'");
rs.next();
int count = rs.getInt(1);
trace(i+" count="+count);
}
stat.execute("DROP TABLE IF EXISTS TEST");
}
void testHashIndex(boolean primaryKey, boolean hash) throws Exception {
if(config.memory) {
return;
}
reconnect();
stat.execute("DROP TABLE IF EXISTS TEST");
if(primaryKey) {
stat.execute("CREATE TABLE TEST(A INT PRIMARY KEY "+(hash?"HASH":"")+", B INT)");
} else {
stat.execute("CREATE TABLE TEST(A INT, B INT)");
stat.execute("CREATE UNIQUE "+(hash?"HASH":"")+" INDEX ON TEST(A)");
}
PreparedStatement prep;
prep = conn.prepareStatement("INSERT INTO TEST VALUES(?, ?)");
int len = getSize(5, 1000);
for(int a=0; a<len; a++) {
prep.setInt(1, a);
prep.setInt(2, a);
prep.execute();
check(1, getValue(stat, "SELECT COUNT(*) FROM TEST WHERE A=" + a));
check(0, getValue(stat, "SELECT COUNT(*) FROM TEST WHERE A=-1-" + a));
}
reconnect();
prep = conn.prepareStatement("DELETE FROM TEST WHERE A=?");
for(int a=0; a<len; a++) {
if(getValue(stat, "SELECT COUNT(*) FROM TEST WHERE A=" + a) != 1) {
check(1, getValue(stat, "SELECT COUNT(*) FROM TEST WHERE A=" + a));
}
prep.setInt(1, a);
check(1, prep.executeUpdate());
}
check(0, getValue(stat, "SELECT COUNT(*) FROM TEST"));
}
void testMultiColumnIndex() throws Exception {
stat.execute("DROP TABLE IF EXISTS TEST");
stat.execute("CREATE TABLE TEST(A INT, B INT)");
PreparedStatement prep;
prep = conn.prepareStatement("INSERT INTO TEST VALUES(?, ?)");
int len = getSize(3, 260);
for(int a=0; a<len; a++) {
prep.setInt(1, a);
prep.setInt(2, a);
prep.execute();
}
stat.execute("INSERT INTO TEST SELECT A, B FROM TEST");
stat.execute("CREATE INDEX ON TEST(A, B)");
prep = conn.prepareStatement("DELETE FROM TEST WHERE A=?");
for(int a=0; a<len; a++) {
log(stat, "SELECT * FROM TEST");
check(2, getValue(stat, "SELECT COUNT(*) FROM TEST WHERE A=" + (len-a-1)));
check((len-a)*2, getValue(stat, "SELECT COUNT(*) FROM TEST"));
prep.setInt(1, (len-a-1));
prep.execute();
}
check(0, getValue(stat, "SELECT COUNT(*) FROM TEST"));
}
void testMultiColumnHashIndex() throws Exception {
if(config.memory) {
return;
}
stat.execute("DROP TABLE IF EXISTS TEST");
stat.execute("CREATE TABLE TEST(A INT, B INT, DATA VARCHAR(255))");
stat.execute("CREATE UNIQUE HASH INDEX IDXAB ON TEST(A, B)");
PreparedStatement prep;
prep = conn.prepareStatement("INSERT INTO TEST VALUES(?, ?, ?)");
// speed is quadratic (len*len)
int len = getSize(2, 14);
for(int a=0; a<len; a++) {
for(int b=0; b<len; b+=2) {
prep.setInt(1, a);
prep.setInt(2, b);
prep.setString(3, "i("+a+","+b+")");
prep.execute();
}
}
reconnect();
prep = conn.prepareStatement("UPDATE TEST SET DATA=DATA||? WHERE A=? AND B=?");
for(int a=0; a<len; a++) {
for(int b=0; b<len; b+=2) {
prep.setString(1, "u("+a+","+b+")");
prep.setInt(2, a);
prep.setInt(3, b);
prep.execute();
}
}
reconnect();
ResultSet rs = stat.executeQuery("SELECT * FROM TEST WHERE DATA <> 'i('||a||','||b||')u('||a||','||b||')'");
checkFalse(rs.next());
check(len*(len/2), getValue(stat, "SELECT COUNT(*) FROM TEST"));
stat.execute("DROP TABLE TEST");
}
int getValue(Statement stat, String sql) throws Exception {
ResultSet rs = stat.executeQuery(sql);
rs.next();
return rs.getInt(1);
}
void log(Statement stat, String sql) throws Exception {
trace(sql);
ResultSet rs = stat.executeQuery(sql);
int cols = rs.getMetaData().getColumnCount();
while(rs.next()) {
for(int i=0; i<cols; i++) {
trace("["+i+"]="+rs.getString(i+1));
}
}
trace("---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.db;
import java.math.BigDecimal;
import java.sql.*;
import org.h2.test.TestBase;
public class TestLinkedTable extends TestBase {
public void test() throws Exception {
deleteDb("linked1");
deleteDb("linked2");
Class.forName("org.h2.Driver");
Connection conn = DriverManager.getConnection("jdbc:h2:"+BASE_DIR+"/linked1", "sa1", "abc");
Statement stat = conn.createStatement();
stat.execute("CREATE TEMP TABLE TEST_TEMP(ID INT PRIMARY KEY)");
stat.execute("CREATE TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR(255), XT TINYINT, XD DECIMAL(10,2), XTS TIMESTAMP, XBY BINARY(255), XBO BIT, XSM SMALLINT, XBI BIGINT, XBL BLOB, XDA DATE, XTI TIME, XCL CLOB, XDO DOUBLE)");
stat.execute("CREATE INDEX IDXNAME ON TEST(NAME)");
stat.execute("INSERT INTO TEST VALUES(0, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL)");
stat.execute("INSERT INTO TEST VALUES(1, 'Hello', -1, 10.30, '2001-02-03 11:22:33.4455', X'FF0102', TRUE, 3000, 1234567890123456789, X'1122AA', DATE '0002-01-01', TIME '00:00:00', 'J\u00fcrg', 2.25)");
testRow(stat, "TEST");
stat.execute("INSERT INTO TEST VALUES(2, 'World', 30, 100.05, '2005-12-31 12:34:56.789', X'FFEECC33', FALSE, 1, -1234567890123456789, X'4455FF', DATE '9999-12-31', TIME '23:59:59', 'George', -2.5)");
testRow(stat, "TEST");
stat.execute("SELECT * FROM TEST_TEMP");
conn.close();
conn = DriverManager.getConnection("jdbc:h2:"+BASE_DIR+"/linked1", "sa1", "abc");
stat = conn.createStatement();
testRow(stat, "TEST");
try {
stat.execute("SELECT * FROM TEST_TEMP");
error("temp table must not be persistent");
} catch(SQLException e) {
checkNotGeneralException(e);
}
conn.close();
conn = DriverManager.getConnection("jdbc:h2:"+BASE_DIR+"/linked2", "sa2", "def");
stat = conn.createStatement();
stat.execute("CREATE LINKED TABLE IF NOT EXISTS LINK_TEST('org.h2.Driver', 'jdbc:h2:"+BASE_DIR+"/linked1', 'sa1', 'abc', 'TEST')");
stat.execute("CREATE LINKED TABLE IF NOT EXISTS LINK_TEST('org.h2.Driver', 'jdbc:h2:"+BASE_DIR+"/linked1', 'sa1', 'abc', 'TEST')");
testRow(stat, "LINK_TEST");
conn.close();
conn = DriverManager.getConnection("jdbc:h2:"+BASE_DIR+"/linked2", "sa2", "def");
stat = conn.createStatement();
stat.execute("INSERT INTO LINK_TEST VALUES(3, 'Link Test', 30, 100.05, '2005-12-31 12:34:56.789', X'FFEECC33', FALSE, 1, -1234567890123456789, X'4455FF', DATE '9999-12-31', TIME '23:59:59', 'George', -2.5)");
ResultSet rs = stat.executeQuery("SELECT COUNT(*) FROM LINK_TEST");
rs.next();
check(rs.getInt(1), 4);
rs = stat.executeQuery("SELECT COUNT(*) FROM LINK_TEST WHERE NAME='Link Test'");
rs.next();
check(rs.getInt(1), 1);
int uc = stat.executeUpdate("DELETE FROM LINK_TEST WHERE ID=3");
check(uc, 1);
rs = stat.executeQuery("SELECT COUNT(*) FROM LINK_TEST");
rs.next();
check(rs.getInt(1), 3);
rs = stat.executeQuery("SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME='LINK_TEST'");
rs.next();
check(rs.getString("TABLE_TYPE"), "TABLE LINK");
rs.next();
rs = stat.executeQuery("SELECT * FROM LINK_TEST WHERE ID=0");
rs.next();
check(rs.getString("NAME")==null && rs.wasNull());
check(rs.getString("XT")==null && rs.wasNull());
check(rs.getInt("ID")==0 && !rs.wasNull());
check(rs.getBigDecimal("XD")==null && rs.wasNull());
check(rs.getTimestamp("XTS")==null && rs.wasNull());
check(rs.getBytes("XBY")==null && rs.wasNull());
check(rs.getBoolean("XBO")==false && rs.wasNull());
check(rs.getShort("XSM")==0 && rs.wasNull());
check(rs.getLong("XBI")==0 && rs.wasNull());
check(rs.getString("XBL")==null && rs.wasNull());
check(rs.getString("XDA")==null && rs.wasNull());
check(rs.getString("XTI")==null && rs.wasNull());
check(rs.getString("XCL")==null && rs.wasNull());
check(rs.getString("XDO")==null && rs.wasNull());
checkFalse(rs.next());
stat.execute("DROP TABLE LINK_TEST");
stat.execute("CREATE LINKED TABLE LINK_TEST('org.h2.Driver', 'jdbc:h2:"+BASE_DIR+"/linked1', 'sa1', 'abc', '(SELECT COUNT(*) FROM TEST)')");
rs = stat.executeQuery("SELECT * FROM LINK_TEST");
rs.next();
check(rs.getInt(1), 3);
checkFalse(rs.next());
conn.close();
deleteDb("linked1");
deleteDb("linked2");
}
void testRow(Statement stat, String name) throws Exception {
ResultSet rs = stat.executeQuery("SELECT * FROM "+name+" WHERE ID=1");
rs.next();
check(rs.getString("NAME"), "Hello");
check(rs.getByte("XT"), -1);
BigDecimal bd = rs.getBigDecimal("XD");
check(bd.equals(new BigDecimal("10.30")));
Timestamp ts = rs.getTimestamp("XTS");
String s = ts.toString();
check(s, "2001-02-03 11:22:33.4455");
check(ts.equals(Timestamp.valueOf("2001-02-03 11:22:33.4455")));
check(rs.getBytes("XBY"), new byte[]{(byte)255, (byte)1, (byte)2});
check(rs.getBoolean("XBO"));
check(rs.getShort("XSM"), 3000);
check(rs.getLong("XBI"), 1234567890123456789L);
check(rs.getString("XBL"), "1122aa");
check(rs.getString("XDA"), "0002-01-01");
check(rs.getString("XTI"), "00:00:00");
check(rs.getString("XCL"), "J\u00fcrg");
check(rs.getString("XDO"), "2.25");
}
}
/*
* 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.db;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import org.h2.api.DatabaseEventListener;
import org.h2.test.TestBase;
public class TestListener extends TestBase implements DatabaseEventListener {
private long last, start;
public TestListener() {
start = last = System.currentTimeMillis();
}
public void test() throws Exception {
if(config.networked) {
return;
}
deleteDb("listener");
Connection conn;
conn = getConnection("listener");
Statement stat = conn.createStatement();
stat.execute("CREATE TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR)");
PreparedStatement prep = conn.prepareStatement("INSERT INTO TEST VALUES(?, 'Test' || SPACE(100))");
int len = getSize(100, 100000);
for(int i=0; i<len; i++) {
prep.setInt(1, i);
prep.execute();
}
crash(conn);
conn = getConnection("listener;database_event_listener='" + getClass().getName() + "'");
conn.close();
}
public void diskSpaceIsLow(long stillAvailable) throws SQLException {
System.out.println("diskSpaceIsLow stillAvailable="+stillAvailable);
}
public void exceptionThrown(SQLException e) {
e.printStackTrace();
}
public void setProgress(int state, String name, int current, int max) {
long time = System.currentTimeMillis();
if(time < last+1000) {
return;
}
last = time;
String stateName;
switch(state) {
case STATE_SCAN_FILE:
stateName = "Scan " + name;
break;
case STATE_CREATE_INDEX:
stateName = "Create Index " + name;
break;
case STATE_RECOVER:
stateName = "Recover";
break;
default:
new Error("unknownn state: " + state).printStackTrace();
stateName = "? " + name;
}
try {
Thread.sleep(1);
} catch (InterruptedException e) {
}
System.out.println("state: " + stateName + " " + (100*current/max) + " " + (time-start));
}
public void closingDatabase() {
}
public void init(String url) {
}
}
/*
* Copyright 2004-2006 H2 Group. Licensed under the H2 License, Version 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.test.db;
import java.io.ByteArrayInputStream;
import java.io.CharArrayReader;
import java.io.InputStream;
import java.io.Reader;
import java.io.StringReader;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Random;
import org.h2.test.TestBase;
import org.h2.util.IOUtils;
import org.h2.util.StringUtils;
/**
* @author Thomas
*/
public class TestLob extends TestBase {
public void test() throws Exception {
if(config.memory) {
return;
}
testLobCopy();
testLobHibernate();
testLobCopy(false);
testLobCopy(true);
testLobCompression(false);
testLobCompression(true);
testManyLobs();
testClob();
testUpdateLob();
testLobReconnect();
testLob(false);
testLob(true);
testJavaObject();
}
private void testLobCopy() throws Exception {
deleteDb("lob");
Connection conn = reconnect(null);
Statement stat = conn.createStatement();
stat.execute("create table test(id int, data clob)");
stat.execute("insert into test values(1, space(1000));");
stat.execute("insert into test values(2, space(1000));");
stat.execute("create table test2(id int, data clob);");
stat.execute("insert into test2 select * from test;");
stat.execute("drop table test;");
stat.execute("select * from test2;");
stat.execute("update test2 set id=id;");
stat.execute("select * from test2;");
conn.close();
}
private void testLobHibernate() throws Exception {
deleteDb("lob");
Connection conn0 = reconnect(null);
conn0.getAutoCommit();
conn0.setAutoCommit(false);
DatabaseMetaData dbMeta0 =
conn0.getMetaData();
dbMeta0.getDatabaseProductName();
dbMeta0.getDatabaseMajorVersion();
dbMeta0.getDatabaseProductVersion();
dbMeta0.getDriverName();
dbMeta0.getDriverVersion();
dbMeta0.supportsResultSetType(1004);
dbMeta0.supportsBatchUpdates();
dbMeta0.dataDefinitionCausesTransactionCommit();
dbMeta0.dataDefinitionIgnoredInTransactions();
dbMeta0.supportsGetGeneratedKeys();
conn0.getAutoCommit();
conn0.getAutoCommit();
conn0.commit();
conn0.setAutoCommit(true);
Statement stat0 =
conn0.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();
conn0.getWarnings();
conn0.clearWarnings();
conn0.setAutoCommit(false);
conn0.getAutoCommit();
conn0.getAutoCommit();
PreparedStatement prep0 =
conn0.prepareStatement("select max(ID) from CLOB_ENTITY");
ResultSet rs0 =
prep0.executeQuery();
rs0.next();
rs0.getLong(1);
rs0.wasNull();
rs0.close();
prep0.close();
conn0.getAutoCommit();
PreparedStatement prep1 =
conn0.prepareStatement("insert into CLOB_ENTITY (SER_DATA, CLOB_DATA, ID) values (?, ?, ?)");
prep1.setNull(1, 2005);
StringBuffer buff = new StringBuffer(10000);
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();
conn0.getAutoCommit();
conn0.getAutoCommit();
conn0.commit();
conn0.isClosed();
conn0.getWarnings();
conn0.clearWarnings();
conn0.getAutoCommit();
conn0.getAutoCommit();
PreparedStatement prep2 =
conn0.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();
rs1.getCharacterStream("SER2_0_0_");
Clob clob0 =
rs1.getClob("CLOB3_0_0_");
rs1.wasNull();
rs1.next();
rs1.close();
prep2.getMaxRows();
prep2.getQueryTimeout();
prep2.close();
conn0.getAutoCommit();
Reader r = clob0.getCharacterStream();
for(int i=0; i<10000; i++) {
int ch = r.read();
if(ch != ('0' + (i%10))) {
error("expected "+ (char)('0' + (i%10)) + " got: " + ch + " (" + (char)ch + ")");
}
}
int ch = r.read();
if(ch != -1) {
error("expected -1 got: " + ch );
}
conn0.close();
}
private void testLobCopy(boolean compress) throws Exception {
deleteDb("lob");
Connection conn;
conn = reconnect(null);
Statement stat = conn.createStatement();
if(compress) {
conn.createStatement().execute("SET COMPRESS_LOB LZF");
} else {
conn.createStatement().execute("SET COMPRESS_LOB NO");
}
conn = reconnect(conn);
stat = conn.createStatement();
ResultSet rs;
rs = stat.executeQuery("select value from information_schema.settings where NAME='COMPRESS_LOB'");
rs.next();
check(rs.getString(1), compress ? "LZF" : "NO");
checkFalse(rs.next());
stat.execute("create table test(text clob)");
stat.execute("create table test2(text clob)");
StringBuffer buff = new StringBuffer();
for(int i=0; i<1000; i++) {
buff.append(' ');
}
String spaces = buff.toString();
stat.execute("insert into test values('"+spaces+"')");
stat.execute("insert into test2 select * from test");
rs = stat.executeQuery("select * from test2");
rs.next();
check(rs.getString(1), spaces);
stat.execute("drop table test");
rs = stat.executeQuery("select * from test2");
rs.next();
check(rs.getString(1), spaces);
stat.execute("alter table test2 add column id int before text");
rs = stat.executeQuery("select * from test2");
rs.next();
check(rs.getString("text"), spaces);
conn.close();
}
private void testLobCompression(boolean compress) throws Exception {
deleteDb("lob");
Connection conn;
conn = reconnect(null);
if(compress) {
conn.createStatement().execute("SET COMPRESS_LOB LZF");
} else {
conn.createStatement().execute("SET COMPRESS_LOB NO");
}
conn.createStatement().execute("CREATE TABLE TEST(ID INT PRIMARY KEY, C CLOB)");
PreparedStatement prep = conn.prepareStatement("INSERT INTO TEST VALUES(?, ?)");
long time = System.currentTimeMillis();
int len = getSize(10, 40);
if(config.networked && config.big) {
len = 5;
}
StringBuffer buff = new StringBuffer();
for(int i=0; i<100; i++) {
buff.append(StringUtils.xmlNode("content", null, "This is a test " + i));
}
String xml = buff.toString();
for(int i=0; i<len; i++) {
prep.setInt(1, i);
prep.setString(2, xml + i);
prep.execute();
}
for(int i=0; i<len; i++) {
ResultSet rs = conn.createStatement().executeQuery("SELECT * FROM TEST");
while(rs.next()) {
if(i==0) {
check(xml + rs.getInt(1), rs.getString(2));
} else {
Reader r = rs.getCharacterStream(2);
String result = IOUtils.readStringAndClose(r, -1);
check(xml + rs.getInt(1), result);
}
}
}
time = System.currentTimeMillis() - time;
// System.out.println("time: " + time +" compress: " + compress);
conn.close();
}
private void testManyLobs() throws Exception {
deleteDb("lob");
Connection conn;
conn = reconnect(null);
conn.createStatement().execute("CREATE TABLE TEST(ID INT PRIMARY KEY, B BLOB, C CLOB)");
int len = getSize(10, 2000);
if(config.networked) {
len = 100;
}
int start = 1, increment = 19;
PreparedStatement prep = conn.prepareStatement("INSERT INTO TEST(ID, B, C) VALUES(?, ?, ?)");
for(int i=start; i<len; i+=increment) {
int l = i;
prep.setInt(1, i);
prep.setBinaryStream(2, getRandomStream(l, i), -1);
prep.setCharacterStream(3, getRandomReader(l, i), -1);
prep.execute();
}
conn = reconnect(conn);
ResultSet rs = conn.createStatement().executeQuery("SELECT * FROM TEST ORDER BY ID");
while(rs.next()) {
int i = rs.getInt("ID");
Blob b = rs.getBlob("B");
Clob c = rs.getClob("C");
int l = i;
check(b.length(), l);
check(c.length(), l);
checkStream(b.getBinaryStream(), getRandomStream(l, i), -1);
checkReader(c.getCharacterStream(), getRandomReader(l, i), -1);
}
prep = conn.prepareStatement("UPDATE TEST SET B=?, C=? WHERE ID=?");
for(int i=start; i<len; i+=increment) {
int l = i;
prep.setBinaryStream(1, getRandomStream(l, -i), -1);
prep.setCharacterStream(2, getRandomReader(l, -i), -1);
prep.setInt(3, i);
prep.execute();
}
conn = reconnect(conn);
rs = conn.createStatement().executeQuery("SELECT * FROM TEST ORDER BY ID");
while(rs.next()) {
int i = rs.getInt("ID");
Blob b = rs.getBlob("B");
Clob c = rs.getClob("C");
int l = i;
check(b.length(), l);
check(c.length(), l);
checkStream(b.getBinaryStream(), getRandomStream(l, -i), -1);
checkReader(c.getCharacterStream(), getRandomReader(l, -i), -1);
}
conn.close();
}
private void testClob() throws Exception {
deleteDb("lob");
Connection conn;
conn = reconnect(null);
conn.createStatement().execute("CREATE TABLE TEST(ID IDENTITY, C CLOB)");
PreparedStatement prep = conn.prepareStatement("INSERT INTO TEST(C) VALUES(?)");
prep.setCharacterStream(1, new CharArrayReader("Bohlen".toCharArray()), "Bohlen".length());
prep.execute();
prep.setCharacterStream(1, new CharArrayReader("B\u00f6hlen".toCharArray()), "B\u00f6hlen".length());
prep.execute();
prep.setCharacterStream(1, getRandomReader(501, 1), -1);
prep.execute();
prep.setCharacterStream(1, getRandomReader(1501, 2), 401);
prep.execute();
conn = reconnect(conn);
ResultSet rs = conn.createStatement().executeQuery("SELECT * FROM TEST ORDER BY ID");
rs.next();
check("Bohlen", rs.getString("C"));
checkReader(new CharArrayReader("Bohlen".toCharArray()), rs.getCharacterStream("C"), -1);
rs.next();
checkReader(new CharArrayReader("B\u00f6hlen".toCharArray()), rs.getCharacterStream("C"), -1);
rs.next();
checkReader(getRandomReader(501, 1), rs.getCharacterStream("C"), -1);
Clob clob = rs.getClob("C");
checkReader(getRandomReader(501, 1), clob.getCharacterStream(), -1);
check(clob.length(), 501);
rs.next();
checkReader(getRandomReader(401, 2), rs.getCharacterStream("C"), -1);
checkReader(getRandomReader(1500, 2), rs.getCharacterStream("C"), 401);
clob = rs.getClob("C");
checkReader(getRandomReader(1501, 2), clob.getCharacterStream(), 401);
checkReader(getRandomReader(401, 2), clob.getCharacterStream(), 401);
check(clob.length(), 401);
checkFalse(rs.next());
conn.close();
}
private Connection reconnect(Connection conn) throws Exception {
long time = System.currentTimeMillis();
if(conn != null) {
conn.close();
}
conn = getConnection("lob");
trace("re-connect="+(System.currentTimeMillis()-time));
return conn;
}
void testUpdateLob() throws Exception {
deleteDb("lob");
Connection conn;
conn = reconnect(null);
PreparedStatement prep = conn.prepareStatement(
"CREATE TABLE IF NOT EXISTS p( id int primary key, rawbyte BLOB ); ");
prep.execute();
prep.close();
prep = conn.prepareStatement("INSERT INTO p(id) VALUES(?);");
for (int i = 0; i < 10; i++) {
prep.setInt(1, i);
prep.execute();
}
prep.close();
prep = conn.prepareStatement("UPDATE p set rawbyte=? WHERE id=?");
for (int i = 0; i < 8; i++) {
prep.setBinaryStream(1, getRandomStream(10000, i), 0);
prep.setInt(2, i);
prep.execute();
}
prep.close();
conn.commit();
conn = reconnect(conn);
conn.setAutoCommit(true);
prep = conn.prepareStatement("UPDATE p set rawbyte=? WHERE id=?");
for (int i = 8; i < 10; i++) {
prep.setBinaryStream(1, getRandomStream(10000, i), 0);
prep.setInt(2, i);
prep.execute();
}
prep.close();
prep = conn.prepareStatement("SELECT * from p");
ResultSet rs = prep.executeQuery();
while (rs.next()) {
for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) {
rs.getMetaData().getColumnName(i);
rs.getString(i);
}
}
conn.close();
}
void testLobReconnect() throws Exception {
deleteDb("lob");
Connection conn = reconnect(null);
Statement stat = conn.createStatement();
stat.execute("CREATE TABLE TEST(ID INT PRIMARY KEY, TEXT CLOB)");
PreparedStatement prep;
prep = conn.prepareStatement("INSERT INTO TEST VALUES(1, ?)");
String s = new String(getRandomChars(10000, 1));
byte[] data = s.getBytes("UTF-8");
prep.setBinaryStream(1, new ByteArrayInputStream(data), 0);
prep.execute();
conn = reconnect(conn);
stat = conn.createStatement();
ResultSet rs = stat.executeQuery("SELECT * FROM TEST WHERE ID=1");
rs.next();
checkStream(new ByteArrayInputStream(data), rs.getBinaryStream("TEXT"), -1);
prep = conn.prepareStatement("UPDATE TEST SET TEXT = ?");
s = new String(getRandomChars(10201, 1));
prep.setBinaryStream(1, new ByteArrayInputStream(data), 0);
prep.execute();
conn = reconnect(conn);
stat = conn.createStatement();
rs = stat.executeQuery("SELECT * FROM TEST WHERE ID=1");
rs.next();
checkStream(new ByteArrayInputStream(data), rs.getBinaryStream("TEXT"), -1);
stat.execute("DROP TABLE IF EXISTS TEST");
conn.close();
}
void testLob(boolean clob) throws Exception {
deleteDb("lob");
Connection conn = reconnect(null);
conn = reconnect(conn);
Statement stat = conn.createStatement();
stat.execute("DROP TABLE IF EXISTS TEST");
PreparedStatement prep;
ResultSet rs;
long time;
stat.execute("CREATE TABLE TEST(ID INT PRIMARY KEY, VALUE "+(clob?"CLOB":"BLOB")+")");
int len = getSize(1, 1000);
if(config.networked && config.big) {
len = 100;
}
time = System.currentTimeMillis();
prep = conn.prepareStatement("INSERT INTO TEST VALUES(?, ?)");
for(int i=0; i<len; i+=(i+i+1)) {
prep.setInt(1, i);
int size = i*i;
if(clob) {
prep.setCharacterStream(2, getRandomReader(size, i), 0);
} else {
prep.setBinaryStream(2, getRandomStream(size, i), 0);
}
prep.execute();
}
trace("insert="+(System.currentTimeMillis()-time));
traceMemory();
conn = reconnect(conn);
time = System.currentTimeMillis();
prep = conn.prepareStatement("SELECT ID, VALUE FROM TEST");
rs = prep.executeQuery();
while(rs.next()) {
int id = rs.getInt("ID");
int size = id*id;
if(clob) {
Reader rt = rs.getCharacterStream(2);
checkReader(rt, getRandomReader(size, id), -1);
checkReader((Reader)rs.getObject(2), getRandomReader(size, id), -1);
} else {
InputStream in = rs.getBinaryStream(2);
checkStream(in, getRandomStream(size, id), -1);
checkStream((InputStream)rs.getObject(2), getRandomStream(size, id), -1);
}
}
trace("select="+(System.currentTimeMillis()-time));
traceMemory();
conn = reconnect(conn);
time = System.currentTimeMillis();
prep = conn.prepareStatement("DELETE FROM TEST WHERE ID=?");
for(int i=0; i<len; i++) {
prep.setInt(1, i);
prep.executeUpdate();
}
trace("delete="+(System.currentTimeMillis()-time));
traceMemory();
conn = reconnect(conn);
conn.setAutoCommit(false);
prep = conn.prepareStatement(
"INSERT INTO TEST VALUES(1, ?)");
if(clob) {
prep.setCharacterStream(1, getRandomReader(0, 0), 0);
} else {
prep.setBinaryStream(1, getRandomStream(0, 0), 0);
}
prep.execute();
conn.rollback();
prep.execute();
conn.commit();
conn.createStatement().execute("DELETE FROM TEST WHERE ID=1");
conn.rollback();
conn.createStatement().execute("DELETE FROM TEST WHERE ID=1");
conn.commit();
conn.createStatement().execute("DROP TABLE TEST");
conn.close();
}
void testJavaObject() throws Exception {
deleteDb("lob");
Connection conn = getConnection("lob");
conn.createStatement().execute("CREATE TABLE TEST(ID INT PRIMARY KEY, DATA OTHER)");
PreparedStatement prep = conn.prepareStatement("INSERT INTO TEST VALUES(1, ?)");
prep.setObject(1, new TestLobObject("abc"));
prep.execute();
ResultSet rs = conn.createStatement().executeQuery("SELECT * FROM TEST");
rs.next();
Object oa = rs.getObject(2);
TestLobObject a = (TestLobObject)oa;
Object ob = rs.getObject("DATA");
TestLobObject b = (TestLobObject)ob;
check(a.data, "abc");
check(b.data, "abc");
checkFalse(rs.next());
conn.close();
}
private void checkStream(InputStream a, InputStream b, int len) throws Exception {
// this doesn't actually read anything - just tests reading 0 bytes
a.read(new byte[0]);
b.read(new byte[0]);
a.read(new byte[10], 3, 0);
b.read(new byte[10], 0, 0);
for(int i=0; len<0 || i<len; i++) {
int ca = a.read();
a.read(new byte[0]);
int cb = b.read();
check(ca, cb);
if(ca==-1) {
break;
}
}
a.read(new byte[10], 3, 0);
b.read(new byte[10], 0, 0);
a.read(new byte[0]);
b.read(new byte[0]);
a.close();
b.close();
}
private void checkReader(Reader a, Reader b, int len) throws Exception {
for(int i=0; len<0 || i<len; i++) {
int ca = a.read();
int cb = b.read();
check(ca, cb);
if(ca==-1) {
break;
}
}
a.close();
b.close();
}
private Reader getRandomReader(int len, int seed) {
return new CharArrayReader(getRandomChars(len, seed));
}
private char[] getRandomChars(int len, int seed) {
Random random = new Random(seed);
char[] buff = new char[len];
for(int i=0; i<len; i++) {
char ch;
do {
ch = (char)random.nextInt(Character.MAX_VALUE);
// UTF8: String.getBytes("UTF-8") only returns 1 byte for 0xd800-0xdfff
} while(ch >= 0xd800 && ch <= 0xdfff);
buff[i] = ch;
}
return buff;
}
private InputStream getRandomStream(int len, int seed) {
Random random = new Random(seed);
byte[] buff = new byte[len];
random.nextBytes(buff);
return new ByteArrayInputStream(buff);
}
}
/*
* 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.db;
import java.io.Serializable;
class TestLobObject implements Serializable {
private static final long serialVersionUID = 904356179316518715L;
String data;
TestLobObject(String data) {
this.data = data;
}
}
/*
* 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.db;
import java.io.File;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.Statement;
import java.util.ArrayList;
import org.h2.test.TestBase;
import org.h2.tools.FileBase;
public class TestLogFile extends TestBase {
private Connection conn;
private static final int MAX_LOG_SIZE = 1;
private long reconnect(int maxFiles) throws Exception {
if(conn != null) {
conn.close();
}
long length = 0;
ArrayList files = FileBase.getDatabaseFiles(BASE_DIR, "logfile", false);
checkSmaller(files.size(), maxFiles+2);
for(int i=0; i<files.size(); i++) {
String fileName = (String) files.get(i);
long len = new File(fileName).length();
length += len;
}
conn = getConnection("logfile");
return length;
}
public void test() throws Exception {
if(config.memory) {
return;
}
deleteDb("logfile");
reconnect(0);
insert();
int maxFiles = 3; // data, index, log
for(int i=0; i<3; i++) {
long length = reconnect(maxFiles);
insert();
long l2 = reconnect(maxFiles);
trace("l2="+ l2);
check(l2 <= length * 2);
}
conn.close();
}
private void checkLogSize() throws Exception {
String[] files = new File(".").list();
for(int j=0; j<files.length; j++) {
String name = files[j];
if(name.startsWith("logfile") && name.endsWith(".log.db")) {
long length = new File(name).length();
checkSmaller(length, MAX_LOG_SIZE * 1024 * 1024 * 2);
}
}
}
void insert() throws Exception {
Statement stat = conn.createStatement();
stat.execute("SET LOGSIZE 200");
stat.execute("SET MAX_LOG_SIZE " + MAX_LOG_SIZE);
stat.execute("DROP TABLE IF EXISTS TEST");
stat.execute("CREATE TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR(255))");
PreparedStatement prep = conn.prepareStatement("INSERT INTO TEST VALUES(?, 'Hello' || ?)");
int len = getSize(1, 10000);
for(int i=0; i<len; i++) {
prep.setInt(1, i);
prep.setInt(2, i);
prep.execute();
if(i>0 && (i % 2000) == 0) {
checkLogSize();
}
}
checkLogSize();
}
}
/*
* 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.db;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Random;
import org.h2.test.TestBase;
public class TestMemoryUsage extends TestBase {
private Connection conn;
private void reconnect() throws Exception {
if(conn != null) {
conn.close();
}
// Class.forName("org.hsqldb.jdbcDriver");
// conn = DriverManager.getConnection("jdbc:hsqldb:test", "sa", "");
conn = getConnection("memoryUsage");
}
public void test() throws Exception {
deleteDb("memoryUsage");
reconnect();
insertUpdateSelectDelete();
reconnect();
insertUpdateSelectDelete();
conn.close();
}
void insertUpdateSelectDelete() throws Exception {
Statement stat = conn.createStatement();
long time;
int len = getSize(1, 2000);
// insert
time = System.currentTimeMillis();
stat.execute("DROP TABLE IF EXISTS TEST");
trace("drop=" + (System.currentTimeMillis()-time));
stat.execute("CREATE CACHED TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR(255))");
PreparedStatement prep = conn.prepareStatement("INSERT INTO TEST VALUES(?, 'Hello World')");
printTimeMemory("start", 0);
time = System.currentTimeMillis();
for(int i=0; i<len; i++) {
prep.setInt(1, i);
prep.execute();
if(i % 50000 == 0) {
trace(" " + (100*i/len) + "%");
}
}
printTimeMemory("insert", System.currentTimeMillis()-time);
// update
time = System.currentTimeMillis();
prep = conn.prepareStatement("UPDATE TEST SET NAME='Hallo Welt' WHERE ID = ?");
for(int i=0; i<len; i++) {
prep.setInt(1, i);
prep.execute();
if(i % 50000 == 0) {
trace(" " + (100*i/len) + "%");
}
}
printTimeMemory("update", System.currentTimeMillis()-time);
// select
time = System.currentTimeMillis();
prep = conn.prepareStatement("SELECT * FROM TEST WHERE ID = ?");
for(int i=0; i<len; i++) {
prep.setInt(1, i);
ResultSet rs = prep.executeQuery();
rs.next();
if(rs.next()) {
error("one row expected, got more");
}
if(i % 50000 == 0) {
trace(" " + (100*i/len) + "%");
}
}
printTimeMemory("select", System.currentTimeMillis()-time);
// select randomized
Random random = new Random(1);
time = System.currentTimeMillis();
prep = conn.prepareStatement("SELECT * FROM TEST WHERE ID = ?");
for(int i=0; i<len; i++) {
prep.setInt(1, random.nextInt(len));
ResultSet rs = prep.executeQuery();
rs.next();
if(rs.next()) {
error("one row expected, got more");
}
if(i % 50000 == 0) {
trace(" " + (100*i/len) + "%");
}
}
printTimeMemory("select randomized", System.currentTimeMillis()-time);
// delete
time = System.currentTimeMillis();
prep = conn.prepareStatement("DELETE FROM TEST WHERE ID = ?");
for(int i=0; i<len; i++) {
prep.setInt(1, random.nextInt(len));
prep.executeUpdate();
if(i % 50000 == 0) {
trace(" " + (100*i/len) + "%");
}
}
printTimeMemory("delete", System.currentTimeMillis()-time);
}
}
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论