sqltemplate

package module
v1.0.0-beta2 Latest Latest
Warning

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

Go to latest
Published: Jan 6, 2023 License: MIT Imports: 10 Imported by: 0

README

SQL Template

SQL Template is a package to help generate correct SQL queries. Built on the standard text/template language sqltemplate generates SQL queries inserting values as SQL literals.

Documentation

Package documentation can be found at https://pkg.go.dev/github.com/mhilton/sqltemplate.

Documentation

Overview

Package sqltemplate provides a template language to help generate correct SQL queries. It is built on the standard library's text/template (see https://golang.org/pkg/text/template) package, and uses the same template language.

This package wraps the templates created by text/template such that the result of any pipeline is encoded using the sqlliteral function.

Unlike the html/template package no attempt is made to derive semantic understanding of the template and encode values differently depending on where they are used. Templates in this package will always encode the same value in the same way regardless of context.

The sqlliteral function

The sqlliteral template function must be a function of the form func(v interface{}) (RawSQL, error), the default implementation is PostgresLiteral.

Implementations of sqlliteral must support any type that implements database/sql/driver.Valuer along with the types documented to make up the database/sql/driver.Value type. These are:

nil
int64
float64
bool
[]byte
string
time.Time

Additional types may also be supported.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type FuncMap

type FuncMap = template.FuncMap

A FuncMap is an alias for text/template.FuncMap. See https://golang.org/pkg/text/template#FuncMap for details.

type Identifier

type Identifier string

An Identifier holds a value that should be formatted as an identifier in the SQL output.

type RawSQL

type RawSQL string

A RawSQL value contains part of an SQL query that will be inserted into the template output verbatim.

func PostgresLiteral

func PostgresLiteral(v interface{}) (RawSQL, error)

PostgresLiteral formats the value v as a literal suitable for use in queries used with the PostgreSQL database.

If v implements database/sql/driver.Valuer then Value() will be called before further processing.

The literal form used for values of a specified type is:

nil
  The SQL keyword NULL.
bool
  Either the SQL keyword TRUE, or FALSE.
int, int64
  The decimal value.
float64
  If the value represents +Inf, -Inf or Nan then the literal will be
  'Infinity', '-Infinity' or 'Nan' respectively. Otherwise the %g
  encoding provided by fmt.Printf is used.
string
  A string literal.
[]byte
  A bytea hex format literal, see
  https://www.postgresql.org/docs/13/datatype-binary.html#id-1.5.7.12.9.
time.Time
  A string literal containing the RFC3339 encoding of the time stamp.
Identifier
  A quoted identifier, see
  https://www.postgresql.org/docs/13/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS.

type Template

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

A Template is the representation of a parsed template.

func Must

func Must(t *Template, err error) *Template

Must is a helper that wraps a call to a function returning (*Template, error) and panics if the error is non-nil. It is intended for use in variable initializations such as

var t = sqltemplate.Must(sqltemplate.New("name").Parse("text"))

func New

func New(name string) *Template

New allocates a new, undefined template with the given name.

func ParseFS

func ParseFS(fsys fs.FS, patterns ...string) (*Template, error)

ParseFS is like ParseFiles or ParseGlob but reads from the file system fsys instead of the host operating system's file system. It accepts a list of glob patterns. (Note that most file names serve as glob patterns matching only themselves.)

func ParseFiles

func ParseFiles(filenames ...string) (*Template, error)

ParseFiles creates a new Template and parses the template defintions from the named files. The returned template's name will have the base name and parsed contents of the first file. There must be at least one file. If an error occurs, parsing stops and the returned *Template is nil.

When parsing multiple files with the same name in different directories, the last one mentioned will be the one that results. For instance, ParseFiles("a/foo", "b/foo") stores "b/foo" as the template named "foo", while "a/foo" is unavailable.

func ParseGlob

func ParseGlob(pattern string) (*Template, error)

ParseGlob creates a new Template and parses the template definitions from the files identified by the pattern. The files are matched according to the semantics of filepath.Match, and the pattern must match at least one file. The returned template will have the (base) name and (parsed) contents of the first file matched by the pattern. ParseGlob is equivalent to calling ParseFiles with the list of files matched by the pattern.

When parsing multiple files with the same name in different directories, the last one mentioned will be the one that results.

func (*Template) AddParseTree

func (t *Template) AddParseTree(name string, tree *parse.Tree) (*Template, error)

AddParseTree associates the argument parse tree with the template t, giving it the specified name. If the template has not been defined, this tree becomes its definition. If it has been defined and already has that name, the existing definition is replaced; otherwise a new template is created, defined, and returned.

func (*Template) Clone

func (t *Template) Clone() (*Template, error)

