ICU-738/Refactor internal/db to domain errors (#815)

* Refactor internal/db to domain errors
This commit is contained in:
Louis Ruch authored and GitHub committed 2020-12-21 10:07:34 -08:00
1 parent b5d84495a3
commit bfbb179741
82 files changed
+742 -640

No files matched your search

+1 -2
View File
@@ -3,8 +3,7 @@ package dbassert
import (
"database/sql"
dbassert "github.com/hashicorp/dbassert"
"github.com/hashicorp/dbassert"
gormAssert "github.com/hashicorp/dbassert/gorm"
"github.com/stretchr/testify/assert"
)
+10 -13
View File
@@ -4,26 +4,22 @@
package common
import (
"errors"
"fmt"
"reflect"
"strings"
"github.com/hashicorp/boundary/internal/errors"
"github.com/jinzhu/gorm"
)
var (
// ErrInvalidParameter is returned when a required parameter is nil.
ErrInvalidParameter = errors.New("nil parameter")
)
// UpdateFields will create a map[string]interface of the update values to be
// sent to the db. The map keys will be the field names for the fields to be
// updated. The caller provided fieldMaskPaths and setToNullPaths must not
// intersect. fieldMaskPaths and setToNullPaths cannot both be zero len.
func UpdateFields(i interface{}, fieldMaskPaths []string, setToNullPaths []string) (map[string]interface{}, error) {
const op = "common.UpdateFields"
if i == nil {
return nil, fmt.Errorf("interface is missing: %w", ErrInvalidParameter)
return nil, errors.New(errors.InvalidParameter, op, "interface is missing")
}
if fieldMaskPaths == nil {
fieldMaskPaths = []string{}
@@ -32,7 +28,7 @@ func UpdateFields(i interface{}, fieldMaskPaths []string, setToNullPaths []strin
setToNullPaths = []string{}
}
if len(fieldMaskPaths) == 0 && len(setToNullPaths) == 0 {
return nil, errors.New("both fieldMaskPaths and setToNullPaths are zero len")
return nil, errors.New(errors.InvalidParameter, op, "both fieldMaskPaths and setToNullPaths are zero len")
}
inter, maskPaths, nullPaths, err := Intersection(fieldMaskPaths, setToNullPaths)
@@ -40,7 +36,7 @@ func UpdateFields(i interface{}, fieldMaskPaths []string, setToNullPaths []strin
return nil, err
}
if len(inter) != 0 {
return nil, fmt.Errorf("fieldMashPaths and setToNullPaths cannot intersect")
return nil, errors.New(errors.InvalidParameter, op, "fieldMashPaths and setToNullPaths cannot intersect")
}
updateFields := map[string]interface{}{} // case sensitive update fields to values
@@ -91,11 +87,11 @@ func UpdateFields(i interface{}, fieldMaskPaths []string, setToNullPaths []strin
}
if missing := findMissingPaths(setToNullPaths, found); len(missing) != 0 {
return nil, fmt.Errorf("null paths not found in resource: %s", missing)
return nil, errors.New(errors.InvalidParameter, op, fmt.Sprintf("null paths not found in resource: %s", missing))
}
if missing := findMissingPaths(fieldMaskPaths, found); len(missing) != 0 {
return nil, fmt.Errorf("field mask paths not found in resource: %s", missing)
return nil, errors.New(errors.InvalidParameter, op, fmt.Sprintf("field mask paths not found in resource: %s", missing))
}
return updateFields, nil
@@ -116,11 +112,12 @@ func findMissingPaths(paths []string, foundPaths map[string]struct{}) []string {
// of the original av and bv, with the key set to uppercase and value set to the
// original
func Intersection(av, bv []string) ([]string, map[string]string, map[string]string, error) {
const op = "common.Intersection"
if av == nil {
return nil, nil, nil, fmt.Errorf("av is missing: %w", ErrInvalidParameter)
return nil, nil, nil, errors.New(errors.InvalidParameter, op, "av is missing")
}
if bv == nil {
return nil, nil, nil, fmt.Errorf("bv is missing: %w", ErrInvalidParameter)
return nil, nil, nil, errors.New(errors.InvalidParameter, op, "bv is missing")
}
if len(av) == 0 && len(bv) == 0 {
return []string{}, map[string]string{}, map[string]string{}, nil
+9 -9
View File
@@ -147,7 +147,7 @@ func Test_intersection(t *testing.T) {
want1: nil,
want2: nil,
wantErr: true,
wantErrMsg: "av is missing: nil parameter",
wantErrMsg: "common.Intersection: av is missing: parameter violation: error #100",
},
{
name: "nil-bv",
@@ -159,7 +159,7 @@ func Test_intersection(t *testing.T) {
want1: nil,
want2: nil,
wantErr: true,
wantErrMsg: "bv is missing: nil parameter",
wantErrMsg: "common.Intersection: bv is missing: parameter violation: error #100",
},
}
for _, tt := range tests {
@@ -206,7 +206,7 @@ func TestUpdateFields(t *testing.T) {
},
want: nil,
wantErr: true,
wantErrMsg: "interface is missing: nil parameter",
wantErrMsg: "common.UpdateFields: interface is missing: parameter violation: error #100",
},
{
name: "missing fieldmasks",
@@ -217,7 +217,7 @@ func TestUpdateFields(t *testing.T) {
},
want: nil,
wantErr: true,
wantErrMsg: "both fieldMaskPaths and setToNullPaths are zero len",
wantErrMsg: "common.UpdateFields: both fieldMaskPaths and setToNullPaths are zero len: parameter violation: error #100",
},
{
name: "missing null fields",
@@ -239,7 +239,7 @@ func TestUpdateFields(t *testing.T) {
setToNullPaths: nil,
},
wantErr: true,
wantErrMsg: "both fieldMaskPaths and setToNullPaths are zero len",
wantErrMsg: "common.UpdateFields: both fieldMaskPaths and setToNullPaths are zero len: parameter violation: error #100",
},
{
name: "not found masks",
@@ -250,7 +250,7 @@ func TestUpdateFields(t *testing.T) {
},
want: nil,
wantErr: true,
wantErrMsg: "field mask paths not found in resource: [invalidFieldName]",
wantErrMsg: "common.UpdateFields: field mask paths not found in resource: [invalidFieldName]: parameter violation: error #100",
},
{
name: "not found null paths",
@@ -261,7 +261,7 @@ func TestUpdateFields(t *testing.T) {
},
want: nil,
wantErr: true,
wantErrMsg: "null paths not found in resource: [invalidFieldName]",
wantErrMsg: "common.UpdateFields: null paths not found in resource: [invalidFieldName]: parameter violation: error #100",
},
{
name: "intersection",
@@ -272,7 +272,7 @@ func TestUpdateFields(t *testing.T) {
},
want: nil,
wantErr: true,
wantErrMsg: "fieldMashPaths and setToNullPaths cannot intersect",
wantErrMsg: "common.UpdateFields: fieldMashPaths and setToNullPaths cannot intersect: parameter violation: error #100",
},
{
name: "valid",
@@ -381,7 +381,7 @@ func TestUpdateFields(t *testing.T) {
},
want: nil,
wantErr: true,
wantErrMsg: "null paths not found in resource: [invalidFieldName]",
wantErrMsg: "common.UpdateFields: null paths not found in resource: [invalidFieldName]: parameter violation: error #100",
},
}
for _, tt := range tests {
+155 -139
View File
@@ -3,7 +3,6 @@ package db
import (
"context"
"database/sql"
stderrors "errors"
"fmt"
"reflect"
"strings"
@@ -180,13 +179,14 @@ func New(underlying *gorm.DB) *Db {
// Exec will execute the sql with the values as parameters. The int returned
// is the number of rows affected by the sql. No options are currently
// supported.
func (rw *Db) Exec(ctx context.Context, sql string, values []interface{}, opt ...Option) (int, error) {
func (rw *Db) Exec(_ context.Context, sql string, values []interface{}, _ ...Option) (int, error) {
const op = "db.Exec"
if sql == "" {
return NoRowsAffected, fmt.Errorf("missing sql: %w", errors.ErrInvalidParameter)
return NoRowsAffected, errors.New(errors.InvalidParameter, op, "missing sql")
}
gormDb := rw.underlying.Exec(sql, values...)
if gormDb.Error != nil {
return NoRowsAffected, fmt.Errorf("exec: failed: %w", gormDb.Error)
return NoRowsAffected, errors.Wrap(gormDb.Error, op)
}
return int(gormDb.RowsAffected), nil
}
@@ -195,29 +195,32 @@ func (rw *Db) Exec(ctx context.Context, sql string, values []interface{}, opt ..
// operate within the context of any ongoing transaction for the db.Reader. The
// caller must close the returned *sql.Rows. Query can/should be used in
// combination with ScanRows.
func (rw *Db) Query(ctx context.Context, sql string, values []interface{}, opt ...Option) (*sql.Rows, error) {
func (rw *Db) Query(_ context.Context, sql string, values []interface{}, _ ...Option) (*sql.Rows, error) {
const op = "db.Query"
if sql == "" {
return nil, fmt.Errorf("raw missing sql: %w", errors.ErrInvalidParameter)
return nil, errors.New(errors.InvalidParameter, op, "missing sql")
}
gormDb := rw.underlying.Raw(sql, values...)
if gormDb.Error != nil {
return nil, fmt.Errorf("exec: failed: %w", gormDb.Error)
return nil, errors.Wrap(gormDb.Error, op)
}
return gormDb.Rows()
}
// Scan rows will scan the rows into the interface
func (rw *Db) ScanRows(rows *sql.Rows, result interface{}) error {
const op = "db.ScanRows"
if rw.underlying == nil {
return fmt.Errorf("scan rows: missing underlying db %w", errors.ErrInvalidParameter)
return errors.New(errors.InvalidParameter, op, "missing underlying db")
}
if isNil(result) {
return fmt.Errorf("scan rows: result is missing %w", errors.ErrInvalidParameter)
return errors.New(errors.InvalidParameter, op, "missing result")
}
return rw.underlying.ScanRows(rows, result)
}
func (rw *Db) lookupAfterWrite(ctx context.Context, i interface{}, opt ...Option) error {
const op = "db.lookupAfterWrite"
opts := GetOpts(opt...)
withLookup := opts.withLookup
@@ -225,7 +228,7 @@ func (rw *Db) lookupAfterWrite(ctx context.Context, i interface{}, opt ...Option
return nil
}
if err := rw.LookupById(ctx, i, opt...); err != nil {
return fmt.Errorf("lookup after write: %w", err)
return errors.Wrap(err, op)
}
return nil
}
@@ -235,22 +238,23 @@ func (rw *Db) lookupAfterWrite(ctx context.Context, i interface{}, opt ...Option
// NewOplogMsg will return in-memory oplog message. WithOplog and NewOplogMsg
// cannot be used together. WithLookup with to force a lookup after create.
func (rw *Db) Create(ctx context.Context, i interface{}, opt ...Option) error {
const op = "db.Create"
if rw.underlying == nil {
return fmt.Errorf("create: missing underlying db: %w", errors.ErrInvalidParameter)
return errors.New(errors.InvalidParameter, op, "missing underlying db")
}
if isNil(i) {
return fmt.Errorf("create: interface is missing: %w", errors.ErrInvalidParameter)
return errors.New(errors.InvalidParameter, op, "missing interface")
}
opts := GetOpts(opt...)
withOplog := opts.withOplog
if withOplog && opts.newOplogMsg != nil {
return fmt.Errorf("create: both WithOplog and NewOplogMsg options have been specified: %w", errors.ErrInvalidParameter)
return errors.New(errors.InvalidParameter, op, "both WithOplog and NewOplogMsg options have been specified")
}
if withOplog {
// let's validate oplog options before we start writing to the database
_, err := validateOplogArgs(i, opts)
if err != nil {
return fmt.Errorf("create: oplog validation failed: %w", err)
return errors.Wrap(err, op, errors.WithMsg("oplog validation failed"))
}
}
// these fields should be nil, since they are not writeable and we want the
@@ -260,7 +264,7 @@ func (rw *Db) Create(ctx context.Context, i interface{}, opt ...Option) error {
if !opts.withSkipVetForWrite {
if vetter, ok := i.(VetForWriter); ok {
if err := vetter.VetForWrite(ctx, rw, CreateOp); err != nil {
return fmt.Errorf("create: vet for write failed: %w", err)
return errors.Wrap(err, op, errors.WithMsg("vet for write failed"))
}
}
}
@@ -269,26 +273,26 @@ func (rw *Db) Create(ctx context.Context, i interface{}, opt ...Option) error {
var err error
ticket, err = rw.GetTicket(i)
if err != nil {
return fmt.Errorf("create: unable to get ticket: %w", err)
return errors.Wrap(err, op, errors.WithMsg("unable to get ticket"))
}
}
if err := rw.underlying.Create(i).Error; err != nil {
return fmt.Errorf("create: failed: %w", err)
return errors.Wrap(err, op, errors.WithMsg("create failed"))
}
if withOplog {
if err := rw.addOplog(ctx, CreateOp, opts, ticket, i); err != nil {
return err
return errors.Wrap(err, op)
}
}
if opts.newOplogMsg != nil {
msg, err := rw.newOplogMessage(ctx, CreateOp, i)
if err != nil {
return fmt.Errorf("create: returning oplog failed: %w", err)
return errors.Wrap(err, op, errors.WithMsg("returning oplog failed"))
}
*opts.newOplogMsg = *msg
}
if err := rw.lookupAfterWrite(ctx, i, opt...); err != nil {
return fmt.Errorf("create: %w", err)
return errors.Wrap(err, op)
}
return nil
}
@@ -297,21 +301,22 @@ func (rw *Db) Create(ctx context.Context, i interface{}, opt ...Option) error {
// WithOplog and WithOplogMsgs. WithOplog and WithOplogMsgs may not be used
// together. WithLookup is not a supported option.
func (rw *Db) CreateItems(ctx context.Context, createItems []interface{}, opt ...Option) error {
const op = "db.CreateItems"
if rw.underlying == nil {
return fmt.Errorf("create items: missing underlying db: %w", errors.ErrInvalidParameter)
return errors.New(errors.InvalidParameter, op, "missing underlying db")
}
if len(createItems) == 0 {
return fmt.Errorf("create items: no interfaces to create: %w", errors.ErrInvalidParameter)
return errors.New(errors.InvalidParameter, op, "missing interfaces")
}
opts := GetOpts(opt...)
if opts.withLookup {
return fmt.Errorf("create items: with lookup not a supported option: %w", errors.ErrInvalidParameter)
return errors.New(errors.InvalidParameter, op, "with lookup not a supported option")
}
if opts.newOplogMsg != nil {
return fmt.Errorf("create items: new oplog msg (singular) is not a supported option: %w", errors.ErrInvalidParameter)
return errors.New(errors.InvalidParameter, op, "new oplog msg (singular) is not a supported option")
}
if opts.withOplog && opts.newOplogMsgs != nil {
return fmt.Errorf("create items: both WithOplog and NewOplogMsgs options have been specified: %w", errors.ErrInvalidParameter)
return errors.New(errors.InvalidParameter, op, "both WithOplog and NewOplogMsgs options have been specified")
}
// verify that createItems are all the same type.
var foundType reflect.Type
@@ -321,35 +326,35 @@ func (rw *Db) CreateItems(ctx context.Context, createItems []interface{}, opt ..
}
currentType := reflect.TypeOf(v)
if foundType != currentType {
return fmt.Errorf("create items: create items contains disparate types. item %d is not a %s: %w", i, foundType.Name(), errors.ErrInvalidParameter)
return errors.New(errors.InvalidParameter, op, fmt.Sprintf("create items contains disparate types. item %d is not a %s", i, foundType.Name()))
}
}
var ticket *store.Ticket
if opts.withOplog {
_, err := validateOplogArgs(createItems[0], opts)
if err != nil {
return fmt.Errorf("create items: oplog validation failed: %w", err)
return errors.Wrap(err, op, errors.WithMsg("oplog validation failed"))
}
ticket, err = rw.GetTicket(createItems[0])
if err != nil {
return fmt.Errorf("create items: unable to get ticket: %w", err)
return errors.Wrap(err, op, errors.WithMsg("unable to get ticket"))
}
}
for _, item := range createItems {
if err := rw.Create(ctx, item); err != nil {
return fmt.Errorf("create items: %w", err)
return errors.Wrap(err, op)
}
}
if opts.withOplog {
if err := rw.addOplogForItems(ctx, CreateOp, opts, ticket, createItems); err != nil {
return fmt.Errorf("create items: unable to add oplog: %w", err)
return errors.Wrap(err, op, errors.WithMsg("unable to add oplog"))
}
}
if opts.newOplogMsgs != nil {
msgs, err := rw.oplogMsgsForItems(ctx, CreateOp, opts, createItems)
if err != nil {
return fmt.Errorf("create items: returning oplog msgs failed %w", err)
return errors.Wrap(err, op, errors.WithMsg("returning oplog msgs failed"))
}
*opts.newOplogMsgs = append(*opts.newOplogMsgs, msgs...)
}
@@ -376,46 +381,47 @@ func (rw *Db) CreateItems(ctx context.Context, createItems []interface{}, opt ..
// version matches the WithVersion option. Zero is not a valid value for the
// WithVersion option and will return an error.
func (rw *Db) Update(ctx context.Context, i interface{}, fieldMaskPaths []string, setToNullPaths []string, opt ...Option) (int, error) {
const op = "db.Update"
if rw.underlying == nil {
return NoRowsAffected, fmt.Errorf("update: missing underlying db %w", errors.ErrInvalidParameter)
return NoRowsAffected, errors.New(errors.InvalidParameter, op, "missing underlying db")
}
if isNil(i) {
return NoRowsAffected, fmt.Errorf("update: interface is missing %w", errors.ErrInvalidParameter)
return NoRowsAffected, errors.New(errors.InvalidParameter, op, "missing interface")
}
if len(fieldMaskPaths) == 0 && len(setToNullPaths) == 0 {
return NoRowsAffected, stderrors.New("update: both fieldMaskPaths and setToNullPaths are missing")
return NoRowsAffected, errors.New(errors.InvalidParameter, op, "both fieldMaskPaths and setToNullPaths are missing")
}
opts := GetOpts(opt...)
withOplog := opts.withOplog
if withOplog && opts.newOplogMsg != nil {
return NoRowsAffected, fmt.Errorf("update: both WithOplog and NewOplogMsg options have been specified: %w", errors.ErrInvalidParameter)
return NoRowsAffected, errors.New(errors.InvalidParameter, op, "both WithOplog and NewOplogMsg options have been specified")
}
// we need to filter out some non-updatable fields (like: CreateTime, etc)
fieldMaskPaths = filterPaths(fieldMaskPaths)
setToNullPaths = filterPaths(setToNullPaths)
if len(fieldMaskPaths) == 0 && len(setToNullPaths) == 0 {
return NoRowsAffected, fmt.Errorf("update: after filtering non-updated fields, there are no fields left in fieldMaskPaths or setToNullPaths")
return NoRowsAffected, errors.New(errors.InvalidParameter, op, "after filtering non-updated fields, there are no fields left in fieldMaskPaths or setToNullPaths")
}
updateFields, err := common.UpdateFields(i, fieldMaskPaths, setToNullPaths)
if err != nil {
return NoRowsAffected, fmt.Errorf("update: getting update fields failed: %w", err)
return NoRowsAffected, errors.Wrap(err, op, errors.WithMsg("getting update fields failed"))
}
if len(updateFields) == 0 {
return NoRowsAffected, fmt.Errorf("update: no fields matched using fieldMaskPaths %s", fieldMaskPaths)
return NoRowsAffected, errors.New(errors.InvalidParameter, op, fmt.Sprintf("no fields matched using fieldMaskPaths %s", fieldMaskPaths))
}
// This is not a boundary scope, but rather a gorm Scope:
// https://godoc.org/github.com/jinzhu/gorm#DB.NewScope
scope := rw.underlying.NewScope(i)
if scope.PrimaryKeyZero() {
return NoRowsAffected, fmt.Errorf("update: primary key is not set")
return NoRowsAffected, errors.New(errors.InvalidParameter, op, "primary key is not set")
}
for _, f := range scope.PrimaryFields() {
if contains(fieldMaskPaths, f.Name) {
return NoRowsAffected, fmt.Errorf("update: not allowed on primary key field %s: %w", f.Name, errors.ErrInvalidFieldMask)
return NoRowsAffected, errors.New(errors.InvalidFieldMask, op, fmt.Sprintf("not allowed on primary key field %s", f.Name))
}
}
@@ -423,13 +429,13 @@ func (rw *Db) Update(ctx context.Context, i interface{}, fieldMaskPaths []string
// let's validate oplog options before we start writing to the database
_, err := validateOplogArgs(i, opts)
if err != nil {
return NoRowsAffected, fmt.Errorf("update: oplog validation failed: %w", err)
return NoRowsAffected, errors.Wrap(err, op, errors.WithMsg("oplog validation failed"))
}
}
if !opts.withSkipVetForWrite {
if vetter, ok := i.(VetForWriter); ok {
if err := vetter.VetForWrite(ctx, rw, UpdateOp, WithFieldMaskPaths(fieldMaskPaths), WithNullPaths(setToNullPaths)); err != nil {
return NoRowsAffected, fmt.Errorf("update: vet for write failed: %w", err)
return NoRowsAffected, errors.Wrap(err, op, errors.WithMsg("vet for write failed"))
}
}
}
@@ -438,7 +444,7 @@ func (rw *Db) Update(ctx context.Context, i interface{}, fieldMaskPaths []string
var err error
ticket, err = rw.GetTicket(i)
if err != nil {
return NoRowsAffected, fmt.Errorf("update: unable to get ticket: %w", err)
return NoRowsAffected, errors.Wrap(err, op, errors.WithMsg("unable to get ticket"))
}
}
var underlying *gorm.DB
@@ -448,10 +454,10 @@ func (rw *Db) Update(ctx context.Context, i interface{}, fieldMaskPaths []string
var args []interface{}
if opts.WithVersion != nil {
if *opts.WithVersion == 0 {
return NoRowsAffected, fmt.Errorf("update: with version option is zero: %w", errors.ErrInvalidParameter)
return NoRowsAffected, errors.New(errors.InvalidParameter, op, "with version option is zero")
}
if _, ok := scope.FieldByName("version"); !ok {
return NoRowsAffected, fmt.Errorf("update: %s does not have a version field", scope.TableName())
return NoRowsAffected, errors.New(errors.InvalidParameter, op, fmt.Sprintf("%s does not have a version field", scope.TableName()))
}
where, args = append(where, "version = ?"), append(args, opts.WithVersion)
}
@@ -463,10 +469,10 @@ func (rw *Db) Update(ctx context.Context, i interface{}, fieldMaskPaths []string
underlying = rw.underlying.Model(i).Updates(updateFields)
}
if underlying.Error != nil {
if err == gorm.ErrRecordNotFound {
return NoRowsAffected, fmt.Errorf("update: failed: %w", errors.ErrRecordNotFound)
if underlying.Error == gorm.ErrRecordNotFound {
return NoRowsAffected, errors.E(errors.WithCode(errors.RecordNotFound), errors.WithOp(op))
}
return NoRowsAffected, fmt.Errorf("update: failed: %w", underlying.Error)
return NoRowsAffected, errors.Wrap(underlying.Error, op)
}
rowsUpdated := int(underlying.RowsAffected)
if rowsUpdated > 0 && (withOplog || opts.newOplogMsg != nil) {
@@ -484,13 +490,13 @@ func (rw *Db) Update(ctx context.Context, i interface{}, fieldMaskPaths []string
}
if withOplog {
if err := rw.addOplog(ctx, UpdateOp, oplogOpts, ticket, i); err != nil {
return rowsUpdated, fmt.Errorf("update: add oplog failed %w", err)
return rowsUpdated, errors.Wrap(err, op, errors.WithMsg("add oplog failed"))
}
}
if opts.newOplogMsg != nil {
msg, err := rw.newOplogMessage(ctx, UpdateOp, i, WithFieldMaskPaths(oplogFieldMasks), WithNullPaths(oplogNullPaths))
if err != nil {
return rowsUpdated, fmt.Errorf("update: returning oplog failed %w", err)
return rowsUpdated, errors.Wrap(err, op, errors.WithMsg("returning oplog failed"))
}
*opts.newOplogMsg = *msg
}
@@ -499,7 +505,7 @@ func (rw *Db) Update(ctx context.Context, i interface{}, fieldMaskPaths []string
// from the db
opt = append(opt, WithLookup(true))
if err := rw.lookupAfterWrite(ctx, i, opt...); err != nil {
return NoRowsAffected, fmt.Errorf("update: %w", err)
return NoRowsAffected, errors.Wrap(err, op)
}
return rowsUpdated, nil
}
@@ -510,29 +516,30 @@ func (rw *Db) Update(ctx context.Context, i interface{}, fieldMaskPaths []string
// WithWhere allows specifying a constraint. Delete returns the number of rows
// deleted and any errors.
func (rw *Db) Delete(ctx context.Context, i interface{}, opt ...Option) (int, error) {
const op = "db.Delete"
if rw.underlying == nil {
return NoRowsAffected, fmt.Errorf("delete: missing underlying db %w", errors.ErrInvalidParameter)
return NoRowsAffected, errors.New(errors.InvalidParameter, op, "missing underlying db")
}
if isNil(i) {
return NoRowsAffected, fmt.Errorf("delete: interface is missing %w", errors.ErrInvalidParameter)
return NoRowsAffected, errors.New(errors.InvalidParameter, op, "missing interface")
}
opts := GetOpts(opt...)
withOplog := opts.withOplog
if withOplog && opts.newOplogMsg != nil {
return NoRowsAffected, fmt.Errorf("delete: both WithOplog and NewOplogMsg options have been specified: %w", errors.ErrInvalidParameter)
return NoRowsAffected, errors.New(errors.InvalidParameter, op, "both WithOplog and NewOplogMsg options have been specified")
}
// This is not a boundary scope, but rather a gorm Scope:
// https://godoc.org/github.com/jinzhu/gorm#DB.NewScope
scope := rw.underlying.NewScope(i)
if opts.withWhereClause == "" {
if scope.PrimaryKeyZero() {
return NoRowsAffected, fmt.Errorf("delete: primary key is not set")
return NoRowsAffected, errors.New(errors.InvalidParameter, op, "primary key is not set")
}
}
if withOplog {
_, err := validateOplogArgs(i, opts)
if err != nil {
return NoRowsAffected, fmt.Errorf("delete: oplog validation failed %w", err)
return NoRowsAffected, errors.Wrap(err, op, errors.WithMsg("oplog validation failed"))
}
}
var ticket *store.Ticket
@@ -540,7 +547,7 @@ func (rw *Db) Delete(ctx context.Context, i interface{}, opt ...Option) (int, er
var err error
ticket, err = rw.GetTicket(i)
if err != nil {
return NoRowsAffected, fmt.Errorf("delete: unable to get ticket: %w", err)
return NoRowsAffected, errors.Wrap(err, op, errors.WithMsg("unable to get ticket"))
}
}
db := rw.underlying
@@ -549,19 +556,19 @@ func (rw *Db) Delete(ctx context.Context, i interface{}, opt ...Option) (int, er
}
db = db.Delete(i)
if db.Error != nil {
return NoRowsAffected, fmt.Errorf("delete: failed %w", db.Error)
return NoRowsAffected, errors.Wrap(db.Error, op)
}
rowsDeleted := int(db.RowsAffected)
if rowsDeleted > 0 && (withOplog || opts.newOplogMsg != nil) {
if withOplog {
if err := rw.addOplog(ctx, DeleteOp, opts, ticket, i); err != nil {
return rowsDeleted, fmt.Errorf("delete: add oplog failed %w", err)
return rowsDeleted, errors.Wrap(db.Error, op, errors.WithMsg("add oplog failed"))
}
}
if opts.newOplogMsg != nil {
msg, err := rw.newOplogMessage(ctx, DeleteOp, i)
if err != nil {
return rowsDeleted, fmt.Errorf("delete: returning oplog failed %w", err)
return rowsDeleted, errors.Wrap(db.Error, op, errors.WithMsg("returning oplog failed"))
}
*opts.newOplogMsg = *msg
}
@@ -573,18 +580,19 @@ func (rw *Db) Delete(ctx context.Context, i interface{}, opt ...Option) (int, er
// WithOplog and WithOplogMsgs. WithOplog and WithOplogMsgs may not be used
// together.
func (rw *Db) DeleteItems(ctx context.Context, deleteItems []interface{}, opt ...Option) (int, error) {
const op = "db.DeleteItems"
if rw.underlying == nil {
return NoRowsAffected, fmt.Errorf("delete items: missing underlying db: %w", errors.ErrInvalidParameter)
return NoRowsAffected, errors.New(errors.InvalidParameter, op, "missing underlying db")
}
if len(deleteItems) == 0 {
return NoRowsAffected, fmt.Errorf("delete items: no interfaces to delete: %w", errors.ErrInvalidParameter)
return NoRowsAffected, errors.New(errors.InvalidParameter, op, "no interfaces to delete")
}
opts := GetOpts(opt...)
if opts.newOplogMsg != nil {
return NoRowsAffected, fmt.Errorf("delete items: new oplog msg (singular) is not a supported option: %w", errors.ErrInvalidParameter)
return NoRowsAffected, errors.New(errors.InvalidParameter, op, "new oplog msg (singular) is not a supported option")
}
if opts.withOplog && opts.newOplogMsgs != nil {
return NoRowsAffected, fmt.Errorf("delete items: both WithOplog and NewOplogMsgs options have been specified: %w", errors.ErrInvalidParameter)
return NoRowsAffected, errors.New(errors.InvalidParameter, op, "both WithOplog and NewOplogMsgs options have been specified")
}
// verify that createItems are all the same type.
var foundType reflect.Type
@@ -594,7 +602,7 @@ func (rw *Db) DeleteItems(ctx context.Context, deleteItems []interface{}, opt ..
}
currentType := reflect.TypeOf(v)
if foundType != currentType {
return NoRowsAffected, fmt.Errorf("delete items: items contain disparate types. item %d is not a %s: %w", i, foundType.Name(), errors.ErrInvalidParameter)
return NoRowsAffected, errors.New(errors.InvalidParameter, op, fmt.Sprintf("items contain disparate types. item %d is not a %s", i, foundType.Name()))
}
}
@@ -602,11 +610,11 @@ func (rw *Db) DeleteItems(ctx context.Context, deleteItems []interface{}, opt ..
if opts.withOplog {
_, err := validateOplogArgs(deleteItems[0], opts)
if err != nil {
return NoRowsAffected, fmt.Errorf("delete items: oplog validation failed: %w", err)
return NoRowsAffected, errors.Wrap(err, op, errors.WithMsg("oplog validation failed"))
}
ticket, err = rw.GetTicket(deleteItems[0])
if err != nil {
return NoRowsAffected, fmt.Errorf("delete items: unable to get ticket: %w", err)
return NoRowsAffected, errors.Wrap(err, op, errors.WithMsg("unable to get ticket"))
}
}
rowsDeleted := 0
@@ -616,20 +624,20 @@ func (rw *Db) DeleteItems(ctx context.Context, deleteItems []interface{}, opt ..
// relationship between Create and CreateItems).
underlying := rw.underlying.Delete(item)
if underlying.Error != nil {
return rowsDeleted, fmt.Errorf("delete: failed: %w", underlying.Error)
return rowsDeleted, errors.Wrap(underlying.Error, op)
}
rowsDeleted += int(underlying.RowsAffected)
}
if rowsDeleted > 0 && (opts.withOplog || opts.newOplogMsgs != nil) {
if opts.withOplog {
if err := rw.addOplogForItems(ctx, DeleteOp, opts, ticket, deleteItems); err != nil {
return rowsDeleted, fmt.Errorf("delete items: unable to add oplog: %w", err)
return rowsDeleted, errors.Wrap(err, op, errors.WithMsg("unable to add oplog"))
}
}
if opts.newOplogMsgs != nil {
msgs, err := rw.oplogMsgsForItems(ctx, DeleteOp, opts, deleteItems)
if err != nil {
return rowsDeleted, fmt.Errorf("delete items: returning oplog msgs failed %w", err)
return rowsDeleted, errors.Wrap(err, op, errors.WithMsg("returning oplog msgs failed"))
}
*opts.newOplogMsgs = append(*opts.newOplogMsgs, msgs...)
}
@@ -638,31 +646,33 @@ func (rw *Db) DeleteItems(ctx context.Context, deleteItems []interface{}, opt ..
}
func validateOplogArgs(i interface{}, opts Options) (oplog.ReplayableMessage, error) {
const op = "db.validateOplogArgs"
oplogArgs := opts.oplogOpts
if oplogArgs.wrapper == nil {
return nil, fmt.Errorf("error no wrapper WithOplog: %w", errors.ErrInvalidParameter)
return nil, errors.New(errors.InvalidParameter, op, "missing wrapper")
}
if len(oplogArgs.metadata) == 0 {
return nil, fmt.Errorf("error no metadata for WithOplog: %w", errors.ErrInvalidParameter)
return nil, errors.New(errors.InvalidParameter, op, "missing metadata")
}
replayable, ok := i.(oplog.ReplayableMessage)
if !ok {
return nil, stderrors.New("error not a replayable message for WithOplog")
return nil, errors.E(errors.WithOp(op), errors.WithMsg("not a replayable message"))
}
return replayable, nil
}
func (rw *Db) getTicketFor(aggregateName string) (*store.Ticket, error) {
const op = "db.getTicketFor"
if rw.underlying == nil {
return nil, fmt.Errorf("get ticket for %s: underlying db missing: %w", aggregateName, errors.ErrInvalidParameter)
return nil, errors.New(errors.InvalidParameter, op, fmt.Sprintf("%s: underlying db missing", aggregateName))
}
ticketer, err := oplog.NewGormTicketer(rw.underlying, oplog.WithAggregateNames(true))
if err != nil {
return nil, fmt.Errorf("get ticket for %s: unable to get Ticketer %w", aggregateName, err)
return nil, errors.Wrap(err, op, errors.WithMsg(fmt.Sprintf("%s: unable to get Ticketer", aggregateName)))
}
ticket, err := ticketer.GetTicket(aggregateName)
if err != nil {
return nil, fmt.Errorf("get ticket for %s: unable to get ticket %w", aggregateName, err)
return nil, errors.Wrap(err, op, errors.WithMsg(fmt.Sprintf("%s: unable to get ticket", aggregateName)))
}
return ticket, nil
}
@@ -670,22 +680,24 @@ func (rw *Db) getTicketFor(aggregateName string) (*store.Ticket, error) {
// GetTicket returns an oplog ticket for the aggregate root of "i" which can
// be used to WriteOplogEntryWith for that aggregate root.
func (rw *Db) GetTicket(i interface{}) (*store.Ticket, error) {
const op = "db.GetTicket"
if rw.underlying == nil {
return nil, fmt.Errorf("get ticket: underlying db missing: %w", errors.ErrInvalidParameter)
return nil, errors.New(errors.InvalidParameter, op, "missing underlying db")
}
if isNil(i) {
return nil, fmt.Errorf("get ticket: interface is missing %w", errors.ErrInvalidParameter)
return nil, errors.New(errors.InvalidParameter, op, "missing interface")
}
replayable, ok := i.(oplog.ReplayableMessage)
if !ok {
return nil, fmt.Errorf("get ticket: not a replayable message %w", errors.ErrInvalidParameter)
return nil, errors.New(errors.InvalidParameter, op, "not a replayable message")
}
return rw.getTicketFor(replayable.TableName())
}
func (rw *Db) oplogMsgsForItems(ctx context.Context, opType OpType, opts Options, items []interface{}) ([]*oplog.Message, error) {
const op = "db.oplogMsgsForItems"
if len(items) == 0 {
return nil, fmt.Errorf("oplog msgs for items: items is empty: %w", errors.ErrInvalidParameter)
return nil, errors.New(errors.InvalidParameter, op, "missing items")
}
oplogMsgs := []*oplog.Message{}
var foundType reflect.Type
@@ -695,11 +707,11 @@ func (rw *Db) oplogMsgsForItems(ctx context.Context, opType OpType, opts Options
}
currentType := reflect.TypeOf(item)
if foundType != currentType {
return nil, fmt.Errorf("oplog msgs for items: items contains disparate types. item (%d) %s is not a %s: %w", i, currentType, foundType, errors.ErrInvalidParameter)
return nil, errors.New(errors.InvalidParameter, op, fmt.Sprintf("items contains disparate types. item (%d) %s is not a %s", i, currentType, foundType))
}
msg, err := rw.newOplogMessage(ctx, opType, item, WithFieldMaskPaths(opts.WithFieldMaskPaths), WithNullPaths(opts.WithNullPaths))
if err != nil {
return nil, fmt.Errorf("oplog msgs for items: %w", err)
return nil, errors.Wrap(err, op)
}
oplogMsgs = append(oplogMsgs, msg)
}
@@ -710,35 +722,33 @@ func (rw *Db) oplogMsgsForItems(ctx context.Context, opType OpType, opts Options
// item. Items must all be of the same type. Only CreateOp and DeleteOp are
// currently supported operations.
func (rw *Db) addOplogForItems(ctx context.Context, opType OpType, opts Options, ticket *store.Ticket, items []interface{}) error {
const op = "db.addOplogForItems"
oplogArgs := opts.oplogOpts
if ticket == nil {
return fmt.Errorf("oplog for items: ticket is missing: %w", errors.ErrInvalidParameter)
}
if items == nil {
return fmt.Errorf("oplog for items: items are missing: %w", errors.ErrInvalidParameter)
return errors.New(errors.InvalidParameter, op, "missing ticket")
}
if len(items) == 0 {
return fmt.Errorf("oplog for items: items is empty: %w", errors.ErrInvalidParameter)
return errors.New(errors.InvalidParameter, op, "missing items")
}
if oplogArgs.metadata == nil {
return fmt.Errorf("oplog for items: metadata is missing: %w", errors.ErrInvalidParameter)
return errors.New(errors.InvalidParameter, op, "missing metadata")
}
if oplogArgs.wrapper == nil {
return fmt.Errorf("oplog for items: wrapper is missing: %w", errors.ErrInvalidParameter)
return errors.New(errors.InvalidParameter, op, "missing wrapper")
}
oplogMsgs, err := rw.oplogMsgsForItems(ctx, opType, opts, items)
if err != nil {
return fmt.Errorf("oplog for items: %w", err)
return errors.Wrap(err, op)
}
replayable, err := validateOplogArgs(items[0], opts)
if err != nil {
return fmt.Errorf("oplog for items: oplog validation failed %w", err)
return errors.Wrap(err, op, errors.WithMsg("oplog validation failed"))
}
ticketer, err := oplog.NewGormTicketer(rw.underlying, oplog.WithAggregateNames(true))
if err != nil {
return fmt.Errorf("oplog for items: unable to get Ticketer %w", err)
return errors.Wrap(err, op, errors.WithMsg("unable to get Ticketer"))
}
entry, err := oplog.NewEntry(
replayable.TableName(),
@@ -747,7 +757,7 @@ func (rw *Db) addOplogForItems(ctx context.Context, opType OpType, opts Options,
ticketer,
)
if err != nil {
return fmt.Errorf("oplog for items: unable to create oplog entry %w", err)
return errors.Wrap(err, op, errors.WithMsg("unable to create oplog entry"))
}
if err := entry.WriteEntryWith(
ctx,
@@ -755,23 +765,24 @@ func (rw *Db) addOplogForItems(ctx context.Context, opType OpType, opts Options,
ticket,
oplogMsgs...,
); err != nil {
return fmt.Errorf("oplog for items: unable to write oplog entry %w", err)
return errors.Wrap(err, op, errors.WithMsg("unable to write oplog entry"))
}
return nil
}
func (rw *Db) addOplog(ctx context.Context, opType OpType, opts Options, ticket *store.Ticket, i interface{}) error {
const op = "db.addOplog"
oplogArgs := opts.oplogOpts
replayable, err := validateOplogArgs(i, opts)
if err != nil {
return err
return errors.Wrap(err, op)
}
if ticket == nil {
return fmt.Errorf("add oplog: missing ticket %w", errors.ErrInvalidParameter)
return errors.New(errors.InvalidParameter, op, "missing ticket")
}
ticketer, err := oplog.NewGormTicketer(rw.underlying, oplog.WithAggregateNames(true))
if err != nil {
return fmt.Errorf("add oplog: unable to get Ticketer %w", err)
return errors.Wrap(err, op, errors.WithMsg("unable to get Ticketer"))
}
entry, err := oplog.NewEntry(
replayable.TableName(),
@@ -784,7 +795,7 @@ func (rw *Db) addOplog(ctx context.Context, opType OpType, opts Options, ticket
}
msg, err := rw.newOplogMessage(ctx, opType, i, WithFieldMaskPaths(opts.WithFieldMaskPaths), WithNullPaths(opts.WithNullPaths))
if err != nil {
return fmt.Errorf("add oplog: %w", err)
return errors.Wrap(err, op)
}
err = entry.WriteEntryWith(
ctx,
@@ -793,36 +804,34 @@ func (rw *Db) addOplog(ctx context.Context, opType OpType, opts Options, ticket
msg,
)
if err != nil {
return fmt.Errorf("add oplog: unable to write oplog entry: %w", err)
return errors.Wrap(err, op, errors.WithMsg("unable to write oplog entry"))
}
return nil
}
// WriteOplogEntryWith will write an oplog entry with the msgs provided for
// the ticket's aggregateName. No options are currently supported.
func (rw *Db) WriteOplogEntryWith(ctx context.Context, wrapper wrapping.Wrapper, ticket *store.Ticket, metadata oplog.Metadata, msgs []*oplog.Message, opt ...Option) error {
func (rw *Db) WriteOplogEntryWith(ctx context.Context, wrapper wrapping.Wrapper, ticket *store.Ticket, metadata oplog.Metadata, msgs []*oplog.Message, _ ...Option) error {
const op = "db.WriteOplogEntryWith"
if wrapper == nil {
return fmt.Errorf("write oplog: wrapper is unset %w", errors.ErrInvalidParameter)
return errors.New(errors.InvalidParameter, op, "missing wrapper")
}
if ticket == nil {
return fmt.Errorf("write oplog: ticket is unset %w", errors.ErrInvalidParameter)
return errors.New(errors.InvalidParameter, op, "missing ticket")
}
if len(msgs) == 0 {
return fmt.Errorf("write oplog: msgs are empty %w", errors.ErrInvalidParameter)
return errors.New(errors.InvalidParameter, op, "missing msgs")
}
if rw.underlying == nil {
return fmt.Errorf("write oplog: underlying is unset %w", errors.ErrInvalidParameter)
}
if metadata == nil {
return fmt.Errorf("write oplog: metadata is unset %w", errors.ErrInvalidParameter)
return errors.New(errors.InvalidParameter, op, "missing underlying db")
}
if len(metadata) == 0 {
return fmt.Errorf("write oplog: metadata is empty %w", errors.ErrInvalidParameter)
return errors.New(errors.InvalidParameter, op, "missing metadata")
}
ticketer, err := oplog.NewGormTicketer(rw.underlying, oplog.WithAggregateNames(true))
if err != nil {
return fmt.Errorf("write oplog: unable to get Ticketer %w", err)
return errors.Wrap(err, op, errors.WithMsg("unable to get Ticketer"))
}
entry, err := oplog.NewEntry(
@@ -832,7 +841,7 @@ func (rw *Db) WriteOplogEntryWith(ctx context.Context, wrapper wrapping.Wrapper,
ticketer,
)
if err != nil {
return fmt.Errorf("write oplog: unable to create oplog entry: %w", err)
return errors.Wrap(err, op, errors.WithMsg("unable to create oplog entry"))
}
err = entry.WriteEntryWith(
ctx,
@@ -841,16 +850,17 @@ func (rw *Db) WriteOplogEntryWith(ctx context.Context, wrapper wrapping.Wrapper,
msgs...,
)
if err != nil {
return fmt.Errorf("write oplog: unable to write oplog entry: %w", err)
return errors.Wrap(err, op, errors.WithMsg("unable to write oplog entry"))
}
return nil
}
func (rw *Db) newOplogMessage(ctx context.Context, opType OpType, i interface{}, opt ...Option) (*oplog.Message, error) {
func (rw *Db) newOplogMessage(_ context.Context, opType OpType, i interface{}, opt ...Option) (*oplog.Message, error) {
const op = "db.newOplogMessage"
opts := GetOpts(opt...)
replayable, ok := i.(oplog.ReplayableMessage)
if !ok {
return nil, stderrors.New("error not a replayable interface")
return nil, errors.New(errors.InvalidParameter, op, "not a replayable interface")
}
msg := oplog.Message{
Message: i.(proto.Message),
@@ -866,7 +876,7 @@ func (rw *Db) newOplogMessage(ctx context.Context, opType OpType, i interface{},
case DeleteOp:
msg.OpType = oplog.OpType_OP_TYPE_DELETE
default:
return nil, fmt.Errorf("operation type %v is not supported", opType)
return nil, errors.New(errors.InvalidParameter, op, fmt.Sprintf("operation type %v is not supported", opType))
}
return &msg, nil
}
@@ -876,13 +886,14 @@ func (rw *Db) newOplogMessage(ctx context.Context, opType OpType, i interface{},
// means that the object may be sent to the db several times (retried), so things like the primary key must
// be reset before retry
func (w *Db) DoTx(ctx context.Context, retries uint, backOff Backoff, Handler TxHandler) (RetryInfo, error) {
const op = "db.DoTx"
if w.underlying == nil {
return RetryInfo{}, stderrors.New("do underlying db is nil")
return RetryInfo{}, errors.New(errors.InvalidParameter, op, "missing underlying db")
}
info := RetryInfo{}
for attempts := uint(1); ; attempts++ {
if attempts > retries+1 {
return info, fmt.Errorf("Too many retries: %d of %d", attempts-1, retries+1)
return info, errors.New(errors.MaxRetries, op, fmt.Sprintf("Too many retries: %d of %d", attempts-1, retries+1))
}
// step one of this, start a transaction...
@@ -891,7 +902,7 @@ func (w *Db) DoTx(ctx context.Context, retries uint, backOff Backoff, Handler Tx
rw := &Db{newTx}
if err := Handler(rw, rw); err != nil {
if err := newTx.Rollback().Error; err != nil {
return info, err
return info, errors.Wrap(err, op)
}
if errors.Is(err, oplog.ErrTicketAlreadyRedeemed) {
d := backOff.Duration(attempts)
@@ -900,14 +911,14 @@ func (w *Db) DoTx(ctx context.Context, retries uint, backOff Backoff, Handler Tx
time.Sleep(d)
continue
}
return info, err
return info, errors.Wrap(err, op)
}
if err := newTx.Commit().Error; err != nil {
if err := newTx.Rollback().Error; err != nil {
return info, err
return info, errors.Wrap(err, op)
}
return info, err
return info, errors.Wrap(err, op)
}
return info, nil // it all worked!!!
}
@@ -915,27 +926,29 @@ func (w *Db) DoTx(ctx context.Context, retries uint, backOff Backoff, Handler Tx
// LookupByPublicId will lookup resource by its public_id or private_id, which
// must be unique. Options are ignored.
func (rw *Db) LookupById(ctx context.Context, resourceWithIder interface{}, opt ...Option) error {
func (rw *Db) LookupById(_ context.Context, resourceWithIder interface{}, _ ...Option) error {
const op = "db.LookupById"
if rw.underlying == nil {
return fmt.Errorf("lookup by id: underlying db nil %w", errors.ErrInvalidParameter)
return errors.New(errors.InvalidParameter, op, "missing underlying db")
}
if reflect.ValueOf(resourceWithIder).Kind() != reflect.Ptr {
return fmt.Errorf("lookup by id: interface parameter must to be a pointer: %w", errors.ErrInvalidParameter)
return errors.New(errors.InvalidParameter, op, "interface parameter must to be a pointer")
}
primaryKey, where, err := primaryKeyWhere(resourceWithIder)
if err != nil {
return fmt.Errorf("lookup by id: %w", err)
return errors.Wrap(err, op)
}
if err := rw.underlying.Where(where, primaryKey).First(resourceWithIder).Error; err != nil {
if err == gorm.ErrRecordNotFound {
return errors.ErrRecordNotFound
return errors.E(errors.WithCode(errors.RecordNotFound), errors.WithOp(op))
}
return err
return errors.Wrap(err, op)
}
return nil
}
func primaryKeyWhere(resourceWithIder interface{}) (pkey string, w string, e error) {
const op = "db.primaryKeyWhere"
var primaryKey, where string
switch resourceType := resourceWithIder.(type) {
case ResourcePublicIder:
@@ -945,10 +958,10 @@ func primaryKeyWhere(resourceWithIder interface{}) (pkey string, w string, e err
primaryKey = resourceType.GetPrivateId()
where = "private_id = ?"
default:
return "", "", fmt.Errorf("unsupported interface type %w", errors.ErrInvalidParameter)
return "", "", errors.New(errors.InvalidParameter, op, fmt.Sprintf("unsupported interface type %T", resourceWithIder))
}
if primaryKey == "" {
return "", "", fmt.Errorf("primary key unset %w", errors.ErrInvalidParameter)
return "", "", errors.New(errors.InvalidParameter, op, "missing primary key")
}
return primaryKey, where, nil
}
@@ -960,16 +973,17 @@ func (rw *Db) LookupByPublicId(ctx context.Context, resource ResourcePublicIder,
}
// LookupWhere will lookup the first resource using a where clause with parameters (it only returns the first one)
func (rw *Db) LookupWhere(ctx context.Context, resource interface{}, where string, args ...interface{}) error {
func (rw *Db) LookupWhere(_ context.Context, resource interface{}, where string, args ...interface{}) error {
const op = "db.LookupWhere"
if rw.underlying == nil {
return stderrors.New("error underlying db nil for lookup by")
return errors.New(errors.InvalidParameter, op, "missing underlying db")
}
if reflect.ValueOf(resource).Kind() != reflect.Ptr {
return stderrors.New("error interface parameter must to be a pointer for lookup by")
return errors.New(errors.InvalidParameter, op, "interface parameter must to be a pointer")
}
if err := rw.underlying.Where(where, args...).First(resource).Error; err != nil {
if err == gorm.ErrRecordNotFound {
return errors.ErrRecordNotFound
return errors.E(errors.WithCode(errors.RecordNotFound), errors.WithOp(op))
}
return err
}
@@ -980,13 +994,14 @@ func (rw *Db) LookupWhere(ctx context.Context, resource interface{}, where strin
// clause with parameters. Supports the WithLimit option. If
// WithLimit < 0, then unlimited results are returned. If WithLimit == 0, then
// default limits are used for results. Supports the WithOrder option.
func (rw *Db) SearchWhere(ctx context.Context, resources interface{}, where string, args []interface{}, opt ...Option) error {
func (rw *Db) SearchWhere(_ context.Context, resources interface{}, where string, args []interface{}, opt ...Option) error {
const op = "db.SearchWhere"
opts := GetOpts(opt...)
if rw.underlying == nil {
return stderrors.New("error underlying db nil for search by")
return errors.New(errors.InvalidParameter, op, "missing underlying db")
}
if reflect.ValueOf(resources).Kind() != reflect.Ptr {
return stderrors.New("error interface parameter must to be a pointer for search by")
return errors.New(errors.InvalidParameter, op, "interface parameter must to be a pointer")
}
var err error
db := rw.underlying.Order(opts.withOrder)
@@ -1011,7 +1026,7 @@ func (rw *Db) SearchWhere(ctx context.Context, resources interface{}, where stri
err = db.Find(resources).Error
if err != nil {
// searching with a slice parameter does not return a gorm.ErrRecordNotFound
return err
return errors.Wrap(err, op)
}
return nil
}
@@ -1070,6 +1085,7 @@ func contains(ss []string, t string) bool {
// A depth of 2 will change i and i's children. A depth of 1 will change i
// but no children of i. A depth of 0 will return with no changes to i.
func Clear(i interface{}, fields []string, depth int) error {
const op = "db.Clear"
if len(fields) == 0 || depth == 0 {
return nil
}
@@ -1081,13 +1097,13 @@ func Clear(i interface{}, fields []string, depth int) error {
v := reflect.ValueOf(i)
switch v.Kind() {
default:
return errors.ErrInvalidParameter
case reflect.Ptr:
if v.IsNil() || v.Elem().Kind() != reflect.Struct {
return errors.ErrInvalidParameter
return errors.E(errors.WithCode(errors.InvalidParameter), errors.WithOp(op))
}
clear(v, fm, depth)
default:
return errors.E(errors.WithCode(errors.InvalidParameter), errors.WithOp(op))
}
return nil
}
+79 -80
View File
@@ -129,7 +129,7 @@ func TestDb_Update(t *testing.T) {
},
want: 0,
wantErr: true,
wantErrMsg: "update: with version option is zero: invalid parameter:",
wantErrMsg: "db.Update: with version option is zero: parameter violation: error #100",
},
{
name: "simple-with-version",
@@ -213,7 +213,7 @@ func TestDb_Update(t *testing.T) {
},
want: 0,
wantErr: true,
wantErrMsg: `update: failed: pq: column "foo" does not exist`,
wantErrMsg: `db.Update: column "foo" does not exist: integrity violation: error #1102`,
},
{
name: "multiple-null",
@@ -276,7 +276,7 @@ func TestDb_Update(t *testing.T) {
},
want: 0,
wantErr: true,
wantErrMsg: "update: not allowed on primary key field Id: invalid field mask:",
wantErrMsg: "db.Update: not allowed on primary key field Id: parameter violation: error #103",
},
{
name: "both are missing",
@@ -293,7 +293,7 @@ func TestDb_Update(t *testing.T) {
},
want: 0,
wantErr: true,
wantErrMsg: "update: both fieldMaskPaths and setToNullPaths are missing",
wantErrMsg: "db.Update: both fieldMaskPaths and setToNullPaths are missing: parameter violation: error #100",
},
{
name: "i is nil",
@@ -304,7 +304,7 @@ func TestDb_Update(t *testing.T) {
},
want: 0,
wantErr: true,
wantErrMsg: "update: interface is missing invalid parameter:",
wantErrMsg: "db.Update: missing interface: parameter violation: error #100",
},
{
name: "only read-only",
@@ -321,7 +321,7 @@ func TestDb_Update(t *testing.T) {
},
want: 0,
wantErr: true,
wantErrMsg: "update: after filtering non-updated fields, there are no fields left in fieldMaskPaths or setToNullPaths",
wantErrMsg: "db.Update: after filtering non-updated fields, there are no fields left in fieldMaskPaths or setToNullPaths: parameter violation: error #100",
},
}
for _, tt := range tests {
@@ -444,7 +444,7 @@ func TestDb_Update(t *testing.T) {
)
require.Error(err)
assert.Equal(0, rowsUpdated)
assert.True(errors.Is(err, errors.ErrInvalidParameter))
assert.True(errors.Match(errors.T(errors.InvalidParameter), err))
})
t.Run("valid-NewOplogMsg", func(t *testing.T) {
assert, require := assert.New(t), require.New(t)
@@ -530,7 +530,7 @@ func TestDb_Update(t *testing.T) {
rowsUpdated, err := w.Update(context.Background(), user, []string{"Name"}, nil)
assert.Error(err)
assert.Equal(0, rowsUpdated)
assert.Contains(err.Error(), "update: missing underlying db invalid parameter:")
assert.Contains(err.Error(), "db.Update: missing underlying db: parameter violation: error #100")
})
t.Run("no-wrapper-WithOplog", func(t *testing.T) {
assert, require := assert.New(t), require.New(t)
@@ -552,7 +552,7 @@ func TestDb_Update(t *testing.T) {
)
require.Error(err)
assert.Equal(0, rowsUpdated)
assert.Contains(err.Error(), "update: oplog validation failed: error no wrapper WithOplog: invalid parameter:")
assert.Contains(err.Error(), "db.Update: oplog validation failed: db.validateOplogArgs: missing wrapper: parameter violation: error #100")
})
t.Run("no-metadata-WithOplog", func(t *testing.T) {
assert, require := assert.New(t), require.New(t)
@@ -569,7 +569,7 @@ func TestDb_Update(t *testing.T) {
)
require.Error(err)
assert.Equal(0, rowsUpdated)
assert.Contains(err.Error(), "update: oplog validation failed: error no metadata for WithOplog: invalid parameter:")
assert.Contains(err.Error(), "db.Update: oplog validation failed: db.validateOplogArgs: missing metadata: parameter violation: error #100")
})
}
@@ -684,7 +684,7 @@ func TestDb_Create(t *testing.T) {
WithOplog(TestWrapper(t), oplog.Metadata{"alice": []string{"bob"}}),
)
require.Error(err)
assert.True(errors.Is(err, errors.ErrInvalidParameter))
assert.True(errors.Match(errors.T(errors.InvalidParameter), err))
})
t.Run("valid-NewOplogMsg", func(t *testing.T) {
assert, require := assert.New(t), require.New(t)
@@ -750,7 +750,7 @@ func TestDb_Create(t *testing.T) {
),
)
require.Error(err)
assert.Contains(err.Error(), "create: oplog validation failed: error no wrapper WithOplog: invalid parameter")
assert.Contains(err.Error(), "db.Create: oplog validation failed: db.validateOplogArgs: missing wrapper: parameter violation: error #100")
})
t.Run("no-metadata-WithOplog", func(t *testing.T) {
assert, require := assert.New(t), require.New(t)
@@ -769,7 +769,7 @@ func TestDb_Create(t *testing.T) {
),
)
require.Error(err)
assert.Contains(err.Error(), "create: oplog validation failed: error no metadata for WithOplog: invalid parameter")
assert.Contains(err.Error(), "db.Create: oplog validation failed: db.validateOplogArgs: missing metadata: parameter violation: error #100")
})
t.Run("nil-tx", func(t *testing.T) {
assert, require := assert.New(t), require.New(t)
@@ -781,7 +781,7 @@ func TestDb_Create(t *testing.T) {
user.Name = "foo-" + id
err = w.Create(context.Background(), user)
require.Error(err)
assert.Contains(err.Error(), "create: missing underlying db: invalid parameter")
assert.Contains(err.Error(), "db.Create: missing underlying db: parameter violation: error #100")
})
}
@@ -814,7 +814,7 @@ func TestDb_LookupByPublicId(t *testing.T) {
require.NoError(err)
err = w.LookupByPublicId(context.Background(), foundUser)
require.Error(err)
assert.Contains(err.Error(), "lookup by id: underlying db nil invalid parameter")
assert.Contains(err.Error(), "db.LookupById: missing underlying db: parameter violation: error #100")
})
t.Run("no-public-id-set", func(t *testing.T) {
assert, require := assert.New(t), require.New(t)
@@ -824,7 +824,7 @@ func TestDb_LookupByPublicId(t *testing.T) {
require.NoError(err)
err = w.LookupByPublicId(context.Background(), foundUser)
require.Error(err)
assert.Contains(err.Error(), "lookup by id: primary key unset invalid parameter")
assert.Contains(err.Error(), "db.LookupById: db.primaryKeyWhere: missing primary key: parameter violation: error #100")
})
t.Run("not-found", func(t *testing.T) {
assert, require := assert.New(t), require.New(t)
@@ -836,7 +836,7 @@ func TestDb_LookupByPublicId(t *testing.T) {
foundUser.PublicId = id
err = w.LookupByPublicId(context.Background(), foundUser)
require.Error(err)
assert.Equal(errors.ErrRecordNotFound, err)
assert.True(errors.Match(errors.T(errors.RecordNotFound), err))
})
}
@@ -866,7 +866,7 @@ func TestDb_LookupWhere(t *testing.T) {
var foundUser db_test.TestUser
err := w.LookupWhere(context.Background(), &foundUser, "public_id = ?", 1)
require.Error(err)
assert.Equal("error underlying db nil for lookup by", err.Error())
assert.Equal("db.LookupWhere: missing underlying db: parameter violation: error #100", err.Error())
})
t.Run("not-found", func(t *testing.T) {
assert, require := assert.New(t), require.New(t)
@@ -877,8 +877,7 @@ func TestDb_LookupWhere(t *testing.T) {
var foundUser db_test.TestUser
err = w.LookupWhere(context.Background(), &foundUser, "public_id = ?", id)
require.Error(err)
assert.Equal(errors.ErrRecordNotFound, err)
assert.True(errors.Is(err, errors.ErrRecordNotFound))
assert.True(errors.Match(errors.T(errors.RecordNotFound), err))
})
t.Run("bad-where", func(t *testing.T) {
require := require.New(t)
@@ -1113,7 +1112,7 @@ func TestDb_DoTx(t *testing.T) {
got, err := w.DoTx(context.Background(), 1, ExpBackoff{}, func(Reader, Writer) error { attempts += 1; return nil })
require.Error(err)
assert.Equal(RetryInfo{}, got)
assert.Equal("do underlying db is nil", err.Error())
assert.Equal("db.DoTx: missing underlying db: parameter violation: error #100", err.Error())
})
t.Run("not-a-retry-err", func(t *testing.T) {
assert, require := assert.New(t), require.New(t)
@@ -1130,7 +1129,7 @@ func TestDb_DoTx(t *testing.T) {
got, err := w.DoTx(context.Background(), 2, ExpBackoff{}, func(Reader, Writer) error { attempts += 1; return oplog.ErrTicketAlreadyRedeemed })
require.Error(err)
assert.Equal(3, got.Retries)
assert.Equal("Too many retries: 3 of 3", err.Error())
assert.Equal("db.DoTx: Too many retries: 3 of 3: db transaction issue: error #1103", err.Error())
})
t.Run("updating-good-bad-good", func(t *testing.T) {
assert, require := assert.New(t), require.New(t)
@@ -1238,7 +1237,7 @@ func TestDb_Delete(t *testing.T) {
want int
wantOplog bool
wantErr bool
wantErrIs error
wantErrIs errors.Code
}{
{
name: "simple-no-oplog",
@@ -1273,7 +1272,7 @@ func TestDb_Delete(t *testing.T) {
wantOplog: true,
want: 0,
wantErr: true,
wantErrIs: errors.ErrInvalidParameter,
wantErrIs: errors.InvalidParameter,
},
{
name: "nil-metadata",
@@ -1286,7 +1285,7 @@ func TestDb_Delete(t *testing.T) {
wantOplog: true,
want: 0,
wantErr: true,
wantErrIs: errors.ErrInvalidParameter,
wantErrIs: errors.InvalidParameter,
},
{
name: "nil-underlying",
@@ -1297,7 +1296,7 @@ func TestDb_Delete(t *testing.T) {
},
want: 0,
wantErr: true,
wantErrIs: errors.ErrInvalidParameter,
wantErrIs: errors.InvalidParameter,
},
{
name: "not-found",
@@ -1326,8 +1325,8 @@ func TestDb_Delete(t *testing.T) {
assert.Equal(tt.want, got)
if tt.wantErr {
require.Error(err)
if tt.wantErrIs != nil {
assert.Truef(errors.Is(err, tt.wantErrIs), "received unexpected error: %v", err)
if tt.wantErrIs != 0 {
assert.Truef(errors.Match(errors.T(tt.wantErrIs), err), "received unexpected error: %v", err)
}
err := TestVerifyOplog(t, rw, tt.args.i.GetPublicId(), WithOperation(oplog.OpType_OP_TYPE_DELETE), WithCreateNotBefore(5*time.Second))
assert.Error(err)
@@ -1340,7 +1339,7 @@ func TestDb_Delete(t *testing.T) {
foundUser.PublicId = tt.args.i.PublicId
err = rw.LookupByPublicId(context.Background(), foundUser)
assert.Error(err)
assert.Equal(errors.ErrRecordNotFound, err)
assert.True(errors.Match(errors.T(errors.RecordNotFound), err))
err = TestVerifyOplog(t, rw, tt.args.i.GetPublicId(), WithOperation(oplog.OpType_OP_TYPE_DELETE), WithCreateNotBefore(5*time.Second))
switch {
@@ -1370,7 +1369,7 @@ func TestDb_Delete(t *testing.T) {
rowsDeleted, err := w.Delete(context.Background(), user, NewOplogMsg(&deleteMsg), WithOplog(TestWrapper(t), oplog.Metadata{"alice": []string{"bob"}}))
require.Error(err)
assert.Equal(0, rowsDeleted)
assert.True(errors.Is(err, errors.ErrInvalidParameter))
assert.True(errors.Match(errors.T(errors.InvalidParameter), err))
})
t.Run("valid-NewOplogMsg", func(t *testing.T) {
assert, require := assert.New(t), require.New(t)
@@ -1402,7 +1401,7 @@ func TestDb_Delete(t *testing.T) {
foundUser.PublicId = user.PublicId
err = w.LookupByPublicId(context.Background(), foundUser)
require.Error(err)
assert.True(errors.Is(err, errors.ErrRecordNotFound))
assert.True(errors.Match(errors.T(errors.RecordNotFound), err))
metadata := oplog.Metadata{
"resource-public-id": []string{user.PublicId},
@@ -1509,7 +1508,7 @@ func TestDb_CreateItems(t *testing.T) {
wantOplogId string
wantOplogMsgs bool
wantErr bool
wantErrIs error
wantErrIs errors.Code
}{
{
name: "simple",
@@ -1565,7 +1564,7 @@ func TestDb_CreateItems(t *testing.T) {
),
},
},
wantErrIs: errors.ErrInvalidParameter,
wantErrIs: errors.InvalidParameter,
wantErr: true,
},
{
@@ -1575,7 +1574,7 @@ func TestDb_CreateItems(t *testing.T) {
createItems: createMixedFn(),
},
wantErr: true,
wantErrIs: errors.ErrInvalidParameter,
wantErrIs: errors.InvalidParameter,
},
{
name: "bad oplog opt: nil metadata",
@@ -1590,7 +1589,7 @@ func TestDb_CreateItems(t *testing.T) {
},
},
wantErr: true,
wantErrIs: errors.ErrInvalidParameter,
wantErrIs: errors.InvalidParameter,
},
{
name: "bad oplog opt: nil wrapper",
@@ -1608,7 +1607,7 @@ func TestDb_CreateItems(t *testing.T) {
},
},
wantErr: true,
wantErrIs: errors.ErrInvalidParameter,
wantErrIs: errors.InvalidParameter,
},
{
name: "bad opt: WithLookup",
@@ -1618,7 +1617,7 @@ func TestDb_CreateItems(t *testing.T) {
opt: []Option{WithLookup(true)},
},
wantErr: true,
wantErrIs: errors.ErrInvalidParameter,
wantErrIs: errors.InvalidParameter,
},
{
name: "nil underlying",
@@ -1627,7 +1626,7 @@ func TestDb_CreateItems(t *testing.T) {
createItems: createFn(),
},
wantErr: true,
wantErrIs: errors.ErrInvalidParameter,
wantErrIs: errors.InvalidParameter,
},
{
name: "empty items",
@@ -1636,7 +1635,7 @@ func TestDb_CreateItems(t *testing.T) {
createItems: []interface{}{},
},
wantErr: true,
wantErrIs: errors.ErrInvalidParameter,
wantErrIs: errors.InvalidParameter,
},
{
name: "nil items",
@@ -1645,7 +1644,7 @@ func TestDb_CreateItems(t *testing.T) {
createItems: nil,
},
wantErr: true,
wantErrIs: errors.ErrInvalidParameter,
wantErrIs: errors.InvalidParameter,
},
}
for _, tt := range tests {
@@ -1657,8 +1656,8 @@ func TestDb_CreateItems(t *testing.T) {
err := rw.CreateItems(context.Background(), tt.args.createItems, tt.args.opt...)
if tt.wantErr {
require.Error(err)
if tt.wantErrIs != nil {
assert.Truef(errors.Is(err, tt.wantErrIs), "unexpected error: %s", err.Error())
if tt.wantErrIs != 0 {
assert.Truef(errors.Match(errors.T(tt.wantErrIs), err), "unexpected error: %s", err.Error())
}
return
}
@@ -1713,7 +1712,7 @@ func TestDb_DeleteItems(t *testing.T) {
wantOplogId string
wantOplogMsgs bool
wantErr bool
wantErrIs error
wantErrIs errors.Code
}{
{
name: "simple",
@@ -1753,7 +1752,7 @@ func TestDb_DeleteItems(t *testing.T) {
},
},
wantErr: true,
wantErrIs: errors.ErrInvalidParameter,
wantErrIs: errors.InvalidParameter,
},
{
name: "withOplog",
@@ -1787,7 +1786,7 @@ func TestDb_DeleteItems(t *testing.T) {
},
},
wantErr: true,
wantErrIs: errors.ErrInvalidParameter,
wantErrIs: errors.InvalidParameter,
},
{
name: "bad oplog opt: nil wrapper",
@@ -1805,7 +1804,7 @@ func TestDb_DeleteItems(t *testing.T) {
},
},
wantErr: true,
wantErrIs: errors.ErrInvalidParameter,
wantErrIs: errors.InvalidParameter,
},
{
name: "bad opt: WithLookup",
@@ -1815,7 +1814,7 @@ func TestDb_DeleteItems(t *testing.T) {
opt: []Option{WithLookup(true)},
},
wantErr: true,
wantErrIs: errors.ErrInvalidParameter,
wantErrIs: errors.InvalidParameter,
},
{
name: "nil underlying",
@@ -1824,7 +1823,7 @@ func TestDb_DeleteItems(t *testing.T) {
deleteItems: createFn(),
},
wantErr: true,
wantErrIs: errors.ErrInvalidParameter,
wantErrIs: errors.InvalidParameter,
},
{
name: "empty items",
@@ -1833,7 +1832,7 @@ func TestDb_DeleteItems(t *testing.T) {
deleteItems: []interface{}{},
},
wantErr: true,
wantErrIs: errors.ErrInvalidParameter,
wantErrIs: errors.InvalidParameter,
},
{
name: "nil items",
@@ -1842,7 +1841,7 @@ func TestDb_DeleteItems(t *testing.T) {
deleteItems: nil,
},
wantErr: true,
wantErrIs: errors.ErrInvalidParameter,
wantErrIs: errors.InvalidParameter,
},
}
for _, tt := range tests {
@@ -1854,8 +1853,8 @@ func TestDb_DeleteItems(t *testing.T) {
rowsDeleted, err := rw.DeleteItems(context.Background(), tt.args.deleteItems, tt.args.opt...)
if tt.wantErr {
require.Error(err)
if tt.wantErrIs != nil {
assert.Truef(errors.Is(err, tt.wantErrIs), "unexpected error: %s", err.Error())
if tt.wantErrIs != 0 {
assert.Truef(errors.Match(errors.T(tt.wantErrIs), err), "unexpected error: %s", err.Error())
}
return
}
@@ -1866,7 +1865,7 @@ func TestDb_DeleteItems(t *testing.T) {
u.PublicId = item.(*db_test.TestUser).PublicId
err := rw.LookupByPublicId(context.Background(), &u)
require.Error(err)
require.Truef(errors.Is(err, errors.ErrRecordNotFound), "found item %s that should be deleted", u.PublicId)
require.Truef(errors.Match(errors.T(errors.RecordNotFound), err), "found item %s that should be deleted", u.PublicId)
}
if tt.wantOplogId != "" {
err = TestVerifyOplog(t, rw, tt.wantOplogId, WithOperation(oplog.OpType_OP_TYPE_DELETE), WithCreateNotBefore(10*time.Second))
@@ -1966,7 +1965,7 @@ func TestDb_LookupById(t *testing.T) {
args args
wantErr bool
want proto.Message
wantIsErr error
wantIsErr errors.Code
}{
{
name: "simple-private-id",
@@ -1995,7 +1994,7 @@ func TestDb_LookupById(t *testing.T) {
},
},
wantErr: true,
wantIsErr: errors.ErrInvalidParameter,
wantIsErr: errors.InvalidParameter,
},
{
name: "missing-private-id",
@@ -2006,7 +2005,7 @@ func TestDb_LookupById(t *testing.T) {
},
},
wantErr: true,
wantIsErr: errors.ErrInvalidParameter,
wantIsErr: errors.InvalidParameter,
},
{
name: "not-an-ider",
@@ -2015,7 +2014,7 @@ func TestDb_LookupById(t *testing.T) {
resourceWithIder: &db_test.NotIder{},
},
wantErr: true,
wantIsErr: errors.ErrInvalidParameter,
wantIsErr: errors.InvalidParameter,
},
{
name: "missing-underlying-db",
@@ -2024,7 +2023,7 @@ func TestDb_LookupById(t *testing.T) {
resourceWithIder: user,
},
wantErr: true,
wantIsErr: errors.ErrInvalidParameter,
wantIsErr: errors.InvalidParameter,
},
}
for _, tt := range tests {
@@ -2039,7 +2038,7 @@ func TestDb_LookupById(t *testing.T) {
err := rw.LookupById(context.Background(), cp, tt.args.opt...)
if tt.wantErr {
require.Error(err)
require.True(errors.Is(err, tt.wantIsErr))
require.True(errors.Match(errors.T(tt.wantIsErr), err))
return
}
require.NoError(err)
@@ -2053,7 +2052,7 @@ func TestDb_LookupById(t *testing.T) {
}
err := rw.LookupById(context.Background(), *u)
require.Error(t, err)
assert.True(t, errors.Is(err, errors.ErrInvalidParameter))
assert.True(t, errors.Match(errors.T(errors.InvalidParameter), err))
})
}
@@ -2065,7 +2064,7 @@ func TestDb_GetTicket(t *testing.T) {
underlying *gorm.DB
aggregateType interface{}
wantErr bool
wantErrIs error
wantErrIs errors.Code
}{
{
name: "simple",
@@ -2078,21 +2077,21 @@ func TestDb_GetTicket(t *testing.T) {
underlying: db,
aggregateType: &notReplayable{},
wantErr: true,
wantErrIs: errors.ErrInvalidParameter,
wantErrIs: errors.InvalidParameter,
},
{
name: "nil-aggregate-type",
underlying: db,
aggregateType: nil,
wantErr: true,
wantErrIs: errors.ErrInvalidParameter,
wantErrIs: errors.InvalidParameter,
},
{
name: "no-underlying",
underlying: nil,
aggregateType: &db_test.TestUser{},
wantErr: true,
wantErrIs: errors.ErrInvalidParameter,
wantErrIs: errors.InvalidParameter,
},
}
for _, tt := range tests {
@@ -2104,8 +2103,8 @@ func TestDb_GetTicket(t *testing.T) {
got, err := rw.GetTicket(tt.aggregateType)
if tt.wantErr {
require.Error(err)
if tt.wantErrIs != nil {
assert.Truef(errors.Is(err, tt.wantErrIs), "unexpected error type: %s", err.Error())
if tt.wantErrIs != 0 {
assert.Truef(errors.Match(errors.T(tt.wantErrIs), err), "unexpected error type: %s", err.Error())
}
return
}
@@ -2153,7 +2152,7 @@ func TestDb_WriteOplogEntryWith(t *testing.T) {
underlying *gorm.DB
args args
wantErr bool
wantErrIs error
wantErrIs errors.Code
wantErrContains string
}{
{
@@ -2188,7 +2187,7 @@ func TestDb_WriteOplogEntryWith(t *testing.T) {
msgs: []*oplog.Message{&createMsg},
},
wantErr: true,
wantErrIs: errors.ErrInvalidParameter,
wantErrIs: errors.InvalidParameter,
},
{
name: "missing-db",
@@ -2200,7 +2199,7 @@ func TestDb_WriteOplogEntryWith(t *testing.T) {
msgs: []*oplog.Message{&createMsg},
},
wantErr: true,
wantErrIs: errors.ErrInvalidParameter,
wantErrIs: errors.InvalidParameter,
},
{
name: "missing-wrapper",
@@ -2212,7 +2211,7 @@ func TestDb_WriteOplogEntryWith(t *testing.T) {
msgs: []*oplog.Message{&createMsg},
},
wantErr: true,
wantErrIs: errors.ErrInvalidParameter,
wantErrIs: errors.InvalidParameter,
},
{
name: "nil-metadata",
@@ -2224,7 +2223,7 @@ func TestDb_WriteOplogEntryWith(t *testing.T) {
msgs: []*oplog.Message{&createMsg},
},
wantErr: true,
wantErrIs: errors.ErrInvalidParameter,
wantErrIs: errors.InvalidParameter,
},
{
name: "empty-metadata",
@@ -2236,7 +2235,7 @@ func TestDb_WriteOplogEntryWith(t *testing.T) {
msgs: []*oplog.Message{&createMsg},
},
wantErr: true,
wantErrIs: errors.ErrInvalidParameter,
wantErrIs: errors.InvalidParameter,
},
}
for _, tt := range tests {
@@ -2248,8 +2247,8 @@ func TestDb_WriteOplogEntryWith(t *testing.T) {
err := rw.WriteOplogEntryWith(context.Background(), tt.args.wrapper, tt.args.ticket, tt.args.metadata, tt.args.msgs, tt.args.opt...)
if tt.wantErr {
require.Error(err)
if tt.wantErrIs != nil {
assert.Truef(errors.Is(err, tt.wantErrIs), "unexpected error %s", err.Error())
if tt.wantErrIs != 0 {
assert.Truef(errors.Match(errors.T(tt.wantErrIs), err), "unexpected error %s", err.Error())
}
if tt.wantErrContains != "" {
assert.Contains(err.Error(), tt.wantErrContains)
@@ -2787,7 +2786,7 @@ func TestDb_oplogMsgsForItems(t *testing.T) {
args args
want []*oplog.Message
wantErr bool
wantIsErr error
wantIsErr errors.Code
}{
{
name: "valid",
@@ -2805,7 +2804,7 @@ func TestDb_oplogMsgsForItems(t *testing.T) {
items: nil,
},
wantErr: true,
wantIsErr: errors.ErrInvalidParameter,
wantIsErr: errors.InvalidParameter,
},
{
name: "zero items",
@@ -2814,7 +2813,7 @@ func TestDb_oplogMsgsForItems(t *testing.T) {
items: []interface{}{},
},
wantErr: true,
wantIsErr: errors.ErrInvalidParameter,
wantIsErr: errors.InvalidParameter,
},
{
name: "mixed items",
@@ -2823,7 +2822,7 @@ func TestDb_oplogMsgsForItems(t *testing.T) {
items: mixed,
},
wantErr: true,
wantIsErr: errors.ErrInvalidParameter,
wantIsErr: errors.InvalidParameter,
},
{
name: "bad op",
@@ -2840,8 +2839,8 @@ func TestDb_oplogMsgsForItems(t *testing.T) {
got, err := rw.oplogMsgsForItems(context.Background(), tt.args.opType, tt.args.opts, tt.args.items)
if tt.wantErr {
require.Error(err)
if tt.wantIsErr != nil {
assert.Truef(errors.Is(err, tt.wantIsErr), "unexpected error %s", err.Error())
if tt.wantIsErr != 0 {
assert.Truef(errors.Match(errors.T(tt.wantIsErr), err), "unexpected error %s", err.Error())
}
return
}