Repository: tobymao/sqlglot

Issue:
duckdb binder error after json_extract_string is converted to ->>
Hello,

When parsing duckdb, sqlglot converts `JSON_EXTRACT_STRING` to `->>`, but this seems to change the operator precedence in some cases. Also seeing similar behavior for `JSON_EXTRACT` as well.

**Fully reproducible code snippet**
```
import duckdb
import sqlglot

con = duckdb.connect()
con.execute("CREATE TABLE t as SELECT [{id: 'a'}, {id: 'b'}, {id: 'c'}] as col")

q0 = "SELECT (JSON_EXTRACT_STRING(col, '$[*].id'))[0:2] FROM t"
print(q0)
print(con.execute(q0).fetchall())
print()

q1 = sqlglot.parse_one(q0, dialect="duckdb").sql(dialect="duckdb")
print(q1)
print(con.execute(q1).fetchall())
```

```
SELECT JSON_EXTRACT_STRING(col, '$[*].id')[0:2] FROM t
[(['a', 'b'],)]

SELECT col ->> '$[*].id'[0 : 2] FROM t
---------------------------------------------------------------------------
BinderException                           Traceback (most recent call last)
Cell In[5], line 14
     12 q1 = sqlglot.parse_one(q0, dialect="duckdb").sql(dialect="duckdb")
     13 print(q1)
---> 14 print(con.execute(q1).fetchall())

BinderException: Binder Error: JSON path error near '['
```
Expected the second query to have no error.

**Official Documentation**
https://duckdb.org/docs/extensions/json.html#json-extraction-functions


Discussion:

Patch:
diff --git a/sqlglot/dialects/duckdb.py b/sqlglot/dialects/duckdb.py
index c2f58a16..79c88a2b 100644
--- a/sqlglot/dialects/duckdb.py
+++ b/sqlglot/dialects/duckdb.py
@@ -168,7 +168,7 @@ def _unix_to_time_sql(self: DuckDB.Generator, expression: exp.UnixToTime) -> str
 
 def _arrow_json_extract_sql(self: DuckDB.Generator, expression: JSON_EXTRACT_TYPE) -> str:
     arrow_sql = arrow_json_extract_sql(self, expression)
-    if not expression.same_parent and isinstance(expression.parent, exp.Binary):
+    if not expression.same_parent and isinstance(expression.parent, (exp.Binary, exp.Bracket)):
         arrow_sql = self.wrap(arrow_sql)
     return arrow_sql
 


Test patch:
diff --git a/tests/dialects/test_duckdb.py b/tests/dialects/test_duckdb.py
index bcabd20d..63e8179a 100644
--- a/tests/dialects/test_duckdb.py
+++ b/tests/dialects/test_duckdb.py
@@ -308,6 +308,14 @@ class TestDuckDB(Validator):
             "SELECT JSON_EXTRACT(c, '$.k1') = 'v1'",
             "SELECT (c -> '$.k1') = 'v1'",
         )
+        self.validate_identity(
+            "SELECT JSON_EXTRACT(c, '$[*].id')[0:2]",
+            "SELECT (c -> '$[*].id')[0 : 2]",
+        )
+        self.validate_identity(
+            "SELECT JSON_EXTRACT_STRING(c, '$[*].id')[0:2]",
+            "SELECT (c ->> '$[*].id')[0 : 2]",
+        )
         self.validate_identity(
             """SELECT '{"foo": [1, 2, 3]}' -> 'foo' -> 0""",
             """SELECT '{"foo": [1, 2, 3]}' -> '$.foo' -> '$[0]'""",