sqlparams

package module
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Jan 3, 2022 License: BSD-3-Clause Imports: 8 Imported by: 1

README

sqlparams for Golang

Install

go get github.com/kaibox-git/sqlparams

Usage

The only Inline(query, params ...) method returns a 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 Inline

func Inline(sql string, avars ...interface{}) string

Types

This section is empty.

Jump to

Keyboard shortcuts

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