rest-query-parser icon indicating copy to clipboard operation
rest-query-parser copied to clipboard

Support generate sql for postgres

Open miramir opened this issue 4 years ago • 6 comments

In Postgres substitutions params look like $1. In this library only "?"

miramir avatar Jul 17 '21 04:07 miramir

@miramir hi, what kind of library do you use to interact with Postgres? Some ORM ?

timsolov avatar Jul 19 '21 07:07 timsolov

I use in pgx.

miramir avatar Jul 19 '21 07:07 miramir

@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.

timsolov avatar Jul 19 '21 12:07 timsolov

The problem with this solution is: what if I want to find a string in the database with the symbol '?' ?

miramir avatar Jul 22 '21 03:07 miramir

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. :)

miramir avatar Jul 22 '21 03:07 miramir

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 ;-)

timsolov avatar Jul 29 '21 10:07 timsolov