SqlserverSchemaTest.php 30 KB

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