Cookies management by TermsFeed Cookie Consent

Implement Update method

Please consider supporting us by disabling your ad blocker

13/21

Our repository should also be able to update an existing row. This is what the Update() method is for. Copy it into the code of our repository.

Update() method

The Update() method updates the record with the specified id. It is not significantly different from other methods you have seen before.

First, we execute the SQL UPDATE query using the DB.ExecContext(), which updates the values of all columns of the websites table row. During the update, there may be a situation where the value of the updated field name already existed in the database, in which case a unique constraint violation error will occur. We handle such an error in the same way as in the Create() function.

Finally, we get the value of the RowsAffected() function from the returned sql.Result object to see how many rows were affected by our change. If 0, this indicates an error during the update, such as an invalid id was passed as an argument. We return this information to the user in the form of an ErrUpdateFailed error we defined earlier. If everything is fine, we return the updated Website object.

website/repository_postgresql_classic.go

// ...

func (r *PostgreSQLClassicRepository) Update(ctx context.Context, id int64, updated Website) (*Website, error) {
    res, err := r.db.ExecContext(ctx, "UPDATE websites SET name = $1, url = $2, rank = $3 WHERE id = $4", updated.Name, updated.URL, updated.Rank, id)
    if err != nil {
        var pgxError *pgconn.PgError
        if errors.As(err, &pgxError) {
            if pgxError.Code == "23505" {
                return nil, ErrDuplicate
            }
        }
        return nil, err
    }

    rowsAffected, err := res.RowsAffected()
    if err != nil {
        return nil, err
    }

    if rowsAffected == 0 {
        return nil, ErrUpdateFailed
    }

    return &updated, nil
}
13/21