1 package com.quantum.sql;
3 import java.io.ByteArrayOutputStream;
4 import java.io.InputStream;
6 import java.io.UnsupportedEncodingException;
7 import java.sql.Connection;
8 import java.sql.DatabaseMetaData;
9 import java.sql.Driver;
10 import java.sql.ResultSet;
11 import java.sql.ResultSetMetaData;
12 import java.sql.SQLException;
13 import java.sql.Statement;
14 import java.util.Properties;
15 import java.util.Vector;
17 import com.quantum.model.Bookmark;
18 import com.quantum.model.ConnectionException;
19 import com.quantum.model.Entity;
20 import com.quantum.model.JDBCDriver;
21 import com.quantum.model.PasswordFinder;
22 import com.quantum.sql.metadata.MetaDataJDBCInterface;
23 import com.quantum.sql.metadata.ObjectMetaData;
24 import com.quantum.view.LogProxy;
25 import com.quantum.view.bookmark.EntityNode;
26 import com.quantum.view.bookmark.TreeNode;
30 * MultiSQLServer is a Singleton, used as a interface with the sql drivers.
31 * Use MultiSQLServer.getInstance() to get the object.
33 public class MultiSQLServer implements ConnectionEstablisher {
34 private static final int STREAM = 1024 * 2;
35 public static final String USERNAME = "user"; //$NON-NLS-1$
36 public static final String PASSWORD = "password"; //$NON-NLS-1$
37 private static MultiSQLServer instance = null;
38 boolean running = true;
40 private MultiSQLServer() {
42 public synchronized static MultiSQLServer getInstance() {
43 if (instance == null) {
44 instance = new MultiSQLServer();
49 public void commit(Connection con) {
50 LogProxy log = LogProxy.getInstance();
53 } catch (SQLException e) {
54 log.addText(LogProxy.ERROR, "Error commiting: " + e, e); //$NON-NLS-1$
58 public void rollback(Connection con) {
59 LogProxy log = LogProxy.getInstance();
62 } catch (SQLException e) {
63 log.addText(LogProxy.ERROR, "Error rolling back: " + e, e); //$NON-NLS-1$
67 public void setAutoCommit(Connection con, boolean enabled) {
68 LogProxy log = LogProxy.getInstance();
71 con.setAutoCommit(enabled);
73 log.addText(LogProxy.ERROR, "Please connect before setting autocommit"); //$NON-NLS-1$
75 } catch (SQLException e) {
76 log.addText(LogProxy.ERROR, "Error setting autocommit: " + e, e); //$NON-NLS-1$
80 public void disconnect(Connection connection) throws ConnectionException {
82 if (connection != null) {
85 } catch (SQLException e) {
86 throw new ConnectionException(e);
91 * Makes a connection to a JDBC driver based on the data from a bookmark
93 * The Bookmark with the data needed to make the connection
94 * @param passwordFinder -
95 * A utility class that can be invoked if the bookmark does not
97 * @return The Connection object if everything went OK
99 public Connection connect(Bookmark bookmark, PasswordFinder passwordFinder)
100 throws ConnectionException {
102 String password = bookmark.getPassword();
103 if (bookmark.getPromptForPassword()) {
104 password = passwordFinder.getPassword();
105 if (passwordFinder.isPasswordMeantToBeSaved()) {
106 bookmark.setPassword(password);
110 if (password != null) {
111 Connection connection = connect(bookmark, password);
112 if (connection != null) {
113 // Set the autoCommit state of the bookmark to the default on new connections
114 bookmark.setAutoCommit(bookmark.getDefaultAutoCommit());
115 // Set the autoCommit state of the JDBC connection to the bookmark autoCommit statec
116 setAutoCommit(connection, bookmark.isAutoCommit());
124 private Connection connect(Bookmark bookmark, String password)
125 throws ConnectionException {
126 LogProxy log = LogProxy.getInstance();
127 log.addText(LogProxy.QUERY, "Connecting to: " + bookmark.getName()); //$NON-NLS-1$
129 JDBCDriver jdbcDriver = bookmark.getJDBCDriver();
130 Driver driver = jdbcDriver.getDriver();
131 Connection connection = null;
132 if (driver != null) {
133 Properties props = new Properties();
134 props.put(USERNAME, bookmark.getUsername());
135 props.put(PASSWORD, password);
137 driver.connect(bookmark.getConnect(), props);
138 if (connection == null) {
139 throw new ConnectionException("Error: Driver returned a null connection: " + bookmark.toString()); //$NON-NLS-1$
142 DatabaseMetaData metaData = connection.getMetaData();
143 jdbcDriver.setName(metaData.getDriverName());
144 jdbcDriver.setVersion(metaData.getDriverVersion());
145 log.addText(LogProxy.RESULTS, "Connected to: " + bookmark.getName()); //$NON-NLS-1$
146 System.out.println("Connected"); //$NON-NLS-1$
149 } catch (SQLException e) {
150 throw new ConnectionException(e);
153 public SQLResults execute(Connection con, String s) throws SQLException {
154 return execute(con, s, -1, -1);
156 public SQLResults execute(Connection con, String s, int startRow, int endRow) throws SQLException {
157 return execute(con, s, -1, -1, Integer.MAX_VALUE);
160 public SQLResults execute(Connection con, String s, int startRow, int endRow, int maxLength) throws SQLException {
161 return execute(con, s, startRow, endRow, maxLength, ""); //$NON-NLS-1$
164 public SQLResults execute(
171 throws SQLException {
173 SQLResults results = new SQLResults();
175 System.out.println("Executing"); //$NON-NLS-1$
176 LogProxy log = LogProxy.getInstance();
177 log.addText(LogProxy.QUERY, "Executing Request [" + s + "]"); //$NON-NLS-1$ //$NON-NLS-2$
178 boolean metadata = false;
179 if (s.startsWith("METADATA")) { //$NON-NLS-1$
184 String table = s.substring(s.indexOf(':') + 1);
185 String query = "SELECT * FROM " + table + " WHERE (1 = 0)"; //$NON-NLS-1$ //$NON-NLS-2$
187 log.addText(LogProxy.QUERY, "Metadata Request [" + s + "]"); //$NON-NLS-1$ //$NON-NLS-2$
192 Statement stmt = con.createStatement();
193 boolean flag = stmt.execute(s);
194 results.setResultSet(flag);
196 genMetadataResultSet(results, stmt);
200 int updates = stmt.getUpdateCount();
201 results.setUpdateCount(updates);
202 log.addText(LogProxy.RESULTS, "Success: " + updates + " records updated"); //$NON-NLS-1$ //$NON-NLS-2$
205 ResultSet set = stmt.getResultSet();
206 ResultSetMetaData metaData = set.getMetaData();
207 int columnCount = metaData.getColumnCount();
208 Vector columnNames = new Vector();
209 for (int i = 1; i <= columnCount; i++) {
210 columnNames.addElement(metaData.getColumnName(i));
212 results.setColumnNames(columnNames);
213 Vector columnTypes = new Vector();
214 for (int i = 1; i <= columnCount; i++) {
215 columnTypes.addElement(metaData.getColumnTypeName(i));
217 results.setColumnTypes(columnTypes);
218 int columnSizes[] = new int[columnCount];
219 for (int i = 1; i <= columnCount; i++) {
220 columnSizes[i - 1] = metaData.getColumnDisplaySize(i);
223 boolean exitEarly = false;
225 boolean disable = startRow < 1 || endRow < 1;
226 boolean start = rowCount >= startRow;
227 boolean end = rowCount <= endRow;
228 if (disable || (start && end)) {
229 Vector row = new Vector();
230 for (int i = 1; i <= columnCount; i++) {
232 if (columnSizes[i - 1] < STREAM
233 && columnSizes[i - 1] < maxLength) {
234 if (encoding.equals("")) { //$NON-NLS-1$
235 value = set.getString(i);
239 new String(set.getBytes(i), encoding);
240 } catch (UnsupportedEncodingException e) {
241 log.addText(LogProxy.ERROR, "Error Unsupported encoding " + encoding.toString() + ":" + e.toString(), e); //$NON-NLS-1$ //$NON-NLS-2$
242 value = new String(set.getBytes(i));
247 if (encoding.equals("")) { //$NON-NLS-1$
248 Reader reader = set.getCharacterStream(i);
249 StringBuffer buffer = new StringBuffer();
250 if (reader != null) {
251 int retVal = reader.read();
253 while (retVal >= 0) {
254 buffer.append((char) retVal);
255 retVal = reader.read();
257 if (count > maxLength) {
258 buffer.append("...>>>"); //$NON-NLS-1$
264 value = buffer.toString();
266 InputStream binaryStream =
267 set.getBinaryStream(i);
268 ByteArrayOutputStream baos =
269 new ByteArrayOutputStream();
270 if (binaryStream != null) {
271 int retVal = binaryStream.read();
273 while (retVal >= 0) {
275 retVal = binaryStream.read();
277 if (count > maxLength) {
281 binaryStream.close();
288 } catch (Throwable e) {
289 // hack for mysql which doesn't implement
291 value = set.getString(i);
295 row.addElement("<NULL>"); //$NON-NLS-1$
297 row.addElement(value);
303 if (!disable && (rowCount > endRow)) {
309 results.setHasMore(set.next());
311 results.setMaxSize(rowCount);
312 results.setHasMore(false);
316 log.addText(LogProxy.RESULTS, "Success: result set displayed"); //$NON-NLS-1$
318 System.out.println("Executed"); //$NON-NLS-1$
319 System.out.println();
322 private void genMetadataResultSet(SQLResults results, Statement stmt)
323 throws SQLException {
324 ResultSet set = stmt.getResultSet();
325 ResultSetMetaData metaData = set.getMetaData();
326 int columnCount = metaData.getColumnCount();
327 Vector columnNames = new Vector();
328 columnNames.addElement("ColumnName"); //$NON-NLS-1$
329 columnNames.addElement("Type"); //$NON-NLS-1$
330 columnNames.addElement("Size"); //$NON-NLS-1$
331 columnNames.addElement("Nullable"); //$NON-NLS-1$
332 columnNames.addElement("AutoIncrement"); //$NON-NLS-1$
333 results.setColumnNames(columnNames);
334 for (int i = 1; i <= columnCount; i++) {
335 Vector row = new Vector();
336 row.addElement(metaData.getColumnName(i));
337 row.addElement(metaData.getColumnTypeName(i));
338 int textSize = metaData.getColumnDisplaySize(i);
339 int precision = metaData.getPrecision(i);
340 int scale = metaData.getScale(i);
341 if (scale == 0 && precision == 0) {
342 row.addElement(Integer.toString(precision));
344 row.addElement(textSize + ", " + precision + ", " + scale); //$NON-NLS-1$ //$NON-NLS-2$
346 int nullable = metaData.isNullable(i);
347 if (nullable == ResultSetMetaData.columnNoNulls) {
348 row.addElement("Not Null"); //$NON-NLS-1$
349 } else if (nullable == ResultSetMetaData.columnNullable) {
350 row.addElement("Nullable"); //$NON-NLS-1$
352 nullable == ResultSetMetaData.columnNullableUnknown) {
353 row.addElement("Nullable"); //$NON-NLS-1$
355 row.addElement("<Error>"); //$NON-NLS-1$
358 (metaData.isAutoIncrement(i)
364 results.setHasMore(false);
369 * Returns an ObjectMetadata object got from the connection 'con' using the name and schema of the node.
373 * @throws SQLException
375 public ObjectMetaData getObjectMetadata(Connection con, TreeNode node) throws SQLException {
376 ObjectMetaData metadata = new ObjectMetaData();
377 if (!(node instanceof Entity)) return metadata;
379 String schema = ((Entity)node).getSchema();
380 String tableName = node.getName();
382 if (schema.length() == 0) schema = null;
383 metadata.setColumns(MetaDataJDBCInterface.getColumns(con, schema, tableName));
384 if (node instanceof EntityNode && ((EntityNode) node).isTable()) {
385 metadata.setPrimaryKeys(MetaDataJDBCInterface.getPrimaryKeys(con, schema, tableName));
386 metadata.setForeignKeys(MetaDataJDBCInterface.getForeignKeys(con, schema, tableName, true));
387 metadata.setIndexInfo(MetaDataJDBCInterface.getIndexInfo(con, schema, tableName));
388 metadata.setBestRowId(MetaDataJDBCInterface.getBestRowId(con, schema, tableName));