KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > openharmonise > commons > dsi > impl > DataStoreInterfaceSQLServer


1 /*
2  * The contents of this file are subject to the
3  * Mozilla Public License Version 1.1 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at http://www.mozilla.org/MPL/
6  *
7  * Software distributed under the License is distributed on an "AS IS"
8  * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied.
9  * See the License for the specific language governing rights and
10  * limitations under the License.
11  *
12  * The Initial Developer of the Original Code is Simulacra Media Ltd.
13  * Portions created by Simulacra Media Ltd are Copyright (C) Simulacra Media Ltd, 2004.
14  *
15  * All Rights Reserved.
16  *
17  * Contributor(s):
18  */

19 package org.openharmonise.commons.dsi.impl;
20
21 import java.io.*;
22 import java.sql.*;
23 import java.text.*;
24 import java.util.*;
25 import java.util.Date JavaDoc;
26 import java.util.logging.*;
27 import java.util.logging.Level JavaDoc;
28
29 import org.openharmonise.commons.dsi.*;
30 import org.openharmonise.commons.dsi.ddl.*;
31 import org.openharmonise.commons.dsi.dml.*;
32 import org.openharmonise.commons.dsi.dml.functions.*;
33
34
35
36 /**
37   * Class providing interface to a MS SQLServer database.
38   *
39   * @author Michael Bell
40   *
41   * @see java.sql
42   */

