| 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 |
"fmt" |
| 13 |
"net/url" |
| 14 |
"regexp" |
| 15 |
"strings" |
| 16 |
"time" |
| 17 |
|
| 18 |
"go.mau.fi/util/exsync" |
| 19 |
) |
| 20 |
|
| 21 |
type Dialect int |
| 22 |
|
| 23 |
const ( |
| 24 |
DialectUnknown Dialect = iota |
| 25 |
Postgres |
| 26 |
SQLite |
| 27 |
) |
| 28 |
|
| 29 |
func (dialect Dialect) String() string { |
| 30 |
switch dialect { |
| 31 |
case Postgres: |
| 32 |
return "postgres" |
| 33 |
case SQLite: |
| 34 |
return "sqlite3" |
| 35 |
default: |
| 36 |
return "" |
| 37 |
} |
| 38 |
} |
| 39 |
|
| 40 |
func ParseDialect(engine string) (Dialect, error) { |
| 41 |
engine = strings.ToLower(engine) |
| 42 |
|
| 43 |
if strings.HasPrefix(engine, "postgres") || engine == "pgx" { |
| 44 |
return Postgres, nil |
| 45 |
} else if strings.HasPrefix(engine, "sqlite") || strings.HasPrefix(engine, "litestream") { |
| 46 |
return SQLite, nil |
| 47 |
} else { |
| 48 |
return DialectUnknown, fmt.Errorf("unknown dialect '%s'", engine) |
| 49 |
} |
| 50 |
} |
| 51 |
|
| 52 |
type Rows interface { |
| 53 |
Close() error |
| 54 |
ColumnTypes() ([]*sql.ColumnType, error) |
| 55 |
Columns() ([]string, error) |
| 56 |
Err() error |
| 57 |
Next() bool |
| 58 |
NextResultSet() bool |
| 59 |
Scan(...any) error |
| 60 |
} |
| 61 |
|
| 62 |
type Scannable interface { |
| 63 |
Scan(...any) error |
| 64 |
} |
| 65 |
|
| 66 |
// Expected implementations of Scannable |
| 67 |
var ( |
| 68 |
_ Scannable = (*sql.Row)(nil) |
| 69 |
_ Scannable = (Rows)(nil) |
| 70 |
) |
| 71 |
|
| 72 |
type UnderlyingExecable interface { |
| 73 |
ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error) |
| 74 |
QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error) |
| 75 |
QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row |
| 76 |
} |
| 77 |
|
| 78 |
type UnderlyingExecutableWithTx interface { |
| 79 |
UnderlyingExecable |
| 80 |
BeginTx(ctx context.Context, opts *sql.TxOptions) (*sql.Tx, error) |
| 81 |
} |
| 82 |
|
| 83 |
type Execable interface { |
| 84 |
ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error) |
| 85 |
QueryContext(ctx context.Context, query string, args ...any) (Rows, error) |
| 86 |
QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row |
| 87 |
} |
| 88 |
|
| 89 |
type Conn interface { |
| 90 |
Execable |
| 91 |
internalTxnStarter |
| 92 |
} |
| 93 |
|
| 94 |
type Transaction interface { |
| 95 |
Execable |
| 96 |
Commit() error |
| 97 |
Rollback() error |
| 98 |
} |
| 99 |
|
| 100 |
// Expected implementations of Execable |
| 101 |
var ( |
| 102 |
_ UnderlyingExecable = (*sql.Tx)(nil) |
| 103 |
_ UnderlyingExecutableWithTx = (*sql.DB)(nil) |
| 104 |
_ UnderlyingExecutableWithTx = (*sql.Conn)(nil) |
| 105 |
_ Execable = (*LoggingExecable)(nil) |
| 106 |
_ Transaction = (*LoggingTxn)(nil) |
| 107 |
) |
| 108 |
|
| 109 |
type Database struct { |
| 110 |
LoggingDB loggingDB |
| 111 |
RawDB *sql.DB |
| 112 |
ReadOnlyDB *sql.DB |
| 113 |
Owner string |
| 114 |
VersionTable string |
| 115 |
Log DatabaseLogger |
| 116 |
Dialect Dialect |
| 117 |
UpgradeTable UpgradeTable |
| 118 |
|
| 119 |
txnCtxKey contextKey |
| 120 |
txnDeadlockMap *exsync.Set[int64] |
| 121 |
|
| 122 |
IgnoreForeignTables bool |
| 123 |
IgnoreUnsupportedDatabase bool |
| 124 |
DeadlockDetection bool |
| 125 |
} |
| 126 |
|
| 127 |
var ForceDeadlockDetection bool |
| 128 |
|
| 129 |
var positionalParamPattern = regexp.MustCompile(`\$(\d+)`) |
| 130 |
|
| 131 |
func (db *Database) mutateQuery(query string) string { |
| 132 |
switch db.Dialect { |
| 133 |
case SQLite: |
| 134 |
return positionalParamPattern.ReplaceAllString(query, "?$1") |
| 135 |
default: |
| 136 |
return query |
| 137 |
} |
| 138 |
} |
| 139 |
|
| 140 |
func (db *Database) Child(versionTable string, upgradeTable UpgradeTable, log DatabaseLogger) *Database { |
| 141 |
if log == nil { |
| 142 |
log = db.Log |
| 143 |
} |
| 144 |
return &Database{ |
| 145 |
RawDB: db.RawDB, |
| 146 |
LoggingDB: db.LoggingDB, |
| 147 |
Owner: "", |
| 148 |
VersionTable: versionTable, |
| 149 |
UpgradeTable: upgradeTable, |
| 150 |
Log: log, |
| 151 |
Dialect: db.Dialect, |
| 152 |
|
| 153 |
txnCtxKey: db.txnCtxKey, |
| 154 |
txnDeadlockMap: db.txnDeadlockMap, |
| 155 |
|
| 156 |
IgnoreForeignTables: true, |
| 157 |
IgnoreUnsupportedDatabase: db.IgnoreUnsupportedDatabase, |
| 158 |
DeadlockDetection: db.DeadlockDetection, |
| 159 |
} |
| 160 |
} |
| 161 |
|
| 162 |
func NewWithDB(db *sql.DB, rawDialect string) (*Database, error) { |
| 163 |
dialect, err := ParseDialect(rawDialect) |
| 164 |
if err != nil { |
| 165 |
return nil, err |
| 166 |
} |
| 167 |
wrappedDB := &Database{ |
| 168 |
RawDB: db, |
| 169 |
Dialect: dialect, |
| 170 |
Log: NoopLogger, |
| 171 |
|
| 172 |
IgnoreForeignTables: true, |
| 173 |
VersionTable: "version", |
| 174 |
|
| 175 |
txnCtxKey: contextKey(nextContextKeyDatabaseTransaction.Add(1)), |
| 176 |
txnDeadlockMap: exsync.NewSet[int64](), |
| 177 |
|
| 178 |
DeadlockDetection: ForceDeadlockDetection, |
| 179 |
} |
| 180 |
wrappedDB.LoggingDB.UnderlyingExecable = db |
| 181 |
wrappedDB.LoggingDB.db = wrappedDB |
| 182 |
return wrappedDB, nil |
| 183 |
} |
| 184 |
|
| 185 |
func NewWithDialect(uri, rawDialect string) (*Database, error) { |
| 186 |
db, err := sql.Open(rawDialect, uri) |
| 187 |
if err != nil { |
| 188 |
return nil, err |
| 189 |
} |
| 190 |
|
| 191 |
return NewWithDB(db, rawDialect) |
| 192 |
} |
| 193 |
|
| 194 |
type PoolConfig struct { |
| 195 |
Type string `yaml:"type"` |
| 196 |
URI string `yaml:"uri"` |
| 197 |
|
| 198 |
MaxOpenConns int `yaml:"max_open_conns"` |
| 199 |
MaxIdleConns int `yaml:"max_idle_conns"` |
| 200 |
|
| 201 |
ConnMaxIdleTime string `yaml:"conn_max_idle_time"` |
| 202 |
ConnMaxLifetime string `yaml:"conn_max_lifetime"` |
| 203 |
} |
| 204 |
|
| 205 |
type Config struct { |
| 206 |
PoolConfig `yaml:",inline"` |
| 207 |
ReadOnlyPool PoolConfig `yaml:"ro_pool"` |
| 208 |
|
| 209 |
DeadlockDetection bool `yaml:"deadlock_detection"` |
| 210 |
} |
| 211 |
|
| 212 |
func (db *Database) Close() error { |
| 213 |
err := db.RawDB.Close() |
| 214 |
if db.ReadOnlyDB != nil { |
| 215 |
if err2 := db.ReadOnlyDB.Close(); err2 != nil { |
| 216 |
if err == nil { |
| 217 |
err = fmt.Errorf("closing read-only db failed: %w", err2) |
| 218 |
} else { |
| 219 |
err = fmt.Errorf("%w (closing read-only db also failed: %v)", err, err2) |
| 220 |
} |
| 221 |
} |
| 222 |
} |
| 223 |
return err |
| 224 |
} |
| 225 |
|
| 226 |
func (db *Database) Configure(cfg Config) error { |
| 227 |
db.DeadlockDetection = cfg.DeadlockDetection || ForceDeadlockDetection |
| 228 |
|
| 229 |
if err := db.configure(db.ReadOnlyDB, cfg.ReadOnlyPool); err != nil { |
| 230 |
return err |
| 231 |
} |
| 232 |
|
| 233 |
return db.configure(db.RawDB, cfg.PoolConfig) |
| 234 |
} |
| 235 |
|
| 236 |
func (db *Database) configure(rawDB *sql.DB, cfg PoolConfig) error { |
| 237 |
if rawDB == nil { |
| 238 |
return nil |
| 239 |
} |
| 240 |
|
| 241 |
rawDB.SetMaxOpenConns(cfg.MaxOpenConns) |
| 242 |
rawDB.SetMaxIdleConns(cfg.MaxIdleConns) |
| 243 |
if len(cfg.ConnMaxIdleTime) > 0 { |
| 244 |
maxIdleTimeDuration, err := time.ParseDuration(cfg.ConnMaxIdleTime) |
| 245 |
if err != nil { |
| 246 |
return fmt.Errorf("failed to parse max_conn_idle_time: %w", err) |
| 247 |
} |
| 248 |
rawDB.SetConnMaxIdleTime(maxIdleTimeDuration) |
| 249 |
} |
| 250 |
if len(cfg.ConnMaxLifetime) > 0 { |
| 251 |
maxLifetimeDuration, err := time.ParseDuration(cfg.ConnMaxLifetime) |
| 252 |
if err != nil { |
| 253 |
return fmt.Errorf("failed to parse max_conn_idle_time: %w", err) |
| 254 |
} |
| 255 |
rawDB.SetConnMaxLifetime(maxLifetimeDuration) |
| 256 |
} |
| 257 |
return nil |
| 258 |
} |
| 259 |
|
| 260 |
func NewFromConfig(owner string, cfg Config, logger DatabaseLogger) (*Database, error) { |
| 261 |
wrappedDB, err := NewWithDialect(cfg.URI, cfg.Type) |
| 262 |
if err != nil { |
| 263 |
return nil, err |
| 264 |
} |
| 265 |
|
| 266 |
wrappedDB.Owner = owner |
| 267 |
if logger != nil { |
| 268 |
wrappedDB.Log = logger |
| 269 |
} |
| 270 |
|
| 271 |
if cfg.ReadOnlyPool.MaxOpenConns > 0 { |
| 272 |
if cfg.ReadOnlyPool.Type == "" { |
| 273 |
cfg.ReadOnlyPool.Type = cfg.Type |
| 274 |
} |
| 275 |
|
| 276 |
roUri := cfg.ReadOnlyPool.URI |
| 277 |
if roUri == "" { |
| 278 |
uriParts := strings.Split(cfg.URI, "?") |
| 279 |
|
| 280 |
qs := url.Values{} |
| 281 |
if len(uriParts) == 2 { |
| 282 |
var err error |
| 283 |
qs, err = url.ParseQuery(uriParts[1]) |
| 284 |
if err != nil { |
| 285 |
return nil, err |
| 286 |
} |
| 287 |
|
| 288 |
qs.Del("_txlock") |
| 289 |
qs.Del("_auto_vacuum") |
| 290 |
qs.Del("_vacuum") |
| 291 |
} |
| 292 |
qs.Set("_query_only", "true") |
| 293 |
|
| 294 |
roUri = uriParts[0] + "?" + qs.Encode() |
| 295 |
} |
| 296 |
|
| 297 |
wrappedDB.ReadOnlyDB, err = sql.Open(cfg.ReadOnlyPool.Type, roUri) |
| 298 |
if err != nil { |
| 299 |
return nil, err |
| 300 |
} |
| 301 |
} |
| 302 |
|
| 303 |
err = wrappedDB.Configure(cfg) |
| 304 |
if err != nil { |
| 305 |
return nil, err |
| 306 |
} |
| 307 |
|
| 308 |
return wrappedDB, nil |
| 309 |
} |