Create comprehensive documentation for future Claude Code instances working in this repository, including: - Development commands for testing, building, and code quality - Core architecture overview of the SQL query builder system - Directory structure and component explanations - Testing patterns and conventions - Key dependencies and their purposes 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com>
119 lines
2.1 KiB
Go
119 lines
2.1 KiB
Go
package engine
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"fmt"
|
|
|
|
"github.com/lib/pq"
|
|
|
|
_ "github.com/denisenkom/go-mssqldb"
|
|
_ "github.com/go-sql-driver/mysql"
|
|
"github.com/mattn/go-sqlite3"
|
|
_ "github.com/mattn/go-sqlite3"
|
|
|
|
_ "git.fsdpf.net/go/db/dialect/mysql"
|
|
_ "git.fsdpf.net/go/db/dialect/postgres"
|
|
_ "git.fsdpf.net/go/db/dialect/sqlite3"
|
|
_ "git.fsdpf.net/go/db/dialect/sqlserver"
|
|
|
|
"git.fsdpf.net/go/db"
|
|
"git.fsdpf.net/go/db/internal/errors"
|
|
)
|
|
|
|
type Engine struct {
|
|
configs map[string]DBConfig
|
|
dbs map[string]*sql.DB
|
|
}
|
|
|
|
var _engine *Engine
|
|
|
|
func init() {
|
|
_engine = &Engine{
|
|
configs: make(map[string]DBConfig),
|
|
dbs: make(map[string]*sql.DB),
|
|
}
|
|
}
|
|
|
|
func (e Engine) Connection(name string) *db.Database {
|
|
cfg, ok := e.configs[name]
|
|
|
|
if !ok {
|
|
panic(errors.New(fmt.Sprintf("Database connection %s not configured.", name)))
|
|
}
|
|
|
|
_db, ok := e.dbs[name]
|
|
|
|
if !ok {
|
|
_db = e.MakeConnection(cfg)
|
|
e.dbs[name] = _db
|
|
}
|
|
|
|
return db.New(cfg.Driver, _db)
|
|
}
|
|
|
|
func (e Engine) MakeConnection(cfg DBConfig) (db *sql.DB) {
|
|
dsn := cfg.ToDSN()
|
|
|
|
switch cfg.Driver {
|
|
case "mysql":
|
|
case "sqlite3":
|
|
defer func() {
|
|
if r := recover(); r != nil {
|
|
panic(r)
|
|
}
|
|
if cfg.SQLite.Raw == nil {
|
|
return
|
|
}
|
|
conn, err := db.Conn(context.Background())
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
err = conn.Raw(func(driverConn any) error {
|
|
sqliteConn := driverConn.(*sqlite3.SQLiteConn)
|
|
return cfg.SQLite.Raw(sqliteConn)
|
|
})
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
}()
|
|
case "sqlserver":
|
|
case "postgres":
|
|
if url, err := pq.ParseURL(dsn); err == nil {
|
|
dsn = url
|
|
} else {
|
|
panic(err)
|
|
}
|
|
default:
|
|
panic(fmt.Sprintf("Unsupported driver: %s", cfg.Driver))
|
|
}
|
|
|
|
db, err := sql.Open(cfg.Driver, dsn)
|
|
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
if err := db.Ping(); err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
return db
|
|
}
|
|
|
|
func Open(cfgs map[string]DBConfig) Engine {
|
|
for n, cfg := range cfgs {
|
|
_engine.configs[n] = cfg
|
|
}
|
|
|
|
return *_engine
|
|
}
|
|
|
|
func Mock(cfgs map[string]MockDBConfig) Engine {
|
|
for k, cfg := range cfgs {
|
|
_engine.dbs[k] = cfg.Mock
|
|
_engine.configs[k] = DBConfig{Driver: cfg.Driver}
|
|
}
|
|
return *_engine
|
|
}
|