ef233fbb80db81aad07b04b1d18e405d87680a25
[phpeclipse.git] / archive / net.sourceforge.phpeclipse.quantum.sql / src / com / quantum / sql / MultiSQLServer.java
1 package com.quantum.sql;
2
3 import java.io.ByteArrayOutputStream;
4 import java.io.InputStream;
5 import java.io.Reader;
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;
16
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;
27
28
29 /**
30  * MultiSQLServer is a Singleton, used  as a interface with the sql drivers.
31  * Use MultiSQLServer.getInstance() to get the object.
32  */
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;
39
40     private MultiSQLServer() {
41     }
42     public synchronized static MultiSQLServer getInstance() {
43         if (instance == null) {
44             instance = new MultiSQLServer();
45         }
46         return instance;
47     }
48
49     public void commit(Connection con) {
50         LogProxy log = LogProxy.getInstance();
51         try {
52             con.commit();
53         } catch (SQLException e) {
54             log.addText(LogProxy.ERROR, "Error commiting: " + e, e); //$NON-NLS-1$
55         }
56     }
57
58     public void rollback(Connection con) {
59         LogProxy log = LogProxy.getInstance();
60         try {
61             con.rollback();
62         } catch (SQLException e) {
63             log.addText(LogProxy.ERROR, "Error rolling back: " + e, e); //$NON-NLS-1$
64         }
65     }
66
67     public void setAutoCommit(Connection con, boolean enabled) {
68         LogProxy log = LogProxy.getInstance();
69         try {
70             if (con != null) {
71                 con.setAutoCommit(enabled);
72             } else {
73                 log.addText(LogProxy.ERROR, "Please connect before setting autocommit"); //$NON-NLS-1$
74             }
75         } catch (SQLException e) {
76             log.addText(LogProxy.ERROR, "Error setting autocommit: " + e, e); //$NON-NLS-1$
77         }
78     }
79
80     public void disconnect(Connection connection) throws ConnectionException {
81         try {
82             if (connection != null) {
83                 connection.close();
84             }
85         } catch (SQLException e) {
86             throw new ConnectionException(e);
87         }
88     }
89
90     /**
91      * Makes a connection to a JDBC driver based on the data from a bookmark
92      * @param 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 
96      *     include a password
97      * @return The Connection object if everything went OK
98      */
99     public Connection connect(Bookmark bookmark, PasswordFinder passwordFinder)
100         throws ConnectionException {
101
102         String password = bookmark.getPassword();
103         if (bookmark.getPromptForPassword()) {
104             password = passwordFinder.getPassword();
105             if (passwordFinder.isPasswordMeantToBeSaved()) {
106                 bookmark.setPassword(password);
107             }
108         }
109         
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());
117             }
118                 return connection;
119         } else {
120             return null;
121         }
122         
123     }
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$
128         try {
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);
136                     connection =
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$
140                     }
141                     
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$
147             }
148             return connection;
149         } catch (SQLException e) {
150             throw new ConnectionException(e);
151         }
152     }
153         public SQLResults execute(Connection con, String s) throws SQLException {
154                 return execute(con, s, -1, -1);
155         }
156         public SQLResults execute(Connection con, String s, int startRow, int endRow) throws SQLException {
157                 return execute(con, s, -1, -1, Integer.MAX_VALUE);
158         }
159
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$
162         }
163         
164         public SQLResults execute(
165                 Connection con,
166                 String s,
167                 int startRow,
168                 int endRow,
169                 int maxLength,
170                 String encoding)
171                 throws SQLException {
172
173                 SQLResults results = new SQLResults();
174
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$
180                         metadata = true;
181                 }
182                 if (metadata) {
183                         results.setQuery(s);
184                         String table = s.substring(s.indexOf(':') + 1);
185                         String query = "SELECT * FROM " + table + " WHERE (1 = 0)"; //$NON-NLS-1$ //$NON-NLS-2$
186                         s = query;
187                         log.addText(LogProxy.QUERY, "Metadata Request [" + s + "]"); //$NON-NLS-1$ //$NON-NLS-2$
188                 } else {
189                         results.setQuery(s);
190                 }
191
192                 Statement stmt = con.createStatement();
193                 boolean flag = stmt.execute(s);
194                 results.setResultSet(flag);
195                 if (metadata) {
196                         genMetadataResultSet(results, stmt);
197                         return results;
198                 }
199                 if (!flag) {
200                         int updates = stmt.getUpdateCount();
201                         results.setUpdateCount(updates);
202                         log.addText(LogProxy.RESULTS, "Success: " + updates + " records updated"); //$NON-NLS-1$ //$NON-NLS-2$
203
204                 } else {
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));
211                         }
212                         results.setColumnNames(columnNames);
213                         Vector columnTypes = new Vector();
214                         for (int i = 1; i <= columnCount; i++) {
215                                 columnTypes.addElement(metaData.getColumnTypeName(i));
216                         }
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);
221                         }
222                         int rowCount = 1;
223                         boolean exitEarly = false;
224                         while (set.next()) {
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++) {
231                                                 String value;
232                                                 if (columnSizes[i - 1] < STREAM
233                                                         && columnSizes[i - 1] < maxLength) {
234                                                         if (encoding.equals("")) { //$NON-NLS-1$
235                                                                 value = set.getString(i);
236                                                         } else {
237                                                                 try {
238                                                                         value =
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));
243                                                                 }
244                                                         }
245                                                 } else {
246                                                         try {
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();
252                                                                                 int count = 0;
253                                                                                 while (retVal >= 0) {
254                                                                                         buffer.append((char) retVal);
255                                                                                         retVal = reader.read();
256                                                                                         count++;
257                                                                                         if (count > maxLength) {
258                                                                                                 buffer.append("...>>>"); //$NON-NLS-1$
259                                                                                                 break;
260                                                                                         }
261                                                                                 }
262                                                                                 reader.close();
263                                                                         }
264                                                                         value = buffer.toString();
265                                                                 } else {
266                                                                         InputStream binaryStream =
267                                                                                 set.getBinaryStream(i);
268                                                                         ByteArrayOutputStream baos =
269                                                                                 new ByteArrayOutputStream();
270                                                                         if (binaryStream != null) {
271                                                                                 int retVal = binaryStream.read();
272                                                                                 int count = 0;
273                                                                                 while (retVal >= 0) {
274                                                                                         baos.write(retVal);
275                                                                                         retVal = binaryStream.read();
276                                                                                         count++;
277                                                                                         if (count > maxLength) {
278                                                                                                 break;
279                                                                                         }
280                                                                                 }
281                                                                                 binaryStream.close();
282                                                                         }
283                                                                         value =
284                                                                                 new String(
285                                                                                         baos.toByteArray(),
286                                                                                         encoding);
287                                                                 }
288                                                         } catch (Throwable e) {
289                                                                 // hack for mysql which doesn't implement
290                                                                 // character streams
291                                                                 value = set.getString(i);
292                                                         }
293                                                 }
294                                                 if (set.wasNull()) {
295                                                         row.addElement("<NULL>"); //$NON-NLS-1$
296                                                 } else {
297                                                         row.addElement(value);
298                                                 }
299                                         }
300                                         results.addRow(row);
301                                 }
302                                 rowCount++;
303                                 if (!disable && (rowCount > endRow)) {
304                                         exitEarly = true;
305                                         break;
306                                 }
307                         }
308                         if (exitEarly) {
309                                 results.setHasMore(set.next());
310                         } else {
311                                 results.setMaxSize(rowCount);
312                                 results.setHasMore(false);
313                         }
314                         set.close();
315                 }
316                 log.addText(LogProxy.RESULTS, "Success: result set displayed"); //$NON-NLS-1$
317                 stmt.close();
318                 System.out.println("Executed"); //$NON-NLS-1$
319                 System.out.println();
320                 return results;
321         }
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));
343                         } else {
344                                 row.addElement(textSize + ", " + precision + ", " + scale); //$NON-NLS-1$ //$NON-NLS-2$
345                         }
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$
351                         } else if (
352                                 nullable == ResultSetMetaData.columnNullableUnknown) {
353                                 row.addElement("Nullable"); //$NON-NLS-1$
354                         } else {
355                                 row.addElement("<Error>"); //$NON-NLS-1$
356                         }
357                         row.addElement(
358                                 (metaData.isAutoIncrement(i)
359                                         ? Boolean.TRUE
360                                         : Boolean.FALSE)
361                                         .toString());
362                         results.addRow(row);
363                 }
364                 results.setHasMore(false);
365                 set.close();
366         }
367
368         /**
369          * Returns an ObjectMetadata object got from the connection 'con' using the name and schema of the node.
370          * @param con
371          * @param node
372          * @return
373          * @throws SQLException
374          */
375         public ObjectMetaData getObjectMetadata(Connection con, TreeNode node) throws SQLException {
376                 ObjectMetaData metadata = new ObjectMetaData();
377                 if (!(node instanceof Entity)) return metadata;
378                 
379                 String schema = ((Entity)node).getSchema();
380                 String tableName = node.getName();
381                 
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));
389                 }
390                 return metadata;
391         }
392         
393 }