Files
simpleorm/exec/exec.go
T
gdulai 5c56241cf6
Go Tests / test (push) Successful in 1m2s
Separate exec types into files, document code (#10)
Reviewed-on: #10
2026-07-28 20:16:23 +00:00

249 lines
5.4 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"
)
// Created and executes the DDL created by [simpleorm.ORM]
func ExecuteDDL(conn *simpleorm.DBConnection, orm *simpleorm.ORM) {
schema, err := orm.CreateSchema()
if err != nil {
log.LogError("Failed to run DDL: %s", schema)
return
}
log.LogInfo("Executing DDL:\n%s", schema)
if _, err := conn.Exec(schema); err != nil {
log.LogFatalError("%", err)
}
}
// Wraps and represents a DB transaction.
// Allows for all at once or separate execution of [exec.Exec] implementations.
type Transaction struct {
conn *simpleorm.DBConnection
executions []*Exec[any]
tx *sql.Tx
finished bool
}
// Creates a new [exec.Transaction].
// Can be initialized with a set of [exec.Exec]s.
func NewTransaction(conn *simpleorm.DBConnection, executions ...*Exec[any]) *Transaction {
return &Transaction{conn: conn, executions: executions, finished: false}
}
// The executions assigned to this transaction.
func (t *Transaction) Executions() []*Exec[any] {
return t.executions
}
// Executes all the [exec.Exec] implementations assigned to this transactions.
// Begins, commits or rollbacks the transaction.
// This is a terminal operation, the [exec.Transaction] is considered finished after calling this.
func (t *Transaction) ExecuteAtOnce() error {
if t.finished {
return errors.New("Transaction already finished.")
}
if t.tx == nil {
tx, err := t.conn.Begin()
t.tx = tx
if err != nil {
t.finished = true
return err
}
}
for _, exec := range t.executions {
err := (*exec).execute(nil, t.tx)
if err != nil {
rollbackErr := t.Rollback()
if rollbackErr != nil {
return rollbackErr
}
return err
}
}
err := t.tx.Commit()
if err != nil {
return err
}
t.finished = true
return nil
}
// Executes and assigns the passed [exec.Exec]s to the Transaction.
// Calls rollback in case of an error.
// This is NOT a terminal operation, transactions still has to be committed.
func (t *Transaction) Execute(execs ...Exec[any]) error {
if t.finished {
return errors.New("Transaction already finished.")
}
for _, exec := range execs {
execPtr := &exec
t.executions = append(t.executions, execPtr)
if t.tx == nil {
tx, err := t.conn.Begin()
t.tx = tx
if err != nil {
t.finished = true
return err
}
}
err := (*execPtr).execute(nil, t.tx)
if err != nil {
rollbackErr := t.Rollback()
if rollbackErr != nil {
return rollbackErr
}
return err
}
}
return nil
}
// Finishes the transaction, commits the changes.
// This is terminal operation.
func (t *Transaction) Finish() error {
if t.finished {
return errors.New("Transaction already finished.")
}
if t.tx == nil {
return errors.New("Transaction is nil.")
}
t.tx.Commit()
t.finished = true
return nil
}
// Rollbacks and aborts the transaction.
// This is a terminal operation.
func (t *Transaction) Rollback() error {
if t.finished {
return errors.New("Transaction already finished.")
}
if t.tx == nil {
return errors.New("Transaction is nil.")
}
rollbackErr := t.tx.Rollback()
if rollbackErr != nil {
return rollbackErr
}
t.finished = true
return nil
}
type Exec[T any] interface {
Execute(conn *simpleorm.DBConnection) error
execute(conn *simpleorm.DBConnection, tx *sql.Tx) error
}
func createSelectResultContainer(t schema.Table) []any {
typ := t.Type()
vals := make([]any, typ.NumField())
for i := range vals {
switch typ.Field(i).Type.Kind().String() {
case "string":
var fieldContainer string
vals[i] = &fieldContainer
case "int", "bool":
var fieldContainer int
vals[i] = &fieldContainer
case "int64", "time.Time":
var fieldContainer int64
vals[i] = &fieldContainer
}
}
return vals
}
func prepareParams(src any, t schema.Table) []any {
typ := t.Type()
var params []any
for _, col := range t.Columns() {
_, ok := col.Modifiers["pk"]
if ok && t.IsPkAuto() {
continue
}
field, ok := typ.FieldByName(col.FieldName)
if !ok {
continue
}
fieldValue := reflect.ValueOf(src).FieldByIndex(field.Index)
params = append(params, col.Encode(fieldValue))
}
return params
}
func getPk(src any, t schema.Table) ([]any, error) {
typ := t.Type()
var values []any
for _, constraint := range t.Constraints() {
if constraint.Type == "pk" {
for _, col := range constraint.Columns {
field, ok := typ.FieldByName(col.FieldName)
if !ok {
continue
}
fieldValue := reflect.ValueOf(src).FieldByIndex(field.Index)
values = append(values, fieldValue.Interface())
}
}
}
if len(values) == 0 {
return nil, errors.New("Could not determine pk column!")
}
return values, nil
}
func readRows[T any](table schema.Table, rows *sql.Rows) ([]T, error) {
rowContainer := createSelectResultContainer(table)
var results []T
for rows.Next() {
err := rows.Scan(rowContainer...)
if err != nil {
return nil, err
}
targetType := table.Type()
cols := table.Columns()
parsedResult := reflect.New(targetType)
for i, fieldVal := range rowContainer {
col := cols[i]
targetField := parsedResult.Elem().Field(i)
rawValue := reflect.Indirect(reflect.ValueOf(fieldVal))
decoded := reflect.ValueOf(col.Decode(targetField.Type().Name(), rawValue))
targetField.Set(decoded)
}
parsedObj := reflect.Indirect(parsedResult).Interface().(T)
results = append(results, parsedObj)
}
return results, nil
}