diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 0000000..bbd9e6f --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,53 @@ +name: Build + +on: + push: + branches: [ master, main ] + pull_request: + +permissions: + contents: read + +concurrency: + group: build-${{ github.ref }} + cancel-in-progress: true + +jobs: + build: + name: Build and test (JDK ${{ matrix.java }}) + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + java: [ 21, 25 ] + steps: + - uses: actions/checkout@v4 + + - name: Set up Temurin JDK ${{ matrix.java }} + uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: ${{ matrix.java }} + + - uses: gradle/actions/setup-gradle@v4 + + - name: Build and test + run: ./gradlew build + + - name: Build javadoc + run: ./gradlew javadoc + + - name: Upload test reports + if: failure() + uses: actions/upload-artifact@v4 + with: + name: test-reports-jdk${{ matrix.java }} + path: build/reports/tests + + - name: Upload coverage to Codecov + if: matrix.java == 21 + uses: codecov/codecov-action@v5 + with: + files: build/reports/jacoco/test/jacocoTestReport.xml + fail_ci_if_error: false + token: ${{ secrets.CODECOV_TOKEN }} diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..45dbe3b --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,42 @@ +name: Release + +on: + push: + tags: + - 'v*' + workflow_dispatch: + +permissions: + contents: read + +jobs: + publish: + name: Publish to Maven Central + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Set up Temurin JDK 21 + uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: 21 + + - uses: gradle/actions/setup-gradle@v4 + + - name: Determine version + run: | + if [[ "$GITHUB_REF_TYPE" == "tag" ]]; then + echo "VERSION=${GITHUB_REF_NAME#v}" >> "$GITHUB_ENV" + fi + + - name: Build and test + run: ./gradlew build + + - name: Deploy + run: ./gradlew publishToMavenCentral --no-configuration-cache + env: + ORG_GRADLE_PROJECT_mavenCentralUsername: ${{ secrets.CENTRAL_USERNAME }} + ORG_GRADLE_PROJECT_mavenCentralPassword: ${{ secrets.CENTRAL_PASSWORD }} + ORG_GRADLE_PROJECT_signingInMemoryKey: ${{ secrets.GPG_PRIVATE_KEY }} + ORG_GRADLE_PROJECT_signingInMemoryKeyPassword: ${{ secrets.GPG_PASSPHRASE }} diff --git a/.gitignore b/.gitignore index 8b804e5..ac499e3 100644 --- a/.gitignore +++ b/.gitignore @@ -1,94 +1,22 @@ -# Created by .ignore support plugin (hsz.mobi) -### Maven template -target/ -pom.xml.tag -pom.xml.releaseBackup -pom.xml.versionsBackup -pom.xml.next -release.properties -dependency-reduced-pom.xml -buildNumber.properties -.mvn/timing.properties - -# Avoid ignoring Maven wrapper jar file (.jar files are usually ignored) -!/.mvn/wrapper/maven-wrapper.jar -### JetBrains template -# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm -# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 - -# User-specific stuff: -.idea/**/workspace.xml -.idea/**/tasks.xml -.idea/dictionaries - -# Sensitive or high-churn files: -.idea/**/dataSources/ -.idea/**/dataSources.ids -.idea/**/dataSources.xml -.idea/**/dataSources.local.xml -.idea/**/sqlDataSources.xml -.idea/**/dynamic.xml -.idea/**/uiDesigner.xml - -# Gradle: -.idea/**/gradle.xml -.idea/**/libraries - -# CMake -cmake-build-debug/ - -# Mongo Explorer plugin: -.idea/**/mongoSettings.xml - -## File-based project format: +# Gradle +.gradle/ +build/ +!gradle/wrapper/gradle-wrapper.jar + +# IntelliJ IDEA +.idea/ +*.iml *.iws - -## Plugin-specific files: - -# IntelliJ out/ -# mpeltonen/sbt-idea plugin -.idea_modules/ - -# JIRA plugin -atlassian-ide-plugin.xml - -# Cursive Clojure plugin -.idea/replstate.xml - -# Crashlytics plugin (for Android Studio and IntelliJ) -com_crashlytics_export_strings.xml -crashlytics.properties -crashlytics-build.properties -fabric.properties -### Java template -# Compiled class file +# Compiled / logs *.class - -# Log file *.log - -# BlueJ files -*.ctxt - -# Mobile Tools for Java (J2ME) -.mtj.tmp/ - -# Package Files # -*.jar -*.war -*.ear -*.zip -*.tar.gz -*.rar - -# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml hs_err_pid* -target -.idea -querycompiler.iml +# Tools +.fastRequest/ -build -.gradle \ No newline at end of file +# OS +.DS_Store +Thumbs.db diff --git a/README.md b/README.md index 9afa387..524a3da 100644 --- a/README.md +++ b/README.md @@ -1,202 +1,136 @@ -# Simple Query Compiler -![travis](https://travis-ci.org/nRo/SimpleQueryCompiler.svg?branch=master) -[![codecov](https://codecov.io/gh/nRo/SimpleQueryCompiler/branch/master/graph/badge.svg)](https://codecov.io/gh/nRo/SimpleQueryCompiler) -[![Codacy Badge](https://api.codacy.com/project/badge/Grade/a03214f7198f4461ab341adecb75e0da)](https://www.codacy.com/app/nRo/DataFrame?utm_source=github.com&utm_medium=referral&utm_content=nRo/DataFrame&utm_campaign=Badge_Grade) +# Query Compiler -A Java library to compile and parse simple filter queries. +[![Build](https://github.com/nRo/query-compiler/actions/workflows/build.yml/badge.svg)](https://github.com/nRo/query-compiler/actions/workflows/build.yml) +[![codecov](https://codecov.io/gh/nRo/query-compiler/branch/master/graph/badge.svg)](https://codecov.io/gh/nRo/query-compiler) +[![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE.txt) + +A Java library that parses filter queries and turns them into any target object +(SQL, Elasticsearch queries, in-memory predicates, ...). +The grammar is built with [ANTLR 4](https://www.antlr.org/). -The following query formats can be parsed: ``` -// multiple terms with AND and OR operator -(x > 0 && !(y < 1 || z == 'test')) +String ──► ANTLR lexer/parser ──► QueryTree ──► optimizations ──► your creators ──► target object ``` + +Supported query formats: + ``` -//full text search +// terms combined with logical operators +(x > 0 && !(y < 1 || z == 'test')) + +// full text search "text search" test -example ``` -Default term operators: -``` -==, !=, <, <=, >, >=, text, regex -``` +Term operators: `==`, `!=`, `<`, `<=`, `>`, `>=`, `text`, `regex`, `in`, `!in` +Logical operators, from highest to lowest precedence: `AND` (`&`, `&&`), `XOR`, `OR` (`|`, `||`) and `NOR`. +Operators of the same level are grouped from left to right; use brackets to override: `(a || b) && c`. + +## Build + +Requires JDK 21 or newer. -Logical operators: ``` -AND, OR, XOR, NOR +git clone https://github.com/nRo/query-compiler.git +cd query-compiler +./gradlew build ``` -Build ------ -To build the library from sources: +The library is not published to a public repository yet. To use it in another project, run +`./gradlew publishToMavenLocal` and add: -1) Clone github repository +```kotlin +repositories { mavenLocal() } +dependencies { implementation("dev.gruen:query-compiler:0.0.1-SNAPSHOT") } +``` + +## Usage - $ git clone https://github.com/nRo/SimpleQueryCompiler.git +A `QueryCompiler` is built for a target type `T` (any class implementing `Query`). +You tell the builder how to create a `T` for each term operator (`==`, `>`, ...) and each logical operator +(`AND`, `OR`, ...). The compiler then turns query strings into `T` objects. -2) Change to the created folder and run `mvn install` +The following example compiles queries into a filter that is evaluated against a row of values +(the complete code is in [`ReadmeExampleTest`](src/test/java/dev/gruen/query/ReadmeExampleTest.java)): - $ cd SimpleQueryCompiler - - $ mvn install +```java +interface RowFilter extends Query { + boolean test(Map row); +} -3) Include it by adding the following to your project's `pom.xml`: +QueryCompiler compiler = QueryCompilerBuilder.create(RowFilter.class) + .withTermCreator(TermOperators.EQ, + (node, field, value) -> row -> row.containsKey(field.toString()) + && compare(row.get(field.toString()), value) == 0) + .withTermCreator(TermOperators.GT, + (node, field, value) -> row -> row.containsKey(field.toString()) + && compare(row.get(field.toString()), value) > 0) + .withANDCreator((node, children) -> row -> Arrays.stream(children).allMatch(c -> c.test(row))) + .withORCreator((node, children) -> row -> Arrays.stream(children).anyMatch(c -> c.test(row))) + .withOptimization(new RemoveRedundantBrackets()) + .build(); -```xml - -... - - de.alexgruen - querycompiler - 0.3-SNAPSHOT - -... - +RowFilter filter = compiler.compile("age > 18 && (country == 'DE' || country == 'AT')"); +filter.test(Map.of("age", 30, "country", "DE")); // true +filter.test(Map.of("age", 30, "country", "FR")); // false ``` -Usage ------ -This library works by defining by building a QueryCompiler for the desired output type. -Building a QueryCompiler requires the definition of Creators for the supported -term operators (==, !=, <, <=, ...) and logical operators (AND, OR,...). -The Creators are responsible to create the target object, for example SQL queries, elasticsearch queries,... +### Implement `QueryCreator` + +Instead of registering every operator separately, implement `QueryCreator`. It contains one method per operator +(`eq`, `ne`, `lt`, `le`, `gt`, `ge`, `regex`, `text`, `in`, `notIn`, `not`, `and`, `or`, `xor`, `nor`, +`fullSearch`, `empty`). +`PrintQueryCreator` is a ready-made implementation that turns a query back into a string: -There are two ways to create a QueryCompiler. -For the following examples be specify example ElasticSearchQuery as target class: ```java -public abstract class ElasticSearchQuery implements Query{ - //Every query must create an ElasticSearch QueryBuilder - public abstract QueryBuilder create(); - ... -} +QueryCompiler compiler = QueryCompilerBuilder + .createDefault(PrintQuery.class, new PrintQueryCreator()) + .build(); + +PrintQuery query = compiler.compile("x > 0 && (y < 1 || z == 'test')"); +// ((x > 0) && ((y < 1) || (z == 'test'))) ``` -If a QueryCompiler is built, input strings can be parsed with: + +### Custom term operators + +Custom operators can be added with `withTermCreator`. Afterwards they can be used in queries: + ```java -QueryCompiler esCompiler = ... -ElasticSearchQuery esQuery = esCompiler.compile("(x > 1 && y < 1)"); +builder.withTermCreator(new TermOperator("PHRASE"), (node, field, value) -> ...); ``` -##### Override DefaultCreator -DefaultCreator is an abstract class that contains functions for all standard operations. -If such a method is not overridden, an error is thrown if the input query string contains the respective operator. -```java -public class ElasticSearchQueryCreator extends DefaultCreator { - //override eq(field,value) to support == operator in input queries - //text search is implemented by overriding the fullSearch(Value value) method - @Override - public ElasticSearchQuery eq(Field field, Value value) { - return new ElasticSearchQuery() { - @Override - public QueryBuilder create() { - return QueryBuilders.termQuery(field.toString(), value.getValue()); - } - }; - } - - - //override other term operator methods: ne (!=), le(>=), lt(>),... - - ... - - //override and(query....) to support AND concatenation of terms - @Override - public ElasticSearchQuery and(ElasticSearchQuery... queries) { - return new ElasticSearchQuery() { - @Override - public QueryBuilder create() { - BoolQueryBuilder boolQueryBuilder = boolQuery(); - for(ElasticSearchQuery q : queries){ - boolQueryBuilder.must(q.create()); - } - - return boolQueryBuilder; - } - }; - } - //override other logic operator methods: OR, XOR, NOR,... -} + ``` -The compiler can then be created using the following Builder methods: -```java -QueryCompiler esCompiler - = QueryCompiler.create(ElasticSearchQuery.class) - .withDefaultCreator(new ElasticSearchQueryCreator()) - .build(); +x PHRASE 'test phrase' || y == 'test' ``` -##### Define creators using QueryCompilerBuilder +### Print the query tree + +Queries are first compiled to a `QueryTree` before the target object is created. The tree can be printed: ```java - QueryCompiler compiler = QueryCompiler - .create(ElasticSearchQuery.class) - .withTermCreator( - TermOperators.EQ, - (field,value) -> new ElasticSearchQuery() { - @Override - public String create() { - return QueryBuilders.termQuery(field.toString(), value.getValue()); - } - } - ) - .withANDCreator( - (queries) -> new ElasticSearchQuery() { - BoolQueryBuilder boolQueryBuilder = boolQuery(); - for(ElasticSearchQuery q : queries){ - boolQueryBuilder.must(q.create()); - } - - return boolQueryBuilder; - } - ) - ).build() +QueryTree tree = compiler.compileTree("x > 0 && (y < 1 || z == 'test')"); +String str = QueryPrinter.create().build().toString(tree.getRoot()); ``` - -#### Custom term operators - -Custom term operators can be added to the QueryCompilerBuilder. -In this example we add a PHRASE operator that creates an matchPhrase query for elasticsearch. -User can than input queries like:; ``` -x PHRASE 'test phrase' || y == 'test' +──┐ AND + ├── (x > 0) + └──┐ OR + ├── (y < 1) + └── (z == test) ``` -```java - QueryCompiler compiler = QueryCompiler - .create(ElasticSearchQuery.class) - .withTermCreator( - .withTermCreator( - new TermOperator("PHRASE"), - (f,v) -> new ElasticSearchQuery() { - @Override - public String create() { - return QueryBuilders.matchPhraseQuery(field.toString(), value.getValue()); - } - } - ) - ) - ) -``` +The tree can then be converted to the target object with `compiler.compile(tree)`. -#### Print queries -Queries are first compiled to a tree before being converted to the target object. -This tree can be printed +## Release -```java - QueryTree tree = compiler.compileTree( - "(x > 0 && y < 1 || (u == 2 && (h != 1 || z < 2))) || z == 2"); - String str = QueryPrinter.DEFAULT.toString(tree.getRoot()); - /** - * ──┐ OR - ├──┐ AND - │ ├── (x > 0) - │ └── (y < 1) - ├──┐ AND - │ ├── (u == 2) - │ └──┐ OR - │ ├── (h != 1) - │ └── (z < 2) - └── (z == 2) - **/ - //The tree can then be converted to the target object - ElasticSearchQuery esQuery = compiler.compile(tree); -``` \ No newline at end of file +Releases are published to Maven Central with `./gradlew publishToMavenCentral`. The +[vanniktech maven-publish plugin](https://vanniktech.github.io/gradle-maven-publish-plugin/) attaches the sources and +javadoc jars, signs the artifacts and uploads them to the Central Portal; the deployment is then released manually there. +The GitHub Actions workflow `release.yml` runs this for tags named `v*` (tag `v1.0.0` publishes version `1.0.0`) and +needs the secrets `CENTRAL_USERNAME`, `CENTRAL_PASSWORD`, `GPG_PRIVATE_KEY` and `GPG_PASSPHRASE`. + +## License + +[MIT](LICENSE.txt) diff --git a/build.gradle.kts b/build.gradle.kts index 84e492b..8c965f3 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -1,17 +1,13 @@ plugins { - java + `java-library` antlr - id("maven-publish") + jacoco + id("com.vanniktech.maven.publish") version "0.37.0" } group = "dev.gruen" version = System.getenv("VERSION") ?: "0.0.1-SNAPSHOT" -description = "Simple QueryCompiler for Java" - -java { - sourceCompatibility = JavaVersion.VERSION_21 - targetCompatibility = JavaVersion.VERSION_21 -} +description = "Query compiler: compiles filter query strings into any target object" repositories { mavenCentral() @@ -19,21 +15,83 @@ repositories { dependencies { antlr("org.antlr:antlr4:4.13.2") - implementation("org.antlr:antlr4-runtime:4.13.2") - testImplementation("org.junit.jupiter:junit-jupiter-api:5.11.4") - testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:5.11.4") + api("org.antlr:antlr4-runtime:4.13.2") + + testImplementation(platform("org.junit:junit-bom:5.11.4")) + testImplementation("org.junit.jupiter:junit-jupiter") + testRuntimeOnly("org.junit.platform:junit-platform-launcher") +} + +configurations.api { + setExtendsFrom(extendsFrom.filter { it.name != "antlr" }) +} + +tasks.withType().configureEach { + options.encoding = "UTF-8" + options.release = 21 } -tasks.withType { +tasks.javadoc { options.encoding = "UTF-8" + (options as StandardJavadocDocletOptions).apply { + addStringOption("Xdoclint:all,-missing", "-quiet") + } } tasks.test { useJUnitPlatform() + finalizedBy(tasks.jacocoTestReport) } +jacoco { + toolVersion = "0.8.13" +} + +tasks.jacocoTestReport { + dependsOn(tasks.test) + reports { + xml.required = true + html.required = true + } + classDirectories.setFrom(files(classDirectories.files.map { + fileTree(it) { exclude("dev/gruen/query/generated/**") } + })) +} tasks.generateGrammarSource { - maxHeapSize = "64m" arguments = arguments + listOf("-visitor", "-long-messages") } + +mavenPublishing { + publishToMavenCentral(automaticRelease = false) + + if (providers.gradleProperty("signingInMemoryKey").isPresent) { + signAllPublications() + } + + coordinates(project.group.toString(), "query-compiler", project.version.toString()) + + pom { + name = "query-compiler" + description = project.description + url = "https://github.com/nRo/query-compiler" + licenses { + license { + name = "MIT License" + url = "https://opensource.org/licenses/MIT" + } + } + developers { + developer { + id = "alexgruen" + name = "Alexander Grün" + email = "alex@gruen.dev" + } + } + scm { + url = "https://github.com/nRo/query-compiler" + connection = "scm:git:https://github.com/nRo/query-compiler.git" + developerConnection = "scm:git:ssh://git@github.com/nRo/query-compiler.git" + } + } +} diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..61285a6 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 9355b41..37f78a6 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,6 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.10-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-9.3.1-bin.zip networkTimeout=10000 validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME diff --git a/gradlew b/gradlew old mode 100644 new mode 100755 index 1aa94a4..adff685 --- a/gradlew +++ b/gradlew @@ -1,7 +1,7 @@ #!/bin/sh # -# Copyright © 2015-2021 the original authors. +# Copyright © 2015 the original authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -15,6 +15,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # +# SPDX-License-Identifier: Apache-2.0 +# ############################################################################## # @@ -55,7 +57,7 @@ # Darwin, MinGW, and NonStop. # # (3) This script is generated from the Groovy template -# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt # within the Gradle project. # # You can find Gradle at https://github.com/gradle/gradle/. @@ -84,7 +86,7 @@ done # shellcheck disable=SC2034 APP_BASE_NAME=${0##*/} # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) -APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD=maximum @@ -112,7 +114,6 @@ case "$( uname )" in #( NONSTOP* ) nonstop=true ;; esac -CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar # Determine the Java command to use to start the JVM. @@ -170,7 +171,6 @@ fi # For Cygwin or MSYS, switch paths to Windows format before running java if "$cygwin" || "$msys" ; then APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) - CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) JAVACMD=$( cygpath --unix "$JAVACMD" ) @@ -203,15 +203,14 @@ fi DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' # Collect all arguments for the java command: -# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, # and any embedded shellness will be escaped. # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be # treated as '${Hostname}' itself on the command line. set -- \ "-Dorg.gradle.appname=$APP_BASE_NAME" \ - -classpath "$CLASSPATH" \ - org.gradle.wrapper.GradleWrapperMain \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ "$@" # Stop when "xargs" is not available. diff --git a/gradlew.bat b/gradlew.bat index 93e3f59..c4bdd3a 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -13,6 +13,8 @@ @rem See the License for the specific language governing permissions and @rem limitations under the License. @rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem @if "%DEBUG%"=="" @echo off @rem ########################################################################## @@ -43,11 +45,11 @@ set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 if %ERRORLEVEL% equ 0 goto execute -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 goto fail @@ -57,22 +59,21 @@ set JAVA_EXE=%JAVA_HOME%/bin/java.exe if exist "%JAVA_EXE%" goto execute -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 goto fail :execute @rem Setup the command line -set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar @rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* :end @rem End local scope for the variables with windows NT shell diff --git a/settings.gradle.kts b/settings.gradle.kts index 66fb61a..8fe213d 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -1 +1 @@ -rootProject.name = "query-compiler" \ No newline at end of file +rootProject.name = "query-compiler" diff --git a/src/main/antlr/de/alexgruen/query/generated/Query.g4 b/src/main/antlr/dev/gruen/query/generated/Query.g4 similarity index 60% rename from src/main/antlr/de/alexgruen/query/generated/Query.g4 rename to src/main/antlr/dev/gruen/query/generated/Query.g4 index be57750..696ddfb 100644 --- a/src/main/antlr/de/alexgruen/query/generated/Query.g4 +++ b/src/main/antlr/dev/gruen/query/generated/Query.g4 @@ -1,29 +1,10 @@ -/* - * Copyright (c) 2016 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. - */ +// SPDX-License-Identifier: MIT +// Copyright (c) 2018 Alexander Grün grammar Query; @header { - package de.alexgruen.query.generated; + package dev.gruen.query.generated; import java.util.*; } @@ -53,10 +34,13 @@ variable MATCH REGEX; value_list: OPEN_BRACKET value (COMMA value)* CLOSE_BRACKET; +// Alternatives are listed from highest to lowest precedence: AND binds tighter than XOR, XOR tighter than OR/NOR. +// All binary operators are left-associative. query: NEGATE? OPEN_BRACKET query CLOSE_BRACKET | -OPEN_BRACKET query LOGICAL_OPERATOR query CLOSE_BRACKET| -query LOGICAL_OPERATOR query| +query AND query | +query XOR query | +query (OR | NOR) query | term; @@ -96,10 +80,6 @@ MATCH : ('~=' | '~' ); fragment IN : ('IN' | 'in'); fragment NOT_IN : ('!IN' | '!in'); -fragment AND : ('AND' | 'and' | '&' | '&&'); -fragment OR : ('OR' | 'or' | '|' | '||'); -fragment NOR : ('NOR' | 'nor') ; -fragment XOR : ('XOR' | 'xor') ; fragment TEXT : UNESCAPED_STRING|STRING; fragment VAR_NAME : TEXT ('.' TEXT)*; @@ -110,7 +90,10 @@ COMMA : ','; NEGATE: ('!'|'-'); POSITIVE: '+'; -LOGICAL_OPERATOR : AND | OR | NOR; +AND : 'AND' | 'and' | '&' | '&&'; +OR : 'OR' | 'or' | '|' | '||'; +NOR : 'NOR' | 'nor'; +XOR : 'XOR' | 'xor'; TERM_OPERATOR : EQ | NE | LE | LT | GT | GE | TM; diff --git a/src/main/java/de/alexgruen/query/LogicalOperator.java b/src/main/java/de/alexgruen/query/LogicalOperator.java deleted file mode 100644 index a63076e..0000000 --- a/src/main/java/de/alexgruen/query/LogicalOperator.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * MIT License - * - * Copyright (c) 2018 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 de.alexgruen.query; - -/** - * Logic operators are used to concatenate multiple array (e.g. AND, OR, XOR,...) - */ -public class LogicalOperator extends Operator { - - /** - * Creates a logic operator from a name and array of aliases - * - * @param name operator name - * @param aliases operator aliases - */ - public LogicalOperator(String name, String... aliases) { - super(name, aliases); - } -} diff --git a/src/main/java/de/alexgruen/query/PrintQuery.java b/src/main/java/de/alexgruen/query/PrintQuery.java deleted file mode 100644 index 89c464b..0000000 --- a/src/main/java/de/alexgruen/query/PrintQuery.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * MIT License - * - * Copyright (c) 2018 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 de.alexgruen.query; - -/** - * Simple queries that create a string representation of the query - */ -public abstract class PrintQuery implements Query { - - /** - * Returns the string representation of this query - * - * @return string representation - */ - @Override - public abstract String toString(); -} \ No newline at end of file diff --git a/src/main/java/de/alexgruen/query/Query.java b/src/main/java/de/alexgruen/query/Query.java deleted file mode 100644 index d5da1d7..0000000 --- a/src/main/java/de/alexgruen/query/Query.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * MIT License - * - * Copyright (c) 2018 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 de.alexgruen.query; - -/** - * Base interface for queries - */ -public interface Query { -} diff --git a/src/main/java/de/alexgruen/query/QueryTree.java b/src/main/java/de/alexgruen/query/QueryTree.java deleted file mode 100644 index bc97705..0000000 --- a/src/main/java/de/alexgruen/query/QueryTree.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * MIT License - * - * Copyright (c) 2018 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 de.alexgruen.query; - - -public class QueryTree { - private static final QueryPrinter PRINTER = QueryPrinter.create().build(); - - private QueryNode root; - - public QueryTree(QueryNode root) { - this.root = root; - } - - public QueryNode getRoot() { - return root; - } - - public void setRoot(QueryNode root) { - this.root = root; - } - - @Override - public String toString() { - return PRINTER.toString(root); - } - -} diff --git a/src/main/java/de/alexgruen/query/compiler/QueryCompilerErrorListener.java b/src/main/java/de/alexgruen/query/compiler/QueryCompilerErrorListener.java deleted file mode 100644 index 446cb2f..0000000 --- a/src/main/java/de/alexgruen/query/compiler/QueryCompilerErrorListener.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * MIT License - * - * Copyright (c) 2018 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 de.alexgruen.query.compiler; - -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 QueryCompilerErrorListener extends BaseErrorListener { - //Query String that lead to an error - private final String queryString; - - public QueryCompilerErrorListener(String queryString) { - this.queryString = queryString; - } - - /** - * Listener method that gets evoked if an error occurs during query compilation. - * This method throws {@link QueryCompilerException} if called by the compiler - * - * @param recognizer recognizer - * @param offendingSymbol offending symbol - * @param line line in input string - * @param charPositionInLine char position in the input line - * @param msg error message - * @param e exception - */ - @Override - public void syntaxError(Recognizer recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) { - throw new QueryCompilerException(String.format("syntax error (%s : %s) line:%s, pos:%s ", msg, queryString, line, charPositionInLine)); - } - - /** - * Returns the query string that caused an error during compilation - * - * @return - */ - public String getQueryString() { - return queryString; - } -} diff --git a/src/main/java/de/alexgruen/query/compiler/QueryCompilerException.java b/src/main/java/de/alexgruen/query/compiler/QueryCompilerException.java deleted file mode 100644 index ddf0733..0000000 --- a/src/main/java/de/alexgruen/query/compiler/QueryCompilerException.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * MIT License - * - * Copyright (c) 2018 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 de.alexgruen.query.compiler; - -/** - * Created by Alex on 21.05.2017. - *

