SqliteSchemaTest.php 32 KB

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