LuaScriptBuilder.php 14 KB

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