SqliteSchemaTest.php 29 KB

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