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.

QueryBuilder.php 37KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  6. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  7. * @author Daniel Kesselberg <mail@danielkesselberg.de>
  8. * @author J0WI <J0WI@users.noreply.github.com>
  9. * @author Joas Schilling <coding@schilljs.com>
  10. * @author Lukas Reschke <lukas@statuscode.ch>
  11. * @author Robin Appelman <robin@icewind.nl>
  12. * @author Roeland Jago Douma <roeland@famdouma.nl>
  13. * @author Thomas Müller <thomas.mueller@tmit.eu>
  14. * @author Vincent Petry <vincent@nextcloud.com>
  15. *
  16. * @license AGPL-3.0
  17. *
  18. * This code is free software: you can redistribute it and/or modify
  19. * it under the terms of the GNU Affero General Public License, version 3,
  20. * as published by the Free Software Foundation.
  21. *
  22. * This program is distributed in the hope that it will be useful,
  23. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  24. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  25. * GNU Affero General Public License for more details.
  26. *
  27. * You should have received a copy of the GNU Affero General Public License, version 3,
  28. * along with this program. If not, see <http://www.gnu.org/licenses/>
  29. *
  30. */
  31. namespace OC\DB\QueryBuilder;
  32. use Doctrine\DBAL\Platforms\MySQLPlatform;
  33. use Doctrine\DBAL\Platforms\OraclePlatform;
  34. use Doctrine\DBAL\Platforms\PostgreSQL94Platform;
  35. use Doctrine\DBAL\Platforms\SqlitePlatform;
  36. use Doctrine\DBAL\Query\QueryException;
  37. use OC\DB\ConnectionAdapter;
  38. use OC\DB\QueryBuilder\ExpressionBuilder\ExpressionBuilder;
  39. use OC\DB\QueryBuilder\ExpressionBuilder\MySqlExpressionBuilder;
  40. use OC\DB\QueryBuilder\ExpressionBuilder\OCIExpressionBuilder;
  41. use OC\DB\QueryBuilder\ExpressionBuilder\PgSqlExpressionBuilder;
  42. use OC\DB\QueryBuilder\ExpressionBuilder\SqliteExpressionBuilder;
  43. use OC\DB\QueryBuilder\FunctionBuilder\FunctionBuilder;
  44. use OC\DB\QueryBuilder\FunctionBuilder\OCIFunctionBuilder;
  45. use OC\DB\QueryBuilder\FunctionBuilder\PgSqlFunctionBuilder;
  46. use OC\DB\QueryBuilder\FunctionBuilder\SqliteFunctionBuilder;
  47. use OC\DB\ResultAdapter;
  48. use OC\SystemConfig;
  49. use OCP\DB\IResult;
  50. use OCP\DB\QueryBuilder\ICompositeExpression;
  51. use OCP\DB\QueryBuilder\ILiteral;
  52. use OCP\DB\QueryBuilder\IParameter;
  53. use OCP\DB\QueryBuilder\IQueryBuilder;
  54. use OCP\DB\QueryBuilder\IQueryFunction;
  55. use Psr\Log\LoggerInterface;
  56. class QueryBuilder implements IQueryBuilder {
  57. /** @var ConnectionAdapter */
  58. private $connection;
  59. /** @var SystemConfig */
  60. private $systemConfig;
  61. private LoggerInterface $logger;
  62. /** @var \Doctrine\DBAL\Query\QueryBuilder */
  63. private $queryBuilder;
  64. /** @var QuoteHelper */
  65. private $helper;
  66. /** @var bool */
  67. private $automaticTablePrefix = true;
  68. /** @var string */
  69. protected $lastInsertedTable;
  70. /**
  71. * Initializes a new QueryBuilder.
  72. *
  73. * @param ConnectionAdapter $connection
  74. * @param SystemConfig $systemConfig
  75. */
  76. public function __construct(ConnectionAdapter $connection, SystemConfig $systemConfig, LoggerInterface $logger) {
  77. $this->connection = $connection;
  78. $this->systemConfig = $systemConfig;
  79. $this->logger = $logger;
  80. $this->queryBuilder = new \Doctrine\DBAL\Query\QueryBuilder($this->connection->getInner());
  81. $this->helper = new QuoteHelper();
  82. }
  83. /**
  84. * Enable/disable automatic prefixing of table names with the oc_ prefix
  85. *
  86. * @param bool $enabled If set to true table names will be prefixed with the
  87. * owncloud database prefix automatically.
  88. * @since 8.2.0
  89. */
  90. public function automaticTablePrefix($enabled) {
  91. $this->automaticTablePrefix = (bool) $enabled;
  92. }
  93. /**
  94. * Gets an ExpressionBuilder used for object-oriented construction of query expressions.
  95. * This producer method is intended for convenient inline usage. Example:
  96. *
  97. * <code>
  98. * $qb = $conn->getQueryBuilder()
  99. * ->select('u')
  100. * ->from('users', 'u')
  101. * ->where($qb->expr()->eq('u.id', 1));
  102. * </code>
  103. *
  104. * For more complex expression construction, consider storing the expression
  105. * builder object in a local variable.
  106. *
  107. * @return \OCP\DB\QueryBuilder\IExpressionBuilder
  108. */
  109. public function expr() {
  110. if ($this->connection->getDatabasePlatform() instanceof OraclePlatform) {
  111. return new OCIExpressionBuilder($this->connection, $this);
  112. }
  113. if ($this->connection->getDatabasePlatform() instanceof PostgreSQL94Platform) {
  114. return new PgSqlExpressionBuilder($this->connection, $this);
  115. }
  116. if ($this->connection->getDatabasePlatform() instanceof MySQLPlatform) {
  117. return new MySqlExpressionBuilder($this->connection, $this);
  118. }
  119. if ($this->connection->getDatabasePlatform() instanceof SqlitePlatform) {
  120. return new SqliteExpressionBuilder($this->connection, $this);
  121. }
  122. return new ExpressionBuilder($this->connection, $this);
  123. }
  124. /**
  125. * Gets an FunctionBuilder used for object-oriented construction of query functions.
  126. * This producer method is intended for convenient inline usage. Example:
  127. *
  128. * <code>
  129. * $qb = $conn->getQueryBuilder()
  130. * ->select('u')
  131. * ->from('users', 'u')
  132. * ->where($qb->fun()->md5('u.id'));
  133. * </code>
  134. *
  135. * For more complex function construction, consider storing the function
  136. * builder object in a local variable.
  137. *
  138. * @return \OCP\DB\QueryBuilder\IFunctionBuilder
  139. */
  140. public function func() {
  141. if ($this->connection->getDatabasePlatform() instanceof OraclePlatform) {
  142. return new OCIFunctionBuilder($this->connection, $this, $this->helper);
  143. }
  144. if ($this->connection->getDatabasePlatform() instanceof SqlitePlatform) {
  145. return new SqliteFunctionBuilder($this->connection, $this, $this->helper);
  146. }
  147. if ($this->connection->getDatabasePlatform() instanceof PostgreSQL94Platform) {
  148. return new PgSqlFunctionBuilder($this->connection, $this, $this->helper);
  149. }
  150. return new FunctionBuilder($this->connection, $this, $this->helper);
  151. }
  152. /**
  153. * Gets the type of the currently built query.
  154. *
  155. * @return integer
  156. */
  157. public function getType() {
  158. return $this->queryBuilder->getType();
  159. }
  160. /**
  161. * Gets the associated DBAL Connection for this query builder.
  162. *
  163. * @return \OCP\IDBConnection
  164. */
  165. public function getConnection() {
  166. return $this->connection;
  167. }
  168. /**
  169. * Gets the state of this query builder instance.
  170. *
  171. * @return integer Either QueryBuilder::STATE_DIRTY or QueryBuilder::STATE_CLEAN.
  172. */
  173. public function getState() {
  174. return $this->queryBuilder->getState();
  175. }
  176. /**
  177. * Executes this query using the bound parameters and their types.
  178. *
  179. * Uses {@see Connection::executeQuery} for select statements and {@see Connection::executeUpdate}
  180. * for insert, update and delete statements.
  181. *
  182. * @return IResult|int
  183. */
  184. public function execute() {
  185. if ($this->systemConfig->getValue('log_query', false)) {
  186. try {
  187. $params = [];
  188. foreach ($this->getParameters() as $placeholder => $value) {
  189. if ($value instanceof \DateTime) {
  190. $params[] = $placeholder . ' => DateTime:\'' . $value->format('c') . '\'';
  191. } elseif (is_array($value)) {
  192. $params[] = $placeholder . ' => (\'' . implode('\', \'', $value) . '\')';
  193. } else {
  194. $params[] = $placeholder . ' => \'' . $value . '\'';
  195. }
  196. }
  197. if (empty($params)) {
  198. $this->logger->debug('DB QueryBuilder: \'{query}\'', [
  199. 'query' => $this->getSQL(),
  200. 'app' => 'core',
  201. ]);
  202. } else {
  203. $this->logger->debug('DB QueryBuilder: \'{query}\' with parameters: {params}', [
  204. 'query' => $this->getSQL(),
  205. 'params' => implode(', ', $params),
  206. 'app' => 'core',
  207. ]);
  208. }
  209. } catch (\Error $e) {
  210. // likely an error during conversion of $value to string
  211. $this->logger->error('DB QueryBuilder: error trying to log SQL query', ['exception' => $e]);
  212. }
  213. }
  214. if (!empty($this->getQueryPart('select'))) {
  215. $select = $this->getQueryPart('select');
  216. $hasSelectAll = array_filter($select, static function ($s) {
  217. return $s === '*';
  218. });
  219. $hasSelectSpecific = array_filter($select, static function ($s) {
  220. return $s !== '*';
  221. });
  222. if (empty($hasSelectAll) === empty($hasSelectSpecific)) {
  223. $exception = new QueryException('Query is selecting * and specific values in the same query. This is not supported in Oracle.');
  224. $this->logger->error($exception->getMessage(), [
  225. 'query' => $this->getSQL(),
  226. 'app' => 'core',
  227. 'exception' => $exception,
  228. ]);
  229. }
  230. }
  231. $numberOfParameters = 0;
  232. $hasTooLargeArrayParameter = false;
  233. foreach ($this->getParameters() as $parameter) {
  234. if (is_array($parameter)) {
  235. $count = count($parameter);
  236. $numberOfParameters += $count;
  237. $hasTooLargeArrayParameter = $hasTooLargeArrayParameter || ($count > 1000);
  238. }
  239. }
  240. if ($hasTooLargeArrayParameter) {
  241. $exception = new QueryException('More than 1000 expressions in a list are not allowed on Oracle.');
  242. $this->logger->error($exception->getMessage(), [
  243. 'query' => $this->getSQL(),
  244. 'app' => 'core',
  245. 'exception' => $exception,
  246. ]);
  247. }
  248. if ($numberOfParameters > 65535) {
  249. $exception = new QueryException('The number of parameters must not exceed 65535. Restriction by PostgreSQL.');
  250. $this->logger->error($exception->getMessage(), [
  251. 'query' => $this->getSQL(),
  252. 'app' => 'core',
  253. 'exception' => $exception,
  254. ]);
  255. }
  256. $result = $this->queryBuilder->execute();
  257. if (is_int($result)) {
  258. return $result;
  259. }
  260. return new ResultAdapter($result);
  261. }
  262. public function executeQuery(): IResult {
  263. if ($this->getType() !== \Doctrine\DBAL\Query\QueryBuilder::SELECT) {
  264. throw new \RuntimeException('Invalid query type, expected SELECT query');
  265. }
  266. try {
  267. $result = $this->execute();
  268. } catch (\Doctrine\DBAL\Exception $e) {
  269. throw \OC\DB\Exceptions\DbalException::wrap($e);
  270. }
  271. if ($result instanceof IResult) {
  272. return $result;
  273. }
  274. throw new \RuntimeException('Invalid return type for query');
  275. }
  276. /**
  277. * Monkey-patched compatibility layer for apps that were adapted for Nextcloud 22 before
  278. * the first beta, where executeStatement was named executeUpdate.
  279. *
  280. * Static analysis should catch those misuses, but until then let's try to keep things
  281. * running.
  282. *
  283. * @internal
  284. * @deprecated
  285. * @todo drop ASAP
  286. */
  287. public function executeUpdate(): int {
  288. return $this->executeStatement();
  289. }
  290. public function executeStatement(): int {
  291. if ($this->getType() === \Doctrine\DBAL\Query\QueryBuilder::SELECT) {
  292. throw new \RuntimeException('Invalid query type, expected INSERT, DELETE or UPDATE statement');
  293. }
  294. try {
  295. $result = $this->execute();
  296. } catch (\Doctrine\DBAL\Exception $e) {
  297. throw \OC\DB\Exceptions\DbalException::wrap($e);
  298. }
  299. if (!is_int($result)) {
  300. throw new \RuntimeException('Invalid return type for statement');
  301. }
  302. return $result;
  303. }
  304. /**
  305. * Gets the complete SQL string formed by the current specifications of this QueryBuilder.
  306. *
  307. * <code>
  308. * $qb = $conn->getQueryBuilder()
  309. * ->select('u')
  310. * ->from('User', 'u')
  311. * echo $qb->getSQL(); // SELECT u FROM User u
  312. * </code>
  313. *
  314. * @return string The SQL query string.
  315. */
  316. public function getSQL() {
  317. return $this->queryBuilder->getSQL();
  318. }
  319. /**
  320. * Sets a query parameter for the query being constructed.
  321. *
  322. * <code>
  323. * $qb = $conn->getQueryBuilder()
  324. * ->select('u')
  325. * ->from('users', 'u')
  326. * ->where('u.id = :user_id')
  327. * ->setParameter(':user_id', 1);
  328. * </code>
  329. *
  330. * @param string|integer $key The parameter position or name.
  331. * @param mixed $value The parameter value.
  332. * @param string|null|int $type One of the IQueryBuilder::PARAM_* constants.
  333. *
  334. * @return $this This QueryBuilder instance.
  335. */
  336. public function setParameter($key, $value, $type = null) {
  337. $this->queryBuilder->setParameter($key, $value, $type);
  338. return $this;
  339. }
  340. /**
  341. * Sets a collection of query parameters for the query being constructed.
  342. *
  343. * <code>
  344. * $qb = $conn->getQueryBuilder()
  345. * ->select('u')
  346. * ->from('users', 'u')
  347. * ->where('u.id = :user_id1 OR u.id = :user_id2')
  348. * ->setParameters(array(
  349. * ':user_id1' => 1,
  350. * ':user_id2' => 2
  351. * ));
  352. * </code>
  353. *
  354. * @param array $params The query parameters to set.
  355. * @param array $types The query parameters types to set.
  356. *
  357. * @return $this This QueryBuilder instance.
  358. */
  359. public function setParameters(array $params, array $types = []) {
  360. $this->queryBuilder->setParameters($params, $types);
  361. return $this;
  362. }
  363. /**
  364. * Gets all defined query parameters for the query being constructed indexed by parameter index or name.
  365. *
  366. * @return array The currently defined query parameters indexed by parameter index or name.
  367. */
  368. public function getParameters() {
  369. return $this->queryBuilder->getParameters();
  370. }
  371. /**
  372. * Gets a (previously set) query parameter of the query being constructed.
  373. *
  374. * @param mixed $key The key (index or name) of the bound parameter.
  375. *
  376. * @return mixed The value of the bound parameter.
  377. */
  378. public function getParameter($key) {
  379. return $this->queryBuilder->getParameter($key);
  380. }
  381. /**
  382. * Gets all defined query parameter types for the query being constructed indexed by parameter index or name.
  383. *
  384. * @return array The currently defined query parameter types indexed by parameter index or name.
  385. */
  386. public function getParameterTypes() {
  387. return $this->queryBuilder->getParameterTypes();
  388. }
  389. /**
  390. * Gets a (previously set) query parameter type of the query being constructed.
  391. *
  392. * @param mixed $key The key (index or name) of the bound parameter type.
  393. *
  394. * @return mixed The value of the bound parameter type.
  395. */
  396. public function getParameterType($key) {
  397. return $this->queryBuilder->getParameterType($key);
  398. }
  399. /**
  400. * Sets the position of the first result to retrieve (the "offset").
  401. *
  402. * @param int $firstResult The first result to return.
  403. *
  404. * @return $this This QueryBuilder instance.
  405. */
  406. public function setFirstResult($firstResult) {
  407. $this->queryBuilder->setFirstResult((int) $firstResult);
  408. return $this;
  409. }
  410. /**
  411. * Gets the position of the first result the query object was set to retrieve (the "offset").
  412. * Returns 0 if {@link setFirstResult} was not applied to this QueryBuilder.
  413. *
  414. * @return int The position of the first result.
  415. */
  416. public function getFirstResult() {
  417. return $this->queryBuilder->getFirstResult();
  418. }
  419. /**
  420. * Sets the maximum number of results to retrieve (the "limit").
  421. *
  422. * NOTE: Setting max results to "0" will cause mixed behaviour. While most
  423. * of the databases will just return an empty result set, Oracle will return
  424. * all entries.
  425. *
  426. * @param int|null $maxResults The maximum number of results to retrieve.
  427. *
  428. * @return $this This QueryBuilder instance.
  429. */
  430. public function setMaxResults($maxResults) {
  431. if ($maxResults === null) {
  432. $this->queryBuilder->setMaxResults($maxResults);
  433. } else {
  434. $this->queryBuilder->setMaxResults((int) $maxResults);
  435. }
  436. return $this;
  437. }
  438. /**
  439. * Gets the maximum number of results the query object was set to retrieve (the "limit").
  440. * Returns NULL if {@link setMaxResults} was not applied to this query builder.
  441. *
  442. * @return int|null The maximum number of results.
  443. */
  444. public function getMaxResults() {
  445. return $this->queryBuilder->getMaxResults();
  446. }
  447. /**
  448. * Specifies an item that is to be returned in the query result.
  449. * Replaces any previously specified selections, if any.
  450. *
  451. * <code>
  452. * $qb = $conn->getQueryBuilder()
  453. * ->select('u.id', 'p.id')
  454. * ->from('users', 'u')
  455. * ->leftJoin('u', 'phonenumbers', 'p', 'u.id = p.user_id');
  456. * </code>
  457. *
  458. * @param mixed ...$selects The selection expressions.
  459. *
  460. * '@return $this This QueryBuilder instance.
  461. */
  462. public function select(...$selects) {
  463. if (count($selects) === 1 && is_array($selects[0])) {
  464. $selects = $selects[0];
  465. }
  466. $this->queryBuilder->select(
  467. $this->helper->quoteColumnNames($selects)
  468. );
  469. return $this;
  470. }
  471. /**
  472. * Specifies an item that is to be returned with a different name in the query result.
  473. *
  474. * <code>
  475. * $qb = $conn->getQueryBuilder()
  476. * ->selectAlias('u.id', 'user_id')
  477. * ->from('users', 'u')
  478. * ->leftJoin('u', 'phonenumbers', 'p', 'u.id = p.user_id');
  479. * </code>
  480. *
  481. * @param mixed $select The selection expressions.
  482. * @param string $alias The column alias used in the constructed query.
  483. *
  484. * @return $this This QueryBuilder instance.
  485. */
  486. public function selectAlias($select, $alias) {
  487. $this->queryBuilder->addSelect(
  488. $this->helper->quoteColumnName($select) . ' AS ' . $this->helper->quoteColumnName($alias)
  489. );
  490. return $this;
  491. }
  492. /**
  493. * Specifies an item that is to be returned uniquely in the query result.
  494. *
  495. * <code>
  496. * $qb = $conn->getQueryBuilder()
  497. * ->selectDistinct('type')
  498. * ->from('users');
  499. * </code>
  500. *
  501. * @param mixed $select The selection expressions.
  502. *
  503. * @return $this This QueryBuilder instance.
  504. */
  505. public function selectDistinct($select) {
  506. if (!is_array($select)) {
  507. $select = [$select];
  508. }
  509. $quotedSelect = $this->helper->quoteColumnNames($select);
  510. $this->queryBuilder->addSelect(
  511. 'DISTINCT ' . implode(', ', $quotedSelect)
  512. );
  513. return $this;
  514. }
  515. /**
  516. * Adds an item that is to be returned in the query result.
  517. *
  518. * <code>
  519. * $qb = $conn->getQueryBuilder()
  520. * ->select('u.id')
  521. * ->addSelect('p.id')
  522. * ->from('users', 'u')
  523. * ->leftJoin('u', 'phonenumbers', 'u.id = p.user_id');
  524. * </code>
  525. *
  526. * @param mixed ...$selects The selection expression.
  527. *
  528. * @return $this This QueryBuilder instance.
  529. */
  530. public function addSelect(...$selects) {
  531. if (count($selects) === 1 && is_array($selects[0])) {
  532. $selects = $selects[0];
  533. }
  534. $this->queryBuilder->addSelect(
  535. $this->helper->quoteColumnNames($selects)
  536. );
  537. return $this;
  538. }
  539. /**
  540. * Turns the query being built into a bulk delete query that ranges over
  541. * a certain table.
  542. *
  543. * <code>
  544. * $qb = $conn->getQueryBuilder()
  545. * ->delete('users', 'u')
  546. * ->where('u.id = :user_id');
  547. * ->setParameter(':user_id', 1);
  548. * </code>
  549. *
  550. * @param string $delete The table whose rows are subject to the deletion.
  551. * @param string $alias The table alias used in the constructed query.
  552. *
  553. * @return $this This QueryBuilder instance.
  554. */
  555. public function delete($delete = null, $alias = null) {
  556. $this->queryBuilder->delete(
  557. $this->getTableName($delete),
  558. $alias
  559. );
  560. return $this;
  561. }
  562. /**
  563. * Turns the query being built into a bulk update query that ranges over
  564. * a certain table
  565. *
  566. * <code>
  567. * $qb = $conn->getQueryBuilder()
  568. * ->update('users', 'u')
  569. * ->set('u.password', md5('password'))
  570. * ->where('u.id = ?');
  571. * </code>
  572. *
  573. * @param string $update The table whose rows are subject to the update.
  574. * @param string $alias The table alias used in the constructed query.
  575. *
  576. * @return $this This QueryBuilder instance.
  577. */
  578. public function update($update = null, $alias = null) {
  579. $this->queryBuilder->update(
  580. $this->getTableName($update),
  581. $alias
  582. );
  583. return $this;
  584. }
  585. /**
  586. * Turns the query being built into an insert query that inserts into
  587. * a certain table
  588. *
  589. * <code>
  590. * $qb = $conn->getQueryBuilder()
  591. * ->insert('users')
  592. * ->values(
  593. * array(
  594. * 'name' => '?',
  595. * 'password' => '?'
  596. * )
  597. * );
  598. * </code>
  599. *
  600. * @param string $insert The table into which the rows should be inserted.
  601. *
  602. * @return $this This QueryBuilder instance.
  603. */
  604. public function insert($insert = null) {
  605. $this->queryBuilder->insert(
  606. $this->getTableName($insert)
  607. );
  608. $this->lastInsertedTable = $insert;
  609. return $this;
  610. }
  611. /**
  612. * Creates and adds a query root corresponding to the table identified by the
  613. * given alias, forming a cartesian product with any existing query roots.
  614. *
  615. * <code>
  616. * $qb = $conn->getQueryBuilder()
  617. * ->select('u.id')
  618. * ->from('users', 'u')
  619. * </code>
  620. *
  621. * @param string|IQueryFunction $from The table.
  622. * @param string|null $alias The alias of the table.
  623. *
  624. * @return $this This QueryBuilder instance.
  625. */
  626. public function from($from, $alias = null) {
  627. $this->queryBuilder->from(
  628. $this->getTableName($from),
  629. $this->quoteAlias($alias)
  630. );
  631. return $this;
  632. }
  633. /**
  634. * Creates and adds a join to the query.
  635. *
  636. * <code>
  637. * $qb = $conn->getQueryBuilder()
  638. * ->select('u.name')
  639. * ->from('users', 'u')
  640. * ->join('u', 'phonenumbers', 'p', 'p.is_primary = 1');
  641. * </code>
  642. *
  643. * @param string $fromAlias The alias that points to a from clause.
  644. * @param string $join The table name to join.
  645. * @param string $alias The alias of the join table.
  646. * @param string|ICompositeExpression|null $condition The condition for the join.
  647. *
  648. * @return $this This QueryBuilder instance.
  649. */
  650. public function join($fromAlias, $join, $alias, $condition = null) {
  651. $this->queryBuilder->join(
  652. $this->quoteAlias($fromAlias),
  653. $this->getTableName($join),
  654. $this->quoteAlias($alias),
  655. $condition
  656. );
  657. return $this;
  658. }
  659. /**
  660. * Creates and adds a join to the query.
  661. *
  662. * <code>
  663. * $qb = $conn->getQueryBuilder()
  664. * ->select('u.name')
  665. * ->from('users', 'u')
  666. * ->innerJoin('u', 'phonenumbers', 'p', 'p.is_primary = 1');
  667. * </code>
  668. *
  669. * @param string $fromAlias The alias that points to a from clause.
  670. * @param string $join The table name to join.
  671. * @param string $alias The alias of the join table.
  672. * @param string|ICompositeExpression|null $condition The condition for the join.
  673. *
  674. * @return $this This QueryBuilder instance.
  675. */
  676. public function innerJoin($fromAlias, $join, $alias, $condition = null) {
  677. $this->queryBuilder->innerJoin(
  678. $this->quoteAlias($fromAlias),
  679. $this->getTableName($join),
  680. $this->quoteAlias($alias),
  681. $condition
  682. );
  683. return $this;
  684. }
  685. /**
  686. * Creates and adds a left join to the query.
  687. *
  688. * <code>
  689. * $qb = $conn->getQueryBuilder()
  690. * ->select('u.name')
  691. * ->from('users', 'u')
  692. * ->leftJoin('u', 'phonenumbers', 'p', 'p.is_primary = 1');
  693. * </code>
  694. *
  695. * @param string $fromAlias The alias that points to a from clause.
  696. * @param string $join The table name to join.
  697. * @param string $alias The alias of the join table.
  698. * @param string|ICompositeExpression|null $condition The condition for the join.
  699. *
  700. * @return $this This QueryBuilder instance.
  701. */
  702. public function leftJoin($fromAlias, $join, $alias, $condition = null) {
  703. $this->queryBuilder->leftJoin(
  704. $this->quoteAlias($fromAlias),
  705. $this->getTableName($join),
  706. $this->quoteAlias($alias),
  707. $condition
  708. );
  709. return $this;
  710. }
  711. /**
  712. * Creates and adds a right join to the query.
  713. *
  714. * <code>
  715. * $qb = $conn->getQueryBuilder()
  716. * ->select('u.name')
  717. * ->from('users', 'u')
  718. * ->rightJoin('u', 'phonenumbers', 'p', 'p.is_primary = 1');
  719. * </code>
  720. *
  721. * @param string $fromAlias The alias that points to a from clause.
  722. * @param string $join The table name to join.
  723. * @param string $alias The alias of the join table.
  724. * @param string|ICompositeExpression|null $condition The condition for the join.
  725. *
  726. * @return $this This QueryBuilder instance.
  727. */
  728. public function rightJoin($fromAlias, $join, $alias, $condition = null) {
  729. $this->queryBuilder->rightJoin(
  730. $this->quoteAlias($fromAlias),
  731. $this->getTableName($join),
  732. $this->quoteAlias($alias),
  733. $condition
  734. );
  735. return $this;
  736. }
  737. /**
  738. * Sets a new value for a column in a bulk update query.
  739. *
  740. * <code>
  741. * $qb = $conn->getQueryBuilder()
  742. * ->update('users', 'u')
  743. * ->set('u.password', md5('password'))
  744. * ->where('u.id = ?');
  745. * </code>
  746. *
  747. * @param string $key The column to set.
  748. * @param ILiteral|IParameter|IQueryFunction|string $value The value, expression, placeholder, etc.
  749. *
  750. * @return $this This QueryBuilder instance.
  751. */
  752. public function set($key, $value) {
  753. $this->queryBuilder->set(
  754. $this->helper->quoteColumnName($key),
  755. $this->helper->quoteColumnName($value)
  756. );
  757. return $this;
  758. }
  759. /**
  760. * Specifies one or more restrictions to the query result.
  761. * Replaces any previously specified restrictions, if any.
  762. *
  763. * <code>
  764. * $qb = $conn->getQueryBuilder()
  765. * ->select('u.name')
  766. * ->from('users', 'u')
  767. * ->where('u.id = ?');
  768. *
  769. * // You can optionally programmatically build and/or expressions
  770. * $qb = $conn->getQueryBuilder();
  771. *
  772. * $or = $qb->expr()->orx();
  773. * $or->add($qb->expr()->eq('u.id', 1));
  774. * $or->add($qb->expr()->eq('u.id', 2));
  775. *
  776. * $qb->update('users', 'u')
  777. * ->set('u.password', md5('password'))
  778. * ->where($or);
  779. * </code>
  780. *
  781. * @param mixed ...$predicates The restriction predicates.
  782. *
  783. * @return $this This QueryBuilder instance.
  784. */
  785. public function where(...$predicates) {
  786. if ($this->getQueryPart('where') !== null && $this->systemConfig->getValue('debug', false)) {
  787. // Only logging a warning, not throwing for now.
  788. $e = new QueryException('Using where() on non-empty WHERE part, please verify it is intentional to not call andWhere() or orWhere() instead. Otherwise consider creating a new query builder object or call resetQueryPart(\'where\') first.');
  789. $this->logger->warning($e->getMessage(), ['exception' => $e]);
  790. }
  791. call_user_func_array(
  792. [$this->queryBuilder, 'where'],
  793. $predicates
  794. );
  795. return $this;
  796. }
  797. /**
  798. * Adds one or more restrictions to the query results, forming a logical
  799. * conjunction with any previously specified restrictions.
  800. *
  801. * <code>
  802. * $qb = $conn->getQueryBuilder()
  803. * ->select('u')
  804. * ->from('users', 'u')
  805. * ->where('u.username LIKE ?')
  806. * ->andWhere('u.is_active = 1');
  807. * </code>
  808. *
  809. * @param mixed ...$where The query restrictions.
  810. *
  811. * @return $this This QueryBuilder instance.
  812. *
  813. * @see where()
  814. */
  815. public function andWhere(...$where) {
  816. call_user_func_array(
  817. [$this->queryBuilder, 'andWhere'],
  818. $where
  819. );
  820. return $this;
  821. }
  822. /**
  823. * Adds one or more restrictions to the query results, forming a logical
  824. * disjunction with any previously specified restrictions.
  825. *
  826. * <code>
  827. * $qb = $conn->getQueryBuilder()
  828. * ->select('u.name')
  829. * ->from('users', 'u')
  830. * ->where('u.id = 1')
  831. * ->orWhere('u.id = 2');
  832. * </code>
  833. *
  834. * @param mixed ...$where The WHERE statement.
  835. *
  836. * @return $this This QueryBuilder instance.
  837. *
  838. * @see where()
  839. */
  840. public function orWhere(...$where) {
  841. call_user_func_array(
  842. [$this->queryBuilder, 'orWhere'],
  843. $where
  844. );
  845. return $this;
  846. }
  847. /**
  848. * Specifies a grouping over the results of the query.
  849. * Replaces any previously specified groupings, if any.
  850. *
  851. * <code>
  852. * $qb = $conn->getQueryBuilder()
  853. * ->select('u.name')
  854. * ->from('users', 'u')
  855. * ->groupBy('u.id');
  856. * </code>
  857. *
  858. * @param mixed ...$groupBys The grouping expression.
  859. *
  860. * @return $this This QueryBuilder instance.
  861. */
  862. public function groupBy(...$groupBys) {
  863. if (count($groupBys) === 1 && is_array($groupBys[0])) {
  864. $groupBys = $groupBys[0];
  865. }
  866. call_user_func_array(
  867. [$this->queryBuilder, 'groupBy'],
  868. $this->helper->quoteColumnNames($groupBys)
  869. );
  870. return $this;
  871. }
  872. /**
  873. * Adds a grouping expression to the query.
  874. *
  875. * <code>
  876. * $qb = $conn->getQueryBuilder()
  877. * ->select('u.name')
  878. * ->from('users', 'u')
  879. * ->groupBy('u.lastLogin');
  880. * ->addGroupBy('u.createdAt')
  881. * </code>
  882. *
  883. * @param mixed ...$groupBy The grouping expression.
  884. *
  885. * @return $this This QueryBuilder instance.
  886. */
  887. public function addGroupBy(...$groupBy) {
  888. call_user_func_array(
  889. [$this->queryBuilder, 'addGroupBy'],
  890. $this->helper->quoteColumnNames($groupBy)
  891. );
  892. return $this;
  893. }
  894. /**
  895. * Sets a value for a column in an insert query.
  896. *
  897. * <code>
  898. * $qb = $conn->getQueryBuilder()
  899. * ->insert('users')
  900. * ->values(
  901. * array(
  902. * 'name' => '?'
  903. * )
  904. * )
  905. * ->setValue('password', '?');
  906. * </code>
  907. *
  908. * @param string $column The column into which the value should be inserted.
  909. * @param IParameter|string $value The value that should be inserted into the column.
  910. *
  911. * @return $this This QueryBuilder instance.
  912. */
  913. public function setValue($column, $value) {
  914. $this->queryBuilder->setValue(
  915. $this->helper->quoteColumnName($column),
  916. (string) $value
  917. );
  918. return $this;
  919. }
  920. /**
  921. * Specifies values for an insert query indexed by column names.
  922. * Replaces any previous values, if any.
  923. *
  924. * <code>
  925. * $qb = $conn->getQueryBuilder()
  926. * ->insert('users')
  927. * ->values(
  928. * array(
  929. * 'name' => '?',
  930. * 'password' => '?'
  931. * )
  932. * );
  933. * </code>
  934. *
  935. * @param array $values The values to specify for the insert query indexed by column names.
  936. *
  937. * @return $this This QueryBuilder instance.
  938. */
  939. public function values(array $values) {
  940. $quotedValues = [];
  941. foreach ($values as $key => $value) {
  942. $quotedValues[$this->helper->quoteColumnName($key)] = $value;
  943. }
  944. $this->queryBuilder->values($quotedValues);
  945. return $this;
  946. }
  947. /**
  948. * Specifies a restriction over the groups of the query.
  949. * Replaces any previous having restrictions, if any.
  950. *
  951. * @param mixed ...$having The restriction over the groups.
  952. *
  953. * @return $this This QueryBuilder instance.
  954. */
  955. public function having(...$having) {
  956. call_user_func_array(
  957. [$this->queryBuilder, 'having'],
  958. $having
  959. );
  960. return $this;
  961. }
  962. /**
  963. * Adds a restriction over the groups of the query, forming a logical
  964. * conjunction with any existing having restrictions.
  965. *
  966. * @param mixed ...$having The restriction to append.
  967. *
  968. * @return $this This QueryBuilder instance.
  969. */
  970. public function andHaving(...$having) {
  971. call_user_func_array(
  972. [$this->queryBuilder, 'andHaving'],
  973. $having
  974. );
  975. return $this;
  976. }
  977. /**
  978. * Adds a restriction over the groups of the query, forming a logical
  979. * disjunction with any existing having restrictions.
  980. *
  981. * @param mixed ...$having The restriction to add.
  982. *
  983. * @return $this This QueryBuilder instance.
  984. */
  985. public function orHaving(...$having) {
  986. call_user_func_array(
  987. [$this->queryBuilder, 'orHaving'],
  988. $having
  989. );
  990. return $this;
  991. }
  992. /**
  993. * Specifies an ordering for the query results.
  994. * Replaces any previously specified orderings, if any.
  995. *
  996. * @param string|IQueryFunction|ILiteral|IParameter $sort The ordering expression.
  997. * @param string $order The ordering direction.
  998. *
  999. * @return $this This QueryBuilder instance.
  1000. */
  1001. public function orderBy($sort, $order = null) {
  1002. $this->queryBuilder->orderBy(
  1003. $this->helper->quoteColumnName($sort),
  1004. $order
  1005. );
  1006. return $this;
  1007. }
  1008. /**
  1009. * Adds an ordering to the query results.
  1010. *
  1011. * @param string|ILiteral|IParameter|IQueryFunction $sort The ordering expression.
  1012. * @param string $order The ordering direction.
  1013. *
  1014. * @return $this This QueryBuilder instance.
  1015. */
  1016. public function addOrderBy($sort, $order = null) {
  1017. $this->queryBuilder->addOrderBy(
  1018. $this->helper->quoteColumnName($sort),
  1019. $order
  1020. );
  1021. return $this;
  1022. }
  1023. /**
  1024. * Gets a query part by its name.
  1025. *
  1026. * @param string $queryPartName
  1027. *
  1028. * @return mixed
  1029. */
  1030. public function getQueryPart($queryPartName) {
  1031. return $this->queryBuilder->getQueryPart($queryPartName);
  1032. }
  1033. /**
  1034. * Gets all query parts.
  1035. *
  1036. * @return array
  1037. */
  1038. public function getQueryParts() {
  1039. return $this->queryBuilder->getQueryParts();
  1040. }
  1041. /**
  1042. * Resets SQL parts.
  1043. *
  1044. * @param array|null $queryPartNames
  1045. *
  1046. * @return $this This QueryBuilder instance.
  1047. */
  1048. public function resetQueryParts($queryPartNames = null) {
  1049. $this->queryBuilder->resetQueryParts($queryPartNames);
  1050. return $this;
  1051. }
  1052. /**
  1053. * Resets a single SQL part.
  1054. *
  1055. * @param string $queryPartName
  1056. *
  1057. * @return $this This QueryBuilder instance.
  1058. */
  1059. public function resetQueryPart($queryPartName) {
  1060. $this->queryBuilder->resetQueryPart($queryPartName);
  1061. return $this;
  1062. }
  1063. /**
  1064. * Creates a new named parameter and bind the value $value to it.
  1065. *
  1066. * This method provides a shortcut for PDOStatement::bindValue
  1067. * when using prepared statements.
  1068. *
  1069. * The parameter $value specifies the value that you want to bind. If
  1070. * $placeholder is not provided bindValue() will automatically create a
  1071. * placeholder for you. An automatic placeholder will be of the name
  1072. * ':dcValue1', ':dcValue2' etc.
  1073. *
  1074. * For more information see {@link https://www.php.net/pdostatement-bindparam}
  1075. *
  1076. * Example:
  1077. * <code>
  1078. * $value = 2;
  1079. * $q->eq( 'id', $q->bindValue( $value ) );
  1080. * $stmt = $q->executeQuery(); // executed with 'id = 2'
  1081. * </code>
  1082. *
  1083. * @license New BSD License
  1084. * @link http://www.zetacomponents.org
  1085. *
  1086. * @param mixed $value
  1087. * @param IQueryBuilder::PARAM_* $type
  1088. * @param string $placeHolder The name to bind with. The string must start with a colon ':'.
  1089. *
  1090. * @return IParameter the placeholder name used.
  1091. */
  1092. public function createNamedParameter($value, $type = IQueryBuilder::PARAM_STR, $placeHolder = null) {
  1093. return new Parameter($this->queryBuilder->createNamedParameter($value, $type, $placeHolder));
  1094. }
  1095. /**
  1096. * Creates a new positional parameter and bind the given value to it.
  1097. *
  1098. * Attention: If you are using positional parameters with the query builder you have
  1099. * to be very careful to bind all parameters in the order they appear in the SQL
  1100. * statement , otherwise they get bound in the wrong order which can lead to serious
  1101. * bugs in your code.
  1102. *
  1103. * Example:
  1104. * <code>
  1105. * $qb = $conn->getQueryBuilder();
  1106. * $qb->select('u.*')
  1107. * ->from('users', 'u')
  1108. * ->where('u.username = ' . $qb->createPositionalParameter('Foo', IQueryBuilder::PARAM_STR))
  1109. * ->orWhere('u.username = ' . $qb->createPositionalParameter('Bar', IQueryBuilder::PARAM_STR))
  1110. * </code>
  1111. *
  1112. * @param mixed $value
  1113. * @param IQueryBuilder::PARAM_* $type
  1114. *
  1115. * @return IParameter
  1116. */
  1117. public function createPositionalParameter($value, $type = IQueryBuilder::PARAM_STR) {
  1118. return new Parameter($this->queryBuilder->createPositionalParameter($value, $type));
  1119. }
  1120. /**
  1121. * Creates a new parameter
  1122. *
  1123. * Example:
  1124. * <code>
  1125. * $qb = $conn->getQueryBuilder();
  1126. * $qb->select('u.*')
  1127. * ->from('users', 'u')
  1128. * ->where('u.username = ' . $qb->createParameter('name'))
  1129. * ->setParameter('name', 'Bar', IQueryBuilder::PARAM_STR))
  1130. * </code>
  1131. *
  1132. * @param string $name
  1133. *
  1134. * @return IParameter
  1135. */
  1136. public function createParameter($name) {
  1137. return new Parameter(':' . $name);
  1138. }
  1139. /**
  1140. * Creates a new function
  1141. *
  1142. * Attention: Column names inside the call have to be quoted before hand
  1143. *
  1144. * Example:
  1145. * <code>
  1146. * $qb = $conn->getQueryBuilder();
  1147. * $qb->select($qb->createFunction('COUNT(*)'))
  1148. * ->from('users', 'u')
  1149. * echo $qb->getSQL(); // SELECT COUNT(*) FROM `users` u
  1150. * </code>
  1151. * <code>
  1152. * $qb = $conn->getQueryBuilder();
  1153. * $qb->select($qb->createFunction('COUNT(`column`)'))
  1154. * ->from('users', 'u')
  1155. * echo $qb->getSQL(); // SELECT COUNT(`column`) FROM `users` u
  1156. * </code>
  1157. *
  1158. * @param string $call
  1159. *
  1160. * @return IQueryFunction
  1161. */
  1162. public function createFunction($call) {
  1163. return new QueryFunction($call);
  1164. }
  1165. /**
  1166. * Used to get the id of the last inserted element
  1167. * @return int
  1168. * @throws \BadMethodCallException When being called before an insert query has been run.
  1169. */
  1170. public function getLastInsertId(): int {
  1171. if ($this->getType() === \Doctrine\DBAL\Query\QueryBuilder::INSERT && $this->lastInsertedTable) {
  1172. // lastInsertId() needs the prefix but no quotes
  1173. $table = $this->prefixTableName($this->lastInsertedTable);
  1174. return $this->connection->lastInsertId($table);
  1175. }
  1176. throw new \BadMethodCallException('Invalid call to getLastInsertId without using insert() before.');
  1177. }
  1178. /**
  1179. * Returns the table name quoted and with database prefix as needed by the implementation
  1180. *
  1181. * @param string|IQueryFunction $table
  1182. * @return string
  1183. */
  1184. public function getTableName($table) {
  1185. if ($table instanceof IQueryFunction) {
  1186. return (string) $table;
  1187. }
  1188. $table = $this->prefixTableName($table);
  1189. return $this->helper->quoteColumnName($table);
  1190. }
  1191. /**
  1192. * Returns the table name with database prefix as needed by the implementation
  1193. *
  1194. * @param string $table
  1195. * @return string
  1196. */
  1197. protected function prefixTableName($table) {
  1198. if ($this->automaticTablePrefix === false || str_starts_with($table, '*PREFIX*')) {
  1199. return $table;
  1200. }
  1201. return '*PREFIX*' . $table;
  1202. }
  1203. /**
  1204. * Returns the column name quoted and with table alias prefix as needed by the implementation
  1205. *
  1206. * @param string $column
  1207. * @param string $tableAlias
  1208. * @return string
  1209. */
  1210. public function getColumnName($column, $tableAlias = '') {
  1211. if ($tableAlias !== '') {
  1212. $tableAlias .= '.';
  1213. }
  1214. return $this->helper->quoteColumnName($tableAlias . $column);
  1215. }
  1216. /**
  1217. * Returns the column name quoted and with table alias prefix as needed by the implementation
  1218. *
  1219. * @param string $alias
  1220. * @return string
  1221. */
  1222. public function quoteAlias($alias) {
  1223. if ($alias === '' || $alias === null) {
  1224. return $alias;
  1225. }
  1226. return $this->helper->quoteColumnName($alias);
  1227. }
  1228. }