Debian Codegraph @

query_builder.go

raw symbols SCIP
1 // Copyright 2016 Qiang Xue. All rights reserved.
2 // Use of this source code is governed by a MIT-style
3 // license that can be found in the LICENSE file.
4
5 package dbx
6
7 import (
8 "bytes"
9 "fmt"
10 "regexp"
11 "strings"
12 )
13
14 // QueryBuilder builds different clauses for a SELECT SQL statement.
15 type QueryBuilder interface {
16 // BuildSelect generates a SELECT clause from the given selected column names.
17 BuildSelect(cols []string, distinct bool, option string) string
18 // BuildFrom generates a FROM clause from the given tables.
19 BuildFrom(tables []string) string
20 // BuildGroupBy generates a GROUP BY clause from the given group-by columns.
21 BuildGroupBy(cols []string) string
22 // BuildJoin generates a JOIN clause from the given join information.
23 BuildJoin([]JoinInfo, Params) string
24 // BuildWhere generates a WHERE clause from the given expression.
25 BuildWhere(Expression, Params) string
26 // BuildHaving generates a HAVING clause from the given expression.
27 BuildHaving(Expression, Params) string
28 // BuildOrderByAndLimit generates the ORDER BY and LIMIT clauses.
29 BuildOrderByAndLimit(string, []string, int64, int64) string
30 // BuildUnion generates a UNION clause from the given union information.
31 BuildUnion([]UnionInfo, Params) string
32
33 // CombineUnion combines the nonempty unionClause with the provided sql string.
34 //
35 // The unionClause is expected to be the result of BuildUnion.
36 // If the unionClause is an empty string it returns the sql argument unmodified.
37 //
38 // This method exists as a workaround to minimize breaking changes
39 // and to allow different SQL builders to specify for example whether
40 // they support parenthesis around the UNION SQL queries
41 // (SQLite for example will throw a SyntaxError if the UNION parts are wrapped in parenthesis).
42 CombineUnion(sql string, unionClause string) string
43 }
44
45 // BaseQueryBuilder provides a basic implementation of QueryBuilder.
46 type BaseQueryBuilder struct {
47 db *DB
48 }
49
50 var _ QueryBuilder = &BaseQueryBuilder{}
51
52 // NewBaseQueryBuilder creates a new BaseQueryBuilder instance.
53 func NewBaseQueryBuilder(db *DB) *BaseQueryBuilder {
54 return &BaseQueryBuilder{db}
55 }
56
57 // DB returns the DB instance associated with the query builder.
58 func (q *BaseQueryBuilder) DB() *DB {
59 return q.db
60 }
61
62 // the regexp for columns and tables.
63 var selectRegex = regexp.MustCompile(`(?i:\s+as\s+|\s+)([\w\-_\.]+)$`)
64
65 // BuildSelect generates a SELECT clause from the given selected column names.
66 func (q *BaseQueryBuilder) BuildSelect(cols []string, distinct bool, option string) string {
67 var s bytes.Buffer
68 s.WriteString("SELECT ")
69 if distinct {
70 s.WriteString("DISTINCT ")
71 }
72 if option != "" {
73 s.WriteString(option)
74 s.WriteString(" ")
75 }
76 if len(cols) == 0 {
77 s.WriteString("*")
78 return s.String()
79 }
80
81 for i, col := range cols {
82 if i > 0 {
83 s.WriteString(", ")
84 }
85 matches := selectRegex.FindStringSubmatch(col)
86 if len(matches) == 0 {
87 s.WriteString(q.db.QuoteColumnName(col))
88 } else {
89 col := col[:len(col)-len(matches[0])]
90 alias := matches[1]
91 s.WriteString(q.db.QuoteColumnName(col) + " AS " + q.db.QuoteSimpleColumnName(alias))
92 }
93 }
94
95 return s.String()
96 }
97
98 // BuildFrom generates a FROM clause from the given tables.
99 func (q *BaseQueryBuilder) BuildFrom(tables []string) string {
100 if len(tables) == 0 {
101 return ""
102 }
103 s := ""
104 for _, table := range tables {
105 table = q.quoteTableNameAndAlias(table)
106 if s == "" {
107 s = table
108 } else {
109 s += ", " + table
110 }
111 }
112 return "FROM " + s
113 }
114
115 // BuildJoin generates a JOIN clause from the given join information.
116 func (q *BaseQueryBuilder) BuildJoin(joins []JoinInfo, params Params) string {
117 if len(joins) == 0 {
118 return ""
119 }
120 parts := []string{}
121 for _, join := range joins {
122 sql := join.Join + " " + q.quoteTableNameAndAlias(join.Table)
123 on := ""
124 if join.On != nil {
125 on = join.On.Build(q.db, params)
126 }
127 if on != "" {
128 sql += " ON " + on
129 }
130 parts = append(parts, sql)
131 }
132 return strings.Join(parts, " ")
133 }
134
135 // BuildWhere generates a WHERE clause from the given expression.
136 func (q *BaseQueryBuilder) BuildWhere(e Expression, params Params) string {
137 if e != nil {
138 if c := e.Build(q.db, params); c != "" {
139 return "WHERE " + c
140 }
141 }
142 return ""
143 }
144
145 // BuildHaving generates a HAVING clause from the given expression.
146 func (q *BaseQueryBuilder) BuildHaving(e Expression, params Params) string {
147 if e != nil {
148 if c := e.Build(q.db, params); c != "" {
149 return "HAVING " + c
150 }
151 }
152 return ""
153 }
154
155 // BuildGroupBy generates a GROUP BY clause from the given group-by columns.
156 func (q *BaseQueryBuilder) BuildGroupBy(cols []string) string {
157 if len(cols) == 0 {
158 return ""
159 }
160 s := ""
161 for i, col := range cols {
162 if i == 0 {
163 s = q.db.QuoteColumnName(col)
164 } else {
165 s += ", " + q.db.QuoteColumnName(col)
166 }
167 }
168 return "GROUP BY " + s
169 }
170
171 // BuildOrderByAndLimit generates the ORDER BY and LIMIT clauses.
172 func (q *BaseQueryBuilder) BuildOrderByAndLimit(sql string, cols []string, limit int64, offset int64) string {
173 if orderBy := q.BuildOrderBy(cols); orderBy != "" {
174 sql += " " + orderBy
175 }
176 if limit := q.BuildLimit(limit, offset); limit != "" {
177 return sql + " " + limit
178 }
179 return sql
180 }
181
182 // BuildUnion generates a UNION clause from the given union information.
183 func (q *BaseQueryBuilder) BuildUnion(unions []UnionInfo, params Params) string {
184 if len(unions) == 0 {
185 return ""
186 }
187 sql := ""
188 for i, union := range unions {
189 if i > 0 {
190 sql += " "
191 }
192 for k, v := range union.Query.params {
193 params[k] = v
194 }
195 u := "UNION"
196 if union.All {
197 u = "UNION ALL"
198 }
199 sql += fmt.Sprintf("%v (%v)", u, union.Query.sql)
200 }
201 return sql
202 }
203
204 // CombineUnion combines the nonempty unionClause with the provided sql string.
205 //
206 // The unionClause is expected to be the result of BuildUnion.
207 // If the unionClause is an empty string it returns the sql argument unmodified.
208 //
209 // This method exists as a workaround to minimize breaking changes
210 // and to allow different SQL builders to specify for example whether
211 // they support parenthesis around the UNION SQL queries
212 // (SQLite for example will throw a SyntaxError if the UNION parts are wrapped in parenthesis).
213 func (q *BaseQueryBuilder) CombineUnion(sql string, unionClause string) string {
214 if unionClause == "" {
215 return sql
216 }
217
218 return fmt.Sprintf("(%v) %v", sql, unionClause)
219 }
220
221 var orderRegex = regexp.MustCompile(`\s+((?i)ASC|DESC)$`)
222
223 // BuildOrderBy generates the ORDER BY clause.
224 func (q *BaseQueryBuilder) BuildOrderBy(cols []string) string {
225 if len(cols) == 0 {
226 return ""
227 }
228 s := ""
229 for i, col := range cols {
230 if i > 0 {
231 s += ", "
232 }
233 matches := orderRegex.FindStringSubmatch(col)
234 if len(matches) == 0 {
235 s += q.db.QuoteColumnName(col)
236 } else {
237 col := col[:len(col)-len(matches[0])]
238 dir := matches[1]
239 s += q.db.QuoteColumnName(col) + " " + dir
240 }
241 }
242 return "ORDER BY " + s
243 }
244
245 // BuildLimit generates the LIMIT clause.
246 func (q *BaseQueryBuilder) BuildLimit(limit int64, offset int64) string {
247 if limit < 0 && offset > 0 {
248 // most DBMS requires LIMIT when OFFSET is present
249 limit = 9223372036854775807 // 2^63 - 1
250 }
251
252 sql := ""
253 if limit >= 0 {
254 sql = fmt.Sprintf("LIMIT %v", limit)
255 }
256 if offset <= 0 {
257 return sql
258 }
259 if sql != "" {
260 sql += " "
261 }
262 return sql + fmt.Sprintf("OFFSET %v", offset)
263 }
264
265 func (q *BaseQueryBuilder) quoteTableNameAndAlias(table string) string {
266 matches := selectRegex.FindStringSubmatch(table)
267 if len(matches) == 0 {
268 return q.db.QuoteTableName(table)
269 }
270 table = table[:len(table)-len(matches[0])]
271 return q.db.QuoteTableName(table) + " " + q.db.QuoteSimpleTableName(matches[1])
272 }