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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源