001: /*
002: * Copyright 2004-2008 H2 Group. Licensed under the H2 License, Version 1.0
003: * (license2)
004: * Initial Developer: H2 Group
005: */
006: package org.h2.test.bench;
007:
008: import java.io.PrintWriter;
009: import java.lang.reflect.Method;
010: import java.sql.Connection;
011: import java.sql.DriverManager;
012: import java.sql.PreparedStatement;
013: import java.sql.ResultSet;
014: import java.sql.ResultSetMetaData;
015: import java.sql.Statement;
016: import java.util.ArrayList;
017: import java.util.Iterator;
018: import java.util.Properties;
019: import java.util.Random;
020: import java.util.StringTokenizer;
021:
022: import org.h2.test.TestBase;
023: import org.h2.tools.Server;
024: import org.h2.util.JdbcUtils;
025: import org.h2.util.StringUtils;
026:
027: /**
028: * Represents a database in the benchmark test application.
029: */
030: class Database {
031:
032: private TestPerformance test;
033: private int id;
034: private String name, url, user, password;
035: private ArrayList replace = new ArrayList();
036: private String action;
037: private long startTime;
038: private Connection conn;
039: private Statement stat;
040: private boolean trace = true;
041: private long lastTrace;
042: private Random random = new Random(1);
043: private ArrayList results = new ArrayList();
044: private int totalTime;
045: private int executedStatements;
046:
047: private Server serverH2;
048: private Object serverDerby;
049: private boolean serverHSQLDB;
050:
051: String getName() {
052: return name;
053: }
054:
055: int getTotalTime() {
056: return totalTime;
057: }
058:
059: ArrayList getResults() {
060: return results;
061: }
062:
063: Random getRandom() {
064: return random;
065: }
066:
067: void startServer() throws Exception {
068: if (url.startsWith("jdbc:h2:tcp:")) {
069: serverH2 = Server.createTcpServer(new String[0]).start();
070: Thread.sleep(100);
071: } else if (url.startsWith("jdbc:derby://")) {
072: serverDerby = Class.forName(
073: "org.apache.derby.drda.NetworkServerControl")
074: .newInstance();
075: Method m = serverDerby.getClass().getMethod("start",
076: new Class[] { PrintWriter.class });
077: m.invoke(serverDerby, new Object[] { null });
078: // serverDerby = new NetworkServerControl();
079: // serverDerby.start(null);
080: Thread.sleep(100);
081: } else if (url.startsWith("jdbc:hsqldb:hsql:")) {
082: if (!serverHSQLDB) {
083: Class c = Class.forName("org.hsqldb.Server");
084: Method m = c.getMethod("main",
085: new Class[] { String[].class });
086: m.invoke(null, new Object[] { new String[] {
087: "-database.0",
088: "data/mydb;hsqldb.default_table_type=cached",
089: "-dbname.0", "xdb" } });
090: // org.hsqldb.Server.main(new String[]{"-database.0", "mydb",
091: // "-dbname.0", "xdb"});
092: serverHSQLDB = true;
093: Thread.sleep(100);
094: }
095: }
096: }
097:
098: void stopServer() throws Exception {
099: if (serverH2 != null) {
100: serverH2.stop();
101: serverH2 = null;
102: }
103: if (serverDerby != null) {
104: Method m = serverDerby.getClass().getMethod("shutdown",
105: new Class[] {});
106: // cast for JDK 1.5
107: m.invoke(serverDerby, (Object[]) null);
108: // serverDerby.shutdown();
109: serverDerby = null;
110: } else if (serverHSQLDB) {
111: // can not shut down (shutdown calls System.exit)
112: // openConnection();
113: // update("SHUTDOWN");
114: // closeConnection();
115: // serverHSQLDB = false;
116: }
117: }
118:
119: static Database parse(TestPerformance test, int id, String dbString) {
120: try {
121: StringTokenizer tokenizer = new StringTokenizer(dbString,
122: ",");
123: Database db = new Database();
124: db.id = id;
125: db.test = test;
126: db.name = tokenizer.nextToken().trim();
127: String driver = tokenizer.nextToken().trim();
128: Class.forName(driver);
129: db.url = tokenizer.nextToken().trim();
130: db.user = tokenizer.nextToken().trim();
131: db.password = "";
132: if (tokenizer.hasMoreTokens()) {
133: db.password = tokenizer.nextToken().trim();
134: }
135: System.out.println("Loaded successfully: " + db.name);
136: return db;
137: } catch (Exception e) {
138: System.out.println("Cannot load database " + dbString
139: + " :" + e.toString());
140: return null;
141: }
142: }
143:
144: Connection getConnection() throws Exception {
145: Connection conn = DriverManager.getConnection(url, user,
146: password);
147: if (url.startsWith("jdbc:derby:")) {
148: // Derby: use higher cache size
149: Statement stat = null;
150: try {
151: stat = conn.createStatement();
152: // stat.execute("CALL
153: // SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY('derby.storage.pageCacheSize',
154: // '64')");
155: // stat.execute("CALL
156: // SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY('derby.storage.pageSize',
157: // '8192')");
158: } finally {
159: JdbcUtils.closeSilently(stat);
160: }
161: } else if (url.startsWith("jdbc:hsqldb:")) {
162: // HSQLDB: use a WRITE_DELAY of 1 second
163: Statement stat = null;
164: try {
165: stat = conn.createStatement();
166: stat.execute("SET WRITE_DELAY 1");
167: } finally {
168: JdbcUtils.closeSilently(stat);
169: }
170: }
171: return conn;
172: }
173:
174: void openConnection() throws Exception {
175: conn = DriverManager.getConnection(url, user, password);
176: stat = conn.createStatement();
177: }
178:
179: void closeConnection() throws Exception {
180: // if(!serverHSQLDB && url.startsWith("jdbc:hsqldb:")) {
181: // stat.execute("SHUTDOWN");
182: // }
183: conn.close();
184: stat = null;
185: conn = null;
186: }
187:
188: public void setTranslations(Properties prop) {
189: String id = url.substring("jdbc:".length());
190: id = id.substring(0, id.indexOf(':'));
191: for (Iterator it = prop.keySet().iterator(); it.hasNext();) {
192: String key = (String) it.next();
193: if (key.startsWith(id + ".")) {
194: String pattern = key.substring(id.length() + 1);
195: pattern = StringUtils.replaceAll(pattern, "_", " ");
196: pattern = StringUtils.toUpperEnglish(pattern);
197: String replacement = prop.getProperty(key);
198: replace.add(new String[] { pattern, replacement });
199: }
200: }
201: }
202:
203: PreparedStatement prepare(String sql) throws Exception {
204: sql = getSQL(sql);
205: return conn.prepareStatement(sql);
206: }
207:
208: public String getSQL(String sql) {
209: for (int i = 0; i < replace.size(); i++) {
210: String[] pair = (String[]) replace.get(i);
211: String pattern = pair[0];
212: String replace = pair[1];
213: sql = StringUtils.replaceAll(sql, pattern, replace);
214: }
215: return sql;
216: }
217:
218: void start(Bench bench, String action) {
219: this .action = bench.getName() + ": " + action;
220: this .startTime = System.currentTimeMillis();
221: }
222:
223: void end() {
224: long time = System.currentTimeMillis() - startTime;
225: log(action, "ms", (int) time);
226: if (test.collect) {
227: totalTime += time;
228: }
229: }
230:
231: void dropTable(String table) {
232: try {
233: update("DROP TABLE " + table);
234: } catch (Exception e) {
235: // ignore - table may not exist
236: }
237: }
238:
239: public void update(PreparedStatement prep, String log)
240: throws Exception {
241: test.log(log);
242: prep.executeUpdate();
243: executedStatements++;
244: }
245:
246: public void update(String sql) throws Exception {
247: sql = getSQL(sql);
248: if (sql.trim().length() > 0) {
249: executedStatements++;
250: stat.execute(sql);
251: } else {
252: System.out.println("?");
253: }
254: }
255:
256: public void setAutoCommit(boolean b) throws Exception {
257: conn.setAutoCommit(b);
258: }
259:
260: public void commit() throws Exception {
261: conn.commit();
262: }
263:
264: public void rollback() throws Exception {
265: conn.rollback();
266: }
267:
268: void trace(String action, int i, int max) {
269: if (trace) {
270: long time = System.currentTimeMillis();
271: if (i == 0 || lastTrace == 0) {
272: lastTrace = time;
273: } else if (time > lastTrace + 1000) {
274: System.out.println(action + ": "
275: + ((100 * i / max) + "%"));
276: lastTrace = time;
277: }
278: }
279: }
280:
281: void logMemory(Bench bench, String action) {
282: log(bench.getName() + ": " + action, "MB", TestBase
283: .getMemoryUsed());
284: }
285:
286: void log(String action, String scale, int value) {
287: if (test.collect) {
288: results.add(new Object[] { action, scale,
289: new Integer(value) });
290: }
291: }
292:
293: public ResultSet query(PreparedStatement prep) throws Exception {
294: // long time = System.currentTimeMillis();
295: ResultSet rs = prep.executeQuery();
296: // time = System.currentTimeMillis() - time;
297: // if(time > 100) {
298: // System.out.println("time="+time);
299: // }
300: executedStatements++;
301: return rs;
302: }
303:
304: public void queryReadResult(PreparedStatement prep)
305: throws Exception {
306: ResultSet rs = prep.executeQuery();
307: ResultSetMetaData meta = rs.getMetaData();
308: int columnCount = meta.getColumnCount();
309: while (rs.next()) {
310: for (int i = 0; i < columnCount; i++) {
311: rs.getString(i + 1);
312: }
313: }
314: }
315:
316: int getExecutedStatements() {
317: return executedStatements;
318: }
319:
320: public int getId() {
321: return id;
322: }
323:
324: public Connection getCurrentConnection() {
325: return conn;
326: }
327:
328: }
|