SqliteSchemaTest.php 35 KB

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