PageRenderTime 47ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 0ms

/library/Zend/Queue/Adapter/Db.php

http://github.com/centurion-project/Centurion
PHP | 536 lines | 257 code | 75 blank | 204 comment | 42 complexity | d759bdac92d4176ba9c80f78aef851b8 MD5 | raw file
Possible License(s): BSD-3-Clause
  1. <?php
  2. /**
  3. * Zend Framework
  4. *
  5. * LICENSE
  6. *
  7. * This source file is subject to the new BSD license that is bundled
  8. * with this package in the file LICENSE.txt.
  9. * It is also available through the world-wide-web at this URL:
  10. * http://framework.zend.com/license/new-bsd
  11. * If you did not receive a copy of the license and are unable to
  12. * obtain it through the world-wide-web, please send an email
  13. * to license@zend.com so we can send you a copy immediately.
  14. *
  15. * @category Zend
  16. * @package Zend_Queue
  17. * @subpackage Adapter
  18. * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
  19. * @license http://framework.zend.com/license/new-bsd New BSD License
  20. * @version $Id$
  21. */
  22. /**
  23. * @see Zend_Queue_Adapter_AdapterAbstract
  24. */
  25. //$1 'Zend/Queue/Adapter/AdapterAbstract.php';
  26. /**
  27. * @see Zend_Db_Select
  28. */
  29. //$1 'Zend/Db/Select.php';
  30. /**
  31. * @see Zend_Db
  32. */
  33. //$1 'Zend/Db.php';
  34. /**
  35. * @see Zend_Queue_Adapter_Db_Queue
  36. */
  37. //$1 'Zend/Queue/Adapter/Db/Queue.php';
  38. /**
  39. * @see Zend_Queue_Adapter_Db_Message
  40. */
  41. //$1 'Zend/Queue/Adapter/Db/Message.php';
  42. /**
  43. * Class for using connecting to a Zend_Db-based queuing system
  44. *
  45. * @category Zend
  46. * @package Zend_Queue
  47. * @subpackage Adapter
  48. * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
  49. * @license http://framework.zend.com/license/new-bsd New BSD License
  50. */
  51. class Zend_Queue_Adapter_Db extends Zend_Queue_Adapter_AdapterAbstract
  52. {
  53. /**
  54. * @var Zend_Queue_Adapter_Db_Queue
  55. */
  56. protected $_queueTable = null;
  57. /**
  58. * @var Zend_Queue_Adapter_Db_Message
  59. */
  60. protected $_messageTable = null;
  61. /**
  62. * @var Zend_Db_Table_Row_Abstract
  63. */
  64. protected $_messageRow = null;
  65. /**
  66. * Constructor
  67. *
  68. * @param array|Zend_Config $options
  69. * @param Zend_Queue|null $queue
  70. * @return void
  71. */
  72. public function __construct($options, Zend_Queue $queue = null)
  73. {
  74. parent::__construct($options, $queue);
  75. if (!isset($this->_options['options'][Zend_Db_Select::FOR_UPDATE])) {
  76. // turn off auto update by default
  77. $this->_options['options'][Zend_Db_Select::FOR_UPDATE] = false;
  78. }
  79. if (!is_bool($this->_options['options'][Zend_Db_Select::FOR_UPDATE])) {
  80. //$1 'Zend/Queue/Exception.php';
  81. throw new Zend_Queue_Exception('Options array item: Zend_Db_Select::FOR_UPDATE must be boolean');
  82. }
  83. if (isset($this->_options['dbAdapter'])
  84. && $this->_options['dbAdapter'] instanceof Zend_Db_Adapter_Abstract) {
  85. $db = $this->_options['dbAdapter'];
  86. } else {
  87. $db = $this->_initDbAdapter();
  88. }
  89. $this->_queueTable = new Zend_Queue_Adapter_Db_Queue(array(
  90. 'db' => $db,
  91. ));
  92. $this->_messageTable = new Zend_Queue_Adapter_Db_Message(array(
  93. 'db' => $db,
  94. ));
  95. }
  96. /**
  97. * Initialize Db adapter using 'driverOptions' section of the _options array
  98. *
  99. * Throws an exception if the adapter cannot connect to DB.
  100. *
  101. * @return Zend_Db_Adapter_Abstract
  102. * @throws Zend_Queue_Exception
  103. */
  104. protected function _initDbAdapter()
  105. {
  106. $options = &$this->_options['driverOptions'];
  107. if (!array_key_exists('type', $options)) {
  108. //$1 'Zend/Queue/Exception.php';
  109. throw new Zend_Queue_Exception("Configuration array must have a key for 'type' for the database type to use");
  110. }
  111. if (!array_key_exists('host', $options)) {
  112. //$1 'Zend/Queue/Exception.php';
  113. throw new Zend_Queue_Exception("Configuration array must have a key for 'host' for the host to use");
  114. }
  115. if (!array_key_exists('username', $options)) {
  116. //$1 'Zend/Queue/Exception.php';
  117. throw new Zend_Queue_Exception("Configuration array must have a key for 'username' for the username to use");
  118. }
  119. if (!array_key_exists('password', $options)) {
  120. //$1 'Zend/Queue/Exception.php';
  121. throw new Zend_Queue_Exception("Configuration array must have a key for 'password' for the password to use");
  122. }
  123. if (!array_key_exists('dbname', $options)) {
  124. //$1 'Zend/Queue/Exception.php';
  125. throw new Zend_Queue_Exception("Configuration array must have a key for 'dbname' for the database to use");
  126. }
  127. $type = $options['type'];
  128. unset($options['type']);
  129. try {
  130. $db = Zend_Db::factory($type, $options);
  131. } catch (Zend_Db_Exception $e) {
  132. //$1 'Zend/Queue/Exception.php';
  133. throw new Zend_Queue_Exception('Error connecting to database: ' . $e->getMessage(), $e->getCode(), $e);
  134. }
  135. return $db;
  136. }
  137. /********************************************************************
  138. * Queue management functions
  139. *********************************************************************/
  140. /**
  141. * Does a queue already exist?
  142. *
  143. * Throws an exception if the adapter cannot determine if a queue exists.
  144. * use isSupported('isExists') to determine if an adapter can test for
  145. * queue existance.
  146. *
  147. * @param string $name
  148. * @return boolean
  149. * @throws Zend_Queue_Exception
  150. */
  151. public function isExists($name)
  152. {
  153. $id = 0;
  154. try {
  155. $id = $this->getQueueId($name);
  156. } catch (Zend_Queue_Exception $e) {
  157. return false;
  158. }
  159. return ($id > 0);
  160. }
  161. /**
  162. * Create a new queue
  163. *
  164. * Visibility timeout is how long a message is left in the queue "invisible"
  165. * to other readers. If the message is acknowleged (deleted) before the
  166. * timeout, then the message is deleted. However, if the timeout expires
  167. * then the message will be made available to other queue readers.
  168. *
  169. * @param string $name queue name
  170. * @param integer $timeout default visibility timeout
  171. * @return boolean
  172. * @throws Zend_Queue_Exception - database error
  173. */
  174. public function create($name, $timeout = null)
  175. {
  176. if ($this->isExists($name)) {
  177. return false;
  178. }
  179. $queue = $this->_queueTable->createRow();
  180. $queue->queue_name = $name;
  181. $queue->timeout = ($timeout === null) ? self::CREATE_TIMEOUT_DEFAULT : (int)$timeout;
  182. try {
  183. if ($queue->save()) {
  184. return true;
  185. }
  186. } catch (Exception $e) {
  187. //$1 'Zend/Queue/Exception.php';
  188. throw new Zend_Queue_Exception($e->getMessage(), $e->getCode(), $e);
  189. }
  190. return false;
  191. }
  192. /**
  193. * Delete a queue and all of it's messages
  194. *
  195. * Returns false if the queue is not found, true if the queue exists
  196. *
  197. * @param string $name queue name
  198. * @return boolean
  199. * @throws Zend_Queue_Exception - database error
  200. */
  201. public function delete($name)
  202. {
  203. $id = $this->getQueueId($name); // get primary key
  204. // if the queue does not exist then it must already be deleted.
  205. $list = $this->_queueTable->find($id);
  206. if (count($list) === 0) {
  207. return false;
  208. }
  209. $queue = $list->current();
  210. if ($queue instanceof Zend_Db_Table_Row_Abstract) {
  211. try {
  212. $queue->delete();
  213. } catch (Exception $e) {
  214. //$1 'Zend/Queue/Exception.php';
  215. throw new Zend_Queue_Exception($e->getMessage(), $e->getCode(), $e);
  216. }
  217. }
  218. if (array_key_exists($name, $this->_queues)) {
  219. unset($this->_queues[$name]);
  220. }
  221. return true;
  222. }
  223. /*
  224. * Get an array of all available queues
  225. *
  226. * Not all adapters support getQueues(), use isSupported('getQueues')
  227. * to determine if the adapter supports this feature.
  228. *
  229. * @return array
  230. * @throws Zend_Queue_Exception - database error
  231. */
  232. public function getQueues()
  233. {
  234. $query = $this->_queueTable->select();
  235. $query->from($this->_queueTable, array('queue_id', 'queue_name'));
  236. $this->_queues = array();
  237. foreach ($this->_queueTable->fetchAll($query) as $queue) {
  238. $this->_queues[$queue->queue_name] = (int)$queue->queue_id;
  239. }
  240. $list = array_keys($this->_queues);
  241. return $list;
  242. }
  243. /**
  244. * Return the approximate number of messages in the queue
  245. *
  246. * @param Zend_Queue $queue
  247. * @return integer
  248. * @throws Zend_Queue_Exception
  249. */
  250. public function count(Zend_Queue $queue = null)
  251. {
  252. if ($queue === null) {
  253. $queue = $this->_queue;
  254. }
  255. $info = $this->_messageTable->info();
  256. $db = $this->_messageTable->getAdapter();
  257. $query = $db->select();
  258. $query->from($info['name'], array(new Zend_Db_Expr('COUNT(1)')))
  259. ->where('queue_id=?', $this->getQueueId($queue->getName()));
  260. // return count results
  261. return (int) $db->fetchOne($query);
  262. }
  263. /********************************************************************
  264. * Messsage management functions
  265. *********************************************************************/
  266. /**
  267. * Send a message to the queue
  268. *
  269. * @param string $message Message to send to the active queue
  270. * @param Zend_Queue $queue
  271. * @return Zend_Queue_Message
  272. * @throws Zend_Queue_Exception - database error
  273. */
  274. public function send($message, Zend_Queue $queue = null)
  275. {
  276. if ($this->_messageRow === null) {
  277. $this->_messageRow = $this->_messageTable->createRow();
  278. }
  279. if ($queue === null) {
  280. $queue = $this->_queue;
  281. }
  282. if (is_scalar($message)) {
  283. $message = (string) $message;
  284. }
  285. if (is_string($message)) {
  286. $message = trim($message);
  287. }
  288. if (!$this->isExists($queue->getName())) {
  289. //$1 'Zend/Queue/Exception.php';
  290. throw new Zend_Queue_Exception('Queue does not exist:' . $queue->getName());
  291. }
  292. $msg = clone $this->_messageRow;
  293. $msg->queue_id = $this->getQueueId($queue->getName());
  294. $msg->created = time();
  295. $msg->body = $message;
  296. $msg->md5 = md5($message);
  297. // $msg->timeout = ??? @TODO
  298. try {
  299. $msg->save();
  300. } catch (Exception $e) {
  301. //$1 'Zend/Queue/Exception.php';
  302. throw new Zend_Queue_Exception($e->getMessage(), $e->getCode(), $e);
  303. }
  304. $options = array(
  305. 'queue' => $queue,
  306. 'data' => $msg->toArray(),
  307. );
  308. $classname = $queue->getMessageClass();
  309. if (!class_exists($classname)) {
  310. //$1 'Zend/Loader.php';
  311. Zend_Loader::loadClass($classname);
  312. }
  313. return new $classname($options);
  314. }
  315. /**
  316. * Get messages in the queue
  317. *
  318. * @param integer $maxMessages Maximum number of messages to return
  319. * @param integer $timeout Visibility timeout for these messages
  320. * @param Zend_Queue $queue
  321. * @return Zend_Queue_Message_Iterator
  322. * @throws Zend_Queue_Exception - database error
  323. */
  324. public function receive($maxMessages = null, $timeout = null, Zend_Queue $queue = null)
  325. {
  326. if ($maxMessages === null) {
  327. $maxMessages = 1;
  328. }
  329. if ($timeout === null) {
  330. $timeout = self::RECEIVE_TIMEOUT_DEFAULT;
  331. }
  332. if ($queue === null) {
  333. $queue = $this->_queue;
  334. }
  335. $msgs = array();
  336. $info = $this->_messageTable->info();
  337. $microtime = microtime(true); // cache microtime
  338. $db = $this->_messageTable->getAdapter();
  339. // start transaction handling
  340. try {
  341. if ( $maxMessages > 0 ) { // ZF-7666 LIMIT 0 clause not included.
  342. $db->beginTransaction();
  343. $query = $db->select();
  344. if ($this->_options['options'][Zend_Db_Select::FOR_UPDATE]) {
  345. // turn on forUpdate
  346. $query->forUpdate();
  347. }
  348. $query->from($info['name'], array('*'))
  349. ->where('queue_id=?', $this->getQueueId($queue->getName()))
  350. ->where('handle IS NULL OR timeout+' . (int)$timeout . ' < ' . (int)$microtime)
  351. ->limit($maxMessages);
  352. foreach ($db->fetchAll($query) as $data) {
  353. // setup our changes to the message
  354. $data['handle'] = md5(uniqid(rand(), true));
  355. $update = array(
  356. 'handle' => $data['handle'],
  357. 'timeout' => $microtime,
  358. );
  359. // update the database
  360. $where = array();
  361. $where[] = $db->quoteInto('message_id=?', $data['message_id']);
  362. $where[] = 'handle IS NULL OR timeout+' . (int)$timeout . ' < ' . (int)$microtime;
  363. $count = $db->update($info['name'], $update, $where);
  364. // we check count to make sure no other thread has gotten
  365. // the rows after our select, but before our update.
  366. if ($count > 0) {
  367. $msgs[] = $data;
  368. }
  369. }
  370. $db->commit();
  371. }
  372. } catch (Exception $e) {
  373. $db->rollBack();
  374. //$1 'Zend/Queue/Exception.php';
  375. throw new Zend_Queue_Exception($e->getMessage(), $e->getCode(), $e);
  376. }
  377. $options = array(
  378. 'queue' => $queue,
  379. 'data' => $msgs,
  380. 'messageClass' => $queue->getMessageClass(),
  381. );
  382. $classname = $queue->getMessageSetClass();
  383. if (!class_exists($classname)) {
  384. //$1 'Zend/Loader.php';
  385. Zend_Loader::loadClass($classname);
  386. }
  387. return new $classname($options);
  388. }
  389. /**
  390. * Delete a message from the queue
  391. *
  392. * Returns true if the message is deleted, false if the deletion is
  393. * unsuccessful.
  394. *
  395. * @param Zend_Queue_Message $message
  396. * @return boolean
  397. * @throws Zend_Queue_Exception - database error
  398. */
  399. public function deleteMessage(Zend_Queue_Message $message)
  400. {
  401. $db = $this->_messageTable->getAdapter();
  402. $where = $db->quoteInto('handle=?', $message->handle);
  403. if ($this->_messageTable->delete($where)) {
  404. return true;
  405. }
  406. return false;
  407. }
  408. /********************************************************************
  409. * Supporting functions
  410. *********************************************************************/
  411. /**
  412. * Return a list of queue capabilities functions
  413. *
  414. * $array['function name'] = true or false
  415. * true is supported, false is not supported.
  416. *
  417. * @param string $name
  418. * @return array
  419. */
  420. public function getCapabilities()
  421. {
  422. return array(
  423. 'create' => true,
  424. 'delete' => true,
  425. 'send' => true,
  426. 'receive' => true,
  427. 'deleteMessage' => true,
  428. 'getQueues' => true,
  429. 'count' => true,
  430. 'isExists' => true,
  431. );
  432. }
  433. /********************************************************************
  434. * Functions that are not part of the Zend_Queue_Adapter_Abstract
  435. *********************************************************************/
  436. /**
  437. * Get the queue ID
  438. *
  439. * Returns the queue's row identifier.
  440. *
  441. * @param string $name
  442. * @return integer|null
  443. * @throws Zend_Queue_Exception
  444. */
  445. protected function getQueueId($name)
  446. {
  447. if (array_key_exists($name, $this->_queues)) {
  448. return $this->_queues[$name];
  449. }
  450. $query = $this->_queueTable->select();
  451. $query->from($this->_queueTable, array('queue_id'))
  452. ->where('queue_name=?', $name);
  453. $queue = $this->_queueTable->fetchRow($query);
  454. if ($queue === null) {
  455. //$1 'Zend/Queue/Exception.php';
  456. throw new Zend_Queue_Exception('Queue does not exist: ' . $name);
  457. }
  458. $this->_queues[$name] = (int)$queue->queue_id;
  459. return $this->_queues[$name];
  460. }
  461. }