SqliteSchemaTest.php 31 KB

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