Back to all reviewers

Guard database query results

appwrite/appwrite
Based on 3 comments
PHP

Always validate database query results before accessing their methods or properties. Methods like `findOne()`, `getDocument()`, and similar database operations can return null or empty documents. Failing to check these results before access leads to runtime errors.

Null Handling PHP

Reviewer Prompt

Always validate database query results before accessing their methods or properties. Methods like findOne(), getDocument(), and similar database operations can return null or empty documents. Failing to check these results before access leads to runtime errors.

Example of unsafe code:

$latestDeployment = $dbForProject->findOne('deployments', [ /* ... */ ]);
$latestBuild = $dbForProject->getDocument('builds', 
    $latestDeployment->getAttribute('buildId', '')  // May throw if $latestDeployment is null
);

Safe pattern:

$latestDeployment = $dbForProject->findOne('deployments', [ /* ... */ ]) 
    ?? new Document();  // Provide empty fallback

if (!$latestDeployment->isEmpty()) {  // Check before accessing
    try {
        $latestBuild = $dbForProject->getDocument(
            'builds',
            $latestDeployment->getAttribute('buildId', '')
        );
    } catch (Throwable $e) {
        $latestBuild = new Document();  // Handle failure gracefully
    }
}

Key practices:

  1. Provide fallback empty documents when queries may return null
  2. Check document existence before accessing properties
  3. Use try-catch when chaining dependent queries
  4. Consider logging failed lookups in production environments
3
Comments Analyzed
PHP
Primary Language
Null Handling
Category

Source Discussions