Skip to content

Commit

Permalink
Use db tag to customize ID field (#453)
Browse files Browse the repository at this point in the history
This will only work with Find method for now, but we can migrate other hard-coded IDs after.
  • Loading branch information
stanislas-m committed Nov 1, 2019
1 parent f8da582 commit 39043e3
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 2 deletions.
18 changes: 16 additions & 2 deletions model.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,20 @@ func (m *Model) ID() interface{} {
return fbn.Interface()
}

// IDField returns the name of the DB field used for the ID.
// By default, it will return "id".
func (m *Model) IDField() string {
field, ok := reflect.TypeOf(m.Value).Elem().FieldByName("ID")
if !ok {
return "id"
}
dbField := field.Tag.Get("db")
if dbField == "" {
return "id"
}
return dbField
}

// PrimaryKeyType gives the primary key type of the `Model`.
func (m *Model) PrimaryKeyType() string {
fbn, err := m.fieldByName("ID")
Expand Down Expand Up @@ -174,11 +188,11 @@ func (m *Model) touchUpdatedAt() {
}

func (m *Model) whereID() string {
return fmt.Sprintf("%s.id = ?", m.TableName())
return fmt.Sprintf("%s.%s = ?", m.TableName(), m.IDField())
}

func (m *Model) whereNamedID() string {
return fmt.Sprintf("%s.id = :id", m.TableName())
return fmt.Sprintf("%s.%s = :id", m.TableName(), m.IDField())
}

func (m *Model) isSlice() bool {
Expand Down
16 changes: 16 additions & 0 deletions model_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -130,3 +130,19 @@ func Test_Touch_Unix_Timestamp_With_Existing_Value(t *testing.T) {
r.Equal(createdAt, v.CreatedAt)
r.Equal(int(t0.Unix()), v.UpdatedAt)
}

func Test_IDField(t *testing.T) {
r := require.New(t)

type testCustomID struct {
ID int `db:"custom_id"`
}
m := Model{Value: &testCustomID{ID: 1}}
r.Equal("custom_id", m.IDField())

type testNormalID struct {
ID int
}
m = Model{Value: &testNormalID{ID: 1}}
r.Equal("id", m.IDField())
}

0 comments on commit 39043e3

Please sign in to comment.