Skip to content

Commit

Permalink
Fix: postgres exponent precedence closes tobymao#1555
Browse files Browse the repository at this point in the history
  • Loading branch information
tobymao authored and adrianisk committed Jun 21, 2023
1 parent 271c3b5 commit e17a095
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 3 deletions.
2 changes: 1 addition & 1 deletion sqlglot/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,7 @@ def transpile(
Returns:
The list of transpiled SQL statements.
"""
write = write or read if identity else write
write = (read if write is None else write) if identity else write
return [
Dialect.get_or_raise(write)().generate(expression, **opts)
for expression in parse(sql, read, error_level=error_level)
Expand Down
11 changes: 9 additions & 2 deletions sqlglot/dialects/postgres.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
from __future__ import annotations

import typing as t

from sqlglot import exp, generator, parser, tokens, transforms
from sqlglot.dialects.dialect import (
Dialect,
Expand Down Expand Up @@ -273,8 +275,7 @@ class Parser(parser.Parser):
TokenType.HASH: exp.BitwiseXor,
}

FACTOR = {
**parser.Parser.FACTOR,
EXPONENT = {
TokenType.CARET: exp.Pow,
}

Expand All @@ -285,6 +286,12 @@ class Parser(parser.Parser):
TokenType.LT_AT: binary_range_parser(exp.ArrayContained),
}

def _parse_factor(self) -> t.Optional[exp.Expression]:
return self._parse_tokens(self._parse_exponent, self.FACTOR)

def _parse_exponent(self) -> t.Optional[exp.Expression]:
return self._parse_tokens(self._parse_unary, self.EXPONENT)

def _parse_date_part(self) -> exp.Expression:
part = self._parse_type()
self._match(TokenType.COMMA)
Expand Down
8 changes: 8 additions & 0 deletions tests/dialects/test_postgres.py
Original file line number Diff line number Diff line change
Expand Up @@ -491,6 +491,14 @@ def test_postgres(self):
},
)

self.validate_all(
"x / y ^ z",
write={
"": "x / POWER(y, z)",
"postgres": "x / y ^ z",
},
)

self.assertIsInstance(parse_one("id::UUID", read="postgres"), exp.TryCast)

def test_bool_or(self):
Expand Down

0 comments on commit e17a095

Please sign in to comment.