sqlutil

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Jul 23, 2021 License: MIT Imports: 5 Imported by: 0

README

sqlutil

Build Status Go Report Card go.dev reference

A collection of helpers to deal with database.

Example:

package main

import (
	"context"
	"database/sql"
	"fmt"
	"log"

	"github.com/allisson/sqlutil"
	_ "github.com/lib/pq"
)

type Player struct {
	ID   string `db:"id"`
	Name string `db:"name" fieldtag:"update"`
	Age  int    `db:"age" fieldtag:"update"`
}

func main() {
	// Connect to database
	db, err := sql.Open("postgres", "postgres://user:pass@localhost/sqlutil?sslmode=disable")
	if err != nil {
		log.Fatal(err)
	}
	err = db.Ping()
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	// Create table
	_, err = db.Exec(`
		CREATE TABLE IF NOT EXISTS players(
			id VARCHAR PRIMARY KEY,
			name VARCHAR NOT NULL,
			age INTEGER NOT NULL
		)
	`)
	if err != nil {
		log.Fatal(err)
	}

	// Insert players
	r9 := Player{
		ID:   "R9",
		Name: "Ronaldo Fenômeno",
		Age:  44,
	}
	r10 := Player{
		ID:   "R10",
		Name: "Ronaldinho Gaúcho",
		Age:  41,
	}
	flavour := sqlutil.PostgreSQLFlavor
	tag := "" // empty tag will use all fields from struct
	ctx := context.Background()
	if err := sqlutil.Insert(ctx, db, sqlutil.PostgreSQLFlavor, tag, "players", &r9); err != nil {
		log.Fatal(err)
	}
	if err := sqlutil.Insert(ctx, db, sqlutil.PostgreSQLFlavor, tag, "players", &r10); err != nil {
		log.Fatal(err)
	}

	// Get player
	findOptions := sqlutil.NewFindOptions(flavour).WithFilter("id", "R10")
	if err := sqlutil.Get(ctx, db, "players", findOptions, &r10); err != nil {
		log.Fatal(err)
	}
	fmt.Printf("%#v\n", r10)

	// Select players
	players := []*Player{}
	findAllOptions := sqlutil.NewFindAllOptions(flavour).WithLimit(10).WithOffset(0).WithOrderBy("name asc")
	if err := sqlutil.Select(ctx, db, "players", findAllOptions, &players); err != nil {
		log.Fatal(err)
	}
	for _, p := range players {
		fmt.Printf("%#v\n", p)
	}

	// Update player
	tag = "update" // will use fields with fieldtag:"update"
	r10.Name = "Ronaldinho Bruxo"
	if err := sqlutil.Update(ctx, db, sqlutil.PostgreSQLFlavor, tag, "players", r10.ID, &r10); err != nil {
		log.Fatal(err)
	}

	// Delete player
	if err := sqlutil.Delete(ctx, db, sqlutil.PostgreSQLFlavor, "players", r9.ID); err != nil {
		log.Fatal(err)
	}
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Delete

func Delete(ctx context.Context, db *sql.DB, flavor Flavor, tableName string, id interface{}) error

Delete is a high-level function that calls DeleteQuery and db.ExecContext.

func DeleteQuery

func DeleteQuery(flavor Flavor, tableName string, id interface{}) (string, []interface{})

DeleteQuery returns compiled DELETE string and args.

func FindAllQuery

func FindAllQuery(tableName string, options *FindAllOptions) (string, []interface{})

FindAllQuery returns compiled SELECT string and args.

func FindQuery

func FindQuery(tableName string, options *FindOptions) (string, []interface{})

FindQuery returns compiled SELECT string and args.

func Get

func Get(ctx context.Context, db *sql.DB, tableName string, options *FindOptions, dst interface{}) error

Get is a high-level function that calls FindQuery and scany sqlscan.Get function.

func Insert

func Insert(ctx context.Context, db *sql.DB, flavor Flavor, tag, tableName string, structValue interface{}) error

Insert is a high-level function that calls InsertQuery and db.ExecContext.

func InsertQuery

func InsertQuery(flavor Flavor, tag, tableName string, structValue interface{}) (string, []interface{})

InsertQuery returns compiled INSERT string and args.

func Select

func Select(ctx context.Context, db *sql.DB, tableName string, options *FindAllOptions, dst interface{}) error

Select is a high-level function that calls FindAllQuery and scany sqlscan.Select function.

func Update

func Update(ctx context.Context, db *sql.DB, flavor Flavor, tag, tableName string, id interface{}, structValue interface{}) error

Update is a high-level function that calls UpdateQuery and db.ExecContext.

func UpdateQuery

func UpdateQuery(flavor Flavor, tag, tableName string, id interface{}, structValue interface{}) (string, []interface{})

UpdateQuery returns compiled UPDATE string and args.

Types

type FindAllOptions

type FindAllOptions struct {
	Flavor  Flavor
	Fields  []string
	Filters map[string]interface{}
	Limit   int
	Offset  int
	OrderBy string
}

FindAllOptions provides configuration for FindAllQuery function.

func NewFindAllOptions

func NewFindAllOptions(flavor Flavor) *FindAllOptions

NewFindAllOptions returns a FindAllOptions.

func (*FindAllOptions) WithFields

func (f *FindAllOptions) WithFields(fields []string) *FindAllOptions

WithFields is a helper function to construct functional options that sets Fields field.

func (*FindAllOptions) WithFilter

func (f *FindAllOptions) WithFilter(field string, value interface{}) *FindAllOptions

WithFilter is a helper function to construct functional options that sets Filters field.

func (*FindAllOptions) WithLimit

func (f *FindAllOptions) WithLimit(limit int) *FindAllOptions

WithLimit is a helper function to construct functional options that sets Limit field.

func (*FindAllOptions) WithOffset

func (f *FindAllOptions) WithOffset(offset int) *FindAllOptions

WithOffset is a helper function to construct functional options that sets Offset field.

func (*FindAllOptions) WithOrderBy

func (f *FindAllOptions) WithOrderBy(orderBy string) *FindAllOptions

WithOrderBy is a helper function to construct functional options that sets OrderBy field.

type FindOptions

type FindOptions struct {
	Flavor  Flavor
	Fields  []string
	Filters map[string]interface{}
}

FindOptions provides configuration for FindQuery function.

func NewFindOptions

func NewFindOptions(flavor Flavor) *FindOptions

NewFindOptions returns a FindOptions.

func (*FindOptions) WithFields

func (f *FindOptions) WithFields(fields []string) *FindOptions

WithFields is a helper function to construct functional options that sets Fields field.

func (*FindOptions) WithFilter

func (f *FindOptions) WithFilter(field string, value interface{}) *FindOptions

WithFilter is a helper function to construct functional options that sets Filters field.

type Flavor

type Flavor int

Flavor is the flag to control the format of compiled sql.

const (
	MySQLFlavor Flavor = iota + 1
	PostgreSQLFlavor
	SQLiteFlavor
)

Supported flavors.

Jump to

Keyboard shortcuts

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