SqlserverTest.php 18 KB

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