Statistics
| Revision:

svn-gvsig-desktop / tags / v2_0_0_Build_2021 / libraries / libFMap_daldb / src / org / gvsig / fmap / dal / store / postgresql / PostgreSQLHelper.java @ 34088

History | View | Annotate | Download (22.1 KB)

1
/* gvSIG. Geographic Information System of the Valencian Government
2
*
3
* Copyright (C) 2007-2008 Infrastructures and Transports Department
4
* of the Valencian Government (CIT)
5
*
6
* This program is free software; you can redistribute it and/or
7
* modify it under the terms of the GNU General Public License
8
* as published by the Free Software Foundation; either version 2
9
* of the License, or (at your option) any later version.
10
*
11
* This program is distributed in the hope that it will be useful,
12
* but WITHOUT ANY WARRANTY; without even the implied warranty of
13
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
* GNU General Public License for more details.
15
*
16
* You should have received a copy of the GNU General Public License
17
* along with this program; if not, write to the Free Software
18
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19
* MA  02110-1301, USA.
20
*
21
*/
22

    
23
/*
24
* AUTHORS (In addition to CIT):
25
* 2009 IVER T.I   {{Task}}
26
*/
27

    
28
/**
29
 *
30
 */
31
package org.gvsig.fmap.dal.store.postgresql;
32

    
33
import java.sql.Connection;
34
import java.sql.PreparedStatement;
35
import java.sql.ResultSet;
36
import java.sql.ResultSetMetaData;
37
import java.sql.SQLException;
38
import java.sql.Statement;
39
import java.util.ArrayList;
40
import java.util.Comparator;
41
import java.util.Iterator;
42
import java.util.List;
43
import java.util.Map;
44
import java.util.TreeMap;
45
import java.util.TreeSet;
46

    
47
import org.cresques.cts.IProjection;
48
import org.gvsig.fmap.crs.CRSFactory;
49
import org.gvsig.fmap.dal.DALLocator;
50
import org.gvsig.fmap.dal.DataTypes;
51
import org.gvsig.fmap.dal.NewDataStoreParameters;
52
import org.gvsig.fmap.dal.exception.DataException;
53
import org.gvsig.fmap.dal.exception.InitializeException;
54
import org.gvsig.fmap.dal.exception.ReadException;
55
import org.gvsig.fmap.dal.feature.EditableFeatureAttributeDescriptor;
56
import org.gvsig.fmap.dal.feature.EditableFeatureType;
57
import org.gvsig.fmap.dal.feature.FeatureAttributeDescriptor;
58
import org.gvsig.fmap.dal.feature.FeatureType;
59
import org.gvsig.fmap.dal.feature.exception.UnsupportedDataTypeException;
60
import org.gvsig.fmap.dal.feature.exception.UnsupportedGeometryException;
61
import org.gvsig.fmap.dal.resource.ResourceAction;
62
import org.gvsig.fmap.dal.resource.spi.ResourceManagerProviderServices;
63
import org.gvsig.fmap.dal.store.jdbc.ConnectionAction;
64
import org.gvsig.fmap.dal.store.jdbc.JDBCHelper;
65
import org.gvsig.fmap.dal.store.jdbc.JDBCHelperUser;
66
import org.gvsig.fmap.dal.store.jdbc.JDBCStoreParameters;
67
import org.gvsig.fmap.dal.store.jdbc.exception.JDBCException;
68
import org.gvsig.fmap.dal.store.jdbc.exception.JDBCExecutePreparedSQLException;
69
import org.gvsig.fmap.dal.store.jdbc.exception.JDBCExecuteSQLException;
70
import org.gvsig.fmap.dal.store.jdbc.exception.JDBCPreparingSQLException;
71
import org.gvsig.fmap.dal.store.jdbc.exception.JDBCSQLException;
72
import org.gvsig.fmap.geom.Geometry;
73
import org.gvsig.fmap.geom.GeometryLocator;
74
import org.gvsig.fmap.geom.GeometryManager;
75
import org.gvsig.fmap.geom.operation.fromwkb.FromWKB;
76
import org.gvsig.fmap.geom.operation.fromwkb.FromWKBGeometryOperationContext;
77
import org.gvsig.fmap.geom.primitive.Envelope;
78
import org.gvsig.tools.ToolsLocator;
79
import org.gvsig.tools.exception.BaseException;
80
import org.postgresql.PGResultSetMetaData;
81
import org.slf4j.Logger;
82
import org.slf4j.LoggerFactory;
83

    
84
/**
85
 * @author jmvivo
86
 *
87
 */
