Statistics
| Revision:

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

History | View | Annotate | Download (21.7 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.edition.IWriteable;
78
import com.iver.cit.gvsig.fmap.edition.IWriter;
79
import com.iver.cit.gvsig.fmap.layers.FLayer;
80

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

    
91
        private static int FETCH_SIZE = 5000;
92

    
93
        private PostGISWriter writer = new PostGISWriter();
94

    
95
        private WKBParser2 parser = new WKBParser2();
96

    
97
        private int fetch_min = -1;
98

    
99
        private int fetch_max = -1;
100

    
101
        private String sqlOrig;
102

    
103
        /**
104
         * Used by setAbsolutePosition
105
         */
106
        private String sqlTotal;
107

    
108
        private String strEPSG = null;
109

    
110
        private String originalEPSG = null;
111

    
112
        private Rectangle2D fullExtent = null;
113

    
114
        private String strAux;
115

    
116
        private String completeWhere;
117

    
118
        private String provCursorName = null;
119

    
120
        int numProvCursors = 0;
121

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

    
130
        /**
131
         *
132
         */
133
        public PostGisDriver() {
134

    
135
        }
136

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

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

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

    
173
                return geom;
174
        }
175

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

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

    
199
                lyrDef.setConnection(conn);
200
                setLyrDef(lyrDef);
201

    
202
                getTableEPSG();
203

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

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

    
239

    
240
                } catch (SQLException e) {
241
                        NotificationManager.addError(
242
                                        "Error al conectar a la base de datos.", e);
243
                } catch (EditionException e) {
244
                        e.printStackTrace();
245
                        NotificationManager.addError(
246
                                        "Error inicializando PosGIS Writer.", e);
247
                        
248
                }
249
        }
250

    
251
        /**
252
         * @see com.iver.cit.gvsig.fmap.layers.ReadableVectorial#getFullExtent()
253
         */
254
        public Rectangle2D getFullExtent() {
255
                if (fullExtent == null) {
256
                        try {
257
                                Statement s = conn.createStatement();
258
                                ResultSet r = s.executeQuery("SELECT extent("
259
                                                + getLyrDef().getFieldGeometry()
260
                                                + ") AS FullExtent FROM " + getLyrDef().getTableName()
261
                                                + " " + getCompleteWhere());
262
                                r.next();
263
                                String strAux = r.getString(1);
264
                                System.out.println("fullExtent = " + strAux);
265
                                if (strAux.startsWith("BOX3D")) {
266
                                        PGbox3d regeom = new PGbox3d(strAux);
267
                                        double x = regeom.getLLB().x;
268
                                        double y = regeom.getLLB().y;
269
                                        double w = regeom.getURT().x - x;
270
                                        double h = regeom.getURT().y - y;
271
                                        fullExtent = new Rectangle2D.Double(x, y, w, h);
272
                                } else {
273
                                        PGbox2d regeom = new PGbox2d(strAux);
274
                                        double x = regeom.getLLB().x;
275
                                        double y = regeom.getLLB().y;
276
                                        double w = regeom.getURT().x - x;
277
                                        double h = regeom.getURT().y - y;
278
                                        fullExtent = new Rectangle2D.Double(x, y, w, h);
279
                                }
280
                        } catch (SQLException e) {
281
                                System.err.println(e.getMessage());
282
                        }
283

    
284
                }
285
                return fullExtent;
286
        }
287

    
288
        /*
289
         * (non-Javadoc)
290
         *
291
         * @see com.iver.cit.gvsig.fmap.drivers.VectorialDatabaseDriver#getGeometryIterator(java.lang.String)
292
         */
293
        public IFeatureIterator getFeatureIterator(String sql)
294
                        throws com.iver.cit.gvsig.fmap.DriverException {
295
                PostGisFeatureIterator geomIterator = null;
296
                try {
297
                        // st = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
298
                        // ResultSet.CONCUR_READ_ONLY);
299

    
300

    
301
                        if (provCursorName != null) {
302
                                /* st.execute("BEGIN");
303
                                st.execute("CLOSE " + provCursorName);
304
                                bCursorActivo = false;
305
                                st.execute("COMMIT"); */
306
                                numProvCursors++;
307
                        }
308
                        // st.execute("BEGIN");
309
                        provCursorName = "wkb_cursor_prov_" + System.currentTimeMillis() + "" + numProvCursors;
310

    
311
                        // st.execute("BEGIN");
312
                        bCursorActivo = true;
313
                        // ResultSet rs = st.executeQuery(sql);
314
                        geomIterator = new PostGisFeatureIterator(conn, provCursorName, sql);
315
                        geomIterator.setLyrDef(getLyrDef());
316
                } catch (SQLException e) {
317
                        e.printStackTrace();
318

    
319
                        throw new DriverException(e);
320
                        // return null;
321
                }
322

    
323
                return geomIterator;
324
        }
325

    
326
        public IFeatureIterator getFeatureIterator(Rectangle2D r, String strEPSG)
327
                        throws DriverException {
328
                if (workingArea != null)
329
                        r = r.createIntersection(workingArea);
330

    
331
                String sqlAux;
332
                if (canReproject(strEPSG)) {
333
                        sqlAux = sqlOrig + getCompoundWhere(sqlOrig, r, strEPSG);
334
                } else {
335
                        sqlAux = sqlOrig + getCompoundWhere(sqlOrig, r, originalEPSG);
336
                }
337

    
338
                System.out.println("SqlAux getFeatureIterator = " + sqlAux);
339

    
340
                return getFeatureIterator(sqlAux);
341
        }
342

    
343
        /**
344
         * Le pasas el rect?ngulo que quieres pedir. La primera vez es el
345
         * workingArea, y las siguientes una interseccion de este rectangulo con el
346
         * workingArea
347
         *
348
         * @param r
349
         * @param strEPSG
350
         * @return
351
         */
352
        private String getCompoundWhere(String sql, Rectangle2D r, String strEPSG) {
353
                if (r == null)
354
                        return "";
355

    
356
                double xMin = r.getMinX();
357
                double yMin = r.getMinY();
358
                double xMax = r.getMaxX();
359
                double yMax = r.getMaxY();
360
                String wktBox = "GeometryFromText('LINESTRING(" + xMin + " " + yMin
361
                                + ", " + xMax + " " + yMin + ", " + xMax + " " + yMax + ", "
362
                                + xMin + " " + yMax + ")', " + strEPSG + ")";
363
                String sqlAux;
364
                if (getWhereClause().indexOf("WHERE") != -1)
365
                        sqlAux = getLyrDef().getFieldGeometry() + " && " + wktBox;
366
                else
367
                        sqlAux = "WHERE " + getLyrDef().getFieldGeometry() + " && "
368
                                        + wktBox;
369
                return sqlAux;
370
        }
371

    
372
        /**
373
         * @see com.iver.cit.gvsig.fmap.drivers.VectorialDatabaseDriver#getConnectionStringBeginning()
374
         */
375
        public String getConnectionStringBeginning() {
376
                return "jdbc:postgresql:";
377
        }
378

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

    
430
                                        for (int iDigit = 0; iDigit < ndigits; iDigit++) {
431
                                                short digit = buf.getShort();
432
                                                strAux = strAux + digit;
433
                                                if (iDigit == weight)
434
                                                        strAux = strAux + ".";
435

    
436
                                        }
437
                                        strAux = strAux + "0";
438
                                        String str2;
439
                                        BigDecimal dec;
440
                                        dec = new BigDecimal(strAux);
441
                                        // System.out.println(ndigits + "_" + weight + "_" + dscale
442
                                        // + "_" + strAux);
443
                                        // System.out.println(strAux + " Big= " + dec);
444
                                        return ValueFactory.createValue(dec.doubleValue());
445
                                }
446

    
447
                        }
448
                } catch (SQLException e) {
449
                        throw new com.hardcode.gdbms.engine.data.driver.DriverException(e
450
                                        .getMessage());
451
                }
