Debian Codegraph @

mysql/mysql.go

raw
1 // Copyright 2019 The Go Cloud Development Kit Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 // Package mysql provides functions to open MySQL databases with OpenTelemetry instrumentation.
16 package mysql
17
18 import (
19 "context"
20 "database/sql"
21 "fmt"
22 "net/url"
23 "regexp"
24 "strings"
25
26 "github.com/XSAM/otelsql"
27 "github.com/go-sql-driver/mysql"
28 "gocloud.dev/internal/openurl"
29 )
30
31 // Scheme is the URL scheme this package registers its URLOpener under on
32 // DefaultMux.
33 const Scheme = "mysql"
34
35 func init() {
36 DefaultURLMux().RegisterMySQL(Scheme, &URLOpener{})
37 }
38
39 // URLOpener opens URLs like "mysql://" by using the underlying MySQL driver.
40 // like "mysql://user:password@localhost:3306/mydb".
41 type URLOpener struct {
42 TraceOpts []otelsql.Option
43 }
44
45 // OpenMySQLURL opens a new database connection wrapped with OpenTelemetry instrumentation.
46 func (uo *URLOpener) OpenMySQLURL(_ context.Context, u *url.URL) (*sql.DB, error) {
47 cfg, err := ConfigFromURL(u)
48 if err != nil {
49 return nil, err
50 }
51 c, err := mysql.NewConnector(cfg)
52 if err != nil {
53 return nil, fmt.Errorf("mysql: could not create connector: %v", err)
54 }
55 return otelsql.OpenDB(c, uo.TraceOpts...), nil
56 }
57
58 var netAddrRE = regexp.MustCompile(`^(.+)\((.+)\)$`)
59
60 // ConfigFromURL creates a mysql.Config from URL.
61 func ConfigFromURL(u *url.URL) (cfg *mysql.Config, err error) {
62 dbName := strings.TrimPrefix(u.Path, "/")
63 if u.RawQuery != "" {
64 optDsn := fmt.Sprintf("/%s?%s", dbName, u.RawQuery)
65 if cfg, err = mysql.ParseDSN(optDsn); err != nil {
66 return nil, err
67 }
68 } else {
69 cfg = mysql.NewConfig()
70 }
71 if matches := netAddrRE.FindStringSubmatch(u.Host); len(matches) == 3 {
72 cfg.Net = matches[1]
73 cfg.Addr = matches[2]
74 } else {
75 cfg.Net = "tcp"
76 cfg.Addr = u.Host
77 }
78 cfg.User = u.User.Username()
79 cfg.Passwd, _ = u.User.Password()
80 cfg.DBName = dbName
81 cfg.AllowCleartextPasswords = true
82 cfg.AllowNativePasswords = true
83 return cfg, nil
84 }
85
86 // MySQLURLOpener implements MySQLURLOpener and can open connections based on a URL.
87 // The opener must not modify the URL argument. OpenMySQLURL must be safe to
88 // call from multiple goroutines.
89 //
90 // This interface is generally implemented by types in driver packages.
91 type MySQLURLOpener interface {
92 OpenMySQLURL(ctx context.Context, u *url.URL) (*sql.DB, error)
93 }
94
95 // URLMux is a URL opener multiplexer. It matches the scheme of the URLs
96 // against a set of registered schemes and calls the opener that matches the
97 // URL's scheme.
98 //
99 // The zero value is a multiplexer with no registered schemes.
100 type URLMux struct {
101 schemes openurl.SchemeMap
102 }
103
104 // RegisterMySQL registers the opener with the given scheme. If an opener
105 // already exists for the scheme, RegisterMySQL panics.
106 func (mux *URLMux) RegisterMySQL(scheme string, opener MySQLURLOpener) {
107 mux.schemes.Register("mysql", "DB", scheme, opener)
108 }
109
110 // OpenMySQL calls OpenMySQLURL with the URL parsed from urlstr.
111 // OpenMySQL is safe to call from multiple goroutines.
112 func (mux *URLMux) OpenMySQL(ctx context.Context, urlstr string) (*sql.DB, error) {
113 opener, u, err := mux.schemes.FromString("DB", urlstr)
114 if err != nil {
115 return nil, err
116 }
117 return opener.(MySQLURLOpener).OpenMySQLURL(ctx, u)
118 }
119
120 // OpenMySQLURL dispatches the URL to the opener that is registered with the
121 // URL's scheme. OpenMySQLURL is safe to call from multiple goroutines.
122 func (mux *URLMux) OpenMySQLURL(ctx context.Context, u *url.URL) (*sql.DB, error) {
123 opener, err := mux.schemes.FromURL("DB", u)
124 if err != nil {
125 return nil, err
126 }
127 return opener.(MySQLURLOpener).OpenMySQLURL(ctx, u)
128 }
129
130 var defaultURLMux = new(URLMux)
131
132 // DefaultURLMux returns the URLMux used by OpenMySql.
133 //
134 // Driver packages can use this to register their MySQLURLOpener on the mux.
135 func DefaultURLMux() *URLMux {
136 return defaultURLMux
137 }
138
139 // Open opens the bucket identified by the URL given. URL openers must be
140 // registered in the DefaultURLMux, which is typically done in driver
141 // packages' initialization.
142 //
143 // See the URLOpener documentation in driver subpackages for more
144 // details on supported scheme(s) and URL parameter(s).
145 func Open(ctx context.Context, urlstr string) (*sql.DB, error) {
146 return defaultURLMux.OpenMySQL(ctx, urlstr)
147 }