Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion internal/cmd/generate.go
Original file line number Diff line number Diff line change
Expand Up @@ -343,7 +343,8 @@ func codegen(ctx context.Context, combo config.CombinedSettings, sql OutputPair,

case sql.Gen.Go != nil:
out = combo.Go.Out
handler = ext.HandleFunc(golang.Generate)
generator := golang.Generator{TypeMapper: result.GoTypeMapper}
handler = ext.HandleFunc(generator.Generate)
opts, err := json.Marshal(sql.Gen.Go)
if err != nil {
return "", nil, fmt.Errorf("opts marshal failed: %w", err)
Expand Down
5 changes: 2 additions & 3 deletions internal/codegen/golang/driver.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,8 @@ func usesPqArrays(engine string, driver opts.SQLDriver) bool {
return !driver.IsPGX()
}

// usesDriverTypes reports whether the engine is one whose mapper reads the
// type expression and draws types from its driver's packages, the ones in
// driverTypes. These engines generate code for database/sql only.
// usesDriverTypes identifies database/sql bindings that scan arrays directly
// instead of using lib/pq's wrappers.
func usesDriverTypes(engine string) bool {
switch engine {
case engineClickHouse, engineDuckDB, engineGoogleSQL, engineMSSQL:
Expand Down
10 changes: 10 additions & 0 deletions internal/codegen/golang/gen.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import (
"github.com/sqlc-dev/sqlc/internal/codegen/golang/opts"
"github.com/sqlc-dev/sqlc/internal/codegen/sdk"
"github.com/sqlc-dev/sqlc/internal/metadata"
sqlopts "github.com/sqlc-dev/sqlc/internal/opts"
"github.com/sqlc-dev/sqlc/internal/plugin"
)

Expand Down Expand Up @@ -110,11 +111,20 @@ func (t *tmplCtx) codegenQueryRetval(q Query) (string, error) {
}
}

type Generator struct {
TypeMapper sqlopts.GoTypeMapper
}

func Generate(ctx context.Context, req *plugin.GenerateRequest) (*plugin.GenerateResponse, error) {
return (Generator{}).Generate(ctx, req)
}

func (g Generator) Generate(ctx context.Context, req *plugin.GenerateRequest) (*plugin.GenerateResponse, error) {
options, err := opts.Parse(req)
if err != nil {
return nil, err
}
options.TypeMapper = g.TypeMapper

if err := opts.ValidateOpts(options); err != nil {
return nil, err
Expand Down
13 changes: 10 additions & 3 deletions internal/codegen/golang/go_type.go
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,16 @@ func goInnerType(req *plugin.GenerateRequest, options *opts.Options, col *plugin
}
}

// TODO: Extend the engine interface to handle types
if options.TypeMapper != nil {
t, nullable := columnType(col)
mapped := options.TypeMapper.GoType(t, param)
typ := mapped.Type
if mapped.NullableType != "" {
typ = nullableGoType(options, nullable, typ, mapped.NullableType)
}
return typ, mapped.Complete
}

switch req.Settings.Engine {
case engineMySQL:
return mysqlType(req, options, col), false
Expand All @@ -109,8 +118,6 @@ func goInnerType(req *plugin.GenerateRequest, options *opts.Options, col *plugin
return duckdbType(req, options, col, param), true
case engineGoogleSQL:
return googlesqlType(req, options, col), true
case engineMSSQL:
return mssqlType(req, options, col), true
default:
return "any", false
}
Expand Down
13 changes: 8 additions & 5 deletions internal/codegen/golang/imports.go
Original file line number Diff line number Diff line change
Expand Up @@ -157,13 +157,12 @@ var stdlibTypes = map[string]string{
"big.Rat": "math/big",
}

// driverTypes are the packages the ClickHouse, DuckDB, Spanner and SQL
// Server mappers draw types from, by the qualifier those types carry.
// driverTypes are the packages the legacy mappers draw types from, by the
// qualifier those types carry.
var driverTypes = map[string]string{
"civil.": "cloud.google.com/go/civil",
"decimal.": "github.com/shopspring/decimal",
"duckdb.": "github.com/duckdb/duckdb-go/v2",
"mssql.": "github.com/microsoft/go-mssqldb",
"orb.": "github.com/paulmach/orb",
"spanner.": "cloud.google.com/go/spanner",
}
Expand Down Expand Up @@ -242,8 +241,12 @@ func buildImports(options *opts.Options, engine string, queries []Query, uses fu
// them, and an override whose type carries the same qualifier brings
// its own import: a PostgreSQL numeric overridden to another package's
// decimal.Decimal must not pull in shopspring's as well.
if usesDriverTypes(engine) {
for qualifier, path := range driverTypes {
typeImports := driverTypes
if options.TypeMapper != nil {
typeImports = options.TypeMapper.GoTypeImports()
}
if options.TypeMapper != nil || usesDriverTypes(engine) {
for qualifier, path := range typeImports {
if uses(qualifier) && !overrideHasQualifier(overrideTypes, qualifier) {
pkg[ImportSpec{Path: path}] = struct{}{}
}
Expand Down
65 changes: 0 additions & 65 deletions internal/codegen/golang/mssql_type.go

This file was deleted.

4 changes: 3 additions & 1 deletion internal/codegen/golang/opts/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"maps"
"path/filepath"

sqlopts "github.com/sqlc-dev/sqlc/internal/opts"
"github.com/sqlc-dev/sqlc/internal/plugin"
)

Expand Down Expand Up @@ -52,7 +53,8 @@ type Options struct {
BuildTags string `json:"build_tags,omitempty" yaml:"build_tags"`
Initialisms *[]string `json:"initialisms,omitempty" yaml:"initialisms"`

InitialismsMap map[string]struct{} `json:"-" yaml:"-"`
InitialismsMap map[string]struct{} `json:"-" yaml:"-"`
TypeMapper sqlopts.GoTypeMapper `json:"-" yaml:"-"`
}

type GlobalOptions struct {
Expand Down
25 changes: 23 additions & 2 deletions internal/codegen/golang/result.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import (
"fmt"
"sort"
"strings"
"unicode"
"unicode/utf8"

"github.com/sqlc-dev/sqlc/internal/codegen/golang/opts"
"github.com/sqlc-dev/sqlc/internal/codegen/sdk"
Expand Down Expand Up @@ -164,6 +166,26 @@ func columnName(c *plugin.Column, pos int) string {
return fmt.Sprintf("column_%d", pos+1)
}

// goIdent makes a column name a Go identifier for the variable a single
// column is scanned into: a database may name a column anything, as SQL
// Server names a FOR JSON result JSON_F52E2B61-18A1-11d1-B105-00805F49916B
// and a pivoted one 2023.
func goIdent(name string) string {
name = strings.Map(func(r rune) rune {
if r == '_' || unicode.IsLetter(r) || unicode.IsDigit(r) {
return r
}
return '_'
}, name)
if strings.Trim(name, "_") == "" {
return "column_1"
}
if r, _ := utf8.DecodeRuneInString(name); unicode.IsDigit(r) {
name = "_" + name
}
return name
}

func paramName(p *plugin.Parameter) string {
if p.Column.Name != "" {
return argName(p.Column.Name)
Expand Down Expand Up @@ -282,8 +304,7 @@ func buildQueries(req *plugin.GenerateRequest, options *opts.Options, enums []En

if len(query.Columns) == 1 && query.Columns[0].EmbedTable == nil {
c := query.Columns[0]
name := columnName(c, 0)
name = strings.Replace(name, "$", "_", -1)
name := goIdent(columnName(c, 0))
retName := escape(name)
// For :one queries the scan destination lives in the same scope as
// the query parameters, so reusing a parameter's name would cause
Expand Down
6 changes: 4 additions & 2 deletions internal/compiler/compile.go
Original file line number Diff line number Diff line change
Expand Up @@ -240,9 +240,11 @@ func (c *Compiler) parseQueries(o opts.Parser) (*Result, error) {
return nil, fmt.Errorf("no queries contained in paths %s", strings.Join(c.conf.Queries, ","))
}

typeMapper, _ := c.parser.(opts.GoTypeMapper)
return &Result{
Catalog: c.catalog,
Queries: q,
GoTypeMapper: typeMapper,
Catalog: c.catalog,
Queries: q,
}, nil
}

Expand Down
6 changes: 4 additions & 2 deletions internal/compiler/result.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
package compiler

import (
"github.com/sqlc-dev/sqlc/internal/opts"
"github.com/sqlc-dev/sqlc/internal/sql/catalog"
)

type Result struct {
Catalog *catalog.Catalog
Queries []*Query
Catalog *catalog.Catalog
Queries []*Query
GoTypeMapper opts.GoTypeMapper
}
11 changes: 6 additions & 5 deletions internal/endtoend/testdata/core_types/mssql/go/models.go

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

13 changes: 8 additions & 5 deletions internal/endtoend/testdata/core_types/mssql/go/query.sql.go

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

Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"contexts": ["base"]
}
31 changes: 31 additions & 0 deletions internal/endtoend/testdata/mssql_go_type_mapping/mssql/go/db.go

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.

Loading