Statistics
| Revision:

svn-gvsig-desktop / trunk / extensions / extJDBC / src / com / iver / cit / gvsig / jdbc_spatial / util / PostGIS.java @ 4740

History | View | Annotate | Download (8.62 KB)

1
/*
2
 * Created on 26-oct-2005
3
 *
4
 * gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
5
 * 
6
 * Copyright (C) 2004 IVER T.I. and Generalitat Valenciana.
7
 * 
8
 * This program is free software; you can redistribute it and/or
9
 * modify it under the terms of the GNU General Public License
10
 * as published by the Free Software Foundation; either version 2
11
 * of the License, or (at your option) any later version.
12
 *  
13
 * This program is distributed in the hope that it will be useful,
14
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16
 * GNU General Public License for more details.
17
 * 
18
 * You should have received a copy of the GNU General Public License
19
 * along with this program; if not, write to the Free Software
20
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
21
 *  
22
 * For more information, contact:
23
 *
24
 *  Generalitat Valenciana
25
 *   Conselleria d'Infraestructures i Transport
26
 *   Av. Blasco Ib??ez, 50
27
 *   46010 VALENCIA
28
 *   SPAIN
29
 *
30
 *      +34 963862235
31
 *   gvsig@gva.es
32
 *      www.gvsig.gva.es
33
 * 
34
 *    or
35
 * 
36
 *   IVER T.I. S.A
37
 *   Salamanca 50
38
 *   46005 Valencia
39
 *   Spain
40
 * 
41
 *   +34 963163400
42
 *   dac@iver.es
43
 */
