Giter Site home page Giter Site logo

make it less pg dependant about sqlc HOT 4 CLOSED

kyleconroy avatar kyleconroy commented on May 3, 2024
make it less pg dependant

from sqlc.

Comments (4)

eullerpereira94 avatar eullerpereira94 commented on May 3, 2024

With an update to Go 1.13, the ties to pg will be even smaller, but right now, pq.Array is too convenient so substitute.
But since this is a code generation tool, I think that creating array to slice scanner types is reasonable task.But I can't think of the right approach to do it.
One way would be identify every instance of where arrays are used in the creation scripts and generate package-wide scanner types to be used in every piece of code that an array would be needed. The good side is that the code would be clean and elegant. The downside is that I think it would greatly increases the complexity of the tool.
Another would be generate the scanners on demand. Whenever a array would appear in the script, a scanner type with its methods would be prepended to code that is currently generating. The good side is that I think it wouldn't add too much complexity to the tool. But the downside is that the code would be ugly (but this is a personal opinion).

from sqlc.

mh-cbon avatar mh-cbon commented on May 3, 2024

I did not realize pq.Array was doing so much... this needs some deeper inspection

two examples of differences i can think of
https://stackoverflow.com/a/45352902/4466350
https://stackoverflow.com/a/34627688/4466350

from sqlc.

eullerpereira94 avatar eullerpereira94 commented on May 3, 2024

The solution for arrays indeed works, but it is for a specific case that was already covered by a previous issue (refer to #77). I think a more general and idiomatic approach is to make full use of sql.Scanner and the driver.Valuer interfaces. I think this piece of code could be something that would be useful:

package models

import (
	"database/sql"
	"database/sql/driver"
	"encoding/csv"
	"errors"
	"fmt"
	"regexp"
	"strings"
)

type StringSlice []string

// StringSlice is a slice of strings.
type StringSlice []string

// quoteEscapeRegex is the regex to match escaped characters in a string.
var quoteEscapeRegex = regexp.MustCompile(`([^\\]([\\]{2})*)\\"`)

// Scan satisfies the sql.Scanner interface for StringSlice.
func (ss *StringSlice) Scan(src interface{}) error {
	buf, ok := src.([]byte)
	if !ok {
		return errors.New("invalid StringSlice")
	}

	// change quote escapes for csv parser
	str := quoteEscapeRegex.ReplaceAllString(string(buf), `$1""`)
	str = strings.Replace(str, `\\`, `\`, -1)

	// remove braces
	str = str[1 : len(str)-1]

	// bail if only one
	if len(str) == 0 {
		*ss = StringSlice([]string{})
		return nil
	}

	// parse with csv reader
	cr := csv.NewReader(strings.NewReader(str))
	slice, err := cr.Read()
	if err != nil {
		fmt.Printf("exiting!: %v\n", err)
		return err
	}

	*ss = StringSlice(slice)

	return nil
}

// Value satisfies the driver.Valuer interface for StringSlice.
func (ss StringSlice) Value() (driver.Value, error) {
	v := make([]string, len(ss))
	for i, s := range ss {
		v[i] = `"` + strings.Replace(strings.Replace(s, `\`, `\\\`, -1), `"`, `\"`, -1) + `"`
	}
	return "{" + strings.Join(v, ",") + "}", nil
}

Note: this is a straight copy of some of the code generated by the xo package. But this code works and can be refactored for any of the basic types in Go. It can be used either as field in the generated structs and as a parameter in the db.Query* methods.

If we include scanner types for the ints, the floats, string, bool, Time and interface{} in the generated db.go or models.go file, and use them to substitute each instance of an Postgres array, then the dependence to the pq package would be eliminated in Go 1.13 onwards. Any version below that would be impossible to not have any dependence to the pq package.

from sqlc.

kyleconroy avatar kyleconroy commented on May 3, 2024

@mh-cohen I understand the appeal of having sqlc work with multiple databases. However, the current implementation is built on the top of the PostgreSQL query parser (https://github.com/lfittl/pg_query_go). If there is a Go package containing the SQL parser for your database of choice, I can add it to sqlc.

from sqlc.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.