QueryBuilderTest.php 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469
  1. <?php
  2. /**
  3. * @author Joas Schilling <nickvergessen@owncloud.com>
  4. *
  5. * @copyright Copyright (c) 2015, ownCloud, Inc.
  6. * @license AGPL-3.0
  7. *
  8. * This code is free software: you can redistribute it and/or modify
  9. * it under the terms of the GNU Affero General Public License, version 3,
  10. * as published by the Free Software Foundation.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU Affero General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Affero General Public License, version 3,
  18. * along with this program. If not, see <http://www.gnu.org/licenses/>
  19. *
  20. */
  21. namespace Test\DB\QueryBuilder;
  22. use Doctrine\DBAL\Query\Expression\CompositeExpression;
  23. use Doctrine\DBAL\Query\QueryException;
  24. use Doctrine\DBAL\Result;
  25. use OC\DB\QueryBuilder\Literal;
  26. use OC\DB\QueryBuilder\Parameter;
  27. use OC\DB\QueryBuilder\QueryBuilder;
  28. use OC\SystemConfig;
  29. use OCP\DB\QueryBuilder\IQueryFunction;
  30. use OCP\IDBConnection;
  31. use Psr\Log\LoggerInterface;
  32. /**
  33. * Class QueryBuilderTest
  34. *
  35. * @group DB
  36. *
  37. * @package Test\DB\QueryBuilder
  38. */
  39. class QueryBuilderTest extends \Test\TestCase {
  40. /** @var QueryBuilder */
  41. protected $queryBuilder;
  42. /** @var IDBConnection */
  43. protected $connection;
  44. /** @var SystemConfig|\PHPUnit\Framework\MockObject\MockObject */
  45. protected $config;
  46. /** @var LoggerInterface|\PHPUnit\Framework\MockObject\MockObject */
  47. protected $logger;
  48. protected function setUp(): void {
  49. parent::setUp();
  50. $this->connection = \OC::$server->getDatabaseConnection();
  51. $this->config = $this->createMock(SystemConfig::class);
  52. $this->logger = $this->createMock(LoggerInterface::class);
  53. $this->queryBuilder = new QueryBuilder($this->connection, $this->config, $this->logger);
  54. }
  55. protected function createTestingRows($appId = 'testFirstResult') {
  56. $qB = $this->connection->getQueryBuilder();
  57. for ($i = 1; $i < 10; $i++) {
  58. $qB->insert('*PREFIX*appconfig')
  59. ->values([
  60. 'appid' => $qB->expr()->literal($appId),
  61. 'configkey' => $qB->expr()->literal('testing' . $i),
  62. 'configvalue' => $qB->expr()->literal(100 - $i),
  63. ])
  64. ->execute();
  65. }
  66. }
  67. protected function getTestingRows(QueryBuilder $queryBuilder) {
  68. $queryBuilder->select('configvalue')
  69. ->from('*PREFIX*appconfig')
  70. ->where($queryBuilder->expr()->eq(
  71. 'appid',
  72. $queryBuilder->expr()->literal('testFirstResult')
  73. ))
  74. ->orderBy('configkey', 'ASC');
  75. $query = $queryBuilder->execute();
  76. $rows = [];
  77. while ($row = $query->fetch()) {
  78. $rows[] = $row['configvalue'];
  79. }
  80. $query->closeCursor();
  81. return $rows;
  82. }
  83. protected function deleteTestingRows($appId = 'testFirstResult') {
  84. $qB = $this->connection->getQueryBuilder();
  85. $qB->delete('*PREFIX*appconfig')
  86. ->where($qB->expr()->eq('appid', $qB->expr()->literal($appId)))
  87. ->execute();
  88. }
  89. public function dataFirstResult() {
  90. return [
  91. [0, [99, 98, 97, 96, 95, 94, 93, 92, 91]],
  92. [0, [99, 98, 97, 96, 95, 94, 93, 92, 91]],
  93. [1, [98, 97, 96, 95, 94, 93, 92, 91]],
  94. [5, [94, 93, 92, 91]],
  95. ];
  96. }
  97. /**
  98. * @dataProvider dataFirstResult
  99. *
  100. * @param int|null $firstResult
  101. * @param array $expectedSet
  102. */
  103. public function testFirstResult($firstResult, $expectedSet) {
  104. $this->deleteTestingRows();
  105. $this->createTestingRows();
  106. if ($firstResult !== null) {
  107. $this->queryBuilder->setFirstResult($firstResult);
  108. }
  109. $this->assertSame(
  110. $firstResult ?? 0,
  111. $this->queryBuilder->getFirstResult()
  112. );
  113. $rows = $this->getTestingRows($this->queryBuilder);
  114. $this->assertCount(sizeof($expectedSet), $rows);
  115. $this->assertEquals($expectedSet, $rows);
  116. $this->deleteTestingRows();
  117. }
  118. public function dataMaxResults() {
  119. return [
  120. [null, [99, 98, 97, 96, 95, 94, 93, 92, 91]],
  121. // Limit 0 gives mixed results: either all entries or none is returned
  122. //[0, []],
  123. [1, [99]],
  124. [5, [99, 98, 97, 96, 95]],
  125. ];
  126. }
  127. /**
  128. * @dataProvider dataMaxResults
  129. *
  130. * @param int $maxResult
  131. * @param array $expectedSet
  132. */
  133. public function testMaxResults($maxResult, $expectedSet) {
  134. $this->deleteTestingRows();
  135. $this->createTestingRows();
  136. if ($maxResult !== null) {
  137. $this->queryBuilder->setMaxResults($maxResult);
  138. }
  139. $this->assertSame(
  140. $maxResult,
  141. $this->queryBuilder->getMaxResults()
  142. );
  143. $rows = $this->getTestingRows($this->queryBuilder);
  144. $this->assertCount(sizeof($expectedSet), $rows);
  145. $this->assertEquals($expectedSet, $rows);
  146. $this->deleteTestingRows();
  147. }
  148. public function dataSelect() {
  149. $config = $this->createMock(SystemConfig::class);
  150. $logger = $this->createMock(LoggerInterface::class);
  151. $queryBuilder = new QueryBuilder(\OC::$server->getDatabaseConnection(), $config, $logger);
  152. return [
  153. // select('column1')
  154. [['configvalue'], ['configvalue' => '99']],
  155. // select('column1', 'column2')
  156. [['configvalue', 'configkey'], ['configvalue' => '99', 'configkey' => 'testing1']],
  157. // select(['column1', 'column2'])
  158. [[['configvalue', 'configkey']], ['configvalue' => '99', 'configkey' => 'testing1']],
  159. // select(new Literal('column1'))
  160. [[$queryBuilder->expr()->literal('column1')], [], 'column1'],
  161. // select('column1', 'column2')
  162. [[$queryBuilder->expr()->literal('column1'), 'configkey'], ['configkey' => 'testing1'], 'column1'],
  163. // select(['column1', 'column2'])
  164. [[[$queryBuilder->expr()->literal('column1'), 'configkey']], ['configkey' => 'testing1'], 'column1'],
  165. ];
  166. }
  167. /**
  168. * @dataProvider dataSelect
  169. *
  170. * @param array $selectArguments
  171. * @param array $expected
  172. * @param string $expectedLiteral
  173. */
  174. public function testSelect($selectArguments, $expected, $expectedLiteral = '') {
  175. $this->deleteTestingRows();
  176. $this->createTestingRows();
  177. call_user_func_array(
  178. [$this->queryBuilder, 'select'],
  179. $selectArguments
  180. );
  181. $this->queryBuilder->from('*PREFIX*appconfig')
  182. ->where($this->queryBuilder->expr()->eq(
  183. 'appid',
  184. $this->queryBuilder->expr()->literal('testFirstResult')
  185. ))
  186. ->orderBy('configkey', 'ASC')
  187. ->setMaxResults(1);
  188. $query = $this->queryBuilder->execute();
  189. $row = $query->fetch();
  190. $query->closeCursor();
  191. foreach ($expected as $key => $value) {
  192. $this->assertArrayHasKey($key, $row);
  193. $this->assertEquals($value, $row[$key]);
  194. unset($row[$key]);
  195. }
  196. if ($expectedLiteral) {
  197. $this->assertEquals([$expectedLiteral], array_values($row));
  198. } else {
  199. $this->assertEmpty($row);
  200. }
  201. $this->deleteTestingRows();
  202. }
  203. public function dataSelectAlias() {
  204. $config = $this->createMock(SystemConfig::class);
  205. $logger = $this->createMock(LoggerInterface::class);
  206. $queryBuilder = new QueryBuilder(\OC::$server->getDatabaseConnection(), $config, $logger);
  207. return [
  208. ['configvalue', 'cv', ['cv' => '99']],
  209. [$queryBuilder->expr()->literal('column1'), 'thing', ['thing' => 'column1']],
  210. ];
  211. }
  212. /**
  213. * @dataProvider dataSelectAlias
  214. *
  215. * @param mixed $select
  216. * @param array $alias
  217. * @param array $expected
  218. */
  219. public function testSelectAlias($select, $alias, $expected) {
  220. $this->deleteTestingRows();
  221. $this->createTestingRows();
  222. $this->queryBuilder->selectAlias($select, $alias);
  223. $this->queryBuilder->from('*PREFIX*appconfig')
  224. ->where($this->queryBuilder->expr()->eq(
  225. 'appid',
  226. $this->queryBuilder->expr()->literal('testFirstResult')
  227. ))
  228. ->orderBy('configkey', 'ASC')
  229. ->setMaxResults(1);
  230. $query = $this->queryBuilder->execute();
  231. $row = $query->fetch();
  232. $query->closeCursor();
  233. $this->assertEquals(
  234. $expected,
  235. $row
  236. );
  237. $this->deleteTestingRows();
  238. }
  239. public function testSelectDistinct() {
  240. $this->deleteTestingRows('testFirstResult1');
  241. $this->deleteTestingRows('testFirstResult2');
  242. $this->createTestingRows('testFirstResult1');
  243. $this->createTestingRows('testFirstResult2');
  244. $this->queryBuilder->selectDistinct('appid');
  245. $this->queryBuilder->from('*PREFIX*appconfig')
  246. ->where($this->queryBuilder->expr()->in(
  247. 'appid',
  248. [$this->queryBuilder->expr()->literal('testFirstResult1'), $this->queryBuilder->expr()->literal('testFirstResult2')]
  249. ))
  250. ->orderBy('appid', 'DESC');
  251. $query = $this->queryBuilder->execute();
  252. $rows = $query->fetchAll();
  253. $query->closeCursor();
  254. $this->assertEquals(
  255. [['appid' => 'testFirstResult2'], ['appid' => 'testFirstResult1']],
  256. $rows
  257. );
  258. $this->deleteTestingRows('testFirstResult1');
  259. $this->deleteTestingRows('testFirstResult2');
  260. }
  261. public function testSelectDistinctMultiple() {
  262. $this->deleteTestingRows('testFirstResult1');
  263. $this->deleteTestingRows('testFirstResult2');
  264. $this->createTestingRows('testFirstResult1');
  265. $this->createTestingRows('testFirstResult2');
  266. $this->queryBuilder->selectDistinct(['appid', 'configkey']);
  267. $this->queryBuilder->from('*PREFIX*appconfig')
  268. ->where($this->queryBuilder->expr()->eq(
  269. 'appid',
  270. $this->queryBuilder->expr()->literal('testFirstResult1')
  271. ))
  272. ->orderBy('appid', 'DESC');
  273. $query = $this->queryBuilder->execute();
  274. $rows = $query->fetchAll();
  275. $query->closeCursor();
  276. $this->assertEquals(
  277. [
  278. ['appid' => 'testFirstResult1', 'configkey' => 'testing1'],
  279. ['appid' => 'testFirstResult1', 'configkey' => 'testing2'],
  280. ['appid' => 'testFirstResult1', 'configkey' => 'testing3'],
  281. ['appid' => 'testFirstResult1', 'configkey' => 'testing4'],
  282. ['appid' => 'testFirstResult1', 'configkey' => 'testing5'],
  283. ['appid' => 'testFirstResult1', 'configkey' => 'testing6'],
  284. ['appid' => 'testFirstResult1', 'configkey' => 'testing7'],
  285. ['appid' => 'testFirstResult1', 'configkey' => 'testing8'],
  286. ['appid' => 'testFirstResult1', 'configkey' => 'testing9'],
  287. ],
  288. $rows
  289. );
  290. $this->deleteTestingRows('testFirstResult1');
  291. $this->deleteTestingRows('testFirstResult2');
  292. }
  293. public function dataAddSelect() {
  294. $config = $this->createMock(SystemConfig::class);
  295. $logger = $this->createMock(LoggerInterface::class);
  296. $queryBuilder = new QueryBuilder(\OC::$server->getDatabaseConnection(), $config, $logger);
  297. return [
  298. // addSelect('column1')
  299. [['configvalue'], ['appid' => 'testFirstResult', 'configvalue' => '99']],
  300. // addSelect('column1', 'column2')
  301. [['configvalue', 'configkey'], ['appid' => 'testFirstResult', 'configvalue' => '99', 'configkey' => 'testing1']],
  302. // addSelect(['column1', 'column2'])
  303. [[['configvalue', 'configkey']], ['appid' => 'testFirstResult', 'configvalue' => '99', 'configkey' => 'testing1']],
  304. // select(new Literal('column1'))
  305. [[$queryBuilder->expr()->literal('column1')], ['appid' => 'testFirstResult'], 'column1'],
  306. // select('column1', 'column2')
  307. [[$queryBuilder->expr()->literal('column1'), 'configkey'], ['appid' => 'testFirstResult', 'configkey' => 'testing1'], 'column1'],
  308. // select(['column1', 'column2'])
  309. [[[$queryBuilder->expr()->literal('column1'), 'configkey']], ['appid' => 'testFirstResult', 'configkey' => 'testing1'], 'column1'],
  310. ];
  311. }
  312. /**
  313. * @dataProvider dataAddSelect
  314. *
  315. * @param array $selectArguments
  316. * @param array $expected
  317. * @param string $expectedLiteral
  318. */
  319. public function testAddSelect($selectArguments, $expected, $expectedLiteral = '') {
  320. $this->deleteTestingRows();
  321. $this->createTestingRows();
  322. $this->queryBuilder->select('appid');
  323. call_user_func_array(
  324. [$this->queryBuilder, 'addSelect'],
  325. $selectArguments
  326. );
  327. $this->queryBuilder->from('*PREFIX*appconfig')
  328. ->where($this->queryBuilder->expr()->eq(
  329. 'appid',
  330. $this->queryBuilder->expr()->literal('testFirstResult')
  331. ))
  332. ->orderBy('configkey', 'ASC')
  333. ->setMaxResults(1);
  334. $query = $this->queryBuilder->execute();
  335. $row = $query->fetch();
  336. $query->closeCursor();
  337. foreach ($expected as $key => $value) {
  338. $this->assertArrayHasKey($key, $row);
  339. $this->assertEquals($value, $row[$key]);
  340. unset($row[$key]);
  341. }
  342. if ($expectedLiteral) {
  343. $this->assertEquals([$expectedLiteral], array_values($row));
  344. } else {
  345. $this->assertEmpty($row);
  346. }
  347. $this->deleteTestingRows();
  348. }
  349. public function dataDelete() {
  350. return [
  351. ['data', null, ['table' => '`*PREFIX*data`', 'alias' => null], '`*PREFIX*data`'],
  352. ['data', 't', ['table' => '`*PREFIX*data`', 'alias' => 't'], '`*PREFIX*data` t'],
  353. ];
  354. }
  355. /**
  356. * @dataProvider dataDelete
  357. *
  358. * @param string $tableName
  359. * @param string $tableAlias
  360. * @param array $expectedQueryPart
  361. * @param string $expectedQuery
  362. */
  363. public function testDelete($tableName, $tableAlias, $expectedQueryPart, $expectedQuery) {
  364. $this->queryBuilder->delete($tableName, $tableAlias);
  365. $this->assertSame(
  366. $expectedQueryPart,
  367. $this->queryBuilder->getQueryPart('from')
  368. );
  369. $this->assertSame(
  370. 'DELETE FROM ' . $expectedQuery,
  371. $this->queryBuilder->getSQL()
  372. );
  373. }
  374. public function dataUpdate() {
  375. return [
  376. ['data', null, ['table' => '`*PREFIX*data`', 'alias' => null], '`*PREFIX*data`'],
  377. ['data', 't', ['table' => '`*PREFIX*data`', 'alias' => 't'], '`*PREFIX*data` t'],
  378. ];
  379. }
  380. /**
  381. * @dataProvider dataUpdate
  382. *
  383. * @param string $tableName
  384. * @param string $tableAlias
  385. * @param array $expectedQueryPart
  386. * @param string $expectedQuery
  387. */
  388. public function testUpdate($tableName, $tableAlias, $expectedQueryPart, $expectedQuery) {
  389. $this->queryBuilder->update($tableName, $tableAlias);
  390. $this->assertSame(
  391. $expectedQueryPart,
  392. $this->queryBuilder->getQueryPart('from')
  393. );
  394. $this->assertSame(
  395. 'UPDATE ' . $expectedQuery . ' SET ',
  396. $this->queryBuilder->getSQL()
  397. );
  398. }
  399. public function dataInsert() {
  400. return [
  401. ['data', ['table' => '`*PREFIX*data`'], '`*PREFIX*data`'],
  402. ];
  403. }
  404. /**
  405. * @dataProvider dataInsert
  406. *
  407. * @param string $tableName
  408. * @param array $expectedQueryPart
  409. * @param string $expectedQuery
  410. */
  411. public function testInsert($tableName, $expectedQueryPart, $expectedQuery) {
  412. $this->queryBuilder->insert($tableName);
  413. $this->assertSame(
  414. $expectedQueryPart,
  415. $this->queryBuilder->getQueryPart('from')
  416. );
  417. $this->assertSame(
  418. 'INSERT INTO ' . $expectedQuery . ' () VALUES()',
  419. $this->queryBuilder->getSQL()
  420. );
  421. }
  422. public function dataFrom() {
  423. $config = $this->createMock(SystemConfig::class);
  424. $logger = $this->createMock(LoggerInterface::class);
  425. $qb = new QueryBuilder(\OC::$server->getDatabaseConnection(), $config, $logger);
  426. return [
  427. [$qb->createFunction('(' . $qb->select('*')->from('test')->getSQL() . ')'), 'q', null, null, [
  428. ['table' => '(SELECT * FROM `*PREFIX*test`)', 'alias' => '`q`']
  429. ], '(SELECT * FROM `*PREFIX*test`) `q`'],
  430. ['data', null, null, null, [['table' => '`*PREFIX*data`', 'alias' => null]], '`*PREFIX*data`'],
  431. ['data', 't', null, null, [['table' => '`*PREFIX*data`', 'alias' => '`t`']], '`*PREFIX*data` `t`'],
  432. ['data1', null, 'data2', null, [
  433. ['table' => '`*PREFIX*data1`', 'alias' => null],
  434. ['table' => '`*PREFIX*data2`', 'alias' => null]
  435. ], '`*PREFIX*data1`, `*PREFIX*data2`'],
  436. ['data', 't1', 'data', 't2', [
  437. ['table' => '`*PREFIX*data`', 'alias' => '`t1`'],
  438. ['table' => '`*PREFIX*data`', 'alias' => '`t2`']
  439. ], '`*PREFIX*data` `t1`, `*PREFIX*data` `t2`'],
  440. ];
  441. }
  442. /**
  443. * @dataProvider dataFrom
  444. *
  445. * @param string|IQueryFunction $table1Name
  446. * @param string $table1Alias
  447. * @param string|IQueryFunction $table2Name
  448. * @param string $table2Alias
  449. * @param array $expectedQueryPart
  450. * @param string $expectedQuery
  451. */
  452. public function testFrom($table1Name, $table1Alias, $table2Name, $table2Alias, $expectedQueryPart, $expectedQuery) {
  453. $this->queryBuilder->from($table1Name, $table1Alias);
  454. if ($table2Name !== null) {
  455. $this->queryBuilder->from($table2Name, $table2Alias);
  456. }
  457. $this->assertSame(
  458. $expectedQueryPart,
  459. $this->queryBuilder->getQueryPart('from')
  460. );
  461. $this->assertSame(
  462. 'SELECT FROM ' . $expectedQuery,
  463. $this->queryBuilder->getSQL()
  464. );
  465. }
  466. public function dataJoin() {
  467. return [
  468. [
  469. 'd1', 'data2', null, null,
  470. ['`d1`' => [['joinType' => 'inner', 'joinTable' => '`*PREFIX*data2`', 'joinAlias' => null, 'joinCondition' => null]]],
  471. '`*PREFIX*data1` `d1` INNER JOIN `*PREFIX*data2` '
  472. ],
  473. [
  474. 'd1', 'data2', 'd2', null,
  475. ['`d1`' => [['joinType' => 'inner', 'joinTable' => '`*PREFIX*data2`', 'joinAlias' => '`d2`', 'joinCondition' => null]]],
  476. '`*PREFIX*data1` `d1` INNER JOIN `*PREFIX*data2` `d2`'
  477. ],
  478. [
  479. 'd1', 'data2', 'd2', '`d1`.`field1` = `d2`.`field2`',
  480. ['`d1`' => [['joinType' => 'inner', 'joinTable' => '`*PREFIX*data2`', 'joinAlias' => '`d2`', 'joinCondition' => '`d1`.`field1` = `d2`.`field2`']]],
  481. '`*PREFIX*data1` `d1` INNER JOIN `*PREFIX*data2` `d2` ON `d1`.`field1` = `d2`.`field2`'
  482. ],
  483. ];
  484. }
  485. /**
  486. * @dataProvider dataJoin
  487. *
  488. * @param string $fromAlias
  489. * @param string $tableName
  490. * @param string $tableAlias
  491. * @param string $condition
  492. * @param array $expectedQueryPart
  493. * @param string $expectedQuery
  494. */
  495. public function testJoin($fromAlias, $tableName, $tableAlias, $condition, $expectedQueryPart, $expectedQuery) {
  496. $this->queryBuilder->from('data1', 'd1');
  497. $this->queryBuilder->join(
  498. $fromAlias,
  499. $tableName,
  500. $tableAlias,
  501. $condition
  502. );
  503. $this->assertSame(
  504. $expectedQueryPart,
  505. $this->queryBuilder->getQueryPart('join')
  506. );
  507. $this->assertSame(
  508. 'SELECT FROM ' . $expectedQuery,
  509. $this->queryBuilder->getSQL()
  510. );
  511. }
  512. /**
  513. * @dataProvider dataJoin
  514. *
  515. * @param string $fromAlias
  516. * @param string $tableName
  517. * @param string $tableAlias
  518. * @param string $condition
  519. * @param array $expectedQueryPart
  520. * @param string $expectedQuery
  521. */
  522. public function testInnerJoin($fromAlias, $tableName, $tableAlias, $condition, $expectedQueryPart, $expectedQuery) {
  523. $this->queryBuilder->from('data1', 'd1');
  524. $this->queryBuilder->innerJoin(
  525. $fromAlias,
  526. $tableName,
  527. $tableAlias,
  528. $condition
  529. );
  530. $this->assertSame(
  531. $expectedQueryPart,
  532. $this->queryBuilder->getQueryPart('join')
  533. );
  534. $this->assertSame(
  535. 'SELECT FROM ' . $expectedQuery,
  536. $this->queryBuilder->getSQL()
  537. );
  538. }
  539. public function dataLeftJoin() {
  540. return [
  541. [
  542. 'd1', 'data2', null, null,
  543. ['`d1`' => [['joinType' => 'left', 'joinTable' => '`*PREFIX*data2`', 'joinAlias' => null, 'joinCondition' => null]]],
  544. '`*PREFIX*data1` `d1` LEFT JOIN `*PREFIX*data2` '
  545. ],
  546. [
  547. 'd1', 'data2', 'd2', null,
  548. ['`d1`' => [['joinType' => 'left', 'joinTable' => '`*PREFIX*data2`', 'joinAlias' => '`d2`', 'joinCondition' => null]]],
  549. '`*PREFIX*data1` `d1` LEFT JOIN `*PREFIX*data2` `d2`'
  550. ],
  551. [
  552. 'd1', 'data2', 'd2', '`d1`.`field1` = `d2`.`field2`',
  553. ['`d1`' => [['joinType' => 'left', 'joinTable' => '`*PREFIX*data2`', 'joinAlias' => '`d2`', 'joinCondition' => '`d1`.`field1` = `d2`.`field2`']]],
  554. '`*PREFIX*data1` `d1` LEFT JOIN `*PREFIX*data2` `d2` ON `d1`.`field1` = `d2`.`field2`'
  555. ],
  556. ];
  557. }
  558. /**
  559. * @dataProvider dataLeftJoin
  560. *
  561. * @param string $fromAlias
  562. * @param string $tableName
  563. * @param string $tableAlias
  564. * @param string $condition
  565. * @param array $expectedQueryPart
  566. * @param string $expectedQuery
  567. */
  568. public function testLeftJoin($fromAlias, $tableName, $tableAlias, $condition, $expectedQueryPart, $expectedQuery) {
  569. $this->queryBuilder->from('data1', 'd1');
  570. $this->queryBuilder->leftJoin(
  571. $fromAlias,
  572. $tableName,
  573. $tableAlias,
  574. $condition
  575. );
  576. $this->assertSame(
  577. $expectedQueryPart,
  578. $this->queryBuilder->getQueryPart('join')
  579. );
  580. $this->assertSame(
  581. 'SELECT FROM ' . $expectedQuery,
  582. $this->queryBuilder->getSQL()
  583. );
  584. }
  585. public function dataRightJoin() {
  586. return [
  587. [
  588. 'd1', 'data2', null, null,
  589. ['`d1`' => [['joinType' => 'right', 'joinTable' => '`*PREFIX*data2`', 'joinAlias' => null, 'joinCondition' => null]]],
  590. '`*PREFIX*data1` `d1` RIGHT JOIN `*PREFIX*data2` '
  591. ],
  592. [
  593. 'd1', 'data2', 'd2', null,
  594. ['`d1`' => [['joinType' => 'right', 'joinTable' => '`*PREFIX*data2`', 'joinAlias' => '`d2`', 'joinCondition' => null]]],
  595. '`*PREFIX*data1` `d1` RIGHT JOIN `*PREFIX*data2` `d2`'
  596. ],
  597. [
  598. 'd1', 'data2', 'd2', '`d1`.`field1` = `d2`.`field2`',
  599. ['`d1`' => [['joinType' => 'right', 'joinTable' => '`*PREFIX*data2`', 'joinAlias' => '`d2`', 'joinCondition' => '`d1`.`field1` = `d2`.`field2`']]],
  600. '`*PREFIX*data1` `d1` RIGHT JOIN `*PREFIX*data2` `d2` ON `d1`.`field1` = `d2`.`field2`'
  601. ],
  602. ];
  603. }
  604. /**
  605. * @dataProvider dataRightJoin
  606. *
  607. * @param string $fromAlias
  608. * @param string $tableName
  609. * @param string $tableAlias
  610. * @param string $condition
  611. * @param array $expectedQueryPart
  612. * @param string $expectedQuery
  613. */
  614. public function testRightJoin($fromAlias, $tableName, $tableAlias, $condition, $expectedQueryPart, $expectedQuery) {
  615. $this->queryBuilder->from('data1', 'd1');
  616. $this->queryBuilder->rightJoin(
  617. $fromAlias,
  618. $tableName,
  619. $tableAlias,
  620. $condition
  621. );
  622. $this->assertSame(
  623. $expectedQueryPart,
  624. $this->queryBuilder->getQueryPart('join')
  625. );
  626. $this->assertSame(
  627. 'SELECT FROM ' . $expectedQuery,
  628. $this->queryBuilder->getSQL()
  629. );
  630. }
  631. public function dataSet() {
  632. return [
  633. ['column1', new Literal('value'), null, null, ['`column1` = value'], '`column1` = value'],
  634. ['column1', new Parameter(':param'), null, null, ['`column1` = :param'], '`column1` = :param'],
  635. ['column1', 'column2', null, null, ['`column1` = `column2`'], '`column1` = `column2`'],
  636. ['column1', 'column2', 'column3', new Literal('value'), ['`column1` = `column2`', '`column3` = value'], '`column1` = `column2`, `column3` = value'],
  637. ];
  638. }
  639. /**
  640. * @dataProvider dataSet
  641. *
  642. * @param string $partOne1
  643. * @param string $partOne2
  644. * @param string $partTwo1
  645. * @param string $partTwo2
  646. * @param array $expectedQueryPart
  647. * @param string $expectedQuery
  648. */
  649. public function testSet($partOne1, $partOne2, $partTwo1, $partTwo2, $expectedQueryPart, $expectedQuery) {
  650. $this->queryBuilder->update('data');
  651. $this->queryBuilder->set($partOne1, $partOne2);
  652. if ($partTwo1 !== null) {
  653. $this->queryBuilder->set($partTwo1, $partTwo2);
  654. }
  655. $this->assertSame(
  656. $expectedQueryPart,
  657. $this->queryBuilder->getQueryPart('set')
  658. );
  659. $this->assertSame(
  660. 'UPDATE `*PREFIX*data` SET ' . $expectedQuery,
  661. $this->queryBuilder->getSQL()
  662. );
  663. }
  664. public function dataWhere() {
  665. return [
  666. [['where1'], new CompositeExpression('AND', ['where1']), 'where1'],
  667. [['where1', 'where2'], new CompositeExpression('AND', ['where1', 'where2']), '(where1) AND (where2)'],
  668. ];
  669. }
  670. /**
  671. * @dataProvider dataWhere
  672. *
  673. * @param array $whereArguments
  674. * @param array $expectedQueryPart
  675. * @param string $expectedQuery
  676. */
  677. public function testWhere($whereArguments, $expectedQueryPart, $expectedQuery) {
  678. $this->queryBuilder->select('column');
  679. call_user_func_array(
  680. [$this->queryBuilder, 'where'],
  681. $whereArguments
  682. );
  683. $this->assertEquals(
  684. $expectedQueryPart,
  685. $this->queryBuilder->getQueryPart('where')
  686. );
  687. $this->assertSame(
  688. 'SELECT `column` WHERE ' . $expectedQuery,
  689. $this->queryBuilder->getSQL()
  690. );
  691. }
  692. /**
  693. * @dataProvider dataWhere
  694. *
  695. * @param array $whereArguments
  696. * @param array $expectedQueryPart
  697. * @param string $expectedQuery
  698. */
  699. public function testAndWhere($whereArguments, $expectedQueryPart, $expectedQuery) {
  700. $this->queryBuilder->select('column');
  701. call_user_func_array(
  702. [$this->queryBuilder, 'andWhere'],
  703. $whereArguments
  704. );
  705. $this->assertEquals(
  706. $expectedQueryPart,
  707. $this->queryBuilder->getQueryPart('where')
  708. );
  709. $this->assertSame(
  710. 'SELECT `column` WHERE ' . $expectedQuery,
  711. $this->queryBuilder->getSQL()
  712. );
  713. }
  714. public function dataOrWhere() {
  715. return [
  716. [['where1'], new CompositeExpression('OR', ['where1']), 'where1'],
  717. [['where1', 'where2'], new CompositeExpression('OR', ['where1', 'where2']), '(where1) OR (where2)'],
  718. ];
  719. }
  720. /**
  721. * @dataProvider dataOrWhere
  722. *
  723. * @param array $whereArguments
  724. * @param array $expectedQueryPart
  725. * @param string $expectedQuery
  726. */
  727. public function testOrWhere($whereArguments, $expectedQueryPart, $expectedQuery) {
  728. $this->queryBuilder->select('column');
  729. call_user_func_array(
  730. [$this->queryBuilder, 'orWhere'],
  731. $whereArguments
  732. );
  733. $this->assertEquals(
  734. $expectedQueryPart,
  735. $this->queryBuilder->getQueryPart('where')
  736. );
  737. $this->assertSame(
  738. 'SELECT `column` WHERE ' . $expectedQuery,
  739. $this->queryBuilder->getSQL()
  740. );
  741. }
  742. public function dataGroupBy() {
  743. return [
  744. [['column1'], ['`column1`'], '`column1`'],
  745. [['column1', 'column2'], ['`column1`', '`column2`'], '`column1`, `column2`'],
  746. ];
  747. }
  748. /**
  749. * @dataProvider dataGroupBy
  750. *
  751. * @param array $groupByArguments
  752. * @param array $expectedQueryPart
  753. * @param string $expectedQuery
  754. */
  755. public function testGroupBy($groupByArguments, $expectedQueryPart, $expectedQuery) {
  756. $this->queryBuilder->select('column');
  757. call_user_func_array(
  758. [$this->queryBuilder, 'groupBy'],
  759. $groupByArguments
  760. );
  761. $this->assertEquals(
  762. $expectedQueryPart,
  763. $this->queryBuilder->getQueryPart('groupBy')
  764. );
  765. $this->assertSame(
  766. 'SELECT `column` GROUP BY ' . $expectedQuery,
  767. $this->queryBuilder->getSQL()
  768. );
  769. }
  770. public function dataAddGroupBy() {
  771. return [
  772. [['column2'], ['`column1`', '`column2`'], '`column1`, `column2`'],
  773. [['column2', 'column3'], ['`column1`', '`column2`', '`column3`'], '`column1`, `column2`, `column3`'],
  774. ];
  775. }
  776. /**
  777. * @dataProvider dataAddGroupBy
  778. *
  779. * @param array $groupByArguments
  780. * @param array $expectedQueryPart
  781. * @param string $expectedQuery
  782. */
  783. public function testAddGroupBy($groupByArguments, $expectedQueryPart, $expectedQuery) {
  784. $this->queryBuilder->select('column');
  785. $this->queryBuilder->groupBy('column1');
  786. call_user_func_array(
  787. [$this->queryBuilder, 'addGroupBy'],
  788. $groupByArguments
  789. );
  790. $this->assertEquals(
  791. $expectedQueryPart,
  792. $this->queryBuilder->getQueryPart('groupBy')
  793. );
  794. $this->assertSame(
  795. 'SELECT `column` GROUP BY ' . $expectedQuery,
  796. $this->queryBuilder->getSQL()
  797. );
  798. }
  799. public function dataSetValue() {
  800. return [
  801. ['column', 'value', ['`column`' => 'value'], '(`column`) VALUES(value)'],
  802. ];
  803. }
  804. /**
  805. * @dataProvider dataSetValue
  806. *
  807. * @param string $column
  808. * @param string $value
  809. * @param array $expectedQueryPart
  810. * @param string $expectedQuery
  811. */
  812. public function testSetValue($column, $value, $expectedQueryPart, $expectedQuery) {
  813. $this->queryBuilder->insert('data');
  814. $this->queryBuilder->setValue($column, $value);
  815. $this->assertEquals(
  816. $expectedQueryPart,
  817. $this->queryBuilder->getQueryPart('values')
  818. );
  819. $this->assertSame(
  820. 'INSERT INTO `*PREFIX*data` ' . $expectedQuery,
  821. $this->queryBuilder->getSQL()
  822. );
  823. }
  824. /**
  825. * @dataProvider dataSetValue
  826. *
  827. * @param string $column
  828. * @param string $value
  829. * @param array $expectedQueryPart
  830. * @param string $expectedQuery
  831. */
  832. public function testValues($column, $value, $expectedQueryPart, $expectedQuery) {
  833. $this->queryBuilder->insert('data');
  834. $this->queryBuilder->values([
  835. $column => $value,
  836. ]);
  837. $this->assertEquals(
  838. $expectedQueryPart,
  839. $this->queryBuilder->getQueryPart('values')
  840. );
  841. $this->assertSame(
  842. 'INSERT INTO `*PREFIX*data` ' . $expectedQuery,
  843. $this->queryBuilder->getSQL()
  844. );
  845. }
  846. public function dataHaving() {
  847. return [
  848. [['condition1'], new CompositeExpression('AND', ['condition1']), 'HAVING condition1'],
  849. [['condition1', 'condition2'], new CompositeExpression('AND', ['condition1', 'condition2']), 'HAVING (condition1) AND (condition2)'],
  850. [
  851. [new CompositeExpression('OR', ['condition1', 'condition2'])],
  852. new CompositeExpression('OR', ['condition1', 'condition2']),
  853. 'HAVING (condition1) OR (condition2)'
  854. ],
  855. [
  856. [new CompositeExpression('AND', ['condition1', 'condition2'])],
  857. new CompositeExpression('AND', ['condition1', 'condition2']),
  858. 'HAVING (condition1) AND (condition2)'
  859. ],
  860. ];
  861. }
  862. /**
  863. * @dataProvider dataHaving
  864. *
  865. * @param array $havingArguments
  866. * @param array $expectedQueryPart
  867. * @param string $expectedQuery
  868. */
  869. public function testHaving($havingArguments, $expectedQueryPart, $expectedQuery) {
  870. call_user_func_array(
  871. [$this->queryBuilder, 'having'],
  872. $havingArguments
  873. );
  874. $this->assertEquals(
  875. $expectedQueryPart,
  876. $this->queryBuilder->getQueryPart('having')
  877. );
  878. $this->assertSame(
  879. 'SELECT ' . $expectedQuery,
  880. $this->queryBuilder->getSQL()
  881. );
  882. }
  883. public function dataAndHaving() {
  884. return [
  885. [['condition2'], new CompositeExpression('AND', ['condition1', 'condition2']), 'HAVING (condition1) AND (condition2)'],
  886. [['condition2', 'condition3'], new CompositeExpression('AND', ['condition1', 'condition2', 'condition3']), 'HAVING (condition1) AND (condition2) AND (condition3)'],
  887. [
  888. [new CompositeExpression('OR', ['condition2', 'condition3'])],
  889. new CompositeExpression('AND', ['condition1', new CompositeExpression('OR', ['condition2', 'condition3'])]),
  890. 'HAVING (condition1) AND ((condition2) OR (condition3))'
  891. ],
  892. [
  893. [new CompositeExpression('AND', ['condition2', 'condition3'])],
  894. new CompositeExpression('AND', ['condition1', new CompositeExpression('AND', ['condition2', 'condition3'])]),
  895. 'HAVING (condition1) AND ((condition2) AND (condition3))'
  896. ],
  897. ];
  898. }
  899. /**
  900. * @dataProvider dataAndHaving
  901. *
  902. * @param array $havingArguments
  903. * @param array $expectedQueryPart
  904. * @param string $expectedQuery
  905. */
  906. public function testAndHaving($havingArguments, $expectedQueryPart, $expectedQuery) {
  907. $this->queryBuilder->having('condition1');
  908. call_user_func_array(
  909. [$this->queryBuilder, 'andHaving'],
  910. $havingArguments
  911. );
  912. $this->assertEquals(
  913. $expectedQueryPart,
  914. $this->queryBuilder->getQueryPart('having')
  915. );
  916. $this->assertSame(
  917. 'SELECT ' . $expectedQuery,
  918. $this->queryBuilder->getSQL()
  919. );
  920. }
  921. public function dataOrHaving() {
  922. return [
  923. [['condition2'], new CompositeExpression('OR', ['condition1', 'condition2']), 'HAVING (condition1) OR (condition2)'],
  924. [['condition2', 'condition3'], new CompositeExpression('OR', ['condition1', 'condition2', 'condition3']), 'HAVING (condition1) OR (condition2) OR (condition3)'],
  925. [
  926. [new CompositeExpression('OR', ['condition2', 'condition3'])],
  927. new CompositeExpression('OR', ['condition1', new CompositeExpression('OR', ['condition2', 'condition3'])]),
  928. 'HAVING (condition1) OR ((condition2) OR (condition3))'
  929. ],
  930. [
  931. [new CompositeExpression('AND', ['condition2', 'condition3'])],
  932. new CompositeExpression('OR', ['condition1', new CompositeExpression('AND', ['condition2', 'condition3'])]),
  933. 'HAVING (condition1) OR ((condition2) AND (condition3))'
  934. ],
  935. ];
  936. }
  937. /**
  938. * @dataProvider dataOrHaving
  939. *
  940. * @param array $havingArguments
  941. * @param array $expectedQueryPart
  942. * @param string $expectedQuery
  943. */
  944. public function testOrHaving($havingArguments, $expectedQueryPart, $expectedQuery) {
  945. $this->queryBuilder->having('condition1');
  946. call_user_func_array(
  947. [$this->queryBuilder, 'orHaving'],
  948. $havingArguments
  949. );
  950. $this->assertEquals(
  951. $expectedQueryPart,
  952. $this->queryBuilder->getQueryPart('having')
  953. );
  954. $this->assertSame(
  955. 'SELECT ' . $expectedQuery,
  956. $this->queryBuilder->getSQL()
  957. );
  958. }
  959. public function dataOrderBy() {
  960. return [
  961. ['column', null, ['`column` ASC'], 'ORDER BY `column` ASC'],
  962. ['column', 'ASC', ['`column` ASC'], 'ORDER BY `column` ASC'],
  963. ['column', 'DESC', ['`column` DESC'], 'ORDER BY `column` DESC'],
  964. ];
  965. }
  966. /**
  967. * @dataProvider dataOrderBy
  968. *
  969. * @param string $sort
  970. * @param string $order
  971. * @param array $expectedQueryPart
  972. * @param string $expectedQuery
  973. */
  974. public function testOrderBy($sort, $order, $expectedQueryPart, $expectedQuery) {
  975. $this->queryBuilder->orderBy($sort, $order);
  976. $this->assertEquals(
  977. $expectedQueryPart,
  978. $this->queryBuilder->getQueryPart('orderBy')
  979. );
  980. $this->assertSame(
  981. 'SELECT ' . $expectedQuery,
  982. $this->queryBuilder->getSQL()
  983. );
  984. }
  985. public function dataAddOrderBy() {
  986. return [
  987. ['column2', null, null, ['`column1` ASC', '`column2` ASC'], 'ORDER BY `column1` ASC, `column2` ASC'],
  988. ['column2', null, 'ASC', ['`column1` ASC', '`column2` ASC'], 'ORDER BY `column1` ASC, `column2` ASC'],
  989. ['column2', null, 'DESC', ['`column1` DESC', '`column2` ASC'], 'ORDER BY `column1` DESC, `column2` ASC'],
  990. ['column2', 'ASC', null, ['`column1` ASC', '`column2` ASC'], 'ORDER BY `column1` ASC, `column2` ASC'],
  991. ['column2', 'ASC', 'ASC', ['`column1` ASC', '`column2` ASC'], 'ORDER BY `column1` ASC, `column2` ASC'],
  992. ['column2', 'ASC', 'DESC', ['`column1` DESC', '`column2` ASC'], 'ORDER BY `column1` DESC, `column2` ASC'],
  993. ['column2', 'DESC', null, ['`column1` ASC', '`column2` DESC'], 'ORDER BY `column1` ASC, `column2` DESC'],
  994. ['column2', 'DESC', 'ASC', ['`column1` ASC', '`column2` DESC'], 'ORDER BY `column1` ASC, `column2` DESC'],
  995. ['column2', 'DESC', 'DESC', ['`column1` DESC', '`column2` DESC'], 'ORDER BY `column1` DESC, `column2` DESC'],
  996. ];
  997. }
  998. /**
  999. * @dataProvider dataAddOrderBy
  1000. *
  1001. * @param string $sort2
  1002. * @param string $order2
  1003. * @param string $order1
  1004. * @param array $expectedQueryPart
  1005. * @param string $expectedQuery
  1006. */
  1007. public function testAddOrderBy($sort2, $order2, $order1, $expectedQueryPart, $expectedQuery) {
  1008. $this->queryBuilder->orderBy('column1', $order1);
  1009. $this->queryBuilder->addOrderBy($sort2, $order2);
  1010. $this->assertEquals(
  1011. $expectedQueryPart,
  1012. $this->queryBuilder->getQueryPart('orderBy')
  1013. );
  1014. $this->assertSame(
  1015. 'SELECT ' . $expectedQuery,
  1016. $this->queryBuilder->getSQL()
  1017. );
  1018. }
  1019. public function testGetLastInsertId() {
  1020. $qB = $this->connection->getQueryBuilder();
  1021. try {
  1022. $qB->getLastInsertId();
  1023. $this->fail('getLastInsertId() should throw an exception, when being called before insert()');
  1024. } catch (\BadMethodCallException $e) {
  1025. $this->addToAssertionCount(1);
  1026. }
  1027. $qB->insert('properties')
  1028. ->values([
  1029. 'userid' => $qB->expr()->literal('testFirstResult'),
  1030. 'propertypath' => $qB->expr()->literal('testing'),
  1031. 'propertyname' => $qB->expr()->literal('testing'),
  1032. 'propertyvalue' => $qB->expr()->literal('testing'),
  1033. ])
  1034. ->execute();
  1035. $actual = $qB->getLastInsertId();
  1036. $this->assertNotNull($actual);
  1037. $this->assertIsInt($actual);
  1038. $this->assertEquals($this->connection->lastInsertId('*PREFIX*properties'), $actual);
  1039. $qB->delete('properties')
  1040. ->where($qB->expr()->eq('userid', $qB->expr()->literal('testFirstResult')))
  1041. ->execute();
  1042. try {
  1043. $qB->getLastInsertId();
  1044. $this->fail('getLastInsertId() should throw an exception, when being called after delete()');
  1045. } catch (\BadMethodCallException $e) {
  1046. $this->addToAssertionCount(1);
  1047. }
  1048. }
  1049. public function dataGetTableName() {
  1050. $config = $this->createMock(SystemConfig::class);
  1051. $logger = $this->createMock(LoggerInterface::class);
  1052. $qb = new QueryBuilder(\OC::$server->getDatabaseConnection(), $config, $logger);
  1053. return [
  1054. ['*PREFIX*table', null, '`*PREFIX*table`'],
  1055. ['*PREFIX*table', true, '`*PREFIX*table`'],
  1056. ['*PREFIX*table', false, '`*PREFIX*table`'],
  1057. ['table', null, '`*PREFIX*table`'],
  1058. ['table', true, '`*PREFIX*table`'],
  1059. ['table', false, '`table`'],
  1060. [$qb->createFunction('(' . $qb->select('*')->from('table')->getSQL() . ')'), null, '(SELECT * FROM `*PREFIX*table`)'],
  1061. [$qb->createFunction('(' . $qb->select('*')->from('table')->getSQL() . ')'), true, '(SELECT * FROM `*PREFIX*table`)'],
  1062. [$qb->createFunction('(' . $qb->select('*')->from('table')->getSQL() . ')'), false, '(SELECT * FROM `*PREFIX*table`)'],
  1063. ];
  1064. }
  1065. /**
  1066. * @dataProvider dataGetTableName
  1067. *
  1068. * @param string|IQueryFunction $tableName
  1069. * @param bool $automatic
  1070. * @param string $expected
  1071. */
  1072. public function testGetTableName($tableName, $automatic, $expected) {
  1073. if ($automatic !== null) {
  1074. $this->queryBuilder->automaticTablePrefix($automatic);
  1075. }
  1076. $this->assertSame(
  1077. $expected,
  1078. $this->queryBuilder->getTableName($tableName)
  1079. );
  1080. }
  1081. public function dataGetColumnName() {
  1082. return [
  1083. ['column', '', '`column`'],
  1084. ['column', 'a', '`a`.`column`'],
  1085. ];
  1086. }
  1087. /**
  1088. * @dataProvider dataGetColumnName
  1089. * @param string $column
  1090. * @param string $prefix
  1091. * @param string $expected
  1092. */
  1093. public function testGetColumnName($column, $prefix, $expected) {
  1094. $this->assertSame(
  1095. $expected,
  1096. $this->queryBuilder->getColumnName($column, $prefix)
  1097. );
  1098. }
  1099. public function testExecuteWithoutLogger() {
  1100. $queryBuilder = $this->createMock(\Doctrine\DBAL\Query\QueryBuilder::class);
  1101. $queryBuilder
  1102. ->expects($this->once())
  1103. ->method('execute')
  1104. ->willReturn(3);
  1105. $queryBuilder
  1106. ->expects($this->any())
  1107. ->method('getParameters')
  1108. ->willReturn([]);
  1109. $this->logger
  1110. ->expects($this->never())
  1111. ->method('debug');
  1112. $this->config
  1113. ->expects($this->once())
  1114. ->method('getValue')
  1115. ->with('log_query', false)
  1116. ->willReturn(false);
  1117. $this->invokePrivate($this->queryBuilder, 'queryBuilder', [$queryBuilder]);
  1118. $this->assertEquals(3, $this->queryBuilder->execute());
  1119. }
  1120. public function testExecuteWithLoggerAndNamedArray() {
  1121. $queryBuilder = $this->createMock(\Doctrine\DBAL\Query\QueryBuilder::class);
  1122. $queryBuilder
  1123. ->expects($this->any())
  1124. ->method('getParameters')
  1125. ->willReturn([
  1126. 'foo' => 'bar',
  1127. 'key' => 'value',
  1128. ]);
  1129. $queryBuilder
  1130. ->expects($this->any())
  1131. ->method('getSQL')
  1132. ->willReturn('SELECT * FROM FOO WHERE BAR = ?');
  1133. $queryBuilder
  1134. ->expects($this->once())
  1135. ->method('execute')
  1136. ->willReturn(3);
  1137. $this->logger
  1138. ->expects($this->once())
  1139. ->method('debug')
  1140. ->with(
  1141. 'DB QueryBuilder: \'{query}\' with parameters: {params}',
  1142. [
  1143. 'query' => 'SELECT * FROM FOO WHERE BAR = ?',
  1144. 'params' => 'foo => \'bar\', key => \'value\'',
  1145. 'app' => 'core',
  1146. ]
  1147. );
  1148. $this->config
  1149. ->expects($this->once())
  1150. ->method('getValue')
  1151. ->with('log_query', false)
  1152. ->willReturn(true);
  1153. $this->invokePrivate($this->queryBuilder, 'queryBuilder', [$queryBuilder]);
  1154. $this->assertEquals(3, $this->queryBuilder->execute());
  1155. }
  1156. public function testExecuteWithLoggerAndUnnamedArray() {
  1157. $queryBuilder = $this->createMock(\Doctrine\DBAL\Query\QueryBuilder::class);
  1158. $queryBuilder
  1159. ->expects($this->any())
  1160. ->method('getParameters')
  1161. ->willReturn(['Bar']);
  1162. $queryBuilder
  1163. ->expects($this->any())
  1164. ->method('getSQL')
  1165. ->willReturn('SELECT * FROM FOO WHERE BAR = ?');
  1166. $queryBuilder
  1167. ->expects($this->once())
  1168. ->method('execute')
  1169. ->willReturn(3);
  1170. $this->logger
  1171. ->expects($this->once())
  1172. ->method('debug')
  1173. ->with(
  1174. 'DB QueryBuilder: \'{query}\' with parameters: {params}',
  1175. [
  1176. 'query' => 'SELECT * FROM FOO WHERE BAR = ?',
  1177. 'params' => '0 => \'Bar\'',
  1178. 'app' => 'core',
  1179. ]
  1180. );
  1181. $this->config
  1182. ->expects($this->once())
  1183. ->method('getValue')
  1184. ->with('log_query', false)
  1185. ->willReturn(true);
  1186. $this->invokePrivate($this->queryBuilder, 'queryBuilder', [$queryBuilder]);
  1187. $this->assertEquals(3, $this->queryBuilder->execute());
  1188. }
  1189. public function testExecuteWithLoggerAndNoParams() {
  1190. $queryBuilder = $this->createMock(\Doctrine\DBAL\Query\QueryBuilder::class);
  1191. $queryBuilder
  1192. ->expects($this->any())
  1193. ->method('getParameters')
  1194. ->willReturn([]);
  1195. $queryBuilder
  1196. ->expects($this->any())
  1197. ->method('getSQL')
  1198. ->willReturn('SELECT * FROM FOO WHERE BAR = ?');
  1199. $queryBuilder
  1200. ->expects($this->once())
  1201. ->method('execute')
  1202. ->willReturn(3);
  1203. $this->logger
  1204. ->expects($this->once())
  1205. ->method('debug')
  1206. ->with(
  1207. 'DB QueryBuilder: \'{query}\'',
  1208. [
  1209. 'query' => 'SELECT * FROM FOO WHERE BAR = ?',
  1210. 'app' => 'core',
  1211. ]
  1212. );
  1213. $this->config
  1214. ->expects($this->once())
  1215. ->method('getValue')
  1216. ->with('log_query', false)
  1217. ->willReturn(true);
  1218. $this->invokePrivate($this->queryBuilder, 'queryBuilder', [$queryBuilder]);
  1219. $this->assertEquals(3, $this->queryBuilder->execute());
  1220. }
  1221. public function testExecuteWithParameterTooLarge() {
  1222. $queryBuilder = $this->createMock(\Doctrine\DBAL\Query\QueryBuilder::class);
  1223. $p = array_fill(0, 1001, 'foo');
  1224. $queryBuilder
  1225. ->expects($this->any())
  1226. ->method('getParameters')
  1227. ->willReturn([$p]);
  1228. $queryBuilder
  1229. ->expects($this->any())
  1230. ->method('getSQL')
  1231. ->willReturn('SELECT * FROM FOO WHERE BAR IN (?)');
  1232. $queryBuilder
  1233. ->expects($this->once())
  1234. ->method('execute')
  1235. ->willReturn($this->createMock(Result::class));
  1236. $this->logger
  1237. ->expects($this->once())
  1238. ->method('error')
  1239. ->willReturnCallback(function ($message, $parameters) {
  1240. $this->assertInstanceOf(QueryException::class, $parameters['exception']);
  1241. $this->assertSame(
  1242. 'More than 1000 expressions in a list are not allowed on Oracle.',
  1243. $message
  1244. );
  1245. });
  1246. $this->config
  1247. ->expects($this->once())
  1248. ->method('getValue')
  1249. ->with('log_query', false)
  1250. ->willReturn(false);
  1251. $this->invokePrivate($this->queryBuilder, 'queryBuilder', [$queryBuilder]);
  1252. $this->queryBuilder->execute();
  1253. }
  1254. public function testExecuteWithParametersTooMany() {
  1255. $queryBuilder = $this->createMock(\Doctrine\DBAL\Query\QueryBuilder::class);
  1256. $p = array_fill(0, 999, 'foo');
  1257. $queryBuilder
  1258. ->expects($this->any())
  1259. ->method('getParameters')
  1260. ->willReturn(array_fill(0, 66, $p));
  1261. $queryBuilder
  1262. ->expects($this->any())
  1263. ->method('getSQL')
  1264. ->willReturn('SELECT * FROM FOO WHERE BAR IN (?) OR BAR IN (?)');
  1265. $queryBuilder
  1266. ->expects($this->once())
  1267. ->method('execute')
  1268. ->willReturn($this->createMock(Result::class));
  1269. $this->logger
  1270. ->expects($this->once())
  1271. ->method('error')
  1272. ->willReturnCallback(function ($message, $parameters) {
  1273. $this->assertInstanceOf(QueryException::class, $parameters['exception']);
  1274. $this->assertSame(
  1275. 'The number of parameters must not exceed 65535. Restriction by PostgreSQL.',
  1276. $message
  1277. );
  1278. });
  1279. $this->config
  1280. ->expects($this->once())
  1281. ->method('getValue')
  1282. ->with('log_query', false)
  1283. ->willReturn(false);
  1284. $this->invokePrivate($this->queryBuilder, 'queryBuilder', [$queryBuilder]);
  1285. $this->queryBuilder->execute();
  1286. }
  1287. }