SqlserverSchemaTest.php 15 KB

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