Statistics
| Revision:

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

History | View | Annotate | Download (21.4 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.ITableDefinition;
73
import com.iver.cit.gvsig.fmap.drivers.jdbc.WKBParser2;
74
import com.iver.cit.gvsig.fmap.edition.EditionException;
75
import com.iver.cit.gvsig.fmap.edition.IRowEdited;
76
import com.iver.cit.gvsig.fmap.edition.ISpatialWriter;
77
import com.iver.cit.gvsig.fmap.layers.FLayer;
78

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

    
89
        private static int FETCH_SIZE = 5000;
90

    
91
        private PostGISWriter writer = new PostGISWriter();
92

    
93
        private WKBParser2 parser = new WKBParser2();
94

    
95
        private int fetch_min = -1;
96

    
97
        private int fetch_max = -1;
98

    
99
        private String sqlOrig;
100

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

    
106
        private String strEPSG = null;
107

    
108
        private String originalEPSG = null;
109

    
110
        private Rectangle2D fullExtent = null;
111

    
112
        private String strAux;
113

    
114
        private String completeWhere;
115

    
116
        private String provCursorName = null;
117

    
118
        int numProvCursors = 0;
119

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

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

    
133
        }
134

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

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

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

    
171
                return geom;
172
        }
173

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

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

    
197
                lyrDef.setConnection(conn);
198
                setLyrDef(lyrDef);
199

    
200
                getTableEPSG();
201

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

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

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

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

    
272
                }
273
                return fullExtent;
274
        }
275

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

    
288

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

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

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

    
311
                return geomIterator;
312
        }
313

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

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

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

    
328
                return getFeatureIterator(sqlAux);
329
        }
330

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

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

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

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

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

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

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

    
442
        }
443

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

    
454
        }
455

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

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

    
472
                        // rs.beforeFirst();
473

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

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

    
495
        }
496

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

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

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

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

    
527
        }
528

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

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

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

    
566
        }
567

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

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

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

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

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

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

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

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

    
685
        }
686

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

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

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

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

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

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

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

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

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

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

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

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

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

    
764
        public void initialize(ITableDefinition layerDef) throws EditionException {
765
                writer.setCreateTable(false);
766
                writer.setWriteAll(false);
767
                // Obtenemos el DBLayerDefinition a partir del driver
768

    
769
                DBLayerDefinition dbLyrDef = getLyrDef();
770

    
771

    
772
                writer.initialize(dbLyrDef);
773
        }
774

    
775
        public boolean isWritable() {
776
                // TODO Auto-generated method stub
777
                return true;
778
        }
779

    
780

    
781
}