Repository: tobymao/sqlglot

Issue:
Postgres: table name alias causing issue for INSERT queries
I am facing an issue parsing a valid Postgres SQL. Below is the simplified reproducable version of the SQL. Here the issue arises when I specify a alias for the table.

```
insert into newtable as t (a,b,c) values (1,2,3)
on conflict (c)
do update
   set a = t.a + 1
where
   t.a < 1
``` 
Error: `ParseError: Invalid expression / Unexpected token. Line 2, Col: 23.`

If I remove table alias, it works just fine.

**Fully reproducible code snippet**
```python
from sqlglot import parse_one, exp
sql = """
insert into newtable as t (a,b,c) values (1,2,3)
on conflict (c)
do update
   set a = t.a + 1
where
   t.a < 1
"""
for table in parse_one(sql, read="postgres").find_all(exp.Table):
    print(table.name)
```

Hints from issue comments:

Solution patch:
diff --git a/sqlglot/expressions.py b/sqlglot/expressions.py
index 9d65e57e8a..56a347abaf 100644
--- a/sqlglot/expressions.py
+++ b/sqlglot/expressions.py
@@ -2291,6 +2291,7 @@ class OnConflict(Expression):
         "action": False,
         "conflict_keys": False,
         "constraint": False,
+        "where": False,
     }
 
 
diff --git a/sqlglot/generator.py b/sqlglot/generator.py
index f30472fd0f..f717e31252 100644
--- a/sqlglot/generator.py
+++ b/sqlglot/generator.py
@@ -1861,7 +1861,8 @@ def onconflict_sql(self, expression: exp.OnConflict) -> str:
             set_keyword = "SET " if self.DUPLICATE_KEY_UPDATE_WITH_SET else ""
             expressions = f" {set_keyword}{expressions}"
 
-        return f"{conflict}{constraint}{conflict_keys}{action}{expressions}"
+        where = self.sql(expression, "where")
+        return f"{conflict}{constraint}{conflict_keys}{action}{expressions}{where}"
 
     def returning_sql(self, expression: exp.Returning) -> str:
         return f"{self.seg('RETURNING')} {self.expressions(expression, flat=True)}"
diff --git a/sqlglot/parser.py b/sqlglot/parser.py
index 2fa9ab448e..0e525e7a87 100644
--- a/sqlglot/parser.py
+++ b/sqlglot/parser.py
@@ -2732,6 +2732,8 @@ def _parse_insert(self) -> t.Union[exp.Insert, exp.MultitableInserts]:
                 if not is_function
                 else self._parse_function()
             )
+            if isinstance(this, exp.Table) and self._match(TokenType.ALIAS, advance=False):
+                this.set("alias", self._parse_table_alias())
 
         returning = self._parse_returning()
 
@@ -2796,6 +2798,7 @@ def _parse_on_conflict(self) -> t.Optional[exp.OnConflict]:
             action=action,
             conflict_keys=conflict_keys,
             constraint=constraint,
+            where=self._parse_where(),
         )
 
     def _parse_returning(self) -> t.Optional[exp.Returning]:


Test patch:
diff --git a/tests/dialects/test_postgres.py b/tests/dialects/test_postgres.py
index acdb2d4a83..019a10e985 100644
--- a/tests/dialects/test_postgres.py
+++ b/tests/dialects/test_postgres.py
@@ -874,6 +874,9 @@ def test_ddl(self):
         self.validate_identity("ALTER TABLE t1 SET ACCESS METHOD method")
         self.validate_identity("ALTER TABLE t1 SET TABLESPACE tablespace")
         self.validate_identity("ALTER TABLE t1 SET (fillfactor = 5, autovacuum_enabled = TRUE)")
+        self.validate_identity(
+            "INSERT INTO newtable AS t(a, b, c) VALUES (1, 2, 3) ON CONFLICT(c) DO UPDATE SET a = t.a + 1 WHERE t.a < 1"
+        )
         self.validate_identity(
             "ALTER TABLE tested_table ADD CONSTRAINT unique_example UNIQUE (column_name) NOT VALID"
         )