QueryBuilder.php 37 KB

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