Statistics
| Revision:

svn-gvsig-desktop / tags / Root_v061 / extensions / extJDBC / src / com / iver / cit / gvsig / fmap / drivers / jdbc / mysql / MySQLDriver.java @ 4812

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