Files
mysql/README.md

55 lines
1.2 KiB
Markdown
Raw Permalink Normal View History

# mysql
`database/sql`-backed MySQL client with launcher lifecycle and health check integration.
## Install
```
go get code.nochebuena.dev/go/mysql
```
## Usage
```go
db := mysql.New(logger, cfg)
lc.Append(db)
r.Get("/health", health.NewHandler(logger, db))
```
## Unit of Work
```go
uow := mysql.NewUnitOfWork(logger, db)
err := uow.Do(ctx, func(ctx context.Context) error {
exec := db.GetExecutor(ctx) // returns the active Tx
_, err := exec.ExecContext(ctx, "INSERT INTO orders ...")
return err
})
```
## Error mapping
```go
if err := db.HandleError(err); err != nil { ... }
```
| MySQL error | xerrors code |
|---|---|
| 1062 (ER_DUP_ENTRY) | `ErrAlreadyExists` |
| 1216/1217/1451/1452 (foreign key) | `ErrInvalidInput` |
| `sql.ErrNoRows` | `ErrNotFound` |
| anything else | `ErrInternal` |
## Configuration
| Env var | Default | Description |
|---|---|---|
| `MYSQL_HOST` | required | Database host |
| `MYSQL_PORT` | `3306` | Database port |
| `MYSQL_USER` | required | Username |
| `MYSQL_PASSWORD` | required | Password |
| `MYSQL_NAME` | required | Database name |
| `MYSQL_MAX_CONNS` | `5` | Max open connections |
| `MYSQL_MIN_CONNS` | `2` | Max idle connections |