Skip to content

ORM Scan Feild Error #4096

@aveyuan

Description

@aveyuan

Go version

go1.23.2 linux/amd64

GoFrame version

v2.8.3

Can this bug be reproduced with the latest release?

Option Yes

What did you do?

package main

import (
	"context"
	"fmt"
	"log"

	_ "github.com/gogf/gf/contrib/drivers/mysql/v2"
	_ "github.com/gogf/gf/contrib/nosql/redis/v2"
	"github.com/gogf/gf/v2/frame/g"
)

func main() {
	ctx := context.Background()

	_, _ = g.DB().Exec(ctx, "DROP TABLE IF EXISTS proxy_param")
	_, _ = g.DB().Exec(ctx, `CREATE TABLE proxy_param (
	  proxy_id bigint NOT NULL,
	  recommend_ids json DEFAULT NULL,
	  photos json DEFAULT NULL,
	  PRIMARY KEY (proxy_id)
	) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci`)

	type ProxyParam struct {
		ProxyId      int64    `json:"proxyId"              orm:"proxy_id"              description:""`
		RecommendIds []int64  `json:"recommendIds" orm:"recommend_ids" description:""`
		Photos       []string `json:"photos"              orm:"photos"                 description:""`
	}

	_, err := g.DB().Ctx(ctx).Insert(ctx, "proxy_param", &ProxyParam{
		ProxyId: 1,
		// Photos:  []string{},  这里,如果没有传入photos,数据库的字段值会被设置为null,最终导致scan的时候 Photos的值为 ["null"],显然这应该是一个空
	})

	if err != nil {
		log.Fatal(err)
	}

	_, err = g.DB().Ctx(ctx).Insert(ctx, "proxy_param", &ProxyParam{
		ProxyId: 2,
		Photos:  []string{}, //这里,因为传入了变量,数据库的字段值会被设置为[],scan的时候,能够正确返回
	})

	if err != nil {
		log.Fatal(err)
	}

	var proxyParamList []*ProxyParam
	err = g.DB().Model("proxy_param").Ctx(ctx).Scan(&proxyParamList)
	fmt.Println(err) // nil
	for _, param := range proxyParamList {
		fmt.Printf("%+v\n", param)
	}

}

What did you see happen?

image
image

What did you expect to see?

scan返回的数据类型应该为空,我们注意到 https://goframe.org/docs/core/gdb-practice-using-json-for-complicated-field 中的实现,在写入的时候没有传值,读取的时候却读取到了错误的数据,从源码来看,目前看来在strings的转换上还欠缺一定的考虑。见 #3465 冲突。

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugIt is confirmed a bug, but don't worry, we'll handle it.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions