Statistics
| Revision:

svn-gvsig-desktop / trunk / extensions / extJDBC / src / com / iver / cit / gvsig / fmap / drivers / jdbc / postgis / PostGisDriver.java @ 5007

History | View | Annotate | Download (21.3 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.postgis;
45

    
46
import java.awt.geom.Rectangle2D;
47
import java.math.BigDecimal;
48
import java.nio.ByteBuffer;
49
import java.sql.Connection;
50
import java.sql.ResultSet;
51
import java.sql.SQLException;
52
import java.sql.Statement;
53
import java.sql.Types;
54
import java.util.Hashtable;
55
import java.util.Properties;
56

    
57
import org.apache.log4j.Logger;
58
import org.postgis.PGbox2d;
59
import org.postgis.PGbox3d;
60

    
61
import com.hardcode.gdbms.engine.data.edition.DataWare;
62
import com.hardcode.gdbms.engine.values.Value;
63
import com.hardcode.gdbms.engine.values.ValueFactory;
64
import com.iver.andami.messages.NotificationManager;
65
import com.iver.cit.gvsig.fmap.DriverException;
66
import com.iver.cit.gvsig.fmap.core.ICanReproject;
67
import com.iver.cit.gvsig.fmap.core.IGeometry;
68
import com.iver.cit.gvsig.fmap.drivers.DBLayerDefinition;
69
import com.iver.cit.gvsig.fmap.drivers.DefaultDBDriver;
70
import com.iver.cit.gvsig.fmap.drivers.DriverAttributes;
71
import com.iver.cit.gvsig.fmap.drivers.IFeatureIterator;
72
import com.iver.cit.gvsig.fmap.drivers.jdbc.WKBParser2;
73
import com.iver.cit.gvsig.fmap.edition.EditionException;
74
import com.iver.cit.gvsig.fmap.edition.IRowEdited;
75
import com.iver.cit.gvsig.fmap.edition.ISpatialWriter;
76
import com.iver.cit.gvsig.fmap.layers.FLayer;
77

    
78
/**
79
 * @author FJP
80
 * 
81
 * TODO To change the template for this generated type comment go to Window -
82
 * Preferences - Java - Code Generation - Code and Comments
83
 */
84
public class PostGisDriver extends DefaultDBDriver implements ICanReproject, ISpatialWriter {
85
        private static Logger logger = Logger.getLogger(PostGisDriver.class
86
                        .getName());
87
        
88
        private static int FETCH_SIZE = 5000;
89
        
90
        private PostGISWriter writer = new PostGISWriter();
91

    
92
        private WKBParser2 parser = new WKBParser2();
93

    
94
        private int fetch_min = -1;
95

    
96
        private int fetch_max = -1;
97

    
98
        private String sqlOrig;
99

    
100
        /**
101
         * Used by setAbsolutePosition
102
         */
103
        private String sqlTotal;
104

    
105
        private String strEPSG = null;
106

    
107
        private String originalEPSG = null;
108

    
109
        private Rectangle2D fullExtent = null;
110

    
111
        private String strAux;
112

    
113
        private String completeWhere;
114

    
115
        private String provCursorName = null;
116
        
117
        int numProvCursors = 0;
118

    
119
        static {
120
                try {
121
                        Class.forName("org.postgresql.Driver");
122
                } catch (ClassNotFoundException e) {
123
                        throw new RuntimeException(e);
124
                }
125
        }
126

    
127
        /**
128
         * 
129
         */
130
        public PostGisDriver() {
131
                
132
        }
133

    
134
        /*
135
         * (non-Javadoc)
136
         * 
137
         * @see com.iver.cit.gvsig.fmap.drivers.VectorialDriver#getDriverAttributes()
138
         */
139
        public DriverAttributes getDriverAttributes() {
140
                return null;
141
        }
142

    
143
        /*
144
         * (non-Javadoc)
145
         * 
146
         * @see com.hardcode.driverManager.Driver#getName()
147
         */
148
        public String getName() {
149
                return "PostGIS JDBC Driver";
150
        }
151

    
152
        /**
153
         * @see com.iver.cit.gvsig.fmap.layers.ReadableVectorial#getShape(int)
154
         */
155
        public IGeometry getShape(int index) {
156
                IGeometry geom = null;
157
                boolean resul;
158
                try {
159
                        setAbsolutePosition(index);
160
                        // strAux = rs.getString(1);
161
                        // geom = parser.read(strAux);
162
                        if (rs != null) {
163
                                byte[] data = rs.getBytes(1);
164
                                geom = parser.parse(data);
165
                        }
166
                } catch (SQLException e) {
167
                        e.printStackTrace();
168
                }
169

    
170
                return geom;
171
        }
172

    
173
        /**
174
         * First, the geometry field. After, the rest of fields
175
         * 
176
         * @return
177
         */
178
        /*
179
         * public String getTotalFields() { String strAux = "AsBinary(" +
180
         * getLyrDef().getFieldGeometry() + ")"; String[] fieldNames =
181
         * getLyrDef().getFieldNames(); for (int i=0; i< fieldNames.length; i++) {
182
         * strAux = strAux + ", " + fieldNames[i]; } return strAux; }
183
         */
184

    
185
        /**
186
         * Antes de llamar a esta funci?n hay que haber fijado el workingArea si se
187
         * quiere usar.
188
         * 
189
         * @param conn
190
         */
191
        public void setData(Connection conn, DBLayerDefinition lyrDef) {
192
                this.conn = conn;
193
                // TODO: Deber?amos poder quitar Conneciton de la llamada y meterlo
194
                // en lyrDef desde el principio.
195
                
196
                lyrDef.setConnection(conn);
197
                setLyrDef(lyrDef);
198

    
199
                getTableEPSG();
200

    
201
                try {
202
                        conn.setAutoCommit(false);
203
                        sqlOrig = "SELECT " + getTotalFields() + " FROM "
204
                                        + getLyrDef().getTableName() + " "
205
                                        + getLyrDef().getWhereClause();
206
                        if (canReproject(strEPSG)) {
207
                                completeWhere = getCompoundWhere(sqlOrig, workingArea, strEPSG);
208
                        } else {
209
                                completeWhere = getCompoundWhere(sqlOrig, workingArea,
210
                                                originalEPSG);
211
                        }
212
                        String sqlAux = sqlOrig + completeWhere + " ORDER BY "
213
                                        + getLyrDef().getFieldID();
214
                        completeWhere = getLyrDef().getWhereClause() + completeWhere;
215

    
216
                        sqlTotal = sqlAux;
217
                        logger.info("Cadena SQL:" + sqlAux);
218
                        st = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
219
                                        ResultSet.CONCUR_READ_ONLY);
220
                        // st.setFetchSize(FETCH_SIZE);
221
                        st.execute("declare wkb_cursor binary cursor for " + sqlAux);
222
                        rs = st.executeQuery("fetch forward " + FETCH_SIZE
223
                                        + " in wkb_cursor");
224
                        // st.execute("begin");
225
                        // bCursorActivo = true;
226
                        // rs = st.executeQuery(sqlOrig);
227
                        fetch_min = 0;
228
                        fetch_max = FETCH_SIZE - 1;
229
                        metaData = rs.getMetaData();
230
                        doRelateID_FID();
231

    
232
                } catch (SQLException e) {
233
                        NotificationManager.addError(
234
                                        "Error al conectar a la base de datos.", e);
235
                }
236
        }
237

    
238
        /**
239
         * @see com.iver.cit.gvsig.fmap.layers.ReadableVectorial#getFullExtent()
240
         */
241
        public Rectangle2D getFullExtent() {
242
                if (fullExtent == null) {
243
                        try {
244
                                Statement s = conn.createStatement();
245
                                ResultSet r = s.executeQuery("SELECT extent("
246
                                                + getLyrDef().getFieldGeometry()
247
                                                + ") AS FullExtent FROM " + getLyrDef().getTableName()
248
                                                + " " + getCompleteWhere());
249
                                r.next();
250
                                String strAux = r.getString(1);
251
                                System.out.println("fullExtent = " + strAux);
252
                                if (strAux.startsWith("BOX3D")) {
253
                                        PGbox3d regeom = new PGbox3d(strAux);
254
                                        double x = regeom.getLLB().x;
255
                                        double y = regeom.getLLB().y;
256
                                        double w = regeom.getURT().x - x;
257
                                        double h = regeom.getURT().y - y;
258
                                        fullExtent = new Rectangle2D.Double(x, y, w, h);
259
                                } else {
260
                                        PGbox2d regeom = new PGbox2d(strAux);
261
                                        double x = regeom.getLLB().x;
262
                                        double y = regeom.getLLB().y;
263
                                        double w = regeom.getURT().x - x;
264
                                        double h = regeom.getURT().y - y;
265
                                        fullExtent = new Rectangle2D.Double(x, y, w, h);
266
                                }
267
                        } catch (SQLException e) {
268
                                System.err.println(e.getMessage());
269
                        }
270

    
271
                }
272
                return fullExtent;
273
        }
274

    
275
        /*
276
         * (non-Javadoc)
277
         * 
278
         * @see com.iver.cit.gvsig.fmap.drivers.VectorialDatabaseDriver#getGeometryIterator(java.lang.String)
279
         */
280
        public IFeatureIterator getFeatureIterator(String sql)
281
                        throws com.iver.cit.gvsig.fmap.DriverException {
282
                PostGisFeatureIterator geomIterator = null;
283
                try {
284
                        // st = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
285
                        // ResultSet.CONCUR_READ_ONLY);
286

    
287
                        
288
                        if (provCursorName != null) {
289
                                /* st.execute("BEGIN");
290
                                st.execute("CLOSE " + provCursorName);
291
                                bCursorActivo = false;
292
                                st.execute("COMMIT"); */
293
                                numProvCursors++;
294
                        }
295
                        // st.execute("BEGIN");
296
                        provCursorName = "wkb_cursor_prov_" + System.currentTimeMillis() + "" + numProvCursors;
297

    
298
                        // st.execute("BEGIN");
299
                        bCursorActivo = true;
300
                        // ResultSet rs = st.executeQuery(sql);
301
                        geomIterator = new PostGisFeatureIterator(conn, provCursorName, sql);
302
                        geomIterator.setLyrDef(getLyrDef());
303
                } catch (SQLException e) {
304
                        e.printStackTrace();
305

    
306
                        throw new DriverException(e);
307
                        // return null;
308
                }
309

    
310
                return geomIterator;
311
        }
312

    
313
        public IFeatureIterator getFeatureIterator(Rectangle2D r, String strEPSG)
314
                        throws DriverException {
315
                if (workingArea != null)
316
                        r = r.createIntersection(workingArea);
317

    
318
                String sqlAux;
319
                if (canReproject(strEPSG)) {
320
                        sqlAux = sqlOrig + getCompoundWhere(sqlOrig, r, strEPSG);
321
                } else {
322
                        sqlAux = sqlOrig + getCompoundWhere(sqlOrig, r, originalEPSG);
323
                }
324

    
325
                System.out.println("SqlAux getFeatureIterator = " + sqlAux);
326

    
327
                return getFeatureIterator(sqlAux);
328
        }
329

    
330
        /**
331
         * Le pasas el rect?ngulo que quieres pedir. La primera vez es el
332
         * workingArea, y las siguientes una interseccion de este rectangulo con el
333
         * workingArea
334
         * 
335
         * @param r
336
         * @param strEPSG
337
         * @return
338
         */
339
        private String getCompoundWhere(String sql, Rectangle2D r, String strEPSG) {
340
                if (r == null)
341
                        return "";
342

    
343
                double xMin = r.getMinX();
344
                double yMin = r.getMinY();
345
                double xMax = r.getMaxX();
346
                double yMax = r.getMaxY();
347
                String wktBox = "GeometryFromText('LINESTRING(" + xMin + " " + yMin
348
                                + ", " + xMax + " " + yMin + ", " + xMax + " " + yMax + ", "
349
                                + xMin + " " + yMax + ")', " + strEPSG + ")";
350
                String sqlAux;
351
                if (getWhereClause().indexOf("WHERE") != -1)
352
                        sqlAux = getLyrDef().getFieldGeometry() + " && " + wktBox;
353
                else
354
                        sqlAux = "WHERE " + getLyrDef().getFieldGeometry() + " && "
355
                                        + wktBox;
356
                return sqlAux;
357
        }
358

    
359
        /**
360
         * @see com.iver.cit.gvsig.fmap.drivers.VectorialDatabaseDriver#getConnectionStringBeginning()
361
         */
362
        public String getConnectionStringBeginning() {
363
                return "jdbc:postgresql:";
364
        }
365

    
366
        /*
367
         * (non-Javadoc)
368
         * 
369
         * @see com.iver.cit.gvsig.fmap.drivers.DefaultDBDriver#getFieldValue(long,
370
         *      int)
371
         */
372
        public Value getFieldValue(long rowIndex, int idField)
373
                        throws com.hardcode.gdbms.engine.data.driver.DriverException {
374
                boolean resul;
375
                // EL ABSOLUTE NO HACE QUE SE VUELVAN A LEER LAS
376
                // FILAS, ASI QUE MONTAMOS ESTA HISTORIA PARA QUE
377
                // LO HAGA
378
                // System.out.println("getShape " + index);
379
                int index = (int) (rowIndex);
380
                try {
381
                        setAbsolutePosition(index);
382
                        int fieldId = idField + 2;
383
                        byte[] byteBuf = rs.getBytes(fieldId);
384
                        if (byteBuf == null)
385
                                return ValueFactory.createNullValue();
386
                        else {
387
                                ByteBuffer buf = ByteBuffer.wrap(byteBuf);
388
                                if (metaData.getColumnType(fieldId) == Types.VARCHAR)
389
                                        return ValueFactory.createValue(rs.getString(fieldId));
390
                                if (metaData.getColumnType(fieldId) == Types.FLOAT)
391
                                        return ValueFactory.createValue(buf.getFloat());
392
                                if (metaData.getColumnType(fieldId) == Types.DOUBLE)
393
                                        return ValueFactory.createValue(buf.getDouble());
394
                                if (metaData.getColumnType(fieldId) == Types.INTEGER)
395
                                        return ValueFactory.createValue(buf.getInt());
396
                                if (metaData.getColumnType(fieldId) == Types.BIGINT)
397
                                        return ValueFactory.createValue(buf.getLong());
398
                                if (metaData.getColumnType(fieldId) == Types.BIT)
399
                                        // TODO
400
                                        return ValueFactory.createValue(rs.getBoolean(fieldId));
401
                                if (metaData.getColumnType(fieldId) == Types.DATE)
402
                                        // TODO
403
                                        return ValueFactory.createValue(rs.getDate(fieldId));
404
                                if (metaData.getColumnType(fieldId) == Types.NUMERIC) {
405
                                        // System.out.println(metaData.getColumnName(fieldId) + " "
406
                                        // + metaData.getColumnClassName(fieldId));
407
                                        short ndigits = buf.getShort();
408
                                        short weight = buf.getShort();
409
                                        short sign = buf.getShort();
410
                                        short dscale = buf.getShort();
411
                                        String strAux;
412
                                        if (sign == 0)
413
                                                strAux = "+";
414
                                        else
415
                                                strAux = "-";
416

    
417
                                        for (int iDigit = 0; iDigit < ndigits; iDigit++) {
418
                                                short digit = buf.getShort();
419
                                                strAux = strAux + digit;
420
                                                if (iDigit == weight)
421
                                                        strAux = strAux + ".";
422

    
423
                                        }
424
                                        strAux = strAux + "0";
425
                                        String str2;
426
                                        BigDecimal dec;
427
                                        dec = new BigDecimal(strAux);
428
                                        // System.out.println(ndigits + "_" + weight + "_" + dscale
429
                                        // + "_" + strAux);
430
                                        // System.out.println(strAux + " Big= " + dec);
431
                                        return ValueFactory.createValue(dec.doubleValue());
432
                                }
433

    
434
                        }
435
                } catch (SQLException e) {
436
                        throw new com.hardcode.gdbms.engine.data.driver.DriverException(e
437
                                        .getMessage());
438
                }
439
                return ValueFactory.createNullValue();
440

    
441
        }
442

    
443
        public void open() throws com.iver.cit.gvsig.fmap.DriverException {
444
                /*
445
                 * try { st = conn.createStatement(); st.setFetchSize(2000); if
446
                 * (bCursorActivo) close(); st.execute("declare wkb_cursor binary cursor
447
                 * for " + sqlOrig); rs = st.executeQuery("fetch forward all in
448
                 * wkb_cursor"); // st.execute("BEGIN"); bCursorActivo = true; } catch
449
                 * (SQLException e) { e.printStackTrace(); throw new
450
                 * com.iver.cit.gvsig.fmap.DriverException(e); }
451
                 */
452

    
453
        }
454

    
455
        private void setAbsolutePosition(int index) throws SQLException {
456
                // TODO: USAR LIMIT Y ORDER BY, Y HACERLO TAMBI?N PARA
457
                // MYSQL
458

    
459
                // EL ABSOLUTE NO HACE QUE SE VUELVAN A LEER LAS
460
                // FILAS, ASI QUE MONTAMOS ESTA HISTORIA PARA QUE
461
                // LO HAGA
462
                // System.out.println("getShape " + index + " fetchMin=" + fetch_min + "
463
                // fetchMax=" + fetch_max);
464
                if (index < fetch_min) {
465
                        // rs.close();
466
                        st.execute("CLOSE wkb_cursor");
467
                        st.execute("declare wkb_cursor binary cursor for " + sqlTotal);
468
                        rs = st.executeQuery("fetch forward " + FETCH_SIZE
469
                                        + " in wkb_cursor");
470

    
471
                        // rs.beforeFirst();
472

    
473
                        // rs = st.executeQuery(sqlOrig);
474
                        fetch_min = 0;
475
                        fetch_max = FETCH_SIZE - 1;
476
                }
477
                while (index > fetch_max && index != 0) {
478
                        rs = st.executeQuery("fetch forward " + FETCH_SIZE
479
                                        + " in wkb_cursor");
480
                        // rs.next();
481
                        /*
482
                         * rs.afterLast(); // forzamos una carga rs.next();
483
                         */
484
                        fetch_min = fetch_max + 1;
485
                        fetch_max = fetch_min + FETCH_SIZE - 1;
486
                        // System.out.println("fetchSize = " + rs.getFetchSize() + " " +
487
                        // fetch_min + "-" + fetch_max);
488
                }
489
                if (rs != null)
490
                        rs.absolute(index - fetch_min + 1);
491

    
492
                // rs.absolute(index+1);
493

    
494
        }
495

    
496
        /**
497
         * @see com.iver.cit.gvsig.fmap.drivers.VectorialDatabaseDriver#getGeometryField(java.lang.String)
498
         */
499
        public String getGeometryField(String fieldName) {
500
                return "ASBINARY(" + fieldName + ", 'XDR')";
501
        }
502

    
503
        /**
504
         * @see com.hardcode.gdbms.engine.data.driver.ObjectDriver#getPrimaryKeys()
505
         */
506
        public int[] getPrimaryKeys()
507
                        throws com.hardcode.gdbms.engine.data.driver.DriverException {
508
                // TODO Auto-generated method stub
509
                return null;
510
        }
511

    
512
        /**
513
         * @see com.iver.cit.gvsig.fmap.drivers.VectorialJDBCDriver#getDefaultPort()
514
         */
515
        public int getDefaultPort() {
516
                return 5432;
517
        }
518

    
519
        /**
520
         * @see com.hardcode.gdbms.engine.data.driver.ObjectDriver#write(com.hardcode.gdbms.engine.data.edition.DataWare)
521
         */
522
        public void write(DataWare arg0)
523
                        throws com.hardcode.gdbms.engine.data.driver.DriverException {
524
                // TODO Auto-generated method stub
525

    
526
        }
527

    
528
        /*
529
         * (non-Javadoc)
530
         * 
531
         * @see com.iver.cit.gvsig.fmap.core.ICanReproject#getSourceProjection()
532
         */
533
        public String getSourceProjection() {
534
                if (originalEPSG == null)
535
                        getTableEPSG();
536
                return originalEPSG;
537
        }
538

    
539
        /**
540
         * Las tablas con geometr?as est?n en la tabla GEOMETRY_COLUMNS y de 
541
         * ah? sacamos en qu? proyecci?n est?n.
542
         * El problema es que si el usuario hace una vista de esa
543
         * tabla, no estar? dada de alta aqu? y entonces gvSIG
544
         * no se entera en qu? proyecci?n est? trabajando (y le
545
         * ponemos un -1 como mal menor). El -1 implica que luego
546
         * no podremos reproyectar al vuelo desde la base de datos.
547
         */
548
        private void getTableEPSG() {                
549
                try {
550
                        Statement stAux = conn.createStatement();
551

    
552
                        String sql = "SELECT * FROM GEOMETRY_COLUMNS WHERE F_TABLE_NAME = '"
553
                                        + getTableName() + "';";
554
                        ResultSet rs = stAux.executeQuery(sql);
555
                        rs.next();
556
                        originalEPSG = "" + rs.getInt("SRID");
557
                        rs.close();
558
                } catch (SQLException e) {
559
                        // TODO Auto-generated catch block
560
                        originalEPSG = "-1";
561
                        logger.error(e);
562
                        e.printStackTrace();
563
                }
564

    
565
        }
566

    
567
        /*
568
         * (non-Javadoc)
569
         * 
570
         * @see com.iver.cit.gvsig.fmap.core.ICanReproject#getDestProjection()
571
         */
572
        public String getDestProjection() {
573
                return strEPSG;
574
        }
575

    
576
        /*
577
         * (non-Javadoc)
578
         * 
579
         * @see com.iver.cit.gvsig.fmap.core.ICanReproject#setDestProjection(java.lang.String)
580
         */
581
        public void setDestProjection(String toEPSG) {
582
                this.strEPSG = toEPSG;
583
        }
584

    
585
        /*
586
         * (non-Javadoc)
587
         * 
588
         * @see com.iver.cit.gvsig.fmap.core.ICanReproject#canReproject(java.lang.String)
589
         */
590
        public boolean canReproject(String toEPSGdestinyProjection) {
591
                // TODO POR AHORA, REPROYECTA SIEMPRE gvSIG.
592
                return false;
593
        }
594

    
595
        /*
596
         * (non-Javadoc)
597
         * 
598
         * @see com.iver.cit.gvsig.fmap.drivers.DefaultDBDriver#doRelateID_FID()
599
         */
600
        protected void doRelateID_FID() {
601
                hashRelate = new Hashtable();
602
                try {
603
                        String strSQL = "SELECT " + getLyrDef().getFieldID() + " FROM "
604
                                        + getLyrDef().getTableName() + " "
605
                                        + getLyrDef().getWhereClause();
606
                        if (canReproject(strEPSG)) {
607
                                strSQL = strSQL
608
                                                + getCompoundWhere(strSQL, workingArea, strEPSG);
609
                        } else {
610
                                strSQL = strSQL
611
                                                + getCompoundWhere(strSQL, workingArea, originalEPSG);
612
                        }
613
                        String sqlAux = strSQL + " ORDER BY " + getLyrDef().getFieldID();
614
                        Statement s = getConnection().createStatement(
615
                                        ResultSet.TYPE_SCROLL_INSENSITIVE,
616
                                        ResultSet.CONCUR_READ_ONLY);
617
                        int fetchSize = 5000;
618
                        ResultSet r = s.executeQuery(strSQL);
619
                        int id = 0;
620
                        String gid;
621
                        while (r.next()) {
622
                                gid = r.getString(1);
623
                                Value aux = ValueFactory.createValue(gid);
624
                                hashRelate.put(aux, new Integer(id));
625
                                // System.out.println("ASOCIANDO CLAVE " + aux + " CON VALOR " +
626
                                // id);
627
                                id++;
628
                                // System.out.println("Row " + id + ":" + strAux);
629
                        }
630
                        s.close();
631
                        numReg = id;
632

    
633
                        /*
634
                         * for (int index = 0; index < getShapeCount(); index++) { Value aux =
635
                         * getFieldValue(index, idFID_FieldName-2); hashRelate.put(aux, new
636
                         * Integer(index)); // System.out.println("Row " + index + " clave=" +
637
                         * aux); }
638
                         */
639
                        /*
640
                         * int index = 0;
641
                         * 
642
                         * while (rs.next()) { Value aux = getFieldValue(index,
643
                         * idFID_FieldName-2); hashRelate.put(aux, new Integer(index));
644
                         * index++; System.out.println("Row " + index + " clave=" + aux); }
645
                         * numReg = index;
646
                         */
647
                        // rs.beforeFirst();
648
                        /*
649
                         * } catch (com.hardcode.gdbms.engine.data.driver.DriverException e) { //
650
                         * TODO Auto-generated catch block e.printStackTrace();
651
                         */
652
                } catch (SQLException e) {
653
                        // TODO Auto-generated catch block
654
                        e.printStackTrace();
655
                }
656
        }
657

    
658
        public String getSqlTotal() {
659
                return sqlTotal;
660
        }
661

    
662
        /**
663
         * @return Returns the completeWhere.
664
         */
665
        public String getCompleteWhere() {
666
                return completeWhere;
667
        }
668

    
669
        /*
670
         * (non-Javadoc)
671
         * 
672
         * @see com.iver.cit.gvsig.fmap.drivers.DefaultDBDriver#close()
673
         */
674
        public void close() {
675
                super.close();
676
                /*
677
                 * if (bCursorActivo) { try { // st =
678
                 * conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
679
                 * ResultSet.CONCUR_READ_ONLY); st.execute("CLOSE wkb_cursor_prov"); //
680
                 * st.close(); } catch (SQLException e) { // TODO Auto-generated catch
681
                 * block e.printStackTrace(); } bCursorActivo = false; }
682
                 */
683

    
684
        }
685

    
686
        /*
687
         * (non-Javadoc)
688
         * 
689
         * @see com.iver.cit.gvsig.fmap.drivers.VectorialDatabaseDriver#getFeatureIterator(java.awt.geom.Rectangle2D,
690
         *      java.lang.String, java.lang.String[])
691
         */
692
        public IFeatureIterator getFeatureIterator(Rectangle2D r, String strEPSG,
693
                        String[] alphaNumericFieldsNeeded) throws DriverException {
694
                try {
695
                        if (workingArea != null)
696
                                r = r.createIntersection(workingArea);
697
                        // if (getLyrDef()==null){
698
                        // load();
699
                        // throw new DriverException("Fallo de la conexi?n");
700
                        // }
701
                        String strAux = getGeometryField(getLyrDef().getFieldGeometry());
702

    
703
                        boolean found = false;
704
                        if (alphaNumericFieldsNeeded != null) {
705
                                for (int i = 0; i < alphaNumericFieldsNeeded.length; i++) {
706
                                        strAux = strAux + ", " + alphaNumericFieldsNeeded[i];
707
                                        if (alphaNumericFieldsNeeded[i].equals(getLyrDef()
708
                                                        .getFieldID()))
709
                                                found = true;
710
                                }
711
                        }
712
                        // Nos aseguramos de pedir siempre el campo ID
713
                        if (found == false)
714
                                strAux = strAux + ", " + getLyrDef().getFieldID();
715

    
716
                        String sqlProv = "SELECT " + strAux + " FROM "
717
                                        + getLyrDef().getTableName() + " "
718
                                        + getLyrDef().getWhereClause();
719

    
720
                        String sqlAux;
721
                        if (canReproject(strEPSG)) {
722
                                sqlAux = sqlProv + getCompoundWhere(sqlProv, r, strEPSG);
723
                        } else {
724
                                sqlAux = sqlProv + getCompoundWhere(sqlProv, r, originalEPSG);
725
                        }
726

    
727
                        System.out.println("SqlAux getFeatureIterator = " + sqlAux);
728

    
729
                        return getFeatureIterator(sqlAux);
730
                } catch (Exception e) {
731
                        throw new DriverException(e);
732
                }
733
        }
734

    
735
        public void preProcess() throws EditionException {
736
                writer.preProcess();
737
        }
738

    
739
        public void process(IRowEdited row) throws EditionException {
740
                writer.process(row);
741
        }
742

    
743
        public void postProcess() throws EditionException {
744
                writer.postProcess();
745
        }
746

    
747
        public String getCapability(String capability) {
748
                return writer.getCapability(capability);
749
        }
750

    
751
        public void setCapabilities(Properties capabilities) {
752
                writer.setCapabilities(capabilities);
753
        }
754

    
755
        public boolean canWriteAttribute(int sqlType) {
756
                return writer.canWriteAttribute(sqlType);
757
        }
758

    
759
        public boolean canWriteGeometry(int gvSIGgeometryType) {
760
                return writer.canWriteGeometry(gvSIGgeometryType);
761
        }
762

    
763
        public void initialize(FLayer layer) throws EditionException {                
764
                writer.setCreateTable(false);
765
                writer.setWriteAll(false);
766
                // Obtenemos el DBLayerDefinition a partir del driver
767
                
768
                DBLayerDefinition dbLyrDef = getLyrDef(); 
769
                
770
                
771
                writer.initialize(dbLyrDef);
772
        }
773

    
774
}