Files
wms-app/app/assets/utils/db_helpers.php
T

100 lines
3.0 KiB
PHP

<?php
/**
* Check PDO statement for errors
* Logs full error server-side, returns generic message to client
*
* @param PDOStatement $sth - The executed PDO statement
* @param array &$answer - Response array passed by reference
* @param array $options - Optional settings:
* 'message' => Custom client-facing error message
* 'log' => Custom server log label
* 'code' => HTTP response code (default: 500)
* 'before_exit' => Callback function before exit
*
* @example
* // Simple — use all defaults
* db_check($sth, $answer);
*
* @example
* // Custom client message
* db_check($sth, $answer, [
* 'message' => "Contact not found."
* ]);
*
* @example
* // Custom log label + message
* db_check($sth, $answer, [
* 'log' => "Failed to fetch contact",
* 'message' => "Could not load contact. Please try again."
* ]);
*
* @example
* // Custom HTTP status code
* db_check($sth, $answer, [
* 'code' => 403,
* 'message' => "Access denied."
* ]);
*
* @example
* // Cleanup callback before exit
* db_check($sth, $answer, [
* 'message' => "Upload failed.",
* 'before_exit' => function() use ($tmp_file) {
* if(file_exists($tmp_file)) unlink($tmp_file);
* }
* ]);
*/
function db_check($sth, &$answer, $options = []) {
if ($sth->errorInfo()[0] != "00000" && !empty($sth->errorInfo()[0])) {
$trace = debug_backtrace()[0];
$log_message = $options['log'] ?? "DB Error";
error_log($log_message . " in " . $trace['file'] . " line " . $trace['line'] . ": " . $sth->errorInfo()[2]);
// production version
$answer["message"] = $options['message'] ?? "A server error occurred. Please try again.";
http_response_code($options['code'] ?? 500);
if(isset($options['before_exit'])) {
call_user_func($options['before_exit']);
}
exit(json_encode($answer));
}
}
// transaction wrapper with retry logic for deadlocks
function dbTransaction($pdo, $callback, $maxRetries = 3) {
for ($attempt = 0; $attempt < $maxRetries; $attempt++) {
try {
$pdo->beginTransaction();
$result = $callback($pdo);
$pdo->commit();
return $result;
} catch (PDOException $e) {
$pdo->rollBack();
if ($e->getCode() == '40001' && $attempt < $maxRetries - 1) {
usleep(600000 * ($attempt + 1));
continue;
}
error_log("[DB ERROR] " . $e->getMessage() . " | " . $e->getFile() . ":" . $e->getLine());
throw $e;
} catch (Exception $e) {
$pdo->rollBack();
error_log("[ERROR] " . $e->getMessage() . " | " . $e->getFile() . ":" . $e->getLine());
throw $e;
}
}
}
?>