82 lines
1.6 KiB
Go
82 lines
1.6 KiB
Go
package orm
|
|
|
|
import (
|
|
"context"
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
"time"
|
|
)
|
|
|
|
type Engine struct {
|
|
modelMap *ModelMap
|
|
conn *pgxpool.Pool
|
|
m2mSeen map[string]bool
|
|
dryRun bool
|
|
cfg *pgxpool.Config
|
|
ctx context.Context
|
|
}
|
|
|
|
func (e *Engine) Models(v ...any) {
|
|
e.modelMap = makeModelMap(v...)
|
|
}
|
|
|
|
func (e *Engine) Model(val any) *Query {
|
|
qq := &Query{
|
|
engine: e,
|
|
ctx: context.Background(),
|
|
wheres: make(map[string][]any),
|
|
joins: make(map[*Relationship][3]string),
|
|
orders: make([]string, 0),
|
|
relatedModels: make(map[string]*Model),
|
|
}
|
|
return qq.Model(val)
|
|
}
|
|
|
|
func (e *Engine) Migrate() error {
|
|
failedMigrations := make(map[string]*Model)
|
|
var err error
|
|
for mk, m := range e.modelMap.Map {
|
|
err = m.migrate(e)
|
|
if err != nil {
|
|
failedMigrations[mk] = m
|
|
}
|
|
}
|
|
|
|
for len(failedMigrations) > 0 {
|
|
e.m2mSeen = make(map[string]bool)
|
|
for mk, m := range failedMigrations {
|
|
err = m.migrate(e)
|
|
if err == nil {
|
|
delete(failedMigrations, mk)
|
|
}
|
|
}
|
|
}
|
|
return err
|
|
}
|
|
|
|
func Open(connString string) (*Engine, error) {
|
|
e := &Engine{
|
|
modelMap: &ModelMap{
|
|
Map: make(map[string]*Model),
|
|
},
|
|
m2mSeen: make(map[string]bool),
|
|
dryRun: connString == "",
|
|
ctx: context.Background(),
|
|
}
|
|
if connString != "" {
|
|
var err error
|
|
e.cfg, err = pgxpool.ParseConfig(connString)
|
|
e.cfg.MinConns = 5
|
|
e.cfg.MaxConns = 10
|
|
e.cfg.MaxConnIdleTime = time.Minute * 2
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
e.conn, err = pgxpool.NewWithConfig(e.ctx, e.cfg)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
}
|
|
return e, nil
|
|
}
|