SqlserverSchemaTest.php 34 KB

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