SqliteSchemaTest.php 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954
  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 generating column definitions
  521. *
  522. * @dataProvider columnSqlProvider
  523. * @return void
  524. */
  525. public function testColumnSql($name, $data, $expected)
  526. {
  527. $driver = $this->_getMockedDriver();
  528. $schema = new SqliteSchema($driver);
  529. $table = (new Table('articles'))->addColumn($name, $data);
  530. $this->assertEquals($expected, $schema->columnSql($table, $name));
  531. }
  532. /**
  533. * Test generating a column that is a primary key.
  534. *
  535. * @return void
  536. */
  537. public function testColumnSqlPrimaryKey()
  538. {
  539. $driver = $this->_getMockedDriver();
  540. $schema = new SqliteSchema($driver);
  541. $table = new Table('articles');
  542. $table->addColumn('id', [
  543. 'type' => 'integer',
  544. 'null' => false
  545. ])
  546. ->addConstraint('primary', [
  547. 'type' => 'primary',
  548. 'columns' => ['id']
  549. ]);
  550. $result = $schema->columnSql($table, 'id');
  551. $this->assertEquals($result, '"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT');
  552. $result = $schema->constraintSql($table, 'primary');
  553. $this->assertEquals('', $result, 'Integer primary keys are special in sqlite.');
  554. }
  555. /**
  556. * Test generating a bigint column that is a primary key.
  557. *
  558. * @return void
  559. */
  560. public function testColumnSqlPrimaryKeyBigInt()
  561. {
  562. $driver = $this->_getMockedDriver();
  563. $schema = new SqliteSchema($driver);
  564. $table = new Table('articles');
  565. $table->addColumn('id', [
  566. 'type' => 'biginteger',
  567. 'null' => false
  568. ])
  569. ->addConstraint('primary', [
  570. 'type' => 'primary',
  571. 'columns' => ['id']
  572. ]);
  573. $result = $schema->columnSql($table, 'id');
  574. $this->assertEquals($result, '"id" BIGINT NOT NULL');
  575. $result = $schema->constraintSql($table, 'primary');
  576. $this->assertEquals('CONSTRAINT "primary" PRIMARY KEY ("id")', $result, 'Bigint primary keys are not special.');
  577. }
  578. /**
  579. * Provide data for testing constraintSql
  580. *
  581. * @return array
  582. */
  583. public static function constraintSqlProvider()
  584. {
  585. return [
  586. [
  587. 'primary',
  588. ['type' => 'primary', 'columns' => ['title']],
  589. 'CONSTRAINT "primary" PRIMARY KEY ("title")'
  590. ],
  591. [
  592. 'unique_idx',
  593. ['type' => 'unique', 'columns' => ['title', 'author_id']],
  594. 'CONSTRAINT "unique_idx" UNIQUE ("title", "author_id")'
  595. ],
  596. [
  597. 'author_id_idx',
  598. ['type' => 'foreign', 'columns' => ['author_id'], 'references' => ['authors', 'id']],
  599. 'CONSTRAINT "author_id_idx" FOREIGN KEY ("author_id") ' .
  600. 'REFERENCES "authors" ("id") ON UPDATE RESTRICT ON DELETE RESTRICT'
  601. ],
  602. [
  603. 'author_id_idx',
  604. ['type' => 'foreign', 'columns' => ['author_id'], 'references' => ['authors', 'id'], 'update' => 'cascade'],
  605. 'CONSTRAINT "author_id_idx" FOREIGN KEY ("author_id") ' .
  606. 'REFERENCES "authors" ("id") ON UPDATE CASCADE ON DELETE RESTRICT'
  607. ],
  608. [
  609. 'author_id_idx',
  610. ['type' => 'foreign', 'columns' => ['author_id'], 'references' => ['authors', 'id'], 'update' => 'restrict'],
  611. 'CONSTRAINT "author_id_idx" FOREIGN KEY ("author_id") ' .
  612. 'REFERENCES "authors" ("id") ON UPDATE RESTRICT ON DELETE RESTRICT'
  613. ],
  614. [
  615. 'author_id_idx',
  616. ['type' => 'foreign', 'columns' => ['author_id'], 'references' => ['authors', 'id'], 'update' => 'setNull'],
  617. 'CONSTRAINT "author_id_idx" FOREIGN KEY ("author_id") ' .
  618. 'REFERENCES "authors" ("id") ON UPDATE SET NULL ON DELETE RESTRICT'
  619. ],
  620. [
  621. 'author_id_idx',
  622. ['type' => 'foreign', 'columns' => ['author_id'], 'references' => ['authors', 'id'], 'update' => 'noAction'],
  623. 'CONSTRAINT "author_id_idx" FOREIGN KEY ("author_id") ' .
  624. 'REFERENCES "authors" ("id") ON UPDATE NO ACTION ON DELETE RESTRICT'
  625. ],
  626. ];
  627. }
  628. /**
  629. * Test the constraintSql method.
  630. *
  631. * @dataProvider constraintSqlProvider
  632. */
  633. public function testConstraintSql($name, $data, $expected)
  634. {
  635. $driver = $this->_getMockedDriver();
  636. $schema = new SqliteSchema($driver);
  637. $table = (new Table('articles'))->addColumn('title', [
  638. 'type' => 'string',
  639. 'length' => 255
  640. ])->addColumn('author_id', [
  641. 'type' => 'integer',
  642. ])->addConstraint($name, $data);
  643. $this->assertEquals($expected, $schema->constraintSql($table, $name));
  644. }
  645. /**
  646. * Provide data for testing indexSql
  647. *
  648. * @return array
  649. */
  650. public static function indexSqlProvider()
  651. {
  652. return [
  653. [
  654. 'author_idx',
  655. ['type' => 'index', 'columns' => ['title', 'author_id']],
  656. 'CREATE INDEX "author_idx" ON "articles" ("title", "author_id")'
  657. ],
  658. ];
  659. }
  660. /**
  661. * Test the indexSql method.
  662. *
  663. * @dataProvider indexSqlProvider
  664. */
  665. public function testIndexSql($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. ])->addIndex($name, $data);
  675. $this->assertEquals($expected, $schema->indexSql($table, $name));
  676. }
  677. /**
  678. * Integration test for converting a Schema\Table into MySQL table creates.
  679. *
  680. * @return void
  681. */
  682. public function testCreateSql()
  683. {
  684. $driver = $this->_getMockedDriver();
  685. $connection = $this->getMock('Cake\Database\Connection', [], [], '', false);
  686. $connection->expects($this->any())->method('driver')
  687. ->will($this->returnValue($driver));
  688. $table = (new Table('articles'))->addColumn('id', [
  689. 'type' => 'integer',
  690. 'null' => false
  691. ])
  692. ->addColumn('title', [
  693. 'type' => 'string',
  694. 'null' => false,
  695. ])
  696. ->addColumn('body', ['type' => 'text'])
  697. ->addColumn('created', 'datetime')
  698. ->addConstraint('primary', [
  699. 'type' => 'primary',
  700. 'columns' => ['id']
  701. ])
  702. ->addIndex('title_idx', [
  703. 'type' => 'index',
  704. 'columns' => ['title']
  705. ]);
  706. $expected = <<<SQL
  707. CREATE TABLE "articles" (
  708. "id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
  709. "title" VARCHAR NOT NULL,
  710. "body" TEXT,
  711. "created" DATETIME
  712. )
  713. SQL;
  714. $result = $table->createSql($connection);
  715. $this->assertCount(2, $result);
  716. $this->assertTextEquals($expected, $result[0]);
  717. $this->assertEquals(
  718. 'CREATE INDEX "title_idx" ON "articles" ("title")',
  719. $result[1]
  720. );
  721. }
  722. /**
  723. * Tests creating temporary tables
  724. *
  725. * @return void
  726. */
  727. public function testCreateTemporary()
  728. {
  729. $driver = $this->_getMockedDriver();
  730. $connection = $this->getMock('Cake\Database\Connection', [], [], '', false);
  731. $connection->expects($this->any())->method('driver')
  732. ->will($this->returnValue($driver));
  733. $table = (new Table('schema_articles'))->addColumn('id', [
  734. 'type' => 'integer',
  735. 'null' => false
  736. ]);
  737. $table->temporary(true);
  738. $sql = $table->createSql($connection);
  739. $this->assertContains('CREATE TEMPORARY TABLE', $sql[0]);
  740. }
  741. /**
  742. * Test primary key generation & auto-increment.
  743. *
  744. * @return void
  745. */
  746. public function testCreateSqlCompositeIntegerKey()
  747. {
  748. $driver = $this->_getMockedDriver();
  749. $connection = $this->getMock('Cake\Database\Connection', [], [], '', false);
  750. $connection->expects($this->any())->method('driver')
  751. ->will($this->returnValue($driver));
  752. $table = (new Table('articles_tags'))
  753. ->addColumn('article_id', [
  754. 'type' => 'integer',
  755. 'null' => false
  756. ])
  757. ->addColumn('tag_id', [
  758. 'type' => 'integer',
  759. 'null' => false,
  760. ])
  761. ->addConstraint('primary', [
  762. 'type' => 'primary',
  763. 'columns' => ['article_id', 'tag_id']
  764. ]);
  765. $expected = <<<SQL
  766. CREATE TABLE "articles_tags" (
  767. "article_id" INTEGER NOT NULL,
  768. "tag_id" INTEGER NOT NULL,
  769. CONSTRAINT "primary" PRIMARY KEY ("article_id", "tag_id")
  770. )
  771. SQL;
  772. $result = $table->createSql($connection);
  773. $this->assertCount(1, $result);
  774. $this->assertTextEquals($expected, $result[0]);
  775. // Sqlite only supports AUTO_INCREMENT on single column primary
  776. // keys. Ensure that schema data follows the limitations of Sqlite.
  777. $table = (new Table('composite_key'))
  778. ->addColumn('id', [
  779. 'type' => 'integer',
  780. 'null' => false,
  781. 'autoIncrement' => true
  782. ])
  783. ->addColumn('account_id', [
  784. 'type' => 'integer',
  785. 'null' => false,
  786. ])
  787. ->addConstraint('primary', [
  788. 'type' => 'primary',
  789. 'columns' => ['id', 'account_id']
  790. ]);
  791. $expected = <<<SQL
  792. CREATE TABLE "composite_key" (
  793. "id" INTEGER NOT NULL,
  794. "account_id" INTEGER NOT NULL,
  795. CONSTRAINT "primary" PRIMARY KEY ("id", "account_id")
  796. )
  797. SQL;
  798. $result = $table->createSql($connection);
  799. $this->assertCount(1, $result);
  800. $this->assertTextEquals($expected, $result[0]);
  801. }
  802. /**
  803. * test dropSql
  804. *
  805. * @return void
  806. */
  807. public function testDropSql()
  808. {
  809. $driver = $this->_getMockedDriver();
  810. $connection = $this->getMock('Cake\Database\Connection', [], [], '', false);
  811. $connection->expects($this->any())->method('driver')
  812. ->will($this->returnValue($driver));
  813. $table = new Table('articles');
  814. $result = $table->dropSql($connection);
  815. $this->assertCount(1, $result);
  816. $this->assertEquals('DROP TABLE "articles"', $result[0]);
  817. }
  818. /**
  819. * Test truncateSql()
  820. *
  821. * @return void
  822. */
  823. public function testTruncateSql()
  824. {
  825. $driver = $this->_getMockedDriver();
  826. $connection = $this->getMock('Cake\Database\Connection', [], [], '', false);
  827. $connection->expects($this->any())->method('driver')
  828. ->will($this->returnValue($driver));
  829. $statement = $this->getMock(
  830. '\PDOStatement',
  831. ['execute', 'rowCount', 'closeCursor', 'fetch']
  832. );
  833. $driver->connection()->expects($this->once())->method('prepare')
  834. ->with('SELECT 1 FROM sqlite_master WHERE name = "sqlite_sequence"')
  835. ->will($this->returnValue($statement));
  836. $statement->expects($this->at(0))->method('fetch')
  837. ->will($this->returnValue(['1']));
  838. $statement->expects($this->at(2))->method('fetch')
  839. ->will($this->returnValue(false));
  840. $table = new Table('articles');
  841. $result = $table->truncateSql($connection);
  842. $this->assertCount(2, $result);
  843. $this->assertEquals('DELETE FROM sqlite_sequence WHERE name="articles"', $result[0]);
  844. $this->assertEquals('DELETE FROM "articles"', $result[1]);
  845. }
  846. /**
  847. * Test truncateSql() with no sequences
  848. *
  849. * @return void
  850. */
  851. public function testTruncateSqlNoSequences()
  852. {
  853. $driver = $this->_getMockedDriver();
  854. $connection = $this->getMock('Cake\Database\Connection', [], [], '', false);
  855. $connection->expects($this->any())->method('driver')
  856. ->will($this->returnValue($driver));
  857. $statement = $this->getMock(
  858. '\PDOStatement',
  859. ['execute', 'rowCount', 'closeCursor', 'fetch']
  860. );
  861. $driver->connection()->expects($this->once())->method('prepare')
  862. ->with('SELECT 1 FROM sqlite_master WHERE name = "sqlite_sequence"')
  863. ->will($this->returnValue($statement));
  864. $statement->expects($this->once())->method('fetch')
  865. ->will($this->returnValue(false));
  866. $table = new Table('articles');
  867. $result = $table->truncateSql($connection);
  868. $this->assertCount(1, $result);
  869. $this->assertEquals('DELETE FROM "articles"', $result[0]);
  870. }
  871. /**
  872. * Get a schema instance with a mocked driver/pdo instances
  873. *
  874. * @return Driver
  875. */
  876. protected function _getMockedDriver()
  877. {
  878. $driver = new \Cake\Database\Driver\Sqlite();
  879. $mock = $this->getMock('FakePdo', ['quote', 'quoteIdentifier', 'prepare']);
  880. $mock->expects($this->any())
  881. ->method('quote')
  882. ->will($this->returnCallback(function ($value) {
  883. return '"' . $value . '"';
  884. }));
  885. $mock->expects($this->any())
  886. ->method('quoteIdentifier')
  887. ->will($this->returnCallback(function ($value) {
  888. return '"' . $value . '"';
  889. }));
  890. $driver->connection($mock);
  891. return $driver;
  892. }
  893. }