Revision 5

View differences:

trunk/org.gvsig.postgresql/org.gvsig.postgresql.provider/pom.xml
1
<?xml version="1.0" encoding="UTF-8"?>
2

  
3
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4

  
5
  <modelVersion>4.0.0</modelVersion>
6
  <artifactId>org.gvsig.postgresql.provider</artifactId>
7
  <packaging>jar</packaging>
8
  <name>${project.artifactId}</name>
9
  <description>DAL provider for PostgeSQL files</description>
10
  <parent>
11
      <groupId>org.gvsig</groupId>
12
      <artifactId>org.gvsig.postgresql</artifactId>
13
      <version>2.0.10-SNAPSHOT</version>
14
  </parent>
15

  
16
  <dependencies>
17

  
18
    <dependency>
19
        <groupId>org.gvsig</groupId>
20
        <artifactId>org.gvsig.tools.lib</artifactId>
21
        <scope>compile</scope>
22
    </dependency>
23
    <dependency>
24
        <groupId>org.gvsig</groupId>
25
        <artifactId>org.gvsig.projection.api</artifactId>
26
        <scope>compile</scope>
27
    </dependency>
28
    <dependency>
29
        <groupId>org.gvsig</groupId>
30
        <artifactId>org.gvsig.fmap.dal.api</artifactId>
31
        <scope>compile</scope>
32
    </dependency>
33
    
34
    <dependency>
35
        <groupId>org.gvsig</groupId>
36
        <artifactId>org.gvsig.fmap.dal.db.jdbc</artifactId>
37
        <scope>compile</scope>
38
    </dependency>
39

  
40
    <dependency>
41
        <groupId>org.gvsig</groupId>
42
        <artifactId>org.gvsig.fmap.dal.db.lib</artifactId>
43
        <scope>compile</scope>
44
    </dependency>
45
    
46
    <dependency>
47
        <groupId>org.gvsig</groupId>
48
        <artifactId>org.gvsig.fmap.dal.spi</artifactId>
49
        <scope>compile</scope>
50
    </dependency>
51
    <dependency>
52
        <groupId>org.gvsig</groupId>
53
        <artifactId>org.gvsig.metadata.lib.basic.api</artifactId>
54
        <scope>compile</scope>
55
    </dependency>
56
    <dependency>
57
        <groupId>org.gvsig</groupId>
58
        <artifactId>org.gvsig.fmap.geometry.api</artifactId>
59
        <scope>compile</scope>
60
    </dependency>
61
    
62
    <dependency>
63
        <groupId>org.gvsig</groupId>
64
        <artifactId>org.gvsig.fmap.geometry.operation</artifactId>
65
        <scope>compile</scope>
66
    </dependency>
67
    
68
    <dependency>
69
        <groupId>org.gvsig</groupId>
70
        <artifactId>org.gvsig.timesupport.lib.api</artifactId>
71
        <scope>compile</scope>
72
    </dependency>  
73
    <dependency>
74
      <groupId>org.gvsig</groupId>
75
      <artifactId>org.gvsig.utils</artifactId>
76
      <scope>compile</scope>
77
    </dependency>
78
    <dependency>
79
      <groupId>postgresql</groupId>
80
      <artifactId>postgresql</artifactId>
81
      <scope>compile</scope>
82
    </dependency>
83
    <dependency>
84
      <groupId>commons-dbcp</groupId>
85
      <artifactId>commons-dbcp</artifactId>
86
      <scope>compile</scope>
87
    </dependency>
88
    <dependency>
89
      <groupId>commons-collections</groupId>
90
      <artifactId>commons-collections</artifactId>
91
      <scope>compile</scope>
92
    </dependency>
93

  
94

  
95
    <!-- TESTS -->
96
    <dependency>
97
      <groupId>org.gvsig</groupId>
98
      <artifactId>org.gvsig.tools.lib</artifactId>
99
      <type>test-jar</type>
100
      <scope>test</scope>
101
    </dependency>
102
    <dependency>
103
      <groupId>org.gvsig</groupId>
104
      <artifactId>org.gvsig.compat.se</artifactId>
105
      <scope>test</scope>
106
    </dependency>
107
    <dependency>
108
      <groupId>org.gvsig</groupId>
109
      <artifactId>org.gvsig.fmap.dal.impl</artifactId>
110
      <scope>test</scope>
111
    </dependency>
112
    
113
    <!--
114
    <dependency>
115
      <groupId>org.gvsig</groupId>
116
      <artifactId>org.gvsig.fmap.dal.index.spatial.jts</artifactId>
117
      <scope>test</scope>
118
    </dependency>
119
    -->
120
    
121
    <dependency>
122
      <groupId>org.gvsig</groupId>
123
      <artifactId>org.gvsig.fmap.geometry.impl</artifactId>
124
      <scope>test</scope>
125
    </dependency>
126
    <dependency>
127
      <groupId>org.gvsig</groupId>
128
      <artifactId>org.gvsig.projection.cresques.impl</artifactId>
129
      <scope>test</scope>
130
    </dependency>
131
    <dependency>
132
      <groupId>org.gvsig</groupId>
133
      <artifactId>org.gvsig.timesupport.lib.impl</artifactId>
134
      <scope>test</scope>
135
    </dependency>   
136

  
137

  
138
  </dependencies>
139

  
140
</project>
trunk/org.gvsig.postgresql/org.gvsig.postgresql.provider/src/test/java/org/gvsig/fmap/dal/store/postgresql/TestPostgreSQLWrite.java
1
/* gvSIG. Geographic Information System of the Valencian Government
2
*
3
* Copyright (C) 2007-2008 Infrastructures and Transports Department
4
* of the Valencian Government (CIT)
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 2
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
*/
22

  
23
/*
24
* AUTHORS (In addition to CIT):
25
* 2009 IVER T.I   {{Task}}
26
*/
27

  
28
/**
29
 *
30
 */
31
package org.gvsig.fmap.dal.store.postgresql;
32

  
33
import java.util.Iterator;
34

  
35
import org.gvsig.fmap.dal.DataStoreParameters;
36
import org.gvsig.fmap.dal.exception.DataException;
37
import org.gvsig.fmap.dal.feature.BaseTestEditableFeatureStore;
38
import org.gvsig.fmap.dal.feature.EditableFeatureAttributeDescriptor;
39
import org.gvsig.fmap.dal.feature.EditableFeatureType;
40
import org.gvsig.fmap.dal.feature.FeatureAttributeDescriptor;
41
import org.gvsig.fmap.dal.feature.FeatureQuery;
42
import org.gvsig.fmap.dal.feature.FeatureStore;
43
import org.gvsig.fmap.dal.feature.FeatureStoreTransform;
44
import org.gvsig.fmap.dal.feature.FeatureType;
45
import org.gvsig.fmap.dal.feature.NewFeatureStoreParameters;
46
import org.gvsig.fmap.dal.store.jdbc.JDBCServerExplorer;
47
import org.gvsig.fmap.geom.Geometry;
48
import org.gvsig.fmap.geom.operation.towkt.ToWKT;
49
import org.gvsig.tools.evaluator.Evaluator;
50
import org.gvsig.tools.evaluator.EvaluatorData;
51
import org.gvsig.tools.evaluator.EvaluatorException;
52
import org.gvsig.tools.evaluator.EvaluatorFieldsInfo;
53

  
54

  
55

  
56
/**
57
 * @author jmvivo
58
 *
59
 */