88
public class PostgreSQLHelper extends JDBCHelper {
89

    
90
        private static Logger logger = LoggerFactory
91
                        .getLogger(PostgreSQLHelper.class);
92

    
93
        private Map pgSR2SRSID = new TreeMap();
94
        private Map srsID2pgSR = new TreeMap();
95

    
96

    
97
        PostgreSQLHelper(JDBCHelperUser consumer,
98
                        PostgreSQLConnectionParameters params)
99
                        throws InitializeException {
100

    
101
                super(consumer, params);
102
        }
103

    
104
        protected void initializeResource() throws InitializeException {
105
                ResourceManagerProviderServices manager = (ResourceManagerProviderServices) DALLocator
106
                .getResourceManager();
107
                PostgreSQLResource resource = (PostgreSQLResource) manager
108
                .createAddResource(
109
                                PostgreSQLResource.NAME, new Object[] {
110
                                                params.getUrl(), params.getHost(),
111
                                                params.getPort(), params.getDBName(), params.getUser(),
112
                                                params.getPassword(),
113
                                                params.getJDBCDriverClassName(),
114
                                                ((PostgreSQLConnectionParameters) params).getUseSSL() });
115
                this.setResource(resource);
116
        }
117

    
118

    
119
        protected String getDefaultSchema(Connection conn)
120
                        throws JDBCException {
121
                if (defaultSchema == null) {
122
                        String sql = "Select current_schema()";
123
                        ResultSet rs = null;
124
                        Statement st = null;
125
                        String schema = null;
126
                        try {
127
                                st = conn.createStatement();
128
                                try {
129
                                        rs = st.executeQuery(sql);
130
                                } catch (java.sql.SQLException e) {
131
                                        throw new JDBCExecuteSQLException(sql, e);
132
                                }
133
                                rs.next();
134
                                schema = rs.getString(1);
135
                        } catch (java.sql.SQLException e) {
136
                                throw new JDBCSQLException(e);
137
                        } finally {
138
                                try {rs.close();} catch (Exception e) {logger.error("Exception clossing resulset", e);};
139
                                try {st.close();} catch (Exception e) {logger.error("Exception clossing statement", e);};
140
                                rs = null;
141
                                st = null;
142
                        }
143
                        defaultSchema = schema;
144
                }
145

    
146
                return defaultSchema;
147
        }
148

    
149
        public Envelope getFullEnvelopeOfField(
150
                        JDBCStoreParameters storeParams,
151
                        String geometryAttrName, Envelope limit)
152
                        throws DataException {
153

    
154
                StringBuilder strb = new StringBuilder();
155
                strb.append("Select asbinary(extent(");
156
                strb.append(escapeFieldName(geometryAttrName));
157
                strb.append(")) from ");
158

    
159
                if (storeParams.getSQL() != null
160
                                && storeParams.getSQL().trim().length() == 0) {
161
                        strb.append('(');
162
                        strb.append(storeParams.getSQL());
163
                        strb.append(") as __extentfield__ ");
164
                } else {
165
                        strb.append(storeParams.tableID());
166
                }
167

    
168

    
169
                if (limit != null){
170
                        strb.append(" where  intersects(GeomFromText('");
171
                        strb.append(limit.toString());
172
                        strb.append("')), boundary(");
173
                        strb.append(escapeFieldName(geometryAttrName));
174
                        strb.append(")) ");
175
                }
176

    
177
                final String sql = strb.toString();
178

    
179
                GeometryManager geoMan = GeometryLocator.getGeometryManager();
180

    
181
                this.open();
182

    
183
                return (Envelope) getResource().execute(new ResourceAction() {
184
                        public Object run() throws Exception {
185
                                ResultSet rs = null;
186
                                Statement st = null;
187
                                String schema = null;
188
                                Connection conn = null;
189
                                Envelope fullEnvelope = null;
190
                                try {
191

    
192
                                        conn = getConnection();
193
                                        st = conn.createStatement();
194
                                        try {
195
                                                rs = st.executeQuery(sql);
196
                                        } catch (java.sql.SQLException e) {
197
                                                throw new JDBCExecuteSQLException(sql, e);
198
                                        }
199
                                        if (!rs.next()) {
200
                                                return null;
201
                                        }
202

    
203
                                        byte[] data = rs.getBytes(1);
204
                                        if (data == null) {
205
                                                return null;
206
                                        }
207
                                        initializeFromWKBOperation();
208
                                        fromWKBContext.setData(data);
209
                                        Geometry geom =
210
                                                        (Geometry) fromWKB.invoke(null, fromWKBContext);
211

    
212
                                        fullEnvelope = geom.getEnvelope();
213

    
214
                                        return fullEnvelope;
215
                                } catch (java.sql.SQLException e) {
216
                                        throw new JDBCSQLException(e);
217
                                } catch (BaseException e) {
218
                                        throw new ReadException(user.getProviderName(), e);
219
                                } finally {
220
                                        try {
221
                                                rs.close();
222
                                        } catch (Exception e) {
223
                                        }
224
                                        try {
225
                                                st.close();
226
                                        } catch (Exception e) {
227
                                        }
228
                                        try {
229
                                                conn.close();
230
                                        } catch (Exception e) {
231
                                        }
232
                                        rs = null;
233
                                        st = null;
234
                                        conn = null;
235
                                }
236
                        }
237
                });
238
        }
239

    
240
        protected void initializeFromWKBOperation() throws BaseException {
241
                if (fromWKB == null) {
242
                        fromWKB = (FromWKB) GeometryLocator.getGeometryManager()
243
                                        .getGeometryOperation(FromWKB.CODE,
244
                                                        Geometry.TYPES.GEOMETRY, Geometry.SUBTYPES.GEOM2D);
245
                        fromWKBContext = new FromWKBGeometryOperationContext();
246

    
247
                }
248
        }
249

    
250
        @Override
251
        protected boolean supportsGeometry() {
252
                return true;
253
        }
254

    
255
        public Geometry getGeometry(byte[] buffer) throws BaseException {
256
                if (buffer == null) {
257
                        return null;
258
                }
259
                initializeFromWKBOperation();
260
                Geometry geom;
261
                try {
262
                        fromWKBContext.setData(buffer);
263

    
264
                        geom = (Geometry) fromWKB.invoke(null, fromWKBContext);
265
                } finally {
266
                        fromWKBContext.setData(null);
267
                }
268
                return geom;
269
        }
270

    
271
        /**
272
         * Fill <code>featureType</code> geometry attributes with SRS and ShapeType
273
         * information stored in the table GEOMETRY_COLUMNS
274
         *
275
         * @param conn
276
         * @param rsMetadata
277
         * @param featureType
278
         * @throws ReadException
279
         */
280
        protected void loadSRS_and_shapeType(Connection conn,
281
                        ResultSetMetaData rsMetadata, EditableFeatureType featureType,
282
                        String baseSchema, String baseTable)
283
                        throws JDBCException {
284

    
285
                Statement st = null;
286
                ResultSet rs = null;
287
                try {
288
                        // Sacamos la lista de los attributos geometricos
289
                        EditableFeatureAttributeDescriptor attr;
290
                        List geoAttrs = new ArrayList();
291

    
292
                        Iterator iter = featureType.iterator();
293
                        while (iter.hasNext()) {
294
                                attr = (EditableFeatureAttributeDescriptor) iter.next();
295
                                if (attr.getType() == DataTypes.GEOMETRY) {
296
                                        geoAttrs.add(attr);
297
                                }
298
                        }
299
                        if (geoAttrs.size() < 1) {
300
                                return;
301
                        }
302

    
303

    
304
                        // preparamos un set con las lista de tablas de origen
305
                        // de los campos
306
                        class TableId {
307
                                public String schema=null;
308
                                public String table=null;
309
                                public String field = null;
310

    
311
                                public void appendToSQL(StringBuilder strb) {
312
                                        if (schema == null || schema.length() == 0) {
313
                                                strb
314
                                                                .append("( F_TABLE_SCHEMA = current_schema() AND F_TABLE_NAME = '");
315
                                        } else {
316
                                                strb.append("( F_TABLE_SCHEMA = '");
317
                                                strb.append(schema);
318
                                                strb.append("' AND F_TABLE_NAME = '");
319
                                        }
320
                                        strb.append(table);
321
                                        strb.append("' AND F_GEOMETRY_COLUMN = '");
322
                                        strb.append(field);
323
                                        strb.append("' )");
324
                                }
325

    
326
                        }
327
                        Comparator cmp = new Comparator(){
328
                                public int compare(Object arg0, Object arg1) {
329
                                        TableId a0 = (TableId) arg0;
330
                                        TableId a1 = (TableId) arg1;
331

    
332
                                        if (!a0.field.equals(a1.field)) {
333
                                                return -1;
334
                                        }
335
                                        if (!a0.table.equals(a1.table)) {
336
                                                return -1;
337
                                        }
338
                                        if (!a0.schema.equals(a1.schema)) {
339
                                                return -1;
340
                                        }
341
                                        return 0;
342
                                }
343
                        };
344
                        TreeSet set = new TreeSet(cmp);
345
                        TableId tableId;
346
                        iter = geoAttrs.iterator();
347
                        int rsIndex;
348
                        while (iter.hasNext()) {
349
                                attr = (EditableFeatureAttributeDescriptor) iter.next();
350
                                tableId = new TableId();
351
                                rsIndex = attr.getIndex() + 1;
352

    
353
                                if (baseSchema == null && baseTable == null) {
354
                                        if (rsMetadata instanceof PGResultSetMetaData) {
355
                                                tableId.schema = ((PGResultSetMetaData) rsMetadata)
356
                                                                .getBaseSchemaName(rsIndex);
357
                                                tableId.table = ((PGResultSetMetaData) rsMetadata)
358
                                                                .getBaseTableName(rsIndex);
359
                                                tableId.field = ((PGResultSetMetaData) rsMetadata)
360
                                                                .getBaseColumnName(rsIndex);
361

    
362
                                        } else {
363
                                                tableId.schema = rsMetadata.getSchemaName(rsIndex);
364
                                                tableId.table = rsMetadata.getTableName(rsIndex);
365
                                                tableId.field = rsMetadata.getColumnName(rsIndex);
366
                                        }
367
                                } else {
368
                                        tableId.schema = baseSchema;
369
                                        tableId.table = baseTable;
370
                                        tableId.field = rsMetadata.getColumnName(rsIndex);
371
                                }
372
                                if (tableId.table == null || tableId.table.length() == 0) {
373
                                        // Si no tiene tabla origen (viene de algun calculo por ej.)
374
                                        // lo saltamos ya que no estara en la tabla GEOMETRY_COLUMNS
375
                                        continue;
376
                                }
377
                                set.add(tableId);
378
                        }
379

    
380
                        if (set.size() == 0) {
381
                                return;
382
                        }
383

    
384
                        // Preparamos una sql para que nos saque el resultado
385
                        StringBuilder strb = new StringBuilder();
386
                        strb.append("Select geometry_columns.*,auth_name || ':' || auth_srid as SRSID ");
387
                        strb.append("from geometry_columns left join spatial_ref_sys on ");
388
                        strb.append("geometry_columns.srid = spatial_ref_sys.srid WHERE ");
389
                        iter = set.iterator();
390
                        for (int i=0;i<set.size()-1;i++) {
391
                                tableId = (TableId) iter.next();
392
                                tableId.appendToSQL(strb);
393
                                strb.append(" OR ");
394
                        }
395
                        tableId = (TableId) iter.next();
396
                        tableId.appendToSQL(strb);
397
                        String sql = strb.toString();
398

    
399

    
400
                        st = conn.createStatement();
401
                        try {
402
                                rs = st.executeQuery(sql);
403
                        } catch (SQLException e) {
404
                                throw new JDBCExecuteSQLException(sql, e);
405
                        }
406
                        String srsID;
407
                        int pgSrid;
408
                        int geometryType;
409
                        int geometrySubtype;
410
                        String geomTypeStr;
411
                        int dimensions;
412
                        IProjection srs;
413

    
414
                        while (rs.next()){
415
                                srsID = rs.getString("SRSID");
416
                                pgSrid = rs.getInt("SRID");
417
                                geomTypeStr = rs.getString("TYPE").toUpperCase();
418
                                geometryType = Geometry.TYPES.GEOMETRY;
419
                                if (geomTypeStr.startsWith("POINT")) {
420
                                        geometryType = Geometry.TYPES.POINT;
421
                                } else if (geomTypeStr.startsWith("LINESTRING")) {
422
                                        geometryType = Geometry.TYPES.CURVE;
423
                                } else if (geomTypeStr.startsWith("POLYGON")) {
424
                                        geometryType = Geometry.TYPES.SURFACE;
425
                                } else if (geomTypeStr.startsWith("MULTIPOINT")) {
426
                                        geometryType = Geometry.TYPES.MULTIPOINT;
427
                                } else if (geomTypeStr.startsWith("MULTILINESTRING")) {
428
                                        geometryType = Geometry.TYPES.MULTICURVE;
429
                                } else if (geomTypeStr.startsWith("MULTIPOLYGON")) {
430
                                        geometryType = Geometry.TYPES.MULTISURFACE;
431
                                }
432
                                dimensions = rs.getInt("coord_dimension");
433
                                geometrySubtype = Geometry.SUBTYPES.GEOM2D;
434
                                if (dimensions > 2) {
435
                                        if (dimensions == 3) {
436
                                                if (geomTypeStr.endsWith("M")) {
437
                                                        geometrySubtype = Geometry.SUBTYPES.GEOM2DM;
438
                                                } else {
439
                                                        geometrySubtype = Geometry.SUBTYPES.GEOM3D;
440
                                                }
441

    
442
                                        } else {
443
                                                geometrySubtype = Geometry.SUBTYPES.GEOM3DM;
444
                                        }
445
                                }
446
                                addToPgSRToSRSID(pgSrid, srsID);
447

    
448

    
449
                                iter = geoAttrs.iterator();
450
                                while (iter.hasNext()) {
451
                                        attr = (EditableFeatureAttributeDescriptor) iter.next();
452
                                        rsIndex = attr.getIndex() + 1;
453
                                        if (!rsMetadata.getColumnName(rsIndex).equals(
454
                                                        rs.getString("f_geometry_column"))) {
455
                                                continue;
456
                                        }
457

    
458
                                        if (baseSchema == null && baseTable == null) {
459

    
460
                                                if (rsMetadata instanceof PGResultSetMetaData) {
461
                                                        if (!((PGResultSetMetaData) rsMetadata)
462
                                                                        .getBaseTableName(rsIndex).equals(
463
                                                                                        rs.getString("f_table_name"))) {
464
                                                                continue;
465
                                                        }
466
                                                        String curSchema = rs.getString("f_table_schema");
467
                                                        String metaSchema = ((PGResultSetMetaData) rsMetadata)
468
                                                                        .getBaseSchemaName(rsIndex);
469
                                                        if (!metaSchema.equals(curSchema)) {
470
                                                                if (metaSchema.length() == 0
471
                                                                                && metaSchema == getDefaultSchema(conn)) {
472
                                                                } else {
473
                                                                        continue;
474
                                                                }
475
                                                        }
476

    
477
                                                } else {
478

    
479
                                                        if (!rsMetadata.getTableName(rsIndex).equals(
480
                                                                        rs.getString("f_table_name"))) {
481
                                                                continue;
482
                                                        }
483
                                                        String curSchema = rs.getString("f_table_schema");
484
                                                        String metaSchema = rsMetadata
485
                                                                        .getSchemaName(rsIndex);
486
                                                        if (!metaSchema.equals(curSchema)) {
487
                                                                if (metaSchema.length() == 0
488
                                                                                && metaSchema == getDefaultSchema(conn)) {
489
                                                                } else {
490
                                                                        continue;
491
                                                                }
492
                                                        }
493
                                                }
494
                                        }
495
                                        attr.setGeometryType(geometryType);
496
                                        attr.setGeometrySubType(geometrySubtype);
497
                                        if (srsID != null && srsID.length() > 0) {
498
                                                attr.setSRS(CRSFactory.getCRS(srsID));
499
                                        }
500
                                        iter.remove();
501
                                }
502
                                iter = geoAttrs.iterator();
503
                                while (iter.hasNext()) {
504
                                        attr = (EditableFeatureAttributeDescriptor) iter.next();
505
                                        attr.setSRS(null);
506
                                        attr.setGeometryType(Geometry.TYPES.GEOMETRY);
507

    
508
                                }
509
                        }
510

    
511
                } catch (java.sql.SQLException e) {
512
                        throw new JDBCSQLException(e);
513
                } finally {
514
                        try {rs.close();} catch (Exception e) {        };
515
                        try {st.close();} catch (Exception e) {        };
516
                }
517

    
518
        }
519

    
520

    
521
        public String getSqlColumnTypeDescription(FeatureAttributeDescriptor attr) {
522
                if (attr.getType() == DataTypes.GEOMETRY) {
523
                        return "geometry";
524
                }
525
                return super.getSqlColumnTypeDescription(attr);
526
        }
527

    
528

    
529
        public int getPostgisGeomDimensions(int geometrySubType) {
530
                switch (geometrySubType) {
531
                case Geometry.SUBTYPES.GEOM2D:
532
                        return 2;
533
                case Geometry.SUBTYPES.GEOM2DM:
534
                case Geometry.SUBTYPES.GEOM3D:
535
                        return 3;
536

    
537
                case Geometry.SUBTYPES.GEOM3DM:
538
                        return 4;
539
                default:
540
                        throw new UnsupportedDataTypeException(
541
                                        ToolsLocator.getDataTypesManager().getTypeName(DataTypes.GEOMETRY),
542
                                        DataTypes.GEOMETRY);
543
                }
544
        }
545

    
546
        public String getPostgisGeomType(int geometryType, int geometrySubType) {
547
                String pgGeomType;
548
                switch (geometryType) {
549
                case Geometry.TYPES.GEOMETRY:
550
                        pgGeomType = "GEOMETRY";
551
                        break;
552
                case Geometry.TYPES.POINT:
553
                        pgGeomType = "POINT";
554
                        break;
555
                case Geometry.TYPES.CURVE:
556
                        pgGeomType = "LINESTRING";
557
                        break;
558
                case Geometry.TYPES.SURFACE:
559
                        pgGeomType = "POLYGON";
560
                        break;
561
                case Geometry.TYPES.MULTIPOINT:
562
                        pgGeomType = "MULTIPOINT";
563
                        break;
564
                case Geometry.TYPES.MULTICURVE:
565
                        pgGeomType = "MULTILINESTRING";
566
                        break;
567
                case Geometry.TYPES.MULTISURFACE:
568
                        pgGeomType = "MULTIPOLYGON";
569
                        break;
570
                default:
571
                        throw new UnsupportedGeometryException(geometryType,
572
                                        geometrySubType);
573
                }
574
                if (geometrySubType == Geometry.SUBTYPES.GEOM2DM
575
                                || geometrySubType == Geometry.SUBTYPES.GEOM3DM) {
576
                        pgGeomType = pgGeomType + "M";
577
                } else if (geometrySubType == Geometry.SUBTYPES.GEOM2DZ) {
578
                        throw new UnsupportedGeometryException(geometryType,
579
                                        geometrySubType);
580
                }
581
                return pgGeomType;
582
        }
583

    
584
        public int getProviderSRID(String srs) {
585
                if (srs != null) {
586
                        Integer pgSRID = (Integer) srsID2pgSR.get(srs);
587
                        if (pgSRID != null) {
588
                                return pgSRID.intValue();
589
                        }
590

    
591
                        return searchpgSRID(srs);
592

    
593
                }
594
                return -1;
595
        }
596

    
597

    
598
        public int getProviderSRID(IProjection srs) {
599
                if (srs != null) {
600
                        Integer pgSRID = (Integer) srsID2pgSR.get(srs.getAbrev());
601
                        if (pgSRID != null) {
602
                                return pgSRID.intValue();
603
                        }
604

    
605
                        return searchpgSRID(srs);
606

    
607
                }
608
                return -1;
609
        }
610

    
611
        private int searchpgSRID(final IProjection srs) {
612
                if (srs == null) {
613
                        return -1;
614
                }
615
                return searchpgSRID(srs.getAbrev());
616
        }
617

    
618
        private int searchpgSRID(final String srsID) {
619
                if (srsID == null) {
620
                        return -1;
621
                }
622

    
623
                ConnectionAction action = new ConnectionAction(){
624

    
625
                        public Object action(Connection conn) throws DataException {
626
                                // select srid from spatial_ref_sys where auth_name = 'EPSG' and
627
                                // auth_srid = 23030
628
                                String[] abrev = srsID.split(":");
629
                                StringBuilder sqlb = new StringBuilder();
630
                                sqlb.append("select srid from spatial_ref_sys where ");
631
                                if (abrev.length > 1) {
632
                                        sqlb.append("auth_name = ? and ");
633
                                }
634
                                sqlb.append("auth_srid = ?");
635

    
636
                                String sql = sqlb.toString();
637
                                PreparedStatement st;
638
                                try {
639
                                        st = conn.prepareStatement(sql);
640
                                } catch (SQLException e){
641
                                        throw new JDBCPreparingSQLException(sql,e);
642
                                }
643
                                ResultSet rs = null;
644
                                try{
645
                                        int i=0;
646
                                        if (abrev.length > 1){
647
                                                st.setString(i+1, abrev[i]);
648
                                                i++;
649
                                        }
650
                                        st.setInt(i + 1, Integer.parseInt(abrev[i]));
651

    
652
                                        try{
653
                                                rs = st.executeQuery();
654
                                        } catch (SQLException e){
655
                                                throw new JDBCExecutePreparedSQLException(sql, abrev, e);
656
                                        }
657

    
658
                                        if (!rs.next()) {
659
                                                return null;
660
                                        }
661

    
662
                                        return new Integer(rs.getInt(1));
663

    
664
                                } catch (SQLException e){
665
                                        throw new JDBCSQLException(e);
666
                                } finally{
667
                                        try {rs.close(); } catch (Exception e) {};
668
                                        try {st.close(); } catch (Exception e) {};
669
                                }
670

    
671
                        }
672

    
673
                };
674

    
675
                Integer pgSRSID = null;
676
                try {
677
                        pgSRSID = (Integer) doConnectionAction(action);
678
                } catch (Exception e) {
679
                        logger.error("Excetion searching pgSRS", e);
680
                        return -1;
681
                }
682

    
683
                if (pgSRSID != null) {
684
                        addToPgSRToSRSID(pgSRSID.intValue(), srsID);
685
                        return pgSRSID.intValue();
686
                }
687
                return -1;
688

    
689
        }
690

    
691
        private void addToPgSRToSRSID(int pgSRID, String srsId) {
692
                if (pgSRID < 0 || srsId == null || srsId.length() == 0) {
693
                        return;
694
                }
695
                Integer pgSRIDInteger = new Integer(pgSRID);
696
                pgSR2SRSID.put(pgSRIDInteger, srsId);
697
                srsID2pgSR.put(srsId, pgSRIDInteger);
698
        }
699

    
700
        public List<String> getSqlGeometyFieldAdd(FeatureAttributeDescriptor attr,
701
                        String table, String schema) {
702
                // SELECT AddGeometryColumn({schema}, {table}, {field}, {srid}(int),
703
                // {geomType}(Str), {dimensions}(int))
704

    
705
                // gemoType:
706
                /*
707
                 * POINT, LINESTRING, POLYGON, MULTIPOINT, MULTILINESTRING,
708
                 * MULTIPOLYGON, GEOMETRYCOLLECTION POINTM, LINESTRINGM, POLYGONM,
709
                 * MULTIPOINTM, MULTILINESTRINGM, MULTIPOLYGONM, GEOMETRYCOLLECTIONM
710
                 */
711

    
712
                List<String> sqls = new ArrayList<String>();
713

    
714
                StringBuilder strb = new StringBuilder();
715
                strb.append("SELECT AddGeometryColumn('");
716
                if (schema != null && schema.length() > 0) {
717
                        strb.append(schema);
718
                        strb.append("', '");
719
                }
720
                strb.append(table);
721
                strb.append("', '");
722
                strb.append(attr.getName());
723
                strb.append("', ");
724
                // strb.append("-1");
725
                strb.append(getProviderSRID(attr.getSRS()));
726
                strb.append(", '");
727
                strb.append(getPostgisGeomType(attr.getGeometryType(), attr
728
                                .getGeometrySubType()));
729
                strb.append("', ");
730
                strb.append(getPostgisGeomDimensions(attr.getGeometrySubType()));
731
                strb.append(")");
732

    
733

    
734
                sqls.add(strb.toString());
735

    
736
                /*ALTER TABLE muni10000_peq_test DROP CONSTRAINT enforce_srid_the_geom;*/
737
                /*
738
                strb = new StringBuilder();
739
                strb.append("Alter table ");
740
                if (schema != null && schema.length() > 0) {
741
                        strb.append(schema);
742
                        strb.append(".");
743
                }
744
                strb.append("f_table_name = '");
745
                strb.append(table);
746
                strb.append("' AND f_geometry_column = '");
747
                strb.append(attr.getName());
748
                strb.append("' AND srid = -1");
749

750

751
                sqls.add(strb.toString());
752
                */
753
                return sqls;
754
        }
755

    
756
        public String getSqlFieldName(FeatureAttributeDescriptor attribute) {
757
                if (attribute.getType() == DataTypes.GEOMETRY) {
758
                        return "asBinary(" + super.getSqlFieldName(attribute) + ")";
759
                }
760
                return super.getSqlFieldName(attribute);
761
        }
762

    
763
        protected EditableFeatureAttributeDescriptor createAttributeFromJDBC(
764
                        EditableFeatureType type, Connection conn,
765
                        ResultSetMetaData rsMetadata, int colIndex) throws SQLException {
766
                if (rsMetadata.getColumnType(colIndex) == java.sql.Types.OTHER) {
767
                        if (rsMetadata.getColumnTypeName(colIndex).equalsIgnoreCase(
768
                                        "geometry")) {
769
                                return type.add(rsMetadata.getColumnName(colIndex),
770
                                                DataTypes.GEOMETRY);
771

    
772
                        }
773
                }
774

    
775
                return super.createAttributeFromJDBC(type, conn, rsMetadata, colIndex);
776
        }
777

    
778
        public List getAdditionalSqlToCreate(NewDataStoreParameters ndsp,
779
                        FeatureType fType) {
780
                FeatureAttributeDescriptor attr;
781
                Iterator iter = fType.iterator();
782
                List result = new ArrayList();
783
                PostgreSQLNewStoreParameters pgNdsp = (PostgreSQLNewStoreParameters) ndsp;
784
                while (iter.hasNext()){
785
                        attr = (FeatureAttributeDescriptor) iter.next();
786
                        if (attr.getType() == DataTypes.GEOMETRY){
787
                                result.addAll(getSqlGeometyFieldAdd(attr, pgNdsp.getTable(),
788
                                                pgNdsp
789
                                                .getSchema()));
790
                        }
791
                }
792

    
793
                return result;
794
        }
795

    
796
        public String getSqlFieldDescription(FeatureAttributeDescriptor attr)
797
                        throws DataException {
798
                if (attr.getType() == DataTypes.GEOMETRY){
799
                        return null;
800
                }
801
                return super.getSqlFieldDescription(attr);
802
        }
803

    
804

    
805
        public boolean allowAutomaticValues() {
806
                return Boolean.TRUE;
807
        }
808

    
809
        public boolean supportOffset() {
810
                return true;
811
        }
812

    
813
        public boolean supportsUnion() {
814
                return true;
815
        }
816

    
817
}