简体   繁体   English

如何使用gorm在postgres SQL数据库中存储一个点

[英]How to store a point in postgres SQL database using gorm

我正在尝试在 Go 服务器上使用 GORM 在 SQL 数据库中存储 Point 变量,我尝试到处寻找,但还没有看到让我满意的答案

For any type that's not supported by the standard library's database/sql package, nor by a 3rd party package that depends on database/sql , like gorm does, you can implement the Valuer and Scanner interfaces to add custom support for the type.对于不是由标准库的支持的任何类型database/sql包,也不是由第三方软件包依赖于database/sql ,像gorm做,你可以实现ValuerScanner接口,增加了对类型的自定义支持。

To be able to correctly implement those two interfaces you need to first find out what the target database expects as input and what it returns as output for that type.为了能够正确实现这两个接口,您需要首先找出目标数据库期望作为输入的内容以及该类型返回的输出内容。 In the case of PostgreSQL and the Point type the syntax is (x,y) .在 PostgreSQL 和 Point 类型的情况下,语法是(x,y)

So what you can do is the following:所以你可以做的是:

  1. Declare the type.声明类型。
type Point struct {
    X, Y float64
}
  1. Implement the Valuer interface.实现 Valuer 接口。
func (p Point) Value() (driver.Value, error) {
    out := []byte{'('}
    out = strconv.AppendFloat(out, p.X, 'f', -1, 64)
    out = append(out, ',')
    out = strconv.AppendFloat(out, p.Y, 'f', -1, 64)
    out = append(out, ')')
    return out, nil
}
  1. Implement the Scanner interface.实现扫描仪接口。
func (p *Point) Scan(src interface{}) (err error) {
    var data []byte
    switch src := src.(type) {
    case []byte:
        data = src
    case string:
        data = []byte(src)
    case nil:
        return nil
    default:
        return errors.New("(*Point).Scan: unsupported data type")
    }

    if len(data) == 0 {
        return nil
    }

    data = data[1 : len(data)-1] // drop the surrounding parentheses
    for i := 0; i < len(data); i++ {
        if data[i] == ',' {
            if p.X, err = strconv.ParseFloat(string(data[:i]), 64); err != nil {
                return err
            }
            if p.Y, err := strconv.ParseFloat(string(data[i+1:]), 64); err != nil {
                return err
            }
            break
        }
    }
    return nil
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM