Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Scan interface to lowercase a string read from the database

Tags:

go

I want to lower case a string as I read it in from the database. I know this can be done in SQL, but this is my first day with go and this is more of a proof of concept (and understanding of go) rather than an actual requirement.

type EmailAddress should always be lowercase when read from the db using the Scan interface, this breaks with panic: interface conversion: interface is []uint8, not string

package main

import (
  "database/sql"
  "github.com/kisielk/sqlstruct"
  _ "github.com/lib/pq"
  "log"
  "strings"
)

type EmailAddress string

func (g *EmailAddress) Scan(src interface{}) error {
  *g = EmailAddress(strings.ToLower(src.(string)))
  return nil
}

type User struct {
  Id          int
  MobilePhone string `sql:"mobile_phone"`
  Email       EmailAddress
}

func main() {
  db, _ := sql.Open("postgres", "host=localhost dbname=test sslmode=disable")
  defer db.Close()

  rows, _ := db.Query("SELECT id, mobile_phone, COALESCE(email,'') as email FROM users limit 5")

  for rows.Next() {
    var t User
    _ = sqlstruct.Scan(&t, rows)
    log.Printf("%+v\n", t)
  }
}
like image 236
Krut Avatar asked Dec 14 '13 07:12

Krut


1 Answers

You're seeing the []uint8 error because the EmailAddress is being provided as a byte slice, rather than a string. Remember, byte is just an alias for uint8. Here's a simple example which shows the error you're seeing: http://play.golang.org/p/iN5y3PaFAL

So, the easiest fix would be to change the scan function:

func (g *EmailAddress) Scan(src interface{}) error {
  b, ok := src.([]byte)
  if !ok {
    return fmt.Errorf("expected []byte, got %T", src)
  }
  *g = EmailAddress(strings.ToLower(string(b))
  return nil
}
like image 198
djd Avatar answered Oct 16 '22 02:10

djd