SqlserverSchemaTest.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724
  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 http://www.opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\Test\TestCase\Database\Schema;
  16. use Cake\Core\Configure;
  17. use Cake\Database\Schema\Collection as SchemaCollection;
  18. use Cake\Database\Schema\SqlserverSchema;
  19. use Cake\Database\Schema\Table;
  20. use Cake\Datasource\ConnectionManager;
  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['driver'], '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. 'NVARCHAR',
  171. 50,
  172. null,
  173. null,
  174. ['type' => 'string', 'length' => 50]
  175. ],
  176. [
  177. 'CHAR',
  178. 10,
  179. null,
  180. null,
  181. ['type' => 'string', 'fixed' => true, 'length' => 10]
  182. ],
  183. [
  184. 'NCHAR',
  185. 10,
  186. null,
  187. null,
  188. ['type' => 'string', 'fixed' => true, 'length' => 10]
  189. ],
  190. [
  191. 'UNIQUEIDENTIFIER',
  192. null,
  193. null,
  194. null,
  195. ['type' => 'uuid']
  196. ],
  197. [
  198. 'TEXT',
  199. null,
  200. null,
  201. null,
  202. ['type' => 'text', 'length' => null]
  203. ],
  204. [
  205. 'REAL',
  206. null,
  207. null,
  208. null,
  209. ['type' => 'float', 'length' => null]
  210. ],
  211. [
  212. 'VARCHAR',
  213. -1,
  214. null,
  215. null,
  216. ['type' => 'text', 'length' => null]
  217. ],
  218. ];
  219. }
  220. /**
  221. * Test parsing Sqlserver column types from field description.
  222. *
  223. * @dataProvider convertColumnProvider
  224. * @return void
  225. */
  226. public function testConvertColumn($type, $length, $precision, $scale, $expected) {
  227. $field = [
  228. 'name' => 'field',
  229. 'type' => $type,
  230. 'null' => 'YES',
  231. 'default' => 'Default value',
  232. 'char_length' => $length,
  233. 'precision' => $precision,
  234. 'scale' => $scale
  235. ];
  236. $expected += [
  237. 'null' => true,
  238. 'default' => 'Default value',
  239. ];
  240. $driver = $this->getMock('Cake\Database\Driver\Sqlserver');
  241. $dialect = new SqlserverSchema($driver);
  242. $table = $this->getMock('Cake\Database\Schema\Table', [], ['table']);
  243. $table->expects($this->at(0))->method('addColumn')->with('field', $expected);
  244. $dialect->convertFieldDescription($table, $field);
  245. }
  246. /**
  247. * Test listing tables with Sqlserver
  248. *
  249. * @return void
  250. */
  251. public function testListTables() {
  252. $connection = ConnectionManager::get('test');
  253. $this->_createTables($connection);
  254. $schema = new SchemaCollection($connection);
  255. $result = $schema->listTables();
  256. $this->assertInternalType('array', $result);
  257. $this->assertCount(2, $result);
  258. $this->assertEquals('schema_articles', $result[0]);
  259. $this->assertEquals('schema_authors', $result[1]);
  260. }
  261. /**
  262. * Test describing a table with Sqlserver
  263. *
  264. * @return void
  265. */
  266. public function testDescribeTable() {
  267. $connection = ConnectionManager::get('test');
  268. $this->_createTables($connection);
  269. $schema = new SchemaCollection($connection);
  270. $result = $schema->describe('schema_articles');
  271. $expected = [
  272. 'id' => [
  273. 'type' => 'biginteger',
  274. 'null' => false,
  275. 'default' => null,
  276. 'length' => 19,
  277. 'precision' => null,
  278. 'unsigned' => null,
  279. 'autoIncrement' => null,
  280. 'comment' => null,
  281. ],
  282. 'title' => [
  283. 'type' => 'string',
  284. 'null' => true,
  285. 'default' => null,
  286. 'length' => 20,
  287. 'precision' => null,
  288. 'comment' => null,
  289. 'fixed' => null,
  290. ],
  291. 'body' => [
  292. 'type' => 'string',
  293. 'null' => true,
  294. 'default' => null,
  295. 'length' => 1000,
  296. 'precision' => null,
  297. 'fixed' => null,
  298. 'comment' => null,
  299. ],
  300. 'author_id' => [
  301. 'type' => 'integer',
  302. 'null' => false,
  303. 'default' => null,
  304. 'length' => 10,
  305. 'precision' => null,
  306. 'unsigned' => null,
  307. 'autoIncrement' => null,
  308. 'comment' => null,
  309. ],
  310. 'published' => [
  311. 'type' => 'boolean',
  312. 'null' => true,
  313. 'default' => 0,
  314. 'length' => null,
  315. 'precision' => null,
  316. 'comment' => null,
  317. ],
  318. 'views' => [
  319. 'type' => 'integer',
  320. 'null' => true,
  321. 'default' => 0,
  322. 'length' => 5,
  323. 'precision' => null,
  324. 'unsigned' => null,
  325. 'autoIncrement' => null,
  326. 'comment' => null,
  327. ],
  328. 'created' => [
  329. 'type' => 'timestamp',
  330. 'null' => true,
  331. 'default' => null,
  332. 'length' => null,
  333. 'precision' => null,
  334. 'comment' => null,
  335. ],
  336. ];
  337. $this->assertEquals(['id'], $result->primaryKey());
  338. foreach ($expected as $field => $definition) {
  339. $this->assertEquals($definition, $result->column($field), 'Failed to match field ' . $field);
  340. }
  341. }
  342. /**
  343. * Test describing a table with indexes
  344. *
  345. * @return void
  346. */
  347. public function testDescribeTableIndexes() {
  348. $connection = ConnectionManager::get('test');
  349. $this->_createTables($connection);
  350. $schema = new SchemaCollection($connection);
  351. $result = $schema->describe('schema_articles');
  352. $this->assertInstanceOf('Cake\Database\Schema\Table', $result);
  353. $this->assertCount(3, $result->constraints());
  354. $expected = [
  355. 'primary' => [
  356. 'type' => 'primary',
  357. 'columns' => ['id'],
  358. 'length' => []
  359. ],
  360. 'content_idx' => [
  361. 'type' => 'unique',
  362. 'columns' => ['title', 'body'],
  363. 'length' => []
  364. ],
  365. 'author_idx' => [
  366. 'type' => 'foreign',
  367. 'columns' => ['author_id'],
  368. 'references' => ['schema_authors', 'id'],
  369. 'length' => [],
  370. 'update' => 'cascade',
  371. 'delete' => 'cascade',
  372. ]
  373. ];
  374. $this->assertEquals($expected['primary'], $result->constraint('primary'));
  375. $this->assertEquals($expected['content_idx'], $result->constraint('content_idx'));
  376. $this->assertEquals($expected['author_idx'], $result->constraint('author_idx'));
  377. $this->assertCount(1, $result->indexes());
  378. $expected = [
  379. 'type' => 'index',
  380. 'columns' => ['author_id'],
  381. 'length' => []
  382. ];
  383. $this->assertEquals($expected, $result->index('author_idx'));
  384. }
  385. /**
  386. * Column provider for creating column sql
  387. *
  388. * @return array
  389. */
  390. public static function columnSqlProvider() {
  391. return [
  392. // strings
  393. [
  394. 'title',
  395. ['type' => 'string', 'length' => 25, 'null' => false],
  396. '[title] NVARCHAR(25) NOT NULL'
  397. ],
  398. [
  399. 'title',
  400. ['type' => 'string', 'length' => 25, 'null' => true, 'default' => 'ignored'],
  401. '[title] NVARCHAR(25) DEFAULT NULL'
  402. ],
  403. [
  404. 'id',
  405. ['type' => 'string', 'length' => 32, 'fixed' => true, 'null' => false],
  406. '[id] NCHAR(32) NOT NULL'
  407. ],
  408. [
  409. 'id',
  410. ['type' => 'uuid', 'null' => false],
  411. '[id] UNIQUEIDENTIFIER NOT NULL'
  412. ],
  413. [
  414. 'role',
  415. ['type' => 'string', 'length' => 10, 'null' => false, 'default' => 'admin'],
  416. "[role] NVARCHAR(10) NOT NULL DEFAULT [admin]"
  417. ],
  418. [
  419. 'title',
  420. ['type' => 'string'],
  421. '[title] NVARCHAR(255)'
  422. ],
  423. // Text
  424. [
  425. 'body',
  426. ['type' => 'text', 'null' => false],
  427. '[body] NVARCHAR(MAX) NOT NULL'
  428. ],
  429. // Integers
  430. [
  431. 'post_id',
  432. ['type' => 'integer', 'length' => 11],
  433. '[post_id] INTEGER'
  434. ],
  435. [
  436. 'post_id',
  437. ['type' => 'biginteger', 'length' => 20],
  438. '[post_id] BIGINT'
  439. ],
  440. // Decimal
  441. [
  442. 'value',
  443. ['type' => 'decimal'],
  444. '[value] DECIMAL'
  445. ],
  446. [
  447. 'value',
  448. ['type' => 'decimal', 'length' => 11],
  449. '[value] DECIMAL(11,0)'
  450. ],
  451. [
  452. 'value',
  453. ['type' => 'decimal', 'length' => 12, 'precision' => 5],
  454. '[value] DECIMAL(12,5)'
  455. ],
  456. // Float
  457. [
  458. 'value',
  459. ['type' => 'float'],
  460. '[value] FLOAT'
  461. ],
  462. [
  463. 'value',
  464. ['type' => 'float', 'length' => 11, 'precision' => 3],
  465. '[value] FLOAT(3)'
  466. ],
  467. // Binary
  468. [
  469. 'img',
  470. ['type' => 'binary'],
  471. '[img] VARBINARY(MAX)'
  472. ],
  473. // Boolean
  474. [
  475. 'checked',
  476. ['type' => 'boolean', 'default' => false],
  477. '[checked] BIT DEFAULT 0'
  478. ],
  479. [
  480. 'checked',
  481. ['type' => 'boolean', 'default' => true, 'null' => false],
  482. '[checked] BIT NOT NULL DEFAULT 1'
  483. ],
  484. // datetimes
  485. [
  486. 'created',
  487. ['type' => 'datetime'],
  488. '[created] DATETIME'
  489. ],
  490. // Date & Time
  491. [
  492. 'start_date',
  493. ['type' => 'date'],
  494. '[start_date] DATE'
  495. ],
  496. [
  497. 'start_time',
  498. ['type' => 'time'],
  499. '[start_time] TIME'
  500. ],
  501. // timestamps
  502. [
  503. 'created',
  504. ['type' => 'timestamp', 'null' => true],
  505. '[created] DATETIME DEFAULT NULL'
  506. ],
  507. ];
  508. }
  509. /**
  510. * Test generating column definitions
  511. *
  512. * @dataProvider columnSqlProvider
  513. * @return void
  514. */
  515. public function testColumnSql($name, $data, $expected) {
  516. $driver = $this->_getMockedDriver();
  517. $schema = new SqlserverSchema($driver);
  518. $table = (new Table('schema_articles'))->addColumn($name, $data);
  519. $this->assertEquals($expected, $schema->columnSql($table, $name));
  520. }
  521. /**
  522. * Provide data for testing constraintSql
  523. *
  524. * @return array
  525. */
  526. public static function constraintSqlProvider() {
  527. return [
  528. [
  529. 'primary',
  530. ['type' => 'primary', 'columns' => ['title']],
  531. 'PRIMARY KEY ([title])'
  532. ],
  533. [
  534. 'unique_idx',
  535. ['type' => 'unique', 'columns' => ['title', 'author_id']],
  536. 'CONSTRAINT [unique_idx] UNIQUE ([title], [author_id])'
  537. ],
  538. [
  539. 'author_id_idx',
  540. ['type' => 'foreign', 'columns' => ['author_id'], 'references' => ['authors', 'id']],
  541. 'CONSTRAINT [author_id_idx] FOREIGN KEY ([author_id]) ' .
  542. 'REFERENCES [authors] ([id]) ON UPDATE SET NULL ON DELETE SET NULL'
  543. ],
  544. [
  545. 'author_id_idx',
  546. ['type' => 'foreign', 'columns' => ['author_id'], 'references' => ['authors', 'id'], 'update' => 'cascade'],
  547. 'CONSTRAINT [author_id_idx] FOREIGN KEY ([author_id]) ' .
  548. 'REFERENCES [authors] ([id]) ON UPDATE CASCADE ON DELETE SET NULL'
  549. ],
  550. [
  551. 'author_id_idx',
  552. ['type' => 'foreign', 'columns' => ['author_id'], 'references' => ['authors', 'id'], 'update' => 'setDefault'],
  553. 'CONSTRAINT [author_id_idx] FOREIGN KEY ([author_id]) ' .
  554. 'REFERENCES [authors] ([id]) ON UPDATE SET DEFAULT ON DELETE SET NULL'
  555. ],
  556. [
  557. 'author_id_idx',
  558. ['type' => 'foreign', 'columns' => ['author_id'], 'references' => ['authors', 'id'], 'update' => 'setNull'],
  559. 'CONSTRAINT [author_id_idx] FOREIGN KEY ([author_id]) ' .
  560. 'REFERENCES [authors] ([id]) ON UPDATE SET NULL ON DELETE SET NULL'
  561. ],
  562. [
  563. 'author_id_idx',
  564. ['type' => 'foreign', 'columns' => ['author_id'], 'references' => ['authors', 'id'], 'update' => 'noAction'],
  565. 'CONSTRAINT [author_id_idx] FOREIGN KEY ([author_id]) ' .
  566. 'REFERENCES [authors] ([id]) ON UPDATE NO ACTION ON DELETE SET NULL'
  567. ],
  568. ];
  569. }
  570. /**
  571. * Test the constraintSql method.
  572. *
  573. * @dataProvider constraintSqlProvider
  574. */
  575. public function testConstraintSql($name, $data, $expected) {
  576. $driver = $this->_getMockedDriver();
  577. $schema = new SqlserverSchema($driver);
  578. $table = (new Table('schema_articles'))->addColumn('title', [
  579. 'type' => 'string',
  580. 'length' => 255
  581. ])->addColumn('author_id', [
  582. 'type' => 'integer',
  583. ])->addConstraint($name, $data);
  584. $this->assertEquals($expected, $schema->constraintSql($table, $name));
  585. }
  586. /**
  587. * Integration test for converting a Schema\Table into MySQL table creates.
  588. *
  589. * @return void
  590. */
  591. public function testCreateSql() {
  592. $driver = $this->_getMockedDriver();
  593. $connection = $this->getMock('Cake\Database\Connection', [], [], '', false);
  594. $connection->expects($this->any())->method('driver')
  595. ->will($this->returnValue($driver));
  596. $table = (new Table('schema_articles'))->addColumn('id', [
  597. 'type' => 'integer',
  598. 'null' => false
  599. ])
  600. ->addColumn('title', [
  601. 'type' => 'string',
  602. 'null' => false,
  603. ])
  604. ->addColumn('body', ['type' => 'text'])
  605. ->addColumn('created', 'datetime')
  606. ->addConstraint('primary', [
  607. 'type' => 'primary',
  608. 'columns' => ['id'],
  609. ])
  610. ->addIndex('title_idx', [
  611. 'type' => 'index',
  612. 'columns' => ['title'],
  613. ]);
  614. $expected = <<<SQL
  615. CREATE TABLE [schema_articles] (
  616. [id] INTEGER IDENTITY(1, 1),
  617. [title] NVARCHAR(255) NOT NULL,
  618. [body] NVARCHAR(MAX),
  619. [created] DATETIME,
  620. PRIMARY KEY ([id])
  621. )
  622. SQL;
  623. $result = $table->createSql($connection);
  624. $this->assertCount(2, $result);
  625. $this->assertEquals(str_replace("\r\n", "\n", $expected), str_replace("\r\n", "\n", $result[0]));
  626. $this->assertEquals(
  627. 'CREATE INDEX [title_idx] ON [schema_articles] ([title])',
  628. $result[1]
  629. );
  630. }
  631. /**
  632. * test dropSql
  633. *
  634. * @return void
  635. */
  636. public function testDropSql() {
  637. $driver = $this->_getMockedDriver();
  638. $connection = $this->getMock('Cake\Database\Connection', [], [], '', false);
  639. $connection->expects($this->any())->method('driver')
  640. ->will($this->returnValue($driver));
  641. $table = new Table('schema_articles');
  642. $result = $table->dropSql($connection);
  643. $this->assertCount(1, $result);
  644. $this->assertEquals('DROP TABLE [schema_articles]', $result[0]);
  645. }
  646. /**
  647. * Test truncateSql()
  648. *
  649. * @return void
  650. */
  651. public function testTruncateSql() {
  652. $driver = $this->_getMockedDriver();
  653. $connection = $this->getMock('Cake\Database\Connection', [], [], '', false);
  654. $connection->expects($this->any())->method('driver')
  655. ->will($this->returnValue($driver));
  656. $table = new Table('schema_articles');
  657. $table->addColumn('id', 'integer')
  658. ->addConstraint('primary', [
  659. 'type' => 'primary',
  660. 'columns' => ['id']
  661. ]);
  662. $result = $table->truncateSql($connection);
  663. $this->assertCount(1, $result);
  664. $this->assertEquals('TRUNCATE TABLE [schema_articles]', $result[0]);
  665. }
  666. /**
  667. * Get a schema instance with a mocked driver/pdo instances
  668. *
  669. * @return Driver
  670. */
  671. protected function _getMockedDriver() {
  672. $driver = new \Cake\Database\Driver\Sqlserver();
  673. $mock = $this->getMock('FakePdo', ['quote', 'quoteIdentifier']);
  674. $mock->expects($this->any())
  675. ->method('quote')
  676. ->will($this->returnCallback(function ($value) {
  677. return '[' . $value . ']';
  678. }));
  679. $mock->expects($this->any())
  680. ->method('quoteIdentifier')
  681. ->will($this->returnCallback(function ($value) {
  682. return '[' . $value . ']';
  683. }));
  684. $driver->connection($mock);
  685. return $driver;
  686. }
  687. }