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

--no commit message

--no commit message
上级 f447a3e4
...@@ -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();
...@@ -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;
...@@ -75,7 +80,7 @@ public class TestBatchUpdates extends TestBase { ...@@ -75,7 +80,7 @@ public class TestBatchUpdates extends TestBase {
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);
...@@ -88,15 +93,14 @@ public class TestBatchUpdates extends TestBase { ...@@ -88,15 +93,14 @@ public class TestBatchUpdates extends TestBase {
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) {
...@@ -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,10 +15,10 @@ import org.h2.util.MemoryUtils; ...@@ -15,10 +15,10 @@ 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();
...@@ -30,51 +30,35 @@ public class TestBigDb extends TestBase { ...@@ -30,51 +30,35 @@ public class TestBigDb extends TestBase {
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,9 +93,9 @@ public class TestBigDb extends TestBase { ...@@ -109,9 +93,9 @@ 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();
} }
...@@ -132,11 +116,11 @@ public class TestBigDb extends TestBase { ...@@ -132,11 +116,11 @@ 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();
...@@ -144,5 +128,4 @@ public class TestBigDb extends TestBase { ...@@ -144,5 +128,4 @@ public class TestBigDb extends TestBase {
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,7 +15,7 @@ import org.h2.test.TestBase; ...@@ -12,7 +15,7 @@ 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();
...@@ -26,14 +29,14 @@ public class TestBigResult extends TestBase { ...@@ -26,14 +29,14 @@ public class TestBigResult extends TestBase {
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,21 +47,21 @@ public class TestBigResult extends TestBase { ...@@ -44,21 +47,21 @@ 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();
...@@ -69,19 +72,16 @@ public class TestBigResult extends TestBase { ...@@ -69,19 +72,16 @@ public class TestBigResult extends TestBase {
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,9 +121,9 @@ public class TestBigResult extends TestBase { ...@@ -121,9 +121,9 @@ 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);
...@@ -132,13 +132,11 @@ public class TestBigResult extends TestBase { ...@@ -132,13 +132,11 @@ public class TestBigResult extends TestBase {
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;
......
...@@ -19,12 +19,12 @@ import org.h2.tools.Server; ...@@ -19,12 +19,12 @@ 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;
...@@ -36,34 +36,33 @@ public class TestCluster extends TestBase { ...@@ -36,34 +36,33 @@ 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 n1 = org.h2.tools.Server.createTcpServer(
Server n2 = org.h2.tools.Server.createTcpServer(new String[]{"-tcpPort", "9092", "-baseDir", baseDir + "/node2"}).start(); new String[] { "-tcpPort", "9091", "-baseDir", baseDir + "/node1" }).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);
} }
...@@ -79,13 +78,15 @@ public class TestCluster extends TestBase { ...@@ -79,13 +78,15 @@ 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");
...@@ -95,11 +96,11 @@ public class TestCluster extends TestBase { ...@@ -95,11 +96,11 @@ public class TestCluster extends TestBase {
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());
} }
} }
......
...@@ -27,19 +27,20 @@ public class TestCsv extends TestBase { ...@@ -27,19 +27,20 @@ public class TestCsv extends TestBase {
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();
} }
...@@ -48,17 +49,17 @@ public class TestCsv extends TestBase { ...@@ -48,17 +49,17 @@ public class TestCsv extends TestBase {
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();
} }
...@@ -97,13 +98,13 @@ public class TestCsv extends TestBase { ...@@ -97,13 +98,13 @@ public class TestCsv extends TestBase {
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 {
...@@ -114,7 +115,7 @@ public class TestCsv extends TestBase { ...@@ -114,7 +115,7 @@ public class TestCsv extends TestBase {
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,9 +123,9 @@ public class TestCsv extends TestBase { ...@@ -122,9 +123,9 @@ 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());
......
...@@ -137,11 +137,11 @@ public class TestFunctions extends TestBase { ...@@ -137,11 +137,11 @@ 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
} }
...@@ -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);
...@@ -205,7 +205,8 @@ public class TestFunctions extends TestBase { ...@@ -205,7 +205,8 @@ public class TestFunctions extends TestBase {
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);
......
...@@ -21,7 +21,7 @@ public class TestListener extends TestBase implements DatabaseEventListener { ...@@ -21,7 +21,7 @@ public class TestListener extends TestBase implements DatabaseEventListener {
} }
public void test() throws Exception { public void test() throws Exception {
if(config.networked) { if (config.networked) {
return; return;
} }
deleteDb("listener"); deleteDb("listener");
...@@ -31,7 +31,7 @@ public class TestListener extends TestBase implements DatabaseEventListener { ...@@ -31,7 +31,7 @@ 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();
} }
...@@ -43,7 +43,7 @@ public class TestListener extends TestBase implements DatabaseEventListener { ...@@ -43,7 +43,7 @@ public class TestListener extends TestBase implements DatabaseEventListener {
} }
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() {
......
...@@ -19,13 +19,13 @@ public class TestLogFile extends TestBase { ...@@ -19,13 +19,13 @@ public class TestLogFile extends TestBase {
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;
...@@ -35,18 +35,18 @@ public class TestLogFile extends TestBase { ...@@ -35,18 +35,18 @@ public class TestLogFile extends TestBase {
} }
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();
...@@ -54,9 +54,9 @@ public class TestLogFile extends TestBase { ...@@ -54,9 +54,9 @@ public class TestLogFile extends TestBase {
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);
} }
...@@ -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();
} }
} }
......
...@@ -17,11 +17,11 @@ public class TestMemoryUsage extends TestBase { ...@@ -17,11 +17,11 @@ 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");
} }
...@@ -41,14 +41,14 @@ public class TestMemoryUsage extends TestBase { ...@@ -41,14 +41,14 @@ public class TestMemoryUsage extends TestBase {
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();
} }
...@@ -60,77 +60,76 @@ public class TestMemoryUsage extends TestBase { ...@@ -60,77 +60,76 @@ public class TestMemoryUsage extends TestBase {
// 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);
} }
} }
...@@ -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);
} }
} }
...@@ -85,7 +85,7 @@ public class TestMultiConn extends TestBase implements DatabaseEventListener { ...@@ -85,7 +85,7 @@ public class TestMultiConn extends TestBase implements DatabaseEventListener {
} }
private void testConcurrentOpen() throws Exception { private void testConcurrentOpen() throws Exception {
if(config.memory) { if (config.memory) {
return; return;
} }
deleteDb("multiConn"); deleteDb("multiConn");
...@@ -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);
} }
} }
...@@ -113,7 +114,6 @@ public class TestMultiConn extends TestBase implements DatabaseEventListener { ...@@ -113,7 +114,6 @@ public class TestMultiConn extends TestBase implements DatabaseEventListener {
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;
...@@ -157,16 +157,16 @@ public class TestMultiConn extends TestBase implements DatabaseEventListener { ...@@ -157,16 +157,16 @@ public class TestMultiConn extends TestBase implements DatabaseEventListener {
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,10 +17,10 @@ public class TestMultiDimension extends TestBase { ...@@ -17,10 +17,10 @@ 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));
...@@ -31,24 +31,27 @@ public class TestMultiDimension extends TestBase { ...@@ -31,24 +31,27 @@ public class TestMultiDimension extends TestBase {
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));
...@@ -131,6 +126,6 @@ public class TestMultiDimension extends TestBase { ...@@ -131,6 +126,6 @@ public class TestMultiDimension extends TestBase {
} }
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 });
} }
} }
...@@ -39,21 +39,21 @@ public class TestMultiThread extends TestBase implements Runnable { ...@@ -39,21 +39,21 @@ public class TestMultiThread extends TestBase implements Runnable {
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();
} }
...@@ -63,7 +63,7 @@ public class TestMultiThread extends TestBase implements Runnable { ...@@ -63,7 +63,7 @@ public class TestMultiThread extends TestBase implements Runnable {
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);
} }
} }
......
...@@ -33,17 +33,17 @@ public class TestOpenClose extends TestBase implements DatabaseEventListener { ...@@ -33,17 +33,17 @@ public class TestOpenClose extends TestBase implements DatabaseEventListener {
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);
...@@ -58,7 +58,8 @@ public class TestOpenClose extends TestBase implements DatabaseEventListener { ...@@ -58,7 +58,8 @@ public class TestOpenClose extends TestBase implements DatabaseEventListener {
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", "");
...@@ -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();
...@@ -32,7 +32,7 @@ public class TestOptimizations extends TestBase { ...@@ -32,7 +32,7 @@ public class TestOptimizations extends TestBase {
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();
...@@ -47,10 +47,12 @@ public class TestOptimizations extends TestBase { ...@@ -47,10 +47,12 @@ public class TestOptimizations extends TestBase {
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();
} }
...@@ -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");
...@@ -101,35 +103,35 @@ public class TestOptimizations extends TestBase { ...@@ -101,35 +103,35 @@ public class TestOptimizations extends TestBase {
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,7 +176,7 @@ public class TestOptimizations extends TestBase { ...@@ -174,7 +176,7 @@ 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')");
...@@ -210,12 +212,14 @@ public class TestOptimizations extends TestBase { ...@@ -210,12 +212,14 @@ 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());
...@@ -223,5 +227,4 @@ public class TestOptimizations extends TestBase { ...@@ -223,5 +227,4 @@ public class TestOptimizations extends TestBase {
conn.close(); conn.close();
} }
} }
...@@ -17,7 +17,7 @@ import org.h2.test.TestBase; ...@@ -17,7 +17,7 @@ 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;
} }
...@@ -53,7 +53,7 @@ public class TestReadOnly extends TestBase { ...@@ -53,7 +53,7 @@ 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();
...@@ -64,7 +64,7 @@ public class TestReadOnly extends TestBase { ...@@ -64,7 +64,7 @@ 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();
...@@ -72,7 +72,7 @@ public class TestReadOnly extends TestBase { ...@@ -72,7 +72,7 @@ public class TestReadOnly extends TestBase {
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,7 +4,11 @@ ...@@ -4,7 +4,11 @@
*/ */
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;
...@@ -13,7 +17,7 @@ public class TestRights extends TestBase { ...@@ -13,7 +17,7 @@ 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;
} }
...@@ -80,25 +84,25 @@ public class TestRights extends TestBase { ...@@ -80,25 +84,25 @@ public class TestRights extends TestBase {
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");
...@@ -153,7 +157,8 @@ public class TestRights extends TestBase { ...@@ -153,7 +157,8 @@ public class TestRights extends TestBase {
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,13 +168,13 @@ public class TestRights extends TestBase { ...@@ -163,13 +168,13 @@ 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
...@@ -177,22 +182,22 @@ public class TestRights extends TestBase { ...@@ -177,22 +182,22 @@ public class TestRights extends TestBase {
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;
...@@ -238,7 +236,7 @@ public class TestScript extends TestBase { ...@@ -238,7 +236,7 @@ public class TestScript extends TestBase {
} }
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);
...@@ -52,11 +53,10 @@ public class TestScriptSimple extends TestBase { ...@@ -52,11 +53,10 @@ public class TestScriptSimple extends TestBase {
} }
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,21 +14,21 @@ public class TestSequence extends TestBase { ...@@ -14,21 +14,21 @@ 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;
......
...@@ -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 {
......
...@@ -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;
...@@ -17,10 +21,12 @@ public class TestCancel extends TestBase { ...@@ -17,10 +21,12 @@ 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,7 +34,7 @@ public class TestCancel extends TestBase { ...@@ -28,7 +34,7 @@ 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);
} }
} }
...@@ -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,28 +18,29 @@ import org.h2.test.TestBase; ...@@ -18,28 +18,29 @@ 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();
...@@ -49,11 +50,12 @@ public class TestDataSource extends TestBase { ...@@ -49,11 +50,12 @@ public class TestDataSource extends TestBase {
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) {
} }
}); });
...@@ -70,7 +72,7 @@ public class TestDataSource extends TestBase { ...@@ -70,7 +72,7 @@ public class TestDataSource extends TestBase {
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();
......
...@@ -22,14 +22,14 @@ public class TestManyJdbcObjects extends TestBase { ...@@ -22,14 +22,14 @@ public class TestManyJdbcObjects extends TestBase {
} }
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);
} }
...@@ -37,7 +37,7 @@ public class TestManyJdbcObjects extends TestBase { ...@@ -37,7 +37,7 @@ public class TestManyJdbcObjects extends TestBase {
} }
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,19 +47,19 @@ public class TestManyJdbcObjects extends TestBase { ...@@ -47,19 +47,19 @@ 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;
...@@ -72,30 +72,30 @@ public class TestManyJdbcObjects extends TestBase { ...@@ -72,30 +72,30 @@ 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;
......
...@@ -4,7 +4,9 @@ ...@@ -4,7 +4,9 @@
*/ */
package org.h2.test.jdbc; package org.h2.test.jdbc;
import java.sql.*; import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import org.h2.test.TestBase; import org.h2.test.TestBase;
...@@ -18,8 +20,8 @@ public class TestNativeSQL extends TestBase { ...@@ -18,8 +20,8 @@ public class TestNativeSQL extends TestBase {
deleteDb("nativeSql"); deleteDb("nativeSql");
Connection conn = getConnection("nativeSql"); Connection conn = getConnection("nativeSql");
for(int i=0;i<PAIRS.length;i+=2) { for (int i = 0; i < PAIRS.length; i += 2) {
test(conn, PAIRS[i], PAIRS[i+1]); test(conn, PAIRS[i], PAIRS[i + 1]);
} }
conn.nativeSQL("TEST"); conn.nativeSQL("TEST");
conn.nativeSQL("TEST--testing"); conn.nativeSQL("TEST--testing");
...@@ -42,7 +44,7 @@ public class TestNativeSQL extends TestBase { ...@@ -42,7 +44,7 @@ public class TestNativeSQL extends TestBase {
try { try {
stat.execute("CALL {d '2001-01-01'} // this is a test"); stat.execute("CALL {d '2001-01-01'} // this is a test");
error("expected error if setEscapeProcessing=false"); error("expected error if setEscapeProcessing=false");
} catch(SQLException e) { } catch (SQLException e) {
checkNotGeneralException(e); checkNotGeneralException(e);
} }
checkFalse(conn.isClosed()); checkFalse(conn.isClosed());
...@@ -50,31 +52,22 @@ public class TestNativeSQL extends TestBase { ...@@ -50,31 +52,22 @@ public class TestNativeSQL extends TestBase {
check(conn.isClosed()); check(conn.isClosed());
} }
static final String[] PAIRS = new String[] { "CREATE TABLE TEST(ID INT PRIMARY KEY)",
static final String[] PAIRS=new String[]{
"CREATE TABLE TEST(ID INT PRIMARY KEY)",
"CREATE TABLE TEST(ID INT PRIMARY KEY)", "CREATE TABLE TEST(ID INT PRIMARY KEY)",
"INSERT INTO TEST VALUES(1)", "INSERT INTO TEST VALUES(1)", "INSERT INTO TEST VALUES(1)",
"INSERT INTO TEST VALUES(1)",
"SELECT '{nothing}' FROM TEST", "SELECT '{nothing}' FROM TEST", "SELECT '{nothing}' FROM TEST",
"SELECT '{nothing}' FROM TEST",
"SELECT '{fn ABS(1)}' FROM TEST", "SELECT '{fn ABS(1)}' FROM TEST", "SELECT '{fn ABS(1)}' FROM TEST",
"SELECT '{fn ABS(1)}' FROM TEST",
"SELECT {d '2001-01-01'} FROM TEST", "SELECT {d '2001-01-01'} FROM TEST", "SELECT '2001-01-01' FROM TEST",
"SELECT '2001-01-01' FROM TEST",
"SELECT {t '20:00:00'} FROM TEST", "SELECT {t '20:00:00'} FROM TEST", "SELECT '20:00:00' FROM TEST",
"SELECT '20:00:00' FROM TEST",
"SELECT {ts '2001-01-01 20:00:00'} FROM TEST", "SELECT {ts '2001-01-01 20:00:00'} FROM TEST", "SELECT '2001-01-01 20:00:00' FROM TEST",
"SELECT '2001-01-01 20:00:00' FROM TEST",
"SELECT {fn CONCAT('{fn x}','{oj}')} FROM TEST", "SELECT {fn CONCAT('{fn x}','{oj}')} FROM TEST", "SELECT CONCAT('{fn x}','{oj}') FROM TEST",
"SELECT CONCAT('{fn x}','{oj}') FROM TEST",
"SELECT * FROM {oj TEST T1 LEFT OUTER JOIN TEST T2 ON T1.ID=T2.ID}", "SELECT * FROM {oj TEST T1 LEFT OUTER JOIN TEST T2 ON T1.ID=T2.ID}",
"SELECT * FROM TEST T1 LEFT OUTER JOIN TEST T2 ON T1.ID=T2.ID ", "SELECT * FROM TEST T1 LEFT OUTER JOIN TEST T2 ON T1.ID=T2.ID ",
...@@ -85,27 +78,22 @@ public class TestNativeSQL extends TestBase { ...@@ -85,27 +78,22 @@ public class TestNativeSQL extends TestBase {
"SELECT * FROM TEST WHERE '}' LIKE '}}' {escape '}'}", "SELECT * FROM TEST WHERE '}' LIKE '}}' {escape '}'}",
"SELECT * FROM TEST WHERE '}' LIKE '}}' escape '}' ", "SELECT * FROM TEST WHERE '}' LIKE '}}' escape '}' ",
"{call TEST('}')}", "{call TEST('}')}", " call TEST('}') ",
" call TEST('}') ",
"{?= call TEST('}')}", "{?= call TEST('}')}", " call TEST('}') ",
" call TEST('}') ",
"{? = call TEST('}')}", "{? = call TEST('}')}", " call TEST('}') ",
" call TEST('}') ",
"{{{{this is a bug}", "{{{{this is a bug}", null, };
null,
};
void test(Connection conn, String original,String expected) throws Exception { void test(Connection conn, String original, String expected) throws Exception {
trace("original: <"+original+">"); trace("original: <" + original + ">");
trace("expected: <"+expected+">"); trace("expected: <" + expected + ">");
try { try {
String result=conn.nativeSQL(original); String result = conn.nativeSQL(original);
trace("result: <"+result+">"); trace("result: <" + result + ">");
check(expected, result); check(expected, result);
} catch(SQLException e) { } catch (SQLException e) {
check(expected, null); check(expected, null);
checkNotGeneralException(e); checkNotGeneralException(e);
trace("got exception, good"); trace("got exception, good");
......
...@@ -4,7 +4,8 @@ ...@@ -4,7 +4,8 @@
*/ */
package org.h2.test.jdbc; package org.h2.test.jdbc;
import java.sql.*; import java.sql.Connection;
import java.sql.SQLException;
import org.h2.test.TestBase; import org.h2.test.TestBase;
...@@ -13,7 +14,7 @@ public class TestTransactionIsolation extends TestBase { ...@@ -13,7 +14,7 @@ public class TestTransactionIsolation extends TestBase {
Connection conn1, conn2; Connection conn1, conn2;
public void test() throws Exception { public void test() throws Exception {
if(config.isMVCC()) { if (config.isMVCC()) {
// no tests yet // no tests yet
} else { } else {
testTableLevelLocking(); testTableLevelLocking();
...@@ -54,7 +55,7 @@ public class TestTransactionIsolation extends TestBase { ...@@ -54,7 +55,7 @@ public class TestTransactionIsolation extends TestBase {
try { try {
checkSingleValue(conn2.createStatement(), "SELECT * FROM TEST", 1); checkSingleValue(conn2.createStatement(), "SELECT * FROM TEST", 1);
error("Expected lock timeout"); error("Expected lock timeout");
} catch(SQLException e) { } catch (SQLException e) {
checkNotGeneralException(e); checkNotGeneralException(e);
} }
conn1.commit(); conn1.commit();
...@@ -76,7 +77,7 @@ public class TestTransactionIsolation extends TestBase { ...@@ -76,7 +77,7 @@ public class TestTransactionIsolation extends TestBase {
try { try {
conn1.createStatement().executeUpdate("DELETE FROM TEST"); conn1.createStatement().executeUpdate("DELETE FROM TEST");
error("Expected lock timeout"); error("Expected lock timeout");
} catch(SQLException e) { } catch (SQLException e) {
checkNotGeneralException(e); checkNotGeneralException(e);
} }
conn2.commit(); conn2.commit();
......
...@@ -5,6 +5,7 @@ ...@@ -5,6 +5,7 @@
package org.h2.test.jdbc; package org.h2.test.jdbc;
import java.sql.Connection; import java.sql.Connection;
import org.h2.jdbcx.JdbcDataSource; import org.h2.jdbcx.JdbcDataSource;
public class TestXASimple { public class TestXASimple {
...@@ -14,9 +15,8 @@ public class TestXASimple { ...@@ -14,9 +15,8 @@ public class TestXASimple {
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
Class.forName("org.h2.Driver"); Class.forName("org.h2.Driver");
// InitialContext context = new InitialContext();
// InitialContext context = new InitialContext(); // context.rebind(USER_TRANSACTION_JNDI_NAME, j.getUserTransaction());
// context.rebind(USER_TRANSACTION_JNDI_NAME, j.getUserTransaction());
JdbcDataSource ds1 = new JdbcDataSource(); JdbcDataSource ds1 = new JdbcDataSource();
ds1.setPassword(""); ds1.setPassword("");
...@@ -28,8 +28,9 @@ public class TestXASimple { ...@@ -28,8 +28,9 @@ public class TestXASimple {
ds2.setUser("sa"); ds2.setUser("sa");
ds2.setURL("jdbc:h2:db2H2"); ds2.setURL("jdbc:h2:db2H2");
// UserTransaction ut = (UserTransaction) context.lookup("UserTransaction"); // UserTransaction ut = (UserTransaction)
// ut.begin(); // context.lookup("UserTransaction");
// ut.begin();
Connection c1 = ds1.getXAConnection().getConnection(); Connection c1 = ds1.getXAConnection().getConnection();
c1.setAutoCommit(false); c1.setAutoCommit(false);
...@@ -39,13 +40,12 @@ public class TestXASimple { ...@@ -39,13 +40,12 @@ public class TestXASimple {
c1.createStatement().executeUpdate("create table test(id int, test varchar(255))"); c1.createStatement().executeUpdate("create table test(id int, test varchar(255))");
c2.createStatement().executeUpdate("create table test(id int, test varchar(255))"); c2.createStatement().executeUpdate("create table test(id int, test varchar(255))");
// ut.rollback();
// ut.rollback();
c1.close(); c1.close();
c2.close(); c2.close();
// j.stop(); // j.stop();
// System.exit(0); // System.exit(0);
} }
} }
...@@ -61,6 +61,7 @@ public class TestZloty extends TestBase { ...@@ -61,6 +61,7 @@ public class TestZloty extends TestBase {
/** /**
* H2 destroyer application ;-> * H2 destroyer application ;->
*
* @author Maciej Wegorkiewicz * @author Maciej Wegorkiewicz
*/ */
private void testZloty() throws Exception { private void testZloty() throws Exception {
...@@ -76,20 +77,23 @@ public class TestZloty extends TestBase { ...@@ -76,20 +77,23 @@ public class TestZloty extends TestBase {
prep.setBigDecimal(2, new ZlotyBigDecimal("11.0")); prep.setBigDecimal(2, new ZlotyBigDecimal("11.0"));
prep.execute(); prep.execute();
error("unexpected success"); error("unexpected success");
} catch(SQLException e) { } catch (SQLException e) {
checkNotGeneralException(e); checkNotGeneralException(e);
} }
prep.setInt(1, 3); prep.setInt(1, 3);
try { try {
BigDecimal value=new BigDecimal("12.100000") { BigDecimal value = new BigDecimal("12.100000") {
private static final long serialVersionUID = -7909023971521750844L; private static final long serialVersionUID = -7909023971521750844L;
public String toString() { return "12,100000 EURO"; }
public String toString() {
return "12,100000 EURO";
}
}; };
prep.setBigDecimal(2, value); prep.setBigDecimal(2, value);
prep.execute(); prep.execute();
error("unexpected success"); error("unexpected success");
} catch(SQLException e) { } catch (SQLException e) {
checkNotGeneralException(e); checkNotGeneralException(e);
} }
......
...@@ -31,7 +31,7 @@ class DbConnection implements DbInterface { ...@@ -31,7 +31,7 @@ class DbConnection implements DbInterface {
this.password = password; this.password = password;
this.id = id; this.id = id;
this.useSentinel = useSentinel; this.useSentinel = useSentinel;
log("url="+url); log("url=" + url);
} }
public void reset() throws SQLException { public void reset() throws SQLException {
...@@ -39,10 +39,10 @@ class DbConnection implements DbInterface { ...@@ -39,10 +39,10 @@ class DbConnection implements DbInterface {
DatabaseMetaData meta = conn.getMetaData(); DatabaseMetaData meta = conn.getMetaData();
Statement stat = conn.createStatement(); Statement stat = conn.createStatement();
ArrayList tables = new ArrayList(); ArrayList tables = new ArrayList();
ResultSet rs = meta.getTables(null, null, null, new String[] { "TABLE"}); ResultSet rs = meta.getTables(null, null, null, new String[] { "TABLE" });
while (rs.next()) { while (rs.next()) {
String schemaName = rs.getString("TABLE_SCHEM"); String schemaName = rs.getString("TABLE_SCHEM");
if(!"INFORMATION_SCHEMA".equals(schemaName)) { if (!"INFORMATION_SCHEMA".equals(schemaName)) {
tables.add(rs.getString("TABLE_NAME")); tables.add(rs.getString("TABLE_NAME"));
} }
} }
...@@ -61,22 +61,22 @@ class DbConnection implements DbInterface { ...@@ -61,22 +61,22 @@ class DbConnection implements DbInterface {
} }
// could not drop any table and still tables to drop // could not drop any table and still tables to drop
if (dropped == 0 && tables.size() > 0) { if (dropped == 0 && tables.size() > 0) {
throw new Error("Cannot drop "+tables); throw new Error("Cannot drop " + tables);
} }
} }
} }
public void connect() throws Exception { public void connect() throws Exception {
if(useSentinel && sentinel == null) { if (useSentinel && sentinel == null) {
sentinel = getConnection(); sentinel = getConnection();
} }
log("connect to "+url+";"); log("connect to " + url + ";");
conn = getConnection(); conn = getConnection();
} }
private Connection getConnection() throws Exception { private Connection getConnection() throws Exception {
log("(getConnection to "+url+");"); log("(getConnection to " + url + ");");
if(driver==null) { if (driver == null) {
return config.getConnection("synth"); return config.getConnection("synth");
} else { } else {
Class.forName(driver); Class.forName(driver);
...@@ -85,13 +85,13 @@ class DbConnection implements DbInterface { ...@@ -85,13 +85,13 @@ class DbConnection implements DbInterface {
} }
public void disconnect() throws SQLException { public void disconnect() throws SQLException {
log("disconnect "+url+";"); log("disconnect " + url + ";");
conn.close(); conn.close();
} }
public void end() throws SQLException { public void end() throws SQLException {
log("end "+url+";"); log("end " + url + ";");
if(sentinel != null) { if (sentinel != null) {
sentinel.close(); sentinel.close();
sentinel = null; sentinel = null;
} }
...@@ -122,12 +122,12 @@ class DbConnection implements DbInterface { ...@@ -122,12 +122,12 @@ class DbConnection implements DbInterface {
} }
private void execute(String sql) throws SQLException { private void execute(String sql) throws SQLException {
log(sql+";"); log(sql + ";");
conn.createStatement().execute(sql); conn.createStatement().execute(sql);
} }
public Result select(String sql) throws SQLException { public Result select(String sql) throws SQLException {
log(sql+";"); log(sql + ";");
Statement stat = conn.createStatement(); Statement stat = conn.createStatement();
Result result = new Result(config, sql, stat.executeQuery(sql)); Result result = new Result(config, sql, stat.executeQuery(sql));
return result; return result;
...@@ -135,10 +135,10 @@ class DbConnection implements DbInterface { ...@@ -135,10 +135,10 @@ class DbConnection implements DbInterface {
public Result delete(Table table, String condition) throws SQLException { public Result delete(Table table, String condition) throws SQLException {
String sql = "DELETE FROM " + table.getName(); String sql = "DELETE FROM " + table.getName();
if(condition!=null) { if (condition != null) {
sql += " WHERE " + condition; sql += " WHERE " + condition;
} }
log(sql+";"); log(sql + ";");
Statement stat = conn.createStatement(); Statement stat = conn.createStatement();
Result result = new Result(sql, stat.executeUpdate(sql)); Result result = new Result(sql, stat.executeUpdate(sql));
return result; return result;
...@@ -146,23 +146,23 @@ class DbConnection implements DbInterface { ...@@ -146,23 +146,23 @@ class DbConnection implements DbInterface {
public Result update(Table table, Column[] columns, Value[] values, String condition) throws SQLException { public Result update(Table table, Column[] columns, Value[] values, String condition) throws SQLException {
String sql = "UPDATE " + table.getName() + " SET "; String sql = "UPDATE " + table.getName() + " SET ";
for(int i=0; i<columns.length; i++) { for (int i = 0; i < columns.length; i++) {
if(i>0) { if (i > 0) {
sql += ", "; sql += ", ";
} }
sql += columns[i].getName() + "=" + values[i].getSQL(); sql += columns[i].getName() + "=" + values[i].getSQL();
} }
if(condition!=null) { if (condition != null) {
sql += " WHERE " + condition; sql += " WHERE " + condition;
} }
log(sql+";"); log(sql + ";");
Statement stat = conn.createStatement(); Statement stat = conn.createStatement();
Result result = new Result(sql, stat.executeUpdate(sql)); Result result = new Result(sql, stat.executeUpdate(sql));
return result; return result;
} }
public void setAutoCommit(boolean b) throws SQLException { public void setAutoCommit(boolean b) throws SQLException {
log("set autoCommit " + b+";"); log("set autoCommit " + b + ";");
conn.setAutoCommit(b); conn.setAutoCommit(b);
} }
......
...@@ -75,7 +75,7 @@ public class DbState implements DbInterface { ...@@ -75,7 +75,7 @@ public class DbState implements DbInterface {
} }
public Table randomTable() { public Table randomTable() {
if(tables.size() == 0) { if (tables.size() == 0) {
return null; return null;
} }
int i = config.random().getInt(tables.size()); int i = config.random().getInt(tables.size());
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论