Statistics
| Revision:

svn-gvsig-desktop / trunk / org.gvsig.desktop / org.gvsig.desktop.compat.cdc / org.gvsig.fmap.dal / org.gvsig.fmap.dal.db / org.gvsig.fmap.dal.db.jdbc / src / main / java / org / gvsig / fmap / dal / store / jdbc / JDBCHelper.java @ 41437

History | View | Annotate | Download (33 KB)

1
/**
2
 * gvSIG. Desktop Geographic Information System.
3
 *
4
 * Copyright (C) 2007-2013 gvSIG Association.
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 3
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
 * For any additional information, do not hesitate to contact us
22
 * at info AT gvsig.com, or visit our website www.gvsig.com.
23
 */
24
package org.gvsig.fmap.dal.store.jdbc;
25

    
26
import java.sql.Connection;
27
import java.sql.DatabaseMetaData;
28
import java.sql.ResultSet;
29
import java.sql.ResultSetMetaData;
30
import java.sql.SQLException;
31
import java.sql.Statement;
32
import java.sql.Time;
33
import java.util.ArrayList;
34
import java.util.Arrays;
35
import java.util.Date;
36
import java.util.List;
37
import java.util.logging.Level;
38

    
39
import org.cresques.cts.IProjection;
40
import org.gvsig.fmap.dal.DALLocator;
41
import org.gvsig.fmap.dal.DataTypes;
42
import org.gvsig.fmap.dal.NewDataStoreParameters;
43
import org.gvsig.fmap.dal.exception.CloseException;
44
import org.gvsig.fmap.dal.exception.DataException;
45
import org.gvsig.fmap.dal.exception.InitializeException;
46
import org.gvsig.fmap.dal.exception.OpenException;
47
import org.gvsig.fmap.dal.exception.ReadException;
48
import org.gvsig.fmap.dal.exception.WriteException;
49
import org.gvsig.fmap.dal.feature.EditableFeatureAttributeDescriptor;
50
import org.gvsig.fmap.dal.feature.EditableFeatureType;
51
import org.gvsig.fmap.dal.feature.FeatureAttributeDescriptor;
52
import org.gvsig.fmap.dal.feature.FeatureType;
53
import org.gvsig.fmap.dal.feature.exception.UnsupportedDataTypeException;
54
import org.gvsig.fmap.dal.resource.ResourceAction;
55
import org.gvsig.fmap.dal.resource.exception.AccessResourceException;
56
import org.gvsig.fmap.dal.resource.exception.ResourceExecuteException;
57
import org.gvsig.fmap.dal.resource.spi.ResourceConsumer;
58
import org.gvsig.fmap.dal.resource.spi.ResourceManagerProviderServices;
59
import org.gvsig.fmap.dal.resource.spi.ResourceProvider;
60
import org.gvsig.fmap.dal.store.jdbc.exception.JDBCException;
61
import org.gvsig.fmap.dal.store.jdbc.exception.JDBCExecuteSQLException;
62
import org.gvsig.fmap.dal.store.jdbc.exception.JDBCSQLException;
63
import org.gvsig.fmap.dal.store.jdbc.exception.JDBCTransactionCommitException;
64
import org.gvsig.fmap.dal.store.jdbc.exception.JDBCTransactionRollbackException;
65
import org.gvsig.fmap.geom.Geometry;
66
import org.gvsig.fmap.geom.GeometryLocator;
67
import org.gvsig.fmap.geom.GeometryManager;
68
import org.gvsig.fmap.geom.aggregate.Aggregate;
69
import org.gvsig.fmap.geom.aggregate.MultiPrimitive;
70
import org.gvsig.fmap.geom.exception.CreateGeometryException;
71
/*
72
import org.gvsig.fmap.geom.operation.fromwkb.FromWKB;
73
import org.gvsig.fmap.geom.operation.fromwkb.FromWKBGeometryOperationContext;
74
import org.gvsig.fmap.geom.operation.towkb.ToWKB;
75
import org.gvsig.fmap.geom.operation.towkb.ToWKBOperationContext;
76
*/
77
import org.gvsig.fmap.geom.primitive.Envelope;
78
import org.gvsig.fmap.geom.primitive.Primitive;
79
import org.gvsig.fmap.geom.type.GeometryType;
80
import org.gvsig.tools.dispose.impl.AbstractDisposable;
81
import org.gvsig.tools.exception.BaseException;
82
import org.slf4j.Logger;
83
import org.slf4j.LoggerFactory;
84

    
85
/**
86
 * @author jmvivo
87
 *
88
 */
