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 @ 41037

History | View | Annotate | Download (30.4 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

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

    
79
/**
80
 * @author jmvivo
81
 *
82
 */
83
public class JDBCHelper extends AbstractDisposable implements ResourceConsumer {
84

    
85
        private static Logger logger = LoggerFactory.getLogger(JDBCHelper.class);
86

    
87
        protected JDBCHelperUser user;
88
        protected boolean isOpen;
89
        protected String name;
90
        protected String defaultSchema;
91
        protected JDBCConnectionParameters params;
92
        private JDBCResource resource;
93

    
94
        protected GeometryManager geomManager = null;
95

    
96
        private Boolean allowAutomaticValues = null;
97
        private Boolean supportsUnions = null;
98

    
99
        private String identifierQuoteString;
100

    
101
        protected JDBCHelper(JDBCHelperUser consumer,
102
                        JDBCConnectionParameters params) throws InitializeException {
103
                this.geomManager = GeometryLocator.getGeometryManager();
104
                this.user = consumer;
105
                this.name = user.getProviderName();
106
                this.params = params;
107
                initializeResource();
108

    
109
        }
110

    
111
        protected void initializeResource() throws InitializeException {
112
                ResourceManagerProviderServices manager = (ResourceManagerProviderServices) DALLocator
113
                                .getResourceManager();
114
                JDBCResource resource = (JDBCResource) manager
115
                                .createAddResource(
116
                                JDBCResource.NAME, new Object[] { params.getUrl(),
117
                                                params.getHost(), params.getPort(), params.getDBName(),
118
                                                params.getUser(), params.getPassword(),
119
                                                params.getJDBCDriverClassName() });
120
                this.setResource(resource);
121

    
122
        }
123

    
124
        protected final void setResource(JDBCResource resource) {
125
                this.resource = resource;
126
                this.resource.addConsumer(this);
127
        }
128

    
129
        public boolean closeResourceRequested(ResourceProvider resource) {
130
                return user.closeResourceRequested(resource);
131
        }
132

    
133
        public void resourceChanged(ResourceProvider resource) {
134
                user.resourceChanged(resource);
135

    
136
        }
137

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

    
159
                                        user.opendDone();
160

    
161
                                        isOpen = true;
162
                                        return null;
163
                                }
164
                        });
165
                        return true;
166
                } catch (ResourceExecuteException e) {
167
                        throw new OpenException(name, e);
168
                        // } finally {
169
                        // end();
170
                }
171

    
172
        }
173

    
174
        public JDBCResource getResource() {
175
                return resource;
176
        }
177

    
178
        public void close() throws CloseException {
179
                if (!isOpen) {
180
                        return;
181
                }
182
                // try {
183
                // begin();
184
                // } catch (ResourceExecuteException e) {
185
                // throw new CloseException(name, e);
186
                // }
187
                try {
188
                        getResource().execute(new ResourceAction() {
189
                                public Object run() throws Exception {
190
                                        isOpen = false;
191

    
192
                                        resource.notifyClose();
193
                                        user.closeDone();
194
                                        return null;
195
                                }
196
                        });
197
                } catch (ResourceExecuteException e) {
198
                        throw new CloseException(this.name, e);
199
                        // } finally {
200
                        // end();
201
                }
202
        }
203

    
204
        // public void end() {
205
        // resource.end();
206
        // }
207
        //
208
        // public void begin() throws ResourceExecuteException {
209
        // this.resource.begin();
210
        // }
211

    
212
        public Connection getConnection() throws AccessResourceException {
213
                return resource.getJDBCConnection();
214

    
215
        }
216

    
217
        @Override
218
        protected void doDispose() throws BaseException {
219
                resource.removeConsumer(this);
220
        }
221

    
222
        public boolean isOpen() {
223
                return isOpen;
224
        }
225

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

    
267
                                        result = action.action(conn);
268

    
269
                                        if (beginTrans) {
270
                                                try {
271
                                                        conn.commit();
272
                                                } catch (SQLException e) {
273
                                                        throw new JDBCTransactionCommitException(e);
274
                                                }
275
                                        }
276

    
277
                                        return result;
