Statistics
| Revision:

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

History | View | Annotate | Download (11.9 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.SQLException;
50
import java.sql.Statement;
51

    
52
import org.apache.log4j.Logger;
53
import org.cresques.cts.ICoordTrans;
54

    
55
import com.hardcode.gdbms.engine.data.edition.DataWare;
56
import com.iver.andami.messages.NotificationManager;
57
import com.iver.cit.gvsig.fmap.DriverException;
58
import com.iver.cit.gvsig.fmap.core.IGeometry;
59
import com.iver.cit.gvsig.fmap.drivers.DBLayerDefinition;
60
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
import com.iver.cit.gvsig.fmap.drivers.WKTParser;
64
import com.iver.cit.gvsig.fmap.drivers.jdbc.WKBParser;
65
import com.iver.cit.gvsig.fmap.drivers.jdbc.postgis.PostGisDriver;
66
import com.vividsolutions.jts.io.ParseException;
67

    
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
    private static Logger logger = Logger.getLogger(MySQLDriver.class.getName());
76
    private WKBParser parser = new WKBParser();
77
    private WKTParser wktParser = new WKTParser();
78
    /* private int fetch_min=-1;
79
    private int fetch_max=-1; */
80
    private Statement st;
81
    
82
    private String strAux;
83
    private String strEPSG = "-1";
84
    private String originalEPSG;
85
    private String completeWhere;
86
    /**
87
     * 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
     * 
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
                    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
                    
153
                    
154
            } catch (SQLException e) {
155
                e.printStackTrace();
156
            }
157
                
158
            return geom;
159
        }
160
    
161
    
162
        /**
163
         * @param conn
164
         */
165
        /* (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
        public void setData(Connection conn, DBLayerDefinition lyrDef)
169
        {
170
            this.conn = conn;        
171
        setLyrDef(lyrDef);
172
            try {
173
            
174
            // NO ESTA LISTO ESTO AUN EN mySQL, o no s? usuarlo getTableEPSG();
175
            
176
        sqlOrig = "SELECT " + getTotalFields() + " FROM " + getLyrDef().getTableName()
177
            + " " + getLyrDef().getWhereClause(); 
178
        completeWhere = getCompoundWhere(workingArea, strEPSG);
179
        completeWhere  = completeWhere ;
180
        String sqlAux = sqlOrig + completeWhere + " ORDER BY " + getLyrDef().getFieldID();
181
        completeWhere = getLyrDef().getWhereClause() + completeWhere;
182
        logger.info("Cadena SQL:" + sqlAux);
183
        sqlTotal = sqlAux;
184

    
185
            
186
                st = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
187
                        
188
                rs = st.executeQuery(sqlTotal);
189
            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
            NotificationManager.addError("Error al conectar a la base de datos.",e);
199
            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
            logger.debug(sql);
211
            st = conn.createStatement();
212
            // st.setFetchSize(2000);
213
            ResultSet rs = st.executeQuery(sql);
214
            geomIterator = new MySqlFeatureIterator(rs);
215
            geomIterator.setLyrDef(getLyrDef());
216
        } 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
            r = r.createIntersection(workingArea);
229
        String sqlAux = sqlOrig + getCompoundWhere(r, strEPSG);
230

    
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
            return "";
245
        
246
        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
        + xMax + " " + yMin + ", "
253
        + xMax + " " + yMax + ", "
254
        + xMin + " " + yMax + ")', "
255
        + strEPSG + ")";
256
        String sqlAux;
257
        if (getWhereClause().startsWith("WHERE")) 
258
            sqlAux = " MBRIntersects(" + wktBox + ",ogc_geom)" ;
259
        else
260
            sqlAux = "WHERE MBRIntersects(" + wktBox + ",ogc_geom)" ;
261
        return sqlAux;
262
    }
263

    
264
    
265
    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
        return new int[]{getLyrDef().getIdFieldID() - 2};
295
    }
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
    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
    public String getSqlTotal()
328
    {
329
        return sqlTotal;
330
    }
331
    /**
332
     * @return Returns the completeWhere.
333
     */
334
    public String getCompleteWhere() {
335
        return completeWhere;
336
    }
337

    
338
    /* (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
    
371
    
372
}