package exec import ( "database/sql" "errors" "reflect" "git.gdulai.com/gdulai/simpleorm" "git.gdulai.com/gdulai/simpleorm/schema" log "gitlab.com/gdulai/simpleloglvl" ) // Delete represents a delete operation. type Delete[T any] struct { target schema.Table // The table from which records will be deleted. toDelete []T // A slice of model instances to be deleted. } // NewDelete creates a new instance of Delete. // // Parameters: // - orm: The ORM instance that manages the database connection and schema // - toDelete: A slice of model instances to delete // // Returns: // - Delete[T]: A new Delete operation instance // - error: An error if the table could not be found in the schema cache func NewDelete[T any](orm *simpleorm.ORM, toDelete []T) (Delete[T], error) { table, ok := orm.Cache().Get(reflect.TypeFor[T]().Name()) if !ok { return Delete[T]{}, errors.New("Failed to get table from schema cache") } return Delete[T]{target: *table, toDelete: toDelete}, nil } // Execute executes the delete operation. func (d *Delete[T]) Execute(conn *simpleorm.DBConnection) error { return d.execute(conn, nil) } // execute constructs and executes the DELETE 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 (d *Delete[T]) execute(conn *simpleorm.DBConnection, tx *sql.Tx) error { count := len(d.toDelete) dml, err := d.target.GetDeleteDML(count) if err != nil { return err } var params []any for _, del := range d.toDelete { pkCols, err := getPk(del, d.target) if err != nil { return err } 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("Deleted %s row", rowsAffected) } return nil }