Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,45 @@ builder.withTermCreator(new TermOperator("PHRASE"), (node, field, value) -> ...)
x PHRASE 'test phrase' || y == 'test'
```

### Column values (column-to-column comparison)

By default the right-hand side of a term must be a value (number, text, boolean or `null`).
Call `withColumnValues()` to also allow a column reference there:

```java
QueryCompiler<PrintQuery> compiler = QueryCompilerBuilder
.createDefault(PrintQuery.class, new PrintQueryCreator())
.withColumnValues()
.build();

compiler.compile(".a > .b && price lt .limit && 'my col' != .'other col'");
// ((.a > .b) && (price < .limit) && ('my col' != .'other col'))
```

* The right-hand column is written like any other column with a leading `.` prefix; quoted names are allowed
(`.'other col'`, `.a.'b c'`). A name without the prefix (`a > b`) is still a syntax error.
* It works with all term operators including custom operators registered with `withTermCreator`
(`.a like .b`) and can be combined with `and`, `or`, `xor`, `nor`, `!` and brackets.
* Regex terms (`~`) and `in` / `!in` lists do not support columns.
* Without `withColumnValues()` (the default) a column on the right-hand side is rejected with a syntax error,
exactly as before. `withColumnValues(false)` switches it off again.

Creators (`eq`, `ne`, `lt`, `le`, `gt`, `ge`, `text` and custom term creators) receive the column as a `Value` of type
`Value.Type.FIELD`:

```java
builder.withTermCreator(TermOperators.GT, (node, field, value) -> {
if (value.isField()) {
Field other = value.getField(); // built the same way as the field on the left-hand side
return compareColumns(field, other);
}
return compareWithValue(field, value);
});
```

`value.getString()` and `value.toString()` return the column name as it was written in the query (`.'other col'`).
`PrintQueryCreator` prints such values the same way, so printed queries can be parsed again.

### Print the query tree

Queries are first compiled to a `QueryTree` before the target object is created. The tree can be printed:
Expand Down
12 changes: 12 additions & 0 deletions src/main/antlr/dev/gruen/query/generated/Query.g4
Original file line number Diff line number Diff line change
Expand Up @@ -10,20 +10,30 @@ grammar Query;

@members {
Set<String> customOperators = new HashSet<>();
boolean columnValues = false;

public Set<String> getCustomOperators(){
return customOperators;
}
public boolean validOperator(String id){
return customOperators.contains(id);
}

public boolean isColumnValues(){
return columnValues;
}

public void setColumnValues(boolean columnValues){
this.columnValues = columnValues;
}
}

compilationUnit : (query|full_search) EOF ;

term :
NEGATE? OPEN_BRACKET term CLOSE_BRACKET |
variable term_operation value |
{columnValues}? variable term_operation column_value |
variable term_list_operation value_list |
regex_term
;
Expand All @@ -45,6 +55,8 @@ term;


value: (NUMBER | BOOLEAN_VALUE | TEXT_VALUE | NULL);
// column reference as right-hand value, only active if the parser flag columnValues is set
column_value: COLUMN;
variable: VAR | COLUMN | TEXT_VALUE;

term_operation: TERM_OPERATOR | custom_operator;
Expand Down
3 changes: 3 additions & 0 deletions src/main/java/dev/gruen/query/PrintQueryCreator.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ public static String value2string(Value value) {
if (value.isNull()) {
return null;
}
if (value.isField()) {
return value.getString();
}
return value.isString() ? String.format("'%s'", value) : value.toString();
}

Expand Down
26 changes: 25 additions & 1 deletion src/main/java/dev/gruen/query/compiler/QueryCompilerBuilder.java
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ public class QueryCompilerBuilder<T extends Query> {
private final Class<T> cl;
private final List<QueryOptimization> optimizations = new ArrayList<>();
private TermCreator<T> emptyCreator;
private boolean columnValues;

private QueryCompilerBuilder(Class<T> cl) {
this.cl = cl;
Expand Down Expand Up @@ -171,14 +172,37 @@ public QueryCompilerBuilder<T> withNOTCreator(LogicCreator<T> creator) {
return this;
}

/**
* Allows column references as right-hand value of a term, e.g. <code>.a &gt; .b</code> or
* <code>price lt .limit</code>. Creators receive such a value as {@link dev.gruen.query.term.Value.Type#FIELD}.
* Without this option a column on the right-hand side is a syntax error.
*
* @return <code>self</code> for method chaining
*/
public QueryCompilerBuilder<T> withColumnValues() {
return withColumnValues(true);
}

/**
* Enables or disables column references as right-hand value of a term, see {@link #withColumnValues()}.
* Disabled by default.
*
* @param enabled true to allow column references as values
* @return <code>self</code> for method chaining
*/
public QueryCompilerBuilder<T> withColumnValues(boolean enabled) {
this.columnValues = enabled;
return this;
}

/**
* Creates the query context used by the resulting compiler
*
* @return query context
*/
private QueryContext<T> createContext() {
return new QueryContext<>(
termCreators, logicCreators, emptyCreator, cl
termCreators, logicCreators, emptyCreator, cl, columnValues
);
}

Expand Down
20 changes: 20 additions & 0 deletions src/main/java/dev/gruen/query/compiler/QueryContext.java
Original file line number Diff line number Diff line change
Expand Up @@ -22,15 +22,25 @@ public class QueryContext<T extends Query> {
private final OperatorCreatorMap<LogicalOperator, LogicCreator<T>> logicCreators;
private final TermCreator<T> emptyCreator;
private final Class<T> cl;
private final boolean columnValues;

protected QueryContext(OperatorCreatorMap<TermOperator, TermCreator<T>> termCreators,
OperatorCreatorMap<LogicalOperator, LogicCreator<T>> logicCreators,
TermCreator<T> emptyCreator,
Class<T> cl) {
this(termCreators, logicCreators, emptyCreator, cl, false);
}

protected QueryContext(OperatorCreatorMap<TermOperator, TermCreator<T>> termCreators,
OperatorCreatorMap<LogicalOperator, LogicCreator<T>> logicCreators,
TermCreator<T> emptyCreator,
Class<T> cl,
boolean columnValues) {
this.emptyCreator = emptyCreator;
this.termCreators = termCreators;
this.logicCreators = logicCreators;
this.cl = cl;
this.columnValues = columnValues;
}

/**
Expand Down Expand Up @@ -101,4 +111,14 @@ public TermCreator<T> getEmptyCreator() {
public Class<T> getCl() {
return cl;
}

/**
* Returns true if column references are allowed as right-hand value of a term (<code>.a &gt; .b</code>).
* Values of such terms have the type {@link dev.gruen.query.term.Value.Type#FIELD}.
*
* @return true if column values are enabled
*/
public boolean isColumnValues() {
return columnValues;
}
}
2 changes: 2 additions & 0 deletions src/main/java/dev/gruen/query/compiler/QueryTreeCompiler.java
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,8 @@ public QueryTree compile(String queryString) {
}
}

parser.setColumnValues(context.isColumnValues());

//Don't print errors to stderr
parser.removeErrorListener(ConsoleErrorListener.INSTANCE);
parser.addErrorListener(errorListener);
Expand Down
4 changes: 3 additions & 1 deletion src/main/java/dev/gruen/query/compiler/TermVisitor.java
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,9 @@ else if (ctx.regex_term() != null) {
private QueryNode createFieldFilterNode(QueryParser.TermContext ctx) {
Field field = CompilerUtil.createField(ctx.variable());
String operation = ctx.term_operation().getText();
Value value = CompilerUtil.createValue(ctx.value());
Value value = ctx.column_value() != null
? CompilerUtil.createValue(ctx.column_value())
: CompilerUtil.createValue(ctx.value());
return createFieldFilterNode(field, value, operation);
}

Expand Down
31 changes: 31 additions & 0 deletions src/main/java/dev/gruen/query/term/Field.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@

import dev.gruen.query.util.StringUtil;

import java.util.Arrays;
import java.util.Objects;

/**
* Represents the field in a query term (field operator value)
*/
Expand Down Expand Up @@ -161,4 +164,32 @@ public String getJoinedPath(int from, int to) {
public String toString() {
return getJoinedPath();
}

/**
* Two fields are equal if their full path and path array are equal
*
* @param o other object
* @return true if equal
*/
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Field other = (Field) o;
return Objects.equals(fullPath, other.fullPath) && Arrays.equals(path, other.path);
}

/**
* Calculates the hashcode of this field, consistent with {@link #equals(Object)}
*
* @return hashcode
*/
@Override
public int hashCode() {
return 31 * Objects.hashCode(fullPath) + Arrays.hashCode(path);
}
}
Loading
Loading