Skip to content

Commit

Permalink
feat(Go):Add query_parameter_limit conf to codegen
Browse files Browse the repository at this point in the history
  • Loading branch information
go-mez committed Apr 18, 2022
1 parent 6e45a9f commit 04ab48f
Show file tree
Hide file tree
Showing 24 changed files with 627 additions and 107 deletions.
3 changes: 3 additions & 0 deletions docs/reference/config.md
Expand Up @@ -24,6 +24,7 @@ packages:
output_db_file_name: "db.go"
output_models_file_name: "models.go"
output_querier_file_name: "querier.go"
query_parameter_limit: 2
```

Each package document has the following keys:
Expand Down Expand Up @@ -70,6 +71,8 @@ Each package document has the following keys:
- Customize the name of the querier file. Defaults to `querier.go`.
- `output_files_suffix`:
- If specified the suffix will be added to the name of the generated files.
- `query_parameter_limit`:
- Positional arguments that will be generated in go functions (>= `1` or `-1`). To always emit a parameter struct, you would need to set it to `-1`. `0` is invalid. Defaults to `1`.

## Type Overrides

Expand Down
1 change: 1 addition & 0 deletions internal/cmd/shim.go
Expand Up @@ -92,6 +92,7 @@ func pluginGoCode(s config.SQLGo) *plugin.GoCode {
OutputModelsFileName: s.OutputModelsFileName,
OutputQuerierFileName: s.OutputQuerierFileName,
OutputFilesSuffix: s.OutputFilesSuffix,
QueryParameterLimit: *s.QueryParameterLimit,
}
}

Expand Down
9 changes: 9 additions & 0 deletions internal/codegen/golang/field.go
Expand Up @@ -77,3 +77,12 @@ func toCamelInitCase(name string, initUpper bool) string {
}
return out
}

func toLowerCase(str string) string {
var b strings.Builder

b.WriteString(strings.ToLower(string(str[0])))
b.WriteString(str[1:])

return b.String()
}
12 changes: 12 additions & 0 deletions internal/codegen/golang/query.go
Expand Up @@ -37,6 +37,16 @@ func (v QueryValue) Pair() string {
if v.isEmpty() {
return ""
}

var out []string
if !v.EmitStruct() && v.IsStruct() {
for _, f := range v.Struct.Fields {
out = append(out, toLowerCase(f.Name)+" "+f.Type)
}

return strings.Join(out, ",")
}

return v.Name + " " + v.DefineType()
}

Expand Down Expand Up @@ -102,6 +112,8 @@ func (v QueryValue) Params() string {
for _, f := range v.Struct.Fields {
if strings.HasPrefix(f.Type, "[]") && f.Type != "[]byte" && v.SQLPackage != SQLPackagePGX {
out = append(out, "pq.Array("+v.Name+"."+f.Name+")")
} else if !v.EmitStruct() && v.IsStruct() {
out = append(out, toLowerCase(f.Name))
} else {
out = append(out, v.Name+"."+f.Name)
}
Expand Down
10 changes: 8 additions & 2 deletions internal/codegen/golang/result.go
Expand Up @@ -157,14 +157,16 @@ func buildQueries(req *plugin.CodeGenRequest, structs []Struct) ([]Query, error)
}
sqlpkg := SQLPackageFromString(req.Settings.Go.SqlPackage)

if len(query.Params) == 1 {
qpl := int(req.Settings.Go.QueryParameterLimit)

if len(query.Params) == 1 && qpl != -1 {
p := query.Params[0]
gq.Arg = QueryValue{
Name: paramName(p),
Typ: goType(req, p.Column),
SQLPackage: sqlpkg,
}
} else if len(query.Params) > 1 {
} else if len(query.Params) >= 1 && (qpl >= 1 || qpl == -1) {
var cols []goColumn
for _, p := range query.Params {
cols = append(cols, goColumn{
Expand All @@ -183,6 +185,10 @@ func buildQueries(req *plugin.CodeGenRequest, structs []Struct) ([]Query, error)
SQLPackage: sqlpkg,
EmitPointer: req.Settings.Go.EmitParamsStructPointers,
}

if len(query.Params) <= qpl {
gq.Arg.Emit = false
}
}

if len(query.Columns) == 1 {
Expand Down
2 changes: 2 additions & 0 deletions internal/config/config.go
Expand Up @@ -137,6 +137,7 @@ type SQLGo struct {
OutputModelsFileName string `json:"output_models_file_name,omitempty" yaml:"output_models_file_name"`
OutputQuerierFileName string `json:"output_querier_file_name,omitempty" yaml:"output_querier_file_name"`
OutputFilesSuffix string `json:"output_files_suffix,omitempty" yaml:"output_files_suffix"`
QueryParameterLimit *int32 `json:"query_parameter_limit,omitempty" yaml:"query_parameter_limit"`
}

type SQLKotlin struct {
Expand Down Expand Up @@ -308,6 +309,7 @@ var ErrNoPackageName = errors.New("missing package name")
var ErrNoPackagePath = errors.New("missing package path")
var ErrNoOutPath = errors.New("no output path")
var ErrNoQuerierType = errors.New("no querier emit type enabled")
var ErrInvalidQueryParameterLimit = errors.New("invalid query parameter limit")

func ParseConfig(rd io.Reader) (Config, error) {
var buf bytes.Buffer
Expand Down
13 changes: 13 additions & 0 deletions internal/config/v_one.go
Expand Up @@ -40,6 +40,7 @@ type v1PackageSettings struct {
OutputQuerierFileName string `json:"output_querier_file_name,omitempty" yaml:"output_querier_file_name"`
OutputFilesSuffix string `json:"output_files_suffix,omitempty" yaml:"output_files_suffix"`
StrictFunctionChecks bool `json:"strict_function_checks" yaml:"strict_function_checks"`
QueryParameterLimit *int32 `json:"query_parameter_limit,omitempty" yaml:"query_parameter_limit"`
}

func v1ParseConfig(rd io.Reader) (Config, error) {
Expand Down Expand Up @@ -71,6 +72,17 @@ func v1ParseConfig(rd io.Reader) (Config, error) {
if settings.Packages[j].Path == "" {
return config, ErrNoPackagePath
}

if settings.Packages[j].QueryParameterLimit != nil && (*settings.Packages[j].QueryParameterLimit < -1 ||
*settings.Packages[j].QueryParameterLimit == 0) {
return config, ErrInvalidQueryParameterLimit
}

if settings.Packages[j].QueryParameterLimit == nil {
settings.Packages[j].QueryParameterLimit = new(int32)
*settings.Packages[j].QueryParameterLimit = 1
}

for i := range settings.Packages[j].Overrides {
if err := settings.Packages[j].Overrides[i].Parse(); err != nil {
return config, err
Expand Down Expand Up @@ -135,6 +147,7 @@ func (c *V1GenerateSettings) Translate() Config {
OutputModelsFileName: pkg.OutputModelsFileName,
OutputQuerierFileName: pkg.OutputQuerierFileName,
OutputFilesSuffix: pkg.OutputFilesSuffix,
QueryParameterLimit: pkg.QueryParameterLimit,
},
},
StrictFunctionChecks: pkg.StrictFunctionChecks,
Expand Down
10 changes: 10 additions & 0 deletions internal/config/v_two.go
Expand Up @@ -45,6 +45,16 @@ func v2ParseConfig(rd io.Reader) (Config, error) {
if conf.SQL[j].Gen.Go.Package == "" {
conf.SQL[j].Gen.Go.Package = filepath.Base(conf.SQL[j].Gen.Go.Out)
}

if conf.SQL[j].Gen.Go.QueryParameterLimit != nil && (*conf.SQL[j].Gen.Go.QueryParameterLimit < -1 ||
*conf.SQL[j].Gen.Go.QueryParameterLimit == 0) {
return conf, ErrInvalidQueryParameterLimit
}

if conf.SQL[j].Gen.Go.QueryParameterLimit == nil {
*conf.SQL[j].Gen.Go.QueryParameterLimit = 1
}

for i := range conf.SQL[j].Gen.Go.Overrides {
if err := conf.SQL[j].Gen.Go.Overrides[i].Parse(); err != nil {
return conf, err
Expand Down
@@ -0,0 +1,27 @@
-- Example queries for sqlc
CREATE TABLE authors (
id BIGSERIAL PRIMARY KEY,
name text NOT NULL,
bio text,
country_code CHAR(2) NOT NULL
);

-- name: GetAuthor :one
SELECT * FROM authors
WHERE name = $1 AND country_code = $2 LIMIT 1;

-- name: ListAuthors :many
SELECT * FROM authors
ORDER BY name;

-- name: CreateAuthor :one
INSERT INTO authors (
name, bio, country_code
) VALUES (
$1, $2, $3
)
RETURNING *;

-- name: DeleteAuthor :exec
DELETE FROM authors
WHERE id = $1;
@@ -0,0 +1,14 @@
{
"version": "1",
"packages": [
{
"path": "go",
"engine": "postgresql",
"name": "querytest",
"schema": "query.sql",
"queries": "query.sql",
"query_parameter_limit": 0
}
]
}

@@ -0,0 +1 @@
error parsing sqlc.json: invalid query parameter limit

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

@@ -0,0 +1,27 @@
-- Example queries for sqlc
CREATE TABLE authors (
id BIGSERIAL PRIMARY KEY,
name text NOT NULL,
bio text,
country_code CHAR(2) NOT NULL
);

-- name: GetAuthor :one
SELECT * FROM authors
WHERE name = $1 AND country_code = $2 LIMIT 1;

-- name: ListAuthors :many
SELECT * FROM authors
ORDER BY name;

-- name: CreateAuthor :one
INSERT INTO authors (
name, bio, country_code
) VALUES (
$1, $2, $3
)
RETURNING *;

-- name: DeleteAuthor :exec
DELETE FROM authors
WHERE id = $1;

0 comments on commit 04ab48f

Please sign in to comment.