Statistics
| Revision:

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

History | View | Annotate | Download (21.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.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.WKBParser;
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;
91

    
92
        private WKBParser parser = new WKBParser();
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
         * (non-Javadoc)
135
         * 
136
         * @see com.iver.cit.gvsig.fmap.drivers.VectorialDriver#getDriverAttributes()
137
         */
138
        public DriverAttributes getDriverAttributes() {
139
                return null;
140
        }
141

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

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

    
169
                return geom;
170
        }
171

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

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

    
197
                getTableEPSG();
198

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

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

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

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

    
268
                }
269
                return fullExtent;
270
        }
271

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

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

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

    
303
                        throw new DriverException(e);
304
                        // return null;
305
                }
306

    
307
                return geomIterator;
308
        }
309

    
310
        public IFeatureIterator getFeatureIterator(Rectangle2D r, String strEPSG)
311
                        throws DriverException {
312
                if (workingArea != null)
313
                        r = r.createIntersection(workingArea);
314

    
315
                String sqlAux;
316
                if (canReproject(strEPSG)) {
317
                        sqlAux = sqlOrig + getCompoundWhere(sqlOrig, r, strEPSG);
318
                } else {
319
                        sqlAux = sqlOrig + getCompoundWhere(sqlOrig, r, originalEPSG);
320
                }
321

    
322
                System.out.println("SqlAux getFeatureIterator = " + sqlAux);
323

    
324
                return getFeatureIterator(sqlAux);
325
        }
326

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

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

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

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

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

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

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

    
438
        }
439

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

    
450
        }
451

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

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

    
468
                        // rs.beforeFirst();
469

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

    
489
                // rs.absolute(index+1);
490

    
491
        }
492

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

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

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

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

    
523
        }
524

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

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

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

    
562
        }
563

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

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

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

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

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

    
655
        public String getSqlTotal() {
656
                return sqlTotal;
657
        }
658

    
659
        /**
660
         * @return Returns the completeWhere.
661
         */
662
        public String getCompleteWhere() {
663
                return completeWhere;
664
        }
665

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

    
681
        }
682

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

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

    
713
                        String sqlProv = "SELECT " + strAux + " FROM "
714
                                        + getLyrDef().getTableName() + " "
715
                                        + getLyrDef().getWhereClause();
716

    
717
                        String sqlAux;
718
                        if (canReproject(strEPSG)) {
719
                                sqlAux = sqlProv + getCompoundWhere(sqlProv, r, strEPSG);
720
                        } else {
721
                                sqlAux = sqlProv + getCompoundWhere(sqlProv, r, originalEPSG);
722
                        }
723

    
724
                        System.out.println("SqlAux getFeatureIterator = " + sqlAux);
725

    
726
                        return getFeatureIterator(sqlAux);
727
                } catch (Exception e) {
728
                        throw new DriverException(e);
729
                }
730
        }
731

    
732
        public void preProcess() throws EditionException {
733
                writer.preProcess();
734
        }
735

    
736
        public void process(IRowEdited row) throws EditionException {
737
                writer.process(row);
738
        }
739

    
740
        public void postProcess() throws EditionException {
741
                writer.postProcess();
742
        }
743

    
744
        public String getCapability(String capability) {
745
                return writer.getCapability(capability);
746
        }
747

    
748
        public void setCapabilities(Properties capabilities) {
749
                writer.setCapabilities(capabilities);
750
        }
751

    
752
        public boolean canWriteAttribute(int sqlType) {
753
                return writer.canWriteAttribute(sqlType);
754
        }
755

    
756
        public boolean canWriteGeometry(int gvSIGgeometryType) {
757
                return writer.canWriteGeometry(gvSIGgeometryType);
758
        }
759

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

    
772
}