60
// public class TestPostgreSQL extends BaseTestEditableFeatureStore {
61
public class TestPostgreSQLWrite extends BaseTestEditableFeatureStore {
62

  
63

  
64
	private JDBCServerExplorer myExplorer;
65
	private PostgreSQLNewStoreParameters newParams;
66

  
67
	@Override
68
	protected void doSetUp() throws Exception {
69
		// Initialize wkt geom operation
70
		int wktCode = ToWKT.CODE;
71
	}
72

  
73
	public DataStoreParameters getDefaultDataStoreParameters()
74
			throws DataException {
75
		PostgreSQLStoreParameters pgParameters = null;
76
		pgParameters = (PostgreSQLStoreParameters) dataManager
77
				.createStoreParameters(PostgreSQLStoreProvider.NAME);
78

  
79
		pgParameters.setHost("localhost");
80
		pgParameters.setUser("postgres");
81
		pgParameters.setPassword("postgres");
82
		pgParameters.setDBName("gis");
83
		pgParameters.setTable("muni10000_peq");
84

  
85
		return pgParameters;
86
	}
87

  
88
	public boolean hasExplorer() {
89
		return true;
90
	}
91

  
92
	public void testLoadMetadata() throws Exception {
93
		DataStoreParameters params = this.getDefaultDataStoreParameters();
94

  
95
		FeatureStore store = null;
96
		store = (FeatureStore) dataManager.createStore(params);
97
		FeatureType fType = store.getDefaultFeatureType();
98
		FeatureAttributeDescriptor geomAttr;
99

  
100

  
101

  
102
		if (fType.getDefaultGeometryAttributeIndex() >= 0) {
103
			assertNotNull(store.getEnvelope());
104
			geomAttr = fType.getAttributeDescriptor(fType
105
					.getDefaultGeometryAttributeIndex());
106
			assertTrue(geomAttr.getGeometryType() == Geometry.TYPES.MULTISURFACE);
107
			assertTrue(geomAttr.getGeometrySubType() == Geometry.SUBTYPES.GEOM2D);
108
			assertNotNull(store.getDynValue("CRS"));
109

  
110
		}
111

  
112
	}
113

  
114
	public void testCloserConnection() throws Exception {
115

  
116
		DataStoreParameters params = this.getDefaultDataStoreParameters();
117

  
118
		FeatureStore store = null;
119
		store = (FeatureStore) dataManager.createStore(params);
120

  
121
		FeatureQuery query = store.createFeatureQuery();
122

  
123
		query.getOrder().add("gid", true);
124

  
125
		query.setFilter(new Evaluator() {
126

  
127
			public Object evaluate(EvaluatorData data)
128
					throws EvaluatorException {
129
				// TODO Auto-generated method stub
130
				return Boolean.TRUE;
131
			}
132

  
133
			public String getSQL() {
134
				return "true = true";
135
			}
136

  
137
			public String getDescription() {
138
				// TODO Auto-generated method stub
139
				return null;
140
			}
141

  
142
			public String getName() {
143
				return "AlwaysTrue";
144
			}
145

  
146
			public EvaluatorFieldsInfo getFieldsInfo() {
147
				// TODO Auto-generated method stub
148
				return null;
149
			}
150

  
151
		});
152

  
153
		FeatureStoreTransform transform = new StringsToLowerTransform();
154
		transform.setFeatureStore(store);
155

  
156
		store.getTransforms().add(transform);
157

  
158
		transform = new StringsToLowerTransform();
159
		transform.setFeatureStore(store);
160

  
161
		store.getTransforms().add(transform);
162

  
163
		transform = new StringsToLowerTransform();
164
		transform.setFeatureStore(store);
165

  
166
		store.getTransforms().add(transform);
167

  
168
		for (int i = 0; i < 30; i++) {
169
			// this.fullStoreIteratorTest(store);
170

  
171
			this.testIterationFastAndStandart(store, query);
172
		}
173

  
174

  
175
		store.dispose();
176

  
177
	}
178

  
179
	public boolean usesResources() {
180
		return true;
181
	}
182

  
183
	public NewFeatureStoreParameters getDefaultNewDataStoreParameters()
184
			throws Exception {
185
		PostgreSQLStoreParameters parameters = (PostgreSQLStoreParameters) this
186
				.getDefaultDataStoreParameters();
187

  
188
		FeatureStore store = null;
189

  
190
		if (this.myExplorer == null) {
191
			store = (FeatureStore) dataManager.createStore(parameters);
192
			myExplorer = (JDBCServerExplorer) store.getExplorer();
193
		}
194
		if (this.newParams == null) {
195
			if (store == null){
196
				store = (FeatureStore) dataManager.createStore(parameters);
197
			}
198

  
199
			newParams = (PostgreSQLNewStoreParameters) myExplorer
200
					.getAddParameters();
201

  
202
			newParams.setTable(parameters.getTable() + "_test");
203
			FeatureType ftOrg = store.getDefaultFeatureType();
204
			EditableFeatureType ftTrg = (EditableFeatureType) newParams
205
					.getDefaultFeatureType();
206
			FeatureAttributeDescriptor org;
207
			EditableFeatureAttributeDescriptor trg;
208
			Iterator iter = ftOrg.iterator();
209
			while (iter.hasNext()) {
210
				org = (FeatureAttributeDescriptor) iter.next();
211
				trg = ftTrg.add(org.getName(), org.getType());
212
				trg.setAllowNull(org.allowNull());
213
				trg.setDefaultValue(org.getDefaultValue());
214
				trg.setGeometrySubType(org.getGeometrySubType());
215
				trg.setGeometryType(org.getGeometryType());
216
				trg.setIsAutomatic(org.isAutomatic());
217
				trg.setIsPrimaryKey(org.isPrimaryKey());
218
				trg.setIsReadOnly(org.isReadOnly());
219
				trg.setMaximumOccurrences(org.getMaximumOccurrences());
220
				trg.setMinimumOccurrences(org.getMinimumOccurrences());
221
				trg.setPrecision(org.getPrecision());
222
				trg.setSize(org.getSize());
223
				trg.setSRS(org.getSRS());
224
			}
225
			ftTrg.setDefaultGeometryAttributeName(ftOrg
226
					.getDefaultGeometryAttributeName());
227
			ftTrg.setHasOID(ftOrg.hasOID());
228

  
229
		}
230
		if (store != null){
231
			store.dispose();
232
		}
233

  
234
		return this.newParams;
235
	}
236

  
237
	public boolean resourcesNotifyChanges() {
238
		return false;
239
	}
240
}
trunk/org.gvsig.postgresql/org.gvsig.postgresql.provider/src/test/java/org/gvsig/fmap/dal/store/postgresql/TestReadAndWriteGeom.java
1
/* gvSIG. Geographic Information System of the Valencian Government
2
*
3
* Copyright (C) 2007-2008 Infrastructures and Transports Department
4
* of the Valencian Government (CIT)
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 2
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
*/
22

  
23
/*
24
* AUTHORS (In addition to CIT):
25
* 2009 IVER T.I   {{Task}}
26
*/
27

  
28
package org.gvsig.fmap.dal.store.postgresql;
29

  
30
import java.sql.Connection;
31
import java.sql.DriverManager;
32
import java.sql.PreparedStatement;
33
import java.sql.ResultSet;
34
import java.sql.SQLException;
35
import java.sql.Statement;
36
import java.text.MessageFormat;
37

  
38
import org.gvsig.fmap.geom.Geometry;
39
import org.gvsig.fmap.geom.GeometryLocator;
40
import org.gvsig.fmap.geom.GeometryManager;
41
import org.gvsig.fmap.geom.operation.fromwkb.FromWKB;
42
import org.gvsig.fmap.geom.operation.fromwkb.FromWKBGeometryOperationContext;
43
import org.gvsig.fmap.geom.operation.towkb.ToWKB;
44
import org.gvsig.fmap.geom.operation.towkt.ToWKT;
45
import org.gvsig.fmap.geom.primitive.impl.Point2D;
46
import org.gvsig.tools.junit.AbstractLibraryAutoInitTestCase;
47

  
48
public class TestReadAndWriteGeom extends AbstractLibraryAutoInitTestCase {
49
	private static final int FEATURES_TO_INSERT = 12000;
50
	private static final String TABLE_NAME_INSERT = "testReadadnwritegeom_testcase";
51
	private static final String FIELD_NAME_INSERT = "geom";
52
	private Connection conn;
53
	private GeometryManager geoManager;
54
	private static String SQL_FOR_READ_TEST = "Select {0} from medio_ejes";
55

  
56
	@Override
57
	protected void doSetUp() throws Exception {
58
		geoManager = GeometryLocator.getGeometryManager();
59

  
60
		Class klass = Class.forName(PostgreSQLLibrary.DEFAULT_JDCB_DRIVER_NAME);
61
		if (klass == null) {
62
			throw new Exception("Driver not found: "
63
					+ PostgreSQLLibrary.DEFAULT_JDCB_DRIVER_NAME);
64
		}
65

  
66
		// inicializamos operaciones de geometrias de las que dependemos
67
		int code = FromWKB.CODE;
68
		code = ToWKB.CODE;
69
		code = ToWKT.CODE;
70
		conn = DriverManager.getConnection(PostgreSQLLibrary.getJdbcUrl(
71
				"localhost", 5432, "gis"), "postgres", "postgres");
72
	}
73

  
74
	public void testInsertWKB() throws Exception {
75
		PreparedStatement pst = null;
76
		try {
77
			crearTablaTest();
78
			Point2D geom = (Point2D) geoManager.createPoint(0, 0,
79
					Geometry.SUBTYPES.GEOM2D);
80
			pst = conn.prepareStatement(
81
					"Insert into "
82
					+ TABLE_NAME_INSERT.toLowerCase() +
83
					"  ("
84
					+ FIELD_NAME_INSERT + ") Values (GeomFromWKB(?))");
85

  
86

  
87
			int i;
88
			for (i = 1; i <= FEATURES_TO_INSERT; i++) {
89
				pst.clearParameters();
90
				geom.setX(i);
91
				geom.setY(i);
92
				pst.setBytes(1,
93
					(byte[]) geom.invokeOperation(
94
							ToWKB.CODE,
95
							null)
96
					);
97

  
98
				pst.executeUpdate();
99
			}
100

  
101
			System.out
102
					.println("TestReadAndWriteGeom.testInsertPostgis() Inserteds= i");
103

  
104

  
105

  
106

  
107
		} finally {
108
			if (pst != null) {
109
				try {pst.close();} catch (SQLException e) {e.printStackTrace();}
110
			}
111

  
112
		}
113

  
114

  
115
	}
116

  
117
	private void crearTablaTest() throws SQLException {
118
		execute("DROP TABLE IF EXISTS " + TABLE_NAME_INSERT.toLowerCase());
119
		execute("Delete from geometry_columns  where  f_table_name = '"
120
				+ TABLE_NAME_INSERT.toLowerCase() + "'");
121
		execute("CREATE TABLE " + TABLE_NAME_INSERT.toLowerCase()
122
				+ " (id serial PRIMARY KEY)");
123
		execute("Select AddGeometryColumn('" + TABLE_NAME_INSERT.toLowerCase()
124
				+ "','"
125
				+ FIELD_NAME_INSERT + "',-1,'GEOMETRY',2)");
126
	}
127

  
128
	private void execute(String sql) throws SQLException {
129
		Statement st = null;
130
		try {
131
			st = conn.createStatement();
132
			st.execute(sql);
133
		} finally {
134
			if (st != null) {
135
				try {st.close();} catch (SQLException e) {e.printStackTrace();}
136
			}
137
		}
138

  
139
	}
140

  
141
	public String getSQLForRead(String geoColumn) {
142
		return MessageFormat.format(SQL_FOR_READ_TEST, geoColumn);
143

  
144
	}
145

  
146
	public void testReadBinary() throws Exception {
147
		// st.execute("declare " + getTableName() + myCursorId +
148
		// "_wkb_cursor binary scroll cursor with hold for " + sqlAux);
149
		// rs = st.executeQuery("fetch forward " + FETCH_SIZE+ " in " +
150
		// getTableName() + myCursorId + "_wkb_cursor");
151

  
152
		Statement st = null;
153
		ResultSet rs = null;
154
		long count = 0;
155
		Geometry geom;
156
		Geometry nullGeom = geoManager.createNullGeometry(Geometry.SUBTYPES.GEOM2D);
157

  
158
		try {
159
			st = conn.createStatement();
160
			String cursorName = "myCursor___xxx";
161
			st.execute("declare " + cursorName
162
					+ "_wkb_cursor binary scroll cursor with hold for "
163
					+ getSQLForRead("the_geom"));
164
			rs = st.executeQuery("fetch forward all in " + cursorName
165
					+ "_wkb_cursor");
166
			byte[] buff;
167
			FromWKBGeometryOperationContext opContext = new FromWKBGeometryOperationContext();
168
			while (rs.next()) {
169
				count++;
170
				buff = rs.getBytes(1);
171
//				if (buff != null) {
172
//					opContext.setData(buff);
173
//					geom = (Geometry) nullGeom.invokeOperation(FromWKB.CODE,
174
//							opContext);
175
//					assertNotNull(geom);
176
//				}
177
			}
178

  
179
			System.out
180
					.println("TestReadAndWriteGeom.testReadPostgis() Count = "
181
							+ count);
182

  
183
		} finally {
184
			if (st != null) {
185
				try {
186
					st.close();
187
				} catch (SQLException e) {
188
					e.printStackTrace();
189
				}
190
			}
191
			if (rs != null) {
192
				try {
193
					rs.close();
194
				} catch (SQLException e) {
195
					e.printStackTrace();
196
				}
197
			}
198
		}
199

  
200
	}
201

  
202
	public void testReadWKB() throws Exception {
203
		Statement st = null;
204
		ResultSet rs = null;
205
		long count = 0;
206
		Geometry geom;
207
		Geometry nullGeom = geoManager
208
				.createNullGeometry(Geometry.SUBTYPES.GEOM2D);
209
		byte[] buff;
210
		FromWKBGeometryOperationContext opContext = new FromWKBGeometryOperationContext();
211
		try {
212
			st = conn.createStatement();
213
			rs = st.executeQuery(getSQLForRead("asBinary(the_geom)"));
214
			while (rs.next()) {
215
				count++;
216
				buff = rs.getBytes(1);
217
//				if (buff != null) {
218
//					opContext.setData(buff);
219
//					geom = (Geometry) nullGeom.invokeOperation(FromWKB.CODE,
220
//							opContext);
221
//					assertNotNull(geom);
222
//				}
223
			}
224

  
225
			System.out
226
					.println("TestReadAndWriteGeom.testReadPostgis() Count = "
227
							+ count);
228

  
229

  
230
		} finally {
231
			if (st != null) {
232
				try {
233
					st.close();
234
				} catch (SQLException e) {
235
					e.printStackTrace();
236
				}
237
			}
238
			if (rs != null) {
239
				try {
240
					rs.close();
241
				} catch (SQLException e) {
242
					e.printStackTrace();
243
				}
244
			}
245
		}
246
	}
247

  
248
//	public void testReadPostgis() throws Exception {
249
//		Statement st = null;
250
//		ResultSet rs = null;
251
//		long count = 0;
252
//		Geometry geom;
253
//		PGgeometry pgGeom;
254
//		PostGIS2Geometry converter = new PostGIS2Geometry();
255
//		try {
256
//			st = conn.createStatement();
257
//			rs = st.executeQuery(getSQLForRead("the_geom"));
258
//			while (rs.next()) {
259
//				count++;
260
//				pgGeom = (PGgeometry) rs.getObject(1);
261
//				if (pgGeom != null) {
262
//					geom = converter.getGeometry(pgGeom);
263
//					assertNotNull(geom);
264
//				}
265
//			}
266
//
267
//
268
//			System.out
269
//					.println("TestReadAndWriteGeom.testReadPostgis() Count = "
270
//							+ count);
271
//
272
//
273
//		} finally {
274
//			if (st != null) {
275
//				try {
276
//					st.close();
277
//				} catch (SQLException e) {
278
//					e.printStackTrace();
279
//				}
280
//			}
281
//			if (rs != null) {
282
//				try {
283
//					rs.close();
284
//				} catch (SQLException e) {
285
//					e.printStackTrace();
286
//				}
287
//			}
288
//		}
289
//	}
290

  
291

  
292
	protected void tearDown() throws Exception {
293
		super.tearDown();
294
		conn.close();
295
	}
296

  
297
}
trunk/org.gvsig.postgresql/org.gvsig.postgresql.provider/src/test/java/org/gvsig/fmap/dal/store/postgresql/TestPostgreSQL.java
1
/* gvSIG. Geographic Information System of the Valencian Government
2
*
3
* Copyright (C) 2007-2008 Infrastructures and Transports Department
4
* of the Valencian Government (CIT)
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 2
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
*/
22

  
23
/*
24
* AUTHORS (In addition to CIT):
25
* 2009 IVER T.I   {{Task}}
26
*/
27

  
28
/**
29
 *
30
 */
31
package org.gvsig.fmap.dal.store.postgresql;
32

  
33
import org.gvsig.fmap.dal.DataStoreParameters;
34
import org.gvsig.fmap.dal.exception.DataException;
35
import org.gvsig.fmap.dal.feature.BaseTestFeatureStore;
36
import org.gvsig.fmap.dal.feature.FeatureAttributeDescriptor;
37
import org.gvsig.fmap.dal.feature.FeatureQuery;
38
import org.gvsig.fmap.dal.feature.FeatureStore;
39
import org.gvsig.fmap.dal.feature.FeatureStoreTransform;
40
import org.gvsig.fmap.dal.feature.FeatureType;
41
import org.gvsig.fmap.dal.feature.NewFeatureStoreParameters;
42
import org.gvsig.fmap.geom.Geometry;
43
import org.gvsig.tools.evaluator.Evaluator;
44
import org.gvsig.tools.evaluator.EvaluatorData;
45
import org.gvsig.tools.evaluator.EvaluatorException;
46
import org.gvsig.tools.evaluator.EvaluatorFieldsInfo;
47

  
48
/**
49
 * @author jmvivo
50
 *
51
 */
52
// public class TestPostgreSQL extends BaseTestEditableFeatureStore {
53
public class TestPostgreSQL extends BaseTestFeatureStore {
54

  
55
	@Override
56
	protected void doSetUp() throws Exception {
57
		super.doSetUp();
58
	}
59

  
60
	public DataStoreParameters getDefaultDataStoreParameters()
61
			throws DataException {
62
		PostgreSQLStoreParameters pgParameters = null;
63
		pgParameters = (PostgreSQLStoreParameters) dataManager
64
				.createStoreParameters(PostgreSQLStoreProvider.NAME);
65

  
66
		pgParameters.setHost("localhost");
67
		pgParameters.setUser("postgres");
68
		pgParameters.setPassword("postgres");
69
		pgParameters.setDBName("gis");
70
		pgParameters.setTable("muni10000_peq");
71

  
72
		return pgParameters;
73
	}
74

  
75
	public boolean hasExplorer() {
76
		return true;
77
	}
78

  
79
	public void testLoadMetadata() throws Exception {
80
		DataStoreParameters params = this.getDefaultDataStoreParameters();
81

  
82
		FeatureStore store = null;
83
		store = (FeatureStore) dataManager.createStore(params);
84
		FeatureType fType = store.getDefaultFeatureType();
85
		FeatureAttributeDescriptor geomAttr;
86

  
87

  
88

  
89
		if (fType.getDefaultGeometryAttributeIndex() >= 0) {
90
			assertNotNull(store.getEnvelope());
91
			geomAttr = fType.getAttributeDescriptor(fType
92
					.getDefaultGeometryAttributeIndex());
93
			assertTrue(geomAttr.getGeometryType() == Geometry.TYPES.MULTISURFACE);
94
			assertTrue(geomAttr.getGeometrySubType() == Geometry.SUBTYPES.GEOM2D);
95
			assertNotNull(store.getDynValue("CRS"));
96

  
97
		}
98

  
99
	}
100

  
101
	public void testCloserConnection() throws Exception {
102

  
103
		DataStoreParameters params = this.getDefaultDataStoreParameters();
104

  
105
		FeatureStore store = null;
106
		store = (FeatureStore) dataManager.createStore(params);
107

  
108
		FeatureQuery query = store.createFeatureQuery();
109

  
110
		query.getOrder().add("gid", true);
111

  
112
		query.setFilter(new Evaluator() {
113

  
114
			public Object evaluate(EvaluatorData data)
115
					throws EvaluatorException {
116
				// TODO Auto-generated method stub
117
				return Boolean.TRUE;
118
			}
119

  
120
			public String getSQL() {
121
				return "true = true";
122
			}
123

  
124
			public String getDescription() {
125
				// TODO Auto-generated method stub
126
				return null;
127
			}
128

  
129
			public String getName() {
130
				return "AlwaysTrue";
131
			}
132

  
133
			public EvaluatorFieldsInfo getFieldsInfo() {
134
				// TODO Auto-generated method stub
135
				return null;
136
			}
137

  
138
		});
139

  
140
		FeatureStoreTransform transform = new StringsToLowerTransform();
141
		transform.setFeatureStore(store);
142

  
143
		store.getTransforms().add(transform);
144

  
145
		transform = new StringsToLowerTransform();
146
		transform.setFeatureStore(store);
147

  
148
		store.getTransforms().add(transform);
149

  
150
		transform = new StringsToLowerTransform();
151
		transform.setFeatureStore(store);
152

  
153
		store.getTransforms().add(transform);
154

  
155
		for (int i = 0; i < 30; i++) {
156
			// this.fullStoreIteratorTest(store);
157

  
158
			this.testIterationFastAndStandart(store, query);
159
		}
160

  
161

  
162
		store.dispose();
163

  
164
	}
165

  
166
	public boolean usesResources() {
167
		return true;
168
	}
169

  
170
	public NewFeatureStoreParameters getDefaultNewDataStoreParameters()
171
			throws Exception {
172
		// TODO Auto-generated method stub
173
		return null;
174
	}
175
}
trunk/org.gvsig.postgresql/org.gvsig.postgresql.provider/src/test/java/org/gvsig/fmap/dal/store/postgresql/DatabaseMetadataChecks.java
1
/**
2
 * 
3
 */
