Statistics
| Revision:

svn-gvsig-desktop / branches / v2_0_0_prep / libraries / libFMap_daldb / src / org / gvsig / fmap / dal / store / mysql / MySQLHelper.java @ 28948

History | View | Annotate | Download (11.1 KB)

1
/* gvSIG. Geographic Information System of the Valencian Government
2
*
3
* Copyright (C) 2007-2008 Infrastructures and Transports Department
4
* of the Valencian Government (CIT)
5
*
6
* This program is free software; you can redistribute it and/or
7
* modify it under the terms of the GNU General Public License
8
* as published by the Free Software Foundation; either version 2
9
* of the License, or (at your option) any later version.
10
*
11
* This program is distributed in the hope that it will be useful,
12
* but WITHOUT ANY WARRANTY; without even the implied warranty of
13
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
* GNU General Public License for more details.
15
*
16
* You should have received a copy of the GNU General Public License
17
* along with this program; if not, write to the Free Software
18
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19
* MA  02110-1301, USA.
20
*
21
*/
22

    
23
/*
24
* AUTHORS (In addition to CIT):
25
* 2009 IVER T.I   {{Task}}
26
*/
27

    
28
/**
29
 *
30
 */
31
package org.gvsig.fmap.dal.store.mysql;
32

    
33
import java.sql.Connection;
34
import java.sql.ResultSet;
35
import java.sql.ResultSetMetaData;
36
import java.sql.SQLException;
37
import java.sql.Statement;
38

    
39
import org.gvsig.fmap.dal.DALLocator;
40
import org.gvsig.fmap.dal.DataTypes;
41
import org.gvsig.fmap.dal.exception.DataException;
42
import org.gvsig.fmap.dal.exception.InitializeException;
43
import org.gvsig.fmap.dal.exception.ReadException;
44
import org.gvsig.fmap.dal.feature.EditableFeatureAttributeDescriptor;
45
import org.gvsig.fmap.dal.feature.EditableFeatureType;
46
import org.gvsig.fmap.dal.feature.FeatureAttributeDescriptor;
47
import org.gvsig.fmap.dal.feature.exception.UnsupportedDataTypeException;
48
import org.gvsig.fmap.dal.resource.spi.ResourceManagerProviderServices;
49
import org.gvsig.fmap.dal.store.jdbc.JDBCHelper;
50
import org.gvsig.fmap.dal.store.jdbc.JDBCHelperUser;
51
import org.gvsig.fmap.dal.store.jdbc.JDBCStoreParameters;
52
import org.gvsig.fmap.dal.store.jdbc.exception.JDBCException;
53
import org.gvsig.fmap.dal.store.jdbc.exception.JDBCExecuteSQLException;
54
import org.gvsig.fmap.dal.store.jdbc.exception.JDBCSQLException;
55
import org.gvsig.fmap.geom.Geometry;
56
import org.gvsig.fmap.geom.GeometryLocator;
57
import org.gvsig.fmap.geom.GeometryManager;
58
import org.gvsig.fmap.geom.operation.fromwkb.FromWKB;
59
import org.gvsig.fmap.geom.operation.fromwkb.FromWKBGeometryOperationContext;
60
import org.gvsig.fmap.geom.primitive.Envelope;
61
import org.gvsig.tools.exception.BaseException;
62
import org.slf4j.Logger;
63
import org.slf4j.LoggerFactory;
64

    
65
/**
66
 * @author jmvivo
67
 *
68
 */