452
                return ValueFactory.createNullValue();
453

    
454
        }
455

    
456
        public void open() throws com.iver.cit.gvsig.fmap.DriverException {
457
                /*
458
                 * try { st = conn.createStatement(); st.setFetchSize(2000); if
459
                 * (bCursorActivo) close(); st.execute("declare wkb_cursor binary cursor
460
                 * for " + sqlOrig); rs = st.executeQuery("fetch forward all in
461
                 * wkb_cursor"); // st.execute("BEGIN"); bCursorActivo = true; } catch
462
                 * (SQLException e) { e.printStackTrace(); throw new
463
                 * com.iver.cit.gvsig.fmap.DriverException(e); }
464
                 */
465

    
466
        }
467

    
468
        private void setAbsolutePosition(int index) throws SQLException {
469
                // TODO: USAR LIMIT Y ORDER BY, Y HACERLO TAMBI?N PARA
470
                // MYSQL
471

    
472
                // EL ABSOLUTE NO HACE QUE SE VUELVAN A LEER LAS
473
                // FILAS, ASI QUE MONTAMOS ESTA HISTORIA PARA QUE
474
                // LO HAGA
475
                // System.out.println("getShape " + index + " fetchMin=" + fetch_min + "
476
                // fetchMax=" + fetch_max);
477
                if (index < fetch_min) {
478
                        // rs.close();
479
                        st.execute("CLOSE wkb_cursor");
480
                        st.execute("declare wkb_cursor binary cursor for " + sqlTotal);
481
                        rs = st.executeQuery("fetch forward " + FETCH_SIZE
482
                                        + " in wkb_cursor");
483

    
484
                        // rs.beforeFirst();
485

    
486
                        // rs = st.executeQuery(sqlOrig);
487
                        fetch_min = 0;
488
                        fetch_max = FETCH_SIZE - 1;
489
                }
490
                while (index > fetch_max && index != 0) {
491
                        rs = st.executeQuery("fetch forward " + FETCH_SIZE
492
                                        + " in wkb_cursor");
493
                        // rs.next();
494
                        /*
495
                         * rs.afterLast(); // forzamos una carga rs.next();
496
                         */
497
                        fetch_min = fetch_max + 1;
498
                        fetch_max = fetch_min + FETCH_SIZE - 1;
499
                        // System.out.println("fetchSize = " + rs.getFetchSize() + " " +
500
                        // fetch_min + "-" + fetch_max);
501
                }
502
                if (rs != null)
503
                        rs.absolute(index - fetch_min + 1);
504

    
505
                // rs.absolute(index+1);
506

    
507
        }
508

    
509
        /**
510
         * @see com.iver.cit.gvsig.fmap.drivers.VectorialDatabaseDriver#getGeometryField(java.lang.String)
511
         */
512
        public String getGeometryField(String fieldName) {
513
                return "ASBINARY(" + fieldName + ", 'XDR')";
514
        }
515

    
516
        /**
517
         * @see com.hardcode.gdbms.engine.data.driver.ObjectDriver#getPrimaryKeys()
518
         */
519
        public int[] getPrimaryKeys()
520
                        throws com.hardcode.gdbms.engine.data.driver.DriverException {
521
                // TODO Auto-generated method stub
522
                return null;
523
        }
524

    
525
        /**
526
         * @see com.iver.cit.gvsig.fmap.drivers.VectorialJDBCDriver#getDefaultPort()
527
         */
528
        public int getDefaultPort() {
529
                return 5432;
530
        }
531

    
532
        /**
533
         * @see com.hardcode.gdbms.engine.data.driver.ObjectDriver#write(com.hardcode.gdbms.engine.data.edition.DataWare)
534
         */
535
        public void write(DataWare arg0)
536
                        throws com.hardcode.gdbms.engine.data.driver.DriverException {
537
                // TODO Auto-generated method stub
538

    
539
        }
