SqliteSchemaTest.php 34 KB

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