Scan Nullable SQL Columns Safely

Map nullable database columns into sql.NullString and *string fields, then emit clean nulls through a custom JSON view.

GoData Integrity

Code

gosnippet
51 lines
package main

import (
	"database/sql"
	"encoding/json"
	"fmt"
)

type Profile struct {
	ID       int64          `json:"id"`
	Nickname sql.NullString `json:"-"`
	Bio      *string        `json:"bio"`
}

type profileJSON struct {
	ID       int64   `json:"id"`
	Nickname *string `json:"nickname"`
	Bio      *string `json:"bio"`
}

func nullString(value sql.NullString) *string {
	if !value.Valid {
		return nil
	}
	return &value.String
}

func (p Profile) MarshalJSON() ([]byte, error) {
	return json.Marshal(profileJSON{
		ID:       p.ID,
		Nickname: nullString(p.Nickname),
		Bio:      p.Bio,
	})
}

func scanProfile(row *sql.Row) (Profile, error) {
	var profile Profile
	err := row.Scan(&profile.ID, &profile.Nickname, &profile.Bio)
	return profile, err
}

func main() {
	encoded, _ := json.Marshal(Profile{ID: 7})
	fmt.Println(string(encoded))
	encoded, _ = json.Marshal(Profile{
		ID:       8,
		Nickname: sql.NullString{String: "ada", Valid: true},
	})
	fmt.Println(string(encoded))
}

Inside the snippet

The working surface is the functions nullString, MarshalJSON, scanProfile and main — everything else is wiring.

Putting it to use

The primary signature is func (p Profile) MarshalJSON() ([]byte, error)

Core lines

func scanProfile(row *sql.Row) (Profile, error) {
	var profile Profile
	err := row.Scan(&profile.ID, &profile.Nickname, &profile.Bio)
	return profile, err
}
func (p Profile) MarshalJSON() ([]byte, error) {
	return json.Marshal(profileJSON{
		ID:       p.ID,
		Nickname: nullString(p.Nickname),
		Bio:      p.Bio,
	})
}
func nullString(value sql.NullString) *string {
	if !value.Valid {
		return nil
	}
	return &value.String
}

Interactive Tools for This Topic

FAQ

How do you run Scan Nullable SQL Columns Safely?
This is a complete program, not a library excerpt — execution starts at the top.