Skip to content

Commit cb4983d

Browse files
committed
added db.TableForStruct
1 parent 2f2bd4d commit cb4983d

File tree

2 files changed

+108
-0
lines changed

2 files changed

+108
-0
lines changed

db/table.go

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package db
2+
3+
import (
4+
"fmt"
5+
"reflect"
6+
)
7+
8+
type Table struct{}
9+
10+
var typeOfTable = reflect.TypeFor[Table]()
11+
12+
func TableForStruct(t reflect.Type, tagKey string) (table string, err error) {
13+
if t.Kind() != reflect.Struct {
14+
return "", fmt.Errorf("db.StructTable: %s is not a struct", t)
15+
}
16+
if tagKey == "" {
17+
return "", fmt.Errorf("db.StructTable: tagKey is empty")
18+
}
19+
for i := 0; i < t.NumField(); i++ {
20+
field := t.Field(i)
21+
if field.Anonymous && field.Type == typeOfTable {
22+
table = field.Tag.Get(tagKey)
23+
if table == "" {
24+
return "", fmt.Errorf("db.StructTable: embedded db.Table has no tag '%s'", tagKey)
25+
}
26+
return table, nil
27+
}
28+
}
29+
return "", fmt.Errorf("db.StructTable: struct type %s has no embedded db.Table field", t)
30+
}

db/table_test.go

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
package db
2+
3+
import (
4+
"reflect"
5+
"testing"
6+
)
7+
8+
func TestTableForStruct(t *testing.T) {
9+
tests := []struct {
10+
name string
11+
t reflect.Type
12+
tagKey string
13+
wantTable string
14+
wantErr bool
15+
}{
16+
{
17+
name: "OK",
18+
t: reflect.TypeFor[struct {
19+
Table `db:"table_name"`
20+
}](),
21+
tagKey: "db",
22+
wantTable: "table_name",
23+
},
24+
{
25+
name: "more struct fields",
26+
t: reflect.TypeFor[struct {
27+
ID int `db:"id"`
28+
Table `db:"table_name"`
29+
Value string `db:"value"`
30+
}](),
31+
tagKey: "db",
32+
wantTable: "table_name",
33+
},
34+
// Error cases
35+
{
36+
name: "empty",
37+
t: reflect.TypeFor[struct{}](),
38+
tagKey: "db",
39+
wantErr: true,
40+
},
41+
{
42+
name: "no tagKey",
43+
t: reflect.TypeFor[struct {
44+
Table
45+
}](),
46+
tagKey: "db",
47+
wantErr: true,
48+
},
49+
{
50+
name: "wrong tagKey",
51+
t: reflect.TypeFor[struct {
52+
Table `json:"table_name"`
53+
}](),
54+
tagKey: "db",
55+
wantErr: true,
56+
},
57+
{
58+
name: "named field",
59+
t: reflect.TypeFor[struct {
60+
Table Table `db:"table_name"`
61+
}](),
62+
tagKey: "db",
63+
wantErr: true,
64+
},
65+
}
66+
for _, tt := range tests {
67+
t.Run(tt.name, func(t *testing.T) {
68+
gotTable, err := TableForStruct(tt.t, tt.tagKey)
69+
if (err != nil) != tt.wantErr {
70+
t.Errorf("TableForStruct(%s, %#v) error = %v, wantErr %v", tt.t, tt.tagKey, err, tt.wantErr)
71+
return
72+
}
73+
if gotTable != tt.wantTable {
74+
t.Errorf("TableForStruct(%s, %#v) = %v, want %v", tt.t, tt.tagKey, gotTable, tt.wantTable)
75+
}
76+
})
77+
}
78+
}

0 commit comments

Comments
 (0)