Files
gas-stack/pkg/schema/table.go

97 lines
2.4 KiB
Go

package schema
import (
"sort"
)
// 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
}
// HasSoftDelete reports whether this table supports soft-deletion, i.e., whether it has both
// an "is_deleted" and a "deleted_at" column.
func (t Table) HasSoftDelete() bool {
var hasIsDeleted, hasDeletedAt bool
for _, c := range t.Columns {
if c.Name == "is_deleted" && c.Type == "integer" {
hasIsDeleted = true
}
if c.Name == "deleted_at" && c.Type == "integer" {
hasDeletedAt = true
}
}
return hasIsDeleted && hasDeletedAt
}
// GetUpdateableColumns returns the columns that should be written to by an "update" operation.
func (t Table) GetUpdateableColumns() (ret []Column) {
hasCreatedAt, _ := t.HasAutoTimestamps()
for _, col := range t.Columns {
if col.Name == "rowid" || col.IsPrimaryKey {
continue // Rowid / primary key is never updateable
}
if col.Name == "created_at" && hasCreatedAt {
continue // Update shouldn't write `created_at`
}
if t.HasSoftDelete() && (col.Name == "is_deleted" || col.Name == "deleted_at") {
continue // Soft-delete state is managed by SoftDeleteXyz(), not by updates
}
ret = append(ret, col)
}
return
}