278

    
279
                                } catch (Exception e) {
280

    
281
                                        if (beginTrans) {
282
                                                try {
283
                                                        conn.rollback();
284
                                                } catch (Exception e1) {
285
                                                        throw new JDBCTransactionRollbackException(e1, e);
286
                                                }
287
                                        }
288
                                        throw e;
289

    
290
                                } finally {
291
                                        try {
292
                                                if (conn != null) {
293
                                                        conn.close();
294
                                                }
295
                                        } catch (Exception e1) {
296
                                                logger.error("Exception on close connection", e1);
297
                                        }
298
                                        // this.end();
299
                                }
300
                        }
301
                });
302

    
303
        }
304

    
305
        protected String getDefaultSchema(Connection conn) throws JDBCException {
306
                return defaultSchema;
307
        }
308

    
309
        protected EditableFeatureAttributeDescriptor createAttributeFromJDBC(
310
                        EditableFeatureType fType, Connection conn,
311
                        ResultSetMetaData rsMetadata, int colIndex)
312
        throws java.sql.SQLException {
313

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

    
377
                default:
378
                        column = fType.add(rsMetadata.getColumnName(colIndex),
379
                                        DataTypes.OBJECT);
380
                        column.setAdditionalInfo("SQLType", new Integer(rsMetadata
381
                                        .getColumnType(colIndex)));
382
                        column.setAdditionalInfo("SQLTypeName", rsMetadata
383
                                        .getColumnTypeName(colIndex));
384

    
385
                        break;
386
                }
387

    
388
                return column;
389

    
390
        }
391

    
392
        protected EditableFeatureAttributeDescriptor getAttributeFromJDBC(
393
                        EditableFeatureType fType, Connection conn,
394
                        ResultSetMetaData rsMetadata, int colIndex) throws JDBCException {
395
                EditableFeatureAttributeDescriptor column;
396
                try {
397

    
398
                        column = createAttributeFromJDBC(fType, conn, rsMetadata, colIndex);
399
                        // column.setCaseSensitive(rsMetadata.isCaseSensitive(colIndex));
400
                        // column.setSqlType(rsMetadata.getColumnType(colIndex));
401
                        column.setAllowNull(
402
                                        rsMetadata.isNullable(colIndex) == ResultSetMetaData.columnNullable);
403
                        column.setIsAutomatic(rsMetadata.isAutoIncrement(colIndex));
404
                        column.setIsReadOnly(rsMetadata.isReadOnly(colIndex));
405
                        // column.setWritable(rsMetadata.isWritable(colIndex));
406
                        // column.setClassName(rsMetadata.getColumnClassName(colIndex));
407
                        // column.setCatalogName(rsMetadata.getCatalogName(colIndex));
408
                        // column.setDefinitelyWritable(rsMetadata
409
                        // .isDefinitelyWritable(colIndex));
410
                        // column.setLabel(rsMetadata.getColumnLabel(colIndex));
411
                        // column.setSchemaName(rsMetadata.getSchemaName(colIndex));
412
                        // column.setTableName(rsMetadata.getTableName(colIndex));
413
                        // column.setCatalogName(rsMetadata.getCatalogName(colIndex));
414
                        // column.setSqlTypeName();
415
                        // column.setSearchable(rsMetadata.isSearchable(colIndex));
416
                        // column.setSigned(rsMetadata.isSigned(colIndex));
417
                        // column.setCurrency(rsMetadata.isCurrency(colIndex));
418
                        column.setPrecision(rsMetadata.getPrecision(colIndex));
419
                        column.setSize(rsMetadata.getColumnDisplaySize(colIndex));
420

    
421
                } catch (java.sql.SQLException e) {
422
                        throw new JDBCSQLException(e);
423
                }
424

    
425
                return column;
426

    
427
        }
428

    
429
        /**
430
         * Fill <code>featureType</code> geometry attributes with SRS and ShapeType
431
         * information
432
         *
433
         * <b>Override this if provider has native eometry support</b>
434
         *
435
         * @param conn
436
         * @param rsMetadata
437
         * @param featureType
438
         * @throws ReadException
439
         */
