Skip to content

build: make the database drivers optional extras - #1628

Draft
dimitri-yatsenko wants to merge 56 commits into
nextfrom
build/drivers-optional-extras
Draft

dimitri-yatsenko wants to merge 56 commits into
nextfrom
build/drivers-optional-extras

Conversation

@dimitri-yatsenko

Copy link
Copy Markdown
Member

Closes #1626.

Summary

pymysql is no longer a core dependency. Each database driver is an optional extra, and import datajoint loads no driver:

Extra Installs
datajoint[postgres] psycopg2-binary>=2.9.0 (unchanged)
datajoint[mysql] pymysql>=0.7.2 (new; same floor as the former core dependency)

A bare pip install datajoint installs no database driver.

Changes

  • pyproject.toml. pymysql moves from [project].dependencies to the new mysql extra. The test dependency group and the test and dev extras list both drivers.
  • Lazy driver import. A new helper, import_driver in adapters/base.py, imports a driver when its adapter is created, which happens on connect. A missing driver raises a DataJointError that names the extra:
    The MySQL backend requires the pymysql driver, which is not installed. Install it with: pip install "datajoint[mysql]"
    
    adapters/mysql.py no longer imports pymysql at module load. adapters/postgres.py drops its module-level try: import psycopg2 (and the unused psycopg2.sql import). Its adapter raised ImportError for a missing driver and now raises the same DataJointError.
  • psycopg2 vs psycopg2-binary. The adapter imports the psycopg2 module, which both distributions provide, so either one satisfies it.
  • Other places that assumed pymysql is installed.
    • README install line: now shows datajoint[postgres] and datajoint[mysql].
    • CONTRIBUTING.md: the backend section lists both extras.
    • Development Dockerfile: installs /main[postgres,mysql].
    • RELEASE_MEMO.md: conda has no extras, so the feedstock recipe lists both drivers under run.
    • The lazy-import comment in __init__.py.

Migration

  • MySQL: pip install "datajoint[mysql]", or datajoint[mysql] in a requirements file.
  • PostgreSQL: pip install "datajoint[postgres]", as before.
  • An upgrade in place keeps a pymysql that is already installed. A fresh environment built from a requirements file that lists only datajoint has no driver, and the first connection names the extra to install.
  • Code that caught ImportError from PostgreSQLAdapter() should catch DataJointError.

Tests

  • tests/unit/test_lazy_imports.py: in a fresh interpreter, import datajoint loads neither pymysql nor psycopg2.
  • tests/unit/test_adapters.py::TestMissingDriver: blocks each driver in sys.modules, then checks two things:
    • get_adapter and Connection(...) raise a DataJointError naming the right extra, before any server is contacted.
    • Each backend needs only its own driver.
  • Full suite (testcontainers, local): 1166 passed, 14 skipped.
  • Clean virtual environments, each with an editable install of this branch:
    • Bare install: no driver installed. import datajoint succeeds with no driver loaded. dj.conn() raises ... pip install "datajoint[mysql]" (or [postgres] with DJ_BACKEND=postgresql).
    • [mysql]: installs PyMySQL only. dj.conn() reaches the MySQL driver, and psycopg2 is never imported.
    • [postgres]: installs psycopg2-binary only. dj.conn() reaches psycopg2, and pymysql is never imported.

Notes for review

  • pixi.lock is not regenerated in this PR. Re-solving it changes no package versions in the existing default, dev, and test environments. The only changes are that default drops pymysql and gains packaging, which the committed lock was already missing. The rest of the re-solve adds the test-py310/test-py314 environments, which the open Python 3.15 build PR (build: support Python 3.15 #1596) also adds. pixi.lock merges as binary, so regenerating it in both PRs would conflict. CI runs with locked: false.
  • datajoint[mysql] installs plain pymysql. Without cryptography, pymysql cannot complete caching_sha2_password authentication over a non-TLS connection. This was equally true when pymysql was a core dependency. pymysql[rsa] would add cryptography.

pymysql was a core dependency, so every install of datajoint pulled in the
MySQL driver whether or not it was used, while the PostgreSQL driver was
already the optional postgres extra. Both drivers are now extras:
pip install "datajoint[postgres]" installs psycopg2-binary, and
pip install "datajoint[mysql]" installs pymysql, with the same >=0.7.2 floor
as before. A bare pip install datajoint installs no database driver.

import datajoint no longer imports a driver. Each adapter imports its driver
when it is created, which happens when a connection is made, through a new
helper, import_driver, in adapters/base.py. When the driver is missing,
connecting raises a DataJointError that names the extra, for example: The
MySQL backend requires the pymysql driver, which is not installed. Install it
with: pip install "datajoint[mysql]". The PostgreSQL adapter raised
ImportError for its missing driver; it now raises the same DataJointError.
The adapter imports the psycopg2 module, which both the psycopg2 and the
psycopg2-binary distributions provide, so either one satisfies it.

The test dependency group and the test and dev extras install both drivers.
The README install line, CONTRIBUTING.md, the development Docker image (it
now installs both extras), and the conda-forge notes in RELEASE_MEMO.md
(conda has no extras, so the recipe lists both drivers) are updated to match.

Migration: an environment that connects to MySQL needs
pip install "datajoint[mysql]", or pymysql installed some other way; one
that connects to PostgreSQL needs pip install "datajoint[postgres]". An
upgrade in place keeps a pymysql that is already installed, but a fresh
install from a requirements file that lists only datajoint gets no driver.
Code that caught ImportError from PostgreSQLAdapter() should catch
DataJointError instead.

Tests: test_lazy_imports.py checks, in a fresh interpreter, that
import datajoint loads neither pymysql nor psycopg2. test_adapters.py blocks
each driver in sys.modules and checks that get_adapter and Connection raise
a DataJointError naming the right extra before any server is contacted, and
that each backend needs only its own driver.
@dimitri-yatsenko dimitri-yatsenko added this to the v2.4 milestone Oct 17, 2026
@dimitri-yatsenko dimitri-yatsenko added the breaking Not backward compatible changes label Oct 17, 2026
…otes for the backend

Signed-off-by: mayuriphad <mayuriphad656@gmail.com>
MilagrosMarin
MilagrosMarin previously approved these changes Oct 21, 2026

@MilagrosMarin MilagrosMarin left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thanks @dimitri-yatsenko, this is a clean change and the error message is exactly what a new user needs to see.

Verified locally:
✅ No remaining module-level driver imports under src/; client is only used after __init__ sets it
✅ test_adapters.py + test_lazy_imports.py pass; restoring import pymysql as client in mysql.py makes test_import_loads_no_database_driver fail, so the test guards the behavior
✅ Bare pip install -e .: import datajoint loads no driver, and dj.conn() raises the datajoint[mysql] hint

A few follow-ups:

  • #1596 has merged since CI ran, so this PR hasn't run the new test-py315 / Windows py3.15 legs. A rebase/re-run would confirm. That also removes the reason given for not regenerating pixi.lock (its default env still locks pymysql), so the lock could be refreshed here or in a follow-up.
  • The conda recipe now lists psycopg2 under run, so conda users get a new hard dependency. Worth a line in the release notes next to the pip migration.
  • On the docs side, how-to/installation.md and tutorials/index.md still show pip install datajoint. I'll open a docs PR to match this before the release goes out.

Let me know if anything here is off!

TheeCoderAhmed and others added 3 commits October 29, 2026 06:45
For s3, gcs and azure stores, full_path built <protocol>://<bucket>/<path> and left out the store's location, so it pointed to a path where the object is not when location is set. Use StorageBackend.get_url(), which builds the URL from the same _full_path the backend writes to.

Fixes #1646
Dependabot rejects time "9:00" (must match ^\d\d:\d\d$), so the
config failed to parse and no GitHub Actions updates were scheduled.
Adds a pip entry for pyproject.toml alongside the github-actions one.
increase-if-necessary keeps minimum-version requirements unchanged when
they already admit a new release; security updates are grouped.
numpy, pandas, pyparsing, tqdm, networkx, pydot, and packaging had no
version specifier. GitHub's dependency graph omits such requirements, so
they were missing from the SBOM and from Dependabot alerts.

The minimums were verified by running the full test suite on Python 3.10
with each dependency at its minimum. pyparsing 3.1.0 and pydot 2.x fail
it: pyparsing 3.1.0 strips the quotes from quoted defaults, and pydot 2.x
produces DOT that graphviz rejects. tqdm>=4.66.3 excludes CVE-2024-34062.
pyproject.toml keeps deepdiff<9 for Python 3.15 on purpose: deepdiff 9
requires cachebox<6, which has no 3.15 wheels. With increase-if-necessary,
Dependabot would propose widening that cap at every new deepdiff major, so
ignore semver-major updates for deepdiff.

Also state that version updates stay one PR per package, since each raises
an upper bound and deserves its own test run and review.
Pin every action in the lint, test, and stale workflows to the commit its
current tag resolves to, so a moved or compromised tag cannot change what
runs. Lint and test get a read-only GITHUB_TOKEN, and their checkouts do not
persist the token in the working copy.
- pandas>=2.2.2: pandas does not cap numpy, so pandas 1.5.3 with numpy 2
  installs and then fails on import (numpy.dtype size changed). 2.2.2 is
  the first pandas built against numpy 2; 2.2.1 still requires numpy<2.
- deepdiff>=6.6.0: DeepHash(ignore_iterable_order=...) first appears in
  6.4, and deepdiff before 6.6 uses np.float_, which numpy 2 removed.
- pymysql>=1.0.0: connections pass ssl_disabled, which pymysql 0.x does
  not accept, so every MySQL connection fails on 0.7.2 through 0.10.1.

Full suite on Python 3.10 with every core dependency at its minimum
passes, and again with numpy 2.2.6 in place of numpy 1.22.4.
Dependabot rejects time "9:00" (must match ^\d\d:\d\d$), so the
config failed to parse and no GitHub Actions updates were scheduled.

(cherry picked from commit 247125c)
pre-commit/action calls actions/cache by tag and installs an unpinned
pre-commit. Run the same steps directly: pre-commit pinned to a version and
actions/cache pinned by SHA.
PR 1588 adds a workflow_call trigger just before jobs:, where the
permissions block was, so the two PRs conflicted.
…nimums

A new test job runs the full suite on Python 3.10 with every runtime
dependency pinned at the minimum pyproject.toml declares.
.github/scripts/minimum_requirements.py derives the pins and fails when a
runtime dependency declares no minimum.

deepdiff and pymysql now start at the first release without known
vulnerabilities rather than the oldest that works: deepdiff>=8.6.2
(CVE-2025-58367, CVE-2026-33155; was 6.6.0) and pymysql>=1.1.1
(CVE-2024-36039; was 1.0.0). pixi.lock moves deepdiff from 8.6.1 to 9.1.0
where Python < 3.15.
CVE-2025-58367 and CVE-2026-33155 are in deepdiff's Delta class and
pickle_load. datajoint uses only DeepHash, so the oldest working version
stays the minimum and Dependabot reports the advisories. pymysql stays at
1.1.1 for CVE-2024-36039.
@dimitri-yatsenko
dimitri-yatsenko changed the base branch from master to next November 6, 2026 17:01
…hed rows

aggr (exclude_nonmatching=False), extend, and union of operands with
secondary attributes use a left join. A restriction on the right operand,
including dj.Top, went into the outer WHERE, where it removed the left rows
with no match. It is now applied inside a subquery for the right operand. An
unrestricted right operand is joined directly, and inner joins are unchanged.

Fixes #1650.
…uery

An expression restricted by dj.Top keeps its ORDER BY/LIMIT in _top, and
several operations ignored it or broke on it:

- join() joined a limited operand directly, on either side, so the limit was
  dropped from *, aggr, and extend. A limited operand is now a subquery.
- Restriction by a limited expression put the LIMIT inside IN (...), which
  MySQL rejects (error 1235). The expression is now a subquery there.
- dj.U.aggr ignored the group's limit, and dj.U & expr applied DISTINCT
  before the limit. Both now apply the limit first.
- Union put its ORDER BY/LIMIT inside the quoted alias name (a syntax error),
  and ignored it for operands with secondary attributes.
- proj() kept the limit while dropping or redefining an attribute its
  ORDER BY names, so keys() and similar calls failed or selected other rows.
  It now adds a subquery in exactly those cases.
- Top.merge let a second Top with an offset reach past the first Top's limit.
- bool() ignored the limit.
- Diagram.restrict() ignored a dj.Top on its seed; it now builds the seed as
  cascade and trace do.
- A subquery heading dropped table_info, so a later rename quoted with
  backticks on PostgreSQL.

dj.Top still cannot be negated or nested in a list or AndList; the error now
says so and names the complement, dj.Top(None, order_by=..., offset=n).

Fixes #1656.
dimitri-yatsenko and others added 26 commits November 10, 2026 13:51
fix: Dependabot config fails to parse (schedule time must be HH:MM)
ci: Dependabot watches Python dependencies, not only GitHub Actions
fix: declare minimum versions for all core dependencies
ci: pin actions to commit SHAs and run workflows with read-only tokens
fix: aggr, extend and union keep unmatched rows when the right operand is restricted
fix: dj.Top is honored when a limited expression is used in another query
fix(heading): keep table_info in set_primary_key so a later rename quotes for the backend
…location

fix: include the store location in ObjectRef.full_path
…ectories

A world-writable secrets directory with the sticky bit, such as a Kubernetes
secret volume mounted at /run/secrets/datajoint, no longer produces a
"writable by all users" warning: each file in it is still checked when read.
A world-writable secrets directory without the sticky bit still warns.

Tests also cover running as root, another user's datajoint.json in a
world-writable directory without the sticky bit, and a named pipe in place
of a secret file.
… not given

Connection now falls back to database.use_tls (DJ_USE_TLS) from its config
when use_tls is None, as dj.conn and Schema already did. This covers
dj.Instance, which passes its own config, and a direct dj.Connection. An
explicit use_tls argument still wins.

The docstrings for an existing connection now say it is reconnected with
the requested TLS settings unless it already satisfies them.
- MySQL string literals double single quotes ('') instead of writing \',
  so a literal stays closed even if the session's sql_mode includes
  NO_BACKSLASH_ESCAPES. The value read back in the default sql_mode is
  unchanged.
- On PostgreSQL, a list value whose text contains a backslash is
  rendered as an E'...' literal, which reads the same whether or not
  standard_conforming_strings is on. Plain string and JSON object values
  are rendered as before.
ObjectRef.download of a folder object lists the keys under the object and
refuses the whole download, before writing any file, if a key relative to
the object is not made of plain file names (for example, one containing a
".." component). It no longer relies on the installed fsspec version to
keep such keys inside the destination. Files still land at
destination/<object name>/..., and fsspec still fetches them in one batch.

The store-path error message now says that allow_filepath_outside_store
applies to <filepath@> values only, and to use it only with trusted data.
The check for mentioned names used `if not self.heading.names`, which
never refers to the attribute and is always false, so a rename or
replicate of an attribute missing from the heading was silently dropped.

Fixes #1677

Signed-off-by: mayuriphad <mayuriphad656@gmail.com>
With a file store whose location is "" or ".", a stored path is used
as given, and fsspec reads a leading "file:" or "local:" as a protocol
and expands a leading "~". Such a path passed the store-path check and
then resolved outside the working directory. The full path is now also
checked after fsspec resolves it, so it must lie inside the location
whatever the location is.
Keep attachment and store paths inside their roots
fix(connection): require TLS when use_tls is set; honor use_tls certificate options
Render values in mapping restrictions as quoted literals
Parse foreign key references instead of evaluating them; cap blob decompression
fix(config): skip config files other users could place in shared directories
fsspec before 2024 leaves "." segments in a resolved path, so a store whose
location is "" or "." rejected every path, including ones inside it. Compare
normalized paths instead.

The working-directory test now checks what the store does with each path: it
is rejected, or fsspec resolves it inside the store and I/O stays there. Old
fsspec does not read some "file:" and "local:" forms as a protocol, so it
accepts them as names inside the store. The Windows download test accepts
OSError, which Windows raises for a source path containing ":".
Match the floor master declares for the core dependency: pymysql 1.0
adds the ssl_disabled connection option, and 1.1.1 fixes CVE-2024-36039.
Raise the same floor in the test and dev extras, the test dependency
group, and the conda run requirements in RELEASE_MEMO.md, and refresh
pixi.lock.
codespell flags "acter" in the char(?:acter)? pattern in condition.py; add
it to the ignore list. mypy reports server_capabilities and
_request_authentication on the TLS connection subclass, which are PyMySQL
internals that types-PyMySQL does not declare; mark those three lines with
targeted type-ignore codes. No behavior change.
fix(proj): raise for a rename or replicate of a missing attribute
fix(storage): accept paths in a file store located in the working directory on fsspec before 2024
Fix lint: codespell regex fragment and mypy errors in the MySQL TLS connection
…-next

Conflicts:
- pyproject.toml: kept master's numpy>=1.22.4 and deepdiff>=6.6.0 floors
  in the core dependencies; pymysql stays out of them and keeps master's
  pymysql>=1.1.1 floor (CVE-2024-36039) in the mysql, test and dev extras.
- src/datajoint/adapters/mysql.py: kept master's TLS handling (use_tls
  modes, unverified TLS context, the check that refuses to authenticate
  without TLS). The PyMySQL subclasses that enforce it are now defined by
  _define_tls_classes() when the first MySQLAdapter imports the driver, so
  import datajoint still loads no database driver.
- pixi.lock: took the merge/master-into-next lock and regenerated it with
  pixi lock; the only changes are pymysql leaving the default environment
  and the extras in the datajoint requires_dist.

Also adjusted tests/unit/test_tls.py: the MySQL parameter fixture creates a
MySQLAdapter before patching, since the driver and the TLS classes now load
with the first adapter.
@dimitri-yatsenko

Copy link
Copy Markdown
Member Author

This branch now includes master through #1720 (the 2.3.6 fixes). That PR has since merged into next, so the diff against next shows only this PR's changes again.

Three files conflicted. Here is how each was resolved, so you can check it:

  • pyproject.toml: the core dependencies keep master's floors for numpy and deepdiff. PyMySQL stays out of them, as this PR intends. The mysql, test and dev extras keep master's pymysql>=1.1.1 floor (CVE-2024-36039).
  • src/datajoint/adapters/mysql.py: master's TLS handling is kept unchanged in behavior. Master defines PyMySQL subclasses at import time to enforce use_tls. They are now defined when the first MySQLAdapter imports the driver, so import datajoint still loads no database driver.
  • pixi.lock: taken from next and regenerated with pixi lock. The only changes are PyMySQL leaving the default environment and the new extras in the package metadata.

One test needed a small change: the MySQL TLS parameter fixture in tests/unit/test_tls.py now creates a MySQLAdapter before it patches the driver, because the driver loads with the first adapter.

If #1750 lands on master first (pymysql[rsa]>=1.2.4), that requirement goes into the mysql extra here (and the test and dev extras), not into the core dependencies.

The unit suite and the full integration suite pass on MySQL and PostgreSQL, and CI is green.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

breaking Not backward compatible changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Database drivers become optional extras

4 participants