sqljson

package module
v0.0.0-...-143c24a Latest Latest
Warning

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

Go to latest
Published: May 2, 2022 License: Apache-2.0 Imports: 4 Imported by: 0

README

sqljson

Wraps a Go type for automatic marshalling and unmarshalling with SQL, so you don't have to implement Scan() and Value().

You have a struct that is marshalled/unmarshalled to JSON data, and you want to store it in a SQL database, and have the struct type automatically marshal/unmarshal when you save/load it, without having to marshal to JSON manually. With generics in Go 1.18, this is now possible! 🥳

Usage

// You have a struct that you marshal/unmarshal from JSON and you want to automatically unmarshal.
type UserData struct {
	Name string `json:"name"`
}

// Your SQL model, in this example used with GORM.
type Model struct {
	ID       uint                    `gorm:"primarykey"`
	UserData sqljson.JSON[UserData] // Use the JSON type with UserData, your data struct, as a type parameter.
}


func main() {
  db, _ := gorm.Open(sqlite.Open("file::memory:"), &gorm.Config{})
  user := UserData{Name: "Beautiful Name"}
  // INSERT INTO `models` (`user_data`) VALUES ("{\"name\":\"user\"}") RETURNING `id`
  db.Save(&Model{UserData: sqljson.From(user)})
  
  modelFromDb := Model{}
  db.First(&modelFromDb)
  println(modelFromDb.UserData.Item.Name) // "Beautiful Name"
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type JSON

type JSON[T any] struct {
	Item T
}

func From

func From[T any](input T) JSON[T]

func (JSON[T]) MarshalJSON

func (j JSON[T]) MarshalJSON() ([]byte, error)

func (*JSON[T]) Scan

func (j *JSON[T]) Scan(value interface{}) error

func (*JSON[T]) UnmarshalJSON

func (j *JSON[T]) UnmarshalJSON(data []byte) error

func (JSON[T]) Value

func (j JSON[T]) Value() (driver.Value, error)

Jump to

Keyboard shortcuts

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