Clone returns a duplicate of the template, including all associated templates. The actual representation is not copied, but the name space of associated templates is, so further calls to Parse in the copy will add templates to the copy but not to the original. Clone can be used to prepare common templates and use them with variant definitions for other templates by adding the variants after the clone is made.

func (*Template) DefinedTemplates

func (t *Template) DefinedTemplates() string

DefinedTemplates returns a string listing the defined templates, prefixed by the string "; defined templates are: ". If there are none, it returns the empty string. Used to generate an error message.

func (*Template) Delims

func (t *Template) Delims(left, right string) *Template

Delims sets the action delimiters to the specified strings, to be used in subsequent calls to Parse, ParseFiles, or ParseGlob. Nested template definitions will inherit the settings. An empty delimiter stands for the corresponding default: {{ or }}. The return value is the template, so calls can be chained.

func (*Template) Execute

func (t *Template) Execute(w io.Writer, data interface{}) error

Execute applies a parsed template to the specified data object, and writes the output to w. If an error occurs executing the template or writing its output, execution stops, but partial results may already have been written to the output writer. A template may be executed safely in parallel, although if parallel executions share a Writer the output may be interleaved.

If data is a reflect.Value, the template applies to the concrete value that the reflect.Value holds, as in fmt.Print.

func (*Template) ExecuteTemplate

func (t *Template) ExecuteTemplate(w io.Writer, name string, data interface{}) error

ExecuteTemplate applies the template associated with t that has the given name to the specified data object and writes the output to w. If an error occurs executing the template or writing its output, execution stops, but partial results may already have been written to the output writer. A template may be executed safely in parallel, although if parallel executions share a Writer the output may be interleaved.

func (*Template) Funcs

func (t *Template) Funcs(funcMap FuncMap) *Template

Funcs adds the elements of the argument map to the template's function map. It must be called before the template is parsed. It panics if a value in the map is not a function with appropriate return type or if the name cannot be used syntactically as a function in a template. It is legal to overwrite elements of the map. The return value is the template, so calls can be chained.

func (*Template) Lookup

func (t *Template) Lookup(name string) *Template

Lookup returns the template with the given name that is associated with t. It returns nil if there is no such template or the template has no definition.

func (*Template) Name

func (t *Template) Name() string

Name returns the name of the template.

func (*Template) New

func (t *Template) New(name string) *Template

New allocates a new, undefined template associated with the given one and with the same delimiters. The association, which is transitive, allows one template to invoke another with a {{template}} action.

Because associated templates share underlying data, template construction cannot be done safely in parallel. Once the templates are constructed, they can be executed in parallel.

func (*Template) Option

func (t *Template) Option(opt ...string) *Template

Option sets options for the template. Options are described by strings, either a simple string or "key=value". There can be at most one equals sign in an option string. If the option string is unrecognized or otherwise invalid, Option panics.

This package does not define any options, the only options supported are those listed in https://golang.org/pkg/text/template#Template.Option.

func (*Template) Parse

func (t *Template) Parse(text string) (*Template, error)

Parse parses text as a template body for t. Named template definitions ({{define ...}} or {{block ...}} statements) in text define additional templates associated with t and are removed from the definition of t itself.

Templates can be redefined in successive calls to Parse. A template definition with a body containing only white space and comments is considered empty and will not replace an existing template's body. This allows using Parse to add new named template definitions without overwriting the main template body.

func (*Template) ParseFS

func (t *Template) ParseFS(fsys fs.FS, patterns ...string) (*Template, error)

ParseFS is like ParseFiles or ParseGlob but reads from the file system fsys instead of the host operating system's file system. It accepts a list of glob patterns. (Note that most file names serve as glob patterns matching only themselves.)

func (*Template) ParseFiles

func (t *Template) ParseFiles(filenames ...string) (*Template, error)

ParseFiles parses the named files and associates the resulting templates with t. If an error occurs, parsing stops and the returned template is nil; otherwise it is t. There must be at least one file. Since the templates created by ParseFiles are named by the base names of the argument files, t should usually have the name of one of the (base) names of the files. If it does not, depending on t's contents before calling ParseFiles, t.Execute may fail. In that case use t.ExecuteTemplate to execute a valid template.

When parsing multiple files with the same name in different directories, the last one mentioned will be the one that results.

func (*Template) ParseGlob

func (t *Template) ParseGlob(pattern string) (*Template, error)

ParseGlob parses the template definitions in the files identified by the pattern and associates the resulting templates with t. The files are matched according to the semantics of filepath.Match, and the pattern must match at least one file. ParseGlob is equivalent to calling t.ParseFiles with the list of files matched by the pattern.

When parsing multiple files with the same name in different directories, the last one mentioned will be the one that results.

func (*Template) Templates

func (t *Template) Templates() []*Template

Templates returns a slice of defined templates associated with t.

Jump to

Keyboard shortcuts

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