From 8c781f64524e3e8351ad44e22ed7704251ed47b1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alexander=20Gr=C3=BCn?= Date: Mon, 26 Oct 2026 21:52:34 +0100 Subject: [PATCH] use query library --- CHANGELOG.md | 14 ++ README.md | 21 +- pom.xml | 32 +-- spotbugs-exclude.xml | 4 - .../gruen/dataframe/generated/Predicate.g4 | 102 --------- .../dataframe/filter/FilterPredicate.java | 3 +- .../filter/compile/BooleanFilterVisitor.java | 46 ---- .../compile/ColumnPredicateFilterVisitor.java | 67 ------ .../filter/compile/FieldFilterOperation.java | 70 ------ .../filter/compile/FieldFilterVisitor.java | 153 ------------- .../compile/FilterPredicateQueryCreator.java | 209 ++++++++++++++++++ .../compile/FilterPredicateVisitor.java | 84 ------- .../PredicateCompileErrorListener.java | 47 ---- .../filter/compile/PredicateCompiler.java | 38 ++-- .../filter/compile/PredicateOperation.java | 63 ------ .../filter/compile/RegexFilterVisitor.java | 55 ----- .../gruen/dataframe/ReadmeExamplesTest.java | 18 +- .../filter/PredicateValueReaderTest.java | 10 +- .../FilterPredicateQueryCreatorTest.java | 156 +++++++++++++ 19 files changed, 436 insertions(+), 756 deletions(-) delete mode 100644 src/main/antlr4/dev/gruen/dataframe/generated/Predicate.g4 delete mode 100644 src/main/java/dev/gruen/dataframe/filter/compile/BooleanFilterVisitor.java delete mode 100644 src/main/java/dev/gruen/dataframe/filter/compile/ColumnPredicateFilterVisitor.java delete mode 100644 src/main/java/dev/gruen/dataframe/filter/compile/FieldFilterOperation.java delete mode 100644 src/main/java/dev/gruen/dataframe/filter/compile/FieldFilterVisitor.java create mode 100644 src/main/java/dev/gruen/dataframe/filter/compile/FilterPredicateQueryCreator.java delete mode 100644 src/main/java/dev/gruen/dataframe/filter/compile/FilterPredicateVisitor.java delete mode 100644 src/main/java/dev/gruen/dataframe/filter/compile/PredicateCompileErrorListener.java delete mode 100644 src/main/java/dev/gruen/dataframe/filter/compile/PredicateOperation.java delete mode 100644 src/main/java/dev/gruen/dataframe/filter/compile/RegexFilterVisitor.java create mode 100644 src/test/java/dev/gruen/dataframe/filter/compile/FilterPredicateQueryCreatorTest.java diff --git a/CHANGELOG.md b/CHANGELOG.md index 808649d..a5ec787 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,20 @@ All notable changes to this project are documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). +## [0.8.1] + +### Breaking changes +- Filter queries (`DataFrame.select(String)`, `FilterPredicate.compile(String)`) are now parsed by the [query-compiler](https://github.com/nRo/query-compiler) library + (`dev.gruen:query-compiler`) instead of the built-in ANTLR grammar. The ANTLR grammar, the generated parser and the visitors were removed. + Changes in the query syntax: + - Logical operators have a precedence now: `AND` binds stronger than `XOR`, which binds stronger than `OR` / `NOR` (left-associative). Before, all logical operators were evaluated from left to right with equal precedence. Use brackets to keep the old evaluation order. + - Boolean column flags (`flag`, `!flag`) are no longer supported. Use `flag == true` / `flag == false`. + - A query that is a single word is parsed as full-text search, which is not supported by DataFrame, and raises a `PredicateCompilerException`. + - Decimal numbers with a comma (`1,5`) are no longer supported because `,` separates the values of `in (..)` lists. Use `1.5`. + +### Added +- Filter queries support `in (1, 2)`, `!in (1, 2)` and `*=` (contains) operators. + ## [0.8.0] ### Breaking changes diff --git a/README.md b/README.md index f08c476..7a4248a 100644 --- a/README.md +++ b/README.md @@ -2,8 +2,8 @@ An easy-to-use DataFrame Library for Java. -[![CI](https://github.com/nRo/DataFrame/actions/workflows/ci.yml/badge.svg)](https://github.com/nRo/DataFrame/actions/workflows/ci.yml) -[![codecov](https://codecov.io/gh/nRo/DataFrame/branch/master/graph/badge.svg)](https://codecov.io/gh/nRo/DataFrame) +[![CI](https://github.com/nRo/dataframe/actions/workflows/ci.yml/badge.svg)](https://github.com/nRo/dataframe/actions/workflows/ci.yml) +[![codecov](https://codecov.io/gh/nRo/dataframe/branch/master/graph/badge.svg)](https://codecov.io/gh/nRo/dataframe) [![Maven Central](https://img.shields.io/maven-central/v/dev.gruen/dataframe.svg?label=Maven%20Central)](https://central.sonatype.com/artifact/dev.gruen/dataframe) [![Javadocs](https://javadoc.io/badge2/dev.gruen/dataframe/javadoc.svg)](https://javadoc.io/doc/dev.gruen/dataframe) ![Java 21+](https://img.shields.io/badge/Java-21%2B-blue) @@ -41,7 +41,7 @@ To build the library from sources you need JDK 21+ and Maven 3.9+: 1) Clone github repository - $ git clone https://github.com/nRo/DataFrame.git + $ git clone https://github.com/nRo/dataframe.git 2) Change to the created folder and run `mvn verify` (compile, tests, coverage gate and SpotBugs). Use `mvn install` to install the library into your local repository. @@ -118,7 +118,7 @@ All examples are executed by `ReadmeExamplesTest` using the files in `src/test/r Select all users called Meier or Schmitt from Germany, group by age and add column that contains the number of users with the respective age. Then sort by age and print ```java -URL csvUrl = new URL("https://raw.githubusercontent.com/nRo/DataFrame/master/src/test/resources/users.csv"); +URL csvUrl = new URL("https://raw.githubusercontent.com/nRo/dataframe/master/src/test/resources/users.csv"); DataFrame users = DataFrame.load(csvUrl, FileFormat.CSV); @@ -138,7 +138,7 @@ users.select("(name == 'Schmitt' || name == 'Meier') && country == 'Germany'") Load a csv file, set a unique column as primary key and add an index for two other columns. Select rows using the previously created index, change the values in their NAME column and join them with the original DataFrame. ```java -URL csvUrl = new URL("https://raw.githubusercontent.com/nRo/DataFrame/master/src/test/resources/data_index.csv"); +URL csvUrl = new URL("https://raw.githubusercontent.com/nRo/dataframe/master/src/test/resources/data_index.csv"); DataFrame dataFrame = DataFrame.load(csvUrl, FileFormat.CSV); @@ -356,21 +356,24 @@ DataFrame foundUsers = users.select( ``` Create and compile predicates from strings \ +The queries are parsed by the [query-compiler](https://github.com/nRo/query-compiler) library. \ Available value comparison operations: \ -```==, !=, <, <=, >, >=, ~= (regex)``` \ +```==, !=, <, <=, >, >=, ~= (regex), *= (contains), LIKE, in (..), !in (..)``` \ Available predicate operations: \ -```&&, ||, NOR, XOR, !(predicate) (negates the predicate) ``` +```&&, ||, NOR, XOR, !(predicate) (negates the predicate) ``` \ +Operator precedence: ```AND``` binds stronger than ```XOR```, which binds stronger than ```OR``` / ```NOR```. Use brackets to group terms. ```java //find all users that are younger than 18 or older users with first_name == "Max" DataFrame foundUsers = users.select("(age > 18 && first_name == 'Max') OR (age < 18)"); //Boolean column filter +//Boolean columns must be compared explicitly, a single word is not a valid query //find all users that are older than 18 or the selected column is true -DataFrame foundUsers = users.select("(age > 18) OR selected"); +DataFrame foundUsers = users.select("(age > 18) OR selected == true"); //find all users the selected column is false -DataFrame notSelected = users.select("!selected"); +DataFrame notSelected = users.select("selected == false"); //compare tow columns //returns all rows where col1 equals col2 diff --git a/pom.xml b/pom.xml index cb1c8c4..b3d4065 100644 --- a/pom.xml +++ b/pom.xml @@ -6,20 +6,19 @@ dev.gruen dataframe - 0.8.0 + 0.8.1 UTF-8 21 - 4.13.2 2.0.17 5.14.4 true 0.74 0.70 - DataFrame + dataframe DataFrame Library for Java - https://github.com/nRo/DataFrame + https://github.com/nRo/dataframe MIT License @@ -27,8 +26,8 @@ - https://github.com/nRo/DataFrame - scm:git:https://github.com/nRo/DataFrame.git + https://github.com/nRo/dataframe + scm:git:https://github.com/nRo/dataframe.git HEAD @@ -41,9 +40,9 @@ - org.antlr - antlr4-runtime - ${antlr4.version} + dev.gruen + query-compiler + 0.5.1 org.slf4j @@ -134,21 +133,6 @@ - - org.antlr - antlr4-maven-plugin - ${antlr4.version} - - true - - - - - antlr4 - - - - maven-source-plugin 3.3.1 diff --git a/spotbugs-exclude.xml b/spotbugs-exclude.xml index 7383c97..43c3863 100644 --- a/spotbugs-exclude.xml +++ b/spotbugs-exclude.xml @@ -1,9 +1,5 @@ - - - - diff --git a/src/main/antlr4/dev/gruen/dataframe/generated/Predicate.g4 b/src/main/antlr4/dev/gruen/dataframe/generated/Predicate.g4 deleted file mode 100644 index b72b096..0000000 --- a/src/main/antlr4/dev/gruen/dataframe/generated/Predicate.g4 +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Copyright (c) 2019 Alexander Grün - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -grammar Predicate; - -/* - * Parser Rules - */ - -compilationUnit : predicate EOF ; - -field_filter : -NEGATE? OPEN_BRACKET field_filter CLOSE_BRACKET| -variable FIELD_OPERATION value| -column_predicate| -regex_filter| -boolean_filter -; - - -boolean_filter : -variable | (NEGATE variable); - -regex_filter : -variable MATCH REGEX; - -column_predicate : -COLUMN FIELD_OPERATION COLUMN; - -predicate: -NEGATE? OPEN_BRACKET predicate CLOSE_BRACKET | -OPEN_BRACKET predicate PREDICATE_OPERATION predicate CLOSE_BRACKET| -predicate PREDICATE_OPERATION predicate| -field_filter; - - -value: (NUMBER | BOOLEAN_VALUE | TEXT_VALUE | NULL); -variable: VAR | COLUMN; -/* - * Lexer Rules - */ -fragment DIGIT : [0-9]; -fragment COL_PREFIX : '.'; - -fragment CHAR : [a-zA-Z]; -fragment STRING : '\'' (~('\'')|'\\\'') * '\''|'"' (~('"')|'\\"')* '"'; - -fragment UNESCAPED_STRING :~('.'| ' '|')' | '(' | '!') ~('\''|' '|')' | '(')*; - -fragment EQ : ('EQ' | 'eq' | '=' | '=='); -fragment NE : ('NE' | 'ne' | '!='); -fragment LE : ('LE' | 'le' | '<='); -fragment LT : ('LT' | 'lt' | '<'); -fragment GE : ('GE' | 'ge' | '>='); -fragment GT : ('GT' | 'gt' | '>'); -fragment LIKE : ('LIKE' | 'like'); -REGEX : '/' (~('/') | '\\/')+ '/'; -MATCH : ('~=' | '~' ); - - -fragment AND : ('AND' | 'and' | '&' | '&&'); -fragment OR : ('OR' | 'or' | '|' | '||'); -fragment XOR : ('XOR' | 'xor') ; -fragment NOR : ('NOR' | 'nor') ; -fragment VAR_NAME : (UNESCAPED_STRING | STRING); - -OPEN_BRACKET: '('; -CLOSE_BRACKET: ')'; - -NEGATE: '!'; - -PREDICATE_OPERATION : AND | OR | XOR | NOR; - -FIELD_OPERATION : EQ | NE |LE | LT | GT | GE | LIKE; - -NUMBER : '-'? DIGIT+([.,]DIGIT+)?; -BOOLEAN_VALUE: 'true' | 'false'; -TEXT_VALUE : STRING; -NULL: 'null' | 'NULL' | 'NA' | 'na'; - -COLUMN : COL_PREFIX VAR_NAME; -VAR: VAR_NAME; -WHITESPACE : ' ' -> skip ; diff --git a/src/main/java/dev/gruen/dataframe/filter/FilterPredicate.java b/src/main/java/dev/gruen/dataframe/filter/FilterPredicate.java index 8b14fa5..9a75331 100644 --- a/src/main/java/dev/gruen/dataframe/filter/FilterPredicate.java +++ b/src/main/java/dev/gruen/dataframe/filter/FilterPredicate.java @@ -27,6 +27,7 @@ import dev.gruen.dataframe.DataFrameRuntimeException; import dev.gruen.dataframe.common.Row; import dev.gruen.dataframe.filter.compile.PredicateCompiler; +import dev.gruen.query.Query; import java.util.Arrays; import java.util.Collection; @@ -37,7 +38,7 @@ /** * Created by Alex on 09.03.2016. */ -public abstract class FilterPredicate { +public abstract class FilterPredicate implements Query { public static final FilterPredicate EMPTY_FILTER = empty(); diff --git a/src/main/java/dev/gruen/dataframe/filter/compile/BooleanFilterVisitor.java b/src/main/java/dev/gruen/dataframe/filter/compile/BooleanFilterVisitor.java deleted file mode 100644 index 59d7b55..0000000 --- a/src/main/java/dev/gruen/dataframe/filter/compile/BooleanFilterVisitor.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * - * * Copyright (c) 2019-2026 Alexander Grün - * * - * * Permission is hereby granted, free of charge, to any person obtaining a copy - * * of this software and associated documentation files (the "Software"), to deal - * * in the Software without restriction, including without limitation the rights - * * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * * copies of the Software, and to permit persons to whom the Software is - * * furnished to do so, subject to the following conditions: - * * - * * The above copyright notice and this permission notice shall be included in all - * * copies or substantial portions of the Software. - * * - * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * * SOFTWARE. - * - */ - -package dev.gruen.dataframe.filter.compile; - -import dev.gruen.dataframe.filter.FilterPredicate; -import dev.gruen.dataframe.generated.PredicateBaseVisitor; -import dev.gruen.dataframe.generated.PredicateParser; - -/** - * Created by Alex on 21.05.2017. - */ -public class BooleanFilterVisitor extends PredicateBaseVisitor { - - @Override - public FilterPredicate visitBoolean_filter(PredicateParser.Boolean_filterContext ctx) { - String colName = FieldFilterVisitor.getColname(ctx.variable().getText()); - if(ctx.NEGATE() != null){ - return FilterPredicate.eq(colName,false); - } - return FilterPredicate.eq(colName,true); - } - - -} diff --git a/src/main/java/dev/gruen/dataframe/filter/compile/ColumnPredicateFilterVisitor.java b/src/main/java/dev/gruen/dataframe/filter/compile/ColumnPredicateFilterVisitor.java deleted file mode 100644 index e3f6f05..0000000 --- a/src/main/java/dev/gruen/dataframe/filter/compile/ColumnPredicateFilterVisitor.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * - * * Copyright (c) 2019-2026 Alexander Grün - * * - * * Permission is hereby granted, free of charge, to any person obtaining a copy - * * of this software and associated documentation files (the "Software"), to deal - * * in the Software without restriction, including without limitation the rights - * * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * * copies of the Software, and to permit persons to whom the Software is - * * furnished to do so, subject to the following conditions: - * * - * * The above copyright notice and this permission notice shall be included in all - * * copies or substantial portions of the Software. - * * - * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * * SOFTWARE. - * - */ - -package dev.gruen.dataframe.filter.compile; - -import dev.gruen.dataframe.filter.FilterPredicate; -import dev.gruen.dataframe.generated.PredicateBaseVisitor; -import dev.gruen.dataframe.generated.PredicateParser; - -/** - * Created by Alex on 21.05.2017. - */ -public class ColumnPredicateFilterVisitor extends PredicateBaseVisitor { - - @Override - public FilterPredicate visitColumn_predicate(PredicateParser.Column_predicateContext ctx) { - String colNameA = FieldFilterVisitor.getColname(ctx.COLUMN(0).getText()); - String colNameB = FieldFilterVisitor.getColname(ctx.COLUMN(1).getText()); - return createColumnFieldFilter(colNameA,colNameB,ctx.FIELD_OPERATION().getText()); - } - - private static FilterPredicate createColumnFieldFilter(String colNameA, String colNameB, String operation) { - FieldFilterOperation fieldFilterOperation = FieldFilterOperation.find(operation); - - switch (fieldFilterOperation) { - case EQ: - return FilterPredicate.eqColumn(colNameA, colNameB); - case NE: - return FilterPredicate.neColumn(colNameA, colNameB); - case LE: - return FilterPredicate.leColumn(colNameA, colNameB); - case LT: - return FilterPredicate.ltColumn(colNameA, colNameB); - case GE: - return FilterPredicate.geColumn(colNameA, colNameB); - case GT: - return FilterPredicate.gtColumn(colNameA, colNameB); - default: - throw new PredicateCompilerException(String.format("unsupported filter operation '%s'", operation)); - - } - } - - - -} diff --git a/src/main/java/dev/gruen/dataframe/filter/compile/FieldFilterOperation.java b/src/main/java/dev/gruen/dataframe/filter/compile/FieldFilterOperation.java deleted file mode 100644 index 560297f..0000000 --- a/src/main/java/dev/gruen/dataframe/filter/compile/FieldFilterOperation.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * - * * Copyright (c) 2019-2026 Alexander Grün - * * - * * Permission is hereby granted, free of charge, to any person obtaining a copy - * * of this software and associated documentation files (the "Software"), to deal - * * in the Software without restriction, including without limitation the rights - * * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * * copies of the Software, and to permit persons to whom the Software is - * * furnished to do so, subject to the following conditions: - * * - * * The above copyright notice and this permission notice shall be included in all - * * copies or substantial portions of the Software. - * * - * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * * SOFTWARE. - * - */ - -package dev.gruen.dataframe.filter.compile; - -import java.util.HashMap; -import java.util.Map; - -/** - * Created by Alex on 21.05.2017. - */ -public enum FieldFilterOperation { - - EQ("EQ","eq","=","=="), - NE("NE","ne","!="), - LE("LE","le","<="), - LT("LT","lt","<"), - GE("GE","ge",">="), - GT("GT","Gt",">"), - LIKE("LIKE"); - private final String[] aliases; - - FieldFilterOperation(String... aliases){ - this.aliases = aliases; - } - - /** - * Getter for property 'aliases'. - * - * @return Value for property 'aliases'. - */ - public String[] getAliases() { - return aliases; - } - - - private final static Map ALIASES_MAP = new HashMap<>(); - static{ - for(FieldFilterOperation fieldOperation : values()){ - for(String alias : fieldOperation.aliases){ - ALIASES_MAP.put(alias,fieldOperation); - } - } - } - - public static FieldFilterOperation find(String alias){ - return ALIASES_MAP.get(alias); - } -} diff --git a/src/main/java/dev/gruen/dataframe/filter/compile/FieldFilterVisitor.java b/src/main/java/dev/gruen/dataframe/filter/compile/FieldFilterVisitor.java deleted file mode 100644 index c0087e2..0000000 --- a/src/main/java/dev/gruen/dataframe/filter/compile/FieldFilterVisitor.java +++ /dev/null @@ -1,153 +0,0 @@ -/* - * - * * Copyright (c) 2019-2026 Alexander Grün - * * - * * Permission is hereby granted, free of charge, to any person obtaining a copy - * * of this software and associated documentation files (the "Software"), to deal - * * in the Software without restriction, including without limitation the rights - * * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * * copies of the Software, and to permit persons to whom the Software is - * * furnished to do so, subject to the following conditions: - * * - * * The above copyright notice and this permission notice shall be included in all - * * copies or substantial portions of the Software. - * * - * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * * SOFTWARE. - * - */ - -package dev.gruen.dataframe.filter.compile; - -import dev.gruen.dataframe.Values; -import dev.gruen.dataframe.filter.FilterPredicate; -import dev.gruen.dataframe.generated.PredicateBaseVisitor; -import dev.gruen.dataframe.generated.PredicateParser; -import dev.gruen.dataframe.type.DataFrameTypeManager; - -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * Created by Alex on 21.05.2017. - */ -public class FieldFilterVisitor extends PredicateBaseVisitor { - private static final Pattern NUMBER_PATTERN = Pattern.compile("[0-9]+([.,][0-9]+)?"); - private static final Object NULL_RETURN_TYPE = Values.NA; - - @Override - public FilterPredicate visitField_filter(PredicateParser.Field_filterContext ctx) { - FilterPredicate result; - if(ctx.regex_filter() != null){ - RegexFilterVisitor regexFilterVisitor = new RegexFilterVisitor(); - result = regexFilterVisitor.visitRegex_filter(ctx.regex_filter()); - } - else if(ctx.column_predicate() != null){ - ColumnPredicateFilterVisitor columnPredicateFilterVisitor = new ColumnPredicateFilterVisitor(); - result = columnPredicateFilterVisitor.visitColumn_predicate(ctx.column_predicate()); - } - else if(ctx.boolean_filter() != null){ - BooleanFilterVisitor booleanFilterVisitor = new BooleanFilterVisitor(); - result = booleanFilterVisitor.visitBoolean_filter(ctx.boolean_filter()); - } - else{ - result = createFieldFilter(ctx); - } - if(ctx.NEGATE() != null){ - result = result.neg(); - } - return result; - } - - private static FilterPredicate createFieldFilter(PredicateParser.Field_filterContext ctx){ - String colName = getColname(ctx.variable().getText()); - String operation = ctx.FIELD_OPERATION().getText(); - Object value = getValue(ctx); - - return createFieldFilter(colName,value,operation); - } - - - private static FilterPredicate createFieldFilter(String colName, Object value, String operation) { - FieldFilterOperation fieldFilterOperation = FieldFilterOperation.find(operation); - - switch (fieldFilterOperation) { - case EQ: - return FilterPredicate.eq(colName, value); - case NE: - return FilterPredicate.ne(colName, value); - case LE: - return FilterPredicate.le(colName, value); - case LT: - return FilterPredicate.lt(colName, value); - case GE: - return FilterPredicate.ge(colName, value); - case GT: - return FilterPredicate.gt(colName, value); - case LIKE: - return FilterPredicate.like(colName, value); - default: throw new PredicateCompilerException(String.format("unsupported filter operation '%s'",operation)); - - } - } - public static String getColname(String text){ - String colName = text; - if(colName.startsWith(".")){ - colName = colName.substring(1); - } - if(colName.startsWith("'")){ - return colName.substring(1,colName.length() - 1); - } - return colName; - } - - - private static Object getValue(PredicateParser.Field_filterContext ctx) { - if (ctx.value().NULL() != null) { - return NULL_RETURN_TYPE; - } - if (ctx.value().NUMBER() != null) { - String n = ctx.value().NUMBER().getText(); - try { - if (n.contains(".")) { - return DataFrameTypeManager.get().parse(Double.class, n); - } else { - return DataFrameTypeManager.get().parse(Long.class, n); - } - } - catch (Exception e){ - throw new PredicateCompilerException(String.format("error parsing value '%s'",ctx.value().BOOLEAN_VALUE().getText())); - } - } - if(ctx.value().BOOLEAN_VALUE() != null){ - try{ - return DataFrameTypeManager.get().parse(Boolean.class, ctx.value().BOOLEAN_VALUE().getText()); - } - catch (Exception e){ - throw new PredicateCompilerException(String.format("error parsing value '%s'",ctx.value().BOOLEAN_VALUE().getText())); - } - } - String value = ctx.value().getText(); - if(value.startsWith("'")){ - return value.substring(1,value.length() - 1); - } - Matcher m = NUMBER_PATTERN.matcher(value); - if(m.matches()){ - String n = m.group(); - n = n.replace(",",""); - if(n.contains(".")){ - return Double.parseDouble(n); - } - else{ - return Long.parseLong(n); - } - } - return value; - } - -} diff --git a/src/main/java/dev/gruen/dataframe/filter/compile/FilterPredicateQueryCreator.java b/src/main/java/dev/gruen/dataframe/filter/compile/FilterPredicateQueryCreator.java new file mode 100644 index 0000000..2f564de --- /dev/null +++ b/src/main/java/dev/gruen/dataframe/filter/compile/FilterPredicateQueryCreator.java @@ -0,0 +1,209 @@ +/* + * + * * Copyright (c) 2019-2026 Alexander Grün + * * + * * Permission is hereby granted, free of charge, to any person obtaining a copy + * * of this software and associated documentation files (the "Software"), to deal + * * in the Software without restriction, including without limitation the rights + * * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * * copies of the Software, and to permit persons to whom the Software is + * * furnished to do so, subject to the following conditions: + * * + * * The above copyright notice and this permission notice shall be included in all + * * copies or substantial portions of the Software. + * * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * * SOFTWARE. + * + */ + +package dev.gruen.dataframe.filter.compile; + +import dev.gruen.dataframe.Values; +import dev.gruen.dataframe.filter.FilterPredicate; +import dev.gruen.query.QueryCreator; +import dev.gruen.query.QueryNode; +import dev.gruen.query.term.Field; +import dev.gruen.query.term.Value; + +import java.util.List; + +/** + * Creates {@link FilterPredicate}s from the terms parsed by the query compiler library. + */ +public class FilterPredicateQueryCreator implements QueryCreator { + + @Override + public FilterPredicate eq(QueryNode node, Field field, Value value) { + if (value.isField()) { + return FilterPredicate.eqColumn(columnName(field), columnName(value.getField())); + } + return FilterPredicate.eq(columnName(field), convert(value)); + } + + @Override + public FilterPredicate ne(QueryNode node, Field field, Value value) { + if (value.isField()) { + return FilterPredicate.neColumn(columnName(field), columnName(value.getField())); + } + return FilterPredicate.ne(columnName(field), convert(value)); + } + + @Override + public FilterPredicate lt(QueryNode node, Field field, Value value) { + if (value.isField()) { + return FilterPredicate.ltColumn(columnName(field), columnName(value.getField())); + } + return FilterPredicate.lt(columnName(field), convert(value)); + } + + @Override + public FilterPredicate le(QueryNode node, Field field, Value value) { + if (value.isField()) { + return FilterPredicate.leColumn(columnName(field), columnName(value.getField())); + } + return FilterPredicate.le(columnName(field), convert(value)); + } + + @Override + public FilterPredicate gt(QueryNode node, Field field, Value value) { + if (value.isField()) { + return FilterPredicate.gtColumn(columnName(field), columnName(value.getField())); + } + return FilterPredicate.gt(columnName(field), convert(value)); + } + + @Override + public FilterPredicate ge(QueryNode node, Field field, Value value) { + if (value.isField()) { + return FilterPredicate.geColumn(columnName(field), columnName(value.getField())); + } + return FilterPredicate.ge(columnName(field), convert(value)); + } + + /** + * Creates a LIKE predicate. Registered as custom term operator in {@link PredicateCompiler}. + * + * @param node query node + * @param field column + * @param value like pattern + * @return like predicate + */ + public FilterPredicate like(QueryNode node, Field field, Value value) { + if (!value.isString()) { + throw new PredicateCompilerException(String.format("LIKE requires a text value but was '%s'", value)); + } + return FilterPredicate.like(columnName(field), value.getString()); + } + + @Override + public FilterPredicate regex(QueryNode node, Field field, Value value) { + if (!value.isPattern()) { + throw new PredicateCompilerException(String.format("wrong pattern format: %s", value)); + } + return FilterPredicate.matches(columnName(field), value.getPattern()); + } + + @Override + public FilterPredicate text(QueryNode node, Field field, Value value) { + return FilterPredicate.like(columnName(field), "%" + value.getString() + "%"); + } + + @Override + public FilterPredicate in(QueryNode node, Field field, Value value) { + Object[] values = convertList(value); + String column = columnName(field); + FilterPredicate[] predicates = new FilterPredicate[values.length]; + for (int i = 0; i < values.length; i++) { + predicates[i] = FilterPredicate.eq(column, values[i]); + } + return FilterPredicate.or(predicates); + } + + @Override + public FilterPredicate notIn(QueryNode node, Field field, Value value) { + return FilterPredicate.not(in(node, field, value)); + } + + @Override + public FilterPredicate not(QueryNode node, FilterPredicate predicate) { + return FilterPredicate.not(predicate); + } + + @Override + public FilterPredicate and(QueryNode node, FilterPredicate[] predicates) { + return FilterPredicate.and(predicates); + } + + @Override + public FilterPredicate or(QueryNode node, FilterPredicate[] predicates) { + return FilterPredicate.or(predicates); + } + + @Override + public FilterPredicate xor(QueryNode node, FilterPredicate[] predicates) { + FilterPredicate result = predicates[0]; + for (int i = 1; i < predicates.length; i++) { + result = FilterPredicate.xor(result, predicates[i]); + } + return result; + } + + @Override + public FilterPredicate nor(QueryNode node, FilterPredicate[] predicates) { + FilterPredicate result = predicates[0]; + for (int i = 1; i < predicates.length; i++) { + result = FilterPredicate.nor(result, predicates[i]); + } + return result; + } + + @Override + public FilterPredicate fullSearch(Value value) { + throw new PredicateCompilerException(String.format( + "full-text search is not supported: '%s'. Use 'column == true' for boolean columns", value)); + } + + @Override + public FilterPredicate empty() { + return FilterPredicate.empty(); + } + + private static Object convert(Value value) { + if (value.isNull()) { + return Values.NA; + } + return value.getValue(); + } + + private static Object[] convertList(Value value) { + if (!value.isList()) { + return new Object[]{convert(value)}; + } + List values = value.getList(); + Object[] result = new Object[values.size()]; + for (int i = 0; i < result.length; i++) { + result[i] = convert(values.get(i)); + } + return result; + } + + static String columnName(Field field) { + String name = field.getFullPath(); + if (name.startsWith(".")) { + name = name.substring(1); + } + if (name.length() >= 2) { + char first = name.charAt(0); + if ((first == '\'' || first == '"') && name.charAt(name.length() - 1) == first) { + return name.substring(1, name.length() - 1); + } + } + return name; + } +} diff --git a/src/main/java/dev/gruen/dataframe/filter/compile/FilterPredicateVisitor.java b/src/main/java/dev/gruen/dataframe/filter/compile/FilterPredicateVisitor.java deleted file mode 100644 index 21fa426..0000000 --- a/src/main/java/dev/gruen/dataframe/filter/compile/FilterPredicateVisitor.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * - * * Copyright (c) 2019-2026 Alexander Grün - * * - * * Permission is hereby granted, free of charge, to any person obtaining a copy - * * of this software and associated documentation files (the "Software"), to deal - * * in the Software without restriction, including without limitation the rights - * * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * * copies of the Software, and to permit persons to whom the Software is - * * furnished to do so, subject to the following conditions: - * * - * * The above copyright notice and this permission notice shall be included in all - * * copies or substantial portions of the Software. - * * - * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * * SOFTWARE. - * - */ - -package dev.gruen.dataframe.filter.compile; - -import dev.gruen.dataframe.filter.FilterPredicate; -import dev.gruen.dataframe.generated.PredicateBaseVisitor; -import dev.gruen.dataframe.generated.PredicateParser; - -/** - * Created by Alex on 21.05.2017. - */ -public class FilterPredicateVisitor extends PredicateBaseVisitor { - - @Override - public FilterPredicate visitCompilationUnit(PredicateParser.CompilationUnitContext ctx) { - if(ctx.predicate() == null){ - throw new PredicateCompilerException("no predicate found"); - } - return visitPredicate(ctx.predicate()); - } - - @Override - public FilterPredicate visitPredicate(PredicateParser.PredicateContext ctx){ - if(ctx.field_filter() != null){ - FieldFilterVisitor fieldFilterVisitor = new FieldFilterVisitor(); - return fieldFilterVisitor.visitField_filter(ctx.field_filter()); - } - - if(ctx.predicate().size() == 1){ - FilterPredicateVisitor predicateVisitor = new FilterPredicateVisitor(); - FilterPredicate result = predicateVisitor.visit(ctx.predicate(0)); - if(ctx.NEGATE() != null){ - result = result.neg(); - } - return result; - } - - FilterPredicateVisitor predicateVisitorA = new FilterPredicateVisitor(); - FilterPredicateVisitor predicateVisitorB = new FilterPredicateVisitor(); - - FilterPredicate predicateA = predicateVisitorA.visitPredicate(ctx.predicate(0)); - FilterPredicate predicateB = predicateVisitorB.visitPredicate(ctx.predicate(1)); - FilterPredicate result = createPredicate(predicateA,predicateB,ctx.PREDICATE_OPERATION().getText()); - if(ctx.NEGATE() != null){ - result = result.neg(); - } - return result; - } - - - private static FilterPredicate createPredicate(FilterPredicate predicateA, FilterPredicate predicateB, String operation){ - PredicateOperation predicateOperation = PredicateOperation.find(operation); - - return switch (predicateOperation) { - case AND -> FilterPredicate.and(predicateA, predicateB); - case OR -> FilterPredicate.or(predicateA, predicateB); - case XOR -> FilterPredicate.xor(predicateA, predicateB); - case NOR -> FilterPredicate.nor(predicateA, predicateB); - default -> throw new PredicateCompilerException(String.format("unsupported predicate operation '%s'", operation)); - }; - } -} diff --git a/src/main/java/dev/gruen/dataframe/filter/compile/PredicateCompileErrorListener.java b/src/main/java/dev/gruen/dataframe/filter/compile/PredicateCompileErrorListener.java deleted file mode 100644 index 3fdf9b6..0000000 --- a/src/main/java/dev/gruen/dataframe/filter/compile/PredicateCompileErrorListener.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * - * * Copyright (c) 2019-2026 Alexander Grün - * * - * * Permission is hereby granted, free of charge, to any person obtaining a copy - * * of this software and associated documentation files (the "Software"), to deal - * * in the Software without restriction, including without limitation the rights - * * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * * copies of the Software, and to permit persons to whom the Software is - * * furnished to do so, subject to the following conditions: - * * - * * The above copyright notice and this permission notice shall be included in all - * * copies or substantial portions of the Software. - * * - * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * * SOFTWARE. - * - */ - -package dev.gruen.dataframe.filter.compile; - -import org.antlr.v4.runtime.BaseErrorListener; -import org.antlr.v4.runtime.RecognitionException; -import org.antlr.v4.runtime.Recognizer; - - -/** - * Created by Alex on 21.05.2017. - */ -public class PredicateCompileErrorListener extends BaseErrorListener { - private final String predicateString; - - public PredicateCompileErrorListener(String predicateString) { - this.predicateString = predicateString; - } - - @Override - public void syntaxError(Recognizer recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) { - throw new PredicateCompilerException(String.format("syntax error (%s : %s) line:%s, pos:%s ", msg, predicateString, line, charPositionInLine)); - } - -} diff --git a/src/main/java/dev/gruen/dataframe/filter/compile/PredicateCompiler.java b/src/main/java/dev/gruen/dataframe/filter/compile/PredicateCompiler.java index 9c052c4..afcde37 100644 --- a/src/main/java/dev/gruen/dataframe/filter/compile/PredicateCompiler.java +++ b/src/main/java/dev/gruen/dataframe/filter/compile/PredicateCompiler.java @@ -25,35 +25,37 @@ package dev.gruen.dataframe.filter.compile; import dev.gruen.dataframe.filter.FilterPredicate; -import dev.gruen.dataframe.generated.PredicateLexer; -import dev.gruen.dataframe.generated.PredicateParser; -import org.antlr.v4.runtime.CharStream; -import org.antlr.v4.runtime.CharStreams; -import org.antlr.v4.runtime.CommonTokenStream; -import org.antlr.v4.runtime.ConsoleErrorListener; +import dev.gruen.query.compiler.QueryCompiler; +import dev.gruen.query.compiler.QueryCompilerBuilder; +import dev.gruen.query.compiler.QueryCompilerException; +import dev.gruen.query.term.TermOperator; /** * Created by Alex on 18.05.2017. */ public class PredicateCompiler { + private static final TermOperator LIKE_OPERATOR = new TermOperator("LIKE", "like"); + + private static final QueryCompiler COMPILER = createCompiler(); + + private static QueryCompiler createCompiler() { + FilterPredicateQueryCreator creator = new FilterPredicateQueryCreator(); + return QueryCompilerBuilder.createDefault(FilterPredicate.class, creator) + .withColumnValues() + .withTermCreator(LIKE_OPERATOR, creator::like) + .build(); + } public static FilterPredicate compile(String predicateString){ predicateString = predicateString.trim(); if(predicateString.isEmpty()){ return FilterPredicate.empty(); } - PredicateCompileErrorListener errorListener = new PredicateCompileErrorListener(predicateString); - - CharStream stream = CharStreams.fromString(predicateString); - PredicateLexer lexer = new PredicateLexer(stream); - lexer.removeErrorListener(ConsoleErrorListener.INSTANCE); - lexer.addErrorListener(errorListener); - CommonTokenStream tokens = new CommonTokenStream(lexer); - PredicateParser parser = new PredicateParser(tokens); - parser.removeErrorListener(ConsoleErrorListener.INSTANCE); - parser.addErrorListener(errorListener); - FilterPredicateVisitor filterPredicateVisitor = new FilterPredicateVisitor(); - return filterPredicateVisitor.visit(parser.compilationUnit()); + try { + return COMPILER.compile(predicateString); + } catch (QueryCompilerException e) { + throw new PredicateCompilerException(e.getMessage(), e); + } } } diff --git a/src/main/java/dev/gruen/dataframe/filter/compile/PredicateOperation.java b/src/main/java/dev/gruen/dataframe/filter/compile/PredicateOperation.java deleted file mode 100644 index 9926ed7..0000000 --- a/src/main/java/dev/gruen/dataframe/filter/compile/PredicateOperation.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * - * * Copyright (c) 2019-2026 Alexander Grün - * * - * * Permission is hereby granted, free of charge, to any person obtaining a copy - * * of this software and associated documentation files (the "Software"), to deal - * * in the Software without restriction, including without limitation the rights - * * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * * copies of the Software, and to permit persons to whom the Software is - * * furnished to do so, subject to the following conditions: - * * - * * The above copyright notice and this permission notice shall be included in all - * * copies or substantial portions of the Software. - * * - * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * * SOFTWARE. - * - */ - -package dev.gruen.dataframe.filter.compile; - -import java.util.HashMap; -import java.util.Map; - -/** - * Created by Alex on 21.05.2017. - */ -public enum PredicateOperation { - AND("AND","and","&","&&"), - OR("OR","or","|","||"), - NOR("NOR","nor"), - XOR("XOR","xor"); - - private static final Map ALIASES_MAP = new HashMap<>(); - - private final String[] aliases; - - PredicateOperation(String... aliases){ - this.aliases = aliases; - } - - public String[] getAliases() { - return aliases; - } - - - static{ - for(PredicateOperation predicateOperation : values()){ - for(String alias : predicateOperation.aliases){ - ALIASES_MAP.put(alias,predicateOperation); - } - } - } - - public static PredicateOperation find(String alias){ - return ALIASES_MAP.get(alias); - } -} diff --git a/src/main/java/dev/gruen/dataframe/filter/compile/RegexFilterVisitor.java b/src/main/java/dev/gruen/dataframe/filter/compile/RegexFilterVisitor.java deleted file mode 100644 index 6d33bda..0000000 --- a/src/main/java/dev/gruen/dataframe/filter/compile/RegexFilterVisitor.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * - * * Copyright (c) 2019-2026 Alexander Grün - * * - * * Permission is hereby granted, free of charge, to any person obtaining a copy - * * of this software and associated documentation files (the "Software"), to deal - * * in the Software without restriction, including without limitation the rights - * * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * * copies of the Software, and to permit persons to whom the Software is - * * furnished to do so, subject to the following conditions: - * * - * * The above copyright notice and this permission notice shall be included in all - * * copies or substantial portions of the Software. - * * - * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * * SOFTWARE. - * - */ - -package dev.gruen.dataframe.filter.compile; - -import dev.gruen.dataframe.filter.FilterPredicate; -import dev.gruen.dataframe.generated.PredicateBaseVisitor; -import dev.gruen.dataframe.generated.PredicateParser; - -import java.util.regex.Pattern; - -/** - * Created by Alex on 21.05.2017. - */ -public class RegexFilterVisitor extends PredicateBaseVisitor { - - @Override - public FilterPredicate visitRegex_filter(PredicateParser.Regex_filterContext ctx) { - String colName = FieldFilterVisitor.getColname(ctx.variable().getText()); - return FilterPredicate.matches(colName,convertPattern(ctx.REGEX().getText())); - } - private static Pattern convertPattern(String text){ - String regex = text; - if(!regex.startsWith("/") || ! regex.endsWith("/")){ - throw new PredicateCompilerException(String.format("wrong pattern format: %s",text)); - } - regex = regex.substring(1,regex.length()-1); - return Pattern.compile(regex); - - } - - - -} diff --git a/src/test/java/dev/gruen/dataframe/ReadmeExamplesTest.java b/src/test/java/dev/gruen/dataframe/ReadmeExamplesTest.java index 6f5f97b..ee50098 100644 --- a/src/test/java/dev/gruen/dataframe/ReadmeExamplesTest.java +++ b/src/test/java/dev/gruen/dataframe/ReadmeExamplesTest.java @@ -5,6 +5,7 @@ import dev.gruen.dataframe.csv.CSVWriter; import dev.gruen.dataframe.csv.CSVWriterBuilder; import dev.gruen.dataframe.filter.FilterPredicate; +import dev.gruen.dataframe.filter.compile.PredicateCompilerException; import dev.gruen.dataframe.group.DataGroup; import dev.gruen.dataframe.group.DataGrouping; import dev.gruen.dataframe.group.aggr.Aggregate; @@ -153,15 +154,15 @@ public void testDataRows() { } DataRows rows = dataFrame.getRows(); - Assertions.assertEquals(24, rows.get(0).getInteger("age")); + Assertions.assertEquals(24, rows.getFirst().getInteger("age")); dataFrame.sort("name"); // the DataFrame was sorted after the DataRows were obtained: accessing the old rows throws - Assertions.assertThrows(RuntimeException.class, () -> rows.get(0).getInteger("age")); + Assertions.assertThrows(RuntimeException.class, () -> rows.getFirst().getInteger("age")); DataRows validRows = dataFrame.getRows(); - validRows.get(0).getInteger("age"); + validRows.getFirst().getInteger("age"); DataFrame independent = validRows.toDataFrame(); dataFrame.sort("age"); @@ -266,8 +267,9 @@ public void testBooleanColumnFilter() { DataFrame df = DataFrame.create().addStringColumn("name").addBooleanColumn("selected"); df.append("a", true); df.append("b", false); - Assertions.assertEquals(1, df.select("!selected").size()); - Assertions.assertEquals(2, df.select("(name == 'a') OR !selected").size()); + Assertions.assertEquals(1, df.select("selected == false").size()); + Assertions.assertEquals(2, df.select("(name == 'a') OR selected == false").size()); + Assertions.assertThrows(PredicateCompilerException.class, () -> df.select("!selected")); } @Test @@ -321,11 +323,11 @@ public void testGroupAggregation() { @Test public void testJoin() throws IOException { File a = new File(tempDir, "visits.csv"); - Files.write(a.toPath(), "person_id;visits\n1;5\n2;7\n".getBytes(StandardCharsets.UTF_8)); + Files.writeString(a.toPath(), "person_id;visits\n1;5\n2;7\n"); File b = new File(tempDir, "orders.csv"); - Files.write(b.toPath(), "customer_id;item\n1;book\n1;pen\n3;lamp\n".getBytes(StandardCharsets.UTF_8)); + Files.writeString(b.toPath(), "customer_id;item\n1;book\n1;pen\n3;lamp\n"); File u = new File(tempDir, "persons.csv"); - Files.write(u.toPath(), "person_id;name\n1;Max\n2;Eva\n".getBytes(StandardCharsets.UTF_8)); + Files.writeString(u.toPath(), "person_id;name\n1;Max\n2;Eva\n"); DataFrame users = DataFrame.fromCSV(u, ';', true); DataFrame visits = DataFrame.fromCSV(a, ';', true); diff --git a/src/test/java/dev/gruen/dataframe/filter/PredicateValueReaderTest.java b/src/test/java/dev/gruen/dataframe/filter/PredicateValueReaderTest.java index e045b89..4337f98 100644 --- a/src/test/java/dev/gruen/dataframe/filter/PredicateValueReaderTest.java +++ b/src/test/java/dev/gruen/dataframe/filter/PredicateValueReaderTest.java @@ -64,7 +64,7 @@ public void test() { Assertions.assertEquals(1, filtered.size()); Assertions.assertEquals("b", filtered.getRow(0).getString("name")); - filtered = dataFrame.select("(name != 'a' && z) OR (name != 'd' && !z)"); + filtered = dataFrame.select("(name != 'a' && z == true) OR (name != 'd' && z == false)"); Assertions.assertEquals(2, filtered.size()); Assertions.assertEquals("b", filtered.getRow(0).getString("name")); Assertions.assertEquals("c", filtered.getRow(1).getString("name")); @@ -125,14 +125,14 @@ public void test() { filtered = dataFrame.select("(.z == true) XOR (v == true)"); Assertions.assertEquals(2, filtered.size()); - DataFrame filtered2 = dataFrame.select(".z XOR v"); + DataFrame filtered2 = dataFrame.select(".z == true XOR v == true"); Assertions.assertEquals(2, filtered2.size()); Assertions.assertEquals(filtered, filtered2); filtered = dataFrame.select("(z == true) NOR (v == true)"); Assertions.assertEquals(1, filtered.size()); - filtered2 = dataFrame.select("z NOR v"); + filtered2 = dataFrame.select("z == true NOR v == true"); Assertions.assertEquals(1, filtered.size()); Assertions.assertEquals(filtered, filtered2); @@ -147,11 +147,11 @@ public void test() { Assertions.assertEquals("b", filtered.getRow(0).getString("name")); Assertions.assertEquals("c", filtered.getRow(1).getString("name")); - filtered = dataFrame.select(".z && .v"); + filtered = dataFrame.select(".z == true && .v == true"); Assertions.assertEquals(1, filtered.size()); Assertions.assertEquals("a", filtered.getRow(0).getString("name")); - filtered = dataFrame.select("z || v"); + filtered = dataFrame.select("z == true || v == true"); Assertions.assertEquals(3, filtered.size()); filtered = dataFrame.select("n == null"); diff --git a/src/test/java/dev/gruen/dataframe/filter/compile/FilterPredicateQueryCreatorTest.java b/src/test/java/dev/gruen/dataframe/filter/compile/FilterPredicateQueryCreatorTest.java new file mode 100644 index 0000000..b3e4868 --- /dev/null +++ b/src/test/java/dev/gruen/dataframe/filter/compile/FilterPredicateQueryCreatorTest.java @@ -0,0 +1,156 @@ +/* + * + * * Copyright (c) 2019-2026 Alexander Grün + * * + * * Permission is hereby granted, free of charge, to any person obtaining a copy + * * of this software and associated documentation files (the "Software"), to deal + * * in the Software without restriction, including without limitation the rights + * * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * * copies of the Software, and to permit persons to whom the Software is + * * furnished to do so, subject to the following conditions: + * * + * * The above copyright notice and this permission notice shall be included in all + * * copies or substantial portions of the Software. + * * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * * SOFTWARE. + * + */ + +package dev.gruen.dataframe.filter.compile; + +import dev.gruen.dataframe.DataFrame; +import dev.gruen.dataframe.DefaultDataFrame; +import dev.gruen.dataframe.column.BooleanColumn; +import dev.gruen.dataframe.column.IntegerColumn; +import dev.gruen.dataframe.column.StringColumn; +import dev.gruen.dataframe.filter.FilterPredicate; +import dev.gruen.query.term.Field; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +public class FilterPredicateQueryCreatorTest { + private DataFrame dataFrame; + + @BeforeEach + public void setUp() { + dataFrame = new DefaultDataFrame(); + dataFrame.addColumn(new StringColumn("name")); + dataFrame.addColumn(new IntegerColumn("x")); + dataFrame.addColumn(new IntegerColumn("y")); + dataFrame.addColumn(new IntegerColumn("my col")); + dataFrame.addColumn(new BooleanColumn("flag")); + dataFrame.append("abc", 1, 1, 5, true); + dataFrame.append("bcd", 2, 2, 1, false); + dataFrame.append("cde", 2, 1, 2, true); + dataFrame.append("def", 3, 4, 3, false); + } + + private String names(String query) { + DataFrame filtered = dataFrame.select(query); + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < filtered.size(); i++) { + sb.append(filtered.getRow(i).getString("name")); + } + return sb.toString(); + } + + @Test + public void testColumnName() { + Assertions.assertEquals("abc", FilterPredicateQueryCreator.columnName(new Field("abc"))); + Assertions.assertEquals("abc", FilterPredicateQueryCreator.columnName(new Field(".abc"))); + Assertions.assertEquals("a b", FilterPredicateQueryCreator.columnName(new Field(".'a b'"))); + Assertions.assertEquals("a b", FilterPredicateQueryCreator.columnName(new Field("'a b'"))); + Assertions.assertEquals("a b", FilterPredicateQueryCreator.columnName(new Field("\"a b\""))); + } + + @Test + public void testBlankIsEmpty() { + Assertions.assertEquals("", PredicateCompiler.compile(" ").toString()); + Assertions.assertEquals("abcbcdcdedef", names(" ")); + } + + @Test + public void testPrefixedColumn() { + Assertions.assertEquals("abc", names(".x == 1")); + Assertions.assertEquals("abc", names("x eq 1")); + Assertions.assertEquals("bcdcdedef", names("x != 1")); + } + + @Test + public void testColumnComparison() { + Assertions.assertEquals("abcbcd", names(".x == .y")); + Assertions.assertEquals("cde", names("x > .y")); + Assertions.assertEquals("def", names(".x < .y")); + Assertions.assertEquals("abcbcdcde", names("x >= .y && name != 'def'")); + } + + @Test + public void testQuotedColumns() { + Assertions.assertEquals("abc", names("'my col' > 4")); + Assertions.assertEquals("abc", names("'my col' > .x && x != 2")); + } + + @Test + public void testPrecedence() { + Assertions.assertEquals("abcbcd", names("x == 1 || x == 2 && y == 2")); + Assertions.assertEquals("bcd", names("(x == 1 || x == 2) && y == 2")); + } + + @Test + public void testLogicalOperators() { + Assertions.assertEquals("abcbcdcde", names("flag == true XOR x < 3 && y == 2")); + Assertions.assertEquals("bcddef", names("flag == true NOR x == 1")); + Assertions.assertEquals("bcddef", names("!(flag == true)")); + } + + @Test + public void testInAndText() { + Assertions.assertEquals("abcdef", names("x in (1, 3)")); + Assertions.assertEquals("bcdcde", names("x !in (1, 3)")); + Assertions.assertEquals("abcbcd", names("name *= 'bc'")); + } + + @Test + public void testLikeAndRegex() { + Assertions.assertEquals("abc", names("name LIKE 'a%'")); + Assertions.assertEquals("bcdcde", names("name ~= /[b-d]{2}.*/ && name != 'abc'")); + } + + @Test + public void testNull() { + dataFrame.append("ghi", null, 1, 1, null); + Assertions.assertEquals("ghi", names("x == null")); + } + + @Test + public void testFlagIsNotSupported() { + Assertions.assertThrows(PredicateCompilerException.class, () -> PredicateCompiler.compile("flag")); + Assertions.assertThrows(PredicateCompilerException.class, () -> PredicateCompiler.compile("!flag")); + Assertions.assertThrows(PredicateCompilerException.class, () -> PredicateCompiler.compile("x == 1 && flag")); + } + + @Test + public void testCommaDecimalIsNotSupported() { + Assertions.assertThrows(PredicateCompilerException.class, () -> PredicateCompiler.compile("x > 1,5")); + } + + @Test + public void testSyntaxError() { + PredicateCompilerException e = Assertions.assertThrows(PredicateCompilerException.class, + () -> PredicateCompiler.compile("x == ")); + Assertions.assertNotNull(e.getMessage()); + } + + @Test + public void testFilterPredicateCompile() { + FilterPredicate predicate = FilterPredicate.compile("x == 2 && y == 1"); + Assertions.assertEquals(1, dataFrame.select(predicate).size()); + } +}