- * Exception that is thrown if an error occurs during query compilation - */ - -public class QueryCompilerException extends RuntimeException { - public QueryCompilerException(String message) { - super(message); - } - - public QueryCompilerException(String message, Throwable throwable) { - super(message, throwable); - } -} diff --git a/src/main/java/de/alexgruen/query/compiler/RegexTermVisitor.java b/src/main/java/de/alexgruen/query/compiler/RegexTermVisitor.java deleted file mode 100644 index 153869f..0000000 --- a/src/main/java/de/alexgruen/query/compiler/RegexTermVisitor.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * MIT License - * - * Copyright (c) 2018 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 de.alexgruen.query.compiler; - -import de.alexgruen.query.QueryNode; -import de.alexgruen.query.generated.QueryBaseVisitor; -import de.alexgruen.query.generated.QueryParser; -import de.alexgruen.query.term.Field; -import de.alexgruen.query.term.Term; -import de.alexgruen.query.term.TermOperators; -import de.alexgruen.query.term.Value; -import de.alexgruen.query.util.CompilerUtil; - -import java.util.regex.Pattern; - -/** - * Created by Alex on 21.05.2017. - */ -public class RegexTermVisitor extends QueryBaseVisitor { - - /** - * Creates a {@link QueryNode} that represents a regex term. - * An exception is thrown if the context cannot be converted to a node - * - * @param ctx input regex context - * @return query node - */ - @Override - public QueryNode visitRegex_term(QueryParser.Regex_termContext ctx) { - Field field = CompilerUtil.createField(ctx.variable()); - - Pattern pattern = convertPattern(ctx.REGEX().getText()); - Value value = new Value(pattern); - return new QueryNode(new Term(field, TermOperators.REGEX, value)); - } - - /** - * Converts an input string to a {@link Pattern}. - * A {@link QueryCompilerException} is thrown if the input string is not in the right format - * - * @param text input string - * @return compiled pattern - */ - private static Pattern convertPattern(String text) { - String regex = text; - if (!regex.startsWith("/") || !regex.endsWith("/")) { - throw new QueryCompilerException(String.format("wrong pattern format: %s", text)); - } - regex = regex.substring(1, regex.length() - 1); - return Pattern.compile(regex); - } -} diff --git a/src/main/java/de/alexgruen/query/compiler/TermQueryVisitor.java b/src/main/java/de/alexgruen/query/compiler/TermQueryVisitor.java deleted file mode 100644 index 571dd87..0000000 --- a/src/main/java/de/alexgruen/query/compiler/TermQueryVisitor.java +++ /dev/null @@ -1,145 +0,0 @@ -/* - * MIT License - * - * Copyright (c) 2018 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 de.alexgruen.query.compiler; - -import de.alexgruen.query.QueryNode; -import de.alexgruen.query.generated.QueryBaseVisitor; -import de.alexgruen.query.generated.QueryParser; - -/** - * Created by Alex on 21.05.2017. - */ -public class TermQueryVisitor extends QueryBaseVisitor { - - private final QueryContext context; - - public TermQueryVisitor(QueryContext context) { - this.context = context; - } - - - /** - * Converts the root compilation context to the root query node - * - * @param ctx root context - * @return root node - */ - @Override - public QueryNode visitCompilationUnit(QueryParser.CompilationUnitContext ctx) { - if (ctx.query() == null && ctx.full_search() == null) { - throw new QueryCompilerException("no valid query found"); - } - if (ctx.query() != null) { - return visitQuery(ctx.query()); - } else { - return visitFull_search(ctx.full_search()); - } - } - - /** - * Uses a {@link TextSearchVisitor} to convert a full text search context to a query node - * - * @param ctx full search context - * @return query node - */ - @Override - public QueryNode visitFull_search(QueryParser.Full_searchContext ctx) { - TextSearchVisitor textSearchVisitor = new TextSearchVisitor(); - return textSearchVisitor.visitFull_search(ctx); - } - - /** - * Creates a query node from a query context. - * Recursively creates all child query nodes for the root query context. - * - * @param ctx root query context - * @return query node - */ - @Override - public QueryNode visitQuery(QueryParser.QueryContext ctx) { - if (ctx.term() != null) { - TermVisitor termVisitor = new TermVisitor(context); - return termVisitor.visitTerm(ctx.term()); - } - - if (ctx.query().size() == 1) { - TermQueryVisitor termQueryVisitor = new TermQueryVisitor(context); - QueryNode queryNode = termQueryVisitor.visit(ctx.query(0)); - if (ctx.NEGATE() != null) { - queryNode.setNegate(true); - } - return queryNode; - } - - - QueryNode parent = new QueryNode(); - QueryNode left = visitQueryRecursive(ctx.query(0)); - QueryNode right = visitQueryRecursive(ctx.query(1)); - parent.getChildren().add(left); - parent.getChildren().add(right); - parent.setOperator(context.getLogicalOperator(ctx.LOGICAL_OPERATOR().getText())); - return parent; - } - - - /** - * Recursive function to create query nodes from a query context - * - * @param ctx query context - * @return query node with all child query nodes - */ - private QueryNode visitQueryRecursive(QueryParser.QueryContext ctx) { - if (ctx.term() != null) { - TermVisitor termVisitor = new TermVisitor(context); - QueryNode n = termVisitor.visitTerm(ctx.term()); - if (ctx.NEGATE() != null) { - n.setNegate(true); - } - return n; - } - - if (ctx.query().size() == 1) { - QueryNode n = visitQueryRecursive(ctx.query(0)); - if (ctx.NEGATE() != null) { - n.setNegate(true); - } - return n; - } - - - QueryNode parent = new QueryNode(); - QueryNode left = visitQueryRecursive(ctx.query(0)); - QueryNode right = visitQueryRecursive(ctx.query(1)); - parent.getChildren().add(left); - parent.getChildren().add(right); - parent.setOperator(context.getLogicalOperator(ctx.LOGICAL_OPERATOR().getText())); - - if (ctx.NEGATE() != null) { - parent.setNegate(true); - } - return parent; - } - -} diff --git a/src/main/java/de/alexgruen/query/compiler/parser/Parser.java b/src/main/java/de/alexgruen/query/compiler/parser/Parser.java deleted file mode 100644 index 32e6eec..0000000 --- a/src/main/java/de/alexgruen/query/compiler/parser/Parser.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * MIT License - * - * Copyright (c) 2018 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 de.alexgruen.query.compiler.parser; - -import java.text.ParseException; - -/** - * Created by Alex on 04.06.2015. - */ -public abstract class Parser { - - /** - * Parse input String and returns the an object of type T - * - * @param s input string - * @return resulting object - * @throws ParseException throw if there was an error during parsing - */ - public abstract T parse(String s) throws ParseException; - - /** - * Parse input String and returns the an object of type T. - * If parsing doesn't work, null is returned - * - * @param s input string - * @return resulting object - */ - public T parseOrNull(String s) { - try { - return parse(s); - } catch (Exception e) { - return null; - } - } - -} diff --git a/src/main/java/de/alexgruen/query/compiler/parser/ParserNotFoundException.java b/src/main/java/de/alexgruen/query/compiler/parser/ParserNotFoundException.java deleted file mode 100644 index 19ddde9..0000000 --- a/src/main/java/de/alexgruen/query/compiler/parser/ParserNotFoundException.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * MIT License - * - * Copyright (c) 2018 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 de.alexgruen.query.compiler.parser; - -import de.alexgruen.query.compiler.QueryCompilerException; - -/** - * Created by Alex on 04.06.2015. - */ - -public class ParserNotFoundException extends QueryCompilerException { - public ParserNotFoundException(Class c) { - super("no parser found for " + c.getName()); - } -} diff --git a/src/main/java/de/alexgruen/query/creator/LogicCreator.java b/src/main/java/de/alexgruen/query/creator/LogicCreator.java deleted file mode 100644 index 88aed32..0000000 --- a/src/main/java/de/alexgruen/query/creator/LogicCreator.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * MIT License - * - * Copyright (c) 2018 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 de.alexgruen.query.creator; - - -import de.alexgruen.query.QueryNode; - -public interface LogicCreator extends OperatorCreator { - - /** - * Creates a new term from several input terms. - * - * @param node query node - * @param children input terms - * @return new term - */ - @SuppressWarnings("unchecked") - T create(QueryNode node, T... children); -} diff --git a/src/main/java/de/alexgruen/query/creator/OperatorCreator.java b/src/main/java/de/alexgruen/query/creator/OperatorCreator.java deleted file mode 100644 index a6385a2..0000000 --- a/src/main/java/de/alexgruen/query/creator/OperatorCreator.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * MIT License - * - * Copyright (c) 2018 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 de.alexgruen.query.creator; - -/** - * Interface that is implemented by LogicCreators and TermCreators - */ -public interface OperatorCreator { -} diff --git a/src/main/java/de/alexgruen/query/creator/TermCreator.java b/src/main/java/de/alexgruen/query/creator/TermCreator.java deleted file mode 100644 index 565c6ea..0000000 --- a/src/main/java/de/alexgruen/query/creator/TermCreator.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * MIT License - * - * Copyright (c) 2018 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 de.alexgruen.query.creator; - -import de.alexgruen.query.QueryNode; -import de.alexgruen.query.term.Field; -import de.alexgruen.query.term.Value; - -public interface TermCreator extends OperatorCreator { - /** - * Crates a Query of the desired type from a {@link Field} and {@link Value} - * - * @param node query node - * @param field input field - * @param value input value - * @return query - */ - T create(QueryNode node, Field field, Value value); -} diff --git a/src/main/java/de/alexgruen/query/optimization/Optimizations.java b/src/main/java/de/alexgruen/query/optimization/Optimizations.java deleted file mode 100644 index c1dc2cc..0000000 --- a/src/main/java/de/alexgruen/query/optimization/Optimizations.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * MIT License - * - * Copyright (c) 2018 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 de.alexgruen.query.optimization; - -public class Optimizations { - private Optimizations() { - throw new IllegalStateException("utility class"); - } - - /** - * Removes redundant brackets from a query tree. - */ - public static final QueryOptimization RemoveRedundantBrackets = new RemoveRedundantBrackets(); -} diff --git a/src/main/java/de/alexgruen/query/optimization/QueryOptimization.java b/src/main/java/de/alexgruen/query/optimization/QueryOptimization.java deleted file mode 100644 index b77f223..0000000 --- a/src/main/java/de/alexgruen/query/optimization/QueryOptimization.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * MIT License - * - * Copyright (c) 2018 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 de.alexgruen.query.optimization; - -import de.alexgruen.query.QueryTree; - -public interface QueryOptimization { - /** - * Optimizes an input query tree. - * - * @param queryTree input query tree - */ - void apply(QueryTree queryTree); -} diff --git a/src/main/java/de/alexgruen/query/term/TermOperator.java b/src/main/java/de/alexgruen/query/term/TermOperator.java deleted file mode 100644 index 790aba0..0000000 --- a/src/main/java/de/alexgruen/query/term/TermOperator.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * MIT License - * - * Copyright (c) 2018 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 de.alexgruen.query.term; - - -import de.alexgruen.query.Operator; - -/** - * Represents a term operator (==, !=, >, ...) - */ -public class TermOperator extends Operator { - - /** - * Creates a new Term operator from a name and array of aliases - * - * @param name term name - * @param aliases term aliases - */ - public TermOperator(String name, String... aliases) { - super(name, aliases); - } - - -} diff --git a/src/main/java/dev/gruen/query/LogicalOperator.java b/src/main/java/dev/gruen/query/LogicalOperator.java new file mode 100644 index 0000000..0407636 --- /dev/null +++ b/src/main/java/dev/gruen/query/LogicalOperator.java @@ -0,0 +1,20 @@ +// SPDX-License-Identifier: MIT +// Copyright (c) 2018 Alexander Grün + +package dev.gruen.query; + +/** + * Logic operators are used to concatenate multiple array (e.g. AND, OR, XOR,...) + */ +public class LogicalOperator extends Operator { + + /** + * Creates a logic operator from a name and array of aliases + * + * @param name operator name + * @param aliases operator aliases + */ + public LogicalOperator(String name, String... aliases) { + super(name, aliases); + } +} diff --git a/src/main/java/de/alexgruen/query/LogicalOperators.java b/src/main/java/dev/gruen/query/LogicalOperators.java similarity index 53% rename from src/main/java/de/alexgruen/query/LogicalOperators.java rename to src/main/java/dev/gruen/query/LogicalOperators.java index 5318d17..5a95ff1 100644 --- a/src/main/java/de/alexgruen/query/LogicalOperators.java +++ b/src/main/java/dev/gruen/query/LogicalOperators.java @@ -1,28 +1,7 @@ -/* - * MIT License - * - * Copyright (c) 2018 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. - */ +// SPDX-License-Identifier: MIT +// Copyright (c) 2018 Alexander Grün -package de.alexgruen.query; +package dev.gruen.query; import java.util.ArrayList; import java.util.Arrays; diff --git a/src/main/java/de/alexgruen/query/Operator.java b/src/main/java/dev/gruen/query/Operator.java similarity index 53% rename from src/main/java/de/alexgruen/query/Operator.java rename to src/main/java/dev/gruen/query/Operator.java index 9d6c829..c8192a6 100644 --- a/src/main/java/de/alexgruen/query/Operator.java +++ b/src/main/java/dev/gruen/query/Operator.java @@ -1,34 +1,13 @@ -/* - * MIT License - * - * Copyright (c) 2018 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. - */ +// SPDX-License-Identifier: MIT +// Copyright (c) 2018 Alexander Grün -package de.alexgruen.query; +package dev.gruen.query; import java.util.Arrays; import java.util.Objects; /** - * Base class for {@link de.alexgruen.query.term.TermOperator} and {@link LogicalOperator} + * Base class for {@link dev.gruen.query.term.TermOperator} and {@link LogicalOperator} */ public class Operator { //Name of the operator diff --git a/src/main/java/dev/gruen/query/PrintQuery.java b/src/main/java/dev/gruen/query/PrintQuery.java new file mode 100644 index 0000000..c6e9ab4 --- /dev/null +++ b/src/main/java/dev/gruen/query/PrintQuery.java @@ -0,0 +1,18 @@ +// SPDX-License-Identifier: MIT +// Copyright (c) 2018 Alexander Grün + +package dev.gruen.query; + +/** + * Simple queries that create a string representation of the query + */ +public abstract class PrintQuery implements Query { + + /** + * Returns the string representation of this query + * + * @return string representation + */ + @Override + public abstract String toString(); +} \ No newline at end of file diff --git a/src/main/java/de/alexgruen/query/PrintQueryCreator.java b/src/main/java/dev/gruen/query/PrintQueryCreator.java similarity index 84% rename from src/main/java/de/alexgruen/query/PrintQueryCreator.java rename to src/main/java/dev/gruen/query/PrintQueryCreator.java index dfe40a0..23643f7 100644 --- a/src/main/java/de/alexgruen/query/PrintQueryCreator.java +++ b/src/main/java/dev/gruen/query/PrintQueryCreator.java @@ -1,31 +1,10 @@ -/* - * MIT License - * - * Copyright (c) 2018 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. - */ +// SPDX-License-Identifier: MIT +// Copyright (c) 2018 Alexander Grün -package de.alexgruen.query; +package dev.gruen.query; -import de.alexgruen.query.term.Field; -import de.alexgruen.query.term.Value; +import dev.gruen.query.term.Field; +import dev.gruen.query.term.Value; /** * Default creator for {@link PrintQuery} diff --git a/src/main/java/dev/gruen/query/Query.java b/src/main/java/dev/gruen/query/Query.java new file mode 100644 index 0000000..0c69a67 --- /dev/null +++ b/src/main/java/dev/gruen/query/Query.java @@ -0,0 +1,10 @@ +// SPDX-License-Identifier: MIT +// Copyright (c) 2018 Alexander Grün + +package dev.gruen.query; + +/** + * Base interface for queries + */ +public interface Query { +} diff --git a/src/main/java/de/alexgruen/query/QueryCreator.java b/src/main/java/dev/gruen/query/QueryCreator.java similarity index 95% rename from src/main/java/de/alexgruen/query/QueryCreator.java rename to src/main/java/dev/gruen/query/QueryCreator.java index 4f8bd7c..8b5332c 100644 --- a/src/main/java/de/alexgruen/query/QueryCreator.java +++ b/src/main/java/dev/gruen/query/QueryCreator.java @@ -1,7 +1,7 @@ -package de.alexgruen.query; +package dev.gruen.query; -import de.alexgruen.query.term.Field; -import de.alexgruen.query.term.Value; +import dev.gruen.query.term.Field; +import dev.gruen.query.term.Value; public interface QueryCreator { /** @@ -45,7 +45,7 @@ public interface QueryCreator { T gt(QueryNode queryNode, Field field, Value value); /** - * Query creator for < operator + * Query creator for the {@code <} operator * * @param queryNode current query node * @param field input field @@ -55,7 +55,7 @@ public interface QueryCreator { T lt(QueryNode queryNode, Field field, Value value); /** - * Query creator for <= operator + * Query creator for the {@code <=} operator * * @param queryNode current query node * @param field input field diff --git a/src/main/java/de/alexgruen/query/QueryNode.java b/src/main/java/dev/gruen/query/QueryNode.java similarity index 72% rename from src/main/java/de/alexgruen/query/QueryNode.java rename to src/main/java/dev/gruen/query/QueryNode.java index 980e6ce..a5f8bc7 100644 --- a/src/main/java/de/alexgruen/query/QueryNode.java +++ b/src/main/java/dev/gruen/query/QueryNode.java @@ -1,30 +1,9 @@ -/* - * MIT License - * - * Copyright (c) 2018 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 de.alexgruen.query; - -import de.alexgruen.query.term.Term; +// SPDX-License-Identifier: MIT +// Copyright (c) 2018 Alexander Grün + +package dev.gruen.query; + +import dev.gruen.query.term.Term; import java.util.*; @@ -101,13 +80,9 @@ public Object getAttribute(String name) { public Object setAttribute(String name, Object value) { return attributes.put(name, value); } - /** - * Creates a new leaf node from a term - * @param term term - */ /** - * Returns true if this node is negated + * Returns true if this node is negated * * @return true if negated */ diff --git a/src/main/java/de/alexgruen/query/QueryPrinter.java b/src/main/java/dev/gruen/query/QueryPrinter.java similarity index 78% rename from src/main/java/de/alexgruen/query/QueryPrinter.java rename to src/main/java/dev/gruen/query/QueryPrinter.java index 9242937..67647ac 100644 --- a/src/main/java/de/alexgruen/query/QueryPrinter.java +++ b/src/main/java/dev/gruen/query/QueryPrinter.java @@ -1,30 +1,9 @@ -/* - * MIT License - * - * Copyright (c) 2018 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 de.alexgruen.query; - -import de.alexgruen.query.util.StringUtil; +// SPDX-License-Identifier: MIT +// Copyright (c) 2018 Alexander Grün + +package dev.gruen.query; + +import dev.gruen.query.util.StringUtil; import java.util.function.Function; import java.util.function.UnaryOperator; diff --git a/src/main/java/dev/gruen/query/QueryTree.java b/src/main/java/dev/gruen/query/QueryTree.java new file mode 100644 index 0000000..c43acc3 --- /dev/null +++ b/src/main/java/dev/gruen/query/QueryTree.java @@ -0,0 +1,29 @@ +// SPDX-License-Identifier: MIT +// Copyright (c) 2018 Alexander Grün + +package dev.gruen.query; + + +public class QueryTree { + private static final QueryPrinter PRINTER = QueryPrinter.create().build(); + + private QueryNode root; + + public QueryTree(QueryNode root) { + this.root = root; + } + + public QueryNode getRoot() { + return root; + } + + public void setRoot(QueryNode root) { + this.root = root; + } + + @Override + public String toString() { + return PRINTER.toString(root); + } + +} diff --git a/src/main/java/de/alexgruen/query/compiler/QueryCompiler.java b/src/main/java/dev/gruen/query/compiler/QueryCompiler.java similarity index 70% rename from src/main/java/de/alexgruen/query/compiler/QueryCompiler.java rename to src/main/java/dev/gruen/query/compiler/QueryCompiler.java index 4cee91d..eacfcad 100644 --- a/src/main/java/de/alexgruen/query/compiler/QueryCompiler.java +++ b/src/main/java/dev/gruen/query/compiler/QueryCompiler.java @@ -1,38 +1,24 @@ -/* - * MIT License - * - * Copyright (c) 2018 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. - */ +// SPDX-License-Identifier: MIT +// Copyright (c) 2018 Alexander Grün -package de.alexgruen.query.compiler; +package dev.gruen.query.compiler; -import de.alexgruen.query.*; -import de.alexgruen.query.creator.LogicCreator; -import de.alexgruen.query.creator.TermCreator; -import de.alexgruen.query.optimization.QueryOptimization; -import de.alexgruen.query.term.Term; -import de.alexgruen.query.util.CompilerUtil; +import dev.gruen.query.*; +import dev.gruen.query.creator.LogicCreator; +import dev.gruen.query.creator.TermCreator; +import dev.gruen.query.optimization.QueryOptimization; +import dev.gruen.query.term.Term; +import dev.gruen.query.util.CompilerUtil; import java.util.List; +/** + * Compiles query strings to a target class, see {@link QueryCompilerBuilder} for creating instances. + *

+ * A compiler can be shared between threads if the configured creators and optimizations are thread-safe. + * + * @param target class + */ public class QueryCompiler { private final QueryContext context; @@ -41,7 +27,7 @@ public class QueryCompiler { protected QueryCompiler(QueryContext context, List optimizations) { this.context = context; - this.optimizations = optimizations; + this.optimizations = List.copyOf(optimizations); this.queryTreeCompiler = new QueryTreeCompiler<>(context); } @@ -55,9 +41,9 @@ public QueryContext getContext() { } /** - * Returns all assigned optimizations ({@link QueryOptimization} + * Returns all assigned optimizations ({@link QueryOptimization}). * - * @return optimizations + * @return unmodifiable list of optimizations */ public List getOptimizations() { return optimizations; @@ -75,7 +61,8 @@ public T compile(String str) { } /** - * Compiles an input string to a query tree ({@link QueryTree} + * Compiles an input string to a query tree ({@link QueryTree}). + * All assigned optimizations are applied to the freshly created tree in place. * * @param str input string * @return query tree @@ -108,7 +95,11 @@ private T compileTreeRec(QueryNode node) { if (context.getEmptyCreator() == null) { throw new QueryCompilerException("no empty creator defined"); } - return context.getEmptyCreator().create(node, null, null); + T t = context.getEmptyCreator().create(node, null, null); + if (node.isNegate()) { + t = negate(node, t); + } + return t; } //return if node contains term if (node.getTerm() != null) { @@ -140,6 +131,7 @@ private T compileTreeRec(QueryNode node) { /** * Use {@link LogicCreator} to negate a target object * + * @param node node that is negated * @param t input object * @return negated object */ @@ -152,6 +144,7 @@ private T negate(QueryNode node, T t) { /** * Create an object of target class for a term using the creator ({@link TermCreator}) specified in the {@link QueryContext} * + * @param node node containing the term * @param term input term * @return object of target class */ @@ -161,7 +154,8 @@ private T createTerm(QueryNode node, Term term) { } /** - * Apply all optimizations ({@link QueryOptimization}) specified in the {@link QueryContext} to a {@link QueryTree} + * Apply all optimizations ({@link QueryOptimization}) specified in the {@link QueryContext} to a {@link QueryTree}. + * The tree is modified in place. */ private void optimize(QueryTree tree) { for (QueryOptimization optimization : optimizations) { diff --git a/src/main/java/de/alexgruen/query/compiler/QueryCompilerBuilder.java b/src/main/java/dev/gruen/query/compiler/QueryCompilerBuilder.java similarity index 71% rename from src/main/java/de/alexgruen/query/compiler/QueryCompilerBuilder.java rename to src/main/java/dev/gruen/query/compiler/QueryCompilerBuilder.java index 7be5570..96a25a3 100644 --- a/src/main/java/de/alexgruen/query/compiler/QueryCompilerBuilder.java +++ b/src/main/java/dev/gruen/query/compiler/QueryCompilerBuilder.java @@ -1,37 +1,16 @@ -/* - * MIT License - * - * Copyright (c) 2018 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 de.alexgruen.query.compiler; - -import de.alexgruen.query.*; -import de.alexgruen.query.creator.LogicCreator; -import de.alexgruen.query.creator.OperatorCreatorMap; -import de.alexgruen.query.creator.TermCreator; -import de.alexgruen.query.optimization.QueryOptimization; -import de.alexgruen.query.optimization.RemoveRedundantBrackets; -import de.alexgruen.query.term.TermOperator; -import de.alexgruen.query.term.TermOperators; +// SPDX-License-Identifier: MIT +// Copyright (c) 2018 Alexander Grün + +package dev.gruen.query.compiler; + +import dev.gruen.query.*; +import dev.gruen.query.creator.LogicCreator; +import dev.gruen.query.creator.OperatorCreatorMap; +import dev.gruen.query.creator.TermCreator; +import dev.gruen.query.optimization.QueryOptimization; +import dev.gruen.query.optimization.RemoveRedundantBrackets; +import dev.gruen.query.term.TermOperator; +import dev.gruen.query.term.TermOperators; import java.util.ArrayList; import java.util.List; @@ -78,7 +57,7 @@ public static QueryCompilerBuilder createDefault(Class c * Use a {@link QueryCreator} to define all default logic and term operations * * @param dc default creator - * @return self for method chaining + * @return self for method chaining */ public QueryCompilerBuilder withQueryCreator(QueryCreator dc) { withANDCreator(dc::and); @@ -102,12 +81,12 @@ public QueryCompilerBuilder withQueryCreator(QueryCreator dc) { } /** - * Adds a {@link QueryOptimization} that is used to optimize the resulting {@link de.alexgruen.query.QueryTree} + * Adds a {@link QueryOptimization} that is used to optimize the resulting {@link dev.gruen.query.QueryTree} * before the final query is compiled. * The order of added optimizations is important and can influence the result. * * @param optimization query optimization - * @return self for method chaining + * @return self for method chaining */ public QueryCompilerBuilder withOptimization(QueryOptimization optimization) { this.optimizations.add(optimization); @@ -118,7 +97,7 @@ public QueryCompilerBuilder withOptimization(QueryOptimization optimization) * Adds an {@link TermCreator} that is used to create 'empty' terms (match all) * * @param creator term creator - * @return self for method chaining + * @return self for method chaining */ public QueryCompilerBuilder withEmptyCreator(TermCreator creator) { this.emptyCreator = creator; @@ -130,7 +109,7 @@ public QueryCompilerBuilder withEmptyCreator(TermCreator creator) { * * @param op term operator * @param creator term creator - * @return self for method chaining + * @return self for method chaining */ public QueryCompilerBuilder withTermCreator(TermOperator op, TermCreator creator) { termCreators.add(op, creator); @@ -138,10 +117,10 @@ public QueryCompilerBuilder withTermCreator(TermOperator op, TermCreator c } /** - * Adds an {@link LogicCreator} that is used to create a new term by joining terms using the logic operator AND + * Adds an {@link LogicCreator} that is used to create a new term by joining terms using the logic operator AND * * @param creator logic creator - * @return self for method chaining + * @return self for method chaining */ public QueryCompilerBuilder withANDCreator(LogicCreator creator) { logicCreators.add(LogicalOperators.AND, creator); @@ -149,10 +128,10 @@ public QueryCompilerBuilder withANDCreator(LogicCreator creator) { } /** - * Adds an {@link LogicCreator} that is used to create a new term by joining terms using the logic operator OR + * Adds an {@link LogicCreator} that is used to create a new term by joining terms using the logic operator OR * * @param creator logic creator - * @return self for method chaining + * @return self for method chaining */ public QueryCompilerBuilder withORCreator(LogicCreator creator) { logicCreators.add(LogicalOperators.OR, creator); @@ -160,10 +139,10 @@ public QueryCompilerBuilder withORCreator(LogicCreator creator) { } /** - * Adds an {@link LogicCreator} that is used to create a new term by joining terms using the logic operator XOR + * Adds an {@link LogicCreator} that is used to create a new term by joining terms using the logic operator XOR * * @param creator logic creator - * @return self for method chaining + * @return self for method chaining */ public QueryCompilerBuilder withXORCreator(LogicCreator creator) { logicCreators.add(LogicalOperators.XOR, creator); @@ -171,10 +150,10 @@ public QueryCompilerBuilder withXORCreator(LogicCreator creator) { } /** - * Adds an {@link LogicCreator} that is used to create a new term by joining terms using the logic operator NOR + * Adds an {@link LogicCreator} that is used to create a new term by joining terms using the logic operator NOR * * @param creator logic creator - * @return self for method chaining + * @return self for method chaining */ public QueryCompilerBuilder withNORCreator(LogicCreator creator) { logicCreators.add(LogicalOperators.NOR, creator); @@ -185,7 +164,7 @@ public QueryCompilerBuilder withNORCreator(LogicCreator creator) { * Adds an {@link LogicCreator} that is used to create a new term by negating an input term * * @param creator logic creator - * @return self for method chaining + * @return self for method chaining */ public QueryCompilerBuilder withNOTCreator(LogicCreator creator) { logicCreators.add(LogicalOperators.NOT, creator); diff --git a/src/main/java/dev/gruen/query/compiler/QueryCompilerErrorListener.java b/src/main/java/dev/gruen/query/compiler/QueryCompilerErrorListener.java new file mode 100644 index 0000000..695bfba --- /dev/null +++ b/src/main/java/dev/gruen/query/compiler/QueryCompilerErrorListener.java @@ -0,0 +1,53 @@ +// SPDX-License-Identifier: MIT +// Copyright (c) 2018 Alexander Grün + +package dev.gruen.query.compiler; + +import org.antlr.v4.runtime.BaseErrorListener; +import org.antlr.v4.runtime.RecognitionException; +import org.antlr.v4.runtime.Recognizer; + + +/** + * Error listener that turns every syntax error into a {@link QueryCompilerException}. + */ +public class QueryCompilerErrorListener extends BaseErrorListener { + //Query String that lead to an error + private final String queryString; + + /** + * Creates a new listener + * + * @param queryString query string that is compiled, used in error messages + */ + public QueryCompilerErrorListener(String queryString) { + this.queryString = queryString; + } + + /** + * Listener method that gets evoked if an error occurs during query compilation. + * This method throws a {@link QueryCompilerException} if called by the compiler. + * The message contains the line, the position, the problem and the complete query string. + * + * @param recognizer recognizer + * @param offendingSymbol offending symbol + * @param line line in input string + * @param charPositionInLine char position in the input line + * @param msg error message + * @param e exception + */ + @Override + public void syntaxError(Recognizer recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) { + throw new QueryCompilerException(String.format( + "syntax error at line %d, position %d: %s (query: %s)", line, charPositionInLine, msg, queryString)); + } + + /** + * Returns the query string that caused an error during compilation + * + * @return query string + */ + public String getQueryString() { + return queryString; + } +} diff --git a/src/main/java/dev/gruen/query/compiler/QueryCompilerException.java b/src/main/java/dev/gruen/query/compiler/QueryCompilerException.java new file mode 100644 index 0000000..89dca51 --- /dev/null +++ b/src/main/java/dev/gruen/query/compiler/QueryCompilerException.java @@ -0,0 +1,17 @@ +// SPDX-License-Identifier: MIT +// Copyright (c) 2018 Alexander Grün + +package dev.gruen.query.compiler; + +/** + * Exception that is thrown if an error occurs during query compilation + */ +public class QueryCompilerException extends RuntimeException { + public QueryCompilerException(String message) { + super(message); + } + + public QueryCompilerException(String message, Throwable throwable) { + super(message, throwable); + } +} diff --git a/src/main/java/de/alexgruen/query/compiler/QueryContext.java b/src/main/java/dev/gruen/query/compiler/QueryContext.java similarity index 66% rename from src/main/java/de/alexgruen/query/compiler/QueryContext.java rename to src/main/java/dev/gruen/query/compiler/QueryContext.java index 22ae4ff..9184dae 100644 --- a/src/main/java/de/alexgruen/query/compiler/QueryContext.java +++ b/src/main/java/dev/gruen/query/compiler/QueryContext.java @@ -1,35 +1,14 @@ -/* - * MIT License - * - * Copyright (c) 2018 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. - */ +// SPDX-License-Identifier: MIT +// Copyright (c) 2018 Alexander Grün -package de.alexgruen.query.compiler; +package dev.gruen.query.compiler; -import de.alexgruen.query.LogicalOperator; -import de.alexgruen.query.Query; -import de.alexgruen.query.creator.LogicCreator; -import de.alexgruen.query.creator.OperatorCreatorMap; -import de.alexgruen.query.creator.TermCreator; -import de.alexgruen.query.term.TermOperator; +import dev.gruen.query.LogicalOperator; +import dev.gruen.query.Query; +import dev.gruen.query.creator.LogicCreator; +import dev.gruen.query.creator.OperatorCreatorMap; +import dev.gruen.query.creator.TermCreator; +import dev.gruen.query.term.TermOperator; import java.util.List; diff --git a/src/main/java/de/alexgruen/query/compiler/QueryTreeCompiler.java b/src/main/java/dev/gruen/query/compiler/QueryTreeCompiler.java similarity index 58% rename from src/main/java/de/alexgruen/query/compiler/QueryTreeCompiler.java rename to src/main/java/dev/gruen/query/compiler/QueryTreeCompiler.java index d89341d..66cb128 100644 --- a/src/main/java/de/alexgruen/query/compiler/QueryTreeCompiler.java +++ b/src/main/java/dev/gruen/query/compiler/QueryTreeCompiler.java @@ -1,44 +1,20 @@ -/* - * MIT License - * - * Copyright (c) 2018 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. - */ +// SPDX-License-Identifier: MIT +// Copyright (c) 2018 Alexander Grün -package de.alexgruen.query.compiler; +package dev.gruen.query.compiler; -import de.alexgruen.query.Query; -import de.alexgruen.query.QueryNode; -import de.alexgruen.query.QueryTree; -import de.alexgruen.query.generated.QueryLexer; -import de.alexgruen.query.generated.QueryParser; -import de.alexgruen.query.term.TermOperators; +import dev.gruen.query.Query; +import dev.gruen.query.QueryNode; +import dev.gruen.query.QueryTree; +import dev.gruen.query.generated.QueryLexer; +import dev.gruen.query.generated.QueryParser; +import dev.gruen.query.term.TermOperators; import org.antlr.v4.runtime.CharStream; import org.antlr.v4.runtime.CharStreams; import org.antlr.v4.runtime.CommonTokenStream; import org.antlr.v4.runtime.ConsoleErrorListener; -/** - * Created by Alex on 18.05.2017. - */ public class QueryTreeCompiler { private final QueryContext context; diff --git a/src/main/java/dev/gruen/query/compiler/RegexTermVisitor.java b/src/main/java/dev/gruen/query/compiler/RegexTermVisitor.java new file mode 100644 index 0000000..848b6ad --- /dev/null +++ b/src/main/java/dev/gruen/query/compiler/RegexTermVisitor.java @@ -0,0 +1,50 @@ +// SPDX-License-Identifier: MIT +// Copyright (c) 2018 Alexander Grün + +package dev.gruen.query.compiler; + +import dev.gruen.query.QueryNode; +import dev.gruen.query.generated.QueryBaseVisitor; +import dev.gruen.query.generated.QueryParser; +import dev.gruen.query.term.Field; +import dev.gruen.query.term.Term; +import dev.gruen.query.term.TermOperators; +import dev.gruen.query.term.Value; +import dev.gruen.query.util.CompilerUtil; + +import java.util.regex.Pattern; + +public class RegexTermVisitor extends QueryBaseVisitor { + + /** + * Creates a {@link QueryNode} that represents a regex term. + * An exception is thrown if the context cannot be converted to a node + * + * @param ctx input regex context + * @return query node + */ + @Override + public QueryNode visitRegex_term(QueryParser.Regex_termContext ctx) { + Field field = CompilerUtil.createField(ctx.variable()); + + Pattern pattern = convertPattern(ctx.REGEX().getText()); + Value value = new Value(pattern); + return new QueryNode(new Term(field, TermOperators.REGEX, value)); + } + + /** + * Converts an input string to a {@link Pattern}. + * A {@link QueryCompilerException} is thrown if the input string is not in the right format + * + * @param text input string + * @return compiled pattern + */ + private static Pattern convertPattern(String text) { + String regex = text; + if (!regex.startsWith("/") || !regex.endsWith("/")) { + throw new QueryCompilerException(String.format("wrong pattern format: %s", text)); + } + regex = regex.substring(1, regex.length() - 1); + return Pattern.compile(regex); + } +} diff --git a/src/main/java/dev/gruen/query/compiler/TermQueryVisitor.java b/src/main/java/dev/gruen/query/compiler/TermQueryVisitor.java new file mode 100644 index 0000000..698fa9f --- /dev/null +++ b/src/main/java/dev/gruen/query/compiler/TermQueryVisitor.java @@ -0,0 +1,79 @@ +// SPDX-License-Identifier: MIT +// Copyright (c) 2018 Alexander Grün + +package dev.gruen.query.compiler; + +import dev.gruen.query.QueryNode; +import dev.gruen.query.generated.QueryBaseVisitor; +import dev.gruen.query.generated.QueryParser; + +public class TermQueryVisitor extends QueryBaseVisitor { + + private final QueryContext context; + + public TermQueryVisitor(QueryContext context) { + this.context = context; + } + + + /** + * Converts the root compilation context to the root query node + * + * @param ctx root context + * @return root node + */ + @Override + public QueryNode visitCompilationUnit(QueryParser.CompilationUnitContext ctx) { + if (ctx.query() == null && ctx.full_search() == null) { + throw new QueryCompilerException("no valid query found"); + } + if (ctx.query() != null) { + return visitQuery(ctx.query()); + } else { + return visitFull_search(ctx.full_search()); + } + } + + /** + * Uses a {@link TextSearchVisitor} to convert a full text search context to a query node + * + * @param ctx full search context + * @return query node + */ + @Override + public QueryNode visitFull_search(QueryParser.Full_searchContext ctx) { + TextSearchVisitor textSearchVisitor = new TextSearchVisitor(); + return textSearchVisitor.visitFull_search(ctx); + } + + /** + * Creates a query node from a query context. + * Recursively creates all child query nodes for the root query context. + * + * @param ctx root query context + * @return query node + */ + @Override + public QueryNode visitQuery(QueryParser.QueryContext ctx) { + if (ctx.term() != null) { + return new TermVisitor(context).visitTerm(ctx.term()); + } + + if (ctx.query().size() == 1) { + // bracketed query, optionally negated + QueryNode node = visitQuery(ctx.query(0)); + if (ctx.NEGATE() != null) { + node.setNegate(!node.isNegate()); + } + return node; + } + + // binary alternative: query query, the operator is the second child + QueryNode parent = new QueryNode(); + parent.getChildren().add(visitQuery(ctx.query(0))); + parent.getChildren().add(visitQuery(ctx.query(1))); + parent.setOperator(context.getLogicalOperator(ctx.getChild(1).getText())); + return parent; + } + +} diff --git a/src/main/java/de/alexgruen/query/compiler/TermVisitor.java b/src/main/java/dev/gruen/query/compiler/TermVisitor.java similarity index 62% rename from src/main/java/de/alexgruen/query/compiler/TermVisitor.java rename to src/main/java/dev/gruen/query/compiler/TermVisitor.java index a73c77e..fe431b3 100644 --- a/src/main/java/de/alexgruen/query/compiler/TermVisitor.java +++ b/src/main/java/dev/gruen/query/compiler/TermVisitor.java @@ -1,42 +1,18 @@ -/* - * MIT License - * - * Copyright (c) 2018 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. - */ +// SPDX-License-Identifier: MIT +// Copyright (c) 2018 Alexander Grün -package de.alexgruen.query.compiler; +package dev.gruen.query.compiler; -import de.alexgruen.query.QueryNode; -import de.alexgruen.query.generated.QueryBaseVisitor; -import de.alexgruen.query.generated.QueryParser; -import de.alexgruen.query.term.Field; -import de.alexgruen.query.term.Term; -import de.alexgruen.query.term.TermOperator; -import de.alexgruen.query.term.Value; -import de.alexgruen.query.util.CompilerUtil; +import dev.gruen.query.QueryNode; +import dev.gruen.query.generated.QueryBaseVisitor; +import dev.gruen.query.generated.QueryParser; +import dev.gruen.query.term.Field; +import dev.gruen.query.term.Term; +import dev.gruen.query.term.TermOperator; +import dev.gruen.query.term.Value; +import dev.gruen.query.util.CompilerUtil; -/** - * Created by Alex on 21.05.2017. - */ public class TermVisitor extends QueryBaseVisitor { private final QueryContext context; diff --git a/src/main/java/de/alexgruen/query/compiler/TextSearchVisitor.java b/src/main/java/dev/gruen/query/compiler/TextSearchVisitor.java similarity index 57% rename from src/main/java/de/alexgruen/query/compiler/TextSearchVisitor.java rename to src/main/java/dev/gruen/query/compiler/TextSearchVisitor.java index 7665bf4..2fe8959 100644 --- a/src/main/java/de/alexgruen/query/compiler/TextSearchVisitor.java +++ b/src/main/java/dev/gruen/query/compiler/TextSearchVisitor.java @@ -1,46 +1,22 @@ -/* - * MIT License - * - * Copyright (c) 2018 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. - */ +// SPDX-License-Identifier: MIT +// Copyright (c) 2018 Alexander Grün -package de.alexgruen.query.compiler; +package dev.gruen.query.compiler; -import de.alexgruen.query.LogicalOperators; -import de.alexgruen.query.QueryNode; -import de.alexgruen.query.generated.QueryBaseVisitor; -import de.alexgruen.query.generated.QueryParser; -import de.alexgruen.query.term.Field; -import de.alexgruen.query.term.Term; -import de.alexgruen.query.term.TermOperators; -import de.alexgruen.query.term.Value; -import de.alexgruen.query.util.CompilerUtil; +import dev.gruen.query.LogicalOperators; +import dev.gruen.query.QueryNode; +import dev.gruen.query.generated.QueryBaseVisitor; +import dev.gruen.query.generated.QueryParser; +import dev.gruen.query.term.Field; +import dev.gruen.query.term.Term; +import dev.gruen.query.term.TermOperators; +import dev.gruen.query.term.Value; +import dev.gruen.query.util.CompilerUtil; import java.util.ArrayList; import java.util.List; -/** - * Created by Alex on 21.05.2017. - */ public class TextSearchVisitor extends QueryBaseVisitor { /** diff --git a/src/main/java/dev/gruen/query/compiler/parser/Parser.java b/src/main/java/dev/gruen/query/compiler/parser/Parser.java new file mode 100644 index 0000000..695c4c0 --- /dev/null +++ b/src/main/java/dev/gruen/query/compiler/parser/Parser.java @@ -0,0 +1,41 @@ +// SPDX-License-Identifier: MIT +// Copyright (c) 2018 Alexander Grün + +package dev.gruen.query.compiler.parser; + +import java.text.ParseException; + +/** + * Parses a String into an object of type T. Since this is a functional interface, parsers can be + * written as lambdas or method references, e.g. Double::parseDouble. + * + * @param type of the parsed object + */ +@FunctionalInterface +public interface Parser { + + /** + * Parse input String and returns an object of type T + * + * @param s input string + * @return resulting object + * @throws ParseException throw if there was an error during parsing + */ + T parse(String s) throws ParseException; + + /** + * Parse input String and returns an object of type T. + * If parsing doesn't work, null is returned + * + * @param s input string + * @return resulting object + */ + default T parseOrNull(String s) { + try { + return parse(s); + } catch (Exception e) { + return null; + } + } + +} diff --git a/src/main/java/dev/gruen/query/compiler/parser/ParserNotFoundException.java b/src/main/java/dev/gruen/query/compiler/parser/ParserNotFoundException.java new file mode 100644 index 0000000..2bb78dd --- /dev/null +++ b/src/main/java/dev/gruen/query/compiler/parser/ParserNotFoundException.java @@ -0,0 +1,13 @@ +// SPDX-License-Identifier: MIT +// Copyright (c) 2018 Alexander Grün + +package dev.gruen.query.compiler.parser; + +import dev.gruen.query.compiler.QueryCompilerException; + + +public class ParserNotFoundException extends QueryCompilerException { + public ParserNotFoundException(Class c) { + super("no parser found for " + c.getName()); + } +} diff --git a/src/main/java/de/alexgruen/query/compiler/parser/ParserUtil.java b/src/main/java/dev/gruen/query/compiler/parser/ParserUtil.java similarity index 56% rename from src/main/java/de/alexgruen/query/compiler/parser/ParserUtil.java rename to src/main/java/dev/gruen/query/compiler/parser/ParserUtil.java index a23122c..99389b9 100644 --- a/src/main/java/de/alexgruen/query/compiler/parser/ParserUtil.java +++ b/src/main/java/dev/gruen/query/compiler/parser/ParserUtil.java @@ -1,28 +1,7 @@ -/* - * MIT License - * - * Copyright (c) 2018 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. - */ +// SPDX-License-Identifier: MIT +// Copyright (c) 2018 Alexander Grün -package de.alexgruen.query.compiler.parser; +package dev.gruen.query.compiler.parser; import java.lang.reflect.Array; import java.text.ParseException; @@ -30,7 +9,7 @@ import java.util.concurrent.ConcurrentHashMap; /** - * Created by Alex on 04.06.2015. + * Utility class for parsing Strings to objects, using the registered {@link Parser}s. */ public class ParserUtil { private ParserUtil() { @@ -54,87 +33,30 @@ private static Map, Parser> getParserMap() { * Adds the default parsers */ private static void init() { - parserMap.put(String.class, new Parser() { - @Override - public String parse(String s) { - return s; - } - }); - - parserMap.put(Double.class, new Parser() { - @Override - public Double parse(String s) { - return Double.parseDouble(s); - } - }); - - - parserMap.put(Integer.class, new Parser() { - @Override - public Integer parse(String s) { - return Integer.parseInt(s); - } - }); - - - parserMap.put(Float.class, new Parser() { - @Override - public Float parse(String s) { - return Float.parseFloat(s); - } - }); - - parserMap.put(Long.class, new Parser() { - @Override - public Long parse(String s) { - return Long.parseLong(s); - } - }); - - parserMap.put(Boolean.class, new Parser() { - @Override - public Boolean parse(String s) throws ParseException { - if(s == null){ - throw new ParseException("illegal boolean value: null", 0); - } - s = s.toLowerCase(); - if (!( - "false".equals(s) - || "true".equals(s) - || "f".equals(s) - || "t".equals(s) - )) { - throw new ParseException(String.format("illegal boolean value: %s", s), 0); - } - return switch (s) { - case "f" -> false; - case "t" -> true; - default -> Boolean.parseBoolean(s); - }; - } - }); - - parserMap.put(Short.class, new Parser() { - @Override - public Short parse(String s) { - return Short.parseShort(s); - } - }); - - parserMap.put(Character.class, new Parser() { - @Override - public Character parse(String s) { - return s.charAt(0); - } - }); - - parserMap.put(Byte.class, new Parser() { - @Override - public Byte parse(String s) { - return Byte.parseByte(s); - } - }); + parserMap.put(String.class, (Parser) s -> s); + parserMap.put(Double.class, (Parser) Double::parseDouble); + parserMap.put(Integer.class, (Parser) Integer::parseInt); + parserMap.put(Float.class, (Parser) Float::parseFloat); + parserMap.put(Long.class, (Parser) Long::parseLong); + parserMap.put(Short.class, (Parser) Short::parseShort); + parserMap.put(Byte.class, (Parser) Byte::parseByte); + parserMap.put(Character.class, (Parser) s -> s.charAt(0)); + parserMap.put(Boolean.class, (Parser) ParserUtil::parseBoolean); + } + /** + * Parses a boolean. Accepted values are true, false, t and f + * (case insensitive). + */ + private static Boolean parseBoolean(String s) throws ParseException { + if (s == null) { + throw new ParseException("illegal boolean value: null", 0); + } + return switch (s.toLowerCase()) { + case "true", "t" -> true; + case "false", "f" -> false; + default -> throw new ParseException(String.format("illegal boolean value: %s", s), 0); + }; } diff --git a/src/main/java/dev/gruen/query/creator/LogicCreator.java b/src/main/java/dev/gruen/query/creator/LogicCreator.java new file mode 100644 index 0000000..f9488d3 --- /dev/null +++ b/src/main/java/dev/gruen/query/creator/LogicCreator.java @@ -0,0 +1,20 @@ +// SPDX-License-Identifier: MIT +// Copyright (c) 2018 Alexander Grün + +package dev.gruen.query.creator; + + +import dev.gruen.query.QueryNode; + +public interface LogicCreator extends OperatorCreator { + + /** + * Creates a new term from several input terms. + * + * @param node query node + * @param children input terms + * @return new term + */ + @SuppressWarnings("unchecked") + T create(QueryNode node, T... children); +} diff --git a/src/main/java/dev/gruen/query/creator/OperatorCreator.java b/src/main/java/dev/gruen/query/creator/OperatorCreator.java new file mode 100644 index 0000000..f4ae585 --- /dev/null +++ b/src/main/java/dev/gruen/query/creator/OperatorCreator.java @@ -0,0 +1,10 @@ +// SPDX-License-Identifier: MIT +// Copyright (c) 2018 Alexander Grün + +package dev.gruen.query.creator; + +/** + * Interface that is implemented by LogicCreators and TermCreators + */ +public interface OperatorCreator { +} diff --git a/src/main/java/de/alexgruen/query/creator/OperatorCreatorMap.java b/src/main/java/dev/gruen/query/creator/OperatorCreatorMap.java similarity index 63% rename from src/main/java/de/alexgruen/query/creator/OperatorCreatorMap.java rename to src/main/java/dev/gruen/query/creator/OperatorCreatorMap.java index 10f131e..b148da4 100644 --- a/src/main/java/de/alexgruen/query/creator/OperatorCreatorMap.java +++ b/src/main/java/dev/gruen/query/creator/OperatorCreatorMap.java @@ -1,31 +1,10 @@ -/* - * MIT License - * - * Copyright (c) 2018 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. - */ +// SPDX-License-Identifier: MIT +// Copyright (c) 2018 Alexander Grün -package de.alexgruen.query.creator; +package dev.gruen.query.creator; -import de.alexgruen.query.Operator; -import de.alexgruen.query.compiler.QueryCompilerException; +import dev.gruen.query.Operator; +import dev.gruen.query.compiler.QueryCompilerException; import java.util.ArrayList; import java.util.HashMap; @@ -34,9 +13,9 @@ /** * Map that links Operators to Creators. - * Can be used for {@link de.alexgruen.query.term.TermOperator} and {@link de.alexgruen.query.LogicalOperator} + * Can be used for {@link dev.gruen.query.term.TermOperator} and {@link dev.gruen.query.LogicalOperator} * - * @param operator type ({@link de.alexgruen.query.term.TermOperator}, {@link de.alexgruen.query.LogicalOperator}) + * @param operator type ({@link dev.gruen.query.term.TermOperator}, {@link dev.gruen.query.LogicalOperator}) * @param creator type ({@link TermCreator}, {@link LogicCreator}) */ public class OperatorCreatorMap { diff --git a/src/main/java/dev/gruen/query/creator/TermCreator.java b/src/main/java/dev/gruen/query/creator/TermCreator.java new file mode 100644 index 0000000..68d5800 --- /dev/null +++ b/src/main/java/dev/gruen/query/creator/TermCreator.java @@ -0,0 +1,20 @@ +// SPDX-License-Identifier: MIT +// Copyright (c) 2018 Alexander Grün + +package dev.gruen.query.creator; + +import dev.gruen.query.QueryNode; +import dev.gruen.query.term.Field; +import dev.gruen.query.term.Value; + +public interface TermCreator extends OperatorCreator { + /** + * Crates a Query of the desired type from a {@link Field} and {@link Value} + * + * @param node query node + * @param field input field + * @param value input value + * @return query + */ + T create(QueryNode node, Field field, Value value); +} diff --git a/src/main/java/dev/gruen/query/optimization/Optimizations.java b/src/main/java/dev/gruen/query/optimization/Optimizations.java new file mode 100644 index 0000000..81d5655 --- /dev/null +++ b/src/main/java/dev/gruen/query/optimization/Optimizations.java @@ -0,0 +1,15 @@ +// SPDX-License-Identifier: MIT +// Copyright (c) 2018 Alexander Grün + +package dev.gruen.query.optimization; + +public class Optimizations { + private Optimizations() { + throw new IllegalStateException("utility class"); + } + + /** + * Removes redundant brackets from a query tree. + */ + public static final QueryOptimization RemoveRedundantBrackets = new RemoveRedundantBrackets(); +} diff --git a/src/main/java/dev/gruen/query/optimization/QueryOptimization.java b/src/main/java/dev/gruen/query/optimization/QueryOptimization.java new file mode 100644 index 0000000..e774370 --- /dev/null +++ b/src/main/java/dev/gruen/query/optimization/QueryOptimization.java @@ -0,0 +1,15 @@ +// SPDX-License-Identifier: MIT +// Copyright (c) 2018 Alexander Grün + +package dev.gruen.query.optimization; + +import dev.gruen.query.QueryTree; + +public interface QueryOptimization { + /** + * Optimizes an input query tree. + * + * @param queryTree input query tree + */ + void apply(QueryTree queryTree); +} diff --git a/src/main/java/de/alexgruen/query/optimization/RemoveRedundantBrackets.java b/src/main/java/dev/gruen/query/optimization/RemoveRedundantBrackets.java similarity index 50% rename from src/main/java/de/alexgruen/query/optimization/RemoveRedundantBrackets.java rename to src/main/java/dev/gruen/query/optimization/RemoveRedundantBrackets.java index c478aa9..f722fc6 100644 --- a/src/main/java/de/alexgruen/query/optimization/RemoveRedundantBrackets.java +++ b/src/main/java/dev/gruen/query/optimization/RemoveRedundantBrackets.java @@ -1,31 +1,10 @@ -/* - * MIT License - * - * Copyright (c) 2018 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. - */ +// SPDX-License-Identifier: MIT +// Copyright (c) 2018 Alexander Grün -package de.alexgruen.query.optimization; +package dev.gruen.query.optimization; -import de.alexgruen.query.QueryNode; -import de.alexgruen.query.QueryTree; +import dev.gruen.query.QueryNode; +import dev.gruen.query.QueryTree; import java.util.ArrayList; import java.util.List; @@ -33,18 +12,20 @@ public class RemoveRedundantBrackets implements QueryOptimization { /** * Removes redundant brackets from a query tree. - *

+ *

{@code
      * ── AND
      * ├── (x > 1)
      * └── AND
-     * ├── (y > 2)
-     * └── (z < 3)
-     * ---->
-     * 

+ * ├── (y > 2) + * └── (z < 3) + * }

+ * becomes + *
{@code
      * ── AND
      * ├── (x > 1)
      * ├── (y > 2)
      * └── (z < 3)
+     * }
* * @param queryTree input query tree */ diff --git a/src/main/java/de/alexgruen/query/term/Field.java b/src/main/java/dev/gruen/query/term/Field.java similarity index 70% rename from src/main/java/de/alexgruen/query/term/Field.java rename to src/main/java/dev/gruen/query/term/Field.java index 6a92967..30f55a7 100644 --- a/src/main/java/de/alexgruen/query/term/Field.java +++ b/src/main/java/dev/gruen/query/term/Field.java @@ -1,30 +1,9 @@ -/* - * MIT License - * - * Copyright (c) 2018 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. - */ +// SPDX-License-Identifier: MIT +// Copyright (c) 2018 Alexander Grün -package de.alexgruen.query.term; +package dev.gruen.query.term; -import de.alexgruen.query.util.StringUtil; +import dev.gruen.query.util.StringUtil; /** * Represents the field in a query term (field operator value) @@ -67,9 +46,9 @@ public String getFullPath() { } /** - * Returns the path array (e.g. ["test", "field"] + * Returns the path array (e.g. ["test", "field"]) * - * @return + * @return path array */ public String[] getPath() { return path; @@ -87,7 +66,7 @@ public void setFullPath(String fullPath) { /** * Sets the path array * - * @param path + * @param path path array */ public void setPath(String[] path) { this.path = path; @@ -95,7 +74,7 @@ public void setPath(String[] path) { /** * Creates the joinend path string from a path array. - * from and to can be used to create the path string only from a certain range in the array + * from and to can be used to create the path string only from a certain range in the array *

* e.g. ["test", "field 1"] -> "test.'field 1'" * from : 1, to: 2 : ["test","field 1", "subfield 2", "x"] -> "'field 1'.'subfield 2'" @@ -109,7 +88,7 @@ public static String toJoinedPath(String[] path, int from, int to) { StringBuilder sb = new StringBuilder(); for (int i = from; i < to; i++) { String p = path[i]; - if (sb.length() > 0) { + if (!sb.isEmpty()) { sb.append("."); } if (StringUtil.requiresQuotation(p)) { @@ -123,7 +102,7 @@ public static String toJoinedPath(String[] path, int from, int to) { /** * Returns the length of the path array * - * @return + * @return path length */ public int getLength() { return path.length; @@ -151,6 +130,7 @@ public String getJoinedPath() { /** * Returns the joined path for this field starting at a specified index ({@link #toJoinedPath(String[], int, int)}) * + * @param from start index * @return joined path string */ public String getJoinedPath(int from) { @@ -160,6 +140,8 @@ public String getJoinedPath(int from) { /** * Returns the joined path for this field at a specified range from the path array ({@link #toJoinedPath(String[], int, int)}) * + * @param from start index + * @param to end index (exclusive) * @return joined path string */ public String getJoinedPath(int from, int to) { diff --git a/src/main/java/de/alexgruen/query/term/Term.java b/src/main/java/dev/gruen/query/term/Term.java similarity index 54% rename from src/main/java/de/alexgruen/query/term/Term.java rename to src/main/java/dev/gruen/query/term/Term.java index eae7e9f..a874cf1 100644 --- a/src/main/java/de/alexgruen/query/term/Term.java +++ b/src/main/java/dev/gruen/query/term/Term.java @@ -1,28 +1,7 @@ -/* - * MIT License - * - * Copyright (c) 2018 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. - */ +// SPDX-License-Identifier: MIT +// Copyright (c) 2018 Alexander Grün -package de.alexgruen.query.term; +package dev.gruen.query.term; /** * Represents a term within the query (field operator value) @@ -55,7 +34,7 @@ public Field getField() { } /** - * Sets the field ({@link Field} + * Sets the field ({@link Field}) * * @param field field */ @@ -64,7 +43,7 @@ public void setField(Field field) { } /** - * Returns the operator ({@link TermOperator} from this term + * Returns the operator ({@link TermOperator}) from this term * * @return operator */ @@ -75,14 +54,14 @@ public TermOperator getOperator() { /** * Sets the operator * - * @param operator + * @param operator operator */ public void setOperator(TermOperator operator) { this.operator = operator; } /** - * Returns the value ({@link Value} from this term + * Returns the value ({@link Value}) from this term * * @return value */ @@ -102,7 +81,7 @@ public void setValue(Value value) { /** * Returns a string representation of this term (field operation value) * - * @return + * @return string representation */ @Override public String toString() { diff --git a/src/main/java/dev/gruen/query/term/TermOperator.java b/src/main/java/dev/gruen/query/term/TermOperator.java new file mode 100644 index 0000000..24c370b --- /dev/null +++ b/src/main/java/dev/gruen/query/term/TermOperator.java @@ -0,0 +1,25 @@ +// SPDX-License-Identifier: MIT +// Copyright (c) 2018 Alexander Grün + +package dev.gruen.query.term; + + +import dev.gruen.query.Operator; + +/** + * Represents a term operator (==, !=, >, ...) + */ +public class TermOperator extends Operator { + + /** + * Creates a new Term operator from a name and array of aliases + * + * @param name term name + * @param aliases term aliases + */ + public TermOperator(String name, String... aliases) { + super(name, aliases); + } + + +} diff --git a/src/main/java/de/alexgruen/query/term/TermOperators.java b/src/main/java/dev/gruen/query/term/TermOperators.java similarity index 70% rename from src/main/java/de/alexgruen/query/term/TermOperators.java rename to src/main/java/dev/gruen/query/term/TermOperators.java index 809060f..fcaeec2 100644 --- a/src/main/java/de/alexgruen/query/term/TermOperators.java +++ b/src/main/java/dev/gruen/query/term/TermOperators.java @@ -1,28 +1,7 @@ -/* - * MIT License - * - * Copyright (c) 2018 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 de.alexgruen.query.term; +// SPDX-License-Identifier: MIT +// Copyright (c) 2018 Alexander Grün + +package dev.gruen.query.term; import java.util.*; diff --git a/src/main/java/de/alexgruen/query/term/Value.java b/src/main/java/dev/gruen/query/term/Value.java similarity index 83% rename from src/main/java/de/alexgruen/query/term/Value.java rename to src/main/java/dev/gruen/query/term/Value.java index 14bdb8d..095d41c 100644 --- a/src/main/java/de/alexgruen/query/term/Value.java +++ b/src/main/java/dev/gruen/query/term/Value.java @@ -1,31 +1,10 @@ -/* - * MIT License - * - * Copyright (c) 2018 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. - */ +// SPDX-License-Identifier: MIT +// Copyright (c) 2018 Alexander Grün -package de.alexgruen.query.term; +package dev.gruen.query.term; -import de.alexgruen.query.compiler.QueryCompilerException; +import dev.gruen.query.compiler.QueryCompilerException; import java.util.List; import java.util.regex.Pattern; @@ -205,7 +184,7 @@ public Pattern getPattern() { } /** - * Returns the value as String. If the value is not a String the respective toString() value is returned. + * Returns the value as String. If the value is not a String the respective toString() value is returned. * * @return String value */ diff --git a/src/main/java/de/alexgruen/query/util/CompilerUtil.java b/src/main/java/dev/gruen/query/util/CompilerUtil.java similarity index 71% rename from src/main/java/de/alexgruen/query/util/CompilerUtil.java rename to src/main/java/dev/gruen/query/util/CompilerUtil.java index df4c914..a0ff370 100644 --- a/src/main/java/de/alexgruen/query/util/CompilerUtil.java +++ b/src/main/java/dev/gruen/query/util/CompilerUtil.java @@ -1,34 +1,13 @@ -/* - * MIT License - * - * Copyright (c) 2018 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 de.alexgruen.query.util; - -import de.alexgruen.query.compiler.QueryCompilerException; -import de.alexgruen.query.compiler.parser.ParserUtil; -import de.alexgruen.query.generated.QueryParser; -import de.alexgruen.query.term.Field; -import de.alexgruen.query.term.Value; +// SPDX-License-Identifier: MIT +// Copyright (c) 2018 Alexander Grün + +package dev.gruen.query.util; + +import dev.gruen.query.compiler.QueryCompilerException; +import dev.gruen.query.compiler.parser.ParserUtil; +import dev.gruen.query.generated.QueryParser; +import dev.gruen.query.term.Field; +import dev.gruen.query.term.Value; import org.antlr.v4.runtime.tree.TerminalNode; import java.lang.reflect.Array; @@ -84,9 +63,10 @@ public static Value createValue(QueryParser.Full_search_valueContext ctx) { } /** - * Creates a Value object from the nodes in a value context + * Creates a Value object from the nodes in a value context. + * A null literal results in a {@link Value} of type {@link Value.Type#NULL}. * - * @param text node inner text + * @param text node inner text * @param nullNode null node * @param numberNode number node * @param boolNode boolean node @@ -94,7 +74,7 @@ public static Value createValue(QueryParser.Full_search_valueContext ctx) { */ public static Value createValue(String text, TerminalNode nullNode, TerminalNode numberNode, TerminalNode boolNode) { if (nullNode != null) { - return null; + return new Value(null); } if (numberNode != null) { return createNumberValue(numberNode); diff --git a/src/main/java/de/alexgruen/query/util/StringUtil.java b/src/main/java/dev/gruen/query/util/StringUtil.java similarity index 82% rename from src/main/java/de/alexgruen/query/util/StringUtil.java rename to src/main/java/dev/gruen/query/util/StringUtil.java index e405689..6098820 100644 --- a/src/main/java/de/alexgruen/query/util/StringUtil.java +++ b/src/main/java/dev/gruen/query/util/StringUtil.java @@ -1,37 +1,13 @@ -/* - * MIT License - * - * Copyright (c) 2018 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 de.alexgruen.query.util; +// SPDX-License-Identifier: MIT +// Copyright (c) 2018 Alexander Grün + +package dev.gruen.query.util; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; -/** - * Created by Alex on 15.03.2016. - */ public class StringUtil { private StringUtil() { @@ -142,7 +118,7 @@ public static String putInQuotes(String input, Character quoteChar) { /** * Split an input string at a specified split-character into several parts. - * " and ' are considered during the process. + * " and ' are considered during the process. *

"testA testB testB" -> [testA,testB,testC]

*

"'testA testB' testB" -> [testA testB,testC]

* @@ -160,7 +136,7 @@ public static String[] splitQuoted(String input, Character split) { /** * Split an input string at a specified split-character into several parts. - * " and ' are considered during the process. + * " and ' are considered during the process. *

"testA testB testB" -> [testA,testB,testC]

*

"'testA testB' testB" -> [testA testB,testC]

* diff --git a/src/test/java/dev/gruen/query/PrecedenceTest.java b/src/test/java/dev/gruen/query/PrecedenceTest.java new file mode 100644 index 0000000..d193166 --- /dev/null +++ b/src/test/java/dev/gruen/query/PrecedenceTest.java @@ -0,0 +1,71 @@ +package dev.gruen.query; + +import dev.gruen.query.compiler.QueryCompiler; +import dev.gruen.query.compiler.QueryCompilerBuilder; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +/** + * Tests the logical operators of the grammar: XOR support, operator precedence and associativity. + * Precedence from highest to lowest: AND, XOR, OR/NOR. All binary operators are left-associative. + */ +class PrecedenceTest { + + private final QueryCompiler compiler = QueryCompilerBuilder + .createDefault(PrintQuery.class, new PrintQueryCreator()) + .build(); + + private String compile(String query) { + return compiler.compile(query).toString(); + } + + @Test + void testXor() { + Assertions.assertEquals("((a == 1) XOR (b == 2))", compile("a == 1 xor b == 2")); + Assertions.assertEquals("((a == 1) XOR (b == 2))", compile("a == 1 XOR b == 2")); + } + + @Test + void testNor() { + Assertions.assertEquals("((a == 1) NOR (b == 2))", compile("a == 1 nor b == 2")); + } + + @Test + void testAndBindsTighterThanOr() { + Assertions.assertEquals("((a == 1) || ((b == 2) && (c == 3)))", compile("a == 1 || b == 2 && c == 3")); + Assertions.assertEquals("(((a == 1) && (b == 2)) || (c == 3))", compile("a == 1 && b == 2 || c == 3")); + } + + @Test + void testXorBetweenAndAndOr() { + Assertions.assertEquals("((a == 1) || ((b == 2) XOR (c == 3)))", compile("a == 1 || b == 2 xor c == 3")); + Assertions.assertEquals("(((a == 1) && (b == 2)) XOR (c == 3))", compile("a == 1 && b == 2 xor c == 3")); + } + + @Test + void testSameOperatorChainIsFlattened() { + Assertions.assertEquals("((a == 1) || (b == 2) || (c == 3))", compile("a == 1 || b == 2 || c == 3")); + } + + @Test + void testLeftAssociative() { + Assertions.assertEquals("(((a == 1) XOR (b == 2)) NOR (c == 3))", compile("a == 1 xor b == 2 nor c == 3")); + } + + @Test + void testBracketsOverridePrecedence() { + Assertions.assertEquals("(((a == 1) || (b == 2)) && (c == 3))", compile("(a == 1 || b == 2) && c == 3")); + } + + @Test + void testNegatedGroups() { + String negated = compile("a == 1 && !(b == 2 || c == 3)"); + Assertions.assertNotEquals(compile("a == 1 && (b == 2 || c == 3)"), negated); + Assertions.assertTrue(negated.contains("!")); + } + + @Test + void testDoubleNegationCancelsOut() { + Assertions.assertEquals(compile("(a == 1 || b == 2)"), compile("!(!(a == 1 || b == 2))")); + } +} diff --git a/src/test/java/de/alexgruen/query/PrintQueryCreatorTest.java b/src/test/java/dev/gruen/query/PrintQueryCreatorTest.java similarity index 96% rename from src/test/java/de/alexgruen/query/PrintQueryCreatorTest.java rename to src/test/java/dev/gruen/query/PrintQueryCreatorTest.java index e69fc6a..e5c32a0 100644 --- a/src/test/java/de/alexgruen/query/PrintQueryCreatorTest.java +++ b/src/test/java/dev/gruen/query/PrintQueryCreatorTest.java @@ -1,7 +1,7 @@ -package de.alexgruen.query; +package dev.gruen.query; -import de.alexgruen.query.term.Field; -import de.alexgruen.query.term.Value; +import dev.gruen.query.term.Field; +import dev.gruen.query.term.Value; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; diff --git a/src/test/java/dev/gruen/query/ReadmeExampleTest.java b/src/test/java/dev/gruen/query/ReadmeExampleTest.java new file mode 100644 index 0000000..cc3d05d --- /dev/null +++ b/src/test/java/dev/gruen/query/ReadmeExampleTest.java @@ -0,0 +1,77 @@ +package dev.gruen.query; + +import dev.gruen.query.compiler.QueryCompiler; +import dev.gruen.query.compiler.QueryCompilerBuilder; +import dev.gruen.query.optimization.RemoveRedundantBrackets; +import dev.gruen.query.term.TermOperators; +import dev.gruen.query.term.Value; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +import java.util.Arrays; +import java.util.Map; + +/** + * Keeps the examples from the README compiling and working. + */ +class ReadmeExampleTest { + + /** + * Target type: a filter that is evaluated against a row of values + */ + interface RowFilter extends Query { + boolean test(Map row); + } + + private static int compare(Object rowValue, Value value) { + if (rowValue instanceof Number a && value.getValue() instanceof Number b) { + return Double.compare(a.doubleValue(), b.doubleValue()); + } + return rowValue.toString().compareTo(String.valueOf(value.getValue())); + } + + private static QueryCompiler createCompiler() { + return QueryCompilerBuilder.create(RowFilter.class) + .withTermCreator(TermOperators.EQ, + (node, field, value) -> row -> row.containsKey(field.toString()) + && compare(row.get(field.toString()), value) == 0) + .withTermCreator(TermOperators.GT, + (node, field, value) -> row -> row.containsKey(field.toString()) + && compare(row.get(field.toString()), value) > 0) + .withANDCreator((node, children) -> row -> Arrays.stream(children).allMatch(c -> c.test(row))) + .withORCreator((node, children) -> row -> Arrays.stream(children).anyMatch(c -> c.test(row))) + .withOptimization(new RemoveRedundantBrackets()) + .build(); + } + + @Test + void testRowFilter() { + QueryCompiler compiler = createCompiler(); + RowFilter filter = compiler.compile("age > 18 && (country == 'DE' || country == 'AT')"); + + Assertions.assertTrue(filter.test(Map.of("age", 30, "country", "DE"))); + Assertions.assertTrue(filter.test(Map.of("age", 19, "country", "AT"))); + Assertions.assertFalse(filter.test(Map.of("age", 17, "country", "DE"))); + Assertions.assertFalse(filter.test(Map.of("age", 30, "country", "FR"))); + } + + @Test + void testPrintQuery() { + QueryCompiler compiler = QueryCompilerBuilder + .createDefault(PrintQuery.class, new PrintQueryCreator()) + .build(); + + PrintQuery query = compiler.compile("x > 0 && (y < 1 || z == 'test')"); + Assertions.assertEquals("((x > 0) && ((y < 1) || (z == 'test')))", query.toString()); + + QueryTree tree = compiler.compileTree("x > 0 && (y < 1 || z == 'test')"); + String expected = """ + ──┐ AND + ├── (x > 0) + └──┐ OR + ├── (y < 1) + └── (z == test) + """; + Assertions.assertEquals(expected, QueryPrinter.create().build().toString(tree.getRoot())); + } +} diff --git a/src/test/java/dev/gruen/query/compiler/CodeQualityTest.java b/src/test/java/dev/gruen/query/compiler/CodeQualityTest.java new file mode 100644 index 0000000..d1216f3 --- /dev/null +++ b/src/test/java/dev/gruen/query/compiler/CodeQualityTest.java @@ -0,0 +1,84 @@ +package dev.gruen.query.compiler; + +import dev.gruen.query.PrintQuery; +import dev.gruen.query.PrintQueryCreator; +import dev.gruen.query.QueryNode; +import dev.gruen.query.QueryTree; +import dev.gruen.query.optimization.Optimizations; +import dev.gruen.query.optimization.QueryOptimization; +import dev.gruen.query.term.Field; +import dev.gruen.query.term.Value; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.concurrent.atomic.AtomicReference; + +class CodeQualityTest { + + private final QueryCompiler compiler = QueryCompilerBuilder + .createDefault(PrintQuery.class, new PrintQueryCreator()) + .build(); + + @Test + void testNullLiteralIsPassedAsNullValue() { + AtomicReference received = new AtomicReference<>(); + QueryCompiler eqCompiler = QueryCompilerBuilder + .createDefault(PrintQuery.class, new PrintQueryCreator() { + @Override + public PrintQuery eq(QueryNode node, Field field, Value value) { + received.set(value); + return super.eq(node, field, value); + } + }) + .build(); + + eqCompiler.compile("x == null"); + + Assertions.assertNotNull(received.get()); + Assertions.assertTrue(received.get().isNull()); + Assertions.assertEquals(Value.Type.NULL, received.get().getType()); + } + + @Test + void testNullValuesInListAndFullText() { + Assertions.assertEquals("(x in [null, 1])", compiler.compile("x in (null, 1)").toString()); + Assertions.assertDoesNotThrow(() -> compiler.compile("null")); + } + + @Test + void testSyntaxErrorMessageContainsPositionAndQuery() { + QueryCompilerException e = Assertions.assertThrows(QueryCompilerException.class, + () -> compiler.compile("x == 1 &&& y")); + Assertions.assertTrue(e.getMessage().startsWith("syntax error at line 1, position "), e.getMessage()); + Assertions.assertTrue(e.getMessage().contains("(query: x == 1 &&& y)"), e.getMessage()); + } + + @Test + void testUnknownCustomOperatorFails() { + QueryCompilerException e = Assertions.assertThrows(QueryCompilerException.class, + () -> compiler.compile("x &= 1")); + Assertions.assertTrue(e.getMessage().contains("x &= 1"), e.getMessage()); + } + + @Test + void testNegatedEmptyNodeIsNegated() { + QueryNode empty = new QueryNode(); + empty.setNegate(true); + Assertions.assertEquals("!*", compiler.compile(new QueryTree(empty)).toString()); + } + + @Test + void testOptimizationsAreCopiedAndUnmodifiable() { + QueryCompilerBuilder builder = QueryCompilerBuilder + .createDefault(PrintQuery.class, new PrintQueryCreator()); + QueryCompiler built = builder.build(); + int size = built.getOptimizations().size(); + + builder.withOptimization(Optimizations.RemoveRedundantBrackets); + + Assertions.assertEquals(size, built.getOptimizations().size()); + List optimizations = built.getOptimizations(); + Assertions.assertThrows(UnsupportedOperationException.class, () -> optimizations.add(tree -> { })); + } +} diff --git a/src/test/java/de/alexgruen/query/compiler/CompileTest.java b/src/test/java/dev/gruen/query/compiler/CompileTest.java similarity index 87% rename from src/test/java/de/alexgruen/query/compiler/CompileTest.java rename to src/test/java/dev/gruen/query/compiler/CompileTest.java index 3c125a0..1b23f37 100644 --- a/src/test/java/de/alexgruen/query/compiler/CompileTest.java +++ b/src/test/java/dev/gruen/query/compiler/CompileTest.java @@ -1,10 +1,10 @@ -package de.alexgruen.query.compiler; +package dev.gruen.query.compiler; -import de.alexgruen.query.PrintQuery; -import de.alexgruen.query.PrintQueryCreator; -import de.alexgruen.query.QueryTree; -import de.alexgruen.query.optimization.Optimizations; -import de.alexgruen.query.term.TermOperator; +import dev.gruen.query.PrintQuery; +import dev.gruen.query.PrintQueryCreator; +import dev.gruen.query.QueryTree; +import dev.gruen.query.optimization.Optimizations; +import dev.gruen.query.term.TermOperator; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; @@ -48,8 +48,6 @@ void testCompile() { @Test void testOptimization() { - System.out.println("###### remove brackets optimization:"); - QueryCompiler noOptimizationCompiler = QueryCompilerBuilder .create(PrintQuery.class) .withQueryCreator(new PrintQueryCreator()) @@ -63,12 +61,11 @@ void testOptimization() { test("((x > 1) && ((y > 2) && z < 3))", "((x > 1) && ((y > 2) && (z < 3)))", - noOptimizationCompiler, true); + noOptimizationCompiler); - System.out.println(); test("((x > 1) && ((y > 2) && z < 3))", "((x > 1) && (y > 2) && (z < 3))", - withOptimizationCompiler, true); + withOptimizationCompiler); } @Test @@ -140,18 +137,15 @@ public String toString() { .withOptimization(Optimizations.RemoveRedundantBrackets) .build(); - test("x &= 2", "(x &= 2)", compiler, true); + test("x &= 2", "(x &= 2)", compiler); } private void test(String input, String output) { - test(input, output, PRINT_COMPILER, false); + test(input, output, PRINT_COMPILER); } - private void test(String input, String output, QueryCompiler compiler, boolean printTree) { + private void test(String input, String output, QueryCompiler compiler) { QueryTree tree = compiler.compileTree(input); - if (printTree) { - System.out.printf("%s ->%n%s%n", input, tree.toString()); - } PrintQuery p = compiler.compile(tree); Assertions.assertEquals(output, p.toString()); } diff --git a/src/test/java/de/alexgruen/query/compiler/QueryCompilerBuilderTest.java b/src/test/java/dev/gruen/query/compiler/QueryCompilerBuilderTest.java similarity index 94% rename from src/test/java/de/alexgruen/query/compiler/QueryCompilerBuilderTest.java rename to src/test/java/dev/gruen/query/compiler/QueryCompilerBuilderTest.java index f6d09bc..950c5fb 100644 --- a/src/test/java/de/alexgruen/query/compiler/QueryCompilerBuilderTest.java +++ b/src/test/java/dev/gruen/query/compiler/QueryCompilerBuilderTest.java @@ -1,14 +1,14 @@ -package de.alexgruen.query.compiler; - -import de.alexgruen.query.LogicalOperators; -import de.alexgruen.query.PrintQuery; -import de.alexgruen.query.PrintQueryCreator; -import de.alexgruen.query.creator.LogicCreator; -import de.alexgruen.query.creator.TermCreator; -import de.alexgruen.query.optimization.QueryOptimization; -import de.alexgruen.query.optimization.RemoveRedundantBrackets; -import de.alexgruen.query.term.TermOperator; -import de.alexgruen.query.term.TermOperators; +package dev.gruen.query.compiler; + +import dev.gruen.query.LogicalOperators; +import dev.gruen.query.PrintQuery; +import dev.gruen.query.PrintQueryCreator; +import dev.gruen.query.creator.LogicCreator; +import dev.gruen.query.creator.TermCreator; +import dev.gruen.query.optimization.QueryOptimization; +import dev.gruen.query.optimization.RemoveRedundantBrackets; +import dev.gruen.query.term.TermOperator; +import dev.gruen.query.term.TermOperators; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; diff --git a/src/test/java/de/alexgruen/query/compiler/QueryCompilerTest.java b/src/test/java/dev/gruen/query/compiler/QueryCompilerTest.java similarity index 94% rename from src/test/java/de/alexgruen/query/compiler/QueryCompilerTest.java rename to src/test/java/dev/gruen/query/compiler/QueryCompilerTest.java index f824af8..0b63268 100644 --- a/src/test/java/de/alexgruen/query/compiler/QueryCompilerTest.java +++ b/src/test/java/dev/gruen/query/compiler/QueryCompilerTest.java @@ -1,9 +1,9 @@ -package de.alexgruen.query.compiler; +package dev.gruen.query.compiler; -import de.alexgruen.query.PrintQuery; -import de.alexgruen.query.PrintQueryCreator; -import de.alexgruen.query.QueryTree; -import de.alexgruen.query.optimization.QueryOptimization; +import dev.gruen.query.PrintQuery; +import dev.gruen.query.PrintQueryCreator; +import dev.gruen.query.QueryTree; +import dev.gruen.query.optimization.QueryOptimization; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; diff --git a/src/test/java/de/alexgruen/query/compiler/RegexTermVisitorTest.java b/src/test/java/dev/gruen/query/compiler/RegexTermVisitorTest.java similarity index 98% rename from src/test/java/de/alexgruen/query/compiler/RegexTermVisitorTest.java rename to src/test/java/dev/gruen/query/compiler/RegexTermVisitorTest.java index 94621ac..2514662 100644 --- a/src/test/java/de/alexgruen/query/compiler/RegexTermVisitorTest.java +++ b/src/test/java/dev/gruen/query/compiler/RegexTermVisitorTest.java @@ -1,4 +1,4 @@ -package de.alexgruen.query.compiler; +package dev.gruen.query.compiler; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; diff --git a/src/test/java/de/alexgruen/query/compiler/parser/ParserTest.java b/src/test/java/dev/gruen/query/compiler/parser/ParserTest.java similarity index 90% rename from src/test/java/de/alexgruen/query/compiler/parser/ParserTest.java rename to src/test/java/dev/gruen/query/compiler/parser/ParserTest.java index c31da55..01cbb8a 100644 --- a/src/test/java/de/alexgruen/query/compiler/parser/ParserTest.java +++ b/src/test/java/dev/gruen/query/compiler/parser/ParserTest.java @@ -1,4 +1,4 @@ -package de.alexgruen.query.compiler.parser; +package dev.gruen.query.compiler.parser; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; @@ -26,7 +26,7 @@ void testParseOrNull() { Assertions.assertNull(nullResult); } - private static class TestParser extends Parser { + private static class TestParser implements Parser { @Override public Integer parse(String s) throws ParseException { try { diff --git a/src/test/java/de/alexgruen/query/compiler/parser/ParserUtilTest.java b/src/test/java/dev/gruen/query/compiler/parser/ParserUtilTest.java similarity index 99% rename from src/test/java/de/alexgruen/query/compiler/parser/ParserUtilTest.java rename to src/test/java/dev/gruen/query/compiler/parser/ParserUtilTest.java index 0ea77d1..fd63a11 100644 --- a/src/test/java/de/alexgruen/query/compiler/parser/ParserUtilTest.java +++ b/src/test/java/dev/gruen/query/compiler/parser/ParserUtilTest.java @@ -1,4 +1,4 @@ -package de.alexgruen.query.compiler.parser; +package dev.gruen.query.compiler.parser; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; diff --git a/src/test/java/de/alexgruen/query/creator/TermCreatorTest.java b/src/test/java/dev/gruen/query/creator/TermCreatorTest.java similarity index 93% rename from src/test/java/de/alexgruen/query/creator/TermCreatorTest.java rename to src/test/java/dev/gruen/query/creator/TermCreatorTest.java index 3b937c6..307eac2 100644 --- a/src/test/java/de/alexgruen/query/creator/TermCreatorTest.java +++ b/src/test/java/dev/gruen/query/creator/TermCreatorTest.java @@ -1,9 +1,9 @@ -package de.alexgruen.query.creator; +package dev.gruen.query.creator; -import de.alexgruen.query.PrintQuery; -import de.alexgruen.query.QueryNode; -import de.alexgruen.query.term.Field; -import de.alexgruen.query.term.Value; +import dev.gruen.query.PrintQuery; +import dev.gruen.query.QueryNode; +import dev.gruen.query.term.Field; +import dev.gruen.query.term.Value; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; diff --git a/src/test/java/de/alexgruen/query/term/ValueTest.java b/src/test/java/dev/gruen/query/term/ValueTest.java similarity index 98% rename from src/test/java/de/alexgruen/query/term/ValueTest.java rename to src/test/java/dev/gruen/query/term/ValueTest.java index 45df9fb..eafa491 100644 --- a/src/test/java/de/alexgruen/query/term/ValueTest.java +++ b/src/test/java/dev/gruen/query/term/ValueTest.java @@ -1,6 +1,6 @@ -package de.alexgruen.query.term; +package dev.gruen.query.term; -import de.alexgruen.query.compiler.QueryCompilerException; +import dev.gruen.query.compiler.QueryCompilerException; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; diff --git a/src/test/java/de/alexgruen/query/util/CompilerUtilTest.java b/src/test/java/dev/gruen/query/util/CompilerUtilTest.java similarity index 94% rename from src/test/java/de/alexgruen/query/util/CompilerUtilTest.java rename to src/test/java/dev/gruen/query/util/CompilerUtilTest.java index 87310f2..d48e5dd 100644 --- a/src/test/java/de/alexgruen/query/util/CompilerUtilTest.java +++ b/src/test/java/dev/gruen/query/util/CompilerUtilTest.java @@ -1,7 +1,7 @@ -package de.alexgruen.query.util; +package dev.gruen.query.util; -import de.alexgruen.query.term.Field; -import de.alexgruen.query.term.Value; +import dev.gruen.query.term.Field; +import dev.gruen.query.term.Value; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; diff --git a/src/test/java/de/alexgruen/query/util/StringTest.java b/src/test/java/dev/gruen/query/util/StringTest.java similarity index 98% rename from src/test/java/de/alexgruen/query/util/StringTest.java rename to src/test/java/dev/gruen/query/util/StringTest.java index 2be8af5..813b013 100644 --- a/src/test/java/de/alexgruen/query/util/StringTest.java +++ b/src/test/java/dev/gruen/query/util/StringTest.java @@ -1,4 +1,4 @@ -package de.alexgruen.query.util; +package dev.gruen.query.util; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test;