Skip to content

DataJoint Library 2.3.7

Latest

Choose a tag to compare

@github-actions github-actions released this 04 Dec 16:19
a209058

DataJoint 2.3.7, the last 2.3 release, fixes queries, deletes, table definitions, storage and PostgreSQL support.

It contains 2.3.6 and the bug fixes merged since 2.3.5. The 2.3 line gets no further releases except possible security fixes; move to 2.4 when you can. Several fixes change results that earlier releases returned without an error, so read the behavior changes below before upgrading.

Upgrade with pip install --upgrade "datajoint>=2.3.7". The conda-forge package follows within about an hour of PyPI.

Behavior changes

Deletes

  • A delete restricted by another query, such as (Subject & (Session & "quality = 0")).delete() or (Subject & Session).delete(), now deletes the rows the restriction selects (#1610; #1611). Before, it raised Attribute ... is not found in query or deleted nothing. A delete whose restriction contains %, such as (Label & "name = '50%'").delete() or {"name": "50%"}, now deletes the matching rows instead of returning 0 (#1636; #1611).
    • Adapt: deletes that removed no rows under 2.3.6 now delete them. Preview with dj.Diagram.cascade(restricted).counts(), or call delete(prompt=True) and check the counts before answering, before running a delete that relied on the old behavior. The 2.3.5 workaround (T & (T & cond).keys()).delete() still works and can stay.
  • With the default part_integrity="enforce", delete() refuses, before deleting anything, a delete that would keep a master row but remove some of its part rows, and dj.Diagram.cascade() previews raise the same error (#1760; #1764). Before, the check compared whole tables after deleting, so a cascade that also removed other rows of the master table committed the split.
    • Adapt: such a delete or preview now raises DataJointError naming the part table and its master. Pass part_integrity="cascade" to delete those masters with all their parts, or part_integrity="ignore" to delete only the part rows reached.
  • Part tables are now recognized in schemas whose names contain hyphens, $ or spaces (#1719; #1728). In such schemas, delete() and drop() now enforce the master-part rule, part_integrity="cascade" reaches the master, and diagrams and topo_sort place each part after its master. Before, all of these were skipped without a warning. Schema names containing a dot remain unsupported.
    • Adapt: in such a schema, deleting or dropping a part table without its master now raises. Delete or drop from the master instead. For delete(), pass part_integrity="cascade" to include the masters. For either call, pass part_integrity="ignore" to keep the old behavior.

Queries

  • A.aggr(B & cond, ...) keeps every row of A again, as documented, when B is restricted (#1650; #1655). Before, Parent.aggr(Child & "color='red'", n="count(child_id)") returned only parents with a red child; now the others come back with n = 0. The same fix applies to Child.extend(Parent & cond) and to a union whose second operand is restricted, which now keep unmatched rows with NULLs.
    • Adapt: pass exclude_nonmatching=True to aggr, use a join (*) instead of extend, or restrict the result (for example & "n > 0").
  • An expression limited by dj.Top keeps its limit when used inside another query: in joins, aggr, extend, dj.U, unions, proj() and as a restriction (#1656, #1666; #1657). Before, such queries returned every matching row without a warning, or failed with a SQL error (MySQL error 1235 for Parent & (Child & dj.Top(...))). Chained dj.Top limits and to_dicts(limit=..., offset=...) on a limited expression stay within the first limit, and Diagram.restrict() honors a dj.Top seed.
    • Adapt: queries that returned the full set now return the limited rows. dj.U(attrs) & (expr & dj.Top(n, ...)) now limits expr first; for the first n distinct values write (dj.U(attrs) & expr) & dj.Top(n, ...). A negated dj.Top, or one inside a list or AndList, now raises DataJointError; replace T - dj.Top(n) with T & dj.Top(None, order_by=..., offset=n).
  • dj.U(...) & expr stays free of repeated rows when used inside another query (#1660; #1662). Parent * (dj.U("parent_id") & Child) returns one row per parent instead of one per child, aggr over such an operand counts each key once, and dj.U(...) & union returns distinct rows. len() now counts the rows to_dicts() returns. Queries that cannot return repeated rows no longer add a DISTINCT or a deduplicating UNION, which makes some queries on PostgreSQL much faster.
    • Adapt: counts and joins that included repeated rows now return one row per key; check code that compensated for the repeats. len(Parent * keyless) now equals the number of fetched rows rather than the number of distinct primary keys.
  • dj.U(...).aggr(group, ...) aggregates the rows that group returns when it is a union, an aggregation, or has computed or renamed attributes (#1661; #1733). Before, a union's second operand was dropped, an inner aggregation's grouping and restrictions were lost, and grouping by a renamed attribute grouped by the original column. dj.U().aggr(Parent.aggr(Child, n="count(child_id)"), k="count(*)") now counts parents, not parent-child pairs.
    • Adapt: an aggregate that names a column the group does not have (a column's name before a rename, a column the projection dropped, or a column of an inner aggregation's table) now raises UnknownAttributeError. Name the group's own attribute (max(pid)) or keep the column in the projection (Child.proj("color", score="child_id * 10")).
  • A dict restriction on a JSON path whose value holds non-ASCII text, such as {"data.sub": {"name": "Zoë"}}, now matches the rows that hold it; in 2.3.6 it matched none. A bytes value for a uuid attribute, in a restriction or an insert, now raises DataJointError instead of TypeError (#1715; #1735).
    • Adapt: catch DataJointError instead of TypeError when passing bytes for a uuid attribute.
  • proj() raises DataJointError: Attribute `nonexistent` not found. when a rename or copy names an attribute the query does not have, as in T.proj(c="nonexistent") (#1677; #1681). Before, the new attribute was left out without a warning. Contributed by @mayuriphad.
    • Adapt: fix the attribute name passed to proj().
  • A string restriction whose literal has a backslash right before a quote, or ends in a backslash, now runs instead of raising Attribute ... is not found in query (#1697; #1722). This became more common after 2.3.6 changed how quotes in MySQL literals are written. The SQL sent was already correct.
    • Adapt: on PostgreSQL, column names written in double quotes in a string restriction, as in "name" = 'x', are now checked against the query. A double-quoted name the query does not have now raises; fix the name.

Table definitions

  • The declared type that DataJoint stores at the start of a column comment (:int32:, :<blob>:) is read back only when it is a known core or codec type and does not span lines, and a jobs table refuses an inherited key attribute whose name or type contains a line break (#1711; #1721).
    • Adapt: only tables whose column comments were edited outside DataJoint to start with an unrecognized :word: marker are affected. describe() and the heading now show that text as part of the comment, and the attribute shows its database type. Remove such markers, or move them later in the comment.
  • On PostgreSQL, describe() now shows secondary indexes and the [unique] option of foreign keys, and alter() with an unchanged definition no longer raises NotImplementedError on tables with secondary indexes (#1699; #1751). On both backends, alter() compares indexes regardless of their order.
    • Adapt: an index that contains an expression (such as a JSON path or lower(b)) is now left out of heading.indexes and describe() on both backends, instead of being shown by its plain columns alone (a unique index on (a, lower(b)) used to appear as UNIQUE INDEX (a)). If you regenerate definitions from describe(), add such indexes back by hand.
  • On PostgreSQL, alter() now changes an attribute's type, nullability, default and comment, changes the table comment, and renames attributes, as it does on MySQL (#1625; #1639). The changes run in one transaction, so a failure leaves the table as it was, and a conversion with no meaning (such as a date to a number) raises before anything runs. describe() on PostgreSQL writes defaults without the server's type cast (1.5 instead of '1.5'::real).
    • Adapt: before, these changes on PostgreSQL failed with a syntax error, were ignored (comment-only changes) or were refused (renames). Table.alter() keeps its signature. Code that calls the internal datajoint.declare.alter directly must pass full_table_name instead of schema_name and expect a 3-tuple. MySQL statements are unchanged.
  • A new setting, blob.max_decompressed_size (environment variable DJ_BLOB_MAX_DECOMPRESSED_SIZE), refuses to expand a compressed blob whose recorded size exceeds it (#1717; #1738). It is unset by default, so nothing changes unless you set it. Foreign-key references again accept any Python identifier as a name, as in 2.3.5 and earlier, and dj.Diagram now draws a schema whose column names contain quotes or backslashes, or whose tables cannot be described.
    • Adapt: with the setting on, fetching a larger compressed blob raises DataJointError. If a projected foreign-key attribute has a name that is not a Python identifier (for example a column renamed in SQL to a-b), describe() now warns and alter() raises; rename the column first.

Jobs

  • populate() records the hidden _job_start_time on the database server's clock, so it lines up with the job table's reserved_time and completed_time, and workers in different time zones record the same value for the same moment (#1584; #1622). Before, it was the worker's local time with no zone.
    • Adapt: rows written before 2.3.7 keep the worker's local time and cannot be corrected, because the zone was never recorded. Code that compares _job_start_time with a local clock, or across old and new rows, should expect new rows in the server's time.
  • refresh(stale_timeout=0), and populate() with config.jobs.stale_timeout = 0, now remove at once every job whose key has left key_source, whatever its age, except jobs marked ignore (#1577; #1623). Before, 0 skipped the check and left all such jobs in place. Leaving stale_timeout unset still uses the configured grace period (3600 seconds by default).
    • Adapt: if you set stale_timeout to 0 to keep such jobs, set a long timeout instead (for example config.jobs.stale_timeout = 10**9). 0 now removes them, including reserved jobs.

Storage

  • Store attributes declared with a bare @, such as <npy@>, <object@>, <blob@>, <attach@>, <hash@> and <filepath@>, now use stores.default (or stores.filepath_default for <filepath@>) as documented (#1574; #1575). Before, every insert, fetch or garbage collection on such a column raised "Storage '' is requested but not configured in stores". Garbage collection of the default store also counts these columns' files as referenced.
    • Adapt: make sure stores.default and stores.filepath_default name the stores these columns should use before inserting.
  • Garbage collection no longer deletes files when it fails to read a table or attribute for references (#1689). Each such failure is now a scan error: collect(dry_run=False) raises DataJointError("Refusing to delete: ...") without deleting anything, and collect(dry_run=True) returns its report with the failures under scan_errors. Before, the failing table was skipped and the files only it referenced were deleted as unreferenced.
    • Adapt: a table whose heading cannot be loaded, such as one with a pre-2.0 external column or an invalid codec type, now blocks collect(dry_run=False). Run a dry run to see the scan_errors, then migrate or drop that table before collecting.
  • Garbage collection keeps the stored objects of custom codecs that store through <hash@>, <blob@>, <attach@>, <object@> or <npy@> (#1700; #1752). Before, collect(dry_run=False) did not scan such columns and deleted their objects, and fetching those rows then raised MissingExternalFile.
    • Adapt: a column whose codec plugin is not installed is now scanned instead of skipped, and its failed scan blocks deletion. Install the codec package (or drop the column) and collect again; a dry run lists the column under scan_errors.
  • staged_insert1 stores <object@> values the way insert1 does: the object's path uses the table name instead of the Python class name, and the row records the resolved store name instead of "" for the default store (#1701; #1741). Objects inserted this way stay readable after stores.default changes, and garbage collection no longer counts them as unreferenced. Contributed by @godara-alt.
    • Adapt: rows staged earlier keep their class-name folders. On a case-insensitive file store, run collect(dry_run=True) first and review its report before collecting.
  • ObjectRef.full_path now includes the store's location on s3, gcs and azure stores, so ref.fs.exists(ref.full_path) and ref.fs.open(ref.full_path) find the object that ref.read() opens (#1646; #1648). Local file stores are unchanged. Contributed by @TheeCoderAhmed.
    • Adapt: stop adding the store location to full_path by hand on these stores.
  • Follow-ups to the 2.3.6 file-store changes (#1713; #1731): an insert into a <filepath@> column with no store named now checks the path in stores.filepath_default, the store it records, instead of stores.default. Folder downloads work on fsspec older than 2023.9 for keys containing [, * or ?, empty folder objects download on fsspec older than 2024.3.1, and fetching an <attach> value can no longer hang on the check for an existing file of the same name.
    • Adapt: when stores.filepath_default and stores.default name different stores, place <filepath@> files in stores.filepath_default.
  • Columns declared blob@store, attach@store or filepath@store in a 0.14 schema can be fetched in 2.x after the documented migration, whether the schema is copied into a 2.x schema or migrated in place (#1698; #1753). A rerun repairs columns that an earlier 2.x migration left unreadable, create_parallel_schema copies schemas whose foreign keys reference tables that sort after them, and garbage collection keeps migrated 0.14 files in stores that use the root-level layout. See Migrate In-Store Metadata in the Migration Guide.
    • Adapt: when migrating a copy of a 0.14 schema (for example one made with create_parallel_schema(..., copy_data=True)), pass legacy_database="<original database>" to migrate_external, migrate_external_pointers_v2, copy_table_data and verify_external_integrity; without it these calls refuse and change nothing. Columns repaired from an earlier 2.x migration stay nullable; restore NOT NULL in SQL where needed.

Blobs

  • Character matrices are now written in column-major order, as MATLAB writes them, so they round-trip through <blob> unchanged (#1702; #1743). Contributed by @godara-alt.
    • Values with two or more dimensions larger than 1 that earlier Python versions of DataJoint wrote read back with their elements rearranged (not transposed). For example, np.array([[b"a", b"b", b"c"], [b"d", b"e", b"f"]]) written by 2.3.6 or earlier reads back as [['a','c','e'], ['b','d','f']].
    • Adapt: restore such a fetched value v with v.flatten(order='F').reshape(v.shape). Never apply this to values MATLAB wrote.
    • Single rows, strings and values MATLAB wrote are unchanged.
    • In hash-addressed storage, such matrices get new hashes.

Connection

  • A use_tls dict with an unknown key, such as ssl_ca for ca, now raises DataJointError naming the key and listing the accepted ones, on MySQL and PostgreSQL (#1714; #1732). Before, MySQL ignored it and connected without the intended certificate check. On MySQL, an unknown verify_mode value raises, and an ssl.VerifyMode such as ssl.CERT_REQUIRED is now applied, verifying against the system's trusted CAs when no ca is given. On PostgreSQL, use_tls=None falls back to a connection without TLS when the server has no SSL, whatever language the server's messages are in.
    • Adapt: use only the keys ca, capath, cert, key, password, cipher, check_hostname and verify_mode. On PostgreSQL only ca, cert, key, password and, with ca, check_hostname take effect; the others log a warning and are ignored. Give verify_mode as a boolean, one of 'none', 'optional' or 'required', or an ssl.VerifyMode. With verify_mode=ssl.CERT_REQUIRED and no ca, a server with a self-signed certificate now fails verification; pass the server's CA as ca.
  • conn.is_connected is False and repr(conn) says "disconnected" once the server has dropped the connection, as in 2.0, and conn.ping() raises LostConnectionError for a dropped or closed connection (#1775; #1777). Since 2.1 they reported such a connection as connected. On PostgreSQL, a connection inside a failed transaction still counts as connected.
    • Adapt: code that calls conn.ping() directly should catch dj.errors.LostConnectionError, or check conn.is_connected. Changing use_tls is refused while a transaction is recorded, even one lost with its connection.
  • On PostgreSQL, a query after the server drops the connection, for example after an idle-session timeout on a managed database, now reconnects and runs again, as it already did on MySQL (#1776; #1778). Inside a transaction it raises LostConnectionError("Connection was lost during a transaction.") instead of the driver's own error.
    • Adapt: catch dj.errors.LostConnectionError instead of psycopg2.OperationalError or psycopg2.InterfaceError. With database.reconnect on (the default), queries outside a transaction no longer raise.

Configuration

  • Environment variables now take precedence over datajoint.json for every setting that reads one, as documented (#1585; #1603). Before, the file won for jobs.* (DJ_JOBS_*), provenance.*, database.use_tls (DJ_USE_TLS), database.reconnect, safemode, query_cache, download_path, ignore_config_file and allow_filepath_outside_store.
    • Adapt: if a deployment sets one of these environment variables and relied on datajoint.json to override it, unset the variable or set it to the value you want.
  • DJ_LOG_LEVEL accepts any case (DJ_LOG_LEVEL=error no longer fails at import), and a loglevel set in datajoint.json takes effect from import on instead of being reset to INFO (#1718; #1736). Loading configuration from <path> is logged at DEBUG for the file found at import and by dj.Instance(...), and still at INFO for dj.config.load(path). A config or secrets file skipped because another user owns it in a writable location now also issues a UserWarning, and using another user's file from a protected directory logs one INFO line naming it.
    • Adapt: set DJ_LOG_LEVEL=debug to see which config file was loaded. DJ_LOG_LEVEL still overrides loglevel from datajoint.json. Filter the new UserWarning if a skipped file is intentional.

Dependencies

  • Every core dependency now declares a tested minimum version (#1653): numpy>=1.22.4, pandas>=2.2.2, deepdiff>=6.6.0, pyparsing>=3.1.1, tqdm>=4.66.3, networkx>=3.0, pydot>=3.0.0 and packaging>=22.0. The other floors are unchanged: fsspec>=2023.1.0 and pydantic-settings>=2.0.0. These rule out combinations that installed but failed: pandas older than 2.2.2 with numpy 2 fails on import, pyparsing 3.1.0 drops the quotes from = "" defaults, declaring the attribute with no default, and pydot 2.x produces diagrams that Graphviz rejects.
    • Adapt: pip upgrades older installed versions of these packages. Environments that pin a version below these minimums must raise the pin.
  • DataJoint now requires pymysql[rsa]>=1.2.4, which installs cryptography (#1750; #1756). Since 2.3.6, use_tls=False disables TLS on MySQL. Without TLS, a MySQL 8 login with caching_sha2_password or sha256_password needs cryptography and PyMySQL 1.2.4 or later, and it failed with "'cryptography' package is required" whenever the server had no cached login for the account (a new account, a server restart, a password change). 2.3.7 now installs both.
    • Adapt: allow PyMySQL to upgrade to 1.2.4 or later and cryptography to install. Conda environments need pymysql>=1.2.4 and cryptography listed directly.

Guidance

  • The delete() docstring now says that prompt=True is for development and interactive work: it holds the transaction open while it waits for an answer, which can block other users' writes on the affected tables (#1682; #1690). In production, preview with dj.Diagram.cascade(restricted).counts(), then call restricted.delete(prompt=False) with the same part_integrity. The behavior of delete() is unchanged.

Fixes

Queries

  • len() works on queries with no primary key (#1580, #1581; #1605). len(dj.U() & T) returns 0 or 1, and len() of a table with no primary key, such as one created in plain SQL and opened with dj.FreeTable, returns its row count with repeated rows included; both used to raise a SQL syntax error. Restricting a dj.U() aggregation, as in dj.U().aggr(T, n="count(*)") & "n = 3", filters rows instead of raising AssertionError, and restricting any aggregation by False returns an empty result instead of raising TypeError.
  • A join or restriction on two same-named attributes that are not linked through a foreign key now reports that they are unrelated, names the attribute and the side that does not inherit it, and suggests renaming or excluding it with .proj() (#1640; #1642). Before, the error suggested schema.rebuild_lineage(), which could not help. The join is still refused; only the message changes.
  • Restricting by a union, as in A & (B + C) or A - (B + C), now works instead of raising TypeError (#1739; #1755). A union whose left operand is itself a union of operands with secondary attributes no longer fails on fetch and len().
  • On MySQL, a key fetched from a table with a time attribute restricts its own table, so deleting by it and populating below it work (#1762; #1765). Before, the timedelta value MySQL returns for time raised "Unsupported value of type timedelta". numpy.timedelta64 values from a DataFrame also restrict, with NaT matching NULL.
  • On PostgreSQL, renaming an attribute in a projection of a dj.U restriction, such as (dj.U("b") & T).proj(c="b"), no longer fails with a quoting error (#1638; #1643). Contributed by @mayuriphad.

Deletes

  • A cascade delete, Diagram.restrict() and Diagram.trace() no longer copy a string restriction to related tables. They now reach those tables through the rows the restriction selects (#1757; #1758). Dict, key and query restrictions are handled as before.
  • A delete or Diagram.cascade() preview whose seed is a projection that renames primary-key attributes, restricted by dj.Top or by a subquery ((T.proj(sid="subject") & dj.Top(1)).delete()), now covers only the rows the seed selects (#1784; #1786). Before, it covered every row of the table and its descendants.
  • Pressing Ctrl-C at the delete() confirmation prompt or between its delete statements, or reaching end of input at the prompt (as in a script run without a terminal), now rolls back the delete and leaves the connection usable (#1691; #1734). Before, the connection stayed inside the delete's transaction, so later inserts and deletes on it were lost and the deleted rows stayed locked. If the final commit itself fails or is interrupted, the connection is closed and a warning says the delete may or may not have been committed.

Table definitions

  • A column that a foreign key copies from its parent keeps the parent's core type (int32, int16, uuid, float64) on both backends, so the child's heading, describe(), and tables built from the child (further children, jobs tables) show the same type as the parent (#1578; #1579). The "Native type 'int' is used" warnings when a jobs table is created are gone. On PostgreSQL, copied columns also keep the parent's comment. This applies to tables declared from 2.3.7 on.
  • Attribute and table comments containing double quotes, single quotes or backslashes are stored exactly as declared on both backends (#1729; #1754). Before, PostgreSQL stored a backslash before each double quote (and describe() output added more each time it was declared again), MySQL failed to declare a table comment containing a double quote, and MySQL read a backslash in a comment as an escape (\n became a line break). On MySQL with the NO_BACKSLASH_ESCAPES SQL mode, each backslash in a comment is stored doubled. Comments already stored are not rewritten; to clean one, correct it in the class definition and run alter().
  • On PostgreSQL, a table with an index on a JSON path, such as index(data.size:int32) or a unique index mixing a column and a JSON path, now declares (#1672; #1684). Contributed by @mayuriphad.
  • describe() reads an enum whose values contain a colon, such as enum('10:00','11:00'), correctly, so its output declares the same table again (#1724; #1730). alter() on such a table now runs instead of failing with Unsupported attribute type, and a rename of such an attribute keeps its values on MySQL.

Jobs

  • On MySQL, refresh() of the job table stays fast when key_source is restricted by part tables, such as A * B & A.Item & B.Item (#1673; #1674). In the reported case one refresh took about two minutes; it now takes about as long as reading key_source itself.

Diagrams

  • dj.Diagram produces the same output in every run: the SVG, dot source and Mermaid text are identical byte for byte, and sibling tables such as two part tables of one master no longer trade places between runs (#1551; #1606). A committed figure now changes only when the pipeline does. A diagram may lay out differently from earlier releases, once.
  • A new setting, display.diagram_fontname (environment variable DJ_DIAGRAM_FONTNAME), sets the typeface of table and schema labels in Graphviz diagrams (#1539; #1624). It defaults to Helvetica, so diagrams look the same unless you set it. Graphviz sizes boxes with the fonts installed where it renders. Mermaid output is unchanged.

Storage

  • On Windows, writing a file into a file store overwrites an existing file instead of raising FileExistsError (#1744; #1746). On every OS, each write uses its own temporary file, so two processes writing the same path no longer share one, and a failed write leaves no *.copying or *.saving file behind. Contributed by @Ramnath0521.

Connection

  • On PostgreSQL, a login with only SELECT privileges now sees primary and foreign keys (#1554; #1604). Before, Table.primary_key was empty for such a login, key_source raised, and len() failed.

Configuration

  • The deprecation warning for database.database_prefix no longer says the setting will be removed in 2.3; it says it will be removed in a future release and is not applied to schema names (#1675; #1727). The setting is read and ignored as before.

Packaging

  • The package is named the DataJoint Library in the README and the PyPI summary, distinct from the DataJoint Platform (#1570).
  • The pipeline figure in the README now shows on PyPI (#1688).
  • Releases are published to PyPI from annotated tags through trusted publishing; git show v2.3.7 prints these notes (#1588).

Development

  • Tests and CI run on the official mysql:8.4 and mysql:8.0 images and use SeaweedFS as the S3-compatible test store (#1726, #1647).
  • docker compose build app and the djtest test service build again without a .git directory in the image (#1723; #1737). The image reports version 0.0.0+docker unless DJ_BUILD_VERSION is set, as in DJ_BUILD_VERSION=2.3.7 docker compose build app.