svn-gvsig-desktop / trunk / org.gvsig.desktop / org.gvsig.desktop.compat.cdc / org.gvsig.fmap.dal / org.gvsig.fmap.dal.db / org.gvsig.fmap.dal.db.jdbc / src / main / java / org / gvsig / fmap / dal / store / jdbc2 / spi / operations / FetchFeatureTypeOperation.java @ 44947
History | View | Annotate | Download (16.1 KB)
1 |
package org.gvsig.fmap.dal.store.jdbc2.spi.operations; |
---|---|
2 |
|
3 |
import java.sql.Connection; |
4 |
import java.sql.DatabaseMetaData; |
5 |
import java.sql.ResultSet; |
6 |
import java.sql.ResultSetMetaData; |
7 |
import java.sql.SQLException; |
8 |
import java.sql.Statement; |
9 |
import java.util.ArrayList; |
10 |
import java.util.List; |
11 |
import org.apache.commons.collections.CollectionUtils; |
12 |
import org.apache.commons.lang3.StringUtils; |
13 |
import org.cresques.cts.IProjection; |
14 |
import org.gvsig.expressionevaluator.ExpressionBuilder; |
15 |
import org.gvsig.fmap.dal.DataTypes; |
16 |
import org.gvsig.fmap.dal.exception.DataException; |
17 |
import org.gvsig.fmap.dal.feature.EditableFeatureAttributeDescriptor; |
18 |
import org.gvsig.fmap.dal.feature.EditableFeatureType; |
19 |
import org.gvsig.fmap.dal.store.jdbc2.spi.JDBCSQLBuilderBase; |
20 |
import org.gvsig.fmap.dal.store.jdbc2.JDBCHelper; |
21 |
import org.gvsig.fmap.dal.store.jdbc2.JDBCUtils; |
22 |
import org.gvsig.fmap.dal.store.jdbc2.OperationsFactory.TableReference; |
23 |
import org.gvsig.fmap.geom.Geometry; |
24 |
import org.gvsig.fmap.geom.GeometryLocator; |
25 |
import org.gvsig.fmap.geom.type.GeometryType; |
26 |
import static org.gvsig.fmap.dal.store.jdbc2.spi.operations.AbstractConnectionOperation.LOGGER; |
27 |
import org.gvsig.tools.dataTypes.DataType; |
28 |
|
29 |
@SuppressWarnings("UseSpecificCatch") |
30 |
public class FetchFeatureTypeOperation extends AbstractConnectionOperation { |
31 |
private final EditableFeatureType featureType; |
32 |
protected final TableReference table; |
33 |
private final List<String> primaryKeys; |
34 |
private final String defaultGeometryColumn; |
35 |
private final IProjection crs; |
36 |
|
37 |
public FetchFeatureTypeOperation(
|
38 |
JDBCHelper helper |
39 |
) { |
40 |
this(helper, null, null, null, null, null); |
41 |
} |
42 |
|
43 |
public FetchFeatureTypeOperation(
|
44 |
JDBCHelper helper, |
45 |
EditableFeatureType featureType, |
46 |
String defaultGeometryColumn,
|
47 |
IProjection crs |
48 |
) { |
49 |
this(helper, featureType, null, null, defaultGeometryColumn, crs); |
50 |
} |
51 |
|
52 |
public FetchFeatureTypeOperation(
|
53 |
JDBCHelper helper, |
54 |
EditableFeatureType featureType, |
55 |
TableReference table, |
56 |
List<String> primaryKeys, |
57 |
String defaultGeometryColumn,
|
58 |
IProjection crs |
59 |
) { |
60 |
super(helper);
|
61 |
this.featureType = featureType;
|
62 |
this.table = table;
|
63 |
this.primaryKeys = primaryKeys;
|
64 |
this.defaultGeometryColumn = defaultGeometryColumn;
|
65 |
this.crs = crs;
|
66 |
} |
67 |
|
68 |
@Override
|
69 |
public final Object perform(Connection conn) throws DataException { |
70 |
this.fetch(conn);
|
71 |
return true; |
72 |
} |
73 |
|
74 |
protected TableReference getTable() {
|
75 |
return this.table; |
76 |
} |
77 |
|
78 |
public void fetch(Connection conn) throws DataException { |
79 |
List<String> pks = this.primaryKeys; |
80 |
Statement st = null; |
81 |
ResultSet rs = null; |
82 |
try {
|
83 |
if (CollectionUtils.isEmpty(pks)) {
|
84 |
if (table.hasSubquery()) {
|
85 |
LOGGER.info("Searching pk in a table with a subquery ("+table.toString()+"."); |
86 |
} |
87 |
pks = this.getPrimaryKeysFromMetadata(conn, null, table.getSchema(), table.getTable()); |
88 |
if (CollectionUtils.isEmpty(pks)) {
|
89 |
pks = getPrimaryKeysFromInformationSchema(conn); |
90 |
} |
91 |
} |
92 |
st = conn.createStatement(); |
93 |
st.setFetchSize(1);
|
94 |
rs = JDBCUtils.executeQuery(st, this.getSQLToRetrieveFirstRowOfTable());
|
95 |
ResultSetMetaData rsMetadata = rs.getMetaData();
|
96 |
|
97 |
fetchFeatureTypeFromMetadata(conn, rsMetadata, pks); |
98 |
|
99 |
} catch (SQLException ex) { |
100 |
throw new RuntimeException("Can't fecth feature type.",ex); |
101 |
} finally {
|
102 |
JDBCUtils.closeQuietly(rs); |
103 |
JDBCUtils.closeQuietly(st); |
104 |
} |
105 |
} |
106 |
|
107 |
public String getSQLToRetrieveFirstRowOfTable() { |
108 |
JDBCSQLBuilderBase sqlbuilder = this.createSQLBuilder();
|
109 |
sqlbuilder.select().column().all(); |
110 |
sqlbuilder.select().from().table() |
111 |
.database(this.table.getDatabase())
|
112 |
.schema(this.table.getSchema())
|
113 |
.name(this.table.getTable());
|
114 |
sqlbuilder.select().from().subquery(this.table.getSubquery());
|
115 |
sqlbuilder.select().limit(1);
|
116 |
|
117 |
String sql = sqlbuilder.toString();
|
118 |
return sql;
|
119 |
} |
120 |
|
121 |
|
122 |
public void fetchFeatureTypeFromMetadata(Connection conn, ResultSetMetaData rsMetadata) throws SQLException { |
123 |
this.fetchFeatureTypeFromMetadata(conn, rsMetadata, new ArrayList<String>()); |
124 |
} |
125 |
|
126 |
protected void fetchFeatureTypeFromMetadata(Connection conn, ResultSetMetaData rsMetadata, List<String> pks) throws SQLException { |
127 |
int i;
|
128 |
int geometriesColumns = 0; |
129 |
String lastGeometry = null; |
130 |
|
131 |
EditableFeatureAttributeDescriptor attr; |
132 |
boolean firstGeometryAttrFound = false; |
133 |
for (i = 1; i <= rsMetadata.getColumnCount(); i++) { |
134 |
attr = getAttributeFromMetadata(featureType, conn, rsMetadata, i); |
135 |
if ( isInPrimaryKeys(pks,attr) ) {
|
136 |
attr.setIsPrimaryKey(true);
|
137 |
} |
138 |
if (attr.getType() == DataTypes.GEOMETRY) {
|
139 |
geometriesColumns++; |
140 |
lastGeometry = attr.getName(); |
141 |
// Set the default geometry attribute if it is the one
|
142 |
// given as parameter or it is the first one, just in case.
|
143 |
if (!firstGeometryAttrFound || lastGeometry.equals(defaultGeometryColumn)) {
|
144 |
firstGeometryAttrFound = true;
|
145 |
featureType.setDefaultGeometryAttributeName(lastGeometry); |
146 |
} |
147 |
} |
148 |
|
149 |
} |
150 |
if (defaultGeometryColumn == null && geometriesColumns == 1) { |
151 |
featureType.setDefaultGeometryAttributeName(lastGeometry); |
152 |
} |
153 |
|
154 |
if (crs != null && featureType.getDefaultGeometryAttribute() != null) { |
155 |
((EditableFeatureAttributeDescriptor) featureType.getDefaultGeometryAttribute()).setSRS(crs); |
156 |
} |
157 |
} |
158 |
|
159 |
protected boolean isInPrimaryKeys(List<String> pks, EditableFeatureAttributeDescriptor attr) { |
160 |
if( pks == null || attr == null ) { |
161 |
return false; |
162 |
} |
163 |
// En algunos gestores de BBDD, los nombres obtenidos de las pks de los
|
164 |
// metadados no coinciden con los nombres de los campos ya que unos estan
|
165 |
// en mayusculas y otros en minusculas, asi que en lugar de usar un "contains"
|
166 |
// nos los recorremos y comparamos con IgnoreCase.
|
167 |
for (String pk : pks) { |
168 |
if( StringUtils.equalsIgnoreCase(pk, attr.getName()) ) {
|
169 |
return true; |
170 |
} |
171 |
} |
172 |
return false; |
173 |
} |
174 |
|
175 |
protected List<String> getPrimaryKeysFromMetadata( |
176 |
Connection conn,
|
177 |
String catalog,
|
178 |
String schema,
|
179 |
String table) throws SQLException { |
180 |
|
181 |
ResultSet rsPrimaryKeys = null; |
182 |
ResultSet rs = null; |
183 |
try {
|
184 |
DatabaseMetaData metadata = conn.getMetaData();
|
185 |
rs = metadata.getTables(catalog, schema, table, null);
|
186 |
|
187 |
if (!rs.next()) {
|
188 |
// No tables found with default values, ignoring catalog
|
189 |
rs.close(); |
190 |
catalog = null;
|
191 |
schema = null;
|
192 |
rs = metadata.getTables(catalog, schema, table, null);
|
193 |
if (!rs.next()) {
|
194 |
// table not found
|
195 |
return null; |
196 |
} else if (rs.next()) { |
197 |
// More that one, cant identify
|
198 |
return null; |
199 |
} |
200 |
|
201 |
} else if (rs.next()) { |
202 |
// More that one, cant identify
|
203 |
return null; |
204 |
} |
205 |
rsPrimaryKeys = metadata.getPrimaryKeys(catalog, schema, table); |
206 |
List pks = new ArrayList(); |
207 |
while (rsPrimaryKeys.next()) {
|
208 |
pks.add(rsPrimaryKeys.getString("COLUMN_NAME"));
|
209 |
} |
210 |
return pks;
|
211 |
|
212 |
} catch (SQLException e) { |
213 |
return null; |
214 |
|
215 |
} finally {
|
216 |
JDBCUtils.closeQuietly(rs); |
217 |
JDBCUtils.closeQuietly(rsPrimaryKeys); |
218 |
} |
219 |
|
220 |
} |
221 |
|
222 |
protected List<String> getPrimaryKeysFromInformationSchema(Connection conn) throws SQLException { |
223 |
|
224 |
String sql = getSQLToRetrievePrimaryKeysFromInformationSchema();
|
225 |
|
226 |
Statement st = null; |
227 |
ResultSet rs = null; |
228 |
List<String> pks = new ArrayList(); |
229 |
try {
|
230 |
st = conn.createStatement(); |
231 |
rs = JDBCUtils.executeQuery(st, sql); |
232 |
while (rs.next()) {
|
233 |
pks.add(rs.getString(1));
|
234 |
} |
235 |
if (pks.isEmpty()) {
|
236 |
return null; |
237 |
} |
238 |
return pks;
|
239 |
|
240 |
} catch (Exception ex) { |
241 |
return pks;
|
242 |
|
243 |
} finally {
|
244 |
JDBCUtils.closeQuietly(rs); |
245 |
JDBCUtils.closeQuietly(st); |
246 |
} |
247 |
} |
248 |
|
249 |
public String getSQLToRetrievePrimaryKeysFromInformationSchema() throws SQLException { |
250 |
JDBCSQLBuilderBase sqlbuilder = this.createSQLBuilder();
|
251 |
ExpressionBuilder expbuilder = sqlbuilder.expression(); |
252 |
|
253 |
sqlbuilder.select().column().name("COLUMN_NAME");
|
254 |
sqlbuilder.select().column().name("CONSTRAINT_TYPE");
|
255 |
sqlbuilder.select().from().custom( |
256 |
"INFORMATION_SCHEMA.table_constraints t_cons "
|
257 |
+ "inner join INFORMATION_SCHEMA.key_column_usage c on "
|
258 |
+ "c.constraint_catalog = t_cons.constraint_catalog and "
|
259 |
+ "c.table_schema = t_cons.table_schema and "
|
260 |
+ "c.table_name = t_cons.table_name and "
|
261 |
+ "c.constraint_name = t_cons.constraint_name "
|
262 |
); |
263 |
sqlbuilder.select().where().set( |
264 |
expbuilder.like( |
265 |
expbuilder.custom("c.TABLE_NAME"),
|
266 |
expbuilder.constant(table.getTable()) |
267 |
) |
268 |
); |
269 |
if( table.hasSchema() ) {
|
270 |
sqlbuilder.select().where().and( |
271 |
expbuilder.like( |
272 |
expbuilder.custom("c.TABLE_SCHEMA"),
|
273 |
expbuilder.constant(table.getSchema()) |
274 |
) |
275 |
); |
276 |
} |
277 |
// if (catalog != null) {
|
278 |
// sqlbuilder.select().where().and(
|
279 |
// expbuilder.like(
|
280 |
// expbuilder.custom("c.CONSTRAINT_CATALOG"),
|
281 |
// expbuilder.constant(catalog)
|
282 |
// )
|
283 |
// );
|
284 |
// }
|
285 |
sqlbuilder.select().where().and( |
286 |
expbuilder.eq( |
287 |
expbuilder.column("CONSTRAINT_TYPE"),
|
288 |
expbuilder.constant("PRIMARY KEY")
|
289 |
) |
290 |
); |
291 |
return sqlbuilder.toString();
|
292 |
} |
293 |
|
294 |
|
295 |
protected EditableFeatureAttributeDescriptor getAttributeFromMetadata(
|
296 |
EditableFeatureType type, |
297 |
Connection conn,
|
298 |
ResultSetMetaData rsMetadata,
|
299 |
int colIndex
|
300 |
) throws SQLException { |
301 |
|
302 |
EditableFeatureAttributeDescriptor attr = type.add( |
303 |
rsMetadata.getColumnName(colIndex), |
304 |
this.getDataTypeFromMetadata(rsMetadata, colIndex)
|
305 |
); |
306 |
attr.setAllowNull( |
307 |
rsMetadata.isNullable(colIndex) == ResultSetMetaData.columnNullable
|
308 |
); |
309 |
attr.setIsAutomatic(rsMetadata.isAutoIncrement(colIndex)); |
310 |
attr.setIsReadOnly(rsMetadata.isReadOnly(colIndex)); |
311 |
switch(attr.getType()) {
|
312 |
case DataTypes.STRING:
|
313 |
attr.setSize(rsMetadata.getPrecision(colIndex)); |
314 |
attr.setPrecision(DataType.PRECISION_NONE); |
315 |
attr.setScale(DataType.SCALE_NONE); |
316 |
break;
|
317 |
case DataTypes.BYTE:
|
318 |
attr.setDisplaySize(rsMetadata.getColumnDisplaySize(colIndex)); |
319 |
attr.setPrecision(DataType.BYTE_DEFAULT_PRECISION); |
320 |
attr.setScale(DataType.SCALE_NONE); |
321 |
break;
|
322 |
case DataTypes.INT:
|
323 |
attr.setDisplaySize(rsMetadata.getColumnDisplaySize(colIndex)); |
324 |
attr.setPrecision(DataType.INT_DEFAULT_PRECISION); |
325 |
attr.setScale(DataType.SCALE_NONE); |
326 |
break;
|
327 |
case DataTypes.LONG:
|
328 |
attr.setDisplaySize(rsMetadata.getColumnDisplaySize(colIndex)); |
329 |
attr.setPrecision(DataType.LONG_DEFAULT_PRECISION); |
330 |
attr.setScale(DataType.SCALE_NONE); |
331 |
break;
|
332 |
case DataTypes.FLOAT:
|
333 |
attr.setDisplaySize(rsMetadata.getColumnDisplaySize(colIndex)); |
334 |
attr.setPrecision(DataType.FLOAT_DEFAULT_PRECISION); |
335 |
attr.setScale(DataType.SCALE_NONE); |
336 |
break;
|
337 |
case DataTypes.DOUBLE:
|
338 |
attr.setDisplaySize(rsMetadata.getColumnDisplaySize(colIndex)); |
339 |
attr.setPrecision(DataType.DOUBLE_DEFAULT_PRECISION); |
340 |
attr.setScale(DataType.SCALE_NONE); |
341 |
break;
|
342 |
case DataTypes.DECIMAL:
|
343 |
attr.setDisplaySize(rsMetadata.getColumnDisplaySize(colIndex)); |
344 |
attr.setScale(rsMetadata.getScale(colIndex)); |
345 |
attr.setPrecision(rsMetadata.getPrecision(colIndex)); |
346 |
break;
|
347 |
case DataTypes.OBJECT:
|
348 |
attr.setAdditionalInfo( |
349 |
"SQLType",
|
350 |
rsMetadata.getColumnType(colIndex) |
351 |
); |
352 |
attr.setAdditionalInfo( |
353 |
"SQLTypeName",
|
354 |
rsMetadata.getColumnTypeName(colIndex) |
355 |
); |
356 |
break;
|
357 |
case DataTypes.GEOMETRY:
|
358 |
this.fetchGeometryTypeAndSRS(attr, rsMetadata, colIndex);
|
359 |
break;
|
360 |
} |
361 |
return attr;
|
362 |
} |
363 |
|
364 |
protected int getDataTypeFromMetadata( |
365 |
ResultSetMetaData rsMetadata,
|
366 |
int colIndex
|
367 |
) throws SQLException { |
368 |
|
369 |
switch (rsMetadata.getColumnType(colIndex)) {
|
370 |
case java.sql.Types.TINYINT:
|
371 |
return DataTypes.BYTE;
|
372 |
|
373 |
case java.sql.Types.SMALLINT:
|
374 |
case java.sql.Types.INTEGER:
|
375 |
return DataTypes.INT;
|
376 |
|
377 |
case java.sql.Types.BIGINT:
|
378 |
return DataTypes.LONG;
|
379 |
|
380 |
case java.sql.Types.REAL:
|
381 |
case java.sql.Types.FLOAT:
|
382 |
return DataTypes.FLOAT;
|
383 |
|
384 |
case java.sql.Types.DOUBLE:
|
385 |
return DataTypes.DOUBLE;
|
386 |
|
387 |
case java.sql.Types.NUMERIC:
|
388 |
case java.sql.Types.DECIMAL:
|
389 |
return DataTypes.DECIMAL;
|
390 |
|
391 |
case java.sql.Types.CHAR:
|
392 |
case java.sql.Types.VARCHAR:
|
393 |
case java.sql.Types.LONGVARCHAR:
|
394 |
return DataTypes.STRING;
|
395 |
|
396 |
case java.sql.Types.DATE:
|
397 |
return DataTypes.DATE;
|
398 |
|
399 |
case java.sql.Types.TIME:
|
400 |
return DataTypes.TIME;
|
401 |
|
402 |
case java.sql.Types.TIMESTAMP:
|
403 |
return DataTypes.TIMESTAMP;
|
404 |
|
405 |
case java.sql.Types.BOOLEAN:
|
406 |
case java.sql.Types.BIT:
|
407 |
return DataTypes.BOOLEAN;
|
408 |
|
409 |
case java.sql.Types.BLOB:
|
410 |
case java.sql.Types.BINARY:
|
411 |
case java.sql.Types.LONGVARBINARY:
|
412 |
return DataTypes.BYTEARRAY;
|
413 |
|
414 |
default:
|
415 |
String typeName = rsMetadata.getColumnTypeName(colIndex);
|
416 |
if( "geometry".equalsIgnoreCase(typeName) ) { |
417 |
return DataTypes.GEOMETRY;
|
418 |
} |
419 |
return DataTypes.OBJECT;
|
420 |
} |
421 |
} |
422 |
|
423 |
/**
|
424 |
* Inicializa el tipo, subtipo y SRS del attributo de tipo geometria.
|
425 |
*
|
426 |
* @param attr
|
427 |
* @param rsMetadata
|
428 |
* @param colIndex
|
429 |
*/
|
430 |
protected void fetchGeometryTypeAndSRS( |
431 |
EditableFeatureAttributeDescriptor attr, |
432 |
ResultSetMetaData rsMetadata,
|
433 |
int colIndex
|
434 |
) { |
435 |
if( attr.getType()!=DataTypes.GEOMETRY ) {
|
436 |
return;
|
437 |
} |
438 |
try {
|
439 |
GeometryType geomType = GeometryLocator.getGeometryManager().getGeometryType( |
440 |
Geometry.TYPES.GEOMETRY, |
441 |
Geometry.SUBTYPES.GEOM2D |
442 |
); |
443 |
attr.setGeometryType(geomType); |
444 |
attr.setSRS((IProjection)null);
|
445 |
} catch (Exception ex) { |
446 |
LOGGER.warn("Can't get default geometry type.",ex);
|
447 |
} |
448 |
} |
449 |
|
450 |
} |