440
        protected void loadSRS_and_shapeType(Connection conn,
441
                        ResultSetMetaData rsMetadata, EditableFeatureType featureType,
442
                        String baseSchema, String baseTable) throws JDBCException {
443

    
444
                // Nothing to do
445

    
446
        }
447

    
448
        public void loadFeatureType(EditableFeatureType featureType,
449
                        JDBCStoreParameters storeParams) throws DataException {
450
                if (storeParams.getSQL() != null
451
                                && storeParams.getSQL().trim().length() > 0) {
452
                        loadFeatureType(featureType, storeParams, storeParams.getSQL(),
453
                                        null, null);
454
                } else {
455
                        String sql = "Select * from " + storeParams.tableID()
456
                                        + " where false";
457
                        loadFeatureType(featureType, storeParams, sql, storeParams
458
                                        .getSchema(), storeParams.getTable());
459
                }
460
        }
461

    
462
        public void loadFeatureType(final EditableFeatureType featureType,
463
                        final JDBCStoreParameters storeParams, final String sql,
464
                        final String schema, final String table) throws DataException {
465
                this.open();
466
//                this.begin();
467
                getResource().execute(new ResourceAction() {
468
                        public Object run() throws Exception {
469
                                Connection conn = null;
470
                                try {
471
                                        conn = getConnection();
472
                                        
473
                                        String[] pks = storeParams.getPkFields();
474
                                        if (pks == null || pks.length < 1) {
475
                                                if (storeParams.getTable() != null
476
                                                                && storeParams.getTable().trim().length() > 0) {
477
                                                        pks = getPksFrom(conn, storeParams);
478
                                                        
479
                                                }
480
                                        }
481
                                        
482
                                        loadFeatureType(conn, featureType, sql, pks, storeParams
483
                                                        .getDefaultGeometryField(), schema, table);
484
                                        if (storeParams.getCRS()!=null && ((EditableFeatureAttributeDescriptor)featureType.getDefaultGeometryAttribute()) != null){
485
                                                ((EditableFeatureAttributeDescriptor)featureType.getDefaultGeometryAttribute()).setSRS(storeParams.getCRS());
486
                                        }
487
                                        
488
                                } finally {
489
                                        try {
490
                                                conn.close();
491
                                        } catch (Exception e) {
492
                                        }
493
//                        this.end();
494
                                }
495
                                return null;
496
                        }
497
                });
498
        }
499

    
500
        protected String[] getPksFrom(Connection conn, JDBCStoreParameters params)
501
                throws JDBCException {
502
                try{
503
                        DatabaseMetaData metadata = conn.getMetaData();
504
                        ResultSet rsPrimaryKeys = null;
505
                        ResultSet rs = null;
506
                        String catalog = params.getCatalog();
507
                        String schema = params.getSchema();
508

    
509
                        try{
510
                                rs = metadata.getTables(catalog,
511
                                                schema, params.getTable(), null);
512

    
513
                                if (!rs.next()) {
514
                                        // No tables found with default values, ignoring catalog
515
                                        rs.close();
516
                                        catalog = null;
517
                                        schema = null;
518
                                        rs = metadata
519
                                                        .getTables(catalog, schema, params.getTable(), null);
520

    
521
                                        if (!rs.next()) {
522
                                                // table not found
523
                                                return null;
524
                                        } else if (rs.next()){
525
                                                // More that one, cant identify
526
                                                return null;
527
                                        }
528

    
529
                                } else if (rs.next()) {
530
                                        // More that one, cant identify
531
                                        return null;
532
                                }
533
                                rsPrimaryKeys = metadata.getPrimaryKeys(catalog, schema, params
534
                                                .getTable());
535
                                List pks = new ArrayList();
536
                                while (rsPrimaryKeys.next()){
537
                                        pks.add(rsPrimaryKeys.getString("COLUMN_NAME"));
538
                                }
539
                                return (String[]) pks.toArray(new String[pks.size()]);
540

    
541

    
542
                        } finally {
543
                                try{if (rs != null) {
544
                                        rs.close();
545
                                }} catch (SQLException ex) {logger.warn("Exception closing tables rs", ex);};
546
                                try{if (rsPrimaryKeys != null) {
547
                                        rsPrimaryKeys.close();
548
                                }} catch (SQLException ex) {logger.warn("Exception closing pk rs", ex);};
549
                        }
550

    
551

    
552
                } catch (SQLException e) {
553
                        logger.warn("Unable to get pk from DatabaseMetada", e);
554
                        return getPksFromInformationSchema(conn, params);
555
                }
556

    
557
        }
558

    
559
        protected String[] getPksFromInformationSchema(Connection conn,
560
                        JDBCStoreParameters params)
561
                        throws JDBCException {
562
                Statement st;
563
                StringBuffer sql = new StringBuffer();
564
                ResultSet rs;
565
                ArrayList list = new ArrayList();
566

    
567
                /*
568
                 select column_name as primary_key
569
                        from information_schema.table_constraints t_cons
570
                                inner join information_schema.key_column_usage c on
571
                                        c.constraint_catalog = t_cons.table_catalog and
572
                                    c.table_schema = t_cons.table_schema and
573
                                    c.table_name = t_cons.table_name and
574
                                        c.constraint_name = t_cons.constraint_name
575
                                where t_cons.table_schema = <schema>
576
                                and t_cons.constraint_catalog = <catalog>
577
                                 and t_cons.table_name = <table>
578
                                 and constraint_type = 'PRIMARY KEY'
579
                 */
580
                /*
581
                 * SELECT column_name FROM INFORMATION_SCHEMA.constraint_column_usage
582
                 * left join INFORMATION_SCHEMA.table_constraints on
583
                 * (INFORMATION_SCHEMA.table_constraints.constraint_name =
584
                 * INFORMATION_SCHEMA.constraint_column_usage.constraint_name and
585
                 * INFORMATION_SCHEMA.table_constraints.table_name =
586
                 * INFORMATION_SCHEMA.constraint_column_usage.table_name and
587
                 * INFORMATION_SCHEMA.table_constraints.table_schema =
588
                 * INFORMATION_SCHEMA.constraint_column_usage.table_schema) WHERE
589
                 * INFORMATION_SCHEMA.constraint_column_usage.table_name like
590
                 * 'muni10000_peq' AND
591
                 * INFORMATION_SCHEMA.constraint_column_usage.table_schema like 'public'
592
                 * AND INFORMATION_SCHEMA.constraint_column_usage.table_catalog like
593
                 * 'gis' AND constraint_type='PRIMARY KEY'
594
                 */
595

    
596
                sql.append("select column_name as primary_key ");
597
                sql.append("from information_schema.table_constraints t_cons ");
598
                sql.append("inner join information_schema.key_column_usage c on ");
599
                sql.append("c.constraint_catalog = t_cons.constraint_catalog and ");
600
                sql.append("c.table_schema = t_cons.table_schema and ");
601
                sql.append("c.table_name = t_cons.table_name and ");
602
                sql.append("c.constraint_name = t_cons.constraint_name ");
603
                sql.append("WHERE t_cons.table_name like '");
604

    
605
                sql.append(params.getTable());
606
                sql.append("' ");
607
                String schema = null;
608

    
609

    
610
                if (params.getSchema() == null || params.getSchema() == "") {
611
                        schema = getDefaultSchema(conn);
612
                } else {
613
                        schema = params.getSchema();
614
                }
615
                if (schema != null) {
616
                        sql.append(" and t_cons.table_schema like '");
617
                        sql.append(schema);
618
                        sql.append("' ");
619
                }
620

    
621
                if (params.getCatalog() != null && params.getCatalog() != "") {
622
                        sql
623
                                        .append(" and t_cons.constraint_catalog like '");
624
                        sql.append(params.getCatalog());
625
                        sql.append("' ");
626
                }
627

    
628
                sql.append("' and constraint_type = 'PRIMARY KEY'");
629

    
630
                // System.out.println(sql.toString());
631
                try {
632
                        st = conn.createStatement();
633
                        try {
634
                                rs = st.executeQuery(sql.toString());
635
                        } catch (java.sql.SQLException e) {
636
                                throw new JDBCExecuteSQLException(sql.toString(), e);
637
                        }
638
                        while (rs.next()) {
639
                                list.add(rs.getString(1));
640
                        }
641
                        rs.close();
642
                        st.close();
643

    
644
                } catch (java.sql.SQLException e) {
645
                        throw new JDBCSQLException(e);
646
                }
647
                if (list.size() == 0) {
648
                        return null;
649
                }
650

    
651
                return (String[]) list.toArray(new String[0]);
652

    
653
        }
