不支持的扫描:SQL UUID数组

时间:2016-03-18 11:25:15

标签: postgresql go

我试图从PostgreSQL数据库中获取UUID数组,这会产生以下错误:

sql: Scan error on column index 0: unsupported Scan, storing driver.Value type []uint8 into type *[]string

获取单个UUID没有问题,但当它是array时,Scan函数会将元素的类型推断为uint8

有解决方法/解决方案吗?或者我应该重新考虑我的数据库?

代码:

func FetchListIdsForUser(id string, db *sql.DB) ([]string, error) {

        // where the results will be stored

        var (
            lists []string
        )


        // statement prep

        stmt, err := db.Prepare("select lists from users where object_id = $1")
            if err != nil {
            formattedError := er.New("FetchListIdsForUser SQL Select: " + err.Error())
            log.Println(formattedError)
            return nil,formattedError
        }
        defer stmt.Close()


        // query happening

        rows, err := stmt.Query(id)
        if err != nil {
            formattedError := er.New("FetchListIdsForUser SQL Query: " + err.Error())
            log.Println(formattedError)
            return nil,formattedError
        }

        defer rows.Close()


        // for each row

        for rows.Next() {

            // scan : this is where the error happens.

            err := rows.Scan(&lists)
            if err != nil {
                formattedError := er.New("FetchListIdsForUser SQL Scan: " + err.Error())
                log.Println(formattedError)
                return nil,formattedError
            }
            return lists,nil
        }

        err = rows.Err()
        if err != nil {
            formattedError := er.New("FetchListIdsForUser: " + id + " Does Not Exist")
            log.Println(formattedError)
            return nil,formattedError
        }
        return nil,er.New("FetchListIdsForUser: " + id + " Does Not Exist")
}

1 个答案:

答案 0 :(得分:1)

您的代码可以简化很多:

func FetchListIdsForUser(id string, db *sql.DB) ([]string, error) {

        rows, err := db.Query("SELECT unnest(lists) FROM users WHERE object_id = $1", id)
        if err != nil { 
            formattedError := errors.New("FetchListIdsForUser SQL Query: " + err.Error())
            return nil, formattedError
        }

        defer rows.Close()

        var lists []string
        var list string

        for rows.Next() {
            // scan every item of the array and append it to lists
            err := rows.Scan(&list)
            if err != nil {
                formattedError := errors.New("FetchListIdsForUser SQL Scan: " + err.Error())
                return nil,formattedError
            }
            lists = append(lists, list)
        }

        if lists == nil {
            // no rows returned
            formattedError := errors.New("FetchListIdsForUser: " + id + " Does Not Exist")
            return nil, formattedError
        }

        return lists, nil
}
  • db.Query()将为您准备(并缓存)该语句。没有必要手动执行此操作。
  • 我在select语句中添加了unnest(lists)。这将为数组中的每个元素生成一行。
  • 在for循环中,我们单独扫描每个元素并将其附加到lists

此外,this driver支持开箱即用的扫描阵列。