Skip to content

Sorting not working in Food Database#695

Merged
CodeWithCJ merged 2 commits intomainfrom
dev
Feb 20, 2026
Merged

Sorting not working in Food Database#695
CodeWithCJ merged 2 commits intomainfrom
dev

Conversation

@CodeWithCJ
Copy link
Owner

fixes #689

@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @CodeWithCJ, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request addresses a critical bug in the food database's sorting mechanism, which previously led to incorrect ordering of food items, particularly when sorting by nutritional information. The changes focus on enhancing the backend query logic to accurately sort food entries and include new tests to ensure the reliability of this functionality.

Highlights

  • Food Database Sorting Fix: Resolved an issue where sorting in the food database was not functioning correctly, especially for nutritional fields, by refining the SQL query generation.
  • Improved ORDER BY Clause Logic: Modified the getFoodsWithPagination function to correctly apply sorting based on nutritional values (e.g., calories, protein) by referencing the food_variants table, and by food name.
  • Removed DISTINCT ON Clause: Eliminated the DISTINCT ON clause from the food retrieval query to ensure accurate and consistent sorting behavior.
  • New Unit Tests for Sorting: Introduced dedicated unit tests to validate the corrected food sorting functionality, covering various sort criteria and edge cases.
Changelog
  • SparkyFitnessFrontend/package-lock.json
    • Updated @eslint/js to version 9.39.3.
    • Updated ajv to version 6.14.0.
    • Updated eslint to version 9.39.3.
  • SparkyFitnessServer/models/food.js
    • Refactored sanitizeGlycemicIndex, sanitizeNumeric, and sanitizeBoolean functions for improved readability with multi-line conditions.
    • Adjusted the searchFoods function signature for multi-line parameters.
    • Removed the DISTINCT ON clause from the getFoodsWithPagination query.
    • Modified the orderByClause generation in getFoodsWithPagination to correctly sort by nutrition fields (e.g., fv.calories) and food name (f.name).
    • Updated parameter formatting for various database queries across createFood, getFoodById, getFoodOwnerId, updateFood, deleteFood, getFoodDeletionImpact, createFoodsInBulk, getFoodsNeedingReview, updateFoodEntriesSnapshot, and clearUserIgnoredUpdate functions.
    • Added a newline at the end of the file.
  • SparkyFitnessServer/tests/foodSorting.test.js
    • Added a new test file for food database sorting.
    • Implemented unit tests for getFoodsWithPagination to verify correct sorting by calories and name.
    • Included a test to ensure the system falls back to default sorting for invalid sortBy parameters.
    • Verified that the DISTINCT ON clause is not present in the generated queries.
Activity
  • No human activity has been recorded on this pull request yet.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@CodeWithCJ CodeWithCJ merged commit 1bba282 into main Feb 20, 2026
6 checks passed
Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

The pull request successfully addresses the sorting issue in the food database by removing the DISTINCT ON clause, which was overly restrictive for the ORDER BY expressions. The implementation correctly handles both name-based and nutrient-based sorting with appropriate table aliases and whitelisting for security. The addition of unit tests for the query construction logic is a great practice. I've suggested a few improvements to ensure sort stability during pagination and better handling of missing nutrient data.


let query = `
SELECT DISTINCT ON (f.id, f.name, f.brand)
SELECT
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

Removing DISTINCT ON allows for arbitrary sorting, but it also removes the safeguard against duplicate food entries if a food happens to have multiple default variants. While the application logic should ideally prevent this, using a subquery for the join or ensuring a unique constraint in the database would be more robust.

`;

let orderByClause = "f.id, f.name ASC"; // DISTINCT ON requires f.id to be the first sort field
let orderByClause = "f.name ASC";
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

To ensure consistent results across paginated requests, it's recommended to include a unique column (like f.id) as a final tie-breaker in the ORDER BY clause. Without this, Postgres does not guarantee a stable sort order for rows with identical values in the primary sort fields, which can lead to items appearing on multiple pages or being skipped.

Suggested change
let orderByClause = "f.name ASC";
let orderByClause = "f.name ASC, f.id ASC";

) {
orderByClause = `f.id, ${sortField} ${sortOrder.toUpperCase()}`;
if (nutritionSortFields.includes(sortField)) {
orderByClause = `fv.${sortField} ${sortOrder.toUpperCase()}, f.name ASC`;
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

When sorting by nutrition fields in descending order, Postgres defaults to NULLS FIRST. This means foods without a default variant or missing nutrient data will appear at the top of the list. Adding NULLS LAST ensures these items always appear at the end regardless of the sort direction. Additionally, adding f.id ensures a stable sort.

Suggested change
orderByClause = `fv.${sortField} ${sortOrder.toUpperCase()}, f.name ASC`;
orderByClause = `fv.${sortField} ${sortOrder.toUpperCase()} NULLS LAST, f.name ASC, f.id ASC`;

if (nutritionSortFields.includes(sortField)) {
orderByClause = `fv.${sortField} ${sortOrder.toUpperCase()}, f.name ASC`;
} else {
orderByClause = `f.${sortField} ${sortOrder.toUpperCase()}`;
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

Adding f.id as a secondary sort field ensures that the results are deterministic when multiple foods have the same name, which is critical for reliable pagination.

Suggested change
orderByClause = `f.${sortField} ${sortOrder.toUpperCase()}`;
orderByClause = `f.${sortField} ${sortOrder.toUpperCase()}, f.id ASC`;

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Sorting not working in Food Database

1 participant