69
public class MySQLHelper extends JDBCHelper {
70

    
71
        private static Logger logger = LoggerFactory
72
                        .getLogger(MySQLHelper.class);
73

    
74

    
75
        MySQLHelper(JDBCHelperUser consumer,
76
                        MySQLConnectionParameters params)
77
                        throws InitializeException {
78

    
79
                super(consumer, params);
80
        }
81

    
82
        protected void initializeResource() throws InitializeException {
83
                ResourceManagerProviderServices manager = (ResourceManagerProviderServices) DALLocator
84
                .getResourceManager();
85
                MySQLResource resource = (MySQLResource) manager
86
                .createResource(
87
                                MySQLResource.NAME, new Object[] {
88
                                                params.getUrl(), params.getHost(),
89
                                                params.getPort(), params.getDBName(), params.getUser(),
90
                                                params.getPassword(),
91
                                                params.getJDBCDriverClassName(),
92
                                                ((MySQLConnectionParameters) params).getUseSSL() });
93
                this.setResource(resource);
94
        }
95

    
96

    
97
        protected String getDefaultSchema(Connection conn)
98
                        throws JDBCException {
99
                if (defaultSchema == null) {
100
                        defaultSchema = params.getDBName();
101
                }
102

    
103
                return defaultSchema;
104
        }
105

    
106
        public Envelope getFullEnvelopeOfField(
107
                        JDBCStoreParameters storeParams,
108
                        String geometryAttrName, Envelope limit)
109
                        throws DataException {
110

    
111
                StringBuilder strb = new StringBuilder();
112
                strb.append("Select asbinary(envelope(");
113
                strb.append(geometryAttrName);
114
                strb.append(")) from ");
115

    
116
                if (storeParams.getSQL() != null
117
                                && storeParams.getSQL().trim().length() == 0) {
118
                        strb.append('(');
119
                        strb.append(storeParams.getSQL());
120
                        strb.append(") as __tmp__ ");
121
                } else {
122
                        strb.append(storeParams.tableID());
123
                }
124

    
125

    
126
                if (limit != null){
127
                        strb.append(" where  intersects(GeomFromText('");
128
                        strb.append(limit.toString());
129
                        strb.append("')), boundary(");
130
                        strb.append(geometryAttrName);
131
                        strb.append(")) ");
132
                }
133

    
134
                String sql = strb.toString();
135

    
136

    
137
                ResultSet rs = null;
138
                Statement st = null;
139
                String schema = null;
140
                Connection conn = null;
141

    
142
                GeometryManager geoMan = GeometryLocator.getGeometryManager();
143

    
144
                Envelope fullEnvelope = null;
145
                this.open();
146
                this.begin();
147
                try{
148
                        conn = getConnection();
149
                        st = conn.createStatement();
150
                        try {
151
                                rs = st.executeQuery(sql);
152
                        } catch (java.sql.SQLException e) {
153
                                throw new JDBCExecuteSQLException(sql, e);
154
                        }
155
                        if (!rs.next()) {
156
                                return null;
157
                        }
158

    
159
                        byte[] data = rs.getBytes(1);
160
                        if (data == null) {
161
                                return null;
162
                        }
163
                        initializeFromWKBOperation();
164
                        fromWKBContext.setData(data);
165
                        Geometry geom = (Geometry) fromWKB.invoke(null, fromWKBContext);
166

    
167
                        fullEnvelope = geom.getEnvelope();
168

    
169
                        return fullEnvelope;
170
                } catch (java.sql.SQLException e) {
171
                        throw new JDBCSQLException(e);
172
                } catch (BaseException e) {
173
                        throw new ReadException(user.getName(), e);
174
                } finally {
175
                        try{ rs.close(); } catch (Exception e){};
176
                        try{ st.close(); } catch (Exception e){};
177
                        try{ conn.close(); } catch (Exception e){};
178
                        rs = null;
179
                        st = null;
180
                        conn = null;
181
                        end();
182
                }
183

    
184

    
185
        }
186

    
187
        protected void initializeFromWKBOperation() throws BaseException {
188
                if (fromWKB == null) {
189
                        fromWKB = (FromWKB) GeometryLocator.getGeometryManager()
190
                                        .getGeometryOperation(FromWKB.CODE,
191
                                                        Geometry.TYPES.GEOMETRY, Geometry.SUBTYPES.GEOM2D);
192
                        fromWKBContext = new FromWKBGeometryOperationContext();
193

    
194
                }
195
        }
196

    
197
        public Geometry getGeometry(byte[] buffer) throws BaseException {
198
                if (buffer == null) {
199
                        return null;
200
                }
201
                initializeFromWKBOperation();
202
                Geometry geom;
203
                try {
204
                        fromWKBContext.setData(buffer);
205

    
206
                        geom = (Geometry) fromWKB.invoke(null, fromWKBContext);
207
                } finally {
208
                        fromWKBContext.setData(null);
209
                }
210
                return geom;
211
        }
212

    
213
        public String getSqlColumnTypeDescription(FeatureAttributeDescriptor attr) {
214

    
215
                switch (attr.getDataType()) {
216
                case DataTypes.STRING:
217
                        return "VARCHAR(" + attr.getSize() + ")";
218
                case DataTypes.BOOLEAN:
219
                        return "BOOL";
220

    
221
                case DataTypes.BYTE:
222
                        return "TINYINT UNSIGNED";
223

    
224
                case DataTypes.DATE:
225
                        return "DATE";
226

    
227
                case DataTypes.TIMESTAMP:
228
                        return "TIMESTAMP";
229

    
230
                case DataTypes.TIME:
231
                        return "TIME";
232

    
233
                case DataTypes.BYTEARRAY:
234
                        if (attr.getSize() > 0) {
235
                                return "BLOB(" + attr.getSize() + ")";
236
                        } else {
237
                                return "BLOB";
238
                        }
239

    
240
                case DataTypes.DOUBLE:
241
                        if (attr.getSize() > 0) {
242
                                return "DOUBLE(" + attr.getSize() + "," + attr.getPrecision()
243
                                                + ")";
244
                        } else {
245
                                return "DOBLE";
246
                        }
247
                case DataTypes.FLOAT:
248
                        return "FLOAT";
249

    
250
                case DataTypes.GEOMETRY:
251
                        switch (attr.getGeometryType()) {
252
                        case Geometry.TYPES.POINT:
253
                                return "POINT";
254
                        case Geometry.TYPES.CURVE:
255
                                return "LINESTRING";
256
                        case Geometry.TYPES.SURFACE:
257
                                return "SURFACE";
258
                        case Geometry.TYPES.SOLID:
259
                                return "POLYGON";
260

    
261
                        case Geometry.TYPES.MULTIPOINT:
262
                                return "MULTIPOIN";
263
                        case Geometry.TYPES.MULTICURVE:
264
                                return "MULTILINESTRING";
265
                        case Geometry.TYPES.MULTISURFACE:
266
                                return "MULTISURFACE";
267
                        case Geometry.TYPES.MULTISOLID:
268
                                return "MULTIPOLYGON";
269

    
270
                        default:
271
                                return "GEOMETRY";
272
                        }
273
                case DataTypes.INT:
274
                        if (attr.getSize() > 0) {
275
                                return "INT(" + attr.getSize() + ")";
276
                        }
277
                case DataTypes.LONG:
278
                        return "BIGINT";
279

    
280
                default:
281
                        String typeName = (String) attr.getAdditionalInfo("SQLTypeName");
282
                        if (typeName != null) {
283
                                return typeName;
284
                        }
285

    
286
                        throw new UnsupportedDataTypeException(attr.getDataTypeName(), attr
287
                                        .getDataType());
288
                }
289
        }
290

    
291

    
292
        public String getSqlFieldName(FeatureAttributeDescriptor attribute) {
293
                if (attribute.getDataType() == DataTypes.GEOMETRY) {
294
                        return "asBinary(" + super.getSqlFieldName(attribute) + ")";
295
                }
296
                return super.getSqlFieldName(attribute);
297
        }
298

    
299
        protected EditableFeatureAttributeDescriptor createAttributeFromJDBC(
300
                        EditableFeatureType type, Connection conn,
301
                        ResultSetMetaData rsMetadata, int colIndex) throws SQLException {
302
                int colType = rsMetadata.getColumnType(colIndex);
303
                if (colType == java.sql.Types.OTHER || colType == java.sql.Types.STRUCT
304
                                || colType == java.sql.Types.BLOB
305
                                || colType == java.sql.Types.BINARY) {
306
                        Integer geoType = null;
307

    
308
                        if (rsMetadata.getColumnTypeName(colIndex).equalsIgnoreCase(
309
                                        "geometry")) {
310
                                geoType = new Integer(Geometry.TYPES.GEOMETRY);
311
                        } else if (rsMetadata.getColumnTypeName(colIndex).equalsIgnoreCase("POINT")) {
312
                                geoType = new Integer(Geometry.TYPES.POINT);
313
                        } else if (rsMetadata.getColumnTypeName(colIndex).equalsIgnoreCase("LINESTRING")) {
314
                                geoType = new Integer(Geometry.TYPES.CURVE);
315
                        } else if (rsMetadata.getColumnTypeName(colIndex).equalsIgnoreCase("SURFACE")) {
316
                                geoType = new Integer(Geometry.TYPES.SURFACE);
317
                        } else if (rsMetadata.getColumnTypeName(colIndex).equalsIgnoreCase("POLYGON")) {
318
                                geoType = new Integer(Geometry.TYPES.SOLID);
319
                        } else if (rsMetadata.getColumnTypeName(colIndex).equalsIgnoreCase("MULTIPOIN")) {
320
                                geoType = new Integer(Geometry.TYPES.MULTIPOINT);
321
                        } else if (rsMetadata.getColumnTypeName(colIndex).equalsIgnoreCase("MULTILINESTRING")) {
322
                                geoType = new Integer(Geometry.TYPES.MULTICURVE);
323
                        } else if (rsMetadata.getColumnTypeName(colIndex).equalsIgnoreCase(
324
                                        "MULTISURFACE")) {
325
                                geoType = new Integer(Geometry.TYPES.MULTISURFACE);
326
                        } else if (rsMetadata.getColumnTypeName(colIndex).equalsIgnoreCase(
327
                                        "MULTIPOLYGON")) {
328
                                geoType = new Integer(Geometry.TYPES.MULTISOLID);
329
                        }
330
                        if (geoType != null){
331
                                EditableFeatureAttributeDescriptor attr = type.add(rsMetadata
332
                                                .getColumnName(colIndex), DataTypes.GEOMETRY);
333
                                attr.setGeometrySubType(Geometry.SUBTYPES.GEOM2D);
334

    
335
                                return attr;
336
                        }
337

    
338
                }
339

    
340
                return super.createAttributeFromJDBC(type, conn, rsMetadata, colIndex);
341
        }
342

    
343
        public String escapeFieldName(String field) {
344
                if (field.matches("[a-z][a-z0-9_]*")) {
345
                        return field;
346
                }
347
                return "`" + field + "`";
348
        }
349

    
350

    
351
        public boolean allowAutomaticValues() {
352
                return Boolean.TRUE;
353
        }
354

    
355

    
356
        public String getSqlFieldDescription(FeatureAttributeDescriptor attr)
357
                        throws DataException {
358

    
359
                /**
360
                        column_definition:
361
                            data_type [NOT NULL | NULL] [DEFAULT default_value]
362
                              [AUTO_INCREMENT] [UNIQUE [KEY] | [PRIMARY] KEY]
363
                              [COMMENT 'string'] [reference_definition]
364

365
                 */
366

    
367
                StringBuilder strb = new StringBuilder();
368
                // name
369
                strb.append(escapeFieldName(attr.getName()));
370
                strb.append(" ");
371

    
372
                // Type
373
                strb.append(this.getSqlColumnTypeDescription(attr));
374
                strb.append(" ");
375

    
376
                boolean allowNull = attr.allowNull()
377
                                && !(attr.isPrimaryKey() || attr.isAutomatic());
378

    
379
                // Null
380
                if (allowNull) {
381
                        strb.append("NULL ");
382
                } else {
383
                        strb.append("NOT NULL ");
384
                }
385
                if (attr.isAutomatic()) {
386
                        strb.append("AUTO_INCREMENT ");
387
                }
388

    
389
                // Default
390
                if (attr.getDefaultValue() == null) {
391
                        if (allowNull) {
392
                                strb.append("DEFAULT NULL ");
393
                        }
394
                } else {
395
                        String value = getDefaltFieldValueString(attr);
396
                        strb.append("DEFAULT '");
397
                        strb.append(value);
398
                        strb.append("' ");
399
                }
400

    
401
                // Primery key
402
                if (attr.isPrimaryKey()) {
403
                        strb.append("PRIMARY KEY ");
404
                }
405
                return strb.toString();
406
        }
407

    
408

    
409
}