SqlserverSchemaTest.php 32 KB

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