Db.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  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. * @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. require_once 'Zend/Queue/Exception.php';
  81. throw new Zend_Queue_Exception('Options array item: Zend_Db_Select::FOR_UPDATE must be boolean');
  82. }
  83. if ($this->_options['dbAdapter'] !== null
  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. require_once '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. require_once '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. require_once '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. require_once '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. require_once '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. require_once 'Zend/Queue/Exception.php';
  133. throw new Zend_Queue_Exception('Error connecting to database: ' . $e->getMessage(), $e->getCode());
  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. require_once 'Zend/Queue/Exception.php';
  188. throw new Zend_Queue_Exception($e->getMessage(), $e->getCode());
  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. require_once 'Zend/Queue/Exception.php';
  215. throw new Zend_Queue_Exception($e->getMessage(), $e->getCode());
  216. }
  217. }
  218. return true;
  219. }
  220. /*
  221. * Get an array of all available queues
  222. *
  223. * Not all adapters support getQueues(), use isSupported('getQueues')
  224. * to determine if the adapter supports this feature.
  225. *
  226. * @return array
  227. * @throws Zend_Queue_Exception - database error
  228. */
  229. public function getQueues()
  230. {
  231. $query = $this->_queueTable->select();
  232. $query->from($this->_queueTable, array('queue_id', 'queue_name'));
  233. $list = array();
  234. foreach ($this->_queueTable->fetchAll($query) as $queue) {
  235. $list[] = $queue->queue_name;
  236. }
  237. return $list;
  238. }
  239. /**
  240. * Return the approximate number of messages in the queue
  241. *
  242. * @param Zend_Queue $queue
  243. * @return integer
  244. * @throws Zend_Queue_Exception
  245. */
  246. public function count(Zend_Queue $queue = null)
  247. {
  248. if ($queue === null) {
  249. $queue = $this->_queue;
  250. }
  251. $info = $this->_messageTable->info();
  252. $db = $this->_messageTable->getAdapter();
  253. $query = $db->select();
  254. $query->from($info['name'], array(new Zend_Db_Expr('COUNT(1)')))
  255. ->where('queue_id=?', $this->getQueueId($queue->getName()));
  256. // return count results
  257. return (int) $db->fetchOne($query);
  258. }
  259. /********************************************************************
  260. * Messsage management functions
  261. *********************************************************************/
  262. /**
  263. * Send a message to the queue
  264. *
  265. * @param string $message Message to send to the active queue
  266. * @param Zend_Queue $queue
  267. * @return Zend_Queue_Message
  268. * @throws Zend_Queue_Exception - database error
  269. */
  270. public function send($message, Zend_Queue $queue = null)
  271. {
  272. if ($this->_messageRow === null) {
  273. $this->_messageRow = $this->_messageTable->createRow();
  274. }
  275. if ($queue === null) {
  276. $queue = $this->_queue;
  277. }
  278. if (is_scalar($message)) {
  279. $message = (string) $message;
  280. }
  281. if (is_string($message)) {
  282. $message = trim($message);
  283. }
  284. if (!$this->isExists($queue->getName())) {
  285. require_once 'Zend/Queue/Exception.php';
  286. throw new Zend_Queue_Exception('Queue does not exist:' . $queue->getName());
  287. }
  288. $msg = clone $this->_messageRow;
  289. $msg->queue_id = $this->getQueueId($queue->getName());
  290. $msg->created = time();
  291. $msg->body = $message;
  292. $msg->md5 = md5($message);
  293. // $msg->timeout = ??? @TODO
  294. try {
  295. $msg->save();
  296. } catch (Exception $e) {
  297. require_once 'Zend/Queue/Exception.php';
  298. throw new Zend_Queue_Exception($e->getMessage(), $e->getCode());
  299. }
  300. $options = array(
  301. 'queue' => $queue,
  302. 'data' => $msg->toArray(),
  303. );
  304. $classname = $queue->getMessageClass();
  305. if (!class_exists($classname)) {
  306. require_once 'Zend/Loader.php';
  307. Zend_Loader::loadClass($classname);
  308. }
  309. return new $classname($options);
  310. }
  311. /**
  312. * Get messages in the queue
  313. *
  314. * @param integer $maxMessages Maximum number of messages to return
  315. * @param integer $timeout Visibility timeout for these messages
  316. * @param Zend_Queue $queue
  317. * @return Zend_Queue_Message_Iterator
  318. * @throws Zend_Queue_Exception - database error
  319. */
  320. public function receive($maxMessages = null, $timeout = null, Zend_Queue $queue = null)
  321. {
  322. if ($maxMessages === null) {
  323. $maxMessages = 1;
  324. }
  325. if ($timeout === null) {
  326. $timeout = self::RECEIVE_TIMEOUT_DEFAULT;
  327. }
  328. if ($queue === null) {
  329. $queue = $this->_queue;
  330. }
  331. $msgs = array();
  332. $info = $this->_messageTable->info();
  333. $microtime = microtime(true); // cache microtime
  334. $db = $this->_messageTable->getAdapter();
  335. // start transaction handling
  336. try {
  337. if ( $maxMessages > 0 ) { // ZF-7666 LIMIT 0 clause not included.
  338. $db->beginTransaction();
  339. $query = $db->select();
  340. if ($this->_options['options'][Zend_Db_Select::FOR_UPDATE]) {
  341. // turn on forUpdate
  342. $query->forUpdate();
  343. }
  344. $query->from($info['name'], array('*'))
  345. ->where('queue_id=?', $this->getQueueId($queue->getName()))
  346. ->where('handle IS NULL OR timeout+' . (int)$timeout . ' < ' . (int)$microtime)
  347. ->limit($maxMessages);
  348. foreach ($db->fetchAll($query) as $data) {
  349. // setup our changes to the message
  350. $data['handle'] = md5(uniqid(rand(), true));
  351. $update = array(
  352. 'handle' => $data['handle'],
  353. 'timeout' => $microtime,
  354. );
  355. // update the database
  356. $where = array();
  357. $where[] = $db->quoteInto('message_id=?', $data['message_id']);
  358. $where[] = 'handle IS NULL OR timeout+' . (int)$timeout . ' < ' . (int)$microtime;
  359. $count = $db->update($info['name'], $update, $where);
  360. // we check count to make sure no other thread has gotten
  361. // the rows after our select, but before our update.
  362. if ($count > 0) {
  363. $msgs[] = $data;
  364. }
  365. }
  366. $db->commit();
  367. }
  368. } catch (Exception $e) {
  369. $db->rollBack();
  370. require_once 'Zend/Queue/Exception.php';
  371. throw new Zend_Queue_Exception($e->getMessage(), $e->getCode());
  372. }
  373. $options = array(
  374. 'queue' => $queue,
  375. 'data' => $msgs,
  376. 'messageClass' => $queue->getMessageClass(),
  377. );
  378. $classname = $queue->getMessageSetClass();
  379. if (!class_exists($classname)) {
  380. require_once 'Zend/Loader.php';
  381. Zend_Loader::loadClass($classname);
  382. }
  383. return new $classname($options);
  384. }
  385. /**
  386. * Delete a message from the queue
  387. *
  388. * Returns true if the message is deleted, false if the deletion is
  389. * unsuccessful.
  390. *
  391. * @param Zend_Queue_Message $message
  392. * @return boolean
  393. * @throws Zend_Queue_Exception - database error
  394. */
  395. public function deleteMessage(Zend_Queue_Message $message)
  396. {
  397. $db = $this->_messageTable->getAdapter();
  398. $where = $db->quoteInto('handle=?', $message->handle);
  399. if ($this->_messageTable->delete($where)) {
  400. return true;
  401. }
  402. return false;
  403. }
  404. /********************************************************************
  405. * Supporting functions
  406. *********************************************************************/
  407. /**
  408. * Return a list of queue capabilities functions
  409. *
  410. * $array['function name'] = true or false
  411. * true is supported, false is not supported.
  412. *
  413. * @param string $name
  414. * @return array
  415. */
  416. public function getCapabilities()
  417. {
  418. return array(
  419. 'create' => true,
  420. 'delete' => true,
  421. 'send' => true,
  422. 'receive' => true,
  423. 'deleteMessage' => true,
  424. 'getQueues' => true,
  425. 'count' => true,
  426. 'isExists' => true,
  427. );
  428. }
  429. /********************************************************************
  430. * Functions that are not part of the Zend_Queue_Adapter_Abstract
  431. *********************************************************************/
  432. /**
  433. * Get the queue ID
  434. *
  435. * Returns the queue's row identifier.
  436. *
  437. * @param string $name
  438. * @return integer|null
  439. * @throws Zend_Queue_Exception
  440. */
  441. protected function getQueueId($name)
  442. {
  443. if (array_key_exists($name, $this->_queues)) {
  444. return $this->_queues[$name];
  445. }
  446. $query = $this->_queueTable->select();
  447. $query->from($this->_queueTable, array('queue_id'))
  448. ->where('queue_name=?', $name);
  449. $queue = $this->_queueTable->fetchRow($query);
  450. if ($queue === null) {
  451. require_once 'Zend/Queue/Exception.php';
  452. throw new Zend_Queue_Exception('Queue does not exist: ' . $name);
  453. }
  454. $this->_queues[$name] = (int)$queue->queue_id;
  455. return $this->_queues[$name];
  456. }
  457. }