SqlserverSchemaTest.php 37 KB

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