You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@sis.apache.org by de...@apache.org on 2021/09/27 10:57:51 UTC
[sis] branch geoapi-4.0 updated (aaa0dd0 -> 56d681c)
This is an automated email from the ASF dual-hosted git repository.
desruisseaux pushed a change to branch geoapi-4.0
in repository https://gitbox.apache.org/repos/asf/sis.git.
from aaa0dd0 Modify the API for allowing user to specify a SQL query instead of a table name for a resource. Refactor implementation for sharing more code between table analyzer and query analyzer.
new 957d7b0 Support "export" foreigner keys on queries as we did for tables.
new 56d681c Port tests written by Alexis Manin.
The 2 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails. The revisions
listed as "add" were already present in the repository and have only
been added to this reference.
Summary of changes:
.../apache/sis/internal/sql/feature/Column.java | 42 ++---
.../sis/internal/sql/feature/FeatureAdapter.java | 4 +-
.../sis/internal/sql/feature/FeatureAnalyzer.java | 36 +++-
.../sis/internal/sql/feature/FeatureStream.java | 4 +-
.../sis/internal/sql/feature/QueryAnalyzer.java | 82 +++++-----
.../org/apache/sis/internal/sql/feature/Table.java | 6 +-
.../sis/internal/sql/feature/TableAnalyzer.java | 42 -----
.../org/apache/sis/storage/sql/SQLStoreTest.java | 181 ++++++++++++++++++---
8 files changed, 256 insertions(+), 141 deletions(-)
[sis] 02/02: Port tests written by Alexis Manin.
Posted by de...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
desruisseaux pushed a commit to branch geoapi-4.0
in repository https://gitbox.apache.org/repos/asf/sis.git
commit 56d681ce00105041959dd04dec00e24769cc4374
Author: Martin Desruisseaux <ma...@geomatys.com>
AuthorDate: Mon Sep 27 12:48:48 2021 +0200
Port tests written by Alexis Manin.
---
.../apache/sis/internal/sql/feature/Column.java | 42 +++---
.../sis/internal/sql/feature/FeatureAdapter.java | 4 +-
.../sis/internal/sql/feature/FeatureAnalyzer.java | 6 +-
.../sis/internal/sql/feature/FeatureStream.java | 4 +-
.../org/apache/sis/internal/sql/feature/Table.java | 6 +-
.../org/apache/sis/storage/sql/SQLStoreTest.java | 143 ++++++++++++++++++++-
6 files changed, 169 insertions(+), 36 deletions(-)
diff --git a/storage/sis-sqlstore/src/main/java/org/apache/sis/internal/sql/feature/Column.java b/storage/sis-sqlstore/src/main/java/org/apache/sis/internal/sql/feature/Column.java
index 5ea94e1..36418a9 100644
--- a/storage/sis-sqlstore/src/main/java/org/apache/sis/internal/sql/feature/Column.java
+++ b/storage/sis-sqlstore/src/main/java/org/apache/sis/internal/sql/feature/Column.java
@@ -23,7 +23,6 @@ import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.apache.sis.internal.metadata.sql.Reflection;
-import org.apache.sis.internal.metadata.sql.SQLBuilder;
import org.apache.sis.internal.metadata.sql.SQLUtilities;
import org.apache.sis.internal.feature.GeometryType;
import org.apache.sis.internal.util.Strings;
@@ -62,7 +61,13 @@ public final class Column {
* Title to use for displays. This is the name specified by the {@code AS} keyword in a {@code SELECT} clause.
* This is never null but may be identical to {@link #name} if no label was specified.
*/
- String label;
+ public final String label;
+
+ /**
+ * Name to use for feature property. This is the same as {@link #label} unless there is a name collision.
+ * In that case the property name is modified for avoiding the collision.
+ */
+ String propertyName;
/**
* Type of values as one of the constant enumerated in {@link Types} class.
@@ -130,6 +135,7 @@ public final class Column {
typeName = metadata.getString(Reflection.TYPE_NAME);
precision = metadata.getInt(Reflection.COLUMN_SIZE);
isNullable = Boolean.TRUE.equals(SQLUtilities.parseBoolean(metadata.getString(Reflection.IS_NULLABLE)));
+ propertyName = label;
}
/**
@@ -141,12 +147,13 @@ public final class Column {
* @see ResultSet#getMetaData()
*/
Column(final ResultSetMetaData metadata, final int column) throws SQLException {
- name = metadata.getColumnName(column);
- label = metadata.getColumnLabel(column);
- type = metadata.getColumnType(column);
- typeName = metadata.getColumnTypeName(column);
- precision = metadata.getPrecision(column);
- isNullable = metadata.isNullable(column) == ResultSetMetaData.columnNullable;
+ name = metadata.getColumnName(column);
+ label = metadata.getColumnLabel(column);
+ type = metadata.getColumnType(column);
+ typeName = metadata.getColumnTypeName(column);
+ precision = metadata.getPrecision(column);
+ isNullable = metadata.isNullable(column) == ResultSetMetaData.columnNullable;
+ propertyName = label;
}
/**
@@ -203,7 +210,7 @@ public final class Column {
*/
final AttributeTypeBuilder<?> createAttribute(final FeatureTypeBuilder feature) {
final Class<?> type = valueGetter.valueType;
- final AttributeTypeBuilder<?> attribute = feature.addAttribute(type).setName(label);
+ final AttributeTypeBuilder<?> attribute = feature.addAttribute(type).setName(propertyName);
if (precision > 0 && CharSequence.class.isAssignableFrom(type)) {
attribute.setMaximalLength(precision);
}
@@ -215,27 +222,14 @@ public final class Column {
}
/**
- * Appends the name and label of this column in a SQL statement.
- *
- * @param target builder of SQL statement where to append this column name.
- * @return {@code target} for invocation chaining.
- */
- final SQLBuilder append(final SQLBuilder target) {
- target.appendIdentifier(name);
- if (!name.equals(label)) {
- target.append(" AS ").appendIdentifier(label);
- }
- return target;
- }
-
- /**
* Returns a string representation for debugging purposes.
*
* @return a string representation of this column.
*/
@Override
public String toString() {
- return Strings.toString(getClass(), "name", name, "label", label, "type", type, "typeName", typeName,
+ return Strings.toString(getClass(),
+ "name", name, "propertyName", propertyName, "type", type, "typeName", typeName,
"geometryType", geometryType, "precision", precision, "isNullable", isNullable);
}
}
diff --git a/storage/sis-sqlstore/src/main/java/org/apache/sis/internal/sql/feature/FeatureAdapter.java b/storage/sis-sqlstore/src/main/java/org/apache/sis/internal/sql/feature/FeatureAdapter.java
index 44d60f1..d0a3613 100644
--- a/storage/sis-sqlstore/src/main/java/org/apache/sis/internal/sql/feature/FeatureAdapter.java
+++ b/storage/sis-sqlstore/src/main/java/org/apache/sis/internal/sql/feature/FeatureAdapter.java
@@ -172,7 +172,7 @@ final class FeatureAdapter {
*/
final SQLBuilder sql = new SQLBuilder(table.database).append(SQLBuilder.SELECT);
for (final Column column : attributes) {
- appendColumn(sql, column.name, columnIndices);
+ appendColumn(sql, column.label, columnIndices);
}
/*
* Collect information about associations in local arrays before to assign
@@ -326,7 +326,7 @@ final class FeatureAdapter {
final Column column = attributes[i];
final Object value = column.valueGetter.getValue(result, i+1);
if (value != null) {
- feature.setPropertyValue(column.label, value);
+ feature.setPropertyValue(column.propertyName, value);
}
}
return feature;
diff --git a/storage/sis-sqlstore/src/main/java/org/apache/sis/internal/sql/feature/FeatureAnalyzer.java b/storage/sis-sqlstore/src/main/java/org/apache/sis/internal/sql/feature/FeatureAnalyzer.java
index 5ecd631..e806e92 100644
--- a/storage/sis-sqlstore/src/main/java/org/apache/sis/internal/sql/feature/FeatureAnalyzer.java
+++ b/storage/sis-sqlstore/src/main/java/org/apache/sis/internal/sql/feature/FeatureAnalyzer.java
@@ -253,7 +253,7 @@ abstract class FeatureAnalyzer {
* do not know which column describes better the association (often there is none).
* In such case we use the foreigner key name as a fallback.
*/
- dependency.setPropertyName(column.label, count++);
+ dependency.setPropertyName(column.propertyName, count++);
final AssociationRoleBuilder association;
if (table != null) {
dependency.setSearchTable(analyzer, table, table.primaryKey, Relation.Direction.IMPORT);
@@ -272,8 +272,8 @@ abstract class FeatureAnalyzer {
* column should rarely be used directly.
*/
if (attribute != null) {
- attribute.setName(analyzer.nameFactory.createGenericName(null, "pk", column.label));
- column.label = attribute.getName().toString();
+ attribute.setName(analyzer.nameFactory.createGenericName(null, "pk", column.propertyName));
+ column.propertyName = attribute.getName().toString();
attribute = null;
}
}
diff --git a/storage/sis-sqlstore/src/main/java/org/apache/sis/internal/sql/feature/FeatureStream.java b/storage/sis-sqlstore/src/main/java/org/apache/sis/internal/sql/feature/FeatureStream.java
index 1254e02..f68951d 100644
--- a/storage/sis-sqlstore/src/main/java/org/apache/sis/internal/sql/feature/FeatureStream.java
+++ b/storage/sis-sqlstore/src/main/java/org/apache/sis/internal/sql/feature/FeatureStream.java
@@ -317,12 +317,12 @@ final class FeatureStream extends DeferredStream<Feature> {
if (distinct) {
String separator = "DISTINCT ";
for (final Column attribute : table.attributes) {
- attribute.append(sql.append(separator));
+ sql.append(separator).appendIdentifier(attribute.label);
separator = ", ";
}
} else {
// If we want a count and no distinct clause is specified, a single column is sufficient.
- table.attributes[0].append(sql);
+ sql.appendIdentifier(table.attributes[0].label);
}
table.appendFromClause(sql.append(')'));
if (selection != null) {
diff --git a/storage/sis-sqlstore/src/main/java/org/apache/sis/internal/sql/feature/Table.java b/storage/sis-sqlstore/src/main/java/org/apache/sis/internal/sql/feature/Table.java
index acf92ae..0d72ab8 100644
--- a/storage/sis-sqlstore/src/main/java/org/apache/sis/internal/sql/feature/Table.java
+++ b/storage/sis-sqlstore/src/main/java/org/apache/sis/internal/sql/feature/Table.java
@@ -98,7 +98,7 @@ final class Table extends AbstractFeatureSet {
* This array shall not be modified after construction.
*
* <p>Columns may have alias if it was necessary to avoid name collisions.
- * The alias is given by {@link Column#label} and will be the name used in {@link FeatureType}.</p>
+ * The alias is given by {@link Column#propertyName} and will be the name used in {@link FeatureType}.</p>
*/
final Column[] attributes;
@@ -266,7 +266,7 @@ final class Table extends AbstractFeatureSet {
final void appendTo(TreeTable.Node parent) {
parent = Relation.newChild(parent, featureType.getName().toString());
for (final Column attribute : attributes) {
- TableReference.newChild(parent, attribute.label);
+ TableReference.newChild(parent, attribute.propertyName);
}
appendAll(parent, importedKeys, " → ");
appendAll(parent, exportedKeys, " ← ");
@@ -320,7 +320,7 @@ final class Table extends AbstractFeatureSet {
if (m == null) {
m = new HashMap<>(Containers.hashMapCapacity(attributes.length));
for (final Column c : attributes) {
- String label = c.label;
+ String label = c.propertyName;
m.put(label, c);
final int s = label.lastIndexOf(DefaultNameSpace.DEFAULT_SEPARATOR);
if (s >= 0) {
diff --git a/storage/sis-sqlstore/src/test/java/org/apache/sis/storage/sql/SQLStoreTest.java b/storage/sis-sqlstore/src/test/java/org/apache/sis/storage/sql/SQLStoreTest.java
index 4e113fd..3dcf87b 100644
--- a/storage/sis-sqlstore/src/test/java/org/apache/sis/storage/sql/SQLStoreTest.java
+++ b/storage/sis-sqlstore/src/test/java/org/apache/sis/storage/sql/SQLStoreTest.java
@@ -22,10 +22,12 @@ import java.util.HashSet;
import java.util.Arrays;
import java.util.Collection;
import java.util.stream.Stream;
+import java.util.concurrent.atomic.AtomicInteger;
import org.apache.sis.storage.FeatureSet;
import org.apache.sis.storage.StorageConnector;
import org.apache.sis.storage.DataStoreException;
import org.apache.sis.filter.DefaultFilterFactory;
+import org.apache.sis.internal.feature.AttributeConvention;
import org.apache.sis.storage.FeatureQuery;
import org.apache.sis.test.sql.TestDatabase;
import org.apache.sis.test.TestUtilities;
@@ -185,12 +187,16 @@ public final strictfp class SQLStoreTest extends TestCase {
*/
verifySimpleQuerySorting(store);
verifySimpleWhere(store);
+ verifyStreamOperations(store.findResource("Cities"));
canada = null;
}
/*
* Verify using SQL statements instead of tables.
*/
verifyFetchCityTableAsQuery(connector);
+ verifyNestedSQLQuery(connector);
+ verifyLimitOffsetAndColumnSelectionFromQuery(connector);
+ verifyDistinctQuery(connector);
}
}
@@ -369,13 +375,49 @@ public final strictfp class SQLStoreTest extends TestCase {
}
/**
+ * Checks that operations stacked on feature stream are well executed.
+ * This test focuses on mapping and peeking actions overloaded by SQL streams.
+ * Operations used here are meaningless; we just want to ensure that the pipeline does not skip any operation.
+ *
+ * @param cities a feature set containing all cities defined for the test class.
+ */
+ private void verifyStreamOperations(final FeatureSet cities) throws DataStoreException {
+ try (Stream<Feature> features = cities.features(false)) {
+ final AtomicInteger peekCount = new AtomicInteger();
+ final AtomicInteger mapCount = new AtomicInteger();
+ final long actualPopulations = features.peek(f -> peekCount.incrementAndGet())
+ .peek(f -> peekCount.incrementAndGet())
+ .map (f -> {mapCount.incrementAndGet(); return f;})
+ .peek(f -> peekCount.incrementAndGet())
+ .map (f -> {mapCount.incrementAndGet(); return f;})
+ .map (f -> f.getPropertyValue("population"))
+ .mapToDouble(obj -> ((Number) obj).doubleValue())
+ .peek(f -> peekCount.incrementAndGet())
+ .peek(f -> peekCount.incrementAndGet())
+ .boxed()
+ .mapToDouble(d -> {mapCount.incrementAndGet(); return d;})
+ .mapToObj (d -> {mapCount.incrementAndGet(); return d;})
+ .mapToDouble(d -> {mapCount.incrementAndGet(); return d;})
+ .map (d -> {mapCount.incrementAndGet(); return d;})
+ .mapToLong (d -> (long) d)
+ .sum();
+
+ long expectedPopulations = 0;
+ for (City city : City.values()) expectedPopulations += city.population;
+ assertEquals("Overall population count via Stream pipeline", expectedPopulations, actualPopulations);
+ assertEquals("Number of mapping (by element in the stream)", 24, mapCount.get());
+ assertEquals("Number of peeking (by element in the stream)", 20, peekCount.get());
+ }
+ }
+
+ /**
* Tests fetching the content of the Cities table, but using a user-supplied SQL query.
*/
private void verifyFetchCityTableAsQuery(final StorageConnector connector) throws Exception {
- try (SQLStore store = new SQLStore(null, connector, ResourceDefinition.query("MyQuery",
+ try (SQLStore store = new SQLStore(null, connector, ResourceDefinition.query("LargeCities",
"SELECT * FROM " + SCHEMA + ".\"Cities\" WHERE \"population\" >= 1000000")))
{
- final FeatureSet cities = store.findResource("MyQuery");
+ final FeatureSet cities = store.findResource("LargeCities");
final Map<String,Integer> countryCount = new HashMap<>();
try (Stream<Feature> features = cities.features(false)) {
features.forEach((f) -> verifyContent(f, countryCount, false));
@@ -386,4 +428,101 @@ public final strictfp class SQLStoreTest extends TestCase {
assertTrue(countryCount.isEmpty());
}
}
+
+ /**
+ * Tests a user-supplied query followed by another query built from filters.
+ */
+ private void verifyNestedSQLQuery(final StorageConnector connector) throws Exception {
+ try (SQLStore store = new SQLStore(null, connector, ResourceDefinition.query("MyParks",
+ "SELECT * FROM " + SCHEMA + ".\"Parks\"")))
+ {
+ final FeatureSet parks = store.findResource("MyParks");
+ /*
+ * Add a filter for parks in France.
+ */
+ final FeatureQuery query = new FeatureQuery();
+ query.setSortBy(FF.sort(FF.property("native_name"), SortOrder.DESCENDING));
+ query.setSelection(FF.equal(FF.property("country"), FF.literal("FRA")));
+ query.setProjection(new FeatureQuery.NamedExpression(FF.property("native_name")));
+ final FeatureSet frenchParks = parks.subset(query);
+ /*
+ * Verify the feature type.
+ */
+ final PropertyType property = TestUtilities.getSingleton(frenchParks.getType().getProperties(true));
+ assertEquals("native_name", property.getName().toString());
+ assertEquals(String.class, ((AttributeType<?>) property).getValueClass());
+ /*
+ * Verify the values.
+ */
+ final Object[] result;
+ try (Stream<Feature> fs = frenchParks.features(false)) {
+ result = fs.map(f -> f.getPropertyValue("native_name")).toArray();
+ }
+ assertArrayEquals(new String[] {"Jardin du Luxembourg", "Jardin des Tuileries"}, result);
+ }
+ }
+
+ /**
+ * Tests a query having limit, offset, filtering of columns and label usage.
+ * When user provides an offset, stream {@linkplain Stream#skip(long) skip operator} should not override it,
+ * but stack on it (i.e. the feature set provide user defined result, and the stream navigate through it).
+ */
+ private void verifyLimitOffsetAndColumnSelectionFromQuery(final StorageConnector connector) throws Exception {
+ try (SQLStore store = new SQLStore(null, connector, ResourceDefinition.query("MyQuery",
+ "SELECT \"english_name\" AS \"title\" " +
+ "FROM " + SCHEMA + ".\"Parks\"\n" + // Test that multiline text is accepted.
+ "ORDER BY \"english_name\" ASC " +
+ "OFFSET 2 ROWS FETCH NEXT 3 ROWS ONLY")))
+ {
+ final FeatureSet parks = store.findResource("MyQuery");
+ final FeatureType type = parks.getType();
+ final AttributeType<?> property = (AttributeType<?>) TestUtilities.getSingleton(type.getProperties(true));
+ assertEquals("Property name should be label defined in query", "title", property.getName().toString());
+ assertEquals("Attribute should be a string", String.class, property.getValueClass());
+ assertEquals("Column should be nullable.", 0, property.getMinimumOccurs());
+ final Integer precision = AttributeConvention.getMaximalLengthCharacteristic(type, property);
+ assertEquals("Column length constraint should be visible from attribute type.", Integer.valueOf(20), precision);
+ /*
+ * Get third row in the table, as query starts on second one, and we want to skip one entry from there.
+ * Tries to increase limit. The test will ensure it's not possible.
+ */
+ assertArrayEquals(
+ "Should get fourth and fifth park names from ascending order",
+ new String[] {"Tuileries Garden", "Yoyogi-kōen"},
+ getTitles(parks, 1, 4));
+ /*
+ * Get first row only.
+ */
+ assertArrayEquals("Only second third name should be returned",
+ new String[] {"Shinjuku Gyoen"},
+ getTitles(parks, 0, 1));
+ }
+ }
+
+ /**
+ * Applies an offset and limit on the given feature set,
+ * then returns the values of the "title" property of all features.
+ */
+ private static String[] getTitles(final FeatureSet parks, final long skip, final long limit) throws DataStoreException {
+ try (Stream<Feature> in = parks.features(false).skip(skip).limit(limit)) {
+ return in.map(f -> f.getPropertyValue("title").toString()).toArray(String[]::new);
+ }
+ }
+
+ /**
+ * Tests a query with a call to {@link Stream#distinct()} on the stream.
+ */
+ private void verifyDistinctQuery(final StorageConnector connector) throws Exception {
+ final Object[] expected;
+ try (SQLStore store = new SQLStore(null, connector, ResourceDefinition.query("Countries",
+ "SELECT \"country\" FROM " + SCHEMA + ".\"Parks\" ORDER BY \"country\"")))
+ {
+ final FeatureSet countries = store.findResource("Countries");
+ try (Stream<Feature> features = countries.features(false).distinct()) {
+ expected = features.map(f -> f.getPropertyValue("country")).toArray();
+ }
+ }
+ assertArrayEquals("Distinct country names, sorted in ascending order",
+ new String[] {"CAN", "FRA", "JPN"}, expected);
+ }
}
[sis] 01/02: Support "export" foreigner keys on queries as we did
for tables.
Posted by de...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
desruisseaux pushed a commit to branch geoapi-4.0
in repository https://gitbox.apache.org/repos/asf/sis.git
commit 957d7b0832878b94d307a14d35d01a41169bbe0d
Author: Martin Desruisseaux <ma...@geomatys.com>
AuthorDate: Mon Sep 27 10:50:44 2021 +0200
Support "export" foreigner keys on queries as we did for tables.
---
.../sis/internal/sql/feature/FeatureAnalyzer.java | 30 +++++++-
.../sis/internal/sql/feature/QueryAnalyzer.java | 82 +++++++++++-----------
.../sis/internal/sql/feature/TableAnalyzer.java | 42 -----------
.../org/apache/sis/storage/sql/SQLStoreTest.java | 38 +++++-----
4 files changed, 87 insertions(+), 105 deletions(-)
diff --git a/storage/sis-sqlstore/src/main/java/org/apache/sis/internal/sql/feature/FeatureAnalyzer.java b/storage/sis-sqlstore/src/main/java/org/apache/sis/internal/sql/feature/FeatureAnalyzer.java
index 19b8e3b..5ecd631 100644
--- a/storage/sis-sqlstore/src/main/java/org/apache/sis/internal/sql/feature/FeatureAnalyzer.java
+++ b/storage/sis-sqlstore/src/main/java/org/apache/sis/internal/sql/feature/FeatureAnalyzer.java
@@ -297,14 +297,38 @@ abstract class FeatureAnalyzer {
* @throws DataStoreException if a logical error occurred while analyzing the relations.
* @throws Exception for WKB parsing error or other kinds of errors.
*/
- PrimaryKey createAssociations(Relation[] exportedKeys) throws Exception {
+ final PrimaryKey createAssociations(Relation[] exportedKeys) throws Exception {
if (primaryKey.size() > 1) {
if (!primaryKeyNullable) {
primaryKeyClass = Numbers.wrapperToPrimitive(primaryKeyClass);
}
primaryKeyClass = Classes.changeArrayDimension(primaryKeyClass, 1);
}
- return PrimaryKey.create(primaryKeyClass, primaryKey);
+ final PrimaryKey pk = PrimaryKey.create(primaryKeyClass, primaryKey);
+ int count = 0;
+ for (final Relation dependency : exportedKeys) {
+ if (dependency != null) {
+ final GenericName typeName = dependency.getName(analyzer);
+ String propertyName = toHeuristicLabel(typeName.tip().toString());
+ final String base = propertyName;
+ while (feature.isNameUsed(propertyName)) {
+ propertyName = base + '-' + ++count;
+ }
+ dependency.propertyName = propertyName;
+ final Table table = analyzer.table(dependency, typeName, null); // `null` because exported, not imported.
+ final AssociationRoleBuilder association;
+ if (table != null) {
+ dependency.setSearchTable(analyzer, table, pk, Relation.Direction.EXPORT);
+ association = feature.addAssociation(table.featureType);
+ } else {
+ association = feature.addAssociation(typeName); // May happen in case of cyclic dependency.
+ }
+ association.setName(propertyName)
+ .setMinimumOccurs(0)
+ .setMaximumOccurs(Integer.MAX_VALUE);
+ }
+ }
+ return pk;
}
/**
@@ -330,7 +354,7 @@ abstract class FeatureAnalyzer {
* @param propertyName name of the property to rewrite.
* @return proposed human-readable property name.
*/
- final String toHeuristicLabel(String propertyName) {
+ private String toHeuristicLabel(String propertyName) {
if (countLowerCaseStarts > 0) {
final CharSequence words = CharSequences.camelCaseToWords(propertyName, true);
final int first = Character.codePointAt(words, 0);
diff --git a/storage/sis-sqlstore/src/main/java/org/apache/sis/internal/sql/feature/QueryAnalyzer.java b/storage/sis-sqlstore/src/main/java/org/apache/sis/internal/sql/feature/QueryAnalyzer.java
index edb3c1e..475a578 100644
--- a/storage/sis-sqlstore/src/main/java/org/apache/sis/internal/sql/feature/QueryAnalyzer.java
+++ b/storage/sis-sqlstore/src/main/java/org/apache/sis/internal/sql/feature/QueryAnalyzer.java
@@ -108,53 +108,53 @@ final class QueryAnalyzer extends FeatureAnalyzer {
*/
@Override
Relation[] getForeignerKeys(final Relation.Direction direction) throws SQLException, DataStoreException {
- if (Relation.Direction.IMPORT.equals(direction)) {
- List<String> primaryKeyColumns = new ArrayList<>();
- final List<Relation> relations = new ArrayList<>();
- for (final Map.Entry<TableReference, Map<String,Column>> entry : columnsPerTable.entrySet()) {
- final Set<String> columnNames = entry.getValue().keySet();
- final TableReference src = entry.getKey();
- /*
- * Search for foreigner keys in the table where the query columns come from.
- * Foreigner keys can be handled as such only if all required columns are in the query.
- * Otherwise we will handle those columns as ordinary attributes.
- */
- try (ResultSet reflect = analyzer.metadata.getImportedKeys(src.catalog, src.schema, src.table)) {
- if (reflect.next()) do {
- final Relation relation = new Relation(analyzer, direction, reflect);
- if (columnNames.containsAll(relation.getForeignerKeys())) {
+ final boolean isImport = (direction == Relation.Direction.IMPORT);
+ List<String> primaryKeyColumns = isImport ? new ArrayList<>() : null;
+ final List<Relation> relations = new ArrayList<>();
+ for (final Map.Entry<TableReference, Map<String,Column>> entry : columnsPerTable.entrySet()) {
+ final Set<String> columnNames = entry.getValue().keySet();
+ final TableReference src = entry.getKey();
+ /*
+ * Search for foreigner keys in the table where the query columns come from.
+ * Foreigner keys can be handled as such only if all required columns are in the query.
+ * Otherwise we will handle those columns as ordinary attributes.
+ */
+ try (ResultSet reflect = isImport ? analyzer.metadata.getImportedKeys(src.catalog, src.schema, src.table)
+ : analyzer.metadata.getExportedKeys(src.catalog, src.schema, src.table))
+ {
+ if (reflect.next()) do {
+ final Relation relation = new Relation(analyzer, direction, reflect);
+ if (columnNames.containsAll(relation.getForeignerKeys())) {
+ if (isImport) {
addForeignerKeys(relation);
- relations.add(relation);
- }
- } while (!reflect.isClosed());
- }
- /*
- * Opportunistically search for primary keys. They are not needed by this method,
- * but will be needed later by `createAttributes(…)` and other methods.
- * This is a "all or nothing" operations: if some primary key columns are missing
- * from the query, then we can not have primary key at all for this query.
- */
- if (primaryKeyColumns != null) {
- try (ResultSet reflect = analyzer.metadata.getPrimaryKeys(src.catalog, src.schema, src.table)) {
- while (reflect.next()) {
- primaryKeyColumns.add(analyzer.getUniqueString(reflect, Reflection.COLUMN_NAME));
- }
- if (columnNames.containsAll(primaryKeyColumns)) {
- primaryKey.addAll(primaryKeyColumns);
- primaryKeyColumns.clear();
- } else {
- primaryKey.clear();
- primaryKeyColumns = null; // Means to not search anymore.
}
+ relations.add(relation);
}
- }
+ } while (!reflect.isClosed());
}
- final int size = relations.size();
- if (size != 0) {
- return relations.toArray(new Relation[size]);
+ /*
+ * Opportunistically search for primary keys. They are not needed by this method,
+ * but will be needed later by `createAttributes(…)` and other methods.
+ * This is a "all or nothing" operations: if some primary key columns are missing
+ * from the query, then we can not have primary key at all for this query.
+ */
+ if (primaryKeyColumns != null) {
+ try (ResultSet reflect = analyzer.metadata.getPrimaryKeys(src.catalog, src.schema, src.table)) {
+ while (reflect.next()) {
+ primaryKeyColumns.add(analyzer.getUniqueString(reflect, Reflection.COLUMN_NAME));
+ }
+ if (columnNames.containsAll(primaryKeyColumns)) {
+ primaryKey.addAll(primaryKeyColumns);
+ primaryKeyColumns.clear();
+ } else {
+ primaryKey.clear();
+ primaryKeyColumns = null; // Means to not search anymore.
+ }
+ }
}
}
- return Relation.EMPTY;
+ final int size = relations.size();
+ return (size != 0) ? relations.toArray(new Relation[size]) : Relation.EMPTY;
}
/**
diff --git a/storage/sis-sqlstore/src/main/java/org/apache/sis/internal/sql/feature/TableAnalyzer.java b/storage/sis-sqlstore/src/main/java/org/apache/sis/internal/sql/feature/TableAnalyzer.java
index 38e7c56..736bb44 100644
--- a/storage/sis-sqlstore/src/main/java/org/apache/sis/internal/sql/feature/TableAnalyzer.java
+++ b/storage/sis-sqlstore/src/main/java/org/apache/sis/internal/sql/feature/TableAnalyzer.java
@@ -22,9 +22,7 @@ import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.sql.SQLException;
import java.sql.ResultSet;
-import org.opengis.util.GenericName;
import org.apache.sis.storage.DataStoreException;
-import org.apache.sis.feature.builder.AssociationRoleBuilder;
import org.apache.sis.internal.metadata.sql.Reflection;
import org.apache.sis.internal.metadata.sql.SQLUtilities;
import org.apache.sis.internal.util.Strings;
@@ -173,46 +171,6 @@ final class TableAnalyzer extends FeatureAnalyzer {
}
/**
- * Adds the associations created by other tables having foreigner keys to this table.
- * We infer the column name from the target type. We may have a name clash with other columns,
- * in which case an arbitrary name change is applied.
- *
- * <h4>Side effects</h4>
- * <p><b>Required by this method:</b> {@link #primaryKeyClass}.</p>
- * <p><b>Computed by this method:</b> none.</p>
- *
- * @eturn the components of the primary key, or {@code null} if there is no primary key.
- */
- @Override
- final PrimaryKey createAssociations(final Relation[] exportedKeys) throws Exception {
- final PrimaryKey pk = super.createAssociations(exportedKeys);
- int count = 0;
- for (final Relation dependency : exportedKeys) {
- if (dependency != null) {
- final GenericName typeName = dependency.getName(analyzer);
- String propertyName = toHeuristicLabel(typeName.tip().toString());
- final String base = propertyName;
- while (feature.isNameUsed(propertyName)) {
- propertyName = base + '-' + ++count;
- }
- dependency.propertyName = propertyName;
- final Table table = analyzer.table(dependency, typeName, null); // `null` because exported, not imported.
- final AssociationRoleBuilder association;
- if (table != null) {
- dependency.setSearchTable(analyzer, table, pk, Relation.Direction.EXPORT);
- association = feature.addAssociation(table.featureType);
- } else {
- association = feature.addAssociation(typeName); // May happen in case of cyclic dependency.
- }
- association.setName(propertyName)
- .setMinimumOccurs(0)
- .setMaximumOccurs(Integer.MAX_VALUE);
- }
- }
- return pk;
- }
-
- /**
* Returns an optional description of the application schema.
*/
@Override
diff --git a/storage/sis-sqlstore/src/test/java/org/apache/sis/storage/sql/SQLStoreTest.java b/storage/sis-sqlstore/src/test/java/org/apache/sis/storage/sql/SQLStoreTest.java
index 7e84d04..4e113fd 100644
--- a/storage/sis-sqlstore/src/test/java/org/apache/sis/storage/sql/SQLStoreTest.java
+++ b/storage/sis-sqlstore/src/test/java/org/apache/sis/storage/sql/SQLStoreTest.java
@@ -228,9 +228,9 @@ public final strictfp class SQLStoreTest extends TestCase {
*
* @param feature a feature returned by the stream.
* @param countryCount number of time that the each country has been seen while iterating over the cities.
- * @param hasExport whether the feature is expected to have associations for "export" foreigner keys.
+ * @param isTable {@code true} if the resource is from a table, or {@code false} if from a query.
*/
- private void verifyContent(final Feature feature, final Map<String,Integer> countryCount, final boolean hasExport) {
+ private void verifyContent(final Feature feature, final Map<String,Integer> countryCount, final boolean isTable) {
final String city = feature.getPropertyValue("native_name").toString();
final City c;
boolean isCanada = false;
@@ -266,23 +266,23 @@ public final strictfp class SQLStoreTest extends TestCase {
* Associations using Relation.Direction.EXPORT.
* Contrarily to the IMPORT case, those associations can contain many values.
*/
- if (hasExport) {
- final Collection<?> actualParks = (Collection<?>) feature.getPropertyValue("parks");
- assertNotNull("parks", actualParks);
- assertEquals("parks.length", c.parks.length, actualParks.size());
- final Collection<String> expectedParks = new HashSet<>(Arrays.asList(c.parks));
- for (final Object park : actualParks) {
- final Feature pf = (Feature) park;
- final String npn = (String) pf.getPropertyValue("native_name");
- final String epn = (String) pf.getPropertyValue("english_name");
- assertNotNull("park.native_name", npn);
- assertNotNull("park.english_name", epn);
- assertNotEquals("park.names", npn, epn);
- assertTrue("park.english_name", expectedParks.remove(epn));
- /*
- * Verify the reverse association form Parks to Cities.
- * This create a cyclic graph, but SQLStore is capable to handle it.
- */
+ final Collection<?> actualParks = (Collection<?>) feature.getPropertyValue("parks");
+ assertNotNull("parks", actualParks);
+ assertEquals("parks.length", c.parks.length, actualParks.size());
+ final Collection<String> expectedParks = new HashSet<>(Arrays.asList(c.parks));
+ for (final Object park : actualParks) {
+ final Feature pf = (Feature) park;
+ final String npn = (String) pf.getPropertyValue("native_name");
+ final String epn = (String) pf.getPropertyValue("english_name");
+ assertNotNull("park.native_name", npn);
+ assertNotNull("park.english_name", epn);
+ assertNotEquals("park.names", npn, epn);
+ assertTrue("park.english_name", expectedParks.remove(epn));
+ /*
+ * Verify the reverse association form Parks to Cities.
+ * This create a cyclic graph, but SQLStore is capable to handle it.
+ */
+ if (isTable) {
assertSame("City → Park → City", feature, pf.getPropertyValue("FK_City"));
}
}