Statistics
| Revision:

svn-gvsig-desktop / trunk / libraries / libDataSourceDBBaseDrivers / src / org / gvsig / data / datastores / vectorial / db / jdbc / h2 / H2FeaturesWriter.java @ 20376

History | View | Annotate | Download (12.2 KB)

1
package org.gvsig.data.datastores.vectorial.db.jdbc.h2;
2

    
3
import java.sql.Connection;
4
import java.sql.DatabaseMetaData;
5
import java.sql.PreparedStatement;
6
import java.sql.ResultSet;
7
import java.sql.SQLException;
8
import java.sql.Statement;
9
import java.util.Iterator;
10

    
11
import org.gvsig.data.IDataExplorer;
12
import org.gvsig.data.IDataStoreParameters;
13
import org.gvsig.data.datastores.vectorial.ISelectiveWriter;
14
import org.gvsig.data.datastores.vectorial.db.DBFeatureType;
15
import org.gvsig.data.datastores.vectorial.db.jdbc.JDBCAttributeDescriptor;
16
import org.gvsig.data.datastores.vectorial.db.jdbc.JDBCFeature;
17
import org.gvsig.data.datastores.vectorial.db.jdbc.JDBCFeaturesWriter;
18
import org.gvsig.data.datastores.vectorial.db.jdbc.JDBCTypes;
19
import org.gvsig.data.exception.InitializeException;
20
import org.gvsig.data.exception.InitializeWriterException;
21
import org.gvsig.data.exception.ReadException;
22
import org.gvsig.data.exception.WriteException;
23
import org.gvsig.data.vectorial.IFeature;
24
import org.gvsig.data.vectorial.IFeatureAttributeDescriptor;
25
import org.gvsig.data.vectorial.IFeatureStore;
26
import org.gvsig.data.vectorial.IFeatureType;
27
import org.gvsig.data.vectorial.INewFeatureStoreParameters;
28

    
29
import com.iver.cit.gvsig.fmap.core.FShape;
30
import com.iver.cit.gvsig.fmap.core.IGeometry;
31
import com.vividsolutions.jts.io.WKBWriter;
32

    
33
class H2FeaturesWriter extends JDBCFeaturesWriter implements ISelectiveWriter {
34
        DBFeatureType featureType;
35
        boolean bCreateTable=false;
36
        private String toEncode;
37
        H2StoreParameters parameters;
38

    
39
        private PreparedStatement insertSt;
40
        private PreparedStatement updateSt;
41

    
42
        private static WKBWriter wkbWriter = new WKBWriter();
43

    
44
        H2FeaturesWriter(){
45

    
46
        }
47

    
48
        public void init(IFeatureStore store) {
49
                super.init(store);
50
                H2Store h2Store = (H2Store)store;
51
                this.parameters=h2Store.getParametersH2();
52
                this.featureType = (DBFeatureType)this.store.getDefaultFeatureType();
53

    
54
        }
55

    
56
        public void preProcess() throws WriteException, ReadException {
57
                super.preProcess();
58

    
59
                if (bCreateTable) {
60
                        H2Explorer explorer = (H2Explorer)this.store.getExplorer();
61

    
62
                        IDataStoreParameters params =this.store.getParameters();
63
                        explorer.remove(params,conex);
64

    
65
                        INewFeatureStoreParameters newParam = (INewFeatureStoreParameters)explorer.createNewDataStoreParameter();
66

    
67

    
68
                        newParam.setFeatureType(this.featureType);
69
                        explorer.add(newParam,conex);
70
                }
71
        }
72

    
73
        public void deleteFeature(IFeature feature) throws WriteException {
74
                Statement st;
75
                String sqlDelete = getSqlDeleteFeature(featureType, (JDBCFeature)feature);
76
                System.out.println("sql = " + sqlDelete);
77
                try {
78
                        st = this.conex.createStatement();
79
                        st.execute(sqlDelete);
80
                } catch (SQLException e) {
81
                        throw new WriteException(this.store.getName(),e);
82
                }
83

    
84
        }
85

    
86
        public void insertFeature(IFeature feature) throws WriteException {
87

    
88
                DBFeatureType ftype = (DBFeatureType)feature.getType();
89

    
90
                try {
91
                        PreparedStatement ps=this.getInsertFeatureStatement(ftype);
92
                        Iterator it = ftype.iterator();
93

    
94
                        int index= 1;
95
                        while (it.hasNext()){
96
                                JDBCAttributeDescriptor fad=(JDBCAttributeDescriptor)it.next();
97
                                if (fad.isReadOnly())
98
                                        continue;
99

    
100

    
101
                                loadValueInPreparedStatement(ps, index, fad, feature);
102
                                index++;
103
                        }
104
//                        ps.setObject(index, feature.get(ftype.getFieldIdIndex()));
105

    
106
                        ps.execute();
107

    
108
                } catch (SQLException e) {
109
                        throw new WriteException(this.store.getName(),e);
110
                }
111
        }
112

    
113
        private PreparedStatement getInsertFeatureStatement(DBFeatureType ftype) throws SQLException {
114
                if (this.insertSt == null){
115
                        StringBuffer fields = new StringBuffer();
116
                        StringBuffer values = new StringBuffer();
117
                        StringBuffer sql = new StringBuffer();
118

    
119
                        Iterator iter = ftype.iterator();
120
                        JDBCAttributeDescriptor fad;
121
                        while (iter.hasNext()){
122
                                fad=(JDBCAttributeDescriptor)iter.next();
123
                                String name = fad.getName();
124
                                if (fad.isReadOnly())
125
                                        continue;
126
                                fields.append(name+",");
127
                                values.append("?,");
128

    
129
                        }
130
                        sql.append("INSERT INTO "+ftype.getTableID()+" (");
131
                        sql.append(fields.substring(0, fields.length()-1));
132
                        sql.append(") VALUES (");
133
                        sql.append(values.substring(0, values.length()-1));
134
                        sql.append(")");
135

    
136
                        this.insertSt= this.conex.prepareStatement(sql.toString());
137
                        System.out.println(sql.toString());
138
                } else{
139
                        this.insertSt.clearParameters();
140
                }
141
                return this.insertSt;
142

    
143
        }
144

    
145
        public void updateFeatureType(IFeatureType featureType) {
146
                this.featureType=(DBFeatureType)featureType;
147
        }
148

    
149
        /**
150
         * @param createTable
151
         *            The bCreateTable to set.
152
         */
153
        public void setCreateTable(boolean createTable) {
154
                bCreateTable = createTable;
155
        }
156

    
157
        boolean dropTableIfExist() throws SQLException{
158
                if (!this.existTable(parameters.getSchema(), parameters.getTableName())){
159
                        return false;
160
                }
161
                Statement st = conex.createStatement();
162
                st.execute("DROP TABLE " + parameters.tableID() + ";");
163
                st.close();
164
                return false;
165
        }
166
        private boolean existTable(String schema, String tableName) throws SQLException{
167
                boolean exists =false;
168
                DatabaseMetaData metadata = conex.getMetaData();
169

    
170
                ResultSet rs = metadata.getTables(null, schema, tableName, null);
171

    
172
                exists = !rs.isAfterLast();
173
                rs.close();
174

    
175
                return exists;
176
        }
177

    
178
        public void updateFeature(IFeature oldFeature, IFeature feature) throws WriteException, ReadException {
179

    
180
                DBFeatureType ftype = (DBFeatureType)feature.getType();
181

    
182
                try {
183
                        PreparedStatement ps=this.getUpdateFeatureStatement(ftype);
184
                        Iterator it = ftype.iterator();
185

    
186
                        int index= 1;
187
                        while (it.hasNext()){
188
                                JDBCAttributeDescriptor fad=(JDBCAttributeDescriptor)it.next();
189
                                if (fad.isPrimaryKey())
190
                                        continue;
191
                                loadValueInPreparedStatement(ps, index, fad, feature);
192
                                index++;
193
                        }
194

    
195
                        loadPkInPreparedStatement(ps, index, ftype, feature);
196

    
197
                        ps.execute();
198

    
199
                } catch (SQLException e) {
200
                        throw new WriteException(this.store.getName(),e);
201
                }
202
        }
203

    
204
        public void deleteAttribute(IFeatureAttributeDescriptor attribute) throws WriteException {
205
                try {
206
                        Statement st = conex.createStatement();
207
                        String sql = "ALTER TABLE " + parameters.tableID() + " DROP COLUMN "
208
                                + attribute.getName() + ";";
209
                        st.execute(sql);
210
                } catch (SQLException e) {
211
                        throw new WriteException(this.store.getName(),e);
212
                }
213
        }
214

    
215
        public void updateAttribute(IFeatureAttributeDescriptor oldAttribute, IFeatureAttributeDescriptor attribute) throws WriteException, ReadException {
216
                try {
217
                        Statement st = conex.createStatement();
218
                        String sql = "ALTER TABLE " + parameters.tableID() + " RENAME COLUMN "
219
                        + oldAttribute.getName() + " TO " + attribute.getName() + ";";
220
                        st.execute(sql);
221
                } catch (SQLException e) {
222
                        throw new WriteException(this.store.getName(),e);
223
                }
224
        }
225

    
226
        public void insertAttribute(IFeatureAttributeDescriptor attribute) throws WriteException {
227
                try {
228
                        Statement st = conex.createStatement();
229

    
230
                        String sql = "ALTER TABLE "
231
                                + parameters.tableID()
232
                                + " ADD COLUMN "
233
                                + attribute.getName()
234
                                + " "
235
                                + JDBCTypes.fieldTypeToString(attribute.getDataType())
236
                                + " "
237
                                + "DEFAULT " + attribute.getDefaultValue()
238
                                + ";";
239
                        st.execute(sql);
240
                } catch (SQLException e) {
241
                        throw new WriteException(this.store.getName(),e);
242
                }
243
        }
244

    
245

    
246
        public boolean canWriteGeometry(int gvSIGgeometryType) {
247
                switch (gvSIGgeometryType) {
248
                case FShape.POINT:
249
                        return true;
250
                case FShape.LINE:
251
                        return true;
252
                case FShape.POLYGON:
253
                        return true;
254
                case FShape.ARC:
255
                        return false;
256
                case FShape.ELLIPSE:
257
                        return false;
258
                case FShape.MULTIPOINT:
259
                        return true;
260
                case FShape.TEXT:
261
                        return false;
262
                }
263
                return false;
264
        }
265

    
266

    
267
        private PreparedStatement getUpdateFeatureStatement(DBFeatureType dbFeatureType) throws SQLException{
268
                if (this.updateSt == null){
269
                        StringBuffer sqlBuf = new StringBuffer("UPDATE "
270
                                        + this.parameters.tableID() + " SET");
271
                        String sql = null;
272

    
273
                        Iterator iter = dbFeatureType.iterator();
274
                        while (iter.hasNext()){
275
                                IFeatureAttributeDescriptor fad=(IFeatureAttributeDescriptor)iter.next();
276
                                String name = fad.getName();
277
                                // El campo gid no lo actualizamos.
278
                                if (fad.isPrimaryKey())
279
                                        continue;
280
                                sqlBuf.append(" " + name + " = ? ,");
281

    
282
                        }
283
                        sqlBuf.deleteCharAt(sqlBuf.lastIndexOf(","));
284
                        sqlBuf.append(" WHERE ");
285
                        sqlBuf.append(getFliterForIDForPStatement(dbFeatureType));
286
                        sql = sqlBuf.toString();
287

    
288

    
289
                        this.updateSt= this.conex.prepareStatement(sql);
290
                } else{
291
                        this.updateSt.clearParameters();
292
                }
293
                return this.updateSt;
294

    
295
        }
296

    
297
        public String getSqlDeleteFeature(DBFeatureType dbFeatureType, JDBCFeature feature) {
298
                StringBuffer sqlBuf = new StringBuffer("DELETE FROM "
299
                                + this.parameters.tableID() + " WHERE ");
300
                String sql = null;
301
                sqlBuf.append(((JDBCFeature)feature).getFilterForID());
302
                sql = sqlBuf.toString();
303

    
304
                return sql;
305
        }
306

    
307
        public static void create(H2StoreParameters parameters, IFeatureType featureType)throws InitializeWriterException, InitializeException {
308
                Connection con = H2Utils.getConnection(parameters.getUrl(), parameters.getUser(), parameters.getPassw());
309

    
310
                StringBuffer sb=new StringBuffer();
311
                sb.append("CREATE TABLE ");
312
                sb.append(parameters.tableID());
313
                sb.append(" (");
314
                sb.append("id int, ");
315
                for (int i=0 ; i<featureType.size() ; i++){
316
                        IFeatureAttributeDescriptor descriptor=(IFeatureAttributeDescriptor)featureType.get(i);
317
                        String type = descriptor.getDataType();
318

    
319
                        if (type.equals(IFeatureAttributeDescriptor.TYPE_BOOLEAN)){
320
                                sb.append(descriptor.getName());
321
                                sb.append(" bit, ");
322
                        }else if (type.equals(IFeatureAttributeDescriptor.TYPE_BYTE)){
323
                                sb.append(descriptor.getName());
324
                                sb.append(" byte, ");
325
                        }else if (type.equals(IFeatureAttributeDescriptor.TYPE_DATE)){
326
                                sb.append(descriptor.getName());
327
                                sb.append(" date, ");
328
                        }else if (type.equals(IFeatureAttributeDescriptor.TYPE_DOUBLE)){
329
                                sb.append(descriptor.getName());
330
                                sb.append(" double, ");
331
                        }else if (type.equals(IFeatureAttributeDescriptor.TYPE_FLOAT)){
332
                                sb.append(descriptor.getName());
333
                                sb.append(" float, ");
334
                        }else if (type.equals(IFeatureAttributeDescriptor.TYPE_INT)){
335
                                sb.append(descriptor.getName());
336
                                sb.append(" int, ");
337
                        }else if (type.equals(IFeatureAttributeDescriptor.TYPE_LONG)){
338
                                sb.append(descriptor.getName());
339
                                sb.append(" bigint, ");
340
                        }else if (type.equals(IFeatureAttributeDescriptor.TYPE_STRING)){
341
                                sb.append(descriptor.getName());
342
                                sb.append(" varchar, ");
343
                        }else if (type.equals(IFeatureAttributeDescriptor.TYPE_GEOMETRY)){
344
                                sb.append(descriptor.getName());
345
                                sb.append(" other, ");
346
                        }else {
347
                                System.out.print(" ---- " + "TYPE UNKNOWN");
348
                        }
349
                }
350
                String createTable=sb.toString();
351
                createTable=createTable.substring(0, createTable.length()-2);
352
                createTable+=")";
353

    
354
                try{
355
                        Statement st=con.createStatement();
356
                        st.execute(createTable);
357
                        st.close();
358
                }
359
                catch(SQLException except){
360
                        throw new InitializeWriterException(parameters.getDataStoreName(),except);
361

    
362
                }
363
        }
364

    
365
        protected void loadPkInPreparedStatement(PreparedStatement ps,int paramIndex,DBFeatureType fType,IFeature feature) throws java.sql.SQLException{
366
                if (fType.getFieldsId().length != 1)
367
                        throw new UnsupportedOperationException("ID fields > 1");
368
                String id =fType.getFieldsId()[0];
369
                loadValueInPreparedStatement(ps, paramIndex, (JDBCAttributeDescriptor)fType.get(fType.getFieldIndex(id)), feature);
370
        }
371

    
372
        protected void loadValueInPreparedStatement(PreparedStatement ps,int paramIndex,JDBCAttributeDescriptor attr,IFeature feature) throws java.sql.SQLException{
373
                Object value = feature.get(attr.ordinal());
374
                if (value == null){
375
                        ps.setNull(paramIndex, attr.getSqlType());
376
                        return;
377
                }
378

    
379
                if (attr.getDataType() == IFeatureAttributeDescriptor.TYPE_GEOMETRY){
380
                        IGeometry geom =(IGeometry)feature.get(attr.ordinal());
381
                        ps.setBytes(
382
                                paramIndex,        wkbWriter.write(geom.toJTSGeometry())
383
                        );
384
                        return;
385
                }
386
                ps.setObject(paramIndex, feature.get(attr.ordinal()));
387
        }
388

    
389
        protected static String getFliterForIDForPStatement(DBFeatureType fType) {
390
                if (fType.getFieldsId().length != 1)
391
                        throw new UnsupportedOperationException("ID fields > 1");
392
                String id =fType.getFieldsId()[0];
393
                return id + " = ?";
394
        }
395
}