SqliteSchemaTest.php 35 KB

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