Debian Codegraph @

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 "errors"
9 "fmt"
10 "sort"
11 "strings"
12 )
13
14 // Builder supports building SQL statements in a DB-agnostic way.
15 // Builder mainly provides two sets of query building methods: those building SELECT statements
16 // and those manipulating DB data or schema (e.g. INSERT statements, CREATE TABLE statements).
17 type Builder interface {
18 // NewQuery creates a new Query object with the given SQL statement.
19 // The SQL statement may contain parameter placeholders which can be bound with actual parameter
20 // values before the statement is executed.
21 NewQuery(string) *Query
22 // Select returns a new SelectQuery object that can be used to build a SELECT statement.
23 // The parameters to this method should be the list column names to be selected.
24 // A column name may have an optional alias name. For example, Select("id", "my_name AS name").
25 Select(...string) *SelectQuery
26 // ModelQuery returns a new ModelQuery object that can be used to perform model insertion, update, and deletion.
27 // The parameter to this method should be a pointer to the model struct that needs to be inserted, updated, or deleted.
28 Model(interface{}) *ModelQuery
29
30 // GeneratePlaceholder generates an anonymous parameter placeholder with the given parameter ID.
31 GeneratePlaceholder(int) string
32
33 // Quote quotes a string so that it can be embedded in a SQL statement as a string value.
34 Quote(string) string
35 // QuoteSimpleTableName quotes a simple table name.
36 // A simple table name does not contain any schema prefix.
37 QuoteSimpleTableName(string) string
38 // QuoteSimpleColumnName quotes a simple column name.
39 // A simple column name does not contain any table prefix.
40 QuoteSimpleColumnName(string) string
41
42 // QueryBuilder returns the query builder supporting the current DB.
43 QueryBuilder() QueryBuilder
44
45 // Insert creates a Query that represents an INSERT SQL statement.
46 // The keys of cols are the column names, while the values of cols are the corresponding column
47 // values to be inserted.
48 Insert(table string, cols Params) *Query
49 // Upsert creates a Query that represents an UPSERT SQL statement.
50 // Upsert inserts a row into the table if the primary key or unique index is not found.
51 // Otherwise it will update the row with the new values.
52 // The keys of cols are the column names, while the values of cols are the corresponding column
53 // values to be inserted.
54 Upsert(table string, cols Params, constraints ...string) *Query
55 // Update creates a Query that represents an UPDATE SQL statement.
56 // The keys of cols are the column names, while the values of cols are the corresponding new column
57 // values. If the "where" expression is nil, the UPDATE SQL statement will have no WHERE clause
58 // (be careful in this case as the SQL statement will update ALL rows in the table).
59 Update(table string, cols Params, where Expression) *Query
60 // Delete creates a Query that represents a DELETE SQL statement.
61 // If the "where" expression is nil, the DELETE SQL statement will have no WHERE clause
62 // (be careful in this case as the SQL statement will delete ALL rows in the table).
63 Delete(table string, where Expression) *Query
64
65 // CreateTable creates a Query that represents a CREATE TABLE SQL statement.
66 // The keys of cols are the column names, while the values of cols are the corresponding column types.
67 // The optional "options" parameters will be appended to the generated SQL statement.
68 CreateTable(table string, cols map[string]string, options ...string) *Query
69 // RenameTable creates a Query that can be used to rename a table.
70 RenameTable(oldName, newName string) *Query
71 // DropTable creates a Query that can be used to drop a table.
72 DropTable(table string) *Query
73 // TruncateTable creates a Query that can be used to truncate a table.
74 TruncateTable(table string) *Query
75
76 // AddColumn creates a Query that can be used to add a column to a table.
77 AddColumn(table, col, typ string) *Query
78 // DropColumn creates a Query that can be used to drop a column from a table.
79 DropColumn(table, col string) *Query
80 // RenameColumn creates a Query that can be used to rename a column in a table.
81 RenameColumn(table, oldName, newName string) *Query
82 // AlterColumn creates a Query that can be used to change the definition of a table column.
83 AlterColumn(table, col, typ string) *Query
84
85 // AddPrimaryKey creates a Query that can be used to specify primary key(s) for a table.
86 // The "name" parameter specifies the name of the primary key constraint.
87 AddPrimaryKey(table, name string, cols ...string) *Query
88 // DropPrimaryKey creates a Query that can be used to remove the named primary key constraint from a table.
89 DropPrimaryKey(table, name string) *Query
90
91 // AddForeignKey creates a Query that can be used to add a foreign key constraint to a table.
92 // The length of cols and refCols must be the same as they refer to the primary and referential columns.
93 // The optional "options" parameters will be appended to the SQL statement. They can be used to
94 // specify options such as "ON DELETE CASCADE".
95 AddForeignKey(table, name string, cols, refCols []string, refTable string, options ...string) *Query
96 // DropForeignKey creates a Query that can be used to remove the named foreign key constraint from a table.
97 DropForeignKey(table, name string) *Query
98
99 // CreateIndex creates a Query that can be used to create an index for a table.
100 CreateIndex(table, name string, cols ...string) *Query
101 // CreateUniqueIndex creates a Query that can be used to create a unique index for a table.
102 CreateUniqueIndex(table, name string, cols ...string) *Query
103 // DropIndex creates a Query that can be used to remove the named index from a table.
104 DropIndex(table, name string) *Query
105 }
106
107 // BaseBuilder provides a basic implementation of the Builder interface.
108 type BaseBuilder struct {
109 db *DB
110 executor Executor
111 }
112
113 // NewBaseBuilder creates a new BaseBuilder instance.
114 func NewBaseBuilder(db *DB, executor Executor) *BaseBuilder {
115 return &BaseBuilder{db, executor}
116 }
117
118 // DB returns the DB instance that this builder is associated with.
119 func (b *BaseBuilder) DB() *DB {
120 return b.db
121 }
122
123 // Executor returns the executor object (a DB instance or a transaction) for executing SQL statements.
124 func (b *BaseBuilder) Executor() Executor {
125 return b.executor
126 }
127
128 // NewQuery creates a new Query object with the given SQL statement.
129 // The SQL statement may contain parameter placeholders which can be bound with actual parameter
130 // values before the statement is executed.
131 func (b *BaseBuilder) NewQuery(sql string) *Query {
132 return NewQuery(b.db, b.executor, sql)
133 }
134
135 // GeneratePlaceholder generates an anonymous parameter placeholder with the given parameter ID.
136 func (b *BaseBuilder) GeneratePlaceholder(int) string {
137 return "?"
138 }
139
140 // Quote quotes a string so that it can be embedded in a SQL statement as a string value.
141 func (b *BaseBuilder) Quote(s string) string {
142 return "'" + strings.Replace(s, "'", "''", -1) + "'"
143 }
144
145 // QuoteSimpleTableName quotes a simple table name.
146 // A simple table name does not contain any schema prefix.
147 func (b *BaseBuilder) QuoteSimpleTableName(s string) string {
148 if strings.Contains(s, `"`) {
149 return s
150 }
151 return `"` + s + `"`
152 }
153
154 // QuoteSimpleColumnName quotes a simple column name.
155 // A simple column name does not contain any table prefix.
156 func (b *BaseBuilder) QuoteSimpleColumnName(s string) string {
157 if strings.Contains(s, `"`) || s == "*" {
158 return s
159 }
160 return `"` + s + `"`
161 }
162
163 // Insert creates a Query that represents an INSERT SQL statement.
164 // The keys of cols are the column names, while the values of cols are the corresponding column
165 // values to be inserted.
166 func (b *BaseBuilder) Insert(table string, cols Params) *Query {
167 names := make([]string, 0, len(cols))
168 for name := range cols {
169 names = append(names, name)
170 }
171 sort.Strings(names)
172
173 params := Params{}
174 columns := make([]string, 0, len(names))
175 values := make([]string, 0, len(names))
176 for _, name := range names {
177 columns = append(columns, b.db.QuoteColumnName(name))
178 value := cols[name]
179 if e, ok := value.(Expression); ok {
180 values = append(values, e.Build(b.db, params))
181 } else {
182 values = append(values, fmt.Sprintf("{:p%v}", len(params)))
183 params[fmt.Sprintf("p%v", len(params))] = value
184 }
185 }
186
187 var sql string
188 if len(names) == 0 {
189 sql = fmt.Sprintf("INSERT INTO %v DEFAULT VALUES", b.db.QuoteTableName(table))
190 } else {
191 sql = fmt.Sprintf("INSERT INTO %v (%v) VALUES (%v)",
192 b.db.QuoteTableName(table),
193 strings.Join(columns, ", "),
194 strings.Join(values, ", "),
195 )
196 }
197
198 return b.NewQuery(sql).Bind(params)
199 }
200
201 // Upsert creates a Query that represents an UPSERT SQL statement.
202 // Upsert inserts a row into the table if the primary key or unique index is not found.
203 // Otherwise it will update the row with the new values.
204 // The keys of cols are the column names, while the values of cols are the corresponding column
205 // values to be inserted.
206 func (b *BaseBuilder) Upsert(table string, cols Params, constraints ...string) *Query {
207 q := b.NewQuery("")
208 q.LastError = errors.New("Upsert is not supported")
209 return q
210 }
211
212 // Update creates a Query that represents an UPDATE SQL statement.
213 // The keys of cols are the column names, while the values of cols are the corresponding new column
214 // values. If the "where" expression is nil, the UPDATE SQL statement will have no WHERE clause
215 // (be careful in this case as the SQL statement will update ALL rows in the table).
216 func (b *BaseBuilder) Update(table string, cols Params, where Expression) *Query {
217 names := make([]string, 0, len(cols))
218 for name := range cols {
219 names = append(names, name)
220 }
221 sort.Strings(names)
222
223 params := Params{}
224 lines := make([]string, 0, len(names))
225 for _, name := range names {
226 value := cols[name]
227 name = b.db.QuoteColumnName(name)
228 if e, ok := value.(Expression); ok {
229 lines = append(lines, name+"="+e.Build(b.db, params))
230 } else {
231 lines = append(lines, fmt.Sprintf("%v={:p%v}", name, len(params)))
232 params[fmt.Sprintf("p%v", len(params))] = value
233 }
234 }
235
236 sql := fmt.Sprintf("UPDATE %v SET %v", b.db.QuoteTableName(table), strings.Join(lines, ", "))
237 if where != nil {
238 w := where.Build(b.db, params)
239 if w != "" {
240 sql += " WHERE " + w
241 }
242 }
243
244 return b.NewQuery(sql).Bind(params)
245 }
246
247 // Delete creates a Query that represents a DELETE SQL statement.
248 // If the "where" expression is nil, the DELETE SQL statement will have no WHERE clause
249 // (be careful in this case as the SQL statement will delete ALL rows in the table).
250 func (b *BaseBuilder) Delete(table string, where Expression) *Query {
251 sql := "DELETE FROM " + b.db.QuoteTableName(table)
252 params := Params{}
253 if where != nil {
254 w := where.Build(b.db, params)
255 if w != "" {
256 sql += " WHERE " + w
257 }
258 }
259 return b.NewQuery(sql).Bind(params)
260 }
261
262 // CreateTable creates a Query that represents a CREATE TABLE SQL statement.
263 // The keys of cols are the column names, while the values of cols are the corresponding column types.
264 // The optional "options" parameters will be appended to the generated SQL statement.
265 func (b *BaseBuilder) CreateTable(table string, cols map[string]string, options ...string) *Query {
266 names := []string{}
267 for name := range cols {
268 names = append(names, name)
269 }
270 sort.Strings(names)
271
272 columns := []string{}
273 for _, name := range names {
274 columns = append(columns, b.db.QuoteColumnName(name)+" "+cols[name])
275 }
276
277 sql := fmt.Sprintf("CREATE TABLE %v (%v)", b.db.QuoteTableName(table), strings.Join(columns, ", "))
278 for _, opt := range options {
279 sql += " " + opt
280 }
281
282 return b.NewQuery(sql)
283 }
284
285 // RenameTable creates a Query that can be used to rename a table.
286 func (b *BaseBuilder) RenameTable(oldName, newName string) *Query {
287 sql := fmt.Sprintf("RENAME TABLE %v TO %v", b.db.QuoteTableName(oldName), b.db.QuoteTableName(newName))
288 return b.NewQuery(sql)
289 }
290
291 // DropTable creates a Query that can be used to drop a table.
292 func (b *BaseBuilder) DropTable(table string) *Query {
293 sql := "DROP TABLE " + b.db.QuoteTableName(table)
294 return b.NewQuery(sql)
295 }
296
297 // TruncateTable creates a Query that can be used to truncate a table.
298 func (b *BaseBuilder) TruncateTable(table string) *Query {
299 sql := "TRUNCATE TABLE " + b.db.QuoteTableName(table)
300 return b.NewQuery(sql)
301 }
302
303 // AddColumn creates a Query that can be used to add a column to a table.
304 func (b *BaseBuilder) AddColumn(table, col, typ string) *Query {
305 sql := fmt.Sprintf("ALTER TABLE %v ADD %v %v", b.db.QuoteTableName(table), b.db.QuoteColumnName(col), typ)
306 return b.NewQuery(sql)
307 }
308
309 // DropColumn creates a Query that can be used to drop a column from a table.
310 func (b *BaseBuilder) DropColumn(table, col string) *Query {
311 sql := fmt.Sprintf("ALTER TABLE %v DROP COLUMN %v", b.db.QuoteTableName(table), b.db.QuoteColumnName(col))
312 return b.NewQuery(sql)
313 }
314
315 // RenameColumn creates a Query that can be used to rename a column in a table.
316 func (b *BaseBuilder) RenameColumn(table, oldName, newName string) *Query {
317 sql := fmt.Sprintf("ALTER TABLE %v RENAME COLUMN %v TO %v", b.db.QuoteTableName(table), b.db.QuoteColumnName(oldName), b.db.QuoteColumnName(newName))
318 return b.NewQuery(sql)
319 }
320
321 // AlterColumn creates a Query that can be used to change the definition of a table column.
322 func (b *BaseBuilder) AlterColumn(table, col, typ string) *Query {
323 col = b.db.QuoteColumnName(col)
324 sql := fmt.Sprintf("ALTER TABLE %v CHANGE %v %v %v", b.db.QuoteTableName(table), col, col, typ)
325 return b.NewQuery(sql)
326 }
327
328 // AddPrimaryKey creates a Query that can be used to specify primary key(s) for a table.
329 // The "name" parameter specifies the name of the primary key constraint.
330 func (b *BaseBuilder) AddPrimaryKey(table, name string, cols ...string) *Query {
331 sql := fmt.Sprintf("ALTER TABLE %v ADD CONSTRAINT %v PRIMARY KEY (%v)",
332 b.db.QuoteTableName(table),
333 b.db.QuoteColumnName(name),
334 b.quoteColumns(cols))
335 return b.NewQuery(sql)
336 }
337
338 // DropPrimaryKey creates a Query that can be used to remove the named primary key constraint from a table.
339 func (b *BaseBuilder) DropPrimaryKey(table, name string) *Query {
340 sql := fmt.Sprintf("ALTER TABLE %v DROP CONSTRAINT %v", b.db.QuoteTableName(table), b.db.QuoteColumnName(name))
341 return b.NewQuery(sql)
342 }
343
344 // AddForeignKey creates a Query that can be used to add a foreign key constraint to a table.
345 // The length of cols and refCols must be the same as they refer to the primary and referential columns.
346 // The optional "options" parameters will be appended to the SQL statement. They can be used to
347 // specify options such as "ON DELETE CASCADE".
348 func (b *BaseBuilder) AddForeignKey(table, name string, cols, refCols []string, refTable string, options ...string) *Query {
349 sql := fmt.Sprintf("ALTER TABLE %v ADD CONSTRAINT %v FOREIGN KEY (%v) REFERENCES %v (%v)",
350 b.db.QuoteTableName(table),
351 b.db.QuoteColumnName(name),
352 b.quoteColumns(cols),
353 b.db.QuoteTableName(refTable),
354 b.quoteColumns(refCols))
355 for _, opt := range options {
356 sql += " " + opt
357 }
358 return b.NewQuery(sql)
359 }
360
361 // DropForeignKey creates a Query that can be used to remove the named foreign key constraint from a table.
362 func (b *BaseBuilder) DropForeignKey(table, name string) *Query {
363 sql := fmt.Sprintf("ALTER TABLE %v DROP CONSTRAINT %v", b.db.QuoteTableName(table), b.db.QuoteColumnName(name))
364 return b.NewQuery(sql)
365 }
366
367 // CreateIndex creates a Query that can be used to create an index for a table.
368 func (b *BaseBuilder) CreateIndex(table, name string, cols ...string) *Query {
369 sql := fmt.Sprintf("CREATE INDEX %v ON %v (%v)",
370 b.db.QuoteColumnName(name),
371 b.db.QuoteTableName(table),
372 b.quoteColumns(cols))
373 return b.NewQuery(sql)
374 }
375
376 // CreateUniqueIndex creates a Query that can be used to create a unique index for a table.
377 func (b *BaseBuilder) CreateUniqueIndex(table, name string, cols ...string) *Query {
378 sql := fmt.Sprintf("CREATE UNIQUE INDEX %v ON %v (%v)",
379 b.db.QuoteColumnName(name),
380 b.db.QuoteTableName(table),
381 b.quoteColumns(cols))
382 return b.NewQuery(sql)
383 }
384
385 // DropIndex creates a Query that can be used to remove the named index from a table.
386 func (b *BaseBuilder) DropIndex(table, name string) *Query {
387 sql := fmt.Sprintf("DROP INDEX %v ON %v", b.db.QuoteColumnName(name), b.db.QuoteTableName(table))
388 return b.NewQuery(sql)
389 }
390
391 // quoteColumns quotes a list of columns and concatenates them with commas.
392 func (b *BaseBuilder) quoteColumns(cols []string) string {
393 s := ""
394 for i, col := range cols {
395 if i == 0 {
396 s = b.db.QuoteColumnName(col)
397 } else {
398 s += ", " + b.db.QuoteColumnName(col)
399 }
400 }
401 return s
402 }