Add resumable checked migrations and explicit schema administration commands. Port ML budgets, namespaces, identity and group persistence with three-backend contracts. Keep MySQL unavailable as the full application backend.
60 lines
1.9 KiB
Go
60 lines
1.9 KiB
Go
package db
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"errors"
|
|
"io"
|
|
"log"
|
|
"time"
|
|
|
|
"github.com/go-sql-driver/mysql"
|
|
)
|
|
|
|
// MySQL is currently a component-pilot backend, not a Pages serving backend.
|
|
// Credentials are instance configuration and must never be logged.
|
|
type MySQLOptions struct {
|
|
DSN string
|
|
AllowInsecure bool
|
|
}
|
|
|
|
func OpenMySQL(ctx context.Context, options MySQLOptions) (*sql.DB, error) {
|
|
c, e := mysql.ParseDSN(options.DSN)
|
|
if e != nil || options.DSN == "" {
|
|
return nil, errors.New("invalid MySQL configuration")
|
|
}
|
|
if c.DBName == "" || c.Net != "tcp" || c.MultiStatements || c.AllowAllFiles || c.AllowCleartextPasswords || c.AllowFallbackToPlaintext || len(c.Params) != 0 {
|
|
return nil, errors.New("unsupported MySQL configuration")
|
|
}
|
|
if !options.AllowInsecure && c.TLSConfig != "true" {
|
|
return nil, errors.New("MySQL requires verified TLS (tls=true)")
|
|
}
|
|
c.Timeout = 10 * time.Second
|
|
c.ReadTimeout = 30 * time.Second
|
|
c.WriteTimeout = 30 * time.Second
|
|
c.Collation = "utf8mb4_bin"
|
|
// Set on EVERY new pooled connection. Relying on a server's permissive
|
|
// sql_mode can silently truncate identifiers or coerce invalid values.
|
|
// User-supplied session variables remain rejected above.
|
|
c.Params = map[string]string{"sql_mode": "'STRICT_ALL_TABLES,ONLY_FULL_GROUP_BY,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION'"}
|
|
c.Logger = log.New(io.Discard, "", 0)
|
|
connector, e := mysql.NewConnector(c)
|
|
if e != nil {
|
|
return nil, errors.New("invalid MySQL connector configuration")
|
|
}
|
|
database := sql.OpenDB(connector)
|
|
database.SetMaxOpenConns(8)
|
|
database.SetMaxIdleConns(2)
|
|
database.SetConnMaxLifetime(10 * time.Minute)
|
|
ping, cancel := context.WithTimeout(ctx, 10*time.Second)
|
|
defer cancel()
|
|
if e = database.PingContext(ping); e != nil {
|
|
database.Close()
|
|
if ctx.Err() != nil {
|
|
return nil, ctx.Err()
|
|
}
|
|
return nil, errors.New("MySQL connection failed")
|
|
}
|
|
return database, nil
|
|
}
|