Skip to content

Commit

Permalink
Support UNNEST WITH OFFSET (#37)
Browse files Browse the repository at this point in the history
* Support `UNNEST WITH OFFSET`

* Update README.md
  • Loading branch information
ohaibbq authored Mar 29, 2024
1 parent caa4ebd commit 42838f7
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 5 deletions.
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
- [x] PIVOT operator
- [x] 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 @@ -727,6 +727,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 @@ -762,15 +768,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 @@ -2392,6 +2392,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

0 comments on commit 42838f7

Please sign in to comment.