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

--no commit message

--no commit message
上级 f447a3e4
...@@ -456,4 +456,4 @@ SELECT 'newsfeed-atom.xml' FILE, ...@@ -456,4 +456,4 @@ SELECT 'newsfeed-atom.xml' FILE,
) CONTENT ) CONTENT
FROM CHANNEL C, ITEM I FROM CHANNEL C, ITEM I
UNION UNION
SELECT '-newsletter-' FILE, I.DESC CONTENT FROM ITEM I WHERE I.ID = (SELECT MAX(ID) FROM ITEM) SELECT '-newsletter-' FILE, I.DESC CONTENT FROM ITEM I WHERE I.ID = (SELECT MAX(ID) FROM ITEM)
\ No newline at end of file
...@@ -63,4 +63,4 @@ ...@@ -63,4 +63,4 @@
</description> </description>
</item> </item>
</channel> </channel>
</rss> </rss>
\ No newline at end of file
...@@ -13,7 +13,7 @@ import org.h2.tools.Restore; ...@@ -13,7 +13,7 @@ import org.h2.tools.Restore;
public class TestBackup extends TestBase { public class TestBackup extends TestBase {
public void test() throws Exception { public void test() throws Exception {
if(config.memory || config.logMode == 0) { if (config.memory || config.logMode == 0) {
return; return;
} }
testBackup(); testBackup();
...@@ -35,11 +35,11 @@ public class TestBackup extends TestBase { ...@@ -35,11 +35,11 @@ public class TestBackup extends TestBase {
conn2.setAutoCommit(false); conn2.setAutoCommit(false);
stat2.execute("insert into test values(4, 'fourth (uncommitted)')"); stat2.execute("insert into test values(4, 'fourth (uncommitted)')");
stat2.execute("insert into testlob values(2, ' ', '00')"); stat2.execute("insert into testlob values(2, ' ', '00')");
stat1.execute("backup to '" + baseDir + "/backup.zip'"); stat1.execute("backup to '" + baseDir + "/backup.zip'");
conn2.rollback(); conn2.rollback();
compareDatabases(stat1, stat2); compareDatabases(stat1, stat2);
Restore.execute(baseDir + "/backup.zip", baseDir, "restored", true); Restore.execute(baseDir + "/backup.zip", baseDir, "restored", true);
conn3 = getConnection("restored"); conn3 = getConnection("restored");
stat3 = conn3.createStatement(); stat3 = conn3.createStatement();
...@@ -51,4 +51,3 @@ public class TestBackup extends TestBase { ...@@ -51,4 +51,3 @@ public class TestBackup extends TestBase {
} }
} }
...@@ -4,7 +4,12 @@ ...@@ -4,7 +4,12 @@
*/ */
package org.h2.test.db; package org.h2.test.db;
import java.sql.*; import java.sql.BatchUpdateException;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import org.h2.test.TestBase; import org.h2.test.TestBase;
...@@ -68,14 +73,14 @@ public class TestBatchUpdates extends TestBase { ...@@ -68,14 +73,14 @@ public class TestBatchUpdates extends TestBase {
testExecuteBatch06(); testExecuteBatch06();
testExecuteBatch07(); testExecuteBatch07();
testContinueBatch01(); testContinueBatch01();
conn.close(); conn.close();
} }
public void testAddBatch01() throws Exception { public void testAddBatch01() throws Exception {
trace("testAddBatch01"); trace("testAddBatch01");
int i = 0; int i = 0;
int[] retValue = { 0, 0, 0}; int[] retValue = { 0, 0, 0 };
String s = COFFEE_UPDATE; String s = COFFEE_UPDATE;
trace("Prepared Statement String:" + s); trace("Prepared Statement String:" + s);
prep = conn.prepareStatement(s); prep = conn.prepareStatement(s);
...@@ -87,17 +92,16 @@ public class TestBatchUpdates extends TestBase { ...@@ -87,17 +92,16 @@ public class TestBatchUpdates extends TestBase {
prep.addBatch(); prep.addBatch();
int[] updateCount = prep.executeBatch(); int[] updateCount = prep.executeBatch();
int updateCountLen = updateCount.length; int updateCountLen = updateCount.length;
// PreparedStatement p; // PreparedStatement p;
// p = conn.prepareStatement(COFFEE_UPDATE); // p = conn.prepareStatement(COFFEE_UPDATE);
// p.setInt(1,2); // p.setInt(1,2);
// System.out.println("upc="+p.executeUpdate()); // System.out.println("upc="+p.executeUpdate());
// p.setInt(1,3); // p.setInt(1,3);
// System.out.println("upc="+p.executeUpdate()); // System.out.println("upc="+p.executeUpdate());
// p.setInt(1,4); // p.setInt(1,4);
// System.out.println("upc="+p.executeUpdate()); // System.out.println("upc="+p.executeUpdate());
trace("updateCount length:" + updateCountLen); trace("updateCount length:" + updateCountLen);
if (updateCountLen != 3) { if (updateCountLen != 3) {
error("addBatch"); error("addBatch");
...@@ -125,7 +129,7 @@ public class TestBatchUpdates extends TestBase { ...@@ -125,7 +129,7 @@ public class TestBatchUpdates extends TestBase {
public void testAddBatch02() throws Exception { public void testAddBatch02() throws Exception {
trace("testAddBatch02"); trace("testAddBatch02");
int i = 0; int i = 0;
int[] retValue = { 0, 0, 0}; int[] retValue = { 0, 0, 0 };
int updCountLength = 0; int updCountLength = 0;
String sUpdCoffee = COFFEE_UPDATE1; String sUpdCoffee = COFFEE_UPDATE1;
String sDelCoffee = COFFEE_DELETE1; String sDelCoffee = COFFEE_DELETE1;
...@@ -203,7 +207,7 @@ public class TestBatchUpdates extends TestBase { ...@@ -203,7 +207,7 @@ public class TestBatchUpdates extends TestBase {
public void testExecuteBatch01() throws Exception { public void testExecuteBatch01() throws Exception {
trace("testExecuteBatch01"); trace("testExecuteBatch01");
int i = 0; int i = 0;
int[] retValue = { 0, 0, 0}; int[] retValue = { 0, 0, 0 };
int updCountLength = 0; int updCountLength = 0;
String sPrepStmt = COFFEE_UPDATE; String sPrepStmt = COFFEE_UPDATE;
trace("Prepared Statement String:" + sPrepStmt); trace("Prepared Statement String:" + sPrepStmt);
...@@ -224,9 +228,9 @@ public class TestBatchUpdates extends TestBase { ...@@ -224,9 +228,9 @@ public class TestBatchUpdates extends TestBase {
} else { } else {
trace("executeBatch executes the Batch of SQL statements"); trace("executeBatch executes the Batch of SQL statements");
} }
//1 is the number that is set First for Type Id in Prepared Statement // 1 is the number that is set First for Type Id in Prepared Statement
String query1 = "SELECT COUNT(*) FROM TEST WHERE TYPE_ID=1"; String query1 = "SELECT COUNT(*) FROM TEST WHERE TYPE_ID=1";
//2 is the number that is set second for Type id in Prepared Statement // 2 is the number that is set second for Type id in Prepared Statement
String query2 = "SELECT COUNT(*) FROM TEST WHERE TYPE_ID=2"; String query2 = "SELECT COUNT(*) FROM TEST WHERE TYPE_ID=2";
// 3 is the number that is set Third for Type id in Prepared Statement // 3 is the number that is set Third for Type id in Prepared Statement
String query3 = "SELECT COUNT(*) FROM TEST WHERE TYPE_ID=3"; String query3 = "SELECT COUNT(*) FROM TEST WHERE TYPE_ID=3";
...@@ -291,7 +295,7 @@ public class TestBatchUpdates extends TestBase { ...@@ -291,7 +295,7 @@ public class TestBatchUpdates extends TestBase {
public void testExecuteBatch04() throws Exception { public void testExecuteBatch04() throws Exception {
trace("testExecuteBatch04"); trace("testExecuteBatch04");
int i = 0; int i = 0;
int[] retValue = { 0, 0, 0}; int[] retValue = { 0, 0, 0 };
int updCountLength = 0; int updCountLength = 0;
String sUpdCoffee = COFFEE_UPDATE1; String sUpdCoffee = COFFEE_UPDATE1;
String sInsCoffee = COFFEE_INSERT1; String sInsCoffee = COFFEE_INSERT1;
...@@ -340,7 +344,7 @@ public class TestBatchUpdates extends TestBase { ...@@ -340,7 +344,7 @@ public class TestBatchUpdates extends TestBase {
public void testExecuteBatch06() throws Exception { public void testExecuteBatch06() throws Exception {
trace("testExecuteBatch06"); trace("testExecuteBatch06");
boolean batchExceptionFlag = false; boolean batchExceptionFlag = false;
//Insert a row which is already Present // Insert a row which is already Present
String sInsCoffee = COFFEE_INSERT1; String sInsCoffee = COFFEE_INSERT1;
String sDelCoffee = COFFEE_DELETE1; String sDelCoffee = COFFEE_DELETE1;
stat.addBatch(sInsCoffee); stat.addBatch(sInsCoffee);
...@@ -384,7 +388,7 @@ public class TestBatchUpdates extends TestBase { ...@@ -384,7 +388,7 @@ public class TestBatchUpdates extends TestBase {
public void testContinueBatch01() throws Exception { public void testContinueBatch01() throws Exception {
trace("testContinueBatch01"); trace("testContinueBatch01");
int[] batchUpdates = { 0, 0, 0}; int[] batchUpdates = { 0, 0, 0 };
int buCountLen = 0; int buCountLen = 0;
try { try {
String sPrepStmt = COFFEE_UPDATE_SET; String sPrepStmt = COFFEE_UPDATE_SET;
......
...@@ -15,66 +15,50 @@ import org.h2.util.MemoryUtils; ...@@ -15,66 +15,50 @@ import org.h2.util.MemoryUtils;
public class TestBigDb extends TestBase { public class TestBigDb extends TestBase {
public void test() throws Exception { public void test() throws Exception {
if(config.memory) { if (config.memory) {
return; return;
} }
if(config.networked && config.big) { if (config.networked && config.big) {
return; return;
} }
testLargeTable(); testLargeTable();
testInsert(); testInsert();
testLeftSummary(); testLeftSummary();
} }
private void testLargeTable() throws Exception { private void testLargeTable() throws Exception {
deleteDb("bigDb"); deleteDb("bigDb");
Connection conn = getConnection("bigDb"); Connection conn = getConnection("bigDb");
Statement stat = conn.createStatement(); Statement stat = conn.createStatement();
stat.execute( stat.execute("CREATE CACHED TABLE TEST(" + "M_CODE CHAR(1) DEFAULT CAST(RAND()*9 AS INT),"
"CREATE CACHED TABLE TEST("+ + "PRD_CODE CHAR(20) DEFAULT SECURE_RAND(10)," + "ORG_CODE_SUPPLIER CHAR(13) DEFAULT SECURE_RAND(6),"
"M_CODE CHAR(1) DEFAULT CAST(RAND()*9 AS INT),"+ + "PRD_CODE_1 CHAR(14) DEFAULT SECURE_RAND(7)," + "PRD_CODE_2 CHAR(20) DEFAULT SECURE_RAND(10),"
"PRD_CODE CHAR(20) DEFAULT SECURE_RAND(10),"+ + "ORG_CODE CHAR(13) DEFAULT SECURE_RAND(6)," + "SUBSTITUTED_BY CHAR(20) DEFAULT SECURE_RAND(10),"
"ORG_CODE_SUPPLIER CHAR(13) DEFAULT SECURE_RAND(6),"+ + "SUBSTITUTED_BY_2 CHAR(14) DEFAULT SECURE_RAND(7),"
"PRD_CODE_1 CHAR(14) DEFAULT SECURE_RAND(7),"+ + "SUBSTITUTION_FOR CHAR(20) DEFAULT SECURE_RAND(10),"
"PRD_CODE_2 CHAR(20) DEFAULT SECURE_RAND(10),"+ + "SUBSTITUTION_FOR_2 CHAR(14) DEFAULT SECURE_RAND(7)," + "TEST CHAR(2) DEFAULT SECURE_RAND(1),"
"ORG_CODE CHAR(13) DEFAULT SECURE_RAND(6),"+ + "TEST_2 CHAR(2) DEFAULT SECURE_RAND(1)," + "TEST_3 DECIMAL(7,2) DEFAULT RAND(),"
"SUBSTITUTED_BY CHAR(20) DEFAULT SECURE_RAND(10),"+ + "PRIMARY_UNIT_CODE CHAR(3) DEFAULT SECURE_RAND(1),"
"SUBSTITUTED_BY_2 CHAR(14) DEFAULT SECURE_RAND(7),"+ + "RATE_PRICE_ORDER_UNIT DECIMAL(9,3) DEFAULT RAND(),"
"SUBSTITUTION_FOR CHAR(20) DEFAULT SECURE_RAND(10),"+ + "ORDER_UNIT_CODE CHAR(3) DEFAULT SECURE_RAND(1)," + "ORDER_QTY_MIN DECIMAL(6,1) DEFAULT RAND(),"
"SUBSTITUTION_FOR_2 CHAR(14) DEFAULT SECURE_RAND(7),"+ + "ORDER_QTY_LOT_SIZE DECIMAL(6,1) DEFAULT RAND(),"
"TEST CHAR(2) DEFAULT SECURE_RAND(1),"+ + "ORDER_UNIT_CODE_2 CHAR(3) DEFAULT SECURE_RAND(1)," + "PRICE_GROUP CHAR(20) DEFAULT SECURE_RAND(10),"
"TEST_2 CHAR(2) DEFAULT SECURE_RAND(1),"+ + "LEAD_TIME INTEGER DEFAULT RAND()," + "LEAD_TIME_UNIT_CODE CHAR(3) DEFAULT SECURE_RAND(1),"
"TEST_3 DECIMAL(7,2) DEFAULT RAND(),"+ + "PRD_GROUP CHAR(10) DEFAULT SECURE_RAND(5)," + "WEIGHT_GROSS DECIMAL(7,3) DEFAULT RAND(),"
"PRIMARY_UNIT_CODE CHAR(3) DEFAULT SECURE_RAND(1),"+ + "WEIGHT_UNIT_CODE CHAR(3) DEFAULT SECURE_RAND(1)," + "PACK_UNIT_CODE CHAR(3) DEFAULT SECURE_RAND(1),"
"RATE_PRICE_ORDER_UNIT DECIMAL(9,3) DEFAULT RAND(),"+ + "PACK_LENGTH DECIMAL(7,3) DEFAULT RAND()," + "PACK_WIDTH DECIMAL(7,3) DEFAULT RAND(),"
"ORDER_UNIT_CODE CHAR(3) DEFAULT SECURE_RAND(1),"+ + "PACK_HEIGHT DECIMAL(7,3) DEFAULT RAND()," + "SIZE_UNIT_CODE CHAR(3) DEFAULT SECURE_RAND(1),"
"ORDER_QTY_MIN DECIMAL(6,1) DEFAULT RAND(),"+ + "STATUS_CODE CHAR(3) DEFAULT SECURE_RAND(1)," + "INTRA_STAT_CODE CHAR(12) DEFAULT SECURE_RAND(6),"
"ORDER_QTY_LOT_SIZE DECIMAL(6,1) DEFAULT RAND(),"+ + "PRD_TITLE CHAR(50) DEFAULT SECURE_RAND(25)," + "VALID_FROM DATE DEFAULT NOW(),"
"ORDER_UNIT_CODE_2 CHAR(3) DEFAULT SECURE_RAND(1),"+ + "MOD_DATUM DATE DEFAULT NOW())");
"PRICE_GROUP CHAR(20) DEFAULT SECURE_RAND(10),"+
"LEAD_TIME INTEGER DEFAULT RAND(),"+
"LEAD_TIME_UNIT_CODE CHAR(3) DEFAULT SECURE_RAND(1),"+
"PRD_GROUP CHAR(10) DEFAULT SECURE_RAND(5),"+
"WEIGHT_GROSS DECIMAL(7,3) DEFAULT RAND(),"+
"WEIGHT_UNIT_CODE CHAR(3) DEFAULT SECURE_RAND(1),"+
"PACK_UNIT_CODE CHAR(3) DEFAULT SECURE_RAND(1),"+
"PACK_LENGTH DECIMAL(7,3) DEFAULT RAND(),"+
"PACK_WIDTH DECIMAL(7,3) DEFAULT RAND(),"+
"PACK_HEIGHT DECIMAL(7,3) DEFAULT RAND(),"+
"SIZE_UNIT_CODE CHAR(3) DEFAULT SECURE_RAND(1),"+
"STATUS_CODE CHAR(3) DEFAULT SECURE_RAND(1),"+
"INTRA_STAT_CODE CHAR(12) DEFAULT SECURE_RAND(6),"+
"PRD_TITLE CHAR(50) DEFAULT SECURE_RAND(25),"+
"VALID_FROM DATE DEFAULT NOW(),"+
"MOD_DATUM DATE DEFAULT NOW())");
int len = getSize(10, 50000); int len = getSize(10, 50000);
try { try {
PreparedStatement prep = conn.prepareStatement("INSERT INTO TEST(PRD_CODE) VALUES('abc' || ?)"); PreparedStatement prep = conn.prepareStatement("INSERT INTO TEST(PRD_CODE) VALUES('abc' || ?)");
long time = System.currentTimeMillis(); long time = System.currentTimeMillis();
for(int i=0; i<len; i++) { for (int i = 0; i < len; i++) {
if((i % 1000) == 0) { if ((i % 1000) == 0) {
long t = System.currentTimeMillis(); long t = System.currentTimeMillis();
if(t-time > 1000) { if (t - time > 1000) {
time = t; time = t;
int free = MemoryUtils.getMemoryFree(); int free = MemoryUtils.getMemoryFree();
System.out.println("i: " + i + " free: " + free + " used: " + MemoryUtils.getMemoryUsed()); System.out.println("i: " + i + " free: " + free + " used: " + MemoryUtils.getMemoryUsed());
...@@ -86,12 +70,12 @@ public class TestBigDb extends TestBase { ...@@ -86,12 +70,12 @@ public class TestBigDb extends TestBase {
stat.execute("CREATE INDEX IDX_TEST_PRD_CODE ON TEST(PRD_CODE)"); stat.execute("CREATE INDEX IDX_TEST_PRD_CODE ON TEST(PRD_CODE)");
ResultSet rs = stat.executeQuery("SELECT * FROM TEST"); ResultSet rs = stat.executeQuery("SELECT * FROM TEST");
int columns = rs.getMetaData().getColumnCount(); int columns = rs.getMetaData().getColumnCount();
while(rs.next()) { while (rs.next()) {
for(int i=0; i<columns; i++) { for (int i = 0; i < columns; i++) {
rs.getString(i+1); rs.getString(i + 1);
} }
} }
} catch(OutOfMemoryError e) { } catch (OutOfMemoryError e) {
TestBase.logError("memory", e); TestBase.logError("memory", e);
conn.close(); conn.close();
throw e; throw e;
...@@ -109,12 +93,12 @@ public class TestBigDb extends TestBase { ...@@ -109,12 +93,12 @@ public class TestBigDb extends TestBase {
int len = getSize(10, 1000); int len = getSize(10, 1000);
int block = getSize(3, 10); int block = getSize(3, 10);
int left, x = 0; int left, x = 0;
for(int i=0; i<len; i++) { for (int i = 0; i < len; i++) {
left = x+block/2; left = x + block / 2;
for(int j=0; j<block; j++) { for (int j = 0; j < block; j++) {
prep.setInt(1, x++); prep.setInt(1, x++);
prep.execute(); prep.execute();
} }
stat.execute("DELETE FROM TEST WHERE ID>" + left); stat.execute("DELETE FROM TEST WHERE ID>" + left);
ResultSet rs = stat.executeQuery("SELECT COUNT(*) FROM TEST"); ResultSet rs = stat.executeQuery("SELECT COUNT(*) FROM TEST");
rs.next(); rs.next();
...@@ -123,7 +107,7 @@ public class TestBigDb extends TestBase { ...@@ -123,7 +107,7 @@ public class TestBigDb extends TestBase {
} }
conn.close(); conn.close();
} }
private void testInsert() throws Exception { private void testInsert() throws Exception {
deleteDb("bigDb"); deleteDb("bigDb");
Connection conn = getConnection("bigDb"); Connection conn = getConnection("bigDb");
...@@ -132,17 +116,16 @@ public class TestBigDb extends TestBase { ...@@ -132,17 +116,16 @@ public class TestBigDb extends TestBase {
PreparedStatement prep = conn.prepareStatement("INSERT INTO TEST(NAME) VALUES('Hello World')"); PreparedStatement prep = conn.prepareStatement("INSERT INTO TEST(NAME) VALUES('Hello World')");
int len = getSize(1000, 10000); int len = getSize(1000, 10000);
long time = System.currentTimeMillis(); long time = System.currentTimeMillis();
for(int i=0; i<len; i++) { for (int i = 0; i < len; i++) {
if(i % 1000 == 0) { if (i % 1000 == 0) {
long t = System.currentTimeMillis(); long t = System.currentTimeMillis();
time = t; time = t;
trace("rows:" + i + " time:" + (t-time)); trace("rows:" + i + " time:" + (t - time));
Thread.yield(); Thread.yield();
} }
prep.execute(); prep.execute();
} }
conn.close(); conn.close();
} }
} }
...@@ -4,7 +4,10 @@ ...@@ -4,7 +4,10 @@
*/ */
package org.h2.test.db; package org.h2.test.db;
import java.sql.*; import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList; import java.util.ArrayList;
import org.h2.store.FileLister; import org.h2.store.FileLister;
...@@ -12,28 +15,28 @@ import org.h2.test.TestBase; ...@@ -12,28 +15,28 @@ import org.h2.test.TestBase;
public class TestBigResult extends TestBase { public class TestBigResult extends TestBase {
public void test() throws Exception { public void test() throws Exception {
if(config.memory) { if (config.memory) {
return; return;
} }
testCloseConnectionDelete(); testCloseConnectionDelete();
testOrderGroup(); testOrderGroup();
testLimitBufferedResult(); testLimitBufferedResult();
} }
private void testCloseConnectionDelete() throws Exception { private void testCloseConnectionDelete() throws Exception {
deleteDb("bigResult"); deleteDb("bigResult");
Connection conn = getConnection("bigResult"); Connection conn = getConnection("bigResult");
Statement stat = conn.createStatement(); Statement stat = conn.createStatement();
stat.execute("SET MAX_MEMORY_ROWS 2"); stat.execute("SET MAX_MEMORY_ROWS 2");
ResultSet rs = stat.executeQuery("SELECT * FROM SYSTEM_RANGE(1, 100)"); ResultSet rs = stat.executeQuery("SELECT * FROM SYSTEM_RANGE(1, 100)");
while(rs.next()) { while (rs.next()) {
// ignore // ignore
} }
// rs.close(); // rs.close();
conn.close(); conn.close();
deleteDb("bigResult"); deleteDb("bigResult");
ArrayList files = FileLister.getDatabaseFiles(baseDir, "bigResult", true); ArrayList files = FileLister.getDatabaseFiles(baseDir, "bigResult", true);
if(files.size() > 0) { if (files.size() > 0) {
error("file not deleted: " + files.get(0)); error("file not deleted: " + files.get(0));
} }
} }
...@@ -44,44 +47,41 @@ public class TestBigResult extends TestBase { ...@@ -44,44 +47,41 @@ public class TestBigResult extends TestBase {
Statement stat = conn.createStatement(); Statement stat = conn.createStatement();
stat.execute("DROP TABLE IF EXISTS TEST"); stat.execute("DROP TABLE IF EXISTS TEST");
stat.execute("CREATE TABLE TEST(ID INT)"); stat.execute("CREATE TABLE TEST(ID INT)");
for(int i=0; i<200; i++) { for (int i = 0; i < 200; i++) {
stat.execute("INSERT INTO TEST(ID) VALUES("+i+")"); stat.execute("INSERT INTO TEST(ID) VALUES(" + i + ")");
} }
stat.execute("SET MAX_MEMORY_ROWS 100"); stat.execute("SET MAX_MEMORY_ROWS 100");
ResultSet rs; ResultSet rs;
rs = stat.executeQuery("select id from test order by id limit 10 offset 85"); rs = stat.executeQuery("select id from test order by id limit 10 offset 85");
for(int i=85; rs.next(); i++) { for (int i = 85; rs.next(); i++) {
check(i, rs.getInt(1)); check(i, rs.getInt(1));
} }
rs = stat.executeQuery("select id from test order by id limit 10 offset 95"); rs = stat.executeQuery("select id from test order by id limit 10 offset 95");
for(int i=95; rs.next(); i++) { for (int i = 95; rs.next(); i++) {
check(i, rs.getInt(1)); check(i, rs.getInt(1));
} }
rs = stat.executeQuery("select id from test order by id limit 10 offset 105"); rs = stat.executeQuery("select id from test order by id limit 10 offset 105");
for(int i=105; rs.next(); i++) { for (int i = 105; rs.next(); i++) {
check(i, rs.getInt(1)); check(i, rs.getInt(1));
} }
conn.close(); conn.close();
} }
private void testOrderGroup() throws Exception { private void testOrderGroup() throws Exception {
deleteDb("bigResult"); deleteDb("bigResult");
Connection conn = getConnection("bigResult"); Connection conn = getConnection("bigResult");
Statement stat = conn.createStatement(); Statement stat = conn.createStatement();
stat.execute("DROP TABLE IF EXISTS TEST"); stat.execute("DROP TABLE IF EXISTS TEST");
stat.execute("CREATE TABLE TEST(" + "ID INT PRIMARY KEY, " stat.execute("CREATE TABLE TEST(" + "ID INT PRIMARY KEY, " + "Name VARCHAR(255), " + "FirstName VARCHAR(255), "
+ "Name VARCHAR(255), " + "Points INT," + "LicenseID INT)");
+ "FirstName VARCHAR(255), "
+ "Points INT,"
+ "LicenseID INT)");
int len = getSize(10, 5000); int len = getSize(10, 5000);
PreparedStatement prep = conn.prepareStatement("INSERT INTO TEST VALUES(?, ?, ?, ?, ?)"); PreparedStatement prep = conn.prepareStatement("INSERT INTO TEST VALUES(?, ?, ?, ?, ?)");
for(int i=0; i<len; i++) { for (int i = 0; i < len; i++) {
prep.setInt(1, i); prep.setInt(1, i);
prep.setString(2, "Name " + i); prep.setString(2, "Name " + i);
prep.setString(3, "First Name " + i); prep.setString(3, "First Name " + i);
prep.setInt(4, i*10); prep.setInt(4, i * 10);
prep.setInt(5, i*i); prep.setInt(5, i * i);
prep.execute(); prep.execute();
} }
conn.close(); conn.close();
...@@ -89,29 +89,29 @@ public class TestBigResult extends TestBase { ...@@ -89,29 +89,29 @@ public class TestBigResult extends TestBase {
stat = conn.createStatement(); stat = conn.createStatement();
stat.setMaxRows(len + 1); stat.setMaxRows(len + 1);
ResultSet rs = stat.executeQuery("SELECT * FROM TEST ORDER BY ID"); ResultSet rs = stat.executeQuery("SELECT * FROM TEST ORDER BY ID");
for(int i=0; i<len; i++) { for (int i = 0; i < len; i++) {
rs.next(); rs.next();
check(i, rs.getInt(1)); check(i, rs.getInt(1));
check("Name " + i, rs.getString(2)); check("Name " + i, rs.getString(2));
check("First Name " + i, rs.getString(3)); check("First Name " + i, rs.getString(3));
check(i*10, rs.getInt(4)); check(i * 10, rs.getInt(4));
check(i*i, rs.getInt(5)); check(i * i, rs.getInt(5));
} }
stat.setMaxRows(len + 1); stat.setMaxRows(len + 1);
rs = stat.executeQuery("SELECT * FROM TEST WHERE ID >= 1000 ORDER BY ID"); rs = stat.executeQuery("SELECT * FROM TEST WHERE ID >= 1000 ORDER BY ID");
for(int i=1000; i<len; i++) { for (int i = 1000; i < len; i++) {
rs.next(); rs.next();
check(i, rs.getInt(1)); check(i, rs.getInt(1));
check("Name " + i, rs.getString(2)); check("Name " + i, rs.getString(2));
check("First Name " + i, rs.getString(3)); check("First Name " + i, rs.getString(3));
check(i*10, rs.getInt(4)); check(i * 10, rs.getInt(4));
check(i*i, rs.getInt(5)); check(i * i, rs.getInt(5));
} }
stat.execute("SET MAX_MEMORY_ROWS 2"); stat.execute("SET MAX_MEMORY_ROWS 2");
rs = stat.executeQuery("SELECT Name, SUM(ID) FROM TEST GROUP BY NAME"); rs = stat.executeQuery("SELECT Name, SUM(ID) FROM TEST GROUP BY NAME");
while(rs.next()) { while (rs.next()) {
rs.getString(1); rs.getString(1);
rs.getInt(2); rs.getInt(2);
} }
...@@ -121,24 +121,22 @@ public class TestBigResult extends TestBase { ...@@ -121,24 +121,22 @@ public class TestBigResult extends TestBase {
stat.execute("SET MAX_MEMORY_ROWS 0"); stat.execute("SET MAX_MEMORY_ROWS 0");
stat.execute("CREATE TABLE DATA(ID INT, NAME VARCHAR_IGNORECASE(255))"); stat.execute("CREATE TABLE DATA(ID INT, NAME VARCHAR_IGNORECASE(255))");
prep = conn.prepareStatement("INSERT INTO DATA VALUES(?, ?)"); prep = conn.prepareStatement("INSERT INTO DATA VALUES(?, ?)");
for(int i=0; i<len; i++) { for (int i = 0; i < len; i++) {
prep.setInt(1, i); prep.setInt(1, i);
prep.setString(2, ""+i/200); prep.setString(2, "" + i / 200);
prep.execute(); prep.execute();
} }
Statement s2 = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); Statement s2 = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
rs = s2.executeQuery("SELECT NAME FROM DATA"); rs = s2.executeQuery("SELECT NAME FROM DATA");
rs.last(); rs.last();
conn.setAutoCommit(true); conn.setAutoCommit(true);
rs = s2.executeQuery("SELECT NAME FROM DATA ORDER BY ID"); rs = s2.executeQuery("SELECT NAME FROM DATA ORDER BY ID");
while(rs.next()) { while (rs.next()) {
// do nothing // do nothing
} }
conn.close(); conn.close();
} }
} }
...@@ -4,7 +4,8 @@ ...@@ -4,7 +4,8 @@
*/ */
package org.h2.test.db; package org.h2.test.db;
import java.sql.*; import java.sql.Connection;
import java.sql.Statement;
import org.h2.test.TestBase; import org.h2.test.TestBase;
...@@ -20,15 +21,15 @@ public class TestCheckpoint extends TestBase { ...@@ -20,15 +21,15 @@ public class TestCheckpoint extends TestBase {
s1.execute("CREATE TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR(255))"); s1.execute("CREATE TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR(255))");
s1.execute("INSERT INTO TEST VALUES(1, 'Hello')"); s1.execute("INSERT INTO TEST VALUES(1, 'Hello')");
s0.execute("CHECKPOINT"); s0.execute("CHECKPOINT");
s1.execute("INSERT INTO TEST VALUES(2, 'World')"); s1.execute("INSERT INTO TEST VALUES(2, 'World')");
c1.setAutoCommit(false); c1.setAutoCommit(false);
s1.execute("INSERT INTO TEST VALUES(3, 'Maybe')"); s1.execute("INSERT INTO TEST VALUES(3, 'Maybe')");
s0.execute("CHECKPOINT"); s0.execute("CHECKPOINT");
s1.execute("INSERT INTO TEST VALUES(4, 'Or not')"); s1.execute("INSERT INTO TEST VALUES(4, 'Or not')");
s0.execute("CHECKPOINT"); s0.execute("CHECKPOINT");
s1.execute("INSERT INTO TEST VALUES(5, 'ok yes')"); s1.execute("INSERT INTO TEST VALUES(5, 'ok yes')");
s1.execute("COMMIT"); s1.execute("COMMIT");
s0.execute("CHECKPOINT"); s0.execute("CHECKPOINT");
......
...@@ -19,13 +19,13 @@ import org.h2.tools.Server; ...@@ -19,13 +19,13 @@ import org.h2.tools.Server;
public class TestCluster extends TestBase { public class TestCluster extends TestBase {
public void test() throws Exception { public void test() throws Exception {
if(config.memory || config.networked) { if (config.memory || config.networked) {
return; return;
} }
DeleteDbFiles.main(new String[]{"-dir", baseDir + "/node1", "-quiet"}); DeleteDbFiles.main(new String[] { "-dir", baseDir + "/node1", "-quiet" });
DeleteDbFiles.main(new String[]{"-dir", baseDir + "/node2", "-quiet"}); DeleteDbFiles.main(new String[] { "-dir", baseDir + "/node2", "-quiet" });
// create the master database // create the master database
Connection conn; Connection conn;
Class.forName("org.h2.Driver"); Class.forName("org.h2.Driver");
...@@ -36,37 +36,36 @@ public class TestCluster extends TestBase { ...@@ -36,37 +36,36 @@ public class TestCluster extends TestBase {
stat.execute("CREATE TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR(255))"); stat.execute("CREATE TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR(255))");
PreparedStatement prep = conn.prepareStatement("INSERT INTO TEST VALUES(?, ?)"); PreparedStatement prep = conn.prepareStatement("INSERT INTO TEST VALUES(?, ?)");
int len = getSize(10, 1000); int len = getSize(10, 1000);
for(int i=0; i<len; i++) { for (int i = 0; i < len; i++) {
prep.setInt(1, i); prep.setInt(1, i);
prep.setString(2, "Data" + i); prep.setString(2, "Data" + i);
prep.executeUpdate(); prep.executeUpdate();
} }
conn.close(); conn.close();
CreateCluster.main(new String[]{ CreateCluster.main(new String[] { "-urlSource", "jdbc:h2:file:" + baseDir + "/node1/test", "-urlTarget",
"-urlSource", "jdbc:h2:file:"+ baseDir + "/node1/test", "jdbc:h2:file:" + baseDir + "/node2/test", "-user", "sa", "-serverlist",
"-urlTarget", "jdbc:h2:file:"+baseDir + "/node2/test", "localhost:9091,localhost:9092" });
"-user", "sa",
"-serverlist", "localhost:9091,localhost:9092" Server n1 = org.h2.tools.Server.createTcpServer(
}); new String[] { "-tcpPort", "9091", "-baseDir", baseDir + "/node1" }).start();
Server n2 = org.h2.tools.Server.createTcpServer(
Server n1 = org.h2.tools.Server.createTcpServer(new String[]{"-tcpPort", "9091", "-baseDir", baseDir + "/node1"}).start(); new String[] { "-tcpPort", "9092", "-baseDir", baseDir + "/node2" }).start();
Server n2 = org.h2.tools.Server.createTcpServer(new String[]{"-tcpPort", "9092", "-baseDir", baseDir + "/node2"}).start();
try { try {
conn = DriverManager.getConnection("jdbc:h2:tcp://localhost:9091/test", "sa", ""); conn = DriverManager.getConnection("jdbc:h2:tcp://localhost:9091/test", "sa", "");
error("should not be able to connect in standalone mode"); error("should not be able to connect in standalone mode");
} catch(SQLException e) { } catch (SQLException e) {
checkNotGeneralException(e); checkNotGeneralException(e);
} }
try { try {
conn = DriverManager.getConnection("jdbc:h2:tcp://localhost:9092/test", "sa", ""); conn = DriverManager.getConnection("jdbc:h2:tcp://localhost:9092/test", "sa", "");
error("should not be able to connect in standalone mode"); error("should not be able to connect in standalone mode");
} catch(SQLException e) { } catch (SQLException e) {
checkNotGeneralException(e); checkNotGeneralException(e);
} }
conn = DriverManager.getConnection("jdbc:h2:tcp://localhost:9091,localhost:9092/test", "sa", ""); conn = DriverManager.getConnection("jdbc:h2:tcp://localhost:9091,localhost:9092/test", "sa", "");
stat = conn.createStatement(); stat = conn.createStatement();
check(conn, len); check(conn, len);
...@@ -79,27 +78,29 @@ public class TestCluster extends TestBase { ...@@ -79,27 +78,29 @@ public class TestCluster extends TestBase {
conn.close(); conn.close();
n2.stop(); n2.stop();
n1 = org.h2.tools.Server.createTcpServer(new String[]{"-tcpPort", "9091", "-baseDir", baseDir + "/node1"}).start(); n1 = org.h2.tools.Server.createTcpServer(new String[] { "-tcpPort", "9091", "-baseDir", baseDir + "/node1" })
.start();
conn = DriverManager.getConnection("jdbc:h2:tcp://localhost:9091/test;CLUSTER=''", "sa", ""); conn = DriverManager.getConnection("jdbc:h2:tcp://localhost:9091/test;CLUSTER=''", "sa", "");
check(conn, len); check(conn, len);
conn.close(); conn.close();
n1.stop(); n1.stop();
n2 = org.h2.tools.Server.createTcpServer(new String[]{"-tcpPort", "9092", "-baseDir", baseDir + "/node2"}).start(); n2 = org.h2.tools.Server.createTcpServer(new String[] { "-tcpPort", "9092", "-baseDir", baseDir + "/node2" })
.start();
conn = DriverManager.getConnection("jdbc:h2:tcp://localhost:9092/test;CLUSTER=''", "sa", ""); conn = DriverManager.getConnection("jdbc:h2:tcp://localhost:9092/test;CLUSTER=''", "sa", "");
check(conn, len); check(conn, len);
conn.createStatement().execute("SELECT * FROM A"); conn.createStatement().execute("SELECT * FROM A");
conn.close(); conn.close();
n2.stop(); n2.stop();
} }
void check(Connection conn, int len) throws Exception { void check(Connection conn, int len) throws Exception {
PreparedStatement prep = conn.prepareStatement("SELECT * FROM TEST WHERE ID=?"); PreparedStatement prep = conn.prepareStatement("SELECT * FROM TEST WHERE ID=?");
for(int i=0; i<len; i++) { for (int i = 0; i < len; i++) {
prep.setInt(1, i); prep.setInt(1, i);
ResultSet rs = prep.executeQuery(); ResultSet rs = prep.executeQuery();
rs.next(); rs.next();
check(rs.getString(2), "Data"+i); check(rs.getString(2), "Data" + i);
checkFalse(rs.next()); checkFalse(rs.next());
} }
} }
......
...@@ -22,46 +22,47 @@ public class TestCsv extends TestBase { ...@@ -22,46 +22,47 @@ public class TestCsv extends TestBase {
testRead(); testRead();
testPipe(); testPipe();
} }
private void testPipe() throws Exception { private void testPipe() throws Exception {
deleteDb("csv"); deleteDb("csv");
Connection conn = getConnection("csv"); Connection conn = getConnection("csv");
Statement stat = conn.createStatement(); Statement stat = conn.createStatement();
stat.execute("call csvwrite('"+baseDir+"/test.csv', 'select 1 id, ''Hello'' name', 'utf-8', '|')"); stat.execute("call csvwrite('" + baseDir + "/test.csv', 'select 1 id, ''Hello'' name', 'utf-8', '|')");
ResultSet rs = stat.executeQuery("select * from csvread('"+baseDir+"/test.csv', null, 'utf-8', '|')"); ResultSet rs = stat.executeQuery("select * from csvread('" + baseDir + "/test.csv', null, 'utf-8', '|')");
check(rs.next()); check(rs.next());
check(rs.getInt(1), 1); check(rs.getInt(1), 1);
check(rs.getString(2), "Hello"); check(rs.getString(2), "Hello");
checkFalse(rs.next()); checkFalse(rs.next());
new File(baseDir+"/test.csv").delete(); new File(baseDir + "/test.csv").delete();
// PreparedStatement prep = conn.prepareStatement("select * from csvread(?, null, ?, ?)"); // PreparedStatement prep = conn.prepareStatement("select * from
// prep.setString(1, BASE_DIR+"/test.csv"); // csvread(?, null, ?, ?)");
// prep.setString(2, "utf-8"); // prep.setString(1, BASE_DIR+"/test.csv");
// prep.setString(3, "|"); // prep.setString(2, "utf-8");
// rs = prep.executeQuery(); // prep.setString(3, "|");
// rs = prep.executeQuery();
conn.close(); conn.close();
} }
private void testAsTable() throws Exception { private void testAsTable() throws Exception {
deleteDb("csv"); deleteDb("csv");
Connection conn = getConnection("csv"); Connection conn = getConnection("csv");
Statement stat = conn.createStatement(); Statement stat = conn.createStatement();
stat.execute("call csvwrite('"+baseDir+"/test.csv', 'select 1 id, ''Hello'' name')"); stat.execute("call csvwrite('" + baseDir + "/test.csv', 'select 1 id, ''Hello'' name')");
ResultSet rs = stat.executeQuery("select name from csvread('"+baseDir+"/test.csv')"); ResultSet rs = stat.executeQuery("select name from csvread('" + baseDir + "/test.csv')");
check(rs.next()); check(rs.next());
check(rs.getString(1), "Hello"); check(rs.getString(1), "Hello");
checkFalse(rs.next()); checkFalse(rs.next());
rs = stat.executeQuery("call csvread('"+baseDir+"/test.csv')"); rs = stat.executeQuery("call csvread('" + baseDir + "/test.csv')");
check(rs.next()); check(rs.next());
check(rs.getInt(1), 1); check(rs.getInt(1), 1);
check(rs.getString(2), "Hello"); check(rs.getString(2), "Hello");
checkFalse(rs.next()); checkFalse(rs.next());
new File(baseDir+"/test.csv").delete(); new File(baseDir + "/test.csv").delete();
conn.close(); conn.close();
} }
public void testRead() throws Exception { public void testRead() throws Exception {
File f = new File(baseDir + "/test.csv"); File f = new File(baseDir + "/test.csv");
f.delete(); f.delete();
...@@ -96,25 +97,25 @@ public class TestCsv extends TestBase { ...@@ -96,25 +97,25 @@ public class TestCsv extends TestBase {
check(rs.getString(3), "7"); check(rs.getString(3), "7");
check(rs.getString(4), "8"); check(rs.getString(4), "8");
checkFalse(rs.next()); checkFalse(rs.next());
// a,b,c,d // 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
// 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 { public void testWriteRead() throws Exception {
deleteDb("csv"); deleteDb("csv");
Connection conn = getConnection("csv"); Connection conn = getConnection("csv");
Statement stat = conn.createStatement(); Statement stat = conn.createStatement();
stat.execute("CREATE TABLE TEST(ID IDENTITY, NAME VARCHAR)"); stat.execute("CREATE TABLE TEST(ID IDENTITY, NAME VARCHAR)");
int len = 100; int len = 100;
for(int i=0; i<len; i++) { for (int i = 0; i < len; i++) {
stat.execute("INSERT INTO TEST(NAME) VALUES('Ruebezahl')"); stat.execute("INSERT INTO TEST(NAME) VALUES('Ruebezahl')");
} }
Csv.getInstance().write(conn, baseDir + "/testRW.csv", "SELECT * FROM TEST", "UTF8"); Csv.getInstance().write(conn, baseDir + "/testRW.csv", "SELECT * FROM TEST", "UTF8");
...@@ -122,15 +123,15 @@ public class TestCsv extends TestBase { ...@@ -122,15 +123,15 @@ public class TestCsv extends TestBase {
// stat.execute("CREATE ALIAS CSVREAD FOR \"org.h2.tools.Csv.read\""); // stat.execute("CREATE ALIAS CSVREAD FOR \"org.h2.tools.Csv.read\"");
ResultSetMetaData meta = rs.getMetaData(); ResultSetMetaData meta = rs.getMetaData();
check(2, meta.getColumnCount()); check(2, meta.getColumnCount());
for(int i=0; i<len; i++) { for (int i = 0; i < len; i++) {
rs.next(); rs.next();
check(rs.getString("ID"), "" + (i+1)); check(rs.getString("ID"), "" + (i + 1));
check(rs.getString("NAME"), "Ruebezahl"); check(rs.getString("NAME"), "Ruebezahl");
} }
checkFalse(rs.next()); checkFalse(rs.next());
rs.close(); rs.close();
conn.close(); conn.close();
} }
} }
...@@ -53,7 +53,7 @@ public class TestFunctions extends TestBase { ...@@ -53,7 +53,7 @@ public class TestFunctions extends TestBase {
check(rs.getInt(1), 2); check(rs.getInt(1), 2);
check(rs.getString(2), "World"); check(rs.getString(2), "World");
checkFalse(rs.next()); checkFalse(rs.next());
rs = stat.executeQuery("SELECT NAME FROM SELECT_F('SELECT * FROM TEST ORDER BY NAME') ORDER BY NAME DESC"); rs = stat.executeQuery("SELECT NAME FROM SELECT_F('SELECT * FROM TEST ORDER BY NAME') ORDER BY NAME DESC");
check(rs.getMetaData().getColumnCount(), 1); check(rs.getMetaData().getColumnCount(), 1);
rs.next(); rs.next();
...@@ -137,14 +137,14 @@ public class TestFunctions extends TestBase { ...@@ -137,14 +137,14 @@ public class TestFunctions extends TestBase {
stat.execute("INSERT INTO TEST_BLOB VALUES(0, null)"); stat.execute("INSERT INTO TEST_BLOB VALUES(0, null)");
stat.execute("INSERT INTO TEST_BLOB VALUES(1, 'edd1f011edd1f011edd1f011')"); stat.execute("INSERT INTO TEST_BLOB VALUES(1, 'edd1f011edd1f011edd1f011')");
rs = stat.executeQuery("SELECT blob2stream(VALUE) FROM TEST_BLOB"); rs = stat.executeQuery("SELECT blob2stream(VALUE) FROM TEST_BLOB");
while(rs.next()) { while (rs.next()) {
} }
rs.close(); rs.close();
rs = stat.executeQuery("SELECT stream2stream(VALUE) FROM TEST_BLOB"); rs = stat.executeQuery("SELECT stream2stream(VALUE) FROM TEST_BLOB");
while(rs.next()) { while (rs.next()) {
// ignore // ignore
} }
stat.execute("CREATE ALIAS NULL_RESULT FOR \"" + getClass().getName() + ".nullResultSet\""); stat.execute("CREATE ALIAS NULL_RESULT FOR \"" + getClass().getName() + ".nullResultSet\"");
rs = stat.executeQuery("CALL NULL_RESULT()"); rs = stat.executeQuery("CALL NULL_RESULT()");
check(rs.getMetaData().getColumnCount(), 1); check(rs.getMetaData().getColumnCount(), 1);
...@@ -163,7 +163,7 @@ public class TestFunctions extends TestBase { ...@@ -163,7 +163,7 @@ public class TestFunctions extends TestBase {
} }
public static BufferedInputStream blob2stream(Blob value) throws SQLException { public static BufferedInputStream blob2stream(Blob value) throws SQLException {
if(value == null) { if (value == null) {
return null; return null;
} }
BufferedInputStream bufferedInStream = new BufferedInputStream(value.getBinaryStream()); BufferedInputStream bufferedInStream = new BufferedInputStream(value.getBinaryStream());
...@@ -171,7 +171,7 @@ public class TestFunctions extends TestBase { ...@@ -171,7 +171,7 @@ public class TestFunctions extends TestBase {
} }
public static BufferedInputStream stream2stream(InputStream value) throws SQLException { public static BufferedInputStream stream2stream(InputStream value) throws SQLException {
if(value == null) { if (value == null) {
return null; return null;
} }
BufferedInputStream bufferedInStream = new BufferedInputStream(value); BufferedInputStream bufferedInStream = new BufferedInputStream(value);
...@@ -199,13 +199,14 @@ public class TestFunctions extends TestBase { ...@@ -199,13 +199,14 @@ public class TestFunctions extends TestBase {
public static Object[] getArray() { public static Object[] getArray() {
return new Object[] { new Integer(0), "Hello" }; return new Object[] { new Integer(0), "Hello" };
} }
public static ResultSet nullResultSet(Connection conn) throws SQLException { public static ResultSet nullResultSet(Connection conn) throws SQLException {
PreparedStatement statement = conn.prepareStatement("select null from system_range(1,1)"); PreparedStatement statement = conn.prepareStatement("select null from system_range(1,1)");
return statement.executeQuery(); return statement.executeQuery();
} }
public static ResultSet simpleResultSet(Integer count, int ip, boolean bp, float fp, double dp, long lp, byte byParam, short sp) throws SQLException { public static ResultSet simpleResultSet(Integer count, int ip, boolean bp, float fp, double dp, long lp,
byte byParam, short sp) throws SQLException {
SimpleResultSet rs = new SimpleResultSet(); SimpleResultSet rs = new SimpleResultSet();
rs.addColumn("ID", Types.INTEGER, 10, 0); rs.addColumn("ID", Types.INTEGER, 10, 0);
rs.addColumn("NAME", Types.VARCHAR, 255, 0); rs.addColumn("NAME", Types.VARCHAR, 255, 0);
......
...@@ -13,15 +13,15 @@ import org.h2.api.DatabaseEventListener; ...@@ -13,15 +13,15 @@ import org.h2.api.DatabaseEventListener;
import org.h2.test.TestBase; import org.h2.test.TestBase;
public class TestListener extends TestBase implements DatabaseEventListener { public class TestListener extends TestBase implements DatabaseEventListener {
private long last, start; private long last, start;
public TestListener() { public TestListener() {
start = last = System.currentTimeMillis(); start = last = System.currentTimeMillis();
} }
public void test() throws Exception { public void test() throws Exception {
if(config.networked) { if (config.networked) {
return; return;
} }
deleteDb("listener"); deleteDb("listener");
...@@ -31,19 +31,19 @@ public class TestListener extends TestBase implements DatabaseEventListener { ...@@ -31,19 +31,19 @@ public class TestListener extends TestBase implements DatabaseEventListener {
stat.execute("CREATE TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR)"); stat.execute("CREATE TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR)");
PreparedStatement prep = conn.prepareStatement("INSERT INTO TEST VALUES(?, 'Test' || SPACE(100))"); PreparedStatement prep = conn.prepareStatement("INSERT INTO TEST VALUES(?, 'Test' || SPACE(100))");
int len = getSize(100, 100000); int len = getSize(100, 100000);
for(int i=0; i<len; i++) { for (int i = 0; i < len; i++) {
prep.setInt(1, i); prep.setInt(1, i);
prep.execute(); prep.execute();
} }
crash(conn); crash(conn);
conn = getConnection("listener;database_event_listener='" + getClass().getName() + "'"); conn = getConnection("listener;database_event_listener='" + getClass().getName() + "'");
conn.close(); conn.close();
} }
public void diskSpaceIsLow(long stillAvailable) throws SQLException { public void diskSpaceIsLow(long stillAvailable) throws SQLException {
System.out.println("diskSpaceIsLow stillAvailable="+stillAvailable); System.out.println("diskSpaceIsLow stillAvailable=" + stillAvailable);
} }
public void exceptionThrown(SQLException e, String sql) { public void exceptionThrown(SQLException e, String sql) {
...@@ -52,12 +52,12 @@ public class TestListener extends TestBase implements DatabaseEventListener { ...@@ -52,12 +52,12 @@ public class TestListener extends TestBase implements DatabaseEventListener {
public void setProgress(int state, String name, int current, int max) { public void setProgress(int state, String name, int current, int max) {
long time = System.currentTimeMillis(); long time = System.currentTimeMillis();
if(time < last+1000) { if (time < last + 1000) {
return; return;
} }
last = time; last = time;
String stateName; String stateName;
switch(state) { switch (state) {
case STATE_SCAN_FILE: case STATE_SCAN_FILE:
stateName = "Scan " + name; stateName = "Scan " + name;
break; break;
...@@ -75,7 +75,7 @@ public class TestListener extends TestBase implements DatabaseEventListener { ...@@ -75,7 +75,7 @@ public class TestListener extends TestBase implements DatabaseEventListener {
Thread.sleep(1); Thread.sleep(1);
} catch (InterruptedException e) { } catch (InterruptedException e) {
} }
System.out.println("state: " + stateName + " " + (100*current/max) + " " + (time-start)); System.out.println("state: " + stateName + " " + (100 * current / max) + " " + (time - start));
} }
public void closingDatabase() { public void closingDatabase() {
......
...@@ -17,15 +17,15 @@ public class TestLogFile extends TestBase { ...@@ -17,15 +17,15 @@ public class TestLogFile extends TestBase {
private Connection conn; private Connection conn;
private static final int MAX_LOG_SIZE = 1; private static final int MAX_LOG_SIZE = 1;
private long reconnect(int maxFiles) throws Exception { private long reconnect(int maxFiles) throws Exception {
if(conn != null) { if (conn != null) {
conn.close(); conn.close();
} }
long length = 0; long length = 0;
ArrayList files = FileLister.getDatabaseFiles(baseDir, "logfile", false); ArrayList files = FileLister.getDatabaseFiles(baseDir, "logfile", false);
checkSmaller(files.size(), maxFiles+2); checkSmaller(files.size(), maxFiles + 2);
for(int i=0; i<files.size(); i++) { for (int i = 0; i < files.size(); i++) {
String fileName = (String) files.get(i); String fileName = (String) files.get(i);
long len = new File(fileName).length(); long len = new File(fileName).length();
length += len; length += len;
...@@ -33,36 +33,36 @@ public class TestLogFile extends TestBase { ...@@ -33,36 +33,36 @@ public class TestLogFile extends TestBase {
conn = getConnection("logfile"); conn = getConnection("logfile");
return length; return length;
} }
public void test() throws Exception { public void test() throws Exception {
if(config.memory) { if (config.memory) {
return; return;
} }
deleteDb("logfile"); deleteDb("logfile");
reconnect(0); reconnect(0);
insert(); insert();
int maxFiles = 3; // data, index, log int maxFiles = 3; // data, index, log
for(int i=0; i<3; i++) { for (int i = 0; i < 3; i++) {
long length = reconnect(maxFiles); long length = reconnect(maxFiles);
insert(); insert();
long l2 = reconnect(maxFiles); long l2 = reconnect(maxFiles);
trace("l2="+ l2); trace("l2=" + l2);
check(l2 <= length * 2); check(l2 <= length * 2);
} }
conn.close(); conn.close();
} }
private void checkLogSize() throws Exception { private void checkLogSize() throws Exception {
String[] files = new File(".").list(); String[] files = new File(".").list();
for(int j=0; j<files.length; j++) { for (int j = 0; j < files.length; j++) {
String name = files[j]; String name = files[j];
if(name.startsWith("logfile") && name.endsWith(".log.db")) { if (name.startsWith("logfile") && name.endsWith(".log.db")) {
long length = new File(name).length(); long length = new File(name).length();
checkSmaller(length, MAX_LOG_SIZE * 1024 * 1024 * 2); checkSmaller(length, MAX_LOG_SIZE * 1024 * 1024 * 2);
} }
} }
} }
void insert() throws Exception { void insert() throws Exception {
Statement stat = conn.createStatement(); Statement stat = conn.createStatement();
stat.execute("SET LOGSIZE 200"); stat.execute("SET LOGSIZE 200");
...@@ -71,11 +71,11 @@ public class TestLogFile extends TestBase { ...@@ -71,11 +71,11 @@ public class TestLogFile extends TestBase {
stat.execute("CREATE TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR(255))"); stat.execute("CREATE TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR(255))");
PreparedStatement prep = conn.prepareStatement("INSERT INTO TEST VALUES(?, 'Hello' || ?)"); PreparedStatement prep = conn.prepareStatement("INSERT INTO TEST VALUES(?, 'Hello' || ?)");
int len = getSize(1, 10000); int len = getSize(1, 10000);
for(int i=0; i<len; i++) { for (int i = 0; i < len; i++) {
prep.setInt(1, i); prep.setInt(1, i);
prep.setInt(2, i); prep.setInt(2, i);
prep.execute(); prep.execute();
if(i>0 && (i % 2000) == 0) { if (i > 0 && (i % 2000) == 0) {
checkLogSize(); checkLogSize();
} }
} }
......
...@@ -15,16 +15,16 @@ import org.h2.test.TestBase; ...@@ -15,16 +15,16 @@ import org.h2.test.TestBase;
public class TestMemoryUsage extends TestBase { public class TestMemoryUsage extends TestBase {
private Connection conn; private Connection conn;
private void reconnect() throws Exception { private void reconnect() throws Exception {
if(conn != null) { if (conn != null) {
conn.close(); conn.close();
} }
// Class.forName("org.hsqldb.jdbcDriver"); // Class.forName("org.hsqldb.jdbcDriver");
// conn = DriverManager.getConnection("jdbc:hsqldb:test", "sa", ""); // conn = DriverManager.getConnection("jdbc:hsqldb:test", "sa", "");
conn = getConnection("memoryUsage"); conn = getConnection("memoryUsage");
} }
public void test() throws Exception { public void test() throws Exception {
deleteDb("memoryUsage"); deleteDb("memoryUsage");
testReconnectOften(); testReconnectOften();
...@@ -35,102 +35,101 @@ public class TestMemoryUsage extends TestBase { ...@@ -35,102 +35,101 @@ public class TestMemoryUsage extends TestBase {
insertUpdateSelectDelete(); insertUpdateSelectDelete();
conn.close(); conn.close();
} }
private void testReconnectOften() throws Exception { private void testReconnectOften() throws Exception {
int len = getSize(1, 2000); int len = getSize(1, 2000);
Connection conn1 = getConnection("memoryUsage"); Connection conn1 = getConnection("memoryUsage");
printTimeMemory("start", 0); printTimeMemory("start", 0);
long time = System.currentTimeMillis(); long time = System.currentTimeMillis();
for(int i=0; i<len; i++) { for (int i = 0; i < len; i++) {
Connection conn2 = getConnection("memoryUsage"); Connection conn2 = getConnection("memoryUsage");
conn2.close(); conn2.close();
if(i % 10000 == 0) { if (i % 10000 == 0) {
printTimeMemory("connect", System.currentTimeMillis()-time); printTimeMemory("connect", System.currentTimeMillis() - time);
} }
} }
printTimeMemory("connect", System.currentTimeMillis()-time); printTimeMemory("connect", System.currentTimeMillis() - time);
conn1.close(); conn1.close();
} }
void insertUpdateSelectDelete() throws Exception { void insertUpdateSelectDelete() throws Exception {
Statement stat = conn.createStatement(); Statement stat = conn.createStatement();
long time; long time;
int len = getSize(1, 2000); int len = getSize(1, 2000);
// insert // insert
time = System.currentTimeMillis(); time = System.currentTimeMillis();
stat.execute("DROP TABLE IF EXISTS TEST"); stat.execute("DROP TABLE IF EXISTS TEST");
trace("drop=" + (System.currentTimeMillis()-time)); trace("drop=" + (System.currentTimeMillis() - time));
stat.execute("CREATE CACHED TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR(255))"); stat.execute("CREATE CACHED TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR(255))");
PreparedStatement prep = conn.prepareStatement("INSERT INTO TEST VALUES(?, 'Hello World')"); PreparedStatement prep = conn.prepareStatement("INSERT INTO TEST VALUES(?, 'Hello World')");
printTimeMemory("start", 0); printTimeMemory("start", 0);
time = System.currentTimeMillis(); time = System.currentTimeMillis();
for(int i=0; i<len; i++) { for (int i = 0; i < len; i++) {
prep.setInt(1, i); prep.setInt(1, i);
prep.execute(); prep.execute();
if(i % 50000 == 0) { if (i % 50000 == 0) {
trace(" " + (100*i/len) + "%"); trace(" " + (100 * i / len) + "%");
} }
} }
printTimeMemory("insert", System.currentTimeMillis()-time); printTimeMemory("insert", System.currentTimeMillis() - time);
// update // update
time = System.currentTimeMillis(); time = System.currentTimeMillis();
prep = conn.prepareStatement("UPDATE TEST SET NAME='Hallo Welt' WHERE ID = ?"); prep = conn.prepareStatement("UPDATE TEST SET NAME='Hallo Welt' WHERE ID = ?");
for(int i=0; i<len; i++) { for (int i = 0; i < len; i++) {
prep.setInt(1, i); prep.setInt(1, i);
prep.execute(); prep.execute();
if(i % 50000 == 0) { if (i % 50000 == 0) {
trace(" " + (100*i/len) + "%"); trace(" " + (100 * i / len) + "%");
} }
} }
printTimeMemory("update", System.currentTimeMillis()-time); printTimeMemory("update", System.currentTimeMillis() - time);
// select // select
time = System.currentTimeMillis(); time = System.currentTimeMillis();
prep = conn.prepareStatement("SELECT * FROM TEST WHERE ID = ?"); prep = conn.prepareStatement("SELECT * FROM TEST WHERE ID = ?");
for(int i=0; i<len; i++) { for (int i = 0; i < len; i++) {
prep.setInt(1, i); prep.setInt(1, i);
ResultSet rs = prep.executeQuery(); ResultSet rs = prep.executeQuery();
rs.next(); rs.next();
if(rs.next()) { if (rs.next()) {
error("one row expected, got more"); error("one row expected, got more");
} }
if(i % 50000 == 0) { if (i % 50000 == 0) {
trace(" " + (100*i/len) + "%"); trace(" " + (100 * i / len) + "%");
} }
} }
printTimeMemory("select", System.currentTimeMillis()-time); printTimeMemory("select", System.currentTimeMillis() - time);
// select randomized // select randomized
Random random = new Random(1); Random random = new Random(1);
time = System.currentTimeMillis(); time = System.currentTimeMillis();
prep = conn.prepareStatement("SELECT * FROM TEST WHERE ID = ?"); prep = conn.prepareStatement("SELECT * FROM TEST WHERE ID = ?");
for(int i=0; i<len; i++) { for (int i = 0; i < len; i++) {
prep.setInt(1, random.nextInt(len)); prep.setInt(1, random.nextInt(len));
ResultSet rs = prep.executeQuery(); ResultSet rs = prep.executeQuery();
rs.next(); rs.next();
if(rs.next()) { if (rs.next()) {
error("one row expected, got more"); error("one row expected, got more");
} }
if(i % 50000 == 0) { if (i % 50000 == 0) {
trace(" " + (100*i/len) + "%"); trace(" " + (100 * i / len) + "%");
} }
} }
printTimeMemory("select randomized", System.currentTimeMillis()-time); printTimeMemory("select randomized", System.currentTimeMillis() - time);
// delete // delete
time = System.currentTimeMillis(); time = System.currentTimeMillis();
prep = conn.prepareStatement("DELETE FROM TEST WHERE ID = ?"); prep = conn.prepareStatement("DELETE FROM TEST WHERE ID = ?");
for(int i=0; i<len; i++) { for (int i = 0; i < len; i++) {
prep.setInt(1, random.nextInt(len)); prep.setInt(1, random.nextInt(len));
prep.executeUpdate(); prep.executeUpdate();
if(i % 50000 == 0) { if (i % 50000 == 0) {
trace(" " + (100*i/len) + "%"); trace(" " + (100 * i / len) + "%");
} }
} }
printTimeMemory("delete", System.currentTimeMillis()-time); printTimeMemory("delete", System.currentTimeMillis() - time);
} }
} }
...@@ -23,9 +23,9 @@ public class TestMultiConn extends TestBase implements DatabaseEventListener { ...@@ -23,9 +23,9 @@ public class TestMultiConn extends TestBase implements DatabaseEventListener {
testConcurrentOpen(); testConcurrentOpen();
testThreeThreads(); testThreeThreads();
} }
private static int wait; private static int wait;
private void testThreeThreads() throws Exception { private void testThreeThreads() throws Exception {
deleteDb("multiConn"); deleteDb("multiConn");
final Connection conn1 = getConnection("multiConn"); final Connection conn1 = getConnection("multiConn");
...@@ -51,7 +51,7 @@ public class TestMultiConn extends TestBase implements DatabaseEventListener { ...@@ -51,7 +51,7 @@ public class TestMultiConn extends TestBase implements DatabaseEventListener {
try { try {
s3.execute("INSERT INTO TEST2 VALUES(4)"); s3.execute("INSERT INTO TEST2 VALUES(4)");
conn3.commit(); conn3.commit();
} catch(SQLException e) { } catch (SQLException e) {
TestBase.logError("insert", e); TestBase.logError("insert", e);
} }
} }
...@@ -63,7 +63,7 @@ public class TestMultiConn extends TestBase implements DatabaseEventListener { ...@@ -63,7 +63,7 @@ public class TestMultiConn extends TestBase implements DatabaseEventListener {
try { try {
s2.execute("INSERT INTO TEST1 VALUES(5)"); s2.execute("INSERT INTO TEST1 VALUES(5)");
conn2.commit(); conn2.commit();
} catch(SQLException e) { } catch (SQLException e) {
TestBase.logError("insert", e); TestBase.logError("insert", e);
} }
} }
...@@ -83,12 +83,12 @@ public class TestMultiConn extends TestBase implements DatabaseEventListener { ...@@ -83,12 +83,12 @@ public class TestMultiConn extends TestBase implements DatabaseEventListener {
conn2.close(); conn2.close();
conn3.close(); conn3.close();
} }
private void testConcurrentOpen() throws Exception { private void testConcurrentOpen() throws Exception {
if(config.memory) { if (config.memory) {
return; return;
} }
deleteDb("multiConn"); deleteDb("multiConn");
Connection conn = getConnection("multiConn"); Connection conn = getConnection("multiConn");
conn.createStatement().execute("CREATE TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR)"); conn.createStatement().execute("CREATE TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR)");
conn.createStatement().execute("INSERT INTO TEST VALUES(0, 'Hello'), (1, 'World')"); conn.createStatement().execute("INSERT INTO TEST VALUES(0, 'Hello'), (1, 'World')");
...@@ -98,9 +98,10 @@ public class TestMultiConn extends TestBase implements DatabaseEventListener { ...@@ -98,9 +98,10 @@ public class TestMultiConn extends TestBase implements DatabaseEventListener {
Runnable r = new Runnable() { Runnable r = new Runnable() {
public void run() { public void run() {
try { try {
Connection c1 = getConnection("multiConn;DATABASE_EVENT_LISTENER='"+listener+"';file_lock=socket"); Connection c1 = getConnection("multiConn;DATABASE_EVENT_LISTENER='" + listener
+ "';file_lock=socket");
c1.close(); c1.close();
} catch(Exception e) { } catch (Exception e) {
TestBase.logError("connect", e); TestBase.logError("connect", e);
} }
} }
...@@ -112,7 +113,6 @@ public class TestMultiConn extends TestBase implements DatabaseEventListener { ...@@ -112,7 +113,6 @@ public class TestMultiConn extends TestBase implements DatabaseEventListener {
c2.close(); c2.close();
thread.join(); thread.join();
} }
public void diskSpaceIsLow(long stillAvailable) throws SQLException { public void diskSpaceIsLow(long stillAvailable) throws SQLException {
} }
...@@ -121,7 +121,7 @@ public class TestMultiConn extends TestBase implements DatabaseEventListener { ...@@ -121,7 +121,7 @@ public class TestMultiConn extends TestBase implements DatabaseEventListener {
} }
public void setProgress(int state, String name, int x, int max) { public void setProgress(int state, String name, int x, int max) {
while(wait > 0) { while (wait > 0) {
try { try {
Thread.sleep(wait); Thread.sleep(wait);
wait = 0; wait = 0;
...@@ -132,8 +132,8 @@ public class TestMultiConn extends TestBase implements DatabaseEventListener { ...@@ -132,8 +132,8 @@ public class TestMultiConn extends TestBase implements DatabaseEventListener {
} }
public void closingDatabase() { public void closingDatabase() {
} }
private void testCommitRollback() throws Exception { private void testCommitRollback() throws Exception {
deleteDb("multiConn"); deleteDb("multiConn");
Connection c1 = getConnection("multiConn"); Connection c1 = getConnection("multiConn");
...@@ -156,17 +156,17 @@ public class TestMultiConn extends TestBase implements DatabaseEventListener { ...@@ -156,17 +156,17 @@ public class TestMultiConn extends TestBase implements DatabaseEventListener {
c2.commit(); c2.commit();
c1.close(); c1.close();
c2.close(); c2.close();
if(!config.memory) { if (!config.memory) {
Connection conn = getConnection("multiConn"); Connection conn = getConnection("multiConn");
ResultSet rs; ResultSet rs;
rs = conn.createStatement().executeQuery("SELECT * FROM MULTI_A ORDER BY ID"); rs = conn.createStatement().executeQuery("SELECT * FROM MULTI_A ORDER BY ID");
rs.next(); rs.next();
check(rs.getString("NAME"), "0-insert-A" ); check(rs.getString("NAME"), "0-insert-A");
checkFalse(rs.next()); checkFalse(rs.next());
rs = conn.createStatement().executeQuery("SELECT * FROM MULTI_B ORDER BY ID"); rs = conn.createStatement().executeQuery("SELECT * FROM MULTI_B ORDER BY ID");
rs.next(); rs.next();
check(rs.getString("NAME"), "1-insert-D" ); check(rs.getString("NAME"), "1-insert-D");
checkFalse(rs.next()); checkFalse(rs.next());
conn.close(); conn.close();
} }
......
...@@ -17,38 +17,41 @@ public class TestMultiDimension extends TestBase { ...@@ -17,38 +17,41 @@ public class TestMultiDimension extends TestBase {
public void test() throws Exception { public void test() throws Exception {
Random rand = new Random(10); Random rand = new Random(10);
for(int i=0; i<1000; i++) { for (int i = 0; i < 1000; i++) {
int x = rand.nextInt(1000), y = rand.nextInt(1000), z = rand.nextInt(1000); int x = rand.nextInt(1000), y = rand.nextInt(1000), z = rand.nextInt(1000);
MultiDimension tool = MultiDimension.getInstance(); MultiDimension tool = MultiDimension.getInstance();
long xyz = tool.interleave(new int[]{x, y, z}); long xyz = tool.interleave(new int[] { x, y, z });
check(x, tool.deinterleave(xyz, 3, 0)); check(x, tool.deinterleave(xyz, 3, 0));
check(y, tool.deinterleave(xyz, 3, 1)); check(y, tool.deinterleave(xyz, 3, 1));
check(z, tool.deinterleave(xyz, 3, 2)); check(z, tool.deinterleave(xyz, 3, 2));
} }
deleteDb("multiDimension"); deleteDb("multiDimension");
Connection conn; Connection conn;
conn = getConnection("multiDimension"); conn = getConnection("multiDimension");
Statement stat = conn.createStatement(); Statement stat = conn.createStatement();
stat.execute("CREATE ALIAS MAP FOR \"" + getClass().getName() + ".interleave\""); stat.execute("CREATE ALIAS MAP FOR \"" + getClass().getName() + ".interleave\"");
stat.execute("CREATE TABLE TEST(X INT NOT NULL, Y INT NOT NULL, Z INT NOT NULL, XYZ BIGINT AS MAP(X, Y, Z), DATA VARCHAR)"); stat
.execute("CREATE TABLE TEST(X INT NOT NULL, Y INT NOT NULL, Z INT NOT NULL, XYZ BIGINT AS MAP(X, Y, Z), DATA VARCHAR)");
stat.execute("CREATE INDEX IDX_X ON TEST(X, Y, Z)"); stat.execute("CREATE INDEX IDX_X ON TEST(X, Y, Z)");
stat.execute("CREATE INDEX IDX_XYZ ON TEST(XYZ)"); stat.execute("CREATE INDEX IDX_XYZ ON TEST(XYZ)");
PreparedStatement prep = conn.prepareStatement("INSERT INTO TEST(X, Y, Z, DATA) VALUES(?, ?, ?, ?)"); PreparedStatement prep = conn.prepareStatement("INSERT INTO TEST(X, Y, Z, DATA) VALUES(?, ?, ?, ?)");
// a reasonable max value to see the performance difference is 60; the higher the bigger the difference // a reasonable max value to see the performance difference is 60; the
// higher the bigger the difference
int max = getSize(10, 20); int max = getSize(10, 20);
long time = System.currentTimeMillis(); long time = System.currentTimeMillis();
for(int x=0; x<max; x++) { for (int x = 0; x < max; x++) {
for(int y=0; y<max; y++) { for (int y = 0; y < max; y++) {
for(int z=0; z<max; z++) { for (int z = 0; z < max; z++) {
long t2 = System.currentTimeMillis(); long t2 = System.currentTimeMillis();
if(t2 - time > 1000) { if (t2 - time > 1000) {
int percent = (int)(100.0 * ((double)x*x*x) / ((double)max * max * max)); int percent = (int) (100.0 * ((double) x * x * x) / ((double) max * max * max));
trace(percent + "%"); trace(percent + "%");
time = t2; time = t2;
try { try {
Thread.sleep(10); Thread.sleep(10);
} catch(Exception e) {} } catch (Exception e) {
}
} }
prep.setInt(1, x); prep.setInt(1, x);
prep.setInt(2, y); prep.setInt(2, y);
...@@ -59,25 +62,22 @@ public class TestMultiDimension extends TestBase { ...@@ -59,25 +62,22 @@ public class TestMultiDimension extends TestBase {
} }
} }
stat.execute("ANALYZE SAMPLE_SIZE 10000"); stat.execute("ANALYZE SAMPLE_SIZE 10000");
PreparedStatement prepRegular = conn.prepareStatement( PreparedStatement prepRegular = conn.prepareStatement("SELECT * FROM TEST WHERE X BETWEEN ? AND ? "
"SELECT * FROM TEST WHERE X BETWEEN ? AND ? " + + "AND Y BETWEEN ? AND ? AND Z BETWEEN ? AND ? ORDER BY X, Y, Z");
"AND Y BETWEEN ? AND ? AND Z BETWEEN ? AND ? ORDER BY X, Y, Z");
MultiDimension multi = MultiDimension.getInstance(); MultiDimension multi = MultiDimension.getInstance();
String sql = multi.generatePreparedQuery("TEST", "XYZ", new String[]{"X", "Y", "Z"}); String sql = multi.generatePreparedQuery("TEST", "XYZ", new String[] { "X", "Y", "Z" });
sql += " ORDER BY X, Y, Z"; sql += " ORDER BY X, Y, Z";
PreparedStatement prepMulti = conn.prepareStatement(sql); PreparedStatement prepMulti = conn.prepareStatement(sql);
long timeMulti = 0, timeRegular = 0; long timeMulti = 0, timeRegular = 0;
int timeMax = getSize(100, 2000); int timeMax = getSize(100, 2000);
for(int i=0; timeMulti < timeMax; i++) { for (int i = 0; timeMulti < timeMax; i++) {
int size = rand.nextInt(max / 10); int size = rand.nextInt(max / 10);
int minX = rand.nextInt(max-size); int minX = rand.nextInt(max - size);
int minY = rand.nextInt(max-size); int minY = rand.nextInt(max - size);
int minZ = rand.nextInt(max-size); int minZ = rand.nextInt(max - size);
int maxX = minX+size, maxY = minY+size, maxZ = minZ+size; int maxX = minX + size, maxY = minY + size, maxZ = minZ + size;
time = System.currentTimeMillis(); time = System.currentTimeMillis();
ResultSet rs1 = multi.getResult(prepMulti, ResultSet rs1 = multi.getResult(prepMulti, new int[] { minX, minY, minZ }, new int[] { maxX, maxY, maxZ });
new int[]{minX, minY, minZ},
new int[]{maxX, maxY, maxZ});
timeMulti += System.currentTimeMillis() - time; timeMulti += System.currentTimeMillis() - time;
time = System.currentTimeMillis(); time = System.currentTimeMillis();
prepRegular.setInt(1, minX); prepRegular.setInt(1, minX);
...@@ -88,7 +88,7 @@ public class TestMultiDimension extends TestBase { ...@@ -88,7 +88,7 @@ public class TestMultiDimension extends TestBase {
prepRegular.setInt(6, maxZ); prepRegular.setInt(6, maxZ);
ResultSet rs2 = prepRegular.executeQuery(); ResultSet rs2 = prepRegular.executeQuery();
timeRegular += System.currentTimeMillis() - time; timeRegular += System.currentTimeMillis() - time;
while(rs1.next()) { while (rs1.next()) {
check(rs2.next()); check(rs2.next());
check(rs1.getInt(1), rs2.getInt(1)); check(rs1.getInt(1), rs2.getInt(1));
check(rs1.getInt(2), rs2.getInt(2)); check(rs1.getInt(2), rs2.getInt(2));
...@@ -96,29 +96,24 @@ public class TestMultiDimension extends TestBase { ...@@ -96,29 +96,24 @@ public class TestMultiDimension extends TestBase {
checkFalse(rs2.next()); checkFalse(rs2.next());
} }
trace("multi: " + timeMulti + " regular: " + timeRegular); trace("multi: " + timeMulti + " regular: " + timeRegular);
for(int i=0; i<50; i++) { for (int i = 0; i < 50; i++) {
int size = rand.nextInt(max / 10); int size = rand.nextInt(max / 10);
int minX = rand.nextInt(max-size); int minX = rand.nextInt(max - size);
int minY = rand.nextInt(max-size); int minY = rand.nextInt(max - size);
int minZ = rand.nextInt(max-size); int minZ = rand.nextInt(max - size);
int maxX = minX+size, maxY = minY+size, maxZ = minZ+size; int maxX = minX + size, maxY = minY + size, maxZ = minZ + size;
long time1 = System.currentTimeMillis(); long time1 = System.currentTimeMillis();
String query1 = MultiDimension.getInstance().generateQuery( String query1 = MultiDimension.getInstance().generateQuery("TEST", "XYZ", new String[] { "X", "Y", "Z" },
"TEST", "XYZ", new int[] { minX, minY, minZ }, new int[] { minX + size, minY + size, minZ + size });
new String[]{"X", "Y", "Z"},
new int[]{minX, minY, minZ},
new int[]{minX+size, minY+size, minZ+size});
ResultSet rs1 = conn.createStatement().executeQuery(query1 + " ORDER BY X, Y, Z"); ResultSet rs1 = conn.createStatement().executeQuery(query1 + " ORDER BY X, Y, Z");
time1 = System.currentTimeMillis() - time1; time1 = System.currentTimeMillis() - time1;
long time2 = System.currentTimeMillis(); long time2 = System.currentTimeMillis();
String query2 = "SELECT * FROM TEST WHERE " String query2 = "SELECT * FROM TEST WHERE " + "X BETWEEN " + minX + " AND " + maxX + " AND " + "Y BETWEEN "
+"X BETWEEN " + minX + " AND " + maxX + " AND " + minY + " AND " + maxY + " AND " + "Z BETWEEN " + minZ + " AND " + maxZ;
+"Y BETWEEN " + minY + " AND " + maxY + " AND "
+"Z BETWEEN " + minZ + " AND " + maxZ;
PreparedStatement prep2 = conn.prepareStatement(query2 + " ORDER BY X, Y, Z"); PreparedStatement prep2 = conn.prepareStatement(query2 + " ORDER BY X, Y, Z");
ResultSet rs2 = prep2.executeQuery(); ResultSet rs2 = prep2.executeQuery();
time2 = System.currentTimeMillis() - time2; time2 = System.currentTimeMillis() - time2;
while(rs1.next()) { while (rs1.next()) {
check(rs2.next()); check(rs2.next());
check(rs1.getInt(1), rs2.getInt(1)); check(rs1.getInt(1), rs2.getInt(1));
check(rs1.getInt(2), rs2.getInt(2)); check(rs1.getInt(2), rs2.getInt(2));
...@@ -129,8 +124,8 @@ public class TestMultiDimension extends TestBase { ...@@ -129,8 +124,8 @@ public class TestMultiDimension extends TestBase {
} }
conn.close(); conn.close();
} }
public static long interleave(int x, int y, int z) { public static long interleave(int x, int y, int z) {
return MultiDimension.getInstance().interleave(new int[]{x, y, z}); return MultiDimension.getInstance().interleave(new int[] { x, y, z });
} }
} }
...@@ -31,39 +31,39 @@ public class TestMultiThread extends TestBase implements Runnable { ...@@ -31,39 +31,39 @@ public class TestMultiThread extends TestBase implements Runnable {
conn = getConnection(); conn = getConnection();
stat = conn.createStatement(); stat = conn.createStatement();
} }
public void test() throws Exception { public void test() throws Exception {
Connection conn = getConnection(); Connection conn = getConnection();
Statement stat = conn.createStatement(); Statement stat = conn.createStatement();
stat.execute("CREATE TABLE TEST(ID IDENTITY, NAME VARCHAR)"); stat.execute("CREATE TABLE TEST(ID IDENTITY, NAME VARCHAR)");
int len = getSize(10, 200); int len = getSize(10, 200);
Thread[] threads = new Thread[len]; Thread[] threads = new Thread[len];
for(int i=0; i<len; i++) { for (int i = 0; i < len; i++) {
threads[i] = new Thread(new TestMultiThread(config, this)); threads[i] = new Thread(new TestMultiThread(config, this));
} }
for(int i=0; i<len; i++) { for (int i = 0; i < len; i++) {
threads[i].start(); threads[i].start();
} }
int sleep = getSize(400, 10000); int sleep = getSize(400, 10000);
Thread.sleep(sleep); Thread.sleep(sleep);
this.stop = true; this.stop = true;
for(int i=0; i<len; i++) { for (int i = 0; i < len; i++) {
threads[i].join(); threads[i].join();
} }
ResultSet rs = stat.executeQuery("SELECT COUNT(*) FROM TEST"); ResultSet rs = stat.executeQuery("SELECT COUNT(*) FROM TEST");
rs.next(); rs.next();
trace("max id="+rs.getInt(1)); trace("max id=" + rs.getInt(1));
conn.close(); conn.close();
} }
Connection getConnection() throws Exception { Connection getConnection() throws Exception {
return getConnection("jdbc:h2:mem:multiThread"); return getConnection("jdbc:h2:mem:multiThread");
} }
public void run() { public void run() {
try { try {
while(!parent.stop) { while (!parent.stop) {
stat.execute("SELECT COUNT(*) FROM TEST"); stat.execute("SELECT COUNT(*) FROM TEST");
stat.execute("INSERT INTO TEST VALUES(NULL, 'Hi')"); stat.execute("INSERT INTO TEST VALUES(NULL, 'Hi')");
PreparedStatement prep = conn.prepareStatement("UPDATE TEST SET NAME='Hello' WHERE ID=?"); PreparedStatement prep = conn.prepareStatement("UPDATE TEST SET NAME='Hello' WHERE ID=?");
...@@ -72,12 +72,12 @@ public class TestMultiThread extends TestBase implements Runnable { ...@@ -72,12 +72,12 @@ public class TestMultiThread extends TestBase implements Runnable {
prep = conn.prepareStatement("SELECT * FROM TEST WHERE ID=?"); prep = conn.prepareStatement("SELECT * FROM TEST WHERE ID=?");
prep.setInt(1, random.nextInt(10000)); prep.setInt(1, random.nextInt(10000));
ResultSet rs = prep.executeQuery(); ResultSet rs = prep.executeQuery();
while(rs.next()) { while (rs.next()) {
rs.getString("NAME"); rs.getString("NAME");
} }
} }
conn.close(); conn.close();
} catch(Exception e) { } catch (Exception e) {
logError("multi", e); logError("multi", e);
} }
} }
......
...@@ -29,21 +29,21 @@ public class TestOpenClose extends TestBase implements DatabaseEventListener { ...@@ -29,21 +29,21 @@ public class TestOpenClose extends TestBase implements DatabaseEventListener {
testCase(); testCase();
testReconnectFast(); testReconnectFast();
} }
private void testBackup(boolean encrypt) throws Exception { private void testBackup(boolean encrypt) throws Exception {
deleteDb(baseDir, "openClose"); deleteDb(baseDir, "openClose");
String url; String url;
if(encrypt) { if (encrypt) {
url = "jdbc:h2:"+baseDir+"/openClose;CIPHER=XTEA"; url = "jdbc:h2:" + baseDir + "/openClose;CIPHER=XTEA";
} else { } else {
url = "jdbc:h2:"+baseDir+"/openClose"; url = "jdbc:h2:" + baseDir + "/openClose";
} }
org.h2.Driver.load(); org.h2.Driver.load();
Connection conn = DriverManager.getConnection(url, "sa", "abc def"); Connection conn = DriverManager.getConnection(url, "sa", "abc def");
Statement stat = conn.createStatement(); Statement stat = conn.createStatement();
stat.execute("CREATE TABLE TEST(C CLOB)"); stat.execute("CREATE TABLE TEST(C CLOB)");
stat.execute("INSERT INTO TEST VALUES(SPACE(10000))"); stat.execute("INSERT INTO TEST VALUES(SPACE(10000))");
stat.execute("BACKUP TO '"+baseDir+"/test.zip'"); stat.execute("BACKUP TO '" + baseDir + "/test.zip'");
conn.close(); conn.close();
deleteDb(baseDir, "openClose"); deleteDb(baseDir, "openClose");
Restore.execute(baseDir + "/test.zip", baseDir, null, true); Restore.execute(baseDir + "/test.zip", baseDir, null, true);
...@@ -55,10 +55,11 @@ public class TestOpenClose extends TestBase implements DatabaseEventListener { ...@@ -55,10 +55,11 @@ public class TestOpenClose extends TestBase implements DatabaseEventListener {
checkFalse(rs.next()); checkFalse(rs.next());
conn.close(); conn.close();
} }
private void testReconnectFast() throws Exception { private void testReconnectFast() throws Exception {
deleteDb(baseDir, "openClose"); deleteDb(baseDir, "openClose");
String url = "jdbc:h2:"+baseDir+"/openClose;DATABASE_EVENT_LISTENER='" + TestOpenClose.class.getName()+"'"; String url = "jdbc:h2:" + baseDir + "/openClose;DATABASE_EVENT_LISTENER='" + TestOpenClose.class.getName()
+ "'";
Connection conn = DriverManager.getConnection(url, "sa", "sa"); Connection conn = DriverManager.getConnection(url, "sa", "sa");
Statement stat = conn.createStatement(); Statement stat = conn.createStatement();
try { try {
...@@ -91,14 +92,14 @@ public class TestOpenClose extends TestBase implements DatabaseEventListener { ...@@ -91,14 +92,14 @@ public class TestOpenClose extends TestBase implements DatabaseEventListener {
void testCase() throws Exception { void testCase() throws Exception {
Class.forName("org.h2.Driver"); Class.forName("org.h2.Driver");
deleteDb(baseDir, "openClose"); deleteDb(baseDir, "openClose");
final String url = "jdbc:h2:"+baseDir+"/openClose;FILE_LOCK=NO"; final String url = "jdbc:h2:" + baseDir + "/openClose;FILE_LOCK=NO";
Connection conn = DriverManager.getConnection(url, "sa", ""); Connection conn = DriverManager.getConnection(url, "sa", "");
conn.createStatement().execute("drop table employee if exists"); conn.createStatement().execute("drop table employee if exists");
conn.createStatement().execute("create table employee(id int primary key, name varchar, salary int)"); conn.createStatement().execute("create table employee(id int primary key, name varchar, salary int)");
conn.close(); conn.close();
int len = this.getSize(200, 4000); int len = this.getSize(200, 4000);
Thread[] threads = new Thread[len]; Thread[] threads = new Thread[len];
for(int i=0; i<len; i++) { for (int i = 0; i < len; i++) {
threads[i] = new Thread() { threads[i] = new Thread() {
public void run() { public void run() {
try { try {
...@@ -109,17 +110,17 @@ public class TestOpenClose extends TestBase implements DatabaseEventListener { ...@@ -109,17 +110,17 @@ public class TestOpenClose extends TestBase implements DatabaseEventListener {
prep.setString(2, "employee " + id); prep.setString(2, "employee " + id);
prep.execute(); prep.execute();
conn.close(); conn.close();
} catch(Throwable e) { } catch (Throwable e) {
TestBase.logError("insert", e); TestBase.logError("insert", e);
} }
} }
}; };
threads[i].start(); threads[i].start();
} }
// for(int i=0; i<len; i++) { // for(int i=0; i<len; i++) {
// threads[i].start(); // threads[i].start();
// } // }
for(int i=0; i<len; i++) { for (int i = 0; i < len; i++) {
threads[i].join(); threads[i].join();
} }
conn = DriverManager.getConnection(url, "sa", ""); conn = DriverManager.getConnection(url, "sa", "");
...@@ -132,7 +133,7 @@ public class TestOpenClose extends TestBase implements DatabaseEventListener { ...@@ -132,7 +133,7 @@ public class TestOpenClose extends TestBase implements DatabaseEventListener {
synchronized int getNextId() { synchronized int getNextId() {
return nextId++; return nextId++;
} }
public void diskSpaceIsLow(long stillAvailable) throws SQLException { public void diskSpaceIsLow(long stillAvailable) throws SQLException {
throw new SQLException("unexpected"); throw new SQLException("unexpected");
} }
...@@ -143,16 +144,16 @@ public class TestOpenClose extends TestBase implements DatabaseEventListener { ...@@ -143,16 +144,16 @@ public class TestOpenClose extends TestBase implements DatabaseEventListener {
public void setProgress(int state, String name, int current, int max) { public void setProgress(int state, String name, int current, int max) {
String stateName; String stateName;
switch(state) { switch (state) {
case STATE_SCAN_FILE: case STATE_SCAN_FILE:
stateName = "Scan " + name + " " + current + "/" + max; stateName = "Scan " + name + " " + current + "/" + max;
if(current > 0) { if (current > 0) {
throw new Error("unexpected: " + stateName); throw new Error("unexpected: " + stateName);
} }
break; break;
case STATE_CREATE_INDEX: case STATE_CREATE_INDEX:
stateName = "Create Index " + name + " " + current + "/" + max; stateName = "Create Index " + name + " " + current + "/" + max;
if(!"SYS".equals(name)) { if (!"SYS".equals(name)) {
throw new Error("unexpected: " + stateName); throw new Error("unexpected: " + stateName);
} }
break; break;
...@@ -162,7 +163,7 @@ public class TestOpenClose extends TestBase implements DatabaseEventListener { ...@@ -162,7 +163,7 @@ public class TestOpenClose extends TestBase implements DatabaseEventListener {
default: default:
stateName = "?"; stateName = "?";
} }
// System.out.println(": " + stateName); // System.out.println(": " + stateName);
} }
public void closingDatabase() { public void closingDatabase() {
......
...@@ -18,7 +18,7 @@ import org.h2.test.TestBase; ...@@ -18,7 +18,7 @@ import org.h2.test.TestBase;
public class TestOptimizations extends TestBase { public class TestOptimizations extends TestBase {
public void test() throws Exception { public void test() throws Exception {
if(config.networked) { if (config.networked) {
return; return;
} }
testQueryCacheTimestamp(); testQueryCacheTimestamp();
...@@ -29,10 +29,10 @@ public class TestOptimizations extends TestBase { ...@@ -29,10 +29,10 @@ public class TestOptimizations extends TestBase {
testMinMaxCountOptimization(true); testMinMaxCountOptimization(true);
testMinMaxCountOptimization(false); testMinMaxCountOptimization(false);
} }
private void testQueryCacheTimestamp() throws Exception { private void testQueryCacheTimestamp() throws Exception {
deleteDb("optimizations"); deleteDb("optimizations");
Connection conn=getConnection("optimizations"); Connection conn = getConnection("optimizations");
PreparedStatement prep = conn.prepareStatement("SELECT CURRENT_TIMESTAMP()"); PreparedStatement prep = conn.prepareStatement("SELECT CURRENT_TIMESTAMP()");
ResultSet rs = prep.executeQuery(); ResultSet rs = prep.executeQuery();
rs.next(); rs.next();
...@@ -42,18 +42,20 @@ public class TestOptimizations extends TestBase { ...@@ -42,18 +42,20 @@ public class TestOptimizations extends TestBase {
rs.next(); rs.next();
String b = rs.getString(1); String b = rs.getString(1);
checkFalse(a.equals(b)); checkFalse(a.equals(b));
conn.close(); conn.close();
} }
private void testQueryCacheSpeed() throws Exception { private void testQueryCacheSpeed() throws Exception {
deleteDb("optimizations"); deleteDb("optimizations");
Connection conn=getConnection("optimizations"); Connection conn = getConnection("optimizations");
Statement stat = conn.createStatement(); Statement stat = conn.createStatement();
testQuerySpeed(stat, "select sum(x) from system_range(1, 10000) a where a.x in (select b.x from system_range(1, 30) b)"); testQuerySpeed(stat,
testQuerySpeed(stat, "select sum(a.n), sum(b.x) from system_range(1, 100) b, (select sum(x) n from system_range(1, 4000)) a"); "select sum(x) from system_range(1, 10000) a where a.x in (select b.x from system_range(1, 30) b)");
testQuerySpeed(stat,
"select sum(a.n), sum(b.x) from system_range(1, 100) b, (select sum(x) n from system_range(1, 4000)) a");
conn.close(); conn.close();
} }
private void testQuerySpeed(Statement stat, String sql) throws Exception { private void testQuerySpeed(Statement stat, String sql) throws Exception {
stat.execute("set OPTIMIZE_REUSE_RESULTS 0"); stat.execute("set OPTIMIZE_REUSE_RESULTS 0");
stat.execute(sql); stat.execute(sql);
...@@ -65,16 +67,16 @@ public class TestOptimizations extends TestBase { ...@@ -65,16 +67,16 @@ public class TestOptimizations extends TestBase {
long time2 = System.currentTimeMillis(); long time2 = System.currentTimeMillis();
stat.execute(sql); stat.execute(sql);
time2 = System.currentTimeMillis() - time2; time2 = System.currentTimeMillis() - time2;
if(time2 > time) { if (time2 > time) {
error("not optimized: " + time + " optimized: " + time2+ " sql:"+sql); error("not optimized: " + time + " optimized: " + time2 + " sql:" + sql);
} }
} }
private void testQueryCache(boolean optimize) throws Exception { private void testQueryCache(boolean optimize) throws Exception {
deleteDb("optimizations"); deleteDb("optimizations");
Connection conn=getConnection("optimizations"); Connection conn = getConnection("optimizations");
Statement stat = conn.createStatement(); Statement stat = conn.createStatement();
if(optimize) { if (optimize) {
stat.execute("set OPTIMIZE_REUSE_RESULTS 1"); stat.execute("set OPTIMIZE_REUSE_RESULTS 1");
} else { } else {
stat.execute("set OPTIMIZE_REUSE_RESULTS 0"); stat.execute("set OPTIMIZE_REUSE_RESULTS 0");
...@@ -90,46 +92,46 @@ public class TestOptimizations extends TestBase { ...@@ -90,46 +92,46 @@ public class TestOptimizations extends TestBase {
rs1.next(); rs1.next();
check(rs1.getInt(1), 1); check(rs1.getInt(1), 1);
checkFalse(rs1.next()); checkFalse(rs1.next());
stat.execute("update test2 set id = 2"); stat.execute("update test2 set id = 2");
ResultSet rs2 = prep.executeQuery(); ResultSet rs2 = prep.executeQuery();
rs2.next(); rs2.next();
check(rs2.getInt(1), 2); check(rs2.getInt(1), 2);
conn.close(); conn.close();
} }
private void testMinMaxCountOptimization(boolean memory) throws Exception { private void testMinMaxCountOptimization(boolean memory) throws Exception {
deleteDb("optimizations"); deleteDb("optimizations");
Connection conn=getConnection("optimizations"); Connection conn = getConnection("optimizations");
Statement stat = conn.createStatement(); Statement stat = conn.createStatement();
stat.execute("create "+(memory?"memory":"") +" table test(id int primary key, value int)"); stat.execute("create " + (memory ? "memory" : "") + " table test(id int primary key, value int)");
stat.execute("create index idx_value_id on test(value, id);"); stat.execute("create index idx_value_id on test(value, id);");
int len = getSize(1000, 10000); int len = getSize(1000, 10000);
HashMap map = new HashMap(); HashMap map = new HashMap();
TreeSet set = new TreeSet(); TreeSet set = new TreeSet();
Random random = new Random(1); Random random = new Random(1);
for(int i=0; i<len ; i++) { for (int i = 0; i < len; i++) {
if(i==len / 2) { if (i == len / 2) {
if(!config.memory) { if (!config.memory) {
conn.close(); conn.close();
conn=getConnection("optimizations"); conn = getConnection("optimizations");
stat = conn.createStatement(); stat = conn.createStatement();
} }
} }
switch(random.nextInt(10)) { switch (random.nextInt(10)) {
case 0: case 0:
case 1: case 1:
case 2: case 2:
case 3: case 3:
case 4: case 4:
case 5: case 5:
if(random.nextInt(1000)==1) { if (random.nextInt(1000) == 1) {
stat.execute("insert into test values("+i+", null)"); stat.execute("insert into test values(" + i + ", null)");
map.put(new Integer(i), null); map.put(new Integer(i), null);
} else { } else {
int value = random.nextInt(); int value = random.nextInt();
stat.execute("insert into test values("+i+", "+value+")"); stat.execute("insert into test values(" + i + ", " + value + ")");
map.put(new Integer(i), new Integer(value)); map.put(new Integer(i), new Integer(value));
set.add(new Integer(value)); set.add(new Integer(value));
} }
...@@ -137,14 +139,14 @@ public class TestOptimizations extends TestBase { ...@@ -137,14 +139,14 @@ public class TestOptimizations extends TestBase {
case 6: case 6:
case 7: case 7:
case 8: { case 8: {
if(map.size()>0) { if (map.size() > 0) {
for(int j=random.nextInt(i), k=0; k<10; k++, j++) { for (int j = random.nextInt(i), k = 0; k < 10; k++, j++) {
if(map.containsKey(new Integer(j))) { if (map.containsKey(new Integer(j))) {
Integer x = (Integer) map.remove(new Integer(j)); Integer x = (Integer) map.remove(new Integer(j));
if(x != null) { if (x != null) {
set.remove(x); set.remove(x);
} }
stat.execute("delete from test where id="+j); stat.execute("delete from test where id=" + j);
} }
} }
} }
...@@ -154,14 +156,14 @@ public class TestOptimizations extends TestBase { ...@@ -154,14 +156,14 @@ public class TestOptimizations extends TestBase {
ArrayList list = new ArrayList(map.values()); ArrayList list = new ArrayList(map.values());
int count = list.size(); int count = list.size();
Integer min = null, max = null; Integer min = null, max = null;
if(count > 0) { if (count > 0) {
min = (Integer) set.first(); min = (Integer) set.first();
max = (Integer) set.last(); max = (Integer) set.last();
} }
ResultSet rs = stat.executeQuery("select min(value), max(value), count(*) from test"); ResultSet rs = stat.executeQuery("select min(value), max(value), count(*) from test");
rs.next(); rs.next();
Integer minDb = (Integer)rs.getObject(1); Integer minDb = (Integer) rs.getObject(1);
Integer maxDb = (Integer)rs.getObject(2); Integer maxDb = (Integer) rs.getObject(2);
int countDb = rs.getInt(3); int countDb = rs.getInt(3);
check(minDb, min); check(minDb, min);
check(maxDb, max); check(maxDb, max);
...@@ -174,14 +176,14 @@ public class TestOptimizations extends TestBase { ...@@ -174,14 +176,14 @@ public class TestOptimizations extends TestBase {
private void testIn() throws Exception { private void testIn() throws Exception {
deleteDb("optimizations"); deleteDb("optimizations");
Connection conn=getConnection("optimizations"); Connection conn = getConnection("optimizations");
Statement stat = conn.createStatement(); Statement stat = conn.createStatement();
stat.execute("create table test(id int primary key, name varchar)"); stat.execute("create table test(id int primary key, name varchar)");
stat.execute("insert into test values(1, 'Hello')"); stat.execute("insert into test values(1, 'Hello')");
stat.execute("insert into test values(2, 'World')"); stat.execute("insert into test values(2, 'World')");
PreparedStatement prep; PreparedStatement prep;
ResultSet rs; ResultSet rs;
prep = conn.prepareStatement("select * from test t1 where t1.id in(?)"); prep = conn.prepareStatement("select * from test t1 where t1.id in(?)");
prep.setInt(1, 1); prep.setInt(1, 1);
rs = prep.executeQuery(); rs = prep.executeQuery();
...@@ -210,18 +212,19 @@ public class TestOptimizations extends TestBase { ...@@ -210,18 +212,19 @@ public class TestOptimizations extends TestBase {
check(rs.getString(2), "World"); check(rs.getString(2), "World");
checkFalse(rs.next()); checkFalse(rs.next());
prep = conn.prepareStatement("select * from test t1 where t1.id in(select t2.id from test t2 where t2.id=? and t1.id<>t2.id)"); prep = conn
.prepareStatement("select * from test t1 where t1.id in(select t2.id from test t2 where t2.id=? and t1.id<>t2.id)");
prep.setInt(1, 2); prep.setInt(1, 2);
rs = prep.executeQuery(); rs = prep.executeQuery();
checkFalse(rs.next()); checkFalse(rs.next());
prep = conn.prepareStatement("select * from test t1 where t1.id in(select t2.id from test t2 where t2.id in(cast(?+10 as varchar)))"); prep = conn
.prepareStatement("select * from test t1 where t1.id in(select t2.id from test t2 where t2.id in(cast(?+10 as varchar)))");
prep.setInt(1, 2); prep.setInt(1, 2);
rs = prep.executeQuery(); rs = prep.executeQuery();
checkFalse(rs.next()); checkFalse(rs.next());
conn.close(); conn.close();
} }
} }
...@@ -17,10 +17,10 @@ import org.h2.test.TestBase; ...@@ -17,10 +17,10 @@ import org.h2.test.TestBase;
public class TestReadOnly extends TestBase { public class TestReadOnly extends TestBase {
public void test() throws Exception { public void test() throws Exception {
if(config.memory) { if (config.memory) {
return; return;
} }
File f = File.createTempFile("test", "temp"); File f = File.createTempFile("test", "temp");
check(f.canWrite()); check(f.canWrite());
f.setReadOnly(); f.setReadOnly();
...@@ -43,9 +43,9 @@ public class TestReadOnly extends TestBase { ...@@ -43,9 +43,9 @@ public class TestReadOnly extends TestBase {
stat.execute("INSERT INTO TEST VALUES(2, 'World')"); stat.execute("INSERT INTO TEST VALUES(2, 'World')");
check(!conn.isReadOnly()); check(!conn.isReadOnly());
conn.close(); conn.close();
setReadOnly(); setReadOnly();
conn = getConnection("readonly"); conn = getConnection("readonly");
check(conn.isReadOnly()); check(conn.isReadOnly());
stat = conn.createStatement(); stat = conn.createStatement();
...@@ -53,26 +53,26 @@ public class TestReadOnly extends TestBase { ...@@ -53,26 +53,26 @@ public class TestReadOnly extends TestBase {
try { try {
stat.execute("DELETE FROM TEST"); stat.execute("DELETE FROM TEST");
error("read only delete"); error("read only delete");
} catch(SQLException e) { } catch (SQLException e) {
checkNotGeneralException(e); checkNotGeneralException(e);
} }
conn.close(); conn.close();
conn = getConnection("readonly;DB_CLOSE_DELAY=1"); conn = getConnection("readonly;DB_CLOSE_DELAY=1");
stat = conn.createStatement(); stat = conn.createStatement();
stat.execute("SELECT * FROM TEST"); stat.execute("SELECT * FROM TEST");
try { try {
stat.execute("DELETE FROM TEST"); stat.execute("DELETE FROM TEST");
error("read only delete"); error("read only delete");
} catch(SQLException e) { } catch (SQLException e) {
checkNotGeneralException(e); checkNotGeneralException(e);
} }
conn.close(); conn.close();
} }
private void setReadOnly() throws SQLException { private void setReadOnly() throws SQLException {
ArrayList list = FileLister.getDatabaseFiles(TestBase.baseDir, "readonly", true); ArrayList list = FileLister.getDatabaseFiles(TestBase.baseDir, "readonly", true);
for(int i=0; i<list.size(); i++) { for (int i = 0; i < list.size(); i++) {
String fileName = (String) list.get(i); String fileName = (String) list.get(i);
File file = new File(fileName); File file = new File(fileName);
file.setReadOnly(); file.setReadOnly();
......
...@@ -4,19 +4,23 @@ ...@@ -4,19 +4,23 @@
*/ */
package org.h2.test.db; package org.h2.test.db;
import java.sql.*; import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import org.h2.test.TestBase; import org.h2.test.TestBase;
public class TestRights extends TestBase { public class TestRights extends TestBase {
Statement stat; Statement stat;
public void test() throws Exception { public void test() throws Exception {
if(config.memory) { if (config.memory) {
return; return;
} }
deleteDb("rights"); deleteDb("rights");
Connection conn = getConnection("rights"); Connection conn = getConnection("rights");
stat = conn.createStatement(); stat = conn.createStatement();
...@@ -32,7 +36,7 @@ public class TestRights extends TestBase { ...@@ -32,7 +36,7 @@ public class TestRights extends TestBase {
executeSuccess("GRANT SELECT ON PASS_NAME TO PASS_READER"); executeSuccess("GRANT SELECT ON PASS_NAME TO PASS_READER");
executeSuccess("GRANT SELECT, INSERT, UPDATE ON TEST TO PASS_READER"); executeSuccess("GRANT SELECT, INSERT, UPDATE ON TEST TO PASS_READER");
conn.close(); conn.close();
conn = getConnection("rights", "PASS_READER", "abc"); conn = getConnection("rights", "PASS_READER", "abc");
stat = conn.createStatement(); stat = conn.createStatement();
executeSuccess("SELECT * FROM PASS_NAME"); executeSuccess("SELECT * FROM PASS_NAME");
...@@ -47,15 +51,15 @@ public class TestRights extends TestBase { ...@@ -47,15 +51,15 @@ public class TestRights extends TestBase {
executeError("SELECT * FROM (SELECT * FROM PASS)"); executeError("SELECT * FROM (SELECT * FROM PASS)");
executeError("CREATE VIEW X AS SELECT * FROM PASS_READER"); executeError("CREATE VIEW X AS SELECT * FROM PASS_READER");
conn.close(); conn.close();
conn = getConnection("rights"); conn = getConnection("rights");
stat = conn.createStatement(); stat = conn.createStatement();
executeSuccess("DROP TABLE TEST"); executeSuccess("DROP TABLE TEST");
executeSuccess("CREATE USER TEST PASSWORD 'abc'"); executeSuccess("CREATE USER TEST PASSWORD 'abc'");
executeSuccess("ALTER USER TEST ADMIN TRUE"); executeSuccess("ALTER USER TEST ADMIN TRUE");
executeSuccess("CREATE TABLE TEST(ID INT)"); executeSuccess("CREATE TABLE TEST(ID INT)");
executeSuccess("CREATE SCHEMA SCHEMA_A AUTHORIZATION SA"); executeSuccess("CREATE SCHEMA SCHEMA_A AUTHORIZATION SA");
executeSuccess("CREATE TABLE SCHEMA_A.TABLE_B(ID INT)"); executeSuccess("CREATE TABLE SCHEMA_A.TABLE_B(ID INT)");
executeSuccess("GRANT ALL ON SCHEMA_A.TABLE_B TO TEST"); executeSuccess("GRANT ALL ON SCHEMA_A.TABLE_B TO TEST");
executeSuccess("CREATE TABLE HIDDEN(ID INT)"); executeSuccess("CREATE TABLE HIDDEN(ID INT)");
...@@ -76,34 +80,34 @@ public class TestRights extends TestBase { ...@@ -76,34 +80,34 @@ public class TestRights extends TestBase {
executeSuccess("REVOKE UPDATE, DELETE ON SUB_TABLE FROM SUB2"); executeSuccess("REVOKE UPDATE, DELETE ON SUB_TABLE FROM SUB2");
executeSuccess("GRANT SUB2 TO SUB1"); executeSuccess("GRANT SUB2 TO SUB1");
executeSuccess("GRANT SUB1 TO TEST"); executeSuccess("GRANT SUB1 TO TEST");
executeSuccess("ALTER USER TEST SET PASSWORD 'def'"); executeSuccess("ALTER USER TEST SET PASSWORD 'def'");
executeSuccess("CREATE USER TEST2 PASSWORD 'def' ADMIN"); executeSuccess("CREATE USER TEST2 PASSWORD 'def' ADMIN");
executeSuccess("ALTER USER TEST ADMIN FALSE"); executeSuccess("ALTER USER TEST ADMIN FALSE");
executeSuccess("SCRIPT TO '"+baseDir+"/rights.sql' CIPHER XTEA PASSWORD 'test'"); executeSuccess("SCRIPT TO '" + baseDir + "/rights.sql' CIPHER XTEA PASSWORD 'test'");
conn.close(); conn.close();
try { try {
conn = getConnection("rights", "Test", "abc"); conn = getConnection("rights", "Test", "abc");
error("unexpected success (mixed case user name)"); error("unexpected success (mixed case user name)");
} catch(SQLException e) { } catch (SQLException e) {
checkNotGeneralException(e); checkNotGeneralException(e);
} }
try { try {
conn = getConnection("rights", "TEST", "abc"); conn = getConnection("rights", "TEST", "abc");
error("unexpected success (wrong password)"); error("unexpected success (wrong password)");
} catch(SQLException e) { } catch (SQLException e) {
checkNotGeneralException(e); checkNotGeneralException(e);
} }
try { try {
conn = getConnection("rights", "TEST", null); conn = getConnection("rights", "TEST", null);
error("unexpected success (wrong password)"); error("unexpected success (wrong password)");
} catch(SQLException e) { } catch (SQLException e) {
checkNotGeneralException(e); checkNotGeneralException(e);
} }
conn = getConnection("rights", "TEST", "def"); conn = getConnection("rights", "TEST", "def");
stat = conn.createStatement(); stat = conn.createStatement();
executeError("SET DEFAULT_TABLE_TYPE MEMORY"); executeError("SET DEFAULT_TABLE_TYPE MEMORY");
executeSuccess("SELECT * FROM TEST"); executeSuccess("SELECT * FROM TEST");
...@@ -120,7 +124,7 @@ public class TestRights extends TestBase { ...@@ -120,7 +124,7 @@ public class TestRights extends TestBase {
executeSuccess("INSERT INTO SUB_TABLE VALUES(1)"); executeSuccess("INSERT INTO SUB_TABLE VALUES(1)");
executeError("DELETE FROM SUB_TABLE"); executeError("DELETE FROM SUB_TABLE");
executeError("UPDATE FROM SUB_TABLE"); executeError("UPDATE FROM SUB_TABLE");
executeError("CREATE USER TEST3 PASSWORD 'def'"); executeError("CREATE USER TEST3 PASSWORD 'def'");
executeError("ALTER USER TEST2 ADMIN FALSE"); executeError("ALTER USER TEST2 ADMIN FALSE");
executeError("ALTER USER TEST2 SET PASSWORD 'ghi'"); executeError("ALTER USER TEST2 SET PASSWORD 'ghi'");
...@@ -128,14 +132,14 @@ public class TestRights extends TestBase { ...@@ -128,14 +132,14 @@ public class TestRights extends TestBase {
executeError("ALTER USER TEST RENAME TO TEST_X"); executeError("ALTER USER TEST RENAME TO TEST_X");
executeSuccess("ALTER USER TEST SET PASSWORD 'ghi'"); executeSuccess("ALTER USER TEST SET PASSWORD 'ghi'");
executeError("DROP USER TEST2"); executeError("DROP USER TEST2");
conn.close(); conn.close();
conn = getConnection("rights"); conn = getConnection("rights");
stat = conn.createStatement(); stat = conn.createStatement();
executeSuccess("DROP ROLE SUB1"); executeSuccess("DROP ROLE SUB1");
executeSuccess("DROP TABLE ROLE_TABLE"); executeSuccess("DROP TABLE ROLE_TABLE");
executeSuccess("DROP USER TEST"); executeSuccess("DROP USER TEST");
conn.close(); conn.close();
conn = getConnection("rights"); conn = getConnection("rights");
stat = conn.createStatement(); stat = conn.createStatement();
...@@ -149,11 +153,12 @@ public class TestRights extends TestBase { ...@@ -149,11 +153,12 @@ public class TestRights extends TestBase {
conn = getConnection("rights"); conn = getConnection("rights");
conn.close(); conn.close();
} }
private void testTableType(Connection conn, String type) throws Exception { private void testTableType(Connection conn, String type) throws Exception {
executeSuccess("SET DEFAULT_TABLE_TYPE " + type); executeSuccess("SET DEFAULT_TABLE_TYPE " + type);
executeSuccess("CREATE TABLE TEST(ID INT)"); executeSuccess("CREATE TABLE TEST(ID INT)");
ResultSet rs = conn.createStatement().executeQuery("SELECT STORAGE_TYPE FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME='TEST'"); ResultSet rs = conn.createStatement().executeQuery(
"SELECT STORAGE_TYPE FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME='TEST'");
rs.next(); rs.next();
check(rs.getString(1), type); check(rs.getString(1), type);
executeSuccess("DROP TABLE TEST"); executeSuccess("DROP TABLE TEST");
...@@ -163,39 +168,39 @@ public class TestRights extends TestBase { ...@@ -163,39 +168,39 @@ public class TestRights extends TestBase {
try { try {
stat.execute(sql); stat.execute(sql);
error("unexpected success (not admin)"); error("unexpected success (not admin)");
} catch(SQLException e) { } catch (SQLException e) {
checkNotGeneralException(e); checkNotGeneralException(e);
} }
} }
public void executeSuccess(String sql) throws Exception { public void executeSuccess(String sql) throws Exception {
if(stat.execute(sql)) { if (stat.execute(sql)) {
ResultSet rs = stat.getResultSet(); ResultSet rs = stat.getResultSet();
// this will check if the result set is updatable // this will check if the result set is updatable
rs.getConcurrency(); rs.getConcurrency();
ResultSetMetaData meta = rs.getMetaData(); ResultSetMetaData meta = rs.getMetaData();
int columnCount = meta.getColumnCount(); int columnCount = meta.getColumnCount();
for(int i=0; i<columnCount; i++) { for (int i = 0; i < columnCount; i++) {
meta.getCatalogName(i+1); meta.getCatalogName(i + 1);
meta.getColumnClassName(i+1); meta.getColumnClassName(i + 1);
meta.getColumnDisplaySize(i+1); meta.getColumnDisplaySize(i + 1);
meta.getColumnLabel(i+1); meta.getColumnLabel(i + 1);
meta.getColumnName(i+1); meta.getColumnName(i + 1);
meta.getColumnType(i+1); meta.getColumnType(i + 1);
meta.getColumnTypeName(i+1); meta.getColumnTypeName(i + 1);
meta.getPrecision(i+1); meta.getPrecision(i + 1);
meta.getScale(i+1); meta.getScale(i + 1);
meta.getSchemaName(i+1); meta.getSchemaName(i + 1);
meta.getTableName(i+1); meta.getTableName(i + 1);
} }
while(rs.next()) { while (rs.next()) {
for(int i=0; i<columnCount; i++) { for (int i = 0; i < columnCount; i++) {
rs.getObject(i+1); rs.getObject(i + 1);
} }
} }
} }
} }
} }
...@@ -31,22 +31,23 @@ public class TestRunscript extends TestBase implements Trigger { ...@@ -31,22 +31,23 @@ public class TestRunscript extends TestBase implements Trigger {
stat1.execute("create table test (id identity, name varchar(12))"); stat1.execute("create table test (id identity, name varchar(12))");
stat1.execute("insert into test (name) values ('first'), ('second')"); stat1.execute("insert into test (name) values ('first'), ('second')");
stat1.execute("create sequence testSeq start with 100 increment by 10"); stat1.execute("create sequence testSeq start with 100 increment by 10");
stat1.execute("create alias myTest for \""+getClass().getName()+".test\""); stat1.execute("create alias myTest for \"" + getClass().getName() + ".test\"");
stat1.execute("create trigger myTrigger before insert on test nowait call \""+getClass().getName()+"\""); stat1.execute("create trigger myTrigger before insert on test nowait call \"" + getClass().getName() + "\"");
stat1.execute("create view testView as select * from test where 1=0 union all select * from test where 0=1"); stat1.execute("create view testView as select * from test where 1=0 union all select * from test where 0=1");
stat1.execute("create user testAdmin salt '00' hash '01' admin"); stat1.execute("create user testAdmin salt '00' hash '01' admin");
stat1.execute("create schema testSchema authorization testAdmin"); stat1.execute("create schema testSchema authorization testAdmin");
stat1.execute("create table testSchema.parent(id int primary key, name varchar)"); stat1.execute("create table testSchema.parent(id int primary key, name varchar)");
stat1.execute("create index idxname on testSchema.parent(name)"); stat1.execute("create index idxname on testSchema.parent(name)");
stat1.execute("create table testSchema.child(id int primary key, parentId int, name varchar, foreign key(parentId) references parent(id))"); stat1
.execute("create table testSchema.child(id int primary key, parentId int, name varchar, foreign key(parentId) references parent(id))");
stat1.execute("create user testUser salt '02' hash '03'"); stat1.execute("create user testUser salt '02' hash '03'");
stat1.execute("create role testRole"); stat1.execute("create role testRole");
stat1.execute("grant all on testSchema.child to testUser"); stat1.execute("grant all on testSchema.child to testUser");
stat1.execute("grant select, insert on testSchema.parent to testRole"); stat1.execute("grant select, insert on testSchema.parent to testRole");
stat1.execute("grant testRole to testUser"); stat1.execute("grant testRole to testUser");
String sql = "script to '"+baseDir+"/backup.2.sql'"; String sql = "script to '" + baseDir + "/backup.2.sql'";
if(password) { if (password) {
sql += " CIPHER AES PASSWORD 't1e2s3t4'"; sql += " CIPHER AES PASSWORD 't1e2s3t4'";
} }
stat1.execute(sql); stat1.execute(sql);
...@@ -54,24 +55,24 @@ public class TestRunscript extends TestBase implements Trigger { ...@@ -54,24 +55,24 @@ public class TestRunscript extends TestBase implements Trigger {
deleteDb("runscriptRestore"); deleteDb("runscriptRestore");
conn2 = getConnection("runscriptRestore"); conn2 = getConnection("runscriptRestore");
stat2 = conn2.createStatement(); stat2 = conn2.createStatement();
sql = "runscript from '"+baseDir+"/backup.2.sql'"; sql = "runscript from '" + baseDir + "/backup.2.sql'";
if(password) { if (password) {
sql += " CIPHER AES PASSWORD 'wrongPassword'"; sql += " CIPHER AES PASSWORD 'wrongPassword'";
} }
if(password) { if (password) {
try { try {
stat2.execute(sql); stat2.execute(sql);
error("should fail"); error("should fail");
} catch(SQLException e) { } catch (SQLException e) {
checkNotGeneralException(e); checkNotGeneralException(e);
} }
} }
sql = "runscript from '"+baseDir+"/backup.2.sql'"; sql = "runscript from '" + baseDir + "/backup.2.sql'";
if(password) { if (password) {
sql += " CIPHER AES PASSWORD 't1e2s3t4'"; sql += " CIPHER AES PASSWORD 't1e2s3t4'";
} }
stat2.execute(sql); stat2.execute(sql);
stat2.execute("script to '"+baseDir+"/backup.3.sql'"); stat2.execute("script to '" + baseDir + "/backup.3.sql'");
compareDatabases(stat1, stat2); compareDatabases(stat1, stat2);
......
...@@ -48,13 +48,13 @@ public class TestScript extends TestBase { ...@@ -48,13 +48,13 @@ public class TestScript extends TestBase {
} }
public void test() throws Exception { public void test() throws Exception {
if(config.networked && config.big) { if (config.networked && config.big) {
return; return;
} }
alwaysReconnect = false; alwaysReconnect = false;
testScript(); testScript();
if(!config.memory) { if (!config.memory) {
if(config.big) { if (config.big) {
alwaysReconnect = true; alwaysReconnect = true;
testScript(); testScript();
} }
...@@ -72,7 +72,7 @@ public class TestScript extends TestBase { ...@@ -72,7 +72,7 @@ public class TestScript extends TestBase {
testFile(inFile); testFile(inFile);
conn.close(); conn.close();
out.close(); out.close();
if(errors.length()>0) { if (errors.length() > 0) {
throw new Exception("errors:\n" + errors.toString()); throw new Exception("errors:\n" + errors.toString());
} else { } else {
new File(outFile).delete(); new File(outFile).delete();
...@@ -85,13 +85,13 @@ public class TestScript extends TestBase { ...@@ -85,13 +85,13 @@ public class TestScript extends TestBase {
putBack = null; putBack = null;
return s; return s;
} }
while(true) { while (true) {
String s = in.readLine(); String s = in.readLine();
if(s==null) { if (s == null) {
return s; return s;
} }
s = s.trim(); s = s.trim();
if(s.length() > 0) { if (s.length() > 0) {
return s; return s;
} }
} }
...@@ -125,11 +125,11 @@ public class TestScript extends TestBase { ...@@ -125,11 +125,11 @@ public class TestScript extends TestBase {
} }
private boolean containsTempTables() throws SQLException { private boolean containsTempTables() throws SQLException {
ResultSet rs = conn.getMetaData().getTables(null, null, null, new String[]{"TABLE"}); ResultSet rs = conn.getMetaData().getTables(null, null, null, new String[] { "TABLE" });
while(rs.next()) { while (rs.next()) {
String sql = rs.getString("SQL"); String sql = rs.getString("SQL");
if(sql != null) { if (sql != null) {
if(sql.indexOf("TEMPORARY") >= 0) { if (sql.indexOf("TEMPORARY") >= 0) {
return true; return true;
} }
} }
...@@ -138,10 +138,10 @@ public class TestScript extends TestBase { ...@@ -138,10 +138,10 @@ public class TestScript extends TestBase {
} }
private void process(String sql) throws Exception { private void process(String sql) throws Exception {
if(alwaysReconnect) { if (alwaysReconnect) {
if(!containsTempTables()) { if (!containsTempTables()) {
boolean autocommit = conn.getAutoCommit(); boolean autocommit = conn.getAutoCommit();
if(autocommit) { if (autocommit) {
conn.close(); conn.close();
conn = getConnection("script"); conn = getConnection("script");
conn.setAutoCommit(autocommit); conn.setAutoCommit(autocommit);
...@@ -149,7 +149,7 @@ public class TestScript extends TestBase { ...@@ -149,7 +149,7 @@ public class TestScript extends TestBase {
} }
} }
} }
if(statements != null) { if (statements != null) {
statements.add(sql); statements.add(sql);
} }
if (sql.indexOf('?') == -1) { if (sql.indexOf('?') == -1) {
...@@ -179,16 +179,14 @@ public class TestScript extends TestBase { ...@@ -179,16 +179,14 @@ public class TestScript extends TestBase {
write(""); write("");
} }
private void setParameter(PreparedStatement prep, int i, String param) private void setParameter(PreparedStatement prep, int i, String param) throws SQLException {
throws SQLException {
if (param.equalsIgnoreCase("null")) { if (param.equalsIgnoreCase("null")) {
param = null; param = null;
} }
prep.setString(i, param); prep.setString(i, param);
} }
private int processPrepared(String sql, PreparedStatement prep, String param) private int processPrepared(String sql, PreparedStatement prep, String param) throws Exception {
throws Exception {
try { try {
StringBuffer buff = new StringBuffer(); StringBuffer buff = new StringBuffer();
int index = 0; int index = 0;
...@@ -236,9 +234,9 @@ public class TestScript extends TestBase { ...@@ -236,9 +234,9 @@ public class TestScript extends TestBase {
} }
return 0; return 0;
} }
private String formatString(String s) { private String formatString(String s) {
if (s== null) { if (s == null) {
return "null"; return "null";
} }
return s.replace('\n', ' '); return s.replace('\n', ' ');
...@@ -288,7 +286,7 @@ public class TestScript extends TestBase { ...@@ -288,7 +286,7 @@ public class TestScript extends TestBase {
int length = max.length; int length = max.length;
StringBuffer buff = new StringBuffer(); StringBuffer buff = new StringBuffer();
for (int i = 0; i < length; i++) { for (int i = 0; i < length; i++) {
if(i>0) { if (i > 0) {
buff.append(' '); buff.append(' ');
} }
if (row == null) { if (row == null) {
...@@ -298,7 +296,7 @@ public class TestScript extends TestBase { ...@@ -298,7 +296,7 @@ public class TestScript extends TestBase {
} else { } else {
int len = row[i].length(); int len = row[i].length();
buff.append(row[i]); buff.append(row[i]);
if(i < length - 1) { if (i < length - 1) {
for (int j = len; j < max[i]; j++) { for (int j = len; j < max[i]; j++) {
buff.append(' '); buff.append(' ');
} }
...@@ -325,10 +323,10 @@ public class TestScript extends TestBase { ...@@ -325,10 +323,10 @@ public class TestScript extends TestBase {
errors.append("\n" + "got: "); errors.append("\n" + "got: ");
errors.append(s); errors.append(s);
errors.append("\n"); errors.append("\n");
if(e != null) { if (e != null) {
TestBase.logError("script", e); TestBase.logError("script", e);
} }
if(failFast) { if (failFast) {
TestBase.logError(errors.toString(), null); TestBase.logError(errors.toString(), null);
conn.close(); conn.close();
System.exit(1); System.exit(1);
......
...@@ -16,8 +16,9 @@ import org.h2.util.ScriptReader; ...@@ -16,8 +16,9 @@ import org.h2.util.ScriptReader;
public class TestScriptSimple extends TestBase { public class TestScriptSimple extends TestBase {
private Connection conn; private Connection conn;
public void test() throws Exception { public void test() throws Exception {
if(config.memory || config.big || config.networked) { if (config.memory || config.big || config.networked) {
return; return;
} }
deleteDb("scriptSimple"); deleteDb("scriptSimple");
...@@ -26,19 +27,19 @@ public class TestScriptSimple extends TestBase { ...@@ -26,19 +27,19 @@ public class TestScriptSimple extends TestBase {
InputStream is = getClass().getClassLoader().getResourceAsStream(inFile); InputStream is = getClass().getClassLoader().getResourceAsStream(inFile);
LineNumberReader lineReader = new LineNumberReader(new InputStreamReader(is, "Cp1252")); LineNumberReader lineReader = new LineNumberReader(new InputStreamReader(is, "Cp1252"));
ScriptReader reader = new ScriptReader(lineReader); ScriptReader reader = new ScriptReader(lineReader);
while(true) { while (true) {
String sql = reader.readStatement(); String sql = reader.readStatement();
if(sql == null) { if (sql == null) {
break; break;
} }
sql = sql.trim(); sql = sql.trim();
if("@reconnect".equals(sql.toLowerCase())) { if ("@reconnect".equals(sql.toLowerCase())) {
reconnect(); reconnect();
} else if(sql.length() == 0) { } else if (sql.length() == 0) {
// ignore // ignore
} else if(sql.toLowerCase().startsWith("select")) { } else if (sql.toLowerCase().startsWith("select")) {
ResultSet rs = conn.createStatement().executeQuery(sql); ResultSet rs = conn.createStatement().executeQuery(sql);
while(rs.next()) { while (rs.next()) {
String expected = reader.readStatement().trim(); String expected = reader.readStatement().trim();
String got = "> " + rs.getString(1); String got = "> " + rs.getString(1);
check(expected, got); check(expected, got);
...@@ -50,13 +51,12 @@ public class TestScriptSimple extends TestBase { ...@@ -50,13 +51,12 @@ public class TestScriptSimple extends TestBase {
is.close(); is.close();
conn.close(); conn.close();
} }
private void reconnect() throws Exception { private void reconnect() throws Exception {
if(conn != null) { if (conn != null) {
conn.close(); conn.close();
} }
conn = getConnection("scriptSimple"); conn = getConnection("scriptSimple");
} }
} }
...@@ -14,27 +14,27 @@ public class TestSequence extends TestBase { ...@@ -14,27 +14,27 @@ public class TestSequence extends TestBase {
public void test() throws Exception { public void test() throws Exception {
deleteDb("sequence"); deleteDb("sequence");
Connection conn=getConnection("sequence"); Connection conn = getConnection("sequence");
Statement stat = conn.createStatement(); Statement stat = conn.createStatement();
stat.execute("create sequence testSequence"); stat.execute("create sequence testSequence");
conn.setAutoCommit(false); conn.setAutoCommit(false);
Connection conn2=getConnection("sequence"); Connection conn2 = getConnection("sequence");
Statement stat2 = conn2.createStatement(); Statement stat2 = conn2.createStatement();
conn2.setAutoCommit(false); conn2.setAutoCommit(false);
long last = 0; long last = 0;
for(int i=0; i<100; i++) { for (int i = 0; i < 100; i++) {
long v1 = getNext(stat); long v1 = getNext(stat);
check(v1 > last); check(v1 > last);
last = v1; last = v1;
for(int j=0; j<100; j++) { for (int j = 0; j < 100; j++) {
long v2 = getNext(stat2); long v2 = getNext(stat2);
check(v2 > last); check(v2 > last);
last = v2; last = v2;
} }
} }
conn2.close(); conn2.close();
conn.close(); conn.close();
} }
......
...@@ -4,8 +4,9 @@ ...@@ -4,8 +4,9 @@
*/ */
package org.h2.test.db; package org.h2.test.db;
import java.io.*; import java.io.File;
import java.sql.*; import java.sql.Connection;
import java.sql.Statement;
import org.h2.test.TestBase; import org.h2.test.TestBase;
......
...@@ -33,7 +33,8 @@ public class TestTriggersConstraints extends TestBase implements Trigger { ...@@ -33,7 +33,8 @@ public class TestTriggersConstraints extends TestBase implements Trigger {
Statement stat = conn.createStatement(); Statement stat = conn.createStatement();
stat.execute("DROP TABLE IF EXISTS TEST"); stat.execute("DROP TABLE IF EXISTS TEST");
stat.execute("create table test(id int primary key, parent int)"); stat.execute("create table test(id int primary key, parent int)");
stat.execute("alter table test add constraint test_parent_id foreign key(parent) references test (id) on delete cascade"); stat
.execute("alter table test add constraint test_parent_id foreign key(parent) references test (id) on delete cascade");
stat.execute("insert into test select x, x/2 from system_range(0, 100)"); stat.execute("insert into test select x, x/2 from system_range(0, 100)");
stat.execute("delete from test"); stat.execute("delete from test");
checkSingleValue(stat, "select count(*) from test", 0); checkSingleValue(stat, "select count(*) from test", 0);
...@@ -47,22 +48,29 @@ public class TestTriggersConstraints extends TestBase implements Trigger { ...@@ -47,22 +48,29 @@ public class TestTriggersConstraints extends TestBase implements Trigger {
Statement stat = conn.createStatement(); Statement stat = conn.createStatement();
stat.execute("DROP TABLE IF EXISTS TEST"); stat.execute("DROP TABLE IF EXISTS TEST");
stat.execute("CREATE TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR(255))"); stat.execute("CREATE TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR(255))");
// CREATE TRIGGER trigger {BEFORE|AFTER} {INSERT|UPDATE|DELETE} ON table [FOR EACH ROW] [QUEUE n] [NOWAIT] CALL triggeredClass // CREATE TRIGGER trigger {BEFORE|AFTER} {INSERT|UPDATE|DELETE} ON table
stat.execute("CREATE TRIGGER IF NOT EXISTS INS_BEFORE BEFORE INSERT ON TEST FOR EACH ROW NOWAIT CALL \""+getClass().getName()+"\""); // [FOR EACH ROW] [QUEUE n] [NOWAIT] CALL triggeredClass
stat.execute("CREATE TRIGGER IF NOT EXISTS INS_BEFORE BEFORE INSERT ON TEST FOR EACH ROW NOWAIT CALL \""+getClass().getName()+"\""); stat.execute("CREATE TRIGGER IF NOT EXISTS INS_BEFORE BEFORE INSERT ON TEST FOR EACH ROW NOWAIT CALL \""
stat.execute("CREATE TRIGGER INS_AFTER AFTER INSERT ON TEST FOR EACH ROW NOWAIT CALL \""+getClass().getName()+"\""); + getClass().getName() + "\"");
stat.execute("CREATE TRIGGER UPD_BEFORE BEFORE UPDATE ON TEST FOR EACH ROW NOWAIT CALL \""+getClass().getName()+"\""); stat.execute("CREATE TRIGGER IF NOT EXISTS INS_BEFORE BEFORE INSERT ON TEST FOR EACH ROW NOWAIT CALL \""
+ getClass().getName() + "\"");
stat.execute("CREATE TRIGGER INS_AFTER AFTER INSERT ON TEST FOR EACH ROW NOWAIT CALL \"" + getClass().getName()
+ "\"");
stat.execute("CREATE TRIGGER UPD_BEFORE BEFORE UPDATE ON TEST FOR EACH ROW NOWAIT CALL \""
+ getClass().getName() + "\"");
stat.execute("INSERT INTO TEST VALUES(1, 'Hello')"); stat.execute("INSERT INTO TEST VALUES(1, 'Hello')");
ResultSet rs; ResultSet rs;
rs = stat.executeQuery("SCRIPT"); rs = stat.executeQuery("SCRIPT");
checkRows(rs, new String[]{ checkRows(rs, new String[] {
"CREATE TRIGGER PUBLIC.INS_BEFORE BEFORE INSERT ON PUBLIC.TEST FOR EACH ROW NOWAIT CALL \""+getClass().getName()+"\"", "CREATE TRIGGER PUBLIC.INS_BEFORE BEFORE INSERT ON PUBLIC.TEST FOR EACH ROW NOWAIT CALL \""
"CREATE TRIGGER PUBLIC.INS_AFTER AFTER INSERT ON PUBLIC.TEST FOR EACH ROW NOWAIT CALL \""+getClass().getName()+"\"", + getClass().getName() + "\"",
"CREATE TRIGGER PUBLIC.UPD_BEFORE BEFORE UPDATE ON PUBLIC.TEST FOR EACH ROW NOWAIT CALL \""+getClass().getName()+"\"" "CREATE TRIGGER PUBLIC.INS_AFTER AFTER INSERT ON PUBLIC.TEST FOR EACH ROW NOWAIT CALL \""
}); + getClass().getName() + "\"",
while(rs.next()) { "CREATE TRIGGER PUBLIC.UPD_BEFORE BEFORE UPDATE ON PUBLIC.TEST FOR EACH ROW NOWAIT CALL \""
+ getClass().getName() + "\"" });
while (rs.next()) {
String sql = rs.getString(1); String sql = rs.getString(1);
if(sql.startsWith("CREATE TRIGGER")) { if (sql.startsWith("CREATE TRIGGER")) {
System.out.println(sql); System.out.println(sql);
} }
} }
...@@ -83,7 +91,7 @@ public class TestTriggersConstraints extends TestBase implements Trigger { ...@@ -83,7 +91,7 @@ public class TestTriggersConstraints extends TestBase implements Trigger {
try { try {
stat.execute("DROP TRIGGER INS_BEFORE"); stat.execute("DROP TRIGGER INS_BEFORE");
error("must not work"); error("must not work");
} catch(SQLException e) { } catch (SQLException e) {
checkNotGeneralException(e); checkNotGeneralException(e);
} }
stat.execute("DROP TRIGGER INS_AFTER"); stat.execute("DROP TRIGGER INS_AFTER");
...@@ -100,10 +108,10 @@ public class TestTriggersConstraints extends TestBase implements Trigger { ...@@ -100,10 +108,10 @@ public class TestTriggersConstraints extends TestBase implements Trigger {
private void checkRows(ResultSet rs, String[] expected) throws Exception { private void checkRows(ResultSet rs, String[] expected) throws Exception {
HashSet set = new HashSet(Arrays.asList(expected)); HashSet set = new HashSet(Arrays.asList(expected));
while(rs.next()) { while (rs.next()) {
set.remove(rs.getString(1)); set.remove(rs.getString(1));
} }
if(set.size()>0) { if (set.size() > 0) {
error("set should be empty: " + set); error("set should be empty: " + set);
} }
} }
...@@ -111,22 +119,22 @@ public class TestTriggersConstraints extends TestBase implements Trigger { ...@@ -111,22 +119,22 @@ public class TestTriggersConstraints extends TestBase implements Trigger {
private String triggerName; private String triggerName;
public void fire(Connection conn, Object[] oldRow, Object[] newRow) throws SQLException { public void fire(Connection conn, Object[] oldRow, Object[] newRow) throws SQLException {
if(mustNotCallTrigger) { if (mustNotCallTrigger) {
throw new Error("must not be called now"); throw new Error("must not be called now");
} }
if(conn == null) { if (conn == null) {
throw new Error("connection is null"); throw new Error("connection is null");
} }
if(triggerName.startsWith("INS_BEFORE")) { if (triggerName.startsWith("INS_BEFORE")) {
newRow[1] = newRow[1] + "-updated"; newRow[1] = newRow[1] + "-updated";
} else if(triggerName.startsWith("INS_AFTER")) { } else if (triggerName.startsWith("INS_AFTER")) {
if(!newRow[1].toString().endsWith("-updated")) { if (!newRow[1].toString().endsWith("-updated")) {
throw new Error("supposed to be updated"); throw new Error("supposed to be updated");
} }
} else if(triggerName.startsWith("UPD_BEFORE")) { } else if (triggerName.startsWith("UPD_BEFORE")) {
newRow[1] = newRow[1] + "-updated2"; newRow[1] = newRow[1] + "-updated2";
} else if(triggerName.startsWith("UPD_AFTER")) { } else if (triggerName.startsWith("UPD_AFTER")) {
if(!newRow[1].toString().endsWith("-updated2")) { if (!newRow[1].toString().endsWith("-updated2")) {
throw new Error("supposed to be updated2"); throw new Error("supposed to be updated2");
} }
} }
...@@ -134,7 +142,7 @@ public class TestTriggersConstraints extends TestBase implements Trigger { ...@@ -134,7 +142,7 @@ public class TestTriggersConstraints extends TestBase implements Trigger {
public void init(Connection conn, String schemaName, String triggerName, String tableName) throws SQLException { public void init(Connection conn, String schemaName, String triggerName, String tableName) throws SQLException {
this.triggerName = triggerName; this.triggerName = triggerName;
if(!"TEST".equals(tableName)) { if (!"TEST".equals(tableName)) {
throw new Error("supposed to be TEST"); throw new Error("supposed to be TEST");
} }
} }
......
...@@ -7,6 +7,7 @@ package org.h2.test.db; ...@@ -7,6 +7,7 @@ package org.h2.test.db;
import java.sql.Connection; import java.sql.Connection;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.Statement; import java.sql.Statement;
import org.h2.test.TestBase; import org.h2.test.TestBase;
public class TestView extends TestBase { public class TestView extends TestBase {
......
command=cmd /c "del /s /q /f *.* 2> nul | rmdir /s /q data dataCrash dataIndex dataJoin dataScript dataSynth trace.db org 2> nul | rmdir /s /q data 2> nul" command=cmd /c "del /s /q /f *.* 2> nul | rmdir /s /q data dataCrash dataIndex dataJoin dataScript dataSynth trace.db org 2> nul | rmdir /s /q data 2> nul"
\ No newline at end of file
command=java org.h2.test.TestAll all command=java org.h2.test.TestAll all
\ No newline at end of file
command=java org.h2.test.TestAll btree command=java org.h2.test.TestAll btree
\ No newline at end of file
command=java org.h2.test.TestAll crash command=java org.h2.test.TestAll crash
\ No newline at end of file
command=java org.h2.test.TestAll halt command=java org.h2.test.TestAll halt
\ No newline at end of file
command=java org.h2.test.TestAll join command=java org.h2.test.TestAll join
\ No newline at end of file
command=java org.h2.test.TestAll command=java org.h2.test.TestAll
\ No newline at end of file
command=java org.h2.test.TestAll random command=java org.h2.test.TestAll random
\ No newline at end of file
command=java org.h2.test.TestAll synth command=java org.h2.test.TestAll synth
\ No newline at end of file
...@@ -4,7 +4,11 @@ ...@@ -4,7 +4,11 @@
*/ */
package org.h2.test.jdbc; package org.h2.test.jdbc;
import java.sql.*; import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.h2.test.TestBase; import org.h2.test.TestBase;
...@@ -13,14 +17,16 @@ import org.h2.test.TestBase; ...@@ -13,14 +17,16 @@ import org.h2.test.TestBase;
*/ */
public class TestCancel extends TestBase { public class TestCancel extends TestBase {
class CancelThread extends Thread { class CancelThread extends Thread {
private Statement cancel; private Statement cancel;
private int wait; private int wait;
CancelThread(Statement cancel, int wait) { CancelThread(Statement cancel, int wait) {
this.cancel = cancel; this.cancel = cancel;
this.wait = wait; this.wait = wait;
} }
public void run() { public void run() {
try { try {
Thread.sleep(wait); Thread.sleep(wait);
...@@ -28,12 +34,12 @@ public class TestCancel extends TestBase { ...@@ -28,12 +34,12 @@ public class TestCancel extends TestBase {
Thread.yield(); Thread.yield();
} catch (SQLException e) { } catch (SQLException e) {
// ignore errors on closed statements // ignore errors on closed statements
} catch(Exception e) { } catch (Exception e) {
TestBase.logError("sleep", e); TestBase.logError("sleep", e);
} }
} }
} }
public void test() throws Exception { public void test() throws Exception {
deleteDb("cancel"); deleteDb("cancel");
Connection conn = getConnection("cancel"); Connection conn = getConnection("cancel");
...@@ -43,9 +49,9 @@ public class TestCancel extends TestBase { ...@@ -43,9 +49,9 @@ public class TestCancel extends TestBase {
PreparedStatement prep = conn.prepareStatement("INSERT INTO TEST VALUES(?, ?)"); PreparedStatement prep = conn.prepareStatement("INSERT INTO TEST VALUES(?, ?)");
trace("insert"); trace("insert");
int len = getSize(1, 1000); int len = getSize(1, 1000);
for(int i=0; i<len; i++) { for (int i = 0; i < len; i++) {
prep.setInt(1, i); prep.setInt(1, i);
//prep.setString(2, "Test Value "+i); // prep.setString(2, "Test Value "+i);
prep.setString(2, "hi"); prep.setString(2, "hi");
prep.execute(); prep.execute();
} }
...@@ -56,21 +62,21 @@ public class TestCancel extends TestBase { ...@@ -56,21 +62,21 @@ public class TestCancel extends TestBase {
CancelThread cancel = new CancelThread(query, i); CancelThread cancel = new CancelThread(query, i);
cancel.start(); cancel.start();
Thread.yield(); Thread.yield();
int j=0; int j = 0;
try { try {
ResultSet rs = query.executeQuery("SELECT * FROM TEST"); ResultSet rs = query.executeQuery("SELECT * FROM TEST");
while(rs.next()) { while (rs.next()) {
j++; j++;
} }
trace("record count: "+j); trace("record count: " + j);
} catch(SQLException e) { } catch (SQLException e) {
checkNotGeneralException(e); checkNotGeneralException(e);
// ignore cancelled statements // ignore cancelled statements
trace("record count: "+j); trace("record count: " + j);
} }
if(j == 0) { if (j == 0) {
i += 10; i += 10;
} else if(j == len) { } else if (j == len) {
break; break;
} }
} }
......
...@@ -18,42 +18,44 @@ import org.h2.test.TestBase; ...@@ -18,42 +18,44 @@ import org.h2.test.TestBase;
public class TestDataSource extends TestBase { public class TestDataSource extends TestBase {
// public static void main(String[] args) throws Exception {
// public static void main(String[] args) throws Exception { //
// // // first, need to start on the command line:
// // first, need to start on the command line: // // rmiregistry 1099
// // rmiregistry 1099 //
// // // System.setProperty(Context.INITIAL_CONTEXT_FACTORY,
// // System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); // "com.sun.jndi.ldap.LdapCtxFactory");
// System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.rmi.registry.RegistryContextFactory"); // System.setProperty(Context.INITIAL_CONTEXT_FACTORY,
// System.setProperty(Context.PROVIDER_URL, "rmi://localhost:1099"); // "com.sun.jndi.rmi.registry.RegistryContextFactory");
// // System.setProperty(Context.PROVIDER_URL, "rmi://localhost:1099");
// JdbcDataSource ds = new JdbcDataSource(); //
// ds.setURL("jdbc:h2:test"); // JdbcDataSource ds = new JdbcDataSource();
// ds.setUser("test"); // ds.setURL("jdbc:h2:test");
// ds.setPassword(""); // ds.setUser("test");
// // ds.setPassword("");
// Context ctx = new InitialContext(); //
// ctx.bind("jdbc/test", ds); // Context ctx = new InitialContext();
// // ctx.bind("jdbc/test", ds);
// DataSource ds2 = (DataSource)ctx.lookup("jdbc/test"); //
// Connection conn = ds2.getConnection(); // DataSource ds2 = (DataSource)ctx.lookup("jdbc/test");
// conn.close(); // Connection conn = ds2.getConnection();
// } // conn.close();
// }
public void test() throws Exception { public void test() throws Exception {
testDataSource(); testDataSource();
testXAConnection(); testXAConnection();
} }
private void testXAConnection() throws Exception { private void testXAConnection() throws Exception {
deleteDb(baseDir, "dataSource"); deleteDb(baseDir, "dataSource");
JdbcDataSource ds = new JdbcDataSource(); JdbcDataSource ds = new JdbcDataSource();
ds.setURL("jdbc:h2:"+baseDir+"/dataSource"); ds.setURL("jdbc:h2:" + baseDir + "/dataSource");
XAConnection xaConn = ds.getXAConnection(); XAConnection xaConn = ds.getXAConnection();
xaConn.addConnectionEventListener(new ConnectionEventListener() { xaConn.addConnectionEventListener(new ConnectionEventListener() {
public void connectionClosed(ConnectionEvent event) { public void connectionClosed(ConnectionEvent event) {
} }
public void connectionErrorOccurred(ConnectionEvent event) { public void connectionErrorOccurred(ConnectionEvent event) {
} }
}); });
...@@ -66,11 +68,11 @@ public class TestDataSource extends TestBase { ...@@ -66,11 +68,11 @@ public class TestDataSource extends TestBase {
conn.close(); conn.close();
xaConn.close(); xaConn.close();
} }
private void testDataSource() throws Exception { private void testDataSource() throws Exception {
deleteDb(baseDir, "dataSource"); deleteDb(baseDir, "dataSource");
JdbcDataSource ds = new JdbcDataSource(); JdbcDataSource ds = new JdbcDataSource();
ds.setURL("jdbc:h2:"+baseDir+"/dataSource"); ds.setURL("jdbc:h2:" + baseDir + "/dataSource");
ds.setUser("sa"); ds.setUser("sa");
Connection conn = ds.getConnection(); Connection conn = ds.getConnection();
Statement stat = conn.createStatement(); Statement stat = conn.createStatement();
......
...@@ -20,24 +20,24 @@ public class TestManyJdbcObjects extends TestBase { ...@@ -20,24 +20,24 @@ public class TestManyJdbcObjects extends TestBase {
testManyConnections(); testManyConnections();
testOneConnectionPrepare(); testOneConnectionPrepare();
} }
private void testNestedResultSets() throws Exception { private void testNestedResultSets() throws Exception {
if(config.networked == false) { if (!config.networked) {
return; return;
} }
deleteDb("manyObjects"); deleteDb("manyObjects");
Connection conn = getConnection("manyObjects"); Connection conn = getConnection("manyObjects");
DatabaseMetaData meta = conn.getMetaData(); DatabaseMetaData meta = conn.getMetaData();
ResultSet rsTables = meta.getColumns(null, null, null, null); ResultSet rsTables = meta.getColumns(null, null, null, null);
while(rsTables.next()) { while (rsTables.next()) {
meta.getExportedKeys(null, null, null); meta.getExportedKeys(null, null, null);
meta.getImportedKeys(null, null, null); meta.getImportedKeys(null, null, null);
} }
conn.close(); conn.close();
} }
private void testManyConnections() throws Exception { private void testManyConnections() throws Exception {
if(config.networked == false || config.memory) { if (!config.networked || config.memory) {
return; return;
} }
// SERVER_CACHED_OBJECTS = 1000: connections = 20 (1250) // SERVER_CACHED_OBJECTS = 1000: connections = 20 (1250)
...@@ -47,24 +47,24 @@ public class TestManyJdbcObjects extends TestBase { ...@@ -47,24 +47,24 @@ public class TestManyJdbcObjects extends TestBase {
SysProperties.runFinalize = false; SysProperties.runFinalize = false;
int connCount = getSize(4, 40); int connCount = getSize(4, 40);
Connection[] conn = new Connection[connCount]; Connection[] conn = new Connection[connCount];
for(int i=0; i<connCount; i++) { for (int i = 0; i < connCount; i++) {
conn[i] = getConnection("manyObjects"); conn[i] = getConnection("manyObjects");
} }
int len = getSize(50, 500); int len = getSize(50, 500);
for (int j=0;j<len;j++) { for (int j = 0; j < len; j++) {
if((j % 10) == 0) { if ((j % 10) == 0) {
trace("j=" + j); trace("j=" + j);
} }
for(int i=0; i<connCount; i++) { for (int i = 0; i < connCount; i++) {
conn[i].getMetaData().getSchemas().close(); conn[i].getMetaData().getSchemas().close();
} }
} }
for(int i=0; i<connCount; i++) { for (int i = 0; i < connCount; i++) {
conn[i].close(); conn[i].close();
} }
SysProperties.runFinalize = true; SysProperties.runFinalize = true;
} }
private void testOneConnectionPrepare() throws Exception { private void testOneConnectionPrepare() throws Exception {
deleteDb("manyObjects"); deleteDb("manyObjects");
SysProperties.runFinalize = false; SysProperties.runFinalize = false;
...@@ -72,33 +72,33 @@ public class TestManyJdbcObjects extends TestBase { ...@@ -72,33 +72,33 @@ public class TestManyJdbcObjects extends TestBase {
PreparedStatement prep; PreparedStatement prep;
Statement stat; Statement stat;
int size = getSize(10, 1000); int size = getSize(10, 1000);
for(int i=0; i<size; i++) { for (int i = 0; i < size; i++) {
conn.getMetaData(); conn.getMetaData();
} }
for(int i=0; i<size; i++) { for (int i = 0; i < size; i++) {
conn.createStatement(); conn.createStatement();
} }
stat = conn.createStatement(); stat = conn.createStatement();
stat.execute("CREATE TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR)"); stat.execute("CREATE TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR)");
stat.execute("INSERT INTO TEST VALUES(1, 'Hello')"); stat.execute("INSERT INTO TEST VALUES(1, 'Hello')");
for(int i=0; i<size; i++) { for (int i = 0; i < size; i++) {
stat.executeQuery("SELECT * FROM TEST WHERE 1=0"); stat.executeQuery("SELECT * FROM TEST WHERE 1=0");
} }
for(int i=0; i<size; i++) { for (int i = 0; i < size; i++) {
stat.executeQuery("SELECT * FROM TEST"); stat.executeQuery("SELECT * FROM TEST");
} }
for(int i=0; i<size; i++) { for (int i = 0; i < size; i++) {
conn.prepareStatement("SELECT * FROM TEST"); conn.prepareStatement("SELECT * FROM TEST");
} }
prep = conn.prepareStatement("SELECT * FROM TEST WHERE 1=0"); prep = conn.prepareStatement("SELECT * FROM TEST WHERE 1=0");
for(int i=0; i<size; i++) { for (int i = 0; i < size; i++) {
prep.executeQuery(); prep.executeQuery();
} }
prep = conn.prepareStatement("SELECT * FROM TEST"); prep = conn.prepareStatement("SELECT * FROM TEST");
for(int i=0; i<size; i++) { for (int i = 0; i < size; i++) {
prep.executeQuery(); prep.executeQuery();
} }
SysProperties.runFinalize = true; SysProperties.runFinalize = true;
conn.close(); conn.close();
} }
......
...@@ -9,18 +9,32 @@ import java.sql.SQLException; ...@@ -9,18 +9,32 @@ import java.sql.SQLException;
public interface DbInterface { public interface DbInterface {
void reset() throws SQLException; void reset() throws SQLException;
void connect() throws Exception; void connect() throws Exception;
void disconnect() throws SQLException; void disconnect() throws SQLException;
void end() throws SQLException; void end() throws SQLException;
void createTable(Table table) throws SQLException; void createTable(Table table) throws SQLException;
void dropTable(Table table) throws SQLException; void dropTable(Table table) throws SQLException;
void createIndex(Index index) throws SQLException; void createIndex(Index index) throws SQLException;
void dropIndex(Index index) throws SQLException; void dropIndex(Index index) throws SQLException;
Result insert(Table table, Column[] c, Value[] v) throws SQLException; Result insert(Table table, Column[] c, Value[] v) throws SQLException;
Result select(String sql) throws SQLException; Result select(String sql) throws SQLException;
Result delete(Table table, String condition) throws SQLException; Result delete(Table table, String condition) throws SQLException;
Result update(Table table, Column[] columns, Value[] values, String condition) throws SQLException; Result update(Table table, Column[] columns, Value[] values, String condition) throws SQLException;
void setAutoCommit(boolean b) throws SQLException; void setAutoCommit(boolean b) throws SQLException;
void commit() throws SQLException; void commit() throws SQLException;
void rollback() throws SQLException; void rollback() throws SQLException;
} }
...@@ -505,4 +505,4 @@ prio zvikico incrementally nocheck differently eng admins problog nio though typ ...@@ -505,4 +505,4 @@ prio zvikico incrementally nocheck differently eng admins problog nio though typ
lightweight builder lightweight builder
tunes elephant codewave incorrectly mytunesrss speeds cte honoured httpdocs department whereever dog dept edh oops flower music appends research plant tunes elephant codewave incorrectly mytunesrss speeds cte honoured httpdocs department whereever dog dept edh oops flower music appends research plant
testview gaps birth vid weblog blojsom unsubscribe testview gaps birth vid weblog blojsom unsubscribe
imports bnot severity colon braces suppress star bxor band bor unary bsr puppy lor rcurly lcurly puppycrawl crawl ctor subclasses ell slist lnot land unchecked curly dtds question imports bnot severity colon braces suppress star bxor band bor unary bsr puppy lor rcurly lcurly puppycrawl crawl ctor subclasses ell slist lnot land unchecked curly dtds question
\ No newline at end of file
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论