From cc86920c57bbf401663f3c5b1cda5ac8afcfabd6 Mon Sep 17 00:00:00 2001 From: Dimitri Yatsenko Date: Mon, 23 Nov 2026 17:08:41 -0600 Subject: [PATCH 1/6] fix(migrate): 0.14 blob@, attach@ and filepath@ columns read in 2.x after migration migrate_external wrote a url built from a NULL filepath, the 32-digit hex hash, no path or store, and a :blob@store: comment that the heading does not read. It now writes {hash, path, schema, store, size}, with the path where 0.14 stored the file and the same MD5 digest in base32, and a :: comment. Migrated attachments record their name, which get_hash puts back before checking the hash, as 0.14 hashed it. migrate_filepath matches 0.14's binary(16) columns and writes filepath metadata from the tracking table. migrate_external_pointers_v2 writes the same metadata and refuses a binary(16) column. verify_external_integrity derives blob and attachment paths, and verify_schema_v20 escapes % in LIKE. Every referenced file is looked up before anything changes; a missing file stops the migration with the schema unchanged. Fixes #1698 --- src/datajoint/hash_registry.py | 13 +- src/datajoint/migrate.py | 569 +++++++++++------- .../test_migrate_legacy_external.py | 321 ++++++++++ tests/unit/test_migrate_legacy_store.py | 138 +++++ 4 files changed, 813 insertions(+), 228 deletions(-) create mode 100644 tests/integration/test_migrate_legacy_external.py create mode 100644 tests/unit/test_migrate_legacy_store.py diff --git a/src/datajoint/hash_registry.py b/src/datajoint/hash_registry.py index 7a14c76f7..325eb0b88 100644 --- a/src/datajoint/hash_registry.py +++ b/src/datajoint/hash_registry.py @@ -265,7 +265,8 @@ def get_hash(metadata: dict[str, Any], config: Config | None = None) -> bytes: Parameters ---------- metadata : dict - Metadata dict with keys: path, hash, store (optional). + Metadata dict with keys: path, hash, store (optional), and + attachment_name (only on attachments migrated from DataJoint 0.14). config : Config, optional Config instance. If None, falls back to global settings.config. @@ -280,6 +281,13 @@ def get_hash(metadata: dict[str, Any], config: Config | None = None) -> bytes: If content is not found at the stored path. DataJointError If hash verification fails (data corruption). + + Notes + ----- + DataJoint 0.14 stored an attachment's contents alone in its file, and hashed + the attachment name, a NUL byte, and the contents. Those are the bytes that + ```` stores, so for a migrated attachment the name is put back in + front of the contents before the hash is checked. """ path = metadata["path"] expected_hash = metadata["hash"] @@ -287,6 +295,9 @@ def get_hash(metadata: dict[str, Any], config: Config | None = None) -> bytes: backend = get_store_backend(store_name, config=config) data = backend.get_buffer(path) + attachment_name = metadata.get("attachment_name") + if attachment_name is not None: + data = attachment_name.encode("utf-8") + b"\x00" + data # Verify hash for integrity actual_hash = compute_hash(data) diff --git a/src/datajoint/migrate.py b/src/datajoint/migrate.py index b78f00750..4867bce06 100644 --- a/src/datajoint/migrate.py +++ b/src/datajoint/migrate.py @@ -19,9 +19,12 @@ from __future__ import annotations +import base64 +import json import logging import re import warnings +from collections.abc import Mapping from typing import TYPE_CHECKING from packaging.version import Version @@ -871,13 +874,14 @@ def _find_filepath_columns(schema: Schema) -> list[dict]: tables = connection.query(tables_query, args=(schema.database,)).fetchall() for (table_name,) in tables: - # Find VARCHAR columns with :filepath: in comment + # Find BINARY(16) columns with :filepath@store: in comment (0.x filepath format) columns_query = """ SELECT COLUMN_NAME, COLUMN_TYPE, COLUMN_COMMENT FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = %s AND TABLE_NAME = %s - AND DATA_TYPE = 'varchar' + AND DATA_TYPE = 'binary' + AND CHARACTER_MAXIMUM_LENGTH = 16 AND COLUMN_COMMENT LIKE '%%:filepath%%' """ columns = connection.query(columns_query, args=(schema.database, table_name)).fetchall() @@ -900,6 +904,239 @@ def _find_filepath_columns(schema: Schema) -> list[dict]: return results +# In 0.14, each in-store column held a 16-byte MD5 digest in a BINARY(16) column, +# and the store's `~external_` table tracked one row per digest: +# +# - a blob: the digest of its serialized bytes, stored at +# `{database}/{subfolders}/{hex digest}`; +# - an attachment: the digest of its name, a NUL byte, and its contents, stored +# (contents only) at `{database}/{subfolders}/{hex digest}.{attachment_name}`; +# - a filepath: the digest of its relative path, stored at `filepath`; +# - a blob migrated from 0.11: stored at `filepath`, with the digest of its +# serialized bytes in `contents_hash`. +# +# Subfolders come from the store's `subfolding` setting, (2, 2) unless set. +LEGACY_SUBFOLDING = (2, 2) + + +def _legacy_subfolding(store_name: str, config=None) -> tuple[int, ...]: + """ + Return the subfolding 0.14 used for a store. + + This is the store's own ``subfolding`` setting, or 0.14's default of (2, 2) + when it has none. The raw setting is read because 2.x defaults to no + subfolding. ``config`` defaults to the global settings. + """ + if config is None: + from .settings import config + + spec = config.stores.get(store_name) + if isinstance(spec, Mapping) and "subfolding" in spec: + return tuple(spec["subfolding"] or ()) + return LEGACY_SUBFOLDING + + +def _legacy_hash(digest: bytes) -> str: + """ + Return the 2.x hash for a 0.14 content digest. + + Both versions take the MD5 digest of the same bytes. 2.x writes it in base32, + as `hash_registry.compute_hash` does, so reads check migrated values as they + check any other. + """ + return base64.b32encode(digest).decode("ascii").rstrip("=").lower() + + +def _legacy_path( + database: str, + digest: bytes, + subfolding: tuple[int, ...], + attachment_name: str | None = None, +) -> str: + """Return the store-relative path of a 0.14 blob or, given its name, attachment.""" + from .hash_registry import _subfold + + hex_digest = digest.hex() + name = hex_digest if attachment_name is None else f"{hex_digest}.{attachment_name}" + return "/".join((database, *_subfold(hex_digest, subfolding), name)) + + +def _plan_legacy_references( + connection, + database: str, + table_name: str, + column_name: str, + kind: str, + store_name: str, + dest_store: str | None = None, +) -> tuple[dict[bytes, dict], list[str]]: + """ + Build the 2.x metadata for each 0.14 reference in one column. + + Parameters + ---------- + connection : Connection + Database connection. + database, table_name, column_name : str + The column holding 0.14 BINARY(16) references. + kind : str + ``"blob"``, ``"attach"``, or ``"filepath"``. + store_name : str + The 0.14 store; its references are tracked in ``~external_``. + dest_store : str, optional + The 2.x store the metadata names. Defaults to ``store_name``. Files are + looked up through this store, so it must point at the 0.14 location. + + Returns + ------- + tuple[dict[bytes, dict], list[str]] + The metadata for each referenced digest, and a description of each + reference that cannot be converted: one with no tracking row, or whose + file is not in the store. + """ + from .hash_registry import get_store_backend + + dest_store = dest_store or store_name + config = getattr(connection, "_config", None) # the config reads resolve stores with + backend = get_store_backend(dest_store, config=config) + subfolding = _legacy_subfolding(dest_store, config) + + rows = connection.query( + f""" + SELECT DISTINCT t.`{column_name}`, e.hash, e.size, e.attachment_name, + e.filepath, e.contents_hash, e.timestamp + FROM `{database}`.`{table_name}` t + LEFT JOIN `{database}`.`~external_{store_name}` e ON e.hash = t.`{column_name}` + WHERE t.`{column_name}` IS NOT NULL + """ + ).fetchall() + + metadata: dict[bytes, dict] = {} + problems: list[str] = [] + for reference, tracked, size, attachment_name, filepath, contents_hash, timestamp in rows: + reference = bytes(reference) + label = f"{reference.hex()} in {database}.{table_name}.{column_name}" + if tracked is None: + problems.append(f"{label}: no row in ~external_{store_name}") + continue + + if kind == "filepath": + path, digest = filepath, None + elif kind == "attach": + path = None if attachment_name is None else _legacy_path(database, reference, subfolding, attachment_name) + digest = reference + elif filepath: # a blob migrated from 0.11 + path, digest = filepath, contents_hash + else: + path, digest = _legacy_path(database, reference, subfolding), reference + if path is None or (kind != "filepath" and digest is None): + problems.append(f"{label}: the tracking row in ~external_{store_name} is incomplete") + continue + + try: + found = backend.exists(path) + except DataJointError as error: + problems.append(f"{label}: {error}") + continue + if not found: + problems.append(f"{label}: no file at {path} in store '{dest_store}'") + continue + + if kind == "filepath": + metadata[reference] = { + "path": path, + "store": dest_store, + "size": size, + "is_dir": False, + "timestamp": timestamp.isoformat() if timestamp else None, + } + else: + metadata[reference] = { + "hash": _legacy_hash(bytes(digest)), + "path": path, + "schema": database, + "store": dest_store, + "size": size, + } + if kind == "attach": + metadata[reference]["attachment_name"] = attachment_name + return metadata, problems + + +def _refuse_problems(where: str, problems: list[str]) -> None: + """Raise if any reference cannot be converted. Called before anything is changed.""" + if problems: + listed = "\n ".join(problems[:10]) + more = f"\n ... and {len(problems) - 10} more" if len(problems) > 10 else "" + raise DataJointError( + f"Cannot migrate {where}: {len(problems)} reference(s) cannot be converted. " + f"Nothing was changed.\n {listed}{more}" + ) + + +def _plan_columns(connection, database: str, columns: list[dict], dry_run: bool, kind: str | None = None) -> dict: + """ + Plan the conversion of each column not yet migrated, keyed by (table, column). + + Every reference in every column is looked up before anything is changed, so + that one missing file stops the migration with the schema unchanged. A dry + run reports the problems instead of raising. + """ + plans = {} + for col in columns: + table_name, column_name = col["table_name"], col["column_name"] + exists = connection.query( + """ + SELECT COUNT(*) FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = %s AND TABLE_NAME = %s AND COLUMN_NAME = %s + """, + args=(database, table_name, f"{column_name}_v2"), + ).fetchone()[0] + if not exists: + plans[table_name, column_name] = _plan_legacy_references( + connection, database, table_name, column_name, kind or col["external_type"], col["store_name"] + ) + if not dry_run: + _refuse_problems(database, [problem for _, problems in plans.values() for problem in problems]) + return plans + + +def _add_converted_column( + connection, + database: str, + table_name: str, + column_name: str, + new_column: str, + comment: str, + metadata: dict[bytes, dict], +) -> int: + """ + Add ``new_column`` as JSON and fill it with the metadata for each reference. + + If any reference is left unconverted, or any step fails, the new column is + dropped again so that a later run starts over. Returns the number of rows + converted. + """ + table = f"`{database}`.`{table_name}`" + connection.query(f"ALTER TABLE {table} ADD COLUMN `{new_column}` JSON COMMENT '{comment}'") + try: + with connection.transaction: + for reference, value in metadata.items(): + connection.query( + f"UPDATE {table} SET `{new_column}` = %s WHERE `{column_name}` = %s", + args=(json.dumps(value), reference), + ) + unconverted = connection.query( + f"SELECT COUNT(*) FROM {table} WHERE `{column_name}` IS NOT NULL AND `{new_column}` IS NULL" + ).fetchone()[0] + if unconverted: + raise DataJointError(f"{unconverted} row(s) of {database}.{table_name}.{column_name} were not converted") + except Exception: + connection.query(f"ALTER TABLE {table} DROP COLUMN `{new_column}`") + raise + return connection.query(f"SELECT COUNT(*) FROM {table} WHERE `{new_column}` IS NOT NULL").fetchone()[0] + + def migrate_external( schema: Schema, dry_run: bool = True, @@ -916,8 +1153,8 @@ def migrate_external( 2. **Verification**: You verify all data is accessible via DataJoint 2.0. - 3. **Finalize** (finalize=True): Renames columns (old → `_v1`, new → original - name) and optionally drops the old columns. + 3. **Finalize** (dry_run=False, finalize=True): Renames columns (old → `_v1`, + new → original name). This allows 0.x and 2.0 to coexist during migration and provides a rollback path if issues are discovered. @@ -957,14 +1194,18 @@ def migrate_external( >>> # Step 3: Verify data is accessible via DataJoint 2.0 >>> # ... manual verification ... >>> - >>> # Step 4: Finalize (rename columns, drop old) - >>> result = migrate_external(schema, finalize=True) + >>> # Step 4: Finalize (rename columns) + >>> result = migrate_external(schema, dry_run=False, finalize=True) Notes ----- - The migration reads from the hidden `~external_` tables to build - JSON metadata. Ensure store configuration in datajoint.json matches the - paths stored in these tables. + The migration reads the hidden `~external_` tables and finds each + file where 0.14 stored it. Configure each store under its 0.14 name, with + its 0.14 location and, if 0.14 set one, its `subfolding`. + + Every referenced file is looked up before anything is changed. If a + reference has no tracking row or its file is missing, the migration raises + and changes nothing; a dry run lists these references under `problems`. """ columns = _find_external_columns(schema) connection = schema.connection @@ -981,6 +1222,8 @@ def migrate_external( logger.info(f"No external columns found in {database}") return result + plans = {} if finalize else _plan_columns(connection, database, columns, dry_run) + for col in columns: table_name = col["table_name"] column_name = col["column_name"] @@ -997,11 +1240,10 @@ def migrate_external( "rows": 0, } - # Build new comment + # Build new comment: the 2.x codec marker, then the rest of the comment codec = "blob" if external_type == "blob" else "attach" - # Remove old :external...: pattern from comment new_comment = EXTERNAL_PATTERNS[external_type].sub("", old_comment).strip() - new_comment = f":{codec}@{store_name}: {new_comment}".strip() + new_comment = f":<{codec}@{store_name}>:{new_comment}" new_column = f"{column_name}_v2" @@ -1046,20 +1288,13 @@ def migrate_external( # Initial migration: add new column and copy data detail["action"] = "migrate" - # Check if _v2 column already exists - existing = connection.query( - """ - SELECT COLUMN_NAME FROM information_schema.COLUMNS - WHERE TABLE_SCHEMA = %s AND TABLE_NAME = %s AND COLUMN_NAME = %s - """, - args=(database, table_name, new_column), - ).fetchone() - - if existing: + # Skip columns whose _v2 column already exists + if (table_name, column_name) not in plans: detail["status"] = "already_migrated" logger.info(f"Column {new_column} already exists, skipping") result["details"].append(detail) continue + metadata, problems = plans[table_name, column_name] if dry_run: # Count rows that would be migrated @@ -1069,49 +1304,16 @@ def migrate_external( """ count = connection.query(count_sql).fetchone()[0] detail["rows"] = count + detail["problems"] = problems detail["status"] = "dry_run" logger.info(f"Would migrate {database}.{table_name}.{column_name}: " f"{count} rows, store={store_name}") + for problem in problems: + logger.warning(f"Cannot migrate {problem}") else: try: - # Add new JSON column - sql = ( - f"ALTER TABLE `{database}`.`{table_name}` " - f"ADD COLUMN `{new_column}` JSON " - f"COMMENT '{new_comment}'" + count = _add_converted_column( + connection, database, table_name, column_name, new_column, new_comment, metadata ) - connection.query(sql) - - # Copy and convert data from old column - # Query the external table for metadata - external_table = f"~external_{store_name}" - - # Get store config for URL building - from .settings import config - - store_config = config.get("stores", {}).get(store_name, {}) - protocol = store_config.get("protocol", "file") - location = store_config.get("location", "") - - # Update rows with JSON metadata - update_sql = f""" - UPDATE `{database}`.`{table_name}` t - JOIN `{database}`.`{external_table}` e - ON t.`{column_name}` = e.hash - SET t.`{new_column}` = JSON_OBJECT( - 'url', CONCAT('{protocol}://', '{location}/', e.filepath), - 'size', e.size, - 'hash', HEX(e.hash) - ) - WHERE t.`{column_name}` IS NOT NULL - """ - connection.query(update_sql) - - # Count migrated rows - count_sql = f""" - SELECT COUNT(*) FROM `{database}`.`{table_name}` - WHERE `{new_column}` IS NOT NULL - """ - count = connection.query(count_sql).fetchone()[0] detail["rows"] = count detail["status"] = "migrated" result["columns_migrated"] += 1 @@ -1334,7 +1536,7 @@ def verify_external_integrity(schema: Schema, store_name: str = None) -> dict: # Query external table for all entries try: entries_query = f""" - SELECT HEX(hash), filepath, size + SELECT hash, filepath, size, attachment_name FROM `{schema.database}`.`{table_name}` """ entries = connection.query(entries_query).fetchall() @@ -1342,14 +1544,17 @@ def verify_external_integrity(schema: Schema, store_name: str = None) -> dict: logger.warning(f"Could not read {table_name}: {e}") continue - for hash_hex, filepath, size in entries: + subfolding = _legacy_subfolding(current_store, config) + for digest, filepath, size, attachment_name in entries: result["total_references"] += 1 - # Build full path + # Filepaths (and blobs migrated from 0.11) record their path; blobs and + # attachments are stored at a path derived from their hash. + relative_path = filepath or _legacy_path(schema.database, bytes(digest), subfolding, attachment_name) if location: - full_path = os.path.join(location, filepath) + full_path = os.path.join(location, relative_path) else: - full_path = filepath + full_path = relative_path if os.path.exists(full_path): result["valid"] += 1 @@ -1357,8 +1562,8 @@ def verify_external_integrity(schema: Schema, store_name: str = None) -> dict: result["missing"].append( { "store": current_store, - "hash": hash_hex, - "filepath": filepath, + "hash": bytes(digest).hex().upper(), + "filepath": relative_path, "full_path": full_path, "expected_size": size, } @@ -1510,9 +1715,12 @@ def migrate_filepath( Same multi-step approach as migrate_external: - 1. **Initial run**: Adds new `_v2` columns with JSON type + 1. **Initial run** (dry_run=False): Adds new `_v2` columns with JSON type 2. **Verification**: Verify files accessible via DataJoint 2.0 - 3. **Finalize**: Rename columns and drop old + 3. **Finalize** (dry_run=False, finalize=True): Rename columns (old → `_v1`) + + As with migrate_external, every referenced file is looked up first, and the + migration raises and changes nothing if one is missing. Parameters ---------- @@ -1539,7 +1747,7 @@ def migrate_filepath( >>> result = migrate_filepath(schema, dry_run=False) >>> >>> # Finalize after verification - >>> result = migrate_filepath(schema, finalize=True) + >>> result = migrate_filepath(schema, dry_run=False, finalize=True) """ columns = _find_filepath_columns(schema) connection = schema.connection @@ -1556,6 +1764,8 @@ def migrate_filepath( logger.info(f"No filepath columns found in {database}") return result + plans = {} if finalize else _plan_columns(connection, database, columns, dry_run, kind="filepath") + for col in columns: table_name = col["table_name"] column_name = col["column_name"] @@ -1570,9 +1780,9 @@ def migrate_filepath( "rows": 0, } - # Build new comment + # Build new comment: the 2.x codec marker, then the rest of the comment new_comment = FILEPATH_PATTERN.sub("", old_comment).strip() - new_comment = f":filepath@{store_name}: {new_comment}".strip() + new_comment = f"::{new_comment}" new_column = f"{column_name}_v2" @@ -1611,19 +1821,12 @@ def migrate_filepath( else: detail["action"] = "migrate" - # Check if _v2 column already exists - existing = connection.query( - """ - SELECT COLUMN_NAME FROM information_schema.COLUMNS - WHERE TABLE_SCHEMA = %s AND TABLE_NAME = %s AND COLUMN_NAME = %s - """, - args=(database, table_name, new_column), - ).fetchone() - - if existing: + # Skip columns whose _v2 column already exists + if (table_name, column_name) not in plans: detail["status"] = "already_migrated" result["details"].append(detail) continue + metadata, problems = plans[table_name, column_name] if dry_run: count_sql = f""" @@ -1632,40 +1835,16 @@ def migrate_filepath( """ count = connection.query(count_sql).fetchone()[0] detail["rows"] = count + detail["problems"] = problems detail["status"] = "dry_run" logger.info(f"Would migrate {database}.{table_name}.{column_name}: " f"{count} rows") + for problem in problems: + logger.warning(f"Cannot migrate {problem}") else: try: - # Get store config - from .settings import config - - store_config = config.get("stores", {}).get(store_name, {}) - protocol = store_config.get("protocol", "file") - location = store_config.get("location", "") - - # Add new JSON column - sql = ( - f"ALTER TABLE `{database}`.`{table_name}` " - f"ADD COLUMN `{new_column}` JSON " - f"COMMENT '{new_comment}'" + count = _add_converted_column( + connection, database, table_name, column_name, new_column, new_comment, metadata ) - connection.query(sql) - - # Convert filepath to JSON with URL - update_sql = f""" - UPDATE `{database}`.`{table_name}` - SET `{new_column}` = JSON_OBJECT( - 'url', CONCAT('{protocol}://', '{location}/', `{column_name}`) - ) - WHERE `{column_name}` IS NOT NULL - """ - connection.query(update_sql) - - count_sql = f""" - SELECT COUNT(*) FROM `{database}`.`{table_name}` - WHERE `{new_column}` IS NOT NULL - """ - count = connection.query(count_sql).fetchone()[0] detail["rows"] = count detail["status"] = "migrated" result["columns_migrated"] += 1 @@ -2125,7 +2304,7 @@ def verify_schema_v20( columns_query = """ SELECT TABLE_NAME, COLUMN_NAME, COLUMN_TYPE, COLUMN_COMMENT FROM information_schema.COLUMNS - WHERE TABLE_SCHEMA = %s AND COLUMN_TYPE LIKE '%blob' + WHERE TABLE_SCHEMA = %s AND COLUMN_TYPE LIKE '%%blob' """ blob_columns = connection.query(columns_query, args=(schema,)).fetchall() @@ -2153,8 +2332,8 @@ def migrate_external_pointers_v2( """ Migrate external storage pointers from 0.14.6 to 2.0 format. - Converts BINARY(16) UUID references to JSON metadata format. - Optionally copies blob files to new storage location. + Converts the 16-byte 0.14 references in one column to JSON metadata, + in place. File copying (``copy_files``) is not implemented yet. This is useful when copying production data to _v2 schemas and you need to access external storage attributes but don't want to move the files yet. @@ -2182,7 +2361,8 @@ def migrate_external_pointers_v2( dict - rows_migrated: int - number of pointers migrated - files_copied: int - number of files copied (if copy_files=True) - - errors: list - any errors encountered + - errors: list - always empty; a reference that cannot be converted + raises before any row is updated Examples -------- @@ -2200,24 +2380,22 @@ def migrate_external_pointers_v2( Notes ----- This function: - 1. Reads BINARY(16) UUID from table column - 2. Looks up file in ~external_{source_store} table - 3. Creates JSON metadata with file path - 4. Optionally copies file to new store location - 5. Updates column with JSON metadata - - The JSON format is: - { - "path": "schema/table/key_hash/file.ext", - "size": 12345, - "hash": null, - "ext": ".dat", - "is_dir": false, - "timestamp": "2025-01-14T10:30:00+00:00" - } + 1. Reads the BINARY(16) references in the column + 2. Looks each one up in the ~external_{source_store} table + 3. Finds its file where 0.14 stored it, through ``dest_store`` + 4. Updates the column with JSON metadata + + It writes the same metadata as ``migrate_external``: + ``{hash, path, schema, store, size}`` for blobs and attachments (attachments + also record ``attachment_name``) and ``{path, store, size, is_dir, timestamp}`` + for filepaths. + + The column must already be able to hold the JSON metadata. A column still in + the 0.14 layout (BINARY(16)) is refused; ``migrate_external`` and + ``migrate_filepath`` convert such columns in place. Every reference is looked + up before any row is updated: if one has no tracking row or its file is + missing, the function raises and changes nothing. """ - import json - from datetime import datetime, timezone from . import conn as get_conn if connection is None: @@ -2248,107 +2426,44 @@ def migrate_external_pointers_v2( "errors": [], } - # Query rows with external attributes - query = f""" - SELECT * FROM `{schema}`.`{table}` - WHERE `{attribute}` IS NOT NULL - """ - - rows = connection.query(query).fetchall() - - # Get column info to identify UUID column - col_query = """ - SELECT ORDINAL_POSITION, COLUMN_NAME + # Find the column and what its 0.14 type was + column = connection.query( + """ + SELECT DATA_TYPE, CHARACTER_MAXIMUM_LENGTH, COLUMN_COMMENT FROM information_schema.COLUMNS - WHERE TABLE_SCHEMA = %s AND TABLE_NAME = %s - ORDER BY ORDINAL_POSITION - """ - columns = connection.query(col_query, args=(schema, table)).fetchall() - col_names = [col[1] for col in columns] - - # Find attribute column index - try: - attr_idx = col_names.index(attribute) - except ValueError: + WHERE TABLE_SCHEMA = %s AND TABLE_NAME = %s AND COLUMN_NAME = %s + """, + args=(schema, table, attribute), + ).fetchone() + if column is None: raise DataJointError(f"Attribute {attribute} not found in {schema}.{table}") + data_type, max_length, comment = column - for row in rows: - uuid_bytes = row[attr_idx] - - if uuid_bytes is None: - continue - - # Look up file info in external tracking table - lookup_query = f""" - SELECT hash, size, timestamp, filepath - FROM `{schema}`.`{external_table}` - WHERE hash = %s - """ - - file_info = connection.query(lookup_query, args=(uuid_bytes,)).fetchone() - - if file_info is None: - result["errors"].append(f"External file not found for UUID: {uuid_bytes.hex()}") - continue - - hash_hex, size, timestamp, filepath = file_info - - # Build JSON metadata - # Extract extension from filepath - import os - - ext = os.path.splitext(filepath)[1] if filepath else "" - - metadata = { - "path": filepath, - "size": size, - "hash": hash_hex.hex() if hash_hex else None, - "ext": ext, - "is_dir": False, - "timestamp": timestamp.isoformat() if timestamp else datetime.now(timezone.utc).isoformat(), - } - - # Update row with JSON metadata - # Build WHERE clause from primary keys - pk_columns = [] - pk_values = [] - - # Get primary key info - pk_query = """ - SELECT COLUMN_NAME - FROM information_schema.KEY_COLUMN_USAGE - WHERE TABLE_SCHEMA = %s - AND TABLE_NAME = %s - AND CONSTRAINT_NAME = 'PRIMARY' - ORDER BY ORDINAL_POSITION - """ - pk_cols = connection.query(pk_query, args=(schema, table)).fetchall() - - for pk_col in pk_cols: - pk_name = pk_col[0] - pk_idx = col_names.index(pk_name) - pk_columns.append(pk_name) - pk_values.append(row[pk_idx]) - - # Build UPDATE statement - where_parts = [f"`{col}` = %s" for col in pk_columns] - where_clause = " AND ".join(where_parts) - - update_query = f""" - UPDATE `{schema}`.`{table}` - SET `{attribute}` = %s - WHERE {where_clause} - """ + patterns = {**EXTERNAL_PATTERNS, "filepath": FILEPATH_PATTERN} + kind = next((name for name, pattern in patterns.items() if pattern.search(comment or "")), None) + if kind is None: + raise DataJointError( + f"{schema}.{table}.{attribute} has no 0.14 in-store type (blob@, attach@, or filepath@) in its comment." + ) + if data_type.lower() == "binary" and max_length == 16: + raise DataJointError( + f"{schema}.{table}.{attribute} is a 0.14 BINARY(16) column and cannot hold JSON metadata. " + f"Use migrate_external or migrate_filepath to convert it in place." + ) - connection.query(update_query, args=(json.dumps(metadata), *pk_values)) + metadata, problems = _plan_legacy_references(connection, schema, table, attribute, kind, source_store, dest_store) + _refuse_problems(f"{schema}.{table}.{attribute}", problems) - result["rows_migrated"] += 1 + if copy_files: + logger.warning("File copying not yet implemented in migrate_external_pointers_v2") - # Copy file if requested - if copy_files: - # TODO: Implement file copying using fsspec - # This requires knowing source and dest store locations - logger.warning("File copying not yet implemented in migrate_external_pointers_v2") + with connection.transaction: + for reference, value in metadata.items(): + cursor = connection.query( + f"UPDATE `{schema}`.`{table}` SET `{attribute}` = %s WHERE `{attribute}` = %s", + args=(json.dumps(value), reference), + ) + result["rows_migrated"] += cursor.rowcount logger.info(f"Migrated {result['rows_migrated']} external pointers for {schema}.{table}.{attribute}") diff --git a/tests/integration/test_migrate_legacy_external.py b/tests/integration/test_migrate_legacy_external.py new file mode 100644 index 000000000..6078100cb --- /dev/null +++ b/tests/integration/test_migrate_legacy_external.py @@ -0,0 +1,321 @@ +"""Migrating a DataJoint 0.14 schema's in-store columns, then reading them in 2.x. + +The fixture lays a schema out as 0.14.6 does (``declare.py``, ``external.py`` and +``hash.py`` at that tag): a ``~external_legacy`` tracking table, ``binary(16)`` +columns with 0.14 comments and foreign keys to it, and files at 0.14's paths. The +blobs are serialized by 0.14.6's own ``blob.pack``. 0.14 ran on MySQL only, so +the fixture does too; the read of a migrated attachment runs on both backends. +""" + +import hashlib +import json +from pathlib import Path + +import numpy as np +import pytest + +import datajoint as dj +from datajoint.errors import DataJointError +from datajoint.hash_registry import compute_hash, get_hash +from datajoint.migrate import ( + _legacy_hash, + _legacy_path, + migrate_external, + migrate_external_pointers_v2, + migrate_filepath, + verify_external_integrity, + verify_schema_v20, +) + +# np.array([[1.5, -2.0, 3.25], [4.0, 5.5, -6.75]]), packed by DataJoint 0.14.6 +SIGNAL = np.array([[1.5, -2.0, 3.25], [4.0, 5.5, -6.75]]) +SIGNAL_BLOB = bytes.fromhex( + "6d596d00410200000000000000020000000000000003000000000000000600000000000000000000000000f83f" + "000000000000104000000000000000c000000000000016400000000000000a400000000000001bc0" +) +# np.array([10, 20, 30, 40], dtype=np.int64), packed by DataJoint 0.14.6 +COUNTS = np.array([10, 20, 30, 40], dtype=np.int64) +COUNTS_BLOB = bytes.fromhex( + "6d596d0041010000000000000004000000000000000e000000000000000a0000000000000014000000000000001e000000000000002800000000000000" +) +REPORT_NAME = "report.txt" +REPORT = b"spike count: 12\n" +RAW_PATH = "acquisition/session1/raw.dat" +RAW = b"raw samples" + +# DDL as 0.14.6 declares ExternalTable.definition and a table using blob@, attach@, filepath@ +HASH_COMMENT = ":uuid:hash of contents (blob), of filename + contents (attach), or relative filepath (filepath)" +EXTERNAL_TABLE_DDL = """ +CREATE TABLE `{db}`.`~external_legacy` ( +`hash` binary(16) NOT NULL COMMENT "{hash_comment}", +`size` bigint unsigned NOT NULL COMMENT "size of object in bytes", +`attachment_name` varchar(255) DEFAULT NULL COMMENT "the filename of an attachment", +`filepath` varchar(1000) DEFAULT NULL COMMENT "relative filepath or attachment filename", +`contents_hash` binary(16) DEFAULT NULL COMMENT ":uuid:used for the filepath datatype", +`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT "automatic timestamp", +PRIMARY KEY (`hash`) +) ENGINE=InnoDB, COMMENT "external storage tracking" +""" +RECORDING_DDL = """ +CREATE TABLE `{db}`.`recording` ( +`recording_id` int NOT NULL, +`signal` binary(16) NOT NULL COMMENT ":blob@legacy:raw signal", +`report` binary(16) DEFAULT NULL COMMENT ":attach@legacy:report file", +`raw_file` binary(16) DEFAULT NULL COMMENT ":filepath@legacy:acquired file", +PRIMARY KEY (`recording_id`), +FOREIGN KEY (`signal`) REFERENCES `{db}`.`~external_legacy` (`hash`) ON UPDATE RESTRICT ON DELETE RESTRICT, +FOREIGN KEY (`report`) REFERENCES `{db}`.`~external_legacy` (`hash`) ON UPDATE RESTRICT ON DELETE RESTRICT, +FOREIGN KEY (`raw_file`) REFERENCES `{db}`.`~external_legacy` (`hash`) ON UPDATE RESTRICT ON DELETE RESTRICT +) ENGINE=InnoDB, COMMENT "recordings" +""" + + +def _md5(data: bytes) -> bytes: + return hashlib.md5(data).digest() + + +@pytest.fixture +def legacy_store(tmp_path): + """Configure store `legacy` (no subfolding set, so 0.14 used (2, 2)) and a download path.""" + location = tmp_path / "legacy_store" + location.mkdir() + saved_stores, saved_download = dict(dj.config.stores), dj.config.get("download_path") + dj.config.stores["legacy"] = {"protocol": "file", "location": str(location)} + dj.config["download_path"] = str(tmp_path / "downloads") + yield location + dj.config.stores.clear() + dj.config.stores.update(saved_stores) + dj.config["download_path"] = saved_download + + +@pytest.fixture +def schema014(connection_test, prefix, legacy_store): + """A schema laid out as 0.14.6 lays it out, with its files in the store.""" + db = f"{prefix}_legacy014" + connection_test.query(f"DROP DATABASE IF EXISTS `{db}`") + connection_test.query(f"CREATE DATABASE `{db}`") + connection_test.query(EXTERNAL_TABLE_DDL.format(db=db, hash_comment=HASH_COMMENT)) + connection_test.query(RECORDING_DDL.format(db=db)) + + def put(path, data): + file = legacy_store / path + file.parent.mkdir(parents=True, exist_ok=True) + file.write_bytes(data) + + def track(digest, size, attachment_name=None, filepath=None, contents_hash=None): + connection_test.query( + f"INSERT INTO `{db}`.`~external_legacy` (hash, size, attachment_name, filepath, contents_hash) " + "VALUES (%s, %s, %s, %s, %s)", + args=(digest, size, attachment_name, filepath, contents_hash), + ) + + # Blob: ExternalTable.put + signal = _md5(SIGNAL_BLOB) + put(f"{db}/{signal.hex()[:2]}/{signal.hex()[2:4]}/{signal.hex()}", SIGNAL_BLOB) + track(signal, len(SIGNAL_BLOB)) + # Attachment: ExternalTable.upload_attachment + report = _md5((REPORT_NAME + "\0").encode() + REPORT) + put(f"{db}/{report.hex()[:2]}/{report.hex()[2:4]}/{report.hex()}.{REPORT_NAME}", REPORT) + track(report, len(REPORT), attachment_name=REPORT_NAME) + # Filepath: ExternalTable.upload_filepath + raw = _md5(RAW_PATH.encode()) + put(RAW_PATH, RAW) + track(raw, len(RAW), filepath=RAW_PATH, contents_hash=_md5(RAW)) + # Blob migrated from 0.11: kept at an explicit path, hash of the path, contents_hash of the bytes + counts_path = f"{db}/0123456789abcdefABCDEF0123456789abcdefABCDE" + counts = _md5(counts_path.encode()) + put(counts_path, COUNTS_BLOB) + track(counts, len(COUNTS_BLOB), filepath=counts_path, contents_hash=_md5(COUNTS_BLOB)) + + connection_test.query( + f"INSERT INTO `{db}`.`recording` VALUES (1, %s, %s, %s), (2, %s, NULL, NULL)", + args=(signal, report, raw, counts), + ) + schema = dj.Schema(db, connection=connection_test) + yield schema + connection_test.query(f"DROP DATABASE IF EXISTS `{db}`") + + +def _recording(schema): + return dj.FreeTable(schema.connection, f"`{schema.database}`.`recording`") + + +def _columns(schema): + rows = schema.connection.query( + "SELECT COLUMN_NAME FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = %s AND TABLE_NAME = 'recording'", + args=(schema.database,), + ).fetchall() + return {name for (name,) in rows} + + +def _migrate(schema): + """The guide's in-place steps for in-store columns.""" + preview = migrate_external(schema, dry_run=True) + assert preview["columns_found"] == 2 + assert all(detail["problems"] == [] for detail in preview["details"]) + assert migrate_external(schema, dry_run=False)["rows_migrated"] == 3 + assert migrate_filepath(schema, dry_run=False)["rows_migrated"] == 1 + assert migrate_external(schema, dry_run=False, finalize=True)["columns_migrated"] == 2 + assert migrate_filepath(schema, dry_run=False, finalize=True)["columns_migrated"] == 1 + + +def test_v2_columns_read_before_finalize(schema014): + """The guide's verification step: the new columns read in 2.x before finalizing.""" + migrate_external(schema014, dry_run=False) + migrate_filepath(schema014, dry_run=False) + recording = _recording(schema014) & {"recording_id": 1} + np.testing.assert_array_equal(recording.fetch1("signal_v2"), SIGNAL) + assert Path(recording.fetch1("report_v2")).read_bytes() == REPORT + assert recording.fetch1("raw_file_v2").read() == RAW + + +def test_integrity_check_finds_014_files(schema014): + result = verify_external_integrity(schema014) + assert result["total_references"] == 4 + assert result["missing"] == [] + assert result["valid"] == 4 + + +def test_migrated_columns_return_their_values(schema014): + _migrate(schema014) + + recording = _recording(schema014) + np.testing.assert_array_equal((recording & {"recording_id": 1}).fetch1("signal"), SIGNAL) + np.testing.assert_array_equal((recording & {"recording_id": 2}).fetch1("signal"), COUNTS) + + report = Path((recording & {"recording_id": 1}).fetch1("report")) + assert report.name == REPORT_NAME + assert report.read_bytes() == REPORT + assert (recording & {"recording_id": 2}).fetch1("report") is None + + assert (recording & {"recording_id": 1}).fetch1("raw_file").read() == RAW + + # The 0.14 references are kept beside the migrated columns. + assert {"signal_v1", "report_v1", "raw_file_v1"} <= _columns(schema014) + assert verify_schema_v20(schema014.database, connection=schema014.connection)["compatible"] + + +def test_migrated_values_carry_2x_metadata(schema014): + _migrate(schema014) + db = schema014.database + stored = schema014.connection.query(f"SELECT `signal` FROM `{db}`.`recording` WHERE recording_id = 1").fetchone()[0] + stored = json.loads(stored) + assert stored["hash"] == compute_hash(SIGNAL_BLOB) + assert stored["store"] == "legacy" + assert stored["path"] == _legacy_path(db, _md5(SIGNAL_BLOB), (2, 2)) + + +def test_changed_files_fail_the_hash_check(schema014, legacy_store): + _migrate(schema014) + db = schema014.database + signal, report = _md5(SIGNAL_BLOB), _md5((REPORT_NAME + "\0").encode() + REPORT) + (legacy_store / _legacy_path(db, signal, (2, 2))).write_bytes(COUNTS_BLOB) + (legacy_store / _legacy_path(db, report, (2, 2), REPORT_NAME)).write_bytes(b"spike count: 13\n") + + recording = _recording(schema014) & {"recording_id": 1} + with pytest.raises(DataJointError, match="Hash mismatch"): + recording.fetch1("signal") + with pytest.raises(DataJointError, match="Hash mismatch"): + recording.fetch1("report") + + +def test_missing_file_stops_migration_unchanged(schema014, legacy_store): + report = _md5((REPORT_NAME + "\0").encode() + REPORT) + (legacy_store / _legacy_path(schema014.database, report, (2, 2), REPORT_NAME)).unlink() + + preview = migrate_external(schema014, dry_run=True) + problems = [p for detail in preview["details"] for p in detail["problems"]] + assert len(problems) == 1 and REPORT_NAME in problems[0] + + before = _columns(schema014) + with pytest.raises(DataJointError, match="Nothing was changed"): + migrate_external(schema014, dry_run=False) + assert _columns(schema014) == before # the blob column was not converted either + + +def test_pointers_v2_refuses_binary16_column(schema014): + before = _columns(schema014) + with pytest.raises(DataJointError, match="BINARY\\(16\\)"): + migrate_external_pointers_v2( + schema=schema014.database, + table="recording", + attribute="signal", + source_store="legacy", + dest_store="legacy", + connection=schema014.connection, + ) + assert _columns(schema014) == before + + +def test_pointers_v2_writes_2x_metadata(schema014): + db, connection = schema014.database, schema014.connection + # Widen the column so that it can hold the JSON metadata. + constraint = connection.query( + "SELECT CONSTRAINT_NAME FROM information_schema.KEY_COLUMN_USAGE " + "WHERE TABLE_SCHEMA = %s AND TABLE_NAME = 'recording' AND COLUMN_NAME = 'signal' " + "AND REFERENCED_TABLE_NAME IS NOT NULL", + args=(db,), + ).fetchone()[0] + connection.query(f"ALTER TABLE `{db}`.`recording` DROP FOREIGN KEY `{constraint}`") + connection.query( + f"ALTER TABLE `{db}`.`recording` MODIFY `signal` varbinary(1024) NOT NULL COMMENT ':blob@legacy:raw signal'" + ) + + result = migrate_external_pointers_v2( + schema=db, + table="recording", + attribute="signal", + source_store="legacy", + dest_store="legacy", + connection=connection, + ) + assert result["rows_migrated"] == 2 + rows = connection.query(f"SELECT recording_id, `signal` FROM `{db}`.`recording` ORDER BY recording_id").fetchall() + for (_, stored), blob in zip(rows, (SIGNAL_BLOB, COUNTS_BLOB)): + metadata = json.loads(stored) + assert metadata["store"] == "legacy" + assert metadata["hash"] == compute_hash(blob) + assert get_hash(metadata) == blob + + +def test_migrated_attachment_reads(connection_by_backend, backend, prefix, legacy_store): + """A migrated attachment's metadata reads through on either backend.""" + schema = dj.Schema(f"{prefix}_legacy_attach_{backend}", connection=connection_by_backend) + + @schema + class Document(dj.Manual): + definition = """ + doc_id : int32 + --- + report = null : + """ + + try: + Document.insert1({"doc_id": 1}) + digest = _md5((REPORT_NAME + "\0").encode() + REPORT) + path = _legacy_path(schema.database, digest, (2, 2), REPORT_NAME) + (legacy_store / path).parent.mkdir(parents=True) + (legacy_store / path).write_bytes(REPORT) + metadata = { + "hash": _legacy_hash(digest), + "path": path, + "schema": schema.database, + "store": "legacy", + "size": len(REPORT), + "attachment_name": REPORT_NAME, + } + quote = connection_by_backend.adapter.quote_identifier + connection_by_backend.query( + f"UPDATE {Document.full_table_name} SET {quote('report')} = %s WHERE {quote('doc_id')} = 1", + args=(json.dumps(metadata),), + ) + + report = Path((Document & {"doc_id": 1}).fetch1("report")) + assert report.name == REPORT_NAME + assert report.read_bytes() == REPORT + + (legacy_store / path).write_bytes(b"spike count: 13\n") + with pytest.raises(DataJointError, match="Hash mismatch"): + (Document & {"doc_id": 1}).fetch1("report") + finally: + schema.drop(prompt=False) diff --git a/tests/unit/test_migrate_legacy_store.py b/tests/unit/test_migrate_legacy_store.py new file mode 100644 index 000000000..644a237e1 --- /dev/null +++ b/tests/unit/test_migrate_legacy_store.py @@ -0,0 +1,138 @@ +"""Reading DataJoint 0.14 in-store objects after migration. + +DataJoint 0.14 kept blobs and attachments at paths derived from a 16-byte MD5 +digest. Its layout, taken from ``datajoint/external.py`` and ``datajoint/hash.py`` +at the 0.14.6 tag: + +- a blob at ``{database}/{subfolders}/{hex digest}``, the digest of its bytes; +- an attachment at ``{database}/{subfolders}/{hex digest}.{name}``, the digest of + its name, a NUL byte, and its contents, with the contents alone in the file; +- subfolders from the store's ``subfolding`` setting, (2, 2) unless set. + +These tests pin the paths and hashes the migration writes, and the read of a +migrated attachment, without a database. +""" + +import hashlib +from pathlib import Path + +import pytest + +from datajoint.errors import DataJointError +from datajoint.hash_registry import compute_hash, get_hash +from datajoint.migrate import _legacy_hash, _legacy_path, _legacy_subfolding, verify_schema_v20 +from datajoint.settings import Config + +# The digest from the issue report: `{location}/{database}/ec/88/`. +DIGEST = bytes.fromhex("ec88a4468ab852d319309178a2e34955") + + +class TestLegacyLayout: + def test_blob_path_is_subfolded_hex_digest(self): + hex_digest = DIGEST.hex() + assert _legacy_path("lab_ephys", DIGEST, (2, 2)) == f"lab_ephys/ec/88/{hex_digest}" + + def test_attachment_path_appends_the_name(self): + hex_digest = DIGEST.hex() + assert _legacy_path("lab_ephys", DIGEST, (2, 2), "report.txt") == f"lab_ephys/ec/88/{hex_digest}.report.txt" + + def test_custom_and_empty_subfolding(self): + hex_digest = DIGEST.hex() + assert _legacy_path("db", DIGEST, (3,)) == f"db/ec8/{hex_digest}" + assert _legacy_path("db", DIGEST, ()) == f"db/{hex_digest}" + + def test_hash_is_the_same_digest_in_base32(self): + data = b"any serialized blob" + assert _legacy_hash(hashlib.md5(data).digest()) == compute_hash(data) + # The issue's digest gives the hash 2.x computed from that file. + assert _legacy_hash(DIGEST).startswith("5sekiruk") + + def test_attachment_hash_matches_what_attach_stores(self): + # 0.14: uuid_from_file(path, init_string=name + "\0"); 2.x stores name\0contents. + name, contents = "report.txt", b"spike count: 12\n" + digest = hashlib.md5((name + "\0").encode() + contents).digest() + assert _legacy_hash(digest) == compute_hash(name.encode() + b"\x00" + contents) + + +class TestLegacySubfolding: + def test_default_is_014_default(self): + config = Config() + config.stores["legacy"] = {"protocol": "file", "location": "/data"} + assert _legacy_subfolding("legacy", config) == (2, 2) + + def test_store_setting_wins(self): + config = Config() + config.stores["legacy"] = {"protocol": "file", "location": "/data", "subfolding": [3]} + assert _legacy_subfolding("legacy", config) == (3,) + config.stores["legacy"] = {"protocol": "file", "location": "/data", "subfolding": None} + assert _legacy_subfolding("legacy", config) == () + + +class TestMigratedAttachmentRead: + """`get_hash` puts a migrated attachment's name back before checking the hash.""" + + NAME = "report.txt" + CONTENTS = b"spike count: 12\n" + + @pytest.fixture + def cfg(self, tmp_path): + config = Config() + config.stores["legacy"] = {"protocol": "file", "location": str(tmp_path)} + return config + + @pytest.fixture + def metadata(self, tmp_path): + digest = hashlib.md5((self.NAME + "\0").encode() + self.CONTENTS).digest() + path = _legacy_path("db", digest, (2, 2), self.NAME) + file = Path(tmp_path, path) + file.parent.mkdir(parents=True) + file.write_bytes(self.CONTENTS) + return { + "hash": _legacy_hash(digest), + "path": path, + "store": "legacy", + "size": len(self.CONTENTS), + "attachment_name": self.NAME, + } + + def test_returns_what_attach_decodes(self, cfg, metadata): + assert get_hash(metadata, config=cfg) == self.NAME.encode() + b"\x00" + self.CONTENTS + + def test_changed_contents_fail_the_hash_check(self, cfg, metadata, tmp_path): + Path(tmp_path, metadata["path"]).write_bytes(b"spike count: 13\n") + with pytest.raises(DataJointError, match="Hash mismatch"): + get_hash(metadata, config=cfg) + + def test_changed_name_fails_the_hash_check(self, cfg, metadata): + with pytest.raises(DataJointError, match="Hash mismatch"): + get_hash({**metadata, "attachment_name": "other.txt"}, config=cfg) + + def test_without_the_name_the_hash_check_fails(self, cfg, metadata): + del metadata["attachment_name"] + with pytest.raises(DataJointError, match="Hash mismatch"): + get_hash(metadata, config=cfg) + + +class _PyMySQLFormatting: + """Formats each query with its arguments as PyMySQL does, and returns no rows.""" + + def __init__(self): + self.queries = [] + + def query(self, sql, args=()): + self.queries.append(sql % tuple(repr(a) for a in args)) + return self + + def fetchone(self): + return (0,) + + def fetchall(self): + return [] + + +def test_verify_schema_v20_query_formats_with_arguments(): + """The LIKE pattern's % is escaped, so formatting with the schema name succeeds.""" + connection = _PyMySQLFormatting() + result = verify_schema_v20("lab_ephys", connection=connection) + assert result["compatible"] + assert any("LIKE '%blob'" in q for q in connection.queries) From a08a91e4a982b39e1454e9ab59e162a870bca7d1 Mon Sep 17 00:00:00 2001 From: Dimitri Yatsenko Date: Mon, 23 Nov 2026 17:46:19 -0600 Subject: [PATCH 2/6] fix(migrate): Option A reads in 2.x; escape comments; repair earlier runs; keep NOT NULL - copy_table_data converts 0.14 in-store columns when it copies a 0.14 table into a table declared by 2.x, so the guide's Option A works end to end. Every file is looked up first; a missing one stops the copy with nothing copied. - migrate_external_pointers_v2 converts one 0.14 column in place: it adds the JSON column, fills it, and swaps it in with a 2.x comment that names dest_store. It refuses a column already declared by 2.x, pointing to copy_table_data. - Column comments are quoted and escaped in every ALTER, including apostrophes, backslashes, and percent signs. - If a step fails, the _v2 columns the run wrote are dropped again. - A rerun rewrites _v2 columns written by an earlier release, whose values 2.x cannot read, and repairs columns an earlier release finalized. - Finalize checks every _v2 column first, renames both columns in one statement, and keeps the original nullability. - Tests for each of these, for filepath rows without contents_hash, and for a dry run without the store configured. --- src/datajoint/migrate.py | 1092 ++++++++++------- .../test_migrate_legacy_external.py | 319 ++++- tests/unit/test_migrate_legacy_store.py | 47 +- 3 files changed, 969 insertions(+), 489 deletions(-) diff --git a/src/datajoint/migrate.py b/src/datajoint/migrate.py index 4867bce06..45230e367 100644 --- a/src/datajoint/migrate.py +++ b/src/datajoint/migrate.py @@ -56,6 +56,8 @@ FILEPATH_PATTERN = re.compile(r":filepath@([a-z][\-\w]*):", re.I) +LEGACY_PATTERNS = {**EXTERNAL_PATTERNS, "filepath": FILEPATH_PATTERN} + # Pattern to detect blob types BLOB_TYPES = re.compile(r"^(tiny|small|medium|long|)blob$", re.I) @@ -786,121 +788,145 @@ def add_job_metadata_columns(target, dry_run: bool = True) -> dict: # ============================================================================= -def _find_external_columns(schema: Schema) -> list[dict]: +def _comment_literal(connection, comment: str) -> str: """ - Find columns using 0.x external storage format. + Return ``comment`` as a quoted SQL string literal for a DDL statement. - Returns list of dicts with column info and detected store name. + Quotes and backslashes are escaped. ``%`` is doubled, because + ``Connection.query`` always formats the statement with its arguments. """ - connection = schema.connection - results = [] + return connection.adapter.quote_string(comment).replace("%", "%%") - # Get all tables (excluding hidden tables) - tables_query = """ - SELECT TABLE_NAME - FROM information_schema.TABLES - WHERE TABLE_SCHEMA = %s - AND TABLE_TYPE = 'BASE TABLE' - AND TABLE_NAME NOT LIKE '~%%' - """ - tables = connection.query(tables_query, args=(schema.database,)).fetchall() - for (table_name,) in tables: - # Find BINARY(16) columns (0.x external storage format) - columns_query = """ - SELECT COLUMN_NAME, COLUMN_TYPE, COLUMN_COMMENT - FROM information_schema.COLUMNS - WHERE TABLE_SCHEMA = %s - AND TABLE_NAME = %s - AND DATA_TYPE = 'binary' - AND CHARACTER_MAXIMUM_LENGTH = 16 - """ - columns = connection.query(columns_query, args=(schema.database, table_name)).fetchall() +def _legacy_kind(comment: str) -> tuple[str | None, str | None]: + """Return the 0.14 in-store type (``blob``, ``attach``, ``filepath``) and store named in a comment.""" + for kind, pattern in LEGACY_PATTERNS.items(): + match = pattern.search(comment or "") + if match: + return kind, match.group(1) + return None, None - for column_name, column_type, comment in columns: - comment = comment or "" - # Check for external blob pattern - blob_match = EXTERNAL_PATTERNS["blob"].search(comment) - if blob_match: - store_name = blob_match.group(1) or "external" - results.append( - { - "table_name": table_name, - "column_name": column_name, - "column_type": column_type, - "comment": comment, - "store_name": store_name, - "external_type": "blob", - } - ) - continue +def _new_comment(kind: str, store_name: str, old_comment: str) -> str: + """Return the 2.x comment: the codec marker, then the rest of the 0.14 comment.""" + rest = LEGACY_PATTERNS[kind].sub("", old_comment or "").strip() + return f":<{kind}@{store_name}>:{rest}" - # Check for external attach pattern - attach_match = EXTERNAL_PATTERNS["attach"].search(comment) - if attach_match: - store_name = attach_match.group(1) or "external" - results.append( - { - "table_name": table_name, - "column_name": column_name, - "column_type": column_type, - "comment": comment, - "store_name": store_name, - "external_type": "attach", - } - ) - return results +def _column_info(connection, database: str, table_name: str, column_name: str) -> dict | None: + """Return the type, comment, and nullability of one column, or None if it does not exist.""" + row = connection.query( + """ + SELECT DATA_TYPE, CHARACTER_MAXIMUM_LENGTH, COLUMN_TYPE, COLUMN_COMMENT, IS_NULLABLE + FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = %s AND TABLE_NAME = %s AND COLUMN_NAME = %s + """, + args=(database, table_name, column_name), + ).fetchone() + if row is None: + return None + data_type, max_length, column_type, comment, nullable = row + return { + "binary16": data_type.lower() == "binary" and max_length == 16, + "data_type": data_type.lower(), + "column_type": column_type, + "comment": comment or "", + "nullable": nullable == "YES", + } -def _find_filepath_columns(schema: Schema) -> list[dict]: +def _find_legacy_columns(schema: Schema, kinds: tuple[str, ...]) -> list[dict]: """ - Find columns using 0.x filepath format. + Find 0.14 in-store columns of the given kinds. - Returns list of dicts with column info and detected store name. + In 0.14, these are BINARY(16) columns whose comment starts with a marker + such as ``:blob@store:``. Returns a list of dicts with the column's type, + comment, nullability, kind, and store. """ - connection = schema.connection + rows = schema.connection.query( + """ + SELECT c.TABLE_NAME, c.COLUMN_NAME, c.COLUMN_TYPE, c.COLUMN_COMMENT, c.IS_NULLABLE + FROM information_schema.COLUMNS c + JOIN information_schema.TABLES t + ON t.TABLE_SCHEMA = c.TABLE_SCHEMA AND t.TABLE_NAME = c.TABLE_NAME + WHERE c.TABLE_SCHEMA = %s + AND t.TABLE_TYPE = 'BASE TABLE' + AND c.TABLE_NAME NOT LIKE '~%%' + AND c.DATA_TYPE = 'binary' + AND c.CHARACTER_MAXIMUM_LENGTH = 16 + ORDER BY c.TABLE_NAME, c.ORDINAL_POSITION + """, + args=(schema.database,), + ).fetchall() + results = [] + for table_name, column_name, column_type, comment, nullable in rows: + kind, store_name = _legacy_kind(comment) + if kind in kinds: + results.append( + { + "table_name": table_name, + "column_name": column_name, + "column_type": column_type, + "comment": comment or "", + "nullable": nullable == "YES", + "store_name": store_name, + "external_type": kind, + } + ) + return results - # Get all tables (excluding hidden tables) - tables_query = """ - SELECT TABLE_NAME - FROM information_schema.TABLES - WHERE TABLE_SCHEMA = %s - AND TABLE_TYPE = 'BASE TABLE' - AND TABLE_NAME NOT LIKE '~%%' + +def _find_external_columns(schema: Schema) -> list[dict]: + """Find 0.14 ``blob@store`` and ``attach@store`` columns.""" + return _find_legacy_columns(schema, ("blob", "attach")) + + +def _find_filepath_columns(schema: Schema) -> list[dict]: + """Find 0.14 ``filepath@store`` columns.""" + return _find_legacy_columns(schema, ("filepath",)) + + +def _find_columns_finalized_earlier(schema: Schema, kinds: tuple[str, ...]) -> list[dict]: """ - tables = connection.query(tables_query, args=(schema.database,)).fetchall() + Find columns that an earlier 2.x release finalized with values 2.x cannot read. - for (table_name,) in tables: - # Find BINARY(16) columns with :filepath@store: in comment (0.x filepath format) - columns_query = """ - SELECT COLUMN_NAME, COLUMN_TYPE, COLUMN_COMMENT - FROM information_schema.COLUMNS - WHERE TABLE_SCHEMA = %s - AND TABLE_NAME = %s - AND DATA_TYPE = 'binary' - AND CHARACTER_MAXIMUM_LENGTH = 16 - AND COLUMN_COMMENT LIKE '%%:filepath%%' + That release renamed the 0.14 column to ``_v1`` (BINARY(16), which + still holds the references) and gave its name to a JSON column whose comment + kept the 0.14 form, such as ``:blob@store:``. A JSON column written by 2.x + has a ``::`` comment instead, so the two cannot be confused. + """ + rows = schema.connection.query( """ - columns = connection.query(columns_query, args=(schema.database, table_name)).fetchall() - - for column_name, column_type, comment in columns: - comment = comment or "" - match = FILEPATH_PATTERN.search(comment) - if match: - store_name = match.group(1) or "external" - results.append( - { - "table_name": table_name, - "column_name": column_name, - "column_type": column_type, - "comment": comment, - "store_name": store_name, - } - ) + SELECT c.TABLE_NAME, c.COLUMN_NAME, c.COLUMN_COMMENT, c.IS_NULLABLE + FROM information_schema.COLUMNS c + JOIN information_schema.COLUMNS r + ON r.TABLE_SCHEMA = c.TABLE_SCHEMA AND r.TABLE_NAME = c.TABLE_NAME + AND r.COLUMN_NAME = CONCAT(c.COLUMN_NAME, '_v1') + WHERE c.TABLE_SCHEMA = %s + AND c.TABLE_NAME NOT LIKE '~%%' + AND c.DATA_TYPE = 'json' + AND r.DATA_TYPE = 'binary' + AND r.CHARACTER_MAXIMUM_LENGTH = 16 + ORDER BY c.TABLE_NAME, c.ORDINAL_POSITION + """, + args=(schema.database,), + ).fetchall() + results = [] + for table_name, column_name, comment, nullable in rows: + kind, store_name = _legacy_kind(comment) + if kind in kinds: + results.append( + { + "table_name": table_name, + "column_name": column_name, + "comment": comment or "", + "nullable": nullable == "YES", + "store_name": store_name, + "external_type": kind, + } + ) return results @@ -911,11 +937,14 @@ def _find_filepath_columns(schema: Schema) -> list[dict]: # `{database}/{subfolders}/{hex digest}`; # - an attachment: the digest of its name, a NUL byte, and its contents, stored # (contents only) at `{database}/{subfolders}/{hex digest}.{attachment_name}`; -# - a filepath: the digest of its relative path, stored at `filepath`; +# - a filepath: the digest of its relative path, stored at `filepath`. From +# 0.14.7, `contents_hash` is NULL for files above +# `filepath_checksum_size_limit_insert`; 2.x does not need it; # - a blob migrated from 0.11: stored at `filepath`, with the digest of its # serialized bytes in `contents_hash`. # # Subfolders come from the store's `subfolding` setting, (2, 2) unless set. +# This layout is the same from 0.14.0 through 0.14.10. LEGACY_SUBFOLDING = (2, 2) @@ -969,6 +998,7 @@ def _plan_legacy_references( kind: str, store_name: str, dest_store: str | None = None, + where_clause: str | None = None, ) -> tuple[dict[bytes, dict], list[str]]: """ Build the 2.x metadata for each 0.14 reference in one column. @@ -986,6 +1016,8 @@ def _plan_legacy_references( dest_store : str, optional The 2.x store the metadata names. Defaults to ``store_name``. Files are looked up through this store, so it must point at the 0.14 location. + where_clause : str, optional + Only plan the rows of the table that match this SQL condition. Returns ------- @@ -1001,13 +1033,16 @@ def _plan_legacy_references( backend = get_store_backend(dest_store, config=config) subfolding = _legacy_subfolding(dest_store, config) + condition = f" AND ({where_clause})" if where_clause else "" rows = connection.query( f""" - SELECT DISTINCT t.`{column_name}`, e.hash, e.size, e.attachment_name, + SELECT t.reference, e.hash, e.size, e.attachment_name, e.filepath, e.contents_hash, e.timestamp - FROM `{database}`.`{table_name}` t - LEFT JOIN `{database}`.`~external_{store_name}` e ON e.hash = t.`{column_name}` - WHERE t.`{column_name}` IS NOT NULL + FROM ( + SELECT DISTINCT `{column_name}` AS reference FROM `{database}`.`{table_name}` + WHERE `{column_name}` IS NOT NULL{condition} + ) t + LEFT JOIN `{database}`.`~external_{store_name}` e ON e.hash = t.reference """ ).fetchall() @@ -1021,6 +1056,7 @@ def _plan_legacy_references( continue if kind == "filepath": + # contents_hash may be NULL (0.14.7+ skips it for large files); it is not needed path, digest = filepath, None elif kind == "attach": path = None if attachment_name is None else _legacy_path(database, reference, subfolding, attachment_name) @@ -1063,42 +1099,42 @@ def _plan_legacy_references( return metadata, problems -def _refuse_problems(where: str, problems: list[str]) -> None: - """Raise if any reference cannot be converted. Called before anything is changed.""" +def _refuse_problems(where: str, problems: list[str], what: str = "reference(s) cannot be converted") -> None: + """Raise if any problem was found. Called before anything is changed.""" if problems: listed = "\n ".join(problems[:10]) more = f"\n ... and {len(problems) - 10} more" if len(problems) > 10 else "" - raise DataJointError( - f"Cannot migrate {where}: {len(problems)} reference(s) cannot be converted. " - f"Nothing was changed.\n {listed}{more}" - ) + raise DataJointError(f"Cannot migrate {where}: {len(problems)} {what}. Nothing was changed.\n {listed}{more}") -def _plan_columns(connection, database: str, columns: list[dict], dry_run: bool, kind: str | None = None) -> dict: +def _unreadable_rows(connection, database: str, table_name: str, reference_column: str, column: str, kind: str) -> int: """ - Plan the conversion of each column not yet migrated, keyed by (table, column). + Count the rows whose ``column`` does not hold readable 2.x metadata for ``reference_column``. - Every reference in every column is looked up before anything is changed, so - that one missing file stops the migration with the schema unchanged. A dry - run reports the problems instead of raising. + A row counts if one of the two columns is NULL and the other is not, or if + the metadata has no ``path`` or ``store``, or (blobs and attachments) no + 26-character base32 ``hash``. Values written by earlier 2.x releases fail + this check: they have no ``path`` and a hexadecimal hash. """ - plans = {} - for col in columns: - table_name, column_name = col["table_name"], col["column_name"] - exists = connection.query( - """ - SELECT COUNT(*) FROM information_schema.COLUMNS - WHERE TABLE_SCHEMA = %s AND TABLE_NAME = %s AND COLUMN_NAME = %s - """, - args=(database, table_name, f"{column_name}_v2"), - ).fetchone()[0] - if not exists: - plans[table_name, column_name] = _plan_legacy_references( - connection, database, table_name, column_name, kind or col["external_type"], col["store_name"] - ) - if not dry_run: - _refuse_problems(database, [problem for _, problems in plans.values() for problem in problems]) - return plans + value = f"`{column}`" + + def is_string(key): + return f"JSON_TYPE(JSON_EXTRACT({value}, '$.{key}')) = 'STRING'" + + readable = f"{is_string('path')} AND {is_string('store')}" + if kind != "filepath": + readable += f" AND {is_string('hash')} AND CHAR_LENGTH(JSON_UNQUOTE(JSON_EXTRACT({value}, '$.hash'))) = 26" + return connection.query( + f""" + SELECT COUNT(*) FROM `{database}`.`{table_name}` + WHERE (`{reference_column}` IS NULL) <> ({value} IS NULL) + OR ({value} IS NOT NULL AND NOT COALESCE({readable}, FALSE)) + """ + ).fetchone()[0] + + +def _column_exists(connection, database: str, table_name: str, column_name: str) -> bool: + return _column_info(connection, database, table_name, column_name) is not None def _add_converted_column( @@ -1108,17 +1144,23 @@ def _add_converted_column( column_name: str, new_column: str, comment: str, + kind: str, metadata: dict[bytes, dict], + replace: bool = False, ) -> int: """ Add ``new_column`` as JSON and fill it with the metadata for each reference. - If any reference is left unconverted, or any step fails, the new column is - dropped again so that a later run starts over. Returns the number of rows - converted. + With ``replace``, an existing ``new_column`` is dropped in the same + statement. If any reference is left unconverted, or any step fails, the new + column is dropped again so that a later run starts over. Returns the number + of rows converted. """ table = f"`{database}`.`{table_name}`" - connection.query(f"ALTER TABLE {table} ADD COLUMN `{new_column}` JSON COMMENT '{comment}'") + add = f"ADD COLUMN `{new_column}` JSON COMMENT {_comment_literal(connection, comment)}" + if replace: + add = f"DROP COLUMN `{new_column}`, {add}" + connection.query(f"ALTER TABLE {table} {add}") # one statement: on failure, nothing changed try: with connection.transaction: for reference, value in metadata.items(): @@ -1126,9 +1168,7 @@ def _add_converted_column( f"UPDATE {table} SET `{new_column}` = %s WHERE `{column_name}` = %s", args=(json.dumps(value), reference), ) - unconverted = connection.query( - f"SELECT COUNT(*) FROM {table} WHERE `{column_name}` IS NOT NULL AND `{new_column}` IS NULL" - ).fetchone()[0] + unconverted = _unreadable_rows(connection, database, table_name, column_name, new_column, kind) if unconverted: raise DataJointError(f"{unconverted} row(s) of {database}.{table_name}.{column_name} were not converted") except Exception: @@ -1137,6 +1177,229 @@ def _add_converted_column( return connection.query(f"SELECT COUNT(*) FROM {table} WHERE `{new_column}` IS NOT NULL").fetchone()[0] +def _swap_in_converted_column( + connection, + database: str, + table_name: str, + column_name: str, + new_column: str, + column_type: str, + comment: str, + nullable: bool, +) -> None: + """ + Rename ``column_name`` to ``_v1`` and ``new_column`` to ``column_name``. + + Both renames are one statement, so either both happen or neither does. The + converted column keeps the original's nullability. The ``_v1`` column + becomes nullable, so that new rows need not fill it. + """ + null = "NULL" if nullable else "NOT NULL" + connection.query( + f"ALTER TABLE `{database}`.`{table_name}` " + f"CHANGE COLUMN `{column_name}` `{column_name}_v1` {column_type} NULL COMMENT 'legacy 0.x', " + f"CHANGE COLUMN `{new_column}` `{column_name}` JSON {null} COMMENT {_comment_literal(connection, comment)}" + ) + + +def _repair_column(connection, database: str, col: dict, comment: str, metadata: dict[bytes, dict]) -> int: + """ + Rewrite a column finalized by an earlier release from the references in ``_v1``. + + The values are rewritten in one transaction and checked before it commits. + Then the comment is rewritten. Returns the number of rows converted. + """ + table_name, column_name, kind = col["table_name"], col["column_name"], col["external_type"] + table = f"`{database}`.`{table_name}`" + reference_column = f"{column_name}_v1" + with connection.transaction: + for reference, value in metadata.items(): + connection.query( + f"UPDATE {table} SET `{column_name}` = %s WHERE `{reference_column}` = %s", + args=(json.dumps(value), reference), + ) + unconverted = _unreadable_rows(connection, database, table_name, reference_column, column_name, kind) + if unconverted: + raise DataJointError(f"{unconverted} row(s) of {database}.{table_name}.{column_name} were not converted") + null = "NULL" if col["nullable"] else "NOT NULL" + connection.query( + f"ALTER TABLE {table} MODIFY COLUMN `{column_name}` JSON {null} COMMENT {_comment_literal(connection, comment)}" + ) + return connection.query(f"SELECT COUNT(*) FROM {table} WHERE `{column_name}` IS NOT NULL").fetchone()[0] + + +def _finalize_problems(connection, database: str, col: dict) -> list[str]: + """Return the reasons a column cannot be finalized yet.""" + table_name, column_name = col["table_name"], col["column_name"] + label = f"{database}.{table_name}.{column_name}" + new_column = f"{column_name}_v2" + if not _column_exists(connection, database, table_name, new_column): + return [f"{label}: {new_column} does not exist; run the migration with dry_run=False first"] + problems = [] + if _column_exists(connection, database, table_name, f"{column_name}_v1"): + problems.append(f"{label}: {column_name}_v1 already exists") + unreadable = _unreadable_rows(connection, database, table_name, column_name, new_column, col["external_type"]) + if unreadable: + problems.append( + f"{label}: {unreadable} row(s) of {new_column} do not hold metadata that 2.x reads; " + f"run the migration with dry_run=False again to rewrite them" + ) + return problems + + +def _migrate_legacy_columns(schema: Schema, kinds: tuple[str, ...], dry_run: bool, finalize: bool) -> dict: + """Run ``migrate_external`` (blob, attach) or ``migrate_filepath`` (filepath).""" + connection = schema.connection + database = schema.database + columns = _find_legacy_columns(schema, kinds) + repairs = [] if finalize else _find_columns_finalized_earlier(schema, kinds) + + result = { + "columns_found": len(columns) + len(repairs), + "columns_migrated": 0, + "rows_migrated": 0, + "details": [], + } + if not columns and not repairs: + logger.info(f"No {' or '.join(kinds)} in-store columns found in {database}") + return result + + def new_detail(col, action): + detail = { + "table": f"{database}.{col['table_name']}", + "column": col["column_name"], + "store": col["store_name"], + "type": col["external_type"], + "action": action, + "status": "pending", + "rows": 0, + } + result["details"].append(detail) + return detail + + if finalize: + steps = [(col, new_detail(col, "finalize"), _finalize_problems(connection, database, col)) for col in columns] + if dry_run: + for col, detail, problems in steps: + detail["status"] = "dry_run" + detail["problems"] = problems + logger.info( + f"Would finalize {detail['table']}.{col['column_name']}: rename {col['column_name']} → " + f"{col['column_name']}_v1, {col['column_name']}_v2 → {col['column_name']}" + ) + for problem in problems: + logger.warning(f"Cannot finalize {problem}") + return result + _refuse_problems(database, [p for _, _, problems in steps for p in problems], "column(s) cannot be finalized") + for col, detail, _ in steps: + try: + _swap_in_converted_column( + connection, + database, + col["table_name"], + col["column_name"], + f"{col['column_name']}_v2", + col["column_type"], + _new_comment(col["external_type"], col["store_name"], col["comment"]), + col["nullable"], + ) + except Exception as error: + detail["status"] = "error" + detail["error"] = str(error) + logger.error(f"Failed to finalize {detail['table']}.{col['column_name']}: {error}") + raise DataJointError(f"Finalize failed: {error}") from error + detail["status"] = "finalized" + result["columns_migrated"] += 1 + logger.info(f"Finalized {detail['table']}.{col['column_name']}") + return result + + # Plan every column before changing anything. + jobs = [] + for col in columns: + table_name, column_name, kind = col["table_name"], col["column_name"], col["external_type"] + new_column = f"{column_name}_v2" + mode = "add" + if _column_exists(connection, database, table_name, new_column): + if not _unreadable_rows(connection, database, table_name, column_name, new_column, kind): + new_detail(col, "migrate")["status"] = "already_migrated" + logger.info(f"Column {new_column} already exists, skipping") + continue + mode = "rewrite" # written by an earlier release, with values 2.x cannot read + detail = new_detail(col, "rewrite" if mode == "rewrite" else "migrate") + metadata, problems = _plan_legacy_references(connection, database, table_name, column_name, kind, col["store_name"]) + jobs.append((mode, col, column_name, detail, metadata, problems)) + for col in repairs: + detail = new_detail(col, "repair") + metadata, problems = _plan_legacy_references( + connection, + database, + col["table_name"], + f"{col['column_name']}_v1", + col["external_type"], + col["store_name"], + ) + jobs.append(("repair", col, f"{col['column_name']}_v1", detail, metadata, problems)) + + if dry_run: + for mode, col, reference_column, detail, metadata, problems in jobs: + count = connection.query( + f"SELECT COUNT(*) FROM `{database}`.`{col['table_name']}` WHERE `{reference_column}` IS NOT NULL" + ).fetchone()[0] + detail["rows"] = count + detail["problems"] = problems + detail["status"] = "dry_run" + verb = {"add": "migrate", "rewrite": "rewrite", "repair": "repair"}[mode] + logger.info(f"Would {verb} {detail['table']}.{col['column_name']}: {count} rows, store={col['store_name']}") + for problem in problems: + logger.warning(f"Cannot migrate {problem}") + return result + + _refuse_problems(database, [p for *_, problems in jobs for p in problems]) + + # Repairs commit as they go, so they run after every step that can be undone. + added = [] + detail = None + try: + for mode, col, reference_column, detail, metadata, _ in sorted(jobs, key=lambda job: job[0] == "repair"): + comment = _new_comment(col["external_type"], col["store_name"], col["comment"]) + if mode == "repair": + count = _repair_column(connection, database, col, comment, metadata) + else: + new_column = f"{col['column_name']}_v2" + count = _add_converted_column( + connection, + database, + col["table_name"], + col["column_name"], + new_column, + comment, + col["external_type"], + metadata, + replace=mode == "rewrite", + ) + added.append((col["table_name"], new_column)) + detail["rows"] = count + detail["status"] = "migrated" + result["columns_migrated"] += 1 + result["rows_migrated"] += count + logger.info(f"Migrated {detail['table']}.{col['column_name']}: {count} rows") + except Exception as error: + if detail is not None: + detail["status"] = "error" + detail["error"] = str(error) + for table_name, new_column in reversed(added): + try: + connection.query(f"ALTER TABLE `{database}`.`{table_name}` DROP COLUMN `{new_column}`") + except Exception as drop_error: # keep the original error + logger.error(f"Could not drop {database}.{table_name}.{new_column}: {drop_error}") + logger.error(f"Failed to migrate {database}: {error}") + raise DataJointError( + f"Migration failed: {error}. The original columns are unchanged, " + f"and the _v2 columns this run wrote were dropped." + ) from error + return result + + def migrate_external( schema: Schema, dry_run: bool = True, @@ -1148,8 +1411,7 @@ def migrate_external( This migration uses a safe, multi-step approach: 1. **Initial run** (dry_run=False): Adds new `_v2` columns with JSON - type and copies data from the old columns, converting UUID references to - JSON metadata. + type and fills them with the 2.0 metadata for each 0.14 reference. 2. **Verification**: You verify all data is accessible via DataJoint 2.0. @@ -1166,8 +1428,8 @@ def migrate_external( dry_run : bool, optional If True, only preview changes without applying. Default True. finalize : bool, optional - If True, rename migrated columns to original names and drop old columns. - Only run after verifying migration succeeded. Default False. + If True, rename the original columns to `_v1` and the migrated columns + to the original names. Only run after verifying the migration. Default False. Returns ------- @@ -1177,7 +1439,8 @@ def migrate_external( - columns_found: Number of external columns found - columns_migrated: Number of columns processed - rows_migrated: Number of rows with data converted - - details: Per-column migration details + - details: Per-column migration details. On a dry run, each lists + under ``problems`` what would stop the migration. Examples -------- @@ -1203,132 +1466,23 @@ def migrate_external( file where 0.14 stored it. Configure each store under its 0.14 name, with its 0.14 location and, if 0.14 set one, its `subfolding`. - Every referenced file is looked up before anything is changed. If a - reference has no tracking row or its file is missing, the migration raises - and changes nothing; a dry run lists these references under `problems`. - """ - columns = _find_external_columns(schema) - connection = schema.connection - database = schema.database + Every referenced file is looked up before anything is changed, on a dry run + as well, so the stores must be configured and reachable even for a preview. + This is one existence check per distinct file. If a reference has no + tracking row or its file is missing, the migration raises and changes + nothing; a dry run lists these references under `problems`. If a later step + fails, the `_v2` columns the run wrote are dropped again. - result = { - "columns_found": len(columns), - "columns_migrated": 0, - "rows_migrated": 0, - "details": [], - } - - if not columns: - logger.info(f"No external columns found in {database}") - return result - - plans = {} if finalize else _plan_columns(connection, database, columns, dry_run) - - for col in columns: - table_name = col["table_name"] - column_name = col["column_name"] - store_name = col["store_name"] - external_type = col["external_type"] - old_comment = col["comment"] - - detail = { - "table": f"{database}.{table_name}", - "column": column_name, - "store": store_name, - "type": external_type, - "status": "pending", - "rows": 0, - } - - # Build new comment: the 2.x codec marker, then the rest of the comment - codec = "blob" if external_type == "blob" else "attach" - new_comment = EXTERNAL_PATTERNS[external_type].sub("", old_comment).strip() - new_comment = f":<{codec}@{store_name}>:{new_comment}" - - new_column = f"{column_name}_v2" - - if finalize: - # Finalize: rename columns - detail["action"] = "finalize" - - if dry_run: - logger.info( - f"Would finalize {database}.{table_name}.{column_name}: " - f"rename {column_name} → {column_name}_v1, " - f"{new_column} → {column_name}" - ) - detail["status"] = "dry_run" - else: - try: - # Rename old column to _v1 - sql = ( - f"ALTER TABLE `{database}`.`{table_name}` " - f"CHANGE COLUMN `{column_name}` `{column_name}_v1` " - f"{col['column_type']} COMMENT 'legacy 0.x'" - ) - connection.query(sql) - - # Rename new column to original name - sql = ( - f"ALTER TABLE `{database}`.`{table_name}` " - f"CHANGE COLUMN `{new_column}` `{column_name}` " - f"JSON COMMENT '{new_comment}'" - ) - connection.query(sql) - - detail["status"] = "finalized" - result["columns_migrated"] += 1 - logger.info(f"Finalized {database}.{table_name}.{column_name}") - except Exception as e: - detail["status"] = "error" - detail["error"] = str(e) - logger.error(f"Failed to finalize {table_name}.{column_name}: {e}") - raise DataJointError(f"Finalize failed: {e}") from e - else: - # Initial migration: add new column and copy data - detail["action"] = "migrate" - - # Skip columns whose _v2 column already exists - if (table_name, column_name) not in plans: - detail["status"] = "already_migrated" - logger.info(f"Column {new_column} already exists, skipping") - result["details"].append(detail) - continue - metadata, problems = plans[table_name, column_name] - - if dry_run: - # Count rows that would be migrated - count_sql = f""" - SELECT COUNT(*) FROM `{database}`.`{table_name}` - WHERE `{column_name}` IS NOT NULL - """ - count = connection.query(count_sql).fetchone()[0] - detail["rows"] = count - detail["problems"] = problems - detail["status"] = "dry_run" - logger.info(f"Would migrate {database}.{table_name}.{column_name}: " f"{count} rows, store={store_name}") - for problem in problems: - logger.warning(f"Cannot migrate {problem}") - else: - try: - count = _add_converted_column( - connection, database, table_name, column_name, new_column, new_comment, metadata - ) - detail["rows"] = count - detail["status"] = "migrated" - result["columns_migrated"] += 1 - result["rows_migrated"] += count - - logger.info(f"Migrated {database}.{table_name}.{column_name}: " f"{count} rows") - except Exception as e: - detail["status"] = "error" - detail["error"] = str(e) - logger.error(f"Failed to migrate {table_name}.{column_name}: {e}") - raise DataJointError(f"Migration failed: {e}") from e + A rerun skips `_v2` columns that already hold readable metadata. It + rewrites `_v2` columns written by an earlier 2.x release, whose values 2.x + cannot read. It also repairs columns that an earlier release finalized: + the values are rewritten from the references kept in `_v1`. - result["details"].append(detail) - - return result + Finalizing checks first that every `_v2` column exists and holds readable + metadata, and changes nothing otherwise. The migrated column keeps the + original column's nullability. + """ + return _migrate_legacy_columns(schema, ("blob", "attach"), dry_run, finalize) # ============================================================================= @@ -1719,8 +1873,12 @@ def migrate_filepath( 2. **Verification**: Verify files accessible via DataJoint 2.0 3. **Finalize** (dry_run=False, finalize=True): Rename columns (old → `_v1`) - As with migrate_external, every referenced file is looked up first, and the - migration raises and changes nothing if one is missing. + As with migrate_external, every referenced file is looked up first, on a + dry run as well, and the migration raises and changes nothing if one is + missing. Reruns rewrite `_v2` columns and repair finalized columns written + by an earlier 2.x release, and finalizing keeps the original nullability. + 0.14 filepath rows whose `contents_hash` is NULL (0.14.7 and later skip it + for large files) are migrated like any other: 2.0 does not need it. Parameters ---------- @@ -1749,117 +1907,7 @@ def migrate_filepath( >>> # Finalize after verification >>> result = migrate_filepath(schema, dry_run=False, finalize=True) """ - columns = _find_filepath_columns(schema) - connection = schema.connection - database = schema.database - - result = { - "columns_found": len(columns), - "columns_migrated": 0, - "rows_migrated": 0, - "details": [], - } - - if not columns: - logger.info(f"No filepath columns found in {database}") - return result - - plans = {} if finalize else _plan_columns(connection, database, columns, dry_run, kind="filepath") - - for col in columns: - table_name = col["table_name"] - column_name = col["column_name"] - store_name = col["store_name"] - old_comment = col["comment"] - - detail = { - "table": f"{database}.{table_name}", - "column": column_name, - "store": store_name, - "status": "pending", - "rows": 0, - } - - # Build new comment: the 2.x codec marker, then the rest of the comment - new_comment = FILEPATH_PATTERN.sub("", old_comment).strip() - new_comment = f"::{new_comment}" - - new_column = f"{column_name}_v2" - - if finalize: - detail["action"] = "finalize" - - if dry_run: - logger.info(f"Would finalize {database}.{table_name}.{column_name}") - detail["status"] = "dry_run" - else: - try: - # Rename old column to _v1 - sql = ( - f"ALTER TABLE `{database}`.`{table_name}` " - f"CHANGE COLUMN `{column_name}` `{column_name}_v1` " - f"{col['column_type']} COMMENT 'legacy 0.x'" - ) - connection.query(sql) - - # Rename new column to original name - sql = ( - f"ALTER TABLE `{database}`.`{table_name}` " - f"CHANGE COLUMN `{new_column}` `{column_name}` " - f"JSON COMMENT '{new_comment}'" - ) - connection.query(sql) - - detail["status"] = "finalized" - result["columns_migrated"] += 1 - logger.info(f"Finalized {database}.{table_name}.{column_name}") - except Exception as e: - detail["status"] = "error" - detail["error"] = str(e) - logger.error(f"Failed to finalize: {e}") - raise DataJointError(f"Finalize failed: {e}") from e - else: - detail["action"] = "migrate" - - # Skip columns whose _v2 column already exists - if (table_name, column_name) not in plans: - detail["status"] = "already_migrated" - result["details"].append(detail) - continue - metadata, problems = plans[table_name, column_name] - - if dry_run: - count_sql = f""" - SELECT COUNT(*) FROM `{database}`.`{table_name}` - WHERE `{column_name}` IS NOT NULL - """ - count = connection.query(count_sql).fetchone()[0] - detail["rows"] = count - detail["problems"] = problems - detail["status"] = "dry_run" - logger.info(f"Would migrate {database}.{table_name}.{column_name}: " f"{count} rows") - for problem in problems: - logger.warning(f"Cannot migrate {problem}") - else: - try: - count = _add_converted_column( - connection, database, table_name, column_name, new_column, new_comment, metadata - ) - detail["rows"] = count - detail["status"] = "migrated" - result["columns_migrated"] += 1 - result["rows_migrated"] += count - - logger.info(f"Migrated {database}.{table_name}.{column_name}: " f"{count} rows") - except Exception as e: - detail["status"] = "error" - detail["error"] = str(e) - logger.error(f"Failed to migrate: {e}") - raise DataJointError(f"Migration failed: {e}") from e - - result["details"].append(detail) - - return result + return _migrate_legacy_columns(schema, ("filepath",), dry_run, finalize) # ============================================================================= @@ -1956,6 +2004,126 @@ def create_parallel_schema( return result +def _plan_copy_conversions( + connection, source_schema: str, dest_schema: str, table: str, where_clause: str | None +) -> dict[str, dict[bytes, dict]]: + """ + Plan the conversion of the 0.14 in-store columns that ``copy_table_data`` copies. + + A source column in the 0.14 layout (BINARY(16) with a ``:blob@store:``, + ``:attach@store:``, or ``:filepath@store:`` comment) is converted when the + destination column is not BINARY(16): it must then be declared with the + same codec, for example ````, whose store names the 2.0 store. + Returns the metadata for each reference, keyed by column. Raises before + anything is copied if a reference cannot be converted. + """ + from .settings import config + + rows = connection.query( + """ + SELECT COLUMN_NAME FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = %s AND TABLE_NAME = %s AND DATA_TYPE = 'binary' AND CHARACTER_MAXIMUM_LENGTH = 16 + ORDER BY ORDINAL_POSITION + """, + args=(source_schema, table), + ).fetchall() + + conversions: dict[str, dict[bytes, dict]] = {} + problems: list[str] = [] + for (column_name,) in rows: + source = _column_info(connection, source_schema, table, column_name) + kind, store_name = _legacy_kind(source["comment"]) + if kind is None: + continue + dest = _column_info(connection, dest_schema, table, column_name) + if dest is None or dest["binary16"]: + continue # the destination keeps the 0.14 layout: copy the references as they are + match = re.match(rf":<{kind}@([a-z][\-\w]*)?>:", dest["comment"]) + if match is None: + raise DataJointError( + f"Cannot copy {source_schema}.{table}.{column_name}, a 0.14 {kind}@{store_name} column: " + f"{dest_schema}.{table}.{column_name} is not declared as <{kind}@store>. Nothing was copied." + ) + dest_store = match.group(1) or config.resolve_store_name(None, use_filepath_default=kind == "filepath") + metadata, column_problems = _plan_legacy_references( + connection, source_schema, table, column_name, kind, store_name, dest_store, where_clause=where_clause + ) + conversions[column_name] = metadata + problems += column_problems + if problems: + listed = "\n ".join(problems[:10]) + more = f"\n ... and {len(problems) - 10} more" if len(problems) > 10 else "" + raise DataJointError( + f"Cannot copy {source_schema}.{table}: {len(problems)} reference(s) cannot be converted. " + f"Nothing was copied.\n {listed}{more}" + ) + return conversions + + +def _copy_with_conversions( + connection, + source_schema: str, + dest_schema: str, + table: str, + conversions: dict[str, dict[bytes, dict]], + where_clause: str | None, + limit: int | None, +) -> None: + """ + Copy rows, writing the 2.0 metadata for each converted column, in one INSERT. + + The metadata is staged in a temporary table per column and joined to the + source rows, so the copy is a single statement. + """ + source = f"`{source_schema}`.`{table}`" + columns = [ + name + for (name,) in connection.query( + """ + SELECT COLUMN_NAME FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = %s AND TABLE_NAME = %s ORDER BY ORDINAL_POSITION + """, + args=(source_schema, table), + ).fetchall() + ] + staged = {name: f"`{dest_schema}`.`~migrate_{index}`" for index, name in enumerate(conversions)} + try: + select, joins = [], [] + for index, name in enumerate(conversions): + connection.query( + f"CREATE TEMPORARY TABLE {staged[name]} " + f"(`__dj_reference` binary(16) NOT NULL PRIMARY KEY, `__dj_metadata` JSON NOT NULL)" + ) + items = list(conversions[name].items()) + for start in range(0, len(items), 500): + chunk = items[start : start + 500] + connection.query( + f"INSERT INTO {staged[name]} VALUES " + ", ".join(["(%s, %s)"] * len(chunk)), + args=tuple(value for reference, metadata in chunk for value in (reference, json.dumps(metadata))), + ) + joins.append( + f"LEFT JOIN {staged[name]} AS `__dj_migrate_{index}` " + f"ON `__dj_migrate_{index}`.`__dj_reference` = {source}.`{name}`" + ) + for name in columns: + if name in conversions: + select.append(f"`__dj_migrate_{list(conversions).index(name)}`.`__dj_metadata`") + else: + select.append(f"{source}.`{name}`") + query = ( + f"INSERT INTO `{dest_schema}`.`{table}` ({', '.join(f'`{name}`' for name in columns)}) " + f"SELECT {', '.join(select)} FROM {source} {' '.join(joins)}" + ) + if where_clause: + query += f" WHERE {where_clause}" + if limit: + query += f" LIMIT {limit}" + connection.query(query) + finally: + for table_name in staged.values(): + connection.query(f"DROP TEMPORARY TABLE IF EXISTS {table_name}") + + def copy_table_data( source_schema: str, dest_schema: str, @@ -1999,6 +2167,19 @@ def copy_table_data( ... limit=100, ... where_clause="session_date >= '2024-01-01'" ... ) + + Notes + ----- + When the source table is in the 0.14 layout and the destination table is + declared by DataJoint 2.0, in-store columns are converted as they are + copied. A 0.14 ``blob@store``, ``attach@store``, or ``filepath@store`` + column must then be declared ````, ````, or + ```` in the destination. The destination store names the + store in the metadata, and must point to the 0.14 location. Files stay + where they are. Every referenced file is looked up before anything is + copied; if one has no row in the source's ``~external_`` table or is + missing, the copy raises and copies nothing. The rows are then copied in a + single statement. """ import time from . import conn as get_conn @@ -2008,17 +2189,16 @@ def copy_table_data( start_time = time.time() - # Build query - query = f"INSERT INTO `{dest_schema}`.`{table}` SELECT * FROM `{source_schema}`.`{table}`" - - if where_clause: - query += f" WHERE {where_clause}" - - if limit: - query += f" LIMIT {limit}" - - # Execute copy - connection.query(query) + conversions = _plan_copy_conversions(connection, source_schema, dest_schema, table, where_clause) + if conversions: + _copy_with_conversions(connection, source_schema, dest_schema, table, conversions, where_clause, limit) + else: + query = f"INSERT INTO `{dest_schema}`.`{table}` SELECT * FROM `{source_schema}`.`{table}`" + if where_clause: + query += f" WHERE {where_clause}" + if limit: + query += f" LIMIT {limit}" + connection.query(query) # Get row count count_query = f"SELECT COUNT(*) FROM `{dest_schema}`.`{table}`" @@ -2330,13 +2510,15 @@ def migrate_external_pointers_v2( connection=None, ) -> dict: """ - Migrate external storage pointers from 0.14.6 to 2.0 format. + Convert one 0.14 in-store column to 2.0 format, in place. - Converts the 16-byte 0.14 references in one column to JSON metadata, - in place. File copying (``copy_files``) is not implemented yet. + Use it on a table still in the 0.14 layout, for example in a copy made with + ``create_parallel_schema(..., copy_data=True)``, to convert one column and + name a different 2.0 store. File copying (``copy_files``) is not + implemented yet: the metadata points to the existing files. - This is useful when copying production data to _v2 schemas and you need - to access external storage attributes but don't want to move the files yet. + To copy a 0.14 table into a table declared by DataJoint 2.0, use + ``copy_table_data``, which converts in-store columns as it copies. Parameters ---------- @@ -2362,7 +2544,7 @@ def migrate_external_pointers_v2( - rows_migrated: int - number of pointers migrated - files_copied: int - number of files copied (if copy_files=True) - errors: list - always empty; a reference that cannot be converted - raises before any row is updated + raises before anything is changed Examples -------- @@ -2379,22 +2561,21 @@ def migrate_external_pointers_v2( Notes ----- - This function: - 1. Reads the BINARY(16) references in the column - 2. Looks each one up in the ~external_{source_store} table - 3. Finds its file where 0.14 stored it, through ``dest_store`` - 4. Updates the column with JSON metadata - - It writes the same metadata as ``migrate_external``: - ``{hash, path, schema, store, size}`` for blobs and attachments (attachments - also record ``attachment_name``) and ``{path, store, size, is_dir, timestamp}`` - for filepaths. - - The column must already be able to hold the JSON metadata. A column still in - the 0.14 layout (BINARY(16)) is refused; ``migrate_external`` and - ``migrate_filepath`` convert such columns in place. Every reference is looked - up before any row is updated: if one has no tracking row or its file is - missing, the function raises and changes nothing. + The column must hold 0.14 references (16 bytes) and keep its 0.14 comment, + such as ``:blob@external-raw:``, whose store must be ``source_store``. The + function: + + 1. Looks each reference up in ``~external_{source_store}`` and finds its + file where 0.14 stored it, through ``dest_store`` + 2. Adds a JSON column ``_v2`` with the 2.0 metadata, as + ``migrate_external`` and ``migrate_filepath`` write it, naming ``dest_store`` + 3. Renames ``attribute`` to ``_v1`` and ``_v2`` to + ``attribute``, with the comment ``::`` (or ``attach``, + ``filepath``) and the original nullability + + Every reference is looked up before anything is changed: if one has no + tracking row or its file is missing, the function raises and changes + nothing. If a later step fails, the added column is dropped again. """ from . import conn as get_conn @@ -2403,68 +2584,61 @@ def migrate_external_pointers_v2( logger.info(f"Migrating external pointers: {schema}.{table}.{attribute} " f"({source_store} → {dest_store})") - # Get source store specification (0.14.6) - # Note: This assumes old external table exists - external_table = f"~external_{source_store}" + label = f"{schema}.{table}.{attribute}" + column = _column_info(connection, schema, table, attribute) + if column is None: + raise DataJointError(f"Attribute {attribute} not found in {schema}.{table}") + kind, store_name = _legacy_kind(column["comment"]) + if kind is None: + if re.match(r":<(blob|attach|filepath)@", column["comment"]): + raise DataJointError( + f"{label} is already a 2.0 in-store column and holds no 0.14 references. " + f"To copy a 0.14 table into a 2.0 table, use copy_table_data, " + f"which converts in-store columns as it copies." + ) + raise DataJointError(f"{label} has no 0.14 in-store type (blob@, attach@, or filepath@) in its comment.") + if column["data_type"] == "json": + raise DataJointError( + f"{label} was finalized by an earlier DataJoint 2.x release. " + f"Run migrate_external or migrate_filepath with dry_run=False to repair it." + ) + if store_name != source_store: + raise DataJointError(f"{label} is in 0.14 store '{store_name}', not source_store '{source_store}'.") - # Check if external tracking table exists - check_query = """ + external_table = f"~external_{source_store}" + exists = connection.query( + """ SELECT COUNT(*) FROM information_schema.TABLES WHERE TABLE_SCHEMA = %s AND TABLE_NAME = %s - """ - exists = connection.query(check_query, args=(schema, external_table)).fetchone()[0] - + """, + args=(schema, external_table), + ).fetchone()[0] if not exists: raise DataJointError( f"External tracking table {schema}.{external_table} not found. " f"Cannot migrate external pointers from 0.14.6 format." ) - result = { - "rows_migrated": 0, - "files_copied": 0, - "errors": [], - } - - # Find the column and what its 0.14 type was - column = connection.query( - """ - SELECT DATA_TYPE, CHARACTER_MAXIMUM_LENGTH, COLUMN_COMMENT - FROM information_schema.COLUMNS - WHERE TABLE_SCHEMA = %s AND TABLE_NAME = %s AND COLUMN_NAME = %s - """, - args=(schema, table, attribute), - ).fetchone() - if column is None: - raise DataJointError(f"Attribute {attribute} not found in {schema}.{table}") - data_type, max_length, comment = column - - patterns = {**EXTERNAL_PATTERNS, "filepath": FILEPATH_PATTERN} - kind = next((name for name, pattern in patterns.items() if pattern.search(comment or "")), None) - if kind is None: - raise DataJointError( - f"{schema}.{table}.{attribute} has no 0.14 in-store type (blob@, attach@, or filepath@) in its comment." - ) - if data_type.lower() == "binary" and max_length == 16: - raise DataJointError( - f"{schema}.{table}.{attribute} is a 0.14 BINARY(16) column and cannot hold JSON metadata. " - f"Use migrate_external or migrate_filepath to convert it in place." - ) + for suffix in ("_v1", "_v2"): + if _column_exists(connection, schema, table, attribute + suffix): + raise DataJointError(f"Cannot migrate {label}: {attribute}{suffix} already exists. Nothing was changed.") metadata, problems = _plan_legacy_references(connection, schema, table, attribute, kind, source_store, dest_store) - _refuse_problems(f"{schema}.{table}.{attribute}", problems) + _refuse_problems(label, problems) if copy_files: logger.warning("File copying not yet implemented in migrate_external_pointers_v2") - with connection.transaction: - for reference, value in metadata.items(): - cursor = connection.query( - f"UPDATE `{schema}`.`{table}` SET `{attribute}` = %s WHERE `{attribute}` = %s", - args=(json.dumps(value), reference), - ) - result["rows_migrated"] += cursor.rowcount - - logger.info(f"Migrated {result['rows_migrated']} external pointers for {schema}.{table}.{attribute}") + new_column = f"{attribute}_v2" + comment = _new_comment(kind, dest_store, column["comment"]) + rows = _add_converted_column(connection, schema, table, attribute, new_column, comment, kind, metadata) + try: + _swap_in_converted_column( + connection, schema, table, attribute, new_column, column["column_type"], comment, column["nullable"] + ) + except Exception: + connection.query(f"ALTER TABLE `{schema}`.`{table}` DROP COLUMN `{new_column}`") + raise - return result + logger.info(f"Migrated {rows} external pointers for {label}") + return {"rows_migrated": rows, "files_copied": 0, "errors": []} diff --git a/tests/integration/test_migrate_legacy_external.py b/tests/integration/test_migrate_legacy_external.py index 6078100cb..36e5780e0 100644 --- a/tests/integration/test_migrate_legacy_external.py +++ b/tests/integration/test_migrate_legacy_external.py @@ -17,9 +17,11 @@ import datajoint as dj from datajoint.errors import DataJointError from datajoint.hash_registry import compute_hash, get_hash +from datajoint import migrate as dj_migrate from datajoint.migrate import ( _legacy_hash, _legacy_path, + copy_table_data, migrate_external, migrate_external_pointers_v2, migrate_filepath, @@ -192,6 +194,11 @@ def test_migrated_columns_return_their_values(schema014): # The 0.14 references are kept beside the migrated columns. assert {"signal_v1", "report_v1", "raw_file_v1"} <= _columns(schema014) + # A required 0.14 column stays required; optional ones stay optional. + attributes = _recording(schema014).heading.attributes + assert not attributes["signal"].nullable + assert attributes["report"].nullable and attributes["raw_file"].nullable + assert attributes["signal"].comment == "raw signal" assert verify_schema_v20(schema014.database, connection=schema014.connection)["compatible"] @@ -233,43 +240,66 @@ def test_missing_file_stops_migration_unchanged(schema014, legacy_store): assert _columns(schema014) == before # the blob column was not converted either -def test_pointers_v2_refuses_binary16_column(schema014): - before = _columns(schema014) - with pytest.raises(DataJointError, match="BINARY\\(16\\)"): - migrate_external_pointers_v2( - schema=schema014.database, - table="recording", - attribute="signal", - source_store="legacy", - dest_store="legacy", - connection=schema014.connection, - ) - assert _columns(schema014) == before - - -def test_pointers_v2_writes_2x_metadata(schema014): - db, connection = schema014.database, schema014.connection - # Widen the column so that it can hold the JSON metadata. +def _drop_foreign_key(schema, column): + db, connection = schema.database, schema.connection constraint = connection.query( "SELECT CONSTRAINT_NAME FROM information_schema.KEY_COLUMN_USAGE " - "WHERE TABLE_SCHEMA = %s AND TABLE_NAME = 'recording' AND COLUMN_NAME = 'signal' " + "WHERE TABLE_SCHEMA = %s AND TABLE_NAME = 'recording' AND COLUMN_NAME = %s " "AND REFERENCED_TABLE_NAME IS NOT NULL", - args=(db,), + args=(db, column), ).fetchone()[0] connection.query(f"ALTER TABLE `{db}`.`recording` DROP FOREIGN KEY `{constraint}`") - connection.query( - f"ALTER TABLE `{db}`.`recording` MODIFY `signal` varbinary(1024) NOT NULL COMMENT ':blob@legacy:raw signal'" - ) - result = migrate_external_pointers_v2( - schema=db, + +def _pointers_v2(schema, attribute, dest_store="legacy"): + return migrate_external_pointers_v2( + schema=schema.database, table="recording", - attribute="signal", + attribute=attribute, source_store="legacy", - dest_store="legacy", - connection=connection, + dest_store=dest_store, + connection=schema.connection, + ) + + +@pytest.fixture +def raw_store(legacy_store): + """A 2.x store named `raw` at the 0.14 location.""" + dj.config.stores["raw"] = {"protocol": "file", "location": str(legacy_store)} + yield "raw" + + +def test_pointers_v2_converts_binary16_column(schema014, raw_store): + """Option A on a table in the 0.14 layout: the column reads in 2.x, through the new store name.""" + assert _pointers_v2(schema014, "signal", dest_store=raw_store)["rows_migrated"] == 2 + assert _pointers_v2(schema014, "report", dest_store=raw_store)["rows_migrated"] == 1 + + recording = _recording(schema014) + np.testing.assert_array_equal((recording & {"recording_id": 1}).fetch1("signal"), SIGNAL) + np.testing.assert_array_equal((recording & {"recording_id": 2}).fetch1("signal"), COUNTS) + assert Path((recording & {"recording_id": 1}).fetch1("report")).read_bytes() == REPORT + attributes = recording.heading.attributes + assert not attributes["signal"].nullable and attributes["report"].nullable + assert attributes["signal"].comment == "raw signal" + assert {"signal_v1", "report_v1"} <= _columns(schema014) + + db = schema014.database + stored = schema014.connection.query(f"SELECT `signal` FROM `{db}`.`recording` WHERE recording_id = 1").fetchone()[0] + assert json.loads(stored)["store"] == raw_store + + +def test_pointers_v2_converts_widened_column(schema014): + """A column widened by hand that keeps its 0.14 comment is converted to a column 2.x reads.""" + db, connection = schema014.database, schema014.connection + _drop_foreign_key(schema014, "signal") + connection.query( + f"ALTER TABLE `{db}`.`recording` MODIFY `signal` varbinary(1024) NOT NULL COMMENT ':blob@legacy:raw signal'" ) - assert result["rows_migrated"] == 2 + + assert _pointers_v2(schema014, "signal")["rows_migrated"] == 2 + recording = _recording(schema014) + for recording_id, expected in ((1, SIGNAL), (2, COUNTS)): + np.testing.assert_array_equal((recording & {"recording_id": recording_id}).fetch1("signal"), expected) rows = connection.query(f"SELECT recording_id, `signal` FROM `{db}`.`recording` ORDER BY recording_id").fetchall() for (_, stored), blob in zip(rows, (SIGNAL_BLOB, COUNTS_BLOB)): metadata = json.loads(stored) @@ -278,6 +308,239 @@ def test_pointers_v2_writes_2x_metadata(schema014): assert get_hash(metadata) == blob +def test_pointers_v2_refuses_2x_declared_column(schema014, raw_store): + """A column declared by 2.x holds no 0.14 references; the error points to copy_table_data.""" + v2 = _schema_v2(schema014) + try: + with pytest.raises(DataJointError, match="copy_table_data"): + migrate_external_pointers_v2( + schema=v2.database, + table="recording", + attribute="signal", + source_store="legacy", + dest_store=raw_store, + connection=v2.connection, + ) + finally: + v2.drop(prompt=False) + + +def test_pointers_v2_missing_file_changes_nothing(schema014, legacy_store): + (legacy_store / _legacy_path(schema014.database, _md5(SIGNAL_BLOB), (2, 2))).unlink() + before = _columns(schema014) + with pytest.raises(DataJointError, match="Nothing was changed"): + _pointers_v2(schema014, "signal") + assert _columns(schema014) == before + + +def _schema_v2(schema014, store="raw"): + """The 2.x declaration of `recording`, as Option A's Phase I code declares it.""" + v2 = dj.Schema(f"{schema014.database}_v2", connection=schema014.connection) + + @v2 + class Recording(dj.Manual): + definition = f""" + recording_id : int32 + --- + signal : # raw signal + report = null : # report file + raw_file = null : # acquired file + """ + + return v2 + + +def test_copy_table_data_converts_014_columns(schema014, raw_store): + """Option A end to end: copy a 0.14 table into its 2.x declaration and read it back.""" + v2 = _schema_v2(schema014) + try: + result = copy_table_data(schema014.database, v2.database, "recording", connection=schema014.connection) + assert result["rows_copied"] == 2 + + recording = dj.FreeTable(v2.connection, f"`{v2.database}`.`recording`") + np.testing.assert_array_equal((recording & {"recording_id": 1}).fetch1("signal"), SIGNAL) + np.testing.assert_array_equal((recording & {"recording_id": 2}).fetch1("signal"), COUNTS) + report = Path((recording & {"recording_id": 1}).fetch1("report")) + assert report.name == REPORT_NAME and report.read_bytes() == REPORT + assert (recording & {"recording_id": 2}).fetch1("report") is None + assert (recording & {"recording_id": 1}).fetch1("raw_file").read() == RAW + finally: + v2.drop(prompt=False) + + +def test_copy_table_data_with_where_and_limit(schema014, raw_store, legacy_store): + """Only the rows copied are looked up; a missing file elsewhere does not block the copy.""" + (legacy_store / _legacy_path(schema014.database, _md5(SIGNAL_BLOB), (2, 2))).unlink() + v2 = _schema_v2(schema014) + try: + result = copy_table_data( + schema014.database, + v2.database, + "recording", + where_clause="recording_id = 2", + limit=1, + connection=schema014.connection, + ) + assert result["rows_copied"] == 1 + recording = dj.FreeTable(v2.connection, f"`{v2.database}`.`recording`") + np.testing.assert_array_equal((recording & {"recording_id": 2}).fetch1("signal"), COUNTS) + finally: + v2.drop(prompt=False) + + +def test_copy_table_data_missing_file_copies_nothing(schema014, raw_store, legacy_store): + (legacy_store / _legacy_path(schema014.database, _md5(SIGNAL_BLOB), (2, 2))).unlink() + v2 = _schema_v2(schema014) + try: + with pytest.raises(DataJointError, match="Nothing was copied"): + copy_table_data(schema014.database, v2.database, "recording", connection=schema014.connection) + recording = dj.FreeTable(v2.connection, f"`{v2.database}`.`recording`") + assert len(recording) == 0 + finally: + v2.drop(prompt=False) + + +def test_copy_table_data_refuses_other_codec(schema014, raw_store): + """A 0.14 blob@ column copied into a column that is not is refused.""" + v2 = dj.Schema(f"{schema014.database}_v2", connection=schema014.connection) + + @v2 + class Recording(dj.Manual): + definition = """ + recording_id : int32 + --- + signal : + report = null : + raw_file = null : + """ + + try: + with pytest.raises(DataJointError, match="not declared as "): + copy_table_data(schema014.database, v2.database, "recording", connection=schema014.connection) + assert len(Recording()) == 0 + finally: + v2.drop(prompt=False) + + +def test_comments_with_quotes_and_percent(schema014): + """0.14 comments with an apostrophe, a percent sign, or a backslash are kept through migration.""" + db, connection = schema014.database, schema014.connection + comment = "subject's report, 100% done \\ v2" + connection.query( + f"ALTER TABLE `{db}`.`recording` MODIFY `report` binary(16) DEFAULT NULL COMMENT %s", + args=(":attach@legacy:" + comment,), + ) + _migrate(schema014) + recording = _recording(schema014) + assert recording.heading.attributes["report"].comment == comment + assert Path((recording & {"recording_id": 1}).fetch1("report")).read_bytes() == REPORT + + +def test_failure_drops_the_columns_this_run_added(schema014, monkeypatch): + """If a later column fails, the _v2 columns already added are dropped again.""" + added = dj_migrate._add_converted_column + calls = [] + + def fail_second(*args, **kwargs): + calls.append(args[3]) + if len(calls) == 2: + raise DataJointError("simulated failure") + return added(*args, **kwargs) + + monkeypatch.setattr(dj_migrate, "_add_converted_column", fail_second) + before = _columns(schema014) + with pytest.raises(DataJointError, match="simulated failure"): + migrate_external(schema014, dry_run=False) + assert len(calls) == 2 + assert _columns(schema014) == before + + +# Values that DataJoint 2.x releases before this fix wrote: no path, no store, a hex hash +def _old_value(digest, size): + return json.dumps({"url": None, "hash": digest.hex().upper(), "size": size}) + + +def _write_old_v2_columns(schema): + db, connection = schema.database, schema.connection + for column, comment in (("signal", ":blob@legacy: raw signal"), ("report", ":attach@legacy: report file")): + connection.query(f"ALTER TABLE `{db}`.`recording` ADD COLUMN `{column}_v2` JSON COMMENT '{comment}'") + connection.query( + f"UPDATE `{db}`.`recording` t JOIN `{db}`.`~external_legacy` e ON t.`{column}` = e.hash " + f"SET t.`{column}_v2` = JSON_OBJECT('url', NULL, 'hash', HEX(e.hash), 'size', e.size)" + ) + + +def test_rerun_rewrites_v2_columns_from_earlier_release(schema014): + """_v2 columns written by an earlier release are rewritten, not skipped.""" + _write_old_v2_columns(schema014) + + preview = migrate_external(schema014, dry_run=True) + assert {detail["action"] for detail in preview["details"]} == {"rewrite"} + with pytest.raises(DataJointError, match="cannot be finalized"): + migrate_external(schema014, dry_run=False, finalize=True) + + assert migrate_external(schema014, dry_run=False)["rows_migrated"] == 3 + recording = _recording(schema014) & {"recording_id": 1} + np.testing.assert_array_equal(recording.fetch1("signal_v2"), SIGNAL) + assert Path(recording.fetch1("report_v2")).read_bytes() == REPORT + + # Now readable, so a further rerun skips them. + statuses = {detail["status"] for detail in migrate_external(schema014, dry_run=False)["details"]} + assert statuses == {"already_migrated"} + assert migrate_external(schema014, dry_run=False, finalize=True)["columns_migrated"] == 2 + np.testing.assert_array_equal((_recording(schema014) & {"recording_id": 1}).fetch1("signal"), SIGNAL) + + +def test_rerun_repairs_columns_finalized_by_earlier_release(schema014): + """Columns that an earlier release finalized are rewritten from the references kept in _v1.""" + db, connection = schema014.database, schema014.connection + _write_old_v2_columns(schema014) + # What finalize did in an earlier release + for column, comment in (("signal", ":blob@legacy: raw signal"), ("report", ":attach@legacy: report file")): + connection.query( + f"ALTER TABLE `{db}`.`recording` CHANGE COLUMN `{column}` `{column}_v1` binary(16) COMMENT 'legacy 0.x'" + ) + connection.query(f"ALTER TABLE `{db}`.`recording` CHANGE COLUMN `{column}_v2` `{column}` JSON COMMENT '{comment}'") + + result = migrate_external(schema014, dry_run=False) + assert {detail["action"] for detail in result["details"]} == {"repair"} + assert result["rows_migrated"] == 3 + recording = _recording(schema014) + np.testing.assert_array_equal((recording & {"recording_id": 1}).fetch1("signal"), SIGNAL) + np.testing.assert_array_equal((recording & {"recording_id": 2}).fetch1("signal"), COUNTS) + assert Path((recording & {"recording_id": 1}).fetch1("report")).read_bytes() == REPORT + assert recording.heading.attributes["signal"].comment == "raw signal" + + +def test_finalize_refuses_without_v2_columns(schema014): + before = _columns(schema014) + preview = migrate_filepath(schema014, dry_run=True, finalize=True) + assert "does not exist" in preview["details"][0]["problems"][0] + with pytest.raises(DataJointError, match="Nothing was changed"): + migrate_filepath(schema014, dry_run=False, finalize=True) + assert _columns(schema014) == before + + +def test_filepath_without_contents_hash(schema014): + """0.14.7+ leaves contents_hash NULL for large files; the file still migrates and reads.""" + db = schema014.database + schema014.connection.query( + f"UPDATE `{db}`.`~external_legacy` SET contents_hash = NULL WHERE hash = %s", + args=(_md5(RAW_PATH.encode()),), + ) + preview = migrate_filepath(schema014, dry_run=True) + assert preview["details"][0]["problems"] == [] + _migrate(schema014) + assert (_recording(schema014) & {"recording_id": 1}).fetch1("raw_file").read() == RAW + + +def test_dry_run_needs_the_store(schema014): + """A dry run looks files up, so the store must be configured.""" + del dj.config.stores["legacy"] + with pytest.raises(DataJointError, match="legacy"): + migrate_external(schema014, dry_run=True) + + def test_migrated_attachment_reads(connection_by_backend, backend, prefix, legacy_store): """A migrated attachment's metadata reads through on either backend.""" schema = dj.Schema(f"{prefix}_legacy_attach_{backend}", connection=connection_by_backend) diff --git a/tests/unit/test_migrate_legacy_store.py b/tests/unit/test_migrate_legacy_store.py index 644a237e1..dc85ea8b9 100644 --- a/tests/unit/test_migrate_legacy_store.py +++ b/tests/unit/test_migrate_legacy_store.py @@ -2,7 +2,7 @@ DataJoint 0.14 kept blobs and attachments at paths derived from a 16-byte MD5 digest. Its layout, taken from ``datajoint/external.py`` and ``datajoint/hash.py`` -at the 0.14.6 tag: +at the 0.14.6 tag and unchanged through 0.14.10: - a blob at ``{database}/{subfolders}/{hex digest}``, the digest of its bytes; - an attachment at ``{database}/{subfolders}/{hex digest}.{name}``, the digest of @@ -20,7 +20,16 @@ from datajoint.errors import DataJointError from datajoint.hash_registry import compute_hash, get_hash -from datajoint.migrate import _legacy_hash, _legacy_path, _legacy_subfolding, verify_schema_v20 +from datajoint.adapters.mysql import MySQLAdapter +from datajoint.migrate import ( + _comment_literal, + _legacy_hash, + _legacy_kind, + _legacy_path, + _legacy_subfolding, + _new_comment, + verify_schema_v20, +) from datajoint.settings import Config # The digest from the issue report: `{location}/{database}/ec/88/`. @@ -136,3 +145,37 @@ def test_verify_schema_v20_query_formats_with_arguments(): result = verify_schema_v20("lab_ephys", connection=connection) assert result["compatible"] assert any("LIKE '%blob'" in q for q in connection.queries) + + +class _MySQLConnection: + adapter = MySQLAdapter() + + +@pytest.mark.parametrize( + "comment", + ["subject's report", "100% done", "path C:\\data\\raw", "it's 50% \\ 'quoted'"], +) +def test_comment_literal_survives_formatting(comment): + """A comment literal formats with arguments and reads back as the same text.""" + literal = _comment_literal(_MySQLConnection(), comment) + formatted = literal % () # what Connection.query does with no arguments + assert formatted.startswith("'") and formatted.endswith("'") + body = formatted[1:-1] + assert body.replace("''", "'").replace("\\\\", "\\") == comment + + +@pytest.mark.parametrize( + "comment, kind, store, new", + [ + (":blob@legacy:raw signal", "blob", "legacy", "::raw signal"), + (":attach@ext-store:subject's report", "attach", "ext-store", "::subject's report"), + (":filepath@raw:", "filepath", "raw", "::"), + ], +) +def test_legacy_kind_and_new_comment(comment, kind, store, new): + assert _legacy_kind(comment) == (kind, store) + assert _new_comment(kind, store, comment) == new + + +def test_2x_comment_is_not_a_legacy_kind(): + assert _legacy_kind("::raw signal") == (None, None) From 9ab9f898ccea3b92d829d9479003876206bec4c3 Mon Sep 17 00:00:00 2001 From: Dimitri Yatsenko Date: Mon, 23 Nov 2026 18:16:36 -0600 Subject: [PATCH 3/6] fix(migrate): 0.14 paths on copied schemas; GC keeps 0.14 files; null subfolding - migrate_external, migrate_external_pointers_v2, copy_table_data and verify_external_integrity take legacy_database, the database 0.14 wrote the files from. 0.14 put blob and attachment files under that name, so a copy of a 0.14 schema is migrated by naming the original. copy_table_data defaults to the source schema. A refusal for missing files says so. - create_parallel_schema creates and fills tables with foreign key checks off for the session, so tables that come before the tables they reference (such as the 0.14 ~external_* tables, which sort last) are created. Comments with % are copied. - Garbage collection never deletes migrated 0.14 files in the root-level layout (schema_prefix=""): hash references count as covering, files named as 0.14 named blobs and attachments are never orphans, and the section of a schema that still has ~external_* tables is not listed. - "subfolding": null, as the configuration template writes it, means unset, so 0.14's default (2, 2) applies. - Repair keeps a column nullable when an earlier release's finalize made it so, says so in the dry run and the log, and the docstring explains how to restore NOT NULL. --- src/datajoint/gc.py | 49 ++++- src/datajoint/migrate.py | 166 ++++++++++++---- .../test_migrate_legacy_external.py | 178 ++++++++++++++++++ tests/unit/test_migrate_legacy_store.py | 8 +- 4 files changed, 362 insertions(+), 39 deletions(-) diff --git a/src/datajoint/gc.py b/src/datajoint/gc.py index 97f8c89d2..0d14a3117 100644 --- a/src/datajoint/gc.py +++ b/src/datajoint/gc.py @@ -36,6 +36,13 @@ schemas sharing a store may be collected safely, and GC never touches another schema's objects or user-managed content elsewhere in the store. +Files migrated from DataJoint 0.14 stay where 0.14 stored them, +``{database}/...``, which is inside the schema section when a store uses the +root-level layout (``schema_prefix=""``). GC never deletes them there: a file +that a migrated row references counts as referenced, a file named as 0.14 named +its blobs and attachments is never an orphan, and the section of a schema that +still has 0.14 ``~external_*`` tracking tables is not listed at all. + See Also -------- datajoint.builtin_codecs : Codec implementations for object storage types. @@ -58,6 +65,11 @@ # Base32 content-hash filename: 26 lowercase alphanumeric chars. _BASE32_HASH = re.compile(r"^[a-z2-7]{26}$") +# DataJoint 0.14 named an in-store blob by the hex MD5 digest of its contents, +# and an attachment by that digest, a dot, and the attachment's name, under +# ``{database}/``. These files can sit inside the root-level schema section. +_LEGACY_014_NAME = re.compile(r"^[0-9a-f]{32}(\..+)?$") + def _is_covered(path: str, referenced: set[str]) -> bool: """ @@ -277,6 +289,18 @@ def list_schema_paths(self, schema_name: str) -> dict[str, int]: self._scan_errors.append(f"list_schema_paths({schema_name}): {e}") return stored + @staticmethod + def _has_legacy_tracking_tables(schema: "Schema") -> bool: + """Return True if the schema has DataJoint 0.14 ``~external_`` tracking tables.""" + if schema.connection.adapter.backend != "mysql": + return False # DataJoint 0.14 ran on MySQL only + return bool( + schema.connection.query( + "SELECT COUNT(*) FROM information_schema.TABLES WHERE TABLE_SCHEMA = %s AND TABLE_NAME LIKE %s", + args=(schema.database, "~external\\_%"), + ).fetchone()[0] + ) + # ------------------------------------------------------------------ # # Deletion # ------------------------------------------------------------------ # @@ -340,6 +364,8 @@ def collect(self, dry_run: bool = True, verbose: bool = False) -> dict[str, Any] - orphaned_schema_paths: orphaned schema files as full relative store paths - hash_paths_deleted / schema_paths_deleted / deleted / bytes_freed (0 when dry_run) / errors / dry_run + - skipped_schemas: schemas whose root-level section was not listed + because they still have DataJoint 0.14 tracking tables """ self._scan_errors = [] # reset per-call; populated by list_*_paths below # References can be gathered across all schemas at once: because paths @@ -350,14 +376,32 @@ def collect(self, dry_run: bool = True, verbose: bool = False) -> dict[str, Any] hash_paths_stored: dict[str, int] = {} schema_paths_stored: dict[str, int] = {} + skipped_schemas: list[str] = [] for schema in self.schemas: hash_paths_stored.update(self.list_hash_paths(schema.database)) + if not self._schema_prefix and self._has_legacy_tracking_tables(schema): + # Root-level layout: {schema}/ is also where DataJoint 0.14 kept + # this schema's files. Their references are in 0.14 tables that + # GC does not read, so the section is not listed at all. + logger.warning( + f"Not listing {schema.database}/ in store {self.store or 'default'}: the schema has " + f"DataJoint 0.14 tracking tables (~external_*), and its 0.14 files share this folder." + ) + skipped_schemas.append(schema.database) + continue schema_paths_stored.update(self.list_schema_paths(schema.database)) orphaned_hash_paths = sorted(set(hash_paths_stored.keys()) - hash_paths_referenced) # Coverage, not exact set difference: a referenced path may be a - # directory-valued object (many files + a manifest sidecar). - orphaned_schema_paths = sorted(p for p in schema_paths_stored if not _is_covered(p, schema_paths_referenced)) + # directory-valued object (many files + a manifest sidecar). Hash + # references count too: metadata migrated from DataJoint 0.14 points to + # files where 0.14 stored them, which in the root-level layout lie + # inside the schema section. Files named as 0.14 named them are never + # orphans here, whether or not a row references them. + covering = schema_paths_referenced | hash_paths_referenced + orphaned_schema_paths = sorted( + p for p in schema_paths_stored if not _is_covered(p, covering) and not _LEGACY_014_NAME.match(p.rsplit("/", 1)[-1]) + ) hash_paths_deleted = 0 schema_paths_deleted = 0 @@ -415,5 +459,6 @@ def collect(self, dry_run: bool = True, verbose: bool = False) -> dict[str, Any] "bytes_freed": bytes_freed, "errors": errors, "scan_errors": list(self._scan_errors), + "skipped_schemas": skipped_schemas, "dry_run": dry_run, } diff --git a/src/datajoint/migrate.py b/src/datajoint/migrate.py index 45230e367..6f8f904bf 100644 --- a/src/datajoint/migrate.py +++ b/src/datajoint/migrate.py @@ -944,6 +944,8 @@ def _find_columns_finalized_earlier(schema: Schema, kinds: tuple[str, ...]) -> l # serialized bytes in `contents_hash`. # # Subfolders come from the store's `subfolding` setting, (2, 2) unless set. +# The path starts with the name of the database 0.14 wrote the file from. For a +# copy of a 0.14 schema, that is the original database, not the copy. # This layout is the same from 0.14.0 through 0.14.10. LEGACY_SUBFOLDING = (2, 2) @@ -953,15 +955,18 @@ def _legacy_subfolding(store_name: str, config=None) -> tuple[int, ...]: Return the subfolding 0.14 used for a store. This is the store's own ``subfolding`` setting, or 0.14's default of (2, 2) - when it has none. The raw setting is read because 2.x defaults to no - subfolding. ``config`` defaults to the global settings. + when it has none. A setting of ``null`` (``None``), which the 2.x + configuration template writes, counts as none. An explicit list wins, + including ``[]`` for a 0.14 store that turned subfolding off. The raw + setting is read because 2.x defaults to no subfolding. ``config`` + defaults to the global settings. """ if config is None: from .settings import config spec = config.stores.get(store_name) - if isinstance(spec, Mapping) and "subfolding" in spec: - return tuple(spec["subfolding"] or ()) + if isinstance(spec, Mapping) and spec.get("subfolding") is not None: + return tuple(spec["subfolding"]) return LEGACY_SUBFOLDING @@ -999,6 +1004,7 @@ def _plan_legacy_references( store_name: str, dest_store: str | None = None, where_clause: str | None = None, + legacy_database: str | None = None, ) -> tuple[dict[bytes, dict], list[str]]: """ Build the 2.x metadata for each 0.14 reference in one column. @@ -1018,6 +1024,9 @@ def _plan_legacy_references( looked up through this store, so it must point at the 0.14 location. where_clause : str, optional Only plan the rows of the table that match this SQL condition. + legacy_database : str, optional + The database that 0.14 put blob and attachment files under. Defaults to + ``database``. For a copy of a 0.14 schema, this is the original. Returns ------- @@ -1029,6 +1038,7 @@ def _plan_legacy_references( from .hash_registry import get_store_backend dest_store = dest_store or store_name + legacy_database = legacy_database or database config = getattr(connection, "_config", None) # the config reads resolve stores with backend = get_store_backend(dest_store, config=config) subfolding = _legacy_subfolding(dest_store, config) @@ -1059,12 +1069,12 @@ def _plan_legacy_references( # contents_hash may be NULL (0.14.7+ skips it for large files); it is not needed path, digest = filepath, None elif kind == "attach": - path = None if attachment_name is None else _legacy_path(database, reference, subfolding, attachment_name) + path = None if attachment_name is None else _legacy_path(legacy_database, reference, subfolding, attachment_name) digest = reference elif filepath: # a blob migrated from 0.11 path, digest = filepath, contents_hash else: - path, digest = _legacy_path(database, reference, subfolding), reference + path, digest = _legacy_path(legacy_database, reference, subfolding), reference if path is None or (kind != "filepath" and digest is None): problems.append(f"{label}: the tracking row in ~external_{store_name} is incomplete") continue @@ -1090,7 +1100,7 @@ def _plan_legacy_references( metadata[reference] = { "hash": _legacy_hash(bytes(digest)), "path": path, - "schema": database, + "schema": legacy_database, "store": dest_store, "size": size, } @@ -1099,12 +1109,19 @@ def _plan_legacy_references( return metadata, problems +_COPY_HINT = ( + "If this schema is a copy of a 0.14 schema, pass legacy_database='': " + "0.14 put blob and attachment files under the name of the database it wrote them from." +) + + def _refuse_problems(where: str, problems: list[str], what: str = "reference(s) cannot be converted") -> None: """Raise if any problem was found. Called before anything is changed.""" if problems: listed = "\n ".join(problems[:10]) more = f"\n ... and {len(problems) - 10} more" if len(problems) > 10 else "" - raise DataJointError(f"Cannot migrate {where}: {len(problems)} {what}. Nothing was changed.\n {listed}{more}") + hint = f"\n{_COPY_HINT}" if any(": no file at " in problem for problem in problems) else "" + raise DataJointError(f"Cannot migrate {where}: {len(problems)} {what}. Nothing was changed.\n {listed}{more}{hint}") def _unreadable_rows(connection, database: str, table_name: str, reference_column: str, column: str, kind: str) -> int: @@ -1225,6 +1242,13 @@ def _repair_column(connection, database: str, col: dict, comment: str, metadata: connection.query( f"ALTER TABLE {table} MODIFY COLUMN `{column_name}` JSON {null} COMMENT {_comment_literal(connection, comment)}" ) + if col["nullable"]: + # The earlier release's finalize made every column nullable; the 0.14 setting is lost. + logger.warning( + f"{database}.{table_name}.{column_name} stays nullable. If it was required in 0.14, " + f"restore NOT NULL by hand, for example: ALTER TABLE {table} MODIFY COLUMN `{column_name}` " + f"JSON NOT NULL COMMENT " + ) return connection.query(f"SELECT COUNT(*) FROM {table} WHERE `{column_name}` IS NOT NULL").fetchone()[0] @@ -1247,7 +1271,9 @@ def _finalize_problems(connection, database: str, col: dict) -> list[str]: return problems -def _migrate_legacy_columns(schema: Schema, kinds: tuple[str, ...], dry_run: bool, finalize: bool) -> dict: +def _migrate_legacy_columns( + schema: Schema, kinds: tuple[str, ...], dry_run: bool, finalize: bool, legacy_database: str | None = None +) -> dict: """Run ``migrate_external`` (blob, attach) or ``migrate_filepath`` (filepath).""" connection = schema.connection database = schema.database @@ -1326,7 +1352,9 @@ def new_detail(col, action): continue mode = "rewrite" # written by an earlier release, with values 2.x cannot read detail = new_detail(col, "rewrite" if mode == "rewrite" else "migrate") - metadata, problems = _plan_legacy_references(connection, database, table_name, column_name, kind, col["store_name"]) + metadata, problems = _plan_legacy_references( + connection, database, table_name, column_name, kind, col["store_name"], legacy_database=legacy_database + ) jobs.append((mode, col, column_name, detail, metadata, problems)) for col in repairs: detail = new_detail(col, "repair") @@ -1337,6 +1365,7 @@ def new_detail(col, action): f"{col['column_name']}_v1", col["external_type"], col["store_name"], + legacy_database=legacy_database, ) jobs.append(("repair", col, f"{col['column_name']}_v1", detail, metadata, problems)) @@ -1348,6 +1377,8 @@ def new_detail(col, action): detail["rows"] = count detail["problems"] = problems detail["status"] = "dry_run" + if mode == "repair" and col["nullable"]: + detail["nullable"] = True # an earlier release's finalize dropped NOT NULL; repair keeps it so verb = {"add": "migrate", "rewrite": "rewrite", "repair": "repair"}[mode] logger.info(f"Would {verb} {detail['table']}.{col['column_name']}: {count} rows, store={col['store_name']}") for problem in problems: @@ -1404,6 +1435,7 @@ def migrate_external( schema: Schema, dry_run: bool = True, finalize: bool = False, + legacy_database: str | None = None, ) -> dict: """ Migrate external storage columns from 0.x to 2.0 format. @@ -1430,6 +1462,11 @@ def migrate_external( finalize : bool, optional If True, rename the original columns to `_v1` and the migrated columns to the original names. Only run after verifying the migration. Default False. + legacy_database : str, optional + The name of the database 0.14 wrote the files from. 0.14 put blob and + attachment files under it: ``{database}/{subfolders}/{hex digest}``. + Defaults to the schema's own name. Set it when migrating a copy of a + 0.14 schema, for example one made with ``create_parallel_schema``. Returns ------- @@ -1476,13 +1513,16 @@ def migrate_external( A rerun skips `_v2` columns that already hold readable metadata. It rewrites `_v2` columns written by an earlier 2.x release, whose values 2.x cannot read. It also repairs columns that an earlier release finalized: - the values are rewritten from the references kept in `_v1`. + the values are rewritten from the references kept in `_v1`. That + release's finalize made every column nullable and did not keep the 0.14 + setting, so a repaired column stays nullable; restore NOT NULL by hand + where the column was required. Finalizing checks first that every `_v2` column exists and holds readable metadata, and changes nothing otherwise. The migrated column keeps the original column's nullability. """ - return _migrate_legacy_columns(schema, ("blob", "attach"), dry_run, finalize) + return _migrate_legacy_columns(schema, ("blob", "attach"), dry_run, finalize, legacy_database) # ============================================================================= @@ -1610,7 +1650,7 @@ def check_store_configuration(schema: Schema) -> dict: return result -def verify_external_integrity(schema: Schema, store_name: str = None) -> dict: +def verify_external_integrity(schema: Schema, store_name: str = None, legacy_database: str | None = None) -> dict: """ Check that all external references point to existing files. @@ -1623,6 +1663,10 @@ def verify_external_integrity(schema: Schema, store_name: str = None) -> dict: The DataJoint schema to check. store_name : str, optional Specific store to check. If None, checks all stores. + legacy_database : str, optional + The name of the database 0.14 wrote the files from, under which it put + blob and attachment files. Defaults to the schema's own name. Set it + for a copy of a 0.14 schema. Returns ------- @@ -1704,7 +1748,9 @@ def verify_external_integrity(schema: Schema, store_name: str = None) -> dict: # Filepaths (and blobs migrated from 0.11) record their path; blobs and # attachments are stored at a path derived from their hash. - relative_path = filepath or _legacy_path(schema.database, bytes(digest), subfolding, attachment_name) + relative_path = filepath or _legacy_path( + legacy_database or schema.database, bytes(digest), subfolding, attachment_name + ) if location: full_path = os.path.join(location, relative_path) else: @@ -1951,6 +1997,15 @@ def create_parallel_schema( >>> result = create_parallel_schema('my_pipeline', 'my_pipeline_v20') >>> print(f"Created {result['tables_created']} tables") + Notes + ----- + The copy is made with foreign key checks off for the session, because + tables are created in name order. With ``copy_data=True``, a 0.14 schema's + in-store columns are copied as they are, with its ``~external_*`` tables: + the copy is still in the 0.14 layout. Its files stay under the source's + name, so pass ``legacy_database=source`` to ``migrate_external`` or + ``migrate_external_pointers_v2`` when migrating the copy. + See Also -------- copy_table_data : Copy data between schemas @@ -1980,24 +2035,34 @@ def create_parallel_schema( "tables": [], } - for table in tables: - # Get CREATE TABLE statement from source - create_stmt = connection.query(f"SHOW CREATE TABLE `{source}`.`{table}`").fetchone()[1] + # Tables are created in name order, so a table can come before the tables + # its foreign keys reference, such as the 0.14 `~external_*` tables, which + # sort last. Foreign key checks are off for this session while the tables + # are created and filled; the source rows already satisfy the constraints. + checks = connection.query("SELECT @@SESSION.foreign_key_checks").fetchone()[0] + connection.query("SET SESSION foreign_key_checks = 0") + try: + for table in tables: + # Get CREATE TABLE statement from source + create_stmt = connection.query(f"SHOW CREATE TABLE `{source}`.`{table}`").fetchone()[1] - # Replace schema name in CREATE statement - create_stmt = create_stmt.replace(f"CREATE TABLE `{table}`", f"CREATE TABLE `{dest}`.`{table}`") + # Replace schema name in CREATE statement. References to tables in + # the same database are unqualified, so they resolve in `dest`. + create_stmt = create_stmt.replace(f"CREATE TABLE `{table}`", f"CREATE TABLE `{dest}`.`{table}`") - # Create table in destination - connection.query(create_stmt) + # Create table in destination (`%` doubled: queries are formatted with their arguments) + connection.query(create_stmt.replace("%", "%%")) - result["tables_created"] += 1 - result["tables"].append(table) + result["tables_created"] += 1 + result["tables"].append(table) - # Copy data if requested - if copy_data: - connection.query(f"INSERT INTO `{dest}`.`{table}` SELECT * FROM `{source}`.`{table}`") + # Copy data if requested + if copy_data: + connection.query(f"INSERT INTO `{dest}`.`{table}` SELECT * FROM `{source}`.`{table}`") - logger.info(f"Created {dest}.{table}") + logger.info(f"Created {dest}.{table}") + finally: + connection.query(f"SET SESSION foreign_key_checks = {int(checks)}") logger.info(f"Created {result['tables_created']} tables in {dest}") @@ -2005,7 +2070,12 @@ def create_parallel_schema( def _plan_copy_conversions( - connection, source_schema: str, dest_schema: str, table: str, where_clause: str | None + connection, + source_schema: str, + dest_schema: str, + table: str, + where_clause: str | None, + legacy_database: str | None = None, ) -> dict[str, dict[bytes, dict]]: """ Plan the conversion of the 0.14 in-store columns that ``copy_table_data`` copies. @@ -2046,16 +2116,25 @@ def _plan_copy_conversions( ) dest_store = match.group(1) or config.resolve_store_name(None, use_filepath_default=kind == "filepath") metadata, column_problems = _plan_legacy_references( - connection, source_schema, table, column_name, kind, store_name, dest_store, where_clause=where_clause + connection, + source_schema, + table, + column_name, + kind, + store_name, + dest_store, + where_clause=where_clause, + legacy_database=legacy_database, ) conversions[column_name] = metadata problems += column_problems if problems: listed = "\n ".join(problems[:10]) more = f"\n ... and {len(problems) - 10} more" if len(problems) > 10 else "" + hint = f"\n{_COPY_HINT}" if any(": no file at " in problem for problem in problems) else "" raise DataJointError( f"Cannot copy {source_schema}.{table}: {len(problems)} reference(s) cannot be converted. " - f"Nothing was copied.\n {listed}{more}" + f"Nothing was copied.\n {listed}{more}{hint}" ) return conversions @@ -2131,6 +2210,7 @@ def copy_table_data( limit: int | None = None, where_clause: str | None = None, connection=None, + legacy_database: str | None = None, ) -> dict: """ Copy data from production table to test table. @@ -2149,6 +2229,10 @@ def copy_table_data( SQL WHERE clause for filtering (without 'WHERE' keyword) connection : Connection, optional Database connection. If None, uses default connection. + legacy_database : str, optional + The name of the database 0.14 wrote the source's files from. Defaults + to ``source_schema``. Set it when the source is itself a copy of a 0.14 + schema. Returns ------- @@ -2179,7 +2263,9 @@ def copy_table_data( where they are. Every referenced file is looked up before anything is copied; if one has no row in the source's ``~external_`` table or is missing, the copy raises and copies nothing. The rows are then copied in a - single statement. + single statement. 0.14 put blob and attachment files under the name of the + database it wrote them from, which is ``source_schema`` unless + ``legacy_database`` is given. """ import time from . import conn as get_conn @@ -2189,7 +2275,7 @@ def copy_table_data( start_time = time.time() - conversions = _plan_copy_conversions(connection, source_schema, dest_schema, table, where_clause) + conversions = _plan_copy_conversions(connection, source_schema, dest_schema, table, where_clause, legacy_database) if conversions: _copy_with_conversions(connection, source_schema, dest_schema, table, conversions, where_clause, limit) else: @@ -2508,13 +2594,15 @@ def migrate_external_pointers_v2( dest_store: str, copy_files: bool = False, connection=None, + legacy_database: str | None = None, ) -> dict: """ Convert one 0.14 in-store column to 2.0 format, in place. Use it on a table still in the 0.14 layout, for example in a copy made with ``create_parallel_schema(..., copy_data=True)``, to convert one column and - name a different 2.0 store. File copying (``copy_files``) is not + name a different 2.0 store. On a copy, pass the original schema's name as + ``legacy_database``. File copying (``copy_files``) is not implemented yet: the metadata points to the existing files. To copy a 0.14 table into a table declared by DataJoint 2.0, use @@ -2537,6 +2625,10 @@ def migrate_external_pointers_v2( If False (default), JSON points to existing files. connection : Connection, optional Database connection. If None, uses default connection. + legacy_database : str, optional + The name of the database 0.14 wrote the files from. 0.14 put blob and + attachment files under it. Defaults to ``schema``. Set it on a copy of + a 0.14 schema. Returns ------- @@ -2548,14 +2640,14 @@ def migrate_external_pointers_v2( Examples -------- - >>> # Migrate pointers without moving files + >>> # Migrate pointers without moving files, in a copy of 'my_pipeline' >>> result = migrate_external_pointers_v2( ... schema='my_pipeline_v2', ... table='recording', ... attribute='signal', ... source_store='external-raw', ... dest_store='raw', - ... copy_files=False + ... legacy_database='my_pipeline', ... ) >>> print(f"Migrated {result['rows_migrated']} pointers") @@ -2623,7 +2715,9 @@ def migrate_external_pointers_v2( if _column_exists(connection, schema, table, attribute + suffix): raise DataJointError(f"Cannot migrate {label}: {attribute}{suffix} already exists. Nothing was changed.") - metadata, problems = _plan_legacy_references(connection, schema, table, attribute, kind, source_store, dest_store) + metadata, problems = _plan_legacy_references( + connection, schema, table, attribute, kind, source_store, dest_store, legacy_database=legacy_database + ) _refuse_problems(label, problems) if copy_files: diff --git a/tests/integration/test_migrate_legacy_external.py b/tests/integration/test_migrate_legacy_external.py index 36e5780e0..a1a910004 100644 --- a/tests/integration/test_migrate_legacy_external.py +++ b/tests/integration/test_migrate_legacy_external.py @@ -18,10 +18,12 @@ from datajoint.errors import DataJointError from datajoint.hash_registry import compute_hash, get_hash from datajoint import migrate as dj_migrate +from datajoint.gc import GarbageCollector from datajoint.migrate import ( _legacy_hash, _legacy_path, copy_table_data, + create_parallel_schema, migrate_external, migrate_external_pointers_v2, migrate_filepath, @@ -502,6 +504,8 @@ def test_rerun_repairs_columns_finalized_by_earlier_release(schema014): ) connection.query(f"ALTER TABLE `{db}`.`recording` CHANGE COLUMN `{column}_v2` `{column}` JSON COMMENT '{comment}'") + preview = migrate_external(schema014, dry_run=True) + assert all(detail["nullable"] for detail in preview["details"]) result = migrate_external(schema014, dry_run=False) assert {detail["action"] for detail in result["details"]} == {"repair"} assert result["rows_migrated"] == 3 @@ -511,6 +515,16 @@ def test_rerun_repairs_columns_finalized_by_earlier_release(schema014): assert Path((recording & {"recording_id": 1}).fetch1("report")).read_bytes() == REPORT assert recording.heading.attributes["signal"].comment == "raw signal" + # The earlier finalize dropped NOT NULL, and repair cannot know it was there. + assert recording.heading.attributes["signal"].nullable + # The guide's statement restores it. + connection.query( + f"ALTER TABLE `{db}`.`recording` MODIFY COLUMN `signal` JSON NOT NULL COMMENT '::raw signal'" + ) + recording = _recording(schema014) + assert not recording.heading.attributes["signal"].nullable + np.testing.assert_array_equal((recording & {"recording_id": 1}).fetch1("signal"), SIGNAL) + def test_finalize_refuses_without_v2_columns(schema014): before = _columns(schema014) @@ -534,6 +548,170 @@ def test_filepath_without_contents_hash(schema014): assert (_recording(schema014) & {"recording_id": 1}).fetch1("raw_file").read() == RAW +def test_null_subfolding_means_the_014_default(schema014): + """The 2.x configuration template writes "subfolding": null; 0.14's default (2, 2) applies.""" + dj.config.stores["legacy"]["subfolding"] = None + _migrate(schema014) + np.testing.assert_array_equal((_recording(schema014) & {"recording_id": 1}).fetch1("signal"), SIGNAL) + + +@pytest.fixture +def copy014(schema014): + """A copy of the 0.14 schema made with create_parallel_schema; its files stay under the original name.""" + db, connection = schema014.database, schema014.connection + copy_db = f"{db}_copy" + connection.query(f"DROP DATABASE IF EXISTS `{copy_db}`") + result = create_parallel_schema(db, copy_db, copy_data=True, connection=connection) + assert set(result["tables"]) == {"recording", "~external_legacy"} + yield dj.Schema(copy_db, connection=connection) + connection.query(f"DROP DATABASE IF EXISTS `{copy_db}`") + + +def test_parallel_schema_copies_014_schema(schema014, copy014): + """The tracking table sorts last; the copy's foreign keys point to the copy's own tracking table.""" + connection = copy014.connection + referenced = connection.query( + "SELECT DISTINCT REFERENCED_TABLE_SCHEMA, REFERENCED_TABLE_NAME FROM information_schema.KEY_COLUMN_USAGE " + "WHERE TABLE_SCHEMA = %s AND TABLE_NAME = 'recording' AND REFERENCED_TABLE_NAME IS NOT NULL", + args=(copy014.database,), + ).fetchall() + assert referenced == ((copy014.database, "~external_legacy"),) + assert len(_recording(copy014)) == 2 + assert connection.query("SELECT @@SESSION.foreign_key_checks").fetchone()[0] == 1 + + +def test_parallel_schema_keeps_percent_in_comments(schema014, connection_test): + db = schema014.database + connection_test.query( + f"ALTER TABLE `{db}`.`recording` MODIFY `report` binary(16) DEFAULT NULL COMMENT %s", + args=(":attach@legacy:report, 100% done",), + ) + try: + create_parallel_schema(db, f"{db}_copy", connection=connection_test) + comment = connection_test.query( + "SELECT COLUMN_COMMENT FROM information_schema.COLUMNS " + "WHERE TABLE_SCHEMA = %s AND TABLE_NAME = 'recording' AND COLUMN_NAME = 'report'", + args=(f"{db}_copy",), + ).fetchone()[0] + assert comment == ":attach@legacy:report, 100% done" + finally: + connection_test.query(f"DROP DATABASE IF EXISTS `{db}_copy`") + + +def test_copy_needs_the_original_database_name(schema014, copy014): + """On a copy, blob and attachment files are found under the original name, given as legacy_database.""" + with pytest.raises(DataJointError, match="legacy_database"): + migrate_external(copy014, dry_run=False) + + assert verify_external_integrity(copy014, legacy_database=schema014.database)["missing"] == [] + preview = migrate_external(copy014, dry_run=True, legacy_database=schema014.database) + assert all(detail["problems"] == [] for detail in preview["details"]) + assert migrate_external(copy014, dry_run=False, legacy_database=schema014.database)["rows_migrated"] == 3 + assert migrate_filepath(copy014, dry_run=False)["rows_migrated"] == 1 + assert migrate_external(copy014, dry_run=False, finalize=True)["columns_migrated"] == 2 + assert migrate_filepath(copy014, dry_run=False, finalize=True)["columns_migrated"] == 1 + + recording = _recording(copy014) + np.testing.assert_array_equal((recording & {"recording_id": 1}).fetch1("signal"), SIGNAL) + np.testing.assert_array_equal((recording & {"recording_id": 2}).fetch1("signal"), COUNTS) + assert Path((recording & {"recording_id": 1}).fetch1("report")).read_bytes() == REPORT + assert (recording & {"recording_id": 1}).fetch1("raw_file").read() == RAW + stored = copy014.connection.query( + f"SELECT `signal` FROM `{copy014.database}`.`recording` WHERE recording_id = 1" + ).fetchone()[0] + assert json.loads(stored)["path"].startswith(f"{schema014.database}/") + + +def test_pointers_v2_on_a_copy(schema014, copy014, raw_store): + for attribute in ("signal", "report"): + with pytest.raises(DataJointError, match="legacy_database"): + _pointers_v2(copy014, attribute, dest_store=raw_store) + migrate_external_pointers_v2( + schema=copy014.database, + table="recording", + attribute=attribute, + source_store="legacy", + dest_store=raw_store, + connection=copy014.connection, + legacy_database=schema014.database, + ) + recording = _recording(copy014) + np.testing.assert_array_equal((recording & {"recording_id": 1}).fetch1("signal"), SIGNAL) + assert Path((recording & {"recording_id": 1}).fetch1("report")).read_bytes() == REPORT + + +def test_copy_table_data_from_a_copy(schema014, copy014, raw_store): + """copy_table_data uses the source's name unless legacy_database names the original.""" + v2 = _schema_v2(copy014) + try: + with pytest.raises(DataJointError, match="legacy_database"): + copy_table_data(copy014.database, v2.database, "recording", connection=copy014.connection) + result = copy_table_data( + copy014.database, + v2.database, + "recording", + connection=copy014.connection, + legacy_database=schema014.database, + ) + assert result["rows_copied"] == 2 + recording = dj.FreeTable(v2.connection, f"`{v2.database}`.`recording`") + np.testing.assert_array_equal((recording & {"recording_id": 1}).fetch1("signal"), SIGNAL) + assert Path((recording & {"recording_id": 1}).fetch1("report")).read_bytes() == REPORT + finally: + v2.drop(prompt=False) + + +def _014_files(legacy_store, db): + return {str(path.relative_to(legacy_store)) for path in (legacy_store / db).rglob("*") if path.is_file()} + + +def test_gc_root_level_layout_skips_schema_with_tracking_tables(schema014, legacy_store): + """With schema_prefix="", {database}/ holds the 0.14 files; GC does not list it while 0.14 tables remain.""" + _migrate(schema014) + db = schema014.database + files = _014_files(legacy_store, db) + dj.config.stores["legacy"]["schema_prefix"] = "" + + collector = GarbageCollector(schema014, store="legacy") + stats = collector.collect(dry_run=False) + assert stats["skipped_schemas"] == [db] + assert stats["orphaned_schema_paths"] == [] and stats["deleted"] == 0 + assert _014_files(legacy_store, db) == files + np.testing.assert_array_equal((_recording(schema014) & {"recording_id": 1}).fetch1("signal"), SIGNAL) + + +def test_gc_root_level_layout_keeps_migrated_files(schema014, legacy_store): + """Without the tracking tables, migrated files count as referenced and 0.14 names are never orphans.""" + _migrate(schema014) + db, connection = schema014.database, schema014.connection + constraints = connection.query( + "SELECT TABLE_NAME, CONSTRAINT_NAME FROM information_schema.KEY_COLUMN_USAGE " + "WHERE TABLE_SCHEMA = %s AND REFERENCED_TABLE_NAME = '~external_legacy'", + args=(db,), + ).fetchall() + for table_name, constraint in constraints: + connection.query(f"ALTER TABLE `{db}`.`{table_name}` DROP FOREIGN KEY `{constraint}`") + connection.query(f"DROP TABLE `{db}`.`~external_legacy`") + + # A 0.14 blob that no row references, and a file in the root-level layout that nothing references + unreferenced = _legacy_path(db, _md5(b"unreferenced"), (2, 2)) + stray = f"{db}/recording/rid=9/data_x1y2z3w4.npy" + for path in (unreferenced, stray): + (legacy_store / path).parent.mkdir(parents=True, exist_ok=True) + (legacy_store / path).write_bytes(b"x") + files = _014_files(legacy_store, db) + dj.config.stores["legacy"]["schema_prefix"] = "" + + collector = GarbageCollector(schema014, store="legacy") + assert collector.collect()["orphaned_schema_paths"] == [stray] + collector.collect(dry_run=False) + assert _014_files(legacy_store, db) == files - {stray} + recording = _recording(schema014) + np.testing.assert_array_equal((recording & {"recording_id": 1}).fetch1("signal"), SIGNAL) + np.testing.assert_array_equal((recording & {"recording_id": 2}).fetch1("signal"), COUNTS) + assert Path((recording & {"recording_id": 1}).fetch1("report")).read_bytes() == REPORT + + def test_dry_run_needs_the_store(schema014): """A dry run looks files up, so the store must be configured.""" del dj.config.stores["legacy"] diff --git a/tests/unit/test_migrate_legacy_store.py b/tests/unit/test_migrate_legacy_store.py index dc85ea8b9..8a8fa7b06 100644 --- a/tests/unit/test_migrate_legacy_store.py +++ b/tests/unit/test_migrate_legacy_store.py @@ -73,9 +73,15 @@ def test_store_setting_wins(self): config = Config() config.stores["legacy"] = {"protocol": "file", "location": "/data", "subfolding": [3]} assert _legacy_subfolding("legacy", config) == (3,) - config.stores["legacy"] = {"protocol": "file", "location": "/data", "subfolding": None} + config.stores["legacy"] = {"protocol": "file", "location": "/data", "subfolding": []} assert _legacy_subfolding("legacy", config) == () + def test_null_setting_is_unset(self): + # The 2.x configuration template writes "subfolding": null. + config = Config() + config.stores["legacy"] = {"protocol": "file", "location": "/data", "subfolding": None} + assert _legacy_subfolding("legacy", config) == (2, 2) + class TestMigratedAttachmentRead: """`get_hash` puts a migrated attachment's name back before checking the hash.""" From bd12ce13df5cbbcee6dfbaa4dec1b13e48cf4f71 Mon Sep 17 00:00:00 2001 From: Dimitri Yatsenko Date: Mon, 23 Nov 2026 18:18:03 -0600 Subject: [PATCH 4/6] test(migrate): check files before the GC report keys --- tests/integration/test_migrate_legacy_external.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/integration/test_migrate_legacy_external.py b/tests/integration/test_migrate_legacy_external.py index a1a910004..6461eeab3 100644 --- a/tests/integration/test_migrate_legacy_external.py +++ b/tests/integration/test_migrate_legacy_external.py @@ -674,9 +674,9 @@ def test_gc_root_level_layout_skips_schema_with_tracking_tables(schema014, legac collector = GarbageCollector(schema014, store="legacy") stats = collector.collect(dry_run=False) - assert stats["skipped_schemas"] == [db] - assert stats["orphaned_schema_paths"] == [] and stats["deleted"] == 0 assert _014_files(legacy_store, db) == files + assert stats["orphaned_schema_paths"] == [] and stats["deleted"] == 0 + assert stats["skipped_schemas"] == [db] np.testing.assert_array_equal((_recording(schema014) & {"recording_id": 1}).fetch1("signal"), SIGNAL) From 924f6f63036ef2a331d9832f09ca01e39345b75f Mon Sep 17 00:00:00 2001 From: Dimitri Yatsenko Date: Mon, 23 Nov 2026 18:58:00 -0600 Subject: [PATCH 5/6] fix(gc): root-level layout keeps top-level schema files and reads references In the root-level layout (schema_prefix=""), a file directly under {schema}/ is never an orphan: 2.x schema-addressed paths are {schema}/{table}/..., so such a file is a 0.14 file stored without subfolding or a blob 0.14 had migrated from 0.11, which a copy migrated with legacy_database may reference. GC also reads references of the collected schemas in this layout. The 0.14 file rules and hash-reference coverage now apply only to the root-level layout. --- src/datajoint/gc.py | 106 +++++++++++++---- .../test_migrate_legacy_external.py | 112 ++++++++++++++++++ 2 files changed, 194 insertions(+), 24 deletions(-) diff --git a/src/datajoint/gc.py b/src/datajoint/gc.py index 0d14a3117..df54ddd4a 100644 --- a/src/datajoint/gc.py +++ b/src/datajoint/gc.py @@ -34,14 +34,31 @@ **per-schema**: each schema is scanned against its own subtree only. Orphan detection is therefore confined to the collector's schemas — any subset of the schemas sharing a store may be collected safely, and GC never touches another -schema's objects or user-managed content elsewhere in the store. - -Files migrated from DataJoint 0.14 stay where 0.14 stored them, -``{database}/...``, which is inside the schema section when a store uses the -root-level layout (``schema_prefix=""``). GC never deletes them there: a file -that a migrated row references counts as referenced, a file named as 0.14 named -its blobs and attachments is never an orphan, and the section of a schema that -still has 0.14 ``~external_*`` tracking tables is not listed at all. +schema's objects or user-managed content elsewhere in the store. The root-level +layout, below, is the exception. + +Root-level layout (``schema_prefix=""``). Files migrated from DataJoint 0.14 +stay where 0.14 stored them, ``{database}/...``, which is then inside the schema +section, and ```` files may lie there too. In this layout only, GC +keeps these files: + +- a file that a hash reference (such as a migrated ```` or ```` + value) or a ```` reference points to counts as referenced; +- a file named as 0.14 named blobs and attachments (32 hex digits, optionally + followed by ``.`` and a name) is never an orphan; +- a file directly under ``{schema}/``, with no subfolder, is never an orphan. + 2.x schema-addressed paths are ``{schema}/{table}/...``, so such a file is a + 0.14 file stored without subfolding or a blob that 0.14 had migrated from 0.11; +- the section of a schema that still has 0.14 ``~external_*`` tracking tables is + not listed at all, and the schema is reported under ``skipped_schemas``. + +GC reads references only from the schemas it collects, in the store it +collects. A file in a subfolder of ``{schema}/`` that is not named as 0.14 +named its files, and that only rows of other schemas reference (for example a +```` file referenced from another schema), is still listed as an +orphan. Pass every schema whose rows reference files in the store, such as a +copy migrated with ``legacy_database``, to the same collector, and preview +with ``dry_run=True`` before deleting. See Also -------- @@ -71,6 +88,18 @@ _LEGACY_014_NAME = re.compile(r"^[0-9a-f]{32}(\..+)?$") +def _kept_in_root_level_layout(path: str) -> bool: + """ + Return True for a root-level schema-section file that GC never treats as an orphan. + + That is a file named as 0.14 named its blobs and attachments, or a file + directly under ``{schema}/`` (``{schema}/{name}``). 2.x schema-addressed + paths are ``{schema}/{table}/...``, so a file with no subfolder is a 0.14 + file stored without subfolding, or a blob that 0.14 had migrated from 0.11. + """ + return path.count("/") == 1 or bool(_LEGACY_014_NAME.match(path.rsplit("/", 1)[-1])) + + def _is_covered(path: str, referenced: set[str]) -> bool: """ Return True if a stored file is accounted for by a referenced object path. @@ -171,6 +200,24 @@ def schema_references(self, verbose: bool = False) -> set[str]: """ return self._references("schema_objects", verbose) + def filepath_references(self, verbose: bool = False) -> set[str]: + """ + Store paths that ```` columns of live rows across this + collector's schemas point to, filtered to this collector's store. + + GC never deletes ```` files. It reads these references only + in the root-level layout (``schema_prefix=""``), where such a file may + lie inside a schema section. + """ + return self._references("filepath_objects", verbose) + + @staticmethod + def _attribute_names(heading, heading_attr: str) -> list[str]: + if heading_attr == "filepath_objects": + return [k for k, v in heading.attributes.items() if getattr(v.codec, "name", "") == "filepath"] + # Classification lives on the heading — one source of truth. + return getattr(heading, heading_attr) + def _references(self, heading_attr: str, verbose: bool) -> set[str]: referenced: set[str] = set() for schema in self.schemas: @@ -179,8 +226,7 @@ def _references(self, heading_attr: str, verbose: bool) -> set[str]: for table_name in schema.list_tables(): try: table = schema.get_table(table_name) - # Classification lives on the heading — one source of truth. - for attr_name in getattr(table.heading, heading_attr): + for attr_name in self._attribute_names(table.heading, heading_attr): attr = table.heading.attributes[attr_name] if verbose: logger.info(f" Scanning {table_name}.{attr_name}") @@ -261,7 +307,9 @@ def list_schema_paths(self, schema_name: str) -> dict[str, int]: datajoint/datajoint-python#1487). Such a store should set ``schema_prefix=""`` so writes and this walk use the root-level layout consistently; otherwise those objects remain readable but outside the - scanned section. + scanned section. In that layout the section ``{schema}/`` can also hold + files migrated from DataJoint 0.14 and ```` files; + :meth:`collect` keeps the ones the module docstring lists. Returns a dict mapping each object file's relative path to size. """ @@ -366,20 +414,27 @@ def collect(self, dry_run: bool = True, verbose: bool = False) -> dict[str, Any] dry_run) / errors / dry_run - skipped_schemas: schemas whose root-level section was not listed because they still have DataJoint 0.14 tracking tables + + In the root-level layout (``schema_prefix=""``), files migrated from + DataJoint 0.14 and ```` files can lie in a schema section; + the module docstring lists the files GC keeps there and the case it + does not cover. Preview with ``dry_run=True`` before deleting. """ self._scan_errors = [] # reset per-call; populated by list_*_paths below - # References can be gathered across all schemas at once: because paths - # embed the schema, a file under schema X is only ever covered by an X - # reference, so combined coverage equals per-schema coverage. + # References are gathered across all schemas at once, so a file that any + # collected schema references is kept. 2.x paths embed their schema, so + # for them combined coverage equals per-schema coverage. hash_paths_referenced = self.hash_references(verbose=verbose) schema_paths_referenced = self.schema_references(verbose=verbose) + root_level = not self._schema_prefix + filepath_paths_referenced = self.filepath_references(verbose=verbose) if root_level else set() hash_paths_stored: dict[str, int] = {} schema_paths_stored: dict[str, int] = {} skipped_schemas: list[str] = [] for schema in self.schemas: hash_paths_stored.update(self.list_hash_paths(schema.database)) - if not self._schema_prefix and self._has_legacy_tracking_tables(schema): + if root_level and self._has_legacy_tracking_tables(schema): # Root-level layout: {schema}/ is also where DataJoint 0.14 kept # this schema's files. Their references are in 0.14 tables that # GC does not read, so the section is not listed at all. @@ -393,15 +448,18 @@ def collect(self, dry_run: bool = True, verbose: bool = False) -> dict[str, Any] orphaned_hash_paths = sorted(set(hash_paths_stored.keys()) - hash_paths_referenced) # Coverage, not exact set difference: a referenced path may be a - # directory-valued object (many files + a manifest sidecar). Hash - # references count too: metadata migrated from DataJoint 0.14 points to - # files where 0.14 stored them, which in the root-level layout lie - # inside the schema section. Files named as 0.14 named them are never - # orphans here, whether or not a row references them. - covering = schema_paths_referenced | hash_paths_referenced - orphaned_schema_paths = sorted( - p for p in schema_paths_stored if not _is_covered(p, covering) and not _LEGACY_014_NAME.match(p.rsplit("/", 1)[-1]) - ) + # directory-valued object (many files + a manifest sidecar). + if root_level: + # The schema section is {schema}/, where DataJoint 0.14 stored its + # files and where files may lie. Hash and filepath + # references count too, and files named as 0.14 named them, or + # directly under {schema}/, are never orphans. + covering = schema_paths_referenced | hash_paths_referenced | filepath_paths_referenced + orphaned_schema_paths = sorted( + p for p in schema_paths_stored if not _is_covered(p, covering) and not _kept_in_root_level_layout(p) + ) + else: + orphaned_schema_paths = sorted(p for p in schema_paths_stored if not _is_covered(p, schema_paths_referenced)) hash_paths_deleted = 0 schema_paths_deleted = 0 diff --git a/tests/integration/test_migrate_legacy_external.py b/tests/integration/test_migrate_legacy_external.py index 6461eeab3..003c7e864 100644 --- a/tests/integration/test_migrate_legacy_external.py +++ b/tests/integration/test_migrate_legacy_external.py @@ -712,6 +712,118 @@ def test_gc_root_level_layout_keeps_migrated_files(schema014, legacy_store): assert Path((recording & {"recording_id": 1}).fetch1("report")).read_bytes() == REPORT +def test_gc_root_level_layout_keeps_files_a_copy_references(schema014, copy014, legacy_store): + """Files under the original's name that only the migrated copy references stay when the original is collected.""" + db, connection = schema014.database, schema014.connection + assert migrate_external(copy014, dry_run=False, legacy_database=db)["rows_migrated"] == 3 + assert migrate_external(copy014, dry_run=False, finalize=True)["columns_migrated"] == 2 + # The original no longer has 0.14 tables, so GC lists its section + connection.query(f"DROP TABLE `{db}`.`recording`") + connection.query(f"DROP TABLE `{db}`.`~external_legacy`") + stray = f"{db}/recording/rid=9/data_x1y2z3w4.npy" + (legacy_store / stray).parent.mkdir(parents=True) + (legacy_store / stray).write_bytes(b"x") + files = _014_files(legacy_store, db) + dj.config.stores["legacy"]["schema_prefix"] = "" + + collector = GarbageCollector(schema014, store="legacy") + assert collector.collect()["orphaned_schema_paths"] == [stray] + collector.collect(dry_run=False) + assert _014_files(legacy_store, db) == files - {stray} + recording = _recording(copy014) + np.testing.assert_array_equal((recording & {"recording_id": 1}).fetch1("signal"), SIGNAL) + np.testing.assert_array_equal((recording & {"recording_id": 2}).fetch1("signal"), COUNTS) + assert Path((recording & {"recording_id": 1}).fetch1("report")).read_bytes() == REPORT + + +def test_gc_root_level_layout_copy_on_both_backends(connection_by_backend, backend, prefix, legacy_store): + """ + A copy's migrated values point under the original's name. Collecting the + original alone keeps the 0.14-named and top-level files and the original's + own files; a file in a subfolder that only the copy references + is kept when the copy is collected too. + """ + dj.config.stores["legacy"]["schema_prefix"] = "" + original = dj.Schema(f"{prefix}_gc_original_{backend}", connection=connection_by_backend) + copy = dj.Schema(f"{prefix}_gc_copy_{backend}", connection=connection_by_backend) + db = original.database + + @original + class Note(dj.Manual): + definition = """ + note_id : int32 + --- + note : + """ + + @copy + class Recording(dj.Manual): + definition = """ + recording_id : int32 + --- + signal = null : + report = null : + raw_file = null : + """ + + def put(path, data): + (legacy_store / path).parent.mkdir(parents=True, exist_ok=True) + (legacy_store / path).write_bytes(data) + + try: + signal = _md5(SIGNAL_BLOB) + signal_path = _legacy_path(db, signal, (2, 2)) + report = _md5((REPORT_NAME + "\0").encode() + REPORT) + report_path = _legacy_path(db, report, (2, 2), REPORT_NAME) + counts_path = f"{db}/0123456789abcdefABCDEF0123456789abcdefABCDE" # a blob 0.14 migrated from 0.11 + note_path, raw_path = f"{db}/notes/readme.txt", f"{db}/acquisition/raw.dat" + stray = f"{db}/recording/rid=9/data_x1y2z3w4.npy" + for path, data in ( + (signal_path, SIGNAL_BLOB), + (report_path, REPORT), + (counts_path, COUNTS_BLOB), + (note_path, b"notes"), + (raw_path, RAW), + (stray, b"x"), + ): + put(path, data) + + Note.insert1({"note_id": 1, "note": note_path}) + Recording.insert([{"recording_id": 1, "raw_file": raw_path}, {"recording_id": 2, "raw_file": None}]) + quote = connection_by_backend.adapter.quote_identifier + + def set_metadata(recording_id, column, metadata): + connection_by_backend.query( + f"UPDATE {Recording.full_table_name} SET {quote(column)} = %s WHERE {quote('recording_id')} = %s", + args=(json.dumps({"schema": db, "store": "legacy", **metadata}), recording_id), + ) + + set_metadata(1, "signal", {"hash": _legacy_hash(signal), "path": signal_path, "size": len(SIGNAL_BLOB)}) + set_metadata( + 1, + "report", + {"hash": _legacy_hash(report), "path": report_path, "size": len(REPORT), "attachment_name": REPORT_NAME}, + ) + set_metadata(2, "signal", {"hash": _legacy_hash(_md5(COUNTS_BLOB)), "path": counts_path, "size": len(COUNTS_BLOB)}) + files = _014_files(legacy_store, db) + + # The original alone: the file in a subfolder that only the copy references is listed + assert GarbageCollector(original, store="legacy").collect()["orphaned_schema_paths"] == [raw_path, stray] + + collector = GarbageCollector(original, copy, store="legacy") + assert collector.collect()["orphaned_schema_paths"] == [stray] + collector.collect(dry_run=False) + assert _014_files(legacy_store, db) == files - {stray} + np.testing.assert_array_equal((Recording & {"recording_id": 1}).fetch1("signal"), SIGNAL) + np.testing.assert_array_equal((Recording & {"recording_id": 2}).fetch1("signal"), COUNTS) + assert Path((Recording & {"recording_id": 1}).fetch1("report")).read_bytes() == REPORT + assert (Recording & {"recording_id": 1}).fetch1("raw_file").read() == RAW + assert (Note & {"note_id": 1}).fetch1("note").read() == b"notes" + finally: + copy.drop(prompt=False) + original.drop(prompt=False) + + def test_dry_run_needs_the_store(schema014): """A dry run looks files up, so the store must be configured.""" del dj.config.stores["legacy"] From 6c6a7d76cff0424d30837419f40f8c714a0d2219 Mon Sep 17 00:00:00 2001 From: Dimitri Yatsenko Date: Mon, 23 Nov 2026 19:17:39 -0600 Subject: [PATCH 6/6] fix(gc): normalize reference paths in the root-level layout A value is stored as written, so './{db}/sub/a.txt' and '{db}//sub/b.txt' read the file at '{db}/sub/a.txt' but did not match the listed path, and collect(dry_run=False) deleted it. Normalize every reference path before matching (backslashes to '/', posixpath.normpath, leading '/' stripped), as does for its reserved-section check. Qualify the GarbageCollector *schemas docstring and the filepath_references docstring for the root-level layout. --- src/datajoint/gc.py | 32 +++++++++++++++---- .../test_migrate_legacy_external.py | 32 +++++++++++++++++++ 2 files changed, 58 insertions(+), 6 deletions(-) diff --git a/src/datajoint/gc.py b/src/datajoint/gc.py index df54ddd4a..773ce4e68 100644 --- a/src/datajoint/gc.py +++ b/src/datajoint/gc.py @@ -68,6 +68,7 @@ from __future__ import annotations import logging +import posixpath import re from typing import TYPE_CHECKING, Any @@ -100,6 +101,17 @@ def _kept_in_root_level_layout(path: str) -> bool: return path.count("/") == 1 or bool(_LEGACY_014_NAME.match(path.rsplit("/", 1)[-1])) +def _normalized(paths: set[str]) -> set[str]: + """ + Return reference paths in the form the store listing uses. + + A ```` value is stored as written, so it may hold ``./``, ``//`` + or backslashes (``./{schema}/sub/a.txt``) and still read. The store listing + returns clean relative paths (``{schema}/sub/a.txt``). + """ + return {posixpath.normpath(p.replace("\\", "/")).lstrip("/") for p in paths} + + def _is_covered(path: str, referenced: set[str]) -> bool: """ Return True if a stored file is accounted for by a referenced object path. @@ -142,7 +154,11 @@ class GarbageCollector: The schemas to collect. At least one is required. Every managed path embeds its schema, so collection is per-schema and confined to these schemas: objects of any other schema sharing the store are never listed - and never at risk — pass any subset safely. + and never at risk — pass any subset safely. The root-level layout + (``schema_prefix=""``) is the exception: there a file in a subfolder of + ``{schema}/`` that only other schemas reference is listed as an orphan, + so pass every schema that references files in the store (see the + module docstring). store : str, optional Store name (None = the default store), keyword-only. config : Config, optional @@ -205,9 +221,12 @@ def filepath_references(self, verbose: bool = False) -> set[str]: Store paths that ```` columns of live rows across this collector's schemas point to, filtered to this collector's store. - GC never deletes ```` files. It reads these references only - in the root-level layout (``schema_prefix=""``), where such a file may - lie inside a schema section. + GC reads these references only in the root-level layout + (``schema_prefix=""``), where a ```` file may lie inside a + schema section. There GC does not delete a ```` file it reads + a reference to; a file that only schemas outside this collector + reference is listed as an orphan (see the module docstring). Outside + that layout, ```` files lie outside the scanned sections. """ return self._references("filepath_objects", verbose) @@ -453,8 +472,9 @@ def collect(self, dry_run: bool = True, verbose: bool = False) -> dict[str, Any] # The schema section is {schema}/, where DataJoint 0.14 stored its # files and where files may lie. Hash and filepath # references count too, and files named as 0.14 named them, or - # directly under {schema}/, are never orphans. - covering = schema_paths_referenced | hash_paths_referenced | filepath_paths_referenced + # directly under {schema}/, are never orphans. A value + # is stored as written, so references are normalized before matching. + covering = _normalized(schema_paths_referenced | hash_paths_referenced | filepath_paths_referenced) orphaned_schema_paths = sorted( p for p in schema_paths_stored if not _is_covered(p, covering) and not _kept_in_root_level_layout(p) ) diff --git a/tests/integration/test_migrate_legacy_external.py b/tests/integration/test_migrate_legacy_external.py index 003c7e864..ea4a03193 100644 --- a/tests/integration/test_migrate_legacy_external.py +++ b/tests/integration/test_migrate_legacy_external.py @@ -824,6 +824,38 @@ def set_metadata(recording_id, column, metadata): original.drop(prompt=False) +def test_gc_root_level_layout_normalizes_filepath_references(connection_by_backend, backend, prefix, legacy_store): + """ values stored with ./ or // still count as references to the files they read.""" + dj.config.stores["legacy"]["schema_prefix"] = "" + schema = dj.Schema(f"{prefix}_gc_filepath_{backend}", connection=connection_by_backend) + db = schema.database + + @schema + class Note(dj.Manual): + definition = """ + note_id : int32 + --- + note : + """ + + try: + files = {f"{db}/sub/a.txt": b"a", f"{db}/sub/b.txt": b"b"} + for path, data in files.items(): + (legacy_store / path).parent.mkdir(parents=True, exist_ok=True) + (legacy_store / path).write_bytes(data) + Note.insert([{"note_id": 1, "note": f"./{db}/sub/a.txt"}, {"note_id": 2, "note": f"{db}//sub/b.txt"}]) + + collector = GarbageCollector(schema, store="legacy") + assert collector.collect()["orphaned_schema_paths"] == [] + stats = collector.collect(dry_run=False) + assert stats["deleted"] == 0 + assert _014_files(legacy_store, db) == set(files) + assert (Note & {"note_id": 1}).fetch1("note").read() == b"a" + assert (Note & {"note_id": 2}).fetch1("note").read() == b"b" + finally: + schema.drop(prompt=False) + + def test_dry_run_needs_the_store(schema014): """A dry run looks files up, so the store must be configured.""" del dj.config.stores["legacy"]