sqlparams for Golang

Method Fill(query, params…) returns a query with embedded params, so you can execute it in database console, write to log or send by email.

MySQL example:

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

It will print:

    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}
    fullsql := sqlparams.Fill(query, params...)
    println(fullsql)

It will print:

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

Supported named params:

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

Supported struct (may be a pointer):

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

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

    query := `SELECT name FROM table WHERE code=:code AND prefix=:prefix`
    p := struct{
        Code int
        Pref string `db:"prefix"`
    }{
        Code: 5,
        Pref: `some`,
    }
    fullsql := sqlparams.Fill(query, p)

See more cases in sqlmaker_test.go

GitHub

View Github