diff --git a/.github/dependabot.yml b/.github/dependabot.yml index aac560ed2..0b0fbc610 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -5,8 +5,30 @@ updates: schedule: interval: "monthly" day: "wednesday" - time: "9:00" + time: "09:00" timezone: "America/Chicago" groups: all-actions: - patterns: [ "*" ] \ No newline at end of file + patterns: [ "*" ] + - package-ecosystem: "pip" + directory: "/" + schedule: + interval: "weekly" + day: "wednesday" + time: "09:00" + timezone: "America/Chicago" + # datajoint is a library: its dependencies declare minimum versions only. + # Leave a requirement alone when it already admits the new release, so + # users are not pushed onto the newest version of each dependency. + versioning-strategy: "increase-if-necessary" + # deepdiff<9 on Python 3.15 is deliberate (see pyproject.toml); do not + # propose raising it to admit a new major version. + ignore: + - dependency-name: "deepdiff" + update-types: [ "version-update:semver-major" ] + # Version updates stay one PR per package: each one raises an upper bound + # and gets its own test run and review. Security updates are grouped. + groups: + python-security: + applies-to: security-updates + patterns: [ "*" ] diff --git a/.github/scripts/minimum_requirements.py b/.github/scripts/minimum_requirements.py new file mode 100644 index 000000000..4801e2937 --- /dev/null +++ b/.github/scripts/minimum_requirements.py @@ -0,0 +1,81 @@ +"""Print pins for the minimum version of each runtime dependency. + +Reads [project].dependencies from pyproject.toml and prints one `name==minimum` +line per dependency that applies to the given Python version. CI installs the +package with these as constraints, so the test suite runs against the oldest +versions that pyproject.toml admits. Optional extras are not pinned. + +Every applicable dependency must declare a minimum (>=, ==, or ~=). A +dependency without one is an error: GitHub's dependency graph omits it, and +its oldest release is untested. + +Usage: python minimum_requirements.py [pyproject.toml] [--python 3.10] +""" + +import argparse +import re +import sys + +from packaging.requirements import Requirement +from packaging.specifiers import SpecifierSet +from packaging.utils import canonicalize_name +from packaging.version import Version + +try: + import tomllib +except ModuleNotFoundError: # Python 3.10 + import tomli as tomllib + + +def python_version(value: str) -> str: + if not re.fullmatch(r"3\.\d+", value): + raise argparse.ArgumentTypeError(f"expected a version like 3.10, got {value!r}") + return value + + +def main() -> int: + parser = argparse.ArgumentParser() + parser.add_argument("pyproject", nargs="?", default="pyproject.toml") + parser.add_argument("--python", type=python_version, default="3.10", help="Python version to evaluate markers for") + args = parser.parse_args() + + with open(args.pyproject, "rb") as f: + dependencies = tomllib.load(f)["project"]["dependencies"] + + # A dependency may span several lines, e.g. a minimum plus an upper bound + # under a marker. Combine the applicable lines per package. + environment = {"python_version": args.python, "python_full_version": f"{args.python}.0"} + specifiers: dict[str, SpecifierSet] = {} + for line in dependencies: + req = Requirement(line) + if req.marker is not None and not req.marker.evaluate(environment): + continue + name = canonicalize_name(req.name) + specifiers[name] = specifiers.get(name, SpecifierSet()) & req.specifier + + pins, errors = {}, [] + for name, specifier in sorted(specifiers.items()): + bounds = [s.version for s in specifier if s.operator in (">=", "==", "~=")] + if not bounds: + errors.append(f"{name} declares no minimum version") + continue + if any("*" in bound for bound in bounds): + errors.append(f"{name}: wildcard versions are not supported ({specifier})") + continue + minimum = max(bounds, key=Version) + if minimum not in specifier: + errors.append(f"{name}: minimum {minimum} is excluded by {specifier}") + continue + pins[name] = minimum + + if errors: + for error in errors: + print(f"error: {error}", file=sys.stderr) + return 1 + for name, version in pins.items(): + print(f"{name}=={version}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/.github/workflows/close_inactive_issues_prs.yaml b/.github/workflows/close_inactive_issues_prs.yaml index bb2eba036..4c68e30e0 100644 --- a/.github/workflows/close_inactive_issues_prs.yaml +++ b/.github/workflows/close_inactive_issues_prs.yaml @@ -11,7 +11,7 @@ jobs: issues: write pull-requests: write steps: - - uses: actions/stale@v9 + - uses: actions/stale@5bef64f19d7facfb25b37b414482c7164d639639 # v9.1.0 with: repo-token: ${{ secrets.GITHUB_TOKEN }} operations-per-run: 500 # API rate limit diff --git a/.github/workflows/lint.yaml b/.github/workflows/lint.yaml index e7e6dc2ae..456b254c7 100644 --- a/.github/workflows/lint.yaml +++ b/.github/workflows/lint.yaml @@ -1,4 +1,6 @@ name: Lint +permissions: + contents: read on: push: branches: @@ -14,16 +16,19 @@ jobs: lint: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 - - uses: actions/setup-python@v5 - # enforce the same check as pre-commit - # but only run important checks - - uses: pre-commit/action@v3.0.1 - with: - extra_args: codespell --all-files - - uses: pre-commit/action@v3.0.1 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 with: - extra_args: ruff --all-files - - uses: pre-commit/action@v3.0.1 + persist-credentials: false + - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0 + # enforce the same check as pre-commit + # but only run important checks. + # These steps are what pre-commit/action does, written out so that every + # action is pinned by SHA (pre-commit/action calls actions/cache by tag). + - run: python -m pip install pre-commit==4.7.0 + - uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 with: - extra_args: ruff-format --all-files + path: ~/.cache/pre-commit + key: pre-commit-3|${{ env.pythonLocation }}|${{ hashFiles('.pre-commit-config.yaml') }} + - run: pre-commit run --show-diff-on-failure --color=always codespell --all-files + - run: pre-commit run --show-diff-on-failure --color=always ruff --all-files + - run: pre-commit run --show-diff-on-failure --color=always ruff-format --all-files diff --git a/.github/workflows/test.yaml b/.github/workflows/test.yaml index a3f2bc5c8..1435f8b38 100644 --- a/.github/workflows/test.yaml +++ b/.github/workflows/test.yaml @@ -1,5 +1,8 @@ name: Test +permissions: + contents: read + on: push: branches: @@ -11,6 +14,7 @@ on: - "tests/**" - "pyproject.toml" - "pixi.lock" + - ".github/scripts/minimum_requirements.py" - ".github/workflows/test.yaml" pull_request: branches: @@ -22,6 +26,7 @@ on: - "tests/**" - "pyproject.toml" - "pixi.lock" + - ".github/scripts/minimum_requirements.py" - ".github/workflows/test.yaml" jobs: @@ -40,10 +45,12 @@ jobs: mysql-image: ["datajoint/mysql:8.0", "mysql:8.4"] name: test (${{ matrix.environment }}, mysql=${{ matrix.mysql-image }}) steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + with: + persist-credentials: false - name: Set up pixi - uses: prefix-dev/setup-pixi@v0.9.3 + uses: prefix-dev/setup-pixi@82d477f15f3a381dbcc8adc1206ce643fe110fb7 # v0.9.3 with: cache: true locked: false @@ -58,10 +65,12 @@ jobs: unit-tests: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + with: + persist-credentials: false - name: Set up pixi - uses: prefix-dev/setup-pixi@v0.9.3 + uses: prefix-dev/setup-pixi@82d477f15f3a381dbcc8adc1206ce643fe110fb7 # v0.9.3 with: cache: true locked: false @@ -84,12 +93,13 @@ jobs: python-version: ["3.10", "3.14", "3.15"] name: unit-tests-windows (py${{ matrix.python-version }}) steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 with: fetch-depth: 0 # hatch-vcs derives the version from git history/tags + persist-credentials: false - name: Set up Python - uses: actions/setup-python@v5 + uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0 with: python-version: ${{ matrix.python-version }} @@ -104,3 +114,39 @@ jobs: - name: Run unit tests run: pytest tests/unit -v + + # Minimum versions: run the full suite on the oldest supported Python with + # every runtime dependency ([project].dependencies; extras are not pinned) at + # the minimum pyproject.toml declares, so those minimums stay true. + # minimum_requirements.py also fails the job when a runtime dependency + # declares no minimum. Uses pip, not pixi, because pixi resolves the newest + # versions from the lock file. + test-min-versions: + runs-on: ubuntu-latest + timeout-minutes: 45 + name: test (minimum dependency versions, py3.10) + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + with: + fetch-depth: 0 # hatch-vcs derives the version from git history/tags + persist-credentials: false + + - name: Set up Python + uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0 + with: + python-version: "3.10" + + - name: Install graphviz + run: sudo apt-get update && sudo apt-get install -y graphviz + + - name: Pin runtime dependencies at their minimums + run: | + python -m pip install tomli==2.5.0 packaging==26.3 + python .github/scripts/minimum_requirements.py --python 3.10 > "$RUNNER_TEMP/minimum.txt" + cat "$RUNNER_TEMP/minimum.txt" + + - name: Install package with test extras + run: python -m pip install -e ".[test]" -c "$RUNNER_TEMP/minimum.txt" + + - name: Run tests + run: python -m pytest tests/ diff --git a/pixi.lock b/pixi.lock index e287ed2ae..a0be5dec5 100644 --- a/pixi.lock +++ b/pixi.lock @@ -455,6 +455,7 @@ environments: - pypi: https://files.pythonhosted.org/packages/d5/4e/e4691508f9477ce67da2015d8c00acd751e6287739123113a9fca6f1604e/frozenlist-1.8.0-cp313-cp313-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl - pypi: https://files.pythonhosted.org/packages/d5/1f/5f4a3cd9e4440e9d9bc78ad0a91a1c8d46b4d429d5239ebe6793c9fe5c41/fsspec-2026.3.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/7a/34/259b28ea7a2a0c904b11cd36c79b8cef8019b26ee5dbe24e73b469dea347/greenlet-3.3.2-cp313-cp313-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl + - pypi: https://files.pythonhosted.org/packages/f5/94/50b6330833c24c8e172e3759902fdebed487611c63a1e18e34db7b024bae/hypothesis-6.170.17-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl - pypi: https://files.pythonhosted.org/packages/e5/ae/2ad30f4652712c82f1c23423d79136fbce338932ad166d70c1efb86a5998/identify-2.6.14-py2.py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/76/c6/c88e154df9c4e1a2a66ccf0005a88dfb2650c1dffb6f5ce603dfbd452ce3/idna-3.10-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/2c/e1/e6716421ea10d38022b952c159d5161ca1193197fb744506875fbb87ea7b/iniconfig-2.1.0-py3-none-any.whl @@ -504,6 +505,7 @@ environments: - pypi: https://files.pythonhosted.org/packages/f3/51/0489a6a5595b7760b5dbac0dd82852b510326e7d88d51dbffcd2e07e3ff3/ruff-0.14.9-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl - pypi: https://files.pythonhosted.org/packages/6a/52/5ccdc01f7a8a61357d15a66b5d8a6580aa8529cb33f32e6cbb71c52622c5/s3fs-2026.3.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/b7/ce/149a00dd41f10bc29e5921b496af8b574d8413afcd5e30dfa0ed46c2cc5e/six-1.17.0-py2.py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/32/46/9cb0e58b2deb7f82b84065f37f3bffeb12413f947f9388e4cac22c4621ce/sortedcontainers-2.4.0-py2.py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/fe/88/cb59509e4668d8001818d7355d9995be90c321313078c912420603a7cb95/sqlalchemy-2.0.48-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl - pypi: https://files.pythonhosted.org/packages/f1/7b/ce1eafaf1a76852e2ec9b22edecf1daa58175c090266e9f6c64afcd81d91/stack_data-0.6.3-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/13/2d/26b8b30067d94339afee62c3edc9b803a6eb9332f521ba77d8aaab5de873/testcontainers-4.14.2-py3-none-any.whl @@ -649,6 +651,7 @@ environments: - pypi: https://files.pythonhosted.org/packages/40/76/c202df58e3acdf12969a7895fd6f3bc016c642e6726aa63bd3025e0fc71c/frozenlist-1.8.0-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl - pypi: https://files.pythonhosted.org/packages/d5/1f/5f4a3cd9e4440e9d9bc78ad0a91a1c8d46b4d429d5239ebe6793c9fe5c41/fsspec-2026.3.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/49/8d/9771d03e7a8b1ee456511961e1b97a6d77ae1dea4a34a5b98eee706689d3/greenlet-3.3.2-cp313-cp313-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl + - pypi: https://files.pythonhosted.org/packages/55/10/17d825f0d0238ba7e1d6735f3f5c44f43e9003e6ff1c128951585c915451/hypothesis-6.170.17-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.whl - pypi: https://files.pythonhosted.org/packages/0f/1c/e5fd8f973d4f375adb21565739498e2e9a1e54c858a97b9a8ccfdc81da9b/identify-2.6.15-py2.py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/0e/61/66938bbb5fc52dbdf84594873d5b51fb1f7c7794e9c0f5bd885f30bc507b/idna-3.11-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/cb/b1/3846dd7f199d53cb17f49cba7e651e9ce294d8497c8c150530ed11865bb8/iniconfig-2.3.0-py3-none-any.whl @@ -698,6 +701,7 @@ environments: - pypi: https://files.pythonhosted.org/packages/9e/e9/08840ff5127916bb989c86f18924fd568938b06f58b60e206176f327c0fe/ruff-0.14.9-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl - pypi: https://files.pythonhosted.org/packages/6a/52/5ccdc01f7a8a61357d15a66b5d8a6580aa8529cb33f32e6cbb71c52622c5/s3fs-2026.3.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/b7/ce/149a00dd41f10bc29e5921b496af8b574d8413afcd5e30dfa0ed46c2cc5e/six-1.17.0-py2.py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/32/46/9cb0e58b2deb7f82b84065f37f3bffeb12413f947f9388e4cac22c4621ce/sortedcontainers-2.4.0-py2.py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/6d/ff/f4e04a4bd5a24304f38cb0d4aa2ad4c0fb34999f8b884c656535e1b2b74c/sqlalchemy-2.0.48-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl - pypi: https://files.pythonhosted.org/packages/f1/7b/ce1eafaf1a76852e2ec9b22edecf1daa58175c090266e9f6c64afcd81d91/stack_data-0.6.3-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/13/2d/26b8b30067d94339afee62c3edc9b803a6eb9332f521ba77d8aaab5de873/testcontainers-4.14.2-py3-none-any.whl @@ -797,6 +801,7 @@ environments: - pypi: https://files.pythonhosted.org/packages/7c/5b/cdd2c612277b7ac7ec8c0c9bc41812c43dc7b2d5f2b0897e15fdf5a1f915/fonttools-4.60.1-cp313-cp313-macosx_10_13_universal2.whl - pypi: https://files.pythonhosted.org/packages/0c/ab/6e5080ee374f875296c4243c381bbdef97a9ac39c6e3ce1d5f7d42cb78d6/frozenlist-1.8.0-cp313-cp313-macosx_11_0_arm64.whl - pypi: https://files.pythonhosted.org/packages/d5/1f/5f4a3cd9e4440e9d9bc78ad0a91a1c8d46b4d429d5239ebe6793c9fe5c41/fsspec-2026.3.0-py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/89/ca/22b57e85b174f53a13d5178911860a16d4ea59b7e314662bb3063e28ed7e/hypothesis-6.170.17-cp313-cp313-macosx_11_0_arm64.whl - pypi: https://files.pythonhosted.org/packages/0f/1c/e5fd8f973d4f375adb21565739498e2e9a1e54c858a97b9a8ccfdc81da9b/identify-2.6.15-py2.py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/0e/61/66938bbb5fc52dbdf84594873d5b51fb1f7c7794e9c0f5bd885f30bc507b/idna-3.11-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/cb/b1/3846dd7f199d53cb17f49cba7e651e9ce294d8497c8c150530ed11865bb8/iniconfig-2.3.0-py3-none-any.whl @@ -846,6 +851,7 @@ environments: - pypi: https://files.pythonhosted.org/packages/7d/f8/2be49047f929d6965401855461e697ab185e1a6a683d914c5c19c7962d9e/ruff-0.14.9-py3-none-macosx_11_0_arm64.whl - pypi: https://files.pythonhosted.org/packages/6a/52/5ccdc01f7a8a61357d15a66b5d8a6580aa8529cb33f32e6cbb71c52622c5/s3fs-2026.3.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/b7/ce/149a00dd41f10bc29e5921b496af8b574d8413afcd5e30dfa0ed46c2cc5e/six-1.17.0-py2.py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/32/46/9cb0e58b2deb7f82b84065f37f3bffeb12413f947f9388e4cac22c4621ce/sortedcontainers-2.4.0-py2.py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/d1/c6/569dc8bf3cd375abc5907e82235923e986799f301cd79a903f784b996fca/sqlalchemy-2.0.48-cp313-cp313-macosx_11_0_arm64.whl - pypi: https://files.pythonhosted.org/packages/f1/7b/ce1eafaf1a76852e2ec9b22edecf1daa58175c090266e9f6c64afcd81d91/stack_data-0.6.3-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/13/2d/26b8b30067d94339afee62c3edc9b803a6eb9332f521ba77d8aaab5de873/testcontainers-4.14.2-py3-none-any.whl @@ -985,6 +991,7 @@ environments: - pypi: https://files.pythonhosted.org/packages/d5/1f/5f4a3cd9e4440e9d9bc78ad0a91a1c8d46b4d429d5239ebe6793c9fe5c41/fsspec-2026.3.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/91/4c/e0ce1ef95d4000ebc1c11801f9b944fa5910ecc15b5e351865763d8657f8/graphviz-0.21-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/7a/34/259b28ea7a2a0c904b11cd36c79b8cef8019b26ee5dbe24e73b469dea347/greenlet-3.3.2-cp313-cp313-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl + - pypi: https://files.pythonhosted.org/packages/f5/94/50b6330833c24c8e172e3759902fdebed487611c63a1e18e34db7b024bae/hypothesis-6.170.17-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl - pypi: https://files.pythonhosted.org/packages/76/c6/c88e154df9c4e1a2a66ccf0005a88dfb2650c1dffb6f5ce603dfbd452ce3/idna-3.10-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/2c/e1/e6716421ea10d38022b952c159d5161ca1193197fb744506875fbb87ea7b/iniconfig-2.1.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/08/2a/5628a99d04acb2d2f2e749cdf4ea571d2575e898df0528a090948018b726/ipython-9.5.0-py3-none-any.whl @@ -1028,6 +1035,7 @@ environments: - pypi: https://files.pythonhosted.org/packages/1e/db/4254e3eabe8020b458f1a747140d32277ec7a271daf1d235b70dc0b4e6e3/requests-2.32.5-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/6a/52/5ccdc01f7a8a61357d15a66b5d8a6580aa8529cb33f32e6cbb71c52622c5/s3fs-2026.3.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/b7/ce/149a00dd41f10bc29e5921b496af8b574d8413afcd5e30dfa0ed46c2cc5e/six-1.17.0-py2.py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/32/46/9cb0e58b2deb7f82b84065f37f3bffeb12413f947f9388e4cac22c4621ce/sortedcontainers-2.4.0-py2.py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/fe/88/cb59509e4668d8001818d7355d9995be90c321313078c912420603a7cb95/sqlalchemy-2.0.48-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl - pypi: https://files.pythonhosted.org/packages/f1/7b/ce1eafaf1a76852e2ec9b22edecf1daa58175c090266e9f6c64afcd81d91/stack_data-0.6.3-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/13/2d/26b8b30067d94339afee62c3edc9b803a6eb9332f521ba77d8aaab5de873/testcontainers-4.14.2-py3-none-any.whl @@ -1169,6 +1177,7 @@ environments: - pypi: https://files.pythonhosted.org/packages/d5/1f/5f4a3cd9e4440e9d9bc78ad0a91a1c8d46b4d429d5239ebe6793c9fe5c41/fsspec-2026.3.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/91/4c/e0ce1ef95d4000ebc1c11801f9b944fa5910ecc15b5e351865763d8657f8/graphviz-0.21-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/49/8d/9771d03e7a8b1ee456511961e1b97a6d77ae1dea4a34a5b98eee706689d3/greenlet-3.3.2-cp313-cp313-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl + - pypi: https://files.pythonhosted.org/packages/55/10/17d825f0d0238ba7e1d6735f3f5c44f43e9003e6ff1c128951585c915451/hypothesis-6.170.17-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.whl - pypi: https://files.pythonhosted.org/packages/0e/61/66938bbb5fc52dbdf84594873d5b51fb1f7c7794e9c0f5bd885f30bc507b/idna-3.11-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/cb/b1/3846dd7f199d53cb17f49cba7e651e9ce294d8497c8c150530ed11865bb8/iniconfig-2.3.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/05/aa/62893d6a591d337aa59dcc4c6f6c842f1fe20cd72c8c5c1f980255243252/ipython-9.7.0-py3-none-any.whl @@ -1212,6 +1221,7 @@ environments: - pypi: https://files.pythonhosted.org/packages/1e/db/4254e3eabe8020b458f1a747140d32277ec7a271daf1d235b70dc0b4e6e3/requests-2.32.5-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/6a/52/5ccdc01f7a8a61357d15a66b5d8a6580aa8529cb33f32e6cbb71c52622c5/s3fs-2026.3.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/b7/ce/149a00dd41f10bc29e5921b496af8b574d8413afcd5e30dfa0ed46c2cc5e/six-1.17.0-py2.py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/32/46/9cb0e58b2deb7f82b84065f37f3bffeb12413f947f9388e4cac22c4621ce/sortedcontainers-2.4.0-py2.py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/6d/ff/f4e04a4bd5a24304f38cb0d4aa2ad4c0fb34999f8b884c656535e1b2b74c/sqlalchemy-2.0.48-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl - pypi: https://files.pythonhosted.org/packages/f1/7b/ce1eafaf1a76852e2ec9b22edecf1daa58175c090266e9f6c64afcd81d91/stack_data-0.6.3-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/13/2d/26b8b30067d94339afee62c3edc9b803a6eb9332f521ba77d8aaab5de873/testcontainers-4.14.2-py3-none-any.whl @@ -1307,6 +1317,7 @@ environments: - pypi: https://files.pythonhosted.org/packages/0c/ab/6e5080ee374f875296c4243c381bbdef97a9ac39c6e3ce1d5f7d42cb78d6/frozenlist-1.8.0-cp313-cp313-macosx_11_0_arm64.whl - pypi: https://files.pythonhosted.org/packages/d5/1f/5f4a3cd9e4440e9d9bc78ad0a91a1c8d46b4d429d5239ebe6793c9fe5c41/fsspec-2026.3.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/91/4c/e0ce1ef95d4000ebc1c11801f9b944fa5910ecc15b5e351865763d8657f8/graphviz-0.21-py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/89/ca/22b57e85b174f53a13d5178911860a16d4ea59b7e314662bb3063e28ed7e/hypothesis-6.170.17-cp313-cp313-macosx_11_0_arm64.whl - pypi: https://files.pythonhosted.org/packages/0e/61/66938bbb5fc52dbdf84594873d5b51fb1f7c7794e9c0f5bd885f30bc507b/idna-3.11-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/cb/b1/3846dd7f199d53cb17f49cba7e651e9ce294d8497c8c150530ed11865bb8/iniconfig-2.3.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/48/c5/d5e07995077e48220269c28a221e168c91123ad5ceee44d548f54a057fc0/ipython-9.6.0-py3-none-any.whl @@ -1350,6 +1361,7 @@ environments: - pypi: https://files.pythonhosted.org/packages/1e/db/4254e3eabe8020b458f1a747140d32277ec7a271daf1d235b70dc0b4e6e3/requests-2.32.5-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/6a/52/5ccdc01f7a8a61357d15a66b5d8a6580aa8529cb33f32e6cbb71c52622c5/s3fs-2026.3.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/b7/ce/149a00dd41f10bc29e5921b496af8b574d8413afcd5e30dfa0ed46c2cc5e/six-1.17.0-py2.py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/32/46/9cb0e58b2deb7f82b84065f37f3bffeb12413f947f9388e4cac22c4621ce/sortedcontainers-2.4.0-py2.py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/d1/c6/569dc8bf3cd375abc5907e82235923e986799f301cd79a903f784b996fca/sqlalchemy-2.0.48-cp313-cp313-macosx_11_0_arm64.whl - pypi: https://files.pythonhosted.org/packages/f1/7b/ce1eafaf1a76852e2ec9b22edecf1daa58175c090266e9f6c64afcd81d91/stack_data-0.6.3-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/13/2d/26b8b30067d94339afee62c3edc9b803a6eb9332f521ba77d8aaab5de873/testcontainers-4.14.2-py3-none-any.whl @@ -1504,6 +1516,7 @@ environments: - pypi: https://files.pythonhosted.org/packages/6c/c0/a98505f18594f1bce828bb159cec0fcf9860562f1a2c85913409fc8f3d9e/fsspec-2026.9.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/91/4c/e0ce1ef95d4000ebc1c11801f9b944fa5910ecc15b5e351865763d8657f8/graphviz-0.21-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/94/5c/092682ae7ca1aadd44aa36b0bc35c48c9ed55f9ffebb5794980b1e2ae74b/greenlet-3.5.6-cp310-cp310-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl + - pypi: https://files.pythonhosted.org/packages/42/42/31e66ce21aa6ea030ace8874269e5a169b0c69d8a3043042e315bd64c6ad/hypothesis-6.168.5-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl - pypi: https://files.pythonhosted.org/packages/58/a2/bb081bab032533a855d44de1d56f8e8426114ff1ba5d1f07a438a0a654f8/idna-3.20-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/56/43/4ca9e49d27a1fcf6bece6f6aec0ea46bb9112489b93d4b688fb415457bdb/iniconfig-2.3.1-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/c0/56/4cc7fc9e9e3f38fd324f24f8afe0ad8bb5fa41283f37f1aaf9de0612c968/ipython-8.39.0-py3-none-any.whl @@ -1546,6 +1559,7 @@ environments: - pypi: https://files.pythonhosted.org/packages/a0/f4/c67b0b3f1b9245e8d266f0f112c500d50e5b4e83cb6f3b71b6528104182a/requests-2.34.2-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/bc/9c/15fb18bd708949dc953fe120be8d3c7a1b1b140c2592a9c81ce7961e9ecf/s3fs-2026.9.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/b7/ce/149a00dd41f10bc29e5921b496af8b574d8413afcd5e30dfa0ed46c2cc5e/six-1.17.0-py2.py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/32/46/9cb0e58b2deb7f82b84065f37f3bffeb12413f947f9388e4cac22c4621ce/sortedcontainers-2.4.0-py2.py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/c8/93/9d26b109f5472017bf6e7a1b9dac12ac5f6165ba37a297834d0690c42cf3/sqlalchemy-2.0.54-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl - pypi: https://files.pythonhosted.org/packages/f1/7b/ce1eafaf1a76852e2ec9b22edecf1daa58175c090266e9f6c64afcd81d91/stack_data-0.6.3-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/00/7e/424aac8b355597835deb333e757a0e94b5ccf38ad00f07fe6ed1f4e17c88/testcontainers-4.15.0-py3-none-any.whl @@ -1693,6 +1707,7 @@ environments: - pypi: https://files.pythonhosted.org/packages/6c/c0/a98505f18594f1bce828bb159cec0fcf9860562f1a2c85913409fc8f3d9e/fsspec-2026.9.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/91/4c/e0ce1ef95d4000ebc1c11801f9b944fa5910ecc15b5e351865763d8657f8/graphviz-0.21-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/1d/05/dc0d54e90af2f192724936799cee990687792ff54a4638d3ae0e0a0145c0/greenlet-3.5.6-cp310-cp310-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl + - pypi: https://files.pythonhosted.org/packages/53/1b/8257699b8456241b8348fe0071c29912aeeaf5d16ef97a45e9c1d3170ca6/hypothesis-6.168.5-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl - pypi: https://files.pythonhosted.org/packages/58/a2/bb081bab032533a855d44de1d56f8e8426114ff1ba5d1f07a438a0a654f8/idna-3.20-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/56/43/4ca9e49d27a1fcf6bece6f6aec0ea46bb9112489b93d4b688fb415457bdb/iniconfig-2.3.1-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/c0/56/4cc7fc9e9e3f38fd324f24f8afe0ad8bb5fa41283f37f1aaf9de0612c968/ipython-8.39.0-py3-none-any.whl @@ -1735,6 +1750,7 @@ environments: - pypi: https://files.pythonhosted.org/packages/a0/f4/c67b0b3f1b9245e8d266f0f112c500d50e5b4e83cb6f3b71b6528104182a/requests-2.34.2-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/bc/9c/15fb18bd708949dc953fe120be8d3c7a1b1b140c2592a9c81ce7961e9ecf/s3fs-2026.9.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/b7/ce/149a00dd41f10bc29e5921b496af8b574d8413afcd5e30dfa0ed46c2cc5e/six-1.17.0-py2.py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/32/46/9cb0e58b2deb7f82b84065f37f3bffeb12413f947f9388e4cac22c4621ce/sortedcontainers-2.4.0-py2.py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/84/1f/80122de187c0f80cb47addce97609160004a8605010afdd815e608fcf003/sqlalchemy-2.0.54-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl - pypi: https://files.pythonhosted.org/packages/f1/7b/ce1eafaf1a76852e2ec9b22edecf1daa58175c090266e9f6c64afcd81d91/stack_data-0.6.3-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/00/7e/424aac8b355597835deb333e757a0e94b5ccf38ad00f07fe6ed1f4e17c88/testcontainers-4.15.0-py3-none-any.whl @@ -1834,6 +1850,7 @@ environments: - pypi: https://files.pythonhosted.org/packages/63/70/26ca3f06aace16f2352796b08704338d74b6d1a24ca38f2771afbb7ed915/frozenlist-1.8.0-cp310-cp310-macosx_11_0_arm64.whl - pypi: https://files.pythonhosted.org/packages/6c/c0/a98505f18594f1bce828bb159cec0fcf9860562f1a2c85913409fc8f3d9e/fsspec-2026.9.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/91/4c/e0ce1ef95d4000ebc1c11801f9b944fa5910ecc15b5e351865763d8657f8/graphviz-0.21-py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/a1/60/90ccc9e18d831480920dc0f1d33a9af142e796d67dbe6a760e93d0122587/hypothesis-6.168.5-cp310-cp310-macosx_11_0_arm64.whl - pypi: https://files.pythonhosted.org/packages/58/a2/bb081bab032533a855d44de1d56f8e8426114ff1ba5d1f07a438a0a654f8/idna-3.20-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/56/43/4ca9e49d27a1fcf6bece6f6aec0ea46bb9112489b93d4b688fb415457bdb/iniconfig-2.3.1-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/c0/56/4cc7fc9e9e3f38fd324f24f8afe0ad8bb5fa41283f37f1aaf9de0612c968/ipython-8.39.0-py3-none-any.whl @@ -1876,6 +1893,7 @@ environments: - pypi: https://files.pythonhosted.org/packages/a0/f4/c67b0b3f1b9245e8d266f0f112c500d50e5b4e83cb6f3b71b6528104182a/requests-2.34.2-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/bc/9c/15fb18bd708949dc953fe120be8d3c7a1b1b140c2592a9c81ce7961e9ecf/s3fs-2026.9.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/b7/ce/149a00dd41f10bc29e5921b496af8b574d8413afcd5e30dfa0ed46c2cc5e/six-1.17.0-py2.py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/32/46/9cb0e58b2deb7f82b84065f37f3bffeb12413f947f9388e4cac22c4621ce/sortedcontainers-2.4.0-py2.py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/d5/2f/7a427d7e10bc5f285d41fa1cadf46031ffc6c84f35a9d6e19737587a4eb0/sqlalchemy-2.0.54-cp310-cp310-macosx_11_0_arm64.whl - pypi: https://files.pythonhosted.org/packages/f1/7b/ce1eafaf1a76852e2ec9b22edecf1daa58175c090266e9f6c64afcd81d91/stack_data-0.6.3-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/00/7e/424aac8b355597835deb333e757a0e94b5ccf38ad00f07fe6ed1f4e17c88/testcontainers-4.15.0-py3-none-any.whl @@ -2028,6 +2046,7 @@ environments: - pypi: https://files.pythonhosted.org/packages/a7/b2/fabede9fafd976b991e9f1b9c8c873ed86f202889b864756f240ce6dd855/frozenlist-1.8.0-cp314-cp314-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl - pypi: https://files.pythonhosted.org/packages/6c/c0/a98505f18594f1bce828bb159cec0fcf9860562f1a2c85913409fc8f3d9e/fsspec-2026.9.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/91/4c/e0ce1ef95d4000ebc1c11801f9b944fa5910ecc15b5e351865763d8657f8/graphviz-0.21-py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/9a/40/dd25bf4f43b0fc5f11a1c940dcbed32d7b64f49a038176d7e1bb19daef45/hypothesis-6.170.17-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl - pypi: https://files.pythonhosted.org/packages/58/a2/bb081bab032533a855d44de1d56f8e8426114ff1ba5d1f07a438a0a654f8/idna-3.20-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/56/43/4ca9e49d27a1fcf6bece6f6aec0ea46bb9112489b93d4b688fb415457bdb/iniconfig-2.3.1-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/2d/1e/65b59cf518c106aa755e7f7da3099027738687a862ec785060702a481320/ipython-9.17.1-py3-none-any.whl @@ -2071,6 +2090,7 @@ environments: - pypi: https://files.pythonhosted.org/packages/a0/f4/c67b0b3f1b9245e8d266f0f112c500d50e5b4e83cb6f3b71b6528104182a/requests-2.34.2-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/bc/9c/15fb18bd708949dc953fe120be8d3c7a1b1b140c2592a9c81ce7961e9ecf/s3fs-2026.9.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/b7/ce/149a00dd41f10bc29e5921b496af8b574d8413afcd5e30dfa0ed46c2cc5e/six-1.17.0-py2.py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/32/46/9cb0e58b2deb7f82b84065f37f3bffeb12413f947f9388e4cac22c4621ce/sortedcontainers-2.4.0-py2.py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/0e/02/953686f44448b92cc628245687a242799b6eb11ef30ad2bc7adacd51986d/sqlalchemy-2.1.4-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl - pypi: https://files.pythonhosted.org/packages/f1/7b/ce1eafaf1a76852e2ec9b22edecf1daa58175c090266e9f6c64afcd81d91/stack_data-0.6.3-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/00/7e/424aac8b355597835deb333e757a0e94b5ccf38ad00f07fe6ed1f4e17c88/testcontainers-4.15.0-py3-none-any.whl @@ -2213,6 +2233,7 @@ environments: - pypi: https://files.pythonhosted.org/packages/3a/3b/d9b1e0b0eed36e70477ffb8360c49c85c8ca8ef9700a4e6711f39a6e8b45/frozenlist-1.8.0-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl - pypi: https://files.pythonhosted.org/packages/6c/c0/a98505f18594f1bce828bb159cec0fcf9860562f1a2c85913409fc8f3d9e/fsspec-2026.9.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/91/4c/e0ce1ef95d4000ebc1c11801f9b944fa5910ecc15b5e351865763d8657f8/graphviz-0.21-py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/05/aa/15aee492ab8305a5684268fd56828ea7c578f6d5ad0af63a3a70262f6846/hypothesis-6.170.17-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.whl - pypi: https://files.pythonhosted.org/packages/58/a2/bb081bab032533a855d44de1d56f8e8426114ff1ba5d1f07a438a0a654f8/idna-3.20-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/56/43/4ca9e49d27a1fcf6bece6f6aec0ea46bb9112489b93d4b688fb415457bdb/iniconfig-2.3.1-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/2d/1e/65b59cf518c106aa755e7f7da3099027738687a862ec785060702a481320/ipython-9.17.1-py3-none-any.whl @@ -2256,6 +2277,7 @@ environments: - pypi: https://files.pythonhosted.org/packages/a0/f4/c67b0b3f1b9245e8d266f0f112c500d50e5b4e83cb6f3b71b6528104182a/requests-2.34.2-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/bc/9c/15fb18bd708949dc953fe120be8d3c7a1b1b140c2592a9c81ce7961e9ecf/s3fs-2026.9.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/b7/ce/149a00dd41f10bc29e5921b496af8b574d8413afcd5e30dfa0ed46c2cc5e/six-1.17.0-py2.py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/32/46/9cb0e58b2deb7f82b84065f37f3bffeb12413f947f9388e4cac22c4621ce/sortedcontainers-2.4.0-py2.py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/7e/24/4630a4009ea08a0769d5ff6517c7fc978f6a63eba32e08c44b98c284d7e4/sqlalchemy-2.1.4-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl - pypi: https://files.pythonhosted.org/packages/f1/7b/ce1eafaf1a76852e2ec9b22edecf1daa58175c090266e9f6c64afcd81d91/stack_data-0.6.3-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/00/7e/424aac8b355597835deb333e757a0e94b5ccf38ad00f07fe6ed1f4e17c88/testcontainers-4.15.0-py3-none-any.whl @@ -2353,6 +2375,7 @@ environments: - pypi: https://files.pythonhosted.org/packages/a1/93/72b1736d68f03fda5fdf0f2180fb6caaae3894f1b854d006ac61ecc727ee/frozenlist-1.8.0-cp314-cp314-macosx_11_0_arm64.whl - pypi: https://files.pythonhosted.org/packages/6c/c0/a98505f18594f1bce828bb159cec0fcf9860562f1a2c85913409fc8f3d9e/fsspec-2026.9.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/91/4c/e0ce1ef95d4000ebc1c11801f9b944fa5910ecc15b5e351865763d8657f8/graphviz-0.21-py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/8d/87/1cfea1cfdc41bc6bbfd4a55060fbf29074bc2e8dda5fa683584438a7c1d8/hypothesis-6.170.17-cp314-cp314-macosx_11_0_arm64.whl - pypi: https://files.pythonhosted.org/packages/58/a2/bb081bab032533a855d44de1d56f8e8426114ff1ba5d1f07a438a0a654f8/idna-3.20-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/56/43/4ca9e49d27a1fcf6bece6f6aec0ea46bb9112489b93d4b688fb415457bdb/iniconfig-2.3.1-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/2d/1e/65b59cf518c106aa755e7f7da3099027738687a862ec785060702a481320/ipython-9.17.1-py3-none-any.whl @@ -2396,6 +2419,7 @@ environments: - pypi: https://files.pythonhosted.org/packages/a0/f4/c67b0b3f1b9245e8d266f0f112c500d50e5b4e83cb6f3b71b6528104182a/requests-2.34.2-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/bc/9c/15fb18bd708949dc953fe120be8d3c7a1b1b140c2592a9c81ce7961e9ecf/s3fs-2026.9.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/b7/ce/149a00dd41f10bc29e5921b496af8b574d8413afcd5e30dfa0ed46c2cc5e/six-1.17.0-py2.py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/32/46/9cb0e58b2deb7f82b84065f37f3bffeb12413f947f9388e4cac22c4621ce/sortedcontainers-2.4.0-py2.py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/43/b0/6675a01f4e6215e0a809d28a800953294ab31370fe8c4bb3eb9e28c0b5a6/sqlalchemy-2.1.4-cp314-cp314-macosx_11_0_arm64.whl - pypi: https://files.pythonhosted.org/packages/f1/7b/ce1eafaf1a76852e2ec9b22edecf1daa58175c090266e9f6c64afcd81d91/stack_data-0.6.3-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/00/7e/424aac8b355597835deb333e757a0e94b5ccf38ad00f07fe6ed1f4e17c88/testcontainers-4.15.0-py3-none-any.whl @@ -2543,6 +2567,7 @@ environments: - pypi: https://files.pythonhosted.org/packages/9a/9a/e35b4a917281c0b8419d4207f4334c8e8c5dbf4f3f5f9ada73958d937dcc/frozenlist-1.8.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/6c/c0/a98505f18594f1bce828bb159cec0fcf9860562f1a2c85913409fc8f3d9e/fsspec-2026.9.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/91/4c/e0ce1ef95d4000ebc1c11801f9b944fa5910ecc15b5e351865763d8657f8/graphviz-0.21-py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/5e/2d/085fb8685b15572e62fd5e7400b35e2656c0a54d82fd87945914ae741908/hypothesis-6.170.17-cp315-abi3.abi3t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl - pypi: https://files.pythonhosted.org/packages/58/a2/bb081bab032533a855d44de1d56f8e8426114ff1ba5d1f07a438a0a654f8/idna-3.20-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/56/43/4ca9e49d27a1fcf6bece6f6aec0ea46bb9112489b93d4b688fb415457bdb/iniconfig-2.3.1-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/2d/1e/65b59cf518c106aa755e7f7da3099027738687a862ec785060702a481320/ipython-9.17.1-py3-none-any.whl @@ -2586,6 +2611,7 @@ environments: - pypi: https://files.pythonhosted.org/packages/a0/f4/c67b0b3f1b9245e8d266f0f112c500d50e5b4e83cb6f3b71b6528104182a/requests-2.34.2-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/bc/9c/15fb18bd708949dc953fe120be8d3c7a1b1b140c2592a9c81ce7961e9ecf/s3fs-2026.9.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/b7/ce/149a00dd41f10bc29e5921b496af8b574d8413afcd5e30dfa0ed46c2cc5e/six-1.17.0-py2.py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/32/46/9cb0e58b2deb7f82b84065f37f3bffeb12413f947f9388e4cac22c4621ce/sortedcontainers-2.4.0-py2.py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/70/81/5cadd72b0c26b6ee7c1e6950cb9f0cfc383246a842314a1b2a87f455db25/sqlalchemy-2.1.4-cp315-cp315-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl - pypi: https://files.pythonhosted.org/packages/f1/7b/ce1eafaf1a76852e2ec9b22edecf1daa58175c090266e9f6c64afcd81d91/stack_data-0.6.3-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/00/7e/424aac8b355597835deb333e757a0e94b5ccf38ad00f07fe6ed1f4e17c88/testcontainers-4.15.0-py3-none-any.whl @@ -2725,6 +2751,7 @@ environments: - pypi: https://files.pythonhosted.org/packages/9a/9a/e35b4a917281c0b8419d4207f4334c8e8c5dbf4f3f5f9ada73958d937dcc/frozenlist-1.8.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/6c/c0/a98505f18594f1bce828bb159cec0fcf9860562f1a2c85913409fc8f3d9e/fsspec-2026.9.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/91/4c/e0ce1ef95d4000ebc1c11801f9b944fa5910ecc15b5e351865763d8657f8/graphviz-0.21-py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/eb/88/99a5b9d2230bd8c8b7f48408b2a026c12d56f36aa74f1f1689b8b4c09b58/hypothesis-6.170.17-cp315-abi3.abi3t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl - pypi: https://files.pythonhosted.org/packages/58/a2/bb081bab032533a855d44de1d56f8e8426114ff1ba5d1f07a438a0a654f8/idna-3.20-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/56/43/4ca9e49d27a1fcf6bece6f6aec0ea46bb9112489b93d4b688fb415457bdb/iniconfig-2.3.1-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/2d/1e/65b59cf518c106aa755e7f7da3099027738687a862ec785060702a481320/ipython-9.17.1-py3-none-any.whl @@ -2768,6 +2795,7 @@ environments: - pypi: https://files.pythonhosted.org/packages/a0/f4/c67b0b3f1b9245e8d266f0f112c500d50e5b4e83cb6f3b71b6528104182a/requests-2.34.2-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/bc/9c/15fb18bd708949dc953fe120be8d3c7a1b1b140c2592a9c81ce7961e9ecf/s3fs-2026.9.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/b7/ce/149a00dd41f10bc29e5921b496af8b574d8413afcd5e30dfa0ed46c2cc5e/six-1.17.0-py2.py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/32/46/9cb0e58b2deb7f82b84065f37f3bffeb12413f947f9388e4cac22c4621ce/sortedcontainers-2.4.0-py2.py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/d1/35/74db254005ecb384533973b157ba1fc3fe5bc41a5bc6e0500ab8369c49e6/sqlalchemy-2.1.4-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl - pypi: https://files.pythonhosted.org/packages/f1/7b/ce1eafaf1a76852e2ec9b22edecf1daa58175c090266e9f6c64afcd81d91/stack_data-0.6.3-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/00/7e/424aac8b355597835deb333e757a0e94b5ccf38ad00f07fe6ed1f4e17c88/testcontainers-4.15.0-py3-none-any.whl @@ -2863,6 +2891,7 @@ environments: - pypi: https://files.pythonhosted.org/packages/9a/9a/e35b4a917281c0b8419d4207f4334c8e8c5dbf4f3f5f9ada73958d937dcc/frozenlist-1.8.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/6c/c0/a98505f18594f1bce828bb159cec0fcf9860562f1a2c85913409fc8f3d9e/fsspec-2026.9.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/91/4c/e0ce1ef95d4000ebc1c11801f9b944fa5910ecc15b5e351865763d8657f8/graphviz-0.21-py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/2b/c7/da7f8f554e4bb5ad0c1e44f8ed105f495add887922bafd20dc5858e6c988/hypothesis-6.170.17-cp315-abi3.abi3t-macosx_11_0_arm64.whl - pypi: https://files.pythonhosted.org/packages/58/a2/bb081bab032533a855d44de1d56f8e8426114ff1ba5d1f07a438a0a654f8/idna-3.20-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/56/43/4ca9e49d27a1fcf6bece6f6aec0ea46bb9112489b93d4b688fb415457bdb/iniconfig-2.3.1-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/2d/1e/65b59cf518c106aa755e7f7da3099027738687a862ec785060702a481320/ipython-9.17.1-py3-none-any.whl @@ -2906,6 +2935,7 @@ environments: - pypi: https://files.pythonhosted.org/packages/a0/f4/c67b0b3f1b9245e8d266f0f112c500d50e5b4e83cb6f3b71b6528104182a/requests-2.34.2-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/bc/9c/15fb18bd708949dc953fe120be8d3c7a1b1b140c2592a9c81ce7961e9ecf/s3fs-2026.9.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/b7/ce/149a00dd41f10bc29e5921b496af8b574d8413afcd5e30dfa0ed46c2cc5e/six-1.17.0-py2.py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/32/46/9cb0e58b2deb7f82b84065f37f3bffeb12413f947f9388e4cac22c4621ce/sortedcontainers-2.4.0-py2.py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/2b/8e/a082a165b473dae45d2f2f79be15f5c405ac579830c64253efbf04695177/sqlalchemy-2.1.4-cp315-cp315-macosx_11_0_arm64.whl - pypi: https://files.pythonhosted.org/packages/f1/7b/ce1eafaf1a76852e2ec9b22edecf1daa58175c090266e9f6c64afcd81d91/stack_data-0.6.3-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/00/7e/424aac8b355597835deb333e757a0e94b5ccf38ad00f07fe6ed1f4e17c88/testcontainers-4.15.0-py3-none-any.whl @@ -4495,24 +4525,25 @@ packages: requires_python: '>=3.8' - pypi: ./ name: datajoint - version: 2.3.5.dev28+ge3d2a553e.d20261024 - sha256: 9ac2b52fcb44ab2d1c54ec75a4c390fc2a8d53b0480a2490d897c2dc22f593a3 + version: 2.3.5.dev47+g753f704b0.d20261123 + sha256: eefdb6654d0cf7ad77691419e94118b9ed13c2d4458eacdbf74d62e2fdb6a820 requires_dist: - - deepdiff - deepdiff<9 ; python_full_version >= '3.15' + - deepdiff>=6.6.0 - fsspec>=2023.1.0 - - networkx - - numpy - - packaging - - pandas + - networkx>=3.0 + - numpy>=1.22.4 + - packaging>=22.0 + - pandas>=2.2.2 - pydantic-settings>=2.0.0 - - pydot - - pymysql>=0.7.2 - - pyparsing - - tqdm + - pydot>=3.0.0 + - pymysql>=1.1.1 + - pyparsing>=3.1.1 + - tqdm>=4.66.3 - pyarrow>=14.0.0 ; extra == 'arrow' - adlfs>=2023.1.0 ; extra == 'azure' - codespell ; extra == 'dev' + - hypothesis ; extra == 'dev' - polars>=0.20.0 ; extra == 'dev' - pre-commit ; extra == 'dev' - pyarrow>=14.0.0 ; extra == 'dev' @@ -4524,6 +4555,7 @@ packages: - psycopg2-binary>=2.9.0 ; extra == 'postgres' - s3fs>=2023.1.0 ; extra == 's3' - faker ; extra == 'test' + - hypothesis ; extra == 'test' - ipython ; extra == 'test' - matplotlib ; extra == 'test' - polars>=0.20.0 ; extra == 'test' @@ -6581,6 +6613,513 @@ packages: purls: [] size: 17616 timestamp: 1771539622983 +- pypi: https://files.pythonhosted.org/packages/42/42/31e66ce21aa6ea030ace8874269e5a169b0c69d8a3043042e315bd64c6ad/hypothesis-6.168.5-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl + name: hypothesis + version: 6.168.5 + sha256: 30208c44364b6fe1f70c74b45f3f1f8a173a749d876294a80fe88c9cf16ab6d0 + requires_dist: + - exceptiongroup>=1.0.0 ; python_full_version < '3.11' + - sortedcontainers>=2.1.0,<3.0.0 + - black>=20.8b0 ; extra == 'all' + - click>=7.0 ; extra == 'all' + - crosshair-tool>=0.0.111 ; extra == 'all' + - django>=5.2 ; extra == 'all' + - dpcontracts>=0.4 ; extra == 'all' + - hypothesis-crosshair>=0.0.30 ; extra == 'all' + - lark>=0.10.1 ; extra == 'all' + - libcst>=0.3.16 ; extra == 'all' + - numpy>=1.21.6 ; extra == 'all' + - pandas>=1.1 ; extra == 'all' + - pytest>=4.6 ; extra == 'all' + - python-dateutil>=1.4 ; extra == 'all' + - pytz>=2014.1 ; extra == 'all' + - redis>=3.0.0 ; extra == 'all' + - rich>=9.0.0 ; extra == 'all' + - tzdata>=2026.5 ; (sys_platform == 'emscripten' and extra == 'all') or (sys_platform == 'win32' and extra == 'all') + - watchdog>=4.0.0 ; extra == 'all' + - click>=7.0 ; extra == 'cli' + - black>=20.8b0 ; extra == 'cli' + - rich>=9.0.0 ; extra == 'cli' + - libcst>=0.3.16 ; extra == 'codemods' + - hypothesis-crosshair>=0.0.30 ; extra == 'crosshair' + - crosshair-tool>=0.0.111 ; extra == 'crosshair' + - python-dateutil>=1.4 ; extra == 'dateutil' + - django>=5.2 ; extra == 'django' + - dpcontracts>=0.4 ; extra == 'dpcontracts' + - black>=20.8b0 ; extra == 'ghostwriter' + - lark>=0.10.1 ; extra == 'lark' + - numpy>=1.21.6 ; extra == 'numpy' + - pandas>=1.1 ; extra == 'pandas' + - pytest>=4.6 ; extra == 'pytest' + - pytz>=2014.1 ; extra == 'pytz' + - redis>=3.0.0 ; extra == 'redis' + - watchdog>=4.0.0 ; extra == 'watchdog' + - tzdata>=2026.5 ; (sys_platform == 'emscripten' and extra == 'zoneinfo') or (sys_platform == 'win32' and extra == 'zoneinfo') + requires_python: '>=3.10' +- pypi: https://files.pythonhosted.org/packages/53/1b/8257699b8456241b8348fe0071c29912aeeaf5d16ef97a45e9c1d3170ca6/hypothesis-6.168.5-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl + name: hypothesis + version: 6.168.5 + sha256: 54f40be9b9c6b7b058ff56b0b18a91ff4cfa57a7c7756043eabaa094a0a162c9 + requires_dist: + - exceptiongroup>=1.0.0 ; python_full_version < '3.11' + - sortedcontainers>=2.1.0,<3.0.0 + - black>=20.8b0 ; extra == 'all' + - click>=7.0 ; extra == 'all' + - crosshair-tool>=0.0.111 ; extra == 'all' + - django>=5.2 ; extra == 'all' + - dpcontracts>=0.4 ; extra == 'all' + - hypothesis-crosshair>=0.0.30 ; extra == 'all' + - lark>=0.10.1 ; extra == 'all' + - libcst>=0.3.16 ; extra == 'all' + - numpy>=1.21.6 ; extra == 'all' + - pandas>=1.1 ; extra == 'all' + - pytest>=4.6 ; extra == 'all' + - python-dateutil>=1.4 ; extra == 'all' + - pytz>=2014.1 ; extra == 'all' + - redis>=3.0.0 ; extra == 'all' + - rich>=9.0.0 ; extra == 'all' + - tzdata>=2026.5 ; (sys_platform == 'emscripten' and extra == 'all') or (sys_platform == 'win32' and extra == 'all') + - watchdog>=4.0.0 ; extra == 'all' + - click>=7.0 ; extra == 'cli' + - black>=20.8b0 ; extra == 'cli' + - rich>=9.0.0 ; extra == 'cli' + - libcst>=0.3.16 ; extra == 'codemods' + - hypothesis-crosshair>=0.0.30 ; extra == 'crosshair' + - crosshair-tool>=0.0.111 ; extra == 'crosshair' + - python-dateutil>=1.4 ; extra == 'dateutil' + - django>=5.2 ; extra == 'django' + - dpcontracts>=0.4 ; extra == 'dpcontracts' + - black>=20.8b0 ; extra == 'ghostwriter' + - lark>=0.10.1 ; extra == 'lark' + - numpy>=1.21.6 ; extra == 'numpy' + - pandas>=1.1 ; extra == 'pandas' + - pytest>=4.6 ; extra == 'pytest' + - pytz>=2014.1 ; extra == 'pytz' + - redis>=3.0.0 ; extra == 'redis' + - watchdog>=4.0.0 ; extra == 'watchdog' + - tzdata>=2026.5 ; (sys_platform == 'emscripten' and extra == 'zoneinfo') or (sys_platform == 'win32' and extra == 'zoneinfo') + requires_python: '>=3.10' +- pypi: https://files.pythonhosted.org/packages/a1/60/90ccc9e18d831480920dc0f1d33a9af142e796d67dbe6a760e93d0122587/hypothesis-6.168.5-cp310-cp310-macosx_11_0_arm64.whl + name: hypothesis + version: 6.168.5 + sha256: 658563b8f2782a0577a4d8d195e31f29b18f3f3b61ba58c4dcbd8e6ac502d14d + requires_dist: + - exceptiongroup>=1.0.0 ; python_full_version < '3.11' + - sortedcontainers>=2.1.0,<3.0.0 + - black>=20.8b0 ; extra == 'all' + - click>=7.0 ; extra == 'all' + - crosshair-tool>=0.0.111 ; extra == 'all' + - django>=5.2 ; extra == 'all' + - dpcontracts>=0.4 ; extra == 'all' + - hypothesis-crosshair>=0.0.30 ; extra == 'all' + - lark>=0.10.1 ; extra == 'all' + - libcst>=0.3.16 ; extra == 'all' + - numpy>=1.21.6 ; extra == 'all' + - pandas>=1.1 ; extra == 'all' + - pytest>=4.6 ; extra == 'all' + - python-dateutil>=1.4 ; extra == 'all' + - pytz>=2014.1 ; extra == 'all' + - redis>=3.0.0 ; extra == 'all' + - rich>=9.0.0 ; extra == 'all' + - tzdata>=2026.5 ; (sys_platform == 'emscripten' and extra == 'all') or (sys_platform == 'win32' and extra == 'all') + - watchdog>=4.0.0 ; extra == 'all' + - click>=7.0 ; extra == 'cli' + - black>=20.8b0 ; extra == 'cli' + - rich>=9.0.0 ; extra == 'cli' + - libcst>=0.3.16 ; extra == 'codemods' + - hypothesis-crosshair>=0.0.30 ; extra == 'crosshair' + - crosshair-tool>=0.0.111 ; extra == 'crosshair' + - python-dateutil>=1.4 ; extra == 'dateutil' + - django>=5.2 ; extra == 'django' + - dpcontracts>=0.4 ; extra == 'dpcontracts' + - black>=20.8b0 ; extra == 'ghostwriter' + - lark>=0.10.1 ; extra == 'lark' + - numpy>=1.21.6 ; extra == 'numpy' + - pandas>=1.1 ; extra == 'pandas' + - pytest>=4.6 ; extra == 'pytest' + - pytz>=2014.1 ; extra == 'pytz' + - redis>=3.0.0 ; extra == 'redis' + - watchdog>=4.0.0 ; extra == 'watchdog' + - tzdata>=2026.5 ; (sys_platform == 'emscripten' and extra == 'zoneinfo') or (sys_platform == 'win32' and extra == 'zoneinfo') + requires_python: '>=3.10' +- pypi: https://files.pythonhosted.org/packages/05/aa/15aee492ab8305a5684268fd56828ea7c578f6d5ad0af63a3a70262f6846/hypothesis-6.170.17-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.whl + name: hypothesis + version: 6.170.17 + sha256: 3dc7aad87973e8305370f1d79e8b1593c6373524447fa2cb7688438e658275ed + requires_dist: + - sortedcontainers>=2.1.0,<3.0.0 + - black>=20.8b0 ; extra == 'all' + - click>=7.0 ; extra == 'all' + - crosshair-tool>=0.0.113 ; extra == 'all' + - django>=5.2 ; extra == 'all' + - dpcontracts>=0.4 ; extra == 'all' + - hypothesis-crosshair>=0.0.32 ; extra == 'all' + - lark>=0.10.1 ; extra == 'all' + - libcst>=0.3.16 ; extra == 'all' + - numpy>=1.23.2 ; extra == 'all' + - pandas>=1.5 ; extra == 'all' + - pytest>=4.6 ; extra == 'all' + - python-dateutil>=1.4 ; extra == 'all' + - pytz>=2014.1 ; extra == 'all' + - redis>=3.0.0 ; extra == 'all' + - rich>=9.0.0 ; extra == 'all' + - tzdata>=2026.6 ; (sys_platform == 'emscripten' and extra == 'all') or (sys_platform == 'win32' and extra == 'all') + - watchdog>=4.0.0 ; extra == 'all' + - click>=7.0 ; extra == 'cli' + - black>=20.8b0 ; extra == 'cli' + - rich>=9.0.0 ; extra == 'cli' + - libcst>=0.3.16 ; extra == 'codemods' + - hypothesis-crosshair>=0.0.32 ; extra == 'crosshair' + - crosshair-tool>=0.0.113 ; extra == 'crosshair' + - python-dateutil>=1.4 ; extra == 'dateutil' + - django>=5.2 ; extra == 'django' + - dpcontracts>=0.4 ; extra == 'dpcontracts' + - black>=20.8b0 ; extra == 'ghostwriter' + - lark>=0.10.1 ; extra == 'lark' + - numpy>=1.23.2 ; extra == 'numpy' + - pandas>=1.5 ; extra == 'pandas' + - pytest>=4.6 ; extra == 'pytest' + - pytz>=2014.1 ; extra == 'pytz' + - redis>=3.0.0 ; extra == 'redis' + - watchdog>=4.0.0 ; extra == 'watchdog' + - tzdata>=2026.6 ; (sys_platform == 'emscripten' and extra == 'zoneinfo') or (sys_platform == 'win32' and extra == 'zoneinfo') + requires_python: '>=3.11' +- pypi: https://files.pythonhosted.org/packages/2b/c7/da7f8f554e4bb5ad0c1e44f8ed105f495add887922bafd20dc5858e6c988/hypothesis-6.170.17-cp315-abi3.abi3t-macosx_11_0_arm64.whl + name: hypothesis + version: 6.170.17 + sha256: d5c20b61e3e7052e6de81ad1399066f660de7585faec7365bc351bcabfabfc98 + requires_dist: + - sortedcontainers>=2.1.0,<3.0.0 + - black>=20.8b0 ; extra == 'all' + - click>=7.0 ; extra == 'all' + - crosshair-tool>=0.0.113 ; extra == 'all' + - django>=5.2 ; extra == 'all' + - dpcontracts>=0.4 ; extra == 'all' + - hypothesis-crosshair>=0.0.32 ; extra == 'all' + - lark>=0.10.1 ; extra == 'all' + - libcst>=0.3.16 ; extra == 'all' + - numpy>=1.23.2 ; extra == 'all' + - pandas>=1.5 ; extra == 'all' + - pytest>=4.6 ; extra == 'all' + - python-dateutil>=1.4 ; extra == 'all' + - pytz>=2014.1 ; extra == 'all' + - redis>=3.0.0 ; extra == 'all' + - rich>=9.0.0 ; extra == 'all' + - tzdata>=2026.6 ; (sys_platform == 'emscripten' and extra == 'all') or (sys_platform == 'win32' and extra == 'all') + - watchdog>=4.0.0 ; extra == 'all' + - click>=7.0 ; extra == 'cli' + - black>=20.8b0 ; extra == 'cli' + - rich>=9.0.0 ; extra == 'cli' + - libcst>=0.3.16 ; extra == 'codemods' + - hypothesis-crosshair>=0.0.32 ; extra == 'crosshair' + - crosshair-tool>=0.0.113 ; extra == 'crosshair' + - python-dateutil>=1.4 ; extra == 'dateutil' + - django>=5.2 ; extra == 'django' + - dpcontracts>=0.4 ; extra == 'dpcontracts' + - black>=20.8b0 ; extra == 'ghostwriter' + - lark>=0.10.1 ; extra == 'lark' + - numpy>=1.23.2 ; extra == 'numpy' + - pandas>=1.5 ; extra == 'pandas' + - pytest>=4.6 ; extra == 'pytest' + - pytz>=2014.1 ; extra == 'pytz' + - redis>=3.0.0 ; extra == 'redis' + - watchdog>=4.0.0 ; extra == 'watchdog' + - tzdata>=2026.6 ; (sys_platform == 'emscripten' and extra == 'zoneinfo') or (sys_platform == 'win32' and extra == 'zoneinfo') + requires_python: '>=3.11' +- pypi: https://files.pythonhosted.org/packages/55/10/17d825f0d0238ba7e1d6735f3f5c44f43e9003e6ff1c128951585c915451/hypothesis-6.170.17-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.whl + name: hypothesis + version: 6.170.17 + sha256: c9e5128120882dd8b75de43f8be753f2090d176c3f0be614c6e782fb4029fa86 + requires_dist: + - sortedcontainers>=2.1.0,<3.0.0 + - black>=20.8b0 ; extra == 'all' + - click>=7.0 ; extra == 'all' + - crosshair-tool>=0.0.113 ; extra == 'all' + - django>=5.2 ; extra == 'all' + - dpcontracts>=0.4 ; extra == 'all' + - hypothesis-crosshair>=0.0.32 ; extra == 'all' + - lark>=0.10.1 ; extra == 'all' + - libcst>=0.3.16 ; extra == 'all' + - numpy>=1.23.2 ; extra == 'all' + - pandas>=1.5 ; extra == 'all' + - pytest>=4.6 ; extra == 'all' + - python-dateutil>=1.4 ; extra == 'all' + - pytz>=2014.1 ; extra == 'all' + - redis>=3.0.0 ; extra == 'all' + - rich>=9.0.0 ; extra == 'all' + - tzdata>=2026.6 ; (sys_platform == 'emscripten' and extra == 'all') or (sys_platform == 'win32' and extra == 'all') + - watchdog>=4.0.0 ; extra == 'all' + - click>=7.0 ; extra == 'cli' + - black>=20.8b0 ; extra == 'cli' + - rich>=9.0.0 ; extra == 'cli' + - libcst>=0.3.16 ; extra == 'codemods' + - hypothesis-crosshair>=0.0.32 ; extra == 'crosshair' + - crosshair-tool>=0.0.113 ; extra == 'crosshair' + - python-dateutil>=1.4 ; extra == 'dateutil' + - django>=5.2 ; extra == 'django' + - dpcontracts>=0.4 ; extra == 'dpcontracts' + - black>=20.8b0 ; extra == 'ghostwriter' + - lark>=0.10.1 ; extra == 'lark' + - numpy>=1.23.2 ; extra == 'numpy' + - pandas>=1.5 ; extra == 'pandas' + - pytest>=4.6 ; extra == 'pytest' + - pytz>=2014.1 ; extra == 'pytz' + - redis>=3.0.0 ; extra == 'redis' + - watchdog>=4.0.0 ; extra == 'watchdog' + - tzdata>=2026.6 ; (sys_platform == 'emscripten' and extra == 'zoneinfo') or (sys_platform == 'win32' and extra == 'zoneinfo') + requires_python: '>=3.11' +- pypi: https://files.pythonhosted.org/packages/5e/2d/085fb8685b15572e62fd5e7400b35e2656c0a54d82fd87945914ae741908/hypothesis-6.170.17-cp315-abi3.abi3t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl + name: hypothesis + version: 6.170.17 + sha256: 8b429c7028a9d2859e08575f88c68925b517e37ee96ea2ab6757411331933b4c + requires_dist: + - sortedcontainers>=2.1.0,<3.0.0 + - black>=20.8b0 ; extra == 'all' + - click>=7.0 ; extra == 'all' + - crosshair-tool>=0.0.113 ; extra == 'all' + - django>=5.2 ; extra == 'all' + - dpcontracts>=0.4 ; extra == 'all' + - hypothesis-crosshair>=0.0.32 ; extra == 'all' + - lark>=0.10.1 ; extra == 'all' + - libcst>=0.3.16 ; extra == 'all' + - numpy>=1.23.2 ; extra == 'all' + - pandas>=1.5 ; extra == 'all' + - pytest>=4.6 ; extra == 'all' + - python-dateutil>=1.4 ; extra == 'all' + - pytz>=2014.1 ; extra == 'all' + - redis>=3.0.0 ; extra == 'all' + - rich>=9.0.0 ; extra == 'all' + - tzdata>=2026.6 ; (sys_platform == 'emscripten' and extra == 'all') or (sys_platform == 'win32' and extra == 'all') + - watchdog>=4.0.0 ; extra == 'all' + - click>=7.0 ; extra == 'cli' + - black>=20.8b0 ; extra == 'cli' + - rich>=9.0.0 ; extra == 'cli' + - libcst>=0.3.16 ; extra == 'codemods' + - hypothesis-crosshair>=0.0.32 ; extra == 'crosshair' + - crosshair-tool>=0.0.113 ; extra == 'crosshair' + - python-dateutil>=1.4 ; extra == 'dateutil' + - django>=5.2 ; extra == 'django' + - dpcontracts>=0.4 ; extra == 'dpcontracts' + - black>=20.8b0 ; extra == 'ghostwriter' + - lark>=0.10.1 ; extra == 'lark' + - numpy>=1.23.2 ; extra == 'numpy' + - pandas>=1.5 ; extra == 'pandas' + - pytest>=4.6 ; extra == 'pytest' + - pytz>=2014.1 ; extra == 'pytz' + - redis>=3.0.0 ; extra == 'redis' + - watchdog>=4.0.0 ; extra == 'watchdog' + - tzdata>=2026.6 ; (sys_platform == 'emscripten' and extra == 'zoneinfo') or (sys_platform == 'win32' and extra == 'zoneinfo') + requires_python: '>=3.11' +- pypi: https://files.pythonhosted.org/packages/89/ca/22b57e85b174f53a13d5178911860a16d4ea59b7e314662bb3063e28ed7e/hypothesis-6.170.17-cp313-cp313-macosx_11_0_arm64.whl + name: hypothesis + version: 6.170.17 + sha256: 90b5691ce795c9708fd4d984370088716ee59fc2b3271ed2350e7821cf87d82a + requires_dist: + - sortedcontainers>=2.1.0,<3.0.0 + - black>=20.8b0 ; extra == 'all' + - click>=7.0 ; extra == 'all' + - crosshair-tool>=0.0.113 ; extra == 'all' + - django>=5.2 ; extra == 'all' + - dpcontracts>=0.4 ; extra == 'all' + - hypothesis-crosshair>=0.0.32 ; extra == 'all' + - lark>=0.10.1 ; extra == 'all' + - libcst>=0.3.16 ; extra == 'all' + - numpy>=1.23.2 ; extra == 'all' + - pandas>=1.5 ; extra == 'all' + - pytest>=4.6 ; extra == 'all' + - python-dateutil>=1.4 ; extra == 'all' + - pytz>=2014.1 ; extra == 'all' + - redis>=3.0.0 ; extra == 'all' + - rich>=9.0.0 ; extra == 'all' + - tzdata>=2026.6 ; (sys_platform == 'emscripten' and extra == 'all') or (sys_platform == 'win32' and extra == 'all') + - watchdog>=4.0.0 ; extra == 'all' + - click>=7.0 ; extra == 'cli' + - black>=20.8b0 ; extra == 'cli' + - rich>=9.0.0 ; extra == 'cli' + - libcst>=0.3.16 ; extra == 'codemods' + - hypothesis-crosshair>=0.0.32 ; extra == 'crosshair' + - crosshair-tool>=0.0.113 ; extra == 'crosshair' + - python-dateutil>=1.4 ; extra == 'dateutil' + - django>=5.2 ; extra == 'django' + - dpcontracts>=0.4 ; extra == 'dpcontracts' + - black>=20.8b0 ; extra == 'ghostwriter' + - lark>=0.10.1 ; extra == 'lark' + - numpy>=1.23.2 ; extra == 'numpy' + - pandas>=1.5 ; extra == 'pandas' + - pytest>=4.6 ; extra == 'pytest' + - pytz>=2014.1 ; extra == 'pytz' + - redis>=3.0.0 ; extra == 'redis' + - watchdog>=4.0.0 ; extra == 'watchdog' + - tzdata>=2026.6 ; (sys_platform == 'emscripten' and extra == 'zoneinfo') or (sys_platform == 'win32' and extra == 'zoneinfo') + requires_python: '>=3.11' +- pypi: https://files.pythonhosted.org/packages/8d/87/1cfea1cfdc41bc6bbfd4a55060fbf29074bc2e8dda5fa683584438a7c1d8/hypothesis-6.170.17-cp314-cp314-macosx_11_0_arm64.whl + name: hypothesis + version: 6.170.17 + sha256: 6c77ea50c8c77fec99f18e3f3e4ac48730e573e63d500275170ca94e48c6ec55 + requires_dist: + - sortedcontainers>=2.1.0,<3.0.0 + - black>=20.8b0 ; extra == 'all' + - click>=7.0 ; extra == 'all' + - crosshair-tool>=0.0.113 ; extra == 'all' + - django>=5.2 ; extra == 'all' + - dpcontracts>=0.4 ; extra == 'all' + - hypothesis-crosshair>=0.0.32 ; extra == 'all' + - lark>=0.10.1 ; extra == 'all' + - libcst>=0.3.16 ; extra == 'all' + - numpy>=1.23.2 ; extra == 'all' + - pandas>=1.5 ; extra == 'all' + - pytest>=4.6 ; extra == 'all' + - python-dateutil>=1.4 ; extra == 'all' + - pytz>=2014.1 ; extra == 'all' + - redis>=3.0.0 ; extra == 'all' + - rich>=9.0.0 ; extra == 'all' + - tzdata>=2026.6 ; (sys_platform == 'emscripten' and extra == 'all') or (sys_platform == 'win32' and extra == 'all') + - watchdog>=4.0.0 ; extra == 'all' + - click>=7.0 ; extra == 'cli' + - black>=20.8b0 ; extra == 'cli' + - rich>=9.0.0 ; extra == 'cli' + - libcst>=0.3.16 ; extra == 'codemods' + - hypothesis-crosshair>=0.0.32 ; extra == 'crosshair' + - crosshair-tool>=0.0.113 ; extra == 'crosshair' + - python-dateutil>=1.4 ; extra == 'dateutil' + - django>=5.2 ; extra == 'django' + - dpcontracts>=0.4 ; extra == 'dpcontracts' + - black>=20.8b0 ; extra == 'ghostwriter' + - lark>=0.10.1 ; extra == 'lark' + - numpy>=1.23.2 ; extra == 'numpy' + - pandas>=1.5 ; extra == 'pandas' + - pytest>=4.6 ; extra == 'pytest' + - pytz>=2014.1 ; extra == 'pytz' + - redis>=3.0.0 ; extra == 'redis' + - watchdog>=4.0.0 ; extra == 'watchdog' + - tzdata>=2026.6 ; (sys_platform == 'emscripten' and extra == 'zoneinfo') or (sys_platform == 'win32' and extra == 'zoneinfo') + requires_python: '>=3.11' +- pypi: https://files.pythonhosted.org/packages/9a/40/dd25bf4f43b0fc5f11a1c940dcbed32d7b64f49a038176d7e1bb19daef45/hypothesis-6.170.17-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl + name: hypothesis + version: 6.170.17 + sha256: 38122420168c2f47a42ee848b73f684bc03f6d7c5e0ffcb10eb2a153af55be96 + requires_dist: + - sortedcontainers>=2.1.0,<3.0.0 + - black>=20.8b0 ; extra == 'all' + - click>=7.0 ; extra == 'all' + - crosshair-tool>=0.0.113 ; extra == 'all' + - django>=5.2 ; extra == 'all' + - dpcontracts>=0.4 ; extra == 'all' + - hypothesis-crosshair>=0.0.32 ; extra == 'all' + - lark>=0.10.1 ; extra == 'all' + - libcst>=0.3.16 ; extra == 'all' + - numpy>=1.23.2 ; extra == 'all' + - pandas>=1.5 ; extra == 'all' + - pytest>=4.6 ; extra == 'all' + - python-dateutil>=1.4 ; extra == 'all' + - pytz>=2014.1 ; extra == 'all' + - redis>=3.0.0 ; extra == 'all' + - rich>=9.0.0 ; extra == 'all' + - tzdata>=2026.6 ; (sys_platform == 'emscripten' and extra == 'all') or (sys_platform == 'win32' and extra == 'all') + - watchdog>=4.0.0 ; extra == 'all' + - click>=7.0 ; extra == 'cli' + - black>=20.8b0 ; extra == 'cli' + - rich>=9.0.0 ; extra == 'cli' + - libcst>=0.3.16 ; extra == 'codemods' + - hypothesis-crosshair>=0.0.32 ; extra == 'crosshair' + - crosshair-tool>=0.0.113 ; extra == 'crosshair' + - python-dateutil>=1.4 ; extra == 'dateutil' + - django>=5.2 ; extra == 'django' + - dpcontracts>=0.4 ; extra == 'dpcontracts' + - black>=20.8b0 ; extra == 'ghostwriter' + - lark>=0.10.1 ; extra == 'lark' + - numpy>=1.23.2 ; extra == 'numpy' + - pandas>=1.5 ; extra == 'pandas' + - pytest>=4.6 ; extra == 'pytest' + - pytz>=2014.1 ; extra == 'pytz' + - redis>=3.0.0 ; extra == 'redis' + - watchdog>=4.0.0 ; extra == 'watchdog' + - tzdata>=2026.6 ; (sys_platform == 'emscripten' and extra == 'zoneinfo') or (sys_platform == 'win32' and extra == 'zoneinfo') + requires_python: '>=3.11' +- pypi: https://files.pythonhosted.org/packages/eb/88/99a5b9d2230bd8c8b7f48408b2a026c12d56f36aa74f1f1689b8b4c09b58/hypothesis-6.170.17-cp315-abi3.abi3t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl + name: hypothesis + version: 6.170.17 + sha256: 3668a9b07a785e3211b5529f0710245abbef9902a649325bd220a82af49aa35c + requires_dist: + - sortedcontainers>=2.1.0,<3.0.0 + - black>=20.8b0 ; extra == 'all' + - click>=7.0 ; extra == 'all' + - crosshair-tool>=0.0.113 ; extra == 'all' + - django>=5.2 ; extra == 'all' + - dpcontracts>=0.4 ; extra == 'all' + - hypothesis-crosshair>=0.0.32 ; extra == 'all' + - lark>=0.10.1 ; extra == 'all' + - libcst>=0.3.16 ; extra == 'all' + - numpy>=1.23.2 ; extra == 'all' + - pandas>=1.5 ; extra == 'all' + - pytest>=4.6 ; extra == 'all' + - python-dateutil>=1.4 ; extra == 'all' + - pytz>=2014.1 ; extra == 'all' + - redis>=3.0.0 ; extra == 'all' + - rich>=9.0.0 ; extra == 'all' + - tzdata>=2026.6 ; (sys_platform == 'emscripten' and extra == 'all') or (sys_platform == 'win32' and extra == 'all') + - watchdog>=4.0.0 ; extra == 'all' + - click>=7.0 ; extra == 'cli' + - black>=20.8b0 ; extra == 'cli' + - rich>=9.0.0 ; extra == 'cli' + - libcst>=0.3.16 ; extra == 'codemods' + - hypothesis-crosshair>=0.0.32 ; extra == 'crosshair' + - crosshair-tool>=0.0.113 ; extra == 'crosshair' + - python-dateutil>=1.4 ; extra == 'dateutil' + - django>=5.2 ; extra == 'django' + - dpcontracts>=0.4 ; extra == 'dpcontracts' + - black>=20.8b0 ; extra == 'ghostwriter' + - lark>=0.10.1 ; extra == 'lark' + - numpy>=1.23.2 ; extra == 'numpy' + - pandas>=1.5 ; extra == 'pandas' + - pytest>=4.6 ; extra == 'pytest' + - pytz>=2014.1 ; extra == 'pytz' + - redis>=3.0.0 ; extra == 'redis' + - watchdog>=4.0.0 ; extra == 'watchdog' + - tzdata>=2026.6 ; (sys_platform == 'emscripten' and extra == 'zoneinfo') or (sys_platform == 'win32' and extra == 'zoneinfo') + requires_python: '>=3.11' +- pypi: https://files.pythonhosted.org/packages/f5/94/50b6330833c24c8e172e3759902fdebed487611c63a1e18e34db7b024bae/hypothesis-6.170.17-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl + name: hypothesis + version: 6.170.17 + sha256: 475bd1ed6971a237540f68a5b2004a415b738a6c7a68bdc3efaa85f8e385d942 + requires_dist: + - sortedcontainers>=2.1.0,<3.0.0 + - black>=20.8b0 ; extra == 'all' + - click>=7.0 ; extra == 'all' + - crosshair-tool>=0.0.113 ; extra == 'all' + - django>=5.2 ; extra == 'all' + - dpcontracts>=0.4 ; extra == 'all' + - hypothesis-crosshair>=0.0.32 ; extra == 'all' + - lark>=0.10.1 ; extra == 'all' + - libcst>=0.3.16 ; extra == 'all' + - numpy>=1.23.2 ; extra == 'all' + - pandas>=1.5 ; extra == 'all' + - pytest>=4.6 ; extra == 'all' + - python-dateutil>=1.4 ; extra == 'all' + - pytz>=2014.1 ; extra == 'all' + - redis>=3.0.0 ; extra == 'all' + - rich>=9.0.0 ; extra == 'all' + - tzdata>=2026.6 ; (sys_platform == 'emscripten' and extra == 'all') or (sys_platform == 'win32' and extra == 'all') + - watchdog>=4.0.0 ; extra == 'all' + - click>=7.0 ; extra == 'cli' + - black>=20.8b0 ; extra == 'cli' + - rich>=9.0.0 ; extra == 'cli' + - libcst>=0.3.16 ; extra == 'codemods' + - hypothesis-crosshair>=0.0.32 ; extra == 'crosshair' + - crosshair-tool>=0.0.113 ; extra == 'crosshair' + - python-dateutil>=1.4 ; extra == 'dateutil' + - django>=5.2 ; extra == 'django' + - dpcontracts>=0.4 ; extra == 'dpcontracts' + - black>=20.8b0 ; extra == 'ghostwriter' + - lark>=0.10.1 ; extra == 'lark' + - numpy>=1.23.2 ; extra == 'numpy' + - pandas>=1.5 ; extra == 'pandas' + - pytest>=4.6 ; extra == 'pytest' + - pytz>=2014.1 ; extra == 'pytz' + - redis>=3.0.0 ; extra == 'redis' + - watchdog>=4.0.0 ; extra == 'watchdog' + - tzdata>=2026.6 ; (sys_platform == 'emscripten' and extra == 'zoneinfo') or (sys_platform == 'win32' and extra == 'zoneinfo') + requires_python: '>=3.11' - conda: https://conda.anaconda.org/conda-forge/linux-64/icu-75.1-he02047a_0.conda sha256: 71e750d509f5fa3421087ba88ef9a7b9be11c53174af3aa4d06aff4c18b38e8e md5: 8b189310083baabfb622af68fd9d3ae3 @@ -13527,6 +14066,10 @@ packages: version: 1.17.0 sha256: 4721f391ed90541fddacab5acf947aa0d3dc7d27b2e1e8eda2be8970586c3274 requires_python: '>=2.7,!=3.0.*,!=3.1.*,!=3.2.*' +- pypi: https://files.pythonhosted.org/packages/32/46/9cb0e58b2deb7f82b84065f37f3bffeb12413f947f9388e4cac22c4621ce/sortedcontainers-2.4.0-py2.py3-none-any.whl + name: sortedcontainers + version: 2.4.0 + sha256: a163dcaede0f1c021485e957a39245190e74249897e2ae4b2aa38595db237ee0 - pypi: https://files.pythonhosted.org/packages/6d/ff/f4e04a4bd5a24304f38cb0d4aa2ad4c0fb34999f8b884c656535e1b2b74c/sqlalchemy-2.0.48-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl name: sqlalchemy version: 2.0.48 diff --git a/pyproject.toml b/pyproject.toml index 47c1019e7..a73865200 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -6,20 +6,31 @@ build-backend = "hatchling.build" name = "datajoint" dynamic = ["version"] dependencies = [ - "numpy", - "pymysql>=0.7.2", - "deepdiff", + "numpy>=1.22.4", + # pymysql 1.0 adds the ssl_disabled connection option; 1.1.1 fixes + # CVE-2024-36039. + "pymysql>=1.1.1", + # deepdiff 6.4 adds DeepHash(ignore_iterable_order=...); 6.6 supports numpy 2. + # CVE-2025-58367 and CVE-2026-33155 (fixed in 8.6.2) affect Delta and + # pickle_load; datajoint uses only DeepHash. + "deepdiff>=6.6.0", # deepdiff 9 requires cachebox<6, which ships no Python 3.15 wheels and cannot # be built for 3.15 (PyO3 0.27). Drop once deepdiff accepts cachebox 6. "deepdiff<9; python_version >= '3.15'", - "pyparsing", - "pandas", - "tqdm", - "networkx", - "pydot", + # pyparsing 3.1.0 drops the quotes from quoted defaults (= ""), which + # declares the attribute without a default. + "pyparsing>=3.1.1", + # pandas 2.2.2 is the first release built against numpy 2; older pandas + # fails on import when numpy 2 is installed. + "pandas>=2.2.2", + # CVE-2024-34062 + "tqdm>=4.66.3", + "networkx>=3.0", + # pydot 2.x emits DOT that graphviz rejects for datajoint diagrams. + "pydot>=3.0.0", "fsspec>=2023.1.0", "pydantic-settings>=2.0.0", - "packaging", + "packaging>=22.0", ] requires-python = ">=3.10,<3.16" @@ -91,6 +102,7 @@ datajoint = "datajoint.cli:cli" test = [ "pytest", "pytest-cov", + "hypothesis", "requests", "faker", "matplotlib", @@ -112,6 +124,7 @@ viz = ["matplotlib", "ipython"] test = [ "pytest", "pytest-cov", + "hypothesis", "requests", "faker", "matplotlib", @@ -129,6 +142,7 @@ dev = [ # including test "pytest", "pytest-cov", + "hypothesis", "polars>=0.20.0", "pyarrow>=14.0.0", ] @@ -240,7 +254,8 @@ skip = ".git,*.pdf,*.svg,*.csv,*.ipynb,*.drawio" # Rever -- nobody knows # numer -- numerator variable # astroid -- Python library name (not "asteroid") -ignore-words-list = "rever,numer,astroid" +# acter -- regex fragment char(?:acter)? +ignore-words-list = "rever,numer,astroid,acter" [tool.pytest.ini_options] markers = [ diff --git a/src/datajoint/__init__.py b/src/datajoint/__init__.py index 69c6df269..df7577042 100644 --- a/src/datajoint/__init__.py +++ b/src/datajoint/__init__.py @@ -134,7 +134,11 @@ def conn( reset : bool, optional If True, reset existing connection. Default False. use_tls : bool or dict, optional - TLS encryption option. + TLS encryption option: True (required), False (no TLS), None (from + config; TLS if the server supports it by default), or dict (TLS + required; ``ca``, ``cert``, ``key``; with ``ca``, the server + certificate is verified). If the singleton connection exists, it is + reconnected with these unless it already satisfies them. Returns ------- @@ -152,10 +156,12 @@ def conn( _check_thread_safe() # If reset requested, always recreate - # If credentials provided and no singleton exists, create one - # If credentials provided and singleton exists, return existing singleton + # If credentials or use_tls provided and no singleton exists, create one + # If credentials provided and singleton exists, return existing singleton, + # reconnected with use_tls unless it already satisfies use_tls if reset or ( - instance_module._singleton_connection is None and (host is not None or user is not None or password is not None) + instance_module._singleton_connection is None + and (host is not None or user is not None or password is not None or use_tls is not None) ): # Use provided values or fall back to config host = host if host is not None else _global_config.database.host @@ -177,6 +183,8 @@ def conn( ) instance_module._singleton_connection = Connection(host, user, password, port, use_tls, config_override=_global_config) + elif instance_module._singleton_connection is not None: + instance_module._singleton_connection._ensure_tls(use_tls) return _get_singleton_connection() diff --git a/src/datajoint/adapters/mysql.py b/src/datajoint/adapters/mysql.py index 38e3ad1b1..e55425254 100644 --- a/src/datajoint/adapters/mysql.py +++ b/src/datajoint/adapters/mysql.py @@ -7,9 +7,11 @@ from __future__ import annotations +import ssl from typing import Any import pymysql as client +from pymysql.constants import CLIENT, CR from .. import errors from .base import DatabaseAdapter @@ -45,6 +47,53 @@ } +class _TLSUnavailableError(client.err.OperationalError): + """TLS is required but the server does not offer it.""" + + def __init__(self): + super().__init__( + CR.CR_SSL_CONNECTION_ERROR, + "TLS is required (use_tls) but the server does not support it", + ) + + +class _TLSRequiredConnection(client.connections.Connection): + """ + PyMySQL connection that does not authenticate without TLS. + + Depending on its version, PyMySQL continues without TLS or fails with a + handshake error when TLS is configured and the server does not offer it. + This check runs after the server greeting, before the credentials are sent. + """ + + tls_required = True + + # server_capabilities and _request_authentication are PyMySQL internals + # that types-PyMySQL does not declare. + def _request_authentication(self): + if not self.server_capabilities & CLIENT.SSL: # type: ignore[attr-defined] + if self.tls_required: + raise _TLSUnavailableError() + # Continue without TLS: do not announce TLS in the handshake response + self.ssl = False + self.client_flag &= ~CLIENT.SSL + super()._request_authentication() # type: ignore[misc] + + +class _TLSPreferredConnection(_TLSRequiredConnection): + """PyMySQL connection that uses TLS when the server offers it and continues without TLS otherwise.""" + + tls_required = False + + +def _unverified_tls_context() -> ssl.SSLContext: + """TLS context that encrypts without verifying the server certificate.""" + context = ssl.create_default_context() + context.check_hostname = False + context.verify_mode = ssl.CERT_NONE + return context + + class MySQLAdapter(DatabaseAdapter): """MySQL database adapter implementation.""" @@ -76,7 +125,13 @@ def connect( **kwargs : Any Additional MySQL-specific parameters: - ssl: TLS/SSL configuration dict (deprecated, use use_tls) - - use_tls: bool or dict - DataJoint's SSL parameter (preferred) + - use_tls: bool or dict - DataJoint's SSL parameter (preferred). + None: TLS if the server offers it, otherwise no TLS; server + certificate not verified. + True: TLS required, server certificate not verified. + dict: TLS required, configured with PyMySQL ``ssl`` keys + (``ca``, ``cert``, ``key``, ``check_hostname``, ...); with ``ca``, + the server certificate is verified. False: TLS disabled. - charset: Character set (default from kwargs) Returns @@ -86,9 +141,11 @@ def connect( """ # Handle both ssl (old) and use_tls (new) parameter names ssl_config = kwargs.get("use_tls", kwargs.get("ssl")) - # Convert boolean True to dict for PyMySQL (PyMySQL expects dict or SSLContext) - if ssl_config is True: - ssl_config = {} # Enable SSL with default settings + tls_required = ssl_config is not None + # PyMySQL treats an empty dict as "no TLS"; None, True, and {} use TLS + # without verifying the server certificate. + if ssl_config is None or ssl_config is True or (isinstance(ssl_config, dict) and not ssl_config): + ssl_config = _unverified_tls_context() charset = kwargs.get("charset", "") # Prepare connection parameters @@ -107,13 +164,22 @@ def connect( if ssl_config is False: # Explicitly disable SSL conn_params["ssl_disabled"] = True - elif ssl_config is not None: - # Enable SSL with config dict (can be empty for defaults) - conn_params["ssl"] = ssl_config - # Explicitly enable SSL by setting ssl_disabled=False - conn_params["ssl_disabled"] = False - - return client.connect(**conn_params) + return client.connect(**conn_params) + + conn_params["ssl"] = ssl_config + # Explicitly enable SSL by setting ssl_disabled=False + conn_params["ssl_disabled"] = False + if not tls_required: + # use_tls=None: one connection, with TLS if the server offers it + return _TLSPreferredConnection(**conn_params) + + # Require SSL, configured by the dict or SSLContext + connection = _TLSRequiredConnection(**conn_params) + # Checked again in case a PyMySQL version bypasses the hook above + if not connection.server_capabilities & CLIENT.SSL: # type: ignore[attr-defined] # PyMySQL internal + connection.close() + raise _TLSUnavailableError() + return connection def close(self, connection: Any) -> None: """Close the MySQL connection.""" @@ -219,8 +285,8 @@ def quote_string(self, value: str) -> str: str Quoted and escaped string literal. """ - # Use pymysql's escape_string for proper escaping - escaped = client.converters.escape_string(value) + # Use pymysql's escape_string, but double quotes so the literal stays closed even under NO_BACKSLASH_ESCAPES + escaped = client.converters.escape_string(value).replace("\\'", "''") return f"'{escaped}'" def get_master_table_name(self, part_table: str) -> str | None: @@ -892,7 +958,7 @@ def json_path_expr(self, column: str, path: str, return_type: str | None = None) """ quoted_col = self.quote_identifier(column) return_clause = f" returning {return_type}" if return_type else "" - return f"json_value({quoted_col}, _utf8mb4'$.{path}'{return_clause})" + return f"json_value({quoted_col}, _utf8mb4{self.quote_string('$.' + path)}{return_clause})" def translate_expression(self, expr: str) -> str: """ diff --git a/src/datajoint/adapters/postgres.py b/src/datajoint/adapters/postgres.py index 91cc5311b..52686763f 100644 --- a/src/datajoint/adapters/postgres.py +++ b/src/datajoint/adapters/postgres.py @@ -7,6 +7,7 @@ from __future__ import annotations +import logging import re from typing import Any @@ -20,6 +21,53 @@ from .. import errors from .base import DatabaseAdapter +logger = logging.getLogger(__name__.split(".")[0]) + +# use_tls dict keys (PyMySQL ssl names, as for MySQL) → libpq connection parameters +_LIBPQ_TLS_KEYS = {"ca": "sslrootcert", "cert": "sslcert", "key": "sslkey", "password": "sslpassword"} + + +def _tls_rejected(error: Exception) -> bool: + """ + Whether a connection attempt with sslmode=require was refused before authentication + because of SSL: the server does not support SSL, or pg_hba.conf has no entry + for SSL connections from this client. + + psycopg2 does not report a SQLSTATE for connection failures, so the libpq and + server messages are matched. Authentication failures do not match. + """ + message = str(error) + if "server does not support SSL" in message: + return True + # SQLSTATE 28000 from pg_hba.conf; "SSL encryption" (PostgreSQL 14+) or "SSL on" (earlier) + return "pg_hba.conf" in message and ("SSL encryption" in message or "SSL on" in message) + + +def _libpq_tls_params(use_tls: dict) -> dict[str, Any]: + """ + Map a ``use_tls`` dict to libpq SSL connection parameters. + + With ``ca``, the server certificate is verified against it: sslmode + ``verify-full`` (certificate and host name), or ``verify-ca`` when + ``check_hostname`` is False. Without ``ca``, sslmode is ``require``. + """ + params = {_LIBPQ_TLS_KEYS[k]: v for k, v in use_tls.items() if k in _LIBPQ_TLS_KEYS and v is not None} + supported = set(_LIBPQ_TLS_KEYS) + if "sslrootcert" in params: + params["sslmode"] = "verify-full" if use_tls.get("check_hostname", True) else "verify-ca" + supported.add("check_hostname") + else: + params["sslmode"] = "require" + # Keys set to None or False request nothing; other unused keys are reported + ignored = sorted(k for k in set(use_tls) - supported if use_tls[k] not in (None, False)) + if ignored: + logger.warning( + "use_tls keys ignored for PostgreSQL: %s. Supported: ca, cert, key, password, and check_hostname with ca.", + ", ".join(ignored), + ) + return params + + # Core type mapping: DataJoint core types → PostgreSQL types CORE_TYPE_MAP = { "int64": "bigint", @@ -90,8 +138,15 @@ def connect( **kwargs : Any Additional PostgreSQL-specific parameters: - dbname: Database name - - sslmode: SSL mode ('disable', 'allow', 'prefer', 'require') - - use_tls: bool or dict - DataJoint's SSL parameter (converted to sslmode) + - sslmode: SSL mode ('disable', 'allow', 'prefer', 'require', + 'verify-ca', 'verify-full') + - use_tls: bool or dict - DataJoint's SSL parameter (converted to sslmode). + True: 'require'. False: 'disable'. + None: 'require', then 'disable' only if the server does not support + SSL or pg_hba.conf does not accept SSL connections from this client. + dict: ``ca``, ``cert``, ``key``, ``password`` map to sslrootcert, + sslcert, sslkey, sslpassword; sslmode is 'verify-full' with ``ca`` + ('verify-ca' if ``check_hostname`` is False), otherwise 'require'. - connect_timeout: Connection timeout in seconds Returns @@ -105,28 +160,41 @@ def connect( # Handle use_tls parameter (from DataJoint Connection) # Convert to PostgreSQL's sslmode use_tls = kwargs.get("use_tls") + tls_params = {} if "sslmode" in kwargs: # Explicit sslmode takes precedence sslmode = kwargs["sslmode"] elif use_tls is False: # use_tls=False → disable SSL sslmode = "disable" - elif use_tls is True or isinstance(use_tls, dict): - # use_tls=True or dict → require SSL + elif isinstance(use_tls, dict): + # use_tls=dict → require SSL, verified when a CA is given + tls_params = _libpq_tls_params(use_tls) + sslmode = tls_params.pop("sslmode") + elif use_tls is True: + # use_tls=True → require SSL sslmode = "require" else: - # use_tls=None (default) → prefer SSL but allow fallback - sslmode = "prefer" + # use_tls=None (default) → require SSL, then fall back below. libpq's + # sslmode=prefer also retries without SSL after an authentication failure. + sslmode = "require" - conn = client.connect( + params = dict( host=host, port=port, user=user, password=password, dbname=dbname, - sslmode=sslmode, connect_timeout=connect_timeout, + **tls_params, ) + try: + conn = client.connect(sslmode=sslmode, **params) + except client.OperationalError as error: + if "sslmode" in kwargs or use_tls is not None or not _tls_rejected(error): + raise + logger.debug("Connecting without SSL: %s", str(error).strip()) + conn = client.connect(sslmode="disable", **params) # DataJoint manages transactions explicitly via start_transaction() # Set autocommit=True to avoid implicit transactions conn.autocommit = True @@ -1136,7 +1204,7 @@ def json_path_expr(self, column: str, path: str, return_type: str | None = None) path_parts.extend(indices) else: path_parts.append(part) - path_args = ", ".join(f"'{part}'" for part in path_parts) + path_args = ", ".join(self.quote_string(part) for part in path_parts) expr = f"jsonb_extract_path_text({quoted_col}, {path_args})" # Add cast if return type specified if return_type: diff --git a/src/datajoint/blob.py b/src/datajoint/blob.py index 633f55b79..d8bf7a416 100644 --- a/src/datajoint/blob.py +++ b/src/datajoint/blob.py @@ -10,6 +10,7 @@ import collections import datetime +import sys import uuid import zlib from decimal import Decimal @@ -58,7 +59,32 @@ } -compression = {b"ZL123\0": zlib.decompress} +def _zlib_decompress(data, size): + """ + Decompress zlib ``data`` that is declared to expand to exactly ``size`` bytes. + + Output is capped at ``size`` bytes, so a payload that expands beyond its + declared size is rejected without being expanded in full. + """ + if size > sys.maxsize: + raise DataJointError(f"Blob size mismatch: declared size {size} is not supported") + decompressor = zlib.decompressobj() + try: + # max_length=0 would mean "no limit", so ask for at least one byte + blob = decompressor.decompress(data, max(size, 1)) + if not decompressor.eof: + # check whether the stream holds more than the declared size + blob += decompressor.decompress(decompressor.unconsumed_tail, 1) + except zlib.error as error: + raise DataJointError(f"Corrupt compressed blob: {error}") from None + if len(blob) > size: + raise DataJointError(f"Blob size mismatch: expected {size} bytes, compressed data holds more") + if len(blob) != size or not decompressor.eof: + raise DataJointError(f"Blob size mismatch: expected {size}, got {len(blob)}") + return blob + + +compression = {b"ZL123\0": _zlib_decompress} # runtime setting to read integers as 32-bit to read blobs created by the 32-bit # version of the mYm library for MATLAB @@ -161,10 +187,7 @@ def unpack(self, blob): else: self._pos += len(prefix) blob_size = self.read_value() - blob = compression[prefix](self._blob[self._pos :]) - if len(blob) != blob_size: - raise DataJointError(f"Blob size mismatch: expected {blob_size}, got {len(blob)}") - self._blob = blob + self._blob = compression[prefix](self._blob[self._pos :], int(blob_size)) self._pos = 0 blob_format = self.read_zero_terminated_string() if blob_format in ("mYm", "dj0"): diff --git a/src/datajoint/builtin_codecs/attach.py b/src/datajoint/builtin_codecs/attach.py index 8035810be..5c6e9eb70 100644 --- a/src/datajoint/builtin_codecs/attach.py +++ b/src/datajoint/builtin_codecs/attach.py @@ -4,9 +4,46 @@ from __future__ import annotations +import os +import stat +from pathlib import Path from typing import Any from ..codecs import Codec +from ..errors import DataJointError +from ..utils import is_plain_file_name + + +def _check_file_name(filename: str) -> None: + """ + Raise unless ``filename`` is a plain file name with no directory part. + + ``encode`` stores only the base name of the attached file. A stored name + with path separators (``/`` or ``\\``), ``..``, a NUL byte, or (on Windows) + a drive or stream marker ``:`` is refused. + """ + if not is_plain_file_name(filename): + raise DataJointError(f" stored file name {filename!r} is not a plain file name.") + + +def _has_contents(path: Path, contents: bytes) -> bool: + """ + Check whether ``path`` is a regular file holding exactly ``contents``. + + Symbolic links, devices, and pipes are never opened, and a file is read only + when its size matches. + """ + try: + st = os.lstat(path) + except FileNotFoundError: + return False + if not stat.S_ISREG(st.st_mode) or st.st_size != len(contents): + return False + fd = os.open(path, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_BINARY", 0)) + with os.fdopen(fd, "rb") as f: + if not stat.S_ISREG(os.fstat(f.fileno()).st_mode): + return False + return f.read(len(contents) + 1) == contents class AttachCodec(Codec): @@ -19,7 +56,9 @@ class AttachCodec(Codec): - ````: Stored in specific named store The filename is preserved and the file is extracted to the configured - download path on fetch. + download path on fetch. Only the base name is kept, and fetch refuses a + stored name that is not a plain file name, so extracted files always land + directly in the download path. Example:: @@ -70,8 +109,6 @@ def encode( bytes Filename (UTF-8) + null byte + file contents. """ - from pathlib import Path - path = Path(value) if not path.exists(): raise FileNotFoundError(f"Attachment file not found: {path}") @@ -97,13 +134,17 @@ def decode(self, stored: bytes, *, key: dict | None = None, context: dict | None ------- str Path to extracted file. - """ - from pathlib import Path + Raises + ------ + DataJointError + If the stored file name is not a plain file name. + """ # Split on first null byte null_pos = stored.index(b"\x00") filename = stored[:null_pos].decode("utf-8") contents = stored[null_pos + 1 :] + _check_file_name(filename) # Write to download path config = self._codec_config(key, context) @@ -113,28 +154,31 @@ def decode(self, stored: bytes, *, key: dict | None = None, context: dict | None download_path = Path(config.get("download_path", ".")) download_path.mkdir(parents=True, exist_ok=True) local_path = download_path / filename - - # Handle filename collision - if file exists with different content, add suffix - if local_path.exists(): - existing_contents = local_path.read_bytes() - if existing_contents != contents: - # Find unique filename - stem = local_path.stem - suffix = local_path.suffix - counter = 1 - while local_path.exists() and local_path.read_bytes() != contents: - local_path = download_path / f"{stem}_{counter}{suffix}" - counter += 1 - - # Only write if file doesn't exist or has different content - if not local_path.exists(): - local_path.write_bytes(contents) - - return str(local_path) + if local_path.parent != download_path: + raise DataJointError(f" file name {filename!r} leads outside the download path.") + + # Reuse a file with identical content; otherwise add a numeric suffix until + # a free name is found. New files are created exclusively, never through an + # existing file or link. + stem = local_path.stem + suffix = local_path.suffix + counter = 0 + while True: + if _has_contents(local_path, contents): + return str(local_path) + if not os.path.lexists(local_path): + flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_BINARY", 0) + try: + fd = os.open(local_path, flags, 0o666) + except FileExistsError: + continue # created concurrently; check it again + with os.fdopen(fd, "wb") as f: + f.write(contents) + return str(local_path) + counter += 1 + local_path = download_path / f"{stem}_{counter}{suffix}" def validate(self, value: Any) -> None: """Validate that value is a valid file path.""" - from pathlib import Path - if not isinstance(value, (str, Path)): raise TypeError(f" expects a file path, got {type(value).__name__}") diff --git a/src/datajoint/builtin_codecs/filepath.py b/src/datajoint/builtin_codecs/filepath.py index 9ba128c86..abe14c0e6 100644 --- a/src/datajoint/builtin_codecs/filepath.py +++ b/src/datajoint/builtin_codecs/filepath.py @@ -59,6 +59,14 @@ class Recordings(dj.Manual): Paths cannot start with the store's reserved ``hash_prefix`` or ``schema_prefix`` sections (defaults ``_hash/`` and ``_schema/``). + Store Boundary: + Paths must stay inside the store location: paths with ``..`` + components and, for ``file`` stores, absolute paths outside the + location are rejected on insert and on access. An absolute path + inside a ``file`` store's location is recorded relative to it. Set + ``dj.config.allow_filepath_outside_store`` to accept references that + point outside the store. + Warning: The file must exist in the store at the specified path. DataJoint does not manage the lifecycle of referenced files. @@ -99,12 +107,16 @@ def encode( ------ ValueError If path uses the store's reserved hash/schema sections. + DataJointError + If path leads outside the store location (see + ``allow_filepath_outside_store``). FileNotFoundError If file does not exist in the store. """ + import posixpath from datetime import datetime, timezone - from ..hash_registry import get_store_backend + from ..storage import path_in_location config = self._codec_config(key, context) if config is None: @@ -117,8 +129,16 @@ def encode( # Use filepath_default if no store specified (filepath is not part of OAS) spec = config.get_store_spec(store_name, use_filepath_default=True) - # Validate path doesn't use reserved sections (hash and schema) - path_normalized = path.lstrip("/") + # Reject paths outside the store before any prefix checks. An absolute + # path inside a file store's location is recorded relative to it. + backend = self._get_backend(store_name, config) + backend._full_path(path) + if spec.get("protocol") == "file": + path = path_in_location(spec["location"], path) or path + + # Validate path doesn't use reserved sections (hash and schema). + # Normalize first so that "./_hash/x" or "//_hash/x" are caught too. + path_normalized = posixpath.normpath(path.replace("\\", "/")).lstrip("/") reserved_prefixes = [] hash_prefix = spec.get("hash_prefix") @@ -129,10 +149,11 @@ def encode( if schema_prefix: reserved_prefixes.append(("schema_prefix", schema_prefix)) - # Check if path starts with any reserved prefix + # Check if path starts with any reserved prefix. Compare without case: + # on case-insensitive file systems "_HASH/x" is the same as "_hash/x". for prefix_name, prefix_value in reserved_prefixes: prefix_normalized = prefix_value.strip("/") + "/" - if path_normalized.startswith(prefix_normalized): + if (path_normalized + "/").casefold().startswith(prefix_normalized.casefold()): raise ValueError( f" cannot use reserved section '{prefix_value}' ({prefix_name}). " f"This section is managed by DataJoint. " @@ -147,7 +168,6 @@ def encode( raise ValueError(f" must use prefix '{filepath_prefix}' (filepath_prefix). Got path: {path}") # Verify file exists - backend = get_store_backend(store_name, config=config) if not backend.exists(path): raise FileNotFoundError(f"File not found in store '{store_name or 'default'}': {path}") @@ -187,13 +207,25 @@ def decode(self, stored: dict, *, key: dict | None = None, context: dict | None Handle for accessing the file. """ from ..objectref import ObjectRef - from ..hash_registry import get_store_backend config = self._codec_config(key, context) - store_name = stored.get("store") - backend = get_store_backend(store_name, config=config) + backend = self._get_backend(stored.get("store"), config) return ObjectRef.from_json(stored, backend=backend) + @staticmethod + def _get_backend(store_name: str | None, config): + """ + Get the store backend, confined to the store location unless + ``allow_filepath_outside_store`` is set. + """ + from ..hash_registry import get_store_backend + + if config is None: + from ..settings import config # type: ignore[assignment] + backend = get_store_backend(store_name, config=config) + backend.confine_paths = not config.get("allow_filepath_outside_store", False) + return backend + def validate(self, value: Any) -> None: """Validate that value is a path string or Path object.""" from pathlib import Path diff --git a/src/datajoint/builtin_codecs/npy.py b/src/datajoint/builtin_codecs/npy.py index c6eab2118..df9d00b85 100644 --- a/src/datajoint/builtin_codecs/npy.py +++ b/src/datajoint/builtin_codecs/npy.py @@ -4,11 +4,83 @@ from __future__ import annotations +import logging +import os +import shutil +import stat +import tempfile +from pathlib import Path from typing import Any from ..errors import DataJointError from .schema import SchemaCodec +logger = logging.getLogger(__name__.split(".")[0]) + +# Private directory created for this process when the per-user cache path is unusable +_fallback_mmap_cache_dir: Path | None = None + + +def _mmap_cache_dir() -> Path: + """ + Return the current user's cache directory for remote arrays opened with ``mmap_mode``. + + On POSIX systems the directory is ``/datajoint_mmap_``, created + with mode 0700. An existing directory is used only if it is a directory (not + a symbolic link) owned by the current user. If other users have access to + it, its permissions are reset to 0700 and its contents are removed, since + they may not have been written by the current user. If the path exists but + cannot be used, a new private directory is created for this process instead. + + Where ``os.getuid`` is unavailable (Windows), the temporary directory is + already per-user and ``/datajoint_mmap`` is used. + + Returns + ------- + Path + Directory for cached ``.npy`` files. + """ + global _fallback_mmap_cache_dir + + getuid = getattr(os, "getuid", None) + if getuid is None: + cache_dir = Path(tempfile.gettempdir()) / "datajoint_mmap" + cache_dir.mkdir(exist_ok=True) + return cache_dir + + if _fallback_mmap_cache_dir is not None and _fallback_mmap_cache_dir.is_dir(): + return _fallback_mmap_cache_dir + + uid = getuid() + cache_dir = Path(tempfile.gettempdir()) / f"datajoint_mmap_{uid}" + try: + cache_dir.mkdir(mode=0o700) + except FileExistsError: + pass + + st = os.lstat(cache_dir) + if stat.S_ISDIR(st.st_mode) and st.st_uid == uid: + if not stat.S_IMODE(st.st_mode) & 0o077: + return cache_dir + try: + os.chmod(cache_dir, 0o700) + for entry in os.scandir(cache_dir): + if entry.is_dir(follow_symlinks=False): + shutil.rmtree(entry.path) + else: + os.unlink(entry.path) + except OSError as e: + reason = f"its contents could not be removed after other users had access to it ({e})" + else: + logger.info(f"Cleared {cache_dir} and restricted it to the current user.") + return cache_dir + else: + reason = "it is not a directory owned by the current user" + + _fallback_mmap_cache_dir = Path(tempfile.mkdtemp(prefix="datajoint_mmap_")) + logger.warning(f"Not using {cache_dir} to cache arrays: {reason}. Using {_fallback_mmap_cache_dir} for this session.") + return _fallback_mmap_cache_dir + class NpyRef: """ @@ -135,7 +207,8 @@ def load(self, mmap_mode=None): For local filesystem stores, memory mapping accesses the file directly with no download. For remote stores (S3, etc.), the file is downloaded - to a local cache (``{tempdir}/datajoint_mmap/``) before memory mapping. + to a per-user local cache (``{tempdir}/datajoint_mmap_{uid}/``, or + ``{tempdir}/datajoint_mmap/`` on Windows) before memory mapping. Examples -------- @@ -165,15 +238,11 @@ def load(self, mmap_mode=None): local_path = self._backend._full_path(self.path) return np.load(local_path, mmap_mode=mmap_mode, allow_pickle=False) else: - # Remote storage - download to local cache first + # Remote storage - download to the user's local cache first import hashlib - import tempfile - from pathlib import Path path_hash = hashlib.md5(self.path.encode()).hexdigest()[:12] - cache_dir = Path(tempfile.gettempdir()) / "datajoint_mmap" - cache_dir.mkdir(exist_ok=True) - cache_path = cache_dir / f"{path_hash}.npy" + cache_path = _mmap_cache_dir() / f"{path_hash}.npy" if not cache_path.exists(): buffer = self._backend.get_buffer(self.path) diff --git a/src/datajoint/builtin_codecs/object.py b/src/datajoint/builtin_codecs/object.py index 138f8a9c2..f3201878e 100644 --- a/src/datajoint/builtin_codecs/object.py +++ b/src/datajoint/builtin_codecs/object.py @@ -111,7 +111,8 @@ def encode( # Check for pre-computed metadata (from staged insert) if isinstance(value, dict) and "path" in value: - # Already encoded, pass through + # Already encoded, pass through once the path is known to stay in the store + self._get_backend(value.get("store"), config=config)._full_path(value["path"]) return value # Determine content type and extension diff --git a/src/datajoint/condition.py b/src/datajoint/condition.py index 650015539..e9b6cdbfe 100644 --- a/src/datajoint/condition.py +++ b/src/datajoint/condition.py @@ -13,6 +13,7 @@ import inspect import json import logging +import numbers import re import uuid from dataclasses import dataclass @@ -30,6 +31,23 @@ JSON_PATTERN = re.compile(r"^(?P\w+)(\.(?P[\w.*\[\]]+))?(:(?P[\w(,\s)]+))?$") +# Return types accepted after ``:`` in a JSON attribute key, e.g. ``"attr.path:decimal(10,2)"``: +# type names understood by MySQL (``JSON_VALUE ... RETURNING``) or PostgreSQL (``::`` cast), +# with an optional length/precision, time zone qualifier, character set, and collation. +_JSON_TYPE_PATTERN = re.compile( + r"\s*(?:(?:un)?signed(?:\s+int(?:eger)?)?|int[248]?|integer|tinyint|smallint|mediumint|bigint" + r"|real|float[48]?|double(?:\s+precision)?|decimal|numeric|dec|bool(?:ean)?|bit" + r"|char(?:acter)?(?:\s+varying)?|varchar|nchar|text|binary|varbinary|bytea|jsonb?|uuid" + r"|date|datetime|year|time(?:tz)?|timestamp(?:tz)?|interval)" + r"(?:\s*\(\s*\d+\s*(?:,\s*\d+\s*)?\))?" + r"(?:\s+with(?:out)?\s+time\s+zone)?" + r"(?:\s+(?:character\s+set|charset)\s+\w+)?(?:\s+collate\s+\w+)?\s*", + re.IGNORECASE, +) + +# Text of a finite numeric value that may appear unquoted in a condition +_NUMERIC_LITERAL_PATTERN = re.compile(r"[+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?|true|false", re.IGNORECASE) + def translate_attribute(key: str, adapter=None) -> tuple[dict | None, str]: """ @@ -56,6 +74,8 @@ def translate_attribute(key: str, adapter=None) -> tuple[dict | None, str]: if match["path"] is None: return match, match["attr"] else: + if match["type"] is not None and not _JSON_TYPE_PATTERN.fullmatch(match["type"]): + raise DataJointError(f"Unsupported return type `{match['type']}` in JSON attribute `{key}`.") # Use adapter's json_path_expr if available, otherwise fall back to MySQL syntax if adapter is not None: return match, adapter.json_path_expr(match["attr"], match["path"], match["type"]) @@ -167,15 +187,13 @@ def merge(self, other: "Top") -> "Top": Top New Top with merged limit/offset and preserved ordering. """ - # Compute effective limit (minimum of defined limits) - if self.limit is None and other.limit is None: - new_limit = None - elif self.limit is None: + # other skips other.offset rows of self's window and takes up to other.limit of the + # rest, so the merged window never extends past self's limit + if self.limit is None: new_limit = other.limit - elif other.limit is None: - new_limit = self.limit else: - new_limit = min(self.limit, other.limit) + remaining = max(self.limit - other.offset, 0) + new_limit = remaining if other.limit is None else min(remaining, other.limit) return Top( limit=new_limit, @@ -335,18 +353,25 @@ def make_condition( # Get adapter for backend-agnostic SQL generation adapter = query_expression.connection.adapter + def literal(text): + """quoted string literal; % is doubled for the driver's parameter substitution""" + return adapter.quote_string(text).replace("%", "%%") + def prep_value(k, v): """prepare SQL condition""" + key = k key_match, k = translate_attribute(k, adapter) - is_json_path = key_match is not None and key_match.get("path") is not None + if key_match is None: + raise DataJointError(f"Invalid JSON path `{key}` in restriction.") + is_json_path = key_match.get("path") is not None if not is_json_path: k = adapter.quote_identifier(k) if is_json_path and isinstance(v, dict): - return f"{k}='{json.dumps(v)}'" + return f"{k}={literal(json.dumps(v))}" if v is None: return f"{k} IS NULL" - if key_match is not None and query_expression.heading[key_match["attr"]].uuid: + if query_expression.heading[key_match["attr"]].uuid: if not isinstance(v, uuid.UUID): try: v = uuid.UUID(v) @@ -363,13 +388,25 @@ def prep_value(k, v): list, ), ): - # Use single quotes for string literals (works for both MySQL and PostgreSQL) - return f"{k}='{v}'" + text = str(v) + if isinstance(v, list) and adapter.backend == "postgresql" and "\\" in text: + # An E'' literal reads backslashes the same way whether or not + # standard_conforming_strings is on. + escaped = text.replace("\\", "\\\\").replace("'", "''").replace("%", "%%") + return f"{k}=E'{escaped}'" + return f"{k}={literal(text)}" if isinstance(v, str): - # Escape single quotes by doubling them, and escape % for driver - v = v.replace("'", "''").replace("%", "%%").replace("\\", "\\\\") - return f"{k}='{v}'" - return f"{k}={v}" + if adapter.backend == "postgresql": + # Backslashes are doubled as in previous releases so that string + # restrictions keep matching the same rows. + v = v.replace("\\", "\\\\") + return f"{k}={literal(v)}" + if isinstance(v, (numbers.Number, numpy.number, numpy.bool_)): + text = f"{v}" + if _NUMERIC_LITERAL_PATTERN.fullmatch(text): + return f"{k}={text}" + raise DataJointError(f"Cannot restrict by `{key}` with the non-finite or non-real value {text}.") + raise DataJointError(f"Unsupported value of type {type(v).__name__} in restriction by `{key}`.") def combine_conditions(negate, conditions): return f"{'NOT ' if negate else ''} ({')AND('.join(conditions)})" @@ -379,6 +416,15 @@ def combine_conditions(negate, conditions): negate = not negate condition = condition.restriction + # restrict() applies dj.Top itself; here it was negated or nested in a list or AndList + if isinstance(condition, Top): + raise DataJointError( + "dj.Top must be applied on its own, as `expression & dj.Top(...)`. It cannot be negated " + "(with - or dj.Not) or combined with other restrictions in a list, an AndList, or the " + "restrictions passed to populate() or progress(). For the rows after the first n, " + "use dj.Top(None, order_by=..., offset=n)." + ) + # restrict by string if isinstance(condition, str): columns.update(extract_column_names(condition)) @@ -442,7 +488,9 @@ def combine_conditions(negate, conditions): # Match on all non-hidden namesakes (hidden attributes excluded) common_attributes = [q for q in condition.heading.names if q in query_expression.heading.names] columns.update(common_attributes) - if isinstance(condition, Aggregation): + # A dj.Top limit stays inside a subquery: it applies to the expression's rows before + # they are projected to the common attributes, and MySQL rejects LIMIT inside IN (...). + if isinstance(condition, Aggregation) or condition._top is not None: condition = condition.make_subquery() return ( # without common attributes, any non-empty set matches everything diff --git a/src/datajoint/connection.py b/src/datajoint/connection.py index 4e6252e0d..1ac607653 100644 --- a/src/datajoint/connection.py +++ b/src/datajoint/connection.py @@ -79,7 +79,10 @@ def conn( If True, reset existing connection. Default False. use_tls : bool or dict, optional TLS encryption option: True (required), False (no TLS), - None (preferred, default), or dict for manual configuration. + None (preferred, default), or dict for manual configuration + (TLS required; ``ca``, ``cert``, ``key``; with ``ca``, the server + certificate is verified). The existing connection is reconnected with + these unless it already satisfies them. Returns ------- @@ -105,6 +108,8 @@ def conn( ) use_tls = use_tls if use_tls is not None else config["database.use_tls"] conn.connection = Connection(host, user, password, None, use_tls) + else: + conn.connection._ensure_tls(use_tls) return conn.connection @@ -162,7 +167,11 @@ class Connection: port : int, optional Port number. Overridden if specified in host. use_tls : bool or dict, optional - TLS encryption option. + TLS encryption option: True (required), False (no TLS), + None (default; ``database.use_tls`` from config, and TLS if the + server supports it when that is unset), or dict for manual + configuration (TLS required; ``ca``, ``cert``, ``key``; with ``ca``, + the server certificate is verified). Attributes ---------- @@ -196,17 +205,9 @@ def __init__( if database_name is None: database_name = self._config.get("database.name") self.conn_info = dict(host=host, port=port, user=user, passwd=password, database_name=database_name) - if use_tls is not False: - # use_tls can be: None (auto-detect), True (enable), False (disable), or dict (custom config) - if isinstance(use_tls, dict): - self.conn_info["ssl"] = use_tls - elif use_tls is None: - # Auto-detect: try SSL, fallback to non-SSL if server doesn't support it - self.conn_info["ssl"] = True - else: - # use_tls=True: enable SSL with default settings - self.conn_info["ssl"] = True - self.conn_info["ssl_input"] = use_tls + if use_tls is None: + use_tls = self._config["database.use_tls"] + self._set_use_tls(use_tls) self._conn = None self._query_cache = None self._is_closed = True # Mark as closed until connect() succeeds @@ -255,7 +256,36 @@ def __repr__(self): db_str = f"/{db}" if db else "" return f"DataJoint connection ({connected}) {user}@{host}:{port}{db_str}" - def _build_connect_kwargs(self, use_tls=None): + def _set_use_tls(self, use_tls: bool | dict | None) -> None: + """Record the use_tls option in conn_info.""" + # use_tls can be: None (TLS if the server supports it), True (required), False (disabled), + # or dict (required, custom config) + self.conn_info.pop("ssl", None) + if use_tls is not False: + self.conn_info["ssl"] = use_tls if isinstance(use_tls, dict) else True + self.conn_info["ssl_input"] = use_tls + + def _ensure_tls(self, use_tls: bool | dict | None) -> None: + """ + Reconnect with ``use_tls`` unless the existing connection already satisfies it. + + ``use_tls=True`` is met by a connection made with True or a dict; + a dict is met only by a connection made with the same dict. + None and False request nothing beyond the existing connection. + """ + current = self.conn_info.get("ssl_input") + if use_tls is None or use_tls is False or current == use_tls: + return + if use_tls is True and isinstance(current, dict): + return + if self.in_transaction: + raise errors.DataJointError("Cannot change use_tls of a connection during a transaction.") + logger.info("Reconnecting with use_tls=%r (connection was made with use_tls=%r).", use_tls, current) + self.close() + self._set_use_tls(use_tls) + self.connect() + + def _build_connect_kwargs(self): """Build kwargs dict for adapter.connect().""" kwargs = dict( host=self.conn_info["host"], @@ -263,7 +293,7 @@ def _build_connect_kwargs(self, use_tls=None): user=self.conn_info["user"], password=self.conn_info["passwd"], charset=self._config["connection.charset"], - use_tls=use_tls if use_tls is not None else self.conn_info.get("ssl"), + use_tls=self.conn_info["ssl_input"], ) if self.conn_info.get("database_name"): kwargs["dbname"] = self.conn_info["database_name"] @@ -273,19 +303,9 @@ def connect(self) -> None: """Establish or re-establish connection to the database server.""" with warnings.catch_warnings(): warnings.filterwarnings("ignore", ".*deprecated.*") - try: - self._conn = self.adapter.connect(**self._build_connect_kwargs()) - except Exception as ssl_error: - # If SSL fails, retry without SSL (if it was auto-detected) - if self.conn_info.get("ssl_input") is None: - logger.warning( - "SSL connection failed (%s). Falling back to non-SSL connection. " - "To require SSL, set use_tls=True explicitly.", - ssl_error, - ) - self._conn = self.adapter.connect(**self._build_connect_kwargs(use_tls=False)) - else: - raise + # With use_tls=None, the adapter uses TLS if the server supports it and + # continues without TLS otherwise; it does not retry after other errors. + self._conn = self.adapter.connect(**self._build_connect_kwargs()) self._is_closed = False # Mark as connected after successful connection def set_query_cache(self, query_cache: str | None = None) -> None: diff --git a/src/datajoint/declare.py b/src/datajoint/declare.py index 438bb72b0..87cef4619 100644 --- a/src/datajoint/declare.py +++ b/src/datajoint/declare.py @@ -7,6 +7,7 @@ from __future__ import annotations +import ast import logging import re @@ -172,6 +173,211 @@ def build_attribute_parser() -> pp.ParserElement: foreign_key_parser = build_foreign_key_parser() attribute_parser = build_attribute_parser() +_REFERENCE_TOKEN = re.compile( + r"""\s*(?: + (?P\#.*) + | (?P[^\W\d]\w*) + | (?P"(?:[^"\\\n]|\\.)*"|'(?:[^'\\\n]|\\.)*') + | (?P[.(),=]) + )""", + re.VERBOSE, +) + +_REFERENCE_FORMS = ( + "use a table name such as Parent, module.Parent or Master.Part, " + "optionally projected with Parent.proj(new_name='old_name')" +) + + +def _tokenize_reference(text: str) -> list[tuple[str, str]]: + """Split a foreign key reference into (kind, value) tokens, dropping a trailing comment.""" + tokens = [] + pos = 0 + while pos < len(text): + match = _REFERENCE_TOKEN.match(text, pos) + if match is None: + if text[pos:].strip(): + raise ValueError(f"unexpected text {text[pos:].strip()!r}") + break + pos = match.end() + kind = match.lastgroup + value = match.group(kind) + if kind == "comment": + break + if kind == "name" and not value.isidentifier(): + raise ValueError(f"{value!r} is not a name") + if kind == "string": + value = ast.literal_eval(value) + tokens.append((kind, value)) + return tokens + + +def parse_foreign_key_reference(text: str) -> list[tuple]: + """ + Parse the table reference of a foreign key line into lookup steps. + + The supported forms are a dotted name (``Parent``, ``module.Parent``, + ``Master.Part``), optionally in parentheses, instantiated with ``()``, or + projected with ``.proj(...)`` whose arguments are string literals. The + text is only parsed; nothing in it is evaluated. + + Parameters + ---------- + text : str + The reference, e.g. ``"Parent.proj(new_id='parent_id')"``. + + Returns + ------- + list[tuple] + Steps ``("name", name)``, ``("attr", name)``, ``("instance",)`` and + ``("proj", args, kwargs)``, applied in order by + :func:`resolve_foreign_key_reference`. + + Raises + ------ + ValueError + If the text is not one of the supported forms. + """ + tokens = _tokenize_reference(text) + pos = 0 + + def peek(value=None): + if pos >= len(tokens): + return False + return value is None or tokens[pos] == ("punct", value) + + def expect(kind, value=None): + nonlocal pos + if pos >= len(tokens) or tokens[pos][0] != kind or (value is not None and tokens[pos][1] != value): + found = repr(tokens[pos][1]) if pos < len(tokens) else "end of line" + raise ValueError(f"expected {value or kind}, found {found}") + pos += 1 + return tokens[pos - 1][1] + + def arguments(): + args, kwargs = [], {} + while not peek(")"): + if pos + 1 < len(tokens) and tokens[pos][0] == "name" and tokens[pos + 1] == ("punct", "="): + key = expect("name") + expect("punct", "=") + if key in kwargs: + raise ValueError(f"repeated argument {key!r}") + kwargs[key] = expect("string") + elif kwargs: + raise ValueError("positional argument follows keyword argument") + else: + args.append(expect("string")) + if not peek(")"): + expect("punct", ",") + expect("punct", ")") + return args, kwargs + + def reference(): + nonlocal pos + if peek("("): + pos += 1 + steps = reference() + expect("punct", ")") + else: + name = expect("name") + if name.startswith("__"): + raise ValueError(f"name {name!r} is not a table") + steps = [("name", name)] + while peek("(") or peek("."): + if peek("."): + pos += 1 + attr = expect("name") + if attr.startswith("__"): + raise ValueError(f"attribute {attr!r} is not a table") + if attr == "proj" and peek("("): + pos += 1 + steps.append(("proj", *arguments())) + else: + steps.append(("attr", attr)) + else: + pos += 1 + expect("punct", ")") + steps.append(("instance",)) + return steps + + steps = reference() + if pos < len(tokens): + raise ValueError(f"unexpected {tokens[pos][1]!r}") + return steps + + +def resolve_foreign_key_reference(ref_table: str, context: dict): + """ + Resolve the table reference of a foreign key line in a namespace. + + The reference is parsed by :func:`parse_foreign_key_reference`, never + evaluated: names are looked up in ``context`` attribute by attribute, a + table class may be instantiated with ``()``, and ``.proj(...)`` is called + with the parsed string arguments. + + Parameters + ---------- + ref_table : str + The reference, e.g. ``"Parent"``, ``"Master.Part"`` or + ``"Parent.proj(new_id='parent_id')"``. + context : dict + Namespace containing referenced table objects. + + Returns + ------- + object + The referenced table class, table, or projection. + + Raises + ------ + DataJointError + If the reference is not of a supported form or cannot be resolved. + """ + from .expression import QueryExpression + from .table import Table + + text = ref_table.strip() + + def unresolved(reason): + return DataJointError(f"Foreign key reference {text} could not be resolved: {reason}") + + def is_table_class(obj): + return isinstance(obj, type) and issubclass(obj, Table) + + try: + steps = parse_foreign_key_reference(text) + except ValueError as error: + raise unresolved(f"{error}; {_REFERENCE_FORMS}") from None + ref = None + for step in steps: + if step[0] == "name": + if step[1] not in context: + raise unresolved(f"{step[1]} is not defined in the declaration context") + ref = context[step[1]] + elif step[0] == "attr": + try: + ref = getattr(ref, step[1]) + except Exception: + raise unresolved(f"no attribute {step[1]}") from None + elif step[0] == "instance": + if not is_table_class(ref): + raise unresolved(f"only a table class can be instantiated; {_REFERENCE_FORMS}") + ref = ref() + else: # proj + if is_table_class(ref): + ref = ref() + if not isinstance(ref, QueryExpression): + raise unresolved("only a table can be projected") + try: + ref = ref.proj(*step[1], **step[2]) + except DataJointError: + raise + except Exception as error: + raise unresolved(str(error)) from None + if not (isinstance(ref, QueryExpression) or is_table_class(ref)): + raise unresolved("it does not name a table") + return ref + def is_foreign_key(line: str) -> bool: """ @@ -254,10 +460,7 @@ def compile_foreign_key( except pp.ParseException as err: raise DataJointError('Parsing error in line "%s". %s.' % (line, err)) - try: - ref = eval(result.ref_table, context) - except Exception: - raise DataJointError("Foreign key reference %s could not be resolved" % result.ref_table) + ref = resolve_foreign_key_reference(result.ref_table, context) options = [opt.upper() for opt in result.options] for opt in options: # check for invalid options diff --git a/src/datajoint/diagram.py b/src/datajoint/diagram.py index d3d7c40bc..598d36d51 100644 --- a/src/datajoint/diagram.py +++ b/src/datajoint/diagram.py @@ -799,8 +799,9 @@ def restrict(self, table_expr): if node not in result.nodes(): raise DataJointError(f"Table {node} is not in the diagram.") # Seed restriction (AND accumulation) - result._restrict_conditions.setdefault(node, AndList()).extend(table_expr.restriction) - result._restriction_attrs.setdefault(node, set()).update(table_expr.restriction_attributes) + restriction, restriction_attrs = _seed_restriction(table_expr) + result._restrict_conditions.setdefault(node, AndList()).extend(restriction) + result._restriction_attrs.setdefault(node, set()).update(restriction_attrs) # Propagate downstream result._propagate_restrictions(node, mode="restrict") return result diff --git a/src/datajoint/expression.py b/src/datajoint/expression.py index 1b5f5ac9e..ca2b9be1b 100644 --- a/src/datajoint/expression.py +++ b/src/datajoint/expression.py @@ -400,18 +400,21 @@ def join(self, other, semantic_check=True, left=False, allow_nullable_pk=False): need_subquery1 = need_subquery2 = bool( (set(self.original_heading.names) & set(other.original_heading.names)) - join_attributes ) - # need subquery if any of the join attributes are derived + # need subquery if any of the join attributes are derived, or if an operand is limited + # by dj.Top: its ORDER BY/LIMIT must apply to the operand before the join need_subquery1 = ( need_subquery1 or isinstance(self, Aggregation) or any(n in self.heading.new_attributes for n in join_attributes) or isinstance(self, Union) + or self._top is not None ) need_subquery2 = ( need_subquery2 or isinstance(other, Aggregation) or any(n in other.heading.new_attributes for n in join_attributes) or isinstance(self, Union) + or other._top is not None ) # With USING clause (instead of NATURAL JOIN), we need subqueries when # joining with multi-table expressions to ensure correct column matching @@ -419,6 +422,11 @@ def join(self, other, semantic_check=True, left=False, allow_nullable_pk=False): need_subquery1 = True if len(other.support) > 1 and join_attributes: need_subquery2 = True + # A left join keeps every row of self, so a restriction on other (including dj.Top) + # must be applied before the join, inside a subquery. In the outer WHERE it would + # remove the rows of self that have no match. An unrestricted other needs no subquery. + if left and (other.restriction or other._top): + need_subquery2 = True if need_subquery1: self = self.make_subquery() if need_subquery2: @@ -578,7 +586,7 @@ def proj(self, *attributes, **named_attributes): # check that all mentioned names are present in heading mentions = attributes.union(replicate_map.values()).union(rename_map.values()) try: - raise DataJointError("Attribute '%s' not found." % next(a for a in mentions if not self.heading.names)) + raise DataJointError("Attribute `%s` not found." % next(a for a in mentions if a not in self.heading.names)) except StopIteration: pass # all ok @@ -614,6 +622,22 @@ def proj(self, *attributes, **named_attributes): if not need_subquery and self.restriction: # need a subquery if the restriction applies to attributes that have been renamed need_subquery = any(name in self.restriction_attributes for name in self.heading.new_attributes) + if not need_subquery and self._top is not None: + # need a subquery if dj.Top's ORDER BY names an attribute that the projection redefines, + # or a computed or renamed attribute that it drops. A dropped table column needs none. + projected = self.heading.select( + attributes, rename_map=dict(**rename_map, **replicate_map), compute_map=compute_map + ) + ordering = ", ".join(_flatten_attribute_list(self.primary_key, self._top.order_by or ["KEY"])) + need_subquery = any( + ( + projected[name].attribute_expression != self.heading[name].attribute_expression + if name in projected.names + else self.heading[name].attribute_expression is not None + ) + for name in extract_column_names(ordering) + if name in self.heading.names + ) result = self.make_subquery() if need_subquery else copy.copy(self) result._original_heading = result.original_heading @@ -1186,6 +1210,8 @@ def __bool__(self): bool True if the result is not empty. """ + if self._top is not None: + return bool(self.make_subquery()) # EXISTS must see the ORDER BY/LIMIT return bool( self.connection.query( "SELECT EXISTS(SELECT 1 FROM {from_}{where})".format(from_=self.from_clause(), where=self.where_clause()) @@ -1434,15 +1460,17 @@ def make_sql(self): if not arg1.heading.secondary_attributes and not arg2.heading.secondary_attributes: # no secondary attributes: use UNION DISTINCT fields = arg1.primary_key - alias_name = f"_u{next(self.__count)}{self.sorting_clauses()}" - alias_quoted = self.connection.adapter.quote_identifier(alias_name) + alias_quoted = self.connection.adapter.quote_identifier(f"_u{next(self.__count)}") sql1 = arg1.make_sql() if isinstance(arg1, Union) else arg1.make_sql(fields) sql2 = arg2.make_sql() if isinstance(arg2, Union) else arg2.make_sql(fields) - return f"SELECT * FROM (({sql1}) UNION ({sql2})) as {alias_quoted}" + return f"SELECT * FROM (({sql1}) UNION ({sql2})) as {alias_quoted}{self.sorting_clauses()}" # with secondary attributes, use union of left join with anti-restriction fields = self.heading.names sql1 = arg1.join(arg2, left=True).make_sql(fields) sql2 = (arg2 - arg1).proj(..., **{k: "NULL" for k in arg1.heading.secondary_attributes}).make_sql(fields) + if self._top is not None: + alias_quoted = self.connection.adapter.quote_identifier(f"_u{next(self.__count)}") + return f"SELECT * FROM (({sql1}) UNION ({sql2})) as {alias_quoted}{self.sorting_clauses()}" return "({sql1}) UNION ({sql2})".format(sql1=sql1, sql2=sql2) def from_clause(self): @@ -1509,6 +1537,8 @@ def __and__(self, other): other = other() # instantiate if a class if not isinstance(other, QueryExpression): raise DataJointError("Set U can only be restricted with a QueryExpression.") + if other._top is not None: + other = other.make_subquery() # apply the limit before DISTINCT result = copy.copy(other) result._distinct = True result._heading = result.heading.set_primary_key(self.primary_key) @@ -1563,6 +1593,9 @@ def aggr(self, group, **named_attributes): if missing: raise DataJointError(f"Attributes {missing} not found in the group expression.") + if group._top is not None: + group = group.make_subquery() # apply the limit before GROUP BY + # Create Aggregation directly without join - just group by U's primary key result = Aggregation() result._connection = group.connection diff --git a/src/datajoint/heading.py b/src/datajoint/heading.py index 9addae474..a841bf970 100644 --- a/src/datajoint/heading.py +++ b/src/datajoint/heading.py @@ -765,6 +765,7 @@ def set_primary_key(self, primary_key): (dict(self.attributes[name].todict(), in_key=True) for name in primary_key), (dict(self.attributes[name].todict(), in_key=False) for name in self.names if name not in primary_key), ), + table_info=self.table_info, lineage_available=self._lineage_available, ) @@ -775,5 +776,6 @@ def make_subquery_heading(self): """ return Heading( (dict(v.todict(), attribute_expression=None) for v in self.attributes.values()), + table_info=self.table_info, # keep the adapter, so a later rename quotes for the backend lineage_available=self._lineage_available, ) diff --git a/src/datajoint/instance.py b/src/datajoint/instance.py index 455336a7c..eb3c3f6d0 100644 --- a/src/datajoint/instance.py +++ b/src/datajoint/instance.py @@ -56,7 +56,8 @@ class Instance: port : int, optional Database port. Defaults to 3306 for MySQL, 5432 for PostgreSQL. use_tls : bool or dict, optional - TLS configuration. + TLS configuration. Default from ``database.use_tls`` in this + instance's config. backend : str, optional Database backend: ``"mysql"`` or ``"postgresql"``. Default from config. **kwargs : Any diff --git a/src/datajoint/objectref.py b/src/datajoint/objectref.py index c312e0c5d..dd060f5f0 100644 --- a/src/datajoint/objectref.py +++ b/src/datajoint/objectref.py @@ -7,6 +7,7 @@ """ import json +import re from dataclasses import dataclass from datetime import datetime from pathlib import Path @@ -17,6 +18,7 @@ from .errors import DataJointError from .hash_registry import compute_hash from .storage import StorageBackend +from .utils import is_plain_file_name class IntegrityError(DataJointError): @@ -169,20 +171,20 @@ def full_path(self) -> str: Return full URI (e.g., 's3://bucket/path'). This is the complete path including protocol and bucket/location. + + Raises + ------ + DataJointError + If the stored path leads outside the store location. """ self._ensure_backend() + if getattr(self._backend, "confine_paths", False): + self._backend._check_confined(self.path) protocol = self._backend.protocol if protocol == "file": return str(Path(self._backend.spec.get("location", "")) / self.path) - elif protocol == "s3": - bucket = self._backend.spec["bucket"] - return f"s3://{bucket}/{self.path}" - elif protocol == "gcs": - bucket = self._backend.spec["bucket"] - return f"gs://{bucket}/{self.path}" - elif protocol == "azure": - container = self._backend.spec["container"] - return f"az://{container}/{self.path}" + elif protocol in ("s3", "gcs", "azure"): + return self._backend.get_url(self.path) else: return self.path @@ -285,6 +287,13 @@ def download(self, destination: Path | str, subpath: str | None = None) -> Path: ------- Path Path to downloaded file/directory. + + Raises + ------ + DataJointError + If ``destination`` is a directory and the last component of the + stored path is not a plain file name, or if a key inside a folder + object is not made of plain file names. """ self._ensure_backend() destination = Path(destination) @@ -299,12 +308,44 @@ def download(self, destination: Path | str, subpath: str | None = None) -> Path: if self.is_dir and not subpath: # Download entire directory destination.mkdir(parents=True, exist_ok=True) + fs = self._backend.fs full_path = self._backend._full_path(remote_path) - self._backend.fs.get(full_path, str(destination), recursive=True) + root = fs._strip_protocol(full_path).rstrip("/") + # Same layout as fsspec's recursive get: destination//... + name = root.rsplit("/", 1)[-1] + target = destination / name + # Check every key before writing anything: each must be made of plain + # names below the object, so that no file lands outside target + entries = fs.find(full_path, withdirs=True, detail=True) + if not entries: + raise FileNotFoundError(full_path) + rpaths, lpaths, ldirs = [], [], [] + for rpath, info in entries.items(): + key = rpath.rstrip("/") + if key == root: + continue # the object itself + rel = key[len(root) + 1 :] if key.startswith(root + "/") else "" + parts = rel.split("/") + if not all(is_plain_file_name(p) for p in [name, *parts]): + raise DataJointError(f"Cannot download {remote_path!r}: entry {rpath!r} leads outside the destination.") + if info["type"] == "directory": + ldirs.append(target.joinpath(*parts)) + else: + rpaths.append(rpath) + lpaths.append(str(target.joinpath(*parts))) + target.mkdir(exist_ok=True) + for ldir in ldirs: + ldir.mkdir(parents=True, exist_ok=True) + for lpath in lpaths: + Path(lpath).parent.mkdir(parents=True, exist_ok=True) + if rpaths: + fs.get(rpaths, lpaths) else: # Download single file if destination.is_dir(): - filename = remote_path.split("/")[-1] + filename = re.split(r"[\\/]", remote_path)[-1] + if not is_plain_file_name(filename): + raise DataJointError(f"Cannot download {remote_path!r}: {filename!r} is not a plain file name.") destination = destination / filename destination.parent.mkdir(parents=True, exist_ok=True) self._backend.get_file(remote_path, destination) diff --git a/src/datajoint/settings.py b/src/datajoint/settings.py index 0929f301d..981bbc314 100644 --- a/src/datajoint/settings.py +++ b/src/datajoint/settings.py @@ -16,6 +16,15 @@ ``datajoint.json`` takes precedence over ``.secrets/``: the secrets directory only supplies values the config file and environment leave unset. +The search for ``datajoint.json`` and ``.secrets/`` skips, with a warning, a +file or directory owned by another user (other than root) that anyone on the +machine could have placed there: one in a world-writable directory such as +``/tmp``, or below a world-writable directory that lacks the sticky bit. Files +in a shared project directory (e.g. a group directory under a sticky +``/scratch``) are still used. To use a skipped file, name it explicitly: +``dj.config.load(path)`` or the ``DJ_CONFIG_FILE`` environment variable. +``DJ_IGNORE_CONFIG_FILE=true`` turns the search off. + Examples -------- >>> import datajoint as dj @@ -47,11 +56,12 @@ import json import logging import os +import stat import warnings from contextlib import contextmanager from enum import Enum from pathlib import Path -from typing import Any, Iterator, Literal +from typing import Any, Iterable, Iterator, Literal from pydantic import Field, SecretStr, field_validator, model_validator from pydantic_settings import BaseSettings, SettingsConfigDict @@ -61,6 +71,7 @@ CONFIG_FILENAME = "datajoint.json" SECRETS_DIRNAME = ".secrets" SYSTEM_SECRETS_DIR = Path("/run/secrets/datajoint") +CONFIG_FILE_ENV_VAR = "DJ_CONFIG_FILE" DEFAULT_SUBFOLDING = (2, 2) # Mapping of config keys to environment variables @@ -93,41 +104,203 @@ logger = logging.getLogger(__name__.split(".")[0]) -def find_config_file(start: Path | None = None) -> Path | None: +_SECRETS_HINT = " Supply its values through environment variables instead." +_CONFIG_HINT = " To use it, pass its path to dj.config.load() or set " + CONFIG_FILE_ENV_VAR + "." + + +def _is_foreign(uid: int) -> bool: + """True if ``uid`` is neither the current user nor root.""" + return uid not in (os.getuid(), 0) + + +def _open_location(directory: Path) -> Path | None: """ - Search for datajoint.json in current and parent directories. + Find a directory that lets any user create or replace entries in ``directory``. - Searches upward from ``start`` until finding the config file or hitting - a project boundary (``.git``, ``.hg``) or filesystem root. + That is ``directory`` itself if it is world-writable (sticky or not), or an + ancestor that is world-writable without the sticky bit. A world-writable + ancestor with the sticky bit (``/tmp``, ``/scratch``) does not count: other + users cannot rename or remove the entries below it that they do not own. + + Returns + ------- + Path or None + The directory that makes the location writable by all users, or None. + """ + for location in (directory, *directory.parents): + try: + mode = os.stat(location).st_mode + except OSError: + continue + if mode & stat.S_IWOTH and (location == directory or not mode & stat.S_ISVTX): + return location + return None + + +def _reject_foreign(path: Path, uid: int, directories: Iterable[Path], hint: str) -> bool: + """ + Decide whether a path owned by another user is ignored, and say so if it is. + + The path is ignored if any of ``directories`` (where it was found, and + where it resolves to) is a location any user can write + (see ``_open_location``). + """ + for directory in dict.fromkeys(directories): + location = _open_location(directory) + if location is not None: + logger.warning( + f"Ignoring {path}: it is owned by another user (uid {uid}) and {location} is writable by all users.{hint}" + ) + return True + return False + + +def _read_found_file(path: Path, hint: str = "") -> str | None: + """ + Read a config or secret file found by searching, if it may be used. + + A file owned by the current user or by root is read. A file owned by another + user is read only if the directory it was found in, or the one it resolves + to, is not a location any user can write (see ``_open_location``); a shared + project directory qualifies, ``/tmp`` does not. A symbolic link owned by + another user is judged the same way. The ownership check uses the open file + descriptor, and the contents are read from that descriptor. A world-writable + file that is read produces a warning. + + Platforms without POSIX ownership (``os.getuid`` absent, e.g. Windows) read + every file. Parameters ---------- - start : Path, optional - Directory to start search from. Defaults to current working directory. + path : Path + File found by the search. + hint : str, optional + Advice appended to the warning when the file is ignored. Returns ------- - Path or None - Path to config file if found, None otherwise. + str or None + File contents, or None if the file is missing, not a regular file, or + ignored. + """ + if not hasattr(os, "getuid"): + try: + return path.read_text() + except OSError: + return None + + found_in = path.absolute().parent + try: + link_st = os.lstat(path) + except OSError: + return None + if stat.S_ISLNK(link_st.st_mode) and _is_foreign(link_st.st_uid): + if _reject_foreign(path, link_st.st_uid, [found_in], hint): + return None + + resolved = Path(os.path.realpath(path)) + flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0) + try: + fd = os.open(resolved, flags) + except FileNotFoundError: + return None + except OSError as e: + logger.warning(f"Could not read {path}: {e}") + return None + with os.fdopen(fd) as f: + st = os.fstat(f.fileno()) + if not stat.S_ISREG(st.st_mode): + return None + if _is_foreign(st.st_uid) and _reject_foreign(path, st.st_uid, [found_in, resolved.parent], hint): + return None + if st.st_mode & stat.S_IWOTH: + logger.warning(f"{path} is writable by all users; restrict its permissions (e.g. chmod o-w).") + return f.read() + + +def _use_found_dir(path: Path, hint: str = "") -> bool: + """ + Decide whether a secrets directory found by searching may be used. + + The rules of ``_read_found_file`` apply to the directory. The files in a + directory that is used are each checked again when read. For that reason a + world-writable directory with the sticky bit (such as a Kubernetes secret + volume) produces no warning; one without it does. + """ + if not hasattr(os, "getuid"): + return path.is_dir() + found_in = path.absolute().parent + try: + link_st = os.lstat(path) + st = os.stat(path) + except OSError: + return False + if not stat.S_ISDIR(st.st_mode): + return False + if stat.S_ISLNK(link_st.st_mode) and _is_foreign(link_st.st_uid): + if _reject_foreign(path, link_st.st_uid, [found_in], hint): + return False + if _is_foreign(st.st_uid): + if _reject_foreign(path, st.st_uid, [found_in, Path(os.path.realpath(path)).parent], hint): + return False + if st.st_mode & stat.S_IWOTH and not st.st_mode & stat.S_ISVTX: + logger.warning(f"{path} is writable by all users; restrict its permissions (e.g. chmod o-w).") + return True + + +def _search_config_file(start: Path | None = None) -> tuple[Path | None, str | None]: + """ + Search for datajoint.json and read it. + + Returns + ------- + tuple + ``(path, text)``: ``(None, None)`` if no file was found, ``(path, None)`` + if the file found was ignored (see ``_read_found_file``), otherwise the + path and its contents. """ current = (start or Path.cwd()).resolve() while True: config_path = current / CONFIG_FILENAME if config_path.is_file(): - return config_path + return config_path, _read_found_file(config_path, _CONFIG_HINT) # Stop at project/repo root if (current / ".git").exists() or (current / ".hg").exists(): - return None + return None, None # Stop at filesystem root if current == current.parent: - return None + return None, None current = current.parent +def find_config_file(start: Path | None = None) -> Path | None: + """ + Search for datajoint.json in current and parent directories. + + Searches upward from ``start`` until finding the config file or hitting + a project boundary (``.git``, ``.hg``) or filesystem root. A file that + another user could have placed there ends the search without a result: + one owned by another user (not root) in a world-writable directory such as + ``/tmp``, or below a world-writable directory without the sticky bit. + + Parameters + ---------- + start : Path, optional + Directory to start search from. Defaults to current working directory. + + Returns + ------- + Path or None + Path to config file if found, None otherwise. + """ + config_path, text = _search_config_file(start) + return config_path if text is not None else None + + def find_secrets_dir(config_path: Path | None = None) -> Path | None: """ Find the secrets directory. @@ -137,6 +310,9 @@ def find_secrets_dir(config_path: Path | None = None) -> Path | None: 1. ``.secrets/`` in same directory as datajoint.json (project secrets) 2. ``/run/secrets/datajoint/`` (Docker/Kubernetes secrets) + A directory that another user could have placed there is not used, under + the same rule as ``find_config_file``. + Parameters ---------- config_path : Path, optional @@ -150,12 +326,12 @@ def find_secrets_dir(config_path: Path | None = None) -> Path | None: # Check project secrets directory (next to config file) if config_path is not None: project_secrets = config_path.parent / SECRETS_DIRNAME - if project_secrets.is_dir(): + if project_secrets.is_dir() and _use_found_dir(project_secrets, _SECRETS_HINT): return project_secrets # Check system secrets directory (Docker/Kubernetes) if SYSTEM_SECRETS_DIR.is_dir(): - return SYSTEM_SECRETS_DIR + return SYSTEM_SECRETS_DIR if _use_found_dir(SYSTEM_SECRETS_DIR, _SECRETS_HINT) else None return None @@ -164,6 +340,9 @@ def read_secret_file(secrets_dir: Path | None, name: str) -> str | None: """ Read a secret value from a file in the secrets directory. + A file that another user could have placed there is ignored, under the + same rule as ``find_config_file``. + Parameters ---------- secrets_dir : Path or None @@ -179,11 +358,8 @@ def read_secret_file(secrets_dir: Path | None, name: str) -> str | None: if secrets_dir is None: return None - secret_path = secrets_dir / name - if secret_path.is_file(): - return secret_path.read_text().strip() - - return None + value = _read_found_file(secrets_dir / name, _SECRETS_HINT) + return value.strip() if value is not None else None class DatabaseSettings(BaseSettings): @@ -444,6 +620,15 @@ class Config(BaseSettings): # Download path for attachments and filepaths download_path: str = "." + allow_filepath_outside_store: bool = Field( + default=False, + description="If True, values may point outside the store location " + "(absolute paths outside a file store's location, or paths with '..' components). " + "By default such paths are rejected on insert and on access. Enable only for " + "trusted data whose references deliberately point elsewhere, such as rows " + "migrated from DataJoint 0.14. Set via DJ_ALLOW_FILEPATH_OUTSIDE_STORE.", + ) + # Internal: track where config was loaded from _config_path: Path | None = None _secrets_dir: Path | None = None @@ -749,12 +934,15 @@ def load(self, filename: str | Path) -> None: if not filepath.exists(): raise FileNotFoundError(f"Config file not found: {filepath}") - logger.info(f"Loading configuration from {filepath.absolute()}") - with open(filepath) as f: - data = json.load(f) + text = f.read() + + self._load_text(text, filepath) - self._update_from_flat_dict(data) + def _load_text(self, text: str, filepath: Path) -> None: + """Apply the JSON settings in ``text``, read from ``filepath``.""" + logger.info(f"Loading configuration from {filepath.absolute()}") + self._update_from_flat_dict(json.loads(text)) self._config_path = filepath def _update_from_flat_dict(self, data: dict[str, Any]) -> None: @@ -842,8 +1030,11 @@ def _load_secrets(self, secrets_dir: Path) -> None: parts = secret_file.name.split(".") if len(parts) == 3 and parts[0] == "stores": + text = _read_found_file(secret_file, _SECRETS_HINT) + if text is None: + continue store_name, attr = parts[1], parts[2] - value = secret_file.read_text().strip() + value = text.strip() # Initialize store dict if needed if store_name not in self.stores: self.stores[store_name] = {} @@ -1131,12 +1322,24 @@ def _create_config() -> Config: config_path: Path | None = None if not cfg.ignore_config_file: - config_path = find_config_file() - if config_path is not None: + # DJ_CONFIG_FILE names the config file explicitly; it is used as given, + # like dj.config.load(), without searching. + explicit_path = os.environ.get(CONFIG_FILE_ENV_VAR) + if explicit_path: + config_path = Path(explicit_path).expanduser() + if not config_path.is_file(): + raise FileNotFoundError(f"{CONFIG_FILE_ENV_VAR} is set to {explicit_path!r}, which is not a file.") + text: str | None = config_path.read_text() + else: + config_path, text = _search_config_file() + if text is not None and config_path is not None: try: - cfg.load(config_path) + cfg._load_text(text, config_path) except Exception as e: warnings.warn(f"Failed to load config from {config_path}: {e}") + elif config_path is not None: + # The file found was not read; _read_found_file logged why. + config_path = None else: warnings.warn( f"No {CONFIG_FILENAME} found. Using defaults and environment variables. " diff --git a/src/datajoint/storage.py b/src/datajoint/storage.py index 51e1d80cd..60c03ad36 100644 --- a/src/datajoint/storage.py +++ b/src/datajoint/storage.py @@ -9,6 +9,9 @@ import json import logging +import os +import posixpath +import re import secrets import urllib.parse from datetime import datetime, timezone @@ -16,6 +19,7 @@ from typing import Any import fsspec +from fsspec.implementations.local import LocalFileSystem from . import errors @@ -45,6 +49,45 @@ def is_url(path: str) -> bool: return path.lower().startswith(URL_PROTOCOLS) +def _has_parent_reference(path: str) -> bool: + """ + Check whether a path has a ``..`` component. + + Both ``/`` and ``\\`` count as separators so the result does not depend on the + platform. + """ + return ".." in re.split(r"[\\/]", path) + + +def path_in_location(location: str, path: str) -> str | None: + """ + Express an absolute local path inside ``location`` relative to it. + + The comparison is lexical: symbolic links are not resolved. + + Parameters + ---------- + location : str + Local directory (a ``file`` store's location). + path : str + Path to express relative to ``location``. + + Returns + ------- + str or None + The path relative to ``location`` with POSIX separators, or None if + ``path`` is not absolute, has ``..`` components, or lies outside + ``location``. + """ + if not Path(path).anchor or _has_parent_reference(path): + return None + root = Path(os.path.abspath(location or ".")) + try: + return Path(os.path.abspath(path)).relative_to(root).as_posix() + except ValueError: + return None + + def _path_to_file_url(resolved_path: Path | PurePosixPath) -> str: """ Convert an already-resolved absolute path to a ``file://`` URL. @@ -309,8 +352,14 @@ class StorageBackend: Storage configuration dictionary. protocol : str Storage protocol (``'file'``, ``'s3'``, ``'gcs'``, ``'azure'``). + confine_paths : bool + If True (default), paths passed to the backend must stay inside the + store location: paths with ``..`` components and, for ``file`` stores, + absolute paths outside the location are rejected. """ + confine_paths: bool = True + def __init__(self, spec: dict[str, Any]) -> None: """ Initialize storage backend from configuration spec. @@ -352,8 +401,7 @@ def _validate_spec(self): # with a clear message. if bool(self.spec.get("access_key")) != bool(self.spec.get("secret_key")): raise errors.DataJointError( - "Incomplete S3 credentials: set both access_key and secret_key, " - "or neither to use ambient AWS credentials." + "Incomplete S3 credentials: set both access_key and secret_key, or neither to use ambient AWS credentials." ) @property @@ -429,8 +477,16 @@ def _full_path(self, path: str | PurePosixPath) -> str: ------- str Full path suitable for fsspec operations. + + Raises + ------ + DataJointError + If ``confine_paths`` is set and the path leads outside the store + location. """ path = str(path) + if self.confine_paths: + self._check_confined(path) if self.protocol == "s3": bucket = self.spec["bucket"] location = self.spec.get("location", "") @@ -445,12 +501,43 @@ def _full_path(self, path: str | PurePosixPath) -> str: return f"{bucket}/{path}" elif self.protocol == "file": location = self.spec.get("location", "") - if location: - return (Path(location) / path).as_posix() - return path + full = (Path(location) / path).as_posix() if location else path + # A location of "" or "." adds no prefix, and fsspec reads a leading "file:" or + # "local:" as a protocol and expands "~", so compare where fsspec resolves both. + # fsspec before 2024 leaves "." segments in place, so normalize both sides + if self.confine_paths: + root = posixpath.normpath(LocalFileSystem._strip_protocol(Path(location or ".").as_posix())).rstrip("/") + resolved = posixpath.normpath(LocalFileSystem._strip_protocol(full)) + if resolved != root and not resolved.startswith(root + "/"): + raise self._confinement_error(path) + return full else: return self._require_adapter().full_path(self.spec, path) + def _check_confined(self, path: str) -> None: + """Raise if ``path`` does not stay inside the store location.""" + if ( + "\x00" in path + or _has_parent_reference(path) + or (self.protocol == "file" and Path(path).anchor and self._path_in_location(path) is None) + ): + raise self._confinement_error(path) + + @staticmethod + def _confinement_error(path: str) -> errors.DataJointError: + return errors.DataJointError( + f"Path {path!r} may lead outside the store location. Use a path relative to the " + "store location, without '..' components. ( only: " + "dj.config.allow_filepath_outside_store = True accepts such paths for every " + "value; use it only with trusted data.)" + ) + + def _path_in_location(self, path: str) -> str | None: + """Express an absolute path inside a ``file`` store's location relative to it (see :func:`path_in_location`).""" + if self.protocol != "file": + return None + return path_in_location(self.spec.get("location", ""), path) + def get_url(self, path: str | PurePosixPath) -> str: """ Get the full URL for a path in storage. diff --git a/src/datajoint/table.py b/src/datajoint/table.py index 2c8a4adaa..dd6e979f8 100644 --- a/src/datajoint/table.py +++ b/src/datajoint/table.py @@ -5,6 +5,7 @@ import itertools import json import logging +import re import uuid import warnings from dataclasses import dataclass, field @@ -1371,7 +1372,8 @@ def describe(self, context=None, printout=False): self.connection.dependencies.load() parents = self.parents(foreign_key_info=True) in_key = True - definition = "# " + self.heading.table_status["comment"] + "\n" if self.heading.table_status["comment"] else "" + table_comment = _one_line(self.heading.table_status["comment"]) + definition = "# " + table_comment + "\n" if table_comment else "" attributes_thus_far = set() attributes_declared = set() indexes = self.heading.indexes.copy() if self.heading.indexes else {} @@ -1408,15 +1410,17 @@ def describe(self, context=None, printout=False): # simple foreign key definition += "->{options} {class_name}\n".format( options=options_str, - class_name=lookup_class_name(parent_name, context) or parent_name, + class_name=_one_line(lookup_class_name(parent_name, context) or parent_name), ) else: # projected foreign key definition += "->{options} {class_name}.proj({proj_list})\n".format( options=options_str, - class_name=lookup_class_name(parent_name, context) or parent_name, + class_name=_one_line(lookup_class_name(parent_name, context) or parent_name), proj_list=",".join( - '{}="{}"'.format(attr, ref) for attr, ref in fk_props["attr_map"].items() if ref != attr + "{}={}".format(_one_line(attr), _quoted(ref)) + for attr, ref in fk_props["attr_map"].items() + if ref != attr ), ) attributes_declared.update(fk_props["attr_map"]) @@ -1424,14 +1428,18 @@ def describe(self, context=None, printout=False): attributes_declared.add(attr.name) # Use original_type (core type alias) if available, otherwise use type display_type = attr.original_type or attr.type + attr_name = _one_line(attr.name) + attr_comment = _one_line(attr.comment) definition += "%-20s : %-28s %s\n" % ( - (attr.name if attr.default is None else "%s=%s" % (attr.name, attr.default)), - "%s%s" % (display_type, " auto_increment" if attr.autoincrement else ""), - "# " + attr.comment if attr.comment else "", + (attr_name if attr.default is None else "%s=%s" % (attr_name, _one_line(str(attr.default)))), + "%s%s" % (_one_line(display_type), " auto_increment" if attr.autoincrement else ""), + "# " + attr_comment if attr_comment else "", ) # add remaining indexes for k, v in indexes.items(): - definition += "{unique}INDEX ({attrs})\n".format(unique="UNIQUE " if v["unique"] else "", attrs=", ".join(k)) + definition += "{unique}INDEX ({attrs})\n".format( + unique="UNIQUE " if v["unique"] else "", attrs=", ".join(_one_line(a) for a in k) + ) if printout: logger.info("\n" + definition) return definition @@ -1663,6 +1671,16 @@ def check_fields(fields): return row_to_insert +def _one_line(text): + """Return ``text`` with line breaks replaced, so it stays on its line of a definition.""" + return re.sub(r"[\r\n]+", " ", text) if text else text + + +def _quoted(text): + """Return ``text`` as a double-quoted string literal on one line.""" + return '"{}"'.format(_one_line(text).replace("\\", "\\\\").replace('"', '\\"')) + + def lookup_class_name(name, context, depth=3): """ Find a table's class in the context given its full table name. diff --git a/src/datajoint/utils.py b/src/datajoint/utils.py index e36267936..ad20a6b74 100644 --- a/src/datajoint/utils.py +++ b/src/datajoint/utils.py @@ -1,5 +1,6 @@ """General-purpose utilities""" +import os import re import shutil import warnings @@ -8,6 +9,18 @@ from .errors import DataJointError +def is_plain_file_name(name: str) -> bool: + """ + Check that ``name`` is a plain file name with no directory part. + + Rejects empty names, ``.`` and ``..``, the separators ``/`` and ``\\`` (on + every platform), NUL bytes, and on Windows any ``:`` (drives and alternate + data streams). A name that passes always names an entry directly inside + the directory it is joined to. + """ + return not (name in ("", ".", "..") or "/" in name or "\\" in name or "\x00" in name or (os.name == "nt" and ":" in name)) + + def user_choice(prompt, choices=("yes", "no"), default=None): """ Prompt the user for confirmation. diff --git a/tests/conftest.py b/tests/conftest.py index 6173f6623..816e855e7 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -19,11 +19,14 @@ import logging import os from os import remove +from pathlib import Path from typing import Dict, List import certifi import pytest import urllib3 +from hypothesis import settings +from hypothesis.database import DirectoryBasedExampleDatabase import datajoint as dj from datajoint.errors import DataJointError @@ -35,6 +38,26 @@ logger = logging.getLogger(__name__) +# ============================================================================= +# Hypothesis Profiles +# ============================================================================= +# Select a profile with HYPOTHESIS_PROFILE=dev|ci|thorough. Without it, the +# profile is "ci" when the CI environment variable is set (GitHub Actions sets +# it) and "dev" otherwise. The example counts are for the model-level +# properties (tests/unit/test_expand_spec.py); property tests that run against +# a database set their own, smaller max_examples. +# dev fast local runs +# ci 500 examples, the same examples on every run +# thorough 2000 random examples; failing examples are saved under +# .hypothesis/ (gitignored) and replayed first on the next run. +# Run it before each Diagram.expand merge and before a release tag. +_HYPOTHESIS_DB = DirectoryBasedExampleDatabase(str(Path(__file__).resolve().parent.parent / ".hypothesis" / "examples")) +settings.register_profile("dev", max_examples=50, deadline=None, database=_HYPOTHESIS_DB) +settings.register_profile("ci", max_examples=500, derandomize=True, deadline=None, database=None, print_blob=True) +settings.register_profile("thorough", max_examples=2000, deadline=None, database=_HYPOTHESIS_DB) +settings.load_profile(os.environ.get("HYPOTHESIS_PROFILE") or ("ci" if os.environ.get("CI") else "dev")) + + # ============================================================================= # Pytest Hooks # ============================================================================= diff --git a/tests/integration/test_aggr_left_join.py b/tests/integration/test_aggr_left_join.py new file mode 100644 index 000000000..3a5d95fbd --- /dev/null +++ b/tests/integration/test_aggr_left_join.py @@ -0,0 +1,244 @@ +""" +Left joins keep every row of the left operand when the right operand is restricted (#1650). + +aggr (with the default exclude_nonmatching=False), extend, and union of operands with secondary +attributes use a left join. A restriction on the right operand, including dj.Top, must be +applied before the join, in a subquery. In the outer WHERE it removes the left rows that have +no match. An unrestricted right operand is joined without a subquery, and inner joins keep +their restrictions in the WHERE clause. +""" + +import time + +import pytest + +import datajoint as dj + + +@pytest.fixture(scope="function") +def schema_by_backend(connection_by_backend, db_creds_by_backend): + """Create a fresh schema per test, parameterized across backends.""" + backend = db_creds_by_backend["backend"] + test_id = str(int(time.time() * 1000))[-8:] + schema_name = f"djtest_aggr_left_{backend}_{test_id}"[:64] + drop = f"DROP DATABASE IF EXISTS {connection_by_backend.adapter.quote_identifier(schema_name)}" + if connection_by_backend.is_connected: + try: + connection_by_backend.query(drop) + except Exception: + pass + + schema = dj.Schema(schema_name, connection=connection_by_backend) + yield schema + + if connection_by_backend.is_connected: + try: + connection_by_backend.query(drop) + except Exception: + pass + + +@pytest.fixture(scope="function") +def tables(schema_by_backend): + schema = schema_by_backend + + @schema + class Parent(dj.Manual): + definition = """ + parent_id : int32 + --- + label : varchar(8) + """ + + @schema + class Child(dj.Manual): + definition = """ + -> Parent + child_id : int32 + --- + color : varchar(8) + """ + + @schema + class Tag(dj.Manual): + definition = """ + -> Child + """ + + @schema + class ParentInfo(dj.Manual): + definition = """ + -> Parent + --- + info : varchar(8) + """ + + Parent.insert( + [ + {"parent_id": 1, "label": "a"}, + {"parent_id": 2, "label": "b"}, + {"parent_id": 3, "label": "a"}, + ] + ) + Child.insert( + [ + {"parent_id": 1, "child_id": 1, "color": "red"}, + {"parent_id": 1, "child_id": 2, "color": "blue"}, + {"parent_id": 2, "child_id": 1, "color": "blue"}, + ] + ) + Tag.insert([{"parent_id": 1, "child_id": 1}]) + ParentInfo.insert( + [ + {"parent_id": 1, "info": "x"}, + {"parent_id": 2, "info": "y"}, + {"parent_id": 3, "info": "z"}, + ] + ) + return Parent, Child, Tag, ParentInfo + + +def counts(expression): + rows = expression.to_dicts() + result = {row["parent_id"]: row["n"] for row in rows} + assert len(result) == len(rows), "duplicate rows" + return result + + +def right_operand_in_subquery(query): + return "JOIN (SELECT" in query.from_clause() + + +# --- aggr: the restricted group keeps every row of the grouping expression --- + + +def test_unrestricted_group_keeps_all_rows_without_subquery(tables): + Parent, Child, _, _ = tables + query = Parent.aggr(Child, n="count(child_id)") + assert counts(query) == {1: 2, 2: 1, 3: 0} + assert not right_operand_in_subquery(query) + + +def test_group_restricted_by_string_keeps_all_rows(tables): + """The reproduction from #1650.""" + Parent, Child, _, _ = tables + query = Parent.aggr(Child & "color='red'", n="count(child_id)") + assert counts(query) == {1: 1, 2: 0, 3: 0} + assert len(query) == 3 + assert right_operand_in_subquery(query) + + +@pytest.mark.parametrize( + "restriction, expected", + [ + ({"color": "blue"}, {1: 1, 2: 1, 3: 0}), + ({"parent_id": 1, "color": "blue"}, {1: 1, 2: 0, 3: 0}), + ([{"color": "red"}, {"parent_id": 2}], {1: 1, 2: 1, 3: 0}), + ("parent_id > 1", {1: 0, 2: 1, 3: 0}), + ], + ids=["mapping", "mapping-and", "list-or", "join-attribute"], +) +def test_group_restricted_by_condition_keeps_all_rows(tables, restriction, expected): + Parent, Child, _, _ = tables + assert counts(Parent.aggr(Child & restriction, n="count(child_id)")) == expected + + +def test_group_restricted_by_table_keeps_all_rows(tables): + Parent, Child, Tag, _ = tables + assert counts(Parent.aggr(Child & Tag, n="count(child_id)")) == {1: 1, 2: 0, 3: 0} + + +def test_group_restricted_by_negation_keeps_all_rows(tables): + Parent, Child, Tag, _ = tables + Tag.insert1({"parent_id": 2, "child_id": 1}) # every child of parent 2 is tagged + assert counts(Parent.aggr(Child - Tag, n="count(child_id)")) == {1: 1, 2: 0, 3: 0} + assert counts(Parent.aggr(Child - "color='red'", n="count(child_id)")) == {1: 1, 2: 1, 3: 0} + + +def test_group_restricted_by_top_keeps_all_rows(tables): + """dj.Top is applied with & like any restriction; its limit applies to the group.""" + Parent, Child, _, _ = tables + query = Parent.aggr(Child & dj.Top(1, order_by="color DESC"), n="count(child_id)") + assert counts(query) == {1: 1, 2: 0, 3: 0} + assert right_operand_in_subquery(query) + + +def test_restricted_and_projected_group_keeps_all_rows(tables): + Parent, Child, _, _ = tables + assert counts(Parent.aggr((Child & "color='red'").proj(), n="count(child_id)")) == {1: 1, 2: 0, 3: 0} + + +def test_restricted_join_as_group_keeps_all_rows(tables): + """Aggregates other than count are NULL for the rows with no match.""" + Parent, Child, Tag, _ = tables + query = Parent.aggr((Child * Tag) & "color='red'", n="count(child_id)", top="max(child_id)") + rows = {row["parent_id"]: (row["n"], row["top"]) for row in query.to_dicts()} + assert rows == {1: (1, 1), 2: (0, None), 3: (0, None)} + + +def test_restriction_on_grouping_side_stays_outside(tables): + """A restriction on the left operand still filters the result.""" + Parent, Child, _, _ = tables + query = (Parent & "parent_id > 1").aggr(Child & "color='red'", n="count(child_id)") + assert counts(query) == {2: 0, 3: 0} + + +def test_restricting_the_aggregation_result(tables): + """Restrictions on computed attributes (HAVING, or the PostgreSQL subquery) see the zero counts.""" + Parent, Child, _, _ = tables + query = Parent.aggr(Child & "color='red'", n="count(child_id)") & "n = 0" + assert set(counts(query)) == {2, 3} + + +# --- inner joins are unchanged: the restriction stays in WHERE, without a subquery --- + + +def test_inner_aggregation_keeps_restriction_in_where(tables): + Parent, Child, _, _ = tables + query = Parent.aggr(Child & "color='red'", n="count(child_id)", exclude_nonmatching=True) + assert counts(query) == {1: 1} + assert not right_operand_in_subquery(query) + assert "red" in query.where_clause() + + +def test_universal_set_aggregation_unchanged(tables): + """dj.U aggregation always excludes non-matching rows (inner join).""" + _, Child, _, _ = tables + query = dj.U("color").aggr(Child & "parent_id = 1", n="count(*)") + assert {row["color"]: row["n"] for row in query.to_dicts()} == {"red": 1, "blue": 1} + assert "(SELECT" not in query.from_clause() + + +def test_inner_join_with_restricted_operand_has_no_subquery(tables): + Parent, Child, _, _ = tables + query = Parent * (Child & "color='red'") + assert len(query) == 1 + assert not right_operand_in_subquery(query) + assert "red" in query.where_clause() + + +# --- extend and union use the same left join --- + + +def test_extend_with_restricted_operand_keeps_all_rows(tables): + Parent, Child, _, _ = tables + query = Child.extend(Parent & "label='a'") + rows = {(row["parent_id"], row["child_id"]): row["label"] for row in query.to_dicts()} + assert rows == {(1, 1): "a", (1, 2): "a", (2, 1): None} + assert len(query) == 3 + assert right_operand_in_subquery(query) + + +def test_extend_with_unrestricted_operand_has_no_subquery(tables): + Parent, Child, _, _ = tables + query = Child.extend(Parent) + assert len(query) == 3 + assert not right_operand_in_subquery(query) + + +def test_union_with_restricted_operand_keeps_all_rows(tables): + """Union of operands with secondary attributes left-joins the second operand.""" + Parent, _, _, ParentInfo = tables + query = Parent + (ParentInfo & "info in ('x', 'z')") + rows = {row["parent_id"]: (row["label"], row["info"]) for row in query.to_dicts()} + assert rows == {1: ("a", "x"), 2: ("b", None), 3: ("a", "z")} diff --git a/tests/integration/test_alter.py b/tests/integration/test_alter.py index c593dc30a..2bbfaaa5e 100644 --- a/tests/integration/test_alter.py +++ b/tests/integration/test_alter.py @@ -87,6 +87,14 @@ class Note(dj.Part): --- note : varchar(64) """ + + +@schema +class Link(dj.Manual): + definition = """ + -> Item + -> Item.proj(other_item='item') + """ ''' @@ -153,3 +161,62 @@ def test_alter_explicit_context(pipeline): """ pipeline.Measurement.alter(prompt=False, context={"Upstream": pipeline.Item}) assert pipeline.Measurement.heading.secondary_attributes == ["value", "unit"] + + +def test_alter_projected_foreign_key(pipeline): + """A projected foreign key round-trips through describe() and alter().""" + assert '-> Item.proj(other_item="item")' in pipeline.Link.describe(context=vars(pipeline)) + pipeline.Link.definition = """ + -> Item + -> Item.proj(other_item='item') + --- + weight = 1 : float32 + """ + pipeline.Link.alter(prompt=False) + assert pipeline.Link.heading.primary_key == ["item", "other_item"] + assert pipeline.Link.heading.secondary_attributes == ["weight"] + + +def test_alter_reads_catalog_text_as_data(pipeline): + """Text stored in the catalog is reproduced by describe() on one line and only read by alter().""" + calls = [] + + def record(): + calls.append(True) + return pipeline.Item + + context = dict(vars(pipeline), record=record) + table = pipeline.Item() + comment = "note\n-> record()" + if table.connection.adapter.backend == "postgresql": + sql = f"COMMENT ON TABLE {table.full_table_name} IS %s" + else: + sql = f"ALTER TABLE {table.full_table_name} COMMENT = %s" + table.connection.query(sql, args=(comment,)) + table.__class__._heading = dj.heading.Heading(table_info=table.heading.table_info) + described = table.describe(context=context) + assert described.splitlines()[0] == "# note -> record()" + # keep the comment unchanged so that only the new attribute is altered + table.definition = ( + described.splitlines()[0] + + """ + item : int32 + --- + label = "" : varchar(16) + """ + ) + table.alter(prompt=False, context=context) + assert calls == [] + assert table.heading.secondary_attributes == ["label"] + + +def test_alter_unresolved_parent(pipeline): + """A parent that is not in the context is reported as unresolved.""" + pipeline.Measurement.definition = """ + -> Item + --- + value : float32 + unit = "" : varchar(16) + """ + with pytest.raises(dj.DataJointError, match="could not be resolved"): + pipeline.Measurement.alter(prompt=False, context={}) diff --git a/tests/integration/test_declare.py b/tests/integration/test_declare.py index d0b904df1..92ff2b446 100644 --- a/tests/integration/test_declare.py +++ b/tests/integration/test_declare.py @@ -353,7 +353,7 @@ class WithSuchALongPartNameThatItCrashesMySQL(dj.Part): -> (master) """ - with pytest.raises(dj.DataJointError): + with pytest.raises(dj.DataJointError, match="exceeds the max length"): schema_any(WhyWouldAnyoneCreateATableNameThisLong) diff --git a/tests/integration/test_path_confinement.py b/tests/integration/test_path_confinement.py new file mode 100644 index 000000000..1eaf240e5 --- /dev/null +++ b/tests/integration/test_path_confinement.py @@ -0,0 +1,183 @@ +""" +Rows written directly to the database cannot direct fetches outside the store +or the download path. + +Each test inserts a valid row through DataJoint, then rewrites the stored value +with SQL, as anyone with write access to the table could, and fetches it. +""" + +import json +from pathlib import Path + +import pytest + +import datajoint as dj + + +class Document(dj.Manual): + definition = """ + doc_id : int32 + --- + inline_file : + stored_file : + """ + + +class Reference(dj.Manual): + definition = """ + ref_id : int32 + --- + file_ref : + """ + + +class Output(dj.Manual): + definition = """ + output_id : int32 + --- + result : + """ + + +@pytest.fixture +def schema_paths(connection_test, mock_stores, prefix): + schema = dj.Schema(prefix + "_path_confinement", connection=connection_test) + schema(Document) + schema(Reference) + schema(Output) + yield schema + schema.drop() + + +@pytest.fixture +def outside(tmp_path): + """A file outside every store and download path.""" + path = tmp_path / "outside" / "outside.txt" + path.parent.mkdir() + path.write_bytes(b"outside") + return path + + +def _overwrite(table, attr, value, **key): + """Rewrite one stored value with SQL, bypassing the codec.""" + q = table.connection.adapter.quote_identifier + (pk_name, pk_value) = next(iter(key.items())) + table.connection.query( + f"UPDATE {table.full_table_name} SET {q(attr)} = %s WHERE {q(pk_name)} = %s", + args=(value, pk_value), + ) + + +def _json(table, attr, **key): + q = table.connection.adapter.quote_identifier + (pk_name, pk_value) = next(iter(key.items())) + raw = table.connection.query( + f"SELECT {q(attr)} FROM {table.full_table_name} WHERE {q(pk_name)} = %s", args=(pk_value,) + ).fetchone()[0] + return json.loads(raw) if isinstance(raw, (str, bytes)) else dict(raw) + + +@pytest.mark.parametrize( + "name", + ["../outside.txt", "../../outside.txt", "sub/outside.txt", "/outside-of-download-path.txt"], + ids=["parent_ref", "parent_ref_twice", "subdir", "absolute"], +) +def test_attach_fetch_refuses_stored_name_with_directory(schema_paths, tmp_path, name): + source = tmp_path / "report.txt" + source.write_bytes(b"report") + Document.insert1(dict(doc_id=1, inline_file=source, stored_file=source)) + _overwrite(Document, "inline_file", name.encode() + b"\x00payload", doc_id=1) + + download = tmp_path / "a" / "b" / "downloads" + with dj.config.override(download_path=str(download)): + with pytest.raises(dj.DataJointError, match="not a plain file name"): + (Document & "doc_id=1").fetch1("inline_file") + assert not (tmp_path / "a" / "b" / "outside.txt").exists() + assert not (tmp_path / "a" / "outside.txt").exists() + assert not (download / "sub").exists() + + +def test_attach_fetch_still_round_trips(schema_paths, tmp_path): + source = tmp_path / "report.txt" + source.write_bytes(b"report") + Document.insert1(dict(doc_id=1, inline_file=source, stored_file=source)) + download = tmp_path / "downloads" + with dj.config.override(download_path=str(download)): + inline, stored = (Document & "doc_id=1").fetch1("inline_file", "stored_file") + assert Path(inline).parent == download + assert Path(inline).read_bytes() == b"report" + assert Path(stored).read_bytes() == b"report" + + +def test_hash_fetch_refuses_path_outside_store(schema_paths, tmp_path, outside): + source = tmp_path / "report.txt" + source.write_bytes(b"report") + Document.insert1(dict(doc_id=1, inline_file=source, stored_file=source)) + meta = _json(Document, "stored_file", doc_id=1) + meta["path"] = str(outside) + _overwrite(Document, "stored_file", json.dumps(meta), doc_id=1) + with dj.config.override(download_path=str(tmp_path / "downloads")): + with pytest.raises(dj.DataJointError, match="outside the store location"): + (Document & "doc_id=1").fetch1("stored_file") + + +def test_filepath_insert_refuses_path_outside_store(schema_paths, outside): + repo = Path(dj.config.stores["repo"]["location"]) + for path in (str(outside), "../" * len(repo.parts) + str(outside).lstrip("/")): + with pytest.raises(dj.DataJointError, match="outside the store location"): + Reference.insert1(dict(ref_id=1, file_ref=path)) + assert len(Reference()) == 0 + + +@pytest.mark.parametrize("kind", ["absolute", "parent_ref"]) +def test_filepath_fetch_refuses_path_outside_store(schema_paths, outside, kind): + repo = Path(dj.config.stores["repo"]["location"]) + (repo / "inside.txt").write_bytes(b"inside") + Reference.insert1(dict(ref_id=1, file_ref="inside.txt")) + assert (Reference & "ref_id=1").fetch1("file_ref").read() == b"inside" + + meta = _json(Reference, "file_ref", ref_id=1) + meta["path"] = { + "absolute": str(outside), + "parent_ref": "../" * len(repo.parts) + str(outside).lstrip("/"), + }[kind] + _overwrite(Reference, "file_ref", json.dumps(meta), ref_id=1) + ref = (Reference & "ref_id=1").fetch1("file_ref") + with pytest.raises(dj.DataJointError, match="outside the store location"): + ref.read() + + +def test_filepath_absolute_path_inside_store(schema_paths): + repo = Path(dj.config.stores["repo"]["location"]) + (repo / "inside.txt").write_bytes(b"inside") + Reference.insert1(dict(ref_id=1, file_ref=str(repo / "inside.txt"))) + assert _json(Reference, "file_ref", ref_id=1)["path"] == "inside.txt" + # Rows written before paths were recorded relative to the store stay readable + meta = _json(Reference, "file_ref", ref_id=1) + meta["path"] = str(repo / "inside.txt") + _overwrite(Reference, "file_ref", json.dumps(meta), ref_id=1) + assert (Reference & "ref_id=1").fetch1("file_ref").read() == b"inside" + + +def test_filepath_outside_store_when_allowed(schema_paths, outside): + with dj.config.override(allow_filepath_outside_store=True): + Reference.insert1(dict(ref_id=1, file_ref=str(outside))) + assert (Reference & "ref_id=1").fetch1("file_ref").read() == b"outside" + with pytest.raises(dj.DataJointError, match="outside the store location"): + (Reference & "ref_id=1").fetch1("file_ref").read() + + +def test_object_fetch_refuses_path_outside_store(schema_paths, outside): + Output.insert1(dict(output_id=1, result=b"result")) + assert (Output & "output_id=1").fetch1("result").read() == b"result" + meta = _json(Output, "result", output_id=1) + meta["path"] = str(outside) + _overwrite(Output, "result", json.dumps(meta), output_id=1) + with pytest.raises(dj.DataJointError, match="outside the store location"): + (Output & "output_id=1").fetch1("result").read() + + +def test_object_insert_refuses_metadata_outside_store(schema_paths, outside): + with pytest.raises(dj.DataJointError, match="outside the store location"): + Output.insert1(dict(output_id=1, result={"path": str(outside), "store": "local", "size": 6})) + assert len(Output()) == 0 diff --git a/tests/integration/test_relational_operand.py b/tests/integration/test_relational_operand.py index eea53288e..c3209de66 100644 --- a/tests/integration/test_relational_operand.py +++ b/tests/integration/test_relational_operand.py @@ -180,6 +180,12 @@ def test_project(schema_simp_pop): assert len((D() & cond).proj()) == len((D() & cond)), "projection failed: altered its arguments cardinality" +@pytest.mark.parametrize("value", ["nonexistent", "(nonexistent)"]) +def test_project_missing_source_attribute(schema_simp_pop, value): + with pytest.raises(DataJointError, match="Attribute `nonexistent` not found"): + A().proj(c=value) + + def test_rename_non_dj_attribute(connection_test, schema_simp_pop, schema_any_pop, prefix): schema = prefix + "_test1" connection_test.query(f"CREATE TABLE {schema}.test_table (oldID int PRIMARY KEY)").fetchall() @@ -608,12 +614,14 @@ def test_top_errors(self, schema_simp_pop): L() & dj.Top(order_by=1) with pytest.raises(TypeError) as err5: L() & dj.Top(offset="1") - assert "datajoint.errors.DataJointError: Invalid restriction type Top(limit=1, order_by=['KEY'], offset=0)" == str( - err1.exconly() - ) - assert "datajoint.errors.DataJointError: Invalid restriction type Top(limit=1, order_by=['KEY'], offset=0)" == str( - err2.exconly() + nested_top = ( + "datajoint.errors.DataJointError: dj.Top must be applied on its own, as `expression & dj.Top(...)`. " + "It cannot be negated (with - or dj.Not) or combined with other restrictions in a list, an AndList, " + "or the restrictions passed to populate() or progress(). For the rows after the first n, " + "use dj.Top(None, order_by=..., offset=n)." ) + assert nested_top == str(err1.exconly()) + assert nested_top == str(err2.exconly()) assert "TypeError: Top limit must be an integer" == str(err3.exconly()) assert "TypeError: Top order_by attributes must all be strings" == str(err4.exconly()) assert "TypeError: The offset argument must be an integer" == str(err5.exconly()) diff --git a/tests/integration/test_restriction_values.py b/tests/integration/test_restriction_values.py new file mode 100644 index 000000000..94c793209 --- /dev/null +++ b/tests/integration/test_restriction_values.py @@ -0,0 +1,205 @@ +""" +Mapping restrictions with values that need quoting, on both backends. + +Values in dict restrictions are compared as literals: quote characters, backslashes, +``%``, and SQL keywords inside a value are part of the value. +""" + +import numpy as np +import pytest + +import datajoint as dj + +ROWS = [ + dict(item_id=1, name="alpha", data={"label": "alpha", "tags": [1, 2], "sub": {"k": 1}, "size": 3}), + dict(item_id=2, name="o'brien", data={"label": "o'brien", "tags": [3], "sub": {"k": 2}, "size": 4}), + dict(item_id=3, name="50% off", data={"label": "50% off", "tags": [], "sub": {"k": 3}, "size": 5}), + dict(item_id=4, name='say "hi"', data={"label": 'say "hi"', "tags": [4], "sub": {"k": "x"}, "size": 6}), +] + +SPECIAL_CHARACTER_VALUES = [ + "' OR 1=1 --", + "' OR '1'='1", + "x' OR 'a'='a", + "\\' OR 1=1 -- ", + "') OR ('1'='1", + '" OR ""="', + "'; DELETE FROM item; --", + "%' OR 1=1 --", +] + + +@pytest.fixture +def item(connection_by_backend, backend, prefix): + schema = dj.Schema(f"{prefix}_restriction_values_{backend}", connection=connection_by_backend) + + @schema + class Item(dj.Manual): + definition = """ + item_id : int32 + --- + name : varchar(64) + data = null : json + """ + + Item.insert(ROWS) + yield Item() + schema.drop(prompt=False) + + +def ids(query): + return sorted(query.to_arrays("item_id").tolist()) + + +@pytest.mark.parametrize("value", SPECIAL_CHARACTER_VALUES) +def test_values_with_quote_characters_match_nothing(item, value): + assert ids(item & {"name": value}) == [] + assert ids(item & {"data.label": value}) == [] + assert ids(item & {"data.sub": {"k": value}}) == [] + assert ids(item & {"name": [value, 'a"b', "c'd"]}) == [] + assert ids(item & [{"name": value}, {"item_id": 1}]) == [1] + assert ids(item - {"name": value}) == [1, 2, 3, 4] + assert len(item & {"name": value}) == 0 + + +@pytest.mark.parametrize("value", SPECIAL_CHARACTER_VALUES) +def test_values_with_quote_characters_delete_nothing(item, value): + (item & {"name": value}).delete_quick() + (item & {"data.label": value}).delete_quick() + (item & {"name": [value]}).delete_quick() + (item & {"data.sub": {"k": value}}).delete_quick() + assert len(item) == len(ROWS) + + +@pytest.mark.parametrize( + "key", + [ + "data.x') OR 1=1 -- ", + "data.x` OR 1=1 OR `y", + 'data.x" OR 1=1 OR "y', + "data.label'] OR 1=1 --", + ], +) +def test_invalid_json_keys_rejected(item, key): + with pytest.raises(dj.DataJointError): + item & {key: 1} + + +@pytest.mark.parametrize("type_spec", ["unsigned) OR (1", "char(20)) OR (1", "signed or 1", "nonsense"]) +def test_invalid_json_types_rejected(item, type_spec): + with pytest.raises(dj.DataJointError): + item & {f"data.size:{type_spec}": 1} + + +def test_unsupported_value_types_rejected(item): + with pytest.raises(dj.DataJointError): + item & {"name": b"' OR 1=1 --"} + with pytest.raises(dj.DataJointError): + item & {"name": {"a": "' OR 1=1 --"}} + + +def test_ordinary_values_still_match(item): + assert ids(item & {"item_id": 2}) == [2] + assert ids(item & {"item_id": np.int64(3)}) == [3] + assert ids(item & {"name": "alpha"}) == [1] + assert ids(item & {"name": "o'brien"}) == [2] + assert ids(item & {"name": "50% off"}) == [3] + assert ids(item & {"name": 'say "hi"'}) == [4] + assert ids(item & [{"name": "alpha"}, {"name": "o'brien"}]) == [1, 2] + assert ids(item - {"name": "o'brien"}) == [1, 3, 4] + assert ids(item & {"data.label": "o'brien"}) == [2] + assert ids(item & {"data.label": "50% off"}) == [3] + assert ids(item & {"data.tags": [1, 2]}) == [1] + assert ids(item & {"data.sub": {"k": 2}}) == [2] + assert ids(item & {"data.sub": {"k": "x"}}) == [4] + assert ids(item & {"data.size:unsigned": 5}) == [3] + assert ids(item & {"data.size:decimal(4, 1)": 6}) == [4] + assert ids(item & {"data": None}) == [] + + +def test_string_with_backslash(item, backend): + """On MySQL a backslash in a string value matches itself.""" + item.insert1(dict(item_id=5, name="back\\slash", data={"label": "back\\slash", "sub": {"k": "a\\b"}})) + assert ids(item & {"data.sub": {"k": "a\\b"}}) == [5] + if backend == "mysql": + assert ids(item & {"name": "back\\slash"}) == [5] + assert ids(item & {"data.label": "back\\slash"}) == [5] + + +def test_mysql_values_without_backslash_escapes(item, backend): + """On MySQL, string values stay closed literals when the session enables NO_BACKSLASH_ESCAPES.""" + if backend != "mysql": + pytest.skip("sql_mode is MySQL-specific") + connection = item.connection + sql_mode = connection.query("SELECT @@SESSION.sql_mode").fetchone()[0] + try: + connection.query("SET SESSION sql_mode = %s", (",".join(filter(None, [sql_mode, "NO_BACKSLASH_ESCAPES"])),)) + assert ids(item & {"name": "' OR 1=1 --"}) == [] + assert ids(item & {"name": "o'brien"}) == [2] + finally: + connection.query("SET SESSION sql_mode = %s", (sql_mode,)) + + +def test_postgresql_list_values_without_standard_conforming_strings(item, backend): + """On PostgreSQL, list values stay closed literals when standard_conforming_strings is off.""" + if backend != "postgresql": + pytest.skip("standard_conforming_strings is PostgreSQL-specific") + item.insert1(dict(item_id=5, name=str(["back\\slash"]))) + connection = item.connection + setting = connection.query("SHOW standard_conforming_strings").fetchone()[0] + try: + connection.query("SET standard_conforming_strings = off") + assert ids(item & {"name": ["'OR 1=1 -- \""]}) == [] + assert ids(item & {"name": ["back\\slash"]}) == [5] + finally: + connection.query(f"SET standard_conforming_strings = {setting}") + + +NUMERIC_JSON_TYPES = { + "mysql": ["unsigned", "signed", "decimal(4, 1)", "double", "float"], + "postgresql": ["integer", "int", "bigint", "numeric(10,2)", "double precision", "real", "unsigned", "double"], +} +TEXT_JSON_TYPES = { + "mysql": ["char(20)", "char(20) character set utf8mb4"], + "postgresql": ["text", "varchar(32)", "character varying(32)"], +} + + +def test_json_types_in_restriction_and_projection(item, backend): + for type_spec in NUMERIC_JSON_TYPES[backend]: + assert ids(item & {f"data.size:{type_spec}": 5}) == [3], type_spec + values = item.proj(size=f"data.size:{type_spec}").to_arrays("size", order_by="item_id") + assert [float(v) for v in values] == [3, 4, 5, 6], type_spec + for type_spec in TEXT_JSON_TYPES[backend]: + assert ids(item & {f"data.label:{type_spec}": "o'brien"}) == [2], type_spec + values = item.proj(label=f"data.label:{type_spec}").to_arrays("label", order_by="item_id") + assert list(values) == [row["data"]["label"] for row in ROWS], type_spec + + +def test_json_type_in_index_declaration(connection_by_backend, backend, prefix): + if backend == "postgresql": + pytest.skip("Indexes on JSON paths are not created on PostgreSQL (index name is derived from the expression)") + schema = dj.Schema(f"{prefix}_restriction_values_index_{backend}", connection=connection_by_backend) + numeric, text = NUMERIC_JSON_TYPES[backend][0], TEXT_JSON_TYPES[backend][0] + try: + + @schema + class Indexed(dj.Manual): + definition = f""" + item_id : int32 + --- + data = null : json + index(data.size:{numeric}) + index(data.label:{text}) + """ + + Indexed.insert(dict(item_id=r["item_id"], data=r["data"]) for r in ROWS) + assert sorted((Indexed & {f"data.size:{numeric}": 4}).to_arrays("item_id").tolist()) == [2] + finally: + schema.drop(prompt=False) + + +def test_non_finite_numbers_rejected(item): + for value in (float("nan"), float("inf"), np.float64("-inf")): + with pytest.raises(dj.DataJointError): + item & {"item_id": value} diff --git a/tests/integration/test_tls.py b/tests/integration/test_tls.py index 8f2681dd9..fc8a70c77 100644 --- a/tests/integration/test_tls.py +++ b/tests/integration/test_tls.py @@ -1,4 +1,3 @@ -import logging import os import pytest @@ -22,19 +21,11 @@ def test_explicit_ssl_connection(db_creds_test, connection_test): @requires_ssl -def test_ssl_auto_detect(db_creds_test, connection_test, caplog): - """When use_tls is not specified, SSL is preferred but fallback is allowed with warning.""" - with caplog.at_level(logging.WARNING): - conn = dj.conn(reset=True, **db_creds_test) - result = conn.query("SHOW STATUS LIKE 'Ssl_cipher';").fetchone()[1] - - if len(result) > 0: - # SSL connected successfully - assert "SSL connection failed" not in caplog.text - else: - # SSL failed and fell back - warning should be logged - assert "SSL connection failed" in caplog.text - assert "Falling back to non-SSL" in caplog.text +def test_ssl_auto_detect(db_creds_test, connection_test): + """When use_tls is not specified, SSL is used if the server supports it.""" + conn = dj.conn(reset=True, **db_creds_test) + result = conn.query("SHOW STATUS LIKE 'Ssl_cipher';").fetchone()[1] + assert len(result) > 0, "SSL should be active when the server supports it" def test_insecure_connection(db_creds_test, connection_test): diff --git a/tests/integration/test_top_in_queries.py b/tests/integration/test_top_in_queries.py new file mode 100644 index 000000000..52f0ff334 --- /dev/null +++ b/tests/integration/test_top_in_queries.py @@ -0,0 +1,391 @@ +""" +dj.Top is honored when the limited expression is an operand of another query (#1656). + +An expression restricted by dj.Top carries its ORDER BY/LIMIT in ``_top``. Joins (on either +side), aggr, dj.U.aggr, dj.U restriction, union, and restriction by a limited expression must +apply that limit to the operand itself, which takes a subquery. dj.Top cannot be negated; the +rows after the first n are ``dj.Top(None, order_by=..., offset=n)``. +""" + +import time + +import pytest + +import datajoint as dj +from datajoint.errors import DataJointError + + +@pytest.fixture(scope="function") +def schema_by_backend(connection_by_backend, db_creds_by_backend): + """Create a fresh schema per test, parameterized across backends.""" + backend = db_creds_by_backend["backend"] + test_id = str(int(time.time() * 1000))[-8:] + schema_name = f"djtest_top_{backend}_{test_id}"[:64] + drop = f"DROP DATABASE IF EXISTS {connection_by_backend.adapter.quote_identifier(schema_name)}" + if connection_by_backend.is_connected: + try: + connection_by_backend.query(drop) + except Exception: + pass + + schema = dj.Schema(schema_name, connection=connection_by_backend) + yield schema + + if connection_by_backend.is_connected: + try: + connection_by_backend.query(drop) + except Exception: + pass + + +@pytest.fixture(scope="function") +def tables(schema_by_backend): + schema = schema_by_backend + + @schema + class Parent(dj.Manual): + definition = """ + parent_id : int32 + --- + label : varchar(8) + """ + + @schema + class Child(dj.Manual): + definition = """ + -> Parent + child_id : int32 + --- + color : varchar(8) + """ + + @schema + class ParentInfo(dj.Manual): + definition = """ + -> Parent + --- + info : varchar(8) + """ + + Parent.insert( + [ + {"parent_id": 1, "label": "a"}, + {"parent_id": 2, "label": "b"}, + {"parent_id": 3, "label": "a"}, + ] + ) + Child.insert( + [ + {"parent_id": 1, "child_id": 1, "color": "red"}, + {"parent_id": 1, "child_id": 2, "color": "blue"}, + {"parent_id": 2, "child_id": 1, "color": "blue"}, + ] + ) + ParentInfo.insert( + [ + {"parent_id": 1, "info": "x"}, + {"parent_id": 2, "info": "y"}, + {"parent_id": 3, "info": "z"}, + ] + ) + return Parent, Child, ParentInfo + + +# Limits used below, with the rows they select on their own. +def top_child(): # child (1, 2) + return dj.Top(1, order_by="child_id DESC, parent_id") + + +def top2_child(): # children (1, 2), (1, 1) + return dj.Top(2, order_by="child_id DESC, parent_id") + + +def rest_child(): # children (1, 1), (2, 1): all but the first + return dj.Top(None, order_by="child_id DESC, parent_id", offset=1) + + +def top_parent(): # parent 1 + return dj.Top(1, order_by="parent_id") + + +def rest_parent(): # parents 2, 3 + return dj.Top(None, order_by="parent_id", offset=1) + + +def rows(query, *attributes): + result = [tuple(row[a] for a in attributes) for row in query.to_dicts()] + assert len(result) == len(set(result)), "duplicate rows" + return set(result) + + +def counts(query, key, value="n"): + result = {row[key]: row[value] for row in query.to_dicts()} + return result + + +def test_limits_on_their_own(tables): + Parent, Child, _ = tables + assert rows(Child & top_child(), "parent_id", "child_id") == {(1, 2)} + assert rows(Child & top2_child(), "parent_id", "child_id") == {(1, 2), (1, 1)} + assert rows(Child & rest_child(), "parent_id", "child_id") == {(1, 1), (2, 1)} + assert rows(Parent & top_parent(), "parent_id") == {(1,)} + assert rows(Parent & rest_parent(), "parent_id") == {(2,), (3,)} + + +# --- joins: a limited operand on either side keeps its limit --- + + +@pytest.mark.parametrize( + "make, expected", + [ + (lambda P, C: P * (C & top_child()), {(1, 2)}), + (lambda P, C: (P & top_parent()) * C, {(1, 1), (1, 2)}), + (lambda P, C: (P & top_parent()) * (C & top_child()), {(1, 2)}), + (lambda P, C: P * ((C & "color='blue'") & dj.Top(1, order_by="parent_id DESC")), {(2, 1)}), + (lambda P, C: P * (C & rest_child()), {(1, 1), (2, 1)}), + (lambda P, C: (P & rest_parent()) * C, {(2, 1)}), + (lambda P, C: P * (C & top_child()).proj(), {(1, 2)}), + ], + ids=["right", "left", "both", "with-condition", "right-offset", "left-offset", "projected"], +) +def test_join_keeps_limit(tables, make, expected): + Parent, Child, _ = tables + assert rows(make(Parent, Child), "parent_id", "child_id") == expected + + +def test_join_without_limit_has_no_subquery(tables): + Parent, Child, _ = tables + query = Parent * (Child & "color='blue'") + assert rows(query, "parent_id", "child_id") == {(1, 2), (2, 1)} + assert "(SELECT" not in query.from_clause() + + +def test_extend_with_limited_left_operand(tables): + Parent, Child, _ = tables + query = (Child & top_child()).extend(Parent) + assert rows(query, "parent_id", "child_id", "label") == {(1, 2, "a")} + + +# --- aggregation --- + + +def test_aggr_with_limited_grouping_expression(tables): + Parent, Child, _ = tables + assert counts((Parent & top_parent()).aggr(Child, n="count(child_id)"), "parent_id") == {1: 2} + assert counts((Parent & rest_parent()).aggr(Child, n="count(child_id)"), "parent_id") == {2: 1, 3: 0} + + +@pytest.mark.parametrize( + "limit, expected", + [(top_child, {1: 1}), (rest_child, {1: 1, 2: 1})], + ids=["top", "offset"], +) +def test_inner_aggr_with_limited_group(tables, limit, expected): + Parent, Child, _ = tables + query = Parent.aggr(Child & limit(), n="count(child_id)", exclude_nonmatching=True) + assert counts(query, "parent_id") == expected + + +def test_left_join_with_limited_right_operand(tables): + Parent, Child, _ = tables + query = Child.extend(Parent & top_parent()) + assert rows(query, "parent_id", "child_id", "label") == {(1, 1, "a"), (1, 2, "a"), (2, 1, None)} + query = Parent.aggr(Child & rest_child(), n="count(child_id)") + assert counts(query, "parent_id") == {1: 1, 2: 1, 3: 0} + + +@pytest.mark.parametrize( + "limit, expected", + [(top_child, {"blue": 1}), (rest_child, {"red": 1, "blue": 1})], + ids=["top", "offset"], +) +def test_universal_aggr_with_limited_group(tables, limit, expected): + _, Child, _ = tables + assert counts(dj.U("color").aggr(Child & limit(), n="count(*)"), "color") == expected + + +def test_universal_aggr_without_limit_has_no_subquery(tables): + _, Child, _ = tables + query = dj.U("color").aggr(Child, n="count(*)") + assert counts(query, "color") == {"red": 1, "blue": 2} + assert "(SELECT" not in query.from_clause() + + +# --- restriction by a limited expression (MySQL rejects LIMIT inside IN) --- + + +@pytest.mark.parametrize( + "limit, matching, rest", + [ + (top_child, {(1,)}, {(2,), (3,)}), + (top2_child, {(1,)}, {(2,), (3,)}), + (rest_child, {(1,), (2,)}, {(3,)}), + ], + ids=["top", "top2", "offset"], +) +def test_restriction_by_limited_expression(tables, limit, matching, rest): + Parent, Child, _ = tables + assert rows(Parent & (Child & limit()), "parent_id") == matching + assert rows(Parent - (Child & limit()), "parent_id") == rest + + +def test_restriction_by_limit_on_computed_attribute(tables): + """The limit applies before the projection to the common attributes.""" + Parent, Child, _ = tables + # score: (1, 1) -> 11, (1, 2) -> 21, (2, 1) -> 12 + limited = Child.proj(score="child_id * 10 + parent_id") & dj.Top(1, order_by="score DESC") + assert rows(limited, "parent_id", "child_id", "score") == {(1, 2, 21)} + assert rows(Parent & limited, "parent_id") == {(1,)} + assert rows(Parent - limited, "parent_id") == {(2,), (3,)} + + +def test_restriction_by_limited_union(tables): + Parent, Child, ParentInfo = tables + first = (Parent.proj() + ParentInfo.proj()) & dj.Top(1, order_by="parent_id") + assert rows(Child & first, "parent_id", "child_id") == {(1, 1), (1, 2)} + assert rows(Child - first, "parent_id", "child_id") == {(2, 1)} + + +def test_restriction_without_limit_has_no_derived_table(tables): + Parent, Child, _ = tables + query = Parent & (Child & "color='blue'") + assert rows(query, "parent_id") == {(1,), (2,)} + assert query.where_clause().count("SELECT") == 1 + + +@pytest.mark.parametrize( + "limit", + [top2_child, lambda: dj.Top(2, order_by="parent_id")], + ids=["order-by-dropped-attribute", "order-by-kept-attribute"], +) +def test_universal_restriction_by_limited_expression(tables, limit): + """The limit applies to Child's rows before dj.U takes the distinct parent_id values.""" + _, Child, _ = tables + assert rows(dj.U("parent_id") & (Child & limit()), "parent_id") == {(1,)} + + +def test_universal_restriction_without_limit_has_no_subquery(tables): + _, Child, _ = tables + query = dj.U("parent_id") & Child + assert rows(query, "parent_id") == {(1,), (2,)} + assert "(SELECT" not in query.from_clause() + + +# --- projection of a limited expression --- + + +def test_keys_of_limit_on_aggregate(tables): + """The ORDER BY names a computed attribute that keys() drops.""" + Parent, Child, _ = tables + limited = Parent.aggr(Child, n="count(child_id)") & dj.Top(1, order_by="n DESC") + assert limited.keys() == [{"parent_id": 1}] + assert rows(Child * limited.proj(), "parent_id", "child_id") == {(1, 1), (1, 2)} + + +def test_projection_drops_computed_ordering_attribute(tables): + Parent, _, _ = tables + limited = Parent.proj(neg="-parent_id") & dj.Top(1, order_by="neg") # parent 3 + assert rows(limited.proj(), "parent_id") == {(3,)} + assert len(limited.proj()) == 1 + + +@pytest.mark.parametrize( + "make, attributes, expected", + [ + ( + lambda P, C: (P & dj.Top(1, order_by="label DESC, parent_id")).proj(label="-parent_id"), + ("parent_id", "label"), + {(2, -2)}, + ), + ( + lambda P, C: (C & top_child()).proj(child_id="parent_id", parent_id="child_id"), + ("parent_id", "child_id"), + {(2, 1)}, + ), + ], + ids=["recomputed", "swapped"], +) +def test_projection_redefines_ordering_attribute(tables, make, attributes, expected): + """A new attribute that takes an ORDER BY name must not change which rows the limit selects.""" + Parent, Child, _ = tables + assert rows(make(Parent, Child), *attributes) == expected + + +def test_projection_dropping_table_column_keeps_order_in_place(tables): + """ORDER BY on a table column that the projection drops needs no subquery.""" + _, Child, _ = tables + query = (Child & dj.Top(1, order_by="color DESC")).proj() + assert rows(query, "parent_id", "child_id") == {(1, 1)} + assert "(SELECT" not in query.from_clause() + + +# --- merged limits, emptiness, diagrams --- + + +@pytest.mark.parametrize( + "second", + [ + lambda: dj.Top(None, order_by="parent_id", offset=1), + lambda: dj.Top(5, order_by=None, offset=1), + ], + ids=["offset", "offset-inherit"], +) +def test_second_limit_stays_within_first(tables, second): + Parent, _, _ = tables + first_two = Parent & dj.Top(2, order_by="parent_id") # parents 1, 2 + assert rows(first_two & second(), "parent_id") == {(2,)} + assert [row["parent_id"] for row in first_two.to_dicts(limit=5, offset=1)] == [2] + + +def test_bool_of_limited_expression(tables): + Parent, _, _ = tables + assert not (Parent & dj.Top(None, order_by="parent_id", offset=3)) + assert not (Parent & dj.Top(0)) + assert Parent & rest_parent() + + +def test_diagram_restrict_by_limited_expression(tables, schema_by_backend): + Parent, Child, ParentInfo = tables + restricted = dj.Diagram(schema_by_backend).restrict(Parent & top_parent()) + expected = {Parent.full_table_name: 1, Child.full_table_name: 2, ParentInfo.full_table_name: 1} + assert restricted.counts() == expected + + +# --- union --- + + +def test_union_restricted_by_top(tables): + Parent, _, ParentInfo = tables + keys_only = (Parent.proj() + ParentInfo.proj()) & dj.Top(1, order_by="parent_id DESC") + assert rows(keys_only, "parent_id") == {(3,)} + with_attributes = (Parent + ParentInfo) & dj.Top(1, order_by="parent_id DESC") + assert rows(with_attributes, "parent_id", "label", "info") == {(3, "a", "z")} + + +def test_union_of_limited_operands(tables): + Parent, _, ParentInfo = tables + last_info = ParentInfo & dj.Top(1, order_by="parent_id DESC") + keys_only = (Parent & top_parent()).proj() + last_info.proj() + assert rows(keys_only, "parent_id") == {(1,), (3,)} + with_attributes = (Parent & top_parent()) + last_info + assert rows(with_attributes, "parent_id", "label", "info") == {(1, "a", None), (3, None, "z")} + + +# --- dj.Top cannot be negated; the error names the offset form --- + + +@pytest.mark.parametrize( + "make", + [ + lambda P: P - top_parent(), + lambda P: P & dj.Not(top_parent()), + lambda P: P & [top_parent()], + lambda P: P - [top_parent()], + lambda P: P & dj.AndList([top_parent(), "parent_id > 1"]), + ], + ids=["minus", "not", "list", "minus-list", "andlist"], +) +def test_negated_or_nested_top_is_rejected(tables, make): + Parent, _, _ = tables + with pytest.raises(DataJointError, match="offset=n"): + make(Parent) diff --git a/tests/unit/expand_model.py b/tests/unit/expand_model.py new file mode 100644 index 000000000..5c94862aa --- /dev/null +++ b/tests/unit/expand_model.py @@ -0,0 +1,923 @@ +""" +Executable reference model of ``Diagram.expand``. + +This module is an executable copy of the traversal specification (the +"Traversal specification" section of ``diagram.md``). It holds rows in plain +Python dictionaries, needs no database, and defines the row sets that the +engine must produce: + +- ``D(S)``: the least superset of the seed rows ``S`` closed under ``down``. + This is ``expand(seed, "down")`` and ``cascade(seed, part_integrity="cascade")``. +- ``D1(S)``: the closure under ``child`` alone, which ``part_integrity="ignore"`` + deletes and ``"enforce"`` deletes when it is lift-closed. +- ``U(S)``: the least superset closed under ``up``. This is ``expand(seed, "up")`` + and ``trace(seed)``. +- ``both(S) = U(D(S))``, which is ``expand(seed, "both")``. + +Each operation is a plain breadth-first search over row identifiers +``(table, pk_tuple)``. ``test_expand_spec.py`` checks the model against the +theorems of the specification, and later test layers check the engine against +the model. + +The module also models parts of the specification's "Computation" section, so +that its claims can be checked against the definitions: the table-level reach +(the node set of an expanded diagram), the one pass over the group quotient with +its iterating groups, and the rules under which R1 may copy a condition or +relabel materialized keys. + +Model +----- +- A schema is a list of tables in declaration order and a list of foreign keys. + An FK maps child attributes onto the parent's primary key (``attr_map``). + Parallel FKs between the same two tables are separate edges. +- A2: an FK with any NULL column references nothing, as in SQL's MATCH SIMPLE. + FKs can share columns, so partial NULLs occur. +- A1, owned parts: a part is owned by its master if an FK in its primary key + references the master or an owned part of the same master, renames allowed. + The chain maps the part's owning attributes onto the master's key. A master + and its owned parts form its group; a part that is not owned is a plain table. +- A database is ``{table: {pk_tuple: row_dict}}``, where ``pk_tuple`` lists the + primary-key values in the order of ``TableSpec.pk``. +""" + +from __future__ import annotations + +from collections import defaultdict, deque +from dataclasses import dataclass, field +from typing import Callable, Iterable, Mapping + +import networkx as nx + +from datajoint.dependencies import Dependencies + +#: A row identifier: ``(table name, primary-key tuple)``. +Row = tuple +#: A database: ``{table: {pk_tuple: row_dict}}``. +DB = dict + + +# ============================================================================= +# Schema +# ============================================================================= + + +@dataclass(frozen=True) +class TableSpec: + """ + One table of a model schema. + + Parameters + ---------- + name : str + Table name. A part's name is ``__``, as in DataJoint, so + that ``datajoint.dependencies.extract_master`` recognizes it. + pk : tuple[str, ...] + Primary-key attributes, in order. + secondary : tuple[str, ...], optional + Secondary attributes. + master : str, optional + Name of the master table if this table is a part. + """ + + name: str + pk: tuple[str, ...] + secondary: tuple[str, ...] = () + master: str | None = None + + @property + def heading(self) -> tuple[str, ...]: + """All attributes: the primary key, then the secondary attributes.""" + return self.pk + self.secondary + + +@dataclass(frozen=True) +class FK: + """ + One foreign key, an edge ``parent -> child`` of the dependency graph. + + Parameters + ---------- + child : str + The referencing table. + parent : str + The referenced table. + attr_map : dict[str, str] + Maps each child attribute of the FK to the parent primary-key attribute + it references. An unrenamed FK maps every attribute to itself. + nullable : bool, optional + Whether the FK was declared ``-> [nullable]``. The attributes it + introduces may then hold NULL. + """ + + child: str + parent: str + attr_map: Mapping[str, str] = field(hash=False) + nullable: bool = False + + @property + def renamed(self) -> bool: + """True if any child attribute has a different name in the parent.""" + return any(c != p for c, p in self.attr_map.items()) + + +class Schema: + """ + Tables in declaration order and the foreign keys between them. + + Parameters + ---------- + tables : iterable of TableSpec + Tables in declaration order. + fks : iterable of FK + Foreign keys. Each child's FKs are listed in declaration order. + + Notes + ----- + Three facts are derived from the declarations: + + - **Nullable attributes.** A secondary attribute is nullable when the first + FK that includes it is nullable, as in ``declare.py``, where an FK adds + only the attributes not declared yet. Primary-key attributes and + attributes outside every FK are never NULL. + - **Owned parts and groups** (A1). A part is owned if an FK in its primary + key (every attribute of the FK in the primary key, as ``Dependencies`` + marks it ``primary``) references the master or an owned part of the same + master, renamed or not. Each master that has parts forms a group with its + owned parts; ``group[t]`` names the master of table ``t`` for the master + and for its owned parts. A part that is not owned is in no group. + - **Owning attributes.** ``owning[t]`` maps each attribute of the master's + key to the attribute of ``t`` that the owning chain maps onto it: the + identity for the master. If a part has several owning references, an + unrenamed ``-> master`` wins, and otherwise the first in its definition. + """ + + def __init__(self, tables: Iterable[TableSpec], fks: Iterable[FK]) -> None: + self.tables = tuple(tables) + self.fks = tuple(fks) + self._by_name = {t.name: t for t in self.tables} + if len(self._by_name) != len(self.tables): + raise ValueError("table names must be unique") + self._validate() + self.nullable = {t.name: self._nullable_attributes(t) for t in self.tables} + self.owned_parts = {} + self.group = {} + self.owning = {} + for t in self.tables: + parts = [p for p in self.tables if p.master == t.name] + if parts: + owning = self._find_owned(t, parts) + self.owned_parts[t.name] = tuple(p.name for p in parts if p.name in owning) + self.owning.update(owning) + self.group.update({name: t.name for name in owning}) + + def __repr__(self) -> str: + lines = ["Schema("] + for t in self.tables: + master = f", master={t.master!r}" if t.master else "" + lines.append(f" TableSpec({t.name!r}, pk={t.pk!r}, secondary={t.secondary!r}{master}),") + for fk in self.fks: + null = ", nullable=True" if fk.nullable else "" + lines.append(f" FK({fk.child!r}, {fk.parent!r}, {dict(fk.attr_map)!r}{null}),") + return "\n".join(lines) + "\n)" + + def table(self, name: str) -> TableSpec: + """Return the table named ``name``.""" + return self._by_name[name] + + def fks_of(self, child: str) -> list[FK]: + """Return the FKs declared in ``child``, in declaration order.""" + return [fk for fk in self.fks if fk.child == child] + + def is_primary(self, fk: FK) -> bool: + """True if every attribute of the FK is in the child's primary key (as in ``Dependencies``).""" + return set(fk.attr_map) <= set(self.table(fk.child).pk) + + def owning_attributes(self, table: str) -> tuple[str, ...] | None: + """Attributes of ``table`` that hold its master's key, in the master's key order; None if in no group.""" + master = self.group.get(table) + if master is None: + return None + return tuple(self.owning[table][a] for a in self.table(master).pk) + + def intra_group_fks(self, master: str) -> list[FK]: + """FKs between two different tables of the group of ``master``.""" + return [ + fk + for fk in self.fks + if fk.child != fk.parent and self.group.get(fk.child) == master and self.group.get(fk.parent) == master + ] + + def _validate(self) -> None: + declared = set() + for t in self.tables: + if not t.pk: + raise ValueError(f"{t.name} has no primary key") + if len(set(t.heading)) != len(t.heading): + raise ValueError(f"{t.name} repeats an attribute") + if t.master is not None: + if t.master not in declared or self.table(t.master).master is not None: + raise ValueError(f"{t.name}: master {t.master} must be a table declared earlier, not a part") + if not t.name.startswith(t.master + "__"): + raise ValueError(f"part {t.name} must be named {t.master}__") + declared.add(t.name) + for fk in self.fks: + child, parent = self.table(fk.child), self.table(fk.parent) + if not set(fk.attr_map) <= set(child.heading): + raise ValueError(f"{fk}: attributes missing from {child.name}") + if sorted(fk.attr_map.values()) != sorted(parent.pk): + raise ValueError(f"{fk}: must map onto the whole primary key of {parent.name}") + + def _nullable_attributes(self, table: TableSpec) -> frozenset[str]: + seen, nullable = set(), set() + for fk in self.fks_of(table.name): + for attr in fk.attr_map: + if attr not in seen: + seen.add(attr) + if fk.nullable and attr not in table.pk: + nullable.add(attr) + return frozenset(nullable) + + def _find_owned(self, master: TableSpec, parts: list[TableSpec]) -> dict[str, dict[str, str]]: + # Parts are taken in declaration order, so an owning reference to another + # part is decided after that part (an FK references a table declared earlier). + owning = {master.name: {a: a for a in master.pk}} + for part in parts: + chains = [fk for fk in self.fks_of(part.name) if fk.parent in owning and self.is_primary(fk)] + if not chains: + continue + unrenamed = [fk for fk in chains if fk.parent == master.name and not fk.renamed] + fk = (unrenamed or chains)[0] + by_parent_attr = {p: c for c, p in fk.attr_map.items()} + owning[part.name] = {a: by_parent_attr[owning[fk.parent][a]] for a in master.pk} + return owning + + +# ============================================================================= +# Databases and references +# ============================================================================= + + +def make_db(schema: Schema, data: Mapping[str, Iterable[tuple]]) -> DB: + """ + Build a database from rows written as tuples in heading order. + + Parameters + ---------- + schema : Schema + The schema. + data : dict[str, iterable of tuple] + For each table, its rows as tuples of the primary-key values followed by + the secondary values. Tables left out are empty. + + Returns + ------- + DB + ``{table: {pk_tuple: row_dict}}``. + """ + db = {t.name: {} for t in schema.tables} + for name, rows in data.items(): + table = schema.table(name) + for values in rows: + if len(values) != len(table.heading): + raise ValueError(f"{name}: expected {table.heading}, got {values}") + row = dict(zip(table.heading, values)) + key = tuple(row[a] for a in table.pk) + if key in db[name]: + raise ValueError(f"{name}: duplicate primary key {key}") + db[name][key] = row + return db + + +def all_rows(db: DB) -> frozenset[Row]: + """Return the identifiers of every row in ``db``.""" + return frozenset((t, k) for t, rows in db.items() for k in rows) + + +def fk_value(schema: Schema, fk: FK, row: Mapping) -> tuple | None: + """ + Return the parent primary key that ``row`` names through ``fk``. + + Returns None if any FK attribute is NULL (A2, MATCH SIMPLE). + """ + by_parent_attr = {p: c for c, p in fk.attr_map.items()} + value = tuple(row[by_parent_attr[a]] for a in schema.table(fk.parent).pk) + return None if any(v is None for v in value) else value + + +def ref_e(schema: Schema, db: DB, fk: FK, row: Mapping) -> Row | None: + """ + Return the parent row that ``row`` references through ``fk``. + + Returns None if the FK value has a NULL (A2) or names no existing row. + """ + value = fk_value(schema, fk, row) + if value is None or value not in db.get(fk.parent, {}): + return None + return (fk.parent, value) + + +def master_of(schema: Schema, table: str, row: Mapping) -> Row | None: + """ + ``master(r)``: identifier of the master row of a row in a group. + + The master row is named by the row's owning attributes, which lie in the + primary key and so are never NULL. Returns None for a row in no group. The + identifier is returned whether or not the master row exists. + """ + attrs = schema.owning_attributes(table) + if attrs is None: + return None + return (schema.group[table], tuple(row[a] for a in attrs)) + + +def apply_delete(db: DB, rows: Iterable[Row]) -> DB: + """Return a copy of ``db`` without ``rows``.""" + gone = set(rows) + return {t: {k: r for k, r in table.items() if (t, k) not in gone} for t, table in db.items()} + + +def subdatabase(db: DB, rows: Iterable[Row]) -> DB: + """Return the database that holds only ``rows`` (an export of them).""" + keep = set(rows) + return {t: {k: r for k, r in table.items() if (t, k) in keep} for t, table in db.items()} + + +# ============================================================================= +# Integrity checkers +# ============================================================================= + + +def ri_ok(schema: Schema, db: DB) -> bool: + """ + P1, referential integrity: every non-NULL FK value names an existing parent row. + + An FK value with any NULL attribute names nothing (A2) and is not checked. + """ + for fk in schema.fks: + parent_rows = db.get(fk.parent, {}) + for row in db.get(fk.child, {}).values(): + value = fk_value(schema, fk, row) + if value is not None and value not in parent_rows: + return False + return True + + +def group_whole(schema: Schema, db: DB) -> bool: + """ + The static half of P2: no part row exists without its master row. + + This is a property of one database state. P2 for a delete is stronger: the + delete must remove each master-part instance whole or not at all, which + ``RowGraph.group_closed`` checks on the deleted rows. Removing one part row + of an instance leaves a database that still passes this check, yet breaks + P2. For owned parts the check also follows from ``ri_ok``, since each part + row references its master along its owning chain. + """ + for table, master in schema.group.items(): + if table == master: + continue + for row in db.get(table, {}).values(): + m = master_of(schema, table, row) + if m[1] not in db.get(master, {}): + return False + return True + + +def quotient(schema: Schema) -> nx.DiGraph: + """ + The group quotient Q: the FK graph with each master-part group contracted to one node. + + FKs between two tables of the same group are left out. A part that is not + owned is in no group and stays its own node. A self-referencing FK is a + self-loop, which counts as a cycle. + """ + node = {t.name: schema.group.get(t.name, t.name) for t in schema.tables} + q = nx.DiGraph() + q.add_nodes_from(set(node.values())) + for fk in schema.fks: + u, v = node[fk.parent], node[fk.child] + if u != v or fk.parent == fk.child: + q.add_edge(u, v) + return q + + +def q_acyclic(schema: Schema) -> bool: + """True if the group quotient Q is acyclic.""" + return nx.is_directed_acyclic_graph(quotient(schema)) + + +def table_reach(schema: Schema, tables: Iterable[str], direction: str = "down", group_step: bool = True) -> frozenset: + """ + The node set of an expanded diagram: the table-level reach of ``tables``. + + The tables reached by following FKs in the direction of travel, together + with the master and all owned parts of every group that has a reached + member. ``group_step=False`` leaves the group step out (``D1``). For + ``"both"``, it is the upward reach of the downward reach. + """ + if direction == "both": + return table_reach(schema, table_reach(schema, tables, "down", group_step), "up", group_step) + if direction not in ("down", "up"): + raise ValueError(f"direction must be 'down', 'up' or 'both', not {direction!r}") + seen = set(tables) + stack = list(seen) + while stack: + t = stack.pop() + if direction == "down": + nxt = {fk.child for fk in schema.fks if fk.parent == t} + else: + nxt = {fk.parent for fk in schema.fks if fk.child == t} + if group_step and t in schema.group: + master = schema.group[t] + nxt |= {master, *schema.owned_parts[master]} + for n in nxt - seen: + seen.add(n) + stack.append(n) + return frozenset(seen) + + +# ============================================================================= +# Row relations and the operations +# ============================================================================= + + +class PartIntegrityError(Exception): + """``part_integrity="enforce"`` refuses a delete that would split an instance.""" + + +class RowGraph: + """ + The row relations of one database and the closures over them. + + Parameters + ---------- + schema : Schema + The schema. + db : DB + The database. + + Notes + ----- + - ``child(r) = {c : ref_e(c) = r}`` and ``parent(r) = {ref_e(r)}``, over + every FK edge e. + - ``inst(r)`` is the master-part instance of a row in a group: the master + row and every owned part row whose owning attributes hold the same master + key. For a row in no group, ``inst(r) = {r}``. + - ``down = child ∪ inst`` and ``up = parent ∪ inst``, so ``up`` is the + converse of ``down``. + """ + + def __init__(self, schema: Schema, db: DB) -> None: + self.schema = schema + self.db = db + self.rows = all_rows(db) + self._parents = {r: set() for r in self.rows} + self._children = {r: set() for r in self.rows} + for fk in schema.fks: + for key, row in db.get(fk.child, {}).items(): + ref = ref_e(schema, db, fk, row) + if ref is not None: + self._parents[(fk.child, key)].add(ref) + self._children[ref].add((fk.child, key)) + # Instances are keyed by the master row's identifier, which exists in a + # consistent database; the key works even when it does not. + instances = defaultdict(set) + self._master = {} + for table, rows in db.items(): + for key, row in rows.items(): + m = master_of(schema, table, row) + if m is not None: + self._master[(table, key)] = m + instances[m].add((table, key)) + self._inst = {r: frozenset(instances[m]) for r, m in self._master.items()} + + def _check(self, rows: Iterable[Row]) -> set[Row]: + rows = set(rows) + unknown = rows - self.rows + if unknown: + raise ValueError(f"rows not in the database: {sorted(unknown)}") + return rows + + # --- relations ----------------------------------------------------------- + + def child(self, r: Row) -> frozenset[Row]: + """Rows that reference ``r`` through some FK.""" + return frozenset(self._children[r]) + + def parent(self, r: Row) -> frozenset[Row]: + """Rows that ``r`` references through some FK.""" + return frozenset(self._parents[r]) + + def inst(self, r: Row) -> frozenset[Row]: + """The master-part instance of ``r``; ``{r}`` for a row in no group.""" + return self._inst.get(r, frozenset({r})) + + def master(self, r: Row) -> Row | None: + """``master(r)`` for a row in a group, else None.""" + return self._master.get(r) + + def down(self, r: Row) -> frozenset[Row]: + """``down = child ∪ inst``.""" + return self.child(r) | self.inst(r) + + def up(self, r: Row) -> frozenset[Row]: + """``up = parent ∪ inst``.""" + return self.parent(r) | self.inst(r) + + # --- operations ---------------------------------------------------------- + + def closure(self, seed: Iterable[Row], step: Callable[[Row], Iterable[Row]]) -> frozenset[Row]: + """The least superset of ``seed`` closed under ``step``, by breadth-first search.""" + seen = self._check(seed) + queue = deque(seen) + while queue: + for s in step(queue.popleft()): + if s not in seen: + seen.add(s) + queue.append(s) + return frozenset(seen) + + def D(self, seed: Iterable[Row]) -> frozenset[Row]: + """``expand(seed, "down")``: the closure under ``down``.""" + return self.closure(seed, self.down) + + def D1(self, seed: Iterable[Row]) -> frozenset[Row]: + """The closure under ``child`` alone, with no group rule.""" + return self.closure(seed, self.child) + + def U(self, seed: Iterable[Row]) -> frozenset[Row]: + """``expand(seed, "up")``: the closure under ``up``.""" + return self.closure(seed, self.up) + + def both(self, seed: Iterable[Row]) -> frozenset[Row]: + """``expand(seed, "both") = U(D(seed))``.""" + return self.U(self.D(seed)) + + def delete(self, seed: Iterable[Row], part_integrity: str = "enforce") -> frozenset[Row]: + """ + The rows ``delete(part_integrity=...)`` removes. + + ``"cascade"`` deletes D(S) and ``"ignore"`` deletes D1(S). ``"enforce"`` + deletes D1(S) if it is lift-closed, and otherwise raises + ``PartIntegrityError`` before deleting anything, naming a part row and + its master. + """ + if part_integrity == "cascade": + return self.D(seed) + if part_integrity not in ("ignore", "enforce"): + raise ValueError(f"part_integrity must be 'enforce', 'ignore' or 'cascade', not {part_integrity!r}") + rows = self.D1(seed) + if part_integrity == "enforce": + for r in sorted(rows): + m = self._master.get(r) + if m is not None and m != r and m not in rows: + raise PartIntegrityError(f"{r} would be deleted without its master {m}") + return rows + + # --- group predicates ---------------------------------------------------- + + def lift_closed(self, rows: Iterable[Row]) -> bool: + """True if every part row in ``rows`` that belongs to a group has its master row in ``rows``.""" + rows = set(rows) + return all(self._master[r] in rows for r in rows if r in self._master and self._master[r] != r) + + def group_closed(self, rows: Iterable[Row]) -> bool: + """ + True if ``rows`` takes every master-part instance it touches whole. + + This is P2 for an operation: a delete or an export of ``rows`` keeps + each instance whole if and only if this holds. + """ + rows = set(rows) + return all(self.inst(r) <= rows for r in rows) + + +# ============================================================================= +# The one pass over the group quotient +# ============================================================================= + + +def preserves_instance(schema: Schema, fk: FK) -> bool: + """ + True if an FK inside a group maps the referencing part's owning attributes + onto the referenced table's owning attributes, so it stays in the instance. + + A group iterates if and only if some FK inside it does not. + """ + master = schema.group[fk.child] + child_owning, parent_owning = schema.owning[fk.child], schema.owning[fk.parent] + return all(fk.attr_map.get(child_owning[a]) == parent_owning[a] for a in schema.table(master).pk) + + +def iterates(schema: Schema, master: str) -> bool: + """Whether the group of ``master`` iterates: some FK inside it does not preserve the instance.""" + return not all(preserves_instance(schema, fk) for fk in schema.intra_group_fks(master)) + + +def one_pass( + schema: Schema, db: DB, seed: Iterable[Row], direction: str = "down", iterate: bool = True +) -> tuple[frozenset[Row], dict]: + """ + The engine's computation, evaluated on rows: one visit per node of Q. + + The nodes of Q are visited in topological order for ``"down"`` and in + reverse order for ``"up"``. A plain table takes its seed rows and the rows + that R1 reaches from its neighbors on the incoming side. A group takes the + master keys of its seed rows and of the rows R1 reaches in any of its tables + (the lift, through the owning attributes), then all rows of those instances + (the re-expansion). A group that iterates repeats the group step, following + the FKs inside the group, until no new master key appears. + + Parameters + ---------- + schema, db : Schema, DB + The schema, whose Q must be acyclic, and the database. + seed : iterable of Row + The seed rows. + direction : {"down", "up"} + The direction of travel. + iterate : bool + Whether the groups that ``iterates`` selects repeat the group step. With + False, every group takes one step. + + Returns + ------- + rows : frozenset + The rows reached. They equal D(seed) or U(seed) when the computation is exact. + rounds : dict + For each group, the master keys after each group step. + """ + q = quotient(schema) + if not nx.is_directed_acyclic_graph(q): + raise ValueError("the group quotient has a cycle") + graph = RowGraph(schema, db) + seed = graph._check(seed) + order = list(nx.topological_sort(q)) + if direction == "up": + order.reverse() + node_of = {t.name: schema.group.get(t.name, t.name) for t in schema.tables} + members = defaultdict(list) + for t in schema.tables: + members[node_of[t.name]].append(t.name) + + def rows_of(table): + return {(table, k) for k in db[table]} + + def ref(fk, r): + return ref_e(schema, db, fk, db[r[0]][r[1]]) + + def crossing(fk, reached): + # R1 across one FK: children of reached parents (down) or parents of reached children (up). + if direction == "down": + return {c for c in rows_of(fk.child) if ref(fk, c) in reached} + return {p for c in reached if c[0] == fk.child for p in [ref(fk, c)] if p is not None} + + reached, rounds = set(), {} + for node in order: + mem = members[node] + incoming = {r for r in seed if r[0] in mem} + for fk in schema.fks: + inside = fk.child if direction == "down" else fk.parent + outside = fk.parent if direction == "down" else fk.child + if inside in mem and node_of[outside] != node: + incoming |= crossing(fk, reached) + if node not in schema.owned_parts: + reached |= incoming + continue + inner = schema.intra_group_fks(node) + repeat = iterate and iterates(schema, node) + keys = {graph.master(r) for r in incoming} + history = [set(keys)] + while True: + instance = {r for t in mem for r in rows_of(t) if graph.master(r) in keys} + if not repeat: + break + step = set().union(*(crossing(fk, instance) for fk in inner)) + grown = keys | {graph.master(r) for r in step} + if grown == keys: + break + keys = grown + history.append(set(keys)) + rounds[node] = history + reached |= instance + return frozenset(reached), rounds + + +# ============================================================================= +# Conditions: R1 copies and relabeled keys +# ============================================================================= + + +@dataclass(frozen=True) +class Relation: + """ + A query expression used as a condition: rows over ``heading``. + + Restricting a table by it keeps the rows whose values on the shared + attributes appear in it; with no shared attribute, it keeps every row if it + has any rows. + """ + + heading: tuple[str, ...] + rows: frozenset = frozenset() + + +@dataclass(frozen=True) +class Not: + """ + The complement of a condition: ``table - cond``, or ``table & dj.Not(cond)``. + + The complement of a relation follows SQL's ``NOT IN``: a NULL on either side + makes it unknown, so the row is not kept. With several shared attributes, + any NULL counts as unknown, which is exact for one shared attribute. + """ + + cond: object + + +def condition_attributes(cond) -> frozenset[str]: + """The attributes a condition names: a dict's keys, a relation's heading.""" + if isinstance(cond, dict): + return frozenset(cond) + if isinstance(cond, (list, tuple)): + return frozenset().union(*(condition_attributes(c) for c in cond)) if cond else frozenset() + if isinstance(cond, Relation): + return frozenset(cond.heading) + if isinstance(cond, Not): + return condition_attributes(cond.cond) + raise TypeError(f"unsupported condition {cond!r}") + + +def satisfies(row: Mapping, heading: tuple[str, ...], cond) -> bool: + """ + Whether ``row`` of a table with ``heading`` passes the restriction by ``cond``. + + As in DataJoint: a dict compares the keys that are attributes of the table + and ignores the others, and None matches only NULL; a list is the OR of its + elements, so the empty list matches nothing. + """ + if isinstance(cond, dict): + return all(row[k] == v for k, v in cond.items() if k in heading) + if isinstance(cond, (list, tuple)): + return any(satisfies(row, heading, c) for c in cond) + if isinstance(cond, Relation): + shared = [i for i, a in enumerate(cond.heading) if a in heading] + if not shared: + return bool(cond.rows) + value = tuple(row[cond.heading[i]] for i in shared) + return None not in value and value in {tuple(r[i] for i in shared) for r in cond.rows} + if isinstance(cond, Not): + inner = cond.cond + if isinstance(inner, Relation): + shared = [i for i, a in enumerate(inner.heading) if a in heading] + if shared and inner.rows: + value = [row[inner.heading[i]] for i in shared] + if None in value or any(r[i] is None for r in inner.rows for i in shared): + return False # x NOT IN (..., NULL) is never true + return not satisfies(row, heading, inner) + raise TypeError(f"unsupported condition {cond!r}") + + +def restrict(schema: Schema, db: DB, table: str, cond) -> frozenset[Row]: + """The rows of ``table`` that pass the restriction by ``cond``.""" + heading = schema.table(table).heading + return frozenset((table, k) for k, row in db[table].items() if satisfies(row, heading, cond)) + + +def r1_down(schema: Schema, db: DB, fk: FK, parent_rows: Iterable[Row]) -> frozenset[Row]: + """R1 downward across ``fk``: the child rows that reference one of ``parent_rows``.""" + parents = set(parent_rows) + return frozenset((fk.child, k) for k, row in db[fk.child].items() if ref_e(schema, db, fk, row) in parents) + + +def r1_up(schema: Schema, db: DB, fk: FK, child_rows: Iterable[Row]) -> frozenset[Row]: + """R1 upward across ``fk``: the parent rows that one of ``child_rows`` references.""" + refs = {ref_e(schema, db, fk, db[fk.child][k]) for t, k in child_rows if t == fk.child} + return frozenset(refs - {None}) + + +def copy_allowed(schema: Schema, fk: FK, cond) -> bool: + """ + R1's rule for copying a parent's condition to the child unchanged. + + The attributes the condition names are among the FK's attributes, the FK is + not renamed, and none of its columns is nullable. + """ + return ( + condition_attributes(cond) <= set(fk.attr_map) and not fk.renamed and not set(fk.attr_map) & schema.nullable[fk.child] + ) + + +def relabel_down(fk: FK, keys: list[dict]) -> list[dict]: + """Relabel parent keys for the child: keep the keys the FK carries, renamed through ``attr_map``.""" + by_parent_attr = {p: c for c, p in fk.attr_map.items()} + return [{by_parent_attr[a]: v for a, v in key.items() if a in by_parent_attr} for key in keys] + + +def relabel_up(fk: FK, keys: list[dict]) -> list[dict]: + """Relabel child keys for the parent: keep the keys the FK carries, renamed through ``attr_map``.""" + return [{fk.attr_map[c]: v for c, v in key.items() if c in fk.attr_map} for key in keys] + + +def relabel_down_allowed(schema: Schema, fk: FK, keys: list[dict]) -> bool: + """ + The Seeds rule for relabeling parent keys downward. + + Every key names, among the parent's attributes, only attributes the FK + carries; and if the FK has a nullable column, every key names all of the + FK's attributes, none of them NULL. + """ + parent = schema.table(fk.parent) + carried = set(fk.attr_map.values()) + if any(set(key) & set(parent.heading) - carried for key in keys): + return False + if not set(fk.attr_map) & schema.nullable[fk.child]: + return True + return all(carried <= set(key) and all(key[a] is not None for a in carried) for key in keys) + + +# ============================================================================= +# self.upstream for a row not inserted yet +# ============================================================================= + + +def relabel(schema: Schema, fk: FK, key: Mapping) -> tuple | None: + """ + ``relabel_e(key)``: the parent primary key named by a child's primary-key values. + + ``fk`` must be a primary FK of the child, so ``key`` holds every one of its + attributes. Returns None if a value is NULL. + """ + return fk_value(schema, fk, key) + + +def virtual_upstream(schema: Schema, db: DB, table: str, key: Mapping) -> frozenset[Row]: + """ + ``self.upstream`` for a row of ``table`` with primary key ``key``, inserted or not. + + ``make()`` runs before its row is inserted, and ``U(∅) = ∅``, so the upstream + of the row is built from its primary FKs instead: the union, over each FK e + whose attributes all lie in the primary key, of + ``U(rows of P_e matching relabel_e(key))``. Secondary FKs are unknown before + the insert and are left out. + + Parameters + ---------- + schema : Schema + The schema. + db : DB + The database. + table : str + The table that ``make()`` fills. + key : dict + The primary-key values of the row. + + Returns + ------- + frozenset + The upstream rows. The row itself is not included. + """ + graph = RowGraph(schema, db) + upstream = frozenset() + for fk in schema.fks_of(table): + if schema.is_primary(fk): + value = relabel(schema, fk, key) + matching = {(fk.parent, value)} if value is not None and value in db.get(fk.parent, {}) else set() + upstream |= graph.U(matching) + return upstream + + +# ============================================================================= +# The dependency graph, built the way Dependencies.load builds it +# ============================================================================= + + +def full_table_name(name: str, quote: str = "`", database: str = "model") -> str: + """Full table name as ``Dependencies`` stores it, e.g. ```model`.`t0__p1```.""" + return f"{quote}{database}{quote}.{quote}{name}{quote}" + + +def dependency_graph(schema: Schema, quote: str = "`", database: str = "model") -> Dependencies: + """ + Build the ``Dependencies`` graph that ``Dependencies.load`` would build for ``schema``. + + Nodes are full table names with a ``primary_key`` attribute. Each FK is one + edge ``parent -> child`` keyed by the tuple of its child attributes, with the + edge attributes ``primary``, ``attr_map``, ``aliased`` and ``multi``. + ``quote`` is the backtick for MySQL or the double quote for PostgreSQL. + """ + graph = Dependencies() # no connection: nodes and edges are added by hand + for t in schema.tables: + graph.add_node(full_table_name(t.name, quote, database), primary_key=set(t.pk)) + for fk in schema.fks: + child_pk = set(schema.table(fk.child).pk) + graph.add_edge( + full_table_name(fk.parent, quote, database), + full_table_name(fk.child, quote, database), + key=tuple(fk.attr_map), + primary=set(fk.attr_map) <= child_pk, + attr_map=dict(fk.attr_map), + aliased=fk.renamed, + multi=set(fk.attr_map) != child_pk, + ) + return graph diff --git a/tests/unit/test_adapters.py b/tests/unit/test_adapters.py index 1e0678150..bcfe6a612 100644 --- a/tests/unit/test_adapters.py +++ b/tests/unit/test_adapters.py @@ -75,6 +75,8 @@ def test_quote_string(self, adapter): # Should handle escaping result = adapter.quote_string("It's a test") assert "It" in result + # Quotes are doubled, not backslash-escaped + assert adapter.quote_string("It's") == "'It''s'" def test_core_type_to_sql_simple(self, adapter): """Test core type mapping for simple types.""" diff --git a/tests/unit/test_blob_decompression.py b/tests/unit/test_blob_decompression.py new file mode 100644 index 000000000..9bca71928 --- /dev/null +++ b/tests/unit/test_blob_decompression.py @@ -0,0 +1,73 @@ +"""Compressed blobs expand only up to the size their header declares.""" + +import tracemalloc +import zlib + +import numpy as np +import pytest + +from datajoint.blob import len_u64, pack, unpack +from datajoint.errors import DataJointError + +PREFIX = b"ZL123\0" + + +def compressed_blob(payload, declared_size=None): + size = len(payload) if declared_size is None else declared_size + return PREFIX + np.uint64(size).tobytes() + zlib.compress(payload) + + +def test_round_trip_compressed(): + value = np.arange(10_000, dtype=np.float64) + blob = pack(value) + assert blob.startswith(PREFIX) + np.testing.assert_array_equal(unpack(blob), value) + + +def test_round_trip_uncompressed(): + assert unpack(pack({"a": [1, 2, 3]}, compress=False)) == {"a": [1, 2, 3]} + + +def test_payload_larger_than_declared_size_is_rejected_without_expanding_it(): + # a short declared size in front of ~100 MB of zeros that compress to ~100 kB + inner = pack(b"x", compress=False) + blob = compressed_blob(inner + bytes(100_000_000), declared_size=len(inner)) + tracemalloc.start() + try: + with pytest.raises(DataJointError, match="size mismatch"): + unpack(blob) + _, peak = tracemalloc.get_traced_memory() + finally: + tracemalloc.stop() + assert peak < 10_000_000 + + +def test_payload_smaller_than_declared_size_is_rejected(): + payload = pack(np.arange(1000), compress=False) + with pytest.raises(DataJointError, match="size mismatch"): + unpack(compressed_blob(payload, declared_size=len(payload) + 1)) + + +def test_zero_declared_size_is_rejected(): + payload = pack(np.arange(1000), compress=False) + with pytest.raises(DataJointError, match="size mismatch"): + unpack(compressed_blob(payload, declared_size=0)) + + +def test_oversized_declared_size_is_rejected(): + payload = pack(np.arange(1000), compress=False) + with pytest.raises(DataJointError, match="size mismatch"): + unpack(compressed_blob(payload, declared_size=2**64 - 1)) + + +def test_truncated_stream_is_rejected(): + payload = pack(np.arange(1000), compress=False) + blob = compressed_blob(payload) + with pytest.raises(DataJointError): + unpack(blob[:-10]) + + +def test_corrupt_stream_is_rejected(): + payload = pack(np.arange(1000), compress=False) + with pytest.raises(DataJointError, match="Corrupt"): + unpack(PREFIX + len_u64(payload) + b"not zlib data") diff --git a/tests/unit/test_condition.py b/tests/unit/test_condition.py index 3200e34c4..6e6be5ecc 100644 --- a/tests/unit/test_condition.py +++ b/tests/unit/test_condition.py @@ -53,6 +53,21 @@ def test_merge_offsets_add(self): merged = top1.merge(top2) assert merged.offset == 7 + @pytest.mark.parametrize( + "first, second, limit, offset", + [ + (Top(limit=2, order_by="id"), Top(limit=None, order_by=None, offset=1), 1, 1), + (Top(limit=2, order_by="id"), Top(limit=5, order_by=None, offset=1), 1, 1), + (Top(limit=2, order_by="id", offset=3), Top(limit=1, order_by=None, offset=1), 1, 4), + (Top(limit=2, order_by="id"), Top(limit=1, order_by=None, offset=5), 0, 5), + (Top(limit=None, order_by="id"), Top(limit=None, order_by=None, offset=2), 999999999999, 2), + ], + ) + def test_merge_offset_stays_within_first_limit(self, first, second, limit, offset): + """The second Top skips rows of the first Top's window and never reaches past its limit.""" + merged = first.merge(second) + assert (merged.limit, merged.offset) == (limit, offset) + def test_merge_preserves_existing_order(self): """Merged Top preserves first Top's ordering.""" top1 = Top(limit=10, order_by=["col1 desc", "col2 asc"]) @@ -93,3 +108,328 @@ def test_invalid_offset_type_raises(self): """Non-integer offset raises TypeError.""" with pytest.raises(TypeError): Top(offset="1") + + +# --------------------------------------------------------------------------- +# Rendering of values in mapping restrictions +# --------------------------------------------------------------------------- + +import datetime # noqa: E402 +import decimal # noqa: E402 +import importlib.util # noqa: E402 +import json # noqa: E402 +import uuid # noqa: E402 +from types import SimpleNamespace # noqa: E402 + +import numpy as np # noqa: E402 + +from datajoint.adapters import get_adapter # noqa: E402 +from datajoint.condition import make_condition, translate_attribute # noqa: E402 +from datajoint.errors import DataJointError # noqa: E402 + +BACKENDS = [ + "mysql", + pytest.param( + "postgresql", + marks=pytest.mark.skipif(importlib.util.find_spec("psycopg2") is None, reason="psycopg2 not installed"), + ), +] + +SPECIAL_CHARACTER_STRINGS = [ + "' OR 1=1 --", + "x' OR '1'='1", + "\\' OR 1=1 -- ", + "\\", + "a\\'b", + "''", + 'it\'s "quoted"', + "50% off", + "%s", + "line\nbreak; DROP TABLE x; --", + "\x00\x1a", +] + + +# JSON return types accepted by previous releases on MySQL or PostgreSQL +VALID_JSON_TYPES = [ + # MySQL JSON_VALUE ... RETURNING + "unsigned", + "signed", + "UNSIGNED INTEGER", + "float", + "double", + "decimal(4, 1)", + "decimal(10,2)", + "char(20)", + "char(20) character set utf8mb4", + "DATETIME", + "datetime(6)", + "date", + "time", + "year", + "json", + # PostgreSQL casts + "integer", + "int", + "int4", + "bigint", + "smallint", + "numeric", + "numeric(10,2)", + "double precision", + "real", + "text", + "varchar(32)", + "character varying(32)", + "boolean", + "bool", + "jsonb", + "timestamp", + "timestamptz", + "timestamp with time zone", + "timestamp(3) without time zone", + "uuid", +] + + +def _fake_expression(backend, names=("name", "car", "uid")): + """Stand-in for a query expression: an adapter and a heading.""" + attributes = {n: SimpleNamespace(uuid=(n == "uid")) for n in names} + heading = type("Heading", (), {"names": list(names), "__getitem__": lambda self, k: attributes[k]})() + return SimpleNamespace(connection=SimpleNamespace(adapter=get_adapter(backend)), heading=heading) + + +def _condition(backend, restriction): + return make_condition(_fake_expression(backend), restriction, set()) + + +def _read_literal(backend, sql, backslash_escapes=None): + """ + Read one quoted string literal at the start of ``sql`` using the backend's rules + (MySQL with backslash escapes; PostgreSQL with standard_conforming_strings on, + where backslashes are escapes only in an E'...' literal). + + ``backslash_escapes=False`` reads a MySQL literal as under NO_BACKSLASH_ESCAPES; + ``backslash_escapes=True`` reads a PostgreSQL literal as with standard_conforming_strings off. + + Returns the literal's value and the text that follows it. + """ + if backslash_escapes is None: + backslash_escapes = backend == "mysql" + if backend == "postgresql" and sql.startswith("E'"): + sql, backslash_escapes = sql[1:], True + assert sql[0] == "'", sql + out, i = [], 1 + while i < len(sql): + c = sql[i] + if c == "\\" and backslash_escapes: + nxt = sql[i + 1] + out.append({"n": "\n", "r": "\r", "0": "\x00", "Z": "\x1a", "t": "\t", "b": "\b"}.get(nxt, nxt)) + i += 2 + elif c == "'": + if sql[i + 1 : i + 2] == "'": + out.append("'") + i += 2 + else: + return "".join(out), sql[i + 1 :] + else: + out.append(c) + i += 1 + raise AssertionError(f"unterminated literal in {sql!r}") + + +def _literal_value(backend, condition, lhs, backslash_escapes=None): + """Value of the single literal compared with ``lhs`` in a one-term condition.""" + sql = condition % () # the driver's parameter substitution turns %% into % + prefix = f" ({lhs}=" + assert sql.startswith(prefix), sql + value, rest = _read_literal(backend, sql[len(prefix) :], backslash_escapes) + assert rest == ")", f"text after the literal: {rest!r}" + return value + + +def _quoted(backend, name): + return get_adapter(backend).quote_identifier(name) + + +def _json_lhs(backend, path): + return translate_attribute(f"car.{path}", get_adapter(backend))[1] + + +@pytest.mark.parametrize("backend", BACKENDS) +class TestRestrictionLiterals: + """Values in mapping restrictions are rendered as single, complete literals.""" + + @pytest.mark.parametrize("value", SPECIAL_CHARACTER_STRINGS) + def test_string_value(self, backend, value): + cond = _condition(backend, {"name": value}) + expected = value if backend == "mysql" else value.replace("\\", "\\\\") + assert _literal_value(backend, cond, _quoted(backend, "name")) == expected + + @pytest.mark.parametrize("value", SPECIAL_CHARACTER_STRINGS) + def test_json_path_string_value(self, backend, value): + cond = _condition(backend, {"car.name": value}) + expected = value if backend == "mysql" else value.replace("\\", "\\\\") + assert _literal_value(backend, cond, _json_lhs(backend, "name")) == expected + + @pytest.mark.parametrize("value", SPECIAL_CHARACTER_STRINGS) + def test_list_value(self, backend, value): + items = [value, 1, 'a"b', "c'd"] + cond = _condition(backend, {"car.tags": items}) + assert _literal_value(backend, cond, _json_lhs(backend, "tags")) == str(items) + + @pytest.mark.parametrize("value", SPECIAL_CHARACTER_STRINGS) + def test_json_dict_value(self, backend, value): + obj = {"side": value, value: True, "nested": {"k": [value]}} + cond = _condition(backend, {"car.headlights[1]": obj}) + assert _literal_value(backend, cond, _json_lhs(backend, "headlights[1]")) == json.dumps(obj) + + @pytest.mark.parametrize( + "key", + [ + "car.na'me", + 'car.na"me', + "car.x`) OR 1=1 -- ", + 'car.x") OR 1=1 -- ', + "car.a\\b", + "car.name'] OR 1=1 --", + "car.name OR 1=1", + "car.", + ], + ) + def test_invalid_json_key_rejected(self, backend, key): + with pytest.raises(DataJointError): + _condition(backend, {key: 1}) + + @pytest.mark.parametrize( + "type_spec", + [ + "unsigned) OR (1", + "char(20)) OR (1", + "unsigned) OR sleep(5", + "signed or 1", + "text, 1", + "decimal(4, 1) or 1", + "nonsense", + ], + ) + def test_invalid_json_type_rejected(self, backend, type_spec): + with pytest.raises(DataJointError): + _condition(backend, {f"car.length:{type_spec}": 1}) + + @pytest.mark.parametrize("type_spec", VALID_JSON_TYPES) + def test_valid_json_type_accepted(self, backend, type_spec): + cond = _condition(backend, {f"car.length:{type_spec}": 1}) + assert cond.endswith("=1)") + + @pytest.mark.parametrize("value", [float("nan"), float("inf"), -float("inf"), np.float64("nan"), np.float32("inf")]) + def test_non_finite_number_rejected(self, backend, value): + with pytest.raises(DataJointError, match="non-finite"): + _condition(backend, {"name": value}) + + def test_invalid_json_path_message(self, backend): + with pytest.raises(DataJointError, match="Invalid JSON path `car.na'me`"): + _condition(backend, {"car.na'me": 1}) + + @pytest.mark.parametrize("value", [b"x' OR 1=1 --", object(), {"a": 1}, (1, 2), np.datetime64("2020-01-01"), 1 + 2j]) + def test_unsupported_value_type_rejected(self, backend, value): + with pytest.raises(DataJointError): + _condition(backend, {"name": value}) + + def test_negated_value_with_quote_characters(self, backend): + from datajoint.condition import Not + + cond = make_condition(_fake_expression(backend), Not({"name": "' OR 1=1 --"}), set()) + assert cond.startswith("NOT ") + assert _literal_value(backend, cond[4:], _quoted(backend, "name")) == "' OR 1=1 --" + + +@pytest.mark.parametrize("value", SPECIAL_CHARACTER_STRINGS) +@pytest.mark.parametrize("key", ["name", "car.name", "car.tags", "car.headlights[1]"]) +def test_mysql_literal_closed_without_backslash_escapes(key, value): + """MySQL literals stay closed when read with NO_BACKSLASH_ESCAPES in the session's sql_mode.""" + restriction = {"car.tags": [value, 'a"b', "c'd"], "car.headlights[1]": {"side": value}}.get(key, value) + lhs = _quoted("mysql", key) if key == "name" else _json_lhs("mysql", key.split(".", 1)[1]) + # _literal_value asserts that the literal's closing quote is followed only by ")" + _literal_value("mysql", _condition("mysql", {key: restriction}), lhs, backslash_escapes=False) + + +@pytest.mark.skipif(importlib.util.find_spec("psycopg2") is None, reason="psycopg2 not installed") +@pytest.mark.parametrize("value", SPECIAL_CHARACTER_STRINGS) +def test_postgresql_list_value_without_standard_conforming_strings(value): + """PostgreSQL list values read back exactly when standard_conforming_strings is off.""" + items = [value, 1, 'a"b', "c'd"] + cond = _condition("postgresql", {"car.tags": items}) + assert _literal_value("postgresql", cond, _json_lhs("postgresql", "tags"), backslash_escapes=True) == str(items) + + +@pytest.mark.parametrize("backend", BACKENDS) +@pytest.mark.parametrize( + "restriction, expected", + [ + ({"name": "alpha"}, " ({name}='alpha')"), + ({"name": 5}, " ({name}=5)"), + ({"name": -2.5}, " ({name}=-2.5)"), + ({"name": 1e-20}, " ({name}=1e-20)"), + ({"name": True}, " ({name}=True)"), + ({"name": np.int64(7)}, " ({name}=7)"), + ({"name": np.float64(0.25)}, " ({name}=0.25)"), + ({"name": np.bool_(False)}, " ({name}=False)"), + ({"name": None}, " ({name} IS NULL)"), + ({"name": decimal.Decimal("1.50")}, " ({name}='1.50')"), + ({"name": datetime.date(2020, 1, 2)}, " ({name}='2020-01-02')"), + ({"name": datetime.datetime(2020, 1, 2, 3, 4, 5)}, " ({name}='2020-01-02 03:04:05')"), + ({"name": datetime.time(3, 4, 5)}, " ({name}='03:04:05')"), + ({"car.tire_pressure": [34, 30, 27, 32]}, " ({tire_pressure}='[34, 30, 27, 32]')"), + ({"uid": uuid.UUID(int=255)}, " ({uid}=X'000000000000000000000000000000ff')"), + ], +) +def test_ordinary_values_render_as_before(backend, restriction, expected): + """Values that do not need escaping are rendered exactly as in previous releases.""" + adapter = get_adapter(backend) + names = { + "name": adapter.quote_identifier("name"), + "uid": adapter.quote_identifier("uid"), + "tire_pressure": _json_lhs(backend, "tire_pressure"), + } + assert _condition(backend, restriction) == expected.format(**names) + + +@pytest.mark.parametrize("backend", BACKENDS) +def test_json_path_expression_unchanged(backend): + """JSON paths render as in previous releases.""" + adapter = get_adapter(backend) + if backend == "mysql": + assert translate_attribute("car.headlights[0].side:char(20)", adapter)[1] == ( + "json_value(`car`, _utf8mb4'$.headlights[0].side' returning char(20))" + ) + else: + assert translate_attribute("car.headlights[0].side", adapter)[1] == ( + "jsonb_extract_path_text(\"car\", 'headlights', '0', 'side')" + ) + + +@pytest.mark.parametrize("backend", BACKENDS) +@pytest.mark.parametrize("type_spec", VALID_JSON_TYPES) +def test_json_type_in_projection_and_index(backend, type_spec): + """JSON return types accepted in restrictions are also accepted in projections and index declarations.""" + from datajoint.declare import compile_index + + adapter = get_adapter(backend) + expr = translate_attribute(f"car.length:{type_spec}", adapter)[1] + assert expr.startswith("json_value(" if backend == "mysql" else "(jsonb_extract_path_text(") + index_sql = [] + compile_index(f"index(car.length:{type_spec})", index_sql, adapter) + assert index_sql == [f"index (({expr}))"] + + +@pytest.mark.parametrize("backend", BACKENDS) +@pytest.mark.parametrize("type_spec", ["unsigned) OR (1", "nonsense"]) +def test_invalid_json_type_in_projection_and_index(backend, type_spec): + from datajoint.declare import compile_index + + adapter = get_adapter(backend) + with pytest.raises(DataJointError): + translate_attribute(f"car.length:{type_spec}", adapter) + with pytest.raises(DataJointError): + compile_index(f"index(car.length:{type_spec})", [], adapter) diff --git a/tests/unit/test_expand_shapes_model.py b/tests/unit/test_expand_shapes_model.py new file mode 100644 index 000000000..910bef785 --- /dev/null +++ b/tests/unit/test_expand_shapes_model.py @@ -0,0 +1,754 @@ +""" +The Traversal Shape Catalog, checked against the reference model. + +Each test mirrors one shape of ``traversal-shapes.md`` (datajoint-docs, +``src/reference/specs/``) under the same ID: the same schema, rows and seeds, +and the rows the catalog states, copied from it by hand. The node set of each +result (every table the catalog lists, including those marked *none*) is +checked as the table-level reach. Where the catalog's "Why" makes a claim the +model can express (a copy or a relabeling that would select other rows, the +delete modes, the rounds of an iterating group), that claim is checked too. + +A seed is written as the rows its condition selects, by hand. Where the model +can evaluate the condition (a dict, a list of dicts, a query expression, a +``Not``), the test also checks that it selects those rows. + +Left to the integration suite, because they need a database: + +- K3's string seeds (with and without a subquery) and the ``AndList`` with a + string; the seed kinds the model can express are checked here; +- K4's ``dj.Top`` evaluation; the expansion of the two rows it keeps is checked + here; +- K6's warning for a dict that names no attribute; +- X1, the unloaded downstream schema; +- X2's refusal at declaration; the cycle in Q that it refuses is checked here. + +Table names are DataJoint's: ``session__trial`` is ``Session.Trial``. +""" + +import networkx as nx +import pytest + +from .expand_model import ( + FK, + Not, + PartIntegrityError, + Relation, + RowGraph, + Schema, + TableSpec, + apply_delete, + copy_allowed, + dependency_graph, + group_whole, + iterates, + make_db, + one_pass, + preserves_instance, + q_acyclic, + r1_down, + relabel_down_allowed, + relabel_up, + restrict, + ri_ok, + subdatabase, + table_reach, +) + + +def rows(spec: dict) -> frozenset: + """Row identifiers from ``{table: [key, ...]}``; a bare value is a one-attribute key.""" + return frozenset((t, k if isinstance(k, tuple) else (k,)) for t, keys in spec.items() for k in keys) + + +class Shape: + """One shape: its schema and rows, and the operations on them.""" + + def __init__(self, tables, fks, data): + self.schema = Schema(tables, fks) + self.db = make_db(self.schema, data) + assert ri_ok(self.schema, self.db) and group_whole(self.schema, self.db), "the shape must be consistent" + self.g = RowGraph(self.schema, self.db) + + def seed(self, table, cond, selected): + """The seed rows, written by hand, after checking that ``table & cond`` selects them.""" + seed = rows({table: selected}) + if cond is not None: + assert restrict(self.schema, self.db, table, cond) == seed + return seed + + def check(self, table, seed, direction, expected): + """``expand(seed, direction)`` returns ``expected``: its rows, and a node for every table it lists.""" + op = {"down": self.g.D, "up": self.g.U, "both": self.g.both}[direction] + assert op(seed) == rows(expected) + assert table_reach(self.schema, {table}, direction) == set(expected) + + def fk(self, child, parent, *attrs): + """The FK from ``child`` to ``parent``, chosen by its child attributes when there are several.""" + (fk,) = [ + f + for f in self.schema.fks + if f.child == child and f.parent == parent and (not attrs or set(attrs) == set(f.attr_map)) + ] + return fk + + +# ============================================================================= +# Foreign-key shapes +# ============================================================================= + + +def test_S1_identity_fk_in_primary_key(): + """traversal-shapes.md, S1. Identity foreign key in the primary key.""" + s = Shape( + [TableSpec("subject", ("subject_id",)), TableSpec("session", ("subject_id", "session_id"))], + [FK("session", "subject", {"subject_id": "subject_id"})], + {"subject": [(1,), (2,)], "session": [(1, 1), (1, 2), (2, 1)]}, + ) + seed = s.seed("subject", {"subject_id": 1}, [1]) + s.check("subject", seed, "down", {"subject": [1], "session": [(1, 1), (1, 2)]}) + seed = s.seed("session", {"session_id": 1}, [(1, 1), (2, 1)]) + s.check("session", seed, "up", {"session": [(1, 1), (2, 1)], "subject": [1, 2]}) + # Why: the condition subject_id = 1 is copied to Session unchanged. + fk, cond = s.fk("session", "subject"), {"subject_id": 1} + assert copy_allowed(s.schema, fk, cond) + assert restrict(s.schema, s.db, "session", cond) == r1_down(s.schema, s.db, fk, rows({"subject": [1]})) + + +def test_S2_secondary_fk(): + """traversal-shapes.md, S2. Secondary foreign key.""" + s = Shape( + [TableSpec("#rig", ("rig_id",)), TableSpec("session", ("session_id",), ("rig_id",))], + [FK("session", "#rig", {"rig_id": "rig_id"})], + {"#rig": [(1,), (2,), (3,)], "session": [(1, 1), (2, 1), (3, 2)]}, + ) + seed = s.seed("#rig", {"rig_id": 1}, [1]) + s.check("#rig", seed, "down", {"#rig": [1], "session": [1, 2]}) + seed = s.seed("session", {"session_id": 3}, [3]) + s.check("session", seed, "up", {"session": [3], "#rig": [2]}) + # Why: downward, rig_id = 1 names only the FK's own non-null attribute, so it is copied. + fk = s.fk("session", "#rig") + assert copy_allowed(s.schema, fk, {"rig_id": 1}) + # Why: relabeling the dict upward would drop session_id and select every rig. + relabeled = relabel_up(fk, [{"session_id": 3}]) + assert relabeled == [{}] + assert restrict(s.schema, s.db, "#rig", relabeled) == rows({"#rig": [1, 2, 3]}) + + +def test_S3_nullable_fk_sharing_a_primary_key_column(): + """traversal-shapes.md, S3. Nullable foreign key sharing a primary-key column.""" + s = Shape( + [ + TableSpec("subject", ("subject_id",)), + TableSpec("surgery", ("subject_id", "surgery_id")), + TableSpec("session", ("subject_id", "session_id"), ("surgery_id",)), + ], + [ + FK("surgery", "subject", {"subject_id": "subject_id"}), + FK("session", "subject", {"subject_id": "subject_id"}), + FK("session", "surgery", {"subject_id": "subject_id", "surgery_id": "surgery_id"}, nullable=True), + ], + { + "subject": [(1,), (2,)], + "surgery": [(1, 1), (1, 2), (2, 1)], + "session": [(1, 1, 1), (1, 2, None), (1, 3, 2), (2, 1, 1)], + }, + ) + assert s.schema.nullable["session"] == {"surgery_id"} # only surgery_id can be NULL + seed = s.seed("surgery", {"subject_id": 1}, [(1, 1), (1, 2)]) + s.check("surgery", seed, "down", {"surgery": [(1, 1), (1, 2)], "session": [(1, 1), (1, 3)]}) + seed = s.seed("session", {"subject_id": 1, "session_id": 2}, [(1, 2)]) + s.check("session", seed, "up", {"session": [(1, 2)], "subject": [1], "surgery": []}) + # Why: the FK has a nullable column, so subject_id = 1 is not copied; a copy + # would also delete session (1, 2) (#1590). Relabeling the keys is refused too. + fk, cond = s.fk("session", "surgery"), {"subject_id": 1} + assert not copy_allowed(s.schema, fk, cond) + assert ("session", (1, 2)) in restrict(s.schema, s.db, "session", cond) + assert not relabel_down_allowed(s.schema, fk, [cond]) + + +def test_S4_renamed_fk(): + """traversal-shapes.md, S4. Renamed foreign key, with an unrelated attribute named neuron_id.""" + s = Shape( + [TableSpec("neuron", ("neuron_id",)), TableSpec("input", ("source_id", "input_id"), ("neuron_id",))], + [FK("input", "neuron", {"source_id": "neuron_id"})], + {"neuron": [(1,), (2,), (3,)], "input": [(1, 1, 2), (1, 2, 3), (2, 1, 1), (3, 1, 1)]}, + ) + seed = s.seed("neuron", {"neuron_id": 1}, [1]) + s.check("neuron", seed, "down", {"neuron": [1], "input": [(1, 1), (1, 2)]}) + seed = s.seed("input", {"source_id": 2, "input_id": 1}, [(2, 1)]) + s.check("input", seed, "up", {"input": [(2, 1)], "neuron": [2]}) + # Why: copying neuron_id = 1 to Input would match the unrelated label. + cond = {"neuron_id": 1} + assert not copy_allowed(s.schema, s.fk("input", "neuron"), cond) + assert restrict(s.schema, s.db, "input", cond) == rows({"input": [(2, 1), (3, 1)]}) + + +def test_S5_parallel_fks(): + """traversal-shapes.md, S5. Parallel foreign keys.""" + s = Shape( + [TableSpec("neuron", ("neuron_id",)), TableSpec("synapse", ("neuron_id", "target_id"))], + [FK("synapse", "neuron", {"neuron_id": "neuron_id"}), FK("synapse", "neuron", {"target_id": "neuron_id"})], + {"neuron": [(1,), (2,), (3,)], "synapse": [(1, 2), (2, 3), (3, 1)]}, + ) + seed = s.seed("neuron", {"neuron_id": 1}, [1]) + s.check("neuron", seed, "down", {"neuron": [1], "synapse": [(1, 2), (3, 1)]}) + s.check("neuron", seed, "both", {"neuron": [1, 2, 3], "synapse": [(1, 2), (3, 1)]}) + up_seed = s.seed("synapse", {"neuron_id": 1, "target_id": 2}, [(1, 2)]) + s.check("synapse", up_seed, "up", {"synapse": [(1, 2)], "neuron": [1, 2]}) + # Why: combining the two FKs with AND selects only synapses from neuron 1 to itself: none. + per_fk = [r1_down(s.schema, s.db, fk, seed) for fk in s.schema.fks] + assert per_fk[0] & per_fk[1] == set() + # Why (and diagram.md, "Why both is U(D(S))"): D(S) ∪ U(S) leaves out neurons 2 and 3, + # so it carries synapse (3, 1) without neuron 3. + union = s.g.D(seed) | s.g.U(seed) + assert union == rows({"neuron": [1], "synapse": [(1, 2), (3, 1)]}) + assert not ri_ok(s.schema, subdatabase(s.db, union)) + + +def test_S6_diamond_with_a_shared_key(): + """traversal-shapes.md, S6. Diamond with a shared key.""" + s = Shape( + [ + TableSpec("subject", ("subject_id",)), + TableSpec("session", ("subject_id", "session_id")), + TableSpec("implant", ("subject_id", "implant_id")), + TableSpec("recording", ("subject_id", "session_id", "implant_id")), + ], + [ + FK("session", "subject", {"subject_id": "subject_id"}), + FK("implant", "subject", {"subject_id": "subject_id"}), + FK("recording", "session", {"subject_id": "subject_id", "session_id": "session_id"}), + FK("recording", "implant", {"subject_id": "subject_id", "implant_id": "implant_id"}), + ], + { + "subject": [(1,), (2,)], + "session": [(1, 1), (1, 2), (2, 1)], + "implant": [(1, 1), (1, 2), (2, 1)], + "recording": [(1, 1, 1), (1, 2, 2), (2, 1, 1)], + }, + ) + seed = s.seed("subject", {"subject_id": 1}, [1]) + s.check( + "subject", + seed, + "down", + { + "subject": [1], + "session": [(1, 1), (1, 2)], + "implant": [(1, 1), (1, 2)], + "recording": [(1, 1, 1), (1, 2, 2)], + }, + ) + seed = s.seed("implant", {"subject_id": 1, "implant_id": 1}, [(1, 1)]) + s.check("implant", seed, "down", {"implant": [(1, 1)], "recording": [(1, 1, 1)]}) + s.check( + "implant", + seed, + "both", + {"implant": [(1, 1)], "recording": [(1, 1, 1)], "subject": [1], "session": [(1, 1)]}, + ) + seed = s.seed("recording", {"subject_id": 1, "session_id": 2, "implant_id": 2}, [(1, 2, 2)]) + s.check( + "recording", + seed, + "up", + {"recording": [(1, 2, 2)], "session": [(1, 2)], "implant": [(1, 2)], "subject": [1]}, + ) + + +def test_S7_diamond_reached_through_a_secondary_fk(): + """traversal-shapes.md, S7. Diamond reached through a secondary foreign key.""" + s = Shape( + [ + TableSpec("lab", ("lab_id",)), + TableSpec("rig", ("rig_id",), ("lab_id",)), + TableSpec("session", ("lab_id", "session_id"), ("rig_id",)), + ], + [ + FK("rig", "lab", {"lab_id": "lab_id"}), + FK("session", "lab", {"lab_id": "lab_id"}), + FK("session", "rig", {"rig_id": "rig_id"}), + ], + {"lab": [(1,), (2,)], "rig": [(10, 1), (20, 2)], "session": [(1, 1, 20), (2, 1, 10), (2, 2, 20)]}, + ) + seed = s.seed("lab", {"lab_id": 1}, [1]) + s.check("lab", seed, "down", {"lab": [1], "rig": [10], "session": [(1, 1), (2, 1)]}) + seed = s.seed("session", {"lab_id": 2, "session_id": 1}, [(2, 1)]) + s.check("session", seed, "up", {"session": [(2, 1)], "rig": [10], "lab": [1, 2]}) + seed = s.seed("rig", {"rig_id": 10}, [10]) + s.check("rig", seed, "both", {"rig": [10], "session": [(2, 1)], "lab": [1, 2]}) + # Why: Rig's condition lab_id = 1 names an attribute that Session's FK to Rig does not + # carry, so it is not copied. A copy would miss session (2, 1), and the delete would + # then break its FK to rig 10. + cond = {"lab_id": 1} + assert not copy_allowed(s.schema, s.fk("session", "rig"), cond) + copied = restrict(s.schema, s.db, "session", cond) + assert copied == rows({"session": [(1, 1)]}) + assert not ri_ok(s.schema, apply_delete(s.db, rows({"lab": [1], "rig": [10]}) | copied)) + + +# ============================================================================= +# Group shapes +# ============================================================================= + + +def test_G1_part_to_master_lift(): + """traversal-shapes.md, G1. Part-to-master lift, and the delete modes.""" + s = Shape( + [ + TableSpec("session", ("session_id",)), + TableSpec("session__trial", ("session_id", "trial_id"), master="session"), + TableSpec("review", ("session_id", "review_id")), + ], + [ + FK("session__trial", "session", {"session_id": "session_id"}), + FK("review", "session", {"session_id": "session_id"}), + ], + { + "session": [(1,), (2,), (3,)], + "session__trial": [(1, 1), (1, 2), (2, 1), (3, 1)], + "review": [(1, 1), (2, 1)], + }, + ) + seed = s.seed("session__trial", {"trial_id": 2}, [(1, 2)]) + down = {"session__trial": [(1, 1), (1, 2)], "session": [1], "review": [(1, 1)]} + s.check("session__trial", seed, "down", down) + s.check("session__trial", seed, "up", {"session__trial": [(1, 1), (1, 2)], "session": [1]}) + # Why: the lift is Session & (Session.Trial & {"trial_id": 2}), only session 1. The + # old upward copy of trial_id = 2 named no attribute of Session and selected every session. + trials = Relation(("session_id", "trial_id"), frozenset({(1, 2)})) + assert restrict(s.schema, s.db, "session", trials) == rows({"session": [1]}) + assert restrict(s.schema, s.db, "session", {"trial_id": 2}) == rows({"session": [1, 2, 3]}) + # The delete modes. + assert s.g.delete(seed, "cascade") == rows(down) + assert s.g.delete(seed, "ignore") == rows({"session__trial": [(1, 2)]}) + with pytest.raises(PartIntegrityError, match="session__trial"): + s.g.delete(seed, "enforce") + + +def test_G2_part_of_part_with_two_chains(): + """traversal-shapes.md, G2. Part-of-part with two chains.""" + s = Shape( + [ + TableSpec("ext", ("ext_id",)), + TableSpec("master", ("master_id",)), + TableSpec("master__q", ("master_id", "q_id"), ("ext_id",), master="master"), + TableSpec("master__p", ("master_id", "p_id"), ("q_id", "ext_id"), master="master"), + ], + [ + FK("master__q", "master", {"master_id": "master_id"}), + FK("master__q", "ext", {"ext_id": "ext_id"}), + FK("master__p", "master", {"master_id": "master_id"}), + FK("master__p", "master__q", {"master_id": "master_id", "q_id": "q_id"}), + FK("master__p", "ext", {"ext_id": "ext_id"}), + ], + { + "ext": [(1,), (2,)], + "master": [(1,), (2,), (3,)], + "master__q": [(1, 10, 1), (2, 20, 2), (3, 30, 2)], + "master__p": [(1, 100, 10, 2), (2, 200, 20, 1), (3, 300, 30, 2)], + }, + ) + seed = s.seed("ext", {"ext_id": 1}, [1]) + s.check( + "ext", + seed, + "down", + {"ext": [1], "master__q": [(1, 10), (2, 20)], "master__p": [(1, 100), (2, 200)], "master": [1, 2]}, + ) + seed = s.seed("master__p", {"master_id": 1, "p_id": 100}, [(1, 100)]) + s.check( + "master__p", + seed, + "up", + {"master__p": [(1, 100)], "master": [1], "master__q": [(1, 10)], "ext": [1, 2]}, + ) + # Why: the lift is one step on master_id, which every part row carries; the + # references inside the group map owning attributes onto owning attributes, + # so the group does not iterate. + assert s.schema.owning_attributes("master__p") == ("master_id",) + assert not iterates(s.schema, "master") + + +def test_G3_second_renamed_fk_to_its_own_master(): + """traversal-shapes.md, G3. A second, renamed foreign key to its own master.""" + s = Shape( + [ + TableSpec("session", ("session_id",)), + TableSpec("session__link", ("session_id", "link_id"), ("other_session",), master="session"), + ], + [ + FK("session__link", "session", {"session_id": "session_id"}), + FK("session__link", "session", {"other_session": "session_id"}), + ], + {"session": [(1,), (2,), (3,)], "session__link": [(1, 1, 2), (3, 1, 1)]}, + ) + seed = s.seed("session__link", {"session_id": 1}, [(1, 1)]) + s.check("session__link", seed, "down", {"session__link": [(1, 1), (3, 1)], "session": [1, 3]}) + s.check("session__link", seed, "up", {"session__link": [(1, 1)], "session": [1, 2]}) + # Why: Link is owned through -> master, so its owning attribute is session_id. + # The second FK maps other_session, not an owning attribute, onto the master's + # key, so the group iterates. One pass alone stops at session 1. + assert s.schema.owning_attributes("session__link") == ("session_id",) + assert not preserves_instance(s.schema, s.fk("session__link", "session", "other_session")) + assert iterates(s.schema, "session") + assert one_pass(s.schema, s.db, seed, "down", iterate=False)[0] == rows({"session__link": [(1, 1)], "session": [1]}) + assert one_pass(s.schema, s.db, seed, "down")[0] == s.g.D(seed) + # With part_integrity="enforce", deleting session 1 raises: link (3, 1) would go without session 3. + with pytest.raises(PartIntegrityError, match=r"session__link.*\(3, 1\)"): + s.g.delete(rows({"session": [1]}), "enforce") + + +def test_G4_renamed_sibling_fk_chained_across_three_instances(): + """traversal-shapes.md, G4. Renamed sibling foreign key, chained across three instances.""" + s = Shape( + [ + TableSpec("run", ("run_id",)), + TableSpec("run__step", ("run_id", "step_id"), master="run"), + TableSpec("run__carry", ("run_id", "carry_id"), ("prev_run", "prev_step"), master="run"), + ], + [ + FK("run__step", "run", {"run_id": "run_id"}), + FK("run__carry", "run", {"run_id": "run_id"}), + FK("run__carry", "run__step", {"prev_run": "run_id", "prev_step": "step_id"}), + ], + { + "run": [(1,), (2,), (3,), (4,)], + "run__step": [(1, 1), (2, 1), (3, 1), (4, 1)], + "run__carry": [(2, 1, 1, 1), (3, 1, 2, 1)], + }, + ) + run1 = s.seed("run", {"run_id": 1}, [1]) + s.check( + "run", + run1, + "down", + {"run": [1, 2, 3], "run__step": [(1, 1), (2, 1), (3, 1)], "run__carry": [(2, 1), (3, 1)]}, + ) + run2 = s.seed("run", {"run_id": 2}, [2]) + s.check("run", run2, "down", {"run": [2, 3], "run__step": [(2, 1), (3, 1)], "run__carry": [(2, 1), (3, 1)]}) + s.check("run", run2, "up", {"run": [1, 2], "run__step": [(1, 1), (2, 1)], "run__carry": [(2, 1)]}) + s.check( + "run", + run2, + "both", + {"run": [1, 2, 3], "run__step": [(1, 1), (2, 1), (3, 1)], "run__carry": [(2, 1), (3, 1)]}, + ) + # Why: one pass over the group would stop at run 1. Carry's reference to Step maps + # prev_run, not Carry's owning attribute run_id, onto Step's owning attribute, so + # the group step repeats: the master keys grow as {1}, {1, 2}, {1, 2, 3}, and a + # fourth round adds nothing. Upward the chain runs the other way, from run 2 back to run 1. + assert not preserves_instance(s.schema, s.fk("run__carry", "run__step")) + assert one_pass(s.schema, s.db, run1, "down", iterate=False)[0] == rows({"run": [1], "run__step": [(1, 1)]}) + found, rounds = one_pass(s.schema, s.db, run1, "down") + assert found == s.g.D(run1) + assert rounds["run"] == [rows({"run": [1]}), rows({"run": [1, 2]}), rows({"run": [1, 2, 3]})] + found, rounds = one_pass(s.schema, s.db, run2, "up") + assert found == s.g.U(run2) + assert rounds["run"] == [rows({"run": [2]}), rows({"run": [1, 2]})] + + +def test_G5_merge_table(): + """traversal-shapes.md, G5. Merge table.""" + s = Shape( + [ + TableSpec("ephys_source", ("ephys_id",)), + TableSpec("imaging_source", ("imaging_id",)), + TableSpec("recording", ("recording_id",)), + TableSpec("recording__ephys", ("recording_id",), ("ephys_id",), master="recording"), + TableSpec("recording__imaging", ("recording_id",), ("imaging_id",), master="recording"), + TableSpec("analysis", ("recording_id",)), + ], + [ + FK("recording__ephys", "recording", {"recording_id": "recording_id"}), + FK("recording__ephys", "ephys_source", {"ephys_id": "ephys_id"}), + FK("recording__imaging", "recording", {"recording_id": "recording_id"}), + FK("recording__imaging", "imaging_source", {"imaging_id": "imaging_id"}), + FK("analysis", "recording", {"recording_id": "recording_id"}), + ], + { + "ephys_source": [(1,), (2,)], + "imaging_source": [(1,)], + "recording": [(1,), (2,), (3,)], + "recording__ephys": [(1, 1), (2, 2)], + "recording__imaging": [(3, 1)], + "analysis": [(1,), (2,), (3,)], + }, + ) + seed = s.seed("analysis", {"recording_id": 1}, [1]) + s.check( + "analysis", + seed, + "up", + { + "analysis": [1], + "recording": [1], + "recording__ephys": [1], + "recording__imaging": [], + "ephys_source": [1], + "imaging_source": [], + }, + ) + seed = s.seed("ephys_source", {"ephys_id": 2}, [2]) + s.check( + "ephys_source", + seed, + "down", + {"ephys_source": [2], "recording__ephys": [2], "recording": [2], "recording__imaging": [], "analysis": [2]}, + ) + # With part_integrity="enforce" that delete raises: the part row would go without its master. + with pytest.raises(PartIntegrityError, match="recording__ephys"): + s.g.delete(seed, "enforce") + + +def test_G6_part_its_master_does_not_own(): + """traversal-shapes.md, G6. A part its master does not own, traversed as a plain table.""" + tables = [TableSpec("probe", ("probe_id",)), TableSpec("probe__channel", ("channel_id",), ("probe_id",), master="probe")] + data = {"probe": [(1,), (2,)], "probe__channel": [(1, 1), (2, 1), (3, 2)]} + s = Shape(tables, [FK("probe__channel", "probe", {"probe_id": "probe_id"})], data) + assert s.schema.owned_parts == {"probe": ()} + seed = s.seed("probe__channel", {"channel_id": 1}, [1]) + s.check("probe__channel", seed, "down", {"probe__channel": [1]}) + s.check("probe__channel", seed, "up", {"probe__channel": [1], "probe": [1]}) + seed = s.seed("probe", {"probe_id": 1}, [1]) + s.check("probe", seed, "down", {"probe": [1], "probe__channel": [1, 2]}) + # A nullable reference, -> [nullable] master, has the same effect. + nullable = Schema(tables, [FK("probe__channel", "probe", {"probe_id": "probe_id"}, nullable=True)]) + assert nullable.owned_parts == {"probe": ()} + # Moving the reference into the primary key, as -> master or renamed as + # -> master.proj(host_id="probe_id"), would make the part owned. + in_key = Schema( + [TableSpec("probe", ("probe_id",)), TableSpec("probe__channel", ("probe_id", "channel_id"), master="probe")], + [FK("probe__channel", "probe", {"probe_id": "probe_id"})], + ) + renamed = Schema( + [TableSpec("probe", ("probe_id",)), TableSpec("probe__channel", ("host_id", "channel_id"), master="probe")], + [FK("probe__channel", "probe", {"host_id": "probe_id"})], + ) + assert in_key.owned_parts == renamed.owned_parts == {"probe": ("probe__channel",)} + assert renamed.owning_attributes("probe__channel") == ("host_id",) + + +def test_G7_owned_part_of_part_with_renamed_attributes(): + """traversal-shapes.md, G7. Owned part-of-part with renamed attributes (#1429, Case 1).""" + s = Shape( + [ + TableSpec("master", ("master_id",)), + TableSpec("master__part_a", ("master_id", "part_a_id"), master="master"), + TableSpec("master__part_b", ("src_master", "src_part", "part_b_id"), master="master"), + TableSpec("report", ("master_id", "report_id")), + ], + [ + FK("master__part_a", "master", {"master_id": "master_id"}), + FK("master__part_b", "master__part_a", {"src_master": "master_id", "src_part": "part_a_id"}), + FK("report", "master", {"master_id": "master_id"}), + ], + { + "master": [(1,), (2,), (3,)], + "master__part_a": [(1, 10), (1, 11), (2, 20)], + "master__part_b": [(1, 10, 100), (1, 11, 110), (2, 20, 200)], + "report": [(1, 1), (2, 1)], + }, + ) + # PartB has no master_id; it is owned through PartA, and its owning attribute is src_master. + assert s.schema.owned_parts == {"master": ("master__part_a", "master__part_b")} + assert s.schema.owning_attributes("master__part_b") == ("src_master",) + seed = s.seed("master__part_b", {"part_b_id": 100}, [(1, 10, 100)]) + s.check( + "master__part_b", + seed, + "down", + { + "master__part_b": [(1, 10, 100), (1, 11, 110)], + "master": [1], + "master__part_a": [(1, 10), (1, 11)], + "report": [(1, 1)], + }, + ) + s.check( + "master__part_b", + seed, + "up", + {"master__part_b": [(1, 10, 100), (1, 11, 110)], "master": [1], "master__part_a": [(1, 10), (1, 11)]}, + ) + # Why: the lift renames the owning attribute onto the master's key, + # Master & R(PartB).proj(master_id="src_master"), and selects master 1 in one step. + lifted = Relation(("master_id",), frozenset({(s.db["master__part_b"][k]["src_master"],) for _, k in seed})) + assert restrict(s.schema, s.db, "master", lifted) == rows({"master": [1]}) + # PartB's reference to PartA maps src_master onto PartA's owning attribute, so the group does not iterate. + assert not iterates(s.schema, "master") + assert one_pass(s.schema, s.db, seed, "down", iterate=False)[0] == s.g.D(seed) + # With part_integrity="enforce", deleting the seed raises: part B row (1, 10, 100) would go without master 1. + with pytest.raises(PartIntegrityError, match=r"master__part_b.*\(1, 10, 100\)"): + s.g.delete(seed, "enforce") + + +# ============================================================================= +# Seed shapes: K1 to K6 share one schema +# ============================================================================= + + +def k_shape(extra_flags=()): + return Shape( + [ + TableSpec("subject", ("subject_id",), ("species",)), + TableSpec("session", ("subject_id", "session_id"), ("quality",)), + TableSpec("trial", ("subject_id", "session_id", "trial_id")), + TableSpec("flag", ("flag_id",), ("subject_id",)), + ], + [ + FK("session", "subject", {"subject_id": "subject_id"}), + FK("trial", "session", {"subject_id": "subject_id", "session_id": "session_id"}), + FK("flag", "subject", {"subject_id": "subject_id"}, nullable=True), + ], + { + "subject": [(1, "mouse"), (2, "rat"), (3, "mouse"), (4, "rat")], + "session": [(1, 1, 0), (1, 2, 1), (2, 1, 1), (2, 2, 0), (3, 1, 1)], + "trial": [(1, 1, 1), (1, 2, 1), (2, 1, 1), (2, 2, 1), (3, 1, 1)], + "flag": [(1, 1), (2, 3), *extra_flags], + }, + ) + + +SESSION = Relation(("subject_id", "session_id", "quality")) +#: ``Session & "quality = 0"``, written out: the sessions of quality 0. +QUALITY_0 = Relation(SESSION.heading, frozenset({(1, 1, 0), (2, 2, 0)})) +ALL_SESSIONS = [(1, 1), (1, 2), (2, 1), (2, 2), (3, 1)] +ALL_TRIALS = [(1, 1, 1), (1, 2, 1), (2, 1, 1), (2, 2, 1), (3, 1, 1)] + + +def test_K1_seed_restricted_by_a_descendant(): + """traversal-shapes.md, K1. Seed restricted by a descendant.""" + s = k_shape() + seed = s.seed("subject", QUALITY_0, [1, 2]) # Subject & (Session & "quality = 0") + s.check( + "subject", + seed, + "down", + { + "subject": [1, 2], + "session": [(1, 1), (1, 2), (2, 1), (2, 2)], + "trial": [(1, 1, 1), (1, 2, 1), (2, 1, 1), (2, 2, 1)], + "flag": [1], + }, + ) + s.check("subject", seed, "up", {"subject": [1, 2]}) + # diagram.md, R1: copied to Session, the seed's condition would select only the + # sessions of quality 0; and the seed Subject - (Session & "quality = 0") would + # select every session of another quality, including sessions of subjects that are + # not deleted. + fk = s.fk("session", "subject") + assert not copy_allowed(s.schema, fk, QUALITY_0) + assert restrict(s.schema, s.db, "session", QUALITY_0) == rows({"session": [(1, 1), (2, 2)]}) + others = s.seed("subject", Not(QUALITY_0), [3, 4]) + assert s.g.D(others) == rows({"subject": [3, 4], "session": [(3, 1)], "trial": [(3, 1, 1)], "flag": [2]}) + assert restrict(s.schema, s.db, "session", Not(QUALITY_0)) == rows({"session": [(1, 2), (2, 1), (3, 1)]}) + + +def test_K2_self_referencing_seed(): + """traversal-shapes.md, K2. Self-referencing seed: its condition reads its own table.""" + s = k_shape() + # Session & (dj.U("subject_id") & (Session & "quality = 0")): the subjects with a session of quality 0. + subjects_with_q0 = Relation(("subject_id",), frozenset({(1,), (2,)})) + seed = s.seed("session", subjects_with_q0, [(1, 1), (1, 2), (2, 1), (2, 2)]) + s.check( + "session", + seed, + "down", + {"session": [(1, 1), (1, 2), (2, 1), (2, 2)], "trial": [(1, 1, 1), (1, 2, 1), (2, 1, 1), (2, 2, 1)]}, + ) + s.check("session", seed, "up", {"session": [(1, 1), (1, 2), (2, 1), (2, 2)], "subject": [1, 2]}) + + +def test_K3_seed_kinds_give_the_same_rows(): + """ + traversal-shapes.md, K3. Seed kinds give the same rows. + + The kinds the model can evaluate are checked to select sessions (2, 1) and + (2, 2); the string kinds need a database. + """ + s = k_shape() + sessions_of_2 = [(2, 1), (2, 2)] + rats = Relation(("subject_id", "species"), frozenset({(2, "rat"), (4, "rat")})) + flags = Relation(("flag_id", "subject_id"), frozenset({(1, 1), (2, 3)})) + for cond in ( + {"subject_id": 2}, + [{"subject_id": 2, "session_id": 1}, {"subject_id": 2, "session_id": 2}], + rats, # Session & (Subject & {"species": "rat"}) + Not(flags), # Session & dj.Not(Flag), or Session - Flag + ): + seed = s.seed("session", cond, sessions_of_2) + s.check("session", seed, "down", {"session": [(2, 1), (2, 2)], "trial": [(2, 1, 1), (2, 2, 1)]}) + s.check("session", seed, "up", {"session": [(2, 1), (2, 2)], "subject": [2]}) + # The NOT IN NULL trap: after inserting Flag (3; NULL), Session & dj.Not(Flag) selects nothing. + s = k_shape(extra_flags=[(3, None)]) + flags = Relation(("flag_id", "subject_id"), frozenset({(1, 1), (2, 3), (3, None)})) + seed = s.seed("session", Not(flags), []) + s.check("session", seed, "down", {"session": [], "trial": []}) + s.check("session", seed, "up", {"session": [], "subject": []}) + + +def test_K4_top_seed(): + """traversal-shapes.md, K4. ``Session & "quality = 1" & dj.Top(2)`` keeps sessions (1, 2) and (2, 1).""" + s = k_shape() + seed = s.seed("session", None, [(1, 2), (2, 1)]) + s.check("session", seed, "down", {"session": [(1, 2), (2, 1)], "trial": [(1, 2, 1), (2, 1, 1)]}) + s.check("session", seed, "up", {"session": [(1, 2), (2, 1)], "subject": [1, 2]}) + + +def test_K5_empty_seeds(): + """traversal-shapes.md, K5. Empty seeds: nothing in, nothing out, and the nodes are present.""" + s = k_shape() + for cond in ([], {"subject_id": 4}, None): # None stands for Session & False + seed = s.seed("session", cond, []) + s.check("session", seed, "down", {"session": [], "trial": []}) + s.check("session", seed, "up", {"session": [], "subject": []}) + + +def test_K6_unrestricted_seed(): + """traversal-shapes.md, K6. Unrestricted seed; a dict naming no attribute of Session means all rows.""" + s = k_shape() + for cond in ({}, {"species": "rat"}): + seed = s.seed("session", cond, ALL_SESSIONS) + s.check("session", seed, "down", {"session": ALL_SESSIONS, "trial": ALL_TRIALS}) + s.check("session", seed, "up", {"session": ALL_SESSIONS, "subject": [1, 2, 3]}) + + +# ============================================================================= +# Graph shapes +# ============================================================================= + + +def test_X2_group_cycle(): + """ + traversal-shapes.md, X2. The cycle in Q that declaring Session.Note would close. + + The refusal itself happens at declaration and is tested with a database. + """ + tables = [ + TableSpec("session", ("session_id",)), + TableSpec("session__trial", ("session_id", "trial_id"), master="session"), + TableSpec("review", ("session_id",)), + ] + fks = [ + FK("session__trial", "session", {"session_id": "session_id"}), + FK("review", "session", {"session_id": "session_id"}), + ] + before = Schema(tables, fks) + assert q_acyclic(before) + dependency_graph(before).topo_sort() + # Session.Note: -> master, then -> Review below the line. Review's key is session_id, + # which Note already holds, so the FK adds no attribute. + after = Schema( + [*tables, TableSpec("session__note", ("session_id",), master="session")], + [ + *fks, + FK("session__note", "session", {"session_id": "session_id"}), + FK("session__note", "review", {"session_id": "session_id"}), + ], + ) + assert after.owned_parts == {"session": ("session__trial", "session__note")} # Note is owned: -> master in its key + assert not q_acyclic(after) # Session -> Review -> Session.Note, which belongs to Session's group + with pytest.raises(nx.NetworkXUnfeasible): + dependency_graph(after).topo_sort() diff --git a/tests/unit/test_expand_spec.py b/tests/unit/test_expand_spec.py new file mode 100644 index 000000000..e1cd31bf1 --- /dev/null +++ b/tests/unit/test_expand_spec.py @@ -0,0 +1,978 @@ +""" +Tests of the ``Diagram.expand`` specification, without a database. + +The traversal specification (the "Traversal specification" section of +``diagram.md`` and the shape catalog ``traversal-shapes.md`` in datajoint-docs) +is tested in three layers that need no database server: + +- ``expand_model.py`` is the reference model: an executable copy of the + definitions. It holds rows in Python dictionaries and computes ``D``, ``D1``, + ``U`` and ``both`` as plain closures over row identifiers. +- This module tests the model against the specification's derived results + T1-T8, on random schemas and databases drawn by Hypothesis, and checks the + specification's computation rules (the one pass over the group quotient, the + groups that iterate, R1's copy rule, relabeling) against the definitions. +- ``test_expand_shapes_model.py`` mirrors the shape catalog one to one: each + shape's schema, rows, seeds and the rows the catalog states, by hand. + +Later layers run the engine against the same model on MySQL and PostgreSQL. + +Running +------- +``pytest tests/unit/test_expand_spec.py tests/unit/test_expand_shapes_model.py``. +``HYPOTHESIS_PROFILE`` selects the number of examples (``tests/conftest.py``): + +- ``dev`` (the default outside CI): 50 examples per property, for quick runs; +- ``ci`` (the default when ``CI`` is set): 500 examples, the same on every run; +- ``thorough``: 2000 random examples; failing examples are saved under the + gitignored ``.hypothesis/`` directory and replayed first on the next run. + +The derived results +------------------- +- T1 closure: D, U and D1 are extensive, monotone and idempotent. +- T2 additivity: ``X(A ∪ B) = X(A) ∪ X(B)`` for D, U, D1 and both. +- T3 duality: ``y ∈ D({x})`` if and only if ``x ∈ U({y})``. +- T4 delete safety: removing D(S) leaves a consistent database consistent, and + D(S) is the least such superset of S. +- T5 read boundary: U(S) is consistent on its own and is the least such superset. +- T6 both: U(D(S)) contains D(S), is up-closed and group-closed, and is the least + such superset; ``both`` is extensive and monotone but not idempotent. +- T7 enforce: D1(S) is lift-closed if and only if D1(S) = D(S). +- T8 ordering: ``datajoint.dependencies.topo_sort`` succeeds if and only if the + group quotient Q is acyclic, and its order is valid. + +Drawn schemas may contain group cycles (Q cyclic), which the declaration check +refuses (#1619). The row-level properties are stated for acyclic Q and discard +the other schemas with ``assume``; T8 tests both cases. A claim the engine does +not meet yet is kept as a strict ``xfail`` with a minimal example. +""" + +from __future__ import annotations + +import itertools +from dataclasses import dataclass, field + +import networkx as nx +import pytest +from hypothesis import assume, find, given, settings +from hypothesis import strategies as st + +from datajoint.dependencies import extract_master +from datajoint.errors import DataJointError + +from .expand_model import ( + DB, + FK, + Not, + PartIntegrityError, + Relation, + RowGraph, + Schema, + TableSpec, + all_rows, + apply_delete, + copy_allowed, + dependency_graph, + fk_value, + full_table_name, + group_whole, + iterates, + make_db, + one_pass, + preserves_instance, + q_acyclic, + r1_down, + r1_up, + relabel_down, + relabel_down_allowed, + relabel_up, + restrict, + ri_ok, + subdatabase, + virtual_upstream, +) + +#: Attribute values are drawn from this many small integers, so that keys collide. +DOMAIN = 3 +#: Tier prefixes of DataJoint table names: manual, lookup, imported, computed. +TIER_PREFIXES = ("", "#", "_", "__") + + +# ============================================================================= +# Generators +# ============================================================================= + + +class _TableBuilder: + """Collects the attributes and FKs of one table while it is drawn.""" + + def __init__(self, name: str, master: str | None = None) -> None: + self.name = name + self.master = master + self.pk: list[str] = [] + self.secondary: list[str] = [] + self.fks: list[FK] = [] + + def has(self, attr: str) -> bool: + return attr in self.pk or attr in self.secondary + + def add_fk(self, parent: TableSpec, primary: bool, renames: dict, nullable: bool = False) -> None: + # An FK adds only the attributes not declared yet, as in declare.py, so + # unrenamed attributes shared with an earlier FK are reused. + attr_map = {} + for attr in parent.pk: + name = renames.get(attr, attr) + attr_map[name] = attr + if not self.has(name): + (self.pk if primary else self.secondary).append(name) + if any(f.parent == parent.name and dict(f.attr_map) == attr_map for f in self.fks): + return # an identical FK adds nothing + self.fks.append(FK(self.name, parent.name, attr_map, nullable=nullable and not primary)) + + def spec(self) -> TableSpec: + return TableSpec(self.name, tuple(self.pk), tuple(self.secondary), self.master) + + +def _draw_renames(draw, parent: TableSpec, fresh: itertools.count, keep: tuple = ()) -> dict: + """Rename none or some of the parent's key attributes, never those in ``keep``.""" + candidates = [a for a in parent.pk if a not in keep] + if not candidates or not draw(st.booleans()): + return {} + renamed = draw(st.sets(st.sampled_from(candidates), min_size=1)) + return {a: f"{a}_r{next(fresh)}" for a in sorted(renamed)} + + +def _descendants(fks: list[FK], names: set[str]) -> set[str]: + """Tables that reference any of ``names``, directly or through other tables.""" + found, frontier = set(), set(names) + while frontier: + frontier = {fk.child for fk in fks if fk.parent in frontier} - found - names + found |= frontier + return found + + +def _draw_fks(draw, tables, fks, fresh, n, solid, group=None) -> list: + """ + Draw ``n`` FKs from the table being built to tables declared earlier. + + A uniform choice of parent rarely makes the shapes that matter, so the + parent is drawn from one of several pools: every table; tables whose key + shares some but not all of its attributes with this table's non-null + attributes ``solid`` (diamonds and, for a nullable FK, partial NULLs); and, + for a part, its own group (renamed references to the master or a sibling), + the parts of other groups, and the tables downstream of its group (group + cycles). + """ + drawn = [] + solid, known = set(solid), set(solid) + for _ in range(n): + kind = draw(st.sampled_from(["primary", "secondary", "nullable"])) + sharing = [t for t in tables if set(t.pk) & solid and not set(t.pk) <= known] + pools = [tables, sharing] + if kind == "nullable": + pools.append(sharing) # twice as likely, to make partial NULLs + if group is not None: + master = group[0] + pools.append([t for t in tables if t.name in group]) + pools.append([t for t in tables if t.master and t.master != master]) + downstream = _descendants(fks, set(group)) + pools.append([t for t in tables if t.name in downstream]) + parent = draw(st.sampled_from(draw(st.sampled_from([p for p in pools if p])))) + renames = _draw_renames(draw, parent, fresh) + attrs = {renames.get(a, a) for a in parent.pk} + if kind != "nullable": + solid |= attrs - known + known |= attrs + drawn.append((parent, kind == "primary", renames, kind == "nullable")) + return drawn + + +def _finish(draw, builder: _TableBuilder, tables: list[TableSpec], fks: list, own_pk: str, force_own: bool) -> TableSpec: + # Primary FKs first, then the table's own key attribute, then secondary FKs, + # as a definition lists them above and below the --- line. + for parent, primary, renames, nullable in fks: + if primary: + builder.add_fk(parent, True, renames) + # Without its own attribute, a table's key is its parents' (one-to-one, as in S1). + if force_own or not builder.pk or draw(st.sampled_from([True, True, False])): + builder.pk.append(own_pk) + for parent, primary, renames, nullable in fks: + if not primary: + builder.add_fk(parent, False, renames, nullable) + # Sometimes add a namesake: an attribute that shares a name with another + # table's key attribute but belongs to no FK. + namesakes = sorted({a for t in tables for a in t.pk if not builder.has(a)}) + if namesakes and draw(st.booleans()): + builder.secondary.append(draw(st.sampled_from(namesakes))) + return builder.spec() + + +@st.composite +def schemas(draw, max_tables: int = 7, owned_only: bool = False) -> Schema: + """ + Draw a schema: tables in declaration order, so the FK graph is a DAG. + + - Each step declares a plain table, a master, or a part of a master declared + earlier, so parts can be added late, after other tables. + - A master has 0-3 parts. A part is owned through ``-> master`` in its + primary key, a renamed one, or a primary-key FK to an owned sibling with + or without renames (#1429). Unless ``owned_only``, a part may also be not + owned: it references the master only below the line, or through a + nullable FK, or through a part that is not owned, or not at all. + - Other FKs are primary or secondary, nullable, renamed and parallel, to any + table declared earlier. Diamonds that share attributes, part -> part across + groups, references inside a group that link instances, and group cycles + all occur. + - Some tables get a namesake attribute that belongs to no FK. + """ + fresh = itertools.count() + tables: list[TableSpec] = [] + fks: list[FK] = [] + parts_of: dict[str, list[str]] = {} + for i in range(draw(st.integers(min(2, max_tables), max_tables))): + by_name = {t.name: t for t in tables} + open_masters = [m for m, parts in parts_of.items() if len(parts) < 3] + kind = draw(st.sampled_from(["plain", "master"] + (["part", "part"] if open_masters else []))) + if kind != "part": + builder = _TableBuilder(f"{draw(st.sampled_from(TIER_PREFIXES))}t{i}") + extra = _draw_fks(draw, tables, fks, fresh, draw(st.integers(0, 3)) if tables else 0, set()) + spec = _finish(draw, builder, tables, extra, own_pk=f"k{i}", force_own=False) + if kind == "master": + parts_of[spec.name] = [] + else: + master = draw(st.sampled_from(open_masters)) + mspec = by_name[master] + builder = _TableBuilder(f"{master}__p{len(parts_of[master])}", master=master) + owned = Schema(tables, fks).owned_parts.get(master, ()) + not_owned = [p for p in parts_of[master] if p not in owned] + owner_modes = ["direct", "renamed"] + (["sibling"] if owned else []) + ways_not_owned = ["secondary", "nullable", "missing"] + (["through a part not owned"] if not_owned else []) + mode = draw(st.sampled_from(owner_modes + ([] if owned_only else ["not owned"]))) + if mode == "not owned": + mode = draw(st.sampled_from(ways_not_owned)) + below_line = [] # a reference to the master below the line + if mode == "direct": + builder.add_fk(mspec, True, {}) + elif mode == "renamed": + renamed = draw(st.sets(st.sampled_from(mspec.pk), min_size=1)) + builder.add_fk(mspec, True, {a: f"{a}_r{next(fresh)}" for a in sorted(renamed)}) + elif mode == "sibling": + sibling = by_name[draw(st.sampled_from(owned))] + builder.add_fk(sibling, True, _draw_renames(draw, sibling, fresh)) + elif mode == "through a part not owned": + other = by_name[draw(st.sampled_from(not_owned))] + builder.add_fk(other, True, _draw_renames(draw, other, fresh)) + elif mode in ("secondary", "nullable"): + below_line = [(mspec, False, {}, mode == "nullable")] + solid = set(builder.pk) | {a for o in below_line if not o[3] for a in o[0].pk} + group = [master] + parts_of[master] + extra = _draw_fks(draw, tables, fks, fresh, draw(st.integers(0, 3)), solid, group) + # With the master referenced below the line, the part needs a key attribute of its own. + spec = _finish(draw, builder, tables, below_line + extra, own_pk=f"k{i}", force_own=bool(below_line)) + parts_of[master].append(spec.name) + tables.append(spec) + fks.extend(builder.fks) + schema = Schema(tables, fks) + if owned_only: + assert all(t.name in schema.group for t in schema.tables if t.master), schema + return schema + + +def _draw_row(draw, schema: Schema, db: DB, table: TableSpec) -> dict | None: + """Draw one row whose FK values name existing parent rows or are NULL; None if no row fits.""" + row = {} + nullable = schema.nullable[table.name] + for fk in schema.fks_of(table.name): + pairs = list(fk.attr_map.items()) + if any(row.get(c, 0) is None for c, _ in pairs): + continue # an earlier FK set a shared attribute to NULL, so this FK references nothing + matches = [p for p in db[fk.parent].values() if all(c not in row or row[c] == p[a] for c, a in pairs)] + can_be_null = any(c in nullable and c not in row for c, _ in pairs) + options = len(matches) + can_be_null + if not options: + return None + choice = draw(st.integers(0, options - 1)) + if choice < len(matches): + row.update({c: matches[choice][a] for c, a in pairs}) + else: + # NULL in the attributes this FK introduced; shared key attributes keep values (partial NULL). + row.update({c: None for c, _ in pairs if c in nullable and c not in row}) + for attr in table.heading: + if attr not in row: + row[attr] = draw(st.integers(0, DOMAIN - 1)) + return row + + +@st.composite +def databases(draw, schema: Schema, max_rows: int = 4) -> DB: + """Draw a consistent database: tables filled in declaration order over small integer domains.""" + db = {} + for table in schema.tables: + rows = {} + for _ in range(draw(st.integers(1, max_rows))): + row = _draw_row(draw, schema, db, table) + if row is not None: + rows.setdefault(tuple(row[a] for a in table.pk), row) + db[table.name] = rows + return db + + +@dataclass +class Case: + """A drawn schema and database, with the row graph built once.""" + + schema: Schema + db: DB + graph: RowGraph = field(repr=False) + + def __repr__(self) -> str: + rows = {t: list(r.values()) for t, r in self.db.items() if r} + return f"Case(\nschema={self.schema!r},\ndb={rows!r})" + + +@st.composite +def cases(draw, max_tables: int = 7, max_rows: int = 4, acyclic: bool = True, max_total: int | None = None) -> Case: + """Draw a schema and a database. With ``acyclic``, schemas whose Q has a cycle are discarded.""" + schema = draw(schemas(max_tables)) + if acyclic: + assume(q_acyclic(schema)) + db = draw(databases(schema, max_rows)) + if max_total is not None: + assume(len(all_rows(db)) <= max_total) + return Case(schema, db, RowGraph(schema, db)) + + +def seeds(rows) -> st.SearchStrategy: + """Draw a set of seed rows from ``rows``.""" + rows = sorted(rows) + return st.frozensets(st.sampled_from(rows)) if rows else st.just(frozenset()) + + +#: Tiny databases for the brute-force minimality checks (at most 2^8 supersets). +tiny_cases = cases(max_tables=4, max_rows=2, max_total=8) + + +def supersets(rows, seed): + """Every subset of ``rows`` that contains ``seed``.""" + rest = sorted(set(rows) - set(seed)) + for k in range(len(rest) + 1): + for extra in itertools.combinations(rest, k): + yield frozenset(seed) | frozenset(extra) + + +# ============================================================================= +# The generators and the model +# ============================================================================= + + +@given(case=cases(acyclic=False)) +def test_generated_databases_are_consistent(case): + """Every drawn database satisfies P1 and the static half of P2.""" + assert ri_ok(case.schema, case.db) + assert group_whole(case.schema, case.db) + + +@given(case=cases(acyclic=False)) +def test_up_is_the_converse_of_down(case): + """``s ∈ down(r)`` if and only if ``r ∈ up(s)``.""" + g = case.graph + for r in g.rows: + for s in g.down(r): + assert r in g.up(s) + for s in g.up(r): + assert r in g.down(s) + + +def _has_partial_null(case: Case) -> bool: + for fk in case.schema.fks: + for row in case.db[fk.child].values(): + values = [row[c] for c in fk.attr_map] + if None in values and any(v is not None for v in values): + return True + return False + + +def _crosses_instances(case: Case) -> bool: + # A part row references a row of its own group in another master instance. + g = case.graph + for r in g.rows: + for p in g.parent(r): + mr, mp = g.master(r), g.master(p) + if mr and mp and mr[0] == mp[0] and mr != mp: + return True + return False + + +def _owned(s: Schema): + return [t for t in s.tables if t.master and t.name in s.group] + + +def _leaves_instance(s: Schema, fk: FK) -> bool: + master = s.group.get(fk.child) + return master is not None and fk.child != master and fk in s.intra_group_fks(master) and not preserves_instance(s, fk) + + +SCHEMA_FEATURES = { + "group cycle": lambda s: not q_acyclic(s), + "part its master does not own": lambda s: any(t.master and t.name not in s.group for t in s.tables), + "part owned through a sibling": lambda s: any( + not any(fk.parent == t.master and s.is_primary(fk) for fk in s.fks_of(t.name)) for t in _owned(s) + ), + "renamed owning attributes": lambda s: any(s.owning_attributes(t.name) != s.table(t.master).pk for t in _owned(s)), + "FK to the own master that leaves the instance": lambda s: any( + _leaves_instance(s, fk) and fk.parent == s.group[fk.child] for fk in s.fks + ), + "FK to a sibling that leaves the instance": lambda s: any( + _leaves_instance(s, fk) and fk.parent != s.group[fk.child] for fk in s.fks + ), + "part -> part across groups": lambda s: any( + s.table(fk.child).master and s.table(fk.parent).master and s.table(fk.child).master != s.table(fk.parent).master + for fk in s.fks + ), + "parallel FKs": lambda s: any(a.child == b.child and a.parent == b.parent for a, b in itertools.combinations(s.fks, 2)), + "diamond sharing an attribute": lambda s: any( + a.child == b.child and a.parent != b.parent and set(a.attr_map) & set(b.attr_map) + for a, b in itertools.combinations(s.fks, 2) + ), + "nullable FK": lambda s: any(fk.nullable for fk in s.fks), + "namesake attribute": lambda s: any( + a in u.pk + for t in s.tables + for a in t.secondary + if not any(a in fk.attr_map for fk in s.fks_of(t.name)) + for u in s.tables + if u is not t + ), +} + +DATA_FEATURES = { + "partial NULL": _has_partial_null, + "reference across master instances": _crosses_instances, +} + +_FIND_SETTINGS = settings(max_examples=5000, database=None, derandomize=True, deadline=None) + + +@pytest.mark.parametrize("feature", sorted(SCHEMA_FEATURES)) +def test_generator_draws_schema_feature(feature): + """The schema generator reaches every shape that the properties rely on.""" + find(schemas(), SCHEMA_FEATURES[feature], settings=_FIND_SETTINGS) + + +@pytest.mark.parametrize("feature", sorted(DATA_FEATURES)) +def test_generator_draws_data_feature(feature): + """The data generator reaches partial NULLs and references across master instances.""" + find(cases(acyclic=False), DATA_FEATURES[feature], settings=_FIND_SETTINGS) + + +# ============================================================================= +# T1-T3 +# ============================================================================= + + +@given(case=cases(), data=st.data()) +def test_t1_closure(case, data): + """T1: D, U and D1 are extensive, monotone and idempotent.""" + g = case.graph + b = data.draw(seeds(g.rows), label="B") + a = data.draw(seeds(b), label="A ⊆ B") + for op in (g.D, g.U, g.D1): + assert a <= op(a) + assert op(a) <= op(b) + assert op(op(a)) == op(a) + + +@given(case=cases(), data=st.data()) +def test_t2_additivity(case, data): + """T2: X(A ∪ B) = X(A) ∪ X(B) for X in D, U, D1 and both.""" + g = case.graph + a = data.draw(seeds(g.rows), label="A") + b = data.draw(seeds(g.rows), label="B") + for op in (g.D, g.U, g.D1, g.both): + assert op(a | b) == op(a) | op(b) + + +@given(case=cases()) +def test_t3_duality(case): + """T3: y ∈ D({x}) if and only if x ∈ U({y}).""" + g = case.graph + up = {y: g.U({y}) for y in g.rows} + for x in g.rows: + down = g.D({x}) + for y in g.rows: + assert (y in down) == (x in up[y]), (x, y) + + +# ============================================================================= +# T4-T5: delete safety and the read boundary +# ============================================================================= + + +@given(case=cases(), data=st.data()) +def test_t4_delete_safety(case, data): + """T4: removing D(S) leaves the database consistent and takes every master-part instance whole.""" + g = case.graph + s = data.draw(seeds(g.rows), label="S") + d = g.D(s) + after = apply_delete(case.db, d) + assert ri_ok(case.schema, after) + assert group_whole(case.schema, after) + assert g.group_closed(d) + + +@given(case=tiny_cases, data=st.data()) +def test_t4_minimality(case, data): + """T4: D(S) is the least superset of S whose removal is safe.""" + g = case.graph + s = data.draw(seeds(g.rows), label="S") + safe = [x for x in supersets(g.rows, s) if ri_ok(case.schema, apply_delete(case.db, x)) and g.group_closed(x)] + d = g.D(s) + assert d in safe + assert all(d <= x for x in safe) + + +@given(case=cases(), data=st.data()) +def test_t5_read_boundary(case, data): + """T5: U(S) is consistent on its own and holds every master-part instance it touches whole.""" + g = case.graph + s = data.draw(seeds(g.rows), label="S") + u = g.U(s) + export = subdatabase(case.db, u) + assert ri_ok(case.schema, export) + assert group_whole(case.schema, export) + assert g.group_closed(u) + + +def _self_contained(case, rows) -> bool: + return ri_ok(case.schema, subdatabase(case.db, rows)) and case.graph.group_closed(rows) + + +@given(case=tiny_cases, data=st.data()) +def test_t5_minimality(case, data): + """T5: U(S) is the least superset of S that is consistent on its own.""" + g = case.graph + s = data.draw(seeds(g.rows), label="S") + consistent = [x for x in supersets(g.rows, s) if _self_contained(case, x)] + u = g.U(s) + assert u in consistent + assert all(u <= x for x in consistent) + + +# ============================================================================= +# T6-T7: both and enforce +# ============================================================================= + + +@given(case=cases(), data=st.data()) +def test_t6_both(case, data): + """T6: U(D(S)) contains D(S), is up-closed and group-closed; both is extensive and monotone.""" + g = case.graph + big = data.draw(seeds(g.rows), label="B") + s = data.draw(seeds(big), label="S ⊆ B") + b = g.both(s) + assert g.D(s) <= b + assert g.U(b) == b + assert g.group_closed(b) + assert b <= g.both(b) # extensive, though not idempotent (test_t6_both_is_not_idempotent) + assert b <= g.both(big) + + +@given(case=tiny_cases, data=st.data()) +def test_t6_minimality(case, data): + """T6: U(D(S)) is the least superset of D(S) that is consistent on its own.""" + g = case.graph + d = g.D(data.draw(seeds(g.rows), label="S")) + consistent = [x for x in supersets(g.rows, d) if _self_contained(case, x)] + assert g.U(d) in consistent + assert all(g.U(d) <= x for x in consistent) + + +def test_t6_both_is_not_idempotent(): + """T6: A -> B and A -> C with S = {b} give both(S) = {a, b}, then both(both(S)) = {a, b, c}.""" + schema = Schema( + [TableSpec("a", ("a",)), TableSpec("b", ("b",), ("a",)), TableSpec("c", ("c",), ("a",))], + [FK("b", "a", {"a": "a"}), FK("c", "a", {"a": "a"})], + ) + db = make_db(schema, {"a": [(1,)], "b": [(1, 1)], "c": [(1, 1)]}) + g = RowGraph(schema, db) + a, b, c = ("a", (1,)), ("b", (1,)), ("c", (1,)) + assert g.both({b}) == {a, b} + assert g.both(g.both({b})) == {a, b, c} + + +@given(case=cases(), data=st.data()) +def test_t7_enforce(case, data): + """T7: D1(S) is lift-closed if and only if D1(S) = D(S); enforce deletes D1(S) or raises.""" + g = case.graph + s = data.draw(seeds(g.rows), label="S") + d1, d = g.D1(s), g.D(s) + assert d1 <= d + assert g.lift_closed(d1) == (d1 == d) + if d1 == d: + assert g.delete(s, "enforce") == d + else: + with pytest.raises(PartIntegrityError): + g.delete(s, "enforce") + + +# ============================================================================= +# T8: topo_sort and the group quotient +# ============================================================================= + + +def assert_valid_order(schema: Schema, order: list[str], quote: str = "`") -> None: + """Every parent precedes its children, and each master is followed at once by its owned parts.""" + name = {t.name: full_table_name(t.name, quote) for t in schema.tables} + assert sorted(order) == sorted(name.values()) + pos = {n: i for i, n in enumerate(order)} + for fk in schema.fks: + assert pos[name[fk.parent]] < pos[name[fk.child]], fk + for master, parts in schema.owned_parts.items(): + block = order[pos[name[master]] : pos[name[master]] + 1 + len(parts)] + assert set(block) == {name[master]} | {name[p] for p in parts}, (master, order) + + +@pytest.mark.parametrize("quote", ["`", '"']) +@given(schema=schemas(owned_only=True)) +def test_t8_topo_sort(quote, schema): + """ + T8: topo_sort succeeds if and only if Q is acyclic, and its order is valid. + + The graph is a ``Dependencies`` object filled the way ``Dependencies.load`` + fills it, and sorted by ``datajoint.dependencies.topo_sort``. Both MySQL and + PostgreSQL quoting are used, since ``extract_master`` recognizes parts by name. + Every part is owned here: ``topo_sort`` still groups a part with its master + by name, owned or not (see the two examples below). + """ + graph = dependency_graph(schema, quote) + if q_acyclic(schema): + assert_valid_order(schema, graph.topo_sort(), quote) + else: + # The declaration check (#1619) refuses these schemas; topo_sort raises on them. + with pytest.raises((nx.NetworkXUnfeasible, DataJointError)): + graph.topo_sort() + + +@given(schema=schemas()) +def test_model_part_names_follow_datajoint(schema): + """``extract_master`` finds the master of every part in the model, and of no other table.""" + for quote in ("`", '"'): + for t in schema.tables: + expected = full_table_name(t.master, quote) if t.master else None + assert extract_master(full_table_name(t.name, quote)) == expected + + +TOPO_SORT_GROUPS_BY_NAME = ( + "engine vs docs: datajoint.dependencies.topo_sort groups every part with its master by name; " + "diagram.md (A1, T8) makes a part its master does not own a plain table in topo_sort (#1619)" +) + + +@pytest.mark.xfail(strict=True, reason=TOPO_SORT_GROUPS_BY_NAME) +def test_t8_part_not_owned_q_acyclic(): + """ + Q is acyclic, so topo_sort must succeed. + + M; X references M; part P of M does not reference M, and references X. P is + not owned, so it is a plain table and Q is ``M -> X -> P``. Today + ``topo_sort`` treats P as a part and adds the edge ``X -> M``, a cycle. + """ + schema = Schema( + [TableSpec("m", ("m",)), TableSpec("x", ("x",), ("m",)), TableSpec("m__p", ("p",), ("x",), master="m")], + [FK("x", "m", {"m": "m"}), FK("m__p", "x", {"x": "x"})], + ) + assert schema.owned_parts == {"m": ()} + assert q_acyclic(schema) + assert_valid_order(schema, dependency_graph(schema).topo_sort()) + + +@pytest.mark.xfail(strict=True, reason=TOPO_SORT_GROUPS_BY_NAME) +def test_t8_part_not_owned_q_cyclic(): + """ + Q has a cycle, so topo_sort must raise. + + M; part P1 references M only through a nullable FK, so it is not owned; part + P2 is owned and references P1. Q is ``{M, P2} -> P1 -> {M, P2}``. Today + ``topo_sort`` sees P1 as a part of M by name, adds no edge, and succeeds. + The declaration check refuses P2's reference, since P1 depends on M. + """ + schema = Schema( + [ + TableSpec("m", ("m",)), + TableSpec("m__p1", ("p1",), ("m",), master="m"), + TableSpec("m__p2", ("m", "p2"), ("p1",), master="m"), + ], + [FK("m__p1", "m", {"m": "m"}, nullable=True), FK("m__p2", "m", {"m": "m"}), FK("m__p2", "m__p1", {"p1": "p1"})], + ) + assert schema.owned_parts == {"m": ("m__p2",)} + assert not q_acyclic(schema) + with pytest.raises((nx.NetworkXUnfeasible, DataJointError)): + dependency_graph(schema).topo_sort() + + +# ============================================================================= +# The one pass over Q, and the groups that iterate (diagram.md, Computation) +# ============================================================================= +# ``one_pass`` evaluates the engine's computation on rows: one visit per node of +# Q, the lift through the owning attributes, and the group step repeated for a +# group that iterates. It must give D(S) and U(S). + + +@pytest.mark.parametrize("direction", ["down", "up"]) +@given(case=cases(), data=st.data()) +def test_one_pass_equals_the_closure(direction, case, data): + """One pass over Q, iterating the groups that iterate, gives D(S) and U(S).""" + s = data.draw(seeds(case.graph.rows), label="S") + found, _ = one_pass(case.schema, case.db, s, direction) + assert found == (case.graph.D(s) if direction == "down" else case.graph.U(s)) + + +@pytest.mark.parametrize("direction", ["down", "up"]) +@given(case=cases(), data=st.data()) +def test_one_step_suffices_when_no_group_iterates(direction, case, data): + """When every FK inside every group maps owning attributes onto owning attributes, one step per group suffices.""" + assume(not any(iterates(case.schema, m) for m in case.schema.owned_parts)) + s = data.draw(seeds(case.graph.rows), label="S") + found, _ = one_pass(case.schema, case.db, s, direction, iterate=False) + assert found == (case.graph.D(s) if direction == "down" else case.graph.U(s)) + + +@given(schema=schemas()) +def test_every_fk_inside_a_group_carries_a_master_key(schema): + """An FK references the whole primary key, which holds the referenced table's owning attributes.""" + for master in schema.owned_parts: + for fk in schema.intra_group_fks(master): + assert set(schema.owning[fk.parent].values()) <= set(fk.attr_map.values()) + + +# ============================================================================= +# R1: copying a condition (diagram.md, R1, the edge rule) +# ============================================================================= + + +VALUES = st.sampled_from([0, 1, 2, None]) + + +def key_dicts(names: list[str]) -> st.SearchStrategy: + """A dict over some of ``names``, with values that may be NULL.""" + return st.lists(st.sampled_from(names), unique=True, max_size=3).flatmap( + lambda keys: st.fixed_dictionaries({k: VALUES for k in keys}) + ) + + +def relations(names: list[str]) -> st.SearchStrategy: + """A query expression used as a condition: a few rows over some of ``names``.""" + + def over(heading): + rows = st.frozensets(st.tuples(*[VALUES] * len(heading)), max_size=4) if heading else st.just(frozenset({()})) + return rows.map(lambda r: Relation(tuple(heading), r)) + + return st.lists(st.sampled_from(names), unique=True, max_size=3).flatmap(over) + + +def conditions(names: list[str]) -> st.SearchStrategy: + """A dict, a list of dicts, a query expression (Relation) or a Not, over ``names``.""" + return st.one_of( + key_dicts(names), + st.lists(key_dicts(names), max_size=2), + relations(names), + relations(names).map(Not), + key_dicts(names).map(Not), + ) + + +def _edge_and_names(case: Case, data, copyable: bool): + fks = [fk for fk in case.schema.fks if fk.child != fk.parent] + if copyable: + fks = [fk for fk in fks if not fk.renamed and not set(fk.attr_map) & case.schema.nullable[fk.child]] + assume(fks) + fk = data.draw(st.sampled_from(fks), label="fk") + parent, child = case.schema.table(fk.parent), case.schema.table(fk.child) + # The FK's own attributes, three times as likely as the others. + names = list(fk.attr_map) * 3 + sorted(set(parent.heading) | set(child.heading)) + ["unrelated"] + return fk, names + + +@given(case=cases(), data=st.data()) +def test_r1_copy_rule(case, data): + """ + A condition copied under R1's rule selects the same child rows as the restriction. + + The rule: the attributes the condition names (every key of a dict, the whole + heading of a query expression) are among the FK's attributes, the FK is not + renamed, and none of its columns is nullable. + """ + fk, names = _edge_and_names(case, data, copyable=True) + cond = data.draw(conditions(names), label="condition") + assume(copy_allowed(case.schema, fk, cond)) + parents = restrict(case.schema, case.db, fk.parent, cond) + assert restrict(case.schema, case.db, fk.child, cond) == r1_down(case.schema, case.db, fk, parents) + + +# ============================================================================= +# Relabeling materialized keys (diagram.md, Seeds) +# ============================================================================= + + +@given(case=cases(), data=st.data()) +def test_relabel_down_rule(case, data): + """ + Parent keys relabeled under the Seeds rule select the same child rows as R1. + + The rule: every key names, among the parent's attributes, only attributes + the FK carries; and if the FK has a nullable column, every key names all of + the FK's attributes, none of them NULL. + """ + fk, names = _edge_and_names(case, data, copyable=False) + keys = data.draw(st.lists(key_dicts(names), max_size=3), label="keys") + assume(relabel_down_allowed(case.schema, fk, keys)) + parents = restrict(case.schema, case.db, fk.parent, keys) + relabeled = relabel_down(fk, keys) + assert restrict(case.schema, case.db, fk.child, relabeled) == r1_down(case.schema, case.db, fk, parents) + + +@given(case=cases(), data=st.data()) +def test_relabel_up_for_keys_read_from_the_child(case, data): + """Keys read from child rows that contain all the FK's columns, relabeled, select the referenced parents.""" + fk, _ = _edge_and_names(case, data, copyable=False) + child = case.schema.table(fk.child) + picked = data.draw(st.frozensets(st.sampled_from(sorted(case.db[fk.child])) if case.db[fk.child] else st.nothing())) + extra = data.draw(st.sets(st.sampled_from(child.heading)), label="other attributes") + attrs = set(fk.attr_map) | extra + keys = [{a: case.db[fk.child][k][a] for a in attrs} for k in picked] + relabeled = relabel_up(fk, keys) + referenced = r1_up(case.schema, case.db, fk, {(fk.child, k) for k in picked}) + assert restrict(case.schema, case.db, fk.parent, relabeled) == referenced + + +def test_relabel_rule_refuses_a_key_on_a_secondary_attribute(): + """diagram.md, Seeds: ``Session & {"quality": 0}`` relabels to ``{}`` across Trial's FK and would select every trial.""" + schema = Schema( + [ + TableSpec("subject", ("subject_id",), ("species",)), + TableSpec("session", ("subject_id", "session_id"), ("quality",)), + TableSpec("trial", ("subject_id", "session_id", "trial_id")), + ], + [ + FK("session", "subject", {"subject_id": "subject_id"}), + FK("trial", "session", {"subject_id": "subject_id", "session_id": "session_id"}), + ], + ) + db = make_db( + schema, + { + "subject": [(1, "mouse"), (2, "rat")], + "session": [(1, 1, 0), (1, 2, 1), (2, 2, 0)], + "trial": [(1, 1, 1), (1, 2, 1), (2, 2, 1)], + }, + ) + fk, keys = schema.fks_of("trial")[0], [{"quality": 0}] + assert not relabel_down_allowed(schema, fk, keys) + assert relabel_down(fk, keys) == [{}] + assert restrict(schema, db, "trial", [{}]) == {("trial", k) for k in db["trial"]} # every trial + assert r1_down(schema, db, fk, restrict(schema, db, "session", keys)) == {("trial", (1, 1, 1)), ("trial", (2, 2, 1))} + + +def test_relabel_rule_refuses_a_null_key_value(): + """ + diagram.md, Seeds, on S3's schema: ``Surgery & {"subject_id": 1, "surgery_id": None}`` + selects no surgery but, relabeled, would select session (1, 2; NULL). + """ + schema = Schema( + [ + TableSpec("subject", ("subject_id",)), + TableSpec("surgery", ("subject_id", "surgery_id")), + TableSpec("session", ("subject_id", "session_id"), ("surgery_id",)), + ], + [ + FK("surgery", "subject", {"subject_id": "subject_id"}), + FK("session", "subject", {"subject_id": "subject_id"}), + FK("session", "surgery", {"subject_id": "subject_id", "surgery_id": "surgery_id"}, nullable=True), + ], + ) + db = make_db(schema, {"subject": [(1,)], "surgery": [(1, 1)], "session": [(1, 1, 1), (1, 2, None)]}) + fk, keys = schema.fks_of("session")[1], [{"subject_id": 1, "surgery_id": None}] + assert not relabel_down_allowed(schema, fk, keys) + assert restrict(schema, db, "surgery", keys) == set() + assert restrict(schema, db, "session", relabel_down(fk, keys)) == {("session", (1, 2))} + + +# ============================================================================= +# self.upstream for a row not inserted yet +# ============================================================================= + + +def _rows_outside_parts(case: Case): + # make() fills a plain table or a master (with its parts), never a part on its own. + return sorted(r for r in case.graph.rows if case.schema.table(r[0]).master is None) + + +@given(case=cases(), data=st.data()) +def test_virtual_upstream_does_not_need_the_row(case, data): + """ + ``self.upstream`` is the same before and after the row is inserted. + + Before the insert, the row, its parts and its descendants are absent: + ``db - D({r})``. Its upstream is built from its primary FKs alone. + """ + rows = _rows_outside_parts(case) + assume(rows) + r = data.draw(st.sampled_from(rows), label="r") + table = case.schema.table(r[0]) + key = dict(zip(table.pk, r[1])) + before = apply_delete(case.db, case.graph.D({r})) + upstream = virtual_upstream(case.schema, before, table.name, key) + assert upstream == virtual_upstream(case.schema, case.db, table.name, key) + assert r not in upstream + + +@given(case=cases(), data=st.data()) +def test_virtual_upstream_matches_trace_of_the_inserted_row(case, data): + """ + Once the row exists, ``U({r})`` contains ``self.upstream``. They are equal, + apart from r itself, when r is in no group and all its FKs are primary. + """ + rows = _rows_outside_parts(case) + assume(rows) + r = data.draw(st.sampled_from(rows), label="r") + schema, g = case.schema, case.graph + table = schema.table(r[0]) + upstream = virtual_upstream(schema, case.db, table.name, dict(zip(table.pk, r[1]))) + traced = g.U({r}) + assert upstream <= traced + if table.name not in schema.group and all(schema.is_primary(fk) for fk in schema.fks_of(table.name)): + assert upstream == traced - {r} + + +def test_virtual_upstream_of_a_row_not_inserted(): + """U(∅) = ∅, so the upstream of a row not inserted yet comes from its primary FKs.""" + schema = Schema( + [ + TableSpec("subject", ("subject_id",)), + TableSpec("rig", ("rig_id",)), + TableSpec("session", ("subject_id", "session_id"), ("rig_id",)), + TableSpec("analysis", ("subject_id", "session_id")), + ], + [ + FK("session", "subject", {"subject_id": "subject_id"}), + FK("session", "rig", {"rig_id": "rig_id"}), + FK("analysis", "session", {"subject_id": "subject_id", "session_id": "session_id"}), + ], + ) + db = make_db(schema, {"subject": [(1,), (2,)], "rig": [(7,)], "session": [(1, 1, 7), (2, 1, 7)]}) + assert RowGraph(schema, db).U(set()) == set() + assert virtual_upstream(schema, db, "analysis", {"subject_id": 1, "session_id": 1}) == { + ("session", (1, 1)), + ("subject", (1,)), + ("rig", (7,)), # reached through session's secondary FK, which is known + } + # A key with no matching parent row has an empty upstream. + assert virtual_upstream(schema, db, "analysis", {"subject_id": 1, "session_id": 9}) == set() + + +def test_fk_value_follows_match_simple(): + """A2: an FK value with any NULL names nothing, even when its other attributes match a row.""" + fk = FK("child", "parent", {"a": "a", "b": "b"}, nullable=True) + schema = Schema([TableSpec("parent", ("a", "b")), TableSpec("child", ("a", "c"), ("b",))], [fk]) + assert fk_value(schema, fk, {"a": 1, "b": None, "c": 1}) is None + assert fk_value(schema, fk, {"a": 1, "b": 2, "c": 1}) == (1, 2) diff --git a/tests/unit/test_foreign_key_reference.py b/tests/unit/test_foreign_key_reference.py new file mode 100644 index 000000000..8d4656699 --- /dev/null +++ b/tests/unit/test_foreign_key_reference.py @@ -0,0 +1,172 @@ +"""Foreign key references are parsed and looked up, never evaluated. + +The text after ``->`` names a table in the declaration context: a dotted name +(``Parent``, ``module.Parent``, ``Master.Part``), optionally in parentheses, +instantiated with ``()``, or projected with ``.proj(new_name="old_name")``. +``Table.alter`` re-parses the definition that ``describe()`` builds from names +read back from the database catalog, so that text is only ever read as a name. +""" + +import types + +import pytest + +import datajoint as dj +from datajoint.adapters.mysql import MySQLAdapter +from datajoint.declare import parse_foreign_key_reference, prepare_declare, resolve_foreign_key_reference +from datajoint.errors import DataJointError +from datajoint.table import _one_line, _quoted + + +class Parent(dj.Manual): + definition = """ + parent_id : int32 + """ + + class Part(dj.Part): + definition = """ + -> master + part_id : int32 + """ + + +class Projectable(dj.Manual): + """Records the arguments of proj() instead of building a projection.""" + + definition = """ + projectable_id : int32 + """ + + def proj(self, *args, **kwargs): + self.proj_args = (args, kwargs) + return self + + +module = types.SimpleNamespace(Parent=Parent) + + +@pytest.fixture +def calls(): + return [] + + +@pytest.fixture +def context(calls): + def record(*args, **kwargs): + calls.append((args, kwargs)) + return Parent + + return { + "Parent": Parent, + "Projectable": Projectable, + "module": module, + "master": Parent, + "Größe": Parent, + "record": record, + "__builtins__": __builtins__, + } + + +@pytest.mark.parametrize( + "reference, expected", + [ + ("Parent", Parent), + (" Parent ", Parent), + ("module.Parent", Parent), + ("Parent.Part", Parent.Part), + ("master.Part", Parent.Part), + ("(master)", Parent), + ("(module.Parent).Part", Parent.Part), + ("Größe", Parent), + ("Parent # a trailing comment", Parent), + ], +) +def test_dotted_names_resolve(reference, expected, context): + assert resolve_foreign_key_reference(reference, context) is expected + + +def test_instantiation(context): + assert isinstance(resolve_foreign_key_reference("Parent()", context), Parent) + + +@pytest.mark.parametrize( + "reference, args, kwargs", + [ + ("Projectable.proj(new_id='projectable_id')", (), {"new_id": "projectable_id"}), + ('Projectable().proj(a="b", c="d",)', (), {"a": "b", "c": "d"}), + ("(Projectable).proj('x', a='b')", ("x",), {"a": "b"}), + (r'Projectable.proj(a="say \"hi\"")', (), {"a": 'say "hi"'}), + ], +) +def test_projection_arguments_are_string_literals(reference, args, kwargs, context): + ref = resolve_foreign_key_reference(reference, context) + assert ref.proj_args == (args, kwargs) + + +@pytest.mark.parametrize( + "reference", + [ + "record()", + "(record)()", + "module.Parent.proj(x=record())", + "Parent.proj(**record())", + "Parent.proj(x=record)", + "Parent.proj(x=f'{record()}')", + "[record() for _ in 'a']", + "Parent; record()", + "Parent or record()", + "lambda: record()", + "Parent.delete()", + "Parent.Part('x')", + "Parent.Part.__init__.__globals__", + "Parent.__class__", + "__builtins__", + "__builtins__.open", + "Parent & 'parent_id=1'", + "Parent.proj(a='b', 'c')", + "Parent.proj(a='b', a='c')", + "", + ], +) +def test_other_forms_are_refused(reference, context, calls): + with pytest.raises(DataJointError, match="could not be resolved"): + resolve_foreign_key_reference(reference, context) + assert calls == [] + + +@pytest.mark.parametrize("reference", ["Missing", "module.Missing", "`schema`.`parent`", '"schema"."parent"']) +def test_unknown_names_could_not_be_resolved(reference, context): + with pytest.raises(DataJointError, match="could not be resolved"): + resolve_foreign_key_reference(reference, context) + + +@pytest.mark.parametrize("reference", ["module", "record", "types", "Parent.describe"]) +def test_non_tables_are_refused(reference, context): + with pytest.raises(DataJointError, match="does not name a table|is not defined"): + resolve_foreign_key_reference(reference, context) + + +def test_resolution_leaves_context_unchanged(context): + """eval() would add __builtins__ to the context it is given; lookup does not.""" + del context["__builtins__"] + resolve_foreign_key_reference("Parent", context) + assert "__builtins__" not in context + + +def test_definition_reference_is_not_called(context, calls): + definition = """ + -> record() + id : int32 + """ + with pytest.raises(DataJointError, match="could not be resolved"): + prepare_declare(definition, context, MySQLAdapter()) + assert calls == [] + + +def test_describe_text_stays_on_one_line(): + assert _one_line("first\nsecond\r\nthird") == "first second third" + assert _one_line("") == "" + assert _one_line(None) is None + text = 'a "quoted" \\ value\nwith a line break' + steps = parse_foreign_key_reference("Parent.proj(new={})".format(_quoted(text))) + assert steps == [("name", "Parent"), ("proj", [], {"new": _one_line(text)})] diff --git a/tests/unit/test_npy_cache.py b/tests/unit/test_npy_cache.py new file mode 100644 index 000000000..f94771327 --- /dev/null +++ b/tests/unit/test_npy_cache.py @@ -0,0 +1,128 @@ +"""Tests for the cache directory used by NpyRef.load(mmap_mode=...) on remote stores.""" + +import os +import stat +import tempfile + +import numpy as np +import pytest + +from datajoint.builtin_codecs import npy +from datajoint.builtin_codecs.npy import NpyRef + +posix_only = pytest.mark.skipif(not hasattr(os, "getuid"), reason="requires POSIX file ownership") + + +@pytest.fixture +def tempdir(monkeypatch, tmp_path): + """Point tempfile.gettempdir() at tmp_path and reset the per-process fallback.""" + monkeypatch.setattr(tempfile, "tempdir", str(tmp_path)) + monkeypatch.setattr(npy, "_fallback_mmap_cache_dir", None) + return tmp_path + + +@posix_only +def test_cache_dir_is_per_user_and_private(tempdir): + cache_dir = npy._mmap_cache_dir() + + assert cache_dir == tempdir / f"datajoint_mmap_{os.getuid()}" + st = os.lstat(cache_dir) + assert stat.S_ISDIR(st.st_mode) + assert stat.S_IMODE(st.st_mode) == 0o700 + assert st.st_uid == os.getuid() + + +@posix_only +def test_private_cache_dir_keeps_contents(tempdir): + cache_dir = tempdir / f"datajoint_mmap_{os.getuid()}" + cache_dir.mkdir(mode=0o700) + (cache_dir / "abc.npy").write_bytes(b"cached") + + assert npy._mmap_cache_dir() == cache_dir + assert (cache_dir / "abc.npy").read_bytes() == b"cached" + + +@posix_only +def test_open_cache_dir_restricted_and_cleared(tempdir): + """Files in a directory others could write to are not reused once it is made private.""" + cache_dir = tempdir / f"datajoint_mmap_{os.getuid()}" + cache_dir.mkdir() + os.chmod(cache_dir, 0o777) + (cache_dir / "abc.npy").write_bytes(b"from-another-user") + (cache_dir / "subdir").mkdir() + (cache_dir / "link.npy").symlink_to(tempdir) + + assert npy._mmap_cache_dir() == cache_dir + assert stat.S_IMODE(os.lstat(cache_dir).st_mode) == 0o700 + assert list(cache_dir.iterdir()) == [] + assert tempdir.is_dir() + + +@posix_only +def test_foreign_cache_dir_not_used(tempdir, monkeypatch, caplog): + """A directory at the per-user path owned by someone else is replaced by a new private one.""" + cache_dir = tempdir / f"datajoint_mmap_{os.getuid()}" + cache_dir.mkdir(mode=0o777) + real_lstat = os.lstat + + def fake_lstat(path, *args, **kwargs): + st = real_lstat(path, *args, **kwargs) + if os.fspath(path) == os.fspath(cache_dir): + fields = list(st) + fields[stat.ST_UID] = os.getuid() + 54321 + return os.stat_result(fields) + return st + + monkeypatch.setattr(os, "lstat", fake_lstat) + + with caplog.at_level("WARNING", logger="datajoint"): + used = npy._mmap_cache_dir() + + assert used != cache_dir + assert used.parent == tempdir + st = real_lstat(used) + assert stat.S_IMODE(st.st_mode) == 0o700 + assert st.st_uid == os.getuid() + assert any("not a directory owned by the current user" in r.message for r in caplog.records) + # The replacement is reused for the rest of the session + assert npy._mmap_cache_dir() == used + + +@posix_only +def test_symlink_at_cache_path_not_followed(tempdir): + elsewhere = tempdir / "elsewhere" + elsewhere.mkdir() + cache_dir = tempdir / f"datajoint_mmap_{os.getuid()}" + cache_dir.symlink_to(elsewhere) + + used = npy._mmap_cache_dir() + + assert used not in (cache_dir, elsewhere) + assert stat.S_IMODE(os.lstat(used).st_mode) == 0o700 + + +def test_no_posix_ownership_uses_shared_name(tempdir, monkeypatch): + """Without os.getuid (Windows) the per-user temp directory holds datajoint_mmap.""" + monkeypatch.delattr(os, "getuid", raising=False) + + assert npy._mmap_cache_dir() == tempdir / "datajoint_mmap" + assert (tempdir / "datajoint_mmap").is_dir() + + +def test_remote_mmap_load_uses_cache_dir(tempdir, tmp_path): + arr = np.arange(5, dtype=np.int32) + np.save(tmp_path / "src.npy", arr) + payload = (tmp_path / "src.npy").read_bytes() + + class RemoteBackend: + protocol = "s3" + + def get_buffer(self, path): + return payload + + meta = {"path": "schema/table/key/arr.npy", "store": "s3-store", "dtype": "int32", "shape": [5]} + loaded = NpyRef(meta, RemoteBackend()).load(mmap_mode="r") + + np.testing.assert_array_equal(loaded, arr) + cached = list(npy._mmap_cache_dir().glob("*.npy")) + assert len(cached) == 1 diff --git a/tests/unit/test_objectref.py b/tests/unit/test_objectref.py new file mode 100644 index 000000000..ac3f4d316 --- /dev/null +++ b/tests/unit/test_objectref.py @@ -0,0 +1,53 @@ +"""Unit tests for ObjectRef.""" + +from datetime import datetime, timezone + +import pytest + +from datajoint.objectref import ObjectRef +from datajoint.storage import StorageBackend + + +def _object_ref(spec): + return ObjectRef( + path="_schema/scratch/result/data_abc.txt", + size=5, + hash=None, + ext=".txt", + is_dir=False, + timestamp=datetime.now(timezone.utc), + _backend=StorageBackend(spec), + ) + + +@pytest.mark.parametrize( + ("spec", "prefix"), + [ + ( + {"protocol": "s3", "endpoint": "localhost:9000", "bucket": "bkt", "location": "proj/outbox"}, + "s3://bkt/proj/outbox/", + ), + ({"protocol": "s3", "endpoint": "localhost:9000", "bucket": "bkt"}, "s3://bkt/"), + ({"protocol": "gcs", "bucket": "bkt", "location": "proj"}, "gs://bkt/proj/"), + ({"protocol": "azure", "container": "ctr", "location": "proj"}, "az://ctr/proj/"), + ], +) +def test_full_path_includes_store_location(spec, prefix): + """full_path points where the backend stores the object, location included.""" + ref = _object_ref(spec) + assert ref.full_path == prefix + ref.path + + +@pytest.mark.parametrize( + "spec", + [ + {"protocol": "s3", "endpoint": "localhost:9000", "bucket": "bkt", "location": "proj/outbox"}, + {"protocol": "s3", "endpoint": "localhost:9000", "bucket": "bkt", "location": "proj/outbox/"}, + {"protocol": "gcs", "bucket": "bkt", "location": "proj/"}, + {"protocol": "azure", "container": "ctr", "location": "proj/"}, + ], +) +def test_full_path_matches_backend_url(spec): + """full_path is the URL the backend reads and writes, whatever shape location has.""" + ref = _object_ref(spec) + assert ref.full_path == ref._backend.get_url(ref.path) diff --git a/tests/unit/test_path_confinement.py b/tests/unit/test_path_confinement.py new file mode 100644 index 000000000..0e843f1bd --- /dev/null +++ b/tests/unit/test_path_confinement.py @@ -0,0 +1,432 @@ +"""Stored values cannot direct file access outside the store or the download path. + +Rows written by one user are fetched by others, so a path or file name read back +from the database must not reach files the store or ``download_path`` does not +cover: ```` names must be plain file names, and store paths used by +````, ````, and hash-addressed storage must stay inside the +store location. ``allow_filepath_outside_store`` lifts the store check for +```` only. + +No test reads a device or opens a pipe: a regression must fail, not hang. +""" + +import importlib +import os +import sys + +import pytest + +posix_only = pytest.mark.skipif(sys.platform == "win32", reason="needs POSIX paths and symlinks") + + +@pytest.fixture(autouse=True) +def _live_modules(): + """ + Bind the names below from the currently imported ``datajoint`` package. + + Some unit tests purge ``datajoint`` from ``sys.modules`` and import it again; + names bound at collection time would then refer to stale classes, and + ``pytest.raises(DataJointError)`` would miss the error actually raised. + """ + global AttachCodec, FilepathCodec, ObjectCodec, ObjectRef, DataJointError, Config, StorageBackend + AttachCodec = importlib.import_module("datajoint.builtin_codecs.attach").AttachCodec + FilepathCodec = importlib.import_module("datajoint.builtin_codecs.filepath").FilepathCodec + ObjectCodec = importlib.import_module("datajoint.builtin_codecs.object").ObjectCodec + ObjectRef = importlib.import_module("datajoint.objectref").ObjectRef + DataJointError = importlib.import_module("datajoint.errors").DataJointError + Config = importlib.import_module("datajoint.settings").Config + StorageBackend = importlib.import_module("datajoint.storage").StorageBackend + + +@pytest.fixture +def layout(tmp_path): + """A file store, a sibling directory whose name extends the store's, a file outside both, and a download path.""" + store = tmp_path / "store" + store.mkdir() + (store / "data").mkdir() + (store / "data" / "inside.txt").write_text("inside") + sibling_prefix = tmp_path / "store-sibling" + sibling_prefix.mkdir() + (sibling_prefix / "sibling.txt").write_text("sibling") + (tmp_path / "outside.txt").write_text("outside") + downloads = tmp_path / "downloads" + return tmp_path, store, downloads + + +@pytest.fixture +def cfg(layout): + _, store, downloads = layout + config = Config() + config.stores["local"] = {"protocol": "file", "location": str(store)} + config.stores["default"] = "local" + config.download_path = str(downloads) + return config + + +PATHS_WITH_PARENT_REF = [ + "../outside.txt", + "data/../../outside.txt", + "../store-sibling/sibling.txt", + "..\\outside.txt", + "data/..\\..\\outside.txt", + "data/sub/../inside.txt", + "data/..", +] + + +def _outside_paths(root, store): + """Absolute paths outside the store: a plain outside file and a sibling directory sharing the store's name prefix.""" + return [str(root / "outside.txt"), str(root / "store-sibling" / "sibling.txt"), str(store) + "-sibling/sibling.txt"] + + +# --------------------------------------------------------------------------- # +# StorageBackend._full_path +# --------------------------------------------------------------------------- # +class TestStorePathConfinement: + @pytest.mark.parametrize("path", PATHS_WITH_PARENT_REF + ["data/x\x00y"]) + def test_file_store_rejects_parent_ref_and_nul(self, layout, path): + _, store, _ = layout + backend = StorageBackend({"protocol": "file", "location": str(store)}) + with pytest.raises(DataJointError, match="outside the store location"): + backend._full_path(path) + + @posix_only + def test_file_store_rejects_absolute_paths_outside_location(self, layout): + root, store, _ = layout + backend = StorageBackend({"protocol": "file", "location": str(store)}) + for path in _outside_paths(root, store) + [str(store / "data" / ".." / ".." / "outside.txt")]: + with pytest.raises(DataJointError, match="allow_filepath_outside_store"): + backend._full_path(path) + + @posix_only + def test_file_store_accepts_absolute_paths_inside_location(self, layout): + _, store, _ = layout + backend = StorageBackend({"protocol": "file", "location": str(store)}) + inside = str(store / "data" / "inside.txt") + assert backend._full_path(inside) == inside + assert backend._full_path(str(store) + "/./data//inside.txt") + assert backend.get_buffer(inside) == b"inside" + assert backend._path_in_location(inside) == "data/inside.txt" + assert backend._path_in_location(str(store) + "-sibling/sibling.txt") is None + + @pytest.mark.parametrize("path", ["data/inside.txt", "./data/inside.txt", "data//inside.txt", ""]) + def test_file_store_accepts_relative_paths_inside(self, layout, path): + _, store, _ = layout + backend = StorageBackend({"protocol": "file", "location": str(store)}) + assert backend._full_path(path) == (store / path).as_posix() + + @posix_only + @pytest.mark.parametrize("location", [".", ""]) + def test_file_store_in_working_directory_rejects_protocol_and_home_paths(self, layout, monkeypatch, location): + from fsspec.implementations.local import LocalFileSystem + + root, store, _ = layout + monkeypatch.chdir(store) + monkeypatch.setenv("HOME", str(root)) + backend = StorageBackend({"protocol": "file", "location": location}) + outside = str(root / "outside.txt") + cwd = os.path.realpath(os.getcwd()) + for path in ("file://" + outside, "file:" + outside, "local://" + outside, "local:" + outside, "~/outside.txt"): + try: + full = backend._full_path(path) + except DataJointError as error: + assert "outside the store location" in str(error) + continue + # fsspec before 2024 does not read some of these prefixes as a protocol. A path it + # accepts then names a file inside the working directory, and I/O stays there + assert os.path.realpath(LocalFileSystem._strip_protocol(full)).startswith(cwd + "/") + backend.put_buffer(b"written", path) + assert backend.get_buffer(path) == b"written" + assert (root / "outside.txt").read_text() == "outside" + assert backend.get_buffer("data/inside.txt") == b"inside" + + def test_io_never_reaches_outside(self, layout): + root, store, _ = layout + backend = StorageBackend({"protocol": "file", "location": str(store)}) + with pytest.raises(DataJointError): + backend.get_buffer(str(root / "outside.txt")) + with pytest.raises(DataJointError): + backend.get_buffer("../outside.txt") + with pytest.raises(DataJointError): + backend.put_buffer(b"x", "../written.txt") + with pytest.raises(DataJointError): + backend.remove("../outside.txt") + assert not (root / "written.txt").exists() + assert (root / "outside.txt").exists() + + @pytest.mark.parametrize("protocol", ["s3", "gcs", "azure"]) + def test_object_store_rejects_parent_components(self, protocol): + spec = {"protocol": protocol, "endpoint": "localhost:9000", "bucket": "b", "container": "b", "location": "loc"} + backend = StorageBackend(spec) + for path in ("../x", "a/../../x", "../../other-bucket/x"): + with pytest.raises(DataJointError, match="outside the store location"): + backend._full_path(path) + # Paths inside the location are unchanged, including a leading slash + assert backend._full_path("a/b") == "b/loc/a/b" + assert backend._full_path("/a/b") == "b/loc//a/b" + + def test_confinement_can_be_lifted_per_backend(self, layout): + root, store, _ = layout + backend = StorageBackend({"protocol": "file", "location": str(store)}) + backend.confine_paths = False + assert backend._full_path(str(root / "outside.txt")) == (root / "outside.txt").as_posix() + assert backend.get_buffer("../outside.txt") == b"outside" + # Other backends stay confined + assert StorageBackend.confine_paths is True + + +# --------------------------------------------------------------------------- # +# +# --------------------------------------------------------------------------- # +class TestFilepathConfinement: + @pytest.mark.parametrize("path", PATHS_WITH_PARENT_REF[:3]) + def test_encode_rejects_parent_ref(self, cfg, path): + with pytest.raises(DataJointError, match="outside the store location"): + FilepathCodec().encode(path, store_name="local", context={"config": cfg}) + + @posix_only + def test_encode_rejects_absolute_paths_outside_store(self, cfg, layout): + root, store, _ = layout + for path in _outside_paths(root, store): + with pytest.raises(DataJointError, match="outside the store location"): + FilepathCodec().encode(path, store_name="local", context={"config": cfg}) + + @posix_only + def test_encode_records_absolute_path_inside_store_as_relative(self, cfg, layout): + _, store, _ = layout + codec = FilepathCodec() + meta = codec.encode(str(store / "data" / "inside.txt"), store_name="local", context={"config": cfg}) + assert meta["path"] == "data/inside.txt" + assert codec.decode(meta, context={"config": cfg}).read() == b"inside" + + @posix_only + def test_decode_of_existing_absolute_path_inside_store(self, cfg, layout): + _, store, _ = layout + stored = {"path": str(store / "data" / "inside.txt"), "store": "local", "size": 6} + ref = FilepathCodec().decode(stored, context={"config": cfg}) + assert ref.read() == b"inside" + assert ref.full_path == stored["path"] + + @posix_only + def test_encode_absolute_path_into_reserved_section(self, cfg, layout): + _, store, _ = layout + (store / "_hash").mkdir() + (store / "_hash" / "x.bin").write_bytes(b"x") + with pytest.raises(ValueError, match="reserved section"): + FilepathCodec().encode(str(store / "_hash" / "x.bin"), store_name="local", context={"config": cfg}) + + @pytest.mark.parametrize( + "path", ["./_hash/x.bin", "././_schema/x", ".//_hash/x", "_hash", "_HASH/x.bin", "_Schema/x", "./_Hash"] + ) + def test_encode_reserved_sections_after_normalizing(self, cfg, path): + with pytest.raises(ValueError, match="reserved section"): + FilepathCodec().encode(path, store_name="local", context={"config": cfg}) + + def test_encode_filepath_prefix_after_normalizing(self, cfg, layout): + _, store, _ = layout + cfg.stores["local"]["filepath_prefix"] = "data" + (store / "other.txt").write_text("other") + with pytest.raises(DataJointError, match="outside the store location"): + FilepathCodec().encode("data/../other.txt", store_name="local", context={"config": cfg}) + with pytest.raises(ValueError, match="filepath_prefix"): + FilepathCodec().encode("other.txt", store_name="local", context={"config": cfg}) + for path in ("data/inside.txt", "./data/inside.txt"): + meta = FilepathCodec().encode(path, store_name="local", context={"config": cfg}) + assert meta["path"] == path + + def test_round_trip_inside_store(self, cfg): + codec = FilepathCodec() + meta = codec.encode("data/inside.txt", store_name="local", context={"config": cfg}) + assert codec.decode(meta, context={"config": cfg}).read() == b"inside" + + @pytest.mark.parametrize("kind", ["absolute", "parent_ref", "sibling_prefix"]) + def test_decode_of_row_outside_store_does_not_reach_it(self, cfg, layout, kind): + root, store, _ = layout + path = { + "absolute": str(root / "outside.txt"), + "parent_ref": "../outside.txt", + "sibling_prefix": str(store) + "-sibling/sibling.txt", + }[kind] + ref = FilepathCodec().decode({"path": path, "store": "local", "size": None}, context={"config": cfg}) + with pytest.raises(DataJointError, match="outside the store location"): + ref.read() + with pytest.raises(DataJointError, match="outside the store location"): + ref.full_path + with pytest.raises(DataJointError, match="outside the store location"): + ref.download(root / "dl") + + def test_escape_hatch_allows_outside_references(self, cfg, layout): + root, _, _ = layout + cfg.allow_filepath_outside_store = True + codec = FilepathCodec() + meta = codec.encode("../outside.txt", store_name="local", context={"config": cfg}) + assert codec.decode(meta, context={"config": cfg}).read() == b"outside" + absolute = {"path": str(root / "outside.txt"), "store": "local", "size": None} + assert codec.decode(absolute, context={"config": cfg}).read() == b"outside" + + def test_escape_hatch_does_not_apply_to_object(self, cfg, layout): + root, _, _ = layout + cfg.allow_filepath_outside_store = True + ref = ObjectCodec().decode({"path": str(root / "outside.txt"), "store": "local", "size": 7}, context={"config": cfg}) + with pytest.raises(DataJointError, match="outside the store location"): + ref.read() + + +# --------------------------------------------------------------------------- # +# and ObjectRef +# --------------------------------------------------------------------------- # +class TestObjectConfinement: + @pytest.mark.parametrize("path", ["../outside.txt", "/outside.txt", "_schema/../../outside.txt"]) + def test_encode_rejects_precomputed_metadata_outside_store(self, cfg, path): + with pytest.raises(DataJointError, match="outside the store location"): + ObjectCodec().encode({"path": path, "store": "local", "size": 1}, context={"config": cfg}) + + def test_encode_passes_precomputed_metadata_inside_store(self, cfg): + meta = {"path": "_schema/s/t/k/f_tok", "store": "local", "size": 1} + assert ObjectCodec().encode(meta, context={"config": cfg}) is meta + + def test_decode_of_row_outside_store_does_not_reach_it(self, cfg, layout): + root, _, _ = layout + ref = ObjectCodec().decode({"path": str(root / "outside.txt"), "store": "local", "size": 7}, context={"config": cfg}) + with pytest.raises(DataJointError, match="outside the store location"): + ref.read() + with pytest.raises(DataJointError, match="outside the store location"): + ref.full_path + + @pytest.mark.parametrize( + "subpath", + ["sub/C:\\x\\y.dll", "sub/\\\\server\\share\\y.dll", "sub\\..", "sub/x:y"], + ids=["drive", "unc", "parent_ref", "colon"], + ) + def test_download_into_directory_uses_last_component_only(self, cfg, layout, subpath): + """The local file name is the last component, split on both separators, and must be plain.""" + _, store, downloads = layout + backend = StorageBackend({"protocol": "file", "location": str(store)}) + backend.confine_paths = False # isolate the local-name check + downloads.mkdir() + ref = ObjectRef(path="data", size=None, hash=None, ext=None, is_dir=True, timestamp=None, _backend=backend) + name = subpath.replace("\\", "/").split("/")[-1] + if name in ("", ".", "..") or (os.name == "nt" and ":" in name): + with pytest.raises(DataJointError, match="not a plain file name"): + ref.download(downloads, subpath=subpath) + else: + # Missing source file: the error comes from the store, after the name was accepted. + # Windows reports a source path containing ":" as invalid rather than missing + with pytest.raises(OSError): + ref.download(downloads, subpath=subpath) + assert not any(downloads.iterdir()) + + @pytest.fixture + def memory_backend(self): + """A backend over fsspec's in-memory filesystem, whose keys may contain '..' as object stores' keys can.""" + from fsspec.implementations.memory import MemoryFileSystem + + class MemoryBackend: + fs = MemoryFileSystem() + + def _full_path(self, path): + return f"dj-test-bucket/loc/{path}" + + backend = MemoryBackend() + yield backend + backend.fs.rm("/dj-test-bucket", recursive=True) + + def test_download_folder_rejects_key_leading_outside(self, memory_backend, tmp_path): + """Every key is checked before any file is written.""" + memory_backend.fs.pipe( + { + "/dj-test-bucket/loc/obj/a.txt": b"a", + "/dj-test-bucket/loc/obj/sub/b.txt": b"b", + "/dj-test-bucket/loc/obj/sub/../../../../x": b"x", + } + ) + dest = tmp_path / "work" / "dest" # dest/obj/sub/../../../../x is tmp_path/x + ref = ObjectRef(path="obj", size=None, hash=None, ext=None, is_dir=True, timestamp=None, _backend=memory_backend) + with pytest.raises(DataJointError, match="leads outside the destination"): + ref.download(dest) + assert not (tmp_path / "x").exists() + assert [p for p in tmp_path.rglob("*") if not p.is_dir()] == [] + assert not (dest / "obj").exists() + + def test_download_folder_round_trip(self, memory_backend, tmp_path): + """Files land in destination//..., as fsspec's recursive get placed them.""" + memory_backend.fs.pipe({"/dj-test-bucket/loc/obj/a.txt": b"a", "/dj-test-bucket/loc/obj/sub/b.txt": b"b"}) + dest = tmp_path / "dest" + ref = ObjectRef(path="obj", size=None, hash=None, ext=None, is_dir=True, timestamp=None, _backend=memory_backend) + assert ref.download(dest) == dest + assert sorted(p.relative_to(dest).as_posix() for p in dest.rglob("*") if p.is_file()) == ["obj/a.txt", "obj/sub/b.txt"] + assert (dest / "obj" / "a.txt").read_bytes() == b"a" + assert (dest / "obj" / "sub" / "b.txt").read_bytes() == b"b" + + +# --------------------------------------------------------------------------- # +# +# --------------------------------------------------------------------------- # +def _attach_blob(name: str, contents: bytes) -> bytes: + return name.encode("utf-8") + b"\x00" + contents + + +class TestAttachConfinement: + @pytest.mark.parametrize( + "name", + ["../outside.txt", "../../outside.txt", "sub/outside.txt", "..\\outside.txt", "back\\slash.txt", "..", ".", ""], + ids=["parent_ref", "parent_ref_twice", "subdir", "backslash_parent_ref", "backslash", "dotdot", "dot", "empty"], + ) + def test_decode_rejects_stored_name_that_is_not_plain(self, cfg, layout, name): + root, _, downloads = layout + (root / "outside.txt").unlink() + with pytest.raises(DataJointError, match="not a plain file name"): + AttachCodec().decode(_attach_blob(name, b"payload"), context={"config": cfg}) + assert not (root / "outside.txt").exists() + assert not (downloads / "sub").exists() + + def test_decode_rejects_absolute_stored_name(self, cfg, layout): + root, _, _ = layout + target = root / "absolute.txt" + with pytest.raises(DataJointError, match="not a plain file name"): + AttachCodec().decode(_attach_blob(str(target), b"payload"), context={"config": cfg}) + assert not target.exists() + + def test_round_trip(self, cfg, layout, tmp_path): + _, _, downloads = layout + source = tmp_path / "notes.txt" + source.write_bytes(b"hello") + codec = AttachCodec() + blob = codec.encode(source) + assert blob == _attach_blob("notes.txt", b"hello") + first = codec.decode(blob, context={"config": cfg}) + assert first == str(downloads / "notes.txt") + # Identical content reuses the file; different content gets a new name + assert codec.decode(blob, context={"config": cfg}) == first + second = codec.decode(_attach_blob("notes.txt", b"changed"), context={"config": cfg}) + assert second == str(downloads / "notes_1.txt") + assert (downloads / "notes.txt").read_bytes() == b"hello" + assert (downloads / "notes_1.txt").read_bytes() == b"changed" + + def test_decode_skips_directory_with_the_same_name(self, cfg, layout): + """A non-regular file in the way is never opened; the next free name is used.""" + _, _, downloads = layout + (downloads / "notes.txt").mkdir(parents=True) + result = AttachCodec().decode(_attach_blob("notes.txt", b"payload"), context={"config": cfg}) + assert result == str(downloads / "notes_1.txt") + + @posix_only + def test_decode_does_not_reuse_or_write_through_link(self, cfg, layout): + root, _, downloads = layout + downloads.mkdir() + (downloads / "linked.txt").symlink_to(root / "outside.txt") + result = AttachCodec().decode(_attach_blob("linked.txt", b"changed"), context={"config": cfg}) + assert result == str(downloads / "linked_1.txt") + assert (root / "outside.txt").read_text() == "outside" + # A link is not reused even when its target holds the same content + result = AttachCodec().decode(_attach_blob("linked.txt", b"outside"), context={"config": cfg}) + assert result == str(downloads / "linked_2.txt") + + @posix_only + def test_decode_does_not_follow_dangling_link(self, cfg, layout): + root, _, downloads = layout + downloads.mkdir() + (downloads / "new.txt").symlink_to(root / "created-through-link.txt") + result = AttachCodec().decode(_attach_blob("new.txt", b"payload"), context={"config": cfg}) + assert result == str(downloads / "new_1.txt") + assert not (root / "created-through-link.txt").exists() diff --git a/tests/unit/test_pk_rules.py b/tests/unit/test_pk_rules.py index 2c554091b..148bbacc1 100644 --- a/tests/unit/test_pk_rules.py +++ b/tests/unit/test_pk_rules.py @@ -5,6 +5,9 @@ primary keys in join operations. """ +from types import SimpleNamespace + +from datajoint.adapters import PostgreSQLAdapter from datajoint.heading import Heading @@ -205,3 +208,14 @@ def test_b_determines_a_ordering(self): assert names.index("x") < names.index("z") # y should be secondary (demoted from A's PK) assert "y" in result.secondary_attributes + + +class TestSetPrimaryKey: + """Tests for Heading.set_primary_key.""" + + def test_keeps_the_adapter_for_a_later_rename(self): + """A rename after set_primary_key (as dj.U & table does) quotes for the connection's backend.""" + heading = make_heading(["a"], ["b"]) + heading.table_info = {"conn": SimpleNamespace(adapter=PostgreSQLAdapter())} + renamed = heading.set_primary_key(["b"]).select([], rename_map={"c": "b"}) + assert renamed.attributes["c"].attribute_expression == '"b"' diff --git a/tests/unit/test_settings.py b/tests/unit/test_settings.py index 1cb535d81..7e42fa92a 100644 --- a/tests/unit/test_settings.py +++ b/tests/unit/test_settings.py @@ -1,5 +1,9 @@ """Tests for DataJoint settings module.""" +import os +import signal +import stat +import warnings from pathlib import Path import pytest @@ -1197,3 +1201,328 @@ def test_backend_field_in_env_var_mapping(self): assert "database.backend" in ENV_VAR_MAPPING assert ENV_VAR_MAPPING["database.backend"] == "DJ_BACKEND" + + +@pytest.mark.skipif(not hasattr(os, "getuid"), reason="requires POSIX file ownership") +class TestDiscoveredFileOwnership: + """The config search skips files another user could have placed where they are found.""" + + FOREIGN_UID = 54321 + + @pytest.fixture + def mark(self, monkeypatch, tmp_path): + """Patch ``os.stat``/``lstat``/``fstat`` to report chosen owners and permissions. + + Returns ``mark(path, uid=None, world_writable=False, sticky=False, only=None)``, + which applies to the directory entry at ``path`` itself (a symbolic link + is marked, not its target). ``only`` limits the change to the named + functions. Entries not marked keep their real owner and lose any + world-write and sticky bits, so the host's own ``/tmp`` does not affect + the outcome. + """ + real = {name: getattr(os, name) for name in ("stat", "lstat", "fstat")} + overrides: dict[tuple[int, int], dict] = {} + + def wrap(name): + def fake(*args, **kwargs): + st = real[name](*args, **kwargs) + fields = list(st) + mode = fields[stat.ST_MODE] & ~(stat.S_IWOTH | stat.S_ISVTX) + spec = overrides.get((st.st_dev, st.st_ino)) + if spec is not None and name in spec["only"]: + mode |= spec["bits"] + if spec["uid"] is not None: + fields[stat.ST_UID] = spec["uid"] + fields[stat.ST_MODE] = mode + return os.stat_result(fields) + + return fake + + for name in real: + monkeypatch.setattr(os, name, wrap(name)) + monkeypatch.setattr(settings, "SYSTEM_SECRETS_DIR", tmp_path / "nonexistent-system-secrets") + + def mark(path, *, uid=None, world_writable=False, sticky=False, only=("stat", "lstat", "fstat")): + st = real["lstat"](path) + bits = (stat.S_IWOTH if world_writable else 0) | (stat.S_ISVTX if sticky else 0) + overrides[(st.st_dev, st.st_ino)] = {"uid": uid, "bits": bits, "only": only} + + return mark + + @pytest.fixture + def shared(self, tmp_path): + """A shared directory holding a config file, with the user's project below it.""" + shared = tmp_path / "shared" + project = shared / "project" + project.mkdir(parents=True) + (shared / CONFIG_FILENAME).write_text('{"database": {"host": "from-shared"}}') + return shared + + def test_foreign_config_in_world_writable_dir_skipped(self, mark, shared, caplog): + """Another user's datajoint.json directly in /tmp (world-writable, sticky) is skipped.""" + mark(shared, world_writable=True, sticky=True) + mark(shared / CONFIG_FILENAME, uid=self.FOREIGN_UID) + + with caplog.at_level("WARNING", logger="datajoint"): + found = find_config_file(shared / "project") + + assert found is None + messages = [r.message for r in caplog.records] + assert any(str(shared / CONFIG_FILENAME) in m and "DJ_CONFIG_FILE" in m for m in messages) + + def test_group_config_under_sticky_world_writable_root_used(self, mark, tmp_path): + """/scratch (1777) / lab (2770, PI-owned) / datajoint.json owned by the PI is used.""" + scratch = tmp_path / "scratch" + lab = scratch / "lab" + (lab / "project").mkdir(parents=True) + (lab / CONFIG_FILENAME).write_text("{}") + mark(scratch, world_writable=True, sticky=True) + mark(lab, uid=self.FOREIGN_UID) + mark(lab / CONFIG_FILENAME, uid=self.FOREIGN_UID) + + assert find_config_file(lab / "project") == lab / CONFIG_FILENAME + + def test_foreign_config_below_non_sticky_world_writable_dir_skipped(self, mark, tmp_path): + """A world-writable ancestor without the sticky bit lets anyone replace what is below it.""" + open_dir = tmp_path / "open" + lab = open_dir / "lab" + (lab / "project").mkdir(parents=True) + (lab / CONFIG_FILENAME).write_text("{}") + mark(open_dir, world_writable=True) + mark(lab / CONFIG_FILENAME, uid=self.FOREIGN_UID) + + assert find_config_file(lab / "project") is None + + def test_foreign_config_in_non_sticky_world_writable_dir_skipped(self, mark, shared): + """Another user's datajoint.json in a directory anyone can write (e.g. a 0777 volume) is skipped.""" + mark(shared, world_writable=True) + mark(shared / CONFIG_FILENAME, uid=self.FOREIGN_UID) + + assert find_config_file(shared / "project") is None + + def test_foreign_config_in_protected_dir_used(self, mark, shared): + """Another user's file in a directory only its owners can write (e.g. a lab share) is used.""" + mark(shared / CONFIG_FILENAME, uid=self.FOREIGN_UID) + + assert find_config_file(shared / "project") == shared / CONFIG_FILENAME + + def test_root_owned_config_in_world_writable_dir_used(self, mark, shared): + mark(shared, world_writable=True, sticky=True) + mark(shared / CONFIG_FILENAME, uid=0) + + assert find_config_file(shared / "project") == shared / CONFIG_FILENAME + + def test_foreign_config_in_world_writable_dir_skipped_as_root(self, mark, shared, monkeypatch): + """Running as root does not make another user's file in a world-writable directory trusted.""" + monkeypatch.setattr(os, "getuid", lambda: 0) + mark(shared, world_writable=True, sticky=True) + mark(shared / CONFIG_FILENAME, uid=self.FOREIGN_UID) + + assert find_config_file(shared / "project") is None + + def test_foreign_config_in_protected_dir_used_as_root(self, mark, shared, monkeypatch): + monkeypatch.setattr(os, "getuid", lambda: 0) + mark(shared / CONFIG_FILENAME, uid=self.FOREIGN_UID) + + assert find_config_file(shared / "project") == shared / CONFIG_FILENAME + + def test_own_config_in_world_writable_dir_used(self, mark, shared, caplog): + mark(shared, world_writable=True, sticky=True) + + with caplog.at_level("WARNING", logger="datajoint"): + found = find_config_file(shared / "project") + + assert found == shared / CONFIG_FILENAME + assert not caplog.records + + def test_world_writable_own_config_warns(self, mark, shared, caplog): + mark(shared / CONFIG_FILENAME, world_writable=True) + + with caplog.at_level("WARNING", logger="datajoint"): + found = find_config_file(shared / "project") + + assert found == shared / CONFIG_FILENAME + assert any("writable by all users" in r.message for r in caplog.records) + + def test_foreign_symlink_to_own_file_skipped(self, mark, tmp_path): + """A link owned by another user in a world-writable directory is skipped, whatever it points at.""" + own = tmp_path / "own" + own.mkdir() + target = own / "mine.json" + target.write_text("{}") + shared = tmp_path / "shared" + (shared / "project").mkdir(parents=True) + link = shared / CONFIG_FILENAME + link.symlink_to(target) + mark(shared, world_writable=True, sticky=True) + mark(link, uid=self.FOREIGN_UID) + + assert find_config_file(shared / "project") is None + + def test_own_symlink_to_foreign_file_skipped(self, mark, tmp_path): + """A link in a world-writable directory to another user's file is judged by where it was found.""" + protected = tmp_path / "protected" + protected.mkdir() + target = protected / CONFIG_FILENAME + target.write_text("{}") + shared = tmp_path / "shared" + (shared / "project").mkdir(parents=True) + (shared / CONFIG_FILENAME).symlink_to(target) + mark(shared, world_writable=True, sticky=True) + mark(target, uid=self.FOREIGN_UID) + + assert find_config_file(shared / "project") is None + + def test_owner_checked_on_opened_file(self, mark, shared): + """The owner is taken from the opened file, so a file replaced after the search is still checked.""" + mark(shared, world_writable=True, sticky=True) + mark(shared / CONFIG_FILENAME, uid=self.FOREIGN_UID, only=("fstat",)) + + assert find_config_file(shared / "project") is None + + def test_foreign_secrets_dir_in_world_writable_dir_skipped(self, mark, tmp_path): + config_file = tmp_path / CONFIG_FILENAME + config_file.write_text("{}") + secrets_dir = tmp_path / SECRETS_DIRNAME + secrets_dir.mkdir() + mark(tmp_path, world_writable=True, sticky=True) + mark(secrets_dir, uid=self.FOREIGN_UID) + + assert find_secrets_dir(config_file) is None + + def test_foreign_secret_file_in_world_writable_secrets_dir_skipped(self, mark, tmp_path): + secrets_dir = tmp_path / SECRETS_DIRNAME + secrets_dir.mkdir() + (secrets_dir / "database.password").write_text("from-other-user") + (secrets_dir / "stores.main.secret_key").write_text("from-other-user") + (secrets_dir / "database.user").write_text("mine") + mark(secrets_dir, world_writable=True) + mark(secrets_dir / "database.password", uid=self.FOREIGN_UID) + mark(secrets_dir / "stores.main.secret_key", uid=self.FOREIGN_UID) + + assert read_secret_file(secrets_dir, "database.password") is None + assert read_secret_file(secrets_dir, "database.user") == "mine" + + cfg = settings.Config() + cfg._load_secrets(secrets_dir) + assert cfg.database.password is None + assert "main" not in cfg.stores + + def test_root_owned_sticky_system_secrets_dir_used_without_warning(self, mark, tmp_path, monkeypatch, caplog): + """A Kubernetes secret volume (root-owned, mode 1777) is used; only the files in it are checked.""" + secrets_dir = tmp_path / "system-secrets" + secrets_dir.mkdir() + (secrets_dir / "database.password").write_text("from-root") + monkeypatch.setattr(settings, "SYSTEM_SECRETS_DIR", secrets_dir) + mark(secrets_dir, uid=0, world_writable=True, sticky=True) + mark(secrets_dir / "database.password", uid=0) + + with caplog.at_level("WARNING", logger="datajoint"): + found = find_secrets_dir(None) + value = read_secret_file(found, "database.password") + + assert found == secrets_dir + assert value == "from-root" + assert not any("writable by all users" in r.message for r in caplog.records) + + def test_root_owned_non_sticky_system_secrets_dir_warns(self, mark, tmp_path, monkeypatch, caplog): + secrets_dir = tmp_path / "system-secrets" + secrets_dir.mkdir() + (secrets_dir / "database.password").write_text("from-root") + monkeypatch.setattr(settings, "SYSTEM_SECRETS_DIR", secrets_dir) + mark(secrets_dir, uid=0, world_writable=True) + mark(secrets_dir / "database.password", uid=0) + + with caplog.at_level("WARNING", logger="datajoint"): + found = find_secrets_dir(None) + value = read_secret_file(found, "database.password") + + assert found == secrets_dir + assert value == "from-root" + assert any(str(secrets_dir) in r.message and "writable by all users" in r.message for r in caplog.records) + + def test_fifo_secret_file_not_read(self, tmp_path): + """A named pipe in place of a secret file is skipped without waiting for a writer.""" + secrets_dir = tmp_path / SECRETS_DIRNAME + secrets_dir.mkdir() + os.mkfifo(secrets_dir / "database.password") + + def blocked(signum, frame): + pytest.fail("opening the named pipe blocked") + + previous = signal.signal(signal.SIGALRM, blocked) + signal.alarm(5) + try: + value = read_secret_file(secrets_dir, "database.password") + finally: + signal.alarm(0) + signal.signal(signal.SIGALRM, previous) + + assert value is None + + def test_no_posix_ownership_keeps_search(self, mark, shared, monkeypatch): + """Without os.getuid (Windows) the search behaves as before.""" + mark(shared, world_writable=True, sticky=True) + mark(shared / CONFIG_FILENAME, uid=self.FOREIGN_UID) + monkeypatch.delattr(os, "getuid", raising=False) + + assert find_config_file(shared / "project") == shared / CONFIG_FILENAME + + def test_create_config_skips_foreign_config_with_one_warning(self, mark, shared, monkeypatch, caplog): + for var in ("DJ_HOST", "DJ_CONFIG_FILE", "DJ_IGNORE_CONFIG_FILE"): + monkeypatch.delenv(var, raising=False) + monkeypatch.chdir(shared / "project") + mark(shared, world_writable=True, sticky=True) + mark(shared / CONFIG_FILENAME, uid=self.FOREIGN_UID) + + with warnings.catch_warnings(record=True) as caught, caplog.at_level("WARNING", logger="datajoint"): + warnings.simplefilter("always") + cfg = settings._create_config() + + assert cfg.database.host == "localhost" + assert not [w for w in caught if "No datajoint.json found" in str(w.message)] + skipped = [r.message for r in caplog.records if "Ignoring" in r.message] + assert len(skipped) == 1 + assert "DJ_CONFIG_FILE" in skipped[0] and "dj.config.load()" in skipped[0] + + def test_dj_config_file_names_file_explicitly(self, mark, shared, monkeypatch, tmp_path): + """DJ_CONFIG_FILE loads the named file, without searching and without the ownership check.""" + monkeypatch.delenv("DJ_HOST", raising=False) + monkeypatch.delenv("DJ_IGNORE_CONFIG_FILE", raising=False) + elsewhere = tmp_path / "elsewhere" + (elsewhere / ".git").mkdir(parents=True) + monkeypatch.chdir(elsewhere) + mark(shared, world_writable=True, sticky=True) + mark(shared / CONFIG_FILENAME, uid=self.FOREIGN_UID) + monkeypatch.setenv("DJ_CONFIG_FILE", str(shared / CONFIG_FILENAME)) + + cfg = settings._create_config() + + assert cfg.database.host == "from-shared" + + def test_dj_config_file_missing_raises(self, mark, monkeypatch, tmp_path): + monkeypatch.delenv("DJ_IGNORE_CONFIG_FILE", raising=False) + monkeypatch.setenv("DJ_CONFIG_FILE", str(tmp_path / "missing.json")) + + with pytest.raises(FileNotFoundError, match="DJ_CONFIG_FILE"): + settings._create_config() + + def test_dj_config_file_ignored_with_ignore_config_file(self, mark, shared, monkeypatch): + monkeypatch.delenv("DJ_HOST", raising=False) + monkeypatch.setenv("DJ_CONFIG_FILE", str(shared / CONFIG_FILENAME)) + monkeypatch.setenv("DJ_IGNORE_CONFIG_FILE", "true") + + cfg = settings._create_config() + + assert cfg.database.host == "localhost" + + def test_explicit_load_uses_foreign_file(self, mark, shared, monkeypatch): + """dj.config.load(path) is an explicit choice and is not checked.""" + monkeypatch.delenv("DJ_HOST", raising=False) + mark(shared, world_writable=True, sticky=True) + mark(shared / CONFIG_FILENAME, uid=self.FOREIGN_UID) + + cfg = settings.Config() + cfg.load(shared / CONFIG_FILENAME) + + assert cfg.database.host == "from-shared" diff --git a/tests/unit/test_tls.py b/tests/unit/test_tls.py new file mode 100644 index 000000000..e4a0fbb04 --- /dev/null +++ b/tests/unit/test_tls.py @@ -0,0 +1,532 @@ +""" +Unit tests for the ``use_tls`` connection option. + +The adapters' parameter mapping is checked with the driver's connect function +replaced. The handshake checks run the real drivers against a minimal local +server that answers the initial protocol exchange without offering TLS. +Connection and dj.conn are checked with a mock adapter. +""" + +import importlib +import socket +import ssl +import struct +import threading +from unittest import mock + +import pymysql +import pytest +from pymysql.constants import CLIENT, CR + +from datajoint.adapters import MySQLAdapter, PostgreSQLAdapter +from datajoint.adapters import mysql as mysql_adapter + +CREDENTIALS = dict(host="localhost", port=3306, user="alice", password="secret") + + +# ============================================================================= +# Minimal servers for the initial protocol exchange +# ============================================================================= + + +class FakeServer: + """Accept connections on localhost and answer each with ``respond(sock, received)``.""" + + def __init__(self, respond): + self.respond = respond + self.received = [] # bytes received on each connection + self.listener = socket.create_server(("127.0.0.1", 0)) + self.listener.settimeout(0.05) + self.port = self.listener.getsockname()[1] + self.stopped = threading.Event() + self.thread = threading.Thread(target=self._serve, daemon=True) + self.thread.start() + + def _serve(self): + while not self.stopped.is_set(): + try: + sock, _ = self.listener.accept() + except socket.timeout: + continue + except OSError: + return + received = bytearray() + self.received.append(received) + with sock: + sock.settimeout(2) + try: + self.respond(sock, received) + while chunk := sock.recv(4096): + received.extend(chunk) + except OSError: + pass + + def close(self): + self.stopped.set() + self.thread.join(timeout=5) + self.listener.close() + + +def _mysql_packet(payload, seq): + return struct.pack("> 16) + + bytes([len(salt) + 1]) + + b"\x00" * 10 + + salt[8:] + + b"\x00" + + b"mysql_native_password\x00" + ) + return _mysql_packet(payload, 0) + + +MYSQL_CAPABILITIES = CLIENT.LONG_PASSWORD | CLIENT.PROTOCOL_41 | CLIENT.SECURE_CONNECTION | CLIENT.PLUGIN_AUTH + + +def _mysql_server_without_tls(sock, received): + """Greet without CLIENT_SSL; reject any authentication attempt.""" + sock.sendall(_mysql_greeting(MYSQL_CAPABILITIES)) + chunk = sock.recv(4096) + received.extend(chunk) + if chunk: + error = b"\xff" + struct.pack("