SqlserverSchemaTest.php 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023
  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. $column = $result->column($field);
  399. $this->assertEquals($definition, $column, 'Failed to match field ' . $field);
  400. $this->assertSame($definition['length'], $column['length']);
  401. $this->assertSame($definition['precision'], $column['precision']);
  402. }
  403. }
  404. /**
  405. * Test describing a table with postgres and composite keys
  406. *
  407. * @return void
  408. */
  409. public function testDescribeTableCompositeKey()
  410. {
  411. $this->_needsConnection();
  412. $connection = ConnectionManager::get('test');
  413. $sql = <<<SQL
  414. CREATE TABLE schema_composite (
  415. [id] INTEGER IDENTITY(1, 1),
  416. [site_id] INTEGER NOT NULL,
  417. [name] VARCHAR(255),
  418. PRIMARY KEY([id], [site_id])
  419. );
  420. SQL;
  421. $connection->execute($sql);
  422. $schema = new SchemaCollection($connection);
  423. $result = $schema->describe('schema_composite');
  424. $connection->execute('DROP TABLE schema_composite');
  425. $this->assertEquals(['id', 'site_id'], $result->primaryKey());
  426. $this->assertNull($result->column('site_id')['autoIncrement'], 'site_id should not be autoincrement');
  427. $this->assertTrue($result->column('id')['autoIncrement'], 'id should be autoincrement');
  428. }
  429. /**
  430. * Test that describe accepts tablenames containing `schema.table`.
  431. *
  432. * @return void
  433. */
  434. public function testDescribeWithSchemaName()
  435. {
  436. $connection = ConnectionManager::get('test');
  437. $this->_createTables($connection);
  438. $schema = new SchemaCollection($connection);
  439. $result = $schema->describe('dbo.schema_articles');
  440. $this->assertEquals(['id'], $result->primaryKey());
  441. $this->assertEquals('schema_articles', $result->name());
  442. }
  443. /**
  444. * Test describing a table with indexes
  445. *
  446. * @return void
  447. */
  448. public function testDescribeTableIndexes()
  449. {
  450. $connection = ConnectionManager::get('test');
  451. $this->_createTables($connection);
  452. $schema = new SchemaCollection($connection);
  453. $result = $schema->describe('schema_articles');
  454. $this->assertInstanceOf('Cake\Database\Schema\Table', $result);
  455. $this->assertCount(3, $result->constraints());
  456. $expected = [
  457. 'primary' => [
  458. 'type' => 'primary',
  459. 'columns' => ['id'],
  460. 'length' => []
  461. ],
  462. 'content_idx' => [
  463. 'type' => 'unique',
  464. 'columns' => ['title', 'body'],
  465. 'length' => []
  466. ],
  467. 'author_idx' => [
  468. 'type' => 'foreign',
  469. 'columns' => ['author_id'],
  470. 'references' => ['schema_authors', 'id'],
  471. 'length' => [],
  472. 'update' => 'cascade',
  473. 'delete' => 'cascade',
  474. ]
  475. ];
  476. $this->assertEquals($expected['primary'], $result->constraint('primary'));
  477. $this->assertEquals($expected['content_idx'], $result->constraint('content_idx'));
  478. $this->assertEquals($expected['author_idx'], $result->constraint('author_idx'));
  479. $this->assertCount(1, $result->indexes());
  480. $expected = [
  481. 'type' => 'index',
  482. 'columns' => ['author_id'],
  483. 'length' => []
  484. ];
  485. $this->assertEquals($expected, $result->index('author_idx'));
  486. }
  487. /**
  488. * Column provider for creating column sql
  489. *
  490. * @return array
  491. */
  492. public static function columnSqlProvider()
  493. {
  494. return [
  495. // strings
  496. [
  497. 'title',
  498. ['type' => 'string', 'length' => 25, 'null' => false],
  499. '[title] NVARCHAR(25) NOT NULL'
  500. ],
  501. [
  502. 'title',
  503. ['type' => 'string', 'length' => 25, 'null' => true, 'default' => 'ignored'],
  504. "[title] NVARCHAR(25) DEFAULT 'ignored'"
  505. ],
  506. [
  507. 'id',
  508. ['type' => 'string', 'length' => 32, 'fixed' => true, 'null' => false],
  509. '[id] NCHAR(32) NOT NULL'
  510. ],
  511. [
  512. 'id',
  513. ['type' => 'uuid', 'null' => false],
  514. '[id] UNIQUEIDENTIFIER NOT NULL'
  515. ],
  516. [
  517. 'role',
  518. ['type' => 'string', 'length' => 10, 'null' => false, 'default' => 'admin'],
  519. "[role] NVARCHAR(10) NOT NULL DEFAULT 'admin'"
  520. ],
  521. [
  522. 'title',
  523. ['type' => 'string'],
  524. '[title] NVARCHAR(255)'
  525. ],
  526. [
  527. 'title',
  528. ['type' => 'string', 'length' => 25, 'null' => false, 'collate' => 'Japanese_Unicode_CI_AI'],
  529. '[title] NVARCHAR(25) COLLATE Japanese_Unicode_CI_AI NOT NULL'
  530. ],
  531. // Text
  532. [
  533. 'body',
  534. ['type' => 'text', 'null' => false],
  535. '[body] NVARCHAR(MAX) NOT NULL'
  536. ],
  537. [
  538. 'body',
  539. ['type' => 'text', 'length' => TableSchema::LENGTH_TINY, 'null' => false],
  540. sprintf('[body] NVARCHAR(%s) NOT NULL', TableSchema::LENGTH_TINY)
  541. ],
  542. [
  543. 'body',
  544. ['type' => 'text', 'length' => TableSchema::LENGTH_MEDIUM, 'null' => false],
  545. '[body] NVARCHAR(MAX) NOT NULL'
  546. ],
  547. [
  548. 'body',
  549. ['type' => 'text', 'length' => TableSchema::LENGTH_LONG, 'null' => false],
  550. '[body] NVARCHAR(MAX) NOT NULL'
  551. ],
  552. [
  553. 'body',
  554. ['type' => 'text', 'null' => false, 'collate' => 'Japanese_Unicode_CI_AI'],
  555. '[body] NVARCHAR(MAX) COLLATE Japanese_Unicode_CI_AI NOT NULL'
  556. ],
  557. // Integers
  558. [
  559. 'post_id',
  560. ['type' => 'smallinteger', 'length' => 11],
  561. '[post_id] SMALLINT'
  562. ],
  563. [
  564. 'post_id',
  565. ['type' => 'tinyinteger', 'length' => 11],
  566. '[post_id] TINYINT'
  567. ],
  568. [
  569. 'post_id',
  570. ['type' => 'integer', 'length' => 11],
  571. '[post_id] INTEGER'
  572. ],
  573. [
  574. 'post_id',
  575. ['type' => 'biginteger', 'length' => 20],
  576. '[post_id] BIGINT'
  577. ],
  578. // Decimal
  579. [
  580. 'value',
  581. ['type' => 'decimal'],
  582. '[value] DECIMAL'
  583. ],
  584. [
  585. 'value',
  586. ['type' => 'decimal', 'length' => 11],
  587. '[value] DECIMAL(11,0)'
  588. ],
  589. [
  590. 'value',
  591. ['type' => 'decimal', 'length' => 12, 'precision' => 5],
  592. '[value] DECIMAL(12,5)'
  593. ],
  594. // Float
  595. [
  596. 'value',
  597. ['type' => 'float'],
  598. '[value] FLOAT'
  599. ],
  600. [
  601. 'value',
  602. ['type' => 'float', 'length' => 11, 'precision' => 3],
  603. '[value] FLOAT(3)'
  604. ],
  605. // Binary
  606. [
  607. 'img',
  608. ['type' => 'binary', 'length' => null],
  609. '[img] VARBINARY(MAX)'
  610. ],
  611. [
  612. 'img',
  613. ['type' => 'binary', 'length' => TableSchema::LENGTH_TINY],
  614. sprintf('[img] VARBINARY(%s)', TableSchema::LENGTH_TINY)
  615. ],
  616. [
  617. 'img',
  618. ['type' => 'binary', 'length' => TableSchema::LENGTH_MEDIUM],
  619. '[img] VARBINARY(MAX)'
  620. ],
  621. [
  622. 'img',
  623. ['type' => 'binary', 'length' => TableSchema::LENGTH_LONG],
  624. '[img] VARBINARY(MAX)'
  625. ],
  626. // Boolean
  627. [
  628. 'checked',
  629. ['type' => 'boolean', 'default' => false],
  630. '[checked] BIT DEFAULT 0'
  631. ],
  632. [
  633. 'checked',
  634. ['type' => 'boolean', 'default' => true, 'null' => false],
  635. '[checked] BIT NOT NULL DEFAULT 1'
  636. ],
  637. // Datetime
  638. [
  639. 'created',
  640. ['type' => 'datetime'],
  641. '[created] DATETIME'
  642. ],
  643. [
  644. 'open_date',
  645. ['type' => 'datetime', 'null' => false, 'default' => '2016-12-07 23:04:00'],
  646. '[open_date] DATETIME NOT NULL DEFAULT \'2016-12-07 23:04:00\''
  647. ],
  648. [
  649. 'open_date',
  650. ['type' => 'datetime', 'null' => false, 'default' => 'current_timestamp'],
  651. '[open_date] DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP'
  652. ],
  653. [
  654. 'null_date',
  655. ['type' => 'datetime', 'null' => true, 'default' => 'current_timestamp'],
  656. '[null_date] DATETIME DEFAULT CURRENT_TIMESTAMP'
  657. ],
  658. [
  659. 'null_date',
  660. ['type' => 'datetime', 'null' => true],
  661. '[null_date] DATETIME DEFAULT NULL'
  662. ],
  663. // Date & Time
  664. [
  665. 'start_date',
  666. ['type' => 'date'],
  667. '[start_date] DATE'
  668. ],
  669. [
  670. 'start_time',
  671. ['type' => 'time'],
  672. '[start_time] TIME'
  673. ],
  674. // Timestamp
  675. [
  676. 'created',
  677. ['type' => 'timestamp', 'null' => true],
  678. '[created] DATETIME DEFAULT NULL'
  679. ],
  680. ];
  681. }
  682. /**
  683. * Test generating column definitions
  684. *
  685. * @dataProvider columnSqlProvider
  686. * @return void
  687. */
  688. public function testColumnSql($name, $data, $expected)
  689. {
  690. $driver = $this->_getMockedDriver();
  691. $schema = new SqlserverSchema($driver);
  692. $table = (new TableSchema('schema_articles'))->addColumn($name, $data);
  693. $this->assertEquals($expected, $schema->columnSql($table, $name));
  694. }
  695. /**
  696. * Provide data for testing constraintSql
  697. *
  698. * @return array
  699. */
  700. public static function constraintSqlProvider()
  701. {
  702. return [
  703. [
  704. 'primary',
  705. ['type' => 'primary', 'columns' => ['title']],
  706. 'PRIMARY KEY ([title])'
  707. ],
  708. [
  709. 'unique_idx',
  710. ['type' => 'unique', 'columns' => ['title', 'author_id']],
  711. 'CONSTRAINT [unique_idx] UNIQUE ([title], [author_id])'
  712. ],
  713. [
  714. 'author_id_idx',
  715. ['type' => 'foreign', 'columns' => ['author_id'], 'references' => ['authors', 'id']],
  716. 'CONSTRAINT [author_id_idx] FOREIGN KEY ([author_id]) ' .
  717. 'REFERENCES [authors] ([id]) ON UPDATE SET NULL ON DELETE SET NULL'
  718. ],
  719. [
  720. 'author_id_idx',
  721. ['type' => 'foreign', 'columns' => ['author_id'], 'references' => ['authors', 'id'], 'update' => 'cascade'],
  722. 'CONSTRAINT [author_id_idx] FOREIGN KEY ([author_id]) ' .
  723. 'REFERENCES [authors] ([id]) ON UPDATE CASCADE ON DELETE SET NULL'
  724. ],
  725. [
  726. 'author_id_idx',
  727. ['type' => 'foreign', 'columns' => ['author_id'], 'references' => ['authors', 'id'], 'update' => 'setDefault'],
  728. 'CONSTRAINT [author_id_idx] FOREIGN KEY ([author_id]) ' .
  729. 'REFERENCES [authors] ([id]) ON UPDATE SET DEFAULT ON DELETE SET NULL'
  730. ],
  731. [
  732. 'author_id_idx',
  733. ['type' => 'foreign', 'columns' => ['author_id'], 'references' => ['authors', 'id'], 'update' => 'setNull'],
  734. 'CONSTRAINT [author_id_idx] FOREIGN KEY ([author_id]) ' .
  735. 'REFERENCES [authors] ([id]) ON UPDATE SET NULL ON DELETE SET NULL'
  736. ],
  737. [
  738. 'author_id_idx',
  739. ['type' => 'foreign', 'columns' => ['author_id'], 'references' => ['authors', 'id'], 'update' => 'noAction'],
  740. 'CONSTRAINT [author_id_idx] FOREIGN KEY ([author_id]) ' .
  741. 'REFERENCES [authors] ([id]) ON UPDATE NO ACTION ON DELETE SET NULL'
  742. ],
  743. ];
  744. }
  745. /**
  746. * Test the constraintSql method.
  747. *
  748. * @dataProvider constraintSqlProvider
  749. */
  750. public function testConstraintSql($name, $data, $expected)
  751. {
  752. $driver = $this->_getMockedDriver();
  753. $schema = new SqlserverSchema($driver);
  754. $table = (new TableSchema('schema_articles'))->addColumn('title', [
  755. 'type' => 'string',
  756. 'length' => 255
  757. ])->addColumn('author_id', [
  758. 'type' => 'integer',
  759. ])->addConstraint($name, $data);
  760. $this->assertEquals($expected, $schema->constraintSql($table, $name));
  761. }
  762. /**
  763. * Test the addConstraintSql method.
  764. *
  765. * @return void
  766. */
  767. public function testAddConstraintSql()
  768. {
  769. $driver = $this->_getMockedDriver();
  770. $connection = $this->getMockBuilder('Cake\Database\Connection')
  771. ->disableOriginalConstructor()
  772. ->getMock();
  773. $connection->expects($this->any())->method('getDriver')
  774. ->will($this->returnValue($driver));
  775. $table = (new TableSchema('posts'))
  776. ->addColumn('author_id', [
  777. 'type' => 'integer',
  778. 'null' => false
  779. ])
  780. ->addColumn('category_id', [
  781. 'type' => 'integer',
  782. 'null' => false
  783. ])
  784. ->addColumn('category_name', [
  785. 'type' => 'integer',
  786. 'null' => false
  787. ])
  788. ->addConstraint('author_fk', [
  789. 'type' => 'foreign',
  790. 'columns' => ['author_id'],
  791. 'references' => ['authors', 'id'],
  792. 'update' => 'cascade',
  793. 'delete' => 'cascade'
  794. ])
  795. ->addConstraint('category_fk', [
  796. 'type' => 'foreign',
  797. 'columns' => ['category_id', 'category_name'],
  798. 'references' => ['categories', ['id', 'name']],
  799. 'update' => 'cascade',
  800. 'delete' => 'cascade'
  801. ]);
  802. $expected = [
  803. 'ALTER TABLE [posts] ADD CONSTRAINT [author_fk] FOREIGN KEY ([author_id]) REFERENCES [authors] ([id]) ON UPDATE CASCADE ON DELETE CASCADE;',
  804. 'ALTER TABLE [posts] ADD CONSTRAINT [category_fk] FOREIGN KEY ([category_id], [category_name]) REFERENCES [categories] ([id], [name]) ON UPDATE CASCADE ON DELETE CASCADE;'
  805. ];
  806. $result = $table->addConstraintSql($connection);
  807. $this->assertCount(2, $result);
  808. $this->assertEquals($expected, $result);
  809. }
  810. /**
  811. * Test the dropConstraintSql method.
  812. *
  813. * @return void
  814. */
  815. public function testDropConstraintSql()
  816. {
  817. $driver = $this->_getMockedDriver();
  818. $connection = $this->getMockBuilder('Cake\Database\Connection')
  819. ->disableOriginalConstructor()
  820. ->getMock();
  821. $connection->expects($this->any())->method('getDriver')
  822. ->will($this->returnValue($driver));
  823. $table = (new TableSchema('posts'))
  824. ->addColumn('author_id', [
  825. 'type' => 'integer',
  826. 'null' => false
  827. ])
  828. ->addColumn('category_id', [
  829. 'type' => 'integer',
  830. 'null' => false
  831. ])
  832. ->addColumn('category_name', [
  833. 'type' => 'integer',
  834. 'null' => false
  835. ])
  836. ->addConstraint('author_fk', [
  837. 'type' => 'foreign',
  838. 'columns' => ['author_id'],
  839. 'references' => ['authors', 'id'],
  840. 'update' => 'cascade',
  841. 'delete' => 'cascade'
  842. ])
  843. ->addConstraint('category_fk', [
  844. 'type' => 'foreign',
  845. 'columns' => ['category_id', 'category_name'],
  846. 'references' => ['categories', ['id', 'name']],
  847. 'update' => 'cascade',
  848. 'delete' => 'cascade'
  849. ]);
  850. $expected = [
  851. 'ALTER TABLE [posts] DROP CONSTRAINT [author_fk];',
  852. 'ALTER TABLE [posts] DROP CONSTRAINT [category_fk];'
  853. ];
  854. $result = $table->dropConstraintSql($connection);
  855. $this->assertCount(2, $result);
  856. $this->assertEquals($expected, $result);
  857. }
  858. /**
  859. * Integration test for converting a Schema\Table into MySQL table creates.
  860. *
  861. * @return void
  862. */
  863. public function testCreateSql()
  864. {
  865. $driver = $this->_getMockedDriver();
  866. $connection = $this->getMockBuilder('Cake\Database\Connection')
  867. ->disableOriginalConstructor()
  868. ->getMock();
  869. $connection->expects($this->any())->method('getDriver')
  870. ->will($this->returnValue($driver));
  871. $table = (new TableSchema('schema_articles'))->addColumn('id', [
  872. 'type' => 'integer',
  873. 'null' => false
  874. ])
  875. ->addColumn('title', [
  876. 'type' => 'string',
  877. 'null' => false,
  878. ])
  879. ->addColumn('body', ['type' => 'text'])
  880. ->addColumn('data', ['type' => 'json'])
  881. ->addColumn('hash', [
  882. 'type' => 'string',
  883. 'fixed' => true,
  884. 'length' => 40,
  885. 'collate' => 'Latin1_General_BIN',
  886. 'null' => false,
  887. ])
  888. ->addColumn('created', 'datetime')
  889. ->addConstraint('primary', [
  890. 'type' => 'primary',
  891. 'columns' => ['id'],
  892. ])
  893. ->addIndex('title_idx', [
  894. 'type' => 'index',
  895. 'columns' => ['title'],
  896. ]);
  897. $expected = <<<SQL
  898. CREATE TABLE [schema_articles] (
  899. [id] INTEGER IDENTITY(1, 1),
  900. [title] NVARCHAR(255) NOT NULL,
  901. [body] NVARCHAR(MAX),
  902. [data] NVARCHAR(MAX),
  903. [hash] NCHAR(40) COLLATE Latin1_General_BIN NOT NULL,
  904. [created] DATETIME,
  905. PRIMARY KEY ([id])
  906. )
  907. SQL;
  908. $result = $table->createSql($connection);
  909. $this->assertCount(2, $result);
  910. $this->assertEquals(str_replace("\r\n", "\n", $expected), str_replace("\r\n", "\n", $result[0]));
  911. $this->assertEquals(
  912. 'CREATE INDEX [title_idx] ON [schema_articles] ([title])',
  913. $result[1]
  914. );
  915. }
  916. /**
  917. * test dropSql
  918. *
  919. * @return void
  920. */
  921. public function testDropSql()
  922. {
  923. $driver = $this->_getMockedDriver();
  924. $connection = $this->getMockBuilder('Cake\Database\Connection')
  925. ->disableOriginalConstructor()
  926. ->getMock();
  927. $connection->expects($this->any())->method('getDriver')
  928. ->will($this->returnValue($driver));
  929. $table = new TableSchema('schema_articles');
  930. $result = $table->dropSql($connection);
  931. $this->assertCount(1, $result);
  932. $this->assertEquals('DROP TABLE [schema_articles]', $result[0]);
  933. }
  934. /**
  935. * Test truncateSql()
  936. *
  937. * @return void
  938. */
  939. public function testTruncateSql()
  940. {
  941. $driver = $this->_getMockedDriver();
  942. $connection = $this->getMockBuilder('Cake\Database\Connection')
  943. ->disableOriginalConstructor()
  944. ->getMock();
  945. $connection->expects($this->any())->method('getDriver')
  946. ->will($this->returnValue($driver));
  947. $table = new TableSchema('schema_articles');
  948. $table->addColumn('id', 'integer')
  949. ->addConstraint('primary', [
  950. 'type' => 'primary',
  951. 'columns' => ['id']
  952. ]);
  953. $result = $table->truncateSql($connection);
  954. $this->assertCount(2, $result);
  955. $this->assertEquals('DELETE FROM [schema_articles]', $result[0]);
  956. $this->assertEquals("DBCC CHECKIDENT('schema_articles', RESEED, 0)", $result[1]);
  957. }
  958. /**
  959. * Get a schema instance with a mocked driver/pdo instances
  960. *
  961. * @return \Cake\Database\Driver
  962. */
  963. protected function _getMockedDriver()
  964. {
  965. $driver = new Sqlserver();
  966. $mock = $this->getMockBuilder(PDO::class)
  967. ->setMethods(['quote'])
  968. ->disableOriginalConstructor()
  969. ->getMock();
  970. $mock->expects($this->any())
  971. ->method('quote')
  972. ->will($this->returnCallback(function ($value) {
  973. return "'$value'";
  974. }));
  975. $driver->connection($mock);
  976. return $driver;
  977. }
  978. }