Debian Codegraph @

builder_mysql.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 "fmt"
9 "regexp"
10 "sort"
11 "strings"
12 )
13
14 // MysqlBuilder is the builder for MySQL databases.
15 type MysqlBuilder struct {
16 *BaseBuilder
17 qb *BaseQueryBuilder
18 }
19
20 var _ Builder = &MysqlBuilder{}
21
22 // NewMysqlBuilder creates a new MysqlBuilder instance.
23 func NewMysqlBuilder(db *DB, executor Executor) Builder {
24 return &MysqlBuilder{
25 NewBaseBuilder(db, executor),
26 NewBaseQueryBuilder(db),
27 }
28 }
29
30 // QueryBuilder returns the query builder supporting the current DB.
31 func (b *MysqlBuilder) QueryBuilder() QueryBuilder {
32 return b.qb
33 }
34
35 // Select returns a new SelectQuery object that can be used to build a SELECT statement.
36 // The parameters to this method should be the list column names to be selected.
37 // A column name may have an optional alias name. For example, Select("id", "my_name AS name").
38 func (b *MysqlBuilder) Select(cols ...string) *SelectQuery {
39 return NewSelectQuery(b, b.db).Select(cols...)
40 }
41
42 // Model returns a new ModelQuery object that can be used to perform model-based DB operations.
43 // The model passed to this method should be a pointer to a model struct.
44 func (b *MysqlBuilder) Model(model interface{}) *ModelQuery {
45 return NewModelQuery(model, b.db.FieldMapper, b.db, b)
46 }
47
48 // QuoteSimpleTableName quotes a simple table name.
49 // A simple table name does not contain any schema prefix.
50 func (b *MysqlBuilder) QuoteSimpleTableName(s string) string {
51 if strings.ContainsAny(s, "`") {
52 return s
53 }
54 return "`" + s + "`"
55 }
56
57 // QuoteSimpleColumnName quotes a simple column name.
58 // A simple column name does not contain any table prefix.
59 func (b *MysqlBuilder) QuoteSimpleColumnName(s string) string {
60 if strings.Contains(s, "`") || s == "*" {
61 return s
62 }
63 return "`" + s + "`"
64 }
65
66 // Upsert creates a Query that represents an UPSERT SQL statement.
67 // Upsert inserts a row into the table if the primary key or unique index is not found.
68 // Otherwise it will update the row with the new values.
69 // The keys of cols are the column names, while the values of cols are the corresponding column
70 // values to be inserted.
71 func (b *MysqlBuilder) Upsert(table string, cols Params, constraints ...string) *Query {
72 q := b.Insert(table, cols)
73
74 names := []string{}
75 for name := range cols {
76 names = append(names, name)
77 }
78 sort.Strings(names)
79
80 lines := []string{}
81 for _, name := range names {
82 value := cols[name]
83 name = b.db.QuoteColumnName(name)
84 if e, ok := value.(Expression); ok {
85 lines = append(lines, name+"="+e.Build(b.db, q.params))
86 } else {
87 lines = append(lines, fmt.Sprintf("%v={:p%v}", name, len(q.params)))
88 q.params[fmt.Sprintf("p%v", len(q.params))] = value
89 }
90 }
91
92 q.sql += " ON DUPLICATE KEY UPDATE " + strings.Join(lines, ", ")
93
94 return q
95 }
96
97 var mysqlColumnRegexp = regexp.MustCompile("(?m)^\\s*[`\"](.*?)[`\"]\\s+(.*?),?$")
98
99 // RenameColumn creates a Query that can be used to rename a column in a table.
100 func (b *MysqlBuilder) RenameColumn(table, oldName, newName string) *Query {
101 qt := b.db.QuoteTableName(table)
102 sql := fmt.Sprintf("ALTER TABLE %v CHANGE %v %v", qt, b.db.QuoteColumnName(oldName), b.db.QuoteColumnName(newName))
103
104 var info struct {
105 SQL string `db:"Create Table"`
106 }
107 if err := b.db.NewQuery("SHOW CREATE TABLE " + qt).One(&info); err != nil {
108 return b.db.NewQuery(sql)
109 }
110
111 if matches := mysqlColumnRegexp.FindAllStringSubmatch(info.SQL, -1); matches != nil {
112 for _, match := range matches {
113 if match[1] == oldName {
114 sql += " " + match[2]
115 break
116 }
117 }
118 }
119
120 return b.db.NewQuery(sql)
121 }
122
123 // DropPrimaryKey creates a Query that can be used to remove the named primary key constraint from a table.
124 func (b *MysqlBuilder) DropPrimaryKey(table, name string) *Query {
125 sql := fmt.Sprintf("ALTER TABLE %v DROP PRIMARY KEY", b.db.QuoteTableName(table))
126 return b.db.NewQuery(sql)
127 }
128
129 // DropForeignKey creates a Query that can be used to remove the named foreign key constraint from a table.
130 func (b *MysqlBuilder) DropForeignKey(table, name string) *Query {
131 sql := fmt.Sprintf("ALTER TABLE %v DROP FOREIGN KEY %v", b.db.QuoteTableName(table), b.db.QuoteColumnName(name))
132 return b.db.NewQuery(sql)
133 }