diff --git a/cmd/model/db.go b/cmd/model/db.go index cc11f22..6fcade8 100644 --- a/cmd/model/db.go +++ b/cmd/model/db.go @@ -16,13 +16,14 @@ import ( "golang.org/x/term" ) -var TxMaxRetries = 3 +var TxMaxRetries = 5 type ( - DB struct{ *sql.DB } - Tx struct{ *sql.Tx } + DB struct{ *sql.DB } + Tx struct{ *sql.Tx } + Attribute struct { - Value interface{} + Value any Table string AttName string ID int64 @@ -70,9 +71,15 @@ func getCredentials() (string, string, error) { return user, pass, nil } +func wait(iteration int) { + waitTime := time.Duration(math.Pow(2, float64(iteration))) * 100 * time.Millisecond + jitter := time.Duration(rand.IntN(int(waitTime)/2)) * time.Millisecond + time.Sleep(waitTime + jitter) +} + func OpenDB(dbName string) (*DB, error) { var err error - db := DB{DB: &sql.DB{}} + db := DB{DB: new(sql.DB)} cfg := mysql.NewConfig() cfg.DBName = dbName @@ -108,7 +115,7 @@ func (db *DB) UpdateAttributes(a ...*Attribute) error { `, attribute.Table, attribute.AttName) if _, err := tx.Exec(query, attribute.Value, attribute.ID); err != nil { if rollbackErr := tx.Rollback(); rollbackErr != nil { - log.Fatalf("error: transaction error: %v, rollback error: %v", err, rollbackErr) + log.Fatalf("transaction error: %v, rollback error: %v", err, rollbackErr) } return fmt.Errorf("error updating %v in DB: %v", attribute.AttName, err) } @@ -124,9 +131,7 @@ func (db *DB) UpdateAttributes(a ...*Attribute) error { } log.Println(err) - waitTime := time.Duration(math.Pow(2, float64(i))) * time.Second - jitter := time.Duration(rand.IntN(1000)) * time.Millisecond - time.Sleep(waitTime + jitter) + wait(i) } return fmt.Errorf("error: %v unsuccessful retries for DB operation, aborting", TxMaxRetries) } @@ -143,31 +148,6 @@ func (db *DB) CountEntries(table string) (int64, error) { return count, nil } -func (db *DB) StartTransaction() (*Tx, error) { - tx := &Tx{Tx: new(sql.Tx)} - var err error - - tx.Tx, err = db.Begin() - if err != nil { - return nil, fmt.Errorf("error starting transaction: %v", err) - } - - return tx, nil -} - -func (tx *Tx) CommitTransaction() error { - if err := tx.Commit(); err != nil { - return fmt.Errorf("error committing transaction: %v", err) - } - return nil -} - -func (tx *Tx) RollbackTransaction() { - if err := tx.Rollback(); err != nil { - log.Fatalf("error rolling back transaction: %v", err) - } -} - func (tx *Tx) UpdateAttributes(a ...*Attribute) error { for _, attribute := range a { query := fmt.Sprintf(` @@ -177,7 +157,7 @@ func (tx *Tx) UpdateAttributes(a ...*Attribute) error { `, attribute.Table, attribute.AttName) if _, err := tx.Exec(query, attribute.Value, attribute.ID); err != nil { if rollbackErr := tx.Rollback(); rollbackErr != nil { - log.Fatalf("error: transaction error: %v, rollback error: %v", err, rollbackErr) + log.Fatalf("transaction error: %v, rollback error: %v", err, rollbackErr) } return fmt.Errorf("error updating %v in DB: %v", attribute.AttName, err) }