Statistics
| Revision:

svn-gvsig-desktop / trunk / extensions / extJDBC / src / com / iver / cit / gvsig / fmap / drivers / jdbc / mysql / MySQLDriver.java @ 3476

History | View | Annotate | Download (11.8 KB)

1 2269 fjp
/*
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.SQLException;
50
import java.sql.Statement;
51
52 3251 fjp
import org.apache.log4j.Logger;
53 3095 fjp
import org.cresques.cts.ICoordTrans;
54
55 2269 fjp
import com.hardcode.gdbms.engine.data.edition.DataWare;
56 3095 fjp
import com.iver.andami.messages.NotificationManager;
57 2269 fjp
import com.iver.cit.gvsig.fmap.DriverException;
58
import com.iver.cit.gvsig.fmap.core.IGeometry;
59 3251 fjp
import com.iver.cit.gvsig.fmap.drivers.DBLayerDefinition;
60 2269 fjp
import com.iver.cit.gvsig.fmap.drivers.DefaultDBDriver;
61
import com.iver.cit.gvsig.fmap.drivers.DriverAttributes;
62
import com.iver.cit.gvsig.fmap.drivers.IFeatureIterator;
63 3095 fjp
import com.iver.cit.gvsig.fmap.drivers.WKTParser;
64 2302 fjp
import com.iver.cit.gvsig.fmap.drivers.jdbc.WKBParser;
65 3251 fjp
import com.iver.cit.gvsig.fmap.drivers.jdbc.postgis.PostGisDriver;
66 3095 fjp
import com.vividsolutions.jts.io.ParseException;
67 2269 fjp
68
/**
69
 * @author FJP
70
 *
71
 * TODO To change the template for this generated type comment go to
72
 * Window - Preferences - Java - Code Generation - Code and Comments
73
 */
