83 lines
1.9 KiB
Go
83 lines
1.9 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/schema"
|
|
|
|
log "gitlab.com/gdulai/simpleloglvl"
|
|
)
|
|
|
|
// Type to access the ORM functionalities in a structured manner-
|
|
type ORM struct {
|
|
cache *cache.SchemaCache
|
|
}
|
|
|
|
// NewOrm inits and creates an instance ORM library.
|
|
//
|
|
// obj is an array which should be an array of the types which describe the tables.
|
|
func NewORM(objs ...any) *ORM {
|
|
typeParsers := make(map[string]*schema.Parser)
|
|
|
|
log.LogDebug("[ORM] Parsing entities to tables...")
|
|
log.LogDebug("[ORM] Step 1: Parsing table columns")
|
|
for _, obj := range objs {
|
|
typ := reflect.TypeOf(obj)
|
|
log.LogDebug("[ORM] Mapping type for: %s", typ.Name())
|
|
|
|
parser := schema.NewParser(obj)
|
|
parser.ParseColumns()
|
|
|
|
typeParsers[typ.Name()] = parser
|
|
}
|
|
|
|
log.LogDebug("[ORM] Step 1: Finished parsing columns!")
|
|
log.LogDebug("[ORM] Step 2: Parsing constraints...")
|
|
|
|
for _, parser := range typeParsers {
|
|
parser.ParseConstraints(typeParsers)
|
|
}
|
|
|
|
log.LogDebug("[ORM] Step 2: Finished parsing contraints!")
|
|
log.LogDebug("[ORM] Step 3: Creating and caching schema...")
|
|
|
|
var tables []*schema.Table
|
|
for _, parser := range typeParsers {
|
|
tables = append(tables, parser.ParseTable())
|
|
}
|
|
|
|
// Create cache with the initialized tables
|
|
cache := cache.NewSchemaCache(tables)
|
|
|
|
log.LogDebug("[ORM] Step 3: Cache created.")
|
|
|
|
return &ORM{cache: cache}
|
|
}
|
|
|
|
// CreateSchmea 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
|
|
}
|