654

    
655
        protected void loadFeatureType(Connection conn,
656
                        EditableFeatureType featureType, String sql, String[] pks,
657
                        String defGeomName, String schema, String table)
658
                        throws DataException {
659

    
660
                Statement stAux = null;
661
                ResultSet rs = null;
662
                try {
663

    
664
                        stAux = conn.createStatement();
665
                        stAux.setFetchSize(1);
666

    
667
                        try {
668
                                rs = stAux.executeQuery(sql);
669
                        } catch (SQLException e) {
670
                                throw new JDBCExecuteSQLException(sql, e);
671
                        }
672
                        ResultSetMetaData rsMetadata = rs.getMetaData();
673

    
674
                        List pksList = null;
675
                        if (pks != null) {
676
                                pksList = Arrays.asList(pks);
677

    
678
                        }
679

    
680
                        int i;
681
                        int geometriesColumns = 0;
682
                        String lastGeometry = null;
683

    
684
                        EditableFeatureAttributeDescriptor attr;
685
            boolean firstGeometryAttrFound = false;
686
                        for (i = 1; i <= rsMetadata.getColumnCount(); i++) {
687
                                attr = getAttributeFromJDBC(featureType, conn, rsMetadata, i);
688
                                if (pksList != null && pksList.contains(attr.getName())) {
689
                                        attr.setIsPrimaryKey(true);
690
                                }
691
                                if (attr.getType() == DataTypes.GEOMETRY) {
692
                    geometriesColumns++;
693
                    lastGeometry = attr.getName();
694
                    // Set the default geometry attribute if it is the one
695
                    // given as parameter or it is the first one, just in case.
696
                    if (!firstGeometryAttrFound
697
                        || lastGeometry.equals(defGeomName)) {
698
                        firstGeometryAttrFound = true;
699
                        featureType
700
                            .setDefaultGeometryAttributeName(lastGeometry);
701
                    }
702
                                }
703

    
704
                        }
705

    
706
                        if (geometriesColumns > 0) {
707
                                loadSRS_and_shapeType(conn, rsMetadata, featureType, schema,
708
                                                table);
709
                        }
710

    
711
                        if (defGeomName == null && geometriesColumns == 1) {
712
                                featureType.setDefaultGeometryAttributeName(lastGeometry);
713
                                defGeomName = lastGeometry;
714
                        }
715

    
716
                } catch (java.sql.SQLException e) {
717
                        throw new JDBCSQLException(e); // FIXME exception
718
                } finally {
719
                        try {
720
                                rs.close();
721
                        } catch (Exception e) {
722
                        }
723
                        try {
724
                                stAux.close();
725
                        } catch (Exception e) {
726
                        }
727

    
728
                }
729

    
730
        }
731

    
732
        /**
733
         * Override if provider has geometry support
734
         *
735
         * @param storeParams
736
         * @param geometryAttrName
737
         * @param limit
738
         * @return
739
         * @throws DataException
740
         */
741
        public Envelope getFullEnvelopeOfField(JDBCStoreParameters storeParams,
742
                        String geometryAttrName, Envelope limit) throws DataException {
743

    
744
                // TODO
745
                return null;
746

    
747
        }
748

    
749
        public Geometry getGeometry(byte[] buffer) throws BaseException {
750
                if (buffer == null) {
751
                        return null;
752
                }
753
                return geomManager.createFrom(buffer);
754
        }
755

    
756
        public String escapeFieldName(String field) {
757
                if (field.matches("[a-z][a-z0-9_]*")) {
758
                        return field;
759
                }
760
                String quote = getIdentifierQuoteString();
761
                return quote + field + quote;
762
        }