74
public class MySQLDriver extends DefaultDBDriver {
75 3251 fjp
    private static Logger logger = Logger.getLogger(MySQLDriver.class.getName());
76 2269 fjp
    private WKBParser parser = new WKBParser();
77 3095 fjp
    private WKTParser wktParser = new WKTParser();
78 2269 fjp
    /* private int fetch_min=-1;
79
    private int fetch_max=-1; */
80
    private Statement st;
81 3268 fjp
82 2269 fjp
    private String strAux;
83 3095 fjp
    private String strEPSG = "-1";
84
    private String originalEPSG;
85 3251 fjp
    private String completeWhere;
86 2269 fjp
    /**
87 3251 fjp
     * Don't have information about working area
88
     */
89
    private String sqlOrig;
90
91
92
    /**
93
     * Does have information about working area and order
94
     */
95
    private String sqlTotal;
96
97
    /**
98 2269 fjp
     *
99
     */
100
    public MySQLDriver() {
101
    }
102
    /* (non-Javadoc)
103
     * @see com.iver.cit.gvsig.fmap.drivers.VectorialDriver#getDriverAttributes()
104
     */
105
    public DriverAttributes getDriverAttributes() {
106
        return null;
107
    }
108
109
    /* (non-Javadoc)
110
     * @see com.hardcode.driverManager.Driver#getName()
111
     */
112
    public String getName() {
113
        return "mySQL JDBC Driver";
114
    }
115
116
        /**
117
         * @see com.iver.cit.gvsig.fmap.layers.ReadableVectorial#getShape(int)
118
         */
119
        public IGeometry getShape(int index) {
120
            IGeometry geom = null;
121
            boolean resul;
122
                try {
123
                    // EL ABSOLUTE NO HACE QUE SE VUELVAN A LEER LAS
124
                    // FILAS, ASI QUE MONTAMOS ESTA HISTORIA PARA QUE
125
                    // LO HAGA
126
                    // System.out.println("getShape " + index);
127
                    /* if (index < fetch_min)
128
                    {
129
                        rs.close();
130

131
                            rs = st.executeQuery(sqlOrig);
132
                        fetch_min = 0;
133
                        fetch_max = rs.getFetchSize();
134
                    }
135
                    while (index >= fetch_max)
136
                    {
137
                        rs.last();
138
                        // forzamos una carga
139
                        rs.next();
140
                        fetch_min = fetch_max;
141
                        fetch_max = fetch_max + rs.getFetchSize();
142
                        // System.out.println("fetchSize = " + rs.getFetchSize() + " " + fetch_min + "-" + fetch_max);
143
                    }
144
                    rs.absolute(index+1 - fetch_min); */
145
                    rs.absolute(index+1);
146
                    // strAux = rs.getString(1);
147
                    // geom = parser.read(strAux);
148
                    byte[] data = rs.getBytes(1);
149
                    geom = parser.parse(data);
150
151
152
            } catch (SQLException e) {
153
                e.printStackTrace();
154
            }
155
156
            return geom;
157
        }
158 3251 fjp
159
160 2269 fjp
        /**
161
         * @param conn
162
         */
163 2778 fjp
        /* (non-Javadoc)
164
         * @see com.iver.cit.gvsig.fmap.drivers.VectorialJDBCDriver#setData(java.sql.Connection, java.lang.String, java.lang.String, java.lang.String, int)
165
         */
166 3251 fjp
        public void setData(Connection conn, DBLayerDefinition lyrDef)
167 2269 fjp
        {
168 3251 fjp
            this.conn = conn;
169
        setLyrDef(lyrDef);
170 2269 fjp
            try {
171 3095 fjp
172
            // NO ESTA LISTO ESTO AUN EN mySQL, o no s? usuarlo getTableEPSG();
173
174 3251 fjp
        sqlOrig = "SELECT " + getTotalFields() + " FROM " + getLyrDef().getTableName()
175
            + " " + getLyrDef().getWhereClause();
176
        completeWhere = getCompoundWhere(workingArea, strEPSG);
177 3268 fjp
        completeWhere  = completeWhere ;
178
        String sqlAux = sqlOrig + completeWhere + " ORDER BY " + getLyrDef().getFieldID();
179 3251 fjp
        completeWhere = getLyrDef().getWhereClause() + completeWhere;
180
        logger.info("Cadena SQL:" + sqlAux);
181
        sqlTotal = sqlAux;
182
183
184 2269 fjp
                st = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
185 3251 fjp
186
                rs = st.executeQuery(sqlTotal);
187 2269 fjp
            metaData = rs.getMetaData();
188
            // Le pegamos un primera pasada para poder relacionar
189
            // un campo de identificador ?nico (parecido al OID en
190
            // postgresql) con el ?ndice dentro del recordset.
191
            // Esto cuando haya ediciones, no es v?lido, y hay
192
            // que refrescarlo.
193
            doRelateID_FID();
194
195
        } catch (SQLException e) {
196 3095 fjp
            NotificationManager.addError("Error al conectar a la base de datos.",e);
197 2269 fjp
            e.printStackTrace();
198
        }
199
        }
200
201
    /* (non-Javadoc)
202
     * @see com.iver.cit.gvsig.fmap.drivers.VectorialDatabaseDriver#getGeometryIterator(java.lang.String)
203
     */
204
    public IFeatureIterator getFeatureIterator(String sql) throws com.iver.cit.gvsig.fmap.DriverException {
205
        Statement st;
206
        MySqlFeatureIterator geomIterator = null;
207
        try {
208 3251 fjp
            logger.debug(sql);
209 2269 fjp
            st = conn.createStatement();
210
            // st.setFetchSize(2000);
211
            ResultSet rs = st.executeQuery(sql);
212
            geomIterator = new MySqlFeatureIterator(rs);
213 3347 fjp
            geomIterator.setLyrDef(getLyrDef());
214 2269 fjp
        } catch (SQLException e) {
215
            e.printStackTrace();
216
            throw new com.iver.cit.gvsig.fmap.DriverException(e);
217
        }
218
219
        return geomIterator;
220
    }
221
    /* (non-Javadoc)
222
     * @see com.iver.cit.gvsig.fmap.drivers.VectorialDatabaseDriver#getGeometryIterator(java.awt.geom.Rectangle2D)
223
     */
224
    public IFeatureIterator getFeatureIterator(Rectangle2D r, String strEPSG) throws DriverException {
225
        if (workingArea != null)
226 3251 fjp
            r = r.createIntersection(workingArea);
227
        String sqlAux = sqlOrig + getCompoundWhere(r, strEPSG);
228 3095 fjp
229
        return getFeatureIterator(sqlAux);
230
    }
231
232
    /**
233
     * Le pasas el rect?ngulo que quieres pedir. La primera
234
     * vez es el workingArea, y las siguientes una interseccion
235
     * de este rectangulo con el workingArea
236
     * @param r
237
     * @param strEPSG
238
     * @return
239
     */
240
    private String getCompoundWhere(Rectangle2D r, String strEPSG) {
241
        if (r==null)
242 3251 fjp
            return "";
243 3095 fjp
244 2269 fjp
        double xMin = r.getMinX();
245
        double yMin = r.getMinY();
246
        double xMax = r.getMaxX();
247
        double yMax = r.getMaxY();
248
249
        String wktBox = "GeomFromText('LINESTRING(" + xMin + " " + yMin + ", "
250 3095 fjp
        + xMax + " " + yMin + ", "
251
        + xMax + " " + yMax + ", "
252
        + xMin + " " + yMax + ")', "
253
        + strEPSG + ")";
254 2269 fjp
        String sqlAux;
255
        if (getWhereClause().startsWith("WHERE"))
256 3251 fjp
            sqlAux = " MBRIntersects(" + wktBox + ",ogc_geom)" ;
257 2269 fjp
        else
258 3251 fjp
            sqlAux = "WHERE MBRIntersects(" + wktBox + ",ogc_geom)" ;
259 3095 fjp
        return sqlAux;
260
    }
261 2269 fjp
262 3095 fjp
263 2269 fjp
    public void open() {
264
        // TODO Auto-generated method stub
265
266
    }
267
        /**
268
         * @see com.iver.cit.gvsig.fmap.drivers.VectorialDatabaseDriver#getConnectionStringBeginning()
269
         */
270
        public String getConnectionStringBeginning() {
271
                return "jdbc:mysql:";
272
        }
273
274
    static{
275
            try {
276
                        Class.forName("com.mysql.jdbc.Driver");
277
                } catch (ClassNotFoundException e) {
278
                        throw new RuntimeException(e);
279
                }
280
    }
281
282
        /**
283
         * @see com.iver.cit.gvsig.fmap.drivers.VectorialDatabaseDriver#getGeometryField(java.lang.String)
284
         */
285
        public String getGeometryField(String fieldName) {
286
                return "ASBINARY(" + fieldName +")";
287
        }
288
    /**
289
     * @see com.hardcode.gdbms.engine.data.driver.ObjectDriver#getPrimaryKeys()
290
     */
291
    public int[] getPrimaryKeys() throws com.hardcode.gdbms.engine.data.driver.DriverException {
292 3251 fjp
        return new int[]{getLyrDef().getIdFieldID() - 2};
293 2269 fjp
    }
294
    /**
295
     * @see com.iver.cit.gvsig.fmap.drivers.VectorialJDBCDriver#getDefaultPort()
296
     */
297
    public int getDefaultPort() {
298
        return 3306;
299
    }
300
    /**
301
     * @see com.hardcode.gdbms.engine.data.driver.ObjectDriver#write(com.hardcode.gdbms.engine.data.edition.DataWare)
302
     */
303
    public void write(DataWare arg0) throws com.hardcode.gdbms.engine.data.driver.DriverException {
304
        // TODO Auto-generated method stub
305
306
    }
307
308 3095 fjp
    private void getTableEPSG()
309
    {
310
        try {
311
            Statement stAux = conn.createStatement();
312
313
            String sql = "SELECT SRID(ogc_geom) FROM " +
314
                getTableName() + " LIMIT 1;";
315
            ResultSet rs = stAux.executeQuery(sql);
316
            rs.next();
317
            originalEPSG = "" + rs.getInt(1);
318
            rs.close();
319
        } catch (SQLException e) {
320
            // TODO Auto-generated catch block
321
            e.printStackTrace();
322
        }
323
324
    }
325 3251 fjp
    public String getSqlTotal()
326
    {
327
        return sqlTotal;
328
    }
329
    /**
330
     * @return Returns the completeWhere.
331
     */
332
    public String getCompleteWhere() {
333
        return completeWhere;
334
    }
335 3095 fjp
336 3268 fjp
    /* (non-Javadoc)
337
     * @see com.iver.cit.gvsig.fmap.drivers.VectorialDatabaseDriver#getFeatureIterator(java.awt.geom.Rectangle2D, java.lang.String, java.lang.String[])
338
     */
339
    public IFeatureIterator getFeatureIterator(Rectangle2D r, String strEPSG, String[] alphaNumericFieldsNeeded) throws DriverException {
340
        if (workingArea != null)
341
            r = r.createIntersection(workingArea);
342
343
        String strAux = getGeometryField(getLyrDef().getFieldGeometry());
344
        boolean found = false;
345
        if (alphaNumericFieldsNeeded != null)
346
        {
347
            for (int i=0; i< alphaNumericFieldsNeeded.length; i++)
348
            {
349
                strAux = strAux + ", " + alphaNumericFieldsNeeded[i];
350
                if (alphaNumericFieldsNeeded[i].equals(getLyrDef().getFieldID()))
351
                    found = true;
352
            }
353
        }
354
        // Nos aseguramos de pedir siempre el campo ID
355
        if (found == false)
356
            strAux = strAux + ", " + getLyrDef().getFieldID();
357
358
        String sqlProv = "SELECT " + strAux + " FROM " + getLyrDef().getTableName()
359
        + " " + getLyrDef().getWhereClause();
360
361
        String sqlAux;
362
        sqlAux = sqlProv + getCompoundWhere(r, strEPSG);
363
364
        System.out.println("SqlAux getFeatureIterator = " + sqlAux);
365
366
        return getFeatureIterator(sqlAux);
367
    }
368 2269 fjp
369 3268 fjp
370 2269 fjp
}