SqlserverSchemaTest.php 15 KB

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