From 97cb352de65cf165045c8b2cf685584128b932eb Mon Sep 17 00:00:00 2001 From: alingse Date: Mon, 10 Apr 2023 21:30:17 +0800 Subject: [PATCH] add more test for JSONType fix select field fix test --- json_type_test.go | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/json_type_test.go b/json_type_test.go index 53bea48..fd7e5ac 100644 --- a/json_type_test.go +++ b/json_type_test.go @@ -72,6 +72,20 @@ func TestJSONType(t *testing.T) { AssertEqual(t, result.Attributes.Data().Admin, users[1].Attributes.Data().Admin) AssertEqual(t, len(result.Attributes.Data().Orgs), len(users[1].Attributes.Data().Orgs)) + // List + var users2 []UserWithJSON + if err := DB.Model(&UserWithJSON{}).Limit(10).Order("id asc").Find(&users2).Error; err != nil { + t.Fatalf("failed to select attribute field, got error %v", err) + } + AssertEqual(t, users2[0].Attributes.Data().Age, 18) + + // Select Field + var singleUser UserWithJSON + if err := DB.Model(&UserWithJSON{}).Select("attributes").Limit(1).Order("id asc").Find(&singleUser).Error; err != nil { + t.Fatalf("failed to select attribute field, got error %v", err) + } + AssertEqual(t, singleUser.Attributes.Data().Age, 18) + // Pluck var attr datatypes.JSONType[Attribute] if err := DB.Model(&UserWithJSON{}).Limit(1).Order("id asc").Pluck("attributes", &attr).Error; err != nil { @@ -80,6 +94,15 @@ func TestJSONType(t *testing.T) { var attribute = attr.Data() AssertEqual(t, attribute.Age, 18) + // Smart Select Fields + var row struct { + Attributes datatypes.JSONType[Attribute] + } + if err := DB.Model(&UserWithJSON{}).Limit(1).Order("id asc").Find(&row).Error; err != nil { + t.Fatalf("failed to select attribute field, got error %v", err) + } + AssertEqual(t, row.Attributes.Data().Age, 18) + // FirstOrCreate jsonMap := UserWithJSON{ Attributes: newJSONType[Attribute]([]byte(`{"age":19,"name":"json-1","orgs":{"orga":"orga"},"tags":["tag1","tag2"]}`)), @@ -154,6 +177,24 @@ func TestJSONSlice(t *testing.T) { AssertEqual(t, result.Name, users[0].Name) AssertEqual(t, result.Tags[0], users[0].Tags[0]) + // Pluck + var pluckTags datatypes.JSONSlice[Tag] + if err := DB.Model(&UserWithJSON{}).Limit(1).Order("id asc").Pluck("tags", &pluckTags).Error; err != nil { + t.Fatalf("failed to pluck for field, got error %v", err) + } + AssertEqual(t, len(pluckTags), 2) + AssertEqual(t, pluckTags[0].Name, "tag1") + + // Smart Select Fields + var row struct { + Tags datatypes.JSONSlice[Tag] + } + if err := DB.Model(&UserWithJSON{}).Limit(1).Order("id asc").Find(&row).Error; err != nil { + t.Fatalf("failed to select attribute field, got error %v", err) + } + AssertEqual(t, len(row.Tags), 2) + AssertEqual(t, row.Tags[0].Name, "tag1") + // FirstOrCreate jsonMap := UserWithJSON{ Tags: datatypes.NewJSONSlice(tags),