dqhr76378 2019-04-01 00:36
浏览 35
已采纳

扫描Postgres复合类型

I have a composite type defined for use in a table:

CREATE TYPE duration AS (
    hours NUMERIC,
    minutes NUMERIC
);

CREATE TABLE foo (
    id SERIAL PRIMARY KEY,
    my_duration duration
);

INSERT INTO foo (id, my_duration) VALUES
(1, ROW(1, 30));

How can I scan this with database/sql? When I implement the scanner interface with

func (d *Duration) Scan(value interface{}) error {
    log.Println(value)
    if value == nil {
        *d = Duration{
            Hours:   -1,
            Minutes: -1,
        }
        return nil
    }
    if duration, ok := value.(Duration); ok {
        *d = Duration(duration)
        return nil
    }
    return errors.New("Failed to scan duration")
}

The type of the interface comes out as []uint8, and the value itself is an encoded array, something like [40 50 44 51 51 41]. How can I parse the composite type properly?

edit: I have a Duration struct defined as

type Duration struct {
    Hours   int
    Minutes int
}
  • 写回答

1条回答 默认 最新

  • drpmazn9021 2019-04-01 07:27
    关注

    The byte slice [40 50 44 51 51 41], when converted to a string and printed to stdout looks like this (2,33), see link.

    So you can see that what you're getting back from the db is a tuple with two integers separated by a comma. With that knowledge you can implement the Scanner interface that parses the custom data type values.

    func (d *Duration) Scan(value interface{}) error {
        if b, ok := value.([]byte); ok {
            ss := strings.Split(strings.Trim(string(b), "()"), ",")
            if len(ss) != 2 {
                return errors.New("unknown Duration format: " + string(b))
            }
    
            h, err := strconv.Atoi(ss[0])
            if err != nil {
                return err
            }
            m, err := strconv.Atoi(ss[1])
            if err != nil {
                return err
            }
    
            d.Hours, d.Minutes = h, m
        } else {
            d.Hours, d.Minutes = -1, -1
        }
        return nil
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)