Statistics
| Revision:

root / branches / v2_0_0_prep / libraries / libFMap_daldb / src / org / gvsig / fmap / data / feature / db / jdbc / postgresql / PostgresqlExplorer.java @ 24491

History | View | Annotate | Download (11.4 KB)

1
package org.gvsig.fmap.data.feature.db.jdbc.postgresql;
2

    
3
import java.security.KeyException;
4
import java.sql.Connection;
5
import java.sql.ResultSet;
6
import java.sql.SQLException;
7
import java.sql.Statement;
8
import java.util.ArrayList;
9

    
10
import org.gvsig.fmap.dal.DataExplorerParameters;
11
import org.gvsig.fmap.dal.DataStoreParameters;
12
import org.gvsig.fmap.dal.NewDataStoreParameters;
13
import org.gvsig.fmap.dal.exceptions.CloseException;
14
import org.gvsig.fmap.dal.exceptions.DataException;
15
import org.gvsig.fmap.dal.exceptions.InitializeException;
16
import org.gvsig.fmap.dal.exceptions.ReadException;
17
import org.gvsig.fmap.dal.feature.FeatureAttributeDescriptor;
18
import org.gvsig.fmap.dal.feature.FeatureType;
19
import org.gvsig.fmap.dal.feature.NewFeatureStoreParameters;
20
import org.gvsig.fmap.dal.feature.exceptions.InitializeWriterException;
21
import org.gvsig.fmap.dal.resource.ResourceManager;
22
import org.gvsig.fmap.dal.resource.impl.DefaultResourceManager;
23
import org.gvsig.fmap.data.feature.db.DBAttributeDescriptor;
24
import org.gvsig.fmap.data.feature.db.DBFeatureType;
25
import org.gvsig.fmap.data.feature.db.jdbc.JDBCExplorer;
26
import org.gvsig.fmap.data.feature.db.jdbc.JDBCExplorerParameter;
27

    
28
public class PostgresqlExplorer extends JDBCExplorer {
29
        public static String DATAEXPLORER_NAME = "PostgresqlExplorer";
30
        private String defaultSchema;
31

    
32
        private void appendFieldToCreteSQL(DBAttributeDescriptor attr,StringBuffer sql) throws InitializeException{
33
                /**
34
                 * column_name data_type [ DEFAULT default_expr ] [ column_constraint [
35
                 * ... ] ]
36
                 *
37
                 * where column_constraint is:
38
                 *
39
                 * [ CONSTRAINT constraint_name ] { NOT NULL | NULL | UNIQUE | PRIMARY
40
                 * KEY | CHECK (expression) | REFERENCES reftable [ ( refcolumn ) ] [
41
                 * MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] [ ON DELETE action ] [ ON
42
                 * UPDATE action ] } [ DEFERRABLE | NOT DEFERRABLE ] [ INITIALLY
43
                 * DEFERRED | INITIALLY IMMEDIATE ]
44
                 */
45

    
46
                //name
47
                sql.append(attr.getName());
48
                sql.append(" ");
49

    
50
                //dataType
51
                String type =attr.getDataType();
52
                if (type.equals(FeatureAttributeDescriptor.STRING)){
53
                        if (attr.getSize() < 1 || attr.getSize() > 255) {
54
                                sql.append("text");
55
                        } else {
56
                                sql.append("varchar(" + attr.getSize() + ")");
57
                        }
58
                } else if (type.equals(FeatureAttributeDescriptor.BOOLEAN)){
59
                        sql.append("bool");
60
                } else if (type.equals(FeatureAttributeDescriptor.BYTE)){
61
                        sql.append("smallint");
62
                } else if (type.equals(FeatureAttributeDescriptor.DATE)){
63
                        sql.append("date");
64
                } else if (type.equals(FeatureAttributeDescriptor.TIMESTAMP)){
65
                        sql.append("timestamp");
66
                } else if (type.equals(FeatureAttributeDescriptor.TIME)){
67
                        sql.append("time");
68
                } else if (type.equals(FeatureAttributeDescriptor.DOUBLE)){
69
                        sql.append("double precision");
70
                        if (attr.getPrecision() > 0){
71
                                sql.append(" "+ attr.getPrecision());
72
                        }
73
                } else if (type.equals(FeatureAttributeDescriptor.FLOAT)){
74
                        sql.append("real");
75
                } else if (type.equals(FeatureAttributeDescriptor.GEOMETRY)){
76
                        sql.append("geometry");
77
                } else if (type.equals(FeatureAttributeDescriptor.INT)){
78
                        if (attr.isAutoIncrement()){
79
                                sql.append("serial");
80
                        }else{
81
                                sql.append("integer");
82
                        }
83
                } else if (type.equals(FeatureAttributeDescriptor.LONG)){
84
                        if (attr.isAutoIncrement()){
85
                                sql.append("bigserial");
86
                        }else{
87
                                sql.append("bigint");
88
                        }
89
                } else {
90
                        throw new InitializeException(this.getName(),new Exception("Unsuported type "+type));
91
                }
92
                sql.append(" ");
93

    
94
//                //DefeaultValue
95
//                if (attr.getDefaultValue() != null || (attr.getDefaultValue() == null && attr.isAllowNull() )){
96
//                        sql.append("DEFAULT ? ");
97
//                        sqlParams.add(attr.getDefaultValue());
98
//
99
//                }
100

    
101
                //Null
102
                if (attr.isAllowNull()){
103
                        sql.append("NOT NULL ");
104
                } else {
105
                        sql.append("NULL ");
106
                }
107

    
108
                // Primery key
109
                if (attr.isPrimaryKey()) {
110
                        sql.append("PRIMARY KEY ");
111
                }
112

    
113
        }
114

    
115

    
116
        public DataStoreParameters add(NewFeatureStoreParameters ndsp)
117
                        throws InitializeException, InitializeWriterException {
118
                Connection conn;
119
                try {
120
                        conn = this.getConnection();
121
                } catch (ReadException e1) {
122
                        throw new InitializeException(this.getName(),e1);
123
                }
124

    
125
                try {
126
                        conn.setAutoCommit(true);
127
                } catch (SQLException e) {
128
                        throw new InitializeException(this.getName(),e);
129
                }
130
                DataStoreParameters params = this.add(ndsp,conn);
131

    
132
                return params;
133
        }
134

    
135

    
136
        protected DataStoreParameters add(NewFeatureStoreParameters ndsp,Connection conn)
137
                throws InitializeException, InitializeWriterException {
138

    
139
                /**
140
                 * CREATE [ [ GLOBAL | LOCAL ] { TEMPORARY | TEMP } ] TABLE table_name (
141
                 * { column_name data_type [ DEFAULT default_expr ] [ column_constraint
142
                 * [ ... ] ] | table_constraint | LIKE parent_table [ { INCLUDING |
143
                 * EXCLUDING } DEFAULTS ] } [, ... ] ) [ INHERITS ( parent_table [, ...
144
                 * ] ) ] [ WITH OIDS | WITHOUT OIDS ] [ ON COMMIT { PRESERVE ROWS |
145
                 * DELETE ROWS | DROP } ]
146
                 *
147
                 * where column_constraint is:
148
                 *
149
                 * [ CONSTRAINT constraint_name ] { NOT NULL | NULL | UNIQUE | PRIMARY
150
                 * KEY | CHECK (expression) | REFERENCES reftable [ ( refcolumn ) ] [
151
                 * MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] [ ON DELETE action ] [ ON
152
                 * UPDATE action ] } [ DEFERRABLE | NOT DEFERRABLE ] [ INITIALLY
153
                 * DEFERRED | INITIALLY IMMEDIATE ]
154
                 *
155
                 * and table_constraint is:
156
                 *
157
                 * [ CONSTRAINT constraint_name ] { UNIQUE ( column_name [, ... ] ) |
158
                 * PRIMARY KEY ( column_name [, ... ] ) | CHECK ( expression ) | FOREIGN
159
                 * KEY ( column_name [, ... ] ) REFERENCES reftable [ ( refcolumn [, ...
160
                 * ] ) ] [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] [ ON DELETE
161
                 * action ] [ ON UPDATE action ] } [ DEFERRABLE | NOT DEFERRABLE ] [
162
                 * INITIALLY DEFERRED | INITIALLY IMMEDIATE ]
163
                 */
164

    
165
//                PreparedStatement st=null;
166
                Statement st=null;
167
                StringBuffer sql = new StringBuffer();
168

    
169
                if (!ndsp.isValid()){
170
                        //TODO Exception
171
                        throw new InitializeException(this.getName(),new Exception("Parameters not valid"));
172
                }
173
                PostgresqlStoreParameters param = (PostgresqlStoreParameters) ndsp
174
                                .getDataStoreParameters();
175
                DBFeatureType fType = (DBFeatureType)ndsp.getFeatureType();
176

    
177
                sql.append("Create table " + param.tableID() + "(");
178
                DBAttributeDescriptor attr;
179
                FeatureAttributeDescriptor[] fads=(FeatureAttributeDescriptor[])fType.toArray(new FeatureAttributeDescriptor[0]);
180
                for (int j = 0; j < fads.length-1; j++) {
181

    
182
//                        appendFieldToCreteSQL(attr, sql,sqlParamas);
183
                        appendFieldToCreteSQL((DBAttributeDescriptor)fads[j], sql);
184
                        sql.append(",");
185
                }
186
                attr = (DBAttributeDescriptor)fads[fads.length-1];
187
                appendFieldToCreteSQL(attr, sql);
188
                sql.append(")");
189

    
190
                try{
191
//                        st = conn.prepareStatement(sql.toString());
192
//                        for (i=0;i<sqlParamas.size();i++){
193
//                                st.setObject(i+1, sqlParamas.get(i));
194
//                        }
195
                        st = conn.createStatement();
196
                        st.execute(sql.toString());
197
                } catch (SQLException e) {
198
                        throw new InitializeException(this.getName(),e);
199
                } finally{
200
                        if (st != null){
201
                                try {
202
                                        st.close();
203
                                } catch (SQLException e) {
204
                                        // TODO ???
205
                                        e.printStackTrace();
206
                                }
207
                        }
208
                }
209
                return param;
210
        }
211

    
212
        public NewDataStoreParameters createNewDataStoreParameter()
213
                        throws InitializeException {
214
                return new PostgresqlNewStoreParameter(this.parameters
215
                                .newStoreParameters());
216
        }
217

    
218
        public void remove(DataStoreParameters dsp) throws ReadException {
219
                Connection conn = this.getConnection();
220

    
221
                try {
222
                        conn.setAutoCommit(true);
223
                } catch (SQLException e) {
224
                        throw new InitializeException(this.getName(),e);
225
                }
226
                this.remove(dsp, conn);
227
        }
228

    
229
        protected void remove(DataStoreParameters dsp,Connection conn) throws ReadException {
230
                Statement st=null;
231
                try{
232
                        st = conn.createStatement();
233
                        st.execute("Drop table "
234
                                        + ((PostgresqlStoreParameters) dsp).tableID());
235
                } catch (SQLException e) {
236
                        throw new ReadException(this.getName(),e);
237
                } finally{
238
                        if (st != null){
239
                                try {
240
                                        st.close();
241
                                } catch (SQLException e) {
242
                                        // TODO ???
243
                                        e.printStackTrace();
244
                                }
245
                        }
246
                }
247
        }
248

    
249
        public boolean canCreate() {
250
                return true;
251
        }
252

    
253
        public String getName() {
254
                return DATAEXPLORER_NAME;
255
        }
256

    
257
        public void init(DataExplorerParameters parameters) throws InitializeException {
258

    
259
                PostgresqlResource tmpResource = new PostgresqlResource(
260
                                (JDBCExplorerParameter) parameters);
261
                PostgresqlResource theResource;
262
                DefaultResourceManager resMan = DefaultResourceManager.getResourceManager();
263

    
264
                try {
265
                        theResource = (PostgresqlResource) resMan.addResource(tmpResource,
266
                                        this);
267
                } catch (DataException e1) {
268
                        throw new InitializeException(this.getName(),e1);
269
                }
270

    
271
                super.init(parameters,theResource);
272
                try {
273
                        this.defaultSchema = PostgresqlStoreUtils.getDefaultSchema(this
274
                                        .getConnection(), ((JDBCExplorerParameter) this.parameters)
275
                                        .getCatalog());
276
                } catch (ReadException e) {
277
                        throw new InitializeException(this.getName(),e);
278
                }
279
        }
280

    
281
        public DataStoreParameters[] list() throws ReadException {
282
                return this.list(((JDBCExplorerParameter)this.parameters).isShowInformationDBTables());
283
        }
284

    
285
        public DataStoreParameters[] list(boolean showInformationDBTables) throws ReadException {
286
                Connection conn = this.getConnection();
287
                StringBuffer sqlBuf = new StringBuffer();
288
                String sql;
289
                sqlBuf
290
                                .append("SELECT TABLE_CATALOG, TABLE_SCHEMA, TABLE_NAME, false as ISVIEW ");
291
                sqlBuf.append(" FROM INFORMATION_SCHEMA.TABLES ");
292
                sqlBuf.append(" xxWHERExx ");
293
                sqlBuf.append(" union ");
294
                sqlBuf
295
                                .append("SELECT TABLE_CATALOG, TABLE_SCHEMA, TABLE_NAME, true as ISVIEW ");
296
                sqlBuf.append(" FROM INFORMATION_SCHEMA.VIEWS ");
297
                sqlBuf.append(" xxWHERExx ");
298

    
299
                if (showInformationDBTables) {
300
                        sql = sqlBuf
301
                                        .toString()
302
                                        .replaceAll("xxWHERExx",
303
                                                        "");
304
                } else {
305
                        sql = sqlBuf
306
                                        .toString()
307
                                        .replaceAll("xxWHERExx",
308
                                                        "WHERE TABLE_SCHEMA NOT IN ('information_schema','pg_catalog')");
309

    
310
                }
311
                ArrayList paramList = new ArrayList();
312
                PostgresqlStoreParameters param = null;
313
                ResultSet rs = null;
314
                Statement st = null;
315
                try{
316
                        st = conn.createStatement();
317
                        rs = st.executeQuery(sql);
318
                        while (rs.next()){
319
                                param = (PostgresqlStoreParameters) this.parameters
320
                                                .newStoreParameters();
321
                                param.setCatalog(rs.getString(1));
322
                                param.setSchema(rs.getString(2));
323
                                param.setTableName(rs.getString(3));
324
                                param.setFields(new String[] { "*" });
325
                                if (rs.getBoolean(4)) {
326
                                        param.setIsView(param.IS_VIEW);
327
                                } else {
328
                                        param.setIsView(param.NOT_IS_VIEW);
329
                                }
330
                                paramList.add(param);
331
                        }
332

    
333

    
334
                } catch (SQLException e) {
335
                        throw new ReadException(this.getName(),e);
336
                } finally {
337
                        if (st != null) {
338
                                if (rs != null) {
339
                                        try {
340
                                                rs.close();
341
                                        } catch (java.sql.SQLException e) {
342
                                                throw new InitializeException(
343
                                                                PostgresqlStore.DATASTORE_NAME, e);
344
                                        }
345
                                }
346
                                try {
347
                                        st.close();
348
                                } catch (java.sql.SQLException e) {
349
                                        throw new InitializeException(
350
                                                        PostgresqlStore.DATASTORE_NAME, e);
351
                                }
352

    
353
                        }
354

    
355
                }
356

    
357

    
358
                return (DataStoreParameters[]) paramList
359
                                .toArray(new PostgresqlStoreParameters[0]);
360

    
361
        }
362

    
363
        public FeatureType[] getFeatureTypes(DataStoreParameters dsp) throws ReadException {
364
                return new FeatureType[] { PostgresqlStoreUtils.getFeatureType(this
365
                                .getConnection(), (PostgresqlStoreParameters) dsp) };
366
        }
367

    
368
        public String getDefaultSchema(){
369
                return this.defaultSchema;
370
        }
371

    
372
        /* (non-Javadoc)
373
         * @see org.gvsig.fmap.dal.DataExplorer#dispose()
374
         */
375
        public void dispose() throws DataException {
376
                ResourceManager resMan = DefaultResourceManager.getResourceManager();
377

    
378
            try {
379
                        resMan.remove(this.resource, this);
380
                } catch (DataException e1) {
381
                        throw new CloseException(this.getName(),e1);
382
                } catch (KeyException e) {
383
                        throw new CloseException(this.getName(),e);
384
                }
385

    
386
        }
387

    
388
}