The function db_error() doesn't work if you try to get the latest error on the default connection.

Here's some code to reproduce the issue:

<?php

include_once './includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

$result = db_query("SELECT unknown_field FROM {node}");

print "Error: ".db_error()."\n"; // db_error() always returns 0 but should return 1054 in case of MySQL

?>

The reason for this is that in case of a database error this error is reported via trigger_error(...). Drupal's error handler than calls watchdog(...) with an translated error message. Normally both SQL statements triggered by the translation using t(...) and the insert into the watchdog table don't fail. So the last SQL statement has no error and that's what db_error() returns!

A possible solution is to handle translations and watchdog entries via a dedicated connection.

Another workaround for command line scripts like cron.php is to define another error handler that doesn't trigger watchdog entries but prints out errors.

CommentFileSizeAuthor
#4 db-error.patch4.38 KBvgarvardt

Comments

drumm’s picture

Priority: Critical » Normal

The error should be stored in a static variable in db_error(), which would be set when the error happens.

Bumping priority down since this API is not used much.

pukku’s picture

Version: 5.3 » 6.14

This still seems to be a problem in Drupal 6-14. It does make it difficult to determine if something went wrong.

OmarQot’s picture

I see this is critical, since there is no other way to handle db errors in drupal. if error occur then you continue the normal process which is really bad.

vgarvardt’s picture

Version: 6.14 » 6.17
Status: Active » Needs review
StatusFileSize
new4.38 KB

Please check this patch. I made changes to MySQL, MySQLi and PgSQL, but tested only with MySQL(i).

Status: Needs review » Needs work

The last submitted patch, db-error.patch, failed testing.

vgarvardt’s picture

Can you tell me how to create patch correctly? As I run this patch from Drupal root dir and it applies. Patch tester runs patch from sites/default/files/review

mkalkbrenner’s picture

Status: Needs work » Closed (outdated)

Automatically closed because Drupal 6 is no longer supported. If the issue verifiably applies to later versions, please reopen with details and update the version.