SqlserverTest.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  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\Exception\MissingConnectionException;
  18. use Cake\Database\Query;
  19. use Cake\TestSuite\TestCase;
  20. use PDO;
  21. /**
  22. * Tests Sqlserver driver
  23. */
  24. class SqlserverTest extends TestCase
  25. {
  26. /**
  27. * Set up
  28. *
  29. * @return void
  30. */
  31. public function setUp(): void
  32. {
  33. parent::setUp();
  34. $this->missingExtension = !defined('PDO::SQLSRV_ENCODING_UTF8');
  35. }
  36. /**
  37. * data provider for testDnsString
  38. *
  39. * @return array
  40. */
  41. public function dnsStringDataProvider()
  42. {
  43. return [
  44. [
  45. [
  46. 'app' => 'CakePHP-Testapp',
  47. 'encoding' => '',
  48. 'connectionPooling' => true,
  49. 'failoverPartner' => 'failover.local',
  50. 'loginTimeout' => 10,
  51. 'multiSubnetFailover' => 'failover.local',
  52. ],
  53. 'sqlsrv:Server=localhost\SQLEXPRESS;Database=cake;MultipleActiveResultSets=false;APP=CakePHP-Testapp;ConnectionPooling=1;Failover_Partner=failover.local;LoginTimeout=10;MultiSubnetFailover=failover.local',
  54. ],
  55. [
  56. [
  57. 'app' => 'CakePHP-Testapp',
  58. 'encoding' => '',
  59. 'failoverPartner' => 'failover.local',
  60. 'multiSubnetFailover' => 'failover.local',
  61. ],
  62. 'sqlsrv:Server=localhost\SQLEXPRESS;Database=cake;MultipleActiveResultSets=false;APP=CakePHP-Testapp;Failover_Partner=failover.local;MultiSubnetFailover=failover.local',
  63. ],
  64. [
  65. [
  66. 'encoding' => '',
  67. ],
  68. 'sqlsrv:Server=localhost\SQLEXPRESS;Database=cake;MultipleActiveResultSets=false',
  69. ],
  70. [
  71. [
  72. 'app' => 'CakePHP-Testapp',
  73. 'encoding' => '',
  74. 'host' => 'localhost\SQLEXPRESS',
  75. 'port' => 9001,
  76. ],
  77. 'sqlsrv:Server=localhost\SQLEXPRESS,9001;Database=cake;MultipleActiveResultSets=false;APP=CakePHP-Testapp',
  78. ],
  79. ];
  80. }
  81. /**
  82. * Test if all options in dns string are set
  83. *
  84. * @dataProvider dnsStringDataProvider
  85. * @param array $constructorArgs
  86. * @param string $dnsString
  87. * @return void
  88. */
  89. public function testDnsString($constructorArgs, $dnsString)
  90. {
  91. $driver = $this->getMockBuilder('Cake\Database\Driver\Sqlserver')
  92. ->setMethods(['_connect', 'getConnection'])
  93. ->setConstructorArgs([$constructorArgs])
  94. ->getMock();
  95. $driver->method('_connect')
  96. ->with($this->callback(function ($dns) use ($dnsString) {
  97. $this->assertSame($dns, $dnsString);
  98. return true;
  99. }))
  100. ->will($this->returnValue(true));
  101. $driver->method('getConnection')
  102. ->will($this->returnValue(null));
  103. $driver->connect();
  104. }
  105. /**
  106. * Test connecting to Sqlserver with custom configuration
  107. *
  108. * @return void
  109. */
  110. public function testConnectionConfigCustom()
  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. ->setMethods(['_connect', 'setConnection', 'getConnection'])
  125. ->setConstructorArgs([$config])
  126. ->getMock();
  127. $dsn = 'sqlsrv:Server=foo;Database=bar;MultipleActiveResultSets=false';
  128. $expected = $config;
  129. $expected['flags'] += [
  130. PDO::ATTR_EMULATE_PREPARES => false,
  131. PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
  132. PDO::SQLSRV_ATTR_ENCODING => 'a-language',
  133. ];
  134. $expected['attributes'] = [];
  135. $expected['app'] = null;
  136. $expected['connectionPooling'] = null;
  137. $expected['failoverPartner'] = null;
  138. $expected['loginTimeout'] = null;
  139. $expected['multiSubnetFailover'] = null;
  140. $expected['port'] = null;
  141. $connection = $this->getMockBuilder('stdClass')
  142. ->setMethods(['exec', 'quote'])
  143. ->getMock();
  144. $connection->expects($this->any())
  145. ->method('quote')
  146. ->will($this->onConsecutiveCalls(
  147. $this->returnArgument(0),
  148. $this->returnArgument(0),
  149. $this->returnArgument(0)
  150. ));
  151. $connection->expects($this->at(0))->method('exec')->with('Execute this');
  152. $connection->expects($this->at(1))->method('exec')->with('this too');
  153. $connection->expects($this->at(2))->method('exec')->with('SET config1 value1');
  154. $connection->expects($this->at(3))->method('exec')->with('SET config2 value2');
  155. $driver->setConnection($connection);
  156. $driver->expects($this->once())->method('_connect')
  157. ->with($dsn, $expected);
  158. $driver->expects($this->any())->method('getConnection')
  159. ->will($this->returnValue($connection));
  160. $driver->connect();
  161. }
  162. /**
  163. * Test connecting to Sqlserver with persistent set to false
  164. *
  165. * @return void
  166. */
  167. public function testConnectionPersistentFalse()
  168. {
  169. $this->skipIf($this->missingExtension, 'pdo_sqlsrv is not installed.');
  170. $config = [
  171. 'persistent' => false,
  172. 'host' => 'foo',
  173. 'username' => 'Administrator',
  174. 'password' => 'blablabla',
  175. 'database' => 'bar',
  176. 'encoding' => 'a-language',
  177. ];
  178. $driver = $this->getMockBuilder('Cake\Database\Driver\Sqlserver')
  179. ->setMethods(['_connect', 'connection'])
  180. ->setConstructorArgs([$config])
  181. ->getMock();
  182. $dsn = 'sqlsrv:Server=foo;Database=bar;MultipleActiveResultSets=false';
  183. $expected = $config;
  184. $expected['flags'] = [
  185. PDO::ATTR_EMULATE_PREPARES => false,
  186. PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
  187. PDO::SQLSRV_ATTR_ENCODING => 'a-language',
  188. ];
  189. $expected['attributes'] = [];
  190. $expected['settings'] = [];
  191. $expected['init'] = [];
  192. $expected['app'] = null;
  193. $expected['connectionPooling'] = null;
  194. $expected['failoverPartner'] = null;
  195. $expected['loginTimeout'] = null;
  196. $expected['multiSubnetFailover'] = null;
  197. $expected['port'] = null;
  198. $driver->expects($this->once())->method('_connect')
  199. ->with($dsn, $expected);
  200. $this->expectException(MissingConnectionException::class);
  201. $driver->connect();
  202. }
  203. /**
  204. * Test if attempting to connect with the driver throws an exception when
  205. * using an invalid config setting.
  206. *
  207. * @return void
  208. */
  209. public function testConnectionPersistentTrueException()
  210. {
  211. $this->expectException(\InvalidArgumentException::class);
  212. $this->expectExceptionMessage('Config setting "persistent" cannot be set to true, as the Sqlserver PDO driver does not support PDO::ATTR_PERSISTENT');
  213. $this->skipIf($this->missingExtension, 'pdo_sqlsrv is not installed.');
  214. $config = [
  215. 'persistent' => true,
  216. 'host' => 'foo',
  217. 'username' => 'Administrator',
  218. 'password' => 'blablabla',
  219. 'database' => 'bar',
  220. ];
  221. $driver = $this->getMockBuilder('Cake\Database\Driver\Sqlserver')
  222. ->setMethods(['_connect', 'connection'])
  223. ->setConstructorArgs([$config])
  224. ->getMock();
  225. $driver->connect();
  226. }
  227. /**
  228. * Test select with limit only and SQLServer2012+
  229. *
  230. * @return void
  231. */
  232. public function testSelectLimitVersion12()
  233. {
  234. $driver = $this->getMockBuilder('Cake\Database\Driver\Sqlserver')
  235. ->setMethods(['_connect', 'getConnection', 'version'])
  236. ->setConstructorArgs([[]])
  237. ->getMock();
  238. $driver->method('version')
  239. ->will($this->returnValue('12'));
  240. $connection = $this->getMockBuilder('Cake\Database\Connection')
  241. ->setMethods(['connect', 'getDriver', 'setDriver'])
  242. ->setConstructorArgs([['log' => false]])
  243. ->getMock();
  244. $connection->method('getDriver')
  245. ->will($this->returnValue($driver));
  246. $query = new Query($connection);
  247. $query->select(['id', 'title'])
  248. ->from('articles')
  249. ->order(['id'])
  250. ->offset(10);
  251. $this->assertSame('SELECT id, title FROM articles ORDER BY id OFFSET 10 ROWS', $query->sql());
  252. $query = new Query($connection);
  253. $query->select(['id', 'title'])
  254. ->from('articles')
  255. ->order(['id'])
  256. ->limit(10)
  257. ->offset(50);
  258. $this->assertSame('SELECT id, title FROM articles ORDER BY id OFFSET 50 ROWS FETCH FIRST 10 ROWS ONLY', $query->sql());
  259. $query = new Query($connection);
  260. $query->select(['id', 'title'])
  261. ->from('articles')
  262. ->offset(10);
  263. $this->assertSame('SELECT id, title FROM articles ORDER BY (SELECT NULL) OFFSET 10 ROWS', $query->sql());
  264. $query = new Query($connection);
  265. $query->select(['id', 'title'])
  266. ->from('articles')
  267. ->limit(10);
  268. $this->assertSame('SELECT TOP 10 id, title FROM articles', $query->sql());
  269. }
  270. /**
  271. * Test select with limit on lte SQLServer2008
  272. *
  273. * @return void
  274. */
  275. public function testSelectLimitOldServer()
  276. {
  277. $driver = $this->getMockBuilder('Cake\Database\Driver\Sqlserver')
  278. ->setMethods(['_connect', 'getConnection', 'version'])
  279. ->setConstructorArgs([[]])
  280. ->getMock();
  281. $driver->expects($this->any())
  282. ->method('version')
  283. ->will($this->returnValue('8'));
  284. $connection = $this->getMockBuilder('Cake\Database\Connection')
  285. ->setMethods(['connect', 'getDriver', 'setDriver'])
  286. ->setConstructorArgs([['log' => false]])
  287. ->getMock();
  288. $connection->expects($this->any())
  289. ->method('getDriver')
  290. ->will($this->returnValue($driver));
  291. $query = new Query($connection);
  292. $query->select(['id', 'title'])
  293. ->from('articles')
  294. ->limit(10);
  295. $expected = 'SELECT TOP 10 id, title FROM articles';
  296. $this->assertEquals($expected, $query->sql());
  297. $query = new Query($connection);
  298. $query->select(['id', 'title'])
  299. ->from('articles')
  300. ->offset(10);
  301. $expected = 'SELECT * FROM (SELECT id, title, (ROW_NUMBER() OVER (ORDER BY (SELECT NULL))) AS [_cake_page_rownum_] ' .
  302. 'FROM articles) _cake_paging_ ' .
  303. 'WHERE _cake_paging_._cake_page_rownum_ > 10';
  304. $this->assertEquals($expected, $query->sql());
  305. $query = new Query($connection);
  306. $query->select(['id', 'title'])
  307. ->from('articles')
  308. ->order(['id'])
  309. ->offset(10);
  310. $expected = 'SELECT * FROM (SELECT id, title, (ROW_NUMBER() OVER (ORDER BY id)) AS [_cake_page_rownum_] ' .
  311. 'FROM articles) _cake_paging_ ' .
  312. 'WHERE _cake_paging_._cake_page_rownum_ > 10';
  313. $this->assertEquals($expected, $query->sql());
  314. $query = new Query($connection);
  315. $query->select(['id', 'title'])
  316. ->from('articles')
  317. ->order(['id'])
  318. ->where(['title' => 'Something'])
  319. ->limit(10)
  320. ->offset(50);
  321. $expected = 'SELECT * FROM (SELECT id, title, (ROW_NUMBER() OVER (ORDER BY id)) AS [_cake_page_rownum_] ' .
  322. 'FROM articles WHERE title = :c0) _cake_paging_ ' .
  323. 'WHERE (_cake_paging_._cake_page_rownum_ > 50 AND _cake_paging_._cake_page_rownum_ <= 60)';
  324. $this->assertEquals($expected, $query->sql());
  325. }
  326. /**
  327. * Test that insert queries have results available to them.
  328. *
  329. * @return void
  330. */
  331. public function testInsertUsesOutput()
  332. {
  333. $driver = $this->getMockBuilder('Cake\Database\Driver\Sqlserver')
  334. ->setMethods(['_connect', 'getConnection'])
  335. ->setConstructorArgs([[]])
  336. ->getMock();
  337. $connection = $this->getMockBuilder('Cake\Database\Connection')
  338. ->setMethods(['connect', 'getDriver', 'setDriver'])
  339. ->setConstructorArgs([['log' => false]])
  340. ->getMock();
  341. $connection->expects($this->any())
  342. ->method('getDriver')
  343. ->will($this->returnValue($driver));
  344. $query = new Query($connection);
  345. $query->insert(['title'])
  346. ->into('articles')
  347. ->values(['title' => 'A new article']);
  348. $expected = 'INSERT INTO articles (title) OUTPUT INSERTED.* VALUES (:c0)';
  349. $this->assertEquals($expected, $query->sql());
  350. }
  351. }