LuaScriptBuilder.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  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\redis;
  8. use yii\base\InvalidParamException;
  9. use yii\base\NotSupportedException;
  10. use yii\db\Exception;
  11. use yii\db\Expression;
  12. /**
  13. * LuaScriptBuilder builds lua scripts used for retrieving data from redis.
  14. *
  15. * @author Carsten Brandt <mail@cebe.cc>
  16. * @since 2.0
  17. */
  18. class LuaScriptBuilder extends \yii\base\BaseObject
  19. {
  20. /**
  21. * Builds a Lua script for finding a list of records
  22. * @param ActiveQuery $query the query used to build the script
  23. * @return string
  24. */
  25. public function buildAll($query)
  26. {
  27. /* @var $modelClass ActiveRecord */
  28. $modelClass = $query->modelClass;
  29. $key = $this->quoteValue($modelClass::keyPrefix() . ':a:');
  30. return $this->build($query, "n=n+1 pks[n]=redis.call('HGETALL',$key .. pk)", 'pks');
  31. }
  32. /**
  33. * Builds a Lua script for finding one record
  34. * @param ActiveQuery $query the query used to build the script
  35. * @return string
  36. */
  37. public function buildOne($query)
  38. {
  39. /* @var $modelClass ActiveRecord */
  40. $modelClass = $query->modelClass;
  41. $key = $this->quoteValue($modelClass::keyPrefix() . ':a:');
  42. return $this->build($query, "do return redis.call('HGETALL',$key .. pk) end", 'pks');
  43. }
  44. /**
  45. * Builds a Lua script for finding a column
  46. * @param ActiveQuery $query the query used to build the script
  47. * @param string $column name of the column
  48. * @return string
  49. */
  50. public function buildColumn($query, $column)
  51. {
  52. // TODO add support for indexBy
  53. /* @var $modelClass ActiveRecord */
  54. $modelClass = $query->modelClass;
  55. $key = $this->quoteValue($modelClass::keyPrefix() . ':a:');
  56. return $this->build($query, "n=n+1 pks[n]=redis.call('HGET',$key .. pk," . $this->quoteValue($column) . ")", 'pks');
  57. }
  58. /**
  59. * Builds a Lua script for getting count of records
  60. * @param ActiveQuery $query the query used to build the script
  61. * @return string
  62. */
  63. public function buildCount($query)
  64. {
  65. return $this->build($query, 'n=n+1', 'n');
  66. }
  67. /**
  68. * Builds a Lua script for finding the sum of a column
  69. * @param ActiveQuery $query the query used to build the script
  70. * @param string $column name of the column
  71. * @return string
  72. */
  73. public function buildSum($query, $column)
  74. {
  75. /* @var $modelClass ActiveRecord */
  76. $modelClass = $query->modelClass;
  77. $key = $this->quoteValue($modelClass::keyPrefix() . ':a:');
  78. return $this->build($query, "n=n+redis.call('HGET',$key .. pk," . $this->quoteValue($column) . ")", 'n');
  79. }
  80. /**
  81. * Builds a Lua script for finding the average of a column
  82. * @param ActiveQuery $query the query used to build the script
  83. * @param string $column name of the column
  84. * @return string
  85. */
  86. public function buildAverage($query, $column)
  87. {
  88. /* @var $modelClass ActiveRecord */
  89. $modelClass = $query->modelClass;
  90. $key = $this->quoteValue($modelClass::keyPrefix() . ':a:');
  91. return $this->build($query, "n=n+1 if v==nil then v=0 end v=v+redis.call('HGET',$key .. pk," . $this->quoteValue($column) . ")", 'v/n');
  92. }
  93. /**
  94. * Builds a Lua script for finding the min value of a column
  95. * @param ActiveQuery $query the query used to build the script
  96. * @param string $column name of the column
  97. * @return string
  98. */
  99. public function buildMin($query, $column)
  100. {
  101. /* @var $modelClass ActiveRecord */
  102. $modelClass = $query->modelClass;
  103. $key = $this->quoteValue($modelClass::keyPrefix() . ':a:');
  104. return $this->build($query, "n=redis.call('HGET',$key .. pk," . $this->quoteValue($column) . ") if v==nil or n<v then v=n end", 'v');
  105. }
  106. /**
  107. * Builds a Lua script for finding the max value of a column
  108. * @param ActiveQuery $query the query used to build the script
  109. * @param string $column name of the column
  110. * @return string
  111. */
  112. public function buildMax($query, $column)
  113. {
  114. /* @var $modelClass ActiveRecord */
  115. $modelClass = $query->modelClass;
  116. $key = $this->quoteValue($modelClass::keyPrefix() . ':a:');
  117. return $this->build($query, "n=redis.call('HGET',$key .. pk," . $this->quoteValue($column) . ") if v==nil or n>v then v=n end", 'v');
  118. }
  119. /**
  120. * @param ActiveQuery $query the query used to build the script
  121. * @param string $buildResult the lua script for building the result
  122. * @param string $return the lua variable that should be returned
  123. * @throws NotSupportedException when query contains unsupported order by condition
  124. * @return string
  125. */
  126. private function build($query, $buildResult, $return)
  127. {
  128. $columns = [];
  129. if ($query->where !== null) {
  130. $condition = $this->buildCondition($query->where, $columns);
  131. } else {
  132. $condition = 'true';
  133. }
  134. $start = ($query->offset === null || $query->offset < 0) ? 0 : $query->offset;
  135. $limitCondition = 'i>' . $start . (($query->limit === null || $query->limit < 0) ? '' : ' and i<=' . ($start + $query->limit));
  136. /* @var $modelClass ActiveRecord */
  137. $modelClass = $query->modelClass;
  138. $key = $this->quoteValue($modelClass::keyPrefix());
  139. $loadColumnValues = '';
  140. foreach ($columns as $column => $alias) {
  141. $loadColumnValues .= "local $alias=redis.call('HGET',$key .. ':a:' .. pk, " . $this->quoteValue($column) . ")\n";
  142. }
  143. $getAllPks = <<<EOF
  144. local allpks=redis.call('LRANGE',$key,0,-1)
  145. EOF;
  146. if (!empty($query->orderBy)) {
  147. if (!is_array($query->orderBy) || count($query->orderBy) > 1) {
  148. throw new NotSupportedException(
  149. 'orderBy by multiple columns is not currently supported by redis ActiveRecord.'
  150. );
  151. }
  152. $k = key($query->orderBy);
  153. $v = $query->orderBy[$k];
  154. if (is_numeric($k)) {
  155. $orderColumn = $v;
  156. $orderType = 'ASC';
  157. } else {
  158. $orderColumn = $k;
  159. $orderType = $v === SORT_DESC ? 'DESC' : 'ASC';
  160. }
  161. $getAllPks = <<<EOF
  162. local allpks=redis.pcall('SORT', $key, 'BY', $key .. ':a:*->' .. '$orderColumn', '$orderType')
  163. if allpks['err'] then
  164. allpks=redis.pcall('SORT', $key, 'BY', $key .. ':a:*->' .. '$orderColumn', '$orderType', 'ALPHA')
  165. end
  166. EOF;
  167. }
  168. return <<<EOF
  169. $getAllPks
  170. local pks={}
  171. local n=0
  172. local v=nil
  173. local i=0
  174. local key=$key
  175. for k,pk in ipairs(allpks) do
  176. $loadColumnValues
  177. if $condition then
  178. i=i+1
  179. if $limitCondition then
  180. $buildResult
  181. end
  182. end
  183. end
  184. return $return
  185. EOF;
  186. }
  187. /**
  188. * Adds a column to the list of columns to retrieve and creates an alias
  189. * @param string $column the column name to add
  190. * @param array $columns list of columns given by reference
  191. * @return string the alias generated for the column name
  192. */
  193. private function addColumn($column, &$columns)
  194. {
  195. if (isset($columns[$column])) {
  196. return $columns[$column];
  197. }
  198. $name = 'c' . preg_replace("/[^a-z]+/i", "", $column) . count($columns);
  199. return $columns[$column] = $name;
  200. }
  201. /**
  202. * Quotes a string value for use in a query.
  203. * Note that if the parameter is not a string or int, it will be returned without change.
  204. * @param string $str string to be quoted
  205. * @return string the properly quoted string
  206. */
  207. private function quoteValue($str)
  208. {
  209. if (!is_string($str) && !is_int($str)) {
  210. return $str;
  211. }
  212. return "'" . addcslashes($str, "\000\n\r\\\032\047") . "'";
  213. }
  214. /**
  215. * Parses the condition specification and generates the corresponding Lua expression.
  216. * @param string|array $condition the condition specification. Please refer to [[ActiveQuery::where()]]
  217. * on how to specify a condition.
  218. * @param array $columns the list of columns and aliases to be used
  219. * @return string the generated SQL expression
  220. * @throws \yii\db\Exception if the condition is in bad format
  221. * @throws \yii\base\NotSupportedException if the condition is not an array
  222. */
  223. public function buildCondition($condition, &$columns)
  224. {
  225. static $builders = [
  226. 'not' => 'buildNotCondition',
  227. 'and' => 'buildAndCondition',
  228. 'or' => 'buildAndCondition',
  229. 'between' => 'buildBetweenCondition',
  230. 'not between' => 'buildBetweenCondition',
  231. 'in' => 'buildInCondition',
  232. 'not in' => 'buildInCondition',
  233. 'like' => 'buildLikeCondition',
  234. 'not like' => 'buildLikeCondition',
  235. 'or like' => 'buildLikeCondition',
  236. 'or not like' => 'buildLikeCondition',
  237. '>' => 'buildCompareCondition',
  238. '>=' => 'buildCompareCondition',
  239. '<' => 'buildCompareCondition',
  240. '<=' => 'buildCompareCondition',
  241. ];
  242. if (!is_array($condition)) {
  243. throw new NotSupportedException('Where condition must be an array in redis ActiveRecord.');
  244. }
  245. if (isset($condition[0])) { // operator format: operator, operand 1, operand 2, ...
  246. $operator = strtolower($condition[0]);
  247. if (isset($builders[$operator])) {
  248. $method = $builders[$operator];
  249. array_shift($condition);
  250. return $this->$method($operator, $condition, $columns);
  251. }
  252. throw new Exception('Found unknown operator in query: ' . $operator);
  253. }
  254. // hash format: 'column1' => 'value1', 'column2' => 'value2', ...
  255. return $this->buildHashCondition($condition, $columns);
  256. }
  257. private function buildHashCondition($condition, &$columns)
  258. {
  259. $parts = [];
  260. foreach ($condition as $column => $value) {
  261. if (is_array($value)) { // IN condition
  262. $parts[] = $this->buildInCondition('in', [$column, $value], $columns);
  263. } else {
  264. if (is_bool($value)) {
  265. $value = (int) $value;
  266. }
  267. if ($value === null) {
  268. $parts[] = "redis.call('HEXISTS',key .. ':a:' .. pk, ".$this->quoteValue($column).")==0";
  269. } elseif ($value instanceof Expression) {
  270. $column = $this->addColumn($column, $columns);
  271. $parts[] = "$column==" . $value->expression;
  272. } else {
  273. $column = $this->addColumn($column, $columns);
  274. $value = $this->quoteValue($value);
  275. $parts[] = "$column==$value";
  276. }
  277. }
  278. }
  279. return count($parts) === 1 ? $parts[0] : '(' . implode(') and (', $parts) . ')';
  280. }
  281. private function buildNotCondition($operator, $operands, &$params)
  282. {
  283. if (count($operands) != 1) {
  284. throw new InvalidParamException("Operator '$operator' requires exactly one operand.");
  285. }
  286. $operand = reset($operands);
  287. if (is_array($operand)) {
  288. $operand = $this->buildCondition($operand, $params);
  289. }
  290. return "$operator ($operand)";
  291. }
  292. private function buildAndCondition($operator, $operands, &$columns)
  293. {
  294. $parts = [];
  295. foreach ($operands as $operand) {
  296. if (is_array($operand)) {
  297. $operand = $this->buildCondition($operand, $columns);
  298. }
  299. if ($operand !== '') {
  300. $parts[] = $operand;
  301. }
  302. }
  303. if (!empty($parts)) {
  304. return '(' . implode(") $operator (", $parts) . ')';
  305. }
  306. return '';
  307. }
  308. private function buildBetweenCondition($operator, $operands, &$columns)
  309. {
  310. if (!isset($operands[0], $operands[1], $operands[2])) {
  311. throw new Exception("Operator '$operator' requires three operands.");
  312. }
  313. list($column, $value1, $value2) = $operands;
  314. $value1 = $this->quoteValue($value1);
  315. $value2 = $this->quoteValue($value2);
  316. $column = $this->addColumn($column, $columns);
  317. $condition = "$column >= $value1 and $column <= $value2";
  318. return $operator === 'not between' ? "not ($condition)" : $condition;
  319. }
  320. private function buildInCondition($operator, $operands, &$columns)
  321. {
  322. if (!isset($operands[0], $operands[1])) {
  323. throw new Exception("Operator '$operator' requires two operands.");
  324. }
  325. list($column, $values) = $operands;
  326. $values = (array) $values;
  327. if (empty($values) || $column === []) {
  328. return $operator === 'in' ? 'false' : 'true';
  329. }
  330. if (is_array($column) && count($column) > 1) {
  331. return $this->buildCompositeInCondition($operator, $column, $values, $columns);
  332. }
  333. if (is_array($column)) {
  334. $column = reset($column);
  335. }
  336. $columnAlias = $this->addColumn($column, $columns);
  337. $parts = [];
  338. foreach ($values as $value) {
  339. if (is_array($value)) {
  340. $value = isset($value[$column]) ? $value[$column] : null;
  341. }
  342. if ($value === null) {
  343. $parts[] = "redis.call('HEXISTS',key .. ':a:' .. pk, ".$this->quoteValue($column).")==0";
  344. } elseif ($value instanceof Expression) {
  345. $parts[] = "$columnAlias==" . $value->expression;
  346. } else {
  347. $value = $this->quoteValue($value);
  348. $parts[] = "$columnAlias==$value";
  349. }
  350. }
  351. $operator = $operator === 'in' ? '' : 'not ';
  352. return "$operator(" . implode(' or ', $parts) . ')';
  353. }
  354. protected function buildCompositeInCondition($operator, $inColumns, $values, &$columns)
  355. {
  356. $vss = [];
  357. foreach ($values as $value) {
  358. $vs = [];
  359. foreach ($inColumns as $column) {
  360. if (isset($value[$column])) {
  361. $columnAlias = $this->addColumn($column, $columns);
  362. $vs[] = "$columnAlias==" . $this->quoteValue($value[$column]);
  363. } else {
  364. $vs[] = "redis.call('HEXISTS',key .. ':a:' .. pk, ".$this->quoteValue($column).")==0";
  365. }
  366. }
  367. $vss[] = '(' . implode(' and ', $vs) . ')';
  368. }
  369. $operator = $operator === 'in' ? '' : 'not ';
  370. return "$operator(" . implode(' or ', $vss) . ')';
  371. }
  372. protected function buildCompareCondition($operator, $operands, &$columns)
  373. {
  374. if (!isset($operands[0], $operands[1])) {
  375. throw new Exception("Operator '$operator' requires two operands.");
  376. }
  377. list($column, $value) = $operands;
  378. $column = $this->addColumn($column, $columns);
  379. if (is_numeric($value)){
  380. return "tonumber($column) $operator $value";
  381. }
  382. $value = $this->quoteValue($value);
  383. return "$column $operator $value";
  384. }
  385. private function buildLikeCondition($operator, $operands, &$columns)
  386. {
  387. throw new NotSupportedException('LIKE conditions are not suppoerted by redis ActiveRecord.');
  388. }
  389. }