Cookies management by TermsFeed Cookie Consent

Implement Delete method

Please consider supporting us by disabling your ad blocker

14/21

The last letter in the CRUD abbreviation, D, stands for Delete() function. Add its code to the repository.

Delete() method

The Delete(), as the name suggests, deletes a record with the given id from the database. As in the Update() method, to execute the SQL DELETE command, we use the DB.ExecContext() function and also check whether the number of affected rows is equal to 0. If so, it means a delete error, which we return as a previously defined ErrDeleteFailed error.


This way, we have finished creating our first repository based on the classic database/sql package. In the next step, we will make a test procedure and an application to check in practice what we have written.

website/repository_postgresql_classic.go

// ...

func (r *PostgreSQLClassicRepository) Delete(ctx context.Context, id int64) error {
    res, err := r.db.ExecContext(ctx, "DELETE FROM websites WHERE id = $1", id)
    if err != nil {
        return err
    }

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

    if rowsAffected == 0 {
        return ErrDeleteFailed
    }

    return err
}
14/21