QueryBuilder.php 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354
  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. call_user_func_array(
  787. [$this->queryBuilder, 'where'],
  788. $predicates
  789. );
  790. return $this;
  791. }
  792. /**
  793. * Adds one or more restrictions to the query results, forming a logical
  794. * conjunction with any previously specified restrictions.
  795. *
  796. * <code>
  797. * $qb = $conn->getQueryBuilder()
  798. * ->select('u')
  799. * ->from('users', 'u')
  800. * ->where('u.username LIKE ?')
  801. * ->andWhere('u.is_active = 1');
  802. * </code>
  803. *
  804. * @param mixed ...$where The query restrictions.
  805. *
  806. * @return $this This QueryBuilder instance.
  807. *
  808. * @see where()
  809. */
  810. public function andWhere(...$where) {
  811. call_user_func_array(
  812. [$this->queryBuilder, 'andWhere'],
  813. $where
  814. );
  815. return $this;
  816. }
  817. /**
  818. * Adds one or more restrictions to the query results, forming a logical
  819. * disjunction with any previously specified restrictions.
  820. *
  821. * <code>
  822. * $qb = $conn->getQueryBuilder()
  823. * ->select('u.name')
  824. * ->from('users', 'u')
  825. * ->where('u.id = 1')
  826. * ->orWhere('u.id = 2');
  827. * </code>
  828. *
  829. * @param mixed ...$where The WHERE statement.
  830. *
  831. * @return $this This QueryBuilder instance.
  832. *
  833. * @see where()
  834. */
  835. public function orWhere(...$where) {
  836. call_user_func_array(
  837. [$this->queryBuilder, 'orWhere'],
  838. $where
  839. );
  840. return $this;
  841. }
  842. /**
  843. * Specifies a grouping over the results of the query.
  844. * Replaces any previously specified groupings, if any.
  845. *
  846. * <code>
  847. * $qb = $conn->getQueryBuilder()
  848. * ->select('u.name')
  849. * ->from('users', 'u')
  850. * ->groupBy('u.id');
  851. * </code>
  852. *
  853. * @param mixed ...$groupBys The grouping expression.
  854. *
  855. * @return $this This QueryBuilder instance.
  856. */
  857. public function groupBy(...$groupBys) {
  858. if (count($groupBys) === 1 && is_array($groupBys[0])) {
  859. $groupBys = $groupBys[0];
  860. }
  861. call_user_func_array(
  862. [$this->queryBuilder, 'groupBy'],
  863. $this->helper->quoteColumnNames($groupBys)
  864. );
  865. return $this;
  866. }
  867. /**
  868. * Adds a grouping expression to the query.
  869. *
  870. * <code>
  871. * $qb = $conn->getQueryBuilder()
  872. * ->select('u.name')
  873. * ->from('users', 'u')
  874. * ->groupBy('u.lastLogin');
  875. * ->addGroupBy('u.createdAt')
  876. * </code>
  877. *
  878. * @param mixed ...$groupBy The grouping expression.
  879. *
  880. * @return $this This QueryBuilder instance.
  881. */
  882. public function addGroupBy(...$groupBys) {
  883. if (count($groupBys) === 1 && is_array($groupBys[0])) {
  884. $$groupBys = $groupBys[0];
  885. }
  886. call_user_func_array(
  887. [$this->queryBuilder, 'addGroupBy'],
  888. $this->helper->quoteColumnNames($groupBys)
  889. );
  890. return $this;
  891. }
  892. /**
  893. * Sets a value for a column in an insert query.
  894. *
  895. * <code>
  896. * $qb = $conn->getQueryBuilder()
  897. * ->insert('users')
  898. * ->values(
  899. * array(
  900. * 'name' => '?'
  901. * )
  902. * )
  903. * ->setValue('password', '?');
  904. * </code>
  905. *
  906. * @param string $column The column into which the value should be inserted.
  907. * @param IParameter|string $value The value that should be inserted into the column.
  908. *
  909. * @return $this This QueryBuilder instance.
  910. */
  911. public function setValue($column, $value) {
  912. $this->queryBuilder->setValue(
  913. $this->helper->quoteColumnName($column),
  914. (string) $value
  915. );
  916. return $this;
  917. }
  918. /**
  919. * Specifies values for an insert query indexed by column names.
  920. * Replaces any previous values, if any.
  921. *
  922. * <code>
  923. * $qb = $conn->getQueryBuilder()
  924. * ->insert('users')
  925. * ->values(
  926. * array(
  927. * 'name' => '?',
  928. * 'password' => '?'
  929. * )
  930. * );
  931. * </code>
  932. *
  933. * @param array $values The values to specify for the insert query indexed by column names.
  934. *
  935. * @return $this This QueryBuilder instance.
  936. */
  937. public function values(array $values) {
  938. $quotedValues = [];
  939. foreach ($values as $key => $value) {
  940. $quotedValues[$this->helper->quoteColumnName($key)] = $value;
  941. }
  942. $this->queryBuilder->values($quotedValues);
  943. return $this;
  944. }
  945. /**
  946. * Specifies a restriction over the groups of the query.
  947. * Replaces any previous having restrictions, if any.
  948. *
  949. * @param mixed ...$having The restriction over the groups.
  950. *
  951. * @return $this This QueryBuilder instance.
  952. */
  953. public function having(...$having) {
  954. call_user_func_array(
  955. [$this->queryBuilder, 'having'],
  956. $having
  957. );
  958. return $this;
  959. }
  960. /**
  961. * Adds a restriction over the groups of the query, forming a logical
  962. * conjunction with any existing having restrictions.
  963. *
  964. * @param mixed ...$having The restriction to append.
  965. *
  966. * @return $this This QueryBuilder instance.
  967. */
  968. public function andHaving(...$having) {
  969. call_user_func_array(
  970. [$this->queryBuilder, 'andHaving'],
  971. $having
  972. );
  973. return $this;
  974. }
  975. /**
  976. * Adds a restriction over the groups of the query, forming a logical
  977. * disjunction with any existing having restrictions.
  978. *
  979. * @param mixed ...$having The restriction to add.
  980. *
  981. * @return $this This QueryBuilder instance.
  982. */
  983. public function orHaving(...$having) {
  984. call_user_func_array(
  985. [$this->queryBuilder, 'orHaving'],
  986. $having
  987. );
  988. return $this;
  989. }
  990. /**
  991. * Specifies an ordering for the query results.
  992. * Replaces any previously specified orderings, if any.
  993. *
  994. * @param string|IQueryFunction|ILiteral|IParameter $sort The ordering expression.
  995. * @param string $order The ordering direction.
  996. *
  997. * @return $this This QueryBuilder instance.
  998. */
  999. public function orderBy($sort, $order = null) {
  1000. $this->queryBuilder->orderBy(
  1001. $this->helper->quoteColumnName($sort),
  1002. $order
  1003. );
  1004. return $this;
  1005. }
  1006. /**
  1007. * Adds an ordering to the query results.
  1008. *
  1009. * @param string|ILiteral|IParameter|IQueryFunction $sort The ordering expression.
  1010. * @param string $order The ordering direction.
  1011. *
  1012. * @return $this This QueryBuilder instance.
  1013. */
  1014. public function addOrderBy($sort, $order = null) {
  1015. $this->queryBuilder->addOrderBy(
  1016. $this->helper->quoteColumnName($sort),
  1017. $order
  1018. );
  1019. return $this;
  1020. }
  1021. /**
  1022. * Gets a query part by its name.
  1023. *
  1024. * @param string $queryPartName
  1025. *
  1026. * @return mixed
  1027. */
  1028. public function getQueryPart($queryPartName) {
  1029. return $this->queryBuilder->getQueryPart($queryPartName);
  1030. }
  1031. /**
  1032. * Gets all query parts.
  1033. *
  1034. * @return array
  1035. */
  1036. public function getQueryParts() {
  1037. return $this->queryBuilder->getQueryParts();
  1038. }
  1039. /**
  1040. * Resets SQL parts.
  1041. *
  1042. * @param array|null $queryPartNames
  1043. *
  1044. * @return $this This QueryBuilder instance.
  1045. */
  1046. public function resetQueryParts($queryPartNames = null) {
  1047. $this->queryBuilder->resetQueryParts($queryPartNames);
  1048. return $this;
  1049. }
  1050. /**
  1051. * Resets a single SQL part.
  1052. *
  1053. * @param string $queryPartName
  1054. *
  1055. * @return $this This QueryBuilder instance.
  1056. */
  1057. public function resetQueryPart($queryPartName) {
  1058. $this->queryBuilder->resetQueryPart($queryPartName);
  1059. return $this;
  1060. }
  1061. /**
  1062. * Creates a new named parameter and bind the value $value to it.
  1063. *
  1064. * This method provides a shortcut for PDOStatement::bindValue
  1065. * when using prepared statements.
  1066. *
  1067. * The parameter $value specifies the value that you want to bind. If
  1068. * $placeholder is not provided bindValue() will automatically create a
  1069. * placeholder for you. An automatic placeholder will be of the name
  1070. * ':dcValue1', ':dcValue2' etc.
  1071. *
  1072. * For more information see {@link https://www.php.net/pdostatement-bindparam}
  1073. *
  1074. * Example:
  1075. * <code>
  1076. * $value = 2;
  1077. * $q->eq( 'id', $q->bindValue( $value ) );
  1078. * $stmt = $q->executeQuery(); // executed with 'id = 2'
  1079. * </code>
  1080. *
  1081. * @license New BSD License
  1082. * @link http://www.zetacomponents.org
  1083. *
  1084. * @param mixed $value
  1085. * @param mixed $type
  1086. * @param string $placeHolder The name to bind with. The string must start with a colon ':'.
  1087. *
  1088. * @return IParameter the placeholder name used.
  1089. */
  1090. public function createNamedParameter($value, $type = IQueryBuilder::PARAM_STR, $placeHolder = null) {
  1091. return new Parameter($this->queryBuilder->createNamedParameter($value, $type, $placeHolder));
  1092. }
  1093. /**
  1094. * Creates a new positional parameter and bind the given value to it.
  1095. *
  1096. * Attention: If you are using positional parameters with the query builder you have
  1097. * to be very careful to bind all parameters in the order they appear in the SQL
  1098. * statement , otherwise they get bound in the wrong order which can lead to serious
  1099. * bugs in your code.
  1100. *
  1101. * Example:
  1102. * <code>
  1103. * $qb = $conn->getQueryBuilder();
  1104. * $qb->select('u.*')
  1105. * ->from('users', 'u')
  1106. * ->where('u.username = ' . $qb->createPositionalParameter('Foo', IQueryBuilder::PARAM_STR))
  1107. * ->orWhere('u.username = ' . $qb->createPositionalParameter('Bar', IQueryBuilder::PARAM_STR))
  1108. * </code>
  1109. *
  1110. * @param mixed $value
  1111. * @param integer $type
  1112. *
  1113. * @return IParameter
  1114. */
  1115. public function createPositionalParameter($value, $type = IQueryBuilder::PARAM_STR) {
  1116. return new Parameter($this->queryBuilder->createPositionalParameter($value, $type));
  1117. }
  1118. /**
  1119. * Creates a new parameter
  1120. *
  1121. * Example:
  1122. * <code>
  1123. * $qb = $conn->getQueryBuilder();
  1124. * $qb->select('u.*')
  1125. * ->from('users', 'u')
  1126. * ->where('u.username = ' . $qb->createParameter('name'))
  1127. * ->setParameter('name', 'Bar', IQueryBuilder::PARAM_STR))
  1128. * </code>
  1129. *
  1130. * @param string $name
  1131. *
  1132. * @return IParameter
  1133. */
  1134. public function createParameter($name) {
  1135. return new Parameter(':' . $name);
  1136. }
  1137. /**
  1138. * Creates a new function
  1139. *
  1140. * Attention: Column names inside the call have to be quoted before hand
  1141. *
  1142. * Example:
  1143. * <code>
  1144. * $qb = $conn->getQueryBuilder();
  1145. * $qb->select($qb->createFunction('COUNT(*)'))
  1146. * ->from('users', 'u')
  1147. * echo $qb->getSQL(); // SELECT COUNT(*) FROM `users` u
  1148. * </code>
  1149. * <code>
  1150. * $qb = $conn->getQueryBuilder();
  1151. * $qb->select($qb->createFunction('COUNT(`column`)'))
  1152. * ->from('users', 'u')
  1153. * echo $qb->getSQL(); // SELECT COUNT(`column`) FROM `users` u
  1154. * </code>
  1155. *
  1156. * @param string $call
  1157. *
  1158. * @return IQueryFunction
  1159. */
  1160. public function createFunction($call) {
  1161. return new QueryFunction($call);
  1162. }
  1163. /**
  1164. * Used to get the id of the last inserted element
  1165. * @return int
  1166. * @throws \BadMethodCallException When being called before an insert query has been run.
  1167. */
  1168. public function getLastInsertId(): int {
  1169. if ($this->getType() === \Doctrine\DBAL\Query\QueryBuilder::INSERT && $this->lastInsertedTable) {
  1170. // lastInsertId() needs the prefix but no quotes
  1171. $table = $this->prefixTableName($this->lastInsertedTable);
  1172. return $this->connection->lastInsertId($table);
  1173. }
  1174. throw new \BadMethodCallException('Invalid call to getLastInsertId without using insert() before.');
  1175. }
  1176. /**
  1177. * Returns the table name quoted and with database prefix as needed by the implementation
  1178. *
  1179. * @param string|IQueryFunction $table
  1180. * @return string
  1181. */
  1182. public function getTableName($table) {
  1183. if ($table instanceof IQueryFunction) {
  1184. return (string) $table;
  1185. }
  1186. $table = $this->prefixTableName($table);
  1187. return $this->helper->quoteColumnName($table);
  1188. }
  1189. /**
  1190. * Returns the table name with database prefix as needed by the implementation
  1191. *
  1192. * @param string $table
  1193. * @return string
  1194. */
  1195. protected function prefixTableName($table) {
  1196. if ($this->automaticTablePrefix === false || strpos($table, '*PREFIX*') === 0) {
  1197. return $table;
  1198. }
  1199. return '*PREFIX*' . $table;
  1200. }
  1201. /**
  1202. * Returns the column name quoted and with table alias prefix as needed by the implementation
  1203. *
  1204. * @param string $column
  1205. * @param string $tableAlias
  1206. * @return string
  1207. */
  1208. public function getColumnName($column, $tableAlias = '') {
  1209. if ($tableAlias !== '') {
  1210. $tableAlias .= '.';
  1211. }
  1212. return $this->helper->quoteColumnName($tableAlias . $column);
  1213. }
  1214. /**
  1215. * Returns the column name quoted and with table alias prefix as needed by the implementation
  1216. *
  1217. * @param string $alias
  1218. * @return string
  1219. */
  1220. public function quoteAlias($alias) {
  1221. if ($alias === '' || $alias === null) {
  1222. return $alias;
  1223. }
  1224. return $this->helper->quoteColumnName($alias);
  1225. }
  1226. }