Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support UNNEST WITH OFFSET #199

Merged
merged 3 commits into from
Apr 8, 2024
Merged
Show file tree
Hide file tree
Changes from 2 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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@ A list of ZetaSQL ( Google Standard SQL ) specifications and features supported
- [x] UNNEST and STRUCTs
- [ ] Explicit and implicit UNNEST
- [ ] UNNEST and NULLs
- [ ] UNNEST and WITH OFFSET
- [x] UNNEST and WITH OFFSET
- [ ] PIVOT operator
- [ ] UNPIVOT operator
- [ ] TABLESAMPLE operator
Expand Down
14 changes: 10 additions & 4 deletions internal/formatter.go
Original file line number Diff line number Diff line change
Expand Up @@ -660,6 +660,12 @@ func (n *ArrayScanNode) FormatSQL(ctx context.Context) (string, error) {
return "", err
}
colName := uniqueColumnName(ctx, n.node.ElementColumn())
columns := []string{fmt.Sprintf("json_each.value AS `%s`", colName)}

if offsetColumn := n.node.ArrayOffsetColumn(); offsetColumn != nil {
offsetColName := uniqueColumnName(ctx, offsetColumn.Column())
columns = append(columns, fmt.Sprintf("json_each.key AS `%s`", offsetColName))
}
if n.node.InputScan() != nil {
input, err := newNode(n.node.InputScan()).FormatSQL(ctx)
if err != nil {
Expand Down Expand Up @@ -695,15 +701,15 @@ func (n *ArrayScanNode) FormatSQL(ctx context.Context) (string, error) {
}

return fmt.Sprintf(
"SELECT *, json_each.value AS `%s` %s %s",
colName,
"SELECT *, %s %s %s",
strings.Join(columns, ","),
formattedInput,
arrayJoinExpr,
), nil
}
return fmt.Sprintf(
"SELECT json_each.value AS `%s` FROM json_each(zetasqlite_decode_array(%s))",
colName,
"SELECT %s FROM json_each(zetasqlite_decode_array(%s))",
strings.Join(columns, ","),
arrayExpr,
), nil
}
Expand Down
9 changes: 9 additions & 0 deletions query_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2264,6 +2264,15 @@ FROM UNNEST([
query: `SELECT a, b FROM UNNEST([STRUCT(DATE(2022, 1, 1) AS a, 1 AS b)])`,
expectedRows: [][]interface{}{{"2022-01-01", int64(1)}},
},
{
name: "unnest with offset",
query: `SELECT *
FROM UNNEST(['foo', 'bar', 'baz'])
AS element
WITH OFFSET AS offset
ORDER BY offset DESC;`,
expectedRows: [][]interface{}{{"baz", int64(2)}, {"bar", int64(1)}, {"foo", int64(0)}},
},
{
name: "array function",
query: `SELECT ARRAY (SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3) AS new_array`,
Expand Down
Loading