SqliteSchemaTest.php 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094
  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\Sqlite;
  17. use Cake\Database\Schema\Collection as SchemaCollection;
  18. use Cake\Database\Schema\SqliteSchema;
  19. use Cake\Database\Schema\TableSchema;
  20. use Cake\Datasource\ConnectionManager;
  21. use Cake\TestSuite\TestCase;
  22. use PDO;
  23. /**
  24. * Test case for Sqlite Schema Dialect.
  25. */
  26. class SqliteSchemaTest 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'], 'Sqlite') === false, 'Not using Sqlite for test config');
  37. }
  38. /**
  39. * Data provider for convert column testing
  40. *
  41. * @return array
  42. */
  43. public static function convertColumnProvider()
  44. {
  45. return [
  46. [
  47. 'DATETIME',
  48. ['type' => 'datetime', 'length' => null]
  49. ],
  50. [
  51. 'DATE',
  52. ['type' => 'date', 'length' => null]
  53. ],
  54. [
  55. 'TIME',
  56. ['type' => 'time', 'length' => null]
  57. ],
  58. [
  59. 'BOOLEAN',
  60. ['type' => 'boolean', 'length' => null]
  61. ],
  62. [
  63. 'BIGINT',
  64. ['type' => 'biginteger', 'length' => null, 'unsigned' => false]
  65. ],
  66. [
  67. 'UNSIGNED BIGINT',
  68. ['type' => 'biginteger', 'length' => null, 'unsigned' => true]
  69. ],
  70. [
  71. 'VARCHAR(255)',
  72. ['type' => 'string', 'length' => 255]
  73. ],
  74. [
  75. 'CHAR(25)',
  76. ['type' => 'string', 'fixed' => true, 'length' => 25]
  77. ],
  78. [
  79. 'CHAR(36)',
  80. ['type' => 'uuid', 'length' => null]
  81. ],
  82. [
  83. 'BINARY(16)',
  84. ['type' => 'binaryuuid', 'length' => null]
  85. ],
  86. [
  87. 'BLOB',
  88. ['type' => 'binary', 'length' => null]
  89. ],
  90. [
  91. 'INTEGER(11)',
  92. ['type' => 'integer', 'length' => 11, 'unsigned' => false]
  93. ],
  94. [
  95. 'UNSIGNED INTEGER(11)',
  96. ['type' => 'integer', 'length' => 11, 'unsigned' => true]
  97. ],
  98. [
  99. 'TINYINT(3)',
  100. ['type' => 'tinyinteger', 'length' => 3, 'unsigned' => false]
  101. ],
  102. [
  103. 'UNSIGNED TINYINT(3)',
  104. ['type' => 'tinyinteger', 'length' => 3, 'unsigned' => true]
  105. ],
  106. [
  107. 'SMALLINT(5)',
  108. ['type' => 'smallinteger', 'length' => 5, 'unsigned' => false]
  109. ],
  110. [
  111. 'UNSIGNED SMALLINT(5)',
  112. ['type' => 'smallinteger', 'length' => 5, 'unsigned' => true]
  113. ],
  114. [
  115. 'MEDIUMINT(10)',
  116. ['type' => 'integer', 'length' => 10, 'unsigned' => false]
  117. ],
  118. [
  119. 'FLOAT',
  120. ['type' => 'float', 'length' => null, 'unsigned' => false]
  121. ],
  122. [
  123. 'DOUBLE',
  124. ['type' => 'float', 'length' => null, 'unsigned' => false]
  125. ],
  126. [
  127. 'UNSIGNED DOUBLE',
  128. ['type' => 'float', 'length' => null, 'unsigned' => true]
  129. ],
  130. [
  131. 'REAL',
  132. ['type' => 'float', 'length' => null, 'unsigned' => false]
  133. ],
  134. [
  135. 'DECIMAL(11,2)',
  136. ['type' => 'decimal', 'length' => null, 'unsigned' => false]
  137. ],
  138. [
  139. 'UNSIGNED DECIMAL(11,2)',
  140. ['type' => 'decimal', 'length' => null, 'unsigned' => true]
  141. ],
  142. ];
  143. }
  144. /**
  145. * Test parsing SQLite column types from field description.
  146. *
  147. * @dataProvider convertColumnProvider
  148. * @return void
  149. */
  150. public function testConvertColumn($type, $expected)
  151. {
  152. $field = [
  153. 'pk' => false,
  154. 'name' => 'field',
  155. 'type' => $type,
  156. 'notnull' => false,
  157. 'dflt_value' => 'Default value',
  158. ];
  159. $expected += [
  160. 'null' => true,
  161. 'default' => 'Default value',
  162. ];
  163. $driver = $this->getMockBuilder('Cake\Database\Driver\Sqlite')->getMock();
  164. $dialect = new SqliteSchema($driver);
  165. $table = $this->getMockBuilder(TableSchema::class)
  166. ->setConstructorArgs(['table'])
  167. ->getMock();
  168. $table->expects($this->at(1))->method('addColumn')->with('field', $expected);
  169. $dialect->convertColumnDescription($table, $field);
  170. }
  171. /**
  172. * Tests converting multiple rows into a primary constraint with multiple
  173. * columns
  174. *
  175. * @return void
  176. */
  177. public function testConvertCompositePrimaryKey()
  178. {
  179. $driver = $this->getMockBuilder('Cake\Database\Driver\Sqlite')->getMock();
  180. $dialect = new SqliteSchema($driver);
  181. $field1 = [
  182. 'pk' => true,
  183. 'name' => 'field1',
  184. 'type' => 'INTEGER(11)',
  185. 'notnull' => false,
  186. 'dflt_value' => 0,
  187. ];
  188. $field2 = [
  189. 'pk' => true,
  190. 'name' => 'field2',
  191. 'type' => 'INTEGER(11)',
  192. 'notnull' => false,
  193. 'dflt_value' => 1,
  194. ];
  195. $table = new TableSchema('table');
  196. $dialect->convertColumnDescription($table, $field1);
  197. $dialect->convertColumnDescription($table, $field2);
  198. $this->assertEquals(['field1', 'field2'], $table->primaryKey());
  199. }
  200. /**
  201. * Creates tables for testing listTables/describe()
  202. *
  203. * @param \Cake\Database\Connection $connection
  204. * @return void
  205. */
  206. protected function _createTables($connection)
  207. {
  208. $this->_needsConnection();
  209. $schema = new SchemaCollection($connection);
  210. $result = $schema->listTables();
  211. if (in_array('schema_articles', $result) &&
  212. in_array('schema_authors', $result)
  213. ) {
  214. return;
  215. }
  216. $table = <<<SQL
  217. CREATE TABLE schema_authors (
  218. id INTEGER PRIMARY KEY AUTOINCREMENT,
  219. name VARCHAR(50),
  220. bio TEXT,
  221. created DATETIME
  222. )
  223. SQL;
  224. $connection->execute($table);
  225. $table = <<<SQL
  226. CREATE TABLE schema_articles (
  227. id INTEGER PRIMARY KEY AUTOINCREMENT,
  228. title VARCHAR(20) DEFAULT 'Let ''em eat cake',
  229. body TEXT,
  230. author_id INT(11) NOT NULL,
  231. published BOOLEAN DEFAULT 0,
  232. created DATETIME,
  233. field1 VARCHAR(10) DEFAULT NULL,
  234. field2 VARCHAR(10) DEFAULT 'NULL',
  235. CONSTRAINT "title_idx" UNIQUE ("title", "body")
  236. CONSTRAINT "author_idx" FOREIGN KEY ("author_id") REFERENCES "schema_authors" ("id") ON UPDATE CASCADE ON DELETE RESTRICT
  237. );
  238. SQL;
  239. $connection->execute($table);
  240. $connection->execute('CREATE INDEX "created_idx" ON "schema_articles" ("created")');
  241. $sql = <<<SQL
  242. CREATE TABLE schema_composite (
  243. "id" INTEGER NOT NULL,
  244. "site_id" INTEGER NOT NULL,
  245. "name" VARCHAR(255),
  246. PRIMARY KEY("id", "site_id")
  247. );
  248. SQL;
  249. $connection->execute($sql);
  250. }
  251. /**
  252. * Test SchemaCollection listing tables with Sqlite
  253. *
  254. * @return void
  255. */
  256. public function testListTables()
  257. {
  258. $connection = ConnectionManager::get('test');
  259. $this->_createTables($connection);
  260. $schema = new SchemaCollection($connection);
  261. $result = $schema->listTables();
  262. $this->assertInternalType('array', $result);
  263. $this->assertContains('schema_articles', $result);
  264. $this->assertContains('schema_authors', $result);
  265. }
  266. /**
  267. * Test describing a table with Sqlite
  268. *
  269. * @return void
  270. */
  271. public function testDescribeTable()
  272. {
  273. $connection = ConnectionManager::get('test');
  274. $this->_createTables($connection);
  275. $schema = new SchemaCollection($connection);
  276. $result = $schema->describe('schema_articles');
  277. $expected = [
  278. 'id' => [
  279. 'type' => 'integer',
  280. 'null' => false,
  281. 'default' => null,
  282. 'length' => null,
  283. 'precision' => null,
  284. 'comment' => null,
  285. 'unsigned' => false,
  286. 'autoIncrement' => true,
  287. ],
  288. 'title' => [
  289. 'type' => 'string',
  290. 'null' => true,
  291. 'default' => 'Let \'em eat cake',
  292. 'length' => 20,
  293. 'precision' => null,
  294. 'fixed' => null,
  295. 'comment' => null,
  296. 'collate' => null,
  297. ],
  298. 'body' => [
  299. 'type' => 'text',
  300. 'null' => true,
  301. 'default' => null,
  302. 'length' => null,
  303. 'precision' => null,
  304. 'comment' => null,
  305. 'collate' => null,
  306. ],
  307. 'author_id' => [
  308. 'type' => 'integer',
  309. 'null' => false,
  310. 'default' => null,
  311. 'length' => 11,
  312. 'unsigned' => false,
  313. 'precision' => null,
  314. 'comment' => null,
  315. 'autoIncrement' => null,
  316. ],
  317. 'published' => [
  318. 'type' => 'boolean',
  319. 'null' => true,
  320. 'default' => 0,
  321. 'length' => null,
  322. 'precision' => null,
  323. 'comment' => null,
  324. ],
  325. 'created' => [
  326. 'type' => 'datetime',
  327. 'null' => true,
  328. 'default' => null,
  329. 'length' => null,
  330. 'precision' => null,
  331. 'comment' => null,
  332. ],
  333. 'field1' => [
  334. 'type' => 'string',
  335. 'null' => true,
  336. 'default' => null,
  337. 'length' => 10,
  338. 'precision' => null,
  339. 'fixed' => null,
  340. 'comment' => null,
  341. 'collate' => null,
  342. ],
  343. 'field2' => [
  344. 'type' => 'string',
  345. 'null' => true,
  346. 'default' => 'NULL',
  347. 'length' => 10,
  348. 'precision' => null,
  349. 'fixed' => null,
  350. 'comment' => null,
  351. 'collate' => null,
  352. ],
  353. ];
  354. $this->assertInstanceOf('Cake\Database\Schema\Table', $result);
  355. $this->assertEquals(['id'], $result->primaryKey());
  356. foreach ($expected as $field => $definition) {
  357. $this->assertEquals($definition, $result->getColumn($field));
  358. }
  359. }
  360. /**
  361. * Test describing a table with Sqlite and composite keys
  362. *
  363. * Composite keys in SQLite are never autoincrement, and shouldn't be marked
  364. * as such.
  365. *
  366. * @return void
  367. */
  368. public function testDescribeTableCompositeKey()
  369. {
  370. $connection = ConnectionManager::get('test');
  371. $this->_createTables($connection);
  372. $schema = new SchemaCollection($connection);
  373. $result = $schema->describe('schema_composite');
  374. $this->assertEquals(['id', 'site_id'], $result->primaryKey());
  375. $this->assertNull($result->getColumn('site_id')['autoIncrement'], 'site_id should not be autoincrement');
  376. $this->assertNull($result->getColumn('id')['autoIncrement'], 'id should not be autoincrement');
  377. }
  378. /**
  379. * Test describing a table with indexes
  380. *
  381. * @return void
  382. */
  383. public function testDescribeTableIndexes()
  384. {
  385. $connection = ConnectionManager::get('test');
  386. $this->_createTables($connection);
  387. $schema = new SchemaCollection($connection);
  388. $result = $schema->describe('schema_articles');
  389. $this->assertInstanceOf('Cake\Database\Schema\Table', $result);
  390. $expected = [
  391. 'primary' => [
  392. 'type' => 'primary',
  393. 'columns' => ['id'],
  394. 'length' => []
  395. ],
  396. 'sqlite_autoindex_schema_articles_1' => [
  397. 'type' => 'unique',
  398. 'columns' => ['title', 'body'],
  399. 'length' => []
  400. ],
  401. 'author_id_fk' => [
  402. 'type' => 'foreign',
  403. 'columns' => ['author_id'],
  404. 'references' => ['schema_authors', 'id'],
  405. 'length' => [],
  406. 'update' => 'cascade',
  407. 'delete' => 'restrict',
  408. ]
  409. ];
  410. $this->assertCount(3, $result->constraints());
  411. $this->assertEquals($expected['primary'], $result->getConstraint('primary'));
  412. $this->assertEquals(
  413. $expected['sqlite_autoindex_schema_articles_1'],
  414. $result->getConstraint('sqlite_autoindex_schema_articles_1')
  415. );
  416. $this->assertEquals(
  417. $expected['author_id_fk'],
  418. $result->getConstraint('author_id_fk')
  419. );
  420. $this->assertCount(1, $result->indexes());
  421. $expected = [
  422. 'type' => 'index',
  423. 'columns' => ['created'],
  424. 'length' => []
  425. ];
  426. $this->assertEquals($expected, $result->getIndex('created_idx'));
  427. }
  428. /**
  429. * Column provider for creating column sql
  430. *
  431. * @return array
  432. */
  433. public static function columnSqlProvider()
  434. {
  435. return [
  436. // strings
  437. [
  438. 'title',
  439. ['type' => 'string', 'length' => 25, 'null' => false],
  440. '"title" VARCHAR(25) NOT NULL'
  441. ],
  442. [
  443. 'title',
  444. ['type' => 'string', 'length' => 25, 'null' => true, 'default' => 'ignored'],
  445. '"title" VARCHAR(25) DEFAULT "ignored"',
  446. ],
  447. [
  448. 'id',
  449. ['type' => 'string', 'length' => 32, 'fixed' => true, 'null' => false],
  450. '"id" VARCHAR(32) NOT NULL'
  451. ],
  452. [
  453. 'role',
  454. ['type' => 'string', 'length' => 10, 'null' => false, 'default' => 'admin'],
  455. '"role" VARCHAR(10) NOT NULL DEFAULT "admin"'
  456. ],
  457. [
  458. 'title',
  459. ['type' => 'string'],
  460. '"title" VARCHAR'
  461. ],
  462. [
  463. 'id',
  464. ['type' => 'uuid'],
  465. '"id" CHAR(36)'
  466. ],
  467. [
  468. 'id',
  469. ['type' => 'binaryuuid'],
  470. '"id" BINARY(16)'
  471. ],
  472. // Text
  473. [
  474. 'body',
  475. ['type' => 'text', 'null' => false],
  476. '"body" TEXT NOT NULL'
  477. ],
  478. [
  479. 'body',
  480. ['type' => 'text', 'length' => TableSchema::LENGTH_TINY, 'null' => false],
  481. '"body" VARCHAR(' . TableSchema::LENGTH_TINY . ') NOT NULL'
  482. ],
  483. [
  484. 'body',
  485. ['type' => 'text', 'length' => TableSchema::LENGTH_MEDIUM, 'null' => false],
  486. '"body" TEXT NOT NULL'
  487. ],
  488. [
  489. 'body',
  490. ['type' => 'text', 'length' => TableSchema::LENGTH_LONG, 'null' => false],
  491. '"body" TEXT NOT NULL'
  492. ],
  493. // Integers
  494. [
  495. 'post_id',
  496. ['type' => 'smallinteger', 'length' => 5, 'unsigned' => false],
  497. '"post_id" SMALLINT(5)'
  498. ],
  499. [
  500. 'post_id',
  501. ['type' => 'smallinteger', 'length' => 5, 'unsigned' => true],
  502. '"post_id" UNSIGNED SMALLINT(5)'
  503. ],
  504. [
  505. 'post_id',
  506. ['type' => 'tinyinteger', 'length' => 3, 'unsigned' => false],
  507. '"post_id" TINYINT(3)'
  508. ],
  509. [
  510. 'post_id',
  511. ['type' => 'tinyinteger', 'length' => 3, 'unsigned' => true],
  512. '"post_id" UNSIGNED TINYINT(3)'
  513. ],
  514. [
  515. 'post_id',
  516. ['type' => 'integer', 'length' => 11, 'unsigned' => false],
  517. '"post_id" INTEGER(11)'
  518. ],
  519. [
  520. 'post_id',
  521. ['type' => 'biginteger', 'length' => 20, 'unsigned' => false],
  522. '"post_id" BIGINT'
  523. ],
  524. [
  525. 'post_id',
  526. ['type' => 'biginteger', 'length' => 20, 'unsigned' => true],
  527. '"post_id" UNSIGNED BIGINT'
  528. ],
  529. // Decimal
  530. [
  531. 'value',
  532. ['type' => 'decimal', 'unsigned' => false],
  533. '"value" DECIMAL'
  534. ],
  535. [
  536. 'value',
  537. ['type' => 'decimal', 'length' => 11, 'unsigned' => false],
  538. '"value" DECIMAL(11,0)'
  539. ],
  540. [
  541. 'value',
  542. ['type' => 'decimal', 'length' => 11, 'unsigned' => true],
  543. '"value" UNSIGNED DECIMAL(11,0)'
  544. ],
  545. [
  546. 'value',
  547. ['type' => 'decimal', 'length' => 12, 'precision' => 5, 'unsigned' => false],
  548. '"value" DECIMAL(12,5)'
  549. ],
  550. // Float
  551. [
  552. 'value',
  553. ['type' => 'float'],
  554. '"value" FLOAT'
  555. ],
  556. [
  557. 'value',
  558. ['type' => 'float', 'length' => 11, 'precision' => 3, 'unsigned' => false],
  559. '"value" FLOAT(11,3)'
  560. ],
  561. [
  562. 'value',
  563. ['type' => 'float', 'length' => 11, 'precision' => 3, 'unsigned' => true],
  564. '"value" UNSIGNED FLOAT(11,3)'
  565. ],
  566. // Boolean
  567. [
  568. 'checked',
  569. ['type' => 'boolean', 'null' => true, 'default' => false],
  570. '"checked" BOOLEAN DEFAULT FALSE'
  571. ],
  572. [
  573. 'checked',
  574. ['type' => 'boolean', 'default' => true, 'null' => false],
  575. '"checked" BOOLEAN NOT NULL DEFAULT TRUE'
  576. ],
  577. // datetimes
  578. [
  579. 'created',
  580. ['type' => 'datetime'],
  581. '"created" DATETIME'
  582. ],
  583. [
  584. 'open_date',
  585. ['type' => 'datetime', 'null' => false, 'default' => '2016-12-07 23:04:00'],
  586. '"open_date" DATETIME NOT NULL DEFAULT "2016-12-07 23:04:00"'
  587. ],
  588. // Date & Time
  589. [
  590. 'start_date',
  591. ['type' => 'date'],
  592. '"start_date" DATE'
  593. ],
  594. [
  595. 'start_time',
  596. ['type' => 'time'],
  597. '"start_time" TIME'
  598. ],
  599. // timestamps
  600. [
  601. 'created',
  602. ['type' => 'timestamp', 'null' => true],
  603. '"created" TIMESTAMP DEFAULT NULL'
  604. ],
  605. ];
  606. }
  607. /**
  608. * Test the addConstraintSql method.
  609. *
  610. * @return void
  611. */
  612. public function testAddConstraintSql()
  613. {
  614. $driver = $this->_getMockedDriver();
  615. $connection = $this->getMockBuilder('Cake\Database\Connection')
  616. ->disableOriginalConstructor()
  617. ->getMock();
  618. $connection->expects($this->any())->method('getDriver')
  619. ->will($this->returnValue($driver));
  620. $table = new TableSchema('posts');
  621. $result = $table->addConstraintSql($connection);
  622. $this->assertEmpty($result);
  623. }
  624. /**
  625. * Test the dropConstraintSql method.
  626. *
  627. * @return void
  628. */
  629. public function testDropConstraintSql()
  630. {
  631. $driver = $this->_getMockedDriver();
  632. $connection = $this->getMockBuilder('Cake\Database\Connection')
  633. ->disableOriginalConstructor()
  634. ->getMock();
  635. $connection->expects($this->any())->method('getDriver')
  636. ->will($this->returnValue($driver));
  637. $table = new TableSchema('posts');
  638. $result = $table->dropConstraintSql($connection);
  639. $this->assertEmpty($result);
  640. }
  641. /**
  642. * Test generating column definitions
  643. *
  644. * @dataProvider columnSqlProvider
  645. * @return void
  646. */
  647. public function testColumnSql($name, $data, $expected)
  648. {
  649. $driver = $this->_getMockedDriver();
  650. $schema = new SqliteSchema($driver);
  651. $table = (new TableSchema('articles'))->addColumn($name, $data);
  652. $this->assertEquals($expected, $schema->columnSql($table, $name));
  653. }
  654. /**
  655. * Test generating a column that is a primary key.
  656. *
  657. * @return void
  658. */
  659. public function testColumnSqlPrimaryKey()
  660. {
  661. $driver = $this->_getMockedDriver();
  662. $schema = new SqliteSchema($driver);
  663. $table = new TableSchema('articles');
  664. $table->addColumn('id', [
  665. 'type' => 'integer',
  666. 'null' => false,
  667. 'length' => 11,
  668. 'unsigned' => true
  669. ])
  670. ->addConstraint('primary', [
  671. 'type' => 'primary',
  672. 'columns' => ['id']
  673. ]);
  674. $result = $schema->columnSql($table, 'id');
  675. $this->assertEquals($result, '"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT');
  676. $result = $schema->constraintSql($table, 'primary');
  677. $this->assertEquals('', $result, 'Integer primary keys are special in sqlite.');
  678. }
  679. /**
  680. * Test generating a bigint column that is a primary key.
  681. *
  682. * @return void
  683. */
  684. public function testColumnSqlPrimaryKeyBigInt()
  685. {
  686. $driver = $this->_getMockedDriver();
  687. $schema = new SqliteSchema($driver);
  688. $table = new TableSchema('articles');
  689. $table->addColumn('id', [
  690. 'type' => 'biginteger',
  691. 'null' => false
  692. ])
  693. ->addConstraint('primary', [
  694. 'type' => 'primary',
  695. 'columns' => ['id']
  696. ]);
  697. $result = $schema->columnSql($table, 'id');
  698. $this->assertEquals($result, '"id" BIGINT NOT NULL');
  699. $result = $schema->constraintSql($table, 'primary');
  700. $this->assertEquals('CONSTRAINT "primary" PRIMARY KEY ("id")', $result, 'Bigint primary keys are not special.');
  701. }
  702. /**
  703. * Provide data for testing constraintSql
  704. *
  705. * @return array
  706. */
  707. public static function constraintSqlProvider()
  708. {
  709. return [
  710. [
  711. 'primary',
  712. ['type' => 'primary', 'columns' => ['title']],
  713. 'CONSTRAINT "primary" PRIMARY KEY ("title")'
  714. ],
  715. [
  716. 'unique_idx',
  717. ['type' => 'unique', 'columns' => ['title', 'author_id']],
  718. 'CONSTRAINT "unique_idx" UNIQUE ("title", "author_id")'
  719. ],
  720. [
  721. 'author_id_idx',
  722. ['type' => 'foreign', 'columns' => ['author_id'], 'references' => ['authors', 'id']],
  723. 'CONSTRAINT "author_id_idx" FOREIGN KEY ("author_id") ' .
  724. 'REFERENCES "authors" ("id") ON UPDATE RESTRICT ON DELETE RESTRICT'
  725. ],
  726. [
  727. 'author_id_idx',
  728. ['type' => 'foreign', 'columns' => ['author_id'], 'references' => ['authors', 'id'], 'update' => 'cascade'],
  729. 'CONSTRAINT "author_id_idx" FOREIGN KEY ("author_id") ' .
  730. 'REFERENCES "authors" ("id") ON UPDATE CASCADE ON DELETE RESTRICT'
  731. ],
  732. [
  733. 'author_id_idx',
  734. ['type' => 'foreign', 'columns' => ['author_id'], 'references' => ['authors', 'id'], 'update' => 'restrict'],
  735. 'CONSTRAINT "author_id_idx" FOREIGN KEY ("author_id") ' .
  736. 'REFERENCES "authors" ("id") ON UPDATE RESTRICT ON DELETE RESTRICT'
  737. ],
  738. [
  739. 'author_id_idx',
  740. ['type' => 'foreign', 'columns' => ['author_id'], 'references' => ['authors', 'id'], 'update' => 'setNull'],
  741. 'CONSTRAINT "author_id_idx" FOREIGN KEY ("author_id") ' .
  742. 'REFERENCES "authors" ("id") ON UPDATE SET NULL ON DELETE RESTRICT'
  743. ],
  744. [
  745. 'author_id_idx',
  746. ['type' => 'foreign', 'columns' => ['author_id'], 'references' => ['authors', 'id'], 'update' => 'noAction'],
  747. 'CONSTRAINT "author_id_idx" FOREIGN KEY ("author_id") ' .
  748. 'REFERENCES "authors" ("id") ON UPDATE NO ACTION ON DELETE RESTRICT'
  749. ],
  750. ];
  751. }
  752. /**
  753. * Test the constraintSql method.
  754. *
  755. * @dataProvider constraintSqlProvider
  756. */
  757. public function testConstraintSql($name, $data, $expected)
  758. {
  759. $driver = $this->_getMockedDriver();
  760. $schema = new SqliteSchema($driver);
  761. $table = (new TableSchema('articles'))->addColumn('title', [
  762. 'type' => 'string',
  763. 'length' => 255
  764. ])->addColumn('author_id', [
  765. 'type' => 'integer',
  766. ])->addConstraint($name, $data);
  767. $this->assertEquals($expected, $schema->constraintSql($table, $name));
  768. }
  769. /**
  770. * Provide data for testing indexSql
  771. *
  772. * @return array
  773. */
  774. public static function indexSqlProvider()
  775. {
  776. return [
  777. [
  778. 'author_idx',
  779. ['type' => 'index', 'columns' => ['title', 'author_id']],
  780. 'CREATE INDEX "author_idx" ON "articles" ("title", "author_id")'
  781. ],
  782. ];
  783. }
  784. /**
  785. * Test the indexSql method.
  786. *
  787. * @dataProvider indexSqlProvider
  788. */
  789. public function testIndexSql($name, $data, $expected)
  790. {
  791. $driver = $this->_getMockedDriver();
  792. $schema = new SqliteSchema($driver);
  793. $table = (new TableSchema('articles'))->addColumn('title', [
  794. 'type' => 'string',
  795. 'length' => 255
  796. ])->addColumn('author_id', [
  797. 'type' => 'integer',
  798. ])->addIndex($name, $data);
  799. $this->assertEquals($expected, $schema->indexSql($table, $name));
  800. }
  801. /**
  802. * Integration test for converting a Schema\Table into MySQL table creates.
  803. *
  804. * @return void
  805. */
  806. public function testCreateSql()
  807. {
  808. $driver = $this->_getMockedDriver();
  809. $connection = $this->getMockBuilder('Cake\Database\Connection')
  810. ->disableOriginalConstructor()
  811. ->getMock();
  812. $connection->expects($this->any())->method('getDriver')
  813. ->will($this->returnValue($driver));
  814. $table = (new TableSchema('articles'))->addColumn('id', [
  815. 'type' => 'integer',
  816. 'null' => false
  817. ])
  818. ->addColumn('title', [
  819. 'type' => 'string',
  820. 'null' => false,
  821. ])
  822. ->addColumn('body', ['type' => 'text'])
  823. ->addColumn('data', ['type' => 'json'])
  824. ->addColumn('created', 'datetime')
  825. ->addConstraint('primary', [
  826. 'type' => 'primary',
  827. 'columns' => ['id']
  828. ])
  829. ->addIndex('title_idx', [
  830. 'type' => 'index',
  831. 'columns' => ['title']
  832. ]);
  833. $expected = <<<SQL
  834. CREATE TABLE "articles" (
  835. "id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
  836. "title" VARCHAR NOT NULL,
  837. "body" TEXT,
  838. "data" TEXT,
  839. "created" DATETIME
  840. )
  841. SQL;
  842. $result = $table->createSql($connection);
  843. $this->assertCount(2, $result);
  844. $this->assertTextEquals($expected, $result[0]);
  845. $this->assertEquals(
  846. 'CREATE INDEX "title_idx" ON "articles" ("title")',
  847. $result[1]
  848. );
  849. }
  850. /**
  851. * Tests creating temporary tables
  852. *
  853. * @return void
  854. */
  855. public function testCreateTemporary()
  856. {
  857. $driver = $this->_getMockedDriver();
  858. $connection = $this->getMockBuilder('Cake\Database\Connection')
  859. ->disableOriginalConstructor()
  860. ->getMock();
  861. $connection->expects($this->any())->method('getDriver')
  862. ->will($this->returnValue($driver));
  863. $table = (new TableSchema('schema_articles'))->addColumn('id', [
  864. 'type' => 'integer',
  865. 'null' => false
  866. ]);
  867. $table->setTemporary(true);
  868. $sql = $table->createSql($connection);
  869. $this->assertContains('CREATE TEMPORARY TABLE', $sql[0]);
  870. }
  871. /**
  872. * Test primary key generation & auto-increment.
  873. *
  874. * @return void
  875. */
  876. public function testCreateSqlCompositeIntegerKey()
  877. {
  878. $driver = $this->_getMockedDriver();
  879. $connection = $this->getMockBuilder('Cake\Database\Connection')
  880. ->disableOriginalConstructor()
  881. ->getMock();
  882. $connection->expects($this->any())->method('getDriver')
  883. ->will($this->returnValue($driver));
  884. $table = (new TableSchema('articles_tags'))
  885. ->addColumn('article_id', [
  886. 'type' => 'integer',
  887. 'null' => false
  888. ])
  889. ->addColumn('tag_id', [
  890. 'type' => 'integer',
  891. 'null' => false,
  892. ])
  893. ->addConstraint('primary', [
  894. 'type' => 'primary',
  895. 'columns' => ['article_id', 'tag_id']
  896. ]);
  897. $expected = <<<SQL
  898. CREATE TABLE "articles_tags" (
  899. "article_id" INTEGER NOT NULL,
  900. "tag_id" INTEGER NOT NULL,
  901. CONSTRAINT "primary" PRIMARY KEY ("article_id", "tag_id")
  902. )
  903. SQL;
  904. $result = $table->createSql($connection);
  905. $this->assertCount(1, $result);
  906. $this->assertTextEquals($expected, $result[0]);
  907. // Sqlite only supports AUTO_INCREMENT on single column primary
  908. // keys. Ensure that schema data follows the limitations of Sqlite.
  909. $table = (new TableSchema('composite_key'))
  910. ->addColumn('id', [
  911. 'type' => 'integer',
  912. 'null' => false,
  913. 'autoIncrement' => true
  914. ])
  915. ->addColumn('account_id', [
  916. 'type' => 'integer',
  917. 'null' => false,
  918. ])
  919. ->addConstraint('primary', [
  920. 'type' => 'primary',
  921. 'columns' => ['id', 'account_id']
  922. ]);
  923. $expected = <<<SQL
  924. CREATE TABLE "composite_key" (
  925. "id" INTEGER NOT NULL,
  926. "account_id" INTEGER NOT NULL,
  927. CONSTRAINT "primary" PRIMARY KEY ("id", "account_id")
  928. )
  929. SQL;
  930. $result = $table->createSql($connection);
  931. $this->assertCount(1, $result);
  932. $this->assertTextEquals($expected, $result[0]);
  933. }
  934. /**
  935. * test dropSql
  936. *
  937. * @return void
  938. */
  939. public function testDropSql()
  940. {
  941. $driver = $this->_getMockedDriver();
  942. $connection = $this->getMockBuilder('Cake\Database\Connection')
  943. ->disableOriginalConstructor()
  944. ->getMock();
  945. $connection->expects($this->any())->method('getDriver')
  946. ->will($this->returnValue($driver));
  947. $table = new TableSchema('articles');
  948. $result = $table->dropSql($connection);
  949. $this->assertCount(1, $result);
  950. $this->assertEquals('DROP TABLE "articles"', $result[0]);
  951. }
  952. /**
  953. * Test truncateSql()
  954. *
  955. * @return void
  956. */
  957. public function testTruncateSql()
  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. $statement = $this->getMockBuilder('\PDOStatement')
  966. ->setMethods(['execute', 'rowCount', 'closeCursor', 'fetch'])
  967. ->getMock();
  968. $driver->connection()->expects($this->once())->method('prepare')
  969. ->with('SELECT 1 FROM sqlite_master WHERE name = "sqlite_sequence"')
  970. ->will($this->returnValue($statement));
  971. $statement->expects($this->at(0))->method('fetch')
  972. ->will($this->returnValue(['1']));
  973. $statement->expects($this->at(2))->method('fetch')
  974. ->will($this->returnValue(false));
  975. $table = new TableSchema('articles');
  976. $result = $table->truncateSql($connection);
  977. $this->assertCount(2, $result);
  978. $this->assertEquals('DELETE FROM sqlite_sequence WHERE name="articles"', $result[0]);
  979. $this->assertEquals('DELETE FROM "articles"', $result[1]);
  980. }
  981. /**
  982. * Test truncateSql() with no sequences
  983. *
  984. * @return void
  985. */
  986. public function testTruncateSqlNoSequences()
  987. {
  988. $driver = $this->_getMockedDriver();
  989. $connection = $this->getMockBuilder('Cake\Database\Connection')
  990. ->disableOriginalConstructor()
  991. ->getMock();
  992. $connection->expects($this->any())->method('getDriver')
  993. ->will($this->returnValue($driver));
  994. $statement = $this->getMockBuilder('\PDOStatement')
  995. ->setMethods(['execute', 'rowCount', 'closeCursor', 'fetch'])
  996. ->getMock();
  997. $driver->connection()->expects($this->once())->method('prepare')
  998. ->with('SELECT 1 FROM sqlite_master WHERE name = "sqlite_sequence"')
  999. ->will($this->returnValue($statement));
  1000. $statement->expects($this->once())->method('fetch')
  1001. ->will($this->returnValue(false));
  1002. $table = new TableSchema('articles');
  1003. $result = $table->truncateSql($connection);
  1004. $this->assertCount(1, $result);
  1005. $this->assertEquals('DELETE FROM "articles"', $result[0]);
  1006. }
  1007. /**
  1008. * Get a schema instance with a mocked driver/pdo instances
  1009. *
  1010. * @return \Cake\Database\Driver
  1011. */
  1012. protected function _getMockedDriver()
  1013. {
  1014. $driver = new Sqlite();
  1015. $mock = $this->getMockBuilder(PDO::class)
  1016. ->setMethods(['quote', 'prepare'])
  1017. ->disableOriginalConstructor()
  1018. ->getMock();
  1019. $mock->expects($this->any())
  1020. ->method('quote')
  1021. ->will($this->returnCallback(function ($value) {
  1022. return '"' . $value . '"';
  1023. }));
  1024. $driver->connection($mock);
  1025. return $driver;
  1026. }
  1027. }