SearchBuilder.php 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2017 Robin Appelman <robin@icewind.nl>
  4. *
  5. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  6. * @author Robin Appelman <robin@icewind.nl>
  7. * @author Roeland Jago Douma <roeland@famdouma.nl>
  8. * @author Tobias Kaminsky <tobias@kaminsky.me>
  9. *
  10. * @license GNU AGPL version 3 or any later version
  11. *
  12. * This program is free software: you can redistribute it and/or modify
  13. * it under the terms of the GNU Affero General Public License as
  14. * published by the Free Software Foundation, either version 3 of the
  15. * License, or (at your option) any later version.
  16. *
  17. * This program is distributed in the hope that it will be useful,
  18. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  20. * GNU Affero General Public License for more details.
  21. *
  22. * You should have received a copy of the GNU Affero General Public License
  23. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  24. *
  25. */
  26. namespace OC\Files\Cache;
  27. use OCP\DB\QueryBuilder\IQueryBuilder;
  28. use OCP\Files\IMimeTypeLoader;
  29. use OCP\Files\Search\ISearchBinaryOperator;
  30. use OCP\Files\Search\ISearchComparison;
  31. use OCP\Files\Search\ISearchOperator;
  32. use OCP\Files\Search\ISearchOrder;
  33. /**
  34. * Tools for transforming search queries into database queries
  35. */
  36. class SearchBuilder {
  37. protected static $searchOperatorMap = [
  38. ISearchComparison::COMPARE_LIKE => 'iLike',
  39. ISearchComparison::COMPARE_LIKE_CASE_SENSITIVE => 'like',
  40. ISearchComparison::COMPARE_EQUAL => 'eq',
  41. ISearchComparison::COMPARE_GREATER_THAN => 'gt',
  42. ISearchComparison::COMPARE_GREATER_THAN_EQUAL => 'gte',
  43. ISearchComparison::COMPARE_LESS_THAN => 'lt',
  44. ISearchComparison::COMPARE_LESS_THAN_EQUAL => 'lte',
  45. ];
  46. protected static $searchOperatorNegativeMap = [
  47. ISearchComparison::COMPARE_LIKE => 'notLike',
  48. ISearchComparison::COMPARE_LIKE_CASE_SENSITIVE => 'notLike',
  49. ISearchComparison::COMPARE_EQUAL => 'neq',
  50. ISearchComparison::COMPARE_GREATER_THAN => 'lte',
  51. ISearchComparison::COMPARE_GREATER_THAN_EQUAL => 'lt',
  52. ISearchComparison::COMPARE_LESS_THAN => 'gte',
  53. ISearchComparison::COMPARE_LESS_THAN_EQUAL => 'gt',
  54. ];
  55. public const TAG_FAVORITE = '_$!<Favorite>!$_';
  56. /** @var IMimeTypeLoader */
  57. private $mimetypeLoader;
  58. public function __construct(
  59. IMimeTypeLoader $mimetypeLoader
  60. ) {
  61. $this->mimetypeLoader = $mimetypeLoader;
  62. }
  63. /**
  64. * @return string[]
  65. */
  66. public function extractRequestedFields(ISearchOperator $operator): array {
  67. if ($operator instanceof ISearchBinaryOperator) {
  68. return array_reduce($operator->getArguments(), function (array $fields, ISearchOperator $operator) {
  69. return array_unique(array_merge($fields, $this->extractRequestedFields($operator)));
  70. }, []);
  71. } elseif ($operator instanceof ISearchComparison) {
  72. return [$operator->getField()];
  73. }
  74. return [];
  75. }
  76. /**
  77. * @param IQueryBuilder $builder
  78. * @param ISearchOperator[] $operators
  79. */
  80. public function searchOperatorArrayToDBExprArray(IQueryBuilder $builder, array $operators) {
  81. return array_filter(array_map(function ($operator) use ($builder) {
  82. return $this->searchOperatorToDBExpr($builder, $operator);
  83. }, $operators));
  84. }
  85. public function searchOperatorToDBExpr(IQueryBuilder $builder, ISearchOperator $operator) {
  86. $expr = $builder->expr();
  87. if ($operator instanceof ISearchBinaryOperator) {
  88. if (count($operator->getArguments()) === 0) {
  89. return null;
  90. }
  91. switch ($operator->getType()) {
  92. case ISearchBinaryOperator::OPERATOR_NOT:
  93. $negativeOperator = $operator->getArguments()[0];
  94. if ($negativeOperator instanceof ISearchComparison) {
  95. return $this->searchComparisonToDBExpr($builder, $negativeOperator, self::$searchOperatorNegativeMap);
  96. } else {
  97. throw new \InvalidArgumentException('Binary operators inside "not" is not supported');
  98. }
  99. // no break
  100. case ISearchBinaryOperator::OPERATOR_AND:
  101. return call_user_func_array([$expr, 'andX'], $this->searchOperatorArrayToDBExprArray($builder, $operator->getArguments()));
  102. case ISearchBinaryOperator::OPERATOR_OR:
  103. return call_user_func_array([$expr, 'orX'], $this->searchOperatorArrayToDBExprArray($builder, $operator->getArguments()));
  104. default:
  105. throw new \InvalidArgumentException('Invalid operator type: ' . $operator->getType());
  106. }
  107. } elseif ($operator instanceof ISearchComparison) {
  108. return $this->searchComparisonToDBExpr($builder, $operator, self::$searchOperatorMap);
  109. } else {
  110. throw new \InvalidArgumentException('Invalid operator type: ' . get_class($operator));
  111. }
  112. }
  113. private function searchComparisonToDBExpr(IQueryBuilder $builder, ISearchComparison $comparison, array $operatorMap) {
  114. $this->validateComparison($comparison);
  115. [$field, $value, $type] = $this->getOperatorFieldAndValue($comparison);
  116. if (isset($operatorMap[$type])) {
  117. $queryOperator = $operatorMap[$type];
  118. return $builder->expr()->$queryOperator($field, $this->getParameterForValue($builder, $value));
  119. } else {
  120. throw new \InvalidArgumentException('Invalid operator type: ' . $comparison->getType());
  121. }
  122. }
  123. private function getOperatorFieldAndValue(ISearchComparison $operator) {
  124. $field = $operator->getField();
  125. $value = $operator->getValue();
  126. $type = $operator->getType();
  127. if ($field === 'mimetype') {
  128. $value = (string)$value;
  129. if ($operator->getType() === ISearchComparison::COMPARE_EQUAL) {
  130. $value = (int)$this->mimetypeLoader->getId($value);
  131. } elseif ($operator->getType() === ISearchComparison::COMPARE_LIKE) {
  132. // transform "mimetype='foo/%'" to "mimepart='foo'"
  133. if (preg_match('|(.+)/%|', $value, $matches)) {
  134. $field = 'mimepart';
  135. $value = (int)$this->mimetypeLoader->getId($matches[1]);
  136. $type = ISearchComparison::COMPARE_EQUAL;
  137. } elseif (str_contains($value, '%')) {
  138. throw new \InvalidArgumentException('Unsupported query value for mimetype: ' . $value . ', only values in the format "mime/type" or "mime/%" are supported');
  139. } else {
  140. $field = 'mimetype';
  141. $value = (int)$this->mimetypeLoader->getId($value);
  142. $type = ISearchComparison::COMPARE_EQUAL;
  143. }
  144. }
  145. } elseif ($field === 'favorite') {
  146. $field = 'tag.category';
  147. $value = self::TAG_FAVORITE;
  148. } elseif ($field === 'name') {
  149. $field = 'file.name';
  150. } elseif ($field === 'tagname') {
  151. $field = 'tag.category';
  152. } elseif ($field === 'systemtag') {
  153. $field = 'systemtag.name';
  154. } elseif ($field === 'fileid') {
  155. $field = 'file.fileid';
  156. } elseif ($field === 'path' && $type === ISearchComparison::COMPARE_EQUAL && $operator->getQueryHint(ISearchComparison::HINT_PATH_EQ_HASH, true)) {
  157. $field = 'path_hash';
  158. $value = md5((string)$value);
  159. }
  160. return [$field, $value, $type];
  161. }
  162. private function validateComparison(ISearchComparison $operator) {
  163. $types = [
  164. 'mimetype' => 'string',
  165. 'mtime' => 'integer',
  166. 'name' => 'string',
  167. 'path' => 'string',
  168. 'size' => 'integer',
  169. 'tagname' => 'string',
  170. 'systemtag' => 'string',
  171. 'favorite' => 'boolean',
  172. 'fileid' => 'integer',
  173. 'storage' => 'integer',
  174. ];
  175. $comparisons = [
  176. 'mimetype' => ['eq', 'like'],
  177. 'mtime' => ['eq', 'gt', 'lt', 'gte', 'lte'],
  178. 'name' => ['eq', 'like', 'clike'],
  179. 'path' => ['eq', 'like', 'clike'],
  180. 'size' => ['eq', 'gt', 'lt', 'gte', 'lte'],
  181. 'tagname' => ['eq', 'like'],
  182. 'systemtag' => ['eq', 'like'],
  183. 'favorite' => ['eq'],
  184. 'fileid' => ['eq'],
  185. 'storage' => ['eq'],
  186. ];
  187. if (!isset($types[$operator->getField()])) {
  188. throw new \InvalidArgumentException('Unsupported comparison field ' . $operator->getField());
  189. }
  190. $type = $types[$operator->getField()];
  191. if (gettype($operator->getValue()) !== $type) {
  192. throw new \InvalidArgumentException('Invalid type for field ' . $operator->getField());
  193. }
  194. if (!in_array($operator->getType(), $comparisons[$operator->getField()])) {
  195. throw new \InvalidArgumentException('Unsupported comparison for field ' . $operator->getField() . ': ' . $operator->getType());
  196. }
  197. }
  198. private function getParameterForValue(IQueryBuilder $builder, $value) {
  199. if ($value instanceof \DateTime) {
  200. $value = $value->getTimestamp();
  201. }
  202. if (is_numeric($value)) {
  203. $type = IQueryBuilder::PARAM_INT;
  204. } else {
  205. $type = IQueryBuilder::PARAM_STR;
  206. }
  207. return $builder->createNamedParameter($value, $type);
  208. }
  209. /**
  210. * @param IQueryBuilder $query
  211. * @param ISearchOrder[] $orders
  212. */
  213. public function addSearchOrdersToQuery(IQueryBuilder $query, array $orders) {
  214. foreach ($orders as $order) {
  215. $field = $order->getField();
  216. if ($field === 'fileid') {
  217. $field = 'file.fileid';
  218. }
  219. // Mysql really likes to pick an index for sorting if it can't fully satisfy the where
  220. // filter with an index, since search queries pretty much never are fully filtered by index
  221. // mysql often picks an index for sorting instead of the much more useful index for filtering.
  222. //
  223. // By changing the order by to an expression, mysql isn't smart enough to see that it could still
  224. // use the index, so it instead picks an index for the filtering
  225. if ($field === 'mtime') {
  226. $field = $query->func()->add($field, $query->createNamedParameter(0));
  227. }
  228. $query->addOrderBy($field, $order->getDirection());
  229. }
  230. }
  231. }