LuaScriptBuilder.php 11.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace yii\redis;

use yii\base\NotSupportedException;
Carsten Brandt committed
11 12
use yii\db\Exception;
use yii\db\Expression;
13 14 15 16 17 18 19 20 21

/**
 * LuaScriptBuilder builds lua scripts used for retrieving data from redis.
 *
 * @author Carsten Brandt <mail@cebe.cc>
 * @since 2.0
 */
class LuaScriptBuilder extends \yii\base\Object
{
Carsten Brandt committed
22 23 24 25 26
	/**
	 * Builds a Lua script for finding a list of records
	 * @param ActiveQuery $query the query used to build the script
	 * @return string
	 */
27 28
	public function buildAll($query)
	{
29
		// TODO add support for orderBy
Carsten Brandt committed
30
		/** @var ActiveRecord $modelClass */
31
		$modelClass = $query->modelClass;
32
		$key = $this->quoteValue($modelClass::keyPrefix() . ':a:');
33
		return $this->build($query, "n=n+1 pks[n]=redis.call('HGETALL',$key .. pk)", 'pks');
34 35
	}

Carsten Brandt committed
36 37 38 39 40
	/**
	 * Builds a Lua script for finding one record
	 * @param ActiveQuery $query the query used to build the script
	 * @return string
	 */
41 42
	public function buildOne($query)
	{
43
		// TODO add support for orderBy
Carsten Brandt committed
44
		/** @var ActiveRecord $modelClass */
45
		$modelClass = $query->modelClass;
46
		$key = $this->quoteValue($modelClass::keyPrefix() . ':a:');
47
		return $this->build($query, "do return redis.call('HGETALL',$key .. pk) end", 'pks');
48 49
	}

Carsten Brandt committed
50 51 52 53 54 55 56
	/**
	 * Builds a Lua script for finding a column
	 * @param ActiveQuery $query the query used to build the script
	 * @param string $column name of the column
	 * @return string
	 */
	public function buildColumn($query, $column)
57 58
	{
		// TODO add support for orderBy and indexBy
Carsten Brandt committed
59
		/** @var ActiveRecord $modelClass */
60
		$modelClass = $query->modelClass;
61
		$key = $this->quoteValue($modelClass::keyPrefix() . ':a:');
62
		return $this->build($query, "n=n+1 pks[n]=redis.call('HGET',$key .. pk," . $this->quoteValue($column) . ")", 'pks');
63 64
	}

Carsten Brandt committed
65 66 67 68 69
	/**
	 * Builds a Lua script for getting count of records
	 * @param ActiveQuery $query the query used to build the script
	 * @return string
	 */
70 71 72 73 74
	public function buildCount($query)
	{
		return $this->build($query, 'n=n+1', 'n');
	}

Carsten Brandt committed
75 76 77 78 79 80 81
	/**
	 * Builds a Lua script for finding the sum of a column
	 * @param ActiveQuery $query the query used to build the script
	 * @param string $column name of the column
	 * @return string
	 */
	public function buildSum($query, $column)
82
	{
Carsten Brandt committed
83
		/** @var ActiveRecord $modelClass */
84
		$modelClass = $query->modelClass;
85
		$key = $this->quoteValue($modelClass::keyPrefix() . ':a:');
86
		return $this->build($query, "n=n+redis.call('HGET',$key .. pk," . $this->quoteValue($column) . ")", 'n');
87 88
	}

Carsten Brandt committed
89 90 91 92 93 94 95
	/**
	 * Builds a Lua script for finding the average of a column
	 * @param ActiveQuery $query the query used to build the script
	 * @param string $column name of the column
	 * @return string
	 */
	public function buildAverage($query, $column)
96
	{
Carsten Brandt committed
97
		/** @var ActiveRecord $modelClass */
98
		$modelClass = $query->modelClass;
99
		$key = $this->quoteValue($modelClass::keyPrefix() . ':a:');
100
		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');
101 102
	}

Carsten Brandt committed
103 104 105 106 107 108 109
	/**
	 * Builds a Lua script for finding the min value of a column
	 * @param ActiveQuery $query the query used to build the script
	 * @param string $column name of the column
	 * @return string
	 */
	public function buildMin($query, $column)
110
	{
Carsten Brandt committed
111
		/** @var ActiveRecord $modelClass */
112
		$modelClass = $query->modelClass;
113
		$key = $this->quoteValue($modelClass::keyPrefix() . ':a:');
114
		return $this->build($query, "n=redis.call('HGET',$key .. pk," . $this->quoteValue($column) . ") if v==nil or n<v then v=n end", 'v');
115 116
	}

Carsten Brandt committed
117 118 119 120 121 122 123
	/**
	 * Builds a Lua script for finding the max value of a column
	 * @param ActiveQuery $query the query used to build the script
	 * @param string $column name of the column
	 * @return string
	 */
	public function buildMax($query, $column)
124
	{
Carsten Brandt committed
125
		/** @var ActiveRecord $modelClass */
126
		$modelClass = $query->modelClass;
127
		$key = $this->quoteValue($modelClass::keyPrefix() . ':a:');
128
		return $this->build($query, "n=redis.call('HGET',$key .. pk," . $this->quoteValue($column) . ") if v==nil or n>v then v=n end", 'v');
129 130
	}

131
	/**
Carsten Brandt committed
132 133 134 135
	 * @param ActiveQuery $query the query used to build the script
	 * @param string $buildResult the lua script for building the result
	 * @param string $return the lua variable that should be returned
	 * @return string
136
	 */
Carsten Brandt committed
137
	private function build($query, $buildResult, $return)
138
	{
139 140 141 142
		if (!empty($query->orderBy)) {
			throw new NotSupportedException('orderBy is currently not supported by redis ActiveRecord.');
		}

143
		$columns = [];
144 145 146 147 148 149 150 151 152
		if ($query->where !== null) {
			$condition = $this->buildCondition($query->where, $columns);
		} else {
			$condition = 'true';
		}

		$start = $query->offset === null ? 0 : $query->offset;
		$limitCondition = 'i>' . $start . ($query->limit === null ? '' : ' and i<=' . ($start + $query->limit));

153
		/** @var ActiveRecord $modelClass */
154
		$modelClass = $query->modelClass;
155
		$key = $this->quoteValue($modelClass::keyPrefix());
156
		$loadColumnValues = '';
Carsten Brandt committed
157
		foreach($columns as $column => $alias) {
158
			$loadColumnValues .= "local $alias=redis.call('HGET',$key .. ':a:' .. pk, '$column')\n";
159 160 161
		}

		return <<<EOF
162
local allpks=redis.call('LRANGE',$key,0,-1)
163 164
local pks={}
local n=0
165
local v=nil
166 167 168 169 170 171 172 173 174 175 176 177 178 179
local i=0
for k,pk in ipairs(allpks) do
    $loadColumnValues
    if $condition then
      i=i+1
      if $limitCondition then
        $buildResult
      end
    end
end
return $return
EOF;
	}

Carsten Brandt committed
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
	/**
	 * Adds a column to the list of columns to retrieve and creates an alias
	 * @param string $column the column name to add
	 * @param array $columns list of columns given by reference
	 * @return string the alias generated for the column name
	 */
	private function addColumn($column, &$columns)
	{
		if (isset($columns[$column])) {
			return $columns[$column];
		}
		$name = 'c' . preg_replace("/[^A-z]+/", "", $column) . count($columns);
		return $columns[$column] = $name;
	}

195 196
	/**
	 * Quotes a string value for use in a query.
Carsten Brandt committed
197
	 * Note that if the parameter is not a string or int, it will be returned without change.
198 199 200
	 * @param string $str string to be quoted
	 * @return string the properly quoted string
	 */
Carsten Brandt committed
201
	private function quoteValue($str)
202 203 204 205 206 207 208 209 210
	{
		if (!is_string($str) && !is_int($str)) {
			return $str;
		}

		return "'" . addcslashes(str_replace("'", "\\'", $str), "\000\n\r\\\032") . "'";
	}

	/**
Carsten Brandt committed
211 212
	 * Parses the condition specification and generates the corresponding Lua expression.
	 * @param string|array $condition the condition specification. Please refer to [[ActiveQuery::where()]]
213
	 * on how to specify a condition.
Carsten Brandt committed
214
	 * @param array $columns the list of columns and aliases to be used
215 216
	 * @return string the generated SQL expression
	 * @throws \yii\db\Exception if the condition is in bad format
Carsten Brandt committed
217
	 * @throws \yii\base\NotSupportedException if the condition is not an array
218 219 220
	 */
	public function buildCondition($condition, &$columns)
	{
221
		static $builders = [
222
			'not' => 'buildNotCondition',
223 224 225 226 227 228 229 230 231 232
			'and' => 'buildAndCondition',
			'or' => 'buildAndCondition',
			'between' => 'buildBetweenCondition',
			'not between' => 'buildBetweenCondition',
			'in' => 'buildInCondition',
			'not in' => 'buildInCondition',
			'like' => 'buildLikeCondition',
			'not like' => 'buildLikeCondition',
			'or like' => 'buildLikeCondition',
			'or not like' => 'buildLikeCondition',
233
		];
234 235

		if (!is_array($condition)) {
Carsten Brandt committed
236
			throw new NotSupportedException('Where condition must be an array in redis ActiveRecord.');
237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253
		}
		if (isset($condition[0])) { // operator format: operator, operand 1, operand 2, ...
			$operator = strtolower($condition[0]);
			if (isset($builders[$operator])) {
				$method = $builders[$operator];
				array_shift($condition);
				return $this->$method($operator, $condition, $columns);
			} else {
				throw new Exception('Found unknown operator in query: ' . $operator);
			}
		} else { // hash format: 'column1' => 'value1', 'column2' => 'value2', ...
			return $this->buildHashCondition($condition, $columns);
		}
	}

	private function buildHashCondition($condition, &$columns)
	{
254
		$parts = [];
255 256
		foreach ($condition as $column => $value) {
			if (is_array($value)) { // IN condition
257
				$parts[] = $this->buildInCondition('in', [$column, $value], $columns);
258
			} else {
Carsten Brandt committed
259
				$column = $this->addColumn($column, $columns);
260
				if ($value === null) {
Carsten Brandt committed
261
					$parts[] = "$column==nil";
262 263 264 265 266 267 268 269 270 271 272
				} elseif ($value instanceof Expression) {
					$parts[] = "$column==" . $value->expression;
				} else {
					$value = $this->quoteValue($value);
					$parts[] = "$column==$value";
				}
			}
		}
		return count($parts) === 1 ? $parts[0] : '(' . implode(') and (', $parts) . ')';
	}

273 274 275 276 277 278 279 280 281 282 283 284 285
	private function buildNotCondition($operator, $operands, &$params)
	{
		if (count($operands) != 1) {
			throw new InvalidParamException("Operator '$operator' requires exactly one operand.");
		}

		$operand = reset($operands);
		if (is_array($operand)) {
			$operand = $this->buildCondition($operand, $params);
		}
		return "!($operand)";
	}

286 287
	private function buildAndCondition($operator, $operands, &$columns)
	{
288
		$parts = [];
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313
		foreach ($operands as $operand) {
			if (is_array($operand)) {
				$operand = $this->buildCondition($operand, $columns);
			}
			if ($operand !== '') {
				$parts[] = $operand;
			}
		}
		if (!empty($parts)) {
			return '(' . implode(") $operator (", $parts) . ')';
		} else {
			return '';
		}
	}

	private function buildBetweenCondition($operator, $operands, &$columns)
	{
		if (!isset($operands[0], $operands[1], $operands[2])) {
			throw new Exception("Operator '$operator' requires three operands.");
		}

		list($column, $value1, $value2) = $operands;

		$value1 = $this->quoteValue($value1);
		$value2 = $this->quoteValue($value2);
Carsten Brandt committed
314
		$column = $this->addColumn($column, $columns);
315
		return "$column >= $value1 and $column <= $value2";
316 317 318 319 320 321 322 323 324 325 326 327
	}

	private function buildInCondition($operator, $operands, &$columns)
	{
		if (!isset($operands[0], $operands[1])) {
			throw new Exception("Operator '$operator' requires two operands.");
		}

		list($column, $values) = $operands;

		$values = (array)$values;

328
		if (empty($values) || $column === []) {
Carsten Brandt committed
329
			return $operator === 'in' ? 'false' : 'true';
330 331 332 333 334 335 336
		}

		if (count($column) > 1) {
			return $this->buildCompositeInCondition($operator, $column, $values, $columns);
		} elseif (is_array($column)) {
			$column = reset($column);
		}
Carsten Brandt committed
337
		$columnAlias = $this->addColumn($column, $columns);
338
		$parts = [];
339 340 341 342 343
		foreach ($values as $i => $value) {
			if (is_array($value)) {
				$value = isset($value[$column]) ? $value[$column] : null;
			}
			if ($value === null) {
Carsten Brandt committed
344
				$parts[] = "$columnAlias==nil";
345
			} elseif ($value instanceof Expression) {
Carsten Brandt committed
346
				$parts[] = "$columnAlias==" . $value->expression;
347 348
			} else {
				$value = $this->quoteValue($value);
Carsten Brandt committed
349
				$parts[] = "$columnAlias==$value";
350 351
			}
		}
Carsten Brandt committed
352 353
		$operator = $operator === 'in' ? '' : 'not ';
		return "$operator(" . implode(' or ', $parts) . ')';
354 355
	}

Carsten Brandt committed
356
	protected function buildCompositeInCondition($operator, $inColumns, $values, &$columns)
357
	{
358
		$vss = [];
359
		foreach ($values as $value) {
360
			$vs = [];
Carsten Brandt committed
361 362
			foreach ($inColumns as $column) {
				$column = $this->addColumn($column, $columns);
363
				if (isset($value[$column])) {
Carsten Brandt committed
364
					$vs[] = "$column==" . $this->quoteValue($value[$column]);
365
				} else {
Carsten Brandt committed
366
					$vs[] = "$column==nil";
367 368
				}
			}
Carsten Brandt committed
369
			$vss[] = '(' . implode(' and ', $vs) . ')';
370
		}
Carsten Brandt committed
371 372
		$operator = $operator === 'in' ? '' : 'not ';
		return "$operator(" . implode(' or ', $vss) . ')';
373 374
	}

Carsten Brandt committed
375
	private function buildLikeCondition($operator, $operands, &$columns)
376
	{
Carsten Brandt committed
377
		throw new NotSupportedException('LIKE conditions are not suppoerted by redis ActiveRecord.');
378 379
	}
}