68 lines
2.0 KiB
Go
68 lines
2.0 KiB
Go
package schema
|
|
|
|
import (
|
|
"strings"
|
|
|
|
"git.offline-twitter.com/offline-labs/gas-stack/pkg/textutils"
|
|
)
|
|
|
|
// Column represents a single column in a table.
|
|
type Column struct {
|
|
// TableName is the name of the SQLite table this column belongs to.
|
|
TableName string `db:"table_name"`
|
|
|
|
// Name is the SQLite column name.
|
|
Name string `db:"column_name"`
|
|
|
|
// Type is the SQLite type this column contains.
|
|
Type string `db:"column_type"`
|
|
|
|
IsNotNull bool `db:"notnull"`
|
|
HasDefaultValue bool `db:"has_default_value"`
|
|
DefaultValue string `db:"dflt_value"`
|
|
IsPrimaryKey bool `db:"is_primary_key"`
|
|
PrimaryKeyRank uint `db:"primary_key_rank"`
|
|
IsForeignKey bool `db:"is_foreign_key"`
|
|
ForeignKeyTargetTable string `db:"fk_target_table"`
|
|
ForeignKeyTargetColumn string `db:"fk_target_column"`
|
|
}
|
|
|
|
// IsNullableForeignKey is a helper function.
|
|
func (c Column) IsNullableForeignKey() bool {
|
|
return !c.IsNotNull && !c.IsPrimaryKey && c.IsForeignKey
|
|
}
|
|
|
|
func (c Column) IsNonCodeTableForeignKey() bool {
|
|
return c.IsForeignKey && strings.HasSuffix(c.Name, "_id")
|
|
}
|
|
|
|
func (c Column) GoFieldName() string {
|
|
if c.Name == "rowid" {
|
|
return "ID"
|
|
}
|
|
if c.IsNonCodeTableForeignKey() {
|
|
return textutils.SnakeToCamel(strings.TrimSuffix(c.Name, "_id")) + "ID"
|
|
}
|
|
return textutils.SnakeToCamel(c.Name)
|
|
}
|
|
|
|
// GoVarName returns the name of a local variable for this column, e.g., when used as a function parameter.
|
|
func (c Column) GoVarName() string {
|
|
if c.Name == "rowid" {
|
|
return strings.ToLower(c.TableName)[0:1] + "ID"
|
|
// TODO: Or should it just be "id"??
|
|
}
|
|
// For foreign keys, use first letter of the target type and "ID". "UserID" => "uID"
|
|
if c.IsNonCodeTableForeignKey() {
|
|
return strings.ToLower(c.ForeignKeyTargetTable)[0:1] + "ID"
|
|
}
|
|
|
|
// Otherwise, just use the whole name
|
|
return c.LongGoVarName()
|
|
}
|
|
|
|
// LongGoVarName returns a lowercased version of the field name (Pascal => Camel).
|
|
func (c Column) LongGoVarName() string {
|
|
return textutils.CamelToPascal(c.GoFieldName())
|
|
}
|