PostgreSQL error when sorting a table filtered by a many-to-many association

Describe the bug

When a table is filtered through a many-to-many association, sorting by a normal field of the root collection causes a PostgreSQL GROUP BY error.

Without sorting, the filtered table works correctly.

In my case, the root collection is Mtr_proyectos and the filter uses a many-to-many association (proyectos_responsables).

When I sort by the root collection field fecha_creacion, NocoBase sends:

sort[]=fecha_creacion

and PostgreSQL returns:

column "Mtr_proyectos.fecha_creacion" must appear in the GROUP BY clause or be used in an aggregate function

The stack trace points to:

@nocobase/database/lib/eager-loading/eager-loading-tree.js:242

This is NOT sorting by an association field. The association is only used as a filter. The sorted field (fecha_creacion) belongs directly to the root collection.

Cause found

In:

@nocobase/database/lib/eager-loading/eager-loading-tree.js

the GROUP BY is built with:

const group = [`${node.model.name}.${primaryKeyField}`];

if (this.db.inDialect("mssql") || this.db.isMySQLCompatibleDialect()) {
  group.push(
    ...getRootModelOrderFields(node).map(
      (field) => `${node.model.name}.${field}`
    )
  );
}

getRootModelOrderFields(node) already obtains the root model fields used for sorting.

However, these fields are only added to the GROUP BY for MSSQL and MySQL-compatible databases, not PostgreSQL.

Therefore, with PostgreSQL, sorting by fecha_creacion while the many-to-many filter requires grouping results in a query equivalent to:

GROUP BY "Mtr_proyectos"."id"
ORDER BY "Mtr_proyectos"."fecha_creacion"

PostgreSQL rejects this query.

Tested workaround

I changed only the dialect condition to also include PostgreSQL:

if (
  this.db.inDialect("mssql") ||
  this.db.inDialect("postgres") ||
  this.db.isMySQLCompatibleDialect()
) {
  group.push(
    ...getRootModelOrderFields(node).map(
      (field) => `${node.model.name}.${field}`
    )
  );
}

After restarting NocoBase, the same many-to-many filter works correctly and the table can be sorted by fecha_creacion without any PostgreSQL error.

No database changes were required.

Steps to reproduce

  1. Create a root collection with a many-to-many association.
  2. Create a table block for the root collection.
  3. Filter the table using the many-to-many association.
  4. Confirm that the filtered table loads correctly.
  5. Sort the table by a normal field belonging directly to the root collection.
  6. PostgreSQL returns the GROUP BY error.

Environment

  • NocoBase version: 2.1.45
  • Database: PostgreSQL
  • OS: Ubuntu 22.04
  • Deployment method: Docker
  • Docker image: nocobase/nocobase:latest-full

Hello, thank you for your feedback. Please wait for us to fix it.