QueryBuilder.php 35 KB

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