SqlserverSchemaTest.php 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939
  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\Database\Schema\Collection as SchemaCollection;
  17. use Cake\Database\Schema\SqlserverSchema;
  18. use Cake\Database\Schema\Table;
  19. use Cake\Datasource\ConnectionManager;
  20. use Cake\TestSuite\TestCase;
  21. /**
  22. * SQL Server schema test case.
  23. */
  24. class SqlserverSchemaTest extends TestCase
  25. {
  26. /**
  27. * Helper method for skipping tests that need a real connection.
  28. *
  29. * @return void
  30. */
  31. protected function _needsConnection()
  32. {
  33. $config = ConnectionManager::config('test');
  34. $this->skipIf(strpos($config['driver'], 'Sqlserver') === false, 'Not using Sqlserver for test config');
  35. }
  36. /**
  37. * Helper method for testing methods.
  38. *
  39. * @return void
  40. */
  41. protected function _createTables($connection)
  42. {
  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. field1 VARCHAR(10) DEFAULT NULL,
  65. field2 VARCHAR(10) DEFAULT 'NULL',
  66. field3 VARCHAR(10) DEFAULT 'O''hare',
  67. CONSTRAINT [content_idx] UNIQUE ([title], [body]),
  68. CONSTRAINT [author_idx] FOREIGN KEY ([author_id]) REFERENCES [schema_authors] ([id]) ON DELETE CASCADE ON UPDATE CASCADE
  69. )
  70. SQL;
  71. $connection->execute($table);
  72. $connection->execute('CREATE INDEX [author_idx] ON [schema_articles] ([author_id])');
  73. }
  74. /**
  75. * Data provider for convert column testing
  76. *
  77. * @return array
  78. */
  79. public static function convertColumnProvider()
  80. {
  81. return [
  82. [
  83. 'DATETIME',
  84. null,
  85. null,
  86. null,
  87. ['type' => 'timestamp', 'length' => null]
  88. ],
  89. [
  90. 'DATE',
  91. null,
  92. null,
  93. null,
  94. ['type' => 'date', 'length' => null]
  95. ],
  96. [
  97. 'TIME',
  98. null,
  99. null,
  100. null,
  101. ['type' => 'time', 'length' => null]
  102. ],
  103. [
  104. 'SMALLINT',
  105. null,
  106. 4,
  107. null,
  108. ['type' => 'integer', 'length' => 4]
  109. ],
  110. [
  111. 'INTEGER',
  112. null,
  113. null,
  114. null,
  115. ['type' => 'integer', 'length' => 10]
  116. ],
  117. [
  118. 'INTEGER',
  119. null,
  120. 8,
  121. null,
  122. ['type' => 'integer', 'length' => 8]
  123. ],
  124. [
  125. 'BIGINT',
  126. null,
  127. null,
  128. null,
  129. ['type' => 'biginteger', 'length' => 20]
  130. ],
  131. [
  132. 'NUMERIC',
  133. null,
  134. 15,
  135. 5,
  136. ['type' => 'decimal', 'length' => 15, 'precision' => 5]
  137. ],
  138. [
  139. 'DECIMAL',
  140. null,
  141. 11,
  142. 3,
  143. ['type' => 'decimal', 'length' => 11, 'precision' => 3]
  144. ],
  145. [
  146. 'MONEY',
  147. null,
  148. null,
  149. null,
  150. ['type' => 'decimal', 'length' => null, 'precision' => null]
  151. ],
  152. [
  153. 'VARCHAR',
  154. null,
  155. null,
  156. null,
  157. ['type' => 'string', 'length' => 255]
  158. ],
  159. [
  160. 'VARCHAR',
  161. 10,
  162. null,
  163. null,
  164. ['type' => 'string', 'length' => 10]
  165. ],
  166. [
  167. 'NVARCHAR',
  168. 50,
  169. null,
  170. null,
  171. ['type' => 'string', 'length' => 50]
  172. ],
  173. [
  174. 'CHAR',
  175. 10,
  176. null,
  177. null,
  178. ['type' => 'string', 'fixed' => true, 'length' => 10]
  179. ],
  180. [
  181. 'NCHAR',
  182. 10,
  183. null,
  184. null,
  185. ['type' => 'string', 'fixed' => true, 'length' => 10]
  186. ],
  187. [
  188. 'UNIQUEIDENTIFIER',
  189. null,
  190. null,
  191. null,
  192. ['type' => 'uuid']
  193. ],
  194. [
  195. 'TEXT',
  196. null,
  197. null,
  198. null,
  199. ['type' => 'text', 'length' => null]
  200. ],
  201. [
  202. 'REAL',
  203. null,
  204. null,
  205. null,
  206. ['type' => 'float', 'length' => null]
  207. ],
  208. [
  209. 'VARCHAR',
  210. -1,
  211. null,
  212. null,
  213. ['type' => 'text', 'length' => null]
  214. ],
  215. ];
  216. }
  217. /**
  218. * Test parsing Sqlserver column types from field description.
  219. *
  220. * @dataProvider convertColumnProvider
  221. * @return void
  222. */
  223. public function testConvertColumn($type, $length, $precision, $scale, $expected)
  224. {
  225. $field = [
  226. 'name' => 'field',
  227. 'type' => $type,
  228. 'null' => '1',
  229. 'default' => 'Default value',
  230. 'char_length' => $length,
  231. 'precision' => $precision,
  232. 'scale' => $scale
  233. ];
  234. $expected += [
  235. 'null' => true,
  236. 'default' => 'Default value',
  237. ];
  238. $driver = $this->getMockBuilder('Cake\Database\Driver\Sqlserver')->getMock();
  239. $dialect = new SqlserverSchema($driver);
  240. $table = $this->getMockBuilder('Cake\Database\Schema\Table')
  241. ->setConstructorArgs(['table'])
  242. ->getMock();
  243. $table->expects($this->at(0))->method('addColumn')->with('field', $expected);
  244. $dialect->convertColumnDescription($table, $field);
  245. }
  246. /**
  247. * Test listing tables with Sqlserver
  248. *
  249. * @return void
  250. */
  251. public function testListTables()
  252. {
  253. $connection = ConnectionManager::get('test');
  254. $this->_createTables($connection);
  255. $schema = new SchemaCollection($connection);
  256. $result = $schema->listTables();
  257. $this->assertInternalType('array', $result);
  258. $this->assertContains('schema_articles', $result);
  259. $this->assertContains('schema_authors', $result);
  260. }
  261. /**
  262. * Test describing a table with Sqlserver
  263. *
  264. * @return void
  265. */
  266. public function testDescribeTable()
  267. {
  268. $connection = ConnectionManager::get('test');
  269. $this->_createTables($connection);
  270. $schema = new SchemaCollection($connection);
  271. $result = $schema->describe('schema_articles');
  272. $expected = [
  273. 'id' => [
  274. 'type' => 'biginteger',
  275. 'null' => false,
  276. 'default' => null,
  277. 'length' => 19,
  278. 'precision' => null,
  279. 'unsigned' => null,
  280. 'autoIncrement' => null,
  281. 'comment' => null,
  282. ],
  283. 'title' => [
  284. 'type' => 'string',
  285. 'null' => true,
  286. 'default' => null,
  287. 'length' => 20,
  288. 'precision' => null,
  289. 'comment' => null,
  290. 'fixed' => null,
  291. ],
  292. 'body' => [
  293. 'type' => 'string',
  294. 'null' => true,
  295. 'default' => null,
  296. 'length' => 1000,
  297. 'precision' => null,
  298. 'fixed' => null,
  299. 'comment' => null,
  300. ],
  301. 'author_id' => [
  302. 'type' => 'integer',
  303. 'null' => false,
  304. 'default' => null,
  305. 'length' => 10,
  306. 'precision' => null,
  307. 'unsigned' => null,
  308. 'autoIncrement' => null,
  309. 'comment' => null,
  310. ],
  311. 'published' => [
  312. 'type' => 'boolean',
  313. 'null' => true,
  314. 'default' => 0,
  315. 'length' => null,
  316. 'precision' => null,
  317. 'comment' => null,
  318. ],
  319. 'views' => [
  320. 'type' => 'integer',
  321. 'null' => true,
  322. 'default' => 0,
  323. 'length' => 5,
  324. 'precision' => null,
  325. 'unsigned' => null,
  326. 'autoIncrement' => null,
  327. 'comment' => null,
  328. ],
  329. 'created' => [
  330. 'type' => 'timestamp',
  331. 'null' => true,
  332. 'default' => null,
  333. 'length' => null,
  334. 'precision' => null,
  335. 'comment' => null,
  336. ],
  337. 'field1' => [
  338. 'type' => 'string',
  339. 'null' => true,
  340. 'default' => null,
  341. 'length' => 10,
  342. 'precision' => null,
  343. 'fixed' => null,
  344. 'comment' => null,
  345. ],
  346. 'field2' => [
  347. 'type' => 'string',
  348. 'null' => true,
  349. 'default' => 'NULL',
  350. 'length' => 10,
  351. 'precision' => null,
  352. 'fixed' => null,
  353. 'comment' => null,
  354. ],
  355. 'field3' => [
  356. 'type' => 'string',
  357. 'null' => true,
  358. 'default' => 'O\'hare',
  359. 'length' => 10,
  360. 'precision' => null,
  361. 'fixed' => null,
  362. 'comment' => null,
  363. ],
  364. ];
  365. $this->assertEquals(['id'], $result->primaryKey());
  366. foreach ($expected as $field => $definition) {
  367. $this->assertEquals($definition, $result->column($field), 'Failed to match field ' . $field);
  368. }
  369. }
  370. /**
  371. * Test describing a table with postgres and composite keys
  372. *
  373. * @return void
  374. */
  375. public function testDescribeTableCompositeKey()
  376. {
  377. $this->_needsConnection();
  378. $connection = ConnectionManager::get('test');
  379. $sql = <<<SQL
  380. CREATE TABLE schema_composite (
  381. [id] INTEGER IDENTITY(1, 1),
  382. [site_id] INTEGER NOT NULL,
  383. [name] VARCHAR(255),
  384. PRIMARY KEY([id], [site_id])
  385. );
  386. SQL;
  387. $connection->execute($sql);
  388. $schema = new SchemaCollection($connection);
  389. $result = $schema->describe('schema_composite');
  390. $connection->execute('DROP TABLE schema_composite');
  391. $this->assertEquals(['id', 'site_id'], $result->primaryKey());
  392. $this->assertNull($result->column('site_id')['autoIncrement'], 'site_id should not be autoincrement');
  393. $this->assertTrue($result->column('id')['autoIncrement'], 'id should be autoincrement');
  394. }
  395. /**
  396. * Test that describe accepts tablenames containing `schema.table`.
  397. *
  398. * @return void
  399. */
  400. public function testDescribeWithSchemaName()
  401. {
  402. $connection = ConnectionManager::get('test');
  403. $this->_createTables($connection);
  404. $schema = new SchemaCollection($connection);
  405. $result = $schema->describe('dbo.schema_articles');
  406. $this->assertEquals(['id'], $result->primaryKey());
  407. $this->assertEquals('schema_articles', $result->name());
  408. }
  409. /**
  410. * Test describing a table with indexes
  411. *
  412. * @return void
  413. */
  414. public function testDescribeTableIndexes()
  415. {
  416. $connection = ConnectionManager::get('test');
  417. $this->_createTables($connection);
  418. $schema = new SchemaCollection($connection);
  419. $result = $schema->describe('schema_articles');
  420. $this->assertInstanceOf('Cake\Database\Schema\Table', $result);
  421. $this->assertCount(3, $result->constraints());
  422. $expected = [
  423. 'primary' => [
  424. 'type' => 'primary',
  425. 'columns' => ['id'],
  426. 'length' => []
  427. ],
  428. 'content_idx' => [
  429. 'type' => 'unique',
  430. 'columns' => ['title', 'body'],
  431. 'length' => []
  432. ],
  433. 'author_idx' => [
  434. 'type' => 'foreign',
  435. 'columns' => ['author_id'],
  436. 'references' => ['schema_authors', 'id'],
  437. 'length' => [],
  438. 'update' => 'cascade',
  439. 'delete' => 'cascade',
  440. ]
  441. ];
  442. $this->assertEquals($expected['primary'], $result->constraint('primary'));
  443. $this->assertEquals($expected['content_idx'], $result->constraint('content_idx'));
  444. $this->assertEquals($expected['author_idx'], $result->constraint('author_idx'));
  445. $this->assertCount(1, $result->indexes());
  446. $expected = [
  447. 'type' => 'index',
  448. 'columns' => ['author_id'],
  449. 'length' => []
  450. ];
  451. $this->assertEquals($expected, $result->index('author_idx'));
  452. }
  453. /**
  454. * Column provider for creating column sql
  455. *
  456. * @return array
  457. */
  458. public static function columnSqlProvider()
  459. {
  460. return [
  461. // strings
  462. [
  463. 'title',
  464. ['type' => 'string', 'length' => 25, 'null' => false],
  465. '[title] NVARCHAR(25) NOT NULL'
  466. ],
  467. [
  468. 'title',
  469. ['type' => 'string', 'length' => 25, 'null' => true, 'default' => 'ignored'],
  470. '[title] NVARCHAR(25) DEFAULT NULL'
  471. ],
  472. [
  473. 'id',
  474. ['type' => 'string', 'length' => 32, 'fixed' => true, 'null' => false],
  475. '[id] NCHAR(32) NOT NULL'
  476. ],
  477. [
  478. 'id',
  479. ['type' => 'uuid', 'null' => false],
  480. '[id] UNIQUEIDENTIFIER NOT NULL'
  481. ],
  482. [
  483. 'role',
  484. ['type' => 'string', 'length' => 10, 'null' => false, 'default' => 'admin'],
  485. "[role] NVARCHAR(10) NOT NULL DEFAULT [admin]"
  486. ],
  487. [
  488. 'title',
  489. ['type' => 'string'],
  490. '[title] NVARCHAR(255)'
  491. ],
  492. // Text
  493. [
  494. 'body',
  495. ['type' => 'text', 'null' => false],
  496. '[body] NVARCHAR(MAX) NOT NULL'
  497. ],
  498. [
  499. 'body',
  500. ['type' => 'text', 'length' => Table::LENGTH_TINY, 'null' => false],
  501. sprintf('[body] NVARCHAR(%s) NOT NULL', Table::LENGTH_TINY)
  502. ],
  503. [
  504. 'body',
  505. ['type' => 'text', 'length' => Table::LENGTH_MEDIUM, 'null' => false],
  506. '[body] NVARCHAR(MAX) NOT NULL'
  507. ],
  508. [
  509. 'body',
  510. ['type' => 'text', 'length' => Table::LENGTH_LONG, 'null' => false],
  511. '[body] NVARCHAR(MAX) NOT NULL'
  512. ],
  513. // Integers
  514. [
  515. 'post_id',
  516. ['type' => 'integer', 'length' => 11],
  517. '[post_id] INTEGER'
  518. ],
  519. [
  520. 'post_id',
  521. ['type' => 'biginteger', 'length' => 20],
  522. '[post_id] BIGINT'
  523. ],
  524. // Decimal
  525. [
  526. 'value',
  527. ['type' => 'decimal'],
  528. '[value] DECIMAL'
  529. ],
  530. [
  531. 'value',
  532. ['type' => 'decimal', 'length' => 11],
  533. '[value] DECIMAL(11,0)'
  534. ],
  535. [
  536. 'value',
  537. ['type' => 'decimal', 'length' => 12, 'precision' => 5],
  538. '[value] DECIMAL(12,5)'
  539. ],
  540. // Float
  541. [
  542. 'value',
  543. ['type' => 'float'],
  544. '[value] FLOAT'
  545. ],
  546. [
  547. 'value',
  548. ['type' => 'float', 'length' => 11, 'precision' => 3],
  549. '[value] FLOAT(3)'
  550. ],
  551. // Binary
  552. [
  553. 'img',
  554. ['type' => 'binary', 'length' => null],
  555. '[img] VARBINARY(MAX)'
  556. ],
  557. [
  558. 'img',
  559. ['type' => 'binary', 'length' => Table::LENGTH_TINY],
  560. sprintf('[img] VARBINARY(%s)', Table::LENGTH_TINY)
  561. ],
  562. [
  563. 'img',
  564. ['type' => 'binary', 'length' => Table::LENGTH_MEDIUM],
  565. '[img] VARBINARY(MAX)'
  566. ],
  567. [
  568. 'img',
  569. ['type' => 'binary', 'length' => Table::LENGTH_LONG],
  570. '[img] VARBINARY(MAX)'
  571. ],
  572. // Boolean
  573. [
  574. 'checked',
  575. ['type' => 'boolean', 'default' => false],
  576. '[checked] BIT DEFAULT 0'
  577. ],
  578. [
  579. 'checked',
  580. ['type' => 'boolean', 'default' => true, 'null' => false],
  581. '[checked] BIT NOT NULL DEFAULT 1'
  582. ],
  583. // datetimes
  584. [
  585. 'created',
  586. ['type' => 'datetime'],
  587. '[created] DATETIME'
  588. ],
  589. // Date & Time
  590. [
  591. 'start_date',
  592. ['type' => 'date'],
  593. '[start_date] DATE'
  594. ],
  595. [
  596. 'start_time',
  597. ['type' => 'time'],
  598. '[start_time] TIME'
  599. ],
  600. // timestamps
  601. [
  602. 'created',
  603. ['type' => 'timestamp', 'null' => true],
  604. '[created] DATETIME DEFAULT NULL'
  605. ],
  606. ];
  607. }
  608. /**
  609. * Test generating column definitions
  610. *
  611. * @dataProvider columnSqlProvider
  612. * @return void
  613. */
  614. public function testColumnSql($name, $data, $expected)
  615. {
  616. $driver = $this->_getMockedDriver();
  617. $schema = new SqlserverSchema($driver);
  618. $table = (new Table('schema_articles'))->addColumn($name, $data);
  619. $this->assertEquals($expected, $schema->columnSql($table, $name));
  620. }
  621. /**
  622. * Provide data for testing constraintSql
  623. *
  624. * @return array
  625. */
  626. public static function constraintSqlProvider()
  627. {
  628. return [
  629. [
  630. 'primary',
  631. ['type' => 'primary', 'columns' => ['title']],
  632. 'PRIMARY KEY ([title])'
  633. ],
  634. [
  635. 'unique_idx',
  636. ['type' => 'unique', 'columns' => ['title', 'author_id']],
  637. 'CONSTRAINT [unique_idx] UNIQUE ([title], [author_id])'
  638. ],
  639. [
  640. 'author_id_idx',
  641. ['type' => 'foreign', 'columns' => ['author_id'], 'references' => ['authors', 'id']],
  642. 'CONSTRAINT [author_id_idx] FOREIGN KEY ([author_id]) ' .
  643. 'REFERENCES [authors] ([id]) ON UPDATE SET NULL ON DELETE SET NULL'
  644. ],
  645. [
  646. 'author_id_idx',
  647. ['type' => 'foreign', 'columns' => ['author_id'], 'references' => ['authors', 'id'], 'update' => 'cascade'],
  648. 'CONSTRAINT [author_id_idx] FOREIGN KEY ([author_id]) ' .
  649. 'REFERENCES [authors] ([id]) ON UPDATE CASCADE ON DELETE SET NULL'
  650. ],
  651. [
  652. 'author_id_idx',
  653. ['type' => 'foreign', 'columns' => ['author_id'], 'references' => ['authors', 'id'], 'update' => 'setDefault'],
  654. 'CONSTRAINT [author_id_idx] FOREIGN KEY ([author_id]) ' .
  655. 'REFERENCES [authors] ([id]) ON UPDATE SET DEFAULT ON DELETE SET NULL'
  656. ],
  657. [
  658. 'author_id_idx',
  659. ['type' => 'foreign', 'columns' => ['author_id'], 'references' => ['authors', 'id'], 'update' => 'setNull'],
  660. 'CONSTRAINT [author_id_idx] FOREIGN KEY ([author_id]) ' .
  661. 'REFERENCES [authors] ([id]) ON UPDATE SET NULL ON DELETE SET NULL'
  662. ],
  663. [
  664. 'author_id_idx',
  665. ['type' => 'foreign', 'columns' => ['author_id'], 'references' => ['authors', 'id'], 'update' => 'noAction'],
  666. 'CONSTRAINT [author_id_idx] FOREIGN KEY ([author_id]) ' .
  667. 'REFERENCES [authors] ([id]) ON UPDATE NO ACTION ON DELETE SET NULL'
  668. ],
  669. ];
  670. }
  671. /**
  672. * Test the constraintSql method.
  673. *
  674. * @dataProvider constraintSqlProvider
  675. */
  676. public function testConstraintSql($name, $data, $expected)
  677. {
  678. $driver = $this->_getMockedDriver();
  679. $schema = new SqlserverSchema($driver);
  680. $table = (new Table('schema_articles'))->addColumn('title', [
  681. 'type' => 'string',
  682. 'length' => 255
  683. ])->addColumn('author_id', [
  684. 'type' => 'integer',
  685. ])->addConstraint($name, $data);
  686. $this->assertEquals($expected, $schema->constraintSql($table, $name));
  687. }
  688. /**
  689. * Test the addConstraintSql method.
  690. *
  691. * @return void
  692. */
  693. public function testAddConstraintSql()
  694. {
  695. $driver = $this->_getMockedDriver();
  696. $connection = $this->getMockBuilder('Cake\Database\Connection')
  697. ->disableOriginalConstructor()
  698. ->getMock();
  699. $connection->expects($this->any())->method('driver')
  700. ->will($this->returnValue($driver));
  701. $table = (new Table('posts'))
  702. ->addColumn('author_id', [
  703. 'type' => 'integer',
  704. 'null' => false
  705. ])
  706. ->addColumn('category_id', [
  707. 'type' => 'integer',
  708. 'null' => false
  709. ])
  710. ->addColumn('category_name', [
  711. 'type' => 'integer',
  712. 'null' => false
  713. ])
  714. ->addConstraint('author_fk', [
  715. 'type' => 'foreign',
  716. 'columns' => ['author_id'],
  717. 'references' => ['authors', 'id'],
  718. 'update' => 'cascade',
  719. 'delete' => 'cascade'
  720. ])
  721. ->addConstraint('category_fk', [
  722. 'type' => 'foreign',
  723. 'columns' => ['category_id', 'category_name'],
  724. 'references' => ['categories', ['id', 'name']],
  725. 'update' => 'cascade',
  726. 'delete' => 'cascade'
  727. ]);
  728. $expected = [
  729. 'ALTER TABLE [posts] ADD CONSTRAINT [author_fk] FOREIGN KEY ([author_id]) REFERENCES [authors] ([id]) ON UPDATE CASCADE ON DELETE CASCADE;',
  730. 'ALTER TABLE [posts] ADD CONSTRAINT [category_fk] FOREIGN KEY ([category_id], [category_name]) REFERENCES [categories] ([id], [name]) ON UPDATE CASCADE ON DELETE CASCADE;'
  731. ];
  732. $result = $table->addConstraintSql($connection);
  733. $this->assertCount(2, $result);
  734. $this->assertEquals($expected, $result);
  735. }
  736. /**
  737. * Test the dropConstraintSql method.
  738. *
  739. * @return void
  740. */
  741. public function testDropConstraintSql()
  742. {
  743. $driver = $this->_getMockedDriver();
  744. $connection = $this->getMockBuilder('Cake\Database\Connection')
  745. ->disableOriginalConstructor()
  746. ->getMock();
  747. $connection->expects($this->any())->method('driver')
  748. ->will($this->returnValue($driver));
  749. $table = (new Table('posts'))
  750. ->addColumn('author_id', [
  751. 'type' => 'integer',
  752. 'null' => false
  753. ])
  754. ->addColumn('category_id', [
  755. 'type' => 'integer',
  756. 'null' => false
  757. ])
  758. ->addColumn('category_name', [
  759. 'type' => 'integer',
  760. 'null' => false
  761. ])
  762. ->addConstraint('author_fk', [
  763. 'type' => 'foreign',
  764. 'columns' => ['author_id'],
  765. 'references' => ['authors', 'id'],
  766. 'update' => 'cascade',
  767. 'delete' => 'cascade'
  768. ])
  769. ->addConstraint('category_fk', [
  770. 'type' => 'foreign',
  771. 'columns' => ['category_id', 'category_name'],
  772. 'references' => ['categories', ['id', 'name']],
  773. 'update' => 'cascade',
  774. 'delete' => 'cascade'
  775. ]);
  776. $expected = [
  777. 'ALTER TABLE [posts] DROP CONSTRAINT [author_fk];',
  778. 'ALTER TABLE [posts] DROP CONSTRAINT [category_fk];'
  779. ];
  780. $result = $table->dropConstraintSql($connection);
  781. $this->assertCount(2, $result);
  782. $this->assertEquals($expected, $result);
  783. }
  784. /**
  785. * Integration test for converting a Schema\Table into MySQL table creates.
  786. *
  787. * @return void
  788. */
  789. public function testCreateSql()
  790. {
  791. $driver = $this->_getMockedDriver();
  792. $connection = $this->getMockBuilder('Cake\Database\Connection')
  793. ->disableOriginalConstructor()
  794. ->getMock();
  795. $connection->expects($this->any())->method('driver')
  796. ->will($this->returnValue($driver));
  797. $table = (new Table('schema_articles'))->addColumn('id', [
  798. 'type' => 'integer',
  799. 'null' => false
  800. ])
  801. ->addColumn('title', [
  802. 'type' => 'string',
  803. 'null' => false,
  804. ])
  805. ->addColumn('body', ['type' => 'text'])
  806. ->addColumn('data', ['type' => 'json'])
  807. ->addColumn('created', 'datetime')
  808. ->addConstraint('primary', [
  809. 'type' => 'primary',
  810. 'columns' => ['id'],
  811. ])
  812. ->addIndex('title_idx', [
  813. 'type' => 'index',
  814. 'columns' => ['title'],
  815. ]);
  816. $expected = <<<SQL
  817. CREATE TABLE [schema_articles] (
  818. [id] INTEGER IDENTITY(1, 1),
  819. [title] NVARCHAR(255) NOT NULL,
  820. [body] NVARCHAR(MAX),
  821. [data] NVARCHAR(MAX),
  822. [created] DATETIME,
  823. PRIMARY KEY ([id])
  824. )
  825. SQL;
  826. $result = $table->createSql($connection);
  827. $this->assertCount(2, $result);
  828. $this->assertEquals(str_replace("\r\n", "\n", $expected), str_replace("\r\n", "\n", $result[0]));
  829. $this->assertEquals(
  830. 'CREATE INDEX [title_idx] ON [schema_articles] ([title])',
  831. $result[1]
  832. );
  833. }
  834. /**
  835. * test dropSql
  836. *
  837. * @return void
  838. */
  839. public function testDropSql()
  840. {
  841. $driver = $this->_getMockedDriver();
  842. $connection = $this->getMockBuilder('Cake\Database\Connection')
  843. ->disableOriginalConstructor()
  844. ->getMock();
  845. $connection->expects($this->any())->method('driver')
  846. ->will($this->returnValue($driver));
  847. $table = new Table('schema_articles');
  848. $result = $table->dropSql($connection);
  849. $this->assertCount(1, $result);
  850. $this->assertEquals('DROP TABLE [schema_articles]', $result[0]);
  851. }
  852. /**
  853. * Test truncateSql()
  854. *
  855. * @return void
  856. */
  857. public function testTruncateSql()
  858. {
  859. $driver = $this->_getMockedDriver();
  860. $connection = $this->getMockBuilder('Cake\Database\Connection')
  861. ->disableOriginalConstructor()
  862. ->getMock();
  863. $connection->expects($this->any())->method('driver')
  864. ->will($this->returnValue($driver));
  865. $table = new Table('schema_articles');
  866. $table->addColumn('id', 'integer')
  867. ->addConstraint('primary', [
  868. 'type' => 'primary',
  869. 'columns' => ['id']
  870. ]);
  871. $result = $table->truncateSql($connection);
  872. $this->assertCount(2, $result);
  873. $this->assertEquals('DELETE FROM [schema_articles]', $result[0]);
  874. $this->assertEquals("DBCC CHECKIDENT('schema_articles', RESEED, 0)", $result[1]);
  875. }
  876. /**
  877. * Get a schema instance with a mocked driver/pdo instances
  878. *
  879. * @return \Cake\Database\Driver
  880. */
  881. protected function _getMockedDriver()
  882. {
  883. $driver = new \Cake\Database\Driver\Sqlserver();
  884. $mock = $this->getMockBuilder('FakePdo')
  885. ->setMethods(['quote'])
  886. ->getMock();
  887. $mock->expects($this->any())
  888. ->method('quote')
  889. ->will($this->returnCallback(function ($value) {
  890. return '[' . $value . ']';
  891. }));
  892. $driver->connection($mock);
  893. return $driver;
  894. }
  895. }