Files
simpleorm/exec/update.go
T
gdulai 120761ecfd
Go Tests / test (pull_request) Has been cancelled
Documentation
2026-07-28 22:15:29 +02:00

86 lines
2.1 KiB
Go

package exec
import (
"database/sql"
"errors"
"reflect"
"git.gdulai.com/gdulai/simpleorm"
"git.gdulai.com/gdulai/simpleorm/schema"
log "gitlab.com/gdulai/simpleloglvl"
)
// Update represents an update operation.
type Update[T any] struct {
target schema.Table // The table where records will be updated.
toUpdate T // A model instance with the new values.
}
// NewUpdate creates a new instance of Update.
//
// Parameters:
// - orm: The ORM instance that manages the database connection and schema
// - toUpdate: A model instance with new values
//
// Returns:
// - Update[T]: A new Update operation instance
// - error: An error if the table could not be found in the schema cache
func NewUpdate[T any](orm *simpleorm.ORM, toUpdate T) (Update[T], error) {
table, ok := orm.Cache().Get(reflect.TypeFor[T]().Name())
if !ok {
return Update[T]{}, errors.New("Failed to get table from schema cache")
}
return Update[T]{target: *table, toUpdate: toUpdate}, nil
}
// Execute executes the update operation.
func (u Update[T]) Execute(conn *simpleorm.DBConnection) error {
return u.execute(conn, nil)
}
// execute constructs and executes the UPDATE SQL statement.
//
// Parameters:
// - conn: The database connection to use for executing the query
// - tx: Optional transaction to use instead of a connection
//
// Returns:
// - error: An error if the operation fails
func (u Update[T]) execute(conn *simpleorm.DBConnection, tx *sql.Tx) error {
dml, err := u.target.GetUpdateDML()
if err != nil {
return err
}
params := prepareParams(u.toUpdate, u.target)
pkCols, err := getPk(u.toUpdate, u.target)
if err != nil {
return err
}
// Put the pks back at the end
for _, pk := range pkCols {
params = append(params, pk)
}
log.LogDebug("%s [%s]", dml, params)
var stmt *sql.Stmt
if tx != nil {
stmt, err = tx.Prepare(dml)
} else {
stmt, err = conn.Prepare(dml)
}
defer stmt.Close()
result, err := stmt.Exec(params...)
if err != nil {
return err
} else {
rowsAffected, _ := result.RowsAffected()
log.LogInfo("Updated %s row", rowsAffected)
}
return nil
}