gas-stack/pkg/schema/parse.go
wispem-wantex 1b04b71d9d
All checks were successful
CI / release-test (push) Successful in 6s
Rename go.mod module name according to git path
2025-07-12 12:29:28 -07:00

65 lines
1.9 KiB
Go

package schema
import (
"strings"
"github.com/jinzhu/inflection"
"github.com/jmoiron/sqlx"
_ "github.com/mattn/go-sqlite3"
"git.offline-twitter.com/offline-labs/gas-stack/pkg/textutils"
)
// 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 temporary view tables as
select l.schema, l.name, l.type, l.ncol, l.wr, l.strict
from sqlite_schema s
left join pragma_table_list l on s.name = l.name
where s.type = 'table';
create temporary view columns as
select tables.name as table_name,
table_info.name as column_name,
lower(table_info.type) as column_type,
"notnull",
dflt_value is not null as has_default_value,
ifnull(dflt_value, 0) dflt_value,
pk as is_primary_key,
fk."table" is not null as is_foreign_key,
ifnull(fk."table", '') as fk_target_table,
ifnull(fk."to", '') as fk_target_column
from tables
join pragma_table_info(tables.name) as table_info
left join pragma_foreign_key_list(tables.name) as fk on fk."from" = column_name;
`)
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, strict 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
}