SqlserverSchemaTest.php 29 KB

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