Repository navigation
Make @CompileQuery query rewriting strict and part of the build #11
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
zijian-yi
wants to merge
6
commits into
EngineeringSoftware:query-rewriting-ci
Choose a base branch
from
zijian-yi:query-rewriting-hardening
base: query-rewriting-ci
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
8742e00
Make @CompileQuery rewriting strict and part of the build
zijian-yi 1378e8c
Generate compiled-query tests under target/generated-test-sources
zijian-yi 5155853
Remove ImplCodeGen and simplify query rewriting
zijian-yi 0c88941
Refuse to clear a codegen outputDir that contains the sources
zijian-yi 03bf90b
Address review feedback on query rewriting
zijian-yi fbda3b0
Readme
zijian-yi File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,28 @@ | ||
| name: Compiled Queries CI | ||
|
|
||
| on: | ||
| push: | ||
| pull_request: | ||
|
|
||
| jobs: | ||
| compiled-queries: | ||
| runs-on: ubuntu-latest | ||
| steps: | ||
| - uses: actions/checkout@v4 | ||
|
|
||
| - uses: actions/setup-java@v4 | ||
| with: | ||
| distribution: oracle | ||
| java-version: "25" | ||
| cache: maven | ||
|
|
||
| - name: Install test-data tools | ||
| run: sudo apt-get update && sudo apt-get install -y wget zstd | ||
|
|
||
| - name: Install estore and test the codegen plugin | ||
| run: | | ||
| mvn -pl estore -am install -DskipTests -Djacoco.skip=true | ||
| mvn -pl estore-maven-plugin install | ||
|
|
||
| - name: Rewrite @CompileQuery tests and run them | ||
| run: mvn -f estore -Pcompile-queries clean test -Djacoco.skip=true -Dtest='Transformed*' |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
256 changes: 86 additions & 170 deletions
256
estore-maven-plugin/src/main/java/org/estore/CodegenMojo.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,209 +1,125 @@ | ||
| package org.estore; | ||
|
|
||
| import com.github.javaparser.StaticJavaParser; | ||
| import com.github.javaparser.ast.CompilationUnit; | ||
| import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; | ||
| import com.github.javaparser.ast.body.MethodDeclaration; | ||
| import com.github.javaparser.ast.expr.BinaryExpr; | ||
| import com.github.javaparser.ast.expr.Expression; | ||
| import com.github.javaparser.ast.expr.MethodCallExpr; | ||
| import com.github.javaparser.ast.visitor.VoidVisitorAdapter; | ||
| import java.io.File; | ||
| import java.io.FileInputStream; | ||
| import java.io.IOException; | ||
| import java.nio.charset.StandardCharsets; | ||
| import java.nio.file.Files; | ||
| import java.nio.file.Path; | ||
| import java.util.Comparator; | ||
| import java.util.List; | ||
| import java.util.Optional; | ||
| import java.util.stream.Collectors; | ||
| import org.antlr.v4.runtime.CharStreams; | ||
| import org.antlr.v4.runtime.CommonTokenStream; | ||
| import org.antlr.v4.runtime.tree.ParseTree; | ||
| import java.util.stream.Stream; | ||
| import org.apache.maven.plugin.AbstractMojo; | ||
| import org.apache.maven.plugin.MojoExecutionException; | ||
| import org.apache.maven.plugins.annotations.LifecyclePhase; | ||
| import org.apache.maven.plugins.annotations.Mojo; | ||
| import org.apache.maven.plugins.annotations.Parameter; | ||
| import org.estore.antlr4.CypherLexer; | ||
| import org.estore.antlr4.CypherParser; | ||
| import org.estore.compiler.CodeGenBuilder; | ||
|
|
||
| @Mojo(name = "codegen", defaultPhase = LifecyclePhase.PROCESS_SOURCES) | ||
| import org.apache.maven.project.MavenProject; | ||
| import org.estore.compiler.QueryCompileException; | ||
| import org.estore.compiler.QueryRewriter; | ||
|
|
||
| /** | ||
| * Rewrites the queries in every {@code @CompileQuery} method under {@code sourceDir} into Java | ||
|
gliga marked this conversation as resolved.
Resolved
|
||
| * code. Each rewritten file is written to the same package under {@code outputDir} as {@code | ||
| * Transformed<Name>.java}, and {@code outputDir} is added as a test source root. | ||
| */ | ||
| @Mojo(name = "codegen", defaultPhase = LifecyclePhase.GENERATE_TEST_SOURCES) | ||
| public class CodegenMojo extends AbstractMojo { | ||
|
|
||
| @Parameter(property = "sourceDir", defaultValue = "${project.build.testSourceDirectory}") | ||
| private File sourceDir; | ||
| File sourceDir; | ||
|
|
||
| @Parameter( | ||
| property = "outputDir", | ||
| defaultValue = "${project.build.directory}/generated-test-sources/compiled-queries") | ||
| File outputDir; | ||
|
|
||
| @Parameter(defaultValue = "${project}", readonly = true, required = true) | ||
| MavenProject project; | ||
|
|
||
| @Parameter(property = "profiling", defaultValue = "true") | ||
| private Boolean profiling; | ||
| boolean profiling; | ||
|
|
||
| @Override | ||
| public void execute() throws MojoExecutionException { | ||
| long t1 = 0; | ||
| if (profiling) { | ||
| t1 = System.currentTimeMillis(); | ||
| if (!sourceDir.isDirectory()) { | ||
| getLog().info("Skipping query rewriting: " + sourceDir + " does not exist"); | ||
| return; | ||
| } | ||
| try { | ||
| List<Path> javaFiles = | ||
| Files.walk(sourceDir.toPath()) | ||
| .filter(p -> p.toString().endsWith(".java")) | ||
| .collect(Collectors.toList()); | ||
| for (Path fp : javaFiles) { | ||
| File f = fp.toFile(); | ||
| processJavaFile(f); | ||
| long start = System.currentTimeMillis(); | ||
| deleteOutputDir(); | ||
| int rewritten = 0; | ||
| for (Path file : javaFiles()) { | ||
| if (rewriteFile(file)) { | ||
| rewritten++; | ||
| } | ||
| } catch (IOException e) { | ||
| throw new MojoExecutionException("Error processing files", e); | ||
| } | ||
| project.addTestCompileSourceRoot(outputDir.getPath()); | ||
| getLog().info( | ||
| "Rewrote @CompileQuery methods in " | ||
| + rewritten | ||
| + " file(s) into " | ||
| + outputDir); | ||
| if (profiling) { | ||
| long t2 = System.currentTimeMillis(); | ||
| System.out.println("Total Time taken: " + (t2 - t1) + " ms"); | ||
| getLog().info("Total time taken: " + (System.currentTimeMillis() - start) + " ms"); | ||
| } | ||
| } | ||
|
|
||
| private void processJavaFile(File file) throws MojoExecutionException { | ||
| try (FileInputStream in = new FileInputStream(file)) { | ||
| CompilationUnit cu = StaticJavaParser.parse(in); | ||
| boolean[] modified = {false}; | ||
| new AnnotationVisitor().visit(cu, modified); | ||
| if (modified[0]) { | ||
| // if there is a query being transformed | ||
| // add imports, rename the class, and add DFSNode class | ||
| addImports(cu); | ||
| cu.findAll(ClassOrInterfaceDeclaration.class).stream() | ||
| .filter( | ||
| c -> | ||
| c.getParentNode().isPresent() | ||
| && c.getParentNode().get() | ||
| instanceof CompilationUnit) | ||
| .forEach( | ||
| c -> { | ||
| c.setName("Transformed" + c.getNameAsString()); | ||
| c.addMember( | ||
| StaticJavaParser.parseBodyDeclaration( | ||
| createDFSNodeClass())); | ||
| }); | ||
|
|
||
| String originalFilename = file.getName(); | ||
| String newFilename = "Transformed" + originalFilename; | ||
| File newFile = new File(file.getParent(), newFilename); | ||
| Files.write(newFile.toPath(), cu.toString().getBytes()); | ||
|
|
||
| getLog().info("Transformed " + originalFilename + " to " + newFilename); | ||
| private void deleteOutputDir() throws MojoExecutionException { | ||
| Path dir = outputDir.toPath().toAbsolutePath().normalize(); | ||
| if (sourceDir.toPath().toAbsolutePath().normalize().startsWith(dir)) { | ||
| throw new MojoExecutionException( | ||
| "outputDir " | ||
| + outputDir | ||
| + " contains sourceDir " | ||
| + sourceDir | ||
| + "; it is cleared on every run, so it must be a separate directory"); | ||
| } | ||
| if (!Files.exists(dir)) { | ||
| return; | ||
| } | ||
| try (Stream<Path> paths = Files.walk(dir)) { | ||
| for (Path p : paths.sorted(Comparator.reverseOrder()).collect(Collectors.toList())) { | ||
| Files.delete(p); | ||
| } | ||
| } catch (IOException e) { | ||
| throw new MojoExecutionException("Error processing file: " + file, e); | ||
| throw new MojoExecutionException("Cannot clear stale output in " + outputDir, e); | ||
| } | ||
| } | ||
|
|
||
| private class AnnotationVisitor extends VoidVisitorAdapter<boolean[]> { | ||
| @Override | ||
| public void visit(MethodDeclaration md, boolean[] modified) { | ||
| super.visit(md, modified); | ||
| if (md.isAnnotationPresent("CompileQuery")) { | ||
| String mdName = md.getNameAsString(); | ||
| long t1 = 0; | ||
| if (profiling) { | ||
| t1 = System.currentTimeMillis(); | ||
| } | ||
| // remove the annotation to avoid re-processing | ||
| md.getAnnotations().removeIf(a -> a.getNameAsString().equals("CompileQuery")); | ||
| new QueryReplacer().visit(md, modified); | ||
| if (profiling) { | ||
| long t2 = System.currentTimeMillis(); | ||
| System.out.println( | ||
| "Time taken for method " + mdName + ": " + (t2 - t1) + " ms"); | ||
| } | ||
| } | ||
| private List<Path> javaFiles() throws MojoExecutionException { | ||
| try (Stream<Path> paths = Files.walk(sourceDir.toPath())) { | ||
| return paths.filter(p -> p.toString().endsWith(".java")).collect(Collectors.toList()); | ||
| } catch (IOException e) { | ||
| throw new MojoExecutionException("Cannot list Java files under " + sourceDir, e); | ||
| } | ||
| } | ||
|
|
||
| private class QueryReplacer extends VoidVisitorAdapter<boolean[]> { | ||
|
|
||
| @Override | ||
| public void visit(MethodCallExpr n, boolean[] modified) { | ||
| super.visit(n, modified); | ||
| if (n.getNameAsString().equals("query")) { | ||
| modified[0] = true; | ||
|
|
||
| String dbname = n.getScope().get().toString(); | ||
|
|
||
| // get the query string | ||
| String queryString = ""; | ||
| Expression expr = n.getArgument(0); | ||
| if (expr.isStringLiteralExpr()) { | ||
| queryString = expr.asStringLiteralExpr().getValue(); | ||
| } else if (expr.isBinaryExpr()) { | ||
| queryString = resolveStringConcatenation(expr); | ||
| } else { | ||
| System.out.println("Unsupported query argument type"); | ||
| System.exit(1); | ||
| } | ||
|
|
||
| CypherLexer lexer = new CypherLexer(CharStreams.fromString(queryString)); | ||
| CommonTokenStream tokenStream = new CommonTokenStream(lexer); | ||
| CypherParser parser = new CypherParser(tokenStream); | ||
| ParseTree tree = parser.oC_Cypher(); | ||
|
|
||
| CodeGenBuilder builder = new CodeGenBuilder(dbname, null); | ||
| String transformedCode = (String) builder.visit(tree); | ||
|
|
||
| try { | ||
| n.replace(StaticJavaParser.parseExpression(transformedCode)); | ||
| } catch (Exception e) { | ||
| System.out.println( | ||
| "Failed to parse transformed code for query: " + queryString); | ||
| e.printStackTrace(); | ||
| } | ||
| } | ||
| private boolean rewriteFile(Path file) throws MojoExecutionException { | ||
| Optional<String> rewritten; | ||
| try { | ||
| String source = new String(Files.readAllBytes(file), StandardCharsets.UTF_8); | ||
| rewritten = QueryRewriter.rewriteAnnotatedMethods(source); | ||
| } catch (IOException e) { | ||
| throw new MojoExecutionException("Cannot read " + file, e); | ||
| } catch (QueryCompileException e) { | ||
| throw new MojoExecutionException( | ||
| "Cannot rewrite @CompileQuery queries in " + file + ": " + e.getMessage(), e); | ||
| } | ||
| } | ||
|
|
||
| private String resolveStringConcatenation(Expression expr) { | ||
| if (expr.isStringLiteralExpr()) { | ||
| return expr.asStringLiteralExpr().getValue(); | ||
| } else if (expr.isBinaryExpr()) { | ||
| BinaryExpr binaryExpr = expr.asBinaryExpr(); | ||
| String left = resolveStringConcatenation(binaryExpr.getLeft()); | ||
| String right = resolveStringConcatenation(binaryExpr.getRight()); | ||
| return left + right; | ||
| } else { | ||
| // TODO: Handle other types of expressions (e.g., variable references) | ||
| // return expr.toString(); | ||
| System.out.println("Unsupported expression: " + expr); | ||
| System.exit(1); | ||
| return ""; | ||
| if (!rewritten.isPresent()) { | ||
| return false; | ||
| } | ||
| } | ||
|
|
||
| private static String createDFSNodeClass() { | ||
| return "private static class DFSNode {" | ||
| + "Object currentNode;" | ||
| + "int depth;" | ||
| + "DFSNode(Object currentNode, int depth) {" | ||
| + "this.currentNode = currentNode;" | ||
| + "this.depth = depth;}}"; | ||
| } | ||
|
|
||
| private void addImports(CompilationUnit cu) { | ||
| cu.addImport("java.util.function.Supplier"); | ||
| cu.addImport("java.util.Arrays"); | ||
| cu.addImport("java.util.List"); | ||
| cu.addImport("java.util.ArrayList"); | ||
| cu.addImport("java.util.HashMap"); | ||
| cu.addImport("java.util.HashSet"); | ||
| cu.addImport("java.util.Map"); | ||
| cu.addImport("java.util.Set"); | ||
| cu.addImport("java.util.Stack"); | ||
| cu.addImport("java.lang.reflect.Array"); | ||
| cu.addImport("java.lang.reflect.Field"); | ||
| cu.addImport("org.estore.compiler.Util"); | ||
| cu.addImport("org.estore.EstoreEdge"); | ||
| cu.addImport("org.estore.planner.expressions.LogicalExpr"); | ||
| cu.addImport("org.estore.planner.expressions.PropertyLookupExpr"); | ||
| cu.addImport("org.estore.planner.expressions.function.CountFunctionExpr"); | ||
| cu.addImport("org.estore.planner.expressions.function.CountFunctionSingleExpr"); | ||
| cu.addImport("org.estore.planner.expressions.VarExpr"); | ||
| cu.addImport("org.estore.planner.util.ClassInfo"); | ||
| cu.addImport("org.estore.planner.util.NodeProperty"); | ||
| cu.addImport("org.estore.planner.util.ClassHelper"); | ||
| Path packageDir = | ||
| outputDir.toPath().resolve(sourceDir.toPath().relativize(file.getParent())); | ||
| Path target = packageDir.resolve(QueryRewriter.TRANSFORMED_PREFIX + file.getFileName()); | ||
| try { | ||
| Files.createDirectories(packageDir); | ||
| Files.write(target, rewritten.get().getBytes(StandardCharsets.UTF_8)); | ||
| } catch (IOException e) { | ||
| throw new MojoExecutionException("Cannot write " + target, e); | ||
| } | ||
| getLog().info("Transformed " + file.getFileName() + " to " + target.getFileName()); | ||
| return true; | ||
| } | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
this is a good catch, but can we have this in a separate PR
the entire dependency change
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Done in #11