763

    
764
        public class DalValueToJDBCException extends WriteException {
765

    
766
                /**
767
                 * 
768
                 */
769
                private static final long serialVersionUID = -3608973505723097889L;
770
                private final static String MESSAGE_FORMAT = "Can't convert value of attribute '%(attributeName)' to JDBC type (attribute type '%(attributeType)', value class '%(valueClass)').";
771
                private final static String MESSAGE_KEY = "_Cant_convert_value_of_attribute_XattributeNameX_to_JDBC_type_attribute_type_XattributeTypeX_value_class_XvalueClassX";
772

    
773
                public DalValueToJDBCException(FeatureAttributeDescriptor attributeDescriptor, Object object, Throwable cause) {
774
                        super(MESSAGE_FORMAT, cause, MESSAGE_KEY, serialVersionUID);
775
                        if( attributeDescriptor != null ) {
776
                                setValue("attributeName",attributeDescriptor.getName());
777
                                setValue("attributetype",attributeDescriptor.getDataTypeName());
778
                        } else {
779
                                setValue("attributeName","unknown");
780
                                setValue("attributetype","unknown");
781
                        }
782
                        if( object!=null ) {
783
                                setValue("valueClass", object.getClass().getName());
784
                        } else {
785
                                setValue("valueClass", "null");
786
                        }
787
                }
788

    
789
        }
790

    
791
        public Object dalValueToJDBC(
792
                        FeatureAttributeDescriptor attributeDescriptor, Object object)
793
                        throws WriteException {
794
                try {
795
                        if (object == null) {
796
                                return null;
797
                        }
798
        
799
                        if (attributeDescriptor.getType() == DataTypes.TIME) {
800
                            return new Time(((Date)object).getTime());
801
                        }
802
                        if (attributeDescriptor.getType() != DataTypes.GEOMETRY) {
803
                                return object;
804
                        }
805
                        byte[] wkb = null;
806
                        Geometry geom = (Geometry) object;
807
                        IProjection srs = attributeDescriptor.getSRS();
808
                        if (srs != null) {
809
                                wkb =  geom.convertToWKBForcingType(getProviderSRID(srs), attributeDescriptor.getGeomType().getType());
810
                        } else {
811
                                wkb =  geom.convertToWKB();
812
                        }
813
                        return wkb;
814
                } catch (Exception e) {
815
                        throw new DalValueToJDBCException(attributeDescriptor, object,e);
816
                }
817
        }
818

    
819
        public String getSqlColumnTypeDescription(FeatureAttributeDescriptor attr) {
820
                switch (attr.getType()) {
821
                case DataTypes.STRING:
822
                        if (attr.getSize() < 1 || attr.getSize() > 255) {
823
                                return "text";
824
                        } else {
825
                                return "varchar(" + attr.getSize() + ")";
826
                        }
827
                case DataTypes.BOOLEAN:
828
                        return "bool";
829

    
830
                case DataTypes.BYTE:
831
                        return "smallint";
832

    
833
                case DataTypes.DATE:
834
                        return "date";
835

    
836
                case DataTypes.TIMESTAMP:
837
                        return "timestamp";
838

    
839
                case DataTypes.TIME:
840
                        return "time";
841

    
842
                case DataTypes.BYTEARRAY:
843
                case DataTypes.GEOMETRY:
844
                        return "blob";
845

    
846
                case DataTypes.DOUBLE:
847
//                        if (attr.getPrecision() > 0) {
848
//                            return "double precision(" + attr.getPrecision() + ')';
849
//                        } else {
850
                    //It works with PostgreSQL and MySQL. Check with others
851
                            return "double precision";
852
//                        }
853
                case DataTypes.FLOAT:
854
                        return "real";
855

    
856
                case DataTypes.INT:
857
                        if (attr.isAutomatic() && allowAutomaticValues()) {
858
                                return "serial";
859
                        } else {
860
                                return "integer";
861
                        }
862
                case DataTypes.LONG:
863
                        if (attr.isAutomatic()) {
864
                                return "bigserial";
865
                        } else {
866
                                return "bigint";
867
                        }
868

    
869
                default:
870
                        String typeName = (String) attr.getAdditionalInfo("SQLTypeName");
871
                        if (typeName != null) {
872
                                return typeName;
873
                        }
874

    
875
                        throw new UnsupportedDataTypeException(attr.getDataTypeName(), attr
876
                                        .getType());
877
                }
878
        }