89
public class JDBCHelper extends AbstractDisposable implements ResourceConsumer {
90

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

    
93
        protected JDBCHelperUser user;
94
        protected boolean isOpen;
95
        protected String name;
96
        protected String defaultSchema;
97
        protected JDBCConnectionParameters params;
98
        private JDBCResource resource;
99

    
100
        protected GeometryManager geomManager = null;
101

    
102
        private Boolean allowAutomaticValues = null;
103
        private Boolean supportsUnions = null;
104

    
105
        private String identifierQuoteString;
106

    
107
        protected JDBCHelper(JDBCHelperUser consumer,
108
                        JDBCConnectionParameters params) throws InitializeException {
109
                this.geomManager = GeometryLocator.getGeometryManager();
110
                this.user = consumer;
111
                this.name = user.getProviderName();
112
                this.params = params;
113
                initializeResource();
114

    
115
        }
116

    
117
        protected void initializeResource() throws InitializeException {
118
                ResourceManagerProviderServices manager = (ResourceManagerProviderServices) DALLocator
119
                                .getResourceManager();
120
                JDBCResource resource = (JDBCResource) manager
121
                                .createAddResource(
122
                                JDBCResource.NAME, new Object[] { params.getUrl(),
123
                                                params.getHost(), params.getPort(), params.getDBName(),
124
                                                params.getUser(), params.getPassword(),
125
                                                params.getJDBCDriverClassName() });
126
                this.setResource(resource);
127

    
128
        }
129

    
130
        protected final void setResource(JDBCResource resource) {
131
                this.resource = resource;
132
                this.resource.addConsumer(this);
133
        }
134

    
135
        public boolean closeResourceRequested(ResourceProvider resource) {
136
                return user.closeResourceRequested(resource);
137
        }
138

    
139
        public void resourceChanged(ResourceProvider resource) {
140
                user.resourceChanged(resource);
141

    
142
        }
143

    
144
        /**
145
         * open the resource
146
         *
147
         * @return true if the resourse was open in this call
148
         * @throws OpenException
149
         */
150
        public boolean open() throws OpenException {
151
                if (isOpen) {
152
                        return false;
153
                }
154
                // try {
155
                // begin();
156
                // } catch (ResourceExecuteException e1) {
157
                // throw new OpenException(name, e1);
158
                // }
159
                try {
160
                        getResource().execute(new ResourceAction() {
161
                                public Object run() throws Exception {
162
                                        getResource().connect();
163
                                        getResource().notifyOpen();
164

    
165
                                        user.opendDone();
166

    
167
                                        isOpen = true;
168
                                        return null;
169
                                }
170
                                public String toString() {
171
                                    return "open";
172
                                }
173
                        });
174
                        return true;
175
                } catch (ResourceExecuteException e) {
176
                        throw new OpenException(name, e);
177
                        // } finally {
178
                        // end();
179
                }
180

    
181
        }
182

    
183
        public JDBCResource getResource() {
184
                return resource;
185
        }
186

    
187
        public void close() throws CloseException {
188
                if (!isOpen) {
189
                        return;
190
                }
191
                // try {
192
                // begin();
193
                // } catch (ResourceExecuteException e) {
194
                // throw new CloseException(name, e);
195
                // }
196
                try {
197
                        getResource().execute(new ResourceAction() {
198
                                public Object run() throws Exception {
199
                                        isOpen = false;
200

    
201
                                        resource.notifyClose();
202
                                        user.closeDone();
203
                                        return null;
204
                                }
205
                        });
206
                } catch (ResourceExecuteException e) {
207
                        throw new CloseException(this.name, e);
208
                        // } finally {
209
                        // end();
210
                }
211
        }
212

    
213
        // public void end() {
214
        // resource.end();
215
        // }
216
        //
217
        // public void begin() throws ResourceExecuteException {
218
        // this.resource.begin();
219
        // }
220

    
221
        public Connection getConnection() throws AccessResourceException {
222
                return resource.getJDBCConnection();
223

    
224
        }
225

    
226
        @Override
227
        protected void doDispose() throws BaseException {
228
                this.close();
229
                resource.removeConsumer(this);
230
        }
231

    
232
        public boolean isOpen() {
233
                return isOpen;
234
        }
235

    
236
        /**
237
         * Executes an atomic action that uses an DB Connection.<br>
238
         *
239
         * This methos prepares a connection and close it at the end of execution of
240
         * action.<br>
241
         *
242
         * if <code>action</code> is an instance of {@link TransactionalAction} the
243
         * action will be execute inside of a DB transaction.
244
         *
245
         *
246
         * @param action
247
         * @throws Exception
248
         */
249
        public Object doConnectionAction(final ConnectionAction action)
250
                        throws Exception {
251
                this.open();
252
//                this.begin();
253
                return getResource().execute(new ResourceAction() {
254
                        public Object run() throws Exception {
255
                                Object result = null;
256
                                Connection conn = null;
257
                                boolean beginTrans = false;
258
                                try {
259
                                        conn = getConnection();
260
                                        if (action instanceof TransactionalAction) {
261
                                                // XXX OJO esta condicion NO ES FIABLE
262
                                                if (!conn.getAutoCommit()) {
263
                                                        if (!((TransactionalAction) action)
264
                                                                        .continueTransactionAllowed()) {
265
                                                                // FIXME exception
266
                                                                throw new Exception();
267
                                                        }
268
                                                }
269
                                                try {
270
                                                        conn.setAutoCommit(false);
271
                                                } catch (SQLException e) {
272
                                                        throw new JDBCSQLException(e);
273
                                                }
274
                                                beginTrans = true;
275
                                        }
276

    
277
                                        result = action.action(conn);
278

    
279
                                        if (beginTrans) {
280
                                                try {
281
                                                        conn.commit();
282
                                                } catch (SQLException e) {
283
                                                        throw new JDBCTransactionCommitException(e);
284
                                                }
285
                                        }
286

    
287
                                        return result;
288

    
289
                                } catch (Exception e) {
290

    
291
                                        if (beginTrans) {
292
                                                try {
293
                                                        conn.rollback();
294
                                                } catch (Exception e1) {
295
                                                        throw new JDBCTransactionRollbackException(e1, e);
296
                                                }
297
                                        }
298
                                        throw e;
299

    
300
                                } finally {
301
                                        try {
302
                                                if (conn != null) {
303
                                                        conn.close();
304
                                                }
305
                                        } catch (Exception e1) {
306
                                                logger.error("Exception on close connection", e1);
307
                                        }
308
                                        // this.end();
309
                                }
310
                        }
311
                });
312

    
313
        }
314

    
315
        protected String getDefaultSchema(Connection conn) throws JDBCException {
316
                return defaultSchema;
317
        }
318

    
319
        protected EditableFeatureAttributeDescriptor createAttributeFromJDBC(
320
                        EditableFeatureType fType, Connection conn,
321
                        ResultSetMetaData rsMetadata, int colIndex)
322
        throws java.sql.SQLException {
323

    
324
                EditableFeatureAttributeDescriptor column;
325
                switch (rsMetadata.getColumnType(colIndex)) {
326
                case java.sql.Types.INTEGER:
327
                        column = fType.add(rsMetadata.getColumnName(colIndex),
328
                                        DataTypes.INT);
329
                        break;
330
                case java.sql.Types.BIGINT:
331
                        column = fType.add(rsMetadata.getColumnName(colIndex),
332
                                        DataTypes.LONG);
333
                        break;
334
                case java.sql.Types.REAL:
335
                        column = fType.add(rsMetadata.getColumnName(colIndex),
336
                                        DataTypes.DOUBLE);
337
                        break;
338
                case java.sql.Types.DOUBLE:
339
                        column = fType.add(rsMetadata.getColumnName(colIndex),
340
                                        DataTypes.DOUBLE);
341
                        break;
342
                case java.sql.Types.CHAR:
343
                        column = fType.add(rsMetadata.getColumnName(colIndex),
344
                                        DataTypes.STRING);
345
                        break;
346
                case java.sql.Types.VARCHAR:
347
                case java.sql.Types.LONGVARCHAR:
348
                        column = fType.add(rsMetadata.getColumnName(colIndex),
349
                                        DataTypes.STRING);
350
                        break;
351
                case java.sql.Types.FLOAT:
352
                        column = fType.add(rsMetadata.getColumnName(colIndex),
353
                                        DataTypes.FLOAT);
354
                        break;
355
        case java.sql.Types.NUMERIC:
356
            column = fType.add(rsMetadata.getColumnName(colIndex),
357
                    DataTypes.FLOAT);
358
            break;
359
                case java.sql.Types.DECIMAL:
360
                        column = fType.add(rsMetadata.getColumnName(colIndex),
361
                                        DataTypes.FLOAT);
362
                        break;
363
                case java.sql.Types.DATE:
364
                        column = fType.add(rsMetadata.getColumnName(colIndex),
365
                                        DataTypes.DATE);
366
                        break;
367
                case java.sql.Types.TIME:
368
                        column = fType.add(rsMetadata.getColumnName(colIndex),
369
                                        DataTypes.TIME);
370
                        break;
371
                case java.sql.Types.TIMESTAMP:
372
                        column = fType.add(rsMetadata.getColumnName(colIndex),
373
                                        DataTypes.TIMESTAMP);
374
                        break;
375
                case java.sql.Types.BOOLEAN:
376
                case java.sql.Types.BIT:
377
                        column = fType.add(rsMetadata.getColumnName(colIndex),
378
                                        DataTypes.BOOLEAN);
379
                        break;
380
                case java.sql.Types.BLOB:
381
                case java.sql.Types.BINARY:
382
                case java.sql.Types.LONGVARBINARY:
383
                        column = fType.add(rsMetadata.getColumnName(colIndex),
384
                                        DataTypes.BYTEARRAY);
385
                        break;
386

    
387
                default:
388
                    column = createAttributeFromJDBCNativeType(fType, rsMetadata, colIndex);
389
                        break;
390
                }
391

    
392
                return column;
393

    
394
        }
395
        
396
        
397
        protected EditableFeatureAttributeDescriptor createAttributeFromJDBCNativeType(
398
        EditableFeatureType fType, ResultSetMetaData rsMetadata, int colIndex)
399
        throws SQLException {
400
        EditableFeatureAttributeDescriptor column;
401
        column = fType.add(rsMetadata.getColumnName(colIndex),
402
                DataTypes.OBJECT);
403
        column.setAdditionalInfo("SQLType", new Integer(rsMetadata
404
                .getColumnType(colIndex)));
405
        column.setAdditionalInfo("SQLTypeName", rsMetadata
406
                .getColumnTypeName(colIndex));
407
        return column;
408
    }
409
        
410

    
411
        protected EditableFeatureAttributeDescriptor getAttributeFromJDBC(
412
                        EditableFeatureType fType, Connection conn,
413
                        ResultSetMetaData rsMetadata, int colIndex) throws JDBCException {
414
                EditableFeatureAttributeDescriptor column;
415
                try {
416

    
417
                        column = createAttributeFromJDBC(fType, conn, rsMetadata, colIndex);
418
                        // column.setCaseSensitive(rsMetadata.isCaseSensitive(colIndex));
419
                        // column.setSqlType(rsMetadata.getColumnType(colIndex));
420
                        column.setAllowNull(
421
                                        rsMetadata.isNullable(colIndex) == ResultSetMetaData.columnNullable);
422
                        column.setIsAutomatic(rsMetadata.isAutoIncrement(colIndex));
423
                        column.setIsReadOnly(rsMetadata.isReadOnly(colIndex));
424
                        // column.setWritable(rsMetadata.isWritable(colIndex));
425
                        // column.setClassName(rsMetadata.getColumnClassName(colIndex));
426
                        // column.setCatalogName(rsMetadata.getCatalogName(colIndex));
427
                        // column.setDefinitelyWritable(rsMetadata
428
                        // .isDefinitelyWritable(colIndex));
429
                        // column.setLabel(rsMetadata.getColumnLabel(colIndex));
430
                        // column.setSchemaName(rsMetadata.getSchemaName(colIndex));
431
                        // column.setTableName(rsMetadata.getTableName(colIndex));
432
                        // column.setCatalogName(rsMetadata.getCatalogName(colIndex));
433
                        // column.setSqlTypeName();
434
                        // column.setSearchable(rsMetadata.isSearchable(colIndex));
435
                        // column.setSigned(rsMetadata.isSigned(colIndex));
436
                        // column.setCurrency(rsMetadata.isCurrency(colIndex));
437
                        column.setPrecision(rsMetadata.getPrecision(colIndex));
438
                        column.setSize(rsMetadata.getColumnDisplaySize(colIndex));
439

    
440
                } catch (java.sql.SQLException e) {
441
                        throw new JDBCSQLException(e);
442
                }
443

    
444
                return column;
445

    
446
        }
447

    
448
        /**
449
         * Fill <code>featureType</code> geometry attributes with SRS and ShapeType
450
         * information
451
         *
452
         * <b>Override this if provider has native eometry support</b>
453
         *
454
         * @param conn
455
         * @param rsMetadata
456
         * @param featureType
457
         * @throws ReadException
458
         */
459
        protected void loadSRS_and_shapeType(Connection conn,
460
                        ResultSetMetaData rsMetadata, EditableFeatureType featureType,
461
                        String baseSchema, String baseTable) throws JDBCException {
462

    
463
                // Nothing to do
464

    
465
        }
466

    
467
        public void loadFeatureType(EditableFeatureType featureType,
468
                        JDBCStoreParameters storeParams) throws DataException {
469
                if (storeParams.getSQL() != null
470
                                && storeParams.getSQL().trim().length() > 0) {
471
                        loadFeatureType(featureType, storeParams, storeParams.getSQL(),
472
                                        null, null);
473
                } else {
474
                        String sql = "Select * from " + storeParams.tableID()
475
                                        + " where false";
476
                        loadFeatureType(featureType, storeParams, sql, storeParams
477
                                        .getSchema(), storeParams.getTable());
478
                }
479
        }
480

    
481
        public void loadFeatureType(final EditableFeatureType featureType,
482
                        final JDBCStoreParameters storeParams, final String sql,
483
                        final String schema, final String table) throws DataException {
484
                this.open();
485
//                this.begin();
486
                getResource().execute(new ResourceAction() {
487
                        public Object run() throws Exception {
488
                                Connection conn = null;
489
                                try {
490
                                        conn = getConnection();
491
                                        
492
                                        String[] pks = storeParams.getPkFields();
493
                                        if (pks == null || pks.length < 1) {
494
                                                if (storeParams.getTable() != null
495
                                                                && storeParams.getTable().trim().length() > 0) {
496
                                                        pks = getPksFrom(conn, storeParams);
497
                                                        
498
                                                }
499
                                        }
500
                                        
501
                                        loadFeatureType(conn, featureType, sql, pks, storeParams
502
                                                        .getDefaultGeometryField(), schema, table);
503
                                        if (storeParams.getCRS()!=null && ((EditableFeatureAttributeDescriptor)featureType.getDefaultGeometryAttribute()) != null){
504
                                                ((EditableFeatureAttributeDescriptor)featureType.getDefaultGeometryAttribute()).setSRS(storeParams.getCRS());
505
                                        }
506
                                        
507
                                } finally {
508
                                        try {
509
                                                conn.close();
510
                                        } catch (Exception e) {
511
                                        }
512
//                        this.end();
513
                                }
514
                                return null;
515
                        }
516
                });
517
        }
518

    
519
        protected String[] getPksFrom(Connection conn, JDBCStoreParameters params)
520
                throws JDBCException {
521
                try{
522
                        DatabaseMetaData metadata = conn.getMetaData();
523
                        ResultSet rsPrimaryKeys = null;
524
                        ResultSet rs = null;
525
                        String catalog = params.getCatalog();
526
                        String schema = params.getSchema();
527

    
528
                        try{
529
                                rs = metadata.getTables(catalog,
530
                                                schema, params.getTable(), null);
531

    
532
                                if (!rs.next()) {
533
                                        // No tables found with default values, ignoring catalog
534
                                        rs.close();
535
                                        catalog = null;
536
                                        schema = null;
537
                                        rs = metadata
538
                                                        .getTables(catalog, schema, params.getTable(), null);
539

    
540
                                        if (!rs.next()) {
541
                                                // table not found
542
                                                return null;
543
                                        } else if (rs.next()){
544
                                                // More that one, cant identify
545
                                                return null;
546
                                        }
547

    
548
                                } else if (rs.next()) {
549
                                        // More that one, cant identify
550
                                        return null;
551
                                }
552
                                rsPrimaryKeys = metadata.getPrimaryKeys(catalog, schema, params
553
                                                .getTable());
554
                                List pks = new ArrayList();
555
                                while (rsPrimaryKeys.next()){
556
                                        pks.add(rsPrimaryKeys.getString("COLUMN_NAME"));
557
                                }
558
                                return (String[]) pks.toArray(new String[pks.size()]);
559

    
560

    
561
                        } finally {
562
                                try{if (rs != null) {
563
                                        rs.close();
564
                                }} catch (SQLException ex) {logger.warn("Exception closing tables rs", ex);};
565
                                try{if (rsPrimaryKeys != null) {
566
                                        rsPrimaryKeys.close();
567
                                }} catch (SQLException ex) {logger.warn("Exception closing pk rs", ex);};
568
                        }
569

    
570

    
571
                } catch (SQLException e) {
572
                        logger.warn("Unable to get pk from DatabaseMetada", e);
573
                        return getPksFromInformationSchema(conn, params);
574
                }
575

    
576
        }
577

    
578
        protected String[] getPksFromInformationSchema(Connection conn,
579
                        JDBCStoreParameters params)
580
                        throws JDBCException {
581
                Statement st;
582
                StringBuffer sql = new StringBuffer();
583
                ResultSet rs;
584
                ArrayList list = new ArrayList();
585

    
586
                /*
587
                 select column_name as primary_key
588
                        from information_schema.table_constraints t_cons
589
                                inner join information_schema.key_column_usage c on
590
                                        c.constraint_catalog = t_cons.table_catalog and
591
                                    c.table_schema = t_cons.table_schema and
592
                                    c.table_name = t_cons.table_name and
593
                                        c.constraint_name = t_cons.constraint_name
594
                                where t_cons.table_schema = <schema>
595
                                and t_cons.constraint_catalog = <catalog>
596
                                 and t_cons.table_name = <table>
597
                                 and constraint_type = 'PRIMARY KEY'
598
                 */
599
                /*
600
                 * SELECT column_name FROM INFORMATION_SCHEMA.constraint_column_usage
601
                 * left join INFORMATION_SCHEMA.table_constraints on
602
                 * (INFORMATION_SCHEMA.table_constraints.constraint_name =
603
                 * INFORMATION_SCHEMA.constraint_column_usage.constraint_name and
604
                 * INFORMATION_SCHEMA.table_constraints.table_name =
605
                 * INFORMATION_SCHEMA.constraint_column_usage.table_name and
606
                 * INFORMATION_SCHEMA.table_constraints.table_schema =
607
                 * INFORMATION_SCHEMA.constraint_column_usage.table_schema) WHERE
608
                 * INFORMATION_SCHEMA.constraint_column_usage.table_name like
609
                 * 'muni10000_peq' AND
610
                 * INFORMATION_SCHEMA.constraint_column_usage.table_schema like 'public'
611
                 * AND INFORMATION_SCHEMA.constraint_column_usage.table_catalog like
612
                 * 'gis' AND constraint_type='PRIMARY KEY'
613
                 */
614

    
615
                sql.append("select column_name as primary_key ");
616
                sql.append("from information_schema.table_constraints t_cons ");
617
                sql.append("inner join information_schema.key_column_usage c on ");
618
                sql.append("c.constraint_catalog = t_cons.constraint_catalog and ");
619
                sql.append("c.table_schema = t_cons.table_schema and ");
620
                sql.append("c.table_name = t_cons.table_name and ");
621
                sql.append("c.constraint_name = t_cons.constraint_name ");
622
                sql.append("WHERE t_cons.table_name like '");
623

    
624
                sql.append(params.getTable());
625
                sql.append("' ");
626
                String schema = null;
627

    
628

    
629
                if (params.getSchema() == null || params.getSchema() == "") {
630
                        schema = getDefaultSchema(conn);
631
                } else {
632
                        schema = params.getSchema();
633
                }
634
                if (schema != null) {
635
                        sql.append(" and t_cons.table_schema like '");
636
                        sql.append(schema);
637
                        sql.append("' ");
638
                }
639

    
640
                if (params.getCatalog() != null && params.getCatalog() != "") {
641
                        sql
642
                                        .append(" and t_cons.constraint_catalog like '");
643
                        sql.append(params.getCatalog());
644
                        sql.append("' ");
645
                }
646

    
647
                sql.append("' and constraint_type = 'PRIMARY KEY'");
648

    
649
                // System.out.println(sql.toString());
650
                try {
651
                        st = conn.createStatement();
652
                        try {
653
                                rs = st.executeQuery(sql.toString());
654
                        } catch (java.sql.SQLException e) {
655
                                throw new JDBCExecuteSQLException(sql.toString(), e);
656
                        }
657
                        while (rs.next()) {
658
                                list.add(rs.getString(1));
659
                        }
660
                        rs.close();
661
                        st.close();
662

    
663
                } catch (java.sql.SQLException e) {
664
                        throw new JDBCSQLException(e);
665
                }
666
                if (list.size() == 0) {
667
                        return null;
668
                }
669

    
670
                return (String[]) list.toArray(new String[0]);
671

    
672
        }
673

    
674
        protected void loadFeatureType(Connection conn,
675
                        EditableFeatureType featureType, String sql, String[] pks,
676
                        String defGeomName, String schema, String table)
677
                        throws DataException {
678

    
679
                Statement stAux = null;
680
                ResultSet rs = null;
681
                try {
682

    
683
                        stAux = conn.createStatement();
684
                        stAux.setFetchSize(1);
685

    
686
                        try {
687
                                rs = stAux.executeQuery(sql);
688
                        } catch (SQLException e) {
689
                                throw new JDBCExecuteSQLException(sql, e);
690
                        }
691
                        ResultSetMetaData rsMetadata = rs.getMetaData();
692

    
693
                        List pksList = null;
694
                        if (pks != null) {
695
                                pksList = Arrays.asList(pks);
696

    
697
                        }
698

    
699
                        int i;
700
                        int geometriesColumns = 0;
701
                        String lastGeometry = null;
702

    
703
                        EditableFeatureAttributeDescriptor attr;
704
            boolean firstGeometryAttrFound = false;
705
                        for (i = 1; i <= rsMetadata.getColumnCount(); i++) {
706
                                attr = getAttributeFromJDBC(featureType, conn, rsMetadata, i);
707
                                if (pksList != null && pksList.contains(attr.getName())) {
708
                                        attr.setIsPrimaryKey(true);
709
                                }
710
                                if (attr.getType() == DataTypes.GEOMETRY) {
711
                    geometriesColumns++;
712
                    lastGeometry = attr.getName();
713
                    // Set the default geometry attribute if it is the one
714
                    // given as parameter or it is the first one, just in case.
715
                    if (!firstGeometryAttrFound
716
                        || lastGeometry.equals(defGeomName)) {
717
                        firstGeometryAttrFound = true;
718
                        featureType
719
                            .setDefaultGeometryAttributeName(lastGeometry);
720
                    }
721
                                }
722

    
723
                        }
724

    
725
                        if (geometriesColumns > 0) {
726
                                loadSRS_and_shapeType(conn, rsMetadata, featureType, schema,
727
                                                table);
728
                        }
729

    
730
                        if (defGeomName == null && geometriesColumns == 1) {
731
                                featureType.setDefaultGeometryAttributeName(lastGeometry);
732
                                defGeomName = lastGeometry;
733
                        }
734

    
735
                } catch (java.sql.SQLException e) {
736
                        throw new JDBCSQLException(e); // FIXME exception
737
                } finally {
738
                        try {
739
                                rs.close();
740
                        } catch (Exception e) {
741
                        }
742
                        try {
743
                                stAux.close();
744
                        } catch (Exception e) {
745
                        }
746

    
747
                }
748

    
749
        }
750

    
751
        /**
752
         * Override if provider has geometry support
753
         *
754
         * @param storeParams
755
         * @param geometryAttrName
756
         * @param limit
757
         * @return
758
         * @throws DataException
759
         */
760
        public Envelope getFullEnvelopeOfField(JDBCStoreParameters storeParams,
761
                        String geometryAttrName, Envelope limit) throws DataException {
762

    
763
                // TODO
764
                return null;
765

    
766
        }
767

    
768
        public Geometry getGeometry(byte[] buffer) throws BaseException {
769
                if (buffer == null) {
770
                        return null;
771
                }
772
                return geomManager.createFrom(buffer);
773
        }
774

    
775
        public String escapeFieldName(String field) {
776
                if (field.matches("[a-z][a-z0-9_]*")) {
777
                        return field;
778
                }
779
                String quote = getIdentifierQuoteString();
780
                return quote + field + quote;
781
        }
782

    
783
        public class DalValueToJDBCException extends WriteException {
784

    
785
                /**
786
                 * 
787
                 */
788
                private static final long serialVersionUID = -3608973505723097889L;
789
                private final static String MESSAGE_FORMAT = "Can't convert value of attribute '%(attributeName)' to JDBC type (attribute type '%(attributeType)', value class '%(valueClass)').";
790
                private final static String MESSAGE_KEY = "_Cant_convert_value_of_attribute_XattributeNameX_to_JDBC_type_attribute_type_XattributeTypeX_value_class_XvalueClassX";
791

    
792
                public DalValueToJDBCException(FeatureAttributeDescriptor attributeDescriptor, Object object, Throwable cause) {
793
                        super(MESSAGE_FORMAT, cause, MESSAGE_KEY, serialVersionUID);
794
                        if( attributeDescriptor != null ) {
795
                                setValue("attributeName",attributeDescriptor.getName());
796
                                setValue("attributeType",attributeDescriptor.getDataTypeName());
797
                        } else {
798
                                setValue("attributeName","unknown");
799
                                setValue("attributeType","unknown");
800
                        }
801
                        if( object!=null ) {
802
                                setValue("valueClass", object.getClass().getName());
803
                        } else {
804
                                setValue("valueClass", "null");
805
                        }
806
                }
807

    
808
        }
809

    
810
    protected Geometry coerce(GeometryType type, Geometry geometry) {
811
        try {
812
            GeometryType geomType = geometry.getGeometryType();
813
            if (geomType.isTypeOf(type)) {
814
                return geometry;
815
            }
816

    
817
            if (type.isTypeOf(Geometry.TYPES.MULTISURFACE)) {
818
                if (geomType.isTypeOf(Geometry.TYPES.SURFACE)) {
819
                    MultiPrimitive geom2 = (MultiPrimitive) geomManager.create(type.getType(), geomType.getSubType());
820
                    geom2.addPrimitive((Primitive) geometry);
821
                    return geom2;
822
                }
823
            } else if (type.isTypeOf(Geometry.TYPES.MULTICURVE)) {
824
                if (geomType.isTypeOf(Geometry.TYPES.CURVE)) {
825
                    MultiPrimitive geom2 = (MultiPrimitive) geomManager.create(type.getType(), geomType.getSubType());
826
                    geom2.addPrimitive((Primitive) geometry);
827
                    return geom2;
828
                }
829
            } else if (type.isTypeOf(Geometry.TYPES.MULTIPOINT)) {
830
                if (geomType.isTypeOf(Geometry.TYPES.POINT)) {
831
                    MultiPrimitive geom2 = (MultiPrimitive) geomManager.create(type.getType(), geomType.getSubType());
832
                    geom2.addPrimitive((Primitive) geometry);
833
                    return geom2;
834
                }
835
            }
836
        } catch (CreateGeometryException ex) {
837
            // Do nothing, return the same geometry.
838
            logger.debug("Can't coerce geometry '"+geometry+"' to '"+type+"'.",ex);
839
        }
840
        return geometry;
841
    }
842
        
843
        public Object dalValueToJDBC(
844
                        FeatureAttributeDescriptor attributeDescriptor, Object object)
845
                        throws WriteException {
846
            
847
                IProjection srs = null;
848
                byte[] wkb = null;
849
                Geometry geom = null;
850
                try {
851
                        if (object == null) {
852
                                return null;
853
                        }
854
        
855
                        if (attributeDescriptor.getType() == DataTypes.TIME) {
856
                            return new Time(((Date)object).getTime());
857
                        }
858
                        if (attributeDescriptor.getType() != DataTypes.GEOMETRY) {
859
                                return object;
860
                        }
861
                        geom = coerce(attributeDescriptor.getGeomType(),(Geometry) object);                        
862
                        srs = attributeDescriptor.getSRS();
863
                        if (srs != null) {
864
                                wkb =  geom.convertToWKBForcingType(getProviderSRID(srs), attributeDescriptor.getGeomType().getType());
865
                        } else {
866
                                wkb =  geom.convertToWKB();
867
                        }
868
                        return wkb;
869
                } catch (Exception e) {
870
                        throw new DalValueToJDBCException(attributeDescriptor, object,e);
871
                }
872
        }
873

    
874
        public String getSqlColumnTypeDescription(FeatureAttributeDescriptor attr) {
875
                switch (attr.getType()) {
876
                case DataTypes.STRING:
877
                        if (attr.getSize() < 1 || attr.getSize() > 255) {
878
                                return "text";
879
                        } else {
880
                                return "varchar(" + attr.getSize() + ")";
881
                        }
882
                case DataTypes.BOOLEAN:
883
                        return "bool";
884

    
885
                case DataTypes.BYTE:
886
                        return "smallint";
887

    
888
                case DataTypes.DATE:
889
                        return "date";
890

    
891
                case DataTypes.TIMESTAMP:
892
                        return "timestamp";
893

    
894
                case DataTypes.TIME:
895
                        return "time";
896

    
897
                case DataTypes.BYTEARRAY:
898
                case DataTypes.GEOMETRY:
899
                        return "blob";
900

    
901
                case DataTypes.DOUBLE:
902
//                        if (attr.getPrecision() > 0) {
903
//                            return "double precision(" + attr.getPrecision() + ')';
904
//                        } else {
905
                    //It works with PostgreSQL and MySQL. Check with others
906
                            return "double precision";
907
//                        }
908
                case DataTypes.FLOAT:
909
                        return "real";
910

    
911
                case DataTypes.INT:
912
                        if (attr.isAutomatic() && allowAutomaticValues()) {
913
                                return "serial";
914
                        } else {
915
                                return "integer";
916
                        }
917
                case DataTypes.LONG:
918
                        if (attr.isAutomatic()) {
919
                                return "bigserial";
920
                        } else {
921
                                return "bigint";
922
                        }
923

    
924
                default:
925
                        String typeName = (String) attr.getAdditionalInfo("SQLTypeName");
926
                        if (typeName != null) {
927
                                return typeName;
928
                        }
929

    
930
                        throw new UnsupportedDataTypeException(attr.getDataTypeName(), attr
931
                                        .getType());
932
                }
933
        }
934

    
935
        public int getProviderSRID(String srs) {
936
                return -1;
937
        }
938

    
939
        public int getProviderSRID(IProjection srs) {
940
                return -1;
941
        }
942

    
943
        public String getSqlFieldName(FeatureAttributeDescriptor attribute) {
944
                return escapeFieldName(attribute.getName());
945
        }
946

    
947
        public String getSqlFieldDescription(FeatureAttributeDescriptor attr)
948
                        throws DataException {
949

    
950
                /**
951
                 * column_name data_type [ DEFAULT default_expr ] [ column_constraint [
952
                 * ... ] ]
953
                 *
954
                 * where column_constraint is:
955
                 *
956
                 * [ CONSTRAINT constraint_name ] { NOT NULL | NULL | UNIQUE | PRIMARY
957
                 * KEY | CHECK (expression) | REFERENCES reftable [ ( refcolumn ) ] [
958
                 * MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] [ ON DELETE action ] [ ON
959
                 * UPDATE action ] } [ DEFERRABLE | NOT DEFERRABLE ] [ INITIALLY
960
                 * DEFERRED | INITIALLY IMMEDIATE ]
961
                 */
962

    
963
                StringBuilder strb = new StringBuilder();
964
                // name
965
                strb.append(escapeFieldName(attr.getName()));
966
                strb.append(" ");
967

    
968
                // Type
969
                strb.append(this.getSqlColumnTypeDescription(attr));
970
                strb.append(" ");
971

    
972
                boolean allowNull = attr.allowNull()
973
                                && !(attr.isPrimaryKey() || attr.isAutomatic());
974
                // Default
975
                if (attr.getDefaultValue() == null) {
976
                        if (allowNull) {
977
                                strb.append("DEFAULT NULL ");
978
                        }
979
                } else {
980
                        String value = getDefaltFieldValueString(attr);
981
                        strb.append("DEFAULT '");
982
                        strb.append(value);
983
                        strb.append("' ");
984
                }
985

    
986
                // Null
987
                if (allowNull) {
988
                        strb.append("NULL ");
989
                } else {
990
                        strb.append("NOT NULL ");
991
                }
992

    
993
                // Primery key
994
                if (attr.isPrimaryKey()) {
995
                        strb.append("PRIMARY KEY ");
996
                }
997
                return strb.toString();
998
        }
999

    
1000
        /**
1001
         * @deprecated use getDefaultFieldValueString this has a type writer error.
1002
         */
1003
        protected String getDefaltFieldValueString(FeatureAttributeDescriptor attr)
1004
                        throws WriteException {
1005
                return getDefaultFieldValueString(attr);
1006
        }
1007

    
1008
        protected String getDefaultFieldValueString(FeatureAttributeDescriptor attr)
1009
                        throws WriteException {
1010
                return dalValueToJDBC(attr, attr.getDefaultValue()).toString();
1011
        }
1012

    
1013
        public String compoundLimitAndOffset(long limit, long offset) {
1014
                StringBuilder sql = new StringBuilder();
1015
                // limit
1016
                if (limit > 0) {
1017
                        sql.append(" limit ");
1018
                        sql.append(limit);
1019
                        sql.append(' ');
1020
                }
1021

    
1022
                // offset
1023
                if (offset > 0) {
1024
                        sql.append(" offset ");
1025
                        sql.append(offset);
1026
                        sql.append(' ');
1027
                }
1028
                return sql.toString();
1029
        }
1030

    
1031
        public boolean supportOffset() {
1032
                return true;
1033
        }
1034

    
1035
        public List getAdditionalSqlToCreate(NewDataStoreParameters ndsp,
1036
                        FeatureType fType) {
1037
                // TODO Auto-generated method stub
1038
                return null;
1039
        }
1040

    
1041

    
1042
        public String stringJoin(List listToJoin,String sep){
1043
                StringBuilder strb = new StringBuilder();
1044
                stringJoin(listToJoin,sep,strb);
1045
                return strb.toString();
1046
        }
1047

    
1048
        public void stringJoin(List listToJoin, String sep, StringBuilder strb) {
1049
                if (listToJoin.size() < 1) {
1050
                        return;
1051
                }
1052
                if (listToJoin.size() > 1) {
1053
                        for (int i = 0; i < listToJoin.size() - 1; i++) {
1054
                                strb.append(listToJoin.get(i));
1055
                                strb.append(sep);
1056
                        }
1057
                }
1058
                strb.append(listToJoin.get(listToJoin.size() - 1));
1059
        }
1060

    
1061
        /**
1062
         * Inform that provider has supports for geometry store and operations
1063
         * natively
1064
         *
1065
         * @return
1066
         */
1067
        protected boolean supportsGeometry() {
1068
                return false;
1069
        }
1070

    
1071
        public boolean allowAutomaticValues() {
1072
                if (allowAutomaticValues == null) {
1073
                        ConnectionAction action = new ConnectionAction(){
1074

    
1075
                                public Object action(Connection conn) throws DataException {
1076

    
1077
                                        ResultSet rs;
1078
                                        try {
1079
                                                DatabaseMetaData meta = conn.getMetaData();
1080
                                                rs = meta.getTypeInfo();
1081
                                                try{
1082
                                                        while (rs.next()) {
1083
                                                                if (rs.getInt("DATA_TYPE") == java.sql.Types.INTEGER) {
1084
                                                                        if (rs.getBoolean("AUTO_INCREMENT")) {
1085
                                                                                return Boolean.TRUE;
1086
                                                                        } else {
1087
                                                                                return Boolean.FALSE;
1088
                                                                        }
1089
                                                                }
1090
                                                        }
1091
                                                }finally{
1092
                                                        try{ rs.close();} catch (SQLException ex) {logger.error("Exception closing resulset", ex);};
1093
                                                }
1094
                                        } catch (SQLException e) {
1095
                                                throw new JDBCSQLException(e);
1096
                                        }
1097
                                        return Boolean.FALSE;
1098
                                }
1099

    
1100
                        };
1101

    
1102

    
1103

    
1104
                        try {
1105
                                allowAutomaticValues = (Boolean) doConnectionAction(action);
1106
                        } catch (Exception e) {
1107
                                logger.error("Exception checking for automatic integers", e);
1108
                                allowAutomaticValues = Boolean.FALSE;
1109
                        }
1110
                }
1111
                return allowAutomaticValues.booleanValue();
1112
        }
1113

    
1114
        public boolean supportsUnion() {
1115
                if (supportsUnions == null) {
1116
                        ConnectionAction action = new ConnectionAction() {
1117

    
1118
                                public Object action(Connection conn) throws DataException {
1119

    
1120
                                        try {
1121
                                                DatabaseMetaData meta = conn.getMetaData();
1122
                                                return new Boolean(meta.supportsUnion());
1123
                                        } catch (SQLException e) {
1124
                                                throw new JDBCSQLException(e);
1125
                                        }
1126
                                }
1127

    
1128
                        };
1129

    
1130
                        try {
1131
                                supportsUnions = (Boolean) doConnectionAction(action);
1132
                        } catch (Exception e) {
1133
                                logger.error("Exception checking for unions support", e);
1134
                                supportsUnions = Boolean.FALSE;
1135
                        }
1136
                }
1137
                return supportsUnions.booleanValue();
1138
        }
1139

    
1140
        protected String getIdentifierQuoteString() {
1141
                if (identifierQuoteString == null) {
1142
                ConnectionAction action = new ConnectionAction() {
1143

    
1144
                        public Object action(Connection conn) throws DataException {
1145

    
1146
                                try {
1147
                                        DatabaseMetaData meta = conn.getMetaData();
1148
                                        return meta.getIdentifierQuoteString();
1149
                                } catch (SQLException e) {
1150
                                        throw new JDBCSQLException(e);
1151
                                }
1152
                        }
1153

    
1154
                };
1155

    
1156
                try {
1157
                        identifierQuoteString = (String) doConnectionAction(action);
1158
                } catch (Exception e) {
1159
                        logger.error("Exception checking for unions support", e);
1160
                        identifierQuoteString = " ";
1161
                        }
1162
                }
1163
                return identifierQuoteString;
1164
        }
1165

    
1166
        protected boolean isReservedWord(String field) {
1167
                // TODO
1168
                return false;
1169
        }
1170

    
1171
}