This repository has been archived by the owner on Feb 26, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
dialect.go
101 lines (90 loc) · 2.2 KB
/
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
// Package dialect handles differences in various
// SQL dialects.
package dialect
import (
"database/sql/driver"
"fmt"
"reflect"
"strings"
)
// Dialect provides information about an SQL dialect.
type Dialect struct {
driverTypes []string
quoteFunc func(name string) string
placeholderFunc func(n int) string
}
// PostgresDialect is a dialect for PostgreSQL.
type PostgresDialect struct {
Dialect
}
// Pre-defined dialects
var (
ANSI *Dialect
MSSQL *Dialect
MySQL *Dialect
Postgres *PostgresDialect
SQLite *Dialect
)
// Quote quotes a column name.
func (d *Dialect) Quote(name string) string {
return d.quoteFunc(name)
}
// Placeholder returns the string for a placeholder.
func (d *Dialect) Placeholder(n int) string {
if d.placeholderFunc == nil {
return "?"
}
return d.placeholderFunc(n)
}
// Match returns true if the dialect is appropriate for the driver.
func (d *Dialect) Match(drv driver.Driver) bool {
driverType := fmt.Sprint(reflect.TypeOf(drv))
for _, dt := range d.driverTypes {
if driverType == dt {
return true
}
}
return false
}
func init() {
ANSI = &Dialect{
quoteFunc: quoteFunc(`"`, `"`),
}
MSSQL = &Dialect{
quoteFunc: quoteFunc("[", "]"),
driverTypes: []string{"*mssql.MssqlDriver"},
}
MySQL = &Dialect{
quoteFunc: quoteFunc("`", "`"),
driverTypes: []string{"*mysql.MySQLDriver"},
}
SQLite = &Dialect{
quoteFunc: quoteFunc("`", "`"),
driverTypes: []string{"*sqlite3.SQLiteDriver"},
}
Postgres = &PostgresDialect{
Dialect{
quoteFunc: quoteFunc(`"`, `"`),
placeholderFunc: placeholderFunc("$%d"),
driverTypes: []string{"*pq.Driver"},
},
}
}
func quoteFunc(begin string, end string) func(name string) string {
return func(name string) string {
var names []string
for _, n := range strings.Split(name, ".") {
n = strings.TrimLeft(n, "\"`[ \t"+begin)
n = strings.TrimRight(n, "\"`] \t"+end)
names = append(names, begin+n+end)
}
return strings.Join(names, ".")
}
}
func placeholderFunc(format string) func(n int) string {
return func(n int) string {
return fmt.Sprintf(format, n)
}
}
// Postgres is a marker method that indicates the dialect is for PostgreSQL.
func (d *PostgresDialect) Postgres() {}