wherein

package
v0.6.1 Latest Latest
Warning

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

Go to latest
Published: Apr 28, 2019 License: MIT Imports: 10 Imported by: 0

Documentation

Overview

Package wherein expands SQL statements that have placeholders that can accept slices of arguments. This is most commonly useful for SQL statements that might look something like

SELECT * FROM table_name WHERE column_name IN (?)

If the argument associated with the placeholder is a slice containing (say) three values, then the SQL would be expanded to

SELECT * FROM table_name where column_name in (?,?,?)

See the example for more details.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Expand

func Expand(query string, args []interface{}) (newQuery string, newArgs []interface{}, err error)

Expand takes an SQL query and associated arguments and expands out any arguments that are a slice of values. Returns the new, expanded SQL query with arguments that have been flattened into a slice of scalar argument values.

If args contains only scalar values, then query and args are returned unchanged.

Example
// Using MySQL/SQLite style positional placeholders
{
	sql := "SELECT * FROM table_name WHERE column1 IN (?) and column2 = ?"
	args := []interface{}{
		[]int{101, 102, 103},
		"abc",
	}
	newSQL, newArgs, err := Expand(sql, args)
	if err != nil {
		fmt.Print(err)
		return
	}
	fmt.Printf("sql = %s\nargs = %v\n\n", newSQL, newArgs)
}

// Using PostgreSQL style numbered placeholders
{
	sql := "SELECT * FROM table_name WHERE column1 IN ($1) and column2 = $2"
	args := []interface{}{
		[]int{101, 102, 103},
		"abc",
	}
	newSQL, newArgs, err := Expand(sql, args)
	if err != nil {
		fmt.Print(err)
		return
	}
	fmt.Printf("sql = %s\nargs = %v\n\n", newSQL, newArgs)
}

// Using MySQL/SQLite style numbered placeholders
{
	sql := "SELECT * FROM table_name WHERE column1 IN (?2) and column2 IN (?1)"
	args := []interface{}{
		[]int{101, 102, 103},
		[]string{"abc", "def", "ghi"},
	}
	newSQL, newArgs, err := Expand(sql, args)
	if err != nil {
		fmt.Print(err)
		return
	}
	fmt.Printf("sql = %s\nargs = %v\n\n", newSQL, newArgs)
}
Output:

sql = SELECT * FROM table_name WHERE column1 IN (?,?,?) and column2 = ?
args = [101 102 103 abc]

sql = SELECT * FROM table_name WHERE column1 IN ($1,$2,$3) and column2 = $4
args = [101 102 103 abc]

sql = SELECT * FROM table_name WHERE column1 IN (?4,?5,?6) and column2 IN (?1,?2,?3)
args = [101 102 103 abc def ghi]

Types

This section is empty.

Jump to

Keyboard shortcuts

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