Created
July 4, 2017 08:48
-
-
Save pranavgore09/34fb2793affd09e30e0525928364b837 to your computer and use it in GitHub Desktop.
Convert user defined Go language struct into raw sql
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
| 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