540

    
541
        /*
542
         * (non-Javadoc)
543
         *
544
         * @see com.iver.cit.gvsig.fmap.core.ICanReproject#getSourceProjection()
545
         */
546
        public String getSourceProjection() {
547
                if (originalEPSG == null)
548
                        getTableEPSG();
549
                return originalEPSG;
550
        }
551

    
552
        /**
553
         * Las tablas con geometr?as est?n en la tabla GEOMETRY_COLUMNS y de
554
         * ah? sacamos en qu? proyecci?n est?n.
555
         * El problema es que si el usuario hace una vista de esa
556
         * tabla, no estar? dada de alta aqu? y entonces gvSIG
557
         * no se entera en qu? proyecci?n est? trabajando (y le
558
         * ponemos un -1 como mal menor). El -1 implica que luego
559
         * no podremos reproyectar al vuelo desde la base de datos.
560
         */
561
        private void getTableEPSG() {
562
                try {
563
                        Statement stAux = conn.createStatement();
564

    
565
                        String sql = "SELECT * FROM GEOMETRY_COLUMNS WHERE F_TABLE_NAME = '"
566
                                        + getTableName() + "';";
567
                        ResultSet rs = stAux.executeQuery(sql);
568
                        rs.next();
569
                        originalEPSG = "" + rs.getInt("SRID");
570
                        rs.close();
571
                } catch (SQLException e) {
572
                        // TODO Auto-generated catch block
573
                        originalEPSG = "-1";
574
                        logger.error(e);
575
                        e.printStackTrace();
576
                }
577

    
578
        }
579

    
580
        /*
581
         * (non-Javadoc)
582
         *
583
         * @see com.iver.cit.gvsig.fmap.core.ICanReproject#getDestProjection()
584
         */
585
        public String getDestProjection() {
586
                return strEPSG;
587
        }
588

    
589
        /*
590
         * (non-Javadoc)
591
         *
592
         * @see com.iver.cit.gvsig.fmap.core.ICanReproject#setDestProjection(java.lang.String)
593
         */
594
        public void setDestProjection(String toEPSG) {
595
                this.strEPSG = toEPSG;
596
        }
597

    
598
        /*
599
         * (non-Javadoc)
600
         *
601
         * @see com.iver.cit.gvsig.fmap.core.ICanReproject#canReproject(java.lang.String)
602
         */
603
        public boolean canReproject(String toEPSGdestinyProjection) {
604
                // TODO POR AHORA, REPROYECTA SIEMPRE gvSIG.
605
                return false;
606
        }
607

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

    
645
                        /*
646
                         * for (int index = 0; index < getShapeCount(); index++) { Value aux =
647
                         * getFieldValue(index, idFID_FieldName-2); hashRelate.put(aux, new
648
                         * Integer(index)); // System.out.println("Row " + index + " clave=" +
649
                         * aux); }
650
                         */
651
                        /*
652
                         * int index = 0;
653
                         *
654
                         * while (rs.next()) { Value aux = getFieldValue(index,
655
                         * idFID_FieldName-2); hashRelate.put(aux, new Integer(index));
656
                         * index++; System.out.println("Row " + index + " clave=" + aux); }
657
                         * numReg = index;
658
                         */
659
                        // rs.beforeFirst();
660
                        /*
661
                         * } catch (com.hardcode.gdbms.engine.data.driver.DriverException e) { //
662
                         * TODO Auto-generated catch block e.printStackTrace();
663
                         */
664
                } catch (SQLException e) {
665
                        // TODO Auto-generated catch block
666
                        e.printStackTrace();
667
                }
668
        }
669

    
670
        public String getSqlTotal() {
671
                return sqlTotal;
672
        }
673

    
674
        /**
675
         * @return Returns the completeWhere.
676
         */
677
        public String getCompleteWhere() {
678
                return completeWhere;
679
        }
680

    
681
        /*
682
         * (non-Javadoc)
683
         *
684
         * @see com.iver.cit.gvsig.fmap.drivers.DefaultDBDriver#close()
685
         */
686
        public void close() {
687
                super.close();
688
                /*
689
                 * if (bCursorActivo) { try { // st =
690
                 * conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
691
                 * ResultSet.CONCUR_READ_ONLY); st.execute("CLOSE wkb_cursor_prov"); //
692
                 * st.close(); } catch (SQLException e) { // TODO Auto-generated catch
693
                 * block e.printStackTrace(); } bCursorActivo = false; }
694
                 */
695

    
696
        }
697

    
698
        /*
699
         * (non-Javadoc)
700
         *
701
         * @see com.iver.cit.gvsig.fmap.drivers.VectorialDatabaseDriver#getFeatureIterator(java.awt.geom.Rectangle2D,
702
         *      java.lang.String, java.lang.String[])
703
         */
704
        public IFeatureIterator getFeatureIterator(Rectangle2D r, String strEPSG,
705
                        String[] alphaNumericFieldsNeeded) throws DriverException {
706
                try {
707
                        if (workingArea != null)
708
                                r = r.createIntersection(workingArea);
709
                        // if (getLyrDef()==null){
710
                        // load();
711
                        // throw new DriverException("Fallo de la conexi?n");
712
                        // }
713
                        String strAux = getGeometryField(getLyrDef().getFieldGeometry());
714

    
715
                        boolean found = false;
716
                        if (alphaNumericFieldsNeeded != null) {
717
                                for (int i = 0; i < alphaNumericFieldsNeeded.length; i++) {
718
                                        strAux = strAux + ", " + alphaNumericFieldsNeeded[i];
719
                                        if (alphaNumericFieldsNeeded[i].equals(getLyrDef()
720
                                                        .getFieldID()))
721
                                                found = true;
722
                                }
723
                        }
724
                        // Nos aseguramos de pedir siempre el campo ID
725
                        if (found == false)
726
                                strAux = strAux + ", " + getLyrDef().getFieldID();
727

    
728
                        String sqlProv = "SELECT " + strAux + " FROM "
729
                                        + getLyrDef().getTableName() + " "
730
                                        + getLyrDef().getWhereClause();
731

    
732
                        String sqlAux;
733
                        if (canReproject(strEPSG)) {
734
                                sqlAux = sqlProv + getCompoundWhere(sqlProv, r, strEPSG);
735
                        } else {
736
                                sqlAux = sqlProv + getCompoundWhere(sqlProv, r, originalEPSG);
737
                        }
738

    
739
                        System.out.println("SqlAux getFeatureIterator = " + sqlAux);
740

    
741
                        return getFeatureIterator(sqlAux);
742
                } catch (Exception e) {
743
                        throw new DriverException(e);
744
                }
745
        }
746

    
747
        /* public void preProcess() throws EditionException {
748
                writer.preProcess();
749
        }
750

751
        public void process(IRowEdited row) throws EditionException {
752
                writer.process(row);
753
        }
754

755
        public void postProcess() throws EditionException {
756
                writer.postProcess();
757
        }
758

759
        public String getCapability(String capability) {
760
                return writer.getCapability(capability);
761
        }
762

763
        public void setCapabilities(Properties capabilities) {
764
                writer.setCapabilities(capabilities);
765
        }
766

767
        public boolean canWriteAttribute(int sqlType) {
768
                return writer.canWriteAttribute(sqlType);
769
        }
770

771
        public boolean canWriteGeometry(int gvSIGgeometryType) {
772
                return writer.canWriteGeometry(gvSIGgeometryType);
773
        }
774

775
        public void initialize(ITableDefinition layerDef) throws EditionException {
776
                writer.setCreateTable(false);
777
                writer.setWriteAll(false);
778
                // Obtenemos el DBLayerDefinition a partir del driver
779

780
                DBLayerDefinition dbLyrDef = getLyrDef();
781

782

783
                writer.initialize(dbLyrDef);
784
        }
785
*/
786
        public boolean isWritable() {
787
                return true;
788
        } 
789

    
790
        public IWriter getWriter() {
791
                return writer;
792
        }
793

    
794

    
795
}