SqlserverSchemaTest.php 33 KB

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