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
54 changes: 54 additions & 0 deletions internal/core/analyzer/expr.go
Original file line number Diff line number Diff line change
Expand Up @@ -884,6 +884,14 @@ func (a *analyzer) typeFuncCall(f *ast.FuncCall) (exprType, error) {
anyNullable = anyNullable || t.nullable
}

if name == "struct_extract" || name == "unnest" {
if dialect, err := a.cat.DialectOID("duckdb"); err == nil && dialect == a.cat.SeededDialectOID() {
if result, ok := a.duckDBFunctionResult(name, args, argTypes); ok {
return result, nil
}
}
}

overloads, err := a.cat.FindProcs(name, nil)
if err != nil {
return exprType{}, err
Expand Down Expand Up @@ -929,6 +937,52 @@ func (a *analyzer) typeFuncCall(f *ast.FuncCall) (exprType, error) {
return ret, nil
}

func (a *analyzer) duckDBFunctionResult(name string, args []ast.Node, argTypes []exprType) (exprType, bool) {
switch {
case name == "unnest" && len(args) == 1:
// A nonrecursive unnest of a list yields its element type. Optional
// arguments may change the result shape.
if element := a.exprOf(argTypes[0]).Element(); element != nil {
result := a.lookupType(element)
result.nullable = true
return result, true
}
case name == "struct_extract" && len(args) == 2:
key, ok := args[1].(*ast.A_Const)
if !ok {
break
}
field, ok := key.Val.(*ast.String)
if !ok {
break
}
record := a.exprOf(argTypes[0])
if record == nil || record.Name != "struct" {
break
}
fieldName := duckDBStructFieldName(field.Str)
for _, arg := range record.Args {
if arg.Label != "" && arg.Type != nil && duckDBStructFieldName(arg.Label) == fieldName {
result := a.lookupType(arg.Type)
// A nonnull struct can still contain a NULL field.
result.nullable = true
return result, true
}
}
}
return exprType{}, false
}

// DuckDB folds ASCII letters only, including in quoted field names.
func duckDBStructFieldName(name string) string {
return strings.Map(func(r rune) rune {
if 'A' <= r && r <= 'Z' {
return r + ('a' - 'A')
}
return r
}, name)
}

// returnTemplate fills a seed's return template — Decimal(18, $2) — from
// the call: a $n that stands for an integer literal takes its value, and
// one that stands for a typed argument takes its type. A template that
Expand Down
27 changes: 22 additions & 5 deletions internal/core/typeexpr.go
Original file line number Diff line number Diff line change
Expand Up @@ -114,9 +114,9 @@ func (t *TypeExpr) Key() string {

// ParseTypeExpr reads a type spelled the way every dialect spells one, as a
// name optionally applied to a parenthesised, comma-separated argument list
// whose entries may be labelled (`lat Float64` in a tuple, `'a' = 1` in an
// enum). A Nullable(T) wrapper becomes T with Nullable set, and a trailing
// [] becomes an array of the element.
// whose entries may be labelled (`lat Float64` in a tuple, `"full name": varchar`
// in a struct, `'a' = 1` in an enum). A Nullable(T) wrapper becomes T with
// Nullable set, and a trailing [] becomes an array of the element.
func ParseTypeExpr(s string) *TypeExpr {
s = strings.TrimSpace(s)
if element, ok := strings.CutSuffix(s, ArraySuffix); ok {
Expand All @@ -138,6 +138,15 @@ func ParseTypeExpr(s string) *TypeExpr {

func parseTypeArg(a string) TypeArg {
a = strings.TrimSpace(a)
if strings.HasPrefix(a, `"`) {
if lit, err := strconv.QuotedPrefix(a); err == nil {
if rest, ok := strings.CutPrefix(strings.TrimSpace(a[len(lit):]), ":"); ok {
arg := parseTypeArg(rest)
arg.Label, _ = strconv.Unquote(lit)
return arg
}
}
}
if strings.HasPrefix(a, "'") {
end := quotedEnd(a)
lit := strings.ReplaceAll(strings.ReplaceAll(a[1:end-1], `\'`, `'`), `''`, `'`)
Expand Down Expand Up @@ -173,6 +182,15 @@ func parseTypeArg(a string) TypeArg {
return TypeArg{Type: ParseTypeExpr(a)}
}

// FormatTypeLabel writes a field label and its separator in a type expression.
// Quoting keeps the label separate from the type expression's delimiters.
func FormatTypeLabel(label string) string {
if strings.TrimSpace(label) != label || strings.ContainsAny(label, " ,:()'\"`\\") {
label = strconv.Quote(label)
}
return label + ": "
}

// quotedEnd returns the index just past the single-quoted literal starting
// at the beginning of s, honouring backslash escapes and doubled quotes.
func quotedEnd(s string) int {
Expand Down Expand Up @@ -299,8 +317,7 @@ func (t *TypeExpr) String() string {
b.WriteString(", ")
}
if a.Label != "" {
b.WriteString(a.Label)
b.WriteString(": ")
b.WriteString(FormatTypeLabel(a.Label))
}
switch {
case a.Type != nil:
Expand Down
3 changes: 3 additions & 0 deletions internal/endtoend/testdata/duckdb_struct_extract/exec.json
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/duckdb_struct_extract/go/db.go

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

19 changes: 19 additions & 0 deletions internal/endtoend/testdata/duckdb_struct_extract/go/models.go

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

96 changes: 96 additions & 0 deletions internal/endtoend/testdata/duckdb_struct_extract/go/query.sql.go

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

15 changes: 15 additions & 0 deletions internal/endtoend/testdata/duckdb_struct_extract/query.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
-- name: ListAmounts :many
WITH entries AS (
SELECT id, unnest(items) AS item
FROM transactions
)
SELECT id, struct_extract(item, 'amount') AS amount
FROM entries;

-- name: ListLabels :many
SELECT id, struct_extract(info, 'LABEL') AS label,
struct_extract(struct_extract(info, 'details'), 'active') AS active,
struct_extract(info, 'É') AS upper_value,
struct_extract(info, 'é') AS lower_value,
struct_extract(info, 'full, "name"') AS full_name
FROM items;
15 changes: 15 additions & 0 deletions internal/endtoend/testdata/duckdb_struct_extract/schema.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
CREATE TABLE transactions (
id VARCHAR NOT NULL,
items STRUCT(type VARCHAR, amount INTEGER)[]
);

CREATE TABLE items (
id INTEGER NOT NULL,
info STRUCT(
Label VARCHAR,
details STRUCT(active BOOLEAN),
"É" BIGINT,
"é" SMALLINT,
"full, ""name""" VARCHAR
) NOT NULL
);
10 changes: 10 additions & 0 deletions internal/endtoend/testdata/duckdb_struct_extract/sqlc.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
version: "2"
sql:
- engine: "duckdb"
schema: "schema.sql"
queries: "query.sql"
gen:
go:
package: "querytest"
out: "go"
sql_package: "database/sql"
7 changes: 6 additions & 1 deletion internal/engine/duckdb/convert.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (

dw "github.com/sqlc-dev/darkwing/ast"

"github.com/sqlc-dev/sqlc/internal/core"
"github.com/sqlc-dev/sqlc/internal/sql/ast"
)

Expand Down Expand Up @@ -862,7 +863,11 @@ func renderTypeExpression(t *dw.TypeExpression) string {
case *dw.TypeExpression:
part = renderTypeExpression(a)
if a.Alias != "" {
part = identifier(a.Alias) + ": " + part
label := identifier(a.Alias)
if name == "struct" {
label = a.Alias
}
part = core.FormatTypeLabel(label) + part
}
case *dw.ConstantExpression:
switch {
Expand Down
Loading