879

    
880
        public int getProviderSRID(String srs) {
881
                return -1;
882
        }
883

    
884
        public int getProviderSRID(IProjection srs) {
885
                return -1;
886
        }
887

    
888
        public String getSqlFieldName(FeatureAttributeDescriptor attribute) {
889
                return escapeFieldName(attribute.getName());
890
        }
891

    
892
        public String getSqlFieldDescription(FeatureAttributeDescriptor attr)
893
                        throws DataException {
894

    
895
                /**
896
                 * column_name data_type [ DEFAULT default_expr ] [ column_constraint [
897
                 * ... ] ]
898
                 *
899
                 * where column_constraint is:
900
                 *
901
                 * [ CONSTRAINT constraint_name ] { NOT NULL | NULL | UNIQUE | PRIMARY
902
                 * KEY | CHECK (expression) | REFERENCES reftable [ ( refcolumn ) ] [
903
                 * MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] [ ON DELETE action ] [ ON
904
                 * UPDATE action ] } [ DEFERRABLE | NOT DEFERRABLE ] [ INITIALLY
905
                 * DEFERRED | INITIALLY IMMEDIATE ]
906
                 */
907

    
908
                StringBuilder strb = new StringBuilder();
909
                // name
910
                strb.append(escapeFieldName(attr.getName()));
911
                strb.append(" ");
912

    
913
                // Type
914
                strb.append(this.getSqlColumnTypeDescription(attr));
915
                strb.append(" ");
916

    
917
                boolean allowNull = attr.allowNull()
918
                                && !(attr.isPrimaryKey() || attr.isAutomatic());
919
                // Default
920
                if (attr.getDefaultValue() == null) {
921
                        if (allowNull) {
922
                                strb.append("DEFAULT NULL ");
923
                        }
924
                } else {
925
                        String value = getDefaltFieldValueString(attr);
926
                        strb.append("DEFAULT '");
927
                        strb.append(value);
928
                        strb.append("' ");
929
                }
930

    
931
                // Null
932
                if (allowNull) {
933
                        strb.append("NULL ");
934
                } else {
935
                        strb.append("NOT NULL ");
936
                }
937

    
938
                // Primery key
939
                if (attr.isPrimaryKey()) {
940
                        strb.append("PRIMARY KEY ");
941
                }
942
                return strb.toString();
943
        }
944

    
945
        /**
946
         * @deprecated use getDefaultFieldValueString this has a type writer error.
947
         */
948
        protected String getDefaltFieldValueString(FeatureAttributeDescriptor attr)
949
                        throws WriteException {
950
                return getDefaultFieldValueString(attr);
951
        }
952

    
953
        protected String getDefaultFieldValueString(FeatureAttributeDescriptor attr)
954
                        throws WriteException {
955
                return dalValueToJDBC(attr, attr.getDefaultValue()).toString();
956
        }
957

    
958
        public String compoundLimitAndOffset(long limit, long offset) {
959
                StringBuilder sql = new StringBuilder();
960
                // limit
961
                if (limit > 0) {
962
                        sql.append(" limit ");
963
                        sql.append(limit);
964
                        sql.append(' ');
965
                }
966

    
967
                // offset
968
                if (offset > 0) {
969
                        sql.append(" offset ");
970
                        sql.append(offset);
971
                        sql.append(' ');
972
                }
973
                return sql.toString();
974
        }
975

    
976
        public boolean supportOffset() {
977
                return true;
978
        }
979

    
980
        public List getAdditionalSqlToCreate(NewDataStoreParameters ndsp,
981
                        FeatureType fType) {
982
                // TODO Auto-generated method stub
983
                return null;
984
        }
985

    
986

    
987
        public String stringJoin(List listToJoin,String sep){
988
                StringBuilder strb = new StringBuilder();
989
                stringJoin(listToJoin,sep,strb);
990
                return strb.toString();
991
        }
