/
JDBCDataStore.java
5163 lines (4511 loc) · 192 KB
/
JDBCDataStore.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* GeoTools - The Open Source Java GIS Toolkit
* http://geotools.org
*
* (C) 2002-2016, Open Source Geospatial Foundation (OSGeo)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation;
* version 2.1 of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*/
package org.geotools.jdbc;
import static org.geotools.jdbc.VirtualTable.WHERE_CLAUSE_PLACE_HOLDER;
import static org.geotools.jdbc.VirtualTable.WHERE_CLAUSE_PLACE_HOLDER_LENGTH;
import static org.geotools.jdbc.VirtualTable.setKeepWhereClausePlaceHolderHint;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.net.URLDecoder;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.logging.Level;
import javax.sql.DataSource;
import org.apache.commons.lang3.ArrayUtils;
import org.geotools.data.DataStore;
import org.geotools.data.DefaultTransaction;
import org.geotools.data.FeatureStore;
import org.geotools.data.GmlObjectStore;
import org.geotools.data.InProcessLockingManager;
import org.geotools.data.Query;
import org.geotools.data.Transaction;
import org.geotools.data.Transaction.State;
import org.geotools.data.jdbc.FilterToSQL;
import org.geotools.data.jdbc.FilterToSQLException;
import org.geotools.data.jdbc.datasource.ManageableDataSource;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.data.simple.SimpleFeatureIterator;
import org.geotools.data.store.ContentDataStore;
import org.geotools.data.store.ContentEntry;
import org.geotools.data.store.ContentFeatureSource;
import org.geotools.data.store.ContentState;
import org.geotools.feature.AttributeTypeBuilder;
import org.geotools.feature.NameImpl;
import org.geotools.feature.simple.SimpleFeatureBuilder;
import org.geotools.feature.visitor.CountVisitor;
import org.geotools.feature.visitor.GroupByVisitor;
import org.geotools.feature.visitor.LimitingVisitor;
import org.geotools.feature.visitor.UniqueCountVisitor;
import org.geotools.feature.visitor.UniqueVisitor;
import org.geotools.filter.FilterCapabilities;
import org.geotools.filter.visitor.ExpressionTypeVisitor;
import org.geotools.filter.visitor.PostPreProcessFilterSplittingVisitor;
import org.geotools.geometry.jts.ReferencedEnvelope;
import org.geotools.jdbc.JoinInfo.JoinPart;
import org.geotools.referencing.CRS;
import org.geotools.util.Converters;
import org.geotools.util.SoftValueHashMap;
import org.geotools.util.factory.Hints;
import org.locationtech.jts.geom.Envelope;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.GeometryFactory;
import org.locationtech.jts.geom.Point;
import org.opengis.feature.FeatureVisitor;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
import org.opengis.feature.type.AttributeDescriptor;
import org.opengis.feature.type.GeometryDescriptor;
import org.opengis.feature.type.Name;
import org.opengis.filter.Filter;
import org.opengis.filter.Id;
import org.opengis.filter.PropertyIsLessThanOrEqualTo;
import org.opengis.filter.expression.BinaryExpression;
import org.opengis.filter.expression.Expression;
import org.opengis.filter.expression.Function;
import org.opengis.filter.expression.Literal;
import org.opengis.filter.expression.PropertyName;
import org.opengis.filter.identity.FeatureId;
import org.opengis.filter.identity.GmlObjectId;
import org.opengis.filter.sort.SortBy;
import org.opengis.filter.sort.SortOrder;
import org.opengis.referencing.FactoryException;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.opengis.referencing.operation.TransformException;
/**
* Datastore implementation for jdbc based relational databases.
*
* <p>This class is not intended to be subclassed on a per database basis. Instead the notion of a
* "dialect" is used.
*
* <p>
*
* <h3>Dialects</h3>
*
* A dialect ({@link SQLDialect}) encapsulates all the operations that are database specific.
* Therefore to implement a jdbc based datastore one must extend SQLDialect. The specific dialect to
* use is set using {@link #setSQLDialect(SQLDialect)}.
*
* <p>
*
* <h3>Database Connections</h3>
*
* Connections to the underlying database are obtained through a {@link DataSource}. A datastore
* must be specified using {@link #setDataSource(DataSource)}.
*
* <p>
*
* <h3>Schemas</h3>
*
* This datastore supports the notion of database schemas, which is more or less just a grouping of
* tables. When a schema is specified, only those tables which are part of the schema are provided
* by the datastore. The schema is specified using {@link #setDatabaseSchema(String)}.
*
* <p>
*
* <h3>Spatial Functions</h3>
*
* The set of spatial operations or functions that are supported by the specific database are
* reported with a {@link FilterCapabilities} instance. This is specified using {@link
* #setFilterCapabilities(FilterCapabilities)}.
*
* @author Justin Deoliveira, The Open Planning Project
*/
public final class JDBCDataStore extends ContentDataStore implements GmlObjectStore {
/** Caches the "setValue" method in various aggregate visitors */
private static SoftValueHashMap<Class, Method> AGGREGATE_SETVALUE_CACHE =
new SoftValueHashMap<>(1000);
/**
* When true, record a stack trace documenting who disposed the JDBCDataStore. If dispose() is
* called a second time we can identify the offending parties.
*/
protected static final Boolean TRACE_ENABLED =
"true".equalsIgnoreCase(System.getProperty("gt2.jdbc.trace"));
/**
* The native SRID associated to a certain descriptor TODO: qualify this key with
* 'org.geotools.jdbc'
*/
public static final String JDBC_NATIVE_SRID = "nativeSRID";
/** Boolean marker stating whether the feature type is to be considered read only */
public static final String JDBC_READ_ONLY = "org.geotools.jdbc.readOnly";
/** Boolean marker stating whether an attribute is part of the primary key */
public static final String JDBC_PRIMARY_KEY_COLUMN = "org.geotools.jdbc.pk.column";
/**
* The key for attribute descriptor user data which specifies the original database column data
* type.
*/
public static final String JDBC_NATIVE_TYPENAME = "org.geotools.jdbc.nativeTypeName";
/**
* The key for attribute descriptor user data which specifies the original database column data
* type, as a {@link Types} value.
*/
public static final String JDBC_NATIVE_TYPE = "org.geotools.jdbc.nativeType";
/** Used to specify the column alias to use when encoding a column in a select */
public static final String JDBC_COLUMN_ALIAS = "org.geotools.jdbc.columnAlias";
/** Contains a {@link EnumMapper} to support enums mapped from integer values */
public static final String JDBC_ENUM_MAP = "org.geotools.jdbc.enumMap";
/** name of table to use to store geometries when {@link #associations} is set. */
protected static final String GEOMETRY_TABLE = "geometry";
/**
* name of table to use to store multi geometries made up of non-multi geometries when {@link
* #associations} is set.
*/
protected static final String MULTI_GEOMETRY_TABLE = "multi_geometry";
/** name of table to use to store geometry associations when {@link #associations} is set. */
protected static final String GEOMETRY_ASSOCIATION_TABLE = "geometry_associations";
/**
* name of table to use to store feature relationships (information about associations) when
* {@link #associations} is set.
*/
protected static final String FEATURE_RELATIONSHIP_TABLE = "feature_relationships";
/** name of table to use to store feature associations when {@link #associations} is set. */
protected static final String FEATURE_ASSOCIATION_TABLE = "feature_associations";
/** The envelope returned when bounds is called against a geometryless feature type */
protected static final ReferencedEnvelope EMPTY_ENVELOPE = new ReferencedEnvelope();
/** Max number of ids to use for the optimized locks checking filter. */
public static final int MAX_IDS_IN_FILTER = 100;
/** data source */
protected DataSource dataSource;
/**
* Used with TRACE_ENABLED to record the thread responsible for disposing the JDBCDataStore. In
* the event dispose() is called a second time this throwable is used to identify the offending
* party.
*/
private Throwable disposedBy = null;
/** the dialect of sql */
public SQLDialect dialect;
/** The database schema. */
protected String databaseSchema;
/** sql type to java class mappings */
protected HashMap<Integer, Class<?>> sqlTypeToClassMappings;
/** sql type name to java class mappings */
protected HashMap<String, Class<?>> sqlTypeNameToClassMappings;
/** java class to sql type mappings; */
protected HashMap<Class<?>, Integer> classToSqlTypeMappings;
/** sql type to sql type name overrides */
protected HashMap<Integer, String> sqlTypeToSqlTypeNameOverrides;
/** cache of sqltypes found in database */
protected ConcurrentHashMap<Integer, String> dBsqlTypesCache;
/** Feature visitor to aggregate function name */
protected HashMap<Class<? extends FeatureVisitor>, String> aggregateFunctions;
/** java supported filter function mappings to dialect name; */
protected HashMap<String, String> supportedFunctions;
/**
* flag controlling if the datastore is supporting feature and geometry relationships with
* associations
*/
protected boolean associations = false;
/**
* The fetch size for this datastore, defaulting to 1000. Set to a value less or equal to 0 to
* disable fetch size limit and grab all the records in one shot.
*/
public int fetchSize;
/**
* The number of features to bufferize while inserting in order to do batch inserts.
*
* <p>By default 1 to avoid backward compatibility with badly written code that forgets to close
* the JDBCInsertFeatureWriter or does it after closing the DB connection.
*/
protected int batchInsertSize = 1;
/** flag controlling whether primary key columns of a table are exposed via the feature type. */
protected boolean exposePrimaryKeyColumns = false;
/**
* Finds the primary key definitions (instantiated here because the finders might keep state)
*/
protected PrimaryKeyFinder primaryKeyFinder =
new CompositePrimaryKeyFinder(
new MetadataTablePrimaryKeyFinder(), new HeuristicPrimaryKeyFinder());
/** Contains the SQL definition of the various virtual tables */
protected Map<String, VirtualTable> virtualTables = new ConcurrentHashMap<>();
/** The listeners that are allowed to handle the connection lifecycle */
protected List<ConnectionLifecycleListener> connectionLifecycleListeners =
new CopyOnWriteArrayList<>();
protected JDBCCallbackFactory callbackFactory = JDBCCallbackFactory.NULL;
private volatile NamePatternEscaping namePatternEscaping;
public JDBCDataStore() {
super();
}
public void setCallbackFactory(JDBCCallbackFactory factory) {
this.callbackFactory = factory;
}
public JDBCCallbackFactory getCallbackFactory() {
return callbackFactory;
}
public JDBCFeatureSource getAbsoluteFeatureSource(String typeName) throws IOException {
ContentFeatureSource featureSource = getFeatureSource(typeName);
if (featureSource instanceof JDBCFeatureSource) {
return (JDBCFeatureSource) featureSource;
}
return ((JDBCFeatureStore) featureSource).getFeatureSource();
}
/**
* Adds a virtual table to the data store. If a virtual table with the same name was registered
*
* @throws IOException If the view definition is not valid
*/
public void createVirtualTable(VirtualTable vtable) throws IOException {
try {
virtualTables.put(vtable.getName(), new VirtualTable(vtable));
// the new vtable might be overriding a previous definition
entries.remove(new NameImpl(namespaceURI, vtable.getName()));
getSchema(vtable.getName());
} catch (IOException e) {
virtualTables.remove(vtable.getName());
throw e;
}
}
/** Returns a modifiable list of connection lifecycle listeners */
public List<ConnectionLifecycleListener> getConnectionLifecycleListeners() {
return connectionLifecycleListeners;
}
/** Removes and returns the specified virtual table */
public VirtualTable dropVirtualTable(String name) {
// the new vtable might be overriding a previous definition
VirtualTable vt = virtualTables.remove(name);
if (vt != null) {
entries.remove(new NameImpl(namespaceURI, name));
}
return vt;
}
/** Returns a live, immutable view of the virtual tables map (from name to definition) */
public Map<String, VirtualTable> getVirtualTables() {
Map<String, VirtualTable> result = new HashMap<>();
for (String key : virtualTables.keySet()) {
result.put(key, new VirtualTable(virtualTables.get(key)));
}
return Collections.unmodifiableMap(result);
}
/** Returns the finder used to build {@link PrimaryKey} representations */
public PrimaryKeyFinder getPrimaryKeyFinder() {
return primaryKeyFinder;
}
/** Sets the finder used to build {@link PrimaryKey} representations */
public void setPrimaryKeyFinder(PrimaryKeyFinder primaryKeyFinder) {
this.primaryKeyFinder = primaryKeyFinder;
}
/**
* The current fetch size. The fetch size influences how many records are read from the dbms at
* a time. If set to a value less or equal than zero, all the records will be read in one shot,
* severily increasing the memory requirements to read a big number of features.
*/
public int getFetchSize() {
return fetchSize;
}
/** Changes the fetch size. */
public void setFetchSize(int fetchSize) {
this.fetchSize = fetchSize;
}
/** @return the number of features to bufferize while inserting in order to do batch inserts. */
public int getBatchInsertSize() {
return batchInsertSize;
}
/**
* Set the number of features to bufferize while inserting in order to do batch inserts.
*
* <p>Warning: when changing this value from its default of 1, the behavior of the {@link
* JDBCInsertFeatureWriter} is changed in non backward compatible ways. If your code closes the
* writer before closing the connection, you are fine. Plus, the feature added events will be
* delayed until a batch is actually inserted.
*/
public void setBatchInsertSize(int batchInsertSize) {
this.batchInsertSize = batchInsertSize;
}
/**
* Determines if the datastore creates feature types which include those columns / attributes
* which compose the primary key.
*/
public boolean isExposePrimaryKeyColumns() {
return exposePrimaryKeyColumns;
}
/**
* Sets the flag controlling if the datastore creates feature types which include those columns
* / attributes which compose the primary key.
*/
public void setExposePrimaryKeyColumns(boolean exposePrimaryKeyColumns) {
if (this.exposePrimaryKeyColumns != exposePrimaryKeyColumns) {
entries.clear();
}
this.exposePrimaryKeyColumns = exposePrimaryKeyColumns;
}
/**
* The dialect the datastore uses to generate sql statements in order to communicate with the
* underlying database.
*
* @return The dialect, never <code>null</code>.
*/
public SQLDialect getSQLDialect() {
return dialect;
}
/**
* Sets the dialect the datastore uses to generate sql statements in order to communicate with
* the underlying database.
*
* @param dialect The dialect, never <code>null</code>.
*/
public void setSQLDialect(SQLDialect dialect) {
if (dialect == null) {
throw new NullPointerException();
}
this.dialect = dialect;
}
/**
* The data source the datastore uses to obtain connections to the underlying database.
*
* @return The data source, never <code>null</code>.
*/
public DataSource getDataSource() {
if (dataSource == null) {
// Should never return null so throw an exception
if (TRACE_ENABLED) {
// If TRACE_ENABLED disposedBy may have stored an exception
if (disposedBy == null) {
LOGGER.log(Level.WARNING, "JDBCDataStore was never given a DataSource.");
throw new IllegalStateException(
"DataSource not available as it was never set.");
} else {
LOGGER.log(
Level.WARNING, "JDBCDataStore was disposed:" + disposedBy, disposedBy);
throw new IllegalStateException(
"DataSource not available after calling dispose().");
}
} else {
throw new IllegalStateException(
"DataSource not available after calling dispose() or before being set.");
}
}
return dataSource;
}
/**
* Sets the data source the datastore uses to obtain connections to the underlying database.
*
* @param dataSource The data source, never <code>null</code>.
*/
public void setDataSource(DataSource dataSource) {
if (this.dataSource != null) {
LOGGER.log(
Level.FINE,
"Setting DataSource on JDBCDataStore that already has DataSource set");
}
if (dataSource == null) {
throw new IllegalArgumentException(
"JDBCDataStore's DataSource should not be set to null");
}
this.dataSource = dataSource;
}
/**
* The schema from which this datastore is serving tables from.
*
* @return the schema, or <code>null</code> if non specified.
*/
public String getDatabaseSchema() {
return databaseSchema;
}
/**
* Set the database schema for the datastore.
*
* <p>When this value is set only those tables which are part of the schema are served through
* the datastore. This value can be set to <code>null</code> to specify no particular schema.
*
* @param databaseSchema The schema, may be <code>null</code>.
*/
public void setDatabaseSchema(String databaseSchema) {
this.databaseSchema = databaseSchema;
}
/**
* The filter capabilities which reports which spatial operations the underlying database can
* handle natively.
*
* @return The filter capabilities, never <code>null</code>.
*/
public FilterCapabilities getFilterCapabilities() {
if (dialect instanceof PreparedStatementSQLDialect)
return ((PreparedStatementSQLDialect) dialect)
.createPreparedFilterToSQL()
.getCapabilities();
else return ((BasicSQLDialect) dialect).createFilterToSQL().getCapabilities();
}
/**
* Flag controlling if the datastore is supporting feature and geometry relationships with
* associations
*/
public boolean isAssociations() {
return associations;
}
/**
* Sets the flag controlling if the datastore is supporting feature and geometry relationships
* with associations
*/
public void setAssociations(boolean foreignKeyGeometries) {
this.associations = foreignKeyGeometries;
}
/**
* The sql type to java type mappings that the datastore uses when reading and writing objects
* to and from the database.
*
* <p>These mappings are derived from {@link
* SQLDialect#registerSqlTypeToClassMappings(java.util.Map)}
*
* @return The mappings, never <code>null</code>.
*/
public Map<Integer, Class<?>> getSqlTypeToClassMappings() {
if (sqlTypeToClassMappings == null) {
sqlTypeToClassMappings = new HashMap<>();
dialect.registerSqlTypeToClassMappings(sqlTypeToClassMappings);
}
return sqlTypeToClassMappings;
}
/**
* The sql type name to java type mappings that the dialect uses when
* reading and writing objects to and from the database.
* <p>
* These mappings are derived from {@link SQLDialect#registerSqlTypeNameToClassMappings(Map)}
* </p>
*
* @return The mappings, never <code>null<code>.
*/
public Map<String, Class<?>> getSqlTypeNameToClassMappings() {
if (sqlTypeNameToClassMappings == null) {
sqlTypeNameToClassMappings = new HashMap<>();
dialect.registerSqlTypeNameToClassMappings(sqlTypeNameToClassMappings);
}
return sqlTypeNameToClassMappings;
}
/**
* The java type to sql type mappings that the datastore uses when reading and writing objects
* to and from the database.
*
* <p>These mappings are derived from {@link SQLDialect#registerClassToSqlMappings(Map)}
*
* @return The mappings, never <code>null</code>.
*/
public Map<Class<?>, Integer> getClassToSqlTypeMappings() {
if (classToSqlTypeMappings == null) {
HashMap<Class<?>, Integer> classToSqlTypeMappings = new HashMap<>();
dialect.registerClassToSqlMappings(classToSqlTypeMappings);
this.classToSqlTypeMappings = classToSqlTypeMappings;
}
return classToSqlTypeMappings;
}
/**
* Returns any ovverides which map integer constants for database types (from {@link Types}) to
* database type names.
*
* <p>This method will return an empty map when there are no overrides.
*/
public Map<Integer, String> getSqlTypeToSqlTypeNameOverrides() {
if (sqlTypeToSqlTypeNameOverrides == null) {
sqlTypeToSqlTypeNameOverrides = new HashMap<>();
dialect.registerSqlTypeToSqlTypeNameOverrides(sqlTypeToSqlTypeNameOverrides);
}
return sqlTypeToSqlTypeNameOverrides;
}
/**
* Returns a map integer constants for database types (from {@link Types}) to database type
* names.
*
* <p>This method will return an empty map when there are no overrides.
*/
public ConcurrentHashMap<Integer, String> getDBsqlTypesCache() {
if (dBsqlTypesCache == null) {
dBsqlTypesCache = new ConcurrentHashMap<>();
}
return dBsqlTypesCache;
}
/** Returns the supported aggregate functions and the visitors they map to. */
public Map<Class<? extends FeatureVisitor>, String> getAggregateFunctions() {
if (aggregateFunctions == null) {
aggregateFunctions = new HashMap<>();
dialect.registerAggregateFunctions(aggregateFunctions);
}
return aggregateFunctions;
}
/**
* Returns the java type mapped to the specified sql type.
*
* <p>If there is no such type mapped to <tt>sqlType</tt>, <code>null</code> is returned.
*
* @param sqlType The integer constant for the sql type from {@link Types}.
* @return The mapped java class, or <code>null</code>. if no such mapping exists.
*/
public Class<?> getMapping(int sqlType) {
return getSqlTypeToClassMappings().get(Integer.valueOf(sqlType));
}
/**
* Returns the java type mapped to the specified sql type name.
*
* <p>If there is no such type mapped to <tt>sqlTypeName</tt>, <code>null</code> is returned.
*
* @param sqlTypeName The name of the sql type.
* @return The mapped java class, or <code>null</code>. if no such mapping exists.
*/
public Class<?> getMapping(String sqlTypeName) {
Class<?> columnClass = getSqlTypeNameToClassMappings().get(sqlTypeName);
if (columnClass == null) {
return dialect.getMapping(sqlTypeName);
}
return columnClass;
}
/**
* Returns the sql type mapped to the specified java type.
*
* <p>If there is no such type mapped to <tt>clazz</tt>, <code>Types.OTHER</code> is returned.
*
* @param clazz The java class.
* @return The mapped sql type from {@link Types}, Types.OTHER if no such mapping exists.
*/
public Integer getMapping(Class<?> clazz) {
Integer mapping = getClassToSqlTypeMappings().get(clazz);
// check for arrays, but don't get fooled by BLOB/CLOB java counterparts
if (mapping == null && clazz.isArray()) {
mapping = Types.ARRAY;
}
if (mapping == null) {
// no match, try a "fuzzy" match in which we find the super class which matches best
List<Map.Entry<Class<?>, Integer>> matches = new ArrayList<>();
for (Map.Entry<Class<?>, Integer> e : getClassToSqlTypeMappings().entrySet()) {
if (e.getKey().isAssignableFrom(clazz)) {
matches.add(e);
}
}
if (!matches.isEmpty()) {
if (matches.size() == 1) {
// single match, great, use it
mapping = matches.get(0).getValue();
} else {
// sort to match lowest class in type hierarchy, if we end up with a list like:
// A, B where B is a super class of A, then chose A since it is the closest
// subclass to match
Collections.sort(
matches,
(o1, o2) -> {
if (o1.getKey().isAssignableFrom(o2.getKey())) {
return 1;
}
if (o2.getKey().isAssignableFrom(o1.getKey())) {
return -1;
}
return 0;
});
if (matches.get(1).getKey().isAssignableFrom(matches.get(0).getKey())) {
mapping = matches.get(0).getValue();
}
}
}
}
if (mapping == null) {
mapping = Types.OTHER;
LOGGER.warning("No mapping for " + clazz.getName());
}
return mapping;
}
/**
* Creates a table in the underlying database from the specified table.
*
* <p>This method will map the classes of the attributes of <tt>featureType</tt> to sql types
* and generate a 'CREATE TABLE' statement against the underlying database.
*
* @see DataStore#createSchema(SimpleFeatureType)
* @throws IllegalArgumentException If the table already exists.
* @throws IOException If the table cannot be created due to an error.
*/
@Override
public void createSchema(final SimpleFeatureType featureType) throws IOException {
if (entry(featureType.getName()) != null) {
String msg = "Schema '" + featureType.getName() + "' already exists";
throw new IllegalArgumentException(msg);
}
// execute the create table statement
// TODO: create a primary key and a spatial index
Connection cx = createConnection();
try {
String sql = createTableSQL(featureType, cx);
LOGGER.log(Level.FINE, "Create schema: {0}", sql);
Statement st = cx.createStatement();
try {
st.execute(sql);
} finally {
closeSafe(st);
}
dialect.postCreateTable(databaseSchema, featureType, cx);
} catch (Exception e) {
String msg = "Error occurred creating table";
throw (IOException) new IOException(msg).initCause(e);
} finally {
closeSafe(cx);
}
}
@Override
public void removeSchema(String typeName) throws IOException {
removeSchema(name(typeName));
}
@Override
public void removeSchema(Name typeName) throws IOException {
if (entry(typeName) == null) {
String msg = "Schema '" + typeName + "' does not exist";
throw new IllegalArgumentException(msg);
}
// check for virtual table
if (virtualTables.containsKey(typeName.getLocalPart())) {
dropVirtualTable(typeName.getLocalPart());
return;
}
SimpleFeatureType featureType = getSchema(typeName);
// execute the drop table statement
Connection cx = createConnection();
try {
// give the dialect a chance to cleanup pre
dialect.preDropTable(databaseSchema, featureType, cx);
String sql = dropTableSQL(featureType, cx);
LOGGER.log(Level.FINE, "Drop schema: {0}", sql);
Statement st = cx.createStatement();
try {
st.execute(sql);
} finally {
closeSafe(st);
}
dialect.postDropTable(databaseSchema, featureType, cx);
removeEntry(typeName);
} catch (Exception e) {
String msg = "Error occurred dropping table";
throw (IOException) new IOException(msg).initCause(e);
} finally {
closeSafe(cx);
}
}
/** */
@Override
public Object getGmlObject(GmlObjectId id, Hints hints) throws IOException {
// geometry?
if (isAssociations()) {
Connection cx = createConnection();
try {
try {
Statement st = null;
ResultSet rs = null;
if (getSQLDialect() instanceof PreparedStatementSQLDialect) {
st = selectGeometrySQLPS(id.getID(), cx);
rs = ((PreparedStatement) st).executeQuery();
} else {
String sql = selectGeometrySQL(id.getID());
LOGGER.log(Level.FINE, "Get GML object: {0}", sql);
st = cx.createStatement();
rs = st.executeQuery(sql);
}
try {
if (rs.next()) {
// read the geometry
Geometry g =
getSQLDialect()
.decodeGeometryValue(
null,
rs,
"geometry",
getGeometryFactory(),
cx,
hints);
// read the metadata
String name = rs.getString("name");
String desc = rs.getString("description");
setGmlProperties(g, id.getID(), name, desc);
return g;
}
} finally {
closeSafe(rs);
closeSafe(st);
}
} catch (SQLException e) {
throw (IOException) new IOException().initCause(e);
}
} finally {
closeSafe(cx);
}
}
// regular feature, first feature out the feature type
int i = id.getID().indexOf('.');
if (i == -1) {
LOGGER.info("Unable to determine feature type for GmlObjectId:" + id);
return null;
}
// figure out the type name from the id
String featureTypeName = id.getID().substring(0, i);
SimpleFeatureType featureType = getSchema(featureTypeName);
if (featureType == null) {
throw new IllegalArgumentException("No such feature type: " + featureTypeName);
}
// load the feature
Id filter = getFilterFactory().id(Collections.singleton(id));
Query query = new Query(featureTypeName);
query.setFilter(filter);
query.setHints(hints);
SimpleFeatureCollection features = getFeatureSource(featureTypeName).getFeatures(query);
if (!features.isEmpty()) {
try (SimpleFeatureIterator fi = features.features()) {
if (fi.hasNext()) {
return fi.next();
}
}
}
return null;
}
/**
* Creates a new instance of {@link JDBCFeatureStore}.
*
* @see ContentDataStore#createFeatureSource(ContentEntry)
*/
@Override
protected ContentFeatureSource createFeatureSource(ContentEntry entry) throws IOException {
// grab the schema, it carries a flag telling us if the feature type is read only
SimpleFeatureType schema = entry.getState(Transaction.AUTO_COMMIT).getFeatureType();
if (schema == null) {
// if the schema still haven't been computed, force its computation so
// that we can decide if the feature type is read only
schema = new JDBCFeatureSource(entry, null).buildFeatureType();
entry.getState(Transaction.AUTO_COMMIT).setFeatureType(schema);
}
Object readOnlyMarker = schema.getUserData().get(JDBC_READ_ONLY);
if (Boolean.TRUE.equals(readOnlyMarker)) {
return new JDBCFeatureSource(entry, null);
}
return new JDBCFeatureStore(entry, null);
}
// /**
// * Creates a new instance of {@link JDBCTransactionState}.
// */
// protected State createTransactionState(ContentSimpleFeatureSource featureSource)
// throws IOException {
// return new JDBCTransactionState((JDBCFeatureStore) featureSource);
// }
/**
* Creates an instanceof {@link JDBCState}.
*
* @see ContentDataStore#createContentState(ContentEntry)
*/
@Override
protected ContentState createContentState(ContentEntry entry) {
JDBCState state = new JDBCState(entry);
state.setExposePrimaryKeyColumns(exposePrimaryKeyColumns);
return state;
}
/**
* Generates the list of type names provided by the database.
*
* <p>The list is generated from the underlying database metadata.
*/
@Override
protected List<Name> createTypeNames() throws IOException {
Connection cx = createConnection();
/*
* <LI><B>TABLE_CAT</B> String => table catalog (may be <code>null</code>)
* <LI><B>TABLE_SCHEM</B> String => table schema (may be <code>null</code>)
* <LI><B>TABLE_NAME</B> String => table name
* <LI><B>TABLE_TYPE</B> String => table type. Typical types are "TABLE",
* "VIEW", "SYSTEM TABLE", "GLOBAL TEMPORARY",
* "LOCAL TEMPORARY", "ALIAS", "SYNONYM".
* <LI><B>REMARKS</B> String => explanatory comment on the table
* <LI><B>TYPE_CAT</B> String => the types catalog (may be <code>null</code>)
* <LI><B>TYPE_SCHEM</B> String => the types schema (may be <code>null</code>)
* <LI><B>TYPE_NAME</B> String => type name (may be <code>null</code>)
* <LI><B>SELF_REFERENCING_COL_NAME</B> String => name of the designated
* "identifier" column of a typed table (may be <code>null</code>)
* <LI><B>REF_GENERATION</B> String => specifies how values in
* SELF_REFERENCING_COL_NAME are created. Values are
* "SYSTEM", "USER", "DERIVED". (may be <code>null</code>)
*/
List<Name> typeNames = new ArrayList<>();
try {
DatabaseMetaData metaData = cx.getMetaData();
Set<String> availableTableTypes = new HashSet<>();
ResultSet tableTypes = null;
try {
tableTypes = metaData.getTableTypes();
while (tableTypes.next()) {
availableTableTypes.add(tableTypes.getString("TABLE_TYPE"));
}
} finally {
closeSafe(tableTypes);
}
Set<String> queryTypes = new HashSet<>();
for (String desiredTableType : dialect.getDesiredTablesType()) {
if (availableTableTypes.contains(desiredTableType)) {
queryTypes.add(desiredTableType);
}
}
ResultSet tables =
metaData.getTables(
null,
escapeNamePattern(metaData, databaseSchema),
"%",
queryTypes.toArray(new String[0]));
try {
if (fetchSize > 1) {
tables.setFetchSize(fetchSize);
}
while (tables.next()) {
String schemaName = tables.getString("TABLE_SCHEM");
String tableName = tables.getString("TABLE_NAME");
// use the dialect to filter
if (!dialect.includeTable(schemaName, tableName, cx)) {
continue;