2016-06-23 08:09:56 +02:00
|
|
|
package bdb
|
|
|
|
|
2016-07-12 08:48:30 +02:00
|
|
|
import "fmt"
|
|
|
|
|
2016-06-23 08:09:56 +02:00
|
|
|
// Table metadata from the database schema.
|
|
|
|
type Table struct {
|
2016-09-08 23:23:10 +02:00
|
|
|
Name string
|
|
|
|
// For dbs with real schemas, like Postgres.
|
|
|
|
// Example value: "schema_name"."table_name"
|
|
|
|
SchemaName string
|
|
|
|
Columns []Column
|
2016-06-23 08:09:56 +02:00
|
|
|
|
|
|
|
PKey *PrimaryKey
|
2017-05-11 23:42:20 +02:00
|
|
|
UKeys []UniqueKey
|
2016-06-23 08:09:56 +02:00
|
|
|
FKeys []ForeignKey
|
|
|
|
|
|
|
|
IsJoinTable bool
|
2016-07-12 08:49:42 +02:00
|
|
|
|
2016-09-18 08:11:50 +02:00
|
|
|
ToOneRelationships []ToOneRelationship
|
2016-07-12 08:49:42 +02:00
|
|
|
ToManyRelationships []ToManyRelationship
|
2016-06-23 08:09:56 +02:00
|
|
|
}
|
2016-07-12 05:40:24 +02:00
|
|
|
|
2016-07-12 08:48:30 +02:00
|
|
|
// GetTable by name. Panics if not found (for use in templates mostly).
|
|
|
|
func GetTable(tables []Table, name string) (tbl Table) {
|
|
|
|
for _, t := range tables {
|
|
|
|
if t.Name == name {
|
|
|
|
return t
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
panic(fmt.Sprintf("could not find table name: %s", name))
|
|
|
|
}
|
|
|
|
|
|
|
|
// GetColumn by name. Panics if not found (for use in templates mostly).
|
2016-07-12 05:40:24 +02:00
|
|
|
func (t Table) GetColumn(name string) (col Column) {
|
|
|
|
for _, c := range t.Columns {
|
|
|
|
if c.Name == name {
|
|
|
|
return c
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-07-12 08:48:30 +02:00
|
|
|
panic(fmt.Sprintf("could not find column name: %s", name))
|
2016-07-12 05:40:24 +02:00
|
|
|
}
|
2016-09-25 00:58:37 +02:00
|
|
|
|
|
|
|
// CanLastInsertID checks the following:
|
|
|
|
// 1. Is there only one primary key?
|
|
|
|
// 2. Does the primary key column have a default value?
|
|
|
|
// 3. Is the primary key column type one of uintX/intX?
|
|
|
|
// If the above is all true, this table can use LastInsertId
|
|
|
|
func (t Table) CanLastInsertID() bool {
|
|
|
|
if t.PKey == nil || len(t.PKey.Columns) != 1 {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
col := t.GetColumn(t.PKey.Columns[0])
|
|
|
|
if len(col.Default) == 0 {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
switch col.Type {
|
|
|
|
case "int", "int8", "int16", "int32", "int64", "uint", "uint8", "uint16", "uint32", "uint64":
|
|
|
|
default:
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
return true
|
|
|
|
}
|