QueryBuilder.php 38 KB

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