Search code examples
mysqlgosqlx

How do I preprocess rows fetched with sqlx?


Consider the following example:

package main

import (
    "fmt"
    "github.com/jmoiron/sqlx"
    _ "github.com/go-sql-driver/mysql"
)

type Data struct {
    Stuff string
}

func main() {
    db, _ := sqlx.Connect("mysql", "root:root@(localhost:3306)/data")
    var datas []Data
    db.Select(&datas, "select 'a,b' stuff from data limit 10")
    fmt.Println(datas)
}

What I'd like to do is have Stuff as []string, where it would be split by ,. I guess I could add an extra []string field and loop over the results populating this field and removing the source data, but that seems inefficient. What's the canonical way to do this in sqlx?


Solution

  • While this is not supported out of the box you can create custom struct implementing Scanner interface (https://golang.org/pkg/database/sql/#Scanner):

    type StringList []string
    
    // Scan implements Scanner interface and parses 
    // database result to StringList struct.
    func (s *StringList) Scan(src interface{}) error {
        var source string
    
        switch src.(type) {
        case string:
            source = src.(string)
        case []byte:
            source = string(src.([]byte))
        default:
            return errors.New("Incompatible type for StringList")
        }
    
        *s = strings.Split(source, ",")
        for i := range *s {
            (*s)[i] = strings.TrimSpace((*s)[i])
        }
    
        return nil
    }
    

    And use this struct instead of string:

    type Data struct {
        Stuff StringList
    }