gas-stack/pkg/schema/parse.go
wispem-wantex 14d395f0ea
All checks were successful
CI / release-test (push) Successful in 2m33s
Tidy up the Table SQL interface a bit
2025-08-23 15:53:23 -07:00

48 lines
1.1 KiB
Go

package schema
import (
_ "embed"
"strings"
"github.com/jinzhu/inflection"
"github.com/jmoiron/sqlx"
_ "github.com/mattn/go-sqlite3"
"git.offline-twitter.com/offline-labs/gas-stack/pkg/textutils"
)
//go:embed views.sql
var create_views string
// InitDB creates an in-memory DB from a given schema string.
func InitDB(sql_schema string) *sqlx.DB {
db := sqlx.MustOpen("sqlite3", ":memory:")
db.MustExec(sql_schema)
db.MustExec(create_views)
return db
}
// SchemaFromDB takes a DB connection, checks its schema metadata tables, and returns a Schema.
func SchemaFromDB(db *sqlx.DB) Schema {
ret := Schema{}
var tables []Table
err := db.Select(&tables, `select name, is_strict, is_without_rowid from tables`)
if err != nil {
panic(err)
}
for _, tbl := range tables {
tbl.TypeName = textutils.SnakeToCamel(inflection.Singular(tbl.TableName))
tbl.TypeIDName = tbl.TypeName + "ID"
tbl.VarName = strings.ToLower(string(tbl.TableName[0]))
err := db.Select(&tbl.Columns, `select * from columns where table_name = ?`, tbl.TableName)
if err != nil {
panic(err)
}
ret[tbl.TableName] = tbl
}
return ret
}