| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308 |
- <?php
- /**
- * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
- * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
- *
- * Licensed under The MIT License
- * For full copyright and license information, please see the LICENSE.txt
- * Redistributions of files must retain the above copyright notice.
- *
- * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
- * @link https://cakephp.org CakePHP(tm) Project
- * @since 3.0.0
- * @license https://opensource.org/licenses/mit-license.php MIT License
- */
- namespace Cake\Test\TestCase\Database\Schema;
- use Cake\Database\Driver\Postgres;
- use Cake\Database\Schema\Collection as SchemaCollection;
- use Cake\Database\Schema\PostgresSchema;
- use Cake\Database\Schema\TableSchema;
- use Cake\Datasource\ConnectionManager;
- use Cake\TestSuite\TestCase;
- use PDO;
- /**
- * Postgres schema test case.
- */
- class PostgresSchemaTest extends TestCase
- {
- /**
- * Helper method for skipping tests that need a real connection.
- *
- * @return void
- */
- protected function _needsConnection()
- {
- $config = ConnectionManager::getConfig('test');
- $this->skipIf(strpos($config['driver'], 'Postgres') === false, 'Not using Postgres for test config');
- }
- /**
- * Helper method for testing methods.
- *
- * @param \Cake\Datasource\ConnectionInterface $connection
- * @return void
- */
- protected function _createTables($connection)
- {
- $this->_needsConnection();
- $connection->execute('DROP TABLE IF EXISTS schema_articles');
- $connection->execute('DROP TABLE IF EXISTS schema_authors');
- $table = <<<SQL
- CREATE TABLE schema_authors (
- id SERIAL,
- name VARCHAR(50) DEFAULT 'bob',
- bio DATE,
- position INT DEFAULT 1,
- created TIMESTAMP,
- PRIMARY KEY (id),
- CONSTRAINT "unique_position" UNIQUE ("position")
- )
- SQL;
- $connection->execute($table);
- $table = <<<SQL
- CREATE TABLE schema_articles (
- id BIGINT PRIMARY KEY,
- title VARCHAR(20),
- body TEXT,
- author_id INTEGER NOT NULL,
- published BOOLEAN DEFAULT false,
- views SMALLINT DEFAULT 0,
- readingtime TIME,
- data JSONB,
- average_note DECIMAL(4,2),
- average_income NUMERIC(10,2),
- created TIMESTAMP,
- CONSTRAINT "content_idx" UNIQUE ("title", "body"),
- CONSTRAINT "author_idx" FOREIGN KEY ("author_id") REFERENCES "schema_authors" ("id") ON DELETE RESTRICT ON UPDATE CASCADE
- )
- SQL;
- $connection->execute($table);
- $connection->execute('COMMENT ON COLUMN "schema_articles"."title" IS \'a title\'');
- $connection->execute('CREATE INDEX "author_idx" ON "schema_articles" ("author_id")');
- }
- /**
- * Data provider for convert column testing
- *
- * @return array
- */
- public static function convertColumnProvider()
- {
- return [
- // Timestamp
- [
- ['type' => 'TIMESTAMP'],
- ['type' => 'timestamp', 'length' => null]
- ],
- [
- ['type' => 'TIMESTAMP WITHOUT TIME ZONE'],
- ['type' => 'timestamp', 'length' => null]
- ],
- // Date & time
- [
- ['type' => 'DATE'],
- ['type' => 'date', 'length' => null]
- ],
- [
- ['type' => 'TIME'],
- ['type' => 'time', 'length' => null]
- ],
- [
- ['type' => 'TIME WITHOUT TIME ZONE'],
- ['type' => 'time', 'length' => null]
- ],
- // Integer
- [
- ['type' => 'SMALLINT'],
- ['type' => 'smallinteger', 'length' => 5]
- ],
- [
- ['type' => 'INTEGER'],
- ['type' => 'integer', 'length' => 10]
- ],
- [
- ['type' => 'SERIAL'],
- ['type' => 'integer', 'length' => 10]
- ],
- [
- ['type' => 'BIGINT'],
- ['type' => 'biginteger', 'length' => 20]
- ],
- [
- ['type' => 'BIGSERIAL'],
- ['type' => 'biginteger', 'length' => 20]
- ],
- // Decimal
- [
- ['type' => 'NUMERIC'],
- ['type' => 'decimal', 'length' => null, 'precision' => null]
- ],
- [
- ['type' => 'NUMERIC', 'default' => 'NULL::numeric'],
- ['type' => 'decimal', 'length' => null, 'precision' => null, 'default' => null]
- ],
- [
- ['type' => 'DECIMAL(10,2)', 'column_precision' => 10, 'column_scale' => 2],
- ['type' => 'decimal', 'length' => 10, 'precision' => 2]
- ],
- // String
- [
- ['type' => 'VARCHAR'],
- ['type' => 'string', 'length' => null]
- ],
- [
- ['type' => 'VARCHAR(10)'],
- ['type' => 'string', 'length' => 10]
- ],
- [
- ['type' => 'CHARACTER VARYING'],
- ['type' => 'string', 'length' => null]
- ],
- [
- ['type' => 'CHARACTER VARYING(10)'],
- ['type' => 'string', 'length' => 10]
- ],
- [
- ['type' => 'CHARACTER VARYING(255)', 'default' => 'NULL::character varying'],
- ['type' => 'string', 'length' => 255, 'default' => null]
- ],
- [
- ['type' => 'CHAR(10)'],
- ['type' => 'string', 'fixed' => true, 'length' => 10]
- ],
- [
- ['type' => 'CHARACTER(10)'],
- ['type' => 'string', 'fixed' => true, 'length' => 10]
- ],
- [
- ['type' => 'MONEY'],
- ['type' => 'string', 'length' => null]
- ],
- // UUID
- [
- ['type' => 'UUID'],
- ['type' => 'uuid', 'length' => null]
- ],
- [
- ['type' => 'INET'],
- ['type' => 'string', 'length' => 39]
- ],
- // Text
- [
- ['type' => 'TEXT'],
- ['type' => 'text', 'length' => null]
- ],
- // Blob
- [
- ['type' => 'BYTEA'],
- ['type' => 'binary', 'length' => null]
- ],
- // Float
- [
- ['type' => 'REAL'],
- ['type' => 'float', 'length' => null]
- ],
- [
- ['type' => 'DOUBLE PRECISION'],
- ['type' => 'float', 'length' => null]
- ],
- // Json
- [
- ['type' => 'JSON'],
- ['type' => 'json', 'length' => null]
- ],
- [
- ['type' => 'JSONB'],
- ['type' => 'json', 'length' => null]
- ],
- ];
- }
- /**
- * Test parsing Postgres column types from field description.
- *
- * @dataProvider convertColumnProvider
- * @return void
- */
- public function testConvertColumn($field, $expected)
- {
- $field += [
- 'name' => 'field',
- 'null' => 'YES',
- 'default' => 'Default value',
- 'comment' => 'Comment section',
- 'char_length' => null,
- 'column_precision' => null,
- 'column_scale' => null,
- 'collation_name' => 'ja_JP.utf8',
- ];
- $expected += [
- 'null' => true,
- 'default' => 'Default value',
- 'comment' => 'Comment section',
- 'collate' => 'ja_JP.utf8',
- ];
- $driver = $this->getMockBuilder('Cake\Database\Driver\Postgres')->getMock();
- $dialect = new PostgresSchema($driver);
- $table = $this->getMockBuilder(TableSchema::class)
- ->setConstructorArgs(['table'])
- ->getMock();
- $table->expects($this->at(0))->method('addColumn')->with('field', $expected);
- $dialect->convertColumnDescription($table, $field);
- }
- /**
- * Test listing tables with Postgres
- *
- * @return void
- */
- public function testListTables()
- {
- $connection = ConnectionManager::get('test');
- $this->_createTables($connection);
- $schema = new SchemaCollection($connection);
- $result = $schema->listTables();
- $this->assertInternalType('array', $result);
- $this->assertContains('schema_articles', $result);
- $this->assertContains('schema_authors', $result);
- }
- /**
- * Test that describe accepts tablenames containing `schema.table`.
- *
- * @return void
- */
- public function testDescribeWithSchemaName()
- {
- $connection = ConnectionManager::get('test');
- $this->_createTables($connection);
- $schema = new SchemaCollection($connection);
- $result = $schema->describe('public.schema_articles');
- $this->assertEquals(['id'], $result->primaryKey());
- $this->assertEquals('schema_articles', $result->name());
- }
- /**
- * Test describing a table with Postgres
- *
- * @return void
- */
- public function testDescribeTable()
- {
- $connection = ConnectionManager::get('test');
- $this->_createTables($connection);
- $schema = new SchemaCollection($connection);
- $result = $schema->describe('schema_articles');
- $expected = [
- 'id' => [
- 'type' => 'biginteger',
- 'null' => false,
- 'default' => null,
- 'length' => 20,
- 'precision' => null,
- 'unsigned' => null,
- 'comment' => null,
- 'autoIncrement' => false,
- ],
- 'title' => [
- 'type' => 'string',
- 'null' => true,
- 'default' => null,
- 'length' => 20,
- 'precision' => null,
- 'comment' => 'a title',
- 'fixed' => null,
- 'collate' => null,
- ],
- 'body' => [
- 'type' => 'text',
- 'null' => true,
- 'default' => null,
- 'length' => null,
- 'precision' => null,
- 'comment' => null,
- 'collate' => null,
- ],
- 'author_id' => [
- 'type' => 'integer',
- 'null' => false,
- 'default' => null,
- 'length' => 10,
- 'precision' => null,
- 'unsigned' => null,
- 'comment' => null,
- 'autoIncrement' => null,
- ],
- 'published' => [
- 'type' => 'boolean',
- 'null' => true,
- 'default' => 0,
- 'length' => null,
- 'precision' => null,
- 'comment' => null,
- ],
- 'views' => [
- 'type' => 'smallinteger',
- 'null' => true,
- 'default' => 0,
- 'length' => 5,
- 'precision' => null,
- 'unsigned' => null,
- 'comment' => null,
- ],
- 'readingtime' => [
- 'type' => 'time',
- 'null' => true,
- 'default' => null,
- 'length' => null,
- 'precision' => null,
- 'comment' => null,
- ],
- 'data' => [
- 'type' => 'json',
- 'null' => true,
- 'default' => null,
- 'length' => null,
- 'precision' => null,
- 'comment' => null,
- ],
- 'average_note' => [
- 'type' => 'decimal',
- 'null' => true,
- 'default' => null,
- 'length' => 4,
- 'precision' => 2,
- 'unsigned' => null,
- 'comment' => null,
- ],
- 'average_income' => [
- 'type' => 'decimal',
- 'null' => true,
- 'default' => null,
- 'length' => 10,
- 'precision' => 2,
- 'unsigned' => null,
- 'comment' => null,
- ],
- 'created' => [
- 'type' => 'timestamp',
- 'null' => true,
- 'default' => null,
- 'length' => null,
- 'precision' => null,
- 'comment' => null,
- ],
- ];
- $this->assertEquals(['id'], $result->primaryKey());
- foreach ($expected as $field => $definition) {
- $this->assertEquals($definition, $result->getColumn($field));
- }
- }
- /**
- * Test describing a table with postgres and composite keys
- *
- * @return void
- */
- public function testDescribeTableCompositeKey()
- {
- $this->_needsConnection();
- $connection = ConnectionManager::get('test');
- $sql = <<<SQL
- CREATE TABLE schema_composite (
- "id" SERIAL,
- "site_id" INTEGER NOT NULL,
- "name" VARCHAR(255),
- PRIMARY KEY("id", "site_id")
- );
- SQL;
- $connection->execute($sql);
- $schema = new SchemaCollection($connection);
- $result = $schema->describe('schema_composite');
- $connection->execute('DROP TABLE schema_composite');
- $this->assertEquals(['id', 'site_id'], $result->primaryKey());
- $this->assertTrue($result->getColumn('id')['autoIncrement'], 'id should be autoincrement');
- $this->assertNull($result->getColumn('site_id')['autoIncrement'], 'site_id should not be autoincrement');
- }
- /**
- * Test describing a table containing defaults with Postgres
- *
- * @return void
- */
- public function testDescribeTableWithDefaults()
- {
- $connection = ConnectionManager::get('test');
- $this->_createTables($connection);
- $schema = new SchemaCollection($connection);
- $result = $schema->describe('schema_authors');
- $expected = [
- 'id' => [
- 'type' => 'integer',
- 'null' => false,
- 'default' => null,
- 'length' => 10,
- 'precision' => null,
- 'unsigned' => null,
- 'comment' => null,
- 'autoIncrement' => true,
- ],
- 'name' => [
- 'type' => 'string',
- 'null' => true,
- 'default' => 'bob',
- 'length' => 50,
- 'precision' => null,
- 'comment' => null,
- 'fixed' => null,
- 'collate' => null,
- ],
- 'bio' => [
- 'type' => 'date',
- 'null' => true,
- 'default' => null,
- 'length' => null,
- 'precision' => null,
- 'comment' => null,
- ],
- 'position' => [
- 'type' => 'integer',
- 'null' => true,
- 'default' => '1',
- 'length' => 10,
- 'precision' => null,
- 'comment' => null,
- 'unsigned' => null,
- 'autoIncrement' => null,
- ],
- 'created' => [
- 'type' => 'timestamp',
- 'null' => true,
- 'default' => null,
- 'length' => null,
- 'precision' => null,
- 'comment' => null,
- ],
- ];
- $this->assertEquals(['id'], $result->primaryKey());
- foreach ($expected as $field => $definition) {
- $this->assertEquals($definition, $result->getColumn($field), "Mismatch in $field column");
- }
- }
- /**
- * Test describing a table with containing keywords
- *
- * @return void
- */
- public function testDescribeTableConstraintsWithKeywords()
- {
- $connection = ConnectionManager::get('test');
- $this->_createTables($connection);
- $schema = new SchemaCollection($connection);
- $result = $schema->describe('schema_authors');
- $this->assertInstanceOf('Cake\Database\Schema\TableSchema', $result);
- $expected = [
- 'primary' => [
- 'type' => 'primary',
- 'columns' => ['id'],
- 'length' => []
- ],
- 'unique_position' => [
- 'type' => 'unique',
- 'columns' => ['position'],
- 'length' => []
- ]
- ];
- $this->assertCount(2, $result->constraints());
- $this->assertEquals($expected['primary'], $result->getConstraint('primary'));
- $this->assertEquals($expected['unique_position'], $result->getConstraint('unique_position'));
- }
- /**
- * Test describing a table with indexes
- *
- * @return void
- */
- public function testDescribeTableIndexes()
- {
- $connection = ConnectionManager::get('test');
- $this->_createTables($connection);
- $schema = new SchemaCollection($connection);
- $result = $schema->describe('schema_articles');
- $this->assertInstanceOf('Cake\Database\Schema\TableSchema', $result);
- $expected = [
- 'primary' => [
- 'type' => 'primary',
- 'columns' => ['id'],
- 'length' => []
- ],
- 'content_idx' => [
- 'type' => 'unique',
- 'columns' => ['title', 'body'],
- 'length' => []
- ]
- ];
- $this->assertCount(3, $result->constraints());
- $expected = [
- 'primary' => [
- 'type' => 'primary',
- 'columns' => ['id'],
- 'length' => []
- ],
- 'content_idx' => [
- 'type' => 'unique',
- 'columns' => ['title', 'body'],
- 'length' => []
- ],
- 'author_idx' => [
- 'type' => 'foreign',
- 'columns' => ['author_id'],
- 'references' => ['schema_authors', 'id'],
- 'length' => [],
- 'update' => 'cascade',
- 'delete' => 'restrict',
- ]
- ];
- $this->assertEquals($expected['primary'], $result->getConstraint('primary'));
- $this->assertEquals($expected['content_idx'], $result->getConstraint('content_idx'));
- $this->assertEquals($expected['author_idx'], $result->getConstraint('author_idx'));
- $this->assertCount(1, $result->indexes());
- $expected = [
- 'type' => 'index',
- 'columns' => ['author_id'],
- 'length' => []
- ];
- $this->assertEquals($expected, $result->getIndex('author_idx'));
- }
- /**
- * Test describing a table with indexes with nulls first
- *
- * @return void
- */
- public function testDescribeTableIndexesNullsFirst()
- {
- $this->_needsConnection();
- $connection = ConnectionManager::get('test');
- $connection->execute('DROP TABLE IF EXISTS schema_index');
- $table = <<<SQL
- CREATE TABLE schema_index (
- id serial NOT NULL,
- user_id integer NOT NULL,
- group_id integer NOT NULL,
- grade double precision
- )
- WITH (
- OIDS=FALSE
- )
- SQL;
- $connection->execute($table);
- $index = <<<SQL
- CREATE INDEX schema_index_nulls
- ON schema_index
- USING btree
- (group_id, grade DESC NULLS FIRST);
- SQL;
- $connection->execute($index);
- $schema = new SchemaCollection($connection);
- $result = $schema->describe('schema_index');
- $this->assertCount(1, $result->indexes());
- $expected = [
- 'type' => 'index',
- 'columns' => ['group_id', 'grade'],
- 'length' => []
- ];
- $this->assertEquals($expected, $result->getIndex('schema_index_nulls'));
- $connection->execute('DROP TABLE schema_index');
- }
- /**
- * Test describing a table with postgres function defaults
- *
- * @return void
- */
- public function testDescribeTableFunctionDefaultValue()
- {
- $this->_needsConnection();
- $connection = ConnectionManager::get('test');
- $sql = <<<SQL
- CREATE TABLE schema_function_defaults (
- "id" SERIAL,
- year INT DEFAULT DATE_PART('year'::text, NOW()),
- PRIMARY KEY("id")
- );
- SQL;
- $connection->execute($sql);
- $schema = new SchemaCollection($connection);
- $result = $schema->describe('schema_function_defaults');
- $connection->execute('DROP TABLE schema_function_defaults');
- $expected = [
- 'type' => 'integer',
- 'default' => "date_part('year'::text, now())",
- 'null' => true,
- 'precision' => null,
- 'length' => 10,
- 'comment' => null,
- 'unsigned' => null,
- 'autoIncrement' => null,
- ];
- $this->assertEquals($expected, $result->getColumn('year'));
- }
- /**
- * Column provider for creating column sql
- *
- * @return array
- */
- public static function columnSqlProvider()
- {
- return [
- // strings
- [
- 'title',
- ['type' => 'string', 'length' => 25, 'null' => false],
- '"title" VARCHAR(25) NOT NULL'
- ],
- [
- 'title',
- ['type' => 'string', 'length' => 25, 'null' => true, 'default' => 'ignored'],
- '"title" VARCHAR(25) DEFAULT \'ignored\'',
- ],
- [
- 'id',
- ['type' => 'string', 'length' => 32, 'fixed' => true, 'null' => false],
- '"id" CHAR(32) NOT NULL'
- ],
- [
- 'id',
- ['type' => 'uuid', 'length' => 36, 'null' => false],
- '"id" UUID NOT NULL'
- ],
- [
- 'id',
- ['type' => 'binaryuuid', 'length' => null, 'null' => false],
- '"id" UUID NOT NULL'
- ],
- [
- 'role',
- ['type' => 'string', 'length' => 10, 'null' => false, 'default' => 'admin'],
- '"role" VARCHAR(10) NOT NULL DEFAULT \'admin\''
- ],
- [
- 'title',
- ['type' => 'string'],
- '"title" VARCHAR'
- ],
- [
- 'title',
- ['type' => 'string', 'length' => 255, 'null' => false, 'collate' => 'C'],
- '"title" VARCHAR(255) COLLATE "C" NOT NULL'
- ],
- // Text
- [
- 'body',
- ['type' => 'text', 'null' => false],
- '"body" TEXT NOT NULL'
- ],
- [
- 'body',
- ['type' => 'text', 'length' => TableSchema::LENGTH_TINY, 'null' => false],
- sprintf('"body" VARCHAR(%s) NOT NULL', TableSchema::LENGTH_TINY)
- ],
- [
- 'body',
- ['type' => 'text', 'length' => TableSchema::LENGTH_MEDIUM, 'null' => false],
- '"body" TEXT NOT NULL'
- ],
- [
- 'body',
- ['type' => 'text', 'length' => TableSchema::LENGTH_LONG, 'null' => false],
- '"body" TEXT NOT NULL'
- ],
- [
- 'body',
- ['type' => 'text', 'null' => false, 'collate' => 'C'],
- '"body" TEXT COLLATE "C" NOT NULL'
- ],
- // Integers
- [
- 'post_id',
- ['type' => 'tinyinteger', 'length' => 11],
- '"post_id" SMALLINT'
- ],
- [
- 'post_id',
- ['type' => 'smallinteger', 'length' => 11],
- '"post_id" SMALLINT'
- ],
- [
- 'post_id',
- ['type' => 'integer', 'length' => 11],
- '"post_id" INTEGER'
- ],
- [
- 'post_id',
- ['type' => 'biginteger', 'length' => 20],
- '"post_id" BIGINT'
- ],
- [
- 'post_id',
- ['type' => 'integer', 'autoIncrement' => true, 'length' => 11],
- '"post_id" SERIAL'
- ],
- [
- 'post_id',
- ['type' => 'biginteger', 'autoIncrement' => true, 'length' => 20],
- '"post_id" BIGSERIAL'
- ],
- // Decimal
- [
- 'value',
- ['type' => 'decimal'],
- '"value" DECIMAL'
- ],
- [
- 'value',
- ['type' => 'decimal', 'length' => 11],
- '"value" DECIMAL(11,0)'
- ],
- [
- 'value',
- ['type' => 'decimal', 'length' => 12, 'precision' => 5],
- '"value" DECIMAL(12,5)'
- ],
- // Float
- [
- 'value',
- ['type' => 'float'],
- '"value" FLOAT'
- ],
- [
- 'value',
- ['type' => 'float', 'length' => 11, 'precision' => 3],
- '"value" FLOAT(3)'
- ],
- // Binary
- [
- 'img',
- ['type' => 'binary'],
- '"img" BYTEA'
- ],
- // Boolean
- [
- 'checked',
- ['type' => 'boolean', 'default' => false],
- '"checked" BOOLEAN DEFAULT FALSE'
- ],
- [
- 'checked',
- ['type' => 'boolean', 'default' => true, 'null' => false],
- '"checked" BOOLEAN NOT NULL DEFAULT TRUE'
- ],
- // Boolean
- [
- 'checked',
- ['type' => 'boolean', 'default' => 0],
- '"checked" BOOLEAN DEFAULT FALSE'
- ],
- [
- 'checked',
- ['type' => 'boolean', 'default' => 1, 'null' => false],
- '"checked" BOOLEAN NOT NULL DEFAULT TRUE'
- ],
- // Datetime
- [
- 'created',
- ['type' => 'datetime'],
- '"created" TIMESTAMP'
- ],
- [
- 'open_date',
- ['type' => 'datetime', 'null' => false, 'default' => '2016-12-07 23:04:00'],
- '"open_date" TIMESTAMP NOT NULL DEFAULT \'2016-12-07 23:04:00\''
- ],
- [
- 'null_date',
- ['type' => 'datetime', 'null' => true],
- '"null_date" TIMESTAMP DEFAULT NULL'
- ],
- [
- 'current_timestamp',
- ['type' => 'datetime', 'null' => false, 'default' => 'CURRENT_TIMESTAMP'],
- '"current_timestamp" TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP'
- ],
- // Date & Time
- [
- 'start_date',
- ['type' => 'date'],
- '"start_date" DATE'
- ],
- [
- 'start_time',
- ['type' => 'time'],
- '"start_time" TIME'
- ],
- // Timestamp
- [
- 'created',
- ['type' => 'timestamp', 'null' => true],
- '"created" TIMESTAMP DEFAULT NULL'
- ],
- ];
- }
- /**
- * Test generating column definitions
- *
- * @dataProvider columnSqlProvider
- * @return void
- */
- public function testColumnSql($name, $data, $expected)
- {
- $driver = $this->_getMockedDriver();
- $schema = new PostgresSchema($driver);
- $table = (new TableSchema('schema_articles'))->addColumn($name, $data);
- $this->assertEquals($expected, $schema->columnSql($table, $name));
- }
- /**
- * Test generating a column that is a primary key.
- *
- * @return void
- */
- public function testColumnSqlPrimaryKey()
- {
- $driver = $this->_getMockedDriver();
- $schema = new PostgresSchema($driver);
- $table = new TableSchema('schema_articles');
- $table->addColumn('id', [
- 'type' => 'integer',
- 'null' => false
- ])
- ->addConstraint('primary', [
- 'type' => 'primary',
- 'columns' => ['id']
- ]);
- $result = $schema->columnSql($table, 'id');
- $this->assertEquals($result, '"id" SERIAL');
- }
- /**
- * Provide data for testing constraintSql
- *
- * @return array
- */
- public static function constraintSqlProvider()
- {
- return [
- [
- 'primary',
- ['type' => 'primary', 'columns' => ['title']],
- 'PRIMARY KEY ("title")'
- ],
- [
- 'unique_idx',
- ['type' => 'unique', 'columns' => ['title', 'author_id']],
- 'CONSTRAINT "unique_idx" UNIQUE ("title", "author_id")'
- ],
- [
- 'author_id_idx',
- ['type' => 'foreign', 'columns' => ['author_id'], 'references' => ['authors', 'id']],
- 'CONSTRAINT "author_id_idx" FOREIGN KEY ("author_id") ' .
- 'REFERENCES "authors" ("id") ON UPDATE RESTRICT ON DELETE RESTRICT DEFERRABLE INITIALLY IMMEDIATE'
- ],
- [
- 'author_id_idx',
- ['type' => 'foreign', 'columns' => ['author_id'], 'references' => ['authors', 'id'], 'update' => 'cascade'],
- 'CONSTRAINT "author_id_idx" FOREIGN KEY ("author_id") ' .
- 'REFERENCES "authors" ("id") ON UPDATE CASCADE ON DELETE RESTRICT DEFERRABLE INITIALLY IMMEDIATE'
- ],
- [
- 'author_id_idx',
- ['type' => 'foreign', 'columns' => ['author_id'], 'references' => ['authors', 'id'], 'update' => 'restrict'],
- 'CONSTRAINT "author_id_idx" FOREIGN KEY ("author_id") ' .
- 'REFERENCES "authors" ("id") ON UPDATE RESTRICT ON DELETE RESTRICT DEFERRABLE INITIALLY IMMEDIATE'
- ],
- [
- 'author_id_idx',
- ['type' => 'foreign', 'columns' => ['author_id'], 'references' => ['authors', 'id'], 'update' => 'setNull'],
- 'CONSTRAINT "author_id_idx" FOREIGN KEY ("author_id") ' .
- 'REFERENCES "authors" ("id") ON UPDATE SET NULL ON DELETE RESTRICT DEFERRABLE INITIALLY IMMEDIATE'
- ],
- [
- 'author_id_idx',
- ['type' => 'foreign', 'columns' => ['author_id'], 'references' => ['authors', 'id'], 'update' => 'noAction'],
- 'CONSTRAINT "author_id_idx" FOREIGN KEY ("author_id") ' .
- 'REFERENCES "authors" ("id") ON UPDATE NO ACTION ON DELETE RESTRICT DEFERRABLE INITIALLY IMMEDIATE'
- ],
- ];
- }
- /**
- * Test the constraintSql method.
- *
- * @dataProvider constraintSqlProvider
- */
- public function testConstraintSql($name, $data, $expected)
- {
- $driver = $this->_getMockedDriver();
- $schema = new PostgresSchema($driver);
- $table = (new TableSchema('schema_articles'))->addColumn('title', [
- 'type' => 'string',
- 'length' => 255
- ])->addColumn('author_id', [
- 'type' => 'integer',
- ])->addConstraint($name, $data);
- $this->assertTextEquals($expected, $schema->constraintSql($table, $name));
- }
- /**
- * Test the addConstraintSql method.
- *
- * @return void
- */
- public function testAddConstraintSql()
- {
- $driver = $this->_getMockedDriver();
- $connection = $this->getMockBuilder('Cake\Database\Connection')
- ->disableOriginalConstructor()
- ->getMock();
- $connection->expects($this->any())->method('getDriver')
- ->will($this->returnValue($driver));
- $table = (new TableSchema('posts'))
- ->addColumn('author_id', [
- 'type' => 'integer',
- 'null' => false
- ])
- ->addColumn('category_id', [
- 'type' => 'integer',
- 'null' => false
- ])
- ->addColumn('category_name', [
- 'type' => 'integer',
- 'null' => false
- ])
- ->addConstraint('author_fk', [
- 'type' => 'foreign',
- 'columns' => ['author_id'],
- 'references' => ['authors', 'id'],
- 'update' => 'cascade',
- 'delete' => 'cascade'
- ])
- ->addConstraint('category_fk', [
- 'type' => 'foreign',
- 'columns' => ['category_id', 'category_name'],
- 'references' => ['categories', ['id', 'name']],
- 'update' => 'cascade',
- 'delete' => 'cascade'
- ]);
- $expected = [
- 'ALTER TABLE "posts" ADD CONSTRAINT "author_fk" FOREIGN KEY ("author_id") REFERENCES "authors" ("id") ON UPDATE CASCADE ON DELETE CASCADE DEFERRABLE INITIALLY IMMEDIATE;',
- 'ALTER TABLE "posts" ADD CONSTRAINT "category_fk" FOREIGN KEY ("category_id", "category_name") REFERENCES "categories" ("id", "name") ON UPDATE CASCADE ON DELETE CASCADE DEFERRABLE INITIALLY IMMEDIATE;'
- ];
- $result = $table->addConstraintSql($connection);
- $this->assertCount(2, $result);
- $this->assertEquals($expected, $result);
- }
- /**
- * Test the dropConstraintSql method.
- *
- * @return void
- */
- public function testDropConstraintSql()
- {
- $driver = $this->_getMockedDriver();
- $connection = $this->getMockBuilder('Cake\Database\Connection')
- ->disableOriginalConstructor()
- ->getMock();
- $connection->expects($this->any())->method('getDriver')
- ->will($this->returnValue($driver));
- $table = (new TableSchema('posts'))
- ->addColumn('author_id', [
- 'type' => 'integer',
- 'null' => false
- ])
- ->addColumn('category_id', [
- 'type' => 'integer',
- 'null' => false
- ])
- ->addColumn('category_name', [
- 'type' => 'integer',
- 'null' => false
- ])
- ->addConstraint('author_fk', [
- 'type' => 'foreign',
- 'columns' => ['author_id'],
- 'references' => ['authors', 'id'],
- 'update' => 'cascade',
- 'delete' => 'cascade'
- ])
- ->addConstraint('category_fk', [
- 'type' => 'foreign',
- 'columns' => ['category_id', 'category_name'],
- 'references' => ['categories', ['id', 'name']],
- 'update' => 'cascade',
- 'delete' => 'cascade'
- ]);
- $expected = [
- 'ALTER TABLE "posts" DROP CONSTRAINT "author_fk";',
- 'ALTER TABLE "posts" DROP CONSTRAINT "category_fk";'
- ];
- $result = $table->dropConstraintSql($connection);
- $this->assertCount(2, $result);
- $this->assertEquals($expected, $result);
- }
- /**
- * Integration test for converting a Schema\Table into MySQL table creates.
- *
- * @return void
- */
- public function testCreateSql()
- {
- $driver = $this->_getMockedDriver();
- $connection = $this->getMockBuilder('Cake\Database\Connection')
- ->disableOriginalConstructor()
- ->getMock();
- $connection->expects($this->any())->method('getDriver')
- ->will($this->returnValue($driver));
- $table = (new TableSchema('schema_articles'))->addColumn('id', [
- 'type' => 'integer',
- 'null' => false
- ])
- ->addColumn('title', [
- 'type' => 'string',
- 'null' => false,
- 'comment' => 'This is the title',
- ])
- ->addColumn('body', ['type' => 'text'])
- ->addColumn('data', ['type' => 'json'])
- ->addColumn('hash', [
- 'type' => 'string',
- 'fixed' => true,
- 'length' => 40,
- 'collate' => 'C',
- 'null' => false,
- ])
- ->addColumn('created', 'datetime')
- ->addConstraint('primary', [
- 'type' => 'primary',
- 'columns' => ['id'],
- ])
- ->addIndex('title_idx', [
- 'type' => 'index',
- 'columns' => ['title'],
- ]);
- $expected = <<<SQL
- CREATE TABLE "schema_articles" (
- "id" SERIAL,
- "title" VARCHAR NOT NULL,
- "body" TEXT,
- "data" JSONB,
- "hash" CHAR(40) COLLATE "C" NOT NULL,
- "created" TIMESTAMP,
- PRIMARY KEY ("id")
- )
- SQL;
- $result = $table->createSql($connection);
- $this->assertCount(3, $result);
- $this->assertTextEquals($expected, $result[0]);
- $this->assertEquals(
- 'CREATE INDEX "title_idx" ON "schema_articles" ("title")',
- $result[1]
- );
- $this->assertEquals(
- 'COMMENT ON COLUMN "schema_articles"."title" IS \'This is the title\'',
- $result[2]
- );
- }
- /**
- * Tests creating temporary tables
- *
- * @return void
- */
- public function testCreateTemporary()
- {
- $driver = $this->_getMockedDriver();
- $connection = $this->getMockBuilder('Cake\Database\Connection')
- ->disableOriginalConstructor()
- ->getMock();
- $connection->expects($this->any())->method('getDriver')
- ->will($this->returnValue($driver));
- $table = (new TableSchema('schema_articles'))->addColumn('id', [
- 'type' => 'integer',
- 'null' => false
- ]);
- $table->setTemporary(true);
- $sql = $table->createSql($connection);
- $this->assertContains('CREATE TEMPORARY TABLE', $sql[0]);
- }
- /**
- * Test primary key generation & auto-increment.
- *
- * @return void
- */
- public function testCreateSqlCompositeIntegerKey()
- {
- $driver = $this->_getMockedDriver();
- $connection = $this->getMockBuilder('Cake\Database\Connection')
- ->disableOriginalConstructor()
- ->getMock();
- $connection->expects($this->any())->method('getDriver')
- ->will($this->returnValue($driver));
- $table = (new TableSchema('articles_tags'))
- ->addColumn('article_id', [
- 'type' => 'integer',
- 'null' => false
- ])
- ->addColumn('tag_id', [
- 'type' => 'integer',
- 'null' => false,
- ])
- ->addConstraint('primary', [
- 'type' => 'primary',
- 'columns' => ['article_id', 'tag_id']
- ]);
- $expected = <<<SQL
- CREATE TABLE "articles_tags" (
- "article_id" INTEGER NOT NULL,
- "tag_id" INTEGER NOT NULL,
- PRIMARY KEY ("article_id", "tag_id")
- )
- SQL;
- $result = $table->createSql($connection);
- $this->assertCount(1, $result);
- $this->assertTextEquals($expected, $result[0]);
- $table = (new TableSchema('composite_key'))
- ->addColumn('id', [
- 'type' => 'integer',
- 'null' => false,
- 'autoIncrement' => true
- ])
- ->addColumn('account_id', [
- 'type' => 'integer',
- 'null' => false,
- ])
- ->addConstraint('primary', [
- 'type' => 'primary',
- 'columns' => ['id', 'account_id']
- ]);
- $expected = <<<SQL
- CREATE TABLE "composite_key" (
- "id" SERIAL,
- "account_id" INTEGER NOT NULL,
- PRIMARY KEY ("id", "account_id")
- )
- SQL;
- $result = $table->createSql($connection);
- $this->assertCount(1, $result);
- $this->assertTextEquals($expected, $result[0]);
- }
- /**
- * test dropSql
- *
- * @return void
- */
- public function testDropSql()
- {
- $driver = $this->_getMockedDriver();
- $connection = $this->getMockBuilder('Cake\Database\Connection')
- ->disableOriginalConstructor()
- ->getMock();
- $connection->expects($this->any())->method('getDriver')
- ->will($this->returnValue($driver));
- $table = new TableSchema('schema_articles');
- $result = $table->dropSql($connection);
- $this->assertCount(1, $result);
- $this->assertEquals('DROP TABLE "schema_articles" CASCADE', $result[0]);
- }
- /**
- * Test truncateSql()
- *
- * @return void
- */
- public function testTruncateSql()
- {
- $driver = $this->_getMockedDriver();
- $connection = $this->getMockBuilder('Cake\Database\Connection')
- ->disableOriginalConstructor()
- ->getMock();
- $connection->expects($this->any())->method('getDriver')
- ->will($this->returnValue($driver));
- $table = new TableSchema('schema_articles');
- $table->addColumn('id', 'integer')
- ->addConstraint('primary', [
- 'type' => 'primary',
- 'columns' => ['id']
- ]);
- $result = $table->truncateSql($connection);
- $this->assertCount(1, $result);
- $this->assertEquals('TRUNCATE "schema_articles" RESTART IDENTITY CASCADE', $result[0]);
- }
- /**
- * Get a schema instance with a mocked driver/pdo instances
- *
- * @return \Cake\Database\Driver
- */
- protected function _getMockedDriver()
- {
- $driver = new Postgres();
- $mock = $this->getMockBuilder(PDO::class)
- ->setMethods(['quote'])
- ->disableOriginalConstructor()
- ->getMock();
- $mock->expects($this->any())
- ->method('quote')
- ->will($this->returnCallback(function ($value) {
- return "'$value'";
- }));
- $driver->setConnection($mock);
- return $driver;
- }
- }
|