Statistics
| Revision:

root / trunk / extensions / extJDBC / src / com / iver / cit / gvsig / fmap / drivers / jdbc / mysql / MySQLDriver.java @ 12351

History | View | Annotate | Download (11.2 KB)

1
/*
2
 * Created on 04-mar-2005
3
 *
4
 * gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
5
 *
6
 * Copyright (C) 2004 IVER T.I. and Generalitat Valenciana.
7
 *
8
 * This program is free software; you can redistribute it and/or
9
 * modify it under the terms of the GNU General Public License
10
 * as published by the Free Software Foundation; either version 2
11
 * of the License, or (at your option) any later version.
12
 *
13
 * This program is distributed in the hope that it will be useful,
14
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16
 * GNU General Public License for more details.
17
 *
18
 * You should have received a copy of the GNU General Public License
19
 * along with this program; if not, write to the Free Software
20
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
21
 *
22
 * For more information, contact:
23
 *
24
 *  Generalitat Valenciana
25
 *   Conselleria d'Infraestructures i Transport
26
 *   Av. Blasco Ib??ez, 50
27
 *   46010 VALENCIA
28
 *   SPAIN
29
 *
30
 *      +34 963862235
31
 *   gvsig@gva.es
32
 *      www.gvsig.gva.es
33
 *
34
 *    or
35
 *
36
 *   IVER T.I. S.A
37
 *   Salamanca 50
38
 *   46005 Valencia
39
 *   Spain
40
 *
41
 *   +34 963163400
42
 *   dac@iver.es
43
 */
44
package com.iver.cit.gvsig.fmap.drivers.jdbc.mysql;
45

    
46
import java.awt.geom.Rectangle2D;
47
import java.sql.Connection;
48
import java.sql.ResultSet;
49
import java.sql.ResultSetMetaData;
50
import java.sql.SQLException;
51
import java.sql.Statement;
52

    
53
import org.apache.log4j.Logger;
54

    
55
import com.hardcode.gdbms.driver.exceptions.InitializeWriterException;
56
import com.hardcode.gdbms.driver.exceptions.ReadDriverException;
57
import com.hardcode.gdbms.engine.data.edition.DataWare;
58
import com.iver.andami.messages.NotificationManager;
59
import com.iver.cit.gvsig.fmap.SqlDriveExceptionType;
60
import com.iver.cit.gvsig.fmap.core.IGeometry;
61
import com.iver.cit.gvsig.fmap.drivers.ConnectionJDBC;
62
import com.iver.cit.gvsig.fmap.drivers.DBException;
63
import com.iver.cit.gvsig.fmap.drivers.DBLayerDefinition;
64
import com.iver.cit.gvsig.fmap.drivers.DefaultJDBCDriver;
65
import com.iver.cit.gvsig.fmap.drivers.DriverAttributes;
66
import com.iver.cit.gvsig.fmap.drivers.IConnection;
67
import com.iver.cit.gvsig.fmap.drivers.IFeatureIterator;
68
import com.iver.cit.gvsig.fmap.drivers.WKBParser2;
69
import com.iver.cit.gvsig.fmap.edition.IWriteable;
70
import com.iver.cit.gvsig.fmap.edition.IWriter;
71

    
72
/**
73
 * @author FJP
74
 *
75
 * TODO To change the template for this generated type comment go to Window -
76
 * Preferences - Java - Code Generation - Code and Comments
77
 */
78
public class MySQLDriver extends DefaultJDBCDriver
79
                                                        implements IWriteable {
80

    
81
        private static Logger logger = Logger
82
                        .getLogger(MySQLDriver.class.getName());
83

    
84
        private WKBParser2 parser = new WKBParser2();
85

    
86
        private MySQLSpatialWriter writer = new MySQLSpatialWriter();
87

    
88
        /*
89
         * private int fetch_min=-1; private int fetch_max=-1;
90
         */
91
        private Statement st;
92

    
93
        private String strAux;
94

    
95
        private String strEPSG = "-1";
96

    
97
        private String originalEPSG;
98

    
99
        private String completeWhere;
100

    
101
        /**
102
         * Don't have information about working area
103
         */
104
        private String sqlOrig;
105

    
106
        /**
107
         * Does have information about working area and order
108
         */
109
        private String sqlTotal;
110

    
111
        /**
112
         *
113
         */
114
        public MySQLDriver() {
115
        }
116

    
117
        /*
118
         * (non-Javadoc)
119
         *
120
         * @see com.iver.cit.gvsig.fmap.drivers.VectorialDriver#getDriverAttributes()
121
         */
122
        public DriverAttributes getDriverAttributes() {
123
                return null;
124
        }
125

    
126
        /*
127
         * (non-Javadoc)
128
         *
129
         * @see com.hardcode.driverManager.Driver#getName()
130
         */
131
        public String getName() {
132
                return "mySQL JDBC Driver";
133
        }
134

    
135
        /**
136
         * @see com.iver.cit.gvsig.fmap.layers.ReadableVectorial#getShape(int)
137
         */
138
        public IGeometry getShape(int index) {
139
                IGeometry geom = null;
140
                boolean resul;
141
                try {
142
                        if (rs != null) {
143
                                rs.absolute(index + 1);
144
                                byte[] data = rs.getBytes(1);
145
                                geom = parser.parse(data);
146
                        }
147

    
148
                } catch (SQLException e) {
149
                        e.printStackTrace();
150
                }
151

    
152
                return geom;
153
        }
154

    
155
        /**
156
         * @param conn
157
         * @throws DBException
158
         */
159
        /*
160
         * (non-Javadoc)
161
         *
162
         * @see com.iver.cit.gvsig.fmap.drivers.VectorialJDBCDriver#setData(java.sql.Connection,
163
         *      java.lang.String, java.lang.String, java.lang.String, int)
164
         */
165
        public void setData(IConnection conn, DBLayerDefinition lyrDef) throws DBException {
166
                this.conn = conn;
167
                setLyrDef(lyrDef);
168
                try {
169

    
170
                        // NO ESTA LISTO ESTO AUN EN mySQL, o no s? usuarlo getTableEPSG();
171

    
172
                        sqlOrig = "SELECT " + getTotalFields() + " FROM "
173
                                        + getLyrDef().getTableName() + " ";
174
                                        // + getLyrDef().getWhereClause();
175
                        completeWhere = getCompoundWhere(workingArea, strEPSG);
176
                        String sqlAux = sqlOrig + completeWhere + " ORDER BY "
177
                                        + getLyrDef().getFieldID();
178
                        logger.info("Cadena SQL:" + sqlAux);
179
                        sqlTotal = sqlAux;
180

    
181
                        st = ((ConnectionJDBC)conn).getConnection().createStatement(ResultSet.TYPE_FORWARD_ONLY,
182
                                        ResultSet.CONCUR_READ_ONLY);
183

    
184
                        rs = st.executeQuery(sqlTotal);
185
                        metaData = rs.getMetaData();
186
                        // Le pegamos un primera pasada para poder relacionar
187
                        // un campo de identificador ?nico (parecido al OID en
188
                        // postgresql) con el ?ndice dentro del recordset.
189
                        // Esto cuando haya ediciones, no es v?lido, y hay
190
                        // que refrescarlo.
191
                        doRelateID_FID();
192

    
193
                        writer.setCreateTable(false);
194
                        writer.setWriteAll(false);
195
                        writer.initialize(lyrDef);
196

    
197

    
198
                } catch (SQLException e) {
199
                          throw new DBException(e);
200
                } catch (InitializeWriterException e) {
201
                          throw new DBException(e);
202
                }
203
        }
204

    
205
        /*
206
         * (non-Javadoc)
207
         *
208
         * @see com.iver.cit.gvsig.fmap.drivers.VectorialDatabaseDriver#getGeometryIterator(java.lang.String)
209
         */
210
        public IFeatureIterator getFeatureIterator(String sql)
211
                        throws ReadDriverException {
212
                Statement st;
213
                MySqlFeatureIterator geomIterator = null;
214
                try {
215
                        logger.debug(sql);
216
                        st = ((ConnectionJDBC)conn).getConnection().createStatement();
217
                        // st.setFetchSize(2000);
218
                        ResultSet rs = st.executeQuery(sql);
219
                        geomIterator = new MySqlFeatureIterator(rs);
220
                        geomIterator.setLyrDef(getLyrDef());
221
                } catch (SQLException e) {
222
//                        e.printStackTrace();
223
//                        SqlDriveExceptionType type = new SqlDriveExceptionType();
224
//            type.setDriverName("MySQL Driver");
225
//            type.setSql(sql);
226
//            type.setLayerName(getTableName());
227
//            type.setSchema(null);
228
            throw new ReadDriverException("MySQL Driver",e);
229
//                        throw new com.iver.cit.gvsig.fmap.DriverException(e);
230
                }
231

    
232
                return geomIterator;
233
        }
234

    
235
        /*
236
         * (non-Javadoc)
237
         *
238
         * @see com.iver.cit.gvsig.fmap.drivers.VectorialDatabaseDriver#getGeometryIterator(java.awt.geom.Rectangle2D)
239
         */
240
        public IFeatureIterator getFeatureIterator(Rectangle2D r, String strEPSG)
241
                        throws ReadDriverException {
242
                if (workingArea != null)
243
                        r = r.createIntersection(workingArea);
244
                String sqlAux = sqlOrig + getCompoundWhere(r, strEPSG);
245

    
246
                return getFeatureIterator(sqlAux);
247
        }
248

    
249
        /**
250
         * Le pasas el rect?ngulo que quieres pedir. La primera vez es el
251
         * workingArea, y las siguientes una interseccion de este rectangulo con el
252
         * workingArea
253
         *
254
         * @param r
255
         * @param strEPSG
256
         * @return
257
         */
258
        private String getCompoundWhere(Rectangle2D r, String strEPSG) {
259
                if (r == null)
260
                        return getWhereClause();
261

    
262
                double xMin = r.getMinX();
263
                double yMin = r.getMinY();
264
                double xMax = r.getMaxX();
265
                double yMax = r.getMaxY();
266

    
267
                String wktBox = "GeomFromText('LINESTRING(" + xMin + " " + yMin + ", "
268
                                + xMax + " " + yMin + ", " + xMax + " " + yMax + ", " + xMin
269
                                + " " + yMax + ")', '" + strEPSG + "')";
270
                String sqlAux;
271
                if (getWhereClause().startsWith("WHERE"))
272
                        sqlAux = getWhereClause() + " AND " +"MBRIntersects(" + wktBox + ", " + getLyrDef().getFieldGeometry() + ")";
273
                else
274
                        sqlAux = "WHERE MBRIntersects(" + wktBox + ", " + getLyrDef().getFieldGeometry() + ")";
275
                return sqlAux;
276
        }
277

    
278
        public void open() {
279
                // TODO Auto-generated method stub
280

    
281
        }
282

    
283
        /**
284
         * @see com.iver.cit.gvsig.fmap.drivers.IVectorialDatabaseDriver#getConnectionStringBeginning()
285
         */
286
        public String getConnectionStringBeginning() {
287
                return "jdbc:mysql:";
288
        }
289

    
290
        static {
291
                try {
292
                        Class.forName("com.mysql.jdbc.Driver");
293
                } catch (ClassNotFoundException e) {
294
                        throw new RuntimeException(e);
295
                }
296
        }
297

    
298
        /**
299
         * @see com.iver.cit.gvsig.fmap.drivers.IVectorialDatabaseDriver#getGeometryField(java.lang.String)
300
         */
301
        public String getGeometryField(String fieldName) {
302
                return "ASBINARY(" + fieldName + ")";
303
        }
304

    
305
        /**
306
         * @see com.hardcode.gdbms.engine.data.driver.ObjectDriver#getPrimaryKeys()
307
         */
308
        public int[] getPrimaryKeys()
309
                        throws ReadDriverException {
310
                return new int[] { getLyrDef().getIdFieldID() - 2 };
311
        }
312

    
313
        /**
314
         * @see com.iver.cit.gvsig.fmap.drivers.IVectorialJDBCDriver#getDefaultPort()
315
         */
316
        public int getDefaultPort() {
317
                return 3306;
318
        }
319

    
320
        /**
321
         * @see com.hardcode.gdbms.engine.data.driver.ObjectDriver#write(com.hardcode.gdbms.engine.data.edition.DataWare)
322
         */
323
        public void write(DataWare arg0){
324
                // TODO Auto-generated method stub
325

    
326
        }
327

    
328
        private void getTableEPSG() {
329
                try {
330
                        Statement stAux = ((ConnectionJDBC)conn).getConnection().createStatement();
331

    
332
                        String sql = "SELECT SRID(" + getLyrDef().getFieldGeometry() + ") FROM " + getTableName()
333
                                        + " LIMIT 1;";
334
                        ResultSet rs = stAux.executeQuery(sql);
335
                        rs.next();
336
                        originalEPSG = "" + rs.getInt(1);
337
                        rs.close();
338
                } catch (SQLException e) {
339
                        // TODO Auto-generated catch block
340
                        e.printStackTrace();
341
                }
342

    
343
        }
344

    
345
        public String getSqlTotal() {
346
                return sqlTotal;
347
        }
348

    
349
        /**
350
         * @return Returns the completeWhere.
351
         */
352
        public String getCompleteWhere() {
353
                return completeWhere;
354
        }
355

    
356
        /*
357
         * (non-Javadoc)
358
         *
359
         * @see com.iver.cit.gvsig.fmap.drivers.VectorialDatabaseDriver#getFeatureIterator(java.awt.geom.Rectangle2D,
360
         *      java.lang.String, java.lang.String[])
361
         */
362
        public IFeatureIterator getFeatureIterator(Rectangle2D r, String strEPSG,
363
                        String[] alphaNumericFieldsNeeded) throws ReadDriverException {
364
                if (workingArea != null)
365
                        r = r.createIntersection(workingArea);
366

    
367
                String strAux = getGeometryField(getLyrDef().getFieldGeometry());
368
                boolean found = false;
369
                if (alphaNumericFieldsNeeded != null) {
370
                        for (int i = 0; i < alphaNumericFieldsNeeded.length; i++) {
371
                                strAux = strAux + ", " + alphaNumericFieldsNeeded[i];
372
                                if (alphaNumericFieldsNeeded[i]
373
                                                .equals(getLyrDef().getFieldID()))
374
                                        found = true;
375
                        }
376
                }
377
                // Nos aseguramos de pedir siempre el campo ID
378
                if (found == false)
379
                        strAux = strAux + ", " + getLyrDef().getFieldID();
380

    
381
                String sqlProv = "SELECT " + strAux + " FROM "
382
                                + getLyrDef().getTableName() + " ";
383
                                // + getLyrDef().getWhereClause();
384

    
385
                String sqlAux;
386
                sqlAux = sqlProv + getCompoundWhere(r, strEPSG);
387

    
388
                System.out.println("SqlAux getFeatureIterator = " + sqlAux);
389

    
390
                return getFeatureIterator(sqlAux);
391
        }
392

    
393
        public boolean isWritable() {
394
                return true;
395
        }
396

    
397
        public IWriter getWriter() {
398
                return writer;
399
        }
400

    
401
public String[] getTableFields(IConnection conex, String table) throws DBException {
402
                try{
403
                Statement st = ((ConnectionJDBC)conex).getConnection().createStatement();
404
        // ResultSet rs = dbmd.getTables(catalog, null, dbLayerDefinition.getTable(), null);
405
                ResultSet rs = st.executeQuery("select * from " + table + " LIMIT 1");
406
                ResultSetMetaData rsmd = rs.getMetaData();
407

    
408
                String[] ret = new String[rsmd.getColumnCount()];
409

    
410
                for (int i = 0; i < ret.length; i++) {
411
                        ret[i] = rsmd.getColumnName(i+1);
412
                }
413

    
414
                return ret;
415
                }catch (SQLException e) {
416
                        throw new DBException(e);
417
                }
418
        }
419

    
420

    
421
}