SqlserverSchemaTest.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  11. * @link http://cakephp.org CakePHP(tm) Project
  12. * @since 3.0.0
  13. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  14. */
  15. namespace Cake\Test\TestCase\Database\Schema;
  16. use Cake\Core\Configure;
  17. use Cake\Datasource\ConnectionManager;
  18. use Cake\Database\Schema\Collection as SchemaCollection;
  19. use Cake\Database\Schema\SqlserverSchema;
  20. use Cake\Database\Schema\Table;
  21. use Cake\TestSuite\TestCase;
  22. /**
  23. * SQL Server schema test case.
  24. */
  25. class SqlserverSchemaTest extends TestCase {
  26. /**
  27. * Set up
  28. *
  29. * @return void
  30. */
  31. public function setUp() {
  32. parent::setUp();
  33. $this->skipUnless(defined('PDO::SQLSRV_ENCODING_UTF8'), 'SQL Server extension not present');
  34. }
  35. /**
  36. * Helper method for skipping tests that need a real connection.
  37. *
  38. * @return void
  39. */
  40. protected function _needsConnection() {
  41. $config = ConnectionManager::config('test');
  42. $this->skipIf(strpos($config['className'], 'Sqlserver') === false, 'Not using Sqlserver for test config');
  43. }
  44. /**
  45. * Helper method for testing methods.
  46. *
  47. * @return void
  48. */
  49. protected function _createTables($connection) {
  50. $this->_needsConnection();
  51. $connection->execute("IF OBJECT_ID('schema_articles', 'U') IS NOT NULL DROP TABLE schema_articles");
  52. $connection->execute("IF OBJECT_ID('schema_authors', 'U') IS NOT NULL DROP TABLE schema_authors");
  53. $table = <<<SQL
  54. CREATE TABLE schema_authors (
  55. id int IDENTITY(1,1) PRIMARY KEY,
  56. name VARCHAR(50),
  57. bio DATE,
  58. created DATETIME
  59. )
  60. SQL;
  61. $connection->execute($table);
  62. $table = <<<SQL
  63. CREATE TABLE schema_articles (
  64. id BIGINT PRIMARY KEY,
  65. title VARCHAR(20),
  66. body VARCHAR(1000),
  67. author_id INTEGER NOT NULL,
  68. published BIT DEFAULT 0,
  69. views SMALLINT DEFAULT 0,
  70. created DATETIME,
  71. CONSTRAINT [content_idx] UNIQUE ([title], [body]),
  72. CONSTRAINT [author_idx] FOREIGN KEY ([author_id]) REFERENCES [schema_authors] ([id]) ON DELETE CASCADE ON UPDATE CASCADE
  73. )
  74. SQL;
  75. $connection->execute($table);
  76. $connection->execute('CREATE INDEX [author_idx] ON [schema_articles] ([author_id])');
  77. }
  78. /**
  79. * Data provider for convert column testing
  80. *
  81. * @return array
  82. */
  83. public static function convertColumnProvider() {
  84. return [
  85. [
  86. 'DATETIME',
  87. null,
  88. null,
  89. null,
  90. ['type' => 'timestamp', 'length' => null]
  91. ],
  92. [
  93. 'DATE',
  94. null,
  95. null,
  96. null,
  97. ['type' => 'date', 'length' => null]
  98. ],
  99. [
  100. 'TIME',
  101. null,
  102. null,
  103. null,
  104. ['type' => 'time', 'length' => null]
  105. ],
  106. [
  107. 'SMALLINT',
  108. null,
  109. 4,
  110. null,
  111. ['type' => 'integer', 'length' => 4]
  112. ],
  113. [
  114. 'INTEGER',
  115. null,
  116. null,
  117. null,
  118. ['type' => 'integer', 'length' => 10]
  119. ],
  120. [
  121. 'INTEGER',
  122. null,
  123. 8,
  124. null,
  125. ['type' => 'integer', 'length' => 8]
  126. ],
  127. [
  128. 'BIGINT',
  129. null,
  130. null,
  131. null,
  132. ['type' => 'biginteger', 'length' => 20]
  133. ],
  134. [
  135. 'NUMERIC',
  136. null,
  137. 15,
  138. 5,
  139. ['type' => 'decimal', 'length' => 15, 'precision' => 5]
  140. ],
  141. [
  142. 'DECIMAL',
  143. null,
  144. 11,
  145. 3,
  146. ['type' => 'decimal', 'length' => 11, 'precision' => 3]
  147. ],
  148. [
  149. 'MONEY',
  150. null,
  151. null,
  152. null,
  153. ['type' => 'decimal', 'length' => null, 'precision' => null]
  154. ],
  155. [
  156. 'VARCHAR',
  157. null,
  158. null,
  159. null,
  160. ['type' => 'string', 'length' => 255]
  161. ],
  162. [
  163. 'VARCHAR',
  164. 10,
  165. null,
  166. null,
  167. ['type' => 'string', 'length' => 10]
  168. ],
  169. [
  170. 'CHAR',
  171. 10,
  172. null,
  173. null,
  174. ['type' => 'string', 'fixed' => true, 'length' => 10]
  175. ],
  176. [
  177. 'UNIQUEIDENTIFIER',
  178. null,
  179. null,
  180. null,
  181. ['type' => 'uuid']
  182. ],
  183. [
  184. 'TEXT',
  185. null,
  186. null,
  187. null,
  188. ['type' => 'text', 'length' => null]
  189. ],
  190. [
  191. 'REAL',
  192. null,
  193. null,
  194. null,
  195. ['type' => 'float', 'length' => null]
  196. ],
  197. [
  198. 'VARCHAR',
  199. -1,
  200. null,
  201. null,
  202. ['type' => 'text', 'length' => null]
  203. ],
  204. ];
  205. }
  206. /**
  207. * Test parsing Sqlserver column types from field description.
  208. *
  209. * @dataProvider convertColumnProvider
  210. * @return void
  211. */
  212. public function testConvertColumn($type, $length, $precision, $scale, $expected) {
  213. $field = [
  214. 'name' => 'field',
  215. 'type' => $type,
  216. 'null' => 'YES',
  217. 'default' => 'Default value',
  218. 'char_length' => $length,
  219. 'precision' => $precision,
  220. 'scale' => $scale
  221. ];
  222. $expected += [
  223. 'null' => true,
  224. 'default' => 'Default value',
  225. ];
  226. $driver = $this->getMock('Cake\Database\Driver\Sqlserver');
  227. $dialect = new SqlserverSchema($driver);
  228. $table = $this->getMock('Cake\Database\Schema\Table', [], ['table']);
  229. $table->expects($this->at(0))->method('addColumn')->with('field', $expected);
  230. $dialect->convertFieldDescription($table, $field);
  231. }
  232. /**
  233. * Test listing tables with Sqlserver
  234. *
  235. * @return void
  236. */
  237. public function testListTables() {
  238. $connection = ConnectionManager::get('test');
  239. $this->_createTables($connection);
  240. $schema = new SchemaCollection($connection);
  241. $result = $schema->listTables();
  242. $this->assertInternalType('array', $result);
  243. $this->assertCount(2, $result);
  244. $this->assertEquals('schema_articles', $result[0]);
  245. $this->assertEquals('schema_authors', $result[1]);
  246. }
  247. /**
  248. * Test describing a table with Sqlserver
  249. *
  250. * @return void
  251. */
  252. public function testDescribeTable() {
  253. $connection = ConnectionManager::get('test');
  254. $this->_createTables($connection);
  255. $schema = new SchemaCollection($connection);
  256. $result = $schema->describe('schema_articles');
  257. $expected = [
  258. 'id' => [
  259. 'type' => 'biginteger',
  260. 'null' => false,
  261. 'default' => null,
  262. 'length' => 20,
  263. 'precision' => null,
  264. 'unsigned' => null,
  265. 'autoIncrement' => null,
  266. 'comment' => null,
  267. ],
  268. 'title' => [
  269. 'type' => 'string',
  270. 'null' => true,
  271. 'default' => null,
  272. 'length' => 20,
  273. 'precision' => null,
  274. 'comment' => null,
  275. 'fixed' => null,
  276. ],
  277. 'body' => [
  278. 'type' => 'string',
  279. 'null' => true,
  280. 'default' => null,
  281. 'length' => 1000,
  282. 'precision' => null,
  283. 'fixed' => null,
  284. 'comment' => null,
  285. ],
  286. 'author_id' => [
  287. 'type' => 'integer',
  288. 'null' => false,
  289. 'default' => null,
  290. 'length' => 10,
  291. 'precision' => null,
  292. 'unsigned' => null,
  293. 'autoIncrement' => null,
  294. 'comment' => null,
  295. ],
  296. 'published' => [
  297. 'type' => 'boolean',
  298. 'null' => true,
  299. 'default' => 0,
  300. 'length' => null,
  301. 'precision' => null,
  302. 'comment' => null,
  303. ],
  304. 'views' => [
  305. 'type' => 'integer',
  306. 'null' => true,
  307. 'default' => 0,
  308. 'length' => 5,
  309. 'precision' => null,
  310. 'unsigned' => null,
  311. 'autoIncrement' => null,
  312. 'comment' => null,
  313. ],
  314. 'created' => [
  315. 'type' => 'datetime',
  316. 'null' => true,
  317. 'default' => null,
  318. 'length' => null,
  319. 'precision' => null,
  320. 'comment' => null,
  321. ],
  322. ];
  323. $this->assertEquals(['id'], $result->primaryKey());
  324. foreach ($expected as $field => $definition) {
  325. $this->assertEquals($definition, $result->column($field), 'Failed to match field ' . $field);
  326. }
  327. }
  328. /**
  329. * Test describing a table with indexes
  330. *
  331. * @return void
  332. */
  333. public function testDescribeTableIndexes() {
  334. $connection = ConnectionManager::get('test');
  335. $this->_createTables($connection);
  336. $schema = new SchemaCollection($connection);
  337. $result = $schema->describe('schema_articles');
  338. $this->assertInstanceOf('Cake\Database\Schema\Table', $result);
  339. $this->assertCount(3, $result->constraints());
  340. $expected = [
  341. 'primary' => [
  342. 'type' => 'primary',
  343. 'columns' => ['id'],
  344. 'length' => []
  345. ],
  346. 'content_idx' => [
  347. 'type' => 'unique',
  348. 'columns' => ['title', 'body'],
  349. 'length' => []
  350. ],
  351. 'author_idx' => [
  352. 'type' => 'foreign',
  353. 'columns' => ['author_id'],
  354. 'references' => ['schema_authors', 'id'],
  355. 'length' => [],
  356. 'update' => 'cascade',
  357. 'delete' => 'cascade',
  358. ]
  359. ];
  360. $this->assertEquals($expected['primary'], $result->constraint('primary'));
  361. $this->assertEquals($expected['content_idx'], $result->constraint('content_idx'));
  362. $this->assertEquals($expected['author_idx'], $result->constraint('author_idx'));
  363. $this->assertCount(1, $result->indexes());
  364. $expected = [
  365. 'type' => 'index',
  366. 'columns' => ['author_id'],
  367. 'length' => []
  368. ];
  369. $this->assertEquals($expected, $result->index('author_idx'));
  370. }
  371. /**
  372. * Column provider for creating column sql
  373. *
  374. * @return array
  375. */
  376. public static function columnSqlProvider() {
  377. return [
  378. // strings
  379. [
  380. 'title',
  381. ['type' => 'string', 'length' => 25, 'null' => false],
  382. '[title] NVARCHAR(25) NOT NULL'
  383. ],
  384. [
  385. 'title',
  386. ['type' => 'string', 'length' => 25, 'null' => true, 'default' => 'ignored'],
  387. '[title] NVARCHAR(25) DEFAULT NULL'
  388. ],
  389. [
  390. 'id',
  391. ['type' => 'string', 'length' => 32, 'fixed' => true, 'null' => false],
  392. '[id] NCHAR(32) NOT NULL'
  393. ],
  394. [
  395. 'id',
  396. ['type' => 'uuid', 'null' => false],
  397. '[id] UNIQUEIDENTIFIER NOT NULL'
  398. ],
  399. [
  400. 'role',
  401. ['type' => 'string', 'length' => 10, 'null' => false, 'default' => 'admin'],
  402. "[role] NVARCHAR(10) NOT NULL DEFAULT [admin]"
  403. ],
  404. [
  405. 'title',
  406. ['type' => 'string'],
  407. '[title] NVARCHAR(255)'
  408. ],
  409. // Text
  410. [
  411. 'body',
  412. ['type' => 'text', 'null' => false],
  413. '[body] NVARCHAR(MAX) NOT NULL'
  414. ],
  415. // Integers
  416. [
  417. 'post_id',
  418. ['type' => 'integer', 'length' => 11],
  419. '[post_id] INTEGER'
  420. ],
  421. [
  422. 'post_id',
  423. ['type' => 'biginteger', 'length' => 20],
  424. '[post_id] BIGINT'
  425. ],
  426. // Decimal
  427. [
  428. 'value',
  429. ['type' => 'decimal'],
  430. '[value] DECIMAL'
  431. ],
  432. [
  433. 'value',
  434. ['type' => 'decimal', 'length' => 11],
  435. '[value] DECIMAL(11,0)'
  436. ],
  437. [
  438. 'value',
  439. ['type' => 'decimal', 'length' => 12, 'precision' => 5],
  440. '[value] DECIMAL(12,5)'
  441. ],
  442. // Float
  443. [
  444. 'value',
  445. ['type' => 'float'],
  446. '[value] FLOAT'
  447. ],
  448. [
  449. 'value',
  450. ['type' => 'float', 'length' => 11, 'precision' => 3],
  451. '[value] FLOAT(3)'
  452. ],
  453. // Binary
  454. [
  455. 'img',
  456. ['type' => 'binary'],
  457. '[img] BINARY'
  458. ],
  459. // Boolean
  460. [
  461. 'checked',
  462. ['type' => 'boolean', 'default' => false],
  463. '[checked] BIT DEFAULT 0'
  464. ],
  465. [
  466. 'checked',
  467. ['type' => 'boolean', 'default' => true, 'null' => false],
  468. '[checked] BIT NOT NULL DEFAULT 1'
  469. ],
  470. // datetimes
  471. [
  472. 'created',
  473. ['type' => 'datetime'],
  474. '[created] DATETIME'
  475. ],
  476. // Date & Time
  477. [
  478. 'start_date',
  479. ['type' => 'date'],
  480. '[start_date] DATE'
  481. ],
  482. [
  483. 'start_time',
  484. ['type' => 'time'],
  485. '[start_time] TIME'
  486. ],
  487. // timestamps
  488. [
  489. 'created',
  490. ['type' => 'timestamp', 'null' => true],
  491. '[created] DATETIME DEFAULT NULL'
  492. ],
  493. ];
  494. }
  495. /**
  496. * Test generating column definitions
  497. *
  498. * @dataProvider columnSqlProvider
  499. * @return void
  500. */
  501. public function testColumnSql($name, $data, $expected) {
  502. $driver = $this->_getMockedDriver();
  503. $schema = new SqlserverSchema($driver);
  504. $table = (new Table('schema_articles'))->addColumn($name, $data);
  505. $this->assertEquals($expected, $schema->columnSql($table, $name));
  506. }
  507. /**
  508. * Provide data for testing constraintSql
  509. *
  510. * @return array
  511. */
  512. public static function constraintSqlProvider() {
  513. return [
  514. [
  515. 'primary',
  516. ['type' => 'primary', 'columns' => ['title']],
  517. 'PRIMARY KEY ([title])'
  518. ],
  519. [
  520. 'unique_idx',
  521. ['type' => 'unique', 'columns' => ['title', 'author_id']],
  522. 'CONSTRAINT [unique_idx] UNIQUE ([title], [author_id])'
  523. ],
  524. [
  525. 'author_id_idx',
  526. ['type' => 'foreign', 'columns' => ['author_id'], 'references' => ['authors', 'id']],
  527. 'CONSTRAINT [author_id_idx] FOREIGN KEY ([author_id]) ' .
  528. 'REFERENCES [authors] ([id]) ON UPDATE SET NULL ON DELETE SET NULL'
  529. ],
  530. [
  531. 'author_id_idx',
  532. ['type' => 'foreign', 'columns' => ['author_id'], 'references' => ['authors', 'id'], 'update' => 'cascade'],
  533. 'CONSTRAINT [author_id_idx] FOREIGN KEY ([author_id]) ' .
  534. 'REFERENCES [authors] ([id]) ON UPDATE CASCADE ON DELETE SET NULL'
  535. ],
  536. [
  537. 'author_id_idx',
  538. ['type' => 'foreign', 'columns' => ['author_id'], 'references' => ['authors', 'id'], 'update' => 'setDefault'],
  539. 'CONSTRAINT [author_id_idx] FOREIGN KEY ([author_id]) ' .
  540. 'REFERENCES [authors] ([id]) ON UPDATE SET DEFAULT ON DELETE SET NULL'
  541. ],
  542. [
  543. 'author_id_idx',
  544. ['type' => 'foreign', 'columns' => ['author_id'], 'references' => ['authors', 'id'], 'update' => 'setNull'],
  545. 'CONSTRAINT [author_id_idx] FOREIGN KEY ([author_id]) ' .
  546. 'REFERENCES [authors] ([id]) ON UPDATE SET NULL ON DELETE SET NULL'
  547. ],
  548. [
  549. 'author_id_idx',
  550. ['type' => 'foreign', 'columns' => ['author_id'], 'references' => ['authors', 'id'], 'update' => 'noAction'],
  551. 'CONSTRAINT [author_id_idx] FOREIGN KEY ([author_id]) ' .
  552. 'REFERENCES [authors] ([id]) ON UPDATE NO ACTION ON DELETE SET NULL'
  553. ],
  554. ];
  555. }
  556. /**
  557. * Test the constraintSql method.
  558. *
  559. * @dataProvider constraintSqlProvider
  560. */
  561. public function testConstraintSql($name, $data, $expected) {
  562. $driver = $this->_getMockedDriver();
  563. $schema = new SqlserverSchema($driver);
  564. $table = (new Table('schema_articles'))->addColumn('title', [
  565. 'type' => 'string',
  566. 'length' => 255
  567. ])->addColumn('author_id', [
  568. 'type' => 'integer',
  569. ])->addConstraint($name, $data);
  570. $this->assertEquals($expected, $schema->constraintSql($table, $name));
  571. }
  572. /**
  573. * Integration test for converting a Schema\Table into MySQL table creates.
  574. *
  575. * @return void
  576. */
  577. public function testCreateSql() {
  578. $driver = $this->_getMockedDriver();
  579. $connection = $this->getMock('Cake\Database\Connection', [], [], '', false);
  580. $connection->expects($this->any())->method('driver')
  581. ->will($this->returnValue($driver));
  582. $table = (new Table('schema_articles'))->addColumn('id', [
  583. 'type' => 'integer',
  584. 'null' => false
  585. ])
  586. ->addColumn('title', [
  587. 'type' => 'string',
  588. 'null' => false,
  589. ])
  590. ->addColumn('body', ['type' => 'text'])
  591. ->addColumn('created', 'datetime')
  592. ->addConstraint('primary', [
  593. 'type' => 'primary',
  594. 'columns' => ['id'],
  595. ])
  596. ->addIndex('title_idx', [
  597. 'type' => 'index',
  598. 'columns' => ['title'],
  599. ]);
  600. $expected = <<<SQL
  601. CREATE TABLE [schema_articles] (
  602. [id] INTEGER IDENTITY(1, 1),
  603. [title] NVARCHAR(255) NOT NULL,
  604. [body] NVARCHAR(MAX),
  605. [created] DATETIME,
  606. PRIMARY KEY ([id])
  607. )
  608. SQL;
  609. $result = $table->createSql($connection);
  610. $this->assertCount(2, $result);
  611. $this->assertEquals(str_replace("\r\n", "\n", $expected), str_replace("\r\n", "\n", $result[0]));
  612. $this->assertEquals(
  613. 'CREATE INDEX [title_idx] ON [schema_articles] ([title])',
  614. $result[1]
  615. );
  616. }
  617. /**
  618. * test dropSql
  619. *
  620. * @return void
  621. */
  622. public function testDropSql() {
  623. $driver = $this->_getMockedDriver();
  624. $connection = $this->getMock('Cake\Database\Connection', [], [], '', false);
  625. $connection->expects($this->any())->method('driver')
  626. ->will($this->returnValue($driver));
  627. $table = new Table('schema_articles');
  628. $result = $table->dropSql($connection);
  629. $this->assertCount(1, $result);
  630. $this->assertEquals('DROP TABLE [schema_articles]', $result[0]);
  631. }
  632. /**
  633. * Test truncateSql()
  634. *
  635. * @return void
  636. */
  637. public function testTruncateSql() {
  638. $driver = $this->_getMockedDriver();
  639. $connection = $this->getMock('Cake\Database\Connection', [], [], '', false);
  640. $connection->expects($this->any())->method('driver')
  641. ->will($this->returnValue($driver));
  642. $table = new Table('schema_articles');
  643. $table->addColumn('id', 'integer')
  644. ->addConstraint('primary', [
  645. 'type' => 'primary',
  646. 'columns' => ['id']
  647. ]);
  648. $result = $table->truncateSql($connection);
  649. $this->assertCount(1, $result);
  650. $this->assertEquals('TRUNCATE TABLE [schema_articles]', $result[0]);
  651. }
  652. /**
  653. * Get a schema instance with a mocked driver/pdo instances
  654. *
  655. * @return Driver
  656. */
  657. protected function _getMockedDriver() {
  658. $driver = new \Cake\Database\Driver\Sqlserver();
  659. $mock = $this->getMock('FakePdo', ['quote', 'quoteIdentifier']);
  660. $mock->expects($this->any())
  661. ->method('quote')
  662. ->will($this->returnCallback(function ($value) {
  663. return '[' . $value . ']';
  664. }));
  665. $mock->expects($this->any())
  666. ->method('quoteIdentifier')
  667. ->will($this->returnCallback(function ($value) {
  668. return '[' . $value . ']';
  669. }));
  670. $driver->connection($mock);
  671. return $driver;
  672. }
  673. }