Comments (4)
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.
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.
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.
@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)
- Exclude newline sql comments (within query body) from the generated go function comments
- Args in mysql ORDER BY not respected
- Generated `Params` don't allow nullable values when `COALESCE` is used HOT 1
- go/sqlite: integer primary keys are inferred as nullable when declared separately
- go/sqlite: SUM of INTEGER field has inferred type NullFloat64
- Cannot embed empty row into struct HOT 1
- Proposal: Add option to emit `//go:generate` annotation HOT 2
- CAST() produces correct go type for postgres but not mysql
- sqlc.embed handle CTE
- MySQL `JSON_TABLE` not supported HOT 2
- SQLite UPDATE FROM statements not supported
- SQLite: error parsing schema with `UNIQUE`
- sqlc generates empty imports statement, e.g. "import ()"
- custom struct tags are not emmited HOT 1
- Am I missing how to model one to many relationships with sqlc.embed?
- Named parameters not recognized without space before @ char
- Overrides for unsigned types
- Scanning of composite types -- is it possible? HOT 1
- Support `sql.Null` HOT 1
- No binaries for v1.25.0 HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from sqlc.