Skip to content

Instantly share code, notes, and snippets.

@ble
Last active December 15, 2015 04:59
Show Gist options
  • Save ble/5206061 to your computer and use it in GitHub Desktop.
Save ble/5206061 to your computer and use it in GitHub Desktop.
Get a default value for null columns by implementing databse/sql.Scanner
package main
import (
"database/sql"
"errors"
_ "github.com/mattn/go-sqlite3"
"log"
"os"
)
type DefaultString string
func (d *DefaultString) Scan(value interface{}) error {
if value == nil {
return nil
}
if vString, ok := value.(string); ok {
*d = DefaultString(vString)
return nil
}
return errors.New("not clever enough to convert other types")
//but if we wanted to be, pkg/database/sql/convert.go shows the way
}
func main() {
tableDefinition := `
CREATE TABLE example (
eid INTEGER PRIMARY KEY,
etext TEXT(32));`
insertQ := `INSERT INTO example (eid, etext) VALUES (?, ?);`
insertQBlank := `INSERT INTO example (eid) VALUES (?);`
selectQ := `SELECT etext FROM example WHERE eid = ?`
dbFileName := "a_very_stupid_test.db"
_ = os.Remove(dbFileName) //don't care if we succeed at deleting this
db, err := sql.Open("sqlite3", dbFileName)
_, err = db.Exec(tableDefinition)
if err != nil {
log.Print(err.Error()) //blithely continue on if the table already exists
}
//insert with a null column
_, err = db.Exec(insertQBlank, 1)
if err != nil {
log.Panic(err.Error())
}
//insert with a non-null column
_, err = db.Exec(insertQ, 2, "this ain't the default text")
if err != nil {
log.Panic(err.Error())
}
for _, v := range [2]int{1, 2} {
fromDB := DefaultString("this is the default text")
err := db.QueryRow(selectQ, v).Scan(&fromDB)
if err != nil {
log.Panic(err.Error())
}
log.Printf("%d: %s", v, fromDB)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment