SqliteSchemaTest.php 22 KB

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