2009年9月4日星期五

[fw-db] Adding SQL and bound parameters info to a DB exception?

At work we use bound parameters a lot. Not the basic string replacement like
('client_id = ?', 12) but like (client_id = :CLIENT_ID, 12) then it's
prepared on the server and executed, thus using the database server prepared
query mecanism.

The problem with this is that, by default, when you get a DB exception, you
only get the SQL and the :VALUE1, :VALUE2 but you don't know what those
values are, and it makes it very hard to test in a SQL console. I came up
with my own Db_Statement_Pdo but I was wondering if there were any built-in
support for what I'm trying to do? I also created a DB exception that can
hold an SQL statement and a list of params. If there's any built-in
functionality in the framework, I'd like to bypass this class, but do I have
any other choice?

Here's the class:

<?php
class MyCompany_Db_Statement_Pdo extends Zend_Db_Statement_Pdo {
private $sql = null;

/**
* Binds a value to a parameter.
*
* @param mixed $parameter Name the parameter, either integer or string.
* @param mixed $value Scalar value to bind to the parameter.
* @param mixed $type OPTIONAL Datatype of the parameter.
* @return bool
* @throws Zend_Db_Statement_Exception
*/
public function bindValue($parameter, $value, $type = null) {
$this->_bindParam[$parameter] = $value;
return parent::bindValue($parameter, $value, $type);
}

/**
* Prepare a string SQL statement and create a statement object.
*
* @param string $sql
* @return void
* @throws Zend_Db_Statement_Exception
*/
protected function _prepare($sql) {
$this->sql = $sql;
return parent::_prepare($sql);
}

/**
* Executes a prepared statement.
*
* @param array $params OPTIONAL Values to bind to parameter
placeholders.
* @return bool
*/
public function execute(array $params = null) {
if (is_array($params)) {
$this->_bindParam = $params;
}
try {
return parent::execute($params);
}
catch (Exception $e) {
$exDb = new MyCompany_Db_Exception($e->getMessage(),
$e->getCode());
$exDb->setArrayBindValues($this->_bindParam);
$exDb->setSqlQuery($this->sql);
throw $exDb;
}
}
}
?>
--
View this message in context: http://www.nabble.com/Adding-SQL-and-bound-parameters-info-to-a-DB-exception--tp25296021p25296021.html
Sent from the Zend DB mailing list archive at Nabble.com.

没有评论: