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 }