Skip to content

Conversation

@spacepc-de
Copy link
Contributor

Problem
The DASH block generates a complex SQL query using a CTE (modulenames) that merges names and timestamps from multiple activity modules.
When rendering (especially when determining the total number of pages), this SQL fails on MariaDB — Moodle displays “Error reading from database” and a stack trace pointing to the COUNT query.

Root Cause

  • The CTE references many module tables (assign, bigbluebuttonbn, board, kanban, subsection, …).
    If one or more of these modules are not installed, MariaDB aborts the query.
  • The CTE name was output as {modulenames}. Moodle’s curly-brace notation is meant for real tables, not CTEs — this caused incorrect prefix substitution.
  • The original COUNT logic mixed DISTINCT, GROUP BY, and ORDER BY, or referenced the CTE via a derived subquery — combinations that MariaDB handles poorly.

Fixes / Changes

  • Made COUNT more robust:
    • Removed unnecessary DISTINCT, GROUP BY, and ORDER BY.
    • Use direct WITH … SELECT COUNT(…) … instead of wrapping the CTE in a subquery.
  • Cleaned up CTE name:
    • {modulenames}modulenames and updated all references accordingly.
  • Defensive CTE sanitization:
    • Joins to non-existent module tables are replaced with harmless derived tables that return NULL columns, preventing COALESCE expressions from failing.
    • If an installed module lacks the name or timemodified fields, references are rewritten to NULL.
  • Added optional SQL debug logs (DATA and COUNT) to expose the final executed SQL in debugging mode.

Result

  • No more “Error reading from database” on MariaDB when certain modules are missing.
  • COUNT queries are now stable and compatible across MariaDB, MySQL, and PostgreSQL.

Notes

  • Tested on MariaDB (please specify version if available).
  • No schema or data changes — only SQL/Query-Builder logic updates.

- COUNT robuster: ohne globales DISTINCT/GROUP/ORDER; WITH-CTE + direktes COUNT ohne Unterabfrage
- CTE-Name korrigiert: {modulenames} -> modulenames; alle Verwendungen angepasst
- Defensive CTE-Sanitisierung: fehlende Modultabellen als harmlose Derived Tables; fehlende name/timemodified -> NULL
- SQL-Debuglogs für DATA/COUNT aktiviert, um ausgeführte SQL sichtbar zu machen

Ursache: MariaDB bricht die Abfrage ab, wenn referenzierte Modultabellen nicht existieren oder COUNT mit DISTINCT/GROUP/ORDER aus CTE/Derived-Table kombiniert wird.
@stefanscholz
Copy link
Member

Thank you @spacepc-de — we'll review it internally and get back to you after that.

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

Labels

None yet

Development

Successfully merging this pull request may close these issues.

2 participants