Debian Codegraph @

db.go

raw symbols SCIP
1 // Copyright 2016 Qiang Xue. All rights reserved.
2 // Use of this source code is governed by a MIT-style
3 // license that can be found in the LICENSE file.
4
5 // Package dbx provides a set of DB-agnostic and easy-to-use query building methods for relational databases.
6 package dbx
7
8 import (
9 "bytes"
10 "context"
11 "database/sql"
12 "regexp"
13 "strings"
14 "time"
15 )
16
17 type (
18 // LogFunc logs a message for each SQL statement being executed.
19 // This method takes one or multiple parameters. If a single parameter
20 // is provided, it will be treated as the log message. If multiple parameters
21 // are provided, they will be passed to fmt.Sprintf() to generate the log message.
22 LogFunc func(format string, a ...interface{})
23
24 // PerfFunc is called when a query finishes execution.
25 // The query execution time is passed to this function so that the DB performance
26 // can be profiled. The "ns" parameter gives the number of nanoseconds that the
27 // SQL statement takes to execute, while the "execute" parameter indicates whether
28 // the SQL statement is executed or queried (usually SELECT statements).
29 PerfFunc func(ns int64, sql string, execute bool)
30
31 // QueryLogFunc is called each time when performing a SQL query.
32 // The "t" parameter gives the time that the SQL statement takes to execute,
33 // while rows and err are the result of the query.
34 QueryLogFunc func(ctx context.Context, t time.Duration, sql string, rows *sql.Rows, err error)
35
36 // ExecLogFunc is called each time when a SQL statement is executed.
37 // The "t" parameter gives the time that the SQL statement takes to execute,
38 // while result and err refer to the result of the execution.
39 ExecLogFunc func(ctx context.Context, t time.Duration, sql string, result sql.Result, err error)
40
41 // BuilderFunc creates a Builder instance using the given DB instance and Executor.
42 BuilderFunc func(*DB, Executor) Builder
43
44 // DB enhances sql.DB by providing a set of DB-agnostic query building methods.
45 // DB allows easier query building and population of data into Go variables.
46 DB struct {
47 Builder
48
49 // FieldMapper maps struct fields to DB columns. Defaults to DefaultFieldMapFunc.
50 FieldMapper FieldMapFunc
51 // TableMapper maps structs to table names. Defaults to GetTableName.
52 TableMapper TableMapFunc
53 // LogFunc logs the SQL statements being executed. Defaults to nil, meaning no logging.
54 LogFunc LogFunc
55 // PerfFunc logs the SQL execution time. Defaults to nil, meaning no performance profiling.
56 // Deprecated: Please use QueryLogFunc and ExecLogFunc instead.
57 PerfFunc PerfFunc
58 // QueryLogFunc is called each time when performing a SQL query that returns data.
59 QueryLogFunc QueryLogFunc
60 // ExecLogFunc is called each time when a SQL statement is executed.
61 ExecLogFunc ExecLogFunc
62
63 sqlDB *sql.DB
64 driverName string
65 ctx context.Context
66 }
67
68 // Errors represents a list of errors.
69 Errors []error
70 )
71
72 // BuilderFuncMap lists supported BuilderFunc according to DB driver names.
73 // You may modify this variable to add the builder support for a new DB driver.
74 // If a DB driver is not listed here, the StandardBuilder will be used.
75 var BuilderFuncMap = map[string]BuilderFunc{
76 "sqlite": NewSqliteBuilder,
77 "sqlite3": NewSqliteBuilder,
78 "mysql": NewMysqlBuilder,
79 "postgres": NewPgsqlBuilder,
80 "pgx": NewPgsqlBuilder,
81 "mssql": NewMssqlBuilder,
82 "oci8": NewOciBuilder,
83 }
84
85 // NewFromDB encapsulates an existing database connection.
86 func NewFromDB(sqlDB *sql.DB, driverName string) *DB {
87 db := &DB{
88 driverName: driverName,
89 sqlDB: sqlDB,
90 FieldMapper: DefaultFieldMapFunc,
91 TableMapper: GetTableName,
92 }
93 db.Builder = db.newBuilder(db.sqlDB)
94 return db
95 }
96
97 // Open opens a database specified by a driver name and data source name (DSN).
98 // Note that Open does not check if DSN is specified correctly. It doesn't try to establish a DB connection either.
99 // Please refer to sql.Open() for more information.
100 func Open(driverName, dsn string) (*DB, error) {
101 sqlDB, err := sql.Open(driverName, dsn)
102 if err != nil {
103 return nil, err
104 }
105
106 return NewFromDB(sqlDB, driverName), nil
107 }
108
109 // MustOpen opens a database and establishes a connection to it.
110 // Please refer to sql.Open() and sql.Ping() for more information.
111 func MustOpen(driverName, dsn string) (*DB, error) {
112 db, err := Open(driverName, dsn)
113 if err != nil {
114 return nil, err
115 }
116 if err := db.sqlDB.Ping(); err != nil {
117 db.Close()
118 return nil, err
119 }
120 return db, nil
121 }
122
123 // Clone makes a shallow copy of DB.
124 func (db *DB) Clone() *DB {
125 db2 := &DB{
126 driverName: db.driverName,
127 sqlDB: db.sqlDB,
128 FieldMapper: db.FieldMapper,
129 TableMapper: db.TableMapper,
130 PerfFunc: db.PerfFunc,
131 LogFunc: db.LogFunc,
132 QueryLogFunc: db.QueryLogFunc,
133 ExecLogFunc: db.ExecLogFunc,
134 }
135 db2.Builder = db2.newBuilder(db.sqlDB)
136 return db2
137 }
138
139 // WithContext returns a new instance of DB associated with the given context.
140 func (db *DB) WithContext(ctx context.Context) *DB {
141 db2 := db.Clone()
142 db2.ctx = ctx
143 return db2
144 }
145
146 // Context returns the context associated with the DB instance.
147 // It returns nil if no context is associated.
148 func (db *DB) Context() context.Context {
149 return db.ctx
150 }
151
152 // DB returns the sql.DB instance encapsulated by dbx.DB.
153 func (db *DB) DB() *sql.DB {
154 return db.sqlDB
155 }
156
157 // Close closes the database, releasing any open resources.
158 // It is rare to Close a DB, as the DB handle is meant to be
159 // long-lived and shared between many goroutines.
160 func (db *DB) Close() error {
161 return db.sqlDB.Close()
162 }
163
164 // Begin starts a transaction.
165 func (db *DB) Begin() (*Tx, error) {
166 var tx *sql.Tx
167 var err error
168 if db.ctx != nil {
169 tx, err = db.sqlDB.BeginTx(db.ctx, nil)
170 } else {
171 tx, err = db.sqlDB.Begin()
172 }
173 if err != nil {
174 return nil, err
175 }
176 return &Tx{db.newBuilder(tx), tx}, nil
177 }
178
179 // BeginTx starts a transaction with the given context and transaction options.
180 func (db *DB) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) {
181 tx, err := db.sqlDB.BeginTx(ctx, opts)
182 if err != nil {
183 return nil, err
184 }
185 return &Tx{db.newBuilder(tx), tx}, nil
186 }
187
188 // Wrap encapsulates an existing transaction.
189 func (db *DB) Wrap(sqlTx *sql.Tx) *Tx {
190 return &Tx{db.newBuilder(sqlTx), sqlTx}
191 }
192
193 // Transactional starts a transaction and executes the given function.
194 // If the function returns an error, the transaction will be rolled back.
195 // Otherwise, the transaction will be committed.
196 func (db *DB) Transactional(f func(*Tx) error) (err error) {
197 tx, err := db.Begin()
198 if err != nil {
199 return err
200 }
201
202 defer func() {
203 if p := recover(); p != nil {
204 tx.Rollback()
205 panic(p)
206 } else if err != nil {
207 if err2 := tx.Rollback(); err2 != nil {
208 if err2 == sql.ErrTxDone {
209 return
210 }
211 err = Errors{err, err2}
212 }
213 } else {
214 if err = tx.Commit(); err == sql.ErrTxDone {
215 err = nil
216 }
217 }
218 }()
219
220 err = f(tx)
221
222 return err
223 }
224
225 // TransactionalContext starts a transaction and executes the given function with the given context and transaction options.
226 // If the function returns an error, the transaction will be rolled back.
227 // Otherwise, the transaction will be committed.
228 func (db *DB) TransactionalContext(ctx context.Context, opts *sql.TxOptions, f func(*Tx) error) (err error) {
229 tx, err := db.BeginTx(ctx, opts)
230 if err != nil {
231 return err
232 }
233
234 defer func() {
235 if p := recover(); p != nil {
236 tx.Rollback()
237 panic(p)
238 } else if err != nil {
239 if err2 := tx.Rollback(); err2 != nil {
240 if err2 == sql.ErrTxDone {
241 return
242 }
243 err = Errors{err, err2}
244 }
245 } else {
246 if err = tx.Commit(); err == sql.ErrTxDone {
247 err = nil
248 }
249 }
250 }()
251
252 err = f(tx)
253
254 return err
255 }
256
257 // DriverName returns the name of the DB driver.
258 func (db *DB) DriverName() string {
259 return db.driverName
260 }
261
262 // QuoteTableName quotes the given table name appropriately.
263 // If the table name contains DB schema prefix, it will be handled accordingly.
264 // This method will do nothing if the table name is already quoted or if it contains parenthesis.
265 func (db *DB) QuoteTableName(s string) string {
266 if strings.Contains(s, "(") || strings.Contains(s, "{{") {
267 return s
268 }
269 if !strings.Contains(s, ".") {
270 return db.QuoteSimpleTableName(s)
271 }
272 parts := strings.Split(s, ".")
273 for i, part := range parts {
274 parts[i] = db.QuoteSimpleTableName(part)
275 }
276 return strings.Join(parts, ".")
277 }
278
279 // QuoteColumnName quotes the given column name appropriately.
280 // If the table name contains table name prefix, it will be handled accordingly.
281 // This method will do nothing if the column name is already quoted or if it contains parenthesis.
282 func (db *DB) QuoteColumnName(s string) string {
283 if strings.Contains(s, "(") || strings.Contains(s, "{{") || strings.Contains(s, "[[") {
284 return s
285 }
286 prefix := ""
287 if pos := strings.LastIndex(s, "."); pos != -1 {
288 prefix = db.QuoteTableName(s[:pos]) + "."
289 s = s[pos+1:]
290 }
291 return prefix + db.QuoteSimpleColumnName(s)
292 }
293
294 var (
295 plRegex = regexp.MustCompile(`\{:\w+\}`)
296 quoteRegex = regexp.MustCompile(`(\{\{[\w\-\. ]+\}\}|\[\[[\w\-\. ]+\]\])`)
297 )
298
299 // processSQL replaces the named param placeholders in the given SQL with anonymous ones.
300 // It also quotes table names and column names found in the SQL if these names are enclosed
301 // within double square/curly brackets. The method will return the updated SQL and the list of parameter names.
302 func (db *DB) processSQL(s string) (string, []string) {
303 var placeholders []string
304 count := 0
305 s = plRegex.ReplaceAllStringFunc(s, func(m string) string {
306 count++
307 placeholders = append(placeholders, m[2:len(m)-1])
308 return db.GeneratePlaceholder(count)
309 })
310 s = quoteRegex.ReplaceAllStringFunc(s, func(m string) string {
311 if m[0] == '{' {
312 return db.QuoteTableName(m[2 : len(m)-2])
313 }
314 return db.QuoteColumnName(m[2 : len(m)-2])
315 })
316 return s, placeholders
317 }
318
319 // newBuilder creates a query builder based on the current driver name.
320 func (db *DB) newBuilder(executor Executor) Builder {
321 builderFunc, ok := BuilderFuncMap[db.driverName]
322 if !ok {
323 builderFunc = NewStandardBuilder
324 }
325 return builderFunc(db, executor)
326 }
327
328 // Error returns the error string of Errors.
329 func (errs Errors) Error() string {
330 var b bytes.Buffer
331 for i, e := range errs {
332 if i > 0 {
333 b.WriteRune('\n')
334 }
335 b.WriteString(e.Error())
336 }
337 return b.String()
338 }