4
package org.gvsig.fmap.dal.store.postgresql;
5

  
6
import java.sql.Connection;
7
import java.sql.DatabaseMetaData;
8
import java.sql.DriverManager;
9
import java.sql.ResultSet;
10
import java.sql.ResultSetMetaData;
11
import java.sql.SQLException;
12

  
13
/**
14
 * @author cordin
15
 * 
16
 */
17
public class DatabaseMetadataChecks {
18

  
19
	// Columns as specified by the DatabaseMetadata.getTables javadoc
20
	private static final String[] COLUMNS = new String[] {
21
	// Metadata resultset column names
22
			"TABLE_CAT", // String => table catalog (may be null)
23
			"TABLE_SCHEM", // String => table schema (may be null)
24
			"TABLE_NAME", // String => table name
25
			"TABLE_TYPE", // String => table type. Typical types are "TABLE",
26
						// "VIEW", "SYSTEM TABLE", "GLOBAL TEMPORARY",
27
						// "LOCAL TEMPORARY", "ALIAS", "SYNONYM".
28
			"REMARKS", // String => explanatory comment on the table
29
			"TYPE_CAT", // String => the types catalog (may be null)
30
			"TYPE_SCHEM", // String => the types schema (may be null)
31
			"TYPE_NAME", // String => type name (may be null)
32
			"SELF_REFERENCING_COL_NAME", // String => name of the designated
33
										// "identifier" column of a typed
34
										// table (may be null)
35
			"REF_GENERATION", // String => specifies how values in
36
							// SELF_REFERENCING_COL_NAME are created. Values
37
							// are "SYSTEM", "USER", "DERIVED". (may be
38
							// null)
39
	};
40

  
41
	public void showTables() throws Exception {
42

  
43
		Connection conn = DriverManager.getConnection(
44
				"jdbc:postgresql://localhost/gvsigDB", "gvsig", "gvsig");
45

  
46
		try {
47
			// Statement st = conn.createStatement();
48
			// String sql = "select tablename from pg_tables";
49
			// ResultSet result = st.executeQuery(sql);
50

  
51
			DatabaseMetaData metadata = conn.getMetaData();
52
			ResultSet result = metadata.getTables(null, null, null,
53
					new String[] { "TABLE", "VIEW" });
54
			ResultSetMetaData resultMD = result.getMetaData();
55
			String[] columns = new String[resultMD.getColumnCount()];
56
			for (int i = 0; i < columns.length; i++) {
57
				columns[i] = resultMD.getColumnName(i + 1);
58
			}
59

  
60
			for (int i = 0; i < columns.length; i++) {
61
				System.out.print(columns[i]);
62
				System.out.print(";");
63
			}
64
			System.out.println();
65
			while (result.next()) {
66
				
67
				for (int i = 0; i < columns.length; i++) {
68
					System.out.print(result.getString(columns[i]));
69
					System.out.print(";");
70
				}
71
				System.out.println();
72
			}
73

  
74
		} finally {
75
			try {
76
				conn.close();
77
			} catch (SQLException e) {
78
				e.printStackTrace();
79
			}
80
		}
81

  
82
	}
83

  
84
	/**
85
	 * @param args
86
	 */
87
	public static void main(String[] args) {
88
		try {
89
			new DatabaseMetadataChecks().showTables();
90
		} catch (Exception e) {
91
			e.printStackTrace();
92
			System.exit(-1);
93
		}
94
		System.exit(0);
95
	}
96

  
97
}
trunk/org.gvsig.postgresql/org.gvsig.postgresql.provider/src/main/java/org/gvsig/fmap/dal/store/postgresql/PostgreSQLHelper.java
1
/* gvSIG. Geographic Information System of the Valencian Government
2
*
3
* Copyright (C) 2007-2008 Infrastructures and Transports Department
4
* of the Valencian Government (CIT)
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 2
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
*/
22

  
23
/*
24
* AUTHORS (In addition to CIT):
25
* 2009 IVER T.I   {{Task}}
26
*/
27

  
28
/**
29
 *
30
 */
