| 1 |
// Copyright (c) 2022 Tulir Asokan |
| 2 |
// |
| 3 |
// This Source Code Form is subject to the terms of the Mozilla Public |
| 4 |
// License, v. 2.0. If a copy of the MPL was not distributed with this |
| 5 |
// file, You can obtain one at http://mozilla.org/MPL/2.0/. |
| 6 |
|
| 7 |
package dbutil |
| 8 |
|
| 9 |
import ( |
| 10 |
"context" |
| 11 |
"database/sql" |
| 12 |
"errors" |
| 13 |
"fmt" |
| 14 |
"strconv" |
| 15 |
"strings" |
| 16 |
"time" |
| 17 |
) |
| 18 |
|
| 19 |
// LoggingExecable is a wrapper for anything with database Exec methods (i.e. sql.Conn, sql.DB and sql.Tx) |
| 20 |
// that can preprocess queries (e.g. replacing $ with ? on SQLite) and log query durations. |
| 21 |
type LoggingExecable struct { |
| 22 |
UnderlyingExecable UnderlyingExecable |
| 23 |
db *Database |
| 24 |
} |
| 25 |
|
| 26 |
type pqError interface { |
| 27 |
Get(k byte) string |
| 28 |
} |
| 29 |
|
| 30 |
type PQErrorWithLine struct { |
| 31 |
Underlying error |
| 32 |
Line string |
| 33 |
} |
| 34 |
|
| 35 |
func (pqe *PQErrorWithLine) Error() string { |
| 36 |
return pqe.Underlying.Error() |
| 37 |
} |
| 38 |
|
| 39 |
func (pqe *PQErrorWithLine) Unwrap() error { |
| 40 |
return pqe.Underlying |
| 41 |
} |
| 42 |
|
| 43 |
func addErrorLine(query string, err error) error { |
| 44 |
if err == nil { |
| 45 |
return err |
| 46 |
} |
| 47 |
var pqe pqError |
| 48 |
if !errors.As(err, &pqe) { |
| 49 |
return err |
| 50 |
} |
| 51 |
pos, _ := strconv.Atoi(pqe.Get('P')) |
| 52 |
pos-- |
| 53 |
if pos <= 0 { |
| 54 |
return err |
| 55 |
} |
| 56 |
lines := strings.Split(query, "\n") |
| 57 |
for _, line := range lines { |
| 58 |
lineRunes := []rune(line) |
| 59 |
if pos < len(lineRunes)+1 { |
| 60 |
return &PQErrorWithLine{Underlying: err, Line: line} |
| 61 |
} |
| 62 |
pos -= len(lineRunes) + 1 |
| 63 |
} |
| 64 |
return err |
| 65 |
} |
| 66 |
|
| 67 |
func (le *LoggingExecable) ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error) { |
| 68 |
start := time.Now() |
| 69 |
query = le.db.mutateQuery(query) |
| 70 |
res, err := le.UnderlyingExecable.ExecContext(ctx, query, args...) |
| 71 |
err = addErrorLine(query, err) |
| 72 |
le.db.Log.QueryTiming(ctx, "Exec", query, args, -1, time.Since(start), err) |
| 73 |
return res, err |
| 74 |
} |
| 75 |
|
| 76 |
func (le *LoggingExecable) QueryContext(ctx context.Context, query string, args ...any) (Rows, error) { |
| 77 |
start := time.Now() |
| 78 |
query = le.db.mutateQuery(query) |
| 79 |
rows, err := le.UnderlyingExecable.QueryContext(ctx, query, args...) |
| 80 |
err = addErrorLine(query, err) |
| 81 |
le.db.Log.QueryTiming(ctx, "Query", query, args, -1, time.Since(start), err) |
| 82 |
return &LoggingRows{ |
| 83 |
ctx: ctx, |
| 84 |
db: le.db, |
| 85 |
query: query, |
| 86 |
args: args, |
| 87 |
rs: rows, |
| 88 |
start: start, |
| 89 |
}, err |
| 90 |
} |
| 91 |
|
| 92 |
func (le *LoggingExecable) QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row { |
| 93 |
start := time.Now() |
| 94 |
query = le.db.mutateQuery(query) |
| 95 |
row := le.UnderlyingExecable.QueryRowContext(ctx, query, args...) |
| 96 |
le.db.Log.QueryTiming(ctx, "QueryRow", query, args, -1, time.Since(start), nil) |
| 97 |
return row |
| 98 |
} |
| 99 |
|
| 100 |
func (le *LoggingExecable) beginTx(ctx context.Context, opts *sql.TxOptions) (*sql.Tx, error) { |
| 101 |
txBeginner, ok := le.UnderlyingExecable.(UnderlyingExecutableWithTx) |
| 102 |
if !ok { |
| 103 |
return nil, fmt.Errorf("can't start transaction with a %T", le.UnderlyingExecable) |
| 104 |
} |
| 105 |
return txBeginner.BeginTx(ctx, opts) |
| 106 |
} |
| 107 |
|
| 108 |
// loggingDB is a wrapper for LoggingExecable that allows access to BeginTx. |
| 109 |
// |
| 110 |
// While LoggingExecable has a pointer to the database and could use BeginTx, it's not technically safe since |
| 111 |
// the LoggingExecable could be for a transaction (where BeginTx wouldn't make sense). |
| 112 |
type loggingDB struct { |
| 113 |
LoggingExecable |
| 114 |
} |
| 115 |
|
| 116 |
type internalTxnStarter interface { |
| 117 |
beginTx(ctx context.Context, opts *sql.TxOptions) (*sql.Tx, error) |
| 118 |
} |
| 119 |
|
| 120 |
type TxnOptions struct { |
| 121 |
Isolation sql.IsolationLevel |
| 122 |
ReadOnly bool |
| 123 |
Conn Conn |
| 124 |
RetryBegin func(error, int) bool |
| 125 |
} |
| 126 |
|
| 127 |
func (ld *loggingDB) BeginTx(ctx context.Context, opts *TxnOptions) (*LoggingTxn, error) { |
| 128 |
if opts == nil { |
| 129 |
opts = &TxnOptions{} |
| 130 |
} |
| 131 |
sqlOpts := &sql.TxOptions{ |
| 132 |
Isolation: opts.Isolation, |
| 133 |
ReadOnly: opts.ReadOnly, |
| 134 |
} |
| 135 |
var tx *sql.Tx |
| 136 |
var err error |
| 137 |
start := time.Now() |
| 138 |
for i := 0; ; i++ { |
| 139 |
if opts.Conn != nil { |
| 140 |
tx, err = opts.Conn.beginTx(ctx, sqlOpts) |
| 141 |
} else { |
| 142 |
targetDB := ld.db.RawDB |
| 143 |
if opts.ReadOnly && ld.db.ReadOnlyDB != nil { |
| 144 |
targetDB = ld.db.ReadOnlyDB |
| 145 |
} |
| 146 |
tx, err = targetDB.BeginTx(ctx, sqlOpts) |
| 147 |
} |
| 148 |
if opts.RetryBegin == nil || err == nil || !opts.RetryBegin(err, i) { |
| 149 |
break |
| 150 |
} |
| 151 |
} |
| 152 |
ld.db.Log.QueryTiming(ctx, "Begin", "", nil, -1, time.Since(start), err) |
| 153 |
if err != nil { |
| 154 |
return nil, err |
| 155 |
} |
| 156 |
return &LoggingTxn{ |
| 157 |
LoggingExecable: LoggingExecable{UnderlyingExecable: tx, db: ld.db}, |
| 158 |
UnderlyingTx: tx, |
| 159 |
ctx: ctx, |
| 160 |
StartTime: start, |
| 161 |
}, nil |
| 162 |
} |
| 163 |
|
| 164 |
type LoggingTxn struct { |
| 165 |
LoggingExecable |
| 166 |
UnderlyingTx *sql.Tx |
| 167 |
ctx context.Context |
| 168 |
|
| 169 |
StartTime time.Time |
| 170 |
EndTime time.Time |
| 171 |
noTotalLog bool |
| 172 |
} |
| 173 |
|
| 174 |
func (lt *LoggingTxn) Commit() error { |
| 175 |
start := time.Now() |
| 176 |
err := lt.UnderlyingTx.Commit() |
| 177 |
lt.EndTime = time.Now() |
| 178 |
if !lt.noTotalLog { |
| 179 |
lt.db.Log.QueryTiming(lt.ctx, "<Transaction>", "", nil, -1, lt.EndTime.Sub(lt.StartTime), nil) |
| 180 |
} |
| 181 |
lt.db.Log.QueryTiming(lt.ctx, "Commit", "", nil, -1, time.Since(start), err) |
| 182 |
return err |
| 183 |
} |
| 184 |
|
| 185 |
func (lt *LoggingTxn) Rollback() error { |
| 186 |
start := time.Now() |
| 187 |
err := lt.UnderlyingTx.Rollback() |
| 188 |
lt.EndTime = time.Now() |
| 189 |
if !lt.noTotalLog { |
| 190 |
lt.db.Log.QueryTiming(lt.ctx, "<Transaction>", "", nil, -1, lt.EndTime.Sub(lt.StartTime), nil) |
| 191 |
} |
| 192 |
lt.db.Log.QueryTiming(lt.ctx, "Rollback", "", nil, -1, time.Since(start), err) |
| 193 |
return err |
| 194 |
} |
| 195 |
|
| 196 |
type LoggingRows struct { |
| 197 |
ctx context.Context |
| 198 |
db *Database |
| 199 |
query string |
| 200 |
args []any |
| 201 |
rs Rows |
| 202 |
start time.Time |
| 203 |
nrows int |
| 204 |
} |
| 205 |
|
| 206 |
func (lrs *LoggingRows) stopTiming() { |
| 207 |
if !lrs.start.IsZero() { |
| 208 |
lrs.db.Log.QueryTiming(lrs.ctx, "EndRows", lrs.query, lrs.args, lrs.nrows, time.Since(lrs.start), lrs.rs.Err()) |
| 209 |
lrs.start = time.Time{} |
| 210 |
} |
| 211 |
} |
| 212 |
|
| 213 |
func (lrs *LoggingRows) Close() error { |
| 214 |
err := lrs.rs.Close() |
| 215 |
lrs.stopTiming() |
| 216 |
return err |
| 217 |
} |
| 218 |
|
| 219 |
func (lrs *LoggingRows) ColumnTypes() ([]*sql.ColumnType, error) { |
| 220 |
return lrs.rs.ColumnTypes() |
| 221 |
} |
| 222 |
|
| 223 |
func (lrs *LoggingRows) Columns() ([]string, error) { |
| 224 |
return lrs.rs.Columns() |
| 225 |
} |
| 226 |
|
| 227 |
func (lrs *LoggingRows) Err() error { |
| 228 |
return lrs.rs.Err() |
| 229 |
} |
| 230 |
|
| 231 |
func (lrs *LoggingRows) Next() bool { |
| 232 |
hasNext := lrs.rs.Next() |
| 233 |
|
| 234 |
if !hasNext { |
| 235 |
lrs.stopTiming() |
| 236 |
} else { |
| 237 |
lrs.nrows++ |
| 238 |
} |
| 239 |
|
| 240 |
return hasNext |
| 241 |
} |
| 242 |
|
| 243 |
func (lrs *LoggingRows) NextResultSet() bool { |
| 244 |
hasNext := lrs.rs.NextResultSet() |
| 245 |
|
| 246 |
if !hasNext { |
| 247 |
lrs.stopTiming() |
| 248 |
} else { |
| 249 |
lrs.nrows++ |
| 250 |
} |
| 251 |
|
| 252 |
return hasNext |
| 253 |
} |
| 254 |
|
| 255 |
func (lrs *LoggingRows) Scan(dest ...any) error { |
| 256 |
return lrs.rs.Scan(dest...) |
| 257 |
} |