43 public class DataStoreInterfaceSQLServer extends AbstractDataStoreInterface {
44     
45     private static final String JavaDoc TYPE_NTEXT = "NTEXT";
46     private static final String JavaDoc TYPE_NVARCHAR_255 = "NVARCHAR (255)";
47     private static final String JavaDoc TYPE_INT = "INT";
48     private static final String JavaDoc KEYWORD_PRIMARY_KEY = "PRIMARY KEY";
49     private static final String JavaDoc KEYWORD_UNIQUE = "UNIQUE";
50     private static final String JavaDoc KEYWORD_DEFAULT = "DEFAULT";
51     private static final String JavaDoc KEYWORD_NOT_NULL = "NOT NULL";
52     private static final String JavaDoc KEYWORD_FOREIGN_KEY = "FOREIGN KEY";
53     private static final String JavaDoc KEYWORD_REFERENCES = "REFERENCES";
54     
55     public static Date JavaDoc SQLSERVER_CONVERSION_DATE_LIMIT = null;
56     
57     /**
58      * Logger for this class
59      */

60     private static final Logger m_logger = Logger.getLogger(DataStoreInterfaceSQLServer.class.getName());
61     
62     //static initialiser block
63
static {
64         String JavaDoc date_format = "MM-dd-yyyy";
65         SimpleDateFormat format = new SimpleDateFormat(date_format);
66         
67         try {
68             SQLSERVER_CONVERSION_DATE_LIMIT = format.parse("01-01-1753");
69         } catch (ParseException e) {
70             m_logger.log(Level.WARNING, e.getLocalizedMessage(), e);
71         }
72         m_bIsNationalCharacterSupported = true;
73     }
74     
75     /**
76       * Constructs a SQLServer data store interface with no DB settings.
77       */

78     public DataStoreInterfaceSQLServer() {
79     }
80
81     /**
82     * Constructs a SQLServer data store interface with the given connection
83     * type.
84     *
85     * @param nConnectionType the connection type
86     * @throws DataStoreException if any errors occur
87     */

88     public DataStoreInterfaceSQLServer(int nConnectionType)
89                                 throws Exception JavaDoc {
90         super(nConnectionType);
91     }
92
93
94     /* (non-Javadoc)
95      * @see org.openharmonise.commons.dsi.AbstractDataStoreInterface#getSequenceNextValue(java.lang.String)
96      */

97     public int getSequenceNextValue(String JavaDoc sSeqName) throws DataStoreException,
98                                                             SQLException {
99         Connection conn = null;
100         ResultSet rs = null;
101         Statement stmt = null;
102         String JavaDoc sSql = null;
103         int nSeq = -1;
104
105         conn = getConnection();
106
107
108         stmt = conn.createStatement();
109
110         sSql = "UPDATE oh_seq SET id = id +1 WHERE seq_name='" + sSeqName +
111                "'";
112         stmt.executeUpdate(sSql);
113
114         sSql = "SELECT id from oh_seq WHERE seq_name='" + sSeqName + "'";
115         rs = stmt.executeQuery(sSql);
116
117         if (rs.next()) {
118             nSeq = rs.getInt(1);
119         } else {
120             throw new DataStoreException("Sequence [" + sSeqName +
121                                          "] not found.");
122         }
123
124         if (rs != null) {
125             rs.close();
126         }
127
128         if (stmt != null) {
129             stmt.close();
130         }
131
132         if (isPooledConnection() && (conn != null)) {
133             this.closeConnection(conn);
134         }
135
136         return nSeq;
137     }
138
139
140     /* (non-Javadoc)
141      * @see org.openharmonise.commons.dsi.AbstractDataStoreInterface#insertClob(java.lang.String, java.lang.String, java.lang.String, java.lang.String)
142      */

143     public void insertClob(String JavaDoc sTable, String JavaDoc sColumn, String JavaDoc sClob,
144                            String JavaDoc sCondition) throws DataStoreException {
145         Connection conn = null;
146         Statement stmt = null;
147         ResultSet rs = null;
148
149         if ((sCondition == null) || (sCondition.length() == 0)) {
150             throw new DataStoreException("Missing CLOB condition");
151         }
152
153         StringBuffer JavaDoc sSql = new StringBuffer JavaDoc();
154
155         try {
156             conn = getConnection();
157             stmt = conn.createStatement();
158
159             sSql.append("update ");
160             sSql.append(sTable);
161             sSql.append(" set ");
162             sSql.append(sColumn);
163             sSql.append(" = N'");
164             sSql.append(addEscapeChars(sClob));
165             sSql.append("' where ");
166             sSql.append(sCondition);
167
168             stmt.execute(sSql.toString());
169
170             if (isPooledConnection() && (conn != null)) {
171                 this.closeConnection(conn);
172             }
173         } catch (SQLException e) {
174             throw new DataStoreException("SQLException: " + e.getMessage());
175         }
176     }
177
178
179     /* (non-Javadoc)
180      * @see org.openharmonise.commons.dsi.AbstractDataStoreInterface#updateClob(java.lang.String, java.lang.String, java.lang.String, java.lang.String)
181      */

182     public void updateClob(String JavaDoc sTable, String JavaDoc sColumn, String JavaDoc sClob,
183                            String JavaDoc sCondition) throws DataStoreException {
184         Connection conn = null;
185         Statement stmt = null;
186         ResultSet rs = null;
187
188         if ((sCondition == null) || (sCondition.length() == 0)) {
189             throw new DataStoreException("Missing CLOB condition");
190         }
191
192         StringBuffer JavaDoc sSql = new StringBuffer JavaDoc();
193
194         try {
195             conn = getConnection();
196             stmt = conn.createStatement();
197
198             sSql.append("update ");
199             sSql.append(sTable);
200             sSql.append(" set ");
201             sSql.append(sColumn);
202             sSql.append(" = N'");
203             sSql.append(addEscapeChars(sClob));
204             sSql.append("' where ");
205             sSql.append(sCondition);
206
207             stmt.execute(sSql.toString());
208
209             if (stmt != null) {
210                 stmt.close();
211             }
212
213             if (rs != null) {
214                 rs.close();
215             }
216
217             if (isPooledConnection() && (conn != null)) {
218                 this.closeConnection(conn);
219             }
220         } catch (SQLException e) {
221             throw new DataStoreException("SQLException: " + e.getMessage());
222         }
223     }
224
225     /* (non-Javadoc)
226      * @see org.openharmonise.commons.dsi.AbstractDataStoreInterface#getClob(java.lang.String, java.lang.String, java.lang.String)
227      */

228     public String JavaDoc getClob(String JavaDoc sTable, String JavaDoc sColumn, String JavaDoc sCondition)
229                    throws DataStoreException {
230         Connection conn = null;
231         Statement stmt = null;
232         ResultSet rs = null;
233         String JavaDoc sReturn = null;
234
235         if ((sCondition == null) || (sCondition.length() == 0)) {
236             throw new DataStoreException("Missing CLOB condition");
237         }
238
239         StringBuffer JavaDoc sSql = new StringBuffer JavaDoc();
240
241         try {
242             conn = getConnection();
243
244
245             stmt = conn.createStatement();
246
247             sSql.append("select ");
248             sSql.append(sColumn);
249             sSql.append(" from ");
250             sSql.append(sTable);
251             sSql.append(" where ");
252             sSql.append(sCondition);
253
254             try {
255                 rs = stmt.executeQuery(sSql.toString());
256             } catch (SQLException e) {
257                 throw new DataStoreException(sSql.toString() + " : " +
258                                              e.getMessage());
259             }
260
261             if (rs.next()) {
262                 Reader is = rs.getCharacterStream(1);
263                 BufferedReader buffR = new BufferedReader(is);
264                 
265                 StringBuffer JavaDoc sBuffContent = new StringBuffer JavaDoc();
266                 String JavaDoc sTemp = buffR.readLine();
267                             
268                 while(sTemp!=null) {
269                     sBuffContent.append(sTemp);
270                     sTemp = buffR.readLine();
271                 }
272                 sReturn = sBuffContent.toString();
273             }
274
275             if (stmt != null) {
276                 stmt.close();
277             }
278
279             if (rs != null) {
280                 rs.close();
281             }
282
283             if (isPooledConnection() && (conn != null)) {
284                 this.closeConnection(conn);
285             }
286         } catch (SQLException e) {
287             throw new DataStoreException("SQLException",e);
288         } catch (UnsupportedEncodingException e) {
289             m_logger.log(Level.WARNING, e.getLocalizedMessage(), e);
290         } catch (IOException e) {
291             m_logger.log(Level.WARNING, e.getLocalizedMessage(), e);
292         }
293
294         return sReturn;
295     }
296
297
298     /* (non-Javadoc)
299      * @see org.openharmonise.commons.dsi.AbstractDataStoreInterface#addEscapeChars(java.lang.String)
300      */

301     protected String JavaDoc addEscapeChars(String JavaDoc sOldString) {
302         int marker = -1;
303         int lastmarker = 0;
304         int quotemarker = -1;
305
306         if (sOldString == null) {
307             return "";
308         }
309
310         StringBuffer JavaDoc sBuf = new StringBuffer JavaDoc();
311
312         quotemarker = sOldString.indexOf("'");
313
314         if (quotemarker >= 0) {
315             marker = quotemarker;
316         }
317
318         if (marker < 0) {
319             return sOldString;
320         } else {
321             while (marker >= 0) {
322                 //append to stringbuffer
323
sBuf.append(sOldString.substring(lastmarker, marker));
324                 sBuf.append("'");
325
326
327                 //reset markers
328
quotemarker = -1;
329                 lastmarker = marker;
330
331                 quotemarker = sOldString.indexOf("'", marker + 1);
332
333                 if (quotemarker >= 0) {
334                     marker = quotemarker;
335                 } else {
336                     marker = -1;
337                 }
338             }
339
340             sBuf.append(sOldString.substring(lastmarker));
341
342             return (sBuf.toString());
343         }
344     }
345
346     /* (non-Javadoc)
347      * @see org.openharmonise.commons.dsi.AbstractDataStoreInterface#getDateDataType()
348      */

349     public String JavaDoc getDateDataType() {
350         return "DATETIME";
351     }
352
353     /* (non-Javadoc)
354      * @see org.openharmonise.commons.dsi.AbstractDataStoreInterface#getCLOBDataType()
355      */

356     public String JavaDoc getCLOBDataType() {
357         return TYPE_NTEXT;
358     }
359
360     /* (non-Javadoc)
361      * @see org.openharmonise.commons.dsi.AbstractDataStoreInterface#getBooleanDataType()
362      */

363     public String JavaDoc getBooleanDataType() {
364         return "BIT";
365     }
366
367     /* (non-Javadoc)
368      * @see org.openharmonise.commons.dsi.AbstractDataStoreInterface#getTableList()
369      */

370     public List getTableList() throws DataStoreException {
371         Vector tables = new Vector();
372         ResultSet rs = null;
373
374         try {
375             rs = executeQuery(
376                          "select name from sysobjects where type = 'u' and name != 'dtproperties' order by name");
377             
378             while (rs.next()) {
379                 tables.add(rs.getString(1).trim());
380             }
381             
382             rs.close();
383         } catch (SQLException e) {
384             throw new DataStoreException(e);
385         }
386
387         return tables;
388     }
389
390     /* (non-Javadoc)
391      * @see org.openharmonise.commons.dsi.AbstractDataStoreInterface#getSequenceList()
392      */

393     public List getSequenceList() throws DataStoreException {
394         Vector seqs = new Vector();
395         ResultSet rs = null;
396
397         try {
398             rs = executeQuery("select seq_name from oh_seq order by seq_name");
399             
400             while (rs.next()) {
401                 seqs.add(rs.getString(1).trim());
402             }
403             
404             rs.close();
405         } catch (SQLException e) {
406             throw new DataStoreException(e);
407         }
408
409         return seqs;
410     }
411
412     /* (non-Javadoc)
413      * @see org.openharmonise.commons.dsi.AbstractDataStoreInterface#getDateAsSQL(java.lang.String)
414      */

415     protected String JavaDoc getDateAsSQL(String JavaDoc date) {
416         // localise this, as it is different for different DB implementations,
417
// SQL Server
418
StringBuffer JavaDoc sSql = new StringBuffer JavaDoc();
419
420         sSql.append(" CONVERT(datetime, '");
421         sSql.append(date);
422         sSql.append("', 120 )");
423
424         return sSql.toString();
425     }
426
427     /* (non-Javadoc)
428      * @see org.openharmonise.commons.dsi.AbstractDataStoreInterface#getJoinCondition(org.openharmonise.commons.dsi.ColumnRef, org.openharmonise.commons.dsi.ColumnRef, boolean)
429      */

430     public String JavaDoc getJoinCondition(ColumnRef ref1, ColumnRef ref2,
431                                    boolean bIsOuter) {
432         StringBuffer JavaDoc sSql = new StringBuffer JavaDoc();
433
434         sSql.append(ref1.getFullRef());
435         sSql.append("=");
436
437         if (bIsOuter == true) {
438             sSql.append("*");
439         }
440
441         sSql.append(ref2.getFullRef());
442
443         return sSql.toString();
444     }
445
446     /* (non-Javadoc)
447      * @see org.openharmonise.commons.dsi.AbstractDataStoreInterface#getFunction(org.openharmonise.commons.dsi.dml.Function)
448      */

449     protected String JavaDoc getFunction(Function func) throws DataStoreException {
450         
451         
452         String JavaDoc sFunc = null;
453         
454         if(func instanceof Substring) {
455             sFunc = getSubstring((Substring) func);
456             
457         } else if(func instanceof Length) {
458             sFunc = getLength((Length) func);
459                 
460         } else if(func instanceof ToDate) {
461             sFunc = getToDate((ToDate) func);
462                     
463         } else {
464             throw new DataStoreException("Function not supported - " + func.getClass().getName());
465         }
466         
467         return sFunc;
468     }
469     
470
471     /**
472      * Returns the SQL 'todate' statement for the given
473      * <code>ToDate</code> <code>Function</code>.
474      *
475      * @param date the function
476      * @return the SQL 'todate' statement
477      */

478     private String JavaDoc getToDate(ToDate date) {
479         StringBuffer JavaDoc strbuf = new StringBuffer JavaDoc();
480         
481         strbuf.append("CONVERT(datetime,");
482         
483         Object JavaDoc objVal = date.getValue();
484         
485         if(objVal instanceof ColumnRef) {
486             strbuf.append(((ColumnRef)objVal).getFullRef());
487         } else if(objVal instanceof String JavaDoc) {
488             strbuf.append("'").append(objVal).append("'");
489         }
490         
491         strbuf.append(", 120 )");
492         return strbuf.toString();
493     }
494
495     /**
496      * Returns the SQL 'substring' statement from the given
497      * <code>Substring</code> <code>Function</code>.
498      *
499      * @param substr the substring <code>Function</code>
500      * @return the SQL 'substring' statement
501      * @throws DataStoreException if an error occurs
502      */

503     private String JavaDoc getSubstring(Substring substr) throws DataStoreException {
504             
505         StringBuffer JavaDoc strbuf = new StringBuffer JavaDoc();
506
507         strbuf.append("SUBSTRING('").append(substr.getString()).append("',");
508
509         Object JavaDoc objStart = substr.getStart();
510
511         if(objStart instanceof Integer JavaDoc) {
512             strbuf.append(((Integer JavaDoc)objStart).toString());
513         } else if(objStart instanceof String JavaDoc) {
514             strbuf.append((String JavaDoc)objStart);
515         } else if(objStart instanceof Function) {
516             strbuf.append(getFunction((Function)objStart));
517         }
518
519         strbuf.append(",");
520
521         Object JavaDoc objEnd = substr.getFinish();
522
523         if(objEnd instanceof Integer JavaDoc) {
524             strbuf.append(((Integer JavaDoc)objEnd).toString());
525         } else if(objEnd instanceof String JavaDoc) {
526             strbuf.append((String JavaDoc)objEnd);
527         } else if(objEnd instanceof Function) {
528             strbuf.append(getFunction((Function)objEnd));
529         }
530
531         strbuf.append(")");
532
533         return strbuf.toString();
534     }
535     
536     /**
537      * Returns the SQL 'length' statement from the given
538      * <code>Length</code> <code>Function</code>.
539      *
540      * @param func the length function
541      * @return the SQL 'length' statement
542      * @throws DataStoreException if an error occurs
543      */

544     private String JavaDoc getLength(Length func) throws DataStoreException {
545         StringBuffer JavaDoc strbuf = new StringBuffer JavaDoc();
546         
547         strbuf.append("LEN(");
548         
549         Object JavaDoc lenObj = func.getLengthObject();
550         
551         if(lenObj instanceof String JavaDoc) {
552             strbuf.append(lenObj);
553         } else if(lenObj instanceof ColumnRef) {
554             strbuf.append(((ColumnRef)lenObj).getFullRef());
555         }
556         
557         strbuf.append(")");
558         
559         return strbuf.toString();
560     }
561
562     /* (non-Javadoc)
563      * @see org.openharmonise.commons.dsi.AbstractDataStoreInterface#createTable(org.openharmonise.commons.dsi.ddl.TableDefinition)
564      */

565     public void createTable(TableDefinition tblDef) throws DataStoreException {
566         StringBuffer JavaDoc str = new StringBuffer JavaDoc();
567         
568         str.append("create table ")
569             .append(tblDef.getName());
570         str.append(" (");
571         
572         Iterator iter = tblDef.iterator();
573         
574         while (iter.hasNext()) {
575             ColumnDefinition coldef = (ColumnDefinition) iter.next();
576             
577             str.append(coldef.getName());
578             str.append(" ");
579             int nDataType = coldef.getDataType();
580             
581             if(nDataType == ColumnDefinition.NUMBER) {
582                 str.append(TYPE_INT);
583             } else if(nDataType == ColumnDefinition.TEXT) {
584                 str.append(TYPE_NVARCHAR_255);
585             } else if(nDataType == ColumnDefinition.LONG_TEXT) {
586                 str.append(TYPE_NTEXT);
587             } else if(nDataType == ColumnDefinition.DATE) {
588                 str.append(getDateDataType());
589             } else if(nDataType == ColumnDefinition.BOOLEAN) {
590                 str.append(getBooleanDataType());
591             }
592             
593             
594             
595             if(coldef.isPrimaryKey()) {
596                 str.append(" ").append(KEYWORD_PRIMARY_KEY);
597             } else if(coldef.isUnique()) {
598                 str.append(" ").append(KEYWORD_UNIQUE);
599             }
600             
601             Object JavaDoc defaultVal = coldef.getDefault();
602             
603             if(defaultVal != null) {
604                 
605                 str.append(" ").append(KEYWORD_DEFAULT).append(" ");
606                 
607                 if(defaultVal instanceof String JavaDoc && (nDataType == ColumnDefinition.TEXT
608                             || nDataType == ColumnDefinition.LONG_TEXT)) {
609                     str.append(defaultVal);
610                 } else if(defaultVal instanceof Date JavaDoc) {
611                     
612                 } else if(defaultVal instanceof Integer JavaDoc) {
613                     str.append(((Integer JavaDoc)defaultVal).intValue());
614                 }
615             }
616             
617             if(coldef.allowNulls() == false) {
618                 str.append(" ").append(KEYWORD_NOT_NULL);
619             }
620             
621             if(coldef.isForeignKey()) {
622                 str.append(" ").append(KEYWORD_FOREIGN_KEY)
623                     .append(" ").append(KEYWORD_REFERENCES)
624                     .append(" ").append(coldef.getForeignKeyReference());
625             }
626             
627             if(iter.hasNext()) {
628                 str.append(",");
629             }
630         }
631         
632         str.append(")");
633         
634         execute(str.toString());
635         
636     }
637
638 }
Popular Tags