31
package org.gvsig.fmap.dal.store.postgresql;
32

  
33
import java.sql.Connection;
34
import java.sql.PreparedStatement;
35
import java.sql.ResultSet;
36
import java.sql.ResultSetMetaData;
37
import java.sql.SQLException;
38
import java.sql.Statement;
39
import java.util.ArrayList;
40
import java.util.Comparator;
41
import java.util.Iterator;
42
import java.util.List;
43
import java.util.Map;
44
import java.util.TreeMap;
45
import java.util.TreeSet;
46

  
47
import org.cresques.cts.IProjection;
48
import org.postgresql.PGResultSetMetaData;
49
import org.slf4j.Logger;
50
import org.slf4j.LoggerFactory;
51

  
52
import org.gvsig.fmap.crs.CRSFactory;
53
import org.gvsig.fmap.dal.DALLocator;
54
import org.gvsig.fmap.dal.DataTypes;
55
import org.gvsig.fmap.dal.NewDataStoreParameters;
56
import org.gvsig.fmap.dal.exception.DataException;
57
import org.gvsig.fmap.dal.exception.InitializeException;
58
import org.gvsig.fmap.dal.exception.ReadException;
59
import org.gvsig.fmap.dal.feature.EditableFeatureAttributeDescriptor;
60
import org.gvsig.fmap.dal.feature.EditableFeatureType;
61
import org.gvsig.fmap.dal.feature.FeatureAttributeDescriptor;
62
import org.gvsig.fmap.dal.feature.FeatureType;
63
import org.gvsig.fmap.dal.feature.exception.UnsupportedDataTypeException;
64
import org.gvsig.fmap.dal.feature.exception.UnsupportedGeometryException;
65
import org.gvsig.fmap.dal.resource.ResourceAction;
66
import org.gvsig.fmap.dal.resource.spi.ResourceManagerProviderServices;
67
import org.gvsig.fmap.dal.store.jdbc.ConnectionAction;
68
import org.gvsig.fmap.dal.store.jdbc.JDBCHelper;
69
import org.gvsig.fmap.dal.store.jdbc.JDBCHelperUser;
70
import org.gvsig.fmap.dal.store.jdbc.JDBCStoreParameters;
71
import org.gvsig.fmap.dal.store.jdbc.exception.JDBCException;
72
import org.gvsig.fmap.dal.store.jdbc.exception.JDBCExecutePreparedSQLException;
73
import org.gvsig.fmap.dal.store.jdbc.exception.JDBCExecuteSQLException;
74
import org.gvsig.fmap.dal.store.jdbc.exception.JDBCPreparingSQLException;
75
import org.gvsig.fmap.dal.store.jdbc.exception.JDBCSQLException;
76
import org.gvsig.fmap.geom.Geometry;
77
import org.gvsig.fmap.geom.GeometryLocator;
78
import org.gvsig.fmap.geom.GeometryManager;
79
import org.gvsig.fmap.geom.operation.fromwkb.FromWKB;
80
import org.gvsig.fmap.geom.operation.fromwkb.FromWKBGeometryOperationContext;
81
import org.gvsig.fmap.geom.primitive.Envelope;
82
import org.gvsig.tools.ToolsLocator;
83
import org.gvsig.tools.exception.BaseException;
84

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

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

  
94
	private Map pgSR2SRSID = new TreeMap();
95
	private Map srsID2pgSR = new TreeMap();
96

  
97

  
98
	PostgreSQLHelper(JDBCHelperUser consumer,
99
			PostgreSQLConnectionParameters params)
100
			throws InitializeException {
101

  
102
		super(consumer, params);
103
	}
104

  
105
	protected void initializeResource() throws InitializeException {
106
		ResourceManagerProviderServices manager = (ResourceManagerProviderServices) DALLocator
107
		.getResourceManager();
108
		PostgreSQLResource resource = (PostgreSQLResource) manager
109
		.createAddResource(
110
				PostgreSQLResource.NAME, new Object[] {
111
						params.getUrl(), params.getHost(),
112
						params.getPort(), params.getDBName(), params.getUser(),
113
						params.getPassword(),
114
						params.getJDBCDriverClassName(),
115
						((PostgreSQLConnectionParameters) params).getUseSSL() });
116
		this.setResource(resource);
117
	}
118

  
119

  
120
	protected String getDefaultSchema(Connection conn)
121
			throws JDBCException {
122
		if (defaultSchema == null) {
123
			String sql = "Select current_schema()";
124
			ResultSet rs = null;
125
			Statement st = null;
126
			String schema = null;
127
			try {
128
				st = conn.createStatement();
129
				try {
130
					rs = st.executeQuery(sql);
131
				} catch (java.sql.SQLException e) {
132
					throw new JDBCExecuteSQLException(sql, e);
133
				}
134
				rs.next();
135
				schema = rs.getString(1);
136
			} catch (java.sql.SQLException e) {
137
				throw new JDBCSQLException(e);
138
			} finally {
139
				try {rs.close();} catch (Exception e) {logger.error("Exception clossing resulset", e);};
140
				try {st.close();} catch (Exception e) {logger.error("Exception clossing statement", e);};
141
				rs = null;
142
				st = null;
143
			}
144
			defaultSchema = schema;
145
		}
146

  
147
		return defaultSchema;
148
	}
149

  
150
	public Envelope getFullEnvelopeOfField(
151
			JDBCStoreParameters storeParams,
152
			String geometryAttrName, Envelope limit)
