SqlserverSchemaTest.php 32 KB

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