stmts

package module
v0.0.0-...-daa34e1 Latest Latest
Warning

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

Go to latest
Published: Aug 25, 2017 License: MIT Imports: 3 Imported by: 0

README

stmts

This is a utility package to create a concurrency safe collection of sqlx named statements that can be consumed in 3 stages. Registration, preparation, and execution.

Go Report Card Go Doc license

how to

package main

import (
  "fmt"
  "database/sql"
  
  "github.com/jmoiron/sqlx"
  "github.com/whitecypher/stmts"
)

// storing queries in constants will make it easier to retrieve the queries from the collection later. The query is the key.
const (
  qGetSomething = `SELECT * FROM mytable WHERE id = :id`
  qUpdateSomething = `UPDATE mytable SET my_name_is = :name WHERE id = :id`
  qDeleteSomething = `DELETE FROM mytable WHERE id = :id`
)

func main() { 
  // using sqlx for database operations
  var db *sqlx.DB
  
  // TODO: resolve the connection to the database
  
  // collection has no dependencies so a simple declaration is sufficient.
  var named stmts.Named
  
  // add queries
  named.Add(
    qGetSomething,
    qUpdateSomething,
    qDeleteSomething,
  )
  
  // prepare the statements
  err := named.Prepare(db)
  if err != nil {
    // TODO: handle the error however you like
  }
  // or use
  named.MustPrepare(db, func(format string, v ...interface{}) { 
    // TODO: handle the error however you like
  }) 
  
  // retrieve and execute a query
  var row struct {
    ID   uint64 `db:"id"`
    Name string `db:"name"`
  }
  err := named.Stmt(qGetSomething).Get(&row, struct {
    ID uint64 `db:"id"`
  }{
    ID: 1,
  })
  if err != nil && err != sql.ErrNoRows {
    // TODO: handle the error however you like
  }
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Logf

type Logf func(format string, v ...interface{})

Logf interface for logging formatted messages such as log.Fatalf, log.Panicf, or log.Printf

type Named

type Named struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

Named map of queries and their *sqlx.NamedStmt counterparts.

func (*Named) Add

func (n *Named) Add(queries ...string)

Add queries to the Named stmts map. Statements for these queries can be retrieved using the same query after the map has been prepared.

func (*Named) MustPrepare

func (n *Named) MustPrepare(db *sqlx.DB, logf Logf)

MustPrepare prepares all the queries in the map and triggers the provided logf function if something goes wrong

func (*Named) Prepare

func (n *Named) Prepare(db *sqlx.DB) error

Prepare all the queries in the map

func (*Named) Stmt

func (n *Named) Stmt(query string) *sqlx.NamedStmt

Stmt gets a prepared *sqlx.NamedStmt by query

Jump to

Keyboard shortcuts

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