Skip to content

PostgreSQL CREATE INDEX rejects column sort options like DESC #22

@AlexS778

Description

@AlexS778

Summary

The PostgreSQL grammar currently produces an ERROR node for valid index
definitions that specify per-column sort order:

CREATE INDEX tasks_created
    ON main.tasks
        USING btree (created DESC);

The error starts at DESC.

This affects ordinary btree index definitions such as:

(created DESC)
(updated DESC)
(created ASC NULLS FIRST)
(updated DESC NULLS LAST)

Minimal reproduction

From the repository root:

cat > /tmp/index_desc.sql <<'SQL'
CREATE INDEX tasks_created
    ON main.tasks
        USING btree (created DESC);
SQL

./node_modules/.bin/tree-sitter parse --grammar-path postgres /tmp/index_desc.sql

Actual behavior

The index statement is mostly parsed, but DESC is left under an ERROR node:

(IndexStmt
  ...
  (index_params
    (index_elem
      (ColId
        (identifier))))
  (ERROR
    (any_name
      (ColId
        (identifier)))))

The reported range is equivalent to:

ERROR at DESC

Expected behavior

The whole statement should parse without an ERROR node.

DESC, ASC, and optional NULLS FIRST / NULLS LAST should be part of the
index element options.

Expected valid examples:

CREATE INDEX idx_created_desc ON t USING btree (created DESC);
CREATE INDEX idx_created_asc ON t USING btree (created ASC);
CREATE INDEX idx_created_nf ON t USING btree (created ASC NULLS FIRST);
CREATE INDEX idx_created_nl ON t USING btree (created DESC NULLS LAST);

Why this matters

This is common PostgreSQL syntax for indexes used by ordered queries. In a
schema corpus, every file containing indexes like USING btree (created DESC)
fails to parse even though the SQL is valid PostgreSQL.

Likely location

The relevant rules appear to be around index element options:

postgres/grammar.js
  index_elem
  index_elem_options
  opt_asc_desc
  opt_nulls_order

Because the grammar is generated, the fix may need to happen in the generator
source as well, not only in the generated postgres/grammar.js.

Suggested regression tests

Add corpus cases for:

CREATE INDEX idx_a ON t USING btree (a DESC);
CREATE INDEX idx_b ON t USING btree (b ASC);
CREATE INDEX idx_c ON t USING btree (c DESC NULLS LAST);
CREATE INDEX idx_d ON t USING btree (d ASC NULLS FIRST);
CREATE INDEX idx_multi ON t USING btree (a DESC, b ASC NULLS FIRST);

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions