2019-01-24 20:15:10 +00:00
|
|
|
// Copyright (C) 2019 Storj Labs, Inc.
|
2018-12-05 09:35:50 +00:00
|
|
|
// See LICENSE for copying information.
|
|
|
|
|
|
|
|
package satellitedb
|
|
|
|
|
2018-12-07 14:46:42 +00:00
|
|
|
import (
|
2019-03-12 13:08:23 +00:00
|
|
|
"context"
|
|
|
|
|
2018-12-07 14:46:42 +00:00
|
|
|
"github.com/zeebo/errs"
|
|
|
|
)
|
|
|
|
|
2018-12-17 20:14:16 +00:00
|
|
|
//go:generate dbx.v1 schema -d postgres -d sqlite3 satellitedb.dbx .
|
|
|
|
//go:generate dbx.v1 golang -d postgres -d sqlite3 satellitedb.dbx .
|
|
|
|
|
2018-12-07 14:46:42 +00:00
|
|
|
func init() {
|
|
|
|
// catch dbx errors
|
|
|
|
c := errs.Class("satellitedb")
|
2018-12-17 20:14:16 +00:00
|
|
|
WrapErr = func(e *Error) error {
|
2019-04-01 21:14:58 +01:00
|
|
|
switch e.Code {
|
|
|
|
case ErrorCode_NoRows:
|
2018-12-17 20:14:16 +00:00
|
|
|
return e.Err
|
2019-04-01 21:14:58 +01:00
|
|
|
case ErrorCode_ConstraintViolation:
|
|
|
|
return errs.New("violates constraint")
|
2018-12-17 20:14:16 +00:00
|
|
|
}
|
2019-04-01 21:14:58 +01:00
|
|
|
|
2018-12-17 20:14:16 +00:00
|
|
|
return c.Wrap(e)
|
|
|
|
}
|
2018-12-07 14:46:42 +00:00
|
|
|
}
|
2019-03-12 13:08:23 +00:00
|
|
|
|
|
|
|
// WithTx wraps DB code in a transaction
|
|
|
|
func (db *DB) WithTx(ctx context.Context, fn func(context.Context, *Tx) error) (err error) {
|
|
|
|
tx, err := db.Open(ctx)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer func() {
|
|
|
|
if err == nil {
|
|
|
|
err = tx.Commit()
|
|
|
|
} else {
|
|
|
|
err = errs.Combine(err, tx.Rollback())
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
return fn(ctx, tx)
|
|
|
|
}
|