44
package com.iver.cit.gvsig.jdbc_spatial.util;
45

    
46
import java.io.ByteArrayOutputStream;
47
import java.io.PrintStream;
48
import java.io.UnsupportedEncodingException;
49
import java.sql.Types;
50

    
51
import com.hardcode.gdbms.engine.values.Value;
52
import com.hardcode.gdbms.engine.values.ValueWriter;
53
import com.iver.cit.gvsig.fmap.core.FShape;
54
import com.iver.cit.gvsig.fmap.core.IFeature;
55
import com.iver.cit.gvsig.fmap.drivers.DBLayerDefinition;
56
import com.iver.cit.gvsig.fmap.drivers.FieldDescription;
57
import com.iver.cit.gvsig.jdbc_spatial.XTypes;
58

    
59
public class PostGIS {
60

    
61
        public static String toEncode;
62

    
63
        /**
64
         * Mover esto a IverUtiles
65
         * 
66
         * @param val
67
         * @return
68
         */
69
        public static boolean isNumeric(Value val) {
70

    
71
                switch (val.getSQLType()) {
72
                case Types.DOUBLE:
73
                case Types.FLOAT:
74
                case Types.INTEGER:
75
                case Types.SMALLINT:
76
                case Types.BIGINT:
77
                case Types.NUMERIC:
78
                case Types.REAL:
79
                case Types.TINYINT:
80
                        return true;
81
                }
82

    
83
                return false;
84
        }
85

    
86
        /**
87
         * @param dbLayerDef
88
         * @param fieldTypes
89
         *            (see java.sql.Types)
90
         */
91
        public static String getSqlCreateSpatialTable(DBLayerDefinition dbLayerDef,
92
                        FieldDescription[] fieldsDescr) {
93

    
94
                String resul;
95
                boolean bExistGID = false;
96
                for (int i = 0; i < dbLayerDef.getFieldNames().length; i++) {
97
                        if (dbLayerDef.getFieldNames()[i].equalsIgnoreCase("gid")) {
98
                                bExistGID = true;
99
                                break;
100
                        }
101
                }
102
                if (bExistGID) // Usamos el existente y no a?adimos ninguno nosotros
103
                        resul = "CREATE TABLE " + dbLayerDef.getTableName() + " (";
104
                else
105
                        resul = "CREATE TABLE " + dbLayerDef.getTableName()
106
                                        + " (gid serial PRIMARY KEY, ";
107
                for (int i = 0; i < dbLayerDef.getFieldNames().length; i++) {
108
                        int fieldType = fieldsDescr[i].getFieldType();
109
                        String strType = XTypes.fieldTypeToString(fieldType);
110
                        /*
111
                         * if (fieldType == Types.VARCHAR) strType = strType + "(" +
112
                         * fieldsDescr[i].getFieldLength() + ")";
113
                         */
114
                        if (i == 0)
115
                                resul = resul + dbLayerDef.getFieldNames()[i] + " " + strType;
116
                        else
117
                                resul = resul + ", " + dbLayerDef.getFieldNames()[i] + " "
118
                                                + strType;
119
                }
120
                resul = resul + ");";
121
                return resul;
122
        }
123

    
124
        public static String getSqlAlterTable(DBLayerDefinition dbLayerDef) {
125
                String strGeometryFieldType;
126
                strGeometryFieldType = "GEOMETRY";
127

    
128
                switch (dbLayerDef.getShapeType()) {
129
                case FShape.POINT:
130
                        strGeometryFieldType = XTypes.fieldTypeToString(XTypes.POINT2D);
131
                        break;
132
                case FShape.LINE:
133
                        strGeometryFieldType = XTypes.fieldTypeToString(XTypes.LINE2D);
134
                        break;
135
                case FShape.POLYGON:
136
                        strGeometryFieldType = XTypes.fieldTypeToString(XTypes.POLYGON2D);
137
                        break;
138
                case FShape.MULTI:
139
                        strGeometryFieldType = XTypes.fieldTypeToString(XTypes.MULTI2D);
140
                        break;
141
                }
142

    
143
                String result = "SELECT AddGeometryColumn('"
144
                                + dbLayerDef.getCatalogName() + "', '"
145
                                + dbLayerDef.getTableName() + "', '"
146
                                + dbLayerDef.getFieldGeometry() + "', "
147
                                + dbLayerDef.getSRID_EPSG() + ", '" + strGeometryFieldType + "', "
148
                                + dbLayerDef.getDimension() + ");";
149

    
150
                return result;
151
        }
152

    
153
        /**
154
         * From geotools Adds quotes to an object for storage in postgis. The object
155
         * should be a string or a number. To perform an insert strings need quotes
156
         * around them, and numbers work fine with quotes, so this method can be
157
         * called on unknown objects.
158
         * 
159
         * @param value
160
         *            The object to add quotes to.
161
         * 
162
         * @return a string representation of the object with quotes.
163
         */
164
        protected static String addQuotes(Object value) {
165
                String retString;
166

    
167
                if (value != null) {
168
                        retString = "'" + doubleQuote(value) + "'";
169
                } else {
170
                        retString = "null";
171
                }
172

    
173
                return retString;
174
        }
175

    
176
        static String doubleQuote(Object obj) {
177
                String aux = obj.toString().replaceAll("'", "''");
178
                StringBuffer strBuf = new StringBuffer(aux);
179
                ByteArrayOutputStream out = new ByteArrayOutputStream(strBuf.length());
180
                PrintStream printStream = new PrintStream(out);
181
                printStream.print(aux);
182
                String aux2 = "ERROR";
183
                try {
184
                        aux2 = out.toString(toEncode);
185
                        System.out.println(aux + " " + aux2);
186
                } catch (UnsupportedEncodingException e) {
187
                        // TODO Auto-generated catch block
188
                        e.printStackTrace();
189
                }
190

    
191
                return aux2;
192
        }
193

    
194
        /**
195
         * Based in code from JUMP (VividSolutions) and Geotools Things to be aware:
196
         * We always will use Spatial Tables with Unique ID. IFeature has the same
197
         * field order than dbLayerDef.getFieldNames()
198
         * 
199
         * @param dbLayerDef
200
         * @param feat
201
         * @return
202
         */
203
        public static String getSqlInsertFeature(DBLayerDefinition dbLayerDef,
204
                        IFeature feat) {
205
                StringBuffer sqlBuf = new StringBuffer("INSERT INTO "
206
                                + dbLayerDef.getTableName() + " (");
207
                String sql = null;
208
                int numAlphanumericFields = dbLayerDef.getFieldNames().length;
209

    
210
                for (int i = 0; i < numAlphanumericFields; i++) {
211
                        String name = dbLayerDef.getFieldNames()[i];
212
                        // if (cols.contains(name) && (!name.equals(uniqueCol) ||
213
                        // existsUnique)) {
214
                        sqlBuf.append(" " + name + ",");
215
                        // }
216
                }
217
                sqlBuf.append(" " + dbLayerDef.getFieldGeometry());
218
                // sqlBuf.deleteCharAt(sqlBuf.lastIndexOf(","));
219
                sqlBuf.append(" ) VALUES (");
220
                String insertQueryHead = sqlBuf.toString();
221
                sqlBuf = new StringBuffer(insertQueryHead);
222
                for (int j = 0; j < numAlphanumericFields; j++) {
223
                        if (isNumeric(feat.getAttribute(j)))
224
                                sqlBuf.append(feat.getAttribute(j) + ", ");
225
                        else
226
                                sqlBuf.append(addQuotes(feat.getAttribute(j)) + ", ");
227
                }
228
                sqlBuf.append(" GeometryFromText( '"
229
                                + feat.getGeometry().toJTSGeometry().toText() + "', "
230
                                + dbLayerDef.getSRID_EPSG() + ")");
231

    
232
                // sqlBuf.deleteCharAt(sqlBuf.lastIndexOf(","));
233
                sqlBuf.append(" ) ");
234
                sql = sqlBuf.toString();
235
                return sql;
236
        }
237

    
238
        static public String getSqlCreateIndex(DBLayerDefinition lyrDef) {
239
                String indexName = lyrDef.getTableName() + "_"
240
                                + lyrDef.getFieldGeometry() + "_gist";
241
                String sql = "CREATE INDEX \"" + indexName + "\" ON \""
242
                                + lyrDef.getTableName() + "\" USING GIST (\""
243
                                + lyrDef.getFieldGeometry() + "\" GIST_GEOMETRY_OPS)";
244

    
245
                return sql;
246
        }
247

    
248
        public static String getSqlModifyFeature(DBLayerDefinition dbLayerDef, IFeature feat) {
249
                /* 
250
                         UPDATE weather
251
                         SET temp_hi = temp_hi - 2,  temp_lo = temp_lo - 2
252
                         WHERE date > '1994-11-28';
253
                 */
254
                StringBuffer sqlBuf = new StringBuffer("UPDATE "
255
                                + dbLayerDef.getTableName() + " SET");
256
                String sql = null;
257
                int numAlphanumericFields = dbLayerDef.getFieldsDesc().length;
258

    
259
                for (int i = 0; i < numAlphanumericFields; i++) {
260
                        FieldDescription fldDesc = dbLayerDef.getFieldsDesc()[i];
261
                        if (fldDesc != null)
262
                        {
263
                                String name = fldDesc.getFieldName();
264
                                Value val = feat.getAttribute(i);
265
                                if (val != null)
266
                                {
267
                                        String strAux = val.getStringValue(ValueWriter.internalValueWriter);
268
                                        sqlBuf.append(" " + name + " = " + strAux + " ,");
269
                                }
270
                        }
271
                }
272
                sqlBuf.deleteCharAt(sqlBuf.lastIndexOf(","));
273
                if (feat.getGeometry() != null)
274
                {
275
                        sqlBuf.append(", " + dbLayerDef.getFieldGeometry());                
276
                        sqlBuf.append(" = ");
277
                        sqlBuf.append(" GeometryFromText( '"
278
                                + feat.getGeometry().toJTSGeometry().toText() + "', "
279
                                + dbLayerDef.getSRID_EPSG() + ")");
280
                }
281
                sqlBuf.append(" WHERE ");
282
                sqlBuf.append(dbLayerDef.getFieldID() + " = " + feat.getID());
283
                sql = sqlBuf.toString();
284
                return sql;
285

    
286
        }
287

    
288
        public static String getSqlDeleteFeature(DBLayerDefinition dbLayerDef, IFeature feat) {
289
                // DELETE FROM weather WHERE city = 'Hayward';
290
                StringBuffer sqlBuf = new StringBuffer("DELETE "
291
                                + dbLayerDef.getTableName() + " WHERE ");
292
                String sql = null;
293
                sqlBuf.append(dbLayerDef.getFieldID() + " = " + feat.getID());
294
                sql = sqlBuf.toString();
295

    
296
                return sql;
297
        }
298

    
299
}