Support generate sql for postgres
In Postgres substitutions params look like $1. In this library only "?"
@miramir hi, what kind of library do you use to interact with Postgres? Some ORM ?
I use in pgx.
@miramir The library is agnostic for driver so default placeholders for SQL parameters is ? (question symbol).
So, you can use something like this func for your purpose:
package main
import (
"fmt"
"strconv"
"strings"
)
const (
UNKNOWN = iota
QUESTION
DOLLAR
NAMED
AT
)
// Rebind a query from the default bindtype (QUESTION) to the target bindtype.
func Rebind(bindType int, query string) string {
switch bindType {
case QUESTION, UNKNOWN:
return query
}
// Add space enough for 10 params before we have to allocate
rqb := make([]byte, 0, len(query)+10)
var i, j int
for i = strings.Index(query, "?"); i != -1; i = strings.Index(query, "?") {
rqb = append(rqb, query[:i]...)
switch bindType {
case DOLLAR:
rqb = append(rqb, '$')
case NAMED:
rqb = append(rqb, ':', 'a', 'r', 'g')
case AT:
rqb = append(rqb, '@', 'p')
}
j++
rqb = strconv.AppendInt(rqb, int64(j), 10)
query = query[i+1:]
}
return string(append(rqb, query...))
}
func main() {
fmt.Println(Rebind(DOLLAR, "SELECT * FROM table WHERE id = ? AND uid = ?"))
}
This func is taken from the sqlx library.
The problem with this solution is: what if I want to find a string in the database with the symbol '?' ?
There was even an idea to take only url parsing from your library , and give the query construction https://pkg.go.dev/github.com/huandu/go-sqlbuilder . But for now, I'm just wasting time tormented by perfectionism. :)
The problem with this solution is: what if I want to find a string in the database with the symbol '?' ?
Then you've to add feature to escape '?' in this func.
There was even an idea to take only url parsing from your library , and give the query construction https://pkg.go.dev/github.com/huandu/go-sqlbuilder . But for now, I'm just wasting time tormented by perfectionism. :)
Good idea, but it's not necessary for my purposes. But you can fork repo and implement your dreams ;-)