dtt83024 2019-04-28 13:56
浏览 54

正确处理gRPC类型到SQL ORM

I'm implementing a gRPC server and using an ORM called Boiler for Go. I've gotten to a point where I've built all my models and protos and now I'm handling specific type issues.

Within my protobuf files I've declared most types as strings. However my ORM treats (due to how it interfaces with Postgres) strings as null.String in it's models. Hence when I attempt something like so I get an error:

user := &models.User{
    FirstName:   req.FirstName,
    LastName:    req.LastName,
    Email:       req.Email,
    Gender:      req.Gender,
    PhoneNumber: req.PhoneNumber,
}

The error: services/users.go:46:3: cannot use req.FirstName (type string) as type null.String in field value

The question is what would be the most appropriate way of handling this situation. I could: generate a new struct (which I'm already using for data validation) and cast them into null.String or I suppose I could attempt to force the casting somehow?

The question then becomes if a user doesn't supply a value in the API and the validation process allows it, how would that handle the non-existing record?

Edit: Seems like SQLBoiler developers have a package for handling nulls separately. ie. null.StringFrom(), null.Int15From etc. which I'd in essence wrap all my fields with as such:

user := &models.User{
    FirstName:        null.StringFrom(req.FirstName),
    LastName:         null.StringFrom(req.LastName),
    Email:            null.StringFrom(req.Email),
    Password:         string(password_hash),
    Role:             "BASIC_USER",
    Status:           "ACTIVE",
    Gender:           null.Int16From(req.Gender),
    PhoneNumber:      null.StringFrom(req.PhoneNumber),
    VerificationCode: null.StringFrom(code.String()),
}

Feels kind of dirty but I don't see any other options. Suggestions/opinions anyone?

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 虚拟机打包apk出现错误
    • ¥30 最小化遗憾贪心算法上界
    • ¥15 用visual studi code完成html页面
    • ¥15 聚类分析或者python进行数据分析
    • ¥15 逻辑谓词和消解原理的运用
    • ¥15 三菱伺服电机按启动按钮有使能但不动作
    • ¥15 js,页面2返回页面1时定位进入的设备
    • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
    • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
    • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