SqliteSchemaTest.php 29 KB

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