Skip to content

Commit

Permalink
test: has-many with composite keys
Browse files Browse the repository at this point in the history
  • Loading branch information
kmpm committed Jul 29, 2022
1 parent e5d78d4 commit a757e78
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
29 changes: 29 additions & 0 deletions internal/dbtest/orm_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ func TestORM(t *testing.T) {
{testRelationExcludeAll},
{testM2MRelationExcludeColumn},
{testRelationBelongsToSelf},
{testCompositeHasMany},
}

testEachDB(t, func(t *testing.T, dbName string, db *bun.DB) {
Expand Down Expand Up @@ -429,6 +430,18 @@ func testM2MRelationExcludeColumn(t *testing.T, db *bun.DB) {
require.NoError(t, err)
}

func testCompositeHasMany(t *testing.T, db *bun.DB) {
department := new(Department)
err := db.NewSelect().
Model(department).
Where("company_no=? AND no=?", "company one", "hr").
Relation("Employees").
Scan(ctx)
require.NoError(t, err)
require.Equal(t, "hr", department.No)
require.Equal(t, 2, len(department.Employees))
}

type Genre struct {
ID int `bun:",pk"`
Name string
Expand Down Expand Up @@ -530,6 +543,20 @@ type Comment struct {
Text string
}

type Department struct {
bun.BaseModel `bun:"alias:d"`
CompanyNo string `bun:",pk"`
No string `bun:",pk"`
Employees []Employee `bun:"rel:has-many,join:company_no=company_no,join:no=department_no"`
}

type Employee struct {
bun.BaseModel `bun:"alias:p"`
CompanyNo string `bun:",pk"`
DepartmentNo string `bun:",pk"`
Name string `bun:",pk"`
}

func createTestSchema(t *testing.T, db *bun.DB) {
_ = db.Table(reflect.TypeOf((*BookGenre)(nil)).Elem())

Expand All @@ -541,6 +568,8 @@ func createTestSchema(t *testing.T, db *bun.DB) {
(*BookGenre)(nil),
(*Translation)(nil),
(*Comment)(nil),
(*Department)(nil),
(*Employee)(nil),
}
for _, model := range models {
_, err := db.NewDropTable().Model(model).IfExists().Exec(ctx)
Expand Down
22 changes: 22 additions & 0 deletions internal/dbtest/testdata/fixture.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -80,3 +80,25 @@
- trackable_id: 1000
trackable_type: translation
text: comment3

- model: Department
rows:
- company_no: company one
no: accounting
- company_no: company one
no: 'hr'

- model: Employee
rows:
- company_no: company one
department_no: accounting
name: 'adam'
- company_no: company one
department_no: accounting
name: 'bravo'
- company_no: company one
department_no: hr
name: 'charlie'
- company_no: company one
department_no: hr
name: 'foxtrot'

0 comments on commit a757e78

Please sign in to comment.