Db.php 15 KB

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