SqliteSchemaTest.php 23 KB

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