sqlparams

package module
v1.0.8 Latest Latest
Warning

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

Go to latest
Published: Apr 9, 2023 License: MIT Imports: 9 Imported by: 1

README

sqlparams for Golang

Install

go get github.com/kaibox-git/sqlparams

Usage

The only method Inline(query, params...) returns sql query with inline parameters, so you can execute it in the database console or log it. Supports pointer and sql.Null... parameter types.

MySQL example:

query := `SELECT name FROM table WHERE code=? AND prefix=?`
code := 5
prefix := `some`
sql := sqlparams.Inline(query, code, prefix)
println(sql)

Output:

SELECT name FROM table WHERE code=5 AND prefix='some'

PostgreSQL example:

query := `SELECT name FROM table WHERE code=$1 AND prefix=$2`
code := 5
prefix := `some`
params := []interface{}{code, prefix}
sql := sqlparams.Inline(query, params...)
println(sql)

Output:

SELECT name FROM table WHERE code=5 AND prefix='some'

Named parameters are supported:

query := `SELECT name FROM table WHERE code=:code AND prefix=:prefix`
m := map[string]interface{}{
        `code`: 5,
        `prefix`: `some`,
}
sql := sqlparams.Inline(query, m)

Struct (could be a pointer) is supported:

query := `SELECT name FROM table WHERE code=:code AND prefix=:prefix`
p := struct{
        Code int
        Prefix string
}{
        Code: 5,
        Prefix: `some`,
}
sql := sqlparams.Inline(query, &p)

It takes into account the tag 'db' of the struct if using sqlx:

query := `SELECT name FROM table WHERE code=:code AND dep_id=:dep_id`
p := struct{
        Code int
        DepId int `db:"dep_id"`
}{
        Code: 5,
        DepId: 2,
}
sql := sqlparams.Inline(query, p)

See more cases in sqlmaker_test.go.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func In added in v1.0.4

func In(query string, args ...any) (string, []any, error)

In expands slice values in args, returning the modified query string and a new arg list that can be executed by a database. The `query` should use the `?` bindVar. The return value uses the `?` bindVar.

func Inline

func Inline(sql string, avars ...any) string

func Rebind added in v1.0.6

func Rebind(query string) string

Types

This section is empty.

Jump to

Keyboard shortcuts

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