forked from grafana/grafana
-
Notifications
You must be signed in to change notification settings - Fork 0
/
postgres_dialect.go
216 lines (183 loc) · 5.23 KB
/
postgres_dialect.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
package migrator
import (
"errors"
"fmt"
"strconv"
"strings"
"github.com/lib/pq"
"github.com/grafana/grafana/pkg/util/errutil"
"xorm.io/xorm"
)
type PostgresDialect struct {
BaseDialect
}
func NewPostgresDialect(engine *xorm.Engine) Dialect {
d := PostgresDialect{}
d.BaseDialect.dialect = &d
d.BaseDialect.engine = engine
d.BaseDialect.driverName = Postgres
return &d
}
func (db *PostgresDialect) SupportEngine() bool {
return false
}
func (db *PostgresDialect) Quote(name string) string {
return "\"" + name + "\""
}
func (db *PostgresDialect) LikeStr() string {
return "ILIKE"
}
func (db *PostgresDialect) AutoIncrStr() string {
return ""
}
func (db *PostgresDialect) BooleanStr(value bool) string {
return strconv.FormatBool(value)
}
func (db *PostgresDialect) Default(col *Column) string {
if col.Type == DB_Bool {
if col.Default == "0" {
return "FALSE"
}
return "TRUE"
}
return col.Default
}
func (db *PostgresDialect) SQLType(c *Column) string {
var res string
switch t := c.Type; t {
case DB_TinyInt:
res = DB_SmallInt
return res
case DB_MediumInt, DB_Int, DB_Integer:
if c.IsAutoIncrement {
return DB_Serial
}
return DB_Integer
case DB_Serial, DB_BigSerial:
c.IsAutoIncrement = true
c.Nullable = false
res = t
case DB_Binary, DB_VarBinary:
return DB_Bytea
case DB_DateTime:
res = DB_TimeStamp
case DB_TimeStampz:
return "timestamp with time zone"
case DB_Float:
res = DB_Real
case DB_TinyText, DB_MediumText, DB_LongText:
res = DB_Text
case DB_NVarchar:
res = DB_Varchar
case DB_Uuid:
res = DB_Uuid
case DB_Blob, DB_TinyBlob, DB_MediumBlob, DB_LongBlob:
return DB_Bytea
case DB_Double:
return "DOUBLE PRECISION"
default:
if c.IsAutoIncrement {
return DB_Serial
}
res = t
}
var hasLen1 = (c.Length > 0)
var hasLen2 = (c.Length2 > 0)
if hasLen2 {
res += "(" + strconv.Itoa(c.Length) + "," + strconv.Itoa(c.Length2) + ")"
} else if hasLen1 {
res += "(" + strconv.Itoa(c.Length) + ")"
}
return res
}
func (db *PostgresDialect) IndexCheckSQL(tableName, indexName string) (string, []interface{}) {
args := []interface{}{tableName, indexName}
sql := "SELECT 1 FROM " + db.Quote("pg_indexes") + " WHERE" + db.Quote("tablename") + "=? AND " + db.Quote("indexname") + "=?"
return sql, args
}
func (db *PostgresDialect) DropIndexSQL(tableName string, index *Index) string {
quote := db.Quote
idxName := index.XName(tableName)
return fmt.Sprintf("DROP INDEX %v CASCADE", quote(idxName))
}
func (db *PostgresDialect) UpdateTableSQL(tableName string, columns []*Column) string {
var statements = []string{}
for _, col := range columns {
statements = append(statements, "ALTER "+db.Quote(col.Name)+" TYPE "+db.SQLType(col))
}
return "ALTER TABLE " + db.Quote(tableName) + " " + strings.Join(statements, ", ") + ";"
}
func (db *PostgresDialect) CleanDB() error {
sess := db.engine.NewSession()
defer sess.Close()
if _, err := sess.Exec("DROP SCHEMA public CASCADE;"); err != nil {
return errutil.Wrap("failed to drop schema public", err)
}
if _, err := sess.Exec("CREATE SCHEMA public;"); err != nil {
return errutil.Wrap("failed to create schema public", err)
}
return nil
}
// TruncateDBTables truncates all the tables.
// A special case is the dashboard_acl table where we keep the default permissions.
func (db *PostgresDialect) TruncateDBTables() error {
sess := db.engine.NewSession()
defer sess.Close()
for _, table := range db.engine.Tables {
switch table.Name {
case "":
continue
case "dashboard_acl":
// keep default dashboard permissions
if _, err := sess.Exec(fmt.Sprintf("DELETE FROM %v WHERE dashboard_id != -1 AND org_id != -1;", db.Quote(table.Name))); err != nil {
return errutil.Wrapf(err, "failed to truncate table %q", table.Name)
}
if _, err := sess.Exec(fmt.Sprintf("ALTER SEQUENCE %v RESTART WITH 3;", db.Quote(fmt.Sprintf("%v_id_seq", table.Name)))); err != nil {
return errutil.Wrapf(err, "failed to reset table %q", table.Name)
}
default:
if _, err := sess.Exec(fmt.Sprintf("TRUNCATE TABLE %v RESTART IDENTITY CASCADE;", db.Quote(table.Name))); err != nil {
if db.isUndefinedTable(err) {
continue
}
return errutil.Wrapf(err, "failed to truncate table %q", table.Name)
}
}
}
return nil
}
func (db *PostgresDialect) isThisError(err error, errcode string) bool {
var driverErr *pq.Error
if errors.As(err, &driverErr) {
if string(driverErr.Code) == errcode {
return true
}
}
return false
}
func (db *PostgresDialect) ErrorMessage(err error) string {
var driverErr *pq.Error
if errors.As(err, &driverErr) {
return driverErr.Message
}
return ""
}
func (db *PostgresDialect) isUndefinedTable(err error) bool {
return db.isThisError(err, "42P01")
}
func (db *PostgresDialect) IsUniqueConstraintViolation(err error) bool {
return db.isThisError(err, "23505")
}
func (db *PostgresDialect) IsDeadlock(err error) bool {
return db.isThisError(err, "40P01")
}
func (db *PostgresDialect) PostInsertId(table string, sess *xorm.Session) error {
if table != "org" {
return nil
}
// sync primary key sequence of org table
if _, err := sess.Exec("SELECT setval('org_id_seq', (SELECT max(id) FROM org));"); err != nil {
return errutil.Wrapf(err, "failed to sync primary key for org table")
}
return nil
}