forked from fenos/dqlx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
query_operation.go
92 lines (69 loc) · 2.43 KB
/
query_operation.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package dqlx
import (
"bytes"
"fmt"
"strings"
)
type queryOperation struct {
operations []edge
variables []edge
}
// QueriesToDQL returns the DQL statement for 1 or more queries
// Example: dqlx.QueriesToDQL(query1,query2,query3)
func QueriesToDQL(queries ...QueryBuilder) (query string, args map[string]string, err error) {
mainOperation := queryOperation{}
queries = ensureUniqueQueryNames(queries)
for _, query := range queries {
mainOperation.operations = append(mainOperation.operations, query.rootEdge)
for _, variable := range query.variables {
mainOperation.variables = append(mainOperation.variables, variable.rootEdge)
}
}
return mainOperation.ToDQL()
}
// ToDQL returns the DQL statement for 1 or more queries
func (grammar queryOperation) ToDQL() (query string, variables map[string]string, err error) {
variables = map[string]string{}
blocNames := make([]string, len(grammar.operations))
for index, block := range grammar.operations {
blocNames[index] = strings.Title(strings.ToLower(block.GetName()))
}
queryName := strings.Join(blocNames, "_")
var args []interface{}
var statements []string
if err := addOperation(grammar.variables, &statements, &args); err != nil {
return "", nil, err
}
if err := addOperation(grammar.operations, &statements, &args); err != nil {
return "", nil, err
}
innerQuery := strings.Join(statements, " ")
query, rawVariables := replacePlaceholders(innerQuery, args, func(index int, value interface{}) string {
return fmt.Sprintf("$%d", index)
})
variables, placeholders := toVariables(rawVariables)
writer := bytes.Buffer{}
writer.WriteString(fmt.Sprintf("query %s(%s) {", queryName, strings.Join(placeholders, ", ")))
writer.WriteString(" " + query)
writer.WriteString(" }")
return writer.String(), variables, nil
}
func ensureUniqueQueryNames(queries []QueryBuilder) []QueryBuilder {
queryNames := map[string]bool{}
uniqueQueries := make([]QueryBuilder, len(queries))
for index, query := range queries {
if queryNames[query.rootEdge.Name] {
query = query.Name(fmt.Sprintf("%s_%d", query.rootEdge.Name, index))
}
queryNames[query.rootEdge.Name] = true
uniqueQueries[index] = query
}
return uniqueQueries
}
func addOperation(operations []edge, statements *[]string, args *[]interface{}) error {
parts := make([]DQLizer, len(operations))
for index, operation := range operations {
parts[index] = operation
}
return addStatement(parts, statements, args)
}