From 5525d22a9bc5f050a235dfcee78f7ac4643878a4 Mon Sep 17 00:00:00 2001 From: Sergey Tsalkov Date: Fri, 4 Mar 2011 17:07:23 -0500 Subject: [PATCH] we can now throw an exception on errors if DB::$throw_exception_on_error is set --- db.class.php | 19 ++++++++++++++++++- simpletest/BasicTest.php | 30 +++++++++++++++++++++++++++++- 2 files changed, 47 insertions(+), 2 deletions(-) diff --git a/db.class.php b/db.class.php index 4eaf1a6..412404d 100644 --- a/db.class.php +++ b/db.class.php @@ -16,8 +16,9 @@ class DB public static $password = ''; public static $host = 'localhost'; public static $encoding = 'latin1'; - public static $queryMode = 'queryAllRows'; //buffered, unbuffered, queryAllRows + public static $queryMode = 'queryAllRows'; public static $error_handler = 'meekrodb_error_handler'; + public static $throw_exception_on_error = false; public static function get($dbName = '') { static $mysql = null; @@ -298,6 +299,11 @@ class DB 'error' => $error )); } + + if (DB::$throw_exception_on_error) { + $e = new MeekroDBException($error, $sql); + throw $e; + } } else if (DB::$debug) { $runtime = sprintf('%f', $runtime * 1000); $sqlShow = "$sql (" . ($is_buffered ? 'MYSQLI_STORE_RESULT' : 'MYSQLI_USE_RESULT') . ")"; @@ -485,6 +491,17 @@ class DBTransaction { } +class MeekroDBException extends Exception { + protected $query = ''; + + function __construct($message='', $query='') { + parent::__construct($message); + $this->query = $query; + } + + public function getQuery() { return $this->query; } +} + function meekrodb_error_handler($params) { $out[] = "QUERY: " . $params['query']; $out[] = "ERROR: " . $params['error']; diff --git a/simpletest/BasicTest.php b/simpletest/BasicTest.php index 559aae9..01dcd7f 100644 --- a/simpletest/BasicTest.php +++ b/simpletest/BasicTest.php @@ -108,9 +108,37 @@ class BasicTest extends SimpleTest { DB::$error_handler = 'new_error_callback'; DB::query("SELET * FROM accounts"); - $this->assert($error_callback_worked === 1); } + + function test_6_exception_catch() { + DB::$error_handler = ''; + DB::$throw_exception_on_error = true; + try { + DB::query("SELET * FROM accounts"); + } catch(MeekroDBException $e) { + $this->assert(substr_count($e->getMessage(), 'You have an error in your SQL syntax')); + $this->assert($e->getQuery() === 'SELET * FROM accounts'); + $exception_was_caught = 1; + } + $this->assert($exception_was_caught === 1); + + try { + DB::insert('`libdb_test`.`accounts`', array( + 'id' => 2, + 'username' => 'Another Dude\'s \'Mom"', + 'password' => 'asdfsdse', + 'age' => 35, + 'height' => 555.23 + )); + } catch(MeekroDBException $e) { + $this->assert(substr_count($e->getMessage(), 'Duplicate entry')); + $exception_was_caught = 2; + } + $this->assert($exception_was_caught === 2); + + + } }