encoding

package
v0.0.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 13, 2019 License: MIT Imports: 6 Imported by: 0

Documentation

Overview

Package encoding provides marshalling values to and from SQL. Gracefully handles null values.

The simplest way to use this is to take advantage of the base marshal and unmarshal functions:

An example below:

db, err := sql.Open("sqlite3", ":memory:")

type user struct {
	ID int `db:"id"`
}

cols, vals, err := encoding.Marshal(user{1})
_, err = db.Exec(
	"insert into users ("+strings.Join(cols, ",")+") values "+"(?)", vals...,
)

users := []user{}
rows, err := db.Query("select * from users")
err = encoding.Unmarshal(&users, rows)

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrRequiresPtr is returned if a non pointer value is passed to Decode.
	ErrRequiresPtr = errors.New("sqlkit/encoding: non pointer passed to Decode")
	// ErrMustNotBeNil is returned if a nil value is passed to Decode.
	ErrMustNotBeNil = errors.New("sqlkit/encoding: nil value passed to Decode")
	// ErrMissingDestination is returned if a destination value is missing and
	// unsafe is not configured.
	ErrMissingDestination = errors.New("sqlkit/encoding: missing destination")
	// ErrTooManyColumns is returned when too many columns are present to scan
	// into a value.
	ErrTooManyColumns = errors.New("sqlkit/encoding: too many columns to scan")
	// ErrNoRows is mirrored from the database/sql package.
	ErrNoRows = sql.ErrNoRows
)
View Source
var DefaultMapper = reflectx.NewMapperFunc("db", Underscore)

DefaultMapper is the default reflectx mapper used. This uses strings.ToLower to map field names.

View Source
var (
	// ErrDuplicateValue is returned when duplicate values exist in the struct.
	ErrDuplicateValue = errors.New("sqlkit/marshal: duplicate values")
)

Functions

func Marshal

func Marshal(obj interface{}) ([]string, []interface{}, error)

Marshal runs the default encoder.

Example
package main

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

	"github.com/colinjfw/sqlkit/encoding"
)

func main() {
	db, err := sql.Open("sqlite3", ":memory:")
	if err != nil {
		panic(err)
	}

	type user struct {
		ID int `db:"id"`
	}

	_, err = db.Exec("create table users (id int primary key)")
	if err != nil {
		panic(err)
	}

	usr := user{ID: 1}

	cols, vals, err := encoding.Marshal(usr)
	if err != nil {
		panic(err)
	}
	fmt.Printf("cols: %v, vals: %v\n", cols, vals)

	_, err = db.Exec(
		"insert into users ("+strings.Join(cols, ",")+") values "+"(?)", vals...,
	)
	if err != nil {
		panic(err)
	}

}
Output:

cols: [id], vals: [1]

func Underscore

func Underscore(s string) string

Underscore will map camel case wording to snake case.

func Unmarshal

func Unmarshal(dest interface{}, rows *sql.Rows) error

Unmarshal will run Decode with the default Decoder configuration.

Example
package main

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

	"github.com/colinjfw/sqlkit/encoding"
)

func main() {
	db, err := sql.Open("sqlite3", ":memory:")
	if err != nil {
		panic(err)
	}

	type user struct {
		ID int `db:"id"`
	}

	_, err = db.Exec("create table users (id int primary key)")
	if err != nil {
		panic(err)
	}

	usr := user{ID: 1}

	cols, vals, err := encoding.Marshal(usr)
	if err != nil {
		panic(err)
	}
	fmt.Printf("cols: %v, vals: %v\n", cols, vals)

	_, err = db.Exec(
		"insert into users ("+strings.Join(cols, ",")+") values "+"(?)", vals...,
	)
	if err != nil {
		panic(err)
	}

	rows, err := db.Query("select * from users")
	if err != nil {
		panic(err)
	}

	usrs := []user{}
	err = encoding.Unmarshal(&usrs, rows)
	if err != nil {
		panic(err)
	}
	fmt.Printf("query: %+v\n", usrs)

}
Output:

cols: [id], vals: [1]
query: [{ID:1}]

Types

type Encoder

type Encoder struct {
	// contains filtered or unexported fields
}

Encoder manages options for encoding.

func NewEncoder

func NewEncoder() Encoder

NewEncoder returns an Encoder with the default settings which are blank.

func (Encoder) Decode

func (e Encoder) Decode(dest interface{}, rows *sql.Rows) error

Decode does the work of decoding an *sql.Rows into a struct, array or scalar value. Depending on the value passed in the decoder will perform the following actions:

  • If an array is passed in the decoder will work through all rows initializing and scanning in a new instance of the value(s) for all rows.
  • If the values inside the array are scalar, then the decoder will check for only a single column to scan and scan this in.
  • If a single struct or scalar is passed in the decoder will loop once over the rows returning sql.ErrNoRows if this is possible and scan the value.

The rows object is not closed after iteration is completed. The Decode function is thread safe.

func (Encoder) Encode

func (e Encoder) Encode(obj interface{}) ([]string, []interface{}, error)

Encode will encode to a set of fields and values using the Encoder's settings. It will return and error if there are duplicate fields and unsafe is not set.

func (Encoder) Unsafe

func (e Encoder) Unsafe() Encoder

Unsafe configures and returns a new Encoder which uses unsafe options. Specifically it will ignore duplicate fields on marshalling and will ignore missing fields on unmarshalling.

func (Encoder) WithMapper

func (e Encoder) WithMapper(m *reflectx.Mapper) Encoder

WithMapper configures the encoder with a reflectx.Mapper for configuring different fields to be encoded. The DefaultMapper is used if this is not set.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL