jsql

package module
v0.0.0-...-7a002d5 Latest Latest
Warning

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

Go to latest
Published: Aug 23, 2019 License: Unlicense Imports: 10 Imported by: 0

README

go-jsql

Package jsql provides functions to glue json to sql databases.

GoDoc

Documentation

Overview

Package jsql provides glue between database/sql and json.

Index

Constants

This section is empty.

Variables

View Source
var Debug = false
View Source
var PositionalQueryVars = true

PositionalQueryVars controls wether the generated query strings will use '?' or $1, $2... syntax.

Functions

func Handler

func Handler(db *sql.DB, query string) http.Handler

Handler is a convenience wrapper around MkHandler that will die on error.

func MkHandler

func MkHandler(db *sql.DB, query string) (http.Handler, error)

MkHandler produces a http.Handler that takes arguments from the request, and runs Q, producing a nice error message if needed.

The arguments are taken from the request's formvalues or any input json object, depending on the requests content type, merged with the "github.com/gorilla/mux".Vars(r), which take precedence in case of name conflicts.

Types

type QueryFunc

type QueryFunc func(args map[string]interface{}, w io.Writer) (n int, err error)

A queryfunc is the type of function generated by Q. It executes a query substituting arguments from the provided args map, and writes a JSON array of objects to the provided writer. It returns the number of array elements written and any error that may have occured.

If w is an http.ResponseWriter (has a Header() http.Header method), then it will set the Content-Type header to application/json;charset=UTF-8 before the first write.

If n == 0, nothing, not even the opening bracket, will have been written to w, and the header will not have been set, meaning it is not too late to call e.g.

http.Error(w, err.Error(), http.StatusInternalError)

otherwise the error will have to be tacked on to the already produced output or reported out of band. If any elements have been written the queryfunc will always generate a proper closing bracket.

func Q

func Q(db *sql.DB, query string) (QueryFunc, error)

Q builds a function that can execute the query on a database given a map of parameters, and writes the result as json to a writer.

The query must be of the form 'SELECT foo FROM bar WHERE x = ${varname}' that is, any query accepted by the driver that will provide db, but with the normal '$1, $2...' parameters replace by ${varname}.

The generated function will extract the corresponding values from the args map and supply them to the db.Stmt.Execute method in the correct order. The query will be rewritten to use $1, $2 .. etc.

The generated json will be an array of objects, one per row where each row object has keys named after the columns in the SQL query.

Jump to

Keyboard shortcuts

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