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 36KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340
  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. public function executeStatement(): int {
  277. if ($this->getType() === \Doctrine\DBAL\Query\QueryBuilder::SELECT) {
  278. throw new \RuntimeException('Invalid query type, expected INSERT, DELETE or UPDATE statement');
  279. }
  280. try {
  281. $result = $this->execute();
  282. } catch (\Doctrine\DBAL\Exception $e) {
  283. throw \OC\DB\Exceptions\DbalException::wrap($e);
  284. }
  285. if (!is_int($result)) {
  286. throw new \RuntimeException('Invalid return type for statement');
  287. }
  288. return $result;
  289. }
  290. /**
  291. * Gets the complete SQL string formed by the current specifications of this QueryBuilder.
  292. *
  293. * <code>
  294. * $qb = $conn->getQueryBuilder()
  295. * ->select('u')
  296. * ->from('User', 'u')
  297. * echo $qb->getSQL(); // SELECT u FROM User u
  298. * </code>
  299. *
  300. * @return string The SQL query string.
  301. */
  302. public function getSQL() {
  303. return $this->queryBuilder->getSQL();
  304. }
  305. /**
  306. * Sets a query parameter for the query being constructed.
  307. *
  308. * <code>
  309. * $qb = $conn->getQueryBuilder()
  310. * ->select('u')
  311. * ->from('users', 'u')
  312. * ->where('u.id = :user_id')
  313. * ->setParameter(':user_id', 1);
  314. * </code>
  315. *
  316. * @param string|integer $key The parameter position or name.
  317. * @param mixed $value The parameter value.
  318. * @param string|null|int $type One of the IQueryBuilder::PARAM_* constants.
  319. *
  320. * @return $this This QueryBuilder instance.
  321. */
  322. public function setParameter($key, $value, $type = null) {
  323. $this->queryBuilder->setParameter($key, $value, $type);
  324. return $this;
  325. }
  326. /**
  327. * Sets a collection of query parameters for the query being constructed.
  328. *
  329. * <code>
  330. * $qb = $conn->getQueryBuilder()
  331. * ->select('u')
  332. * ->from('users', 'u')
  333. * ->where('u.id = :user_id1 OR u.id = :user_id2')
  334. * ->setParameters(array(
  335. * ':user_id1' => 1,
  336. * ':user_id2' => 2
  337. * ));
  338. * </code>
  339. *
  340. * @param array $params The query parameters to set.
  341. * @param array $types The query parameters types to set.
  342. *
  343. * @return $this This QueryBuilder instance.
  344. */
  345. public function setParameters(array $params, array $types = []) {
  346. $this->queryBuilder->setParameters($params, $types);
  347. return $this;
  348. }
  349. /**
  350. * Gets all defined query parameters for the query being constructed indexed by parameter index or name.
  351. *
  352. * @return array The currently defined query parameters indexed by parameter index or name.
  353. */
  354. public function getParameters() {
  355. return $this->queryBuilder->getParameters();
  356. }
  357. /**
  358. * Gets a (previously set) query parameter of the query being constructed.
  359. *
  360. * @param mixed $key The key (index or name) of the bound parameter.
  361. *
  362. * @return mixed The value of the bound parameter.
  363. */
  364. public function getParameter($key) {
  365. return $this->queryBuilder->getParameter($key);
  366. }
  367. /**
  368. * Gets all defined query parameter types for the query being constructed indexed by parameter index or name.
  369. *
  370. * @return array The currently defined query parameter types indexed by parameter index or name.
  371. */
  372. public function getParameterTypes() {
  373. return $this->queryBuilder->getParameterTypes();
  374. }
  375. /**
  376. * Gets a (previously set) query parameter type of the query being constructed.
  377. *
  378. * @param mixed $key The key (index or name) of the bound parameter type.
  379. *
  380. * @return mixed The value of the bound parameter type.
  381. */
  382. public function getParameterType($key) {
  383. return $this->queryBuilder->getParameterType($key);
  384. }
  385. /**
  386. * Sets the position of the first result to retrieve (the "offset").
  387. *
  388. * @param int $firstResult The first result to return.
  389. *
  390. * @return $this This QueryBuilder instance.
  391. */
  392. public function setFirstResult($firstResult) {
  393. $this->queryBuilder->setFirstResult((int) $firstResult);
  394. return $this;
  395. }
  396. /**
  397. * Gets the position of the first result the query object was set to retrieve (the "offset").
  398. * Returns 0 if {@link setFirstResult} was not applied to this QueryBuilder.
  399. *
  400. * @return int The position of the first result.
  401. */
  402. public function getFirstResult() {
  403. return $this->queryBuilder->getFirstResult();
  404. }
  405. /**
  406. * Sets the maximum number of results to retrieve (the "limit").
  407. *
  408. * NOTE: Setting max results to "0" will cause mixed behaviour. While most
  409. * of the databases will just return an empty result set, Oracle will return
  410. * all entries.
  411. *
  412. * @param int|null $maxResults The maximum number of results to retrieve.
  413. *
  414. * @return $this This QueryBuilder instance.
  415. */
  416. public function setMaxResults($maxResults) {
  417. if ($maxResults === null) {
  418. $this->queryBuilder->setMaxResults($maxResults);
  419. } else {
  420. $this->queryBuilder->setMaxResults((int) $maxResults);
  421. }
  422. return $this;
  423. }
  424. /**
  425. * Gets the maximum number of results the query object was set to retrieve (the "limit").
  426. * Returns NULL if {@link setMaxResults} was not applied to this query builder.
  427. *
  428. * @return int|null The maximum number of results.
  429. */
  430. public function getMaxResults() {
  431. return $this->queryBuilder->getMaxResults();
  432. }
  433. /**
  434. * Specifies an item that is to be returned in the query result.
  435. * Replaces any previously specified selections, if any.
  436. *
  437. * <code>
  438. * $qb = $conn->getQueryBuilder()
  439. * ->select('u.id', 'p.id')
  440. * ->from('users', 'u')
  441. * ->leftJoin('u', 'phonenumbers', 'p', 'u.id = p.user_id');
  442. * </code>
  443. *
  444. * @param mixed ...$selects The selection expressions.
  445. *
  446. * '@return $this This QueryBuilder instance.
  447. */
  448. public function select(...$selects) {
  449. if (count($selects) === 1 && is_array($selects[0])) {
  450. $selects = $selects[0];
  451. }
  452. $this->queryBuilder->select(
  453. $this->helper->quoteColumnNames($selects)
  454. );
  455. return $this;
  456. }
  457. /**
  458. * Specifies an item that is to be returned with a different name in the query result.
  459. *
  460. * <code>
  461. * $qb = $conn->getQueryBuilder()
  462. * ->selectAlias('u.id', 'user_id')
  463. * ->from('users', 'u')
  464. * ->leftJoin('u', 'phonenumbers', 'p', 'u.id = p.user_id');
  465. * </code>
  466. *
  467. * @param mixed $select The selection expressions.
  468. * @param string $alias The column alias used in the constructed query.
  469. *
  470. * @return $this This QueryBuilder instance.
  471. */
  472. public function selectAlias($select, $alias) {
  473. $this->queryBuilder->addSelect(
  474. $this->helper->quoteColumnName($select) . ' AS ' . $this->helper->quoteColumnName($alias)
  475. );
  476. return $this;
  477. }
  478. /**
  479. * Specifies an item that is to be returned uniquely in the query result.
  480. *
  481. * <code>
  482. * $qb = $conn->getQueryBuilder()
  483. * ->selectDistinct('type')
  484. * ->from('users');
  485. * </code>
  486. *
  487. * @param mixed $select The selection expressions.
  488. *
  489. * @return $this This QueryBuilder instance.
  490. */
  491. public function selectDistinct($select) {
  492. if (!is_array($select)) {
  493. $select = [$select];
  494. }
  495. $quotedSelect = $this->helper->quoteColumnNames($select);
  496. $this->queryBuilder->addSelect(
  497. 'DISTINCT ' . implode(', ', $quotedSelect)
  498. );
  499. return $this;
  500. }
  501. /**
  502. * Adds an item that is to be returned in the query result.
  503. *
  504. * <code>
  505. * $qb = $conn->getQueryBuilder()
  506. * ->select('u.id')
  507. * ->addSelect('p.id')
  508. * ->from('users', 'u')
  509. * ->leftJoin('u', 'phonenumbers', 'u.id = p.user_id');
  510. * </code>
  511. *
  512. * @param mixed ...$selects The selection expression.
  513. *
  514. * @return $this This QueryBuilder instance.
  515. */
  516. public function addSelect(...$selects) {
  517. if (count($selects) === 1 && is_array($selects[0])) {
  518. $selects = $selects[0];
  519. }
  520. $this->queryBuilder->addSelect(
  521. $this->helper->quoteColumnNames($selects)
  522. );
  523. return $this;
  524. }
  525. /**
  526. * Turns the query being built into a bulk delete query that ranges over
  527. * a certain table.
  528. *
  529. * <code>
  530. * $qb = $conn->getQueryBuilder()
  531. * ->delete('users', 'u')
  532. * ->where('u.id = :user_id');
  533. * ->setParameter(':user_id', 1);
  534. * </code>
  535. *
  536. * @param string $delete The table whose rows are subject to the deletion.
  537. * @param string $alias The table alias used in the constructed query.
  538. *
  539. * @return $this This QueryBuilder instance.
  540. */
  541. public function delete($delete = null, $alias = null) {
  542. $this->queryBuilder->delete(
  543. $this->getTableName($delete),
  544. $alias
  545. );
  546. return $this;
  547. }
  548. /**
  549. * Turns the query being built into a bulk update query that ranges over
  550. * a certain table
  551. *
  552. * <code>
  553. * $qb = $conn->getQueryBuilder()
  554. * ->update('users', 'u')
  555. * ->set('u.password', md5('password'))
  556. * ->where('u.id = ?');
  557. * </code>
  558. *
  559. * @param string $update The table whose rows are subject to the update.
  560. * @param string $alias The table alias used in the constructed query.
  561. *
  562. * @return $this This QueryBuilder instance.
  563. */
  564. public function update($update = null, $alias = null) {
  565. $this->queryBuilder->update(
  566. $this->getTableName($update),
  567. $alias
  568. );
  569. return $this;
  570. }
  571. /**
  572. * Turns the query being built into an insert query that inserts into
  573. * a certain table
  574. *
  575. * <code>
  576. * $qb = $conn->getQueryBuilder()
  577. * ->insert('users')
  578. * ->values(
  579. * array(
  580. * 'name' => '?',
  581. * 'password' => '?'
  582. * )
  583. * );
  584. * </code>
  585. *
  586. * @param string $insert The table into which the rows should be inserted.
  587. *
  588. * @return $this This QueryBuilder instance.
  589. */
  590. public function insert($insert = null) {
  591. $this->queryBuilder->insert(
  592. $this->getTableName($insert)
  593. );
  594. $this->lastInsertedTable = $insert;
  595. return $this;
  596. }
  597. /**
  598. * Creates and adds a query root corresponding to the table identified by the
  599. * given alias, forming a cartesian product with any existing query roots.
  600. *
  601. * <code>
  602. * $qb = $conn->getQueryBuilder()
  603. * ->select('u.id')
  604. * ->from('users', 'u')
  605. * </code>
  606. *
  607. * @param string|IQueryFunction $from The table.
  608. * @param string|null $alias The alias of the table.
  609. *
  610. * @return $this This QueryBuilder instance.
  611. */
  612. public function from($from, $alias = null) {
  613. $this->queryBuilder->from(
  614. $this->getTableName($from),
  615. $this->quoteAlias($alias)
  616. );
  617. return $this;
  618. }
  619. /**
  620. * Creates and adds a join to the query.
  621. *
  622. * <code>
  623. * $qb = $conn->getQueryBuilder()
  624. * ->select('u.name')
  625. * ->from('users', 'u')
  626. * ->join('u', 'phonenumbers', 'p', 'p.is_primary = 1');
  627. * </code>
  628. *
  629. * @param string $fromAlias The alias that points to a from clause.
  630. * @param string $join The table name to join.
  631. * @param string $alias The alias of the join table.
  632. * @param string|ICompositeExpression|null $condition The condition for the join.
  633. *
  634. * @return $this This QueryBuilder instance.
  635. */
  636. public function join($fromAlias, $join, $alias, $condition = null) {
  637. $this->queryBuilder->join(
  638. $this->quoteAlias($fromAlias),
  639. $this->getTableName($join),
  640. $this->quoteAlias($alias),
  641. $condition
  642. );
  643. return $this;
  644. }
  645. /**
  646. * Creates and adds a join to the query.
  647. *
  648. * <code>
  649. * $qb = $conn->getQueryBuilder()
  650. * ->select('u.name')
  651. * ->from('users', 'u')
  652. * ->innerJoin('u', 'phonenumbers', 'p', 'p.is_primary = 1');
  653. * </code>
  654. *
  655. * @param string $fromAlias The alias that points to a from clause.
  656. * @param string $join The table name to join.
  657. * @param string $alias The alias of the join table.
  658. * @param string|ICompositeExpression|null $condition The condition for the join.
  659. *
  660. * @return $this This QueryBuilder instance.
  661. */
  662. public function innerJoin($fromAlias, $join, $alias, $condition = null) {
  663. $this->queryBuilder->innerJoin(
  664. $this->quoteAlias($fromAlias),
  665. $this->getTableName($join),
  666. $this->quoteAlias($alias),
  667. $condition
  668. );
  669. return $this;
  670. }
  671. /**
  672. * Creates and adds a left join to the query.
  673. *
  674. * <code>
  675. * $qb = $conn->getQueryBuilder()
  676. * ->select('u.name')
  677. * ->from('users', 'u')
  678. * ->leftJoin('u', 'phonenumbers', 'p', 'p.is_primary = 1');
  679. * </code>
  680. *
  681. * @param string $fromAlias The alias that points to a from clause.
  682. * @param string $join The table name to join.
  683. * @param string $alias The alias of the join table.
  684. * @param string|ICompositeExpression|null $condition The condition for the join.
  685. *
  686. * @return $this This QueryBuilder instance.
  687. */
  688. public function leftJoin($fromAlias, $join, $alias, $condition = null) {
  689. $this->queryBuilder->leftJoin(
  690. $this->quoteAlias($fromAlias),
  691. $this->getTableName($join),
  692. $this->quoteAlias($alias),
  693. $condition
  694. );
  695. return $this;
  696. }
  697. /**
  698. * Creates and adds a right join to the query.
  699. *
  700. * <code>
  701. * $qb = $conn->getQueryBuilder()
  702. * ->select('u.name')
  703. * ->from('users', 'u')
  704. * ->rightJoin('u', 'phonenumbers', 'p', 'p.is_primary = 1');
  705. * </code>
  706. *
  707. * @param string $fromAlias The alias that points to a from clause.
  708. * @param string $join The table name to join.
  709. * @param string $alias The alias of the join table.
  710. * @param string|ICompositeExpression|null $condition The condition for the join.
  711. *
  712. * @return $this This QueryBuilder instance.
  713. */
  714. public function rightJoin($fromAlias, $join, $alias, $condition = null) {
  715. $this->queryBuilder->rightJoin(
  716. $this->quoteAlias($fromAlias),
  717. $this->getTableName($join),
  718. $this->quoteAlias($alias),
  719. $condition
  720. );
  721. return $this;
  722. }
  723. /**
  724. * Sets a new value for a column in a bulk update query.
  725. *
  726. * <code>
  727. * $qb = $conn->getQueryBuilder()
  728. * ->update('users', 'u')
  729. * ->set('u.password', md5('password'))
  730. * ->where('u.id = ?');
  731. * </code>
  732. *
  733. * @param string $key The column to set.
  734. * @param ILiteral|IParameter|IQueryFunction|string $value The value, expression, placeholder, etc.
  735. *
  736. * @return $this This QueryBuilder instance.
  737. */
  738. public function set($key, $value) {
  739. $this->queryBuilder->set(
  740. $this->helper->quoteColumnName($key),
  741. $this->helper->quoteColumnName($value)
  742. );
  743. return $this;
  744. }
  745. /**
  746. * Specifies one or more restrictions to the query result.
  747. * Replaces any previously specified restrictions, if any.
  748. *
  749. * <code>
  750. * $qb = $conn->getQueryBuilder()
  751. * ->select('u.name')
  752. * ->from('users', 'u')
  753. * ->where('u.id = ?');
  754. *
  755. * // You can optionally programmatically build and/or expressions
  756. * $qb = $conn->getQueryBuilder();
  757. *
  758. * $or = $qb->expr()->orx();
  759. * $or->add($qb->expr()->eq('u.id', 1));
  760. * $or->add($qb->expr()->eq('u.id', 2));
  761. *
  762. * $qb->update('users', 'u')
  763. * ->set('u.password', md5('password'))
  764. * ->where($or);
  765. * </code>
  766. *
  767. * @param mixed ...$predicates The restriction predicates.
  768. *
  769. * @return $this This QueryBuilder instance.
  770. */
  771. public function where(...$predicates) {
  772. if ($this->getQueryPart('where') !== null && $this->systemConfig->getValue('debug', false)) {
  773. // Only logging a warning, not throwing for now.
  774. $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.');
  775. $this->logger->warning($e->getMessage(), ['exception' => $e]);
  776. }
  777. call_user_func_array(
  778. [$this->queryBuilder, 'where'],
  779. $predicates
  780. );
  781. return $this;
  782. }
  783. /**
  784. * Adds one or more restrictions to the query results, forming a logical
  785. * conjunction with any previously specified restrictions.
  786. *
  787. * <code>
  788. * $qb = $conn->getQueryBuilder()
  789. * ->select('u')
  790. * ->from('users', 'u')
  791. * ->where('u.username LIKE ?')
  792. * ->andWhere('u.is_active = 1');
  793. * </code>
  794. *
  795. * @param mixed ...$where The query restrictions.
  796. *
  797. * @return $this This QueryBuilder instance.
  798. *
  799. * @see where()
  800. */
  801. public function andWhere(...$where) {
  802. call_user_func_array(
  803. [$this->queryBuilder, 'andWhere'],
  804. $where
  805. );
  806. return $this;
  807. }
  808. /**
  809. * Adds one or more restrictions to the query results, forming a logical
  810. * disjunction with any previously specified restrictions.
  811. *
  812. * <code>
  813. * $qb = $conn->getQueryBuilder()
  814. * ->select('u.name')
  815. * ->from('users', 'u')
  816. * ->where('u.id = 1')
  817. * ->orWhere('u.id = 2');
  818. * </code>
  819. *
  820. * @param mixed ...$where The WHERE statement.
  821. *
  822. * @return $this This QueryBuilder instance.
  823. *
  824. * @see where()
  825. */
  826. public function orWhere(...$where) {
  827. call_user_func_array(
  828. [$this->queryBuilder, 'orWhere'],
  829. $where
  830. );
  831. return $this;
  832. }
  833. /**
  834. * Specifies a grouping over the results of the query.
  835. * Replaces any previously specified groupings, if any.
  836. *
  837. * <code>
  838. * $qb = $conn->getQueryBuilder()
  839. * ->select('u.name')
  840. * ->from('users', 'u')
  841. * ->groupBy('u.id');
  842. * </code>
  843. *
  844. * @param mixed ...$groupBys The grouping expression.
  845. *
  846. * @return $this This QueryBuilder instance.
  847. */
  848. public function groupBy(...$groupBys) {
  849. if (count($groupBys) === 1 && is_array($groupBys[0])) {
  850. $groupBys = $groupBys[0];
  851. }
  852. call_user_func_array(
  853. [$this->queryBuilder, 'groupBy'],
  854. $this->helper->quoteColumnNames($groupBys)
  855. );
  856. return $this;
  857. }
  858. /**
  859. * Adds a grouping expression to the query.
  860. *
  861. * <code>
  862. * $qb = $conn->getQueryBuilder()
  863. * ->select('u.name')
  864. * ->from('users', 'u')
  865. * ->groupBy('u.lastLogin');
  866. * ->addGroupBy('u.createdAt')
  867. * </code>
  868. *
  869. * @param mixed ...$groupBy The grouping expression.
  870. *
  871. * @return $this This QueryBuilder instance.
  872. */
  873. public function addGroupBy(...$groupBy) {
  874. call_user_func_array(
  875. [$this->queryBuilder, 'addGroupBy'],
  876. $this->helper->quoteColumnNames($groupBy)
  877. );
  878. return $this;
  879. }
  880. /**
  881. * Sets a value for a column in an insert query.
  882. *
  883. * <code>
  884. * $qb = $conn->getQueryBuilder()
  885. * ->insert('users')
  886. * ->values(
  887. * array(
  888. * 'name' => '?'
  889. * )
  890. * )
  891. * ->setValue('password', '?');
  892. * </code>
  893. *
  894. * @param string $column The column into which the value should be inserted.
  895. * @param IParameter|string $value The value that should be inserted into the column.
  896. *
  897. * @return $this This QueryBuilder instance.
  898. */
  899. public function setValue($column, $value) {
  900. $this->queryBuilder->setValue(
  901. $this->helper->quoteColumnName($column),
  902. (string) $value
  903. );
  904. return $this;
  905. }
  906. /**
  907. * Specifies values for an insert query indexed by column names.
  908. * Replaces any previous values, if any.
  909. *
  910. * <code>
  911. * $qb = $conn->getQueryBuilder()
  912. * ->insert('users')
  913. * ->values(
  914. * array(
  915. * 'name' => '?',
  916. * 'password' => '?'
  917. * )
  918. * );
  919. * </code>
  920. *
  921. * @param array $values The values to specify for the insert query indexed by column names.
  922. *
  923. * @return $this This QueryBuilder instance.
  924. */
  925. public function values(array $values) {
  926. $quotedValues = [];
  927. foreach ($values as $key => $value) {
  928. $quotedValues[$this->helper->quoteColumnName($key)] = $value;
  929. }
  930. $this->queryBuilder->values($quotedValues);
  931. return $this;
  932. }
  933. /**
  934. * Specifies a restriction over the groups of the query.
  935. * Replaces any previous having restrictions, if any.
  936. *
  937. * @param mixed ...$having The restriction over the groups.
  938. *
  939. * @return $this This QueryBuilder instance.
  940. */
  941. public function having(...$having) {
  942. call_user_func_array(
  943. [$this->queryBuilder, 'having'],
  944. $having
  945. );
  946. return $this;
  947. }
  948. /**
  949. * Adds a restriction over the groups of the query, forming a logical
  950. * conjunction with any existing having restrictions.
  951. *
  952. * @param mixed ...$having The restriction to append.
  953. *
  954. * @return $this This QueryBuilder instance.
  955. */
  956. public function andHaving(...$having) {
  957. call_user_func_array(
  958. [$this->queryBuilder, 'andHaving'],
  959. $having
  960. );
  961. return $this;
  962. }
  963. /**
  964. * Adds a restriction over the groups of the query, forming a logical
  965. * disjunction with any existing having restrictions.
  966. *
  967. * @param mixed ...$having The restriction to add.
  968. *
  969. * @return $this This QueryBuilder instance.
  970. */
  971. public function orHaving(...$having) {
  972. call_user_func_array(
  973. [$this->queryBuilder, 'orHaving'],
  974. $having
  975. );
  976. return $this;
  977. }
  978. /**
  979. * Specifies an ordering for the query results.
  980. * Replaces any previously specified orderings, if any.
  981. *
  982. * @param string|IQueryFunction|ILiteral|IParameter $sort The ordering expression.
  983. * @param string $order The ordering direction.
  984. *
  985. * @return $this This QueryBuilder instance.
  986. */
  987. public function orderBy($sort, $order = null) {
  988. $this->queryBuilder->orderBy(
  989. $this->helper->quoteColumnName($sort),
  990. $order
  991. );
  992. return $this;
  993. }
  994. /**
  995. * Adds an ordering to the query results.
  996. *
  997. * @param string|ILiteral|IParameter|IQueryFunction $sort The ordering expression.
  998. * @param string $order The ordering direction.
  999. *
  1000. * @return $this This QueryBuilder instance.
  1001. */
  1002. public function addOrderBy($sort, $order = null) {
  1003. $this->queryBuilder->addOrderBy(
  1004. $this->helper->quoteColumnName($sort),
  1005. $order
  1006. );
  1007. return $this;
  1008. }
  1009. /**
  1010. * Gets a query part by its name.
  1011. *
  1012. * @param string $queryPartName
  1013. *
  1014. * @return mixed
  1015. */
  1016. public function getQueryPart($queryPartName) {
  1017. return $this->queryBuilder->getQueryPart($queryPartName);
  1018. }
  1019. /**
  1020. * Gets all query parts.
  1021. *
  1022. * @return array
  1023. */
  1024. public function getQueryParts() {
  1025. return $this->queryBuilder->getQueryParts();
  1026. }
  1027. /**
  1028. * Resets SQL parts.
  1029. *
  1030. * @param array|null $queryPartNames
  1031. *
  1032. * @return $this This QueryBuilder instance.
  1033. */
  1034. public function resetQueryParts($queryPartNames = null) {
  1035. $this->queryBuilder->resetQueryParts($queryPartNames);
  1036. return $this;
  1037. }
  1038. /**
  1039. * Resets a single SQL part.
  1040. *
  1041. * @param string $queryPartName
  1042. *
  1043. * @return $this This QueryBuilder instance.
  1044. */
  1045. public function resetQueryPart($queryPartName) {
  1046. $this->queryBuilder->resetQueryPart($queryPartName);
  1047. return $this;
  1048. }
  1049. /**
  1050. * Creates a new named parameter and bind the value $value to it.
  1051. *
  1052. * This method provides a shortcut for PDOStatement::bindValue
  1053. * when using prepared statements.
  1054. *
  1055. * The parameter $value specifies the value that you want to bind. If
  1056. * $placeholder is not provided bindValue() will automatically create a
  1057. * placeholder for you. An automatic placeholder will be of the name
  1058. * ':dcValue1', ':dcValue2' etc.
  1059. *
  1060. * For more information see {@link https://www.php.net/pdostatement-bindparam}
  1061. *
  1062. * Example:
  1063. * <code>
  1064. * $value = 2;
  1065. * $q->eq( 'id', $q->bindValue( $value ) );
  1066. * $stmt = $q->executeQuery(); // executed with 'id = 2'
  1067. * </code>
  1068. *
  1069. * @license New BSD License
  1070. * @link http://www.zetacomponents.org
  1071. *
  1072. * @param mixed $value
  1073. * @param IQueryBuilder::PARAM_* $type
  1074. * @param string $placeHolder The name to bind with. The string must start with a colon ':'.
  1075. *
  1076. * @return IParameter the placeholder name used.
  1077. */
  1078. public function createNamedParameter($value, $type = IQueryBuilder::PARAM_STR, $placeHolder = null) {
  1079. return new Parameter($this->queryBuilder->createNamedParameter($value, $type, $placeHolder));
  1080. }
  1081. /**
  1082. * Creates a new positional parameter and bind the given value to it.
  1083. *
  1084. * Attention: If you are using positional parameters with the query builder you have
  1085. * to be very careful to bind all parameters in the order they appear in the SQL
  1086. * statement , otherwise they get bound in the wrong order which can lead to serious
  1087. * bugs in your code.
  1088. *
  1089. * Example:
  1090. * <code>
  1091. * $qb = $conn->getQueryBuilder();
  1092. * $qb->select('u.*')
  1093. * ->from('users', 'u')
  1094. * ->where('u.username = ' . $qb->createPositionalParameter('Foo', IQueryBuilder::PARAM_STR))
  1095. * ->orWhere('u.username = ' . $qb->createPositionalParameter('Bar', IQueryBuilder::PARAM_STR))
  1096. * </code>
  1097. *
  1098. * @param mixed $value
  1099. * @param IQueryBuilder::PARAM_* $type
  1100. *
  1101. * @return IParameter
  1102. */
  1103. public function createPositionalParameter($value, $type = IQueryBuilder::PARAM_STR) {
  1104. return new Parameter($this->queryBuilder->createPositionalParameter($value, $type));
  1105. }
  1106. /**
  1107. * Creates a new parameter
  1108. *
  1109. * Example:
  1110. * <code>
  1111. * $qb = $conn->getQueryBuilder();
  1112. * $qb->select('u.*')
  1113. * ->from('users', 'u')
  1114. * ->where('u.username = ' . $qb->createParameter('name'))
  1115. * ->setParameter('name', 'Bar', IQueryBuilder::PARAM_STR))
  1116. * </code>
  1117. *
  1118. * @param string $name
  1119. *
  1120. * @return IParameter
  1121. */
  1122. public function createParameter($name) {
  1123. return new Parameter(':' . $name);
  1124. }
  1125. /**
  1126. * Creates a new function
  1127. *
  1128. * Attention: Column names inside the call have to be quoted before hand
  1129. *
  1130. * Example:
  1131. * <code>
  1132. * $qb = $conn->getQueryBuilder();
  1133. * $qb->select($qb->createFunction('COUNT(*)'))
  1134. * ->from('users', 'u')
  1135. * echo $qb->getSQL(); // SELECT COUNT(*) FROM `users` u
  1136. * </code>
  1137. * <code>
  1138. * $qb = $conn->getQueryBuilder();
  1139. * $qb->select($qb->createFunction('COUNT(`column`)'))
  1140. * ->from('users', 'u')
  1141. * echo $qb->getSQL(); // SELECT COUNT(`column`) FROM `users` u
  1142. * </code>
  1143. *
  1144. * @param string $call
  1145. *
  1146. * @return IQueryFunction
  1147. */
  1148. public function createFunction($call) {
  1149. return new QueryFunction($call);
  1150. }
  1151. /**
  1152. * Used to get the id of the last inserted element
  1153. * @return int
  1154. * @throws \BadMethodCallException When being called before an insert query has been run.
  1155. */
  1156. public function getLastInsertId(): int {
  1157. if ($this->getType() === \Doctrine\DBAL\Query\QueryBuilder::INSERT && $this->lastInsertedTable) {
  1158. // lastInsertId() needs the prefix but no quotes
  1159. $table = $this->prefixTableName($this->lastInsertedTable);
  1160. return $this->connection->lastInsertId($table);
  1161. }
  1162. throw new \BadMethodCallException('Invalid call to getLastInsertId without using insert() before.');
  1163. }
  1164. /**
  1165. * Returns the table name quoted and with database prefix as needed by the implementation
  1166. *
  1167. * @param string|IQueryFunction $table
  1168. * @return string
  1169. */
  1170. public function getTableName($table) {
  1171. if ($table instanceof IQueryFunction) {
  1172. return (string) $table;
  1173. }
  1174. $table = $this->prefixTableName($table);
  1175. return $this->helper->quoteColumnName($table);
  1176. }
  1177. /**
  1178. * Returns the table name with database prefix as needed by the implementation
  1179. *
  1180. * @param string $table
  1181. * @return string
  1182. */
  1183. protected function prefixTableName($table) {
  1184. if ($this->automaticTablePrefix === false || str_starts_with($table, '*PREFIX*')) {
  1185. return $table;
  1186. }
  1187. return '*PREFIX*' . $table;
  1188. }
  1189. /**
  1190. * Returns the column name quoted and with table alias prefix as needed by the implementation
  1191. *
  1192. * @param string $column
  1193. * @param string $tableAlias
  1194. * @return string
  1195. */
  1196. public function getColumnName($column, $tableAlias = '') {
  1197. if ($tableAlias !== '') {
  1198. $tableAlias .= '.';
  1199. }
  1200. return $this->helper->quoteColumnName($tableAlias . $column);
  1201. }
  1202. /**
  1203. * Returns the column name quoted and with table alias prefix as needed by the implementation
  1204. *
  1205. * @param string $alias
  1206. * @return string
  1207. */
  1208. public function quoteAlias($alias) {
  1209. if ($alias === '' || $alias === null) {
  1210. return $alias;
  1211. }
  1212. return $this->helper->quoteColumnName($alias);
  1213. }
  1214. }