-
Notifications
You must be signed in to change notification settings - Fork 2
/
client.go
115 lines (89 loc) · 2.33 KB
/
client.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
package main
import (
"bytes"
"context"
"database/sql"
"fmt"
)
type client struct {
conn *sql.Conn
}
func (c *client) addForeignKeys(ctx context.Context, database, table string, foreignKeys []string) error {
var query bytes.Buffer
query.WriteString("ALTER TABLE ")
if database != "" {
query.Write(quoteName(database))
query.WriteByte('.')
}
query.Write(quoteName(table))
for i, fk := range foreignKeys {
if i != 0 {
query.WriteByte(',')
}
query.WriteString(" ADD ")
query.WriteString(fk)
}
return c.exec(ctx, query.String())
}
func (c *client) createTable(ctx context.Context, database, table, body string) error {
var query bytes.Buffer
query.WriteString("CREATE TABLE ")
if database != "" {
query.Write(quoteName(database))
query.WriteByte('.')
}
query.Write(quoteName(table))
query.WriteByte(' ')
query.WriteString(body)
return c.exec(ctx, query.String())
}
func (c *client) dropTableIfExists(ctx context.Context, database, table string) error {
var query bytes.Buffer
query.WriteString("DROP TABLE IF EXISTS ")
if database != "" {
query.Write(quoteName(database))
query.WriteByte('.')
}
query.Write(quoteName(table))
return c.exec(ctx, query.String())
}
func (c *client) renameTable(ctx context.Context, database, oldTable, newTable string) error {
var query bytes.Buffer
query.WriteString("RENAME TABLE ")
if database != "" {
query.Write(quoteName(database))
query.WriteByte('.')
}
query.Write(quoteName(oldTable))
query.WriteString(" TO ")
if database != "" {
query.Write(quoteName(database))
query.WriteByte('.')
}
query.Write(quoteName(newTable))
return c.exec(ctx, query.String())
}
func (c *client) setCharacterSet(ctx context.Context, charset string) error {
return c.exec(ctx, fmt.Sprintf("SET NAMES %s", charset))
}
func (c *client) setVariables(ctx context.Context, variables map[string]string) error {
var query bytes.Buffer
query.WriteString("SET ")
for name, value := range variables {
if query.Len() != 4 {
query.WriteString(", ")
}
query.WriteString("SESSION ")
query.WriteString(name)
query.WriteString(" = ")
query.WriteString(value)
}
return c.exec(ctx, query.String())
}
func (c *client) exec(ctx context.Context, query string) error {
_, err := c.conn.ExecContext(ctx, query)
return err
}
func (c *client) close() error {
return c.conn.Close()
}