SqlserverSchemaTest.php 37 KB

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