Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(database/gdb): json type field incorrect scanning to string slice attribute #4107

Open
wants to merge 11 commits into
base: feat/v2.9.0
Choose a base branch
from

Conversation

gqcn
Copy link
Member

@gqcn gqcn commented Jan 9, 2025

No description provided.

@gqcn gqcn requested review from houseme, hailaz, oldme-git and wln32 January 9, 2025 06:18
@gqcn gqcn marked this pull request as ready for review January 10, 2025 02:17
@wln32
Copy link
Member

wln32 commented Jan 12, 2025

@gqcn @cyjaysong
我又看了下我之前提的pr #3557 在这个pr里,我提供了一个叫做RegisterDatabaseConvertFunc的函数,
这个函数可以用来注册任意的数据库类型转换到go类型,issue #4086的问题,可以用如下代码解决,
我们应该提供一个像这样的接口给开发者,用以支持任意数据库类型到go类型的能力,
这样下次遇到不支持的类型时,开发者们不必等到下个版本才能把问题修复或者使用别的办法

// 函数签名
// func RegisterDatabaseConvertFunc(driverName, columnType string, fn fieldConvertFunc) 

gdb.RegisterDatabaseConvertFunc("mysql", "json", func(dest reflect.Value, src any) (err error) {
		// 使用dest.Addr()是因为json.Unmarshal需要指针类型
		dv := dest.Addr().Interface()
		// src就是数据库给的数据
		// dest是要赋值给go的结构体字段
		switch dv.(type) {
		case *[]string:
			err = json.Unmarshal(src.([]byte), dv)
		case *[]int64:
			err = json.Unmarshal(src.([]byte), dv)
		default:
			err=fmt.Errorf("暂时不支从json类型反序列化到%T", dv)
		}
		return err
	})

@wln32
Copy link
Member

wln32 commented Jan 13, 2025

@gqcn 后续对于此类问题可以使用 pr #4114 ,不用每次遇到类型不支持时,就修改gf,开放自定义类型转换的接口出去即可,orm默认只支持一些常见类型即可

@Issues-translate-bot
Copy link

Bot detected the issue body's language is not English, translate it automatically. 👯👭🏻🧑‍🤝‍🧑👫🧑🏿‍🤝‍🧑🏻👩🏾‍🤝‍👨🏿👬🏿


@gqcn You can use pr #4114 for such problems in the future. You don’t need to modify gf every time you encounter a type that is not supported. Just open the interface for custom type conversion. ORM only supports some common types by default.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants