SqlserverSchemaTest.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652
  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\Database\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('dbo.Scores', 'U') IS NOT NULL DROP TABLE schema_articles");
  45. $connection->execute("IF OBJECT_ID('dbo.Scores', '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 TEXT,
  60. author_id INTEGER NOT NULL,
  61. published BOOLEAN DEFAULT false,
  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 SET DEFAULT 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' => 'datetime', '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. 'fixed' => null,
  197. 'comment' => null,
  198. ],
  199. 'title' => [
  200. 'type' => 'string',
  201. 'null' => true,
  202. 'default' => null,
  203. 'length' => 20,
  204. 'precision' => null,
  205. 'comment' => 'a title',
  206. 'fixed' => null,
  207. ],
  208. 'body' => [
  209. 'type' => 'text',
  210. 'null' => true,
  211. 'default' => null,
  212. 'length' => null,
  213. 'precision' => null,
  214. 'fixed' => null,
  215. 'comment' => null,
  216. ],
  217. 'author_id' => [
  218. 'type' => 'integer',
  219. 'null' => false,
  220. 'default' => null,
  221. 'length' => 10,
  222. 'precision' => null,
  223. 'fixed' => null,
  224. 'comment' => null,
  225. ],
  226. 'published' => [
  227. 'type' => 'boolean',
  228. 'null' => true,
  229. 'default' => 0,
  230. 'length' => null,
  231. 'precision' => null,
  232. 'fixed' => null,
  233. 'comment' => null,
  234. ],
  235. 'views' => [
  236. 'type' => 'integer',
  237. 'null' => true,
  238. 'default' => 0,
  239. 'length' => 5,
  240. 'precision' => null,
  241. 'fixed' => null,
  242. 'comment' => null,
  243. ],
  244. 'created' => [
  245. 'type' => 'datetime',
  246. 'null' => true,
  247. 'default' => null,
  248. 'length' => null,
  249. 'precision' => null,
  250. 'fixed' => null,
  251. 'comment' => null,
  252. ],
  253. ];
  254. $this->assertEquals(['id'], $result->primaryKey());
  255. foreach ($expected as $field => $definition) {
  256. $this->assertEquals($definition, $result->column($field));
  257. }
  258. }
  259. /**
  260. * Test describing a table with indexes
  261. *
  262. * @return void
  263. */
  264. public function testDescribeTableIndexes() {
  265. $connection = ConnectionManager::get('test');
  266. $this->_createTables($connection);
  267. $schema = new SchemaCollection($connection);
  268. $result = $schema->describe('schema_articles');
  269. $this->assertInstanceOf('Cake\Database\Schema\Table', $result);
  270. $expected = [
  271. 'primary' => [
  272. 'type' => 'primary',
  273. 'columns' => ['id'],
  274. 'length' => []
  275. ],
  276. 'content_idx' => [
  277. 'type' => 'unique',
  278. 'columns' => ['title', 'body'],
  279. 'length' => []
  280. ]
  281. ];
  282. $this->assertCount(3, $result->constraints());
  283. $expected = [
  284. 'primary' => [
  285. 'type' => 'primary',
  286. 'columns' => ['id'],
  287. 'length' => []
  288. ],
  289. 'content_idx' => [
  290. 'type' => 'unique',
  291. 'columns' => ['title', 'body'],
  292. 'length' => []
  293. ],
  294. 'author_idx' => [
  295. 'type' => 'foreign',
  296. 'columns' => ['author_id'],
  297. 'references' => ['schema_authors', 'id'],
  298. 'length' => [],
  299. 'update' => 'cascade',
  300. 'delete' => 'setDefault',
  301. ]
  302. ];
  303. $this->assertEquals($expected['primary'], $result->constraint('primary'));
  304. $this->assertEquals($expected['content_idx'], $result->constraint('content_idx'));
  305. $this->assertEquals($expected['author_idx'], $result->constraint('author_idx'));
  306. $this->assertCount(1, $result->indexes());
  307. $expected = [
  308. 'type' => 'index',
  309. 'columns' => ['author_id'],
  310. 'length' => []
  311. ];
  312. $this->assertEquals($expected, $result->index('author_idx'));
  313. }
  314. /**
  315. * Column provider for creating column sql
  316. *
  317. * @return array
  318. */
  319. public static function columnSqlProvider() {
  320. return [
  321. // strings
  322. [
  323. 'title',
  324. ['type' => 'string', 'length' => 25, 'null' => false],
  325. '[title] VARCHAR(25) NOT NULL'
  326. ],
  327. [
  328. 'title',
  329. ['type' => 'string', 'length' => 25, 'null' => true, 'default' => 'ignored'],
  330. '[title] VARCHAR(25) DEFAULT NULL'
  331. ],
  332. [
  333. 'id',
  334. ['type' => 'string', 'length' => 32, 'fixed' => true, 'null' => false],
  335. '[id] CHAR(32) NOT NULL'
  336. ],
  337. [
  338. 'id',
  339. ['type' => 'string', 'length' => 36, 'fixed' => true, 'null' => false],
  340. '[id] UNIQUEIDENTIFIER NOT NULL'
  341. ],
  342. [
  343. 'role',
  344. ['type' => 'string', 'length' => 10, 'null' => false, 'default' => 'admin'],
  345. "[role] VARCHAR(10) NOT NULL DEFAULT 'admin'"
  346. ],
  347. [
  348. 'title',
  349. ['type' => 'string'],
  350. '[title] VARCHAR'
  351. ],
  352. // Text
  353. [
  354. 'body',
  355. ['type' => 'text', 'null' => false],
  356. '[body] TEXT NOT NULL'
  357. ],
  358. // Integers
  359. [
  360. 'post_id',
  361. ['type' => 'integer', 'length' => 11],
  362. '[post_id] INTEGER'
  363. ],
  364. [
  365. 'post_id',
  366. ['type' => 'biginteger', 'length' => 20],
  367. '[post_id] BIGINT'
  368. ],
  369. // Decimal
  370. [
  371. 'value',
  372. ['type' => 'decimal'],
  373. '[value] DECIMAL'
  374. ],
  375. [
  376. 'value',
  377. ['type' => 'decimal', 'length' => 11],
  378. '[value] DECIMAL(11,0)'
  379. ],
  380. [
  381. 'value',
  382. ['type' => 'decimal', 'length' => 12, 'precision' => 5],
  383. '[value] DECIMAL(12,5)'
  384. ],
  385. // Float
  386. [
  387. 'value',
  388. ['type' => 'float'],
  389. '[value] FLOAT'
  390. ],
  391. [
  392. 'value',
  393. ['type' => 'float', 'length' => 11, 'precision' => 3],
  394. '[value] FLOAT(3)'
  395. ],
  396. // Binary
  397. [
  398. 'img',
  399. ['type' => 'binary'],
  400. '[img] BINARY'
  401. ],
  402. // Boolean
  403. [
  404. 'checked',
  405. ['type' => 'boolean', 'default' => false],
  406. '[checked] BOOLEAN DEFAULT FALSE'
  407. ],
  408. [
  409. 'checked',
  410. ['type' => 'boolean', 'default' => true, 'null' => false],
  411. '[checked] BOOLEAN NOT NULL DEFAULT TRUE'
  412. ],
  413. // datetimes
  414. [
  415. 'created',
  416. ['type' => 'datetime'],
  417. '[created] DATETIME'
  418. ],
  419. // Date & Time
  420. [
  421. 'start_date',
  422. ['type' => 'date'],
  423. '[start_date] DATE'
  424. ],
  425. [
  426. 'start_time',
  427. ['type' => 'time'],
  428. '[start_time] TIME'
  429. ],
  430. // timestamps
  431. [
  432. 'created',
  433. ['type' => 'timestamp', 'null' => true],
  434. '[created] DATETIME DEFAULT NULL'
  435. ],
  436. ];
  437. }
  438. /**
  439. * Test generating column definitions
  440. *
  441. * @dataProvider columnSqlProvider
  442. * @return void
  443. */
  444. public function testColumnSql($name, $data, $expected) {
  445. $driver = $this->_getMockedDriver();
  446. $schema = new SqlserverSchema($driver);
  447. $table = (new Table('schema_articles'))->addColumn($name, $data);
  448. $this->assertEquals($expected, $schema->columnSql($table, $name));
  449. }
  450. /**
  451. * Provide data for testing constraintSql
  452. *
  453. * @return array
  454. */
  455. public static function constraintSqlProvider() {
  456. return [
  457. [
  458. 'primary',
  459. ['type' => 'primary', 'columns' => ['title']],
  460. 'PRIMARY KEY ([title])'
  461. ],
  462. [
  463. 'unique_idx',
  464. ['type' => 'unique', 'columns' => ['title', 'author_id']],
  465. 'CONSTRAINT [unique_idx] UNIQUE ([title], [author_id])'
  466. ],
  467. [
  468. 'author_id_idx',
  469. ['type' => 'foreign', 'columns' => ['author_id'], 'references' => ['authors', 'id']],
  470. 'CONSTRAINT [author_id_idx] FOREIGN KEY ([author_id]) ' .
  471. 'REFERENCES [authors] ([id]) ON UPDATE SET NULL ON DELETE SET NULL'
  472. ],
  473. [
  474. 'author_id_idx',
  475. ['type' => 'foreign', 'columns' => ['author_id'], 'references' => ['authors', 'id'], 'update' => 'cascade'],
  476. 'CONSTRAINT [author_id_idx] FOREIGN KEY ([author_id]) ' .
  477. 'REFERENCES [authors] ([id]) ON UPDATE CASCADE ON DELETE SET NULL'
  478. ],
  479. [
  480. 'author_id_idx',
  481. ['type' => 'foreign', 'columns' => ['author_id'], 'references' => ['authors', 'id'], 'update' => 'setDefault'],
  482. 'CONSTRAINT [author_id_idx] FOREIGN KEY ([author_id]) ' .
  483. 'REFERENCES [authors] ([id]) ON UPDATE SET NULL ON DELETE SET DEFAULT'
  484. ],
  485. [
  486. 'author_id_idx',
  487. ['type' => 'foreign', 'columns' => ['author_id'], 'references' => ['authors', 'id'], 'update' => 'setNull'],
  488. 'CONSTRAINT [author_id_idx] FOREIGN KEY ([author_id]) ' .
  489. 'REFERENCES [authors] ([id]) ON UPDATE SET NULL ON DELETE SET NULL'
  490. ],
  491. [
  492. 'author_id_idx',
  493. ['type' => 'foreign', 'columns' => ['author_id'], 'references' => ['authors', 'id'], 'update' => 'noAction'],
  494. 'CONSTRAINT [author_id_idx] FOREIGN KEY ([author_id]) ' .
  495. 'REFERENCES [authors] ([id]) ON UPDATE NO ACTION ON DELETE SET NULL'
  496. ],
  497. ];
  498. }
  499. /**
  500. * Test the constraintSql method.
  501. *
  502. * @dataProvider constraintSqlProvider
  503. */
  504. public function testConstraintSql($name, $data, $expected) {
  505. $driver = $this->_getMockedDriver();
  506. $schema = new SqlserverSchema($driver);
  507. $table = (new Table('schema_articles'))->addColumn('title', [
  508. 'type' => 'string',
  509. 'length' => 255
  510. ])->addColumn('author_id', [
  511. 'type' => 'integer',
  512. ])->addConstraint($name, $data);
  513. $this->assertEquals($expected, $schema->constraintSql($table, $name));
  514. }
  515. /**
  516. * Integration test for converting a Schema\Table into MySQL table creates.
  517. *
  518. * @return void
  519. */
  520. public function testCreateSql() {
  521. $driver = $this->_getMockedDriver();
  522. $connection = $this->getMock('Cake\Database\Connection', [], [], '', false);
  523. $connection->expects($this->any())->method('driver')
  524. ->will($this->returnValue($driver));
  525. $table = (new Table('schema_articles'))->addColumn('id', [
  526. 'type' => 'integer',
  527. 'null' => false
  528. ])
  529. ->addColumn('title', [
  530. 'type' => 'string',
  531. 'null' => false,
  532. ])
  533. ->addColumn('body', ['type' => 'text'])
  534. ->addColumn('created', 'datetime')
  535. ->addConstraint('primary', [
  536. 'type' => 'primary',
  537. 'columns' => ['id'],
  538. ])
  539. ->addIndex('title_idx', [
  540. 'type' => 'index',
  541. 'columns' => ['title'],
  542. ]);
  543. $expected = <<<SQL
  544. CREATE TABLE [schema_articles] (
  545. [id] SERIAL,
  546. [title] VARCHAR NOT NULL,
  547. [body] TEXT,
  548. [created] DATETIME,
  549. PRIMARY KEY ([id])
  550. )
  551. SQL;
  552. $result = $table->createSql($connection);
  553. $this->assertCount(2, $result);
  554. $this->assertEquals($expected, $result[0]);
  555. $this->assertEquals(
  556. 'CREATE INDEX [title_idx] ON [schema_articles] ([title])',
  557. $result[1]
  558. );
  559. }
  560. /**
  561. * test dropSql
  562. *
  563. * @return void
  564. */
  565. public function testDropSql() {
  566. $driver = $this->_getMockedDriver();
  567. $connection = $this->getMock('Cake\Database\Connection', [], [], '', false);
  568. $connection->expects($this->any())->method('driver')
  569. ->will($this->returnValue($driver));
  570. $table = new Table('schema_articles');
  571. $result = $table->dropSql($connection);
  572. $this->assertCount(1, $result);
  573. $this->assertEquals('DROP TABLE [schema_articles]', $result[0]);
  574. }
  575. /**
  576. * Test truncateSql()
  577. *
  578. * @return void
  579. */
  580. public function testTruncateSql() {
  581. $driver = $this->_getMockedDriver();
  582. $connection = $this->getMock('Cake\Database\Connection', [], [], '', false);
  583. $connection->expects($this->any())->method('driver')
  584. ->will($this->returnValue($driver));
  585. $table = new Table('schema_articles');
  586. $table->addColumn('id', 'integer')
  587. ->addConstraint('primary', [
  588. 'type' => 'primary',
  589. 'columns' => ['id']
  590. ]);
  591. $result = $table->truncateSql($connection);
  592. $this->assertCount(1, $result);
  593. $this->assertEquals('TRUNCATE TABLE [schema_articles]', $result[0]);
  594. }
  595. /**
  596. * Get a schema instance with a mocked driver/pdo instances
  597. *
  598. * @return Driver
  599. */
  600. protected function _getMockedDriver() {
  601. $driver = new \Cake\Database\Driver\Sqlserver();
  602. $mock = $this->getMock('FakePdo', ['quote', 'quoteIdentifier']);
  603. $mock->expects($this->any())
  604. ->method('quote')
  605. ->will($this->returnCallback(function ($value) {
  606. return '[' . $value . ']';
  607. }));
  608. $mock->expects($this->any())
  609. ->method('quoteIdentifier')
  610. ->will($this->returnCallback(function ($value) {
  611. return '[' . $value . ']';
  612. }));
  613. $driver->connection($mock);
  614. return $driver;
  615. }
  616. }