153
			throws DataException {
154

  
155
		StringBuilder strb = new StringBuilder();
156
		strb.append("Select asbinary(extent(");
157
		strb.append(escapeFieldName(geometryAttrName));
158
		strb.append(")) from ");
159

  
160
		if (storeParams.getSQL() != null
161
				&& storeParams.getSQL().trim().length() == 0) {
162
			strb.append('(');
163
			strb.append(storeParams.getSQL());
164
			strb.append(") as __extentfield__ ");
165
		} else {
166
			strb.append(storeParams.tableID());
167
		}
168

  
169

  
170
		if (limit != null){
171
			strb.append(" where  intersects(GeomFromText('");
172
			strb.append(limit.toString());
173
			strb.append("')), envelope(");
174
			strb.append(escapeFieldName(geometryAttrName));
175
			strb.append(")) ");
176
		}
177

  
178
		final String sql = strb.toString();
179

  
180
		GeometryManager geoMan = GeometryLocator.getGeometryManager();
181

  
182
		this.open();
183

  
184
		return (Envelope) getResource().execute(new ResourceAction() {
185
			public Object run() throws Exception {
186
				ResultSet rs = null;
187
				Statement st = null;
188
				String schema = null;
189
				Connection conn = null;
190
				Envelope fullEnvelope = null;
191
				try {
192

  
193
					conn = getConnection();
194
					st = conn.createStatement();
195
					try {
196
						rs = st.executeQuery(sql);
197
					} catch (java.sql.SQLException e) {
198
						throw new JDBCExecuteSQLException(sql, e);
199
					}
200
					if (!rs.next()) {
201
						return null;
202
					}
203

  
204
					byte[] data = rs.getBytes(1);
205
					if (data == null) {
206
						return null;
207
					}
208

  
209
					Geometry geom = geomManager.createFrom(data);
210

  
211
					fullEnvelope = geom.getEnvelope();
212

  
213
					return fullEnvelope;
214
				} catch (java.sql.SQLException e) {
215
					throw new JDBCSQLException(e);
216
				} catch (BaseException e) {
217
					throw new ReadException(user.getProviderName(), e);
218
				} finally {
219
					try {
220
						rs.close();
221
					} catch (Exception e) {
222
					}
223
					try {
224
						st.close();
225
					} catch (Exception e) {
226
					}
227
					try {
228
						conn.close();
229
					} catch (Exception e) {
230
					}
231
					rs = null;
232
					st = null;
233
					conn = null;
234
				}
235
			}
236
		});
237
	}
238

  
239
	@Override
240
	protected boolean supportsGeometry() {
241
		return true;
242
	}
243

  
244
	/**
245
	 * Fill <code>featureType</code> geometry attributes with SRS and ShapeType
246
	 * information stored in the table GEOMETRY_COLUMNS
247
	 *
248
	 * @param conn
249
	 * @param rsMetadata
250
	 * @param featureType
251
	 * @throws ReadException
252
	 */
253
	protected void loadSRS_and_shapeType(Connection conn,
254
			ResultSetMetaData rsMetadata, EditableFeatureType featureType,
255
			String baseSchema, String baseTable)
256
			throws JDBCException {
257

  
258
		Statement st = null;
259
		ResultSet rs = null;
260
		try {
261
			// Sacamos la lista de los attributos geometricos
262
			EditableFeatureAttributeDescriptor attr;
263
			List geoAttrs = new ArrayList();
264

  
265
			Iterator iter = featureType.iterator();
266
			while (iter.hasNext()) {
267
				attr = (EditableFeatureAttributeDescriptor) iter.next();
268
				if (attr.getType() == DataTypes.GEOMETRY) {
269
					geoAttrs.add(attr);
270
				}
271
			}
272
			if (geoAttrs.size() < 1) {
273
				return;
274
			}
275

  
276

  
277
			// preparamos un set con las lista de tablas de origen
278
			// de los campos
279
			class TableId {
280
				public String schema=null;
281
				public String table=null;
282
				public String field = null;
283

  
284
				public void appendToSQL(StringBuilder strb) {
285
					if (schema == null || schema.length() == 0) {
286
						strb
287
								.append("( F_TABLE_SCHEMA = current_schema() AND F_TABLE_NAME = '");
288
					} else {
289
						strb.append("( F_TABLE_SCHEMA = '");
290
						strb.append(schema);
291
						strb.append("' AND F_TABLE_NAME = '");
292
					}
293
					strb.append(table);
294
					strb.append("' AND F_GEOMETRY_COLUMN = '");
295
					strb.append(field);
296
					strb.append("' )");
297
				}
298

  
299
			}
300
			Comparator cmp = new Comparator(){
301
				public int compare(Object arg0, Object arg1) {
302
					TableId a0 = (TableId) arg0;
303
					TableId a1 = (TableId) arg1;
304

  
305
					int aux = a0.field.compareTo(a1.field);
306
					if (aux != 0) {
307
					    return aux;
308
					}
309

  
310
					aux = a0.table.compareTo(a1.table);
311
                    if (aux != 0) {
312
                        return aux;
313
                    }
314
					
315
                    if (a0.schema == null) {
316
                        if (a1.schema == null) {
317
                            aux = 0;
318
                        } else {
319
                            aux = -1;
320
                        }
321
                    } else {
322
                        if (a1.schema == null) {
323
                            aux = -1;
324
                        } else {
325
                            aux = a0.schema.compareTo(a1.schema);
326
                        }
327
                    }
328
					return aux;
329
				}
330
			};
331
			TreeSet set = new TreeSet(cmp);
332
			TableId tableId;
333
			iter = geoAttrs.iterator();
334
			int rsIndex;
335
			while (iter.hasNext()) {
336
				attr = (EditableFeatureAttributeDescriptor) iter.next();
337
				tableId = new TableId();
338
				rsIndex = attr.getIndex() + 1;
339

  
340
				if (baseSchema == null && baseTable == null) {
341
					if (rsMetadata instanceof PGResultSetMetaData) {
342
						tableId.schema = ((PGResultSetMetaData) rsMetadata)
343
								.getBaseSchemaName(rsIndex);
344
						tableId.table = ((PGResultSetMetaData) rsMetadata)
345
								.getBaseTableName(rsIndex);
346
						tableId.field = ((PGResultSetMetaData) rsMetadata)
347
								.getBaseColumnName(rsIndex);
348

  
349
					} else {
350
						tableId.schema = rsMetadata.getSchemaName(rsIndex);
351
						tableId.table = rsMetadata.getTableName(rsIndex);
352
						tableId.field = rsMetadata.getColumnName(rsIndex);
353
					}
354
				} else {
355
					tableId.schema = baseSchema;
356
					tableId.table = baseTable;
357
					tableId.field = rsMetadata.getColumnName(rsIndex);
358
				}
359
				if (tableId.table == null || tableId.table.length() == 0) {
360
					// Si no tiene tabla origen (viene de algun calculo por ej.)
361
					// lo saltamos ya que no estara en la tabla GEOMETRY_COLUMNS
362
					continue;
363
				}
364
				set.add(tableId);
365
			}
366

  
367
			if (set.size() == 0) {
368
				return;
369
			}
370

  
371
			// Preparamos una sql para que nos saque el resultado
372
			StringBuilder strb = new StringBuilder();
373
			strb.append("Select geometry_columns.*,auth_name || ':' || auth_srid as SRSID ");
374
			strb.append("from geometry_columns left join spatial_ref_sys on ");
375
			strb.append("geometry_columns.srid = spatial_ref_sys.srid WHERE ");
376
			iter = set.iterator();
377
			for (int i=0;i<set.size()-1;i++) {
378
				tableId = (TableId) iter.next();
379
				tableId.appendToSQL(strb);
380
				strb.append(" OR ");
381
			}
382
			tableId = (TableId) iter.next();
383
			tableId.appendToSQL(strb);
384
			String sql = strb.toString();
385

  
386

  
387
			st = conn.createStatement();
388
			try {
389
				rs = st.executeQuery(sql);
390
			} catch (SQLException e) {
391
				throw new JDBCExecuteSQLException(sql, e);
392
			}
393
			String srsID;
394
			int pgSrid;
395
			int geometryType;
396
			int geometrySubtype;
397
			String geomTypeStr;
398
			int dimensions;
399
			IProjection srs;
400

  
401
			while (rs.next()){
402
				srsID = rs.getString("SRSID");
403
				pgSrid = rs.getInt("SRID");
404
				geomTypeStr = rs.getString("TYPE").toUpperCase();
405
				geometryType = Geometry.TYPES.GEOMETRY;
406
				if (geomTypeStr.startsWith("POINT")) {
407
					geometryType = Geometry.TYPES.POINT;
408
				} else if (geomTypeStr.startsWith("LINESTRING")) {
409
					geometryType = Geometry.TYPES.CURVE;
410
				} else if (geomTypeStr.startsWith("POLYGON")) {
411
					geometryType = Geometry.TYPES.SURFACE;
412
				} else if (geomTypeStr.startsWith("MULTIPOINT")) {
413
					geometryType = Geometry.TYPES.MULTIPOINT;
414
				} else if (geomTypeStr.startsWith("MULTILINESTRING")) {
415
					geometryType = Geometry.TYPES.MULTICURVE;
416
				} else if (geomTypeStr.startsWith("MULTIPOLYGON")) {
417
					geometryType = Geometry.TYPES.MULTISURFACE;
418
				}
419
				dimensions = rs.getInt("coord_dimension");
420
				geometrySubtype = Geometry.SUBTYPES.GEOM2D;
421
				if (dimensions > 2) {
422
					if (dimensions == 3) {
423
						if (geomTypeStr.endsWith("M")) {
424
							geometrySubtype = Geometry.SUBTYPES.GEOM2DM;
425
						} else {
426
							geometrySubtype = Geometry.SUBTYPES.GEOM3D;
427
						}
428

  
429
					} else {
430
						geometrySubtype = Geometry.SUBTYPES.GEOM3DM;
431
					}
432
				}
433
				addToPgSRToSRSID(pgSrid, srsID);
434

  
435

  
436
				iter = geoAttrs.iterator();
437
				while (iter.hasNext()) {
438
					attr = (EditableFeatureAttributeDescriptor) iter.next();
439
					rsIndex = attr.getIndex() + 1;
440
					if (!rsMetadata.getColumnName(rsIndex).equals(
441
							rs.getString("f_geometry_column"))) {
442
						continue;
443
					}
444

  
445
					if (baseSchema == null && baseTable == null) {
446

  
447
						if (rsMetadata instanceof PGResultSetMetaData) {
448
							if (!((PGResultSetMetaData) rsMetadata)
449
									.getBaseTableName(rsIndex).equals(
450
											rs.getString("f_table_name"))) {
451
								continue;
452
							}
453
							String curSchema = rs.getString("f_table_schema");
454
							String metaSchema = ((PGResultSetMetaData) rsMetadata)
455
									.getBaseSchemaName(rsIndex);
456
							if (!metaSchema.equals(curSchema)) {
457
								if (metaSchema.length() == 0
458
										&& metaSchema == getDefaultSchema(conn)) {
459
								} else {
460
									continue;
461
								}
462
							}
463

  
464
						} else {
465

  
466
							if (!rsMetadata.getTableName(rsIndex).equals(
467
									rs.getString("f_table_name"))) {
468
								continue;
469
							}
470
							String curSchema = rs.getString("f_table_schema");
471
							String metaSchema = rsMetadata
472
									.getSchemaName(rsIndex);
473
							if (!metaSchema.equals(curSchema)) {
474
								if (metaSchema.length() == 0
475
										&& metaSchema == getDefaultSchema(conn)) {
476
								} else {
477
									continue;
478
								}
479
							}
480
						}
481
					}
482
					attr.setGeometryType(geometryType);
483
					attr.setGeometrySubType(geometrySubtype);
484
					if (srsID != null && srsID.length() > 0) {
485
						attr.setSRS(CRSFactory.getCRS(srsID));
486
					}
487
					iter.remove();
488
				}
489
				iter = geoAttrs.iterator();
490
				while (iter.hasNext()) {
491
					attr = (EditableFeatureAttributeDescriptor) iter.next();
492
					attr.setSRS(null);
493
					attr.setGeometryType(Geometry.TYPES.GEOMETRY);
494

  
495
				}
496
			}
497

  
498
		} catch (java.sql.SQLException e) {
499
			throw new JDBCSQLException(e);
500
		} finally {
501
			try {rs.close();} catch (Exception e) {	};
502
			try {st.close();} catch (Exception e) {	};
503
		}
504

  
505
	}
506

  
507

  
508
	public String getSqlColumnTypeDescription(FeatureAttributeDescriptor attr) {
509
		if (attr.getType() == DataTypes.GEOMETRY) {
510
			return "geometry";
511
		}
512
		return super.getSqlColumnTypeDescription(attr);
513
	}
514

  
515

  
516
	public int getPostgisGeomDimensions(int geometrySubType) {
517
		switch (geometrySubType) {
518
		case Geometry.SUBTYPES.GEOM2D:
519
			return 2;
520
		case Geometry.SUBTYPES.GEOM2DM:
521
		case Geometry.SUBTYPES.GEOM3D:
522
			return 3;
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff