gas-stack/pkg/schema/table.go
wispem-wantex 01e37a0e07
Some checks failed
CI / build-docker (push) Successful in 3s
CI / build-docker-bootstrap (push) Has been skipped
CI / release-test (push) Failing after 9s
TMP: codetables
2026-03-19 23:49:10 -07:00

77 lines
1.8 KiB
Go

package schema
import (
"fmt"
"slices"
"sort"
"git.offline-twitter.com/offline-labs/gas-stack/pkg/flowutils"
"github.com/jmoiron/sqlx"
)
// Table is a single SQLite table.
type Table struct {
TableName string `db:"name"`
// One of "table", "view", "shadow", or "virtual"
TableType string `db:"table_type"`
IsStrict bool `db:"is_strict"`
IsWithoutRowid bool `db:"is_without_rowid"`
Columns []Column
TypeIDName string
// Default variable name for variables of this type to use when generating Go code
VarName string
// Name of corresponding model type to be generated
GoTypeName string
}
// PrimaryKeyColumns returns the ordered list of columns in this table's primary key.
// This can be useful for "without rowid" tables with composite primary keys.
//
// TODO: needs test
func (t Table) PrimaryKeyColumns() []Column {
pks := make([]Column, 0)
for _, c := range t.Columns {
if c.IsPrimaryKey {
pks = append(pks, c)
}
}
sort.Slice(pks, func(i, j int) bool {
return pks[i].PrimaryKeyRank < pks[j].PrimaryKeyRank
})
return pks
}
func (t Table) GetColumnByName(name string) Column {
for _, c := range t.Columns {
if c.Name == name {
return c
}
}
panic("no such column: " + name)
}
func (t Table) HasAutoTimestamps() (hasCreatedAt bool, hasUpdatedAt bool) {
for _, c := range t.Columns {
if c.Name == "created_at" && c.Type == "integer" {
hasCreatedAt = true
}
if c.Name == "updated_at" && c.Type == "integer" {
hasUpdatedAt = true
}
}
return
}
func (t Table) GetCodeTableValues(db *sqlx.DB) (ret []string) {
if !slices.ContainsFunc(t.Columns, func(c Column) bool { return c.Name == "name" }) {
panic("not a code table")
}
flowutils.PanicIf(db.Select(&ret, fmt.Sprintf("select name from %s", t.TableName)))
return
}