Skip to content

add a sql db function that will retrieve a entry and its fields as ro…#2524

Open
Liviu-p wants to merge 6 commits intomasterfrom
feature/new-sql-entry-db-function
Open

add a sql db function that will retrieve a entry and its fields as ro…#2524
Liviu-p wants to merge 6 commits intomasterfrom
feature/new-sql-entry-db-function

Conversation

@Liviu-p
Copy link
Copy Markdown
Contributor

@Liviu-p Liviu-p commented Oct 1, 2025

No description provided.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Oct 1, 2025

Walkthrough

Adds a new static method FrmEntry::get_entries_with_fields that pivots entry meta values into columns per item_id for given field IDs and aliases, optionally filtered by a WHERE clause. It validates inputs, builds dynamic SELECT with MAX(CASE ...) expressions, groups by item_id, and returns query results.

Changes

Cohort / File(s) Summary
Data retrieval pivot method
classes/models/FrmEntry.php
Added public static function get_entries_with_fields( $field_ids_and_aliases, $where = '' ). Validates input, constructs dynamic SELECT using MAX(CASE WHEN field_id = <id> THEN meta_value END) AS <alias> for each requested field, applies optional WHERE via FrmDb::prepend_and_or_where, groups by item_id, and returns results (empty array on invalid input).

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor Caller
  participant FrmEntry
  participant FrmDb
  participant DB as wp_frm_item_metas

  Caller->>FrmEntry: get_entries_with_fields(field_ids_and_aliases, where)
  alt invalid input
    FrmEntry-->>Caller: []
  else valid input
    FrmEntry->>FrmEntry: build SELECT with MAX(CASE...) AS aliases
    FrmEntry->>FrmDb: prepend_and_or_where(where)
    FrmDb-->>FrmEntry: normalized WHERE clause
    FrmEntry->>DB: SELECT item_id, MAX(CASE ...) AS alias... WHERE field_id IN (...) AND <where> GROUP BY item_id
    DB-->>FrmEntry: rows
    FrmEntry-->>Caller: result rows
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Pre-merge checks and finishing touches

❌ Failed checks (1 warning, 1 inconclusive)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
Description Check ❓ Inconclusive No pull request description was provided, so there is insufficient information to determine whether any text relates to the actual changeset and the author’s intent remains unclear. Because the description is empty rather than simply off-topic or generic, the check must be marked inconclusive until more context is added. Please ask the author to add a brief description summarizing the new get_entries_with_fields method, its purpose, input parameters, and expected output to help reviewers quickly understand the change.
✅ Passed checks (1 passed)
Check name Status Explanation
Title Check ✅ Passed The title clearly describes the main change by indicating the addition of a SQL database function for retrieving an entry along with its fields, which matches the core functionality introduced in the patch.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feature/new-sql-entry-db-function

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between eb51798 and f73e652.

📒 Files selected for processing (1)
  • classes/models/FrmEntry.php (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • classes/models/FrmEntry.php
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (4)
  • GitHub Check: Run PHP Syntax inspection (8.3)
  • GitHub Check: PHP 8 tests in WP trunk
  • GitHub Check: PHP 7.4 tests in WP trunk
  • GitHub Check: Cypress

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Nitpick comments (2)
classes/models/FrmEntry.php (2)

541-606: Consider performance implications for large datasets.

The method has no LIMIT clause or pagination support, which could return large result sets and cause performance issues. Additionally, the pivot query with multiple MAX(CASE WHEN) expressions can be expensive on large datasets.

Consider:

  1. Adding pagination parameters (limit, offset)
  2. Adding a cache layer for frequently accessed pivots
  3. Documenting performance characteristics in the PHPDoc

584-605: Document the double-prepare pattern for clarity
This two-stage wpdb->prepare approach mirrors FrmDb.php (line 443); either refactor to a single prepare call for consistency or explicitly comment its intent where used.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a24133c and 99411c6.

📒 Files selected for processing (1)
  • classes/models/FrmEntry.php (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
classes/models/FrmEntry.php (1)
classes/models/FrmDb.php (2)
  • FrmDb (6-759)
  • prepend_and_or_where (570-590)
🔇 Additional comments (1)
classes/models/FrmEntry.php (1)

580-582: LGTM! Input validation is appropriate.

The validation correctly handles empty input and non-array values, returning an empty array as a safe default.

Comment thread classes/models/FrmEntry.php
Comment thread classes/models/FrmEntry.php
Comment thread classes/models/FrmEntry.php
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

♻️ Duplicate comments (3)
classes/models/FrmEntry.php (3)

587-591: Verify WordPress version compatibility for %i placeholder.

The %i identifier placeholder was introduced in WordPress 6.2. If this plugin supports earlier versions, this will cause prepare errors.

#!/bin/bash
# Check the minimum WordPress version requirement

# Check readme files
fd -e txt -e md 'readme' --exec grep -i "requires at least" {} \;

# Check main plugin file
fd -e php --max-depth 2 -x grep -n "Requires at least" {} \;

If the plugin supports WP < 6.2, either update "Requires at least" to 6.2 or replace %i with manual escaping after validation.


560-560: Update the @SInCE version placeholder.

Replace x.x with the actual version number.


573-573: Document WHERE clause sanitization requirements.

The $where parameter is passed to FrmDb::prepend_and_or_where, which only sanitizes array values—string values are NOT automatically sanitized and must be pre-prepared by the caller to prevent SQL injection.

Apply this diff:

- * @param string|array $where The where SQL clause to add to the query.
+ * @param string|array $where The WHERE SQL clause to add to the query.
+ *                            SECURITY: If passing a string, it must be pre-sanitized/prepared.
+ *                            If passing an array, use FrmDb format: array('field' => 'value').
+ *                            String values are NOT automatically sanitized.
🧹 Nitpick comments (1)
classes/models/FrmEntry.php (1)

586-586: Consider rejecting invalid aliases instead of silently sanitizing.

The current approach strips invalid characters, which could lead to unexpected column names (e.g., "my-column" becomes "mycolumn"). Consider validating and returning an empty array for invalid aliases to make errors more obvious.

Optional refactor:

 	$select_case_parts = array();
 	foreach ( $field_ids_and_aliases as $fid => $alias ) {
-		$safe_alias          = preg_replace( '/[^a-zA-Z0-9_]/', '', $alias );
+		// Validate alias as a safe identifier (alphanumeric and underscores only)
+		if ( ! preg_match( '/^[a-zA-Z_][a-zA-Z0-9_]*$/', $alias ) ) {
+			return array();
+		}
 		$select_case_parts[] = $wpdb->prepare(
 			'MAX(CASE WHEN field_id = %d THEN meta_value END) AS %i',
 			absint( $fid ),
-			$safe_alias
+			$alias
 		);
 	}
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 99411c6 and 05bfe93.

📒 Files selected for processing (1)
  • classes/models/FrmEntry.php (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
classes/models/FrmEntry.php (1)
classes/models/FrmDb.php (2)
  • FrmDb (6-759)
  • prepend_and_or_where (570-590)
🔇 Additional comments (2)
classes/models/FrmEntry.php (2)

580-582: LGTM!

Input validation correctly guards against empty or non-array input.


605-607: LGTM!

Query execution properly uses prepared statements, and returning results directly is safe as $wpdb->get_results returns an empty array on failure.

@Liviu-p Liviu-p requested a review from Crabcyborg October 2, 2025 15:25
Comment thread classes/models/FrmEntry.php Outdated
@Crabcyborg Crabcyborg modified the milestones: 6.25, 6.25.1 Oct 10, 2025
@Crabcyborg Crabcyborg modified the milestones: 6.25.1, 6.26 Nov 3, 2025
@Crabcyborg Crabcyborg modified the milestones: 6.26, 6.27 Dec 8, 2025
@Crabcyborg Crabcyborg modified the milestones: 6.27, 6.28 Jan 13, 2026
@Crabcyborg Crabcyborg modified the milestones: 6.28, 6.29 Feb 3, 2026
@Crabcyborg Crabcyborg modified the milestones: 6.29, 6.30 Mar 9, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants