Update primary error functions to take a context, deprecate old functions (#1358)

* add new error funcs which take a ctx and deprecate existing funcs

* use context where available when writing error events

* remove circular internal/errors pkg dep

* suppress some chatty errors using errors.WithoutEvent()

* convert auth oidc funcs to take context where needed to write events

Co-authored-by: Jim <jlambert@hashicorp.com>
This commit is contained in:
s-christoffandJim authored and GitHub committed 2021-07-29 20:52:56 -04:00
1 parent 02ff2db66e
commit 6b78108ecf
227 files changed
+3945 -3736

No files matched your search

+8 -8
View File
@@ -19,7 +19,7 @@ import (
func UpdateFields(i interface{}, fieldMaskPaths []string, setToNullPaths []string) (map[string]interface{}, error) {
const op = "common.UpdateFields"
if i == nil {
return nil, errors.New(errors.InvalidParameter, op, "interface is missing")
return nil, errors.NewDeprecated(errors.InvalidParameter, op, "interface is missing")
}
if fieldMaskPaths == nil {
fieldMaskPaths = []string{}
@@ -28,15 +28,15 @@ func UpdateFields(i interface{}, fieldMaskPaths []string, setToNullPaths []strin
setToNullPaths = []string{}
}
if len(fieldMaskPaths) == 0 && len(setToNullPaths) == 0 {
return nil, errors.New(errors.InvalidParameter, op, "both fieldMaskPaths and setToNullPaths are zero len")
return nil, errors.NewDeprecated(errors.InvalidParameter, op, "both fieldMaskPaths and setToNullPaths are zero len")
}
inter, maskPaths, nullPaths, err := Intersection(fieldMaskPaths, setToNullPaths)
if err != nil {
return nil, errors.Wrap(err, op)
return nil, errors.WrapDeprecated(err, op)
}
if len(inter) != 0 {
return nil, errors.New(errors.InvalidParameter, op, "fieldMashPaths and setToNullPaths cannot intersect")
return nil, errors.NewDeprecated(errors.InvalidParameter, op, "fieldMashPaths and setToNullPaths cannot intersect")
}
updateFields := map[string]interface{}{} // case sensitive update fields to values
@@ -87,11 +87,11 @@ func UpdateFields(i interface{}, fieldMaskPaths []string, setToNullPaths []strin
}
if missing := findMissingPaths(setToNullPaths, found); len(missing) != 0 {
return nil, errors.New(errors.InvalidParameter, op, fmt.Sprintf("null paths not found in resource: %s", missing))
return nil, errors.NewDeprecated(errors.InvalidParameter, op, fmt.Sprintf("null paths not found in resource: %s", missing))
}
if missing := findMissingPaths(fieldMaskPaths, found); len(missing) != 0 {
return nil, errors.New(errors.InvalidParameter, op, fmt.Sprintf("field mask paths not found in resource: %s", missing))
return nil, errors.NewDeprecated(errors.InvalidParameter, op, fmt.Sprintf("field mask paths not found in resource: %s", missing))
}
return updateFields, nil
@@ -114,10 +114,10 @@ func findMissingPaths(paths []string, foundPaths map[string]struct{}) []string {
func Intersection(av, bv []string) ([]string, map[string]string, map[string]string, error) {
const op = "common.Intersection"
if av == nil {
return nil, nil, nil, errors.New(errors.InvalidParameter, op, "av is missing")
return nil, nil, nil, errors.NewDeprecated(errors.InvalidParameter, op, "av is missing")
}
if bv == nil {
return nil, nil, nil, errors.New(errors.InvalidParameter, op, "bv is missing")
return nil, nil, nil, errors.NewDeprecated(errors.InvalidParameter, op, "bv is missing")
}
if len(av) == 0 && len(bv) == 0 {
return []string{}, map[string]string{}, map[string]string{}, nil
+2 -2
View File
@@ -22,7 +22,7 @@ func NewPublicId(prefix string, opt ...Option) (string, error) {
func newId(prefix string, opt ...Option) (string, error) {
const op = "db.newId"
if prefix == "" {
return "", errors.New(errors.InvalidParameter, op, "missing prefix")
return "", errors.NewDeprecated(errors.InvalidParameter, op, "missing prefix")
}
var publicId string
var err error
@@ -35,7 +35,7 @@ func newId(prefix string, opt ...Option) (string, error) {
publicId, err = base62.Random(10)
}
if err != nil {
return "", errors.Wrap(err, op, errors.WithMsg("unable to generate id"), errors.WithCode(errors.Io))
return "", errors.WrapDeprecated(err, op, errors.WithMsg("unable to generate id"), errors.WithCode(errors.Io))
}
return fmt.Sprintf("%s_%s", prefix, publicId), nil
}
+142 -142
View File
@@ -206,14 +206,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(_ context.Context, sql string, values []interface{}, _ ...Option) (int, error) {
func (rw *Db) Exec(ctx context.Context, sql string, values []interface{}, _ ...Option) (int, error) {
const op = "db.Exec"
if sql == "" {
return NoRowsAffected, errors.New(errors.InvalidParameter, op, "missing sql")
return NoRowsAffected, errors.New(ctx, errors.InvalidParameter, op, "missing sql")
}
gormDb := rw.underlying.Exec(sql, values...)
if gormDb.Error != nil {
return NoRowsAffected, errors.Wrap(gormDb.Error, op)
return NoRowsAffected, errors.Wrap(ctx, gormDb.Error, op)
}
return int(gormDb.RowsAffected), nil
}
@@ -222,14 +222,14 @@ func (rw *Db) Exec(_ 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(_ context.Context, sql string, values []interface{}, _ ...Option) (*sql.Rows, error) {
func (rw *Db) Query(ctx context.Context, sql string, values []interface{}, _ ...Option) (*sql.Rows, error) {
const op = "db.Query"
if sql == "" {
return nil, errors.New(errors.InvalidParameter, op, "missing sql")
return nil, errors.New(ctx, errors.InvalidParameter, op, "missing sql")
}
gormDb := rw.underlying.Raw(sql, values...)
if gormDb.Error != nil {
return nil, errors.Wrap(gormDb.Error, op)
return nil, errors.Wrap(ctx, gormDb.Error, op)
}
return gormDb.Rows()
}
@@ -238,10 +238,10 @@ func (rw *Db) Query(_ context.Context, sql string, values []interface{}, _ ...Op
func (rw *Db) ScanRows(rows *sql.Rows, result interface{}) error {
const op = "db.ScanRows"
if rw.underlying == nil {
return errors.New(errors.InvalidParameter, op, "missing underlying db")
return errors.NewDeprecated(errors.InvalidParameter, op, "missing underlying db")
}
if isNil(result) {
return errors.New(errors.InvalidParameter, op, "missing result")
return errors.NewDeprecated(errors.InvalidParameter, op, "missing result")
}
return rw.underlying.ScanRows(rows, result)
}
@@ -255,7 +255,7 @@ func (rw *Db) lookupAfterWrite(ctx context.Context, i interface{}, opt ...Option
return nil
}
if err := rw.LookupById(ctx, i, opt...); err != nil {
return errors.Wrap(err, op)
return errors.Wrap(ctx, err, op)
}
return nil
}
@@ -267,21 +267,21 @@ func (rw *Db) lookupAfterWrite(ctx context.Context, i interface{}, opt ...Option
func (rw *Db) Create(ctx context.Context, i interface{}, opt ...Option) error {
const op = "db.Create"
if rw.underlying == nil {
return errors.New(errors.InvalidParameter, op, "missing underlying db")
return errors.New(ctx, errors.InvalidParameter, op, "missing underlying db")
}
if isNil(i) {
return errors.New(errors.InvalidParameter, op, "missing interface")
return errors.New(ctx, errors.InvalidParameter, op, "missing interface")
}
opts := GetOpts(opt...)
withOplog := opts.withOplog
if withOplog && opts.newOplogMsg != nil {
return errors.New(errors.InvalidParameter, op, "both WithOplog and NewOplogMsg options have been specified")
return errors.New(ctx, 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)
_, err := validateOplogArgs(ctx, i, opts)
if err != nil {
return errors.Wrap(err, op, errors.WithMsg("oplog validation failed"))
return errors.Wrap(ctx, err, op, errors.WithMsg("oplog validation failed"))
}
}
// these fields should be nil, since they are not writeable and we want the
@@ -291,7 +291,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 errors.Wrap(err, op)
return errors.Wrap(ctx, err, op)
}
}
}
@@ -300,26 +300,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 errors.Wrap(err, op, errors.WithMsg("unable to get ticket"))
return errors.Wrap(ctx, err, op, errors.WithMsg("unable to get ticket"))
}
}
if err := rw.underlying.Create(i).Error; err != nil {
return errors.Wrap(err, op, errors.WithMsg("create failed"))
return errors.Wrap(ctx, err, op, errors.WithMsg("create failed"))
}
if withOplog {
if err := rw.addOplog(ctx, CreateOp, opts, ticket, i); err != nil {
return errors.Wrap(err, op)
return errors.Wrap(ctx, err, op)
}
}
if opts.newOplogMsg != nil {
msg, err := rw.newOplogMessage(ctx, CreateOp, i)
if err != nil {
return errors.Wrap(err, op, errors.WithMsg("returning oplog failed"))
return errors.Wrap(ctx, err, op, errors.WithMsg("returning oplog failed"))
}
*opts.newOplogMsg = *msg
}
if err := rw.lookupAfterWrite(ctx, i, opt...); err != nil {
return errors.Wrap(err, op)
return errors.Wrap(ctx, err, op)
}
return nil
}
@@ -330,20 +330,20 @@ func (rw *Db) Create(ctx context.Context, i interface{}, opt ...Option) error {
func (rw *Db) CreateItems(ctx context.Context, createItems []interface{}, opt ...Option) error {
const op = "db.CreateItems"
if rw.underlying == nil {
return errors.New(errors.InvalidParameter, op, "missing underlying db")
return errors.New(ctx, errors.InvalidParameter, op, "missing underlying db")
}
if len(createItems) == 0 {
return errors.New(errors.InvalidParameter, op, "missing interfaces")
return errors.New(ctx, errors.InvalidParameter, op, "missing interfaces")
}
opts := GetOpts(opt...)
if opts.withLookup {
return errors.New(errors.InvalidParameter, op, "with lookup not a supported option")
return errors.New(ctx, errors.InvalidParameter, op, "with lookup not a supported option")
}
if opts.newOplogMsg != nil {
return errors.New(errors.InvalidParameter, op, "new oplog msg (singular) is not a supported option")
return errors.New(ctx, errors.InvalidParameter, op, "new oplog msg (singular) is not a supported option")
}
if opts.withOplog && opts.newOplogMsgs != nil {
return errors.New(errors.InvalidParameter, op, "both WithOplog and NewOplogMsgs options have been specified")
return errors.New(ctx, errors.InvalidParameter, op, "both WithOplog and NewOplogMsgs options have been specified")
}
// verify that createItems are all the same type.
var foundType reflect.Type
@@ -353,34 +353,34 @@ func (rw *Db) CreateItems(ctx context.Context, createItems []interface{}, opt ..
}
currentType := reflect.TypeOf(v)
if foundType != currentType {
return errors.New(errors.InvalidParameter, op, fmt.Sprintf("create items contains disparate types. item %d is not a %s", i, foundType.Name()))
return errors.New(ctx, 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)
_, err := validateOplogArgs(ctx, createItems[0], opts)
if err != nil {
return errors.Wrap(err, op, errors.WithMsg("oplog validation failed"))
return errors.Wrap(ctx, err, op, errors.WithMsg("oplog validation failed"))
}
ticket, err = rw.GetTicket(createItems[0])
if err != nil {
return errors.Wrap(err, op, errors.WithMsg("unable to get ticket"))
return errors.Wrap(ctx, err, op, errors.WithMsg("unable to get ticket"))
}
}
for _, item := range createItems {
if err := rw.Create(ctx, item); err != nil {
return errors.Wrap(err, op)
return errors.Wrap(ctx, err, op)
}
}
if opts.withOplog {
if err := rw.addOplogForItems(ctx, CreateOp, opts, ticket, createItems); err != nil {
return errors.Wrap(err, op, errors.WithMsg("unable to add oplog"))
return errors.Wrap(ctx, err, op, errors.WithMsg("unable to add oplog"))
}
}
if opts.newOplogMsgs != nil {
msgs, err := rw.oplogMsgsForItems(ctx, CreateOp, opts, createItems)
if err != nil {
return errors.Wrap(err, op, errors.WithMsg("returning oplog msgs failed"))
return errors.Wrap(ctx, err, op, errors.WithMsg("returning oplog msgs failed"))
}
*opts.newOplogMsgs = append(*opts.newOplogMsgs, msgs...)
}
@@ -409,59 +409,59 @@ func (rw *Db) CreateItems(ctx context.Context, createItems []interface{}, opt ..
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, errors.New(errors.InvalidParameter, op, "missing underlying db")
return NoRowsAffected, errors.New(ctx, errors.InvalidParameter, op, "missing underlying db")
}
if isNil(i) {
return NoRowsAffected, errors.New(errors.InvalidParameter, op, "missing interface")
return NoRowsAffected, errors.New(ctx, errors.InvalidParameter, op, "missing interface")
}
if len(fieldMaskPaths) == 0 && len(setToNullPaths) == 0 {
return NoRowsAffected, errors.New(errors.InvalidParameter, op, "both fieldMaskPaths and setToNullPaths are missing")
return NoRowsAffected, errors.New(ctx, errors.InvalidParameter, op, "both fieldMaskPaths and setToNullPaths are missing")
}
opts := GetOpts(opt...)
withOplog := opts.withOplog
if withOplog && opts.newOplogMsg != nil {
return NoRowsAffected, errors.New(errors.InvalidParameter, op, "both WithOplog and NewOplogMsg options have been specified")
return NoRowsAffected, errors.New(ctx, 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, errors.New(errors.InvalidParameter, op, "after filtering non-updated fields, there are no fields left in fieldMaskPaths or setToNullPaths")
return NoRowsAffected, errors.New(ctx, 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, errors.Wrap(err, op, errors.WithMsg("getting update fields failed"))
return NoRowsAffected, errors.Wrap(ctx, err, op, errors.WithMsg("getting update fields failed"))
}
if len(updateFields) == 0 {
return NoRowsAffected, errors.New(errors.InvalidParameter, op, fmt.Sprintf("no fields matched using fieldMaskPaths %s", fieldMaskPaths))
return NoRowsAffected, errors.New(ctx, 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, errors.New(errors.InvalidParameter, op, "primary key is not set")
return NoRowsAffected, errors.New(ctx, errors.InvalidParameter, op, "primary key is not set")
}
for _, f := range scope.PrimaryFields() {
if contains(fieldMaskPaths, f.Name) {
return NoRowsAffected, errors.New(errors.InvalidFieldMask, op, fmt.Sprintf("not allowed on primary key field %s", f.Name))
return NoRowsAffected, errors.New(ctx, errors.InvalidFieldMask, op, fmt.Sprintf("not allowed on primary key field %s", f.Name))
}
}
if withOplog {
// let's validate oplog options before we start writing to the database
_, err := validateOplogArgs(i, opts)
_, err := validateOplogArgs(ctx, i, opts)
if err != nil {
return NoRowsAffected, errors.Wrap(err, op, errors.WithMsg("oplog validation failed"))
return NoRowsAffected, errors.Wrap(ctx, 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, errors.Wrap(err, op)
return NoRowsAffected, errors.Wrap(ctx, err, op)
}
}
}
@@ -470,7 +470,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, errors.Wrap(err, op, errors.WithMsg("unable to get ticket"))
return NoRowsAffected, errors.Wrap(ctx, err, op, errors.WithMsg("unable to get ticket"))
}
}
var underlying *gorm.DB
@@ -480,10 +480,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, errors.New(errors.InvalidParameter, op, "with version option is zero")
return NoRowsAffected, errors.New(ctx, errors.InvalidParameter, op, "with version option is zero")
}
if _, ok := scope.FieldByName("version"); !ok {
return NoRowsAffected, errors.New(errors.InvalidParameter, op, fmt.Sprintf("%s does not have a version field", scope.TableName()))
return NoRowsAffected, errors.New(ctx, errors.InvalidParameter, op, fmt.Sprintf("%s does not have a version field", scope.TableName()))
}
where, args = append(where, "version = ?"), append(args, opts.WithVersion)
}
@@ -496,9 +496,9 @@ func (rw *Db) Update(ctx context.Context, i interface{}, fieldMaskPaths []string
}
if underlying.Error != nil {
if underlying.Error == gorm.ErrRecordNotFound {
return NoRowsAffected, errors.E(errors.WithCode(errors.RecordNotFound), errors.WithOp(op))
return NoRowsAffected, errors.E(ctx, errors.WithCode(errors.RecordNotFound), errors.WithOp(op))
}
return NoRowsAffected, errors.Wrap(underlying.Error, op)
return NoRowsAffected, errors.Wrap(ctx, underlying.Error, op)
}
rowsUpdated := int(underlying.RowsAffected)
if rowsUpdated > 0 && (withOplog || opts.newOplogMsg != nil) {
@@ -516,13 +516,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, errors.Wrap(err, op, errors.WithMsg("add oplog failed"))
return rowsUpdated, errors.Wrap(ctx, 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, errors.Wrap(err, op, errors.WithMsg("returning oplog failed"))
return rowsUpdated, errors.Wrap(ctx, err, op, errors.WithMsg("returning oplog failed"))
}
*opts.newOplogMsg = *msg
}
@@ -531,7 +531,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, errors.Wrap(err, op)
return NoRowsAffected, errors.Wrap(ctx, err, op)
}
return rowsUpdated, nil
}
@@ -544,28 +544,28 @@ func (rw *Db) Update(ctx context.Context, i interface{}, fieldMaskPaths []string
func (rw *Db) Delete(ctx context.Context, i interface{}, opt ...Option) (int, error) {
const op = "db.Delete"
if rw.underlying == nil {
return NoRowsAffected, errors.New(errors.InvalidParameter, op, "missing underlying db")
return NoRowsAffected, errors.New(ctx, errors.InvalidParameter, op, "missing underlying db")
}
if isNil(i) {
return NoRowsAffected, errors.New(errors.InvalidParameter, op, "missing interface")
return NoRowsAffected, errors.New(ctx, errors.InvalidParameter, op, "missing interface")
}
opts := GetOpts(opt...)
withOplog := opts.withOplog
if withOplog && opts.newOplogMsg != nil {
return NoRowsAffected, errors.New(errors.InvalidParameter, op, "both WithOplog and NewOplogMsg options have been specified")
return NoRowsAffected, errors.New(ctx, 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, errors.New(errors.InvalidParameter, op, "primary key is not set")
return NoRowsAffected, errors.New(ctx, errors.InvalidParameter, op, "primary key is not set")
}
}
if withOplog {
_, err := validateOplogArgs(i, opts)
_, err := validateOplogArgs(ctx, i, opts)
if err != nil {
return NoRowsAffected, errors.Wrap(err, op, errors.WithMsg("oplog validation failed"))
return NoRowsAffected, errors.Wrap(ctx, err, op, errors.WithMsg("oplog validation failed"))
}
}
var ticket *store.Ticket
@@ -573,7 +573,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, errors.Wrap(err, op, errors.WithMsg("unable to get ticket"))
return NoRowsAffected, errors.Wrap(ctx, err, op, errors.WithMsg("unable to get ticket"))
}
}
db := rw.underlying
@@ -582,19 +582,19 @@ func (rw *Db) Delete(ctx context.Context, i interface{}, opt ...Option) (int, er
}
db = db.Delete(i)
if db.Error != nil {
return NoRowsAffected, errors.Wrap(db.Error, op)
return NoRowsAffected, errors.Wrap(ctx, 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, errors.Wrap(err, op, errors.WithMsg("add oplog failed"))
return rowsDeleted, errors.Wrap(ctx, err, op, errors.WithMsg("add oplog failed"))
}
}
if opts.newOplogMsg != nil {
msg, err := rw.newOplogMessage(ctx, DeleteOp, i)
if err != nil {
return rowsDeleted, errors.Wrap(err, op, errors.WithMsg("returning oplog failed"))
return rowsDeleted, errors.Wrap(ctx, err, op, errors.WithMsg("returning oplog failed"))
}
*opts.newOplogMsg = *msg
}
@@ -608,17 +608,17 @@ func (rw *Db) Delete(ctx context.Context, i interface{}, opt ...Option) (int, er
func (rw *Db) DeleteItems(ctx context.Context, deleteItems []interface{}, opt ...Option) (int, error) {
const op = "db.DeleteItems"
if rw.underlying == nil {
return NoRowsAffected, errors.New(errors.InvalidParameter, op, "missing underlying db")
return NoRowsAffected, errors.New(ctx, errors.InvalidParameter, op, "missing underlying db")
}
if len(deleteItems) == 0 {
return NoRowsAffected, errors.New(errors.InvalidParameter, op, "no interfaces to delete")
return NoRowsAffected, errors.New(ctx, errors.InvalidParameter, op, "no interfaces to delete")
}
opts := GetOpts(opt...)
if opts.newOplogMsg != nil {
return NoRowsAffected, errors.New(errors.InvalidParameter, op, "new oplog msg (singular) is not a supported option")
return NoRowsAffected, errors.New(ctx, errors.InvalidParameter, op, "new oplog msg (singular) is not a supported option")
}
if opts.withOplog && opts.newOplogMsgs != nil {
return NoRowsAffected, errors.New(errors.InvalidParameter, op, "both WithOplog and NewOplogMsgs options have been specified")
return NoRowsAffected, errors.New(ctx, errors.InvalidParameter, op, "both WithOplog and NewOplogMsgs options have been specified")
}
// verify that createItems are all the same type.
var foundType reflect.Type
@@ -628,19 +628,19 @@ func (rw *Db) DeleteItems(ctx context.Context, deleteItems []interface{}, opt ..
}
currentType := reflect.TypeOf(v)
if foundType != currentType {
return NoRowsAffected, errors.New(errors.InvalidParameter, op, fmt.Sprintf("items contain disparate types. item %d is not a %s", i, foundType.Name()))
return NoRowsAffected, errors.New(ctx, errors.InvalidParameter, op, fmt.Sprintf("items contain disparate types. item %d is not a %s", i, foundType.Name()))
}
}
var ticket *store.Ticket
if opts.withOplog {
_, err := validateOplogArgs(deleteItems[0], opts)
_, err := validateOplogArgs(ctx, deleteItems[0], opts)
if err != nil {
return NoRowsAffected, errors.Wrap(err, op, errors.WithMsg("oplog validation failed"))
return NoRowsAffected, errors.Wrap(ctx, err, op, errors.WithMsg("oplog validation failed"))
}
ticket, err = rw.GetTicket(deleteItems[0])
if err != nil {
return NoRowsAffected, errors.Wrap(err, op, errors.WithMsg("unable to get ticket"))
return NoRowsAffected, errors.Wrap(ctx, err, op, errors.WithMsg("unable to get ticket"))
}
}
rowsDeleted := 0
@@ -650,20 +650,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, errors.Wrap(underlying.Error, op)
return rowsDeleted, errors.Wrap(ctx, 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, errors.Wrap(err, op, errors.WithMsg("unable to add oplog"))
return rowsDeleted, errors.Wrap(ctx, 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, errors.Wrap(err, op, errors.WithMsg("returning oplog msgs failed"))
return rowsDeleted, errors.Wrap(ctx, err, op, errors.WithMsg("returning oplog msgs failed"))
}
*opts.newOplogMsgs = append(*opts.newOplogMsgs, msgs...)
}
@@ -671,18 +671,18 @@ func (rw *Db) DeleteItems(ctx context.Context, deleteItems []interface{}, opt ..
return rowsDeleted, nil
}
func validateOplogArgs(i interface{}, opts Options) (oplog.ReplayableMessage, error) {
func validateOplogArgs(ctx context.Context, i interface{}, opts Options) (oplog.ReplayableMessage, error) {
const op = "db.validateOplogArgs"
oplogArgs := opts.oplogOpts
if oplogArgs.wrapper == nil {
return nil, errors.New(errors.InvalidParameter, op, "missing wrapper")
return nil, errors.New(ctx, errors.InvalidParameter, op, "missing wrapper")
}
if len(oplogArgs.metadata) == 0 {
return nil, errors.New(errors.InvalidParameter, op, "missing metadata")
return nil, errors.New(ctx, errors.InvalidParameter, op, "missing metadata")
}
replayable, ok := i.(oplog.ReplayableMessage)
if !ok {
return nil, errors.E(errors.WithOp(op), errors.WithMsg("not a replayable message"))
return nil, errors.E(ctx, errors.WithOp(op), errors.WithMsg("not a replayable message"))
}
return replayable, nil
}
@@ -690,15 +690,15 @@ func validateOplogArgs(i interface{}, opts Options) (oplog.ReplayableMessage, er
func (rw *Db) getTicketFor(aggregateName string) (*store.Ticket, error) {
const op = "db.getTicketFor"
if rw.underlying == nil {
return nil, errors.New(errors.InvalidParameter, op, fmt.Sprintf("%s: underlying db missing", aggregateName))
return nil, errors.NewDeprecated(errors.InvalidParameter, op, fmt.Sprintf("%s: underlying db missing", aggregateName))
}
ticketer, err := oplog.NewGormTicketer(rw.underlying, oplog.WithAggregateNames(true))
if err != nil {
return nil, errors.Wrap(err, op, errors.WithMsg(fmt.Sprintf("%s: unable to get Ticketer", aggregateName)))
return nil, errors.WrapDeprecated(err, op, errors.WithMsg(fmt.Sprintf("%s: unable to get Ticketer", aggregateName)))
}
ticket, err := ticketer.GetTicket(aggregateName)
if err != nil {
return nil, errors.Wrap(err, op, errors.WithMsg(fmt.Sprintf("%s: unable to get ticket", aggregateName)))
return nil, errors.WrapDeprecated(err, op, errors.WithMsg(fmt.Sprintf("%s: unable to get ticket", aggregateName)))
}
return ticket, nil
}
@@ -708,14 +708,14 @@ func (rw *Db) getTicketFor(aggregateName string) (*store.Ticket, error) {
func (rw *Db) GetTicket(i interface{}) (*store.Ticket, error) {
const op = "db.GetTicket"
if rw.underlying == nil {
return nil, errors.New(errors.InvalidParameter, op, "missing underlying db")
return nil, errors.NewDeprecated(errors.InvalidParameter, op, "missing underlying db")
}
if isNil(i) {
return nil, errors.New(errors.InvalidParameter, op, "missing interface")
return nil, errors.NewDeprecated(errors.InvalidParameter, op, "missing interface")
}
replayable, ok := i.(oplog.ReplayableMessage)
if !ok {
return nil, errors.New(errors.InvalidParameter, op, "not a replayable message")
return nil, errors.NewDeprecated(errors.InvalidParameter, op, "not a replayable message")
}
return rw.getTicketFor(replayable.TableName())
}
@@ -723,7 +723,7 @@ func (rw *Db) GetTicket(i interface{}) (*store.Ticket, error) {
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, errors.New(errors.InvalidParameter, op, "missing items")
return nil, errors.New(ctx, errors.InvalidParameter, op, "missing items")
}
oplogMsgs := []*oplog.Message{}
var foundType reflect.Type
@@ -733,11 +733,11 @@ func (rw *Db) oplogMsgsForItems(ctx context.Context, opType OpType, opts Options
}
currentType := reflect.TypeOf(item)
if foundType != currentType {
return nil, errors.New(errors.InvalidParameter, op, fmt.Sprintf("items contains disparate types. item (%d) %s is not a %s", i, currentType, foundType))
return nil, errors.New(ctx, 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, errors.Wrap(err, op)
return nil, errors.Wrap(ctx, err, op)
}
oplogMsgs = append(oplogMsgs, msg)
}
@@ -751,30 +751,30 @@ func (rw *Db) addOplogForItems(ctx context.Context, opType OpType, opts Options,
const op = "db.addOplogForItems"
oplogArgs := opts.oplogOpts
if ticket == nil {
return errors.New(errors.InvalidParameter, op, "missing ticket")
return errors.New(ctx, errors.InvalidParameter, op, "missing ticket")
}
if len(items) == 0 {
return errors.New(errors.InvalidParameter, op, "missing items")
return errors.New(ctx, errors.InvalidParameter, op, "missing items")
}
if oplogArgs.metadata == nil {
return errors.New(errors.InvalidParameter, op, "missing metadata")
return errors.New(ctx, errors.InvalidParameter, op, "missing metadata")
}
if oplogArgs.wrapper == nil {
return errors.New(errors.InvalidParameter, op, "missing wrapper")
return errors.New(ctx, errors.InvalidParameter, op, "missing wrapper")
}
oplogMsgs, err := rw.oplogMsgsForItems(ctx, opType, opts, items)
if err != nil {
return errors.Wrap(err, op)
return errors.Wrap(ctx, err, op)
}
replayable, err := validateOplogArgs(items[0], opts)
replayable, err := validateOplogArgs(ctx, items[0], opts)
if err != nil {
return errors.Wrap(err, op, errors.WithMsg("oplog validation failed"))
return errors.Wrap(ctx, err, op, errors.WithMsg("oplog validation failed"))
}
ticketer, err := oplog.NewGormTicketer(rw.underlying, oplog.WithAggregateNames(true))
if err != nil {
return errors.Wrap(err, op, errors.WithMsg("unable to get Ticketer"))
return errors.Wrap(ctx, err, op, errors.WithMsg("unable to get Ticketer"))
}
entry, err := oplog.NewEntry(
replayable.TableName(),
@@ -783,7 +783,7 @@ func (rw *Db) addOplogForItems(ctx context.Context, opType OpType, opts Options,
ticketer,
)
if err != nil {
return errors.Wrap(err, op, errors.WithMsg("unable to create oplog entry"))
return errors.Wrap(ctx, err, op, errors.WithMsg("unable to create oplog entry"))
}
if err := entry.WriteEntryWith(
ctx,
@@ -791,7 +791,7 @@ func (rw *Db) addOplogForItems(ctx context.Context, opType OpType, opts Options,
ticket,
oplogMsgs...,
); err != nil {
return errors.Wrap(err, op, errors.WithMsg("unable to write oplog entry"))
return errors.Wrap(ctx, err, op, errors.WithMsg("unable to write oplog entry"))
}
return nil
}
@@ -799,16 +799,16 @@ func (rw *Db) addOplogForItems(ctx context.Context, opType OpType, opts Options,
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)
replayable, err := validateOplogArgs(ctx, i, opts)
if err != nil {
return errors.Wrap(err, op)
return errors.Wrap(ctx, err, op)
}
if ticket == nil {
return errors.New(errors.InvalidParameter, op, "missing ticket")
return errors.New(ctx, errors.InvalidParameter, op, "missing ticket")
}
ticketer, err := oplog.NewGormTicketer(rw.underlying, oplog.WithAggregateNames(true))
if err != nil {
return errors.Wrap(err, op, errors.WithMsg("unable to get Ticketer"))
return errors.Wrap(ctx, err, op, errors.WithMsg("unable to get Ticketer"))
}
entry, err := oplog.NewEntry(
replayable.TableName(),
@@ -817,11 +817,11 @@ func (rw *Db) addOplog(ctx context.Context, opType OpType, opts Options, ticket
ticketer,
)
if err != nil {
return errors.Wrap(err, op)
return errors.Wrap(ctx, err, op)
}
msg, err := rw.newOplogMessage(ctx, opType, i, WithFieldMaskPaths(opts.WithFieldMaskPaths), WithNullPaths(opts.WithNullPaths))
if err != nil {
return errors.Wrap(err, op)
return errors.Wrap(ctx, err, op)
}
err = entry.WriteEntryWith(
ctx,
@@ -830,7 +830,7 @@ func (rw *Db) addOplog(ctx context.Context, opType OpType, opts Options, ticket
msg,
)
if err != nil {
return errors.Wrap(err, op, errors.WithMsg("unable to write oplog entry"))
return errors.Wrap(ctx, err, op, errors.WithMsg("unable to write oplog entry"))
}
return nil
}
@@ -840,24 +840,24 @@ func (rw *Db) addOplog(ctx context.Context, opType OpType, opts Options, ticket
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 errors.New(errors.InvalidParameter, op, "missing wrapper")
return errors.New(ctx, errors.InvalidParameter, op, "missing wrapper")
}
if ticket == nil {
return errors.New(errors.InvalidParameter, op, "missing ticket")
return errors.New(ctx, errors.InvalidParameter, op, "missing ticket")
}
if len(msgs) == 0 {
return errors.New(errors.InvalidParameter, op, "missing msgs")
return errors.New(ctx, errors.InvalidParameter, op, "missing msgs")
}
if rw.underlying == nil {
return errors.New(errors.InvalidParameter, op, "missing underlying db")
return errors.New(ctx, errors.InvalidParameter, op, "missing underlying db")
}
if len(metadata) == 0 {
return errors.New(errors.InvalidParameter, op, "missing metadata")
return errors.New(ctx, errors.InvalidParameter, op, "missing metadata")
}
ticketer, err := oplog.NewGormTicketer(rw.underlying, oplog.WithAggregateNames(true))
if err != nil {
return errors.Wrap(err, op, errors.WithMsg("unable to get Ticketer"))
return errors.Wrap(ctx, err, op, errors.WithMsg("unable to get Ticketer"))
}
entry, err := oplog.NewEntry(
@@ -867,7 +867,7 @@ func (rw *Db) WriteOplogEntryWith(ctx context.Context, wrapper wrapping.Wrapper,
ticketer,
)
if err != nil {
return errors.Wrap(err, op, errors.WithMsg("unable to create oplog entry"))
return errors.Wrap(ctx, err, op, errors.WithMsg("unable to create oplog entry"))
}
err = entry.WriteEntryWith(
ctx,
@@ -876,17 +876,17 @@ func (rw *Db) WriteOplogEntryWith(ctx context.Context, wrapper wrapping.Wrapper,
msgs...,
)
if err != nil {
return errors.Wrap(err, op, errors.WithMsg("unable to write oplog entry"))
return errors.Wrap(ctx, err, op, errors.WithMsg("unable to write oplog entry"))
}
return nil
}
func (rw *Db) newOplogMessage(_ context.Context, opType OpType, i interface{}, opt ...Option) (*oplog.Message, error) {
func (rw *Db) newOplogMessage(ctx 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, errors.New(errors.InvalidParameter, op, "not a replayable interface")
return nil, errors.New(ctx, errors.InvalidParameter, op, "not a replayable interface")
}
msg := oplog.Message{
Message: i.(proto.Message),
@@ -902,7 +902,7 @@ func (rw *Db) newOplogMessage(_ context.Context, opType OpType, i interface{}, o
case DeleteOp:
msg.OpType = oplog.OpType_OP_TYPE_DELETE
default:
return nil, errors.New(errors.InvalidParameter, op, fmt.Sprintf("operation type %v is not supported", opType))
return nil, errors.New(ctx, errors.InvalidParameter, op, fmt.Sprintf("operation type %v is not supported", opType))
}
return &msg, nil
}
@@ -914,12 +914,12 @@ func (rw *Db) newOplogMessage(_ context.Context, opType OpType, i interface{}, o
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{}, errors.New(errors.InvalidParameter, op, "missing underlying db")
return RetryInfo{}, errors.New(ctx, errors.InvalidParameter, op, "missing underlying db")
}
info := RetryInfo{}
for attempts := uint(1); ; attempts++ {
if attempts > retries+1 {
return info, errors.New(errors.MaxRetries, op, fmt.Sprintf("Too many retries: %d of %d", attempts-1, retries+1))
return info, errors.New(ctx, errors.MaxRetries, op, fmt.Sprintf("Too many retries: %d of %d", attempts-1, retries+1))
}
// step one of this, start a transaction...
@@ -928,7 +928,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, errors.Wrap(err, op)
return info, errors.Wrap(ctx, err, op)
}
if errors.Match(errors.T(errors.TicketAlreadyRedeemed), err) {
d := backOff.Duration(attempts)
@@ -937,14 +937,14 @@ func (w *Db) DoTx(ctx context.Context, retries uint, backOff Backoff, Handler Tx
time.Sleep(d)
continue
}
return info, errors.Wrap(err, op)
return info, errors.Wrap(ctx, err, op, errors.WithoutEvent())
}
if err := newTx.Commit().Error; err != nil {
if err := newTx.Rollback().Error; err != nil {
return info, errors.Wrap(err, op)
return info, errors.Wrap(ctx, err, op)
}
return info, errors.Wrap(err, op)
return info, errors.Wrap(ctx, err, op)
}
return info, nil // it all worked!!!
}
@@ -952,28 +952,28 @@ 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(_ context.Context, resourceWithIder interface{}, _ ...Option) error {
func (rw *Db) LookupById(ctx context.Context, resourceWithIder interface{}, _ ...Option) error {
const op = "db.LookupById"
if rw.underlying == nil {
return errors.New(errors.InvalidParameter, op, "missing underlying db")
return errors.New(ctx, errors.InvalidParameter, op, "missing underlying db")
}
if reflect.ValueOf(resourceWithIder).Kind() != reflect.Ptr {
return errors.New(errors.InvalidParameter, op, "interface parameter must to be a pointer")
return errors.New(ctx, errors.InvalidParameter, op, "interface parameter must to be a pointer")
}
primaryKey, where, err := primaryKeyWhere(resourceWithIder)
primaryKey, where, err := primaryKeyWhere(ctx, resourceWithIder)
if err != nil {
return errors.Wrap(err, op)
return errors.Wrap(ctx, err, op)
}
if err := rw.underlying.Where(where, primaryKey).First(resourceWithIder).Error; err != nil {
if err == gorm.ErrRecordNotFound {
return errors.E(errors.WithCode(errors.RecordNotFound), errors.WithOp(op))
return errors.E(ctx, errors.WithCode(errors.RecordNotFound), errors.WithOp(op))
}
return errors.Wrap(err, op)
return errors.Wrap(ctx, err, op)
}
return nil
}
func primaryKeyWhere(resourceWithIder interface{}) (pkey string, w string, e error) {
func primaryKeyWhere(ctx context.Context, resourceWithIder interface{}) (pkey string, w string, e error) {
const op = "db.primaryKeyWhere"
var primaryKey, where string
switch resourceType := resourceWithIder.(type) {
@@ -984,10 +984,10 @@ func primaryKeyWhere(resourceWithIder interface{}) (pkey string, w string, e err
primaryKey = resourceType.GetPrivateId()
where = "private_id = ?"
default:
return "", "", errors.New(errors.InvalidParameter, op, fmt.Sprintf("unsupported interface type %T", resourceWithIder))
return "", "", errors.New(ctx, errors.InvalidParameter, op, fmt.Sprintf("unsupported interface type %T", resourceWithIder))
}
if primaryKey == "" {
return "", "", errors.New(errors.InvalidParameter, op, "missing primary key")
return "", "", errors.New(ctx, errors.InvalidParameter, op, "missing primary key")
}
return primaryKey, where, nil
}
@@ -999,19 +999,19 @@ 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(_ context.Context, resource interface{}, where string, args ...interface{}) error {
func (rw *Db) LookupWhere(ctx context.Context, resource interface{}, where string, args ...interface{}) error {
const op = "db.LookupWhere"
if rw.underlying == nil {
return errors.New(errors.InvalidParameter, op, "missing underlying db")
return errors.New(ctx, errors.InvalidParameter, op, "missing underlying db")
}
if reflect.ValueOf(resource).Kind() != reflect.Ptr {
return errors.New(errors.InvalidParameter, op, "interface parameter must to be a pointer")
return errors.New(ctx, 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.E(errors.WithCode(errors.RecordNotFound), errors.WithOp(op))
return errors.E(ctx, errors.WithCode(errors.RecordNotFound), errors.WithOp(op))
}
return errors.Wrap(err, op)
return errors.Wrap(ctx, err, op)
}
return nil
}
@@ -1023,17 +1023,17 @@ func (rw *Db) LookupWhere(_ context.Context, resource interface{}, where string,
// 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(_ context.Context, resources interface{}, where string, args []interface{}, opt ...Option) error {
func (rw *Db) SearchWhere(ctx context.Context, resources interface{}, where string, args []interface{}, opt ...Option) error {
const op = "db.SearchWhere"
opts := GetOpts(opt...)
if rw.underlying == nil {
return errors.New(errors.InvalidParameter, op, "missing underlying db")
return errors.New(ctx, errors.InvalidParameter, op, "missing underlying db")
}
if where == "" && len(args) > 0 {
return errors.New(errors.InvalidParameter, op, "args provided with empty where")
return errors.New(ctx, errors.InvalidParameter, op, "args provided with empty where")
}
if reflect.ValueOf(resources).Kind() != reflect.Ptr {
return errors.New(errors.InvalidParameter, op, "interface parameter must to be a pointer")
return errors.New(ctx, errors.InvalidParameter, op, "interface parameter must to be a pointer")
}
var err error
db := rw.underlying.Order(opts.withOrder)
@@ -1055,7 +1055,7 @@ func (rw *Db) SearchWhere(_ context.Context, resources interface{}, where string
err = db.Find(resources).Error
if err != nil {
// searching with a slice parameter does not return a gorm.ErrRecordNotFound
return errors.Wrap(err, op)
return errors.Wrap(ctx, err, op)
}
return nil
}
@@ -1127,11 +1127,11 @@ func Clear(i interface{}, fields []string, depth int) error {
switch v.Kind() {
case reflect.Ptr:
if v.IsNil() || v.Elem().Kind() != reflect.Struct {
return errors.E(errors.WithCode(errors.InvalidParameter), errors.WithOp(op))
return errors.EDeprecated(errors.WithCode(errors.InvalidParameter), errors.WithOp(op), errors.WithoutEvent())
}
clear(v, fm, depth)
default:
return errors.E(errors.WithCode(errors.InvalidParameter), errors.WithOp(op))
return errors.EDeprecated(errors.WithCode(errors.InvalidParameter), errors.WithOp(op), errors.WithoutEvent())
}
return nil
}
+6 -5
View File
@@ -1066,6 +1066,7 @@ func TestDb_Exec(t *testing.T) {
func TestDb_DoTx(t *testing.T) {
t.Parallel()
ctx := context.TODO()
db, _ := TestSetup(t, "postgres")
t.Run("valid-with-10-retries", func(t *testing.T) {
assert, require := assert.New(t), require.New(t)
@@ -1075,7 +1076,7 @@ func TestDb_DoTx(t *testing.T) {
func(Reader, Writer) error {
attempts += 1
if attempts < 9 {
return errors.E(errors.WithCode(errors.TicketAlreadyRedeemed))
return errors.E(ctx, errors.WithCode(errors.TicketAlreadyRedeemed))
}
return nil
})
@@ -1091,7 +1092,7 @@ func TestDb_DoTx(t *testing.T) {
func(Reader, Writer) error {
attempts += 1
if attempts < 2 {
return errors.E(errors.WithCode(errors.TicketAlreadyRedeemed))
return errors.E(ctx, errors.WithCode(errors.TicketAlreadyRedeemed))
}
return nil
})
@@ -1107,7 +1108,7 @@ func TestDb_DoTx(t *testing.T) {
func(Reader, Writer) error {
attempts += 1
if attempts < 3 {
return errors.E(errors.WithCode(errors.TicketAlreadyRedeemed))
return errors.E(ctx, errors.WithCode(errors.TicketAlreadyRedeemed))
}
return nil
})
@@ -1123,7 +1124,7 @@ func TestDb_DoTx(t *testing.T) {
func(Reader, Writer) error {
attempts += 1
if attempts < 4 {
return errors.E(errors.WithCode(errors.TicketAlreadyRedeemed))
return errors.E(ctx, errors.WithCode(errors.TicketAlreadyRedeemed))
}
return nil
})
@@ -1163,7 +1164,7 @@ func TestDb_DoTx(t *testing.T) {
attempts := 0
got, err := w.DoTx(context.Background(), 2, ExpBackoff{}, func(Reader, Writer) error {
attempts += 1
return errors.E(errors.WithCode(errors.TicketAlreadyRedeemed))
return errors.E(ctx, errors.WithCode(errors.TicketAlreadyRedeemed))
})
require.Error(err)
assert.Equal(3, got.Retries)
+22 -22
View File
@@ -63,10 +63,10 @@ func NewManager(ctx context.Context, dialect string, db *sql.DB, opt ...Option)
var err error
dbM.driver, err = postgres.New(ctx, db)
if err != nil {
return nil, errors.Wrap(err, op)
return nil, errors.Wrap(ctx, err, op)
}
default:
return nil, errors.New(errors.InvalidParameter, op, fmt.Sprintf("unknown dialect %q", dialect))
return nil, errors.New(ctx, errors.InvalidParameter, op, fmt.Sprintf("unknown dialect %q", dialect))
}
return &dbM, nil
}
@@ -92,7 +92,7 @@ func (b *Manager) CurrentState(ctx context.Context) (*State, error) {
v, initialized, dirty, err := b.driver.CurrentState(ctx)
if err != nil {
return nil, errors.Wrap(err, op)
return nil, errors.Wrap(ctx, err, op)
}
dbS.InitializationStarted = initialized
dbS.DatabaseSchemaVersion = v
@@ -106,7 +106,7 @@ func (b *Manager) CurrentState(ctx context.Context) (*State, error) {
func (b *Manager) SharedLock(ctx context.Context) error {
const op = "schema.(Manager).SharedLock"
if err := b.driver.TrySharedLock(ctx); err != nil {
return errors.Wrap(err, op)
return errors.Wrap(ctx, err, op)
}
return nil
}
@@ -117,7 +117,7 @@ func (b *Manager) SharedLock(ctx context.Context) error {
func (b *Manager) SharedUnlock(ctx context.Context) error {
const op = "schema.(Manager).SharedUnlock"
if err := b.driver.UnlockShared(ctx); err != nil {
return errors.Wrap(err, op)
return errors.Wrap(ctx, err, op)
}
return nil
}
@@ -127,7 +127,7 @@ func (b *Manager) SharedUnlock(ctx context.Context) error {
func (b *Manager) ExclusiveLock(ctx context.Context) error {
const op = "schema.(Manager).ExclusiveLock"
if err := b.driver.TryLock(ctx); err != nil {
return errors.Wrap(err, op)
return errors.Wrap(ctx, err, op)
}
return nil
}
@@ -138,7 +138,7 @@ func (b *Manager) ExclusiveLock(ctx context.Context) error {
func (b *Manager) ExclusiveUnlock(ctx context.Context) error {
const op = "schema.(Manager).ExclusiveUnlock"
if err := b.driver.Unlock(ctx); err != nil {
return errors.Wrap(err, op)
return errors.Wrap(ctx, err, op)
}
return nil
}
@@ -151,27 +151,27 @@ func (b *Manager) RollForward(ctx context.Context) error {
// Capturing a lock that this session to the db already possesses is okay.
if err := b.driver.Lock(ctx); err != nil {
return errors.Wrap(err, op)
return errors.Wrap(ctx, err, op)
}
defer func() {
if err := b.driver.Unlock(ctx); err != nil {
// I'm not sure this is ideal, but we have to rollback the current
// transaction if we're unable to release the lock
panic(errors.Wrap(err, op))
panic(errors.Wrap(ctx, err, op))
}
}()
curVersion, _, dirty, err := b.driver.CurrentState(ctx)
if err != nil {
return errors.Wrap(err, op)
return errors.Wrap(ctx, err, op)
}
if dirty {
return errors.New(errors.NotSpecificIntegrity, op, fmt.Sprintf("schema is dirty with version %d", curVersion))
return errors.New(ctx, errors.NotSpecificIntegrity, op, fmt.Sprintf("schema is dirty with version %d", curVersion))
}
if err = b.runMigrations(ctx, newStatementProvider(b.dialect, curVersion, WithMigrationStates(b.migrationStates))); err != nil {
return errors.Wrap(err, op)
return errors.Wrap(ctx, err, op)
}
return nil
}
@@ -187,10 +187,10 @@ func (b *Manager) runMigrations(ctx context.Context, qp *statementProvider) erro
const op = "schema.(Manager).runMigrations"
if err := b.driver.StartRun(ctx); err != nil {
return errors.Wrap(err, op)
return errors.Wrap(ctx, err, op)
}
if err := b.driver.EnsureVersionTable(ctx); err != nil {
return errors.Wrap(err, op)
return errors.Wrap(ctx, err, op)
}
for qp.Next() {
select {
@@ -201,16 +201,16 @@ func (b *Manager) runMigrations(ctx context.Context, qp *statementProvider) erro
err = multierror.Append(err, rbErr)
}
}
return errors.Wrap(err, op)
return errors.Wrap(ctx, err, op)
default:
// context is not done yet. Continue on to the next query to execute.
}
if err := b.driver.Run(ctx, bytes.NewReader(qp.ReadUp()), qp.Version()); err != nil {
return errors.Wrap(err, op)
return errors.Wrap(ctx, err, op)
}
}
if err := b.driver.CommitRun(); err != nil {
return errors.Wrap(err, op)
return errors.Wrap(ctx, err, op)
}
return nil
}
@@ -230,11 +230,11 @@ func GetMigrationLog(ctx context.Context, d *sql.DB, opt ...Option) ([]LogEntry,
const op = "schema.GetMigrationLog"
const sql = "select id, create_time, migration_version, entry from log_migration where migration_version in (select max(version) from boundary_schema_version)"
if d == nil {
return nil, errors.New(errors.InvalidParameter, op, "missing sql db")
return nil, errors.New(ctx, errors.InvalidParameter, op, "missing sql db")
}
rows, err := d.QueryContext(ctx, sql)
if err != nil {
return nil, errors.Wrap(err, op)
return nil, errors.Wrap(ctx, err, op)
}
defer rows.Close()
@@ -242,19 +242,19 @@ func GetMigrationLog(ctx context.Context, d *sql.DB, opt ...Option) ([]LogEntry,
for rows.Next() {
var e LogEntry
if err := rows.Scan(&e.Id, &e.CreateTime, &e.MigrationVersion, &e.Entry); err != nil {
return nil, errors.Wrap(err, op)
return nil, errors.Wrap(ctx, err, op)
}
entries = append(entries, e)
}
if rows.Err() != nil {
return nil, errors.Wrap(err, op)
return nil, errors.Wrap(ctx, err, op)
}
opts := getOpts(opt...)
if opts.withDeleteLog {
// this truncate could change to a delete if FKs are needed in the future
_, err = d.ExecContext(ctx, "truncate log_migration")
if err != nil {
return nil, errors.Wrap(err, op)
return nil, errors.Wrap(ctx, err, op)
}
}
return entries, nil
@@ -24,11 +24,11 @@ func Test_AuthMethodSubtypes(t *testing.T) {
kmsCache := kms.TestKms(t, conn, rootWrapper)
iamRepo := iam.TestRepo(t, conn, rootWrapper)
org, _ := iam.TestScopes(t, iamRepo)
oidcRepo, err := oidc.NewRepository(rw, rw, kmsCache)
oidcRepo, err := oidc.NewRepository(ctx, rw, rw, kmsCache)
require.NoError(err)
// test oidc subtype insert
oidcAm, err := oidc.NewAuthMethod(org.PublicId, "alice-rp", "fido", oidc.WithName("alice"))
oidcAm, err := oidc.NewAuthMethod(ctx, org.PublicId, "alice-rp", "fido", oidc.WithName("alice"))
require.NoError(err)
oidcAm, err = oidcRepo.CreateAuthMethod(ctx, oidcAm)
require.NoError(err)
+36 -36
View File
@@ -66,11 +66,11 @@ type Postgres struct {
func New(ctx context.Context, instance *sql.DB) (*Postgres, error) {
const op = "postgres.New"
if err := instance.PingContext(ctx); err != nil {
return nil, errors.Wrap(err, op)
return nil, errors.Wrap(ctx, err, op)
}
conn, err := instance.Conn(ctx)
if err != nil {
return nil, errors.Wrap(err, op)
return nil, errors.Wrap(ctx, err, op)
}
px := &Postgres{
@@ -87,14 +87,14 @@ func (p *Postgres) TrySharedLock(ctx context.Context) error {
const query = "select pg_try_advisory_lock_shared($1)"
r := p.conn.QueryRowContext(ctx, query, schemaAccessLockId)
if r.Err() != nil {
return errors.Wrap(r.Err(), op)
return errors.Wrap(ctx, r.Err(), op)
}
var gotLock bool
if err := r.Scan(&gotLock); err != nil {
return errors.Wrap(err, op)
return errors.Wrap(ctx, err, op)
}
if !gotLock {
return errors.New(errors.MigrationLock, op, "Lock failed")
return errors.New(ctx, errors.MigrationLock, op, "Lock failed")
}
return nil
}
@@ -106,14 +106,14 @@ func (p *Postgres) TryLock(ctx context.Context) error {
const query = "select pg_try_advisory_lock($1)"
r := p.conn.QueryRowContext(ctx, query, schemaAccessLockId)
if r.Err() != nil {
return errors.Wrap(r.Err(), op)
return errors.Wrap(ctx, r.Err(), op)
}
var gotLock bool
if err := r.Scan(&gotLock); err != nil {
return errors.Wrap(err, op)
return errors.Wrap(ctx, err, op)
}
if !gotLock {
return errors.New(errors.MigrationLock, op, "Lock failed")
return errors.New(ctx, errors.MigrationLock, op, "Lock failed")
}
return nil
}
@@ -124,7 +124,7 @@ func (p *Postgres) Lock(ctx context.Context) error {
const op = "postgres.(Postgres).Lock"
const query = "select pg_advisory_lock($1)"
if _, err := p.conn.ExecContext(ctx, query, schemaAccessLockId); err != nil {
return errors.Wrap(err, op)
return errors.Wrap(ctx, err, op)
}
return nil
}
@@ -135,7 +135,7 @@ func (p *Postgres) Unlock(ctx context.Context) error {
const op = "postgres.(Postgres).Unlock"
const query = `select pg_advisory_unlock($1)`
if _, err := p.conn.ExecContext(ctx, query, schemaAccessLockId); err != nil {
return errors.Wrap(err, op)
return errors.Wrap(ctx, err, op)
}
return nil
}
@@ -146,7 +146,7 @@ func (p *Postgres) UnlockShared(ctx context.Context) error {
const op = "postgres.(Postgres).UnlockShared"
query := `select pg_advisory_unlock_shared($1)`
if _, err := p.conn.ExecContext(ctx, query, schemaAccessLockId); err != nil {
return errors.Wrap(err, op)
return errors.Wrap(ctx, err, op)
}
return nil
}
@@ -159,10 +159,10 @@ func (p *Postgres) Rollback() error {
p.tx = nil
}()
if p.tx == nil {
return errors.New(errors.MigrationIntegrity, op, "no pending transaction")
return errors.NewDeprecated(errors.MigrationIntegrity, op, "no pending transaction")
}
if err := p.tx.Rollback(); err != nil {
return errors.Wrap(err, op)
return errors.WrapDeprecated(err, op)
}
return nil
}
@@ -184,13 +184,13 @@ func (p *Postgres) CommitRun() error {
p.tx = nil
}()
if p.tx == nil {
return errors.New(errors.MigrationIntegrity, op, "no pending transaction")
return errors.NewDeprecated(errors.MigrationIntegrity, op, "no pending transaction")
}
if err := p.tx.Commit(); err != nil {
if errRollback := p.tx.Rollback(); errRollback != nil {
err = multierror.Append(err, errRollback)
}
return errors.Wrap(err, op)
return errors.WrapDeprecated(err, op)
}
return nil
}
@@ -207,7 +207,7 @@ func (p *Postgres) Run(ctx context.Context, migration io.Reader, version int) er
const op = "postgres.(Postgres).Run"
migr, err := ioutil.ReadAll(migration)
if err != nil {
return errors.Wrap(err, op)
return errors.Wrap(ctx, err, op)
}
// Run migration
query := string(migr)
@@ -225,7 +225,7 @@ func (p *Postgres) Run(ctx context.Context, migration io.Reader, version int) er
// set the version first, so logs will be associated with this new version.
// if there's an error, it will get rollback
if err := p.setVersion(ctx, version, false); err != nil {
return errors.Wrap(err, op)
return errors.Wrap(ctx, err, op)
}
if _, err := extr.ExecContext(ctx, query); err != nil {
@@ -249,9 +249,9 @@ func (p *Postgres) Run(ctx context.Context, migration io.Reader, version int) er
message = fmt.Sprintf("%s, %s", message, pgErr.Detail)
}
message = fmt.Sprintf("%s, on line %v: %s", message, line, migr)
return errors.Wrap(err, op, errors.WithMsg(message))
return errors.Wrap(ctx, err, op, errors.WithMsg(message))
}
return errors.Wrap(err, op, errors.WithMsg(fmt.Sprintf("migration failed: %s", migr)))
return errors.Wrap(ctx, err, op, errors.WithMsg(fmt.Sprintf("migration failed: %s", migr)))
}
return nil
@@ -314,7 +314,7 @@ func (p *Postgres) setVersion(ctx context.Context, version int, dirty bool) erro
if errRollback := rollback(); errRollback != nil {
err = multierror.Append(err, errRollback)
}
return errors.Wrap(err, op)
return errors.Wrap(ctx, err, op)
}
// Also re-write the schema Version for nil dirty versions to prevent
@@ -327,13 +327,13 @@ func (p *Postgres) setVersion(ctx context.Context, version int, dirty bool) erro
if errRollback := rollback(); errRollback != nil {
err = multierror.Append(err, errRollback)
}
return errors.Wrap(err, op)
return errors.Wrap(ctx, err, op)
}
}
if p.tx == nil {
if err := tx.Commit(); err != nil {
return errors.Wrap(err, op)
return errors.Wrap(ctx, err, op)
}
}
return nil
@@ -351,7 +351,7 @@ func (p *Postgres) CurrentState(ctx context.Context) (version int, previouslyRan
tableQuery := `select table_name from information_schema.tables where table_schema=(select current_schema()) and table_name in ('schema_migrations', '` + defaultMigrationsTable + `')`
tableResult, err := p.conn.QueryContext(ctx, tableQuery)
if err != nil {
return nilVersion, previouslyRan, dirty, errors.Wrap(err, op)
return nilVersion, previouslyRan, dirty, errors.Wrap(ctx, err, op)
}
defer tableResult.Close()
if !tableResult.Next() {
@@ -361,17 +361,17 @@ func (p *Postgres) CurrentState(ctx context.Context) (version int, previouslyRan
tableName := defaultMigrationsTable
if err := tableResult.Scan(&tableName); err != nil {
return nilVersion, previouslyRan, dirty, errors.Wrap(err, op)
return nilVersion, previouslyRan, dirty, errors.Wrap(ctx, err, op)
}
previouslyRan = true
if tableResult.Next() {
return nilVersion, previouslyRan, dirty, errors.New(errors.MigrationIntegrity, op, "both old and new migration tables exist")
return nilVersion, previouslyRan, dirty, errors.New(ctx, errors.MigrationIntegrity, op, "both old and new migration tables exist")
}
query := `select version, dirty from ` + pq.QuoteIdentifier(tableName)
results, err := p.conn.QueryContext(ctx, query)
if err != nil {
return nilVersion, previouslyRan, dirty, errors.Wrap(err, op)
return nilVersion, previouslyRan, dirty, errors.Wrap(ctx, err, op)
}
defer results.Close()
if !results.Next() {
@@ -379,10 +379,10 @@ func (p *Postgres) CurrentState(ctx context.Context) (version int, previouslyRan
return nilVersion, previouslyRan, dirty, nil
}
if err := results.Scan(&version, &dirty); err != nil {
return nilVersion, previouslyRan, dirty, errors.Wrap(err, op)
return nilVersion, previouslyRan, dirty, errors.Wrap(ctx, err, op)
}
if results.Next() {
return nilVersion, previouslyRan, dirty, errors.New(errors.MigrationIntegrity, op, "to many versions in version table")
return nilVersion, previouslyRan, dirty, errors.New(ctx, errors.MigrationIntegrity, op, "to many versions in version table")
}
return version, previouslyRan, dirty, nil
}
@@ -393,12 +393,12 @@ func (p *Postgres) drop(ctx context.Context) (err error) {
query := `select table_name from information_schema.tables where table_schema=(select current_schema()) and table_type='BASE TABLE'`
tables, err := p.conn.QueryContext(ctx, query)
if err != nil {
return errors.Wrap(err, op)
return errors.Wrap(ctx, err, op)
}
defer func() {
if errClose := tables.Close(); errClose != nil {
err = multierror.Append(err, errClose)
err = errors.Wrap(err, op)
err = errors.Wrap(ctx, err, op)
}
}()
@@ -407,14 +407,14 @@ func (p *Postgres) drop(ctx context.Context) (err error) {
for tables.Next() {
var tableName string
if err := tables.Scan(&tableName); err != nil {
return errors.Wrap(err, op)
return errors.Wrap(ctx, err, op)
}
if len(tableName) > 0 {
tableNames = append(tableNames, tableName)
}
}
if err := tables.Err(); err != nil {
return errors.Wrap(err, op)
return errors.Wrap(ctx, err, op)
}
if len(tableNames) > 0 {
@@ -422,7 +422,7 @@ func (p *Postgres) drop(ctx context.Context) (err error) {
for _, t := range tableNames {
query = `drop table if exists ` + pq.QuoteIdentifier(t) + ` cascade`
if _, err := p.conn.ExecContext(ctx, query); err != nil {
return errors.Wrap(err, op)
return errors.Wrap(ctx, err, op)
}
}
}
@@ -450,7 +450,7 @@ func (p *Postgres) EnsureVersionTable(ctx context.Context) (err error) {
if wpErr := rollback(); wpErr != nil {
err = multierror.Append(err, wpErr)
}
return errors.Wrap(err, op)
return errors.Wrap(ctx, err, op)
}
if exists {
return nil
@@ -461,7 +461,7 @@ func (p *Postgres) EnsureVersionTable(ctx context.Context) (err error) {
if wpErr := rollback(); wpErr != nil {
err = multierror.Append(err, wpErr)
}
return errors.Wrap(err, op)
return errors.Wrap(ctx, err, op)
}
createStmt := `create table if not exists ` + pq.QuoteIdentifier(defaultMigrationsTable) + ` (version bigint primary key, dirty boolean not null)`
@@ -469,7 +469,7 @@ func (p *Postgres) EnsureVersionTable(ctx context.Context) (err error) {
if wpErr := rollback(); wpErr != nil {
err = multierror.Append(err, wpErr)
}
return errors.Wrap(err, op)
return errors.Wrap(ctx, err, op)
}
return nil
+5 -5
View File
@@ -15,20 +15,20 @@ func MigrateStore(ctx context.Context, dialect string, url string, opt ...Option
d, err := sql.Open(dialect, url)
if err != nil {
return false, errors.Wrap(err, op)
return false, errors.Wrap(ctx, err, op)
}
sMan, err := NewManager(ctx, dialect, d, opt...)
if err != nil {
return false, errors.Wrap(err, op)
return false, errors.Wrap(ctx, err, op)
}
st, err := sMan.CurrentState(ctx)
if err != nil {
return false, errors.Wrap(err, op)
return false, errors.Wrap(ctx, err, op)
}
if st.Dirty {
return false, errors.New(errors.MigrationIntegrity, op, "db marked dirty")
return false, errors.New(ctx, errors.MigrationIntegrity, op, "db marked dirty")
}
if st.InitializationStarted && st.DatabaseSchemaVersion == st.BinarySchemaVersion {
@@ -36,7 +36,7 @@ func MigrateStore(ctx context.Context, dialect string, url string, opt ...Option
}
if err := sMan.RollForward(ctx); err != nil {
return false, errors.Wrap(err, op)
return false, errors.Wrap(ctx, err, op)
}
return true, nil