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)
``` 


Discussion:

Patch:
diff --git a/sqlglot/expressions.py b/sqlglot/expressions.py
index 9d65e57e..56a347ab 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 f30472fd..f717e312 100644
--- a/sqlglot/generator.py
+++ b/sqlglot/generator.py
@@ -1861,7 +1861,8 @@ class Generator(metaclass=_Generator):
             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 2fa9ab44..0e525e7a 100644
--- a/sqlglot/parser.py
+++ b/sqlglot/parser.py
@@ -2732,6 +2732,8 @@ class Parser(metaclass=_Parser):
                 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 @@ class Parser(metaclass=_Parser):
             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 acdb2d4a..019a10e9 100644
--- a/tests/dialects/test_postgres.py
+++ b/tests/dialects/test_postgres.py
@@ -874,6 +874,9 @@ class TestPostgres(Validator):
         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"
         )