feat: establish Orbit models, migrations and development baseline
This commit is contained in:
66
internal/storage/mysql/db.go
Normal file
66
internal/storage/mysql/db.go
Normal file
@@ -0,0 +1,66 @@
|
||||
// Package mysql owns SQL connections, explicit migrations and transaction boundaries.
|
||||
package mysql
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
driver "github.com/go-sql-driver/mysql"
|
||||
)
|
||||
|
||||
// Open configures UTC, bounded I/O and an explicit connection pool. It never
|
||||
// applies migrations and never logs the DSN. TLS is chosen in the secret DSN.
|
||||
func Open(ctx context.Context, dsn string, maxOpen, maxIdle int) (*sql.DB, error) {
|
||||
if maxOpen <= 0 || maxIdle < 0 || maxIdle > maxOpen {
|
||||
return nil, errors.New("invalid database pool configuration")
|
||||
}
|
||||
cfg, err := driver.ParseDSN(dsn)
|
||||
if err != nil {
|
||||
return nil, errors.New("invalid MySQL DSN")
|
||||
}
|
||||
if cfg.DBName == "" {
|
||||
return nil, errors.New("MySQL database name required")
|
||||
}
|
||||
cfg.ParseTime = true
|
||||
cfg.Loc = time.UTC
|
||||
cfg.MultiStatements = false
|
||||
cfg.InterpolateParams = false
|
||||
cfg.Timeout = 5 * time.Second
|
||||
cfg.ReadTimeout = 10 * time.Second
|
||||
cfg.WriteTimeout = 10 * time.Second
|
||||
if cfg.Params == nil {
|
||||
cfg.Params = map[string]string{}
|
||||
}
|
||||
cfg.Params["time_zone"] = "'+00:00'"
|
||||
cfg.Params["sql_mode"] = "'STRICT_ALL_TABLES,NO_ZERO_DATE,NO_ZERO_IN_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION'"
|
||||
connector, err := driver.NewConnector(cfg)
|
||||
if err != nil {
|
||||
return nil, errors.New("invalid MySQL connection configuration")
|
||||
}
|
||||
db := sql.OpenDB(connector)
|
||||
db.SetMaxOpenConns(maxOpen)
|
||||
db.SetMaxIdleConns(maxIdle)
|
||||
db.SetConnMaxLifetime(5 * time.Minute)
|
||||
db.SetConnMaxIdleTime(time.Minute)
|
||||
if err := db.PingContext(ctx); err != nil {
|
||||
db.Close()
|
||||
return nil, errors.New("MySQL connection failed; check endpoint, credentials and TLS configuration")
|
||||
}
|
||||
return db, nil
|
||||
}
|
||||
|
||||
// WithTx does not replay callbacks: a failed commit may have succeeded remotely.
|
||||
// Callers reconcile by stable operation identity before retrying an ambiguous write.
|
||||
func WithTx(ctx context.Context, db *sql.DB, fn func(*sql.Tx) error) error {
|
||||
tx, err := db.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelReadCommitted})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
if err := fn(tx); err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
Reference in New Issue
Block a user