Repository navigation
fix(declare): declare JSON-path indexes on PostgreSQL - #1684
Conversation
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>
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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.
| 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] |
There was a problem hiding this comment.
Cut the readable part before appending the hash, so the hash survives the 63-character limit and plain-column names stay as they are:
| 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] |
There was a problem hiding this comment.
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>
|
Thanks @dimitri-yatsenko. In abaf481, |
dimitri-yatsenko
left a comment
There was a problem hiding this comment.
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:
-
Rebase onto current
master(or mergemasterinto the branch). The branch is 26 commits behind. The failing checks on abaf481 come from that older base, not from this PR:lint: codespell flagssrc/datajoint/condition.py:40, whichmasterhas since fixed.test (minimum dependency versions, py3.10): two failures intests/unit/test_path_confinement.py, which this PR does not touch.unit-tests-windows: also failing on the old base.
I merged
masterinto this branch locally: there are no conflicts, and the unit suite passes (1073 passed). -
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.pyandtests/integration/test_declare.pypass 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>
|
Thanks @dimitri-yatsenko. Merged current |
dimitri-yatsenko
left a comment
There was a problem hiding this comment.
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_distinctfails on 7612756 and passes on this head. masteris merged in (60c1d9b) with no conflicts, and the branch is now level withmaster. CI is green on this head, and the job log showstest_json_index.pyrunning on both backends.
I also ran the tests locally on this head:
tests/unitpasses (1073 passed).tests/unit/test_declare_index.pyandtests/integration/test_json_index.py,test_json.py,test_declare.py,test_fk_index.py,test_alter.pyandtest_multi_backend.pypass 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 intest_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_indexeslists 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_indexeson PostgreSQL,information_schema.statisticson MySQL) rather thanheading.indexes. On PostgreSQL,heading.indexesis empty for now (#1699, which is being fixed separately). On MySQL it leaves out the JSON-path items. -
The hash in
create_index_ddlcovers 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 secondCREATE INDEXfails. I hit this with two part tables of one long-named master,spike_sorting_curation_parameters_set_for_probe_ins__alpha_partandspike_sorting_curation_parameters_set_for_probe_ins__beta_part, each withindex(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.
Fixes #1672.
On PostgreSQL,
declare()turns each compiled index into a separateCREATE INDEX. It re-parsed the compiled text withindex\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: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.pycreate_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:
MySQL is unaffected: it keeps the inline index from
compile_index.Tests
tests/unit/test_declare_index.pychecks 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 onmaster; the plain-column one passes on both.tests/integration/test_json_index.pydeclares a table with a JSON-path index and a mixed unique index on both backends (connection_by_backend) and inserts into it. It usesdecimal(4,1)andchar(20)because MySQL'sJSON_VALUE ... RETURNINGdoes not acceptintegerorvarchar, so thedata.size:integerexample from the issue still fails on MySQL. That is a separate problem in the MySQL type mapping, which this PR leaves alone.ruff checkandruff format --check(v0.8.4, the pre-commit pin) pass on the changed files.