SqlserverSchemaTest.php 33 KB

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