58 lines
2.0 KiB
Go
58 lines
2.0 KiB
Go
|
|
// Package mysql provides a database/sql-backed MySQL client with lifecycle
|
||
|
|
// management, health checks, and unit-of-work transaction support for
|
||
|
|
// Einherjar applications.
|
||
|
|
//
|
||
|
|
// # Overview
|
||
|
|
//
|
||
|
|
// [New] returns a [Component] that manages a *sql.DB connection pool,
|
||
|
|
// satisfies the [lifecycle.Component] lifecycle hooks (OnInit, OnStart, OnStop),
|
||
|
|
// and implements [observability.Checkable] with critical priority.
|
||
|
|
//
|
||
|
|
// [NewUnitOfWork] wraps multiple repository operations in a single transaction
|
||
|
|
// via context injection — no transaction object is passed between functions.
|
||
|
|
//
|
||
|
|
// # Lifecycle Registration
|
||
|
|
//
|
||
|
|
// db := mysql.New(logger, cfg)
|
||
|
|
// launcher.Register(db)
|
||
|
|
// health.Register(db)
|
||
|
|
//
|
||
|
|
// # Querying
|
||
|
|
//
|
||
|
|
// Repository code receives a [Provider] or [Executor] and calls [Provider.GetExecutor]
|
||
|
|
// to obtain the active transaction (if inside a [UnitOfWork]) or the pool:
|
||
|
|
//
|
||
|
|
// exec := db.GetExecutor(ctx)
|
||
|
|
// row := exec.QueryRowContext(ctx, "SELECT id FROM users WHERE email = ?", email)
|
||
|
|
// if err := row.Scan(&id); err != nil {
|
||
|
|
// return db.HandleError(err)
|
||
|
|
// }
|
||
|
|
//
|
||
|
|
// # Unit of Work
|
||
|
|
//
|
||
|
|
// [NewUnitOfWork] wraps operations in a single transaction. The transaction is
|
||
|
|
// injected into the context; [Provider.GetExecutor] returns it automatically.
|
||
|
|
//
|
||
|
|
// uow := mysql.NewUnitOfWork(logger, db)
|
||
|
|
// err := uow.Do(ctx, func(ctx context.Context) error {
|
||
|
|
// exec := db.GetExecutor(ctx) // returns active Tx
|
||
|
|
// _, err := exec.ExecContext(ctx, "INSERT INTO orders ...")
|
||
|
|
// return err
|
||
|
|
// })
|
||
|
|
//
|
||
|
|
// # Error Handling
|
||
|
|
//
|
||
|
|
// [HandleError] translates MySQL driver errors into typed [xerrors] values.
|
||
|
|
// Call it at every point where a driver error is first observed:
|
||
|
|
//
|
||
|
|
// if err := row.Scan(&out); err != nil {
|
||
|
|
// return db.HandleError(err)
|
||
|
|
// }
|
||
|
|
//
|
||
|
|
// Mapped codes:
|
||
|
|
// - 1062 (ER_DUP_ENTRY) → ErrAlreadyExists
|
||
|
|
// - 1216, 1217, 1451, 1452 (FK errors) → ErrInvalidInput
|
||
|
|
// - sql.ErrNoRows → ErrNotFound
|
||
|
|
// - all others → ErrInternal
|
||
|
|
package mysql
|