Statistics
| Revision:

root / branches / v2_0_0_prep / libraries / libFMap_dataDB / src / org / gvsig / fmap / data / datastores / vectorial / db / jdbc / h2 / H2Explorer.java @ 22032

History | View | Annotate | Download (11.8 KB)

1
package org.gvsig.fmap.data.datastores.vectorial.db.jdbc.h2;
2

    
3
import java.security.KeyException;
4
import java.sql.Connection;
5
import java.sql.ResultSet;
6
import java.sql.SQLException;
7
import java.sql.Statement;
8
import java.util.ArrayList;
9
import java.util.List;
10

    
11
import org.gvsig.fmap.data.CloseException;
12
import org.gvsig.fmap.data.DataException;
13
import org.gvsig.fmap.data.DataExplorerParameters;
14
import org.gvsig.fmap.data.DataManager;
15
import org.gvsig.fmap.data.DataStoreParameters;
16
import org.gvsig.fmap.data.InitializeException;
17
import org.gvsig.fmap.data.NewDataStoreParameters;
18
import org.gvsig.fmap.data.ReadException;
19
import org.gvsig.fmap.data.ResourceManager;
20
import org.gvsig.fmap.data.datastores.vectorial.db.DBAttributeDescriptor;
21
import org.gvsig.fmap.data.datastores.vectorial.db.DBFeatureType;
22
import org.gvsig.fmap.data.datastores.vectorial.db.jdbc.JDBCExplorer;
23
import org.gvsig.fmap.data.vectorial.FeatureAttributeDescriptor;
24
import org.gvsig.fmap.data.vectorial.FeatureType;
25
import org.gvsig.fmap.data.vectorial.InitializeWriterException;
26
import org.gvsig.fmap.data.vectorial.NewFeatureStoreParameters;
27

    
28
public class H2Explorer extends JDBCExplorer {
29
        public static String DATAEXPLORER_NAME = "H2Explorer";
30
        private String defaultSchema;
31

    
32
        private void appendFieldToCreteSQL(DBAttributeDescriptor attr,StringBuffer sql) throws InitializeException{
33
                /**
34
                 * {name dataType
35
                        [{AS computedColumnExpression | DEFAULT expression}]
36
                        [[NOT] NULL]
37
                        [{AUTO_INCREMENT | IDENTITY}[(startInt [, incrementInt])]]
38
                        [SELECTIVITY selectivity]
39
                        [PRIMARY KEY [HASH] | UNIQUE]
40
                        | constraint}
41
                 */
42

    
43
                //name
44
                sql.append(attr.getName());
45
                sql.append(" ");
46

    
47
                //dataType
48
                String type =attr.getDataType();
49
                if (type.equals(FeatureAttributeDescriptor.TYPE_STRING)){
50
                        if (attr.getSize() < 1){
51
                                sql.append("VARCHAR");
52
                        } else {
53
                                sql.append("VARCHAR("+attr.getSize()+")");
54
                        }
55
                } else if (type.equals(FeatureAttributeDescriptor.TYPE_BOOLEAN)){
56
                        sql.append("BOOL");
57
                } else if (type.equals(FeatureAttributeDescriptor.TYPE_BYTE)){
58
                        sql.append("TINYINT");
59
                } else if (type.equals(FeatureAttributeDescriptor.TYPE_DATE)){
60
                        sql.append("DATE");
61
                } else if (type.equals(FeatureAttributeDescriptor.TYPE_TIMESTAMP)){
62
                        sql.append("TIMESTAMP");
63
                } else if (type.equals(FeatureAttributeDescriptor.TYPE_TIME)){
64
                        sql.append("TIME");
65
                } else if (type.equals(FeatureAttributeDescriptor.TYPE_DOUBLE)){
66
                        sql.append("DOUBLE");
67
                        if (attr.getPrecision() > 0){
68
                                sql.append(" "+ attr.getPrecision());
69
                        }
70
                } else if (type.equals(FeatureAttributeDescriptor.TYPE_FLOAT)){
71
                        sql.append("REAL");
72
                } else if (type.equals(FeatureAttributeDescriptor.TYPE_GEOMETRY)){
73
                        sql.append("OTHER");
74
                } else if (type.equals(FeatureAttributeDescriptor.TYPE_INT)){
75
                        if (attr.isAutoIncrement()){
76
                                sql.append("IDENTITY");
77
                        }else{
78
                                sql.append("INT");
79
                        }
80
                } else if (type.equals(FeatureAttributeDescriptor.TYPE_LONG)){
81
                        if (attr.isAutoIncrement()){
82
                                sql.append("IDENTITY");
83
                        }else{
84
                                sql.append("BIGINT");
85
                        }
86
                } else {
87
                        throw new InitializeException(this.getName(),new Exception("Unsuported type "+type));
88
                }
89
                sql.append(" ");
90

    
91
//                //DefeaultValue
92
//                if (attr.getDefaultValue() != null || (attr.getDefaultValue() == null && attr.isAllowNull() )){
93
//                        sql.append("DEFAULT ? ");
94
//                        sqlParams.add(attr.getDefaultValue());
95
//
96
//                }
97

    
98
                //Null
99
                if (attr.isAllowNull()){
100
                        sql.append("NOT NULL ");
101
                } else {
102
                        sql.append("NULL ");
103
                }
104

    
105
                //Primery key
106
                if (attr.isPrimaryKey()){
107
                        sql.append("PRIMARY KEY ");
108
                }
109

    
110
        }
111

    
112
        /**
113
         * @deprecated
114
         *
115
         * @param attr
116
         * @param sql
117
         * @param sqlParams
118
         * @throws InitializeException
119
         */
120
        private void appendFieldToCreteSQL(DBAttributeDescriptor attr,StringBuffer sql,List sqlParams) throws InitializeException{
121
                /**
122
                 * {name dataType
123
                        [{AS computedColumnExpression | DEFAULT expression}]
124
                        [[NOT] NULL]
125
                        [{AUTO_INCREMENT | IDENTITY}[(startInt [, incrementInt])]]
126
                        [SELECTIVITY selectivity]
127
                        [PRIMARY KEY [HASH] | UNIQUE]
128
                        | constraint}
129
                 */
130

    
131
                //name
132
                sql.append(attr.getName());
133
                sql.append(" ");
134

    
135
                //dataType
136
                String type =attr.getDataType();
137
                if (type.equals(FeatureAttributeDescriptor.TYPE_STRING)){
138
                        if (attr.getSize() < 1){
139
                                sql.append("VARCHAR");
140
                        } else {
141
                                sql.append("VARCHAR("+attr.getSize()+")");
142
                        }
143
                } else if (type.equals(FeatureAttributeDescriptor.TYPE_BOOLEAN)){
144
                        sql.append("BOOL");
145
                } else if (type.equals(FeatureAttributeDescriptor.TYPE_BYTE)){
146
                        sql.append("TINYINT");
147
                } else if (type.equals(FeatureAttributeDescriptor.TYPE_DATE)){
148
                        sql.append("DATE");
149
                } else if (type.equals(FeatureAttributeDescriptor.TYPE_TIMESTAMP)){
150
                        sql.append("TIMESTAMP");
151
                } else if (type.equals(FeatureAttributeDescriptor.TYPE_TIME)){
152
                        sql.append("TIME");
153
                } else if (type.equals(FeatureAttributeDescriptor.TYPE_DOUBLE)){
154
                        sql.append("DOUBLE");
155
                        if (attr.getPrecision() > 0){
156
                                sql.append(" "+ attr.getPrecision());
157
                        }
158
                } else if (type.equals(FeatureAttributeDescriptor.TYPE_FLOAT)){
159
                        sql.append("REAL");
160
                } else if (type.equals(FeatureAttributeDescriptor.TYPE_GEOMETRY)){
161
                        sql.append("OTHER");
162
                } else if (type.equals(FeatureAttributeDescriptor.TYPE_INT)){
163
                        if (attr.isAutoIncrement()){
164
                                sql.append("IDENTITY");
165
                        }else{
166
                                sql.append("INT");
167
                        }
168
                } else if (type.equals(FeatureAttributeDescriptor.TYPE_LONG)){
169
                        if (attr.isAutoIncrement()){
170
                                sql.append("IDENTITY");
171
                        }else{
172
                                sql.append("BIGINT");
173
                        }
174
                } else {
175
                        throw new InitializeException(this.getName(),new Exception("Unsuported type "+type));
176
                }
177
                sql.append(" ");
178

    
179
                //DefeaultValue
180
                if (attr.getDefaultValue() != null || (attr.getDefaultValue() == null && attr.isAllowNull() )){
181
                        sql.append("DEFAULT ? ");
182
                        sqlParams.add(attr.getDefaultValue());
183
                }
184

    
185
                //Null
186
                if (attr.isAllowNull()){
187
                        sql.append("NOT NULL ");
188
                }
189

    
190
                //Primery key
191
                if (attr.isPrimaryKey()){
192
                        sql.append("PRIMARY KEY ");
193
                }
194

    
195
        }
196

    
197

    
198
        public DataStoreParameters add(NewFeatureStoreParameters ndsp)
199
                        throws InitializeException, InitializeWriterException {
200
                Connection conn;
201
                try {
202
                        conn = this.getConnection();
203
                } catch (ReadException e1) {
204
                        throw new InitializeException(this.getName(),e1);
205
                }
206

    
207
                try {
208
                        conn.setAutoCommit(true);
209
                } catch (SQLException e) {
210
                        throw new InitializeException(this.getName(),e);
211
                }
212
                DataStoreParameters params = this.add(ndsp,conn);
213

    
214
                return params;
215
        }
216

    
217

    
218
        protected DataStoreParameters add(NewFeatureStoreParameters ndsp,Connection conn)
219
                throws InitializeException, InitializeWriterException {
220

    
221

    
222
                /**
223
                 CREATE [CACHED | MEMORY | TEMP | [GLOBAL | LOCAL] TEMPORARY]
224
                        TABLE [IF NOT EXISTS] name
225
                        { ( {name dataType
226
                        [{AS computedColumnExpression | DEFAULT expression}]
227
                        [[NOT] NULL]
228
                        [{AUTO_INCREMENT | IDENTITY}[(startInt [, incrementInt])]]
229
                        [SELECTIVITY selectivity]
230
                        [PRIMARY KEY [HASH] | UNIQUE]
231
                        | constraint} [,...] ) [ AS select ] } | { AS select }
232
                 */
233

    
234
//                PreparedStatement st=null;
235
                Statement st=null;
236
                StringBuffer sql = new StringBuffer();
237
                ArrayList sqlParamas = new ArrayList();
238

    
239
                if (!ndsp.isValid()){
240
                        //TODO Exception
241
                        throw new InitializeException(this.getName(),new Exception("Parameters not valid"));
242
                }
243
                H2StoreParameters h2Param = (H2StoreParameters)ndsp.getDataStoreParameters();
244
                DBFeatureType fType = (DBFeatureType)ndsp.getFeatureType();
245

    
246
                sql.append("Create table "+ h2Param.tableID()+"(");
247
                DBAttributeDescriptor attr;
248
                int i;
249
                FeatureAttributeDescriptor[] fads=(FeatureAttributeDescriptor[])fType.toArray(new FeatureAttributeDescriptor[0]);
250
                for (int j = 0; j < fads.length-1; j++) {
251

    
252
//                        appendFieldToCreteSQL(attr, sql,sqlParamas);
253
                        appendFieldToCreteSQL((DBAttributeDescriptor)fads[j], sql);
254
                        sql.append(",");
255
                }
256
                attr = (DBAttributeDescriptor)fads[fads.length-1];
257
                appendFieldToCreteSQL(attr, sql);
258
                sql.append(")");
259

    
260
                try{
261
//                        st = conn.prepareStatement(sql.toString());
262
//                        for (i=0;i<sqlParamas.size();i++){
263
//                                st.setObject(i+1, sqlParamas.get(i));
264
//                        }
265
                        st = conn.createStatement();
266
                        st.execute(sql.toString());
267
                } catch (SQLException e) {
268
                        throw new InitializeException(this.getName(),e);
269
                } finally{
270
                        if (st != null){
271
                                try {
272
                                        st.close();
273
                                } catch (SQLException e) {
274
                                        // TODO ???
275
                                        e.printStackTrace();
276
                                }
277
                        }
278
                }
279
                return h2Param;
280
        }
281

    
282
        public NewDataStoreParameters createNewDataStoreParameter() {
283
                return new H2NewStoreParameter(this.newStoreParamters());
284
        }
285

    
286
        public void remove(DataStoreParameters dsp) throws ReadException {
287
                Connection conn = this.getConnection();
288

    
289
                try {
290
                        conn.setAutoCommit(true);
291
                } catch (SQLException e) {
292
                        throw new InitializeException(this.getName(),e);
293
                }
294
                this.remove(dsp, conn);
295
        }
296

    
297
        protected void remove(DataStoreParameters dsp,Connection conn) throws ReadException {
298
                Statement st=null;
299
                try{
300
                        st = conn.createStatement();
301
                        st.execute("Drop table "+ ((H2StoreParameters)dsp).tableID());
302
                } catch (SQLException e) {
303
                        throw new ReadException(this.getName(),e);
304
                } finally{
305
                        if (st != null){
306
                                try {
307
                                        st.close();
308
                                } catch (SQLException e) {
309
                                        // TODO ???
310
                                        e.printStackTrace();
311
                                }
312
                        }
313
                }
314
        }
315

    
316
        public boolean canCreate() {
317
                return true;
318
        }
319

    
320
        public String getName() {
321
                return DATAEXPLORER_NAME;
322
        }
323

    
324
        public String getDataStoreName(){
325
                return H2Store.DATASTORE_NAME;
326
        }
327

    
328
        public void init(DataExplorerParameters parameters) throws InitializeException {
329

    
330
                H2Resource tmpResource = new H2Resource((H2ExplorerParameters)parameters);
331
                H2Resource theResource;
332
                ResourceManager resMan = ResourceManager.getResourceManager();
333

    
334
                try {
335
                        theResource = (H2Resource)resMan.addResource(tmpResource);
336
                } catch (DataException e1) {
337
                        throw new InitializeException(this.getName(),e1);
338
                }
339

    
340
                super.init(parameters,theResource);
341
                try {
342
                        ((H2Resource)this.resource).close();
343
                        this.defaultSchema = H2Utils.getDefaultSchema(this.getConnection(), this.parameters.getCatalog());
344
                } catch (ReadException e) {
345
                        throw new InitializeException(this.getName(),e);
346
                }
347
        }
348

    
349
        private H2StoreParameters newStoreParamters(){
350
                DataManager manager = DataManager.getManager();
351
                H2StoreParameters param;
352
                try {
353
                        param = (H2StoreParameters)manager.createDataStoreParameters(getDataStoreName());
354
                } catch (InitializeException e) {
355
                        // FIXME no deber?a de ocurrir pero... que hacemos???
356
                        return null;
357
                }
358
                this.parameters.fillStoreParameters(param);
359
                return param;
360
        }
361

    
362
        public DataStoreParameters[] list() throws ReadException {
363
                return this.list(((H2ExplorerParameters)this.parameters).isShowInformationDBTables());
364
        }
365

    
366
        public DataStoreParameters[] list(boolean showInformationDBTables) throws ReadException {
367
                Connection conn = this.getConnection();
368
                String sql = "SELECT TABLE_CATALOG, TABLE_SCHEMA, TABLE_NAME FROM INFORMATION_SCHEMA.TABLES";
369
                if (!showInformationDBTables){
370
                        sql = sql + " WHERE TABLE_SCHEMA <> 'INFORMATION_SCHEMA'";
371
                }
372
                ArrayList paramList = new ArrayList();
373
                H2StoreParameters h2param = null;
374

    
375
                try{
376
                        Statement st = conn.createStatement();
377
                        ResultSet rs = st.executeQuery(sql);
378
                        while (rs.next()){
379
                                h2param = this.newStoreParamters();
380
                                h2param.setCatalog(rs.getString(1));
381
                                h2param.setSchema(rs.getString(2));
382
                                h2param.setTableName(rs.getString(3));
383
                                h2param.setFields(new String[] {"*"});
384
                                paramList.add(h2param);
385

    
386
                        }
387

    
388

    
389
                } catch (SQLException e) {
390
                        throw new ReadException(this.getName(),e);
391
                }
392

    
393
                return (H2StoreParameters[])paramList.toArray(new H2StoreParameters[0]);
394

    
395
        }
396

    
397
        public FeatureType[] getFeatureTypes(DataStoreParameters dsp) throws ReadException {
398
                return new FeatureType[] {H2Utils.getFeatureType(this.getConnection(), (H2StoreParameters)dsp)};
399
        }
400

    
401
        public String getDefaultSchema(){
402
                return this.defaultSchema;
403
        }
404

    
405
        /* (non-Javadoc)
406
         * @see org.gvsig.fmap.data.DataExplorer#dispose()
407
         */
408
        public void dispose() throws DataException {
409
                ResourceManager resMan = ResourceManager.getResourceManager();
410

    
411
            try {
412
                        resMan.remove(this.resource);
413
                } catch (DataException e1) {
414
                        throw new CloseException(this.getName(),e1);
415
                } catch (KeyException e) {
416
                        throw new CloseException(this.getName(),e);
417
                }
418

    
419
        }
420

    
421
}