Skip to content

Instantly share code, notes, and snippets.

@pranavgore09
Created July 4, 2017 08:48
Show Gist options
  • Select an option

  • Save pranavgore09/34fb2793affd09e30e0525928364b837 to your computer and use it in GitHub Desktop.

Select an option

Save pranavgore09/34fb2793affd09e30e0525928364b837 to your computer and use it in GitHub Desktop.
Convert user defined Go language struct into raw sql
package main
import (
"fmt"
"strings"
)
type Node struct {
Name string
Value *string
Children []*Node
}
func main() {
planner := "planner"
osio := "openshiftio"
rhel := "rhel"
a := Node{
Name: "OR",
Value: nil,
Children: []*Node{
&Node{
Name: "AND",
Value: nil,
Children: []*Node{
&Node{
Name: "space",
Value: &osio,
Children: nil,
},
&Node{
Name: "area",
Value: &planner,
Children: nil,
},
},
},
&Node{
Name: "space",
Value: &rhel,
Children: nil,
},
},
}
b := Node{
Name: "AND",
Value: nil,
Children: []*Node{
&Node{
Name: "space",
Value: &osio,
Children: nil,
}, &Node{
Name: "area",
Value: &planner,
Children: nil,
},
},
}
fmt.Println(generateExpression(&a))
fmt.Println(generateExpression(&b))
}
func isOperator(str string) bool {
return str == "AND" || str == "OR"
}
func generateExpression(n *Node) string {
var query string
var expr []string
currentOperator := n.Name
if !isOperator(currentOperator) {
q := fmt.Sprintf("( %s = %s )", n.Name, *n.Value)
expr = append(expr, q)
}
for _, child := range n.Children {
if isOperator(child.Name) {
q := generateExpression(child)
q = fmt.Sprintf(" ( %s ) ", q)
expr = append(expr, q)
} else {
q := fmt.Sprintf(" ( %s = %s ) ", child.Name, *child.Value)
expr = append(expr, q)
}
}
query = strings.Join(expr, currentOperator)
return query
}
//$ go run main.go
// ( ( space = openshiftio ) AND ( area = planner ) ) OR ( space = rhel )
// ( space = openshiftio ) AND ( area = planner )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment