SqlserverSchemaTest.php 39 KB

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