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)
- Generate fails for UPDATE ... FROM (...) with subquery HOT 1
- Query "SELECT * FROM unnest(..)" has wrong generated code
- Determine which indices are needed for efficient execution of a query HOT 5
- Interpret schema migrations numerically
- Temp table created using schema.sql is not insertable. HOT 3
- Incorrect code gen without
- Basic usage - relation "x" does not exist HOT 2
- underscore is not properly supported HOT 1
- Fails if structure is mysqldump containing rocksdb_has_p_s_session_variables
- Missing columns not being detected
- Error "not enough args to execute query" on complex select query.
- Does it support logging of executed SQL? HOT 1
- Generate in-memory mocked implementation of the Querier interface HOT 2
- Renaming a materialized view causes `sqlc generate` to fail
- sql\queries\users.sql:1:1: relation "users" does not exist HOT 2
- NULL JSON field fails to Scan into json.RawMessage
- Views models do not get updated when base tables are altered
- sqlite ALTER TABLE ADD COLUMN without type name panics HOT 2
- wrong type for params in tuple
- COALESCE doesn't appear to work within a CTE
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.