Repository: tobymao/sqlglot

Issue:
TSQL: PRIMARY KEY constraint fails to parse if sort option is given
The following CREATE TABLE statement parses just fine:
```
import sqlglot

test = """CREATE TABLE dbo.test (
      id INT,
      name VARCHAR(50),
      CONSTRAINT pk_testTable PRIMARY KEY (id)
      ) ;"""
        
    parsed_script = sqlglot.parse(test, read="tsql")
```

However, when I add ASC or DESC to the PRIMARY KEY constraint, it fails to parse:

```
import sqlglot

test = """CREATE TABLE dbo.test (
    id INT,
    name VARCHAR(50),
    CONSTRAINT pk_testTable PRIMARY KEY (id DESC)
    ) ;"""
        
    parsed_script = sqlglot.parse(test, read="tsql")
```

Error Message:

```
Exception has occurred: ParseError
Expecting ). Line 4, Col: 45.
  bo.test (
        id INT,
        name VARCHAR(50),
        CONSTRAINT pk_testTable PRIMARY KEY (id [4mDESC[0m)
        ) ;
  File "C:\*snip*\main.py", line 96, in main
    parsed_script = sqlglot.parse(test, read="tsql")
                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\*snip*\main.py", line 116, in <module>
    main()
sqlglot.errors.ParseError: Expecting ). Line 4, Col: 45.
  bo.test (
        id INT,
        name VARCHAR(50),
        CONSTRAINT pk_testTable PRIMARY KEY (id [4mDESC[0m)
        ) ;
```

Official Documentation: https://learn.microsoft.com/en-us/sql/t-sql/statements/create-table-transact-sql?view=sql-server-ver16#constraint

Edit: sqlglot version is 25.21.3.


Discussion:

Fix (patch):
diff --git a/sqlglot/parser.py b/sqlglot/parser.py
index 7f310b3b..ae3f6cde 100644
--- a/sqlglot/parser.py
+++ b/sqlglot/parser.py
@@ -5902,7 +5902,7 @@ class Parser(metaclass=_Parser):
         )
 
     def _parse_primary_key_part(self) -> t.Optional[exp.Expression]:
-        return self._parse_field()
+        return self._parse_ordered() or self._parse_field()
 
     def _parse_period_for_system_time(self) -> t.Optional[exp.PeriodForSystemTimeConstraint]:
         if not self._match(TokenType.TIMESTAMP_SNAPSHOT):


Test changes:
diff --git a/tests/dialects/test_tsql.py b/tests/dialects/test_tsql.py
index 738120a2..fe1aa9c5 100644
--- a/tests/dialects/test_tsql.py
+++ b/tests/dialects/test_tsql.py
@@ -436,6 +436,13 @@ class TestTSQL(Validator):
             "'a' + 'b'",
         )
 
+        self.validate_identity(
+            "CREATE TABLE db.t1 (a INTEGER, b VARCHAR(50), CONSTRAINT c PRIMARY KEY (a DESC))",
+        )
+        self.validate_identity(
+            "CREATE TABLE db.t1 (a INTEGER, b INTEGER, CONSTRAINT c PRIMARY KEY (a DESC, b))"
+        )
+
     def test_option(self):
         possible_options = [
             "HASH GROUP",