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"
|
2019-04-23 12:13:57 +01:00
|
|
|
"fmt"
|
2019-03-12 13:08:23 +00:00
|
|
|
|
2018-12-07 14:46:42 +00:00
|
|
|
"github.com/zeebo/errs"
|
|
|
|
)
|
|
|
|
|
2019-10-18 22:27:57 +01:00
|
|
|
//go:generate dbx.v1 schema -d postgres satellitedb.dbx .
|
|
|
|
//go:generate dbx.v1 golang -d postgres satellitedb.dbx .
|
2018-12-17 20:14:16 +00:00
|
|
|
|
2018-12-07 14:46:42 +00:00
|
|
|
func init() {
|
|
|
|
// catch dbx errors
|
2019-04-23 12:13:57 +01:00
|
|
|
class := 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:
|
2019-04-23 12:13:57 +01:00
|
|
|
return class.Wrap(&constraintError{e.Constraint, e.Err})
|
2018-12-17 20:14:16 +00:00
|
|
|
}
|
2019-04-23 12:13:57 +01:00
|
|
|
return class.Wrap(e)
|
2018-12-17 20:14:16 +00:00
|
|
|
}
|
2018-12-07 14:46:42 +00:00
|
|
|
}
|
2019-03-12 13:08:23 +00:00
|
|
|
|
2019-04-23 12:13:57 +01:00
|
|
|
// Unwrap returns the underlying error.
|
2019-04-23 20:48:57 +01:00
|
|
|
func (e *Error) Unwrap() error { return e.Err }
|
|
|
|
|
|
|
|
// Cause returns the underlying error.
|
|
|
|
func (e *Error) Cause() error { return e.Err }
|
2019-04-23 12:13:57 +01:00
|
|
|
|
|
|
|
type constraintError struct {
|
|
|
|
constraint string
|
|
|
|
err error
|
|
|
|
}
|
|
|
|
|
|
|
|
// Unwrap returns the underlying error.
|
2019-04-23 20:48:57 +01:00
|
|
|
func (err *constraintError) Unwrap() error { return err.err }
|
|
|
|
|
|
|
|
// Cause returns the underlying error.
|
|
|
|
func (err *constraintError) Cause() error { return err.err }
|
2019-04-23 12:13:57 +01:00
|
|
|
|
|
|
|
// Error implements the error interface.
|
|
|
|
func (err *constraintError) Error() string {
|
|
|
|
return fmt.Sprintf("violates constraint %q: %v", err.constraint, err.err)
|
|
|
|
}
|
|
|
|
|
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)
|
|
|
|
}
|