将客户端UUID转换为SQL UUID

时间:2018-01-27 18:43:34

标签: postgresql go

我正在使用go和包uuid来生成类型为[16]byte的uuid。但是,当我尝试将该uuid插入postgres类型的uuid列时,我收到错误converting argument $1 type: unsupported type [16]uint8, a array。显然我应该在将其插入数据库之前在客户端上转换uuid。我该怎么办?我应该将它转换为什么类型?

简而言之:go数据类型适用于uuid中的postgres

1 个答案:

答案 0 :(得分:1)

通过@sberry的链接,我找到了成功。以下是有益的代码段(带有PostgreSQL 9.5数据库):

import (
    "database/sql"
    "net/http"

    "github.com/google/uuid"
)

type Thing struct {
    ID     uuid.UUID `json:"-" sql:",type:uuid"`
    Name   string    `json:"name"`
}

// For a database table created as such:
// CREATE TABLE things ( 
// id UUID PRIMARY KEY DEFAULT gen_random_uuid(), 
// name TEXT DEFAULT ''::text
// )

func selectThingssSQL() ([]Thing, error) {
    things := make([]Thing, 0)

    rows, err := db.Query("SELECT id, name FROM things")
    if err != nil {
        return nil, err
    }
    defer rows.Close()

    for rows.Next() {
        t := &Thing{}
        if err := rows.Scan(&t.ID, &t.Name); err != nil {
            return nil, err
        }
        things = append(things, *t)
    }

    return things, nil
}