Repository navigation
feat: PostgreSQL is the default backend - #1629
dimitri-yatsenko wants to merge 58 commits into
Conversation
database.backend defaulted to "mysql", so a connection made without configuring a backend went to MySQL. It now defaults to "postgresql" on port 5432. MySQL stays a fully supported backend, selected with one setting. The port follows the backend unless it is set. The port was derived from the backend only when the settings were first built, so a backend set later, in datajoint.json or by assignment, kept the other backend's port: with the new default, backend "mysql" in datajoint.json would have connected to port 5432. The validator now recomputes a port that was not set whenever the backend changes. A port set by DJ_PORT, datajoint.json, or assignment is kept, and setting it to None returns it to the backend's default. When a connection fails and the backend is still the default, so that neither the backend argument nor the configuration chose one, the error is re-raised as a DataJointError that keeps the original message and adds: The default backend is postgresql since DataJoint 2.4; set database.backend='mysql' (DJ_BACKEND=mysql) for a MySQL server. The same applies when the adapter cannot be created, as when psycopg2 is not installed. The settings record which fields were set (pydantic's model_fields_set), so DJ_BACKEND, datajoint.json, dj.config assignment, and Instance(backend=...) all count as chosen, and with any of them the original error is raised unchanged. Instance no longer passes its config's backend to Connection as an argument, which hid whether it was chosen; Connection reads it from that config. save_template writes "backend": "postgresql" and port 5432. The settings docstring, the Connection and Instance docstrings, the CLI help, docker-compose.yaml, and CONTRIBUTING.md list PostgreSQL first. In the compose file the app service's DJ_HOST, DJ_USER, and DJ_PASS name the MySQL service, which the test suite reads as its MySQL server, so the service now sets DJ_BACKEND=mysql to match. Migration for MySQL users: select the backend with DJ_BACKEND=mysql, "backend": "mysql" under "database" in datajoint.json, dj.config["database.backend"] = "mysql" before connecting, or dj.Instance(..., backend="mysql"). The port then defaults to 3306; an explicit port is kept. A MySQL setup that sets no backend fails to connect with the message above. Tests: the MySQL-only fixtures no longer rely on the default. A session fixture, mysql_backend_config, selects MySQL in dj.config for the tests that connect through db_creds_root and db_creds_test. connection_root_bare and connection_test pass backend="mysql". The CLI test's subprocess sets DJ_BACKEND=mysql. connection_by_backend falls back to "postgresql". New unit tests, which need no server, check the default backend and port, that a port not set follows the backend (including backend "mysql" in datajoint.json), that a port that was set survives a change of backend, and that the hint appears for a failed connection or missing driver with the default backend. They also check that it does not appear when the backend comes from the argument, assignment, DJ_BACKEND, or datajoint.json, using a stub adapter and a real refused connection to a closed local port.
…otes for the backend Signed-off-by: mayuriphad <mayuriphad656@gmail.com>
MilagrosMarin
left a comment
There was a problem hiding this comment.
Thanks @dimitri-yatsenko, the default-backend hint is a nice touch for the migration, and keying it off model_fields_set is a neat way to tell "chosen" from "defaulted".
Verified locally:
✅ Unit suite passes on this branch, and on master + #1628 + #1629 merged together
✅ An unset port follows the backend both ways; port=None returns it to the backend default; Instance(backend="mysql") and dj.conn() pick up the backend from config
One issue:
config.override()restores values withsetattr, which marks them as explicitly set. Afterthe port stays 5432 (now inwith dj.config.override(database__port=1234): ... dj.config["database.backend"] = "mysql"
model_fields_set), so it no longer follows the backend. The same restore marksbackendas set afteroverride(database__backend=...), which turns the hint off for the rest of the session. Saving and restoring each field'smodel_fields_setmembership inoverride()would fix both.
Minor:
- With the default backend, unrelated connect failures (e.g. a wrong password on a real PostgreSQL server) also get the MySQL hint. Fine by me given the migration, just noting it.
- CI ran before #1596 merged, so the py3.15 legs haven't run here. A rebase/re-run would confirm.
- On the docs side,
configure-database.md,reference/configuration.md,tutorials/index.md, andinstallation.mdstill show 3306 / MySQL as the default. I'll fold those into the docs PR for #1628.
Let me know what you think!
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
# Conflicts: # CONTRIBUTING.md # docker-compose.yaml
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.
…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.
…ctories The search for datajoint.json walks up from the working directory and the .secrets/ directory is read next to the file it finds. A file or directory owned by another user (other than root) is now skipped, with a warning, when it or a directory above it is writable by all users (for example /tmp). A world-writable file that is used produces a warning. To use such a file, name it explicitly: dj.config.load(path), or the new DJ_CONFIG_FILE environment variable, which loads the named file without searching. DJ_IGNORE_CONFIG_FILE=true still turns the search off. Platforms without os.getuid (Windows) are unchanged. fix(npy): keep the mmap download cache in a per-user private directory NpyRef.load(mmap_mode=...) on a remote store cached downloads in a directory shared by all users. The cache is now <tempdir>/datajoint_mmap_<uid>, created with mode 0700; an existing directory is used only if the current user owns it, and otherwise a new private directory is created for the session. On Windows the per-user temp directory keeps datajoint_mmap.
…ompression Foreign key references in table definitions are now parsed and looked up in the declaration context attribute by attribute. A reference is a dotted name (Parent, module.Parent, Master.Part), optionally projected with .proj(new_name="old_name"); anything else raises a DataJointError naming the supported forms. alter() re-parses the definition that describe() builds from the database catalog, and that text is now only ever read as a table name. describe() keeps each element of the definition on its own line: line breaks in table and attribute comments become spaces, and attribute names that are not plain identifiers raise a DataJointError. Compressed blobs now expand only up to the size declared in their header. A payload that holds more, or less, raises a DataJointError, as does a corrupt zlib stream.
<attach> fetch now accepts only a plain stored file name (no directory part, "..", or NUL byte; on Windows, no drive or ":"), creates the file exclusively, and never opens or reuses a symbolic link, device, or pipe already in the download path. encode has always stored only the base name, so attachments written by DataJoint are unaffected. Store paths are confined to the store location: StorageBackend rejects paths with ".." components and, for file stores, absolute paths. This covers every store operation, including <hash@>, <object@>, <npy@>, and <filepath@> access, and pre-computed <object@> metadata on insert. <filepath@> checks its reserved sections and filepath_prefix on the normalized path. The new setting allow_filepath_outside_store (DJ_ALLOW_FILEPATH_OUTSIDE_STORE) lets <filepath@> values point outside their store, for data whose references deliberately do, such as rows migrated from DataJoint 0.14.
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 ":".
Cover each way the backend reaches a connection with no port set: Instance(database__backend=...) gives 3306 for mysql and 5432 for postgresql, DJ_BACKEND=mysql without DJ_PORT gives 3306 both in the created config and in an Instance, and the default backend gives 5432.
Instance(backend=...) overwrote the port with the backend's default whenever no port argument was given, so a port set by DJ_PORT or in datajoint.json was dropped, while Instance(database__backend=...) kept it. The database settings now derive a port that was not set from the backend whenever the backend changes, so Instance no longer derives it itself, and both forms connect on the configured port.
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.
PostgreSQL is the default backend, and the backend is never inferred from the port. A connection on port 3306, MySQL's default port, with the backend left at its default now raises a DataJointError before any network access. The message names the port, says the backend defaults to PostgreSQL since 2.4 and that PostgreSQL uses 5432, and lists how to set the backend: DJ_BACKEND=mysql, database.backend in datajoint.json or dj.config, or the backend keyword. The check runs in Connection.__init__, which every path reaches (dj.conn, dj.Instance, dj.Connection), so DJ_PORT, datajoint.json, dj.config assignment, port arguments, and host:port are all covered. It is not in the settings validator: settings are assigned one at a time, so port 3306 may be set before the backend, and a validator error would be swallowed into a warning when datajoint.json loads. An explicit backend, including "postgresql", allows port 3306.
The port 3306 error now fits the path the user took. A connection that reads the global config suggests dj.config; one from dj.Instance says that an Instance reads only the environment, datajoint.json, and its keyword arguments, and suggests backend='mysql', database__backend, or DJ_BACKEND. The closing sentence now reads: "PostgreSQL's default port is 5432. To reach a PostgreSQL server on port 3306, set the backend to 'postgresql' explicitly." Ports are compared as numbers. Config.override() restores whether each setting was set explicitly, not only its value: a setting unset before the block is unset after it, and database.port is derived again from the backend. Before, an override of database.backend left the backend counted as set, so port 3306 later reached PostgreSQL without the error. The backend name is accepted in any case, an empty DJ_BACKEND counts as not set, and any other value raises a DataJointError that lists 'mysql' and 'postgresql', instead of a pydantic literal_error on import. CONTRIBUTING notes that a datajoint.json from save_template() sets the backend to "postgresql" explicitly, so MySQL users change the backend, not only the port.
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: - src/datajoint/connection.py: Connection docstring. Kept master's use_tls description (None: TLS if offered; True: required; dict: verified with ca; False: off) and this branch's backend parameter and Raises section. Code merged without conflict. - tests/unit/test_settings.py: both sides added a test class at the same place. Kept both (TestBackendEnvAtImport and TestDiscoveredFileOwnership). Follow-up from the merge: - tests/unit/test_tls.py: test_connection_error_is_not_retried now passes backend="postgresql", since with the default backend a connect error is wrapped with the MySQL-backend hint.
|
This branch now includes master through #1720 (merge commit d25e6da). Since 1720 has merged into Conflicts and how each was resolved:
One test changed after the merge:
The full test suite passes locally on MySQL and PostgreSQL, and CI passes. |
Closes #1627.
Summary
database.backendnow defaults to"postgresql"on port 5432. MySQL remains a fully supported backend, selected withDJ_BACKEND=mysqlordatabase.backend = "mysql". A connection that fails while the backend is still the default says so:Changes
settings.py).backenddefaults to"postgresql", and the docstring examples and field descriptions match.datajoint.jsonor by assignment, kept the other backend's port. With the new default,{"database": {"backend": "mysql"}}would have connected to 5432.DJ_PORT,datajoint.json, or assignment is kept. Setting it toNonereturns it to the backend default.test_port_auto_detection_on_initialization) is replaced.connection.py). The hint applies when the backend is still the default: nobackendargument was passed, anddatabase.backendis not in the settings'model_fields_set. In that case, a failure to create the adapter or to connect is re-raised as aDataJointErrorthat keeps the original message, appends the hint, and chains the original error. The adapter failure covers a missing psycopg2.DJ_BACKEND,datajoint.json,dj.configassignment, thebackendargument, orInstance(backend=...)raises the original error unchanged.backendargument toConnection. Passing its config's value made every backend look chosen, soConnectionnow reads the backend from that config."backend": "postgresql"and"port": 5432.DJ_BACKEND=mysqlfor MySQL.docker-compose.yaml: service order,depends_on, and header comments.CONTRIBUTING.md: test descriptions, external-container recipes, and environment variable tables.appservice. ItsDJ_HOST/DJ_USER/DJ_PASSname the MySQL service, which the test suite reads as its MySQL server. The service now setsDJ_BACKEND=mysqlto match.Tests that relied on MySQL being the default
tests/conftest.py:mysql_backend_config, selects MySQL indj.configfor every test that connects throughdb_creds_root/db_creds_test, asdj.conn(**db_creds_root)anddj.Connection(**db_creds_test)do.connection_root_bareandconnection_testpassbackend="mysql".connection_by_backendfallback is"postgresql".tests/integration/test_cli.py::test_cli_schemasstartspython -m datajoint.cliagainst the MySQL test server. Its subprocess now setsDJ_BACKEND=mysql.tests/unit/test_settings.py,tests/unit/test_thread_safe.py: these expect the new default and port, and they isolateDJ_BACKEND/DJ_PORTwhere they assert defaults.New tests (no server needed)
tests/unit/test_connection_backend_hint.py:DJ_BACKEND, ordatajoint.json.tests/unit/test_settings.py, covering the port:backend: "mysql"indatajoint.jsonwithout a port gives 3306.Nonereturns it to the default.tests/unit/test_thread_safe.py:Instance(backend="mysql")connects on 3306.Full suite (testcontainers, local): 1307 passed, 14 skipped.
Checked against real servers, with this branch merged with the drivers-as-extras PR and installed in clean virtual environments (no
datajoint.json):[postgres][mysql]DJ_BACKEND=mysql[mysql]datajoint[postgres], plus the hint[postgres]Migration for MySQL users
Use any one of:
export DJ_BACKEND=mysqldatajoint.json:{"database": {"backend": "mysql", "host": "..."}}dj.config["database.backend"] = "mysql"before connectingdj.Instance(host=..., user=..., password=..., backend="mysql")The port then defaults to 3306, and an explicit port is kept.
The backend is never inferred from the port. Connecting on port 3306 (from
DJ_PORT,datajoint.json,dj.config, aportargument, orhost:3306) with no backend set raises aDataJointErrorbefore any connection is attempted. The message says that 3306 is MySQL's default port and that the backend defaults to PostgreSQL, and lists the ways to setmysqlthat apply to the path taken (dj.configfordj.conn; keyword arguments,DJ_BACKENDordatajoint.jsonfor adj.Instance, whichdj.configdoes not reach). An explicitbackend="postgresql"on port 3306 is allowed. Adatajoint.jsonmade withdj.config.save_template()sets the backend to"postgresql"explicitly, so for a MySQL server change itsbackendto"mysql"rather than only the port.DJ_BACKENDis read case-insensitively, and an empty value counts as not set. Any other invalid backend raises aDataJointErrorthat lists the valid values, instead of a pydanticValidationError.Notes for review
The 3306 check runs in
Connection.__init__, after the backend is resolved and before the adapter is created, so it is never wrapped by the failure hint. It is not in the settings validator: settings are assigned one at a time, so a validator would refuse port 3306 set before the backend, andDJ_PORT=3306would failimport datajointbefore the user could set the backend.Config.override()now restores whether each setting was explicitly set, not only its value, so a backend set inside anoverrideblock does not count as set after it.Re-raising as
DataJointErrorchanges the exception type only when the backend is the default. Code that catches a driver exception (for examplepymysql.err.OperationalError) arounddj.conn()sees it unchanged once the backend is set.This PR is independent of the drivers-as-extras PR. Together, a MySQL user who has only pymysql installed and sets no backend gets the missing-psycopg2 message plus the hint above.