Db.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  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-2009 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. require_once 'Zend/Queue/Adapter/AdapterAbstract.php';
  26. /**
  27. * @see Zend_Db_Select
  28. */
  29. require_once 'Zend/Db/Select.php';
  30. /**
  31. * @see Zend_Db
  32. */
  33. require_once 'Zend/Db.php';
  34. /**
  35. * @see Zend_Queue_Adapter_Db_Queue
  36. */
  37. require_once 'Zend/Queue/Adapter/Db/Queue.php';
  38. /**
  39. * @see Zend_Queue_Adapter_Db_Message
  40. */
  41. require_once '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-2009 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. * Constructor
  63. *
  64. * @param array|Zend_Config $options
  65. * @param Zend_Queue|null $queue
  66. * @return void
  67. */
  68. public function __construct($options, Zend_Queue $queue = null)
  69. {
  70. parent::__construct($options, $queue);
  71. if (!isset($this->_options['options'][Zend_Db_Select::FOR_UPDATE])) {
  72. // turn off auto update by default
  73. $this->_options['options'][Zend_Db_Select::FOR_UPDATE] = false;
  74. }
  75. if (!is_bool($this->_options['options'][Zend_Db_Select::FOR_UPDATE])) {
  76. require_once 'Zend/Queue/Exception.php';
  77. throw new Zend_Queue_Exception('Options array item: Zend_Db_Select::FOR_UPDATE must be boolean');
  78. }
  79. $options = &$this->_options['driverOptions'];
  80. if (!array_key_exists('type', $options)) {
  81. require_once 'Zend/Queue/Exception.php';
  82. throw new Zend_Queue_Exception("Configuration array must have a key for 'type' for the database type to use");
  83. }
  84. if (!array_key_exists('host', $options)) {
  85. require_once 'Zend/Queue/Exception.php';
  86. throw new Zend_Queue_Exception("Configuration array must have a key for 'host' for the host to use");
  87. }
  88. if (!array_key_exists('username', $options)) {
  89. require_once 'Zend/Queue/Exception.php';
  90. throw new Zend_Queue_Exception("Configuration array must have a key for 'username' for the username to use");
  91. }
  92. if (!array_key_exists('password', $options)) {
  93. require_once 'Zend/Queue/Exception.php';
  94. throw new Zend_Queue_Exception("Configuration array must have a key for 'password' for the password to use");
  95. }
  96. if (!array_key_exists('dbname', $options)) {
  97. require_once 'Zend/Queue/Exception.php';
  98. throw new Zend_Queue_Exception("Configuration array must have a key for 'dbname' for the database to use");
  99. }
  100. $type = $options['type'];
  101. unset($options['type']);
  102. try {
  103. $db = Zend_Db::factory($type, $options);
  104. $this->_queueTable = new Zend_Queue_Adapter_Db_Queue(array(
  105. 'db' => $db,
  106. ));
  107. $this->_messageTable = new Zend_Queue_Adapter_Db_Message(array(
  108. 'db' => $db,
  109. ));
  110. } catch (Zend_Db_Exception $e) {
  111. require_once 'Zend/Queue/Exception.php';
  112. throw new Zend_Queue_Exception('Error connecting to database: ' . $e->getMessage(), $e->getCode());
  113. }
  114. }
  115. /********************************************************************
  116. * Queue management functions
  117. *********************************************************************/
  118. /**
  119. * Does a queue already exist?
  120. *
  121. * Throws an exception if the adapter cannot determine if a queue exists.
  122. * use isSupported('isExists') to determine if an adapter can test for
  123. * queue existance.
  124. *
  125. * @param string $name
  126. * @return boolean
  127. * @throws Zend_Queue_Exception
  128. */
  129. public function isExists($name)
  130. {
  131. return in_array($name, $this->getQueues());
  132. }
  133. /**
  134. * Create a new queue
  135. *
  136. * Visibility timeout is how long a message is left in the queue "invisible"
  137. * to other readers. If the message is acknowleged (deleted) before the
  138. * timeout, then the message is deleted. However, if the timeout expires
  139. * then the message will be made available to other queue readers.
  140. *
  141. * @param string $name queue name
  142. * @param integer $timeout default visibility timeout
  143. * @return boolean
  144. * @throws Zend_Queue_Exception - database error
  145. */
  146. public function create($name, $timeout = null)
  147. {
  148. if ($this->isExists($name)) {
  149. return false;
  150. }
  151. $queue = $this->_queueTable->createRow();
  152. $queue->queue_name = $name;
  153. $queue->timeout = ($timeout === null) ? self::CREATE_TIMEOUT_DEFAULT : (int)$timeout;
  154. try {
  155. if ($queue->save()) {
  156. return true;
  157. }
  158. } catch (Exception $e) {
  159. require_once 'Zend/Queue/Exception.php';
  160. throw new Zend_Queue_Exception($e->getMessage(), $e->getCode());
  161. }
  162. return false;
  163. }
  164. /**
  165. * Delete a queue and all of it's messages
  166. *
  167. * Returns false if the queue is not found, true if the queue exists
  168. *
  169. * @param string $name queue name
  170. * @return boolean
  171. * @throws Zend_Queue_Exception - database error
  172. */
  173. public function delete($name)
  174. {
  175. $id = $this->getQueueId($name); // get primary key
  176. // if the queue does not exist then it must already be deleted.
  177. $list = $this->_queueTable->find($id);
  178. if (count($list) === 0) {
  179. return false;
  180. }
  181. $queue = $list->current();
  182. if ($queue instanceof Zend_Db_Table_Row_Abstract) {
  183. try {
  184. $queue->delete();
  185. } catch (Exception $e) {
  186. require_once 'Zend/Queue/Exception.php';
  187. throw new Zend_Queue_Exception($e->getMessage(), $e->getCode());
  188. }
  189. }
  190. return true;
  191. }
  192. /*
  193. * Get an array of all available queues
  194. *
  195. * Not all adapters support getQueues(), use isSupported('getQueues')
  196. * to determine if the adapter supports this feature.
  197. *
  198. * @return array
  199. * @throws Zend_Queue_Exception - database error
  200. */
  201. public function getQueues()
  202. {
  203. $query = $this->_queueTable->select();
  204. $query->from($this->_queueTable, array('queue_id', 'queue_name'));
  205. $list = array();
  206. foreach ($this->_queueTable->fetchAll($query) as $queue) {
  207. $list[] = $queue->queue_name;
  208. }
  209. return $list;
  210. }
  211. /**
  212. * Return the approximate number of messages in the queue
  213. *
  214. * @param Zend_Queue $queue
  215. * @return integer
  216. * @throws Zend_Queue_Exception
  217. */
  218. public function count(Zend_Queue $queue = null)
  219. {
  220. if ($queue === null) {
  221. $queue = $this->_queue;
  222. }
  223. $info = $this->_messageTable->info();
  224. $db = $this->_messageTable->getAdapter();
  225. $query = $db->select();
  226. $query->from($info['name'], array(new Zend_Db_Expr('COUNT(1)')))
  227. ->where('queue_id=?', $this->getQueueId($queue->getName()));
  228. // return count results
  229. return (int) $db->fetchOne($query);
  230. }
  231. /********************************************************************
  232. * Messsage management functions
  233. *********************************************************************/
  234. /**
  235. * Send a message to the queue
  236. *
  237. * @param string $message Message to send to the active queue
  238. * @param Zend_Queue $queue
  239. * @return Zend_Queue_Message
  240. * @throws Zend_Queue_Exception - database error
  241. */
  242. public function send($message, Zend_Queue $queue = null)
  243. {
  244. if ($queue === null) {
  245. $queue = $this->_queue;
  246. }
  247. if (is_scalar($message)) {
  248. $message = (string) $message;
  249. }
  250. if (is_string($message)) {
  251. $message = trim($message);
  252. }
  253. if (!$this->isExists($queue->getName())) {
  254. require_once 'Zend/Queue/Exception.php';
  255. throw new Zend_Queue_Exception('Queue does not exist:' . $queue->getName());
  256. }
  257. $msg = $this->_messageTable->createRow();
  258. $msg->queue_id = $this->getQueueId($queue->getName());
  259. $msg->created = time();
  260. $msg->body = $message;
  261. $msg->md5 = md5($message);
  262. // $msg->timeout = ??? @TODO
  263. try {
  264. $msg->save();
  265. } catch (Exception $e) {
  266. require_once 'Zend/Queue/Exception.php';
  267. throw new Zend_Queue_Exception($e->getMessage(), $e->getCode());
  268. }
  269. $options = array(
  270. 'queue' => $queue,
  271. 'data' => $msg->toArray(),
  272. );
  273. $classname = $queue->getMessageClass();
  274. if (!class_exists($classname)) {
  275. require_once 'Zend/Loader.php';
  276. Zend_Loader::loadClass($classname);
  277. }
  278. return new $classname($options);
  279. }
  280. /**
  281. * Get messages in the queue
  282. *
  283. * @param integer $maxMessages Maximum number of messages to return
  284. * @param integer $timeout Visibility timeout for these messages
  285. * @param Zend_Queue $queue
  286. * @return Zend_Queue_Message_Iterator
  287. * @throws Zend_Queue_Exception - database error
  288. */
  289. public function receive($maxMessages = null, $timeout = null, Zend_Queue $queue = null)
  290. {
  291. if ($maxMessages === null) {
  292. $maxMessages = 1;
  293. }
  294. if ($timeout === null) {
  295. $timeout = self::RECEIVE_TIMEOUT_DEFAULT;
  296. }
  297. if ($queue === null) {
  298. $queue = $this->_queue;
  299. }
  300. $msgs = array();
  301. $info = $this->_messageTable->info();
  302. $microtime = microtime(true); // cache microtime
  303. $db = $this->_messageTable->getAdapter();
  304. // start transaction handling
  305. try {
  306. if ( $maxMessages > 0 ) { // ZF-7666 LIMIT 0 clause not included.
  307. $db->beginTransaction();
  308. $query = $db->select();
  309. if ($this->_options['options'][Zend_Db_Select::FOR_UPDATE]) {
  310. // turn on forUpdate
  311. $query->forUpdate();
  312. }
  313. $query->from($info['name'], array('*'))
  314. ->where('queue_id=?', $this->getQueueId($queue->getName()))
  315. ->where('handle IS NULL OR timeout+' . (int)$timeout . ' < ' . (int)$microtime)
  316. ->limit($maxMessages);
  317. foreach ($db->fetchAll($query) as $data) {
  318. // setup our changes to the message
  319. $data['handle'] = md5(uniqid(rand(), true));
  320. $update = array(
  321. 'handle' => $data['handle'],
  322. 'timeout' => $microtime,
  323. );
  324. // update the database
  325. $where = array();
  326. $where[] = $db->quoteInto('message_id=?', $data['message_id']);
  327. $where[] = 'handle IS NULL OR timeout+' . (int)$timeout . ' < ' . (int)$microtime;
  328. $count = $db->update($info['name'], $update, $where);
  329. // we check count to make sure no other thread has gotten
  330. // the rows after our select, but before our update.
  331. if ($count > 0) {
  332. $msgs[] = $data;
  333. }
  334. }
  335. $db->commit();
  336. }
  337. } catch (Exception $e) {
  338. $db->rollBack();
  339. require_once 'Zend/Queue/Exception.php';
  340. throw new Zend_Queue_Exception($e->getMessage(), $e->getCode());
  341. }
  342. $options = array(
  343. 'queue' => $queue,
  344. 'data' => $msgs,
  345. 'messageClass' => $queue->getMessageClass(),
  346. );
  347. $classname = $queue->getMessageSetClass();
  348. if (!class_exists($classname)) {
  349. require_once 'Zend/Loader.php';
  350. Zend_Loader::loadClass($classname);
  351. }
  352. return new $classname($options);
  353. }
  354. /**
  355. * Delete a message from the queue
  356. *
  357. * Returns true if the message is deleted, false if the deletion is
  358. * unsuccessful.
  359. *
  360. * @param Zend_Queue_Message $message
  361. * @return boolean
  362. * @throws Zend_Queue_Exception - database error
  363. */
  364. public function deleteMessage(Zend_Queue_Message $message)
  365. {
  366. $db = $this->_messageTable->getAdapter();
  367. $where = $db->quoteInto('handle=?', $message->handle);
  368. if ($this->_messageTable->delete($where)) {
  369. return true;
  370. }
  371. return false;
  372. }
  373. /********************************************************************
  374. * Supporting functions
  375. *********************************************************************/
  376. /**
  377. * Return a list of queue capabilities functions
  378. *
  379. * $array['function name'] = true or false
  380. * true is supported, false is not supported.
  381. *
  382. * @param string $name
  383. * @return array
  384. */
  385. public function getCapabilities()
  386. {
  387. return array(
  388. 'create' => true,
  389. 'delete' => true,
  390. 'send' => true,
  391. 'receive' => true,
  392. 'deleteMessage' => true,
  393. 'getQueues' => true,
  394. 'count' => true,
  395. 'isExists' => true,
  396. );
  397. }
  398. /********************************************************************
  399. * Functions that are not part of the Zend_Queue_Adapter_Abstract
  400. *********************************************************************/
  401. /**
  402. * Get the queue ID
  403. *
  404. * Returns the queue's row identifier.
  405. *
  406. * @param string $name
  407. * @return integer|null
  408. * @throws Zend_Queue_Exception
  409. */
  410. protected function getQueueId($name)
  411. {
  412. $query = $this->_queueTable->select();
  413. $query->from($this->_queueTable, array('queue_id'))
  414. ->where('queue_name=?', $name);
  415. $queue = $this->_queueTable->fetchRow($query);
  416. if ($queue === null) {
  417. require_once 'Zend/Queue/Exception.php';
  418. throw new Zend_Queue_Exception('Queue does not exist: ' . $name);
  419. }
  420. return (int)$queue->queue_id;
  421. }
  422. }