Statistics
| Revision:

root / trunk / libraries / libFMap_dataDB / src / org / gvsig / data / datastores / vectorial / db / jdbc / h2 / H2Utils.java @ 20908

History | View | Annotate | Download (14.7 KB)

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

    
3
import java.sql.Connection;
4
import java.sql.ResultSet;
5
import java.sql.ResultSetMetaData;
6
import java.sql.Statement;
7
import java.util.ArrayList;
8
import java.util.Iterator;
9

    
10
import org.gvsig.data.datastores.vectorial.db.DBAttributeDescriptor;
11
import org.gvsig.data.datastores.vectorial.db.DBFeatureType;
12
import org.gvsig.data.datastores.vectorial.db.jdbc.exception.SQLException;
13
import org.gvsig.data.exception.DataException;
14
import org.gvsig.data.exception.InitializeException;
15
import org.gvsig.data.exception.ReadException;
16
import org.gvsig.data.vectorial.AttributeDescriptor;
17
import org.gvsig.data.vectorial.FeatureType;
18
import org.gvsig.data.vectorial.IFeatureAttributeDescriptor;
19
import org.gvsig.data.vectorial.IsNotAttributeSettingException;
20

    
21
import com.iver.cit.gvsig.fmap.core.FShape;
22

    
23
public class H2Utils {
24

    
25

    
26

    
27
        static String getDefaultSchema(Connection conn, String catalog) throws InitializeException {
28
                String sql= "SELECT * FROM INFORMATION_SCHEMA.SCHEMATA WHERE IS_DEFAULT = TRUE";
29
                if (catalog != null && catalog !=""){
30
                        sql= sql+ " AND CATALOG_NAME = '"+catalog+"'";
31
                }
32

    
33
                String schema = null;
34
                Statement st = null;
35
                ResultSet rs= null;
36
                try{
37
                        st = conn.createStatement(ResultSet.FETCH_FORWARD, ResultSet.CONCUR_READ_ONLY);
38
                        rs = st.executeQuery(sql);
39
                        if (!rs.next()){
40
                                throw new InitializeException("Can't find default schema.","getDefaulSchema");
41
                        }
42
                        schema = rs.getString("SCHEMA_NAME");
43
                        if (rs.next()){
44
                                throw new InitializeException("Checks catalog parm.","getDefaulSchema");
45
                        }
46

    
47

    
48
                } catch (java.sql.SQLException e) {
49
                        // TODO Auto-generated catch block
50
                        throw new SQLException(sql,"getDefaultSchema",e);
51
                } finally{
52
                        try{
53
                                if (rs != null){
54
                                        rs.close();
55
                                } else if (st != null){
56
                                        st.close();
57
                                }
58
                        } catch (java.sql.SQLException e1){
59
                                //Ignore ??
60
                        }
61

    
62
                }
63
                return schema;
64
        }
65

    
66
        private static void loadFieldsToFeatureType(Connection conn,H2StoreParameters params,DBFeatureType featureType) throws ReadException{
67
                String sql="";
68
                String columns=params.getFieldsString();
69

    
70
                if (params.getSqlSoure() != null){
71
                        sql = params.getSqlSoure();
72
                } else {
73
                        sql = "Select "+columns+" from " + params.tableID() + " limit 1;";
74
                }
75

    
76
                try {
77

    
78
                        Statement stAux = conn.createStatement();
79
                        Statement stAux1 = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
80
                        ResultSet rs = stAux.executeQuery(sql);
81
                        ResultSetMetaData rsMetadata = rs.getMetaData();
82
                        String schemaFilter="";
83
                        if (params.getSchema() != null && params.getSchema() != ""){
84
                                schemaFilter = " TABLE_SCHEMA='" + params.getSchema() +"' AND ";
85
                        }
86
                        String sqlAllMeta = "SELECT * FROM INFORMATION_SCHEMA.COLUMNS where "
87
                                + schemaFilter
88
                                + "TABLE_NAME='"+ params.getTableName() +"'";
89

    
90
                        ResultSet rsAllMeta = stAux1.executeQuery(sqlAllMeta);
91

    
92
//                        ResultSet rsAllMeta = conn.getMetaData().getAttributes(null, null, tableName, "*");
93

    
94
                        String colName;
95
                        int i;
96

    
97
                        featureType.setTableID(params.tableID());
98
                        AttributeDescriptor attr;
99
                        for (i=1;i<=rsMetadata.getColumnCount();i++){
100
                                colName= rsMetadata.getColumnName(i);
101
                                rsAllMeta.first();
102

    
103
                                while (true){
104
                                        if  (rsAllMeta.isAfterLast()){
105
                                                attr = getAttributeFromJDBC(featureType,conn,rsMetadata,i);
106
                                                featureType.add(attr);
107
//                                                attr.setOrdinal(i-1);
108
                                                break;
109
                                        } else if(rsAllMeta.getString("COLUMN_NAME").equals(colName)){
110
                                                attr = getAttributeFromJDBC(featureType,conn,rsAllMeta);
111
                                                featureType.add(attr);
112
//                                                attr.setOrdinal(i-1);
113
                                                break;
114
                                        }
115
                                        rsAllMeta.next();
116
                                }
117
                                if (attr.getName().equals(params.getGeometryField())){
118
                                        if (attr.getDataType().equals(IFeatureAttributeDescriptor.TYPE_OBJECT)){
119
                                                attr.loading();
120
                                                attr.setType(IFeatureAttributeDescriptor.TYPE_GEOMETRY);
121
                                                attr.stopLoading();
122
                                        }else{
123
                                                throw new InitializeException(
124
                                                        "H2Utils.getFeatureType",
125
                                                        new Exception("Geometry Field '"
126
                                                                + params.getGeometryField()
127
                                                                + "' is a "
128
                                                                + attr.getDataType()
129
                                                                + " but sould be "
130
                                                                + IFeatureAttributeDescriptor.TYPE_OBJECT));
131
                                        }
132

    
133
                                }
134
                        }
135

    
136
                        rs.close();
137
                        rsAllMeta.close();
138
                } catch (java.sql.SQLException e) {
139
                        // TODO Auto-generated catch block
140
                        throw new SQLException(sql,"getFeatureType",e);
141
                } catch (IsNotAttributeSettingException e) {
142
                        e.printStackTrace();
143
                }
144

    
145
        }
146

    
147
        static DBFeatureType getFeatureType(Connection conn,H2StoreParameters params) throws ReadException{
148
                DBFeatureType featureType = new DBFeatureType();
149

    
150

    
151
                loadFieldsToFeatureType(conn, params, featureType);
152

    
153
                try {
154
                        if (params.getFieldsId() == null || params.getFieldsId().length == 0){
155
                                String[] ids =loadFieldsId(conn,params);
156
                                if (ids == null){
157
                                        featureType.setReadOnly(true);
158
                                        ids = new String[featureType.size()];
159
                                        Iterator iter = featureType.iterator();
160
                                        for (int i=0;i<featureType.size();i++){
161
                                                ids[i]=((AttributeDescriptor)iter.next()).getName();
162
                                        }
163
                                }
164
                                featureType.setFieldsId(ids);
165
                        } else{
166
                                featureType.setFieldsId(params.getFieldsId());
167
                        }
168
                } catch (DataException e) {
169
                        throw new ReadException(H2Store.DATASTORE_NAME,e);
170
                }
171

    
172
                if (params.getGeometryField() != null && params.getGeometryField() != ""){
173
                        if (featureType.getFieldIndex(params.getGeometryField())< 0){
174
                                // FIXME: crear una nueva excepcion??
175
                                throw new InitializeException(
176
                                                H2Store.DATASTORE_NAME,
177
                                                new Exception("Geometry Field '"+ params.getGeometryField() +"' not Found"));
178

    
179
                        }
180

    
181
                        featureType.setDefaultGeometry(params.getGeometryField());
182
                }
183

    
184
                return featureType;
185

    
186
        }
187

    
188
        private static String[] loadFieldsId(Connection conn, H2StoreParameters params) throws ReadException {
189
                Statement st;
190
                StringBuffer sql = new StringBuffer();
191
                ResultSet rs;
192
                ArrayList list = new ArrayList();
193
                /*SELECT column_name FROM INFORMATION_SCHEMA.INDEXES
194
                 *   WHERE table_name='' AND
195
                 *         table_schema='' AND
196
                 *         table_catalog=''
197
                 *         AND index_type_name='PRIMARY KEY'
198
                 *
199
                 */
200
                sql.append("SELECT column_name FROM INFORMATION_SCHEMA.INDEXES WHERE table_name like '");
201
                sql.append(params.getTableName());
202
                sql.append("' AND table_schema like '");
203

    
204
                if (params.getSchema() == null || params.getSchema() == ""){
205
                        sql.append(getDefaultSchema(conn, params.getDb()));
206
                } else{
207
                        sql.append(params.getSchema());
208
                }
209

    
210

    
211
                if (params.getCatalog() == null || params.getCatalog() == ""){
212
                        if (params.getDb() != null && params.getDb() != ""){
213
                                sql.append("' AND table_catalog like '");
214
                                sql.append(params.getDb());
215
                        }
216
                } else {
217
                        sql.append("' AND table_catalog like '");
218
                        sql.append(params.getCatalog());
219
                }
220

    
221

    
222

    
223
                sql.append("' AND index_type_name='PRIMARY KEY'");
224

    
225
//                System.out.println(sql.toString());
226
                try {
227
                        st = conn.createStatement();
228
                        rs = st.executeQuery(sql.toString());
229
                        while (rs.next()){
230
                                list.add(rs.getString(1));
231
                        }
232
                        rs.close();
233
                        st.close();
234

    
235
                } catch (java.sql.SQLException e) {
236
                        throw new ReadException(params.getDataStoreName(),e);
237
                }
238
                if (list.size() == 0){
239
                        return null;
240
                }
241

    
242
                String[] x = new String[] {""};
243
                return (String[])list.toArray(x);
244

    
245
        }
246

    
247
        private static AttributeDescriptor getAttributeFromJDBC(FeatureType fType,Connection conn,ResultSetMetaData rsMetadata,int colIndex) throws SQLException{
248
                DBAttributeDescriptor column= (DBAttributeDescriptor) fType.createAttributeDescriptor();
249
                try {
250
                        column.loading();
251
                        column.setName(rsMetadata.getColumnName(colIndex));
252
                        column.setCaseSensitive(rsMetadata.isCaseSensitive(colIndex));
253
                        column.setSqlType(rsMetadata.getColumnType(colIndex));
254
                        column.setAllowNull(rsMetadata.isNullable(colIndex) == ResultSetMetaData.columnNullable);
255
                        column.setAutoIncrement(rsMetadata.isAutoIncrement(colIndex));
256
                        column.setReadOnly(rsMetadata.isReadOnly(colIndex));
257
                        column.setWritable(rsMetadata.isWritable(colIndex));
258
                        column.setClassName(rsMetadata.getColumnClassName(colIndex));
259
                        column.setCatalogName(rsMetadata.getCatalogName(colIndex));
260
                        column.setDefinitelyWritable(rsMetadata.isDefinitelyWritable(colIndex));
261
                        column.setLabel(rsMetadata.getColumnLabel(colIndex));
262
                        column.setSchemaName(rsMetadata.getSchemaName(colIndex));
263
                        column.setTableName(rsMetadata.getTableName(colIndex));
264
                        column.setCatalogName(rsMetadata.getCatalogName(colIndex));
265
                        column.setSqlTypeName(rsMetadata.getColumnTypeName(colIndex));
266
                        column.setSearchable(rsMetadata.isSearchable(colIndex));
267
                        column.setSigned(rsMetadata.isSigned(colIndex));
268
                        column.setCurrency(rsMetadata.isCurrency(colIndex));
269
                        column.setPrecision(rsMetadata.getPrecision(colIndex));
270
                        column.setSize(rsMetadata.getColumnDisplaySize(colIndex));                        switch (rsMetadata.getColumnType(colIndex)) {
271
                        case java.sql.Types.INTEGER:
272
                                column.setType(IFeatureAttributeDescriptor.TYPE_INT);
273
                                break;
274
                        case java.sql.Types.BIGINT:
275
                                column.setType(IFeatureAttributeDescriptor.TYPE_LONG);
276
                                break;
277
                        case java.sql.Types.REAL:
278
                                column.setType(IFeatureAttributeDescriptor.TYPE_DOUBLE);
279
                                break;
280
                        case java.sql.Types.DOUBLE:
281
                                column.setType(IFeatureAttributeDescriptor.TYPE_DOUBLE);
282
                                break;
283
                        case java.sql.Types.CHAR:
284
                                column.setType(IFeatureAttributeDescriptor.TYPE_STRING);
285
                                break;
286
                        case java.sql.Types.VARCHAR:
287
                                column.setType(IFeatureAttributeDescriptor.TYPE_STRING);
288
                                break;
289
                        case java.sql.Types.FLOAT:
290
                                column.setType(IFeatureAttributeDescriptor.TYPE_FLOAT);
291
                                break;
292
                        case java.sql.Types.DECIMAL:
293
                                column.setType(IFeatureAttributeDescriptor.TYPE_FLOAT);
294
                                break;
295
                        case java.sql.Types.DATE:
296
                                column.setType(IFeatureAttributeDescriptor.TYPE_DATE);
297
                                break;
298
                        case java.sql.Types.TIME:
299
                                column.setType(IFeatureAttributeDescriptor.TYPE_TIME);
300
                                break;
301
                        case java.sql.Types.TIMESTAMP:
302
                                column.setType(IFeatureAttributeDescriptor.TYPE_TIMESTAMP);
303
                                break;
304
                        case java.sql.Types.BOOLEAN:
305
                                column.setType(IFeatureAttributeDescriptor.TYPE_BOOLEAN);
306
                                break;
307
                        default:
308
                                column.setType(IFeatureAttributeDescriptor.TYPE_OBJECT);
309
                                break;
310
                        }
311
                        column.stopLoading();
312
                } catch (java.sql.SQLException e){
313
                        throw new SQLException("","load attribute definition",e);
314
                } catch (IsNotAttributeSettingException e) {
315
                        e.printStackTrace();
316
                }
317

    
318
                return column;
319

    
320
        }
321

    
322
        private static AttributeDescriptor getAttributeFromJDBC(FeatureType fType, Connection conn, ResultSet rsMetadata) throws SQLException{
323
                DBAttributeDescriptor column= (DBAttributeDescriptor) fType.createAttributeDescriptor();
324
                try {
325
                        column.loading();
326
                        column.setName(rsMetadata.getString("COLUMN_NAME"));
327
                        column.setSqlType(rsMetadata.getInt("DATA_TYPE"));
328
                        switch (rsMetadata.getInt("DATA_TYPE")) {
329
                        case java.sql.Types.INTEGER:
330
                                column.setType(IFeatureAttributeDescriptor.TYPE_INT);
331
                                break;
332
                        case java.sql.Types.BIGINT:
333
                                column.setType(IFeatureAttributeDescriptor.TYPE_LONG);
334
                                break;
335
                        case java.sql.Types.REAL:
336
                                column.setType(IFeatureAttributeDescriptor.TYPE_DOUBLE);
337
//                                column.setPrecision(rsMetadata.getInt("DECIMAL_DIGITS"));
338
                                column.setPrecision(rsMetadata.getInt("NUMERIC_PRECISION"));
339
                                break;
340
                        case java.sql.Types.DOUBLE:
341
                                column.setType(IFeatureAttributeDescriptor.TYPE_DOUBLE);
342
//                                column.setPrecision(rsMetadata.getInt("DECIMAL_DIGITS"));
343
                                column.setPrecision(rsMetadata.getInt("NUMERIC_PRECISION"));
344
                                break;
345
                        case java.sql.Types.CHAR:
346
                                column.setType(IFeatureAttributeDescriptor.TYPE_STRING);
347
//                                column.setSize(rsMetadata.getInt("COLUMN_SIZE"));
348
                                column.setSize(rsMetadata.getInt("CHARACTER_MAXIMUM_LENGTH"));
349
                                break;
350
                        case java.sql.Types.VARCHAR:
351
                                column.setType(IFeatureAttributeDescriptor.TYPE_STRING);
352
//                                column.setSize(rsMetadata.getInt("COLUMN_SIZE"));
353
                                column.setSize(rsMetadata.getInt("CHARACTER_MAXIMUM_LENGTH"));
354

    
355
                                break;
356
                        case java.sql.Types.FLOAT:
357
                                column.setType(IFeatureAttributeDescriptor.TYPE_FLOAT);
358
//                                column.setSize(rsMetadata.getInt("COLUMN_SIZE"));
359
                                column.setSize(rsMetadata.getInt("CHARACTER_MAXIMUM_LENGTH"));
360
                                break;
361
                        case java.sql.Types.DECIMAL:
362
                                column.setType(IFeatureAttributeDescriptor.TYPE_FLOAT);
363
//                                column.setSize(rsMetadata.getInt("COLUMN_SIZE"));
364
                                column.setSize(rsMetadata.getInt("CHARACTER_MAXIMUM_LENGTH"));
365
//                                column.setPrecision(rsMetadata.getInt("DECIMAL_DIGITS"));
366
                                column.setPrecision(rsMetadata.getInt("NUMERIC_PRECISION"));
367
                                break;
368
                        case java.sql.Types.DATE:
369
                                column.setType(IFeatureAttributeDescriptor.TYPE_DATE);
370
                                break;
371
                        case java.sql.Types.BOOLEAN:
372
                                column.setType(IFeatureAttributeDescriptor.TYPE_BOOLEAN);
373
                                break;
374
                        default:
375
                                //FIXME: Falta comprobar si es geometrica!!!
376
                                column.setType(IFeatureAttributeDescriptor.TYPE_OBJECT);
377
                                break;
378
                        }
379

    
380
                        column.setDefaultValue(rsMetadata.getObject("COLUMN_DEFAULT"));
381
                        column.setAllowNull(rsMetadata.getBoolean("IS_NULLABLE"));
382
                        column.stopLoading();
383
                } catch (java.sql.SQLException e){
384
                        throw new SQLException("","load attribute definition",e);
385
                } catch (IsNotAttributeSettingException e) {
386
                        e.printStackTrace();
387
                }
388

    
389
                return column;
390

    
391
        }
392

    
393

    
394

    
395
        static void initializeTableEPSG_and_shapeType(Connection conn,String tableID, DBFeatureType dbld) throws ReadException {
396
                try {
397
                        Statement stAux = conn.createStatement();
398

    
399
//                        String sql = "SELECT * FROM GEOMETRY_COLUMNS WHERE F_TABLE_NAME = '"
400
//                                        + getTableName() + "' AND F_GEOMETRY_COLUMN = '" + getLyrDef().getFieldGeometry() + "'";
401
                        String sql= "SELECT SRID("+dbld.getDefaultGeometry()+"), GeometryType("+dbld.getDefaultGeometry()+") FROM "+tableID +" WHERE "+dbld.getDefaultGeometry()+" is not null LIMIT 1";
402

    
403
                        ResultSet rs = stAux.executeQuery(sql);
404
                        if(!rs.next()){
405
                                dbld.setDefaultSRS("");
406
                                dbld.setGeometryTypes(new int[]{FShape.MULTI});
407
                                return;
408
                        }
409
                        dbld.setDefaultSRS("EPSG:"+rs.getInt(1));
410

    
411
                        String geometryType = rs.getString(2);
412
                        int shapeType = FShape.MULTI;
413
                        if (geometryType.compareToIgnoreCase("Point") == 0)
414
                                shapeType = FShape.POINT;
415
                        else if (geometryType.compareToIgnoreCase("LineString") == 0)
416
                                shapeType = FShape.LINE;
417
                        else if (geometryType.compareToIgnoreCase("Polygon") == 0)
418
                                shapeType = FShape.POLYGON;
419
                        else if (geometryType.compareToIgnoreCase("MultiPoint") == 0)
420
                                shapeType = FShape.POINT;
421
                        else if (geometryType.compareToIgnoreCase("MultiLineString") == 0)
422
                                shapeType = FShape.LINE;
423
                        else if (geometryType.compareToIgnoreCase("MultiPolygon") == 0)
424
                                shapeType = FShape.POLYGON;
425

    
426
                        dbld.setGeometryTypes(new int[]{shapeType});
427
                        rs.close();
428

    
429
                } catch (java.sql.SQLException e) {
430
                        dbld.setDefaultSRS("");
431
                        dbld.setGeometryTypes(new int[]{FShape.MULTI});
432
                        throw new ReadException("H2Utils.getTableEPSG_and_shapeType",e);
433
                }
434

    
435
        }
436

    
437
        static String getConnectionResourceID(String dbUrl,String dbUser){
438
                return H2Store.CONNECTION_STRING+";"+dbUrl+";"+dbUser;
439

    
440
        }
441

    
442

    
443
        static String getJDBCUrl(String host,String db){
444
                String url;
445
                url = "jdbc:h2:tcp://"+host;
446
                if (db == null || db == ""){
447
                        url=url+"/default";
448
                }else {
449
                        url=url+"/"+db;
450
                }
451

    
452
                return url;
453
        }
454

    
455
}