Skip to content

fix(declare): declare JSON-path indexes on PostgreSQL - #1684

Merged
dimitri-yatsenko merged 4 commits into
datajoint:masterfrom
mayuriphad:fix/1672-postgres-json-index
Nov 24, 2026
Merged

dimitri-yatsenko merged 4 commits into
datajoint:masterfrom
mayuriphad:fix/1672-postgres-json-index

Conversation

@mayuriphad

Copy link
Copy Markdown
Contributor

Fixes #1672.

On PostgreSQL, declare() turns each compiled index into a separate CREATE INDEX. It re-parsed the compiled text with index\s*\(([^)]+)\) and split the result on every comma, so a JSON-path item was cut at its first ), its pieces were quoted as identifiers, and the same text went into the index name:

CREATE INDEX "idx_indexed_((jsonb_extract_path_text("dat" ON "s"."indexed" ("((jsonb_extract_path_text("data", "'size'")

Changes:

  • declare.py: match the whole parenthesized list and split it with the existing _parse_index_args, which only splits on top-level commas. Plain columns are unquoted as before; parenthesized expressions are passed through unchanged.
  • adapters/base.py create_index_ddl: emit items that start with ( as they are, and quote the rest. When the index has an expression, the name keeps only word characters from the item text and adds an 8-character hash of the items, so two JSON paths in the same table get different names. The name is capped at PostgreSQL's 63-character identifier limit. Plain column indexes keep the names they get today.

For the definition in the issue, the DDL is now:

CREATE INDEX "idx_indexed_jsonb_extract_path_text_dat_04627560" ON "s"."indexed" (((jsonb_extract_path_text("data", 'size'))::integer))

MySQL is unaffected: it keeps the inline index from compile_index.

Tests

  • tests/unit/test_declare_index.py checks the generated PostgreSQL DDL for a JSON-path index, a unique index that mixes a column and a JSON path, a plain column index (unchanged name), and that two expression indexes get valid, distinct names within 63 characters. Three of the four fail on master; the plain-column one passes on both.
  • tests/integration/test_json_index.py declares a table with a JSON-path index and a mixed unique index on both backends (connection_by_backend) and inserts into it. It uses decimal(4,1) and char(20) because MySQL's JSON_VALUE ... RETURNING does not accept integer or varchar, so the data.size:integer example from the issue still fails on MySQL. That is a separate problem in the MySQL type mapping, which this PR leaves alone.
  • Unit tests pass locally (483 passed). I don't have Docker here, so the integration suite ran on my fork's CI: all cells pass (run).
  • ruff check and ruff format --check (v0.8.4, the pre-commit pin) pass on the changed files.

PostgreSQL has no inline INDEX in CREATE TABLE, so declare() re-parses
each compiled index into a CREATE INDEX statement. The regex stopped at
the first ")" and the column list was split on every comma, so a
JSON-path expression was cut into pieces, quoted as identifiers and
used in the index name, giving invalid SQL.

Split the items on top-level commas, keep parenthesized expressions as
they are in create_index_ddl, and derive the index name for an
expression from its word characters plus a short hash, capped at 63
characters. Plain column indexes keep their current names.

Fixes datajoint#1672

Signed-off-by: mayuriphad <mayuriphad656@gmail.com>
MySQL's JSON_VALUE ... RETURNING has no integer or varchar type, so use
decimal and char, which both backends accept.

Signed-off-by: mayuriphad <mayuriphad656@gmail.com>
Copilot AI balanced review requested due to automatic review settings November 17, 2026 02:21

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

An organization owner can choose the repository organization as the billing source for reviews requested by members with a paid Copilot license. Learn about Copilot code review billing.

@dimitri-yatsenko dimitri-yatsenko added this to the v2.3.7 milestone Nov 18, 2026

@dimitri-yatsenko dimitri-yatsenko left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The diagnosis is right. Reusing _parse_index_args is the right way to split the items. I ran the full suite on this branch merged with current master, on MySQL and PostgreSQL: 2045 passed, 17 skipped.

One bug in the index name: the name is cut to 63 characters after the hash is appended. On a table with a long name, the cut removes the hash, and two JSON-path indexes get the same name. On a table _ephys_recording_probe_insertion, indexes on data.a and data.b both become idx__ephys_recording_probe_insertion_jsonb_extract_path_text_da. PostgreSQL index names are unique within a schema, so the second CREATE INDEX fails. Cutting the readable part before appending the hash keeps the names distinct, and plain-column names stay as they are today (inline suggestion). A long table name in test_expression_index_names_are_valid_and_distinct would cover it.

The MySQL JSON_VALUE ... RETURNING limit you hit is #1563, with a draft fix in #1607, so leaving it out of this PR is right.

Optional: the bug was in the generated DDL, so the integration test could also check that both indexes exist, for example in pg_indexes on PostgreSQL, besides declaring and inserting.

Comment thread src/datajoint/adapters/base.py Outdated
Comment on lines +706 to +711
if any(col.startswith("(") for col in columns):
# Expressions are not valid in an identifier: keep the word
# characters and add a hash so distinct expressions get distinct names.
digest = hashlib.md5("_".join(columns).encode()).hexdigest()[:8]
col_part = re.sub(r"\W+", "_", col_part).strip("_") + "_" + digest
index_name = f"idx_{table_part}_{col_part}"[:63]

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cut the readable part before appending the hash, so the hash survives the 63-character limit and plain-column names stay as they are:

Suggested change
if any(col.startswith("(") for col in columns):
# Expressions are not valid in an identifier: keep the word
# characters and add a hash so distinct expressions get distinct names.
digest = hashlib.md5("_".join(columns).encode()).hexdigest()[:8]
col_part = re.sub(r"\W+", "_", col_part).strip("_") + "_" + digest
index_name = f"idx_{table_part}_{col_part}"[:63]
if any(col.startswith("(") for col in columns):
# Expressions are not valid in an identifier: keep the word
# characters and add a hash so distinct expressions get distinct names.
# Cut before adding the hash, so it survives the 63-character limit.
digest = hashlib.md5("_".join(columns).encode()).hexdigest()[:8]
col_part = re.sub(r"\W+", "_", col_part).strip("_")
index_name = f"idx_{table_part}_{col_part}"[:54] + "_" + digest
else:
index_name = f"idx_{table_part}_{col_part}"[:63]

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Applied in abaf481: the readable part is cut to 54 characters before _ and the 8-character hash are added, and plain-column names still use the old [:63] cut.

Cut the readable part of an expression index name before appending the
hash, so the hash survives the 63-character limit and two JSON-path
indexes on a table with a long name still get distinct names.

Signed-off-by: mayuriphad <mayuriphad656@gmail.com>
@mayuriphad

Copy link
Copy Markdown
Contributor Author

Thanks @dimitri-yatsenko. In abaf481, test_expression_index_names_are_valid_and_distinct is parametrized over t and _ephys_recording_probe_insertion. The long-name case fails on the previous commit (both names end in _da) and passes now.

@dimitri-yatsenko dimitri-yatsenko left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @mayuriphad. abaf481 fixes the index-name bug from the earlier review: the readable part is cut before the hash is added, and the long-table case is now tested. The code changes look ready.

What is still needed to merge:

  1. Rebase onto current master (or merge master into the branch). The branch is 26 commits behind. The failing checks on abaf481 come from that older base, not from this PR:

    • lint: codespell flags src/datajoint/condition.py:40, which master has since fixed.
    • test (minimum dependency versions, py3.10): two failures in tests/unit/test_path_confinement.py, which this PR does not touch.
    • unit-tests-windows: also failing on the old base.

    I merged master into this branch locally: there are no conflicts, and the unit suite passes (1073 passed).

  2. Green CI on both backends after the rebase. Locally, on the merged branch, tests/unit/test_declare_index.py, tests/integration/test_json_index.py, tests/integration/test_json.py and tests/integration/test_declare.py pass on MySQL and PostgreSQL (40 passed, 1 skipped). CI needs to confirm the same on the rebased head.

Optional, not blocking: test_declare_json_path_index could also check that both indexes exist after the declaration (for example, pg_indexes on PostgreSQL and SHOW INDEX on MySQL), since the bug was in the generated DDL.

Once the rebased branch is green, this is ready for final review.

…son-index

Signed-off-by: mayuriphad <mayuriphad656@gmail.com>
@mayuriphad

Copy link
Copy Markdown
Contributor Author

Thanks @dimitri-yatsenko. Merged current master into the branch in 60c1d9b (no conflicts, no force-push). tests/unit passes locally (1034 passed, 39 skipped). CI on the new head will confirm both backends.

@dimitri-yatsenko dimitri-yatsenko left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @mayuriphad. Everything from both earlier reviews is addressed:

  • abaf481 fixes the index-name bug: the readable part is cut before the hash is added, and plain-column names keep the old cut at 63 characters. The long-table case in test_expression_index_names_are_valid_and_distinct fails on 7612756 and passes on this head.
  • master is merged in (60c1d9b) with no conflicts, and the branch is now level with master. CI is green on this head, and the job log shows test_json_index.py running on both backends.

I also ran the tests locally on this head:

  • tests/unit passes (1073 passed).
  • tests/unit/test_declare_index.py and tests/integration/test_json_index.py, test_json.py, test_declare.py, test_fk_index.py, test_alter.py and test_multi_backend.py pass on MySQL and PostgreSQL: 70 passed, 5 skipped. The skips are the PostgreSQL-only foreign-key index tests on MySQL and the existing functional-index skip in test_json.py.
  • With the src/ changes reverted, four of the five unit tests fail. The PostgreSQL case of the integration test also fails, with the syntax error from the issue.
  • On PostgreSQL, pg_indexes lists every declared JSON-path index with its expression intact.

Two optional points, neither blocking:

  • The integration test could still check that the indexes exist. If you add that check, please query the catalog directly (pg_indexes on PostgreSQL, information_schema.statistics on MySQL) rather than heading.indexes. On PostgreSQL, heading.indexes is empty for now (#1699, which is being fixed separately). On MySQL it leaves out the JSON-path items.

  • The hash in create_index_ddl covers only the index items. Two tables whose names share their first 50 characters therefore get the same name for the same JSON-path index. PostgreSQL requires index names to be unique within a schema, so the second CREATE INDEX fails. I hit this with two part tables of one long-named master, spike_sorting_curation_parameters_set_for_probe_ins__alpha_part and spike_sorting_curation_parameters_set_for_probe_ins__beta_part, each with index(data.a:decimal(4,1)). Including the table name in the hash fixes it (src/datajoint/adapters/base.py, line 710):

                    digest = hashlib.md5("_".join([table_part, *columns]).encode()).hexdigest()[:8]

    With that change the unit tests still pass and both indexes are created. Plain-column index names can already collide the same way on very long table names, so this is not a regression. It can go in here or in a follow-up.

This is ready to merge from my side.

@dimitri-yatsenko
dimitri-yatsenko merged commit a63784d into datajoint:master Nov 24, 2026
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Index on a JSON path fails to declare on PostgreSQL

3 participants