Add function to check LastInsertId-ability

- Previously we used a lot of template magic to see if we could
  use LastInsertId. But there's a much simpler check that's worth doing,
  do this at the table level and then let it fall through.
This commit is contained in:
Aaron L 2016-09-24 15:58:37 -07:00
parent 5f394a4f69
commit 5eb14f262a
2 changed files with 77 additions and 0 deletions

View file

@ -40,3 +40,27 @@ func (t Table) GetColumn(name string) (col Column) {
panic(fmt.Sprintf("could not find column name: %s", name))
}
// 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
}

View file

@ -65,3 +65,56 @@ func TestGetColumnMissing(t *testing.T) {
table.GetColumn("missing")
}
func TestCanLastInsertID(t *testing.T) {
t.Parallel()
tests := []struct {
Can bool
PKeys []Column
}{
{true, []Column{
{Name: "id", Type: "int64", Default: "a"},
}},
{true, []Column{
{Name: "id", Type: "uint64", Default: "a"},
}},
{true, []Column{
{Name: "id", Type: "int", Default: "a"},
}},
{true, []Column{
{Name: "id", Type: "uint", Default: "a"},
}},
{true, []Column{
{Name: "id", Type: "uint", Default: "a"},
}},
{false, []Column{
{Name: "id", Type: "uint", Default: "a"},
{Name: "id2", Type: "uint", Default: "a"},
}},
{false, []Column{
{Name: "id", Type: "string", Default: "a"},
}},
{false, []Column{
{Name: "id", Type: "int", Default: ""},
}},
{false, nil},
}
for i, test := range tests {
table := Table{
Columns: test.PKeys,
PKey: &PrimaryKey{},
}
var pkeyNames []string
for _, pk := range test.PKeys {
pkeyNames = append(pkeyNames, pk.Name)
}
table.PKey.Columns = pkeyNames
if got := table.CanLastInsertID(); got != test.Can {
t.Errorf("%d) wrong: %t", i, got)
}
}
}