go-gorm / datatypes

GORM Customized Data Types Collection
https://gorm.io/docs/data_types.html
MIT License
698 stars 107 forks source link

add JSONSlice generic for slice data #199

Closed alingse closed 1 year ago

alingse commented 1 year ago

What did this pull request do?

  1. add type JSONSlice[T any] []T for generic type slice data.

why not use JSONType[[]T] ?

because JSONSlice is good for reflection, but JSONType is not.

for example

type User struct {
    Tags  JSONSlice[Tag]
    Tags2 JSONType[[]Tag]
}

when we use json to marshal the value we can got

{
   "tags":  [{"name": "tag1", "score":  1.0}],
   "tags2":  [{"name": "tag1", "score":  1.0}]
}

but we use other decode/encode/reflect method to process data (like https://github.com/mitchellh/mapstructure)

it will got an extra data level, cause JSONType with an extra Data Field

{
   "tags":  [{"name": "tag1", "score":  1.0}],
   "tags2": {
       "data": [{"name": "tag1", "score":  1.0}],
   }
}

golang do not support the generic type alias liketype JSONType[T any] T to auto bind the Value/ Scan method.

so, add a JSONSlice can solve this problem just for the slice value.

User Case Description

see the json_type_test.go

        type Tag struct {
            Name  string
            Score float64
        }
        type UserWithJSON struct {
            gorm.Model
            Name string
            Tags datatypes.JSONSlice[Tag]
        }

        var tags = []Tag{{Name: "tag1", Score: 0.1}, {Name: "tag2", Score: 0.2}}
                 var user = UserWithJSON{
            Name: "json-4",
            Tags: datatypes.NewJSONSlice(tags),
        }
                DB.Create(&users)
alingse commented 1 year ago
2023/03/16 04:34:18 /home/runner/work/datatypes/datatypes/json_type_test.go:142 ERROR: cached plan must not change result type (SQLSTATE 0A000)
[0.293ms] [rows:0] SELECT * FROM "user_with_jsons" WHERE "user_with_jsons"."id" = 2 AND "user_with_jsons"."deleted_at" IS NULL ORDER BY "user_with_jsons"."id" LIMIT 1
--- FAIL: TestJSONSlice (0.01s)
    json_type_test.go:143: failed to find user with json key, got error ERROR: cached plan must not change result type (SQLSTATE 0A000)
alingse commented 1 year ago

cc @jinzhu

rmacklin commented 1 year ago

Thanks for adding this! Are there plans to include this in a new release?

rmacklin commented 1 year ago

Thanks for releasing https://github.com/go-gorm/datatypes/releases/tag/v1.2.0 !