sqltmpl

package module
v0.0.3 Latest Latest
Warning

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

Go to latest
Published: Sep 9, 2025 License: MIT Imports: 7 Imported by: 1

README

SQL-Template

A template engine for SQL in Golang.

Example

import (
    "github.com/deadblue/sqltmpl"
)

func main() {
    tmpl := sqltmpl.MustParse[string](
        "SELECT * FROM table WHERE id = {{ . }}",
    )
    var query string
    var args []any

    query, args = tmpl.MustRender("a")
    // query: SELECT * FROM table WHERE id = ?
    // args: ["a"]

    query, args = tmpl.MustRender("b")
    // query: SELECT * FROM table WHERE id = ?
    // args: ["b"]
}

Specification

The SQL template follows the specification of standard package "text/template" with some limitations in below:

  • Function/Method calling is unsupported.
  • Chained pipelines is unsupported.
  • Variable definition is unsupported.

License

MIT

Documentation

Overview

Example
package main

import (
	"fmt"

	"github.com/deadblue/sqltmpl"
)

type Params struct {
	Ids  []int
	Type string
}

func main() {
	tmpl := sqltmpl.MustParse[Params](
		"SELECT a, b, c FROM table WHERE id IN (",
		"{{- range $index, $elem := .Ids -}}",
		"{{ if $index }}, {{ end }}{{ $elem }}",
		"{{- end -}}",
		") AND type = {{ .Type }}",
	)

	query, args := tmpl.MustRender(Params{
		Ids:  []int{1, 2, 3},
		Type: "foobar",
	})
	fmt.Printf("Query: %s\n", query)
	fmt.Printf("Arguments: %v", args)

}
Output:

Query: SELECT a, b, c FROM table WHERE id IN (?, ?, ?) AND type = ?
Arguments: [1 2 3 foobar]

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Template

type Template[P any] interface {
	// Render renders template with given params.
	//
	// The result is rendered query statement, corresponding SQL arguments, and
	// an error that will be not-nil when rendering failed.
	Render(params P) (query string, args []any, err error)

	// MustRender is like [Render] but panics when rendering failed.
	MustRender(params P) (query string, args []any)
}

func MustParse

func MustParse[P any](line ...string) Template[P]

MustParse is like Parse but panics when parsing failed.

func Parse

func Parse[P any](line ...string) (tmpl Template[P], err error)

Parse parses SQL template and returns a Template object if successful.

Jump to

Keyboard shortcuts

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