Files
simpleorm/orm.go
T
gdulai ffd9cd004e
Go Tests / test (push) Failing after 6s
Introduce Exec interface and implementers (#1)
Reviewed-on: #1
2026-05-11 06:03:40 +00:00

72 lines
1.8 KiB
Go

// Package simpleorm provies a simple, basic ORM functionalities for making
// interaction with relational databses easier.
package simpleorm
import (
"reflect"
"strings"
"git.gdulai.com/gdulai/simpleorm/cache"
"git.gdulai.com/gdulai/simpleorm/parser"
"git.gdulai.com/gdulai/simpleorm/schema"
log "gitlab.com/gdulai/simpleloglvl"
)
// Type to access the ORM functionalities in a structured manner-
type ORM struct {
cache *cache.SchemaCache
}
// Inits the ORM library.
// Param objs is an array which should be an array of the types which describe the tables.
func NewORM(objs ...any) *ORM {
var parsers []*parser.Parser
var tables []*schema.Table
for _, obj := range objs {
log.LogDebug("[ORM] Mapping type for: %s", reflect.TypeOf(obj).Name())
parser := parser.NewParser(obj)
parsers = append(parsers, parser)
tables = append(tables, parser.ParseColumns())
}
log.LogDebug("[ORM] Tables initiated, creating cache.")
// Create cache with the initialized tables
cache := cache.NewSchemaCache(tables)
log.LogDebug("[ORM] Cache created.")
// Finish the parsing with the constraints and add the to the tables
for _, parser := range parsers {
log.LogDebug("[ORM] Parsing constraing for: %s", parser.Table.Name)
parser.ParseConstraints(cache)
log.LogDebug("[ORM] Parsed constraints for: %s", parser.Table.Name)
}
return &ORM{cache: cache}
}
// Builds the DDL and returns it as a string
func (orm *ORM) CreateSchema() (string, error) {
var ddl strings.Builder
tables := orm.cache.GetAll()
for i, table := range tables {
if i != 0 {
ddl.WriteString("\n")
}
tableDdl, err := table.GetDDL()
if err != nil {
return "", err
}
ddl.WriteString(tableDdl)
}
return ddl.String(), nil
}
func (orm *ORM) Cache() *cache.SchemaCache {
return orm.cache
}