SqlserverSchemaTest.php 28 KB

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