-
Notifications
You must be signed in to change notification settings - Fork 3
/
wordpress.go
102 lines (79 loc) · 2.23 KB
/
wordpress.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
package wordpress
import (
"database/sql"
// WordPress needs mysql
"go.opencensus.io/trace"
"github.com/elgris/sqrl"
_ "github.com/go-sql-driver/mysql"
"golang.org/x/net/context"
)
type ctxKey int
var (
databaseKey interface{} = ctxKey(0)
prefixKey interface{} = ctxKey(1)
)
// WordPress represents access to the WordPress database
type WordPress struct {
db *sql.DB
TablePrefix string
}
// New creates and returns a new WordPress connection
func New(host, user, password, database string) (*WordPress, error) {
if password != "" {
user += ":" + password
}
db, err := sql.Open("mysql", user+"@"+host+"/"+database+"?parseTime=true")
if err != nil {
return nil, err
}
return &WordPress{db: db}, nil
}
// SetMaxOpenConns sets the max number open connections
func (wp *WordPress) SetMaxOpenConns(n int) {
wp.db.SetMaxOpenConns(n)
}
// Close closes the connection to the database
//
// Not very useful when the sql package is designed to have long lived connections
func (wp *WordPress) Close() error {
return wp.db.Close()
}
// NewContext returns a derived context containing the database connection
func NewContext(parent context.Context, wp *WordPress) context.Context {
parent = context.WithValue(parent, databaseKey, wp.db)
parent = context.WithValue(parent, prefixKey, wp.TablePrefix)
return parent
}
func table(c context.Context, table string) string {
prefix, ok := c.Value(prefixKey).(string)
if !ok {
panic("non-wordpress context")
}
return prefix + table
}
func database(c context.Context) *sql.DB {
db, ok := c.Value(databaseKey).(*sql.DB)
if !ok {
panic("non-wordpress context")
}
return db
}
// GetOption returns the string value of the WordPress option
func GetOption(c context.Context, name string) (string, error) {
c, span := trace.StartSpan(c, "/wordpress.GetOption")
defer span.End()
span.AddAttributes(trace.StringAttribute("wp/option/name", name))
stmt, args, err := sqrl.Select("option_value").
From(table(c, "options")).
Where(sqrl.Eq{"option_name": name}).ToSql()
if err != nil {
return "", err
}
span.AddAttributes(trace.StringAttribute("wp/query", stmt))
var value string
err = database(c).QueryRow(stmt, args...).Scan(&value)
if err != nil {
return "", err
}
return value, err
}