992

    
993
        public void stringJoin(List listToJoin, String sep, StringBuilder strb) {
994
                if (listToJoin.size() < 1) {
995
                        return;
996
                }
997
                if (listToJoin.size() > 1) {
998
                        for (int i = 0; i < listToJoin.size() - 1; i++) {
999
                                strb.append(listToJoin.get(i));
1000
                                strb.append(sep);
1001
                        }
1002
                }
1003
                strb.append(listToJoin.get(listToJoin.size() - 1));
1004
        }
1005

    
1006
        /**
1007
         * Inform that provider has supports for geometry store and operations
1008
         * natively
1009
         *
1010
         * @return
1011
         */
1012
        protected boolean supportsGeometry() {
1013
                return false;
1014
        }
1015

    
1016
        public boolean allowAutomaticValues() {
1017
                if (allowAutomaticValues == null) {
1018
                        ConnectionAction action = new ConnectionAction(){
1019

    
1020
                                public Object action(Connection conn) throws DataException {
1021

    
1022
                                        ResultSet rs;
1023
                                        try {
1024
                                                DatabaseMetaData meta = conn.getMetaData();
1025
                                                rs = meta.getTypeInfo();
1026
                                                try{
1027
                                                        while (rs.next()) {
1028
                                                                if (rs.getInt("DATA_TYPE") == java.sql.Types.INTEGER) {
1029
                                                                        if (rs.getBoolean("AUTO_INCREMENT")) {
1030
                                                                                return Boolean.TRUE;
1031
                                                                        } else {
1032
                                                                                return Boolean.FALSE;
1033
                                                                        }
1034
                                                                }
1035
                                                        }
1036
                                                }finally{
1037
                                                        try{ rs.close();} catch (SQLException ex) {logger.error("Exception closing resulset", ex);};
1038
                                                }
1039
                                        } catch (SQLException e) {
1040
                                                throw new JDBCSQLException(e);
1041
                                        }
1042
                                        return Boolean.FALSE;
1043
                                }
1044

    
1045
                        };
1046

    
1047

    
1048

    
1049
                        try {
1050
                                allowAutomaticValues = (Boolean) doConnectionAction(action);
1051
                        } catch (Exception e) {
1052
                                logger.error("Exception checking for automatic integers", e);
1053
                                allowAutomaticValues = Boolean.FALSE;
1054
                        }
1055
                }
1056
                return allowAutomaticValues.booleanValue();
1057
        }
1058

    
1059
        public boolean supportsUnion() {
1060
                if (supportsUnions == null) {
1061
                        ConnectionAction action = new ConnectionAction() {
1062

    
1063
                                public Object action(Connection conn) throws DataException {
1064

    
1065
                                        try {
1066
                                                DatabaseMetaData meta = conn.getMetaData();
1067
                                                return new Boolean(meta.supportsUnion());
1068
                                        } catch (SQLException e) {
1069
                                                throw new JDBCSQLException(e);
1070
                                        }
1071
                                }
1072

    
1073
                        };
1074

    
1075
                        try {
1076
                                supportsUnions = (Boolean) doConnectionAction(action);
1077
                        } catch (Exception e) {
1078
                                logger.error("Exception checking for unions support", e);
1079
                                supportsUnions = Boolean.FALSE;
1080
                        }
1081
                }
1082
                return supportsUnions.booleanValue();
1083
        }
1084

    
1085
        protected String getIdentifierQuoteString() {
1086
                if (identifierQuoteString == null) {
1087
                ConnectionAction action = new ConnectionAction() {
1088

    
1089
                        public Object action(Connection conn) throws DataException {
1090

    
1091
                                try {
1092
                                        DatabaseMetaData meta = conn.getMetaData();
1093
                                        return meta.getIdentifierQuoteString();
1094
                                } catch (SQLException e) {
1095
                                        throw new JDBCSQLException(e);
1096
                                }
1097
                        }
1098

    
1099
                };
1100

    
1101
                try {
1102
                        identifierQuoteString = (String) doConnectionAction(action);
1103
                } catch (Exception e) {
1104
                        logger.error("Exception checking for unions support", e);
1105
                        identifierQuoteString = " ";
1106
                        }
1107
                }
1108
                return identifierQuoteString;
1109
        }
1110

    
1111
        protected boolean isReservedWord(String field) {
1112
                // TODO
1113
                return false;
1114
        }
1115

    
1116
}