github.com/vescale/zgraph@v0.0.0-20230410094002-959c02d50f95/compiler/compile.go (about) 1 // Copyright 2022 zGraph Authors. All rights reserved. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package compiler 16 17 import ( 18 "github.com/vescale/zgraph/executor" 19 "github.com/vescale/zgraph/parser/ast" 20 "github.com/vescale/zgraph/planner" 21 "github.com/vescale/zgraph/stmtctx" 22 ) 23 24 // Compile compiles the statement AST node into an executable statement. The compiler relay 25 // on the statement context to retrieve some environment information and set some intermediate 26 // variables while compiling. The catalog is used to resolve names in the query. 27 func Compile(sc *stmtctx.Context, node ast.StmtNode) (executor.Executor, error) { 28 // Macro expansion 29 macroExp := NewMacroExpansion() 30 node.Accept(macroExp) 31 32 // Check the AST to ensure it is valid. 33 preprocess := NewPreprocess(sc) 34 node.Accept(preprocess) 35 err := preprocess.Error() 36 if err != nil { 37 return nil, err 38 } 39 40 // Prepare missing properties 41 propPrep := NewPropertyPreparation(sc) 42 node.Accept(propPrep) 43 err = propPrep.CreateMissing() 44 if err != nil { 45 return nil, err 46 } 47 48 // Build plan tree from a valid AST. 49 planBuilder := planner.NewBuilder(sc) 50 plan, err := planBuilder.Build(node) 51 if err != nil { 52 return nil, err 53 } 54 logicalPlan, isLogicalPlan := plan.(planner.LogicalPlan) 55 if isLogicalPlan { 56 // Optimize the logical plan and generate physical plan. 57 plan = planner.Optimize(logicalPlan) 58 } 59 60 execBuilder := executor.NewBuilder(sc) 61 exec := execBuilder.Build(plan) 62 err = execBuilder.Error() 63 if err != nil { 64 return nil, err 65 } 66 67 return exec, nil 68 }