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 flask实现搜索框访问数据库
  • ¥15 mrk3399刷完安卓11后投屏调试只能显示一个设备
  • ¥20 白日门传奇少一个启动区服和启动服务器的快捷键,东西都是全的 , 他们说套一个出来就行了 但我就是弄不好,谁看看,
  • ¥100 如何用js写一个游戏云存档
  • ¥15 ansys fluent计算闪退
  • ¥15 有关wireshark抓包的问题
  • ¥15 需要写计算过程,不要写代码,求解答,数据都在图上
  • ¥15 向数据表用newid方式插入GUID问题
  • ¥15 multisim电路设计
  • ¥20 用keil,写代码解决两个问题,用库函数