You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\caching;
  8. use Yii;
  9. use yii\base\InvalidConfigException;
  10. use yii\db\Connection;
  11. use yii\di\Instance;
  12. /**
  13. * DbDependency represents a dependency based on the query result of a SQL statement.
  14. *
  15. * If the query result changes, the dependency is considered as changed.
  16. * The query is specified via the [[sql]] property.
  17. *
  18. * @author Qiang Xue <qiang.xue@gmail.com>
  19. * @since 2.0
  20. */
  21. class DbDependency extends Dependency
  22. {
  23. /**
  24. * @var string the application component ID of the DB connection.
  25. */
  26. public $db = 'db';
  27. /**
  28. * @var string the SQL query whose result is used to determine if the dependency has been changed.
  29. * Only the first row of the query result will be used.
  30. */
  31. public $sql;
  32. /**
  33. * @var array the parameters (name => value) to be bound to the SQL statement specified by [[sql]].
  34. */
  35. public $params = [];
  36. /**
  37. * Generates the data needed to determine if dependency has been changed.
  38. * This method returns the value of the global state.
  39. * @param Cache $cache the cache component that is currently evaluating this dependency
  40. * @return mixed the data needed to determine if dependency has been changed.
  41. * @throws InvalidConfigException if [[db]] is not a valid application component ID
  42. */
  43. protected function generateDependencyData($cache)
  44. {
  45. $db = Instance::ensure($this->db, Connection::className());
  46. if ($this->sql === null) {
  47. throw new InvalidConfigException('DbDependency::sql must be set.');
  48. }
  49. if ($db->enableQueryCache) {
  50. // temporarily disable and re-enable query caching
  51. $db->enableQueryCache = false;
  52. $result = $db->createCommand($this->sql, $this->params)->queryOne();
  53. $db->enableQueryCache = true;
  54. } else {
  55. $result = $db->createCommand($this->sql, $this->params)->queryOne();
  56. }
  57. return $result;
  58. }
  59. }