Class FilterToSQL
- All Implemented Interfaces:
ExpressionVisitor
,FilterVisitor
- Direct Known Subclasses:
DuckDBFilterToSQL
,H2FilterToSQL
,H2GISFilterToSQL
,InformixFilterToSQL
,MySQLFilterToSQL
,NestedFilterToSQL
,PostgisFilterToSQL
,PreparedFilterToSQL
,SingleStoreFilterToSQL
,SQLServerFilterToSQL
createFilterCapabilities()
method.
The output Writer can be provided either through the constructor, or with a setWriter(Writer)
. It must be
provided before a call to encode.
Note that the class isn't thread-safe and a new object should be created for each call to any of the encode functions.
- Author:
- originally by Chris Holmes, TOPP, ported by Saul Farber, MassGIS
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic interface
Interface for customizing the encoding of Fields, irrespective of which subclass of FilterToSQL we are using. -
Field Summary
FieldsModifier and TypeFieldDescriptionprotected FilterCapabilities
The filter types that this class can encodeprotected Integer
The dimension corresponding to the current binary spatial filter being encodedprotected GeometryDescriptor
the geometry descriptor corresponding to the current binary spatial filter being encodedprotected Integer
the srid corresponding to the current binary spatial filter being encodedprotected String
The schema that contains the table the filter being encoded against.protected boolean
flag which indicates that the encoder is currently encoding a functionprotected boolean
Whether to escape backslash characters in string literalsprotected SimpleFeatureType
the schmema the encoder will be used to be encode sql forprotected FilterToSQL.FieldEncoder
Current field encoderprotected static FilterFactory
filter factoryprotected boolean
Whether the encoder should try to encode "in" function into a SQL IN operatorprotected boolean
inline flag, controlling whether "WHERE" will prefix the SQL encoded filterprotected static final String
error message for exceptionsprotected static Logger
Standard java loggerprotected Writer
where to write the constructed string from visiting the filters.protected PrimaryKey
The primary key corresponding to the table the filter is being encoded against.protected String
Character used to escape database schema, table and column names -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionprotected String
Gives the opportunity to subclasses to force the property to the desired type.protected FilterCapabilities
Sets the capabilities of this filter.void
encode
(Expression expression) Performs the encoding, sends the encoded sql to the writer passed in.void
Performs the encoding, sends the encoded sql to the writer passed in.protected void
encodeBinaryComparisonOperator
(BinaryComparisonOperator filter, Object extraData, Expression left, Expression right, Class leftContext, Class rightContext) Encode a BinaryComparisonOperator to SQLencodeToString
(Expression expression) purely a convenience method.encodeToString
(Filter filter) purely a convenience method.escapeLiteral
(String literal) Escapes the string literal.escapeName
(String name) Surrounds a name with the SQL escape string.evaluateLiteral
(Literal expression, Class<?> target) final FilterCapabilities
Describes the capabilities of this encoder.protected double
Rough evaluation of distance in the units of the current SRID, assuming that the SRID maps to a known EPSG code.getExpressionType
(Expression expression) Returns the expression type, if can be found, or null otherwise.Returns the feature type set in this encoder, if anyprotected String
getFunctionName
(Function function) Maps the function to the native database function nameprotected Class
protected Expression
getParameter
(Function function, int idx, boolean mandatory) Returns the n-th parameter of a function, throwing an exception if the parameter is not there and has been marked as mandatoryprotected boolean
boolean
boolean
Whether "in" like functions are encoded in SQL or notprotected void
processLikeLeftOperand
(Object extraData, boolean matchCase, Expression att, Class attributeType) void
setCapabilities
(FilterCapabilities capabilities) Sets the capabilities for the encoder.void
setDatabaseSchema
(String databaseSchema) void
setEscapeBackslash
(boolean escapeBackslash) void
setFeatureType
(SimpleFeatureType featureType) Sets the featuretype the encoder is encoding sql for.void
setFieldEncoder
(FilterToSQL.FieldEncoder fieldEncoder) Set custom field encodervoid
setInEncodingEnabled
(boolean inEncodingEnabled) Makes the encoder translate in like functions into SQL (see alsoInFunction.isInFunction(Expression)
void
setInline
(boolean inline) void
setPrimaryKey
(PrimaryKey primaryKey) void
setSqlNameEscape
(String escape) Sets the SQL name escape string.void
Sets the writer the encoder will write to.Write the SQL for an And filterprotected Object
visit
(BinaryLogicOperator filter, Object extraData) Common implementation for BinaryLogicOperator filters.visit
(ExcludeFilter filter, Object extraData) VisitFilter.EXCLUDE
(often used during data structure transformations).protected Object
visit
(BinaryExpression expression, String operator, Object extraData) Writes the SQL for the Math Expression.Writes sql for a function expression.Export the contents of a Literal Expresionvisit
(NilExpression expression, Object extraData) Used to visit a Expression.NIL, also called fornull
where an expression is expected.visit
(PropertyName expression, Object extraData) Writes the SQL for the attribute Expression.Encodes an Id filtervisit
(IncludeFilter filter, Object extraData) VisitFilter.INCLUDE
(often used during data structure transformations).visit
(NativeFilter filter, Object data) Write the SQL for a Not filterWrite the SQL for an Or filtervisit
(PropertyIsBetween filter, Object extraData) Writes the SQL for the PropertyIsBetween Filter.visit
(PropertyIsEqualTo filter, Object extraData) Write the SQL for this kind of filtervisit
(PropertyIsGreaterThanOrEqualTo filter, Object extraData) Write the SQL for this kind of filtervisit
(PropertyIsGreaterThan filter, Object extraData) Write the SQL for this kind of filtervisit
(PropertyIsLessThanOrEqualTo filter, Object extraData) Write the SQL for this kind of filtervisit
(PropertyIsLessThan filter, Object extraData) Write the SQL for this kind of filtervisit
(PropertyIsLike filter, Object extraData) Writes the SQL for the Like Filter.visit
(PropertyIsNil filter, Object extraData) visit
(PropertyIsNotEqualTo filter, Object extraData) Write the SQL for this kind of filtervisit
(PropertyIsNull filter, Object extraData) Writes the SQL for the Null Filter.visit
(Intersects filter, Object extraData) visit
(AnyInteracts anyInteracts, Object extraData) visit
(OverlappedBy overlappedBy, Object extraData) protected void
visitBinaryComparisonOperator
(BinaryComparisonOperator filter, Object extraData) Common implementation for BinaryComparisonOperator filters.protected Object
visitBinarySpatialOperator
(BinarySpatialOperator filter, Object extraData) protected Object
visitBinarySpatialOperator
(BinarySpatialOperator filter, Expression e1, Expression e2, Object extraData) Handles the more general case of two generic expressions.protected Object
visitBinarySpatialOperator
(BinarySpatialOperator filter, PropertyName property, Literal geometry, boolean swapped, Object extraData) Handles the common case of a PropertyName,Literal geometry binary spatial operator.protected Object
visitBinaryTemporalOperator
(BinaryTemporalOperator filter, Object extraData) protected Object
visitBinaryTemporalOperator
(BinaryTemporalOperator filter, Expression e1, Expression e2, Object extraData) Handles the general case of two expressions in a binary temporal filter.protected Object
visitBinaryTemporalOperator
(BinaryTemporalOperator filter, PropertyName property, Literal temporal, boolean swapped, Object extraData) Handles the common case of a PropertyName,Literal geometry binary temporal operator.protected void
visitInFunction
(Function function, boolean encodeAsExpression, boolean negate, Object extraData) Encodes a "in" function (as recognized byInFunction.isInFunction(Expression)
protected void
visitLiteralGeometry
(Literal expression) Subclasses must implement this method in order to encode geometry filters according to the specific database implementationprotected void
visitLiteralTimePeriod
(Period expression) visitNullFilter
(Object extraData) Encodes a null filter value.protected void
writeBinaryExpression
(Expression e, Class context) protected void
writeBinaryExpressionMember
(Expression exp, Class context) Writes out an expression, wrapping it in parenthesis if it's a binary oneprotected void
writeLiteral
(Object literal) Writes out a non null, non geometry literal.
-
Field Details
-
IO_ERROR
error message for exceptions- See Also:
-
filterFactory
filter factory -
capabilities
The filter types that this class can encode -
LOGGER
Standard java logger -
sqlNameEscape
Character used to escape database schema, table and column names -
out
where to write the constructed string from visiting the filters. -
The primary key corresponding to the table the filter is being encoded against.
-
databaseSchema
The schema that contains the table the filter being encoded against. -
featureType
the schmema the encoder will be used to be encode sql for -
encodingFunction
protected boolean encodingFunctionflag which indicates that the encoder is currently encoding a function -
currentGeometry
the geometry descriptor corresponding to the current binary spatial filter being encoded -
currentSRID
the srid corresponding to the current binary spatial filter being encoded -
currentDimension
The dimension corresponding to the current binary spatial filter being encoded -
inline
protected boolean inlineinline flag, controlling whether "WHERE" will prefix the SQL encoded filter -
inEncodingEnabled
protected boolean inEncodingEnabledWhether the encoder should try to encode "in" function into a SQL IN operator -
escapeBackslash
protected boolean escapeBackslashWhether to escape backslash characters in string literals -
fieldEncoder
Current field encoder
-
-
Constructor Details
-
FilterToSQL
public FilterToSQL()Default constructor -
FilterToSQL
-
-
Method Details
-
setWriter
Sets the writer the encoder will write to. -
setInline
public void setInline(boolean inline) -
isInEncodingEnabled
public boolean isInEncodingEnabled()Whether "in" like functions are encoded in SQL or not- Returns:
- a boolean value, true if the in linke functions are encoded
-
setInEncodingEnabled
public void setInEncodingEnabled(boolean inEncodingEnabled) Makes the encoder translate in like functions into SQL (see alsoInFunction.isInFunction(Expression)
- Parameters:
inEncodingEnabled
- the new flag controlling in encoding
-
isEscapeBackslash
public boolean isEscapeBackslash()- Returns:
- whether to escape backslash characters in string literals
-
setEscapeBackslash
public void setEscapeBackslash(boolean escapeBackslash) - Parameters:
escapeBackslash
- whether to escape backslash characters in string literals
-
encode
Performs the encoding, sends the encoded sql to the writer passed in.- Parameters:
filter
- the Filter to be encoded.- Throws:
FilterToSQLException
- If filter type not supported, or if there were io problems.
-
encodeToString
purely a convenience method.Equivalent to:
StringWriter out = new StringWriter(); new FilterToSQL(out).encode(filter); out.getBuffer().toString();
- Returns:
- a string representing the filter encoded to SQL.
- Throws:
FilterToSQLException
-
encode
Performs the encoding, sends the encoded sql to the writer passed in.- Parameters:
expression
- the Expression to be encoded.- Throws:
FilterToSQLException
- If filter type not supported, or if there were io problems.
-
encodeToString
purely a convenience method.Equivalent to:
StringWriter out = new StringWriter(); new FilterToSQL(out).encode(filter); out.getBuffer().toString();
- Returns:
- a string representing the filter encoded to SQL.
- Throws:
FilterToSQLException
-
setFeatureType
Sets the featuretype the encoder is encoding sql for.This is used for context for attribute expressions when encoding to sql.
-
getFeatureType
Returns the feature type set in this encoder, if any -
getPrimaryKey
-
setPrimaryKey
-
getDatabaseSchema
-
setDatabaseSchema
-
createFilterCapabilities
Sets the capabilities of this filter.- Returns:
- FilterCapabilities for this Filter
-
getCapabilities
Describes the capabilities of this encoder.Performs lazy creation of capabilities. If you're subclassing this class, override createFilterCapabilities to declare which filtercapabilities you support. Don't use this method.
- Returns:
- The capabilities supported by this encoder.
-
setCapabilities
Sets the capabilities for the encoder. -
visit
Description copied from interface:FilterVisitor
VisitFilter.EXCLUDE
(often used during data structure transformations).- Specified by:
visit
in interfaceFilterVisitor
- Parameters:
filter
- the filter to be visitedextraData
- Value object provided to visitor- Returns:
- subclass supplied
-
visit
Description copied from interface:FilterVisitor
VisitFilter.INCLUDE
(often used during data structure transformations).- Specified by:
visit
in interfaceFilterVisitor
- Parameters:
filter
- the filter to be visitedextraData
- Value object provided to visitor- Returns:
- subclass supplied
-
visit
Writes the SQL for the PropertyIsBetween Filter.- Specified by:
visit
in interfaceFilterVisitor
- Parameters:
filter
- the Filter to be visited.- Throws:
RuntimeException
- for io exception with writer
-
visit
Writes the SQL for the Like Filter. Assumes the current java implemented wildcards for the Like Filter: . for multi and .? for single. And replaces them with the SQL % and _, respectively.- Specified by:
visit
in interfaceFilterVisitor
- Parameters:
filter
- the Like Filter to be visited.- TODO:
- REVISIT: Need to think through the escape char, so it works right when Java uses one, and escapes correctly with an '_'.
-
processLikeLeftOperand
protected void processLikeLeftOperand(Object extraData, boolean matchCase, Expression att, Class attributeType) throws IOException - Throws:
IOException
-
visit
Write the SQL for an And filter- Specified by:
visit
in interfaceFilterVisitor
- Parameters:
filter
- the filter to visitextraData
- extra data (unused by this method)
-
visit
Write the SQL for a Not filter- Specified by:
visit
in interfaceFilterVisitor
- Parameters:
filter
- the filter to visitextraData
- extra data (unused by this method)
-
visit
Write the SQL for an Or filter- Specified by:
visit
in interfaceFilterVisitor
- Parameters:
filter
- the filter to visitextraData
- extra data (unused by this method)
-
visit
Common implementation for BinaryLogicOperator filters. This way they're all handled centrally.- Parameters:
filter
- the logic statement to be turned into SQL.extraData
- extra filter data. Not modified directly by this method.
-
visit
Write the SQL for this kind of filter- Specified by:
visit
in interfaceFilterVisitor
- Parameters:
filter
- the filter to visitextraData
- extra data (unused by this method)
-
visit
Write the SQL for this kind of filter- Specified by:
visit
in interfaceFilterVisitor
- Parameters:
filter
- the filter to visitextraData
- extra data (unused by this method)
-
visit
Write the SQL for this kind of filter- Specified by:
visit
in interfaceFilterVisitor
- Parameters:
filter
- the filter to visitextraData
- extra data (unused by this method)
-
visit
Write the SQL for this kind of filter- Specified by:
visit
in interfaceFilterVisitor
- Parameters:
filter
- the filter to visitextraData
- extra data (unused by this method)
-
visit
Write the SQL for this kind of filter- Specified by:
visit
in interfaceFilterVisitor
- Parameters:
filter
- the filter to visitextraData
- extra data (unused by this method)
-
visit
Write the SQL for this kind of filter- Specified by:
visit
in interfaceFilterVisitor
- Parameters:
filter
- the filter to visitextraData
- extra data (unused by this method)
-
visitBinaryComparisonOperator
protected void visitBinaryComparisonOperator(BinaryComparisonOperator filter, Object extraData) throws RuntimeException Common implementation for BinaryComparisonOperator filters. This way they're all handled centrally. DJB: note, postgis overwrites this implementation because of the way null is handled. This is forfilters and filters are handled. They will come here with "property = null". NOTE: SELECT * FROM WHERE
isnull; -- postgresql SELECT * FROM WHERE isnull(
); -- oracle??? - Parameters:
filter
- the comparison to be turned into SQL.- Throws:
RuntimeException
- for io exception with writer
encodeBinaryComparisonOperator
protected void encodeBinaryComparisonOperator(BinaryComparisonOperator filter, Object extraData, Expression left, Expression right, Class leftContext, Class rightContext) Encode a BinaryComparisonOperator to SQL- Parameters:
filter
- the comparison operator to be turned to SQLextraData
- extraDataleft
- left parameter of the binary operatorright
- right parameter of the binary operatorleftContext
- expression type of the right parameter used as context for the left parameterrightContext
- expression type of the left parameter used as context for the right parameter
writeBinaryExpressionMember
Writes out an expression, wrapping it in parenthesis if it's a binary one- Throws:
IOException
getExpressionType
Returns the expression type, if can be found, or null otherwise. Based on feature type inspection for attribute references, and function return types otherwise. Cannot yet handle arithmetics or literals (the latter are actually not useful and should be ignored, expression in geotools are free to use a string where a number is needed due to the on the fly conversion, here we are concerned only with types that are a reliable reference).- Returns:
- The expression return type, or null if cannot be computed
writeBinaryExpression
- Throws:
IOException
getFunctionReturnType
isBinaryExpression
visit
Writes the SQL for the Null Filter.- Specified by:
visit
in interfaceFilterVisitor
- Parameters:
filter
- the null filter to be written to SQL.- Throws:
RuntimeException
- for io exception with writer
visit
- Specified by:
visit
in interfaceFilterVisitor
visit
Encodes an Id filter- Specified by:
visit
in interfaceFilterVisitor
- Parameters:
filter
- the- Throws:
RuntimeException
- If there's a problem writing output
visit
- Specified by:
visit
in interfaceFilterVisitor
visit
- Specified by:
visit
in interfaceFilterVisitor
visit
- Specified by:
visit
in interfaceFilterVisitor
visit
- Specified by:
visit
in interfaceFilterVisitor
visit
- Specified by:
visit
in interfaceFilterVisitor
visit
- Specified by:
visit
in interfaceFilterVisitor
visit
- Specified by:
visit
in interfaceFilterVisitor
visit
- Specified by:
visit
in interfaceFilterVisitor
visit
- Specified by:
visit
in interfaceFilterVisitor
visit
- Specified by:
visit
in interfaceFilterVisitor
visit
- Specified by:
visit
in interfaceFilterVisitor
visitBinarySpatialOperator
visitBinarySpatialOperator
protected Object visitBinarySpatialOperator(BinarySpatialOperator filter, PropertyName property, Literal geometry, boolean swapped, Object extraData) Handles the common case of a PropertyName,Literal geometry binary spatial operator.visitBinarySpatialOperator
protected Object visitBinarySpatialOperator(BinarySpatialOperator filter, Expression e1, Expression e2, Object extraData) Handles the more general case of two generic expressions.The most common case is two PropertyName expressions, which happens during a spatial join.
visitBinaryTemporalOperator
visitBinaryTemporalOperator
protected Object visitBinaryTemporalOperator(BinaryTemporalOperator filter, PropertyName property, Literal temporal, boolean swapped, Object extraData) Handles the common case of a PropertyName,Literal geometry binary temporal operator.Subclasses should override if they support more temporal operators than what is handled in this base class.
visitBinaryTemporalOperator
protected Object visitBinaryTemporalOperator(BinaryTemporalOperator filter, Expression e1, Expression e2, Object extraData) Handles the general case of two expressions in a binary temporal filter.Subclasses should override if they support more temporal operators than what is handled in this base class.
visitNullFilter
Encodes a null filter value. The current implementation does exactly nothing.- Specified by:
visitNullFilter
in interfaceFilterVisitor
- Parameters:
extraData
- extra data to be used to evaluate the filter- Returns:
- the untouched extraData parameter
visit
Writes the SQL for the attribute Expression.- Specified by:
visit
in interfaceExpressionVisitor
- Parameters:
expression
- the attribute to turn to SQL.- Throws:
RuntimeException
- for io exception with writer
cast
Gives the opportunity to subclasses to force the property to the desired type. By default it simply writes out the property as-is (the property must be already escaped).- Throws:
IOException
visit
Export the contents of a Literal Expresion- Specified by:
visit
in interfaceExpressionVisitor
- Parameters:
expression
- the Literal to export- Throws:
RuntimeException
- for io exception with writer
evaluateLiteral
writeLiteral
Writes out a non null, non geometry literal. The base class properly handles null, numeric and booleans (true|false), and turns everything else into a string. Subclasses are expected to override this shall they need a different treatment (e.g. for dates)- Throws:
IOException
escapeLiteral
Escapes the string literal.visitLiteralGeometry
Subclasses must implement this method in order to encode geometry filters according to the specific database implementation- Throws:
IOException
visitLiteralTimePeriod
visit
- Specified by:
visit
in interfaceExpressionVisitor
visit
- Specified by:
visit
in interfaceExpressionVisitor
visit
- Specified by:
visit
in interfaceExpressionVisitor
visit
- Specified by:
visit
in interfaceExpressionVisitor
visit
protected Object visit(BinaryExpression expression, String operator, Object extraData) throws RuntimeException Writes the SQL for the Math Expression.- Parameters:
expression
- the Math phrase to be written.operator
- The operator of the expression.- Throws:
RuntimeException
- for io problems
visit
Writes sql for a function expression. By default it will write the call by using the same arguments provided to the GeoTools function, subclasses should override on a case by case basis if this behavior is not the desired one.- Specified by:
visit
in interfaceExpressionVisitor
- Parameters:
function
- a function expression- Throws:
RuntimeException
- If an IO error occurs.- See Also:
visitInFunction
protected void visitInFunction(Function function, boolean encodeAsExpression, boolean negate, Object extraData) Encodes a "in" function (as recognized byInFunction.isInFunction(Expression)
getParameter
Returns the n-th parameter of a function, throwing an exception if the parameter is not there and has been marked as mandatorygetFunctionName
Maps the function to the native database function namevisit
Description copied from interface:ExpressionVisitor
Used to visit a Expression.NIL, also called fornull
where an expression is expected.This is particularly useful when doing data transformations, as an example when using a StyleSymbolizer Expression.NIL can be used to represent the default stroke color.
- Specified by:
visit
in interfaceExpressionVisitor
- Returns:
- implementation specific
visit
- Specified by:
visit
in interfaceFilterVisitor
visit
- Specified by:
visit
in interfaceFilterVisitor
visit
- Specified by:
visit
in interfaceFilterVisitor
visit
- Specified by:
visit
in interfaceFilterVisitor
visit
- Specified by:
visit
in interfaceFilterVisitor
visit
- Specified by:
visit
in interfaceFilterVisitor
visit
- Specified by:
visit
in interfaceFilterVisitor
visit
- Specified by:
visit
in interfaceFilterVisitor
visit
- Specified by:
visit
in interfaceFilterVisitor
visit
- Specified by:
visit
in interfaceFilterVisitor
visit
- Specified by:
visit
in interfaceFilterVisitor
visit
- Specified by:
visit
in interfaceFilterVisitor
visit
- Specified by:
visit
in interfaceFilterVisitor
visit
- Specified by:
visit
in interfaceFilterVisitor
setSqlNameEscape
Sets the SQL name escape string.The value of this string is prefixed and appended to table schema names, table names and column names in an SQL statement to support mixed-case and non-English names. Without this, the DBMS may assume a mixed-case name in the query should be treated as upper-case and an SQLCODE of -204 or 206 may result if the name is not found.
Typically this is the double-quote character, ", but may not be for all databases.
If a name contains the escape string itself, the escape string is duplicated.
For example, consider the following query:
SELECT Geom FROM Spear.ArchSites May be interpreted by the database as: SELECT GEOM FROM SPEAR.ARCHSITES If the column and table names were actually created using mixed-case, the query needs to be specified as: SELECT "Geom" from "Spear"."ArchSites"
- Parameters:
escape
- the character to be used to escape database names
getSqlNameEscape
- Returns:
- the sqlNameEscape
escapeName
Surrounds a name with the SQL escape string.If the name contains the SQL escape string, the SQL escape string is duplicated.
setFieldEncoder
Set custom field encoder- Parameters:
fieldEncoder
- the field encoder
getDistanceInNativeUnits
Rough evaluation of distance in the units of the current SRID, assuming that the SRID maps to a known EPSG code. Will use a rather imprecise transformation for distances over degrees, but better than nothing.visit
- Specified by:
visit
in interfaceFilterVisitor
-