type ComputeConfig struct {
DbId
DbOwnerAudit
DbTimeAudit
Name *string `gorm:"column:name" json:"name"`
Type ComputeType `gorm:"column:type" json:"type"`
Endpoint *string `gorm:"column:endpoint" json:"endpoint"`
Config *pgtype.JSONB `gorm:"column:config" json:"config"`
}
func (db PostgresDB) CreateConfig(ctx context.Context, config *model.ComputeConfig) error {
err := db.WithContext(ctx).Create(config).Error
return err
}
[96.007ms] [rows:0] INSERT INTO "compute_config" ("created_by","updated_by","name","type","endpoint","config","id") VALUES ('[email protected]',NULL,'Compute config','DB','https://databricks.com','{"account_id":"acc_id","client_id":"client_id","cluster_id":"cluster1"}','95b17051-095e-4393-9aec-496d88a05cf6') RETURNING "id","created_on","updated_on"
GORM 无法插入此结构,但当我直接在控制台上运行查询时,它就可以插入。
来自 gorm 的错误:
ERROR: invalid input syntax for type json (SQLSTATE 22P02)
Token "" is invalid.
JSON data, line 1: ...
依赖关系
gorm.io/driver/postgres v1.5.11
gorm.io/gorm v1.25.12
go 1.21
已经尝试了一切方法来解决这个问题..尝试了不同的go版本仍然无法解决这个问题
表定义
-- auto-generated definition
create table compute_config
(
id uuid default uuid_generate_v4() not null
constraint pk_compute_config
primary key,
created_by text,
updated_by text,
created_on timestamp with time zone default now() not null,
updated_on timestamp with time zone,
name text not null,
endpoint text not null,
type compute_type not null,
config jsonb
);
alter table compute_config
owner to postgres;
API 请求正文
{
"name": "Compute Config",
"type": "DB",
"endpoint": "https://databricks.com",
"config": {
"account_id": "acc_id",
"client_id": "client_id",
"cluster_id": "cluster1"
}
}
用于转换为 JSONB 元的函数
func ConvertMapToJSONB(data map[string]interface{}) (*pgtype.JSONB, error) {
jsonData, err := json.Marshal(data)
if err != nil {
return nil, err
}
jsonb := &pgtype.JSONB{}
err = jsonb.Set(jsonData)
if err != nil {
return nil, err
}
return jsonb, nil
}
您如何解析您的请求正文? 如果您像这样解析请求正文:
reqBody := `{
"name": "Compute Config",
"type": "DB",
"endpoint": "https://databricks.com",
"config": {
"account_id": "acc_id",
"client_id": "client_id",
"cluster_id": "cluster1"
}
}`
var result ComputeConfig
err = json.Unmarshal([]byte(reqBody), &result)
if err != nil {
fmt.Println("Error unmarshaling JSON:", err)
} else {
fmt.Println("Parsed JSON successfully:", result)
}
您不需要使用
Config
将 ConvertMapToJSONB()
转换为 JSONB。
我可以使用 this。
也许您可以提供有关如何解析请求正文的更多详细信息。