Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert snowflake array to an array in Golang while querying the database

I am using "gosnowflake" driver to query Snowflake DB from my Golang application. Snowflake schema:- NAME STRING AGE INTEGER LOCS ARRAY

Golang Code:-

package main

import (
    "database/sql"
    "fmt"
    "log"
    "strings"

    _ "github.com/snowflakedb/gosnowflake"
)

type Person struct {
    Name        string
    Age         string
    Locs        []string

}

var DB *sql.DB

func main() {

    connString := "USER" + ":" + "PWD" + "@" + "REGION" + "/" + "TEST"
    fmt.Println("DB Connection string..", connString)
    DB, _ = sql.Open("snowflake", connString)

    defer DB.Close()

    QRY := "SELECT NAME,AGE,LOCS FROM TEST.PERSON WHERE NAME='abc'"
    result, _ := DB.Query(QRY)
    fmt.Println(result)

    for result.Next() {
        var row Person
        err := result.Scan(&row.Name, &row.Age, &row.Locs)



        if err != nil {
            log.Fatal(err)
        }

        fmt.Println("Before returning..", row)
    }


}

Issue:- The issue here is in the DB LOCS in an array, but while querying from golang code it returns as a string. so the values are like

[
   "XYZ",
   "DEF"
]

What I want is directly convert the LOCS values to an array in my golang code. So, inside the Person struct it binds directly to Loc []string.

like image 771
dks551 Avatar asked Oct 16 '22 11:10

dks551


1 Answers

Unless there is already a built-in string array type in gosnowflake, you might need to implement your own type that follows the sql.Scanner Interface

e.g.

type ArrayString []string

func (a *ArrayString) Scan(src interface{}) error {

    switch v := src.(type) {
    case string:
        return json.Unmarshal([]byte(v), a)
    case []byte:
        return json.Unmarshal(v, a)
    default:
        return errors.New("invalid type")
    }

}

Then your Person struct would be:

type Person struct {
    Name string
    Age  string
    Locs ArrayString
}
like image 119
ssemilla Avatar answered Nov 15 '22 05:11

ssemilla