SqlserverTest.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  5. * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  6. *
  7. * Licensed under The MIT License
  8. * For full copyright and license information, please see the LICENSE.txt
  9. * Redistributions of files must retain the above copyright notice.
  10. *
  11. * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  12. * @link https://cakephp.org CakePHP(tm) Project
  13. * @since 3.0.0
  14. * @license https://opensource.org/licenses/mit-license.php MIT License
  15. */
  16. namespace Cake\Test\TestCase\Database\Driver;
  17. use Cake\Database\Driver\Sqlserver;
  18. use Cake\Database\DriverInterface;
  19. use Cake\Database\Exception\MissingConnectionException;
  20. use Cake\Database\Query;
  21. use Cake\Datasource\ConnectionManager;
  22. use Cake\TestSuite\TestCase;
  23. use InvalidArgumentException;
  24. use PDO;
  25. /**
  26. * Tests Sqlserver driver
  27. */
  28. class SqlserverTest extends TestCase
  29. {
  30. /**
  31. * @var bool
  32. */
  33. protected $missingExtension;
  34. /**
  35. * Set up
  36. */
  37. public function setUp(): void
  38. {
  39. parent::setUp();
  40. $this->missingExtension = !defined('PDO::SQLSRV_ENCODING_UTF8');
  41. }
  42. /**
  43. * data provider for testDnsString
  44. *
  45. * @return array
  46. */
  47. public function dnsStringDataProvider(): array
  48. {
  49. return [
  50. [
  51. [
  52. 'app' => 'CakePHP-Testapp',
  53. 'encoding' => '',
  54. 'connectionPooling' => true,
  55. 'failoverPartner' => 'failover.local',
  56. 'loginTimeout' => 10,
  57. 'multiSubnetFailover' => 'failover.local',
  58. ],
  59. 'sqlsrv:Server=localhost\SQLEXPRESS;Database=cake;MultipleActiveResultSets=false;APP=CakePHP-Testapp;ConnectionPooling=1;Failover_Partner=failover.local;LoginTimeout=10;MultiSubnetFailover=failover.local',
  60. ],
  61. [
  62. [
  63. 'app' => 'CakePHP-Testapp',
  64. 'encoding' => '',
  65. 'failoverPartner' => 'failover.local',
  66. 'multiSubnetFailover' => 'failover.local',
  67. ],
  68. 'sqlsrv:Server=localhost\SQLEXPRESS;Database=cake;MultipleActiveResultSets=false;APP=CakePHP-Testapp;Failover_Partner=failover.local;MultiSubnetFailover=failover.local',
  69. ],
  70. [
  71. [
  72. 'encoding' => '',
  73. ],
  74. 'sqlsrv:Server=localhost\SQLEXPRESS;Database=cake;MultipleActiveResultSets=false',
  75. ],
  76. [
  77. [
  78. 'app' => 'CakePHP-Testapp',
  79. 'encoding' => '',
  80. 'host' => 'localhost\SQLEXPRESS',
  81. 'port' => 9001,
  82. ],
  83. 'sqlsrv:Server=localhost\SQLEXPRESS,9001;Database=cake;MultipleActiveResultSets=false;APP=CakePHP-Testapp',
  84. ],
  85. ];
  86. }
  87. /**
  88. * Test if all options in dns string are set
  89. *
  90. * @dataProvider dnsStringDataProvider
  91. * @param array $constructorArgs
  92. * @param string $dnsString
  93. */
  94. public function testDnsString($constructorArgs, $dnsString): void
  95. {
  96. $driver = $this->getMockBuilder('Cake\Database\Driver\Sqlserver')
  97. ->onlyMethods(['createPdo'])
  98. ->setConstructorArgs([$constructorArgs])
  99. ->getMock();
  100. $driver->method('createPdo')
  101. ->with($this->callback(function ($dns) use ($dnsString) {
  102. $this->assertSame($dns, $dnsString);
  103. return true;
  104. }));
  105. $driver->connect();
  106. }
  107. /**
  108. * Test connecting to Sqlserver with custom configuration
  109. */
  110. public function testConnectionConfigCustom(): void
  111. {
  112. $this->skipIf($this->missingExtension, 'pdo_sqlsrv is not installed.');
  113. $config = [
  114. 'host' => 'foo',
  115. 'username' => 'Administrator',
  116. 'password' => 'blablabla',
  117. 'database' => 'bar',
  118. 'encoding' => 'a-language',
  119. 'flags' => [1 => true, 2 => false],
  120. 'init' => ['Execute this', 'this too'],
  121. 'settings' => ['config1' => 'value1', 'config2' => 'value2'],
  122. ];
  123. $driver = $this->getMockBuilder('Cake\Database\Driver\Sqlserver')
  124. ->onlyMethods(['createPdo', 'getPdo'])
  125. ->setConstructorArgs([$config])
  126. ->getMock();
  127. $dsn = 'sqlsrv:Server=foo;Database=bar;MultipleActiveResultSets=false';
  128. $expected = $config;
  129. $expected['flags'] += [
  130. PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
  131. PDO::SQLSRV_ATTR_ENCODING => 'a-language',
  132. ];
  133. $expected['attributes'] = [];
  134. $expected['app'] = null;
  135. $expected['connectionPooling'] = null;
  136. $expected['failoverPartner'] = null;
  137. $expected['loginTimeout'] = null;
  138. $expected['multiSubnetFailover'] = null;
  139. $expected['port'] = null;
  140. $expected['log'] = false;
  141. $connection = $this->getMockBuilder('PDO')
  142. ->disableOriginalConstructor()
  143. ->onlyMethods(['exec', 'quote'])
  144. ->getMock();
  145. $connection->expects($this->any())
  146. ->method('quote')
  147. ->will($this->onConsecutiveCalls(
  148. $this->returnArgument(0),
  149. $this->returnArgument(0),
  150. $this->returnArgument(0)
  151. ));
  152. $connection->expects($this->exactly(4))
  153. ->method('exec')
  154. ->withConsecutive(
  155. ['Execute this'],
  156. ['this too'],
  157. ['SET config1 value1'],
  158. ['SET config2 value2']
  159. );
  160. $driver->expects($this->once())->method('createPdo')
  161. ->with($dsn, $expected)
  162. ->will($this->returnValue($connection));
  163. $driver->connect();
  164. }
  165. /**
  166. * Test connecting to Sqlserver with persistent set to false
  167. */
  168. public function testConnectionPersistentFalse(): void
  169. {
  170. $this->skipIf($this->missingExtension, 'pdo_sqlsrv is not installed.');
  171. $driver = new Sqlserver([
  172. 'persistent' => false,
  173. 'host' => 'shouldnotexist',
  174. 'username' => 'Administrator',
  175. 'password' => 'blablabla',
  176. 'database' => 'bar',
  177. 'loginTimeout' => 1,
  178. ]);
  179. // This should not throw an InvalidArgumentException because
  180. // persistent is false (the default).
  181. $this->expectException(MissingConnectionException::class);
  182. $driver->connect();
  183. }
  184. /**
  185. * Test if attempting to connect with the driver throws an exception when
  186. * using an invalid config setting.
  187. */
  188. public function testConnectionPersistentTrueException(): void
  189. {
  190. $this->skipIf($this->missingExtension, 'pdo_sqlsrv is not installed.');
  191. $driver = new Sqlserver([
  192. 'persistent' => true,
  193. 'host' => 'shouldnotexist',
  194. 'username' => 'Administrator',
  195. 'password' => 'blablabla',
  196. 'database' => 'bar',
  197. 'loginTimeout' => 1,
  198. ]);
  199. $this->expectException(InvalidArgumentException::class);
  200. $this->expectExceptionMessage('Config setting "persistent" cannot be set to true, as the Sqlserver PDO driver does not support PDO::ATTR_PERSISTENT');
  201. $driver->connect();
  202. }
  203. /**
  204. * Test select with limit only and SQLServer2012+
  205. */
  206. public function testSelectLimitVersion12(): void
  207. {
  208. $driver = $this->getMockBuilder('Cake\Database\Driver\Sqlserver')
  209. ->onlyMethods(['createPdo', 'getPdo', 'version', 'enabled'])
  210. ->setConstructorArgs([[]])
  211. ->getMock();
  212. $driver->method('version')
  213. ->will($this->returnValue('12'));
  214. $driver->method('enabled')
  215. ->will($this->returnValue(true));
  216. $connection = $this->getMockBuilder('Cake\Database\Connection')
  217. ->onlyMethods(['connect'])
  218. ->setConstructorArgs([['driver' => $driver, 'log' => false]])
  219. ->getMock();
  220. $query = new Query($connection);
  221. $query->select(['id', 'title'])
  222. ->from('articles')
  223. ->order(['id'])
  224. ->offset(10);
  225. $this->assertSame('SELECT id, title FROM articles ORDER BY id OFFSET 10 ROWS', $query->sql());
  226. $query = new Query($connection);
  227. $query->select(['id', 'title'])
  228. ->from('articles')
  229. ->order(['id'])
  230. ->limit(10)
  231. ->offset(50);
  232. $this->assertSame('SELECT id, title FROM articles ORDER BY id OFFSET 50 ROWS FETCH FIRST 10 ROWS ONLY', $query->sql());
  233. $query = new Query($connection);
  234. $query->select(['id', 'title'])
  235. ->from('articles')
  236. ->offset(10);
  237. $this->assertSame('SELECT id, title FROM articles ORDER BY (SELECT NULL) OFFSET 10 ROWS', $query->sql());
  238. $query = new Query($connection);
  239. $query->select(['id', 'title'])
  240. ->from('articles')
  241. ->limit(10);
  242. $this->assertSame('SELECT TOP 10 id, title FROM articles', $query->sql());
  243. }
  244. /**
  245. * Test select with limit on lte SQLServer2008
  246. */
  247. public function testSelectLimitOldServer(): void
  248. {
  249. $driver = $this->getMockBuilder('Cake\Database\Driver\Sqlserver')
  250. ->onlyMethods(['createPdo', 'getPdo', 'version', 'enabled'])
  251. ->setConstructorArgs([[]])
  252. ->getMock();
  253. $driver->expects($this->any())
  254. ->method('version')
  255. ->will($this->returnValue('8'));
  256. $driver->method('enabled')
  257. ->will($this->returnValue(true));
  258. $connection = $this->getMockBuilder('Cake\Database\Connection')
  259. ->onlyMethods(['connect'])
  260. ->setConstructorArgs([['driver' => $driver, 'log' => false]])
  261. ->getMock();
  262. $query = new Query($connection);
  263. $query->select(['id', 'title'])
  264. ->from('articles')
  265. ->limit(10);
  266. $expected = 'SELECT TOP 10 id, title FROM articles';
  267. $this->assertSame($expected, $query->sql());
  268. $query = new Query($connection);
  269. $query->select(['id', 'title'])
  270. ->from('articles')
  271. ->offset(10);
  272. $identifier = '_cake_page_rownum_';
  273. if ($connection->getDriver()->isAutoQuotingEnabled()) {
  274. $identifier = $connection->getDriver()->quoteIdentifier($identifier);
  275. }
  276. $expected = 'SELECT * FROM (SELECT id, title, (ROW_NUMBER() OVER (ORDER BY (SELECT NULL))) AS ' . $identifier . ' ' .
  277. 'FROM articles) _cake_paging_ ' .
  278. 'WHERE _cake_paging_._cake_page_rownum_ > 10';
  279. $this->assertSame($expected, $query->sql());
  280. $query = new Query($connection);
  281. $query->select(['id', 'title'])
  282. ->from('articles')
  283. ->order(['id'])
  284. ->offset(10);
  285. $expected = 'SELECT * FROM (SELECT id, title, (ROW_NUMBER() OVER (ORDER BY id)) AS ' . $identifier . ' ' .
  286. 'FROM articles) _cake_paging_ ' .
  287. 'WHERE _cake_paging_._cake_page_rownum_ > 10';
  288. $this->assertSame($expected, $query->sql());
  289. $query = new Query($connection);
  290. $query->select(['id', 'title'])
  291. ->from('articles')
  292. ->order(['id'])
  293. ->where(['title' => 'Something'])
  294. ->limit(10)
  295. ->offset(50);
  296. $expected = 'SELECT * FROM (SELECT id, title, (ROW_NUMBER() OVER (ORDER BY id)) AS ' . $identifier . ' ' .
  297. 'FROM articles WHERE title = :c0) _cake_paging_ ' .
  298. 'WHERE (_cake_paging_._cake_page_rownum_ > 50 AND _cake_paging_._cake_page_rownum_ <= 60)';
  299. $this->assertSame($expected, $query->sql());
  300. $query = new Query($connection);
  301. $subquery = new Query($connection);
  302. $subquery->select(1);
  303. $query
  304. ->select([
  305. 'id',
  306. 'computed' => $subquery,
  307. ])
  308. ->from('articles')
  309. ->order([
  310. 'computed' => 'ASC',
  311. ])
  312. ->offset(10);
  313. $expected =
  314. 'SELECT * FROM (' .
  315. 'SELECT id, (SELECT 1) AS computed, ' .
  316. '(ROW_NUMBER() OVER (ORDER BY (SELECT 1) ASC)) AS _cake_page_rownum_ FROM articles' .
  317. ') _cake_paging_ ' .
  318. 'WHERE _cake_paging_._cake_page_rownum_ > 10';
  319. $this->assertSame($expected, $query->sql());
  320. $subqueryA = new Query($connection);
  321. $subqueryA
  322. ->select('count(*)')
  323. ->from(['a' => 'articles'])
  324. ->where([
  325. 'a.id = articles.id',
  326. 'a.published' => 'Y',
  327. ]);
  328. $subqueryB = new Query($connection);
  329. $subqueryB
  330. ->select('count(*)')
  331. ->from(['b' => 'articles'])
  332. ->where([
  333. 'b.id = articles.id',
  334. 'b.published' => 'N',
  335. ]);
  336. $query = new Query($connection);
  337. $query
  338. ->select([
  339. 'id',
  340. 'computedA' => $subqueryA,
  341. 'computedB' => $subqueryB,
  342. ])
  343. ->from('articles')
  344. ->order([
  345. 'computedA' => 'ASC',
  346. ])
  347. ->offset(10);
  348. $this->assertSame(
  349. 'SELECT * FROM (' .
  350. 'SELECT id, ' .
  351. '(SELECT count(*) FROM articles a WHERE (a.id = articles.id AND a.published = :c0)) AS computedA, ' .
  352. '(SELECT count(*) FROM articles b WHERE (b.id = articles.id AND b.published = :c1)) AS computedB, ' .
  353. '(ROW_NUMBER() OVER (ORDER BY (SELECT count(*) FROM articles a WHERE (a.id = articles.id AND a.published = :c2)) ASC)) AS _cake_page_rownum_ FROM articles' .
  354. ') _cake_paging_ ' .
  355. 'WHERE _cake_paging_._cake_page_rownum_ > 10',
  356. $query->sql()
  357. );
  358. }
  359. /**
  360. * Test that insert queries have results available to them.
  361. */
  362. public function testInsertUsesOutput(): void
  363. {
  364. $driver = $this->getMockBuilder('Cake\Database\Driver\Sqlserver')
  365. ->onlyMethods(['createPdo', 'getPdo', 'enabled'])
  366. ->setConstructorArgs([[]])
  367. ->getMock();
  368. $driver->method('enabled')
  369. ->will($this->returnValue(true));
  370. $connection = $this->getMockBuilder('Cake\Database\Connection')
  371. ->onlyMethods(['connect'])
  372. ->setConstructorArgs([['driver' => $driver, 'log' => false]])
  373. ->getMock();
  374. $query = new Query($connection);
  375. $query->insert(['title'])
  376. ->into('articles')
  377. ->values(['title' => 'A new article']);
  378. $expected = 'INSERT INTO articles (title) OUTPUT INSERTED.* VALUES (:c0)';
  379. $this->assertSame($expected, $query->sql());
  380. }
  381. /**
  382. * Test that having queries replace the aggregated alias field.
  383. */
  384. public function testHavingReplacesAlias(): void
  385. {
  386. $driver = $this->getMockBuilder('Cake\Database\Driver\Sqlserver')
  387. ->onlyMethods(['connect', 'getPdo', 'version', 'enabled'])
  388. ->setConstructorArgs([[]])
  389. ->getMock();
  390. $driver->expects($this->any())
  391. ->method('version')
  392. ->will($this->returnValue('8'));
  393. $driver->method('enabled')
  394. ->will($this->returnValue(true));
  395. $connection = $this->getMockBuilder('\Cake\Database\Connection')
  396. ->onlyMethods(['connect'])
  397. ->setConstructorArgs([['driver' => $driver, 'log' => false]])
  398. ->getMock();
  399. $query = new Query($connection);
  400. $query
  401. ->select([
  402. 'posts.author_id',
  403. 'post_count' => $query->func()->count('posts.id'),
  404. ])
  405. ->group(['posts.author_id'])
  406. ->having([$query->newExpr()->gte('post_count', 2, 'integer')]);
  407. $expected = 'SELECT posts.author_id, (COUNT(posts.id)) AS post_count ' .
  408. 'GROUP BY posts.author_id HAVING COUNT(posts.id) >= :c0';
  409. $this->assertSame($expected, $query->sql());
  410. }
  411. /**
  412. * Test that having queries replaces nothing is no alias is used.
  413. */
  414. public function testHavingWhenNoAliasIsUsed(): void
  415. {
  416. $driver = $this->getMockBuilder('Cake\Database\Driver\Sqlserver')
  417. ->onlyMethods(['connect', 'getPdo', 'version', 'enabled'])
  418. ->setConstructorArgs([[]])
  419. ->getMock();
  420. $driver->expects($this->any())
  421. ->method('version')
  422. ->will($this->returnValue('8'));
  423. $driver->method('enabled')
  424. ->will($this->returnValue(true));
  425. $connection = $this->getMockBuilder('\Cake\Database\Connection')
  426. ->onlyMethods(['connect'])
  427. ->setConstructorArgs([['driver' => $driver, 'log' => false]])
  428. ->getMock();
  429. $query = new Query($connection);
  430. $query
  431. ->select([
  432. 'posts.author_id',
  433. 'post_count' => $query->func()->count('posts.id'),
  434. ])
  435. ->group(['posts.author_id'])
  436. ->having([$query->newExpr()->gte('posts.author_id', 2, 'integer')]);
  437. $expected = 'SELECT posts.author_id, (COUNT(posts.id)) AS post_count ' .
  438. 'GROUP BY posts.author_id HAVING posts.author_id >= :c0';
  439. $this->assertSame($expected, $query->sql());
  440. }
  441. public function testExceedingMaxParameters(): void
  442. {
  443. $connection = ConnectionManager::get('test');
  444. $this->skipIf(!$connection->getDriver() instanceof Sqlserver);
  445. $query = $connection->newQuery()
  446. ->from('articles')
  447. ->whereInList('id', range(0, 2100));
  448. $this->expectException(InvalidArgumentException::class);
  449. $this->expectExceptionMessage(
  450. 'Exceeded maximum number of parameters (2100) for prepared statements in Sql Server'
  451. );
  452. $connection->getDriver()->prepare($query);
  453. }
  454. /**
  455. * Tests driver-specific feature support check.
  456. */
  457. public function testSupports(): void
  458. {
  459. $driver = ConnectionManager::get('test')->getDriver();
  460. $this->skipIf(!$driver instanceof Sqlserver);
  461. $this->assertTrue($driver->supports(DriverInterface::FEATURE_CTE));
  462. $this->assertFalse($driver->supports(DriverInterface::FEATURE_JSON));
  463. $this->assertTrue($driver->supports(DriverInterface::FEATURE_SAVEPOINT));
  464. $this->assertTrue($driver->supports(DriverInterface::FEATURE_QUOTE));
  465. $this->assertTrue($driver->supports(DriverInterface::FEATURE_WINDOW));
  466. $this->assertFalse($driver->supports('this-is-fake'));
  467. }
  468. }