|
|
@ -6,6 +6,7 @@ import (
|
|
|
|
"time"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
|
|
|
|
"github.com/jackc/pgx/v5"
|
|
|
|
"github.com/jackc/pgx/v5"
|
|
|
|
|
|
|
|
"github.com/jackc/pgx/v5/pgconn"
|
|
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
|
|
)
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
@ -98,7 +99,18 @@ func (m MovieModel) Update(ctx context.Context, movie *Movie) error {
|
|
|
|
return m.pool.QueryRow(ctx, query, args...).Scan(&movie.Version)
|
|
|
|
return m.pool.QueryRow(ctx, query, args...).Scan(&movie.Version)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
func (m MovieModel) Delete(ctx context.Context, id int64) error {
|
|
|
|
// Here I decided to attempt an idiomatic version of the Delete service with
|
|
|
|
|
|
|
|
// a database transaction. Since this is updating just one entry in a single table
|
|
|
|
|
|
|
|
// an explicit db transaction isn't really necessary but I thought I'd practice it
|
|
|
|
|
|
|
|
// none the less. If using sqlc you'd probably not even worry about implementing
|
|
|
|
|
|
|
|
// it this way, but I am here to learn so.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
func (m MovieModel) Delete(ctx context.Context, id int64) (err error) {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
if id < 1 {
|
|
|
|
|
|
|
|
return ErrRecordNotFound
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
query := `DELETE FROM movies WHERE id = $1`
|
|
|
|
query := `DELETE FROM movies WHERE id = $1`
|
|
|
|
|
|
|
|
|
|
|
|
tx, err := m.pool.BeginTx(ctx, pgx.TxOptions{})
|
|
|
|
tx, err := m.pool.BeginTx(ctx, pgx.TxOptions{})
|
|
|
@ -106,9 +118,24 @@ func (m MovieModel) Delete(ctx context.Context, id int64) error {
|
|
|
|
return err
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
defer func() {
|
|
|
|
defer func() {
|
|
|
|
tx.Rollback(ctx)
|
|
|
|
// If it's in error or the context was canceled, rollback
|
|
|
|
|
|
|
|
if err != nil || ctx.Err() != nil {
|
|
|
|
|
|
|
|
_ = tx.Rollback(ctx)
|
|
|
|
|
|
|
|
return
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
// if the commit fails raises the error.
|
|
|
|
|
|
|
|
err = tx.Commit(ctx)
|
|
|
|
}()
|
|
|
|
}()
|
|
|
|
_, err = tx.Exec(ctx, query, id)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
return err
|
|
|
|
var cmd pgconn.CommandTag
|
|
|
|
|
|
|
|
cmd, err = tx.Exec(ctx, query, id)
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
|
|
|
return err
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
if cmd.RowsAffected() == 0 {
|
|
|
|
|
|
|
|
return ErrRecordNotFound
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|