Files
dbx/exec.go
T
end f9befa1b0a refactor: split dbx package into domain files
Reorganize monolithic dbx.go and utility.go into focused files by
concern, add package doc.go, and gitignore coverage.out.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-29 17:46:54 -07:00

70 lines
1.8 KiB
Go

package dbx
import "errors"
// Insert executes an insert statement, returning the last inserted ID or an
// error if the insert fails.
func Insert(sqlo Executable, stmt Statement) (uint64, error) {
res, err := stmt.Exec(sqlo)
if err != nil {
return 0, err
}
id, err := res.LastInsertId()
if err != nil {
return 0, err
}
if id < 1 {
return 0, errors.New("inserted ID is less than 1")
}
return uint64(id), nil
}
// InsertReturning executes an insert statement that returns the inserted row.
// The statement MUST be a Jet InsertStatement with a RETURNING clause. Returns
// the inserted row object T or an error if the insert fails or no rows are returned.
func InsertReturning[T any](sqlo Queryable, stmt Statement) (*T, error) {
var result T
err := stmt.Query(sqlo, &result)
if err != nil {
return nil, err
}
return &result, nil
}
// Update executes an update statement, returning an error if the update fails.
func Update(sqlo Executable, stmt Statement) error {
_, err := stmt.Exec(sqlo)
return err
}
// UpdateAffected executes an update statement and returns the number of rows
// affected and an error if any.
func UpdateAffected(sqlo Executable, stmt Statement) (int64, error) {
res, err := stmt.Exec(sqlo)
if err != nil {
return 0, err
}
rowsAffected, err := res.RowsAffected()
if err != nil {
return 0, err
}
return rowsAffected, nil
}
// UpdateReturning executes an update statement that returns the updated row.
// The statement MUST be a Jet UpdateStatement with a RETURNING clause. Returns
// the updated row object T or an error if the update fails or no rows are returned.
func UpdateReturning[T any](sqlo Queryable, stmt Statement) (*T, error) {
var result T
err := stmt.Query(sqlo, &result)
if err != nil {
return nil, err
}
return &result, nil
}