Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
74 commits
Select commit Hold shift + click to select a range
41babf6
mssql: make the optional side of outer joins nullable
EliSauder Nov 12, 2026
81803a4
mssql: support CROSS APPLY and OUTER APPLY
EliSauder Nov 12, 2026
63e879d
mssql: type TOP and OFFSET/FETCH parameters as bigint
EliSauder Nov 12, 2026
0f54b3d
mssql: pass the datepart of DATEADD and its relatives as a keyword
EliSauder Nov 12, 2026
54cc315
mssql: support recursive common table expressions
EliSauder Nov 12, 2026
b00412c
mssql: support OPENJSON, STRING_SPLIT and GENERATE_SERIES in FROM
EliSauder Nov 12, 2026
53bc773
mssql: type AT TIME ZONE
EliSauder Nov 12, 2026
ebc30aa
mssql: support sqlc.arg, sqlc.narg and sqlc.slice
EliSauder Nov 12, 2026
8ba7824
mssql: support sqlc.embed
EliSauder Nov 12, 2026
bdee10d
core: let set operation branches see the enclosing query
EliSauder Nov 12, 2026
8312412
mssql: support VALUES as a derived table
EliSauder Nov 12, 2026
ea9df4d
mssql: seed common built-in functions
EliSauder Nov 12, 2026
d23c817
mssql: type mixed arithmetic by data type precedence
EliSauder Nov 12, 2026
ae484df
mssql: resolve INSERTED and DELETED in OUTPUT against the target
EliSauder Nov 12, 2026
0143d2c
mssql: type TRY_CAST and TRY_CONVERT as nullable
EliSauder Nov 12, 2026
ac276a8
mssql: type PARSE and TRY_PARSE
EliSauder Nov 12, 2026
e8f1b01
mssql: type @@ROWCOUNT and the other system variables
EliSauder Nov 12, 2026
ee02571
mssql: support PIVOT and UNPIVOT in FROM
EliSauder Nov 12, 2026
7db97f4
mssql: quote expanded identifiers with brackets
EliSauder Nov 12, 2026
c1ad6db
mssql: type ISNULL as nullable only when both arguments are
EliSauder Nov 12, 2026
2e61a8c
mssql: type computed columns by their expression
EliSauder Nov 12, 2026
11a28e1
mssql: report a named query sqlc cannot analyze
EliSauder Nov 12, 2026
e60c401
golang: make a single result column's variable a Go identifier
EliSauder Nov 12, 2026
783c094
mssql: type FOR JSON and FOR XML results
EliSauder Nov 12, 2026
7292623
mssql: support views
EliSauder Nov 12, 2026
4822695
mssql: type set operation columns from every branch
EliSauder Nov 12, 2026
1e9e0bd
golang: read a result variable's first character as a rune
EliSauder Nov 12, 2026
70a7150
golang: expand every use of a named slice
EliSauder Nov 12, 2026
bb4e527
mssql: expand a star qualified with double quotes
EliSauder Nov 12, 2026
89088c5
mssql: embed a table only when the star is all of its columns
EliSauder Nov 12, 2026
ca3c8e0
core: keep a WITH clause's names out of the enclosing query
EliSauder Nov 12, 2026
2256c3f
mssql: leave bracketed identifiers alone when preprocessing
EliSauder Nov 12, 2026
29109a2
mssql: reject a macro name that is not a valid @name
EliSauder Nov 12, 2026
a63e9ed
mssql: keep the length and precision of a computed column
EliSauder Nov 12, 2026
6c8bf76
mssql: count int and bit as decimals when combining types
EliSauder Nov 12, 2026
a42d1e1
mssql: type CASE, COALESCE, GREATEST, LEAST and CHOOSE by precedence
EliSauder Nov 12, 2026
784fef5
mssql: seed ROUND with its function argument
EliSauder Nov 12, 2026
a99032c
mssql: type DATEADD and DATETRUNC over a string date
EliSauder Nov 12, 2026
637b47c
mssql: report an unsupported query named in a block comment
EliSauder Nov 12, 2026
6b38d72
mssql: keep the placeholder in TOP (@n) PERCENT
EliSauder Nov 12, 2026
fb5722d
mssql: keep the placeholders of FOR SYSTEM_TIME
EliSauder Nov 12, 2026
43b8e5c
mssql: keep the placeholders of CONTAINS and FREETEXT
EliSauder Nov 12, 2026
c92fc3e
validate: allow an INSERT whose VALUES has no FROM list
EliSauder Nov 12, 2026
6b661b5
golang: reject :execlastid for SQL Server
EliSauder Nov 12, 2026
a5dfd49
mssql: support WITH on INSERT
EliSauder Nov 12, 2026
e8c0057
mssql: apply ALTER TABLE ALTER COLUMN
EliSauder Nov 12, 2026
2f48b4b
mssql: apply sp_rename to tables and columns
EliSauder Nov 12, 2026
d866aba
mssql: apply the schema changes in IF and BEGIN ... END blocks
EliSauder Nov 12, 2026
26bfd8a
mssql: type NEXT VALUE FOR a sequence
EliSauder Nov 12, 2026
937787e
mssql: type a call to a scalar function the schema creates
EliSauder Nov 12, 2026
e3e6264
mssql: select from a table-valued function the schema creates
EliSauder Nov 12, 2026
f8a773f
mssql: select from a synonym the schema creates
EliSauder Nov 12, 2026
886e8f5
mssql: type the methods of xml, geography, geometry and hierarchyid
EliSauder Nov 12, 2026
7e19529
core: type a placeholder INSERT ... SELECT inserts as its column
EliSauder Nov 12, 2026
170e54a
core: type a placeholder among alternatives as the others combine
EliSauder Nov 12, 2026
33db6e4
mssql: gofmt typeMethods
EliSauder Nov 12, 2026
a7951ed
mssql: seed more built-in functions
EliSauder Nov 12, 2026
4358b1c
mssql: apply ALTER SCHEMA ... TRANSFER
EliSauder Nov 12, 2026
67d9190
mssql: type LEFT, RIGHT and TRIM(chars FROM string)
EliSauder Nov 12, 2026
baf1ec3
mssql: take REPLICATE's and CHARINDEX's integer arguments as int
EliSauder Nov 12, 2026
4e345d0
mssql: type an N'...' literal as nvarchar
EliSauder Nov 12, 2026
3257c15
core: find the family of a type given default arguments
EliSauder Nov 12, 2026
b4cbd83
mssql: type a number with a decimal point as decimal
EliSauder Nov 12, 2026
2ffa47b
golang: map SQL Server decimal to decimal.Decimal and money to mssql.…
EliSauder Nov 13, 2026
c899fe5
golang: map a nullable uniqueidentifier to *mssql.UniqueIdentifier
EliSauder Nov 13, 2026
fccb542
mssql: report a placeholder the converter drops
EliSauder Nov 13, 2026
f59fb16
mssql: keep the placeholder in CONVERT's style
EliSauder Nov 13, 2026
99b6601
mssql: keep the placeholders of TABLESAMPLE
EliSauder Nov 13, 2026
14a031f
core: type a set operation column of an argument-free type as its family
EliSauder Nov 13, 2026
a13cdbc
core: stop pairing INSERT ... SELECT items with columns after a star
EliSauder Nov 13, 2026
38f9390
mssql: leave sqlc.embed out of the @name check
EliSauder Nov 13, 2026
cbc8adc
mssql: read a placeholder's name through #, $ and @
EliSauder Nov 13, 2026
600b393
mssql: measure a star qualifier with escaped quotes as written
EliSauder Nov 13, 2026
f2dbfc7
mssql: embed a table only when its columns are as nullable as the tab…
EliSauder Nov 13, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
3 changes: 3 additions & 0 deletions docs/reference/macros.md
Original file line number Diff line number Diff line change
Expand Up @@ -115,5 +115,8 @@ WHERE age IN (/*SLICE:ages*/?)
Since the `/*SLICE:ages*/` placeholder is dynamically replaced on a per-query
basis, this macro can't be used with prepared statements.

On SQL Server the placeholder is `/*SLICE:ages*/@ages`, and each value is bound
to its own `@p<n>` parameter, the name go-mssqldb gives an unnamed argument.

See a full example in [Passing a slice as a parameter to a
query](../howto/select.md#mysql-and-sqlite).
3 changes: 3 additions & 0 deletions docs/reference/query-annotations.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,9 @@ func (q *Queries) InsertAuthor(ctx context.Context, name string) (int64, error)
}
```

SQL Server's driver reports no last insert ID, so `:execlastid` is not
supported there. Return the ID with `OUTPUT INSERTED.id` and `:one` instead.

## `:many`

The generated method will return a slice of records via
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 @@ -212,6 +212,16 @@ func generate(req *plugin.GenerateRequest, options *opts.Options, enums []Enum,
tctx.SQLDriver = opts.SQLDriverGoSQLDriverMySQL
}

// go-mssqldb never reports a last insert ID; SQL Server returns one with
// OUTPUT INSERTED.
if req.Settings.Engine == engineMSSQL {
for _, q := range queries {
if q.Cmd == metadata.CmdExecLastId {
return nil, fmt.Errorf("query %q: :execlastid is not supported for SQL Server, whose driver reports no last insert ID; use OUTPUT INSERTED.<column> with :one", q.MethodName)
}
}
}

if tctx.UsesBatch && !tctx.SQLDriver.IsPGX() {
return nil, errors.New(":batch* commands are only supported by pgx")
}
Expand Down
16 changes: 13 additions & 3 deletions internal/codegen/golang/imports.go
Original file line number Diff line number Diff line change
Expand Up @@ -244,7 +244,9 @@ func buildImports(options *opts.Options, engine string, queries []Query, uses fu
// decimal.Decimal must not pull in shopspring's as well.
if usesDriverTypes(engine) {
for qualifier, path := range driverTypes {
if uses(qualifier) && !overrideHasQualifier(overrideTypes, qualifier) {
// A generic type's argument needs its package too, as
// mssql.Money[decimal.Decimal] does.
if (uses(qualifier) || uses("mssql.Money["+qualifier)) && !overrideHasQualifier(overrideTypes, qualifier) {
pkg[ImportSpec{Path: path}] = struct{}{}
}
}
Expand Down Expand Up @@ -439,9 +441,16 @@ func (i *importer) queryImports(filename string) fileImports {
return false
}

// A query bound by name passes sql.Named arguments.
// A query bound by name passes sql.Named arguments, except for its
// slices, whose values it binds to numbered placeholders.
for _, q := range gq {
if q.Arg.NamedArgs && !q.Arg.isEmpty() {
if !q.Arg.NamedArgs || q.Arg.isEmpty() {
continue
}
if q.Arg.HasSqlcSlices() {
std["strconv"] = struct{}{}
}
if q.Arg.hasNamedArg() {
std["database/sql"] = struct{}{}
}
}
Expand All @@ -454,6 +463,7 @@ func (i *importer) queryImports(filename string) fileImports {
if sqlcSliceScan() && !sqlpkg.IsPGX() {
std["strings"] = struct{}{}
}

if sliceScan() && usesPqArrays(i.Engine, sqlpkg) {
pkg[ImportSpec{Path: "github.com/lib/pq"}] = struct{}{}
}
Expand Down
17 changes: 12 additions & 5 deletions internal/codegen/golang/mssql_type.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,9 @@ import (

// mssqlType maps a SQL Server type to the Go type
// github.com/microsoft/go-mssqldb hands database/sql for it. Exact numerics
// come back as their decimal text, so they map to string the way
// PostgreSQL's numeric does under database/sql. A uniqueidentifier maps to
// map to shopspring's decimal, which the driver sends as a decimal, and
// money to the driver's Money over it, which it sends as money. A
// uniqueidentifier maps to
// the driver's own type, which keeps SQL Server's byte order straight. An
// alias type created with CREATE TYPE ... FROM is reported by its own name,
// which the catalog does not yet resolve to its base, so it maps to any
Expand All @@ -35,8 +36,11 @@ func mssqlType(req *plugin.GenerateRequest, options *opts.Options, col *plugin.C
case "bit":
return null("bool", "sql.NullBool")

case "decimal", "numeric", "money", "smallmoney":
return null("string", "sql.NullString")
case "decimal", "numeric":
return null("decimal.Decimal", "decimal.NullDecimal")

case "money", "smallmoney":
return null("mssql.Money[decimal.Decimal]", "mssql.Money[decimal.NullDecimal]")

case "float":
return null("float64", "sql.NullFloat64")
Expand All @@ -54,7 +58,10 @@ func mssqlType(req *plugin.GenerateRequest, options *opts.Options, col *plugin.C
return null("time.Time", "sql.NullTime")

case "uniqueidentifier":
return null("mssql.UniqueIdentifier", "mssql.NullUniqueIdentifier")
// go-mssqldb sends a NULL mssql.NullUniqueIdentifier passed by value
// as a malformed GUID, which SQL Server rejects with error 8009; a
// nil *mssql.UniqueIdentifier it sends as NULL.
return null("mssql.UniqueIdentifier", "*mssql.UniqueIdentifier")

case "geography", "geometry", "hierarchyid", "vector":
return "[]byte"
Expand Down
20 changes: 20 additions & 0 deletions internal/codegen/golang/query.go
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,12 @@ func (v QueryValue) namedArg(name, expr string) string {
return "sql.Named(" + strconv.Quote(name) + ", " + expr + ")"
}

// NamedArgForField is the argument expr passed for a field of a query bound
// by name.
func (v QueryValue) NamedArgForField(f Field) string {
return v.namedArg(f.ParamName, v.VariableForField(f))
}

func (v QueryValue) Params() string {
if v.isEmpty() {
return ""
Expand Down Expand Up @@ -224,6 +230,20 @@ func (v QueryValue) HasSqlcSlices() bool {
return false
}

// hasNamedArg reports whether any parameter is passed as sql.Named, which a
// sqlc.slice() never is.
func (v QueryValue) hasNamedArg() bool {
if v.Struct == nil {
return !v.HasSqlcSlices()
}
for _, f := range v.Struct.Fields {
if !f.HasSqlcSlice() {
return true
}
}
return false
}

func (v QueryValue) Scan() string {
var out []string
if v.Struct == nil {
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
30 changes: 29 additions & 1 deletion internal/codegen/golang/templates/stdlib/queryCode.tmpl
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,20 @@ func (q *Queries) {{.MethodName}}(ctx context.Context, {{ dbarg }} {{.Arg.Pair}}
{{- if .Arg.Struct }}
{{- $arg := .Arg }}
{{- range .Arg.Struct.Fields }}
{{- if .HasSqlcSlice }}
{{- if and .HasSqlcSlice $arg.NamedArgs }}
{{- /* The driver names an unnamed argument @p<ordinal>, its
1-based position in queryParams. */}}
if len({{$arg.VariableForField .}}) > 0 {
var placeholders []string
for _, v := range {{$arg.VariableForField .}} {
queryParams = append(queryParams, v)
placeholders = append(placeholders, "@p"+strconv.Itoa(len(queryParams)))
}
query = strings.ReplaceAll(query, "/*SLICE:{{.Column.Name}}*/@{{.Column.Name}}", strings.Join(placeholders, ","))
} else {
query = strings.ReplaceAll(query, "/*SLICE:{{.Column.Name}}*/@{{.Column.Name}}", "NULL")
}
{{- else if .HasSqlcSlice }}
if len({{$arg.VariableForField .}}) > 0 {
for _, v := range {{$arg.VariableForField .}} {
queryParams = append(queryParams, v)
Expand All @@ -140,6 +153,8 @@ func (q *Queries) {{.MethodName}}(ctx context.Context, {{ dbarg }} {{.Arg.Pair}}
} else {
query = strings.Replace(query, "/*SLICE:{{.Column.Name}}*/?", "NULL", 1)
}
{{- else if $arg.NamedArgs }}
queryParams = append(queryParams, {{$arg.NamedArgForField .}})
{{- else }}
queryParams = append(queryParams, {{$arg.VariableForField .}})
{{- end }}
Expand All @@ -149,6 +164,18 @@ func (q *Queries) {{.MethodName}}(ctx context.Context, {{ dbarg }} {{.Arg.Pair}}
in a struct), because .Arg.HasSqlcSlices further up above was true,
this section is 100% a slice (impossible to get here otherwise).
*/}}
{{- if .Arg.NamedArgs }}
if len({{.Arg.Name}}) > 0 {
var placeholders []string
for _, v := range {{.Arg.Name}} {
queryParams = append(queryParams, v)
placeholders = append(placeholders, "@p"+strconv.Itoa(len(queryParams)))
}
query = strings.ReplaceAll(query, "/*SLICE:{{.Arg.Column.Name}}*/@{{.Arg.Column.Name}}", strings.Join(placeholders, ","))
} else {
query = strings.ReplaceAll(query, "/*SLICE:{{.Arg.Column.Name}}*/@{{.Arg.Column.Name}}", "NULL")
}
{{- else }}
if len({{.Arg.Name}}) > 0 {
for _, v := range {{.Arg.Name}} {
queryParams = append(queryParams, v)
Expand All @@ -157,6 +184,7 @@ func (q *Queries) {{.MethodName}}(ctx context.Context, {{ dbarg }} {{.Arg.Pair}}
} else {
query = strings.Replace(query, "/*SLICE:{{.Arg.Column.Name}}*/?", "NULL", 1)
}
{{- end }}
{{- end }}
{{- if emitPreparedQueries }}
{{ queryRetval . }} {{ queryMethod . }}(ctx, nil, query, queryParams...)
Expand Down
14 changes: 13 additions & 1 deletion internal/compiler/expand.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,13 +66,21 @@ func (c *Compiler) quoteIdent(ident string) string {
return c.quote(ident)
}
}
// A column PIVOT names after a value, as [2023], is no regular
// identifier.
if c.conf.Engine == config.EngineMSSQL && !validPostgresIdent.MatchString(strings.ToLower(ident)) {
return c.quote(ident)
}
return ident
}

func (c *Compiler) quote(x string) string {
switch c.conf.Engine {
case config.EngineMySQL:
return "`" + x + "`"
case config.EngineMSSQL:
// Brackets quote whatever QUOTED_IDENTIFIER is set to.
return "[" + strings.ReplaceAll(x, "]", "]]") + "]"
Comment thread
EliSauder marked this conversation as resolved.
Resolved
default:
return "\"" + x + "\""
}
Expand Down Expand Up @@ -100,7 +108,11 @@ func (c *Compiler) starOldFunc(parts []string) func(string) int {
}
if strings.HasPrefix(s[length:], o) {
length += len(o)
} else if quoted := c.quote(o); strings.HasPrefix(s[length:], quoted) {
} else if quoted := c.quote(parts[i]); strings.HasPrefix(s[length:], quoted) {
length += len(quoted)
} else if quoted := `"` + strings.ReplaceAll(parts[i], `"`, `""`) + `"`; strings.HasPrefix(s[length:], quoted) {
// SQL Server quotes with brackets, but reads double quotes
// as an identifier too.
length += len(quoted)
} else {
length += len(o)
Expand Down
79 changes: 79 additions & 0 deletions internal/compiler/parse_core.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ func (c *Compiler) parseQueryCore(raw *ast.RawStmt, src string, pre *preprocess.
for _, col := range res.Columns {
cols = append(cols, coreColumn(col))
}
cols = embedColumns(raw, cols, res.Stars, pre.Embeds, c.coreCatalog)
placeholders, err := placeholderNames(raw)
if err != nil {
return nil, err
Expand Down Expand Up @@ -105,6 +106,84 @@ func (c *Compiler) parseQueryCore(raw *ast.RawStmt, src string, pre *preprocess.
}, nil
}

// embedColumns folds the columns each sqlc.embed() star expanded to into
// the one column codegen embeds the table's struct for. The table is the
// columns' source, so an embed of an alias names the table behind it. The
// struct scans every column of the table in order, so only an expansion
// that is exactly those columns is folded; any other stays flat.
func embedColumns(raw *ast.RawStmt, cols []*Column, stars []core.StarExpansion, embeds preprocess.EmbedSet, cat *core.Catalog) []*Column {
sel, ok := raw.Stmt.(*ast.SelectStmt)
if !ok || len(embeds) == 0 || sel.TargetList == nil {
return cols
}
width := map[int]int{}
for _, star := range stars {
width[star.Location] = len(star.Columns)
}
var out []*Column
i := 0
for _, item := range sel.TargetList.Items {
res, ok := item.(*ast.ResTarget)
if !ok {
return cols
}
ref, ok := res.Val.(*ast.ColumnRef)
if !ok || !hasStarRef(ref) {
out = append(out, cols[i])
i++
continue
}
n, ok := width[res.Location]
if !ok || i+n > len(cols) {
return cols
}
if embed, ok := embeds.Find(ref.Location, res.Location); ok && n > 0 && isWholeTable(cat, cols[i:i+n]) {
out = append(out, &Column{Name: embed.Table.Name, EmbedTable: cols[i].Table})
} else {
out = append(out, cols[i:i+n]...)
}
i += n
}
return out
}

// isWholeTable reports whether cols are every column of one table, in the
// table's order, each as nullable as the table's: the optional side of an
// outer join is not, and the table's model could not hold its NULLs.
func isWholeTable(cat *core.Catalog, cols []*Column) bool {
table := cols[0].Table
if table == nil {
return false
}
schema := table.Schema
if schema == "" {
schema = "public"
}
nsOID, err := cat.NamespaceOID(schema)
if err != nil {
return false
}
classOID, err := cat.ClassOID(nsOID, table.Name)
if err != nil {
return false
}
tableCols, err := cat.ClassColumns(classOID)
if err != nil {
return false
}
i := 0
for _, tc := range tableCols {
if tc.Hidden {
continue
}
if i >= len(cols) || cols[i].Table == nil || *cols[i].Table != *table || cols[i].OriginalName != tc.Name || cols[i].NotNull != tc.NotNull {
return false
}
i++
}
return i == len(cols)
}

func coreColumn(c core.Column) *Column {
col := &Column{
Name: c.Name,
Expand Down
Loading
Loading