2009年9月4日星期五

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

I am pretty sure this is similar to this requested functionality:

http://framework.zend.com/issues/browse/ZF-1399

Can you add notes to that issue? Like your proof-of-concept below?

I will categorize and prioritize this feature request, it seems like a
good addition.

-ralph

william0275 wrote:
> 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;
> }
> }
> }
> ?>

没有评论: