From 40e7c8f8592ebe38d2f420d7eb95b7ccdc281554 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Fri, 7 Jul 2023 15:46:41 +0530 Subject: [PATCH 001/358] Initial commit of this PR --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 7677e7aa..2dd85db3 100644 --- a/README.md +++ b/README.md @@ -530,3 +530,4 @@ Professional support, consulting as well as software development services are av https://www.cebe.cc/en/contact Development of this library is sponsored by [cebe.:cloud: "Your Professional Deployment Platform"](https://cebe.cloud). + From 186045dc08da70dc0edd4d549484f664c3b2ad37 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Fri, 7 Jul 2023 16:59:01 +0530 Subject: [PATCH 002/358] Add failing test --- README.md | 7 ++++- .../132_create_migration_for_drop_table.php | 13 +++++++++ .../132_create_migration_for_drop_table.yaml | 29 +++++++++++++++++++ tests/unit/IssueFixTest.php | 27 +++++++++++++++++ 4 files changed, 75 insertions(+), 1 deletion(-) create mode 100644 tests/specs/issue_fix/132_create_migration_for_drop_table/132_create_migration_for_drop_table.php create mode 100644 tests/specs/issue_fix/132_create_migration_for_drop_table/132_create_migration_for_drop_table.yaml diff --git a/README.md b/README.md index 2dd85db3..8675503a 100644 --- a/README.md +++ b/README.md @@ -273,6 +273,12 @@ Provide custom column name in case of relationship column. Example: - x-fk-column-name: redelivery_of # this will create `redelivery_of` column instead of `redelivery_of_id` ``` + +### `x-keep-tables` + +You may ... TODO docs for https://github.com/cebe/yii2-openapi/issues/132 + + ## Many-to-Many relation definition There are two ways for define many-to-many relations: @@ -530,4 +536,3 @@ Professional support, consulting as well as software development services are av https://www.cebe.cc/en/contact Development of this library is sponsored by [cebe.:cloud: "Your Professional Deployment Platform"](https://cebe.cloud). - diff --git a/tests/specs/issue_fix/132_create_migration_for_drop_table/132_create_migration_for_drop_table.php b/tests/specs/issue_fix/132_create_migration_for_drop_table/132_create_migration_for_drop_table.php new file mode 100644 index 00000000..7fe5327f --- /dev/null +++ b/tests/specs/issue_fix/132_create_migration_for_drop_table/132_create_migration_for_drop_table.php @@ -0,0 +1,13 @@ + '@specs/issue_fix/132_create_migration_for_drop_table/132_create_migration_for_drop_table.yaml', + 'generateUrls' => false, + 'generateModels' => true, + 'excludeModels' => [ + 'Error', + ], + 'generateControllers' => false, + 'generateMigrations' => true, + 'generateModelFaker' => false, +]; diff --git a/tests/specs/issue_fix/132_create_migration_for_drop_table/132_create_migration_for_drop_table.yaml b/tests/specs/issue_fix/132_create_migration_for_drop_table/132_create_migration_for_drop_table.yaml new file mode 100644 index 00000000..a48e1a15 --- /dev/null +++ b/tests/specs/issue_fix/132_create_migration_for_drop_table/132_create_migration_for_drop_table.yaml @@ -0,0 +1,29 @@ +openapi: "3.0.0" +info: + version: 1.0.0 + title: 132_create_migration_for_drop_table \#132 +paths: + /: + get: + summary: List + operationId: list + responses: + '200': + description: The information + +components: + schemas: + Pristine: + type: object + description: 132_create_migration_for_drop_table + required: + - id + properties: + id: + type: integer + billing_factor: + description: integer between 0 and 100, default value 100 + type: integer + default: 100 + nullable: false + x-faker: '$faker->numberBetween(0, 100)' diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index 9a64de11..508f9824 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -65,6 +65,7 @@ private function deleteTables() $this->deleteTableForQuoteInAlterColumn(); $this->deleteTableForTimestampIssue143(); $this->deleteTablesForWrongMigrationForPgsqlForStringVarcharDatatype149(); + $this->deleteTablesForCreateMigrationForDropTable132(); } private function deleteTablesForFloatIssue() @@ -272,4 +273,30 @@ public function testNullableFalseInRequired() ]); $this->checkFiles($actualFiles, $expectedFiles); } + + // Create migration for drop table if a entire schema is deleted from OpenAPI spec #132 + // https://github.com/cebe/yii2-openapi/issues/132 + public function testCreateMigrationForDropTable132() + { + $testFile = Yii::getAlias("@specs/issue_fix/132_create_migration_for_drop_table/132_create_migration_for_drop_table.php"); + $this->deleteTablesForNoSyntaxError107(); + $this->createTableForNoSyntaxError107(); + $this->runGenerator($testFile, 'mysql'); + // ... TODO + $this->deleteTables(); + } + + private function createTableForCreateMigrationForDropTable132() + { + Yii::$app->db->createCommand()->createTable('{{%fruits}}', [ + 'id' => 'pk', + 'name' => 'string(150)', + ])->execute(); + } + + private function deleteTablesForCreateMigrationForDropTable132() + { + Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%fruits}}')->execute(); + } + } From 242ecde72204d4b104a7272dbbb58a6b4ad1f49f Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Mon, 10 Jul 2023 22:23:52 +0530 Subject: [PATCH 003/358] WIP --- README.md | 22 +++++++++++++++++++ src/lib/SchemaToDatabase.php | 2 +- src/lib/generators/MigrationsGenerator.php | 15 +++++++++++++ src/lib/items/MigrationModel.php | 3 ++- .../132_create_migration_for_drop_table.yaml | 10 +++++++++ tests/unit/IssueFixTest.php | 6 ++++- 6 files changed, 55 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 8675503a..2a248b39 100644 --- a/README.md +++ b/README.md @@ -536,3 +536,25 @@ Professional support, consulting as well as software development services are av https://www.cebe.cc/en/contact Development of this library is sponsored by [cebe.:cloud: "Your Professional Deployment Platform"](https://cebe.cloud). + + +--- + + +TODO + +foreach dbmodels + grab table names + +create list of all table names +--- +fetch all table name list from DB (SQL query) + +find the diff + +create drop table mig diff tables + +consider `x-keep-table` + + + diff --git a/src/lib/SchemaToDatabase.php b/src/lib/SchemaToDatabase.php index 0e93ff29..5cdcb799 100644 --- a/src/lib/SchemaToDatabase.php +++ b/src/lib/SchemaToDatabase.php @@ -88,7 +88,7 @@ public function prepareModels():array if ($junctions->isJunctionSchema($schemaName)) { $schemaName = $junctions->trimPrefix($schemaName); } - /**@var \cebe\yii2openapi\lib\AttributeResolver $resolver */ + /** @var \cebe\yii2openapi\lib\AttributeResolver $resolver */ $resolver = Yii::createObject(AttributeResolver::class, [$schemaName, $schema, $junctions, $this->config]); $models[$schemaName] = $resolver->resolve(); } diff --git a/src/lib/generators/MigrationsGenerator.php b/src/lib/generators/MigrationsGenerator.php index 4b5ddee0..309a91f3 100644 --- a/src/lib/generators/MigrationsGenerator.php +++ b/src/lib/generators/MigrationsGenerator.php @@ -110,6 +110,21 @@ public function generate():CodeFiles public function buildMigrations():array { $junctions = []; + + // MySQL + // MariaDB TODO + // PgSQL TODO + $sql='SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES'; + $tables = Yii::$app->db + ->createCommand($sql) + ->queryAll(); + var_dump($tables); die; + + + foreach ($this->models as $model) {var_dump($model->tableAlias);} + + var_dump(array_keys($this->models)); die; + foreach ($this->models as $model) { $migration = $this->createBuilder($model)->build(); if ($migration->notEmpty()) { diff --git a/src/lib/items/MigrationModel.php b/src/lib/items/MigrationModel.php index a8ba6611..2f4bcdb6 100644 --- a/src/lib/items/MigrationModel.php +++ b/src/lib/items/MigrationModel.php @@ -132,7 +132,8 @@ public function addUpCode($code, bool $toTop = false):MigrationModel return $this; } - /**add down code, by default to top + /** + * Add down code, by default to top * @param array|string $code * @param bool $toBottom * @return $this diff --git a/tests/specs/issue_fix/132_create_migration_for_drop_table/132_create_migration_for_drop_table.yaml b/tests/specs/issue_fix/132_create_migration_for_drop_table/132_create_migration_for_drop_table.yaml index a48e1a15..23915a2f 100644 --- a/tests/specs/issue_fix/132_create_migration_for_drop_table/132_create_migration_for_drop_table.yaml +++ b/tests/specs/issue_fix/132_create_migration_for_drop_table/132_create_migration_for_drop_table.yaml @@ -27,3 +27,13 @@ components: default: 100 nullable: false x-faker: '$faker->numberBetween(0, 100)' + Foo: + type: object + description: 132_create_migration_for_drop_table + required: + - id + properties: + id: + type: integer + factor: + type: integer diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index 508f9824..141c677d 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -292,11 +292,15 @@ private function createTableForCreateMigrationForDropTable132() 'id' => 'pk', 'name' => 'string(150)', ])->execute(); + Yii::$app->db->createCommand()->createTable('{{%pristines}}', [ + 'id' => 'pk', + 'name' => 'string(150)', + ])->execute(); } private function deleteTablesForCreateMigrationForDropTable132() { Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%fruits}}')->execute(); + Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%pristines}}')->execute(); } - } From a5cb8fae313ed098252c8a84ee177e5d7ce85b01 Mon Sep 17 00:00:00 2001 From: Carsten Brandt Date: Wed, 29 May 2024 15:12:09 +0200 Subject: [PATCH 004/358] Rename package --- .env.dist | 2 +- .github/workflows/test.yml | 2 +- composer.json | 4 ++-- docker-compose.yml | 4 ++-- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/.env.dist b/.env.dist index 063c3ec3..e1b749c2 100644 --- a/.env.dist +++ b/.env.dist @@ -1 +1 @@ -PHP_VERSION=7.4 +PHP_VERSION=8.3 diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 7d67d101..146e6518 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -20,7 +20,7 @@ jobs: strategy: fail-fast: false matrix: - php-versions: ['7.2', '7.3', '7.4', '8.0', '8.1', '8.2', '8.3'] + php-versions: ['7.4', '8.0', '8.1', '8.2', '8.3'] # TODO use cache steps: diff --git a/composer.json b/composer.json index 4337c483..735e5f07 100644 --- a/composer.json +++ b/composer.json @@ -1,5 +1,5 @@ { - "name": "cebe/yii2-openapi", + "name": "php-openapi/yii2-openapi", "description": "Generate full REST API application from OpenAPI 3 specification.", "keywords": ["yii2", "rest", "openapi"], "homepage": "https://github.com/cebe/yii2-openapi#readme", @@ -23,7 +23,7 @@ "yiisoft/yii2": "~2.0.48", "yiisoft/yii2-gii": "~2.0.0 | ~2.1.0 | ~2.2.0| ~2.3.0", "laminas/laminas-code": ">=3.4 <=4.13", - "insolita/yii2-fractal": "^1.0.0", + "php-openapi/yii2-fractal": "^1.0.0", "fakerphp/faker": "^1.9", "sam-it/yii2-mariadb": "^2.0" }, diff --git a/docker-compose.yml b/docker-compose.yml index 44e6492b..9b71bf9e 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,12 +1,12 @@ version: "3.5" services: php: - image: yii2-openapi-php:${PHP_VERSION:-7.4} + image: yii2-openapi-php:${PHP_VERSION:-8.3} build: dockerfile: tests/docker/Dockerfile context: . args: - - BUILD_PHP_VERSION=${PHP_VERSION:-7.4} + - BUILD_PHP_VERSION=${PHP_VERSION:-8.3} extra_hosts: # https://stackoverflow.com/a/67158212/1106908 - "host.docker.internal:host-gateway" volumes: From c489f22ecc12cfb77b3d329eeb238453d88848ce Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Thu, 30 May 2024 20:53:57 +0530 Subject: [PATCH 005/358] Design: WIP --- src/lib/generators/MigrationsGenerator.php | 14 +++++++------- .../132_create_migration_for_drop_table.yaml | 5 ++++- 2 files changed, 11 insertions(+), 8 deletions(-) diff --git a/src/lib/generators/MigrationsGenerator.php b/src/lib/generators/MigrationsGenerator.php index 309a91f3..07ec7081 100644 --- a/src/lib/generators/MigrationsGenerator.php +++ b/src/lib/generators/MigrationsGenerator.php @@ -114,16 +114,16 @@ public function buildMigrations():array // MySQL // MariaDB TODO // PgSQL TODO - $sql='SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES'; - $tables = Yii::$app->db - ->createCommand($sql) - ->queryAll(); - var_dump($tables); die; + // $sql='SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES'; + // $tables = Yii::$app->db + // ->createCommand($sql) + // ->queryAll(); + // var_dump($tables); die; - foreach ($this->models as $model) {var_dump($model->tableAlias);} + // foreach ($this->models as $model) {var_dump($model->tableAlias);} - var_dump(array_keys($this->models)); die; + // var_dump(array_keys($this->models)); die; foreach ($this->models as $model) { $migration = $this->createBuilder($model)->build(); diff --git a/tests/specs/issue_fix/132_create_migration_for_drop_table/132_create_migration_for_drop_table.yaml b/tests/specs/issue_fix/132_create_migration_for_drop_table/132_create_migration_for_drop_table.yaml index 23915a2f..9f5bb53e 100644 --- a/tests/specs/issue_fix/132_create_migration_for_drop_table/132_create_migration_for_drop_table.yaml +++ b/tests/specs/issue_fix/132_create_migration_for_drop_table/132_create_migration_for_drop_table.yaml @@ -2,6 +2,9 @@ openapi: "3.0.0" info: version: 1.0.0 title: 132_create_migration_for_drop_table \#132 +x-delete-tables: # don't use x-keep-table + - abc + - def paths: /: get: @@ -13,7 +16,7 @@ paths: components: schemas: - Pristine: + Pristine: # if you remove this entire schema and want to remove its table then you need to add its table name in `x-delete-tables` type: object description: 132_create_migration_for_drop_table required: From d4e0d887846a64ad7292c2905963a18bba7edc61 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Fri, 31 May 2024 17:17:27 +0530 Subject: [PATCH 006/358] WIP --- src/generator/ApiGenerator.php | 39 ++++++++++--------- src/lib/SchemaToDatabase.php | 2 +- src/lib/migrations/BaseMigrationBuilder.php | 3 +- src/lib/migrations/MysqlMigrationBuilder.php | 8 ++-- .../132_create_migration_for_drop_table.yaml | 21 ++-------- tests/unit/IssueFixTest.php | 2 +- 6 files changed, 34 insertions(+), 41 deletions(-) diff --git a/src/generator/ApiGenerator.php b/src/generator/ApiGenerator.php index f930f949..eca7aaf2 100644 --- a/src/generator/ApiGenerator.php +++ b/src/generator/ApiGenerator.php @@ -7,9 +7,9 @@ namespace cebe\yii2openapi\generator; -use yii\db\mysql\Schema as MySqlSchema; -use SamIT\Yii2\MariaDb\Schema as MariaDbSchema; -use yii\db\pgsql\Schema as PgSqlSchema; +use cebe\openapi\exceptions\IOException; +use cebe\openapi\exceptions\TypeErrorException; +use cebe\openapi\exceptions\UnresolvableReferenceException; use cebe\openapi\Reader; use cebe\openapi\spec\OpenApi; use cebe\yii2openapi\lib\Config; @@ -22,7 +22,10 @@ use cebe\yii2openapi\lib\generators\UrlRulesGenerator; use cebe\yii2openapi\lib\PathAutoCompletion; use cebe\yii2openapi\lib\SchemaToDatabase; +use Exception; use Yii; +use yii\db\mysql\Schema as MySqlSchema; +use yii\db\pgsql\Schema as PgSqlSchema; use yii\gii\CodeFile; use yii\gii\Generator; use yii\helpers\Html; @@ -176,7 +179,7 @@ class ApiGenerator extends Generator private $_openApiWithoutRef; /** - * @var \cebe\yii2openapi\lib\Config $config + * @var Config $config **/ private $config; @@ -283,11 +286,11 @@ public function rules() /** * @param $attribute - * @throws \cebe\openapi\exceptions\IOException - * @throws \cebe\openapi\exceptions\TypeErrorException - * @throws \cebe\openapi\exceptions\UnresolvableReferenceException + * @throws IOException + * @throws TypeErrorException + * @throws UnresolvableReferenceException */ - public function validateSpec($attribute):void + public function validateSpec($attribute): void { if ($this->ignoreSpecErrors) { return; @@ -299,7 +302,7 @@ public function validateSpec($attribute):void } } - public function validateUrlPrefixes($attribute):void + public function validateUrlPrefixes($attribute): void { if (empty($this->urlPrefixes)) { return; @@ -427,7 +430,7 @@ public function stickyAttributes() ); } - public function makeConfig():Config + public function makeConfig(): Config { if (!$this->config) { $props = get_object_vars($this); @@ -489,12 +492,12 @@ public function generate():array } /** - * @return \cebe\openapi\spec\OpenApi - * @throws \cebe\openapi\exceptions\IOException - * @throws \cebe\openapi\exceptions\TypeErrorException - * @throws \cebe\openapi\exceptions\UnresolvableReferenceException + * @return OpenApi + * @throws IOException + * @throws TypeErrorException + * @throws UnresolvableReferenceException */ - protected function getOpenApiWithoutReferences():OpenApi + protected function getOpenApiWithoutReferences(): OpenApi { if ($this->_openApiWithoutRef === null) { $file = Yii::getAlias($this->openApiPath); @@ -507,17 +510,17 @@ protected function getOpenApiWithoutReferences():OpenApi return $this->_openApiWithoutRef; } - public static function isPostgres():bool + public static function isPostgres(): bool { return Yii::$app->db->schema instanceof PgSqlSchema; } - public static function isMysql():bool + public static function isMysql(): bool { return (Yii::$app->db->schema instanceof MySqlSchema && !static::isMariaDb()); } - public static function isMariaDb():bool + public static function isMariaDb(): bool { return strpos(Yii::$app->db->schema->getServerVersion(), 'MariaDB') !== false; } diff --git a/src/lib/SchemaToDatabase.php b/src/lib/SchemaToDatabase.php index 5cdcb799..b5e74c26 100644 --- a/src/lib/SchemaToDatabase.php +++ b/src/lib/SchemaToDatabase.php @@ -50,7 +50,7 @@ * minLength: #(numeric value, can be applied for validation rules) * default: #(int|string, default value, used for database migration and model rules) * x-db-type: #(Custom database type like JSON, JSONB, CHAR, VARCHAR, UUID, etc ) - * x-faker: #(custom faker generator, for ex '$faker->gender') + * x-faker: #(custom faker generator, for ex '$faker->gender'; PHP code as string) * description: #(optional, used for comment) */ class SchemaToDatabase diff --git a/src/lib/migrations/BaseMigrationBuilder.php b/src/lib/migrations/BaseMigrationBuilder.php index d4c49c21..015e155b 100644 --- a/src/lib/migrations/BaseMigrationBuilder.php +++ b/src/lib/migrations/BaseMigrationBuilder.php @@ -201,6 +201,7 @@ function (string $unknownColumn) { $this->buildColumnsDrop($columnsForDrop); foreach ($columnsForChange as $commonColumn) { $current = $this->tableSchema->columns[$commonColumn]; + /** @var \cebe\yii2openapi\db\ColumnSchema|\yii\db\ColumnSchema $desired */ $desired = $this->newColumns[$commonColumn]; if ($current->isPrimaryKey || in_array($desired->dbType, ['pk', 'upk', 'bigpk', 'ubigpk'])) { // do not adjust existing primary keys @@ -432,7 +433,7 @@ public function tmpSaveNewCol(string $tableAlias, \cebe\yii2openapi\db\ColumnSch $name = MigrationRecordBuilder::quote($columnSchema->name); $column = [$name.' '.$this->newColStr($tmpTableName, $columnSchema)]; if (ApiGenerator::isPostgres() && static::isEnum($columnSchema)) { - $column = strtr($column, [$innerEnumTypeName => $tmpEnumName($columnSchema->name)]); + $column = strtr($column[0], [$innerEnumTypeName => $tmpEnumName($columnSchema->name)]); } } else { $column = [$columnSchema->name => $this->newColStr($tmpTableName, $columnSchema)]; diff --git a/src/lib/migrations/MysqlMigrationBuilder.php b/src/lib/migrations/MysqlMigrationBuilder.php index 42354df3..98598e44 100644 --- a/src/lib/migrations/MysqlMigrationBuilder.php +++ b/src/lib/migrations/MysqlMigrationBuilder.php @@ -45,7 +45,7 @@ protected function compareColumns(ColumnSchema $current, ColumnSchema $desired): $this->modifyDesired($desired); $this->modifyDesiredInContextOfCurrent($current, $desired); - // Why this is needed? Often manually created ColumnSchem instance have dbType 'varchar' with size 255 and ColumnSchema fetched from db have 'varchar(255)'. So varchar !== varchar(255). such normal mistake was leading to errors. So desired column is saved in temporary table and it is fetched from that temp. table and then compared with current ColumnSchema + // Why this is needed? Often manually created ColumnSchema instance have dbType 'varchar' with size 255 and ColumnSchema fetched from db have 'varchar(255)'. So varchar !== varchar(255). such normal mistake was leading to errors. So desired column is saved in temporary table and it is fetched from that temp. table and then compared with current ColumnSchema $desiredFromDb = $this->tmpSaveNewCol($tableAlias, $desired); $this->modifyDesiredInContextOfDesiredFromDb($desired, $desiredFromDb); @@ -121,6 +121,8 @@ public static function getColumnSchemaBuilderClass(): string return \yii\db\mysql\ColumnSchemaBuilder::class; } elseif (ApiGenerator::isMariaDb()) { return \SamIT\Yii2\MariaDb\ColumnSchemaBuilder::class; + } else { + throw new \Exception('Unknown database'); } } @@ -134,7 +136,7 @@ public function modifyCurrent(ColumnSchema $current): void public function modifyDesired(ColumnSchema $desired): void { - /** @var $desired cebe\yii2openapi\db\ColumnSchema|\yii\db\mysql\ColumnSchema */ + /** @var $desired \cebe\yii2openapi\db\ColumnSchema|\yii\db\mysql\ColumnSchema */ if ($desired->phpType === 'int' && $desired->defaultValue !== null) { $desired->defaultValue = (int)$desired->defaultValue; } @@ -148,7 +150,7 @@ public function modifyDesired(ColumnSchema $desired): void public function modifyDesiredInContextOfCurrent(ColumnSchema $current, ColumnSchema $desired): void { /** @var $current \yii\db\mysql\ColumnSchema */ - /** @var $desired cebe\yii2openapi\db\ColumnSchema|\yii\db\mysql\ColumnSchema */ + /** @var $desired \cebe\yii2openapi\db\ColumnSchema|\yii\db\mysql\ColumnSchema */ if ($current->dbType === 'tinyint(1)' && $desired->type === 'boolean') { if (is_bool($desired->defaultValue) || is_string($desired->defaultValue)) { $desired->defaultValue = (int)$desired->defaultValue; diff --git a/tests/specs/issue_fix/132_create_migration_for_drop_table/132_create_migration_for_drop_table.yaml b/tests/specs/issue_fix/132_create_migration_for_drop_table/132_create_migration_for_drop_table.yaml index 9f5bb53e..7acd5abc 100644 --- a/tests/specs/issue_fix/132_create_migration_for_drop_table/132_create_migration_for_drop_table.yaml +++ b/tests/specs/issue_fix/132_create_migration_for_drop_table/132_create_migration_for_drop_table.yaml @@ -2,9 +2,10 @@ openapi: "3.0.0" info: version: 1.0.0 title: 132_create_migration_for_drop_table \#132 + x-delete-tables: # don't use x-keep-table - - abc - - def + - itt_fruits + paths: /: get: @@ -16,21 +17,7 @@ paths: components: schemas: - Pristine: # if you remove this entire schema and want to remove its table then you need to add its table name in `x-delete-tables` - type: object - description: 132_create_migration_for_drop_table - required: - - id - properties: - id: - type: integer - billing_factor: - description: integer between 0 and 100, default value 100 - type: integer - default: 100 - nullable: false - x-faker: '$faker->numberBetween(0, 100)' - Foo: + Foo: # if you remove this entire schema and want to remove its table then you need to add its table name in `x-delete-tables` type: object description: 132_create_migration_for_drop_table required: diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index 6edc9dfa..44b3596b 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -282,7 +282,7 @@ public function testCreateMigrationForDropTable132() $testFile = Yii::getAlias("@specs/issue_fix/132_create_migration_for_drop_table/132_create_migration_for_drop_table.php"); $this->deleteTablesForNoSyntaxError107(); $this->createTableForNoSyntaxError107(); - $this->runGenerator($testFile, 'mysql'); + $this->runGenerator($testFile); // ... TODO $this->deleteTables(); } From be522312749dd31370d2db32fdf0ab3032ab2cff Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Fri, 31 May 2024 19:22:19 +0530 Subject: [PATCH 007/358] WIP --- src/generator/ApiGenerator.php | 12 +++++-- src/lib/generators/MigrationsGenerator.php | 36 +++++++++++++++++++-- src/lib/migrations/BaseMigrationBuilder.php | 7 +++- 3 files changed, 48 insertions(+), 7 deletions(-) diff --git a/src/generator/ApiGenerator.php b/src/generator/ApiGenerator.php index eca7aaf2..208c8dd0 100644 --- a/src/generator/ApiGenerator.php +++ b/src/generator/ApiGenerator.php @@ -460,11 +460,12 @@ public function makeConfig(): Config * Please refer to [[\yii\gii\generators\controller\Generator::generate()]] as an example * on how to implement this method. * @return CodeFile[] a list of code files to be created. - * @throws \Exception + * @throws Exception */ - public function generate():array + public function generate(): array { $config = $this->makeConfig(); + $actionsGenerator = $this->useJsonApi ? Yii::createObject(JsonActionGenerator::class, [$config]) : Yii::createObject(RestActionGenerator::class, [$config]); @@ -485,7 +486,12 @@ public function generate():array $modelsGenerator = Yii::createObject(ModelsGenerator::class, [$config, $models]); $files->merge($modelsGenerator->generate()); - $migrationsGenerator = Yii::createObject(MigrationsGenerator::class, [$config, $models, Yii::$app->db]); + $tablesToDrop = null; + if (isset($config->getOpenApi()->{'x-delete-tables'})) { + $tablesToDrop = $config->getOpenApi()->{'x-delete-tables'}; // for removed (components) schemas + } + + $migrationsGenerator = Yii::createObject(MigrationsGenerator::class, [$config, $models, Yii::$app->db, $tablesToDrop]); $files->merge($migrationsGenerator->generate()); return $files->all(); diff --git a/src/lib/generators/MigrationsGenerator.php b/src/lib/generators/MigrationsGenerator.php index 07ec7081..d1abbd9b 100644 --- a/src/lib/generators/MigrationsGenerator.php +++ b/src/lib/generators/MigrationsGenerator.php @@ -12,6 +12,7 @@ use cebe\yii2openapi\lib\items\DbModel; use cebe\yii2openapi\lib\items\MigrationModel; use cebe\yii2openapi\lib\migrations\BaseMigrationBuilder; +use cebe\yii2openapi\lib\migrations\MigrationRecordBuilder; use cebe\yii2openapi\lib\migrations\MysqlMigrationBuilder; use cebe\yii2openapi\lib\migrations\PostgresMigrationBuilder; use Exception; @@ -52,7 +53,9 @@ class MigrationsGenerator **/ protected $sorted; - public function __construct(Config $config, array $models, Connection $db) + public ?array $tablesToDrop = null; + + public function __construct(Config $config, array $models, Connection $db, array $tablesToDrop = null) { $this->config = $config; $this->models = array_filter($models, static function ($model) { @@ -60,6 +63,7 @@ public function __construct(Config $config, array $models, Connection $db) }); $this->files = new CodeFiles([]); $this->db = $db; + $this->tablesToDrop = $tablesToDrop; } /** @@ -126,6 +130,8 @@ public function buildMigrations():array // var_dump(array_keys($this->models)); die; foreach ($this->models as $model) { + /** @var DbModel $model */ + $migration = $this->createBuilder($model)->build(); if ($migration->notEmpty()) { $this->migrations[$model->tableAlias] = $migration; @@ -141,6 +147,30 @@ public function buildMigrations():array $junctions[] = $relation->viaTableName; } } + + // for deleted schema, create migration for drop table + foreach ($this->tablesToDrop as $tableName) { + $table = Yii::$app->db->schema->getTableSchema($tableName); + if ($table) { + + $dbModelHere = new DbModel([ + 'pkName' => $table->primaryKey, + 'name' => $table->name, + 'tableName' => $tableName, + ]); + $mm = new MigrationModel($dbModelHere); + $builder = new MigrationRecordBuilder($this->db->getSchema()); + $mm->addUpCode($builder->dropTable($tableName)) + ->addDownCode($builder->createTable($tableName, $table->columns)) + ; + if ($mm->notEmpty()) { + var_dump('$this->migrations'); die; + $this->migrations[$tableName] = $mm; + } + } + } + + return !empty($this->migrations) ? $this->sortMigrationsByDeps() : []; } @@ -150,9 +180,9 @@ public function buildMigrations():array protected function createBuilder(DbModel $model):BaseMigrationBuilder { if ($this->db->getDriverName() === 'pgsql') { - return Yii::createObject(PostgresMigrationBuilder::class, [$this->db, $model]); + return Yii::createObject(PostgresMigrationBuilder::class, [$this->db, $model, $this->tablesToDrop]); } - return Yii::createObject(MysqlMigrationBuilder::class, [$this->db, $model]); + return Yii::createObject(MysqlMigrationBuilder::class, [$this->db, $model, $this->tablesToDrop]); } /** diff --git a/src/lib/migrations/BaseMigrationBuilder.php b/src/lib/migrations/BaseMigrationBuilder.php index 015e155b..48572904 100644 --- a/src/lib/migrations/BaseMigrationBuilder.php +++ b/src/lib/migrations/BaseMigrationBuilder.php @@ -52,6 +52,8 @@ abstract class BaseMigrationBuilder */ protected $recordBuilder; + public ?array $tablesToDrop = null; + /** * MigrationBuilder constructor. * @param \yii\db\Connection $db @@ -59,12 +61,13 @@ abstract class BaseMigrationBuilder * @throws \yii\base\InvalidConfigException * @throws \yii\base\NotSupportedException */ - public function __construct(Connection $db, DbModel $model) + public function __construct(Connection $db, DbModel $model, ?array $tablesToDrop = null) { $this->db = $db; $this->model = $model; $this->tableSchema = $db->getTableSchema($model->getTableAlias(), true); $this->recordBuilder = Yii::createObject(MigrationRecordBuilder::class, [$db->getSchema()]); + $this->tablesToDrop = $tablesToDrop; } /** @@ -113,6 +116,7 @@ public function buildJunction(ManyToManyRelation $relation):MigrationModel */ public function buildFresh():MigrationModel { +// var_dump('in 2'); die; $this->migration = Yii::createObject(MigrationModel::class, [$this->model, true, null, []]); $this->newColumns = $this->model->attributesToColumnSchema(); if (empty($this->newColumns)) { @@ -221,6 +225,7 @@ function (string $unknownColumn) { } else { $this->buildRelations(); } + return $this->migration; } From 6c7e792a776896032be639b81c9af775f794ae50 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Tue, 4 Jun 2024 19:39:15 +0530 Subject: [PATCH 008/358] WIP --- src/generator/ApiGenerator.php | 7 +------ src/lib/SchemaToDatabase.php | 10 ++++++++++ src/lib/generators/MigrationsGenerator.php | 5 ++--- src/lib/items/DbModel.php | 6 ++++++ .../132_create_migration_for_drop_table.yaml | 5 +++-- 5 files changed, 22 insertions(+), 11 deletions(-) diff --git a/src/generator/ApiGenerator.php b/src/generator/ApiGenerator.php index 208c8dd0..770aa9c6 100644 --- a/src/generator/ApiGenerator.php +++ b/src/generator/ApiGenerator.php @@ -486,12 +486,7 @@ public function generate(): array $modelsGenerator = Yii::createObject(ModelsGenerator::class, [$config, $models]); $files->merge($modelsGenerator->generate()); - $tablesToDrop = null; - if (isset($config->getOpenApi()->{'x-delete-tables'})) { - $tablesToDrop = $config->getOpenApi()->{'x-delete-tables'}; // for removed (components) schemas - } - - $migrationsGenerator = Yii::createObject(MigrationsGenerator::class, [$config, $models, Yii::$app->db, $tablesToDrop]); + $migrationsGenerator = Yii::createObject(MigrationsGenerator::class, [$config, $models, Yii::$app->db/*, $tablesToDrop*/]); $files->merge($migrationsGenerator->generate()); return $files->all(); diff --git a/src/lib/SchemaToDatabase.php b/src/lib/SchemaToDatabase.php index b5e74c26..abe33cdf 100644 --- a/src/lib/SchemaToDatabase.php +++ b/src/lib/SchemaToDatabase.php @@ -92,6 +92,16 @@ public function prepareModels():array $resolver = Yii::createObject(AttributeResolver::class, [$schemaName, $schema, $junctions, $this->config]); $models[$schemaName] = $resolver->resolve(); } + + // for drop table/schema https://github.com/cebe/yii2-openapi/issues/132 + $tablesToDrop = null; + if (isset($this->config->getOpenApi()->{'x-delete-tables'})) { + $tablesToDrop = $this->config->getOpenApi()->{'x-delete-tables'}; // for removed (components) schemas + } + foreach ($tablesToDrop as $table) { + + } + foreach ($models as $model) { foreach ($model->many2many as $relation) { if (isset($models[$relation->viaModelName])) { diff --git a/src/lib/generators/MigrationsGenerator.php b/src/lib/generators/MigrationsGenerator.php index d1abbd9b..f14a2654 100644 --- a/src/lib/generators/MigrationsGenerator.php +++ b/src/lib/generators/MigrationsGenerator.php @@ -161,16 +161,15 @@ public function buildMigrations():array $mm = new MigrationModel($dbModelHere); $builder = new MigrationRecordBuilder($this->db->getSchema()); $mm->addUpCode($builder->dropTable($tableName)) - ->addDownCode($builder->createTable($tableName, $table->columns)) + ->addDownCode($builder->dropTable($tableName)) ; if ($mm->notEmpty()) { - var_dump('$this->migrations'); die; +// var_dump('$this->migrations'); die; $this->migrations[$tableName] = $mm; } } } - return !empty($this->migrations) ? $this->sortMigrationsByDeps() : []; } diff --git a/src/lib/items/DbModel.php b/src/lib/items/DbModel.php index 4f174370..2de1697c 100644 --- a/src/lib/items/DbModel.php +++ b/src/lib/items/DbModel.php @@ -76,6 +76,12 @@ class DbModel extends BaseObject public $isNotDb = false; + /** + * @var bool + * Drop table if schema is removed. Also see `x-delete-tables` + */ + public $drop = false; + public function getTableAlias():string { return '{{%' . $this->tableName . '}}'; diff --git a/tests/specs/issue_fix/132_create_migration_for_drop_table/132_create_migration_for_drop_table.yaml b/tests/specs/issue_fix/132_create_migration_for_drop_table/132_create_migration_for_drop_table.yaml index 7acd5abc..ac8cc41b 100644 --- a/tests/specs/issue_fix/132_create_migration_for_drop_table/132_create_migration_for_drop_table.yaml +++ b/tests/specs/issue_fix/132_create_migration_for_drop_table/132_create_migration_for_drop_table.yaml @@ -3,8 +3,9 @@ info: version: 1.0.0 title: 132_create_migration_for_drop_table \#132 -x-delete-tables: # don't use x-keep-table - - itt_fruits +x-deleted-schemas: # don't use x-keep-table, x-delete-tables + - Fruit # itt_fruits + - Mango: the_mango # custom table name; `x-table` paths: /: From 16862ad6d398cff1cc990ea13c233697972792e5 Mon Sep 17 00:00:00 2001 From: Carsten Brandt Date: Wed, 5 Jun 2024 08:12:33 +0200 Subject: [PATCH 009/358] Update README.md --- README.md | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 711b2a1c..1cd2090b 100644 --- a/README.md +++ b/README.md @@ -4,17 +4,17 @@ REST API application generator for Yii2, openapi 3.0 YAML -> Yii2. Base on [Gii, the Yii Framework Code Generator](https://www.yiiframework.com/extension/yiisoft/yii2-gii). -[![Latest Stable Version](https://poser.pugx.org/cebe/yii2-openapi/v/stable)](https://packagist.org/packages/cebe/yii2-openapi) -[![Latest Alpha Version](https://poser.pugx.org/cebe/yii2-openapi/v/unstable)](https://packagist.org/packages/cebe/yii2-openapi) -[![Total Downloads](https://poser.pugx.org/cebe/yii2-openapi/downloads)](https://packagist.org/packages/cebe/yii2-openapi) -[![License](https://poser.pugx.org/cebe/yii2-openapi/license)](https://packagist.org/packages/cebe/yii2-openapi) -![yii2-openapi](https://github.com/cebe/yii2-openapi/workflows/yii2-openapi/badge.svg?branch=wip) +[![Latest Stable Version](https://poser.pugx.org/php-openapi/yii2-openapi/v/stable)](https://packagist.org/packages/php-openapi/yii2-openapi) +[![Latest Alpha Version](https://poser.pugx.org/php-openapi/yii2-openapi/v/unstable)](https://packagist.org/packages/php-openapi/yii2-openapi) +[![Total Downloads](https://poser.pugx.org/php-openapi/yii2-openapi/downloads)](https://packagist.org/packages/php-openapi/yii2-openapi) +[![License](https://poser.pugx.org/php-openapi/yii2-openapi/license)](https://packagist.org/packages/php-openapi/yii2-openapi) +![yii2-openapi](https://github.com/php-openapi/yii2-openapi/workflows/yii2-openapi/badge.svg?branch=wip) ## TLDR; what is this? A code generator for OpenAPI and Yii Framework based PHP API application. -Input: [OpenAPI 3.0 YAML or JSON](https://github.com/OAI/OpenAPI-Specification#the-openapi-specification) (via [cebe/php-openapi](https://github.com/cebe/php-openapi)) +Input: [OpenAPI 3.0 YAML or JSON](https://github.com/OAI/OpenAPI-Specification#the-openapi-specification) (via [cebe/php-openapi](https://github.com/php-openapi/php-openapi)) Output: Yii Framework Application with Controllers, Models, database schema @@ -36,12 +36,12 @@ Currently available features: ## Install - composer require cebe/yii2-openapi:^2.0@beta + composer require php-openapi/yii2-openapi:^2.0@beta ## Usage You can use this package in your existing application or start a new project using the -[yii2-app-api](https://github.com/cebe/yii2-app-api) application template. +[yii2-app-api](https://github.com/php-openapi/yii2-app-api) application template. For usage of the template, see instructions in the template repo readme. In your existing Yii application config (works for console as well as web): @@ -76,7 +76,7 @@ return $config; To use the web generator, open `index.php?r=gii` and select the `REST API Generator`. -On console you can run the generator with `./yii gii/api --openApiPath=@app/openapi.yaml`. Where `@app/openapi.yaml` should be the absolute path to your OpenAPI spec file. This can be JSON as well as YAML (see also [cebe/php-openapi](https://github.com/cebe/php-openapi/) for supported formats). +On console you can run the generator with `./yii gii/api --openApiPath=@app/openapi.yaml`. Where `@app/openapi.yaml` should be the absolute path to your OpenAPI spec file. This can be JSON as well as YAML (see also [php-openapi/php-openapi](https://github.com/php-openapi/php-openapi/) for supported formats). Run `./yii gii/api --help` for all options. Example: Disable generation of migrations files `./yii gii/api --generateMigrations=0` From 8d047c547b4f3d186686a4455e7a5c629592b0e6 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Wed, 12 Jun 2024 21:10:55 +0530 Subject: [PATCH 010/358] Create attributes from column schemas and more - WIP --- src/db/ColumnSchema.php | 8 ++ src/lib/SchemaToDatabase.php | 83 ++++++++++++++++--- src/lib/generators/MigrationsGenerator.php | 4 +- src/lib/items/DbModel.php | 4 +- src/lib/openapi/ComponentSchema.php | 3 +- .../132_create_migration_for_drop_table.yaml | 8 +- 6 files changed, 91 insertions(+), 19 deletions(-) diff --git a/src/db/ColumnSchema.php b/src/db/ColumnSchema.php index 71127a24..e8e8092b 100644 --- a/src/db/ColumnSchema.php +++ b/src/db/ColumnSchema.php @@ -25,4 +25,12 @@ class ColumnSchema extends \yii\db\ColumnSchema * ``` */ public $xDbType; + + public function toAttribute(): \cebe\yii2openapi\lib\items\Attribute + { + return new Attribute('id', [ + 'phpType' => 'int', + 'dbType' => 'pk' // TODO resume from here + ]); + } } diff --git a/src/lib/SchemaToDatabase.php b/src/lib/SchemaToDatabase.php index abe33cdf..55147714 100644 --- a/src/lib/SchemaToDatabase.php +++ b/src/lib/SchemaToDatabase.php @@ -7,11 +7,14 @@ namespace cebe\yii2openapi\lib; +use cebe\yii2openapi\lib\items\DbModel; use cebe\yii2openapi\lib\items\JunctionSchemas; +use cebe\yii2openapi\lib\items\MigrationModel; +use cebe\yii2openapi\lib\migrations\MigrationRecordBuilder; use cebe\yii2openapi\lib\openapi\ComponentSchema; use Yii; use yii\base\Exception; -use yii\helpers\StringHelper; +use yii\helpers\{StringHelper, ArrayHelper, Inflector}; use function count; /** @@ -93,15 +96,6 @@ public function prepareModels():array $models[$schemaName] = $resolver->resolve(); } - // for drop table/schema https://github.com/cebe/yii2-openapi/issues/132 - $tablesToDrop = null; - if (isset($this->config->getOpenApi()->{'x-delete-tables'})) { - $tablesToDrop = $this->config->getOpenApi()->{'x-delete-tables'}; // for removed (components) schemas - } - foreach ($tablesToDrop as $table) { - - } - foreach ($models as $model) { foreach ($model->many2many as $relation) { if (isset($models[$relation->viaModelName])) { @@ -114,7 +108,15 @@ public function prepareModels():array // TODO generate inverse relations - return $models; + // for drop table/schema https://github.com/cebe/yii2-openapi/issues/132 + $tablesToDrop = $modelsToDrop = []; + if (isset($this->config->getOpenApi()->{'x-deleted-schemas'})) { + $tablesToDrop = $this->config->getOpenApi()->{'x-deleted-schemas'}; // for removed (components) schemas + $modelsToDrop = static::f7($tablesToDrop); + + } + + return ArrayHelper::merge($models, $modelsToDrop); } /** @@ -233,4 +235,63 @@ private function canGenerateModel(string $schemaName, ComponentSchema $schema):b } return true; } + + /** + * @param array $schemasToDrop. Example: + * ``` + * array(2) { + * [0]=> + * string(5) "Fruit" + * [1]=> + * array(1) { + * ["Mango"]=> + * string(10) "the_mango_table_name" + * } + * } + * ``` + * @return DbModel[] + */ + public static function f7(array $schemasToDrop): array // TODO rename + { + $dbModelsToDrop = []; + foreach ($schemasToDrop as $key => $value) { + if (is_string($value)) { // schema name + $schemaName = $value; + $tableName = static::resolveTableNameHere($schemaName); + } elseif (is_array($value)) { + $schemaName = array_key_first($value); + $tableName = $value[$schemaName]; + } else { + throw new \Exception('Malformed list of schemas to delete'); + } + + $table = Yii::$app->db->schema->getTableSchema("{{%$tableName}}"); + if ($table) { + $dbModelHere = new DbModel([ + 'pkName' => $table->primaryKey[0], + 'name' => $schemaName, + 'tableName' => $tableName, + 'attributes' => [], + 'drop' => true + ]); + $mm = new MigrationModel($dbModelHere); + // $builder = new MigrationRecordBuilder($this->db->getSchema()); + // $mm->addUpCode($builder->dropTable($tableName)) + // ->addDownCode($builder->dropTable($tableName)) + // ; + // if ($mm->notEmpty()) { + // var_dump('$this->migrations'); die; + // $this->migrations[$tableName] = $mm; + // } + } + + } + return $dbModelsToDrop; + + } + + public static function resolveTableNameHere(string $schemaName):string // TODO rename + { + return Inflector::camel2id(StringHelper::basename(Inflector::pluralize($schemaName)), '_'); + } } diff --git a/src/lib/generators/MigrationsGenerator.php b/src/lib/generators/MigrationsGenerator.php index f14a2654..25e53dc3 100644 --- a/src/lib/generators/MigrationsGenerator.php +++ b/src/lib/generators/MigrationsGenerator.php @@ -53,9 +53,9 @@ class MigrationsGenerator **/ protected $sorted; - public ?array $tablesToDrop = null; + public array $tablesToDrop = []; - public function __construct(Config $config, array $models, Connection $db, array $tablesToDrop = null) + public function __construct(Config $config, array $models, Connection $db, array $tablesToDrop = []) { $this->config = $config; $this->models = array_filter($models, static function ($model) { diff --git a/src/lib/items/DbModel.php b/src/lib/items/DbModel.php index 2de1697c..5473f70b 100644 --- a/src/lib/items/DbModel.php +++ b/src/lib/items/DbModel.php @@ -78,7 +78,9 @@ class DbModel extends BaseObject /** * @var bool - * Drop table if schema is removed. Also see `x-delete-tables` + * Drop table if schema is removed. + * @see `x-deleted-schemas` in README.md + * @see https://github.com/cebe/yii2-openapi/issues/132 */ public $drop = false; diff --git a/src/lib/openapi/ComponentSchema.php b/src/lib/openapi/ComponentSchema.php index 1fc9f92f..b1293f90 100644 --- a/src/lib/openapi/ComponentSchema.php +++ b/src/lib/openapi/ComponentSchema.php @@ -11,6 +11,7 @@ use cebe\openapi\spec\Reference; use cebe\openapi\SpecObjectInterface; use cebe\yii2openapi\lib\CustomSpecAttr; +use cebe\yii2openapi\lib\SchemaToDatabase; use Generator; use Yii; use yii\helpers\Inflector; @@ -111,7 +112,7 @@ public function isNonDb():bool public function resolveTableName(string $schemaName):string { return $this->schema->{CustomSpecAttr::TABLE} ?? - Inflector::camel2id(StringHelper::basename(Inflector::pluralize($schemaName)), '_'); + SchemaToDatabase::resolveTableNameHere($schemaName); } public function hasCustomTableName():bool diff --git a/tests/specs/issue_fix/132_create_migration_for_drop_table/132_create_migration_for_drop_table.yaml b/tests/specs/issue_fix/132_create_migration_for_drop_table/132_create_migration_for_drop_table.yaml index ac8cc41b..24215d48 100644 --- a/tests/specs/issue_fix/132_create_migration_for_drop_table/132_create_migration_for_drop_table.yaml +++ b/tests/specs/issue_fix/132_create_migration_for_drop_table/132_create_migration_for_drop_table.yaml @@ -3,9 +3,9 @@ info: version: 1.0.0 title: 132_create_migration_for_drop_table \#132 -x-deleted-schemas: # don't use x-keep-table, x-delete-tables - - Fruit # itt_fruits - - Mango: the_mango # custom table name; `x-table` +x-deleted-schemas: # don't use x-keep-table, use x-deleted-schemas + - Fruit # table name evaluated to `itt_fruits`. `itt_` is prefix + - Mango: the_mango7 # custom table name; `x-table` paths: /: @@ -18,7 +18,7 @@ paths: components: schemas: - Foo: # if you remove this entire schema and want to remove its table then you need to add its table name in `x-delete-tables` + Foo: # if you remove this entire schema and want to remove its table then you need to add its table name in `x-deleted-schemas` type: object description: 132_create_migration_for_drop_table required: From 9d901c9fa5cb7a18e255d3d0da9bc87de50e3f20 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Thu, 13 Jun 2024 16:40:37 +0530 Subject: [PATCH 011/358] Create delete file (migration) containing important DB statements for drop table --- src/db/ColumnSchema.php | 8 ---- src/generator/ApiGenerator.php | 2 +- src/lib/SchemaToDatabase.php | 31 ++++++++++++-- src/lib/generators/MigrationsGenerator.php | 40 +++++++++---------- src/lib/items/Attribute.php | 4 +- src/lib/items/MigrationModel.php | 17 +++++--- src/lib/migrations/BaseMigrationBuilder.php | 16 +++++++- .../132_create_migration_for_drop_table.yaml | 2 +- 8 files changed, 78 insertions(+), 42 deletions(-) diff --git a/src/db/ColumnSchema.php b/src/db/ColumnSchema.php index e8e8092b..71127a24 100644 --- a/src/db/ColumnSchema.php +++ b/src/db/ColumnSchema.php @@ -25,12 +25,4 @@ class ColumnSchema extends \yii\db\ColumnSchema * ``` */ public $xDbType; - - public function toAttribute(): \cebe\yii2openapi\lib\items\Attribute - { - return new Attribute('id', [ - 'phpType' => 'int', - 'dbType' => 'pk' // TODO resume from here - ]); - } } diff --git a/src/generator/ApiGenerator.php b/src/generator/ApiGenerator.php index 770aa9c6..0ea57fb1 100644 --- a/src/generator/ApiGenerator.php +++ b/src/generator/ApiGenerator.php @@ -486,7 +486,7 @@ public function generate(): array $modelsGenerator = Yii::createObject(ModelsGenerator::class, [$config, $models]); $files->merge($modelsGenerator->generate()); - $migrationsGenerator = Yii::createObject(MigrationsGenerator::class, [$config, $models, Yii::$app->db/*, $tablesToDrop*/]); + $migrationsGenerator = Yii::createObject(MigrationsGenerator::class, [$config, $models, Yii::$app->db]); $files->merge($migrationsGenerator->generate()); return $files->all(); diff --git a/src/lib/SchemaToDatabase.php b/src/lib/SchemaToDatabase.php index 55147714..dd9eea3e 100644 --- a/src/lib/SchemaToDatabase.php +++ b/src/lib/SchemaToDatabase.php @@ -7,6 +7,7 @@ namespace cebe\yii2openapi\lib; +use cebe\yii2openapi\lib\items\Attribute; use cebe\yii2openapi\lib\items\DbModel; use cebe\yii2openapi\lib\items\JunctionSchemas; use cebe\yii2openapi\lib\items\MigrationModel; @@ -113,7 +114,6 @@ public function prepareModels():array if (isset($this->config->getOpenApi()->{'x-deleted-schemas'})) { $tablesToDrop = $this->config->getOpenApi()->{'x-deleted-schemas'}; // for removed (components) schemas $modelsToDrop = static::f7($tablesToDrop); - } return ArrayHelper::merge($models, $modelsToDrop); @@ -271,10 +271,11 @@ public static function f7(array $schemasToDrop): array // TODO rename 'pkName' => $table->primaryKey[0], 'name' => $schemaName, 'tableName' => $tableName, - 'attributes' => [], + 'attributes' => static::attributesFromColumnSchemas($table->columns), 'drop' => true ]); - $mm = new MigrationModel($dbModelHere); + $dbModelsToDrop[$key] = $dbModelHere; +// $mm = new MigrationModel($dbModelHere); // $builder = new MigrationRecordBuilder($this->db->getSchema()); // $mm->addUpCode($builder->dropTable($tableName)) // ->addDownCode($builder->dropTable($tableName)) @@ -294,4 +295,28 @@ public static function resolveTableNameHere(string $schemaName):string // TODO r { return Inflector::camel2id(StringHelper::basename(Inflector::pluralize($schemaName)), '_'); } + + /** + * @return Attribute[] + */ + public static function attributesFromColumnSchemas(array $columnSchemas) + { + $attributes = []; + foreach ($columnSchemas as $columnName => $schema) { + /** @var $columnName string */ + /** @var $schema \yii\db\ColumnSchema */ + unset($attribute); + $attribute = new Attribute($schema->name, [ + 'phpType' => $schema->phpType, + 'dbType' => $schema->dbType, + 'nullable' => $schema->allowNull, + 'size' => $schema->size, + // 'limits' => ['min' => null, 'max' => null, 'minLength' => null], // TODO + 'primary' => $schema->isPrimaryKey, + 'enumValues' => $schema->enumValues, + ]); + $attributes[] = $attribute; + } + return $attributes; + } } diff --git a/src/lib/generators/MigrationsGenerator.php b/src/lib/generators/MigrationsGenerator.php index 25e53dc3..c98980bb 100644 --- a/src/lib/generators/MigrationsGenerator.php +++ b/src/lib/generators/MigrationsGenerator.php @@ -149,26 +149,26 @@ public function buildMigrations():array } // for deleted schema, create migration for drop table - foreach ($this->tablesToDrop as $tableName) { - $table = Yii::$app->db->schema->getTableSchema($tableName); - if ($table) { - - $dbModelHere = new DbModel([ - 'pkName' => $table->primaryKey, - 'name' => $table->name, - 'tableName' => $tableName, - ]); - $mm = new MigrationModel($dbModelHere); - $builder = new MigrationRecordBuilder($this->db->getSchema()); - $mm->addUpCode($builder->dropTable($tableName)) - ->addDownCode($builder->dropTable($tableName)) - ; - if ($mm->notEmpty()) { -// var_dump('$this->migrations'); die; - $this->migrations[$tableName] = $mm; - } - } - } +// foreach ($this->tablesToDrop as $tableName) { +// $table = Yii::$app->db->schema->getTableSchema($tableName); +// if ($table) { +// +// $dbModelHere = new DbModel([ +// 'pkName' => $table->primaryKey, +// 'name' => $table->name, +// 'tableName' => $tableName, +// ]); +// $mm = new MigrationModel($dbModelHere); +// $builder = new MigrationRecordBuilder($this->db->getSchema()); +// $mm->addUpCode($builder->dropTable($tableName)) +// ->addDownCode($builder->dropTable($tableName)) +// ; +// if ($mm->notEmpty()) { +//// var_dump('$this->migrations'); die; +// $this->migrations[$tableName] = $mm; +// } +// } +// } return !empty($this->migrations) ? $this->sortMigrationsByDeps() : []; } diff --git a/src/lib/items/Attribute.php b/src/lib/items/Attribute.php index 5563162d..f867b3f7 100644 --- a/src/lib/items/Attribute.php +++ b/src/lib/items/Attribute.php @@ -53,8 +53,8 @@ class Attribute extends BaseObject /** * @var string * Contains foreign key column name - * @example 'redelivery_of' - * See usage docs in README for more info + * @example 'redelivery_of' instead of 'redelivery_of_id' + * @see `x-fk-column-name` in README.md */ public $fkColName; diff --git a/src/lib/items/MigrationModel.php b/src/lib/items/MigrationModel.php index 2f4bcdb6..7f5f6314 100644 --- a/src/lib/items/MigrationModel.php +++ b/src/lib/items/MigrationModel.php @@ -62,13 +62,18 @@ public function __construct(DbModel $model, bool $isFresh = true, ManyToManyRela $this->model = $model; $this->relation = $relation; if ($relation === null) { - $this->fileName = $isFresh - ? 'create_table_' . $model->tableName - : 'change_table_' . $model->tableName; + $this->fileName = $model->drop ? + 'delete_table_' . $model->tableName : + ($isFresh + ? 'create_table_' . $model->tableName + : 'change_table_' . $model->tableName); } else { - $this->fileName = $isFresh - ? 'create_table_' . $relation->viaTableName - : 'change_table_' . $relation->viaTableName; + $this->fileName = + $model->drop ? + 'delete_table_' . $relation->viaTableName : + ($isFresh + ? 'create_table_' . $relation->viaTableName + : 'change_table_' . $relation->viaTableName); } } diff --git a/src/lib/migrations/BaseMigrationBuilder.php b/src/lib/migrations/BaseMigrationBuilder.php index 48572904..5920dd30 100644 --- a/src/lib/migrations/BaseMigrationBuilder.php +++ b/src/lib/migrations/BaseMigrationBuilder.php @@ -116,7 +116,6 @@ public function buildJunction(ManyToManyRelation $relation):MigrationModel */ public function buildFresh():MigrationModel { -// var_dump('in 2'); die; $this->migration = Yii::createObject(MigrationModel::class, [$this->model, true, null, []]); $this->newColumns = $this->model->attributesToColumnSchema(); if (empty($this->newColumns)) { @@ -175,6 +174,7 @@ public function buildSecondary(?ManyToManyRelation $relation = null):MigrationMo { $this->migration = Yii::createObject(MigrationModel::class, [$this->model, false, $relation, []]); $this->newColumns = $relation->columnSchema ?? $this->model->attributesToColumnSchema(); + $this->newColumns = $this->model->drop ? [] : $this->newColumns; // TODO refactor $wantNames = array_keys($this->newColumns); $haveNames = $this->tableSchema->columnNames; $columnsForCreate = array_map( @@ -226,6 +226,8 @@ function (string $unknownColumn) { $this->buildRelations(); } + $this->buildTablesDrop(); + return $this->migration; } @@ -253,6 +255,9 @@ protected function buildColumnsCreation(array $columns):void */ protected function buildColumnsDrop(array $columns):void { + if ($this->model->drop) { + return; + } foreach ($columns as $column) { $tableName = $this->model->getTableAlias(); if ($column->isPrimaryKey && !$column->autoIncrement) { @@ -580,4 +585,13 @@ public function modifyDesiredInContextOfDesiredFromDb(ColumnSchema $desired, Col } $desired->dbType = $desiredFromDb->dbType; } + + public function buildTablesDrop(): void + { + if (!$this->model->drop) { + return; + } + $this->migration->addUpCode($this->recordBuilder->dropTable($this->model->tableName) ) + ->addDownCode($this->recordBuilder->createTable($this->model->tableName, $this->model->attributesToColumnSchema())); + } } diff --git a/tests/specs/issue_fix/132_create_migration_for_drop_table/132_create_migration_for_drop_table.yaml b/tests/specs/issue_fix/132_create_migration_for_drop_table/132_create_migration_for_drop_table.yaml index 24215d48..84edb4f3 100644 --- a/tests/specs/issue_fix/132_create_migration_for_drop_table/132_create_migration_for_drop_table.yaml +++ b/tests/specs/issue_fix/132_create_migration_for_drop_table/132_create_migration_for_drop_table.yaml @@ -5,7 +5,7 @@ info: x-deleted-schemas: # don't use x-keep-table, use x-deleted-schemas - Fruit # table name evaluated to `itt_fruits`. `itt_` is prefix - - Mango: the_mango7 # custom table name; `x-table` +# - Mango: the_mango7 # custom table name; `x-table` paths: /: From 6427a61d90fc46e3583ab2e6c23e4e054f8b83e7 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Thu, 13 Jun 2024 16:46:17 +0530 Subject: [PATCH 012/358] Cleanup --- README.md | 1 - src/lib/generators/MigrationsGenerator.php | 23 +++------------------ src/lib/migrations/BaseMigrationBuilder.php | 9 +++----- 3 files changed, 6 insertions(+), 27 deletions(-) diff --git a/README.md b/README.md index 25c774b0..3cfe6173 100644 --- a/README.md +++ b/README.md @@ -592,7 +592,6 @@ find the diff create drop table mig diff tables -consider `x-keep-table` diff --git a/src/lib/generators/MigrationsGenerator.php b/src/lib/generators/MigrationsGenerator.php index c98980bb..cf977a20 100644 --- a/src/lib/generators/MigrationsGenerator.php +++ b/src/lib/generators/MigrationsGenerator.php @@ -53,9 +53,7 @@ class MigrationsGenerator **/ protected $sorted; - public array $tablesToDrop = []; - - public function __construct(Config $config, array $models, Connection $db, array $tablesToDrop = []) + public function __construct(Config $config, array $models, Connection $db) { $this->config = $config; $this->models = array_filter($models, static function ($model) { @@ -63,7 +61,6 @@ public function __construct(Config $config, array $models, Connection $db, array }); $this->files = new CodeFiles([]); $this->db = $db; - $this->tablesToDrop = $tablesToDrop; } /** @@ -115,20 +112,6 @@ public function buildMigrations():array { $junctions = []; - // MySQL - // MariaDB TODO - // PgSQL TODO - // $sql='SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES'; - // $tables = Yii::$app->db - // ->createCommand($sql) - // ->queryAll(); - // var_dump($tables); die; - - - // foreach ($this->models as $model) {var_dump($model->tableAlias);} - - // var_dump(array_keys($this->models)); die; - foreach ($this->models as $model) { /** @var DbModel $model */ @@ -179,9 +162,9 @@ public function buildMigrations():array protected function createBuilder(DbModel $model):BaseMigrationBuilder { if ($this->db->getDriverName() === 'pgsql') { - return Yii::createObject(PostgresMigrationBuilder::class, [$this->db, $model, $this->tablesToDrop]); + return Yii::createObject(PostgresMigrationBuilder::class, [$this->db, $model]); } - return Yii::createObject(MysqlMigrationBuilder::class, [$this->db, $model, $this->tablesToDrop]); + return Yii::createObject(MysqlMigrationBuilder::class, [$this->db, $model]); } /** diff --git a/src/lib/migrations/BaseMigrationBuilder.php b/src/lib/migrations/BaseMigrationBuilder.php index 5920dd30..3031bb1b 100644 --- a/src/lib/migrations/BaseMigrationBuilder.php +++ b/src/lib/migrations/BaseMigrationBuilder.php @@ -52,8 +52,6 @@ abstract class BaseMigrationBuilder */ protected $recordBuilder; - public ?array $tablesToDrop = null; - /** * MigrationBuilder constructor. * @param \yii\db\Connection $db @@ -61,13 +59,12 @@ abstract class BaseMigrationBuilder * @throws \yii\base\InvalidConfigException * @throws \yii\base\NotSupportedException */ - public function __construct(Connection $db, DbModel $model, ?array $tablesToDrop = null) + public function __construct(Connection $db, DbModel $model) { $this->db = $db; $this->model = $model; $this->tableSchema = $db->getTableSchema($model->getTableAlias(), true); $this->recordBuilder = Yii::createObject(MigrationRecordBuilder::class, [$db->getSchema()]); - $this->tablesToDrop = $tablesToDrop; } /** @@ -591,7 +588,7 @@ public function buildTablesDrop(): void if (!$this->model->drop) { return; } - $this->migration->addUpCode($this->recordBuilder->dropTable($this->model->tableName) ) - ->addDownCode($this->recordBuilder->createTable($this->model->tableName, $this->model->attributesToColumnSchema())); + $this->migration->addUpCode($this->recordBuilder->dropTable($this->model->getTableAlias()) ) + ->addDownCode($this->recordBuilder->createTable($this->model->getTableAlias(), $this->model->attributesToColumnSchema())); } } From aa9ca7135c78c6fc36414e908ea08be3dcd871b9 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Thu, 13 Jun 2024 16:46:44 +0530 Subject: [PATCH 013/358] Fix style --- src/lib/SchemaToDatabase.php | 6 +++--- src/lib/generators/MigrationsGenerator.php | 2 +- src/lib/migrations/BaseMigrationBuilder.php | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/lib/SchemaToDatabase.php b/src/lib/SchemaToDatabase.php index dd9eea3e..923a78e1 100644 --- a/src/lib/SchemaToDatabase.php +++ b/src/lib/SchemaToDatabase.php @@ -15,7 +15,9 @@ use cebe\yii2openapi\lib\openapi\ComponentSchema; use Yii; use yii\base\Exception; -use yii\helpers\{StringHelper, ArrayHelper, Inflector}; +use yii\helpers\StringHelper; +use yii\helpers\ArrayHelper; +use yii\helpers\Inflector; use function count; /** @@ -285,10 +287,8 @@ public static function f7(array $schemasToDrop): array // TODO rename // $this->migrations[$tableName] = $mm; // } } - } return $dbModelsToDrop; - } public static function resolveTableNameHere(string $schemaName):string // TODO rename diff --git a/src/lib/generators/MigrationsGenerator.php b/src/lib/generators/MigrationsGenerator.php index cf977a20..ce60a083 100644 --- a/src/lib/generators/MigrationsGenerator.php +++ b/src/lib/generators/MigrationsGenerator.php @@ -147,7 +147,7 @@ public function buildMigrations():array // ->addDownCode($builder->dropTable($tableName)) // ; // if ($mm->notEmpty()) { -//// var_dump('$this->migrations'); die; + //// var_dump('$this->migrations'); die; // $this->migrations[$tableName] = $mm; // } // } diff --git a/src/lib/migrations/BaseMigrationBuilder.php b/src/lib/migrations/BaseMigrationBuilder.php index 3031bb1b..965e55d2 100644 --- a/src/lib/migrations/BaseMigrationBuilder.php +++ b/src/lib/migrations/BaseMigrationBuilder.php @@ -588,7 +588,7 @@ public function buildTablesDrop(): void if (!$this->model->drop) { return; } - $this->migration->addUpCode($this->recordBuilder->dropTable($this->model->getTableAlias()) ) + $this->migration->addUpCode($this->recordBuilder->dropTable($this->model->getTableAlias())) ->addDownCode($this->recordBuilder->createTable($this->model->getTableAlias(), $this->model->attributesToColumnSchema())); } } From 46ef38706fef19025baf9fe5c83dedb1f91d4478 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Thu, 13 Jun 2024 19:28:18 +0530 Subject: [PATCH 014/358] Generate foreign keys in migrations - WIP --- src/lib/SchemaToDatabase.php | 19 +++++++++--------- src/lib/migrations/BaseMigrationBuilder.php | 16 +++++++++++++-- src/lib/migrations/MigrationRecordBuilder.php | 2 +- .../132_create_migration_for_drop_table.yaml | 3 ++- tests/unit/IssueFixTest.php | 20 +++++++++++++------ 5 files changed, 40 insertions(+), 20 deletions(-) diff --git a/src/lib/SchemaToDatabase.php b/src/lib/SchemaToDatabase.php index 923a78e1..3ce339d2 100644 --- a/src/lib/SchemaToDatabase.php +++ b/src/lib/SchemaToDatabase.php @@ -283,7 +283,6 @@ public static function f7(array $schemasToDrop): array // TODO rename // ->addDownCode($builder->dropTable($tableName)) // ; // if ($mm->notEmpty()) { - // var_dump('$this->migrations'); die; // $this->migrations[$tableName] = $mm; // } } @@ -302,18 +301,18 @@ public static function resolveTableNameHere(string $schemaName):string // TODO r public static function attributesFromColumnSchemas(array $columnSchemas) { $attributes = []; - foreach ($columnSchemas as $columnName => $schema) { + foreach ($columnSchemas as $columnName => $columnSchema) { /** @var $columnName string */ - /** @var $schema \yii\db\ColumnSchema */ + /** @var $columnSchema \yii\db\ColumnSchema */ unset($attribute); - $attribute = new Attribute($schema->name, [ - 'phpType' => $schema->phpType, - 'dbType' => $schema->dbType, - 'nullable' => $schema->allowNull, - 'size' => $schema->size, + $attribute = new Attribute($columnSchema->name, [ + 'phpType' => $columnSchema->phpType, + 'dbType' => $columnSchema->dbType, + 'nullable' => $columnSchema->allowNull, + 'size' => $columnSchema->size, // 'limits' => ['min' => null, 'max' => null, 'minLength' => null], // TODO - 'primary' => $schema->isPrimaryKey, - 'enumValues' => $schema->enumValues, + 'primary' => $columnSchema->isPrimaryKey, + 'enumValues' => $columnSchema->enumValues, ]); $attributes[] = $attribute; } diff --git a/src/lib/migrations/BaseMigrationBuilder.php b/src/lib/migrations/BaseMigrationBuilder.php index 965e55d2..78f8fd25 100644 --- a/src/lib/migrations/BaseMigrationBuilder.php +++ b/src/lib/migrations/BaseMigrationBuilder.php @@ -171,7 +171,9 @@ public function buildSecondary(?ManyToManyRelation $relation = null):MigrationMo { $this->migration = Yii::createObject(MigrationModel::class, [$this->model, false, $relation, []]); $this->newColumns = $relation->columnSchema ?? $this->model->attributesToColumnSchema(); - $this->newColumns = $this->model->drop ? [] : $this->newColumns; // TODO refactor + + $this->newColumns = $this->model->drop ? [] : $this->newColumns; + $wantNames = array_keys($this->newColumns); $haveNames = $this->tableSchema->columnNames; $columnsForCreate = array_map( @@ -588,7 +590,17 @@ public function buildTablesDrop(): void if (!$this->model->drop) { return; } + + $this->migration->addDownCode($this->recordBuilder->addPrimaryKey($this->model->getTableAlias(), $this->tableSchema->primaryKey)); + $this->migration->addUpCode($this->recordBuilder->dropTable($this->model->getTableAlias())) - ->addDownCode($this->recordBuilder->createTable($this->model->getTableAlias(), $this->model->attributesToColumnSchema())); + ->addDownCode( + $this->recordBuilder->createTable( + $this->model->getTableAlias(), +// $this->model->attributesToColumnSchema() + $this->tableSchema->columns + ) + ); + } } diff --git a/src/lib/migrations/MigrationRecordBuilder.php b/src/lib/migrations/MigrationRecordBuilder.php index 98ee03b8..7229258b 100644 --- a/src/lib/migrations/MigrationRecordBuilder.php +++ b/src/lib/migrations/MigrationRecordBuilder.php @@ -66,7 +66,7 @@ public function createTable(string $tableAlias, array $columns):string { $codeColumns = []; foreach ($columns as $columnName => $cebeDbColumnSchema) { - if (is_string($cebeDbColumnSchema->xDbType) && !empty($cebeDbColumnSchema->xDbType)) { + if (!empty($cebeDbColumnSchema->xDbType) && is_string($cebeDbColumnSchema->xDbType)) { $name = static::quote($columnName); $codeColumns[] = $name.' '.$this->columnToCode($tableAlias, $cebeDbColumnSchema, false)->getCode(); } else { diff --git a/tests/specs/issue_fix/132_create_migration_for_drop_table/132_create_migration_for_drop_table.yaml b/tests/specs/issue_fix/132_create_migration_for_drop_table/132_create_migration_for_drop_table.yaml index 84edb4f3..f6cecd25 100644 --- a/tests/specs/issue_fix/132_create_migration_for_drop_table/132_create_migration_for_drop_table.yaml +++ b/tests/specs/issue_fix/132_create_migration_for_drop_table/132_create_migration_for_drop_table.yaml @@ -4,7 +4,8 @@ info: title: 132_create_migration_for_drop_table \#132 x-deleted-schemas: # don't use x-keep-table, use x-deleted-schemas - - Fruit # table name evaluated to `itt_fruits`. `itt_` is prefix +# - Fruit # table name evaluated to `itt_fruits`. `itt_` is prefix + - Pristine # - Mango: the_mango7 # custom table name; `x-table` paths: diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index 44b3596b..35f3827e 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -279,15 +279,19 @@ public function testNullableFalseInRequired() // https://github.com/cebe/yii2-openapi/issues/132 public function testCreateMigrationForDropTable132() { +// $this->changeDbToMariadb(); $testFile = Yii::getAlias("@specs/issue_fix/132_create_migration_for_drop_table/132_create_migration_for_drop_table.php"); - $this->deleteTablesForNoSyntaxError107(); - $this->createTableForNoSyntaxError107(); +// $this->deleteTablesForCreateMigrationForDropTable132(); + $this->createTablesForCreateMigrationForDropTable132(); +// sleep(3000); $this->runGenerator($testFile); +// $this->runActualMigrations('mysql', 3); // ... TODO - $this->deleteTables(); + $this->deleteTablesForCreateMigrationForDropTable132(); +// $this->deleteTables(); } - private function createTableForCreateMigrationForDropTable132() + private function createTablesForCreateMigrationForDropTable132() { Yii::$app->db->createCommand()->createTable('{{%fruits}}', [ 'id' => 'pk', @@ -295,14 +299,18 @@ private function createTableForCreateMigrationForDropTable132() ])->execute(); Yii::$app->db->createCommand()->createTable('{{%pristines}}', [ 'id' => 'pk', - 'name' => 'string(150)', + 'name' => 'string(151)', + 'fruit_id' => 'integer(11)', // FK ])->execute(); + Yii::$app->db->createCommand()->addForeignKey('name', '{{%pristines}}', 'fruit_id', '{{%fruits}}', 'id')->execute(); } private function deleteTablesForCreateMigrationForDropTable132() { - Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%fruits}}')->execute(); + Yii::$app->db->createCommand()->dropForeignKey('name', '{{%pristines}}')->execute(); +// Yii::$app->db->createCommand('')->execute(); Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%pristines}}')->execute(); + Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%fruits}}')->execute(); } public function test162BugDollarrefWithXFaker() From 67cc5a0eb54920595af1e26bb98653e5916a649e Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Wed, 19 Jun 2024 21:14:01 +0530 Subject: [PATCH 015/358] Create PK using Yii's in-built method --- src/lib/SchemaToDatabase.php | 22 +++++++++++++++++-- src/lib/migrations/BaseMigrationBuilder.php | 7 +++--- .../132_create_migration_for_drop_table.yaml | 4 ++-- tests/unit/IssueFixTest.php | 2 +- 4 files changed, 26 insertions(+), 9 deletions(-) diff --git a/src/lib/SchemaToDatabase.php b/src/lib/SchemaToDatabase.php index 3ce339d2..4174cbd3 100644 --- a/src/lib/SchemaToDatabase.php +++ b/src/lib/SchemaToDatabase.php @@ -15,6 +15,7 @@ use cebe\yii2openapi\lib\openapi\ComponentSchema; use Yii; use yii\base\Exception; +use yii\db\Schema; use yii\helpers\StringHelper; use yii\helpers\ArrayHelper; use yii\helpers\Inflector; @@ -306,14 +307,31 @@ public static function attributesFromColumnSchemas(array $columnSchemas) /** @var $columnSchema \yii\db\ColumnSchema */ unset($attribute); $attribute = new Attribute($columnSchema->name, [ - 'phpType' => $columnSchema->phpType, - 'dbType' => $columnSchema->dbType, + 'phpType' => $columnSchema->phpType, // pk + 'dbType' => $columnSchema->dbType, // pk 'nullable' => $columnSchema->allowNull, 'size' => $columnSchema->size, // 'limits' => ['min' => null, 'max' => null, 'minLength' => null], // TODO 'primary' => $columnSchema->isPrimaryKey, 'enumValues' => $columnSchema->enumValues, ]); + + // generate PK using `->primaryKeys()` or similar methods instead of separate SQL statement which sets only PK to a column of table + if ($columnSchema->phpType === 'integer' && $columnSchema->isPrimaryKey === true && $columnSchema->autoIncrement) { + if ($columnSchema->dbType === 'BIGINT' || $columnSchema->dbType === 'bigserial') { + if ($columnSchema->unsigned) { + $attribute->dbType = Schema::TYPE_UBIGPK; + } else { + $attribute->dbType = Schema::TYPE_BIGPK; + } + } else { + if ($columnSchema->unsigned) { + $attribute->dbType = Schema::TYPE_UPK; + } else { + $attribute->dbType = Schema::TYPE_PK; + } + } + } $attributes[] = $attribute; } return $attributes; diff --git a/src/lib/migrations/BaseMigrationBuilder.php b/src/lib/migrations/BaseMigrationBuilder.php index 78f8fd25..2889e78e 100644 --- a/src/lib/migrations/BaseMigrationBuilder.php +++ b/src/lib/migrations/BaseMigrationBuilder.php @@ -591,16 +591,15 @@ public function buildTablesDrop(): void return; } - $this->migration->addDownCode($this->recordBuilder->addPrimaryKey($this->model->getTableAlias(), $this->tableSchema->primaryKey)); +// $this->migration->addDownCode($this->recordBuilder->addPrimaryKey($this->model->getTableAlias(), $this->tableSchema->primaryKey)); $this->migration->addUpCode($this->recordBuilder->dropTable($this->model->getTableAlias())) ->addDownCode( $this->recordBuilder->createTable( $this->model->getTableAlias(), -// $this->model->attributesToColumnSchema() - $this->tableSchema->columns + $this->model->attributesToColumnSchema() +// $this->tableSchema->columns ) ); - } } diff --git a/tests/specs/issue_fix/132_create_migration_for_drop_table/132_create_migration_for_drop_table.yaml b/tests/specs/issue_fix/132_create_migration_for_drop_table/132_create_migration_for_drop_table.yaml index f6cecd25..16ad3de0 100644 --- a/tests/specs/issue_fix/132_create_migration_for_drop_table/132_create_migration_for_drop_table.yaml +++ b/tests/specs/issue_fix/132_create_migration_for_drop_table/132_create_migration_for_drop_table.yaml @@ -4,8 +4,8 @@ info: title: 132_create_migration_for_drop_table \#132 x-deleted-schemas: # don't use x-keep-table, use x-deleted-schemas -# - Fruit # table name evaluated to `itt_fruits`. `itt_` is prefix - - Pristine +# - Pristine + - Fruit # table name evaluated to `itt_fruits`. `itt_` is prefix # - Mango: the_mango7 # custom table name; `x-table` paths: diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index 35f3827e..a3667771 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -66,7 +66,7 @@ private function deleteTables() $this->deleteTableForQuoteInAlterColumn(); $this->deleteTableForTimestampIssue143(); $this->deleteTablesForWrongMigrationForPgsqlForStringVarcharDatatype149(); - $this->deleteTablesForCreateMigrationForDropTable132(); +// $this->deleteTablesForCreateMigrationForDropTable132(); } private function deleteTablesForFloatIssue() From c205866cbd20833ca463d28a26e4b89cbe30335e Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Thu, 20 Jun 2024 20:36:41 +0530 Subject: [PATCH 016/358] Create PK using Yii's in-built method - more concrete --- src/lib/SchemaToDatabase.php | 70 +++++++++++-------- .../132_create_migration_for_drop_table.yaml | 2 +- tests/unit/IssueFixTest.php | 22 +++--- 3 files changed, 54 insertions(+), 40 deletions(-) diff --git a/src/lib/SchemaToDatabase.php b/src/lib/SchemaToDatabase.php index 4174cbd3..4bc51b38 100644 --- a/src/lib/SchemaToDatabase.php +++ b/src/lib/SchemaToDatabase.php @@ -7,18 +7,22 @@ namespace cebe\yii2openapi\lib; +use cebe\openapi\exceptions\IOException; +use cebe\openapi\exceptions\TypeErrorException; +use cebe\openapi\exceptions\UnresolvableReferenceException; +use cebe\yii2openapi\lib\exceptions\InvalidDefinitionException; use cebe\yii2openapi\lib\items\Attribute; use cebe\yii2openapi\lib\items\DbModel; use cebe\yii2openapi\lib\items\JunctionSchemas; -use cebe\yii2openapi\lib\items\MigrationModel; -use cebe\yii2openapi\lib\migrations\MigrationRecordBuilder; use cebe\yii2openapi\lib\openapi\ComponentSchema; use Yii; use yii\base\Exception; +use yii\base\InvalidConfigException; +use yii\db\ColumnSchema; use yii\db\Schema; -use yii\helpers\StringHelper; use yii\helpers\ArrayHelper; use yii\helpers\Inflector; +use yii\helpers\StringHelper; use function count; /** @@ -63,7 +67,7 @@ class SchemaToDatabase { /** - * @var \cebe\yii2openapi\lib\Config + * @var Config */ protected $config; @@ -73,15 +77,15 @@ public function __construct(Config $config) } /** - * @return array|\cebe\yii2openapi\lib\items\DbModel[] - * @throws \cebe\openapi\exceptions\IOException - * @throws \cebe\openapi\exceptions\TypeErrorException - * @throws \cebe\openapi\exceptions\UnresolvableReferenceException - * @throws \cebe\yii2openapi\lib\exceptions\InvalidDefinitionException - * @throws \yii\base\Exception - * @throws \yii\base\InvalidConfigException + * @return array|DbModel[] + * @throws IOException + * @throws TypeErrorException + * @throws UnresolvableReferenceException + * @throws InvalidDefinitionException + * @throws Exception + * @throws InvalidConfigException */ - public function prepareModels():array + public function prepareModels(): array { $models = []; $openApi = $this->config->getOpenApi(); @@ -95,12 +99,12 @@ public function prepareModels():array if ($junctions->isJunctionSchema($schemaName)) { $schemaName = $junctions->trimPrefix($schemaName); } - /** @var \cebe\yii2openapi\lib\AttributeResolver $resolver */ + /** @var AttributeResolver $resolver */ $resolver = Yii::createObject(AttributeResolver::class, [$schemaName, $schema, $junctions, $this->config]); $models[$schemaName] = $resolver->resolve(); } - foreach ($models as $model) { + foreach ($models as $model) { foreach ($model->many2many as $relation) { if (isset($models[$relation->viaModelName])) { $relation->hasViaModel = true; @@ -123,14 +127,14 @@ public function prepareModels():array } /** - * @return \cebe\yii2openapi\lib\items\JunctionSchemas - * @throws \cebe\openapi\exceptions\IOException - * @throws \cebe\openapi\exceptions\TypeErrorException - * @throws \cebe\openapi\exceptions\UnresolvableReferenceException - * @throws \yii\base\Exception - * @throws \yii\base\InvalidConfigException + * @return JunctionSchemas + * @throws IOException + * @throws TypeErrorException + * @throws UnresolvableReferenceException + * @throws Exception + * @throws InvalidConfigException */ - public function findJunctionSchemas():JunctionSchemas + public function findJunctionSchemas(): JunctionSchemas { $junctions = []; $openApi = $this->config->getOpenApi(); @@ -210,7 +214,7 @@ public function findJunctionSchemas():JunctionSchemas return Yii::createObject(JunctionSchemas::class, [$junctions]); } - private function canGenerateModel(string $schemaName, ComponentSchema $schema):bool + private function canGenerateModel(string $schemaName, ComponentSchema $schema): bool { // only generate tables for schemas of type object and those who have defined properties if ($schema->isObjectSchema() && !$schema->hasProperties()) { @@ -240,7 +244,7 @@ private function canGenerateModel(string $schemaName, ComponentSchema $schema):b } /** - * @param array $schemasToDrop. Example: + * @param array $schemasToDrop . Example: * ``` * array(2) { * [0]=> @@ -278,20 +282,21 @@ public static function f7(array $schemasToDrop): array // TODO rename 'drop' => true ]); $dbModelsToDrop[$key] = $dbModelHere; + // TODO // $mm = new MigrationModel($dbModelHere); // $builder = new MigrationRecordBuilder($this->db->getSchema()); // $mm->addUpCode($builder->dropTable($tableName)) // ->addDownCode($builder->dropTable($tableName)) // ; // if ($mm->notEmpty()) { - // $this->migrations[$tableName] = $mm; + // $this->migrations[$tableName] = $mm; // } } } return $dbModelsToDrop; } - public static function resolveTableNameHere(string $schemaName):string // TODO rename + public static function resolveTableNameHere(string $schemaName): string // TODO rename { return Inflector::camel2id(StringHelper::basename(Inflector::pluralize($schemaName)), '_'); } @@ -304,7 +309,7 @@ public static function attributesFromColumnSchemas(array $columnSchemas) $attributes = []; foreach ($columnSchemas as $columnName => $columnSchema) { /** @var $columnName string */ - /** @var $columnSchema \yii\db\ColumnSchema */ + /** @var $columnSchema ColumnSchema */ unset($attribute); $attribute = new Attribute($columnSchema->name, [ 'phpType' => $columnSchema->phpType, // pk @@ -317,8 +322,16 @@ public static function attributesFromColumnSchemas(array $columnSchemas) ]); // generate PK using `->primaryKeys()` or similar methods instead of separate SQL statement which sets only PK to a column of table - if ($columnSchema->phpType === 'integer' && $columnSchema->isPrimaryKey === true && $columnSchema->autoIncrement) { - if ($columnSchema->dbType === 'BIGINT' || $columnSchema->dbType === 'bigserial') { + // https://github.com/cebe/yii2-openapi/issues/132 + if (in_array($columnSchema->phpType, [ + 'integer', + 'string' # https://github.com/yiisoft/yii2/issues/14663 + ]) + && $columnSchema->isPrimaryKey === true && $columnSchema->autoIncrement + ) { + if (stripos($columnSchema->dbType, 'BIGINT') !== false # MySQL, MariaDB + || stripos($columnSchema->dbType, 'bigserial') !== false # PgSQL + ) { if ($columnSchema->unsigned) { $attribute->dbType = Schema::TYPE_UBIGPK; } else { @@ -332,6 +345,7 @@ public static function attributesFromColumnSchemas(array $columnSchemas) } } } + $attributes[] = $attribute; } return $attributes; diff --git a/tests/specs/issue_fix/132_create_migration_for_drop_table/132_create_migration_for_drop_table.yaml b/tests/specs/issue_fix/132_create_migration_for_drop_table/132_create_migration_for_drop_table.yaml index 16ad3de0..ab6fc8a3 100644 --- a/tests/specs/issue_fix/132_create_migration_for_drop_table/132_create_migration_for_drop_table.yaml +++ b/tests/specs/issue_fix/132_create_migration_for_drop_table/132_create_migration_for_drop_table.yaml @@ -4,7 +4,7 @@ info: title: 132_create_migration_for_drop_table \#132 x-deleted-schemas: # don't use x-keep-table, use x-deleted-schemas -# - Pristine + - Pristine - Fruit # table name evaluated to `itt_fruits`. `itt_` is prefix # - Mango: the_mango7 # custom table name; `x-table` diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index a3667771..b98684c3 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -277,30 +277,31 @@ public function testNullableFalseInRequired() // Create migration for drop table if a entire schema is deleted from OpenAPI spec #132 // https://github.com/cebe/yii2-openapi/issues/132 - public function testCreateMigrationForDropTable132() - { + public function testCreateMigrationForDropTable132() + { // $this->changeDbToMariadb(); - $testFile = Yii::getAlias("@specs/issue_fix/132_create_migration_for_drop_table/132_create_migration_for_drop_table.php"); + $testFile = Yii::getAlias("@specs/issue_fix/132_create_migration_for_drop_table/132_create_migration_for_drop_table.php"); // $this->deleteTablesForCreateMigrationForDropTable132(); - $this->createTablesForCreateMigrationForDropTable132(); + $this->createTablesForCreateMigrationForDropTable132(); // sleep(3000); - $this->runGenerator($testFile); + $this->runGenerator($testFile); // $this->runActualMigrations('mysql', 3); - // ... TODO - $this->deleteTablesForCreateMigrationForDropTable132(); + // ... TODO + $this->deleteTablesForCreateMigrationForDropTable132(); // $this->deleteTables(); - } + } private function createTablesForCreateMigrationForDropTable132() { Yii::$app->db->createCommand()->createTable('{{%fruits}}', [ - 'id' => 'pk', + 'id' => 'ubigpk', 'name' => 'string(150)', ])->execute(); Yii::$app->db->createCommand()->createTable('{{%pristines}}', [ 'id' => 'pk', 'name' => 'string(151)', - 'fruit_id' => 'integer(11)', // FK + 'fruit_id' => 'bigint unsigned', // FK +// 'fruit_id' => $this->integer()->unsigned(), // FK ])->execute(); Yii::$app->db->createCommand()->addForeignKey('name', '{{%pristines}}', 'fruit_id', '{{%fruits}}', 'id')->execute(); } @@ -308,7 +309,6 @@ private function createTablesForCreateMigrationForDropTable132() private function deleteTablesForCreateMigrationForDropTable132() { Yii::$app->db->createCommand()->dropForeignKey('name', '{{%pristines}}')->execute(); -// Yii::$app->db->createCommand('')->execute(); Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%pristines}}')->execute(); Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%fruits}}')->execute(); } From 2d10ff497ce984c264cfe5b295e31420339675ee Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Fri, 21 Jun 2024 19:00:03 +0530 Subject: [PATCH 017/358] Fix https://github.com/php-openapi/yii2-openapi/issues/2 --- src/lib/migrations/BaseMigrationBuilder.php | 6 +++--- .../m200000_000005_change_table_v2_comments.php | 4 ++-- .../m200000_000005_change_table_v2_comments.php | 4 ++-- .../m200000_000005_change_table_v2_comments.php | 4 ++-- 4 files changed, 9 insertions(+), 9 deletions(-) diff --git a/src/lib/migrations/BaseMigrationBuilder.php b/src/lib/migrations/BaseMigrationBuilder.php index 2889e78e..632f48a8 100644 --- a/src/lib/migrations/BaseMigrationBuilder.php +++ b/src/lib/migrations/BaseMigrationBuilder.php @@ -334,9 +334,9 @@ protected function buildRelations():void $tableAlias = $this->model->getTableAlias(); $existedRelations = []; foreach ($this->tableSchema->foreignKeys as $fkName => $relation) { - $refTable = $this->unPrefixTableName(array_shift($relation)); - $refCol = array_keys($relation)[0]; - $fkCol = $relation[$refCol]; + $refTable = array_shift($relation); + $fkCol = array_keys($relation)[0]; + $refCol = $relation[$fkCol]; $existedRelations[$fkName] = ['refTable' => $refTable, 'refCol' => $refCol, 'fkCol' => $fkCol]; } diff --git a/tests/specs/blog_v2/migrations_maria_db/m200000_000005_change_table_v2_comments.php b/tests/specs/blog_v2/migrations_maria_db/m200000_000005_change_table_v2_comments.php index 75553729..ee11067f 100644 --- a/tests/specs/blog_v2/migrations_maria_db/m200000_000005_change_table_v2_comments.php +++ b/tests/specs/blog_v2/migrations_maria_db/m200000_000005_change_table_v2_comments.php @@ -27,7 +27,7 @@ public function down() $this->alterColumn('{{%v2_comments}}', 'message', 'json NOT NULL DEFAULT \'[]\''); $this->addColumn('{{%v2_comments}}', 'author_id', $this->integer(11)->notNull()); $this->dropColumn('{{%v2_comments}}', 'user_id'); - $this->addForeignKey('fk_v2_comments_author_id_v2_users_id', '{{%v2_comments}}', 'id', 'v2_users', 'author_id'); - $this->addForeignKey('fk_v2_comments_post_id_v2_posts_uid', '{{%v2_comments}}', 'uid', 'v2_posts', 'post_id'); + $this->addForeignKey('fk_v2_comments_author_id_v2_users_id', '{{%v2_comments}}', 'author_id', 'itt_v2_users', 'id'); + $this->addForeignKey('fk_v2_comments_post_id_v2_posts_uid', '{{%v2_comments}}', 'post_id', 'itt_v2_posts', 'uid'); } } diff --git a/tests/specs/blog_v2/migrations_mysql_db/m200000_000005_change_table_v2_comments.php b/tests/specs/blog_v2/migrations_mysql_db/m200000_000005_change_table_v2_comments.php index 5861542c..475a2639 100644 --- a/tests/specs/blog_v2/migrations_mysql_db/m200000_000005_change_table_v2_comments.php +++ b/tests/specs/blog_v2/migrations_mysql_db/m200000_000005_change_table_v2_comments.php @@ -27,7 +27,7 @@ public function down() $this->alterColumn('{{%v2_comments}}', 'message', 'json NOT NULL'); $this->addColumn('{{%v2_comments}}', 'author_id', $this->integer()->notNull()); $this->dropColumn('{{%v2_comments}}', 'user_id'); - $this->addForeignKey('fk_v2_comments_author_id_v2_users_id', '{{%v2_comments}}', 'id', 'v2_users', 'author_id'); - $this->addForeignKey('fk_v2_comments_post_id_v2_posts_uid', '{{%v2_comments}}', 'uid', 'v2_posts', 'post_id'); + $this->addForeignKey('fk_v2_comments_author_id_v2_users_id', '{{%v2_comments}}', 'author_id', 'itt_v2_users', 'id'); + $this->addForeignKey('fk_v2_comments_post_id_v2_posts_uid', '{{%v2_comments}}', 'post_id', 'itt_v2_posts', 'uid'); } } diff --git a/tests/specs/blog_v2/migrations_pgsql_db/m200000_000005_change_table_v2_comments.php b/tests/specs/blog_v2/migrations_pgsql_db/m200000_000005_change_table_v2_comments.php index 99a896c6..efbb21be 100644 --- a/tests/specs/blog_v2/migrations_pgsql_db/m200000_000005_change_table_v2_comments.php +++ b/tests/specs/blog_v2/migrations_pgsql_db/m200000_000005_change_table_v2_comments.php @@ -33,7 +33,7 @@ public function safeDown() $this->alterColumn('{{%v2_comments}}', 'message', "SET DEFAULT '[]'"); $this->alterColumn('{{%v2_comments}}', 'meta_data', "SET NOT NULL"); $this->alterColumn('{{%v2_comments}}', 'meta_data', "SET DEFAULT '[]'"); - $this->addForeignKey('fk_v2_comments_post_id_v2_posts_uid', '{{%v2_comments}}', 'uid', 'v2_posts', 'post_id'); - $this->addForeignKey('fk_v2_comments_author_id_v2_users_id', '{{%v2_comments}}', 'id', 'v2_users', 'author_id'); + $this->addForeignKey('fk_v2_comments_post_id_v2_posts_uid', '{{%v2_comments}}', 'post_id', 'itt_v2_posts', 'uid'); + $this->addForeignKey('fk_v2_comments_author_id_v2_users_id', '{{%v2_comments}}', 'author_id', 'itt_v2_users', 'id'); } } From 6644d155f48e582de6a4e188395792d1a358dde1 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Fri, 21 Jun 2024 19:38:09 +0530 Subject: [PATCH 018/358] Cleanup --- src/lib/generators/MigrationsGenerator.php | 2 +- .../132_create_migration_for_drop_table.yaml | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/src/lib/generators/MigrationsGenerator.php b/src/lib/generators/MigrationsGenerator.php index ce60a083..80979687 100644 --- a/src/lib/generators/MigrationsGenerator.php +++ b/src/lib/generators/MigrationsGenerator.php @@ -198,7 +198,7 @@ protected function sortByDependencyRecurse(MigrationModel $migration):void //echo "adding dep $dependency\n"; $this->sortByDependencyRecurse($this->migrations[$dependency]); } - unset($this->sorted[$migration->tableAlias]);//necessary for provide valid order + unset($this->sorted[$migration->tableAlias]); // necessary for provide valid order $this->sorted[$migration->tableAlias] = $migration; } elseif ($this->sorted[$migration->tableAlias] === false) { throw new Exception("A circular dependency is detected for table '{$migration->tableAlias}'."); diff --git a/tests/specs/issue_fix/132_create_migration_for_drop_table/132_create_migration_for_drop_table.yaml b/tests/specs/issue_fix/132_create_migration_for_drop_table/132_create_migration_for_drop_table.yaml index ab6fc8a3..d88a1ffc 100644 --- a/tests/specs/issue_fix/132_create_migration_for_drop_table/132_create_migration_for_drop_table.yaml +++ b/tests/specs/issue_fix/132_create_migration_for_drop_table/132_create_migration_for_drop_table.yaml @@ -7,6 +7,7 @@ x-deleted-schemas: # don't use x-keep-table, use x-deleted-schemas - Pristine - Fruit # table name evaluated to `itt_fruits`. `itt_` is prefix # - Mango: the_mango7 # custom table name; `x-table` +# - Upk paths: /: From d45f911e41dc774727e0043527b63d6f8121f59f Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Fri, 21 Jun 2024 19:38:50 +0530 Subject: [PATCH 019/358] Test cleanup --- tests/unit/IssueFixTest.php | 35 +++++++++++++++++++---------------- 1 file changed, 19 insertions(+), 16 deletions(-) diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index b98684c3..f9d0ae92 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -277,31 +277,33 @@ public function testNullableFalseInRequired() // Create migration for drop table if a entire schema is deleted from OpenAPI spec #132 // https://github.com/cebe/yii2-openapi/issues/132 - public function testCreateMigrationForDropTable132() - { -// $this->changeDbToMariadb(); - $testFile = Yii::getAlias("@specs/issue_fix/132_create_migration_for_drop_table/132_create_migration_for_drop_table.php"); -// $this->deleteTablesForCreateMigrationForDropTable132(); - $this->createTablesForCreateMigrationForDropTable132(); -// sleep(3000); - $this->runGenerator($testFile); -// $this->runActualMigrations('mysql', 3); - // ... TODO - $this->deleteTablesForCreateMigrationForDropTable132(); -// $this->deleteTables(); - } + public function testCreateMigrationForDropTable132() + { + $testFile = Yii::getAlias("@specs/issue_fix/132_create_migration_for_drop_table/132_create_migration_for_drop_table.php"); + // $this->deleteTablesForCreateMigrationForDropTable132(); + $this->createTablesForCreateMigrationForDropTable132(); + $this->runGenerator($testFile); + $this->runActualMigrations('mysql', 3); + // ... TODO compare files + $this->deleteTablesForCreateMigrationForDropTable132(); + // $this->deleteTables(); + } private function createTablesForCreateMigrationForDropTable132() { +// Yii::$app->db->createCommand()->createTable('{{%upks}}', [ +// 'id' => 'upk', +// 'name' => 'string(150)', +// ])->execute(); + Yii::$app->db->createCommand()->createTable('{{%fruits}}', [ - 'id' => 'ubigpk', + 'id' => 'pk', 'name' => 'string(150)', ])->execute(); Yii::$app->db->createCommand()->createTable('{{%pristines}}', [ 'id' => 'pk', 'name' => 'string(151)', - 'fruit_id' => 'bigint unsigned', // FK -// 'fruit_id' => $this->integer()->unsigned(), // FK + 'fruit_id' => 'int', // FK ])->execute(); Yii::$app->db->createCommand()->addForeignKey('name', '{{%pristines}}', 'fruit_id', '{{%fruits}}', 'id')->execute(); } @@ -311,6 +313,7 @@ private function deleteTablesForCreateMigrationForDropTable132() Yii::$app->db->createCommand()->dropForeignKey('name', '{{%pristines}}')->execute(); Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%pristines}}')->execute(); Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%fruits}}')->execute(); + Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%upks}}')->execute(); } public function test162BugDollarrefWithXFaker() From 7cf9aa3ce0c10e867403531b248f6ba1b65ed173 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Fri, 21 Jun 2024 19:56:12 +0530 Subject: [PATCH 020/358] Fix issue of migration ordering in drop + fix failing tests --- src/lib/generators/MigrationsGenerator.php | 2 +- ..._pristines.php => m200000_000000_create_table_pristines.php} | 2 +- ...types.php => m200000_000001_create_table_alldbdatatypes.php} | 2 +- ...tcolumns.php => m200000_000003_change_table_editcolumns.php} | 2 +- ..._pristines.php => m200000_000000_create_table_pristines.php} | 2 +- ...types.php => m200000_000001_create_table_alldbdatatypes.php} | 2 +- ...tcolumns.php => m200000_000003_change_table_editcolumns.php} | 2 +- ..._pristines.php => m200000_000000_create_table_pristines.php} | 2 +- ...types.php => m200000_000001_create_table_alldbdatatypes.php} | 2 +- ...tcolumns.php => m200000_000003_change_table_editcolumns.php} | 2 +- 10 files changed, 10 insertions(+), 10 deletions(-) rename tests/specs/x_db_type/edit_column/maria/app/migrations_maria_db/{m200000_000003_create_table_pristines.php => m200000_000000_create_table_pristines.php} (93%) rename tests/specs/x_db_type/edit_column/maria/app/migrations_maria_db/{m200000_000000_create_table_alldbdatatypes.php => m200000_000001_create_table_alldbdatatypes.php} (97%) rename tests/specs/x_db_type/edit_column/maria/app/migrations_maria_db/{m200000_000001_change_table_editcolumns.php => m200000_000003_change_table_editcolumns.php} (97%) rename tests/specs/x_db_type/edit_column/mysql/app/migrations_mysql_db/{m200000_000003_create_table_pristines.php => m200000_000000_create_table_pristines.php} (93%) rename tests/specs/x_db_type/edit_column/mysql/app/migrations_mysql_db/{m200000_000000_create_table_alldbdatatypes.php => m200000_000001_create_table_alldbdatatypes.php} (97%) rename tests/specs/x_db_type/edit_column/mysql/app/migrations_mysql_db/{m200000_000001_change_table_editcolumns.php => m200000_000003_change_table_editcolumns.php} (97%) rename tests/specs/x_db_type/edit_column/pgsql/app/migrations_pgsql_db/{m200000_000003_create_table_pristines.php => m200000_000000_create_table_pristines.php} (93%) rename tests/specs/x_db_type/edit_column/pgsql/app/migrations_pgsql_db/{m200000_000000_create_table_alldbdatatypes.php => m200000_000001_create_table_alldbdatatypes.php} (98%) rename tests/specs/x_db_type/edit_column/pgsql/app/migrations_pgsql_db/{m200000_000001_change_table_editcolumns.php => m200000_000003_change_table_editcolumns.php} (98%) diff --git a/src/lib/generators/MigrationsGenerator.php b/src/lib/generators/MigrationsGenerator.php index 80979687..ee161588 100644 --- a/src/lib/generators/MigrationsGenerator.php +++ b/src/lib/generators/MigrationsGenerator.php @@ -174,7 +174,7 @@ protected function createBuilder(DbModel $model):BaseMigrationBuilder protected function sortMigrationsByDeps():array { $this->sorted = []; - ksort($this->migrations); +// ksort($this->migrations); foreach ($this->migrations as $migration) { //echo "adding {$migration->tableAlias}\n"; $this->sortByDependencyRecurse($migration); diff --git a/tests/specs/x_db_type/edit_column/maria/app/migrations_maria_db/m200000_000003_create_table_pristines.php b/tests/specs/x_db_type/edit_column/maria/app/migrations_maria_db/m200000_000000_create_table_pristines.php similarity index 93% rename from tests/specs/x_db_type/edit_column/maria/app/migrations_maria_db/m200000_000003_create_table_pristines.php rename to tests/specs/x_db_type/edit_column/maria/app/migrations_maria_db/m200000_000000_create_table_pristines.php index 1e27d8d6..d1594797 100644 --- a/tests/specs/x_db_type/edit_column/maria/app/migrations_maria_db/m200000_000003_create_table_pristines.php +++ b/tests/specs/x_db_type/edit_column/maria/app/migrations_maria_db/m200000_000000_create_table_pristines.php @@ -3,7 +3,7 @@ /** * Table for Pristine */ -class m200000_000003_create_table_pristines extends \yii\db\Migration +class m200000_000000_create_table_pristines extends \yii\db\Migration { public function up() { diff --git a/tests/specs/x_db_type/edit_column/maria/app/migrations_maria_db/m200000_000000_create_table_alldbdatatypes.php b/tests/specs/x_db_type/edit_column/maria/app/migrations_maria_db/m200000_000001_create_table_alldbdatatypes.php similarity index 97% rename from tests/specs/x_db_type/edit_column/maria/app/migrations_maria_db/m200000_000000_create_table_alldbdatatypes.php rename to tests/specs/x_db_type/edit_column/maria/app/migrations_maria_db/m200000_000001_create_table_alldbdatatypes.php index 9c002bea..350eedaf 100644 --- a/tests/specs/x_db_type/edit_column/maria/app/migrations_maria_db/m200000_000000_create_table_alldbdatatypes.php +++ b/tests/specs/x_db_type/edit_column/maria/app/migrations_maria_db/m200000_000001_create_table_alldbdatatypes.php @@ -3,7 +3,7 @@ /** * Table for Alldbdatatype */ -class m200000_000000_create_table_alldbdatatypes extends \yii\db\Migration +class m200000_000001_create_table_alldbdatatypes extends \yii\db\Migration { public function up() { diff --git a/tests/specs/x_db_type/edit_column/maria/app/migrations_maria_db/m200000_000001_change_table_editcolumns.php b/tests/specs/x_db_type/edit_column/maria/app/migrations_maria_db/m200000_000003_change_table_editcolumns.php similarity index 97% rename from tests/specs/x_db_type/edit_column/maria/app/migrations_maria_db/m200000_000001_change_table_editcolumns.php rename to tests/specs/x_db_type/edit_column/maria/app/migrations_maria_db/m200000_000003_change_table_editcolumns.php index 239c0a9b..3b9581c0 100644 --- a/tests/specs/x_db_type/edit_column/maria/app/migrations_maria_db/m200000_000001_change_table_editcolumns.php +++ b/tests/specs/x_db_type/edit_column/maria/app/migrations_maria_db/m200000_000003_change_table_editcolumns.php @@ -3,7 +3,7 @@ /** * Table for Editcolumn */ -class m200000_000001_change_table_editcolumns extends \yii\db\Migration +class m200000_000003_change_table_editcolumns extends \yii\db\Migration { public function up() { diff --git a/tests/specs/x_db_type/edit_column/mysql/app/migrations_mysql_db/m200000_000003_create_table_pristines.php b/tests/specs/x_db_type/edit_column/mysql/app/migrations_mysql_db/m200000_000000_create_table_pristines.php similarity index 93% rename from tests/specs/x_db_type/edit_column/mysql/app/migrations_mysql_db/m200000_000003_create_table_pristines.php rename to tests/specs/x_db_type/edit_column/mysql/app/migrations_mysql_db/m200000_000000_create_table_pristines.php index 3e9e8e02..ab96f730 100644 --- a/tests/specs/x_db_type/edit_column/mysql/app/migrations_mysql_db/m200000_000003_create_table_pristines.php +++ b/tests/specs/x_db_type/edit_column/mysql/app/migrations_mysql_db/m200000_000000_create_table_pristines.php @@ -3,7 +3,7 @@ /** * Table for Pristine */ -class m200000_000003_create_table_pristines extends \yii\db\Migration +class m200000_000000_create_table_pristines extends \yii\db\Migration { public function up() { diff --git a/tests/specs/x_db_type/edit_column/mysql/app/migrations_mysql_db/m200000_000000_create_table_alldbdatatypes.php b/tests/specs/x_db_type/edit_column/mysql/app/migrations_mysql_db/m200000_000001_create_table_alldbdatatypes.php similarity index 97% rename from tests/specs/x_db_type/edit_column/mysql/app/migrations_mysql_db/m200000_000000_create_table_alldbdatatypes.php rename to tests/specs/x_db_type/edit_column/mysql/app/migrations_mysql_db/m200000_000001_create_table_alldbdatatypes.php index 2cda660f..5f3d90d1 100644 --- a/tests/specs/x_db_type/edit_column/mysql/app/migrations_mysql_db/m200000_000000_create_table_alldbdatatypes.php +++ b/tests/specs/x_db_type/edit_column/mysql/app/migrations_mysql_db/m200000_000001_create_table_alldbdatatypes.php @@ -3,7 +3,7 @@ /** * Table for Alldbdatatype */ -class m200000_000000_create_table_alldbdatatypes extends \yii\db\Migration +class m200000_000001_create_table_alldbdatatypes extends \yii\db\Migration { public function up() { diff --git a/tests/specs/x_db_type/edit_column/mysql/app/migrations_mysql_db/m200000_000001_change_table_editcolumns.php b/tests/specs/x_db_type/edit_column/mysql/app/migrations_mysql_db/m200000_000003_change_table_editcolumns.php similarity index 97% rename from tests/specs/x_db_type/edit_column/mysql/app/migrations_mysql_db/m200000_000001_change_table_editcolumns.php rename to tests/specs/x_db_type/edit_column/mysql/app/migrations_mysql_db/m200000_000003_change_table_editcolumns.php index b4d63bd3..02626d1e 100644 --- a/tests/specs/x_db_type/edit_column/mysql/app/migrations_mysql_db/m200000_000001_change_table_editcolumns.php +++ b/tests/specs/x_db_type/edit_column/mysql/app/migrations_mysql_db/m200000_000003_change_table_editcolumns.php @@ -3,7 +3,7 @@ /** * Table for Editcolumn */ -class m200000_000001_change_table_editcolumns extends \yii\db\Migration +class m200000_000003_change_table_editcolumns extends \yii\db\Migration { public function up() { diff --git a/tests/specs/x_db_type/edit_column/pgsql/app/migrations_pgsql_db/m200000_000003_create_table_pristines.php b/tests/specs/x_db_type/edit_column/pgsql/app/migrations_pgsql_db/m200000_000000_create_table_pristines.php similarity index 93% rename from tests/specs/x_db_type/edit_column/pgsql/app/migrations_pgsql_db/m200000_000003_create_table_pristines.php rename to tests/specs/x_db_type/edit_column/pgsql/app/migrations_pgsql_db/m200000_000000_create_table_pristines.php index aab6bb88..93b55396 100644 --- a/tests/specs/x_db_type/edit_column/pgsql/app/migrations_pgsql_db/m200000_000003_create_table_pristines.php +++ b/tests/specs/x_db_type/edit_column/pgsql/app/migrations_pgsql_db/m200000_000000_create_table_pristines.php @@ -3,7 +3,7 @@ /** * Table for Pristine */ -class m200000_000003_create_table_pristines extends \yii\db\Migration +class m200000_000000_create_table_pristines extends \yii\db\Migration { public function safeUp() { diff --git a/tests/specs/x_db_type/edit_column/pgsql/app/migrations_pgsql_db/m200000_000000_create_table_alldbdatatypes.php b/tests/specs/x_db_type/edit_column/pgsql/app/migrations_pgsql_db/m200000_000001_create_table_alldbdatatypes.php similarity index 98% rename from tests/specs/x_db_type/edit_column/pgsql/app/migrations_pgsql_db/m200000_000000_create_table_alldbdatatypes.php rename to tests/specs/x_db_type/edit_column/pgsql/app/migrations_pgsql_db/m200000_000001_create_table_alldbdatatypes.php index e0cac52a..7f8403d4 100644 --- a/tests/specs/x_db_type/edit_column/pgsql/app/migrations_pgsql_db/m200000_000000_create_table_alldbdatatypes.php +++ b/tests/specs/x_db_type/edit_column/pgsql/app/migrations_pgsql_db/m200000_000001_create_table_alldbdatatypes.php @@ -3,7 +3,7 @@ /** * Table for Alldbdatatype */ -class m200000_000000_create_table_alldbdatatypes extends \yii\db\Migration +class m200000_000001_create_table_alldbdatatypes extends \yii\db\Migration { public function safeUp() { diff --git a/tests/specs/x_db_type/edit_column/pgsql/app/migrations_pgsql_db/m200000_000001_change_table_editcolumns.php b/tests/specs/x_db_type/edit_column/pgsql/app/migrations_pgsql_db/m200000_000003_change_table_editcolumns.php similarity index 98% rename from tests/specs/x_db_type/edit_column/pgsql/app/migrations_pgsql_db/m200000_000001_change_table_editcolumns.php rename to tests/specs/x_db_type/edit_column/pgsql/app/migrations_pgsql_db/m200000_000003_change_table_editcolumns.php index 5ad21a0a..da02d58f 100644 --- a/tests/specs/x_db_type/edit_column/pgsql/app/migrations_pgsql_db/m200000_000001_change_table_editcolumns.php +++ b/tests/specs/x_db_type/edit_column/pgsql/app/migrations_pgsql_db/m200000_000003_change_table_editcolumns.php @@ -3,7 +3,7 @@ /** * Table for Editcolumn */ -class m200000_000001_change_table_editcolumns extends \yii\db\Migration +class m200000_000003_change_table_editcolumns extends \yii\db\Migration { public function safeUp() { From fbb2e8c02ac196464644ad06d2f8e4b4f4caaf66 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Fri, 21 Jun 2024 19:58:51 +0530 Subject: [PATCH 021/358] Fix another failing tests --- ..._pristines.php => m200000_000000_create_table_pristines.php} | 2 +- ...types.php => m200000_000001_create_table_alldbdatatypes.php} | 2 +- ...tcolumns.php => m200000_000003_create_table_editcolumns.php} | 2 +- ..._pristines.php => m200000_000000_create_table_pristines.php} | 2 +- ...types.php => m200000_000001_create_table_alldbdatatypes.php} | 2 +- ...tcolumns.php => m200000_000003_create_table_editcolumns.php} | 2 +- ..._pristines.php => m200000_000000_create_table_pristines.php} | 2 +- ...types.php => m200000_000001_create_table_alldbdatatypes.php} | 2 +- ...tcolumns.php => m200000_000003_create_table_editcolumns.php} | 2 +- 9 files changed, 9 insertions(+), 9 deletions(-) rename tests/specs/x_db_type/new_column/maria/app/migrations_maria_db/{m200000_000003_create_table_pristines.php => m200000_000000_create_table_pristines.php} (93%) rename tests/specs/x_db_type/new_column/maria/app/migrations_maria_db/{m200000_000000_create_table_alldbdatatypes.php => m200000_000001_create_table_alldbdatatypes.php} (97%) rename tests/specs/x_db_type/new_column/maria/app/migrations_maria_db/{m200000_000001_create_table_editcolumns.php => m200000_000003_create_table_editcolumns.php} (93%) rename tests/specs/x_db_type/new_column/mysql/app/migrations_mysql_db/{m200000_000003_create_table_pristines.php => m200000_000000_create_table_pristines.php} (93%) rename tests/specs/x_db_type/new_column/mysql/app/migrations_mysql_db/{m200000_000000_create_table_alldbdatatypes.php => m200000_000001_create_table_alldbdatatypes.php} (97%) rename tests/specs/x_db_type/new_column/mysql/app/migrations_mysql_db/{m200000_000001_create_table_editcolumns.php => m200000_000003_create_table_editcolumns.php} (93%) rename tests/specs/x_db_type/new_column/pgsql/app/migrations_pgsql_db/{m200000_000003_create_table_pristines.php => m200000_000000_create_table_pristines.php} (93%) rename tests/specs/x_db_type/new_column/pgsql/app/migrations_pgsql_db/{m200000_000000_create_table_alldbdatatypes.php => m200000_000001_create_table_alldbdatatypes.php} (98%) rename tests/specs/x_db_type/new_column/pgsql/app/migrations_pgsql_db/{m200000_000001_create_table_editcolumns.php => m200000_000003_create_table_editcolumns.php} (94%) diff --git a/tests/specs/x_db_type/new_column/maria/app/migrations_maria_db/m200000_000003_create_table_pristines.php b/tests/specs/x_db_type/new_column/maria/app/migrations_maria_db/m200000_000000_create_table_pristines.php similarity index 93% rename from tests/specs/x_db_type/new_column/maria/app/migrations_maria_db/m200000_000003_create_table_pristines.php rename to tests/specs/x_db_type/new_column/maria/app/migrations_maria_db/m200000_000000_create_table_pristines.php index 1e27d8d6..d1594797 100644 --- a/tests/specs/x_db_type/new_column/maria/app/migrations_maria_db/m200000_000003_create_table_pristines.php +++ b/tests/specs/x_db_type/new_column/maria/app/migrations_maria_db/m200000_000000_create_table_pristines.php @@ -3,7 +3,7 @@ /** * Table for Pristine */ -class m200000_000003_create_table_pristines extends \yii\db\Migration +class m200000_000000_create_table_pristines extends \yii\db\Migration { public function up() { diff --git a/tests/specs/x_db_type/new_column/maria/app/migrations_maria_db/m200000_000000_create_table_alldbdatatypes.php b/tests/specs/x_db_type/new_column/maria/app/migrations_maria_db/m200000_000001_create_table_alldbdatatypes.php similarity index 97% rename from tests/specs/x_db_type/new_column/maria/app/migrations_maria_db/m200000_000000_create_table_alldbdatatypes.php rename to tests/specs/x_db_type/new_column/maria/app/migrations_maria_db/m200000_000001_create_table_alldbdatatypes.php index 9c002bea..350eedaf 100644 --- a/tests/specs/x_db_type/new_column/maria/app/migrations_maria_db/m200000_000000_create_table_alldbdatatypes.php +++ b/tests/specs/x_db_type/new_column/maria/app/migrations_maria_db/m200000_000001_create_table_alldbdatatypes.php @@ -3,7 +3,7 @@ /** * Table for Alldbdatatype */ -class m200000_000000_create_table_alldbdatatypes extends \yii\db\Migration +class m200000_000001_create_table_alldbdatatypes extends \yii\db\Migration { public function up() { diff --git a/tests/specs/x_db_type/new_column/maria/app/migrations_maria_db/m200000_000001_create_table_editcolumns.php b/tests/specs/x_db_type/new_column/maria/app/migrations_maria_db/m200000_000003_create_table_editcolumns.php similarity index 93% rename from tests/specs/x_db_type/new_column/maria/app/migrations_maria_db/m200000_000001_create_table_editcolumns.php rename to tests/specs/x_db_type/new_column/maria/app/migrations_maria_db/m200000_000003_create_table_editcolumns.php index 1de3d8d5..1c4a0331 100644 --- a/tests/specs/x_db_type/new_column/maria/app/migrations_maria_db/m200000_000001_create_table_editcolumns.php +++ b/tests/specs/x_db_type/new_column/maria/app/migrations_maria_db/m200000_000003_create_table_editcolumns.php @@ -3,7 +3,7 @@ /** * Table for Editcolumn */ -class m200000_000001_create_table_editcolumns extends \yii\db\Migration +class m200000_000003_create_table_editcolumns extends \yii\db\Migration { public function up() { diff --git a/tests/specs/x_db_type/new_column/mysql/app/migrations_mysql_db/m200000_000003_create_table_pristines.php b/tests/specs/x_db_type/new_column/mysql/app/migrations_mysql_db/m200000_000000_create_table_pristines.php similarity index 93% rename from tests/specs/x_db_type/new_column/mysql/app/migrations_mysql_db/m200000_000003_create_table_pristines.php rename to tests/specs/x_db_type/new_column/mysql/app/migrations_mysql_db/m200000_000000_create_table_pristines.php index 3e9e8e02..ab96f730 100644 --- a/tests/specs/x_db_type/new_column/mysql/app/migrations_mysql_db/m200000_000003_create_table_pristines.php +++ b/tests/specs/x_db_type/new_column/mysql/app/migrations_mysql_db/m200000_000000_create_table_pristines.php @@ -3,7 +3,7 @@ /** * Table for Pristine */ -class m200000_000003_create_table_pristines extends \yii\db\Migration +class m200000_000000_create_table_pristines extends \yii\db\Migration { public function up() { diff --git a/tests/specs/x_db_type/new_column/mysql/app/migrations_mysql_db/m200000_000000_create_table_alldbdatatypes.php b/tests/specs/x_db_type/new_column/mysql/app/migrations_mysql_db/m200000_000001_create_table_alldbdatatypes.php similarity index 97% rename from tests/specs/x_db_type/new_column/mysql/app/migrations_mysql_db/m200000_000000_create_table_alldbdatatypes.php rename to tests/specs/x_db_type/new_column/mysql/app/migrations_mysql_db/m200000_000001_create_table_alldbdatatypes.php index 2cda660f..5f3d90d1 100644 --- a/tests/specs/x_db_type/new_column/mysql/app/migrations_mysql_db/m200000_000000_create_table_alldbdatatypes.php +++ b/tests/specs/x_db_type/new_column/mysql/app/migrations_mysql_db/m200000_000001_create_table_alldbdatatypes.php @@ -3,7 +3,7 @@ /** * Table for Alldbdatatype */ -class m200000_000000_create_table_alldbdatatypes extends \yii\db\Migration +class m200000_000001_create_table_alldbdatatypes extends \yii\db\Migration { public function up() { diff --git a/tests/specs/x_db_type/new_column/mysql/app/migrations_mysql_db/m200000_000001_create_table_editcolumns.php b/tests/specs/x_db_type/new_column/mysql/app/migrations_mysql_db/m200000_000003_create_table_editcolumns.php similarity index 93% rename from tests/specs/x_db_type/new_column/mysql/app/migrations_mysql_db/m200000_000001_create_table_editcolumns.php rename to tests/specs/x_db_type/new_column/mysql/app/migrations_mysql_db/m200000_000003_create_table_editcolumns.php index 8c84e731..81a1592d 100644 --- a/tests/specs/x_db_type/new_column/mysql/app/migrations_mysql_db/m200000_000001_create_table_editcolumns.php +++ b/tests/specs/x_db_type/new_column/mysql/app/migrations_mysql_db/m200000_000003_create_table_editcolumns.php @@ -3,7 +3,7 @@ /** * Table for Editcolumn */ -class m200000_000001_create_table_editcolumns extends \yii\db\Migration +class m200000_000003_create_table_editcolumns extends \yii\db\Migration { public function up() { diff --git a/tests/specs/x_db_type/new_column/pgsql/app/migrations_pgsql_db/m200000_000003_create_table_pristines.php b/tests/specs/x_db_type/new_column/pgsql/app/migrations_pgsql_db/m200000_000000_create_table_pristines.php similarity index 93% rename from tests/specs/x_db_type/new_column/pgsql/app/migrations_pgsql_db/m200000_000003_create_table_pristines.php rename to tests/specs/x_db_type/new_column/pgsql/app/migrations_pgsql_db/m200000_000000_create_table_pristines.php index aab6bb88..93b55396 100644 --- a/tests/specs/x_db_type/new_column/pgsql/app/migrations_pgsql_db/m200000_000003_create_table_pristines.php +++ b/tests/specs/x_db_type/new_column/pgsql/app/migrations_pgsql_db/m200000_000000_create_table_pristines.php @@ -3,7 +3,7 @@ /** * Table for Pristine */ -class m200000_000003_create_table_pristines extends \yii\db\Migration +class m200000_000000_create_table_pristines extends \yii\db\Migration { public function safeUp() { diff --git a/tests/specs/x_db_type/new_column/pgsql/app/migrations_pgsql_db/m200000_000000_create_table_alldbdatatypes.php b/tests/specs/x_db_type/new_column/pgsql/app/migrations_pgsql_db/m200000_000001_create_table_alldbdatatypes.php similarity index 98% rename from tests/specs/x_db_type/new_column/pgsql/app/migrations_pgsql_db/m200000_000000_create_table_alldbdatatypes.php rename to tests/specs/x_db_type/new_column/pgsql/app/migrations_pgsql_db/m200000_000001_create_table_alldbdatatypes.php index e0cac52a..7f8403d4 100644 --- a/tests/specs/x_db_type/new_column/pgsql/app/migrations_pgsql_db/m200000_000000_create_table_alldbdatatypes.php +++ b/tests/specs/x_db_type/new_column/pgsql/app/migrations_pgsql_db/m200000_000001_create_table_alldbdatatypes.php @@ -3,7 +3,7 @@ /** * Table for Alldbdatatype */ -class m200000_000000_create_table_alldbdatatypes extends \yii\db\Migration +class m200000_000001_create_table_alldbdatatypes extends \yii\db\Migration { public function safeUp() { diff --git a/tests/specs/x_db_type/new_column/pgsql/app/migrations_pgsql_db/m200000_000001_create_table_editcolumns.php b/tests/specs/x_db_type/new_column/pgsql/app/migrations_pgsql_db/m200000_000003_create_table_editcolumns.php similarity index 94% rename from tests/specs/x_db_type/new_column/pgsql/app/migrations_pgsql_db/m200000_000001_create_table_editcolumns.php rename to tests/specs/x_db_type/new_column/pgsql/app/migrations_pgsql_db/m200000_000003_create_table_editcolumns.php index b8f286b1..9679a0b8 100644 --- a/tests/specs/x_db_type/new_column/pgsql/app/migrations_pgsql_db/m200000_000001_create_table_editcolumns.php +++ b/tests/specs/x_db_type/new_column/pgsql/app/migrations_pgsql_db/m200000_000003_create_table_editcolumns.php @@ -3,7 +3,7 @@ /** * Table for Editcolumn */ -class m200000_000001_create_table_editcolumns extends \yii\db\Migration +class m200000_000003_create_table_editcolumns extends \yii\db\Migration { public function safeUp() { From 7d7dba7adf6c3b767b530a266126dc0b62425fe5 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Fri, 21 Jun 2024 20:00:56 +0530 Subject: [PATCH 022/358] Fix another failing tests - 2 --- ..._pristines.php => m200000_000000_create_table_pristines.php} | 2 +- ...types.php => m200000_000001_create_table_alldbdatatypes.php} | 2 +- ...tcolumns.php => m200000_000003_create_table_editcolumns.php} | 2 +- ..._pristines.php => m200000_000000_create_table_pristines.php} | 2 +- ...types.php => m200000_000001_create_table_alldbdatatypes.php} | 2 +- ...tcolumns.php => m200000_000003_create_table_editcolumns.php} | 2 +- ..._pristines.php => m200000_000000_create_table_pristines.php} | 2 +- ...types.php => m200000_000001_create_table_alldbdatatypes.php} | 2 +- ...tcolumns.php => m200000_000003_create_table_editcolumns.php} | 2 +- 9 files changed, 9 insertions(+), 9 deletions(-) rename tests/specs/x_db_type/fresh/maria/app/migrations_maria_db/{m200000_000003_create_table_pristines.php => m200000_000000_create_table_pristines.php} (93%) rename tests/specs/x_db_type/fresh/maria/app/migrations_maria_db/{m200000_000000_create_table_alldbdatatypes.php => m200000_000001_create_table_alldbdatatypes.php} (97%) rename tests/specs/x_db_type/fresh/maria/app/migrations_maria_db/{m200000_000001_create_table_editcolumns.php => m200000_000003_create_table_editcolumns.php} (93%) rename tests/specs/x_db_type/fresh/mysql/app/migrations_mysql_db/{m200000_000003_create_table_pristines.php => m200000_000000_create_table_pristines.php} (93%) rename tests/specs/x_db_type/fresh/mysql/app/migrations_mysql_db/{m200000_000000_create_table_alldbdatatypes.php => m200000_000001_create_table_alldbdatatypes.php} (97%) rename tests/specs/x_db_type/fresh/mysql/app/migrations_mysql_db/{m200000_000001_create_table_editcolumns.php => m200000_000003_create_table_editcolumns.php} (93%) rename tests/specs/x_db_type/fresh/pgsql/app/migrations_pgsql_db/{m200000_000003_create_table_pristines.php => m200000_000000_create_table_pristines.php} (93%) rename tests/specs/x_db_type/fresh/pgsql/app/migrations_pgsql_db/{m200000_000000_create_table_alldbdatatypes.php => m200000_000001_create_table_alldbdatatypes.php} (98%) rename tests/specs/x_db_type/fresh/pgsql/app/migrations_pgsql_db/{m200000_000001_create_table_editcolumns.php => m200000_000003_create_table_editcolumns.php} (94%) diff --git a/tests/specs/x_db_type/fresh/maria/app/migrations_maria_db/m200000_000003_create_table_pristines.php b/tests/specs/x_db_type/fresh/maria/app/migrations_maria_db/m200000_000000_create_table_pristines.php similarity index 93% rename from tests/specs/x_db_type/fresh/maria/app/migrations_maria_db/m200000_000003_create_table_pristines.php rename to tests/specs/x_db_type/fresh/maria/app/migrations_maria_db/m200000_000000_create_table_pristines.php index 1e27d8d6..d1594797 100644 --- a/tests/specs/x_db_type/fresh/maria/app/migrations_maria_db/m200000_000003_create_table_pristines.php +++ b/tests/specs/x_db_type/fresh/maria/app/migrations_maria_db/m200000_000000_create_table_pristines.php @@ -3,7 +3,7 @@ /** * Table for Pristine */ -class m200000_000003_create_table_pristines extends \yii\db\Migration +class m200000_000000_create_table_pristines extends \yii\db\Migration { public function up() { diff --git a/tests/specs/x_db_type/fresh/maria/app/migrations_maria_db/m200000_000000_create_table_alldbdatatypes.php b/tests/specs/x_db_type/fresh/maria/app/migrations_maria_db/m200000_000001_create_table_alldbdatatypes.php similarity index 97% rename from tests/specs/x_db_type/fresh/maria/app/migrations_maria_db/m200000_000000_create_table_alldbdatatypes.php rename to tests/specs/x_db_type/fresh/maria/app/migrations_maria_db/m200000_000001_create_table_alldbdatatypes.php index 9c002bea..350eedaf 100644 --- a/tests/specs/x_db_type/fresh/maria/app/migrations_maria_db/m200000_000000_create_table_alldbdatatypes.php +++ b/tests/specs/x_db_type/fresh/maria/app/migrations_maria_db/m200000_000001_create_table_alldbdatatypes.php @@ -3,7 +3,7 @@ /** * Table for Alldbdatatype */ -class m200000_000000_create_table_alldbdatatypes extends \yii\db\Migration +class m200000_000001_create_table_alldbdatatypes extends \yii\db\Migration { public function up() { diff --git a/tests/specs/x_db_type/fresh/maria/app/migrations_maria_db/m200000_000001_create_table_editcolumns.php b/tests/specs/x_db_type/fresh/maria/app/migrations_maria_db/m200000_000003_create_table_editcolumns.php similarity index 93% rename from tests/specs/x_db_type/fresh/maria/app/migrations_maria_db/m200000_000001_create_table_editcolumns.php rename to tests/specs/x_db_type/fresh/maria/app/migrations_maria_db/m200000_000003_create_table_editcolumns.php index 1de3d8d5..1c4a0331 100644 --- a/tests/specs/x_db_type/fresh/maria/app/migrations_maria_db/m200000_000001_create_table_editcolumns.php +++ b/tests/specs/x_db_type/fresh/maria/app/migrations_maria_db/m200000_000003_create_table_editcolumns.php @@ -3,7 +3,7 @@ /** * Table for Editcolumn */ -class m200000_000001_create_table_editcolumns extends \yii\db\Migration +class m200000_000003_create_table_editcolumns extends \yii\db\Migration { public function up() { diff --git a/tests/specs/x_db_type/fresh/mysql/app/migrations_mysql_db/m200000_000003_create_table_pristines.php b/tests/specs/x_db_type/fresh/mysql/app/migrations_mysql_db/m200000_000000_create_table_pristines.php similarity index 93% rename from tests/specs/x_db_type/fresh/mysql/app/migrations_mysql_db/m200000_000003_create_table_pristines.php rename to tests/specs/x_db_type/fresh/mysql/app/migrations_mysql_db/m200000_000000_create_table_pristines.php index 3e9e8e02..ab96f730 100644 --- a/tests/specs/x_db_type/fresh/mysql/app/migrations_mysql_db/m200000_000003_create_table_pristines.php +++ b/tests/specs/x_db_type/fresh/mysql/app/migrations_mysql_db/m200000_000000_create_table_pristines.php @@ -3,7 +3,7 @@ /** * Table for Pristine */ -class m200000_000003_create_table_pristines extends \yii\db\Migration +class m200000_000000_create_table_pristines extends \yii\db\Migration { public function up() { diff --git a/tests/specs/x_db_type/fresh/mysql/app/migrations_mysql_db/m200000_000000_create_table_alldbdatatypes.php b/tests/specs/x_db_type/fresh/mysql/app/migrations_mysql_db/m200000_000001_create_table_alldbdatatypes.php similarity index 97% rename from tests/specs/x_db_type/fresh/mysql/app/migrations_mysql_db/m200000_000000_create_table_alldbdatatypes.php rename to tests/specs/x_db_type/fresh/mysql/app/migrations_mysql_db/m200000_000001_create_table_alldbdatatypes.php index 2cda660f..5f3d90d1 100644 --- a/tests/specs/x_db_type/fresh/mysql/app/migrations_mysql_db/m200000_000000_create_table_alldbdatatypes.php +++ b/tests/specs/x_db_type/fresh/mysql/app/migrations_mysql_db/m200000_000001_create_table_alldbdatatypes.php @@ -3,7 +3,7 @@ /** * Table for Alldbdatatype */ -class m200000_000000_create_table_alldbdatatypes extends \yii\db\Migration +class m200000_000001_create_table_alldbdatatypes extends \yii\db\Migration { public function up() { diff --git a/tests/specs/x_db_type/fresh/mysql/app/migrations_mysql_db/m200000_000001_create_table_editcolumns.php b/tests/specs/x_db_type/fresh/mysql/app/migrations_mysql_db/m200000_000003_create_table_editcolumns.php similarity index 93% rename from tests/specs/x_db_type/fresh/mysql/app/migrations_mysql_db/m200000_000001_create_table_editcolumns.php rename to tests/specs/x_db_type/fresh/mysql/app/migrations_mysql_db/m200000_000003_create_table_editcolumns.php index 8c84e731..81a1592d 100644 --- a/tests/specs/x_db_type/fresh/mysql/app/migrations_mysql_db/m200000_000001_create_table_editcolumns.php +++ b/tests/specs/x_db_type/fresh/mysql/app/migrations_mysql_db/m200000_000003_create_table_editcolumns.php @@ -3,7 +3,7 @@ /** * Table for Editcolumn */ -class m200000_000001_create_table_editcolumns extends \yii\db\Migration +class m200000_000003_create_table_editcolumns extends \yii\db\Migration { public function up() { diff --git a/tests/specs/x_db_type/fresh/pgsql/app/migrations_pgsql_db/m200000_000003_create_table_pristines.php b/tests/specs/x_db_type/fresh/pgsql/app/migrations_pgsql_db/m200000_000000_create_table_pristines.php similarity index 93% rename from tests/specs/x_db_type/fresh/pgsql/app/migrations_pgsql_db/m200000_000003_create_table_pristines.php rename to tests/specs/x_db_type/fresh/pgsql/app/migrations_pgsql_db/m200000_000000_create_table_pristines.php index aab6bb88..93b55396 100644 --- a/tests/specs/x_db_type/fresh/pgsql/app/migrations_pgsql_db/m200000_000003_create_table_pristines.php +++ b/tests/specs/x_db_type/fresh/pgsql/app/migrations_pgsql_db/m200000_000000_create_table_pristines.php @@ -3,7 +3,7 @@ /** * Table for Pristine */ -class m200000_000003_create_table_pristines extends \yii\db\Migration +class m200000_000000_create_table_pristines extends \yii\db\Migration { public function safeUp() { diff --git a/tests/specs/x_db_type/fresh/pgsql/app/migrations_pgsql_db/m200000_000000_create_table_alldbdatatypes.php b/tests/specs/x_db_type/fresh/pgsql/app/migrations_pgsql_db/m200000_000001_create_table_alldbdatatypes.php similarity index 98% rename from tests/specs/x_db_type/fresh/pgsql/app/migrations_pgsql_db/m200000_000000_create_table_alldbdatatypes.php rename to tests/specs/x_db_type/fresh/pgsql/app/migrations_pgsql_db/m200000_000001_create_table_alldbdatatypes.php index e0cac52a..7f8403d4 100644 --- a/tests/specs/x_db_type/fresh/pgsql/app/migrations_pgsql_db/m200000_000000_create_table_alldbdatatypes.php +++ b/tests/specs/x_db_type/fresh/pgsql/app/migrations_pgsql_db/m200000_000001_create_table_alldbdatatypes.php @@ -3,7 +3,7 @@ /** * Table for Alldbdatatype */ -class m200000_000000_create_table_alldbdatatypes extends \yii\db\Migration +class m200000_000001_create_table_alldbdatatypes extends \yii\db\Migration { public function safeUp() { diff --git a/tests/specs/x_db_type/fresh/pgsql/app/migrations_pgsql_db/m200000_000001_create_table_editcolumns.php b/tests/specs/x_db_type/fresh/pgsql/app/migrations_pgsql_db/m200000_000003_create_table_editcolumns.php similarity index 94% rename from tests/specs/x_db_type/fresh/pgsql/app/migrations_pgsql_db/m200000_000001_create_table_editcolumns.php rename to tests/specs/x_db_type/fresh/pgsql/app/migrations_pgsql_db/m200000_000003_create_table_editcolumns.php index b8f286b1..9679a0b8 100644 --- a/tests/specs/x_db_type/fresh/pgsql/app/migrations_pgsql_db/m200000_000001_create_table_editcolumns.php +++ b/tests/specs/x_db_type/fresh/pgsql/app/migrations_pgsql_db/m200000_000003_create_table_editcolumns.php @@ -3,7 +3,7 @@ /** * Table for Editcolumn */ -class m200000_000001_create_table_editcolumns extends \yii\db\Migration +class m200000_000003_create_table_editcolumns extends \yii\db\Migration { public function safeUp() { From 51ebfd70991c56ae51a141979a227742f9e69cee Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Fri, 21 Jun 2024 20:02:40 +0530 Subject: [PATCH 023/358] Fix another failing tests - 3 --- ...le_accounts.php => m200000_000000_create_table_accounts.php} | 2 +- ...able_domains.php => m200000_000001_create_table_domains.php} | 2 +- ...te_table_d123s.php => m200000_000002_create_table_d123s.php} | 2 +- ...te_table_c123s.php => m200000_000003_create_table_c123s.php} | 2 +- ...te_table_b123s.php => m200000_000004_create_table_b123s.php} | 2 +- ...te_table_a123s.php => m200000_000005_create_table_a123s.php} | 2 +- ...le_routings.php => m200000_000006_create_table_routings.php} | 2 +- ...te_table_e123s.php => m200000_000007_create_table_e123s.php} | 2 +- 8 files changed, 8 insertions(+), 8 deletions(-) rename tests/specs/relations_in_faker/app/migrations_pgsql_db/{m200000_000003_create_table_accounts.php => m200000_000000_create_table_accounts.php} (83%) rename tests/specs/relations_in_faker/app/migrations_pgsql_db/{m200000_000005_create_table_domains.php => m200000_000001_create_table_domains.php} (90%) rename tests/specs/relations_in_faker/app/migrations_pgsql_db/{m200000_000004_create_table_d123s.php => m200000_000002_create_table_d123s.php} (83%) rename tests/specs/relations_in_faker/app/migrations_pgsql_db/{m200000_000000_create_table_c123s.php => m200000_000003_create_table_c123s.php} (83%) rename tests/specs/relations_in_faker/app/migrations_pgsql_db/{m200000_000001_create_table_b123s.php => m200000_000004_create_table_b123s.php} (89%) rename tests/specs/relations_in_faker/app/migrations_pgsql_db/{m200000_000002_create_table_a123s.php => m200000_000005_create_table_a123s.php} (89%) rename tests/specs/relations_in_faker/app/migrations_pgsql_db/{m200000_000007_create_table_routings.php => m200000_000006_create_table_routings.php} (95%) rename tests/specs/relations_in_faker/app/migrations_pgsql_db/{m200000_000006_create_table_e123s.php => m200000_000007_create_table_e123s.php} (89%) diff --git a/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000003_create_table_accounts.php b/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000000_create_table_accounts.php similarity index 83% rename from tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000003_create_table_accounts.php rename to tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000000_create_table_accounts.php index 8eba95b2..ef607707 100644 --- a/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000003_create_table_accounts.php +++ b/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000000_create_table_accounts.php @@ -3,7 +3,7 @@ /** * Table for Account */ -class m200000_000003_create_table_accounts extends \yii\db\Migration +class m200000_000000_create_table_accounts extends \yii\db\Migration { public function safeUp() { diff --git a/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000005_create_table_domains.php b/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000001_create_table_domains.php similarity index 90% rename from tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000005_create_table_domains.php rename to tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000001_create_table_domains.php index c830fe7e..5c2336fe 100644 --- a/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000005_create_table_domains.php +++ b/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000001_create_table_domains.php @@ -3,7 +3,7 @@ /** * Table for Domain */ -class m200000_000005_create_table_domains extends \yii\db\Migration +class m200000_000001_create_table_domains extends \yii\db\Migration { public function safeUp() { diff --git a/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000004_create_table_d123s.php b/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000002_create_table_d123s.php similarity index 83% rename from tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000004_create_table_d123s.php rename to tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000002_create_table_d123s.php index 794186a8..5deaa47d 100644 --- a/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000004_create_table_d123s.php +++ b/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000002_create_table_d123s.php @@ -3,7 +3,7 @@ /** * Table for D123 */ -class m200000_000004_create_table_d123s extends \yii\db\Migration +class m200000_000002_create_table_d123s extends \yii\db\Migration { public function safeUp() { diff --git a/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000000_create_table_c123s.php b/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000003_create_table_c123s.php similarity index 83% rename from tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000000_create_table_c123s.php rename to tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000003_create_table_c123s.php index 0c9c1c80..f2dcc3ff 100644 --- a/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000000_create_table_c123s.php +++ b/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000003_create_table_c123s.php @@ -3,7 +3,7 @@ /** * Table for C123 */ -class m200000_000000_create_table_c123s extends \yii\db\Migration +class m200000_000003_create_table_c123s extends \yii\db\Migration { public function safeUp() { diff --git a/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000001_create_table_b123s.php b/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000004_create_table_b123s.php similarity index 89% rename from tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000001_create_table_b123s.php rename to tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000004_create_table_b123s.php index 908bd998..0d719651 100644 --- a/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000001_create_table_b123s.php +++ b/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000004_create_table_b123s.php @@ -3,7 +3,7 @@ /** * Table for B123 */ -class m200000_000001_create_table_b123s extends \yii\db\Migration +class m200000_000004_create_table_b123s extends \yii\db\Migration { public function safeUp() { diff --git a/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000002_create_table_a123s.php b/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000005_create_table_a123s.php similarity index 89% rename from tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000002_create_table_a123s.php rename to tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000005_create_table_a123s.php index 73c70ae2..8a9b4737 100644 --- a/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000002_create_table_a123s.php +++ b/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000005_create_table_a123s.php @@ -3,7 +3,7 @@ /** * Table for A123 */ -class m200000_000002_create_table_a123s extends \yii\db\Migration +class m200000_000005_create_table_a123s extends \yii\db\Migration { public function safeUp() { diff --git a/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000007_create_table_routings.php b/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000006_create_table_routings.php similarity index 95% rename from tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000007_create_table_routings.php rename to tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000006_create_table_routings.php index 98ac2ad9..5fd62f40 100644 --- a/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000007_create_table_routings.php +++ b/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000006_create_table_routings.php @@ -3,7 +3,7 @@ /** * Table for Routing */ -class m200000_000007_create_table_routings extends \yii\db\Migration +class m200000_000006_create_table_routings extends \yii\db\Migration { public function safeUp() { diff --git a/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000006_create_table_e123s.php b/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000007_create_table_e123s.php similarity index 89% rename from tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000006_create_table_e123s.php rename to tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000007_create_table_e123s.php index f8d58a41..bce7944e 100644 --- a/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000006_create_table_e123s.php +++ b/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000007_create_table_e123s.php @@ -3,7 +3,7 @@ /** * Table for E123 */ -class m200000_000006_create_table_e123s extends \yii\db\Migration +class m200000_000007_create_table_e123s extends \yii\db\Migration { public function safeUp() { From 0dbad7ce4fdae317ed0d5ba06edb64cfc3d873a0 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Fri, 21 Jun 2024 20:05:03 +0530 Subject: [PATCH 024/358] Fix another failing tests - 4 --- ..._pristines.php => m200000_000000_create_table_pristines.php} | 2 +- ...tcolumns.php => m200000_000002_create_table_editcolumns.php} | 2 +- ..._pristines.php => m200000_000000_create_table_pristines.php} | 2 +- ...tcolumns.php => m200000_000002_create_table_editcolumns.php} | 2 +- ..._pristines.php => m200000_000000_create_table_pristines.php} | 2 +- ...tcolumns.php => m200000_000002_create_table_editcolumns.php} | 2 +- 6 files changed, 6 insertions(+), 6 deletions(-) rename tests/specs/enum/fresh/maria/app/migrations_maria_db/{m200000_000002_create_table_pristines.php => m200000_000000_create_table_pristines.php} (84%) rename tests/specs/enum/fresh/maria/app/migrations_maria_db/{m200000_000000_create_table_editcolumns.php => m200000_000002_create_table_editcolumns.php} (88%) rename tests/specs/enum/fresh/mysql/app/migrations_mysql_db/{m200000_000002_create_table_pristines.php => m200000_000000_create_table_pristines.php} (84%) rename tests/specs/enum/fresh/mysql/app/migrations_mysql_db/{m200000_000000_create_table_editcolumns.php => m200000_000002_create_table_editcolumns.php} (88%) rename tests/specs/enum/fresh/pgsql/app/migrations_pgsql_db/{m200000_000002_create_table_pristines.php => m200000_000000_create_table_pristines.php} (89%) rename tests/specs/enum/fresh/pgsql/app/migrations_pgsql_db/{m200000_000000_create_table_editcolumns.php => m200000_000002_create_table_editcolumns.php} (93%) diff --git a/tests/specs/enum/fresh/maria/app/migrations_maria_db/m200000_000002_create_table_pristines.php b/tests/specs/enum/fresh/maria/app/migrations_maria_db/m200000_000000_create_table_pristines.php similarity index 84% rename from tests/specs/enum/fresh/maria/app/migrations_maria_db/m200000_000002_create_table_pristines.php rename to tests/specs/enum/fresh/maria/app/migrations_maria_db/m200000_000000_create_table_pristines.php index bdd46f98..2b602da7 100644 --- a/tests/specs/enum/fresh/maria/app/migrations_maria_db/m200000_000002_create_table_pristines.php +++ b/tests/specs/enum/fresh/maria/app/migrations_maria_db/m200000_000000_create_table_pristines.php @@ -3,7 +3,7 @@ /** * Table for Pristine */ -class m200000_000002_create_table_pristines extends \yii\db\Migration +class m200000_000000_create_table_pristines extends \yii\db\Migration { public function up() { diff --git a/tests/specs/enum/fresh/maria/app/migrations_maria_db/m200000_000000_create_table_editcolumns.php b/tests/specs/enum/fresh/maria/app/migrations_maria_db/m200000_000002_create_table_editcolumns.php similarity index 88% rename from tests/specs/enum/fresh/maria/app/migrations_maria_db/m200000_000000_create_table_editcolumns.php rename to tests/specs/enum/fresh/maria/app/migrations_maria_db/m200000_000002_create_table_editcolumns.php index 1d2581bf..d4e6b085 100644 --- a/tests/specs/enum/fresh/maria/app/migrations_maria_db/m200000_000000_create_table_editcolumns.php +++ b/tests/specs/enum/fresh/maria/app/migrations_maria_db/m200000_000002_create_table_editcolumns.php @@ -3,7 +3,7 @@ /** * Table for Editcolumn */ -class m200000_000000_create_table_editcolumns extends \yii\db\Migration +class m200000_000002_create_table_editcolumns extends \yii\db\Migration { public function up() { diff --git a/tests/specs/enum/fresh/mysql/app/migrations_mysql_db/m200000_000002_create_table_pristines.php b/tests/specs/enum/fresh/mysql/app/migrations_mysql_db/m200000_000000_create_table_pristines.php similarity index 84% rename from tests/specs/enum/fresh/mysql/app/migrations_mysql_db/m200000_000002_create_table_pristines.php rename to tests/specs/enum/fresh/mysql/app/migrations_mysql_db/m200000_000000_create_table_pristines.php index bdd46f98..2b602da7 100644 --- a/tests/specs/enum/fresh/mysql/app/migrations_mysql_db/m200000_000002_create_table_pristines.php +++ b/tests/specs/enum/fresh/mysql/app/migrations_mysql_db/m200000_000000_create_table_pristines.php @@ -3,7 +3,7 @@ /** * Table for Pristine */ -class m200000_000002_create_table_pristines extends \yii\db\Migration +class m200000_000000_create_table_pristines extends \yii\db\Migration { public function up() { diff --git a/tests/specs/enum/fresh/mysql/app/migrations_mysql_db/m200000_000000_create_table_editcolumns.php b/tests/specs/enum/fresh/mysql/app/migrations_mysql_db/m200000_000002_create_table_editcolumns.php similarity index 88% rename from tests/specs/enum/fresh/mysql/app/migrations_mysql_db/m200000_000000_create_table_editcolumns.php rename to tests/specs/enum/fresh/mysql/app/migrations_mysql_db/m200000_000002_create_table_editcolumns.php index 3aeb5b25..241a5fd7 100644 --- a/tests/specs/enum/fresh/mysql/app/migrations_mysql_db/m200000_000000_create_table_editcolumns.php +++ b/tests/specs/enum/fresh/mysql/app/migrations_mysql_db/m200000_000002_create_table_editcolumns.php @@ -3,7 +3,7 @@ /** * Table for Editcolumn */ -class m200000_000000_create_table_editcolumns extends \yii\db\Migration +class m200000_000002_create_table_editcolumns extends \yii\db\Migration { public function up() { diff --git a/tests/specs/enum/fresh/pgsql/app/migrations_pgsql_db/m200000_000002_create_table_pristines.php b/tests/specs/enum/fresh/pgsql/app/migrations_pgsql_db/m200000_000000_create_table_pristines.php similarity index 89% rename from tests/specs/enum/fresh/pgsql/app/migrations_pgsql_db/m200000_000002_create_table_pristines.php rename to tests/specs/enum/fresh/pgsql/app/migrations_pgsql_db/m200000_000000_create_table_pristines.php index 45b63115..e336e5e2 100644 --- a/tests/specs/enum/fresh/pgsql/app/migrations_pgsql_db/m200000_000002_create_table_pristines.php +++ b/tests/specs/enum/fresh/pgsql/app/migrations_pgsql_db/m200000_000000_create_table_pristines.php @@ -3,7 +3,7 @@ /** * Table for Pristine */ -class m200000_000002_create_table_pristines extends \yii\db\Migration +class m200000_000000_create_table_pristines extends \yii\db\Migration { public function safeUp() { diff --git a/tests/specs/enum/fresh/pgsql/app/migrations_pgsql_db/m200000_000000_create_table_editcolumns.php b/tests/specs/enum/fresh/pgsql/app/migrations_pgsql_db/m200000_000002_create_table_editcolumns.php similarity index 93% rename from tests/specs/enum/fresh/pgsql/app/migrations_pgsql_db/m200000_000000_create_table_editcolumns.php rename to tests/specs/enum/fresh/pgsql/app/migrations_pgsql_db/m200000_000002_create_table_editcolumns.php index 5180bf54..36bbb3fa 100644 --- a/tests/specs/enum/fresh/pgsql/app/migrations_pgsql_db/m200000_000000_create_table_editcolumns.php +++ b/tests/specs/enum/fresh/pgsql/app/migrations_pgsql_db/m200000_000002_create_table_editcolumns.php @@ -3,7 +3,7 @@ /** * Table for Editcolumn */ -class m200000_000000_create_table_editcolumns extends \yii\db\Migration +class m200000_000002_create_table_editcolumns extends \yii\db\Migration { public function safeUp() { From 72b927b270822ecbc161ee5bbe6e2d8b9243c782 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Fri, 21 Jun 2024 20:06:39 +0530 Subject: [PATCH 025/358] Fix another failing tests - EnumTest::testAddNewColumn --- ..._pristines.php => m200000_000000_create_table_pristines.php} | 2 +- ...tcolumns.php => m200000_000002_create_table_editcolumns.php} | 2 +- ..._pristines.php => m200000_000000_create_table_pristines.php} | 2 +- ...tcolumns.php => m200000_000002_create_table_editcolumns.php} | 2 +- ..._pristines.php => m200000_000000_create_table_pristines.php} | 2 +- ...tcolumns.php => m200000_000002_create_table_editcolumns.php} | 2 +- 6 files changed, 6 insertions(+), 6 deletions(-) rename tests/specs/enum/new_column/maria/app/migrations_maria_db/{m200000_000002_create_table_pristines.php => m200000_000000_create_table_pristines.php} (84%) rename tests/specs/enum/new_column/maria/app/migrations_maria_db/{m200000_000000_create_table_editcolumns.php => m200000_000002_create_table_editcolumns.php} (88%) rename tests/specs/enum/new_column/mysql/app/migrations_mysql_db/{m200000_000002_create_table_pristines.php => m200000_000000_create_table_pristines.php} (84%) rename tests/specs/enum/new_column/mysql/app/migrations_mysql_db/{m200000_000000_create_table_editcolumns.php => m200000_000002_create_table_editcolumns.php} (88%) rename tests/specs/enum/new_column/pgsql/app/migrations_pgsql_db/{m200000_000002_create_table_pristines.php => m200000_000000_create_table_pristines.php} (89%) rename tests/specs/enum/new_column/pgsql/app/migrations_pgsql_db/{m200000_000000_create_table_editcolumns.php => m200000_000002_create_table_editcolumns.php} (93%) diff --git a/tests/specs/enum/new_column/maria/app/migrations_maria_db/m200000_000002_create_table_pristines.php b/tests/specs/enum/new_column/maria/app/migrations_maria_db/m200000_000000_create_table_pristines.php similarity index 84% rename from tests/specs/enum/new_column/maria/app/migrations_maria_db/m200000_000002_create_table_pristines.php rename to tests/specs/enum/new_column/maria/app/migrations_maria_db/m200000_000000_create_table_pristines.php index bdd46f98..2b602da7 100644 --- a/tests/specs/enum/new_column/maria/app/migrations_maria_db/m200000_000002_create_table_pristines.php +++ b/tests/specs/enum/new_column/maria/app/migrations_maria_db/m200000_000000_create_table_pristines.php @@ -3,7 +3,7 @@ /** * Table for Pristine */ -class m200000_000002_create_table_pristines extends \yii\db\Migration +class m200000_000000_create_table_pristines extends \yii\db\Migration { public function up() { diff --git a/tests/specs/enum/new_column/maria/app/migrations_maria_db/m200000_000000_create_table_editcolumns.php b/tests/specs/enum/new_column/maria/app/migrations_maria_db/m200000_000002_create_table_editcolumns.php similarity index 88% rename from tests/specs/enum/new_column/maria/app/migrations_maria_db/m200000_000000_create_table_editcolumns.php rename to tests/specs/enum/new_column/maria/app/migrations_maria_db/m200000_000002_create_table_editcolumns.php index 1d2581bf..d4e6b085 100644 --- a/tests/specs/enum/new_column/maria/app/migrations_maria_db/m200000_000000_create_table_editcolumns.php +++ b/tests/specs/enum/new_column/maria/app/migrations_maria_db/m200000_000002_create_table_editcolumns.php @@ -3,7 +3,7 @@ /** * Table for Editcolumn */ -class m200000_000000_create_table_editcolumns extends \yii\db\Migration +class m200000_000002_create_table_editcolumns extends \yii\db\Migration { public function up() { diff --git a/tests/specs/enum/new_column/mysql/app/migrations_mysql_db/m200000_000002_create_table_pristines.php b/tests/specs/enum/new_column/mysql/app/migrations_mysql_db/m200000_000000_create_table_pristines.php similarity index 84% rename from tests/specs/enum/new_column/mysql/app/migrations_mysql_db/m200000_000002_create_table_pristines.php rename to tests/specs/enum/new_column/mysql/app/migrations_mysql_db/m200000_000000_create_table_pristines.php index bdd46f98..2b602da7 100644 --- a/tests/specs/enum/new_column/mysql/app/migrations_mysql_db/m200000_000002_create_table_pristines.php +++ b/tests/specs/enum/new_column/mysql/app/migrations_mysql_db/m200000_000000_create_table_pristines.php @@ -3,7 +3,7 @@ /** * Table for Pristine */ -class m200000_000002_create_table_pristines extends \yii\db\Migration +class m200000_000000_create_table_pristines extends \yii\db\Migration { public function up() { diff --git a/tests/specs/enum/new_column/mysql/app/migrations_mysql_db/m200000_000000_create_table_editcolumns.php b/tests/specs/enum/new_column/mysql/app/migrations_mysql_db/m200000_000002_create_table_editcolumns.php similarity index 88% rename from tests/specs/enum/new_column/mysql/app/migrations_mysql_db/m200000_000000_create_table_editcolumns.php rename to tests/specs/enum/new_column/mysql/app/migrations_mysql_db/m200000_000002_create_table_editcolumns.php index 3aeb5b25..241a5fd7 100644 --- a/tests/specs/enum/new_column/mysql/app/migrations_mysql_db/m200000_000000_create_table_editcolumns.php +++ b/tests/specs/enum/new_column/mysql/app/migrations_mysql_db/m200000_000002_create_table_editcolumns.php @@ -3,7 +3,7 @@ /** * Table for Editcolumn */ -class m200000_000000_create_table_editcolumns extends \yii\db\Migration +class m200000_000002_create_table_editcolumns extends \yii\db\Migration { public function up() { diff --git a/tests/specs/enum/new_column/pgsql/app/migrations_pgsql_db/m200000_000002_create_table_pristines.php b/tests/specs/enum/new_column/pgsql/app/migrations_pgsql_db/m200000_000000_create_table_pristines.php similarity index 89% rename from tests/specs/enum/new_column/pgsql/app/migrations_pgsql_db/m200000_000002_create_table_pristines.php rename to tests/specs/enum/new_column/pgsql/app/migrations_pgsql_db/m200000_000000_create_table_pristines.php index 45b63115..e336e5e2 100644 --- a/tests/specs/enum/new_column/pgsql/app/migrations_pgsql_db/m200000_000002_create_table_pristines.php +++ b/tests/specs/enum/new_column/pgsql/app/migrations_pgsql_db/m200000_000000_create_table_pristines.php @@ -3,7 +3,7 @@ /** * Table for Pristine */ -class m200000_000002_create_table_pristines extends \yii\db\Migration +class m200000_000000_create_table_pristines extends \yii\db\Migration { public function safeUp() { diff --git a/tests/specs/enum/new_column/pgsql/app/migrations_pgsql_db/m200000_000000_create_table_editcolumns.php b/tests/specs/enum/new_column/pgsql/app/migrations_pgsql_db/m200000_000002_create_table_editcolumns.php similarity index 93% rename from tests/specs/enum/new_column/pgsql/app/migrations_pgsql_db/m200000_000000_create_table_editcolumns.php rename to tests/specs/enum/new_column/pgsql/app/migrations_pgsql_db/m200000_000002_create_table_editcolumns.php index 5180bf54..36bbb3fa 100644 --- a/tests/specs/enum/new_column/pgsql/app/migrations_pgsql_db/m200000_000000_create_table_editcolumns.php +++ b/tests/specs/enum/new_column/pgsql/app/migrations_pgsql_db/m200000_000002_create_table_editcolumns.php @@ -3,7 +3,7 @@ /** * Table for Editcolumn */ -class m200000_000000_create_table_editcolumns extends \yii\db\Migration +class m200000_000002_create_table_editcolumns extends \yii\db\Migration { public function safeUp() { From ad7b022c48a2f263fea0cec59d8db9b0cbc49a68 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Fri, 21 Jun 2024 20:08:15 +0530 Subject: [PATCH 026/358] Fix another failing tests - EnumTest::testChangeToAndFromEnum --- ..._pristines.php => m200000_000000_create_table_pristines.php} | 2 +- ...tcolumns.php => m200000_000002_change_table_editcolumns.php} | 2 +- ..._pristines.php => m200000_000000_create_table_pristines.php} | 2 +- ...tcolumns.php => m200000_000002_change_table_editcolumns.php} | 2 +- ..._pristines.php => m200000_000000_create_table_pristines.php} | 2 +- ...tcolumns.php => m200000_000002_change_table_editcolumns.php} | 2 +- 6 files changed, 6 insertions(+), 6 deletions(-) rename tests/specs/enum/change/maria/app/migrations_maria_db/{m200000_000002_create_table_pristines.php => m200000_000000_create_table_pristines.php} (84%) rename tests/specs/enum/change/maria/app/migrations_maria_db/{m200000_000000_change_table_editcolumns.php => m200000_000002_change_table_editcolumns.php} (92%) rename tests/specs/enum/change/mysql/app/migrations_mysql_db/{m200000_000002_create_table_pristines.php => m200000_000000_create_table_pristines.php} (84%) rename tests/specs/enum/change/mysql/app/migrations_mysql_db/{m200000_000000_change_table_editcolumns.php => m200000_000002_change_table_editcolumns.php} (92%) rename tests/specs/enum/change/pgsql/app/migrations_pgsql_db/{m200000_000002_create_table_pristines.php => m200000_000000_create_table_pristines.php} (89%) rename tests/specs/enum/change/pgsql/app/migrations_pgsql_db/{m200000_000000_change_table_editcolumns.php => m200000_000002_change_table_editcolumns.php} (97%) diff --git a/tests/specs/enum/change/maria/app/migrations_maria_db/m200000_000002_create_table_pristines.php b/tests/specs/enum/change/maria/app/migrations_maria_db/m200000_000000_create_table_pristines.php similarity index 84% rename from tests/specs/enum/change/maria/app/migrations_maria_db/m200000_000002_create_table_pristines.php rename to tests/specs/enum/change/maria/app/migrations_maria_db/m200000_000000_create_table_pristines.php index bdd46f98..2b602da7 100644 --- a/tests/specs/enum/change/maria/app/migrations_maria_db/m200000_000002_create_table_pristines.php +++ b/tests/specs/enum/change/maria/app/migrations_maria_db/m200000_000000_create_table_pristines.php @@ -3,7 +3,7 @@ /** * Table for Pristine */ -class m200000_000002_create_table_pristines extends \yii\db\Migration +class m200000_000000_create_table_pristines extends \yii\db\Migration { public function up() { diff --git a/tests/specs/enum/change/maria/app/migrations_maria_db/m200000_000000_change_table_editcolumns.php b/tests/specs/enum/change/maria/app/migrations_maria_db/m200000_000002_change_table_editcolumns.php similarity index 92% rename from tests/specs/enum/change/maria/app/migrations_maria_db/m200000_000000_change_table_editcolumns.php rename to tests/specs/enum/change/maria/app/migrations_maria_db/m200000_000002_change_table_editcolumns.php index 3df0a659..a2b3f68d 100644 --- a/tests/specs/enum/change/maria/app/migrations_maria_db/m200000_000000_change_table_editcolumns.php +++ b/tests/specs/enum/change/maria/app/migrations_maria_db/m200000_000002_change_table_editcolumns.php @@ -3,7 +3,7 @@ /** * Table for Editcolumn */ -class m200000_000000_change_table_editcolumns extends \yii\db\Migration +class m200000_000002_change_table_editcolumns extends \yii\db\Migration { public function up() { diff --git a/tests/specs/enum/change/mysql/app/migrations_mysql_db/m200000_000002_create_table_pristines.php b/tests/specs/enum/change/mysql/app/migrations_mysql_db/m200000_000000_create_table_pristines.php similarity index 84% rename from tests/specs/enum/change/mysql/app/migrations_mysql_db/m200000_000002_create_table_pristines.php rename to tests/specs/enum/change/mysql/app/migrations_mysql_db/m200000_000000_create_table_pristines.php index bdd46f98..2b602da7 100644 --- a/tests/specs/enum/change/mysql/app/migrations_mysql_db/m200000_000002_create_table_pristines.php +++ b/tests/specs/enum/change/mysql/app/migrations_mysql_db/m200000_000000_create_table_pristines.php @@ -3,7 +3,7 @@ /** * Table for Pristine */ -class m200000_000002_create_table_pristines extends \yii\db\Migration +class m200000_000000_create_table_pristines extends \yii\db\Migration { public function up() { diff --git a/tests/specs/enum/change/mysql/app/migrations_mysql_db/m200000_000000_change_table_editcolumns.php b/tests/specs/enum/change/mysql/app/migrations_mysql_db/m200000_000002_change_table_editcolumns.php similarity index 92% rename from tests/specs/enum/change/mysql/app/migrations_mysql_db/m200000_000000_change_table_editcolumns.php rename to tests/specs/enum/change/mysql/app/migrations_mysql_db/m200000_000002_change_table_editcolumns.php index 117d6069..8d4e499b 100644 --- a/tests/specs/enum/change/mysql/app/migrations_mysql_db/m200000_000000_change_table_editcolumns.php +++ b/tests/specs/enum/change/mysql/app/migrations_mysql_db/m200000_000002_change_table_editcolumns.php @@ -3,7 +3,7 @@ /** * Table for Editcolumn */ -class m200000_000000_change_table_editcolumns extends \yii\db\Migration +class m200000_000002_change_table_editcolumns extends \yii\db\Migration { public function up() { diff --git a/tests/specs/enum/change/pgsql/app/migrations_pgsql_db/m200000_000002_create_table_pristines.php b/tests/specs/enum/change/pgsql/app/migrations_pgsql_db/m200000_000000_create_table_pristines.php similarity index 89% rename from tests/specs/enum/change/pgsql/app/migrations_pgsql_db/m200000_000002_create_table_pristines.php rename to tests/specs/enum/change/pgsql/app/migrations_pgsql_db/m200000_000000_create_table_pristines.php index 45b63115..e336e5e2 100644 --- a/tests/specs/enum/change/pgsql/app/migrations_pgsql_db/m200000_000002_create_table_pristines.php +++ b/tests/specs/enum/change/pgsql/app/migrations_pgsql_db/m200000_000000_create_table_pristines.php @@ -3,7 +3,7 @@ /** * Table for Pristine */ -class m200000_000002_create_table_pristines extends \yii\db\Migration +class m200000_000000_create_table_pristines extends \yii\db\Migration { public function safeUp() { diff --git a/tests/specs/enum/change/pgsql/app/migrations_pgsql_db/m200000_000000_change_table_editcolumns.php b/tests/specs/enum/change/pgsql/app/migrations_pgsql_db/m200000_000002_change_table_editcolumns.php similarity index 97% rename from tests/specs/enum/change/pgsql/app/migrations_pgsql_db/m200000_000000_change_table_editcolumns.php rename to tests/specs/enum/change/pgsql/app/migrations_pgsql_db/m200000_000002_change_table_editcolumns.php index 66287960..0bbb27a9 100644 --- a/tests/specs/enum/change/pgsql/app/migrations_pgsql_db/m200000_000000_change_table_editcolumns.php +++ b/tests/specs/enum/change/pgsql/app/migrations_pgsql_db/m200000_000002_change_table_editcolumns.php @@ -3,7 +3,7 @@ /** * Table for Editcolumn */ -class m200000_000000_change_table_editcolumns extends \yii\db\Migration +class m200000_000002_change_table_editcolumns extends \yii\db\Migration { public function safeUp() { From 07b00b1bd2e6839256d4ff7a49f969e2b7927fa3 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Fri, 21 Jun 2024 20:09:19 +0530 Subject: [PATCH 027/358] Fix another failing tests - ForeignKeyColumnNameTest::testIndex --- ...te_table_users.php => m200000_000000_create_table_users.php} | 2 +- ...eliveries.php => m200000_000001_create_table_deliveries.php} | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) rename tests/specs/fk_col_name/app/migrations_mysql_db/{m200000_000001_create_table_users.php => m200000_000000_create_table_users.php} (82%) rename tests/specs/fk_col_name/app/migrations_mysql_db/{m200000_000000_create_table_deliveries.php => m200000_000001_create_table_deliveries.php} (83%) diff --git a/tests/specs/fk_col_name/app/migrations_mysql_db/m200000_000001_create_table_users.php b/tests/specs/fk_col_name/app/migrations_mysql_db/m200000_000000_create_table_users.php similarity index 82% rename from tests/specs/fk_col_name/app/migrations_mysql_db/m200000_000001_create_table_users.php rename to tests/specs/fk_col_name/app/migrations_mysql_db/m200000_000000_create_table_users.php index e6e9afe4..2616e0a4 100644 --- a/tests/specs/fk_col_name/app/migrations_mysql_db/m200000_000001_create_table_users.php +++ b/tests/specs/fk_col_name/app/migrations_mysql_db/m200000_000000_create_table_users.php @@ -3,7 +3,7 @@ /** * Table for User */ -class m200000_000001_create_table_users extends \yii\db\Migration +class m200000_000000_create_table_users extends \yii\db\Migration { public function up() { diff --git a/tests/specs/fk_col_name/app/migrations_mysql_db/m200000_000000_create_table_deliveries.php b/tests/specs/fk_col_name/app/migrations_mysql_db/m200000_000001_create_table_deliveries.php similarity index 83% rename from tests/specs/fk_col_name/app/migrations_mysql_db/m200000_000000_create_table_deliveries.php rename to tests/specs/fk_col_name/app/migrations_mysql_db/m200000_000001_create_table_deliveries.php index e88d0ea9..b99ba258 100644 --- a/tests/specs/fk_col_name/app/migrations_mysql_db/m200000_000000_create_table_deliveries.php +++ b/tests/specs/fk_col_name/app/migrations_mysql_db/m200000_000001_create_table_deliveries.php @@ -3,7 +3,7 @@ /** * Table for Delivery */ -class m200000_000000_create_table_deliveries extends \yii\db\Migration +class m200000_000001_create_table_deliveries extends \yii\db\Migration { public function up() { From 0c552cec91c01a242b0111d536615f240609ee86 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Fri, 21 Jun 2024 20:10:21 +0530 Subject: [PATCH 028/358] Fix another failing tests - ForeignKeyColumnNameTest::testIndexForColumnWithCustomName --- ...te_table_users.php => m200000_000000_create_table_users.php} | 2 +- ...eliveries.php => m200000_000001_create_table_deliveries.php} | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) rename tests/specs/fk_col_name_index/app/migrations_mysql_db/{m200000_000001_create_table_users.php => m200000_000000_create_table_users.php} (82%) rename tests/specs/fk_col_name_index/app/migrations_mysql_db/{m200000_000000_create_table_deliveries.php => m200000_000001_create_table_deliveries.php} (83%) diff --git a/tests/specs/fk_col_name_index/app/migrations_mysql_db/m200000_000001_create_table_users.php b/tests/specs/fk_col_name_index/app/migrations_mysql_db/m200000_000000_create_table_users.php similarity index 82% rename from tests/specs/fk_col_name_index/app/migrations_mysql_db/m200000_000001_create_table_users.php rename to tests/specs/fk_col_name_index/app/migrations_mysql_db/m200000_000000_create_table_users.php index e6e9afe4..2616e0a4 100644 --- a/tests/specs/fk_col_name_index/app/migrations_mysql_db/m200000_000001_create_table_users.php +++ b/tests/specs/fk_col_name_index/app/migrations_mysql_db/m200000_000000_create_table_users.php @@ -3,7 +3,7 @@ /** * Table for User */ -class m200000_000001_create_table_users extends \yii\db\Migration +class m200000_000000_create_table_users extends \yii\db\Migration { public function up() { diff --git a/tests/specs/fk_col_name_index/app/migrations_mysql_db/m200000_000000_create_table_deliveries.php b/tests/specs/fk_col_name_index/app/migrations_mysql_db/m200000_000001_create_table_deliveries.php similarity index 83% rename from tests/specs/fk_col_name_index/app/migrations_mysql_db/m200000_000000_create_table_deliveries.php rename to tests/specs/fk_col_name_index/app/migrations_mysql_db/m200000_000001_create_table_deliveries.php index e88d0ea9..b99ba258 100644 --- a/tests/specs/fk_col_name_index/app/migrations_mysql_db/m200000_000000_create_table_deliveries.php +++ b/tests/specs/fk_col_name_index/app/migrations_mysql_db/m200000_000001_create_table_deliveries.php @@ -3,7 +3,7 @@ /** * Table for Delivery */ -class m200000_000000_create_table_deliveries extends \yii\db\Migration +class m200000_000001_create_table_deliveries extends \yii\db\Migration { public function up() { From ba2ef56799d3c6ed77b0e8613f2714a8ca2dbd47 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Fri, 21 Jun 2024 20:29:00 +0530 Subject: [PATCH 029/358] Fix another failing tests - GeneratorTest::testGenerate --- .../m200000_000000_create_table_users.php} | 2 +- ...ategories.php => m200000_000001_create_table_categories.php} | 2 +- .../m200000_000003_create_table_post_comments.php} | 2 +- .../m200000_000004_create_table_fakerable.php} | 2 +- .../m200000_000000_create_table_users.php} | 2 +- .../m200000_000001_create_table_categories.php} | 2 +- ...mments.php => m200000_000003_create_table_post_comments.php} | 2 +- ..._fakerable.php => m200000_000004_create_table_fakerable.php} | 2 +- .../m200000_000000_create_table_users.php} | 2 +- .../m200000_000001_create_table_categories.php} | 2 +- .../m200000_000003_create_table_post_comments.php} | 2 +- .../m200000_000004_create_table_fakerable.php} | 2 +- ...te_table_users.php => m200000_000000_create_table_users.php} | 2 +- ...ategories.php => m200000_000001_create_table_categories.php} | 2 +- ...mments.php => m200000_000003_create_table_post_comments.php} | 2 +- ..._fakerable.php => m200000_000004_create_table_fakerable.php} | 2 +- ...te_table_posts.php => m200000_000000_create_table_posts.php} | 2 +- ...eate_table_tags.php => m200000_000001_create_table_tags.php} | 2 +- ...osts2tags.php => m200000_000002_create_table_posts2tags.php} | 2 +- ...te_table_photo.php => m200000_000003_create_table_photo.php} | 2 +- ...s2posts.php => m200000_000004_create_table_photos2posts.php} | 2 +- ...allery.php => m200000_000005_create_table_posts_gallery.php} | 2 +- ...aches.php => m200000_000006_create_table_posts_attaches.php} | 2 +- 23 files changed, 23 insertions(+), 23 deletions(-) rename tests/specs/blog/{migrations_mysql_db/m200000_000001_create_table_users.php => migrations/m200000_000000_create_table_users.php} (94%) rename tests/specs/blog/migrations/{m200000_000000_create_table_categories.php => m200000_000001_create_table_categories.php} (91%) rename tests/specs/blog/{migrations_mysql_db/m200000_000004_create_table_post_comments.php => migrations/m200000_000003_create_table_post_comments.php} (93%) rename tests/specs/blog/{migrations_mysql_db/m200000_000003_create_table_fakerable.php => migrations/m200000_000004_create_table_fakerable.php} (95%) rename tests/specs/blog/{migrations/m200000_000001_create_table_users.php => migrations_maria_db/m200000_000000_create_table_users.php} (94%) rename tests/specs/blog/{migrations_mysql_db/m200000_000000_create_table_categories.php => migrations_maria_db/m200000_000001_create_table_categories.php} (91%) rename tests/specs/blog/migrations_maria_db/{m200000_000004_create_table_post_comments.php => m200000_000003_create_table_post_comments.php} (94%) rename tests/specs/blog/migrations_maria_db/{m200000_000003_create_table_fakerable.php => m200000_000004_create_table_fakerable.php} (95%) rename tests/specs/blog/{migrations_maria_db/m200000_000001_create_table_users.php => migrations_mysql_db/m200000_000000_create_table_users.php} (94%) rename tests/specs/blog/{migrations_maria_db/m200000_000000_create_table_categories.php => migrations_mysql_db/m200000_000001_create_table_categories.php} (91%) rename tests/specs/blog/{migrations/m200000_000004_create_table_post_comments.php => migrations_mysql_db/m200000_000003_create_table_post_comments.php} (93%) rename tests/specs/blog/{migrations/m200000_000003_create_table_fakerable.php => migrations_mysql_db/m200000_000004_create_table_fakerable.php} (95%) rename tests/specs/blog/migrations_pgsql_db/{m200000_000001_create_table_users.php => m200000_000000_create_table_users.php} (94%) rename tests/specs/blog/migrations_pgsql_db/{m200000_000000_create_table_categories.php => m200000_000001_create_table_categories.php} (91%) rename tests/specs/blog/migrations_pgsql_db/{m200000_000004_create_table_post_comments.php => m200000_000003_create_table_post_comments.php} (94%) rename tests/specs/blog/migrations_pgsql_db/{m200000_000003_create_table_fakerable.php => m200000_000004_create_table_fakerable.php} (95%) rename tests/specs/many2many/migrations/{m200000_000001_create_table_posts.php => m200000_000000_create_table_posts.php} (82%) rename tests/specs/many2many/migrations/{m200000_000003_create_table_tags.php => m200000_000001_create_table_tags.php} (82%) rename tests/specs/many2many/migrations/{m200000_000004_create_table_posts2tags.php => m200000_000002_create_table_posts2tags.php} (93%) rename tests/specs/many2many/migrations/{m200000_000000_create_table_photo.php => m200000_000003_create_table_photo.php} (82%) rename tests/specs/many2many/migrations/{m200000_000002_create_table_photos2posts.php => m200000_000004_create_table_photos2posts.php} (92%) rename tests/specs/many2many/migrations/{m200000_000006_create_table_posts_gallery.php => m200000_000005_create_table_posts_gallery.php} (94%) rename tests/specs/many2many/migrations/{m200000_000005_create_table_posts_attaches.php => m200000_000006_create_table_posts_attaches.php} (93%) diff --git a/tests/specs/blog/migrations_mysql_db/m200000_000001_create_table_users.php b/tests/specs/blog/migrations/m200000_000000_create_table_users.php similarity index 94% rename from tests/specs/blog/migrations_mysql_db/m200000_000001_create_table_users.php rename to tests/specs/blog/migrations/m200000_000000_create_table_users.php index a90792e9..de42dde7 100644 --- a/tests/specs/blog/migrations_mysql_db/m200000_000001_create_table_users.php +++ b/tests/specs/blog/migrations/m200000_000000_create_table_users.php @@ -3,7 +3,7 @@ /** * Table for User */ -class m200000_000001_create_table_users extends \yii\db\Migration +class m200000_000000_create_table_users extends \yii\db\Migration { public function up() { diff --git a/tests/specs/blog/migrations/m200000_000000_create_table_categories.php b/tests/specs/blog/migrations/m200000_000001_create_table_categories.php similarity index 91% rename from tests/specs/blog/migrations/m200000_000000_create_table_categories.php rename to tests/specs/blog/migrations/m200000_000001_create_table_categories.php index 0485cafc..957966fb 100644 --- a/tests/specs/blog/migrations/m200000_000000_create_table_categories.php +++ b/tests/specs/blog/migrations/m200000_000001_create_table_categories.php @@ -3,7 +3,7 @@ /** * Table for Category */ -class m200000_000000_create_table_categories extends \yii\db\Migration +class m200000_000001_create_table_categories extends \yii\db\Migration { public function up() { diff --git a/tests/specs/blog/migrations_mysql_db/m200000_000004_create_table_post_comments.php b/tests/specs/blog/migrations/m200000_000003_create_table_post_comments.php similarity index 93% rename from tests/specs/blog/migrations_mysql_db/m200000_000004_create_table_post_comments.php rename to tests/specs/blog/migrations/m200000_000003_create_table_post_comments.php index c16766da..45b512c3 100644 --- a/tests/specs/blog/migrations_mysql_db/m200000_000004_create_table_post_comments.php +++ b/tests/specs/blog/migrations/m200000_000003_create_table_post_comments.php @@ -3,7 +3,7 @@ /** * Table for Comment */ -class m200000_000004_create_table_post_comments extends \yii\db\Migration +class m200000_000003_create_table_post_comments extends \yii\db\Migration { public function up() { diff --git a/tests/specs/blog/migrations_mysql_db/m200000_000003_create_table_fakerable.php b/tests/specs/blog/migrations/m200000_000004_create_table_fakerable.php similarity index 95% rename from tests/specs/blog/migrations_mysql_db/m200000_000003_create_table_fakerable.php rename to tests/specs/blog/migrations/m200000_000004_create_table_fakerable.php index 0f3eebad..82c4db07 100644 --- a/tests/specs/blog/migrations_mysql_db/m200000_000003_create_table_fakerable.php +++ b/tests/specs/blog/migrations/m200000_000004_create_table_fakerable.php @@ -3,7 +3,7 @@ /** * Table for Fakerable */ -class m200000_000003_create_table_fakerable extends \yii\db\Migration +class m200000_000004_create_table_fakerable extends \yii\db\Migration { public function up() { diff --git a/tests/specs/blog/migrations/m200000_000001_create_table_users.php b/tests/specs/blog/migrations_maria_db/m200000_000000_create_table_users.php similarity index 94% rename from tests/specs/blog/migrations/m200000_000001_create_table_users.php rename to tests/specs/blog/migrations_maria_db/m200000_000000_create_table_users.php index a90792e9..de42dde7 100644 --- a/tests/specs/blog/migrations/m200000_000001_create_table_users.php +++ b/tests/specs/blog/migrations_maria_db/m200000_000000_create_table_users.php @@ -3,7 +3,7 @@ /** * Table for User */ -class m200000_000001_create_table_users extends \yii\db\Migration +class m200000_000000_create_table_users extends \yii\db\Migration { public function up() { diff --git a/tests/specs/blog/migrations_mysql_db/m200000_000000_create_table_categories.php b/tests/specs/blog/migrations_maria_db/m200000_000001_create_table_categories.php similarity index 91% rename from tests/specs/blog/migrations_mysql_db/m200000_000000_create_table_categories.php rename to tests/specs/blog/migrations_maria_db/m200000_000001_create_table_categories.php index 0485cafc..957966fb 100644 --- a/tests/specs/blog/migrations_mysql_db/m200000_000000_create_table_categories.php +++ b/tests/specs/blog/migrations_maria_db/m200000_000001_create_table_categories.php @@ -3,7 +3,7 @@ /** * Table for Category */ -class m200000_000000_create_table_categories extends \yii\db\Migration +class m200000_000001_create_table_categories extends \yii\db\Migration { public function up() { diff --git a/tests/specs/blog/migrations_maria_db/m200000_000004_create_table_post_comments.php b/tests/specs/blog/migrations_maria_db/m200000_000003_create_table_post_comments.php similarity index 94% rename from tests/specs/blog/migrations_maria_db/m200000_000004_create_table_post_comments.php rename to tests/specs/blog/migrations_maria_db/m200000_000003_create_table_post_comments.php index d4971f43..fc617edf 100644 --- a/tests/specs/blog/migrations_maria_db/m200000_000004_create_table_post_comments.php +++ b/tests/specs/blog/migrations_maria_db/m200000_000003_create_table_post_comments.php @@ -3,7 +3,7 @@ /** * Table for Comment */ -class m200000_000004_create_table_post_comments extends \yii\db\Migration +class m200000_000003_create_table_post_comments extends \yii\db\Migration { public function up() { diff --git a/tests/specs/blog/migrations_maria_db/m200000_000003_create_table_fakerable.php b/tests/specs/blog/migrations_maria_db/m200000_000004_create_table_fakerable.php similarity index 95% rename from tests/specs/blog/migrations_maria_db/m200000_000003_create_table_fakerable.php rename to tests/specs/blog/migrations_maria_db/m200000_000004_create_table_fakerable.php index 84f6247c..4ec0bb94 100644 --- a/tests/specs/blog/migrations_maria_db/m200000_000003_create_table_fakerable.php +++ b/tests/specs/blog/migrations_maria_db/m200000_000004_create_table_fakerable.php @@ -3,7 +3,7 @@ /** * Table for Fakerable */ -class m200000_000003_create_table_fakerable extends \yii\db\Migration +class m200000_000004_create_table_fakerable extends \yii\db\Migration { public function up() { diff --git a/tests/specs/blog/migrations_maria_db/m200000_000001_create_table_users.php b/tests/specs/blog/migrations_mysql_db/m200000_000000_create_table_users.php similarity index 94% rename from tests/specs/blog/migrations_maria_db/m200000_000001_create_table_users.php rename to tests/specs/blog/migrations_mysql_db/m200000_000000_create_table_users.php index a90792e9..de42dde7 100644 --- a/tests/specs/blog/migrations_maria_db/m200000_000001_create_table_users.php +++ b/tests/specs/blog/migrations_mysql_db/m200000_000000_create_table_users.php @@ -3,7 +3,7 @@ /** * Table for User */ -class m200000_000001_create_table_users extends \yii\db\Migration +class m200000_000000_create_table_users extends \yii\db\Migration { public function up() { diff --git a/tests/specs/blog/migrations_maria_db/m200000_000000_create_table_categories.php b/tests/specs/blog/migrations_mysql_db/m200000_000001_create_table_categories.php similarity index 91% rename from tests/specs/blog/migrations_maria_db/m200000_000000_create_table_categories.php rename to tests/specs/blog/migrations_mysql_db/m200000_000001_create_table_categories.php index 0485cafc..957966fb 100644 --- a/tests/specs/blog/migrations_maria_db/m200000_000000_create_table_categories.php +++ b/tests/specs/blog/migrations_mysql_db/m200000_000001_create_table_categories.php @@ -3,7 +3,7 @@ /** * Table for Category */ -class m200000_000000_create_table_categories extends \yii\db\Migration +class m200000_000001_create_table_categories extends \yii\db\Migration { public function up() { diff --git a/tests/specs/blog/migrations/m200000_000004_create_table_post_comments.php b/tests/specs/blog/migrations_mysql_db/m200000_000003_create_table_post_comments.php similarity index 93% rename from tests/specs/blog/migrations/m200000_000004_create_table_post_comments.php rename to tests/specs/blog/migrations_mysql_db/m200000_000003_create_table_post_comments.php index c16766da..45b512c3 100644 --- a/tests/specs/blog/migrations/m200000_000004_create_table_post_comments.php +++ b/tests/specs/blog/migrations_mysql_db/m200000_000003_create_table_post_comments.php @@ -3,7 +3,7 @@ /** * Table for Comment */ -class m200000_000004_create_table_post_comments extends \yii\db\Migration +class m200000_000003_create_table_post_comments extends \yii\db\Migration { public function up() { diff --git a/tests/specs/blog/migrations/m200000_000003_create_table_fakerable.php b/tests/specs/blog/migrations_mysql_db/m200000_000004_create_table_fakerable.php similarity index 95% rename from tests/specs/blog/migrations/m200000_000003_create_table_fakerable.php rename to tests/specs/blog/migrations_mysql_db/m200000_000004_create_table_fakerable.php index 0f3eebad..82c4db07 100644 --- a/tests/specs/blog/migrations/m200000_000003_create_table_fakerable.php +++ b/tests/specs/blog/migrations_mysql_db/m200000_000004_create_table_fakerable.php @@ -3,7 +3,7 @@ /** * Table for Fakerable */ -class m200000_000003_create_table_fakerable extends \yii\db\Migration +class m200000_000004_create_table_fakerable extends \yii\db\Migration { public function up() { diff --git a/tests/specs/blog/migrations_pgsql_db/m200000_000001_create_table_users.php b/tests/specs/blog/migrations_pgsql_db/m200000_000000_create_table_users.php similarity index 94% rename from tests/specs/blog/migrations_pgsql_db/m200000_000001_create_table_users.php rename to tests/specs/blog/migrations_pgsql_db/m200000_000000_create_table_users.php index e2bc0165..a00af878 100644 --- a/tests/specs/blog/migrations_pgsql_db/m200000_000001_create_table_users.php +++ b/tests/specs/blog/migrations_pgsql_db/m200000_000000_create_table_users.php @@ -3,7 +3,7 @@ /** * Table for User */ -class m200000_000001_create_table_users extends \yii\db\Migration +class m200000_000000_create_table_users extends \yii\db\Migration { public function safeUp() { diff --git a/tests/specs/blog/migrations_pgsql_db/m200000_000000_create_table_categories.php b/tests/specs/blog/migrations_pgsql_db/m200000_000001_create_table_categories.php similarity index 91% rename from tests/specs/blog/migrations_pgsql_db/m200000_000000_create_table_categories.php rename to tests/specs/blog/migrations_pgsql_db/m200000_000001_create_table_categories.php index 9c328a2d..d99b8299 100644 --- a/tests/specs/blog/migrations_pgsql_db/m200000_000000_create_table_categories.php +++ b/tests/specs/blog/migrations_pgsql_db/m200000_000001_create_table_categories.php @@ -3,7 +3,7 @@ /** * Table for Category */ -class m200000_000000_create_table_categories extends \yii\db\Migration +class m200000_000001_create_table_categories extends \yii\db\Migration { public function safeUp() { diff --git a/tests/specs/blog/migrations_pgsql_db/m200000_000004_create_table_post_comments.php b/tests/specs/blog/migrations_pgsql_db/m200000_000003_create_table_post_comments.php similarity index 94% rename from tests/specs/blog/migrations_pgsql_db/m200000_000004_create_table_post_comments.php rename to tests/specs/blog/migrations_pgsql_db/m200000_000003_create_table_post_comments.php index 2aa48549..5f31afad 100644 --- a/tests/specs/blog/migrations_pgsql_db/m200000_000004_create_table_post_comments.php +++ b/tests/specs/blog/migrations_pgsql_db/m200000_000003_create_table_post_comments.php @@ -3,7 +3,7 @@ /** * Table for Comment */ -class m200000_000004_create_table_post_comments extends \yii\db\Migration +class m200000_000003_create_table_post_comments extends \yii\db\Migration { public function safeUp() { diff --git a/tests/specs/blog/migrations_pgsql_db/m200000_000003_create_table_fakerable.php b/tests/specs/blog/migrations_pgsql_db/m200000_000004_create_table_fakerable.php similarity index 95% rename from tests/specs/blog/migrations_pgsql_db/m200000_000003_create_table_fakerable.php rename to tests/specs/blog/migrations_pgsql_db/m200000_000004_create_table_fakerable.php index a42b8954..ae6929cb 100644 --- a/tests/specs/blog/migrations_pgsql_db/m200000_000003_create_table_fakerable.php +++ b/tests/specs/blog/migrations_pgsql_db/m200000_000004_create_table_fakerable.php @@ -3,7 +3,7 @@ /** * Table for Fakerable */ -class m200000_000003_create_table_fakerable extends \yii\db\Migration +class m200000_000004_create_table_fakerable extends \yii\db\Migration { public function safeUp() { diff --git a/tests/specs/many2many/migrations/m200000_000001_create_table_posts.php b/tests/specs/many2many/migrations/m200000_000000_create_table_posts.php similarity index 82% rename from tests/specs/many2many/migrations/m200000_000001_create_table_posts.php rename to tests/specs/many2many/migrations/m200000_000000_create_table_posts.php index 2d07a0d1..4febc421 100644 --- a/tests/specs/many2many/migrations/m200000_000001_create_table_posts.php +++ b/tests/specs/many2many/migrations/m200000_000000_create_table_posts.php @@ -3,7 +3,7 @@ /** * Table for Post */ -class m200000_000001_create_table_posts extends \yii\db\Migration +class m200000_000000_create_table_posts extends \yii\db\Migration { public function up() { diff --git a/tests/specs/many2many/migrations/m200000_000003_create_table_tags.php b/tests/specs/many2many/migrations/m200000_000001_create_table_tags.php similarity index 82% rename from tests/specs/many2many/migrations/m200000_000003_create_table_tags.php rename to tests/specs/many2many/migrations/m200000_000001_create_table_tags.php index 253b8513..b78dfe66 100644 --- a/tests/specs/many2many/migrations/m200000_000003_create_table_tags.php +++ b/tests/specs/many2many/migrations/m200000_000001_create_table_tags.php @@ -3,7 +3,7 @@ /** * Table for Tag */ -class m200000_000003_create_table_tags extends \yii\db\Migration +class m200000_000001_create_table_tags extends \yii\db\Migration { public function up() { diff --git a/tests/specs/many2many/migrations/m200000_000004_create_table_posts2tags.php b/tests/specs/many2many/migrations/m200000_000002_create_table_posts2tags.php similarity index 93% rename from tests/specs/many2many/migrations/m200000_000004_create_table_posts2tags.php rename to tests/specs/many2many/migrations/m200000_000002_create_table_posts2tags.php index dbc82bc3..373e2e65 100644 --- a/tests/specs/many2many/migrations/m200000_000004_create_table_posts2tags.php +++ b/tests/specs/many2many/migrations/m200000_000002_create_table_posts2tags.php @@ -3,7 +3,7 @@ /** * Table for Posts2Tags */ -class m200000_000004_create_table_posts2tags extends \yii\db\Migration +class m200000_000002_create_table_posts2tags extends \yii\db\Migration { public function up() { diff --git a/tests/specs/many2many/migrations/m200000_000000_create_table_photo.php b/tests/specs/many2many/migrations/m200000_000003_create_table_photo.php similarity index 82% rename from tests/specs/many2many/migrations/m200000_000000_create_table_photo.php rename to tests/specs/many2many/migrations/m200000_000003_create_table_photo.php index 4e578d91..2d783bbf 100644 --- a/tests/specs/many2many/migrations/m200000_000000_create_table_photo.php +++ b/tests/specs/many2many/migrations/m200000_000003_create_table_photo.php @@ -3,7 +3,7 @@ /** * Table for Photo */ -class m200000_000000_create_table_photo extends \yii\db\Migration +class m200000_000003_create_table_photo extends \yii\db\Migration { public function up() { diff --git a/tests/specs/many2many/migrations/m200000_000002_create_table_photos2posts.php b/tests/specs/many2many/migrations/m200000_000004_create_table_photos2posts.php similarity index 92% rename from tests/specs/many2many/migrations/m200000_000002_create_table_photos2posts.php rename to tests/specs/many2many/migrations/m200000_000004_create_table_photos2posts.php index f10b43a6..b509a525 100644 --- a/tests/specs/many2many/migrations/m200000_000002_create_table_photos2posts.php +++ b/tests/specs/many2many/migrations/m200000_000004_create_table_photos2posts.php @@ -3,7 +3,7 @@ /** * Table for Photos2Posts */ -class m200000_000002_create_table_photos2posts extends \yii\db\Migration +class m200000_000004_create_table_photos2posts extends \yii\db\Migration { public function up() { diff --git a/tests/specs/many2many/migrations/m200000_000006_create_table_posts_gallery.php b/tests/specs/many2many/migrations/m200000_000005_create_table_posts_gallery.php similarity index 94% rename from tests/specs/many2many/migrations/m200000_000006_create_table_posts_gallery.php rename to tests/specs/many2many/migrations/m200000_000005_create_table_posts_gallery.php index aeb6c64f..fe358e21 100644 --- a/tests/specs/many2many/migrations/m200000_000006_create_table_posts_gallery.php +++ b/tests/specs/many2many/migrations/m200000_000005_create_table_posts_gallery.php @@ -3,7 +3,7 @@ /** * Table for PostsGallery */ -class m200000_000006_create_table_posts_gallery extends \yii\db\Migration +class m200000_000005_create_table_posts_gallery extends \yii\db\Migration { public function up() { diff --git a/tests/specs/many2many/migrations/m200000_000005_create_table_posts_attaches.php b/tests/specs/many2many/migrations/m200000_000006_create_table_posts_attaches.php similarity index 93% rename from tests/specs/many2many/migrations/m200000_000005_create_table_posts_attaches.php rename to tests/specs/many2many/migrations/m200000_000006_create_table_posts_attaches.php index f5092acb..db479676 100644 --- a/tests/specs/many2many/migrations/m200000_000005_create_table_posts_attaches.php +++ b/tests/specs/many2many/migrations/m200000_000006_create_table_posts_attaches.php @@ -3,7 +3,7 @@ /** * Table for PostsAttaches */ -class m200000_000005_create_table_posts_attaches extends \yii\db\Migration +class m200000_000006_create_table_posts_attaches extends \yii\db\Migration { public function up() { From 3a1499b37cc587639d2dbcce2122ad46c9e9b655 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Fri, 21 Jun 2024 20:31:02 +0530 Subject: [PATCH 030/358] Fix another failing tests - NewColumnPositionTest::testAddOneNewColumnAtFirstPosition --- .../migrations_maria_db/m200000_000000_change_table_fruits.php} | 2 +- ...able_fruit2s.php => m200000_000001_change_table_fruit2s.php} | 2 +- ...able_twocols.php => m200000_000002_change_table_twocols.php} | 2 +- ...le_twocol2s.php => m200000_000003_change_table_twocol2s.php} | 2 +- ...stcols.php => m200000_000004_change_table_dropfirstcols.php} | 2 +- ...ols.php => m200000_000005_change_table_dropfirsttwocols.php} | 2 +- ...p => m200000_000006_change_table_addtwonewcolinbetweens.php} | 2 +- ... => m200000_000007_change_table_addtwonewcolinbetween2s.php} | 2 +- ...sts.php => m200000_000008_change_table_twonewcolatlasts.php} | 2 +- ...2s.php => m200000_000009_change_table_twonewcolatlast2s.php} | 2 +- .../migrations_mysql_db/m200000_000000_change_table_fruits.php} | 2 +- ...able_fruit2s.php => m200000_000001_change_table_fruit2s.php} | 2 +- ...able_twocols.php => m200000_000002_change_table_twocols.php} | 2 +- ...le_twocol2s.php => m200000_000003_change_table_twocol2s.php} | 2 +- ...stcols.php => m200000_000004_change_table_dropfirstcols.php} | 2 +- ...ols.php => m200000_000005_change_table_dropfirsttwocols.php} | 2 +- ...p => m200000_000006_change_table_addtwonewcolinbetweens.php} | 2 +- ... => m200000_000007_change_table_addtwonewcolinbetween2s.php} | 2 +- ...sts.php => m200000_000008_change_table_twonewcolatlasts.php} | 2 +- ...2s.php => m200000_000009_change_table_twonewcolatlast2s.php} | 2 +- 20 files changed, 20 insertions(+), 20 deletions(-) rename tests/specs/new_column_position/{mysql/app/migrations_mysql_db/m200000_000005_change_table_fruits.php => maria/app/migrations_maria_db/m200000_000000_change_table_fruits.php} (79%) rename tests/specs/new_column_position/maria/app/migrations_maria_db/{m200000_000004_change_table_fruit2s.php => m200000_000001_change_table_fruit2s.php} (81%) rename tests/specs/new_column_position/maria/app/migrations_maria_db/{m200000_000007_change_table_twocols.php => m200000_000002_change_table_twocols.php} (87%) rename tests/specs/new_column_position/maria/app/migrations_maria_db/{m200000_000006_change_table_twocol2s.php => m200000_000003_change_table_twocol2s.php} (88%) rename tests/specs/new_column_position/maria/app/migrations_maria_db/{m200000_000002_change_table_dropfirstcols.php => m200000_000004_change_table_dropfirstcols.php} (82%) rename tests/specs/new_column_position/maria/app/migrations_maria_db/{m200000_000003_change_table_dropfirsttwocols.php => m200000_000005_change_table_dropfirsttwocols.php} (88%) rename tests/specs/new_column_position/maria/app/migrations_maria_db/{m200000_000001_change_table_addtwonewcolinbetweens.php => m200000_000006_change_table_addtwonewcolinbetweens.php} (92%) rename tests/specs/new_column_position/maria/app/migrations_maria_db/{m200000_000000_change_table_addtwonewcolinbetween2s.php => m200000_000007_change_table_addtwonewcolinbetween2s.php} (92%) rename tests/specs/new_column_position/maria/app/migrations_maria_db/{m200000_000009_change_table_twonewcolatlasts.php => m200000_000008_change_table_twonewcolatlasts.php} (88%) rename tests/specs/new_column_position/maria/app/migrations_maria_db/{m200000_000008_change_table_twonewcolatlast2s.php => m200000_000009_change_table_twonewcolatlast2s.php} (89%) rename tests/specs/new_column_position/{maria/app/migrations_maria_db/m200000_000005_change_table_fruits.php => mysql/app/migrations_mysql_db/m200000_000000_change_table_fruits.php} (79%) rename tests/specs/new_column_position/mysql/app/migrations_mysql_db/{m200000_000004_change_table_fruit2s.php => m200000_000001_change_table_fruit2s.php} (81%) rename tests/specs/new_column_position/mysql/app/migrations_mysql_db/{m200000_000007_change_table_twocols.php => m200000_000002_change_table_twocols.php} (86%) rename tests/specs/new_column_position/mysql/app/migrations_mysql_db/{m200000_000006_change_table_twocol2s.php => m200000_000003_change_table_twocol2s.php} (87%) rename tests/specs/new_column_position/mysql/app/migrations_mysql_db/{m200000_000002_change_table_dropfirstcols.php => m200000_000004_change_table_dropfirstcols.php} (81%) rename tests/specs/new_column_position/mysql/app/migrations_mysql_db/{m200000_000003_change_table_dropfirsttwocols.php => m200000_000005_change_table_dropfirsttwocols.php} (87%) rename tests/specs/new_column_position/mysql/app/migrations_mysql_db/{m200000_000001_change_table_addtwonewcolinbetweens.php => m200000_000006_change_table_addtwonewcolinbetweens.php} (91%) rename tests/specs/new_column_position/mysql/app/migrations_mysql_db/{m200000_000000_change_table_addtwonewcolinbetween2s.php => m200000_000007_change_table_addtwonewcolinbetween2s.php} (92%) rename tests/specs/new_column_position/mysql/app/migrations_mysql_db/{m200000_000009_change_table_twonewcolatlasts.php => m200000_000008_change_table_twonewcolatlasts.php} (88%) rename tests/specs/new_column_position/mysql/app/migrations_mysql_db/{m200000_000008_change_table_twonewcolatlast2s.php => m200000_000009_change_table_twonewcolatlast2s.php} (88%) diff --git a/tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000005_change_table_fruits.php b/tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000000_change_table_fruits.php similarity index 79% rename from tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000005_change_table_fruits.php rename to tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000000_change_table_fruits.php index 8accdd87..2cb90b8e 100644 --- a/tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000005_change_table_fruits.php +++ b/tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000000_change_table_fruits.php @@ -3,7 +3,7 @@ /** * Table for Fruit */ -class m200000_000005_change_table_fruits extends \yii\db\Migration +class m200000_000000_change_table_fruits extends \yii\db\Migration { public function up() { diff --git a/tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000004_change_table_fruit2s.php b/tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000001_change_table_fruit2s.php similarity index 81% rename from tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000004_change_table_fruit2s.php rename to tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000001_change_table_fruit2s.php index 68bfd09e..547fdbf2 100644 --- a/tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000004_change_table_fruit2s.php +++ b/tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000001_change_table_fruit2s.php @@ -3,7 +3,7 @@ /** * Table for Fruit2 */ -class m200000_000004_change_table_fruit2s extends \yii\db\Migration +class m200000_000001_change_table_fruit2s extends \yii\db\Migration { public function up() { diff --git a/tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000007_change_table_twocols.php b/tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000002_change_table_twocols.php similarity index 87% rename from tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000007_change_table_twocols.php rename to tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000002_change_table_twocols.php index d63f7443..0ee4668e 100644 --- a/tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000007_change_table_twocols.php +++ b/tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000002_change_table_twocols.php @@ -3,7 +3,7 @@ /** * Table for Twocol */ -class m200000_000007_change_table_twocols extends \yii\db\Migration +class m200000_000002_change_table_twocols extends \yii\db\Migration { public function up() { diff --git a/tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000006_change_table_twocol2s.php b/tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000003_change_table_twocol2s.php similarity index 88% rename from tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000006_change_table_twocol2s.php rename to tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000003_change_table_twocol2s.php index 45325e91..94f91d2f 100644 --- a/tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000006_change_table_twocol2s.php +++ b/tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000003_change_table_twocol2s.php @@ -3,7 +3,7 @@ /** * Table for Twocol2 */ -class m200000_000006_change_table_twocol2s extends \yii\db\Migration +class m200000_000003_change_table_twocol2s extends \yii\db\Migration { public function up() { diff --git a/tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000002_change_table_dropfirstcols.php b/tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000004_change_table_dropfirstcols.php similarity index 82% rename from tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000002_change_table_dropfirstcols.php rename to tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000004_change_table_dropfirstcols.php index 56f0692d..a6fcdbb9 100644 --- a/tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000002_change_table_dropfirstcols.php +++ b/tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000004_change_table_dropfirstcols.php @@ -3,7 +3,7 @@ /** * Table for Dropfirstcol */ -class m200000_000002_change_table_dropfirstcols extends \yii\db\Migration +class m200000_000004_change_table_dropfirstcols extends \yii\db\Migration { public function up() { diff --git a/tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000003_change_table_dropfirsttwocols.php b/tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000005_change_table_dropfirsttwocols.php similarity index 88% rename from tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000003_change_table_dropfirsttwocols.php rename to tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000005_change_table_dropfirsttwocols.php index 89ef1937..9d438149 100644 --- a/tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000003_change_table_dropfirsttwocols.php +++ b/tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000005_change_table_dropfirsttwocols.php @@ -3,7 +3,7 @@ /** * Table for Dropfirsttwocol */ -class m200000_000003_change_table_dropfirsttwocols extends \yii\db\Migration +class m200000_000005_change_table_dropfirsttwocols extends \yii\db\Migration { public function up() { diff --git a/tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000001_change_table_addtwonewcolinbetweens.php b/tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000006_change_table_addtwonewcolinbetweens.php similarity index 92% rename from tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000001_change_table_addtwonewcolinbetweens.php rename to tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000006_change_table_addtwonewcolinbetweens.php index b9648922..62790337 100644 --- a/tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000001_change_table_addtwonewcolinbetweens.php +++ b/tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000006_change_table_addtwonewcolinbetweens.php @@ -3,7 +3,7 @@ /** * Table for Addtwonewcolinbetweens */ -class m200000_000001_change_table_addtwonewcolinbetweens extends \yii\db\Migration +class m200000_000006_change_table_addtwonewcolinbetweens extends \yii\db\Migration { public function up() { diff --git a/tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000000_change_table_addtwonewcolinbetween2s.php b/tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000007_change_table_addtwonewcolinbetween2s.php similarity index 92% rename from tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000000_change_table_addtwonewcolinbetween2s.php rename to tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000007_change_table_addtwonewcolinbetween2s.php index 544d1084..002a045e 100644 --- a/tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000000_change_table_addtwonewcolinbetween2s.php +++ b/tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000007_change_table_addtwonewcolinbetween2s.php @@ -3,7 +3,7 @@ /** * Table for Addtwonewcolinbetween2s */ -class m200000_000000_change_table_addtwonewcolinbetween2s extends \yii\db\Migration +class m200000_000007_change_table_addtwonewcolinbetween2s extends \yii\db\Migration { public function up() { diff --git a/tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000009_change_table_twonewcolatlasts.php b/tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000008_change_table_twonewcolatlasts.php similarity index 88% rename from tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000009_change_table_twonewcolatlasts.php rename to tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000008_change_table_twonewcolatlasts.php index 0a332d7a..307f1375 100644 --- a/tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000009_change_table_twonewcolatlasts.php +++ b/tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000008_change_table_twonewcolatlasts.php @@ -3,7 +3,7 @@ /** * Table for Twonewcolatlast */ -class m200000_000009_change_table_twonewcolatlasts extends \yii\db\Migration +class m200000_000008_change_table_twonewcolatlasts extends \yii\db\Migration { public function up() { diff --git a/tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000008_change_table_twonewcolatlast2s.php b/tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000009_change_table_twonewcolatlast2s.php similarity index 89% rename from tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000008_change_table_twonewcolatlast2s.php rename to tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000009_change_table_twonewcolatlast2s.php index 0a88452d..51db951e 100644 --- a/tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000008_change_table_twonewcolatlast2s.php +++ b/tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000009_change_table_twonewcolatlast2s.php @@ -3,7 +3,7 @@ /** * Table for Twonewcolatlast2 */ -class m200000_000008_change_table_twonewcolatlast2s extends \yii\db\Migration +class m200000_000009_change_table_twonewcolatlast2s extends \yii\db\Migration { public function up() { diff --git a/tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000005_change_table_fruits.php b/tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000000_change_table_fruits.php similarity index 79% rename from tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000005_change_table_fruits.php rename to tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000000_change_table_fruits.php index 8accdd87..2cb90b8e 100644 --- a/tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000005_change_table_fruits.php +++ b/tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000000_change_table_fruits.php @@ -3,7 +3,7 @@ /** * Table for Fruit */ -class m200000_000005_change_table_fruits extends \yii\db\Migration +class m200000_000000_change_table_fruits extends \yii\db\Migration { public function up() { diff --git a/tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000004_change_table_fruit2s.php b/tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000001_change_table_fruit2s.php similarity index 81% rename from tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000004_change_table_fruit2s.php rename to tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000001_change_table_fruit2s.php index 68bfd09e..547fdbf2 100644 --- a/tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000004_change_table_fruit2s.php +++ b/tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000001_change_table_fruit2s.php @@ -3,7 +3,7 @@ /** * Table for Fruit2 */ -class m200000_000004_change_table_fruit2s extends \yii\db\Migration +class m200000_000001_change_table_fruit2s extends \yii\db\Migration { public function up() { diff --git a/tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000007_change_table_twocols.php b/tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000002_change_table_twocols.php similarity index 86% rename from tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000007_change_table_twocols.php rename to tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000002_change_table_twocols.php index 33c954e0..d49b200e 100644 --- a/tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000007_change_table_twocols.php +++ b/tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000002_change_table_twocols.php @@ -3,7 +3,7 @@ /** * Table for Twocol */ -class m200000_000007_change_table_twocols extends \yii\db\Migration +class m200000_000002_change_table_twocols extends \yii\db\Migration { public function up() { diff --git a/tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000006_change_table_twocol2s.php b/tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000003_change_table_twocol2s.php similarity index 87% rename from tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000006_change_table_twocol2s.php rename to tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000003_change_table_twocol2s.php index 40e3d693..05585780 100644 --- a/tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000006_change_table_twocol2s.php +++ b/tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000003_change_table_twocol2s.php @@ -3,7 +3,7 @@ /** * Table for Twocol2 */ -class m200000_000006_change_table_twocol2s extends \yii\db\Migration +class m200000_000003_change_table_twocol2s extends \yii\db\Migration { public function up() { diff --git a/tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000002_change_table_dropfirstcols.php b/tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000004_change_table_dropfirstcols.php similarity index 81% rename from tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000002_change_table_dropfirstcols.php rename to tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000004_change_table_dropfirstcols.php index 4ae589d3..a103bad4 100644 --- a/tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000002_change_table_dropfirstcols.php +++ b/tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000004_change_table_dropfirstcols.php @@ -3,7 +3,7 @@ /** * Table for Dropfirstcol */ -class m200000_000002_change_table_dropfirstcols extends \yii\db\Migration +class m200000_000004_change_table_dropfirstcols extends \yii\db\Migration { public function up() { diff --git a/tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000003_change_table_dropfirsttwocols.php b/tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000005_change_table_dropfirsttwocols.php similarity index 87% rename from tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000003_change_table_dropfirsttwocols.php rename to tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000005_change_table_dropfirsttwocols.php index aaa54835..482bfa72 100644 --- a/tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000003_change_table_dropfirsttwocols.php +++ b/tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000005_change_table_dropfirsttwocols.php @@ -3,7 +3,7 @@ /** * Table for Dropfirsttwocol */ -class m200000_000003_change_table_dropfirsttwocols extends \yii\db\Migration +class m200000_000005_change_table_dropfirsttwocols extends \yii\db\Migration { public function up() { diff --git a/tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000001_change_table_addtwonewcolinbetweens.php b/tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000006_change_table_addtwonewcolinbetweens.php similarity index 91% rename from tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000001_change_table_addtwonewcolinbetweens.php rename to tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000006_change_table_addtwonewcolinbetweens.php index 355597ac..963c74dc 100644 --- a/tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000001_change_table_addtwonewcolinbetweens.php +++ b/tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000006_change_table_addtwonewcolinbetweens.php @@ -3,7 +3,7 @@ /** * Table for Addtwonewcolinbetweens */ -class m200000_000001_change_table_addtwonewcolinbetweens extends \yii\db\Migration +class m200000_000006_change_table_addtwonewcolinbetweens extends \yii\db\Migration { public function up() { diff --git a/tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000000_change_table_addtwonewcolinbetween2s.php b/tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000007_change_table_addtwonewcolinbetween2s.php similarity index 92% rename from tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000000_change_table_addtwonewcolinbetween2s.php rename to tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000007_change_table_addtwonewcolinbetween2s.php index 7d4f8bfa..7fc2bd8d 100644 --- a/tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000000_change_table_addtwonewcolinbetween2s.php +++ b/tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000007_change_table_addtwonewcolinbetween2s.php @@ -3,7 +3,7 @@ /** * Table for Addtwonewcolinbetween2s */ -class m200000_000000_change_table_addtwonewcolinbetween2s extends \yii\db\Migration +class m200000_000007_change_table_addtwonewcolinbetween2s extends \yii\db\Migration { public function up() { diff --git a/tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000009_change_table_twonewcolatlasts.php b/tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000008_change_table_twonewcolatlasts.php similarity index 88% rename from tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000009_change_table_twonewcolatlasts.php rename to tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000008_change_table_twonewcolatlasts.php index 0a332d7a..307f1375 100644 --- a/tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000009_change_table_twonewcolatlasts.php +++ b/tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000008_change_table_twonewcolatlasts.php @@ -3,7 +3,7 @@ /** * Table for Twonewcolatlast */ -class m200000_000009_change_table_twonewcolatlasts extends \yii\db\Migration +class m200000_000008_change_table_twonewcolatlasts extends \yii\db\Migration { public function up() { diff --git a/tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000008_change_table_twonewcolatlast2s.php b/tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000009_change_table_twonewcolatlast2s.php similarity index 88% rename from tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000008_change_table_twonewcolatlast2s.php rename to tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000009_change_table_twonewcolatlast2s.php index 60931d95..85dbdb59 100644 --- a/tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000008_change_table_twonewcolatlast2s.php +++ b/tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000009_change_table_twonewcolatlast2s.php @@ -3,7 +3,7 @@ /** * Table for Twonewcolatlast2 */ -class m200000_000008_change_table_twonewcolatlast2s extends \yii\db\Migration +class m200000_000009_change_table_twonewcolatlast2s extends \yii\db\Migration { public function up() { From a4dc0a46b749b2ed7e5373a5f976cce5f6888548 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Fri, 21 Jun 2024 20:38:10 +0530 Subject: [PATCH 031/358] Fix another failing tests - MultiDbSecondaryMigrationTest --- ..._v2_users.php => m200000_000000_change_table_v2_users.php} | 2 +- .../m200000_000001_change_table_v2_categories.php} | 2 +- ..._v2_posts.php => m200000_000002_change_table_v2_posts.php} | 2 +- .../m200000_000003_create_table_v2_tags.php} | 2 +- ...ts2tags.php => m200000_000004_create_table_posts2tags.php} | 2 +- ..._v2_users.php => m200000_000000_change_table_v2_users.php} | 2 +- .../m200000_000001_change_table_v2_categories.php} | 2 +- ..._v2_posts.php => m200000_000002_change_table_v2_posts.php} | 2 +- .../m200000_000003_create_table_v2_tags.php} | 2 +- ...ts2tags.php => m200000_000004_create_table_posts2tags.php} | 2 +- .../m200000_000005_change_table_v2_comments.php | 4 ++-- ..._v2_users.php => m200000_000000_change_table_v2_users.php} | 2 +- ...ries.php => m200000_000001_change_table_v2_categories.php} | 2 +- ..._v2_posts.php => m200000_000002_change_table_v2_posts.php} | 2 +- ...le_v2_tags.php => m200000_000003_create_table_v2_tags.php} | 2 +- ...ts2tags.php => m200000_000004_create_table_posts2tags.php} | 2 +- 16 files changed, 17 insertions(+), 17 deletions(-) rename tests/specs/blog_v2/migrations_maria_db/{m200000_000004_change_table_v2_users.php => m200000_000000_change_table_v2_users.php} (95%) rename tests/specs/blog_v2/{migrations_mysql_db/m200000_000003_change_table_v2_categories.php => migrations_maria_db/m200000_000001_change_table_v2_categories.php} (94%) rename tests/specs/blog_v2/migrations_maria_db/{m200000_000000_change_table_v2_posts.php => m200000_000002_change_table_v2_posts.php} (95%) rename tests/specs/blog_v2/{migrations_mysql_db/m200000_000001_create_table_v2_tags.php => migrations_maria_db/m200000_000003_create_table_v2_tags.php} (88%) rename tests/specs/blog_v2/migrations_maria_db/{m200000_000002_create_table_posts2tags.php => m200000_000004_create_table_posts2tags.php} (93%) rename tests/specs/blog_v2/migrations_mysql_db/{m200000_000004_change_table_v2_users.php => m200000_000000_change_table_v2_users.php} (95%) rename tests/specs/blog_v2/{migrations_maria_db/m200000_000003_change_table_v2_categories.php => migrations_mysql_db/m200000_000001_change_table_v2_categories.php} (94%) rename tests/specs/blog_v2/migrations_mysql_db/{m200000_000000_change_table_v2_posts.php => m200000_000002_change_table_v2_posts.php} (95%) rename tests/specs/blog_v2/{migrations_maria_db/m200000_000001_create_table_v2_tags.php => migrations_mysql_db/m200000_000003_create_table_v2_tags.php} (88%) rename tests/specs/blog_v2/migrations_mysql_db/{m200000_000002_create_table_posts2tags.php => m200000_000004_create_table_posts2tags.php} (93%) rename tests/specs/blog_v2/migrations_pgsql_db/{m200000_000004_change_table_v2_users.php => m200000_000000_change_table_v2_users.php} (96%) rename tests/specs/blog_v2/migrations_pgsql_db/{m200000_000003_change_table_v2_categories.php => m200000_000001_change_table_v2_categories.php} (93%) rename tests/specs/blog_v2/migrations_pgsql_db/{m200000_000000_change_table_v2_posts.php => m200000_000002_change_table_v2_posts.php} (95%) rename tests/specs/blog_v2/migrations_pgsql_db/{m200000_000001_create_table_v2_tags.php => m200000_000003_create_table_v2_tags.php} (91%) rename tests/specs/blog_v2/migrations_pgsql_db/{m200000_000002_create_table_posts2tags.php => m200000_000004_create_table_posts2tags.php} (93%) diff --git a/tests/specs/blog_v2/migrations_maria_db/m200000_000004_change_table_v2_users.php b/tests/specs/blog_v2/migrations_maria_db/m200000_000000_change_table_v2_users.php similarity index 95% rename from tests/specs/blog_v2/migrations_maria_db/m200000_000004_change_table_v2_users.php rename to tests/specs/blog_v2/migrations_maria_db/m200000_000000_change_table_v2_users.php index bf1c82fd..4a946df2 100644 --- a/tests/specs/blog_v2/migrations_maria_db/m200000_000004_change_table_v2_users.php +++ b/tests/specs/blog_v2/migrations_maria_db/m200000_000000_change_table_v2_users.php @@ -3,7 +3,7 @@ /** * Table for User */ -class m200000_000004_change_table_v2_users extends \yii\db\Migration +class m200000_000000_change_table_v2_users extends \yii\db\Migration { public function up() { diff --git a/tests/specs/blog_v2/migrations_mysql_db/m200000_000003_change_table_v2_categories.php b/tests/specs/blog_v2/migrations_maria_db/m200000_000001_change_table_v2_categories.php similarity index 94% rename from tests/specs/blog_v2/migrations_mysql_db/m200000_000003_change_table_v2_categories.php rename to tests/specs/blog_v2/migrations_maria_db/m200000_000001_change_table_v2_categories.php index e608ed52..c488ec52 100644 --- a/tests/specs/blog_v2/migrations_mysql_db/m200000_000003_change_table_v2_categories.php +++ b/tests/specs/blog_v2/migrations_maria_db/m200000_000001_change_table_v2_categories.php @@ -3,7 +3,7 @@ /** * Table for Category */ -class m200000_000003_change_table_v2_categories extends \yii\db\Migration +class m200000_000001_change_table_v2_categories extends \yii\db\Migration { public function up() { diff --git a/tests/specs/blog_v2/migrations_maria_db/m200000_000000_change_table_v2_posts.php b/tests/specs/blog_v2/migrations_maria_db/m200000_000002_change_table_v2_posts.php similarity index 95% rename from tests/specs/blog_v2/migrations_maria_db/m200000_000000_change_table_v2_posts.php rename to tests/specs/blog_v2/migrations_maria_db/m200000_000002_change_table_v2_posts.php index 5c43dabf..f8790fd3 100644 --- a/tests/specs/blog_v2/migrations_maria_db/m200000_000000_change_table_v2_posts.php +++ b/tests/specs/blog_v2/migrations_maria_db/m200000_000002_change_table_v2_posts.php @@ -3,7 +3,7 @@ /** * Table for Post */ -class m200000_000000_change_table_v2_posts extends \yii\db\Migration +class m200000_000002_change_table_v2_posts extends \yii\db\Migration { public function up() { diff --git a/tests/specs/blog_v2/migrations_mysql_db/m200000_000001_create_table_v2_tags.php b/tests/specs/blog_v2/migrations_maria_db/m200000_000003_create_table_v2_tags.php similarity index 88% rename from tests/specs/blog_v2/migrations_mysql_db/m200000_000001_create_table_v2_tags.php rename to tests/specs/blog_v2/migrations_maria_db/m200000_000003_create_table_v2_tags.php index 1e671e96..5ed6326c 100644 --- a/tests/specs/blog_v2/migrations_mysql_db/m200000_000001_create_table_v2_tags.php +++ b/tests/specs/blog_v2/migrations_maria_db/m200000_000003_create_table_v2_tags.php @@ -3,7 +3,7 @@ /** * Table for Tag */ -class m200000_000001_create_table_v2_tags extends \yii\db\Migration +class m200000_000003_create_table_v2_tags extends \yii\db\Migration { public function up() { diff --git a/tests/specs/blog_v2/migrations_maria_db/m200000_000002_create_table_posts2tags.php b/tests/specs/blog_v2/migrations_maria_db/m200000_000004_create_table_posts2tags.php similarity index 93% rename from tests/specs/blog_v2/migrations_maria_db/m200000_000002_create_table_posts2tags.php rename to tests/specs/blog_v2/migrations_maria_db/m200000_000004_create_table_posts2tags.php index 2e959d10..9e50b861 100644 --- a/tests/specs/blog_v2/migrations_maria_db/m200000_000002_create_table_posts2tags.php +++ b/tests/specs/blog_v2/migrations_maria_db/m200000_000004_create_table_posts2tags.php @@ -3,7 +3,7 @@ /** * Table for Posts2Tags */ -class m200000_000002_create_table_posts2tags extends \yii\db\Migration +class m200000_000004_create_table_posts2tags extends \yii\db\Migration { public function up() { diff --git a/tests/specs/blog_v2/migrations_mysql_db/m200000_000004_change_table_v2_users.php b/tests/specs/blog_v2/migrations_mysql_db/m200000_000000_change_table_v2_users.php similarity index 95% rename from tests/specs/blog_v2/migrations_mysql_db/m200000_000004_change_table_v2_users.php rename to tests/specs/blog_v2/migrations_mysql_db/m200000_000000_change_table_v2_users.php index b7a1f5e3..23a2e3b1 100644 --- a/tests/specs/blog_v2/migrations_mysql_db/m200000_000004_change_table_v2_users.php +++ b/tests/specs/blog_v2/migrations_mysql_db/m200000_000000_change_table_v2_users.php @@ -3,7 +3,7 @@ /** * Table for User */ -class m200000_000004_change_table_v2_users extends \yii\db\Migration +class m200000_000000_change_table_v2_users extends \yii\db\Migration { public function up() { diff --git a/tests/specs/blog_v2/migrations_maria_db/m200000_000003_change_table_v2_categories.php b/tests/specs/blog_v2/migrations_mysql_db/m200000_000001_change_table_v2_categories.php similarity index 94% rename from tests/specs/blog_v2/migrations_maria_db/m200000_000003_change_table_v2_categories.php rename to tests/specs/blog_v2/migrations_mysql_db/m200000_000001_change_table_v2_categories.php index e608ed52..c488ec52 100644 --- a/tests/specs/blog_v2/migrations_maria_db/m200000_000003_change_table_v2_categories.php +++ b/tests/specs/blog_v2/migrations_mysql_db/m200000_000001_change_table_v2_categories.php @@ -3,7 +3,7 @@ /** * Table for Category */ -class m200000_000003_change_table_v2_categories extends \yii\db\Migration +class m200000_000001_change_table_v2_categories extends \yii\db\Migration { public function up() { diff --git a/tests/specs/blog_v2/migrations_mysql_db/m200000_000000_change_table_v2_posts.php b/tests/specs/blog_v2/migrations_mysql_db/m200000_000002_change_table_v2_posts.php similarity index 95% rename from tests/specs/blog_v2/migrations_mysql_db/m200000_000000_change_table_v2_posts.php rename to tests/specs/blog_v2/migrations_mysql_db/m200000_000002_change_table_v2_posts.php index be309829..d3b7fc2b 100644 --- a/tests/specs/blog_v2/migrations_mysql_db/m200000_000000_change_table_v2_posts.php +++ b/tests/specs/blog_v2/migrations_mysql_db/m200000_000002_change_table_v2_posts.php @@ -3,7 +3,7 @@ /** * Table for Post */ -class m200000_000000_change_table_v2_posts extends \yii\db\Migration +class m200000_000002_change_table_v2_posts extends \yii\db\Migration { public function up() { diff --git a/tests/specs/blog_v2/migrations_maria_db/m200000_000001_create_table_v2_tags.php b/tests/specs/blog_v2/migrations_mysql_db/m200000_000003_create_table_v2_tags.php similarity index 88% rename from tests/specs/blog_v2/migrations_maria_db/m200000_000001_create_table_v2_tags.php rename to tests/specs/blog_v2/migrations_mysql_db/m200000_000003_create_table_v2_tags.php index 1e671e96..5ed6326c 100644 --- a/tests/specs/blog_v2/migrations_maria_db/m200000_000001_create_table_v2_tags.php +++ b/tests/specs/blog_v2/migrations_mysql_db/m200000_000003_create_table_v2_tags.php @@ -3,7 +3,7 @@ /** * Table for Tag */ -class m200000_000001_create_table_v2_tags extends \yii\db\Migration +class m200000_000003_create_table_v2_tags extends \yii\db\Migration { public function up() { diff --git a/tests/specs/blog_v2/migrations_mysql_db/m200000_000002_create_table_posts2tags.php b/tests/specs/blog_v2/migrations_mysql_db/m200000_000004_create_table_posts2tags.php similarity index 93% rename from tests/specs/blog_v2/migrations_mysql_db/m200000_000002_create_table_posts2tags.php rename to tests/specs/blog_v2/migrations_mysql_db/m200000_000004_create_table_posts2tags.php index 2e959d10..9e50b861 100644 --- a/tests/specs/blog_v2/migrations_mysql_db/m200000_000002_create_table_posts2tags.php +++ b/tests/specs/blog_v2/migrations_mysql_db/m200000_000004_create_table_posts2tags.php @@ -3,7 +3,7 @@ /** * Table for Posts2Tags */ -class m200000_000002_create_table_posts2tags extends \yii\db\Migration +class m200000_000004_create_table_posts2tags extends \yii\db\Migration { public function up() { diff --git a/tests/specs/blog_v2/migrations_mysql_db/m200000_000005_change_table_v2_comments.php b/tests/specs/blog_v2/migrations_mysql_db/m200000_000005_change_table_v2_comments.php index 475a2639..d53d0505 100644 --- a/tests/specs/blog_v2/migrations_mysql_db/m200000_000005_change_table_v2_comments.php +++ b/tests/specs/blog_v2/migrations_mysql_db/m200000_000005_change_table_v2_comments.php @@ -7,8 +7,8 @@ class m200000_000005_change_table_v2_comments extends \yii\db\Migration { public function up() { - $this->dropForeignKey('fk_v2_comments_post_id_v2_posts_uid', '{{%v2_comments}}'); $this->dropForeignKey('fk_v2_comments_author_id_v2_users_id', '{{%v2_comments}}'); + $this->dropForeignKey('fk_v2_comments_post_id_v2_posts_uid', '{{%v2_comments}}'); $this->addColumn('{{%v2_comments}}', 'user_id', $this->bigInteger()->null()->defaultValue(null)->after('post_id')); $this->dropColumn('{{%v2_comments}}', 'author_id'); $this->alterColumn('{{%v2_comments}}', 'message', $this->text()->notNull()); @@ -27,7 +27,7 @@ public function down() $this->alterColumn('{{%v2_comments}}', 'message', 'json NOT NULL'); $this->addColumn('{{%v2_comments}}', 'author_id', $this->integer()->notNull()); $this->dropColumn('{{%v2_comments}}', 'user_id'); - $this->addForeignKey('fk_v2_comments_author_id_v2_users_id', '{{%v2_comments}}', 'author_id', 'itt_v2_users', 'id'); $this->addForeignKey('fk_v2_comments_post_id_v2_posts_uid', '{{%v2_comments}}', 'post_id', 'itt_v2_posts', 'uid'); + $this->addForeignKey('fk_v2_comments_author_id_v2_users_id', '{{%v2_comments}}', 'author_id', 'itt_v2_users', 'id'); } } diff --git a/tests/specs/blog_v2/migrations_pgsql_db/m200000_000004_change_table_v2_users.php b/tests/specs/blog_v2/migrations_pgsql_db/m200000_000000_change_table_v2_users.php similarity index 96% rename from tests/specs/blog_v2/migrations_pgsql_db/m200000_000004_change_table_v2_users.php rename to tests/specs/blog_v2/migrations_pgsql_db/m200000_000000_change_table_v2_users.php index a57ea8df..cb77b61d 100644 --- a/tests/specs/blog_v2/migrations_pgsql_db/m200000_000004_change_table_v2_users.php +++ b/tests/specs/blog_v2/migrations_pgsql_db/m200000_000000_change_table_v2_users.php @@ -3,7 +3,7 @@ /** * Table for User */ -class m200000_000004_change_table_v2_users extends \yii\db\Migration +class m200000_000000_change_table_v2_users extends \yii\db\Migration { public function safeUp() { diff --git a/tests/specs/blog_v2/migrations_pgsql_db/m200000_000003_change_table_v2_categories.php b/tests/specs/blog_v2/migrations_pgsql_db/m200000_000001_change_table_v2_categories.php similarity index 93% rename from tests/specs/blog_v2/migrations_pgsql_db/m200000_000003_change_table_v2_categories.php rename to tests/specs/blog_v2/migrations_pgsql_db/m200000_000001_change_table_v2_categories.php index 5f934936..9c307743 100644 --- a/tests/specs/blog_v2/migrations_pgsql_db/m200000_000003_change_table_v2_categories.php +++ b/tests/specs/blog_v2/migrations_pgsql_db/m200000_000001_change_table_v2_categories.php @@ -3,7 +3,7 @@ /** * Table for Category */ -class m200000_000003_change_table_v2_categories extends \yii\db\Migration +class m200000_000001_change_table_v2_categories extends \yii\db\Migration { public function safeUp() { diff --git a/tests/specs/blog_v2/migrations_pgsql_db/m200000_000000_change_table_v2_posts.php b/tests/specs/blog_v2/migrations_pgsql_db/m200000_000002_change_table_v2_posts.php similarity index 95% rename from tests/specs/blog_v2/migrations_pgsql_db/m200000_000000_change_table_v2_posts.php rename to tests/specs/blog_v2/migrations_pgsql_db/m200000_000002_change_table_v2_posts.php index 5188983b..474c6c82 100644 --- a/tests/specs/blog_v2/migrations_pgsql_db/m200000_000000_change_table_v2_posts.php +++ b/tests/specs/blog_v2/migrations_pgsql_db/m200000_000002_change_table_v2_posts.php @@ -3,7 +3,7 @@ /** * Table for Post */ -class m200000_000000_change_table_v2_posts extends \yii\db\Migration +class m200000_000002_change_table_v2_posts extends \yii\db\Migration { public function safeUp() { diff --git a/tests/specs/blog_v2/migrations_pgsql_db/m200000_000001_create_table_v2_tags.php b/tests/specs/blog_v2/migrations_pgsql_db/m200000_000003_create_table_v2_tags.php similarity index 91% rename from tests/specs/blog_v2/migrations_pgsql_db/m200000_000001_create_table_v2_tags.php rename to tests/specs/blog_v2/migrations_pgsql_db/m200000_000003_create_table_v2_tags.php index 2466cff0..45593cfa 100644 --- a/tests/specs/blog_v2/migrations_pgsql_db/m200000_000001_create_table_v2_tags.php +++ b/tests/specs/blog_v2/migrations_pgsql_db/m200000_000003_create_table_v2_tags.php @@ -3,7 +3,7 @@ /** * Table for Tag */ -class m200000_000001_create_table_v2_tags extends \yii\db\Migration +class m200000_000003_create_table_v2_tags extends \yii\db\Migration { public function safeUp() { diff --git a/tests/specs/blog_v2/migrations_pgsql_db/m200000_000002_create_table_posts2tags.php b/tests/specs/blog_v2/migrations_pgsql_db/m200000_000004_create_table_posts2tags.php similarity index 93% rename from tests/specs/blog_v2/migrations_pgsql_db/m200000_000002_create_table_posts2tags.php rename to tests/specs/blog_v2/migrations_pgsql_db/m200000_000004_create_table_posts2tags.php index d518ff32..4e4766fa 100644 --- a/tests/specs/blog_v2/migrations_pgsql_db/m200000_000002_create_table_posts2tags.php +++ b/tests/specs/blog_v2/migrations_pgsql_db/m200000_000004_create_table_posts2tags.php @@ -3,7 +3,7 @@ /** * Table for Posts2Tags */ -class m200000_000002_create_table_posts2tags extends \yii\db\Migration +class m200000_000004_create_table_posts2tags extends \yii\db\Migration { public function safeUp() { From cc829185284307322306aaf26cf286c8381681cc Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Fri, 21 Jun 2024 20:39:56 +0530 Subject: [PATCH 032/358] Fix issue in test --- .../m200000_000005_change_table_v2_comments.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/specs/blog_v2/migrations_mysql_db/m200000_000005_change_table_v2_comments.php b/tests/specs/blog_v2/migrations_mysql_db/m200000_000005_change_table_v2_comments.php index d53d0505..475a2639 100644 --- a/tests/specs/blog_v2/migrations_mysql_db/m200000_000005_change_table_v2_comments.php +++ b/tests/specs/blog_v2/migrations_mysql_db/m200000_000005_change_table_v2_comments.php @@ -7,8 +7,8 @@ class m200000_000005_change_table_v2_comments extends \yii\db\Migration { public function up() { - $this->dropForeignKey('fk_v2_comments_author_id_v2_users_id', '{{%v2_comments}}'); $this->dropForeignKey('fk_v2_comments_post_id_v2_posts_uid', '{{%v2_comments}}'); + $this->dropForeignKey('fk_v2_comments_author_id_v2_users_id', '{{%v2_comments}}'); $this->addColumn('{{%v2_comments}}', 'user_id', $this->bigInteger()->null()->defaultValue(null)->after('post_id')); $this->dropColumn('{{%v2_comments}}', 'author_id'); $this->alterColumn('{{%v2_comments}}', 'message', $this->text()->notNull()); @@ -27,7 +27,7 @@ public function down() $this->alterColumn('{{%v2_comments}}', 'message', 'json NOT NULL'); $this->addColumn('{{%v2_comments}}', 'author_id', $this->integer()->notNull()); $this->dropColumn('{{%v2_comments}}', 'user_id'); - $this->addForeignKey('fk_v2_comments_post_id_v2_posts_uid', '{{%v2_comments}}', 'post_id', 'itt_v2_posts', 'uid'); $this->addForeignKey('fk_v2_comments_author_id_v2_users_id', '{{%v2_comments}}', 'author_id', 'itt_v2_users', 'id'); + $this->addForeignKey('fk_v2_comments_post_id_v2_posts_uid', '{{%v2_comments}}', 'post_id', 'itt_v2_posts', 'uid'); } } From 7a426191a9d50680bee4e58e8a49d3ca2d971bad Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Fri, 21 Jun 2024 20:55:30 +0530 Subject: [PATCH 033/358] Add more tests for different PKs --- src/lib/generators/MigrationsGenerator.php | 1 + .../132_create_migration_for_drop_table.yaml | 4 +++- tests/unit/IssueFixTest.php | 23 ++++++++++++++----- 3 files changed, 21 insertions(+), 7 deletions(-) diff --git a/src/lib/generators/MigrationsGenerator.php b/src/lib/generators/MigrationsGenerator.php index ee161588..3ddf6810 100644 --- a/src/lib/generators/MigrationsGenerator.php +++ b/src/lib/generators/MigrationsGenerator.php @@ -131,6 +131,7 @@ public function buildMigrations():array } } + // TODO remove // for deleted schema, create migration for drop table // foreach ($this->tablesToDrop as $tableName) { // $table = Yii::$app->db->schema->getTableSchema($tableName); diff --git a/tests/specs/issue_fix/132_create_migration_for_drop_table/132_create_migration_for_drop_table.yaml b/tests/specs/issue_fix/132_create_migration_for_drop_table/132_create_migration_for_drop_table.yaml index d88a1ffc..471a8c7b 100644 --- a/tests/specs/issue_fix/132_create_migration_for_drop_table/132_create_migration_for_drop_table.yaml +++ b/tests/specs/issue_fix/132_create_migration_for_drop_table/132_create_migration_for_drop_table.yaml @@ -7,7 +7,9 @@ x-deleted-schemas: # don't use x-keep-table, use x-deleted-schemas - Pristine - Fruit # table name evaluated to `itt_fruits`. `itt_` is prefix # - Mango: the_mango7 # custom table name; `x-table` -# - Upk + - Upk + - Bigpk + - Ubigpk paths: /: diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index f9d0ae92..29e98a07 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -283,18 +283,27 @@ public function testCreateMigrationForDropTable132() // $this->deleteTablesForCreateMigrationForDropTable132(); $this->createTablesForCreateMigrationForDropTable132(); $this->runGenerator($testFile); - $this->runActualMigrations('mysql', 3); + $this->runActualMigrations('mysql', 6); // ... TODO compare files $this->deleteTablesForCreateMigrationForDropTable132(); - // $this->deleteTables(); + $this->deleteTables(); } private function createTablesForCreateMigrationForDropTable132() { -// Yii::$app->db->createCommand()->createTable('{{%upks}}', [ -// 'id' => 'upk', -// 'name' => 'string(150)', -// ])->execute(); + Yii::$app->db->createCommand()->createTable('{{%upks}}', [ + 'id' => 'upk', + 'name' => 'string(150)', + ])->execute(); + Yii::$app->db->createCommand()->createTable('{{%bigpks}}', [ + 'id' => 'bigpk', + 'name' => 'string(150)', + ])->execute(); + Yii::$app->db->createCommand()->createTable('{{%ubigpks}}', [ + 'id' => 'ubigpk', + 'name' => 'string(150)', + ])->execute(); + Yii::$app->db->createCommand()->createTable('{{%fruits}}', [ 'id' => 'pk', @@ -314,6 +323,8 @@ private function deleteTablesForCreateMigrationForDropTable132() Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%pristines}}')->execute(); Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%fruits}}')->execute(); Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%upks}}')->execute(); + Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%bigpks}}')->execute(); + Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%ubigpks}}')->execute(); } public function test162BugDollarrefWithXFaker() From 11a7d5e49605c1788b50a55c34f7d5b2d1e77f4a Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Sat, 22 Jun 2024 15:43:00 +0530 Subject: [PATCH 034/358] Handle case of custom column name --- src/lib/SchemaToDatabase.php | 2 +- src/lib/generators/MigrationsGenerator.php | 1 - .../132_create_migration_for_drop_table.yaml | 7 +++--- tests/unit/IssueFixTest.php | 24 +++++++++++++++++-- 4 files changed, 27 insertions(+), 7 deletions(-) diff --git a/src/lib/SchemaToDatabase.php b/src/lib/SchemaToDatabase.php index 4bc51b38..fcba88d7 100644 --- a/src/lib/SchemaToDatabase.php +++ b/src/lib/SchemaToDatabase.php @@ -282,7 +282,7 @@ public static function f7(array $schemasToDrop): array // TODO rename 'drop' => true ]); $dbModelsToDrop[$key] = $dbModelHere; - // TODO + // TODO remove // $mm = new MigrationModel($dbModelHere); // $builder = new MigrationRecordBuilder($this->db->getSchema()); // $mm->addUpCode($builder->dropTable($tableName)) diff --git a/src/lib/generators/MigrationsGenerator.php b/src/lib/generators/MigrationsGenerator.php index 3ddf6810..6e37b90f 100644 --- a/src/lib/generators/MigrationsGenerator.php +++ b/src/lib/generators/MigrationsGenerator.php @@ -175,7 +175,6 @@ protected function createBuilder(DbModel $model):BaseMigrationBuilder protected function sortMigrationsByDeps():array { $this->sorted = []; -// ksort($this->migrations); foreach ($this->migrations as $migration) { //echo "adding {$migration->tableAlias}\n"; $this->sortByDependencyRecurse($migration); diff --git a/tests/specs/issue_fix/132_create_migration_for_drop_table/132_create_migration_for_drop_table.yaml b/tests/specs/issue_fix/132_create_migration_for_drop_table/132_create_migration_for_drop_table.yaml index 471a8c7b..607ec5da 100644 --- a/tests/specs/issue_fix/132_create_migration_for_drop_table/132_create_migration_for_drop_table.yaml +++ b/tests/specs/issue_fix/132_create_migration_for_drop_table/132_create_migration_for_drop_table.yaml @@ -3,10 +3,11 @@ info: version: 1.0.0 title: 132_create_migration_for_drop_table \#132 -x-deleted-schemas: # don't use x-keep-table, use x-deleted-schemas +x-deleted-schemas: - Pristine - - Fruit # table name evaluated to `itt_fruits`. `itt_` is prefix -# - Mango: the_mango7 # custom table name; `x-table` + - Fruit # Example: table name evaluated to `itt_fruits`. `itt_` is prefix set in DB config + - Mango: the_mango_table_name # custom table name; see `x-table` in README.md + - Animal: the_animal_table_name - Upk - Bigpk - Ubigpk diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index 29e98a07..fa5aeeb7 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -283,7 +283,7 @@ public function testCreateMigrationForDropTable132() // $this->deleteTablesForCreateMigrationForDropTable132(); $this->createTablesForCreateMigrationForDropTable132(); $this->runGenerator($testFile); - $this->runActualMigrations('mysql', 6); + $this->runActualMigrations('mysql', 8); // ... TODO compare files $this->deleteTablesForCreateMigrationForDropTable132(); $this->deleteTables(); @@ -304,10 +304,11 @@ private function createTablesForCreateMigrationForDropTable132() 'name' => 'string(150)', ])->execute(); - + // --- Yii::$app->db->createCommand()->createTable('{{%fruits}}', [ 'id' => 'pk', 'name' => 'string(150)', + 'food_of' => 'int' ])->execute(); Yii::$app->db->createCommand()->createTable('{{%pristines}}', [ 'id' => 'pk', @@ -315,16 +316,35 @@ private function createTablesForCreateMigrationForDropTable132() 'fruit_id' => 'int', // FK ])->execute(); Yii::$app->db->createCommand()->addForeignKey('name', '{{%pristines}}', 'fruit_id', '{{%fruits}}', 'id')->execute(); + + // --- + Yii::$app->db->createCommand()->createTable('{{%the_animal_table_name}}', [ + 'id' => 'pk', + 'name' => 'string(150)', + ])->execute(); + Yii::$app->db->createCommand()->addForeignKey('name2', '{{%fruits}}', 'food_of', '{{%the_animal_table_name}}', 'id')->execute(); + Yii::$app->db->createCommand()->createTable('{{%the_mango_table_name}}', [ + 'id' => 'pk', + 'name' => 'string(150)', + 'food_of' => 'int' + ])->execute(); + Yii::$app->db->createCommand()->addForeignKey('animal_fruit_fk', '{{%the_mango_table_name}}', 'food_of', '{{%the_animal_table_name}}', 'id')->execute(); } private function deleteTablesForCreateMigrationForDropTable132() { Yii::$app->db->createCommand()->dropForeignKey('name', '{{%pristines}}')->execute(); Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%pristines}}')->execute(); + Yii::$app->db->createCommand()->dropForeignKey('name2', '{{%fruits}}')->execute(); Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%fruits}}')->execute(); + Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%upks}}')->execute(); Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%bigpks}}')->execute(); Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%ubigpks}}')->execute(); + + Yii::$app->db->createCommand()->dropForeignKey('animal_fruit_fk', '{{%the_mango_table_name}}')->execute(); + Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%the_mango_table_name}}')->execute(); + Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%the_animal_table_name}}')->execute(); } public function test162BugDollarrefWithXFaker() From e0b96a3135ca90e431706a8a01729553c4254ced Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Sat, 22 Jun 2024 17:42:08 +0530 Subject: [PATCH 035/358] Separate tests for PgSQL and more --- src/lib/SchemaToDatabase.php | 7 +- src/lib/migrations/BaseMigrationBuilder.php | 13 +-- .../migrations/PostgresMigrationBuilder.php | 2 + tests/unit/IssueFixTest.php | 81 +++++++++++++++++++ 4 files changed, 97 insertions(+), 6 deletions(-) diff --git a/src/lib/SchemaToDatabase.php b/src/lib/SchemaToDatabase.php index fcba88d7..9e555310 100644 --- a/src/lib/SchemaToDatabase.php +++ b/src/lib/SchemaToDatabase.php @@ -314,11 +314,16 @@ public static function attributesFromColumnSchemas(array $columnSchemas) $attribute = new Attribute($columnSchema->name, [ 'phpType' => $columnSchema->phpType, // pk 'dbType' => $columnSchema->dbType, // pk + 'fkColName' => $columnSchema->name, + + 'required' => !$columnSchema->allowNull && ($columnSchema->defaultValue === null), 'nullable' => $columnSchema->allowNull, 'size' => $columnSchema->size, - // 'limits' => ['min' => null, 'max' => null, 'minLength' => null], // TODO + 'primary' => $columnSchema->isPrimaryKey, 'enumValues' => $columnSchema->enumValues, + 'defaultValue' => $columnSchema->defaultValue, + 'description' => $columnSchema->comment, ]); // generate PK using `->primaryKeys()` or similar methods instead of separate SQL statement which sets only PK to a column of table diff --git a/src/lib/migrations/BaseMigrationBuilder.php b/src/lib/migrations/BaseMigrationBuilder.php index 632f48a8..cc0706fc 100644 --- a/src/lib/migrations/BaseMigrationBuilder.php +++ b/src/lib/migrations/BaseMigrationBuilder.php @@ -172,8 +172,6 @@ public function buildSecondary(?ManyToManyRelation $relation = null):MigrationMo $this->migration = Yii::createObject(MigrationModel::class, [$this->model, false, $relation, []]); $this->newColumns = $relation->columnSchema ?? $this->model->attributesToColumnSchema(); - $this->newColumns = $this->model->drop ? [] : $this->newColumns; - $wantNames = array_keys($this->newColumns); $haveNames = $this->tableSchema->columnNames; $columnsForCreate = array_map( @@ -192,6 +190,14 @@ function (string $unknownColumn) { $columnsForChange = array_intersect($wantNames, $haveNames); + if ($this->model->drop) { + $this->newColumns = []; + $wantNames = []; + $columnsForCreate = []; + $columnsForChange = []; + $columnsForDrop = []; + } + $this->buildColumnsCreation($columnsForCreate); if ($this->model->junctionCols && !isset($this->model->attributes[$this->model->pkName])) { if (!empty(array_intersect($columnsForDrop, $this->model->junctionCols))) { @@ -254,9 +260,6 @@ protected function buildColumnsCreation(array $columns):void */ protected function buildColumnsDrop(array $columns):void { - if ($this->model->drop) { - return; - } foreach ($columns as $column) { $tableName = $this->model->getTableAlias(); if ($column->isPrimaryKey && !$column->autoIncrement) { diff --git a/src/lib/migrations/PostgresMigrationBuilder.php b/src/lib/migrations/PostgresMigrationBuilder.php index b8c9324d..7e7c2598 100644 --- a/src/lib/migrations/PostgresMigrationBuilder.php +++ b/src/lib/migrations/PostgresMigrationBuilder.php @@ -18,6 +18,7 @@ final class PostgresMigrationBuilder extends BaseMigrationBuilder * @param array|ColumnSchema[] $columns * @throws \yii\base\InvalidConfigException */ + #[\Override] protected function buildColumnsCreation(array $columns):void { foreach ($columns as $column) { @@ -35,6 +36,7 @@ protected function buildColumnsCreation(array $columns):void * @param array|ColumnSchema[] $columns * @throws \yii\base\InvalidConfigException */ + #[\Override] protected function buildColumnsDrop(array $columns):void { foreach ($columns as $column) { diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index fa5aeeb7..87b157e4 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -302,6 +302,10 @@ private function createTablesForCreateMigrationForDropTable132() Yii::$app->db->createCommand()->createTable('{{%ubigpks}}', [ 'id' => 'ubigpk', 'name' => 'string(150)', + 'size' => "ENUM('x-small', 'small', 'medium', 'large', 'x-large') NOT NULL DEFAULT 'x-small'", + 'd SMALLINT UNSIGNED ZEROFILL', + 'e' => 'SMALLINT UNSIGNED ZEROFILL', + 'f' => 'decimal(12,4)', ])->execute(); // --- @@ -347,6 +351,83 @@ private function deleteTablesForCreateMigrationForDropTable132() Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%the_animal_table_name}}')->execute(); } + // Create migration for drop table if a entire schema is deleted from OpenAPI spec #132 + // https://github.com/cebe/yii2-openapi/issues/132 + // For PgSQL + public function testCreateMigrationForDropTable132ForPgsql() + { + $this->changeDbToPgsql(); + $testFile = Yii::getAlias("@specs/issue_fix/132_create_migration_for_drop_table/132_create_migration_for_drop_table.php"); + $this->createTablesForCreateMigrationForDropTable132ForPgsql(); + $this->runGenerator($testFile, 'pgsql'); + $this->runActualMigrations('pgsql', 8); + // ... TODO compare files + $this->deleteTablesForCreateMigrationForDropTable132ForPgsql(); + $this->deleteTables(); + } + + private function createTablesForCreateMigrationForDropTable132ForPgsql() + { + Yii::$app->db->createCommand()->createTable('{{%upks}}', [ + 'id' => 'upk', + 'name' => 'string(150)', + ])->execute(); + Yii::$app->db->createCommand()->createTable('{{%bigpks}}', [ + 'id' => 'bigpk', + 'name' => 'string(150)', + ])->execute(); + Yii::$app->db->createCommand()->createTable('{{%ubigpks}}', [ + 'id' => 'ubigpk', + 'name' => 'string(150)', +// 'size' => "ENUM('x-small', 'small', 'medium', 'large', 'x-large') NOT NULL DEFAULT 'x-small'", +// 'd SMALLINT UNSIGNED ZEROFILL', +// 'e' => 'SMALLINT UNSIGNED ZEROFILL', +// 'f' => 'decimal(12,4)', + ])->execute(); + + // --- + Yii::$app->db->createCommand()->createTable('{{%fruits}}', [ + 'id' => 'pk', + 'name' => 'string(150)', + 'food_of' => 'int' + ])->execute(); + Yii::$app->db->createCommand()->createTable('{{%pristines}}', [ + 'id' => 'pk', + 'name' => 'string(151)', + 'fruit_id' => 'int', // FK + ])->execute(); + Yii::$app->db->createCommand()->addForeignKey('name', '{{%pristines}}', 'fruit_id', '{{%fruits}}', 'id')->execute(); + + // --- + Yii::$app->db->createCommand()->createTable('{{%the_animal_table_name}}', [ + 'id' => 'pk', + 'name' => 'string(150)', + ])->execute(); + Yii::$app->db->createCommand()->addForeignKey('name2', '{{%fruits}}', 'food_of', '{{%the_animal_table_name}}', 'id')->execute(); + Yii::$app->db->createCommand()->createTable('{{%the_mango_table_name}}', [ + 'id' => 'pk', + 'name' => 'string(150)', + 'food_of' => 'int' + ])->execute(); + Yii::$app->db->createCommand()->addForeignKey('animal_fruit_fk', '{{%the_mango_table_name}}', 'food_of', '{{%the_animal_table_name}}', 'id')->execute(); + } + + private function deleteTablesForCreateMigrationForDropTable132ForPgsql() + { + Yii::$app->db->createCommand()->dropForeignKey('name', '{{%pristines}}')->execute(); + Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%pristines}}')->execute(); + Yii::$app->db->createCommand()->dropForeignKey('name2', '{{%fruits}}')->execute(); + Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%fruits}}')->execute(); + + Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%upks}}')->execute(); + Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%bigpks}}')->execute(); + Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%ubigpks}}')->execute(); + + Yii::$app->db->createCommand()->dropForeignKey('animal_fruit_fk', '{{%the_mango_table_name}}')->execute(); + Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%the_mango_table_name}}')->execute(); + Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%the_animal_table_name}}')->execute(); + } + public function test162BugDollarrefWithXFaker() { $testFile = Yii::getAlias("@specs/issue_fix/162_bug_dollarref_with_x_faker/162_bug_dollarref_with_x_faker.php"); From f06d6dc34543251580e54ae7e3b3d1028b9aa36d Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Sat, 22 Jun 2024 20:22:01 +0530 Subject: [PATCH 036/358] Apply work-around for https://github.com/yiisoft/yii2/issues/20209 --- src/lib/SchemaToDatabase.php | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/lib/SchemaToDatabase.php b/src/lib/SchemaToDatabase.php index 9e555310..3a94b4d8 100644 --- a/src/lib/SchemaToDatabase.php +++ b/src/lib/SchemaToDatabase.php @@ -334,9 +334,8 @@ public static function attributesFromColumnSchemas(array $columnSchemas) ]) && $columnSchema->isPrimaryKey === true && $columnSchema->autoIncrement ) { - if (stripos($columnSchema->dbType, 'BIGINT') !== false # MySQL, MariaDB - || stripos($columnSchema->dbType, 'bigserial') !== false # PgSQL - ) { + str_ireplace(['BIGINT', 'int8', 'bigserial', 'serial8'], 'nothing',$columnSchema->dbType, $count); # can be refactored if https://github.com/yiisoft/yii2/issues/20209 is fixed + if ($count) { if ($columnSchema->unsigned) { $attribute->dbType = Schema::TYPE_UBIGPK; } else { From 37cfd689a7bddc17950dd9d1780d5a5be92f3135 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Sat, 22 Jun 2024 20:29:11 +0530 Subject: [PATCH 037/358] Fix style --- src/lib/SchemaToDatabase.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/lib/SchemaToDatabase.php b/src/lib/SchemaToDatabase.php index 3a94b4d8..faab8621 100644 --- a/src/lib/SchemaToDatabase.php +++ b/src/lib/SchemaToDatabase.php @@ -334,7 +334,7 @@ public static function attributesFromColumnSchemas(array $columnSchemas) ]) && $columnSchema->isPrimaryKey === true && $columnSchema->autoIncrement ) { - str_ireplace(['BIGINT', 'int8', 'bigserial', 'serial8'], 'nothing',$columnSchema->dbType, $count); # can be refactored if https://github.com/yiisoft/yii2/issues/20209 is fixed + str_ireplace(['BIGINT', 'int8', 'bigserial', 'serial8'], 'nothing', $columnSchema->dbType, $count); # can be refactored if https://github.com/yiisoft/yii2/issues/20209 is fixed if ($count) { if ($columnSchema->unsigned) { $attribute->dbType = Schema::TYPE_UBIGPK; From feba5f103ecdc78c791fab20dc419a3e0886b1a7 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Mon, 24 Jun 2024 19:18:47 +0530 Subject: [PATCH 038/358] Add support for PgSQL array data type --- src/lib/SchemaToDatabase.php | 13 ++++++++++--- .../132_create_migration_for_drop_table.yaml | 14 +++++++------- tests/unit/IssueFixTest.php | 3 +++ 3 files changed, 20 insertions(+), 10 deletions(-) diff --git a/src/lib/SchemaToDatabase.php b/src/lib/SchemaToDatabase.php index faab8621..3489e455 100644 --- a/src/lib/SchemaToDatabase.php +++ b/src/lib/SchemaToDatabase.php @@ -272,7 +272,7 @@ public static function f7(array $schemasToDrop): array // TODO rename throw new \Exception('Malformed list of schemas to delete'); } - $table = Yii::$app->db->schema->getTableSchema("{{%$tableName}}"); + $table = Yii::$app->db->schema->getTableSchema("{{%$tableName}}", true); if ($table) { $dbModelHere = new DbModel([ 'pkName' => $table->primaryKey[0], @@ -312,8 +312,8 @@ public static function attributesFromColumnSchemas(array $columnSchemas) /** @var $columnSchema ColumnSchema */ unset($attribute); $attribute = new Attribute($columnSchema->name, [ - 'phpType' => $columnSchema->phpType, // pk - 'dbType' => $columnSchema->dbType, // pk + 'phpType' => $columnSchema->phpType, + 'dbType' => $columnSchema->dbType, 'fkColName' => $columnSchema->name, 'required' => !$columnSchema->allowNull && ($columnSchema->defaultValue === null), @@ -326,6 +326,13 @@ public static function attributesFromColumnSchemas(array $columnSchemas) 'description' => $columnSchema->comment, ]); + // PgSQL array + if (property_exists($columnSchema, 'dimension') && $columnSchema->dimension !== 0) { + for ($i = 0; $i < $columnSchema->dimension; $i++) { + $attribute->dbType .= '[]'; + } + } + // generate PK using `->primaryKeys()` or similar methods instead of separate SQL statement which sets only PK to a column of table // https://github.com/cebe/yii2-openapi/issues/132 if (in_array($columnSchema->phpType, [ diff --git a/tests/specs/issue_fix/132_create_migration_for_drop_table/132_create_migration_for_drop_table.yaml b/tests/specs/issue_fix/132_create_migration_for_drop_table/132_create_migration_for_drop_table.yaml index 607ec5da..114ea255 100644 --- a/tests/specs/issue_fix/132_create_migration_for_drop_table/132_create_migration_for_drop_table.yaml +++ b/tests/specs/issue_fix/132_create_migration_for_drop_table/132_create_migration_for_drop_table.yaml @@ -4,13 +4,13 @@ info: title: 132_create_migration_for_drop_table \#132 x-deleted-schemas: - - Pristine - - Fruit # Example: table name evaluated to `itt_fruits`. `itt_` is prefix set in DB config - - Mango: the_mango_table_name # custom table name; see `x-table` in README.md - - Animal: the_animal_table_name - - Upk - - Bigpk - - Ubigpk + - Pristine + - Fruit # Example: table name evaluated to `itt_fruits`. `itt_` is prefix set in DB config + - Mango: the_mango_table_name # custom table name; see `x-table` in README.md + - Animal: the_animal_table_name + - Upk + - Bigpk + - Ubigpk paths: /: diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index 87b157e4..aa39d2a8 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -383,6 +383,9 @@ private function createTablesForCreateMigrationForDropTable132ForPgsql() // 'd SMALLINT UNSIGNED ZEROFILL', // 'e' => 'SMALLINT UNSIGNED ZEROFILL', // 'f' => 'decimal(12,4)', + 'g5' => 'text[]', + 'g6' => 'text[][]', + 'g7' => 'numeric(10,4)', ])->execute(); // --- From 990ae26362f576dfadf9697484b619b4666c6d0b Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Wed, 26 Jun 2024 13:32:28 +0530 Subject: [PATCH 039/358] Fix lot of issues and failing test + proper handling of text[] (array), decimal enum and more --- src/lib/AttributeResolver.php | 6 +- src/lib/ColumnToCode.php | 5 +- src/lib/SchemaToDatabase.php | 28 ++- src/lib/items/Attribute.php | 11 + src/lib/migrations/BaseMigrationBuilder.php | 8 +- .../migrations/PostgresMigrationBuilder.php | 4 +- tests/DbTestCase.php | 2 +- tests/unit/AttributeResolverTest.php | 208 +++++++++--------- tests/unit/IssueFixTest.php | 95 +++----- 9 files changed, 181 insertions(+), 186 deletions(-) diff --git a/src/lib/AttributeResolver.php b/src/lib/AttributeResolver.php index 0063d8df..7bb29bfa 100644 --- a/src/lib/AttributeResolver.php +++ b/src/lib/AttributeResolver.php @@ -147,7 +147,8 @@ protected function resolveJunctionTableProperty(PropertySchema $property, bool $ ->asReference($junkAttribute['relatedClassName']) ->setPhpType($junkAttribute['phpType']) ->setDbType($junkAttribute['dbType']) - ->setForeignKeyColumnName($property->fkColName); + ->setForeignKeyColumnName($property->fkColName) + ->setTableName($this->schema->resolveTableName($this->schemaName)); $relation = Yii::createObject(AttributeRelation::class, [ $property->getName(), $junkAttribute['relatedTableName'], @@ -228,7 +229,8 @@ protected function resolveProperty( ->setXDbDefaultExpression($property->getAttr(CustomSpecAttr::DB_DEFAULT_EXPRESSION)) ->setNullable($nullableValue) ->setIsPrimary($property->isPrimaryKey()) - ->setForeignKeyColumnName($property->fkColName); + ->setForeignKeyColumnName($property->fkColName) + ->setTableName($this->schema->resolveTableName($this->schemaName)); if ($property->isReference()) { if ($property->isVirtual()) { throw new InvalidDefinitionException('References not supported for virtual attributes'); diff --git a/src/lib/ColumnToCode.php b/src/lib/ColumnToCode.php index e9a570bc..35432b00 100644 --- a/src/lib/ColumnToCode.php +++ b/src/lib/ColumnToCode.php @@ -398,8 +398,9 @@ private function getIsBuiltinType($type, $dbType) private function resolveEnumType():void { if (ApiGenerator::isPostgres()) { - $rawTableName = $this->dbSchema->getRawTableName($this->tableAlias); - $this->rawParts['type'] = '"enum_'.$rawTableName.'_' . $this->column->name.'"'; + // $rawTableName = $this->dbSchema->getRawTableName($this->tableAlias); + // $this->rawParts['type'] = '"enum_'.$rawTableName.'_' . $this->column->name.'"'; + $this->rawParts['type'] = '"'.$this->column->dbType.'"'; return; } $this->rawParts['type'] = 'enum(' . self::mysqlEnumToString($this->column->enumValues) . ')'; diff --git a/src/lib/SchemaToDatabase.php b/src/lib/SchemaToDatabase.php index 3489e455..52ddfe3a 100644 --- a/src/lib/SchemaToDatabase.php +++ b/src/lib/SchemaToDatabase.php @@ -10,6 +10,7 @@ use cebe\openapi\exceptions\IOException; use cebe\openapi\exceptions\TypeErrorException; use cebe\openapi\exceptions\UnresolvableReferenceException; +use cebe\yii2openapi\generator\ApiGenerator; use cebe\yii2openapi\lib\exceptions\InvalidDefinitionException; use cebe\yii2openapi\lib\items\Attribute; use cebe\yii2openapi\lib\items\DbModel; @@ -278,7 +279,7 @@ public static function f7(array $schemasToDrop): array // TODO rename 'pkName' => $table->primaryKey[0], 'name' => $schemaName, 'tableName' => $tableName, - 'attributes' => static::attributesFromColumnSchemas($table->columns), + 'attributes' => static::attributesFromColumnSchemas(static::enhanceColumnSchemas($table->columns)), 'drop' => true ]); $dbModelsToDrop[$key] = $dbModelHere; @@ -325,14 +326,25 @@ public static function attributesFromColumnSchemas(array $columnSchemas) 'defaultValue' => $columnSchema->defaultValue, 'description' => $columnSchema->comment, ]); + $attributes[] = $attribute; + } + return $attributes; + } + public static function enhanceColumnSchemas(array $columnSchemas) + { + foreach ($columnSchemas as $columnSchema) { // PgSQL array if (property_exists($columnSchema, 'dimension') && $columnSchema->dimension !== 0) { for ($i = 0; $i < $columnSchema->dimension; $i++) { - $attribute->dbType .= '[]'; + $columnSchema->dbType .= '[]'; } } + if (ApiGenerator::isPostgres() && $columnSchema->type === Schema::TYPE_DECIMAL) { + $columnSchema->dbType .= '('.$columnSchema->precision.','.$columnSchema->scale.')'; + } + // generate PK using `->primaryKeys()` or similar methods instead of separate SQL statement which sets only PK to a column of table // https://github.com/cebe/yii2-openapi/issues/132 if (in_array($columnSchema->phpType, [ @@ -344,21 +356,19 @@ public static function attributesFromColumnSchemas(array $columnSchemas) str_ireplace(['BIGINT', 'int8', 'bigserial', 'serial8'], 'nothing', $columnSchema->dbType, $count); # can be refactored if https://github.com/yiisoft/yii2/issues/20209 is fixed if ($count) { if ($columnSchema->unsigned) { - $attribute->dbType = Schema::TYPE_UBIGPK; + $columnSchema->dbType = Schema::TYPE_UBIGPK; } else { - $attribute->dbType = Schema::TYPE_BIGPK; + $columnSchema->dbType = Schema::TYPE_BIGPK; } } else { if ($columnSchema->unsigned) { - $attribute->dbType = Schema::TYPE_UPK; + $columnSchema->dbType = Schema::TYPE_UPK; } else { - $attribute->dbType = Schema::TYPE_PK; + $columnSchema->dbType = Schema::TYPE_PK; } } } - - $attributes[] = $attribute; } - return $attributes; + return $columnSchemas; } } diff --git a/src/lib/items/Attribute.php b/src/lib/items/Attribute.php index f867b3f7..1c28b74c 100644 --- a/src/lib/items/Attribute.php +++ b/src/lib/items/Attribute.php @@ -124,6 +124,8 @@ class Attribute extends BaseObject **/ public $fakerStub; + public $tableName; // required for PgSQL enum + /** * @var bool **/ @@ -148,6 +150,12 @@ public function setDbType(string $dbType):Attribute return $this; } + public function setTableName(string $tableName):Attribute + { + $this->tableName = $tableName; + return $this; + } + public function setXDbType($xDbType):Attribute { $this->xDbType = $xDbType; @@ -326,6 +334,9 @@ public function toColumnSchema():ColumnSchema } if (is_array($this->enumValues)) { $column->enumValues = $this->enumValues; + if (ApiGenerator::isPostgres() && empty($this->xDbType)) { + $column->dbType = 'enum_'.Yii::$app->db->tablePrefix.$this->tableName.'_' . $column->name; + } } $this->handleDecimal($column); diff --git a/src/lib/migrations/BaseMigrationBuilder.php b/src/lib/migrations/BaseMigrationBuilder.php index cc0706fc..d028612c 100644 --- a/src/lib/migrations/BaseMigrationBuilder.php +++ b/src/lib/migrations/BaseMigrationBuilder.php @@ -12,6 +12,7 @@ use cebe\yii2openapi\lib\items\DbModel; use cebe\yii2openapi\lib\items\ManyToManyRelation; use cebe\yii2openapi\lib\items\MigrationModel; +use cebe\yii2openapi\lib\SchemaToDatabase; use Yii; use yii\db\ColumnSchema; use yii\db\Connection; @@ -450,6 +451,9 @@ public function tmpSaveNewCol(string $tableAlias, \cebe\yii2openapi\db\ColumnSch } else { $column = [$columnSchema->name => $this->newColStr($tmpTableName, $columnSchema)]; if (ApiGenerator::isPostgres() && static::isEnum($columnSchema)) { + $clonedSchema = clone $columnSchema; + $clonedSchema->dbType = trim($innerEnumTypeName, '"'); + $column = [$columnSchema->name => $this->newColStr($tmpTableName, $clonedSchema)]; $column[$columnSchema->name] = strtr($column[$columnSchema->name], [$innerEnumTypeName => $tmpEnumName($columnSchema->name)]); } } @@ -600,8 +604,8 @@ public function buildTablesDrop(): void ->addDownCode( $this->recordBuilder->createTable( $this->model->getTableAlias(), - $this->model->attributesToColumnSchema() -// $this->tableSchema->columns +// $this->model->attributesToColumnSchema() + SchemaToDatabase::enhanceColumnSchemas($this->tableSchema->columns) ) ); } diff --git a/src/lib/migrations/PostgresMigrationBuilder.php b/src/lib/migrations/PostgresMigrationBuilder.php index 7e7c2598..51b3734a 100644 --- a/src/lib/migrations/PostgresMigrationBuilder.php +++ b/src/lib/migrations/PostgresMigrationBuilder.php @@ -232,7 +232,7 @@ public function modifyCurrent(ColumnSchema $current): void public function modifyDesired(ColumnSchema $desired): void { - /** @var $desired cebe\yii2openapi\db\ColumnSchema|\yii\db\pgsql\ColumnSchema */ + /** @var $desired \cebe\yii2openapi\db\ColumnSchema|\yii\db\pgsql\ColumnSchema */ if (in_array($desired->phpType, ['int', 'integer']) && $desired->defaultValue !== null) { $desired->defaultValue = (int)$desired->defaultValue; } @@ -245,7 +245,7 @@ public function modifyDesired(ColumnSchema $desired): void public function modifyDesiredInContextOfCurrent(ColumnSchema $current, ColumnSchema $desired): void { /** @var $current \yii\db\pgsql\ColumnSchema */ - /** @var $desired cebe\yii2openapi\db\ColumnSchema|\yii\db\pgsql\ColumnSchema */ + /** @var $desired \cebe\yii2openapi\db\ColumnSchema|\yii\db\pgsql\ColumnSchema */ if ($current->type === $desired->type && !$desired->size && $this->isDbDefaultSize($current)) { $desired->size = $current->size; } diff --git a/tests/DbTestCase.php b/tests/DbTestCase.php index ca7b17ff..f36137e2 100644 --- a/tests/DbTestCase.php +++ b/tests/DbTestCase.php @@ -180,8 +180,8 @@ protected function runDownMigrations(string $db = 'mysql', int $number = 2): voi exec('cd tests; php -dxdebug.mode=develop ./yii migrate-'.$db.'/down --interactive=0 '.$number, $downOutput, $downExitCode); $last = count($downOutput) - 1; $lastThird = count($downOutput) - 3; - $this->assertSame($downExitCode, 0); $this->assertSame($downOutput[$last], 'Migrated down successfully.'); + $this->assertSame($downExitCode, 0); $this->assertSame($downOutput[$lastThird], $number.' '.(($number === 1) ? 'migration was' : 'migrations were').' reverted.'); } } diff --git a/tests/unit/AttributeResolverTest.php b/tests/unit/AttributeResolverTest.php index ae07cdf7..89d9ffc1 100644 --- a/tests/unit/AttributeResolverTest.php +++ b/tests/unit/AttributeResolverTest.php @@ -17,115 +17,115 @@ class AttributeResolverTest extends DbTestCase { - public function testManyToManyResolve() - { - $schemaFile = Yii::getAlias("@specs/many2many.yaml"); - $openApi = Reader::readFromYamlFile($schemaFile, OpenApi::class, false); - $schema = new ComponentSchema($openApi->components->schemas['Post'], 'Post'); - $postModel = (new AttributeResolver('Post', $schema, new JunctionSchemas([])))->resolve(); - self::assertNotEmpty($postModel->many2many); - $relation = $postModel->many2many['tags']; - self::assertInstanceOf(ManyToManyRelation::class, $relation); - self::assertEquals('Tag', $relation->relatedClassName); - self::assertEquals('Post', $relation->className); - self::assertEquals('id', $relation->pkAttribute->propertyName); - self::assertEquals('posts2tags', $relation->getViaTableName()); - self::assertEquals(['id' => 'tag_id'], $relation->getLink()); - self::assertEquals(['post_id' => 'id'], $relation->getViaLink()); + // public function testManyToManyResolve() + // { + // $schemaFile = Yii::getAlias("@specs/many2many.yaml"); + // $openApi = Reader::readFromYamlFile($schemaFile, OpenApi::class, false); + // $schema = new ComponentSchema($openApi->components->schemas['Post'], 'Post'); + // $postModel = (new AttributeResolver('Post', $schema, new JunctionSchemas([])))->resolve(); + // self::assertNotEmpty($postModel->many2many); + // $relation = $postModel->many2many['tags']; + // self::assertInstanceOf(ManyToManyRelation::class, $relation); + // self::assertEquals('Tag', $relation->relatedClassName); + // self::assertEquals('Post', $relation->className); + // self::assertEquals('id', $relation->pkAttribute->propertyName); + // self::assertEquals('posts2tags', $relation->getViaTableName()); + // self::assertEquals(['id' => 'tag_id'], $relation->getLink()); + // self::assertEquals(['post_id' => 'id'], $relation->getViaLink()); - $schema = new ComponentSchema($openApi->components->schemas['Tag'], 'Tag'); - $tagModel = (new AttributeResolver('Tag', $schema, new JunctionSchemas([])))->resolve(); - self::assertNotEmpty($tagModel->many2many); - $relation = $tagModel->many2many['posts']; - self::assertInstanceOf(ManyToManyRelation::class, $relation); - self::assertEquals('Post', $relation->relatedClassName); - self::assertEquals('Tag', $relation->className); - self::assertEquals('id', $relation->pkAttribute->propertyName); - self::assertEquals('posts2tags', $relation->getViaTableName()); - self::assertEquals(['id' => 'post_id'], $relation->getLink()); - self::assertEquals(['tag_id' => 'id'], $relation->getViaLink()); + // $schema = new ComponentSchema($openApi->components->schemas['Tag'], 'Tag'); + // $tagModel = (new AttributeResolver('Tag', $schema, new JunctionSchemas([])))->resolve(); + // self::assertNotEmpty($tagModel->many2many); + // $relation = $tagModel->many2many['posts']; + // self::assertInstanceOf(ManyToManyRelation::class, $relation); + // self::assertEquals('Post', $relation->relatedClassName); + // self::assertEquals('Tag', $relation->className); + // self::assertEquals('id', $relation->pkAttribute->propertyName); + // self::assertEquals('posts2tags', $relation->getViaTableName()); + // self::assertEquals(['id' => 'post_id'], $relation->getLink()); + // self::assertEquals(['tag_id' => 'id'], $relation->getViaLink()); - } + // } - /** - * @dataProvider dataProvider - * @param string $schemaName - * @param \cebe\openapi\spec\Schema $openApiSchema - * @param \cebe\yii2openapi\lib\items\DbModel $expected - */ - public function testResolve(string $schemaName, Schema $openApiSchema, DbModel $expected):void - { - $schema = new ComponentSchema($openApiSchema, $schemaName); - $resolver = new AttributeResolver($schemaName, $schema, new JunctionSchemas([])); - $model = $resolver->resolve(); - //echo $schemaName . PHP_EOL; - self::assertEquals($expected->name, $model->name); - self::assertEquals($expected->tableName, $model->tableName); - self::assertEquals($expected->description, $model->description); - self::assertEquals($expected->tableAlias, $model->tableAlias); - //VarDumper::dump($model->indexes); - self::assertEquals($expected->indexes, $model->indexes); - foreach ($model->relations as $name => $relation) { - self::assertTrue(isset($expected->relations[$name])); - self::assertEquals($expected->relations[$name], $relation); - } - foreach ($model->attributes as $name => $attribute) { - self::assertTrue(isset($expected->attributes[$name])); - self::assertEquals($expected->attributes[$name], $attribute); - } - } + // /** + // * @dataProvider dataProvider + // * @param string $schemaName + // * @param \cebe\openapi\spec\Schema $openApiSchema + // * @param \cebe\yii2openapi\lib\items\DbModel $expected + // */ + // public function testResolve(string $schemaName, Schema $openApiSchema, DbModel $expected):void + // { + // $schema = new ComponentSchema($openApiSchema, $schemaName); + // $resolver = new AttributeResolver($schemaName, $schema, new JunctionSchemas([])); + // $model = $resolver->resolve(); + // //echo $schemaName . PHP_EOL; + // self::assertEquals($expected->name, $model->name); + // self::assertEquals($expected->tableName, $model->tableName); + // self::assertEquals($expected->description, $model->description); + // self::assertEquals($expected->tableAlias, $model->tableAlias); + // //VarDumper::dump($model->indexes); + // self::assertEquals($expected->indexes, $model->indexes); + // foreach ($model->relations as $name => $relation) { + // self::assertTrue(isset($expected->relations[$name])); + // self::assertEquals($expected->relations[$name], $relation); + // } + // foreach ($model->attributes as $name => $attribute) { + // self::assertTrue(isset($expected->attributes[$name])); + // self::assertEquals($expected->attributes[$name], $attribute); + // } + // } - public function dataProvider():array - { - $schemaFile = Yii::getAlias("@specs/blog.yaml"); - $fixture = require Yii::getAlias('@fixtures/blog.php'); - $openApi = Reader::readFromYamlFile($schemaFile, OpenApi::class, false); - return [ - [ - 'User', - $openApi->components->schemas['User'], - $fixture['user'], - ], - [ - 'Category', - $openApi->components->schemas['Category'], - $fixture['category'], - ], - [ - 'Post', - $openApi->components->schemas['Post'], - $fixture['post'], - ], - [ - 'Comment', - $openApi->components->schemas['Comment'], - $fixture['comment'], - ], - ]; - } + // public function dataProvider():array + // { + // $schemaFile = Yii::getAlias("@specs/blog.yaml"); + // $fixture = require Yii::getAlias('@fixtures/blog.php'); + // $openApi = Reader::readFromYamlFile($schemaFile, OpenApi::class, false); + // return [ + // [ + // 'User', + // $openApi->components->schemas['User'], + // $fixture['user'], + // ], + // [ + // 'Category', + // $openApi->components->schemas['Category'], + // $fixture['category'], + // ], + // [ + // 'Post', + // $openApi->components->schemas['Post'], + // $fixture['post'], + // ], + // [ + // 'Comment', + // $openApi->components->schemas['Comment'], + // $fixture['comment'], + // ], + // ]; + // } - public function testResolveRefNoObject() - { - $schemaFile = Yii::getAlias("@specs/ref_noobject.yaml"); - $openApi = Reader::readFromYamlFile($schemaFile, OpenApi::class, false); - $schema = new ComponentSchema($openApi->components->schemas['PersonWatch'], 'PersonWatch'); - $resolver = new AttributeResolver('PersonWatch', $schema, new JunctionSchemas([])); - $model = $resolver->resolve(); - $fixture = require Yii::getAlias('@fixtures/non-db.php'); - $testModel = $fixture['personWatch']; - self::assertEquals($testModel, $model); - } + // public function testResolveRefNoObject() + // { + // $schemaFile = Yii::getAlias("@specs/ref_noobject.yaml"); + // $openApi = Reader::readFromYamlFile($schemaFile, OpenApi::class, false); + // $schema = new ComponentSchema($openApi->components->schemas['PersonWatch'], 'PersonWatch'); + // $resolver = new AttributeResolver('PersonWatch', $schema, new JunctionSchemas([])); + // $model = $resolver->resolve(); + // $fixture = require Yii::getAlias('@fixtures/non-db.php'); + // $testModel = $fixture['personWatch']; + // self::assertEquals($testModel, $model); + // } - public function testResolveNonDbModel() - { - $schemaFile = Yii::getAlias("@specs/petstore_jsonapi.yaml"); - $openApi = Reader::readFromYamlFile($schemaFile, OpenApi::class, false); - $schema = new ComponentSchema($openApi->components->schemas['PetStatistic'], 'PetStatistic'); - $resolver = new AttributeResolver('PetStatistic', $schema, new JunctionSchemas([])); - $model = $resolver->resolve(); - $fixture = require Yii::getAlias('@fixtures/non-db.php'); - $testModel = $fixture['PetStatistic']; - self::assertEquals($testModel, $model); - } + // public function testResolveNonDbModel() + // { + // $schemaFile = Yii::getAlias("@specs/petstore_jsonapi.yaml"); + // $openApi = Reader::readFromYamlFile($schemaFile, OpenApi::class, false); + // $schema = new ComponentSchema($openApi->components->schemas['PetStatistic'], 'PetStatistic'); + // $resolver = new AttributeResolver('PetStatistic', $schema, new JunctionSchemas([])); + // $model = $resolver->resolve(); + // $fixture = require Yii::getAlias('@fixtures/non-db.php'); + // $testModel = $fixture['PetStatistic']; + // self::assertEquals($testModel, $model); + // } } diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index aa39d2a8..448f6d16 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -66,7 +66,6 @@ private function deleteTables() $this->deleteTableForQuoteInAlterColumn(); $this->deleteTableForTimestampIssue143(); $this->deleteTablesForWrongMigrationForPgsqlForStringVarcharDatatype149(); -// $this->deleteTablesForCreateMigrationForDropTable132(); } private function deleteTablesForFloatIssue() @@ -158,41 +157,6 @@ private function createTableForQuoteInAlterColumn() ])->execute(); } - // Stub -> https://github.com/cebe/yii2-openapi/issues/132 - // public function testCreateTableInDownCode() - // { - // $testFile = Yii::getAlias("@specs/issue_fix/create_table_in_down_code/create_table_in_down_code.php"); - // $this->deleteTablesForCreateTableInDownCode(); - // $this->createTableForCreateTableInDownCode(); - // $this->runGenerator($testFile, 'mysql'); - // // $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ - // // 'recursive' => true, - // // ]); - // // $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/create_table_in_down_code/mysql/app"), [ - // // 'recursive' => true, - // // ]); - // // $this->checkFiles($actualFiles, $expectedFiles); - // // $this->runActualMigrations('mysql', 1); - // } - - // private function deleteTablesForCreateTableInDownCode() - // { - // Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%fruits}}')->execute(); - // Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%animals}}')->execute(); - // } - - // private function createTableForCreateTableInDownCode() - // { - // Yii::$app->db->createCommand()->createTable('{{%fruits}}', [ - // 'id' => 'pk', - // 'colourName' => 'varchar(255)', - // ])->execute(); - // Yii::$app->db->createCommand()->createTable('{{%animals}}', [ - // 'id' => 'pk', - // 'colourName' => 'varchar(255)', - // ])->execute(); - // } - // fix https://github.com/cebe/yii2-openapi/issues/143 // timestamp_143 public function testTimestampIssue143() @@ -277,17 +241,15 @@ public function testNullableFalseInRequired() // Create migration for drop table if a entire schema is deleted from OpenAPI spec #132 // https://github.com/cebe/yii2-openapi/issues/132 - public function testCreateMigrationForDropTable132() - { - $testFile = Yii::getAlias("@specs/issue_fix/132_create_migration_for_drop_table/132_create_migration_for_drop_table.php"); - // $this->deleteTablesForCreateMigrationForDropTable132(); - $this->createTablesForCreateMigrationForDropTable132(); - $this->runGenerator($testFile); - $this->runActualMigrations('mysql', 8); - // ... TODO compare files - $this->deleteTablesForCreateMigrationForDropTable132(); - $this->deleteTables(); - } + public function testCreateMigrationForDropTable132() + { + $testFile = Yii::getAlias("@specs/issue_fix/132_create_migration_for_drop_table/132_create_migration_for_drop_table.php"); + $this->createTablesForCreateMigrationForDropTable132(); + $this->runGenerator($testFile); + $this->runActualMigrations('mysql', 8); + // ... TODO compare files + $this->deleteTablesForCreateMigrationForDropTable132(); + } private function createTablesForCreateMigrationForDropTable132() { @@ -304,8 +266,10 @@ private function createTablesForCreateMigrationForDropTable132() 'name' => 'string(150)', 'size' => "ENUM('x-small', 'small', 'medium', 'large', 'x-large') NOT NULL DEFAULT 'x-small'", 'd SMALLINT UNSIGNED ZEROFILL', - 'e' => 'SMALLINT UNSIGNED ZEROFILL', + 'e' => 'MEDIUMINT UNSIGNED ZEROFILL', 'f' => 'decimal(12,4)', + 'dp' => 'double precision', + 'dp2' => 'double precision(10, 4)' ])->execute(); // --- @@ -354,23 +318,27 @@ private function deleteTablesForCreateMigrationForDropTable132() // Create migration for drop table if a entire schema is deleted from OpenAPI spec #132 // https://github.com/cebe/yii2-openapi/issues/132 // For PgSQL - public function testCreateMigrationForDropTable132ForPgsql() - { - $this->changeDbToPgsql(); - $testFile = Yii::getAlias("@specs/issue_fix/132_create_migration_for_drop_table/132_create_migration_for_drop_table.php"); - $this->createTablesForCreateMigrationForDropTable132ForPgsql(); - $this->runGenerator($testFile, 'pgsql'); - $this->runActualMigrations('pgsql', 8); - // ... TODO compare files - $this->deleteTablesForCreateMigrationForDropTable132ForPgsql(); - $this->deleteTables(); - } + public function testCreateMigrationForDropTable132ForPgsql() + { + $this->changeDbToPgsql(); + $testFile = Yii::getAlias("@specs/issue_fix/132_create_migration_for_drop_table/132_create_migration_for_drop_table.php"); + $this->createTablesForCreateMigrationForDropTable132ForPgsql(); + $this->runGenerator($testFile, 'pgsql'); + $this->runActualMigrations('pgsql', 8); + // ... TODO compare files + $this->deleteTablesForCreateMigrationForDropTable132ForPgsql(); + } private function createTablesForCreateMigrationForDropTable132ForPgsql() { + Yii::$app->db->createCommand('CREATE TYPE mood AS ENUM (\'sad\', \'ok\', \'happy\')')->execute(); + Yii::$app->db->createCommand('CREATE TYPE enum_itt_upks_e2 AS ENUM (\'sad2\', \'ok2\', \'happy2\')')->execute(); + Yii::$app->db->createCommand()->createTable('{{%upks}}', [ 'id' => 'upk', 'name' => 'string(150)', + 'current_mood' => 'mood', + 'e2' => 'enum_itt_upks_e2', ])->execute(); Yii::$app->db->createCommand()->createTable('{{%bigpks}}', [ 'id' => 'bigpk', @@ -379,13 +347,11 @@ private function createTablesForCreateMigrationForDropTable132ForPgsql() Yii::$app->db->createCommand()->createTable('{{%ubigpks}}', [ 'id' => 'ubigpk', 'name' => 'string(150)', -// 'size' => "ENUM('x-small', 'small', 'medium', 'large', 'x-large') NOT NULL DEFAULT 'x-small'", -// 'd SMALLINT UNSIGNED ZEROFILL', -// 'e' => 'SMALLINT UNSIGNED ZEROFILL', -// 'f' => 'decimal(12,4)', + 'f' => 'decimal(12,4)', 'g5' => 'text[]', 'g6' => 'text[][]', - 'g7' => 'numeric(10,4)', + 'g7' => 'numeric(10,7)', + 'dp double precision', ])->execute(); // --- @@ -423,6 +389,7 @@ private function deleteTablesForCreateMigrationForDropTable132ForPgsql() Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%fruits}}')->execute(); Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%upks}}')->execute(); + Yii::$app->db->createCommand('DROP TYPE mood')->execute(); Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%bigpks}}')->execute(); Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%ubigpks}}')->execute(); From ea8f499a8be9b05464d5e2afd5e615bc7d2a68aa Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Wed, 26 Jun 2024 13:34:42 +0530 Subject: [PATCH 040/358] Fix drop migration --- tests/unit/IssueFixTest.php | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index 448f6d16..d81a1815 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -390,6 +390,7 @@ private function deleteTablesForCreateMigrationForDropTable132ForPgsql() Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%upks}}')->execute(); Yii::$app->db->createCommand('DROP TYPE mood')->execute(); + Yii::$app->db->createCommand('DROP TYPE enum_itt_upks_e2')->execute(); Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%bigpks}}')->execute(); Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%ubigpks}}')->execute(); From 193b66da55fb0be852e5cf2785118284585c638a Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Wed, 26 Jun 2024 13:46:19 +0530 Subject: [PATCH 041/358] Fix style --- src/lib/items/Attribute.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/lib/items/Attribute.php b/src/lib/items/Attribute.php index 1c28b74c..d697e78f 100644 --- a/src/lib/items/Attribute.php +++ b/src/lib/items/Attribute.php @@ -334,9 +334,9 @@ public function toColumnSchema():ColumnSchema } if (is_array($this->enumValues)) { $column->enumValues = $this->enumValues; - if (ApiGenerator::isPostgres() && empty($this->xDbType)) { + if (ApiGenerator::isPostgres() && empty($this->xDbType)) { $column->dbType = 'enum_'.Yii::$app->db->tablePrefix.$this->tableName.'_' . $column->name; - } + } } $this->handleDecimal($column); From 83e2ef8f404ee4178b006e4ee7346fcba6e096e2 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Wed, 26 Jun 2024 16:59:55 +0530 Subject: [PATCH 042/358] Fix failing AttributeResolverTest --- tests/unit/AttributeResolverTest.php | 210 ++++++++++++++------------- 1 file changed, 106 insertions(+), 104 deletions(-) diff --git a/tests/unit/AttributeResolverTest.php b/tests/unit/AttributeResolverTest.php index 89d9ffc1..2a974d96 100644 --- a/tests/unit/AttributeResolverTest.php +++ b/tests/unit/AttributeResolverTest.php @@ -17,115 +17,117 @@ class AttributeResolverTest extends DbTestCase { - // public function testManyToManyResolve() - // { - // $schemaFile = Yii::getAlias("@specs/many2many.yaml"); - // $openApi = Reader::readFromYamlFile($schemaFile, OpenApi::class, false); - // $schema = new ComponentSchema($openApi->components->schemas['Post'], 'Post'); - // $postModel = (new AttributeResolver('Post', $schema, new JunctionSchemas([])))->resolve(); - // self::assertNotEmpty($postModel->many2many); - // $relation = $postModel->many2many['tags']; - // self::assertInstanceOf(ManyToManyRelation::class, $relation); - // self::assertEquals('Tag', $relation->relatedClassName); - // self::assertEquals('Post', $relation->className); - // self::assertEquals('id', $relation->pkAttribute->propertyName); - // self::assertEquals('posts2tags', $relation->getViaTableName()); - // self::assertEquals(['id' => 'tag_id'], $relation->getLink()); - // self::assertEquals(['post_id' => 'id'], $relation->getViaLink()); + public function testManyToManyResolve() + { + $schemaFile = Yii::getAlias("@specs/many2many.yaml"); + $openApi = Reader::readFromYamlFile($schemaFile, OpenApi::class, false); + $schema = new ComponentSchema($openApi->components->schemas['Post'], 'Post'); + $postModel = (new AttributeResolver('Post', $schema, new JunctionSchemas([])))->resolve(); + self::assertNotEmpty($postModel->many2many); + $relation = $postModel->many2many['tags']; + self::assertInstanceOf(ManyToManyRelation::class, $relation); + self::assertEquals('Tag', $relation->relatedClassName); + self::assertEquals('Post', $relation->className); + self::assertEquals('id', $relation->pkAttribute->propertyName); + self::assertEquals('posts2tags', $relation->getViaTableName()); + self::assertEquals(['id' => 'tag_id'], $relation->getLink()); + self::assertEquals(['post_id' => 'id'], $relation->getViaLink()); - // $schema = new ComponentSchema($openApi->components->schemas['Tag'], 'Tag'); - // $tagModel = (new AttributeResolver('Tag', $schema, new JunctionSchemas([])))->resolve(); - // self::assertNotEmpty($tagModel->many2many); - // $relation = $tagModel->many2many['posts']; - // self::assertInstanceOf(ManyToManyRelation::class, $relation); - // self::assertEquals('Post', $relation->relatedClassName); - // self::assertEquals('Tag', $relation->className); - // self::assertEquals('id', $relation->pkAttribute->propertyName); - // self::assertEquals('posts2tags', $relation->getViaTableName()); - // self::assertEquals(['id' => 'post_id'], $relation->getLink()); - // self::assertEquals(['tag_id' => 'id'], $relation->getViaLink()); + $schema = new ComponentSchema($openApi->components->schemas['Tag'], 'Tag'); + $tagModel = (new AttributeResolver('Tag', $schema, new JunctionSchemas([])))->resolve(); + self::assertNotEmpty($tagModel->many2many); + $relation = $tagModel->many2many['posts']; + self::assertInstanceOf(ManyToManyRelation::class, $relation); + self::assertEquals('Post', $relation->relatedClassName); + self::assertEquals('Tag', $relation->className); + self::assertEquals('id', $relation->pkAttribute->propertyName); + self::assertEquals('posts2tags', $relation->getViaTableName()); + self::assertEquals(['id' => 'post_id'], $relation->getLink()); + self::assertEquals(['tag_id' => 'id'], $relation->getViaLink()); - // } + } - // /** - // * @dataProvider dataProvider - // * @param string $schemaName - // * @param \cebe\openapi\spec\Schema $openApiSchema - // * @param \cebe\yii2openapi\lib\items\DbModel $expected - // */ - // public function testResolve(string $schemaName, Schema $openApiSchema, DbModel $expected):void - // { - // $schema = new ComponentSchema($openApiSchema, $schemaName); - // $resolver = new AttributeResolver($schemaName, $schema, new JunctionSchemas([])); - // $model = $resolver->resolve(); - // //echo $schemaName . PHP_EOL; - // self::assertEquals($expected->name, $model->name); - // self::assertEquals($expected->tableName, $model->tableName); - // self::assertEquals($expected->description, $model->description); - // self::assertEquals($expected->tableAlias, $model->tableAlias); - // //VarDumper::dump($model->indexes); - // self::assertEquals($expected->indexes, $model->indexes); - // foreach ($model->relations as $name => $relation) { - // self::assertTrue(isset($expected->relations[$name])); - // self::assertEquals($expected->relations[$name], $relation); - // } - // foreach ($model->attributes as $name => $attribute) { - // self::assertTrue(isset($expected->attributes[$name])); - // self::assertEquals($expected->attributes[$name], $attribute); - // } - // } + /** + * @dataProvider dataProvider + * @param string $schemaName + * @param \cebe\openapi\spec\Schema $openApiSchema + * @param \cebe\yii2openapi\lib\items\DbModel $expected + */ + public function testResolve(string $schemaName, Schema $openApiSchema, DbModel $expected):void + { + $schema = new ComponentSchema($openApiSchema, $schemaName); + $resolver = new AttributeResolver($schemaName, $schema, new JunctionSchemas([])); + $model = $resolver->resolve(); + //echo $schemaName . PHP_EOL; + self::assertEquals($expected->name, $model->name); + self::assertEquals($expected->tableName, $model->tableName); + self::assertEquals($expected->description, $model->description); + self::assertEquals($expected->tableAlias, $model->tableAlias); + //VarDumper::dump($model->indexes); + self::assertEquals($expected->indexes, $model->indexes); + foreach ($model->relations as $name => $relation) { + self::assertTrue(isset($expected->relations[$name])); + self::assertEquals($expected->relations[$name], $relation); + } - // public function dataProvider():array - // { - // $schemaFile = Yii::getAlias("@specs/blog.yaml"); - // $fixture = require Yii::getAlias('@fixtures/blog.php'); - // $openApi = Reader::readFromYamlFile($schemaFile, OpenApi::class, false); - // return [ - // [ - // 'User', - // $openApi->components->schemas['User'], - // $fixture['user'], - // ], - // [ - // 'Category', - // $openApi->components->schemas['Category'], - // $fixture['category'], - // ], - // [ - // 'Post', - // $openApi->components->schemas['Post'], - // $fixture['post'], - // ], - // [ - // 'Comment', - // $openApi->components->schemas['Comment'], - // $fixture['comment'], - // ], - // ]; - // } + foreach ($model->attributes as $name => $attribute) { + $attribute->tableName = null; # just skip `tableName` from testing as of now + self::assertTrue(isset($expected->attributes[$name])); + self::assertEquals($expected->attributes[$name], $attribute); + } + } - // public function testResolveRefNoObject() - // { - // $schemaFile = Yii::getAlias("@specs/ref_noobject.yaml"); - // $openApi = Reader::readFromYamlFile($schemaFile, OpenApi::class, false); - // $schema = new ComponentSchema($openApi->components->schemas['PersonWatch'], 'PersonWatch'); - // $resolver = new AttributeResolver('PersonWatch', $schema, new JunctionSchemas([])); - // $model = $resolver->resolve(); - // $fixture = require Yii::getAlias('@fixtures/non-db.php'); - // $testModel = $fixture['personWatch']; - // self::assertEquals($testModel, $model); - // } + public function dataProvider():array + { + $schemaFile = Yii::getAlias("@specs/blog.yaml"); + $fixture = require Yii::getAlias('@fixtures/blog.php'); + $openApi = Reader::readFromYamlFile($schemaFile, OpenApi::class, false); + return [ + [ + 'User', + $openApi->components->schemas['User'], + $fixture['user'], + ], + [ + 'Category', + $openApi->components->schemas['Category'], + $fixture['category'], + ], + [ + 'Post', + $openApi->components->schemas['Post'], + $fixture['post'], + ], + [ + 'Comment', + $openApi->components->schemas['Comment'], + $fixture['comment'], + ], + ]; + } - // public function testResolveNonDbModel() - // { - // $schemaFile = Yii::getAlias("@specs/petstore_jsonapi.yaml"); - // $openApi = Reader::readFromYamlFile($schemaFile, OpenApi::class, false); - // $schema = new ComponentSchema($openApi->components->schemas['PetStatistic'], 'PetStatistic'); - // $resolver = new AttributeResolver('PetStatistic', $schema, new JunctionSchemas([])); - // $model = $resolver->resolve(); - // $fixture = require Yii::getAlias('@fixtures/non-db.php'); - // $testModel = $fixture['PetStatistic']; - // self::assertEquals($testModel, $model); - // } + public function testResolveRefNoObject() + { + $schemaFile = Yii::getAlias("@specs/ref_noobject.yaml"); + $openApi = Reader::readFromYamlFile($schemaFile, OpenApi::class, false); + $schema = new ComponentSchema($openApi->components->schemas['PersonWatch'], 'PersonWatch'); + $resolver = new AttributeResolver('PersonWatch', $schema, new JunctionSchemas([])); + $model = $resolver->resolve(); + $fixture = require Yii::getAlias('@fixtures/non-db.php'); + $testModel = $fixture['personWatch']; + self::assertEquals($testModel, $model); + } + + public function testResolveNonDbModel() + { + $schemaFile = Yii::getAlias("@specs/petstore_jsonapi.yaml"); + $openApi = Reader::readFromYamlFile($schemaFile, OpenApi::class, false); + $schema = new ComponentSchema($openApi->components->schemas['PetStatistic'], 'PetStatistic'); + $resolver = new AttributeResolver('PetStatistic', $schema, new JunctionSchemas([])); + $model = $resolver->resolve(); + $fixture = require Yii::getAlias('@fixtures/non-db.php'); + $testModel = $fixture['PetStatistic']; + self::assertEquals($testModel, $model); + } } From e5737fcf253355547daa29cfab4ff1b797cffa23 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Wed, 26 Jun 2024 17:12:35 +0530 Subject: [PATCH 043/358] Compare files in test --- .../m200000_000000_create_table_foos.php | 20 ++++++++ .../m200000_000001_delete_table_pristines.php | 23 ++++++++++ .../m200000_000002_delete_table_fruits.php | 23 ++++++++++ ...0003_delete_table_the_mango_table_name.php | 23 ++++++++++ ...004_delete_table_the_animal_table_name.php | 20 ++++++++ .../m200000_000005_delete_table_upks.php | 20 ++++++++ .../m200000_000006_delete_table_bigpks.php | 20 ++++++++ .../m200000_000007_delete_table_ubigpks.php | 26 +++++++++++ .../mysql/models/Animal.php | 10 ++++ .../mysql/models/Bigpk.php | 10 ++++ .../mysql/models/Foo.php | 10 ++++ .../mysql/models/Fruit.php | 10 ++++ .../mysql/models/Mango.php | 10 ++++ .../mysql/models/Pristine.php | 10 ++++ .../mysql/models/Ubigpk.php | 10 ++++ .../mysql/models/Upk.php | 10 ++++ .../mysql/models/base/Animal.php | 26 +++++++++++ .../mysql/models/base/Bigpk.php | 26 +++++++++++ .../mysql/models/base/Foo.php | 25 ++++++++++ .../mysql/models/base/Fruit.php | 28 +++++++++++ .../mysql/models/base/Mango.php | 28 +++++++++++ .../mysql/models/base/Pristine.php | 28 +++++++++++ .../mysql/models/base/Ubigpk.php | 46 +++++++++++++++++++ .../mysql/models/base/Upk.php | 26 +++++++++++ .../m200000_000000_create_table_foos.php | 20 ++++++++ .../m200000_000001_delete_table_pristines.php | 23 ++++++++++ .../m200000_000002_delete_table_fruits.php | 23 ++++++++++ ...0003_delete_table_the_mango_table_name.php | 23 ++++++++++ ...004_delete_table_the_animal_table_name.php | 20 ++++++++ .../m200000_000005_delete_table_upks.php | 22 +++++++++ .../m200000_000006_delete_table_bigpks.php | 20 ++++++++ .../m200000_000007_delete_table_ubigpks.php | 25 ++++++++++ .../pgsql/models/Animal.php | 10 ++++ .../pgsql/models/Bigpk.php | 10 ++++ .../pgsql/models/Foo.php | 10 ++++ .../pgsql/models/Fruit.php | 10 ++++ .../pgsql/models/Mango.php | 10 ++++ .../pgsql/models/Pristine.php | 10 ++++ .../pgsql/models/Ubigpk.php | 10 ++++ .../pgsql/models/Upk.php | 10 ++++ .../pgsql/models/base/Animal.php | 26 +++++++++++ .../pgsql/models/base/Bigpk.php | 26 +++++++++++ .../pgsql/models/base/Foo.php | 25 ++++++++++ .../pgsql/models/base/Fruit.php | 28 +++++++++++ .../pgsql/models/base/Mango.php | 28 +++++++++++ .../pgsql/models/base/Pristine.php | 28 +++++++++++ .../pgsql/models/base/Ubigpk.php | 36 +++++++++++++++ .../pgsql/models/base/Upk.php | 40 ++++++++++++++++ tests/unit/IssueFixTest.php | 20 +++++++- 49 files changed, 999 insertions(+), 2 deletions(-) create mode 100644 tests/specs/issue_fix/132_create_migration_for_drop_table/mysql/migrations_mysql_db/m200000_000000_create_table_foos.php create mode 100644 tests/specs/issue_fix/132_create_migration_for_drop_table/mysql/migrations_mysql_db/m200000_000001_delete_table_pristines.php create mode 100644 tests/specs/issue_fix/132_create_migration_for_drop_table/mysql/migrations_mysql_db/m200000_000002_delete_table_fruits.php create mode 100644 tests/specs/issue_fix/132_create_migration_for_drop_table/mysql/migrations_mysql_db/m200000_000003_delete_table_the_mango_table_name.php create mode 100644 tests/specs/issue_fix/132_create_migration_for_drop_table/mysql/migrations_mysql_db/m200000_000004_delete_table_the_animal_table_name.php create mode 100644 tests/specs/issue_fix/132_create_migration_for_drop_table/mysql/migrations_mysql_db/m200000_000005_delete_table_upks.php create mode 100644 tests/specs/issue_fix/132_create_migration_for_drop_table/mysql/migrations_mysql_db/m200000_000006_delete_table_bigpks.php create mode 100644 tests/specs/issue_fix/132_create_migration_for_drop_table/mysql/migrations_mysql_db/m200000_000007_delete_table_ubigpks.php create mode 100644 tests/specs/issue_fix/132_create_migration_for_drop_table/mysql/models/Animal.php create mode 100644 tests/specs/issue_fix/132_create_migration_for_drop_table/mysql/models/Bigpk.php create mode 100644 tests/specs/issue_fix/132_create_migration_for_drop_table/mysql/models/Foo.php create mode 100644 tests/specs/issue_fix/132_create_migration_for_drop_table/mysql/models/Fruit.php create mode 100644 tests/specs/issue_fix/132_create_migration_for_drop_table/mysql/models/Mango.php create mode 100644 tests/specs/issue_fix/132_create_migration_for_drop_table/mysql/models/Pristine.php create mode 100644 tests/specs/issue_fix/132_create_migration_for_drop_table/mysql/models/Ubigpk.php create mode 100644 tests/specs/issue_fix/132_create_migration_for_drop_table/mysql/models/Upk.php create mode 100644 tests/specs/issue_fix/132_create_migration_for_drop_table/mysql/models/base/Animal.php create mode 100644 tests/specs/issue_fix/132_create_migration_for_drop_table/mysql/models/base/Bigpk.php create mode 100644 tests/specs/issue_fix/132_create_migration_for_drop_table/mysql/models/base/Foo.php create mode 100644 tests/specs/issue_fix/132_create_migration_for_drop_table/mysql/models/base/Fruit.php create mode 100644 tests/specs/issue_fix/132_create_migration_for_drop_table/mysql/models/base/Mango.php create mode 100644 tests/specs/issue_fix/132_create_migration_for_drop_table/mysql/models/base/Pristine.php create mode 100644 tests/specs/issue_fix/132_create_migration_for_drop_table/mysql/models/base/Ubigpk.php create mode 100644 tests/specs/issue_fix/132_create_migration_for_drop_table/mysql/models/base/Upk.php create mode 100644 tests/specs/issue_fix/132_create_migration_for_drop_table/pgsql/migrations_pgsql_db/m200000_000000_create_table_foos.php create mode 100644 tests/specs/issue_fix/132_create_migration_for_drop_table/pgsql/migrations_pgsql_db/m200000_000001_delete_table_pristines.php create mode 100644 tests/specs/issue_fix/132_create_migration_for_drop_table/pgsql/migrations_pgsql_db/m200000_000002_delete_table_fruits.php create mode 100644 tests/specs/issue_fix/132_create_migration_for_drop_table/pgsql/migrations_pgsql_db/m200000_000003_delete_table_the_mango_table_name.php create mode 100644 tests/specs/issue_fix/132_create_migration_for_drop_table/pgsql/migrations_pgsql_db/m200000_000004_delete_table_the_animal_table_name.php create mode 100644 tests/specs/issue_fix/132_create_migration_for_drop_table/pgsql/migrations_pgsql_db/m200000_000005_delete_table_upks.php create mode 100644 tests/specs/issue_fix/132_create_migration_for_drop_table/pgsql/migrations_pgsql_db/m200000_000006_delete_table_bigpks.php create mode 100644 tests/specs/issue_fix/132_create_migration_for_drop_table/pgsql/migrations_pgsql_db/m200000_000007_delete_table_ubigpks.php create mode 100644 tests/specs/issue_fix/132_create_migration_for_drop_table/pgsql/models/Animal.php create mode 100644 tests/specs/issue_fix/132_create_migration_for_drop_table/pgsql/models/Bigpk.php create mode 100644 tests/specs/issue_fix/132_create_migration_for_drop_table/pgsql/models/Foo.php create mode 100644 tests/specs/issue_fix/132_create_migration_for_drop_table/pgsql/models/Fruit.php create mode 100644 tests/specs/issue_fix/132_create_migration_for_drop_table/pgsql/models/Mango.php create mode 100644 tests/specs/issue_fix/132_create_migration_for_drop_table/pgsql/models/Pristine.php create mode 100644 tests/specs/issue_fix/132_create_migration_for_drop_table/pgsql/models/Ubigpk.php create mode 100644 tests/specs/issue_fix/132_create_migration_for_drop_table/pgsql/models/Upk.php create mode 100644 tests/specs/issue_fix/132_create_migration_for_drop_table/pgsql/models/base/Animal.php create mode 100644 tests/specs/issue_fix/132_create_migration_for_drop_table/pgsql/models/base/Bigpk.php create mode 100644 tests/specs/issue_fix/132_create_migration_for_drop_table/pgsql/models/base/Foo.php create mode 100644 tests/specs/issue_fix/132_create_migration_for_drop_table/pgsql/models/base/Fruit.php create mode 100644 tests/specs/issue_fix/132_create_migration_for_drop_table/pgsql/models/base/Mango.php create mode 100644 tests/specs/issue_fix/132_create_migration_for_drop_table/pgsql/models/base/Pristine.php create mode 100644 tests/specs/issue_fix/132_create_migration_for_drop_table/pgsql/models/base/Ubigpk.php create mode 100644 tests/specs/issue_fix/132_create_migration_for_drop_table/pgsql/models/base/Upk.php diff --git a/tests/specs/issue_fix/132_create_migration_for_drop_table/mysql/migrations_mysql_db/m200000_000000_create_table_foos.php b/tests/specs/issue_fix/132_create_migration_for_drop_table/mysql/migrations_mysql_db/m200000_000000_create_table_foos.php new file mode 100644 index 00000000..1e71fcd5 --- /dev/null +++ b/tests/specs/issue_fix/132_create_migration_for_drop_table/mysql/migrations_mysql_db/m200000_000000_create_table_foos.php @@ -0,0 +1,20 @@ +createTable('{{%foos}}', [ + 'id' => $this->primaryKey(), + 'factor' => $this->integer()->null()->defaultValue(null), + ]); + } + + public function down() + { + $this->dropTable('{{%foos}}'); + } +} diff --git a/tests/specs/issue_fix/132_create_migration_for_drop_table/mysql/migrations_mysql_db/m200000_000001_delete_table_pristines.php b/tests/specs/issue_fix/132_create_migration_for_drop_table/mysql/migrations_mysql_db/m200000_000001_delete_table_pristines.php new file mode 100644 index 00000000..efc571a5 --- /dev/null +++ b/tests/specs/issue_fix/132_create_migration_for_drop_table/mysql/migrations_mysql_db/m200000_000001_delete_table_pristines.php @@ -0,0 +1,23 @@ +dropForeignKey('name', '{{%pristines}}'); + $this->dropTable('{{%pristines}}'); + } + + public function down() + { + $this->createTable('{{%pristines}}', [ + 'id' => $this->primaryKey(), + 'name' => $this->string(151)->null()->defaultValue(null), + 'fruit_id' => 'int NULL DEFAULT NULL', + ]); + $this->addForeignKey('name', '{{%pristines}}', 'fruit_id', 'itt_fruits', 'id'); + } +} diff --git a/tests/specs/issue_fix/132_create_migration_for_drop_table/mysql/migrations_mysql_db/m200000_000002_delete_table_fruits.php b/tests/specs/issue_fix/132_create_migration_for_drop_table/mysql/migrations_mysql_db/m200000_000002_delete_table_fruits.php new file mode 100644 index 00000000..4a7936ab --- /dev/null +++ b/tests/specs/issue_fix/132_create_migration_for_drop_table/mysql/migrations_mysql_db/m200000_000002_delete_table_fruits.php @@ -0,0 +1,23 @@ +dropForeignKey('name2', '{{%fruits}}'); + $this->dropTable('{{%fruits}}'); + } + + public function down() + { + $this->createTable('{{%fruits}}', [ + 'id' => $this->primaryKey(), + 'name' => $this->string(150)->null()->defaultValue(null), + 'food_of' => 'int NULL DEFAULT NULL', + ]); + $this->addForeignKey('name2', '{{%fruits}}', 'food_of', 'itt_the_animal_table_name', 'id'); + } +} diff --git a/tests/specs/issue_fix/132_create_migration_for_drop_table/mysql/migrations_mysql_db/m200000_000003_delete_table_the_mango_table_name.php b/tests/specs/issue_fix/132_create_migration_for_drop_table/mysql/migrations_mysql_db/m200000_000003_delete_table_the_mango_table_name.php new file mode 100644 index 00000000..033c95ed --- /dev/null +++ b/tests/specs/issue_fix/132_create_migration_for_drop_table/mysql/migrations_mysql_db/m200000_000003_delete_table_the_mango_table_name.php @@ -0,0 +1,23 @@ +dropForeignKey('animal_fruit_fk', '{{%the_mango_table_name}}'); + $this->dropTable('{{%the_mango_table_name}}'); + } + + public function down() + { + $this->createTable('{{%the_mango_table_name}}', [ + 'id' => $this->primaryKey(), + 'name' => $this->string(150)->null()->defaultValue(null), + 'food_of' => 'int NULL DEFAULT NULL', + ]); + $this->addForeignKey('animal_fruit_fk', '{{%the_mango_table_name}}', 'food_of', 'itt_the_animal_table_name', 'id'); + } +} diff --git a/tests/specs/issue_fix/132_create_migration_for_drop_table/mysql/migrations_mysql_db/m200000_000004_delete_table_the_animal_table_name.php b/tests/specs/issue_fix/132_create_migration_for_drop_table/mysql/migrations_mysql_db/m200000_000004_delete_table_the_animal_table_name.php new file mode 100644 index 00000000..c5d36223 --- /dev/null +++ b/tests/specs/issue_fix/132_create_migration_for_drop_table/mysql/migrations_mysql_db/m200000_000004_delete_table_the_animal_table_name.php @@ -0,0 +1,20 @@ +dropTable('{{%the_animal_table_name}}'); + } + + public function down() + { + $this->createTable('{{%the_animal_table_name}}', [ + 'id' => $this->primaryKey(), + 'name' => $this->string(150)->null()->defaultValue(null), + ]); + } +} diff --git a/tests/specs/issue_fix/132_create_migration_for_drop_table/mysql/migrations_mysql_db/m200000_000005_delete_table_upks.php b/tests/specs/issue_fix/132_create_migration_for_drop_table/mysql/migrations_mysql_db/m200000_000005_delete_table_upks.php new file mode 100644 index 00000000..c68dd4d8 --- /dev/null +++ b/tests/specs/issue_fix/132_create_migration_for_drop_table/mysql/migrations_mysql_db/m200000_000005_delete_table_upks.php @@ -0,0 +1,20 @@ +dropTable('{{%upks}}'); + } + + public function down() + { + $this->createTable('{{%upks}}', [ + 'id' => $this->primaryKey()->unsigned(), + 'name' => $this->string(150)->null()->defaultValue(null), + ]); + } +} diff --git a/tests/specs/issue_fix/132_create_migration_for_drop_table/mysql/migrations_mysql_db/m200000_000006_delete_table_bigpks.php b/tests/specs/issue_fix/132_create_migration_for_drop_table/mysql/migrations_mysql_db/m200000_000006_delete_table_bigpks.php new file mode 100644 index 00000000..6f0e76c2 --- /dev/null +++ b/tests/specs/issue_fix/132_create_migration_for_drop_table/mysql/migrations_mysql_db/m200000_000006_delete_table_bigpks.php @@ -0,0 +1,20 @@ +dropTable('{{%bigpks}}'); + } + + public function down() + { + $this->createTable('{{%bigpks}}', [ + 'id' => $this->bigPrimaryKey(), + 'name' => $this->string(150)->null()->defaultValue(null), + ]); + } +} diff --git a/tests/specs/issue_fix/132_create_migration_for_drop_table/mysql/migrations_mysql_db/m200000_000007_delete_table_ubigpks.php b/tests/specs/issue_fix/132_create_migration_for_drop_table/mysql/migrations_mysql_db/m200000_000007_delete_table_ubigpks.php new file mode 100644 index 00000000..57687175 --- /dev/null +++ b/tests/specs/issue_fix/132_create_migration_for_drop_table/mysql/migrations_mysql_db/m200000_000007_delete_table_ubigpks.php @@ -0,0 +1,26 @@ +dropTable('{{%ubigpks}}'); + } + + public function down() + { + $this->createTable('{{%ubigpks}}', [ + 'id' => $this->bigPrimaryKey()->unsigned(), + 'name' => $this->string(150)->null()->defaultValue(null), + 'size' => 'enum("x-small", "small", "medium", "large", "x-large") NOT NULL DEFAULT \'x-small\'', + 'd' => 'smallint(5) unsigned zerofill NULL DEFAULT NULL', + 'e' => 'mediumint(8) unsigned zerofill NULL DEFAULT NULL', + 'f' => 'decimal(12,4) NULL DEFAULT NULL', + 'dp' => $this->double()->null()->defaultValue(null), + 'dp2' => 'double(10,4) NULL DEFAULT NULL', + ]); + } +} diff --git a/tests/specs/issue_fix/132_create_migration_for_drop_table/mysql/models/Animal.php b/tests/specs/issue_fix/132_create_migration_for_drop_table/mysql/models/Animal.php new file mode 100644 index 00000000..92caf2f3 --- /dev/null +++ b/tests/specs/issue_fix/132_create_migration_for_drop_table/mysql/models/Animal.php @@ -0,0 +1,10 @@ + [['name'], 'trim'], + 'name_string' => [['name'], 'string', 'max' => 150], + ]; + } +} diff --git a/tests/specs/issue_fix/132_create_migration_for_drop_table/mysql/models/base/Bigpk.php b/tests/specs/issue_fix/132_create_migration_for_drop_table/mysql/models/base/Bigpk.php new file mode 100644 index 00000000..2bf05933 --- /dev/null +++ b/tests/specs/issue_fix/132_create_migration_for_drop_table/mysql/models/base/Bigpk.php @@ -0,0 +1,26 @@ + [['name'], 'trim'], + 'name_string' => [['name'], 'string', 'max' => 150], + ]; + } +} diff --git a/tests/specs/issue_fix/132_create_migration_for_drop_table/mysql/models/base/Foo.php b/tests/specs/issue_fix/132_create_migration_for_drop_table/mysql/models/base/Foo.php new file mode 100644 index 00000000..49c10419 --- /dev/null +++ b/tests/specs/issue_fix/132_create_migration_for_drop_table/mysql/models/base/Foo.php @@ -0,0 +1,25 @@ + [['factor'], 'integer'], + ]; + } +} diff --git a/tests/specs/issue_fix/132_create_migration_for_drop_table/mysql/models/base/Fruit.php b/tests/specs/issue_fix/132_create_migration_for_drop_table/mysql/models/base/Fruit.php new file mode 100644 index 00000000..274eacd5 --- /dev/null +++ b/tests/specs/issue_fix/132_create_migration_for_drop_table/mysql/models/base/Fruit.php @@ -0,0 +1,28 @@ + [['name'], 'trim'], + 'name_string' => [['name'], 'string', 'max' => 150], + 'food_of_integer' => [['food_of'], 'integer'], + ]; + } +} diff --git a/tests/specs/issue_fix/132_create_migration_for_drop_table/mysql/models/base/Mango.php b/tests/specs/issue_fix/132_create_migration_for_drop_table/mysql/models/base/Mango.php new file mode 100644 index 00000000..cf8d111f --- /dev/null +++ b/tests/specs/issue_fix/132_create_migration_for_drop_table/mysql/models/base/Mango.php @@ -0,0 +1,28 @@ + [['name'], 'trim'], + 'name_string' => [['name'], 'string', 'max' => 150], + 'food_of_integer' => [['food_of'], 'integer'], + ]; + } +} diff --git a/tests/specs/issue_fix/132_create_migration_for_drop_table/mysql/models/base/Pristine.php b/tests/specs/issue_fix/132_create_migration_for_drop_table/mysql/models/base/Pristine.php new file mode 100644 index 00000000..c8021ca6 --- /dev/null +++ b/tests/specs/issue_fix/132_create_migration_for_drop_table/mysql/models/base/Pristine.php @@ -0,0 +1,28 @@ + [['name'], 'trim'], + 'name_string' => [['name'], 'string', 'max' => 151], + 'fruit_id_integer' => [['fruit_id'], 'integer'], + ]; + } +} diff --git a/tests/specs/issue_fix/132_create_migration_for_drop_table/mysql/models/base/Ubigpk.php b/tests/specs/issue_fix/132_create_migration_for_drop_table/mysql/models/base/Ubigpk.php new file mode 100644 index 00000000..3ffa6a51 --- /dev/null +++ b/tests/specs/issue_fix/132_create_migration_for_drop_table/mysql/models/base/Ubigpk.php @@ -0,0 +1,46 @@ + [['name', 'f'], 'trim'], + 'name_string' => [['name'], 'string', 'max' => 150], + 'size_string' => [['size'], 'string'], + 'size_in' => [['size'], 'in', 'range' => [ + 'x-small', + 'small', + 'medium', + 'large', + 'x-large', + ]], + 'size_default' => [['size'], 'default', 'value' => 'x-small'], + 'd_integer' => [['d'], 'integer'], + 'e_integer' => [['e'], 'integer'], + 'f_string' => [['f'], 'string', 'max' => 12], + 'dp_double' => [['dp'], 'double'], + 'dp2_double' => [['dp2'], 'double'], + ]; + } +} diff --git a/tests/specs/issue_fix/132_create_migration_for_drop_table/mysql/models/base/Upk.php b/tests/specs/issue_fix/132_create_migration_for_drop_table/mysql/models/base/Upk.php new file mode 100644 index 00000000..644bc0d1 --- /dev/null +++ b/tests/specs/issue_fix/132_create_migration_for_drop_table/mysql/models/base/Upk.php @@ -0,0 +1,26 @@ + [['name'], 'trim'], + 'name_string' => [['name'], 'string', 'max' => 150], + ]; + } +} diff --git a/tests/specs/issue_fix/132_create_migration_for_drop_table/pgsql/migrations_pgsql_db/m200000_000000_create_table_foos.php b/tests/specs/issue_fix/132_create_migration_for_drop_table/pgsql/migrations_pgsql_db/m200000_000000_create_table_foos.php new file mode 100644 index 00000000..268bd109 --- /dev/null +++ b/tests/specs/issue_fix/132_create_migration_for_drop_table/pgsql/migrations_pgsql_db/m200000_000000_create_table_foos.php @@ -0,0 +1,20 @@ +createTable('{{%foos}}', [ + 'id' => $this->primaryKey(), + 'factor' => $this->integer()->null()->defaultValue(null), + ]); + } + + public function safeDown() + { + $this->dropTable('{{%foos}}'); + } +} diff --git a/tests/specs/issue_fix/132_create_migration_for_drop_table/pgsql/migrations_pgsql_db/m200000_000001_delete_table_pristines.php b/tests/specs/issue_fix/132_create_migration_for_drop_table/pgsql/migrations_pgsql_db/m200000_000001_delete_table_pristines.php new file mode 100644 index 00000000..54dd111e --- /dev/null +++ b/tests/specs/issue_fix/132_create_migration_for_drop_table/pgsql/migrations_pgsql_db/m200000_000001_delete_table_pristines.php @@ -0,0 +1,23 @@ +dropForeignKey('name', '{{%pristines}}'); + $this->dropTable('{{%pristines}}'); + } + + public function safeDown() + { + $this->createTable('{{%pristines}}', [ + 'id' => $this->primaryKey(), + 'name' => $this->string(151)->null()->defaultValue(null), + 'fruit_id' => 'int4 NULL DEFAULT NULL', + ]); + $this->addForeignKey('name', '{{%pristines}}', 'fruit_id', 'itt_fruits', 'id'); + } +} diff --git a/tests/specs/issue_fix/132_create_migration_for_drop_table/pgsql/migrations_pgsql_db/m200000_000002_delete_table_fruits.php b/tests/specs/issue_fix/132_create_migration_for_drop_table/pgsql/migrations_pgsql_db/m200000_000002_delete_table_fruits.php new file mode 100644 index 00000000..7a6b2e8f --- /dev/null +++ b/tests/specs/issue_fix/132_create_migration_for_drop_table/pgsql/migrations_pgsql_db/m200000_000002_delete_table_fruits.php @@ -0,0 +1,23 @@ +dropForeignKey('name2', '{{%fruits}}'); + $this->dropTable('{{%fruits}}'); + } + + public function safeDown() + { + $this->createTable('{{%fruits}}', [ + 'id' => $this->primaryKey(), + 'name' => $this->string(150)->null()->defaultValue(null), + 'food_of' => 'int4 NULL DEFAULT NULL', + ]); + $this->addForeignKey('name2', '{{%fruits}}', 'food_of', 'itt_the_animal_table_name', 'id'); + } +} diff --git a/tests/specs/issue_fix/132_create_migration_for_drop_table/pgsql/migrations_pgsql_db/m200000_000003_delete_table_the_mango_table_name.php b/tests/specs/issue_fix/132_create_migration_for_drop_table/pgsql/migrations_pgsql_db/m200000_000003_delete_table_the_mango_table_name.php new file mode 100644 index 00000000..fd72c4b4 --- /dev/null +++ b/tests/specs/issue_fix/132_create_migration_for_drop_table/pgsql/migrations_pgsql_db/m200000_000003_delete_table_the_mango_table_name.php @@ -0,0 +1,23 @@ +dropForeignKey('animal_fruit_fk', '{{%the_mango_table_name}}'); + $this->dropTable('{{%the_mango_table_name}}'); + } + + public function safeDown() + { + $this->createTable('{{%the_mango_table_name}}', [ + 'id' => $this->primaryKey(), + 'name' => $this->string(150)->null()->defaultValue(null), + 'food_of' => 'int4 NULL DEFAULT NULL', + ]); + $this->addForeignKey('animal_fruit_fk', '{{%the_mango_table_name}}', 'food_of', 'itt_the_animal_table_name', 'id'); + } +} diff --git a/tests/specs/issue_fix/132_create_migration_for_drop_table/pgsql/migrations_pgsql_db/m200000_000004_delete_table_the_animal_table_name.php b/tests/specs/issue_fix/132_create_migration_for_drop_table/pgsql/migrations_pgsql_db/m200000_000004_delete_table_the_animal_table_name.php new file mode 100644 index 00000000..c3f3c88f --- /dev/null +++ b/tests/specs/issue_fix/132_create_migration_for_drop_table/pgsql/migrations_pgsql_db/m200000_000004_delete_table_the_animal_table_name.php @@ -0,0 +1,20 @@ +dropTable('{{%the_animal_table_name}}'); + } + + public function safeDown() + { + $this->createTable('{{%the_animal_table_name}}', [ + 'id' => $this->primaryKey(), + 'name' => $this->string(150)->null()->defaultValue(null), + ]); + } +} diff --git a/tests/specs/issue_fix/132_create_migration_for_drop_table/pgsql/migrations_pgsql_db/m200000_000005_delete_table_upks.php b/tests/specs/issue_fix/132_create_migration_for_drop_table/pgsql/migrations_pgsql_db/m200000_000005_delete_table_upks.php new file mode 100644 index 00000000..9e9e49ac --- /dev/null +++ b/tests/specs/issue_fix/132_create_migration_for_drop_table/pgsql/migrations_pgsql_db/m200000_000005_delete_table_upks.php @@ -0,0 +1,22 @@ +dropTable('{{%upks}}'); + } + + public function safeDown() + { + $this->createTable('{{%upks}}', [ + 'id' => $this->primaryKey(), + 'name' => $this->string(150)->null()->defaultValue(null), + 'current_mood' => '"mood" NULL DEFAULT NULL', + 'e2' => '"enum_itt_upks_e2" NULL DEFAULT NULL', + ]); + } +} diff --git a/tests/specs/issue_fix/132_create_migration_for_drop_table/pgsql/migrations_pgsql_db/m200000_000006_delete_table_bigpks.php b/tests/specs/issue_fix/132_create_migration_for_drop_table/pgsql/migrations_pgsql_db/m200000_000006_delete_table_bigpks.php new file mode 100644 index 00000000..2ba13f50 --- /dev/null +++ b/tests/specs/issue_fix/132_create_migration_for_drop_table/pgsql/migrations_pgsql_db/m200000_000006_delete_table_bigpks.php @@ -0,0 +1,20 @@ +dropTable('{{%bigpks}}'); + } + + public function safeDown() + { + $this->createTable('{{%bigpks}}', [ + 'id' => $this->bigPrimaryKey(), + 'name' => $this->string(150)->null()->defaultValue(null), + ]); + } +} diff --git a/tests/specs/issue_fix/132_create_migration_for_drop_table/pgsql/migrations_pgsql_db/m200000_000007_delete_table_ubigpks.php b/tests/specs/issue_fix/132_create_migration_for_drop_table/pgsql/migrations_pgsql_db/m200000_000007_delete_table_ubigpks.php new file mode 100644 index 00000000..197081f6 --- /dev/null +++ b/tests/specs/issue_fix/132_create_migration_for_drop_table/pgsql/migrations_pgsql_db/m200000_000007_delete_table_ubigpks.php @@ -0,0 +1,25 @@ +dropTable('{{%ubigpks}}'); + } + + public function safeDown() + { + $this->createTable('{{%ubigpks}}', [ + 'id' => $this->bigPrimaryKey(), + 'name' => $this->string(150)->null()->defaultValue(null), + 'f' => 'numeric(12,4) NULL DEFAULT NULL', + 'g5' => 'text[] NULL DEFAULT NULL', + 'g6' => 'text[][] NULL DEFAULT NULL', + 'g7' => 'numeric(10,7) NULL DEFAULT NULL', + 'dp' => 'float8 NULL DEFAULT NULL', + ]); + } +} diff --git a/tests/specs/issue_fix/132_create_migration_for_drop_table/pgsql/models/Animal.php b/tests/specs/issue_fix/132_create_migration_for_drop_table/pgsql/models/Animal.php new file mode 100644 index 00000000..92caf2f3 --- /dev/null +++ b/tests/specs/issue_fix/132_create_migration_for_drop_table/pgsql/models/Animal.php @@ -0,0 +1,10 @@ + [['name'], 'trim'], + 'name_string' => [['name'], 'string', 'max' => 150], + ]; + } +} diff --git a/tests/specs/issue_fix/132_create_migration_for_drop_table/pgsql/models/base/Bigpk.php b/tests/specs/issue_fix/132_create_migration_for_drop_table/pgsql/models/base/Bigpk.php new file mode 100644 index 00000000..2bf05933 --- /dev/null +++ b/tests/specs/issue_fix/132_create_migration_for_drop_table/pgsql/models/base/Bigpk.php @@ -0,0 +1,26 @@ + [['name'], 'trim'], + 'name_string' => [['name'], 'string', 'max' => 150], + ]; + } +} diff --git a/tests/specs/issue_fix/132_create_migration_for_drop_table/pgsql/models/base/Foo.php b/tests/specs/issue_fix/132_create_migration_for_drop_table/pgsql/models/base/Foo.php new file mode 100644 index 00000000..49c10419 --- /dev/null +++ b/tests/specs/issue_fix/132_create_migration_for_drop_table/pgsql/models/base/Foo.php @@ -0,0 +1,25 @@ + [['factor'], 'integer'], + ]; + } +} diff --git a/tests/specs/issue_fix/132_create_migration_for_drop_table/pgsql/models/base/Fruit.php b/tests/specs/issue_fix/132_create_migration_for_drop_table/pgsql/models/base/Fruit.php new file mode 100644 index 00000000..274eacd5 --- /dev/null +++ b/tests/specs/issue_fix/132_create_migration_for_drop_table/pgsql/models/base/Fruit.php @@ -0,0 +1,28 @@ + [['name'], 'trim'], + 'name_string' => [['name'], 'string', 'max' => 150], + 'food_of_integer' => [['food_of'], 'integer'], + ]; + } +} diff --git a/tests/specs/issue_fix/132_create_migration_for_drop_table/pgsql/models/base/Mango.php b/tests/specs/issue_fix/132_create_migration_for_drop_table/pgsql/models/base/Mango.php new file mode 100644 index 00000000..cf8d111f --- /dev/null +++ b/tests/specs/issue_fix/132_create_migration_for_drop_table/pgsql/models/base/Mango.php @@ -0,0 +1,28 @@ + [['name'], 'trim'], + 'name_string' => [['name'], 'string', 'max' => 150], + 'food_of_integer' => [['food_of'], 'integer'], + ]; + } +} diff --git a/tests/specs/issue_fix/132_create_migration_for_drop_table/pgsql/models/base/Pristine.php b/tests/specs/issue_fix/132_create_migration_for_drop_table/pgsql/models/base/Pristine.php new file mode 100644 index 00000000..c8021ca6 --- /dev/null +++ b/tests/specs/issue_fix/132_create_migration_for_drop_table/pgsql/models/base/Pristine.php @@ -0,0 +1,28 @@ + [['name'], 'trim'], + 'name_string' => [['name'], 'string', 'max' => 151], + 'fruit_id_integer' => [['fruit_id'], 'integer'], + ]; + } +} diff --git a/tests/specs/issue_fix/132_create_migration_for_drop_table/pgsql/models/base/Ubigpk.php b/tests/specs/issue_fix/132_create_migration_for_drop_table/pgsql/models/base/Ubigpk.php new file mode 100644 index 00000000..8ea477cd --- /dev/null +++ b/tests/specs/issue_fix/132_create_migration_for_drop_table/pgsql/models/base/Ubigpk.php @@ -0,0 +1,36 @@ + [['name', 'f', 'g5', 'g6', 'g7'], 'trim'], + 'name_string' => [['name'], 'string', 'max' => 150], + 'f_string' => [['f'], 'string'], + 'g5_string' => [['g5'], 'string'], + 'g6_string' => [['g6'], 'string'], + 'g7_string' => [['g7'], 'string'], + 'dp_double' => [['dp'], 'double'], + ]; + } +} diff --git a/tests/specs/issue_fix/132_create_migration_for_drop_table/pgsql/models/base/Upk.php b/tests/specs/issue_fix/132_create_migration_for_drop_table/pgsql/models/base/Upk.php new file mode 100644 index 00000000..91e7cc76 --- /dev/null +++ b/tests/specs/issue_fix/132_create_migration_for_drop_table/pgsql/models/base/Upk.php @@ -0,0 +1,40 @@ + [['name'], 'trim'], + 'name_string' => [['name'], 'string', 'max' => 150], + 'current_mood_string' => [['current_mood'], 'string'], + 'current_mood_in' => [['current_mood'], 'in', 'range' => [ + 'sad', + 'ok', + 'happy', + ]], + 'e2_string' => [['e2'], 'string'], + 'e2_in' => [['e2'], 'in', 'range' => [ + 'sad2', + 'ok2', + 'happy2', + ]], + ]; + } +} diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index d81a1815..402d852d 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -247,7 +247,15 @@ public function testCreateMigrationForDropTable132() $this->createTablesForCreateMigrationForDropTable132(); $this->runGenerator($testFile); $this->runActualMigrations('mysql', 8); - // ... TODO compare files + + $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ + 'recursive' => true, + ]); + $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/132_create_migration_for_drop_table/mysql"), [ + 'recursive' => true, + ]); + $this->checkFiles($actualFiles, $expectedFiles); + $this->deleteTablesForCreateMigrationForDropTable132(); } @@ -325,7 +333,15 @@ public function testCreateMigrationForDropTable132ForPgsql() $this->createTablesForCreateMigrationForDropTable132ForPgsql(); $this->runGenerator($testFile, 'pgsql'); $this->runActualMigrations('pgsql', 8); - // ... TODO compare files + + $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ + 'recursive' => true, + ]); + $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/132_create_migration_for_drop_table/pgsql"), [ + 'recursive' => true, + ]); + $this->checkFiles($actualFiles, $expectedFiles); + $this->deleteTablesForCreateMigrationForDropTable132ForPgsql(); } From e8dd4afa1f1243b72810dc6a106c87f9f1d116fa Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Wed, 26 Jun 2024 18:50:33 +0530 Subject: [PATCH 044/358] Add docs + enhancements + refactoring --- README.md | 37 +++++++------------ src/lib/CustomSpecAttr.php | 6 +++ src/lib/SchemaToDatabase.php | 29 +++++---------- src/lib/generators/MigrationsGenerator.php | 23 ------------ src/lib/openapi/ComponentSchema.php | 2 +- .../132_create_migration_for_drop_table.yaml | 2 +- 6 files changed, 32 insertions(+), 67 deletions(-) diff --git a/README.md b/README.md index 3cfe6173..9a653719 100644 --- a/README.md +++ b/README.md @@ -310,9 +310,21 @@ Provide custom database table column name in case of relationship column. This w ``` -### `x-keep-tables` +### `x-deleted-schemas` -You may ... TODO docs for https://github.com/cebe/yii2-openapi/issues/132 +This is root level key used to generate "drop table" migration for the deleted component schema. If a component schema (DB model) is removed from OpenAPI spec then its following entities should be also deleted from the code: + + - DB table (migrations) + - model + - faker + +So to generate appropriate migration for the removed schema, explicitly setting schema name or schema name + custom table name is required in this key. Only then the migrations will be generated. It should be set as: + +```yaml +x-deleted-schemas: + - Fruit # Example: table name is evaluated to `itt_fruits`, if `itt_` is prefix set in DB config + - Mango: the_mango_table_name # custom table name; see `x-table` in README.md +``` ## Many-to-Many relation definition @@ -574,24 +586,3 @@ Professional support, consulting as well as software development services are av https://www.cebe.cc/en/contact Development of this library is sponsored by [cebe.:cloud: "Your Professional Deployment Platform"](https://cebe.cloud). - - ---- - - -TODO - -foreach dbmodels - grab table names - -create list of all table names ---- -fetch all table name list from DB (SQL query) - -find the diff - -create drop table mig diff tables - - - - diff --git a/src/lib/CustomSpecAttr.php b/src/lib/CustomSpecAttr.php index 7e02a85d..3e424e1c 100644 --- a/src/lib/CustomSpecAttr.php +++ b/src/lib/CustomSpecAttr.php @@ -40,4 +40,10 @@ class CustomSpecAttr * Foreign key column name. See README for usage docs */ public const FK_COLUMN_NAME = 'x-fk-column-name'; + + /** + * Drop table Migrations to be generated from removed component schemas + * See README for docs + */ + public const DELETED_SCHEMAS = 'x-deleted-schemas'; } diff --git a/src/lib/SchemaToDatabase.php b/src/lib/SchemaToDatabase.php index 52ddfe3a..435a9e37 100644 --- a/src/lib/SchemaToDatabase.php +++ b/src/lib/SchemaToDatabase.php @@ -118,10 +118,10 @@ public function prepareModels(): array // TODO generate inverse relations // for drop table/schema https://github.com/cebe/yii2-openapi/issues/132 - $tablesToDrop = $modelsToDrop = []; - if (isset($this->config->getOpenApi()->{'x-deleted-schemas'})) { - $tablesToDrop = $this->config->getOpenApi()->{'x-deleted-schemas'}; // for removed (components) schemas - $modelsToDrop = static::f7($tablesToDrop); + $modelsToDrop = []; + if (isset($this->config->getOpenApi()->{CustomSpecAttr::DELETED_SCHEMAS})) { + $tablesToDrop = $this->config->getOpenApi()->{CustomSpecAttr::DELETED_SCHEMAS}; // for removed (components) schemas + $modelsToDrop = static::dbModelsForDropTable($tablesToDrop); } return ArrayHelper::merge($models, $modelsToDrop); @@ -245,7 +245,7 @@ private function canGenerateModel(string $schemaName, ComponentSchema $schema): } /** - * @param array $schemasToDrop . Example: + * @param array $schemasToDrop . Example structure: * ``` * array(2) { * [0]=> @@ -253,19 +253,19 @@ private function canGenerateModel(string $schemaName, ComponentSchema $schema): * [1]=> * array(1) { * ["Mango"]=> - * string(10) "the_mango_table_name" + * string(10) "the_mango_custom_table_name" * } * } * ``` * @return DbModel[] */ - public static function f7(array $schemasToDrop): array // TODO rename + public static function dbModelsForDropTable(array $schemasToDrop): array { $dbModelsToDrop = []; foreach ($schemasToDrop as $key => $value) { if (is_string($value)) { // schema name $schemaName = $value; - $tableName = static::resolveTableNameHere($schemaName); + $tableName = static::resolveTableName($schemaName); } elseif (is_array($value)) { $schemaName = array_key_first($value); $tableName = $value[$schemaName]; @@ -283,21 +283,12 @@ public static function f7(array $schemasToDrop): array // TODO rename 'drop' => true ]); $dbModelsToDrop[$key] = $dbModelHere; - // TODO remove -// $mm = new MigrationModel($dbModelHere); - // $builder = new MigrationRecordBuilder($this->db->getSchema()); - // $mm->addUpCode($builder->dropTable($tableName)) - // ->addDownCode($builder->dropTable($tableName)) - // ; - // if ($mm->notEmpty()) { - // $this->migrations[$tableName] = $mm; - // } } } return $dbModelsToDrop; } - public static function resolveTableNameHere(string $schemaName): string // TODO rename + public static function resolveTableName(string $schemaName): string { return Inflector::camel2id(StringHelper::basename(Inflector::pluralize($schemaName)), '_'); } @@ -305,7 +296,7 @@ public static function resolveTableNameHere(string $schemaName): string // TODO /** * @return Attribute[] */ - public static function attributesFromColumnSchemas(array $columnSchemas) + public static function attributesFromColumnSchemas(array $columnSchemas): array { $attributes = []; foreach ($columnSchemas as $columnName => $columnSchema) { diff --git a/src/lib/generators/MigrationsGenerator.php b/src/lib/generators/MigrationsGenerator.php index 6e37b90f..828b7c30 100644 --- a/src/lib/generators/MigrationsGenerator.php +++ b/src/lib/generators/MigrationsGenerator.php @@ -131,29 +131,6 @@ public function buildMigrations():array } } - // TODO remove - // for deleted schema, create migration for drop table -// foreach ($this->tablesToDrop as $tableName) { -// $table = Yii::$app->db->schema->getTableSchema($tableName); -// if ($table) { -// -// $dbModelHere = new DbModel([ -// 'pkName' => $table->primaryKey, -// 'name' => $table->name, -// 'tableName' => $tableName, -// ]); -// $mm = new MigrationModel($dbModelHere); -// $builder = new MigrationRecordBuilder($this->db->getSchema()); -// $mm->addUpCode($builder->dropTable($tableName)) -// ->addDownCode($builder->dropTable($tableName)) -// ; -// if ($mm->notEmpty()) { - //// var_dump('$this->migrations'); die; -// $this->migrations[$tableName] = $mm; -// } -// } -// } - return !empty($this->migrations) ? $this->sortMigrationsByDeps() : []; } diff --git a/src/lib/openapi/ComponentSchema.php b/src/lib/openapi/ComponentSchema.php index b1293f90..809f0958 100644 --- a/src/lib/openapi/ComponentSchema.php +++ b/src/lib/openapi/ComponentSchema.php @@ -112,7 +112,7 @@ public function isNonDb():bool public function resolveTableName(string $schemaName):string { return $this->schema->{CustomSpecAttr::TABLE} ?? - SchemaToDatabase::resolveTableNameHere($schemaName); + SchemaToDatabase::resolveTableName($schemaName); } public function hasCustomTableName():bool diff --git a/tests/specs/issue_fix/132_create_migration_for_drop_table/132_create_migration_for_drop_table.yaml b/tests/specs/issue_fix/132_create_migration_for_drop_table/132_create_migration_for_drop_table.yaml index 114ea255..74f46474 100644 --- a/tests/specs/issue_fix/132_create_migration_for_drop_table/132_create_migration_for_drop_table.yaml +++ b/tests/specs/issue_fix/132_create_migration_for_drop_table/132_create_migration_for_drop_table.yaml @@ -5,7 +5,7 @@ info: x-deleted-schemas: - Pristine - - Fruit # Example: table name evaluated to `itt_fruits`. `itt_` is prefix set in DB config + - Fruit # Example: table name is evaluated to `itt_fruits`, if `itt_` is prefix set in DB config - Mango: the_mango_table_name # custom table name; see `x-table` in README.md - Animal: the_animal_table_name - Upk From d9bad2e15d9c802d3984bafcf54e66dfb6da6f71 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Wed, 26 Jun 2024 19:41:32 +0530 Subject: [PATCH 045/358] Polish --- src/lib/AttributeResolver.php | 154 +++++++------- src/lib/items/Attribute.php | 2 +- src/lib/migrations/BaseMigrationBuilder.php | 3 - tests/unit/AttributeResolverTest.php | 212 ++++++++++---------- 4 files changed, 183 insertions(+), 188 deletions(-) diff --git a/src/lib/AttributeResolver.php b/src/lib/AttributeResolver.php index 7bb29bfa..a5a344f5 100644 --- a/src/lib/AttributeResolver.php +++ b/src/lib/AttributeResolver.php @@ -7,8 +7,6 @@ namespace cebe\yii2openapi\lib; -use cebe\yii2openapi\lib\Config; -use cebe\yii2openapi\lib\CustomSpecAttr; use cebe\yii2openapi\lib\exceptions\InvalidDefinitionException; use cebe\yii2openapi\lib\items\Attribute; use cebe\yii2openapi\lib\items\AttributeRelation; @@ -20,9 +18,9 @@ use cebe\yii2openapi\lib\openapi\ComponentSchema; use cebe\yii2openapi\lib\openapi\PropertySchema; use Yii; +use yii\base\InvalidConfigException; use yii\helpers\Inflector; use yii\helpers\StringHelper; -use yii\helpers\VarDumper; use function explode; use function strpos; use function strtolower; @@ -63,7 +61,7 @@ class AttributeResolver private $schema; /** - * @var \cebe\yii2openapi\lib\items\JunctionSchemas + * @var JunctionSchemas */ private $junctions; @@ -88,14 +86,14 @@ public function __construct(string $schemaName, ComponentSchema $schema, Junctio } /** - * @return \cebe\yii2openapi\lib\items\DbModel - * @throws \cebe\yii2openapi\lib\exceptions\InvalidDefinitionException - * @throws \yii\base\InvalidConfigException + * @return DbModel + * @throws InvalidDefinitionException + * @throws InvalidConfigException */ - public function resolve():DbModel + public function resolve(): DbModel { foreach ($this->schema->getProperties() as $property) { - /** @var $property \cebe\yii2openapi\lib\openapi\PropertySchema */ + /** @var $property PropertySchema */ $isRequired = $this->schema->isRequiredProperty($property->getName()); $nullableValue = $property->getProperty()->getSerializableData()->nullable ?? null; @@ -130,25 +128,25 @@ public function resolve():DbModel } /** - * @param \cebe\yii2openapi\lib\openapi\PropertySchema $property - * @param bool $isRequired - * @throws \cebe\yii2openapi\lib\exceptions\InvalidDefinitionException - * @throws \yii\base\InvalidConfigException + * @param PropertySchema $property + * @param bool $isRequired + * @throws InvalidDefinitionException + * @throws InvalidConfigException */ - protected function resolveJunctionTableProperty(PropertySchema $property, bool $isRequired):void + protected function resolveJunctionTableProperty(PropertySchema $property, bool $isRequired): void { if ($this->junctions->isJunctionProperty($this->schemaName, $property->getName())) { $junkAttribute = $this->junctions->byJunctionSchema($this->schemaName)[$property->getName()]; $attribute = Yii::createObject(Attribute::class, [$property->getName()]); $attribute->setRequired($isRequired) - ->setDescription($property->getAttr('description', '')) - ->setReadOnly($property->isReadonly()) - ->setIsPrimary($property->isPrimaryKey()) - ->asReference($junkAttribute['relatedClassName']) - ->setPhpType($junkAttribute['phpType']) - ->setDbType($junkAttribute['dbType']) - ->setForeignKeyColumnName($property->fkColName) - ->setTableName($this->schema->resolveTableName($this->schemaName)); + ->setDescription($property->getAttr('description', '')) + ->setReadOnly($property->isReadonly()) + ->setIsPrimary($property->isPrimaryKey()) + ->asReference($junkAttribute['relatedClassName']) + ->setPhpType($junkAttribute['phpType']) + ->setDbType($junkAttribute['dbType']) + ->setForeignKeyColumnName($property->fkColName) + ->setTableName($this->schema->resolveTableName($this->schemaName)); $relation = Yii::createObject(AttributeRelation::class, [ $property->getName(), $junkAttribute['relatedTableName'], @@ -163,12 +161,12 @@ protected function resolveJunctionTableProperty(PropertySchema $property, bool $ } /** - * @param \cebe\yii2openapi\lib\openapi\PropertySchema $property - * @param bool $isRequired - * @throws \cebe\yii2openapi\lib\exceptions\InvalidDefinitionException - * @throws \yii\base\InvalidConfigException + * @param PropertySchema $property + * @param bool $isRequired + * @throws InvalidDefinitionException + * @throws InvalidConfigException */ - protected function resolveHasMany2ManyTableProperty(PropertySchema $property, bool $isRequired):void + protected function resolveHasMany2ManyTableProperty(PropertySchema $property, bool $isRequired): void { if ($this->junctions->isManyToManyProperty($this->schemaName, $property->getName())) { return; @@ -198,7 +196,7 @@ protected function resolveHasMany2ManyTableProperty(PropertySchema $property, bo $this->relations[Inflector::pluralize($junkRef)] = Yii::createObject(AttributeRelation::class, [$junkRef, $junkAttribute['junctionTable'], $viaModel]) - ->asHasMany([$junkAttribute['pairProperty'] . '_id' => $this->schema->getPkName()]); + ->asHasMany([$junkAttribute['pairProperty'] . '_id' => $this->schema->getPkName()]); return; } @@ -206,36 +204,37 @@ protected function resolveHasMany2ManyTableProperty(PropertySchema $property, bo } /** - * @param \cebe\yii2openapi\lib\openapi\PropertySchema $property - * @param bool $isRequired - * @param bool|null|string $nullableValue if string then its value will be only constant `ARG_ABSENT`. Default `null` is avoided because it can be in passed value in method call - * @throws \cebe\yii2openapi\lib\exceptions\InvalidDefinitionException - * @throws \yii\base\InvalidConfigException + * @param PropertySchema $property + * @param bool $isRequired + * @param bool|null|string $nullableValue if string then its value will be only constant `ARG_ABSENT`. Default `null` is avoided because it can be in passed value in method call + * @throws InvalidDefinitionException + * @throws InvalidConfigException */ protected function resolveProperty( PropertySchema $property, - bool $isRequired, - $nullableValue = 'ARG_ABSENT' - ):void { + bool $isRequired, + $nullableValue = 'ARG_ABSENT' + ): void + { if ($nullableValue === 'ARG_ABSENT') { $nullableValue = $property->getProperty()->getSerializableData()->nullable ?? null; } $attribute = Yii::createObject(Attribute::class, [$property->getName()]); $attribute->setRequired($isRequired) - ->setDescription($property->getAttr('description', '')) - ->setReadOnly($property->isReadonly()) - ->setDefault($property->guessDefault()) - ->setXDbType($property->getAttr(CustomSpecAttr::DB_TYPE)) - ->setXDbDefaultExpression($property->getAttr(CustomSpecAttr::DB_DEFAULT_EXPRESSION)) - ->setNullable($nullableValue) - ->setIsPrimary($property->isPrimaryKey()) - ->setForeignKeyColumnName($property->fkColName) - ->setTableName($this->schema->resolveTableName($this->schemaName)); + ->setDescription($property->getAttr('description', '')) + ->setReadOnly($property->isReadonly()) + ->setDefault($property->guessDefault()) + ->setXDbType($property->getAttr(CustomSpecAttr::DB_TYPE)) + ->setXDbDefaultExpression($property->getAttr(CustomSpecAttr::DB_DEFAULT_EXPRESSION)) + ->setNullable($nullableValue) + ->setIsPrimary($property->isPrimaryKey()) + ->setForeignKeyColumnName($property->fkColName) + ->setTableName($this->schema->resolveTableName($this->schemaName)); if ($property->isReference()) { if ($property->isVirtual()) { throw new InvalidDefinitionException('References not supported for virtual attributes'); } - + if ($property->isNonDbReference()) { $attribute->asNonDbReference($property->getRefClassName()); $relation = Yii::createObject( @@ -260,17 +259,17 @@ protected function resolveProperty( [$min, $max] = $fkProperty->guessMinMax(); $attribute->asReference($relatedClassName); $attribute->setPhpType($fkProperty->guessPhpType()) - ->setDbType($fkProperty->guessDbType(true)) - ->setSize($fkProperty->getMaxLength()) - ->setDescription($property->getRefSchema()->getDescription()) - ->setDefault($fkProperty->guessDefault()) - ->setLimits($min, $max, $fkProperty->getMinLength()); + ->setDbType($fkProperty->guessDbType(true)) + ->setSize($fkProperty->getMaxLength()) + ->setDescription($property->getRefSchema()->getDescription()) + ->setDefault($fkProperty->guessDefault()) + ->setLimits($min, $max, $fkProperty->getMinLength()); $relation = Yii::createObject( AttributeRelation::class, [$property->getName(), $relatedTableName, $relatedClassName] ) - ->asHasOne([$fkProperty->getName() => $attribute->columnName]); + ->asHasOne([$fkProperty->getName() => $attribute->columnName]); $relation->onUpdateFkConstraint = $property->onUpdateFkConstraint; $relation->onDeleteFkConstraint = $property->onDeleteFkConstraint; if ($property->isRefPointerToSelf()) { @@ -281,10 +280,10 @@ protected function resolveProperty( if (!$property->isReference() && !$property->hasRefItems()) { [$min, $max] = $property->guessMinMax(); $attribute->setIsVirtual($property->isVirtual()) - ->setPhpType($property->guessPhpType()) - ->setDbType($property->guessDbType()) - ->setSize($property->getMaxLength()) - ->setLimits($min, $max, $property->getMinLength()); + ->setPhpType($property->guessPhpType()) + ->setDbType($property->guessDbType()) + ->setSize($property->getMaxLength()) + ->setLimits($min, $max, $property->getMinLength()); if ($property->hasEnum()) { $attribute->setEnumValues($property->getAttr('enum')); } @@ -321,7 +320,7 @@ protected function resolveProperty( AttributeRelation::class, [$property->getName(), $relatedTableName, $relatedClassName] ) - ->asHasMany([$fkProperty->getName() => $fkProperty->getName()])->asSelfReference(); + ->asHasMany([$fkProperty->getName() => $fkProperty->getName()])->asSelfReference(); return; } $foreignPk = Inflector::camel2id($fkProperty->getName(), '_') . '_id'; @@ -330,7 +329,7 @@ protected function resolveProperty( AttributeRelation::class, [$property->getName(), $relatedTableName, $relatedClassName] ) - ->asHasMany([$foreignPk => $this->schema->getPkName()]); + ->asHasMany([$foreignPk => $this->schema->getPkName()]); return; } $relatedClassName = $property->getRefClassName(); @@ -349,7 +348,7 @@ protected function resolveProperty( AttributeRelation::class, [$property->getName(), $relatedTableName, $relatedClassName] ) - ->asHasMany([Inflector::camel2id($this->schemaName, '_') . '_id' => $this->schema->getPkName()]); + ->asHasMany([Inflector::camel2id($this->schemaName, '_') . '_id' => $this->schema->getPkName()]); return; } if ($this->schema->isNonDb() && $attribute->isReference()) { @@ -369,14 +368,15 @@ protected function resolveProperty( * @param string $relatedTableName * @param ComponentSchema $refSchema * @return bool - * @throws \yii\base\InvalidConfigException + * @throws InvalidConfigException */ protected function catchManyToMany( - string $propertyName, - string $relatedSchemaName, - string $relatedTableName, + string $propertyName, + string $relatedSchemaName, + string $relatedTableName, ComponentSchema $refSchema - ):bool { + ): bool + { if (strtolower(Inflector::id2camel($propertyName, '_')) !== strtolower(Inflector::pluralize($relatedSchemaName))) { return false; @@ -408,9 +408,9 @@ protected function catchManyToMany( } /** - * @throws \yii\base\InvalidConfigException + * @throws InvalidConfigException */ - protected function guessFakerStub(Attribute $attribute, PropertySchema $property):?string + protected function guessFakerStub(Attribute $attribute, PropertySchema $property): ?string { $resolver = Yii::createObject(['class' => FakerStubResolver::class], [$attribute, $property, $this->config]); return $resolver->resolve(); @@ -419,9 +419,9 @@ protected function guessFakerStub(Attribute $attribute, PropertySchema $property /** * @param array $indexes * @return array|DbIndex[] - * @throws \cebe\yii2openapi\lib\exceptions\InvalidDefinitionException + * @throws InvalidDefinitionException */ - protected function prepareIndexes(array $indexes):array + protected function prepareIndexes(array $indexes): array { $dbIndexes = []; foreach ($indexes as $index) { @@ -472,12 +472,12 @@ protected function prepareIndexes(array $indexes):array } /** - * @param \cebe\yii2openapi\lib\openapi\PropertySchema $property - * @param \cebe\yii2openapi\lib\items\Attribute $attribute + * @param PropertySchema $property + * @param Attribute $attribute * @return void - * @throws \yii\base\InvalidConfigException + * @throws InvalidConfigException */ - protected function resolvePropertyRef(PropertySchema $property, Attribute $attribute):void + protected function resolvePropertyRef(PropertySchema $property, Attribute $attribute): void { $fkProperty = new PropertySchema( $property->getRefSchema()->getSchema(), @@ -486,11 +486,11 @@ protected function resolvePropertyRef(PropertySchema $property, Attribute $attri ); [$min, $max] = $fkProperty->guessMinMax(); $attribute->setPhpType($fkProperty->guessPhpType()) - ->setDbType($fkProperty->guessDbType(true)) - ->setSize($fkProperty->getMaxLength()) - ->setDescription($fkProperty->getAttr('description')) - ->setDefault($fkProperty->guessDefault()) - ->setLimits($min, $max, $fkProperty->getMinLength()); + ->setDbType($fkProperty->guessDbType(true)) + ->setSize($fkProperty->getMaxLength()) + ->setDescription($fkProperty->getAttr('description')) + ->setDefault($fkProperty->guessDefault()) + ->setLimits($min, $max, $fkProperty->getMinLength()); $this->attributes[$property->getName()] = $attribute->setFakerStub($this->guessFakerStub($attribute, $fkProperty)); } diff --git a/src/lib/items/Attribute.php b/src/lib/items/Attribute.php index d697e78f..26a079d9 100644 --- a/src/lib/items/Attribute.php +++ b/src/lib/items/Attribute.php @@ -150,7 +150,7 @@ public function setDbType(string $dbType):Attribute return $this; } - public function setTableName(string $tableName):Attribute + public function setTableName(string $tableName): Attribute { $this->tableName = $tableName; return $this; diff --git a/src/lib/migrations/BaseMigrationBuilder.php b/src/lib/migrations/BaseMigrationBuilder.php index d028612c..7ec2e3fc 100644 --- a/src/lib/migrations/BaseMigrationBuilder.php +++ b/src/lib/migrations/BaseMigrationBuilder.php @@ -598,13 +598,10 @@ public function buildTablesDrop(): void return; } -// $this->migration->addDownCode($this->recordBuilder->addPrimaryKey($this->model->getTableAlias(), $this->tableSchema->primaryKey)); - $this->migration->addUpCode($this->recordBuilder->dropTable($this->model->getTableAlias())) ->addDownCode( $this->recordBuilder->createTable( $this->model->getTableAlias(), -// $this->model->attributesToColumnSchema() SchemaToDatabase::enhanceColumnSchemas($this->tableSchema->columns) ) ); diff --git a/tests/unit/AttributeResolverTest.php b/tests/unit/AttributeResolverTest.php index 2a974d96..9c55107c 100644 --- a/tests/unit/AttributeResolverTest.php +++ b/tests/unit/AttributeResolverTest.php @@ -12,122 +12,120 @@ use cebe\yii2openapi\lib\openapi\ComponentSchema; use tests\DbTestCase; use Yii; -use yii\helpers\VarDumper; -use const PHP_EOL; class AttributeResolverTest extends DbTestCase { - public function testManyToManyResolve() - { - $schemaFile = Yii::getAlias("@specs/many2many.yaml"); - $openApi = Reader::readFromYamlFile($schemaFile, OpenApi::class, false); - $schema = new ComponentSchema($openApi->components->schemas['Post'], 'Post'); - $postModel = (new AttributeResolver('Post', $schema, new JunctionSchemas([])))->resolve(); - self::assertNotEmpty($postModel->many2many); - $relation = $postModel->many2many['tags']; - self::assertInstanceOf(ManyToManyRelation::class, $relation); - self::assertEquals('Tag', $relation->relatedClassName); - self::assertEquals('Post', $relation->className); - self::assertEquals('id', $relation->pkAttribute->propertyName); - self::assertEquals('posts2tags', $relation->getViaTableName()); - self::assertEquals(['id' => 'tag_id'], $relation->getLink()); - self::assertEquals(['post_id' => 'id'], $relation->getViaLink()); + public function testManyToManyResolve() + { + $schemaFile = Yii::getAlias("@specs/many2many.yaml"); + $openApi = Reader::readFromYamlFile($schemaFile, OpenApi::class, false); + $schema = new ComponentSchema($openApi->components->schemas['Post'], 'Post'); + $postModel = (new AttributeResolver('Post', $schema, new JunctionSchemas([])))->resolve(); + self::assertNotEmpty($postModel->many2many); + $relation = $postModel->many2many['tags']; + self::assertInstanceOf(ManyToManyRelation::class, $relation); + self::assertEquals('Tag', $relation->relatedClassName); + self::assertEquals('Post', $relation->className); + self::assertEquals('id', $relation->pkAttribute->propertyName); + self::assertEquals('posts2tags', $relation->getViaTableName()); + self::assertEquals(['id' => 'tag_id'], $relation->getLink()); + self::assertEquals(['post_id' => 'id'], $relation->getViaLink()); - $schema = new ComponentSchema($openApi->components->schemas['Tag'], 'Tag'); - $tagModel = (new AttributeResolver('Tag', $schema, new JunctionSchemas([])))->resolve(); - self::assertNotEmpty($tagModel->many2many); - $relation = $tagModel->many2many['posts']; - self::assertInstanceOf(ManyToManyRelation::class, $relation); - self::assertEquals('Post', $relation->relatedClassName); - self::assertEquals('Tag', $relation->className); - self::assertEquals('id', $relation->pkAttribute->propertyName); - self::assertEquals('posts2tags', $relation->getViaTableName()); - self::assertEquals(['id' => 'post_id'], $relation->getLink()); - self::assertEquals(['tag_id' => 'id'], $relation->getViaLink()); + $schema = new ComponentSchema($openApi->components->schemas['Tag'], 'Tag'); + $tagModel = (new AttributeResolver('Tag', $schema, new JunctionSchemas([])))->resolve(); + self::assertNotEmpty($tagModel->many2many); + $relation = $tagModel->many2many['posts']; + self::assertInstanceOf(ManyToManyRelation::class, $relation); + self::assertEquals('Post', $relation->relatedClassName); + self::assertEquals('Tag', $relation->className); + self::assertEquals('id', $relation->pkAttribute->propertyName); + self::assertEquals('posts2tags', $relation->getViaTableName()); + self::assertEquals(['id' => 'post_id'], $relation->getLink()); + self::assertEquals(['tag_id' => 'id'], $relation->getViaLink()); - } + } - /** - * @dataProvider dataProvider - * @param string $schemaName - * @param \cebe\openapi\spec\Schema $openApiSchema - * @param \cebe\yii2openapi\lib\items\DbModel $expected - */ - public function testResolve(string $schemaName, Schema $openApiSchema, DbModel $expected):void - { - $schema = new ComponentSchema($openApiSchema, $schemaName); - $resolver = new AttributeResolver($schemaName, $schema, new JunctionSchemas([])); - $model = $resolver->resolve(); - //echo $schemaName . PHP_EOL; - self::assertEquals($expected->name, $model->name); - self::assertEquals($expected->tableName, $model->tableName); - self::assertEquals($expected->description, $model->description); - self::assertEquals($expected->tableAlias, $model->tableAlias); - //VarDumper::dump($model->indexes); - self::assertEquals($expected->indexes, $model->indexes); - foreach ($model->relations as $name => $relation) { - self::assertTrue(isset($expected->relations[$name])); - self::assertEquals($expected->relations[$name], $relation); - } + /** + * @dataProvider dataProvider + * @param string $schemaName + * @param Schema $openApiSchema + * @param DbModel $expected + */ + public function testResolve(string $schemaName, Schema $openApiSchema, DbModel $expected): void + { + $schema = new ComponentSchema($openApiSchema, $schemaName); + $resolver = new AttributeResolver($schemaName, $schema, new JunctionSchemas([])); + $model = $resolver->resolve(); + //echo $schemaName . PHP_EOL; + self::assertEquals($expected->name, $model->name); + self::assertEquals($expected->tableName, $model->tableName); + self::assertEquals($expected->description, $model->description); + self::assertEquals($expected->tableAlias, $model->tableAlias); + //VarDumper::dump($model->indexes); + self::assertEquals($expected->indexes, $model->indexes); + foreach ($model->relations as $name => $relation) { + self::assertTrue(isset($expected->relations[$name])); + self::assertEquals($expected->relations[$name], $relation); + } - foreach ($model->attributes as $name => $attribute) { - $attribute->tableName = null; # just skip `tableName` from testing as of now - self::assertTrue(isset($expected->attributes[$name])); - self::assertEquals($expected->attributes[$name], $attribute); - } - } + foreach ($model->attributes as $name => $attribute) { + $attribute->tableName = null; # just skip `tableName` from testing as of now + self::assertTrue(isset($expected->attributes[$name])); + self::assertEquals($expected->attributes[$name], $attribute); + } + } - public function dataProvider():array - { - $schemaFile = Yii::getAlias("@specs/blog.yaml"); - $fixture = require Yii::getAlias('@fixtures/blog.php'); - $openApi = Reader::readFromYamlFile($schemaFile, OpenApi::class, false); - return [ - [ - 'User', - $openApi->components->schemas['User'], - $fixture['user'], - ], - [ - 'Category', - $openApi->components->schemas['Category'], - $fixture['category'], - ], - [ - 'Post', - $openApi->components->schemas['Post'], - $fixture['post'], - ], - [ - 'Comment', - $openApi->components->schemas['Comment'], - $fixture['comment'], - ], - ]; - } + public function dataProvider(): array + { + $schemaFile = Yii::getAlias("@specs/blog.yaml"); + $fixture = require Yii::getAlias('@fixtures/blog.php'); + $openApi = Reader::readFromYamlFile($schemaFile, OpenApi::class, false); + return [ + [ + 'User', + $openApi->components->schemas['User'], + $fixture['user'], + ], + [ + 'Category', + $openApi->components->schemas['Category'], + $fixture['category'], + ], + [ + 'Post', + $openApi->components->schemas['Post'], + $fixture['post'], + ], + [ + 'Comment', + $openApi->components->schemas['Comment'], + $fixture['comment'], + ], + ]; + } - public function testResolveRefNoObject() - { - $schemaFile = Yii::getAlias("@specs/ref_noobject.yaml"); - $openApi = Reader::readFromYamlFile($schemaFile, OpenApi::class, false); - $schema = new ComponentSchema($openApi->components->schemas['PersonWatch'], 'PersonWatch'); - $resolver = new AttributeResolver('PersonWatch', $schema, new JunctionSchemas([])); - $model = $resolver->resolve(); - $fixture = require Yii::getAlias('@fixtures/non-db.php'); - $testModel = $fixture['personWatch']; - self::assertEquals($testModel, $model); - } + public function testResolveRefNoObject() + { + $schemaFile = Yii::getAlias("@specs/ref_noobject.yaml"); + $openApi = Reader::readFromYamlFile($schemaFile, OpenApi::class, false); + $schema = new ComponentSchema($openApi->components->schemas['PersonWatch'], 'PersonWatch'); + $resolver = new AttributeResolver('PersonWatch', $schema, new JunctionSchemas([])); + $model = $resolver->resolve(); + $fixture = require Yii::getAlias('@fixtures/non-db.php'); + $testModel = $fixture['personWatch']; + self::assertEquals($testModel, $model); + } - public function testResolveNonDbModel() - { - $schemaFile = Yii::getAlias("@specs/petstore_jsonapi.yaml"); - $openApi = Reader::readFromYamlFile($schemaFile, OpenApi::class, false); - $schema = new ComponentSchema($openApi->components->schemas['PetStatistic'], 'PetStatistic'); - $resolver = new AttributeResolver('PetStatistic', $schema, new JunctionSchemas([])); - $model = $resolver->resolve(); - $fixture = require Yii::getAlias('@fixtures/non-db.php'); - $testModel = $fixture['PetStatistic']; - self::assertEquals($testModel, $model); - } + public function testResolveNonDbModel() + { + $schemaFile = Yii::getAlias("@specs/petstore_jsonapi.yaml"); + $openApi = Reader::readFromYamlFile($schemaFile, OpenApi::class, false); + $schema = new ComponentSchema($openApi->components->schemas['PetStatistic'], 'PetStatistic'); + $resolver = new AttributeResolver('PetStatistic', $schema, new JunctionSchemas([])); + $model = $resolver->resolve(); + $fixture = require Yii::getAlias('@fixtures/non-db.php'); + $testModel = $fixture['PetStatistic']; + self::assertEquals($testModel, $model); + } } From 29761255fecba33c30d662cbf42046187a4ead1c Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Wed, 26 Jun 2024 19:43:22 +0530 Subject: [PATCH 046/358] Fix style --- src/lib/AttributeResolver.php | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/src/lib/AttributeResolver.php b/src/lib/AttributeResolver.php index a5a344f5..9c0d2c92 100644 --- a/src/lib/AttributeResolver.php +++ b/src/lib/AttributeResolver.php @@ -213,9 +213,8 @@ protected function resolveHasMany2ManyTableProperty(PropertySchema $property, bo protected function resolveProperty( PropertySchema $property, bool $isRequired, - $nullableValue = 'ARG_ABSENT' - ): void - { + $nullableValue = 'ARG_ABSENT' + ): void { if ($nullableValue === 'ARG_ABSENT') { $nullableValue = $property->getProperty()->getSerializableData()->nullable ?? null; } @@ -375,8 +374,7 @@ protected function catchManyToMany( string $relatedSchemaName, string $relatedTableName, ComponentSchema $refSchema - ): bool - { + ): bool { if (strtolower(Inflector::id2camel($propertyName, '_')) !== strtolower(Inflector::pluralize($relatedSchemaName))) { return false; From 5ffbb338c5e57fe7fc7e610476dbb7c6cab6fca8 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Wed, 26 Jun 2024 20:11:53 +0530 Subject: [PATCH 047/358] Update README.md --- README.md | 5 ----- 1 file changed, 5 deletions(-) diff --git a/README.md b/README.md index c32d577e..a1b22067 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,5 @@ # yii2-openapi -> -> **This repository has been moved to .** -> **Please use the new package `php-openapi/yii2-openapi` instead.** -> - REST API application generator for Yii2, openapi 3.0 YAML -> Yii2. Base on [Gii, the Yii Framework Code Generator](https://www.yiiframework.com/extension/yiisoft/yii2-gii). From d8d8a90261ffc964efae75ae85cc9ff4c9ce5794 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Thu, 27 Jun 2024 16:31:11 +0530 Subject: [PATCH 048/358] Initial commit to create PR --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 1cd2090b..3bb79307 100644 --- a/README.md +++ b/README.md @@ -568,3 +568,4 @@ Professional support, consulting as well as software development services are av https://www.cebe.cc/en/contact Development of this library is sponsored by [cebe.:cloud: "Your Professional Deployment Platform"](https://cebe.cloud). + From f57ae6c0dde6b0d932f09c4f059340858f527282 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Thu, 27 Jun 2024 19:10:24 +0530 Subject: [PATCH 049/358] Add failing test --- README.md | 1 - .../index.php | 13 +++++++ .../index.yaml | 38 +++++++++++++++++++ tests/unit/IssueFixTest.php | 35 +++++++++++++++++ 4 files changed, 86 insertions(+), 1 deletion(-) create mode 100644 tests/specs/issue_fix/3_bug_add_remove_property_and_at_the_same_time_change_it_at_x_indexes/index.php create mode 100644 tests/specs/issue_fix/3_bug_add_remove_property_and_at_the_same_time_change_it_at_x_indexes/index.yaml diff --git a/README.md b/README.md index 3bb79307..1cd2090b 100644 --- a/README.md +++ b/README.md @@ -568,4 +568,3 @@ Professional support, consulting as well as software development services are av https://www.cebe.cc/en/contact Development of this library is sponsored by [cebe.:cloud: "Your Professional Deployment Platform"](https://cebe.cloud). - diff --git a/tests/specs/issue_fix/3_bug_add_remove_property_and_at_the_same_time_change_it_at_x_indexes/index.php b/tests/specs/issue_fix/3_bug_add_remove_property_and_at_the_same_time_change_it_at_x_indexes/index.php new file mode 100644 index 00000000..2dc7823c --- /dev/null +++ b/tests/specs/issue_fix/3_bug_add_remove_property_and_at_the_same_time_change_it_at_x_indexes/index.php @@ -0,0 +1,13 @@ + '@specs/issue_fix/3_bug_add_remove_property_and_at_the_same_time_change_it_at_x_indexes/index.yaml', + 'generateUrls' => false, + 'generateModels' => true, + 'excludeModels' => [ + 'Error', + ], + 'generateControllers' => false, + 'generateMigrations' => true, + 'generateModelFaker' => false, +]; diff --git a/tests/specs/issue_fix/3_bug_add_remove_property_and_at_the_same_time_change_it_at_x_indexes/index.yaml b/tests/specs/issue_fix/3_bug_add_remove_property_and_at_the_same_time_change_it_at_x_indexes/index.yaml new file mode 100644 index 00000000..3e1cc80c --- /dev/null +++ b/tests/specs/issue_fix/3_bug_add_remove_property_and_at_the_same_time_change_it_at_x_indexes/index.yaml @@ -0,0 +1,38 @@ +openapi: "3.0.0" +info: + version: 1.0.0 + title: 3_bug_add_remove_property_and_at_the_same_time_change_it_at_x_indexes +paths: + /: + get: + summary: List + operationId: list + responses: + '200': + description: The information + +components: + schemas: + Address: + type: object + description: desc + x-indexes: + - 'unique:shortName,postCode' + required: + - id + properties: + id: + type: integer + readOnly: true + + name: + type: string + maxLength: 64 + + shortName: + type: string + maxLength: 64 + + postCode: + type: string + maxLength: 64 diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index b6c7abdb..9630be6c 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -360,4 +360,39 @@ public function test158BugGiiapiGeneratedRulesEnumWithTrim() ]); $this->checkFiles($actualFiles, $expectedFiles); } + + // https://github.com/php-openapi/yii2-openapi/issues/3 + public function test3BugAddRemovePropertyAndAtTheSameTimeChangeItAtXIndexes() + { +// $this->changeDbToMariadb(); + $this->createTestTableFor3BugAddRemovePropertyAndAtTheSameTimeChangeItAtXIndexes(); + $testFile = Yii::getAlias("@specs/issue_fix/3_bug_add_remove_property_and_at_the_same_time_change_it_at_x_indexes/index.php"); + $this->runGenerator($testFile); + $this->runActualMigrations('mysql', 1); +// $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ +// 'recursive' => true, +// ]); +// $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/158_bug_giiapi_generated_rules_enum_with_trim/maria"), [ +// 'recursive' => true, +// ]); +// $this->checkFiles($actualFiles, $expectedFiles); + $this->dropTestTableFor3BugAddRemovePropertyAndAtTheSameTimeChangeItAtXIndexes(); + } + + private function createTestTableFor3BugAddRemovePropertyAndAtTheSameTimeChangeItAtXIndexes() + { + Yii::$app->db->createCommand()->createTable('{{%addresses}}', [ + 'id' => 'pk', + 'name' => 'varchar(64)', + 'shortName' => 'varchar(64)', + 'postalCode' => 'varchar(64)', + ])->execute(); + Yii::$app->db->createCommand()->createIndex('addresses_shortName_postalCode_key', '{{%addresses}}', ["shortName", "postalCode"], true)->execute(); + } + + private function dropTestTableFor3BugAddRemovePropertyAndAtTheSameTimeChangeItAtXIndexes() + { + Yii::$app->db->createCommand()->dropIndex('addresses_shortName_postalCode_key', '{{%addresses}}')->execute(); + Yii::$app->db->createCommand()->dropTable('{{%addresses}}')->execute(); + } } From 7cd81e891ecc0d4ebe34784a61849a35892e10ab Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Thu, 27 Jun 2024 19:11:01 +0530 Subject: [PATCH 050/358] Add potential fix --- src/lib/migrations/BaseMigrationBuilder.php | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/src/lib/migrations/BaseMigrationBuilder.php b/src/lib/migrations/BaseMigrationBuilder.php index d4c49c21..b5aa7515 100644 --- a/src/lib/migrations/BaseMigrationBuilder.php +++ b/src/lib/migrations/BaseMigrationBuilder.php @@ -198,7 +198,13 @@ function (string $unknownColumn) { ->addDownCode($builder->addPrimaryKey($tableName, $this->model->junctionCols)); } } + + if (!$relation) { + $this->buildIndexChanges(); + } + $this->buildColumnsDrop($columnsForDrop); + foreach ($columnsForChange as $commonColumn) { $current = $this->tableSchema->columns[$commonColumn]; $desired = $this->newColumns[$commonColumn]; @@ -212,14 +218,13 @@ function (string $unknownColumn) { } $this->buildColumnChanges($current, $desired, $changedAttributes); } - if (!$relation) { - $this->buildIndexChanges(); - } + if ($relation) { $this->buildRelationsForJunction($relation); } else { $this->buildRelations(); } + return $this->migration; } From f5f2d79f4f2acf106b6367ec8f5b90ef4a9ceeae Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Thu, 27 Jun 2024 20:38:38 +0530 Subject: [PATCH 051/358] Fix failing tests --- tests/DbTestCase.php | 2 +- .../m200000_000000_change_table_v2_posts.php | 4 ++-- .../m200000_000003_change_table_v2_categories.php | 8 ++++---- .../m200000_000004_change_table_v2_users.php | 12 ++++++------ .../m200000_000000_change_table_v2_posts.php | 4 ++-- .../m200000_000003_change_table_v2_categories.php | 8 ++++---- .../m200000_000004_change_table_v2_users.php | 12 ++++++------ .../m200000_000000_change_table_v2_posts.php | 4 ++-- .../m200000_000003_change_table_v2_categories.php | 6 +++--- .../m200000_000004_change_table_v2_users.php | 12 ++++++------ .../m200000_000000_change_table_v3_pgcustom.php | 2 +- 11 files changed, 37 insertions(+), 37 deletions(-) diff --git a/tests/DbTestCase.php b/tests/DbTestCase.php index ca7b17ff..877cf38e 100644 --- a/tests/DbTestCase.php +++ b/tests/DbTestCase.php @@ -167,8 +167,8 @@ protected function runUpMigrations(string $db = 'mysql', int $number = 2): void exec('cd tests; php -dxdebug.mode=develop ./yii migrate-'.$db.' --interactive=0', $upOutput, $upExitCode); $last = count($upOutput) - 1; $lastThird = count($upOutput) - 3; - $this->assertSame($upExitCode, 0); $this->assertSame($upOutput[$last], 'Migrated up successfully.'); + $this->assertSame($upExitCode, 0); $this->assertSame($upOutput[$lastThird], $number.' '.(($number === 1) ? 'migration was' : 'migrations were').' applied.'); // 1 migration was applied. // 2 migrations were applied. diff --git a/tests/specs/blog_v2/migrations_maria_db/m200000_000000_change_table_v2_posts.php b/tests/specs/blog_v2/migrations_maria_db/m200000_000000_change_table_v2_posts.php index 5c43dabf..5f50d0d7 100644 --- a/tests/specs/blog_v2/migrations_maria_db/m200000_000000_change_table_v2_posts.php +++ b/tests/specs/blog_v2/migrations_maria_db/m200000_000000_change_table_v2_posts.php @@ -9,20 +9,20 @@ public function up() { $this->addColumn('{{%v2_posts}}', 'id', $this->bigPrimaryKey()); $this->addColumn('{{%v2_posts}}', 'lang', 'enum("ru", "eng") NULL DEFAULT \'ru\' AFTER slug'); + $this->dropIndex('v2_posts_slug_key', '{{%v2_posts}}'); $this->dropColumn('{{%v2_posts}}', 'uid'); $this->alterColumn('{{%v2_posts}}', 'category_id', $this->bigInteger()->notNull()); $this->alterColumn('{{%v2_posts}}', 'active', $this->tinyInteger(1)->notNull()); $this->alterColumn('{{%v2_posts}}', 'created_by_id', $this->bigInteger()->null()->defaultValue(null)); - $this->dropIndex('v2_posts_slug_key', '{{%v2_posts}}'); } public function down() { - $this->createIndex('v2_posts_slug_key', '{{%v2_posts}}', 'slug', true); $this->alterColumn('{{%v2_posts}}', 'created_by_id', $this->integer(11)->null()->defaultValue(null)); $this->alterColumn('{{%v2_posts}}', 'active', $this->tinyInteger(1)->notNull()->defaultValue(0)); $this->alterColumn('{{%v2_posts}}', 'category_id', $this->integer(11)->notNull()); $this->addColumn('{{%v2_posts}}', 'uid', $this->bigInteger(20)->notNull()->first()); + $this->createIndex('v2_posts_slug_key', '{{%v2_posts}}', 'slug', true); $this->dropColumn('{{%v2_posts}}', 'lang'); $this->dropColumn('{{%v2_posts}}', 'id'); } diff --git a/tests/specs/blog_v2/migrations_maria_db/m200000_000003_change_table_v2_categories.php b/tests/specs/blog_v2/migrations_maria_db/m200000_000003_change_table_v2_categories.php index e608ed52..a91537a9 100644 --- a/tests/specs/blog_v2/migrations_maria_db/m200000_000003_change_table_v2_categories.php +++ b/tests/specs/blog_v2/migrations_maria_db/m200000_000003_change_table_v2_categories.php @@ -8,18 +8,18 @@ class m200000_000003_change_table_v2_categories extends \yii\db\Migration public function up() { $this->addColumn('{{%v2_categories}}', 'cover', $this->text()->notNull()->after('title')); - $this->alterColumn('{{%v2_categories}}', 'title', $this->string(100)->notNull()); - $this->alterColumn('{{%v2_categories}}', 'active', $this->tinyInteger(1)->notNull()); $this->dropIndex('v2_categories_title_key', '{{%v2_categories}}'); $this->createIndex('v2_categories_title_index', '{{%v2_categories}}', 'title', false); + $this->alterColumn('{{%v2_categories}}', 'title', $this->string(100)->notNull()); + $this->alterColumn('{{%v2_categories}}', 'active', $this->tinyInteger(1)->notNull()); } public function down() { - $this->dropIndex('v2_categories_title_index', '{{%v2_categories}}'); - $this->createIndex('v2_categories_title_key', '{{%v2_categories}}', 'title', true); $this->alterColumn('{{%v2_categories}}', 'active', $this->tinyInteger(1)->notNull()->defaultValue(0)); $this->alterColumn('{{%v2_categories}}', 'title', $this->string(255)->notNull()); + $this->dropIndex('v2_categories_title_index', '{{%v2_categories}}'); + $this->createIndex('v2_categories_title_key', '{{%v2_categories}}', 'title', true); $this->dropColumn('{{%v2_categories}}', 'cover'); } } diff --git a/tests/specs/blog_v2/migrations_maria_db/m200000_000004_change_table_v2_users.php b/tests/specs/blog_v2/migrations_maria_db/m200000_000004_change_table_v2_users.php index bf1c82fd..9f0f30f2 100644 --- a/tests/specs/blog_v2/migrations_maria_db/m200000_000004_change_table_v2_users.php +++ b/tests/specs/blog_v2/migrations_maria_db/m200000_000004_change_table_v2_users.php @@ -8,24 +8,24 @@ class m200000_000004_change_table_v2_users extends \yii\db\Migration public function up() { $this->addColumn('{{%v2_users}}', 'login', $this->text()->notNull()->after('id')); + $this->dropIndex('v2_users_username_key', '{{%v2_users}}'); + $this->createIndex('v2_users_login_key', '{{%v2_users}}', 'login', true); + $this->createIndex('v2_users_role_flags_hash_index', '{{%v2_users}}', ["role", "flags"], 'hash'); $this->dropColumn('{{%v2_users}}', 'username'); $this->alterColumn('{{%v2_users}}', 'email', $this->string(255)->notNull()); $this->alterColumn('{{%v2_users}}', 'role', 'enum("admin", "editor", "reader") NULL DEFAULT NULL'); $this->alterColumn('{{%v2_users}}', 'created_at', $this->timestamp()->null()->defaultValue(null)); - $this->dropIndex('v2_users_username_key', '{{%v2_users}}'); - $this->createIndex('v2_users_login_key', '{{%v2_users}}', 'login', true); - $this->createIndex('v2_users_role_flags_hash_index', '{{%v2_users}}', ["role", "flags"], 'hash'); } public function down() { - $this->dropIndex('v2_users_role_flags_hash_index', '{{%v2_users}}'); - $this->dropIndex('v2_users_login_key', '{{%v2_users}}'); - $this->createIndex('v2_users_username_key', '{{%v2_users}}', 'username', true); $this->alterColumn('{{%v2_users}}', 'created_at', $this->timestamp()->null()->defaultExpression("current_timestamp()")); $this->alterColumn('{{%v2_users}}', 'role', $this->string(20)->null()->defaultValue('reader')); $this->alterColumn('{{%v2_users}}', 'email', $this->string(200)->notNull()); $this->addColumn('{{%v2_users}}', 'username', $this->string(200)->notNull()); + $this->dropIndex('v2_users_role_flags_hash_index', '{{%v2_users}}'); + $this->dropIndex('v2_users_login_key', '{{%v2_users}}'); + $this->createIndex('v2_users_username_key', '{{%v2_users}}', 'username', true); $this->dropColumn('{{%v2_users}}', 'login'); } } diff --git a/tests/specs/blog_v2/migrations_mysql_db/m200000_000000_change_table_v2_posts.php b/tests/specs/blog_v2/migrations_mysql_db/m200000_000000_change_table_v2_posts.php index be309829..eea03cca 100644 --- a/tests/specs/blog_v2/migrations_mysql_db/m200000_000000_change_table_v2_posts.php +++ b/tests/specs/blog_v2/migrations_mysql_db/m200000_000000_change_table_v2_posts.php @@ -9,20 +9,20 @@ public function up() { $this->addColumn('{{%v2_posts}}', 'id', $this->bigPrimaryKey()); $this->addColumn('{{%v2_posts}}', 'lang', 'enum("ru", "eng") NULL DEFAULT \'ru\' AFTER slug'); + $this->dropIndex('v2_posts_slug_key', '{{%v2_posts}}'); $this->dropColumn('{{%v2_posts}}', 'uid'); $this->alterColumn('{{%v2_posts}}', 'category_id', $this->bigInteger()->notNull()); $this->alterColumn('{{%v2_posts}}', 'active', $this->tinyInteger(1)->notNull()); $this->alterColumn('{{%v2_posts}}', 'created_by_id', $this->bigInteger()->null()->defaultValue(null)); - $this->dropIndex('v2_posts_slug_key', '{{%v2_posts}}'); } public function down() { - $this->createIndex('v2_posts_slug_key', '{{%v2_posts}}', 'slug', true); $this->alterColumn('{{%v2_posts}}', 'created_by_id', $this->integer()->null()->defaultValue(null)); $this->alterColumn('{{%v2_posts}}', 'active', $this->tinyInteger(1)->notNull()->defaultValue(0)); $this->alterColumn('{{%v2_posts}}', 'category_id', $this->integer()->notNull()); $this->addColumn('{{%v2_posts}}', 'uid', $this->bigInteger()->notNull()->first()); + $this->createIndex('v2_posts_slug_key', '{{%v2_posts}}', 'slug', true); $this->dropColumn('{{%v2_posts}}', 'lang'); $this->dropColumn('{{%v2_posts}}', 'id'); } diff --git a/tests/specs/blog_v2/migrations_mysql_db/m200000_000003_change_table_v2_categories.php b/tests/specs/blog_v2/migrations_mysql_db/m200000_000003_change_table_v2_categories.php index e608ed52..a91537a9 100644 --- a/tests/specs/blog_v2/migrations_mysql_db/m200000_000003_change_table_v2_categories.php +++ b/tests/specs/blog_v2/migrations_mysql_db/m200000_000003_change_table_v2_categories.php @@ -8,18 +8,18 @@ class m200000_000003_change_table_v2_categories extends \yii\db\Migration public function up() { $this->addColumn('{{%v2_categories}}', 'cover', $this->text()->notNull()->after('title')); - $this->alterColumn('{{%v2_categories}}', 'title', $this->string(100)->notNull()); - $this->alterColumn('{{%v2_categories}}', 'active', $this->tinyInteger(1)->notNull()); $this->dropIndex('v2_categories_title_key', '{{%v2_categories}}'); $this->createIndex('v2_categories_title_index', '{{%v2_categories}}', 'title', false); + $this->alterColumn('{{%v2_categories}}', 'title', $this->string(100)->notNull()); + $this->alterColumn('{{%v2_categories}}', 'active', $this->tinyInteger(1)->notNull()); } public function down() { - $this->dropIndex('v2_categories_title_index', '{{%v2_categories}}'); - $this->createIndex('v2_categories_title_key', '{{%v2_categories}}', 'title', true); $this->alterColumn('{{%v2_categories}}', 'active', $this->tinyInteger(1)->notNull()->defaultValue(0)); $this->alterColumn('{{%v2_categories}}', 'title', $this->string(255)->notNull()); + $this->dropIndex('v2_categories_title_index', '{{%v2_categories}}'); + $this->createIndex('v2_categories_title_key', '{{%v2_categories}}', 'title', true); $this->dropColumn('{{%v2_categories}}', 'cover'); } } diff --git a/tests/specs/blog_v2/migrations_mysql_db/m200000_000004_change_table_v2_users.php b/tests/specs/blog_v2/migrations_mysql_db/m200000_000004_change_table_v2_users.php index b7a1f5e3..39ef65b2 100644 --- a/tests/specs/blog_v2/migrations_mysql_db/m200000_000004_change_table_v2_users.php +++ b/tests/specs/blog_v2/migrations_mysql_db/m200000_000004_change_table_v2_users.php @@ -8,24 +8,24 @@ class m200000_000004_change_table_v2_users extends \yii\db\Migration public function up() { $this->addColumn('{{%v2_users}}', 'login', $this->text()->notNull()->after('id')); + $this->dropIndex('v2_users_username_key', '{{%v2_users}}'); + $this->createIndex('v2_users_login_key', '{{%v2_users}}', 'login', true); + $this->createIndex('v2_users_role_flags_hash_index', '{{%v2_users}}', ["role", "flags"], 'hash'); $this->dropColumn('{{%v2_users}}', 'username'); $this->alterColumn('{{%v2_users}}', 'email', $this->string(255)->notNull()); $this->alterColumn('{{%v2_users}}', 'role', 'enum("admin", "editor", "reader") NULL DEFAULT NULL'); $this->alterColumn('{{%v2_users}}', 'created_at', $this->timestamp()->null()->defaultValue(null)); - $this->dropIndex('v2_users_username_key', '{{%v2_users}}'); - $this->createIndex('v2_users_login_key', '{{%v2_users}}', 'login', true); - $this->createIndex('v2_users_role_flags_hash_index', '{{%v2_users}}', ["role", "flags"], 'hash'); } public function down() { - $this->dropIndex('v2_users_role_flags_hash_index', '{{%v2_users}}'); - $this->dropIndex('v2_users_login_key', '{{%v2_users}}'); - $this->createIndex('v2_users_username_key', '{{%v2_users}}', 'username', true); $this->alterColumn('{{%v2_users}}', 'created_at', $this->timestamp()->null()->defaultExpression("CURRENT_TIMESTAMP")); $this->alterColumn('{{%v2_users}}', 'role', $this->string(20)->null()->defaultValue('reader')); $this->alterColumn('{{%v2_users}}', 'email', $this->string(200)->notNull()); $this->addColumn('{{%v2_users}}', 'username', $this->string(200)->notNull()); + $this->dropIndex('v2_users_role_flags_hash_index', '{{%v2_users}}'); + $this->dropIndex('v2_users_login_key', '{{%v2_users}}'); + $this->createIndex('v2_users_username_key', '{{%v2_users}}', 'username', true); $this->dropColumn('{{%v2_users}}', 'login'); } } diff --git a/tests/specs/blog_v2/migrations_pgsql_db/m200000_000000_change_table_v2_posts.php b/tests/specs/blog_v2/migrations_pgsql_db/m200000_000000_change_table_v2_posts.php index 5188983b..9444aef9 100644 --- a/tests/specs/blog_v2/migrations_pgsql_db/m200000_000000_change_table_v2_posts.php +++ b/tests/specs/blog_v2/migrations_pgsql_db/m200000_000000_change_table_v2_posts.php @@ -10,19 +10,19 @@ public function safeUp() $this->addColumn('{{%v2_posts}}', 'id', $this->bigPrimaryKey()); $this->execute('CREATE TYPE "enum_itt_v2_posts_lang" AS ENUM(\'ru\', \'eng\')'); $this->addColumn('{{%v2_posts}}', 'lang', '"enum_itt_v2_posts_lang" NULL DEFAULT \'ru\''); + $this->dropIndex('v2_posts_slug_key', '{{%v2_posts}}'); $this->dropColumn('{{%v2_posts}}', 'uid'); $this->alterColumn('{{%v2_posts}}', 'category_id', 'int8 NOT NULL USING "category_id"::int8'); $this->alterColumn('{{%v2_posts}}', 'active', "DROP DEFAULT"); $this->alterColumn('{{%v2_posts}}', 'created_by_id', 'int8 NULL USING "created_by_id"::int8'); - $this->dropIndex('v2_posts_slug_key', '{{%v2_posts}}'); } public function safeDown() { - $this->createIndex('v2_posts_slug_key', '{{%v2_posts}}', 'slug', true); $this->alterColumn('{{%v2_posts}}', 'created_by_id', 'int4 NULL USING "created_by_id"::int4'); $this->alterColumn('{{%v2_posts}}', 'category_id', 'int4 NOT NULL USING "category_id"::int4'); $this->addColumn('{{%v2_posts}}', 'uid', $this->bigInteger()->notNull()); + $this->createIndex('v2_posts_slug_key', '{{%v2_posts}}', 'slug', true); $this->dropColumn('{{%v2_posts}}', 'lang'); $this->dropColumn('{{%v2_posts}}', 'id'); $this->execute('DROP TYPE "enum_itt_v2_posts_lang"'); diff --git a/tests/specs/blog_v2/migrations_pgsql_db/m200000_000003_change_table_v2_categories.php b/tests/specs/blog_v2/migrations_pgsql_db/m200000_000003_change_table_v2_categories.php index 5f934936..d3958265 100644 --- a/tests/specs/blog_v2/migrations_pgsql_db/m200000_000003_change_table_v2_categories.php +++ b/tests/specs/blog_v2/migrations_pgsql_db/m200000_000003_change_table_v2_categories.php @@ -8,17 +8,17 @@ class m200000_000003_change_table_v2_categories extends \yii\db\Migration public function safeUp() { $this->addColumn('{{%v2_categories}}', 'cover', $this->text()->notNull()); - $this->alterColumn('{{%v2_categories}}', 'title', $this->string(100)->notNull()); - $this->alterColumn('{{%v2_categories}}', 'active', "DROP DEFAULT"); $this->dropIndex('v2_categories_title_key', '{{%v2_categories}}'); $this->createIndex('v2_categories_title_index', '{{%v2_categories}}', 'title', false); + $this->alterColumn('{{%v2_categories}}', 'title', $this->string(100)->notNull()); + $this->alterColumn('{{%v2_categories}}', 'active', "DROP DEFAULT"); } public function safeDown() { + $this->alterColumn('{{%v2_categories}}', 'title', $this->string(255)->notNull()); $this->dropIndex('v2_categories_title_index', '{{%v2_categories}}'); $this->createIndex('v2_categories_title_key', '{{%v2_categories}}', 'title', true); - $this->alterColumn('{{%v2_categories}}', 'title', $this->string(255)->notNull()); $this->dropColumn('{{%v2_categories}}', 'cover'); $this->alterColumn('{{%v2_categories}}', 'active', "SET DEFAULT 'f'"); } diff --git a/tests/specs/blog_v2/migrations_pgsql_db/m200000_000004_change_table_v2_users.php b/tests/specs/blog_v2/migrations_pgsql_db/m200000_000004_change_table_v2_users.php index a57ea8df..e8847b2d 100644 --- a/tests/specs/blog_v2/migrations_pgsql_db/m200000_000004_change_table_v2_users.php +++ b/tests/specs/blog_v2/migrations_pgsql_db/m200000_000004_change_table_v2_users.php @@ -9,24 +9,24 @@ public function safeUp() { $this->execute('CREATE TYPE "enum_itt_v2_users_role" AS ENUM(\'admin\', \'editor\', \'reader\')'); $this->addColumn('{{%v2_users}}', 'login', $this->text()->notNull()); + $this->dropIndex('v2_users_username_key', '{{%v2_users}}'); + $this->createIndex('v2_users_login_key', '{{%v2_users}}', 'login', true); + $this->createIndex('v2_users_role_flags_hash_index', '{{%v2_users}}', ["role", "flags"], 'hash'); $this->dropColumn('{{%v2_users}}', 'username'); $this->db->createCommand('ALTER TABLE {{%v2_users}} ALTER COLUMN "email" SET DATA TYPE varchar(255)')->execute(); $this->alterColumn('{{%v2_users}}', 'role', '"enum_itt_v2_users_role" USING "role"::"enum_itt_v2_users_role"'); $this->alterColumn('{{%v2_users}}', 'role', "DROP DEFAULT"); $this->alterColumn('{{%v2_users}}', 'created_at', "DROP DEFAULT"); - $this->dropIndex('v2_users_username_key', '{{%v2_users}}'); - $this->createIndex('v2_users_login_key', '{{%v2_users}}', 'login', true); - $this->createIndex('v2_users_role_flags_hash_index', '{{%v2_users}}', ["role", "flags"], 'hash'); } public function safeDown() { - $this->dropIndex('v2_users_role_flags_hash_index', '{{%v2_users}}'); - $this->dropIndex('v2_users_login_key', '{{%v2_users}}'); - $this->createIndex('v2_users_username_key', '{{%v2_users}}', 'username', true); $this->alterColumn('{{%v2_users}}', 'role', 'varchar(20) NULL USING "role"::varchar'); $this->alterColumn('{{%v2_users}}', 'email', $this->string(200)->notNull()); $this->addColumn('{{%v2_users}}', 'username', $this->string(200)->notNull()); + $this->dropIndex('v2_users_role_flags_hash_index', '{{%v2_users}}'); + $this->dropIndex('v2_users_login_key', '{{%v2_users}}'); + $this->createIndex('v2_users_username_key', '{{%v2_users}}', 'username', true); $this->dropColumn('{{%v2_users}}', 'login'); $this->alterColumn('{{%v2_users}}', 'role', "SET DEFAULT 'reader'"); $this->execute('DROP TYPE "enum_itt_v2_users_role"'); diff --git a/tests/specs/postgres_custom/migrations_pgsql_db/m200000_000000_change_table_v3_pgcustom.php b/tests/specs/postgres_custom/migrations_pgsql_db/m200000_000000_change_table_v3_pgcustom.php index a1ffe61a..70a540b3 100644 --- a/tests/specs/postgres_custom/migrations_pgsql_db/m200000_000000_change_table_v3_pgcustom.php +++ b/tests/specs/postgres_custom/migrations_pgsql_db/m200000_000000_change_table_v3_pgcustom.php @@ -7,6 +7,7 @@ class m200000_000000_change_table_v3_pgcustom extends \yii\db\Migration { public function safeUp() { + $this->createIndex('v3_pgcustom_search_gin_index', '{{%v3_pgcustom}}', 'search', 'gin(to_tsvector(\'english\', status))'); $this->alterColumn('{{%v3_pgcustom}}', 'json1', "SET NOT NULL"); $this->alterColumn('{{%v3_pgcustom}}', 'json1', "SET DEFAULT '[]'"); $this->alterColumn('{{%v3_pgcustom}}', 'json2', "SET NOT NULL"); @@ -17,7 +18,6 @@ public function safeUp() $this->alterColumn('{{%v3_pgcustom}}', 'json4', "SET DEFAULT '{\"foo\":\"bar\",\"bar\":\"baz\"}'"); $this->alterColumn('{{%v3_pgcustom}}', 'status', "SET DEFAULT 'draft'"); $this->alterColumn('{{%v3_pgcustom}}', 'status_x', "SET DEFAULT 'draft'"); - $this->createIndex('v3_pgcustom_search_gin_index', '{{%v3_pgcustom}}', 'search', 'gin(to_tsvector(\'english\', status))'); } public function safeDown() From a67e14afba8e34846cfe8f3fa93ad73e33bb66e0 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Thu, 27 Jun 2024 20:43:25 +0530 Subject: [PATCH 052/358] Compare files in test --- .../m200000_000000_change_table_addresses.php | 23 +++++++++++++ .../mysql/models/Address.php | 10 ++++++ .../mysql/models/base/Address.php | 34 +++++++++++++++++++ tests/unit/IssueFixTest.php | 15 ++++---- 4 files changed, 74 insertions(+), 8 deletions(-) create mode 100644 tests/specs/issue_fix/3_bug_add_remove_property_and_at_the_same_time_change_it_at_x_indexes/mysql/migrations_mysql_db/m200000_000000_change_table_addresses.php create mode 100644 tests/specs/issue_fix/3_bug_add_remove_property_and_at_the_same_time_change_it_at_x_indexes/mysql/models/Address.php create mode 100644 tests/specs/issue_fix/3_bug_add_remove_property_and_at_the_same_time_change_it_at_x_indexes/mysql/models/base/Address.php diff --git a/tests/specs/issue_fix/3_bug_add_remove_property_and_at_the_same_time_change_it_at_x_indexes/mysql/migrations_mysql_db/m200000_000000_change_table_addresses.php b/tests/specs/issue_fix/3_bug_add_remove_property_and_at_the_same_time_change_it_at_x_indexes/mysql/migrations_mysql_db/m200000_000000_change_table_addresses.php new file mode 100644 index 00000000..d86cdcc9 --- /dev/null +++ b/tests/specs/issue_fix/3_bug_add_remove_property_and_at_the_same_time_change_it_at_x_indexes/mysql/migrations_mysql_db/m200000_000000_change_table_addresses.php @@ -0,0 +1,23 @@ +addColumn('{{%addresses}}', 'postCode', $this->string(64)->null()->defaultValue(null)); + $this->dropIndex('addresses_shortName_postalCode_key', '{{%addresses}}'); + $this->createIndex('addresses_shortName_postCode_key', '{{%addresses}}', ["shortName", "postCode"], true); + $this->dropColumn('{{%addresses}}', 'postalCode'); + } + + public function down() + { + $this->addColumn('{{%addresses}}', 'postalCode', $this->string(64)->null()->defaultValue(null)); + $this->dropIndex('addresses_shortName_postCode_key', '{{%addresses}}'); + $this->createIndex('addresses_shortName_postalCode_key', '{{%addresses}}', ["shortName", "postalCode"], true); + $this->dropColumn('{{%addresses}}', 'postCode'); + } +} diff --git a/tests/specs/issue_fix/3_bug_add_remove_property_and_at_the_same_time_change_it_at_x_indexes/mysql/models/Address.php b/tests/specs/issue_fix/3_bug_add_remove_property_and_at_the_same_time_change_it_at_x_indexes/mysql/models/Address.php new file mode 100644 index 00000000..abfd7d59 --- /dev/null +++ b/tests/specs/issue_fix/3_bug_add_remove_property_and_at_the_same_time_change_it_at_x_indexes/mysql/models/Address.php @@ -0,0 +1,10 @@ + [['name', 'shortName', 'postCode'], 'trim'], + 'shortName_postCode_unique' => [['shortName', 'postCode'], 'unique', 'targetAttribute' => [ + 'shortName', + 'postCode', + ]], + 'name_string' => [['name'], 'string', 'max' => 64], + 'shortName_string' => [['shortName'], 'string', 'max' => 64], + 'postCode_string' => [['postCode'], 'string', 'max' => 64], + ]; + } +} diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index 9630be6c..7036f51b 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -364,18 +364,17 @@ public function test158BugGiiapiGeneratedRulesEnumWithTrim() // https://github.com/php-openapi/yii2-openapi/issues/3 public function test3BugAddRemovePropertyAndAtTheSameTimeChangeItAtXIndexes() { -// $this->changeDbToMariadb(); $this->createTestTableFor3BugAddRemovePropertyAndAtTheSameTimeChangeItAtXIndexes(); $testFile = Yii::getAlias("@specs/issue_fix/3_bug_add_remove_property_and_at_the_same_time_change_it_at_x_indexes/index.php"); $this->runGenerator($testFile); $this->runActualMigrations('mysql', 1); -// $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ -// 'recursive' => true, -// ]); -// $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/158_bug_giiapi_generated_rules_enum_with_trim/maria"), [ -// 'recursive' => true, -// ]); -// $this->checkFiles($actualFiles, $expectedFiles); + $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ + 'recursive' => true, + ]); + $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/3_bug_add_remove_property_and_at_the_same_time_change_it_at_x_indexes/mysql"), [ + 'recursive' => true, + ]); + $this->checkFiles($actualFiles, $expectedFiles); $this->dropTestTableFor3BugAddRemovePropertyAndAtTheSameTimeChangeItAtXIndexes(); } From 4ee32a5b59d82a5d941d33928b185b404c3dc0ad Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Fri, 28 Jun 2024 16:17:19 +0530 Subject: [PATCH 053/358] Initial commit to create PR --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 1cd2090b..3bb79307 100644 --- a/README.md +++ b/README.md @@ -568,3 +568,4 @@ Professional support, consulting as well as software development services are av https://www.cebe.cc/en/contact Development of this library is sponsored by [cebe.:cloud: "Your Professional Deployment Platform"](https://cebe.cloud). + From 02b8c231b45ea8286b6de03eec447b06683ba1ac Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Fri, 28 Jun 2024 16:24:13 +0530 Subject: [PATCH 054/358] Initial commit to create PR --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 1cd2090b..3bb79307 100644 --- a/README.md +++ b/README.md @@ -568,3 +568,4 @@ Professional support, consulting as well as software development services are av https://www.cebe.cc/en/contact Development of this library is sponsored by [cebe.:cloud: "Your Professional Deployment Platform"](https://cebe.cloud). + From 2498abef0d67ca445cfb42b052b44daec33b213a Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Fri, 28 Jun 2024 16:56:04 +0530 Subject: [PATCH 055/358] Add docs --- CONTRIBUTING.md | 8 ++++++++ README.md | 1 - 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index e1a62b7d..cc3ace96 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -95,6 +95,14 @@ with Zend OPcache v7.4.27, Copyright (c), by Zend Technologies with Xdebug v2.9.6, Copyright (c) 2002-2020, by Derick Rethans ``` +If a PHP version is changed as mentioned above, then following operations must be performed: + +``` +rm -rf vendor +rm -rf composer.lock +composer install +``` + Issues and solutions -------------------- diff --git a/README.md b/README.md index 3bb79307..1cd2090b 100644 --- a/README.md +++ b/README.md @@ -568,4 +568,3 @@ Professional support, consulting as well as software development services are av https://www.cebe.cc/en/contact Development of this library is sponsored by [cebe.:cloud: "Your Professional Deployment Platform"](https://cebe.cloud). - From eeb7a7216b87252d38a94b3309dfc1d7d51f7f01 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Mon, 1 Jul 2024 20:42:27 +0530 Subject: [PATCH 056/358] Fix main part of this issue --- README.md | 1 - src/lib/AttributeResolver.php | 4 +++- tests/specs/postgres_custom.yaml | 2 +- .../m200000_000000_change_table_v3_pgcustom.php | 2 +- tests/unit/MultiDbSecondaryMigrationTest.php | 1 + 5 files changed, 6 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 3bb79307..1cd2090b 100644 --- a/README.md +++ b/README.md @@ -568,4 +568,3 @@ Professional support, consulting as well as software development services are av https://www.cebe.cc/en/contact Development of this library is sponsored by [cebe.:cloud: "Your Professional Deployment Platform"](https://cebe.cloud). - diff --git a/src/lib/AttributeResolver.php b/src/lib/AttributeResolver.php index 0063d8df..aca8b1a9 100644 --- a/src/lib/AttributeResolver.php +++ b/src/lib/AttributeResolver.php @@ -425,7 +425,9 @@ protected function prepareIndexes(array $indexes):array foreach ($indexes as $index) { $unique = false; if (strpos($index, ':') !== false) { - [$indexType, $props] = explode(':', $index); + $props = strrchr($index, ':'); + $props = substr($props, 1); + $indexType = str_replace(':'.$props, '', $index); } else { $props = $index; $indexType = null; diff --git a/tests/specs/postgres_custom.yaml b/tests/specs/postgres_custom.yaml index e3d9a810..d6137a3d 100644 --- a/tests/specs/postgres_custom.yaml +++ b/tests/specs/postgres_custom.yaml @@ -35,7 +35,7 @@ components: Custom: x-table: v3_pgcustom x-indexes: - - "gin(to_tsvector('english', status)):search" + - "gin(to_tsvector('english', search::text)):search" required: - id properties: diff --git a/tests/specs/postgres_custom/migrations_pgsql_db/m200000_000000_change_table_v3_pgcustom.php b/tests/specs/postgres_custom/migrations_pgsql_db/m200000_000000_change_table_v3_pgcustom.php index a1ffe61a..6d1badd0 100644 --- a/tests/specs/postgres_custom/migrations_pgsql_db/m200000_000000_change_table_v3_pgcustom.php +++ b/tests/specs/postgres_custom/migrations_pgsql_db/m200000_000000_change_table_v3_pgcustom.php @@ -17,7 +17,7 @@ public function safeUp() $this->alterColumn('{{%v3_pgcustom}}', 'json4', "SET DEFAULT '{\"foo\":\"bar\",\"bar\":\"baz\"}'"); $this->alterColumn('{{%v3_pgcustom}}', 'status', "SET DEFAULT 'draft'"); $this->alterColumn('{{%v3_pgcustom}}', 'status_x', "SET DEFAULT 'draft'"); - $this->createIndex('v3_pgcustom_search_gin_index', '{{%v3_pgcustom}}', 'search', 'gin(to_tsvector(\'english\', status))'); + $this->createIndex('v3_pgcustom_search_gin_index', '{{%v3_pgcustom}}', 'search', 'gin(to_tsvector(\'english\', search::text))'); } public function safeDown() diff --git a/tests/unit/MultiDbSecondaryMigrationTest.php b/tests/unit/MultiDbSecondaryMigrationTest.php index f20b3e93..cc3d90cb 100644 --- a/tests/unit/MultiDbSecondaryMigrationTest.php +++ b/tests/unit/MultiDbSecondaryMigrationTest.php @@ -22,6 +22,7 @@ public function testPostgresCustom() $this->assertInstanceOf(PgSqlSchema::class, Yii::$app->db->schema); $testFile = Yii::getAlias('@specs/postgres_custom.php'); $this->runGenerator($testFile, $dbName); + $this->runActualMigrations('pgsql', 1); $expectedFiles = $this->findExpectedFiles($testFile, $dbName); $actualFiles = $this->findActualFiles(); $this->assertEquals($expectedFiles, $actualFiles); From 25c2e5f5e6a5aed974323fa584e57ca4a46fd201 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Tue, 2 Jul 2024 19:24:31 +0530 Subject: [PATCH 057/358] WIP --- src/lib/AttributeResolver.php | 8 +++++--- src/lib/migrations/MigrationRecordBuilder.php | 2 +- tests/unit/MultiDbSecondaryMigrationTest.php | 2 +- 3 files changed, 7 insertions(+), 5 deletions(-) diff --git a/src/lib/AttributeResolver.php b/src/lib/AttributeResolver.php index aca8b1a9..cba2bbdd 100644 --- a/src/lib/AttributeResolver.php +++ b/src/lib/AttributeResolver.php @@ -425,9 +425,11 @@ protected function prepareIndexes(array $indexes):array foreach ($indexes as $index) { $unique = false; if (strpos($index, ':') !== false) { - $props = strrchr($index, ':'); - $props = substr($props, 1); - $indexType = str_replace(':'.$props, '', $index); + // [$indexType, $props] = explode(':', $index); + // if `$index` is `gin(to_tsvector('english', search::text)):search,prop2` + $props = strrchr($index, ':'); # `$props` is now `:search,prop2` + $props = substr($props, 1); # search,prop2 + $indexType = str_replace(':'.$props, '', $index); # `gin(to_tsvector('english', search::text))` } else { $props = $index; $indexType = null; diff --git a/src/lib/migrations/MigrationRecordBuilder.php b/src/lib/migrations/MigrationRecordBuilder.php index 98ee03b8..e12f5d72 100644 --- a/src/lib/migrations/MigrationRecordBuilder.php +++ b/src/lib/migrations/MigrationRecordBuilder.php @@ -246,7 +246,7 @@ public function addIndex(string $tableAlias, string $indexName, array $columns, self::ADD_INDEX, $indexName, $tableAlias, - count($columns) === 1 ? "'{$columns[0]}'" : '["'.implode('", "', $columns).'"]', + count($columns) === 1 ? "'". ColumnToCode::escapeQuotes($columns[0])."'" : '["'.implode('", "', $columns).'"]', $indexType ); } diff --git a/tests/unit/MultiDbSecondaryMigrationTest.php b/tests/unit/MultiDbSecondaryMigrationTest.php index cc3d90cb..8ae94374 100644 --- a/tests/unit/MultiDbSecondaryMigrationTest.php +++ b/tests/unit/MultiDbSecondaryMigrationTest.php @@ -22,7 +22,7 @@ public function testPostgresCustom() $this->assertInstanceOf(PgSqlSchema::class, Yii::$app->db->schema); $testFile = Yii::getAlias('@specs/postgres_custom.php'); $this->runGenerator($testFile, $dbName); - $this->runActualMigrations('pgsql', 1); +// $this->runActualMigrations('pgsql', 1); $expectedFiles = $this->findExpectedFiles($testFile, $dbName); $actualFiles = $this->findActualFiles(); $this->assertEquals($expectedFiles, $actualFiles); From 4ddf375ceb60f69156fdaa8e406eeaf43bc41f60 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Tue, 2 Jul 2024 21:03:30 +0530 Subject: [PATCH 058/358] Fix bug --- src/lib/AttributeResolver.php | 2 +- src/lib/migrations/MigrationRecordBuilder.php | 11 ++++++++++- .../m200000_000000_change_table_v3_pgcustom.php | 2 +- tests/unit/MultiDbSecondaryMigrationTest.php | 2 +- 4 files changed, 13 insertions(+), 4 deletions(-) diff --git a/src/lib/AttributeResolver.php b/src/lib/AttributeResolver.php index cba2bbdd..3a6374a2 100644 --- a/src/lib/AttributeResolver.php +++ b/src/lib/AttributeResolver.php @@ -434,7 +434,7 @@ protected function prepareIndexes(array $indexes):array $props = $index; $indexType = null; } - if ($indexType === 'unique') { + if (strtolower($indexType) === 'unique') { $indexType = null; $unique = true; } diff --git a/src/lib/migrations/MigrationRecordBuilder.php b/src/lib/migrations/MigrationRecordBuilder.php index e12f5d72..886658bd 100644 --- a/src/lib/migrations/MigrationRecordBuilder.php +++ b/src/lib/migrations/MigrationRecordBuilder.php @@ -227,6 +227,7 @@ public function addFk(string $fkName, string $tableAlias, string $fkCol, string $onUpdate ); } + throw new \Exception('Cannot add foreign key'); } public function addUniqueIndex(string $tableAlias, string $indexName, array $columns):string @@ -242,11 +243,19 @@ public function addUniqueIndex(string $tableAlias, string $indexName, array $col public function addIndex(string $tableAlias, string $indexName, array $columns, ?string $using = null):string { $indexType = $using === null ? 'false' : "'".ColumnToCode::escapeQuotes($using)."'"; + + if (ApiGenerator::isPostgres() && $using && stripos($using, '(') !== false) { + $r = explode('(', $using, 2); + $indexType = "'".$r[0]."'"; # `gin` + $columnDbIndexExpression = substr($r[1], 0, -1); # to_tsvector('english', search::text) + $columns = [ColumnToCode::escapeQuotes($columnDbIndexExpression)]; + } + return sprintf( self::ADD_INDEX, $indexName, $tableAlias, - count($columns) === 1 ? "'". ColumnToCode::escapeQuotes($columns[0])."'" : '["'.implode('", "', $columns).'"]', + count($columns) === 1 ? "'". $columns[0]."'" : '["'.implode('", "', $columns).'"]', $indexType ); } diff --git a/tests/specs/postgres_custom/migrations_pgsql_db/m200000_000000_change_table_v3_pgcustom.php b/tests/specs/postgres_custom/migrations_pgsql_db/m200000_000000_change_table_v3_pgcustom.php index 6d1badd0..37cb7765 100644 --- a/tests/specs/postgres_custom/migrations_pgsql_db/m200000_000000_change_table_v3_pgcustom.php +++ b/tests/specs/postgres_custom/migrations_pgsql_db/m200000_000000_change_table_v3_pgcustom.php @@ -17,7 +17,7 @@ public function safeUp() $this->alterColumn('{{%v3_pgcustom}}', 'json4', "SET DEFAULT '{\"foo\":\"bar\",\"bar\":\"baz\"}'"); $this->alterColumn('{{%v3_pgcustom}}', 'status', "SET DEFAULT 'draft'"); $this->alterColumn('{{%v3_pgcustom}}', 'status_x', "SET DEFAULT 'draft'"); - $this->createIndex('v3_pgcustom_search_gin_index', '{{%v3_pgcustom}}', 'search', 'gin(to_tsvector(\'english\', search::text))'); + $this->createIndex('v3_pgcustom_search_gin_index', '{{%v3_pgcustom}}', 'to_tsvector(\'english\', search::text)', 'gin'); } public function safeDown() diff --git a/tests/unit/MultiDbSecondaryMigrationTest.php b/tests/unit/MultiDbSecondaryMigrationTest.php index 8ae94374..cc3d90cb 100644 --- a/tests/unit/MultiDbSecondaryMigrationTest.php +++ b/tests/unit/MultiDbSecondaryMigrationTest.php @@ -22,7 +22,7 @@ public function testPostgresCustom() $this->assertInstanceOf(PgSqlSchema::class, Yii::$app->db->schema); $testFile = Yii::getAlias('@specs/postgres_custom.php'); $this->runGenerator($testFile, $dbName); -// $this->runActualMigrations('pgsql', 1); + $this->runActualMigrations('pgsql', 1); $expectedFiles = $this->findExpectedFiles($testFile, $dbName); $actualFiles = $this->findActualFiles(); $this->assertEquals($expectedFiles, $actualFiles); From b66fe48599bb93dc2d8de816ab6feaeaecfefacd Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Tue, 2 Jul 2024 21:13:19 +0530 Subject: [PATCH 059/358] Add docs --- README.md | 8 ++++++++ src/lib/migrations/MigrationRecordBuilder.php | 1 + 2 files changed, 9 insertions(+) diff --git a/README.md b/README.md index 1cd2090b..7fec4f9e 100644 --- a/README.md +++ b/README.md @@ -212,6 +212,14 @@ Specify table indexes default: '{}' ``` +If raw DB expression is needed in index, then it must be for only one column. Example: + +```yaml + x-indexes: + - "gin(to_tsvector('english', search::text)):search" # valid + - "gin(to_tsvector('english', search::text)):search,column2" # invalid +``` + ### `x-db-default-expression` Ability to provide default value by database expression diff --git a/src/lib/migrations/MigrationRecordBuilder.php b/src/lib/migrations/MigrationRecordBuilder.php index 886658bd..0251be3a 100644 --- a/src/lib/migrations/MigrationRecordBuilder.php +++ b/src/lib/migrations/MigrationRecordBuilder.php @@ -245,6 +245,7 @@ public function addIndex(string $tableAlias, string $indexName, array $columns, $indexType = $using === null ? 'false' : "'".ColumnToCode::escapeQuotes($using)."'"; if (ApiGenerator::isPostgres() && $using && stripos($using, '(') !== false) { + // if `$using` is `gin(to_tsvector('english', search::text))` $r = explode('(', $using, 2); $indexType = "'".$r[0]."'"; # `gin` $columnDbIndexExpression = substr($r[1], 0, -1); # to_tsvector('english', search::text) From 1adc170a10c58ef58c7c0d673fd1fe8d645912da Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Tue, 2 Jul 2024 21:19:43 +0530 Subject: [PATCH 060/358] Fix failing test --- src/lib/AttributeResolver.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/lib/AttributeResolver.php b/src/lib/AttributeResolver.php index 3a6374a2..79ff91f6 100644 --- a/src/lib/AttributeResolver.php +++ b/src/lib/AttributeResolver.php @@ -434,7 +434,7 @@ protected function prepareIndexes(array $indexes):array $props = $index; $indexType = null; } - if (strtolower($indexType) === 'unique') { + if (strtolower((string) $indexType) === 'unique') { $indexType = null; $unique = true; } From e934a3dd9e21b3ffdd7292d5f78942d2cc05ec64 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Wed, 3 Jul 2024 18:12:19 +0530 Subject: [PATCH 061/358] Run actual generated migrations in tests --- src/lib/migrations/MigrationRecordBuilder.php | 2 +- tests/unit/MultiDbFreshMigrationTest.php | 3 +++ tests/unit/MultiDbSecondaryMigrationTest.php | 3 ++- 3 files changed, 6 insertions(+), 2 deletions(-) diff --git a/src/lib/migrations/MigrationRecordBuilder.php b/src/lib/migrations/MigrationRecordBuilder.php index 0251be3a..1d4b0ed0 100644 --- a/src/lib/migrations/MigrationRecordBuilder.php +++ b/src/lib/migrations/MigrationRecordBuilder.php @@ -244,7 +244,7 @@ public function addIndex(string $tableAlias, string $indexName, array $columns, { $indexType = $using === null ? 'false' : "'".ColumnToCode::escapeQuotes($using)."'"; - if (ApiGenerator::isPostgres() && $using && stripos($using, '(') !== false) { + if ($using && (stripos($using, '(') !== false) && ApiGenerator::isPostgres()) { // if `$using` is `gin(to_tsvector('english', search::text))` $r = explode('(', $using, 2); $indexType = "'".$r[0]."'"; # `gin` diff --git a/tests/unit/MultiDbFreshMigrationTest.php b/tests/unit/MultiDbFreshMigrationTest.php index 366bfb0b..f2495903 100644 --- a/tests/unit/MultiDbFreshMigrationTest.php +++ b/tests/unit/MultiDbFreshMigrationTest.php @@ -26,6 +26,7 @@ public function testMaria() $this->assertInstanceOf(MySqlSchema::class, Yii::$app->db->schema); $testFile = Yii::getAlias('@specs/blog.php'); $this->runGenerator($testFile, $dbName); + $this->runActualMigrations($dbName, 5); $expectedFiles = $this->findExpectedFiles($testFile, $dbName); $actualFiles = $this->findActualFiles(); $this->assertEquals($expectedFiles, $actualFiles); @@ -39,6 +40,7 @@ public function testPostgres() $this->assertInstanceOf(PgSqlSchema::class, Yii::$app->db->schema); $testFile = Yii::getAlias('@specs/blog.php'); $this->runGenerator($testFile, $dbName); + $this->runActualMigrations($dbName, 5); $expectedFiles = $this->findExpectedFiles($testFile, $dbName); $actualFiles = $this->findActualFiles(); $this->assertEquals($expectedFiles, $actualFiles); @@ -52,6 +54,7 @@ public function testMysql() $this->assertInstanceOf(MySqlSchema::class, Yii::$app->db->schema); $testFile = Yii::getAlias('@specs/blog.php'); $this->runGenerator($testFile, $dbName); + $this->runActualMigrations($dbName, 5); $expectedFiles = $this->findExpectedFiles($testFile, $dbName); $actualFiles = $this->findActualFiles(); $this->assertEquals($expectedFiles, $actualFiles); diff --git a/tests/unit/MultiDbSecondaryMigrationTest.php b/tests/unit/MultiDbSecondaryMigrationTest.php index cc3d90cb..36f9179c 100644 --- a/tests/unit/MultiDbSecondaryMigrationTest.php +++ b/tests/unit/MultiDbSecondaryMigrationTest.php @@ -22,7 +22,7 @@ public function testPostgresCustom() $this->assertInstanceOf(PgSqlSchema::class, Yii::$app->db->schema); $testFile = Yii::getAlias('@specs/postgres_custom.php'); $this->runGenerator($testFile, $dbName); - $this->runActualMigrations('pgsql', 1); + $this->runActualMigrations($dbName, 1); $expectedFiles = $this->findExpectedFiles($testFile, $dbName); $actualFiles = $this->findActualFiles(); $this->assertEquals($expectedFiles, $actualFiles); @@ -36,6 +36,7 @@ public function testMaria() $this->assertInstanceOf(MySqlSchema::class, Yii::$app->db->schema); $testFile = Yii::getAlias('@specs/blog_v2.php'); $this->runGenerator($testFile, $dbName); +// $this->runActualMigrations($dbName, 6); since PK is changed, no need to run actual migrations here $expectedFiles = $this->findExpectedFiles($testFile, $dbName); $actualFiles = $this->findActualFiles(); $this->assertEquals($expectedFiles, $actualFiles); From 3d2f9958cff523e2f3c5722204d1b7fa221d46ef Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Thu, 4 Jul 2024 17:12:27 +0530 Subject: [PATCH 062/358] Initial commit to create PR --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 1cd2090b..3bb79307 100644 --- a/README.md +++ b/README.md @@ -568,3 +568,4 @@ Professional support, consulting as well as software development services are av https://www.cebe.cc/en/contact Development of this library is sponsored by [cebe.:cloud: "Your Professional Deployment Platform"](https://cebe.cloud). + From dbcf4a98471a8093436272951672cd3727a51bc6 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Thu, 4 Jul 2024 19:16:42 +0530 Subject: [PATCH 063/358] WIP --- README.md | 3 +-- src/lib/ColumnToCode.php | 5 ++++- src/lib/migrations/PostgresMigrationBuilder.php | 1 + 3 files changed, 6 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 3bb79307..d3756483 100644 --- a/README.md +++ b/README.md @@ -390,7 +390,7 @@ User: `NOT NULL` in DB migrations is determined by `nullable` and `required` properties of the OpenAPI schema. e.g. attribute = 'my_property'. -- If you define attribute neither "required" nor via "nullable", then it is by default `NULL`: +- If you define attribute neither "required" nor via "nullable", then it is by default `NULL` ([opposite of OpenAPI spec](https://swagger.io/specification/v3/?sbsearch=nullable)): ```yaml ExampleSchema: @@ -568,4 +568,3 @@ Professional support, consulting as well as software development services are av https://www.cebe.cc/en/contact Development of this library is sponsored by [cebe.:cloud: "Your Professional Deployment Platform"](https://cebe.cloud). - diff --git a/src/lib/ColumnToCode.php b/src/lib/ColumnToCode.php index e9a570bc..2e686201 100644 --- a/src/lib/ColumnToCode.php +++ b/src/lib/ColumnToCode.php @@ -345,7 +345,9 @@ private function resolve():void $fluentSize = $this->column->size ? '(' . $this->column->size . ')' : '()'; $rawSize = $this->column->size ? '(' . $this->column->size . ')' : ''; $this->rawParts['nullable'] = $this->column->allowNull ? 'NULL' : 'NOT NULL'; - $this->fluentParts['nullable'] = $this->column->allowNull === true ? 'null()' : 'notNull()'; +// if (!ApiGenerator::isPostgres()) { + $this->fluentParts['nullable'] = $this->column->allowNull === true ? 'null()' : 'notNull()'; +// } if (array_key_exists($dbType, self::INT_TYPE_MAP)) { $this->fluentParts['type'] = self::INT_TYPE_MAP[$dbType] . $fluentSize; $this->rawParts['type'] = @@ -384,6 +386,7 @@ private function getIsBuiltinType($type, $dbType) if ($this->isEnum()) { return false; } + if ($this->fromDb === true) { return isset( (new ColumnSchemaBuilder(''))->categoryMap[$type] diff --git a/src/lib/migrations/PostgresMigrationBuilder.php b/src/lib/migrations/PostgresMigrationBuilder.php index b8c9324d..953c4305 100644 --- a/src/lib/migrations/PostgresMigrationBuilder.php +++ b/src/lib/migrations/PostgresMigrationBuilder.php @@ -72,6 +72,7 @@ protected function buildColumnChanges(ColumnSchema $current, ColumnSchema $desir $this->migration->addDownCode($this->recordBuilder->alterColumnTypeFromDb($tableName, $current, $addUsing)); } if (in_array('allowNull', $changed, true)) { +// TODO if last up code contains `null()` string then do execute below statement, same for notNull() and same in down code if ($desired->allowNull === true) { $this->migration->addUpCode($this->recordBuilder->dropColumnNotNull($tableName, $desired)); $this->migration->addDownCode($this->recordBuilder->setColumnNotNull($tableName, $current), true); From be26ed5ca72e56a9ae2d518233305859ca092b32 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Fri, 5 Jul 2024 16:26:23 +0530 Subject: [PATCH 064/358] Fix style --- src/lib/ColumnToCode.php | 2 +- src/lib/migrations/PostgresMigrationBuilder.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/lib/ColumnToCode.php b/src/lib/ColumnToCode.php index 2e686201..d602a24b 100644 --- a/src/lib/ColumnToCode.php +++ b/src/lib/ColumnToCode.php @@ -346,7 +346,7 @@ private function resolve():void $rawSize = $this->column->size ? '(' . $this->column->size . ')' : ''; $this->rawParts['nullable'] = $this->column->allowNull ? 'NULL' : 'NOT NULL'; // if (!ApiGenerator::isPostgres()) { - $this->fluentParts['nullable'] = $this->column->allowNull === true ? 'null()' : 'notNull()'; + $this->fluentParts['nullable'] = $this->column->allowNull === true ? 'null()' : 'notNull()'; // } if (array_key_exists($dbType, self::INT_TYPE_MAP)) { $this->fluentParts['type'] = self::INT_TYPE_MAP[$dbType] . $fluentSize; diff --git a/src/lib/migrations/PostgresMigrationBuilder.php b/src/lib/migrations/PostgresMigrationBuilder.php index 953c4305..6f487812 100644 --- a/src/lib/migrations/PostgresMigrationBuilder.php +++ b/src/lib/migrations/PostgresMigrationBuilder.php @@ -72,7 +72,7 @@ protected function buildColumnChanges(ColumnSchema $current, ColumnSchema $desir $this->migration->addDownCode($this->recordBuilder->alterColumnTypeFromDb($tableName, $current, $addUsing)); } if (in_array('allowNull', $changed, true)) { -// TODO if last up code contains `null()` string then do execute below statement, same for notNull() and same in down code + // TODO if last up code contains `null()` string then do execute below statement, same for notNull() and same in down code if ($desired->allowNull === true) { $this->migration->addUpCode($this->recordBuilder->dropColumnNotNull($tableName, $desired)); $this->migration->addDownCode($this->recordBuilder->setColumnNotNull($tableName, $current), true); From 7897d0dc672986008c026d299c8e181377600498 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Sun, 7 Jul 2024 20:15:27 +0530 Subject: [PATCH 065/358] Fix this issue --- src/lib/ColumnToCode.php | 4 ++-- src/lib/migrations/MigrationRecordBuilder.php | 10 ++++++++++ src/lib/migrations/PostgresMigrationBuilder.php | 14 +++++++++----- .../m200000_000000_change_table_fruits.php | 2 -- .../m200000_000001_change_table_editcolumns.php | 4 ++-- .../m200000_000001_create_table_editcolumns.php | 2 +- .../x_db_type/fresh/pgsql/x_db_type_pgsql.yaml | 1 + .../m200000_000001_create_table_editcolumns.php | 2 +- .../app/models/pgsqlmodel/base/Editcolumn.php | 2 +- 9 files changed, 27 insertions(+), 14 deletions(-) diff --git a/src/lib/ColumnToCode.php b/src/lib/ColumnToCode.php index d602a24b..67fcc30d 100644 --- a/src/lib/ColumnToCode.php +++ b/src/lib/ColumnToCode.php @@ -69,7 +69,7 @@ class ColumnToCode * @var bool * Built In Type means the \cebe\yii2openapi\lib\items\Attribute::$type or \cebe\yii2openapi\lib\items\Attribute::$dbType is in list of Yii abstract data type list or not. And if is found we can use \yii\db\SchemaBuilderTrait methods to build migration instead of putting raw SQL */ - private $isBuiltinType = false; + public $isBuiltinType = false; /** * @var bool @@ -468,7 +468,7 @@ private function resolveDefaultValue():void private function isDefaultAllowed():bool { - // default expression with parenthases is allowed + // default expression with parentheses is allowed if ($this->column->defaultValue instanceof \yii\db\Expression) { return true; } diff --git a/src/lib/migrations/MigrationRecordBuilder.php b/src/lib/migrations/MigrationRecordBuilder.php index 98ee03b8..97481e9e 100644 --- a/src/lib/migrations/MigrationRecordBuilder.php +++ b/src/lib/migrations/MigrationRecordBuilder.php @@ -51,6 +51,12 @@ final class MigrationRecordBuilder */ private $dbSchema; + /** + * @var bool + * Only required for PgSQL alter column for set null/set default related statement + */ + public $isBuiltInType = false; + public function __construct(Schema $dbSchema) { $this->dbSchema = $dbSchema; @@ -134,6 +140,7 @@ public function alterColumnType(string $tableAlias, ColumnSchema $column, bool $ { if (property_exists($column, 'xDbType') && is_string($column->xDbType) && !empty($column->xDbType)) { $converter = $this->columnToCode($tableAlias, $column, false, false, true, true); + $this->isBuiltInType = $converter->isBuiltinType; return sprintf( ApiGenerator::isPostgres() ? self::ALTER_COLUMN_RAW_PGSQL : self::ALTER_COLUMN_RAW, $tableAlias, @@ -142,6 +149,7 @@ public function alterColumnType(string $tableAlias, ColumnSchema $column, bool $ ); } $converter = $this->columnToCode($tableAlias, $column, false); + $this->isBuiltInType = $converter->isBuiltinType; return sprintf(self::ALTER_COLUMN, $tableAlias, $column->name, $converter->getAlterExpression($addUsing)); } @@ -153,6 +161,7 @@ public function alterColumnTypeFromDb(string $tableAlias, ColumnSchema $column, { if (property_exists($column, 'xDbType') && is_string($column->xDbType) && !empty($column->xDbType)) { $converter = $this->columnToCode($tableAlias, $column, true, false, true, true); + $this->isBuiltInType = $converter->isBuiltinType; return sprintf( ApiGenerator::isPostgres() ? self::ALTER_COLUMN_RAW_PGSQL : self::ALTER_COLUMN_RAW, $tableAlias, @@ -161,6 +170,7 @@ public function alterColumnTypeFromDb(string $tableAlias, ColumnSchema $column, ); } $converter = $this->columnToCode($tableAlias, $column, true); + $this->isBuiltInType = $converter->isBuiltinType; return sprintf(self::ALTER_COLUMN, $tableAlias, $column->name, $converter->getAlterExpression($addUsing)); } diff --git a/src/lib/migrations/PostgresMigrationBuilder.php b/src/lib/migrations/PostgresMigrationBuilder.php index 6f487812..3ea1a28d 100644 --- a/src/lib/migrations/PostgresMigrationBuilder.php +++ b/src/lib/migrations/PostgresMigrationBuilder.php @@ -62,16 +62,20 @@ protected function buildColumnChanges(ColumnSchema $current, ColumnSchema $desir // This action require several steps and can't be applied during single transaction return; } - + $forUp = $forDown = false; if (!empty(array_intersect(['type', 'size' , 'dbType', 'phpType' , 'precision', 'scale', 'unsigned' ], $changed))) { $addUsing = $this->isNeedUsingExpression($current->dbType, $desired->dbType); $this->migration->addUpCode($this->recordBuilder->alterColumnType($tableName, $desired, $addUsing)); + $forUp = $this->recordBuilder->isBuiltInType; $this->migration->addDownCode($this->recordBuilder->alterColumnTypeFromDb($tableName, $current, $addUsing)); + $forDown = $this->recordBuilder->isBuiltInType; } - if (in_array('allowNull', $changed, true)) { + if (in_array('allowNull', $changed, true) + && ($forUp === false || $forDown === false) + ) { // TODO if last up code contains `null()` string then do execute below statement, same for notNull() and same in down code if ($desired->allowNull === true) { $this->migration->addUpCode($this->recordBuilder->dropColumnNotNull($tableName, $desired)); @@ -81,6 +85,9 @@ protected function buildColumnChanges(ColumnSchema $current, ColumnSchema $desir $this->migration->addDownCode($this->recordBuilder->dropColumnNotNull($tableName, $current), true); } } + + $this->recordBuilder->isBuiltInType = $forUp = $forDown = false; + if (in_array('defaultValue', $changed, true)) { $upCode = $desired->defaultValue === null ? $this->recordBuilder->dropColumnDefault($tableName, $desired) @@ -97,9 +104,6 @@ protected function buildColumnChanges(ColumnSchema $current, ColumnSchema $desir } if ($isChangeFromEnum) { $this->migration->addUpCode($this->recordBuilder->dropEnum($tableName, $current->name)); - } - - if ($isChangeFromEnum) { $this->migration ->addDownCode($this->recordBuilder->createEnum($tableName, $current->name, $current->enumValues)); } diff --git a/tests/specs/issue_fix/wrong_migration_for_pgsql_is_generated_for_string_varchar_datatype_149/app/migrations_pgsql_db/m200000_000000_change_table_fruits.php b/tests/specs/issue_fix/wrong_migration_for_pgsql_is_generated_for_string_varchar_datatype_149/app/migrations_pgsql_db/m200000_000000_change_table_fruits.php index 574730fe..f89f7f63 100644 --- a/tests/specs/issue_fix/wrong_migration_for_pgsql_is_generated_for_string_varchar_datatype_149/app/migrations_pgsql_db/m200000_000000_change_table_fruits.php +++ b/tests/specs/issue_fix/wrong_migration_for_pgsql_is_generated_for_string_varchar_datatype_149/app/migrations_pgsql_db/m200000_000000_change_table_fruits.php @@ -8,12 +8,10 @@ class m200000_000000_change_table_fruits extends \yii\db\Migration public function safeUp() { $this->alterColumn('{{%fruits}}', 'name', $this->string(151)->notNull()); - $this->alterColumn('{{%fruits}}', 'name', "SET NOT NULL"); } public function safeDown() { $this->alterColumn('{{%fruits}}', 'name', $this->string(150)->null()); - $this->alterColumn('{{%fruits}}', 'name', "DROP NOT NULL"); } } diff --git a/tests/specs/x_db_type/edit_column/pgsql/app/migrations_pgsql_db/m200000_000001_change_table_editcolumns.php b/tests/specs/x_db_type/edit_column/pgsql/app/migrations_pgsql_db/m200000_000001_change_table_editcolumns.php index 5ad21a0a..f1890895 100644 --- a/tests/specs/x_db_type/edit_column/pgsql/app/migrations_pgsql_db/m200000_000001_change_table_editcolumns.php +++ b/tests/specs/x_db_type/edit_column/pgsql/app/migrations_pgsql_db/m200000_000001_change_table_editcolumns.php @@ -14,7 +14,6 @@ public function safeUp() $this->db->createCommand('ALTER TABLE {{%editcolumns}} ALTER COLUMN "name" SET DATA TYPE varchar(254)')->execute(); $this->alterColumn('{{%editcolumns}}', 'name', "SET DEFAULT 'Horse-2'"); $this->alterColumn('{{%editcolumns}}', 'string_col', 'text NULL USING "string_col"::text'); - $this->alterColumn('{{%editcolumns}}', 'string_col', "DROP NOT NULL"); $this->db->createCommand('ALTER TABLE {{%editcolumns}} ALTER COLUMN "dec_col" SET DATA TYPE decimal(12,2) USING "dec_col"::decimal(12,2)')->execute(); $this->alterColumn('{{%editcolumns}}', 'dec_col', "SET DEFAULT 3.14"); $this->alterColumn('{{%editcolumns}}', 'str_col_def', "SET NOT NULL"); @@ -25,6 +24,7 @@ public function safeUp() $this->alterColumn('{{%editcolumns}}', 'json_col_2', "SET NOT NULL"); $this->alterColumn('{{%editcolumns}}', 'json_col_2', "SET DEFAULT '[]'"); $this->db->createCommand('ALTER TABLE {{%editcolumns}} ALTER COLUMN "numeric_col" SET DATA TYPE double precision USING "numeric_col"::double precision')->execute(); + $this->alterColumn('{{%editcolumns}}', 'numeric_col', "SET NOT NULL"); } public function safeDown() @@ -39,7 +39,6 @@ public function safeDown() $this->dropColumn('{{%editcolumns}}', 'json_col_def_n'); $this->dropColumn('{{%editcolumns}}', 'first_name'); $this->alterColumn('{{%editcolumns}}', 'name', "SET DEFAULT 'Horse'"); - $this->alterColumn('{{%editcolumns}}', 'string_col', "SET NOT NULL"); $this->alterColumn('{{%editcolumns}}', 'dec_col', "DROP DEFAULT"); $this->alterColumn('{{%editcolumns}}', 'str_col_def', "DROP NOT NULL"); $this->alterColumn('{{%editcolumns}}', 'str_col_def', "SET DEFAULT 'hi there'"); @@ -47,5 +46,6 @@ public function safeDown() $this->alterColumn('{{%editcolumns}}', 'json_col', "DROP DEFAULT"); $this->alterColumn('{{%editcolumns}}', 'json_col_2', "DROP NOT NULL"); $this->alterColumn('{{%editcolumns}}', 'json_col_2', "DROP DEFAULT"); + $this->alterColumn('{{%editcolumns}}', 'numeric_col', "DROP NOT NULL"); } } diff --git a/tests/specs/x_db_type/fresh/pgsql/app/migrations_pgsql_db/m200000_000001_create_table_editcolumns.php b/tests/specs/x_db_type/fresh/pgsql/app/migrations_pgsql_db/m200000_000001_create_table_editcolumns.php index b8f286b1..fcf648ed 100644 --- a/tests/specs/x_db_type/fresh/pgsql/app/migrations_pgsql_db/m200000_000001_create_table_editcolumns.php +++ b/tests/specs/x_db_type/fresh/pgsql/app/migrations_pgsql_db/m200000_000001_create_table_editcolumns.php @@ -17,7 +17,7 @@ public function safeUp() 3 => '"str_col_def" varchar NOT NULL', 4 => '"json_col" text NOT NULL DEFAULT \'fox jumps over dog\'', 5 => '"json_col_2" jsonb NOT NULL DEFAULT \'[]\'', - 6 => '"numeric_col" double precision NULL DEFAULT NULL', + 6 => '"numeric_col" double precision NOT NULL', 7 => '"json_col_def_n" json NOT NULL DEFAULT \'[]\'', 8 => '"json_col_def_n_2" json NOT NULL DEFAULT \'[]\'', 9 => '"text_col_array" text[] NULL DEFAULT NULL', diff --git a/tests/specs/x_db_type/fresh/pgsql/x_db_type_pgsql.yaml b/tests/specs/x_db_type/fresh/pgsql/x_db_type_pgsql.yaml index ff629112..15233c63 100644 --- a/tests/specs/x_db_type/fresh/pgsql/x_db_type_pgsql.yaml +++ b/tests/specs/x_db_type/fresh/pgsql/x_db_type_pgsql.yaml @@ -516,6 +516,7 @@ components: numeric_col: type: string x-db-type: double precision + nullable: false json_col_def_n: type: string x-db-type: json diff --git a/tests/specs/x_db_type/new_column/pgsql/app/migrations_pgsql_db/m200000_000001_create_table_editcolumns.php b/tests/specs/x_db_type/new_column/pgsql/app/migrations_pgsql_db/m200000_000001_create_table_editcolumns.php index b8f286b1..fcf648ed 100644 --- a/tests/specs/x_db_type/new_column/pgsql/app/migrations_pgsql_db/m200000_000001_create_table_editcolumns.php +++ b/tests/specs/x_db_type/new_column/pgsql/app/migrations_pgsql_db/m200000_000001_create_table_editcolumns.php @@ -17,7 +17,7 @@ public function safeUp() 3 => '"str_col_def" varchar NOT NULL', 4 => '"json_col" text NOT NULL DEFAULT \'fox jumps over dog\'', 5 => '"json_col_2" jsonb NOT NULL DEFAULT \'[]\'', - 6 => '"numeric_col" double precision NULL DEFAULT NULL', + 6 => '"numeric_col" double precision NOT NULL', 7 => '"json_col_def_n" json NOT NULL DEFAULT \'[]\'', 8 => '"json_col_def_n_2" json NOT NULL DEFAULT \'[]\'', 9 => '"text_col_array" text[] NULL DEFAULT NULL', diff --git a/tests/specs/x_db_type/rules_and_more/pgsql/app/models/pgsqlmodel/base/Editcolumn.php b/tests/specs/x_db_type/rules_and_more/pgsql/app/models/pgsqlmodel/base/Editcolumn.php index 730bff5a..0add2f71 100644 --- a/tests/specs/x_db_type/rules_and_more/pgsql/app/models/pgsqlmodel/base/Editcolumn.php +++ b/tests/specs/x_db_type/rules_and_more/pgsql/app/models/pgsqlmodel/base/Editcolumn.php @@ -31,7 +31,7 @@ public function rules() { return [ 'trim' => [['name', 'tag', 'first_name', 'string_col', 'str_col_def', 'json_col'], 'trim'], - 'required' => [['name', 'str_col_def', 'json_col', 'json_col_2'], 'required'], + 'required' => [['name', 'str_col_def', 'json_col', 'json_col_2', 'numeric_col'], 'required'], 'name_string' => [['name'], 'string', 'max' => 254], 'name_default' => [['name'], 'default', 'value' => 'Horse-2'], 'tag_string' => [['tag'], 'string'], From e73d9a0d5e19e7397067859d3daba6a4890f339f Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Sun, 7 Jul 2024 20:18:34 +0530 Subject: [PATCH 066/358] Cleanup --- src/lib/ColumnToCode.php | 2 -- src/lib/migrations/PostgresMigrationBuilder.php | 1 - 2 files changed, 3 deletions(-) diff --git a/src/lib/ColumnToCode.php b/src/lib/ColumnToCode.php index 67fcc30d..b7394388 100644 --- a/src/lib/ColumnToCode.php +++ b/src/lib/ColumnToCode.php @@ -345,9 +345,7 @@ private function resolve():void $fluentSize = $this->column->size ? '(' . $this->column->size . ')' : '()'; $rawSize = $this->column->size ? '(' . $this->column->size . ')' : ''; $this->rawParts['nullable'] = $this->column->allowNull ? 'NULL' : 'NOT NULL'; -// if (!ApiGenerator::isPostgres()) { $this->fluentParts['nullable'] = $this->column->allowNull === true ? 'null()' : 'notNull()'; -// } if (array_key_exists($dbType, self::INT_TYPE_MAP)) { $this->fluentParts['type'] = self::INT_TYPE_MAP[$dbType] . $fluentSize; $this->rawParts['type'] = diff --git a/src/lib/migrations/PostgresMigrationBuilder.php b/src/lib/migrations/PostgresMigrationBuilder.php index 3ea1a28d..956ac9d5 100644 --- a/src/lib/migrations/PostgresMigrationBuilder.php +++ b/src/lib/migrations/PostgresMigrationBuilder.php @@ -76,7 +76,6 @@ protected function buildColumnChanges(ColumnSchema $current, ColumnSchema $desir if (in_array('allowNull', $changed, true) && ($forUp === false || $forDown === false) ) { - // TODO if last up code contains `null()` string then do execute below statement, same for notNull() and same in down code if ($desired->allowNull === true) { $this->migration->addUpCode($this->recordBuilder->dropColumnNotNull($tableName, $desired)); $this->migration->addDownCode($this->recordBuilder->setColumnNotNull($tableName, $current), true); From aee7c15b0f28ec4d9e1acaaa9eebfe4f7ff06fdc Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Mon, 8 Jul 2024 18:29:24 +0530 Subject: [PATCH 067/358] Initial commit to create this PR --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 1cd2090b..3bb79307 100644 --- a/README.md +++ b/README.md @@ -568,3 +568,4 @@ Professional support, consulting as well as software development services are av https://www.cebe.cc/en/contact Development of this library is sponsored by [cebe.:cloud: "Your Professional Deployment Platform"](https://cebe.cloud). + From 221f8acbca0b5f8a62ddc615c523b27a23234885 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Tue, 9 Jul 2024 20:46:19 +0530 Subject: [PATCH 068/358] Fix issue: `actionCreateinvoicePayment` instead of `actionCreateInvoicePayment` --- README.md | 1 - src/lib/generators/RestActionGenerator.php | 3 +- .../index.php | 13 +++ .../index.yaml | 84 +++++++++++++++++++ .../index.php | 2 +- .../index.php | 2 +- .../162_bug_dollarref_with_x_faker.php | 2 +- .../index.php | 2 +- .../index.php | 2 +- .../index.php | 2 +- tests/unit/IssueFixTest.php | 14 ++++ 11 files changed, 119 insertions(+), 8 deletions(-) create mode 100644 tests/specs/issue_fix/144_methods_naming_for_non_crud_actions/index.php create mode 100644 tests/specs/issue_fix/144_methods_naming_for_non_crud_actions/index.yaml diff --git a/README.md b/README.md index 3bb79307..1cd2090b 100644 --- a/README.md +++ b/README.md @@ -568,4 +568,3 @@ Professional support, consulting as well as software development services are av https://www.cebe.cc/en/contact Development of this library is sponsored by [cebe.:cloud: "Your Professional Deployment Platform"](https://cebe.cloud). - diff --git a/src/lib/generators/RestActionGenerator.php b/src/lib/generators/RestActionGenerator.php index daedd20f..4be6e6c7 100644 --- a/src/lib/generators/RestActionGenerator.php +++ b/src/lib/generators/RestActionGenerator.php @@ -109,9 +109,10 @@ protected function prepareAction(string $method, Operation $operation, RouteData } else { $controllerId = $routeData->controller; } + $action = ucfirst($routeData->action); return Yii::createObject(RestAction::class, [ [ - 'id' => trim("$actionType{$routeData->action}", '-'), + 'id' => trim("$actionType$action", '-'), 'controllerId' => $controllerId, 'urlPath' => $routeData->path, 'requestMethod' => strtoupper($method), diff --git a/tests/specs/issue_fix/144_methods_naming_for_non_crud_actions/index.php b/tests/specs/issue_fix/144_methods_naming_for_non_crud_actions/index.php new file mode 100644 index 00000000..d461ae44 --- /dev/null +++ b/tests/specs/issue_fix/144_methods_naming_for_non_crud_actions/index.php @@ -0,0 +1,13 @@ + '@specs/issue_fix/144_methods_naming_for_non_crud_actions/index.yaml', + 'generateUrls' => true, + 'generateModels' => false, + 'excludeModels' => [ + 'Error', + ], + 'generateControllers' => true, + 'generateMigrations' => false, + 'generateModelFaker' => false, // `generateModels` must be `true` in order to use `generateModelFaker` as `true` +]; diff --git a/tests/specs/issue_fix/144_methods_naming_for_non_crud_actions/index.yaml b/tests/specs/issue_fix/144_methods_naming_for_non_crud_actions/index.yaml new file mode 100644 index 00000000..c11b1e9d --- /dev/null +++ b/tests/specs/issue_fix/144_methods_naming_for_non_crud_actions/index.yaml @@ -0,0 +1,84 @@ +openapi: 3.0.3 + +info: + title: 'Custom action name' + version: 1.0.0 + +tags: + - name: Payments + description: Pay or receive payments for your products from different channels + externalDocs: + description: Find out more + url: https://developer.adiuta.com/book/payments +paths: + /payments/invoice/{invoice}: + parameters: + - name: invoice + in: path + description: lorem ipsum + required: true + schema: + type: integer + post: + summary: Pay Invoice + description: Pay for Invoice with given invoice number + requestBody: + description: Record new payment for an invoice + content: + application/json: + schema: + $ref: '#/components/schemas/Payments' + required: true + responses: + '200': + description: Successfully paid the invoice + content: + application/json: + schema: + $ref: '#/components/schemas/Success' + + /payments/invoice-payment: + get: + operationId: opnid + summary: List + description: Lists + responses: + '200': + description: The Response + +components: + schemas: + Payments: + required: + - reference + - amount + - currency + properties: + invoice_number: + type: string + amount: + type: integer + format: int64 + currency: + type: string + + Success: + required: + - success + - message + properties: + success: + type: boolean + message: + type: string + + Error: + required: + - code + - message + properties: + code: + type: integer + format: int32 + message: + type: string \ No newline at end of file diff --git a/tests/specs/issue_fix/158_bug_giiapi_generated_rules_enum_with_trim/index.php b/tests/specs/issue_fix/158_bug_giiapi_generated_rules_enum_with_trim/index.php index 515b362c..70e43b74 100644 --- a/tests/specs/issue_fix/158_bug_giiapi_generated_rules_enum_with_trim/index.php +++ b/tests/specs/issue_fix/158_bug_giiapi_generated_rules_enum_with_trim/index.php @@ -9,6 +9,6 @@ ], 'generateControllers' => false, 'generateMigrations' => false, - 'generateModelFaker' => true, // `generateModels` must be `true` in orde to use `generateModelFaker` as `true` + 'generateModelFaker' => true, // `generateModels` must be `true` in order to use `generateModelFaker` as `true` ]; diff --git a/tests/specs/issue_fix/159_bug_giiapi_generated_rules_emailid/index.php b/tests/specs/issue_fix/159_bug_giiapi_generated_rules_emailid/index.php index b66f036b..645671f2 100644 --- a/tests/specs/issue_fix/159_bug_giiapi_generated_rules_emailid/index.php +++ b/tests/specs/issue_fix/159_bug_giiapi_generated_rules_emailid/index.php @@ -9,6 +9,6 @@ ], 'generateControllers' => false, 'generateMigrations' => false, - 'generateModelFaker' => true, // `generateModels` must be `true` in orde to use `generateModelFaker` as `true` + 'generateModelFaker' => true, // `generateModels` must be `true` in order to use `generateModelFaker` as `true` ]; diff --git a/tests/specs/issue_fix/162_bug_dollarref_with_x_faker/162_bug_dollarref_with_x_faker.php b/tests/specs/issue_fix/162_bug_dollarref_with_x_faker/162_bug_dollarref_with_x_faker.php index 19951cd4..8e6ca8d0 100644 --- a/tests/specs/issue_fix/162_bug_dollarref_with_x_faker/162_bug_dollarref_with_x_faker.php +++ b/tests/specs/issue_fix/162_bug_dollarref_with_x_faker/162_bug_dollarref_with_x_faker.php @@ -9,5 +9,5 @@ ], 'generateControllers' => false, 'generateMigrations' => false, - 'generateModelFaker' => true, // `generateModels` must be `true` in orde to use `generateModelFaker` as `true` + 'generateModelFaker' => true, // `generateModels` must be `true` in order to use `generateModelFaker` as `true` ]; diff --git a/tests/specs/issue_fix/163_generator_crash_when_using_reference_inside_an_object/index.php b/tests/specs/issue_fix/163_generator_crash_when_using_reference_inside_an_object/index.php index 784db168..504db8f9 100644 --- a/tests/specs/issue_fix/163_generator_crash_when_using_reference_inside_an_object/index.php +++ b/tests/specs/issue_fix/163_generator_crash_when_using_reference_inside_an_object/index.php @@ -9,6 +9,6 @@ ], 'generateControllers' => true, 'generateMigrations' => true, - 'generateModelFaker' => true, // `generateModels` must be `true` in orde to use `generateModelFaker` as `true` + 'generateModelFaker' => true, // `generateModels` must be `true` in order to use `generateModelFaker` as `true` ]; diff --git a/tests/specs/issue_fix/172_schemayaml_requestbody_has_no_effect/index.php b/tests/specs/issue_fix/172_schemayaml_requestbody_has_no_effect/index.php index 3debbb46..91969e28 100644 --- a/tests/specs/issue_fix/172_schemayaml_requestbody_has_no_effect/index.php +++ b/tests/specs/issue_fix/172_schemayaml_requestbody_has_no_effect/index.php @@ -9,6 +9,6 @@ ], 'generateControllers' => true, 'generateMigrations' => false, - 'generateModelFaker' => false, // `generateModels` must be `true` in orde to use `generateModelFaker` as `true` + 'generateModelFaker' => false, // `generateModels` must be `true` in order to use `generateModelFaker` as `true` ]; diff --git a/tests/specs/issue_fix/175_bug_allof_with_multiple_dollarrefs/index.php b/tests/specs/issue_fix/175_bug_allof_with_multiple_dollarrefs/index.php index 3ccbc836..43e214b1 100644 --- a/tests/specs/issue_fix/175_bug_allof_with_multiple_dollarrefs/index.php +++ b/tests/specs/issue_fix/175_bug_allof_with_multiple_dollarrefs/index.php @@ -9,6 +9,6 @@ ], 'generateControllers' => true, 'generateMigrations' => true, - 'generateModelFaker' => true, // `generateModels` must be `true` in orde to use `generateModelFaker` as `true` + 'generateModelFaker' => true, // `generateModels` must be `true` in order to use `generateModelFaker` as `true` ]; diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index b6c7abdb..5ccd5907 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -360,4 +360,18 @@ public function test158BugGiiapiGeneratedRulesEnumWithTrim() ]); $this->checkFiles($actualFiles, $expectedFiles); } + + // https://github.com/cebe/yii2-openapi/issues/144 + public function test144MethodsNamingForNonCrudActions() + { + $testFile = Yii::getAlias("@specs/issue_fix/144_methods_naming_for_non_crud_actions/index.php"); + $this->runGenerator($testFile); +// $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ +// 'recursive' => true, +// ]); +// $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/158_bug_giiapi_generated_rules_enum_with_trim/maria"), [ +// 'recursive' => true, +// ]); +// $this->checkFiles($actualFiles, $expectedFiles); + } } From 7799c8e3777dfdf6a87db6c34c4a2fc836f89307 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Wed, 10 Jul 2024 13:58:55 +0530 Subject: [PATCH 069/358] Fix issue in generated url rule config --- src/generator/default/urls.php | 8 +++++++- src/lib/generators/RestActionGenerator.php | 4 ++-- src/lib/items/RestAction.php | 4 ++-- 3 files changed, 11 insertions(+), 5 deletions(-) diff --git a/src/generator/default/urls.php b/src/generator/default/urls.php index e666a428..302ad533 100644 --- a/src/generator/default/urls.php +++ b/src/generator/default/urls.php @@ -1,3 +1,8 @@ + /** @@ -5,5 +10,6 @@ * * This file is auto generated. */ - + return ; diff --git a/src/lib/generators/RestActionGenerator.php b/src/lib/generators/RestActionGenerator.php index 4be6e6c7..90a0cf9b 100644 --- a/src/lib/generators/RestActionGenerator.php +++ b/src/lib/generators/RestActionGenerator.php @@ -109,10 +109,10 @@ protected function prepareAction(string $method, Operation $operation, RouteData } else { $controllerId = $routeData->controller; } - $action = ucfirst($routeData->action); + $action = Inflector::camel2id($routeData->action); return Yii::createObject(RestAction::class, [ [ - 'id' => trim("$actionType$action", '-'), + 'id' => trim("$actionType-$action", '-'), 'controllerId' => $controllerId, 'urlPath' => $routeData->path, 'requestMethod' => strtoupper($method), diff --git a/src/lib/items/RestAction.php b/src/lib/items/RestAction.php index 6852fafc..03a42a0c 100644 --- a/src/lib/items/RestAction.php +++ b/src/lib/items/RestAction.php @@ -72,9 +72,9 @@ public function getRoute():string { if ($this->prefix && !empty($this->prefixSettings)) { $prefix = $this->prefixSettings['module'] ?? $this->prefix; - return trim($prefix, '/').'/'.$this->controllerId.'/'.$this->id; + return trim($prefix, '/') . '/' . $this->controllerId . '/' . $this->id; } - return $this->controllerId.'/'.$this->id; + return $this->controllerId . '/' . $this->id; } public function getOptionsRoute():string From 5423164b78ceae04424094c2f0a06446b2283e50 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Thu, 11 Jul 2024 16:34:30 +0530 Subject: [PATCH 070/358] Fix this issue --- README.md | 5 +++ src/lib/CustomSpecAttr.php | 5 +++ src/lib/generators/RestActionGenerator.php | 8 ++++- .../app/config/urls.rest.php | 15 ++++++++ .../app/controllers/AbcController.php | 25 ++++++++++++++ .../app/controllers/PaymentController.php | 20 +++++++++++ .../app/controllers/PaymentsController.php | 20 +++++++++++ .../app/controllers/base/AbcController.php | 34 +++++++++++++++++++ .../controllers/base/PaymentController.php | 32 +++++++++++++++++ .../controllers/base/PaymentsController.php | 32 +++++++++++++++++ .../index.yaml | 19 ++++++++++- tests/unit/IssueFixTest.php | 14 ++++---- 12 files changed, 220 insertions(+), 9 deletions(-) create mode 100644 tests/specs/issue_fix/144_methods_naming_for_non_crud_actions/app/config/urls.rest.php create mode 100644 tests/specs/issue_fix/144_methods_naming_for_non_crud_actions/app/controllers/AbcController.php create mode 100644 tests/specs/issue_fix/144_methods_naming_for_non_crud_actions/app/controllers/PaymentController.php create mode 100644 tests/specs/issue_fix/144_methods_naming_for_non_crud_actions/app/controllers/PaymentsController.php create mode 100644 tests/specs/issue_fix/144_methods_naming_for_non_crud_actions/app/controllers/base/AbcController.php create mode 100644 tests/specs/issue_fix/144_methods_naming_for_non_crud_actions/app/controllers/base/PaymentController.php create mode 100644 tests/specs/issue_fix/144_methods_naming_for_non_crud_actions/app/controllers/base/PaymentsController.php diff --git a/README.md b/README.md index 1cd2090b..43089919 100644 --- a/README.md +++ b/README.md @@ -309,6 +309,11 @@ Provide custom database table column name in case of relationship column. This w - x-fk-column-name: redelivery_of # this will create `redelivery_of` column instead of `redelivery_of_id` ``` +### `x-route` + +https://github.com/cebe/yii2-openapi/issues/144 +TODO + ## Many-to-Many relation definition There are two ways for define many-to-many relations: diff --git a/src/lib/CustomSpecAttr.php b/src/lib/CustomSpecAttr.php index 7e02a85d..1c87e4db 100644 --- a/src/lib/CustomSpecAttr.php +++ b/src/lib/CustomSpecAttr.php @@ -40,4 +40,9 @@ class CustomSpecAttr * Foreign key column name. See README for usage docs */ public const FK_COLUMN_NAME = 'x-fk-column-name'; + + /** + * Custom route (controller ID/action ID) instead of auto-generated. See README for usage docs. https://github.com/cebe/yii2-openapi/issues/144 + */ + public const ROUTE = 'x-route'; } diff --git a/src/lib/generators/RestActionGenerator.php b/src/lib/generators/RestActionGenerator.php index 90a0cf9b..27a78ce7 100644 --- a/src/lib/generators/RestActionGenerator.php +++ b/src/lib/generators/RestActionGenerator.php @@ -11,6 +11,7 @@ use cebe\openapi\spec\PathItem; use cebe\openapi\spec\Reference; use cebe\yii2openapi\lib\Config; +use cebe\yii2openapi\lib\CustomSpecAttr; use cebe\yii2openapi\lib\items\RestAction; use cebe\yii2openapi\lib\items\RouteData; use cebe\yii2openapi\lib\openapi\ResponseSchema; @@ -44,6 +45,11 @@ public function generate():array { $actions = []; foreach ($this->config->getOpenApi()->paths as $path => $pathItem) { + $customRoute = null; + if (isset($pathItem->{CustomSpecAttr::ROUTE})) { # https://github.com/cebe/yii2-openapi/issues/144 + $customRoute = $pathItem->{CustomSpecAttr::ROUTE}; + } + if ($path[0] !== '/') { throw new InvalidConfigException('Path must begin with /'); } @@ -53,7 +59,7 @@ public function generate():array if ($pathItem instanceof Reference) { $pathItem = $pathItem->resolve(); } - $actions[] = $this->resolvePath($path, $pathItem); + $actions[] = $this->resolvePath(!empty($customRoute) ? '/' . $customRoute : $path, $pathItem); } return array_merge(...$actions); } diff --git a/tests/specs/issue_fix/144_methods_naming_for_non_crud_actions/app/config/urls.rest.php b/tests/specs/issue_fix/144_methods_naming_for_non_crud_actions/app/config/urls.rest.php new file mode 100644 index 00000000..c658232f --- /dev/null +++ b/tests/specs/issue_fix/144_methods_naming_for_non_crud_actions/app/config/urls.rest.php @@ -0,0 +1,15 @@ +' => 'payments/create-invoice', + 'GET payments/invoice-payment' => 'payment/invoice-payment', + 'GET abc/xyz' => 'abc/xyz', + 'POST abc/xyz' => 'abc/create-xyz', + 'payments/invoice/' => 'payments/options', + 'payments/invoice-payment' => 'payment/options', + 'abc/xyz' => 'abc/options', +]; diff --git a/tests/specs/issue_fix/144_methods_naming_for_non_crud_actions/app/controllers/AbcController.php b/tests/specs/issue_fix/144_methods_naming_for_non_crud_actions/app/controllers/AbcController.php new file mode 100644 index 00000000..41621b8d --- /dev/null +++ b/tests/specs/issue_fix/144_methods_naming_for_non_crud_actions/app/controllers/AbcController.php @@ -0,0 +1,25 @@ + [ + 'class' => \yii\rest\OptionsAction::class, + ], + ]; + } + + /** + * Checks the privilege of the current user. + * + * This method checks whether the current user has the privilege + * to run the specified action against the specified data model. + * If the user does not have access, a [[ForbiddenHttpException]] should be thrown. + * + * @param string $action the ID of the action to be executed + * @param object $model the model to be accessed. If null, it means no specific model is being accessed. + * @param array $params additional parameters + * @throws \yii\web\ForbiddenHttpException if the user does not have access + */ + abstract public function checkAccess($action, $model = null, $params = []); + + abstract public function actionXyz(); + + abstract public function actionCreateXyz(); + +} diff --git a/tests/specs/issue_fix/144_methods_naming_for_non_crud_actions/app/controllers/base/PaymentController.php b/tests/specs/issue_fix/144_methods_naming_for_non_crud_actions/app/controllers/base/PaymentController.php new file mode 100644 index 00000000..4d39cdb8 --- /dev/null +++ b/tests/specs/issue_fix/144_methods_naming_for_non_crud_actions/app/controllers/base/PaymentController.php @@ -0,0 +1,32 @@ + [ + 'class' => \yii\rest\OptionsAction::class, + ], + ]; + } + + /** + * Checks the privilege of the current user. + * + * This method checks whether the current user has the privilege + * to run the specified action against the specified data model. + * If the user does not have access, a [[ForbiddenHttpException]] should be thrown. + * + * @param string $action the ID of the action to be executed + * @param object $model the model to be accessed. If null, it means no specific model is being accessed. + * @param array $params additional parameters + * @throws \yii\web\ForbiddenHttpException if the user does not have access + */ + abstract public function checkAccess($action, $model = null, $params = []); + + abstract public function actionInvoicePayment(); + +} diff --git a/tests/specs/issue_fix/144_methods_naming_for_non_crud_actions/app/controllers/base/PaymentsController.php b/tests/specs/issue_fix/144_methods_naming_for_non_crud_actions/app/controllers/base/PaymentsController.php new file mode 100644 index 00000000..5fc9ac27 --- /dev/null +++ b/tests/specs/issue_fix/144_methods_naming_for_non_crud_actions/app/controllers/base/PaymentsController.php @@ -0,0 +1,32 @@ + [ + 'class' => \yii\rest\OptionsAction::class, + ], + ]; + } + + /** + * Checks the privilege of the current user. + * + * This method checks whether the current user has the privilege + * to run the specified action against the specified data model. + * If the user does not have access, a [[ForbiddenHttpException]] should be thrown. + * + * @param string $action the ID of the action to be executed + * @param object $model the model to be accessed. If null, it means no specific model is being accessed. + * @param array $params additional parameters + * @throws \yii\web\ForbiddenHttpException if the user does not have access + */ + abstract public function checkAccess($action, $model = null, $params = []); + + abstract public function actionCreateInvoice($invoice); + +} diff --git a/tests/specs/issue_fix/144_methods_naming_for_non_crud_actions/index.yaml b/tests/specs/issue_fix/144_methods_naming_for_non_crud_actions/index.yaml index c11b1e9d..ee80b435 100644 --- a/tests/specs/issue_fix/144_methods_naming_for_non_crud_actions/index.yaml +++ b/tests/specs/issue_fix/144_methods_naming_for_non_crud_actions/index.yaml @@ -1,7 +1,7 @@ openapi: 3.0.3 info: - title: 'Custom action name' + title: 'Custom route for path' version: 1.0.0 tags: @@ -46,6 +46,23 @@ paths: '200': description: The Response + /a1/b1: + x-route: 'abc/xyz' + get: + operationId: opnid5 + summary: List + description: Lists + responses: + '200': + description: The Response + post: + operationId: opnid23 + summary: List + description: Lists + responses: + '200': + description: The Response + components: schemas: Payments: diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index 5ccd5907..1b3720cf 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -366,12 +366,12 @@ public function test144MethodsNamingForNonCrudActions() { $testFile = Yii::getAlias("@specs/issue_fix/144_methods_naming_for_non_crud_actions/index.php"); $this->runGenerator($testFile); -// $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ -// 'recursive' => true, -// ]); -// $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/158_bug_giiapi_generated_rules_enum_with_trim/maria"), [ -// 'recursive' => true, -// ]); -// $this->checkFiles($actualFiles, $expectedFiles); + $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ + 'recursive' => true, + ]); + $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/144_methods_naming_for_non_crud_actions/app"), [ + 'recursive' => true, + ]); + $this->checkFiles($actualFiles, $expectedFiles); } } From 0521ec269a67a25014b0d03e8a479f2efcd6f3a8 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Thu, 11 Jul 2024 20:42:11 +0530 Subject: [PATCH 071/358] Fix bug - WIP --- src/lib/generators/ControllersGenerator.php | 14 +++++++------ src/lib/generators/RestActionGenerator.php | 20 ++++++++++++------- src/lib/items/RouteData.php | 1 + .../index.yaml | 14 ++++++++++++- tests/unit/IssueFixTest.php | 6 +++++- 5 files changed, 40 insertions(+), 15 deletions(-) diff --git a/src/lib/generators/ControllersGenerator.php b/src/lib/generators/ControllersGenerator.php index 366f5532..bdea6e8c 100644 --- a/src/lib/generators/ControllersGenerator.php +++ b/src/lib/generators/ControllersGenerator.php @@ -129,12 +129,14 @@ protected function makeCustomController( $params = array_map(static function ($param) { return ['name' => $param]; }, $action->getParamNames()); - $reflection->addMethod( - $action->actionMethodName, - $params, - AbstractMemberGenerator::FLAG_PUBLIC, - '//TODO implement ' . $action->actionMethodName - ); + if (!$reflection->hasMethod($action->actionMethodName)) { + $reflection->addMethod( + $action->actionMethodName, + $params, + AbstractMemberGenerator::FLAG_PUBLIC, + '//TODO implement ' . $action->actionMethodName + ); + } } $classFileGenerator->setClasses([$reflection]); return $classFileGenerator; diff --git a/src/lib/generators/RestActionGenerator.php b/src/lib/generators/RestActionGenerator.php index 27a78ce7..c3b0f314 100644 --- a/src/lib/generators/RestActionGenerator.php +++ b/src/lib/generators/RestActionGenerator.php @@ -45,10 +45,6 @@ public function generate():array { $actions = []; foreach ($this->config->getOpenApi()->paths as $path => $pathItem) { - $customRoute = null; - if (isset($pathItem->{CustomSpecAttr::ROUTE})) { # https://github.com/cebe/yii2-openapi/issues/144 - $customRoute = $pathItem->{CustomSpecAttr::ROUTE}; - } if ($path[0] !== '/') { throw new InvalidConfigException('Path must begin with /'); @@ -59,7 +55,7 @@ public function generate():array if ($pathItem instanceof Reference) { $pathItem = $pathItem->resolve(); } - $actions[] = $this->resolvePath(!empty($customRoute) ? '/' . $customRoute : $path, $pathItem); + $actions[] = $this->resolvePath($path, $pathItem); } return array_merge(...$actions); } @@ -77,7 +73,11 @@ protected function resolvePath(string $path, PathItem $pathItem):array $routeData = Yii::createObject(RouteData::class, [$pathItem, $path, $this->config->urlPrefixes]); foreach ($pathItem->getOperations() as $method => $operation) { - $actions[] = $this->prepareAction($method, $operation, $routeData); + $customRoute = null; + if (isset($operation->{CustomSpecAttr::ROUTE})) { # https://github.com/cebe/yii2-openapi/issues/144 + $customRoute = $operation->{CustomSpecAttr::ROUTE}; + } + $actions[] = $this->prepareAction($method, $operation, $routeData, $customRoute); } return $actions; } @@ -90,7 +90,7 @@ protected function resolvePath(string $path, PathItem $pathItem):array * @throws \cebe\openapi\exceptions\UnresolvableReferenceException * @throws \yii\base\InvalidConfigException */ - protected function prepareAction(string $method, Operation $operation, RouteData $routeData):BaseObject + protected function prepareAction(string $method, Operation $operation, RouteData $routeData, $customRoute):BaseObject { $actionType = $this->resolveActionType($routeData, $method); $modelClass = ResponseSchema::guessModelClass($operation, $actionType); @@ -112,10 +112,16 @@ protected function prepareAction(string $method, Operation $operation, RouteData $controllerId = isset($this->config->controllerModelMap[$modelClass]) ? Inflector::camel2id($this->config->controllerModelMap[$modelClass]) : Inflector::camel2id($modelClass); + } elseif (!empty($customRoute)) { + $controllerId = explode('/', $customRoute)[0]; } else { $controllerId = $routeData->controller; } $action = Inflector::camel2id($routeData->action); + if (!empty($customRoute)) { + $actionType = ''; + $action = explode('/', $customRoute)[1]; + } return Yii::createObject(RestAction::class, [ [ 'id' => trim("$actionType-$action", '-'), diff --git a/src/lib/items/RouteData.php b/src/lib/items/RouteData.php index c426a517..48455835 100644 --- a/src/lib/items/RouteData.php +++ b/src/lib/items/RouteData.php @@ -166,6 +166,7 @@ final class RouteData extends BaseObject public function __construct(PathItem $pathItem, string $path, array $urlPrefixes = [], $config = []) { + // TODO url rules config php file should have path but not the x-route $this->path = $this->unprefixedPath = $path; $this->parts = explode('/', trim($path, '/')); $this->pathItem = $pathItem; diff --git a/tests/specs/issue_fix/144_methods_naming_for_non_crud_actions/index.yaml b/tests/specs/issue_fix/144_methods_naming_for_non_crud_actions/index.yaml index ee80b435..4e299184 100644 --- a/tests/specs/issue_fix/144_methods_naming_for_non_crud_actions/index.yaml +++ b/tests/specs/issue_fix/144_methods_naming_for_non_crud_actions/index.yaml @@ -20,6 +20,7 @@ paths: schema: type: integer post: + x-route: 'payments/invoice' summary: Pay Invoice description: Pay for Invoice with given invoice number requestBody: @@ -47,8 +48,8 @@ paths: description: The Response /a1/b1: - x-route: 'abc/xyz' get: + x-route: 'abc/xyz' operationId: opnid5 summary: List description: Lists @@ -56,6 +57,7 @@ paths: '200': description: The Response post: + x-route: 'abc/xyz' operationId: opnid23 summary: List description: Lists @@ -63,6 +65,16 @@ paths: '200': description: The Response + /aa2/bb2: +# x-route: 'payment/xyz2' + get: + operationId: opnid7 + summary: List + description: Lists + responses: + '200': + description: The Response + components: schemas: Payments: diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index 1b3720cf..977a0331 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -349,6 +349,10 @@ public function test159BugGiiapiGeneratedRulesEmailid() // https://github.com/cebe/yii2-openapi/issues/158 public function test158BugGiiapiGeneratedRulesEnumWithTrim() { + // TODO add more test case + // one new controller new action + // one new action in exiting controller + $this->changeDbToMariadb(); $testFile = Yii::getAlias("@specs/issue_fix/158_bug_giiapi_generated_rules_enum_with_trim/index.php"); $this->runGenerator($testFile, 'maria'); @@ -372,6 +376,6 @@ public function test144MethodsNamingForNonCrudActions() $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/144_methods_naming_for_non_crud_actions/app"), [ 'recursive' => true, ]); - $this->checkFiles($actualFiles, $expectedFiles); +// $this->checkFiles($actualFiles, $expectedFiles); // TODO } } From 53b3d80b6c5163da17c14c1293f272de04ecae25 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Thu, 11 Jul 2024 20:44:12 +0530 Subject: [PATCH 072/358] Fix failing test --- src/lib/generators/JsonActionGenerator.php | 2 +- src/lib/generators/RestActionGenerator.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/lib/generators/JsonActionGenerator.php b/src/lib/generators/JsonActionGenerator.php index 696f7974..ff18a696 100644 --- a/src/lib/generators/JsonActionGenerator.php +++ b/src/lib/generators/JsonActionGenerator.php @@ -26,7 +26,7 @@ class JsonActionGenerator extends RestActionGenerator * @throws \yii\base\InvalidConfigException * @throws \cebe\openapi\exceptions\UnresolvableReferenceException */ - protected function prepareAction(string $method, Operation $operation, RouteData $routeData):BaseObject + protected function prepareAction(string $method, Operation $operation, RouteData $routeData, $customRoute = null):BaseObject { $actionType = $this->resolveActionType($routeData, $method); $modelClass = ResponseSchema::guessModelClass($operation, $actionType); diff --git a/src/lib/generators/RestActionGenerator.php b/src/lib/generators/RestActionGenerator.php index c3b0f314..07f16a84 100644 --- a/src/lib/generators/RestActionGenerator.php +++ b/src/lib/generators/RestActionGenerator.php @@ -90,7 +90,7 @@ protected function resolvePath(string $path, PathItem $pathItem):array * @throws \cebe\openapi\exceptions\UnresolvableReferenceException * @throws \yii\base\InvalidConfigException */ - protected function prepareAction(string $method, Operation $operation, RouteData $routeData, $customRoute):BaseObject + protected function prepareAction(string $method, Operation $operation, RouteData $routeData, $customRoute = null):BaseObject { $actionType = $this->resolveActionType($routeData, $method); $modelClass = ResponseSchema::guessModelClass($operation, $actionType); From b73b8993156455caf269cb2b8f427ce85d8c998d Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Fri, 12 Jul 2024 16:34:03 +0530 Subject: [PATCH 073/358] Fix style --- src/lib/generators/RestActionGenerator.php | 1 - 1 file changed, 1 deletion(-) diff --git a/src/lib/generators/RestActionGenerator.php b/src/lib/generators/RestActionGenerator.php index 07f16a84..933ff310 100644 --- a/src/lib/generators/RestActionGenerator.php +++ b/src/lib/generators/RestActionGenerator.php @@ -45,7 +45,6 @@ public function generate():array { $actions = []; foreach ($this->config->getOpenApi()->paths as $path => $pathItem) { - if ($path[0] !== '/') { throw new InvalidConfigException('Path must begin with /'); } From 7d64bc0500c44563709a03285259379162387eb9 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Fri, 12 Jul 2024 21:08:25 +0530 Subject: [PATCH 074/358] Fix bug --- src/lib/generators/JsonActionGenerator.php | 8 +++- src/lib/generators/RestActionGenerator.php | 8 +++- src/lib/items/RouteData.php | 1 - .../index.yaml | 45 ++++++++++++++++++- tests/unit/IssueFixTest.php | 4 -- 5 files changed, 56 insertions(+), 10 deletions(-) diff --git a/src/lib/generators/JsonActionGenerator.php b/src/lib/generators/JsonActionGenerator.php index ff18a696..3cc2de2a 100644 --- a/src/lib/generators/JsonActionGenerator.php +++ b/src/lib/generators/JsonActionGenerator.php @@ -26,8 +26,12 @@ class JsonActionGenerator extends RestActionGenerator * @throws \yii\base\InvalidConfigException * @throws \cebe\openapi\exceptions\UnresolvableReferenceException */ - protected function prepareAction(string $method, Operation $operation, RouteData $routeData, $customRoute = null):BaseObject - { + protected function prepareAction( + string $method, + Operation $operation, + RouteData $routeData, + ?string $customRoute = null + ): BaseObject { $actionType = $this->resolveActionType($routeData, $method); $modelClass = ResponseSchema::guessModelClass($operation, $actionType); $expectedRelations = in_array($actionType, ['list', 'view']) diff --git a/src/lib/generators/RestActionGenerator.php b/src/lib/generators/RestActionGenerator.php index 933ff310..d9fa2f68 100644 --- a/src/lib/generators/RestActionGenerator.php +++ b/src/lib/generators/RestActionGenerator.php @@ -89,8 +89,12 @@ protected function resolvePath(string $path, PathItem $pathItem):array * @throws \cebe\openapi\exceptions\UnresolvableReferenceException * @throws \yii\base\InvalidConfigException */ - protected function prepareAction(string $method, Operation $operation, RouteData $routeData, $customRoute = null):BaseObject - { + protected function prepareAction( + string $method, + Operation $operation, + RouteData $routeData, + ?string $customRoute = null + ): BaseObject { $actionType = $this->resolveActionType($routeData, $method); $modelClass = ResponseSchema::guessModelClass($operation, $actionType); $responseWrapper = ResponseSchema::findResponseWrapper($operation, $modelClass); diff --git a/src/lib/items/RouteData.php b/src/lib/items/RouteData.php index 48455835..c426a517 100644 --- a/src/lib/items/RouteData.php +++ b/src/lib/items/RouteData.php @@ -166,7 +166,6 @@ final class RouteData extends BaseObject public function __construct(PathItem $pathItem, string $path, array $urlPrefixes = [], $config = []) { - // TODO url rules config php file should have path but not the x-route $this->path = $this->unprefixedPath = $path; $this->parts = explode('/', trim($path, '/')); $this->pathItem = $pathItem; diff --git a/tests/specs/issue_fix/144_methods_naming_for_non_crud_actions/index.yaml b/tests/specs/issue_fix/144_methods_naming_for_non_crud_actions/index.yaml index 4e299184..4641aefc 100644 --- a/tests/specs/issue_fix/144_methods_naming_for_non_crud_actions/index.yaml +++ b/tests/specs/issue_fix/144_methods_naming_for_non_crud_actions/index.yaml @@ -11,6 +11,49 @@ tags: description: Find out more url: https://developer.adiuta.com/book/payments paths: + /fruit/mango: + get: + x-route: fruits/mango + operationId: opnid9 + summary: Lorem ipsum + description: Lorem ipsum description + responses: + '200': + description: The Response + + + /fruits/mango: + get: + operationId: opnid8 + summary: Lorem ipsum + description: Lorem ipsum description + responses: + '200': + description: The Response + post: + operationId: opnid9 + summary: Lorem ipsum + description: Lorem ipsum description + responses: + '200': + description: The Response + + /animal/goat: + get: + operationId: opnid8 + summary: Lorem ipsum + description: Lorem ipsum description + responses: + '200': + description: The Response + post: + operationId: opnid9 + summary: Lorem ipsum + description: Lorem ipsum description + responses: + '200': + description: The Response + /payments/invoice/{invoice}: parameters: - name: invoice @@ -66,8 +109,8 @@ paths: description: The Response /aa2/bb2: -# x-route: 'payment/xyz2' get: + x-route: 'payments/xyz2' operationId: opnid7 summary: List description: Lists diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index 977a0331..6d1df0c7 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -349,10 +349,6 @@ public function test159BugGiiapiGeneratedRulesEmailid() // https://github.com/cebe/yii2-openapi/issues/158 public function test158BugGiiapiGeneratedRulesEnumWithTrim() { - // TODO add more test case - // one new controller new action - // one new action in exiting controller - $this->changeDbToMariadb(); $testFile = Yii::getAlias("@specs/issue_fix/158_bug_giiapi_generated_rules_enum_with_trim/index.php"); $this->runGenerator($testFile, 'maria'); From 8e5f52b8451c20e483c7dfeb09a71d497e423a77 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Fri, 12 Jul 2024 21:11:57 +0530 Subject: [PATCH 075/358] Add more tests --- .../app/config/urls.rest.php | 18 +++++++--- .../app/controllers/AbcController.php | 5 --- .../app/controllers/AnimalController.php | 25 ++++++++++++++ .../app/controllers/FruitController.php | 25 ++++++++++++++ .../app/controllers/FruitsController.php | 20 +++++++++++ .../app/controllers/PaymentsController.php | 9 +++-- .../app/controllers/base/AbcController.php | 2 +- .../app/controllers/base/AnimalController.php | 34 +++++++++++++++++++ .../app/controllers/base/FruitController.php | 34 +++++++++++++++++++ .../app/controllers/base/FruitsController.php | 32 +++++++++++++++++ .../controllers/base/PaymentsController.php | 4 ++- tests/unit/IssueFixTest.php | 2 +- 12 files changed, 196 insertions(+), 14 deletions(-) create mode 100644 tests/specs/issue_fix/144_methods_naming_for_non_crud_actions/app/controllers/AnimalController.php create mode 100644 tests/specs/issue_fix/144_methods_naming_for_non_crud_actions/app/controllers/FruitController.php create mode 100644 tests/specs/issue_fix/144_methods_naming_for_non_crud_actions/app/controllers/FruitsController.php create mode 100644 tests/specs/issue_fix/144_methods_naming_for_non_crud_actions/app/controllers/base/AnimalController.php create mode 100644 tests/specs/issue_fix/144_methods_naming_for_non_crud_actions/app/controllers/base/FruitController.php create mode 100644 tests/specs/issue_fix/144_methods_naming_for_non_crud_actions/app/controllers/base/FruitsController.php diff --git a/tests/specs/issue_fix/144_methods_naming_for_non_crud_actions/app/config/urls.rest.php b/tests/specs/issue_fix/144_methods_naming_for_non_crud_actions/app/config/urls.rest.php index c658232f..1d39a048 100644 --- a/tests/specs/issue_fix/144_methods_naming_for_non_crud_actions/app/config/urls.rest.php +++ b/tests/specs/issue_fix/144_methods_naming_for_non_crud_actions/app/config/urls.rest.php @@ -5,11 +5,21 @@ * This file is auto generated. */ return [ - 'POST payments/invoice/' => 'payments/create-invoice', + 'GET fruit/mango' => 'fruits/mango', + 'GET fruits/mango' => 'fruit/mango', + 'POST fruits/mango' => 'fruit/create-mango', + 'GET animal/goat' => 'animal/goat', + 'POST animal/goat' => 'animal/create-goat', + 'POST payments/invoice/' => 'payments/invoice', 'GET payments/invoice-payment' => 'payment/invoice-payment', - 'GET abc/xyz' => 'abc/xyz', - 'POST abc/xyz' => 'abc/create-xyz', + 'GET a1/b1' => 'abc/xyz', + 'POST a1/b1' => 'abc/xyz', + 'GET aa2/bb2' => 'payments/xyz2', + 'fruit/mango' => 'fruits/options', + 'fruits/mango' => 'fruit/options', + 'animal/goat' => 'animal/options', 'payments/invoice/' => 'payments/options', 'payments/invoice-payment' => 'payment/options', - 'abc/xyz' => 'abc/options', + 'a1/b1' => 'abc/options', + 'aa2/bb2' => 'payments/options', ]; diff --git a/tests/specs/issue_fix/144_methods_naming_for_non_crud_actions/app/controllers/AbcController.php b/tests/specs/issue_fix/144_methods_naming_for_non_crud_actions/app/controllers/AbcController.php index 41621b8d..833d931e 100644 --- a/tests/specs/issue_fix/144_methods_naming_for_non_crud_actions/app/controllers/AbcController.php +++ b/tests/specs/issue_fix/144_methods_naming_for_non_crud_actions/app/controllers/AbcController.php @@ -15,11 +15,6 @@ public function actionXyz() //TODO implement actionXyz } - public function actionCreateXyz() - { - //TODO implement actionCreateXyz - } - } diff --git a/tests/specs/issue_fix/144_methods_naming_for_non_crud_actions/app/controllers/AnimalController.php b/tests/specs/issue_fix/144_methods_naming_for_non_crud_actions/app/controllers/AnimalController.php new file mode 100644 index 00000000..27b00d8b --- /dev/null +++ b/tests/specs/issue_fix/144_methods_naming_for_non_crud_actions/app/controllers/AnimalController.php @@ -0,0 +1,25 @@ + [ + 'class' => \yii\rest\OptionsAction::class, + ], + ]; + } + + /** + * Checks the privilege of the current user. + * + * This method checks whether the current user has the privilege + * to run the specified action against the specified data model. + * If the user does not have access, a [[ForbiddenHttpException]] should be thrown. + * + * @param string $action the ID of the action to be executed + * @param object $model the model to be accessed. If null, it means no specific model is being accessed. + * @param array $params additional parameters + * @throws \yii\web\ForbiddenHttpException if the user does not have access + */ + abstract public function checkAccess($action, $model = null, $params = []); + + abstract public function actionGoat(); + + abstract public function actionCreateGoat(); + +} diff --git a/tests/specs/issue_fix/144_methods_naming_for_non_crud_actions/app/controllers/base/FruitController.php b/tests/specs/issue_fix/144_methods_naming_for_non_crud_actions/app/controllers/base/FruitController.php new file mode 100644 index 00000000..5cef0ed5 --- /dev/null +++ b/tests/specs/issue_fix/144_methods_naming_for_non_crud_actions/app/controllers/base/FruitController.php @@ -0,0 +1,34 @@ + [ + 'class' => \yii\rest\OptionsAction::class, + ], + ]; + } + + /** + * Checks the privilege of the current user. + * + * This method checks whether the current user has the privilege + * to run the specified action against the specified data model. + * If the user does not have access, a [[ForbiddenHttpException]] should be thrown. + * + * @param string $action the ID of the action to be executed + * @param object $model the model to be accessed. If null, it means no specific model is being accessed. + * @param array $params additional parameters + * @throws \yii\web\ForbiddenHttpException if the user does not have access + */ + abstract public function checkAccess($action, $model = null, $params = []); + + abstract public function actionMango(); + + abstract public function actionCreateMango(); + +} diff --git a/tests/specs/issue_fix/144_methods_naming_for_non_crud_actions/app/controllers/base/FruitsController.php b/tests/specs/issue_fix/144_methods_naming_for_non_crud_actions/app/controllers/base/FruitsController.php new file mode 100644 index 00000000..01549012 --- /dev/null +++ b/tests/specs/issue_fix/144_methods_naming_for_non_crud_actions/app/controllers/base/FruitsController.php @@ -0,0 +1,32 @@ + [ + 'class' => \yii\rest\OptionsAction::class, + ], + ]; + } + + /** + * Checks the privilege of the current user. + * + * This method checks whether the current user has the privilege + * to run the specified action against the specified data model. + * If the user does not have access, a [[ForbiddenHttpException]] should be thrown. + * + * @param string $action the ID of the action to be executed + * @param object $model the model to be accessed. If null, it means no specific model is being accessed. + * @param array $params additional parameters + * @throws \yii\web\ForbiddenHttpException if the user does not have access + */ + abstract public function checkAccess($action, $model = null, $params = []); + + abstract public function actionMango(); + +} diff --git a/tests/specs/issue_fix/144_methods_naming_for_non_crud_actions/app/controllers/base/PaymentsController.php b/tests/specs/issue_fix/144_methods_naming_for_non_crud_actions/app/controllers/base/PaymentsController.php index 5fc9ac27..869d64e6 100644 --- a/tests/specs/issue_fix/144_methods_naming_for_non_crud_actions/app/controllers/base/PaymentsController.php +++ b/tests/specs/issue_fix/144_methods_naming_for_non_crud_actions/app/controllers/base/PaymentsController.php @@ -27,6 +27,8 @@ public function actions() */ abstract public function checkAccess($action, $model = null, $params = []); - abstract public function actionCreateInvoice($invoice); + abstract public function actionInvoice($invoice); + + abstract public function actionXyz2(); } diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index 6d1df0c7..1b3720cf 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -372,6 +372,6 @@ public function test144MethodsNamingForNonCrudActions() $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/144_methods_naming_for_non_crud_actions/app"), [ 'recursive' => true, ]); -// $this->checkFiles($actualFiles, $expectedFiles); // TODO + $this->checkFiles($actualFiles, $expectedFiles); } } From 136cea80d65d71d3bf59343602626295a2106f61 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Sat, 13 Jul 2024 15:02:59 +0530 Subject: [PATCH 076/358] Add docs --- README.md | 60 +++++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 58 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 43089919..f49afb8e 100644 --- a/README.md +++ b/README.md @@ -311,8 +311,64 @@ Provide custom database table column name in case of relationship column. This w ### `x-route` -https://github.com/cebe/yii2-openapi/issues/144 -TODO +To customize route (controller ID/action ID) for a path, use custom key `x-route` with value `/`. It can be used for non-crud paths. It must be used under HTTP method key but not +directly under the `paths` key of OpenAPI spec. Example: + +```yaml +paths: + /payments/invoice/{invoice}: + parameters: + - name: invoice + in: path + description: lorem ipsum + required: true + schema: + type: integer + post: + x-route: 'payments/invoice' + summary: Pay Invoice + description: Pay for Invoice with given invoice number + requestBody: + description: Record new payment for an invoice + content: + application/json: + schema: + $ref: '#/components/schemas/Payments' + required: true + responses: + '200': + description: Successfully paid the invoice + content: + application/json: + schema: + $ref: '#/components/schemas/Success' +``` + +It won't generate `actionCreateInvoice` in `PaymentsController.php` file, but will generate `actionInvoice` instead in +same file. + +Also, if same action is needed for HTTP GET and POST then use same value for `x-route`. Example: + +```yaml +paths: + /a1/b1: + get: + x-route: 'abc/xyz' + operationId: opnid1 + summary: List + description: Lists + responses: + '200': + description: The Response + post: + x-route: 'abc/xyz' + operationId: opnid2 + summary: create + description: create + responses: + '200': + description: The Response +``` ## Many-to-Many relation definition From 528497d9e3adf25aabe8e287c3a76a9450660311 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Sat, 13 Jul 2024 15:10:21 +0530 Subject: [PATCH 077/358] Add docs about URL rules config --- README.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/README.md b/README.md index f49afb8e..f6bebf7b 100644 --- a/README.md +++ b/README.md @@ -347,6 +347,12 @@ paths: It won't generate `actionCreateInvoice` in `PaymentsController.php` file, but will generate `actionInvoice` instead in same file. +Generated URL rules config for above is (in `urls.rest.php` or pertinent file): +```php + 'POST payments/invoice/' => 'payments/invoice', + 'payments/invoice/' => 'payments/options', +``` + Also, if same action is needed for HTTP GET and POST then use same value for `x-route`. Example: ```yaml @@ -370,6 +376,13 @@ paths: description: The Response ``` +Generated URL rules config for above is (in `urls.rest.php` or pertinent file): +```php + 'GET a1/b1' => 'abc/xyz', + 'POST a1/b1' => 'abc/xyz', + 'a1/b1' => 'abc/options', +``` + ## Many-to-Many relation definition There are two ways for define many-to-many relations: From fcf41473e4d085cc6175ec18a4761a12e1c52b03 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Tue, 16 Jul 2024 19:53:39 +0530 Subject: [PATCH 078/358] Add fix & test for https://github.com/cebe/yii2-openapi/issues/84 --- src/generator/ApiGenerator.php | 27 +++++++ src/lib/generators/ControllersGenerator.php | 15 ++-- src/lib/generators/RestActionGenerator.php | 15 +++- src/lib/items/RestAction.php | 13 ++++ .../index.yaml | 6 +- .../index.php | 13 ++++ .../index.yaml | 77 +++++++++++++++++++ tests/unit/IssueFixTest.php | 14 ++++ 8 files changed, 168 insertions(+), 12 deletions(-) create mode 100644 tests/specs/issue_fix/84_how_to_generate_controller_code_with_distinct_method_names_in_case_of_prefix_in_paths/index.php create mode 100644 tests/specs/issue_fix/84_how_to_generate_controller_code_with_distinct_method_names_in_case_of_prefix_in_paths/index.yaml diff --git a/src/generator/ApiGenerator.php b/src/generator/ApiGenerator.php index f930f949..14fdbed0 100644 --- a/src/generator/ApiGenerator.php +++ b/src/generator/ApiGenerator.php @@ -7,6 +7,7 @@ namespace cebe\yii2openapi\generator; +use cebe\yii2openapi\lib\items\RestAction; use yii\db\mysql\Schema as MySqlSchema; use SamIT\Yii2\MariaDb\Schema as MariaDbSchema; use yii\db\pgsql\Schema as PgSqlSchema; @@ -473,6 +474,7 @@ public function generate():array $urlRulesGenerator = Yii::createObject(UrlRulesGenerator::class, [$config, $actions]); $files = $urlRulesGenerator->generate(); + $actions = static::removeDuplicateActions($actions); $controllersGenerator = Yii::createObject(ControllersGenerator::class, [$config, $actions]); $files->merge($controllersGenerator->generate()); @@ -521,4 +523,29 @@ public static function isMariaDb():bool { return strpos(Yii::$app->db->schema->getServerVersion(), 'MariaDB') !== false; } + + /** + * @param RestAction[] $actions + * @return RestAction[] + * https://github.com/cebe/yii2-openapi/issues/84 + */ + public static function removeDuplicateActions(array $actions): array + { + $actions = array_filter($actions, function (RestAction $action) { + if ($action->isDuplicate) { + return false; + } + return true; + }); + + $actions = array_map(function (RestAction $action) { + if ($action->isOriginalForCustomRoute) { + $action->idParam = null; + $action->params = []; + } + return $action; + }, $actions); + + return $actions; + } } diff --git a/src/lib/generators/ControllersGenerator.php b/src/lib/generators/ControllersGenerator.php index bdea6e8c..bd749c9f 100644 --- a/src/lib/generators/ControllersGenerator.php +++ b/src/lib/generators/ControllersGenerator.php @@ -129,14 +129,13 @@ protected function makeCustomController( $params = array_map(static function ($param) { return ['name' => $param]; }, $action->getParamNames()); - if (!$reflection->hasMethod($action->actionMethodName)) { - $reflection->addMethod( - $action->actionMethodName, - $params, - AbstractMemberGenerator::FLAG_PUBLIC, - '//TODO implement ' . $action->actionMethodName - ); - } + + $reflection->addMethod( + $action->actionMethodName, + $params, + AbstractMemberGenerator::FLAG_PUBLIC, + '//TODO implement ' . $action->actionMethodName + ); } $classFileGenerator->setClasses([$reflection]); return $classFileGenerator; diff --git a/src/lib/generators/RestActionGenerator.php b/src/lib/generators/RestActionGenerator.php index d9fa2f68..d05f342a 100644 --- a/src/lib/generators/RestActionGenerator.php +++ b/src/lib/generators/RestActionGenerator.php @@ -59,6 +59,7 @@ public function generate():array return array_merge(...$actions); } + private $allCustomRoutes = []; /** * @param string $path * @param \cebe\openapi\spec\PathItem $pathItem @@ -76,7 +77,19 @@ protected function resolvePath(string $path, PathItem $pathItem):array if (isset($operation->{CustomSpecAttr::ROUTE})) { # https://github.com/cebe/yii2-openapi/issues/144 $customRoute = $operation->{CustomSpecAttr::ROUTE}; } - $actions[] = $this->prepareAction($method, $operation, $routeData, $customRoute); + if ($customRoute === null) { + $actions[] = $this->prepareAction($method, $operation, $routeData, $customRoute); + } else { + // TODO rename + $actionHere = $this->prepareAction($method, $operation, $routeData, $customRoute); + $actionHere->isOriginalForCustomRoute = true; + if (!in_array($customRoute, $this->allCustomRoutes)) { + $actionHere->isOriginalForCustomRoute = false; + $actionHere->isDuplicate = true; + $this->allCustomRoutes[] = $customRoute; + } + $actions[] = $actionHere; + } } return $actions; } diff --git a/src/lib/items/RestAction.php b/src/lib/items/RestAction.php index 03a42a0c..cd97abd3 100644 --- a/src/lib/items/RestAction.php +++ b/src/lib/items/RestAction.php @@ -68,6 +68,19 @@ final class RestAction extends BaseObject */ public $responseWrapper; + /** + * @var bool + * @see $isDuplicate + */ + public $isOriginalForCustomRoute = false; + /** + * @var bool + * https://github.com/cebe/yii2-openapi/issues/84 + * Generate only one action for paths like: `GET /calendar/domains` and `GET /calendar/domains/{id}`. + * @see $isOriginalForCustomRoute + */ + public $isDuplicate = false; + public function getRoute():string { if ($this->prefix && !empty($this->prefixSettings)) { diff --git a/tests/specs/issue_fix/144_methods_naming_for_non_crud_actions/index.yaml b/tests/specs/issue_fix/144_methods_naming_for_non_crud_actions/index.yaml index 4641aefc..43435cc4 100644 --- a/tests/specs/issue_fix/144_methods_naming_for_non_crud_actions/index.yaml +++ b/tests/specs/issue_fix/144_methods_naming_for_non_crud_actions/index.yaml @@ -14,7 +14,7 @@ paths: /fruit/mango: get: x-route: fruits/mango - operationId: opnid9 + operationId: opnid91 summary: Lorem ipsum description: Lorem ipsum description responses: @@ -24,7 +24,7 @@ paths: /fruits/mango: get: - operationId: opnid8 + operationId: opnid81 summary: Lorem ipsum description: Lorem ipsum description responses: @@ -47,7 +47,7 @@ paths: '200': description: The Response post: - operationId: opnid9 + operationId: opnid92 summary: Lorem ipsum description: Lorem ipsum description responses: diff --git a/tests/specs/issue_fix/84_how_to_generate_controller_code_with_distinct_method_names_in_case_of_prefix_in_paths/index.php b/tests/specs/issue_fix/84_how_to_generate_controller_code_with_distinct_method_names_in_case_of_prefix_in_paths/index.php new file mode 100644 index 00000000..6d88068a --- /dev/null +++ b/tests/specs/issue_fix/84_how_to_generate_controller_code_with_distinct_method_names_in_case_of_prefix_in_paths/index.php @@ -0,0 +1,13 @@ + '@specs/issue_fix/84_how_to_generate_controller_code_with_distinct_method_names_in_case_of_prefix_in_paths/index.yaml', + 'generateUrls' => true, + 'generateModels' => false, + 'excludeModels' => [ + 'Error', + ], + 'generateControllers' => true, + 'generateMigrations' => false, + 'generateModelFaker' => false, // `generateModels` must be `true` in order to use `generateModelFaker` as `true` +]; diff --git a/tests/specs/issue_fix/84_how_to_generate_controller_code_with_distinct_method_names_in_case_of_prefix_in_paths/index.yaml b/tests/specs/issue_fix/84_how_to_generate_controller_code_with_distinct_method_names_in_case_of_prefix_in_paths/index.yaml new file mode 100644 index 00000000..7cbbdbf9 --- /dev/null +++ b/tests/specs/issue_fix/84_how_to_generate_controller_code_with_distinct_method_names_in_case_of_prefix_in_paths/index.yaml @@ -0,0 +1,77 @@ +openapi: 3.0.3 + +info: + title: 'Custom route for path' + version: 1.0.0 + +tags: + - name: Payments + description: Pay or receive payments for your products from different channels + externalDocs: + description: Find out more + url: https://developer.adiuta.com/book/payments +paths: + /calendar/domains: + get: + x-route: calendar/domains + summary: Lorem ipsum + description: Lorem ipsum description + responses: + '200': + description: The Response + + + /calendar/domains/{id}: + parameters: + - name: id + in: path + description: lorem ipsum + required: true + schema: + type: integer + get: + x-route: calendar/domains + summary: Lorem ipsum + description: Lorem ipsum description + responses: + '200': + description: The Response + + + +components: + schemas: + Payments: + required: + - reference + - amount + - currency + properties: + invoice_number: + type: string + amount: + type: integer + format: int64 + currency: + type: string + + Success: + required: + - success + - message + properties: + success: + type: boolean + message: + type: string + + Error: + required: + - code + - message + properties: + code: + type: integer + format: int32 + message: + type: string \ No newline at end of file diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index 1b3720cf..040d5ff7 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -374,4 +374,18 @@ public function test144MethodsNamingForNonCrudActions() ]); $this->checkFiles($actualFiles, $expectedFiles); } + + // https://github.com/cebe/yii2-openapi/issues/84 + public function test84HowToGenerateControllerCodeWithDistinctMethodNamesInCaseOfPrefixInPaths() + { + $testFile = Yii::getAlias("@specs/issue_fix/84_how_to_generate_controller_code_with_distinct_method_names_in_case_of_prefix_in_paths/index.php"); + $this->runGenerator($testFile); + $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ + 'recursive' => true, + ]); + $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/84_how_to_generate_controller_code_with_distinct_method_names_in_case_of_prefix_in_paths/app"), [ + 'recursive' => true, + ]); +// $this->checkFiles($actualFiles, $expectedFiles); // TODO + } } From 60d0b1edb17d74d3860d2afae60310fe3ce01f2b Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Tue, 16 Jul 2024 20:30:37 +0530 Subject: [PATCH 079/358] Fix failing tests --- src/generator/ApiGenerator.php | 22 ++++++++++--------- src/lib/generators/RestActionGenerator.php | 17 +++++++------- .../app/controllers/base/AbcController.php | 2 -- 3 files changed, 20 insertions(+), 21 deletions(-) diff --git a/src/generator/ApiGenerator.php b/src/generator/ApiGenerator.php index 14fdbed0..f31efb4c 100644 --- a/src/generator/ApiGenerator.php +++ b/src/generator/ApiGenerator.php @@ -7,10 +7,6 @@ namespace cebe\yii2openapi\generator; -use cebe\yii2openapi\lib\items\RestAction; -use yii\db\mysql\Schema as MySqlSchema; -use SamIT\Yii2\MariaDb\Schema as MariaDbSchema; -use yii\db\pgsql\Schema as PgSqlSchema; use cebe\openapi\Reader; use cebe\openapi\spec\OpenApi; use cebe\yii2openapi\lib\Config; @@ -21,9 +17,13 @@ use cebe\yii2openapi\lib\generators\RestActionGenerator; use cebe\yii2openapi\lib\generators\TransformersGenerator; use cebe\yii2openapi\lib\generators\UrlRulesGenerator; +use cebe\yii2openapi\lib\items\FractalAction; +use cebe\yii2openapi\lib\items\RestAction; use cebe\yii2openapi\lib\PathAutoCompletion; use cebe\yii2openapi\lib\SchemaToDatabase; use Yii; +use yii\db\mysql\Schema as MySqlSchema; +use yii\db\pgsql\Schema as PgSqlSchema; use yii\gii\CodeFile; use yii\gii\Generator; use yii\helpers\Html; @@ -525,21 +525,23 @@ public static function isMariaDb():bool } /** - * @param RestAction[] $actions - * @return RestAction[] + * @param RestAction[]|FractalAction[] $actions + * @return RestAction[]|FractalAction[] * https://github.com/cebe/yii2-openapi/issues/84 */ public static function removeDuplicateActions(array $actions): array { - $actions = array_filter($actions, function (RestAction $action) { - if ($action->isDuplicate) { + $actions = array_filter($actions, function ($action) { + /** @var $action RestAction|FractalAction */ + if ($action instanceof RestAction && $action->isDuplicate) { return false; } return true; }); - $actions = array_map(function (RestAction $action) { - if ($action->isOriginalForCustomRoute) { + $actions = array_map(function ($action) { + /** @var $action RestAction|FractalAction */ + if ($action instanceof RestAction && $action->isOriginalForCustomRoute) { $action->idParam = null; $action->params = []; } diff --git a/src/lib/generators/RestActionGenerator.php b/src/lib/generators/RestActionGenerator.php index d05f342a..8efd2138 100644 --- a/src/lib/generators/RestActionGenerator.php +++ b/src/lib/generators/RestActionGenerator.php @@ -77,19 +77,18 @@ protected function resolvePath(string $path, PathItem $pathItem):array if (isset($operation->{CustomSpecAttr::ROUTE})) { # https://github.com/cebe/yii2-openapi/issues/144 $customRoute = $operation->{CustomSpecAttr::ROUTE}; } - if ($customRoute === null) { - $actions[] = $this->prepareAction($method, $operation, $routeData, $customRoute); - } else { - // TODO rename - $actionHere = $this->prepareAction($method, $operation, $routeData, $customRoute); - $actionHere->isOriginalForCustomRoute = true; - if (!in_array($customRoute, $this->allCustomRoutes)) { - $actionHere->isOriginalForCustomRoute = false; + + // TODO rename + $actionHere = $this->prepareAction($method, $operation, $routeData, $customRoute); + if ($customRoute !== null) { + if (in_array($customRoute, $this->allCustomRoutes)) { $actionHere->isDuplicate = true; + } else { + $actionHere->isDuplicate = false; $this->allCustomRoutes[] = $customRoute; } - $actions[] = $actionHere; } + $actions[] = $actionHere; } return $actions; } diff --git a/tests/specs/issue_fix/144_methods_naming_for_non_crud_actions/app/controllers/base/AbcController.php b/tests/specs/issue_fix/144_methods_naming_for_non_crud_actions/app/controllers/base/AbcController.php index 5fb7d836..4786e4ae 100644 --- a/tests/specs/issue_fix/144_methods_naming_for_non_crud_actions/app/controllers/base/AbcController.php +++ b/tests/specs/issue_fix/144_methods_naming_for_non_crud_actions/app/controllers/base/AbcController.php @@ -29,6 +29,4 @@ abstract public function checkAccess($action, $model = null, $params = []); abstract public function actionXyz(); - abstract public function actionXyz(); - } From 8dd401b19d29551fb3612c377b2126049edf3fc0 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Tue, 16 Jul 2024 20:32:31 +0530 Subject: [PATCH 080/358] Complete the test --- .../app/config/urls.rest.php | 12 +++++++ .../app/controllers/CalendarController.php | 20 ++++++++++++ .../controllers/base/CalendarController.php | 32 +++++++++++++++++++ tests/unit/IssueFixTest.php | 2 +- 4 files changed, 65 insertions(+), 1 deletion(-) create mode 100644 tests/specs/issue_fix/84_how_to_generate_controller_code_with_distinct_method_names_in_case_of_prefix_in_paths/app/config/urls.rest.php create mode 100644 tests/specs/issue_fix/84_how_to_generate_controller_code_with_distinct_method_names_in_case_of_prefix_in_paths/app/controllers/CalendarController.php create mode 100644 tests/specs/issue_fix/84_how_to_generate_controller_code_with_distinct_method_names_in_case_of_prefix_in_paths/app/controllers/base/CalendarController.php diff --git a/tests/specs/issue_fix/84_how_to_generate_controller_code_with_distinct_method_names_in_case_of_prefix_in_paths/app/config/urls.rest.php b/tests/specs/issue_fix/84_how_to_generate_controller_code_with_distinct_method_names_in_case_of_prefix_in_paths/app/config/urls.rest.php new file mode 100644 index 00000000..04937d8d --- /dev/null +++ b/tests/specs/issue_fix/84_how_to_generate_controller_code_with_distinct_method_names_in_case_of_prefix_in_paths/app/config/urls.rest.php @@ -0,0 +1,12 @@ + 'calendar/domains', + 'GET calendar/domains/' => 'calendar/domains', + 'calendar/domains' => 'calendar/options', + 'calendar/domains/' => 'calendar/options', +]; diff --git a/tests/specs/issue_fix/84_how_to_generate_controller_code_with_distinct_method_names_in_case_of_prefix_in_paths/app/controllers/CalendarController.php b/tests/specs/issue_fix/84_how_to_generate_controller_code_with_distinct_method_names_in_case_of_prefix_in_paths/app/controllers/CalendarController.php new file mode 100644 index 00000000..7096a165 --- /dev/null +++ b/tests/specs/issue_fix/84_how_to_generate_controller_code_with_distinct_method_names_in_case_of_prefix_in_paths/app/controllers/CalendarController.php @@ -0,0 +1,20 @@ + [ + 'class' => \yii\rest\OptionsAction::class, + ], + ]; + } + + /** + * Checks the privilege of the current user. + * + * This method checks whether the current user has the privilege + * to run the specified action against the specified data model. + * If the user does not have access, a [[ForbiddenHttpException]] should be thrown. + * + * @param string $action the ID of the action to be executed + * @param object $model the model to be accessed. If null, it means no specific model is being accessed. + * @param array $params additional parameters + * @throws \yii\web\ForbiddenHttpException if the user does not have access + */ + abstract public function checkAccess($action, $model = null, $params = []); + + abstract public function actionDomains(); + +} diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index 040d5ff7..5daf9786 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -386,6 +386,6 @@ public function test84HowToGenerateControllerCodeWithDistinctMethodNamesInCaseOf $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/84_how_to_generate_controller_code_with_distinct_method_names_in_case_of_prefix_in_paths/app"), [ 'recursive' => true, ]); -// $this->checkFiles($actualFiles, $expectedFiles); // TODO + $this->checkFiles($actualFiles, $expectedFiles); } } From 2816f28092982f49b3f33bf29b9a42667c447d77 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Tue, 16 Jul 2024 20:40:54 +0530 Subject: [PATCH 081/358] Add more concrete tests --- src/lib/generators/RestActionGenerator.php | 7 ++++-- .../app/config/urls.rest.php | 2 ++ .../index.yaml | 22 +++++++++++++++++++ 3 files changed, 29 insertions(+), 2 deletions(-) diff --git a/src/lib/generators/RestActionGenerator.php b/src/lib/generators/RestActionGenerator.php index 8efd2138..bd690467 100644 --- a/src/lib/generators/RestActionGenerator.php +++ b/src/lib/generators/RestActionGenerator.php @@ -81,11 +81,14 @@ protected function resolvePath(string $path, PathItem $pathItem):array // TODO rename $actionHere = $this->prepareAction($method, $operation, $routeData, $customRoute); if ($customRoute !== null) { - if (in_array($customRoute, $this->allCustomRoutes)) { + if (in_array($customRoute, array_keys($this->allCustomRoutes))) { $actionHere->isDuplicate = true; + if ($actionHere->params !== $this->allCustomRoutes[$customRoute]) { + $this->allCustomRoutes[$customRoute]->isOriginalForCustomRoute = true; + } } else { $actionHere->isDuplicate = false; - $this->allCustomRoutes[] = $customRoute; + $this->allCustomRoutes[$customRoute] = $actionHere; } } $actions[] = $actionHere; diff --git a/tests/specs/issue_fix/84_how_to_generate_controller_code_with_distinct_method_names_in_case_of_prefix_in_paths/app/config/urls.rest.php b/tests/specs/issue_fix/84_how_to_generate_controller_code_with_distinct_method_names_in_case_of_prefix_in_paths/app/config/urls.rest.php index 04937d8d..9bb87c11 100644 --- a/tests/specs/issue_fix/84_how_to_generate_controller_code_with_distinct_method_names_in_case_of_prefix_in_paths/app/config/urls.rest.php +++ b/tests/specs/issue_fix/84_how_to_generate_controller_code_with_distinct_method_names_in_case_of_prefix_in_paths/app/config/urls.rest.php @@ -7,6 +7,8 @@ return [ 'GET calendar/domains' => 'calendar/domains', 'GET calendar/domains/' => 'calendar/domains', + 'GET calendar/domains//' => 'calendar/domains', 'calendar/domains' => 'calendar/options', 'calendar/domains/' => 'calendar/options', + 'calendar/domains//' => 'calendar/options', ]; diff --git a/tests/specs/issue_fix/84_how_to_generate_controller_code_with_distinct_method_names_in_case_of_prefix_in_paths/index.yaml b/tests/specs/issue_fix/84_how_to_generate_controller_code_with_distinct_method_names_in_case_of_prefix_in_paths/index.yaml index 7cbbdbf9..681ae664 100644 --- a/tests/specs/issue_fix/84_how_to_generate_controller_code_with_distinct_method_names_in_case_of_prefix_in_paths/index.yaml +++ b/tests/specs/issue_fix/84_how_to_generate_controller_code_with_distinct_method_names_in_case_of_prefix_in_paths/index.yaml @@ -37,6 +37,28 @@ paths: '200': description: The Response + /calendar/domains/{id}/{id2}: + parameters: + - name: id + in: path + description: lorem ipsum + required: true + schema: + type: integer + - name: id2 + in: path + description: lorem ipsum + required: true + schema: + type: integer + get: + x-route: calendar/domains + summary: Lorem ipsum + description: Lorem ipsum description + responses: + '200': + description: The Response + components: From f37e45e0d21daa8b4685f4417d9ced0749f9895a Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Tue, 16 Jul 2024 20:57:44 +0530 Subject: [PATCH 082/358] Refactor and add docs --- README.md | 1 + src/generator/ApiGenerator.php | 2 +- src/lib/generators/RestActionGenerator.php | 12 ++++++------ src/lib/items/RestAction.php | 8 +++++++- 4 files changed, 15 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index f6bebf7b..7eeb62ce 100644 --- a/README.md +++ b/README.md @@ -382,6 +382,7 @@ Generated URL rules config for above is (in `urls.rest.php` or pertinent file): 'POST a1/b1' => 'abc/xyz', 'a1/b1' => 'abc/options', ``` +`x-route` does not support [Yii Modules](https://www.yiiframework.com/doc/guide/2.0/en/structure-modules). ## Many-to-Many relation definition diff --git a/src/generator/ApiGenerator.php b/src/generator/ApiGenerator.php index f31efb4c..5a1f83c5 100644 --- a/src/generator/ApiGenerator.php +++ b/src/generator/ApiGenerator.php @@ -474,7 +474,7 @@ public function generate():array $urlRulesGenerator = Yii::createObject(UrlRulesGenerator::class, [$config, $actions]); $files = $urlRulesGenerator->generate(); - $actions = static::removeDuplicateActions($actions); + $actions = static::removeDuplicateActions($actions); // in case of non-crud actions having custom route `x-route` set $controllersGenerator = Yii::createObject(ControllersGenerator::class, [$config, $actions]); $files->merge($controllersGenerator->generate()); diff --git a/src/lib/generators/RestActionGenerator.php b/src/lib/generators/RestActionGenerator.php index bd690467..9796be02 100644 --- a/src/lib/generators/RestActionGenerator.php +++ b/src/lib/generators/RestActionGenerator.php @@ -79,19 +79,19 @@ protected function resolvePath(string $path, PathItem $pathItem):array } // TODO rename - $actionHere = $this->prepareAction($method, $operation, $routeData, $customRoute); + $action = $this->prepareAction($method, $operation, $routeData, $customRoute); if ($customRoute !== null) { if (in_array($customRoute, array_keys($this->allCustomRoutes))) { - $actionHere->isDuplicate = true; - if ($actionHere->params !== $this->allCustomRoutes[$customRoute]) { + $action->isDuplicate = true; + if ($action->params !== $this->allCustomRoutes[$customRoute]) { $this->allCustomRoutes[$customRoute]->isOriginalForCustomRoute = true; } } else { - $actionHere->isDuplicate = false; - $this->allCustomRoutes[$customRoute] = $actionHere; + $action->isDuplicate = false; + $this->allCustomRoutes[$customRoute] = $action; } } - $actions[] = $actionHere; + $actions[] = $action; } return $actions; } diff --git a/src/lib/items/RestAction.php b/src/lib/items/RestAction.php index cd97abd3..fc82712f 100644 --- a/src/lib/items/RestAction.php +++ b/src/lib/items/RestAction.php @@ -71,13 +71,19 @@ final class RestAction extends BaseObject /** * @var bool * @see $isDuplicate + * https://github.com/cebe/yii2-openapi/issues/84 + * see `x-route` in README.md + * Used for generating only one action for paths like: `GET /calendar/domains` and `GET /calendar/domains/{id}` given that they have same `x-route`. + * This is used to flag first of one or more duplicates */ public $isOriginalForCustomRoute = false; + /** * @var bool * https://github.com/cebe/yii2-openapi/issues/84 - * Generate only one action for paths like: `GET /calendar/domains` and `GET /calendar/domains/{id}`. + * Generate only one action for paths like: `GET /calendar/domains` and `GET /calendar/domains/{id}` given that they have same `x-route`. * @see $isOriginalForCustomRoute + * see `x-route` in README.md */ public $isDuplicate = false; From 48e07b251069874b4e47914c0bfcceca9842ba85 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Thu, 25 Jul 2024 10:52:45 +0530 Subject: [PATCH 083/358] Undo disable sorting for non dependent models --- src/lib/generators/MigrationsGenerator.php | 29 ++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/src/lib/generators/MigrationsGenerator.php b/src/lib/generators/MigrationsGenerator.php index 828b7c30..4a22e6f8 100644 --- a/src/lib/generators/MigrationsGenerator.php +++ b/src/lib/generators/MigrationsGenerator.php @@ -152,6 +152,9 @@ protected function createBuilder(DbModel $model):BaseMigrationBuilder protected function sortMigrationsByDeps():array { $this->sorted = []; + if ($this->shouldSortMigrations($this->migrations)) { + ksort($this->migrations); + } foreach ($this->migrations as $migration) { //echo "adding {$migration->tableAlias}\n"; $this->sortByDependencyRecurse($migration); @@ -181,4 +184,30 @@ protected function sortByDependencyRecurse(MigrationModel $migration):void throw new Exception("A circular dependency is detected for table '{$migration->tableAlias}'."); } } + + /** + * Are tables to drop are internally dependent? If yes then don't sort (ksort) + * @param $migrations array (tableAlias => MigrationModel)[] + */ + public function shouldSortMigrations(array $migrations): bool + { + $tables = array_keys($migrations); + + foreach ($this->models as $dbModel) { + /** @var DbModel $dbModel */ + if ($dbModel->drop) { + $ts = Yii::$app->db->getTableSchema('{{%'.$dbModel->tableName.'}}', true); + if ($ts) { + foreach ($ts->foreignKeys as $fk) { + $fkTableName = str_replace(Yii::$app->db->tablePrefix, '{{%', $fk[0]); + $fkTableName .= '}}'; + if (in_array($fkTableName, $tables)) { + return false; + } + } + } + } + } + return true; + } } From cf12d6f8985eb5decc69bb47f71bc138c3831505 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Thu, 25 Jul 2024 15:23:41 +0530 Subject: [PATCH 084/358] Add test for independent tables drop sort --- src/lib/generators/MigrationsGenerator.php | 4 +- .../index.php | 13 ++++ .../index.yaml | 31 ++++++++++ .../m200000_000000_delete_table_bigpks.php | 20 ++++++ .../m200000_000001_create_table_foos.php | 20 ++++++ .../m200000_000002_delete_table_ubigpks.php | 26 ++++++++ .../m200000_000003_delete_table_upks.php | 20 ++++++ .../mysql/models/Bigpk.php | 10 +++ .../mysql/models/Foo.php | 10 +++ .../mysql/models/Ubigpk.php | 10 +++ .../mysql/models/Upk.php | 10 +++ .../mysql/models/base/Bigpk.php | 26 ++++++++ .../mysql/models/base/Foo.php | 25 ++++++++ .../mysql/models/base/Ubigpk.php | 46 ++++++++++++++ .../mysql/models/base/Upk.php | 26 ++++++++ tests/unit/IssueFixTest.php | 62 +++++++++++++++---- 16 files changed, 344 insertions(+), 15 deletions(-) create mode 100644 tests/specs/issue_fix/132_create_migration_for_drop_table/case_independent_tables_drop_sort/index.php create mode 100644 tests/specs/issue_fix/132_create_migration_for_drop_table/case_independent_tables_drop_sort/index.yaml create mode 100644 tests/specs/issue_fix/132_create_migration_for_drop_table/case_independent_tables_drop_sort/mysql/migrations_mysql_db/m200000_000000_delete_table_bigpks.php create mode 100644 tests/specs/issue_fix/132_create_migration_for_drop_table/case_independent_tables_drop_sort/mysql/migrations_mysql_db/m200000_000001_create_table_foos.php create mode 100644 tests/specs/issue_fix/132_create_migration_for_drop_table/case_independent_tables_drop_sort/mysql/migrations_mysql_db/m200000_000002_delete_table_ubigpks.php create mode 100644 tests/specs/issue_fix/132_create_migration_for_drop_table/case_independent_tables_drop_sort/mysql/migrations_mysql_db/m200000_000003_delete_table_upks.php create mode 100644 tests/specs/issue_fix/132_create_migration_for_drop_table/case_independent_tables_drop_sort/mysql/models/Bigpk.php create mode 100644 tests/specs/issue_fix/132_create_migration_for_drop_table/case_independent_tables_drop_sort/mysql/models/Foo.php create mode 100644 tests/specs/issue_fix/132_create_migration_for_drop_table/case_independent_tables_drop_sort/mysql/models/Ubigpk.php create mode 100644 tests/specs/issue_fix/132_create_migration_for_drop_table/case_independent_tables_drop_sort/mysql/models/Upk.php create mode 100644 tests/specs/issue_fix/132_create_migration_for_drop_table/case_independent_tables_drop_sort/mysql/models/base/Bigpk.php create mode 100644 tests/specs/issue_fix/132_create_migration_for_drop_table/case_independent_tables_drop_sort/mysql/models/base/Foo.php create mode 100644 tests/specs/issue_fix/132_create_migration_for_drop_table/case_independent_tables_drop_sort/mysql/models/base/Ubigpk.php create mode 100644 tests/specs/issue_fix/132_create_migration_for_drop_table/case_independent_tables_drop_sort/mysql/models/base/Upk.php diff --git a/src/lib/generators/MigrationsGenerator.php b/src/lib/generators/MigrationsGenerator.php index 4a22e6f8..1c0dfb51 100644 --- a/src/lib/generators/MigrationsGenerator.php +++ b/src/lib/generators/MigrationsGenerator.php @@ -152,7 +152,7 @@ protected function createBuilder(DbModel $model):BaseMigrationBuilder protected function sortMigrationsByDeps():array { $this->sorted = []; - if ($this->shouldSortMigrations($this->migrations)) { + if ($this->shouldSortMigrationsForDropTables($this->migrations)) { ksort($this->migrations); } foreach ($this->migrations as $migration) { @@ -189,7 +189,7 @@ protected function sortByDependencyRecurse(MigrationModel $migration):void * Are tables to drop are internally dependent? If yes then don't sort (ksort) * @param $migrations array (tableAlias => MigrationModel)[] */ - public function shouldSortMigrations(array $migrations): bool + public function shouldSortMigrationsForDropTables(array $migrations): bool { $tables = array_keys($migrations); diff --git a/tests/specs/issue_fix/132_create_migration_for_drop_table/case_independent_tables_drop_sort/index.php b/tests/specs/issue_fix/132_create_migration_for_drop_table/case_independent_tables_drop_sort/index.php new file mode 100644 index 00000000..3987f0d2 --- /dev/null +++ b/tests/specs/issue_fix/132_create_migration_for_drop_table/case_independent_tables_drop_sort/index.php @@ -0,0 +1,13 @@ + '@specs/issue_fix/132_create_migration_for_drop_table/case_independent_tables_drop_sort/index.yaml', + 'generateUrls' => false, + 'generateModels' => true, + 'excludeModels' => [ + 'Error', + ], + 'generateControllers' => false, + 'generateMigrations' => true, + 'generateModelFaker' => false, +]; diff --git a/tests/specs/issue_fix/132_create_migration_for_drop_table/case_independent_tables_drop_sort/index.yaml b/tests/specs/issue_fix/132_create_migration_for_drop_table/case_independent_tables_drop_sort/index.yaml new file mode 100644 index 00000000..7246c450 --- /dev/null +++ b/tests/specs/issue_fix/132_create_migration_for_drop_table/case_independent_tables_drop_sort/index.yaml @@ -0,0 +1,31 @@ +openapi: "3.0.0" +info: + version: 1.0.0 + title: 132_create_migration_for_drop_table \#132 + +x-deleted-schemas: + - Upk + - Bigpk + - Ubigpk + +paths: + /: + get: + summary: List + operationId: list + responses: + '200': + description: The information + +components: + schemas: + Foo: # if you remove this entire schema and want to remove its table then you need to add its table name in `x-deleted-schemas` + type: object + description: 132_create_migration_for_drop_table + required: + - id + properties: + id: + type: integer + factor: + type: integer diff --git a/tests/specs/issue_fix/132_create_migration_for_drop_table/case_independent_tables_drop_sort/mysql/migrations_mysql_db/m200000_000000_delete_table_bigpks.php b/tests/specs/issue_fix/132_create_migration_for_drop_table/case_independent_tables_drop_sort/mysql/migrations_mysql_db/m200000_000000_delete_table_bigpks.php new file mode 100644 index 00000000..9f129332 --- /dev/null +++ b/tests/specs/issue_fix/132_create_migration_for_drop_table/case_independent_tables_drop_sort/mysql/migrations_mysql_db/m200000_000000_delete_table_bigpks.php @@ -0,0 +1,20 @@ +dropTable('{{%bigpks}}'); + } + + public function down() + { + $this->createTable('{{%bigpks}}', [ + 'id' => $this->bigPrimaryKey(), + 'name' => $this->string(150)->null()->defaultValue(null), + ]); + } +} diff --git a/tests/specs/issue_fix/132_create_migration_for_drop_table/case_independent_tables_drop_sort/mysql/migrations_mysql_db/m200000_000001_create_table_foos.php b/tests/specs/issue_fix/132_create_migration_for_drop_table/case_independent_tables_drop_sort/mysql/migrations_mysql_db/m200000_000001_create_table_foos.php new file mode 100644 index 00000000..9f90d171 --- /dev/null +++ b/tests/specs/issue_fix/132_create_migration_for_drop_table/case_independent_tables_drop_sort/mysql/migrations_mysql_db/m200000_000001_create_table_foos.php @@ -0,0 +1,20 @@ +createTable('{{%foos}}', [ + 'id' => $this->primaryKey(), + 'factor' => $this->integer()->null()->defaultValue(null), + ]); + } + + public function down() + { + $this->dropTable('{{%foos}}'); + } +} diff --git a/tests/specs/issue_fix/132_create_migration_for_drop_table/case_independent_tables_drop_sort/mysql/migrations_mysql_db/m200000_000002_delete_table_ubigpks.php b/tests/specs/issue_fix/132_create_migration_for_drop_table/case_independent_tables_drop_sort/mysql/migrations_mysql_db/m200000_000002_delete_table_ubigpks.php new file mode 100644 index 00000000..574610ed --- /dev/null +++ b/tests/specs/issue_fix/132_create_migration_for_drop_table/case_independent_tables_drop_sort/mysql/migrations_mysql_db/m200000_000002_delete_table_ubigpks.php @@ -0,0 +1,26 @@ +dropTable('{{%ubigpks}}'); + } + + public function down() + { + $this->createTable('{{%ubigpks}}', [ + 'id' => $this->bigPrimaryKey()->unsigned(), + 'name' => $this->string(150)->null()->defaultValue(null), + 'size' => 'enum("x-small", "small", "medium", "large", "x-large") NOT NULL DEFAULT \'x-small\'', + 'd' => 'smallint(5) unsigned zerofill NULL DEFAULT NULL', + 'e' => 'mediumint(8) unsigned zerofill NULL DEFAULT NULL', + 'f' => 'decimal(12,4) NULL DEFAULT NULL', + 'dp' => $this->double()->null()->defaultValue(null), + 'dp2' => 'double(10,4) NULL DEFAULT NULL', + ]); + } +} diff --git a/tests/specs/issue_fix/132_create_migration_for_drop_table/case_independent_tables_drop_sort/mysql/migrations_mysql_db/m200000_000003_delete_table_upks.php b/tests/specs/issue_fix/132_create_migration_for_drop_table/case_independent_tables_drop_sort/mysql/migrations_mysql_db/m200000_000003_delete_table_upks.php new file mode 100644 index 00000000..e0261bf1 --- /dev/null +++ b/tests/specs/issue_fix/132_create_migration_for_drop_table/case_independent_tables_drop_sort/mysql/migrations_mysql_db/m200000_000003_delete_table_upks.php @@ -0,0 +1,20 @@ +dropTable('{{%upks}}'); + } + + public function down() + { + $this->createTable('{{%upks}}', [ + 'id' => $this->primaryKey()->unsigned(), + 'name' => $this->string(150)->null()->defaultValue(null), + ]); + } +} diff --git a/tests/specs/issue_fix/132_create_migration_for_drop_table/case_independent_tables_drop_sort/mysql/models/Bigpk.php b/tests/specs/issue_fix/132_create_migration_for_drop_table/case_independent_tables_drop_sort/mysql/models/Bigpk.php new file mode 100644 index 00000000..4f078c1b --- /dev/null +++ b/tests/specs/issue_fix/132_create_migration_for_drop_table/case_independent_tables_drop_sort/mysql/models/Bigpk.php @@ -0,0 +1,10 @@ + [['name'], 'trim'], + 'name_string' => [['name'], 'string', 'max' => 150], + ]; + } +} diff --git a/tests/specs/issue_fix/132_create_migration_for_drop_table/case_independent_tables_drop_sort/mysql/models/base/Foo.php b/tests/specs/issue_fix/132_create_migration_for_drop_table/case_independent_tables_drop_sort/mysql/models/base/Foo.php new file mode 100644 index 00000000..49c10419 --- /dev/null +++ b/tests/specs/issue_fix/132_create_migration_for_drop_table/case_independent_tables_drop_sort/mysql/models/base/Foo.php @@ -0,0 +1,25 @@ + [['factor'], 'integer'], + ]; + } +} diff --git a/tests/specs/issue_fix/132_create_migration_for_drop_table/case_independent_tables_drop_sort/mysql/models/base/Ubigpk.php b/tests/specs/issue_fix/132_create_migration_for_drop_table/case_independent_tables_drop_sort/mysql/models/base/Ubigpk.php new file mode 100644 index 00000000..3ffa6a51 --- /dev/null +++ b/tests/specs/issue_fix/132_create_migration_for_drop_table/case_independent_tables_drop_sort/mysql/models/base/Ubigpk.php @@ -0,0 +1,46 @@ + [['name', 'f'], 'trim'], + 'name_string' => [['name'], 'string', 'max' => 150], + 'size_string' => [['size'], 'string'], + 'size_in' => [['size'], 'in', 'range' => [ + 'x-small', + 'small', + 'medium', + 'large', + 'x-large', + ]], + 'size_default' => [['size'], 'default', 'value' => 'x-small'], + 'd_integer' => [['d'], 'integer'], + 'e_integer' => [['e'], 'integer'], + 'f_string' => [['f'], 'string', 'max' => 12], + 'dp_double' => [['dp'], 'double'], + 'dp2_double' => [['dp2'], 'double'], + ]; + } +} diff --git a/tests/specs/issue_fix/132_create_migration_for_drop_table/case_independent_tables_drop_sort/mysql/models/base/Upk.php b/tests/specs/issue_fix/132_create_migration_for_drop_table/case_independent_tables_drop_sort/mysql/models/base/Upk.php new file mode 100644 index 00000000..644bc0d1 --- /dev/null +++ b/tests/specs/issue_fix/132_create_migration_for_drop_table/case_independent_tables_drop_sort/mysql/models/base/Upk.php @@ -0,0 +1,26 @@ + [['name'], 'trim'], + 'name_string' => [['name'], 'string', 'max' => 150], + ]; + } +} diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index 402d852d..757e26c8 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -241,23 +241,59 @@ public function testNullableFalseInRequired() // Create migration for drop table if a entire schema is deleted from OpenAPI spec #132 // https://github.com/cebe/yii2-openapi/issues/132 - public function testCreateMigrationForDropTable132() - { - $testFile = Yii::getAlias("@specs/issue_fix/132_create_migration_for_drop_table/132_create_migration_for_drop_table.php"); - $this->createTablesForCreateMigrationForDropTable132(); - $this->runGenerator($testFile); - $this->runActualMigrations('mysql', 8); + // https://github.com/php-openapi/yii2-openapi/pull/4#discussion_r1688225258 + public function testCreateMigrationForDropTable132IndependentTablesDropSort() + { + $testFile = Yii::getAlias("@specs/issue_fix/132_create_migration_for_drop_table/case_independent_tables_drop_sort/index.php"); + $this->createTablesForCreateMigrationForDropTable132(); + $this->runGenerator($testFile); + $this->runActualMigrations('mysql', 4); - $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ + $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ 'recursive' => true, - ]); - $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/132_create_migration_for_drop_table/mysql"), [ + ]); + $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/132_create_migration_for_drop_table/case_independent_tables_drop_sort/mysql"), [ 'recursive' => true, - ]); - $this->checkFiles($actualFiles, $expectedFiles); + ]); + $this->checkFiles($actualFiles, $expectedFiles); - $this->deleteTablesForCreateMigrationForDropTable132(); - } + $this->deleteTablesForCreateMigrationForDropTable132(); + } + + // Create migration for drop table if a entire schema is deleted from OpenAPI spec #132 + // https://github.com/cebe/yii2-openapi/issues/132 + public function testCreateMigrationForDropTable132() + { + $testFile = Yii::getAlias("@specs/issue_fix/132_create_migration_for_drop_table/132_create_migration_for_drop_table.php"); + + Yii::$app->db->createCommand()->createTable('{{%upks}}', [ + 'id' => 'upk', + 'name' => 'string(150)', + ])->execute(); + Yii::$app->db->createCommand()->createTable('{{%bigpks}}', [ + 'id' => 'bigpk', + 'name' => 'string(150)', + ])->execute(); + Yii::$app->db->createCommand()->createTable('{{%ubigpks}}', [ + 'id' => 'ubigpk', + 'name' => 'string(150)', + ])->execute(); + + $this->runGenerator($testFile); + $this->runActualMigrations('mysql', 3); + + $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ + 'recursive' => true, + ]); + $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/132_create_migration_for_drop_table/mysql"), [ + 'recursive' => true, + ]); + $this->checkFiles($actualFiles, $expectedFiles); + + Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%bigpks}}')->execute(); + Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%bigpks}}')->execute(); + Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%bigpks}}')->execute(); + } private function createTablesForCreateMigrationForDropTable132() { From 74ca15a5ac7f3989904d478110613554fad4ba84 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Thu, 25 Jul 2024 15:25:22 +0530 Subject: [PATCH 085/358] Revert "Fix another failing tests - MultiDbSecondaryMigrationTest" This reverts commit a4dc0a46b749b2ed7e5373a5f976cce5f6888548. --- ...le_v2_posts.php => m200000_000000_change_table_v2_posts.php} | 2 +- .../m200000_000001_create_table_v2_tags.php} | 2 +- ...osts2tags.php => m200000_000002_create_table_posts2tags.php} | 2 +- ...gories.php => m200000_000003_change_table_v2_categories.php} | 2 +- ...le_v2_users.php => m200000_000004_change_table_v2_users.php} | 2 +- ...le_v2_posts.php => m200000_000000_change_table_v2_posts.php} | 2 +- .../m200000_000001_create_table_v2_tags.php} | 2 +- ...osts2tags.php => m200000_000002_create_table_posts2tags.php} | 2 +- ...gories.php => m200000_000003_change_table_v2_categories.php} | 2 +- ...le_v2_users.php => m200000_000004_change_table_v2_users.php} | 2 +- ...le_v2_posts.php => m200000_000000_change_table_v2_posts.php} | 2 +- ...able_v2_tags.php => m200000_000001_create_table_v2_tags.php} | 2 +- ...osts2tags.php => m200000_000002_create_table_posts2tags.php} | 2 +- ...gories.php => m200000_000003_change_table_v2_categories.php} | 2 +- ...le_v2_users.php => m200000_000004_change_table_v2_users.php} | 2 +- 15 files changed, 15 insertions(+), 15 deletions(-) rename tests/specs/blog_v2/migrations_maria_db/{m200000_000002_change_table_v2_posts.php => m200000_000000_change_table_v2_posts.php} (95%) rename tests/specs/blog_v2/{migrations_mysql_db/m200000_000003_create_table_v2_tags.php => migrations_maria_db/m200000_000001_create_table_v2_tags.php} (88%) rename tests/specs/blog_v2/migrations_maria_db/{m200000_000004_create_table_posts2tags.php => m200000_000002_create_table_posts2tags.php} (93%) rename tests/specs/blog_v2/migrations_maria_db/{m200000_000001_change_table_v2_categories.php => m200000_000003_change_table_v2_categories.php} (94%) rename tests/specs/blog_v2/migrations_maria_db/{m200000_000000_change_table_v2_users.php => m200000_000004_change_table_v2_users.php} (95%) rename tests/specs/blog_v2/migrations_mysql_db/{m200000_000002_change_table_v2_posts.php => m200000_000000_change_table_v2_posts.php} (95%) rename tests/specs/blog_v2/{migrations_maria_db/m200000_000003_create_table_v2_tags.php => migrations_mysql_db/m200000_000001_create_table_v2_tags.php} (88%) rename tests/specs/blog_v2/migrations_mysql_db/{m200000_000004_create_table_posts2tags.php => m200000_000002_create_table_posts2tags.php} (93%) rename tests/specs/blog_v2/migrations_mysql_db/{m200000_000001_change_table_v2_categories.php => m200000_000003_change_table_v2_categories.php} (94%) rename tests/specs/blog_v2/migrations_mysql_db/{m200000_000000_change_table_v2_users.php => m200000_000004_change_table_v2_users.php} (95%) rename tests/specs/blog_v2/migrations_pgsql_db/{m200000_000002_change_table_v2_posts.php => m200000_000000_change_table_v2_posts.php} (95%) rename tests/specs/blog_v2/migrations_pgsql_db/{m200000_000003_create_table_v2_tags.php => m200000_000001_create_table_v2_tags.php} (91%) rename tests/specs/blog_v2/migrations_pgsql_db/{m200000_000004_create_table_posts2tags.php => m200000_000002_create_table_posts2tags.php} (93%) rename tests/specs/blog_v2/migrations_pgsql_db/{m200000_000001_change_table_v2_categories.php => m200000_000003_change_table_v2_categories.php} (93%) rename tests/specs/blog_v2/migrations_pgsql_db/{m200000_000000_change_table_v2_users.php => m200000_000004_change_table_v2_users.php} (96%) diff --git a/tests/specs/blog_v2/migrations_maria_db/m200000_000002_change_table_v2_posts.php b/tests/specs/blog_v2/migrations_maria_db/m200000_000000_change_table_v2_posts.php similarity index 95% rename from tests/specs/blog_v2/migrations_maria_db/m200000_000002_change_table_v2_posts.php rename to tests/specs/blog_v2/migrations_maria_db/m200000_000000_change_table_v2_posts.php index f8790fd3..5c43dabf 100644 --- a/tests/specs/blog_v2/migrations_maria_db/m200000_000002_change_table_v2_posts.php +++ b/tests/specs/blog_v2/migrations_maria_db/m200000_000000_change_table_v2_posts.php @@ -3,7 +3,7 @@ /** * Table for Post */ -class m200000_000002_change_table_v2_posts extends \yii\db\Migration +class m200000_000000_change_table_v2_posts extends \yii\db\Migration { public function up() { diff --git a/tests/specs/blog_v2/migrations_mysql_db/m200000_000003_create_table_v2_tags.php b/tests/specs/blog_v2/migrations_maria_db/m200000_000001_create_table_v2_tags.php similarity index 88% rename from tests/specs/blog_v2/migrations_mysql_db/m200000_000003_create_table_v2_tags.php rename to tests/specs/blog_v2/migrations_maria_db/m200000_000001_create_table_v2_tags.php index 5ed6326c..1e671e96 100644 --- a/tests/specs/blog_v2/migrations_mysql_db/m200000_000003_create_table_v2_tags.php +++ b/tests/specs/blog_v2/migrations_maria_db/m200000_000001_create_table_v2_tags.php @@ -3,7 +3,7 @@ /** * Table for Tag */ -class m200000_000003_create_table_v2_tags extends \yii\db\Migration +class m200000_000001_create_table_v2_tags extends \yii\db\Migration { public function up() { diff --git a/tests/specs/blog_v2/migrations_maria_db/m200000_000004_create_table_posts2tags.php b/tests/specs/blog_v2/migrations_maria_db/m200000_000002_create_table_posts2tags.php similarity index 93% rename from tests/specs/blog_v2/migrations_maria_db/m200000_000004_create_table_posts2tags.php rename to tests/specs/blog_v2/migrations_maria_db/m200000_000002_create_table_posts2tags.php index 9e50b861..2e959d10 100644 --- a/tests/specs/blog_v2/migrations_maria_db/m200000_000004_create_table_posts2tags.php +++ b/tests/specs/blog_v2/migrations_maria_db/m200000_000002_create_table_posts2tags.php @@ -3,7 +3,7 @@ /** * Table for Posts2Tags */ -class m200000_000004_create_table_posts2tags extends \yii\db\Migration +class m200000_000002_create_table_posts2tags extends \yii\db\Migration { public function up() { diff --git a/tests/specs/blog_v2/migrations_maria_db/m200000_000001_change_table_v2_categories.php b/tests/specs/blog_v2/migrations_maria_db/m200000_000003_change_table_v2_categories.php similarity index 94% rename from tests/specs/blog_v2/migrations_maria_db/m200000_000001_change_table_v2_categories.php rename to tests/specs/blog_v2/migrations_maria_db/m200000_000003_change_table_v2_categories.php index c488ec52..e608ed52 100644 --- a/tests/specs/blog_v2/migrations_maria_db/m200000_000001_change_table_v2_categories.php +++ b/tests/specs/blog_v2/migrations_maria_db/m200000_000003_change_table_v2_categories.php @@ -3,7 +3,7 @@ /** * Table for Category */ -class m200000_000001_change_table_v2_categories extends \yii\db\Migration +class m200000_000003_change_table_v2_categories extends \yii\db\Migration { public function up() { diff --git a/tests/specs/blog_v2/migrations_maria_db/m200000_000000_change_table_v2_users.php b/tests/specs/blog_v2/migrations_maria_db/m200000_000004_change_table_v2_users.php similarity index 95% rename from tests/specs/blog_v2/migrations_maria_db/m200000_000000_change_table_v2_users.php rename to tests/specs/blog_v2/migrations_maria_db/m200000_000004_change_table_v2_users.php index 4a946df2..bf1c82fd 100644 --- a/tests/specs/blog_v2/migrations_maria_db/m200000_000000_change_table_v2_users.php +++ b/tests/specs/blog_v2/migrations_maria_db/m200000_000004_change_table_v2_users.php @@ -3,7 +3,7 @@ /** * Table for User */ -class m200000_000000_change_table_v2_users extends \yii\db\Migration +class m200000_000004_change_table_v2_users extends \yii\db\Migration { public function up() { diff --git a/tests/specs/blog_v2/migrations_mysql_db/m200000_000002_change_table_v2_posts.php b/tests/specs/blog_v2/migrations_mysql_db/m200000_000000_change_table_v2_posts.php similarity index 95% rename from tests/specs/blog_v2/migrations_mysql_db/m200000_000002_change_table_v2_posts.php rename to tests/specs/blog_v2/migrations_mysql_db/m200000_000000_change_table_v2_posts.php index d3b7fc2b..be309829 100644 --- a/tests/specs/blog_v2/migrations_mysql_db/m200000_000002_change_table_v2_posts.php +++ b/tests/specs/blog_v2/migrations_mysql_db/m200000_000000_change_table_v2_posts.php @@ -3,7 +3,7 @@ /** * Table for Post */ -class m200000_000002_change_table_v2_posts extends \yii\db\Migration +class m200000_000000_change_table_v2_posts extends \yii\db\Migration { public function up() { diff --git a/tests/specs/blog_v2/migrations_maria_db/m200000_000003_create_table_v2_tags.php b/tests/specs/blog_v2/migrations_mysql_db/m200000_000001_create_table_v2_tags.php similarity index 88% rename from tests/specs/blog_v2/migrations_maria_db/m200000_000003_create_table_v2_tags.php rename to tests/specs/blog_v2/migrations_mysql_db/m200000_000001_create_table_v2_tags.php index 5ed6326c..1e671e96 100644 --- a/tests/specs/blog_v2/migrations_maria_db/m200000_000003_create_table_v2_tags.php +++ b/tests/specs/blog_v2/migrations_mysql_db/m200000_000001_create_table_v2_tags.php @@ -3,7 +3,7 @@ /** * Table for Tag */ -class m200000_000003_create_table_v2_tags extends \yii\db\Migration +class m200000_000001_create_table_v2_tags extends \yii\db\Migration { public function up() { diff --git a/tests/specs/blog_v2/migrations_mysql_db/m200000_000004_create_table_posts2tags.php b/tests/specs/blog_v2/migrations_mysql_db/m200000_000002_create_table_posts2tags.php similarity index 93% rename from tests/specs/blog_v2/migrations_mysql_db/m200000_000004_create_table_posts2tags.php rename to tests/specs/blog_v2/migrations_mysql_db/m200000_000002_create_table_posts2tags.php index 9e50b861..2e959d10 100644 --- a/tests/specs/blog_v2/migrations_mysql_db/m200000_000004_create_table_posts2tags.php +++ b/tests/specs/blog_v2/migrations_mysql_db/m200000_000002_create_table_posts2tags.php @@ -3,7 +3,7 @@ /** * Table for Posts2Tags */ -class m200000_000004_create_table_posts2tags extends \yii\db\Migration +class m200000_000002_create_table_posts2tags extends \yii\db\Migration { public function up() { diff --git a/tests/specs/blog_v2/migrations_mysql_db/m200000_000001_change_table_v2_categories.php b/tests/specs/blog_v2/migrations_mysql_db/m200000_000003_change_table_v2_categories.php similarity index 94% rename from tests/specs/blog_v2/migrations_mysql_db/m200000_000001_change_table_v2_categories.php rename to tests/specs/blog_v2/migrations_mysql_db/m200000_000003_change_table_v2_categories.php index c488ec52..e608ed52 100644 --- a/tests/specs/blog_v2/migrations_mysql_db/m200000_000001_change_table_v2_categories.php +++ b/tests/specs/blog_v2/migrations_mysql_db/m200000_000003_change_table_v2_categories.php @@ -3,7 +3,7 @@ /** * Table for Category */ -class m200000_000001_change_table_v2_categories extends \yii\db\Migration +class m200000_000003_change_table_v2_categories extends \yii\db\Migration { public function up() { diff --git a/tests/specs/blog_v2/migrations_mysql_db/m200000_000000_change_table_v2_users.php b/tests/specs/blog_v2/migrations_mysql_db/m200000_000004_change_table_v2_users.php similarity index 95% rename from tests/specs/blog_v2/migrations_mysql_db/m200000_000000_change_table_v2_users.php rename to tests/specs/blog_v2/migrations_mysql_db/m200000_000004_change_table_v2_users.php index 23a2e3b1..b7a1f5e3 100644 --- a/tests/specs/blog_v2/migrations_mysql_db/m200000_000000_change_table_v2_users.php +++ b/tests/specs/blog_v2/migrations_mysql_db/m200000_000004_change_table_v2_users.php @@ -3,7 +3,7 @@ /** * Table for User */ -class m200000_000000_change_table_v2_users extends \yii\db\Migration +class m200000_000004_change_table_v2_users extends \yii\db\Migration { public function up() { diff --git a/tests/specs/blog_v2/migrations_pgsql_db/m200000_000002_change_table_v2_posts.php b/tests/specs/blog_v2/migrations_pgsql_db/m200000_000000_change_table_v2_posts.php similarity index 95% rename from tests/specs/blog_v2/migrations_pgsql_db/m200000_000002_change_table_v2_posts.php rename to tests/specs/blog_v2/migrations_pgsql_db/m200000_000000_change_table_v2_posts.php index 474c6c82..5188983b 100644 --- a/tests/specs/blog_v2/migrations_pgsql_db/m200000_000002_change_table_v2_posts.php +++ b/tests/specs/blog_v2/migrations_pgsql_db/m200000_000000_change_table_v2_posts.php @@ -3,7 +3,7 @@ /** * Table for Post */ -class m200000_000002_change_table_v2_posts extends \yii\db\Migration +class m200000_000000_change_table_v2_posts extends \yii\db\Migration { public function safeUp() { diff --git a/tests/specs/blog_v2/migrations_pgsql_db/m200000_000003_create_table_v2_tags.php b/tests/specs/blog_v2/migrations_pgsql_db/m200000_000001_create_table_v2_tags.php similarity index 91% rename from tests/specs/blog_v2/migrations_pgsql_db/m200000_000003_create_table_v2_tags.php rename to tests/specs/blog_v2/migrations_pgsql_db/m200000_000001_create_table_v2_tags.php index 45593cfa..2466cff0 100644 --- a/tests/specs/blog_v2/migrations_pgsql_db/m200000_000003_create_table_v2_tags.php +++ b/tests/specs/blog_v2/migrations_pgsql_db/m200000_000001_create_table_v2_tags.php @@ -3,7 +3,7 @@ /** * Table for Tag */ -class m200000_000003_create_table_v2_tags extends \yii\db\Migration +class m200000_000001_create_table_v2_tags extends \yii\db\Migration { public function safeUp() { diff --git a/tests/specs/blog_v2/migrations_pgsql_db/m200000_000004_create_table_posts2tags.php b/tests/specs/blog_v2/migrations_pgsql_db/m200000_000002_create_table_posts2tags.php similarity index 93% rename from tests/specs/blog_v2/migrations_pgsql_db/m200000_000004_create_table_posts2tags.php rename to tests/specs/blog_v2/migrations_pgsql_db/m200000_000002_create_table_posts2tags.php index 4e4766fa..d518ff32 100644 --- a/tests/specs/blog_v2/migrations_pgsql_db/m200000_000004_create_table_posts2tags.php +++ b/tests/specs/blog_v2/migrations_pgsql_db/m200000_000002_create_table_posts2tags.php @@ -3,7 +3,7 @@ /** * Table for Posts2Tags */ -class m200000_000004_create_table_posts2tags extends \yii\db\Migration +class m200000_000002_create_table_posts2tags extends \yii\db\Migration { public function safeUp() { diff --git a/tests/specs/blog_v2/migrations_pgsql_db/m200000_000001_change_table_v2_categories.php b/tests/specs/blog_v2/migrations_pgsql_db/m200000_000003_change_table_v2_categories.php similarity index 93% rename from tests/specs/blog_v2/migrations_pgsql_db/m200000_000001_change_table_v2_categories.php rename to tests/specs/blog_v2/migrations_pgsql_db/m200000_000003_change_table_v2_categories.php index 9c307743..5f934936 100644 --- a/tests/specs/blog_v2/migrations_pgsql_db/m200000_000001_change_table_v2_categories.php +++ b/tests/specs/blog_v2/migrations_pgsql_db/m200000_000003_change_table_v2_categories.php @@ -3,7 +3,7 @@ /** * Table for Category */ -class m200000_000001_change_table_v2_categories extends \yii\db\Migration +class m200000_000003_change_table_v2_categories extends \yii\db\Migration { public function safeUp() { diff --git a/tests/specs/blog_v2/migrations_pgsql_db/m200000_000000_change_table_v2_users.php b/tests/specs/blog_v2/migrations_pgsql_db/m200000_000004_change_table_v2_users.php similarity index 96% rename from tests/specs/blog_v2/migrations_pgsql_db/m200000_000000_change_table_v2_users.php rename to tests/specs/blog_v2/migrations_pgsql_db/m200000_000004_change_table_v2_users.php index cb77b61d..a57ea8df 100644 --- a/tests/specs/blog_v2/migrations_pgsql_db/m200000_000000_change_table_v2_users.php +++ b/tests/specs/blog_v2/migrations_pgsql_db/m200000_000004_change_table_v2_users.php @@ -3,7 +3,7 @@ /** * Table for User */ -class m200000_000000_change_table_v2_users extends \yii\db\Migration +class m200000_000004_change_table_v2_users extends \yii\db\Migration { public function safeUp() { From 9932d26232f3bf7804eddff0dfb0bb9ce9da3ac8 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Thu, 25 Jul 2024 15:26:56 +0530 Subject: [PATCH 086/358] Revert "Fix another failing tests - NewColumnPositionTest::testAddOneNewColumnAtFirstPosition" This reverts commit 3a1499b37cc587639d2dbcce2122ad46c9e9b655. --- ... => m200000_000000_change_table_addtwonewcolinbetween2s.php} | 2 +- ...p => m200000_000001_change_table_addtwonewcolinbetweens.php} | 2 +- ...stcols.php => m200000_000002_change_table_dropfirstcols.php} | 2 +- ...ols.php => m200000_000003_change_table_dropfirsttwocols.php} | 2 +- ...able_fruit2s.php => m200000_000004_change_table_fruit2s.php} | 2 +- ..._table_fruits.php => m200000_000005_change_table_fruits.php} | 2 +- ...le_twocol2s.php => m200000_000006_change_table_twocol2s.php} | 2 +- ...able_twocols.php => m200000_000007_change_table_twocols.php} | 2 +- ...2s.php => m200000_000008_change_table_twonewcolatlast2s.php} | 2 +- ...sts.php => m200000_000009_change_table_twonewcolatlasts.php} | 2 +- ... => m200000_000000_change_table_addtwonewcolinbetween2s.php} | 2 +- ...p => m200000_000001_change_table_addtwonewcolinbetweens.php} | 2 +- ...stcols.php => m200000_000002_change_table_dropfirstcols.php} | 2 +- ...ols.php => m200000_000003_change_table_dropfirsttwocols.php} | 2 +- ...able_fruit2s.php => m200000_000004_change_table_fruit2s.php} | 2 +- ..._table_fruits.php => m200000_000005_change_table_fruits.php} | 2 +- ...le_twocol2s.php => m200000_000006_change_table_twocol2s.php} | 2 +- ...able_twocols.php => m200000_000007_change_table_twocols.php} | 2 +- ...2s.php => m200000_000008_change_table_twonewcolatlast2s.php} | 2 +- ...sts.php => m200000_000009_change_table_twonewcolatlasts.php} | 2 +- 20 files changed, 20 insertions(+), 20 deletions(-) rename tests/specs/new_column_position/maria/app/migrations_maria_db/{m200000_000007_change_table_addtwonewcolinbetween2s.php => m200000_000000_change_table_addtwonewcolinbetween2s.php} (92%) rename tests/specs/new_column_position/maria/app/migrations_maria_db/{m200000_000006_change_table_addtwonewcolinbetweens.php => m200000_000001_change_table_addtwonewcolinbetweens.php} (92%) rename tests/specs/new_column_position/maria/app/migrations_maria_db/{m200000_000004_change_table_dropfirstcols.php => m200000_000002_change_table_dropfirstcols.php} (82%) rename tests/specs/new_column_position/maria/app/migrations_maria_db/{m200000_000005_change_table_dropfirsttwocols.php => m200000_000003_change_table_dropfirsttwocols.php} (88%) rename tests/specs/new_column_position/maria/app/migrations_maria_db/{m200000_000001_change_table_fruit2s.php => m200000_000004_change_table_fruit2s.php} (81%) rename tests/specs/new_column_position/maria/app/migrations_maria_db/{m200000_000000_change_table_fruits.php => m200000_000005_change_table_fruits.php} (79%) rename tests/specs/new_column_position/maria/app/migrations_maria_db/{m200000_000003_change_table_twocol2s.php => m200000_000006_change_table_twocol2s.php} (88%) rename tests/specs/new_column_position/maria/app/migrations_maria_db/{m200000_000002_change_table_twocols.php => m200000_000007_change_table_twocols.php} (87%) rename tests/specs/new_column_position/maria/app/migrations_maria_db/{m200000_000009_change_table_twonewcolatlast2s.php => m200000_000008_change_table_twonewcolatlast2s.php} (89%) rename tests/specs/new_column_position/maria/app/migrations_maria_db/{m200000_000008_change_table_twonewcolatlasts.php => m200000_000009_change_table_twonewcolatlasts.php} (88%) rename tests/specs/new_column_position/mysql/app/migrations_mysql_db/{m200000_000007_change_table_addtwonewcolinbetween2s.php => m200000_000000_change_table_addtwonewcolinbetween2s.php} (92%) rename tests/specs/new_column_position/mysql/app/migrations_mysql_db/{m200000_000006_change_table_addtwonewcolinbetweens.php => m200000_000001_change_table_addtwonewcolinbetweens.php} (91%) rename tests/specs/new_column_position/mysql/app/migrations_mysql_db/{m200000_000004_change_table_dropfirstcols.php => m200000_000002_change_table_dropfirstcols.php} (81%) rename tests/specs/new_column_position/mysql/app/migrations_mysql_db/{m200000_000005_change_table_dropfirsttwocols.php => m200000_000003_change_table_dropfirsttwocols.php} (87%) rename tests/specs/new_column_position/mysql/app/migrations_mysql_db/{m200000_000001_change_table_fruit2s.php => m200000_000004_change_table_fruit2s.php} (81%) rename tests/specs/new_column_position/mysql/app/migrations_mysql_db/{m200000_000000_change_table_fruits.php => m200000_000005_change_table_fruits.php} (79%) rename tests/specs/new_column_position/mysql/app/migrations_mysql_db/{m200000_000003_change_table_twocol2s.php => m200000_000006_change_table_twocol2s.php} (87%) rename tests/specs/new_column_position/mysql/app/migrations_mysql_db/{m200000_000002_change_table_twocols.php => m200000_000007_change_table_twocols.php} (86%) rename tests/specs/new_column_position/mysql/app/migrations_mysql_db/{m200000_000009_change_table_twonewcolatlast2s.php => m200000_000008_change_table_twonewcolatlast2s.php} (88%) rename tests/specs/new_column_position/mysql/app/migrations_mysql_db/{m200000_000008_change_table_twonewcolatlasts.php => m200000_000009_change_table_twonewcolatlasts.php} (88%) diff --git a/tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000007_change_table_addtwonewcolinbetween2s.php b/tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000000_change_table_addtwonewcolinbetween2s.php similarity index 92% rename from tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000007_change_table_addtwonewcolinbetween2s.php rename to tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000000_change_table_addtwonewcolinbetween2s.php index 002a045e..544d1084 100644 --- a/tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000007_change_table_addtwonewcolinbetween2s.php +++ b/tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000000_change_table_addtwonewcolinbetween2s.php @@ -3,7 +3,7 @@ /** * Table for Addtwonewcolinbetween2s */ -class m200000_000007_change_table_addtwonewcolinbetween2s extends \yii\db\Migration +class m200000_000000_change_table_addtwonewcolinbetween2s extends \yii\db\Migration { public function up() { diff --git a/tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000006_change_table_addtwonewcolinbetweens.php b/tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000001_change_table_addtwonewcolinbetweens.php similarity index 92% rename from tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000006_change_table_addtwonewcolinbetweens.php rename to tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000001_change_table_addtwonewcolinbetweens.php index 62790337..b9648922 100644 --- a/tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000006_change_table_addtwonewcolinbetweens.php +++ b/tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000001_change_table_addtwonewcolinbetweens.php @@ -3,7 +3,7 @@ /** * Table for Addtwonewcolinbetweens */ -class m200000_000006_change_table_addtwonewcolinbetweens extends \yii\db\Migration +class m200000_000001_change_table_addtwonewcolinbetweens extends \yii\db\Migration { public function up() { diff --git a/tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000004_change_table_dropfirstcols.php b/tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000002_change_table_dropfirstcols.php similarity index 82% rename from tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000004_change_table_dropfirstcols.php rename to tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000002_change_table_dropfirstcols.php index a6fcdbb9..56f0692d 100644 --- a/tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000004_change_table_dropfirstcols.php +++ b/tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000002_change_table_dropfirstcols.php @@ -3,7 +3,7 @@ /** * Table for Dropfirstcol */ -class m200000_000004_change_table_dropfirstcols extends \yii\db\Migration +class m200000_000002_change_table_dropfirstcols extends \yii\db\Migration { public function up() { diff --git a/tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000005_change_table_dropfirsttwocols.php b/tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000003_change_table_dropfirsttwocols.php similarity index 88% rename from tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000005_change_table_dropfirsttwocols.php rename to tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000003_change_table_dropfirsttwocols.php index 9d438149..89ef1937 100644 --- a/tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000005_change_table_dropfirsttwocols.php +++ b/tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000003_change_table_dropfirsttwocols.php @@ -3,7 +3,7 @@ /** * Table for Dropfirsttwocol */ -class m200000_000005_change_table_dropfirsttwocols extends \yii\db\Migration +class m200000_000003_change_table_dropfirsttwocols extends \yii\db\Migration { public function up() { diff --git a/tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000001_change_table_fruit2s.php b/tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000004_change_table_fruit2s.php similarity index 81% rename from tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000001_change_table_fruit2s.php rename to tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000004_change_table_fruit2s.php index 547fdbf2..68bfd09e 100644 --- a/tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000001_change_table_fruit2s.php +++ b/tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000004_change_table_fruit2s.php @@ -3,7 +3,7 @@ /** * Table for Fruit2 */ -class m200000_000001_change_table_fruit2s extends \yii\db\Migration +class m200000_000004_change_table_fruit2s extends \yii\db\Migration { public function up() { diff --git a/tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000000_change_table_fruits.php b/tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000005_change_table_fruits.php similarity index 79% rename from tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000000_change_table_fruits.php rename to tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000005_change_table_fruits.php index 2cb90b8e..8accdd87 100644 --- a/tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000000_change_table_fruits.php +++ b/tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000005_change_table_fruits.php @@ -3,7 +3,7 @@ /** * Table for Fruit */ -class m200000_000000_change_table_fruits extends \yii\db\Migration +class m200000_000005_change_table_fruits extends \yii\db\Migration { public function up() { diff --git a/tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000003_change_table_twocol2s.php b/tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000006_change_table_twocol2s.php similarity index 88% rename from tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000003_change_table_twocol2s.php rename to tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000006_change_table_twocol2s.php index 94f91d2f..45325e91 100644 --- a/tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000003_change_table_twocol2s.php +++ b/tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000006_change_table_twocol2s.php @@ -3,7 +3,7 @@ /** * Table for Twocol2 */ -class m200000_000003_change_table_twocol2s extends \yii\db\Migration +class m200000_000006_change_table_twocol2s extends \yii\db\Migration { public function up() { diff --git a/tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000002_change_table_twocols.php b/tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000007_change_table_twocols.php similarity index 87% rename from tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000002_change_table_twocols.php rename to tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000007_change_table_twocols.php index 0ee4668e..d63f7443 100644 --- a/tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000002_change_table_twocols.php +++ b/tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000007_change_table_twocols.php @@ -3,7 +3,7 @@ /** * Table for Twocol */ -class m200000_000002_change_table_twocols extends \yii\db\Migration +class m200000_000007_change_table_twocols extends \yii\db\Migration { public function up() { diff --git a/tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000009_change_table_twonewcolatlast2s.php b/tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000008_change_table_twonewcolatlast2s.php similarity index 89% rename from tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000009_change_table_twonewcolatlast2s.php rename to tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000008_change_table_twonewcolatlast2s.php index 51db951e..0a88452d 100644 --- a/tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000009_change_table_twonewcolatlast2s.php +++ b/tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000008_change_table_twonewcolatlast2s.php @@ -3,7 +3,7 @@ /** * Table for Twonewcolatlast2 */ -class m200000_000009_change_table_twonewcolatlast2s extends \yii\db\Migration +class m200000_000008_change_table_twonewcolatlast2s extends \yii\db\Migration { public function up() { diff --git a/tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000008_change_table_twonewcolatlasts.php b/tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000009_change_table_twonewcolatlasts.php similarity index 88% rename from tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000008_change_table_twonewcolatlasts.php rename to tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000009_change_table_twonewcolatlasts.php index 307f1375..0a332d7a 100644 --- a/tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000008_change_table_twonewcolatlasts.php +++ b/tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000009_change_table_twonewcolatlasts.php @@ -3,7 +3,7 @@ /** * Table for Twonewcolatlast */ -class m200000_000008_change_table_twonewcolatlasts extends \yii\db\Migration +class m200000_000009_change_table_twonewcolatlasts extends \yii\db\Migration { public function up() { diff --git a/tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000007_change_table_addtwonewcolinbetween2s.php b/tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000000_change_table_addtwonewcolinbetween2s.php similarity index 92% rename from tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000007_change_table_addtwonewcolinbetween2s.php rename to tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000000_change_table_addtwonewcolinbetween2s.php index 7fc2bd8d..7d4f8bfa 100644 --- a/tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000007_change_table_addtwonewcolinbetween2s.php +++ b/tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000000_change_table_addtwonewcolinbetween2s.php @@ -3,7 +3,7 @@ /** * Table for Addtwonewcolinbetween2s */ -class m200000_000007_change_table_addtwonewcolinbetween2s extends \yii\db\Migration +class m200000_000000_change_table_addtwonewcolinbetween2s extends \yii\db\Migration { public function up() { diff --git a/tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000006_change_table_addtwonewcolinbetweens.php b/tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000001_change_table_addtwonewcolinbetweens.php similarity index 91% rename from tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000006_change_table_addtwonewcolinbetweens.php rename to tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000001_change_table_addtwonewcolinbetweens.php index 963c74dc..355597ac 100644 --- a/tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000006_change_table_addtwonewcolinbetweens.php +++ b/tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000001_change_table_addtwonewcolinbetweens.php @@ -3,7 +3,7 @@ /** * Table for Addtwonewcolinbetweens */ -class m200000_000006_change_table_addtwonewcolinbetweens extends \yii\db\Migration +class m200000_000001_change_table_addtwonewcolinbetweens extends \yii\db\Migration { public function up() { diff --git a/tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000004_change_table_dropfirstcols.php b/tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000002_change_table_dropfirstcols.php similarity index 81% rename from tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000004_change_table_dropfirstcols.php rename to tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000002_change_table_dropfirstcols.php index a103bad4..4ae589d3 100644 --- a/tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000004_change_table_dropfirstcols.php +++ b/tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000002_change_table_dropfirstcols.php @@ -3,7 +3,7 @@ /** * Table for Dropfirstcol */ -class m200000_000004_change_table_dropfirstcols extends \yii\db\Migration +class m200000_000002_change_table_dropfirstcols extends \yii\db\Migration { public function up() { diff --git a/tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000005_change_table_dropfirsttwocols.php b/tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000003_change_table_dropfirsttwocols.php similarity index 87% rename from tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000005_change_table_dropfirsttwocols.php rename to tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000003_change_table_dropfirsttwocols.php index 482bfa72..aaa54835 100644 --- a/tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000005_change_table_dropfirsttwocols.php +++ b/tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000003_change_table_dropfirsttwocols.php @@ -3,7 +3,7 @@ /** * Table for Dropfirsttwocol */ -class m200000_000005_change_table_dropfirsttwocols extends \yii\db\Migration +class m200000_000003_change_table_dropfirsttwocols extends \yii\db\Migration { public function up() { diff --git a/tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000001_change_table_fruit2s.php b/tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000004_change_table_fruit2s.php similarity index 81% rename from tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000001_change_table_fruit2s.php rename to tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000004_change_table_fruit2s.php index 547fdbf2..68bfd09e 100644 --- a/tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000001_change_table_fruit2s.php +++ b/tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000004_change_table_fruit2s.php @@ -3,7 +3,7 @@ /** * Table for Fruit2 */ -class m200000_000001_change_table_fruit2s extends \yii\db\Migration +class m200000_000004_change_table_fruit2s extends \yii\db\Migration { public function up() { diff --git a/tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000000_change_table_fruits.php b/tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000005_change_table_fruits.php similarity index 79% rename from tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000000_change_table_fruits.php rename to tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000005_change_table_fruits.php index 2cb90b8e..8accdd87 100644 --- a/tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000000_change_table_fruits.php +++ b/tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000005_change_table_fruits.php @@ -3,7 +3,7 @@ /** * Table for Fruit */ -class m200000_000000_change_table_fruits extends \yii\db\Migration +class m200000_000005_change_table_fruits extends \yii\db\Migration { public function up() { diff --git a/tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000003_change_table_twocol2s.php b/tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000006_change_table_twocol2s.php similarity index 87% rename from tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000003_change_table_twocol2s.php rename to tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000006_change_table_twocol2s.php index 05585780..40e3d693 100644 --- a/tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000003_change_table_twocol2s.php +++ b/tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000006_change_table_twocol2s.php @@ -3,7 +3,7 @@ /** * Table for Twocol2 */ -class m200000_000003_change_table_twocol2s extends \yii\db\Migration +class m200000_000006_change_table_twocol2s extends \yii\db\Migration { public function up() { diff --git a/tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000002_change_table_twocols.php b/tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000007_change_table_twocols.php similarity index 86% rename from tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000002_change_table_twocols.php rename to tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000007_change_table_twocols.php index d49b200e..33c954e0 100644 --- a/tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000002_change_table_twocols.php +++ b/tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000007_change_table_twocols.php @@ -3,7 +3,7 @@ /** * Table for Twocol */ -class m200000_000002_change_table_twocols extends \yii\db\Migration +class m200000_000007_change_table_twocols extends \yii\db\Migration { public function up() { diff --git a/tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000009_change_table_twonewcolatlast2s.php b/tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000008_change_table_twonewcolatlast2s.php similarity index 88% rename from tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000009_change_table_twonewcolatlast2s.php rename to tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000008_change_table_twonewcolatlast2s.php index 85dbdb59..60931d95 100644 --- a/tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000009_change_table_twonewcolatlast2s.php +++ b/tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000008_change_table_twonewcolatlast2s.php @@ -3,7 +3,7 @@ /** * Table for Twonewcolatlast2 */ -class m200000_000009_change_table_twonewcolatlast2s extends \yii\db\Migration +class m200000_000008_change_table_twonewcolatlast2s extends \yii\db\Migration { public function up() { diff --git a/tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000008_change_table_twonewcolatlasts.php b/tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000009_change_table_twonewcolatlasts.php similarity index 88% rename from tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000008_change_table_twonewcolatlasts.php rename to tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000009_change_table_twonewcolatlasts.php index 307f1375..0a332d7a 100644 --- a/tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000008_change_table_twonewcolatlasts.php +++ b/tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000009_change_table_twonewcolatlasts.php @@ -3,7 +3,7 @@ /** * Table for Twonewcolatlast */ -class m200000_000008_change_table_twonewcolatlasts extends \yii\db\Migration +class m200000_000009_change_table_twonewcolatlasts extends \yii\db\Migration { public function up() { From bed7fbb7f856d81f966661d87f10e8850a090327 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Thu, 25 Jul 2024 15:27:56 +0530 Subject: [PATCH 087/358] Revert "Fix another failing tests - GeneratorTest::testGenerate" This reverts commit ba2ef56799d3c6ed77b0e8613f2714a8ca2dbd47. --- .../m200000_000000_create_table_categories.php} | 2 +- ...te_table_users.php => m200000_000001_create_table_users.php} | 2 +- .../m200000_000003_create_table_fakerable.php} | 2 +- .../m200000_000004_create_table_post_comments.php} | 2 +- .../m200000_000000_create_table_categories.php} | 2 +- .../m200000_000001_create_table_users.php} | 2 +- ..._fakerable.php => m200000_000003_create_table_fakerable.php} | 2 +- ...mments.php => m200000_000004_create_table_post_comments.php} | 2 +- .../m200000_000000_create_table_categories.php} | 2 +- .../m200000_000001_create_table_users.php} | 2 +- .../m200000_000003_create_table_fakerable.php} | 2 +- .../m200000_000004_create_table_post_comments.php} | 2 +- ...ategories.php => m200000_000000_create_table_categories.php} | 2 +- ...te_table_users.php => m200000_000001_create_table_users.php} | 2 +- ..._fakerable.php => m200000_000003_create_table_fakerable.php} | 2 +- ...mments.php => m200000_000004_create_table_post_comments.php} | 2 +- ...te_table_photo.php => m200000_000000_create_table_photo.php} | 2 +- ...te_table_posts.php => m200000_000001_create_table_posts.php} | 2 +- ...s2posts.php => m200000_000002_create_table_photos2posts.php} | 2 +- ...eate_table_tags.php => m200000_000003_create_table_tags.php} | 2 +- ...osts2tags.php => m200000_000004_create_table_posts2tags.php} | 2 +- ...aches.php => m200000_000005_create_table_posts_attaches.php} | 2 +- ...allery.php => m200000_000006_create_table_posts_gallery.php} | 2 +- 23 files changed, 23 insertions(+), 23 deletions(-) rename tests/specs/blog/{migrations_mysql_db/m200000_000001_create_table_categories.php => migrations/m200000_000000_create_table_categories.php} (91%) rename tests/specs/blog/migrations/{m200000_000000_create_table_users.php => m200000_000001_create_table_users.php} (94%) rename tests/specs/blog/{migrations_mysql_db/m200000_000004_create_table_fakerable.php => migrations/m200000_000003_create_table_fakerable.php} (95%) rename tests/specs/blog/{migrations_mysql_db/m200000_000003_create_table_post_comments.php => migrations/m200000_000004_create_table_post_comments.php} (93%) rename tests/specs/blog/{migrations/m200000_000001_create_table_categories.php => migrations_maria_db/m200000_000000_create_table_categories.php} (91%) rename tests/specs/blog/{migrations_mysql_db/m200000_000000_create_table_users.php => migrations_maria_db/m200000_000001_create_table_users.php} (94%) rename tests/specs/blog/migrations_maria_db/{m200000_000004_create_table_fakerable.php => m200000_000003_create_table_fakerable.php} (95%) rename tests/specs/blog/migrations_maria_db/{m200000_000003_create_table_post_comments.php => m200000_000004_create_table_post_comments.php} (94%) rename tests/specs/blog/{migrations_maria_db/m200000_000001_create_table_categories.php => migrations_mysql_db/m200000_000000_create_table_categories.php} (91%) rename tests/specs/blog/{migrations_maria_db/m200000_000000_create_table_users.php => migrations_mysql_db/m200000_000001_create_table_users.php} (94%) rename tests/specs/blog/{migrations/m200000_000004_create_table_fakerable.php => migrations_mysql_db/m200000_000003_create_table_fakerable.php} (95%) rename tests/specs/blog/{migrations/m200000_000003_create_table_post_comments.php => migrations_mysql_db/m200000_000004_create_table_post_comments.php} (93%) rename tests/specs/blog/migrations_pgsql_db/{m200000_000001_create_table_categories.php => m200000_000000_create_table_categories.php} (91%) rename tests/specs/blog/migrations_pgsql_db/{m200000_000000_create_table_users.php => m200000_000001_create_table_users.php} (94%) rename tests/specs/blog/migrations_pgsql_db/{m200000_000004_create_table_fakerable.php => m200000_000003_create_table_fakerable.php} (95%) rename tests/specs/blog/migrations_pgsql_db/{m200000_000003_create_table_post_comments.php => m200000_000004_create_table_post_comments.php} (94%) rename tests/specs/many2many/migrations/{m200000_000003_create_table_photo.php => m200000_000000_create_table_photo.php} (82%) rename tests/specs/many2many/migrations/{m200000_000000_create_table_posts.php => m200000_000001_create_table_posts.php} (82%) rename tests/specs/many2many/migrations/{m200000_000004_create_table_photos2posts.php => m200000_000002_create_table_photos2posts.php} (92%) rename tests/specs/many2many/migrations/{m200000_000001_create_table_tags.php => m200000_000003_create_table_tags.php} (82%) rename tests/specs/many2many/migrations/{m200000_000002_create_table_posts2tags.php => m200000_000004_create_table_posts2tags.php} (93%) rename tests/specs/many2many/migrations/{m200000_000006_create_table_posts_attaches.php => m200000_000005_create_table_posts_attaches.php} (93%) rename tests/specs/many2many/migrations/{m200000_000005_create_table_posts_gallery.php => m200000_000006_create_table_posts_gallery.php} (94%) diff --git a/tests/specs/blog/migrations_mysql_db/m200000_000001_create_table_categories.php b/tests/specs/blog/migrations/m200000_000000_create_table_categories.php similarity index 91% rename from tests/specs/blog/migrations_mysql_db/m200000_000001_create_table_categories.php rename to tests/specs/blog/migrations/m200000_000000_create_table_categories.php index 957966fb..0485cafc 100644 --- a/tests/specs/blog/migrations_mysql_db/m200000_000001_create_table_categories.php +++ b/tests/specs/blog/migrations/m200000_000000_create_table_categories.php @@ -3,7 +3,7 @@ /** * Table for Category */ -class m200000_000001_create_table_categories extends \yii\db\Migration +class m200000_000000_create_table_categories extends \yii\db\Migration { public function up() { diff --git a/tests/specs/blog/migrations/m200000_000000_create_table_users.php b/tests/specs/blog/migrations/m200000_000001_create_table_users.php similarity index 94% rename from tests/specs/blog/migrations/m200000_000000_create_table_users.php rename to tests/specs/blog/migrations/m200000_000001_create_table_users.php index de42dde7..a90792e9 100644 --- a/tests/specs/blog/migrations/m200000_000000_create_table_users.php +++ b/tests/specs/blog/migrations/m200000_000001_create_table_users.php @@ -3,7 +3,7 @@ /** * Table for User */ -class m200000_000000_create_table_users extends \yii\db\Migration +class m200000_000001_create_table_users extends \yii\db\Migration { public function up() { diff --git a/tests/specs/blog/migrations_mysql_db/m200000_000004_create_table_fakerable.php b/tests/specs/blog/migrations/m200000_000003_create_table_fakerable.php similarity index 95% rename from tests/specs/blog/migrations_mysql_db/m200000_000004_create_table_fakerable.php rename to tests/specs/blog/migrations/m200000_000003_create_table_fakerable.php index 82c4db07..0f3eebad 100644 --- a/tests/specs/blog/migrations_mysql_db/m200000_000004_create_table_fakerable.php +++ b/tests/specs/blog/migrations/m200000_000003_create_table_fakerable.php @@ -3,7 +3,7 @@ /** * Table for Fakerable */ -class m200000_000004_create_table_fakerable extends \yii\db\Migration +class m200000_000003_create_table_fakerable extends \yii\db\Migration { public function up() { diff --git a/tests/specs/blog/migrations_mysql_db/m200000_000003_create_table_post_comments.php b/tests/specs/blog/migrations/m200000_000004_create_table_post_comments.php similarity index 93% rename from tests/specs/blog/migrations_mysql_db/m200000_000003_create_table_post_comments.php rename to tests/specs/blog/migrations/m200000_000004_create_table_post_comments.php index 45b512c3..c16766da 100644 --- a/tests/specs/blog/migrations_mysql_db/m200000_000003_create_table_post_comments.php +++ b/tests/specs/blog/migrations/m200000_000004_create_table_post_comments.php @@ -3,7 +3,7 @@ /** * Table for Comment */ -class m200000_000003_create_table_post_comments extends \yii\db\Migration +class m200000_000004_create_table_post_comments extends \yii\db\Migration { public function up() { diff --git a/tests/specs/blog/migrations/m200000_000001_create_table_categories.php b/tests/specs/blog/migrations_maria_db/m200000_000000_create_table_categories.php similarity index 91% rename from tests/specs/blog/migrations/m200000_000001_create_table_categories.php rename to tests/specs/blog/migrations_maria_db/m200000_000000_create_table_categories.php index 957966fb..0485cafc 100644 --- a/tests/specs/blog/migrations/m200000_000001_create_table_categories.php +++ b/tests/specs/blog/migrations_maria_db/m200000_000000_create_table_categories.php @@ -3,7 +3,7 @@ /** * Table for Category */ -class m200000_000001_create_table_categories extends \yii\db\Migration +class m200000_000000_create_table_categories extends \yii\db\Migration { public function up() { diff --git a/tests/specs/blog/migrations_mysql_db/m200000_000000_create_table_users.php b/tests/specs/blog/migrations_maria_db/m200000_000001_create_table_users.php similarity index 94% rename from tests/specs/blog/migrations_mysql_db/m200000_000000_create_table_users.php rename to tests/specs/blog/migrations_maria_db/m200000_000001_create_table_users.php index de42dde7..a90792e9 100644 --- a/tests/specs/blog/migrations_mysql_db/m200000_000000_create_table_users.php +++ b/tests/specs/blog/migrations_maria_db/m200000_000001_create_table_users.php @@ -3,7 +3,7 @@ /** * Table for User */ -class m200000_000000_create_table_users extends \yii\db\Migration +class m200000_000001_create_table_users extends \yii\db\Migration { public function up() { diff --git a/tests/specs/blog/migrations_maria_db/m200000_000004_create_table_fakerable.php b/tests/specs/blog/migrations_maria_db/m200000_000003_create_table_fakerable.php similarity index 95% rename from tests/specs/blog/migrations_maria_db/m200000_000004_create_table_fakerable.php rename to tests/specs/blog/migrations_maria_db/m200000_000003_create_table_fakerable.php index 4ec0bb94..84f6247c 100644 --- a/tests/specs/blog/migrations_maria_db/m200000_000004_create_table_fakerable.php +++ b/tests/specs/blog/migrations_maria_db/m200000_000003_create_table_fakerable.php @@ -3,7 +3,7 @@ /** * Table for Fakerable */ -class m200000_000004_create_table_fakerable extends \yii\db\Migration +class m200000_000003_create_table_fakerable extends \yii\db\Migration { public function up() { diff --git a/tests/specs/blog/migrations_maria_db/m200000_000003_create_table_post_comments.php b/tests/specs/blog/migrations_maria_db/m200000_000004_create_table_post_comments.php similarity index 94% rename from tests/specs/blog/migrations_maria_db/m200000_000003_create_table_post_comments.php rename to tests/specs/blog/migrations_maria_db/m200000_000004_create_table_post_comments.php index fc617edf..d4971f43 100644 --- a/tests/specs/blog/migrations_maria_db/m200000_000003_create_table_post_comments.php +++ b/tests/specs/blog/migrations_maria_db/m200000_000004_create_table_post_comments.php @@ -3,7 +3,7 @@ /** * Table for Comment */ -class m200000_000003_create_table_post_comments extends \yii\db\Migration +class m200000_000004_create_table_post_comments extends \yii\db\Migration { public function up() { diff --git a/tests/specs/blog/migrations_maria_db/m200000_000001_create_table_categories.php b/tests/specs/blog/migrations_mysql_db/m200000_000000_create_table_categories.php similarity index 91% rename from tests/specs/blog/migrations_maria_db/m200000_000001_create_table_categories.php rename to tests/specs/blog/migrations_mysql_db/m200000_000000_create_table_categories.php index 957966fb..0485cafc 100644 --- a/tests/specs/blog/migrations_maria_db/m200000_000001_create_table_categories.php +++ b/tests/specs/blog/migrations_mysql_db/m200000_000000_create_table_categories.php @@ -3,7 +3,7 @@ /** * Table for Category */ -class m200000_000001_create_table_categories extends \yii\db\Migration +class m200000_000000_create_table_categories extends \yii\db\Migration { public function up() { diff --git a/tests/specs/blog/migrations_maria_db/m200000_000000_create_table_users.php b/tests/specs/blog/migrations_mysql_db/m200000_000001_create_table_users.php similarity index 94% rename from tests/specs/blog/migrations_maria_db/m200000_000000_create_table_users.php rename to tests/specs/blog/migrations_mysql_db/m200000_000001_create_table_users.php index de42dde7..a90792e9 100644 --- a/tests/specs/blog/migrations_maria_db/m200000_000000_create_table_users.php +++ b/tests/specs/blog/migrations_mysql_db/m200000_000001_create_table_users.php @@ -3,7 +3,7 @@ /** * Table for User */ -class m200000_000000_create_table_users extends \yii\db\Migration +class m200000_000001_create_table_users extends \yii\db\Migration { public function up() { diff --git a/tests/specs/blog/migrations/m200000_000004_create_table_fakerable.php b/tests/specs/blog/migrations_mysql_db/m200000_000003_create_table_fakerable.php similarity index 95% rename from tests/specs/blog/migrations/m200000_000004_create_table_fakerable.php rename to tests/specs/blog/migrations_mysql_db/m200000_000003_create_table_fakerable.php index 82c4db07..0f3eebad 100644 --- a/tests/specs/blog/migrations/m200000_000004_create_table_fakerable.php +++ b/tests/specs/blog/migrations_mysql_db/m200000_000003_create_table_fakerable.php @@ -3,7 +3,7 @@ /** * Table for Fakerable */ -class m200000_000004_create_table_fakerable extends \yii\db\Migration +class m200000_000003_create_table_fakerable extends \yii\db\Migration { public function up() { diff --git a/tests/specs/blog/migrations/m200000_000003_create_table_post_comments.php b/tests/specs/blog/migrations_mysql_db/m200000_000004_create_table_post_comments.php similarity index 93% rename from tests/specs/blog/migrations/m200000_000003_create_table_post_comments.php rename to tests/specs/blog/migrations_mysql_db/m200000_000004_create_table_post_comments.php index 45b512c3..c16766da 100644 --- a/tests/specs/blog/migrations/m200000_000003_create_table_post_comments.php +++ b/tests/specs/blog/migrations_mysql_db/m200000_000004_create_table_post_comments.php @@ -3,7 +3,7 @@ /** * Table for Comment */ -class m200000_000003_create_table_post_comments extends \yii\db\Migration +class m200000_000004_create_table_post_comments extends \yii\db\Migration { public function up() { diff --git a/tests/specs/blog/migrations_pgsql_db/m200000_000001_create_table_categories.php b/tests/specs/blog/migrations_pgsql_db/m200000_000000_create_table_categories.php similarity index 91% rename from tests/specs/blog/migrations_pgsql_db/m200000_000001_create_table_categories.php rename to tests/specs/blog/migrations_pgsql_db/m200000_000000_create_table_categories.php index d99b8299..9c328a2d 100644 --- a/tests/specs/blog/migrations_pgsql_db/m200000_000001_create_table_categories.php +++ b/tests/specs/blog/migrations_pgsql_db/m200000_000000_create_table_categories.php @@ -3,7 +3,7 @@ /** * Table for Category */ -class m200000_000001_create_table_categories extends \yii\db\Migration +class m200000_000000_create_table_categories extends \yii\db\Migration { public function safeUp() { diff --git a/tests/specs/blog/migrations_pgsql_db/m200000_000000_create_table_users.php b/tests/specs/blog/migrations_pgsql_db/m200000_000001_create_table_users.php similarity index 94% rename from tests/specs/blog/migrations_pgsql_db/m200000_000000_create_table_users.php rename to tests/specs/blog/migrations_pgsql_db/m200000_000001_create_table_users.php index a00af878..e2bc0165 100644 --- a/tests/specs/blog/migrations_pgsql_db/m200000_000000_create_table_users.php +++ b/tests/specs/blog/migrations_pgsql_db/m200000_000001_create_table_users.php @@ -3,7 +3,7 @@ /** * Table for User */ -class m200000_000000_create_table_users extends \yii\db\Migration +class m200000_000001_create_table_users extends \yii\db\Migration { public function safeUp() { diff --git a/tests/specs/blog/migrations_pgsql_db/m200000_000004_create_table_fakerable.php b/tests/specs/blog/migrations_pgsql_db/m200000_000003_create_table_fakerable.php similarity index 95% rename from tests/specs/blog/migrations_pgsql_db/m200000_000004_create_table_fakerable.php rename to tests/specs/blog/migrations_pgsql_db/m200000_000003_create_table_fakerable.php index ae6929cb..a42b8954 100644 --- a/tests/specs/blog/migrations_pgsql_db/m200000_000004_create_table_fakerable.php +++ b/tests/specs/blog/migrations_pgsql_db/m200000_000003_create_table_fakerable.php @@ -3,7 +3,7 @@ /** * Table for Fakerable */ -class m200000_000004_create_table_fakerable extends \yii\db\Migration +class m200000_000003_create_table_fakerable extends \yii\db\Migration { public function safeUp() { diff --git a/tests/specs/blog/migrations_pgsql_db/m200000_000003_create_table_post_comments.php b/tests/specs/blog/migrations_pgsql_db/m200000_000004_create_table_post_comments.php similarity index 94% rename from tests/specs/blog/migrations_pgsql_db/m200000_000003_create_table_post_comments.php rename to tests/specs/blog/migrations_pgsql_db/m200000_000004_create_table_post_comments.php index 5f31afad..2aa48549 100644 --- a/tests/specs/blog/migrations_pgsql_db/m200000_000003_create_table_post_comments.php +++ b/tests/specs/blog/migrations_pgsql_db/m200000_000004_create_table_post_comments.php @@ -3,7 +3,7 @@ /** * Table for Comment */ -class m200000_000003_create_table_post_comments extends \yii\db\Migration +class m200000_000004_create_table_post_comments extends \yii\db\Migration { public function safeUp() { diff --git a/tests/specs/many2many/migrations/m200000_000003_create_table_photo.php b/tests/specs/many2many/migrations/m200000_000000_create_table_photo.php similarity index 82% rename from tests/specs/many2many/migrations/m200000_000003_create_table_photo.php rename to tests/specs/many2many/migrations/m200000_000000_create_table_photo.php index 2d783bbf..4e578d91 100644 --- a/tests/specs/many2many/migrations/m200000_000003_create_table_photo.php +++ b/tests/specs/many2many/migrations/m200000_000000_create_table_photo.php @@ -3,7 +3,7 @@ /** * Table for Photo */ -class m200000_000003_create_table_photo extends \yii\db\Migration +class m200000_000000_create_table_photo extends \yii\db\Migration { public function up() { diff --git a/tests/specs/many2many/migrations/m200000_000000_create_table_posts.php b/tests/specs/many2many/migrations/m200000_000001_create_table_posts.php similarity index 82% rename from tests/specs/many2many/migrations/m200000_000000_create_table_posts.php rename to tests/specs/many2many/migrations/m200000_000001_create_table_posts.php index 4febc421..2d07a0d1 100644 --- a/tests/specs/many2many/migrations/m200000_000000_create_table_posts.php +++ b/tests/specs/many2many/migrations/m200000_000001_create_table_posts.php @@ -3,7 +3,7 @@ /** * Table for Post */ -class m200000_000000_create_table_posts extends \yii\db\Migration +class m200000_000001_create_table_posts extends \yii\db\Migration { public function up() { diff --git a/tests/specs/many2many/migrations/m200000_000004_create_table_photos2posts.php b/tests/specs/many2many/migrations/m200000_000002_create_table_photos2posts.php similarity index 92% rename from tests/specs/many2many/migrations/m200000_000004_create_table_photos2posts.php rename to tests/specs/many2many/migrations/m200000_000002_create_table_photos2posts.php index b509a525..f10b43a6 100644 --- a/tests/specs/many2many/migrations/m200000_000004_create_table_photos2posts.php +++ b/tests/specs/many2many/migrations/m200000_000002_create_table_photos2posts.php @@ -3,7 +3,7 @@ /** * Table for Photos2Posts */ -class m200000_000004_create_table_photos2posts extends \yii\db\Migration +class m200000_000002_create_table_photos2posts extends \yii\db\Migration { public function up() { diff --git a/tests/specs/many2many/migrations/m200000_000001_create_table_tags.php b/tests/specs/many2many/migrations/m200000_000003_create_table_tags.php similarity index 82% rename from tests/specs/many2many/migrations/m200000_000001_create_table_tags.php rename to tests/specs/many2many/migrations/m200000_000003_create_table_tags.php index b78dfe66..253b8513 100644 --- a/tests/specs/many2many/migrations/m200000_000001_create_table_tags.php +++ b/tests/specs/many2many/migrations/m200000_000003_create_table_tags.php @@ -3,7 +3,7 @@ /** * Table for Tag */ -class m200000_000001_create_table_tags extends \yii\db\Migration +class m200000_000003_create_table_tags extends \yii\db\Migration { public function up() { diff --git a/tests/specs/many2many/migrations/m200000_000002_create_table_posts2tags.php b/tests/specs/many2many/migrations/m200000_000004_create_table_posts2tags.php similarity index 93% rename from tests/specs/many2many/migrations/m200000_000002_create_table_posts2tags.php rename to tests/specs/many2many/migrations/m200000_000004_create_table_posts2tags.php index 373e2e65..dbc82bc3 100644 --- a/tests/specs/many2many/migrations/m200000_000002_create_table_posts2tags.php +++ b/tests/specs/many2many/migrations/m200000_000004_create_table_posts2tags.php @@ -3,7 +3,7 @@ /** * Table for Posts2Tags */ -class m200000_000002_create_table_posts2tags extends \yii\db\Migration +class m200000_000004_create_table_posts2tags extends \yii\db\Migration { public function up() { diff --git a/tests/specs/many2many/migrations/m200000_000006_create_table_posts_attaches.php b/tests/specs/many2many/migrations/m200000_000005_create_table_posts_attaches.php similarity index 93% rename from tests/specs/many2many/migrations/m200000_000006_create_table_posts_attaches.php rename to tests/specs/many2many/migrations/m200000_000005_create_table_posts_attaches.php index db479676..f5092acb 100644 --- a/tests/specs/many2many/migrations/m200000_000006_create_table_posts_attaches.php +++ b/tests/specs/many2many/migrations/m200000_000005_create_table_posts_attaches.php @@ -3,7 +3,7 @@ /** * Table for PostsAttaches */ -class m200000_000006_create_table_posts_attaches extends \yii\db\Migration +class m200000_000005_create_table_posts_attaches extends \yii\db\Migration { public function up() { diff --git a/tests/specs/many2many/migrations/m200000_000005_create_table_posts_gallery.php b/tests/specs/many2many/migrations/m200000_000006_create_table_posts_gallery.php similarity index 94% rename from tests/specs/many2many/migrations/m200000_000005_create_table_posts_gallery.php rename to tests/specs/many2many/migrations/m200000_000006_create_table_posts_gallery.php index fe358e21..aeb6c64f 100644 --- a/tests/specs/many2many/migrations/m200000_000005_create_table_posts_gallery.php +++ b/tests/specs/many2many/migrations/m200000_000006_create_table_posts_gallery.php @@ -3,7 +3,7 @@ /** * Table for PostsGallery */ -class m200000_000005_create_table_posts_gallery extends \yii\db\Migration +class m200000_000006_create_table_posts_gallery extends \yii\db\Migration { public function up() { From b08a7dcc0f33198644f45fd25b229063d2a21ef5 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Thu, 25 Jul 2024 15:28:41 +0530 Subject: [PATCH 088/358] Revert "Fix another failing tests - ForeignKeyColumnNameTest::testIndexForColumnWithCustomName" This reverts commit 0c552cec91c01a242b0111d536615f240609ee86. --- ...eliveries.php => m200000_000000_create_table_deliveries.php} | 2 +- ...te_table_users.php => m200000_000001_create_table_users.php} | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) rename tests/specs/fk_col_name_index/app/migrations_mysql_db/{m200000_000001_create_table_deliveries.php => m200000_000000_create_table_deliveries.php} (83%) rename tests/specs/fk_col_name_index/app/migrations_mysql_db/{m200000_000000_create_table_users.php => m200000_000001_create_table_users.php} (82%) diff --git a/tests/specs/fk_col_name_index/app/migrations_mysql_db/m200000_000001_create_table_deliveries.php b/tests/specs/fk_col_name_index/app/migrations_mysql_db/m200000_000000_create_table_deliveries.php similarity index 83% rename from tests/specs/fk_col_name_index/app/migrations_mysql_db/m200000_000001_create_table_deliveries.php rename to tests/specs/fk_col_name_index/app/migrations_mysql_db/m200000_000000_create_table_deliveries.php index b99ba258..e88d0ea9 100644 --- a/tests/specs/fk_col_name_index/app/migrations_mysql_db/m200000_000001_create_table_deliveries.php +++ b/tests/specs/fk_col_name_index/app/migrations_mysql_db/m200000_000000_create_table_deliveries.php @@ -3,7 +3,7 @@ /** * Table for Delivery */ -class m200000_000001_create_table_deliveries extends \yii\db\Migration +class m200000_000000_create_table_deliveries extends \yii\db\Migration { public function up() { diff --git a/tests/specs/fk_col_name_index/app/migrations_mysql_db/m200000_000000_create_table_users.php b/tests/specs/fk_col_name_index/app/migrations_mysql_db/m200000_000001_create_table_users.php similarity index 82% rename from tests/specs/fk_col_name_index/app/migrations_mysql_db/m200000_000000_create_table_users.php rename to tests/specs/fk_col_name_index/app/migrations_mysql_db/m200000_000001_create_table_users.php index 2616e0a4..e6e9afe4 100644 --- a/tests/specs/fk_col_name_index/app/migrations_mysql_db/m200000_000000_create_table_users.php +++ b/tests/specs/fk_col_name_index/app/migrations_mysql_db/m200000_000001_create_table_users.php @@ -3,7 +3,7 @@ /** * Table for User */ -class m200000_000000_create_table_users extends \yii\db\Migration +class m200000_000001_create_table_users extends \yii\db\Migration { public function up() { From 73d36d3ff3c2b30a40210a9ebbbea31a7c8d1a32 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Thu, 25 Jul 2024 15:29:02 +0530 Subject: [PATCH 089/358] Revert "Fix another failing tests - ForeignKeyColumnNameTest::testIndex" This reverts commit 07b00b1bd2e6839256d4ff7a49f969e2b7927fa3. --- ...eliveries.php => m200000_000000_create_table_deliveries.php} | 2 +- ...te_table_users.php => m200000_000001_create_table_users.php} | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) rename tests/specs/fk_col_name/app/migrations_mysql_db/{m200000_000001_create_table_deliveries.php => m200000_000000_create_table_deliveries.php} (83%) rename tests/specs/fk_col_name/app/migrations_mysql_db/{m200000_000000_create_table_users.php => m200000_000001_create_table_users.php} (82%) diff --git a/tests/specs/fk_col_name/app/migrations_mysql_db/m200000_000001_create_table_deliveries.php b/tests/specs/fk_col_name/app/migrations_mysql_db/m200000_000000_create_table_deliveries.php similarity index 83% rename from tests/specs/fk_col_name/app/migrations_mysql_db/m200000_000001_create_table_deliveries.php rename to tests/specs/fk_col_name/app/migrations_mysql_db/m200000_000000_create_table_deliveries.php index b99ba258..e88d0ea9 100644 --- a/tests/specs/fk_col_name/app/migrations_mysql_db/m200000_000001_create_table_deliveries.php +++ b/tests/specs/fk_col_name/app/migrations_mysql_db/m200000_000000_create_table_deliveries.php @@ -3,7 +3,7 @@ /** * Table for Delivery */ -class m200000_000001_create_table_deliveries extends \yii\db\Migration +class m200000_000000_create_table_deliveries extends \yii\db\Migration { public function up() { diff --git a/tests/specs/fk_col_name/app/migrations_mysql_db/m200000_000000_create_table_users.php b/tests/specs/fk_col_name/app/migrations_mysql_db/m200000_000001_create_table_users.php similarity index 82% rename from tests/specs/fk_col_name/app/migrations_mysql_db/m200000_000000_create_table_users.php rename to tests/specs/fk_col_name/app/migrations_mysql_db/m200000_000001_create_table_users.php index 2616e0a4..e6e9afe4 100644 --- a/tests/specs/fk_col_name/app/migrations_mysql_db/m200000_000000_create_table_users.php +++ b/tests/specs/fk_col_name/app/migrations_mysql_db/m200000_000001_create_table_users.php @@ -3,7 +3,7 @@ /** * Table for User */ -class m200000_000000_create_table_users extends \yii\db\Migration +class m200000_000001_create_table_users extends \yii\db\Migration { public function up() { From 8d835c05d5bc83443dd1e77211ceadc01a80dff0 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Thu, 25 Jul 2024 15:29:31 +0530 Subject: [PATCH 090/358] Revert "Fix another failing tests - EnumTest::testChangeToAndFromEnum" This reverts commit ad7b022c48a2f263fea0cec59d8db9b0cbc49a68. --- ...tcolumns.php => m200000_000000_change_table_editcolumns.php} | 2 +- ..._pristines.php => m200000_000002_create_table_pristines.php} | 2 +- ...tcolumns.php => m200000_000000_change_table_editcolumns.php} | 2 +- ..._pristines.php => m200000_000002_create_table_pristines.php} | 2 +- ...tcolumns.php => m200000_000000_change_table_editcolumns.php} | 2 +- ..._pristines.php => m200000_000002_create_table_pristines.php} | 2 +- 6 files changed, 6 insertions(+), 6 deletions(-) rename tests/specs/enum/change/maria/app/migrations_maria_db/{m200000_000002_change_table_editcolumns.php => m200000_000000_change_table_editcolumns.php} (92%) rename tests/specs/enum/change/maria/app/migrations_maria_db/{m200000_000000_create_table_pristines.php => m200000_000002_create_table_pristines.php} (84%) rename tests/specs/enum/change/mysql/app/migrations_mysql_db/{m200000_000002_change_table_editcolumns.php => m200000_000000_change_table_editcolumns.php} (92%) rename tests/specs/enum/change/mysql/app/migrations_mysql_db/{m200000_000000_create_table_pristines.php => m200000_000002_create_table_pristines.php} (84%) rename tests/specs/enum/change/pgsql/app/migrations_pgsql_db/{m200000_000002_change_table_editcolumns.php => m200000_000000_change_table_editcolumns.php} (97%) rename tests/specs/enum/change/pgsql/app/migrations_pgsql_db/{m200000_000000_create_table_pristines.php => m200000_000002_create_table_pristines.php} (89%) diff --git a/tests/specs/enum/change/maria/app/migrations_maria_db/m200000_000002_change_table_editcolumns.php b/tests/specs/enum/change/maria/app/migrations_maria_db/m200000_000000_change_table_editcolumns.php similarity index 92% rename from tests/specs/enum/change/maria/app/migrations_maria_db/m200000_000002_change_table_editcolumns.php rename to tests/specs/enum/change/maria/app/migrations_maria_db/m200000_000000_change_table_editcolumns.php index a2b3f68d..3df0a659 100644 --- a/tests/specs/enum/change/maria/app/migrations_maria_db/m200000_000002_change_table_editcolumns.php +++ b/tests/specs/enum/change/maria/app/migrations_maria_db/m200000_000000_change_table_editcolumns.php @@ -3,7 +3,7 @@ /** * Table for Editcolumn */ -class m200000_000002_change_table_editcolumns extends \yii\db\Migration +class m200000_000000_change_table_editcolumns extends \yii\db\Migration { public function up() { diff --git a/tests/specs/enum/change/maria/app/migrations_maria_db/m200000_000000_create_table_pristines.php b/tests/specs/enum/change/maria/app/migrations_maria_db/m200000_000002_create_table_pristines.php similarity index 84% rename from tests/specs/enum/change/maria/app/migrations_maria_db/m200000_000000_create_table_pristines.php rename to tests/specs/enum/change/maria/app/migrations_maria_db/m200000_000002_create_table_pristines.php index 2b602da7..bdd46f98 100644 --- a/tests/specs/enum/change/maria/app/migrations_maria_db/m200000_000000_create_table_pristines.php +++ b/tests/specs/enum/change/maria/app/migrations_maria_db/m200000_000002_create_table_pristines.php @@ -3,7 +3,7 @@ /** * Table for Pristine */ -class m200000_000000_create_table_pristines extends \yii\db\Migration +class m200000_000002_create_table_pristines extends \yii\db\Migration { public function up() { diff --git a/tests/specs/enum/change/mysql/app/migrations_mysql_db/m200000_000002_change_table_editcolumns.php b/tests/specs/enum/change/mysql/app/migrations_mysql_db/m200000_000000_change_table_editcolumns.php similarity index 92% rename from tests/specs/enum/change/mysql/app/migrations_mysql_db/m200000_000002_change_table_editcolumns.php rename to tests/specs/enum/change/mysql/app/migrations_mysql_db/m200000_000000_change_table_editcolumns.php index 8d4e499b..117d6069 100644 --- a/tests/specs/enum/change/mysql/app/migrations_mysql_db/m200000_000002_change_table_editcolumns.php +++ b/tests/specs/enum/change/mysql/app/migrations_mysql_db/m200000_000000_change_table_editcolumns.php @@ -3,7 +3,7 @@ /** * Table for Editcolumn */ -class m200000_000002_change_table_editcolumns extends \yii\db\Migration +class m200000_000000_change_table_editcolumns extends \yii\db\Migration { public function up() { diff --git a/tests/specs/enum/change/mysql/app/migrations_mysql_db/m200000_000000_create_table_pristines.php b/tests/specs/enum/change/mysql/app/migrations_mysql_db/m200000_000002_create_table_pristines.php similarity index 84% rename from tests/specs/enum/change/mysql/app/migrations_mysql_db/m200000_000000_create_table_pristines.php rename to tests/specs/enum/change/mysql/app/migrations_mysql_db/m200000_000002_create_table_pristines.php index 2b602da7..bdd46f98 100644 --- a/tests/specs/enum/change/mysql/app/migrations_mysql_db/m200000_000000_create_table_pristines.php +++ b/tests/specs/enum/change/mysql/app/migrations_mysql_db/m200000_000002_create_table_pristines.php @@ -3,7 +3,7 @@ /** * Table for Pristine */ -class m200000_000000_create_table_pristines extends \yii\db\Migration +class m200000_000002_create_table_pristines extends \yii\db\Migration { public function up() { diff --git a/tests/specs/enum/change/pgsql/app/migrations_pgsql_db/m200000_000002_change_table_editcolumns.php b/tests/specs/enum/change/pgsql/app/migrations_pgsql_db/m200000_000000_change_table_editcolumns.php similarity index 97% rename from tests/specs/enum/change/pgsql/app/migrations_pgsql_db/m200000_000002_change_table_editcolumns.php rename to tests/specs/enum/change/pgsql/app/migrations_pgsql_db/m200000_000000_change_table_editcolumns.php index 0bbb27a9..66287960 100644 --- a/tests/specs/enum/change/pgsql/app/migrations_pgsql_db/m200000_000002_change_table_editcolumns.php +++ b/tests/specs/enum/change/pgsql/app/migrations_pgsql_db/m200000_000000_change_table_editcolumns.php @@ -3,7 +3,7 @@ /** * Table for Editcolumn */ -class m200000_000002_change_table_editcolumns extends \yii\db\Migration +class m200000_000000_change_table_editcolumns extends \yii\db\Migration { public function safeUp() { diff --git a/tests/specs/enum/change/pgsql/app/migrations_pgsql_db/m200000_000000_create_table_pristines.php b/tests/specs/enum/change/pgsql/app/migrations_pgsql_db/m200000_000002_create_table_pristines.php similarity index 89% rename from tests/specs/enum/change/pgsql/app/migrations_pgsql_db/m200000_000000_create_table_pristines.php rename to tests/specs/enum/change/pgsql/app/migrations_pgsql_db/m200000_000002_create_table_pristines.php index e336e5e2..45b63115 100644 --- a/tests/specs/enum/change/pgsql/app/migrations_pgsql_db/m200000_000000_create_table_pristines.php +++ b/tests/specs/enum/change/pgsql/app/migrations_pgsql_db/m200000_000002_create_table_pristines.php @@ -3,7 +3,7 @@ /** * Table for Pristine */ -class m200000_000000_create_table_pristines extends \yii\db\Migration +class m200000_000002_create_table_pristines extends \yii\db\Migration { public function safeUp() { From 1c0f3b6cfa9f2efd1fabd52266be6e00f0599c42 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Thu, 25 Jul 2024 15:30:28 +0530 Subject: [PATCH 091/358] Revert "Fix another failing tests - EnumTest::testAddNewColumn" This reverts commit 72b927b270822ecbc161ee5bbe6e2d8b9243c782. --- ...tcolumns.php => m200000_000000_create_table_editcolumns.php} | 2 +- ..._pristines.php => m200000_000002_create_table_pristines.php} | 2 +- ...tcolumns.php => m200000_000000_create_table_editcolumns.php} | 2 +- ..._pristines.php => m200000_000002_create_table_pristines.php} | 2 +- ...tcolumns.php => m200000_000000_create_table_editcolumns.php} | 2 +- ..._pristines.php => m200000_000002_create_table_pristines.php} | 2 +- 6 files changed, 6 insertions(+), 6 deletions(-) rename tests/specs/enum/new_column/maria/app/migrations_maria_db/{m200000_000002_create_table_editcolumns.php => m200000_000000_create_table_editcolumns.php} (88%) rename tests/specs/enum/new_column/maria/app/migrations_maria_db/{m200000_000000_create_table_pristines.php => m200000_000002_create_table_pristines.php} (84%) rename tests/specs/enum/new_column/mysql/app/migrations_mysql_db/{m200000_000002_create_table_editcolumns.php => m200000_000000_create_table_editcolumns.php} (88%) rename tests/specs/enum/new_column/mysql/app/migrations_mysql_db/{m200000_000000_create_table_pristines.php => m200000_000002_create_table_pristines.php} (84%) rename tests/specs/enum/new_column/pgsql/app/migrations_pgsql_db/{m200000_000002_create_table_editcolumns.php => m200000_000000_create_table_editcolumns.php} (93%) rename tests/specs/enum/new_column/pgsql/app/migrations_pgsql_db/{m200000_000000_create_table_pristines.php => m200000_000002_create_table_pristines.php} (89%) diff --git a/tests/specs/enum/new_column/maria/app/migrations_maria_db/m200000_000002_create_table_editcolumns.php b/tests/specs/enum/new_column/maria/app/migrations_maria_db/m200000_000000_create_table_editcolumns.php similarity index 88% rename from tests/specs/enum/new_column/maria/app/migrations_maria_db/m200000_000002_create_table_editcolumns.php rename to tests/specs/enum/new_column/maria/app/migrations_maria_db/m200000_000000_create_table_editcolumns.php index d4e6b085..1d2581bf 100644 --- a/tests/specs/enum/new_column/maria/app/migrations_maria_db/m200000_000002_create_table_editcolumns.php +++ b/tests/specs/enum/new_column/maria/app/migrations_maria_db/m200000_000000_create_table_editcolumns.php @@ -3,7 +3,7 @@ /** * Table for Editcolumn */ -class m200000_000002_create_table_editcolumns extends \yii\db\Migration +class m200000_000000_create_table_editcolumns extends \yii\db\Migration { public function up() { diff --git a/tests/specs/enum/new_column/maria/app/migrations_maria_db/m200000_000000_create_table_pristines.php b/tests/specs/enum/new_column/maria/app/migrations_maria_db/m200000_000002_create_table_pristines.php similarity index 84% rename from tests/specs/enum/new_column/maria/app/migrations_maria_db/m200000_000000_create_table_pristines.php rename to tests/specs/enum/new_column/maria/app/migrations_maria_db/m200000_000002_create_table_pristines.php index 2b602da7..bdd46f98 100644 --- a/tests/specs/enum/new_column/maria/app/migrations_maria_db/m200000_000000_create_table_pristines.php +++ b/tests/specs/enum/new_column/maria/app/migrations_maria_db/m200000_000002_create_table_pristines.php @@ -3,7 +3,7 @@ /** * Table for Pristine */ -class m200000_000000_create_table_pristines extends \yii\db\Migration +class m200000_000002_create_table_pristines extends \yii\db\Migration { public function up() { diff --git a/tests/specs/enum/new_column/mysql/app/migrations_mysql_db/m200000_000002_create_table_editcolumns.php b/tests/specs/enum/new_column/mysql/app/migrations_mysql_db/m200000_000000_create_table_editcolumns.php similarity index 88% rename from tests/specs/enum/new_column/mysql/app/migrations_mysql_db/m200000_000002_create_table_editcolumns.php rename to tests/specs/enum/new_column/mysql/app/migrations_mysql_db/m200000_000000_create_table_editcolumns.php index 241a5fd7..3aeb5b25 100644 --- a/tests/specs/enum/new_column/mysql/app/migrations_mysql_db/m200000_000002_create_table_editcolumns.php +++ b/tests/specs/enum/new_column/mysql/app/migrations_mysql_db/m200000_000000_create_table_editcolumns.php @@ -3,7 +3,7 @@ /** * Table for Editcolumn */ -class m200000_000002_create_table_editcolumns extends \yii\db\Migration +class m200000_000000_create_table_editcolumns extends \yii\db\Migration { public function up() { diff --git a/tests/specs/enum/new_column/mysql/app/migrations_mysql_db/m200000_000000_create_table_pristines.php b/tests/specs/enum/new_column/mysql/app/migrations_mysql_db/m200000_000002_create_table_pristines.php similarity index 84% rename from tests/specs/enum/new_column/mysql/app/migrations_mysql_db/m200000_000000_create_table_pristines.php rename to tests/specs/enum/new_column/mysql/app/migrations_mysql_db/m200000_000002_create_table_pristines.php index 2b602da7..bdd46f98 100644 --- a/tests/specs/enum/new_column/mysql/app/migrations_mysql_db/m200000_000000_create_table_pristines.php +++ b/tests/specs/enum/new_column/mysql/app/migrations_mysql_db/m200000_000002_create_table_pristines.php @@ -3,7 +3,7 @@ /** * Table for Pristine */ -class m200000_000000_create_table_pristines extends \yii\db\Migration +class m200000_000002_create_table_pristines extends \yii\db\Migration { public function up() { diff --git a/tests/specs/enum/new_column/pgsql/app/migrations_pgsql_db/m200000_000002_create_table_editcolumns.php b/tests/specs/enum/new_column/pgsql/app/migrations_pgsql_db/m200000_000000_create_table_editcolumns.php similarity index 93% rename from tests/specs/enum/new_column/pgsql/app/migrations_pgsql_db/m200000_000002_create_table_editcolumns.php rename to tests/specs/enum/new_column/pgsql/app/migrations_pgsql_db/m200000_000000_create_table_editcolumns.php index 36bbb3fa..5180bf54 100644 --- a/tests/specs/enum/new_column/pgsql/app/migrations_pgsql_db/m200000_000002_create_table_editcolumns.php +++ b/tests/specs/enum/new_column/pgsql/app/migrations_pgsql_db/m200000_000000_create_table_editcolumns.php @@ -3,7 +3,7 @@ /** * Table for Editcolumn */ -class m200000_000002_create_table_editcolumns extends \yii\db\Migration +class m200000_000000_create_table_editcolumns extends \yii\db\Migration { public function safeUp() { diff --git a/tests/specs/enum/new_column/pgsql/app/migrations_pgsql_db/m200000_000000_create_table_pristines.php b/tests/specs/enum/new_column/pgsql/app/migrations_pgsql_db/m200000_000002_create_table_pristines.php similarity index 89% rename from tests/specs/enum/new_column/pgsql/app/migrations_pgsql_db/m200000_000000_create_table_pristines.php rename to tests/specs/enum/new_column/pgsql/app/migrations_pgsql_db/m200000_000002_create_table_pristines.php index e336e5e2..45b63115 100644 --- a/tests/specs/enum/new_column/pgsql/app/migrations_pgsql_db/m200000_000000_create_table_pristines.php +++ b/tests/specs/enum/new_column/pgsql/app/migrations_pgsql_db/m200000_000002_create_table_pristines.php @@ -3,7 +3,7 @@ /** * Table for Pristine */ -class m200000_000000_create_table_pristines extends \yii\db\Migration +class m200000_000002_create_table_pristines extends \yii\db\Migration { public function safeUp() { From 9fdc293fdae858633a17dbe67c4e73b19fe4d5b1 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Thu, 25 Jul 2024 15:30:54 +0530 Subject: [PATCH 092/358] Revert "Fix another failing tests - 4" This reverts commit 0dbad7ce4fdae317ed0d5ba06edb64cfc3d873a0. --- ...tcolumns.php => m200000_000000_create_table_editcolumns.php} | 2 +- ..._pristines.php => m200000_000002_create_table_pristines.php} | 2 +- ...tcolumns.php => m200000_000000_create_table_editcolumns.php} | 2 +- ..._pristines.php => m200000_000002_create_table_pristines.php} | 2 +- ...tcolumns.php => m200000_000000_create_table_editcolumns.php} | 2 +- ..._pristines.php => m200000_000002_create_table_pristines.php} | 2 +- 6 files changed, 6 insertions(+), 6 deletions(-) rename tests/specs/enum/fresh/maria/app/migrations_maria_db/{m200000_000002_create_table_editcolumns.php => m200000_000000_create_table_editcolumns.php} (88%) rename tests/specs/enum/fresh/maria/app/migrations_maria_db/{m200000_000000_create_table_pristines.php => m200000_000002_create_table_pristines.php} (84%) rename tests/specs/enum/fresh/mysql/app/migrations_mysql_db/{m200000_000002_create_table_editcolumns.php => m200000_000000_create_table_editcolumns.php} (88%) rename tests/specs/enum/fresh/mysql/app/migrations_mysql_db/{m200000_000000_create_table_pristines.php => m200000_000002_create_table_pristines.php} (84%) rename tests/specs/enum/fresh/pgsql/app/migrations_pgsql_db/{m200000_000002_create_table_editcolumns.php => m200000_000000_create_table_editcolumns.php} (93%) rename tests/specs/enum/fresh/pgsql/app/migrations_pgsql_db/{m200000_000000_create_table_pristines.php => m200000_000002_create_table_pristines.php} (89%) diff --git a/tests/specs/enum/fresh/maria/app/migrations_maria_db/m200000_000002_create_table_editcolumns.php b/tests/specs/enum/fresh/maria/app/migrations_maria_db/m200000_000000_create_table_editcolumns.php similarity index 88% rename from tests/specs/enum/fresh/maria/app/migrations_maria_db/m200000_000002_create_table_editcolumns.php rename to tests/specs/enum/fresh/maria/app/migrations_maria_db/m200000_000000_create_table_editcolumns.php index d4e6b085..1d2581bf 100644 --- a/tests/specs/enum/fresh/maria/app/migrations_maria_db/m200000_000002_create_table_editcolumns.php +++ b/tests/specs/enum/fresh/maria/app/migrations_maria_db/m200000_000000_create_table_editcolumns.php @@ -3,7 +3,7 @@ /** * Table for Editcolumn */ -class m200000_000002_create_table_editcolumns extends \yii\db\Migration +class m200000_000000_create_table_editcolumns extends \yii\db\Migration { public function up() { diff --git a/tests/specs/enum/fresh/maria/app/migrations_maria_db/m200000_000000_create_table_pristines.php b/tests/specs/enum/fresh/maria/app/migrations_maria_db/m200000_000002_create_table_pristines.php similarity index 84% rename from tests/specs/enum/fresh/maria/app/migrations_maria_db/m200000_000000_create_table_pristines.php rename to tests/specs/enum/fresh/maria/app/migrations_maria_db/m200000_000002_create_table_pristines.php index 2b602da7..bdd46f98 100644 --- a/tests/specs/enum/fresh/maria/app/migrations_maria_db/m200000_000000_create_table_pristines.php +++ b/tests/specs/enum/fresh/maria/app/migrations_maria_db/m200000_000002_create_table_pristines.php @@ -3,7 +3,7 @@ /** * Table for Pristine */ -class m200000_000000_create_table_pristines extends \yii\db\Migration +class m200000_000002_create_table_pristines extends \yii\db\Migration { public function up() { diff --git a/tests/specs/enum/fresh/mysql/app/migrations_mysql_db/m200000_000002_create_table_editcolumns.php b/tests/specs/enum/fresh/mysql/app/migrations_mysql_db/m200000_000000_create_table_editcolumns.php similarity index 88% rename from tests/specs/enum/fresh/mysql/app/migrations_mysql_db/m200000_000002_create_table_editcolumns.php rename to tests/specs/enum/fresh/mysql/app/migrations_mysql_db/m200000_000000_create_table_editcolumns.php index 241a5fd7..3aeb5b25 100644 --- a/tests/specs/enum/fresh/mysql/app/migrations_mysql_db/m200000_000002_create_table_editcolumns.php +++ b/tests/specs/enum/fresh/mysql/app/migrations_mysql_db/m200000_000000_create_table_editcolumns.php @@ -3,7 +3,7 @@ /** * Table for Editcolumn */ -class m200000_000002_create_table_editcolumns extends \yii\db\Migration +class m200000_000000_create_table_editcolumns extends \yii\db\Migration { public function up() { diff --git a/tests/specs/enum/fresh/mysql/app/migrations_mysql_db/m200000_000000_create_table_pristines.php b/tests/specs/enum/fresh/mysql/app/migrations_mysql_db/m200000_000002_create_table_pristines.php similarity index 84% rename from tests/specs/enum/fresh/mysql/app/migrations_mysql_db/m200000_000000_create_table_pristines.php rename to tests/specs/enum/fresh/mysql/app/migrations_mysql_db/m200000_000002_create_table_pristines.php index 2b602da7..bdd46f98 100644 --- a/tests/specs/enum/fresh/mysql/app/migrations_mysql_db/m200000_000000_create_table_pristines.php +++ b/tests/specs/enum/fresh/mysql/app/migrations_mysql_db/m200000_000002_create_table_pristines.php @@ -3,7 +3,7 @@ /** * Table for Pristine */ -class m200000_000000_create_table_pristines extends \yii\db\Migration +class m200000_000002_create_table_pristines extends \yii\db\Migration { public function up() { diff --git a/tests/specs/enum/fresh/pgsql/app/migrations_pgsql_db/m200000_000002_create_table_editcolumns.php b/tests/specs/enum/fresh/pgsql/app/migrations_pgsql_db/m200000_000000_create_table_editcolumns.php similarity index 93% rename from tests/specs/enum/fresh/pgsql/app/migrations_pgsql_db/m200000_000002_create_table_editcolumns.php rename to tests/specs/enum/fresh/pgsql/app/migrations_pgsql_db/m200000_000000_create_table_editcolumns.php index 36bbb3fa..5180bf54 100644 --- a/tests/specs/enum/fresh/pgsql/app/migrations_pgsql_db/m200000_000002_create_table_editcolumns.php +++ b/tests/specs/enum/fresh/pgsql/app/migrations_pgsql_db/m200000_000000_create_table_editcolumns.php @@ -3,7 +3,7 @@ /** * Table for Editcolumn */ -class m200000_000002_create_table_editcolumns extends \yii\db\Migration +class m200000_000000_create_table_editcolumns extends \yii\db\Migration { public function safeUp() { diff --git a/tests/specs/enum/fresh/pgsql/app/migrations_pgsql_db/m200000_000000_create_table_pristines.php b/tests/specs/enum/fresh/pgsql/app/migrations_pgsql_db/m200000_000002_create_table_pristines.php similarity index 89% rename from tests/specs/enum/fresh/pgsql/app/migrations_pgsql_db/m200000_000000_create_table_pristines.php rename to tests/specs/enum/fresh/pgsql/app/migrations_pgsql_db/m200000_000002_create_table_pristines.php index e336e5e2..45b63115 100644 --- a/tests/specs/enum/fresh/pgsql/app/migrations_pgsql_db/m200000_000000_create_table_pristines.php +++ b/tests/specs/enum/fresh/pgsql/app/migrations_pgsql_db/m200000_000002_create_table_pristines.php @@ -3,7 +3,7 @@ /** * Table for Pristine */ -class m200000_000000_create_table_pristines extends \yii\db\Migration +class m200000_000002_create_table_pristines extends \yii\db\Migration { public function safeUp() { From 38682f1377a2dc758e80f3e314e1588847456a35 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Thu, 25 Jul 2024 15:31:22 +0530 Subject: [PATCH 093/358] Revert "Fix another failing tests - 3" This reverts commit 51ebfd70991c56ae51a141979a227742f9e69cee. --- ...te_table_c123s.php => m200000_000000_create_table_c123s.php} | 2 +- ...te_table_b123s.php => m200000_000001_create_table_b123s.php} | 2 +- ...te_table_a123s.php => m200000_000002_create_table_a123s.php} | 2 +- ...le_accounts.php => m200000_000003_create_table_accounts.php} | 2 +- ...te_table_d123s.php => m200000_000004_create_table_d123s.php} | 2 +- ...able_domains.php => m200000_000005_create_table_domains.php} | 2 +- ...te_table_e123s.php => m200000_000006_create_table_e123s.php} | 2 +- ...le_routings.php => m200000_000007_create_table_routings.php} | 2 +- 8 files changed, 8 insertions(+), 8 deletions(-) rename tests/specs/relations_in_faker/app/migrations_pgsql_db/{m200000_000003_create_table_c123s.php => m200000_000000_create_table_c123s.php} (83%) rename tests/specs/relations_in_faker/app/migrations_pgsql_db/{m200000_000004_create_table_b123s.php => m200000_000001_create_table_b123s.php} (89%) rename tests/specs/relations_in_faker/app/migrations_pgsql_db/{m200000_000005_create_table_a123s.php => m200000_000002_create_table_a123s.php} (89%) rename tests/specs/relations_in_faker/app/migrations_pgsql_db/{m200000_000000_create_table_accounts.php => m200000_000003_create_table_accounts.php} (83%) rename tests/specs/relations_in_faker/app/migrations_pgsql_db/{m200000_000002_create_table_d123s.php => m200000_000004_create_table_d123s.php} (83%) rename tests/specs/relations_in_faker/app/migrations_pgsql_db/{m200000_000001_create_table_domains.php => m200000_000005_create_table_domains.php} (90%) rename tests/specs/relations_in_faker/app/migrations_pgsql_db/{m200000_000007_create_table_e123s.php => m200000_000006_create_table_e123s.php} (89%) rename tests/specs/relations_in_faker/app/migrations_pgsql_db/{m200000_000006_create_table_routings.php => m200000_000007_create_table_routings.php} (95%) diff --git a/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000003_create_table_c123s.php b/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000000_create_table_c123s.php similarity index 83% rename from tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000003_create_table_c123s.php rename to tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000000_create_table_c123s.php index f2dcc3ff..0c9c1c80 100644 --- a/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000003_create_table_c123s.php +++ b/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000000_create_table_c123s.php @@ -3,7 +3,7 @@ /** * Table for C123 */ -class m200000_000003_create_table_c123s extends \yii\db\Migration +class m200000_000000_create_table_c123s extends \yii\db\Migration { public function safeUp() { diff --git a/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000004_create_table_b123s.php b/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000001_create_table_b123s.php similarity index 89% rename from tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000004_create_table_b123s.php rename to tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000001_create_table_b123s.php index 0d719651..908bd998 100644 --- a/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000004_create_table_b123s.php +++ b/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000001_create_table_b123s.php @@ -3,7 +3,7 @@ /** * Table for B123 */ -class m200000_000004_create_table_b123s extends \yii\db\Migration +class m200000_000001_create_table_b123s extends \yii\db\Migration { public function safeUp() { diff --git a/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000005_create_table_a123s.php b/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000002_create_table_a123s.php similarity index 89% rename from tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000005_create_table_a123s.php rename to tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000002_create_table_a123s.php index 8a9b4737..73c70ae2 100644 --- a/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000005_create_table_a123s.php +++ b/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000002_create_table_a123s.php @@ -3,7 +3,7 @@ /** * Table for A123 */ -class m200000_000005_create_table_a123s extends \yii\db\Migration +class m200000_000002_create_table_a123s extends \yii\db\Migration { public function safeUp() { diff --git a/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000000_create_table_accounts.php b/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000003_create_table_accounts.php similarity index 83% rename from tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000000_create_table_accounts.php rename to tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000003_create_table_accounts.php index ef607707..8eba95b2 100644 --- a/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000000_create_table_accounts.php +++ b/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000003_create_table_accounts.php @@ -3,7 +3,7 @@ /** * Table for Account */ -class m200000_000000_create_table_accounts extends \yii\db\Migration +class m200000_000003_create_table_accounts extends \yii\db\Migration { public function safeUp() { diff --git a/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000002_create_table_d123s.php b/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000004_create_table_d123s.php similarity index 83% rename from tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000002_create_table_d123s.php rename to tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000004_create_table_d123s.php index 5deaa47d..794186a8 100644 --- a/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000002_create_table_d123s.php +++ b/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000004_create_table_d123s.php @@ -3,7 +3,7 @@ /** * Table for D123 */ -class m200000_000002_create_table_d123s extends \yii\db\Migration +class m200000_000004_create_table_d123s extends \yii\db\Migration { public function safeUp() { diff --git a/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000001_create_table_domains.php b/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000005_create_table_domains.php similarity index 90% rename from tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000001_create_table_domains.php rename to tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000005_create_table_domains.php index 5c2336fe..c830fe7e 100644 --- a/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000001_create_table_domains.php +++ b/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000005_create_table_domains.php @@ -3,7 +3,7 @@ /** * Table for Domain */ -class m200000_000001_create_table_domains extends \yii\db\Migration +class m200000_000005_create_table_domains extends \yii\db\Migration { public function safeUp() { diff --git a/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000007_create_table_e123s.php b/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000006_create_table_e123s.php similarity index 89% rename from tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000007_create_table_e123s.php rename to tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000006_create_table_e123s.php index bce7944e..f8d58a41 100644 --- a/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000007_create_table_e123s.php +++ b/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000006_create_table_e123s.php @@ -3,7 +3,7 @@ /** * Table for E123 */ -class m200000_000007_create_table_e123s extends \yii\db\Migration +class m200000_000006_create_table_e123s extends \yii\db\Migration { public function safeUp() { diff --git a/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000006_create_table_routings.php b/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000007_create_table_routings.php similarity index 95% rename from tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000006_create_table_routings.php rename to tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000007_create_table_routings.php index 5fd62f40..98ac2ad9 100644 --- a/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000006_create_table_routings.php +++ b/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000007_create_table_routings.php @@ -3,7 +3,7 @@ /** * Table for Routing */ -class m200000_000006_create_table_routings extends \yii\db\Migration +class m200000_000007_create_table_routings extends \yii\db\Migration { public function safeUp() { From e19fffbcef49575ab77e6abb966e62ca0f7dcd52 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Thu, 25 Jul 2024 15:31:44 +0530 Subject: [PATCH 094/358] Revert "Fix another failing tests - 2" This reverts commit 7d7dba7adf6c3b767b530a266126dc0b62425fe5. --- ...types.php => m200000_000000_create_table_alldbdatatypes.php} | 2 +- ...tcolumns.php => m200000_000001_create_table_editcolumns.php} | 2 +- ..._pristines.php => m200000_000003_create_table_pristines.php} | 2 +- ...types.php => m200000_000000_create_table_alldbdatatypes.php} | 2 +- ...tcolumns.php => m200000_000001_create_table_editcolumns.php} | 2 +- ..._pristines.php => m200000_000003_create_table_pristines.php} | 2 +- ...types.php => m200000_000000_create_table_alldbdatatypes.php} | 2 +- ...tcolumns.php => m200000_000001_create_table_editcolumns.php} | 2 +- ..._pristines.php => m200000_000003_create_table_pristines.php} | 2 +- 9 files changed, 9 insertions(+), 9 deletions(-) rename tests/specs/x_db_type/fresh/maria/app/migrations_maria_db/{m200000_000001_create_table_alldbdatatypes.php => m200000_000000_create_table_alldbdatatypes.php} (97%) rename tests/specs/x_db_type/fresh/maria/app/migrations_maria_db/{m200000_000003_create_table_editcolumns.php => m200000_000001_create_table_editcolumns.php} (93%) rename tests/specs/x_db_type/fresh/maria/app/migrations_maria_db/{m200000_000000_create_table_pristines.php => m200000_000003_create_table_pristines.php} (93%) rename tests/specs/x_db_type/fresh/mysql/app/migrations_mysql_db/{m200000_000001_create_table_alldbdatatypes.php => m200000_000000_create_table_alldbdatatypes.php} (97%) rename tests/specs/x_db_type/fresh/mysql/app/migrations_mysql_db/{m200000_000003_create_table_editcolumns.php => m200000_000001_create_table_editcolumns.php} (93%) rename tests/specs/x_db_type/fresh/mysql/app/migrations_mysql_db/{m200000_000000_create_table_pristines.php => m200000_000003_create_table_pristines.php} (93%) rename tests/specs/x_db_type/fresh/pgsql/app/migrations_pgsql_db/{m200000_000001_create_table_alldbdatatypes.php => m200000_000000_create_table_alldbdatatypes.php} (98%) rename tests/specs/x_db_type/fresh/pgsql/app/migrations_pgsql_db/{m200000_000003_create_table_editcolumns.php => m200000_000001_create_table_editcolumns.php} (94%) rename tests/specs/x_db_type/fresh/pgsql/app/migrations_pgsql_db/{m200000_000000_create_table_pristines.php => m200000_000003_create_table_pristines.php} (93%) diff --git a/tests/specs/x_db_type/fresh/maria/app/migrations_maria_db/m200000_000001_create_table_alldbdatatypes.php b/tests/specs/x_db_type/fresh/maria/app/migrations_maria_db/m200000_000000_create_table_alldbdatatypes.php similarity index 97% rename from tests/specs/x_db_type/fresh/maria/app/migrations_maria_db/m200000_000001_create_table_alldbdatatypes.php rename to tests/specs/x_db_type/fresh/maria/app/migrations_maria_db/m200000_000000_create_table_alldbdatatypes.php index 350eedaf..9c002bea 100644 --- a/tests/specs/x_db_type/fresh/maria/app/migrations_maria_db/m200000_000001_create_table_alldbdatatypes.php +++ b/tests/specs/x_db_type/fresh/maria/app/migrations_maria_db/m200000_000000_create_table_alldbdatatypes.php @@ -3,7 +3,7 @@ /** * Table for Alldbdatatype */ -class m200000_000001_create_table_alldbdatatypes extends \yii\db\Migration +class m200000_000000_create_table_alldbdatatypes extends \yii\db\Migration { public function up() { diff --git a/tests/specs/x_db_type/fresh/maria/app/migrations_maria_db/m200000_000003_create_table_editcolumns.php b/tests/specs/x_db_type/fresh/maria/app/migrations_maria_db/m200000_000001_create_table_editcolumns.php similarity index 93% rename from tests/specs/x_db_type/fresh/maria/app/migrations_maria_db/m200000_000003_create_table_editcolumns.php rename to tests/specs/x_db_type/fresh/maria/app/migrations_maria_db/m200000_000001_create_table_editcolumns.php index 1c4a0331..1de3d8d5 100644 --- a/tests/specs/x_db_type/fresh/maria/app/migrations_maria_db/m200000_000003_create_table_editcolumns.php +++ b/tests/specs/x_db_type/fresh/maria/app/migrations_maria_db/m200000_000001_create_table_editcolumns.php @@ -3,7 +3,7 @@ /** * Table for Editcolumn */ -class m200000_000003_create_table_editcolumns extends \yii\db\Migration +class m200000_000001_create_table_editcolumns extends \yii\db\Migration { public function up() { diff --git a/tests/specs/x_db_type/fresh/maria/app/migrations_maria_db/m200000_000000_create_table_pristines.php b/tests/specs/x_db_type/fresh/maria/app/migrations_maria_db/m200000_000003_create_table_pristines.php similarity index 93% rename from tests/specs/x_db_type/fresh/maria/app/migrations_maria_db/m200000_000000_create_table_pristines.php rename to tests/specs/x_db_type/fresh/maria/app/migrations_maria_db/m200000_000003_create_table_pristines.php index d1594797..1e27d8d6 100644 --- a/tests/specs/x_db_type/fresh/maria/app/migrations_maria_db/m200000_000000_create_table_pristines.php +++ b/tests/specs/x_db_type/fresh/maria/app/migrations_maria_db/m200000_000003_create_table_pristines.php @@ -3,7 +3,7 @@ /** * Table for Pristine */ -class m200000_000000_create_table_pristines extends \yii\db\Migration +class m200000_000003_create_table_pristines extends \yii\db\Migration { public function up() { diff --git a/tests/specs/x_db_type/fresh/mysql/app/migrations_mysql_db/m200000_000001_create_table_alldbdatatypes.php b/tests/specs/x_db_type/fresh/mysql/app/migrations_mysql_db/m200000_000000_create_table_alldbdatatypes.php similarity index 97% rename from tests/specs/x_db_type/fresh/mysql/app/migrations_mysql_db/m200000_000001_create_table_alldbdatatypes.php rename to tests/specs/x_db_type/fresh/mysql/app/migrations_mysql_db/m200000_000000_create_table_alldbdatatypes.php index 5f3d90d1..2cda660f 100644 --- a/tests/specs/x_db_type/fresh/mysql/app/migrations_mysql_db/m200000_000001_create_table_alldbdatatypes.php +++ b/tests/specs/x_db_type/fresh/mysql/app/migrations_mysql_db/m200000_000000_create_table_alldbdatatypes.php @@ -3,7 +3,7 @@ /** * Table for Alldbdatatype */ -class m200000_000001_create_table_alldbdatatypes extends \yii\db\Migration +class m200000_000000_create_table_alldbdatatypes extends \yii\db\Migration { public function up() { diff --git a/tests/specs/x_db_type/fresh/mysql/app/migrations_mysql_db/m200000_000003_create_table_editcolumns.php b/tests/specs/x_db_type/fresh/mysql/app/migrations_mysql_db/m200000_000001_create_table_editcolumns.php similarity index 93% rename from tests/specs/x_db_type/fresh/mysql/app/migrations_mysql_db/m200000_000003_create_table_editcolumns.php rename to tests/specs/x_db_type/fresh/mysql/app/migrations_mysql_db/m200000_000001_create_table_editcolumns.php index 81a1592d..8c84e731 100644 --- a/tests/specs/x_db_type/fresh/mysql/app/migrations_mysql_db/m200000_000003_create_table_editcolumns.php +++ b/tests/specs/x_db_type/fresh/mysql/app/migrations_mysql_db/m200000_000001_create_table_editcolumns.php @@ -3,7 +3,7 @@ /** * Table for Editcolumn */ -class m200000_000003_create_table_editcolumns extends \yii\db\Migration +class m200000_000001_create_table_editcolumns extends \yii\db\Migration { public function up() { diff --git a/tests/specs/x_db_type/fresh/mysql/app/migrations_mysql_db/m200000_000000_create_table_pristines.php b/tests/specs/x_db_type/fresh/mysql/app/migrations_mysql_db/m200000_000003_create_table_pristines.php similarity index 93% rename from tests/specs/x_db_type/fresh/mysql/app/migrations_mysql_db/m200000_000000_create_table_pristines.php rename to tests/specs/x_db_type/fresh/mysql/app/migrations_mysql_db/m200000_000003_create_table_pristines.php index ab96f730..3e9e8e02 100644 --- a/tests/specs/x_db_type/fresh/mysql/app/migrations_mysql_db/m200000_000000_create_table_pristines.php +++ b/tests/specs/x_db_type/fresh/mysql/app/migrations_mysql_db/m200000_000003_create_table_pristines.php @@ -3,7 +3,7 @@ /** * Table for Pristine */ -class m200000_000000_create_table_pristines extends \yii\db\Migration +class m200000_000003_create_table_pristines extends \yii\db\Migration { public function up() { diff --git a/tests/specs/x_db_type/fresh/pgsql/app/migrations_pgsql_db/m200000_000001_create_table_alldbdatatypes.php b/tests/specs/x_db_type/fresh/pgsql/app/migrations_pgsql_db/m200000_000000_create_table_alldbdatatypes.php similarity index 98% rename from tests/specs/x_db_type/fresh/pgsql/app/migrations_pgsql_db/m200000_000001_create_table_alldbdatatypes.php rename to tests/specs/x_db_type/fresh/pgsql/app/migrations_pgsql_db/m200000_000000_create_table_alldbdatatypes.php index 7f8403d4..e0cac52a 100644 --- a/tests/specs/x_db_type/fresh/pgsql/app/migrations_pgsql_db/m200000_000001_create_table_alldbdatatypes.php +++ b/tests/specs/x_db_type/fresh/pgsql/app/migrations_pgsql_db/m200000_000000_create_table_alldbdatatypes.php @@ -3,7 +3,7 @@ /** * Table for Alldbdatatype */ -class m200000_000001_create_table_alldbdatatypes extends \yii\db\Migration +class m200000_000000_create_table_alldbdatatypes extends \yii\db\Migration { public function safeUp() { diff --git a/tests/specs/x_db_type/fresh/pgsql/app/migrations_pgsql_db/m200000_000003_create_table_editcolumns.php b/tests/specs/x_db_type/fresh/pgsql/app/migrations_pgsql_db/m200000_000001_create_table_editcolumns.php similarity index 94% rename from tests/specs/x_db_type/fresh/pgsql/app/migrations_pgsql_db/m200000_000003_create_table_editcolumns.php rename to tests/specs/x_db_type/fresh/pgsql/app/migrations_pgsql_db/m200000_000001_create_table_editcolumns.php index 9679a0b8..b8f286b1 100644 --- a/tests/specs/x_db_type/fresh/pgsql/app/migrations_pgsql_db/m200000_000003_create_table_editcolumns.php +++ b/tests/specs/x_db_type/fresh/pgsql/app/migrations_pgsql_db/m200000_000001_create_table_editcolumns.php @@ -3,7 +3,7 @@ /** * Table for Editcolumn */ -class m200000_000003_create_table_editcolumns extends \yii\db\Migration +class m200000_000001_create_table_editcolumns extends \yii\db\Migration { public function safeUp() { diff --git a/tests/specs/x_db_type/fresh/pgsql/app/migrations_pgsql_db/m200000_000000_create_table_pristines.php b/tests/specs/x_db_type/fresh/pgsql/app/migrations_pgsql_db/m200000_000003_create_table_pristines.php similarity index 93% rename from tests/specs/x_db_type/fresh/pgsql/app/migrations_pgsql_db/m200000_000000_create_table_pristines.php rename to tests/specs/x_db_type/fresh/pgsql/app/migrations_pgsql_db/m200000_000003_create_table_pristines.php index 93b55396..aab6bb88 100644 --- a/tests/specs/x_db_type/fresh/pgsql/app/migrations_pgsql_db/m200000_000000_create_table_pristines.php +++ b/tests/specs/x_db_type/fresh/pgsql/app/migrations_pgsql_db/m200000_000003_create_table_pristines.php @@ -3,7 +3,7 @@ /** * Table for Pristine */ -class m200000_000000_create_table_pristines extends \yii\db\Migration +class m200000_000003_create_table_pristines extends \yii\db\Migration { public function safeUp() { From 60df77f06068fc79d0a2ba427bb0890273265e82 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Thu, 25 Jul 2024 15:32:04 +0530 Subject: [PATCH 095/358] Revert "Fix another failing tests" This reverts commit fbb2e8c02ac196464644ad06d2f8e4b4f4caaf66. --- ...types.php => m200000_000000_create_table_alldbdatatypes.php} | 2 +- ...tcolumns.php => m200000_000001_create_table_editcolumns.php} | 2 +- ..._pristines.php => m200000_000003_create_table_pristines.php} | 2 +- ...types.php => m200000_000000_create_table_alldbdatatypes.php} | 2 +- ...tcolumns.php => m200000_000001_create_table_editcolumns.php} | 2 +- ..._pristines.php => m200000_000003_create_table_pristines.php} | 2 +- ...types.php => m200000_000000_create_table_alldbdatatypes.php} | 2 +- ...tcolumns.php => m200000_000001_create_table_editcolumns.php} | 2 +- ..._pristines.php => m200000_000003_create_table_pristines.php} | 2 +- 9 files changed, 9 insertions(+), 9 deletions(-) rename tests/specs/x_db_type/new_column/maria/app/migrations_maria_db/{m200000_000001_create_table_alldbdatatypes.php => m200000_000000_create_table_alldbdatatypes.php} (97%) rename tests/specs/x_db_type/new_column/maria/app/migrations_maria_db/{m200000_000003_create_table_editcolumns.php => m200000_000001_create_table_editcolumns.php} (93%) rename tests/specs/x_db_type/new_column/maria/app/migrations_maria_db/{m200000_000000_create_table_pristines.php => m200000_000003_create_table_pristines.php} (93%) rename tests/specs/x_db_type/new_column/mysql/app/migrations_mysql_db/{m200000_000001_create_table_alldbdatatypes.php => m200000_000000_create_table_alldbdatatypes.php} (97%) rename tests/specs/x_db_type/new_column/mysql/app/migrations_mysql_db/{m200000_000003_create_table_editcolumns.php => m200000_000001_create_table_editcolumns.php} (93%) rename tests/specs/x_db_type/new_column/mysql/app/migrations_mysql_db/{m200000_000000_create_table_pristines.php => m200000_000003_create_table_pristines.php} (93%) rename tests/specs/x_db_type/new_column/pgsql/app/migrations_pgsql_db/{m200000_000001_create_table_alldbdatatypes.php => m200000_000000_create_table_alldbdatatypes.php} (98%) rename tests/specs/x_db_type/new_column/pgsql/app/migrations_pgsql_db/{m200000_000003_create_table_editcolumns.php => m200000_000001_create_table_editcolumns.php} (94%) rename tests/specs/x_db_type/new_column/pgsql/app/migrations_pgsql_db/{m200000_000000_create_table_pristines.php => m200000_000003_create_table_pristines.php} (93%) diff --git a/tests/specs/x_db_type/new_column/maria/app/migrations_maria_db/m200000_000001_create_table_alldbdatatypes.php b/tests/specs/x_db_type/new_column/maria/app/migrations_maria_db/m200000_000000_create_table_alldbdatatypes.php similarity index 97% rename from tests/specs/x_db_type/new_column/maria/app/migrations_maria_db/m200000_000001_create_table_alldbdatatypes.php rename to tests/specs/x_db_type/new_column/maria/app/migrations_maria_db/m200000_000000_create_table_alldbdatatypes.php index 350eedaf..9c002bea 100644 --- a/tests/specs/x_db_type/new_column/maria/app/migrations_maria_db/m200000_000001_create_table_alldbdatatypes.php +++ b/tests/specs/x_db_type/new_column/maria/app/migrations_maria_db/m200000_000000_create_table_alldbdatatypes.php @@ -3,7 +3,7 @@ /** * Table for Alldbdatatype */ -class m200000_000001_create_table_alldbdatatypes extends \yii\db\Migration +class m200000_000000_create_table_alldbdatatypes extends \yii\db\Migration { public function up() { diff --git a/tests/specs/x_db_type/new_column/maria/app/migrations_maria_db/m200000_000003_create_table_editcolumns.php b/tests/specs/x_db_type/new_column/maria/app/migrations_maria_db/m200000_000001_create_table_editcolumns.php similarity index 93% rename from tests/specs/x_db_type/new_column/maria/app/migrations_maria_db/m200000_000003_create_table_editcolumns.php rename to tests/specs/x_db_type/new_column/maria/app/migrations_maria_db/m200000_000001_create_table_editcolumns.php index 1c4a0331..1de3d8d5 100644 --- a/tests/specs/x_db_type/new_column/maria/app/migrations_maria_db/m200000_000003_create_table_editcolumns.php +++ b/tests/specs/x_db_type/new_column/maria/app/migrations_maria_db/m200000_000001_create_table_editcolumns.php @@ -3,7 +3,7 @@ /** * Table for Editcolumn */ -class m200000_000003_create_table_editcolumns extends \yii\db\Migration +class m200000_000001_create_table_editcolumns extends \yii\db\Migration { public function up() { diff --git a/tests/specs/x_db_type/new_column/maria/app/migrations_maria_db/m200000_000000_create_table_pristines.php b/tests/specs/x_db_type/new_column/maria/app/migrations_maria_db/m200000_000003_create_table_pristines.php similarity index 93% rename from tests/specs/x_db_type/new_column/maria/app/migrations_maria_db/m200000_000000_create_table_pristines.php rename to tests/specs/x_db_type/new_column/maria/app/migrations_maria_db/m200000_000003_create_table_pristines.php index d1594797..1e27d8d6 100644 --- a/tests/specs/x_db_type/new_column/maria/app/migrations_maria_db/m200000_000000_create_table_pristines.php +++ b/tests/specs/x_db_type/new_column/maria/app/migrations_maria_db/m200000_000003_create_table_pristines.php @@ -3,7 +3,7 @@ /** * Table for Pristine */ -class m200000_000000_create_table_pristines extends \yii\db\Migration +class m200000_000003_create_table_pristines extends \yii\db\Migration { public function up() { diff --git a/tests/specs/x_db_type/new_column/mysql/app/migrations_mysql_db/m200000_000001_create_table_alldbdatatypes.php b/tests/specs/x_db_type/new_column/mysql/app/migrations_mysql_db/m200000_000000_create_table_alldbdatatypes.php similarity index 97% rename from tests/specs/x_db_type/new_column/mysql/app/migrations_mysql_db/m200000_000001_create_table_alldbdatatypes.php rename to tests/specs/x_db_type/new_column/mysql/app/migrations_mysql_db/m200000_000000_create_table_alldbdatatypes.php index 5f3d90d1..2cda660f 100644 --- a/tests/specs/x_db_type/new_column/mysql/app/migrations_mysql_db/m200000_000001_create_table_alldbdatatypes.php +++ b/tests/specs/x_db_type/new_column/mysql/app/migrations_mysql_db/m200000_000000_create_table_alldbdatatypes.php @@ -3,7 +3,7 @@ /** * Table for Alldbdatatype */ -class m200000_000001_create_table_alldbdatatypes extends \yii\db\Migration +class m200000_000000_create_table_alldbdatatypes extends \yii\db\Migration { public function up() { diff --git a/tests/specs/x_db_type/new_column/mysql/app/migrations_mysql_db/m200000_000003_create_table_editcolumns.php b/tests/specs/x_db_type/new_column/mysql/app/migrations_mysql_db/m200000_000001_create_table_editcolumns.php similarity index 93% rename from tests/specs/x_db_type/new_column/mysql/app/migrations_mysql_db/m200000_000003_create_table_editcolumns.php rename to tests/specs/x_db_type/new_column/mysql/app/migrations_mysql_db/m200000_000001_create_table_editcolumns.php index 81a1592d..8c84e731 100644 --- a/tests/specs/x_db_type/new_column/mysql/app/migrations_mysql_db/m200000_000003_create_table_editcolumns.php +++ b/tests/specs/x_db_type/new_column/mysql/app/migrations_mysql_db/m200000_000001_create_table_editcolumns.php @@ -3,7 +3,7 @@ /** * Table for Editcolumn */ -class m200000_000003_create_table_editcolumns extends \yii\db\Migration +class m200000_000001_create_table_editcolumns extends \yii\db\Migration { public function up() { diff --git a/tests/specs/x_db_type/new_column/mysql/app/migrations_mysql_db/m200000_000000_create_table_pristines.php b/tests/specs/x_db_type/new_column/mysql/app/migrations_mysql_db/m200000_000003_create_table_pristines.php similarity index 93% rename from tests/specs/x_db_type/new_column/mysql/app/migrations_mysql_db/m200000_000000_create_table_pristines.php rename to tests/specs/x_db_type/new_column/mysql/app/migrations_mysql_db/m200000_000003_create_table_pristines.php index ab96f730..3e9e8e02 100644 --- a/tests/specs/x_db_type/new_column/mysql/app/migrations_mysql_db/m200000_000000_create_table_pristines.php +++ b/tests/specs/x_db_type/new_column/mysql/app/migrations_mysql_db/m200000_000003_create_table_pristines.php @@ -3,7 +3,7 @@ /** * Table for Pristine */ -class m200000_000000_create_table_pristines extends \yii\db\Migration +class m200000_000003_create_table_pristines extends \yii\db\Migration { public function up() { diff --git a/tests/specs/x_db_type/new_column/pgsql/app/migrations_pgsql_db/m200000_000001_create_table_alldbdatatypes.php b/tests/specs/x_db_type/new_column/pgsql/app/migrations_pgsql_db/m200000_000000_create_table_alldbdatatypes.php similarity index 98% rename from tests/specs/x_db_type/new_column/pgsql/app/migrations_pgsql_db/m200000_000001_create_table_alldbdatatypes.php rename to tests/specs/x_db_type/new_column/pgsql/app/migrations_pgsql_db/m200000_000000_create_table_alldbdatatypes.php index 7f8403d4..e0cac52a 100644 --- a/tests/specs/x_db_type/new_column/pgsql/app/migrations_pgsql_db/m200000_000001_create_table_alldbdatatypes.php +++ b/tests/specs/x_db_type/new_column/pgsql/app/migrations_pgsql_db/m200000_000000_create_table_alldbdatatypes.php @@ -3,7 +3,7 @@ /** * Table for Alldbdatatype */ -class m200000_000001_create_table_alldbdatatypes extends \yii\db\Migration +class m200000_000000_create_table_alldbdatatypes extends \yii\db\Migration { public function safeUp() { diff --git a/tests/specs/x_db_type/new_column/pgsql/app/migrations_pgsql_db/m200000_000003_create_table_editcolumns.php b/tests/specs/x_db_type/new_column/pgsql/app/migrations_pgsql_db/m200000_000001_create_table_editcolumns.php similarity index 94% rename from tests/specs/x_db_type/new_column/pgsql/app/migrations_pgsql_db/m200000_000003_create_table_editcolumns.php rename to tests/specs/x_db_type/new_column/pgsql/app/migrations_pgsql_db/m200000_000001_create_table_editcolumns.php index 9679a0b8..b8f286b1 100644 --- a/tests/specs/x_db_type/new_column/pgsql/app/migrations_pgsql_db/m200000_000003_create_table_editcolumns.php +++ b/tests/specs/x_db_type/new_column/pgsql/app/migrations_pgsql_db/m200000_000001_create_table_editcolumns.php @@ -3,7 +3,7 @@ /** * Table for Editcolumn */ -class m200000_000003_create_table_editcolumns extends \yii\db\Migration +class m200000_000001_create_table_editcolumns extends \yii\db\Migration { public function safeUp() { diff --git a/tests/specs/x_db_type/new_column/pgsql/app/migrations_pgsql_db/m200000_000000_create_table_pristines.php b/tests/specs/x_db_type/new_column/pgsql/app/migrations_pgsql_db/m200000_000003_create_table_pristines.php similarity index 93% rename from tests/specs/x_db_type/new_column/pgsql/app/migrations_pgsql_db/m200000_000000_create_table_pristines.php rename to tests/specs/x_db_type/new_column/pgsql/app/migrations_pgsql_db/m200000_000003_create_table_pristines.php index 93b55396..aab6bb88 100644 --- a/tests/specs/x_db_type/new_column/pgsql/app/migrations_pgsql_db/m200000_000000_create_table_pristines.php +++ b/tests/specs/x_db_type/new_column/pgsql/app/migrations_pgsql_db/m200000_000003_create_table_pristines.php @@ -3,7 +3,7 @@ /** * Table for Pristine */ -class m200000_000000_create_table_pristines extends \yii\db\Migration +class m200000_000003_create_table_pristines extends \yii\db\Migration { public function safeUp() { From 8b1876fe732085ad5dfd45c8c7b9512d6e9ef1f8 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Thu, 25 Jul 2024 15:36:20 +0530 Subject: [PATCH 096/358] Revert "Fix issue of migration ordering in drop + fix failing tests" This reverts commit 7cf9aa3ce0c10e867403531b248f6ba1b65ed173. --- ...types.php => m200000_000000_create_table_alldbdatatypes.php} | 2 +- ...tcolumns.php => m200000_000001_change_table_editcolumns.php} | 2 +- ..._pristines.php => m200000_000003_create_table_pristines.php} | 2 +- ...types.php => m200000_000000_create_table_alldbdatatypes.php} | 2 +- ...tcolumns.php => m200000_000001_change_table_editcolumns.php} | 2 +- ..._pristines.php => m200000_000003_create_table_pristines.php} | 2 +- ...types.php => m200000_000000_create_table_alldbdatatypes.php} | 2 +- ...tcolumns.php => m200000_000001_change_table_editcolumns.php} | 2 +- ..._pristines.php => m200000_000003_create_table_pristines.php} | 2 +- 9 files changed, 9 insertions(+), 9 deletions(-) rename tests/specs/x_db_type/edit_column/maria/app/migrations_maria_db/{m200000_000001_create_table_alldbdatatypes.php => m200000_000000_create_table_alldbdatatypes.php} (97%) rename tests/specs/x_db_type/edit_column/maria/app/migrations_maria_db/{m200000_000003_change_table_editcolumns.php => m200000_000001_change_table_editcolumns.php} (97%) rename tests/specs/x_db_type/edit_column/maria/app/migrations_maria_db/{m200000_000000_create_table_pristines.php => m200000_000003_create_table_pristines.php} (93%) rename tests/specs/x_db_type/edit_column/mysql/app/migrations_mysql_db/{m200000_000001_create_table_alldbdatatypes.php => m200000_000000_create_table_alldbdatatypes.php} (97%) rename tests/specs/x_db_type/edit_column/mysql/app/migrations_mysql_db/{m200000_000003_change_table_editcolumns.php => m200000_000001_change_table_editcolumns.php} (97%) rename tests/specs/x_db_type/edit_column/mysql/app/migrations_mysql_db/{m200000_000000_create_table_pristines.php => m200000_000003_create_table_pristines.php} (93%) rename tests/specs/x_db_type/edit_column/pgsql/app/migrations_pgsql_db/{m200000_000001_create_table_alldbdatatypes.php => m200000_000000_create_table_alldbdatatypes.php} (98%) rename tests/specs/x_db_type/edit_column/pgsql/app/migrations_pgsql_db/{m200000_000003_change_table_editcolumns.php => m200000_000001_change_table_editcolumns.php} (98%) rename tests/specs/x_db_type/edit_column/pgsql/app/migrations_pgsql_db/{m200000_000000_create_table_pristines.php => m200000_000003_create_table_pristines.php} (93%) diff --git a/tests/specs/x_db_type/edit_column/maria/app/migrations_maria_db/m200000_000001_create_table_alldbdatatypes.php b/tests/specs/x_db_type/edit_column/maria/app/migrations_maria_db/m200000_000000_create_table_alldbdatatypes.php similarity index 97% rename from tests/specs/x_db_type/edit_column/maria/app/migrations_maria_db/m200000_000001_create_table_alldbdatatypes.php rename to tests/specs/x_db_type/edit_column/maria/app/migrations_maria_db/m200000_000000_create_table_alldbdatatypes.php index 350eedaf..9c002bea 100644 --- a/tests/specs/x_db_type/edit_column/maria/app/migrations_maria_db/m200000_000001_create_table_alldbdatatypes.php +++ b/tests/specs/x_db_type/edit_column/maria/app/migrations_maria_db/m200000_000000_create_table_alldbdatatypes.php @@ -3,7 +3,7 @@ /** * Table for Alldbdatatype */ -class m200000_000001_create_table_alldbdatatypes extends \yii\db\Migration +class m200000_000000_create_table_alldbdatatypes extends \yii\db\Migration { public function up() { diff --git a/tests/specs/x_db_type/edit_column/maria/app/migrations_maria_db/m200000_000003_change_table_editcolumns.php b/tests/specs/x_db_type/edit_column/maria/app/migrations_maria_db/m200000_000001_change_table_editcolumns.php similarity index 97% rename from tests/specs/x_db_type/edit_column/maria/app/migrations_maria_db/m200000_000003_change_table_editcolumns.php rename to tests/specs/x_db_type/edit_column/maria/app/migrations_maria_db/m200000_000001_change_table_editcolumns.php index 3b9581c0..239c0a9b 100644 --- a/tests/specs/x_db_type/edit_column/maria/app/migrations_maria_db/m200000_000003_change_table_editcolumns.php +++ b/tests/specs/x_db_type/edit_column/maria/app/migrations_maria_db/m200000_000001_change_table_editcolumns.php @@ -3,7 +3,7 @@ /** * Table for Editcolumn */ -class m200000_000003_change_table_editcolumns extends \yii\db\Migration +class m200000_000001_change_table_editcolumns extends \yii\db\Migration { public function up() { diff --git a/tests/specs/x_db_type/edit_column/maria/app/migrations_maria_db/m200000_000000_create_table_pristines.php b/tests/specs/x_db_type/edit_column/maria/app/migrations_maria_db/m200000_000003_create_table_pristines.php similarity index 93% rename from tests/specs/x_db_type/edit_column/maria/app/migrations_maria_db/m200000_000000_create_table_pristines.php rename to tests/specs/x_db_type/edit_column/maria/app/migrations_maria_db/m200000_000003_create_table_pristines.php index d1594797..1e27d8d6 100644 --- a/tests/specs/x_db_type/edit_column/maria/app/migrations_maria_db/m200000_000000_create_table_pristines.php +++ b/tests/specs/x_db_type/edit_column/maria/app/migrations_maria_db/m200000_000003_create_table_pristines.php @@ -3,7 +3,7 @@ /** * Table for Pristine */ -class m200000_000000_create_table_pristines extends \yii\db\Migration +class m200000_000003_create_table_pristines extends \yii\db\Migration { public function up() { diff --git a/tests/specs/x_db_type/edit_column/mysql/app/migrations_mysql_db/m200000_000001_create_table_alldbdatatypes.php b/tests/specs/x_db_type/edit_column/mysql/app/migrations_mysql_db/m200000_000000_create_table_alldbdatatypes.php similarity index 97% rename from tests/specs/x_db_type/edit_column/mysql/app/migrations_mysql_db/m200000_000001_create_table_alldbdatatypes.php rename to tests/specs/x_db_type/edit_column/mysql/app/migrations_mysql_db/m200000_000000_create_table_alldbdatatypes.php index 5f3d90d1..2cda660f 100644 --- a/tests/specs/x_db_type/edit_column/mysql/app/migrations_mysql_db/m200000_000001_create_table_alldbdatatypes.php +++ b/tests/specs/x_db_type/edit_column/mysql/app/migrations_mysql_db/m200000_000000_create_table_alldbdatatypes.php @@ -3,7 +3,7 @@ /** * Table for Alldbdatatype */ -class m200000_000001_create_table_alldbdatatypes extends \yii\db\Migration +class m200000_000000_create_table_alldbdatatypes extends \yii\db\Migration { public function up() { diff --git a/tests/specs/x_db_type/edit_column/mysql/app/migrations_mysql_db/m200000_000003_change_table_editcolumns.php b/tests/specs/x_db_type/edit_column/mysql/app/migrations_mysql_db/m200000_000001_change_table_editcolumns.php similarity index 97% rename from tests/specs/x_db_type/edit_column/mysql/app/migrations_mysql_db/m200000_000003_change_table_editcolumns.php rename to tests/specs/x_db_type/edit_column/mysql/app/migrations_mysql_db/m200000_000001_change_table_editcolumns.php index 02626d1e..b4d63bd3 100644 --- a/tests/specs/x_db_type/edit_column/mysql/app/migrations_mysql_db/m200000_000003_change_table_editcolumns.php +++ b/tests/specs/x_db_type/edit_column/mysql/app/migrations_mysql_db/m200000_000001_change_table_editcolumns.php @@ -3,7 +3,7 @@ /** * Table for Editcolumn */ -class m200000_000003_change_table_editcolumns extends \yii\db\Migration +class m200000_000001_change_table_editcolumns extends \yii\db\Migration { public function up() { diff --git a/tests/specs/x_db_type/edit_column/mysql/app/migrations_mysql_db/m200000_000000_create_table_pristines.php b/tests/specs/x_db_type/edit_column/mysql/app/migrations_mysql_db/m200000_000003_create_table_pristines.php similarity index 93% rename from tests/specs/x_db_type/edit_column/mysql/app/migrations_mysql_db/m200000_000000_create_table_pristines.php rename to tests/specs/x_db_type/edit_column/mysql/app/migrations_mysql_db/m200000_000003_create_table_pristines.php index ab96f730..3e9e8e02 100644 --- a/tests/specs/x_db_type/edit_column/mysql/app/migrations_mysql_db/m200000_000000_create_table_pristines.php +++ b/tests/specs/x_db_type/edit_column/mysql/app/migrations_mysql_db/m200000_000003_create_table_pristines.php @@ -3,7 +3,7 @@ /** * Table for Pristine */ -class m200000_000000_create_table_pristines extends \yii\db\Migration +class m200000_000003_create_table_pristines extends \yii\db\Migration { public function up() { diff --git a/tests/specs/x_db_type/edit_column/pgsql/app/migrations_pgsql_db/m200000_000001_create_table_alldbdatatypes.php b/tests/specs/x_db_type/edit_column/pgsql/app/migrations_pgsql_db/m200000_000000_create_table_alldbdatatypes.php similarity index 98% rename from tests/specs/x_db_type/edit_column/pgsql/app/migrations_pgsql_db/m200000_000001_create_table_alldbdatatypes.php rename to tests/specs/x_db_type/edit_column/pgsql/app/migrations_pgsql_db/m200000_000000_create_table_alldbdatatypes.php index 7f8403d4..e0cac52a 100644 --- a/tests/specs/x_db_type/edit_column/pgsql/app/migrations_pgsql_db/m200000_000001_create_table_alldbdatatypes.php +++ b/tests/specs/x_db_type/edit_column/pgsql/app/migrations_pgsql_db/m200000_000000_create_table_alldbdatatypes.php @@ -3,7 +3,7 @@ /** * Table for Alldbdatatype */ -class m200000_000001_create_table_alldbdatatypes extends \yii\db\Migration +class m200000_000000_create_table_alldbdatatypes extends \yii\db\Migration { public function safeUp() { diff --git a/tests/specs/x_db_type/edit_column/pgsql/app/migrations_pgsql_db/m200000_000003_change_table_editcolumns.php b/tests/specs/x_db_type/edit_column/pgsql/app/migrations_pgsql_db/m200000_000001_change_table_editcolumns.php similarity index 98% rename from tests/specs/x_db_type/edit_column/pgsql/app/migrations_pgsql_db/m200000_000003_change_table_editcolumns.php rename to tests/specs/x_db_type/edit_column/pgsql/app/migrations_pgsql_db/m200000_000001_change_table_editcolumns.php index da02d58f..5ad21a0a 100644 --- a/tests/specs/x_db_type/edit_column/pgsql/app/migrations_pgsql_db/m200000_000003_change_table_editcolumns.php +++ b/tests/specs/x_db_type/edit_column/pgsql/app/migrations_pgsql_db/m200000_000001_change_table_editcolumns.php @@ -3,7 +3,7 @@ /** * Table for Editcolumn */ -class m200000_000003_change_table_editcolumns extends \yii\db\Migration +class m200000_000001_change_table_editcolumns extends \yii\db\Migration { public function safeUp() { diff --git a/tests/specs/x_db_type/edit_column/pgsql/app/migrations_pgsql_db/m200000_000000_create_table_pristines.php b/tests/specs/x_db_type/edit_column/pgsql/app/migrations_pgsql_db/m200000_000003_create_table_pristines.php similarity index 93% rename from tests/specs/x_db_type/edit_column/pgsql/app/migrations_pgsql_db/m200000_000000_create_table_pristines.php rename to tests/specs/x_db_type/edit_column/pgsql/app/migrations_pgsql_db/m200000_000003_create_table_pristines.php index 93b55396..aab6bb88 100644 --- a/tests/specs/x_db_type/edit_column/pgsql/app/migrations_pgsql_db/m200000_000000_create_table_pristines.php +++ b/tests/specs/x_db_type/edit_column/pgsql/app/migrations_pgsql_db/m200000_000003_create_table_pristines.php @@ -3,7 +3,7 @@ /** * Table for Pristine */ -class m200000_000000_create_table_pristines extends \yii\db\Migration +class m200000_000003_create_table_pristines extends \yii\db\Migration { public function safeUp() { From 1c86e8ec93d89cd0c0ff75013c1d0134faea1043 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Thu, 25 Jul 2024 15:47:04 +0530 Subject: [PATCH 097/358] Fix failing tests --- .../m200000_000002_delete_table_ubigpks.php | 6 --- .../mysql/models/base/Ubigpk.php | 22 +-------- tests/unit/IssueFixTest.php | 46 +++++++++---------- 3 files changed, 23 insertions(+), 51 deletions(-) diff --git a/tests/specs/issue_fix/132_create_migration_for_drop_table/case_independent_tables_drop_sort/mysql/migrations_mysql_db/m200000_000002_delete_table_ubigpks.php b/tests/specs/issue_fix/132_create_migration_for_drop_table/case_independent_tables_drop_sort/mysql/migrations_mysql_db/m200000_000002_delete_table_ubigpks.php index 574610ed..b21388c7 100644 --- a/tests/specs/issue_fix/132_create_migration_for_drop_table/case_independent_tables_drop_sort/mysql/migrations_mysql_db/m200000_000002_delete_table_ubigpks.php +++ b/tests/specs/issue_fix/132_create_migration_for_drop_table/case_independent_tables_drop_sort/mysql/migrations_mysql_db/m200000_000002_delete_table_ubigpks.php @@ -15,12 +15,6 @@ public function down() $this->createTable('{{%ubigpks}}', [ 'id' => $this->bigPrimaryKey()->unsigned(), 'name' => $this->string(150)->null()->defaultValue(null), - 'size' => 'enum("x-small", "small", "medium", "large", "x-large") NOT NULL DEFAULT \'x-small\'', - 'd' => 'smallint(5) unsigned zerofill NULL DEFAULT NULL', - 'e' => 'mediumint(8) unsigned zerofill NULL DEFAULT NULL', - 'f' => 'decimal(12,4) NULL DEFAULT NULL', - 'dp' => $this->double()->null()->defaultValue(null), - 'dp2' => 'double(10,4) NULL DEFAULT NULL', ]); } } diff --git a/tests/specs/issue_fix/132_create_migration_for_drop_table/case_independent_tables_drop_sort/mysql/models/base/Ubigpk.php b/tests/specs/issue_fix/132_create_migration_for_drop_table/case_independent_tables_drop_sort/mysql/models/base/Ubigpk.php index 3ffa6a51..5d1a93be 100644 --- a/tests/specs/issue_fix/132_create_migration_for_drop_table/case_independent_tables_drop_sort/mysql/models/base/Ubigpk.php +++ b/tests/specs/issue_fix/132_create_migration_for_drop_table/case_independent_tables_drop_sort/mysql/models/base/Ubigpk.php @@ -7,12 +7,6 @@ * * @property string $id * @property string $name - * @property string $size - * @property integer $d - * @property integer $e - * @property string $f - * @property double $dp - * @property double $dp2 * */ abstract class Ubigpk extends \yii\db\ActiveRecord @@ -25,22 +19,8 @@ public static function tableName() public function rules() { return [ - 'trim' => [['name', 'f'], 'trim'], + 'trim' => [['name'], 'trim'], 'name_string' => [['name'], 'string', 'max' => 150], - 'size_string' => [['size'], 'string'], - 'size_in' => [['size'], 'in', 'range' => [ - 'x-small', - 'small', - 'medium', - 'large', - 'x-large', - ]], - 'size_default' => [['size'], 'default', 'value' => 'x-small'], - 'd_integer' => [['d'], 'integer'], - 'e_integer' => [['e'], 'integer'], - 'f_string' => [['f'], 'string', 'max' => 12], - 'dp_double' => [['dp'], 'double'], - 'dp2_double' => [['dp2'], 'double'], ]; } } diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index 757e26c8..e0971dd0 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -239,25 +239,38 @@ public function testNullableFalseInRequired() $this->checkFiles($actualFiles, $expectedFiles); } - // Create migration for drop table if a entire schema is deleted from OpenAPI spec #132 - // https://github.com/cebe/yii2-openapi/issues/132 // https://github.com/php-openapi/yii2-openapi/pull/4#discussion_r1688225258 public function testCreateMigrationForDropTable132IndependentTablesDropSort() { $testFile = Yii::getAlias("@specs/issue_fix/132_create_migration_for_drop_table/case_independent_tables_drop_sort/index.php"); - $this->createTablesForCreateMigrationForDropTable132(); + + Yii::$app->db->createCommand()->createTable('{{%upks}}', [ + 'id' => 'upk', + 'name' => 'string(150)', + ])->execute(); + Yii::$app->db->createCommand()->createTable('{{%bigpks}}', [ + 'id' => 'bigpk', + 'name' => 'string(150)', + ])->execute(); + Yii::$app->db->createCommand()->createTable('{{%ubigpks}}', [ + 'id' => 'ubigpk', + 'name' => 'string(150)', + ])->execute(); + $this->runGenerator($testFile); $this->runActualMigrations('mysql', 4); $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ - 'recursive' => true, + 'recursive' => true, ]); $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/132_create_migration_for_drop_table/case_independent_tables_drop_sort/mysql"), [ - 'recursive' => true, + 'recursive' => true, ]); $this->checkFiles($actualFiles, $expectedFiles); - $this->deleteTablesForCreateMigrationForDropTable132(); + Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%ubigpks}}')->execute(); + Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%bigpks}}')->execute(); + Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%upks}}')->execute(); } // Create migration for drop table if a entire schema is deleted from OpenAPI spec #132 @@ -265,22 +278,9 @@ public function testCreateMigrationForDropTable132IndependentTablesDropSort() public function testCreateMigrationForDropTable132() { $testFile = Yii::getAlias("@specs/issue_fix/132_create_migration_for_drop_table/132_create_migration_for_drop_table.php"); - - Yii::$app->db->createCommand()->createTable('{{%upks}}', [ - 'id' => 'upk', - 'name' => 'string(150)', - ])->execute(); - Yii::$app->db->createCommand()->createTable('{{%bigpks}}', [ - 'id' => 'bigpk', - 'name' => 'string(150)', - ])->execute(); - Yii::$app->db->createCommand()->createTable('{{%ubigpks}}', [ - 'id' => 'ubigpk', - 'name' => 'string(150)', - ])->execute(); - + $this->createTablesForCreateMigrationForDropTable132(); $this->runGenerator($testFile); - $this->runActualMigrations('mysql', 3); + $this->runActualMigrations('mysql', 8); $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ 'recursive' => true, @@ -290,9 +290,7 @@ public function testCreateMigrationForDropTable132() ]); $this->checkFiles($actualFiles, $expectedFiles); - Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%bigpks}}')->execute(); - Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%bigpks}}')->execute(); - Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%bigpks}}')->execute(); + $this->deleteTablesForCreateMigrationForDropTable132(); } private function createTablesForCreateMigrationForDropTable132() From 8c764965a1a4fef16ac1124aa508e5a2c33ff862 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Fri, 26 Jul 2024 17:25:19 +0530 Subject: [PATCH 098/358] Remove TODO --- src/lib/generators/RestActionGenerator.php | 1 - 1 file changed, 1 deletion(-) diff --git a/src/lib/generators/RestActionGenerator.php b/src/lib/generators/RestActionGenerator.php index 9796be02..ba8920ec 100644 --- a/src/lib/generators/RestActionGenerator.php +++ b/src/lib/generators/RestActionGenerator.php @@ -78,7 +78,6 @@ protected function resolvePath(string $path, PathItem $pathItem):array $customRoute = $operation->{CustomSpecAttr::ROUTE}; } - // TODO rename $action = $this->prepareAction($method, $operation, $routeData, $customRoute); if ($customRoute !== null) { if (in_array($customRoute, array_keys($this->allCustomRoutes))) { From 5f7e9932872b6ed4427d91803fdb777279bd95d8 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Fri, 26 Jul 2024 18:37:18 +0530 Subject: [PATCH 099/358] Refactor --- src/generator/ApiGenerator.php | 2 +- src/lib/generators/RestActionGenerator.php | 4 ++-- src/lib/items/RestAction.php | 6 +++--- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/generator/ApiGenerator.php b/src/generator/ApiGenerator.php index 5a1f83c5..fe135c5d 100644 --- a/src/generator/ApiGenerator.php +++ b/src/generator/ApiGenerator.php @@ -541,7 +541,7 @@ public static function removeDuplicateActions(array $actions): array $actions = array_map(function ($action) { /** @var $action RestAction|FractalAction */ - if ($action instanceof RestAction && $action->isOriginalForCustomRoute) { + if ($action instanceof RestAction && $action->zeroParams) { $action->idParam = null; $action->params = []; } diff --git a/src/lib/generators/RestActionGenerator.php b/src/lib/generators/RestActionGenerator.php index ba8920ec..b8d5998c 100644 --- a/src/lib/generators/RestActionGenerator.php +++ b/src/lib/generators/RestActionGenerator.php @@ -82,8 +82,8 @@ protected function resolvePath(string $path, PathItem $pathItem):array if ($customRoute !== null) { if (in_array($customRoute, array_keys($this->allCustomRoutes))) { $action->isDuplicate = true; - if ($action->params !== $this->allCustomRoutes[$customRoute]) { - $this->allCustomRoutes[$customRoute]->isOriginalForCustomRoute = true; + if ($action->params !== $this->allCustomRoutes[$customRoute]->params) { + $this->allCustomRoutes[$customRoute]->zeroParams = true; } } else { $action->isDuplicate = false; diff --git a/src/lib/items/RestAction.php b/src/lib/items/RestAction.php index fc82712f..5192997a 100644 --- a/src/lib/items/RestAction.php +++ b/src/lib/items/RestAction.php @@ -74,15 +74,15 @@ final class RestAction extends BaseObject * https://github.com/cebe/yii2-openapi/issues/84 * see `x-route` in README.md * Used for generating only one action for paths like: `GET /calendar/domains` and `GET /calendar/domains/{id}` given that they have same `x-route`. - * This is used to flag first of one or more duplicates + * If duplicates routes have same params then `false`, else action is generated with no (0) params `true` */ - public $isOriginalForCustomRoute = false; + public $zeroParams = false; /** * @var bool * https://github.com/cebe/yii2-openapi/issues/84 * Generate only one action for paths like: `GET /calendar/domains` and `GET /calendar/domains/{id}` given that they have same `x-route`. - * @see $isOriginalForCustomRoute + * @see $zeroParams * see `x-route` in README.md */ public $isDuplicate = false; From 9380c43ac9f3a0fa73a99eded52937b99a7525e3 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Sat, 27 Jul 2024 20:20:11 +0530 Subject: [PATCH 100/358] Fix TODO: MySQL "mysql_native_password" setting for PHP >= 7.4 --- Makefile | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/Makefile b/Makefile index 6d1a22dc..f6c70198 100644 --- a/Makefile +++ b/Makefile @@ -39,9 +39,8 @@ up: echo "Waiting for mariadb to start up..." docker-compose exec -T mysql timeout 60s sh -c "while ! (mysql -udbuser -pdbpass -h maria --execute 'SELECT 1;' > /dev/null 2>&1); do echo -n '.'; sleep 0.1 ; done; echo 'ok'" || (docker-compose ps; docker-compose logs; exit 1) - # Solution to problem https://stackoverflow.com/questions/50026939/php-mysqli-connect-authentication-method-unknown-to-the-client-caching-sha2-pa - # if updated to PHP 7.4 or more, this command is not needed (TODO) - docker-compose exec -T mysql timeout 60s sh -c "while ! (mysql --execute \"ALTER USER 'dbuser'@'%' IDENTIFIED WITH mysql_native_password BY 'dbpass';\" > /dev/null 2>&1); do echo -n '.'; sleep 0.1 ; done; echo 'ok'" || (docker-compose ps; docker-compose logs; exit 1) + echo "Waiting for Mysql to start up..." + docker-compose exec -T mysql timeout 60s sh -c "while ! (mysql -udbuser -pdbpass -h mysql --execute 'SELECT 1;' > /dev/null 2>&1); do echo -n '.'; sleep 0.1 ; done; echo 'ok'" || (docker-compose ps; docker-compose logs; exit 1) cli: docker-compose exec --user=$(UID) php bash From 35c6f956a2ac98bec22713462f0518df0193bbb2 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Sun, 28 Jul 2024 17:31:32 +0530 Subject: [PATCH 101/358] Use cache in tests in Github actions https://github.com/php-openapi/yii2-openapi/issues/17 --- .github/workflows/test.yml | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 146e6518..a650e5d4 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -42,6 +42,17 @@ jobs: - name: docker-compose up run: make up + - name: Get composer cache directory + id: composer-cache + run: echo "dir=$(composer config cache-files-dir)" >> $GITHUB_OUTPUT + + - name: Cache dependencies + uses: actions/cache@v4 + with: + path: ${{ steps.composer-cache.outputs.dir }} + key: ${{ runner.os }}-composer-${{ hashFiles('**/composer.json') }} + restore-keys: ${{ runner.os }}-composer- + - name: Install Docker and composer dependencies run: docker-compose exec php php -v && make installdocker From ed532b08f3caefbc59ea7b088d60356beaa96a67 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Mon, 29 Jul 2024 14:02:30 +0530 Subject: [PATCH 102/358] Attempt 2 --- .github/workflows/test.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index a650e5d4..c0a4bd4f 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -50,7 +50,7 @@ jobs: uses: actions/cache@v4 with: path: ${{ steps.composer-cache.outputs.dir }} - key: ${{ runner.os }}-composer-${{ hashFiles('**/composer.json') }} + key: ${{ runner.os }}-composer-${{ hashFiles('composer.json') }} restore-keys: ${{ runner.os }}-composer- - name: Install Docker and composer dependencies From d0b6c7a020c8a04972b55d57a8fc5f80c03cd48d Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Mon, 29 Jul 2024 14:08:32 +0530 Subject: [PATCH 103/358] Check if cache is used --- src/lib/generators/JsonActionGenerator.php | 1 + 1 file changed, 1 insertion(+) diff --git a/src/lib/generators/JsonActionGenerator.php b/src/lib/generators/JsonActionGenerator.php index 696f7974..39932ffd 100644 --- a/src/lib/generators/JsonActionGenerator.php +++ b/src/lib/generators/JsonActionGenerator.php @@ -61,6 +61,7 @@ protected function prepareAction(string $method, Operation $operation, RouteData $transformerClass = $modelClass !== null ? $this->config->transformerNamespace . '\\' . Inflector::id2camel($modelClass, '_') . 'Transformer' : null; + } if ($routeData->type === RouteData::TYPE_RESOURCE_OPERATION && !$modelClass) { From 0abc782dbcddb2e499b5af8a3255c7adb95df64b Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Mon, 29 Jul 2024 14:27:01 +0530 Subject: [PATCH 104/358] Undo change --- src/lib/generators/JsonActionGenerator.php | 1 - 1 file changed, 1 deletion(-) diff --git a/src/lib/generators/JsonActionGenerator.php b/src/lib/generators/JsonActionGenerator.php index 39932ffd..696f7974 100644 --- a/src/lib/generators/JsonActionGenerator.php +++ b/src/lib/generators/JsonActionGenerator.php @@ -61,7 +61,6 @@ protected function prepareAction(string $method, Operation $operation, RouteData $transformerClass = $modelClass !== null ? $this->config->transformerNamespace . '\\' . Inflector::id2camel($modelClass, '_') . 'Transformer' : null; - } if ($routeData->type === RouteData::TYPE_RESOURCE_OPERATION && !$modelClass) { From bb61c04d0dc701512abe9b4be11d8ee185967031 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Mon, 29 Jul 2024 15:27:19 +0530 Subject: [PATCH 105/358] Check if cache is created and stored --- Makefile | 7 ++++++- src/lib/generators/JsonActionGenerator.php | 2 +- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/Makefile b/Makefile index 6d1a22dc..1585a37c 100644 --- a/Makefile +++ b/Makefile @@ -1,3 +1,8 @@ +# set user to "root" to run commands as root in Docker +#USER=$$(whoami) +# The docker command to execute commands directly in Docker +#DOCKER=docker-compose exec -T --user="$(USER)" php + PHPARGS=-dmemory_limit=64M #PHPARGS=-dmemory_limit=64M -dzend_extension=xdebug.so -dxdebug.remote_enable=1 -dxdebug.remote_host=127.0.0.1 -dxdebug.remote_autostart=1 #PHPARGS=-dmemory_limit=64M -dxdebug.remote_enable=1 @@ -44,7 +49,7 @@ up: docker-compose exec -T mysql timeout 60s sh -c "while ! (mysql --execute \"ALTER USER 'dbuser'@'%' IDENTIFIED WITH mysql_native_password BY 'dbpass';\" > /dev/null 2>&1); do echo -n '.'; sleep 0.1 ; done; echo 'ok'" || (docker-compose ps; docker-compose logs; exit 1) cli: - docker-compose exec --user=$(UID) php bash + docker-compose exec --user="root" php bash # --user=$(UID) cli_mysql: docker-compose exec --user=$(UID) mysql bash diff --git a/src/lib/generators/JsonActionGenerator.php b/src/lib/generators/JsonActionGenerator.php index 696f7974..6434cb53 100644 --- a/src/lib/generators/JsonActionGenerator.php +++ b/src/lib/generators/JsonActionGenerator.php @@ -27,7 +27,7 @@ class JsonActionGenerator extends RestActionGenerator * @throws \cebe\openapi\exceptions\UnresolvableReferenceException */ protected function prepareAction(string $method, Operation $operation, RouteData $routeData):BaseObject - { + { # $actionType = $this->resolveActionType($routeData, $method); $modelClass = ResponseSchema::guessModelClass($operation, $actionType); $expectedRelations = in_array($actionType, ['list', 'view']) From 9ee0d319746581306cf4aa24d77c60219eef2af2 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Mon, 29 Jul 2024 15:46:01 +0530 Subject: [PATCH 106/358] Cache dir --- .github/workflows/test.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index c0a4bd4f..86b87157 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -44,7 +44,8 @@ jobs: - name: Get composer cache directory id: composer-cache - run: echo "dir=$(composer config cache-files-dir)" >> $GITHUB_OUTPUT +# run: echo "dir=$(composer config cache-files-dir)" >> $GITHUB_OUTPUT + run: echo "dir=./tests/tmp/.composer/cache/files" >> $GITHUB_OUTPUT - name: Cache dependencies uses: actions/cache@v4 From 8a41c8a3b983bda987d1bd0765cc307f2c892cd6 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Mon, 29 Jul 2024 15:48:43 +0530 Subject: [PATCH 107/358] Fix user in `make installdocker` --- Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Makefile b/Makefile index 1585a37c..6313a46c 100644 --- a/Makefile +++ b/Makefile @@ -60,7 +60,7 @@ migrate: docker-compose run --user=$(UID) --rm php sh -c 'cd /app/tests && ./yii migrate --interactive=0' installdocker: - docker-compose run --user=$(UID) --rm php composer install && chmod +x tests/yii + docker-compose run --user="root" --rm php composer install && chmod +x tests/yii testdocker: docker-compose run --user=$(UID) --rm php sh -c 'vendor/bin/phpunit --repeat 3' From 4a24aa7277362069afffbfb96b7105363b72574b Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Mon, 29 Jul 2024 15:53:38 +0530 Subject: [PATCH 108/358] Check if cache is used --- src/lib/generators/JsonActionGenerator.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/lib/generators/JsonActionGenerator.php b/src/lib/generators/JsonActionGenerator.php index 6434cb53..696f7974 100644 --- a/src/lib/generators/JsonActionGenerator.php +++ b/src/lib/generators/JsonActionGenerator.php @@ -27,7 +27,7 @@ class JsonActionGenerator extends RestActionGenerator * @throws \cebe\openapi\exceptions\UnresolvableReferenceException */ protected function prepareAction(string $method, Operation $operation, RouteData $routeData):BaseObject - { # + { $actionType = $this->resolveActionType($routeData, $method); $modelClass = ResponseSchema::guessModelClass($operation, $actionType); $expectedRelations = in_array($actionType, ['list', 'view']) From 48d5010fc082b904e5549c12f9345e8940d06ee3 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Mon, 29 Jul 2024 19:06:25 +0530 Subject: [PATCH 109/358] Fix mariadb client in new version --- docker-compose.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docker-compose.yml b/docker-compose.yml index 9b71bf9e..08d61292 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -45,7 +45,7 @@ services: ports: - '23306:3306' volumes: - - ./tests/tmp/maria:/var/lib/mysql:rw + - ./tests/tmp/mariadb:/var/lib/mariadb:rw environment: # TZ: UTC # MARIADB_ALLOW_EMPTY_PASSWORD: 1 From 6cc272e999ca1c11496f5940db3839b69beab996 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Wed, 31 Jul 2024 19:11:31 +0530 Subject: [PATCH 110/358] Make directory writable to restore cache --- .github/workflows/test.yml | 3 +++ CONTRIBUTING.md | 2 +- Makefile | 3 +++ 3 files changed, 7 insertions(+), 1 deletion(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 86b87157..f479cd02 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -47,6 +47,9 @@ jobs: # run: echo "dir=$(composer config cache-files-dir)" >> $GITHUB_OUTPUT run: echo "dir=./tests/tmp/.composer/cache/files" >> $GITHUB_OUTPUT + - name: Make tests dir writable for restoring cache in next step + run: make tests_dir_write_permission + - name: Cache dependencies uses: actions/cache@v4 with: diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index e1a62b7d..a5e4abe8 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -10,7 +10,7 @@ cd yii2-openapi make clean_all make up make installdocker -sudo chmod -R 777 tests/tmp/ # https://github.com/cebe/yii2-openapi/issues/156 +sudo chmod -R 777 tests/tmp/ # TODO avoid 777 https://github.com/cebe/yii2-openapi/issues/156 make migrate # to check everything is setup up correctly ensure all tests passes diff --git a/Makefile b/Makefile index 6313a46c..070364da 100644 --- a/Makefile +++ b/Makefile @@ -62,6 +62,9 @@ migrate: installdocker: docker-compose run --user="root" --rm php composer install && chmod +x tests/yii +tests_dir_write_permission: + docker compose run --user="root" --rm php chmod -R 777 tests/tmp/ # TODO avoid 777 + testdocker: docker-compose run --user=$(UID) --rm php sh -c 'vendor/bin/phpunit --repeat 3' From e6b177676e1f0e6609a3d9cacada40768a0ab0e8 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Wed, 31 Jul 2024 19:17:36 +0530 Subject: [PATCH 111/358] Minor changes --- Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Makefile b/Makefile index 070364da..661cde4a 100644 --- a/Makefile +++ b/Makefile @@ -63,7 +63,7 @@ installdocker: docker-compose run --user="root" --rm php composer install && chmod +x tests/yii tests_dir_write_permission: - docker compose run --user="root" --rm php chmod -R 777 tests/tmp/ # TODO avoid 777 + docker-compose run --user="root" --rm php chmod -R 777 tests/tmp/ # TODO avoid 777 https://github.com/cebe/yii2-openapi/issues/156 testdocker: docker-compose run --user=$(UID) --rm php sh -c 'vendor/bin/phpunit --repeat 3' From 9c690a6b9e0a60c1de7a69a0cd437d502c781767 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Wed, 31 Jul 2024 19:21:21 +0530 Subject: [PATCH 112/358] Enhance --- .github/workflows/test.yml | 2 +- Makefile | 7 +------ 2 files changed, 2 insertions(+), 7 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index f479cd02..61a529fe 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -42,9 +42,9 @@ jobs: - name: docker-compose up run: make up + # https://github.com/shivammathur/setup-php?tab=readme-ov-file#cache-composer-dependencies - name: Get composer cache directory id: composer-cache -# run: echo "dir=$(composer config cache-files-dir)" >> $GITHUB_OUTPUT run: echo "dir=./tests/tmp/.composer/cache/files" >> $GITHUB_OUTPUT - name: Make tests dir writable for restoring cache in next step diff --git a/Makefile b/Makefile index 661cde4a..ccdb082c 100644 --- a/Makefile +++ b/Makefile @@ -1,8 +1,3 @@ -# set user to "root" to run commands as root in Docker -#USER=$$(whoami) -# The docker command to execute commands directly in Docker -#DOCKER=docker-compose exec -T --user="$(USER)" php - PHPARGS=-dmemory_limit=64M #PHPARGS=-dmemory_limit=64M -dzend_extension=xdebug.so -dxdebug.remote_enable=1 -dxdebug.remote_host=127.0.0.1 -dxdebug.remote_autostart=1 #PHPARGS=-dmemory_limit=64M -dxdebug.remote_enable=1 @@ -60,7 +55,7 @@ migrate: docker-compose run --user=$(UID) --rm php sh -c 'cd /app/tests && ./yii migrate --interactive=0' installdocker: - docker-compose run --user="root" --rm php composer install && chmod +x tests/yii + docker-compose run --user=$(UID) --rm php composer install && chmod +x tests/yii tests_dir_write_permission: docker-compose run --user="root" --rm php chmod -R 777 tests/tmp/ # TODO avoid 777 https://github.com/cebe/yii2-openapi/issues/156 From 3950865960d6d1804d3eba2f54d740adab5036dc Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Wed, 31 Jul 2024 19:22:25 +0530 Subject: [PATCH 113/358] Revert a change --- Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Makefile b/Makefile index ccdb082c..d35506d7 100644 --- a/Makefile +++ b/Makefile @@ -44,7 +44,7 @@ up: docker-compose exec -T mysql timeout 60s sh -c "while ! (mysql --execute \"ALTER USER 'dbuser'@'%' IDENTIFIED WITH mysql_native_password BY 'dbpass';\" > /dev/null 2>&1); do echo -n '.'; sleep 0.1 ; done; echo 'ok'" || (docker-compose ps; docker-compose logs; exit 1) cli: - docker-compose exec --user="root" php bash # --user=$(UID) + docker-compose exec --user=$(UID) php bash cli_mysql: docker-compose exec --user=$(UID) mysql bash From 4b8c742300c95ad81251929c28d385dc51285cff Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Wed, 31 Jul 2024 19:35:27 +0530 Subject: [PATCH 114/358] Resolve this TODO --- .github/workflows/test.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 61a529fe..8487efc3 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -22,7 +22,6 @@ jobs: matrix: php-versions: ['7.4', '8.0', '8.1', '8.2', '8.3'] - # TODO use cache steps: - uses: actions/checkout@v3 From 2f9aa2e8cf39845acfac08c901084b89efefee9f Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Thu, 1 Aug 2024 17:20:32 +0530 Subject: [PATCH 115/358] Initial commit to create a PR --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 1cd2090b..3bb79307 100644 --- a/README.md +++ b/README.md @@ -568,3 +568,4 @@ Professional support, consulting as well as software development services are av https://www.cebe.cc/en/contact Development of this library is sponsored by [cebe.:cloud: "Your Professional Deployment Platform"](https://cebe.cloud). + From fa7c240ab72236ba8cbeb8f1dd28be1e72d737cc Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Fri, 2 Aug 2024 20:39:02 +0530 Subject: [PATCH 116/358] Implement for multiple data types --- Makefile | 3 ++ README.md | 1 - composer.json | 3 +- src/lib/FakerStubResolver.php | 30 ++++++++++---- tests/specs/blog_v2/models/CommentFaker.php | 2 +- .../index.php | 13 +++++++ .../index.yaml | 39 +++++++++++++++++++ tests/unit/IssueFixTest.php | 14 +++++++ 8 files changed, 94 insertions(+), 11 deletions(-) create mode 100644 tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/index.php create mode 100644 tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/index.yaml diff --git a/Makefile b/Makefile index 6d1a22dc..abc62f03 100644 --- a/Makefile +++ b/Makefile @@ -46,6 +46,9 @@ up: cli: docker-compose exec --user=$(UID) php bash +cli_root: + docker-compose exec --user="root" php bash + cli_mysql: docker-compose exec --user=$(UID) mysql bash diff --git a/README.md b/README.md index 3bb79307..1cd2090b 100644 --- a/README.md +++ b/README.md @@ -568,4 +568,3 @@ Professional support, consulting as well as software development services are av https://www.cebe.cc/en/contact Development of this library is sponsored by [cebe.:cloud: "Your Professional Deployment Platform"](https://cebe.cloud). - diff --git a/composer.json b/composer.json index 735e5f07..f17b6050 100644 --- a/composer.json +++ b/composer.json @@ -25,7 +25,8 @@ "laminas/laminas-code": ">=3.4 <=4.13", "php-openapi/yii2-fractal": "^1.0.0", "fakerphp/faker": "^1.9", - "sam-it/yii2-mariadb": "^2.0" + "sam-it/yii2-mariadb": "^2.0", + "symfony/var-exporter": "^5.4" }, "require-dev": { "cebe/indent": "*", diff --git a/src/lib/FakerStubResolver.php b/src/lib/FakerStubResolver.php index bd11bc2a..60132c7c 100644 --- a/src/lib/FakerStubResolver.php +++ b/src/lib/FakerStubResolver.php @@ -12,6 +12,7 @@ use cebe\yii2openapi\lib\items\Attribute; use cebe\yii2openapi\lib\openapi\PropertySchema; use yii\helpers\VarDumper; +use Symfony\Component\VarExporter\VarExporter; use function str_replace; use const PHP_EOL; @@ -61,7 +62,7 @@ public function resolve():?string return null; } - // column name ends with `_id` + // column name ends with `_id`/FK if (substr($this->attribute->columnName, -3) === '_id' || !empty($this->attribute->fkColName)) { $config = $this->config; if (!$config) { @@ -76,20 +77,34 @@ public function resolve():?string $limits = $this->attribute->limits; switch ($this->attribute->phpType) { case 'bool': - return '$faker->boolean'; + $result = '$faker->boolean'; + break; case 'int': case 'integer': - return $this->fakeForInt($limits['min'], $limits['max']); + $result = $this->fakeForInt($limits['min'], $limits['max']); + break; case 'string': - return $this->fakeForString(); + $result = $this->fakeForString(); + break; case 'float': case 'double': - return $this->fakeForFloat($limits['min'], $limits['max']); + $result = $this->fakeForFloat($limits['min'], $limits['max']); + break; case 'array': - return $this->fakeForArray(); + $result = $this->fakeForArray(); + break; default: return null; } + if (! $this->property->hasAttr('example')) { + return $result; + } + if (stripos($result, 'uniqueFaker') !== false) { + return $result; + } + $example = $this->property->getAttr('example'); + $example = VarExporter::export($example); + return str_replace('$faker->', '$faker->optional(0.92, '.$example.')->', $result); } private function fakeForString():?string @@ -167,8 +182,6 @@ private function fakeForString():?string } } - // TODO maybe also consider OpenAPI examples here - if ($size) { $method = 'text'; if ($size < 5) { @@ -227,6 +240,7 @@ private function fakeForFloat(?int $min, ?int $max):?string private function fakeForArray():string { +// return '$faker->words()'; // TODO if ($this->attribute->required) { return '["a" => "b"]'; } diff --git a/tests/specs/blog_v2/models/CommentFaker.php b/tests/specs/blog_v2/models/CommentFaker.php index 968d1a10..68535e74 100644 --- a/tests/specs/blog_v2/models/CommentFaker.php +++ b/tests/specs/blog_v2/models/CommentFaker.php @@ -33,7 +33,7 @@ public function generateModel($attributes = []) $model->post_id = $faker->randomElement(\app\models\Post::find()->select("id")->column()); $model->user_id = $faker->randomElement(\app\models\User::find()->select("id")->column()); $model->message = $faker->sentence; - $model->meta_data = substr($faker->text(300), 0, 300); + $model->meta_data = substr($faker->optional(0.92, 'type==\'ticket\' && status==\'closed\'')->text(300), 0, 300); $model->created_at = $faker->dateTimeThisYear('now', 'UTC')->format('Y-m-d H:i:s'); if (!is_callable($attributes)) { $model->setAttributes($attributes, false); diff --git a/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/index.php b/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/index.php new file mode 100644 index 00000000..6afa241e --- /dev/null +++ b/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/index.php @@ -0,0 +1,13 @@ + '@specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/index.yaml', + 'generateUrls' => false, + 'generateModels' => true, +// 'excludeModels' => [ +// 'Error', +// ], + 'generateControllers' => false, + 'generateMigrations' => false, + 'generateModelFaker' => true, // `generateModels` must be `true` in order to use `generateModelFaker` as `true` +]; diff --git a/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/index.yaml b/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/index.yaml new file mode 100644 index 00000000..4a72e48a --- /dev/null +++ b/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/index.yaml @@ -0,0 +1,39 @@ +openapi: "3.0.0" +info: + version: 1.0.0 + title: Consider OpenAPI spec examples in faker code generation https://github.com/php-openapi/yii2-openapi/issues/20 + +paths: + /pet: + get: + summary: get a pet + operationId: aPet + responses: + 200: + description: A pet + content: + application/json: + schema: + $ref: "#/components/schemas/Pet" + +components: + schemas: + Pet: + required: + - id + - name + properties: + id: + type: integer + name: + type: string + example: cat +# example: ['long-tail', 'short-tail', 'black', 'white'] + age: + type: integer + example: 2 + tags: + type: array + items: + type: string + example: ['long-tail', 'short-tail', 'black', 'white'] diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index b6c7abdb..b6a4481a 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -360,4 +360,18 @@ public function test158BugGiiapiGeneratedRulesEnumWithTrim() ]); $this->checkFiles($actualFiles, $expectedFiles); } + + // https://github.com/php-openapi/yii2-openapi/issues/20 + public function test20ConsiderOpenApiSpecExamplesInFakeCodeGeneration() + { + $testFile = Yii::getAlias("@specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/index.php"); + $this->runGenerator($testFile); + $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ + 'recursive' => true, + ]); + $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/mysql"), [ + 'recursive' => true, + ]); +// $this->checkFiles($actualFiles, $expectedFiles); // TODO + } } From c0405e81e210b01d67dce046a8e4421020218941 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Tue, 6 Aug 2024 18:47:40 +0530 Subject: [PATCH 117/358] Implement faker generation of array - WIP --- src/lib/FakerStubResolver.php | 60 +++++++++++++++++-- .../index.yaml | 38 +++++++++++- tests/unit/IssueFixTest.php | 12 ++-- 3 files changed, 98 insertions(+), 12 deletions(-) diff --git a/src/lib/FakerStubResolver.php b/src/lib/FakerStubResolver.php index 60132c7c..c215e3e7 100644 --- a/src/lib/FakerStubResolver.php +++ b/src/lib/FakerStubResolver.php @@ -11,8 +11,9 @@ use cebe\yii2openapi\lib\items\Attribute; use cebe\yii2openapi\lib\openapi\PropertySchema; -use yii\helpers\VarDumper; use Symfony\Component\VarExporter\VarExporter; +use yii\helpers\Json; +use yii\helpers\VarDumper; use function str_replace; use const PHP_EOL; @@ -238,12 +239,61 @@ private function fakeForFloat(?int $min, ?int $max):?string return '$faker->randomFloat()'; } - private function fakeForArray():string + private function fakeForArray(): string { -// return '$faker->words()'; // TODO - if ($this->attribute->required) { - return '["a" => "b"]'; + // TODO consider example of OpenAPI spec + $property = Json::decode(Json::encode($this->property->getProperty()->getSerializableData())); + + $arbitrary = false; + $uniqueItems = false; + $type = null; + $count = 4; # let's set a number to default number of elements + + if (isset($property['items'])) { + $items = $property['items']; + if ($items === []) { + $arbitrary = true; + } + if (isset($items['type'])) { + $type = $items['type']; + } + } + + if (isset($property['minItems'])) { + $minItems = (int)$property['minItems']; + $count = $minItems; + } + + if (isset($property['maxItems'])) { + $maxItems = (int)$property['maxItems']; + if ($maxItems < $count) { + $count = $maxItems; + } } + + if (isset($property['uniqueItems'])) { + $uniqueItems = (bool)$property['uniqueItems']; + } + + if ($arbitrary || $type === 'string') { + return ($uniqueItems ? '$uniqueFaker' : '$faker') . '->words(' . $count . ')'; + } + + if (in_array($type, ['number', 'integer'])) { + return 'array_fill(0, ' . ($count) . ', ' . ($uniqueItems ? '$uniqueFaker' : '$faker') . '->randomNumber())'; + } + + if ($type == 'boolean') { + return 'array_fill(0, ' . ($count) . ', ' . ($uniqueItems ? '$uniqueFaker' : '$faker') . '->boolean())'; + } + + // TODO more complex type array/object; also consider $ref; may be recursively; may use `oneOf` + +// return '$faker->words()'; // TODO implement faker for array; also consider min, max, unique + +// if ($this->attribute->required) { +// return '["a" => "b"]'; // TODO this is incorrect, array schema should be checked first +// } return '[]'; } } diff --git a/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/index.yaml b/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/index.yaml index 4a72e48a..325a04f2 100644 --- a/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/index.yaml +++ b/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/index.yaml @@ -36,4 +36,40 @@ components: type: array items: type: string - example: ['long-tail', 'short-tail', 'black', 'white'] + tags_arbit: + type: array + items: { } # array of arbitrary types e.g. [ "hello", -2, true, [5.7], {"id": 5} ] + minItems: 6 + maxItems: 10 + uniqueItems: true + # type: string + # example: ['long-tail', 'short-tail', 'black', 'white'] + number_arr: + type: array + items: + type: number + + number_arr_min_uniq: + type: array + items: + type: number + minItems: 6 + uniqueItems: true + + int_arr: + type: array + items: + type: integer + + int_arr_min_uniq: + type: array + items: + type: integer + minItems: 7 + uniqueItems: true + + bool_arr: + type: array + items: + type: boolean + diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index b6a4481a..197a9eca 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -366,12 +366,12 @@ public function test20ConsiderOpenApiSpecExamplesInFakeCodeGeneration() { $testFile = Yii::getAlias("@specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/index.php"); $this->runGenerator($testFile); - $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ - 'recursive' => true, - ]); - $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/mysql"), [ - 'recursive' => true, - ]); +// $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ +// 'recursive' => true, +// ]); +// $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/mysql"), [ +// 'recursive' => true, +// ]); // $this->checkFiles($actualFiles, $expectedFiles); // TODO } } From 701d6126ea542a87eb9ac0098ad1980ad40ad066 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Thu, 8 Aug 2024 18:43:21 +0530 Subject: [PATCH 118/358] WIP 2 --- src/lib/FakerStubResolver.php | 59 ++++++++++++------- .../index.yaml | 45 +++++++++++++- 2 files changed, 83 insertions(+), 21 deletions(-) diff --git a/src/lib/FakerStubResolver.php b/src/lib/FakerStubResolver.php index c215e3e7..1089d27f 100644 --- a/src/lib/FakerStubResolver.php +++ b/src/lib/FakerStubResolver.php @@ -9,10 +9,10 @@ /** @noinspection PhpUndefinedFieldInspection */ namespace cebe\yii2openapi\lib; +use cebe\openapi\SpecObjectInterface; use cebe\yii2openapi\lib\items\Attribute; use cebe\yii2openapi\lib\openapi\PropertySchema; use Symfony\Component\VarExporter\VarExporter; -use yii\helpers\Json; use yii\helpers\VarDumper; use function str_replace; use const PHP_EOL; @@ -92,7 +92,7 @@ public function resolve():?string $result = $this->fakeForFloat($limits['min'], $limits['max']); break; case 'array': - $result = $this->fakeForArray(); + $result = $this->fakeForArray($this->property->getProperty()); break; default: return null; @@ -239,40 +239,39 @@ private function fakeForFloat(?int $min, ?int $max):?string return '$faker->randomFloat()'; } - private function fakeForArray(): string + private function fakeForArray(SpecObjectInterface $property): string { // TODO consider example of OpenAPI spec - $property = Json::decode(Json::encode($this->property->getProperty()->getSerializableData())); - $arbitrary = false; $uniqueItems = false; $type = null; $count = 4; # let's set a number to default number of elements - if (isset($property['items'])) { - $items = $property['items']; - if ($items === []) { + $items = $property->items; + + if ($items) { + $type = $items->type; + if ($items->type === null) { $arbitrary = true; } - if (isset($items['type'])) { - $type = $items['type']; - } + } else { + $arbitrary = true; } - if (isset($property['minItems'])) { - $minItems = (int)$property['minItems']; + if ($property->minItems) { + $minItems = $property->minItems; $count = $minItems; } - if (isset($property['maxItems'])) { - $maxItems = (int)$property['maxItems']; + if ($property->maxItems) { + $maxItems = $property->maxItems; if ($maxItems < $count) { $count = $maxItems; } } - if (isset($property['uniqueItems'])) { - $uniqueItems = (bool)$property['uniqueItems']; + if (isset($property->uniqueItems)) { + $uniqueItems = $property->uniqueItems; } if ($arbitrary || $type === 'string') { @@ -280,13 +279,33 @@ private function fakeForArray(): string } if (in_array($type, ['number', 'integer'])) { - return 'array_fill(0, ' . ($count) . ', ' . ($uniqueItems ? '$uniqueFaker' : '$faker') . '->randomNumber())'; + return 'array_map(function () use ($faker, $uniqueFaker) { + return ' . ($uniqueItems ? '$uniqueFaker' : '$faker') . '->randomNumber(); + }, range(1, ' . $count . '))'; } - if ($type == 'boolean') { - return 'array_fill(0, ' . ($count) . ', ' . ($uniqueItems ? '$uniqueFaker' : '$faker') . '->boolean())'; + if ($type === 'boolean') { + return 'array_map(function () use ($faker, $uniqueFaker) { + return ' . ($uniqueItems ? '$uniqueFaker' : '$faker') . '->boolean(); + }, range(1, ' . $count . '))'; } + if ($type === 'array') { # array or nested arrays + return 'array_map(function () use ($faker, $uniqueFaker) { + return ' . $this->fakeForArray($items) . '; + }, range(1, ' . $count . '))'; + } +// +// if ($type === 'object') { +// $props = []; +// foreach ($items['properties'] ?? [] as $name => $prop) { +// $props[$name] = $this->fakeForArray($prop); +// } +// return 'array_map(function () use ($faker, $uniqueFaker) { +// return ' .VarExporter::export($props[$name]). '; +// }, range(1, '.$count.'))'; +// } + // TODO more complex type array/object; also consider $ref; may be recursively; may use `oneOf` // return '$faker->words()'; // TODO implement faker for array; also consider min, max, unique diff --git a/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/index.yaml b/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/index.yaml index 325a04f2..83b4a75c 100644 --- a/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/index.yaml +++ b/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/index.yaml @@ -1,7 +1,7 @@ openapi: "3.0.0" info: version: 1.0.0 - title: Consider OpenAPI spec examples in faker code generation https://github.com/php-openapi/yii2-openapi/issues/20 + title: Consider OpenAPI spec examples in faker code generation https://github.com/php-openapi/yii2-openapi/issues/20. And also generate faker for arrays paths: /pet: @@ -18,6 +18,12 @@ paths: components: schemas: + User: + properties: + id: + type: integer + name: + type: string Pet: required: - id @@ -73,3 +79,40 @@ components: items: type: boolean + arr_arr_int: # [ [1, 2], [3, 4], [5, 6, 7] ] + type: array + items: + type: array + items: + type: integer + + arr_arr_str: + type: array + items: + type: array + items: + type: string + + arr_arr_arr_str: + type: array + items: + type: array + items: + type: array + items: + type: string + + arr_of_obj: + type: array + items: + type: object + properties: + id: + type: integer +# +# ref_obj_arr: +# type: array +# items: +# $ref: '#/components/schemas/User' + +# oneOf From 5b87057864e7590c4a02b0b2c04d178abc03a4cc Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Thu, 8 Aug 2024 20:03:30 +0530 Subject: [PATCH 119/358] Implement for object and obj with array & nested object - WIP --- src/lib/FakerStubResolver.php | 30 ++++++++++++------- .../index.yaml | 30 ++++++++++++++++++- 2 files changed, 48 insertions(+), 12 deletions(-) diff --git a/src/lib/FakerStubResolver.php b/src/lib/FakerStubResolver.php index 1089d27f..6d7df142 100644 --- a/src/lib/FakerStubResolver.php +++ b/src/lib/FakerStubResolver.php @@ -11,6 +11,8 @@ use cebe\openapi\SpecObjectInterface; use cebe\yii2openapi\lib\items\Attribute; +use cebe\yii2openapi\lib\items\JunctionSchemas; +use cebe\yii2openapi\lib\openapi\ComponentSchema; use cebe\yii2openapi\lib\openapi\PropertySchema; use Symfony\Component\VarExporter\VarExporter; use yii\helpers\VarDumper; @@ -251,7 +253,7 @@ private function fakeForArray(SpecObjectInterface $property): string if ($items) { $type = $items->type; - if ($items->type === null) { + if ($type === null) { $arbitrary = true; } } else { @@ -295,16 +297,22 @@ private function fakeForArray(SpecObjectInterface $property): string return ' . $this->fakeForArray($items) . '; }, range(1, ' . $count . '))'; } -// -// if ($type === 'object') { -// $props = []; -// foreach ($items['properties'] ?? [] as $name => $prop) { -// $props[$name] = $this->fakeForArray($prop); -// } -// return 'array_map(function () use ($faker, $uniqueFaker) { -// return ' .VarExporter::export($props[$name]). '; -// }, range(1, '.$count.'))'; -// } + + if ($type === 'object') { + $props = []; + $cs = new ComponentSchema($items, 'somename'); + $dbModels = (new AttributeResolver('somename', $cs, new JunctionSchemas([])))->resolve(); + + foreach ($items->properties ?? [] as $name => $prop) { + $ps = new PropertySchema($prop, $name, $cs); + $attr = $dbModels->attributes[$name]; + $props[$name] = (new static($attr, $ps))->resolve(); + } + $props = str_replace(["' => '", '\',' . PHP_EOL], ["' => ", ',' . PHP_EOL], VarExporter::export($props)); + return 'array_map(function () use ($faker, $uniqueFaker) { + return ' . $props . '; + }, range(1, ' . $count . '))'; + } // TODO more complex type array/object; also consider $ref; may be recursively; may use `oneOf` diff --git a/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/index.yaml b/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/index.yaml index 83b4a75c..fa917155 100644 --- a/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/index.yaml +++ b/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/index.yaml @@ -104,13 +104,41 @@ components: arr_of_obj: type: array + minItems: 3 items: type: object properties: id: type: integer + name: + type: string + age: + type: integer + minimum: 0 + maximum: 200 + tags: + type: array + items: + type: string + uniqueItems: true + + # arr_arr_int_2: # [ [1, 2], [3, 4], [5, 6, 7] ] + # type: array + # items: + # type: array + # items: + # type: integer + + appearance: + type: object + properties: + height: + type: integer + weight: + type: integer + # -# ref_obj_arr: +# user_ref_obj_arr: # type: array # items: # $ref: '#/components/schemas/User' From 46b8d48944bfec20d489ceb8ddf3e0e233953170 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Fri, 9 Aug 2024 19:09:11 +0530 Subject: [PATCH 120/358] Implement for object and obj with nested array & nested object --- src/lib/FakerStubResolver.php | 56 ++++++++++++++----- .../index.yaml | 13 +++-- 2 files changed, 50 insertions(+), 19 deletions(-) diff --git a/src/lib/FakerStubResolver.php b/src/lib/FakerStubResolver.php index 6d7df142..9c6b2715 100644 --- a/src/lib/FakerStubResolver.php +++ b/src/lib/FakerStubResolver.php @@ -9,6 +9,8 @@ /** @noinspection PhpUndefinedFieldInspection */ namespace cebe\yii2openapi\lib; +use cebe\openapi\spec\Reference; +use cebe\openapi\spec\Schema; use cebe\openapi\SpecObjectInterface; use cebe\yii2openapi\lib\items\Attribute; use cebe\yii2openapi\lib\items\JunctionSchemas; @@ -249,6 +251,7 @@ private function fakeForArray(SpecObjectInterface $property): string $type = null; $count = 4; # let's set a number to default number of elements + /** @var Schema|Reference|null $items */ $items = $property->items; if ($items) { @@ -299,19 +302,7 @@ private function fakeForArray(SpecObjectInterface $property): string } if ($type === 'object') { - $props = []; - $cs = new ComponentSchema($items, 'somename'); - $dbModels = (new AttributeResolver('somename', $cs, new JunctionSchemas([])))->resolve(); - - foreach ($items->properties ?? [] as $name => $prop) { - $ps = new PropertySchema($prop, $name, $cs); - $attr = $dbModels->attributes[$name]; - $props[$name] = (new static($attr, $ps))->resolve(); - } - $props = str_replace(["' => '", '\',' . PHP_EOL], ["' => ", ',' . PHP_EOL], VarExporter::export($props)); - return 'array_map(function () use ($faker, $uniqueFaker) { - return ' . $props . '; - }, range(1, ' . $count . '))'; + return $this->handleObject($items, $count); } // TODO more complex type array/object; also consider $ref; may be recursively; may use `oneOf` @@ -323,4 +314,43 @@ private function fakeForArray(SpecObjectInterface $property): string // } return '[]'; } + + /** + * @param $items Schema|Reference|null + * @param $count int + * @return string + * @throws \cebe\openapi\exceptions\UnresolvableReferenceException + * @throws \yii\base\InvalidConfigException + * @throws exceptions\InvalidDefinitionException + * @internal + */ + public function handleObject($items, $count, $nested = false): string + { + $props = '[' . PHP_EOL; + $cs = new ComponentSchema($items, 'unnamed'); + $dbModels = (new AttributeResolver('unnamed', $cs, new JunctionSchemas([])))->resolve(); + + foreach ($items->properties ?? [] as $name => $prop) { + /** @var SpecObjectInterface $prop */ + + if ($prop->properties) { // object + $result = $this->handleObject($prop, $count, true); + } else { + $ps = new PropertySchema($prop, $name, $cs); + $attr = $dbModels->attributes[$name]; + $result = (string)((new static($attr, $ps))->resolve()); + } + + $props .= '\'' . $name . '\' => ' . $result . ',' . PHP_EOL; + } + $props .= ']'; + + if ($nested) { + return $props; + } + + return 'array_map(function () use ($faker, $uniqueFaker) { + return ' . $props . '; + }, range(1, ' . $count . '))'; + } } diff --git a/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/index.yaml b/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/index.yaml index fa917155..73100844 100644 --- a/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/index.yaml +++ b/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/index.yaml @@ -122,18 +122,19 @@ components: type: string uniqueItems: true - # arr_arr_int_2: # [ [1, 2], [3, 4], [5, 6, 7] ] - # type: array - # items: - # type: array - # items: - # type: integer + arr_arr_int_2: # [ [1, 2], [3, 4], [5, 6, 7] ] + type: array + items: + type: array + items: + type: integer appearance: type: object properties: height: type: integer + maximum: 20 weight: type: integer From c1bc83169ee69ae43ccebdd53d2b630f86f23ed2 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Fri, 9 Aug 2024 20:53:20 +0530 Subject: [PATCH 121/358] Implement faker generation for array of referenced component schema --- src/lib/AttributeResolver.php | 7 ++-- src/lib/FakerStubResolver.php | 40 +++++++++---------- src/lib/openapi/PropertySchema.php | 18 ++++----- .../index.yaml | 12 +++--- 4 files changed, 38 insertions(+), 39 deletions(-) diff --git a/src/lib/AttributeResolver.php b/src/lib/AttributeResolver.php index 0063d8df..b6725f4e 100644 --- a/src/lib/AttributeResolver.php +++ b/src/lib/AttributeResolver.php @@ -7,8 +7,6 @@ namespace cebe\yii2openapi\lib; -use cebe\yii2openapi\lib\Config; -use cebe\yii2openapi\lib\CustomSpecAttr; use cebe\yii2openapi\lib\exceptions\InvalidDefinitionException; use cebe\yii2openapi\lib\items\Attribute; use cebe\yii2openapi\lib\items\AttributeRelation; @@ -22,7 +20,6 @@ use Yii; use yii\helpers\Inflector; use yii\helpers\StringHelper; -use yii\helpers\VarDumper; use function explode; use function strpos; use function strtolower; @@ -342,6 +339,10 @@ protected function resolveProperty( return; } $attribute->setPhpType($relatedClassName . '[]'); + + $this->attributes[$property->getName()] = + $attribute->setFakerStub($this->guessFakerStub($attribute, $property)); // TODO + $this->relations[$property->getName()] = Yii::createObject( AttributeRelation::class, diff --git a/src/lib/FakerStubResolver.php b/src/lib/FakerStubResolver.php index 9c6b2715..5b19f712 100644 --- a/src/lib/FakerStubResolver.php +++ b/src/lib/FakerStubResolver.php @@ -80,27 +80,22 @@ public function resolve():?string } $limits = $this->attribute->limits; - switch ($this->attribute->phpType) { - case 'bool': - $result = '$faker->boolean'; - break; - case 'int': - case 'integer': - $result = $this->fakeForInt($limits['min'], $limits['max']); - break; - case 'string': - $result = $this->fakeForString(); - break; - case 'float': - case 'double': - $result = $this->fakeForFloat($limits['min'], $limits['max']); - break; - case 'array': - $result = $this->fakeForArray($this->property->getProperty()); - break; - default: - return null; + + if ($this->attribute->phpType === 'bool') { + $result = '$faker->boolean'; + } elseif (in_array($this->attribute->phpType, ['int', 'integer'])) { + $result = $this->fakeForInt($limits['min'], $limits['max']); + } elseif ($this->attribute->phpType === 'string') { + $result = $this->fakeForString(); + } elseif (in_array($this->attribute->phpType, ['float', 'double'])) { + $result = $this->fakeForFloat($limits['min'], $limits['max']); + } elseif ($this->attribute->phpType === 'array' || + substr($this->attribute->phpType, -2) === '[]') { + $result = $this->fakeForArray($this->property->getProperty()); + } else { + return null; } + if (! $this->property->hasAttr('example')) { return $result; } @@ -255,6 +250,11 @@ private function fakeForArray(SpecObjectInterface $property): string $items = $property->items; if ($items) { + if ($items instanceof Reference) { + $class = str_replace('#/components/schemas/', '', $items->getReference()); + $class .= 'Faker'; + return '(new ' . $class . ')->generateModel()->attributes'; + } $type = $items->type; if ($type === null) { $arbitrary = true; diff --git a/src/lib/openapi/PropertySchema.php b/src/lib/openapi/PropertySchema.php index 6b27def1..7d001e13 100644 --- a/src/lib/openapi/PropertySchema.php +++ b/src/lib/openapi/PropertySchema.php @@ -7,29 +7,27 @@ namespace cebe\yii2openapi\lib\openapi; -use yii\db\ColumnSchema; -use cebe\yii2openapi\generator\ApiGenerator; -use yii\db\mysql\Schema as MySqlSchema; -use SamIT\Yii2\MariaDb\Schema as MariaDbSchema; -use yii\db\pgsql\Schema as PgSqlSchema; -use cebe\yii2openapi\lib\items\Attribute; -use yii\base\NotSupportedException; use BadMethodCallException; use cebe\openapi\ReferenceContext; use cebe\openapi\spec\Reference; use cebe\openapi\SpecObjectInterface; +use cebe\yii2openapi\generator\ApiGenerator; use cebe\yii2openapi\lib\CustomSpecAttr; use cebe\yii2openapi\lib\exceptions\InvalidDefinitionException; +use cebe\yii2openapi\lib\traits\ForeignKeyConstraints; +use SamIT\Yii2\MariaDb\Schema as MariaDbSchema; use Throwable; use Yii; +use yii\base\NotSupportedException; +use yii\db\ColumnSchema; +use yii\db\mysql\Schema as MySqlSchema; +use yii\db\pgsql\Schema as PgSqlSchema; use yii\db\Schema as YiiDbSchema; use yii\helpers\Inflector; use yii\helpers\Json; use yii\helpers\StringHelper; -use yii\helpers\VarDumper; use function is_int; use function strpos; -use cebe\yii2openapi\lib\traits\ForeignKeyConstraints; class PropertySchema { @@ -410,8 +408,6 @@ public function guessPhpType():string return 'bool'; case 'number': // can be double and float return $this->getAttr('format') === 'double' ? 'double' : 'float'; -// case 'array': -// return $property->type; default: return $this->getAttr('type', 'string'); } diff --git a/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/index.yaml b/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/index.yaml index 73100844..558b9f42 100644 --- a/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/index.yaml +++ b/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/index.yaml @@ -137,11 +137,13 @@ components: maximum: 20 weight: type: integer + email: + type: string + format: email -# -# user_ref_obj_arr: -# type: array -# items: -# $ref: '#/components/schemas/User' + user_ref_obj_arr: + type: array + items: + $ref: '#/components/schemas/User' # oneOf From 2f08c41b7f16338d55a41a701684ed731e594b61 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Tue, 13 Aug 2024 16:44:57 +0530 Subject: [PATCH 122/358] Implement oneOf and refactor - WIP --- src/lib/FakerStubResolver.php | 79 ++++++++++++++++--- .../index.yaml | 14 ++++ 2 files changed, 82 insertions(+), 11 deletions(-) diff --git a/src/lib/FakerStubResolver.php b/src/lib/FakerStubResolver.php index 5b19f712..0aa9dd0c 100644 --- a/src/lib/FakerStubResolver.php +++ b/src/lib/FakerStubResolver.php @@ -238,34 +238,36 @@ private function fakeForFloat(?int $min, ?int $max):?string return '$faker->randomFloat()'; } - private function fakeForArray(SpecObjectInterface $property): string + private function fakeForArray(SpecObjectInterface $property, int $count = 4): string { // TODO consider example of OpenAPI spec $arbitrary = false; $uniqueItems = false; $type = null; - $count = 4; # let's set a number to default number of elements +// $count = 4; # let's set a number to default number of elements /** @var Schema|Reference|null $items */ - $items = $property->items; + $items = $property->items ?? $property; # later is used in `oneOf` if ($items) { if ($items instanceof Reference) { $class = str_replace('#/components/schemas/', '', $items->getReference()); $class .= 'Faker'; return '(new ' . $class . ')->generateModel()->attributes'; - } - $type = $items->type; - if ($type === null) { - $arbitrary = true; + } elseif (!empty($items->oneOf)) { + return $this->handleOneOf($items, $count); + } else { + $type = $items->type; + if ($type === null) { + $arbitrary = true; + } } } else { $arbitrary = true; } if ($property->minItems) { - $minItems = $property->minItems; - $count = $minItems; + $count = $property->minItems; } if ($property->maxItems) { @@ -297,7 +299,7 @@ private function fakeForArray(SpecObjectInterface $property): string if ($type === 'array') { # array or nested arrays return 'array_map(function () use ($faker, $uniqueFaker) { - return ' . $this->fakeForArray($items) . '; + return ' . $this->{__FUNCTION__}($items) . '; }, range(1, ' . $count . '))'; } @@ -305,6 +307,7 @@ private function fakeForArray(SpecObjectInterface $property): string return $this->handleObject($items, $count); } + // TODO more complex type array/object; also consider $ref; may be recursively; may use `oneOf` // return '$faker->words()'; // TODO implement faker for array; also consider min, max, unique @@ -334,7 +337,7 @@ public function handleObject($items, $count, $nested = false): string /** @var SpecObjectInterface $prop */ if ($prop->properties) { // object - $result = $this->handleObject($prop, $count, true); + $result = $this->{__FUNCTION__}($prop, $count, true); } else { $ps = new PropertySchema($prop, $name, $cs); $attr = $dbModels->attributes[$name]; @@ -353,4 +356,58 @@ public function handleObject($items, $count, $nested = false): string return ' . $props . '; }, range(1, ' . $count . '))'; } + + /** + * @param $items + * @param $count + * @return string + * @internal + */ + public function handleOneOf($items, $count): string + { + $fakerForADataType = []; + $result = 'array_map(function () use ($faker, $uniqueFaker) {'; + foreach ($items->oneOf as $key => $aDataType) { + /** @var Schema|Reference $aDataType */ +// $fakerForADataType[] = $this->{__FUNCTION__}($aDataType); + $a1 = $this->fakeForArray($aDataType, 1); + $result .= '$dataType' . $key . ' = ' . $a1 . ';'; + } + $ct = count($items->oneOf) - 1; + $result .= 'return ${"dataType".rand(0, ' . $ct . ')};'; +// $items = $items->oneOf[$rand]; + +// $dataType'..' +// return ""; + $result .= '}, range(1, ' . $count . '))'; + return $result; + } + + public function aString() + { + } + + public function aNumber() + { + } + + public function aInteger() + { + } + + public function aBoolean() + { + } + + public function aArray() + { + } + + public function aObject() + { + } + + public function aRefObj() + { + } } diff --git a/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/index.yaml b/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/index.yaml index 558b9f42..cce26484 100644 --- a/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/index.yaml +++ b/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/index.yaml @@ -140,10 +140,24 @@ components: email: type: string format: email + nested_obj: + type: object + properties: + id: + type: integer user_ref_obj_arr: type: array items: $ref: '#/components/schemas/User' + one_of_arr: + type: array # ["foo", 5, -2, "bar"] + maxItems: 8 + items: + oneOf: + - type: string + - type: integer + + # oneOf From 9f83e78622b829878c484cc18bb03530700bb86b Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Tue, 13 Aug 2024 19:54:26 +0530 Subject: [PATCH 123/358] Implement oneOf and refactor - WIP 2 --- src/lib/FakerStubResolver.php | 183 +++++++++--------- .../index.yaml | 1 - 2 files changed, 89 insertions(+), 95 deletions(-) diff --git a/src/lib/FakerStubResolver.php b/src/lib/FakerStubResolver.php index 0aa9dd0c..8a7a9b19 100644 --- a/src/lib/FakerStubResolver.php +++ b/src/lib/FakerStubResolver.php @@ -7,16 +7,23 @@ /** @noinspection InterfacesAsConstructorDependenciesInspection */ /** @noinspection PhpUndefinedFieldInspection */ + namespace cebe\yii2openapi\lib; +use cebe\openapi\exceptions\TypeErrorException; +use cebe\openapi\exceptions\UnresolvableReferenceException; use cebe\openapi\spec\Reference; use cebe\openapi\spec\Schema; use cebe\openapi\SpecObjectInterface; +use cebe\yii2openapi\lib\exceptions\InvalidDefinitionException; use cebe\yii2openapi\lib\items\Attribute; use cebe\yii2openapi\lib\items\JunctionSchemas; use cebe\yii2openapi\lib\openapi\ComponentSchema; use cebe\yii2openapi\lib\openapi\PropertySchema; +use Symfony\Component\VarExporter\Exception\ExceptionInterface; use Symfony\Component\VarExporter\VarExporter; +use yii\base\InvalidConfigException; +use yii\helpers\Json; use yii\helpers\VarDumper; use function str_replace; use const PHP_EOL; @@ -28,18 +35,12 @@ class FakerStubResolver { public const MAX_INT = 1000000; - /** - * @var \cebe\yii2openapi\lib\items\Attribute - */ - private $attribute; - /** - * @var \cebe\yii2openapi\lib\openapi\PropertySchema - */ - private $property; + private Attribute $attribute; - /** @var Config */ - private $config; + private PropertySchema $property; + + private ?Config $config; public function __construct(Attribute $attribute, PropertySchema $property, ?Config $config = null) { @@ -48,7 +49,14 @@ public function __construct(Attribute $attribute, PropertySchema $property, ?Con $this->config = $config; } - public function resolve():?string + /** + * @throws InvalidConfigException + * @throws TypeErrorException + * @throws UnresolvableReferenceException + * @throws InvalidDefinitionException + * @throws ExceptionInterface + */ + public function resolve(): ?string { if ($this->property->xFaker === false) { $this->attribute->setFakerStub(null); @@ -74,9 +82,9 @@ public function resolve():?string $config = new Config; } $mn = $config->modelNamespace; - return '$faker->randomElement(\\'.$mn - . ($mn ? '\\' : '') - . ucfirst($this->attribute->reference).'::find()->select("id")->column())'; + return '$faker->randomElement(\\' . $mn + . ($mn ? '\\' : '') + . ucfirst($this->attribute->reference) . '::find()->select("id")->column())'; } $limits = $this->attribute->limits; @@ -96,7 +104,7 @@ public function resolve():?string return null; } - if (! $this->property->hasAttr('example')) { + if (!$this->property->hasAttr('example')) { return $result; } if (stripos($result, 'uniqueFaker') !== false) { @@ -104,10 +112,10 @@ public function resolve():?string } $example = $this->property->getAttr('example'); $example = VarExporter::export($example); - return str_replace('$faker->', '$faker->optional(0.92, '.$example.')->', $result); + return str_replace('$faker->', '$faker->optional(0.92, ' . $example . ')->', $result); } - private function fakeForString():?string + private function fakeForString(): ?string { $formats = [ 'date' => '$faker->dateTimeThisCentury->format(\'Y-m-d\')', @@ -127,7 +135,7 @@ private function fakeForString():?string } $enum = $this->property->getAttr('enum'); if (!empty($enum) && is_array($enum)) { - $items = str_replace([PHP_EOL, ' ',',]'], ['', '', ']'], VarDumper::export($enum)); + $items = str_replace([PHP_EOL, ' ', ',]'], ['', '', ']'], VarDumper::export($enum)); return '$faker->randomElement(' . $items . ')'; } if ($this->attribute->columnName === 'title' @@ -172,7 +180,7 @@ private function fakeForString():?string '~(url|site|website|href)~i' => '$faker->url', '~(username|login)~i' => '$faker->userName', ]; - $size = $this->attribute->size > 0 ? $this->attribute->size: null; + $size = $this->attribute->size > 0 ? $this->attribute->size : null; foreach ($patterns as $pattern => $fake) { if (preg_match($pattern, $this->attribute->columnName)) { if ($size) { @@ -187,27 +195,27 @@ private function fakeForString():?string if ($size < 5) { $method = 'word'; } - return 'substr($faker->'.$method.'(' . $size . '), 0, ' . $size . ')'; + return 'substr($faker->' . $method . '(' . $size . '), 0, ' . $size . ')'; } return '$faker->sentence'; } - private function fakeForInt(?int $min, ?int $max):?string + private function fakeForInt(?int $min, ?int $max): ?string { $fakerVariable = 'faker'; if (preg_match('~_?id$~', $this->attribute->columnName)) { $fakerVariable = 'uniqueFaker'; } if ($min !== null && $max !== null) { - return "\${$fakerVariable}->numberBetween($min, $max)"; + return "\$$fakerVariable->numberBetween($min, $max)"; } if ($min !== null) { - return "\${$fakerVariable}->numberBetween($min, ".self::MAX_INT.")"; + return "\$$fakerVariable->numberBetween($min, " . self::MAX_INT . ")"; } if ($max !== null) { - return "\${$fakerVariable}->numberBetween(0, $max)"; + return "\$$fakerVariable->numberBetween(0, $max)"; } $patterns = [ @@ -221,10 +229,10 @@ private function fakeForInt(?int $min, ?int $max):?string return $fake; } } - return "\${$fakerVariable}->numberBetween(0, ".self::MAX_INT.")"; + return "\$$fakerVariable->numberBetween(0, " . self::MAX_INT . ")"; } - private function fakeForFloat(?int $min, ?int $max):?string + private function fakeForFloat(?int $min, ?int $max): ?string { if ($min !== null && $max !== null) { return "\$faker->randomFloat(null, $min, $max)"; @@ -238,22 +246,49 @@ private function fakeForFloat(?int $min, ?int $max):?string return '$faker->randomFloat()'; } + /** + * @throws InvalidConfigException + * @throws TypeErrorException + * @throws UnresolvableReferenceException + * @throws InvalidDefinitionException|ExceptionInterface + */ private function fakeForArray(SpecObjectInterface $property, int $count = 4): string { - // TODO consider example of OpenAPI spec - $arbitrary = false; $uniqueItems = false; + $arbitrary = false; $type = null; + if ($property->minItems) { + $count = $property->minItems; + } + if ($property->maxItems) { + $maxItems = $property->maxItems; + if ($maxItems < $count) { + $count = $maxItems; + } + } + if (isset($property->uniqueItems)) { + $uniqueItems = $property->uniqueItems; + } + + // TODO consider example of OpenAPI spec + // $count = 4; # let's set a number to default number of elements /** @var Schema|Reference|null $items */ $items = $property->items ?? $property; # later is used in `oneOf` + $aElementData = Json::decode(Json::encode($this->property->getProperty()->getSerializableData())); + $compoSchemaArr = [ + 'properties' => [ + 'unnamedProp' => $aElementData['items'] + ] + ]; + if ($items) { if ($items instanceof Reference) { $class = str_replace('#/components/schemas/', '', $items->getReference()); $class .= 'Faker'; - return '(new ' . $class . ')->generateModel()->attributes'; + return $this->wrapAsArray('(new ' . $class . ')->generateModel()->attributes', false, $count); } elseif (!empty($items->oneOf)) { return $this->handleOneOf($items, $count); } else { @@ -261,46 +296,24 @@ private function fakeForArray(SpecObjectInterface $property, int $count = 4): st if ($type === null) { $arbitrary = true; } + $cs = new ComponentSchema(new Schema($compoSchemaArr), 'UnnamedCompo'); + $dbModels = (new AttributeResolver('UnnamedCompo', $cs, new JunctionSchemas([])))->resolve(); + $aElementFaker = (new static($dbModels->attributes['unnamedProp'], $cs->getProperty('unnamedProp')))->resolve(); } } else { $arbitrary = true; } - if ($property->minItems) { - $count = $property->minItems; + if ($arbitrary) { + return '$faker->words()'; } - if ($property->maxItems) { - $maxItems = $property->maxItems; - if ($maxItems < $count) { - $count = $maxItems; - } - } - - if (isset($property->uniqueItems)) { - $uniqueItems = $property->uniqueItems; - } - - if ($arbitrary || $type === 'string') { - return ($uniqueItems ? '$uniqueFaker' : '$faker') . '->words(' . $count . ')'; - } - - if (in_array($type, ['number', 'integer'])) { - return 'array_map(function () use ($faker, $uniqueFaker) { - return ' . ($uniqueItems ? '$uniqueFaker' : '$faker') . '->randomNumber(); - }, range(1, ' . $count . '))'; - } - - if ($type === 'boolean') { - return 'array_map(function () use ($faker, $uniqueFaker) { - return ' . ($uniqueItems ? '$uniqueFaker' : '$faker') . '->boolean(); - }, range(1, ' . $count . '))'; + if (in_array($type, ['string', 'number', 'integer', 'boolean'])) { + return $this->wrapAsArray($aElementFaker, $uniqueItems, $count); } if ($type === 'array') { # array or nested arrays - return 'array_map(function () use ($faker, $uniqueFaker) { - return ' . $this->{__FUNCTION__}($items) . '; - }, range(1, ' . $count . '))'; + return $this->{__FUNCTION__}($items); } if ($type === 'object') { @@ -321,13 +334,16 @@ private function fakeForArray(SpecObjectInterface $property, int $count = 4): st /** * @param $items Schema|Reference|null * @param $count int + * @param bool $nested * @return string - * @throws \cebe\openapi\exceptions\UnresolvableReferenceException - * @throws \yii\base\InvalidConfigException - * @throws exceptions\InvalidDefinitionException + * @throws ExceptionInterface + * @throws InvalidConfigException + * @throws InvalidDefinitionException + * @throws TypeErrorException + * @throws UnresolvableReferenceException * @internal */ - public function handleObject($items, $count, $nested = false): string + public function handleObject(Schema $items, int $count, bool $nested = false): string { $props = '[' . PHP_EOL; $cs = new ComponentSchema($items, 'unnamed'); @@ -361,53 +377,32 @@ public function handleObject($items, $count, $nested = false): string * @param $items * @param $count * @return string + * @throws ExceptionInterface + * @throws InvalidConfigException + * @throws InvalidDefinitionException + * @throws TypeErrorException + * @throws UnresolvableReferenceException * @internal */ public function handleOneOf($items, $count): string { - $fakerForADataType = []; $result = 'array_map(function () use ($faker, $uniqueFaker) {'; foreach ($items->oneOf as $key => $aDataType) { /** @var Schema|Reference $aDataType */ -// $fakerForADataType[] = $this->{__FUNCTION__}($aDataType); + $a1 = $this->fakeForArray($aDataType, 1); $result .= '$dataType' . $key . ' = ' . $a1 . ';'; } $ct = count($items->oneOf) - 1; $result .= 'return ${"dataType".rand(0, ' . $ct . ')};'; -// $items = $items->oneOf[$rand]; - -// $dataType'..' -// return ""; $result .= '}, range(1, ' . $count . '))'; return $result; } - public function aString() - { - } - - public function aNumber() - { - } - - public function aInteger() - { - } - - public function aBoolean() - { - } - - public function aArray() - { - } - - public function aObject() - { - } - - public function aRefObj() + public function wrapAsArray($aElementFaker, $uniqueItems, $count): string { + return 'array_map(function () use ($faker, $uniqueFaker) { + return ' . ($uniqueItems ? str_replace('$faker->', '$uniqueFaker->', $aElementFaker) : $aElementFaker) . '; + }, range(1, ' . $count . '))'; } } diff --git a/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/index.yaml b/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/index.yaml index cce26484..782068b9 100644 --- a/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/index.yaml +++ b/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/index.yaml @@ -121,7 +121,6 @@ components: items: type: string uniqueItems: true - arr_arr_int_2: # [ [1, 2], [3, 4], [5, 6, 7] ] type: array items: From b3c660bf9cfe9297484c399d7cbd37fcb99f0997 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Tue, 13 Aug 2024 21:14:29 +0530 Subject: [PATCH 124/358] Implement oneOf and refactor - WIP 3 --- src/lib/FakerStubResolver.php | 75 ++++++++++--------- .../index.yaml | 2 +- 2 files changed, 40 insertions(+), 37 deletions(-) diff --git a/src/lib/FakerStubResolver.php b/src/lib/FakerStubResolver.php index 8a7a9b19..2f4cf444 100644 --- a/src/lib/FakerStubResolver.php +++ b/src/lib/FakerStubResolver.php @@ -207,15 +207,15 @@ private function fakeForInt(?int $min, ?int $max): ?string $fakerVariable = 'uniqueFaker'; } if ($min !== null && $max !== null) { - return "\$$fakerVariable->numberBetween($min, $max)"; + return "\${$fakerVariable}->numberBetween($min, $max)"; } if ($min !== null) { - return "\$$fakerVariable->numberBetween($min, " . self::MAX_INT . ")"; + return "\${$fakerVariable}->numberBetween($min, " . self::MAX_INT . ")"; } if ($max !== null) { - return "\$$fakerVariable->numberBetween(0, $max)"; + return "\${$fakerVariable}->numberBetween(0, $max)"; } $patterns = [ @@ -229,7 +229,7 @@ private function fakeForInt(?int $min, ?int $max): ?string return $fake; } } - return "\$$fakerVariable->numberBetween(0, " . self::MAX_INT . ")"; + return "\${$fakerVariable}->numberBetween(0, " . self::MAX_INT . ")"; } private function fakeForFloat(?int $min, ?int $max): ?string @@ -247,6 +247,7 @@ private function fakeForFloat(?int $min, ?int $max): ?string } /** + * @param int $count let's set a number to default number of elements * @throws InvalidConfigException * @throws TypeErrorException * @throws UnresolvableReferenceException @@ -255,8 +256,6 @@ private function fakeForFloat(?int $min, ?int $max): ?string private function fakeForArray(SpecObjectInterface $property, int $count = 4): string { $uniqueItems = false; - $arbitrary = false; - $type = null; if ($property->minItems) { $count = $property->minItems; } @@ -272,41 +271,26 @@ private function fakeForArray(SpecObjectInterface $property, int $count = 4): st // TODO consider example of OpenAPI spec -// $count = 4; # let's set a number to default number of elements - /** @var Schema|Reference|null $items */ - $items = $property->items ?? $property; # later is used in `oneOf` + $items = $property->items; # later is used only in `oneOf` - $aElementData = Json::decode(Json::encode($this->property->getProperty()->getSerializableData())); - $compoSchemaArr = [ - 'properties' => [ - 'unnamedProp' => $aElementData['items'] - ] - ]; + if (!$items) { + return $this->arbitraryArray(); + } - if ($items) { - if ($items instanceof Reference) { - $class = str_replace('#/components/schemas/', '', $items->getReference()); - $class .= 'Faker'; - return $this->wrapAsArray('(new ' . $class . ')->generateModel()->attributes', false, $count); - } elseif (!empty($items->oneOf)) { - return $this->handleOneOf($items, $count); - } else { - $type = $items->type; - if ($type === null) { - $arbitrary = true; - } - $cs = new ComponentSchema(new Schema($compoSchemaArr), 'UnnamedCompo'); - $dbModels = (new AttributeResolver('UnnamedCompo', $cs, new JunctionSchemas([])))->resolve(); - $aElementFaker = (new static($dbModels->attributes['unnamedProp'], $cs->getProperty('unnamedProp')))->resolve(); - } - } else { - $arbitrary = true; + if ($items instanceof Reference) { + $class = str_replace('#/components/schemas/', '', $items->getReference()); + $class .= 'Faker'; + return $this->wrapAsArray('(new ' . $class . ')->generateModel()->attributes', false, $count); + } elseif (!empty($items->oneOf)) { + return $this->handleOneOf($items, $count); } - if ($arbitrary) { - return '$faker->words()'; + $type = $items->type; + if ($type === null) { + return $this->arbitraryArray(); } + $aElementFaker = $this->aElementFaker(); if (in_array($type, ['string', 'number', 'integer', 'boolean'])) { return $this->wrapAsArray($aElementFaker, $uniqueItems, $count); @@ -390,7 +374,8 @@ public function handleOneOf($items, $count): string foreach ($items->oneOf as $key => $aDataType) { /** @var Schema|Reference $aDataType */ - $a1 = $this->fakeForArray($aDataType, 1); +// $a1 = $this->fakeForArray($aDataType, 1); + $a1 = $this->aElementFaker(); $result .= '$dataType' . $key . ' = ' . $a1 . ';'; } $ct = count($items->oneOf) - 1; @@ -405,4 +390,22 @@ public function wrapAsArray($aElementFaker, $uniqueItems, $count): string return ' . ($uniqueItems ? str_replace('$faker->', '$uniqueFaker->', $aElementFaker) : $aElementFaker) . '; }, range(1, ' . $count . '))'; } + + public function arbitraryArray(): string + { + return '$faker->words()'; + } + + public function aElementFaker(): ?string + { + $aElementData = Json::decode(Json::encode($this->property->getProperty()->getSerializableData())); + $compoSchemaData = [ + 'properties' => [ + 'unnamedProp' => $aElementData['items'] + ] + ]; + $cs = new ComponentSchema(new Schema($compoSchemaData), 'UnnamedCompo'); + $dbModels = (new AttributeResolver('UnnamedCompo', $cs, new JunctionSchemas([])))->resolve(); + return (new static($dbModels->attributes['unnamedProp'], $cs->getProperty('unnamedProp')))->resolve(); + } } diff --git a/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/index.yaml b/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/index.yaml index 782068b9..bfc113af 100644 --- a/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/index.yaml +++ b/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/index.yaml @@ -155,8 +155,8 @@ components: maxItems: 8 items: oneOf: - - type: string - type: integer + - type: string # oneOf From 1e7cea619e206e4c0929c302227fdfbdd07ed5a5 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Tue, 13 Aug 2024 21:24:55 +0530 Subject: [PATCH 125/358] Complex oneOf - WIP --- src/lib/FakerStubResolver.php | 12 ++++++------ .../index.yaml | 11 ++++++++++- 2 files changed, 16 insertions(+), 7 deletions(-) diff --git a/src/lib/FakerStubResolver.php b/src/lib/FakerStubResolver.php index 2f4cf444..b280927c 100644 --- a/src/lib/FakerStubResolver.php +++ b/src/lib/FakerStubResolver.php @@ -272,7 +272,7 @@ private function fakeForArray(SpecObjectInterface $property, int $count = 4): st // TODO consider example of OpenAPI spec /** @var Schema|Reference|null $items */ - $items = $property->items; # later is used only in `oneOf` + $items = $property->items; if (!$items) { return $this->arbitraryArray(); @@ -290,7 +290,7 @@ private function fakeForArray(SpecObjectInterface $property, int $count = 4): st if ($type === null) { return $this->arbitraryArray(); } - $aElementFaker = $this->aElementFaker(); + $aElementFaker = $this->aElementFaker($this->property->getProperty()->getSerializableData()); if (in_array($type, ['string', 'number', 'integer', 'boolean'])) { return $this->wrapAsArray($aElementFaker, $uniqueItems, $count); @@ -375,7 +375,7 @@ public function handleOneOf($items, $count): string /** @var Schema|Reference $aDataType */ // $a1 = $this->fakeForArray($aDataType, 1); - $a1 = $this->aElementFaker(); + $a1 = $this->aElementFaker($aDataType->getSerializableData()); $result .= '$dataType' . $key . ' = ' . $a1 . ';'; } $ct = count($items->oneOf) - 1; @@ -396,12 +396,12 @@ public function arbitraryArray(): string return '$faker->words()'; } - public function aElementFaker(): ?string + public function aElementFaker($data): ?string { - $aElementData = Json::decode(Json::encode($this->property->getProperty()->getSerializableData())); + $aElementData = Json::decode(Json::encode($data)); $compoSchemaData = [ 'properties' => [ - 'unnamedProp' => $aElementData['items'] + 'unnamedProp' => $aElementData['items'] ?? $aElementData # later is used only in `oneOf` ] ]; $cs = new ComponentSchema(new Schema($compoSchemaData), 'UnnamedCompo'); diff --git a/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/index.yaml b/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/index.yaml index bfc113af..9369ecbb 100644 --- a/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/index.yaml +++ b/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/index.yaml @@ -34,7 +34,7 @@ components: name: type: string example: cat -# example: ['long-tail', 'short-tail', 'black', 'white'] + # example: ['long-tail', 'short-tail', 'black', 'white'] age: type: integer example: 2 @@ -157,6 +157,15 @@ components: oneOf: - type: integer - type: string + - type: boolean + - type: array + - type: array + items: + type: string + - type: object + properties: + id: + type: integer # oneOf From 14b2146e556c7d585b85b61534cd55677dbd86e6 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Wed, 14 Aug 2024 20:16:30 +0530 Subject: [PATCH 126/358] Implement complex oneOf + fix error 'Creating default object from empty value in PHP' --- composer.json | 4 +- src/lib/FakerStubResolver.php | 62 ++++++++----------- .../index.yaml | 13 ++++ 3 files changed, 42 insertions(+), 37 deletions(-) diff --git a/composer.json b/composer.json index f17b6050..fecf3eca 100644 --- a/composer.json +++ b/composer.json @@ -19,14 +19,14 @@ }, "require": { "php": "^7.4 || ^8.0", - "cebe/php-openapi": "^1.5.0", "yiisoft/yii2": "~2.0.48", "yiisoft/yii2-gii": "~2.0.0 | ~2.1.0 | ~2.2.0| ~2.3.0", "laminas/laminas-code": ">=3.4 <=4.13", "php-openapi/yii2-fractal": "^1.0.0", "fakerphp/faker": "^1.9", "sam-it/yii2-mariadb": "^2.0", - "symfony/var-exporter": "^5.4" + "symfony/var-exporter": "^5.4", + "cebe/php-openapi": "^1.7" }, "require-dev": { "cebe/indent": "*", diff --git a/src/lib/FakerStubResolver.php b/src/lib/FakerStubResolver.php index b280927c..9be115af 100644 --- a/src/lib/FakerStubResolver.php +++ b/src/lib/FakerStubResolver.php @@ -12,6 +12,7 @@ use cebe\openapi\exceptions\TypeErrorException; use cebe\openapi\exceptions\UnresolvableReferenceException; +use cebe\openapi\ReferenceContext; use cebe\openapi\spec\Reference; use cebe\openapi\spec\Schema; use cebe\openapi\SpecObjectInterface; @@ -22,6 +23,7 @@ use cebe\yii2openapi\lib\openapi\PropertySchema; use Symfony\Component\VarExporter\Exception\ExceptionInterface; use Symfony\Component\VarExporter\VarExporter; +use Yii; use yii\base\InvalidConfigException; use yii\helpers\Json; use yii\helpers\VarDumper; @@ -100,6 +102,8 @@ public function resolve(): ?string } elseif ($this->attribute->phpType === 'array' || substr($this->attribute->phpType, -2) === '[]') { $result = $this->fakeForArray($this->property->getProperty()); + } elseif ($this->attribute->phpType === 'object') { + $result = $this->fakeForObject($this->property->getProperty()); } else { return null; } @@ -265,7 +269,7 @@ private function fakeForArray(SpecObjectInterface $property, int $count = 4): st $count = $maxItems; } } - if (isset($property->uniqueItems)) { + if (!empty($property->uniqueItems)) { $uniqueItems = $property->uniqueItems; } @@ -281,7 +285,7 @@ private function fakeForArray(SpecObjectInterface $property, int $count = 4): st if ($items instanceof Reference) { $class = str_replace('#/components/schemas/', '', $items->getReference()); $class .= 'Faker'; - return $this->wrapAsArray('(new ' . $class . ')->generateModel()->attributes', false, $count); + return $this->wrapInArray('(new ' . $class . ')->generateModel()->attributes', false, $count); } elseif (!empty($items->oneOf)) { return $this->handleOneOf($items, $count); } @@ -293,7 +297,7 @@ private function fakeForArray(SpecObjectInterface $property, int $count = 4): st $aElementFaker = $this->aElementFaker($this->property->getProperty()->getSerializableData()); if (in_array($type, ['string', 'number', 'integer', 'boolean'])) { - return $this->wrapAsArray($aElementFaker, $uniqueItems, $count); + return $this->wrapInArray($aElementFaker, $uniqueItems, $count); } if ($type === 'array') { # array or nested arrays @@ -301,7 +305,8 @@ private function fakeForArray(SpecObjectInterface $property, int $count = 4): st } if ($type === 'object') { - return $this->handleObject($items, $count); + $result = $this->fakeForObject($items, $count); + return $this->wrapInArray($result, $uniqueItems, $count); } @@ -316,18 +321,9 @@ private function fakeForArray(SpecObjectInterface $property, int $count = 4): st } /** - * @param $items Schema|Reference|null - * @param $count int - * @param bool $nested - * @return string - * @throws ExceptionInterface - * @throws InvalidConfigException - * @throws InvalidDefinitionException - * @throws TypeErrorException - * @throws UnresolvableReferenceException * @internal */ - public function handleObject(Schema $items, int $count, bool $nested = false): string + public function fakeForObject(SpecObjectInterface $items): string { $props = '[' . PHP_EOL; $cs = new ComponentSchema($items, 'unnamed'); @@ -337,35 +333,24 @@ public function handleObject(Schema $items, int $count, bool $nested = false): s /** @var SpecObjectInterface $prop */ if ($prop->properties) { // object - $result = $this->{__FUNCTION__}($prop, $count, true); + $result = $this->{__FUNCTION__}($prop); } else { $ps = new PropertySchema($prop, $name, $cs); $attr = $dbModels->attributes[$name]; - $result = (string)((new static($attr, $ps))->resolve()); + $result = (string)((new static($attr, $ps, $this->config))->resolve()); } $props .= '\'' . $name . '\' => ' . $result . ',' . PHP_EOL; } $props .= ']'; - if ($nested) { - return $props; - } - - return 'array_map(function () use ($faker, $uniqueFaker) { - return ' . $props . '; - }, range(1, ' . $count . '))'; + return $props; } /** * @param $items * @param $count * @return string - * @throws ExceptionInterface - * @throws InvalidConfigException - * @throws InvalidDefinitionException - * @throws TypeErrorException - * @throws UnresolvableReferenceException * @internal */ public function handleOneOf($items, $count): string @@ -374,8 +359,7 @@ public function handleOneOf($items, $count): string foreach ($items->oneOf as $key => $aDataType) { /** @var Schema|Reference $aDataType */ -// $a1 = $this->fakeForArray($aDataType, 1); - $a1 = $this->aElementFaker($aDataType->getSerializableData()); + $a1 = $this->aElementFaker(['items' => $aDataType->getSerializableData()]); $result .= '$dataType' . $key . ' = ' . $a1 . ';'; } $ct = count($items->oneOf) - 1; @@ -384,7 +368,7 @@ public function handleOneOf($items, $count): string return $result; } - public function wrapAsArray($aElementFaker, $uniqueItems, $count): string + public function wrapInArray($aElementFaker, $uniqueItems, $count): string { return 'array_map(function () use ($faker, $uniqueFaker) { return ' . ($uniqueItems ? str_replace('$faker->', '$uniqueFaker->', $aElementFaker) : $aElementFaker) . '; @@ -401,11 +385,19 @@ public function aElementFaker($data): ?string $aElementData = Json::decode(Json::encode($data)); $compoSchemaData = [ 'properties' => [ - 'unnamedProp' => $aElementData['items'] ?? $aElementData # later is used only in `oneOf` + 'unnamedProp' => $aElementData['items'] ] ]; - $cs = new ComponentSchema(new Schema($compoSchemaData), 'UnnamedCompo'); - $dbModels = (new AttributeResolver('UnnamedCompo', $cs, new JunctionSchemas([])))->resolve(); - return (new static($dbModels->attributes['unnamedProp'], $cs->getProperty('unnamedProp')))->resolve(); + + $schema = new Schema($compoSchemaData); + + if ($this->config) { + $rc = new ReferenceContext($this->config->getOpenApi(), Yii::getAlias($this->config->openApiPath)); + $schema->setReferenceContext($rc); + } + + $cs = new ComponentSchema($schema, 'UnnamedCompo'); + $dbModels = (new AttributeResolver('UnnamedCompo', $cs, new JunctionSchemas([]), $this->config))->resolve(); + return (new static($dbModels->attributes['unnamedProp'], $cs->getProperty('unnamedProp'), $this->config))->resolve(); } } diff --git a/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/index.yaml b/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/index.yaml index 9369ecbb..08a93030 100644 --- a/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/index.yaml +++ b/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/index.yaml @@ -153,6 +153,15 @@ components: one_of_arr: type: array # ["foo", 5, -2, "bar"] maxItems: 8 + items: + oneOf: + - type: integer + - type: string + - type: boolean + + one_of_arr_complex: + type: array + maxItems: 8 items: oneOf: - type: integer @@ -166,6 +175,10 @@ components: properties: id: type: integer + - type: array + items: + $ref: '#/components/schemas/User' # oneOf +# TODO count is not working in some cases \ No newline at end of file From 4e6bc039be3d1b7772393b147b40b6518d7a2760 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Wed, 14 Aug 2024 20:35:35 +0530 Subject: [PATCH 127/358] Fix failing test for x_db_type --- .../app/models/mariafaker/AlldbdatatypeFaker.php | 8 ++++---- .../app/models/mariafaker/EditcolumnFaker.php | 6 +++--- .../maria/app/models/mariafaker/NewcolumnFaker.php | 4 ++-- .../maria/app/models/mariafaker/PristineFaker.php | 2 +- .../mysql/app/models/AlldbdatatypeFaker.php | 8 ++++---- .../mysql/app/models/EditcolumnFaker.php | 6 +++--- .../mysql/app/models/NewcolumnFaker.php | 4 ++-- .../mysql/app/models/PristineFaker.php | 2 +- .../app/models/pgsqlfaker/AlldbdatatypeFaker.php | 14 +++++++------- .../app/models/pgsqlfaker/EditcolumnFaker.php | 8 ++++---- .../pgsql/app/models/pgsqlfaker/NewcolumnFaker.php | 8 ++++---- .../pgsql/app/models/pgsqlfaker/PristineFaker.php | 2 +- 12 files changed, 36 insertions(+), 36 deletions(-) diff --git a/tests/specs/x_db_type/rules_and_more/maria/app/models/mariafaker/AlldbdatatypeFaker.php b/tests/specs/x_db_type/rules_and_more/maria/app/models/mariafaker/AlldbdatatypeFaker.php index 32934ebe..8a4a3594 100644 --- a/tests/specs/x_db_type/rules_and_more/maria/app/models/mariafaker/AlldbdatatypeFaker.php +++ b/tests/specs/x_db_type/rules_and_more/maria/app/models/mariafaker/AlldbdatatypeFaker.php @@ -66,11 +66,11 @@ public function generateModel($attributes = []) $model->datetime_col = $faker->dateTimeThisYear('now', 'UTC')->format('Y-m-d H:i:s'); $model->timestamp_col = $faker->dateTimeThisYear('now', 'UTC')->format('Y-m-d H:i:s'); $model->year_col = $faker->year; - $model->json_col = []; - $model->json_col_def = []; - $model->json_col_def_2 = []; + $model->json_col = $faker->words(); + $model->json_col_def = $faker->words(); + $model->json_col_def_2 = $faker->words(); $model->text_def = $faker->sentence; - $model->json_def = []; + $model->json_def = $faker->words(); if (!is_callable($attributes)) { $model->setAttributes($attributes, false); } else { diff --git a/tests/specs/x_db_type/rules_and_more/maria/app/models/mariafaker/EditcolumnFaker.php b/tests/specs/x_db_type/rules_and_more/maria/app/models/mariafaker/EditcolumnFaker.php index efe765e5..1f183cd5 100644 --- a/tests/specs/x_db_type/rules_and_more/maria/app/models/mariafaker/EditcolumnFaker.php +++ b/tests/specs/x_db_type/rules_and_more/maria/app/models/mariafaker/EditcolumnFaker.php @@ -38,10 +38,10 @@ public function generateModel($attributes = []) $model->dec_col = $faker->randomFloat(); $model->str_col_def = substr($faker->word(3), 0, 3); $model->json_col = $faker->sentence; - $model->json_col_2 = ["a" => "b"]; + $model->json_col_2 = $faker->words(); $model->numeric_col = $faker->randomFloat(); - $model->json_col_def_n = []; - $model->json_col_def_n_2 = []; + $model->json_col_def_n = $faker->words(); + $model->json_col_def_n_2 = $faker->words(); if (!is_callable($attributes)) { $model->setAttributes($attributes, false); } else { diff --git a/tests/specs/x_db_type/rules_and_more/maria/app/models/mariafaker/NewcolumnFaker.php b/tests/specs/x_db_type/rules_and_more/maria/app/models/mariafaker/NewcolumnFaker.php index a60800cd..0532b9c1 100644 --- a/tests/specs/x_db_type/rules_and_more/maria/app/models/mariafaker/NewcolumnFaker.php +++ b/tests/specs/x_db_type/rules_and_more/maria/app/models/mariafaker/NewcolumnFaker.php @@ -34,10 +34,10 @@ public function generateModel($attributes = []) $model->name = substr($faker->text(255), 0, 255); $model->last_name = $faker->sentence; $model->dec_col = $faker->randomFloat(); - $model->json_col = []; + $model->json_col = $faker->words(); $model->varchar_col = substr($faker->text(5), 0, 5); $model->numeric_col = $faker->randomFloat(); - $model->json_col_def_n = []; + $model->json_col_def_n = $faker->words(); if (!is_callable($attributes)) { $model->setAttributes($attributes, false); } else { diff --git a/tests/specs/x_db_type/rules_and_more/maria/app/models/mariafaker/PristineFaker.php b/tests/specs/x_db_type/rules_and_more/maria/app/models/mariafaker/PristineFaker.php index 2fdf01e5..293dc2df 100644 --- a/tests/specs/x_db_type/rules_and_more/maria/app/models/mariafaker/PristineFaker.php +++ b/tests/specs/x_db_type/rules_and_more/maria/app/models/mariafaker/PristineFaker.php @@ -37,7 +37,7 @@ public function generateModel($attributes = []) $model->col_5 = $faker->randomFloat(); $model->col_6 = $faker->randomFloat(); $model->col_7 = $faker->randomFloat(); - $model->col_8 = []; + $model->col_8 = $faker->words(); $model->col_9 = substr($faker->text(9), 0, 9); $model->col_10 = substr($faker->text(10), 0, 10); $model->col_11 = $faker->sentence; diff --git a/tests/specs/x_db_type/rules_and_more/mysql/app/models/AlldbdatatypeFaker.php b/tests/specs/x_db_type/rules_and_more/mysql/app/models/AlldbdatatypeFaker.php index 9c3e308b..795f4344 100644 --- a/tests/specs/x_db_type/rules_and_more/mysql/app/models/AlldbdatatypeFaker.php +++ b/tests/specs/x_db_type/rules_and_more/mysql/app/models/AlldbdatatypeFaker.php @@ -65,11 +65,11 @@ public function generateModel($attributes = []) $model->datetime_col = $faker->dateTimeThisYear('now', 'UTC')->format('Y-m-d H:i:s'); $model->timestamp_col = $faker->dateTimeThisYear('now', 'UTC')->format('Y-m-d H:i:s'); $model->year_col = $faker->year; - $model->json_col = []; - $model->json_col_def = []; - $model->json_col_def_2 = []; + $model->json_col = $faker->words(); + $model->json_col_def = $faker->words(); + $model->json_col_def_2 = $faker->words(); $model->text_def = $faker->sentence; - $model->json_def = []; + $model->json_def = $faker->words(); if (!is_callable($attributes)) { $model->setAttributes($attributes, false); } else { diff --git a/tests/specs/x_db_type/rules_and_more/mysql/app/models/EditcolumnFaker.php b/tests/specs/x_db_type/rules_and_more/mysql/app/models/EditcolumnFaker.php index 2f60a4e7..6a14b7de 100644 --- a/tests/specs/x_db_type/rules_and_more/mysql/app/models/EditcolumnFaker.php +++ b/tests/specs/x_db_type/rules_and_more/mysql/app/models/EditcolumnFaker.php @@ -37,10 +37,10 @@ public function generateModel($attributes = []) $model->dec_col = $faker->randomFloat(); $model->str_col_def = substr($faker->word(3), 0, 3); $model->json_col = $faker->sentence; - $model->json_col_2 = ["a" => "b"]; + $model->json_col_2 = $faker->words(); $model->numeric_col = $faker->randomFloat(); - $model->json_col_def_n = []; - $model->json_col_def_n_2 = []; + $model->json_col_def_n = $faker->words(); + $model->json_col_def_n_2 = $faker->words(); if (!is_callable($attributes)) { $model->setAttributes($attributes, false); } else { diff --git a/tests/specs/x_db_type/rules_and_more/mysql/app/models/NewcolumnFaker.php b/tests/specs/x_db_type/rules_and_more/mysql/app/models/NewcolumnFaker.php index 87763eb3..fe3319dd 100644 --- a/tests/specs/x_db_type/rules_and_more/mysql/app/models/NewcolumnFaker.php +++ b/tests/specs/x_db_type/rules_and_more/mysql/app/models/NewcolumnFaker.php @@ -33,10 +33,10 @@ public function generateModel($attributes = []) $model->name = substr($faker->text(255), 0, 255); $model->last_name = $faker->sentence; $model->dec_col = $faker->randomFloat(); - $model->json_col = []; + $model->json_col = $faker->words(); $model->varchar_col = substr($faker->text(5), 0, 5); $model->numeric_col = $faker->randomFloat(); - $model->json_col_def_n = []; + $model->json_col_def_n = $faker->words(); if (!is_callable($attributes)) { $model->setAttributes($attributes, false); } else { diff --git a/tests/specs/x_db_type/rules_and_more/mysql/app/models/PristineFaker.php b/tests/specs/x_db_type/rules_and_more/mysql/app/models/PristineFaker.php index 41b186d9..ecd7b315 100644 --- a/tests/specs/x_db_type/rules_and_more/mysql/app/models/PristineFaker.php +++ b/tests/specs/x_db_type/rules_and_more/mysql/app/models/PristineFaker.php @@ -36,7 +36,7 @@ public function generateModel($attributes = []) $model->col_5 = $faker->randomFloat(); $model->col_6 = $faker->randomFloat(); $model->col_7 = $faker->randomFloat(); - $model->col_8 = []; + $model->col_8 = $faker->words(); $model->col_9 = substr($faker->text(9), 0, 9); $model->col_10 = substr($faker->text(10), 0, 10); $model->col_11 = $faker->sentence; diff --git a/tests/specs/x_db_type/rules_and_more/pgsql/app/models/pgsqlfaker/AlldbdatatypeFaker.php b/tests/specs/x_db_type/rules_and_more/pgsql/app/models/pgsqlfaker/AlldbdatatypeFaker.php index e2af0af0..70c2016c 100644 --- a/tests/specs/x_db_type/rules_and_more/pgsql/app/models/pgsqlfaker/AlldbdatatypeFaker.php +++ b/tests/specs/x_db_type/rules_and_more/pgsql/app/models/pgsqlfaker/AlldbdatatypeFaker.php @@ -34,7 +34,7 @@ public function generateModel($attributes = []) $model->string_col = $faker->sentence; $model->varchar_col = $faker->sentence; $model->text_col = $faker->sentence; - $model->text_col_array = []; + $model->text_col_array = $faker->words(); $model->varchar_4_col = substr($faker->word(4), 0, 4); $model->varchar_5_col = substr($faker->text(5), 0, 5); $model->char_4_col = substr($faker->word(4), 0, 4); @@ -90,13 +90,13 @@ public function generateModel($attributes = []) $model->character_n = substr($faker->text(12), 0, 12); $model->character_varying = $faker->sentence; $model->character_varying_n = substr($faker->text(12), 0, 12); - $model->json_col = []; - $model->jsonb_col = []; - $model->json_col_def = []; - $model->json_col_def_2 = []; + $model->json_col = $faker->words(); + $model->jsonb_col = $faker->words(); + $model->json_col_def = $faker->words(); + $model->json_col_def_2 = $faker->words(); $model->text_def = $faker->sentence; - $model->json_def = []; - $model->jsonb_def = []; + $model->json_def = $faker->words(); + $model->jsonb_def = $faker->words(); $model->cidr_col = $faker->sentence; $model->circle_col = $faker->sentence; $model->date_col_z = $faker->dateTimeThisCentury->format('Y-m-d'); diff --git a/tests/specs/x_db_type/rules_and_more/pgsql/app/models/pgsqlfaker/EditcolumnFaker.php b/tests/specs/x_db_type/rules_and_more/pgsql/app/models/pgsqlfaker/EditcolumnFaker.php index af6d1d77..e32c6d82 100644 --- a/tests/specs/x_db_type/rules_and_more/pgsql/app/models/pgsqlfaker/EditcolumnFaker.php +++ b/tests/specs/x_db_type/rules_and_more/pgsql/app/models/pgsqlfaker/EditcolumnFaker.php @@ -38,11 +38,11 @@ public function generateModel($attributes = []) $model->dec_col = $faker->randomFloat(); $model->str_col_def = $faker->sentence; $model->json_col = $faker->sentence; - $model->json_col_2 = ["a" => "b"]; + $model->json_col_2 = $faker->words(); $model->numeric_col = $faker->randomFloat(); - $model->json_col_def_n = []; - $model->json_col_def_n_2 = []; - $model->text_col_array = []; + $model->json_col_def_n = $faker->words(); + $model->json_col_def_n_2 = $faker->words(); + $model->text_col_array = $faker->words(); if (!is_callable($attributes)) { $model->setAttributes($attributes, false); } else { diff --git a/tests/specs/x_db_type/rules_and_more/pgsql/app/models/pgsqlfaker/NewcolumnFaker.php b/tests/specs/x_db_type/rules_and_more/pgsql/app/models/pgsqlfaker/NewcolumnFaker.php index 1b41dae7..64c32ef1 100644 --- a/tests/specs/x_db_type/rules_and_more/pgsql/app/models/pgsqlfaker/NewcolumnFaker.php +++ b/tests/specs/x_db_type/rules_and_more/pgsql/app/models/pgsqlfaker/NewcolumnFaker.php @@ -35,12 +35,12 @@ public function generateModel($attributes = []) $model->first_name = $faker->sentence; $model->last_name = $faker->sentence; $model->dec_col = $faker->randomFloat(); - $model->json_col = []; + $model->json_col = $faker->words(); $model->varchar_col = $faker->sentence; $model->numeric_col = $faker->randomFloat(); - $model->json_col_def_n = []; - $model->json_col_def_n_2 = []; - $model->text_col_array = []; + $model->json_col_def_n = $faker->words(); + $model->json_col_def_n_2 = $faker->words(); + $model->text_col_array = $faker->words(); if (!is_callable($attributes)) { $model->setAttributes($attributes, false); } else { diff --git a/tests/specs/x_db_type/rules_and_more/pgsql/app/models/pgsqlfaker/PristineFaker.php b/tests/specs/x_db_type/rules_and_more/pgsql/app/models/pgsqlfaker/PristineFaker.php index aac33ab7..ab484826 100644 --- a/tests/specs/x_db_type/rules_and_more/pgsql/app/models/pgsqlfaker/PristineFaker.php +++ b/tests/specs/x_db_type/rules_and_more/pgsql/app/models/pgsqlfaker/PristineFaker.php @@ -37,7 +37,7 @@ public function generateModel($attributes = []) $model->col_5 = $faker->randomFloat(); $model->col_6 = $faker->randomFloat(); $model->col_7 = $faker->randomFloat(); - $model->col_8 = []; + $model->col_8 = $faker->words(); $model->col_9 = $faker->sentence; $model->col_10 = $faker->sentence; $model->col_11 = $faker->sentence; From b2c21d1818fee3e9c4e9b9f966474c6d9c52eb92 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Wed, 14 Aug 2024 20:39:54 +0530 Subject: [PATCH 128/358] Fix bug --- src/lib/AttributeResolver.php | 6 ++---- src/lib/FakerStubResolver.php | 1 - 2 files changed, 2 insertions(+), 5 deletions(-) diff --git a/src/lib/AttributeResolver.php b/src/lib/AttributeResolver.php index b6725f4e..b069f419 100644 --- a/src/lib/AttributeResolver.php +++ b/src/lib/AttributeResolver.php @@ -259,7 +259,8 @@ protected function resolveProperty( ->setSize($fkProperty->getMaxLength()) ->setDescription($property->getRefSchema()->getDescription()) ->setDefault($fkProperty->guessDefault()) - ->setLimits($min, $max, $fkProperty->getMinLength()); + ->setLimits($min, $max, $fkProperty->getMinLength()) + ->setFakerStub($this->guessFakerStub($attribute, $property)); $relation = Yii::createObject( AttributeRelation::class, @@ -340,9 +341,6 @@ protected function resolveProperty( } $attribute->setPhpType($relatedClassName . '[]'); - $this->attributes[$property->getName()] = - $attribute->setFakerStub($this->guessFakerStub($attribute, $property)); // TODO - $this->relations[$property->getName()] = Yii::createObject( AttributeRelation::class, diff --git a/src/lib/FakerStubResolver.php b/src/lib/FakerStubResolver.php index 9be115af..6642efcc 100644 --- a/src/lib/FakerStubResolver.php +++ b/src/lib/FakerStubResolver.php @@ -390,7 +390,6 @@ public function aElementFaker($data): ?string ]; $schema = new Schema($compoSchemaData); - if ($this->config) { $rc = new ReferenceContext($this->config->getOpenApi(), Yii::getAlias($this->config->openApiPath)); $schema->setReferenceContext($rc); From 52f2320b329db8f5d2254739457c6e11ef51ec68 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Wed, 14 Aug 2024 21:05:47 +0530 Subject: [PATCH 129/358] Fix failing test --- src/lib/FakerStubResolver.php | 7 ++++++- tests/fixtures/blog.php | 6 ++++-- tests/specs/blog/models/CommentFaker.php | 6 ++++-- tests/specs/menu/models/MenuFaker.php | 4 ++-- tests/specs/postgres_custom/models/CustomFaker.php | 8 ++++---- 5 files changed, 20 insertions(+), 11 deletions(-) diff --git a/src/lib/FakerStubResolver.php b/src/lib/FakerStubResolver.php index 6642efcc..2b831453 100644 --- a/src/lib/FakerStubResolver.php +++ b/src/lib/FakerStubResolver.php @@ -325,11 +325,15 @@ private function fakeForArray(SpecObjectInterface $property, int $count = 4): st */ public function fakeForObject(SpecObjectInterface $items): string { + if (!$items->properties) { + return $this->arbitraryArray(); + } + $props = '[' . PHP_EOL; $cs = new ComponentSchema($items, 'unnamed'); $dbModels = (new AttributeResolver('unnamed', $cs, new JunctionSchemas([])))->resolve(); - foreach ($items->properties ?? [] as $name => $prop) { + foreach ($items->properties as $name => $prop) { /** @var SpecObjectInterface $prop */ if ($prop->properties) { // object @@ -342,6 +346,7 @@ public function fakeForObject(SpecObjectInterface $items): string $props .= '\'' . $name . '\' => ' . $result . ',' . PHP_EOL; } + $props .= ']'; return $props; diff --git a/tests/fixtures/blog.php b/tests/fixtures/blog.php index 74b04000..3c24df46 100644 --- a/tests/fixtures/blog.php +++ b/tests/fixtures/blog.php @@ -117,9 +117,11 @@ ->setDescription('The User') ->setFakerStub('$faker->randomElement(\app\models\User::find()->select("id")->column())'), 'message' => (new Attribute('message', ['phpType' => 'array', 'dbType' => 'json', 'xDbType' => 'json'])) - ->setRequired()->setDefault([])->setFakerStub('["a" => "b"]'), + ->setRequired()->setDefault([])->setFakerStub('$faker->words()'), 'meta_data' => (new Attribute('meta_data', ['phpType' => 'array', 'dbType' => 'json', 'xDbType' => 'json'])) - ->setDefault([])->setFakerStub('[]'), + ->setDefault([])->setFakerStub('array_map(function () use ($faker, $uniqueFaker) { + return $faker->words(); + }, range(1, 4))'), 'created_at' => (new Attribute('created_at',['phpType' => 'int', 'dbType' => 'integer'])) ->setRequired()->setFakerStub('$faker->unixTime'), ], diff --git a/tests/specs/blog/models/CommentFaker.php b/tests/specs/blog/models/CommentFaker.php index 368d541c..723562d8 100644 --- a/tests/specs/blog/models/CommentFaker.php +++ b/tests/specs/blog/models/CommentFaker.php @@ -32,8 +32,10 @@ public function generateModel($attributes = []) //$model->id = $uniqueFaker->numberBetween(0, 1000000); $model->post_id = $faker->randomElement(\app\models\Post::find()->select("id")->column()); $model->author_id = $faker->randomElement(\app\models\User::find()->select("id")->column()); - $model->message = ["a" => "b"]; - $model->meta_data = []; + $model->message = $faker->words(); + $model->meta_data = array_map(function () use ($faker, $uniqueFaker) { + return $faker->words(); + }, range(1, 4)); $model->created_at = $faker->unixTime; if (!is_callable($attributes)) { $model->setAttributes($attributes, false); diff --git a/tests/specs/menu/models/MenuFaker.php b/tests/specs/menu/models/MenuFaker.php index 64e82b3b..32b0f388 100644 --- a/tests/specs/menu/models/MenuFaker.php +++ b/tests/specs/menu/models/MenuFaker.php @@ -32,8 +32,8 @@ public function generateModel($attributes = []) //$model->id = $uniqueFaker->numberBetween(0, 1000000); $model->name = substr($faker->text(100), 0, 100); $model->parent_id = $faker->randomElement(\app\models\Menu::find()->select("id")->column()); - $model->args = []; - $model->kwargs = []; + $model->args = $faker->words(); + $model->kwargs = $faker->words(); if (!is_callable($attributes)) { $model->setAttributes($attributes, false); } else { diff --git a/tests/specs/postgres_custom/models/CustomFaker.php b/tests/specs/postgres_custom/models/CustomFaker.php index 3732716d..cc1b2cd0 100644 --- a/tests/specs/postgres_custom/models/CustomFaker.php +++ b/tests/specs/postgres_custom/models/CustomFaker.php @@ -31,10 +31,10 @@ public function generateModel($attributes = []) $model = new Custom(); //$model->id = $uniqueFaker->numberBetween(0, 1000000); $model->num = $faker->numberBetween(0, 1000000); - $model->json1 = []; - $model->json2 = []; - $model->json3 = []; - $model->json4 = []; + $model->json1 = $faker->words(); + $model->json2 = $faker->words(); + $model->json3 = $faker->words(); + $model->json4 = $faker->words(); $model->status = $faker->randomElement(['active','draft']); $model->status_x = $faker->randomElement(['active','draft']); if (!is_callable($attributes)) { From b03726521bcced70d09d42632a0a5ed626773e4d Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Thu, 15 Aug 2024 16:24:14 +0530 Subject: [PATCH 130/358] Fix failing test --- tests/fixtures/non-db.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/fixtures/non-db.php b/tests/fixtures/non-db.php index 220a486d..04714844 100644 --- a/tests/fixtures/non-db.php +++ b/tests/fixtures/non-db.php @@ -21,7 +21,7 @@ 'catsCount' => (new Attribute('catsCount', ['phpType' => 'int', 'dbType' => 'integer'])), 'summary' => (new Attribute('summary', ['phpType' => 'string', 'dbType' => 'text'])), 'parentPet' => (new Attribute('parentPet', ['phpType' => 'int', 'dbType' => 'bigint'])) - ->asReference('Pet')->setDescription('A Pet'), + ->asReference('Pet')->setDescription('A Pet')->setFakerStub('$faker->randomElement(\app\models\Pet::find()->select("id")->column())'), ], 'relations' => [ 'parentPet' => new AttributeRelation('parentPet', 'pets', 'Pet', 'hasOne', ['id' => 'parentPet_id']), From 091007395cd5dffce14971a4e7ae901b27c32efb Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Thu, 15 Aug 2024 17:36:59 +0530 Subject: [PATCH 131/358] Fix errors --- src/lib/AttributeResolver.php | 3 ++- src/lib/FakerStubResolver.php | 18 ++++++++++++++---- .../index.yaml | 4 +--- 3 files changed, 17 insertions(+), 8 deletions(-) diff --git a/src/lib/AttributeResolver.php b/src/lib/AttributeResolver.php index b069f419..1d7f54a7 100644 --- a/src/lib/AttributeResolver.php +++ b/src/lib/AttributeResolver.php @@ -225,7 +225,8 @@ protected function resolveProperty( ->setXDbDefaultExpression($property->getAttr(CustomSpecAttr::DB_DEFAULT_EXPRESSION)) ->setNullable($nullableValue) ->setIsPrimary($property->isPrimaryKey()) - ->setForeignKeyColumnName($property->fkColName); + ->setForeignKeyColumnName($property->fkColName) + ->setFakerStub($this->guessFakerStub($attribute, $property)); if ($property->isReference()) { if ($property->isVirtual()) { throw new InvalidDefinitionException('References not supported for virtual attributes'); diff --git a/src/lib/FakerStubResolver.php b/src/lib/FakerStubResolver.php index 2b831453..9cf1b6b4 100644 --- a/src/lib/FakerStubResolver.php +++ b/src/lib/FakerStubResolver.php @@ -336,7 +336,7 @@ public function fakeForObject(SpecObjectInterface $items): string foreach ($items->properties as $name => $prop) { /** @var SpecObjectInterface $prop */ - if ($prop->properties) { // object + if ($prop->properties) { // nested object $result = $this->{__FUNCTION__}($prop); } else { $ps = new PropertySchema($prop, $name, $cs); @@ -387,7 +387,7 @@ public function arbitraryArray(): string public function aElementFaker($data): ?string { - $aElementData = Json::decode(Json::encode($data)); + $aElementData = Json::decode(Json::encode($data)); // object of stdClass -> array $compoSchemaData = [ 'properties' => [ 'unnamedProp' => $aElementData['items'] @@ -395,13 +395,23 @@ public function aElementFaker($data): ?string ]; $schema = new Schema($compoSchemaData); + $cs = new ComponentSchema($schema, 'UnnamedCompo'); if ($this->config) { $rc = new ReferenceContext($this->config->getOpenApi(), Yii::getAlias($this->config->openApiPath)); $schema->setReferenceContext($rc); } - - $cs = new ComponentSchema($schema, 'UnnamedCompo'); $dbModels = (new AttributeResolver('UnnamedCompo', $cs, new JunctionSchemas([]), $this->config))->resolve(); + + foreach ($schema->properties as $name => $prop) { + if($prop->items instanceof Reference) { + $dbModels->attributes[$name] = new Attribute($name, [ + 'phpType' => 'array', + 'dbType' => 'array', + 'reference' => $prop->items->getReference(), + ]); + } + } + return (new static($dbModels->attributes['unnamedProp'], $cs->getProperty('unnamedProp'), $this->config))->resolve(); } } diff --git a/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/index.yaml b/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/index.yaml index 08a93030..85794ee0 100644 --- a/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/index.yaml +++ b/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/index.yaml @@ -34,7 +34,6 @@ components: name: type: string example: cat - # example: ['long-tail', 'short-tail', 'black', 'white'] age: type: integer example: 2 @@ -48,8 +47,7 @@ components: minItems: 6 maxItems: 10 uniqueItems: true - # type: string - # example: ['long-tail', 'short-tail', 'black', 'white'] + # example: ['long-tail', 'short-tail', 'black', 'white'] number_arr: type: array items: From f0c5cd3808da8b6aafbe3637f3153464df3163e1 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Thu, 15 Aug 2024 21:09:09 +0530 Subject: [PATCH 132/358] Fix errors 2 + implement custom attribute `x-no-relation` --- src/lib/AttributeResolver.php | 6 ++++++ src/lib/FakerStubResolver.php | 21 +++++++++++-------- tests/specs/blog_v2.yaml | 1 + .../index.php | 2 +- .../index.yaml | 11 +++++++++- 5 files changed, 30 insertions(+), 11 deletions(-) diff --git a/src/lib/AttributeResolver.php b/src/lib/AttributeResolver.php index 1d7f54a7..2a620d51 100644 --- a/src/lib/AttributeResolver.php +++ b/src/lib/AttributeResolver.php @@ -217,7 +217,13 @@ protected function resolveProperty( $nullableValue = $property->getProperty()->getSerializableData()->nullable ?? null; } $attribute = Yii::createObject(Attribute::class, [$property->getName()]); + + if (!empty($property->getAttr('x-no-relation'))) { // TODO custom attr + $this->attributes[$property->getName()] = $attribute->setFakerStub($this->guessFakerStub($attribute, $property)); + } + $attribute->setRequired($isRequired) + ->setPhpType($property->guessPhpType()) ->setDescription($property->getAttr('description', '')) ->setReadOnly($property->isReadonly()) ->setDefault($property->guessDefault()) diff --git a/src/lib/FakerStubResolver.php b/src/lib/FakerStubResolver.php index 9cf1b6b4..c069042e 100644 --- a/src/lib/FakerStubResolver.php +++ b/src/lib/FakerStubResolver.php @@ -393,6 +393,9 @@ public function aElementFaker($data): ?string 'unnamedProp' => $aElementData['items'] ] ]; + if (!empty($compoSchemaData['properties']['unnamedProp']['items']['$ref'])) { // TODO + $compoSchemaData['properties']['unnamedProp']['x-no-relation'] = true; + } $schema = new Schema($compoSchemaData); $cs = new ComponentSchema($schema, 'UnnamedCompo'); @@ -402,15 +405,15 @@ public function aElementFaker($data): ?string } $dbModels = (new AttributeResolver('UnnamedCompo', $cs, new JunctionSchemas([]), $this->config))->resolve(); - foreach ($schema->properties as $name => $prop) { - if($prop->items instanceof Reference) { - $dbModels->attributes[$name] = new Attribute($name, [ - 'phpType' => 'array', - 'dbType' => 'array', - 'reference' => $prop->items->getReference(), - ]); - } - } +// foreach ($schema->properties as $name => $prop) { +// if($prop->items instanceof Reference) { +// $dbModels->attributes[$name] = new Attribute($name, [ +// 'phpType' => 'array', +// 'dbType' => 'array', +// 'reference' => $prop->items->getReference(), +// ]); +// } +// } return (new static($dbModels->attributes['unnamedProp'], $cs->getProperty('unnamedProp'), $this->config))->resolve(); } diff --git a/tests/specs/blog_v2.yaml b/tests/specs/blog_v2.yaml index 68d09367..e4ab5a48 100644 --- a/tests/specs/blog_v2.yaml +++ b/tests/specs/blog_v2.yaml @@ -349,6 +349,7 @@ components: $ref: "#/components/schemas/User" comments: type: array + # x-no-relation: true items: $ref: "#/components/schemas/Comment" tags: diff --git a/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/index.php b/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/index.php index 6afa241e..14397d3e 100644 --- a/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/index.php +++ b/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/index.php @@ -8,6 +8,6 @@ // 'Error', // ], 'generateControllers' => false, - 'generateMigrations' => false, + 'generateMigrations' => true, 'generateModelFaker' => true, // `generateModels` must be `true` in order to use `generateModelFaker` as `true` ]; diff --git a/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/index.yaml b/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/index.yaml index 85794ee0..1879c3dd 100644 --- a/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/index.yaml +++ b/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/index.yaml @@ -143,8 +143,17 @@ components: id: type: integer - user_ref_obj_arr: + user_ref_obj_arr_normal: # faker for this won't be generated type: array + maxItems: 3 + # x-no-relation: true + items: + $ref: '#/components/schemas/User' + + user_ref_obj_arr: # special + type: array + maxItems: 3 + x-no-relation: true items: $ref: '#/components/schemas/User' From de75ca7007c546abe865244c5a85abaf5511a527 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Fri, 16 Aug 2024 10:12:38 +0530 Subject: [PATCH 133/358] Fix failing test in PHP >= 8.1 --- src/lib/FakerStubResolver.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/lib/FakerStubResolver.php b/src/lib/FakerStubResolver.php index c069042e..394673a2 100644 --- a/src/lib/FakerStubResolver.php +++ b/src/lib/FakerStubResolver.php @@ -86,7 +86,7 @@ public function resolve(): ?string $mn = $config->modelNamespace; return '$faker->randomElement(\\' . $mn . ($mn ? '\\' : '') - . ucfirst($this->attribute->reference) . '::find()->select("id")->column())'; + . ucfirst((string) $this->attribute->reference) . '::find()->select("id")->column())'; } $limits = $this->attribute->limits; From 6ab30cc264e8fe0c1240ed3587f171a399f5bc42 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Fri, 16 Aug 2024 11:18:59 +0530 Subject: [PATCH 134/358] Fix count issue for nested array --- src/lib/AttributeResolver.php | 1 - src/lib/FakerStubResolver.php | 48 ++++++++++--------- .../index.yaml | 3 ++ 3 files changed, 29 insertions(+), 23 deletions(-) diff --git a/src/lib/AttributeResolver.php b/src/lib/AttributeResolver.php index 2a620d51..d1fe4678 100644 --- a/src/lib/AttributeResolver.php +++ b/src/lib/AttributeResolver.php @@ -347,7 +347,6 @@ protected function resolveProperty( return; } $attribute->setPhpType($relatedClassName . '[]'); - $this->relations[$property->getName()] = Yii::createObject( AttributeRelation::class, diff --git a/src/lib/FakerStubResolver.php b/src/lib/FakerStubResolver.php index 394673a2..08298e52 100644 --- a/src/lib/FakerStubResolver.php +++ b/src/lib/FakerStubResolver.php @@ -10,6 +10,7 @@ namespace cebe\yii2openapi\lib; +use cebe\openapi\exceptions\IOException; use cebe\openapi\exceptions\TypeErrorException; use cebe\openapi\exceptions\UnresolvableReferenceException; use cebe\openapi\ReferenceContext; @@ -256,6 +257,7 @@ private function fakeForFloat(?int $min, ?int $max): ?string * @throws TypeErrorException * @throws UnresolvableReferenceException * @throws InvalidDefinitionException|ExceptionInterface + * @throws IOException */ private function fakeForArray(SpecObjectInterface $property, int $count = 4): string { @@ -294,22 +296,17 @@ private function fakeForArray(SpecObjectInterface $property, int $count = 4): st if ($type === null) { return $this->arbitraryArray(); } - $aElementFaker = $this->aElementFaker($this->property->getProperty()->getSerializableData()); + $aFaker = $this->aElementFaker($this->property->getProperty()->getSerializableData()); - if (in_array($type, ['string', 'number', 'integer', 'boolean'])) { - return $this->wrapInArray($aElementFaker, $uniqueItems, $count); - } - - if ($type === 'array') { # array or nested arrays - return $this->{__FUNCTION__}($items); + if (in_array($type, ['string', 'number', 'integer', 'boolean', 'array'])) { + return $this->wrapInArray($aFaker, $uniqueItems, $count); } if ($type === 'object') { - $result = $this->fakeForObject($items, $count); + $result = $this->fakeForObject($items); return $this->wrapInArray($result, $uniqueItems, $count); } - // TODO more complex type array/object; also consider $ref; may be recursively; may use `oneOf` // return '$faker->words()'; // TODO implement faker for array; also consider min, max, unique @@ -373,10 +370,10 @@ public function handleOneOf($items, $count): string return $result; } - public function wrapInArray($aElementFaker, $uniqueItems, $count): string + public function wrapInArray($aFaker, $uniqueItems, $count): string { return 'array_map(function () use ($faker, $uniqueFaker) { - return ' . ($uniqueItems ? str_replace('$faker->', '$uniqueFaker->', $aElementFaker) : $aElementFaker) . '; + return ' . ($uniqueItems ? str_replace('$faker->', '$uniqueFaker->', $aFaker) : $aFaker) . '; }, range(1, ' . $count . '))'; } @@ -385,6 +382,19 @@ public function arbitraryArray(): string return '$faker->words()'; } + /** + * This method is only for `fakeForArray()` or methods only used inside `fakeForArray()`. If needed to use outside `fakeForArray()` context then some changes might be required. + * Also see OpenAPI extension `x-no-relation` in README.md + * @param $data + * @return string|null + * @throws ExceptionInterface + * @throws InvalidConfigException + * @throws InvalidDefinitionException + * @throws TypeErrorException + * @throws UnresolvableReferenceException + * @throws IOException + * @internal + */ public function aElementFaker($data): ?string { $aElementData = Json::decode(Json::encode($data)); // object of stdClass -> array @@ -393,7 +403,11 @@ public function aElementFaker($data): ?string 'unnamedProp' => $aElementData['items'] ] ]; - if (!empty($compoSchemaData['properties']['unnamedProp']['items']['$ref'])) { // TODO + + // This condition is only for properties with type = array + // If you intend to use this method from out of `fakeForArray()` context then below condition should be changed depending on your use case + // Also see OpenAPI extension `x-no-relation` in README.md + if (!empty($compoSchemaData['properties']['unnamedProp']['items']['$ref'])) { $compoSchemaData['properties']['unnamedProp']['x-no-relation'] = true; } @@ -405,16 +419,6 @@ public function aElementFaker($data): ?string } $dbModels = (new AttributeResolver('UnnamedCompo', $cs, new JunctionSchemas([]), $this->config))->resolve(); -// foreach ($schema->properties as $name => $prop) { -// if($prop->items instanceof Reference) { -// $dbModels->attributes[$name] = new Attribute($name, [ -// 'phpType' => 'array', -// 'dbType' => 'array', -// 'reference' => $prop->items->getReference(), -// ]); -// } -// } - return (new static($dbModels->attributes['unnamedProp'], $cs->getProperty('unnamedProp'), $this->config))->resolve(); } } diff --git a/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/index.yaml b/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/index.yaml index 1879c3dd..6fb95e77 100644 --- a/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/index.yaml +++ b/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/index.yaml @@ -93,10 +93,13 @@ components: arr_arr_arr_str: type: array + minItems: 3 items: type: array + minItems: 4 items: type: array + minItems: 5 items: type: string From 960cc43095d69c4960bf05a7fcd35940d3a54357 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Fri, 16 Aug 2024 16:35:04 +0530 Subject: [PATCH 135/358] Add typehint to fn args --- src/lib/CustomSpecAttr.php | 5 +++++ src/lib/FakerStubResolver.php | 8 ++++---- .../index.yaml | 4 ++-- tests/unit/IssueFixTest.php | 6 ++++++ 4 files changed, 17 insertions(+), 6 deletions(-) diff --git a/src/lib/CustomSpecAttr.php b/src/lib/CustomSpecAttr.php index 7e02a85d..ba37d272 100644 --- a/src/lib/CustomSpecAttr.php +++ b/src/lib/CustomSpecAttr.php @@ -40,4 +40,9 @@ class CustomSpecAttr * Foreign key column name. See README for usage docs */ public const FK_COLUMN_NAME = 'x-fk-column-name'; + + /** + * Foreign key column name. See README for usage docs + */ +// public const FK_COLUMN_NAME = 'x-fk-column-name'; } diff --git a/src/lib/FakerStubResolver.php b/src/lib/FakerStubResolver.php index 08298e52..3a769438 100644 --- a/src/lib/FakerStubResolver.php +++ b/src/lib/FakerStubResolver.php @@ -355,7 +355,7 @@ public function fakeForObject(SpecObjectInterface $items): string * @return string * @internal */ - public function handleOneOf($items, $count): string + public function handleOneOf(SpecObjectInterface $items, int $count): string { $result = 'array_map(function () use ($faker, $uniqueFaker) {'; foreach ($items->oneOf as $key => $aDataType) { @@ -370,7 +370,7 @@ public function handleOneOf($items, $count): string return $result; } - public function wrapInArray($aFaker, $uniqueItems, $count): string + public function wrapInArray(string $aFaker, bool $uniqueItems, int $count): string { return 'array_map(function () use ($faker, $uniqueFaker) { return ' . ($uniqueItems ? str_replace('$faker->', '$uniqueFaker->', $aFaker) : $aFaker) . '; @@ -385,7 +385,7 @@ public function arbitraryArray(): string /** * This method is only for `fakeForArray()` or methods only used inside `fakeForArray()`. If needed to use outside `fakeForArray()` context then some changes might be required. * Also see OpenAPI extension `x-no-relation` in README.md - * @param $data + * @param $data object|array * @return string|null * @throws ExceptionInterface * @throws InvalidConfigException @@ -397,7 +397,7 @@ public function arbitraryArray(): string */ public function aElementFaker($data): ?string { - $aElementData = Json::decode(Json::encode($data)); // object of stdClass -> array + $aElementData = Json::decode(Json::encode($data)); // element object of stdClass -> array $compoSchemaData = [ 'properties' => [ 'unnamedProp' => $aElementData['items'] diff --git a/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/index.yaml b/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/index.yaml index 6fb95e77..e6d820de 100644 --- a/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/index.yaml +++ b/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/index.yaml @@ -126,9 +126,9 @@ components: type: array items: type: array + minItems: 11 items: type: integer - appearance: type: object properties: @@ -171,7 +171,7 @@ components: one_of_arr_complex: type: array - maxItems: 8 + minItems: 8 items: oneOf: - type: integer diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index 197a9eca..022ba78b 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -364,6 +364,12 @@ public function test158BugGiiapiGeneratedRulesEnumWithTrim() // https://github.com/php-openapi/yii2-openapi/issues/20 public function test20ConsiderOpenApiSpecExamplesInFakeCodeGeneration() { +// $faker = \Faker\Factory::create(); +// $uniqueFaker = $faker->unique(); +// +// var_dump(); +// return; + $testFile = Yii::getAlias("@specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/index.php"); $this->runGenerator($testFile); // $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ From 4f6d72879b9563ea7ecd4fa925efa6c5c60f7a45 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Fri, 16 Aug 2024 20:31:51 +0530 Subject: [PATCH 136/358] Fix issues + add support for all refs only in oneOf --- README.md | 2 + src/lib/FakerStubResolver.php | 40 +++++++++++++------ .../index.yaml | 19 ++++++++- 3 files changed, 46 insertions(+), 15 deletions(-) diff --git a/README.md b/README.md index 1cd2090b..fccf1037 100644 --- a/README.md +++ b/README.md @@ -309,6 +309,8 @@ Provide custom database table column name in case of relationship column. This w - x-fk-column-name: redelivery_of # this will create `redelivery_of` column instead of `redelivery_of_id` ``` +### `x-no-relation` + ## Many-to-Many relation definition There are two ways for define many-to-many relations: diff --git a/src/lib/FakerStubResolver.php b/src/lib/FakerStubResolver.php index 3a769438..9902cf2f 100644 --- a/src/lib/FakerStubResolver.php +++ b/src/lib/FakerStubResolver.php @@ -87,7 +87,7 @@ public function resolve(): ?string $mn = $config->modelNamespace; return '$faker->randomElement(\\' . $mn . ($mn ? '\\' : '') - . ucfirst((string) $this->attribute->reference) . '::find()->select("id")->column())'; + . ucfirst((string)$this->attribute->reference) . '::find()->select("id")->column())'; // TODO PK "id" can be also something else } $limits = $this->attribute->limits; @@ -285,10 +285,10 @@ private function fakeForArray(SpecObjectInterface $property, int $count = 4): st } if ($items instanceof Reference) { - $class = str_replace('#/components/schemas/', '', $items->getReference()); - $class .= 'Faker'; - return $this->wrapInArray('(new ' . $class . ')->generateModel()->attributes', false, $count); - } elseif (!empty($items->oneOf)) { + $aFakerForRef = $this->aElementFaker($items); + return $this->wrapInArray($aFakerForRef, $uniqueItems, $count); + } + if (!empty($items->oneOf)) { return $this->handleOneOf($items, $count); } @@ -296,8 +296,7 @@ private function fakeForArray(SpecObjectInterface $property, int $count = 4): st if ($type === null) { return $this->arbitraryArray(); } - $aFaker = $this->aElementFaker($this->property->getProperty()->getSerializableData()); - + $aFaker = $this->aElementFaker($this->property->getProperty()); if (in_array($type, ['string', 'number', 'integer', 'boolean', 'array'])) { return $this->wrapInArray($aFaker, $uniqueItems, $count); } @@ -350,9 +349,16 @@ public function fakeForObject(SpecObjectInterface $items): string } /** - * @param $items - * @param $count + * This method must be only used incase of array + * @param SpecObjectInterface $items + * @param int $count * @return string + * @throws ExceptionInterface + * @throws IOException + * @throws InvalidConfigException + * @throws InvalidDefinitionException + * @throws TypeErrorException + * @throws UnresolvableReferenceException * @internal */ public function handleOneOf(SpecObjectInterface $items, int $count): string @@ -361,8 +367,9 @@ public function handleOneOf(SpecObjectInterface $items, int $count): string foreach ($items->oneOf as $key => $aDataType) { /** @var Schema|Reference $aDataType */ - $a1 = $this->aElementFaker(['items' => $aDataType->getSerializableData()]); - $result .= '$dataType' . $key . ' = ' . $a1 . ';'; + $inp = $aDataType instanceof Reference ? $aDataType : ['items' => $aDataType->getSerializableData()]; + $aFaker = $this->aElementFaker($inp); + $result .= '$dataType' . $key . ' = ' . $aFaker . ';'; } $ct = count($items->oneOf) - 1; $result .= 'return ${"dataType".rand(0, ' . $ct . ')};'; @@ -385,7 +392,7 @@ public function arbitraryArray(): string /** * This method is only for `fakeForArray()` or methods only used inside `fakeForArray()`. If needed to use outside `fakeForArray()` context then some changes might be required. * Also see OpenAPI extension `x-no-relation` in README.md - * @param $data object|array + * @param $data array|\stdClass|SpecObjectInterface * @return string|null * @throws ExceptionInterface * @throws InvalidConfigException @@ -397,7 +404,14 @@ public function arbitraryArray(): string */ public function aElementFaker($data): ?string { - $aElementData = Json::decode(Json::encode($data)); // element object of stdClass -> array + if ($data instanceof Reference) { + $class = str_replace('#/components/schemas/', '', $data->getReference()); + $class .= 'Faker'; + return '(new ' . $class . ')->generateModel()->attributes'; + } + + $inp = $data instanceof SpecObjectInterface ? $data->getSerializableData() : $data; + $aElementData = Json::decode(Json::encode($inp)); $compoSchemaData = [ 'properties' => [ 'unnamedProp' => $aElementData['items'] diff --git a/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/index.yaml b/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/index.yaml index e6d820de..4b91def0 100644 --- a/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/index.yaml +++ b/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/index.yaml @@ -24,6 +24,12 @@ components: type: integer name: type: string + Fruit: + properties: + id: + type: integer + name: + type: string Pet: required: - id @@ -188,7 +194,16 @@ components: - type: array items: $ref: '#/components/schemas/User' + - $ref: '#/components/schemas/Fruit' + + one_of_from_multi_ref_arr: + type: array + x-no-relation: true + items: + oneOf: + - $ref: '#/components/schemas/User' + - $ref: '#/components/schemas/Fruit' + -# oneOf -# TODO count is not working in some cases \ No newline at end of file +# TODO count is not working in some cases From 65625f00e6a50b71f18621954995518b7ae4f8d6 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Sat, 17 Aug 2024 17:01:03 +0530 Subject: [PATCH 137/358] Refactor --- src/lib/FakerStubResolver.php | 48 +++++++++++++++++------------------ 1 file changed, 24 insertions(+), 24 deletions(-) diff --git a/src/lib/FakerStubResolver.php b/src/lib/FakerStubResolver.php index 9902cf2f..c6b7ebc5 100644 --- a/src/lib/FakerStubResolver.php +++ b/src/lib/FakerStubResolver.php @@ -22,6 +22,7 @@ use cebe\yii2openapi\lib\items\JunctionSchemas; use cebe\yii2openapi\lib\openapi\ComponentSchema; use cebe\yii2openapi\lib\openapi\PropertySchema; +use stdClass; use Symfony\Component\VarExporter\Exception\ExceptionInterface; use Symfony\Component\VarExporter\VarExporter; use Yii; @@ -58,6 +59,7 @@ public function __construct(Attribute $attribute, PropertySchema $property, ?Con * @throws UnresolvableReferenceException * @throws InvalidDefinitionException * @throws ExceptionInterface + * @throws IOException */ public function resolve(): ?string { @@ -285,18 +287,18 @@ private function fakeForArray(SpecObjectInterface $property, int $count = 4): st } if ($items instanceof Reference) { - $aFakerForRef = $this->aElementFaker($items); + $aFakerForRef = $this->aElementFaker($items, $this->attribute->columnName); return $this->wrapInArray($aFakerForRef, $uniqueItems, $count); } if (!empty($items->oneOf)) { - return $this->handleOneOf($items, $count); + return $this->wrapInArray($this->handleOneOf($items, $count), $uniqueItems, $count, true); } $type = $items->type; if ($type === null) { return $this->arbitraryArray(); } - $aFaker = $this->aElementFaker($this->property->getProperty()); + $aFaker = $this->aElementFaker($this->property->getProperty(), $this->attribute->columnName); if (in_array($type, ['string', 'number', 'integer', 'boolean', 'array'])) { return $this->wrapInArray($aFaker, $uniqueItems, $count); } @@ -326,8 +328,6 @@ public function fakeForObject(SpecObjectInterface $items): string } $props = '[' . PHP_EOL; - $cs = new ComponentSchema($items, 'unnamed'); - $dbModels = (new AttributeResolver('unnamed', $cs, new JunctionSchemas([])))->resolve(); foreach ($items->properties as $name => $prop) { /** @var SpecObjectInterface $prop */ @@ -335,11 +335,8 @@ public function fakeForObject(SpecObjectInterface $items): string if ($prop->properties) { // nested object $result = $this->{__FUNCTION__}($prop); } else { - $ps = new PropertySchema($prop, $name, $cs); - $attr = $dbModels->attributes[$name]; - $result = (string)((new static($attr, $ps, $this->config))->resolve()); + $result = $this->aElementFaker(['items' => $prop->getSerializableData()], $name); } - $props .= '\'' . $name . '\' => ' . $result . ',' . PHP_EOL; } @@ -363,24 +360,24 @@ public function fakeForObject(SpecObjectInterface $items): string */ public function handleOneOf(SpecObjectInterface $items, int $count): string { - $result = 'array_map(function () use ($faker, $uniqueFaker) {'; + $result = ''; foreach ($items->oneOf as $key => $aDataType) { /** @var Schema|Reference $aDataType */ $inp = $aDataType instanceof Reference ? $aDataType : ['items' => $aDataType->getSerializableData()]; - $aFaker = $this->aElementFaker($inp); + $aFaker = $this->aElementFaker($inp, $this->attribute->columnName); $result .= '$dataType' . $key . ' = ' . $aFaker . ';'; } $ct = count($items->oneOf) - 1; - $result .= 'return ${"dataType".rand(0, ' . $ct . ')};'; - $result .= '}, range(1, ' . $count . '))'; + $result .= 'return ${"dataType".rand(0, ' . $ct . ')}'; return $result; } - public function wrapInArray(string $aFaker, bool $uniqueItems, int $count): string + public function wrapInArray(string $aFaker, bool $uniqueItems, int $count, bool $oneOf = false): string { + $ret = $oneOf ? '' : 'return '; return 'array_map(function () use ($faker, $uniqueFaker) { - return ' . ($uniqueItems ? str_replace('$faker->', '$uniqueFaker->', $aFaker) : $aFaker) . '; + ' . $ret . ($uniqueItems ? str_replace('$faker->', '$uniqueFaker->', $aFaker) : $aFaker) . '; }, range(1, ' . $count . '))'; } @@ -392,17 +389,18 @@ public function arbitraryArray(): string /** * This method is only for `fakeForArray()` or methods only used inside `fakeForArray()`. If needed to use outside `fakeForArray()` context then some changes might be required. * Also see OpenAPI extension `x-no-relation` in README.md - * @param $data array|\stdClass|SpecObjectInterface + * @param $data array|stdClass|SpecObjectInterface + * @param string|null $columnName * @return string|null * @throws ExceptionInterface + * @throws IOException * @throws InvalidConfigException * @throws InvalidDefinitionException * @throws TypeErrorException * @throws UnresolvableReferenceException - * @throws IOException * @internal */ - public function aElementFaker($data): ?string + public function aElementFaker($data, ?string $columnName = null): ?string { if ($data instanceof Reference) { $class = str_replace('#/components/schemas/', '', $data->getReference()); @@ -412,27 +410,29 @@ public function aElementFaker($data): ?string $inp = $data instanceof SpecObjectInterface ? $data->getSerializableData() : $data; $aElementData = Json::decode(Json::encode($inp)); + $columnName = $columnName ?? 'unnamedProp'; $compoSchemaData = [ 'properties' => [ - 'unnamedProp' => $aElementData['items'] + $columnName => $aElementData['items'] ] ]; // This condition is only for properties with type = array // If you intend to use this method from out of `fakeForArray()` context then below condition should be changed depending on your use case // Also see OpenAPI extension `x-no-relation` in README.md - if (!empty($compoSchemaData['properties']['unnamedProp']['items']['$ref'])) { - $compoSchemaData['properties']['unnamedProp']['x-no-relation'] = true; + if (!empty($compoSchemaData['properties'][$columnName]['items']['$ref'])) { + $compoSchemaData['properties'][$columnName]['x-no-relation'] = true; } $schema = new Schema($compoSchemaData); - $cs = new ComponentSchema($schema, 'UnnamedCompo'); + $compo = 'UnnamedCompo'; + $cs = new ComponentSchema($schema, $compo); if ($this->config) { $rc = new ReferenceContext($this->config->getOpenApi(), Yii::getAlias($this->config->openApiPath)); $schema->setReferenceContext($rc); } - $dbModels = (new AttributeResolver('UnnamedCompo', $cs, new JunctionSchemas([]), $this->config))->resolve(); + $dbModels = (new AttributeResolver($compo, $cs, new JunctionSchemas([]), $this->config))->resolve(); - return (new static($dbModels->attributes['unnamedProp'], $cs->getProperty('unnamedProp'), $this->config))->resolve(); + return (new static($dbModels->attributes[$columnName], $cs->getProperty($columnName), $this->config))->resolve(); } } From 77f6ff2c6cdc5a7a16f2757e22194749327032a4 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Sat, 17 Aug 2024 17:27:04 +0530 Subject: [PATCH 138/358] Fix bug --- src/lib/FakerStubResolver.php | 2 +- .../index.yaml | 16 +++++++++------- 2 files changed, 10 insertions(+), 8 deletions(-) diff --git a/src/lib/FakerStubResolver.php b/src/lib/FakerStubResolver.php index c6b7ebc5..8e253bfc 100644 --- a/src/lib/FakerStubResolver.php +++ b/src/lib/FakerStubResolver.php @@ -332,7 +332,7 @@ public function fakeForObject(SpecObjectInterface $items): string foreach ($items->properties as $name => $prop) { /** @var SpecObjectInterface $prop */ - if ($prop->properties) { // nested object + if (!empty($prop->properties)) { // nested object $result = $this->{__FUNCTION__}($prop); } else { $result = $this->aElementFaker(['items' => $prop->getSerializableData()], $name); diff --git a/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/index.yaml b/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/index.yaml index 4b91def0..1078b726 100644 --- a/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/index.yaml +++ b/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/index.yaml @@ -123,6 +123,13 @@ components: type: integer minimum: 0 maximum: 200 + user: + $ref: '#/components/schemas/User' + user_2: + type: array + # x-no-relation: true # it is not required since we only implemented handling of such object for arrays only + items: + $ref: '#/components/schemas/User' tags: type: array items: @@ -155,14 +162,13 @@ components: user_ref_obj_arr_normal: # faker for this won't be generated type: array maxItems: 3 - # x-no-relation: true items: $ref: '#/components/schemas/User' user_ref_obj_arr: # special type: array maxItems: 3 - x-no-relation: true + x-no-relation: true # it is required because this property is not part of any array items: $ref: '#/components/schemas/User' @@ -198,12 +204,8 @@ components: one_of_from_multi_ref_arr: type: array - x-no-relation: true + # x-no-relation: true # it is not required since we only implemented handling of oneOf for arrays only items: oneOf: - $ref: '#/components/schemas/User' - $ref: '#/components/schemas/Fruit' - - - -# TODO count is not working in some cases From ee6f7ec0ecb38ca309f8b8ba407eb3664d68f539 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Sat, 17 Aug 2024 17:51:47 +0530 Subject: [PATCH 139/358] Add docs for `x-no-relation` and create its constant --- README.md | 65 ++++++++++++++++++++++++++++++++--- src/lib/AttributeResolver.php | 2 +- src/lib/CustomSpecAttr.php | 2 +- src/lib/FakerStubResolver.php | 2 +- 4 files changed, 63 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index fccf1037..c0b0fe07 100644 --- a/README.md +++ b/README.md @@ -76,7 +76,9 @@ return $config; To use the web generator, open `index.php?r=gii` and select the `REST API Generator`. -On console you can run the generator with `./yii gii/api --openApiPath=@app/openapi.yaml`. Where `@app/openapi.yaml` should be the absolute path to your OpenAPI spec file. This can be JSON as well as YAML (see also [php-openapi/php-openapi](https://github.com/php-openapi/php-openapi/) for supported formats). +On console, you can run the generator with `./yii gii/api --openApiPath=@app/openapi.yaml`. Where `@app/openapi.yaml` +should be the absolute path to your OpenAPI spec file. This can be JSON as well as YAML (see +also [php-openapi/php-openapi](https://github.com/php-openapi/php-openapi/) for supported formats). Run `./yii gii/api --help` for all options. Example: Disable generation of migrations files `./yii gii/api --generateMigrations=0` @@ -311,6 +313,58 @@ Provide custom database table column name in case of relationship column. This w ### `x-no-relation` +To differentiate a component schema property from one-to-many or many-to-many relation in favour of array(json) of +related objects, `x-no-relation` is used. + +```yaml + comments: + type: array + items: + $ref: "#/components/schemas/Comment" +``` + +This will not generate 'comments' column in database migrations. But it will generate `getComments()` relation in model. + +In order to make it real database column, extension `x-no-relation` can be used. + +```yaml + comments: + type: array + x-no-relation: true + items: + $ref: "#/components/schemas/Comment" +``` + +Database column type can be `array`, `json` etc. to store such data. + +Now if the Comment schema from the above example is + +```yaml + Comment: + properties: + id: + type: integer + content: + type: string +``` + +then the value can be + +```json +[ + { + "id": 1, + "content": "Hi there" + }, + { + "id": 2, + "content": "Hi there 2" + } +] +``` + +At this moment, `x-no-relation` can be only used with OpenAPI schema data type `array`. + ## Many-to-Many relation definition There are two ways for define many-to-many relations: @@ -318,8 +372,8 @@ There are two ways for define many-to-many relations: ### Simple many-to-many without junction model - property name for many-to-many relation should be equal lower-cased, pluralized related schema name - - - referenced schema should contains mirrored reference to current schema + +- referenced schema should contain mirrored reference to current schema - migration for junction table can be generated automatically - table name should be [pluralized, lower-cased schema_name1]2[pluralized, lower-cased schema name2], in alphabetical order; @@ -510,12 +564,13 @@ created_at: ## Assumptions When generating code from an OpenAPI description there are many possible ways to achive a fitting result. -Thus there are some assumptions and limitations that are currently applied to make this work. +Thus, there are some assumptions and limitations that are currently applied to make this work. Here is a (possibly incomplete) list: - The current implementation works best with OpenAPI description that follows the [JSON:API](https://jsonapi.org/) guidelines. - The request and response format/schema is currently not extracted from OpenAPI schema and may need to be adjusted manually if it does not follow JSON:API -- column/field/property with name `id` is considered as Primary Key by this library and it is automatically handled by DB/Yii; so remove it from validation `rules()` +- column/field/property with name `id` is considered as Primary Key by this library, and it is automatically handled by + DB/Yii; so remove it from validation `rules()` - other fields can currently be used as primary keys using the `x-pk` OpenAPI extension (see below) but it may not be work correctly in all cases, please report bugs if you find them. Other things to keep in mind: diff --git a/src/lib/AttributeResolver.php b/src/lib/AttributeResolver.php index d1fe4678..f21ceb1c 100644 --- a/src/lib/AttributeResolver.php +++ b/src/lib/AttributeResolver.php @@ -218,7 +218,7 @@ protected function resolveProperty( } $attribute = Yii::createObject(Attribute::class, [$property->getName()]); - if (!empty($property->getAttr('x-no-relation'))) { // TODO custom attr + if (!empty($property->getAttr(CustomSpecAttr::NO_RELATION))) { // TODO custom attr $this->attributes[$property->getName()] = $attribute->setFakerStub($this->guessFakerStub($attribute, $property)); } diff --git a/src/lib/CustomSpecAttr.php b/src/lib/CustomSpecAttr.php index ba37d272..53640914 100644 --- a/src/lib/CustomSpecAttr.php +++ b/src/lib/CustomSpecAttr.php @@ -44,5 +44,5 @@ class CustomSpecAttr /** * Foreign key column name. See README for usage docs */ -// public const FK_COLUMN_NAME = 'x-fk-column-name'; + public const NO_RELATION = 'x-no-relation'; } diff --git a/src/lib/FakerStubResolver.php b/src/lib/FakerStubResolver.php index 8e253bfc..f0303904 100644 --- a/src/lib/FakerStubResolver.php +++ b/src/lib/FakerStubResolver.php @@ -421,7 +421,7 @@ public function aElementFaker($data, ?string $columnName = null): ?string // If you intend to use this method from out of `fakeForArray()` context then below condition should be changed depending on your use case // Also see OpenAPI extension `x-no-relation` in README.md if (!empty($compoSchemaData['properties'][$columnName]['items']['$ref'])) { - $compoSchemaData['properties'][$columnName]['x-no-relation'] = true; + $compoSchemaData['properties'][$columnName][CustomSpecAttr::NO_RELATION] = true; } $schema = new Schema($compoSchemaData); From 6cfadcfb7d14e04cdfd22d2809559eaf17211465 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Sat, 17 Aug 2024 20:18:53 +0530 Subject: [PATCH 140/358] Handle example --- README.md | 2 +- src/lib/AttributeResolver.php | 2 +- src/lib/FakerStubResolver.php | 23 ++++++++----------- src/lib/items/Attribute.php | 22 ++++++++---------- .../index.yaml | 9 ++++++-- 5 files changed, 28 insertions(+), 30 deletions(-) diff --git a/README.md b/README.md index c0b0fe07..a71b5ec6 100644 --- a/README.md +++ b/README.md @@ -314,7 +314,7 @@ Provide custom database table column name in case of relationship column. This w ### `x-no-relation` To differentiate a component schema property from one-to-many or many-to-many relation in favour of array(json) of -related objects, `x-no-relation` is used. +related objects, `x-no-relation` (type: boolean, default: false) is used. ```yaml comments: diff --git a/src/lib/AttributeResolver.php b/src/lib/AttributeResolver.php index f21ceb1c..73d6a308 100644 --- a/src/lib/AttributeResolver.php +++ b/src/lib/AttributeResolver.php @@ -218,7 +218,7 @@ protected function resolveProperty( } $attribute = Yii::createObject(Attribute::class, [$property->getName()]); - if (!empty($property->getAttr(CustomSpecAttr::NO_RELATION))) { // TODO custom attr + if (!empty($property->getAttr(CustomSpecAttr::NO_RELATION))) { $this->attributes[$property->getName()] = $attribute->setFakerStub($this->guessFakerStub($attribute, $property)); } diff --git a/src/lib/FakerStubResolver.php b/src/lib/FakerStubResolver.php index f0303904..80eb7ec0 100644 --- a/src/lib/FakerStubResolver.php +++ b/src/lib/FakerStubResolver.php @@ -105,18 +105,21 @@ public function resolve(): ?string } elseif ($this->attribute->phpType === 'array' || substr($this->attribute->phpType, -2) === '[]') { $result = $this->fakeForArray($this->property->getProperty()); + if ($result !== '$faker->words()') { # example for array will only work with a list/`$faker->words()` + return $result; + } } elseif ($this->attribute->phpType === 'object') { $result = $this->fakeForObject($this->property->getProperty()); } else { return null; } - if (!$this->property->hasAttr('example')) { - return $result; - } - if (stripos($result, 'uniqueFaker') !== false) { + if (!$this->property->hasAttr('example') || + $this->property->getAttr('uniqueItems') + ) { return $result; } + $example = $this->property->getAttr('example'); $example = VarExporter::export($example); return str_replace('$faker->', '$faker->optional(0.92, ' . $example . ')->', $result); @@ -277,8 +280,6 @@ private function fakeForArray(SpecObjectInterface $property, int $count = 4): st $uniqueItems = $property->uniqueItems; } - // TODO consider example of OpenAPI spec - /** @var Schema|Reference|null $items */ $items = $property->items; @@ -308,13 +309,6 @@ private function fakeForArray(SpecObjectInterface $property, int $count = 4): st return $this->wrapInArray($result, $uniqueItems, $count); } - // TODO more complex type array/object; also consider $ref; may be recursively; may use `oneOf` - -// return '$faker->words()'; // TODO implement faker for array; also consider min, max, unique - -// if ($this->attribute->required) { -// return '["a" => "b"]'; // TODO this is incorrect, array schema should be checked first -// } return '[]'; } @@ -383,7 +377,8 @@ public function wrapInArray(string $aFaker, bool $uniqueItems, int $count, bool public function arbitraryArray(): string { - return '$faker->words()'; + $theFaker = $this->property->getAttr('uniqueItems') ? '$uniqueFaker' : '$faker'; + return $theFaker . '->words()'; } /** diff --git a/src/lib/items/Attribute.php b/src/lib/items/Attribute.php index 5563162d..95320836 100644 --- a/src/lib/items/Attribute.php +++ b/src/lib/items/Attribute.php @@ -7,19 +7,13 @@ namespace cebe\yii2openapi\lib\items; -use yii\helpers\VarDumper; -use \Yii; -use cebe\yii2openapi\lib\openapi\PropertySchema; -use cebe\yii2openapi\generator\ApiGenerator; +use cebe\yii2openapi\db\ColumnSchema; use cebe\yii2openapi\lib\exceptions\InvalidDefinitionException; +use cebe\yii2openapi\lib\openapi\PropertySchema; use yii\base\BaseObject; -use cebe\yii2openapi\db\ColumnSchema; -use yii\helpers\Inflector; -use yii\helpers\StringHelper; -use yii\db\mysql\Schema as MySqlSchema; -use SamIT\Yii2\MariaDb\Schema as MariaDbSchema; -use yii\db\pgsql\Schema as PgSqlSchema; +use yii\base\InvalidConfigException; use yii\base\NotSupportedException; +use yii\helpers\Inflector; use function is_array; use function strtolower; @@ -302,7 +296,7 @@ public function getFormattedDescription():string return $type.' $'.str_replace("\n", "\n * ", rtrim($comment)); } - public function toColumnSchema():ColumnSchema + public function toColumnSchema(): ColumnSchema { $column = new ColumnSchema([ 'name' => $this->columnName, @@ -333,7 +327,11 @@ public function toColumnSchema():ColumnSchema } /** - * @throws \yii\base\InvalidConfigException + * @param string $dbType + * @return string + * @throws InvalidDefinitionException + * @throws NotSupportedException + * @throws InvalidConfigException */ private function yiiAbstractTypeForDbSpecificType(string $dbType): string { diff --git a/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/index.yaml b/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/index.yaml index 1078b726..97638e4b 100644 --- a/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/index.yaml +++ b/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/index.yaml @@ -52,8 +52,8 @@ components: items: { } # array of arbitrary types e.g. [ "hello", -2, true, [5.7], {"id": 5} ] minItems: 6 maxItems: 10 - uniqueItems: true - # example: ['long-tail', 'short-tail', 'black', 'white'] + # uniqueItems: true + example: [ 'long-tail', 'short-tail', 'black', 'white' ] number_arr: type: array items: @@ -68,6 +68,8 @@ components: int_arr: type: array + # uniqueItems: true + example: [ 4, 5 ] items: type: integer @@ -158,6 +160,9 @@ components: properties: id: type: integer + title: + type: string + maxLength: 4 user_ref_obj_arr_normal: # faker for this won't be generated type: array From b3023c4af96ccc2893bec0c0aa53bed63d4f1d5c Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Sat, 17 Aug 2024 20:23:11 +0530 Subject: [PATCH 141/358] Add test spec file --- .../m200000_000000_create_table_fruits.php | 20 +++ .../m200000_000001_create_table_pets.php | 36 +++++ .../m200000_000002_create_table_users.php | 20 +++ .../mysql/models/BaseModelFaker.php | 144 ++++++++++++++++++ .../mysql/models/Fruit.php | 10 ++ .../mysql/models/FruitFaker.php | 41 +++++ .../mysql/models/Pet.php | 10 ++ .../mysql/models/PetFaker.php | 129 ++++++++++++++++ .../mysql/models/User.php | 10 ++ .../mysql/models/UserFaker.php | 41 +++++ .../mysql/models/base/Fruit.php | 26 ++++ .../mysql/models/base/Pet.php | 57 +++++++ .../mysql/models/base/User.php | 26 ++++ tests/unit/IssueFixTest.php | 20 +-- 14 files changed, 577 insertions(+), 13 deletions(-) create mode 100644 tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/mysql/migrations_mysql_db/m200000_000000_create_table_fruits.php create mode 100644 tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/mysql/migrations_mysql_db/m200000_000001_create_table_pets.php create mode 100644 tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/mysql/migrations_mysql_db/m200000_000002_create_table_users.php create mode 100644 tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/mysql/models/BaseModelFaker.php create mode 100644 tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/mysql/models/Fruit.php create mode 100644 tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/mysql/models/FruitFaker.php create mode 100644 tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/mysql/models/Pet.php create mode 100644 tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/mysql/models/PetFaker.php create mode 100644 tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/mysql/models/User.php create mode 100644 tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/mysql/models/UserFaker.php create mode 100644 tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/mysql/models/base/Fruit.php create mode 100644 tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/mysql/models/base/Pet.php create mode 100644 tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/mysql/models/base/User.php diff --git a/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/mysql/migrations_mysql_db/m200000_000000_create_table_fruits.php b/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/mysql/migrations_mysql_db/m200000_000000_create_table_fruits.php new file mode 100644 index 00000000..18bf5d9f --- /dev/null +++ b/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/mysql/migrations_mysql_db/m200000_000000_create_table_fruits.php @@ -0,0 +1,20 @@ +createTable('{{%fruits}}', [ + 'id' => $this->primaryKey(), + 'name' => $this->text()->null(), + ]); + } + + public function down() + { + $this->dropTable('{{%fruits}}'); + } +} diff --git a/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/mysql/migrations_mysql_db/m200000_000001_create_table_pets.php b/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/mysql/migrations_mysql_db/m200000_000001_create_table_pets.php new file mode 100644 index 00000000..01df98f3 --- /dev/null +++ b/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/mysql/migrations_mysql_db/m200000_000001_create_table_pets.php @@ -0,0 +1,36 @@ +createTable('{{%pets}}', [ + 'id' => $this->primaryKey(), + 'name' => $this->text()->notNull(), + 'age' => $this->integer()->null()->defaultValue(null), + 'tags' => $this->text()->null(), + 'tags_arbit' => $this->text()->null(), + 'number_arr' => $this->text()->null(), + 'number_arr_min_uniq' => $this->text()->null(), + 'int_arr' => $this->text()->null(), + 'int_arr_min_uniq' => $this->text()->null(), + 'bool_arr' => $this->text()->null(), + 'arr_arr_int' => $this->text()->null(), + 'arr_arr_str' => $this->text()->null(), + 'arr_arr_arr_str' => $this->text()->null(), + 'arr_of_obj' => $this->text()->null(), + 'user_ref_obj_arr' => $this->string()->null()->defaultValue(null), + 'one_of_arr' => $this->text()->null(), + 'one_of_arr_complex' => $this->text()->null(), + 'one_of_from_multi_ref_arr' => $this->text()->null(), + ]); + } + + public function down() + { + $this->dropTable('{{%pets}}'); + } +} diff --git a/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/mysql/migrations_mysql_db/m200000_000002_create_table_users.php b/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/mysql/migrations_mysql_db/m200000_000002_create_table_users.php new file mode 100644 index 00000000..0aa915a3 --- /dev/null +++ b/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/mysql/migrations_mysql_db/m200000_000002_create_table_users.php @@ -0,0 +1,20 @@ +createTable('{{%users}}', [ + 'id' => $this->primaryKey(), + 'name' => $this->text()->null(), + ]); + } + + public function down() + { + $this->dropTable('{{%users}}'); + } +} diff --git a/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/mysql/models/BaseModelFaker.php b/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/mysql/models/BaseModelFaker.php new file mode 100644 index 00000000..c367fbb4 --- /dev/null +++ b/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/mysql/models/BaseModelFaker.php @@ -0,0 +1,144 @@ +faker = FakerFactory::create(str_replace('-', '_', \Yii::$app->language)); + $this->uniqueFaker = new UniqueGenerator($this->faker); + } + + abstract public function generateModel($attributes = []); + + public function getFaker():Generator + { + return $this->faker; + } + + public function getUniqueFaker():UniqueGenerator + { + return $this->uniqueFaker; + } + + public function setFaker(Generator $faker):void + { + $this->faker = $faker; + } + + public function setUniqueFaker(UniqueGenerator $faker):void + { + $this->uniqueFaker = $faker; + } + + /** + * Generate and return model + * @param array|callable $attributes + * @param UniqueGenerator|null $uniqueFaker + * @return \yii\db\ActiveRecord + * @example MyFaker::makeOne(['user_id' => 1, 'title' => 'foo']); + * @example MyFaker::makeOne( function($model, $faker) { + * $model->scenario = 'create'; + * $model->setAttributes(['user_id' => 1, 'title' => $faker->sentence]); + * return $model; + * }); + */ + public static function makeOne($attributes = [], ?UniqueGenerator $uniqueFaker = null) + { + $fakeBuilder = new static(); + if ($uniqueFaker !== null) { + $fakeBuilder->setUniqueFaker($uniqueFaker); + } + $model = $fakeBuilder->generateModel($attributes); + return $model; + } + + /** + * Generate, save and return model + * @param array|callable $attributes + * @param UniqueGenerator|null $uniqueFaker + * @return \yii\db\ActiveRecord + * @example MyFaker::saveOne(['user_id' => 1, 'title' => 'foo']); + * @example MyFaker::saveOne( function($model, $faker) { + * $model->scenario = 'create'; + * $model->setAttributes(['user_id' => 1, 'title' => $faker->sentence]); + * return $model; + * }); + */ + public static function saveOne($attributes = [], ?UniqueGenerator $uniqueFaker = null) + { + $model = static::makeOne($attributes, $uniqueFaker); + $model->save(); + return $model; + } + + /** + * Generate and return multiple models + * @param int $number + * @param array|callable $commonAttributes + * @return \yii\db\ActiveRecord[]|array + * @example TaskFaker::make(5, ['project_id'=>1, 'user_id' => 2]); + * @example TaskFaker::make(5, function($model, $faker, $uniqueFaker) { + * $model->setAttributes(['name' => $uniqueFaker->username, 'state'=>$faker->boolean(20)]); + * return $model; + * }); + */ + public static function make(int $number, $commonAttributes = [], ?UniqueGenerator $uniqueFaker = null):array + { + if ($number < 1) { + return []; + } + $fakeBuilder = new static(); + if ($uniqueFaker !== null) { + $fakeBuilder->setUniqueFaker($uniqueFaker); + } + return array_map(function () use ($commonAttributes, $fakeBuilder) { + $model = $fakeBuilder->generateModel($commonAttributes); + return $model; + }, range(0, $number -1)); + } + + /** + * Generate, save and return multiple models + * @param int $number + * @param array|callable $commonAttributes + * @return \yii\db\ActiveRecord[]|array + * @example TaskFaker::save(5, ['project_id'=>1, 'user_id' => 2]); + * @example TaskFaker::save(5, function($model, $faker, $uniqueFaker) { + * $model->setAttributes(['name' => $uniqueFaker->username, 'state'=>$faker->boolean(20)]); + * return $model; + * }); + */ + public static function save(int $number, $commonAttributes = [], ?UniqueGenerator $uniqueFaker = null):array + { + if ($number < 1) { + return []; + } + $fakeBuilder = new static(); + if ($uniqueFaker !== null) { + $fakeBuilder->setUniqueFaker($uniqueFaker); + } + return array_map(function () use ($commonAttributes, $fakeBuilder) { + $model = $fakeBuilder->generateModel($commonAttributes); + $model->save(); + return $model; + }, range(0, $number -1)); + } +} diff --git a/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/mysql/models/Fruit.php b/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/mysql/models/Fruit.php new file mode 100644 index 00000000..c74c53d9 --- /dev/null +++ b/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/mysql/models/Fruit.php @@ -0,0 +1,10 @@ +generateModels(['author_id' => 1]); + * $model = (new PostFaker())->generateModels(function($model, $faker, $uniqueFaker) { + * $model->scenario = 'create'; + * $model->author_id = 1; + * return $model; + * }); + **/ + public function generateModel($attributes = []) + { + $faker = $this->faker; + $uniqueFaker = $this->uniqueFaker; + $model = new Fruit(); + //$model->id = $uniqueFaker->numberBetween(0, 1000000); + $model->name = $faker->sentence; + if (!is_callable($attributes)) { + $model->setAttributes($attributes, false); + } else { + $model = $attributes($model, $faker, $uniqueFaker); + } + return $model; + } +} diff --git a/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/mysql/models/Pet.php b/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/mysql/models/Pet.php new file mode 100644 index 00000000..1b9df07c --- /dev/null +++ b/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/mysql/models/Pet.php @@ -0,0 +1,10 @@ +generateModels(['author_id' => 1]); + * $model = (new PostFaker())->generateModels(function($model, $faker, $uniqueFaker) { + * $model->scenario = 'create'; + * $model->author_id = 1; + * return $model; + * }); + **/ + public function generateModel($attributes = []) + { + $faker = $this->faker; + $uniqueFaker = $this->uniqueFaker; + $model = new Pet(); + //$model->id = $uniqueFaker->numberBetween(0, 1000000); + $model->name = $faker->optional(0.92, 'cat')->sentence; + $model->age = $faker->optional(0.92, 2)->numberBetween(0, 1000000); + $model->tags = array_map(function () use ($faker, $uniqueFaker) { + return $faker->sentence; + }, range(1, 4)); + $model->tags_arbit = $faker->optional(0.92, [ + 'long-tail', + 'short-tail', + 'black', + 'white', +])->words(); + $model->number_arr = array_map(function () use ($faker, $uniqueFaker) { + return $faker->randomFloat(); + }, range(1, 4)); + $model->number_arr_min_uniq = array_map(function () use ($faker, $uniqueFaker) { + return $uniqueFaker->randomFloat(); + }, range(1, 6)); + $model->int_arr = array_map(function () use ($faker, $uniqueFaker) { + return $faker->numberBetween(0, 1000000); + }, range(1, 4)); + $model->int_arr_min_uniq = array_map(function () use ($faker, $uniqueFaker) { + return $uniqueFaker->numberBetween(0, 1000000); + }, range(1, 7)); + $model->bool_arr = array_map(function () use ($faker, $uniqueFaker) { + return $faker->boolean; + }, range(1, 4)); + $model->arr_arr_int = array_map(function () use ($faker, $uniqueFaker) { + return array_map(function () use ($faker, $uniqueFaker) { + return $faker->numberBetween(0, 1000000); + }, range(1, 4)); + }, range(1, 4)); + $model->arr_arr_str = array_map(function () use ($faker, $uniqueFaker) { + return array_map(function () use ($faker, $uniqueFaker) { + return $faker->sentence; + }, range(1, 4)); + }, range(1, 4)); + $model->arr_arr_arr_str = array_map(function () use ($faker, $uniqueFaker) { + return array_map(function () use ($faker, $uniqueFaker) { + return array_map(function () use ($faker, $uniqueFaker) { + return $faker->sentence; + }, range(1, 5)); + }, range(1, 4)); + }, range(1, 3)); + $model->arr_of_obj = array_map(function () use ($faker, $uniqueFaker) { + return [ +'id' => $uniqueFaker->numberBetween(0, 1000000), +'name' => $faker->sentence, +'age' => $faker->numberBetween(0, 200), +'user' => $faker->randomElement(\app\models\User::find()->select("id")->column()), +'user_2' => array_map(function () use ($faker, $uniqueFaker) { + return (new UserFaker)->generateModel()->attributes; + }, range(1, 4)), +'tags' => array_map(function () use ($faker, $uniqueFaker) { + return $uniqueFaker->sentence; + }, range(1, 4)), +'arr_arr_int_2' => array_map(function () use ($faker, $uniqueFaker) { + return array_map(function () use ($faker, $uniqueFaker) { + return $faker->numberBetween(0, 1000000); + }, range(1, 11)); + }, range(1, 4)), +'appearance' => [ +'height' => $faker->numberBetween(0, 20), +'weight' => $faker->numberBetween(0, 1000000), +'email' => $faker->safeEmail, +'nested_obj' => [ +'id' => $uniqueFaker->numberBetween(0, 1000000), +'title' => $faker->title, +], +], +]; + }, range(1, 3)); + $model->user_ref_obj_arr = array_map(function () use ($faker, $uniqueFaker) { + return (new UserFaker)->generateModel()->attributes; + }, range(1, 3)); + $model->one_of_arr = array_map(function () use ($faker, $uniqueFaker) { + $dataType0 = $faker->numberBetween(0, 1000000);$dataType1 = $faker->sentence;$dataType2 = $faker->boolean;return ${"dataType".rand(0, 2)}; + }, range(1, 4)); + $model->one_of_arr_complex = array_map(function () use ($faker, $uniqueFaker) { + $dataType0 = $faker->numberBetween(0, 1000000);$dataType1 = $faker->sentence;$dataType2 = $faker->boolean;$dataType3 = $faker->words();$dataType4 = array_map(function () use ($faker, $uniqueFaker) { + return $faker->sentence; + }, range(1, 4));$dataType5 = [ +'id' => $uniqueFaker->numberBetween(0, 1000000), +];$dataType6 = array_map(function () use ($faker, $uniqueFaker) { + return (new UserFaker)->generateModel()->attributes; + }, range(1, 4));$dataType7 = (new FruitFaker)->generateModel()->attributes;return ${"dataType".rand(0, 7)}; + }, range(1, 8)); + $model->one_of_from_multi_ref_arr = array_map(function () use ($faker, $uniqueFaker) { + $dataType0 = (new UserFaker)->generateModel()->attributes;$dataType1 = (new FruitFaker)->generateModel()->attributes;return ${"dataType".rand(0, 1)}; + }, range(1, 4)); + if (!is_callable($attributes)) { + $model->setAttributes($attributes, false); + } else { + $model = $attributes($model, $faker, $uniqueFaker); + } + return $model; + } +} diff --git a/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/mysql/models/User.php b/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/mysql/models/User.php new file mode 100644 index 00000000..9b837d6e --- /dev/null +++ b/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/mysql/models/User.php @@ -0,0 +1,10 @@ +generateModels(['author_id' => 1]); + * $model = (new PostFaker())->generateModels(function($model, $faker, $uniqueFaker) { + * $model->scenario = 'create'; + * $model->author_id = 1; + * return $model; + * }); + **/ + public function generateModel($attributes = []) + { + $faker = $this->faker; + $uniqueFaker = $this->uniqueFaker; + $model = new User(); + //$model->id = $uniqueFaker->numberBetween(0, 1000000); + $model->name = $faker->sentence; + if (!is_callable($attributes)) { + $model->setAttributes($attributes, false); + } else { + $model = $attributes($model, $faker, $uniqueFaker); + } + return $model; + } +} diff --git a/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/mysql/models/base/Fruit.php b/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/mysql/models/base/Fruit.php new file mode 100644 index 00000000..2106e69d --- /dev/null +++ b/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/mysql/models/base/Fruit.php @@ -0,0 +1,26 @@ + [['name'], 'trim'], + 'name_string' => [['name'], 'string'], + ]; + } +} diff --git a/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/mysql/models/base/Pet.php b/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/mysql/models/base/Pet.php new file mode 100644 index 00000000..73f57ea7 --- /dev/null +++ b/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/mysql/models/base/Pet.php @@ -0,0 +1,57 @@ + [['name'], 'trim'], + 'required' => [['name'], 'required'], + 'name_string' => [['name'], 'string'], + 'age_integer' => [['age'], 'integer'], + 'safe' => [['tags', 'tags_arbit', 'number_arr', 'number_arr_min_uniq', 'int_arr', 'int_arr_min_uniq', 'bool_arr', 'arr_arr_int', 'arr_arr_str', 'arr_arr_arr_str', 'arr_of_obj', 'user_ref_obj_arr', 'one_of_arr', 'one_of_arr_complex', 'one_of_from_multi_ref_arr'], 'safe'], + ]; + } + + public function getUserRefObjArrNormal() + { + return $this->hasMany(\app\models\User::class, ['pet_id' => 'id']); + } + + public function getUserRefObjArr() + { + return $this->hasMany(\app\models\User::class, ['pet_id' => 'id']); + } +} diff --git a/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/mysql/models/base/User.php b/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/mysql/models/base/User.php new file mode 100644 index 00000000..08e59880 --- /dev/null +++ b/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/mysql/models/base/User.php @@ -0,0 +1,26 @@ + [['name'], 'trim'], + 'name_string' => [['name'], 'string'], + ]; + } +} diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index 022ba78b..4e319b28 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -364,20 +364,14 @@ public function test158BugGiiapiGeneratedRulesEnumWithTrim() // https://github.com/php-openapi/yii2-openapi/issues/20 public function test20ConsiderOpenApiSpecExamplesInFakeCodeGeneration() { -// $faker = \Faker\Factory::create(); -// $uniqueFaker = $faker->unique(); -// -// var_dump(); -// return; - $testFile = Yii::getAlias("@specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/index.php"); $this->runGenerator($testFile); -// $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ -// 'recursive' => true, -// ]); -// $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/mysql"), [ -// 'recursive' => true, -// ]); -// $this->checkFiles($actualFiles, $expectedFiles); // TODO + $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ + 'recursive' => true, + ]); + $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/mysql"), [ + 'recursive' => true, + ]); + $this->checkFiles($actualFiles, $expectedFiles); } } From 775ff26adf7915ac42c637900b659e003057efbc Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Sat, 17 Aug 2024 20:31:38 +0530 Subject: [PATCH 142/358] Enhance docs --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index a71b5ec6..8cabdcb5 100644 --- a/README.md +++ b/README.md @@ -323,7 +323,7 @@ related objects, `x-no-relation` (type: boolean, default: false) is used. $ref: "#/components/schemas/Comment" ``` -This will not generate 'comments' column in database migrations. But it will generate `getComments()` relation in model. +This will not generate 'comments' column in database migrations. But it will generate `getComments()` relation in Yii model file. In order to make it real database column, extension `x-no-relation` can be used. @@ -348,7 +348,7 @@ Now if the Comment schema from the above example is type: string ``` -then the value can be +then the value for `comments` can be ```json [ @@ -363,7 +363,7 @@ then the value can be ] ``` -At this moment, `x-no-relation` can be only used with OpenAPI schema data type `array`. +`x-no-relation` can be only used with OpenAPI schema data type `array`. ## Many-to-Many relation definition From e27d9a0822e169145070ef254fe465c10f334bfc Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Sat, 17 Aug 2024 20:35:41 +0530 Subject: [PATCH 143/358] Initial commit to create PR --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 1cd2090b..3bb79307 100644 --- a/README.md +++ b/README.md @@ -568,3 +568,4 @@ Professional support, consulting as well as software development services are av https://www.cebe.cc/en/contact Development of this library is sponsored by [cebe.:cloud: "Your Professional Deployment Platform"](https://cebe.cloud). + From 1bfc499f46a3ff538d924140c9acd07f8b5cfba3 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Sun, 18 Aug 2024 19:31:34 +0530 Subject: [PATCH 144/358] Fix issue and other failing tests --- README.md | 1 - TODO.taskpaper | 9 +++++ src/lib/ValidationRulesBuilder.php | 8 ++--- tests/DbTestCase.php | 7 ++-- tests/specs/blog/models/base/Category.php | 2 +- tests/specs/blog/models/base/Comment.php | 2 +- tests/specs/blog/models/base/Post.php | 2 +- tests/specs/blog/models/base/User.php | 2 +- tests/specs/blog_v2/models/base/Category.php | 2 +- tests/specs/blog_v2/models/base/Comment.php | 2 +- tests/specs/blog_v2/models/base/Post.php | 2 +- tests/specs/blog_v2/models/base/Tag.php | 2 +- tests/specs/blog_v2/models/base/User.php | 2 +- .../app/models/base/ColumnNameChange.php | 2 +- .../app/models/base/ColumnNameChange.php | 2 +- .../app/models/base/ColumnNameChange.php | 2 +- .../fk_col_name/app/models/base/User.php | 2 +- .../app/models/base/User.php | 2 +- .../id_not_in_rules/app/models/base/Fruit.php | 2 +- .../app/models/base/Pristine.php | 2 +- .../maria/models/base/Mailing.php | 2 +- .../maria/models/base/Contact.php | 2 +- .../maria/models/base/Mailing.php | 2 +- .../pgsql/models/base/Account.php | 2 +- .../pgsql/models/base/Contact.php | 2 +- .../pgsql/models/base/PaymentMethod.php | 2 +- .../index.php | 13 +++++++ .../index.yaml | 35 +++++++++++++++++++ .../app/models/base/Account.php | 2 +- tests/specs/many2many/models/base/Photo.php | 2 +- tests/specs/many2many/models/base/Post.php | 2 +- tests/specs/many2many/models/base/Tag.php | 2 +- tests/specs/menu/models/base/Menu.php | 2 +- tests/specs/petstore/models/base/Pet.php | 2 +- tests/specs/petstore/models/base/Store.php | 2 +- .../petstore_arrayref/models/base/Pet.php | 2 +- .../petstore_jsonapi/models/base/Doctor.php | 2 +- .../petstore_jsonapi/models/base/Pet.php | 2 +- .../petstore_namespace/mymodels/base/Pet.php | 2 +- .../mymodels/base/Store.php | 2 +- .../petstore_wrapped/models/base/Pet.php | 2 +- .../specs/petstore_xtable/models/base/Pet.php | 2 +- .../app/models/base/Account.php | 2 +- .../app/models/base/Domain.php | 2 +- .../app/models/base/Routing.php | 2 +- .../models/mariamodel/base/Alldbdatatype.php | 2 +- .../app/models/mariamodel/base/Editcolumn.php | 2 +- .../app/models/mariamodel/base/Newcolumn.php | 2 +- .../app/models/mariamodel/base/Pristine.php | 2 +- .../mysql/app/models/base/Alldbdatatype.php | 2 +- .../mysql/app/models/base/Editcolumn.php | 2 +- .../mysql/app/models/base/Newcolumn.php | 2 +- .../mysql/app/models/base/Pristine.php | 2 +- .../models/pgsqlmodel/base/Alldbdatatype.php | 2 +- .../app/models/pgsqlmodel/base/Editcolumn.php | 2 +- .../app/models/pgsqlmodel/base/Newcolumn.php | 2 +- .../app/models/pgsqlmodel/base/Pristine.php | 2 +- tests/unit/IssueFixTest.php | 14 ++++++++ 58 files changed, 129 insertions(+), 60 deletions(-) create mode 100644 TODO.taskpaper create mode 100644 tests/specs/issue_fix/22_bug_rules_required_is_generated_before_default/index.php create mode 100644 tests/specs/issue_fix/22_bug_rules_required_is_generated_before_default/index.yaml diff --git a/README.md b/README.md index 3bb79307..1cd2090b 100644 --- a/README.md +++ b/README.md @@ -568,4 +568,3 @@ Professional support, consulting as well as software development services are av https://www.cebe.cc/en/contact Development of this library is sponsored by [cebe.:cloud: "Your Professional Deployment Platform"](https://cebe.cloud). - diff --git a/TODO.taskpaper b/TODO.taskpaper new file mode 100644 index 00000000..6fc7c133 --- /dev/null +++ b/TODO.taskpaper @@ -0,0 +1,9 @@ +TODO.taskpaper + +### Bug: rules() "required" is generated before "*_default" #22 + ✔ create failing test @done (24-08-18 19:21) + ✔ implement the solution @done (24-08-18 19:21) + ☐ fix failing tests if any + ☐ resolve TODOs if any + ☐ review PR + ☐ delete this file and submit PR diff --git a/src/lib/ValidationRulesBuilder.php b/src/lib/ValidationRulesBuilder.php index 3f3c1398..f0b1f90d 100644 --- a/src/lib/ValidationRulesBuilder.php +++ b/src/lib/ValidationRulesBuilder.php @@ -10,8 +10,6 @@ use cebe\yii2openapi\lib\items\Attribute; use cebe\yii2openapi\lib\items\DbModel; use cebe\yii2openapi\lib\items\ValidationRule; -use yii\helpers\VarDumper; -use yii\validators\DateValidator; use function count; use function implode; use function in_array; @@ -53,9 +51,6 @@ public function build():array $this->rules['trim'] = new ValidationRule($this->typeScope['trim'], 'trim'); } - if (!empty($this->typeScope['required'])) { - $this->rules['required'] = new ValidationRule($this->typeScope['required'], 'required'); - } if (!empty($this->typeScope['ref'])) { $this->addExistRules($this->typeScope['ref']); } @@ -77,6 +72,9 @@ public function build():array if (!empty($this->typeScope['safe'])) { $this->rules['safe'] = new ValidationRule($this->typeScope['safe'], 'safe'); } + if (!empty($this->typeScope['required'])) { + $this->rules['required'] = new ValidationRule($this->typeScope['required'], 'required'); + } return $this->rules; } diff --git a/tests/DbTestCase.php b/tests/DbTestCase.php index ca7b17ff..c28a314c 100644 --- a/tests/DbTestCase.php +++ b/tests/DbTestCase.php @@ -3,12 +3,12 @@ namespace tests; use cebe\yii2openapi\generator\ApiGenerator; +use SamIT\Yii2\MariaDb\Schema as MariaDbSchema; use Yii; -use yii\di\Container; use yii\db\mysql\Schema as MySqlSchema; use yii\db\pgsql\Schema as PgSqlSchema; -use \SamIT\Yii2\MariaDb\Schema as MariaDbSchema; -use yii\helpers\{ArrayHelper, VarDumper, StringHelper, Console}; +use yii\di\Container; +use yii\helpers\{ArrayHelper, StringHelper}; use yii\helpers\FileHelper; class DbTestCase extends \PHPUnit\Framework\TestCase @@ -127,6 +127,7 @@ protected function checkFiles(array $actual, array $expected) ); } + // exec('cp '.$file.' '.$expectedFilePath); $this->assertFileEquals($expectedFilePath, $file, "Failed asserting that file contents of\n$file\nare equal to file contents of\n$expectedFilePath \n\n cp $file $expectedFilePath \n\n "); } } diff --git a/tests/specs/blog/models/base/Category.php b/tests/specs/blog/models/base/Category.php index f22e0014..0debe57d 100644 --- a/tests/specs/blog/models/base/Category.php +++ b/tests/specs/blog/models/base/Category.php @@ -22,11 +22,11 @@ public function rules() { return [ 'trim' => [['title'], 'trim'], - 'required' => [['title', 'active'], 'required'], 'title_unique' => [['title'], 'unique'], 'title_string' => [['title'], 'string', 'max' => 255], 'active_boolean' => [['active'], 'boolean'], 'active_default' => [['active'], 'default', 'value' => false], + 'required' => [['title', 'active'], 'required'], ]; } diff --git a/tests/specs/blog/models/base/Comment.php b/tests/specs/blog/models/base/Comment.php index 44cd42fc..d74131cb 100644 --- a/tests/specs/blog/models/base/Comment.php +++ b/tests/specs/blog/models/base/Comment.php @@ -26,7 +26,6 @@ public function rules() { return [ 'trim' => [['post_id'], 'trim'], - 'required' => [['post_id', 'author_id', 'message', 'created_at'], 'required'], 'post_id_string' => [['post_id'], 'string', 'max' => 128], 'post_id_exist' => [['post_id'], 'exist', 'targetRelation' => 'Post'], 'author_id_integer' => [['author_id'], 'integer'], @@ -35,6 +34,7 @@ public function rules() 'meta_data_default' => [['meta_data'], 'default', 'value' => []], 'created_at_integer' => [['created_at'], 'integer'], 'safe' => [['message', 'meta_data'], 'safe'], + 'required' => [['post_id', 'author_id', 'message', 'created_at'], 'required'], ]; } diff --git a/tests/specs/blog/models/base/Post.php b/tests/specs/blog/models/base/Post.php index 457978b5..c961a2b0 100644 --- a/tests/specs/blog/models/base/Post.php +++ b/tests/specs/blog/models/base/Post.php @@ -28,7 +28,6 @@ public function rules() { return [ 'trim' => [['title', 'slug', 'created_at'], 'trim'], - 'required' => [['title', 'category_id', 'active'], 'required'], 'category_id_integer' => [['category_id'], 'integer'], 'category_id_exist' => [['category_id'], 'exist', 'targetRelation' => 'Category'], 'created_by_id_integer' => [['created_by_id'], 'integer'], @@ -40,6 +39,7 @@ public function rules() 'active_boolean' => [['active'], 'boolean'], 'active_default' => [['active'], 'default', 'value' => false], 'created_at_date' => [['created_at'], 'date', 'format' => 'php:Y-m-d'], + 'required' => [['title', 'category_id', 'active'], 'required'], ]; } diff --git a/tests/specs/blog/models/base/User.php b/tests/specs/blog/models/base/User.php index f0e484e8..bf30a8bd 100644 --- a/tests/specs/blog/models/base/User.php +++ b/tests/specs/blog/models/base/User.php @@ -25,7 +25,6 @@ public function rules() { return [ 'trim' => [['username', 'email', 'password', 'role', 'created_at'], 'trim'], - 'required' => [['username', 'email', 'password'], 'required'], 'username_unique' => [['username'], 'unique'], 'email_unique' => [['email'], 'unique'], 'username_string' => [['username'], 'string', 'max' => 200], @@ -37,6 +36,7 @@ public function rules() 'flags_integer' => [['flags'], 'integer'], 'flags_default' => [['flags'], 'default', 'value' => 0], 'created_at_datetime' => [['created_at'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], + 'required' => [['username', 'email', 'password'], 'required'], ]; } } diff --git a/tests/specs/blog_v2/models/base/Category.php b/tests/specs/blog_v2/models/base/Category.php index a70be3ff..a3ef9567 100644 --- a/tests/specs/blog_v2/models/base/Category.php +++ b/tests/specs/blog_v2/models/base/Category.php @@ -23,10 +23,10 @@ public function rules() { return [ 'trim' => [['title', 'cover'], 'trim'], - 'required' => [['title', 'cover', 'active'], 'required'], 'title_string' => [['title'], 'string', 'max' => 100], 'cover_string' => [['cover'], 'string'], 'active_boolean' => [['active'], 'boolean'], + 'required' => [['title', 'cover', 'active'], 'required'], ]; } diff --git a/tests/specs/blog_v2/models/base/Comment.php b/tests/specs/blog_v2/models/base/Comment.php index a732c5c0..8f634180 100644 --- a/tests/specs/blog_v2/models/base/Comment.php +++ b/tests/specs/blog_v2/models/base/Comment.php @@ -26,7 +26,6 @@ public function rules() { return [ 'trim' => [['message', 'meta_data', 'created_at'], 'trim'], - 'required' => [['post_id', 'message', 'created_at'], 'required'], 'post_id_integer' => [['post_id'], 'integer'], 'post_id_exist' => [['post_id'], 'exist', 'targetRelation' => 'Post'], 'user_id_integer' => [['user_id'], 'integer'], @@ -35,6 +34,7 @@ public function rules() 'meta_data_string' => [['meta_data'], 'string', 'min' => 1, 'max' => 300], 'meta_data_default' => [['meta_data'], 'default', 'value' => ''], 'created_at_datetime' => [['created_at'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], + 'required' => [['post_id', 'message', 'created_at'], 'required'], ]; } diff --git a/tests/specs/blog_v2/models/base/Post.php b/tests/specs/blog_v2/models/base/Post.php index 44fe4275..17f3c8c4 100644 --- a/tests/specs/blog_v2/models/base/Post.php +++ b/tests/specs/blog_v2/models/base/Post.php @@ -30,7 +30,6 @@ public function rules() { return [ 'trim' => [['title', 'slug', 'created_at'], 'trim'], - 'required' => [['title', 'category_id', 'active'], 'required'], 'category_id_integer' => [['category_id'], 'integer'], 'category_id_exist' => [['category_id'], 'exist', 'targetRelation' => 'Category'], 'created_by_id_integer' => [['created_by_id'], 'integer'], @@ -46,6 +45,7 @@ public function rules() 'lang_default' => [['lang'], 'default', 'value' => 'ru'], 'active_boolean' => [['active'], 'boolean'], 'created_at_date' => [['created_at'], 'date', 'format' => 'php:Y-m-d'], + 'required' => [['title', 'category_id', 'active'], 'required'], ]; } diff --git a/tests/specs/blog_v2/models/base/Tag.php b/tests/specs/blog_v2/models/base/Tag.php index f1a57778..2a971ebc 100644 --- a/tests/specs/blog_v2/models/base/Tag.php +++ b/tests/specs/blog_v2/models/base/Tag.php @@ -22,7 +22,6 @@ public function rules() { return [ 'trim' => [['name'], 'trim'], - 'required' => [['name', 'lang'], 'required'], 'name_unique' => [['name'], 'unique'], 'name_string' => [['name'], 'string', 'max' => 100], 'lang_string' => [['lang'], 'string'], @@ -30,6 +29,7 @@ public function rules() 'ru', 'eng', ]], + 'required' => [['name', 'lang'], 'required'], ]; } diff --git a/tests/specs/blog_v2/models/base/User.php b/tests/specs/blog_v2/models/base/User.php index 195b5b5e..eddb7448 100644 --- a/tests/specs/blog_v2/models/base/User.php +++ b/tests/specs/blog_v2/models/base/User.php @@ -25,7 +25,6 @@ public function rules() { return [ 'trim' => [['login', 'email', 'password', 'created_at'], 'trim'], - 'required' => [['login', 'email', 'password'], 'required'], 'login_unique' => [['login'], 'unique'], 'email_unique' => [['email'], 'unique'], 'login_string' => [['login'], 'string'], @@ -41,6 +40,7 @@ public function rules() 'flags_integer' => [['flags'], 'integer'], 'flags_default' => [['flags'], 'default', 'value' => 0], 'created_at_datetime' => [['created_at'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], + 'required' => [['login', 'email', 'password'], 'required'], ]; } } diff --git a/tests/specs/change_column_name/maria/app/models/base/ColumnNameChange.php b/tests/specs/change_column_name/maria/app/models/base/ColumnNameChange.php index a5393546..79574d97 100644 --- a/tests/specs/change_column_name/maria/app/models/base/ColumnNameChange.php +++ b/tests/specs/change_column_name/maria/app/models/base/ColumnNameChange.php @@ -21,8 +21,8 @@ public function rules() { return [ 'trim' => [['name'], 'trim'], - 'required' => [['name'], 'required'], 'name_string' => [['name'], 'string', 'max' => 255], + 'required' => [['name'], 'required'], ]; } } diff --git a/tests/specs/change_column_name/mysql/app/models/base/ColumnNameChange.php b/tests/specs/change_column_name/mysql/app/models/base/ColumnNameChange.php index a5393546..79574d97 100644 --- a/tests/specs/change_column_name/mysql/app/models/base/ColumnNameChange.php +++ b/tests/specs/change_column_name/mysql/app/models/base/ColumnNameChange.php @@ -21,8 +21,8 @@ public function rules() { return [ 'trim' => [['name'], 'trim'], - 'required' => [['name'], 'required'], 'name_string' => [['name'], 'string', 'max' => 255], + 'required' => [['name'], 'required'], ]; } } diff --git a/tests/specs/change_column_name/pgsql/app/models/base/ColumnNameChange.php b/tests/specs/change_column_name/pgsql/app/models/base/ColumnNameChange.php index 426b5a1f..4040250f 100644 --- a/tests/specs/change_column_name/pgsql/app/models/base/ColumnNameChange.php +++ b/tests/specs/change_column_name/pgsql/app/models/base/ColumnNameChange.php @@ -21,8 +21,8 @@ public function rules() { return [ 'trim' => [['name'], 'trim'], - 'required' => [['name'], 'required'], 'name_string' => [['name'], 'string', 'max' => 255], + 'required' => [['name'], 'required'], ]; } } diff --git a/tests/specs/fk_col_name/app/models/base/User.php b/tests/specs/fk_col_name/app/models/base/User.php index d76c3f4d..3b1bc8d1 100644 --- a/tests/specs/fk_col_name/app/models/base/User.php +++ b/tests/specs/fk_col_name/app/models/base/User.php @@ -20,8 +20,8 @@ public function rules() { return [ 'trim' => [['name'], 'trim'], - 'required' => [['name'], 'required'], 'name_string' => [['name'], 'string'], + 'required' => [['name'], 'required'], ]; } } diff --git a/tests/specs/fk_col_name_index/app/models/base/User.php b/tests/specs/fk_col_name_index/app/models/base/User.php index d76c3f4d..3b1bc8d1 100644 --- a/tests/specs/fk_col_name_index/app/models/base/User.php +++ b/tests/specs/fk_col_name_index/app/models/base/User.php @@ -20,8 +20,8 @@ public function rules() { return [ 'trim' => [['name'], 'trim'], - 'required' => [['name'], 'required'], 'name_string' => [['name'], 'string'], + 'required' => [['name'], 'required'], ]; } } diff --git a/tests/specs/id_not_in_rules/app/models/base/Fruit.php b/tests/specs/id_not_in_rules/app/models/base/Fruit.php index 4b1fcd72..9ecdbcf2 100644 --- a/tests/specs/id_not_in_rules/app/models/base/Fruit.php +++ b/tests/specs/id_not_in_rules/app/models/base/Fruit.php @@ -20,8 +20,8 @@ public function rules() { return [ 'trim' => [['name'], 'trim'], - 'required' => [['name'], 'required'], 'name_string' => [['name'], 'string'], + 'required' => [['name'], 'required'], ]; } } diff --git a/tests/specs/issue_fix/153_nullable_false_in_required/app/models/base/Pristine.php b/tests/specs/issue_fix/153_nullable_false_in_required/app/models/base/Pristine.php index 8cc79e6f..58324717 100644 --- a/tests/specs/issue_fix/153_nullable_false_in_required/app/models/base/Pristine.php +++ b/tests/specs/issue_fix/153_nullable_false_in_required/app/models/base/Pristine.php @@ -19,9 +19,9 @@ public static function tableName() public function rules() { return [ - 'required' => [['billing_factor'], 'required'], 'billing_factor_integer' => [['billing_factor'], 'integer'], 'billing_factor_default' => [['billing_factor'], 'default', 'value' => 100], + 'required' => [['billing_factor'], 'required'], ]; } } diff --git a/tests/specs/issue_fix/158_bug_giiapi_generated_rules_enum_with_trim/maria/models/base/Mailing.php b/tests/specs/issue_fix/158_bug_giiapi_generated_rules_enum_with_trim/maria/models/base/Mailing.php index 2839c526..de55cf39 100644 --- a/tests/specs/issue_fix/158_bug_giiapi_generated_rules_enum_with_trim/maria/models/base/Mailing.php +++ b/tests/specs/issue_fix/158_bug_giiapi_generated_rules_enum_with_trim/maria/models/base/Mailing.php @@ -21,7 +21,6 @@ public function rules() { return [ 'trim' => [['name'], 'trim'], - 'required' => [['name'], 'required'], 'name_string' => [['name'], 'string', 'max' => 128], 'paymentMethodName_string' => [['paymentMethodName'], 'string'], 'paymentMethodName_in' => [['paymentMethodName'], 'in', 'range' => [ @@ -29,6 +28,7 @@ public function rules() 'cash', 'ewallet', ]], + 'required' => [['name'], 'required'], ]; } } diff --git a/tests/specs/issue_fix/159_bug_giiapi_generated_rules_emailid/maria/models/base/Contact.php b/tests/specs/issue_fix/159_bug_giiapi_generated_rules_emailid/maria/models/base/Contact.php index efbd8b32..2186badc 100644 --- a/tests/specs/issue_fix/159_bug_giiapi_generated_rules_emailid/maria/models/base/Contact.php +++ b/tests/specs/issue_fix/159_bug_giiapi_generated_rules_emailid/maria/models/base/Contact.php @@ -23,12 +23,12 @@ public function rules() { return [ 'trim' => [['nickname'], 'trim'], - 'required' => [['mailing_id'], 'required'], 'mailing_id_integer' => [['mailing_id'], 'integer'], 'mailing_id_exist' => [['mailing_id'], 'exist', 'targetRelation' => 'Mailing'], 'active_boolean' => [['active'], 'boolean'], 'active_default' => [['active'], 'default', 'value' => false], 'nickname_string' => [['nickname'], 'string'], + 'required' => [['mailing_id'], 'required'], ]; } diff --git a/tests/specs/issue_fix/159_bug_giiapi_generated_rules_emailid/maria/models/base/Mailing.php b/tests/specs/issue_fix/159_bug_giiapi_generated_rules_emailid/maria/models/base/Mailing.php index 77049b23..5dcaec74 100644 --- a/tests/specs/issue_fix/159_bug_giiapi_generated_rules_emailid/maria/models/base/Mailing.php +++ b/tests/specs/issue_fix/159_bug_giiapi_generated_rules_emailid/maria/models/base/Mailing.php @@ -21,9 +21,9 @@ public function rules() { return [ 'trim' => [['name', 'paymentMethodName'], 'trim'], - 'required' => [['name'], 'required'], 'name_string' => [['name'], 'string', 'max' => 128], 'paymentMethodName_string' => [['paymentMethodName'], 'string'], + 'required' => [['name'], 'required'], ]; } } diff --git a/tests/specs/issue_fix/175_bug_allof_with_multiple_dollarrefs/pgsql/models/base/Account.php b/tests/specs/issue_fix/175_bug_allof_with_multiple_dollarrefs/pgsql/models/base/Account.php index f3dae5db..c671a556 100644 --- a/tests/specs/issue_fix/175_bug_allof_with_multiple_dollarrefs/pgsql/models/base/Account.php +++ b/tests/specs/issue_fix/175_bug_allof_with_multiple_dollarrefs/pgsql/models/base/Account.php @@ -21,9 +21,9 @@ public function rules() { return [ 'trim' => [['name', 'paymentMethodName'], 'trim'], - 'required' => [['name'], 'required'], 'name_string' => [['name'], 'string', 'max' => 128], 'paymentMethodName_string' => [['paymentMethodName'], 'string'], + 'required' => [['name'], 'required'], ]; } } diff --git a/tests/specs/issue_fix/175_bug_allof_with_multiple_dollarrefs/pgsql/models/base/Contact.php b/tests/specs/issue_fix/175_bug_allof_with_multiple_dollarrefs/pgsql/models/base/Contact.php index 21a2e7f1..c3a42a9a 100644 --- a/tests/specs/issue_fix/175_bug_allof_with_multiple_dollarrefs/pgsql/models/base/Contact.php +++ b/tests/specs/issue_fix/175_bug_allof_with_multiple_dollarrefs/pgsql/models/base/Contact.php @@ -23,12 +23,12 @@ public function rules() { return [ 'trim' => [['nickname'], 'trim'], - 'required' => [['account_id'], 'required'], 'account_id_integer' => [['account_id'], 'integer'], 'account_id_exist' => [['account_id'], 'exist', 'targetRelation' => 'Account'], 'active_boolean' => [['active'], 'boolean'], 'active_default' => [['active'], 'default', 'value' => false], 'nickname_string' => [['nickname'], 'string'], + 'required' => [['account_id'], 'required'], ]; } diff --git a/tests/specs/issue_fix/175_bug_allof_with_multiple_dollarrefs/pgsql/models/base/PaymentMethod.php b/tests/specs/issue_fix/175_bug_allof_with_multiple_dollarrefs/pgsql/models/base/PaymentMethod.php index 79e8c05b..6e18e8cd 100644 --- a/tests/specs/issue_fix/175_bug_allof_with_multiple_dollarrefs/pgsql/models/base/PaymentMethod.php +++ b/tests/specs/issue_fix/175_bug_allof_with_multiple_dollarrefs/pgsql/models/base/PaymentMethod.php @@ -20,9 +20,9 @@ public function rules() { return [ 'trim' => [['name'], 'trim'], - 'required' => [['name'], 'required'], 'name_unique' => [['name'], 'unique'], 'name_string' => [['name'], 'string', 'max' => 150], + 'required' => [['name'], 'required'], ]; } } diff --git a/tests/specs/issue_fix/22_bug_rules_required_is_generated_before_default/index.php b/tests/specs/issue_fix/22_bug_rules_required_is_generated_before_default/index.php new file mode 100644 index 00000000..ebfdd29d --- /dev/null +++ b/tests/specs/issue_fix/22_bug_rules_required_is_generated_before_default/index.php @@ -0,0 +1,13 @@ + '@specs/issue_fix/22_bug_rules_required_is_generated_before_default/index.yaml', + 'generateUrls' => false, + 'generateModels' => true, + 'excludeModels' => [ + 'Error', + ], + 'generateControllers' => false, + 'generateMigrations' => true, + 'generateModelFaker' => true, // `generateModels` must be `true` in order to use `generateModelFaker` as `true` +]; diff --git a/tests/specs/issue_fix/22_bug_rules_required_is_generated_before_default/index.yaml b/tests/specs/issue_fix/22_bug_rules_required_is_generated_before_default/index.yaml new file mode 100644 index 00000000..889ab5b3 --- /dev/null +++ b/tests/specs/issue_fix/22_bug_rules_required_is_generated_before_default/index.yaml @@ -0,0 +1,35 @@ +openapi: 3.0.3 + +info: + title: 'Bug: rules() "required" is generated before "*_default" #22' + version: 1.0.0 + +components: + schemas: + Account: + description: Account + type: object + required: + - id + - name + - verified + properties: + id: + type: integer + readOnly: true + name: + description: account name + type: string + maxLength: 128 + paymentMethodName: + type: string + verified: + type: boolean + default: false + +paths: + '/account': + get: + responses: + '200': + description: Account info diff --git a/tests/specs/issue_fix/model_name_more_than_once_in_faker_148/app/models/base/Account.php b/tests/specs/issue_fix/model_name_more_than_once_in_faker_148/app/models/base/Account.php index 0ee4adc0..52b589e1 100644 --- a/tests/specs/issue_fix/model_name_more_than_once_in_faker_148/app/models/base/Account.php +++ b/tests/specs/issue_fix/model_name_more_than_once_in_faker_148/app/models/base/Account.php @@ -20,8 +20,8 @@ public function rules() { return [ 'trim' => [['name'], 'trim'], - 'required' => [['name'], 'required'], 'name_string' => [['name'], 'string', 'max' => 40], + 'required' => [['name'], 'required'], ]; } } diff --git a/tests/specs/many2many/models/base/Photo.php b/tests/specs/many2many/models/base/Photo.php index eb08fec7..b7d13e2e 100644 --- a/tests/specs/many2many/models/base/Photo.php +++ b/tests/specs/many2many/models/base/Photo.php @@ -26,8 +26,8 @@ public function rules() { return [ 'trim' => [['filename'], 'trim'], - 'required' => [['filename'], 'required'], 'filename_string' => [['filename'], 'string'], + 'required' => [['filename'], 'required'], ]; } diff --git a/tests/specs/many2many/models/base/Post.php b/tests/specs/many2many/models/base/Post.php index 6ecfc3ce..c9c37e06 100644 --- a/tests/specs/many2many/models/base/Post.php +++ b/tests/specs/many2many/models/base/Post.php @@ -27,8 +27,8 @@ public function rules() { return [ 'trim' => [['title'], 'trim'], - 'required' => [['title'], 'required'], 'title_string' => [['title'], 'string'], + 'required' => [['title'], 'required'], ]; } diff --git a/tests/specs/many2many/models/base/Tag.php b/tests/specs/many2many/models/base/Tag.php index 8d7cfc24..5f15a84c 100644 --- a/tests/specs/many2many/models/base/Tag.php +++ b/tests/specs/many2many/models/base/Tag.php @@ -21,8 +21,8 @@ public function rules() { return [ 'trim' => [['name'], 'trim'], - 'required' => [['name'], 'required'], 'name_string' => [['name'], 'string'], + 'required' => [['name'], 'required'], ]; } diff --git a/tests/specs/menu/models/base/Menu.php b/tests/specs/menu/models/base/Menu.php index 582d952d..f3e10612 100644 --- a/tests/specs/menu/models/base/Menu.php +++ b/tests/specs/menu/models/base/Menu.php @@ -25,7 +25,6 @@ public function rules() { return [ 'trim' => [['name'], 'trim'], - 'required' => [['name'], 'required'], 'parent_id_integer' => [['parent_id'], 'integer'], 'parent_id_exist' => [['parent_id'], 'exist', 'targetRelation' => 'Parent'], 'name_string' => [['name'], 'string', 'min' => 3, 'max' => 100], @@ -43,6 +42,7 @@ public function rules() ], ]], 'safe' => [['args', 'kwargs'], 'safe'], + 'required' => [['name'], 'required'], ]; } diff --git a/tests/specs/petstore/models/base/Pet.php b/tests/specs/petstore/models/base/Pet.php index 039764d2..27566a9b 100644 --- a/tests/specs/petstore/models/base/Pet.php +++ b/tests/specs/petstore/models/base/Pet.php @@ -23,11 +23,11 @@ public function rules() { return [ 'trim' => [['name', 'tag'], 'trim'], - 'required' => [['name'], 'required'], 'store_id_integer' => [['store_id'], 'integer'], 'store_id_exist' => [['store_id'], 'exist', 'targetRelation' => 'Store'], 'name_string' => [['name'], 'string'], 'tag_string' => [['tag'], 'string'], + 'required' => [['name'], 'required'], ]; } diff --git a/tests/specs/petstore/models/base/Store.php b/tests/specs/petstore/models/base/Store.php index b1f6bc0f..432fed31 100644 --- a/tests/specs/petstore/models/base/Store.php +++ b/tests/specs/petstore/models/base/Store.php @@ -20,8 +20,8 @@ public function rules() { return [ 'trim' => [['name'], 'trim'], - 'required' => [['name'], 'required'], 'name_string' => [['name'], 'string'], + 'required' => [['name'], 'required'], ]; } } diff --git a/tests/specs/petstore_arrayref/models/base/Pet.php b/tests/specs/petstore_arrayref/models/base/Pet.php index 660237dd..6e67994d 100644 --- a/tests/specs/petstore_arrayref/models/base/Pet.php +++ b/tests/specs/petstore_arrayref/models/base/Pet.php @@ -22,9 +22,9 @@ public function rules() { return [ 'trim' => [['name', 'tag'], 'trim'], - 'required' => [['name'], 'required'], 'name_string' => [['name'], 'string'], 'tag_string' => [['tag'], 'string'], + 'required' => [['name'], 'required'], ]; } diff --git a/tests/specs/petstore_jsonapi/models/base/Doctor.php b/tests/specs/petstore_jsonapi/models/base/Doctor.php index b13bdaa5..32f6ca70 100644 --- a/tests/specs/petstore_jsonapi/models/base/Doctor.php +++ b/tests/specs/petstore_jsonapi/models/base/Doctor.php @@ -29,10 +29,10 @@ public function rules() { return [ 'trim' => [['name', 'surname'], 'trim'], - 'required' => [['name'], 'required'], 'name_string' => [['name'], 'string', 'max' => 200], 'surname_string' => [['surname'], 'string', 'max' => 200], 'safe' => [['phones'], 'safe'], + 'required' => [['name'], 'required'], ]; } } diff --git a/tests/specs/petstore_jsonapi/models/base/Pet.php b/tests/specs/petstore_jsonapi/models/base/Pet.php index f0e3138a..e75f31ce 100644 --- a/tests/specs/petstore_jsonapi/models/base/Pet.php +++ b/tests/specs/petstore_jsonapi/models/base/Pet.php @@ -48,10 +48,10 @@ public function rules() { return [ 'trim' => [['name', 'tag', 'petCode'], 'trim'], - 'required' => [['name'], 'required'], 'name_string' => [['name'], 'string'], 'tag_string' => [['tag'], 'string'], 'petCode_string' => [['petCode'], 'string', 'max' => 50], + 'required' => [['name'], 'required'], ]; } diff --git a/tests/specs/petstore_namespace/mymodels/base/Pet.php b/tests/specs/petstore_namespace/mymodels/base/Pet.php index 58750645..9a6be041 100644 --- a/tests/specs/petstore_namespace/mymodels/base/Pet.php +++ b/tests/specs/petstore_namespace/mymodels/base/Pet.php @@ -23,11 +23,11 @@ public function rules() { return [ 'trim' => [['name', 'tag'], 'trim'], - 'required' => [['name'], 'required'], 'store_id_integer' => [['store_id'], 'integer'], 'store_id_exist' => [['store_id'], 'exist', 'targetRelation' => 'Store'], 'name_string' => [['name'], 'string'], 'tag_string' => [['tag'], 'string'], + 'required' => [['name'], 'required'], ]; } diff --git a/tests/specs/petstore_namespace/mymodels/base/Store.php b/tests/specs/petstore_namespace/mymodels/base/Store.php index 6ecc3e47..ecce86b6 100644 --- a/tests/specs/petstore_namespace/mymodels/base/Store.php +++ b/tests/specs/petstore_namespace/mymodels/base/Store.php @@ -20,8 +20,8 @@ public function rules() { return [ 'trim' => [['name'], 'trim'], - 'required' => [['name'], 'required'], 'name_string' => [['name'], 'string'], + 'required' => [['name'], 'required'], ]; } } diff --git a/tests/specs/petstore_wrapped/models/base/Pet.php b/tests/specs/petstore_wrapped/models/base/Pet.php index fc84b808..fadf9d48 100644 --- a/tests/specs/petstore_wrapped/models/base/Pet.php +++ b/tests/specs/petstore_wrapped/models/base/Pet.php @@ -21,9 +21,9 @@ public function rules() { return [ 'trim' => [['name', 'tag'], 'trim'], - 'required' => [['name'], 'required'], 'name_string' => [['name'], 'string'], 'tag_string' => [['tag'], 'string'], + 'required' => [['name'], 'required'], ]; } } diff --git a/tests/specs/petstore_xtable/models/base/Pet.php b/tests/specs/petstore_xtable/models/base/Pet.php index fc84b808..fadf9d48 100644 --- a/tests/specs/petstore_xtable/models/base/Pet.php +++ b/tests/specs/petstore_xtable/models/base/Pet.php @@ -21,9 +21,9 @@ public function rules() { return [ 'trim' => [['name', 'tag'], 'trim'], - 'required' => [['name'], 'required'], 'name_string' => [['name'], 'string'], 'tag_string' => [['tag'], 'string'], + 'required' => [['name'], 'required'], ]; } } diff --git a/tests/specs/relations_in_faker/app/models/base/Account.php b/tests/specs/relations_in_faker/app/models/base/Account.php index 0ee4adc0..52b589e1 100644 --- a/tests/specs/relations_in_faker/app/models/base/Account.php +++ b/tests/specs/relations_in_faker/app/models/base/Account.php @@ -20,8 +20,8 @@ public function rules() { return [ 'trim' => [['name'], 'trim'], - 'required' => [['name'], 'required'], 'name_string' => [['name'], 'string', 'max' => 40], + 'required' => [['name'], 'required'], ]; } } diff --git a/tests/specs/relations_in_faker/app/models/base/Domain.php b/tests/specs/relations_in_faker/app/models/base/Domain.php index 3f861f9e..c51b5163 100644 --- a/tests/specs/relations_in_faker/app/models/base/Domain.php +++ b/tests/specs/relations_in_faker/app/models/base/Domain.php @@ -24,10 +24,10 @@ public function rules() { return [ 'trim' => [['name'], 'trim'], - 'required' => [['name', 'account_id'], 'required'], 'account_id_integer' => [['account_id'], 'integer'], 'account_id_exist' => [['account_id'], 'exist', 'targetRelation' => 'Account'], 'name_string' => [['name'], 'string', 'max' => 128], + 'required' => [['name', 'account_id'], 'required'], ]; } diff --git a/tests/specs/relations_in_faker/app/models/base/Routing.php b/tests/specs/relations_in_faker/app/models/base/Routing.php index 71a31b81..1731d234 100644 --- a/tests/specs/relations_in_faker/app/models/base/Routing.php +++ b/tests/specs/relations_in_faker/app/models/base/Routing.php @@ -30,7 +30,6 @@ public function rules() { return [ 'trim' => [['path', 'service'], 'trim'], - 'required' => [['domain_id'], 'required'], 'domain_id_integer' => [['domain_id'], 'integer'], 'domain_id_exist' => [['domain_id'], 'exist', 'targetRelation' => 'Domain'], 'd123_id_integer' => [['d123_id'], 'integer'], @@ -41,6 +40,7 @@ public function rules() 'ssl_boolean' => [['ssl'], 'boolean'], 'redirect_to_ssl_boolean' => [['redirect_to_ssl'], 'boolean'], 'service_string' => [['service'], 'string', 'max' => 255], + 'required' => [['domain_id'], 'required'], ]; } diff --git a/tests/specs/x_db_type/rules_and_more/maria/app/models/mariamodel/base/Alldbdatatype.php b/tests/specs/x_db_type/rules_and_more/maria/app/models/mariamodel/base/Alldbdatatype.php index 6a35d601..0077fb3a 100644 --- a/tests/specs/x_db_type/rules_and_more/maria/app/models/mariamodel/base/Alldbdatatype.php +++ b/tests/specs/x_db_type/rules_and_more/maria/app/models/mariamodel/base/Alldbdatatype.php @@ -62,7 +62,6 @@ public function rules() { return [ 'trim' => [['string_col', 'varchar_col', 'text_col', 'varchar_4_col', 'char_4_col', 'char_5_col', 'char_6_col', 'char_7_col', 'char_8_col', 'date_col', 'time_col', 'datetime_col', 'timestamp_col', 'year_col', 'text_def'], 'trim'], - 'required' => [['char_6_col', 'char_7_col'], 'required'], 'string_col_string' => [['string_col'], 'string', 'max' => 255], 'varchar_col_string' => [['varchar_col'], 'string', 'max' => 132], 'text_col_string' => [['text_col'], 'string'], @@ -109,6 +108,7 @@ public function rules() 'a' => 'b', ]], 'safe' => [['varbinary_col', 'blob_col', 'json_col', 'json_col_def', 'json_col_def_2', 'blob_def', 'json_def'], 'safe'], + 'required' => [['char_6_col', 'char_7_col'], 'required'], ]; } } diff --git a/tests/specs/x_db_type/rules_and_more/maria/app/models/mariamodel/base/Editcolumn.php b/tests/specs/x_db_type/rules_and_more/maria/app/models/mariamodel/base/Editcolumn.php index 62f98624..1c49081a 100644 --- a/tests/specs/x_db_type/rules_and_more/maria/app/models/mariamodel/base/Editcolumn.php +++ b/tests/specs/x_db_type/rules_and_more/maria/app/models/mariamodel/base/Editcolumn.php @@ -30,7 +30,6 @@ public function rules() { return [ 'trim' => [['name', 'tag', 'first_name', 'string_col', 'str_col_def', 'json_col'], 'trim'], - 'required' => [['name', 'str_col_def', 'json_col', 'json_col_2'], 'required'], 'name_string' => [['name'], 'string', 'max' => 254], 'name_default' => [['name'], 'default', 'value' => 'Horse-2'], 'tag_string' => [['tag'], 'string'], @@ -46,6 +45,7 @@ public function rules() 'json_col_def_n_default' => [['json_col_def_n'], 'default', 'value' => []], 'json_col_def_n_2_default' => [['json_col_def_n_2'], 'default', 'value' => []], 'safe' => [['json_col_2', 'json_col_def_n', 'json_col_def_n_2'], 'safe'], + 'required' => [['name', 'str_col_def', 'json_col', 'json_col_2'], 'required'], ]; } } diff --git a/tests/specs/x_db_type/rules_and_more/maria/app/models/mariamodel/base/Newcolumn.php b/tests/specs/x_db_type/rules_and_more/maria/app/models/mariamodel/base/Newcolumn.php index 15da0af8..4df93c0c 100644 --- a/tests/specs/x_db_type/rules_and_more/maria/app/models/mariamodel/base/Newcolumn.php +++ b/tests/specs/x_db_type/rules_and_more/maria/app/models/mariamodel/base/Newcolumn.php @@ -26,7 +26,6 @@ public function rules() { return [ 'trim' => [['name', 'last_name', 'varchar_col'], 'trim'], - 'required' => [['name'], 'required'], 'name_string' => [['name'], 'string', 'max' => 255], 'last_name_string' => [['last_name'], 'string'], 'dec_col_double' => [['dec_col'], 'double'], @@ -34,6 +33,7 @@ public function rules() 'numeric_col_double' => [['numeric_col'], 'double'], 'json_col_def_n_default' => [['json_col_def_n'], 'default', 'value' => []], 'safe' => [['json_col', 'json_col_def_n'], 'safe'], + 'required' => [['name'], 'required'], ]; } } diff --git a/tests/specs/x_db_type/rules_and_more/maria/app/models/mariamodel/base/Pristine.php b/tests/specs/x_db_type/rules_and_more/maria/app/models/mariamodel/base/Pristine.php index a5d7c1ef..a8ce93d2 100644 --- a/tests/specs/x_db_type/rules_and_more/maria/app/models/mariamodel/base/Pristine.php +++ b/tests/specs/x_db_type/rules_and_more/maria/app/models/mariamodel/base/Pristine.php @@ -30,7 +30,6 @@ public function rules() { return [ 'trim' => [['name', 'tag', 'new_col', 'col_9', 'col_10', 'col_11'], 'trim'], - 'required' => [['custom_id_col', 'name'], 'required'], 'custom_id_col_integer' => [['custom_id_col'], 'integer'], 'name_string' => [['name'], 'string'], 'tag_string' => [['tag'], 'string'], @@ -45,6 +44,7 @@ public function rules() 'price_double' => [['price'], 'double'], 'price_default' => [['price'], 'default', 'value' => 0], 'safe' => [['col_8'], 'safe'], + 'required' => [['custom_id_col', 'name'], 'required'], ]; } } diff --git a/tests/specs/x_db_type/rules_and_more/mysql/app/models/base/Alldbdatatype.php b/tests/specs/x_db_type/rules_and_more/mysql/app/models/base/Alldbdatatype.php index 41326222..02e39bc6 100644 --- a/tests/specs/x_db_type/rules_and_more/mysql/app/models/base/Alldbdatatype.php +++ b/tests/specs/x_db_type/rules_and_more/mysql/app/models/base/Alldbdatatype.php @@ -62,7 +62,6 @@ public function rules() { return [ 'trim' => [['string_col', 'varchar_col', 'text_col', 'varchar_4_col', 'char_4_col', 'char_5_col', 'char_6_col', 'char_7_col', 'char_8_col', 'date_col', 'time_col', 'datetime_col', 'timestamp_col', 'year_col', 'text_def'], 'trim'], - 'required' => [['char_6_col', 'char_7_col'], 'required'], 'string_col_string' => [['string_col'], 'string', 'max' => 255], 'varchar_col_string' => [['varchar_col'], 'string', 'max' => 132], 'text_col_string' => [['text_col'], 'string'], @@ -109,6 +108,7 @@ public function rules() 'a' => 'b', ]], 'safe' => [['varbinary_col', 'blob_col', 'json_col', 'json_col_def', 'json_col_def_2', 'blob_def', 'json_def'], 'safe'], + 'required' => [['char_6_col', 'char_7_col'], 'required'], ]; } } diff --git a/tests/specs/x_db_type/rules_and_more/mysql/app/models/base/Editcolumn.php b/tests/specs/x_db_type/rules_and_more/mysql/app/models/base/Editcolumn.php index 2b630e67..677d16a9 100644 --- a/tests/specs/x_db_type/rules_and_more/mysql/app/models/base/Editcolumn.php +++ b/tests/specs/x_db_type/rules_and_more/mysql/app/models/base/Editcolumn.php @@ -30,7 +30,6 @@ public function rules() { return [ 'trim' => [['name', 'tag', 'first_name', 'string_col', 'str_col_def', 'json_col'], 'trim'], - 'required' => [['name', 'str_col_def', 'json_col', 'json_col_2'], 'required'], 'name_string' => [['name'], 'string', 'max' => 254], 'name_default' => [['name'], 'default', 'value' => 'Horse-2'], 'tag_string' => [['tag'], 'string'], @@ -46,6 +45,7 @@ public function rules() 'json_col_def_n_default' => [['json_col_def_n'], 'default', 'value' => []], 'json_col_def_n_2_default' => [['json_col_def_n_2'], 'default', 'value' => []], 'safe' => [['json_col_2', 'json_col_def_n', 'json_col_def_n_2'], 'safe'], + 'required' => [['name', 'str_col_def', 'json_col', 'json_col_2'], 'required'], ]; } } diff --git a/tests/specs/x_db_type/rules_and_more/mysql/app/models/base/Newcolumn.php b/tests/specs/x_db_type/rules_and_more/mysql/app/models/base/Newcolumn.php index 186ef3fe..0569715e 100644 --- a/tests/specs/x_db_type/rules_and_more/mysql/app/models/base/Newcolumn.php +++ b/tests/specs/x_db_type/rules_and_more/mysql/app/models/base/Newcolumn.php @@ -26,7 +26,6 @@ public function rules() { return [ 'trim' => [['name', 'last_name', 'varchar_col'], 'trim'], - 'required' => [['name'], 'required'], 'name_string' => [['name'], 'string', 'max' => 255], 'last_name_string' => [['last_name'], 'string'], 'dec_col_double' => [['dec_col'], 'double'], @@ -34,6 +33,7 @@ public function rules() 'numeric_col_double' => [['numeric_col'], 'double'], 'json_col_def_n_default' => [['json_col_def_n'], 'default', 'value' => []], 'safe' => [['json_col', 'json_col_def_n'], 'safe'], + 'required' => [['name'], 'required'], ]; } } diff --git a/tests/specs/x_db_type/rules_and_more/mysql/app/models/base/Pristine.php b/tests/specs/x_db_type/rules_and_more/mysql/app/models/base/Pristine.php index 87c54d6c..891a4ef9 100644 --- a/tests/specs/x_db_type/rules_and_more/mysql/app/models/base/Pristine.php +++ b/tests/specs/x_db_type/rules_and_more/mysql/app/models/base/Pristine.php @@ -30,7 +30,6 @@ public function rules() { return [ 'trim' => [['name', 'tag', 'new_col', 'col_9', 'col_10', 'col_11'], 'trim'], - 'required' => [['custom_id_col', 'name'], 'required'], 'custom_id_col_integer' => [['custom_id_col'], 'integer'], 'name_string' => [['name'], 'string'], 'tag_string' => [['tag'], 'string'], @@ -45,6 +44,7 @@ public function rules() 'price_double' => [['price'], 'double'], 'price_default' => [['price'], 'default', 'value' => 0], 'safe' => [['col_8'], 'safe'], + 'required' => [['custom_id_col', 'name'], 'required'], ]; } } diff --git a/tests/specs/x_db_type/rules_and_more/pgsql/app/models/pgsqlmodel/base/Alldbdatatype.php b/tests/specs/x_db_type/rules_and_more/pgsql/app/models/pgsqlmodel/base/Alldbdatatype.php index 5311af96..74c9dc17 100644 --- a/tests/specs/x_db_type/rules_and_more/pgsql/app/models/pgsqlmodel/base/Alldbdatatype.php +++ b/tests/specs/x_db_type/rules_and_more/pgsql/app/models/pgsqlmodel/base/Alldbdatatype.php @@ -112,7 +112,6 @@ public function rules() { return [ 'trim' => [['string_col', 'varchar_col', 'text_col', 'varchar_4_col', 'varchar_5_col', 'char_4_col', 'char_5_col', 'char_6_col', 'char_7_col', 'char_8_col', 'date_col', 'time_col', 'time_col_2', 'time_col_3', 'time_col_4', 'timetz_col', 'timetz_col_2', 'timestamp_col', 'timestamp_col_2', 'timestamp_col_3', 'timestamp_col_4', 'timestamptz_col', 'timestamptz_col_2', 'date2', 'timestamp_col_z', 'box_col', 'character_col', 'character_n', 'character_varying', 'character_varying_n', 'text_def', 'cidr_col', 'circle_col', 'date_col_z', 'inet_col', 'interval_col', 'interval_col_2', 'interval_col_3', 'line_col', 'lseg_col', 'macaddr_col', 'money_col', 'path_col', 'point_col', 'polygon_col', 'tsquery_col', 'tsvector_col', 'txid_snapshot_col', 'uuid_col', 'xml_col'], 'trim'], - 'required' => [['char_6_col', 'char_7_col', 'smallserial_col', 'serial2_col', 'bigserial_col', 'bigserial_col_2', 'serial_col', 'serial4_col'], 'required'], 'string_col_string' => [['string_col'], 'string'], 'varchar_col_string' => [['varchar_col'], 'string'], 'text_col_string' => [['text_col'], 'string'], @@ -209,6 +208,7 @@ public function rules() 'uuid_col_string' => [['uuid_col'], 'string'], 'xml_col_string' => [['xml_col'], 'string'], 'safe' => [['text_col_array', 'bytea_col_2', 'json_col', 'jsonb_col', 'json_col_def', 'json_col_def_2', 'bytea_def', 'json_def', 'jsonb_def'], 'safe'], + 'required' => [['char_6_col', 'char_7_col', 'smallserial_col', 'serial2_col', 'bigserial_col', 'bigserial_col_2', 'serial_col', 'serial4_col'], 'required'], ]; } } diff --git a/tests/specs/x_db_type/rules_and_more/pgsql/app/models/pgsqlmodel/base/Editcolumn.php b/tests/specs/x_db_type/rules_and_more/pgsql/app/models/pgsqlmodel/base/Editcolumn.php index 730bff5a..94500d7c 100644 --- a/tests/specs/x_db_type/rules_and_more/pgsql/app/models/pgsqlmodel/base/Editcolumn.php +++ b/tests/specs/x_db_type/rules_and_more/pgsql/app/models/pgsqlmodel/base/Editcolumn.php @@ -31,7 +31,6 @@ public function rules() { return [ 'trim' => [['name', 'tag', 'first_name', 'string_col', 'str_col_def', 'json_col'], 'trim'], - 'required' => [['name', 'str_col_def', 'json_col', 'json_col_2'], 'required'], 'name_string' => [['name'], 'string', 'max' => 254], 'name_default' => [['name'], 'default', 'value' => 'Horse-2'], 'tag_string' => [['tag'], 'string'], @@ -47,6 +46,7 @@ public function rules() 'json_col_def_n_default' => [['json_col_def_n'], 'default', 'value' => []], 'json_col_def_n_2_default' => [['json_col_def_n_2'], 'default', 'value' => []], 'safe' => [['json_col_2', 'json_col_def_n', 'json_col_def_n_2', 'text_col_array'], 'safe'], + 'required' => [['name', 'str_col_def', 'json_col', 'json_col_2'], 'required'], ]; } } diff --git a/tests/specs/x_db_type/rules_and_more/pgsql/app/models/pgsqlmodel/base/Newcolumn.php b/tests/specs/x_db_type/rules_and_more/pgsql/app/models/pgsqlmodel/base/Newcolumn.php index 09b54731..35cf841e 100644 --- a/tests/specs/x_db_type/rules_and_more/pgsql/app/models/pgsqlmodel/base/Newcolumn.php +++ b/tests/specs/x_db_type/rules_and_more/pgsql/app/models/pgsqlmodel/base/Newcolumn.php @@ -29,7 +29,6 @@ public function rules() { return [ 'trim' => [['name', 'first_name', 'last_name', 'varchar_col'], 'trim'], - 'required' => [['name'], 'required'], 'name_string' => [['name'], 'string'], 'first_name_string' => [['first_name'], 'string'], 'last_name_string' => [['last_name'], 'string'], @@ -39,6 +38,7 @@ public function rules() 'json_col_def_n_default' => [['json_col_def_n'], 'default', 'value' => []], 'json_col_def_n_2_default' => [['json_col_def_n_2'], 'default', 'value' => []], 'safe' => [['json_col', 'json_col_def_n', 'json_col_def_n_2', 'text_col_array'], 'safe'], + 'required' => [['name'], 'required'], ]; } } diff --git a/tests/specs/x_db_type/rules_and_more/pgsql/app/models/pgsqlmodel/base/Pristine.php b/tests/specs/x_db_type/rules_and_more/pgsql/app/models/pgsqlmodel/base/Pristine.php index c24d65b9..430adcec 100644 --- a/tests/specs/x_db_type/rules_and_more/pgsql/app/models/pgsqlmodel/base/Pristine.php +++ b/tests/specs/x_db_type/rules_and_more/pgsql/app/models/pgsqlmodel/base/Pristine.php @@ -30,7 +30,6 @@ public function rules() { return [ 'trim' => [['name', 'tag', 'new_col', 'col_9', 'col_10', 'col_11'], 'trim'], - 'required' => [['custom_id_col', 'name'], 'required'], 'custom_id_col_integer' => [['custom_id_col'], 'integer'], 'name_string' => [['name'], 'string'], 'tag_string' => [['tag'], 'string'], @@ -45,6 +44,7 @@ public function rules() 'price_double' => [['price'], 'double'], 'price_default' => [['price'], 'default', 'value' => 0], 'safe' => [['col_8'], 'safe'], + 'required' => [['custom_id_col', 'name'], 'required'], ]; } } diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index b6c7abdb..eeeeffad 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -360,4 +360,18 @@ public function test158BugGiiapiGeneratedRulesEnumWithTrim() ]); $this->checkFiles($actualFiles, $expectedFiles); } + + // https://github.com/php-openapi/yii2-openapi/issues/22 + public function test22BugRulesRequiredIsGeneratedBeforeDefault() + { + $testFile = Yii::getAlias("@specs/issue_fix/22_bug_rules_required_is_generated_before_default/index.php"); + $this->runGenerator($testFile); + // $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ + // 'recursive' => true, + // ]); + // $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/22_bug_rules_required_is_generated_before_default/mysql"), [ + // 'recursive' => true, + // ]); + // $this->checkFiles($actualFiles, $expectedFiles); + } } From 1beb4d67e30375c09d47b27c0d28e226bb6317df Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Sun, 18 Aug 2024 19:41:54 +0530 Subject: [PATCH 145/358] Complete test --- TODO.taskpaper | 2 +- tests/DbTestCase.php | 1 - .../m200000_000000_create_table_accounts.php | 22 +++ .../mysql/models/Account.php | 10 ++ .../mysql/models/AccountFaker.php | 43 ++++++ .../mysql/models/BaseModelFaker.php | 144 ++++++++++++++++++ .../mysql/models/base/Account.php | 32 ++++ tests/unit/IssueFixTest.php | 14 +- 8 files changed, 259 insertions(+), 9 deletions(-) create mode 100644 tests/specs/issue_fix/22_bug_rules_required_is_generated_before_default/mysql/migrations_mysql_db/m200000_000000_create_table_accounts.php create mode 100644 tests/specs/issue_fix/22_bug_rules_required_is_generated_before_default/mysql/models/Account.php create mode 100644 tests/specs/issue_fix/22_bug_rules_required_is_generated_before_default/mysql/models/AccountFaker.php create mode 100644 tests/specs/issue_fix/22_bug_rules_required_is_generated_before_default/mysql/models/BaseModelFaker.php create mode 100644 tests/specs/issue_fix/22_bug_rules_required_is_generated_before_default/mysql/models/base/Account.php diff --git a/TODO.taskpaper b/TODO.taskpaper index 6fc7c133..54e63549 100644 --- a/TODO.taskpaper +++ b/TODO.taskpaper @@ -3,7 +3,7 @@ TODO.taskpaper ### Bug: rules() "required" is generated before "*_default" #22 ✔ create failing test @done (24-08-18 19:21) ✔ implement the solution @done (24-08-18 19:21) - ☐ fix failing tests if any + ✔ fix failing tests if any @done (24-08-18 19:39) ☐ resolve TODOs if any ☐ review PR ☐ delete this file and submit PR diff --git a/tests/DbTestCase.php b/tests/DbTestCase.php index c28a314c..d3e466aa 100644 --- a/tests/DbTestCase.php +++ b/tests/DbTestCase.php @@ -101,7 +101,6 @@ protected function compareFiles(array $actual, string $testFile) foreach ($actual as $file) { $expectedFile = str_replace('@app', substr($testFile, 0, -4), $file); $actualFile = str_replace('@app', Yii::getAlias('@app'), $file); - // exec('cp '.$actualFile.' '.$expectedFile); $this->checkFiles([$actualFile], [$expectedFile]); } } diff --git a/tests/specs/issue_fix/22_bug_rules_required_is_generated_before_default/mysql/migrations_mysql_db/m200000_000000_create_table_accounts.php b/tests/specs/issue_fix/22_bug_rules_required_is_generated_before_default/mysql/migrations_mysql_db/m200000_000000_create_table_accounts.php new file mode 100644 index 00000000..e59c2946 --- /dev/null +++ b/tests/specs/issue_fix/22_bug_rules_required_is_generated_before_default/mysql/migrations_mysql_db/m200000_000000_create_table_accounts.php @@ -0,0 +1,22 @@ +createTable('{{%accounts}}', [ + 'id' => $this->primaryKey(), + 'name' => $this->string(128)->notNull(), + 'paymentMethodName' => $this->text()->null(), + 'verified' => $this->boolean()->notNull()->defaultValue(false), + ]); + } + + public function down() + { + $this->dropTable('{{%accounts}}'); + } +} diff --git a/tests/specs/issue_fix/22_bug_rules_required_is_generated_before_default/mysql/models/Account.php b/tests/specs/issue_fix/22_bug_rules_required_is_generated_before_default/mysql/models/Account.php new file mode 100644 index 00000000..2d25d7fc --- /dev/null +++ b/tests/specs/issue_fix/22_bug_rules_required_is_generated_before_default/mysql/models/Account.php @@ -0,0 +1,10 @@ +generateModels(['author_id' => 1]); + * $model = (new PostFaker())->generateModels(function($model, $faker, $uniqueFaker) { + * $model->scenario = 'create'; + * $model->author_id = 1; + * return $model; + * }); + **/ + public function generateModel($attributes = []) + { + $faker = $this->faker; + $uniqueFaker = $this->uniqueFaker; + $model = new Account(); + //$model->id = $uniqueFaker->numberBetween(0, 1000000); + $model->name = substr($faker->text(128), 0, 128); + $model->paymentMethodName = $faker->sentence; + $model->verified = $faker->boolean; + if (!is_callable($attributes)) { + $model->setAttributes($attributes, false); + } else { + $model = $attributes($model, $faker, $uniqueFaker); + } + return $model; + } +} diff --git a/tests/specs/issue_fix/22_bug_rules_required_is_generated_before_default/mysql/models/BaseModelFaker.php b/tests/specs/issue_fix/22_bug_rules_required_is_generated_before_default/mysql/models/BaseModelFaker.php new file mode 100644 index 00000000..c367fbb4 --- /dev/null +++ b/tests/specs/issue_fix/22_bug_rules_required_is_generated_before_default/mysql/models/BaseModelFaker.php @@ -0,0 +1,144 @@ +faker = FakerFactory::create(str_replace('-', '_', \Yii::$app->language)); + $this->uniqueFaker = new UniqueGenerator($this->faker); + } + + abstract public function generateModel($attributes = []); + + public function getFaker():Generator + { + return $this->faker; + } + + public function getUniqueFaker():UniqueGenerator + { + return $this->uniqueFaker; + } + + public function setFaker(Generator $faker):void + { + $this->faker = $faker; + } + + public function setUniqueFaker(UniqueGenerator $faker):void + { + $this->uniqueFaker = $faker; + } + + /** + * Generate and return model + * @param array|callable $attributes + * @param UniqueGenerator|null $uniqueFaker + * @return \yii\db\ActiveRecord + * @example MyFaker::makeOne(['user_id' => 1, 'title' => 'foo']); + * @example MyFaker::makeOne( function($model, $faker) { + * $model->scenario = 'create'; + * $model->setAttributes(['user_id' => 1, 'title' => $faker->sentence]); + * return $model; + * }); + */ + public static function makeOne($attributes = [], ?UniqueGenerator $uniqueFaker = null) + { + $fakeBuilder = new static(); + if ($uniqueFaker !== null) { + $fakeBuilder->setUniqueFaker($uniqueFaker); + } + $model = $fakeBuilder->generateModel($attributes); + return $model; + } + + /** + * Generate, save and return model + * @param array|callable $attributes + * @param UniqueGenerator|null $uniqueFaker + * @return \yii\db\ActiveRecord + * @example MyFaker::saveOne(['user_id' => 1, 'title' => 'foo']); + * @example MyFaker::saveOne( function($model, $faker) { + * $model->scenario = 'create'; + * $model->setAttributes(['user_id' => 1, 'title' => $faker->sentence]); + * return $model; + * }); + */ + public static function saveOne($attributes = [], ?UniqueGenerator $uniqueFaker = null) + { + $model = static::makeOne($attributes, $uniqueFaker); + $model->save(); + return $model; + } + + /** + * Generate and return multiple models + * @param int $number + * @param array|callable $commonAttributes + * @return \yii\db\ActiveRecord[]|array + * @example TaskFaker::make(5, ['project_id'=>1, 'user_id' => 2]); + * @example TaskFaker::make(5, function($model, $faker, $uniqueFaker) { + * $model->setAttributes(['name' => $uniqueFaker->username, 'state'=>$faker->boolean(20)]); + * return $model; + * }); + */ + public static function make(int $number, $commonAttributes = [], ?UniqueGenerator $uniqueFaker = null):array + { + if ($number < 1) { + return []; + } + $fakeBuilder = new static(); + if ($uniqueFaker !== null) { + $fakeBuilder->setUniqueFaker($uniqueFaker); + } + return array_map(function () use ($commonAttributes, $fakeBuilder) { + $model = $fakeBuilder->generateModel($commonAttributes); + return $model; + }, range(0, $number -1)); + } + + /** + * Generate, save and return multiple models + * @param int $number + * @param array|callable $commonAttributes + * @return \yii\db\ActiveRecord[]|array + * @example TaskFaker::save(5, ['project_id'=>1, 'user_id' => 2]); + * @example TaskFaker::save(5, function($model, $faker, $uniqueFaker) { + * $model->setAttributes(['name' => $uniqueFaker->username, 'state'=>$faker->boolean(20)]); + * return $model; + * }); + */ + public static function save(int $number, $commonAttributes = [], ?UniqueGenerator $uniqueFaker = null):array + { + if ($number < 1) { + return []; + } + $fakeBuilder = new static(); + if ($uniqueFaker !== null) { + $fakeBuilder->setUniqueFaker($uniqueFaker); + } + return array_map(function () use ($commonAttributes, $fakeBuilder) { + $model = $fakeBuilder->generateModel($commonAttributes); + $model->save(); + return $model; + }, range(0, $number -1)); + } +} diff --git a/tests/specs/issue_fix/22_bug_rules_required_is_generated_before_default/mysql/models/base/Account.php b/tests/specs/issue_fix/22_bug_rules_required_is_generated_before_default/mysql/models/base/Account.php new file mode 100644 index 00000000..96b515cf --- /dev/null +++ b/tests/specs/issue_fix/22_bug_rules_required_is_generated_before_default/mysql/models/base/Account.php @@ -0,0 +1,32 @@ + [['name', 'paymentMethodName'], 'trim'], + 'name_string' => [['name'], 'string', 'max' => 128], + 'paymentMethodName_string' => [['paymentMethodName'], 'string'], + 'verified_boolean' => [['verified'], 'boolean'], + 'verified_default' => [['verified'], 'default', 'value' => false], + 'required' => [['name', 'verified'], 'required'], + ]; + } +} diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index eeeeffad..30968b32 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -366,12 +366,12 @@ public function test22BugRulesRequiredIsGeneratedBeforeDefault() { $testFile = Yii::getAlias("@specs/issue_fix/22_bug_rules_required_is_generated_before_default/index.php"); $this->runGenerator($testFile); - // $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ - // 'recursive' => true, - // ]); - // $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/22_bug_rules_required_is_generated_before_default/mysql"), [ - // 'recursive' => true, - // ]); - // $this->checkFiles($actualFiles, $expectedFiles); + $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ + 'recursive' => true, + ]); + $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/22_bug_rules_required_is_generated_before_default/mysql"), [ + 'recursive' => true, + ]); + $this->checkFiles($actualFiles, $expectedFiles); } } From 99e51928a881be53e20ed1c423b399233b86f77a Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Sun, 18 Aug 2024 19:44:10 +0530 Subject: [PATCH 146/358] Delete TODO.taskpaper file --- TODO.taskpaper | 9 --------- 1 file changed, 9 deletions(-) delete mode 100644 TODO.taskpaper diff --git a/TODO.taskpaper b/TODO.taskpaper deleted file mode 100644 index 54e63549..00000000 --- a/TODO.taskpaper +++ /dev/null @@ -1,9 +0,0 @@ -TODO.taskpaper - -### Bug: rules() "required" is generated before "*_default" #22 - ✔ create failing test @done (24-08-18 19:21) - ✔ implement the solution @done (24-08-18 19:21) - ✔ fix failing tests if any @done (24-08-18 19:39) - ☐ resolve TODOs if any - ☐ review PR - ☐ delete this file and submit PR From 03a68bf261a15c936b463e46bd50d027a5e6fd23 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Sun, 18 Aug 2024 20:00:15 +0530 Subject: [PATCH 147/358] Initial commit to create PR --- TODO.taskpaper | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 TODO.taskpaper diff --git a/TODO.taskpaper b/TODO.taskpaper new file mode 100644 index 00000000..07c175cc --- /dev/null +++ b/TODO.taskpaper @@ -0,0 +1,9 @@ +TODO.taskpaper + +### Generate inverse relations #25 + ☐ create failing test + ☐ implement the solution + ☐ fix failing tests if any + ☐ resolve TODOs if any + ☐ review PR + ☐ delete this file and submit PR From 59be8e59224f4a5bb656d63901e2045cee88b470 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Sun, 18 Aug 2024 20:13:41 +0530 Subject: [PATCH 148/358] Cleanup --- src/lib/SchemaToDatabase.php | 47 +++++++++++++++++++----------------- 1 file changed, 25 insertions(+), 22 deletions(-) diff --git a/src/lib/SchemaToDatabase.php b/src/lib/SchemaToDatabase.php index 0e93ff29..8217513d 100644 --- a/src/lib/SchemaToDatabase.php +++ b/src/lib/SchemaToDatabase.php @@ -7,10 +7,16 @@ namespace cebe\yii2openapi\lib; +use cebe\openapi\exceptions\IOException; +use cebe\openapi\exceptions\TypeErrorException; +use cebe\openapi\exceptions\UnresolvableReferenceException; +use cebe\yii2openapi\lib\exceptions\InvalidDefinitionException; +use cebe\yii2openapi\lib\items\DbModel; use cebe\yii2openapi\lib\items\JunctionSchemas; use cebe\yii2openapi\lib\openapi\ComponentSchema; use Yii; use yii\base\Exception; +use yii\base\InvalidConfigException; use yii\helpers\StringHelper; use function count; @@ -55,10 +61,7 @@ */ class SchemaToDatabase { - /** - * @var \cebe\yii2openapi\lib\Config - */ - protected $config; + protected Config $config; public function __construct(Config $config) { @@ -66,15 +69,15 @@ public function __construct(Config $config) } /** - * @return array|\cebe\yii2openapi\lib\items\DbModel[] - * @throws \cebe\openapi\exceptions\IOException - * @throws \cebe\openapi\exceptions\TypeErrorException - * @throws \cebe\openapi\exceptions\UnresolvableReferenceException - * @throws \cebe\yii2openapi\lib\exceptions\InvalidDefinitionException - * @throws \yii\base\Exception - * @throws \yii\base\InvalidConfigException + * @return array|DbModel[] + * @throws IOException + * @throws TypeErrorException + * @throws UnresolvableReferenceException + * @throws InvalidDefinitionException + * @throws Exception + * @throws InvalidConfigException */ - public function prepareModels():array + public function prepareModels(): array { $models = []; $openApi = $this->config->getOpenApi(); @@ -88,11 +91,11 @@ public function prepareModels():array if ($junctions->isJunctionSchema($schemaName)) { $schemaName = $junctions->trimPrefix($schemaName); } - /**@var \cebe\yii2openapi\lib\AttributeResolver $resolver */ + /**@var AttributeResolver $resolver */ $resolver = Yii::createObject(AttributeResolver::class, [$schemaName, $schema, $junctions, $this->config]); $models[$schemaName] = $resolver->resolve(); } - foreach ($models as $model) { + foreach ($models as $model) { foreach ($model->many2many as $relation) { if (isset($models[$relation->viaModelName])) { $relation->hasViaModel = true; @@ -108,14 +111,14 @@ public function prepareModels():array } /** - * @return \cebe\yii2openapi\lib\items\JunctionSchemas - * @throws \cebe\openapi\exceptions\IOException - * @throws \cebe\openapi\exceptions\TypeErrorException - * @throws \cebe\openapi\exceptions\UnresolvableReferenceException - * @throws \yii\base\Exception - * @throws \yii\base\InvalidConfigException + * @return JunctionSchemas + * @throws IOException + * @throws TypeErrorException + * @throws UnresolvableReferenceException + * @throws Exception + * @throws InvalidConfigException|InvalidDefinitionException */ - public function findJunctionSchemas():JunctionSchemas + public function findJunctionSchemas(): JunctionSchemas { $junctions = []; $openApi = $this->config->getOpenApi(); @@ -195,7 +198,7 @@ public function findJunctionSchemas():JunctionSchemas return Yii::createObject(JunctionSchemas::class, [$junctions]); } - private function canGenerateModel(string $schemaName, ComponentSchema $schema):bool + private function canGenerateModel(string $schemaName, ComponentSchema $schema): bool { // only generate tables for schemas of type object and those who have defined properties if ($schema->isObjectSchema() && !$schema->hasProperties()) { From a0de22f37ac693e97bfab5abeab63dfe8c731b0f Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Sun, 18 Aug 2024 20:29:34 +0530 Subject: [PATCH 149/358] Cleanup and add test OpenAPI spec --- src/lib/AttributeResolver.php | 177 ++++++++---------- .../25_generate_inverse_relations/index.php | 14 ++ .../25_generate_inverse_relations/index.yaml | 83 ++++++++ tests/unit/IssueFixTest.php | 15 ++ 4 files changed, 193 insertions(+), 96 deletions(-) create mode 100644 tests/specs/issue_fix/25_generate_inverse_relations/index.php create mode 100644 tests/specs/issue_fix/25_generate_inverse_relations/index.yaml diff --git a/src/lib/AttributeResolver.php b/src/lib/AttributeResolver.php index 0063d8df..d4340d20 100644 --- a/src/lib/AttributeResolver.php +++ b/src/lib/AttributeResolver.php @@ -7,8 +7,6 @@ namespace cebe\yii2openapi\lib; -use cebe\yii2openapi\lib\Config; -use cebe\yii2openapi\lib\CustomSpecAttr; use cebe\yii2openapi\lib\exceptions\InvalidDefinitionException; use cebe\yii2openapi\lib\items\Attribute; use cebe\yii2openapi\lib\items\AttributeRelation; @@ -20,9 +18,9 @@ use cebe\yii2openapi\lib\openapi\ComponentSchema; use cebe\yii2openapi\lib\openapi\PropertySchema; use Yii; +use yii\base\InvalidConfigException; use yii\helpers\Inflector; use yii\helpers\StringHelper; -use yii\helpers\VarDumper; use function explode; use function strpos; use function strtolower; @@ -32,49 +30,34 @@ class AttributeResolver /** * @var Attribute[]|array */ - private $attributes = []; + private array $attributes = []; /** * @var AttributeRelation[]|array */ - private $relations = []; + private array $relations = []; /** * @var NonDbRelation[]|array */ - private $nonDbRelations = []; + private array $nonDbRelations = []; /** * @var ManyToManyRelation[]|array */ - private $many2many = []; + private array $many2many = []; - /** - * @var string - */ - private $schemaName; + private string $schemaName; - /** - * @var string - */ - private $tableName; + private string $tableName; - /** - * @var ComponentSchema - */ - private $schema; + private ComponentSchema $schema; - /** - * @var \cebe\yii2openapi\lib\items\JunctionSchemas - */ - private $junctions; + private JunctionSchemas $junctions; - /** @var bool */ - private $isJunctionSchema; + private bool $isJunctionSchema; - /** @var bool */ - private $hasMany2Many; + private bool $hasMany2Many; - /** @var Config */ - private $config; + private ?Config $config; public function __construct(string $schemaName, ComponentSchema $schema, JunctionSchemas $junctions, ?Config $config = null) { @@ -88,14 +71,14 @@ public function __construct(string $schemaName, ComponentSchema $schema, Junctio } /** - * @return \cebe\yii2openapi\lib\items\DbModel - * @throws \cebe\yii2openapi\lib\exceptions\InvalidDefinitionException - * @throws \yii\base\InvalidConfigException + * @return DbModel + * @throws InvalidDefinitionException + * @throws InvalidConfigException */ - public function resolve():DbModel + public function resolve(): DbModel { foreach ($this->schema->getProperties() as $property) { - /** @var $property \cebe\yii2openapi\lib\openapi\PropertySchema */ + /** @var $property PropertySchema */ $isRequired = $this->schema->isRequiredProperty($property->getName()); $nullableValue = $property->getProperty()->getSerializableData()->nullable ?? null; @@ -130,24 +113,24 @@ public function resolve():DbModel } /** - * @param \cebe\yii2openapi\lib\openapi\PropertySchema $property - * @param bool $isRequired - * @throws \cebe\yii2openapi\lib\exceptions\InvalidDefinitionException - * @throws \yii\base\InvalidConfigException + * @param PropertySchema $property + * @param bool $isRequired + * @throws InvalidDefinitionException + * @throws InvalidConfigException */ - protected function resolveJunctionTableProperty(PropertySchema $property, bool $isRequired):void + protected function resolveJunctionTableProperty(PropertySchema $property, bool $isRequired): void { if ($this->junctions->isJunctionProperty($this->schemaName, $property->getName())) { $junkAttribute = $this->junctions->byJunctionSchema($this->schemaName)[$property->getName()]; $attribute = Yii::createObject(Attribute::class, [$property->getName()]); $attribute->setRequired($isRequired) - ->setDescription($property->getAttr('description', '')) - ->setReadOnly($property->isReadonly()) - ->setIsPrimary($property->isPrimaryKey()) - ->asReference($junkAttribute['relatedClassName']) - ->setPhpType($junkAttribute['phpType']) - ->setDbType($junkAttribute['dbType']) - ->setForeignKeyColumnName($property->fkColName); + ->setDescription($property->getAttr('description', '')) + ->setReadOnly($property->isReadonly()) + ->setIsPrimary($property->isPrimaryKey()) + ->asReference($junkAttribute['relatedClassName']) + ->setPhpType($junkAttribute['phpType']) + ->setDbType($junkAttribute['dbType']) + ->setForeignKeyColumnName($property->fkColName); $relation = Yii::createObject(AttributeRelation::class, [ $property->getName(), $junkAttribute['relatedTableName'], @@ -162,12 +145,12 @@ protected function resolveJunctionTableProperty(PropertySchema $property, bool $ } /** - * @param \cebe\yii2openapi\lib\openapi\PropertySchema $property - * @param bool $isRequired - * @throws \cebe\yii2openapi\lib\exceptions\InvalidDefinitionException - * @throws \yii\base\InvalidConfigException + * @param PropertySchema $property + * @param bool $isRequired + * @throws InvalidDefinitionException + * @throws InvalidConfigException */ - protected function resolveHasMany2ManyTableProperty(PropertySchema $property, bool $isRequired):void + protected function resolveHasMany2ManyTableProperty(PropertySchema $property, bool $isRequired): void { if ($this->junctions->isManyToManyProperty($this->schemaName, $property->getName())) { return; @@ -197,7 +180,7 @@ protected function resolveHasMany2ManyTableProperty(PropertySchema $property, bo $this->relations[Inflector::pluralize($junkRef)] = Yii::createObject(AttributeRelation::class, [$junkRef, $junkAttribute['junctionTable'], $viaModel]) - ->asHasMany([$junkAttribute['pairProperty'] . '_id' => $this->schema->getPkName()]); + ->asHasMany([$junkAttribute['pairProperty'] . '_id' => $this->schema->getPkName()]); return; } @@ -205,35 +188,36 @@ protected function resolveHasMany2ManyTableProperty(PropertySchema $property, bo } /** - * @param \cebe\yii2openapi\lib\openapi\PropertySchema $property - * @param bool $isRequired - * @param bool|null|string $nullableValue if string then its value will be only constant `ARG_ABSENT`. Default `null` is avoided because it can be in passed value in method call - * @throws \cebe\yii2openapi\lib\exceptions\InvalidDefinitionException - * @throws \yii\base\InvalidConfigException + * @param PropertySchema $property + * @param bool $isRequired + * @param bool|null|string $nullableValue if string then its value will be only constant `ARG_ABSENT`. Default `null` is avoided because it can be in passed value in method call + * @throws InvalidDefinitionException + * @throws InvalidConfigException */ protected function resolveProperty( PropertySchema $property, bool $isRequired, - $nullableValue = 'ARG_ABSENT' - ):void { + $nullableValue = 'ARG_ABSENT' + ): void + { if ($nullableValue === 'ARG_ABSENT') { $nullableValue = $property->getProperty()->getSerializableData()->nullable ?? null; } $attribute = Yii::createObject(Attribute::class, [$property->getName()]); $attribute->setRequired($isRequired) - ->setDescription($property->getAttr('description', '')) - ->setReadOnly($property->isReadonly()) - ->setDefault($property->guessDefault()) - ->setXDbType($property->getAttr(CustomSpecAttr::DB_TYPE)) - ->setXDbDefaultExpression($property->getAttr(CustomSpecAttr::DB_DEFAULT_EXPRESSION)) - ->setNullable($nullableValue) - ->setIsPrimary($property->isPrimaryKey()) - ->setForeignKeyColumnName($property->fkColName); + ->setDescription($property->getAttr('description', '')) + ->setReadOnly($property->isReadonly()) + ->setDefault($property->guessDefault()) + ->setXDbType($property->getAttr(CustomSpecAttr::DB_TYPE)) + ->setXDbDefaultExpression($property->getAttr(CustomSpecAttr::DB_DEFAULT_EXPRESSION)) + ->setNullable($nullableValue) + ->setIsPrimary($property->isPrimaryKey()) + ->setForeignKeyColumnName($property->fkColName); if ($property->isReference()) { if ($property->isVirtual()) { throw new InvalidDefinitionException('References not supported for virtual attributes'); } - + if ($property->isNonDbReference()) { $attribute->asNonDbReference($property->getRefClassName()); $relation = Yii::createObject( @@ -258,17 +242,17 @@ protected function resolveProperty( [$min, $max] = $fkProperty->guessMinMax(); $attribute->asReference($relatedClassName); $attribute->setPhpType($fkProperty->guessPhpType()) - ->setDbType($fkProperty->guessDbType(true)) - ->setSize($fkProperty->getMaxLength()) - ->setDescription($property->getRefSchema()->getDescription()) - ->setDefault($fkProperty->guessDefault()) - ->setLimits($min, $max, $fkProperty->getMinLength()); + ->setDbType($fkProperty->guessDbType(true)) + ->setSize($fkProperty->getMaxLength()) + ->setDescription($property->getRefSchema()->getDescription()) + ->setDefault($fkProperty->guessDefault()) + ->setLimits($min, $max, $fkProperty->getMinLength()); $relation = Yii::createObject( AttributeRelation::class, [$property->getName(), $relatedTableName, $relatedClassName] ) - ->asHasOne([$fkProperty->getName() => $attribute->columnName]); + ->asHasOne([$fkProperty->getName() => $attribute->columnName]); $relation->onUpdateFkConstraint = $property->onUpdateFkConstraint; $relation->onDeleteFkConstraint = $property->onDeleteFkConstraint; if ($property->isRefPointerToSelf()) { @@ -279,10 +263,10 @@ protected function resolveProperty( if (!$property->isReference() && !$property->hasRefItems()) { [$min, $max] = $property->guessMinMax(); $attribute->setIsVirtual($property->isVirtual()) - ->setPhpType($property->guessPhpType()) - ->setDbType($property->guessDbType()) - ->setSize($property->getMaxLength()) - ->setLimits($min, $max, $property->getMinLength()); + ->setPhpType($property->guessPhpType()) + ->setDbType($property->guessDbType()) + ->setSize($property->getMaxLength()) + ->setLimits($min, $max, $property->getMinLength()); if ($property->hasEnum()) { $attribute->setEnumValues($property->getAttr('enum')); } @@ -319,7 +303,7 @@ protected function resolveProperty( AttributeRelation::class, [$property->getName(), $relatedTableName, $relatedClassName] ) - ->asHasMany([$fkProperty->getName() => $fkProperty->getName()])->asSelfReference(); + ->asHasMany([$fkProperty->getName() => $fkProperty->getName()])->asSelfReference(); return; } $foreignPk = Inflector::camel2id($fkProperty->getName(), '_') . '_id'; @@ -328,7 +312,7 @@ protected function resolveProperty( AttributeRelation::class, [$property->getName(), $relatedTableName, $relatedClassName] ) - ->asHasMany([$foreignPk => $this->schema->getPkName()]); + ->asHasMany([$foreignPk => $this->schema->getPkName()]); return; } $relatedClassName = $property->getRefClassName(); @@ -347,7 +331,7 @@ protected function resolveProperty( AttributeRelation::class, [$property->getName(), $relatedTableName, $relatedClassName] ) - ->asHasMany([Inflector::camel2id($this->schemaName, '_') . '_id' => $this->schema->getPkName()]); + ->asHasMany([Inflector::camel2id($this->schemaName, '_') . '_id' => $this->schema->getPkName()]); return; } if ($this->schema->isNonDb() && $attribute->isReference()) { @@ -367,14 +351,15 @@ protected function resolveProperty( * @param string $relatedTableName * @param ComponentSchema $refSchema * @return bool - * @throws \yii\base\InvalidConfigException + * @throws InvalidConfigException|InvalidDefinitionException */ protected function catchManyToMany( string $propertyName, string $relatedSchemaName, string $relatedTableName, ComponentSchema $refSchema - ):bool { + ): bool + { if (strtolower(Inflector::id2camel($propertyName, '_')) !== strtolower(Inflector::pluralize($relatedSchemaName))) { return false; @@ -406,9 +391,9 @@ protected function catchManyToMany( } /** - * @throws \yii\base\InvalidConfigException + * @throws InvalidConfigException */ - protected function guessFakerStub(Attribute $attribute, PropertySchema $property):?string + protected function guessFakerStub(Attribute $attribute, PropertySchema $property): ?string { $resolver = Yii::createObject(['class' => FakerStubResolver::class], [$attribute, $property, $this->config]); return $resolver->resolve(); @@ -417,9 +402,9 @@ protected function guessFakerStub(Attribute $attribute, PropertySchema $property /** * @param array $indexes * @return array|DbIndex[] - * @throws \cebe\yii2openapi\lib\exceptions\InvalidDefinitionException + * @throws InvalidDefinitionException */ - protected function prepareIndexes(array $indexes):array + protected function prepareIndexes(array $indexes): array { $dbIndexes = []; foreach ($indexes as $index) { @@ -470,12 +455,12 @@ protected function prepareIndexes(array $indexes):array } /** - * @param \cebe\yii2openapi\lib\openapi\PropertySchema $property - * @param \cebe\yii2openapi\lib\items\Attribute $attribute + * @param PropertySchema $property + * @param Attribute $attribute * @return void - * @throws \yii\base\InvalidConfigException + * @throws InvalidConfigException|InvalidDefinitionException */ - protected function resolvePropertyRef(PropertySchema $property, Attribute $attribute):void + protected function resolvePropertyRef(PropertySchema $property, Attribute $attribute): void { $fkProperty = new PropertySchema( $property->getRefSchema()->getSchema(), @@ -484,11 +469,11 @@ protected function resolvePropertyRef(PropertySchema $property, Attribute $attri ); [$min, $max] = $fkProperty->guessMinMax(); $attribute->setPhpType($fkProperty->guessPhpType()) - ->setDbType($fkProperty->guessDbType(true)) - ->setSize($fkProperty->getMaxLength()) - ->setDescription($fkProperty->getAttr('description')) - ->setDefault($fkProperty->guessDefault()) - ->setLimits($min, $max, $fkProperty->getMinLength()); + ->setDbType($fkProperty->guessDbType(true)) + ->setSize($fkProperty->getMaxLength()) + ->setDescription($fkProperty->getAttr('description')) + ->setDefault($fkProperty->guessDefault()) + ->setLimits($min, $max, $fkProperty->getMinLength()); $this->attributes[$property->getName()] = $attribute->setFakerStub($this->guessFakerStub($attribute, $fkProperty)); } diff --git a/tests/specs/issue_fix/25_generate_inverse_relations/index.php b/tests/specs/issue_fix/25_generate_inverse_relations/index.php new file mode 100644 index 00000000..535787af --- /dev/null +++ b/tests/specs/issue_fix/25_generate_inverse_relations/index.php @@ -0,0 +1,14 @@ + '@specs/issue_fix/25_generate_inverse_relations/index.yaml', + 'generateUrls' => false, + 'generateModels' => true, + 'excludeModels' => [ + 'Error', + ], + 'generateControllers' => false, + 'generateMigrations' => true, + 'generateModelFaker' => true, // `generateModels` must be `true` in order to use `generateModelFaker` as `true` +]; + diff --git a/tests/specs/issue_fix/25_generate_inverse_relations/index.yaml b/tests/specs/issue_fix/25_generate_inverse_relations/index.yaml new file mode 100644 index 00000000..7a780944 --- /dev/null +++ b/tests/specs/issue_fix/25_generate_inverse_relations/index.yaml @@ -0,0 +1,83 @@ + +openapi: 3.0.3 + +info: + title: 'Generate inverse relations #25' + version: 1.0.0 + +components: + schemas: + User: + type: object + required: + - id + - name + properties: + id: + type: integer + readOnly: true + name: + type: string + maxLength: 128 + + Account: + description: Account + type: object + required: + - id + - name + properties: + id: + type: integer + readOnly: true + name: + description: account name + type: string + maxLength: 128 + paymentMethodName: + type: string + user: + $ref: '#/components/schemas/User' + + Contact: + description: Contact + type: object + required: + - id + - account + properties: + id: + type: integer + readOnly: true + account: + $ref: '#/components/schemas/Account' + active: + type: boolean + default: false + nickname: + type: string + + PaymentMethod: + type: object + description: PaymentMethod + x-indexes: + - 'unique:name' + required: + - id + - name + properties: + id: + type: integer + readOnly: true + name: + type: string + example: Bank transfer within 14 days + maxLength: 150 + x-faker: false + +paths: + '/account': + get: + responses: + '200': + description: Account with id = "\" was not found. diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index b6c7abdb..dd20604a 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -360,4 +360,19 @@ public function test158BugGiiapiGeneratedRulesEnumWithTrim() ]); $this->checkFiles($actualFiles, $expectedFiles); } + + // https://github.com/php-openapi/yii2-openapi/issues/25 + public function test25GenerateInverseRelations() + { + // 25_generate_inverse_relations + $testFile = Yii::getAlias("@specs/issue_fix/25_generate_inverse_relations/index.php"); + $this->runGenerator($testFile); +// $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ +// 'recursive' => true, +// ]); +// $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/25_generate_inverse_relations/mysql"), [ +// 'recursive' => true, +// ]); +// $this->checkFiles($actualFiles, $expectedFiles); + } } From df272319cb49cb09a005ca9be183ae641c9e023e Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Sun, 18 Aug 2024 20:34:32 +0530 Subject: [PATCH 150/358] Cleanup 2 --- .../25_generate_inverse_relations/index.yaml | 36 ------------------- 1 file changed, 36 deletions(-) diff --git a/tests/specs/issue_fix/25_generate_inverse_relations/index.yaml b/tests/specs/issue_fix/25_generate_inverse_relations/index.yaml index 7a780944..f1e9f59e 100644 --- a/tests/specs/issue_fix/25_generate_inverse_relations/index.yaml +++ b/tests/specs/issue_fix/25_generate_inverse_relations/index.yaml @@ -39,42 +39,6 @@ components: user: $ref: '#/components/schemas/User' - Contact: - description: Contact - type: object - required: - - id - - account - properties: - id: - type: integer - readOnly: true - account: - $ref: '#/components/schemas/Account' - active: - type: boolean - default: false - nickname: - type: string - - PaymentMethod: - type: object - description: PaymentMethod - x-indexes: - - 'unique:name' - required: - - id - - name - properties: - id: - type: integer - readOnly: true - name: - type: string - example: Bank transfer within 14 days - maxLength: 150 - x-faker: false - paths: '/account': get: From 489f0f5a251072a1c25e3be5518c61f858dbd996 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Sun, 18 Aug 2024 20:41:07 +0530 Subject: [PATCH 151/358] Fix style --- src/lib/AttributeResolver.php | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/src/lib/AttributeResolver.php b/src/lib/AttributeResolver.php index d4340d20..74ef5e79 100644 --- a/src/lib/AttributeResolver.php +++ b/src/lib/AttributeResolver.php @@ -197,9 +197,8 @@ protected function resolveHasMany2ManyTableProperty(PropertySchema $property, bo protected function resolveProperty( PropertySchema $property, bool $isRequired, - $nullableValue = 'ARG_ABSENT' - ): void - { + $nullableValue = 'ARG_ABSENT' + ): void { if ($nullableValue === 'ARG_ABSENT') { $nullableValue = $property->getProperty()->getSerializableData()->nullable ?? null; } @@ -358,8 +357,7 @@ protected function catchManyToMany( string $relatedSchemaName, string $relatedTableName, ComponentSchema $refSchema - ): bool - { + ): bool { if (strtolower(Inflector::id2camel($propertyName, '_')) !== strtolower(Inflector::pluralize($relatedSchemaName))) { return false; From e25b36c5fd7552e14e19c09aa91cd9373779ddf2 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Tue, 20 Aug 2024 17:04:31 +0530 Subject: [PATCH 152/358] Refactor --- src/lib/items/DbModel.php | 87 ++++++++++++++++++--------------------- 1 file changed, 41 insertions(+), 46 deletions(-) diff --git a/src/lib/items/DbModel.php b/src/lib/items/DbModel.php index 4f174370..ea1c2911 100644 --- a/src/lib/items/DbModel.php +++ b/src/lib/items/DbModel.php @@ -10,9 +10,9 @@ use cebe\yii2openapi\lib\ValidationRulesBuilder; use Yii; use yii\base\BaseObject; +use yii\base\InvalidConfigException; use yii\db\ColumnSchema; use yii\helpers\Inflector; -use yii\helpers\StringHelper; use yii\helpers\VarDumper; use function array_filter; use function array_map; @@ -20,73 +20,68 @@ use const PHP_EOL; /** - * @property-read string $tableAlias - * @property-read array $uniqueColumnsList - * @property-read array[]|array $attributesByType - * @property-read array|\cebe\yii2openapi\lib\items\AttributeRelation[] $hasOneRelations + * @property-read string $tableAlias + * @property-read array $uniqueColumnsList + * @property-read array[]|array $attributesByType + * @property-read array|AttributeRelation[] $hasOneRelations */ class DbModel extends BaseObject { - /** - * @var string primary key attribute name - */ - public $pkName; + // primary key attribute name + public string $pkName; - /** - * @var string model name. - */ - public $name; + // model name + public string $name; - /** - * @var string table name. (without brackets and db prefix) - */ - public $tableName; + // table name. (without brackets and db prefix) + public string $tableName; - /** - * @var string description from the schema. - */ - public $description; + // description from the schema. + public string $description; /** - * @var array|\cebe\yii2openapi\lib\items\Attribute[] model attributes. + * @var array|Attribute[] model attributes. */ - public $attributes = []; + public array $attributes = []; /** - * @var array|\cebe\yii2openapi\lib\items\AttributeRelation[] database relations. + * @var array|AttributeRelation[] database relations. */ - public $relations = []; + public array $relations = []; /*** - * @var array|\cebe\yii2openapi\lib\items\NonDbRelation[] non-db relations + * @var array|NonDbRelation[] non-db relations */ - public $nonDbRelations = []; + public array $nonDbRelations = []; /** - * @var array|\cebe\yii2openapi\lib\items\ManyToManyRelation[] many to many relations. + * @var array|ManyToManyRelation[] many-to-many relations. */ - public $many2many = []; + public array $many2many = []; - public $junctionCols = []; + public array $junctionCols = []; /** - * @var \cebe\yii2openapi\lib\items\DbIndex[]|array + * @var DbIndex[]|array */ - public $indexes = []; + public array $indexes = []; - public $isNotDb = false; + public bool $isNotDb = false; - public function getTableAlias():string + public function getTableAlias(): string { return '{{%' . $this->tableName . '}}'; } - public function getClassName():string + public function getClassName(): string { return Inflector::id2camel($this->name, '_'); } - public function getValidationRules():string + /** + * @throws InvalidConfigException + */ + public function getValidationRules(): string { $rules = Yii::createObject(ValidationRulesBuilder::class, [$this])->build(); $rules = array_map('strval', $rules); @@ -105,9 +100,9 @@ public function getValidationRules():string } /** - * @return \cebe\yii2openapi\lib\items\AttributeRelation[]|array + * @return AttributeRelation[]|array */ - public function getHasOneRelations():array + public function getHasOneRelations(): array { return array_filter( $this->relations, @@ -117,7 +112,7 @@ static function (AttributeRelation $relation) { ); } - public function getPkAttribute():Attribute + public function getPkAttribute(): Attribute { return $this->attributes[$this->pkName]; } @@ -125,7 +120,7 @@ public function getPkAttribute():Attribute /** * @return ColumnSchema[] */ - public function attributesToColumnSchema():array + public function attributesToColumnSchema(): array { return $this->isNotDb ? [] @@ -142,9 +137,9 @@ static function ($acc, Attribute $attribute) { } /** - * @return array|\cebe\yii2openapi\lib\items\Attribute[] + * @return array|Attribute[] */ - public function getEnumAttributes():array + public function getEnumAttributes(): array { return array_filter( $this->attributes, @@ -155,9 +150,9 @@ static function (Attribute $attribute) { } /** - * @return array|\cebe\yii2openapi\lib\items\Attribute[] + * @return array|Attribute[] */ - public function virtualAttributes():array + public function virtualAttributes(): array { return array_filter($this->attributes, static function (Attribute $attribute) { return $attribute->isVirtual; @@ -165,9 +160,9 @@ public function virtualAttributes():array } /** - * @return array|\cebe\yii2openapi\lib\items\Attribute[] + * @return array|Attribute[] */ - public function dbAttributes():array + public function dbAttributes(): array { return array_filter($this->attributes, static function (Attribute $attribute) { return !$attribute->isVirtual; From dcd49d115ba55bd401f238f2d6f5681d9f7c8da3 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Tue, 20 Aug 2024 17:10:27 +0530 Subject: [PATCH 153/358] Refactor again for more code readability --- src/lib/items/AttributeRelation.php | 74 ++++++++++-------------- src/lib/items/DbModel.php | 5 ++ src/lib/traits/ForeignKeyConstraints.php | 6 +- 3 files changed, 38 insertions(+), 47 deletions(-) diff --git a/src/lib/items/AttributeRelation.php b/src/lib/items/AttributeRelation.php index 7b21fa76..3cf2cb6f 100644 --- a/src/lib/items/AttributeRelation.php +++ b/src/lib/items/AttributeRelation.php @@ -7,10 +7,10 @@ namespace cebe\yii2openapi\lib\items; +use cebe\yii2openapi\lib\traits\ForeignKeyConstraints; use yii\helpers\Inflector; use yii\helpers\VarDumper; use function reset; -use cebe\yii2openapi\lib\traits\ForeignKeyConstraints; class AttributeRelation { @@ -19,41 +19,29 @@ class AttributeRelation public const HAS_ONE = 'hasOne'; public const HAS_MANY = 'hasMany'; - /** - * @var string $name - **/ - private $name; + private string $name; - /** - * @var string $tableName - **/ - private $tableName; + private ?string $tableName; - /** - * @var string $className - **/ - private $className; + private ?string $className; /** - * @var string $method (hasOne/hasMany) + * hasOne/hasMany **/ - private $method; + private ?string $method; - /** - * @var array - **/ - private $link = []; + private array $link; - /**@var bool */ - private $selfReference = false; + private bool $selfReference = false; public function __construct( - string $name, + string $name, ?string $tableName = null, ?string $className = null, ?string $method = null, - array $link = [] - ) { + array $link = [] + ) + { $this->name = $name; $this->tableName = $tableName; $this->className = $className; @@ -65,7 +53,7 @@ public function __construct( * @param string $name * @return AttributeRelation */ - public function setName(string $name):AttributeRelation + public function setName(string $name): AttributeRelation { $this->name = $name; return $this; @@ -75,7 +63,7 @@ public function setName(string $name):AttributeRelation * @param string $tableName * @return AttributeRelation */ - public function setTableName(string $tableName):AttributeRelation + public function setTableName(string $tableName): AttributeRelation { $this->tableName = $tableName; return $this; @@ -85,38 +73,38 @@ public function setTableName(string $tableName):AttributeRelation * @param string $className * @return AttributeRelation */ - public function setClassName(string $className):AttributeRelation + public function setClassName(string $className): AttributeRelation { $this->className = $className; return $this; } - public function asSelfReference():AttributeRelation + public function asSelfReference(): AttributeRelation { $this->selfReference = true; return $this; } - public function asHasOne(array $link):AttributeRelation + public function asHasOne(array $link): AttributeRelation { $this->method = self::HAS_ONE; $this->link = $link; return $this; } - public function asHasMany(array $link):AttributeRelation + public function asHasMany(array $link): AttributeRelation { $this->method = self::HAS_MANY; $this->link = $link; return $this; } - public function isHasOne():bool + public function isHasOne(): bool { return $this->method === self::HAS_ONE; } - public function isSelfReferenced():bool + public function isSelfReferenced(): bool { return $this->selfReference; } @@ -124,7 +112,7 @@ public function isSelfReferenced():bool /** * @return string */ - public function getName():string + public function getName(): string { return $this->name; } @@ -132,12 +120,12 @@ public function getName():string /** * @return string */ - public function getTableName():string + public function getTableName(): string { return $this->tableName; } - public function getTableAlias():string + public function getTableAlias(): string { return "{{%$this->tableName}}"; } @@ -145,12 +133,12 @@ public function getTableAlias():string /** * @return string */ - public function getClassName():string + public function getClassName(): string { return $this->className; } - public function getClassKey():string + public function getClassKey(): string { return Inflector::camel2id($this->getClassName()); } @@ -158,7 +146,7 @@ public function getClassKey():string /** * @return string */ - public function getMethod():string + public function getMethod(): string { return $this->method; } @@ -166,27 +154,27 @@ public function getMethod():string /** * @return array */ - public function getLink():array + public function getLink(): array { return $this->link; } - public function getCamelName():string + public function getCamelName(): string { return Inflector::camelize($this->name); } - public function getColumnName():string + public function getColumnName(): string { return reset($this->link); } - public function getForeignName():string + public function getForeignName(): string { return key($this->link); } - public function linkToString():string + public function linkToString(): string { return str_replace( [',', '=>', ', ]'], diff --git a/src/lib/items/DbModel.php b/src/lib/items/DbModel.php index ea1c2911..962fae91 100644 --- a/src/lib/items/DbModel.php +++ b/src/lib/items/DbModel.php @@ -59,6 +59,11 @@ class DbModel extends BaseObject */ public array $many2many = []; + /** + * @var array|AttributeRelation[] inverse relations # TODO + */ + public array $inverseRelations = []; + public array $junctionCols = []; /** diff --git a/src/lib/traits/ForeignKeyConstraints.php b/src/lib/traits/ForeignKeyConstraints.php index a3af3895..215abb42 100644 --- a/src/lib/traits/ForeignKeyConstraints.php +++ b/src/lib/traits/ForeignKeyConstraints.php @@ -10,18 +10,16 @@ trait ForeignKeyConstraints { /** - * @var string * Contains foreign key constraint * @example 'SET NULL' * @example 'CASCADE' */ - public $onDeleteFkConstraint; + public string $onDeleteFkConstraint; /** - * @var string * Contains foreign key constraint * @example 'SET NULL' * @example 'CASCADE' */ - public $onUpdateFkConstraint; + public string $onUpdateFkConstraint; } From 3f4111671b82ffaec1d0eba5dd339f7bc769869e Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Tue, 20 Aug 2024 17:15:11 +0530 Subject: [PATCH 154/358] Fix failing tests --- src/lib/items/DbModel.php | 6 ++++-- src/lib/traits/ForeignKeyConstraints.php | 6 ++++-- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/src/lib/items/DbModel.php b/src/lib/items/DbModel.php index 962fae91..58691c22 100644 --- a/src/lib/items/DbModel.php +++ b/src/lib/items/DbModel.php @@ -27,8 +27,10 @@ */ class DbModel extends BaseObject { - // primary key attribute name - public string $pkName; + /** + * @var string primary key attribute name + */ + public $pkName; // model name public string $name; diff --git a/src/lib/traits/ForeignKeyConstraints.php b/src/lib/traits/ForeignKeyConstraints.php index 215abb42..a3af3895 100644 --- a/src/lib/traits/ForeignKeyConstraints.php +++ b/src/lib/traits/ForeignKeyConstraints.php @@ -10,16 +10,18 @@ trait ForeignKeyConstraints { /** + * @var string * Contains foreign key constraint * @example 'SET NULL' * @example 'CASCADE' */ - public string $onDeleteFkConstraint; + public $onDeleteFkConstraint; /** + * @var string * Contains foreign key constraint * @example 'SET NULL' * @example 'CASCADE' */ - public string $onUpdateFkConstraint; + public $onUpdateFkConstraint; } From 71637c8573b54ce86effa92b4f6376715f6c1c58 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Tue, 20 Aug 2024 17:16:08 +0530 Subject: [PATCH 155/358] Fix style --- src/lib/items/AttributeRelation.php | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/lib/items/AttributeRelation.php b/src/lib/items/AttributeRelation.php index 3cf2cb6f..885abfb5 100644 --- a/src/lib/items/AttributeRelation.php +++ b/src/lib/items/AttributeRelation.php @@ -40,8 +40,7 @@ public function __construct( ?string $className = null, ?string $method = null, array $link = [] - ) - { + ) { $this->name = $name; $this->tableName = $tableName; $this->className = $className; From d593a63d614a67780edd1fce405d1b69fd462081 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sigmar=20K=C3=BChlmann?= Date: Wed, 21 Aug 2024 12:57:13 +0200 Subject: [PATCH 156/358] DbModel with openapiSchema --- src/lib/AttributeResolver.php | 32 +++++++++++++++++--------------- src/lib/items/DbModel.php | 5 +++++ 2 files changed, 22 insertions(+), 15 deletions(-) diff --git a/src/lib/AttributeResolver.php b/src/lib/AttributeResolver.php index 0063d8df..906226d4 100644 --- a/src/lib/AttributeResolver.php +++ b/src/lib/AttributeResolver.php @@ -60,7 +60,7 @@ class AttributeResolver /** * @var ComponentSchema */ - private $schema; + private $componentSchema; /** * @var \cebe\yii2openapi\lib\items\JunctionSchemas @@ -79,7 +79,7 @@ class AttributeResolver public function __construct(string $schemaName, ComponentSchema $schema, JunctionSchemas $junctions, ?Config $config = null) { $this->schemaName = $schemaName; - $this->schema = $schema; + $this->componentSchema = $schema; $this->tableName = $schema->resolveTableName($schemaName); $this->junctions = $junctions; $this->isJunctionSchema = $junctions->isJunctionSchema($schemaName); @@ -94,10 +94,10 @@ public function __construct(string $schemaName, ComponentSchema $schema, Junctio */ public function resolve():DbModel { - foreach ($this->schema->getProperties() as $property) { + foreach ($this->componentSchema->getProperties() as $property) { /** @var $property \cebe\yii2openapi\lib\openapi\PropertySchema */ - $isRequired = $this->schema->isRequiredProperty($property->getName()); + $isRequired = $this->componentSchema->isRequiredProperty($property->getName()); $nullableValue = $property->getProperty()->getSerializableData()->nullable ?? null; if ($nullableValue === false) { // see docs in README regarding NOT NULL, required and nullable $isRequired = true; @@ -113,18 +113,20 @@ public function resolve():DbModel } return Yii::createObject(DbModel::class, [ [ - 'pkName' => $this->schema->getPkName(), + /** @see \cebe\openapi\spec\Schema */ + 'openapiSchema' => $this->componentSchema->getSchema(), + 'pkName' => $this->componentSchema->getPkName(), 'name' => $this->schemaName, 'tableName' => $this->tableName, - 'description' => $this->schema->getDescription(), + 'description' => $this->componentSchema->getDescription(), 'attributes' => $this->attributes, 'relations' => $this->relations, 'nonDbRelations' => $this->nonDbRelations, 'many2many' => $this->many2many, - 'indexes' => $this->prepareIndexes($this->schema->getIndexes()), + 'indexes' => $this->prepareIndexes($this->componentSchema->getIndexes()), //For valid primary keys for junction tables 'junctionCols' => $this->isJunctionSchema ? $this->junctions->junctionCols($this->schemaName) : [], - 'isNotDb' => $this->schema->isNonDb(), + 'isNotDb' => $this->componentSchema->isNonDb(), ], ]); } @@ -185,7 +187,7 @@ protected function resolveHasMany2ManyTableProperty(PropertySchema $property, bo 'relatedSchemaName' => $junkAttribute['relatedClassName'], 'tableName' => $this->tableName, 'relatedTableName' => $junkAttribute['relatedTableName'], - 'pkAttribute' => $this->attributes[$this->schema->getPkName()], + 'pkAttribute' => $this->attributes[$this->componentSchema->getPkName()], 'hasViaModel' => true, 'viaModelName' => $viaModel, 'viaRelationName' => Inflector::id2camel($junkRef, '_'), @@ -197,7 +199,7 @@ protected function resolveHasMany2ManyTableProperty(PropertySchema $property, bo $this->relations[Inflector::pluralize($junkRef)] = Yii::createObject(AttributeRelation::class, [$junkRef, $junkAttribute['junctionTable'], $viaModel]) - ->asHasMany([$junkAttribute['pairProperty'] . '_id' => $this->schema->getPkName()]); + ->asHasMany([$junkAttribute['pairProperty'] . '_id' => $this->componentSchema->getPkName()]); return; } @@ -328,7 +330,7 @@ protected function resolveProperty( AttributeRelation::class, [$property->getName(), $relatedTableName, $relatedClassName] ) - ->asHasMany([$foreignPk => $this->schema->getPkName()]); + ->asHasMany([$foreignPk => $this->componentSchema->getPkName()]); return; } $relatedClassName = $property->getRefClassName(); @@ -347,10 +349,10 @@ protected function resolveProperty( AttributeRelation::class, [$property->getName(), $relatedTableName, $relatedClassName] ) - ->asHasMany([Inflector::camel2id($this->schemaName, '_') . '_id' => $this->schema->getPkName()]); + ->asHasMany([Inflector::camel2id($this->schemaName, '_') . '_id' => $this->componentSchema->getPkName()]); return; } - if ($this->schema->isNonDb() && $attribute->isReference()) { + if ($this->componentSchema->isNonDb() && $attribute->isReference()) { $this->attributes[$property->getName()] = $attribute; return; } @@ -398,7 +400,7 @@ protected function catchManyToMany( 'relatedSchemaName' => $relatedSchemaName, 'tableName' => $this->tableName, 'relatedTableName' => $relatedTableName, - 'pkAttribute' => $this->attributes[$this->schema->getPkName()], + 'pkAttribute' => $this->attributes[$this->componentSchema->getPkName()], ], ]); $this->many2many[$propertyName] = $relation; @@ -480,7 +482,7 @@ protected function resolvePropertyRef(PropertySchema $property, Attribute $attri $fkProperty = new PropertySchema( $property->getRefSchema()->getSchema(), $property->getName(), - $this->schema + $this->componentSchema ); [$min, $max] = $fkProperty->guessMinMax(); $attribute->setPhpType($fkProperty->guessPhpType()) diff --git a/src/lib/items/DbModel.php b/src/lib/items/DbModel.php index 4f174370..0ca396b5 100644 --- a/src/lib/items/DbModel.php +++ b/src/lib/items/DbModel.php @@ -27,6 +27,11 @@ */ class DbModel extends BaseObject { + /** + * @var \cebe\openapi\spec\Schema + */ + public $openapiSchema; + /** * @var string primary key attribute name */ From e499530c80e7d58c306cb637a6873601e721397a Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Wed, 21 Aug 2024 21:34:06 +0530 Subject: [PATCH 157/358] Implement --- src/generator/default/dbmodel.php | 8 ++++ src/lib/AttributeResolver.php | 57 ++++++++++++++++++++--------- src/lib/SchemaToDatabase.php | 20 +++++++++- src/lib/items/AttributeRelation.php | 15 +++++++- src/lib/items/DbModel.php | 2 +- 5 files changed, 81 insertions(+), 21 deletions(-) diff --git a/src/generator/default/dbmodel.php b/src/generator/default/dbmodel.php index d9c60ebc..24b7d98d 100644 --- a/src/generator/default/dbmodel.php +++ b/src/generator/default/dbmodel.php @@ -103,4 +103,12 @@ public function getgetCamelName() ?>() } +inverseRelations as $relationName => $relation): ?> + + public function getgetCamelName() ?>() + { + return $this->getMethod() ?>(\\getClassName() ?>::class, linkToString() ?>)->inverseOf('getClassName()) ?>'); + } + } diff --git a/src/lib/AttributeResolver.php b/src/lib/AttributeResolver.php index 74ef5e79..faa6029f 100644 --- a/src/lib/AttributeResolver.php +++ b/src/lib/AttributeResolver.php @@ -35,7 +35,8 @@ class AttributeResolver /** * @var AttributeRelation[]|array */ - private array $relations = []; + public array $relations = []; + /** * @var NonDbRelation[]|array */ @@ -59,6 +60,11 @@ class AttributeResolver private ?Config $config; + /** + * @var AttributeRelation[]|array + */ + public array $inverseRelations = []; + public function __construct(string $schemaName, ComponentSchema $schema, JunctionSchemas $junctions, ?Config $config = null) { $this->schemaName = $schemaName; @@ -94,22 +100,7 @@ public function resolve(): DbModel $this->resolveProperty($property, $isRequired, $nullableValue); } } - return Yii::createObject(DbModel::class, [ - [ - 'pkName' => $this->schema->getPkName(), - 'name' => $this->schemaName, - 'tableName' => $this->tableName, - 'description' => $this->schema->getDescription(), - 'attributes' => $this->attributes, - 'relations' => $this->relations, - 'nonDbRelations' => $this->nonDbRelations, - 'many2many' => $this->many2many, - 'indexes' => $this->prepareIndexes($this->schema->getIndexes()), - //For valid primary keys for junction tables - 'junctionCols' => $this->isJunctionSchema ? $this->junctions->junctionCols($this->schemaName) : [], - 'isNotDb' => $this->schema->isNonDb(), - ], - ]); + return $this->createDbModel(); } /** @@ -258,6 +249,14 @@ protected function resolveProperty( $relation->asSelfReference(); } $this->relations[$property->getName()] = $relation; + + $inverseRelation = Yii::createObject( + AttributeRelation::class, + [$this->schemaName, $this->tableName, $this->schemaName] + ) + ->asHasOne([$attribute->columnName => $fkProperty->getName()]); + $inverseRelation->setInverse(true); + $this->inverseRelations[$relatedClassName] = $inverseRelation; } if (!$property->isReference() && !$property->hasRefItems()) { [$min, $max] = $property->guessMinMax(); @@ -475,4 +474,28 @@ protected function resolvePropertyRef(PropertySchema $property, Attribute $attri $this->attributes[$property->getName()] = $attribute->setFakerStub($this->guessFakerStub($attribute, $fkProperty)); } + + /** + * @throws InvalidDefinitionException + * @throws InvalidConfigException + */ + public function createDbModel(): DbModel + { + return Yii::createObject(DbModel::class, [ + [ + 'pkName' => $this->schema->getPkName(), + 'name' => $this->schemaName, + 'tableName' => $this->tableName, + 'description' => $this->schema->getDescription(), + 'attributes' => $this->attributes, + 'relations' => $this->relations, + 'nonDbRelations' => $this->nonDbRelations, + 'many2many' => $this->many2many, + 'indexes' => $this->prepareIndexes($this->schema->getIndexes()), + //For valid primary keys for junction tables + 'junctionCols' => $this->isJunctionSchema ? $this->junctions->junctionCols($this->schemaName) : [], + 'isNotDb' => $this->schema->isNonDb(), + ], + ]); + } } diff --git a/src/lib/SchemaToDatabase.php b/src/lib/SchemaToDatabase.php index 8217513d..c13108a7 100644 --- a/src/lib/SchemaToDatabase.php +++ b/src/lib/SchemaToDatabase.php @@ -11,6 +11,7 @@ use cebe\openapi\exceptions\TypeErrorException; use cebe\openapi\exceptions\UnresolvableReferenceException; use cebe\yii2openapi\lib\exceptions\InvalidDefinitionException; +use cebe\yii2openapi\lib\items\AttributeRelation; use cebe\yii2openapi\lib\items\DbModel; use cebe\yii2openapi\lib\items\JunctionSchemas; use cebe\yii2openapi\lib\openapi\ComponentSchema; @@ -79,7 +80,7 @@ public function __construct(Config $config) */ public function prepareModels(): array { - $models = []; + $models = $resolvers = []; $openApi = $this->config->getOpenApi(); $junctions = $this->findJunctionSchemas(); foreach ($openApi->components->schemas as $schemaName => $openApiSchema) { @@ -93,8 +94,23 @@ public function prepareModels(): array } /**@var AttributeResolver $resolver */ $resolver = Yii::createObject(AttributeResolver::class, [$schemaName, $schema, $junctions, $this->config]); - $models[$schemaName] = $resolver->resolve(); + + // $models[$schemaName] = $resolver->resolve(); + $resolvers[$schemaName] = $resolver; + $models[$schemaName] = $resolvers[$schemaName]->resolve(); + } + + // handle inverse relation + foreach ($resolvers as $aResolver) { + /** @var AttributeResolver $aResolver */ + if ($aResolver->inverseRelations) { + foreach ($aResolver->inverseRelations as $name => $aRelation) { + /** @var AttributeRelation $aRelation */ + $models[$name]->inverseRelations[] = $aRelation; + } + } } + foreach ($models as $model) { foreach ($model->many2many as $relation) { if (isset($models[$relation->viaModelName])) { diff --git a/src/lib/items/AttributeRelation.php b/src/lib/items/AttributeRelation.php index 885abfb5..78fbd904 100644 --- a/src/lib/items/AttributeRelation.php +++ b/src/lib/items/AttributeRelation.php @@ -27,13 +27,15 @@ class AttributeRelation /** * hasOne/hasMany - **/ + */ private ?string $method; private array $link; private bool $selfReference = false; + private bool $inverse = false; + public function __construct( string $name, ?string $tableName = null, @@ -181,4 +183,15 @@ public function linkToString(): string preg_replace('~\s+~', '', VarDumper::export($this->getLink())) ); } + + public function setInverse(bool $inverse): AttributeRelation + { + $this->inverse = $inverse; + return $this; + } + + public function getInverse(): bool + { + return $this->inverse; + } } diff --git a/src/lib/items/DbModel.php b/src/lib/items/DbModel.php index 58691c22..394637fe 100644 --- a/src/lib/items/DbModel.php +++ b/src/lib/items/DbModel.php @@ -51,7 +51,7 @@ class DbModel extends BaseObject */ public array $relations = []; - /*** + /** * @var array|NonDbRelation[] non-db relations */ public array $nonDbRelations = []; From 444bfae2b7b390d77a3a50d02511913552e7e0da Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sigmar=20K=C3=BChlmann?= Date: Thu, 22 Aug 2024 11:19:46 +0200 Subject: [PATCH 158/358] x-scenarios: name, description. --- src/generator/default/dbmodel.php | 10 ++++++ src/lib/items/DbModel.php | 56 +++++++++++++++++++++++++++++++ 2 files changed, 66 insertions(+) diff --git a/src/generator/default/dbmodel.php b/src/generator/default/dbmodel.php index d9c60ebc..02d95ab6 100644 --- a/src/generator/default/dbmodel.php +++ b/src/generator/default/dbmodel.php @@ -45,6 +45,16 @@ */ abstract class getClassName() ?> extends \yii\db\ActiveRecord { +getScenarios()): +foreach($scenarios as $scenario): ?> + /** + * + + */ + public const = ''; + + + virtualAttributes())):?> protected $virtualAttributes = ['columnName; diff --git a/src/lib/items/DbModel.php b/src/lib/items/DbModel.php index 0ca396b5..6bd23f21 100644 --- a/src/lib/items/DbModel.php +++ b/src/lib/items/DbModel.php @@ -81,6 +81,11 @@ class DbModel extends BaseObject public $isNotDb = false; + /** + * @var array Automatically generated scenarios from the model 'x-scenarios'. + */ + private array $scenarios; + public function getTableAlias():string { return '{{%' . $this->tableName . '}}'; @@ -178,4 +183,55 @@ public function dbAttributes():array return !$attribute->isVirtual; }); } + + /** + * @return array + */ + public function getScenarios(): array + { + if (isset($this->scenarios)) { + return $this->scenarios; + } + $this->scenarios = $this->getScenariosByOpenapiSchema(); + return $this->scenarios; + } + + /** + * @return array + */ + private function getScenariosByOpenapiSchema(): array + { + $x_scenarios = $this->openapiSchema->{'x-scenarios'} ?? []; + if (empty($x_scenarios) || !is_array($x_scenarios)) { + return []; + } + + $uniqueNames = []; + $scenarios = array_filter($x_scenarios, function ($scenario) use (&$uniqueNames) { + $name = $scenario['name'] ?? ''; + + // Check if the name is empty, already used, or does not meet the criteria + if ( + empty($name) || + in_array($name, $uniqueNames) || + !preg_match('/^[a-zA-Z_][a-zA-Z0-9_]*$/', $name) + ) { + return false; // Exclude this item + } + + // Add the name to the uniqueNames array and keep the item + $uniqueNames[] = $name; + return true; + }); + + foreach ($scenarios as $key => $scenario) { + $scenarios[$key]['const'] = 'SCENARIO_' . strtoupper($scenario['name']); + if (empty($scenario['description'])) { + $scenarios[$key]['description'] = 'Scenario ' . $scenario['name']; + } + } + + return $scenarios; + } + } From f96257d33e29d06e2def9bdd67fe9433495e1b35 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sigmar=20K=C3=BChlmann?= Date: Thu, 22 Aug 2024 16:34:18 +0200 Subject: [PATCH 159/358] ModelClassDescription --- src/generator/default/dbmodel.php | 8 ++++++-- src/lib/items/DbModel.php | 21 +++++++++++++++++++++ 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/src/generator/default/dbmodel.php b/src/generator/default/dbmodel.php index 02d95ab6..8fff1db1 100644 --- a/src/generator/default/dbmodel.php +++ b/src/generator/default/dbmodel.php @@ -11,10 +11,14 @@ +/** + * This file is generated by Gii, do not change manually! + */ + namespace ; /** - *description) ? '' : str_replace("\n", "\n * ", ' ' . trim($model->description)) ?> + *getModelClassDescription() ?> * dbAttributes() as $attribute): ?> @@ -48,7 +52,7 @@ abstract class getClassName() ?> extends \yii\db\ActiveRecord getScenarios()): foreach($scenarios as $scenario): ?> /** - * + * */ public const = ''; diff --git a/src/lib/items/DbModel.php b/src/lib/items/DbModel.php index 6bd23f21..2d9c3f10 100644 --- a/src/lib/items/DbModel.php +++ b/src/lib/items/DbModel.php @@ -234,4 +234,25 @@ private function getScenariosByOpenapiSchema(): array return $scenarios; } + public function getModelClassDescription_() + { + return !empty($this->description) ? + str_replace("\n", "\n *", ' ' . trim($this->description)) + : ' This is the model class for table "'.$this->tableName.'".'; + } + + /** @noinspection PhpParamsInspection */ + public function getModelClassDescription() + { + if (empty($this->description)) { + return ' This is the model class for table "'.$this->tableName.'".'; + } + + $descriptionArr = explode("\n", $this->description); + $descriptionArr = array_map('trim', $descriptionArr); + $descriptionArr = array_map(function($item) { + return $item !== '' ? ' ' . $item : $item; + }, $descriptionArr); + return implode("\n *", $descriptionArr); + } } From b884d80279872f30f24e975f105d27a1cbb3bf73 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sigmar=20K=C3=BChlmann?= Date: Fri, 23 Aug 2024 06:06:17 +0200 Subject: [PATCH 160/358] getPropertyAnnotation with FormattedDescription --- src/generator/default/dbmodel.php | 2 +- src/lib/helpers/FormatHelper.php | 19 +++++++++++++++++++ src/lib/items/Attribute.php | 14 ++++++++++---- src/lib/items/DbModel.php | 22 ++++++---------------- 4 files changed, 36 insertions(+), 21 deletions(-) create mode 100644 src/lib/helpers/FormatHelper.php diff --git a/src/generator/default/dbmodel.php b/src/generator/default/dbmodel.php index 8fff1db1..665b9e3d 100644 --- a/src/generator/default/dbmodel.php +++ b/src/generator/default/dbmodel.php @@ -22,7 +22,7 @@ * dbAttributes() as $attribute): ?> - * @property getFormattedDescription() ?> + * @property getPropertyAnnotation() ?> * diff --git a/src/lib/helpers/FormatHelper.php b/src/lib/helpers/FormatHelper.php new file mode 100644 index 00000000..20c7b0f4 --- /dev/null +++ b/src/lib/helpers/FormatHelper.php @@ -0,0 +1,19 @@ +limits['minLength']; } - public function getFormattedDescription():string + /** + * @return string + */ + public function getPropertyAnnotation(): string { - $comment = $this->columnName.' '.$this->description; - $type = $this->phpType; - return $type.' $'.str_replace("\n", "\n * ", rtrim($comment)); + $annotation = $this->phpType . ' $' . $this->columnName; + if (!empty($this->description)) { + $annotation .= FormatHelper::getFormattedDescription($this->description); + } + return $annotation; } public function toColumnSchema():ColumnSchema diff --git a/src/lib/items/DbModel.php b/src/lib/items/DbModel.php index 2d9c3f10..87528b07 100644 --- a/src/lib/items/DbModel.php +++ b/src/lib/items/DbModel.php @@ -7,6 +7,7 @@ namespace cebe\yii2openapi\lib\items; +use cebe\yii2openapi\lib\helpers\FormatHelper; use cebe\yii2openapi\lib\ValidationRulesBuilder; use Yii; use yii\base\BaseObject; @@ -234,25 +235,14 @@ private function getScenariosByOpenapiSchema(): array return $scenarios; } - public function getModelClassDescription_() - { - return !empty($this->description) ? - str_replace("\n", "\n *", ' ' . trim($this->description)) - : ' This is the model class for table "'.$this->tableName.'".'; - } - - /** @noinspection PhpParamsInspection */ - public function getModelClassDescription() + /** + * @return string + */ + public function getModelClassDescription(): string { if (empty($this->description)) { return ' This is the model class for table "'.$this->tableName.'".'; } - - $descriptionArr = explode("\n", $this->description); - $descriptionArr = array_map('trim', $descriptionArr); - $descriptionArr = array_map(function($item) { - return $item !== '' ? ' ' . $item : $item; - }, $descriptionArr); - return implode("\n *", $descriptionArr); + return FormatHelper::getFormattedDescription($this->description); } } From 5dda2371eabe21c69e37b73c165af92207f9e7ea Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Fri, 23 Aug 2024 20:31:56 +0530 Subject: [PATCH 161/358] Handle multiple relations and add more tests --- src/generator/default/dbmodel.php | 12 ++++---- src/lib/AttributeResolver.php | 29 +++++++++++++------ src/lib/SchemaToDatabase.php | 8 +++-- src/lib/items/AttributeRelation.php | 6 ++-- .../25_generate_inverse_relations/index.yaml | 10 +++++++ 5 files changed, 44 insertions(+), 21 deletions(-) diff --git a/src/generator/default/dbmodel.php b/src/generator/default/dbmodel.php index 24b7d98d..bf04a385 100644 --- a/src/generator/default/dbmodel.php +++ b/src/generator/default/dbmodel.php @@ -87,7 +87,7 @@ public function rules() public function getgetCamelName() ?>() { return $this->getMethod() ?>(\\getClassName() ?>::class, linkToString()?>); + echo $relation->linkToString()?>)getInverse() ? '->inverseOf(\''.$relation->getInverse().'\')' : '' ?>; } many2many as $relation): ?> @@ -103,12 +103,12 @@ public function getgetCamelName() ?>() } -inverseRelations as $relationName => $relation): ?> +inverseRelations as $relationName => $relation): ?> - public function getgetCamelName() ?>() + public function getgetCamelName().($i===1 ? '' : $i) ?>() { - return $this->getMethod() ?>(\\getClassName() ?>::class, linkToString() ?>)->inverseOf('getClassName()) ?>'); + return $this->getMethod() ?>(\\getClassName() ?>::class, linkToString() ?>)->inverseOf('getInverse() ?>'); } - + } diff --git a/src/lib/AttributeResolver.php b/src/lib/AttributeResolver.php index faa6029f..27b305ea 100644 --- a/src/lib/AttributeResolver.php +++ b/src/lib/AttributeResolver.php @@ -249,14 +249,7 @@ protected function resolveProperty( $relation->asSelfReference(); } $this->relations[$property->getName()] = $relation; - - $inverseRelation = Yii::createObject( - AttributeRelation::class, - [$this->schemaName, $this->tableName, $this->schemaName] - ) - ->asHasOne([$attribute->columnName => $fkProperty->getName()]); - $inverseRelation->setInverse(true); - $this->inverseRelations[$relatedClassName] = $inverseRelation; + $this->addInverseRelation($relatedClassName, $attribute, $property, $fkProperty); } if (!$property->isReference() && !$property->hasRefItems()) { [$min, $max] = $property->guessMinMax(); @@ -329,7 +322,8 @@ protected function resolveProperty( AttributeRelation::class, [$property->getName(), $relatedTableName, $relatedClassName] ) - ->asHasMany([Inflector::camel2id($this->schemaName, '_') . '_id' => $this->schema->getPkName()]); + ->asHasMany([Inflector::camel2id($this->schemaName, '_') . '_id' => $this->schema->getPkName()]) + ->setInverse(Inflector::variablize($this->schemaName)); return; } if ($this->schema->isNonDb() && $attribute->isReference()) { @@ -498,4 +492,21 @@ public function createDbModel(): DbModel ], ]); } + + public function addInverseRelation( + string $relatedClassName, + Attribute $attribute, + PropertySchema $property, + PropertySchema $fkProperty + ): void + { + $inverseRelation = Yii::createObject( + AttributeRelation::class, + [$this->schemaName, $this->tableName, $this->schemaName] + ) + ->asHasOne([$attribute->columnName => $fkProperty->getName()]); + $inverseRelation->setInverse($property->getName()); + $this->inverseRelations[$relatedClassName][] = $inverseRelation; + + } } diff --git a/src/lib/SchemaToDatabase.php b/src/lib/SchemaToDatabase.php index c13108a7..4e5737eb 100644 --- a/src/lib/SchemaToDatabase.php +++ b/src/lib/SchemaToDatabase.php @@ -104,9 +104,11 @@ public function prepareModels(): array foreach ($resolvers as $aResolver) { /** @var AttributeResolver $aResolver */ if ($aResolver->inverseRelations) { - foreach ($aResolver->inverseRelations as $name => $aRelation) { - /** @var AttributeRelation $aRelation */ - $models[$name]->inverseRelations[] = $aRelation; + foreach ($aResolver->inverseRelations as $name => $relations) { + foreach ($relations as $relation) { + /** @var AttributeRelation $relation */ + $models[$name]->inverseRelations[] = $relation; + } } } } diff --git a/src/lib/items/AttributeRelation.php b/src/lib/items/AttributeRelation.php index 78fbd904..31acbd2c 100644 --- a/src/lib/items/AttributeRelation.php +++ b/src/lib/items/AttributeRelation.php @@ -34,7 +34,7 @@ class AttributeRelation private bool $selfReference = false; - private bool $inverse = false; + private ?string $inverse = null; public function __construct( string $name, @@ -184,13 +184,13 @@ public function linkToString(): string ); } - public function setInverse(bool $inverse): AttributeRelation + public function setInverse(string $inverse): AttributeRelation { $this->inverse = $inverse; return $this; } - public function getInverse(): bool + public function getInverse(): ?string { return $this->inverse; } diff --git a/tests/specs/issue_fix/25_generate_inverse_relations/index.yaml b/tests/specs/issue_fix/25_generate_inverse_relations/index.yaml index f1e9f59e..1d7c79fe 100644 --- a/tests/specs/issue_fix/25_generate_inverse_relations/index.yaml +++ b/tests/specs/issue_fix/25_generate_inverse_relations/index.yaml @@ -19,6 +19,10 @@ components: name: type: string maxLength: 128 + accounts: + type: array + items: + $ref: '#/components/schemas/Account' Account: description: Account @@ -38,6 +42,12 @@ components: type: string user: $ref: '#/components/schemas/User' + user2: # copy of user (not one to many) + $ref: '#/components/schemas/User' + user3: # copy of user (not one to many) + allOf: + - $ref: '#/components/schemas/User' + - x-fk-column-name: user3 paths: '/account': From 5c7fa9ba40634c6e4c0cd3e585edc4fa0e8a5102 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sigmar=20K=C3=BChlmann?= Date: Sun, 25 Aug 2024 07:30:25 +0200 Subject: [PATCH 162/358] add FormattedDescription to x-scenarios --- src/generator/default/dbmodel.php | 2 +- src/lib/helpers/FormatHelper.php | 11 ++++++----- src/lib/items/DbModel.php | 6 +++--- 3 files changed, 10 insertions(+), 9 deletions(-) diff --git a/src/generator/default/dbmodel.php b/src/generator/default/dbmodel.php index 665b9e3d..32250030 100644 --- a/src/generator/default/dbmodel.php +++ b/src/generator/default/dbmodel.php @@ -52,7 +52,7 @@ abstract class getClassName() ?> extends \yii\db\ActiveRecord getScenarios()): foreach($scenarios as $scenario): ?> /** - * + * */ public const = ''; diff --git a/src/lib/helpers/FormatHelper.php b/src/lib/helpers/FormatHelper.php index 20c7b0f4..6fc29742 100644 --- a/src/lib/helpers/FormatHelper.php +++ b/src/lib/helpers/FormatHelper.php @@ -5,15 +5,16 @@ class FormatHelper { /** - * @param $description + * @param string $description + * @param int $spacing * @return string */ - public static function getFormattedDescription($description): string + public static function getFormattedDescription(string $description, int $spacing = 1): string { $descriptionArr = explode("\n", trim($description)); - $descriptionArr = array_map(function($item) { - return $item !== '' ? ' ' . $item : $item; + $descriptionArr = array_map(function ($item) { + return $item === '' ? '' : ' ' . $item; }, $descriptionArr); - return implode("\n *", $descriptionArr); + return implode("\n".str_repeat(" ", $spacing)."*", $descriptionArr); } } \ No newline at end of file diff --git a/src/lib/items/DbModel.php b/src/lib/items/DbModel.php index 87528b07..513e8669 100644 --- a/src/lib/items/DbModel.php +++ b/src/lib/items/DbModel.php @@ -227,9 +227,9 @@ private function getScenariosByOpenapiSchema(): array foreach ($scenarios as $key => $scenario) { $scenarios[$key]['const'] = 'SCENARIO_' . strtoupper($scenario['name']); - if (empty($scenario['description'])) { - $scenarios[$key]['description'] = 'Scenario ' . $scenario['name']; - } + $scenarios[$key]['description'] = !empty($scenario['description']) ? + FormatHelper::getFormattedDescription($scenario['description'], 5) + : ' Scenario ' . $scenario['name']; } return $scenarios; From 775437fe3a37c760bd9f200cddceab240a7eead0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sigmar=20K=C3=BChlmann?= Date: Sun, 25 Aug 2024 11:10:17 +0200 Subject: [PATCH 163/358] custom scenarioDefaultDescription --- src/generator/ApiGenerator.php | 10 ++++++++++ src/lib/Config.php | 9 +++++++++ src/lib/generators/ModelsGenerator.php | 3 +++ src/lib/items/DbModel.php | 16 +++++++++++++--- 4 files changed, 35 insertions(+), 3 deletions(-) diff --git a/src/generator/ApiGenerator.php b/src/generator/ApiGenerator.php index f930f949..cb9db6dc 100644 --- a/src/generator/ApiGenerator.php +++ b/src/generator/ApiGenerator.php @@ -7,6 +7,7 @@ namespace cebe\yii2openapi\generator; +use cebe\yii2openapi\lib\items\DbModel; use yii\db\mysql\Schema as MySqlSchema; use SamIT\Yii2\MariaDb\Schema as MariaDbSchema; use yii\db\pgsql\Schema as PgSqlSchema; @@ -133,6 +134,15 @@ class ApiGenerator extends Generator */ public $excludeModels = []; + /** + * @var array Map for custom dbModels + * @example + * 'dbModel' => [ + * 'scenarioDefaultDescription' => " Scenario {name}", @see DbModel::$scenarioDefaultDescription + * ] + */ + public $dbModel = []; + /** * @var array Map for custom controller names not based on model name for exclusive cases * @example diff --git a/src/lib/Config.php b/src/lib/Config.php index 60d15910..09cf3181 100644 --- a/src/lib/Config.php +++ b/src/lib/Config.php @@ -109,6 +109,15 @@ class Config extends BaseObject */ public $excludeModels = []; + /** + * @var array Map for custom dbModels + * @example + * 'dbModel' => [ + * 'scenarioDefaultDescription' => " Scenario {name}", @see DbModel::$scenarioDefaultDescription + * ] + */ + public $dbModel = []; + /** * @var array Map for custom controller names not based on model name for exclusive cases * @example diff --git a/src/lib/generators/ModelsGenerator.php b/src/lib/generators/ModelsGenerator.php index 5f196525..27dc6aea 100644 --- a/src/lib/generators/ModelsGenerator.php +++ b/src/lib/generators/ModelsGenerator.php @@ -56,6 +56,9 @@ public function generate():CodeFiles } foreach ($this->models as $model) { $className = $model->getClassName(); + if (!empty($this->config->dbModel['scenarioDefaultDescription'])) { + $model->scenarioDefaultDescription = $this->config->dbModel['scenarioDefaultDescription']; + } if ($model->isNotDb === false) { $this->files->add(new CodeFile( Yii::getAlias("$modelPath/base/$className.php"), diff --git a/src/lib/items/DbModel.php b/src/lib/items/DbModel.php index 513e8669..b5f5dd69 100644 --- a/src/lib/items/DbModel.php +++ b/src/lib/items/DbModel.php @@ -87,6 +87,13 @@ class DbModel extends BaseObject */ private array $scenarios; + /** + * @var string + * Here, you can set your own default description for the scenario. + * You can use the {name} attribute from the schema for the YAML model. + */ + public string $scenarioDefaultDescription = " Scenario {name}"; + public function getTableAlias():string { return '{{%' . $this->tableName . '}}'; @@ -227,9 +234,12 @@ private function getScenariosByOpenapiSchema(): array foreach ($scenarios as $key => $scenario) { $scenarios[$key]['const'] = 'SCENARIO_' . strtoupper($scenario['name']); - $scenarios[$key]['description'] = !empty($scenario['description']) ? - FormatHelper::getFormattedDescription($scenario['description'], 5) - : ' Scenario ' . $scenario['name']; + $scenarios[$key]['description'] = FormatHelper::getFormattedDescription( + !empty($scenario['description']) ? + $scenario['description'] + : str_replace('{name}', $scenario['name'], $this->scenarioDefaultDescription + ), + 5); } return $scenarios; From 19d5c361a2fffa7d31c2c79453ca7ee8203aed80 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sigmar=20K=C3=BChlmann?= Date: Sun, 25 Aug 2024 11:49:54 +0200 Subject: [PATCH 164/358] generate scenario const -fix --- src/lib/items/DbModel.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/lib/items/DbModel.php b/src/lib/items/DbModel.php index b5f5dd69..389a92b1 100644 --- a/src/lib/items/DbModel.php +++ b/src/lib/items/DbModel.php @@ -233,7 +233,7 @@ private function getScenariosByOpenapiSchema(): array }); foreach ($scenarios as $key => $scenario) { - $scenarios[$key]['const'] = 'SCENARIO_' . strtoupper($scenario['name']); + $scenarios[$key]['const'] = 'SCENARIO_' . strtoupper(implode('_', preg_split('/(?=[A-Z])/', $scenario['name']))); $scenarios[$key]['description'] = FormatHelper::getFormattedDescription( !empty($scenario['description']) ? $scenario['description'] From a168e07cdb7d4c8a1b9201ce61210f1493517280 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Sun, 25 Aug 2024 15:23:31 +0530 Subject: [PATCH 165/358] Avoid inverse relation for self reference --- src/lib/AttributeResolver.php | 8 ++++---- .../25_generate_inverse_relations/index.yaml | 20 +++++++++++++++++++ 2 files changed, 24 insertions(+), 4 deletions(-) diff --git a/src/lib/AttributeResolver.php b/src/lib/AttributeResolver.php index 27b305ea..b68b52c9 100644 --- a/src/lib/AttributeResolver.php +++ b/src/lib/AttributeResolver.php @@ -249,7 +249,9 @@ protected function resolveProperty( $relation->asSelfReference(); } $this->relations[$property->getName()] = $relation; - $this->addInverseRelation($relatedClassName, $attribute, $property, $fkProperty); + if (!$property->isRefPointerToSelf()) { + $this->addInverseRelation($relatedClassName, $attribute, $property, $fkProperty); + } } if (!$property->isReference() && !$property->hasRefItems()) { [$min, $max] = $property->guessMinMax(); @@ -498,8 +500,7 @@ public function addInverseRelation( Attribute $attribute, PropertySchema $property, PropertySchema $fkProperty - ): void - { + ): void { $inverseRelation = Yii::createObject( AttributeRelation::class, [$this->schemaName, $this->tableName, $this->schemaName] @@ -507,6 +508,5 @@ public function addInverseRelation( ->asHasOne([$attribute->columnName => $fkProperty->getName()]); $inverseRelation->setInverse($property->getName()); $this->inverseRelations[$relatedClassName][] = $inverseRelation; - } } diff --git a/tests/specs/issue_fix/25_generate_inverse_relations/index.yaml b/tests/specs/issue_fix/25_generate_inverse_relations/index.yaml index 1d7c79fe..b6f5ded3 100644 --- a/tests/specs/issue_fix/25_generate_inverse_relations/index.yaml +++ b/tests/specs/issue_fix/25_generate_inverse_relations/index.yaml @@ -49,6 +49,26 @@ components: - $ref: '#/components/schemas/User' - x-fk-column-name: user3 + Menu: + required: + - id + - name + properties: + id: + type: integer + format: int64 + readOnly: True + name: + type: string + maxLength: 100 + minLength: 3 + parent: + $ref: '#/components/schemas/Menu/properties/id' + childes: + type: array + items: + $ref: '#/components/schemas/Menu/properties/parent' + paths: '/account': get: From 51043121da1c7a81be94b2b05293c7214d7d99ea Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Sun, 25 Aug 2024 15:34:01 +0530 Subject: [PATCH 166/358] Refactor --- TODO.taskpaper | 4 ++-- src/lib/AttributeResolver.php | 39 +++++++++++++++-------------------- src/lib/SchemaToDatabase.php | 18 +++++++++------- 3 files changed, 29 insertions(+), 32 deletions(-) diff --git a/TODO.taskpaper b/TODO.taskpaper index 07c175cc..3d082f94 100644 --- a/TODO.taskpaper +++ b/TODO.taskpaper @@ -1,8 +1,8 @@ TODO.taskpaper ### Generate inverse relations #25 - ☐ create failing test - ☐ implement the solution + ✔ create failing test @done (24-08-25 15:25) + ✔ implement the solution @done (24-08-25 15:25) ☐ fix failing tests if any ☐ resolve TODOs if any ☐ review PR diff --git a/src/lib/AttributeResolver.php b/src/lib/AttributeResolver.php index b68b52c9..d25a28c2 100644 --- a/src/lib/AttributeResolver.php +++ b/src/lib/AttributeResolver.php @@ -100,7 +100,23 @@ public function resolve(): DbModel $this->resolveProperty($property, $isRequired, $nullableValue); } } - return $this->createDbModel(); + + return Yii::createObject(DbModel::class, [ + [ + 'pkName' => $this->schema->getPkName(), + 'name' => $this->schemaName, + 'tableName' => $this->tableName, + 'description' => $this->schema->getDescription(), + 'attributes' => $this->attributes, + 'relations' => $this->relations, + 'nonDbRelations' => $this->nonDbRelations, + 'many2many' => $this->many2many, + 'indexes' => $this->prepareIndexes($this->schema->getIndexes()), + //For valid primary keys for junction tables + 'junctionCols' => $this->isJunctionSchema ? $this->junctions->junctionCols($this->schemaName) : [], + 'isNotDb' => $this->schema->isNonDb(), + ], + ]); } /** @@ -472,29 +488,8 @@ protected function resolvePropertyRef(PropertySchema $property, Attribute $attri } /** - * @throws InvalidDefinitionException * @throws InvalidConfigException */ - public function createDbModel(): DbModel - { - return Yii::createObject(DbModel::class, [ - [ - 'pkName' => $this->schema->getPkName(), - 'name' => $this->schemaName, - 'tableName' => $this->tableName, - 'description' => $this->schema->getDescription(), - 'attributes' => $this->attributes, - 'relations' => $this->relations, - 'nonDbRelations' => $this->nonDbRelations, - 'many2many' => $this->many2many, - 'indexes' => $this->prepareIndexes($this->schema->getIndexes()), - //For valid primary keys for junction tables - 'junctionCols' => $this->isJunctionSchema ? $this->junctions->junctionCols($this->schemaName) : [], - 'isNotDb' => $this->schema->isNonDb(), - ], - ]); - } - public function addInverseRelation( string $relatedClassName, Attribute $attribute, diff --git a/src/lib/SchemaToDatabase.php b/src/lib/SchemaToDatabase.php index 4e5737eb..dae10450 100644 --- a/src/lib/SchemaToDatabase.php +++ b/src/lib/SchemaToDatabase.php @@ -80,7 +80,12 @@ public function __construct(Config $config) */ public function prepareModels(): array { - $models = $resolvers = []; + /** @var DbModel[] $models */ + $models = []; + + /** @var AttributeResolver[] $resolvers */ + $resolvers = []; + $openApi = $this->config->getOpenApi(); $junctions = $this->findJunctionSchemas(); foreach ($openApi->components->schemas as $schemaName => $openApiSchema) { @@ -102,13 +107,10 @@ public function prepareModels(): array // handle inverse relation foreach ($resolvers as $aResolver) { - /** @var AttributeResolver $aResolver */ - if ($aResolver->inverseRelations) { - foreach ($aResolver->inverseRelations as $name => $relations) { - foreach ($relations as $relation) { - /** @var AttributeRelation $relation */ - $models[$name]->inverseRelations[] = $relation; - } + foreach ($aResolver->inverseRelations as $name => $relations) { + foreach ($relations as $relation) { + /** @var AttributeRelation $relation */ + $models[$name]->inverseRelations[] = $relation; } } } From 69dfc10b0d9a867203c2d48b203491aa5a0c4c40 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sigmar=20K=C3=BChlmann?= Date: Sun, 25 Aug 2024 12:58:23 +0200 Subject: [PATCH 167/358] scenarioDefaultDescription: scenarioName, scenarioConst, modelName --- src/generator/ApiGenerator.php | 3 ++- src/lib/Config.php | 3 ++- src/lib/items/DbModel.php | 15 +++++++++++---- 3 files changed, 15 insertions(+), 6 deletions(-) diff --git a/src/generator/ApiGenerator.php b/src/generator/ApiGenerator.php index cb9db6dc..1852260c 100644 --- a/src/generator/ApiGenerator.php +++ b/src/generator/ApiGenerator.php @@ -138,7 +138,8 @@ class ApiGenerator extends Generator * @var array Map for custom dbModels * @example * 'dbModel' => [ - * 'scenarioDefaultDescription' => " Scenario {name}", @see DbModel::$scenarioDefaultDescription + * AcceptedInputs: {scenarioName}, {scenarioConst}, {modelName}. + * 'scenarioDefaultDescription' => " Scenario {scenarioName}", @see DbModel::$scenarioDefaultDescription * ] */ public $dbModel = []; diff --git a/src/lib/Config.php b/src/lib/Config.php index 09cf3181..e8732c27 100644 --- a/src/lib/Config.php +++ b/src/lib/Config.php @@ -113,7 +113,8 @@ class Config extends BaseObject * @var array Map for custom dbModels * @example * 'dbModel' => [ - * 'scenarioDefaultDescription' => " Scenario {name}", @see DbModel::$scenarioDefaultDescription + * AcceptedInputs: {scenarioName}, {scenarioConst}, {modelName}. + * 'scenarioDefaultDescription' => " Scenario {scenarioName}", @see DbModel::$scenarioDefaultDescription * ] */ public $dbModel = []; diff --git a/src/lib/items/DbModel.php b/src/lib/items/DbModel.php index 389a92b1..91377bad 100644 --- a/src/lib/items/DbModel.php +++ b/src/lib/items/DbModel.php @@ -90,9 +90,9 @@ class DbModel extends BaseObject /** * @var string * Here, you can set your own default description for the scenario. - * You can use the {name} attribute from the schema for the YAML model. + * AcceptedInputs: {scenarioName}, {scenarioConst}, {modelName}. */ - public string $scenarioDefaultDescription = " Scenario {name}"; + public string $scenarioDefaultDescription = " Scenario {scenarioName}"; public function getTableAlias():string { @@ -237,8 +237,15 @@ private function getScenariosByOpenapiSchema(): array $scenarios[$key]['description'] = FormatHelper::getFormattedDescription( !empty($scenario['description']) ? $scenario['description'] - : str_replace('{name}', $scenario['name'], $this->scenarioDefaultDescription - ), + : str_replace([ + '{scenarioName}', + '{scenarioConst}', + '{modelName}', + ], [ + $scenario['name'], + $scenarios[$key]['const'], + $this->name, + ], $this->scenarioDefaultDescription), 5); } From d5d1be7a0bbd905d28eba7208d281f1d74f3d5b2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sigmar=20K=C3=BChlmann?= Date: Mon, 26 Aug 2024 08:48:33 +0200 Subject: [PATCH 168/358] single description: scenarioName, scenarioConst, modelName --- src/lib/items/DbModel.php | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/src/lib/items/DbModel.php b/src/lib/items/DbModel.php index 91377bad..387107cd 100644 --- a/src/lib/items/DbModel.php +++ b/src/lib/items/DbModel.php @@ -92,7 +92,7 @@ class DbModel extends BaseObject * Here, you can set your own default description for the scenario. * AcceptedInputs: {scenarioName}, {scenarioConst}, {modelName}. */ - public string $scenarioDefaultDescription = " Scenario {scenarioName}"; + public string $scenarioDefaultDescription = "Scenario {scenarioName}"; public function getTableAlias():string { @@ -234,10 +234,10 @@ private function getScenariosByOpenapiSchema(): array foreach ($scenarios as $key => $scenario) { $scenarios[$key]['const'] = 'SCENARIO_' . strtoupper(implode('_', preg_split('/(?=[A-Z])/', $scenario['name']))); + $description = !empty($scenario['description']) ? + $scenario['description'] : $this->scenarioDefaultDescription; $scenarios[$key]['description'] = FormatHelper::getFormattedDescription( - !empty($scenario['description']) ? - $scenario['description'] - : str_replace([ + str_replace([ '{scenarioName}', '{scenarioConst}', '{modelName}', @@ -245,8 +245,9 @@ private function getScenariosByOpenapiSchema(): array $scenario['name'], $scenarios[$key]['const'], $this->name, - ], $this->scenarioDefaultDescription), - 5); + ], $description), + 5 + ); } return $scenarios; From 6f2d85f51cd02bcaad0a787ddf20ba9645d604a1 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Mon, 26 Aug 2024 13:52:38 +0530 Subject: [PATCH 169/358] Fix failing test - RelationsInFakerTest::testIndex --- src/lib/SchemaToDatabase.php | 2 -- src/lib/items/DbModel.php | 2 +- .../specs/relations_in_faker/app/models/base/A123.php | 5 +++++ .../relations_in_faker/app/models/base/Account.php | 5 +++++ .../specs/relations_in_faker/app/models/base/B123.php | 10 ++++++++++ .../specs/relations_in_faker/app/models/base/C123.php | 5 +++++ .../specs/relations_in_faker/app/models/base/D123.php | 5 +++++ .../relations_in_faker/app/models/base/Domain.php | 7 ++++++- .../relations_in_faker/app/models/base/Routing.php | 2 +- tests/specs/relations_in_faker/relations_in_faker.yaml | 2 +- 10 files changed, 39 insertions(+), 6 deletions(-) diff --git a/src/lib/SchemaToDatabase.php b/src/lib/SchemaToDatabase.php index dae10450..af2521b2 100644 --- a/src/lib/SchemaToDatabase.php +++ b/src/lib/SchemaToDatabase.php @@ -125,8 +125,6 @@ public function prepareModels(): array } } - // TODO generate inverse relations - return $models; } diff --git a/src/lib/items/DbModel.php b/src/lib/items/DbModel.php index 394637fe..5f3c8c4e 100644 --- a/src/lib/items/DbModel.php +++ b/src/lib/items/DbModel.php @@ -62,7 +62,7 @@ class DbModel extends BaseObject public array $many2many = []; /** - * @var array|AttributeRelation[] inverse relations # TODO + * @var array|AttributeRelation[] inverse relations */ public array $inverseRelations = []; diff --git a/tests/specs/relations_in_faker/app/models/base/A123.php b/tests/specs/relations_in_faker/app/models/base/A123.php index 9836dc3b..7b604bad 100644 --- a/tests/specs/relations_in_faker/app/models/base/A123.php +++ b/tests/specs/relations_in_faker/app/models/base/A123.php @@ -32,4 +32,9 @@ public function getB123() { return $this->hasOne(\app\models\B123::class, ['id' => 'b123_id']); } + + public function getRouting() + { + return $this->hasOne(\app\models\Routing::class, ['a123_id' => 'id'])->inverseOf('a123'); + } } diff --git a/tests/specs/relations_in_faker/app/models/base/Account.php b/tests/specs/relations_in_faker/app/models/base/Account.php index 0ee4adc0..07d561cd 100644 --- a/tests/specs/relations_in_faker/app/models/base/Account.php +++ b/tests/specs/relations_in_faker/app/models/base/Account.php @@ -24,4 +24,9 @@ public function rules() 'name_string' => [['name'], 'string', 'max' => 40], ]; } + + public function getDomain() + { + return $this->hasOne(\app\models\Domain::class, ['account_id' => 'id'])->inverseOf('account'); + } } diff --git a/tests/specs/relations_in_faker/app/models/base/B123.php b/tests/specs/relations_in_faker/app/models/base/B123.php index f05fe320..2fdde13d 100644 --- a/tests/specs/relations_in_faker/app/models/base/B123.php +++ b/tests/specs/relations_in_faker/app/models/base/B123.php @@ -32,4 +32,14 @@ public function getC123() { return $this->hasOne(\app\models\C123::class, ['id' => 'c123_id']); } + + public function getA123() + { + return $this->hasOne(\app\models\A123::class, ['b123_id' => 'id'])->inverseOf('b123'); + } + + public function getE1232() + { + return $this->hasOne(\app\models\E123::class, ['b123_id' => 'id'])->inverseOf('b123'); + } } diff --git a/tests/specs/relations_in_faker/app/models/base/C123.php b/tests/specs/relations_in_faker/app/models/base/C123.php index faa3f1e5..7e074ea9 100644 --- a/tests/specs/relations_in_faker/app/models/base/C123.php +++ b/tests/specs/relations_in_faker/app/models/base/C123.php @@ -23,4 +23,9 @@ public function rules() 'name_string' => [['name'], 'string'], ]; } + + public function getB123() + { + return $this->hasOne(\app\models\B123::class, ['c123_id' => 'id'])->inverseOf('c123'); + } } diff --git a/tests/specs/relations_in_faker/app/models/base/D123.php b/tests/specs/relations_in_faker/app/models/base/D123.php index a6050a8a..7cad2f34 100644 --- a/tests/specs/relations_in_faker/app/models/base/D123.php +++ b/tests/specs/relations_in_faker/app/models/base/D123.php @@ -23,4 +23,9 @@ public function rules() 'name_string' => [['name'], 'string'], ]; } + + public function getRouting() + { + return $this->hasOne(\app\models\Routing::class, ['d123_id' => 'id'])->inverseOf('d123'); + } } diff --git a/tests/specs/relations_in_faker/app/models/base/Domain.php b/tests/specs/relations_in_faker/app/models/base/Domain.php index 3f861f9e..b7a807e1 100644 --- a/tests/specs/relations_in_faker/app/models/base/Domain.php +++ b/tests/specs/relations_in_faker/app/models/base/Domain.php @@ -38,6 +38,11 @@ public function getAccount() public function getRoutings() { - return $this->hasMany(\app\models\Routing::class, ['domain_id' => 'id']); + return $this->hasMany(\app\models\Routing::class, ['domain_id' => 'id'])->inverseOf('domain'); + } + + public function getRouting() + { + return $this->hasOne(\app\models\Routing::class, ['domain_id' => 'id'])->inverseOf('domain'); } } diff --git a/tests/specs/relations_in_faker/app/models/base/Routing.php b/tests/specs/relations_in_faker/app/models/base/Routing.php index 71a31b81..2aa9f710 100644 --- a/tests/specs/relations_in_faker/app/models/base/Routing.php +++ b/tests/specs/relations_in_faker/app/models/base/Routing.php @@ -3,7 +3,7 @@ namespace app\models\base; /** - * rounting specification + * routing specification * * @property int $id * @property int $domain_id domain diff --git a/tests/specs/relations_in_faker/relations_in_faker.yaml b/tests/specs/relations_in_faker/relations_in_faker.yaml index 65853bbd..546e9b1a 100644 --- a/tests/specs/relations_in_faker/relations_in_faker.yaml +++ b/tests/specs/relations_in_faker/relations_in_faker.yaml @@ -64,7 +64,7 @@ components: nullable: false Routing: - description: rounting specification + description: routing specification type: object required: - id From 65c9ef85e8cb8846265e68c43fa60bf80acace74 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Mon, 26 Aug 2024 15:06:09 +0530 Subject: [PATCH 170/358] Fix test - GeneratorTest and more --- tests/fixtures/blog.php | 4 ++-- tests/fixtures/non-db.php | 2 +- tests/specs/blog/models/base/Category.php | 7 ++++++- tests/specs/blog/models/base/Post.php | 7 ++++++- tests/specs/blog/models/base/User.php | 10 ++++++++++ tests/specs/blog_v2/models/base/Category.php | 7 ++++++- tests/specs/blog_v2/models/base/Post.php | 7 ++++++- tests/specs/blog_v2/models/base/User.php | 10 ++++++++++ tests/specs/fk_col_name/app/models/base/Delivery.php | 5 +++++ tests/specs/fk_col_name/app/models/base/User.php | 5 +++++ .../fk_col_name_index/app/models/base/Delivery.php | 10 ++++++++++ tests/specs/fk_col_name_index/app/models/base/User.php | 5 +++++ tests/specs/petstore/models/base/Store.php | 5 +++++ tests/specs/petstore_jsonapi/models/base/Pet.php | 5 +++++ tests/specs/petstore_namespace/mymodels/base/Store.php | 5 +++++ 15 files changed, 87 insertions(+), 7 deletions(-) diff --git a/tests/fixtures/blog.php b/tests/fixtures/blog.php index 74b04000..5d6d0b49 100644 --- a/tests/fixtures/blog.php +++ b/tests/fixtures/blog.php @@ -48,7 +48,7 @@ ->setRequired()->setDefault(false)->setFakerStub('$faker->boolean'), ], 'relations' => [ - 'posts' => new AttributeRelation('posts', 'blog_posts', 'Post', 'hasMany', ['category_id' => 'id']), + 'posts' => (new AttributeRelation('posts', 'blog_posts', 'Post', 'hasMany', ['category_id' => 'id']))->setInverse('category'), ], 'indexes' => [ 'categories_active_index' => DbIndex::make('categories', ['active']), @@ -88,7 +88,7 @@ 'hasOne', ['id' => 'category_id']), 'created_by' => new AttributeRelation('created_by', 'users', 'User', 'hasOne', ['id' => 'created_by_id']), - 'comments' => new AttributeRelation('comments', 'post_comments', 'Comment', 'hasMany', ['post_id' => 'uid']), + 'comments' => (new AttributeRelation('comments', 'post_comments', 'Comment', 'hasMany', ['post_id' => 'uid']))->setInverse('post'), ], 'indexes' => [ 'blog_posts_title_key' => DbIndex::make('blog_posts', ['title'], null, true), diff --git a/tests/fixtures/non-db.php b/tests/fixtures/non-db.php index 220a486d..0e4fb69d 100644 --- a/tests/fixtures/non-db.php +++ b/tests/fixtures/non-db.php @@ -25,7 +25,7 @@ ], 'relations' => [ 'parentPet' => new AttributeRelation('parentPet', 'pets', 'Pet', 'hasOne', ['id' => 'parentPet_id']), - 'favoritePets' => new AttributeRelation('favoritePets', 'pets', 'Pet', 'hasMany', ['pet_statistic_id' => 'id']), + 'favoritePets' => (new AttributeRelation('favoritePets', 'pets', 'Pet', 'hasMany', ['pet_statistic_id' => 'id']))->setInverse('petStatistic'), ], 'nonDbRelations' => [ 'topDoctors' => new NonDbRelation('topDoctors', 'Doctor', 'hasMany'), diff --git a/tests/specs/blog/models/base/Category.php b/tests/specs/blog/models/base/Category.php index f22e0014..fc11c09b 100644 --- a/tests/specs/blog/models/base/Category.php +++ b/tests/specs/blog/models/base/Category.php @@ -32,6 +32,11 @@ public function rules() public function getPosts() { - return $this->hasMany(\app\models\Post::class, ['category_id' => 'id']); + return $this->hasMany(\app\models\Post::class, ['category_id' => 'id'])->inverseOf('category'); + } + + public function getPost() + { + return $this->hasOne(\app\models\Post::class, ['category_id' => 'id'])->inverseOf('category'); } } diff --git a/tests/specs/blog/models/base/Post.php b/tests/specs/blog/models/base/Post.php index 457978b5..abe61623 100644 --- a/tests/specs/blog/models/base/Post.php +++ b/tests/specs/blog/models/base/Post.php @@ -55,6 +55,11 @@ public function getCreatedBy() public function getComments() { - return $this->hasMany(\app\models\Comment::class, ['post_id' => 'uid']); + return $this->hasMany(\app\models\Comment::class, ['post_id' => 'uid'])->inverseOf('post'); + } + + public function getComment() + { + return $this->hasOne(\app\models\Comment::class, ['post_id' => 'uid'])->inverseOf('post'); } } diff --git a/tests/specs/blog/models/base/User.php b/tests/specs/blog/models/base/User.php index f0e484e8..dc94110c 100644 --- a/tests/specs/blog/models/base/User.php +++ b/tests/specs/blog/models/base/User.php @@ -39,4 +39,14 @@ public function rules() 'created_at_datetime' => [['created_at'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], ]; } + + public function getPost() + { + return $this->hasOne(\app\models\Post::class, ['created_by_id' => 'id'])->inverseOf('created_by'); + } + + public function getComment2() + { + return $this->hasOne(\app\models\Comment::class, ['author_id' => 'id'])->inverseOf('author'); + } } diff --git a/tests/specs/blog_v2/models/base/Category.php b/tests/specs/blog_v2/models/base/Category.php index a70be3ff..23ed92ea 100644 --- a/tests/specs/blog_v2/models/base/Category.php +++ b/tests/specs/blog_v2/models/base/Category.php @@ -32,6 +32,11 @@ public function rules() public function getPosts() { - return $this->hasMany(\app\models\Post::class, ['category_id' => 'id']); + return $this->hasMany(\app\models\Post::class, ['category_id' => 'id'])->inverseOf('category'); + } + + public function getPost() + { + return $this->hasOne(\app\models\Post::class, ['category_id' => 'id'])->inverseOf('category'); } } diff --git a/tests/specs/blog_v2/models/base/Post.php b/tests/specs/blog_v2/models/base/Post.php index 44fe4275..83316fab 100644 --- a/tests/specs/blog_v2/models/base/Post.php +++ b/tests/specs/blog_v2/models/base/Post.php @@ -61,7 +61,7 @@ public function getCreatedBy() public function getComments() { - return $this->hasMany(\app\models\Comment::class, ['post_id' => 'id']); + return $this->hasMany(\app\models\Comment::class, ['post_id' => 'id'])->inverseOf('post'); } public function getTags() @@ -69,4 +69,9 @@ public function getTags() return $this->hasMany(\app\models\Tag::class, ['id' => 'tag_id']) ->viaTable('posts2tags', ['post_id' => 'id']); } + + public function getComment() + { + return $this->hasOne(\app\models\Comment::class, ['post_id' => 'id'])->inverseOf('post'); + } } diff --git a/tests/specs/blog_v2/models/base/User.php b/tests/specs/blog_v2/models/base/User.php index 195b5b5e..7274ae0a 100644 --- a/tests/specs/blog_v2/models/base/User.php +++ b/tests/specs/blog_v2/models/base/User.php @@ -43,4 +43,14 @@ public function rules() 'created_at_datetime' => [['created_at'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], ]; } + + public function getPost() + { + return $this->hasOne(\app\models\Post::class, ['created_by_id' => 'id'])->inverseOf('created_by'); + } + + public function getComment2() + { + return $this->hasOne(\app\models\Comment::class, ['user_id' => 'id'])->inverseOf('user'); + } } diff --git a/tests/specs/fk_col_name/app/models/base/Delivery.php b/tests/specs/fk_col_name/app/models/base/Delivery.php index ae7cbd83..0380af0e 100644 --- a/tests/specs/fk_col_name/app/models/base/Delivery.php +++ b/tests/specs/fk_col_name/app/models/base/Delivery.php @@ -23,4 +23,9 @@ public function rules() 'title_string' => [['title'], 'string'], ]; } + + public function getWebhook() + { + return $this->hasOne(\app\models\Webhook::class, ['redelivery_of' => 'id'])->inverseOf('redelivery_of'); + } } diff --git a/tests/specs/fk_col_name/app/models/base/User.php b/tests/specs/fk_col_name/app/models/base/User.php index d76c3f4d..2c9c1c06 100644 --- a/tests/specs/fk_col_name/app/models/base/User.php +++ b/tests/specs/fk_col_name/app/models/base/User.php @@ -24,4 +24,9 @@ public function rules() 'name_string' => [['name'], 'string'], ]; } + + public function getWebhook() + { + return $this->hasOne(\app\models\Webhook::class, ['user_id' => 'id'])->inverseOf('user'); + } } diff --git a/tests/specs/fk_col_name_index/app/models/base/Delivery.php b/tests/specs/fk_col_name_index/app/models/base/Delivery.php index ae7cbd83..b1f57fc1 100644 --- a/tests/specs/fk_col_name_index/app/models/base/Delivery.php +++ b/tests/specs/fk_col_name_index/app/models/base/Delivery.php @@ -23,4 +23,14 @@ public function rules() 'title_string' => [['title'], 'string'], ]; } + + public function getWebhook() + { + return $this->hasOne(\app\models\Webhook::class, ['redelivery_of' => 'id'])->inverseOf('redelivery_of'); + } + + public function getWebhook2() + { + return $this->hasOne(\app\models\Webhook::class, ['rd_abc_2' => 'id'])->inverseOf('rd2'); + } } diff --git a/tests/specs/fk_col_name_index/app/models/base/User.php b/tests/specs/fk_col_name_index/app/models/base/User.php index d76c3f4d..2c9c1c06 100644 --- a/tests/specs/fk_col_name_index/app/models/base/User.php +++ b/tests/specs/fk_col_name_index/app/models/base/User.php @@ -24,4 +24,9 @@ public function rules() 'name_string' => [['name'], 'string'], ]; } + + public function getWebhook() + { + return $this->hasOne(\app\models\Webhook::class, ['user_id' => 'id'])->inverseOf('user'); + } } diff --git a/tests/specs/petstore/models/base/Store.php b/tests/specs/petstore/models/base/Store.php index b1f6bc0f..5e6696af 100644 --- a/tests/specs/petstore/models/base/Store.php +++ b/tests/specs/petstore/models/base/Store.php @@ -24,4 +24,9 @@ public function rules() 'name_string' => [['name'], 'string'], ]; } + + public function getPet() + { + return $this->hasOne(\app\models\Pet::class, ['store_id' => 'id'])->inverseOf('store'); + } } diff --git a/tests/specs/petstore_jsonapi/models/base/Pet.php b/tests/specs/petstore_jsonapi/models/base/Pet.php index f0e3138a..251a39a4 100644 --- a/tests/specs/petstore_jsonapi/models/base/Pet.php +++ b/tests/specs/petstore_jsonapi/models/base/Pet.php @@ -59,4 +59,9 @@ public function getDuplicates() { return $this->hasMany(\app\models\Pet::class, ['tag' => 'tag']); } + + public function getPetStatistic() + { + return $this->hasOne(\app\models\PetStatistic::class, ['parentPet_id' => 'id'])->inverseOf('parentPet'); + } } diff --git a/tests/specs/petstore_namespace/mymodels/base/Store.php b/tests/specs/petstore_namespace/mymodels/base/Store.php index 6ecc3e47..fa304857 100644 --- a/tests/specs/petstore_namespace/mymodels/base/Store.php +++ b/tests/specs/petstore_namespace/mymodels/base/Store.php @@ -24,4 +24,9 @@ public function rules() 'name_string' => [['name'], 'string'], ]; } + + public function getPet() + { + return $this->hasOne(\app\mymodels\Pet::class, ['store_id' => 'id'])->inverseOf('store'); + } } From 12a2a426d66bc74f860e19ca1badd8ca987c2945 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Mon, 26 Aug 2024 15:24:39 +0530 Subject: [PATCH 171/358] Fix other failing tests --- .../maria/models/base/Mailing.php | 5 +++++ .../app/models/base/Invoice.php | 5 +++++ .../pgsql/models/base/Account.php | 5 +++++ .../app/models/base/Account.php | 15 +++++++++++++++ 4 files changed, 30 insertions(+) diff --git a/tests/specs/issue_fix/159_bug_giiapi_generated_rules_emailid/maria/models/base/Mailing.php b/tests/specs/issue_fix/159_bug_giiapi_generated_rules_emailid/maria/models/base/Mailing.php index 77049b23..a7d5017a 100644 --- a/tests/specs/issue_fix/159_bug_giiapi_generated_rules_emailid/maria/models/base/Mailing.php +++ b/tests/specs/issue_fix/159_bug_giiapi_generated_rules_emailid/maria/models/base/Mailing.php @@ -26,4 +26,9 @@ public function rules() 'paymentMethodName_string' => [['paymentMethodName'], 'string'], ]; } + + public function getContact() + { + return $this->hasOne(\app\models\Contact::class, ['mailing_id' => 'id'])->inverseOf('mailing'); + } } diff --git a/tests/specs/issue_fix/162_bug_dollarref_with_x_faker/app/models/base/Invoice.php b/tests/specs/issue_fix/162_bug_dollarref_with_x_faker/app/models/base/Invoice.php index 061e3508..4236c8eb 100644 --- a/tests/specs/issue_fix/162_bug_dollarref_with_x_faker/app/models/base/Invoice.php +++ b/tests/specs/issue_fix/162_bug_dollarref_with_x_faker/app/models/base/Invoice.php @@ -19,4 +19,9 @@ public function rules() { return []; } + + public function getOrder() + { + return $this->hasOne(\app\models\Order::class, ['invoice_id' => 'id'])->inverseOf('invoice'); + } } diff --git a/tests/specs/issue_fix/175_bug_allof_with_multiple_dollarrefs/pgsql/models/base/Account.php b/tests/specs/issue_fix/175_bug_allof_with_multiple_dollarrefs/pgsql/models/base/Account.php index f3dae5db..3c6d28b7 100644 --- a/tests/specs/issue_fix/175_bug_allof_with_multiple_dollarrefs/pgsql/models/base/Account.php +++ b/tests/specs/issue_fix/175_bug_allof_with_multiple_dollarrefs/pgsql/models/base/Account.php @@ -26,4 +26,9 @@ public function rules() 'paymentMethodName_string' => [['paymentMethodName'], 'string'], ]; } + + public function getContact() + { + return $this->hasOne(\app\models\Contact::class, ['account_id' => 'id'])->inverseOf('account'); + } } diff --git a/tests/specs/issue_fix/model_name_more_than_once_in_faker_148/app/models/base/Account.php b/tests/specs/issue_fix/model_name_more_than_once_in_faker_148/app/models/base/Account.php index 0ee4adc0..c3125556 100644 --- a/tests/specs/issue_fix/model_name_more_than_once_in_faker_148/app/models/base/Account.php +++ b/tests/specs/issue_fix/model_name_more_than_once_in_faker_148/app/models/base/Account.php @@ -24,4 +24,19 @@ public function rules() 'name_string' => [['name'], 'string', 'max' => 40], ]; } + + public function getE123() + { + return $this->hasOne(\app\models\E123::class, ['account_id' => 'id'])->inverseOf('account'); + } + + public function getE1232() + { + return $this->hasOne(\app\models\E123::class, ['account_2_id' => 'id'])->inverseOf('account_2'); + } + + public function getE1233() + { + return $this->hasOne(\app\models\E123::class, ['account_3_id' => 'id'])->inverseOf('account_3'); + } } From 1a7302e1af0ecc1259b9a015ab466ecf6adb6d80 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Mon, 26 Aug 2024 15:32:06 +0530 Subject: [PATCH 172/358] Complete the test --- TODO.taskpaper | 9 -- .../m200000_000000_create_table_users.php | 20 +++ .../m200000_000001_create_table_accounts.php | 30 ++++ .../m200000_000002_create_table_menus.php | 23 +++ .../mysql/models/Account.php | 10 ++ .../mysql/models/AccountFaker.php | 54 +++++++ .../mysql/models/BaseModelFaker.php | 144 ++++++++++++++++++ .../mysql/models/Menu.php | 10 ++ .../mysql/models/MenuFaker.php | 51 +++++++ .../mysql/models/User.php | 10 ++ .../mysql/models/UserFaker.php | 41 +++++ .../mysql/models/base/Account.php | 56 +++++++ .../mysql/models/base/Menu.php | 42 +++++ .../mysql/models/base/User.php | 48 ++++++ tests/unit/IssueFixTest.php | 16 +- 15 files changed, 547 insertions(+), 17 deletions(-) delete mode 100644 TODO.taskpaper create mode 100644 tests/specs/issue_fix/25_generate_inverse_relations/mysql/migrations_mysql_db/m200000_000000_create_table_users.php create mode 100644 tests/specs/issue_fix/25_generate_inverse_relations/mysql/migrations_mysql_db/m200000_000001_create_table_accounts.php create mode 100644 tests/specs/issue_fix/25_generate_inverse_relations/mysql/migrations_mysql_db/m200000_000002_create_table_menus.php create mode 100644 tests/specs/issue_fix/25_generate_inverse_relations/mysql/models/Account.php create mode 100644 tests/specs/issue_fix/25_generate_inverse_relations/mysql/models/AccountFaker.php create mode 100644 tests/specs/issue_fix/25_generate_inverse_relations/mysql/models/BaseModelFaker.php create mode 100644 tests/specs/issue_fix/25_generate_inverse_relations/mysql/models/Menu.php create mode 100644 tests/specs/issue_fix/25_generate_inverse_relations/mysql/models/MenuFaker.php create mode 100644 tests/specs/issue_fix/25_generate_inverse_relations/mysql/models/User.php create mode 100644 tests/specs/issue_fix/25_generate_inverse_relations/mysql/models/UserFaker.php create mode 100644 tests/specs/issue_fix/25_generate_inverse_relations/mysql/models/base/Account.php create mode 100644 tests/specs/issue_fix/25_generate_inverse_relations/mysql/models/base/Menu.php create mode 100644 tests/specs/issue_fix/25_generate_inverse_relations/mysql/models/base/User.php diff --git a/TODO.taskpaper b/TODO.taskpaper deleted file mode 100644 index 3d082f94..00000000 --- a/TODO.taskpaper +++ /dev/null @@ -1,9 +0,0 @@ -TODO.taskpaper - -### Generate inverse relations #25 - ✔ create failing test @done (24-08-25 15:25) - ✔ implement the solution @done (24-08-25 15:25) - ☐ fix failing tests if any - ☐ resolve TODOs if any - ☐ review PR - ☐ delete this file and submit PR diff --git a/tests/specs/issue_fix/25_generate_inverse_relations/mysql/migrations_mysql_db/m200000_000000_create_table_users.php b/tests/specs/issue_fix/25_generate_inverse_relations/mysql/migrations_mysql_db/m200000_000000_create_table_users.php new file mode 100644 index 00000000..d151ed34 --- /dev/null +++ b/tests/specs/issue_fix/25_generate_inverse_relations/mysql/migrations_mysql_db/m200000_000000_create_table_users.php @@ -0,0 +1,20 @@ +createTable('{{%users}}', [ + 'id' => $this->primaryKey(), + 'name' => $this->string(128)->notNull(), + ]); + } + + public function down() + { + $this->dropTable('{{%users}}'); + } +} diff --git a/tests/specs/issue_fix/25_generate_inverse_relations/mysql/migrations_mysql_db/m200000_000001_create_table_accounts.php b/tests/specs/issue_fix/25_generate_inverse_relations/mysql/migrations_mysql_db/m200000_000001_create_table_accounts.php new file mode 100644 index 00000000..f2bc7b90 --- /dev/null +++ b/tests/specs/issue_fix/25_generate_inverse_relations/mysql/migrations_mysql_db/m200000_000001_create_table_accounts.php @@ -0,0 +1,30 @@ +createTable('{{%accounts}}', [ + 'id' => $this->primaryKey(), + 'name' => $this->string(128)->notNull(), + 'paymentMethodName' => $this->text()->null(), + 'user_id' => $this->integer()->null()->defaultValue(null), + 'user2_id' => $this->integer()->null()->defaultValue(null), + 'user3' => $this->integer()->null()->defaultValue(null), + ]); + $this->addForeignKey('fk_accounts_user_id_users_id', '{{%accounts}}', 'user_id', '{{%users}}', 'id'); + $this->addForeignKey('fk_accounts_user2_id_users_id', '{{%accounts}}', 'user2_id', '{{%users}}', 'id'); + $this->addForeignKey('fk_accounts_user3_users_id', '{{%accounts}}', 'user3', '{{%users}}', 'id'); + } + + public function down() + { + $this->dropForeignKey('fk_accounts_user3_users_id', '{{%accounts}}'); + $this->dropForeignKey('fk_accounts_user2_id_users_id', '{{%accounts}}'); + $this->dropForeignKey('fk_accounts_user_id_users_id', '{{%accounts}}'); + $this->dropTable('{{%accounts}}'); + } +} diff --git a/tests/specs/issue_fix/25_generate_inverse_relations/mysql/migrations_mysql_db/m200000_000002_create_table_menus.php b/tests/specs/issue_fix/25_generate_inverse_relations/mysql/migrations_mysql_db/m200000_000002_create_table_menus.php new file mode 100644 index 00000000..78011c88 --- /dev/null +++ b/tests/specs/issue_fix/25_generate_inverse_relations/mysql/migrations_mysql_db/m200000_000002_create_table_menus.php @@ -0,0 +1,23 @@ +createTable('{{%menus}}', [ + 'id' => $this->bigPrimaryKey(), + 'name' => $this->string(100)->notNull(), + 'parent_id' => $this->bigInteger()->null()->defaultValue(null), + ]); + $this->addForeignKey('fk_menus_parent_id_menus_id', '{{%menus}}', 'parent_id', '{{%menus}}', 'id'); + } + + public function down() + { + $this->dropForeignKey('fk_menus_parent_id_menus_id', '{{%menus}}'); + $this->dropTable('{{%menus}}'); + } +} diff --git a/tests/specs/issue_fix/25_generate_inverse_relations/mysql/models/Account.php b/tests/specs/issue_fix/25_generate_inverse_relations/mysql/models/Account.php new file mode 100644 index 00000000..2d25d7fc --- /dev/null +++ b/tests/specs/issue_fix/25_generate_inverse_relations/mysql/models/Account.php @@ -0,0 +1,10 @@ +generateModels(['author_id' => 1]); + * $model = (new PostFaker())->generateModels(function($model, $faker, $uniqueFaker) { + * $model->scenario = 'create'; + * $model->author_id = 1; + * return $model; + * }); + **/ + public function generateModel($attributes = []) + { + $faker = $this->faker; + $uniqueFaker = $this->uniqueFaker; + $model = new Account(); + //$model->id = $uniqueFaker->numberBetween(0, 1000000); + $model->name = substr($faker->text(128), 0, 128); + $model->paymentMethodName = $faker->sentence; + $model->user_id = $faker->randomElement(\app\models\User::find()->select("id")->column()); + $model->user2_id = $faker->randomElement(\app\models\User::find()->select("id")->column()); + $model->user3 = $faker->randomElement(\app\models\User::find()->select("id")->column()); + if (!is_callable($attributes)) { + $model->setAttributes($attributes, false); + } else { + $model = $attributes($model, $faker, $uniqueFaker); + } + return $model; + } + + public static function dependentOn() + { + return [ + // just model class names + 'User', + + ]; + } +} diff --git a/tests/specs/issue_fix/25_generate_inverse_relations/mysql/models/BaseModelFaker.php b/tests/specs/issue_fix/25_generate_inverse_relations/mysql/models/BaseModelFaker.php new file mode 100644 index 00000000..c367fbb4 --- /dev/null +++ b/tests/specs/issue_fix/25_generate_inverse_relations/mysql/models/BaseModelFaker.php @@ -0,0 +1,144 @@ +faker = FakerFactory::create(str_replace('-', '_', \Yii::$app->language)); + $this->uniqueFaker = new UniqueGenerator($this->faker); + } + + abstract public function generateModel($attributes = []); + + public function getFaker():Generator + { + return $this->faker; + } + + public function getUniqueFaker():UniqueGenerator + { + return $this->uniqueFaker; + } + + public function setFaker(Generator $faker):void + { + $this->faker = $faker; + } + + public function setUniqueFaker(UniqueGenerator $faker):void + { + $this->uniqueFaker = $faker; + } + + /** + * Generate and return model + * @param array|callable $attributes + * @param UniqueGenerator|null $uniqueFaker + * @return \yii\db\ActiveRecord + * @example MyFaker::makeOne(['user_id' => 1, 'title' => 'foo']); + * @example MyFaker::makeOne( function($model, $faker) { + * $model->scenario = 'create'; + * $model->setAttributes(['user_id' => 1, 'title' => $faker->sentence]); + * return $model; + * }); + */ + public static function makeOne($attributes = [], ?UniqueGenerator $uniqueFaker = null) + { + $fakeBuilder = new static(); + if ($uniqueFaker !== null) { + $fakeBuilder->setUniqueFaker($uniqueFaker); + } + $model = $fakeBuilder->generateModel($attributes); + return $model; + } + + /** + * Generate, save and return model + * @param array|callable $attributes + * @param UniqueGenerator|null $uniqueFaker + * @return \yii\db\ActiveRecord + * @example MyFaker::saveOne(['user_id' => 1, 'title' => 'foo']); + * @example MyFaker::saveOne( function($model, $faker) { + * $model->scenario = 'create'; + * $model->setAttributes(['user_id' => 1, 'title' => $faker->sentence]); + * return $model; + * }); + */ + public static function saveOne($attributes = [], ?UniqueGenerator $uniqueFaker = null) + { + $model = static::makeOne($attributes, $uniqueFaker); + $model->save(); + return $model; + } + + /** + * Generate and return multiple models + * @param int $number + * @param array|callable $commonAttributes + * @return \yii\db\ActiveRecord[]|array + * @example TaskFaker::make(5, ['project_id'=>1, 'user_id' => 2]); + * @example TaskFaker::make(5, function($model, $faker, $uniqueFaker) { + * $model->setAttributes(['name' => $uniqueFaker->username, 'state'=>$faker->boolean(20)]); + * return $model; + * }); + */ + public static function make(int $number, $commonAttributes = [], ?UniqueGenerator $uniqueFaker = null):array + { + if ($number < 1) { + return []; + } + $fakeBuilder = new static(); + if ($uniqueFaker !== null) { + $fakeBuilder->setUniqueFaker($uniqueFaker); + } + return array_map(function () use ($commonAttributes, $fakeBuilder) { + $model = $fakeBuilder->generateModel($commonAttributes); + return $model; + }, range(0, $number -1)); + } + + /** + * Generate, save and return multiple models + * @param int $number + * @param array|callable $commonAttributes + * @return \yii\db\ActiveRecord[]|array + * @example TaskFaker::save(5, ['project_id'=>1, 'user_id' => 2]); + * @example TaskFaker::save(5, function($model, $faker, $uniqueFaker) { + * $model->setAttributes(['name' => $uniqueFaker->username, 'state'=>$faker->boolean(20)]); + * return $model; + * }); + */ + public static function save(int $number, $commonAttributes = [], ?UniqueGenerator $uniqueFaker = null):array + { + if ($number < 1) { + return []; + } + $fakeBuilder = new static(); + if ($uniqueFaker !== null) { + $fakeBuilder->setUniqueFaker($uniqueFaker); + } + return array_map(function () use ($commonAttributes, $fakeBuilder) { + $model = $fakeBuilder->generateModel($commonAttributes); + $model->save(); + return $model; + }, range(0, $number -1)); + } +} diff --git a/tests/specs/issue_fix/25_generate_inverse_relations/mysql/models/Menu.php b/tests/specs/issue_fix/25_generate_inverse_relations/mysql/models/Menu.php new file mode 100644 index 00000000..2b5867b4 --- /dev/null +++ b/tests/specs/issue_fix/25_generate_inverse_relations/mysql/models/Menu.php @@ -0,0 +1,10 @@ +generateModels(['author_id' => 1]); + * $model = (new PostFaker())->generateModels(function($model, $faker, $uniqueFaker) { + * $model->scenario = 'create'; + * $model->author_id = 1; + * return $model; + * }); + **/ + public function generateModel($attributes = []) + { + $faker = $this->faker; + $uniqueFaker = $this->uniqueFaker; + $model = new Menu(); + //$model->id = $uniqueFaker->numberBetween(0, 1000000); + $model->name = substr($faker->text(100), 0, 100); + $model->parent_id = $faker->randomElement(\app\models\Menu::find()->select("id")->column()); + if (!is_callable($attributes)) { + $model->setAttributes($attributes, false); + } else { + $model = $attributes($model, $faker, $uniqueFaker); + } + return $model; + } + + public static function dependentOn() + { + return [ + // just model class names + 'Menu', + + ]; + } +} diff --git a/tests/specs/issue_fix/25_generate_inverse_relations/mysql/models/User.php b/tests/specs/issue_fix/25_generate_inverse_relations/mysql/models/User.php new file mode 100644 index 00000000..9b837d6e --- /dev/null +++ b/tests/specs/issue_fix/25_generate_inverse_relations/mysql/models/User.php @@ -0,0 +1,10 @@ +generateModels(['author_id' => 1]); + * $model = (new PostFaker())->generateModels(function($model, $faker, $uniqueFaker) { + * $model->scenario = 'create'; + * $model->author_id = 1; + * return $model; + * }); + **/ + public function generateModel($attributes = []) + { + $faker = $this->faker; + $uniqueFaker = $this->uniqueFaker; + $model = new User(); + //$model->id = $uniqueFaker->numberBetween(0, 1000000); + $model->name = substr($faker->text(128), 0, 128); + if (!is_callable($attributes)) { + $model->setAttributes($attributes, false); + } else { + $model = $attributes($model, $faker, $uniqueFaker); + } + return $model; + } +} diff --git a/tests/specs/issue_fix/25_generate_inverse_relations/mysql/models/base/Account.php b/tests/specs/issue_fix/25_generate_inverse_relations/mysql/models/base/Account.php new file mode 100644 index 00000000..d0f43293 --- /dev/null +++ b/tests/specs/issue_fix/25_generate_inverse_relations/mysql/models/base/Account.php @@ -0,0 +1,56 @@ + [['name', 'paymentMethodName'], 'trim'], + 'required' => [['name'], 'required'], + 'user_id_integer' => [['user_id'], 'integer'], + 'user_id_exist' => [['user_id'], 'exist', 'targetRelation' => 'User'], + 'user2_id_integer' => [['user2_id'], 'integer'], + 'user2_id_exist' => [['user2_id'], 'exist', 'targetRelation' => 'User2'], + 'user3_integer' => [['user3'], 'integer'], + 'user3_exist' => [['user3'], 'exist', 'targetRelation' => 'User3'], + 'name_string' => [['name'], 'string', 'max' => 128], + 'paymentMethodName_string' => [['paymentMethodName'], 'string'], + ]; + } + + public function getUser() + { + return $this->hasOne(\app\models\User::class, ['id' => 'user_id']); + } + + public function getUser2() + { + return $this->hasOne(\app\models\User::class, ['id' => 'user2_id']); + } + + public function getUser3() + { + return $this->hasOne(\app\models\User::class, ['id' => 'user3']); + } +} diff --git a/tests/specs/issue_fix/25_generate_inverse_relations/mysql/models/base/Menu.php b/tests/specs/issue_fix/25_generate_inverse_relations/mysql/models/base/Menu.php new file mode 100644 index 00000000..ec3d0957 --- /dev/null +++ b/tests/specs/issue_fix/25_generate_inverse_relations/mysql/models/base/Menu.php @@ -0,0 +1,42 @@ + [['name'], 'trim'], + 'required' => [['name'], 'required'], + 'parent_id_integer' => [['parent_id'], 'integer'], + 'parent_id_exist' => [['parent_id'], 'exist', 'targetRelation' => 'Parent'], + 'name_string' => [['name'], 'string', 'min' => 3, 'max' => 100], + ]; + } + + public function getParent() + { + return $this->hasOne(\app\models\Menu::class, ['id' => 'parent_id']); + } + + public function getChildes() + { + return $this->hasMany(\app\models\Menu::class, ['parent_id' => 'id']); + } +} diff --git a/tests/specs/issue_fix/25_generate_inverse_relations/mysql/models/base/User.php b/tests/specs/issue_fix/25_generate_inverse_relations/mysql/models/base/User.php new file mode 100644 index 00000000..5f70ce96 --- /dev/null +++ b/tests/specs/issue_fix/25_generate_inverse_relations/mysql/models/base/User.php @@ -0,0 +1,48 @@ + [['name'], 'trim'], + 'required' => [['name'], 'required'], + 'name_string' => [['name'], 'string', 'max' => 128], + ]; + } + + public function getAccounts() + { + return $this->hasMany(\app\models\Account::class, ['user_id' => 'id'])->inverseOf('user'); + } + + public function getAccount() + { + return $this->hasOne(\app\models\Account::class, ['user_id' => 'id'])->inverseOf('user'); + } + + public function getAccount2() + { + return $this->hasOne(\app\models\Account::class, ['user2_id' => 'id'])->inverseOf('user2'); + } + + public function getAccount3() + { + return $this->hasOne(\app\models\Account::class, ['user3' => 'id'])->inverseOf('user3'); + } +} diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index dd20604a..6af7e11b 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -364,15 +364,15 @@ public function test158BugGiiapiGeneratedRulesEnumWithTrim() // https://github.com/php-openapi/yii2-openapi/issues/25 public function test25GenerateInverseRelations() { - // 25_generate_inverse_relations $testFile = Yii::getAlias("@specs/issue_fix/25_generate_inverse_relations/index.php"); $this->runGenerator($testFile); -// $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ -// 'recursive' => true, -// ]); -// $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/25_generate_inverse_relations/mysql"), [ -// 'recursive' => true, -// ]); -// $this->checkFiles($actualFiles, $expectedFiles); + $this->runActualMigrations('mysql', 3); + $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ + 'recursive' => true, + ]); + $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/25_generate_inverse_relations/mysql"), [ + 'recursive' => true, + ]); + $this->checkFiles($actualFiles, $expectedFiles); } } From ba770ca1b1d0d67135f0cc8c852c87faf42465b3 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Mon, 26 Aug 2024 16:13:00 +0530 Subject: [PATCH 173/358] Add sub-tasks --- TODO.taskpaper | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 TODO.taskpaper diff --git a/TODO.taskpaper b/TODO.taskpaper new file mode 100644 index 00000000..e5485208 --- /dev/null +++ b/TODO.taskpaper @@ -0,0 +1,9 @@ +TODO.taskpaper + +### Add validation rules by attribute name or pattern #30 + ☐ create failing test + ☐ implement the solution + ☐ fix failing tests if any + ☐ resolve TODOs if any + ☐ review PR + ☐ delete this file and submit PR From 34459ade05ee81da513e0bf6d9150fe6b685bd85 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Mon, 26 Aug 2024 18:14:00 +0530 Subject: [PATCH 174/358] Contains implementation --- TODO.taskpaper | 8 ++-- src/lib/ValidationRulesBuilder.php | 28 +++++++++--- .../index.php | 14 ++++++ .../index.yaml | 45 +++++++++++++++++++ tests/unit/IssueFixTest.php | 14 ++++++ 5 files changed, 99 insertions(+), 10 deletions(-) create mode 100644 tests/specs/issue_fix/30_add_validation_rules_by_attribute_name_or_pattern/index.php create mode 100644 tests/specs/issue_fix/30_add_validation_rules_by_attribute_name_or_pattern/index.yaml diff --git a/TODO.taskpaper b/TODO.taskpaper index e5485208..617c3c2f 100644 --- a/TODO.taskpaper +++ b/TODO.taskpaper @@ -1,9 +1,9 @@ TODO.taskpaper ### Add validation rules by attribute name or pattern #30 - ☐ create failing test - ☐ implement the solution - ☐ fix failing tests if any - ☐ resolve TODOs if any + ✔ create failing test @done (24-08-26 18:13) + ✔ implement the solution @done (24-08-26 18:13) + ✔ fix failing tests if any @done (24-08-26 18:13) + ✔ resolve TODOs if any @done (24-08-26 18:13) ☐ review PR ☐ delete this file and submit PR diff --git a/src/lib/ValidationRulesBuilder.php b/src/lib/ValidationRulesBuilder.php index 3f3c1398..1e9c3188 100644 --- a/src/lib/ValidationRulesBuilder.php +++ b/src/lib/ValidationRulesBuilder.php @@ -10,8 +10,6 @@ use cebe\yii2openapi\lib\items\Attribute; use cebe\yii2openapi\lib\items\DbModel; use cebe\yii2openapi\lib\items\ValidationRule; -use yii\helpers\VarDumper; -use yii\validators\DateValidator; use function count; use function implode; use function in_array; @@ -65,7 +63,7 @@ public function build():array } } foreach ($this->model->attributes as $attribute) { - // column/field/property with name `id` is considered as Primary Key by this library and it is automatically handled by DB/Yii; so remove it from validation `rules()` + // column/field/property with name `id` is considered as Primary Key by this library, and it is automatically handled by DB/Yii; so remove it from validation `rules()` if (in_array($attribute->columnName, ['id', $this->model->pkName]) || in_array($attribute->propertyName, ['id', $this->model->pkName]) ) { @@ -140,12 +138,30 @@ private function addRulesByAttributeName(Attribute $attribute):void $patterns = [ '~e?mail~i' => 'email', '~(url|site|website|href|link)~i' => 'url', + + # below patters will only work if `format: binary` (file) is present in OpenAPI spec + # also `string` validation rule will be removed + '~(image|photo|picture)~i' => 'image', + '~(file|pdf|audio|video|document|json|yml|yaml|zip|tar|7z)~i' => 'file', ]; + $addRule = function (Attribute $attribute, string $validator): void { + $key = $attribute->columnName . '_' . $validator; + $this->rules[$key] = new ValidationRule([$attribute->columnName], $validator); + }; foreach ($patterns as $pattern => $validator) { if (empty($attribute->reference) # ignore column name based rules in case of reference/relation # https://github.com/cebe/yii2-openapi/issues/159 && preg_match($pattern, strtolower($attribute->columnName))) { - $key = $attribute->columnName . '_' . $validator; - $this->rules[$key] = new ValidationRule([$attribute->columnName], $validator); + + if (in_array($validator, ['image', 'file'], true)) { + if ($attribute->dbType === 'binary') { + $addRule($attribute, $validator); + // for files, we don't need `string` validation + $key = $attribute->columnName . '_string'; + unset($this->rules[$key]); + } + } else { + $addRule($attribute, $validator); + } return; } } @@ -223,7 +239,7 @@ private function prepareTypeScope():void if ($attribute->isReadOnly()) { continue; } - // column/field/property with name `id` is considered as Primary Key by this library and it is automatically handled by DB/Yii; so remove it from validation `rules()` + // column/field/property with name `id` is considered as Primary Key by this library, and it is automatically handled by DB/Yii; so remove it from validation `rules()` if (in_array($attribute->columnName, ['id', $this->model->pkName]) || in_array($attribute->propertyName, ['id', $this->model->pkName]) ) { diff --git a/tests/specs/issue_fix/30_add_validation_rules_by_attribute_name_or_pattern/index.php b/tests/specs/issue_fix/30_add_validation_rules_by_attribute_name_or_pattern/index.php new file mode 100644 index 00000000..ded72814 --- /dev/null +++ b/tests/specs/issue_fix/30_add_validation_rules_by_attribute_name_or_pattern/index.php @@ -0,0 +1,14 @@ + '@specs/issue_fix/30_add_validation_rules_by_attribute_name_or_pattern/index.yaml', + 'generateUrls' => false, + 'generateModels' => true, + 'excludeModels' => [ + 'Error', + ], + 'generateControllers' => false, + 'generateMigrations' => false, + 'generateModelFaker' => true, // `generateModels` must be `true` in order to use `generateModelFaker` as `true` +]; + diff --git a/tests/specs/issue_fix/30_add_validation_rules_by_attribute_name_or_pattern/index.yaml b/tests/specs/issue_fix/30_add_validation_rules_by_attribute_name_or_pattern/index.yaml new file mode 100644 index 00000000..4561070f --- /dev/null +++ b/tests/specs/issue_fix/30_add_validation_rules_by_attribute_name_or_pattern/index.yaml @@ -0,0 +1,45 @@ + +openapi: 3.0.3 + +info: + title: Add validation rules by attribute name or pattern \#30 + version: 1.0.0 + +components: + schemas: + User: + type: object + required: + - id + - name + properties: + id: + type: integer + readOnly: true + name: + description: name + type: string + maxLength: 128 + photo: + type: string + format: binary + profile_photo: + type: string + format: binary + pdf: + type: string + format: binary + a_file: + type: string + format: binary + profile: + type: string + +paths: + '/': + get: + operationId: opId + summary: summary + responses: + '200': + description: OK diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index b6c7abdb..a105928c 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -360,4 +360,18 @@ public function test158BugGiiapiGeneratedRulesEnumWithTrim() ]); $this->checkFiles($actualFiles, $expectedFiles); } + + // https://github.com/php-openapi/yii2-openapi/issues/30 + public function test30AddValidationRulesByAttributeNameOrPattern() + { + $testFile = Yii::getAlias("@specs/issue_fix/30_add_validation_rules_by_attribute_name_or_pattern/index.php"); + $this->runGenerator($testFile); +// $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ +// 'recursive' => true, +// ]); +// $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/30_add_validation_rules_by_attribute_name_or_pattern/mysql"), [ +// 'recursive' => true, +// ]); +// $this->checkFiles($actualFiles, $expectedFiles); + } } From c978bd7107d2028ae567a3619deae2c8b3ce0ed3 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Mon, 26 Aug 2024 18:16:02 +0530 Subject: [PATCH 175/358] Cleanup --- src/lib/ValidationRulesBuilder.php | 1 - .../index.php | 2 +- .../mysql/models/User.php | 10 +++++ .../mysql/models/base/User.php | 37 +++++++++++++++++++ tests/unit/IssueFixTest.php | 14 +++---- 5 files changed, 55 insertions(+), 9 deletions(-) create mode 100644 tests/specs/issue_fix/30_add_validation_rules_by_attribute_name_or_pattern/mysql/models/User.php create mode 100644 tests/specs/issue_fix/30_add_validation_rules_by_attribute_name_or_pattern/mysql/models/base/User.php diff --git a/src/lib/ValidationRulesBuilder.php b/src/lib/ValidationRulesBuilder.php index 1e9c3188..8e9a5ed5 100644 --- a/src/lib/ValidationRulesBuilder.php +++ b/src/lib/ValidationRulesBuilder.php @@ -151,7 +151,6 @@ private function addRulesByAttributeName(Attribute $attribute):void foreach ($patterns as $pattern => $validator) { if (empty($attribute->reference) # ignore column name based rules in case of reference/relation # https://github.com/cebe/yii2-openapi/issues/159 && preg_match($pattern, strtolower($attribute->columnName))) { - if (in_array($validator, ['image', 'file'], true)) { if ($attribute->dbType === 'binary') { $addRule($attribute, $validator); diff --git a/tests/specs/issue_fix/30_add_validation_rules_by_attribute_name_or_pattern/index.php b/tests/specs/issue_fix/30_add_validation_rules_by_attribute_name_or_pattern/index.php index ded72814..4415beda 100644 --- a/tests/specs/issue_fix/30_add_validation_rules_by_attribute_name_or_pattern/index.php +++ b/tests/specs/issue_fix/30_add_validation_rules_by_attribute_name_or_pattern/index.php @@ -9,6 +9,6 @@ ], 'generateControllers' => false, 'generateMigrations' => false, - 'generateModelFaker' => true, // `generateModels` must be `true` in order to use `generateModelFaker` as `true` + 'generateModelFaker' => false, // `generateModels` must be `true` in order to use `generateModelFaker` as `true` ]; diff --git a/tests/specs/issue_fix/30_add_validation_rules_by_attribute_name_or_pattern/mysql/models/User.php b/tests/specs/issue_fix/30_add_validation_rules_by_attribute_name_or_pattern/mysql/models/User.php new file mode 100644 index 00000000..9b837d6e --- /dev/null +++ b/tests/specs/issue_fix/30_add_validation_rules_by_attribute_name_or_pattern/mysql/models/User.php @@ -0,0 +1,10 @@ + [['name', 'photo', 'profile_photo', 'pdf', 'a_file', 'profile'], 'trim'], + 'required' => [['name'], 'required'], + 'name_string' => [['name'], 'string', 'max' => 128], + 'photo_image' => [['photo'], 'image'], + 'profile_photo_image' => [['profile_photo'], 'image'], + 'pdf_file' => [['pdf'], 'file'], + 'a_file_file' => [['a_file'], 'file'], + 'profile_string' => [['profile'], 'string'], + ]; + } +} diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index a105928c..1a7d17b8 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -366,12 +366,12 @@ public function test30AddValidationRulesByAttributeNameOrPattern() { $testFile = Yii::getAlias("@specs/issue_fix/30_add_validation_rules_by_attribute_name_or_pattern/index.php"); $this->runGenerator($testFile); -// $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ -// 'recursive' => true, -// ]); -// $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/30_add_validation_rules_by_attribute_name_or_pattern/mysql"), [ -// 'recursive' => true, -// ]); -// $this->checkFiles($actualFiles, $expectedFiles); + $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ + 'recursive' => true, + ]); + $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/30_add_validation_rules_by_attribute_name_or_pattern/mysql"), [ + 'recursive' => true, + ]); + $this->checkFiles($actualFiles, $expectedFiles); } } From 0dcf9b6b38b73d6b6c362b930dbe7141efe58a98 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Mon, 26 Aug 2024 18:17:08 +0530 Subject: [PATCH 176/358] Format --- tests/unit/IssueFixTest.php | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index 1a7d17b8..e08e6b2b 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -366,12 +366,12 @@ public function test30AddValidationRulesByAttributeNameOrPattern() { $testFile = Yii::getAlias("@specs/issue_fix/30_add_validation_rules_by_attribute_name_or_pattern/index.php"); $this->runGenerator($testFile); - $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ - 'recursive' => true, - ]); - $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/30_add_validation_rules_by_attribute_name_or_pattern/mysql"), [ - 'recursive' => true, - ]); - $this->checkFiles($actualFiles, $expectedFiles); + $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ + 'recursive' => true, + ]); + $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/30_add_validation_rules_by_attribute_name_or_pattern/mysql"), [ + 'recursive' => true, + ]); + $this->checkFiles($actualFiles, $expectedFiles); } } From acfe0aff1ec1f594fb3ad8a294a0e9886608330f Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Mon, 26 Aug 2024 18:18:17 +0530 Subject: [PATCH 177/358] Resolve TODO.taskpaper --- TODO.taskpaper | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/TODO.taskpaper b/TODO.taskpaper index 617c3c2f..821b0e7f 100644 --- a/TODO.taskpaper +++ b/TODO.taskpaper @@ -5,5 +5,5 @@ TODO.taskpaper ✔ implement the solution @done (24-08-26 18:13) ✔ fix failing tests if any @done (24-08-26 18:13) ✔ resolve TODOs if any @done (24-08-26 18:13) - ☐ review PR + ✔ review PR @done (24-08-26 18:17) ☐ delete this file and submit PR From 04e3780e377e94babab2fa41a48eb09c6d1948e2 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Mon, 26 Aug 2024 18:18:45 +0530 Subject: [PATCH 178/358] Apply --- TODO.taskpaper | 9 --------- 1 file changed, 9 deletions(-) delete mode 100644 TODO.taskpaper diff --git a/TODO.taskpaper b/TODO.taskpaper deleted file mode 100644 index 821b0e7f..00000000 --- a/TODO.taskpaper +++ /dev/null @@ -1,9 +0,0 @@ -TODO.taskpaper - -### Add validation rules by attribute name or pattern #30 - ✔ create failing test @done (24-08-26 18:13) - ✔ implement the solution @done (24-08-26 18:13) - ✔ fix failing tests if any @done (24-08-26 18:13) - ✔ resolve TODOs if any @done (24-08-26 18:13) - ✔ review PR @done (24-08-26 18:17) - ☐ delete this file and submit PR From 42674b7be60515f056ddc1ddb2d44cf88115f0d1 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Mon, 26 Aug 2024 18:20:39 +0530 Subject: [PATCH 179/358] Resolve TODO --- src/lib/ValidationRulesBuilder.php | 1 - 1 file changed, 1 deletion(-) diff --git a/src/lib/ValidationRulesBuilder.php b/src/lib/ValidationRulesBuilder.php index 8e9a5ed5..75f07be5 100644 --- a/src/lib/ValidationRulesBuilder.php +++ b/src/lib/ValidationRulesBuilder.php @@ -134,7 +134,6 @@ private function resolveAttributeRules(Attribute $attribute):void private function addRulesByAttributeName(Attribute $attribute):void { - //@TODO: probably also patterns for file, image $patterns = [ '~e?mail~i' => 'email', '~(url|site|website|href|link)~i' => 'url', From a1ac7e3e8a1b23f544ab1224b7d7b535852d1ba6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sigmar=20K=C3=BChlmann?= Date: Tue, 27 Aug 2024 09:48:34 +0200 Subject: [PATCH 180/358] add function scenarios --- src/generator/default/dbmodel.php | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/src/generator/default/dbmodel.php b/src/generator/default/dbmodel.php index 32250030..17fa4a84 100644 --- a/src/generator/default/dbmodel.php +++ b/src/generator/default/dbmodel.php @@ -76,6 +76,33 @@ public static function tableName() { return getTableAlias()) ?>; } + + + /** + * Automatically generated scenarios from the model 'x-scenarios'. + * @return array a list of scenarios and the corresponding active attributes. + */ + public function scenarios() + { + /** + * Each scenario is assigned attributes as in the 'default' scenario. + * The advantage is that the scenario can be used immediately. + * This can be overridden in the child model if needed. + */ + $default = parent::scenarios()[self::SCENARIO_DEFAULT]; + + return [ + + self:: => $default, + + /** + * The 'default' scenario and all scenarios mentioned in the rules() using 'on' and 'except' + * are automatically included in the scenarios() function for the model. + */ + ...parent::scenarios(), + ]; + } + virtualAttributes())):?> public function attributes() From 2ab975b786c36d96424cd32adc9db752390cbaf2 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Wed, 28 Aug 2024 20:12:38 +0530 Subject: [PATCH 181/358] Fix https://github.com/php-openapi/yii2-openapi/issues/33 --- src/lib/items/Attribute.php | 1 - 1 file changed, 1 deletion(-) diff --git a/src/lib/items/Attribute.php b/src/lib/items/Attribute.php index 5563162d..99241501 100644 --- a/src/lib/items/Attribute.php +++ b/src/lib/items/Attribute.php @@ -321,7 +321,6 @@ public function toColumnSchema():ColumnSchema if ($this->defaultValue !== null) { $column->defaultValue = $this->defaultValue; } elseif ($column->allowNull) { - //@TODO: Need to discuss $column->defaultValue = null; } if (is_array($this->enumValues)) { From 4f9e8d16c042451429e35b9b9b79fb7c65951f97 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Wed, 28 Aug 2024 20:25:49 +0530 Subject: [PATCH 182/358] Initial commit --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 1cd2090b..3bb79307 100644 --- a/README.md +++ b/README.md @@ -568,3 +568,4 @@ Professional support, consulting as well as software development services are av https://www.cebe.cc/en/contact Development of this library is sponsored by [cebe.:cloud: "Your Professional Deployment Platform"](https://cebe.cloud). + From df315d45fa1200ff03afe0dff7da22369fec7548 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Fri, 30 Aug 2024 20:29:51 +0530 Subject: [PATCH 183/358] Detect module from namespace or path --- README.md | 1 - TODO.taskpaper | 10 +++++++ src/lib/items/FractalAction.php | 42 +++++++++++++++++++++++++-- tests/specs/petstore_urlprefixes.php | 3 ++ tests/specs/petstore_urlprefixes.yaml | 12 ++++++++ tests/unit/IssueFixTest.php | 15 ++++++++++ 6 files changed, 80 insertions(+), 3 deletions(-) create mode 100644 TODO.taskpaper diff --git a/README.md b/README.md index 3bb79307..1cd2090b 100644 --- a/README.md +++ b/README.md @@ -568,4 +568,3 @@ Professional support, consulting as well as software development services are av https://www.cebe.cc/en/contact Development of this library is sponsored by [cebe.:cloud: "Your Professional Deployment Platform"](https://cebe.cloud). - diff --git a/TODO.taskpaper b/TODO.taskpaper new file mode 100644 index 00000000..5562aa55 --- /dev/null +++ b/TODO.taskpaper @@ -0,0 +1,10 @@ +TODO.taskpaper + +### Add validation rules by attribute name or pattern #30 + ☐ Re-check + ☐ create failing test + ☐ implement the solution + ☐ fix failing tests if any + ☐ resolve TODOs if any + ☐ review PR + ☐ delete this file and submit PR diff --git a/src/lib/items/FractalAction.php b/src/lib/items/FractalAction.php index 148ac191..bb0e0f4d 100644 --- a/src/lib/items/FractalAction.php +++ b/src/lib/items/FractalAction.php @@ -106,8 +106,21 @@ public function getOptionsRoute():string { //@TODO: re-check if ($this->prefix && !empty($this->prefixSettings)) { - $prefix = $this->prefixSettings['module'] ?? $this->prefix; - return trim($prefix, '/').'/'.$this->controllerId.'/options'; +// $prefix = $this->prefixSettings['module'] ?? $this->prefix; + if (isset($this->prefixSettings['module'])) { + $prefix = $this->prefixSettings['module']; + return trim($prefix, '/') . '/' . $this->controllerId . '/options'; + } elseif (isset($this->prefixSettings['namespace']) && str_contains($this->prefixSettings['namespace'], '\modules\\')) { + $prefix = static::computeModule('\\', $this->prefixSettings['namespace']); + if ($prefix) { + return trim($prefix, '/') . '/' . $this->controllerId . '/options'; + } + } elseif (isset($this->prefixSettings['path']) && str_contains($this->prefixSettings['path'], '/modules/')) { + $prefix = static::computeModule('/', $this->prefixSettings['path']); + if ($prefix) { + return trim($prefix, '/') . '/' . $this->controllerId . '/options'; + } + } } return $this->controllerId.'/options'; } @@ -251,4 +264,29 @@ public function getIdParamType(): string } return $this->params[$this->idParam]['type'] === 'integer' ? 'int' : 'string'; } + + /** + * @param string $separator + * @param string $entity path or namespace + * @return void + */ + public static function computeModule(string $separator, string $entity): ?string + { + $parts = explode($separator . 'modules' . $separator, $entity); + if (empty($parts[1])) { + return null; + } + if (str_contains($parts[1], 'controller')) { + $result = explode($separator . 'controller', $parts[1]); + $result = array_map(function ($val) { + return str_replace('\\', '/', $val); + }, $result); + } else { + $result = explode($separator, $parts[1]); + } + if (empty($result[0])) { + return null; + } + return $result[0]; + } } diff --git a/tests/specs/petstore_urlprefixes.php b/tests/specs/petstore_urlprefixes.php index 8041c1fe..f14c4bca 100644 --- a/tests/specs/petstore_urlprefixes.php +++ b/tests/specs/petstore_urlprefixes.php @@ -9,9 +9,12 @@ ], 'generateControllers' => true, 'generateMigrations' => false, + 'useJsonApi' => true, 'urlPrefixes' => [ 'animals' => '', '/info' => ['module' =>'petinfo','namespace' => '\app\modules\petinfo\controllers'], + '/fgh' => ['namespace' => '\app\modules\fgh\controllers'], + '/fgh2' => ['path' => '@app/modules/fgh2/controllers', 'namespace' => '\app\fgh2\controllers'], '/api/v1' => ['path' => '@app/modules/api/v1/controllers', 'namespace' => '\app\api\v1\controllers'] ] ]; diff --git a/tests/specs/petstore_urlprefixes.yaml b/tests/specs/petstore_urlprefixes.yaml index 98701d27..7a3a549a 100644 --- a/tests/specs/petstore_urlprefixes.yaml +++ b/tests/specs/petstore_urlprefixes.yaml @@ -111,6 +111,18 @@ paths: responses: '200': description: list of details + /fgh/pet-detail2s: + get: + description: list all pet details + responses: + '200': + description: list of details + /fgh2/pet-detail3s: + get: + description: list all pet details + responses: + '200': + description: list of details components: schemas: diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index b6c7abdb..6f5fa668 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -360,4 +360,19 @@ public function test158BugGiiapiGeneratedRulesEnumWithTrim() ]); $this->checkFiles($actualFiles, $expectedFiles); } + + + public function testRecheckFractalActionsOptionsRoute() + { + $this->changeDbToMariadb(); + $testFile = Yii::getAlias("@specs/petstore_urlprefixes.php"); + $this->runGenerator($testFile); +// $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ +// 'recursive' => true, +// ]); +// $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/158_bug_giiapi_generated_rules_enum_with_trim/maria"), [ +// 'recursive' => true, +// ]); +// $this->checkFiles($actualFiles, $expectedFiles); + } } From bbefd8efde3527ec6ccb3f8f6be9a07b50ee46d1 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Tue, 3 Sep 2024 16:14:38 +0530 Subject: [PATCH 184/358] Fix TODO --- src/lib/items/FractalAction.php | 13 +- .../index.php | 21 +++ .../index.yaml | 177 ++++++++++++++++++ tests/specs/petstore_urlprefixes.php | 3 - tests/specs/petstore_urlprefixes.yaml | 12 -- tests/unit/IssueFixTest.php | 8 +- 6 files changed, 210 insertions(+), 24 deletions(-) create mode 100644 tests/specs/issue_fix/35_resolve_todo_re_check_options_route_in_fractal_action/index.php create mode 100644 tests/specs/issue_fix/35_resolve_todo_re_check_options_route_in_fractal_action/index.yaml diff --git a/src/lib/items/FractalAction.php b/src/lib/items/FractalAction.php index bb0e0f4d..40101e99 100644 --- a/src/lib/items/FractalAction.php +++ b/src/lib/items/FractalAction.php @@ -104,21 +104,19 @@ public function getRoute():string public function getOptionsRoute():string { - //@TODO: re-check if ($this->prefix && !empty($this->prefixSettings)) { -// $prefix = $this->prefixSettings['module'] ?? $this->prefix; if (isset($this->prefixSettings['module'])) { $prefix = $this->prefixSettings['module']; - return trim($prefix, '/') . '/' . $this->controllerId . '/options'; + return static::finalOptionsRoute($prefix, $this->controllerId); } elseif (isset($this->prefixSettings['namespace']) && str_contains($this->prefixSettings['namespace'], '\modules\\')) { $prefix = static::computeModule('\\', $this->prefixSettings['namespace']); if ($prefix) { - return trim($prefix, '/') . '/' . $this->controllerId . '/options'; + return static::finalOptionsRoute($prefix, $this->controllerId); } } elseif (isset($this->prefixSettings['path']) && str_contains($this->prefixSettings['path'], '/modules/')) { $prefix = static::computeModule('/', $this->prefixSettings['path']); if ($prefix) { - return trim($prefix, '/') . '/' . $this->controllerId . '/options'; + return static::finalOptionsRoute($prefix, $this->controllerId); } } } @@ -289,4 +287,9 @@ public static function computeModule(string $separator, string $entity): ?string } return $result[0]; } + + public static function finalOptionsRoute(string $prefix, string $controllerId): string + { + return trim($prefix, '/') . '/' . $controllerId . '/options'; + } } diff --git a/tests/specs/issue_fix/35_resolve_todo_re_check_options_route_in_fractal_action/index.php b/tests/specs/issue_fix/35_resolve_todo_re_check_options_route_in_fractal_action/index.php new file mode 100644 index 00000000..3c4da05f --- /dev/null +++ b/tests/specs/issue_fix/35_resolve_todo_re_check_options_route_in_fractal_action/index.php @@ -0,0 +1,21 @@ + '@specs/issue_fix/35_resolve_todo_re_check_options_route_in_fractal_action/index.yaml', + 'generateUrls' => true, + 'generateModels' => false, + 'excludeModels' => [ + 'Error', + ], + 'generateControllers' => true, + 'generateMigrations' => false, + 'useJsonApi' => true, + 'urlPrefixes' => [ + 'animals' => '', + '/info' => ['module' => 'petinfo', 'namespace' => '\app\modules\petinfo\controllers'], + '/forum' => ['namespace' => '\app\modules\forum\controllers'], # namespace contains "\modules\" + '/forum2' => ['path' => '@app/modules/forum2/controllers', 'namespace' => '\app\forum2\controllers'], # path contains "/modules/" + '/api/v1' => ['path' => '@app/modules/some/controllers', 'namespace' => '\app\api\v1\controllers'], # namespace contains "\modules\"; module will be "api/v1" + '/api/v2' => ['path' => '@app/modules/api/v2/controllers', 'namespace' => '\app\some\controllers'], # namespace contains "\modules\"; module will be "api/v2" + ] +]; diff --git a/tests/specs/issue_fix/35_resolve_todo_re_check_options_route_in_fractal_action/index.yaml b/tests/specs/issue_fix/35_resolve_todo_re_check_options_route_in_fractal_action/index.yaml new file mode 100644 index 00000000..5dd945dd --- /dev/null +++ b/tests/specs/issue_fix/35_resolve_todo_re_check_options_route_in_fractal_action/index.yaml @@ -0,0 +1,177 @@ +openapi: "3.0.0" +info: + version: 1.0.0 + title: Swagger Petstore + license: + name: MIT +servers: + - url: http://petstore.swagger.io/v1 +paths: + /api/v1/pets: + get: + summary: List all pets + operationId: listPets + tags: + - pets + parameters: + - name: limit + in: query + description: How many items to return at one time (max 100) + required: false + schema: + type: integer + format: int32 + responses: + '200': + description: A paged array of pets + headers: + x-next: + description: A link to the next page of responses + schema: + type: string + content: + application/json: + schema: + $ref: "#/components/schemas/Pets" + default: + description: unexpected error + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + post: + summary: Create a pet + operationId: createPets + tags: + - pets + responses: + '201': + description: Null response + default: + description: unexpected error + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + /animals/pets/{id}: + parameters: + - name: id + in: path + required: true + description: The id of the pet to update + schema: + type: string + get: + summary: Info for a specific pet + operationId: showPetById + tags: + - pets + responses: + '200': + description: Expected response to a valid request + content: + application/json: + schema: + $ref: "#/components/schemas/Pet" + default: + description: unexpected error + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + patch: + summary: update a specific pet + operationId: updatePetById + tags: + - pets + responses: + '200': + description: The updated pet + content: + application/json: + schema: + $ref: "#/components/schemas/Pet" + delete: + summary: delete a specific pet + operationId: deletePetById + tags: + - pets + responses: + '204': + description: successfully deleted pet + /petComments: + get: + description: list all pet comments + responses: + '200': + description: list of comments + /info/pet-details: + get: + description: list all pet details + responses: + '200': + description: list of details + /forum/pet2-details: + get: + description: list all pet details + responses: + '200': + description: list of details + /forum2/pet3-details: + get: + description: list all pet details + responses: + '200': + description: list of details + /api/v2/comments: + get: + description: list all pet details + responses: + '200': + description: list of details + +components: + schemas: + Pet: + description: A Pet + required: + - id + - name + properties: + id: + type: integer + format: int64 + readOnly: True + name: + type: string + store: + $ref: '#/components/schemas/Store' + tag: + type: string + x-faker: "$faker->randomElement(['one', 'two', 'three', 'four'])" + Store: + description: A store's description + required: + - id + - name + properties: + id: + type: integer + format: int64 + readOnly: True + name: + type: string + Pets: + type: array + items: + $ref: "#/components/schemas/Pet" + Error: + required: + - code + - message + properties: + code: + type: integer + format: int32 + message: + type: string diff --git a/tests/specs/petstore_urlprefixes.php b/tests/specs/petstore_urlprefixes.php index f14c4bca..8041c1fe 100644 --- a/tests/specs/petstore_urlprefixes.php +++ b/tests/specs/petstore_urlprefixes.php @@ -9,12 +9,9 @@ ], 'generateControllers' => true, 'generateMigrations' => false, - 'useJsonApi' => true, 'urlPrefixes' => [ 'animals' => '', '/info' => ['module' =>'petinfo','namespace' => '\app\modules\petinfo\controllers'], - '/fgh' => ['namespace' => '\app\modules\fgh\controllers'], - '/fgh2' => ['path' => '@app/modules/fgh2/controllers', 'namespace' => '\app\fgh2\controllers'], '/api/v1' => ['path' => '@app/modules/api/v1/controllers', 'namespace' => '\app\api\v1\controllers'] ] ]; diff --git a/tests/specs/petstore_urlprefixes.yaml b/tests/specs/petstore_urlprefixes.yaml index 7a3a549a..98701d27 100644 --- a/tests/specs/petstore_urlprefixes.yaml +++ b/tests/specs/petstore_urlprefixes.yaml @@ -111,18 +111,6 @@ paths: responses: '200': description: list of details - /fgh/pet-detail2s: - get: - description: list all pet details - responses: - '200': - description: list of details - /fgh2/pet-detail3s: - get: - description: list all pet details - responses: - '200': - description: list of details components: schemas: diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index 6f5fa668..d53ba5c5 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -362,15 +362,15 @@ public function test158BugGiiapiGeneratedRulesEnumWithTrim() } - public function testRecheckFractalActionsOptionsRoute() + // https://github.com/php-openapi/yii2-openapi/issues/35 + public function test35ResolveTodoReCheckOptionsRouteInFractalAction() { - $this->changeDbToMariadb(); - $testFile = Yii::getAlias("@specs/petstore_urlprefixes.php"); + $testFile = Yii::getAlias("@specs/issue_fix/35_resolve_todo_re_check_options_route_in_fractal_action/index.php"); $this->runGenerator($testFile); // $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ // 'recursive' => true, // ]); -// $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/158_bug_giiapi_generated_rules_enum_with_trim/maria"), [ +// $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/158_bug_giiapi_generated_rules_enum_with_trim/mysql"), [ // 'recursive' => true, // ]); // $this->checkFiles($actualFiles, $expectedFiles); From 3a44f9bb3c912739f72385cc44ade67e7aa3e77f Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Tue, 3 Sep 2024 16:45:01 +0530 Subject: [PATCH 185/358] Refactor and add test for RestAction --- src/lib/items/FractalAction.php | 53 +--------------- src/lib/items/OptionsRouteTrait.php | 62 +++++++++++++++++++ src/lib/items/RestAction.php | 12 +--- .../index.php | 2 +- tests/unit/IssueFixTest.php | 16 +++++ 5 files changed, 83 insertions(+), 62 deletions(-) create mode 100644 src/lib/items/OptionsRouteTrait.php diff --git a/src/lib/items/FractalAction.php b/src/lib/items/FractalAction.php index 40101e99..9bfba221 100644 --- a/src/lib/items/FractalAction.php +++ b/src/lib/items/FractalAction.php @@ -32,6 +32,8 @@ */ final class FractalAction extends BaseObject { + use OptionsRouteTrait; + /**@var string* */ public $id; @@ -102,27 +104,6 @@ public function getRoute():string return $this->controllerId.'/'.$this->id; } - public function getOptionsRoute():string - { - if ($this->prefix && !empty($this->prefixSettings)) { - if (isset($this->prefixSettings['module'])) { - $prefix = $this->prefixSettings['module']; - return static::finalOptionsRoute($prefix, $this->controllerId); - } elseif (isset($this->prefixSettings['namespace']) && str_contains($this->prefixSettings['namespace'], '\modules\\')) { - $prefix = static::computeModule('\\', $this->prefixSettings['namespace']); - if ($prefix) { - return static::finalOptionsRoute($prefix, $this->controllerId); - } - } elseif (isset($this->prefixSettings['path']) && str_contains($this->prefixSettings['path'], '/modules/')) { - $prefix = static::computeModule('/', $this->prefixSettings['path']); - if ($prefix) { - return static::finalOptionsRoute($prefix, $this->controllerId); - } - } - } - return $this->controllerId.'/options'; - } - public function getBaseModelName():string { return $this->modelFqn ? StringHelper::basename($this->modelFqn) : ''; @@ -262,34 +243,4 @@ public function getIdParamType(): string } return $this->params[$this->idParam]['type'] === 'integer' ? 'int' : 'string'; } - - /** - * @param string $separator - * @param string $entity path or namespace - * @return void - */ - public static function computeModule(string $separator, string $entity): ?string - { - $parts = explode($separator . 'modules' . $separator, $entity); - if (empty($parts[1])) { - return null; - } - if (str_contains($parts[1], 'controller')) { - $result = explode($separator . 'controller', $parts[1]); - $result = array_map(function ($val) { - return str_replace('\\', '/', $val); - }, $result); - } else { - $result = explode($separator, $parts[1]); - } - if (empty($result[0])) { - return null; - } - return $result[0]; - } - - public static function finalOptionsRoute(string $prefix, string $controllerId): string - { - return trim($prefix, '/') . '/' . $controllerId . '/options'; - } } diff --git a/src/lib/items/OptionsRouteTrait.php b/src/lib/items/OptionsRouteTrait.php new file mode 100644 index 00000000..3d23b37c --- /dev/null +++ b/src/lib/items/OptionsRouteTrait.php @@ -0,0 +1,62 @@ + and contributors + * @license https://github.com/cebe/yii2-openapi/blob/master/LICENSE + */ + +namespace cebe\yii2openapi\lib\items; + +trait OptionsRouteTrait +{ + public function getOptionsRoute():string + { + if ($this->prefix && !empty($this->prefixSettings)) { + if (isset($this->prefixSettings['module'])) { + $prefix = $this->prefixSettings['module']; + return static::finalOptionsRoute($prefix, $this->controllerId); + } elseif (isset($this->prefixSettings['namespace']) && str_contains($this->prefixSettings['namespace'], '\modules\\')) { + $prefix = static::computeModule('\\', $this->prefixSettings['namespace']); + if ($prefix) { + return static::finalOptionsRoute($prefix, $this->controllerId); + } + } elseif (isset($this->prefixSettings['path']) && str_contains($this->prefixSettings['path'], '/modules/')) { + $prefix = static::computeModule('/', $this->prefixSettings['path']); + if ($prefix) { + return static::finalOptionsRoute($prefix, $this->controllerId); + } + } + } + return $this->controllerId.'/options'; + } + + /** + * @param string $separator + * @param string $entity path or namespace + * @return void + */ + public static function computeModule(string $separator, string $entity): ?string + { + $parts = explode($separator . 'modules' . $separator, $entity); # /app/modules/forum/controllers => /forum/controllers + if (empty($parts[1])) { + return null; + } + if (str_contains($parts[1], 'controller')) { + $result = explode($separator . 'controller', $parts[1]); // compute everything in between "modules" and "controllers" e.g. api/v1 + $result = array_map(function ($val) { + return str_replace('\\', '/', $val); + }, $result); + } else { + $result = explode($separator, $parts[1]); # forum/controllers => forum + } + if (empty($result[0])) { + return null; + } + return $result[0]; + } + + public static function finalOptionsRoute(string $prefix, string $controllerId): string + { + return trim($prefix, '/') . '/' . $controllerId . '/options'; + } +} diff --git a/src/lib/items/RestAction.php b/src/lib/items/RestAction.php index 6852fafc..edd96025 100644 --- a/src/lib/items/RestAction.php +++ b/src/lib/items/RestAction.php @@ -31,6 +31,8 @@ */ final class RestAction extends BaseObject { + use OptionsRouteTrait; + /**@var string* */ public $id; @@ -77,16 +79,6 @@ public function getRoute():string return $this->controllerId.'/'.$this->id; } - public function getOptionsRoute():string - { - //@TODO: re-check - if ($this->prefix && !empty($this->prefixSettings)) { - $prefix = $this->prefixSettings['module'] ?? $this->prefix; - return trim($prefix, '/').'/'.$this->controllerId.'/options'; - } - return $this->controllerId.'/options'; - } - public function getBaseModelName():string { return $this->modelFqn ? StringHelper::basename($this->modelFqn) : ''; diff --git a/tests/specs/issue_fix/35_resolve_todo_re_check_options_route_in_fractal_action/index.php b/tests/specs/issue_fix/35_resolve_todo_re_check_options_route_in_fractal_action/index.php index 3c4da05f..f4e7c94b 100644 --- a/tests/specs/issue_fix/35_resolve_todo_re_check_options_route_in_fractal_action/index.php +++ b/tests/specs/issue_fix/35_resolve_todo_re_check_options_route_in_fractal_action/index.php @@ -9,7 +9,7 @@ ], 'generateControllers' => true, 'generateMigrations' => false, - 'useJsonApi' => true, + 'useJsonApi' => false, 'urlPrefixes' => [ 'animals' => '', '/info' => ['module' => 'petinfo', 'namespace' => '\app\modules\petinfo\controllers'], diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index d53ba5c5..f7843ed2 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -373,6 +373,22 @@ public function test35ResolveTodoReCheckOptionsRouteInFractalAction() // $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/158_bug_giiapi_generated_rules_enum_with_trim/mysql"), [ // 'recursive' => true, // ]); +// $this->checkFiles($actualFiles, $expectedFiles); + } + + // https://github.com/php-openapi/yii2-openapi/issues/35 + public function test35ResolveTodoReCheckOptionsRouteInRestAction() + { + $testFile = Yii::getAlias("@specs/issue_fix/35_resolve_todo_re_check_options_route_in_fractal_action/index.php"); + $content = str_replace("'useJsonApi' => true,", "'useJsonApi' => false,", file_get_contents($testFile)); + file_put_contents($testFile, $content); + $this->runGenerator($testFile); +// $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ +// 'recursive' => true, +// ]); +// $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/158_bug_giiapi_generated_rules_enum_with_trim/mysql"), [ +// 'recursive' => true, +// ]); // $this->checkFiles($actualFiles, $expectedFiles); } } From f3d71e7c39a1ab6a509a86d97cce6793fb7fcefd Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Tue, 3 Sep 2024 16:55:22 +0530 Subject: [PATCH 186/358] Complete tests --- TODO.taskpaper | 12 ++-- src/lib/items/FractalAction.php | 2 +- ...sRouteTrait.php => OptionsRoutesTrait.php} | 4 +- src/lib/items/RestAction.php | 2 +- .../mysql/config/urls.rest.php | 25 +++++++++ .../controllers/PetCommentController.php | 20 +++++++ .../controllers/base/PetCommentController.php | 32 +++++++++++ .../api/v2/controllers/CommentController.php | 20 +++++++ .../v2/controllers/base/CommentController.php | 32 +++++++++++ .../controllers/Pet2DetailController.php | 20 +++++++ .../controllers/base/Pet2DetailController.php | 32 +++++++++++ .../controllers/Pet3DetailController.php | 20 +++++++ .../controllers/base/Pet3DetailController.php | 32 +++++++++++ .../controllers/PetDetailController.php | 20 +++++++ .../controllers/base/PetDetailController.php | 32 +++++++++++ .../some/controllers/PetController.php | 15 +++++ .../some/controllers/base/PetController.php | 55 +++++++++++++++++++ tests/unit/IssueFixTest.php | 28 +++++----- 18 files changed, 379 insertions(+), 24 deletions(-) rename src/lib/items/{OptionsRouteTrait.php => OptionsRoutesTrait.php} (96%) create mode 100644 tests/specs/issue_fix/35_resolve_todo_re_check_options_route_in_fractal_action/mysql/config/urls.rest.php create mode 100644 tests/specs/issue_fix/35_resolve_todo_re_check_options_route_in_fractal_action/mysql/controllers/PetCommentController.php create mode 100644 tests/specs/issue_fix/35_resolve_todo_re_check_options_route_in_fractal_action/mysql/controllers/base/PetCommentController.php create mode 100644 tests/specs/issue_fix/35_resolve_todo_re_check_options_route_in_fractal_action/mysql/modules/api/v2/controllers/CommentController.php create mode 100644 tests/specs/issue_fix/35_resolve_todo_re_check_options_route_in_fractal_action/mysql/modules/api/v2/controllers/base/CommentController.php create mode 100644 tests/specs/issue_fix/35_resolve_todo_re_check_options_route_in_fractal_action/mysql/modules/forum/controllers/Pet2DetailController.php create mode 100644 tests/specs/issue_fix/35_resolve_todo_re_check_options_route_in_fractal_action/mysql/modules/forum/controllers/base/Pet2DetailController.php create mode 100644 tests/specs/issue_fix/35_resolve_todo_re_check_options_route_in_fractal_action/mysql/modules/forum2/controllers/Pet3DetailController.php create mode 100644 tests/specs/issue_fix/35_resolve_todo_re_check_options_route_in_fractal_action/mysql/modules/forum2/controllers/base/Pet3DetailController.php create mode 100644 tests/specs/issue_fix/35_resolve_todo_re_check_options_route_in_fractal_action/mysql/modules/petinfo/controllers/PetDetailController.php create mode 100644 tests/specs/issue_fix/35_resolve_todo_re_check_options_route_in_fractal_action/mysql/modules/petinfo/controllers/base/PetDetailController.php create mode 100644 tests/specs/issue_fix/35_resolve_todo_re_check_options_route_in_fractal_action/mysql/modules/some/controllers/PetController.php create mode 100644 tests/specs/issue_fix/35_resolve_todo_re_check_options_route_in_fractal_action/mysql/modules/some/controllers/base/PetController.php diff --git a/TODO.taskpaper b/TODO.taskpaper index 5562aa55..f91a3657 100644 --- a/TODO.taskpaper +++ b/TODO.taskpaper @@ -1,10 +1,10 @@ TODO.taskpaper ### Add validation rules by attribute name or pattern #30 - ☐ Re-check - ☐ create failing test - ☐ implement the solution - ☐ fix failing tests if any - ☐ resolve TODOs if any - ☐ review PR + ✔ Re-check @done (24-09-03 16:48) + ✔ create failing test @done (24-09-03 16:48) + ✔ implement the solution @done (24-09-03 16:48) + ✔ fix failing tests if any @done (24-09-03 16:48) + ✔ resolve TODOs if any @done (24-09-03 16:55) + ✔ review PR @done (24-09-03 16:55) ☐ delete this file and submit PR diff --git a/src/lib/items/FractalAction.php b/src/lib/items/FractalAction.php index 9bfba221..7e824c19 100644 --- a/src/lib/items/FractalAction.php +++ b/src/lib/items/FractalAction.php @@ -32,7 +32,7 @@ */ final class FractalAction extends BaseObject { - use OptionsRouteTrait; + use OptionsRoutesTrait; /**@var string* */ public $id; diff --git a/src/lib/items/OptionsRouteTrait.php b/src/lib/items/OptionsRoutesTrait.php similarity index 96% rename from src/lib/items/OptionsRouteTrait.php rename to src/lib/items/OptionsRoutesTrait.php index 3d23b37c..df9e6714 100644 --- a/src/lib/items/OptionsRouteTrait.php +++ b/src/lib/items/OptionsRoutesTrait.php @@ -7,7 +7,7 @@ namespace cebe\yii2openapi\lib\items; -trait OptionsRouteTrait +trait OptionsRoutesTrait { public function getOptionsRoute():string { @@ -15,7 +15,7 @@ public function getOptionsRoute():string if (isset($this->prefixSettings['module'])) { $prefix = $this->prefixSettings['module']; return static::finalOptionsRoute($prefix, $this->controllerId); - } elseif (isset($this->prefixSettings['namespace']) && str_contains($this->prefixSettings['namespace'], '\modules\\')) { + } elseif (isset($this->prefixSettings['namespace']) && str_contains($this->prefixSettings['namespace'], '\modules\\')) { # if `module` not present then check in namespace and then in path $prefix = static::computeModule('\\', $this->prefixSettings['namespace']); if ($prefix) { return static::finalOptionsRoute($prefix, $this->controllerId); diff --git a/src/lib/items/RestAction.php b/src/lib/items/RestAction.php index edd96025..0ef5dcc1 100644 --- a/src/lib/items/RestAction.php +++ b/src/lib/items/RestAction.php @@ -31,7 +31,7 @@ */ final class RestAction extends BaseObject { - use OptionsRouteTrait; + use OptionsRoutesTrait; /**@var string* */ public $id; diff --git a/tests/specs/issue_fix/35_resolve_todo_re_check_options_route_in_fractal_action/mysql/config/urls.rest.php b/tests/specs/issue_fix/35_resolve_todo_re_check_options_route_in_fractal_action/mysql/config/urls.rest.php new file mode 100644 index 00000000..fb1998ac --- /dev/null +++ b/tests/specs/issue_fix/35_resolve_todo_re_check_options_route_in_fractal_action/mysql/config/urls.rest.php @@ -0,0 +1,25 @@ + 'api/v1/pet/list', + 'POST api/v1/pets' => 'api/v1/pet/create', + 'GET animals/pets/' => 'pet/view', + 'DELETE animals/pets/' => 'pet/delete', + 'PATCH animals/pets/' => 'pet/update', + 'GET petComments' => 'pet-comment/list', + 'GET info/pet-details' => 'petinfo/pet-detail/list', + 'GET forum/pet2-details' => 'forum/pet2-detail/list', + 'GET forum2/pet3-details' => 'forum2/pet3-detail/list', + 'GET api/v2/comments' => 'api/v2/comment/list', + 'api/v1/pets' => 'some/pet/options', + 'animals/pets/' => 'pet/options', + 'petComments' => 'pet-comment/options', + 'info/pet-details' => 'petinfo/pet-detail/options', + 'forum/pet2-details' => 'forum/pet2-detail/options', + 'forum2/pet3-details' => 'forum2/pet3-detail/options', + 'api/v2/comments' => 'api/v2/comment/options', +]; diff --git a/tests/specs/issue_fix/35_resolve_todo_re_check_options_route_in_fractal_action/mysql/controllers/PetCommentController.php b/tests/specs/issue_fix/35_resolve_todo_re_check_options_route_in_fractal_action/mysql/controllers/PetCommentController.php new file mode 100644 index 00000000..b71a5cb0 --- /dev/null +++ b/tests/specs/issue_fix/35_resolve_todo_re_check_options_route_in_fractal_action/mysql/controllers/PetCommentController.php @@ -0,0 +1,20 @@ + [ + 'class' => \yii\rest\OptionsAction::class, + ], + ]; + } + + /** + * Checks the privilege of the current user. + * + * This method checks whether the current user has the privilege + * to run the specified action against the specified data model. + * If the user does not have access, a [[ForbiddenHttpException]] should be thrown. + * + * @param string $action the ID of the action to be executed + * @param object $model the model to be accessed. If null, it means no specific model is being accessed. + * @param array $params additional parameters + * @throws \yii\web\ForbiddenHttpException if the user does not have access + */ + abstract public function checkAccess($action, $model = null, $params = []); + + abstract public function actionList(); + +} diff --git a/tests/specs/issue_fix/35_resolve_todo_re_check_options_route_in_fractal_action/mysql/modules/api/v2/controllers/CommentController.php b/tests/specs/issue_fix/35_resolve_todo_re_check_options_route_in_fractal_action/mysql/modules/api/v2/controllers/CommentController.php new file mode 100644 index 00000000..55b0bc54 --- /dev/null +++ b/tests/specs/issue_fix/35_resolve_todo_re_check_options_route_in_fractal_action/mysql/modules/api/v2/controllers/CommentController.php @@ -0,0 +1,20 @@ + [ + 'class' => \yii\rest\OptionsAction::class, + ], + ]; + } + + /** + * Checks the privilege of the current user. + * + * This method checks whether the current user has the privilege + * to run the specified action against the specified data model. + * If the user does not have access, a [[ForbiddenHttpException]] should be thrown. + * + * @param string $action the ID of the action to be executed + * @param object $model the model to be accessed. If null, it means no specific model is being accessed. + * @param array $params additional parameters + * @throws \yii\web\ForbiddenHttpException if the user does not have access + */ + abstract public function checkAccess($action, $model = null, $params = []); + + abstract public function actionList(); + +} diff --git a/tests/specs/issue_fix/35_resolve_todo_re_check_options_route_in_fractal_action/mysql/modules/forum/controllers/Pet2DetailController.php b/tests/specs/issue_fix/35_resolve_todo_re_check_options_route_in_fractal_action/mysql/modules/forum/controllers/Pet2DetailController.php new file mode 100644 index 00000000..550fa36d --- /dev/null +++ b/tests/specs/issue_fix/35_resolve_todo_re_check_options_route_in_fractal_action/mysql/modules/forum/controllers/Pet2DetailController.php @@ -0,0 +1,20 @@ + [ + 'class' => \yii\rest\OptionsAction::class, + ], + ]; + } + + /** + * Checks the privilege of the current user. + * + * This method checks whether the current user has the privilege + * to run the specified action against the specified data model. + * If the user does not have access, a [[ForbiddenHttpException]] should be thrown. + * + * @param string $action the ID of the action to be executed + * @param object $model the model to be accessed. If null, it means no specific model is being accessed. + * @param array $params additional parameters + * @throws \yii\web\ForbiddenHttpException if the user does not have access + */ + abstract public function checkAccess($action, $model = null, $params = []); + + abstract public function actionList(); + +} diff --git a/tests/specs/issue_fix/35_resolve_todo_re_check_options_route_in_fractal_action/mysql/modules/forum2/controllers/Pet3DetailController.php b/tests/specs/issue_fix/35_resolve_todo_re_check_options_route_in_fractal_action/mysql/modules/forum2/controllers/Pet3DetailController.php new file mode 100644 index 00000000..9fbebaf9 --- /dev/null +++ b/tests/specs/issue_fix/35_resolve_todo_re_check_options_route_in_fractal_action/mysql/modules/forum2/controllers/Pet3DetailController.php @@ -0,0 +1,20 @@ + [ + 'class' => \yii\rest\OptionsAction::class, + ], + ]; + } + + /** + * Checks the privilege of the current user. + * + * This method checks whether the current user has the privilege + * to run the specified action against the specified data model. + * If the user does not have access, a [[ForbiddenHttpException]] should be thrown. + * + * @param string $action the ID of the action to be executed + * @param object $model the model to be accessed. If null, it means no specific model is being accessed. + * @param array $params additional parameters + * @throws \yii\web\ForbiddenHttpException if the user does not have access + */ + abstract public function checkAccess($action, $model = null, $params = []); + + abstract public function actionList(); + +} diff --git a/tests/specs/issue_fix/35_resolve_todo_re_check_options_route_in_fractal_action/mysql/modules/petinfo/controllers/PetDetailController.php b/tests/specs/issue_fix/35_resolve_todo_re_check_options_route_in_fractal_action/mysql/modules/petinfo/controllers/PetDetailController.php new file mode 100644 index 00000000..8f574d21 --- /dev/null +++ b/tests/specs/issue_fix/35_resolve_todo_re_check_options_route_in_fractal_action/mysql/modules/petinfo/controllers/PetDetailController.php @@ -0,0 +1,20 @@ + [ + 'class' => \yii\rest\OptionsAction::class, + ], + ]; + } + + /** + * Checks the privilege of the current user. + * + * This method checks whether the current user has the privilege + * to run the specified action against the specified data model. + * If the user does not have access, a [[ForbiddenHttpException]] should be thrown. + * + * @param string $action the ID of the action to be executed + * @param object $model the model to be accessed. If null, it means no specific model is being accessed. + * @param array $params additional parameters + * @throws \yii\web\ForbiddenHttpException if the user does not have access + */ + abstract public function checkAccess($action, $model = null, $params = []); + + abstract public function actionList(); + +} diff --git a/tests/specs/issue_fix/35_resolve_todo_re_check_options_route_in_fractal_action/mysql/modules/some/controllers/PetController.php b/tests/specs/issue_fix/35_resolve_todo_re_check_options_route_in_fractal_action/mysql/modules/some/controllers/PetController.php new file mode 100644 index 00000000..729402bc --- /dev/null +++ b/tests/specs/issue_fix/35_resolve_todo_re_check_options_route_in_fractal_action/mysql/modules/some/controllers/PetController.php @@ -0,0 +1,15 @@ + [ + 'class' => \yii\rest\IndexAction::class, + 'modelClass' => \app\models\Pet::class, + 'checkAccess' => [$this, 'checkAccess'], + ], + 'create' => [ + 'class' => \yii\rest\CreateAction::class, + 'modelClass' => \app\models\Pet::class, + 'checkAccess' => [$this, 'checkAccess'], + ], + 'view' => [ + 'class' => \yii\rest\ViewAction::class, + 'modelClass' => \app\models\Pet::class, + 'checkAccess' => [$this, 'checkAccess'], + ], + 'delete' => [ + 'class' => \yii\rest\DeleteAction::class, + 'modelClass' => \app\models\Pet::class, + 'checkAccess' => [$this, 'checkAccess'], + ], + 'update' => [ + 'class' => \yii\rest\UpdateAction::class, + 'modelClass' => \app\models\Pet::class, + 'checkAccess' => [$this, 'checkAccess'], + ], + 'options' => [ + 'class' => \yii\rest\OptionsAction::class, + ], + ]; + } + + /** + * Checks the privilege of the current user. + * + * This method checks whether the current user has the privilege + * to run the specified action against the specified data model. + * If the user does not have access, a [[ForbiddenHttpException]] should be thrown. + * + * @param string $action the ID of the action to be executed + * @param object $model the model to be accessed. If null, it means no specific model is being accessed. + * @param array $params additional parameters + * @throws \yii\web\ForbiddenHttpException if the user does not have access + */ + abstract public function checkAccess($action, $model = null, $params = []); + +} diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index f7843ed2..38bd28b3 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -367,13 +367,13 @@ public function test35ResolveTodoReCheckOptionsRouteInFractalAction() { $testFile = Yii::getAlias("@specs/issue_fix/35_resolve_todo_re_check_options_route_in_fractal_action/index.php"); $this->runGenerator($testFile); -// $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ -// 'recursive' => true, -// ]); -// $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/158_bug_giiapi_generated_rules_enum_with_trim/mysql"), [ -// 'recursive' => true, -// ]); -// $this->checkFiles($actualFiles, $expectedFiles); + $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ + 'recursive' => true, + ]); + $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/35_resolve_todo_re_check_options_route_in_fractal_action/mysql"), [ + 'recursive' => true, + ]); + $this->checkFiles($actualFiles, $expectedFiles); } // https://github.com/php-openapi/yii2-openapi/issues/35 @@ -383,12 +383,12 @@ public function test35ResolveTodoReCheckOptionsRouteInRestAction() $content = str_replace("'useJsonApi' => true,", "'useJsonApi' => false,", file_get_contents($testFile)); file_put_contents($testFile, $content); $this->runGenerator($testFile); -// $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ -// 'recursive' => true, -// ]); -// $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/158_bug_giiapi_generated_rules_enum_with_trim/mysql"), [ -// 'recursive' => true, -// ]); -// $this->checkFiles($actualFiles, $expectedFiles); + $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ + 'recursive' => true, + ]); + $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/35_resolve_todo_re_check_options_route_in_fractal_action/mysql"), [ + 'recursive' => true, + ]); + $this->checkFiles($actualFiles, $expectedFiles); } } From 689d98a8aaa1ae100dccf0be6f46d46549d39457 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Tue, 3 Sep 2024 16:56:00 +0530 Subject: [PATCH 187/358] Delete TODO.taskpaper file --- TODO.taskpaper | 10 ---------- 1 file changed, 10 deletions(-) delete mode 100644 TODO.taskpaper diff --git a/TODO.taskpaper b/TODO.taskpaper deleted file mode 100644 index f91a3657..00000000 --- a/TODO.taskpaper +++ /dev/null @@ -1,10 +0,0 @@ -TODO.taskpaper - -### Add validation rules by attribute name or pattern #30 - ✔ Re-check @done (24-09-03 16:48) - ✔ create failing test @done (24-09-03 16:48) - ✔ implement the solution @done (24-09-03 16:48) - ✔ fix failing tests if any @done (24-09-03 16:48) - ✔ resolve TODOs if any @done (24-09-03 16:55) - ✔ review PR @done (24-09-03 16:55) - ☐ delete this file and submit PR From be6b7f636cfef827c04abaf595d9c4c09fb4cf84 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Tue, 3 Sep 2024 17:15:12 +0530 Subject: [PATCH 188/358] Move package symfony/polyfill-php80 from require-dev to require --- composer.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/composer.json b/composer.json index 735e5f07..22556abf 100644 --- a/composer.json +++ b/composer.json @@ -25,13 +25,13 @@ "laminas/laminas-code": ">=3.4 <=4.13", "php-openapi/yii2-fractal": "^1.0.0", "fakerphp/faker": "^1.9", - "sam-it/yii2-mariadb": "^2.0" + "sam-it/yii2-mariadb": "^2.0", + "symfony/polyfill-php80": "^1.30" }, "require-dev": { "cebe/indent": "*", "friendsofphp/php-cs-fixer": "~2.16", "phpunit/phpunit": "^8.0", - "symfony/polyfill-php80": "^1.16", "yiisoft/yii2-gii": ">=2.1.0" }, "autoload": { From bc63159f2a17cab1be2f3c21d7cc3650d52e6d1d Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Wed, 4 Sep 2024 15:47:22 +0530 Subject: [PATCH 189/358] There is nothing to do here. Model create-update action scenario is part of the application. It is still possible but the spec will need custom extension(s) and will possibly bloat spec for no significant gain. --- src/lib/items/FractalAction.php | 1 - src/lib/items/RestAction.php | 1 - 2 files changed, 2 deletions(-) diff --git a/src/lib/items/FractalAction.php b/src/lib/items/FractalAction.php index 148ac191..20b7bb32 100644 --- a/src/lib/items/FractalAction.php +++ b/src/lib/items/FractalAction.php @@ -202,7 +202,6 @@ public function hasTemplate():bool public function getTemplate():?string { - //@TODO: Model scenarios for create/update actions return $this->templateFactory()->getTemplate(); } diff --git a/src/lib/items/RestAction.php b/src/lib/items/RestAction.php index 6852fafc..ae7823a6 100644 --- a/src/lib/items/RestAction.php +++ b/src/lib/items/RestAction.php @@ -126,7 +126,6 @@ public function hasTemplate():bool public function getTemplate():?string { - //@TODO: Model scenarios for create/update actions $template = ActionTemplates::getTemplate($this->id); if (!$template) { return null; From a080e5379eb4e91ee8138e9447953d661eff7c4f Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Fri, 6 Sep 2024 09:14:32 +0530 Subject: [PATCH 190/358] It seems like there is nothing to do here. If params is not required then we get validation error: ``` Array ( [openApiPath] => Array ( [0] => Failed to validate OpenAPI spec:
  • [/paths/~1pets~1{id}/get/parameters/1] Parameter 'required' must be true for 'in': 'path'.
) ) ``` and code generation fails. --- src/lib/items/RouteData.php | 1 - 1 file changed, 1 deletion(-) diff --git a/src/lib/items/RouteData.php b/src/lib/items/RouteData.php index c426a517..e50ab37a 100644 --- a/src/lib/items/RouteData.php +++ b/src/lib/items/RouteData.php @@ -189,7 +189,6 @@ public function init() if (array_key_exists($paramName, $pathParameters)) { //$additional = $pathParameters[$paramName]->schema->additionalProperties ?? null; $this->params[$paramName] = [ - //@TODO: use only required params //'required'=> $pathParameters[$paramName]->required, 'type' => $pathParameters[$paramName]->schema->type ?? null, //'model' => $additional ? SchemaResponseResolver::guessModelByRef($additional) : null, From 2e9d39fe72dd4316eca3286ca36b3f30019ccb0d Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Fri, 6 Sep 2024 09:20:59 +0530 Subject: [PATCH 191/358] Create PR --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 1cd2090b..3bb79307 100644 --- a/README.md +++ b/README.md @@ -568,3 +568,4 @@ Professional support, consulting as well as software development services are av https://www.cebe.cc/en/contact Development of this library is sponsored by [cebe.:cloud: "Your Professional Deployment Platform"](https://cebe.cloud). + From 433984836b40779e61cbb9f840e12a428eef5773 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Fri, 6 Sep 2024 09:41:29 +0530 Subject: [PATCH 192/358] Fix issue of inconsistent return value --- README.md | 1 - src/lib/migrations/MysqlMigrationBuilder.php | 5 ++--- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 3bb79307..1cd2090b 100644 --- a/README.md +++ b/README.md @@ -568,4 +568,3 @@ Professional support, consulting as well as software development services are av https://www.cebe.cc/en/contact Development of this library is sponsored by [cebe.:cloud: "Your Professional Deployment Platform"](https://cebe.cloud). - diff --git a/src/lib/migrations/MysqlMigrationBuilder.php b/src/lib/migrations/MysqlMigrationBuilder.php index 42354df3..359c1af1 100644 --- a/src/lib/migrations/MysqlMigrationBuilder.php +++ b/src/lib/migrations/MysqlMigrationBuilder.php @@ -117,11 +117,10 @@ protected function findTableIndexes():array public static function getColumnSchemaBuilderClass(): string { - if (ApiGenerator::isMysql()) { - return \yii\db\mysql\ColumnSchemaBuilder::class; - } elseif (ApiGenerator::isMariaDb()) { + if (ApiGenerator::isMariaDb()) { return \SamIT\Yii2\MariaDb\ColumnSchemaBuilder::class; } + return \yii\db\mysql\ColumnSchemaBuilder::class; } public function modifyCurrent(ColumnSchema $current): void From f7ed24bc094c9d9f7a216e309189c564f5172628 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Fri, 6 Sep 2024 16:24:58 +0530 Subject: [PATCH 193/358] Refactor --- src/lib/ColumnToCode.php | 3 --- src/lib/migrations/MigrationRecordBuilder.php | 1 + 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/src/lib/ColumnToCode.php b/src/lib/ColumnToCode.php index e9a570bc..cdaef236 100644 --- a/src/lib/ColumnToCode.php +++ b/src/lib/ColumnToCode.php @@ -167,9 +167,6 @@ public function getCode(bool $quoted = false):string } if ($this->rawParts['default'] === null) { $default = ''; - } elseif (ApiGenerator::isPostgres() && $this->isEnum()) { - $default = - $this->rawParts['default'] !== null ? ' DEFAULT ' . trim($this->rawParts['default']) : ''; } else { $default = $this->rawParts['default'] !== null ? ' DEFAULT ' . trim($this->rawParts['default']) : ''; } diff --git a/src/lib/migrations/MigrationRecordBuilder.php b/src/lib/migrations/MigrationRecordBuilder.php index 98ee03b8..0512bbbe 100644 --- a/src/lib/migrations/MigrationRecordBuilder.php +++ b/src/lib/migrations/MigrationRecordBuilder.php @@ -227,6 +227,7 @@ public function addFk(string $fkName, string $tableAlias, string $fkCol, string $onUpdate ); } + return ''; } public function addUniqueIndex(string $tableAlias, string $indexName, array $columns):string From 9e8905ced5ada34fb3eff5e15854956a4166dcae Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Fri, 6 Sep 2024 16:26:34 +0530 Subject: [PATCH 194/358] Refactor --- src/lib/ColumnToCode.php | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/src/lib/ColumnToCode.php b/src/lib/ColumnToCode.php index cdaef236..52460e49 100644 --- a/src/lib/ColumnToCode.php +++ b/src/lib/ColumnToCode.php @@ -165,12 +165,8 @@ public function getCode(bool $quoted = false):string array_unshift($parts, '$this'); return implode('->', array_filter(array_map('trim', $parts))); } - if ($this->rawParts['default'] === null) { - $default = ''; - } else { - $default = $this->rawParts['default'] !== null ? ' DEFAULT ' . trim($this->rawParts['default']) : ''; - } + $default = $this->rawParts['default'] !== null ? ' DEFAULT ' . trim($this->rawParts['default']) : ''; $code = $this->rawParts['type'] . ' ' . $this->rawParts['nullable'] . $default; if ((ApiGenerator::isMysql() || ApiGenerator::isMariaDb()) && $this->rawParts['position']) { $code .= ' ' . $this->rawParts['position']; From f3b3ad93183d893148cbfb1e411abd3fa8166ba0 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Fri, 6 Sep 2024 16:28:29 +0530 Subject: [PATCH 195/358] Refactor --- src/lib/ColumnToCode.php | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/lib/ColumnToCode.php b/src/lib/ColumnToCode.php index 52460e49..81062b0d 100644 --- a/src/lib/ColumnToCode.php +++ b/src/lib/ColumnToCode.php @@ -166,14 +166,15 @@ public function getCode(bool $quoted = false):string return implode('->', array_filter(array_map('trim', $parts))); } + if (ApiGenerator::isPostgres() && $this->alterByXDbType) { + return $quoted ? VarDumper::export($this->rawParts['type']) : $this->rawParts['type']; + } + $default = $this->rawParts['default'] !== null ? ' DEFAULT ' . trim($this->rawParts['default']) : ''; $code = $this->rawParts['type'] . ' ' . $this->rawParts['nullable'] . $default; if ((ApiGenerator::isMysql() || ApiGenerator::isMariaDb()) && $this->rawParts['position']) { $code .= ' ' . $this->rawParts['position']; } - if (ApiGenerator::isPostgres() && $this->alterByXDbType) { - return $quoted ? VarDumper::export($this->rawParts['type']) : $this->rawParts['type']; - } return $quoted ? VarDumper::export($code) : $code; } From e24d6c1efa5fe17b21c6fdaec6a4f23cb05f7422 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Fri, 6 Sep 2024 17:04:41 +0530 Subject: [PATCH 196/358] Remove redundant code --- src/lib/migrations/MysqlMigrationBuilder.php | 3 --- tests/unit/EnumTest.php | 2 +- 2 files changed, 1 insertion(+), 4 deletions(-) diff --git a/src/lib/migrations/MysqlMigrationBuilder.php b/src/lib/migrations/MysqlMigrationBuilder.php index 359c1af1..81061a98 100644 --- a/src/lib/migrations/MysqlMigrationBuilder.php +++ b/src/lib/migrations/MysqlMigrationBuilder.php @@ -29,9 +29,6 @@ protected function buildColumnChanges(ColumnSchema $current, ColumnSchema $desir foreach ($changed as $attr) { $newColumn->$attr = $desired->$attr; } - if (static::isEnum($newColumn)) { - $newColumn->dbType = 'enum'; // TODO this is concretely not correct - } $this->migration->addUpCode($this->recordBuilder->alterColumn($this->model->getTableAlias(), $newColumn)) ->addDownCode($this->recordBuilder->alterColumn($this->model->getTableAlias(), $current)); } diff --git a/tests/unit/EnumTest.php b/tests/unit/EnumTest.php index 8b48e249..46b08d45 100644 --- a/tests/unit/EnumTest.php +++ b/tests/unit/EnumTest.php @@ -168,7 +168,7 @@ public function testChangeToAndFromEnum() // edit enum to string and vice versa $this->deleteTables(); } - // TODO ENH enum change is more work than just changing the eunm values. And for PgSQL it is even more + // TODO ENH enum change is more work than just changing the enum values. And for PgSQL it is even more // public function testEnumValuesChange() // { // $this->deleteTables(); From d43368398168ec9e121ae9af76db6c6008d03b6a Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Fri, 6 Sep 2024 17:05:07 +0530 Subject: [PATCH 197/358] Present in https://github.com/cebe/yii2-openapi/issues/122 and https://github.com/php-openapi/yii2-openapi/issues/10 --- tests/unit/EnumTest.php | 1 - 1 file changed, 1 deletion(-) diff --git a/tests/unit/EnumTest.php b/tests/unit/EnumTest.php index 46b08d45..febc1047 100644 --- a/tests/unit/EnumTest.php +++ b/tests/unit/EnumTest.php @@ -168,7 +168,6 @@ public function testChangeToAndFromEnum() // edit enum to string and vice versa $this->deleteTables(); } - // TODO ENH enum change is more work than just changing the enum values. And for PgSQL it is even more // public function testEnumValuesChange() // { // $this->deleteTables(); From c4b4cf64c6ca22e09e5350a22c05ca4629dd1b68 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Fri, 6 Sep 2024 17:15:19 +0530 Subject: [PATCH 198/358] Already have a task in issue --- tests/unit/EnumTest.php | 1 - 1 file changed, 1 deletion(-) diff --git a/tests/unit/EnumTest.php b/tests/unit/EnumTest.php index febc1047..79797d38 100644 --- a/tests/unit/EnumTest.php +++ b/tests/unit/EnumTest.php @@ -200,7 +200,6 @@ public function testChangeToAndFromEnum() // edit enum to string and vice versa // public function testChangeEnumValues() // { - // // TODO // // add a value to list // // fix a typo in a enum value present in existing list // // remove a value from list From dcaa0d373a0e55b472b0278b11c42a0313a0220a Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Fri, 6 Sep 2024 17:21:26 +0530 Subject: [PATCH 199/358] Add sub-tasks --- TODO.taskpaper | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 TODO.taskpaper diff --git a/TODO.taskpaper b/TODO.taskpaper new file mode 100644 index 00000000..35ef3769 --- /dev/null +++ b/TODO.taskpaper @@ -0,0 +1,9 @@ +TODO.taskpaper + +### Extension FK COLUMN NAME cause error in case of column name without underscore #29 + ☐ create failing test + ☐ implement the solution + ☐ fix failing tests if any + ☐ resolve TODOs if any + ☐ review PR + ☐ delete this file and submit PR From e91e199150dd26b008a018f8aac85deca709835b Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Fri, 6 Sep 2024 17:57:47 +0530 Subject: [PATCH 200/358] Fix this issue --- src/lib/AttributeResolver.php | 20 +++++++---- .../index.php | 13 +++++++ .../index.yaml | 34 +++++++++++++++++++ tests/unit/IssueFixTest.php | 14 ++++++++ 4 files changed, 74 insertions(+), 7 deletions(-) create mode 100644 tests/specs/issue_fix/29_extension_fk_column_name_cause_error_in_case_of_column_name_without_underscore/index.php create mode 100644 tests/specs/issue_fix/29_extension_fk_column_name_cause_error_in_case_of_column_name_without_underscore/index.yaml diff --git a/src/lib/AttributeResolver.php b/src/lib/AttributeResolver.php index 0063d8df..0dabd97e 100644 --- a/src/lib/AttributeResolver.php +++ b/src/lib/AttributeResolver.php @@ -7,8 +7,6 @@ namespace cebe\yii2openapi\lib; -use cebe\yii2openapi\lib\Config; -use cebe\yii2openapi\lib\CustomSpecAttr; use cebe\yii2openapi\lib\exceptions\InvalidDefinitionException; use cebe\yii2openapi\lib\items\Attribute; use cebe\yii2openapi\lib\items\AttributeRelation; @@ -22,7 +20,6 @@ use Yii; use yii\helpers\Inflector; use yii\helpers\StringHelper; -use yii\helpers\VarDumper; use function explode; use function strpos; use function strtolower; @@ -266,7 +263,7 @@ protected function resolveProperty( $relation = Yii::createObject( AttributeRelation::class, - [$property->getName(), $relatedTableName, $relatedClassName] + [static::relationName($property->getName(), $property->fkColName), $relatedTableName, $relatedClassName] ) ->asHasOne([$fkProperty->getName() => $attribute->columnName]); $relation->onUpdateFkConstraint = $property->onUpdateFkConstraint; @@ -317,7 +314,7 @@ protected function resolveProperty( $this->relations[$property->getName()] = Yii::createObject( AttributeRelation::class, - [$property->getName(), $relatedTableName, $relatedClassName] + [static::relationName($property->getName(), $property->fkColName), $relatedTableName, $relatedClassName] ) ->asHasMany([$fkProperty->getName() => $fkProperty->getName()])->asSelfReference(); return; @@ -326,7 +323,7 @@ protected function resolveProperty( $this->relations[$property->getName()] = Yii::createObject( AttributeRelation::class, - [$property->getName(), $relatedTableName, $relatedClassName] + [static::relationName($property->getName(), $property->fkColName), $relatedTableName, $relatedClassName] ) ->asHasMany([$foreignPk => $this->schema->getPkName()]); return; @@ -345,7 +342,7 @@ protected function resolveProperty( $this->relations[$property->getName()] = Yii::createObject( AttributeRelation::class, - [$property->getName(), $relatedTableName, $relatedClassName] + [static::relationName($property->getName(), $property->fkColName), $relatedTableName, $relatedClassName] ) ->asHasMany([Inflector::camel2id($this->schemaName, '_') . '_id' => $this->schema->getPkName()]); return; @@ -492,4 +489,13 @@ protected function resolvePropertyRef(PropertySchema $property, Attribute $attri $this->attributes[$property->getName()] = $attribute->setFakerStub($this->guessFakerStub($attribute, $fkProperty)); } + + public static function relationName(string $propertyName, ?string $fkColumnName): string + { + $relationName = $propertyName; + if (!str_contains($fkColumnName, '_')) { + $relationName = strtolower($fkColumnName) === strtolower($relationName) ? $relationName . 'Rel' : $relationName; + } + return $relationName; + } } diff --git a/tests/specs/issue_fix/29_extension_fk_column_name_cause_error_in_case_of_column_name_without_underscore/index.php b/tests/specs/issue_fix/29_extension_fk_column_name_cause_error_in_case_of_column_name_without_underscore/index.php new file mode 100644 index 00000000..9ecc54a6 --- /dev/null +++ b/tests/specs/issue_fix/29_extension_fk_column_name_cause_error_in_case_of_column_name_without_underscore/index.php @@ -0,0 +1,13 @@ + '@specs/issue_fix/29_extension_fk_column_name_cause_error_in_case_of_column_name_without_underscore/index.yaml', + 'generateUrls' => true, + 'generateModels' => true, + 'excludeModels' => [ + 'Error', + ], + 'generateControllers' => true, + 'generateMigrations' => true, + 'generateModelFaker' => true, +]; diff --git a/tests/specs/issue_fix/29_extension_fk_column_name_cause_error_in_case_of_column_name_without_underscore/index.yaml b/tests/specs/issue_fix/29_extension_fk_column_name_cause_error_in_case_of_column_name_without_underscore/index.yaml new file mode 100644 index 00000000..e15bc483 --- /dev/null +++ b/tests/specs/issue_fix/29_extension_fk_column_name_cause_error_in_case_of_column_name_without_underscore/index.yaml @@ -0,0 +1,34 @@ +openapi: "3.0.0" +info: + version: 1.0.0 + title: Extension FK COLUMN NAME cause error in case of column name without underscore \#29 +paths: + /: + get: + summary: List + operationId: list + responses: + '200': + description: The information + +components: + schemas: + User: + type: object + properties: + id: + type: integer + name: + type: string + Post: + type: object + properties: + id: + type: integer + content: + type: string + user: + allOf: + - $ref: '#/components/schemas/User' + - x-fk-column-name: user + diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index b6c7abdb..ae6dfa61 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -360,4 +360,18 @@ public function test158BugGiiapiGeneratedRulesEnumWithTrim() ]); $this->checkFiles($actualFiles, $expectedFiles); } + + // https://github.com/php-openapi/yii2-openapi/issues/29 + public function test29ExtensionFkColumnNameCauseErrorInCaseOfColumnNameWithoutUnderscore() + { + $testFile = Yii::getAlias("@specs/issue_fix/29_extension_fk_column_name_cause_error_in_case_of_column_name_without_underscore/index.php"); + $this->runGenerator($testFile); + // $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ + // 'recursive' => true, + // ]); + // $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/29_extension_fk_column_name_cause_error_in_case_of_column_name_without_underscore/mysql"), [ + // 'recursive' => true, + // ]); + // $this->checkFiles($actualFiles, $expectedFiles); // TODO + } } From 11adaf2f9327a89ec6e26d0b409d4cd1198bac26 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Fri, 6 Sep 2024 18:47:29 +0530 Subject: [PATCH 201/358] Fix failing tests in PHP >= 8 --- src/lib/AttributeResolver.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/lib/AttributeResolver.php b/src/lib/AttributeResolver.php index 0dabd97e..cbda4267 100644 --- a/src/lib/AttributeResolver.php +++ b/src/lib/AttributeResolver.php @@ -493,7 +493,7 @@ protected function resolvePropertyRef(PropertySchema $property, Attribute $attri public static function relationName(string $propertyName, ?string $fkColumnName): string { $relationName = $propertyName; - if (!str_contains($fkColumnName, '_')) { + if (!str_contains((string) $fkColumnName, '_')) { $relationName = strtolower($fkColumnName) === strtolower($relationName) ? $relationName . 'Rel' : $relationName; } return $relationName; From 216d375d4818fb0cfd9c364f8f256cc327167bee Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Fri, 6 Sep 2024 18:57:37 +0530 Subject: [PATCH 202/358] Fix failing tests --- src/lib/AttributeResolver.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/lib/AttributeResolver.php b/src/lib/AttributeResolver.php index cbda4267..cd770503 100644 --- a/src/lib/AttributeResolver.php +++ b/src/lib/AttributeResolver.php @@ -494,7 +494,7 @@ public static function relationName(string $propertyName, ?string $fkColumnName) { $relationName = $propertyName; if (!str_contains((string) $fkColumnName, '_')) { - $relationName = strtolower($fkColumnName) === strtolower($relationName) ? $relationName . 'Rel' : $relationName; + $relationName = strtolower((string) $fkColumnName) === strtolower($relationName) ? $relationName . 'Rel' : $relationName; } return $relationName; } From e1e5f844110610c15112cb74f9954bef1a7e9220 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Fri, 6 Sep 2024 18:58:55 +0530 Subject: [PATCH 203/358] Refactor --- src/lib/AttributeResolver.php | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/lib/AttributeResolver.php b/src/lib/AttributeResolver.php index cd770503..e8f936cb 100644 --- a/src/lib/AttributeResolver.php +++ b/src/lib/AttributeResolver.php @@ -492,9 +492,10 @@ protected function resolvePropertyRef(PropertySchema $property, Attribute $attri public static function relationName(string $propertyName, ?string $fkColumnName): string { + $fkColumnName = (string) $fkColumnName; $relationName = $propertyName; - if (!str_contains((string) $fkColumnName, '_')) { - $relationName = strtolower((string) $fkColumnName) === strtolower($relationName) ? $relationName . 'Rel' : $relationName; + if (!str_contains($fkColumnName, '_')) { + $relationName = strtolower($fkColumnName) === strtolower($relationName) ? $relationName . 'Rel' : $relationName; } return $relationName; } From ccd7794ab665b216770a5a243cf18c00927592db Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Fri, 6 Sep 2024 19:46:42 +0530 Subject: [PATCH 204/358] Fix relation name in `targetRelation` bug --- src/lib/ValidationRulesBuilder.php | 6 +++--- .../index.php | 4 ++-- .../index.yaml | 1 - 3 files changed, 5 insertions(+), 6 deletions(-) diff --git a/src/lib/ValidationRulesBuilder.php b/src/lib/ValidationRulesBuilder.php index 3f3c1398..d1008cc1 100644 --- a/src/lib/ValidationRulesBuilder.php +++ b/src/lib/ValidationRulesBuilder.php @@ -10,8 +10,6 @@ use cebe\yii2openapi\lib\items\Attribute; use cebe\yii2openapi\lib\items\DbModel; use cebe\yii2openapi\lib\items\ValidationRule; -use yii\helpers\VarDumper; -use yii\validators\DateValidator; use function count; use function implode; use function in_array; @@ -162,10 +160,12 @@ private function addExistRules(array $relations):void } elseif ($attribute->phpType === 'string') { $this->addStringRule($attribute); } + + $targetRelation = AttributeResolver::relationName($attribute->columnName, $attribute->propertyName); $this->rules[$attribute->columnName . '_exist'] = new ValidationRule( [$attribute->columnName], 'exist', - ['targetRelation' => $attribute->camelName()] + ['targetRelation' => $targetRelation] ); } } diff --git a/tests/specs/issue_fix/29_extension_fk_column_name_cause_error_in_case_of_column_name_without_underscore/index.php b/tests/specs/issue_fix/29_extension_fk_column_name_cause_error_in_case_of_column_name_without_underscore/index.php index 9ecc54a6..f818842e 100644 --- a/tests/specs/issue_fix/29_extension_fk_column_name_cause_error_in_case_of_column_name_without_underscore/index.php +++ b/tests/specs/issue_fix/29_extension_fk_column_name_cause_error_in_case_of_column_name_without_underscore/index.php @@ -2,12 +2,12 @@ return [ 'openApiPath' => '@specs/issue_fix/29_extension_fk_column_name_cause_error_in_case_of_column_name_without_underscore/index.yaml', - 'generateUrls' => true, + 'generateUrls' => false, 'generateModels' => true, 'excludeModels' => [ 'Error', ], - 'generateControllers' => true, + 'generateControllers' => false, 'generateMigrations' => true, 'generateModelFaker' => true, ]; diff --git a/tests/specs/issue_fix/29_extension_fk_column_name_cause_error_in_case_of_column_name_without_underscore/index.yaml b/tests/specs/issue_fix/29_extension_fk_column_name_cause_error_in_case_of_column_name_without_underscore/index.yaml index e15bc483..6a872595 100644 --- a/tests/specs/issue_fix/29_extension_fk_column_name_cause_error_in_case_of_column_name_without_underscore/index.yaml +++ b/tests/specs/issue_fix/29_extension_fk_column_name_cause_error_in_case_of_column_name_without_underscore/index.yaml @@ -31,4 +31,3 @@ components: allOf: - $ref: '#/components/schemas/User' - x-fk-column-name: user - From 052b89e1883ff8aff05fa3d4922db1690a051300 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Fri, 6 Sep 2024 19:55:18 +0530 Subject: [PATCH 205/358] Fix bug --- src/lib/ValidationRulesBuilder.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/lib/ValidationRulesBuilder.php b/src/lib/ValidationRulesBuilder.php index d1008cc1..2ef9a684 100644 --- a/src/lib/ValidationRulesBuilder.php +++ b/src/lib/ValidationRulesBuilder.php @@ -161,7 +161,7 @@ private function addExistRules(array $relations):void $this->addStringRule($attribute); } - $targetRelation = AttributeResolver::relationName($attribute->columnName, $attribute->propertyName); + $targetRelation = AttributeResolver::relationName($attribute->propertyName, $attribute->fkColName); $this->rules[$attribute->columnName . '_exist'] = new ValidationRule( [$attribute->columnName], 'exist', From 69d30028b7b449e56bc8d1f769b972a2d4b9d5e2 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Fri, 6 Sep 2024 20:09:57 +0530 Subject: [PATCH 206/358] Fix bug 2 --- src/lib/ValidationRulesBuilder.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/lib/ValidationRulesBuilder.php b/src/lib/ValidationRulesBuilder.php index 2ef9a684..0c5403f2 100644 --- a/src/lib/ValidationRulesBuilder.php +++ b/src/lib/ValidationRulesBuilder.php @@ -10,6 +10,7 @@ use cebe\yii2openapi\lib\items\Attribute; use cebe\yii2openapi\lib\items\DbModel; use cebe\yii2openapi\lib\items\ValidationRule; +use yii\helpers\Inflector; use function count; use function implode; use function in_array; @@ -161,7 +162,7 @@ private function addExistRules(array $relations):void $this->addStringRule($attribute); } - $targetRelation = AttributeResolver::relationName($attribute->propertyName, $attribute->fkColName); + $targetRelation = AttributeResolver::relationName(Inflector::variablize($attribute->camelName()), $attribute->fkColName); $this->rules[$attribute->columnName . '_exist'] = new ValidationRule( [$attribute->columnName], 'exist', From b8192f5929d25a984c559b39bd64915404d0750a Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Fri, 6 Sep 2024 20:23:33 +0530 Subject: [PATCH 207/358] Fix failing tests --- tests/specs/blog/models/base/Comment.php | 4 ++-- tests/specs/blog/models/base/Post.php | 4 ++-- tests/specs/blog_v2/models/base/Comment.php | 4 ++-- tests/specs/blog_v2/models/base/Post.php | 4 ++-- tests/specs/fk_col_name/app/models/base/Webhook.php | 4 ++-- tests/specs/fk_col_name_index/app/models/base/Webhook.php | 6 +++--- .../maria/models/base/Contact.php | 2 +- .../app/models/base/Order.php | 2 +- .../pgsql/models/base/Contact.php | 2 +- .../app/models/base/E123.php | 6 +++--- tests/specs/many2many/models/base/Photos2Posts.php | 4 ++-- tests/specs/many2many/models/base/PostsAttaches.php | 4 ++-- tests/specs/many2many/models/base/PostsGallery.php | 4 ++-- tests/specs/menu/models/base/Menu.php | 2 +- tests/specs/petstore/models/base/Pet.php | 2 +- tests/specs/petstore_jsonapi/models/base/PetStatistic.php | 2 +- tests/specs/petstore_namespace/mymodels/base/Pet.php | 2 +- tests/specs/relations_in_faker/app/models/base/A123.php | 2 +- tests/specs/relations_in_faker/app/models/base/Domain.php | 2 +- tests/unit/ValidatorRulesBuilderTest.php | 2 +- 20 files changed, 32 insertions(+), 32 deletions(-) diff --git a/tests/specs/blog/models/base/Comment.php b/tests/specs/blog/models/base/Comment.php index 44cd42fc..1cf49178 100644 --- a/tests/specs/blog/models/base/Comment.php +++ b/tests/specs/blog/models/base/Comment.php @@ -28,9 +28,9 @@ public function rules() 'trim' => [['post_id'], 'trim'], 'required' => [['post_id', 'author_id', 'message', 'created_at'], 'required'], 'post_id_string' => [['post_id'], 'string', 'max' => 128], - 'post_id_exist' => [['post_id'], 'exist', 'targetRelation' => 'Post'], + 'post_id_exist' => [['post_id'], 'exist', 'targetRelation' => 'post'], 'author_id_integer' => [['author_id'], 'integer'], - 'author_id_exist' => [['author_id'], 'exist', 'targetRelation' => 'Author'], + 'author_id_exist' => [['author_id'], 'exist', 'targetRelation' => 'author'], 'message_default' => [['message'], 'default', 'value' => []], 'meta_data_default' => [['meta_data'], 'default', 'value' => []], 'created_at_integer' => [['created_at'], 'integer'], diff --git a/tests/specs/blog/models/base/Post.php b/tests/specs/blog/models/base/Post.php index 457978b5..d1949af2 100644 --- a/tests/specs/blog/models/base/Post.php +++ b/tests/specs/blog/models/base/Post.php @@ -30,9 +30,9 @@ public function rules() 'trim' => [['title', 'slug', 'created_at'], 'trim'], 'required' => [['title', 'category_id', 'active'], 'required'], 'category_id_integer' => [['category_id'], 'integer'], - 'category_id_exist' => [['category_id'], 'exist', 'targetRelation' => 'Category'], + 'category_id_exist' => [['category_id'], 'exist', 'targetRelation' => 'category'], 'created_by_id_integer' => [['created_by_id'], 'integer'], - 'created_by_id_exist' => [['created_by_id'], 'exist', 'targetRelation' => 'CreatedBy'], + 'created_by_id_exist' => [['created_by_id'], 'exist', 'targetRelation' => 'createdBy'], 'title_unique' => [['title'], 'unique'], 'slug_unique' => [['slug'], 'unique'], 'title_string' => [['title'], 'string', 'max' => 255], diff --git a/tests/specs/blog_v2/models/base/Comment.php b/tests/specs/blog_v2/models/base/Comment.php index a732c5c0..0f9fc288 100644 --- a/tests/specs/blog_v2/models/base/Comment.php +++ b/tests/specs/blog_v2/models/base/Comment.php @@ -28,9 +28,9 @@ public function rules() 'trim' => [['message', 'meta_data', 'created_at'], 'trim'], 'required' => [['post_id', 'message', 'created_at'], 'required'], 'post_id_integer' => [['post_id'], 'integer'], - 'post_id_exist' => [['post_id'], 'exist', 'targetRelation' => 'Post'], + 'post_id_exist' => [['post_id'], 'exist', 'targetRelation' => 'post'], 'user_id_integer' => [['user_id'], 'integer'], - 'user_id_exist' => [['user_id'], 'exist', 'targetRelation' => 'User'], + 'user_id_exist' => [['user_id'], 'exist', 'targetRelation' => 'user'], 'message_string' => [['message'], 'string'], 'meta_data_string' => [['meta_data'], 'string', 'min' => 1, 'max' => 300], 'meta_data_default' => [['meta_data'], 'default', 'value' => ''], diff --git a/tests/specs/blog_v2/models/base/Post.php b/tests/specs/blog_v2/models/base/Post.php index 44fe4275..333167e6 100644 --- a/tests/specs/blog_v2/models/base/Post.php +++ b/tests/specs/blog_v2/models/base/Post.php @@ -32,9 +32,9 @@ public function rules() 'trim' => [['title', 'slug', 'created_at'], 'trim'], 'required' => [['title', 'category_id', 'active'], 'required'], 'category_id_integer' => [['category_id'], 'integer'], - 'category_id_exist' => [['category_id'], 'exist', 'targetRelation' => 'Category'], + 'category_id_exist' => [['category_id'], 'exist', 'targetRelation' => 'category'], 'created_by_id_integer' => [['created_by_id'], 'integer'], - 'created_by_id_exist' => [['created_by_id'], 'exist', 'targetRelation' => 'CreatedBy'], + 'created_by_id_exist' => [['created_by_id'], 'exist', 'targetRelation' => 'createdBy'], 'title_unique' => [['title'], 'unique'], 'title_string' => [['title'], 'string', 'max' => 255], 'slug_string' => [['slug'], 'string', 'min' => 1, 'max' => 200], diff --git a/tests/specs/fk_col_name/app/models/base/Webhook.php b/tests/specs/fk_col_name/app/models/base/Webhook.php index 8746e8f0..6b1d0b44 100644 --- a/tests/specs/fk_col_name/app/models/base/Webhook.php +++ b/tests/specs/fk_col_name/app/models/base/Webhook.php @@ -25,9 +25,9 @@ public function rules() return [ 'trim' => [['name'], 'trim'], 'user_id_integer' => [['user_id'], 'integer'], - 'user_id_exist' => [['user_id'], 'exist', 'targetRelation' => 'User'], + 'user_id_exist' => [['user_id'], 'exist', 'targetRelation' => 'user'], 'redelivery_of_integer' => [['redelivery_of'], 'integer'], - 'redelivery_of_exist' => [['redelivery_of'], 'exist', 'targetRelation' => 'RedeliveryOf'], + 'redelivery_of_exist' => [['redelivery_of'], 'exist', 'targetRelation' => 'redeliveryOf'], 'name_string' => [['name'], 'string'], ]; } diff --git a/tests/specs/fk_col_name_index/app/models/base/Webhook.php b/tests/specs/fk_col_name_index/app/models/base/Webhook.php index 29a40568..7adabbcc 100644 --- a/tests/specs/fk_col_name_index/app/models/base/Webhook.php +++ b/tests/specs/fk_col_name_index/app/models/base/Webhook.php @@ -27,11 +27,11 @@ public function rules() return [ 'trim' => [['name'], 'trim'], 'user_id_integer' => [['user_id'], 'integer'], - 'user_id_exist' => [['user_id'], 'exist', 'targetRelation' => 'User'], + 'user_id_exist' => [['user_id'], 'exist', 'targetRelation' => 'user'], 'redelivery_of_integer' => [['redelivery_of'], 'integer'], - 'redelivery_of_exist' => [['redelivery_of'], 'exist', 'targetRelation' => 'RedeliveryOf'], + 'redelivery_of_exist' => [['redelivery_of'], 'exist', 'targetRelation' => 'redeliveryOf'], 'rd_abc_2_integer' => [['rd_abc_2'], 'integer'], - 'rd_abc_2_exist' => [['rd_abc_2'], 'exist', 'targetRelation' => 'Rd2'], + 'rd_abc_2_exist' => [['rd_abc_2'], 'exist', 'targetRelation' => 'rd2'], 'user_id_name_unique' => [['user_id', 'name'], 'unique', 'targetAttribute' => [ 'user_id', 'name', diff --git a/tests/specs/issue_fix/159_bug_giiapi_generated_rules_emailid/maria/models/base/Contact.php b/tests/specs/issue_fix/159_bug_giiapi_generated_rules_emailid/maria/models/base/Contact.php index efbd8b32..f77b3725 100644 --- a/tests/specs/issue_fix/159_bug_giiapi_generated_rules_emailid/maria/models/base/Contact.php +++ b/tests/specs/issue_fix/159_bug_giiapi_generated_rules_emailid/maria/models/base/Contact.php @@ -25,7 +25,7 @@ public function rules() 'trim' => [['nickname'], 'trim'], 'required' => [['mailing_id'], 'required'], 'mailing_id_integer' => [['mailing_id'], 'integer'], - 'mailing_id_exist' => [['mailing_id'], 'exist', 'targetRelation' => 'Mailing'], + 'mailing_id_exist' => [['mailing_id'], 'exist', 'targetRelation' => 'mailing'], 'active_boolean' => [['active'], 'boolean'], 'active_default' => [['active'], 'default', 'value' => false], 'nickname_string' => [['nickname'], 'string'], diff --git a/tests/specs/issue_fix/162_bug_dollarref_with_x_faker/app/models/base/Order.php b/tests/specs/issue_fix/162_bug_dollarref_with_x_faker/app/models/base/Order.php index 74472cd5..89d5b559 100644 --- a/tests/specs/issue_fix/162_bug_dollarref_with_x_faker/app/models/base/Order.php +++ b/tests/specs/issue_fix/162_bug_dollarref_with_x_faker/app/models/base/Order.php @@ -24,7 +24,7 @@ public function rules() return [ 'trim' => [['name', 'name2'], 'trim'], 'invoice_id_integer' => [['invoice_id'], 'integer'], - 'invoice_id_exist' => [['invoice_id'], 'exist', 'targetRelation' => 'Invoice'], + 'invoice_id_exist' => [['invoice_id'], 'exist', 'targetRelation' => 'invoice'], 'name_string' => [['name'], 'string'], 'name2_string' => [['name2'], 'string'], ]; diff --git a/tests/specs/issue_fix/175_bug_allof_with_multiple_dollarrefs/pgsql/models/base/Contact.php b/tests/specs/issue_fix/175_bug_allof_with_multiple_dollarrefs/pgsql/models/base/Contact.php index 21a2e7f1..ec235266 100644 --- a/tests/specs/issue_fix/175_bug_allof_with_multiple_dollarrefs/pgsql/models/base/Contact.php +++ b/tests/specs/issue_fix/175_bug_allof_with_multiple_dollarrefs/pgsql/models/base/Contact.php @@ -25,7 +25,7 @@ public function rules() 'trim' => [['nickname'], 'trim'], 'required' => [['account_id'], 'required'], 'account_id_integer' => [['account_id'], 'integer'], - 'account_id_exist' => [['account_id'], 'exist', 'targetRelation' => 'Account'], + 'account_id_exist' => [['account_id'], 'exist', 'targetRelation' => 'account'], 'active_boolean' => [['active'], 'boolean'], 'active_default' => [['active'], 'default', 'value' => false], 'nickname_string' => [['nickname'], 'string'], diff --git a/tests/specs/issue_fix/model_name_more_than_once_in_faker_148/app/models/base/E123.php b/tests/specs/issue_fix/model_name_more_than_once_in_faker_148/app/models/base/E123.php index cbec768a..ac4dce54 100644 --- a/tests/specs/issue_fix/model_name_more_than_once_in_faker_148/app/models/base/E123.php +++ b/tests/specs/issue_fix/model_name_more_than_once_in_faker_148/app/models/base/E123.php @@ -27,11 +27,11 @@ public function rules() return [ 'trim' => [['name'], 'trim'], 'account_id_integer' => [['account_id'], 'integer'], - 'account_id_exist' => [['account_id'], 'exist', 'targetRelation' => 'Account'], + 'account_id_exist' => [['account_id'], 'exist', 'targetRelation' => 'account'], 'account_2_id_integer' => [['account_2_id'], 'integer'], - 'account_2_id_exist' => [['account_2_id'], 'exist', 'targetRelation' => 'Account2'], + 'account_2_id_exist' => [['account_2_id'], 'exist', 'targetRelation' => 'account2'], 'account_3_id_integer' => [['account_3_id'], 'integer'], - 'account_3_id_exist' => [['account_3_id'], 'exist', 'targetRelation' => 'Account3'], + 'account_3_id_exist' => [['account_3_id'], 'exist', 'targetRelation' => 'account3'], 'name_string' => [['name'], 'string'], ]; } diff --git a/tests/specs/many2many/models/base/Photos2Posts.php b/tests/specs/many2many/models/base/Photos2Posts.php index 523ecada..80ef4f97 100644 --- a/tests/specs/many2many/models/base/Photos2Posts.php +++ b/tests/specs/many2many/models/base/Photos2Posts.php @@ -23,9 +23,9 @@ public function rules() { return [ 'photo_id_integer' => [['photo_id'], 'integer'], - 'photo_id_exist' => [['photo_id'], 'exist', 'targetRelation' => 'Photo'], + 'photo_id_exist' => [['photo_id'], 'exist', 'targetRelation' => 'photo'], 'post_id_integer' => [['post_id'], 'integer'], - 'post_id_exist' => [['post_id'], 'exist', 'targetRelation' => 'Post'], + 'post_id_exist' => [['post_id'], 'exist', 'targetRelation' => 'post'], ]; } diff --git a/tests/specs/many2many/models/base/PostsAttaches.php b/tests/specs/many2many/models/base/PostsAttaches.php index 54b8adda..8b30ab15 100644 --- a/tests/specs/many2many/models/base/PostsAttaches.php +++ b/tests/specs/many2many/models/base/PostsAttaches.php @@ -23,9 +23,9 @@ public function rules() { return [ 'attach_id_integer' => [['attach_id'], 'integer'], - 'attach_id_exist' => [['attach_id'], 'exist', 'targetRelation' => 'Attach'], + 'attach_id_exist' => [['attach_id'], 'exist', 'targetRelation' => 'attach'], 'target_id_integer' => [['target_id'], 'integer'], - 'target_id_exist' => [['target_id'], 'exist', 'targetRelation' => 'Target'], + 'target_id_exist' => [['target_id'], 'exist', 'targetRelation' => 'target'], ]; } diff --git a/tests/specs/many2many/models/base/PostsGallery.php b/tests/specs/many2many/models/base/PostsGallery.php index 61cfd67f..0adea949 100644 --- a/tests/specs/many2many/models/base/PostsGallery.php +++ b/tests/specs/many2many/models/base/PostsGallery.php @@ -23,9 +23,9 @@ public function rules() { return [ 'image_id_integer' => [['image_id'], 'integer'], - 'image_id_exist' => [['image_id'], 'exist', 'targetRelation' => 'Image'], + 'image_id_exist' => [['image_id'], 'exist', 'targetRelation' => 'image'], 'article_id_integer' => [['article_id'], 'integer'], - 'article_id_exist' => [['article_id'], 'exist', 'targetRelation' => 'Article'], + 'article_id_exist' => [['article_id'], 'exist', 'targetRelation' => 'article'], 'is_cover_boolean' => [['is_cover'], 'boolean'], ]; } diff --git a/tests/specs/menu/models/base/Menu.php b/tests/specs/menu/models/base/Menu.php index 582d952d..a92755f6 100644 --- a/tests/specs/menu/models/base/Menu.php +++ b/tests/specs/menu/models/base/Menu.php @@ -27,7 +27,7 @@ public function rules() 'trim' => [['name'], 'trim'], 'required' => [['name'], 'required'], 'parent_id_integer' => [['parent_id'], 'integer'], - 'parent_id_exist' => [['parent_id'], 'exist', 'targetRelation' => 'Parent'], + 'parent_id_exist' => [['parent_id'], 'exist', 'targetRelation' => 'parent'], 'name_string' => [['name'], 'string', 'min' => 3, 'max' => 100], 'args_default' => [['args'], 'default', 'value' => [ 'foo', diff --git a/tests/specs/petstore/models/base/Pet.php b/tests/specs/petstore/models/base/Pet.php index 039764d2..62f78428 100644 --- a/tests/specs/petstore/models/base/Pet.php +++ b/tests/specs/petstore/models/base/Pet.php @@ -25,7 +25,7 @@ public function rules() 'trim' => [['name', 'tag'], 'trim'], 'required' => [['name'], 'required'], 'store_id_integer' => [['store_id'], 'integer'], - 'store_id_exist' => [['store_id'], 'exist', 'targetRelation' => 'Store'], + 'store_id_exist' => [['store_id'], 'exist', 'targetRelation' => 'store'], 'name_string' => [['name'], 'string'], 'tag_string' => [['tag'], 'string'], ]; diff --git a/tests/specs/petstore_jsonapi/models/base/PetStatistic.php b/tests/specs/petstore_jsonapi/models/base/PetStatistic.php index ba8af41d..adc6e8fd 100644 --- a/tests/specs/petstore_jsonapi/models/base/PetStatistic.php +++ b/tests/specs/petstore_jsonapi/models/base/PetStatistic.php @@ -54,7 +54,7 @@ public function rules() return [ 'trim' => [['title', 'summary'], 'trim'], 'parentPet_id_integer' => [['parentPet_id'], 'integer'], - 'parentPet_id_exist' => [['parentPet_id'], 'exist', 'targetRelation' => 'ParentPet'], + 'parentPet_id_exist' => [['parentPet_id'], 'exist', 'targetRelation' => 'parentPet'], 'title_string' => [['title'], 'string'], 'dogsCount_integer' => [['dogsCount'], 'integer'], 'catsCount_integer' => [['catsCount'], 'integer'], diff --git a/tests/specs/petstore_namespace/mymodels/base/Pet.php b/tests/specs/petstore_namespace/mymodels/base/Pet.php index 58750645..cb549e8f 100644 --- a/tests/specs/petstore_namespace/mymodels/base/Pet.php +++ b/tests/specs/petstore_namespace/mymodels/base/Pet.php @@ -25,7 +25,7 @@ public function rules() 'trim' => [['name', 'tag'], 'trim'], 'required' => [['name'], 'required'], 'store_id_integer' => [['store_id'], 'integer'], - 'store_id_exist' => [['store_id'], 'exist', 'targetRelation' => 'Store'], + 'store_id_exist' => [['store_id'], 'exist', 'targetRelation' => 'store'], 'name_string' => [['name'], 'string'], 'tag_string' => [['tag'], 'string'], ]; diff --git a/tests/specs/relations_in_faker/app/models/base/A123.php b/tests/specs/relations_in_faker/app/models/base/A123.php index 9836dc3b..6aaf6df5 100644 --- a/tests/specs/relations_in_faker/app/models/base/A123.php +++ b/tests/specs/relations_in_faker/app/models/base/A123.php @@ -23,7 +23,7 @@ public function rules() return [ 'trim' => [['name'], 'trim'], 'b123_id_integer' => [['b123_id'], 'integer'], - 'b123_id_exist' => [['b123_id'], 'exist', 'targetRelation' => 'B123'], + 'b123_id_exist' => [['b123_id'], 'exist', 'targetRelation' => 'b123'], 'name_string' => [['name'], 'string'], ]; } diff --git a/tests/specs/relations_in_faker/app/models/base/Domain.php b/tests/specs/relations_in_faker/app/models/base/Domain.php index 3f861f9e..d378bbe3 100644 --- a/tests/specs/relations_in_faker/app/models/base/Domain.php +++ b/tests/specs/relations_in_faker/app/models/base/Domain.php @@ -26,7 +26,7 @@ public function rules() 'trim' => [['name'], 'trim'], 'required' => [['name', 'account_id'], 'required'], 'account_id_integer' => [['account_id'], 'integer'], - 'account_id_exist' => [['account_id'], 'exist', 'targetRelation' => 'Account'], + 'account_id_exist' => [['account_id'], 'exist', 'targetRelation' => 'account'], 'name_string' => [['name'], 'string', 'max' => 128], ]; } diff --git a/tests/unit/ValidatorRulesBuilderTest.php b/tests/unit/ValidatorRulesBuilderTest.php index 43343df6..af018565 100644 --- a/tests/unit/ValidatorRulesBuilderTest.php +++ b/tests/unit/ValidatorRulesBuilderTest.php @@ -48,7 +48,7 @@ public function testBuild() ], 'trim'), 'required' => new ValidationRule(['title', 'category_id', 'required_with_def'], 'required'), 'category_id_integer' => new ValidationRule(['category_id'], 'integer'), - 'category_id_exist' => new ValidationRule(['category_id'], 'exist', ['targetRelation' => 'Category']), + 'category_id_exist' => new ValidationRule(['category_id'], 'exist', ['targetRelation' => 'category']), 'title_active_unique' => new ValidationRule(['title', 'active'], 'unique', [ 'targetAttribute' => ['title', 'active'], From be59c824495c2ff3eb92ecd9be8d1a7ff988ce98 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Fri, 6 Sep 2024 20:24:44 +0530 Subject: [PATCH 208/358] Fix failing tests 2 --- tests/specs/relations_in_faker/app/models/base/B123.php | 2 +- tests/specs/relations_in_faker/app/models/base/E123.php | 2 +- tests/specs/relations_in_faker/app/models/base/Routing.php | 6 +++--- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/tests/specs/relations_in_faker/app/models/base/B123.php b/tests/specs/relations_in_faker/app/models/base/B123.php index f05fe320..8e5caa5a 100644 --- a/tests/specs/relations_in_faker/app/models/base/B123.php +++ b/tests/specs/relations_in_faker/app/models/base/B123.php @@ -23,7 +23,7 @@ public function rules() return [ 'trim' => [['name'], 'trim'], 'c123_id_integer' => [['c123_id'], 'integer'], - 'c123_id_exist' => [['c123_id'], 'exist', 'targetRelation' => 'C123'], + 'c123_id_exist' => [['c123_id'], 'exist', 'targetRelation' => 'c123'], 'name_string' => [['name'], 'string'], ]; } diff --git a/tests/specs/relations_in_faker/app/models/base/E123.php b/tests/specs/relations_in_faker/app/models/base/E123.php index 6eb43814..c1a85c27 100644 --- a/tests/specs/relations_in_faker/app/models/base/E123.php +++ b/tests/specs/relations_in_faker/app/models/base/E123.php @@ -23,7 +23,7 @@ public function rules() return [ 'trim' => [['name'], 'trim'], 'b123_id_integer' => [['b123_id'], 'integer'], - 'b123_id_exist' => [['b123_id'], 'exist', 'targetRelation' => 'B123'], + 'b123_id_exist' => [['b123_id'], 'exist', 'targetRelation' => 'b123'], 'name_string' => [['name'], 'string'], ]; } diff --git a/tests/specs/relations_in_faker/app/models/base/Routing.php b/tests/specs/relations_in_faker/app/models/base/Routing.php index 71a31b81..40e707e6 100644 --- a/tests/specs/relations_in_faker/app/models/base/Routing.php +++ b/tests/specs/relations_in_faker/app/models/base/Routing.php @@ -32,11 +32,11 @@ public function rules() 'trim' => [['path', 'service'], 'trim'], 'required' => [['domain_id'], 'required'], 'domain_id_integer' => [['domain_id'], 'integer'], - 'domain_id_exist' => [['domain_id'], 'exist', 'targetRelation' => 'Domain'], + 'domain_id_exist' => [['domain_id'], 'exist', 'targetRelation' => 'domain'], 'd123_id_integer' => [['d123_id'], 'integer'], - 'd123_id_exist' => [['d123_id'], 'exist', 'targetRelation' => 'D123'], + 'd123_id_exist' => [['d123_id'], 'exist', 'targetRelation' => 'd123'], 'a123_id_integer' => [['a123_id'], 'integer'], - 'a123_id_exist' => [['a123_id'], 'exist', 'targetRelation' => 'A123'], + 'a123_id_exist' => [['a123_id'], 'exist', 'targetRelation' => 'a123'], 'path_string' => [['path'], 'string', 'max' => 255], 'ssl_boolean' => [['ssl'], 'boolean'], 'redirect_to_ssl_boolean' => [['redirect_to_ssl'], 'boolean'], From 65fa9b1af198d9bdf102ba3f73889768bcd1c548 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Fri, 6 Sep 2024 20:27:02 +0530 Subject: [PATCH 209/358] Complete the test --- .../m200000_000000_create_table_users.php | 20 +++ .../m200000_000001_create_table_posts.php | 23 +++ .../mysql/models/BaseModelFaker.php | 144 ++++++++++++++++++ .../mysql/models/Post.php | 10 ++ .../mysql/models/PostFaker.php | 51 +++++++ .../mysql/models/User.php | 10 ++ .../mysql/models/UserFaker.php | 41 +++++ .../mysql/models/base/Post.php | 35 +++++ .../mysql/models/base/User.php | 26 ++++ tests/unit/IssueFixTest.php | 14 +- 10 files changed, 367 insertions(+), 7 deletions(-) create mode 100644 tests/specs/issue_fix/29_extension_fk_column_name_cause_error_in_case_of_column_name_without_underscore/mysql/migrations_mysql_db/m200000_000000_create_table_users.php create mode 100644 tests/specs/issue_fix/29_extension_fk_column_name_cause_error_in_case_of_column_name_without_underscore/mysql/migrations_mysql_db/m200000_000001_create_table_posts.php create mode 100644 tests/specs/issue_fix/29_extension_fk_column_name_cause_error_in_case_of_column_name_without_underscore/mysql/models/BaseModelFaker.php create mode 100644 tests/specs/issue_fix/29_extension_fk_column_name_cause_error_in_case_of_column_name_without_underscore/mysql/models/Post.php create mode 100644 tests/specs/issue_fix/29_extension_fk_column_name_cause_error_in_case_of_column_name_without_underscore/mysql/models/PostFaker.php create mode 100644 tests/specs/issue_fix/29_extension_fk_column_name_cause_error_in_case_of_column_name_without_underscore/mysql/models/User.php create mode 100644 tests/specs/issue_fix/29_extension_fk_column_name_cause_error_in_case_of_column_name_without_underscore/mysql/models/UserFaker.php create mode 100644 tests/specs/issue_fix/29_extension_fk_column_name_cause_error_in_case_of_column_name_without_underscore/mysql/models/base/Post.php create mode 100644 tests/specs/issue_fix/29_extension_fk_column_name_cause_error_in_case_of_column_name_without_underscore/mysql/models/base/User.php diff --git a/tests/specs/issue_fix/29_extension_fk_column_name_cause_error_in_case_of_column_name_without_underscore/mysql/migrations_mysql_db/m200000_000000_create_table_users.php b/tests/specs/issue_fix/29_extension_fk_column_name_cause_error_in_case_of_column_name_without_underscore/mysql/migrations_mysql_db/m200000_000000_create_table_users.php new file mode 100644 index 00000000..9ab60f3e --- /dev/null +++ b/tests/specs/issue_fix/29_extension_fk_column_name_cause_error_in_case_of_column_name_without_underscore/mysql/migrations_mysql_db/m200000_000000_create_table_users.php @@ -0,0 +1,20 @@ +createTable('{{%users}}', [ + 'id' => $this->primaryKey(), + 'name' => $this->text()->null(), + ]); + } + + public function down() + { + $this->dropTable('{{%users}}'); + } +} diff --git a/tests/specs/issue_fix/29_extension_fk_column_name_cause_error_in_case_of_column_name_without_underscore/mysql/migrations_mysql_db/m200000_000001_create_table_posts.php b/tests/specs/issue_fix/29_extension_fk_column_name_cause_error_in_case_of_column_name_without_underscore/mysql/migrations_mysql_db/m200000_000001_create_table_posts.php new file mode 100644 index 00000000..ebb98b8e --- /dev/null +++ b/tests/specs/issue_fix/29_extension_fk_column_name_cause_error_in_case_of_column_name_without_underscore/mysql/migrations_mysql_db/m200000_000001_create_table_posts.php @@ -0,0 +1,23 @@ +createTable('{{%posts}}', [ + 'id' => $this->primaryKey(), + 'content' => $this->text()->null(), + 'user' => $this->integer()->null()->defaultValue(null), + ]); + $this->addForeignKey('fk_posts_user_users_id', '{{%posts}}', 'user', '{{%users}}', 'id'); + } + + public function down() + { + $this->dropForeignKey('fk_posts_user_users_id', '{{%posts}}'); + $this->dropTable('{{%posts}}'); + } +} diff --git a/tests/specs/issue_fix/29_extension_fk_column_name_cause_error_in_case_of_column_name_without_underscore/mysql/models/BaseModelFaker.php b/tests/specs/issue_fix/29_extension_fk_column_name_cause_error_in_case_of_column_name_without_underscore/mysql/models/BaseModelFaker.php new file mode 100644 index 00000000..c367fbb4 --- /dev/null +++ b/tests/specs/issue_fix/29_extension_fk_column_name_cause_error_in_case_of_column_name_without_underscore/mysql/models/BaseModelFaker.php @@ -0,0 +1,144 @@ +faker = FakerFactory::create(str_replace('-', '_', \Yii::$app->language)); + $this->uniqueFaker = new UniqueGenerator($this->faker); + } + + abstract public function generateModel($attributes = []); + + public function getFaker():Generator + { + return $this->faker; + } + + public function getUniqueFaker():UniqueGenerator + { + return $this->uniqueFaker; + } + + public function setFaker(Generator $faker):void + { + $this->faker = $faker; + } + + public function setUniqueFaker(UniqueGenerator $faker):void + { + $this->uniqueFaker = $faker; + } + + /** + * Generate and return model + * @param array|callable $attributes + * @param UniqueGenerator|null $uniqueFaker + * @return \yii\db\ActiveRecord + * @example MyFaker::makeOne(['user_id' => 1, 'title' => 'foo']); + * @example MyFaker::makeOne( function($model, $faker) { + * $model->scenario = 'create'; + * $model->setAttributes(['user_id' => 1, 'title' => $faker->sentence]); + * return $model; + * }); + */ + public static function makeOne($attributes = [], ?UniqueGenerator $uniqueFaker = null) + { + $fakeBuilder = new static(); + if ($uniqueFaker !== null) { + $fakeBuilder->setUniqueFaker($uniqueFaker); + } + $model = $fakeBuilder->generateModel($attributes); + return $model; + } + + /** + * Generate, save and return model + * @param array|callable $attributes + * @param UniqueGenerator|null $uniqueFaker + * @return \yii\db\ActiveRecord + * @example MyFaker::saveOne(['user_id' => 1, 'title' => 'foo']); + * @example MyFaker::saveOne( function($model, $faker) { + * $model->scenario = 'create'; + * $model->setAttributes(['user_id' => 1, 'title' => $faker->sentence]); + * return $model; + * }); + */ + public static function saveOne($attributes = [], ?UniqueGenerator $uniqueFaker = null) + { + $model = static::makeOne($attributes, $uniqueFaker); + $model->save(); + return $model; + } + + /** + * Generate and return multiple models + * @param int $number + * @param array|callable $commonAttributes + * @return \yii\db\ActiveRecord[]|array + * @example TaskFaker::make(5, ['project_id'=>1, 'user_id' => 2]); + * @example TaskFaker::make(5, function($model, $faker, $uniqueFaker) { + * $model->setAttributes(['name' => $uniqueFaker->username, 'state'=>$faker->boolean(20)]); + * return $model; + * }); + */ + public static function make(int $number, $commonAttributes = [], ?UniqueGenerator $uniqueFaker = null):array + { + if ($number < 1) { + return []; + } + $fakeBuilder = new static(); + if ($uniqueFaker !== null) { + $fakeBuilder->setUniqueFaker($uniqueFaker); + } + return array_map(function () use ($commonAttributes, $fakeBuilder) { + $model = $fakeBuilder->generateModel($commonAttributes); + return $model; + }, range(0, $number -1)); + } + + /** + * Generate, save and return multiple models + * @param int $number + * @param array|callable $commonAttributes + * @return \yii\db\ActiveRecord[]|array + * @example TaskFaker::save(5, ['project_id'=>1, 'user_id' => 2]); + * @example TaskFaker::save(5, function($model, $faker, $uniqueFaker) { + * $model->setAttributes(['name' => $uniqueFaker->username, 'state'=>$faker->boolean(20)]); + * return $model; + * }); + */ + public static function save(int $number, $commonAttributes = [], ?UniqueGenerator $uniqueFaker = null):array + { + if ($number < 1) { + return []; + } + $fakeBuilder = new static(); + if ($uniqueFaker !== null) { + $fakeBuilder->setUniqueFaker($uniqueFaker); + } + return array_map(function () use ($commonAttributes, $fakeBuilder) { + $model = $fakeBuilder->generateModel($commonAttributes); + $model->save(); + return $model; + }, range(0, $number -1)); + } +} diff --git a/tests/specs/issue_fix/29_extension_fk_column_name_cause_error_in_case_of_column_name_without_underscore/mysql/models/Post.php b/tests/specs/issue_fix/29_extension_fk_column_name_cause_error_in_case_of_column_name_without_underscore/mysql/models/Post.php new file mode 100644 index 00000000..2825fe31 --- /dev/null +++ b/tests/specs/issue_fix/29_extension_fk_column_name_cause_error_in_case_of_column_name_without_underscore/mysql/models/Post.php @@ -0,0 +1,10 @@ +generateModels(['author_id' => 1]); + * $model = (new PostFaker())->generateModels(function($model, $faker, $uniqueFaker) { + * $model->scenario = 'create'; + * $model->author_id = 1; + * return $model; + * }); + **/ + public function generateModel($attributes = []) + { + $faker = $this->faker; + $uniqueFaker = $this->uniqueFaker; + $model = new Post(); + //$model->id = $uniqueFaker->numberBetween(0, 1000000); + $model->content = $faker->paragraphs(6, true); + $model->user = $faker->randomElement(\app\models\User::find()->select("id")->column()); + if (!is_callable($attributes)) { + $model->setAttributes($attributes, false); + } else { + $model = $attributes($model, $faker, $uniqueFaker); + } + return $model; + } + + public static function dependentOn() + { + return [ + // just model class names + 'User', + + ]; + } +} diff --git a/tests/specs/issue_fix/29_extension_fk_column_name_cause_error_in_case_of_column_name_without_underscore/mysql/models/User.php b/tests/specs/issue_fix/29_extension_fk_column_name_cause_error_in_case_of_column_name_without_underscore/mysql/models/User.php new file mode 100644 index 00000000..9b837d6e --- /dev/null +++ b/tests/specs/issue_fix/29_extension_fk_column_name_cause_error_in_case_of_column_name_without_underscore/mysql/models/User.php @@ -0,0 +1,10 @@ +generateModels(['author_id' => 1]); + * $model = (new PostFaker())->generateModels(function($model, $faker, $uniqueFaker) { + * $model->scenario = 'create'; + * $model->author_id = 1; + * return $model; + * }); + **/ + public function generateModel($attributes = []) + { + $faker = $this->faker; + $uniqueFaker = $this->uniqueFaker; + $model = new User(); + //$model->id = $uniqueFaker->numberBetween(0, 1000000); + $model->name = $faker->sentence; + if (!is_callable($attributes)) { + $model->setAttributes($attributes, false); + } else { + $model = $attributes($model, $faker, $uniqueFaker); + } + return $model; + } +} diff --git a/tests/specs/issue_fix/29_extension_fk_column_name_cause_error_in_case_of_column_name_without_underscore/mysql/models/base/Post.php b/tests/specs/issue_fix/29_extension_fk_column_name_cause_error_in_case_of_column_name_without_underscore/mysql/models/base/Post.php new file mode 100644 index 00000000..c8ba9f96 --- /dev/null +++ b/tests/specs/issue_fix/29_extension_fk_column_name_cause_error_in_case_of_column_name_without_underscore/mysql/models/base/Post.php @@ -0,0 +1,35 @@ + [['content'], 'trim'], + 'user_integer' => [['user'], 'integer'], + 'user_exist' => [['user'], 'exist', 'targetRelation' => 'userRel'], + 'content_string' => [['content'], 'string'], + ]; + } + + public function getUserRel() + { + return $this->hasOne(\app\models\User::class, ['id' => 'user']); + } +} diff --git a/tests/specs/issue_fix/29_extension_fk_column_name_cause_error_in_case_of_column_name_without_underscore/mysql/models/base/User.php b/tests/specs/issue_fix/29_extension_fk_column_name_cause_error_in_case_of_column_name_without_underscore/mysql/models/base/User.php new file mode 100644 index 00000000..08e59880 --- /dev/null +++ b/tests/specs/issue_fix/29_extension_fk_column_name_cause_error_in_case_of_column_name_without_underscore/mysql/models/base/User.php @@ -0,0 +1,26 @@ + [['name'], 'trim'], + 'name_string' => [['name'], 'string'], + ]; + } +} diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index ae6dfa61..ea9d2182 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -366,12 +366,12 @@ public function test29ExtensionFkColumnNameCauseErrorInCaseOfColumnNameWithoutUn { $testFile = Yii::getAlias("@specs/issue_fix/29_extension_fk_column_name_cause_error_in_case_of_column_name_without_underscore/index.php"); $this->runGenerator($testFile); - // $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ - // 'recursive' => true, - // ]); - // $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/29_extension_fk_column_name_cause_error_in_case_of_column_name_without_underscore/mysql"), [ - // 'recursive' => true, - // ]); - // $this->checkFiles($actualFiles, $expectedFiles); // TODO + $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ + 'recursive' => true, + ]); + $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/29_extension_fk_column_name_cause_error_in_case_of_column_name_without_underscore/mysql"), [ + 'recursive' => true, + ]); + $this->checkFiles($actualFiles, $expectedFiles); } } From 452773a4231078fc3b482807ac4f577d088dd323 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Fri, 6 Sep 2024 20:32:29 +0530 Subject: [PATCH 210/358] Delete file --- TODO.taskpaper | 9 --------- 1 file changed, 9 deletions(-) delete mode 100644 TODO.taskpaper diff --git a/TODO.taskpaper b/TODO.taskpaper deleted file mode 100644 index 35ef3769..00000000 --- a/TODO.taskpaper +++ /dev/null @@ -1,9 +0,0 @@ -TODO.taskpaper - -### Extension FK COLUMN NAME cause error in case of column name without underscore #29 - ☐ create failing test - ☐ implement the solution - ☐ fix failing tests if any - ☐ resolve TODOs if any - ☐ review PR - ☐ delete this file and submit PR From e788a21fd2a1ada19e0f9b68e3a858f4a072548f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sigmar=20K=C3=BChlmann?= Date: Fri, 13 Sep 2024 09:48:56 +0200 Subject: [PATCH 211/358] cleanUp + getScenarios description --- src/generator/ApiGenerator.php | 5 ++- src/lib/Config.php | 5 ++- src/lib/items/DbModel.php | 74 +++++++++++++++++++++++++++++----- 3 files changed, 70 insertions(+), 14 deletions(-) diff --git a/src/generator/ApiGenerator.php b/src/generator/ApiGenerator.php index 1852260c..a7eff510 100644 --- a/src/generator/ApiGenerator.php +++ b/src/generator/ApiGenerator.php @@ -136,10 +136,11 @@ class ApiGenerator extends Generator /** * @var array Map for custom dbModels + * + * @see DbModel::$scenarioDefaultDescription with acceptedInputs: {scenarioName}, {scenarioConst}, {modelName}. * @example * 'dbModel' => [ - * AcceptedInputs: {scenarioName}, {scenarioConst}, {modelName}. - * 'scenarioDefaultDescription' => " Scenario {scenarioName}", @see DbModel::$scenarioDefaultDescription + * 'scenarioDefaultDescription' => "Scenario {scenarioName}", * ] */ public $dbModel = []; diff --git a/src/lib/Config.php b/src/lib/Config.php index e8732c27..bd4934a0 100644 --- a/src/lib/Config.php +++ b/src/lib/Config.php @@ -111,10 +111,11 @@ class Config extends BaseObject /** * @var array Map for custom dbModels + * + * @see DbModel::$scenarioDefaultDescription with acceptedInputs: {scenarioName}, {scenarioConst}, {modelName}. * @example * 'dbModel' => [ - * AcceptedInputs: {scenarioName}, {scenarioConst}, {modelName}. - * 'scenarioDefaultDescription' => " Scenario {scenarioName}", @see DbModel::$scenarioDefaultDescription + * 'scenarioDefaultDescription' => "Scenario {scenarioName}", * ] */ public $dbModel = []; diff --git a/src/lib/items/DbModel.php b/src/lib/items/DbModel.php index 387107cd..5c33c09b 100644 --- a/src/lib/items/DbModel.php +++ b/src/lib/items/DbModel.php @@ -82,17 +82,17 @@ class DbModel extends BaseObject public $isNotDb = false; - /** - * @var array Automatically generated scenarios from the model 'x-scenarios'. - */ - private array $scenarios; - /** * @var string * Here, you can set your own default description for the scenario. * AcceptedInputs: {scenarioName}, {scenarioConst}, {modelName}. */ - public string $scenarioDefaultDescription = "Scenario {scenarioName}"; + public $scenarioDefaultDescription = "Scenario {scenarioName}"; + + /** + * @var array Automatically generated scenarios from the model 'x-scenarios'. + */ + private $_scenarios; public function getTableAlias():string { @@ -193,18 +193,72 @@ public function dbAttributes():array } /** + * Returns a scenarios array based on the 'x-scenarios'. + * Each scenario has the following properties: 'name', 'const', and 'description'. + * + * When the `getScenarios` function is called for the first time on this model, + * the value is stored in `_scenarios` and then returned. + * If the `getScenariosByOpenapiSchema` function is called again on this model, + * the stored value from `_scenarios` is returned. + * * @return array */ public function getScenarios(): array { - if (isset($this->scenarios)) { - return $this->scenarios; + if (isset($this->_scenarios)) { + return $this->_scenarios; } - $this->scenarios = $this->getScenariosByOpenapiSchema(); - return $this->scenarios; + $this->_scenarios = $this->getScenariosByOpenapiSchema(); + return $this->_scenarios; } /** + * Returns a scenarios array based on the 'x-scenarios'. + * Each scenario has the following properties: 'name', 'const', and 'description'. + * + * Example for 'schema.yaml': + * x-scenarios: + * - name: create + * description: My custom description for scenario create + * - name: update + * + * 1) With default @see $scenarioDefaultDescription = "Scenario {scenarioName}" + * + * The resulting array: + * [ + * [ + * 'name' => 'create', + * 'const' => 'SCENARIO_CREATE', + * 'description' => "My custom description for scenario create", + * ], + * [ + * 'name' => 'update', + * 'const' => 'SCENARIO_UPDATE', + * 'description' => "Scenario update", + * ], + * ] + * + * 2) With custom @see $scenarioDefaultDescription = implode("\n", [ + * "This Backend-Scenario \"{scenarioName}\" exist in both the frontend model and the backend model.", + * "@see \common\client\models\{modelName}::{scenarioConst}", + * ]); + * + * For the 'update' scenario, it is an example of a two-line description. + * E.g. your modelName is 'Project'. + * The resulting array: + * [ + * [ + * 'name' => 'create', + * 'const' => 'SCENARIO_CREATE', + * 'description' => "My custom description for scenario create", + * ], + * [ + * 'name' => 'update', + * 'const' => 'SCENARIO_UPDATE', + * 'description' => "This Backend-Scenario \"update\" exist in both the frontend model and the backend model.\n@see \common\client\models\Project::SCENARIO_UPDATE", + * ], + * ] + * * @return array */ private function getScenariosByOpenapiSchema(): array From d7dc5733d8ad18635ad12ea808aebe3de3c002bd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sigmar=20K=C3=BChlmann?= Date: Fri, 13 Sep 2024 10:17:15 +0200 Subject: [PATCH 212/358] style fix --- src/lib/helpers/FormatHelper.php | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/lib/helpers/FormatHelper.php b/src/lib/helpers/FormatHelper.php index 6fc29742..12567fe8 100644 --- a/src/lib/helpers/FormatHelper.php +++ b/src/lib/helpers/FormatHelper.php @@ -1,5 +1,10 @@ and contributors + * @license https://github.com/cebe/yii2-openapi/blob/master/LICENSE + */ + namespace cebe\yii2openapi\lib\helpers; class FormatHelper @@ -17,4 +22,4 @@ public static function getFormattedDescription(string $description, int $spacing }, $descriptionArr); return implode("\n".str_repeat(" ", $spacing)."*", $descriptionArr); } -} \ No newline at end of file +} From 9497bf434eef9579ed1e90a06be939cc1669dfe3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sigmar=20K=C3=BChlmann?= Date: Fri, 13 Sep 2024 13:22:16 +0200 Subject: [PATCH 213/358] test fix --- tests/specs/blog/models/base/Category.php | 4 ++++ tests/specs/blog/models/base/Comment.php | 6 +++++- tests/specs/blog/models/base/Fakerable.php | 6 +++++- tests/specs/blog/models/base/Post.php | 4 ++++ tests/specs/blog/models/base/User.php | 4 ++++ tests/specs/blog_v2/models/base/Category.php | 4 ++++ tests/specs/blog_v2/models/base/Comment.php | 6 +++++- tests/specs/blog_v2/models/base/Post.php | 4 ++++ tests/specs/blog_v2/models/base/Tag.php | 6 +++++- tests/specs/blog_v2/models/base/User.php | 4 ++++ .../maria/app/models/base/ColumnNameChange.php | 4 ++++ .../mysql/app/models/base/ColumnNameChange.php | 4 ++++ .../pgsql/app/models/base/ColumnNameChange.php | 4 ++++ tests/specs/fk_col_name/app/models/base/Delivery.php | 6 +++++- tests/specs/fk_col_name/app/models/base/User.php | 4 ++++ tests/specs/fk_col_name/app/models/base/Webhook.php | 4 ++++ tests/specs/fk_col_name_index/app/models/base/Delivery.php | 6 +++++- tests/specs/fk_col_name_index/app/models/base/User.php | 4 ++++ tests/specs/fk_col_name_index/app/models/base/Webhook.php | 4 ++++ tests/specs/id_not_in_rules/app/models/base/Fruit.php | 4 ++++ tests/specs/id_not_in_rules/app/models/base/Post.php | 6 +++++- .../app/models/base/Pristine.php | 4 ++++ .../maria/models/base/Mailing.php | 4 ++++ .../maria/models/base/Contact.php | 4 ++++ .../maria/models/base/Mailing.php | 4 ++++ .../app/models/base/Invoice.php | 6 +++++- .../app/models/base/Order.php | 6 +++++- .../pgsql/models/base/Contact.php | 6 +++++- .../pgsql/models/base/Account.php | 4 ++++ .../pgsql/models/base/Contact.php | 4 ++++ .../pgsql/models/base/PaymentMethod.php | 4 ++++ .../app/models/base/Account.php | 4 ++++ .../app/models/base/E123.php | 4 ++++ .../quote_in_alter_table/pgsql/app/models/base/Fruit.php | 4 ++++ tests/specs/many2many/models/base/Photo.php | 6 +++++- tests/specs/many2many/models/base/Photos2Posts.php | 6 +++++- tests/specs/many2many/models/base/Post.php | 4 ++++ tests/specs/many2many/models/base/PostsAttaches.php | 6 +++++- tests/specs/many2many/models/base/PostsGallery.php | 6 +++++- tests/specs/many2many/models/base/Tag.php | 6 +++++- tests/specs/menu/models/base/Menu.php | 6 +++++- tests/specs/petstore/models/base/Pet.php | 4 ++++ tests/specs/petstore/models/base/Store.php | 4 ++++ tests/specs/petstore_arrayref/models/base/Pet.php | 4 ++++ tests/specs/petstore_jsonapi/models/base/Pet.php | 4 ++++ tests/specs/petstore_namespace/mymodels/base/Pet.php | 4 ++++ tests/specs/petstore_namespace/mymodels/base/Store.php | 4 ++++ tests/specs/petstore_wrapped/models/base/Pet.php | 4 ++++ tests/specs/petstore_xtable/models/base/Pet.php | 4 ++++ tests/specs/postgres_custom/models/base/Custom.php | 6 +++++- tests/specs/relations_in_faker/app/models/base/A123.php | 4 ++++ tests/specs/relations_in_faker/app/models/base/Account.php | 4 ++++ tests/specs/relations_in_faker/app/models/base/B123.php | 4 ++++ tests/specs/relations_in_faker/app/models/base/C123.php | 4 ++++ tests/specs/relations_in_faker/app/models/base/D123.php | 4 ++++ tests/specs/relations_in_faker/app/models/base/Domain.php | 4 ++++ tests/specs/relations_in_faker/app/models/base/E123.php | 4 ++++ tests/specs/relations_in_faker/app/models/base/Routing.php | 4 ++++ .../maria/app/models/mariamodel/base/Alldbdatatype.php | 4 ++++ .../maria/app/models/mariamodel/base/Editcolumn.php | 4 ++++ .../maria/app/models/mariamodel/base/Newcolumn.php | 4 ++++ .../maria/app/models/mariamodel/base/Pristine.php | 4 ++++ .../rules_and_more/mysql/app/models/base/Alldbdatatype.php | 4 ++++ .../rules_and_more/mysql/app/models/base/Editcolumn.php | 4 ++++ .../rules_and_more/mysql/app/models/base/Newcolumn.php | 4 ++++ .../rules_and_more/mysql/app/models/base/Pristine.php | 4 ++++ .../pgsql/app/models/pgsqlmodel/base/Alldbdatatype.php | 4 ++++ .../pgsql/app/models/pgsqlmodel/base/Editcolumn.php | 4 ++++ .../pgsql/app/models/pgsqlmodel/base/Newcolumn.php | 4 ++++ .../pgsql/app/models/pgsqlmodel/base/Pristine.php | 4 ++++ tests/unit/AttributeResolverTest.php | 2 ++ 71 files changed, 299 insertions(+), 17 deletions(-) diff --git a/tests/specs/blog/models/base/Category.php b/tests/specs/blog/models/base/Category.php index f22e0014..1c7cdb97 100644 --- a/tests/specs/blog/models/base/Category.php +++ b/tests/specs/blog/models/base/Category.php @@ -1,5 +1,9 @@ resolve(); $fixture = require Yii::getAlias('@fixtures/non-db.php'); $testModel = $fixture['personWatch']; + $testModel->openapiSchema = $model->openapiSchema; self::assertEquals($testModel, $model); } @@ -126,6 +127,7 @@ public function testResolveNonDbModel() $model = $resolver->resolve(); $fixture = require Yii::getAlias('@fixtures/non-db.php'); $testModel = $fixture['PetStatistic']; + $testModel->openapiSchema = $model->openapiSchema; self::assertEquals($testModel, $model); } } From 0430551830ffbcc609d02b1e6b88655b1506c0b8 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Tue, 24 Sep 2024 19:56:41 +0530 Subject: [PATCH 214/358] Fix this issue and failing tests --- src/lib/migrations/BaseMigrationBuilder.php | 2 +- ...m200000_000002_create_table_posts2tags.php | 4 +- ...m200000_000002_create_table_posts2tags.php | 4 +- ...m200000_000002_create_table_posts2tags.php | 4 +- .../index.php | 14 +++++++ .../index.yml | 38 +++++++++++++++++++ .../m200000_000000_create_table_documents.php | 19 ++++++++++ .../m200000_000001_create_table_labels.php | 19 ++++++++++ ...0_000002_create_table_documents2labels.php | 26 +++++++++++++ ...m200000_000004_create_table_posts2tags.php | 4 +- tests/unit/IssueFixTest.php | 14 +++++++ 11 files changed, 139 insertions(+), 9 deletions(-) create mode 100644 tests/specs/issue_fix/53_bug_inversed_reference_require_cascade/index.php create mode 100644 tests/specs/issue_fix/53_bug_inversed_reference_require_cascade/index.yml create mode 100644 tests/specs/issue_fix/53_bug_inversed_reference_require_cascade/mysql/migrations_mysql_db/m200000_000000_create_table_documents.php create mode 100644 tests/specs/issue_fix/53_bug_inversed_reference_require_cascade/mysql/migrations_mysql_db/m200000_000001_create_table_labels.php create mode 100644 tests/specs/issue_fix/53_bug_inversed_reference_require_cascade/mysql/migrations_mysql_db/m200000_000002_create_table_documents2labels.php diff --git a/src/lib/migrations/BaseMigrationBuilder.php b/src/lib/migrations/BaseMigrationBuilder.php index d4c49c21..874230fc 100644 --- a/src/lib/migrations/BaseMigrationBuilder.php +++ b/src/lib/migrations/BaseMigrationBuilder.php @@ -101,7 +101,7 @@ public function buildJunction(ManyToManyRelation $relation):MigrationModel continue; } $this->migration - ->addUpCode($this->recordBuilder->addFk($fkName, $tableAlias, $fkCol, $refTable, $refCol)) + ->addUpCode($this->recordBuilder->addFk($fkName, $tableAlias, $fkCol, $refTable, $refCol, 'CASCADE')) ->addDownCode($this->recordBuilder->dropFk($fkName, $tableAlias)); $this->migration->dependencies[] = $refTable; } diff --git a/tests/specs/blog_v2/migrations_maria_db/m200000_000002_create_table_posts2tags.php b/tests/specs/blog_v2/migrations_maria_db/m200000_000002_create_table_posts2tags.php index 2e959d10..2a99ba10 100644 --- a/tests/specs/blog_v2/migrations_maria_db/m200000_000002_create_table_posts2tags.php +++ b/tests/specs/blog_v2/migrations_maria_db/m200000_000002_create_table_posts2tags.php @@ -12,8 +12,8 @@ public function up() 'tag_id' => $this->bigInteger()->notNull(), ]); $this->addPrimaryKey('pk_post_id_tag_id', '{{%posts2tags}}', 'post_id,tag_id'); - $this->addForeignKey('fk_posts2tags_post_id_v2_posts_id', '{{%posts2tags}}', 'post_id', '{{%v2_posts}}', 'id'); - $this->addForeignKey('fk_posts2tags_tag_id_v2_tags_id', '{{%posts2tags}}', 'tag_id', '{{%v2_tags}}', 'id'); + $this->addForeignKey('fk_posts2tags_post_id_v2_posts_id', '{{%posts2tags}}', 'post_id', '{{%v2_posts}}', 'id', 'CASCADE'); + $this->addForeignKey('fk_posts2tags_tag_id_v2_tags_id', '{{%posts2tags}}', 'tag_id', '{{%v2_tags}}', 'id', 'CASCADE'); } public function down() diff --git a/tests/specs/blog_v2/migrations_mysql_db/m200000_000002_create_table_posts2tags.php b/tests/specs/blog_v2/migrations_mysql_db/m200000_000002_create_table_posts2tags.php index 2e959d10..2a99ba10 100644 --- a/tests/specs/blog_v2/migrations_mysql_db/m200000_000002_create_table_posts2tags.php +++ b/tests/specs/blog_v2/migrations_mysql_db/m200000_000002_create_table_posts2tags.php @@ -12,8 +12,8 @@ public function up() 'tag_id' => $this->bigInteger()->notNull(), ]); $this->addPrimaryKey('pk_post_id_tag_id', '{{%posts2tags}}', 'post_id,tag_id'); - $this->addForeignKey('fk_posts2tags_post_id_v2_posts_id', '{{%posts2tags}}', 'post_id', '{{%v2_posts}}', 'id'); - $this->addForeignKey('fk_posts2tags_tag_id_v2_tags_id', '{{%posts2tags}}', 'tag_id', '{{%v2_tags}}', 'id'); + $this->addForeignKey('fk_posts2tags_post_id_v2_posts_id', '{{%posts2tags}}', 'post_id', '{{%v2_posts}}', 'id', 'CASCADE'); + $this->addForeignKey('fk_posts2tags_tag_id_v2_tags_id', '{{%posts2tags}}', 'tag_id', '{{%v2_tags}}', 'id', 'CASCADE'); } public function down() diff --git a/tests/specs/blog_v2/migrations_pgsql_db/m200000_000002_create_table_posts2tags.php b/tests/specs/blog_v2/migrations_pgsql_db/m200000_000002_create_table_posts2tags.php index d518ff32..e92fc36c 100644 --- a/tests/specs/blog_v2/migrations_pgsql_db/m200000_000002_create_table_posts2tags.php +++ b/tests/specs/blog_v2/migrations_pgsql_db/m200000_000002_create_table_posts2tags.php @@ -12,8 +12,8 @@ public function safeUp() 'tag_id' => $this->bigInteger()->notNull(), ]); $this->addPrimaryKey('pk_post_id_tag_id', '{{%posts2tags}}', 'post_id,tag_id'); - $this->addForeignKey('fk_posts2tags_post_id_v2_posts_id', '{{%posts2tags}}', 'post_id', '{{%v2_posts}}', 'id'); - $this->addForeignKey('fk_posts2tags_tag_id_v2_tags_id', '{{%posts2tags}}', 'tag_id', '{{%v2_tags}}', 'id'); + $this->addForeignKey('fk_posts2tags_post_id_v2_posts_id', '{{%posts2tags}}', 'post_id', '{{%v2_posts}}', 'id', 'CASCADE'); + $this->addForeignKey('fk_posts2tags_tag_id_v2_tags_id', '{{%posts2tags}}', 'tag_id', '{{%v2_tags}}', 'id', 'CASCADE'); } public function safeDown() diff --git a/tests/specs/issue_fix/53_bug_inversed_reference_require_cascade/index.php b/tests/specs/issue_fix/53_bug_inversed_reference_require_cascade/index.php new file mode 100644 index 00000000..758c13f4 --- /dev/null +++ b/tests/specs/issue_fix/53_bug_inversed_reference_require_cascade/index.php @@ -0,0 +1,14 @@ + '@specs/issue_fix/53_bug_inversed_reference_require_cascade/index.yml', + 'generateUrls' => false, + 'generateModels' => false, + 'excludeModels' => [ + 'Error', + ], + 'generateControllers' => false, + 'generateMigrations' => true, + 'generateModelFaker' => false, // `generateModels` must be `true` in order to use `generateModelFaker` as `true` +]; + diff --git a/tests/specs/issue_fix/53_bug_inversed_reference_require_cascade/index.yml b/tests/specs/issue_fix/53_bug_inversed_reference_require_cascade/index.yml new file mode 100644 index 00000000..7676ad03 --- /dev/null +++ b/tests/specs/issue_fix/53_bug_inversed_reference_require_cascade/index.yml @@ -0,0 +1,38 @@ +openapi: 3.0.3 + +info: + title: '53_bug_inversed_reference_require_cascade' + version: 1.0.0 + +components: + schemas: + Document: + title: Document + properties: + id: + type: integer + labels: + type: array + readOnly: true + description: Inversed reference for detect junction table documents2labels + items: + $ref: '#/components/schemas/Label' + + Label: + title: Label + properties: + id: + type: integer + documents: + type: array + readOnly: true + description: Inversed reference for detect junction table documents2labels + items: + $ref: '#/components/schemas/Document' + +paths: + '/': + get: + responses: + '200': + description: OK diff --git a/tests/specs/issue_fix/53_bug_inversed_reference_require_cascade/mysql/migrations_mysql_db/m200000_000000_create_table_documents.php b/tests/specs/issue_fix/53_bug_inversed_reference_require_cascade/mysql/migrations_mysql_db/m200000_000000_create_table_documents.php new file mode 100644 index 00000000..123e8456 --- /dev/null +++ b/tests/specs/issue_fix/53_bug_inversed_reference_require_cascade/mysql/migrations_mysql_db/m200000_000000_create_table_documents.php @@ -0,0 +1,19 @@ +createTable('{{%documents}}', [ + 'id' => $this->primaryKey(), + ]); + } + + public function down() + { + $this->dropTable('{{%documents}}'); + } +} diff --git a/tests/specs/issue_fix/53_bug_inversed_reference_require_cascade/mysql/migrations_mysql_db/m200000_000001_create_table_labels.php b/tests/specs/issue_fix/53_bug_inversed_reference_require_cascade/mysql/migrations_mysql_db/m200000_000001_create_table_labels.php new file mode 100644 index 00000000..80b6c53d --- /dev/null +++ b/tests/specs/issue_fix/53_bug_inversed_reference_require_cascade/mysql/migrations_mysql_db/m200000_000001_create_table_labels.php @@ -0,0 +1,19 @@ +createTable('{{%labels}}', [ + 'id' => $this->primaryKey(), + ]); + } + + public function down() + { + $this->dropTable('{{%labels}}'); + } +} diff --git a/tests/specs/issue_fix/53_bug_inversed_reference_require_cascade/mysql/migrations_mysql_db/m200000_000002_create_table_documents2labels.php b/tests/specs/issue_fix/53_bug_inversed_reference_require_cascade/mysql/migrations_mysql_db/m200000_000002_create_table_documents2labels.php new file mode 100644 index 00000000..39ba483f --- /dev/null +++ b/tests/specs/issue_fix/53_bug_inversed_reference_require_cascade/mysql/migrations_mysql_db/m200000_000002_create_table_documents2labels.php @@ -0,0 +1,26 @@ +createTable('{{%documents2labels}}', [ + 'document_id' => $this->integer()->notNull(), + 'label_id' => $this->integer()->notNull(), + ]); + $this->addPrimaryKey('pk_document_id_label_id', '{{%documents2labels}}', 'document_id,label_id'); + $this->addForeignKey('fk_documents2labels_document_id_documents_id', '{{%documents2labels}}', 'document_id', '{{%documents}}', 'id', 'CASCADE'); + $this->addForeignKey('fk_documents2labels_label_id_labels_id', '{{%documents2labels}}', 'label_id', '{{%labels}}', 'id', 'CASCADE'); + } + + public function down() + { + $this->dropForeignKey('fk_documents2labels_label_id_labels_id', '{{%documents2labels}}'); + $this->dropForeignKey('fk_documents2labels_document_id_documents_id', '{{%documents2labels}}'); + $this->dropPrimaryKey('pk_document_id_label_id', '{{%documents2labels}}'); + $this->dropTable('{{%documents2labels}}'); + } +} diff --git a/tests/specs/many2many/migrations/m200000_000004_create_table_posts2tags.php b/tests/specs/many2many/migrations/m200000_000004_create_table_posts2tags.php index dbc82bc3..921fefb5 100644 --- a/tests/specs/many2many/migrations/m200000_000004_create_table_posts2tags.php +++ b/tests/specs/many2many/migrations/m200000_000004_create_table_posts2tags.php @@ -12,8 +12,8 @@ public function up() 'tag_id' => $this->bigInteger()->notNull(), ]); $this->addPrimaryKey('pk_post_id_tag_id', '{{%posts2tags}}', 'post_id,tag_id'); - $this->addForeignKey('fk_posts2tags_post_id_posts_id', '{{%posts2tags}}', 'post_id', '{{%posts}}', 'id'); - $this->addForeignKey('fk_posts2tags_tag_id_tags_id', '{{%posts2tags}}', 'tag_id', '{{%tags}}', 'id'); + $this->addForeignKey('fk_posts2tags_post_id_posts_id', '{{%posts2tags}}', 'post_id', '{{%posts}}', 'id', 'CASCADE'); + $this->addForeignKey('fk_posts2tags_tag_id_tags_id', '{{%posts2tags}}', 'tag_id', '{{%tags}}', 'id', 'CASCADE'); } public function down() diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index b6c7abdb..b641bb52 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -360,4 +360,18 @@ public function test158BugGiiapiGeneratedRulesEnumWithTrim() ]); $this->checkFiles($actualFiles, $expectedFiles); } + + // https://github.com/php-openapi/yii2-openapi/issues/53 + public function test53BugInversedReferenceRequireCascade() + { + $testFile = Yii::getAlias("@specs/issue_fix/53_bug_inversed_reference_require_cascade/index.php"); + $this->runGenerator($testFile); + $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ + 'recursive' => true, + ]); + $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/53_bug_inversed_reference_require_cascade/mysql"), [ + 'recursive' => true, + ]); + $this->checkFiles($actualFiles, $expectedFiles); + } } From c6ba36bceb07b1911da8e8a3def01dd728c8edcd Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Wed, 25 Sep 2024 20:20:26 +0530 Subject: [PATCH 215/358] Create PR --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 1cd2090b..3bb79307 100644 --- a/README.md +++ b/README.md @@ -568,3 +568,4 @@ Professional support, consulting as well as software development services are av https://www.cebe.cc/en/contact Development of this library is sponsored by [cebe.:cloud: "Your Professional Deployment Platform"](https://cebe.cloud). + From e4afaebeeade561a8b42beb37a5fe2859a75f926 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Thu, 26 Sep 2024 12:01:04 +0530 Subject: [PATCH 216/358] Implementation --- README.md | 1 - src/lib/generators/ModelsGenerator.php | 4 +++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 3bb79307..1cd2090b 100644 --- a/README.md +++ b/README.md @@ -568,4 +568,3 @@ Professional support, consulting as well as software development services are av https://www.cebe.cc/en/contact Development of this library is sponsored by [cebe.:cloud: "Your Professional Deployment Platform"](https://cebe.cloud). - diff --git a/src/lib/generators/ModelsGenerator.php b/src/lib/generators/ModelsGenerator.php index 27dc6aea..f37296bd 100644 --- a/src/lib/generators/ModelsGenerator.php +++ b/src/lib/generators/ModelsGenerator.php @@ -74,7 +74,9 @@ public function generate():CodeFiles if ($this->config->generateModelFaker) { $deps = []; # list of all models that this model is dependent on foreach ($model->hasOneRelations as $key => $hasOneRelation) { - $deps[] = $model->hasOneRelations[$key]->getClassName(); + if ($model->name !== $hasOneRelation->getClassName()) { # avoid self reference + $deps[] = $hasOneRelation->getClassName(); + } } $deps = array_unique($deps); From 7a761f9d9be57b017fd2533e6c33a6f157fb90be Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Thu, 26 Sep 2024 12:01:25 +0530 Subject: [PATCH 217/358] Add test - WIP --- .../index.php | 14 ++++++ .../index.yml | 44 +++++++++++++++++++ tests/unit/IssueFixTest.php | 14 ++++++ 3 files changed, 72 insertions(+) create mode 100644 tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/index.php create mode 100644 tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/index.yml diff --git a/tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/index.php b/tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/index.php new file mode 100644 index 00000000..9a0fe5d5 --- /dev/null +++ b/tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/index.php @@ -0,0 +1,14 @@ + '@specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/index.yml', + 'generateUrls' => false, + 'generateModels' => true, + 'excludeModels' => [ + 'Error', + ], + 'generateControllers' => false, + 'generateMigrations' => false, + 'generateModelFaker' => true, // `generateModels` must be `true` in order to use `generateModelFaker` as `true` +]; + diff --git a/tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/index.yml b/tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/index.yml new file mode 100644 index 00000000..89ffbd31 --- /dev/null +++ b/tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/index.yml @@ -0,0 +1,44 @@ +openapi: 3.0.3 + +info: + title: 'Bug: dependentOn: allOf with "x-faker: false" #52' + version: 1.0.0 + +components: + schemas: + User: + type: object + properties: + id: + type: integer + name: + type: string + Invoice: + title: Invoice + x-table: invoices + type: object + properties: + id: + type: integer + reference_invoice: + allOf: + - $ref: '#/components/schemas/Invoice' + - x-faker: false + - description: This field is only set on invoices of type "cancellation_invoice" + reference_invoice_2: + allOf: + - $ref: '#/components/schemas/Invoice' + - x-faker: true + user: + $ref: '#/components/schemas/Invoice' + user_2: + allOf: + - $ref: '#/components/schemas/Invoice' + - x-faker: false + +paths: + '/': + get: + responses: + '200': + description: OK diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index b6c7abdb..fefcaeb2 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -360,4 +360,18 @@ public function test158BugGiiapiGeneratedRulesEnumWithTrim() ]); $this->checkFiles($actualFiles, $expectedFiles); } + + // https://github.com/php-openapi/yii2-openapi/issues/52 + public function test52BugDependentonAllofWithXFakerFalse() + { + $testFile = Yii::getAlias("@specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/index.php"); + $this->runGenerator($testFile); + // $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ + // 'recursive' => true, + // ]); + // $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql"), [ + // 'recursive' => true, + // ]); + // $this->checkFiles($actualFiles, $expectedFiles); + } } From 3bc42ff433b4dfdb0f5f7a40934f48b0b3903880 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Thu, 26 Sep 2024 12:04:56 +0530 Subject: [PATCH 218/358] Complete the test --- .../mysql/models/BaseModelFaker.php | 144 ++++++++++++++++++ .../mysql/models/Invoice.php | 10 ++ .../mysql/models/InvoiceFaker.php | 50 ++++++ .../mysql/models/User.php | 10 ++ .../mysql/models/UserFaker.php | 41 +++++ .../mysql/models/base/Invoice.php | 63 ++++++++ .../mysql/models/base/User.php | 30 ++++ tests/unit/IssueFixTest.php | 14 +- 8 files changed, 355 insertions(+), 7 deletions(-) create mode 100644 tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql/models/BaseModelFaker.php create mode 100644 tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql/models/Invoice.php create mode 100644 tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql/models/InvoiceFaker.php create mode 100644 tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql/models/User.php create mode 100644 tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql/models/UserFaker.php create mode 100644 tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql/models/base/Invoice.php create mode 100644 tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql/models/base/User.php diff --git a/tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql/models/BaseModelFaker.php b/tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql/models/BaseModelFaker.php new file mode 100644 index 00000000..c367fbb4 --- /dev/null +++ b/tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql/models/BaseModelFaker.php @@ -0,0 +1,144 @@ +faker = FakerFactory::create(str_replace('-', '_', \Yii::$app->language)); + $this->uniqueFaker = new UniqueGenerator($this->faker); + } + + abstract public function generateModel($attributes = []); + + public function getFaker():Generator + { + return $this->faker; + } + + public function getUniqueFaker():UniqueGenerator + { + return $this->uniqueFaker; + } + + public function setFaker(Generator $faker):void + { + $this->faker = $faker; + } + + public function setUniqueFaker(UniqueGenerator $faker):void + { + $this->uniqueFaker = $faker; + } + + /** + * Generate and return model + * @param array|callable $attributes + * @param UniqueGenerator|null $uniqueFaker + * @return \yii\db\ActiveRecord + * @example MyFaker::makeOne(['user_id' => 1, 'title' => 'foo']); + * @example MyFaker::makeOne( function($model, $faker) { + * $model->scenario = 'create'; + * $model->setAttributes(['user_id' => 1, 'title' => $faker->sentence]); + * return $model; + * }); + */ + public static function makeOne($attributes = [], ?UniqueGenerator $uniqueFaker = null) + { + $fakeBuilder = new static(); + if ($uniqueFaker !== null) { + $fakeBuilder->setUniqueFaker($uniqueFaker); + } + $model = $fakeBuilder->generateModel($attributes); + return $model; + } + + /** + * Generate, save and return model + * @param array|callable $attributes + * @param UniqueGenerator|null $uniqueFaker + * @return \yii\db\ActiveRecord + * @example MyFaker::saveOne(['user_id' => 1, 'title' => 'foo']); + * @example MyFaker::saveOne( function($model, $faker) { + * $model->scenario = 'create'; + * $model->setAttributes(['user_id' => 1, 'title' => $faker->sentence]); + * return $model; + * }); + */ + public static function saveOne($attributes = [], ?UniqueGenerator $uniqueFaker = null) + { + $model = static::makeOne($attributes, $uniqueFaker); + $model->save(); + return $model; + } + + /** + * Generate and return multiple models + * @param int $number + * @param array|callable $commonAttributes + * @return \yii\db\ActiveRecord[]|array + * @example TaskFaker::make(5, ['project_id'=>1, 'user_id' => 2]); + * @example TaskFaker::make(5, function($model, $faker, $uniqueFaker) { + * $model->setAttributes(['name' => $uniqueFaker->username, 'state'=>$faker->boolean(20)]); + * return $model; + * }); + */ + public static function make(int $number, $commonAttributes = [], ?UniqueGenerator $uniqueFaker = null):array + { + if ($number < 1) { + return []; + } + $fakeBuilder = new static(); + if ($uniqueFaker !== null) { + $fakeBuilder->setUniqueFaker($uniqueFaker); + } + return array_map(function () use ($commonAttributes, $fakeBuilder) { + $model = $fakeBuilder->generateModel($commonAttributes); + return $model; + }, range(0, $number -1)); + } + + /** + * Generate, save and return multiple models + * @param int $number + * @param array|callable $commonAttributes + * @return \yii\db\ActiveRecord[]|array + * @example TaskFaker::save(5, ['project_id'=>1, 'user_id' => 2]); + * @example TaskFaker::save(5, function($model, $faker, $uniqueFaker) { + * $model->setAttributes(['name' => $uniqueFaker->username, 'state'=>$faker->boolean(20)]); + * return $model; + * }); + */ + public static function save(int $number, $commonAttributes = [], ?UniqueGenerator $uniqueFaker = null):array + { + if ($number < 1) { + return []; + } + $fakeBuilder = new static(); + if ($uniqueFaker !== null) { + $fakeBuilder->setUniqueFaker($uniqueFaker); + } + return array_map(function () use ($commonAttributes, $fakeBuilder) { + $model = $fakeBuilder->generateModel($commonAttributes); + $model->save(); + return $model; + }, range(0, $number -1)); + } +} diff --git a/tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql/models/Invoice.php b/tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql/models/Invoice.php new file mode 100644 index 00000000..43e37fd3 --- /dev/null +++ b/tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql/models/Invoice.php @@ -0,0 +1,10 @@ +generateModels(['author_id' => 1]); + * $model = (new PostFaker())->generateModels(function($model, $faker, $uniqueFaker) { + * $model->scenario = 'create'; + * $model->author_id = 1; + * return $model; + * }); + **/ + public function generateModel($attributes = []) + { + $faker = $this->faker; + $uniqueFaker = $this->uniqueFaker; + $model = new Invoice(); + //$model->id = $uniqueFaker->numberBetween(0, 1000000); + $model->reference_invoice_2_id = $faker->randomElement(\app\models\Invoice::find()->select("id")->column()); + $model->user_id = $faker->randomElement(\app\models\Invoice::find()->select("id")->column()); + if (!is_callable($attributes)) { + $model->setAttributes($attributes, false); + } else { + $model = $attributes($model, $faker, $uniqueFaker); + } + return $model; + } + + public static function dependentOn() + { + return [ + // just model class names + + ]; + } +} diff --git a/tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql/models/User.php b/tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql/models/User.php new file mode 100644 index 00000000..9b837d6e --- /dev/null +++ b/tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql/models/User.php @@ -0,0 +1,10 @@ +generateModels(['author_id' => 1]); + * $model = (new PostFaker())->generateModels(function($model, $faker, $uniqueFaker) { + * $model->scenario = 'create'; + * $model->author_id = 1; + * return $model; + * }); + **/ + public function generateModel($attributes = []) + { + $faker = $this->faker; + $uniqueFaker = $this->uniqueFaker; + $model = new User(); + //$model->id = $uniqueFaker->numberBetween(0, 1000000); + $model->name = $faker->sentence; + if (!is_callable($attributes)) { + $model->setAttributes($attributes, false); + } else { + $model = $attributes($model, $faker, $uniqueFaker); + } + return $model; + } +} diff --git a/tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql/models/base/Invoice.php b/tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql/models/base/Invoice.php new file mode 100644 index 00000000..f4cb797e --- /dev/null +++ b/tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql/models/base/Invoice.php @@ -0,0 +1,63 @@ + [['reference_invoice_id'], 'integer'], + 'reference_invoice_id_exist' => [['reference_invoice_id'], 'exist', 'targetRelation' => 'ReferenceInvoice'], + 'reference_invoice_2_id_integer' => [['reference_invoice_2_id'], 'integer'], + 'reference_invoice_2_id_exist' => [['reference_invoice_2_id'], 'exist', 'targetRelation' => 'ReferenceInvoice2'], + 'user_id_integer' => [['user_id'], 'integer'], + 'user_id_exist' => [['user_id'], 'exist', 'targetRelation' => 'User'], + 'user_2_id_integer' => [['user_2_id'], 'integer'], + 'user_2_id_exist' => [['user_2_id'], 'exist', 'targetRelation' => 'User2'], + ]; + } + + public function getReferenceInvoice() + { + return $this->hasOne(\app\models\Invoice::class, ['id' => 'reference_invoice_id']); + } + + public function getReferenceInvoice2() + { + return $this->hasOne(\app\models\Invoice::class, ['id' => 'reference_invoice_2_id']); + } + + public function getUser() + { + return $this->hasOne(\app\models\Invoice::class, ['id' => 'user_id']); + } + + public function getUser2() + { + return $this->hasOne(\app\models\Invoice::class, ['id' => 'user_2_id']); + } +} diff --git a/tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql/models/base/User.php b/tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql/models/base/User.php new file mode 100644 index 00000000..bce4e105 --- /dev/null +++ b/tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql/models/base/User.php @@ -0,0 +1,30 @@ + [['name'], 'trim'], + 'name_string' => [['name'], 'string'], + ]; + } +} diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index fefcaeb2..fd102951 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -366,12 +366,12 @@ public function test52BugDependentonAllofWithXFakerFalse() { $testFile = Yii::getAlias("@specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/index.php"); $this->runGenerator($testFile); - // $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ - // 'recursive' => true, - // ]); - // $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql"), [ - // 'recursive' => true, - // ]); - // $this->checkFiles($actualFiles, $expectedFiles); + $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ + 'recursive' => true, + ]); + $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql"), [ + 'recursive' => true, + ]); + $this->checkFiles($actualFiles, $expectedFiles); } } From 93a210baadd33f5bc9a4f429dc64a071f93ad4a3 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Thu, 26 Sep 2024 16:34:00 +0530 Subject: [PATCH 219/358] Complete the implementation --- src/generator/default/dbmodel.php | 8 +++---- src/lib/generators/ModelsGenerator.php | 10 +------- src/lib/items/DbModel.php | 18 +++++++++++++- src/lib/openapi/PropertySchema.php | 18 +++++++------- .../index.yml | 24 +++++++++++++++++-- tests/unit/IssueFixTest.php | 14 +++++------ 6 files changed, 59 insertions(+), 33 deletions(-) diff --git a/src/generator/default/dbmodel.php b/src/generator/default/dbmodel.php index 17fa4a84..a3d269b6 100644 --- a/src/generator/default/dbmodel.php +++ b/src/generator/default/dbmodel.php @@ -49,8 +49,8 @@ */ abstract class getClassName() ?> extends \yii\db\ActiveRecord { -getScenarios()): -foreach($scenarios as $scenario): ?> +getScenarios()): +foreach ($scenarios as $scenario): ?> /** * @@ -76,7 +76,7 @@ public static function tableName() { return getTableAlias()) ?>; } - + /** * Automatically generated scenarios from the model 'x-scenarios'. @@ -92,7 +92,7 @@ public function scenarios() $default = parent::scenarios()[self::SCENARIO_DEFAULT]; return [ - + self:: => $default, /** diff --git a/src/lib/generators/ModelsGenerator.php b/src/lib/generators/ModelsGenerator.php index f37296bd..d2672ff9 100644 --- a/src/lib/generators/ModelsGenerator.php +++ b/src/lib/generators/ModelsGenerator.php @@ -72,14 +72,6 @@ public function generate():CodeFiles ) )); if ($this->config->generateModelFaker) { - $deps = []; # list of all models that this model is dependent on - foreach ($model->hasOneRelations as $key => $hasOneRelation) { - if ($model->name !== $hasOneRelation->getClassName()) { # avoid self reference - $deps[] = $hasOneRelation->getClassName(); - } - } - $deps = array_unique($deps); - $this->files->add(new CodeFile( Yii::getAlias("$fakerPath/{$className}Faker.php"), $this->config->render( @@ -88,7 +80,7 @@ public function generate():CodeFiles 'model' => $model, 'modelNamespace' => $this->config->modelNamespace, 'namespace' => $this->config->fakerNamespace, - 'deps' => $deps, + 'deps' => $model->fakerDependentModels(), ] ) )); diff --git a/src/lib/items/DbModel.php b/src/lib/items/DbModel.php index 5c33c09b..6fab034b 100644 --- a/src/lib/items/DbModel.php +++ b/src/lib/items/DbModel.php @@ -13,7 +13,6 @@ use yii\base\BaseObject; use yii\db\ColumnSchema; use yii\helpers\Inflector; -use yii\helpers\StringHelper; use yii\helpers\VarDumper; use function array_filter; use function array_map; @@ -317,4 +316,21 @@ public function getModelClassDescription(): string } return FormatHelper::getFormattedDescription($this->description); } + + /** + * Return array of models that this models depends on exclusively used in faker. + * Models with `x-faker: false` or with self-reference are excluded + */ + public function fakerDependentModels(): array + { + $result = []; + foreach ($this->attributes as $attribute) { + if ($attribute->reference && $attribute->fakerStub) { + if ($this->name !== $attribute->reference) { # exclude self-referenced models + $result[] = $attribute->reference; + } + } + } + return array_unique($result); + } } diff --git a/src/lib/openapi/PropertySchema.php b/src/lib/openapi/PropertySchema.php index 6b27def1..e4a282dd 100644 --- a/src/lib/openapi/PropertySchema.php +++ b/src/lib/openapi/PropertySchema.php @@ -7,29 +7,27 @@ namespace cebe\yii2openapi\lib\openapi; -use yii\db\ColumnSchema; -use cebe\yii2openapi\generator\ApiGenerator; -use yii\db\mysql\Schema as MySqlSchema; -use SamIT\Yii2\MariaDb\Schema as MariaDbSchema; -use yii\db\pgsql\Schema as PgSqlSchema; -use cebe\yii2openapi\lib\items\Attribute; -use yii\base\NotSupportedException; use BadMethodCallException; use cebe\openapi\ReferenceContext; use cebe\openapi\spec\Reference; use cebe\openapi\SpecObjectInterface; +use cebe\yii2openapi\generator\ApiGenerator; use cebe\yii2openapi\lib\CustomSpecAttr; use cebe\yii2openapi\lib\exceptions\InvalidDefinitionException; +use cebe\yii2openapi\lib\traits\ForeignKeyConstraints; +use SamIT\Yii2\MariaDb\Schema as MariaDbSchema; use Throwable; use Yii; +use yii\base\NotSupportedException; +use yii\db\ColumnSchema; +use yii\db\mysql\Schema as MySqlSchema; +use yii\db\pgsql\Schema as PgSqlSchema; use yii\db\Schema as YiiDbSchema; use yii\helpers\Inflector; use yii\helpers\Json; use yii\helpers\StringHelper; -use yii\helpers\VarDumper; use function is_int; use function strpos; -use cebe\yii2openapi\lib\traits\ForeignKeyConstraints; class PropertySchema { @@ -49,7 +47,7 @@ class PropertySchema /** * @var null|bool|string * If `false`, no faker will be generated in faker model - * See more about usage in README.md file present in root directory of the project + * See more about usage in README.md file present in root directory of this library */ public $xFaker; diff --git a/tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/index.yml b/tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/index.yml index 89ffbd31..685dcac6 100644 --- a/tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/index.yml +++ b/tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/index.yml @@ -13,6 +13,20 @@ components: type: integer name: type: string + Fruit: + type: object + properties: + id: + type: integer + name: + type: string + Animal: + type: object + properties: + id: + type: integer + name: + type: string Invoice: title: Invoice x-table: invoices @@ -30,10 +44,16 @@ components: - $ref: '#/components/schemas/Invoice' - x-faker: true user: - $ref: '#/components/schemas/Invoice' + $ref: '#/components/schemas/User' user_2: allOf: - - $ref: '#/components/schemas/Invoice' + - $ref: '#/components/schemas/User' + - x-faker: false + fruit: + $ref: '#/components/schemas/Fruit' + animal: + allOf: + - $ref: '#/components/schemas/Animal' - x-faker: false paths: diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index fd102951..fefcaeb2 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -366,12 +366,12 @@ public function test52BugDependentonAllofWithXFakerFalse() { $testFile = Yii::getAlias("@specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/index.php"); $this->runGenerator($testFile); - $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ - 'recursive' => true, - ]); - $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql"), [ - 'recursive' => true, - ]); - $this->checkFiles($actualFiles, $expectedFiles); + // $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ + // 'recursive' => true, + // ]); + // $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql"), [ + // 'recursive' => true, + // ]); + // $this->checkFiles($actualFiles, $expectedFiles); } } From 702b880b2ec494afb49142d4a9f5b99a6a0546b3 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Thu, 26 Sep 2024 16:34:57 +0530 Subject: [PATCH 220/358] Fix failing tests --- .../162_bug_dollarref_with_x_faker/app/models/OrderFaker.php | 1 - tests/specs/menu/models/MenuFaker.php | 1 - 2 files changed, 2 deletions(-) diff --git a/tests/specs/issue_fix/162_bug_dollarref_with_x_faker/app/models/OrderFaker.php b/tests/specs/issue_fix/162_bug_dollarref_with_x_faker/app/models/OrderFaker.php index c8bbe589..0fca8d6c 100644 --- a/tests/specs/issue_fix/162_bug_dollarref_with_x_faker/app/models/OrderFaker.php +++ b/tests/specs/issue_fix/162_bug_dollarref_with_x_faker/app/models/OrderFaker.php @@ -43,7 +43,6 @@ public static function dependentOn() { return [ // just model class names - 'Invoice', ]; } diff --git a/tests/specs/menu/models/MenuFaker.php b/tests/specs/menu/models/MenuFaker.php index 64e82b3b..8af0e400 100644 --- a/tests/specs/menu/models/MenuFaker.php +++ b/tests/specs/menu/models/MenuFaker.php @@ -46,7 +46,6 @@ public static function dependentOn() { return [ // just model class names - 'Menu', ]; } From ff08c7166cb612d125e72b0bae9c76e2942e048f Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Thu, 26 Sep 2024 16:38:49 +0530 Subject: [PATCH 221/358] Fix test --- .../mysql/models/Animal.php | 10 +++++ .../mysql/models/AnimalFaker.php | 41 +++++++++++++++++++ .../mysql/models/Fruit.php | 10 +++++ .../mysql/models/FruitFaker.php | 41 +++++++++++++++++++ .../mysql/models/InvoiceFaker.php | 5 ++- .../mysql/models/base/Animal.php | 30 ++++++++++++++ .../mysql/models/base/Fruit.php | 30 ++++++++++++++ .../mysql/models/base/Invoice.php | 26 ++++++++++-- tests/unit/IssueFixTest.php | 14 +++---- 9 files changed, 195 insertions(+), 12 deletions(-) create mode 100644 tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql/models/Animal.php create mode 100644 tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql/models/AnimalFaker.php create mode 100644 tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql/models/Fruit.php create mode 100644 tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql/models/FruitFaker.php create mode 100644 tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql/models/base/Animal.php create mode 100644 tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql/models/base/Fruit.php diff --git a/tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql/models/Animal.php b/tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql/models/Animal.php new file mode 100644 index 00000000..92caf2f3 --- /dev/null +++ b/tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql/models/Animal.php @@ -0,0 +1,10 @@ +generateModels(['author_id' => 1]); + * $model = (new PostFaker())->generateModels(function($model, $faker, $uniqueFaker) { + * $model->scenario = 'create'; + * $model->author_id = 1; + * return $model; + * }); + **/ + public function generateModel($attributes = []) + { + $faker = $this->faker; + $uniqueFaker = $this->uniqueFaker; + $model = new Animal(); + //$model->id = $uniqueFaker->numberBetween(0, 1000000); + $model->name = $faker->sentence; + if (!is_callable($attributes)) { + $model->setAttributes($attributes, false); + } else { + $model = $attributes($model, $faker, $uniqueFaker); + } + return $model; + } +} diff --git a/tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql/models/Fruit.php b/tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql/models/Fruit.php new file mode 100644 index 00000000..c74c53d9 --- /dev/null +++ b/tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql/models/Fruit.php @@ -0,0 +1,10 @@ +generateModels(['author_id' => 1]); + * $model = (new PostFaker())->generateModels(function($model, $faker, $uniqueFaker) { + * $model->scenario = 'create'; + * $model->author_id = 1; + * return $model; + * }); + **/ + public function generateModel($attributes = []) + { + $faker = $this->faker; + $uniqueFaker = $this->uniqueFaker; + $model = new Fruit(); + //$model->id = $uniqueFaker->numberBetween(0, 1000000); + $model->name = $faker->sentence; + if (!is_callable($attributes)) { + $model->setAttributes($attributes, false); + } else { + $model = $attributes($model, $faker, $uniqueFaker); + } + return $model; + } +} diff --git a/tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql/models/InvoiceFaker.php b/tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql/models/InvoiceFaker.php index 2b028222..cd835b11 100644 --- a/tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql/models/InvoiceFaker.php +++ b/tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql/models/InvoiceFaker.php @@ -31,7 +31,8 @@ public function generateModel($attributes = []) $model = new Invoice(); //$model->id = $uniqueFaker->numberBetween(0, 1000000); $model->reference_invoice_2_id = $faker->randomElement(\app\models\Invoice::find()->select("id")->column()); - $model->user_id = $faker->randomElement(\app\models\Invoice::find()->select("id")->column()); + $model->user_id = $faker->randomElement(\app\models\User::find()->select("id")->column()); + $model->fruit_id = $faker->randomElement(\app\models\Fruit::find()->select("id")->column()); if (!is_callable($attributes)) { $model->setAttributes($attributes, false); } else { @@ -44,6 +45,8 @@ public static function dependentOn() { return [ // just model class names + 'User', + 'Fruit', ]; } diff --git a/tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql/models/base/Animal.php b/tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql/models/base/Animal.php new file mode 100644 index 00000000..a99b34da --- /dev/null +++ b/tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql/models/base/Animal.php @@ -0,0 +1,30 @@ + [['name'], 'trim'], + 'name_string' => [['name'], 'string'], + ]; + } +} diff --git a/tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql/models/base/Fruit.php b/tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql/models/base/Fruit.php new file mode 100644 index 00000000..ccdbe894 --- /dev/null +++ b/tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql/models/base/Fruit.php @@ -0,0 +1,30 @@ + [['name'], 'trim'], + 'name_string' => [['name'], 'string'], + ]; + } +} diff --git a/tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql/models/base/Invoice.php b/tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql/models/base/Invoice.php index f4cb797e..1495d16b 100644 --- a/tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql/models/base/Invoice.php +++ b/tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql/models/base/Invoice.php @@ -14,11 +14,15 @@ * @property int $reference_invoice_2_id * @property int $user_id * @property int $user_2_id + * @property int $fruit_id + * @property int $animal_id * * @property \app\models\Invoice $referenceInvoice * @property \app\models\Invoice $referenceInvoice2 - * @property \app\models\Invoice $user - * @property \app\models\Invoice $user2 + * @property \app\models\User $user + * @property \app\models\User $user2 + * @property \app\models\Fruit $fruit + * @property \app\models\Animal $animal */ abstract class Invoice extends \yii\db\ActiveRecord { @@ -38,6 +42,10 @@ public function rules() 'user_id_exist' => [['user_id'], 'exist', 'targetRelation' => 'User'], 'user_2_id_integer' => [['user_2_id'], 'integer'], 'user_2_id_exist' => [['user_2_id'], 'exist', 'targetRelation' => 'User2'], + 'fruit_id_integer' => [['fruit_id'], 'integer'], + 'fruit_id_exist' => [['fruit_id'], 'exist', 'targetRelation' => 'Fruit'], + 'animal_id_integer' => [['animal_id'], 'integer'], + 'animal_id_exist' => [['animal_id'], 'exist', 'targetRelation' => 'Animal'], ]; } @@ -53,11 +61,21 @@ public function getReferenceInvoice2() public function getUser() { - return $this->hasOne(\app\models\Invoice::class, ['id' => 'user_id']); + return $this->hasOne(\app\models\User::class, ['id' => 'user_id']); } public function getUser2() { - return $this->hasOne(\app\models\Invoice::class, ['id' => 'user_2_id']); + return $this->hasOne(\app\models\User::class, ['id' => 'user_2_id']); + } + + public function getFruit() + { + return $this->hasOne(\app\models\Fruit::class, ['id' => 'fruit_id']); + } + + public function getAnimal() + { + return $this->hasOne(\app\models\Animal::class, ['id' => 'animal_id']); } } diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index fefcaeb2..fd102951 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -366,12 +366,12 @@ public function test52BugDependentonAllofWithXFakerFalse() { $testFile = Yii::getAlias("@specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/index.php"); $this->runGenerator($testFile); - // $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ - // 'recursive' => true, - // ]); - // $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql"), [ - // 'recursive' => true, - // ]); - // $this->checkFiles($actualFiles, $expectedFiles); + $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ + 'recursive' => true, + ]); + $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql"), [ + 'recursive' => true, + ]); + $this->checkFiles($actualFiles, $expectedFiles); } } From d4d01f5c07314f5bc6489dc6ba010b945159919d Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Sat, 28 Sep 2024 11:35:30 +0530 Subject: [PATCH 222/358] Create PR --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 1cd2090b..3bb79307 100644 --- a/README.md +++ b/README.md @@ -568,3 +568,4 @@ Professional support, consulting as well as software development services are av https://www.cebe.cc/en/contact Development of this library is sponsored by [cebe.:cloud: "Your Professional Deployment Platform"](https://cebe.cloud). + From 290b7be3ad8e1ce47ff83a5a88ace08ee872706e Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Sat, 28 Sep 2024 13:15:37 +0530 Subject: [PATCH 223/358] Add a failing test --- .../index.php | 13 ++++++++ .../index.yml | 27 ++++++++++++++++ tests/unit/IssueFixTest.php | 32 +++++++++++++++++++ 3 files changed, 72 insertions(+) create mode 100644 tests/specs/issue_fix/58_create_migration_for_column_position_change_if_a_field_position_is_changed_in_spec/index.php create mode 100644 tests/specs/issue_fix/58_create_migration_for_column_position_change_if_a_field_position_is_changed_in_spec/index.yml diff --git a/tests/specs/issue_fix/58_create_migration_for_column_position_change_if_a_field_position_is_changed_in_spec/index.php b/tests/specs/issue_fix/58_create_migration_for_column_position_change_if_a_field_position_is_changed_in_spec/index.php new file mode 100644 index 00000000..8ec860a4 --- /dev/null +++ b/tests/specs/issue_fix/58_create_migration_for_column_position_change_if_a_field_position_is_changed_in_spec/index.php @@ -0,0 +1,13 @@ + '@specs/issue_fix/58_create_migration_for_column_position_change_if_a_field_position_is_changed_in_spec/index.yml', + 'generateUrls' => false, + 'generateModels' => true, + 'excludeModels' => [ + 'Error', + ], + 'generateControllers' => false, + 'generateMigrations' => true, + 'generateModelFaker' => true, // `generateModels` must be `true` in order to use `generateModelFaker` as `true` +]; diff --git a/tests/specs/issue_fix/58_create_migration_for_column_position_change_if_a_field_position_is_changed_in_spec/index.yml b/tests/specs/issue_fix/58_create_migration_for_column_position_change_if_a_field_position_is_changed_in_spec/index.yml new file mode 100644 index 00000000..62612c44 --- /dev/null +++ b/tests/specs/issue_fix/58_create_migration_for_column_position_change_if_a_field_position_is_changed_in_spec/index.yml @@ -0,0 +1,27 @@ +openapi: 3.0.3 + +info: + title: 'Create migration for column position change if a field position is changed in spec #58' + version: 1.0.0 + +components: + schemas: + Fruit: + type: object + properties: + id: + type: integer + name: + type: string + description: desc + # colour: + # type: string + description: + type: string + +paths: + '/': + get: + responses: + '200': + description: OK diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index b6c7abdb..341668ca 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -360,4 +360,36 @@ public function test158BugGiiapiGeneratedRulesEnumWithTrim() ]); $this->checkFiles($actualFiles, $expectedFiles); } + + // https://github.com/php-openapi/yii2-openapi/issues/58 + public function test58CreateMigrationForColumnPositionChangeIfAFieldPositionIsChangedInSpec() + { + $this->deleteTableFor58CreateMigrationForColumnPositionChangeIfAFieldPositionIsChangedInSpec(); + $this->createTableFor58CreateMigrationForColumnPositionChangeIfAFieldPositionIsChangedInSpec(); + + $testFile = Yii::getAlias("@specs/issue_fix/58_create_migration_for_column_position_change_if_a_field_position_is_changed_in_spec/index.php"); + $this->runGenerator($testFile); + // $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ + // 'recursive' => true, + // ]); + // $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/58_create_migration_for_column_position_change_if_a_field_position_is_changed_in_spec/mysql"), [ + // 'recursive' => true, + // ]); + // $this->checkFiles($actualFiles, $expectedFiles); + $this->deleteTableFor58CreateMigrationForColumnPositionChangeIfAFieldPositionIsChangedInSpec(); + } + + private function createTableFor58CreateMigrationForColumnPositionChangeIfAFieldPositionIsChangedInSpec() + { + Yii::$app->db->createCommand()->createTable('{{%fruits}}', [ + 'id' => 'pk', + 'description' => 'text', + 'name' => 'varchar(255) COMMENT "some-comment"', + ])->execute(); + } + + private function deleteTableFor58CreateMigrationForColumnPositionChangeIfAFieldPositionIsChangedInSpec() + { + Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%fruits}}')->execute(); + } } From 3718dc63519f4627d0b3569913b2191929346df3 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Sat, 28 Sep 2024 13:15:47 +0530 Subject: [PATCH 224/358] Cleanup --- README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/README.md b/README.md index 3bb79307..1cd2090b 100644 --- a/README.md +++ b/README.md @@ -568,4 +568,3 @@ Professional support, consulting as well as software development services are av https://www.cebe.cc/en/contact Development of this library is sponsored by [cebe.:cloud: "Your Professional Deployment Platform"](https://cebe.cloud). - From 9ec5b1b86673b328b5d3b3c6d9ef38779c922376 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Sat, 28 Sep 2024 13:19:34 +0530 Subject: [PATCH 225/358] Create PR --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 1cd2090b..3bb79307 100644 --- a/README.md +++ b/README.md @@ -568,3 +568,4 @@ Professional support, consulting as well as software development services are av https://www.cebe.cc/en/contact Development of this library is sponsored by [cebe.:cloud: "Your Professional Deployment Platform"](https://cebe.cloud). + From 87b01da1ce48961e76ad452e5c40e4febb63d46b Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Sat, 28 Sep 2024 13:30:40 +0530 Subject: [PATCH 226/358] Add failing test --- README.md | 1 - .../index.php | 14 ++++++++++ .../index.yml | 27 +++++++++++++++++++ tests/unit/IssueFixTest.php | 14 ++++++++++ 4 files changed, 55 insertions(+), 1 deletion(-) create mode 100644 tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/index.php create mode 100644 tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/index.yml diff --git a/README.md b/README.md index 3bb79307..1cd2090b 100644 --- a/README.md +++ b/README.md @@ -568,4 +568,3 @@ Professional support, consulting as well as software development services are av https://www.cebe.cc/en/contact Development of this library is sponsored by [cebe.:cloud: "Your Professional Deployment Platform"](https://cebe.cloud). - diff --git a/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/index.php b/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/index.php new file mode 100644 index 00000000..8a96371f --- /dev/null +++ b/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/index.php @@ -0,0 +1,14 @@ + '@specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/index.yml', + 'generateUrls' => false, + 'generateModels' => true, + 'excludeModels' => [ + 'Error', + ], + 'generateControllers' => false, + 'generateMigrations' => true, + 'generateModelFaker' => true, // `generateModels` must be `true` in order to use `generateModelFaker` as `true` +]; + diff --git a/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/index.yml b/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/index.yml new file mode 100644 index 00000000..b1dc40f3 --- /dev/null +++ b/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/index.yml @@ -0,0 +1,27 @@ +openapi: 3.0.3 + +info: + title: 'Description of a property in spec must correspond to DB TABLE COLUMN COMMENT #60' + version: 1.0.0 + +components: + schemas: + Fruit: + type: object + properties: + id: + type: integer + name: + type: string + description: desc + # colour: + # type: string + description: + type: string + +paths: + '/': + get: + responses: + '200': + description: OK diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index b6c7abdb..6eed92e9 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -360,4 +360,18 @@ public function test158BugGiiapiGeneratedRulesEnumWithTrim() ]); $this->checkFiles($actualFiles, $expectedFiles); } + + // https://github.com/php-openapi/yii2-openapi/issues/60 + public function test60DescriptionOfAPropertyInSpecMustCorrespondToDbTableColumnComment() + { + $testFile = Yii::getAlias("@specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/index.php"); + $this->runGenerator($testFile); + // $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ + // 'recursive' => true, + // ]); + // $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/mysql"), [ + // 'recursive' => true, + // ]); + // $this->checkFiles($actualFiles, $expectedFiles); + } } From 1e408b7dde8a47169fe2edf9d87baa005688e45f Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Sat, 28 Sep 2024 18:50:34 +0530 Subject: [PATCH 227/358] Fix this issue --- src/lib/ColumnToCode.php | 14 +++++++++----- src/lib/items/Attribute.php | 1 + .../index.php | 1 - .../index.yml | 2 ++ 4 files changed, 12 insertions(+), 6 deletions(-) diff --git a/src/lib/ColumnToCode.php b/src/lib/ColumnToCode.php index e9a570bc..5f152c89 100644 --- a/src/lib/ColumnToCode.php +++ b/src/lib/ColumnToCode.php @@ -84,9 +84,9 @@ class ColumnToCode */ private $isPk = false; - private $rawParts = ['type' => null, 'nullable' => null, 'default' => null, 'position' => null]; + private $rawParts = ['type' => null, 'nullable' => null, 'default' => null, 'position' => null, 'comment' => null]; - private $fluentParts = ['type' => null, 'nullable' => null, 'default' => null, 'position' => null]; + private $fluentParts = ['type' => null, 'nullable' => null, 'default' => null, 'position' => null, 'comment' => null]; /** * @var bool @@ -160,7 +160,8 @@ public function getCode(bool $quoted = false):string $this->fluentParts['type'], $this->fluentParts['nullable'], $this->fluentParts['default'], - $this->fluentParts['position'] + $this->fluentParts['position'], + $this->fluentParts['comment'], ]); array_unshift($parts, '$this'); return implode('->', array_filter(array_map('trim', $parts))); @@ -175,9 +176,12 @@ public function getCode(bool $quoted = false):string } $code = $this->rawParts['type'] . ' ' . $this->rawParts['nullable'] . $default; - if ((ApiGenerator::isMysql() || ApiGenerator::isMariaDb()) && $this->rawParts['position']) { - $code .= ' ' . $this->rawParts['position']; + + if ((ApiGenerator::isMysql() || ApiGenerator::isMariaDb())) { + $code .= $this->rawParts['position'] ? ' ' . $this->rawParts['position'] : ''; + $code .= $this->rawParts['comment'] ? ' '.$this->rawParts['comment'] : ''; } + if (ApiGenerator::isPostgres() && $this->alterByXDbType) { return $quoted ? VarDumper::export($this->rawParts['type']) : $this->rawParts['type']; } diff --git a/src/lib/items/Attribute.php b/src/lib/items/Attribute.php index 5b62e49d..b7a991bf 100644 --- a/src/lib/items/Attribute.php +++ b/src/lib/items/Attribute.php @@ -318,6 +318,7 @@ public function toColumnSchema():ColumnSchema 'allowNull' => $this->allowNull(), 'size' => $this->size > 0 ? $this->size : null, 'xDbType' => $this->xDbType, + 'comment' => $this->description, ]); $column->isPrimaryKey = $this->primary; $column->autoIncrement = $this->primary && $this->phpType === 'int'; diff --git a/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/index.php b/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/index.php index 8a96371f..5642a696 100644 --- a/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/index.php +++ b/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/index.php @@ -11,4 +11,3 @@ 'generateMigrations' => true, 'generateModelFaker' => true, // `generateModels` must be `true` in order to use `generateModelFaker` as `true` ]; - diff --git a/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/index.yml b/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/index.yml index b1dc40f3..43e75c38 100644 --- a/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/index.yml +++ b/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/index.yml @@ -18,6 +18,8 @@ components: # type: string description: type: string + x-db-type: varchar + description: desc 2 paths: '/': From 2fb2d7b3ccb4282b6263455535a397a39cd9269a Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Sat, 28 Sep 2024 18:50:49 +0530 Subject: [PATCH 228/358] Move `resolve()` method --- src/lib/ColumnToCode.php | 104 ++++++++++++++++++++------------------- 1 file changed, 54 insertions(+), 50 deletions(-) diff --git a/src/lib/ColumnToCode.php b/src/lib/ColumnToCode.php index 5f152c89..73030ea5 100644 --- a/src/lib/ColumnToCode.php +++ b/src/lib/ColumnToCode.php @@ -150,6 +150,60 @@ public function __construct( $this->resolve(); } + private function resolve():void + { + $dbType = $this->typeWithoutSize(strtolower($this->column->dbType)); + $type = $this->column->type; + $this->resolvePosition(); + //Primary Keys + if (array_key_exists($type, self::PK_TYPE_MAP)) { + $this->rawParts['type'] = $type; + $this->fluentParts['type'] = self::PK_TYPE_MAP[$type]; + $this->isPk = true; + return; + } + if (array_key_exists($dbType, self::PK_TYPE_MAP)) { + $this->rawParts['type'] = $dbType; + $this->fluentParts['type'] = self::PK_TYPE_MAP[$dbType]; + $this->isPk = true; + return; + } + + if ($dbType === 'varchar') { + $type = $dbType = 'string'; + } + $fluentSize = $this->column->size ? '(' . $this->column->size . ')' : '()'; + $rawSize = $this->column->size ? '(' . $this->column->size . ')' : ''; + $this->rawParts['nullable'] = $this->column->allowNull ? 'NULL' : 'NOT NULL'; + $this->fluentParts['nullable'] = $this->column->allowNull === true ? 'null()' : 'notNull()'; + + $this->fluentParts['comment'] = $this->column->comment ? 'comment(\''.$this->column->comment.'\')' : $this->fluentParts['comment']; + $this->rawParts['comment'] = $this->column->comment ? 'COMMENT \''.$this->column->comment.'\'' : $this->fluentParts['comment']; + + if (array_key_exists($dbType, self::INT_TYPE_MAP)) { + $this->fluentParts['type'] = self::INT_TYPE_MAP[$dbType] . $fluentSize; + $this->rawParts['type'] = + $this->column->dbType . (strpos($this->column->dbType, '(') !== false ? '' : $rawSize); + } elseif (array_key_exists($type, self::INT_TYPE_MAP)) { + $this->fluentParts['type'] = self::INT_TYPE_MAP[$type] . $fluentSize; + $this->rawParts['type'] = + $this->column->dbType . (strpos($this->column->dbType, '(') !== false ? '' : $rawSize); + } elseif ($this->isEnum()) { + $this->resolveEnumType(); + } elseif ($this->isDecimal()) { + $this->fluentParts['type'] = $this->column->dbType; + $this->rawParts['type'] = $this->column->dbType; + } else { + $this->fluentParts['type'] = $type . $fluentSize; + $this->rawParts['type'] = + $this->column->dbType . (strpos($this->column->dbType, '(') !== false ? '' : $rawSize); + } + + $this->isBuiltinType = $this->raw ? false : $this->getIsBuiltinType($type, $dbType); + + $this->resolveDefaultValue(); + } + public function getCode(bool $quoted = false):string { if ($this->isPk) { @@ -324,56 +378,6 @@ private function defaultValueArray(array $value):string return "'{" . trim(Json::encode($value, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_HEX_QUOT), '[]') . "}'"; } - private function resolve():void - { - $dbType = $this->typeWithoutSize(strtolower($this->column->dbType)); - $type = $this->column->type; - $this->resolvePosition(); - //Primary Keys - if (array_key_exists($type, self::PK_TYPE_MAP)) { - $this->rawParts['type'] = $type; - $this->fluentParts['type'] = self::PK_TYPE_MAP[$type]; - $this->isPk = true; - return; - } - if (array_key_exists($dbType, self::PK_TYPE_MAP)) { - $this->rawParts['type'] = $dbType; - $this->fluentParts['type'] = self::PK_TYPE_MAP[$dbType]; - $this->isPk = true; - return; - } - - if ($dbType === 'varchar') { - $type = $dbType = 'string'; - } - $fluentSize = $this->column->size ? '(' . $this->column->size . ')' : '()'; - $rawSize = $this->column->size ? '(' . $this->column->size . ')' : ''; - $this->rawParts['nullable'] = $this->column->allowNull ? 'NULL' : 'NOT NULL'; - $this->fluentParts['nullable'] = $this->column->allowNull === true ? 'null()' : 'notNull()'; - if (array_key_exists($dbType, self::INT_TYPE_MAP)) { - $this->fluentParts['type'] = self::INT_TYPE_MAP[$dbType] . $fluentSize; - $this->rawParts['type'] = - $this->column->dbType . (strpos($this->column->dbType, '(') !== false ? '' : $rawSize); - } elseif (array_key_exists($type, self::INT_TYPE_MAP)) { - $this->fluentParts['type'] = self::INT_TYPE_MAP[$type] . $fluentSize; - $this->rawParts['type'] = - $this->column->dbType . (strpos($this->column->dbType, '(') !== false ? '' : $rawSize); - } elseif ($this->isEnum()) { - $this->resolveEnumType(); - } elseif ($this->isDecimal()) { - $this->fluentParts['type'] = $this->column->dbType; - $this->rawParts['type'] = $this->column->dbType; - } else { - $this->fluentParts['type'] = $type . $fluentSize; - $this->rawParts['type'] = - $this->column->dbType . (strpos($this->column->dbType, '(') !== false ? '' : $rawSize); - } - - $this->isBuiltinType = $this->raw ? false : $this->getIsBuiltinType($type, $dbType); - - $this->resolveDefaultValue(); - } - /** * @param $type * @param $dbType From f998279ad0f218ed2aec766cd9c26eecfb3dca08 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Sat, 28 Sep 2024 19:06:04 +0530 Subject: [PATCH 229/358] Add test to ensure existing comments are preserved --- .../index.yml | 8 ++++++++ tests/unit/IssueFixTest.php | 17 +++++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/index.yml b/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/index.yml index 43e75c38..83f3a948 100644 --- a/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/index.yml +++ b/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/index.yml @@ -20,6 +20,14 @@ components: type: string x-db-type: varchar description: desc 2 + Animal: + type: object + properties: + id: + type: integer + name: + type: integer + description: desc paths: '/': diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index 6eed92e9..45ace04d 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -364,6 +364,8 @@ public function test158BugGiiapiGeneratedRulesEnumWithTrim() // https://github.com/php-openapi/yii2-openapi/issues/60 public function test60DescriptionOfAPropertyInSpecMustCorrespondToDbTableColumnComment() { + $this->deleteTableFor60DescriptionOfAPropertyInSpecMustCorrespondToDbTableColumnComment(); + $this->createTableFor60DescriptionOfAPropertyInSpecMustCorrespondToDbTableColumnComment(); $testFile = Yii::getAlias("@specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/index.php"); $this->runGenerator($testFile); // $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ @@ -373,5 +375,20 @@ public function test60DescriptionOfAPropertyInSpecMustCorrespondToDbTableColumnC // 'recursive' => true, // ]); // $this->checkFiles($actualFiles, $expectedFiles); + + $this->deleteTableFor60DescriptionOfAPropertyInSpecMustCorrespondToDbTableColumnComment(); + } + + private function createTableFor60DescriptionOfAPropertyInSpecMustCorrespondToDbTableColumnComment() + { + Yii::$app->db->createCommand()->createTable('{{%animals}}', [ + 'id' => 'pk', + 'name' => 'text comment "the name"', + ])->execute(); + } + + private function deleteTableFor60DescriptionOfAPropertyInSpecMustCorrespondToDbTableColumnComment() + { + Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%animals}}')->execute(); } } From 4a117856be13e05234f6dfee717eb55dcfe19a93 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Sat, 28 Sep 2024 19:24:35 +0530 Subject: [PATCH 230/358] Fix failing tests --- src/generator/default/dbmodel.php | 8 ++++---- .../migrations/m200000_000002_create_table_blog_posts.php | 4 ++-- .../m200000_000004_create_table_post_comments.php | 4 ++-- .../m200000_000002_create_table_blog_posts.php | 4 ++-- .../m200000_000004_create_table_post_comments.php | 4 ++-- .../m200000_000002_create_table_blog_posts.php | 4 ++-- .../m200000_000004_create_table_post_comments.php | 4 ++-- .../m200000_000002_create_table_blog_posts.php | 4 ++-- .../m200000_000004_create_table_post_comments.php | 4 ++-- .../m200000_000005_change_table_v2_comments.php | 2 +- .../m200000_000005_change_table_v2_comments.php | 2 +- .../m200000_000005_change_table_v2_comments.php | 2 +- .../m200000_000002_create_table_webhooks.php | 2 +- .../m200000_000002_create_table_webhooks.php | 2 +- .../m200000_000000_create_table_accounts.php | 2 +- .../m200000_000001_create_table_contacts.php | 2 +- .../m200000_000001_create_table_b123s.php | 2 +- .../m200000_000002_create_table_a123s.php | 2 +- .../m200000_000003_create_table_accounts.php | 2 +- .../m200000_000005_create_table_domains.php | 4 ++-- .../m200000_000006_create_table_e123s.php | 2 +- .../m200000_000007_create_table_routings.php | 6 +++--- .../m200000_000003_create_table_pristines.php | 2 +- .../m200000_000003_create_table_pristines.php | 2 +- .../m200000_000003_create_table_pristines.php | 2 +- .../m200000_000003_create_table_pristines.php | 2 +- .../m200000_000003_create_table_pristines.php | 2 +- .../m200000_000003_create_table_pristines.php | 2 +- .../m200000_000001_create_table_postxes.php | 8 ++++---- 29 files changed, 46 insertions(+), 46 deletions(-) diff --git a/src/generator/default/dbmodel.php b/src/generator/default/dbmodel.php index 17fa4a84..a3d269b6 100644 --- a/src/generator/default/dbmodel.php +++ b/src/generator/default/dbmodel.php @@ -49,8 +49,8 @@ */ abstract class getClassName() ?> extends \yii\db\ActiveRecord { -getScenarios()): -foreach($scenarios as $scenario): ?> +getScenarios()): +foreach ($scenarios as $scenario): ?> /** * @@ -76,7 +76,7 @@ public static function tableName() { return getTableAlias()) ?>; } - + /** * Automatically generated scenarios from the model 'x-scenarios'. @@ -92,7 +92,7 @@ public function scenarios() $default = parent::scenarios()[self::SCENARIO_DEFAULT]; return [ - + self:: => $default, /** diff --git a/tests/specs/blog/migrations/m200000_000002_create_table_blog_posts.php b/tests/specs/blog/migrations/m200000_000002_create_table_blog_posts.php index b0b8e371..c7cc90fb 100644 --- a/tests/specs/blog/migrations/m200000_000002_create_table_blog_posts.php +++ b/tests/specs/blog/migrations/m200000_000002_create_table_blog_posts.php @@ -11,10 +11,10 @@ public function up() 0 => 'uid varchar(128) NOT NULL', 'title' => $this->string(255)->notNull(), 'slug' => $this->string(200)->null()->defaultValue(null), - 'category_id' => $this->integer()->notNull(), + 'category_id' => $this->integer()->notNull()->comment('Category of posts'), 'active' => $this->boolean()->notNull()->defaultValue(false), 'created_at' => $this->date()->null()->defaultValue(null), - 'created_by_id' => $this->integer()->null()->defaultValue(null), + 'created_by_id' => $this->integer()->null()->defaultValue(null)->comment('The User'), ]); $this->addPrimaryKey('pk_blog_posts_uid', '{{%blog_posts}}', 'uid'); $this->createIndex('blog_posts_title_key', '{{%blog_posts}}', 'title', true); diff --git a/tests/specs/blog/migrations/m200000_000004_create_table_post_comments.php b/tests/specs/blog/migrations/m200000_000004_create_table_post_comments.php index c16766da..175a32b7 100644 --- a/tests/specs/blog/migrations/m200000_000004_create_table_post_comments.php +++ b/tests/specs/blog/migrations/m200000_000004_create_table_post_comments.php @@ -9,8 +9,8 @@ public function up() { $this->createTable('{{%post_comments}}', [ 'id' => $this->bigPrimaryKey(), - 'post_id' => $this->string(128)->notNull(), - 'author_id' => $this->integer()->notNull(), + 'post_id' => $this->string(128)->notNull()->comment('A blog post (uid used as pk for test purposes)'), + 'author_id' => $this->integer()->notNull()->comment('The User'), 0 => 'message json NOT NULL', 1 => 'meta_data json NOT NULL', 'created_at' => $this->integer()->notNull(), diff --git a/tests/specs/blog/migrations_maria_db/m200000_000002_create_table_blog_posts.php b/tests/specs/blog/migrations_maria_db/m200000_000002_create_table_blog_posts.php index b0b8e371..c7cc90fb 100644 --- a/tests/specs/blog/migrations_maria_db/m200000_000002_create_table_blog_posts.php +++ b/tests/specs/blog/migrations_maria_db/m200000_000002_create_table_blog_posts.php @@ -11,10 +11,10 @@ public function up() 0 => 'uid varchar(128) NOT NULL', 'title' => $this->string(255)->notNull(), 'slug' => $this->string(200)->null()->defaultValue(null), - 'category_id' => $this->integer()->notNull(), + 'category_id' => $this->integer()->notNull()->comment('Category of posts'), 'active' => $this->boolean()->notNull()->defaultValue(false), 'created_at' => $this->date()->null()->defaultValue(null), - 'created_by_id' => $this->integer()->null()->defaultValue(null), + 'created_by_id' => $this->integer()->null()->defaultValue(null)->comment('The User'), ]); $this->addPrimaryKey('pk_blog_posts_uid', '{{%blog_posts}}', 'uid'); $this->createIndex('blog_posts_title_key', '{{%blog_posts}}', 'title', true); diff --git a/tests/specs/blog/migrations_maria_db/m200000_000004_create_table_post_comments.php b/tests/specs/blog/migrations_maria_db/m200000_000004_create_table_post_comments.php index d4971f43..5883fa5b 100644 --- a/tests/specs/blog/migrations_maria_db/m200000_000004_create_table_post_comments.php +++ b/tests/specs/blog/migrations_maria_db/m200000_000004_create_table_post_comments.php @@ -9,8 +9,8 @@ public function up() { $this->createTable('{{%post_comments}}', [ 'id' => $this->bigPrimaryKey(), - 'post_id' => $this->string(128)->notNull(), - 'author_id' => $this->integer()->notNull(), + 'post_id' => $this->string(128)->notNull()->comment('A blog post (uid used as pk for test purposes)'), + 'author_id' => $this->integer()->notNull()->comment('The User'), 0 => 'message json NOT NULL DEFAULT \'[]\'', 1 => 'meta_data json NOT NULL DEFAULT \'[]\'', 'created_at' => $this->integer()->notNull(), diff --git a/tests/specs/blog/migrations_mysql_db/m200000_000002_create_table_blog_posts.php b/tests/specs/blog/migrations_mysql_db/m200000_000002_create_table_blog_posts.php index b0b8e371..c7cc90fb 100644 --- a/tests/specs/blog/migrations_mysql_db/m200000_000002_create_table_blog_posts.php +++ b/tests/specs/blog/migrations_mysql_db/m200000_000002_create_table_blog_posts.php @@ -11,10 +11,10 @@ public function up() 0 => 'uid varchar(128) NOT NULL', 'title' => $this->string(255)->notNull(), 'slug' => $this->string(200)->null()->defaultValue(null), - 'category_id' => $this->integer()->notNull(), + 'category_id' => $this->integer()->notNull()->comment('Category of posts'), 'active' => $this->boolean()->notNull()->defaultValue(false), 'created_at' => $this->date()->null()->defaultValue(null), - 'created_by_id' => $this->integer()->null()->defaultValue(null), + 'created_by_id' => $this->integer()->null()->defaultValue(null)->comment('The User'), ]); $this->addPrimaryKey('pk_blog_posts_uid', '{{%blog_posts}}', 'uid'); $this->createIndex('blog_posts_title_key', '{{%blog_posts}}', 'title', true); diff --git a/tests/specs/blog/migrations_mysql_db/m200000_000004_create_table_post_comments.php b/tests/specs/blog/migrations_mysql_db/m200000_000004_create_table_post_comments.php index c16766da..175a32b7 100644 --- a/tests/specs/blog/migrations_mysql_db/m200000_000004_create_table_post_comments.php +++ b/tests/specs/blog/migrations_mysql_db/m200000_000004_create_table_post_comments.php @@ -9,8 +9,8 @@ public function up() { $this->createTable('{{%post_comments}}', [ 'id' => $this->bigPrimaryKey(), - 'post_id' => $this->string(128)->notNull(), - 'author_id' => $this->integer()->notNull(), + 'post_id' => $this->string(128)->notNull()->comment('A blog post (uid used as pk for test purposes)'), + 'author_id' => $this->integer()->notNull()->comment('The User'), 0 => 'message json NOT NULL', 1 => 'meta_data json NOT NULL', 'created_at' => $this->integer()->notNull(), diff --git a/tests/specs/blog/migrations_pgsql_db/m200000_000002_create_table_blog_posts.php b/tests/specs/blog/migrations_pgsql_db/m200000_000002_create_table_blog_posts.php index 8639040d..a7266997 100644 --- a/tests/specs/blog/migrations_pgsql_db/m200000_000002_create_table_blog_posts.php +++ b/tests/specs/blog/migrations_pgsql_db/m200000_000002_create_table_blog_posts.php @@ -11,10 +11,10 @@ public function safeUp() 0 => '"uid" varchar(128) NOT NULL', 'title' => $this->string(255)->notNull(), 'slug' => $this->string(200)->null()->defaultValue(null), - 'category_id' => $this->integer()->notNull(), + 'category_id' => $this->integer()->notNull()->comment('Category of posts'), 'active' => $this->boolean()->notNull()->defaultValue(false), 'created_at' => $this->date()->null()->defaultValue(null), - 'created_by_id' => $this->integer()->null()->defaultValue(null), + 'created_by_id' => $this->integer()->null()->defaultValue(null)->comment('The User'), ]); $this->addPrimaryKey('pk_blog_posts_uid', '{{%blog_posts}}', 'uid'); $this->createIndex('blog_posts_title_key', '{{%blog_posts}}', 'title', true); diff --git a/tests/specs/blog/migrations_pgsql_db/m200000_000004_create_table_post_comments.php b/tests/specs/blog/migrations_pgsql_db/m200000_000004_create_table_post_comments.php index 2aa48549..1229677b 100644 --- a/tests/specs/blog/migrations_pgsql_db/m200000_000004_create_table_post_comments.php +++ b/tests/specs/blog/migrations_pgsql_db/m200000_000004_create_table_post_comments.php @@ -9,8 +9,8 @@ public function safeUp() { $this->createTable('{{%post_comments}}', [ 'id' => $this->bigPrimaryKey(), - 'post_id' => $this->string(128)->notNull(), - 'author_id' => $this->integer()->notNull(), + 'post_id' => $this->string(128)->notNull()->comment('A blog post (uid used as pk for test purposes)'), + 'author_id' => $this->integer()->notNull()->comment('The User'), 0 => '"message" json NOT NULL DEFAULT \'[]\'', 1 => '"meta_data" json NOT NULL DEFAULT \'[]\'', 'created_at' => $this->integer()->notNull(), diff --git a/tests/specs/blog_v2/migrations_maria_db/m200000_000005_change_table_v2_comments.php b/tests/specs/blog_v2/migrations_maria_db/m200000_000005_change_table_v2_comments.php index 75553729..e2f7b4ad 100644 --- a/tests/specs/blog_v2/migrations_maria_db/m200000_000005_change_table_v2_comments.php +++ b/tests/specs/blog_v2/migrations_maria_db/m200000_000005_change_table_v2_comments.php @@ -9,7 +9,7 @@ public function up() { $this->dropForeignKey('fk_v2_comments_post_id_v2_posts_uid', '{{%v2_comments}}'); $this->dropForeignKey('fk_v2_comments_author_id_v2_users_id', '{{%v2_comments}}'); - $this->addColumn('{{%v2_comments}}', 'user_id', $this->bigInteger()->null()->defaultValue(null)->after('post_id')); + $this->addColumn('{{%v2_comments}}', 'user_id', $this->bigInteger()->null()->defaultValue(null)->after('post_id')->comment('The User')); $this->dropColumn('{{%v2_comments}}', 'author_id'); $this->alterColumn('{{%v2_comments}}', 'message', $this->text()->notNull()); $this->alterColumn('{{%v2_comments}}', 'meta_data', $this->string(300)->null()->defaultValue('')); diff --git a/tests/specs/blog_v2/migrations_mysql_db/m200000_000005_change_table_v2_comments.php b/tests/specs/blog_v2/migrations_mysql_db/m200000_000005_change_table_v2_comments.php index 5861542c..130014e7 100644 --- a/tests/specs/blog_v2/migrations_mysql_db/m200000_000005_change_table_v2_comments.php +++ b/tests/specs/blog_v2/migrations_mysql_db/m200000_000005_change_table_v2_comments.php @@ -9,7 +9,7 @@ public function up() { $this->dropForeignKey('fk_v2_comments_post_id_v2_posts_uid', '{{%v2_comments}}'); $this->dropForeignKey('fk_v2_comments_author_id_v2_users_id', '{{%v2_comments}}'); - $this->addColumn('{{%v2_comments}}', 'user_id', $this->bigInteger()->null()->defaultValue(null)->after('post_id')); + $this->addColumn('{{%v2_comments}}', 'user_id', $this->bigInteger()->null()->defaultValue(null)->after('post_id')->comment('The User')); $this->dropColumn('{{%v2_comments}}', 'author_id'); $this->alterColumn('{{%v2_comments}}', 'message', $this->text()->notNull()); $this->alterColumn('{{%v2_comments}}', 'meta_data', $this->string(300)->null()->defaultValue('')); diff --git a/tests/specs/blog_v2/migrations_pgsql_db/m200000_000005_change_table_v2_comments.php b/tests/specs/blog_v2/migrations_pgsql_db/m200000_000005_change_table_v2_comments.php index 99a896c6..452a4401 100644 --- a/tests/specs/blog_v2/migrations_pgsql_db/m200000_000005_change_table_v2_comments.php +++ b/tests/specs/blog_v2/migrations_pgsql_db/m200000_000005_change_table_v2_comments.php @@ -9,7 +9,7 @@ public function safeUp() { $this->dropForeignKey('fk_v2_comments_author_id_v2_users_id', '{{%v2_comments}}'); $this->dropForeignKey('fk_v2_comments_post_id_v2_posts_uid', '{{%v2_comments}}'); - $this->addColumn('{{%v2_comments}}', 'user_id', $this->bigInteger()->null()->defaultValue(null)); + $this->addColumn('{{%v2_comments}}', 'user_id', $this->bigInteger()->null()->defaultValue(null)->comment('The User')); $this->dropColumn('{{%v2_comments}}', 'author_id'); $this->alterColumn('{{%v2_comments}}', 'message', 'text NOT NULL USING "message"::text'); $this->alterColumn('{{%v2_comments}}', 'message', "DROP DEFAULT"); diff --git a/tests/specs/fk_col_name/app/migrations_mysql_db/m200000_000002_create_table_webhooks.php b/tests/specs/fk_col_name/app/migrations_mysql_db/m200000_000002_create_table_webhooks.php index bb6aa050..5d3abaf3 100644 --- a/tests/specs/fk_col_name/app/migrations_mysql_db/m200000_000002_create_table_webhooks.php +++ b/tests/specs/fk_col_name/app/migrations_mysql_db/m200000_000002_create_table_webhooks.php @@ -10,7 +10,7 @@ public function up() $this->createTable('{{%webhooks}}', [ 'id' => $this->primaryKey(), 'name' => $this->text()->null(), - 'user_id' => $this->integer()->null()->defaultValue(null), + 'user_id' => $this->integer()->null()->defaultValue(null)->comment('Test model for model code generation that should not contain id column in rules'), 'redelivery_of' => $this->integer()->null()->defaultValue(null), ]); $this->addForeignKey('fk_webhooks_user_id_users_id', '{{%webhooks}}', 'user_id', '{{%users}}', 'id'); diff --git a/tests/specs/fk_col_name_index/app/migrations_mysql_db/m200000_000002_create_table_webhooks.php b/tests/specs/fk_col_name_index/app/migrations_mysql_db/m200000_000002_create_table_webhooks.php index 783d58b0..591905a0 100644 --- a/tests/specs/fk_col_name_index/app/migrations_mysql_db/m200000_000002_create_table_webhooks.php +++ b/tests/specs/fk_col_name_index/app/migrations_mysql_db/m200000_000002_create_table_webhooks.php @@ -10,7 +10,7 @@ public function up() $this->createTable('{{%webhooks}}', [ 'id' => $this->primaryKey(), 'name' => $this->string(255)->null()->defaultValue(null), - 'user_id' => $this->integer()->null()->defaultValue(null), + 'user_id' => $this->integer()->null()->defaultValue(null)->comment('Test model for model code generation that should not contain id column in rules'), 'redelivery_of' => $this->integer()->null()->defaultValue(null), 'rd_abc_2' => $this->integer()->null()->defaultValue(null), ]); diff --git a/tests/specs/issue_fix/175_bug_allof_with_multiple_dollarrefs/pgsql/migrations_pgsql_db/m200000_000000_create_table_accounts.php b/tests/specs/issue_fix/175_bug_allof_with_multiple_dollarrefs/pgsql/migrations_pgsql_db/m200000_000000_create_table_accounts.php index 1606f2fc..ce7db4f9 100644 --- a/tests/specs/issue_fix/175_bug_allof_with_multiple_dollarrefs/pgsql/migrations_pgsql_db/m200000_000000_create_table_accounts.php +++ b/tests/specs/issue_fix/175_bug_allof_with_multiple_dollarrefs/pgsql/migrations_pgsql_db/m200000_000000_create_table_accounts.php @@ -9,7 +9,7 @@ public function up() { $this->createTable('{{%accounts}}', [ 'id' => $this->primaryKey(), - 'name' => $this->string(128)->notNull(), + 'name' => $this->string(128)->notNull()->comment('account name'), 'paymentMethodName' => $this->text()->null(), ]); } diff --git a/tests/specs/issue_fix/175_bug_allof_with_multiple_dollarrefs/pgsql/migrations_pgsql_db/m200000_000001_create_table_contacts.php b/tests/specs/issue_fix/175_bug_allof_with_multiple_dollarrefs/pgsql/migrations_pgsql_db/m200000_000001_create_table_contacts.php index 5fcda9dc..a706a626 100644 --- a/tests/specs/issue_fix/175_bug_allof_with_multiple_dollarrefs/pgsql/migrations_pgsql_db/m200000_000001_create_table_contacts.php +++ b/tests/specs/issue_fix/175_bug_allof_with_multiple_dollarrefs/pgsql/migrations_pgsql_db/m200000_000001_create_table_contacts.php @@ -9,7 +9,7 @@ public function up() { $this->createTable('{{%contacts}}', [ 'id' => $this->primaryKey(), - 'account_id' => $this->integer()->notNull(), + 'account_id' => $this->integer()->notNull()->comment('Account'), 'active' => $this->boolean()->null()->defaultValue(false), 'nickname' => $this->text()->null(), ]); diff --git a/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000001_create_table_b123s.php b/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000001_create_table_b123s.php index 908bd998..7fe423f5 100644 --- a/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000001_create_table_b123s.php +++ b/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000001_create_table_b123s.php @@ -10,7 +10,7 @@ public function safeUp() $this->createTable('{{%b123s}}', [ 'id' => $this->primaryKey(), 'name' => $this->text()->null()->defaultValue(null), - 'c123_id' => $this->integer()->null()->defaultValue(null), + 'c123_id' => $this->integer()->null()->defaultValue(null)->comment('desc'), ]); $this->addForeignKey('fk_b123s_c123_id_c123s_id', '{{%b123s}}', 'c123_id', '{{%c123s}}', 'id'); } diff --git a/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000002_create_table_a123s.php b/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000002_create_table_a123s.php index 73c70ae2..4b2aad61 100644 --- a/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000002_create_table_a123s.php +++ b/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000002_create_table_a123s.php @@ -10,7 +10,7 @@ public function safeUp() $this->createTable('{{%a123s}}', [ 'id' => $this->primaryKey(), 'name' => $this->text()->null()->defaultValue(null), - 'b123_id' => $this->integer()->null()->defaultValue(null), + 'b123_id' => $this->integer()->null()->defaultValue(null)->comment('desc'), ]); $this->addForeignKey('fk_a123s_b123_id_b123s_id', '{{%a123s}}', 'b123_id', '{{%b123s}}', 'id'); } diff --git a/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000003_create_table_accounts.php b/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000003_create_table_accounts.php index 8eba95b2..843678d6 100644 --- a/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000003_create_table_accounts.php +++ b/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000003_create_table_accounts.php @@ -9,7 +9,7 @@ public function safeUp() { $this->createTable('{{%accounts}}', [ 'id' => $this->primaryKey(), - 'name' => $this->string(40)->notNull(), + 'name' => $this->string(40)->notNull()->comment('account name'), ]); } diff --git a/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000005_create_table_domains.php b/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000005_create_table_domains.php index c830fe7e..871b473f 100644 --- a/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000005_create_table_domains.php +++ b/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000005_create_table_domains.php @@ -9,8 +9,8 @@ public function safeUp() { $this->createTable('{{%domains}}', [ 'id' => $this->primaryKey(), - 'name' => $this->string(128)->notNull(), - 'account_id' => $this->integer()->notNull(), + 'name' => $this->string(128)->notNull()->comment('domain or sub-domain name, in DNS syntax, IDN are converted'), + 'account_id' => $this->integer()->notNull()->comment('user account'), 0 => '"created_at" timestamp NOT NULL', ]); $this->addForeignKey('fk_domains_account_id_accounts_id', '{{%domains}}', 'account_id', '{{%accounts}}', 'id'); diff --git a/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000006_create_table_e123s.php b/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000006_create_table_e123s.php index f8d58a41..59d643a4 100644 --- a/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000006_create_table_e123s.php +++ b/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000006_create_table_e123s.php @@ -10,7 +10,7 @@ public function safeUp() $this->createTable('{{%e123s}}', [ 'id' => $this->primaryKey(), 'name' => $this->text()->null()->defaultValue(null), - 'b123_id' => $this->integer()->null()->defaultValue(null), + 'b123_id' => $this->integer()->null()->defaultValue(null)->comment('desc'), ]); $this->addForeignKey('fk_e123s_b123_id_b123s_id', '{{%e123s}}', 'b123_id', '{{%b123s}}', 'id'); } diff --git a/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000007_create_table_routings.php b/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000007_create_table_routings.php index 98ac2ad9..f880d830 100644 --- a/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000007_create_table_routings.php +++ b/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000007_create_table_routings.php @@ -9,14 +9,14 @@ public function safeUp() { $this->createTable('{{%routings}}', [ 'id' => $this->primaryKey(), - 'domain_id' => $this->integer()->notNull(), + 'domain_id' => $this->integer()->notNull()->comment('domain'), 'path' => $this->string(255)->null()->defaultValue(null), 'ssl' => $this->boolean()->null()->defaultValue(null), 'redirect_to_ssl' => $this->boolean()->null()->defaultValue(null), 'service' => $this->string(255)->null()->defaultValue(null), 0 => '"created_at" timestamp NULL DEFAULT NULL', - 'd123_id' => $this->integer()->null()->defaultValue(null), - 'a123_id' => $this->integer()->null()->defaultValue(null), + 'd123_id' => $this->integer()->null()->defaultValue(null)->comment('desc'), + 'a123_id' => $this->integer()->null()->defaultValue(null)->comment('desc'), ]); $this->addForeignKey('fk_routings_domain_id_domains_id', '{{%routings}}', 'domain_id', '{{%domains}}', 'id'); $this->addForeignKey('fk_routings_d123_id_d123s_id', '{{%routings}}', 'd123_id', '{{%d123s}}', 'id'); diff --git a/tests/specs/x_db_type/edit_column/maria/app/migrations_maria_db/m200000_000003_create_table_pristines.php b/tests/specs/x_db_type/edit_column/maria/app/migrations_maria_db/m200000_000003_create_table_pristines.php index 1e27d8d6..7c0b936f 100644 --- a/tests/specs/x_db_type/edit_column/maria/app/migrations_maria_db/m200000_000003_create_table_pristines.php +++ b/tests/specs/x_db_type/edit_column/maria/app/migrations_maria_db/m200000_000003_create_table_pristines.php @@ -19,7 +19,7 @@ public function up() 7 => 'col_9 varchar(9) NULL DEFAULT NULL', 8 => 'col_10 varchar(10) NULL DEFAULT NULL', 9 => 'col_11 text NULL DEFAULT NULL', - 10 => 'price decimal(10,2) NULL DEFAULT 0', + 10 => 'price decimal(10,2) NULL DEFAULT 0 COMMENT \'price in EUR\'', ]); } diff --git a/tests/specs/x_db_type/edit_column/mysql/app/migrations_mysql_db/m200000_000003_create_table_pristines.php b/tests/specs/x_db_type/edit_column/mysql/app/migrations_mysql_db/m200000_000003_create_table_pristines.php index 3e9e8e02..50881e9d 100644 --- a/tests/specs/x_db_type/edit_column/mysql/app/migrations_mysql_db/m200000_000003_create_table_pristines.php +++ b/tests/specs/x_db_type/edit_column/mysql/app/migrations_mysql_db/m200000_000003_create_table_pristines.php @@ -19,7 +19,7 @@ public function up() 7 => 'col_9 varchar(9) NULL DEFAULT NULL', 8 => 'col_10 varchar(10) NULL DEFAULT NULL', 9 => 'col_11 text NULL', - 10 => 'price decimal(10,2) NULL DEFAULT 0', + 10 => 'price decimal(10,2) NULL DEFAULT 0 COMMENT \'price in EUR\'', ]); } diff --git a/tests/specs/x_db_type/fresh/maria/app/migrations_maria_db/m200000_000003_create_table_pristines.php b/tests/specs/x_db_type/fresh/maria/app/migrations_maria_db/m200000_000003_create_table_pristines.php index 1e27d8d6..7c0b936f 100644 --- a/tests/specs/x_db_type/fresh/maria/app/migrations_maria_db/m200000_000003_create_table_pristines.php +++ b/tests/specs/x_db_type/fresh/maria/app/migrations_maria_db/m200000_000003_create_table_pristines.php @@ -19,7 +19,7 @@ public function up() 7 => 'col_9 varchar(9) NULL DEFAULT NULL', 8 => 'col_10 varchar(10) NULL DEFAULT NULL', 9 => 'col_11 text NULL DEFAULT NULL', - 10 => 'price decimal(10,2) NULL DEFAULT 0', + 10 => 'price decimal(10,2) NULL DEFAULT 0 COMMENT \'price in EUR\'', ]); } diff --git a/tests/specs/x_db_type/fresh/mysql/app/migrations_mysql_db/m200000_000003_create_table_pristines.php b/tests/specs/x_db_type/fresh/mysql/app/migrations_mysql_db/m200000_000003_create_table_pristines.php index 3e9e8e02..50881e9d 100644 --- a/tests/specs/x_db_type/fresh/mysql/app/migrations_mysql_db/m200000_000003_create_table_pristines.php +++ b/tests/specs/x_db_type/fresh/mysql/app/migrations_mysql_db/m200000_000003_create_table_pristines.php @@ -19,7 +19,7 @@ public function up() 7 => 'col_9 varchar(9) NULL DEFAULT NULL', 8 => 'col_10 varchar(10) NULL DEFAULT NULL', 9 => 'col_11 text NULL', - 10 => 'price decimal(10,2) NULL DEFAULT 0', + 10 => 'price decimal(10,2) NULL DEFAULT 0 COMMENT \'price in EUR\'', ]); } diff --git a/tests/specs/x_db_type/new_column/maria/app/migrations_maria_db/m200000_000003_create_table_pristines.php b/tests/specs/x_db_type/new_column/maria/app/migrations_maria_db/m200000_000003_create_table_pristines.php index 1e27d8d6..7c0b936f 100644 --- a/tests/specs/x_db_type/new_column/maria/app/migrations_maria_db/m200000_000003_create_table_pristines.php +++ b/tests/specs/x_db_type/new_column/maria/app/migrations_maria_db/m200000_000003_create_table_pristines.php @@ -19,7 +19,7 @@ public function up() 7 => 'col_9 varchar(9) NULL DEFAULT NULL', 8 => 'col_10 varchar(10) NULL DEFAULT NULL', 9 => 'col_11 text NULL DEFAULT NULL', - 10 => 'price decimal(10,2) NULL DEFAULT 0', + 10 => 'price decimal(10,2) NULL DEFAULT 0 COMMENT \'price in EUR\'', ]); } diff --git a/tests/specs/x_db_type/new_column/mysql/app/migrations_mysql_db/m200000_000003_create_table_pristines.php b/tests/specs/x_db_type/new_column/mysql/app/migrations_mysql_db/m200000_000003_create_table_pristines.php index 3e9e8e02..50881e9d 100644 --- a/tests/specs/x_db_type/new_column/mysql/app/migrations_mysql_db/m200000_000003_create_table_pristines.php +++ b/tests/specs/x_db_type/new_column/mysql/app/migrations_mysql_db/m200000_000003_create_table_pristines.php @@ -19,7 +19,7 @@ public function up() 7 => 'col_9 varchar(9) NULL DEFAULT NULL', 8 => 'col_10 varchar(10) NULL DEFAULT NULL', 9 => 'col_11 text NULL', - 10 => 'price decimal(10,2) NULL DEFAULT 0', + 10 => 'price decimal(10,2) NULL DEFAULT 0 COMMENT \'price in EUR\'', ]); } diff --git a/tests/specs/x_on_x_fk_constraint/app/migrations_pgsql_db/m200000_000001_create_table_postxes.php b/tests/specs/x_on_x_fk_constraint/app/migrations_pgsql_db/m200000_000001_create_table_postxes.php index f0e8adc8..777920de 100644 --- a/tests/specs/x_on_x_fk_constraint/app/migrations_pgsql_db/m200000_000001_create_table_postxes.php +++ b/tests/specs/x_on_x_fk_constraint/app/migrations_pgsql_db/m200000_000001_create_table_postxes.php @@ -10,10 +10,10 @@ public function safeUp() $this->createTable('{{%postxes}}', [ 'id' => $this->primaryKey(), 'title' => $this->text()->null()->defaultValue(null), - 'user_id' => $this->integer()->null()->defaultValue(null), - 'user_2_id' => $this->integer()->null()->defaultValue(null), - 'user_3_id' => $this->integer()->null()->defaultValue(null), - 'user_4_id' => $this->integer()->null()->defaultValue(null), + 'user_id' => $this->integer()->null()->defaultValue(null)->comment('x on-x (update|delete) foreign key constraint'), + 'user_2_id' => $this->integer()->null()->defaultValue(null)->comment('x on-x (update|delete) foreign key constraint'), + 'user_3_id' => $this->integer()->null()->defaultValue(null)->comment('x on-x (update|delete) foreign key constraint'), + 'user_4_id' => $this->integer()->null()->defaultValue(null)->comment('x on-x (update|delete) foreign key constraint'), ]); $this->addForeignKey('fk_postxes_user_id_userxes_id', '{{%postxes}}', 'user_id', '{{%userxes}}', 'id', null, 'CASCADE'); $this->addForeignKey('fk_postxes_user_2_id_userxes_id', '{{%postxes}}', 'user_2_id', '{{%userxes}}', 'id', 'SET NULL', 'CASCADE'); From d4dd0740704c56f95043f43e49e36c39f66e8502 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Sat, 28 Sep 2024 20:48:15 +0530 Subject: [PATCH 231/358] Add comments handling for PgSQL as it is different from MySQL - WIP --- src/lib/migrations/BaseMigrationBuilder.php | 3 +++ src/lib/migrations/MigrationRecordBuilder.php | 7 +++++++ .../migrations/PostgresMigrationBuilder.php | 14 +++++++++++--- .../index.yml | 13 +++++++++++-- tests/unit/IssueFixTest.php | 18 +++++++++++++++++- 5 files changed, 49 insertions(+), 6 deletions(-) diff --git a/src/lib/migrations/BaseMigrationBuilder.php b/src/lib/migrations/BaseMigrationBuilder.php index d4c49c21..8c9464f7 100644 --- a/src/lib/migrations/BaseMigrationBuilder.php +++ b/src/lib/migrations/BaseMigrationBuilder.php @@ -453,6 +453,9 @@ public function tmpSaveNewCol(string $tableAlias, \cebe\yii2openapi\db\ColumnSch } Yii::$app->db->createCommand()->createTable($tmpTableName, $column)->execute(); + if (ApiGenerator::isPostgres()) { + Yii::$app->db->createCommand("comment on column $tmpTableName.$columnSchema->name is '$columnSchema->comment'")->execute(); + } $table = Yii::$app->db->getTableSchema($tmpTableName); diff --git a/src/lib/migrations/MigrationRecordBuilder.php b/src/lib/migrations/MigrationRecordBuilder.php index 98ee03b8..f70808b5 100644 --- a/src/lib/migrations/MigrationRecordBuilder.php +++ b/src/lib/migrations/MigrationRecordBuilder.php @@ -46,6 +46,8 @@ final class MigrationRecordBuilder public const ALTER_COLUMN_RAW_PGSQL = MigrationRecordBuilder::INDENT . "\$this->db->createCommand('ALTER TABLE %s ALTER COLUMN \"%s\" SET DATA TYPE %s')->execute();"; + public const PGSQL_COMMENT_ON_COLUMN = MigrationRecordBuilder::INDENT . "\$this->addCommentOnColumn('%s', '%s', '%s');"; + /** * @var \yii\db\Schema */ @@ -345,4 +347,9 @@ public static function makeString(array $codeColumns): string $codeColumns = '['.PHP_EOL.self::INDENT.' '.$codeColumns.PHP_EOL . self::INDENT.']'; return $codeColumns; } + + public function pgsqlCommentOnColumn($table, string $column, string $comment) + { + return sprintf(self::PGSQL_COMMENT_ON_COLUMN, $table, $column, $comment); + } } diff --git a/src/lib/migrations/PostgresMigrationBuilder.php b/src/lib/migrations/PostgresMigrationBuilder.php index b8c9324d..9b3cb225 100644 --- a/src/lib/migrations/PostgresMigrationBuilder.php +++ b/src/lib/migrations/PostgresMigrationBuilder.php @@ -9,7 +9,6 @@ use cebe\yii2openapi\lib\items\DbIndex; use yii\db\ColumnSchema; -use yii\helpers\VarDumper; use yii\helpers\ArrayHelper; final class PostgresMigrationBuilder extends BaseMigrationBuilder @@ -65,7 +64,7 @@ protected function buildColumnChanges(ColumnSchema $current, ColumnSchema $desir if (!empty(array_intersect(['type', 'size' , 'dbType', 'phpType' - , 'precision', 'scale', 'unsigned' + , 'precision', 'scale', 'unsigned', 'comment' ], $changed))) { $addUsing = $this->isNeedUsingExpression($current->dbType, $desired->dbType); $this->migration->addUpCode($this->recordBuilder->alterColumnType($tableName, $desired, $addUsing)); @@ -91,6 +90,15 @@ protected function buildColumnChanges(ColumnSchema $current, ColumnSchema $desir $this->migration->addUpCode($upCode)->addDownCode($downCode, true); } } + + if (in_array('comment', $changed, true)) { +// if ($desired->comment) { + $this->migration->addUpCode($this->recordBuilder->pgsqlCommentOnColumn($tableName, $desired->name, $desired->comment)); +// } else { +// +// } + } + if ($isChangeToEnum) { $this->migration->addUpCode($this->recordBuilder->createEnum($tableName, $desired->name, $desired->enumValues), true); } @@ -127,7 +135,7 @@ protected function compareColumns(ColumnSchema $current, ColumnSchema $desired): foreach (['type', 'size', 'allowNull', 'defaultValue', 'enumValues' , 'dbType', 'phpType' - , 'precision', 'scale', 'unsigned' + , 'precision', 'scale', 'unsigned', 'comment' ] as $attr) { if ($attr === 'defaultValue') { if ($this->isDefaultValueChanged($current, $desiredFromDb)) { diff --git a/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/index.yml b/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/index.yml index 83f3a948..a6178648 100644 --- a/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/index.yml +++ b/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/index.yml @@ -14,8 +14,10 @@ components: name: type: string description: desc - # colour: - # type: string + colour: + type: string + # maxLength: 255 + # x-db-type: varbinary # TODO description: type: string x-db-type: varchar @@ -28,6 +30,13 @@ components: name: type: integer description: desc + # description: + # type: string + # x-db-type: varchar + # description: desc 2 + g: + type: string + description: desc 3 paths: '/': diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index 45ace04d..1022ab76 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -377,13 +377,29 @@ public function test60DescriptionOfAPropertyInSpecMustCorrespondToDbTableColumnC // $this->checkFiles($actualFiles, $expectedFiles); $this->deleteTableFor60DescriptionOfAPropertyInSpecMustCorrespondToDbTableColumnComment(); + + + $this->changeDbToPgsql(); + $this->deleteTableFor60DescriptionOfAPropertyInSpecMustCorrespondToDbTableColumnComment(); + $this->createTableFor60DescriptionOfAPropertyInSpecMustCorrespondToDbTableColumnComment(); + $this->runGenerator($testFile, 'pgsql'); + // $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ + // 'recursive' => true, + // ]); + // $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/mysql"), [ + // 'recursive' => true, + // ]); + // $this->checkFiles($actualFiles, $expectedFiles); + + $this->deleteTableFor60DescriptionOfAPropertyInSpecMustCorrespondToDbTableColumnComment(); } private function createTableFor60DescriptionOfAPropertyInSpecMustCorrespondToDbTableColumnComment() { Yii::$app->db->createCommand()->createTable('{{%animals}}', [ 'id' => 'pk', - 'name' => 'text comment "the name"', + 'name' => 'text ', # comment "the name" + 'g' => 'text' ])->execute(); } From b18c521a6fb0ee7564c1317ac6dd9b16bf938c3f Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Sun, 29 Sep 2024 12:44:38 +0530 Subject: [PATCH 232/358] Add comments handling for PgSQL as it is different from MySQL - 2 --- src/lib/migrations/BaseMigrationBuilder.php | 4 ++++ src/lib/migrations/MysqlMigrationBuilder.php | 6 ++++++ .../migrations/PostgresMigrationBuilder.php | 12 +++++++++++ .../index.yml | 8 ++++---- tests/unit/IssueFixTest.php | 20 +++++++++---------- 5 files changed, 36 insertions(+), 14 deletions(-) diff --git a/src/lib/migrations/BaseMigrationBuilder.php b/src/lib/migrations/BaseMigrationBuilder.php index 8c9464f7..a413d3a7 100644 --- a/src/lib/migrations/BaseMigrationBuilder.php +++ b/src/lib/migrations/BaseMigrationBuilder.php @@ -161,6 +161,8 @@ public function buildFresh():MigrationModel } } + $this->addCommentsMigration(); + return $this->migration; } @@ -275,6 +277,8 @@ abstract public static function getColumnSchemaBuilderClass(): string; */ abstract protected function findTableIndexes():array; + abstract public function addCommentsMigration(); + protected function buildIndexChanges():void { $haveIndexes = $this->findTableIndexes(); diff --git a/src/lib/migrations/MysqlMigrationBuilder.php b/src/lib/migrations/MysqlMigrationBuilder.php index 42354df3..b65d8719 100644 --- a/src/lib/migrations/MysqlMigrationBuilder.php +++ b/src/lib/migrations/MysqlMigrationBuilder.php @@ -159,4 +159,10 @@ public function modifyDesiredInContextOfCurrent(ColumnSchema $current, ColumnSch $desired->size = $current->size; } } + + public function addCommentsMigration() + { + // nothing to do here as comments can be defined in same statement as of alter/add column in MySQL + // this method is only for PgSQL + } } diff --git a/src/lib/migrations/PostgresMigrationBuilder.php b/src/lib/migrations/PostgresMigrationBuilder.php index 9b3cb225..ef81ad39 100644 --- a/src/lib/migrations/PostgresMigrationBuilder.php +++ b/src/lib/migrations/PostgresMigrationBuilder.php @@ -256,4 +256,16 @@ public function modifyDesiredInContextOfCurrent(ColumnSchema $current, ColumnSch $desired->size = $current->size; } } + + public function addCommentsMigration() + { + $tableAlias = $this->model->getTableAlias(); + foreach ($this->newColumns as $column) { + if($column->comment) { + $this->migration + ->addUpCode($this->recordBuilder->pgsqlCommentOnColumn($tableAlias, $column->name, $column->comment)) + ; + } + } + } } diff --git a/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/index.yml b/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/index.yml index a6178648..cf6728f9 100644 --- a/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/index.yml +++ b/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/index.yml @@ -14,13 +14,13 @@ components: name: type: string description: desc - colour: - type: string +# colour: +# type: string # maxLength: 255 # x-db-type: varbinary # TODO description: - type: string - x-db-type: varchar + type: number + x-db-type: double precision description: desc 2 Animal: type: object diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index 1022ab76..01d751a9 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -364,8 +364,9 @@ public function test158BugGiiapiGeneratedRulesEnumWithTrim() // https://github.com/php-openapi/yii2-openapi/issues/60 public function test60DescriptionOfAPropertyInSpecMustCorrespondToDbTableColumnComment() { - $this->deleteTableFor60DescriptionOfAPropertyInSpecMustCorrespondToDbTableColumnComment(); - $this->createTableFor60DescriptionOfAPropertyInSpecMustCorrespondToDbTableColumnComment(); + // MySQL + $this->deleteTableFor60DescriptionOfAProperty(); + $this->createTableFor60DescriptionOfAProperty(); $testFile = Yii::getAlias("@specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/index.php"); $this->runGenerator($testFile); // $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ @@ -375,13 +376,13 @@ public function test60DescriptionOfAPropertyInSpecMustCorrespondToDbTableColumnC // 'recursive' => true, // ]); // $this->checkFiles($actualFiles, $expectedFiles); - - $this->deleteTableFor60DescriptionOfAPropertyInSpecMustCorrespondToDbTableColumnComment(); + $this->deleteTableFor60DescriptionOfAProperty(); + // PgSQL $this->changeDbToPgsql(); - $this->deleteTableFor60DescriptionOfAPropertyInSpecMustCorrespondToDbTableColumnComment(); - $this->createTableFor60DescriptionOfAPropertyInSpecMustCorrespondToDbTableColumnComment(); + $this->deleteTableFor60DescriptionOfAProperty(); + $this->createTableFor60DescriptionOfAProperty(); $this->runGenerator($testFile, 'pgsql'); // $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ // 'recursive' => true, @@ -390,11 +391,10 @@ public function test60DescriptionOfAPropertyInSpecMustCorrespondToDbTableColumnC // 'recursive' => true, // ]); // $this->checkFiles($actualFiles, $expectedFiles); - - $this->deleteTableFor60DescriptionOfAPropertyInSpecMustCorrespondToDbTableColumnComment(); + $this->deleteTableFor60DescriptionOfAProperty(); } - private function createTableFor60DescriptionOfAPropertyInSpecMustCorrespondToDbTableColumnComment() + private function createTableFor60DescriptionOfAProperty() { Yii::$app->db->createCommand()->createTable('{{%animals}}', [ 'id' => 'pk', @@ -403,7 +403,7 @@ private function createTableFor60DescriptionOfAPropertyInSpecMustCorrespondToDbT ])->execute(); } - private function deleteTableFor60DescriptionOfAPropertyInSpecMustCorrespondToDbTableColumnComment() + private function deleteTableFor60DescriptionOfAProperty() { Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%animals}}')->execute(); } From 72a7a6ae565a0b78a16d36a4b3e87be81529d279 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Sun, 29 Sep 2024 19:49:32 +0530 Subject: [PATCH 233/358] Add comments handling for PgSQL as it is different from MySQL - done --- src/lib/migrations/BaseMigrationBuilder.php | 8 +++--- src/lib/migrations/MigrationRecordBuilder.php | 13 +++++++--- src/lib/migrations/MysqlMigrationBuilder.php | 6 ++--- .../migrations/PostgresMigrationBuilder.php | 25 +++++++++++-------- .../index.yml | 13 ++++++++-- tests/unit/IssueFixTest.php | 14 +++++++++-- 6 files changed, 54 insertions(+), 25 deletions(-) diff --git a/src/lib/migrations/BaseMigrationBuilder.php b/src/lib/migrations/BaseMigrationBuilder.php index a413d3a7..ad37a942 100644 --- a/src/lib/migrations/BaseMigrationBuilder.php +++ b/src/lib/migrations/BaseMigrationBuilder.php @@ -161,7 +161,7 @@ public function buildFresh():MigrationModel } } - $this->addCommentsMigration(); + $this->handleCommentsMigration(); return $this->migration; } @@ -277,7 +277,7 @@ abstract public static function getColumnSchemaBuilderClass(): string; */ abstract protected function findTableIndexes():array; - abstract public function addCommentsMigration(); + abstract public function handleCommentsMigration(); protected function buildIndexChanges():void { @@ -457,8 +457,8 @@ public function tmpSaveNewCol(string $tableAlias, \cebe\yii2openapi\db\ColumnSch } Yii::$app->db->createCommand()->createTable($tmpTableName, $column)->execute(); - if (ApiGenerator::isPostgres()) { - Yii::$app->db->createCommand("comment on column $tmpTableName.$columnSchema->name is '$columnSchema->comment'")->execute(); + if (ApiGenerator::isPostgres() && $columnSchema->comment) { + Yii::$app->db->createCommand("COMMENT ON COLUMN $tmpTableName.$columnSchema->name IS '$columnSchema->comment'")->execute(); } $table = Yii::$app->db->getTableSchema($tmpTableName); diff --git a/src/lib/migrations/MigrationRecordBuilder.php b/src/lib/migrations/MigrationRecordBuilder.php index f70808b5..cbe0af72 100644 --- a/src/lib/migrations/MigrationRecordBuilder.php +++ b/src/lib/migrations/MigrationRecordBuilder.php @@ -46,7 +46,9 @@ final class MigrationRecordBuilder public const ALTER_COLUMN_RAW_PGSQL = MigrationRecordBuilder::INDENT . "\$this->db->createCommand('ALTER TABLE %s ALTER COLUMN \"%s\" SET DATA TYPE %s')->execute();"; - public const PGSQL_COMMENT_ON_COLUMN = MigrationRecordBuilder::INDENT . "\$this->addCommentOnColumn('%s', '%s', '%s');"; + public const ADD_COMMENT_ON_COLUMN = MigrationRecordBuilder::INDENT . "\$this->addCommentOnColumn('%s', '%s', '%s');"; + + public const DROP_COMMENT_ON_COLUMN = MigrationRecordBuilder::INDENT . "\$this->dropCommentFromColumn('%s', '%s');"; /** * @var \yii\db\Schema @@ -348,8 +350,13 @@ public static function makeString(array $codeColumns): string return $codeColumns; } - public function pgsqlCommentOnColumn($table, string $column, string $comment) + public function addCommentOnColumn($table, string $column, string $comment) + { + return sprintf(self::ADD_COMMENT_ON_COLUMN, $table, $column, $comment); + } + + public function dropCommentOnColumn($table, string $column) { - return sprintf(self::PGSQL_COMMENT_ON_COLUMN, $table, $column, $comment); + return sprintf(self::DROP_COMMENT_ON_COLUMN, $table, $column); } } diff --git a/src/lib/migrations/MysqlMigrationBuilder.php b/src/lib/migrations/MysqlMigrationBuilder.php index b65d8719..881068b5 100644 --- a/src/lib/migrations/MysqlMigrationBuilder.php +++ b/src/lib/migrations/MysqlMigrationBuilder.php @@ -14,9 +14,7 @@ use yii\db\ColumnSchema; use yii\db\IndexConstraint; use yii\db\Schema; -use \Yii; use yii\helpers\ArrayHelper; -use yii\helpers\VarDumper; final class MysqlMigrationBuilder extends BaseMigrationBuilder { @@ -56,7 +54,7 @@ protected function compareColumns(ColumnSchema $current, ColumnSchema $desired): foreach (['type', 'size', 'allowNull', 'defaultValue', 'enumValues' , 'dbType', 'phpType' - , 'precision', 'scale', 'unsigned' + , 'precision', 'scale', 'unsigned', 'comment' ] as $attr) { if ($attr === 'defaultValue') { if ($this->isDefaultValueChanged($current, $desiredFromDb)) { @@ -160,7 +158,7 @@ public function modifyDesiredInContextOfCurrent(ColumnSchema $current, ColumnSch } } - public function addCommentsMigration() + public function handleCommentsMigration() { // nothing to do here as comments can be defined in same statement as of alter/add column in MySQL // this method is only for PgSQL diff --git a/src/lib/migrations/PostgresMigrationBuilder.php b/src/lib/migrations/PostgresMigrationBuilder.php index ef81ad39..b072d8b1 100644 --- a/src/lib/migrations/PostgresMigrationBuilder.php +++ b/src/lib/migrations/PostgresMigrationBuilder.php @@ -64,7 +64,7 @@ protected function buildColumnChanges(ColumnSchema $current, ColumnSchema $desir if (!empty(array_intersect(['type', 'size' , 'dbType', 'phpType' - , 'precision', 'scale', 'unsigned', 'comment' + , 'precision', 'scale', 'unsigned' ], $changed))) { $addUsing = $this->isNeedUsingExpression($current->dbType, $desired->dbType); $this->migration->addUpCode($this->recordBuilder->alterColumnType($tableName, $desired, $addUsing)); @@ -91,12 +91,14 @@ protected function buildColumnChanges(ColumnSchema $current, ColumnSchema $desir } } - if (in_array('comment', $changed, true)) { -// if ($desired->comment) { - $this->migration->addUpCode($this->recordBuilder->pgsqlCommentOnColumn($tableName, $desired->name, $desired->comment)); -// } else { -// -// } + if (in_array('comment', $changed, true)) { // TODO + if ($desired->comment) { + $this->migration->addUpCode($this->recordBuilder->addCommentOnColumn($tableName, $desired->name, $desired->comment)); + $this->migration->addDownCode($this->recordBuilder->dropCommentOnColumn($tableName, $desired->name)); + } else { + $this->migration->addUpCode($this->recordBuilder->dropCommentOnColumn($tableName, $desired->name)); + $this->migration->addDownCode($this->recordBuilder->addCommentOnColumn($tableName, $desired->name, $current->comment)); + } } if ($isChangeToEnum) { @@ -257,13 +259,16 @@ public function modifyDesiredInContextOfCurrent(ColumnSchema $current, ColumnSch } } - public function addCommentsMigration() + public function handleCommentsMigration() { $tableAlias = $this->model->getTableAlias(); foreach ($this->newColumns as $column) { - if($column->comment) { + if ($column->comment) { + $this->migration + ->addUpCode($this->recordBuilder->addCommentOnColumn($tableAlias, $column->name, $column->comment)); + } else { $this->migration - ->addUpCode($this->recordBuilder->pgsqlCommentOnColumn($tableAlias, $column->name, $column->comment)) + ->addUpCode($this->recordBuilder->dropCommentOnColumn($tableAlias, $column->name)) ; } } diff --git a/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/index.yml b/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/index.yml index cf6728f9..f4637ada 100644 --- a/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/index.yml +++ b/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/index.yml @@ -29,14 +29,23 @@ components: type: integer name: type: integer - description: desc + # description: desc # description: # type: string # x-db-type: varchar # description: desc 2 g: type: string - description: desc 3 + description: desc for g + g2: + type: string + description: changed comment on g2 col + g3: + type: string + description: the comment on g3 col remains same + g4: + type: integer + description: data type changes but comment remains same paths: '/': diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index 01d751a9..fc5271b4 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -369,6 +369,7 @@ public function test60DescriptionOfAPropertyInSpecMustCorrespondToDbTableColumnC $this->createTableFor60DescriptionOfAProperty(); $testFile = Yii::getAlias("@specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/index.php"); $this->runGenerator($testFile); + $this->runActualMigrations(); // $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ // 'recursive' => true, // ]); @@ -384,6 +385,7 @@ public function test60DescriptionOfAPropertyInSpecMustCorrespondToDbTableColumnC $this->deleteTableFor60DescriptionOfAProperty(); $this->createTableFor60DescriptionOfAProperty(); $this->runGenerator($testFile, 'pgsql'); + $this->runActualMigrations('pgsql'); // $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ // 'recursive' => true, // ]); @@ -391,7 +393,7 @@ public function test60DescriptionOfAPropertyInSpecMustCorrespondToDbTableColumnC // 'recursive' => true, // ]); // $this->checkFiles($actualFiles, $expectedFiles); - $this->deleteTableFor60DescriptionOfAProperty(); +// $this->deleteTableFor60DescriptionOfAProperty(); } private function createTableFor60DescriptionOfAProperty() @@ -399,8 +401,16 @@ private function createTableFor60DescriptionOfAProperty() Yii::$app->db->createCommand()->createTable('{{%animals}}', [ 'id' => 'pk', 'name' => 'text ', # comment "the name" - 'g' => 'text' + 'g' => 'text', + 'g2' => 'text', + 'g3' => 'text', + 'g4' => 'text', ])->execute(); + + Yii::$app->db->createCommand()->addCommentOnColumn('{{%animals}}', 'name', 'the comment on name col')->execute(); + Yii::$app->db->createCommand()->addCommentOnColumn('{{%animals}}', 'g2', 'the comment on g2 col')->execute(); + Yii::$app->db->createCommand()->addCommentOnColumn('{{%animals}}', 'g3', 'the comment on g3 col remains same')->execute(); + Yii::$app->db->createCommand()->addCommentOnColumn('{{%animals}}', 'g4', 'data type changes but comment remains same')->execute(); } private function deleteTableFor60DescriptionOfAProperty() From 7d557c49a65bb89871e2c4e82a8339987c66075e Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Sun, 29 Sep 2024 20:19:43 +0530 Subject: [PATCH 234/358] Complete the test --- src/lib/migrations/BaseMigrationBuilder.php | 4 +- .../index.yml | 3 + .../m200000_000000_change_table_animals.php | 27 ++++ .../m200000_000001_create_table_fruits.php | 21 +++ .../mysql/models/Animal.php | 10 ++ .../mysql/models/AnimalFaker.php | 46 ++++++ .../mysql/models/BaseModelFaker.php | 144 ++++++++++++++++++ .../mysql/models/Fruit.php | 10 ++ .../mysql/models/FruitFaker.php | 42 +++++ .../mysql/models/base/Animal.php | 40 +++++ .../mysql/models/base/Fruit.php | 32 ++++ .../m200000_000000_change_table_animals.php | 29 ++++ .../m200000_000001_create_table_fruits.php | 24 +++ .../pgsql/models/Animal.php | 10 ++ .../pgsql/models/AnimalFaker.php | 46 ++++++ .../pgsql/models/BaseModelFaker.php | 144 ++++++++++++++++++ .../pgsql/models/Fruit.php | 10 ++ .../pgsql/models/FruitFaker.php | 42 +++++ .../pgsql/models/base/Animal.php | 40 +++++ .../pgsql/models/base/Fruit.php | 32 ++++ tests/unit/IssueFixTest.php | 32 ++-- 21 files changed, 771 insertions(+), 17 deletions(-) create mode 100644 tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/mysql/migrations_mysql_db/m200000_000000_change_table_animals.php create mode 100644 tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/mysql/migrations_mysql_db/m200000_000001_create_table_fruits.php create mode 100644 tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/mysql/models/Animal.php create mode 100644 tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/mysql/models/AnimalFaker.php create mode 100644 tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/mysql/models/BaseModelFaker.php create mode 100644 tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/mysql/models/Fruit.php create mode 100644 tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/mysql/models/FruitFaker.php create mode 100644 tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/mysql/models/base/Animal.php create mode 100644 tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/mysql/models/base/Fruit.php create mode 100644 tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/pgsql/migrations_pgsql_db/m200000_000000_change_table_animals.php create mode 100644 tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/pgsql/migrations_pgsql_db/m200000_000001_create_table_fruits.php create mode 100644 tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/pgsql/models/Animal.php create mode 100644 tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/pgsql/models/AnimalFaker.php create mode 100644 tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/pgsql/models/BaseModelFaker.php create mode 100644 tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/pgsql/models/Fruit.php create mode 100644 tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/pgsql/models/FruitFaker.php create mode 100644 tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/pgsql/models/base/Animal.php create mode 100644 tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/pgsql/models/base/Fruit.php diff --git a/src/lib/migrations/BaseMigrationBuilder.php b/src/lib/migrations/BaseMigrationBuilder.php index ad37a942..8a49de34 100644 --- a/src/lib/migrations/BaseMigrationBuilder.php +++ b/src/lib/migrations/BaseMigrationBuilder.php @@ -453,12 +453,12 @@ public function tmpSaveNewCol(string $tableAlias, \cebe\yii2openapi\db\ColumnSch }, $allEnumValues); Yii::$app->db->createCommand( 'CREATE TYPE '.$tmpEnumName($columnSchema->name).' AS ENUM('.implode(', ', $allEnumValues).')' - )->execute(); + )->execute(); // TODO quote value } Yii::$app->db->createCommand()->createTable($tmpTableName, $column)->execute(); if (ApiGenerator::isPostgres() && $columnSchema->comment) { - Yii::$app->db->createCommand("COMMENT ON COLUMN $tmpTableName.$columnSchema->name IS '$columnSchema->comment'")->execute(); + Yii::$app->db->createCommand("COMMENT ON COLUMN $tmpTableName.$columnSchema->name IS '$columnSchema->comment'")->execute(); // TODO quote comment } $table = Yii::$app->db->getTableSchema($tmpTableName); diff --git a/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/index.yml b/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/index.yml index f4637ada..a034947e 100644 --- a/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/index.yml +++ b/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/index.yml @@ -46,6 +46,9 @@ components: g4: type: integer description: data type changes but comment remains same + new_col: + type: string + description: new col added paths: '/': diff --git a/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/mysql/migrations_mysql_db/m200000_000000_change_table_animals.php b/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/mysql/migrations_mysql_db/m200000_000000_change_table_animals.php new file mode 100644 index 00000000..bff6c78d --- /dev/null +++ b/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/mysql/migrations_mysql_db/m200000_000000_change_table_animals.php @@ -0,0 +1,27 @@ +addColumn('{{%animals}}', 'new_col', $this->text()->null()->comment('new col added')); + $this->dropColumn('{{%animals}}', 'drop_col'); + $this->alterColumn('{{%animals}}', 'name', $this->integer()->null()->defaultValue(null)); + $this->alterColumn('{{%animals}}', 'g', $this->text()->null()->comment('desc for g')); + $this->alterColumn('{{%animals}}', 'g2', $this->text()->null()->comment('changed comment on g2 col')); + $this->alterColumn('{{%animals}}', 'g4', $this->integer()->null()->defaultValue(null)->comment('data type changes but comment remains same')); + } + + public function down() + { + $this->alterColumn('{{%animals}}', 'g4', $this->text()->null()->comment('data type changes but comment remains same')); + $this->alterColumn('{{%animals}}', 'g2', $this->text()->null()->comment('the comment on g2 col')); + $this->alterColumn('{{%animals}}', 'g', $this->text()->null()); + $this->alterColumn('{{%animals}}', 'name', $this->text()->null()->comment('the comment on name col')); + $this->addColumn('{{%animals}}', 'drop_col', $this->text()->null()); + $this->dropColumn('{{%animals}}', 'new_col'); + } +} diff --git a/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/mysql/migrations_mysql_db/m200000_000001_create_table_fruits.php b/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/mysql/migrations_mysql_db/m200000_000001_create_table_fruits.php new file mode 100644 index 00000000..4fa328d9 --- /dev/null +++ b/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/mysql/migrations_mysql_db/m200000_000001_create_table_fruits.php @@ -0,0 +1,21 @@ +createTable('{{%fruits}}', [ + 'id' => $this->primaryKey(), + 'name' => $this->text()->null()->comment('desc'), + 0 => 'description double precision NULL DEFAULT NULL COMMENT \'desc 2\'', + ]); + } + + public function down() + { + $this->dropTable('{{%fruits}}'); + } +} diff --git a/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/mysql/models/Animal.php b/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/mysql/models/Animal.php new file mode 100644 index 00000000..92caf2f3 --- /dev/null +++ b/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/mysql/models/Animal.php @@ -0,0 +1,10 @@ +generateModels(['author_id' => 1]); + * $model = (new PostFaker())->generateModels(function($model, $faker, $uniqueFaker) { + * $model->scenario = 'create'; + * $model->author_id = 1; + * return $model; + * }); + **/ + public function generateModel($attributes = []) + { + $faker = $this->faker; + $uniqueFaker = $this->uniqueFaker; + $model = new Animal(); + //$model->id = $uniqueFaker->numberBetween(0, 1000000); + $model->name = $faker->numberBetween(0, 1000000); + $model->g = $faker->sentence; + $model->g2 = $faker->sentence; + $model->g3 = $faker->sentence; + $model->g4 = $faker->numberBetween(0, 1000000); + $model->new_col = $faker->sentence; + if (!is_callable($attributes)) { + $model->setAttributes($attributes, false); + } else { + $model = $attributes($model, $faker, $uniqueFaker); + } + return $model; + } +} diff --git a/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/mysql/models/BaseModelFaker.php b/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/mysql/models/BaseModelFaker.php new file mode 100644 index 00000000..c367fbb4 --- /dev/null +++ b/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/mysql/models/BaseModelFaker.php @@ -0,0 +1,144 @@ +faker = FakerFactory::create(str_replace('-', '_', \Yii::$app->language)); + $this->uniqueFaker = new UniqueGenerator($this->faker); + } + + abstract public function generateModel($attributes = []); + + public function getFaker():Generator + { + return $this->faker; + } + + public function getUniqueFaker():UniqueGenerator + { + return $this->uniqueFaker; + } + + public function setFaker(Generator $faker):void + { + $this->faker = $faker; + } + + public function setUniqueFaker(UniqueGenerator $faker):void + { + $this->uniqueFaker = $faker; + } + + /** + * Generate and return model + * @param array|callable $attributes + * @param UniqueGenerator|null $uniqueFaker + * @return \yii\db\ActiveRecord + * @example MyFaker::makeOne(['user_id' => 1, 'title' => 'foo']); + * @example MyFaker::makeOne( function($model, $faker) { + * $model->scenario = 'create'; + * $model->setAttributes(['user_id' => 1, 'title' => $faker->sentence]); + * return $model; + * }); + */ + public static function makeOne($attributes = [], ?UniqueGenerator $uniqueFaker = null) + { + $fakeBuilder = new static(); + if ($uniqueFaker !== null) { + $fakeBuilder->setUniqueFaker($uniqueFaker); + } + $model = $fakeBuilder->generateModel($attributes); + return $model; + } + + /** + * Generate, save and return model + * @param array|callable $attributes + * @param UniqueGenerator|null $uniqueFaker + * @return \yii\db\ActiveRecord + * @example MyFaker::saveOne(['user_id' => 1, 'title' => 'foo']); + * @example MyFaker::saveOne( function($model, $faker) { + * $model->scenario = 'create'; + * $model->setAttributes(['user_id' => 1, 'title' => $faker->sentence]); + * return $model; + * }); + */ + public static function saveOne($attributes = [], ?UniqueGenerator $uniqueFaker = null) + { + $model = static::makeOne($attributes, $uniqueFaker); + $model->save(); + return $model; + } + + /** + * Generate and return multiple models + * @param int $number + * @param array|callable $commonAttributes + * @return \yii\db\ActiveRecord[]|array + * @example TaskFaker::make(5, ['project_id'=>1, 'user_id' => 2]); + * @example TaskFaker::make(5, function($model, $faker, $uniqueFaker) { + * $model->setAttributes(['name' => $uniqueFaker->username, 'state'=>$faker->boolean(20)]); + * return $model; + * }); + */ + public static function make(int $number, $commonAttributes = [], ?UniqueGenerator $uniqueFaker = null):array + { + if ($number < 1) { + return []; + } + $fakeBuilder = new static(); + if ($uniqueFaker !== null) { + $fakeBuilder->setUniqueFaker($uniqueFaker); + } + return array_map(function () use ($commonAttributes, $fakeBuilder) { + $model = $fakeBuilder->generateModel($commonAttributes); + return $model; + }, range(0, $number -1)); + } + + /** + * Generate, save and return multiple models + * @param int $number + * @param array|callable $commonAttributes + * @return \yii\db\ActiveRecord[]|array + * @example TaskFaker::save(5, ['project_id'=>1, 'user_id' => 2]); + * @example TaskFaker::save(5, function($model, $faker, $uniqueFaker) { + * $model->setAttributes(['name' => $uniqueFaker->username, 'state'=>$faker->boolean(20)]); + * return $model; + * }); + */ + public static function save(int $number, $commonAttributes = [], ?UniqueGenerator $uniqueFaker = null):array + { + if ($number < 1) { + return []; + } + $fakeBuilder = new static(); + if ($uniqueFaker !== null) { + $fakeBuilder->setUniqueFaker($uniqueFaker); + } + return array_map(function () use ($commonAttributes, $fakeBuilder) { + $model = $fakeBuilder->generateModel($commonAttributes); + $model->save(); + return $model; + }, range(0, $number -1)); + } +} diff --git a/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/mysql/models/Fruit.php b/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/mysql/models/Fruit.php new file mode 100644 index 00000000..c74c53d9 --- /dev/null +++ b/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/mysql/models/Fruit.php @@ -0,0 +1,10 @@ +generateModels(['author_id' => 1]); + * $model = (new PostFaker())->generateModels(function($model, $faker, $uniqueFaker) { + * $model->scenario = 'create'; + * $model->author_id = 1; + * return $model; + * }); + **/ + public function generateModel($attributes = []) + { + $faker = $this->faker; + $uniqueFaker = $this->uniqueFaker; + $model = new Fruit(); + //$model->id = $uniqueFaker->numberBetween(0, 1000000); + $model->name = $faker->sentence; + $model->description = $faker->randomFloat(); + if (!is_callable($attributes)) { + $model->setAttributes($attributes, false); + } else { + $model = $attributes($model, $faker, $uniqueFaker); + } + return $model; + } +} diff --git a/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/mysql/models/base/Animal.php b/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/mysql/models/base/Animal.php new file mode 100644 index 00000000..5fd077a3 --- /dev/null +++ b/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/mysql/models/base/Animal.php @@ -0,0 +1,40 @@ + [['g', 'g2', 'g3', 'new_col'], 'trim'], + 'name_integer' => [['name'], 'integer'], + 'g_string' => [['g'], 'string'], + 'g2_string' => [['g2'], 'string'], + 'g3_string' => [['g3'], 'string'], + 'g4_integer' => [['g4'], 'integer'], + 'new_col_string' => [['new_col'], 'string'], + ]; + } +} diff --git a/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/mysql/models/base/Fruit.php b/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/mysql/models/base/Fruit.php new file mode 100644 index 00000000..da1edf2f --- /dev/null +++ b/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/mysql/models/base/Fruit.php @@ -0,0 +1,32 @@ + [['name'], 'trim'], + 'name_string' => [['name'], 'string'], + 'description_double' => [['description'], 'double'], + ]; + } +} diff --git a/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/pgsql/migrations_pgsql_db/m200000_000000_change_table_animals.php b/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/pgsql/migrations_pgsql_db/m200000_000000_change_table_animals.php new file mode 100644 index 00000000..ede74a69 --- /dev/null +++ b/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/pgsql/migrations_pgsql_db/m200000_000000_change_table_animals.php @@ -0,0 +1,29 @@ +addColumn('{{%animals}}', 'new_col', $this->text()->null()->defaultValue(null)->comment('new col added')); + $this->dropColumn('{{%animals}}', 'drop_col'); + $this->alterColumn('{{%animals}}', 'name', 'int4 NULL USING "name"::int4'); + $this->dropCommentFromColumn('{{%animals}}', 'name'); + $this->addCommentOnColumn('{{%animals}}', 'g', 'desc for g'); + $this->addCommentOnColumn('{{%animals}}', 'g2', 'changed comment on g2 col'); + $this->alterColumn('{{%animals}}', 'g4', 'int4 NULL USING "g4"::int4'); + } + + public function safeDown() + { + $this->alterColumn('{{%animals}}', 'g4', 'text NULL USING "g4"::text'); + $this->dropCommentFromColumn('{{%animals}}', 'g2'); + $this->dropCommentFromColumn('{{%animals}}', 'g'); + $this->addCommentOnColumn('{{%animals}}', 'name', 'the comment on name col'); + $this->alterColumn('{{%animals}}', 'name', 'text NULL USING "name"::text'); + $this->addColumn('{{%animals}}', 'drop_col', $this->text()->null()->defaultValue(null)); + $this->dropColumn('{{%animals}}', 'new_col'); + } +} diff --git a/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/pgsql/migrations_pgsql_db/m200000_000001_create_table_fruits.php b/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/pgsql/migrations_pgsql_db/m200000_000001_create_table_fruits.php new file mode 100644 index 00000000..de417197 --- /dev/null +++ b/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/pgsql/migrations_pgsql_db/m200000_000001_create_table_fruits.php @@ -0,0 +1,24 @@ +createTable('{{%fruits}}', [ + 'id' => $this->primaryKey(), + 'name' => $this->text()->null()->defaultValue(null)->comment('desc'), + 0 => '"description" double precision NULL DEFAULT NULL', + ]); + $this->dropCommentFromColumn('{{%fruits}}', 'id'); + $this->addCommentOnColumn('{{%fruits}}', 'name', 'desc'); + $this->addCommentOnColumn('{{%fruits}}', 'description', 'desc 2'); + } + + public function safeDown() + { + $this->dropTable('{{%fruits}}'); + } +} diff --git a/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/pgsql/models/Animal.php b/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/pgsql/models/Animal.php new file mode 100644 index 00000000..92caf2f3 --- /dev/null +++ b/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/pgsql/models/Animal.php @@ -0,0 +1,10 @@ +generateModels(['author_id' => 1]); + * $model = (new PostFaker())->generateModels(function($model, $faker, $uniqueFaker) { + * $model->scenario = 'create'; + * $model->author_id = 1; + * return $model; + * }); + **/ + public function generateModel($attributes = []) + { + $faker = $this->faker; + $uniqueFaker = $this->uniqueFaker; + $model = new Animal(); + //$model->id = $uniqueFaker->numberBetween(0, 1000000); + $model->name = $faker->numberBetween(0, 1000000); + $model->g = $faker->sentence; + $model->g2 = $faker->sentence; + $model->g3 = $faker->sentence; + $model->g4 = $faker->numberBetween(0, 1000000); + $model->new_col = $faker->sentence; + if (!is_callable($attributes)) { + $model->setAttributes($attributes, false); + } else { + $model = $attributes($model, $faker, $uniqueFaker); + } + return $model; + } +} diff --git a/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/pgsql/models/BaseModelFaker.php b/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/pgsql/models/BaseModelFaker.php new file mode 100644 index 00000000..c367fbb4 --- /dev/null +++ b/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/pgsql/models/BaseModelFaker.php @@ -0,0 +1,144 @@ +faker = FakerFactory::create(str_replace('-', '_', \Yii::$app->language)); + $this->uniqueFaker = new UniqueGenerator($this->faker); + } + + abstract public function generateModel($attributes = []); + + public function getFaker():Generator + { + return $this->faker; + } + + public function getUniqueFaker():UniqueGenerator + { + return $this->uniqueFaker; + } + + public function setFaker(Generator $faker):void + { + $this->faker = $faker; + } + + public function setUniqueFaker(UniqueGenerator $faker):void + { + $this->uniqueFaker = $faker; + } + + /** + * Generate and return model + * @param array|callable $attributes + * @param UniqueGenerator|null $uniqueFaker + * @return \yii\db\ActiveRecord + * @example MyFaker::makeOne(['user_id' => 1, 'title' => 'foo']); + * @example MyFaker::makeOne( function($model, $faker) { + * $model->scenario = 'create'; + * $model->setAttributes(['user_id' => 1, 'title' => $faker->sentence]); + * return $model; + * }); + */ + public static function makeOne($attributes = [], ?UniqueGenerator $uniqueFaker = null) + { + $fakeBuilder = new static(); + if ($uniqueFaker !== null) { + $fakeBuilder->setUniqueFaker($uniqueFaker); + } + $model = $fakeBuilder->generateModel($attributes); + return $model; + } + + /** + * Generate, save and return model + * @param array|callable $attributes + * @param UniqueGenerator|null $uniqueFaker + * @return \yii\db\ActiveRecord + * @example MyFaker::saveOne(['user_id' => 1, 'title' => 'foo']); + * @example MyFaker::saveOne( function($model, $faker) { + * $model->scenario = 'create'; + * $model->setAttributes(['user_id' => 1, 'title' => $faker->sentence]); + * return $model; + * }); + */ + public static function saveOne($attributes = [], ?UniqueGenerator $uniqueFaker = null) + { + $model = static::makeOne($attributes, $uniqueFaker); + $model->save(); + return $model; + } + + /** + * Generate and return multiple models + * @param int $number + * @param array|callable $commonAttributes + * @return \yii\db\ActiveRecord[]|array + * @example TaskFaker::make(5, ['project_id'=>1, 'user_id' => 2]); + * @example TaskFaker::make(5, function($model, $faker, $uniqueFaker) { + * $model->setAttributes(['name' => $uniqueFaker->username, 'state'=>$faker->boolean(20)]); + * return $model; + * }); + */ + public static function make(int $number, $commonAttributes = [], ?UniqueGenerator $uniqueFaker = null):array + { + if ($number < 1) { + return []; + } + $fakeBuilder = new static(); + if ($uniqueFaker !== null) { + $fakeBuilder->setUniqueFaker($uniqueFaker); + } + return array_map(function () use ($commonAttributes, $fakeBuilder) { + $model = $fakeBuilder->generateModel($commonAttributes); + return $model; + }, range(0, $number -1)); + } + + /** + * Generate, save and return multiple models + * @param int $number + * @param array|callable $commonAttributes + * @return \yii\db\ActiveRecord[]|array + * @example TaskFaker::save(5, ['project_id'=>1, 'user_id' => 2]); + * @example TaskFaker::save(5, function($model, $faker, $uniqueFaker) { + * $model->setAttributes(['name' => $uniqueFaker->username, 'state'=>$faker->boolean(20)]); + * return $model; + * }); + */ + public static function save(int $number, $commonAttributes = [], ?UniqueGenerator $uniqueFaker = null):array + { + if ($number < 1) { + return []; + } + $fakeBuilder = new static(); + if ($uniqueFaker !== null) { + $fakeBuilder->setUniqueFaker($uniqueFaker); + } + return array_map(function () use ($commonAttributes, $fakeBuilder) { + $model = $fakeBuilder->generateModel($commonAttributes); + $model->save(); + return $model; + }, range(0, $number -1)); + } +} diff --git a/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/pgsql/models/Fruit.php b/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/pgsql/models/Fruit.php new file mode 100644 index 00000000..c74c53d9 --- /dev/null +++ b/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/pgsql/models/Fruit.php @@ -0,0 +1,10 @@ +generateModels(['author_id' => 1]); + * $model = (new PostFaker())->generateModels(function($model, $faker, $uniqueFaker) { + * $model->scenario = 'create'; + * $model->author_id = 1; + * return $model; + * }); + **/ + public function generateModel($attributes = []) + { + $faker = $this->faker; + $uniqueFaker = $this->uniqueFaker; + $model = new Fruit(); + //$model->id = $uniqueFaker->numberBetween(0, 1000000); + $model->name = $faker->sentence; + $model->description = $faker->randomFloat(); + if (!is_callable($attributes)) { + $model->setAttributes($attributes, false); + } else { + $model = $attributes($model, $faker, $uniqueFaker); + } + return $model; + } +} diff --git a/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/pgsql/models/base/Animal.php b/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/pgsql/models/base/Animal.php new file mode 100644 index 00000000..5fd077a3 --- /dev/null +++ b/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/pgsql/models/base/Animal.php @@ -0,0 +1,40 @@ + [['g', 'g2', 'g3', 'new_col'], 'trim'], + 'name_integer' => [['name'], 'integer'], + 'g_string' => [['g'], 'string'], + 'g2_string' => [['g2'], 'string'], + 'g3_string' => [['g3'], 'string'], + 'g4_integer' => [['g4'], 'integer'], + 'new_col_string' => [['new_col'], 'string'], + ]; + } +} diff --git a/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/pgsql/models/base/Fruit.php b/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/pgsql/models/base/Fruit.php new file mode 100644 index 00000000..da1edf2f --- /dev/null +++ b/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/pgsql/models/base/Fruit.php @@ -0,0 +1,32 @@ + [['name'], 'trim'], + 'name_string' => [['name'], 'string'], + 'description_double' => [['description'], 'double'], + ]; + } +} diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index fc5271b4..2287b762 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -370,13 +370,13 @@ public function test60DescriptionOfAPropertyInSpecMustCorrespondToDbTableColumnC $testFile = Yii::getAlias("@specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/index.php"); $this->runGenerator($testFile); $this->runActualMigrations(); - // $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ - // 'recursive' => true, - // ]); - // $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/mysql"), [ - // 'recursive' => true, - // ]); - // $this->checkFiles($actualFiles, $expectedFiles); + $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ + 'recursive' => true, + ]); + $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/mysql"), [ + 'recursive' => true, + ]); + $this->checkFiles($actualFiles, $expectedFiles); $this->deleteTableFor60DescriptionOfAProperty(); @@ -386,14 +386,15 @@ public function test60DescriptionOfAPropertyInSpecMustCorrespondToDbTableColumnC $this->createTableFor60DescriptionOfAProperty(); $this->runGenerator($testFile, 'pgsql'); $this->runActualMigrations('pgsql'); - // $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ - // 'recursive' => true, - // ]); - // $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/mysql"), [ - // 'recursive' => true, - // ]); - // $this->checkFiles($actualFiles, $expectedFiles); -// $this->deleteTableFor60DescriptionOfAProperty(); + $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ + 'recursive' => true, + 'except' => ['migrations_mysql_db'] + ]); + $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/pgsql"), [ + 'recursive' => true, + ]); + $this->checkFiles($actualFiles, $expectedFiles); + $this->deleteTableFor60DescriptionOfAProperty(); } private function createTableFor60DescriptionOfAProperty() @@ -405,6 +406,7 @@ private function createTableFor60DescriptionOfAProperty() 'g2' => 'text', 'g3' => 'text', 'g4' => 'text', + 'drop_col' => 'text', ])->execute(); Yii::$app->db->createCommand()->addCommentOnColumn('{{%animals}}', 'name', 'the comment on name col')->execute(); From d0415fbe03c636880d8a68a40ee48098f2e4248a Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Mon, 30 Sep 2024 18:53:35 +0530 Subject: [PATCH 235/358] Fix bug and failing tests --- src/lib/migrations/PostgresMigrationBuilder.php | 4 ---- .../m200000_000002_create_table_blog_posts.php | 2 ++ .../m200000_000004_create_table_post_comments.php | 2 ++ .../m200000_000000_change_table_v2_posts.php | 4 ++-- .../m200000_000005_change_table_v2_comments.php | 2 ++ .../m200000_000000_change_table_v2_posts.php | 4 ++-- .../m200000_000005_change_table_v2_comments.php | 2 ++ .../m200000_000000_change_table_v2_posts.php | 4 ++++ .../m200000_000005_change_table_v2_comments.php | 2 ++ .../m200000_000001_create_table_fruits.php | 1 - .../migrations_pgsql_db/m200000_000001_create_table_b123s.php | 1 + .../migrations_pgsql_db/m200000_000002_create_table_a123s.php | 1 + .../m200000_000003_create_table_accounts.php | 1 + .../m200000_000005_create_table_domains.php | 2 ++ .../migrations_pgsql_db/m200000_000006_create_table_e123s.php | 1 + .../m200000_000007_create_table_routings.php | 3 +++ .../m200000_000003_create_table_pristines.php | 1 + .../m200000_000003_create_table_pristines.php | 1 + .../m200000_000003_create_table_pristines.php | 1 + .../m200000_000001_create_table_postxes.php | 4 ++++ 20 files changed, 34 insertions(+), 9 deletions(-) diff --git a/src/lib/migrations/PostgresMigrationBuilder.php b/src/lib/migrations/PostgresMigrationBuilder.php index b072d8b1..cc205584 100644 --- a/src/lib/migrations/PostgresMigrationBuilder.php +++ b/src/lib/migrations/PostgresMigrationBuilder.php @@ -266,10 +266,6 @@ public function handleCommentsMigration() if ($column->comment) { $this->migration ->addUpCode($this->recordBuilder->addCommentOnColumn($tableAlias, $column->name, $column->comment)); - } else { - $this->migration - ->addUpCode($this->recordBuilder->dropCommentOnColumn($tableAlias, $column->name)) - ; } } } diff --git a/tests/specs/blog/migrations_pgsql_db/m200000_000002_create_table_blog_posts.php b/tests/specs/blog/migrations_pgsql_db/m200000_000002_create_table_blog_posts.php index a7266997..9dbe55cf 100644 --- a/tests/specs/blog/migrations_pgsql_db/m200000_000002_create_table_blog_posts.php +++ b/tests/specs/blog/migrations_pgsql_db/m200000_000002_create_table_blog_posts.php @@ -21,6 +21,8 @@ public function safeUp() $this->createIndex('blog_posts_slug_key', '{{%blog_posts}}', 'slug', true); $this->addForeignKey('fk_blog_posts_category_id_categories_id', '{{%blog_posts}}', 'category_id', '{{%categories}}', 'id'); $this->addForeignKey('fk_blog_posts_created_by_id_users_id', '{{%blog_posts}}', 'created_by_id', '{{%users}}', 'id'); + $this->addCommentOnColumn('{{%blog_posts}}', 'category_id', 'Category of posts'); + $this->addCommentOnColumn('{{%blog_posts}}', 'created_by_id', 'The User'); } public function safeDown() diff --git a/tests/specs/blog/migrations_pgsql_db/m200000_000004_create_table_post_comments.php b/tests/specs/blog/migrations_pgsql_db/m200000_000004_create_table_post_comments.php index 1229677b..2d924e52 100644 --- a/tests/specs/blog/migrations_pgsql_db/m200000_000004_create_table_post_comments.php +++ b/tests/specs/blog/migrations_pgsql_db/m200000_000004_create_table_post_comments.php @@ -17,6 +17,8 @@ public function safeUp() ]); $this->addForeignKey('fk_post_comments_post_id_blog_posts_uid', '{{%post_comments}}', 'post_id', '{{%blog_posts}}', 'uid'); $this->addForeignKey('fk_post_comments_author_id_users_id', '{{%post_comments}}', 'author_id', '{{%users}}', 'id'); + $this->addCommentOnColumn('{{%post_comments}}', 'post_id', 'A blog post (uid used as pk for test purposes)'); + $this->addCommentOnColumn('{{%post_comments}}', 'author_id', 'The User'); } public function safeDown() diff --git a/tests/specs/blog_v2/migrations_maria_db/m200000_000000_change_table_v2_posts.php b/tests/specs/blog_v2/migrations_maria_db/m200000_000000_change_table_v2_posts.php index 5c43dabf..33bdf987 100644 --- a/tests/specs/blog_v2/migrations_maria_db/m200000_000000_change_table_v2_posts.php +++ b/tests/specs/blog_v2/migrations_maria_db/m200000_000000_change_table_v2_posts.php @@ -10,9 +10,9 @@ public function up() $this->addColumn('{{%v2_posts}}', 'id', $this->bigPrimaryKey()); $this->addColumn('{{%v2_posts}}', 'lang', 'enum("ru", "eng") NULL DEFAULT \'ru\' AFTER slug'); $this->dropColumn('{{%v2_posts}}', 'uid'); - $this->alterColumn('{{%v2_posts}}', 'category_id', $this->bigInteger()->notNull()); + $this->alterColumn('{{%v2_posts}}', 'category_id', $this->bigInteger()->notNull()->comment('Category of posts')); $this->alterColumn('{{%v2_posts}}', 'active', $this->tinyInteger(1)->notNull()); - $this->alterColumn('{{%v2_posts}}', 'created_by_id', $this->bigInteger()->null()->defaultValue(null)); + $this->alterColumn('{{%v2_posts}}', 'created_by_id', $this->bigInteger()->null()->defaultValue(null)->comment('The User')); $this->dropIndex('v2_posts_slug_key', '{{%v2_posts}}'); } diff --git a/tests/specs/blog_v2/migrations_maria_db/m200000_000005_change_table_v2_comments.php b/tests/specs/blog_v2/migrations_maria_db/m200000_000005_change_table_v2_comments.php index e2f7b4ad..3494daeb 100644 --- a/tests/specs/blog_v2/migrations_maria_db/m200000_000005_change_table_v2_comments.php +++ b/tests/specs/blog_v2/migrations_maria_db/m200000_000005_change_table_v2_comments.php @@ -11,6 +11,7 @@ public function up() $this->dropForeignKey('fk_v2_comments_author_id_v2_users_id', '{{%v2_comments}}'); $this->addColumn('{{%v2_comments}}', 'user_id', $this->bigInteger()->null()->defaultValue(null)->after('post_id')->comment('The User')); $this->dropColumn('{{%v2_comments}}', 'author_id'); + $this->alterColumn('{{%v2_comments}}', 'post_id', $this->bigInteger(20)->notNull()->comment('A blog post (uid used as pk for test purposes)')); $this->alterColumn('{{%v2_comments}}', 'message', $this->text()->notNull()); $this->alterColumn('{{%v2_comments}}', 'meta_data', $this->string(300)->null()->defaultValue('')); $this->alterColumn('{{%v2_comments}}', 'created_at', $this->timestamp()->notNull()); @@ -25,6 +26,7 @@ public function down() $this->alterColumn('{{%v2_comments}}', 'created_at', $this->integer(11)->notNull()); $this->alterColumn('{{%v2_comments}}', 'meta_data', 'json NOT NULL DEFAULT \'[]\''); $this->alterColumn('{{%v2_comments}}', 'message', 'json NOT NULL DEFAULT \'[]\''); + $this->alterColumn('{{%v2_comments}}', 'post_id', $this->bigInteger(20)->notNull()); $this->addColumn('{{%v2_comments}}', 'author_id', $this->integer(11)->notNull()); $this->dropColumn('{{%v2_comments}}', 'user_id'); $this->addForeignKey('fk_v2_comments_author_id_v2_users_id', '{{%v2_comments}}', 'id', 'v2_users', 'author_id'); diff --git a/tests/specs/blog_v2/migrations_mysql_db/m200000_000000_change_table_v2_posts.php b/tests/specs/blog_v2/migrations_mysql_db/m200000_000000_change_table_v2_posts.php index be309829..eec5ee6b 100644 --- a/tests/specs/blog_v2/migrations_mysql_db/m200000_000000_change_table_v2_posts.php +++ b/tests/specs/blog_v2/migrations_mysql_db/m200000_000000_change_table_v2_posts.php @@ -10,9 +10,9 @@ public function up() $this->addColumn('{{%v2_posts}}', 'id', $this->bigPrimaryKey()); $this->addColumn('{{%v2_posts}}', 'lang', 'enum("ru", "eng") NULL DEFAULT \'ru\' AFTER slug'); $this->dropColumn('{{%v2_posts}}', 'uid'); - $this->alterColumn('{{%v2_posts}}', 'category_id', $this->bigInteger()->notNull()); + $this->alterColumn('{{%v2_posts}}', 'category_id', $this->bigInteger()->notNull()->comment('Category of posts')); $this->alterColumn('{{%v2_posts}}', 'active', $this->tinyInteger(1)->notNull()); - $this->alterColumn('{{%v2_posts}}', 'created_by_id', $this->bigInteger()->null()->defaultValue(null)); + $this->alterColumn('{{%v2_posts}}', 'created_by_id', $this->bigInteger()->null()->defaultValue(null)->comment('The User')); $this->dropIndex('v2_posts_slug_key', '{{%v2_posts}}'); } diff --git a/tests/specs/blog_v2/migrations_mysql_db/m200000_000005_change_table_v2_comments.php b/tests/specs/blog_v2/migrations_mysql_db/m200000_000005_change_table_v2_comments.php index 130014e7..0fd92aa1 100644 --- a/tests/specs/blog_v2/migrations_mysql_db/m200000_000005_change_table_v2_comments.php +++ b/tests/specs/blog_v2/migrations_mysql_db/m200000_000005_change_table_v2_comments.php @@ -11,6 +11,7 @@ public function up() $this->dropForeignKey('fk_v2_comments_author_id_v2_users_id', '{{%v2_comments}}'); $this->addColumn('{{%v2_comments}}', 'user_id', $this->bigInteger()->null()->defaultValue(null)->after('post_id')->comment('The User')); $this->dropColumn('{{%v2_comments}}', 'author_id'); + $this->alterColumn('{{%v2_comments}}', 'post_id', $this->bigInteger()->notNull()->comment('A blog post (uid used as pk for test purposes)')); $this->alterColumn('{{%v2_comments}}', 'message', $this->text()->notNull()); $this->alterColumn('{{%v2_comments}}', 'meta_data', $this->string(300)->null()->defaultValue('')); $this->alterColumn('{{%v2_comments}}', 'created_at', $this->timestamp()->notNull()); @@ -25,6 +26,7 @@ public function down() $this->alterColumn('{{%v2_comments}}', 'created_at', $this->integer()->notNull()); $this->alterColumn('{{%v2_comments}}', 'meta_data', 'json NOT NULL'); $this->alterColumn('{{%v2_comments}}', 'message', 'json NOT NULL'); + $this->alterColumn('{{%v2_comments}}', 'post_id', $this->bigInteger()->notNull()); $this->addColumn('{{%v2_comments}}', 'author_id', $this->integer()->notNull()); $this->dropColumn('{{%v2_comments}}', 'user_id'); $this->addForeignKey('fk_v2_comments_author_id_v2_users_id', '{{%v2_comments}}', 'id', 'v2_users', 'author_id'); diff --git a/tests/specs/blog_v2/migrations_pgsql_db/m200000_000000_change_table_v2_posts.php b/tests/specs/blog_v2/migrations_pgsql_db/m200000_000000_change_table_v2_posts.php index 5188983b..56755b58 100644 --- a/tests/specs/blog_v2/migrations_pgsql_db/m200000_000000_change_table_v2_posts.php +++ b/tests/specs/blog_v2/migrations_pgsql_db/m200000_000000_change_table_v2_posts.php @@ -12,15 +12,19 @@ public function safeUp() $this->addColumn('{{%v2_posts}}', 'lang', '"enum_itt_v2_posts_lang" NULL DEFAULT \'ru\''); $this->dropColumn('{{%v2_posts}}', 'uid'); $this->alterColumn('{{%v2_posts}}', 'category_id', 'int8 NOT NULL USING "category_id"::int8'); + $this->addCommentOnColumn('{{%v2_posts}}', 'category_id', 'Category of posts'); $this->alterColumn('{{%v2_posts}}', 'active', "DROP DEFAULT"); $this->alterColumn('{{%v2_posts}}', 'created_by_id', 'int8 NULL USING "created_by_id"::int8'); + $this->addCommentOnColumn('{{%v2_posts}}', 'created_by_id', 'The User'); $this->dropIndex('v2_posts_slug_key', '{{%v2_posts}}'); } public function safeDown() { $this->createIndex('v2_posts_slug_key', '{{%v2_posts}}', 'slug', true); + $this->dropCommentFromColumn('{{%v2_posts}}', 'created_by_id'); $this->alterColumn('{{%v2_posts}}', 'created_by_id', 'int4 NULL USING "created_by_id"::int4'); + $this->dropCommentFromColumn('{{%v2_posts}}', 'category_id'); $this->alterColumn('{{%v2_posts}}', 'category_id', 'int4 NOT NULL USING "category_id"::int4'); $this->addColumn('{{%v2_posts}}', 'uid', $this->bigInteger()->notNull()); $this->dropColumn('{{%v2_posts}}', 'lang'); diff --git a/tests/specs/blog_v2/migrations_pgsql_db/m200000_000005_change_table_v2_comments.php b/tests/specs/blog_v2/migrations_pgsql_db/m200000_000005_change_table_v2_comments.php index 452a4401..a77155bd 100644 --- a/tests/specs/blog_v2/migrations_pgsql_db/m200000_000005_change_table_v2_comments.php +++ b/tests/specs/blog_v2/migrations_pgsql_db/m200000_000005_change_table_v2_comments.php @@ -11,6 +11,7 @@ public function safeUp() $this->dropForeignKey('fk_v2_comments_post_id_v2_posts_uid', '{{%v2_comments}}'); $this->addColumn('{{%v2_comments}}', 'user_id', $this->bigInteger()->null()->defaultValue(null)->comment('The User')); $this->dropColumn('{{%v2_comments}}', 'author_id'); + $this->addCommentOnColumn('{{%v2_comments}}', 'post_id', 'A blog post (uid used as pk for test purposes)'); $this->alterColumn('{{%v2_comments}}', 'message', 'text NOT NULL USING "message"::text'); $this->alterColumn('{{%v2_comments}}', 'message', "DROP DEFAULT"); $this->alterColumn('{{%v2_comments}}', 'meta_data', 'varchar(300) NULL USING "meta_data"::varchar'); @@ -28,6 +29,7 @@ public function safeDown() $this->alterColumn('{{%v2_comments}}', 'created_at', 'int4 NOT NULL USING "created_at"::int4'); $this->alterColumn('{{%v2_comments}}', 'meta_data', 'jsonb NOT NULL USING "meta_data"::jsonb'); $this->alterColumn('{{%v2_comments}}', 'message', 'jsonb NOT NULL USING "message"::jsonb'); + $this->dropCommentFromColumn('{{%v2_comments}}', 'post_id'); $this->addColumn('{{%v2_comments}}', 'author_id', $this->integer()->notNull()); $this->dropColumn('{{%v2_comments}}', 'user_id'); $this->alterColumn('{{%v2_comments}}', 'message', "SET DEFAULT '[]'"); diff --git a/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/pgsql/migrations_pgsql_db/m200000_000001_create_table_fruits.php b/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/pgsql/migrations_pgsql_db/m200000_000001_create_table_fruits.php index de417197..b42b2822 100644 --- a/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/pgsql/migrations_pgsql_db/m200000_000001_create_table_fruits.php +++ b/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/pgsql/migrations_pgsql_db/m200000_000001_create_table_fruits.php @@ -12,7 +12,6 @@ public function safeUp() 'name' => $this->text()->null()->defaultValue(null)->comment('desc'), 0 => '"description" double precision NULL DEFAULT NULL', ]); - $this->dropCommentFromColumn('{{%fruits}}', 'id'); $this->addCommentOnColumn('{{%fruits}}', 'name', 'desc'); $this->addCommentOnColumn('{{%fruits}}', 'description', 'desc 2'); } diff --git a/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000001_create_table_b123s.php b/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000001_create_table_b123s.php index 7fe423f5..688d4e58 100644 --- a/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000001_create_table_b123s.php +++ b/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000001_create_table_b123s.php @@ -13,6 +13,7 @@ public function safeUp() 'c123_id' => $this->integer()->null()->defaultValue(null)->comment('desc'), ]); $this->addForeignKey('fk_b123s_c123_id_c123s_id', '{{%b123s}}', 'c123_id', '{{%c123s}}', 'id'); + $this->addCommentOnColumn('{{%b123s}}', 'c123_id', 'desc'); } public function safeDown() diff --git a/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000002_create_table_a123s.php b/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000002_create_table_a123s.php index 4b2aad61..f93343c6 100644 --- a/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000002_create_table_a123s.php +++ b/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000002_create_table_a123s.php @@ -13,6 +13,7 @@ public function safeUp() 'b123_id' => $this->integer()->null()->defaultValue(null)->comment('desc'), ]); $this->addForeignKey('fk_a123s_b123_id_b123s_id', '{{%a123s}}', 'b123_id', '{{%b123s}}', 'id'); + $this->addCommentOnColumn('{{%a123s}}', 'b123_id', 'desc'); } public function safeDown() diff --git a/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000003_create_table_accounts.php b/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000003_create_table_accounts.php index 843678d6..271f8a7b 100644 --- a/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000003_create_table_accounts.php +++ b/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000003_create_table_accounts.php @@ -11,6 +11,7 @@ public function safeUp() 'id' => $this->primaryKey(), 'name' => $this->string(40)->notNull()->comment('account name'), ]); + $this->addCommentOnColumn('{{%accounts}}', 'name', 'account name'); } public function safeDown() diff --git a/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000005_create_table_domains.php b/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000005_create_table_domains.php index 871b473f..c5a0e7f2 100644 --- a/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000005_create_table_domains.php +++ b/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000005_create_table_domains.php @@ -14,6 +14,8 @@ public function safeUp() 0 => '"created_at" timestamp NOT NULL', ]); $this->addForeignKey('fk_domains_account_id_accounts_id', '{{%domains}}', 'account_id', '{{%accounts}}', 'id'); + $this->addCommentOnColumn('{{%domains}}', 'name', 'domain or sub-domain name, in DNS syntax, IDN are converted'); + $this->addCommentOnColumn('{{%domains}}', 'account_id', 'user account'); } public function safeDown() diff --git a/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000006_create_table_e123s.php b/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000006_create_table_e123s.php index 59d643a4..55cb62af 100644 --- a/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000006_create_table_e123s.php +++ b/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000006_create_table_e123s.php @@ -13,6 +13,7 @@ public function safeUp() 'b123_id' => $this->integer()->null()->defaultValue(null)->comment('desc'), ]); $this->addForeignKey('fk_e123s_b123_id_b123s_id', '{{%e123s}}', 'b123_id', '{{%b123s}}', 'id'); + $this->addCommentOnColumn('{{%e123s}}', 'b123_id', 'desc'); } public function safeDown() diff --git a/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000007_create_table_routings.php b/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000007_create_table_routings.php index f880d830..bd09ae48 100644 --- a/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000007_create_table_routings.php +++ b/tests/specs/relations_in_faker/app/migrations_pgsql_db/m200000_000007_create_table_routings.php @@ -21,6 +21,9 @@ public function safeUp() $this->addForeignKey('fk_routings_domain_id_domains_id', '{{%routings}}', 'domain_id', '{{%domains}}', 'id'); $this->addForeignKey('fk_routings_d123_id_d123s_id', '{{%routings}}', 'd123_id', '{{%d123s}}', 'id'); $this->addForeignKey('fk_routings_a123_id_a123s_id', '{{%routings}}', 'a123_id', '{{%a123s}}', 'id'); + $this->addCommentOnColumn('{{%routings}}', 'domain_id', 'domain'); + $this->addCommentOnColumn('{{%routings}}', 'd123_id', 'desc'); + $this->addCommentOnColumn('{{%routings}}', 'a123_id', 'desc'); } public function safeDown() diff --git a/tests/specs/x_db_type/edit_column/pgsql/app/migrations_pgsql_db/m200000_000003_create_table_pristines.php b/tests/specs/x_db_type/edit_column/pgsql/app/migrations_pgsql_db/m200000_000003_create_table_pristines.php index aab6bb88..7fa8a01f 100644 --- a/tests/specs/x_db_type/edit_column/pgsql/app/migrations_pgsql_db/m200000_000003_create_table_pristines.php +++ b/tests/specs/x_db_type/edit_column/pgsql/app/migrations_pgsql_db/m200000_000003_create_table_pristines.php @@ -21,6 +21,7 @@ public function safeUp() 9 => '"col_11" text NULL DEFAULT NULL', 10 => '"price" decimal(10,2) NULL DEFAULT 0', ]); + $this->addCommentOnColumn('{{%pristines}}', 'price', 'price in EUR'); } public function safeDown() diff --git a/tests/specs/x_db_type/fresh/pgsql/app/migrations_pgsql_db/m200000_000003_create_table_pristines.php b/tests/specs/x_db_type/fresh/pgsql/app/migrations_pgsql_db/m200000_000003_create_table_pristines.php index aab6bb88..7fa8a01f 100644 --- a/tests/specs/x_db_type/fresh/pgsql/app/migrations_pgsql_db/m200000_000003_create_table_pristines.php +++ b/tests/specs/x_db_type/fresh/pgsql/app/migrations_pgsql_db/m200000_000003_create_table_pristines.php @@ -21,6 +21,7 @@ public function safeUp() 9 => '"col_11" text NULL DEFAULT NULL', 10 => '"price" decimal(10,2) NULL DEFAULT 0', ]); + $this->addCommentOnColumn('{{%pristines}}', 'price', 'price in EUR'); } public function safeDown() diff --git a/tests/specs/x_db_type/new_column/pgsql/app/migrations_pgsql_db/m200000_000003_create_table_pristines.php b/tests/specs/x_db_type/new_column/pgsql/app/migrations_pgsql_db/m200000_000003_create_table_pristines.php index aab6bb88..7fa8a01f 100644 --- a/tests/specs/x_db_type/new_column/pgsql/app/migrations_pgsql_db/m200000_000003_create_table_pristines.php +++ b/tests/specs/x_db_type/new_column/pgsql/app/migrations_pgsql_db/m200000_000003_create_table_pristines.php @@ -21,6 +21,7 @@ public function safeUp() 9 => '"col_11" text NULL DEFAULT NULL', 10 => '"price" decimal(10,2) NULL DEFAULT 0', ]); + $this->addCommentOnColumn('{{%pristines}}', 'price', 'price in EUR'); } public function safeDown() diff --git a/tests/specs/x_on_x_fk_constraint/app/migrations_pgsql_db/m200000_000001_create_table_postxes.php b/tests/specs/x_on_x_fk_constraint/app/migrations_pgsql_db/m200000_000001_create_table_postxes.php index 777920de..5593db95 100644 --- a/tests/specs/x_on_x_fk_constraint/app/migrations_pgsql_db/m200000_000001_create_table_postxes.php +++ b/tests/specs/x_on_x_fk_constraint/app/migrations_pgsql_db/m200000_000001_create_table_postxes.php @@ -19,6 +19,10 @@ public function safeUp() $this->addForeignKey('fk_postxes_user_2_id_userxes_id', '{{%postxes}}', 'user_2_id', '{{%userxes}}', 'id', 'SET NULL', 'CASCADE'); $this->addForeignKey('fk_postxes_user_3_id_userxes_id', '{{%postxes}}', 'user_3_id', '{{%userxes}}', 'id', 'SET NULL'); $this->addForeignKey('fk_postxes_user_4_id_userxes_id', '{{%postxes}}', 'user_4_id', '{{%userxes}}', 'id'); + $this->addCommentOnColumn('{{%postxes}}', 'user_id', 'x on-x (update|delete) foreign key constraint'); + $this->addCommentOnColumn('{{%postxes}}', 'user_2_id', 'x on-x (update|delete) foreign key constraint'); + $this->addCommentOnColumn('{{%postxes}}', 'user_3_id', 'x on-x (update|delete) foreign key constraint'); + $this->addCommentOnColumn('{{%postxes}}', 'user_4_id', 'x on-x (update|delete) foreign key constraint'); } public function safeDown() From fa47121e01bfdab94ce6b1bddc80e2edfbcd6141 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Mon, 30 Sep 2024 19:27:59 +0530 Subject: [PATCH 236/358] Rename function and constant --- src/lib/migrations/MigrationRecordBuilder.php | 8 ++++---- src/lib/migrations/PostgresMigrationBuilder.php | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/lib/migrations/MigrationRecordBuilder.php b/src/lib/migrations/MigrationRecordBuilder.php index cbe0af72..32cc8885 100644 --- a/src/lib/migrations/MigrationRecordBuilder.php +++ b/src/lib/migrations/MigrationRecordBuilder.php @@ -48,7 +48,7 @@ final class MigrationRecordBuilder public const ADD_COMMENT_ON_COLUMN = MigrationRecordBuilder::INDENT . "\$this->addCommentOnColumn('%s', '%s', '%s');"; - public const DROP_COMMENT_ON_COLUMN = MigrationRecordBuilder::INDENT . "\$this->dropCommentFromColumn('%s', '%s');"; + public const DROP_COMMENT_FROM_COLUMN = MigrationRecordBuilder::INDENT . "\$this->dropCommentFromColumn('%s', '%s');"; /** * @var \yii\db\Schema @@ -350,13 +350,13 @@ public static function makeString(array $codeColumns): string return $codeColumns; } - public function addCommentOnColumn($table, string $column, string $comment) + public function addCommentOnColumn($table, string $column, string $comment): string { return sprintf(self::ADD_COMMENT_ON_COLUMN, $table, $column, $comment); } - public function dropCommentOnColumn($table, string $column) + public function dropCommentFromColumn($table, string $column): string { - return sprintf(self::DROP_COMMENT_ON_COLUMN, $table, $column); + return sprintf(self::DROP_COMMENT_FROM_COLUMN, $table, $column); } } diff --git a/src/lib/migrations/PostgresMigrationBuilder.php b/src/lib/migrations/PostgresMigrationBuilder.php index cc205584..7f5d8a11 100644 --- a/src/lib/migrations/PostgresMigrationBuilder.php +++ b/src/lib/migrations/PostgresMigrationBuilder.php @@ -94,9 +94,9 @@ protected function buildColumnChanges(ColumnSchema $current, ColumnSchema $desir if (in_array('comment', $changed, true)) { // TODO if ($desired->comment) { $this->migration->addUpCode($this->recordBuilder->addCommentOnColumn($tableName, $desired->name, $desired->comment)); - $this->migration->addDownCode($this->recordBuilder->dropCommentOnColumn($tableName, $desired->name)); + $this->migration->addDownCode($this->recordBuilder->dropCommentFromColumn($tableName, $desired->name)); } else { - $this->migration->addUpCode($this->recordBuilder->dropCommentOnColumn($tableName, $desired->name)); + $this->migration->addUpCode($this->recordBuilder->dropCommentFromColumn($tableName, $desired->name)); $this->migration->addDownCode($this->recordBuilder->addCommentOnColumn($tableName, $desired->name, $current->comment)); } } From 3fbf3c7bec2f5204a32181e27057b5cc3312ae53 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Tue, 1 Oct 2024 19:50:05 +0530 Subject: [PATCH 237/358] Handle quoting of values --- src/lib/ColumnToCode.php | 4 ++-- src/lib/migrations/BaseMigrationBuilder.php | 6 +++--- src/lib/migrations/MigrationRecordBuilder.php | 4 ++-- .../index.yml | 4 ++-- .../m200000_000001_create_table_fruits.php | 4 ++-- .../mysql/models/base/Fruit.php | 4 ++-- .../m200000_000001_create_table_fruits.php | 6 +++--- .../pgsql/models/base/Fruit.php | 4 ++-- 8 files changed, 18 insertions(+), 18 deletions(-) diff --git a/src/lib/ColumnToCode.php b/src/lib/ColumnToCode.php index 73030ea5..a192fb41 100644 --- a/src/lib/ColumnToCode.php +++ b/src/lib/ColumnToCode.php @@ -177,8 +177,8 @@ private function resolve():void $this->rawParts['nullable'] = $this->column->allowNull ? 'NULL' : 'NOT NULL'; $this->fluentParts['nullable'] = $this->column->allowNull === true ? 'null()' : 'notNull()'; - $this->fluentParts['comment'] = $this->column->comment ? 'comment(\''.$this->column->comment.'\')' : $this->fluentParts['comment']; - $this->rawParts['comment'] = $this->column->comment ? 'COMMENT \''.$this->column->comment.'\'' : $this->fluentParts['comment']; + $this->fluentParts['comment'] = $this->column->comment ? 'comment('.var_export($this->column->comment, true).')' : $this->fluentParts['comment']; + $this->rawParts['comment'] = $this->column->comment ? 'COMMENT '.var_export($this->column->comment, true) : $this->rawParts['comment']; if (array_key_exists($dbType, self::INT_TYPE_MAP)) { $this->fluentParts['type'] = self::INT_TYPE_MAP[$dbType] . $fluentSize; diff --git a/src/lib/migrations/BaseMigrationBuilder.php b/src/lib/migrations/BaseMigrationBuilder.php index 8a49de34..a9da6374 100644 --- a/src/lib/migrations/BaseMigrationBuilder.php +++ b/src/lib/migrations/BaseMigrationBuilder.php @@ -449,16 +449,16 @@ public function tmpSaveNewCol(string $tableAlias, \cebe\yii2openapi\db\ColumnSch if (ApiGenerator::isPostgres() && static::isEnum($columnSchema)) { $allEnumValues = $columnSchema->enumValues; $allEnumValues = array_map(function ($aValue) { - return "'$aValue'"; + return $this->db->quoteValue($aValue); }, $allEnumValues); Yii::$app->db->createCommand( 'CREATE TYPE '.$tmpEnumName($columnSchema->name).' AS ENUM('.implode(', ', $allEnumValues).')' - )->execute(); // TODO quote value + )->execute(); } Yii::$app->db->createCommand()->createTable($tmpTableName, $column)->execute(); if (ApiGenerator::isPostgres() && $columnSchema->comment) { - Yii::$app->db->createCommand("COMMENT ON COLUMN $tmpTableName.$columnSchema->name IS '$columnSchema->comment'")->execute(); // TODO quote comment + Yii::$app->db->createCommand("COMMENT ON COLUMN $tmpTableName.$columnSchema->name IS {$this->db->quoteValue($columnSchema->comment)}")->execute(); } $table = Yii::$app->db->getTableSchema($tmpTableName); diff --git a/src/lib/migrations/MigrationRecordBuilder.php b/src/lib/migrations/MigrationRecordBuilder.php index 32cc8885..9adfc6af 100644 --- a/src/lib/migrations/MigrationRecordBuilder.php +++ b/src/lib/migrations/MigrationRecordBuilder.php @@ -46,7 +46,7 @@ final class MigrationRecordBuilder public const ALTER_COLUMN_RAW_PGSQL = MigrationRecordBuilder::INDENT . "\$this->db->createCommand('ALTER TABLE %s ALTER COLUMN \"%s\" SET DATA TYPE %s')->execute();"; - public const ADD_COMMENT_ON_COLUMN = MigrationRecordBuilder::INDENT . "\$this->addCommentOnColumn('%s', '%s', '%s');"; + public const ADD_COMMENT_ON_COLUMN = MigrationRecordBuilder::INDENT . "\$this->addCommentOnColumn('%s', '%s', %s);"; public const DROP_COMMENT_FROM_COLUMN = MigrationRecordBuilder::INDENT . "\$this->dropCommentFromColumn('%s', '%s');"; @@ -352,7 +352,7 @@ public static function makeString(array $codeColumns): string public function addCommentOnColumn($table, string $column, string $comment): string { - return sprintf(self::ADD_COMMENT_ON_COLUMN, $table, $column, $comment); + return sprintf(self::ADD_COMMENT_ON_COLUMN, $table, $column, var_export($comment, true)); } public function dropCommentFromColumn($table, string $column): string diff --git a/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/index.yml b/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/index.yml index a034947e..d8e131d6 100644 --- a/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/index.yml +++ b/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/index.yml @@ -13,7 +13,7 @@ components: type: integer name: type: string - description: desc + description: desc with ' quote # colour: # type: string # maxLength: 255 @@ -21,7 +21,7 @@ components: description: type: number x-db-type: double precision - description: desc 2 + description: desc ' 2 Animal: type: object properties: diff --git a/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/mysql/migrations_mysql_db/m200000_000001_create_table_fruits.php b/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/mysql/migrations_mysql_db/m200000_000001_create_table_fruits.php index 4fa328d9..c4271f02 100644 --- a/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/mysql/migrations_mysql_db/m200000_000001_create_table_fruits.php +++ b/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/mysql/migrations_mysql_db/m200000_000001_create_table_fruits.php @@ -9,8 +9,8 @@ public function up() { $this->createTable('{{%fruits}}', [ 'id' => $this->primaryKey(), - 'name' => $this->text()->null()->comment('desc'), - 0 => 'description double precision NULL DEFAULT NULL COMMENT \'desc 2\'', + 'name' => $this->text()->null()->comment('desc with \' quote'), + 0 => 'description double precision NULL DEFAULT NULL COMMENT \'desc \\\' 2\'', ]); } diff --git a/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/mysql/models/base/Fruit.php b/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/mysql/models/base/Fruit.php index da1edf2f..177133f5 100644 --- a/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/mysql/models/base/Fruit.php +++ b/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/mysql/models/base/Fruit.php @@ -10,8 +10,8 @@ * This is the model class for table "fruits". * * @property int $id - * @property string $name desc - * @property double $description desc 2 + * @property string $name desc with ' quote + * @property double $description desc ' 2 * */ abstract class Fruit extends \yii\db\ActiveRecord diff --git a/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/pgsql/migrations_pgsql_db/m200000_000001_create_table_fruits.php b/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/pgsql/migrations_pgsql_db/m200000_000001_create_table_fruits.php index b42b2822..21467feb 100644 --- a/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/pgsql/migrations_pgsql_db/m200000_000001_create_table_fruits.php +++ b/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/pgsql/migrations_pgsql_db/m200000_000001_create_table_fruits.php @@ -9,11 +9,11 @@ public function safeUp() { $this->createTable('{{%fruits}}', [ 'id' => $this->primaryKey(), - 'name' => $this->text()->null()->defaultValue(null)->comment('desc'), + 'name' => $this->text()->null()->defaultValue(null)->comment('desc with \' quote'), 0 => '"description" double precision NULL DEFAULT NULL', ]); - $this->addCommentOnColumn('{{%fruits}}', 'name', 'desc'); - $this->addCommentOnColumn('{{%fruits}}', 'description', 'desc 2'); + $this->addCommentOnColumn('{{%fruits}}', 'name', 'desc with \' quote'); + $this->addCommentOnColumn('{{%fruits}}', 'description', 'desc \' 2'); } public function safeDown() diff --git a/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/pgsql/models/base/Fruit.php b/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/pgsql/models/base/Fruit.php index da1edf2f..177133f5 100644 --- a/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/pgsql/models/base/Fruit.php +++ b/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/pgsql/models/base/Fruit.php @@ -10,8 +10,8 @@ * This is the model class for table "fruits". * * @property int $id - * @property string $name desc - * @property double $description desc 2 + * @property string $name desc with ' quote + * @property double $description desc ' 2 * */ abstract class Fruit extends \yii\db\ActiveRecord From 6ea5f1d273ea407014306520a84e47f803fc7ad1 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Tue, 1 Oct 2024 19:55:52 +0530 Subject: [PATCH 238/358] Resolve TODOs --- src/lib/migrations/PostgresMigrationBuilder.php | 2 +- .../index.yml | 4 ---- 2 files changed, 1 insertion(+), 5 deletions(-) diff --git a/src/lib/migrations/PostgresMigrationBuilder.php b/src/lib/migrations/PostgresMigrationBuilder.php index 7f5d8a11..cc0618c0 100644 --- a/src/lib/migrations/PostgresMigrationBuilder.php +++ b/src/lib/migrations/PostgresMigrationBuilder.php @@ -91,7 +91,7 @@ protected function buildColumnChanges(ColumnSchema $current, ColumnSchema $desir } } - if (in_array('comment', $changed, true)) { // TODO + if (in_array('comment', $changed, true)) { if ($desired->comment) { $this->migration->addUpCode($this->recordBuilder->addCommentOnColumn($tableName, $desired->name, $desired->comment)); $this->migration->addDownCode($this->recordBuilder->dropCommentFromColumn($tableName, $desired->name)); diff --git a/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/index.yml b/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/index.yml index d8e131d6..cfefea9b 100644 --- a/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/index.yml +++ b/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/index.yml @@ -14,10 +14,6 @@ components: name: type: string description: desc with ' quote -# colour: -# type: string - # maxLength: 255 - # x-db-type: varbinary # TODO description: type: number x-db-type: double precision From 79bc270c2022adc2f49bd445e980bf8173ead558 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Thu, 3 Oct 2024 22:11:21 +0530 Subject: [PATCH 239/358] Fix issue: case: drop 2 column: its position in add column in down code in migration --- src/db/ColumnSchema.php | 7 ++++ src/lib/migrations/BaseMigrationBuilder.php | 39 +++++++++++++++---- src/lib/migrations/MigrationRecordBuilder.php | 16 ++++++-- src/lib/migrations/MysqlMigrationBuilder.php | 15 ++++++- .../index.yml | 14 +++---- tests/unit/IssueFixTest.php | 2 +- 6 files changed, 72 insertions(+), 21 deletions(-) diff --git a/src/db/ColumnSchema.php b/src/db/ColumnSchema.php index 71127a24..c6725b10 100644 --- a/src/db/ColumnSchema.php +++ b/src/db/ColumnSchema.php @@ -25,4 +25,11 @@ class ColumnSchema extends \yii\db\ColumnSchema * ``` */ public $xDbType; + + /** + * TODO + * Used only for MySQL/MariaDB + * @var string|null + */ + public ?string $position = null; } diff --git a/src/lib/migrations/BaseMigrationBuilder.php b/src/lib/migrations/BaseMigrationBuilder.php index d4c49c21..ff0c49fe 100644 --- a/src/lib/migrations/BaseMigrationBuilder.php +++ b/src/lib/migrations/BaseMigrationBuilder.php @@ -220,6 +220,9 @@ function (string $unknownColumn) { } else { $this->buildRelations(); } + +// $this->handleColumnsPositionsChanges($haveNames, $wantNames); + return $this->migration; } @@ -249,12 +252,12 @@ protected function buildColumnsDrop(array $columns):void { foreach ($columns as $column) { $tableName = $this->model->getTableAlias(); + $position = $this->findPosition($column, true); if ($column->isPrimaryKey && !$column->autoIncrement) { $pkName = 'pk_' . $this->model->tableName . '_' . $column->name; $this->migration->addDownCode($this->recordBuilder->addPrimaryKey($tableName, [$column->name], $pkName)) ->addUpCode($this->recordBuilder->dropPrimaryKey($tableName, [$column->name], $pkName)); } - $position = $this->findPosition($column, true); $this->migration->addDownCode($this->recordBuilder->addDbColumn($tableName, $column, $position)) ->addUpCode($this->recordBuilder->dropColumn($tableName, $column->name)); } @@ -514,6 +517,8 @@ public function isDefaultValueChanged( } /** + * TODO move this method to MysqlMigrationBuilder + * Only for MySQL and MariaDB * Given a column, compute its previous column name present in OpenAPI schema * @return ?string * `null` if column is added at last @@ -528,24 +533,26 @@ public function findPosition(ColumnSchema $column, bool $forDrop = false): ?stri if ($key > 0) { $prevColName = $columnNames[$key-1]; - if (!isset($columnNames[$key+1])) { // if new col is added at last then no need to add 'AFTER' SQL part. This is checked as if next column is present or not + if (!$forDrop && !isset($columnNames[$key+1])) { // if new col is added at last then no need to add 'AFTER' SQL part. This is checked as if next column is present or not return null; } - // in case of `down()` code of migration, putting 'after ' in add column statmenet is erroneous because may not exist. + // in case of `down()` code of migration, putting 'after ' in add column statement is erroneous because may not exist. // Example: From col a, b, c, d, if I drop c and d then their migration code will be generated like: // `up()` code // drop c // drop d // `down()` code - // add d after c (c does not exist! Error!) - // add c + // add d after c (c does not exist! Error!) (TODO check if c is present in newColumn) + // add c after b (can fix this issue) TODO if ($forDrop) { - return null; +// return null; // TODO this case can be fixed } - - return self::POS_AFTER . ' ' . $prevColName; + if (array_key_exists($prevColName, $this->newColumns)) { + return self::POS_AFTER . ' ' . $prevColName; + } + return null; // if no `$columnSchema` is found, previous column does not exist. This happens when 'after column' is not yet added in migration or added after currently undertaken column } elseif ($key === 0) { @@ -574,4 +581,20 @@ public function modifyDesiredInContextOfDesiredFromDb(ColumnSchema $desired, Col } $desired->dbType = $desiredFromDb->dbType; } + + // TODO + public function handleColumnsPositionsChanges(array $haveNames, array $wantNames) + { + $indices = []; + if ($haveNames !== $wantNames) { + foreach ($wantNames as $key => $name) { + if ($name !== $haveNames[$key]) { + $indices[] = $key; + } + } + } + for ($i = 0; $i < count($indices)/2; $i++) { + $this->migration->addUpCode($this->recordBuilder->alterColumn()); + } + } } diff --git a/src/lib/migrations/MigrationRecordBuilder.php b/src/lib/migrations/MigrationRecordBuilder.php index 98ee03b8..6794d6d0 100644 --- a/src/lib/migrations/MigrationRecordBuilder.php +++ b/src/lib/migrations/MigrationRecordBuilder.php @@ -112,7 +112,7 @@ public function addDbColumn(string $tableAlias, ColumnSchema $column, ?string $p /** * @throws \yii\base\InvalidConfigException */ - public function alterColumn(string $tableAlias, ColumnSchema $column):string + public function alterColumn(string $tableAlias, ColumnSchema $column, ?string $position = null):string # TODO { if (property_exists($column, 'xDbType') && is_string($column->xDbType) && !empty($column->xDbType)) { $converter = $this->columnToCode($tableAlias, $column, true, false, true, true); @@ -130,7 +130,12 @@ public function alterColumn(string $tableAlias, ColumnSchema $column):string /** * @throws \yii\base\InvalidConfigException */ - public function alterColumnType(string $tableAlias, ColumnSchema $column, bool $addUsing = false):string + public function alterColumnType( + string $tableAlias, + ColumnSchema $column, + bool $addUsing = false, + ?string $position = null + ):string # TODO { if (property_exists($column, 'xDbType') && is_string($column->xDbType) && !empty($column->xDbType)) { $converter = $this->columnToCode($tableAlias, $column, false, false, true, true); @@ -149,7 +154,12 @@ public function alterColumnType(string $tableAlias, ColumnSchema $column, bool $ * This method is only used in Pgsql * @throws \yii\base\InvalidConfigException */ - public function alterColumnTypeFromDb(string $tableAlias, ColumnSchema $column, bool $addUsing = false) :string + public function alterColumnTypeFromDb( + string $tableAlias, + ColumnSchema $column, + bool $addUsing = false, + ?string $position = null + ) :string # TODO { if (property_exists($column, 'xDbType') && is_string($column->xDbType) && !empty($column->xDbType)) { $converter = $this->columnToCode($tableAlias, $column, true, false, true, true); diff --git a/src/lib/migrations/MysqlMigrationBuilder.php b/src/lib/migrations/MysqlMigrationBuilder.php index 42354df3..9501bd46 100644 --- a/src/lib/migrations/MysqlMigrationBuilder.php +++ b/src/lib/migrations/MysqlMigrationBuilder.php @@ -26,14 +26,15 @@ final class MysqlMigrationBuilder extends BaseMigrationBuilder protected function buildColumnChanges(ColumnSchema $current, ColumnSchema $desired, array $changed):void { $newColumn = clone $current; + $position = $this->findPosition($desired); foreach ($changed as $attr) { $newColumn->$attr = $desired->$attr; } if (static::isEnum($newColumn)) { $newColumn->dbType = 'enum'; // TODO this is concretely not correct } - $this->migration->addUpCode($this->recordBuilder->alterColumn($this->model->getTableAlias(), $newColumn)) - ->addDownCode($this->recordBuilder->alterColumn($this->model->getTableAlias(), $current)); + $this->migration->addUpCode($this->recordBuilder->alterColumn($this->model->getTableAlias(), $newColumn, $position)) + ->addDownCode($this->recordBuilder->alterColumn($this->model->getTableAlias(), $current, $position)); } protected function compareColumns(ColumnSchema $current, ColumnSchema $desired):array @@ -159,4 +160,14 @@ public function modifyDesiredInContextOfCurrent(ColumnSchema $current, ColumnSch $desired->size = $current->size; } } + + /** + * TODO + * Check if order/position of column is changed + * @return void + */ + public function checkOrder() + { + + } } diff --git a/tests/specs/issue_fix/58_create_migration_for_column_position_change_if_a_field_position_is_changed_in_spec/index.yml b/tests/specs/issue_fix/58_create_migration_for_column_position_change_if_a_field_position_is_changed_in_spec/index.yml index 62612c44..1b2fe2ff 100644 --- a/tests/specs/issue_fix/58_create_migration_for_column_position_change_if_a_field_position_is_changed_in_spec/index.yml +++ b/tests/specs/issue_fix/58_create_migration_for_column_position_change_if_a_field_position_is_changed_in_spec/index.yml @@ -11,13 +11,13 @@ components: properties: id: type: integer - name: - type: string - description: desc - # colour: - # type: string - description: - type: string +# name: # TODO +# type: string +# description: desc +# colour: +# type: string +# description: +# type: string paths: '/': diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index 341668ca..2da7008b 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -384,7 +384,7 @@ private function createTableFor58CreateMigrationForColumnPositionChangeIfAFieldP Yii::$app->db->createCommand()->createTable('{{%fruits}}', [ 'id' => 'pk', 'description' => 'text', - 'name' => 'varchar(255) COMMENT "some-comment"', + 'name' => 'text', ])->execute(); } From d5c2c2800380b78e5d96fc920b3ef62fc997e018 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Fri, 4 Oct 2024 17:26:52 +0530 Subject: [PATCH 240/358] Handle column position in case of dropping a column (in down code -> add column) (for one or more columns) + Fix failing tests --- .../m200000_000004_change_table_v2_users.php | 2 +- .../m200000_000005_change_table_v2_comments.php | 2 +- .../m200000_000004_change_table_v2_users.php | 2 +- .../m200000_000005_change_table_v2_comments.php | 2 +- .../m200000_000000_change_table_column_name_changes.php | 2 +- .../m200000_000000_change_table_column_name_changes.php | 2 +- .../m200000_000001_change_table_newcolumns.php | 2 +- .../m200000_000001_change_table_newcolumns.php | 2 +- 8 files changed, 8 insertions(+), 8 deletions(-) diff --git a/tests/specs/blog_v2/migrations_maria_db/m200000_000004_change_table_v2_users.php b/tests/specs/blog_v2/migrations_maria_db/m200000_000004_change_table_v2_users.php index bf1c82fd..1231f6db 100644 --- a/tests/specs/blog_v2/migrations_maria_db/m200000_000004_change_table_v2_users.php +++ b/tests/specs/blog_v2/migrations_maria_db/m200000_000004_change_table_v2_users.php @@ -25,7 +25,7 @@ public function down() $this->alterColumn('{{%v2_users}}', 'created_at', $this->timestamp()->null()->defaultExpression("current_timestamp()")); $this->alterColumn('{{%v2_users}}', 'role', $this->string(20)->null()->defaultValue('reader')); $this->alterColumn('{{%v2_users}}', 'email', $this->string(200)->notNull()); - $this->addColumn('{{%v2_users}}', 'username', $this->string(200)->notNull()); + $this->addColumn('{{%v2_users}}', 'username', $this->string(200)->notNull()->after('id')); $this->dropColumn('{{%v2_users}}', 'login'); } } diff --git a/tests/specs/blog_v2/migrations_maria_db/m200000_000005_change_table_v2_comments.php b/tests/specs/blog_v2/migrations_maria_db/m200000_000005_change_table_v2_comments.php index 75553729..ead3128c 100644 --- a/tests/specs/blog_v2/migrations_maria_db/m200000_000005_change_table_v2_comments.php +++ b/tests/specs/blog_v2/migrations_maria_db/m200000_000005_change_table_v2_comments.php @@ -25,7 +25,7 @@ public function down() $this->alterColumn('{{%v2_comments}}', 'created_at', $this->integer(11)->notNull()); $this->alterColumn('{{%v2_comments}}', 'meta_data', 'json NOT NULL DEFAULT \'[]\''); $this->alterColumn('{{%v2_comments}}', 'message', 'json NOT NULL DEFAULT \'[]\''); - $this->addColumn('{{%v2_comments}}', 'author_id', $this->integer(11)->notNull()); + $this->addColumn('{{%v2_comments}}', 'author_id', $this->integer(11)->notNull()->after('post_id')); $this->dropColumn('{{%v2_comments}}', 'user_id'); $this->addForeignKey('fk_v2_comments_author_id_v2_users_id', '{{%v2_comments}}', 'id', 'v2_users', 'author_id'); $this->addForeignKey('fk_v2_comments_post_id_v2_posts_uid', '{{%v2_comments}}', 'uid', 'v2_posts', 'post_id'); diff --git a/tests/specs/blog_v2/migrations_mysql_db/m200000_000004_change_table_v2_users.php b/tests/specs/blog_v2/migrations_mysql_db/m200000_000004_change_table_v2_users.php index b7a1f5e3..412d6ade 100644 --- a/tests/specs/blog_v2/migrations_mysql_db/m200000_000004_change_table_v2_users.php +++ b/tests/specs/blog_v2/migrations_mysql_db/m200000_000004_change_table_v2_users.php @@ -25,7 +25,7 @@ public function down() $this->alterColumn('{{%v2_users}}', 'created_at', $this->timestamp()->null()->defaultExpression("CURRENT_TIMESTAMP")); $this->alterColumn('{{%v2_users}}', 'role', $this->string(20)->null()->defaultValue('reader')); $this->alterColumn('{{%v2_users}}', 'email', $this->string(200)->notNull()); - $this->addColumn('{{%v2_users}}', 'username', $this->string(200)->notNull()); + $this->addColumn('{{%v2_users}}', 'username', $this->string(200)->notNull()->after('id')); $this->dropColumn('{{%v2_users}}', 'login'); } } diff --git a/tests/specs/blog_v2/migrations_mysql_db/m200000_000005_change_table_v2_comments.php b/tests/specs/blog_v2/migrations_mysql_db/m200000_000005_change_table_v2_comments.php index 5861542c..497550fc 100644 --- a/tests/specs/blog_v2/migrations_mysql_db/m200000_000005_change_table_v2_comments.php +++ b/tests/specs/blog_v2/migrations_mysql_db/m200000_000005_change_table_v2_comments.php @@ -25,7 +25,7 @@ public function down() $this->alterColumn('{{%v2_comments}}', 'created_at', $this->integer()->notNull()); $this->alterColumn('{{%v2_comments}}', 'meta_data', 'json NOT NULL'); $this->alterColumn('{{%v2_comments}}', 'message', 'json NOT NULL'); - $this->addColumn('{{%v2_comments}}', 'author_id', $this->integer()->notNull()); + $this->addColumn('{{%v2_comments}}', 'author_id', $this->integer()->notNull()->after('post_id')); $this->dropColumn('{{%v2_comments}}', 'user_id'); $this->addForeignKey('fk_v2_comments_author_id_v2_users_id', '{{%v2_comments}}', 'id', 'v2_users', 'author_id'); $this->addForeignKey('fk_v2_comments_post_id_v2_posts_uid', '{{%v2_comments}}', 'uid', 'v2_posts', 'post_id'); diff --git a/tests/specs/change_column_name/maria/app/migrations_maria_db/m200000_000000_change_table_column_name_changes.php b/tests/specs/change_column_name/maria/app/migrations_maria_db/m200000_000000_change_table_column_name_changes.php index 1a75dbd3..199c7fb1 100644 --- a/tests/specs/change_column_name/maria/app/migrations_maria_db/m200000_000000_change_table_column_name_changes.php +++ b/tests/specs/change_column_name/maria/app/migrations_maria_db/m200000_000000_change_table_column_name_changes.php @@ -13,7 +13,7 @@ public function up() public function down() { - $this->addColumn('{{%column_name_changes}}', 'updated_at', $this->datetime()->notNull()); + $this->addColumn('{{%column_name_changes}}', 'updated_at', $this->datetime()->notNull()->after('name')); $this->dropColumn('{{%column_name_changes}}', 'updated_at_2'); } } diff --git a/tests/specs/change_column_name/mysql/app/migrations_mysql_db/m200000_000000_change_table_column_name_changes.php b/tests/specs/change_column_name/mysql/app/migrations_mysql_db/m200000_000000_change_table_column_name_changes.php index 1a75dbd3..199c7fb1 100644 --- a/tests/specs/change_column_name/mysql/app/migrations_mysql_db/m200000_000000_change_table_column_name_changes.php +++ b/tests/specs/change_column_name/mysql/app/migrations_mysql_db/m200000_000000_change_table_column_name_changes.php @@ -13,7 +13,7 @@ public function up() public function down() { - $this->addColumn('{{%column_name_changes}}', 'updated_at', $this->datetime()->notNull()); + $this->addColumn('{{%column_name_changes}}', 'updated_at', $this->datetime()->notNull()->after('name')); $this->dropColumn('{{%column_name_changes}}', 'updated_at_2'); } } diff --git a/tests/specs/enum/new_column/maria/app/migrations_maria_db/m200000_000001_change_table_newcolumns.php b/tests/specs/enum/new_column/maria/app/migrations_maria_db/m200000_000001_change_table_newcolumns.php index 78f6b2e5..b8750ddd 100644 --- a/tests/specs/enum/new_column/maria/app/migrations_maria_db/m200000_000001_change_table_newcolumns.php +++ b/tests/specs/enum/new_column/maria/app/migrations_maria_db/m200000_000001_change_table_newcolumns.php @@ -14,7 +14,7 @@ public function up() public function down() { - $this->addColumn('{{%newcolumns}}', 'delete_col', 'enum("FOUR", "FIVE", "SIX") NULL DEFAULT NULL'); + $this->addColumn('{{%newcolumns}}', 'delete_col', 'enum("FOUR", "FIVE", "SIX") NULL DEFAULT NULL AFTER id'); $this->dropColumn('{{%newcolumns}}', 'new_column_x'); $this->dropColumn('{{%newcolumns}}', 'new_column'); } diff --git a/tests/specs/enum/new_column/mysql/app/migrations_mysql_db/m200000_000001_change_table_newcolumns.php b/tests/specs/enum/new_column/mysql/app/migrations_mysql_db/m200000_000001_change_table_newcolumns.php index 78f6b2e5..b8750ddd 100644 --- a/tests/specs/enum/new_column/mysql/app/migrations_mysql_db/m200000_000001_change_table_newcolumns.php +++ b/tests/specs/enum/new_column/mysql/app/migrations_mysql_db/m200000_000001_change_table_newcolumns.php @@ -14,7 +14,7 @@ public function up() public function down() { - $this->addColumn('{{%newcolumns}}', 'delete_col', 'enum("FOUR", "FIVE", "SIX") NULL DEFAULT NULL'); + $this->addColumn('{{%newcolumns}}', 'delete_col', 'enum("FOUR", "FIVE", "SIX") NULL DEFAULT NULL AFTER id'); $this->dropColumn('{{%newcolumns}}', 'new_column_x'); $this->dropColumn('{{%newcolumns}}', 'new_column'); } From 1516b127394fa730467786c70470f45d94404773 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Fri, 4 Oct 2024 17:27:10 +0530 Subject: [PATCH 241/358] Fix style --- src/generator/default/dbmodel.php | 8 ++++---- src/lib/migrations/MysqlMigrationBuilder.php | 1 - 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/src/generator/default/dbmodel.php b/src/generator/default/dbmodel.php index 17fa4a84..a3d269b6 100644 --- a/src/generator/default/dbmodel.php +++ b/src/generator/default/dbmodel.php @@ -49,8 +49,8 @@ */ abstract class getClassName() ?> extends \yii\db\ActiveRecord { -getScenarios()): -foreach($scenarios as $scenario): ?> +getScenarios()): +foreach ($scenarios as $scenario): ?> /** * @@ -76,7 +76,7 @@ public static function tableName() { return getTableAlias()) ?>; } - + /** * Automatically generated scenarios from the model 'x-scenarios'. @@ -92,7 +92,7 @@ public function scenarios() $default = parent::scenarios()[self::SCENARIO_DEFAULT]; return [ - + self:: => $default, /** diff --git a/src/lib/migrations/MysqlMigrationBuilder.php b/src/lib/migrations/MysqlMigrationBuilder.php index 9501bd46..ad6c96be 100644 --- a/src/lib/migrations/MysqlMigrationBuilder.php +++ b/src/lib/migrations/MysqlMigrationBuilder.php @@ -168,6 +168,5 @@ public function modifyDesiredInContextOfCurrent(ColumnSchema $current, ColumnSch */ public function checkOrder() { - } } From 3a716198fb3122698c61992a19f6e7488fa80e5c Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Fri, 4 Oct 2024 19:02:59 +0530 Subject: [PATCH 242/358] Add more tests --- tests/unit/IssueFixTest.php | 82 +++++++++++++++++++++++++++++++++++++ 1 file changed, 82 insertions(+) diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index 2da7008b..3fd39b92 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -392,4 +392,86 @@ private function deleteTableFor58CreateMigrationForColumnPositionChangeIfAFieldP { Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%fruits}}')->execute(); } + + public function test58DeleteLastCol() + { + $deleteTable = function () { + Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%fruits}}')->execute(); + }; + $createTable = function () { + Yii::$app->db->createCommand()->createTable('{{%fruits}}', [ + 'id' => 'pk', + 'description' => 'text not null', + 'name' => 'text not null', + ])->execute(); + }; + $schema = << 'data://text/plain;base64,'.base64_encode($schema), + 'generateUrls' => false, + 'generateModels' => false, + 'generateControllers' => false, + 'generateMigrations' => true, + 'generateModelFaker' => false, + ]; + $tmpConfigFile = Yii::getAlias("@runtime")."/tmp-config.php"; + file_put_contents($tmpConfigFile, 'dropColumn('{{%fruits}}', 'name'); + } + + public function down() + { + $this->addColumn('{{%fruits}}', 'name', $this->text()->notNull()->after('description')); + } +} + +PHP; + + foreach (['Mysql', 'Mariadb'] as $db) { + $this->{"changeDbTo$db"}(); + $deleteTable(); + $createTable(); + + $dbStr = str_replace('db', '', strtolower($db)); + $this->runGenerator($tmpConfigFile, $dbStr); + $this->runActualMigrations($dbStr, 1); + $actual = file_get_contents(Yii::getAlias('@app').'/migrations_'.$dbStr.'_db/m200000_000000_change_table_fruits.php'); + $this->assertSame($expected, $actual); + + $deleteTable(); + } + FileHelper::unlink($tmpConfigFile); + } } From dae990b0cd08b1f4ee3d0657601be2f8f541b2fc Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Fri, 4 Oct 2024 19:27:50 +0530 Subject: [PATCH 243/358] Add more tests 2 --- tests/unit/IssueFixTest.php | 286 ++++++++++++++++++++++++++++++++---- 1 file changed, 259 insertions(+), 27 deletions(-) diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index 3fd39b92..e8b5d1c4 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -393,7 +393,7 @@ private function deleteTableFor58CreateMigrationForColumnPositionChangeIfAFieldP Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%fruits}}')->execute(); } - public function test58DeleteLastCol() + private function for58($schema, $expected) { $deleteTable = function () { Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%fruits}}')->execute(); @@ -401,10 +401,42 @@ public function test58DeleteLastCol() $createTable = function () { Yii::$app->db->createCommand()->createTable('{{%fruits}}', [ 'id' => 'pk', - 'description' => 'text not null', 'name' => 'text not null', + 'description' => 'text not null', + 'colour' => 'text not null', + 'size' => 'text not null', ])->execute(); }; + + $config = [ + 'openApiPath' => 'data://text/plain;base64,'.base64_encode($schema), + 'generateUrls' => false, + 'generateModels' => false, + 'generateControllers' => false, + 'generateMigrations' => true, + 'generateModelFaker' => false, + ]; + $tmpConfigFile = Yii::getAlias("@runtime")."/tmp-config.php"; + file_put_contents($tmpConfigFile, '{"changeDbTo$db"}(); + $deleteTable(); + $createTable(); + + $dbStr = str_replace('db', '', strtolower($db)); + $this->runGenerator($tmpConfigFile, $dbStr); + $this->runActualMigrations($dbStr, 1); + $actual = file_get_contents(Yii::getAlias('@app').'/migrations_'.$dbStr.'_db/m200000_000000_change_table_fruits.php'); + $this->assertSame($expected, $actual); + + $deleteTable(); + } + FileHelper::unlink($tmpConfigFile); + } + + public function test58DeleteLastCol() + { $schema = << 'data://text/plain;base64,'.base64_encode($schema), - 'generateUrls' => false, - 'generateModels' => false, - 'generateControllers' => false, - 'generateMigrations' => true, - 'generateModelFaker' => false, - ]; - $tmpConfigFile = Yii::getAlias("@runtime")."/tmp-config.php"; - file_put_contents($tmpConfigFile, 'dropColumn('{{%fruits}}', 'name'); + $this->dropColumn('{{%fruits}}', 'size'); } public function down() { - $this->addColumn('{{%fruits}}', 'name', $this->text()->notNull()->after('description')); + $this->addColumn('{{%fruits}}', 'size', $this->text()->notNull()->after('colour')); } } PHP; - foreach (['Mysql', 'Mariadb'] as $db) { - $this->{"changeDbTo$db"}(); - $deleteTable(); - $createTable(); + $this->for58($schema, $expected); + } - $dbStr = str_replace('db', '', strtolower($db)); - $this->runGenerator($tmpConfigFile, $dbStr); - $this->runActualMigrations($dbStr, 1); - $actual = file_get_contents(Yii::getAlias('@app').'/migrations_'.$dbStr.'_db/m200000_000000_change_table_fruits.php'); - $this->assertSame($expected, $actual); - - $deleteTable(); - } - FileHelper::unlink($tmpConfigFile); + public function test58DeleteLast2ConsecutiveCol() + { + $schema = <<dropColumn('{{%fruits}}', 'colour'); + $this->dropColumn('{{%fruits}}', 'size'); + } + + public function down() + { + $this->addColumn('{{%fruits}}', 'size', $this->text()->notNull()); + $this->addColumn('{{%fruits}}', 'colour', $this->text()->notNull()->after('description')); + } +} + +PHP; + + $this->for58($schema, $expected); + } + + public function test58DeleteAColInBetween() + { + $schema = <<dropColumn('{{%fruits}}', 'description'); + } + + public function down() + { + $this->addColumn('{{%fruits}}', 'description', $this->text()->notNull()->after('name')); + } +} + +PHP; + + $this->for58($schema, $expected); + } + + public function test58Delete2ConsecutiveColInBetween() + { + $schema = <<dropColumn('{{%fruits}}', 'description'); + $this->dropColumn('{{%fruits}}', 'colour'); + } + + public function down() + { + $this->addColumn('{{%fruits}}', 'colour', $this->text()->notNull()); + $this->addColumn('{{%fruits}}', 'description', $this->text()->notNull()->after('name')); + } +} + +PHP; + + $this->for58($schema, $expected); + } + + public function test58Delete2NonConsecutiveColInBetween() + { + $schema = <<dropColumn('{{%fruits}}', 'name'); + $this->dropColumn('{{%fruits}}', 'colour'); + } + + public function down() + { + $this->addColumn('{{%fruits}}', 'colour', $this->text()->notNull()->after('description')); + $this->addColumn('{{%fruits}}', 'name', $this->text()->notNull()->after('id')); + } +} + +PHP; + + $this->for58($schema, $expected); } } From 4f3efe94811470c593136e61a2b4fe94e512cd3a Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Sat, 5 Oct 2024 20:19:39 +0530 Subject: [PATCH 244/358] Refactor --- src/lib/migrations/BaseMigrationBuilder.php | 70 +++---------------- src/lib/migrations/MysqlMigrationBuilder.php | 53 +++++++++++++- .../migrations/PostgresMigrationBuilder.php | 16 ++++- 3 files changed, 76 insertions(+), 63 deletions(-) diff --git a/src/lib/migrations/BaseMigrationBuilder.php b/src/lib/migrations/BaseMigrationBuilder.php index ff0c49fe..7a1b0a32 100644 --- a/src/lib/migrations/BaseMigrationBuilder.php +++ b/src/lib/migrations/BaseMigrationBuilder.php @@ -516,51 +516,6 @@ public function isDefaultValueChanged( return false; } - /** - * TODO move this method to MysqlMigrationBuilder - * Only for MySQL and MariaDB - * Given a column, compute its previous column name present in OpenAPI schema - * @return ?string - * `null` if column is added at last - * 'FIRST' if column is added at first position - * 'AFTER ' if column is added in between e.g. if 'email' is added after 'username' then 'AFTER username' - */ - public function findPosition(ColumnSchema $column, bool $forDrop = false): ?string - { - $columnNames = array_keys($forDrop ? $this->tableSchema->columns : $this->newColumns); - - $key = array_search($column->name, $columnNames); - if ($key > 0) { - $prevColName = $columnNames[$key-1]; - - if (!$forDrop && !isset($columnNames[$key+1])) { // if new col is added at last then no need to add 'AFTER' SQL part. This is checked as if next column is present or not - return null; - } - - // in case of `down()` code of migration, putting 'after ' in add column statement is erroneous because may not exist. - // Example: From col a, b, c, d, if I drop c and d then their migration code will be generated like: - // `up()` code - // drop c - // drop d - // `down()` code - // add d after c (c does not exist! Error!) (TODO check if c is present in newColumn) - // add c after b (can fix this issue) TODO - if ($forDrop) { -// return null; // TODO this case can be fixed - } - - if (array_key_exists($prevColName, $this->newColumns)) { - return self::POS_AFTER . ' ' . $prevColName; - } - return null; - - // if no `$columnSchema` is found, previous column does not exist. This happens when 'after column' is not yet added in migration or added after currently undertaken column - } elseif ($key === 0) { - return self::POS_FIRST; - } - - return null; - } public function modifyDesiredFromDbInContextOfDesired(ColumnSchema $desired, ColumnSchema $desiredFromDb): void { @@ -582,19 +537,14 @@ public function modifyDesiredInContextOfDesiredFromDb(ColumnSchema $desired, Col $desired->dbType = $desiredFromDb->dbType; } - // TODO - public function handleColumnsPositionsChanges(array $haveNames, array $wantNames) - { - $indices = []; - if ($haveNames !== $wantNames) { - foreach ($wantNames as $key => $name) { - if ($name !== $haveNames[$key]) { - $indices[] = $key; - } - } - } - for ($i = 0; $i < count($indices)/2; $i++) { - $this->migration->addUpCode($this->recordBuilder->alterColumn()); - } - } + /** + * TODO docs + */ + abstract public function handleColumnsPositionsChanges(array $haveNames, array $wantNames); + + + /** + * TODO docs + */ + abstract public function findPosition(ColumnSchema $column, bool $forDrop = false): ?string; } diff --git a/src/lib/migrations/MysqlMigrationBuilder.php b/src/lib/migrations/MysqlMigrationBuilder.php index ad6c96be..2027da14 100644 --- a/src/lib/migrations/MysqlMigrationBuilder.php +++ b/src/lib/migrations/MysqlMigrationBuilder.php @@ -14,9 +14,7 @@ use yii\db\ColumnSchema; use yii\db\IndexConstraint; use yii\db\Schema; -use \Yii; use yii\helpers\ArrayHelper; -use yii\helpers\VarDumper; final class MysqlMigrationBuilder extends BaseMigrationBuilder { @@ -169,4 +167,55 @@ public function modifyDesiredInContextOfCurrent(ColumnSchema $current, ColumnSch public function checkOrder() { } + + // TODO + public function handleColumnsPositionsChanges(array $haveNames, array $wantNames) + { + $indices = []; + if ($haveNames !== $wantNames) { + foreach ($wantNames as $key => $name) { + if ($name !== $haveNames[$key]) { + $indices[] = $key; + } + } + } + for ($i = 0; $i < count($indices) / 2; $i++) { + $this->migration->addUpCode($this->recordBuilder->alterColumn()); + } + } + + + /** + * TODO move this method to MysqlMigrationBuilder + * Only for MySQL and MariaDB + * Given a column, compute its previous column name present in OpenAPI schema + * @return ?string + * `null` if column is added at last + * 'FIRST' if column is added at first position + * 'AFTER ' if column is added in between e.g. if 'email' is added after 'username' then 'AFTER username' + */ + public function findPosition(ColumnSchema $column, bool $forDrop = false): ?string + { + $columnNames = array_keys($forDrop ? $this->tableSchema->columns : $this->newColumns); + + $key = array_search($column->name, $columnNames); + if ($key > 0) { + $prevColName = $columnNames[$key - 1]; + + if (!$forDrop && !isset($columnNames[$key + 1])) { // if new col is added at last then no need to add 'AFTER' SQL part. This is checked as if next column is present or not + return null; + } + + if (array_key_exists($prevColName, $this->newColumns)) { + return self::POS_AFTER . ' ' . $prevColName; + } + return null; + + // if no `$columnSchema` is found, previous column does not exist. This happens when 'after column' is not yet added in migration or added after currently undertaken column + } elseif ($key === 0) { + return self::POS_FIRST; + } + + return null; + } } diff --git a/src/lib/migrations/PostgresMigrationBuilder.php b/src/lib/migrations/PostgresMigrationBuilder.php index b8c9324d..9810cbf7 100644 --- a/src/lib/migrations/PostgresMigrationBuilder.php +++ b/src/lib/migrations/PostgresMigrationBuilder.php @@ -9,7 +9,6 @@ use cebe\yii2openapi\lib\items\DbIndex; use yii\db\ColumnSchema; -use yii\helpers\VarDumper; use yii\helpers\ArrayHelper; final class PostgresMigrationBuilder extends BaseMigrationBuilder @@ -248,4 +247,19 @@ public function modifyDesiredInContextOfCurrent(ColumnSchema $current, ColumnSch $desired->size = $current->size; } } + + /** + * {@inheritDoc} + */ + public function handleColumnsPositionsChanges(array $haveNames, array $wantNames) + { + } + + + /** + * {@inheritDoc} + */ + public function findPosition(ColumnSchema $column, bool $forDrop = false): ?string + { + } } From 53bbf083cb4c063e5f2c012e2cecfcf8ab310bc5 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Sun, 6 Oct 2024 21:04:54 +0530 Subject: [PATCH 245/358] Implementation in progress + add more tests --- src/lib/migrations/BaseMigrationBuilder.php | 9 +- src/lib/migrations/MigrationRecordBuilder.php | 4 +- src/lib/migrations/MysqlMigrationBuilder.php | 81 +++-- .../index.yml | 11 +- tests/unit/IssueFixTest.php | 342 +++++++++++++++++- 5 files changed, 400 insertions(+), 47 deletions(-) diff --git a/src/lib/migrations/BaseMigrationBuilder.php b/src/lib/migrations/BaseMigrationBuilder.php index 7a1b0a32..6d7a413f 100644 --- a/src/lib/migrations/BaseMigrationBuilder.php +++ b/src/lib/migrations/BaseMigrationBuilder.php @@ -544,7 +544,14 @@ abstract public function handleColumnsPositionsChanges(array $haveNames, array $ /** - * TODO docs + * Only for MySQL and MariaDB + * Given a column, compute its previous column name present in OpenAPI schema + * @param ColumnSchema $column + * @param bool $forDrop + * @return ?string + * `null` if column is added at last + * 'FIRST' if column is added at first position + * 'AFTER ' if column is added in between e.g. if 'email' is added after 'username' then 'AFTER username' */ abstract public function findPosition(ColumnSchema $column, bool $forDrop = false): ?string; } diff --git a/src/lib/migrations/MigrationRecordBuilder.php b/src/lib/migrations/MigrationRecordBuilder.php index 6794d6d0..0ce9bf1b 100644 --- a/src/lib/migrations/MigrationRecordBuilder.php +++ b/src/lib/migrations/MigrationRecordBuilder.php @@ -115,7 +115,7 @@ public function addDbColumn(string $tableAlias, ColumnSchema $column, ?string $p public function alterColumn(string $tableAlias, ColumnSchema $column, ?string $position = null):string # TODO { if (property_exists($column, 'xDbType') && is_string($column->xDbType) && !empty($column->xDbType)) { - $converter = $this->columnToCode($tableAlias, $column, true, false, true, true); + $converter = $this->columnToCode($tableAlias, $column, true, false, true, true, $position); return sprintf( ApiGenerator::isPostgres() ? self::ALTER_COLUMN_RAW_PGSQL : self::ALTER_COLUMN_RAW, $tableAlias, @@ -123,7 +123,7 @@ public function alterColumn(string $tableAlias, ColumnSchema $column, ?string $p ColumnToCode::escapeQuotes($converter->getCode()) ); } - $converter = $this->columnToCode($tableAlias, $column, true); + $converter = $this->columnToCode($tableAlias, $column, true, false, false, false, $position); return sprintf(self::ALTER_COLUMN, $tableAlias, $column->name, $converter->getCode(true)); } diff --git a/src/lib/migrations/MysqlMigrationBuilder.php b/src/lib/migrations/MysqlMigrationBuilder.php index 2027da14..53b99ba4 100644 --- a/src/lib/migrations/MysqlMigrationBuilder.php +++ b/src/lib/migrations/MysqlMigrationBuilder.php @@ -23,16 +23,32 @@ final class MysqlMigrationBuilder extends BaseMigrationBuilder */ protected function buildColumnChanges(ColumnSchema $current, ColumnSchema $desired, array $changed):void { + $positionCurrent = $positionDesired = null; + if (in_array('position', $changed, true)) { + $positionCurrent = $this->findPosition($current, true); + $positionDesired = $this->findPosition($desired); + $key = array_search('position', $changed, true); + if ($key !== false) { + unset($changed[$key]); + } + } $newColumn = clone $current; - $position = $this->findPosition($desired); +// $positionCurrent = $this->findPosition($desired, true); +// $positionDesired = $this->findPosition($desired); +// if ($positionCurrent === $positionDesired) { +// $positionCurrent = $positionDesired = null; +// } # else { +// $position = $positionDesired; +// $newColumn->position = $position; +// } foreach ($changed as $attr) { $newColumn->$attr = $desired->$attr; } if (static::isEnum($newColumn)) { $newColumn->dbType = 'enum'; // TODO this is concretely not correct } - $this->migration->addUpCode($this->recordBuilder->alterColumn($this->model->getTableAlias(), $newColumn, $position)) - ->addDownCode($this->recordBuilder->alterColumn($this->model->getTableAlias(), $current, $position)); + $this->migration->addUpCode($this->recordBuilder->alterColumn($this->model->getTableAlias(), $newColumn, $positionDesired)) + ->addDownCode($this->recordBuilder->alterColumn($this->model->getTableAlias(), $current, $positionCurrent)); } protected function compareColumns(ColumnSchema $current, ColumnSchema $desired):array @@ -67,6 +83,14 @@ protected function compareColumns(ColumnSchema $current, ColumnSchema $desired): } } } + + $positionCurrent = $this->findPosition($desired, true); + $positionDesired = $this->findPosition($desired); + + if ($positionCurrent !== $positionDesired) { + $changedAttributes[] = 'position'; + } + return $changedAttributes; } @@ -168,31 +192,8 @@ public function checkOrder() { } - // TODO - public function handleColumnsPositionsChanges(array $haveNames, array $wantNames) - { - $indices = []; - if ($haveNames !== $wantNames) { - foreach ($wantNames as $key => $name) { - if ($name !== $haveNames[$key]) { - $indices[] = $key; - } - } - } - for ($i = 0; $i < count($indices) / 2; $i++) { - $this->migration->addUpCode($this->recordBuilder->alterColumn()); - } - } - - /** - * TODO move this method to MysqlMigrationBuilder - * Only for MySQL and MariaDB - * Given a column, compute its previous column name present in OpenAPI schema - * @return ?string - * `null` if column is added at last - * 'FIRST' if column is added at first position - * 'AFTER ' if column is added in between e.g. if 'email' is added after 'username' then 'AFTER username' + * {@inheritDoc} */ public function findPosition(ColumnSchema $column, bool $forDrop = false): ?string { @@ -218,4 +219,30 @@ public function findPosition(ColumnSchema $column, bool $forDrop = false): ?stri return null; } + + + // TODO + public function handleColumnsPositionsChanges(array $haveNames, array $wantNames) + { + $indices = []; + if ($haveNames !== $wantNames) { + foreach ($wantNames as $key => $name) { + if ($name !== $haveNames[$key]) { + $indices[] = $key; + } + } + } + for ($i = 0; $i < count($indices) / 2; $i++) { + $this->migration->addUpCode($this->recordBuilder->alterColumn( + $this->model->getTableAlias(), + $this->newColumns[$wantNames[$indices[$i]]], + $this->findPosition($this->newColumns[$wantNames[$indices[$i]]]) + ))->addDownCode($this->recordBuilder->alterColumn( + $this->model->getTableAlias(), + $this->tableSchema->columns[$wantNames[$indices[$i]]], + $this->findPosition($this->tableSchema->columns[$wantNames[$indices[$i]]], true) + )); + } +// $this->migration->addUpCode($this->recordBuilder->dropTable($this->model->getTableAlias())); + } } diff --git a/tests/specs/issue_fix/58_create_migration_for_column_position_change_if_a_field_position_is_changed_in_spec/index.yml b/tests/specs/issue_fix/58_create_migration_for_column_position_change_if_a_field_position_is_changed_in_spec/index.yml index 1b2fe2ff..3c9a1e63 100644 --- a/tests/specs/issue_fix/58_create_migration_for_column_position_change_if_a_field_position_is_changed_in_spec/index.yml +++ b/tests/specs/issue_fix/58_create_migration_for_column_position_change_if_a_field_position_is_changed_in_spec/index.yml @@ -11,13 +11,10 @@ components: properties: id: type: integer -# name: # TODO -# type: string -# description: desc -# colour: -# type: string -# description: -# type: string + name: + type: string + description: + type: string paths: '/': diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index e8b5d1c4..beae7d8b 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -362,10 +362,10 @@ public function test158BugGiiapiGeneratedRulesEnumWithTrim() } // https://github.com/php-openapi/yii2-openapi/issues/58 - public function test58CreateMigrationForColumnPositionChangeIfAFieldPositionIsChangedInSpec() + public function test58CreateMigrationForColumnPositionChange() { - $this->deleteTableFor58CreateMigrationForColumnPositionChangeIfAFieldPositionIsChangedInSpec(); - $this->createTableFor58CreateMigrationForColumnPositionChangeIfAFieldPositionIsChangedInSpec(); + $this->deleteTableFor58CreateMigrationForColumnPositionChange(); + $this->createTableFor58CreateMigrationForColumnPositionChange(); $testFile = Yii::getAlias("@specs/issue_fix/58_create_migration_for_column_position_change_if_a_field_position_is_changed_in_spec/index.php"); $this->runGenerator($testFile); @@ -376,10 +376,10 @@ public function test58CreateMigrationForColumnPositionChangeIfAFieldPositionIsCh // 'recursive' => true, // ]); // $this->checkFiles($actualFiles, $expectedFiles); - $this->deleteTableFor58CreateMigrationForColumnPositionChangeIfAFieldPositionIsChangedInSpec(); + $this->deleteTableFor58CreateMigrationForColumnPositionChange(); } - private function createTableFor58CreateMigrationForColumnPositionChangeIfAFieldPositionIsChangedInSpec() + private function createTableFor58CreateMigrationForColumnPositionChange() { Yii::$app->db->createCommand()->createTable('{{%fruits}}', [ 'id' => 'pk', @@ -388,7 +388,7 @@ private function createTableFor58CreateMigrationForColumnPositionChangeIfAFieldP ])->execute(); } - private function deleteTableFor58CreateMigrationForColumnPositionChangeIfAFieldPositionIsChangedInSpec() + private function deleteTableFor58CreateMigrationForColumnPositionChange() { Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%fruits}}')->execute(); } @@ -409,15 +409,15 @@ private function for58($schema, $expected) }; $config = [ - 'openApiPath' => 'data://text/plain;base64,'.base64_encode($schema), + 'openApiPath' => 'data://text/plain;base64,' . base64_encode($schema), 'generateUrls' => false, 'generateModels' => false, 'generateControllers' => false, 'generateMigrations' => true, 'generateModelFaker' => false, ]; - $tmpConfigFile = Yii::getAlias("@runtime")."/tmp-config.php"; - file_put_contents($tmpConfigFile, '{"changeDbTo$db"}(); @@ -427,7 +427,7 @@ private function for58($schema, $expected) $dbStr = str_replace('db', '', strtolower($db)); $this->runGenerator($tmpConfigFile, $dbStr); $this->runActualMigrations($dbStr, 1); - $actual = file_get_contents(Yii::getAlias('@app').'/migrations_'.$dbStr.'_db/m200000_000000_change_table_fruits.php'); + $actual = file_get_contents(Yii::getAlias('@app') . '/migrations_' . $dbStr . '_db/m200000_000000_change_table_fruits.php'); $this->assertSame($expected, $actual); $deleteTable(); @@ -702,6 +702,328 @@ public function down() } } +PHP; + + $this->for58($schema, $expected); + } + + // ------------ + public function test58AddAColAtLastPos() + { + // default position is last so no `AFTER` needed + $schema = <<addColumn('{{%fruits}}', 'weight', $this->text()->notNull()); + } + + public function down() + { + $this->dropColumn('{{%fruits}}', 'weight'); + } +} + +PHP; + + $this->for58($schema, $expected); + } + + public function test58Add2ConsecutiveColAtLastPos() + { + $schema = <<addColumn('{{%fruits}}', 'weight', $this->text()->notNull()->after('size')); + $this->addColumn('{{%fruits}}', 'location', $this->text()->notNull()); + } + + public function down() + { + $this->dropColumn('{{%fruits}}', 'location'); + $this->dropColumn('{{%fruits}}', 'weight'); + } +} + +PHP; + + $this->for58($schema, $expected); + } + + public function test58AddAColInBetween() + { + $schema = <<addColumn('{{%fruits}}', 'weight', $this->text()->notNull()->after('description')); + } + + public function down() + { + $this->dropColumn('{{%fruits}}', 'weight'); + } +} + +PHP; + + $this->for58($schema, $expected); + } + + public function test58Add2ConsecutiveColInBetween() + { + $schema = <<addColumn('{{%fruits}}', 'weight', $this->text()->notNull()->after('description')); + $this->addColumn('{{%fruits}}', 'location', $this->text()->notNull()->after('weight')); + } + + public function down() + { + $this->dropColumn('{{%fruits}}', 'location'); + $this->dropColumn('{{%fruits}}', 'weight'); + } +} + +PHP; + + $this->for58($schema, $expected); + } + + public function test58Add2NonConsecutiveColInBetween() + { + $schema = <<addColumn('{{%fruits}}', 'weight', $this->text()->notNull()->after('name')); + $this->addColumn('{{%fruits}}', 'location', $this->text()->notNull()->after('colour')); + } + + public function down() + { + $this->dropColumn('{{%fruits}}', 'location'); + $this->dropColumn('{{%fruits}}', 'weight'); + } +} + PHP; $this->for58($schema, $expected); From 832c102fd380245c434b7d34597bbeb9be938109 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Mon, 7 Oct 2024 18:11:16 +0530 Subject: [PATCH 246/358] Implement for many test cases --- src/db/ColumnSchema.php | 13 +++- src/lib/migrations/BaseMigrationBuilder.php | 1 + src/lib/migrations/MysqlMigrationBuilder.php | 73 ++++++++++++++++++- .../migrations/PostgresMigrationBuilder.php | 5 ++ 4 files changed, 86 insertions(+), 6 deletions(-) diff --git a/src/db/ColumnSchema.php b/src/db/ColumnSchema.php index c6725b10..6ce1cb3a 100644 --- a/src/db/ColumnSchema.php +++ b/src/db/ColumnSchema.php @@ -29,7 +29,16 @@ class ColumnSchema extends \yii\db\ColumnSchema /** * TODO * Used only for MySQL/MariaDB - * @var string|null + * @var array|null + * [ + * index => int + * after => ?string + * before => ?string + * ] + * If `before` is null then column is last */ - public ?string $position = null; + public ?array $fromPosition = null; + public ?array $toPosition = null; + + public bool $isPositionReallyChanged = false; } diff --git a/src/lib/migrations/BaseMigrationBuilder.php b/src/lib/migrations/BaseMigrationBuilder.php index 6d7a413f..0a0070e4 100644 --- a/src/lib/migrations/BaseMigrationBuilder.php +++ b/src/lib/migrations/BaseMigrationBuilder.php @@ -171,6 +171,7 @@ public function buildSecondary(?ManyToManyRelation $relation = null):MigrationMo { $this->migration = Yii::createObject(MigrationModel::class, [$this->model, false, $relation, []]); $this->newColumns = $relation->columnSchema ?? $this->model->attributesToColumnSchema(); + $this->setPositions(); $wantNames = array_keys($this->newColumns); $haveNames = $this->tableSchema->columnNames; $columnsForCreate = array_map( diff --git a/src/lib/migrations/MysqlMigrationBuilder.php b/src/lib/migrations/MysqlMigrationBuilder.php index 53b99ba4..1ac1a7b6 100644 --- a/src/lib/migrations/MysqlMigrationBuilder.php +++ b/src/lib/migrations/MysqlMigrationBuilder.php @@ -84,10 +84,10 @@ protected function compareColumns(ColumnSchema $current, ColumnSchema $desired): } } - $positionCurrent = $this->findPosition($desired, true); - $positionDesired = $this->findPosition($desired); - - if ($positionCurrent !== $positionDesired) { +// $positionCurrent = $this->findPosition($desired, true); +// $positionDesired = $this->findPosition($desired); +// if ($positionCurrent !== $positionDesired) { + if ($desired->isPositionReallyChanged) { $changedAttributes[] = 'position'; } @@ -245,4 +245,69 @@ public function handleColumnsPositionsChanges(array $haveNames, array $wantNames } // $this->migration->addUpCode($this->recordBuilder->dropTable($this->model->getTableAlias())); } + + public function setPositions() + { + $i = 0; + $haveColumns = $this->tableSchema->columns; + $onlyColumnNames = array_keys($this->newColumns); + foreach ($this->newColumns as $columnName => $column) { + /** @var \cebe\yii2openapi\db\ColumnSchema $column */ + $column->toPosition = [ + 'index' => $i + 1, + 'after' => $i === 0 ? null : $onlyColumnNames[$i - 1], + 'before' => $i === (count($onlyColumnNames) - 1) ? null : $onlyColumnNames[$i + 1], + ]; + + $haveNamesOnlyColNames = array_keys($haveColumns); + if (isset($haveColumns[$columnName])) { + $index = array_search($columnName, $haveNamesOnlyColNames) + 1; + $column->fromPosition = [ + 'index' => $index, + 'after' => $haveNamesOnlyColNames[$index - 2] ?? null, + 'before' => $haveNamesOnlyColNames[$index] ?? null, + ]; + } + + $i++; + } + + $takenIndices = []; + foreach ($this->newColumns as $columnName => $column) { + /** @var \cebe\yii2openapi\db\ColumnSchema $column */ + if (!$column->fromPosition || !$column->toPosition) { + continue; + } + if ( + is_int(array_search([$column->toPosition['index'], $column->fromPosition['index']], $takenIndices)) + ) { + continue; + } + if ($column->fromPosition === $column->toPosition) { + continue; + } + + if ($column->fromPosition['after'] === $column->toPosition['after']) { + continue; + } + + if ($column->fromPosition['before'] === $column->toPosition['before']) { + continue; + } +// if (!in_array($column->fromPosition['after'], $onlyColumnNames)) { +// continue; +// } +// if (!in_array($column->fromPosition['before'], $onlyColumnNames)) { +// continue; +// } + + if (!in_array($column->fromPosition['after'], $onlyColumnNames) && !in_array($column->fromPosition['before'], $onlyColumnNames)) { + continue; + } + + + $column->isPositionReallyChanged = true; + $takenIndices[] = [$column->fromPosition['index'], $column->toPosition['index']]; + } + } } diff --git a/src/lib/migrations/PostgresMigrationBuilder.php b/src/lib/migrations/PostgresMigrationBuilder.php index 9810cbf7..36a88c3e 100644 --- a/src/lib/migrations/PostgresMigrationBuilder.php +++ b/src/lib/migrations/PostgresMigrationBuilder.php @@ -260,6 +260,11 @@ public function handleColumnsPositionsChanges(array $haveNames, array $wantNames * {@inheritDoc} */ public function findPosition(ColumnSchema $column, bool $forDrop = false): ?string + { + return null; + } + + public function setPositions() { } } From b58bf2ef9fb6c5e8c82f4d8d5409e3200a3b5c37 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Mon, 7 Oct 2024 20:36:23 +0530 Subject: [PATCH 247/358] Resolve TODOs + add tests --- src/lib/migrations/MigrationRecordBuilder.php | 12 +- src/lib/migrations/MysqlMigrationBuilder.php | 8 -- .../index.php | 4 +- .../m200000_000000_change_table_fruits.php | 17 +++ tests/unit/IssueFixTest.php | 117 +++++++++++++++--- 5 files changed, 124 insertions(+), 34 deletions(-) create mode 100644 tests/specs/issue_fix/58_create_migration_for_column_position_change_if_a_field_position_is_changed_in_spec/mysql/migrations_mysql_db/m200000_000000_change_table_fruits.php diff --git a/src/lib/migrations/MigrationRecordBuilder.php b/src/lib/migrations/MigrationRecordBuilder.php index 0ce9bf1b..76107dfa 100644 --- a/src/lib/migrations/MigrationRecordBuilder.php +++ b/src/lib/migrations/MigrationRecordBuilder.php @@ -112,7 +112,7 @@ public function addDbColumn(string $tableAlias, ColumnSchema $column, ?string $p /** * @throws \yii\base\InvalidConfigException */ - public function alterColumn(string $tableAlias, ColumnSchema $column, ?string $position = null):string # TODO + public function alterColumn(string $tableAlias, ColumnSchema $column, ?string $position = null):string { if (property_exists($column, 'xDbType') && is_string($column->xDbType) && !empty($column->xDbType)) { $converter = $this->columnToCode($tableAlias, $column, true, false, true, true, $position); @@ -135,10 +135,10 @@ public function alterColumnType( ColumnSchema $column, bool $addUsing = false, ?string $position = null - ):string # TODO + ):string { if (property_exists($column, 'xDbType') && is_string($column->xDbType) && !empty($column->xDbType)) { - $converter = $this->columnToCode($tableAlias, $column, false, false, true, true); + $converter = $this->columnToCode($tableAlias, $column, false, false, true, true, $position); return sprintf( ApiGenerator::isPostgres() ? self::ALTER_COLUMN_RAW_PGSQL : self::ALTER_COLUMN_RAW, $tableAlias, @@ -146,7 +146,7 @@ public function alterColumnType( rtrim(ltrim($converter->getAlterExpression($addUsing), "'"), "'") ); } - $converter = $this->columnToCode($tableAlias, $column, false); + $converter = $this->columnToCode($tableAlias, $column, false, false, false, false, $position); return sprintf(self::ALTER_COLUMN, $tableAlias, $column->name, $converter->getAlterExpression($addUsing)); } @@ -162,7 +162,7 @@ public function alterColumnTypeFromDb( ) :string # TODO { if (property_exists($column, 'xDbType') && is_string($column->xDbType) && !empty($column->xDbType)) { - $converter = $this->columnToCode($tableAlias, $column, true, false, true, true); + $converter = $this->columnToCode($tableAlias, $column, true, false, true, true, $position); return sprintf( ApiGenerator::isPostgres() ? self::ALTER_COLUMN_RAW_PGSQL : self::ALTER_COLUMN_RAW, $tableAlias, @@ -170,7 +170,7 @@ public function alterColumnTypeFromDb( rtrim(ltrim($converter->getAlterExpression($addUsing), "'"), "'") ); } - $converter = $this->columnToCode($tableAlias, $column, true); + $converter = $this->columnToCode($tableAlias, $column, true, false, false, false, $position); return sprintf(self::ALTER_COLUMN, $tableAlias, $column->name, $converter->getAlterExpression($addUsing)); } diff --git a/src/lib/migrations/MysqlMigrationBuilder.php b/src/lib/migrations/MysqlMigrationBuilder.php index 1ac1a7b6..3044af3c 100644 --- a/src/lib/migrations/MysqlMigrationBuilder.php +++ b/src/lib/migrations/MysqlMigrationBuilder.php @@ -294,18 +294,10 @@ public function setPositions() if ($column->fromPosition['before'] === $column->toPosition['before']) { continue; } -// if (!in_array($column->fromPosition['after'], $onlyColumnNames)) { -// continue; -// } -// if (!in_array($column->fromPosition['before'], $onlyColumnNames)) { -// continue; -// } if (!in_array($column->fromPosition['after'], $onlyColumnNames) && !in_array($column->fromPosition['before'], $onlyColumnNames)) { continue; } - - $column->isPositionReallyChanged = true; $takenIndices[] = [$column->fromPosition['index'], $column->toPosition['index']]; } diff --git a/tests/specs/issue_fix/58_create_migration_for_column_position_change_if_a_field_position_is_changed_in_spec/index.php b/tests/specs/issue_fix/58_create_migration_for_column_position_change_if_a_field_position_is_changed_in_spec/index.php index 8ec860a4..5c16da25 100644 --- a/tests/specs/issue_fix/58_create_migration_for_column_position_change_if_a_field_position_is_changed_in_spec/index.php +++ b/tests/specs/issue_fix/58_create_migration_for_column_position_change_if_a_field_position_is_changed_in_spec/index.php @@ -3,11 +3,11 @@ return [ 'openApiPath' => '@specs/issue_fix/58_create_migration_for_column_position_change_if_a_field_position_is_changed_in_spec/index.yml', 'generateUrls' => false, - 'generateModels' => true, + 'generateModels' => false, 'excludeModels' => [ 'Error', ], 'generateControllers' => false, 'generateMigrations' => true, - 'generateModelFaker' => true, // `generateModels` must be `true` in order to use `generateModelFaker` as `true` + 'generateModelFaker' => false, // `generateModels` must be `true` in order to use `generateModelFaker` as `true` ]; diff --git a/tests/specs/issue_fix/58_create_migration_for_column_position_change_if_a_field_position_is_changed_in_spec/mysql/migrations_mysql_db/m200000_000000_change_table_fruits.php b/tests/specs/issue_fix/58_create_migration_for_column_position_change_if_a_field_position_is_changed_in_spec/mysql/migrations_mysql_db/m200000_000000_change_table_fruits.php new file mode 100644 index 00000000..90ab0c79 --- /dev/null +++ b/tests/specs/issue_fix/58_create_migration_for_column_position_change_if_a_field_position_is_changed_in_spec/mysql/migrations_mysql_db/m200000_000000_change_table_fruits.php @@ -0,0 +1,17 @@ +alterColumn('{{%fruits}}', 'name', $this->text()->null()->after('id')); + } + + public function down() + { + $this->alterColumn('{{%fruits}}', 'name', $this->text()->null()->after('description')); + } +} diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index beae7d8b..5ff0d39b 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -369,13 +369,14 @@ public function test58CreateMigrationForColumnPositionChange() $testFile = Yii::getAlias("@specs/issue_fix/58_create_migration_for_column_position_change_if_a_field_position_is_changed_in_spec/index.php"); $this->runGenerator($testFile); - // $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ - // 'recursive' => true, - // ]); - // $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/58_create_migration_for_column_position_change_if_a_field_position_is_changed_in_spec/mysql"), [ - // 'recursive' => true, - // ]); - // $this->checkFiles($actualFiles, $expectedFiles); + $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ + 'recursive' => true, + ]); + $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/58_create_migration_for_column_position_change_if_a_field_position_is_changed_in_spec/mysql"), [ + 'recursive' => true, + ]); + $this->checkFiles($actualFiles, $expectedFiles); + $this->runActualMigrations('mysql', 1); $this->deleteTableFor58CreateMigrationForColumnPositionChange(); } @@ -393,19 +394,19 @@ private function deleteTableFor58CreateMigrationForColumnPositionChange() Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%fruits}}')->execute(); } - private function for58($schema, $expected) + private function for58($schema, $expected, $columns = [ + 'id' => 'pk', + 'name' => 'text not null', + 'description' => 'text not null', + 'colour' => 'text not null', + 'size' => 'text not null', + ]) { $deleteTable = function () { Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%fruits}}')->execute(); }; - $createTable = function () { - Yii::$app->db->createCommand()->createTable('{{%fruits}}', [ - 'id' => 'pk', - 'name' => 'text not null', - 'description' => 'text not null', - 'colour' => 'text not null', - 'size' => 'text not null', - ])->execute(); + $createTable = function () use ($columns) { + Yii::$app->db->createCommand()->createTable('{{%fruits}}', $columns)->execute(); }; $config = [ @@ -426,15 +427,16 @@ private function for58($schema, $expected) $dbStr = str_replace('db', '', strtolower($db)); $this->runGenerator($tmpConfigFile, $dbStr); - $this->runActualMigrations($dbStr, 1); $actual = file_get_contents(Yii::getAlias('@app') . '/migrations_' . $dbStr . '_db/m200000_000000_change_table_fruits.php'); $this->assertSame($expected, $actual); + $this->runActualMigrations($dbStr, 1); $deleteTable(); } FileHelper::unlink($tmpConfigFile); } + // ------------ Delete public function test58DeleteLastCol() { $schema = <<for58($schema, $expected); } - // ------------ + // ------------ Add public function test58AddAColAtLastPos() { // default position is last so no `AFTER` needed @@ -1028,4 +1030,83 @@ public function down() $this->for58($schema, $expected); } + + // ------------ Just move columns + public function test58MoveColumns() + { + $columns = [ + 'id' => 'pk', + 'name' => 'text null', + 'description' => 'text null', + 'colour' => 'text null', + 'size' => 'text null', + 'col_6' => 'text null', + 'col_7' => 'text null', + 'col_8' => 'text null', + 'col_9' => 'text null', + + ]; + + $schema = <<alterColumn('{{%fruits}}', 'colour', $this->text()->notNull()->after('id')); + $this->alterColumn('{{%fruits}}', 'size', $this->text()->notNull()->after('colour')); + } + + public function down() + { + $this->alterColumn('{{%fruits}}', 'size', $this->text()->notNull()->after('colour')); + $this->alterColumn('{{%fruits}}', 'colour', $this->text()->notNull()->after('description')); + } +} + +PHP; + + $this->for58($schema, $expected, $columns); + } } From 6fa477f292913c4cfeaf92be9eac9f35f4767101 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Mon, 7 Oct 2024 21:41:55 +0530 Subject: [PATCH 248/358] Fix bugs + fix failing tests + add more tests --- src/lib/migrations/MigrationRecordBuilder.php | 3 +- src/lib/migrations/MysqlMigrationBuilder.php | 57 ++++++++++++++++++- tests/unit/IssueFixTest.php | 35 +++++------- 3 files changed, 68 insertions(+), 27 deletions(-) diff --git a/src/lib/migrations/MigrationRecordBuilder.php b/src/lib/migrations/MigrationRecordBuilder.php index 76107dfa..0f7a2ca7 100644 --- a/src/lib/migrations/MigrationRecordBuilder.php +++ b/src/lib/migrations/MigrationRecordBuilder.php @@ -135,8 +135,7 @@ public function alterColumnType( ColumnSchema $column, bool $addUsing = false, ?string $position = null - ):string - { + ):string { if (property_exists($column, 'xDbType') && is_string($column->xDbType) && !empty($column->xDbType)) { $converter = $this->columnToCode($tableAlias, $column, false, false, true, true, $position); return sprintf( diff --git a/src/lib/migrations/MysqlMigrationBuilder.php b/src/lib/migrations/MysqlMigrationBuilder.php index 3044af3c..cc3008b4 100644 --- a/src/lib/migrations/MysqlMigrationBuilder.php +++ b/src/lib/migrations/MysqlMigrationBuilder.php @@ -278,6 +278,7 @@ public function setPositions() if (!$column->fromPosition || !$column->toPosition) { continue; } + if ( is_int(array_search([$column->toPosition['index'], $column->fromPosition['index']], $takenIndices)) ) { @@ -287,19 +288,69 @@ public function setPositions() continue; } - if ($column->fromPosition['after'] === $column->toPosition['after']) { + if (!in_array($column->fromPosition['after'], $onlyColumnNames) && !in_array($column->fromPosition['before'], $onlyColumnNames)) { // deleted column continue; } - if ($column->fromPosition['before'] === $column->toPosition['before']) { + if ($column->fromPosition['index'] === $column->toPosition['index']) { continue; } - if (!in_array($column->fromPosition['after'], $onlyColumnNames) && !in_array($column->fromPosition['before'], $onlyColumnNames)) { + if ($this->checkAfterPosition($column)) { + continue; + } + if ($this->checkBeforePosition($column)) { continue; } + +// if ($column->fromPosition['before'] === $column->toPosition['before'] + //// && $column->fromPosition['index'] !== $column->toPosition['index'] +// ) { +// continue; +// } + $column->isPositionReallyChanged = true; $takenIndices[] = [$column->fromPosition['index'], $column->toPosition['index']]; } } + + public function checkAfterPosition($column) + { + if ($column->fromPosition['after'] === $column->toPosition['after'] +// && $column->fromPosition['index'] !== $column->toPosition['index'] + ) { + $afterColName = $column->toPosition['after']; + $afterCol = $this->newColumns[$afterColName] ?? null; + if ($afterCol) { + if ($this->checkAfterPosition($afterCol)) { + return true; + } else { + return false; + } + } else { + return true; + } + } + return false; + } + + public function checkBeforePosition($column) + { + if ($column->fromPosition['before'] === $column->toPosition['before'] +// && $column->fromPosition['index'] !== $column->toPosition['index'] + ) { + $beforeColName = $column->toPosition['before']; + $beforeCol = $this->newColumns[$beforeColName] ?? null; + if ($beforeCol) { + if ($this->checkBeforePosition($beforeCol)) { + return true; + } else { + return false; + } + } else { + return true; + } + } + return false; + } } diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index 5ff0d39b..b42d0779 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -400,7 +400,7 @@ private function for58($schema, $expected, $columns = [ 'description' => 'text not null', 'colour' => 'text not null', 'size' => 'text not null', - ]) + ], $dbs = ['Mysql', 'Mariadb']) { $deleteTable = function () { Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%fruits}}')->execute(); @@ -420,7 +420,7 @@ private function for58($schema, $expected, $columns = [ $tmpConfigFile = Yii::getAlias("@runtime") . "/tmp-config.php"; file_put_contents($tmpConfigFile, '{"changeDbTo$db"}(); $deleteTable(); $createTable(); @@ -1040,10 +1040,10 @@ public function test58MoveColumns() 'description' => 'text null', 'colour' => 'text null', 'size' => 'text null', - 'col_6' => 'text null', - 'col_7' => 'text null', - 'col_8' => 'text null', - 'col_9' => 'text null', +// 'col_6' => 'text null', +// 'col_7' => 'text null', +// 'col_8' => 'text null', +// 'col_9' => 'text null', ]; @@ -1060,22 +1060,13 @@ public function test58MoveColumns() id: type: integer colour: - type: string + type: string size: type: string name: type: string description: - type: string - col_6: - type: string - col_7: - type: string - col_8: - type: string - col_9: - type: string - + type: string paths: '/': get: @@ -1094,19 +1085,19 @@ class m200000_000000_change_table_fruits extends \yii\db\Migration { public function up() { - $this->alterColumn('{{%fruits}}', 'colour', $this->text()->notNull()->after('id')); - $this->alterColumn('{{%fruits}}', 'size', $this->text()->notNull()->after('colour')); + $this->alterColumn('{{%fruits}}', 'colour', $this->text()->null()->after('id')); + $this->alterColumn('{{%fruits}}', 'size', $this->text()->null()->after('colour')); } public function down() { - $this->alterColumn('{{%fruits}}', 'size', $this->text()->notNull()->after('colour')); - $this->alterColumn('{{%fruits}}', 'colour', $this->text()->notNull()->after('description')); + $this->alterColumn('{{%fruits}}', 'size', $this->text()->null()->after('colour')); + $this->alterColumn('{{%fruits}}', 'colour', $this->text()->null()->after('description')); } } PHP; - $this->for58($schema, $expected, $columns); + $this->for58($schema, $expected, $columns, ['Mysql']); } } From a0090f73eddff2d267e69aead3370e45a2e6d0e6 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Tue, 8 Oct 2024 12:19:05 +0530 Subject: [PATCH 249/358] Fix bugs --- src/lib/migrations/MysqlMigrationBuilder.php | 55 ++++++++++++++++---- 1 file changed, 45 insertions(+), 10 deletions(-) diff --git a/src/lib/migrations/MysqlMigrationBuilder.php b/src/lib/migrations/MysqlMigrationBuilder.php index cc3008b4..dfe089fd 100644 --- a/src/lib/migrations/MysqlMigrationBuilder.php +++ b/src/lib/migrations/MysqlMigrationBuilder.php @@ -251,6 +251,7 @@ public function setPositions() $i = 0; $haveColumns = $this->tableSchema->columns; $onlyColumnNames = array_keys($this->newColumns); + $haveNamesOnlyColNames = array_keys($haveColumns); foreach ($this->newColumns as $columnName => $column) { /** @var \cebe\yii2openapi\db\ColumnSchema $column */ $column->toPosition = [ @@ -259,7 +260,6 @@ public function setPositions() 'before' => $i === (count($onlyColumnNames) - 1) ? null : $onlyColumnNames[$i + 1], ]; - $haveNamesOnlyColNames = array_keys($haveColumns); if (isset($haveColumns[$columnName])) { $index = array_search($columnName, $haveNamesOnlyColNames) + 1; $column->fromPosition = [ @@ -275,6 +275,35 @@ public function setPositions() $takenIndices = []; foreach ($this->newColumns as $columnName => $column) { /** @var \cebe\yii2openapi\db\ColumnSchema $column */ + + if (count($onlyColumnNames) !== count($haveNamesOnlyColNames)) { + // check if only new columns are added without any explicit position change + $onlyColumnNamesCopy = $onlyColumnNames; + $columnsForCreate = array_diff($onlyColumnNames, $haveNamesOnlyColNames); + foreach ($columnsForCreate as $key => $value) { + $at = array_search($value, $onlyColumnNames); + if (is_int($at)) { + unset($onlyColumnNamesCopy[$at]); + } + } + if ($onlyColumnNamesCopy === $onlyColumnNames) { + continue; + } + + $haveNamesOnlyColNamesCopy = $haveNamesOnlyColNames; + $columnsForDrop = array_diff($haveNamesOnlyColNames, $onlyColumnNames); + foreach ($columnsForDrop as $key => $value) { + $at = array_search($value, $haveNamesOnlyColNames); + if (is_int($at)) { + unset($haveNamesOnlyColNamesCopy[$at]); + } + } + if ($haveNamesOnlyColNamesCopy === $haveNamesOnlyColNames) { + continue; + } + } + + if (!$column->fromPosition || !$column->toPosition) { continue; } @@ -288,20 +317,26 @@ public function setPositions() continue; } - if (!in_array($column->fromPosition['after'], $onlyColumnNames) && !in_array($column->fromPosition['before'], $onlyColumnNames)) { // deleted column - continue; - } + // TODO this does not look correct +// if (!in_array($column->fromPosition['after'], $onlyColumnNames) && !in_array($column->fromPosition['before'], $onlyColumnNames)) { // after and before column are deleted +// continue; +// } + + // TODO this does not look correct +// if (!in_array($column->toPosition['after'], $haveNamesOnlyColNames) && !in_array($column->toPosition['before'], $haveNamesOnlyColNames)) { // after and before column are added just now +// continue; +// } if ($column->fromPosition['index'] === $column->toPosition['index']) { continue; } - if ($this->checkAfterPosition($column)) { - continue; - } - if ($this->checkBeforePosition($column)) { - continue; - } + // if ($this->checkAfterPosition($column)) { + // continue; + // } + // if ($this->checkBeforePosition($column)) { + // continue; + // } // if ($column->fromPosition['before'] === $column->toPosition['before'] //// && $column->fromPosition['index'] !== $column->toPosition['index'] From 3dcc87e21a261d4d3c553207b8645f336d9bb2c1 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Tue, 8 Oct 2024 13:33:19 +0530 Subject: [PATCH 250/358] Refactor --- src/lib/migrations/MysqlMigrationBuilder.php | 62 ++++---------------- 1 file changed, 12 insertions(+), 50 deletions(-) diff --git a/src/lib/migrations/MysqlMigrationBuilder.php b/src/lib/migrations/MysqlMigrationBuilder.php index dfe089fd..8e738e2d 100644 --- a/src/lib/migrations/MysqlMigrationBuilder.php +++ b/src/lib/migrations/MysqlMigrationBuilder.php @@ -276,74 +276,38 @@ public function setPositions() foreach ($this->newColumns as $columnName => $column) { /** @var \cebe\yii2openapi\db\ColumnSchema $column */ + if (!$column->fromPosition || !$column->toPosition) { + continue; + } + if (count($onlyColumnNames) !== count($haveNamesOnlyColNames)) { // check if only new columns are added without any explicit position change - $onlyColumnNamesCopy = $onlyColumnNames; $columnsForCreate = array_diff($onlyColumnNames, $haveNamesOnlyColNames); - foreach ($columnsForCreate as $key => $value) { - $at = array_search($value, $onlyColumnNames); - if (is_int($at)) { - unset($onlyColumnNamesCopy[$at]); + if ($columnsForCreate) { + if ($haveNamesOnlyColNames === array_values(array_diff($onlyColumnNames, $columnsForCreate))) { + continue; } } - if ($onlyColumnNamesCopy === $onlyColumnNames) { - continue; - } - $haveNamesOnlyColNamesCopy = $haveNamesOnlyColNames; + // check if only existing columns are deleted without any explicit position change $columnsForDrop = array_diff($haveNamesOnlyColNames, $onlyColumnNames); - foreach ($columnsForDrop as $key => $value) { - $at = array_search($value, $haveNamesOnlyColNames); - if (is_int($at)) { - unset($haveNamesOnlyColNamesCopy[$at]); + if ($columnsForDrop) { + if ($onlyColumnNames === array_values(array_diff($haveNamesOnlyColNames, $columnsForDrop))) { + continue; } } - if ($haveNamesOnlyColNamesCopy === $haveNamesOnlyColNames) { - continue; - } - } - - - if (!$column->fromPosition || !$column->toPosition) { - continue; } - if ( - is_int(array_search([$column->toPosition['index'], $column->fromPosition['index']], $takenIndices)) - ) { + if (is_int(array_search([$column->toPosition['index'], $column->fromPosition['index']], $takenIndices))) { continue; } if ($column->fromPosition === $column->toPosition) { continue; } - - // TODO this does not look correct -// if (!in_array($column->fromPosition['after'], $onlyColumnNames) && !in_array($column->fromPosition['before'], $onlyColumnNames)) { // after and before column are deleted -// continue; -// } - - // TODO this does not look correct -// if (!in_array($column->toPosition['after'], $haveNamesOnlyColNames) && !in_array($column->toPosition['before'], $haveNamesOnlyColNames)) { // after and before column are added just now -// continue; -// } - if ($column->fromPosition['index'] === $column->toPosition['index']) { continue; } - // if ($this->checkAfterPosition($column)) { - // continue; - // } - // if ($this->checkBeforePosition($column)) { - // continue; - // } - -// if ($column->fromPosition['before'] === $column->toPosition['before'] - //// && $column->fromPosition['index'] !== $column->toPosition['index'] -// ) { -// continue; -// } - $column->isPositionReallyChanged = true; $takenIndices[] = [$column->fromPosition['index'], $column->toPosition['index']]; } @@ -352,7 +316,6 @@ public function setPositions() public function checkAfterPosition($column) { if ($column->fromPosition['after'] === $column->toPosition['after'] -// && $column->fromPosition['index'] !== $column->toPosition['index'] ) { $afterColName = $column->toPosition['after']; $afterCol = $this->newColumns[$afterColName] ?? null; @@ -372,7 +335,6 @@ public function checkAfterPosition($column) public function checkBeforePosition($column) { if ($column->fromPosition['before'] === $column->toPosition['before'] -// && $column->fromPosition['index'] !== $column->toPosition['index'] ) { $beforeColName = $column->toPosition['before']; $beforeCol = $this->newColumns[$beforeColName] ?? null; From 9ef528cceb03bc5ad89a356740442cd36e761a00 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Tue, 8 Oct 2024 20:50:39 +0530 Subject: [PATCH 251/358] Fix bugs + fix failing tests + add more tests + refactor --- src/lib/migrations/BaseMigrationBuilder.php | 2 +- src/lib/migrations/MysqlMigrationBuilder.php | 74 +++++++--- tests/unit/IssueFixTest.php | 134 ++++++++++++++++++- 3 files changed, 187 insertions(+), 23 deletions(-) diff --git a/src/lib/migrations/BaseMigrationBuilder.php b/src/lib/migrations/BaseMigrationBuilder.php index 0a0070e4..01905e0b 100644 --- a/src/lib/migrations/BaseMigrationBuilder.php +++ b/src/lib/migrations/BaseMigrationBuilder.php @@ -185,7 +185,7 @@ function (string $missingColumn) { function (string $unknownColumn) { return $this->tableSchema->columns[$unknownColumn]; }, - array_diff($haveNames, $wantNames) + array_reverse(array_diff($haveNames, $wantNames), true) ); $columnsForChange = array_intersect($wantNames, $haveNames); diff --git a/src/lib/migrations/MysqlMigrationBuilder.php b/src/lib/migrations/MysqlMigrationBuilder.php index 8e738e2d..4080ee77 100644 --- a/src/lib/migrations/MysqlMigrationBuilder.php +++ b/src/lib/migrations/MysqlMigrationBuilder.php @@ -197,6 +197,42 @@ public function checkOrder() */ public function findPosition(ColumnSchema $column, bool $forDrop = false): ?string { +// if (!$forDrop) { +// $columnNames = array_keys($this->newColumns); +// $key = array_search($column->name, $columnNames); +// if (is_int($key)) { +// if ($key > 0) { +// $prevColName = $columnNames[$key - 1]; +// +// // if the perv col is last then no need for `'AFTER '` because last is the default position +// if (array_search($prevColName, $columnNames) === (count($columnNames) - 1)) { +// return null; +// } +// +// return self::POS_AFTER . ' ' . $prevColName; +// } elseif ($key === 0) { +// return self::POS_FIRST; +// } +// } +// +// } else { +// $columnNames = array_keys($this->tableSchema->columns); +// $key = array_search($column->name, $columnNames); +// if (is_int($key)) { +// if ($key > 0) { +// $prevColName = $columnNames[$key - 1]; +// +// if (array_search($prevColName, $columnNames) === count($columnNames) - 1) { +// return null; +// } +// +// return self::POS_AFTER . ' ' . $prevColName; +// } elseif ($key === 0) { +// return self::POS_FIRST; +// } +// } +// } +// return null; $columnNames = array_keys($forDrop ? $this->tableSchema->columns : $this->newColumns); $key = array_search($column->name, $columnNames); @@ -250,22 +286,22 @@ public function setPositions() { $i = 0; $haveColumns = $this->tableSchema->columns; - $onlyColumnNames = array_keys($this->newColumns); - $haveNamesOnlyColNames = array_keys($haveColumns); - foreach ($this->newColumns as $columnName => $column) { + $wantNames = array_keys($this->newColumns); + $haveNames = array_keys($haveColumns); + foreach ($this->newColumns as $name => $column) { /** @var \cebe\yii2openapi\db\ColumnSchema $column */ $column->toPosition = [ 'index' => $i + 1, - 'after' => $i === 0 ? null : $onlyColumnNames[$i - 1], - 'before' => $i === (count($onlyColumnNames) - 1) ? null : $onlyColumnNames[$i + 1], + 'after' => $i === 0 ? null : $wantNames[$i - 1], + 'before' => $i === (count($wantNames) - 1) ? null : $wantNames[$i + 1], ]; - if (isset($haveColumns[$columnName])) { - $index = array_search($columnName, $haveNamesOnlyColNames) + 1; + if (isset($haveColumns[$name])) { + $index = array_search($name, $haveNames) + 1; $column->fromPosition = [ 'index' => $index, - 'after' => $haveNamesOnlyColNames[$index - 2] ?? null, - 'before' => $haveNamesOnlyColNames[$index] ?? null, + 'after' => $haveNames[$index - 2] ?? null, + 'before' => $haveNames[$index] ?? null, ]; } @@ -273,28 +309,24 @@ public function setPositions() } $takenIndices = []; - foreach ($this->newColumns as $columnName => $column) { + foreach ($this->newColumns as $column) { /** @var \cebe\yii2openapi\db\ColumnSchema $column */ if (!$column->fromPosition || !$column->toPosition) { continue; } - if (count($onlyColumnNames) !== count($haveNamesOnlyColNames)) { + if (count($wantNames) !== count($haveNames)) { // check if only new columns are added without any explicit position change - $columnsForCreate = array_diff($onlyColumnNames, $haveNamesOnlyColNames); - if ($columnsForCreate) { - if ($haveNamesOnlyColNames === array_values(array_diff($onlyColumnNames, $columnsForCreate))) { - continue; - } + $namesForCreate = array_diff($wantNames, $haveNames); + if ($namesForCreate && $haveNames === array_values(array_diff($wantNames, $namesForCreate))) { + continue; } // check if only existing columns are deleted without any explicit position change - $columnsForDrop = array_diff($haveNamesOnlyColNames, $onlyColumnNames); - if ($columnsForDrop) { - if ($onlyColumnNames === array_values(array_diff($haveNamesOnlyColNames, $columnsForDrop))) { - continue; - } + $namesForDrop = array_diff($haveNames, $wantNames); + if ($namesForDrop && $wantNames === array_values(array_diff($haveNames, $namesForDrop))) { + continue; } } diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index b42d0779..2809ffcc 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -709,6 +709,65 @@ public function down() $this->for58($schema, $expected); } + public function test58DeleteLast4Col() + { + $columns = [ + 'id' => 'pk', + 'name' => 'text null', + 'description' => 'text null', + 'colour' => 'text null', + 'size' => 'text null', + 'col_6' => 'text null', + ]; + + $schema = <<alterColumn('{{%fruits}}', 'colour', $this->text()->null()->after('id')); + $this->alterColumn('{{%fruits}}', 'size', $this->text()->null()->after('colour')); + } + + public function down() + { + $this->alterColumn('{{%fruits}}', 'size', $this->text()->null()->after('colour')); + $this->alterColumn('{{%fruits}}', 'colour', $this->text()->null()->after('description')); + } +} + +PHP; + + $this->for58($schema, $expected, $columns, ['Mysql', 'Mariadb']); + } + // ------------ Add public function test58AddAColAtLastPos() { @@ -1032,7 +1091,7 @@ public function down() } // ------------ Just move columns - public function test58MoveColumns() + public function test58MoveLast2Col2PosUp() { $columns = [ 'id' => 'pk', @@ -1100,4 +1159,77 @@ public function down() $this->for58($schema, $expected, $columns, ['Mysql']); } + + // ----------- + public function test58Move1Add1Del1Col() + { + $columns = [ + 'id' => 'pk', + 'name' => 'text null', + 'description' => 'text null', + 'colour' => 'text null', + 'size' => 'text null', +// 'col_6' => 'text null', +// 'col_7' => 'text null', +// 'col_8' => 'text null', +// 'col_9' => 'text null', + + ]; + + $schema = <<alterColumn('{{%fruits}}', 'colour', $this->text()->null()->after('id')); + $this->alterColumn('{{%fruits}}', 'size', $this->text()->null()->after('colour')); + } + + public function down() + { + $this->alterColumn('{{%fruits}}', 'size', $this->text()->null()->after('colour')); + $this->alterColumn('{{%fruits}}', 'colour', $this->text()->null()->after('description')); + } +} + +PHP; + + $this->for58($schema, $expected, $columns, ['Mysql']); + } + + // add 1 and del 1 col at same position + // add 1 and del 1 col at different position } From 9310dc618c9aaf6f0812bf9af055a80c17ded988 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Thu, 10 Oct 2024 20:19:42 +0530 Subject: [PATCH 252/358] Fix failing tests --- src/lib/migrations/MysqlMigrationBuilder.php | 20 ++++----- tests/unit/IssueFixTest.php | 43 +++++++++++--------- 2 files changed, 33 insertions(+), 30 deletions(-) diff --git a/src/lib/migrations/MysqlMigrationBuilder.php b/src/lib/migrations/MysqlMigrationBuilder.php index 4080ee77..c3e31585 100644 --- a/src/lib/migrations/MysqlMigrationBuilder.php +++ b/src/lib/migrations/MysqlMigrationBuilder.php @@ -316,18 +316,16 @@ public function setPositions() continue; } - if (count($wantNames) !== count($haveNames)) { - // check if only new columns are added without any explicit position change - $namesForCreate = array_diff($wantNames, $haveNames); - if ($namesForCreate && $haveNames === array_values(array_diff($wantNames, $namesForCreate))) { - continue; - } +// // check if only new columns are added without any explicit position change + $namesForCreate = array_diff($wantNames, $haveNames); + if ($namesForCreate && $haveNames === array_values(array_diff($wantNames, $namesForCreate))) { + continue; + } - // check if only existing columns are deleted without any explicit position change - $namesForDrop = array_diff($haveNames, $wantNames); - if ($namesForDrop && $wantNames === array_values(array_diff($haveNames, $namesForDrop))) { - continue; - } + // check if only existing columns are deleted without any explicit position change + $namesForDrop = array_diff($haveNames, $wantNames); + if ($namesForDrop && $wantNames === array_values(array_diff($haveNames, $namesForDrop))) { + continue; } if (is_int(array_search([$column->toPosition['index'], $column->fromPosition['index']], $takenIndices))) { diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index 2809ffcc..3f3ff3be 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -530,14 +530,14 @@ class m200000_000000_change_table_fruits extends \yii\db\Migration { public function up() { - $this->dropColumn('{{%fruits}}', 'colour'); $this->dropColumn('{{%fruits}}', 'size'); + $this->dropColumn('{{%fruits}}', 'colour'); } public function down() { - $this->addColumn('{{%fruits}}', 'size', $this->text()->notNull()); $this->addColumn('{{%fruits}}', 'colour', $this->text()->notNull()->after('description')); + $this->addColumn('{{%fruits}}', 'size', $this->text()->notNull()); } } @@ -639,14 +639,14 @@ class m200000_000000_change_table_fruits extends \yii\db\Migration { public function up() { - $this->dropColumn('{{%fruits}}', 'description'); $this->dropColumn('{{%fruits}}', 'colour'); + $this->dropColumn('{{%fruits}}', 'description'); } public function down() { - $this->addColumn('{{%fruits}}', 'colour', $this->text()->notNull()); $this->addColumn('{{%fruits}}', 'description', $this->text()->notNull()->after('name')); + $this->addColumn('{{%fruits}}', 'colour', $this->text()->notNull()); } } @@ -693,14 +693,14 @@ class m200000_000000_change_table_fruits extends \yii\db\Migration { public function up() { - $this->dropColumn('{{%fruits}}', 'name'); $this->dropColumn('{{%fruits}}', 'colour'); + $this->dropColumn('{{%fruits}}', 'name'); } public function down() { - $this->addColumn('{{%fruits}}', 'colour', $this->text()->notNull()->after('description')); $this->addColumn('{{%fruits}}', 'name', $this->text()->notNull()->after('id')); + $this->addColumn('{{%fruits}}', 'colour', $this->text()->notNull()->after('description')); } } @@ -752,20 +752,24 @@ class m200000_000000_change_table_fruits extends \yii\db\Migration { public function up() { - $this->alterColumn('{{%fruits}}', 'colour', $this->text()->null()->after('id')); - $this->alterColumn('{{%fruits}}', 'size', $this->text()->null()->after('colour')); + $this->dropColumn('{{%fruits}}', 'col_6'); + $this->dropColumn('{{%fruits}}', 'size'); + $this->dropColumn('{{%fruits}}', 'colour'); + $this->dropColumn('{{%fruits}}', 'description'); } public function down() { - $this->alterColumn('{{%fruits}}', 'size', $this->text()->null()->after('colour')); - $this->alterColumn('{{%fruits}}', 'colour', $this->text()->null()->after('description')); + $this->addColumn('{{%fruits}}', 'description', $this->text()->null()); + $this->addColumn('{{%fruits}}', 'colour', $this->text()->null()); + $this->addColumn('{{%fruits}}', 'size', $this->text()->null()); + $this->addColumn('{{%fruits}}', 'col_6', $this->text()->null()); } } PHP; - $this->for58($schema, $expected, $columns, ['Mysql', 'Mariadb']); + $this->for58($schema, $expected, $columns, ['Mysql']); } // ------------ Add @@ -1169,11 +1173,6 @@ public function test58Move1Add1Del1Col() 'description' => 'text null', 'colour' => 'text null', 'size' => 'text null', -// 'col_6' => 'text null', -// 'col_7' => 'text null', -// 'col_8' => 'text null', -// 'col_9' => 'text null', - ]; $schema = <<addColumn('{{%fruits}}', 'col_6', $this->text()->null()); + $this->dropColumn('{{%fruits}}', 'size'); $this->alterColumn('{{%fruits}}', 'colour', $this->text()->null()->after('id')); - $this->alterColumn('{{%fruits}}', 'size', $this->text()->null()->after('colour')); + $this->alterColumn('{{%fruits}}', 'name', $this->text()->null()->after('colour')); + $this->alterColumn('{{%fruits}}', 'description', $this->text()->null()->after('name')); } public function down() { - $this->alterColumn('{{%fruits}}', 'size', $this->text()->null()->after('colour')); + $this->alterColumn('{{%fruits}}', 'description', $this->text()->null()->after('name')); + $this->alterColumn('{{%fruits}}', 'name', $this->text()->null()->after('id')); $this->alterColumn('{{%fruits}}', 'colour', $this->text()->null()->after('description')); + $this->addColumn('{{%fruits}}', 'size', $this->text()->null()->after('colour')); + $this->dropColumn('{{%fruits}}', 'col_6'); } } From 617fdf5b447ac71b4fff1354fb8e3a1b0a33e1c1 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Thu, 10 Oct 2024 20:28:45 +0530 Subject: [PATCH 253/358] Fix other failing tests --- .../m200000_000003_change_table_dropfirsttwocols.php | 4 ++-- .../m200000_000003_change_table_dropfirsttwocols.php | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000003_change_table_dropfirsttwocols.php b/tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000003_change_table_dropfirsttwocols.php index 89ef1937..9877ed34 100644 --- a/tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000003_change_table_dropfirsttwocols.php +++ b/tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000003_change_table_dropfirsttwocols.php @@ -7,13 +7,13 @@ class m200000_000003_change_table_dropfirsttwocols extends \yii\db\Migration { public function up() { - $this->dropColumn('{{%dropfirsttwocols}}', 'name'); $this->dropColumn('{{%dropfirsttwocols}}', 'address'); + $this->dropColumn('{{%dropfirsttwocols}}', 'name'); } public function down() { - $this->addColumn('{{%dropfirsttwocols}}', 'address', $this->text()->null()->defaultValue(null)); $this->addColumn('{{%dropfirsttwocols}}', 'name', $this->text()->null()->defaultValue(null)->first()); + $this->addColumn('{{%dropfirsttwocols}}', 'address', $this->text()->null()->defaultValue(null)); } } diff --git a/tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000003_change_table_dropfirsttwocols.php b/tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000003_change_table_dropfirsttwocols.php index aaa54835..c4b398f5 100644 --- a/tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000003_change_table_dropfirsttwocols.php +++ b/tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000003_change_table_dropfirsttwocols.php @@ -7,13 +7,13 @@ class m200000_000003_change_table_dropfirsttwocols extends \yii\db\Migration { public function up() { - $this->dropColumn('{{%dropfirsttwocols}}', 'name'); $this->dropColumn('{{%dropfirsttwocols}}', 'address'); + $this->dropColumn('{{%dropfirsttwocols}}', 'name'); } public function down() { - $this->addColumn('{{%dropfirsttwocols}}', 'address', $this->text()->null()); $this->addColumn('{{%dropfirsttwocols}}', 'name', $this->text()->null()->first()); + $this->addColumn('{{%dropfirsttwocols}}', 'address', $this->text()->null()); } } From 85aac9105134dfe593eb483a241f1ba96e7a48b1 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Fri, 11 Oct 2024 21:30:41 +0530 Subject: [PATCH 254/358] Fix bugs + fix failing tests --- src/lib/migrations/BaseMigrationBuilder.php | 2 +- src/lib/migrations/MysqlMigrationBuilder.php | 24 ++++++++++++++----- .../migrations/PostgresMigrationBuilder.php | 2 +- tests/unit/IssueFixTest.php | 6 ++--- 4 files changed, 23 insertions(+), 11 deletions(-) diff --git a/src/lib/migrations/BaseMigrationBuilder.php b/src/lib/migrations/BaseMigrationBuilder.php index 01905e0b..d65582b1 100644 --- a/src/lib/migrations/BaseMigrationBuilder.php +++ b/src/lib/migrations/BaseMigrationBuilder.php @@ -554,5 +554,5 @@ abstract public function handleColumnsPositionsChanges(array $haveNames, array $ * 'FIRST' if column is added at first position * 'AFTER ' if column is added in between e.g. if 'email' is added after 'username' then 'AFTER username' */ - abstract public function findPosition(ColumnSchema $column, bool $forDrop = false): ?string; + abstract public function findPosition(ColumnSchema $column, bool $forDrop = false, bool $forAlter = false): ?string; } diff --git a/src/lib/migrations/MysqlMigrationBuilder.php b/src/lib/migrations/MysqlMigrationBuilder.php index c3e31585..ee276e40 100644 --- a/src/lib/migrations/MysqlMigrationBuilder.php +++ b/src/lib/migrations/MysqlMigrationBuilder.php @@ -25,8 +25,8 @@ protected function buildColumnChanges(ColumnSchema $current, ColumnSchema $desir { $positionCurrent = $positionDesired = null; if (in_array('position', $changed, true)) { - $positionCurrent = $this->findPosition($current, true); - $positionDesired = $this->findPosition($desired); + $positionDesired = $this->findPosition($desired, false, true); + $positionCurrent = $this->findPosition($desired, true, true); $key = array_search('position', $changed, true); if ($key !== false) { unset($changed[$key]); @@ -195,8 +195,13 @@ public function checkOrder() /** * {@inheritDoc} */ - public function findPosition(ColumnSchema $column, bool $forDrop = false): ?string + public function findPosition(ColumnSchema $column, bool $forDrop = false, bool $forAlter = false): ?string { +// if ($column instanceof \cebe\yii2openapi\db\ColumnSchema) { +// if (!$column->isPositionReallyChanged) { +// return null; +// } +// } // if (!$forDrop) { // $columnNames = array_keys($this->newColumns); // $key = array_search($column->name, $columnNames); @@ -233,17 +238,24 @@ public function findPosition(ColumnSchema $column, bool $forDrop = false): ?stri // } // } // return null; + $columnNames = array_keys($forDrop ? $this->tableSchema->columns : $this->newColumns); $key = array_search($column->name, $columnNames); if ($key > 0) { $prevColName = $columnNames[$key - 1]; - - if (!$forDrop && !isset($columnNames[$key + 1])) { // if new col is added at last then no need to add 'AFTER' SQL part. This is checked as if next column is present or not + if (($key === count($columnNames) - 1) && !$forAlter) { return null; } - if (array_key_exists($prevColName, $this->newColumns)) { +// if (!$forDrop && !isset($columnNames[$key + 1])) { // if new col is added at last then no need to add 'AFTER' SQL part. This is checked as if next column is present or not +// return null; +// } + + if (array_key_exists($prevColName, $forDrop ? $this->tableSchema->columns : $this->newColumns)) { + if (($prevColName === $columnNames[count($columnNames) - 1]) && !$forAlter) { + return null; + } return self::POS_AFTER . ' ' . $prevColName; } return null; diff --git a/src/lib/migrations/PostgresMigrationBuilder.php b/src/lib/migrations/PostgresMigrationBuilder.php index 36a88c3e..7fbc6419 100644 --- a/src/lib/migrations/PostgresMigrationBuilder.php +++ b/src/lib/migrations/PostgresMigrationBuilder.php @@ -259,7 +259,7 @@ public function handleColumnsPositionsChanges(array $haveNames, array $wantNames /** * {@inheritDoc} */ - public function findPosition(ColumnSchema $column, bool $forDrop = false): ?string + public function findPosition(ColumnSchema $column, bool $forDrop = false, bool $forAlter = false): ?string { return null; } diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index 3f3ff3be..0e1c6027 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -483,7 +483,7 @@ public function up() public function down() { - $this->addColumn('{{%fruits}}', 'size', $this->text()->notNull()->after('colour')); + $this->addColumn('{{%fruits}}', 'size', $this->text()->notNull()); } } @@ -646,7 +646,7 @@ public function up() public function down() { $this->addColumn('{{%fruits}}', 'description', $this->text()->notNull()->after('name')); - $this->addColumn('{{%fruits}}', 'colour', $this->text()->notNull()); + $this->addColumn('{{%fruits}}', 'colour', $this->text()->notNull()->after('description')); } } @@ -1225,7 +1225,7 @@ public function down() $this->alterColumn('{{%fruits}}', 'description', $this->text()->null()->after('name')); $this->alterColumn('{{%fruits}}', 'name', $this->text()->null()->after('id')); $this->alterColumn('{{%fruits}}', 'colour', $this->text()->null()->after('description')); - $this->addColumn('{{%fruits}}', 'size', $this->text()->null()->after('colour')); + $this->addColumn('{{%fruits}}', 'size', $this->text()->null()); $this->dropColumn('{{%fruits}}', 'col_6'); } } From 95db88f3b7674837ffcdb3198c22b3d3edd0d764 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Sat, 12 Oct 2024 17:25:12 +0530 Subject: [PATCH 255/358] Fix bugs + fix failing tests 2 --- src/lib/migrations/MysqlMigrationBuilder.php | 25 ++++++++++++------- ...00000_change_table_column_name_changes.php | 2 +- ...00000_change_table_column_name_changes.php | 2 +- ...m200000_000001_change_table_newcolumns.php | 2 +- ...m200000_000001_change_table_newcolumns.php | 2 +- ...0_000003_change_table_dropfirsttwocols.php | 2 +- ...0_000003_change_table_dropfirsttwocols.php | 2 +- tests/unit/IssueFixTest.php | 11 +++----- 8 files changed, 25 insertions(+), 23 deletions(-) diff --git a/src/lib/migrations/MysqlMigrationBuilder.php b/src/lib/migrations/MysqlMigrationBuilder.php index ee276e40..c03979df 100644 --- a/src/lib/migrations/MysqlMigrationBuilder.php +++ b/src/lib/migrations/MysqlMigrationBuilder.php @@ -28,9 +28,7 @@ protected function buildColumnChanges(ColumnSchema $current, ColumnSchema $desir $positionDesired = $this->findPosition($desired, false, true); $positionCurrent = $this->findPosition($desired, true, true); $key = array_search('position', $changed, true); - if ($key !== false) { - unset($changed[$key]); - } + unset($changed[$key]); } $newColumn = clone $current; // $positionCurrent = $this->findPosition($desired, true); @@ -253,8 +251,12 @@ public function findPosition(ColumnSchema $column, bool $forDrop = false, bool $ // } if (array_key_exists($prevColName, $forDrop ? $this->tableSchema->columns : $this->newColumns)) { - if (($prevColName === $columnNames[count($columnNames) - 1]) && !$forAlter) { - return null; + if ($forDrop && !$forAlter) { + // if the previous column is the last one in the want names then no need for AFTER + $cols = array_keys($this->newColumns); + if ($prevColName === array_pop($cols)) { + return null; + } } return self::POS_AFTER . ' ' . $prevColName; } @@ -328,15 +330,20 @@ public function setPositions() continue; } -// // check if only new columns are added without any explicit position change + // check if only new columns are added without any explicit position change $namesForCreate = array_diff($wantNames, $haveNames); - if ($namesForCreate && $haveNames === array_values(array_diff($wantNames, $namesForCreate))) { + $wantNamesWoNewCols = array_values(array_diff($wantNames, $namesForCreate)); + if ($namesForCreate && $haveNames === $wantNamesWoNewCols) { continue; } - // check if only existing columns are deleted without any explicit position change $namesForDrop = array_diff($haveNames, $wantNames); - if ($namesForDrop && $wantNames === array_values(array_diff($haveNames, $namesForDrop))) { + $haveNamesWoDropCols = array_values(array_diff($haveNames, $namesForDrop)); + if ($namesForDrop && $wantNames === $haveNamesWoDropCols) { + continue; + } + // check both above simultaneously + if ($namesForCreate && $namesForDrop && ($wantNamesWoNewCols === $haveNamesWoDropCols)) { continue; } diff --git a/tests/specs/change_column_name/maria/app/migrations_maria_db/m200000_000000_change_table_column_name_changes.php b/tests/specs/change_column_name/maria/app/migrations_maria_db/m200000_000000_change_table_column_name_changes.php index 199c7fb1..1a75dbd3 100644 --- a/tests/specs/change_column_name/maria/app/migrations_maria_db/m200000_000000_change_table_column_name_changes.php +++ b/tests/specs/change_column_name/maria/app/migrations_maria_db/m200000_000000_change_table_column_name_changes.php @@ -13,7 +13,7 @@ public function up() public function down() { - $this->addColumn('{{%column_name_changes}}', 'updated_at', $this->datetime()->notNull()->after('name')); + $this->addColumn('{{%column_name_changes}}', 'updated_at', $this->datetime()->notNull()); $this->dropColumn('{{%column_name_changes}}', 'updated_at_2'); } } diff --git a/tests/specs/change_column_name/mysql/app/migrations_mysql_db/m200000_000000_change_table_column_name_changes.php b/tests/specs/change_column_name/mysql/app/migrations_mysql_db/m200000_000000_change_table_column_name_changes.php index 199c7fb1..1a75dbd3 100644 --- a/tests/specs/change_column_name/mysql/app/migrations_mysql_db/m200000_000000_change_table_column_name_changes.php +++ b/tests/specs/change_column_name/mysql/app/migrations_mysql_db/m200000_000000_change_table_column_name_changes.php @@ -13,7 +13,7 @@ public function up() public function down() { - $this->addColumn('{{%column_name_changes}}', 'updated_at', $this->datetime()->notNull()->after('name')); + $this->addColumn('{{%column_name_changes}}', 'updated_at', $this->datetime()->notNull()); $this->dropColumn('{{%column_name_changes}}', 'updated_at_2'); } } diff --git a/tests/specs/enum/new_column/maria/app/migrations_maria_db/m200000_000001_change_table_newcolumns.php b/tests/specs/enum/new_column/maria/app/migrations_maria_db/m200000_000001_change_table_newcolumns.php index b8750ddd..78f6b2e5 100644 --- a/tests/specs/enum/new_column/maria/app/migrations_maria_db/m200000_000001_change_table_newcolumns.php +++ b/tests/specs/enum/new_column/maria/app/migrations_maria_db/m200000_000001_change_table_newcolumns.php @@ -14,7 +14,7 @@ public function up() public function down() { - $this->addColumn('{{%newcolumns}}', 'delete_col', 'enum("FOUR", "FIVE", "SIX") NULL DEFAULT NULL AFTER id'); + $this->addColumn('{{%newcolumns}}', 'delete_col', 'enum("FOUR", "FIVE", "SIX") NULL DEFAULT NULL'); $this->dropColumn('{{%newcolumns}}', 'new_column_x'); $this->dropColumn('{{%newcolumns}}', 'new_column'); } diff --git a/tests/specs/enum/new_column/mysql/app/migrations_mysql_db/m200000_000001_change_table_newcolumns.php b/tests/specs/enum/new_column/mysql/app/migrations_mysql_db/m200000_000001_change_table_newcolumns.php index b8750ddd..78f6b2e5 100644 --- a/tests/specs/enum/new_column/mysql/app/migrations_mysql_db/m200000_000001_change_table_newcolumns.php +++ b/tests/specs/enum/new_column/mysql/app/migrations_mysql_db/m200000_000001_change_table_newcolumns.php @@ -14,7 +14,7 @@ public function up() public function down() { - $this->addColumn('{{%newcolumns}}', 'delete_col', 'enum("FOUR", "FIVE", "SIX") NULL DEFAULT NULL AFTER id'); + $this->addColumn('{{%newcolumns}}', 'delete_col', 'enum("FOUR", "FIVE", "SIX") NULL DEFAULT NULL'); $this->dropColumn('{{%newcolumns}}', 'new_column_x'); $this->dropColumn('{{%newcolumns}}', 'new_column'); } diff --git a/tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000003_change_table_dropfirsttwocols.php b/tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000003_change_table_dropfirsttwocols.php index 9877ed34..b67baf29 100644 --- a/tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000003_change_table_dropfirsttwocols.php +++ b/tests/specs/new_column_position/maria/app/migrations_maria_db/m200000_000003_change_table_dropfirsttwocols.php @@ -14,6 +14,6 @@ public function up() public function down() { $this->addColumn('{{%dropfirsttwocols}}', 'name', $this->text()->null()->defaultValue(null)->first()); - $this->addColumn('{{%dropfirsttwocols}}', 'address', $this->text()->null()->defaultValue(null)); + $this->addColumn('{{%dropfirsttwocols}}', 'address', $this->text()->null()->defaultValue(null)->after('name')); } } diff --git a/tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000003_change_table_dropfirsttwocols.php b/tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000003_change_table_dropfirsttwocols.php index c4b398f5..83aa17eb 100644 --- a/tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000003_change_table_dropfirsttwocols.php +++ b/tests/specs/new_column_position/mysql/app/migrations_mysql_db/m200000_000003_change_table_dropfirsttwocols.php @@ -14,6 +14,6 @@ public function up() public function down() { $this->addColumn('{{%dropfirsttwocols}}', 'name', $this->text()->null()->first()); - $this->addColumn('{{%dropfirsttwocols}}', 'address', $this->text()->null()); + $this->addColumn('{{%dropfirsttwocols}}', 'address', $this->text()->null()->after('name')); } } diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index 0e1c6027..138967b8 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -536,7 +536,7 @@ public function up() public function down() { - $this->addColumn('{{%fruits}}', 'colour', $this->text()->notNull()->after('description')); + $this->addColumn('{{%fruits}}', 'colour', $this->text()->notNull()); $this->addColumn('{{%fruits}}', 'size', $this->text()->notNull()); } } @@ -761,8 +761,8 @@ public function up() public function down() { $this->addColumn('{{%fruits}}', 'description', $this->text()->null()); - $this->addColumn('{{%fruits}}', 'colour', $this->text()->null()); - $this->addColumn('{{%fruits}}', 'size', $this->text()->null()); + $this->addColumn('{{%fruits}}', 'colour', $this->text()->null()->after('description')); + $this->addColumn('{{%fruits}}', 'size', $this->text()->null()->after('colour')); $this->addColumn('{{%fruits}}', 'col_6', $this->text()->null()); } } @@ -1103,11 +1103,6 @@ public function test58MoveLast2Col2PosUp() 'description' => 'text null', 'colour' => 'text null', 'size' => 'text null', -// 'col_6' => 'text null', -// 'col_7' => 'text null', -// 'col_8' => 'text null', -// 'col_9' => 'text null', - ]; $schema = << Date: Sat, 12 Oct 2024 20:21:41 +0530 Subject: [PATCH 256/358] Change tests and add few more --- tests/unit/IssueFixTest.php | 214 ++++++++++++++++++++++++++++-------- 1 file changed, 171 insertions(+), 43 deletions(-) diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index 138967b8..947cadea 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -713,11 +713,11 @@ public function test58DeleteLast4Col() { $columns = [ 'id' => 'pk', - 'name' => 'text null', - 'description' => 'text null', - 'colour' => 'text null', - 'size' => 'text null', - 'col_6' => 'text null', + 'name' => 'bool null', + 'description' => 'bool null', + 'colour' => 'bool null', + 'size' => 'bool null', + 'col_6' => 'bool null', ]; $schema = <<addColumn('{{%fruits}}', 'description', $this->text()->null()); - $this->addColumn('{{%fruits}}', 'colour', $this->text()->null()->after('description')); - $this->addColumn('{{%fruits}}', 'size', $this->text()->null()->after('colour')); - $this->addColumn('{{%fruits}}', 'col_6', $this->text()->null()); + $this->addColumn('{{%fruits}}', 'description', $this->tinyInteger(1)->null()->defaultValue(null)); + $this->addColumn('{{%fruits}}', 'colour', $this->tinyInteger(1)->null()->defaultValue(null)->after('description')); + $this->addColumn('{{%fruits}}', 'size', $this->tinyInteger(1)->null()->defaultValue(null)->after('colour')); + $this->addColumn('{{%fruits}}', 'col_6', $this->tinyInteger(1)->null()->defaultValue(null)); } } PHP; - $this->for58($schema, $expected, $columns, ['Mysql']); + $this->for58($schema, $expected, $columns/*, ['Mysql']*/); + } + + public function test58DeleteFirst4Col() + { + $columns = [ + 'name' => 'boolean null', + 'description' => 'boolean null', + 'colour' => 'boolean null', + 'size' => 'boolean null', + 'col_6' => 'boolean null', + 'col_7' => 'boolean null', + ]; + + $schema = <<dropColumn('{{%fruits}}', 'size'); + $this->dropColumn('{{%fruits}}', 'colour'); + $this->dropColumn('{{%fruits}}', 'description'); + $this->dropColumn('{{%fruits}}', 'name'); + } + + public function down() + { + $this->addColumn('{{%fruits}}', 'name', $this->tinyInteger(1)->null()->defaultValue(null)->first()); + $this->addColumn('{{%fruits}}', 'description', $this->tinyInteger(1)->null()->defaultValue(null)->after('name')); + $this->addColumn('{{%fruits}}', 'colour', $this->tinyInteger(1)->null()->defaultValue(null)->after('description')); + $this->addColumn('{{%fruits}}', 'size', $this->tinyInteger(1)->null()->defaultValue(null)->after('colour')); + } +} + +PHP; + + $this->for58($schema, $expected, $columns/*, ['Mysql']*/); } // ------------ Add @@ -1099,10 +1162,10 @@ public function test58MoveLast2Col2PosUp() { $columns = [ 'id' => 'pk', - 'name' => 'text null', - 'description' => 'text null', - 'colour' => 'text null', - 'size' => 'text null', + 'name' => 'bool null', + 'description' => 'bool null', + 'colour' => 'bool null', + 'size' => 'bool null', ]; $schema = <<alterColumn('{{%fruits}}', 'colour', $this->text()->null()->after('id')); - $this->alterColumn('{{%fruits}}', 'size', $this->text()->null()->after('colour')); + $this->alterColumn('{{%fruits}}', 'colour', $this->tinyInteger(1)->null()->defaultValue(null)->after('id')); + $this->alterColumn('{{%fruits}}', 'size', $this->tinyInteger(1)->null()->defaultValue(null)->after('colour')); } public function down() { - $this->alterColumn('{{%fruits}}', 'size', $this->text()->null()->after('colour')); - $this->alterColumn('{{%fruits}}', 'colour', $this->text()->null()->after('description')); + $this->alterColumn('{{%fruits}}', 'size', $this->tinyInteger(1)->null()->defaultValue(null)->after('colour')); + $this->alterColumn('{{%fruits}}', 'colour', $this->tinyInteger(1)->null()->defaultValue(null)->after('description')); } } PHP; - $this->for58($schema, $expected, $columns, ['Mysql']); + $this->for58($schema, $expected, $columns/*, ['Mysql']*/); } - // ----------- + // ----------- Miscellaneous public function test58Move1Add1Del1Col() { $columns = [ 'id' => 'pk', - 'name' => 'text null', - 'description' => 'text null', - 'colour' => 'text null', - 'size' => 'text null', + 'name' => 'boolean null', + 'description' => 'boolean null', + 'colour' => 'boolean null', + 'size' => 'boolean null', ]; $schema = <<addColumn('{{%fruits}}', 'col_6', $this->text()->null()); + $this->addColumn('{{%fruits}}', 'col_6', $this->boolean()->null()->defaultValue(null)); $this->dropColumn('{{%fruits}}', 'size'); - $this->alterColumn('{{%fruits}}', 'colour', $this->text()->null()->after('id')); - $this->alterColumn('{{%fruits}}', 'name', $this->text()->null()->after('colour')); - $this->alterColumn('{{%fruits}}', 'description', $this->text()->null()->after('name')); + $this->alterColumn('{{%fruits}}', 'colour', $this->tinyInteger(1)->null()->defaultValue(null)->after('id')); + $this->alterColumn('{{%fruits}}', 'name', $this->tinyInteger(1)->null()->defaultValue(null)->after('colour')); + $this->alterColumn('{{%fruits}}', 'description', $this->tinyInteger(1)->null()->defaultValue(null)->after('name')); } public function down() { - $this->alterColumn('{{%fruits}}', 'description', $this->text()->null()->after('name')); - $this->alterColumn('{{%fruits}}', 'name', $this->text()->null()->after('id')); - $this->alterColumn('{{%fruits}}', 'colour', $this->text()->null()->after('description')); - $this->addColumn('{{%fruits}}', 'size', $this->text()->null()); + $this->alterColumn('{{%fruits}}', 'description', $this->tinyInteger(1)->null()->defaultValue(null)->after('name')); + $this->alterColumn('{{%fruits}}', 'name', $this->tinyInteger(1)->null()->defaultValue(null)->after('id')); + $this->alterColumn('{{%fruits}}', 'colour', $this->tinyInteger(1)->null()->defaultValue(null)->after('description')); + $this->addColumn('{{%fruits}}', 'size', $this->tinyInteger(1)->null()->defaultValue(null)); $this->dropColumn('{{%fruits}}', 'col_6'); } } PHP; - $this->for58($schema, $expected, $columns, ['Mysql']); + $this->for58($schema, $expected, $columns/*, ['Mysql']*/); + } + + public function test58Add1Del1ColAtSamePosition() + { + $columns = [ + 'id' => 'pk', + 'name' => 'bool null', + 'description' => 'bool null', + 'colour' => 'bool null', + 'size' => 'bool null', + ]; + + $schema = <<addColumn('{{%fruits}}', 'description_new', $this->boolean()->null()->defaultValue(null)->after('name')); + $this->dropColumn('{{%fruits}}', 'description'); + } + + public function down() + { + $this->addColumn('{{%fruits}}', 'description', $this->tinyInteger(1)->null()->defaultValue(null)->after('name')); + $this->dropColumn('{{%fruits}}', 'description_new'); + } +} + +PHP; + + $this->for58($schema, $expected, $columns); } - // add 1 and del 1 col at same position + // TODO add tests cases: // add 1 and del 1 col at different position + // add 2 and del 1 col at different positions } From e54defe5aef10d1a8b37087b9edc47b9a9a9f408 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Mon, 14 Oct 2024 17:33:13 +0530 Subject: [PATCH 257/358] Fix bug --- src/lib/migrations/MysqlMigrationBuilder.php | 5 + tests/unit/IssueFixTest.php | 149 ++++++++++++++++++- 2 files changed, 146 insertions(+), 8 deletions(-) diff --git a/src/lib/migrations/MysqlMigrationBuilder.php b/src/lib/migrations/MysqlMigrationBuilder.php index c03979df..8ba6a0fa 100644 --- a/src/lib/migrations/MysqlMigrationBuilder.php +++ b/src/lib/migrations/MysqlMigrationBuilder.php @@ -258,6 +258,11 @@ public function findPosition(ColumnSchema $column, bool $forDrop = false, bool $ return null; } } + if ($forAlter && $forDrop) { + if (!array_key_exists($prevColName, $this->newColumns)) { + return null; + } + } return self::POS_AFTER . ' ' . $prevColName; } return null; diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index 947cadea..f1d2410c 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -430,7 +430,6 @@ private function for58($schema, $expected, $columns = [ $actual = file_get_contents(Yii::getAlias('@app') . '/migrations_' . $dbStr . '_db/m200000_000000_change_table_fruits.php'); $this->assertSame($expected, $actual); $this->runActualMigrations($dbStr, 1); - $deleteTable(); } FileHelper::unlink($tmpConfigFile); @@ -769,7 +768,7 @@ public function down() PHP; - $this->for58($schema, $expected, $columns/*, ['Mysql']*/); + $this->for58($schema, $expected, $columns); } public function test58DeleteFirst4Col() @@ -832,7 +831,7 @@ public function down() PHP; - $this->for58($schema, $expected, $columns/*, ['Mysql']*/); + $this->for58($schema, $expected, $columns); } // ------------ Add @@ -1219,7 +1218,7 @@ public function down() PHP; - $this->for58($schema, $expected, $columns/*, ['Mysql']*/); + $this->for58($schema, $expected, $columns); } // ----------- Miscellaneous @@ -1290,7 +1289,7 @@ public function down() PHP; - $this->for58($schema, $expected, $columns/*, ['Mysql']*/); + $this->for58($schema, $expected, $columns); } public function test58Add1Del1ColAtSamePosition() @@ -1357,7 +1356,141 @@ public function down() $this->for58($schema, $expected, $columns); } - // TODO add tests cases: - // add 1 and del 1 col at different position - // add 2 and del 1 col at different positions + public function test58Add3Del2ColAtDiffPos() + { + $columns = [ + 'id' => 'pk', + 'name' => 'bool null', + 'description' => 'bool null', + 'colour' => 'bool null', + 'size' => 'bool null', + ]; + + $schema = <<addColumn('{{%fruits}}', 'col_6', $this->boolean()->null()->defaultValue(null)->after('id')); + $this->addColumn('{{%fruits}}', 'col_7', $this->boolean()->null()->defaultValue(null)->after('name')); + $this->addColumn('{{%fruits}}', 'col_8', $this->boolean()->null()->defaultValue(null)->after('col_7')); + $this->dropColumn('{{%fruits}}', 'colour'); + $this->dropColumn('{{%fruits}}', 'description'); + } + + public function down() + { + $this->addColumn('{{%fruits}}', 'description', $this->tinyInteger(1)->null()->defaultValue(null)->after('name')); + $this->addColumn('{{%fruits}}', 'colour', $this->tinyInteger(1)->null()->defaultValue(null)->after('description')); + $this->dropColumn('{{%fruits}}', 'col_8'); + $this->dropColumn('{{%fruits}}', 'col_7'); + $this->dropColumn('{{%fruits}}', 'col_6'); + } +} + +PHP; + + $this->for58($schema, $expected, $columns); + } + + // This test fails. See description of https://github.com/php-openapi/yii2-openapi/pull/59 +// public function test58Add3Del2Move3ColAtDiffPos() +// { +// $columns = [ +// 'id' => 'pk', +// 'name' => 'bool null', +// 'description' => 'bool null', +// 'colour' => 'bool null', +// 'size' => 'bool null', +// 'col_6' => 'bool null', +// ]; +// +// $schema = <<for58($schema, $expected, $columns); +// } } From ca2273150a7eee864af85a3315aa880887d20fad Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Mon, 14 Oct 2024 17:53:28 +0530 Subject: [PATCH 258/358] Add docs + refactor --- src/db/ColumnSchema.php | 14 +-- src/lib/migrations/BaseMigrationBuilder.php | 11 +-- src/lib/migrations/MysqlMigrationBuilder.php | 87 +------------------ .../migrations/PostgresMigrationBuilder.php | 10 +-- 4 files changed, 17 insertions(+), 105 deletions(-) diff --git a/src/db/ColumnSchema.php b/src/db/ColumnSchema.php index 6ce1cb3a..90b43f06 100644 --- a/src/db/ColumnSchema.php +++ b/src/db/ColumnSchema.php @@ -27,18 +27,22 @@ class ColumnSchema extends \yii\db\ColumnSchema public $xDbType; /** - * TODO * Used only for MySQL/MariaDB * @var array|null * [ - * index => int - * after => ?string - * before => ?string + * index => int # position: starts from 1 + * after => ?string # after column + * before => ?string # before column * ] * If `before` is null then column is last + * If `after` is null then column is first + * If both are null then table has only 1 column */ public ?array $fromPosition = null; public ?array $toPosition = null; - public bool $isPositionReallyChanged = false; + /** + * From `$this->fromPosition` and `$this->toPosition` we can check if the position is changed or not. This is done in `BaseMigrationBuilder::setColumnsPositions()` + */ + public bool $isPositionChanged = false; } diff --git a/src/lib/migrations/BaseMigrationBuilder.php b/src/lib/migrations/BaseMigrationBuilder.php index d65582b1..89b20ccd 100644 --- a/src/lib/migrations/BaseMigrationBuilder.php +++ b/src/lib/migrations/BaseMigrationBuilder.php @@ -171,7 +171,7 @@ public function buildSecondary(?ManyToManyRelation $relation = null):MigrationMo { $this->migration = Yii::createObject(MigrationModel::class, [$this->model, false, $relation, []]); $this->newColumns = $relation->columnSchema ?? $this->model->attributesToColumnSchema(); - $this->setPositions(); + $this->setColumnsPositions(); $wantNames = array_keys($this->newColumns); $haveNames = $this->tableSchema->columnNames; $columnsForCreate = array_map( @@ -538,21 +538,18 @@ public function modifyDesiredInContextOfDesiredFromDb(ColumnSchema $desired, Col $desired->dbType = $desiredFromDb->dbType; } - /** - * TODO docs - */ - abstract public function handleColumnsPositionsChanges(array $haveNames, array $wantNames); - - /** * Only for MySQL and MariaDB * Given a column, compute its previous column name present in OpenAPI schema * @param ColumnSchema $column * @param bool $forDrop + * @param bool $forAlter * @return ?string * `null` if column is added at last * 'FIRST' if column is added at first position * 'AFTER ' if column is added in between e.g. if 'email' is added after 'username' then 'AFTER username' */ abstract public function findPosition(ColumnSchema $column, bool $forDrop = false, bool $forAlter = false): ?string; + + abstract public function setColumnsPositions(); } diff --git a/src/lib/migrations/MysqlMigrationBuilder.php b/src/lib/migrations/MysqlMigrationBuilder.php index 8ba6a0fa..2d8c6928 100644 --- a/src/lib/migrations/MysqlMigrationBuilder.php +++ b/src/lib/migrations/MysqlMigrationBuilder.php @@ -85,7 +85,7 @@ protected function compareColumns(ColumnSchema $current, ColumnSchema $desired): // $positionCurrent = $this->findPosition($desired, true); // $positionDesired = $this->findPosition($desired); // if ($positionCurrent !== $positionDesired) { - if ($desired->isPositionReallyChanged) { + if ($desired->isPositionChanged) { $changedAttributes[] = 'position'; } @@ -181,62 +181,11 @@ public function modifyDesiredInContextOfCurrent(ColumnSchema $current, ColumnSch } } - /** - * TODO - * Check if order/position of column is changed - * @return void - */ - public function checkOrder() - { - } - /** * {@inheritDoc} */ public function findPosition(ColumnSchema $column, bool $forDrop = false, bool $forAlter = false): ?string { -// if ($column instanceof \cebe\yii2openapi\db\ColumnSchema) { -// if (!$column->isPositionReallyChanged) { -// return null; -// } -// } -// if (!$forDrop) { -// $columnNames = array_keys($this->newColumns); -// $key = array_search($column->name, $columnNames); -// if (is_int($key)) { -// if ($key > 0) { -// $prevColName = $columnNames[$key - 1]; -// -// // if the perv col is last then no need for `'AFTER '` because last is the default position -// if (array_search($prevColName, $columnNames) === (count($columnNames) - 1)) { -// return null; -// } -// -// return self::POS_AFTER . ' ' . $prevColName; -// } elseif ($key === 0) { -// return self::POS_FIRST; -// } -// } -// -// } else { -// $columnNames = array_keys($this->tableSchema->columns); -// $key = array_search($column->name, $columnNames); -// if (is_int($key)) { -// if ($key > 0) { -// $prevColName = $columnNames[$key - 1]; -// -// if (array_search($prevColName, $columnNames) === count($columnNames) - 1) { -// return null; -// } -// -// return self::POS_AFTER . ' ' . $prevColName; -// } elseif ($key === 0) { -// return self::POS_FIRST; -// } -// } -// } -// return null; - $columnNames = array_keys($forDrop ? $this->tableSchema->columns : $this->newColumns); $key = array_search($column->name, $columnNames); @@ -246,10 +195,6 @@ public function findPosition(ColumnSchema $column, bool $forDrop = false, bool $ return null; } -// if (!$forDrop && !isset($columnNames[$key + 1])) { // if new col is added at last then no need to add 'AFTER' SQL part. This is checked as if next column is present or not -// return null; -// } - if (array_key_exists($prevColName, $forDrop ? $this->tableSchema->columns : $this->newColumns)) { if ($forDrop && !$forAlter) { // if the previous column is the last one in the want names then no need for AFTER @@ -275,33 +220,7 @@ public function findPosition(ColumnSchema $column, bool $forDrop = false, bool $ return null; } - - // TODO - public function handleColumnsPositionsChanges(array $haveNames, array $wantNames) - { - $indices = []; - if ($haveNames !== $wantNames) { - foreach ($wantNames as $key => $name) { - if ($name !== $haveNames[$key]) { - $indices[] = $key; - } - } - } - for ($i = 0; $i < count($indices) / 2; $i++) { - $this->migration->addUpCode($this->recordBuilder->alterColumn( - $this->model->getTableAlias(), - $this->newColumns[$wantNames[$indices[$i]]], - $this->findPosition($this->newColumns[$wantNames[$indices[$i]]]) - ))->addDownCode($this->recordBuilder->alterColumn( - $this->model->getTableAlias(), - $this->tableSchema->columns[$wantNames[$indices[$i]]], - $this->findPosition($this->tableSchema->columns[$wantNames[$indices[$i]]], true) - )); - } -// $this->migration->addUpCode($this->recordBuilder->dropTable($this->model->getTableAlias())); - } - - public function setPositions() + public function setColumnsPositions() { $i = 0; $haveColumns = $this->tableSchema->columns; @@ -362,7 +281,7 @@ public function setPositions() continue; } - $column->isPositionReallyChanged = true; + $column->isPositionChanged = true; $takenIndices[] = [$column->fromPosition['index'], $column->toPosition['index']]; } } diff --git a/src/lib/migrations/PostgresMigrationBuilder.php b/src/lib/migrations/PostgresMigrationBuilder.php index 7fbc6419..82dcfc76 100644 --- a/src/lib/migrations/PostgresMigrationBuilder.php +++ b/src/lib/migrations/PostgresMigrationBuilder.php @@ -248,14 +248,6 @@ public function modifyDesiredInContextOfCurrent(ColumnSchema $current, ColumnSch } } - /** - * {@inheritDoc} - */ - public function handleColumnsPositionsChanges(array $haveNames, array $wantNames) - { - } - - /** * {@inheritDoc} */ @@ -264,7 +256,7 @@ public function findPosition(ColumnSchema $column, bool $forDrop = false, bool $ return null; } - public function setPositions() + public function setColumnsPositions() { } } From 815907e7eb5b411142d72be3061ff38f8f5a3fd9 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Mon, 14 Oct 2024 18:05:23 +0530 Subject: [PATCH 259/358] Refactor --- src/lib/migrations/BaseMigrationBuilder.php | 2 - src/lib/migrations/MigrationRecordBuilder.php | 2 +- src/lib/migrations/MysqlMigrationBuilder.php | 90 +++++-------------- 3 files changed, 23 insertions(+), 71 deletions(-) diff --git a/src/lib/migrations/BaseMigrationBuilder.php b/src/lib/migrations/BaseMigrationBuilder.php index 89b20ccd..1bd09e9b 100644 --- a/src/lib/migrations/BaseMigrationBuilder.php +++ b/src/lib/migrations/BaseMigrationBuilder.php @@ -222,8 +222,6 @@ function (string $unknownColumn) { $this->buildRelations(); } -// $this->handleColumnsPositionsChanges($haveNames, $wantNames); - return $this->migration; } diff --git a/src/lib/migrations/MigrationRecordBuilder.php b/src/lib/migrations/MigrationRecordBuilder.php index 0f7a2ca7..d624893b 100644 --- a/src/lib/migrations/MigrationRecordBuilder.php +++ b/src/lib/migrations/MigrationRecordBuilder.php @@ -158,7 +158,7 @@ public function alterColumnTypeFromDb( ColumnSchema $column, bool $addUsing = false, ?string $position = null - ) :string # TODO + ) :string { if (property_exists($column, 'xDbType') && is_string($column->xDbType) && !empty($column->xDbType)) { $converter = $this->columnToCode($tableAlias, $column, true, false, true, true, $position); diff --git a/src/lib/migrations/MysqlMigrationBuilder.php b/src/lib/migrations/MysqlMigrationBuilder.php index 2d8c6928..352daed5 100644 --- a/src/lib/migrations/MysqlMigrationBuilder.php +++ b/src/lib/migrations/MysqlMigrationBuilder.php @@ -31,14 +31,6 @@ protected function buildColumnChanges(ColumnSchema $current, ColumnSchema $desir unset($changed[$key]); } $newColumn = clone $current; -// $positionCurrent = $this->findPosition($desired, true); -// $positionDesired = $this->findPosition($desired); -// if ($positionCurrent === $positionDesired) { -// $positionCurrent = $positionDesired = null; -// } # else { -// $position = $positionDesired; -// $newColumn->position = $position; -// } foreach ($changed as $attr) { $newColumn->$attr = $desired->$attr; } @@ -82,10 +74,7 @@ protected function compareColumns(ColumnSchema $current, ColumnSchema $desired): } } -// $positionCurrent = $this->findPosition($desired, true); -// $positionDesired = $this->findPosition($desired); -// if ($positionCurrent !== $positionDesired) { - if ($desired->isPositionChanged) { + if (property_exists($desired, 'isPositionChanged') && $desired->isPositionChanged) { $changedAttributes[] = 'position'; } @@ -226,6 +215,8 @@ public function setColumnsPositions() $haveColumns = $this->tableSchema->columns; $wantNames = array_keys($this->newColumns); $haveNames = array_keys($haveColumns); + + // Part 1/2 compute from and to position foreach ($this->newColumns as $name => $column) { /** @var \cebe\yii2openapi\db\ColumnSchema $column */ $column->toPosition = [ @@ -246,6 +237,25 @@ public function setColumnsPositions() $i++; } + // Part 2/2 compute is position is really changed + + // check if only new columns are added without any explicit position change + $namesForCreate = array_diff($wantNames, $haveNames); + $wantNamesWoNewCols = array_values(array_diff($wantNames, $namesForCreate)); + if ($namesForCreate && $haveNames === $wantNamesWoNewCols) { + return; + } + // check if only existing columns are deleted without any explicit position change + $namesForDrop = array_diff($haveNames, $wantNames); + $haveNamesWoDropCols = array_values(array_diff($haveNames, $namesForDrop)); + if ($namesForDrop && $wantNames === $haveNamesWoDropCols) { + return; + } + // check both above simultaneously + if ($namesForCreate && $namesForDrop && ($wantNamesWoNewCols === $haveNamesWoDropCols)) { + return; + } + $takenIndices = []; foreach ($this->newColumns as $column) { /** @var \cebe\yii2openapi\db\ColumnSchema $column */ @@ -253,24 +263,6 @@ public function setColumnsPositions() if (!$column->fromPosition || !$column->toPosition) { continue; } - - // check if only new columns are added without any explicit position change - $namesForCreate = array_diff($wantNames, $haveNames); - $wantNamesWoNewCols = array_values(array_diff($wantNames, $namesForCreate)); - if ($namesForCreate && $haveNames === $wantNamesWoNewCols) { - continue; - } - // check if only existing columns are deleted without any explicit position change - $namesForDrop = array_diff($haveNames, $wantNames); - $haveNamesWoDropCols = array_values(array_diff($haveNames, $namesForDrop)); - if ($namesForDrop && $wantNames === $haveNamesWoDropCols) { - continue; - } - // check both above simultaneously - if ($namesForCreate && $namesForDrop && ($wantNamesWoNewCols === $haveNamesWoDropCols)) { - continue; - } - if (is_int(array_search([$column->toPosition['index'], $column->fromPosition['index']], $takenIndices))) { continue; } @@ -285,42 +277,4 @@ public function setColumnsPositions() $takenIndices[] = [$column->fromPosition['index'], $column->toPosition['index']]; } } - - public function checkAfterPosition($column) - { - if ($column->fromPosition['after'] === $column->toPosition['after'] - ) { - $afterColName = $column->toPosition['after']; - $afterCol = $this->newColumns[$afterColName] ?? null; - if ($afterCol) { - if ($this->checkAfterPosition($afterCol)) { - return true; - } else { - return false; - } - } else { - return true; - } - } - return false; - } - - public function checkBeforePosition($column) - { - if ($column->fromPosition['before'] === $column->toPosition['before'] - ) { - $beforeColName = $column->toPosition['before']; - $beforeCol = $this->newColumns[$beforeColName] ?? null; - if ($beforeCol) { - if ($this->checkBeforePosition($beforeCol)) { - return true; - } else { - return false; - } - } else { - return true; - } - } - return false; - } } From edbd140e3e13a6a0a9b859a58c3f8fa0fb84e4b3 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Tue, 15 Oct 2024 18:42:01 +0530 Subject: [PATCH 260/358] Add more tests + refactor `setColumnsPositions()` to remove unwanted migrations --- src/lib/migrations/MigrationRecordBuilder.php | 3 +- src/lib/migrations/MysqlMigrationBuilder.php | 29 ++- tests/unit/IssueFixTest.php | 192 +++++++++++++++++- 3 files changed, 217 insertions(+), 7 deletions(-) diff --git a/src/lib/migrations/MigrationRecordBuilder.php b/src/lib/migrations/MigrationRecordBuilder.php index d624893b..73fdce7d 100644 --- a/src/lib/migrations/MigrationRecordBuilder.php +++ b/src/lib/migrations/MigrationRecordBuilder.php @@ -158,8 +158,7 @@ public function alterColumnTypeFromDb( ColumnSchema $column, bool $addUsing = false, ?string $position = null - ) :string - { + ) :string { if (property_exists($column, 'xDbType') && is_string($column->xDbType) && !empty($column->xDbType)) { $converter = $this->columnToCode($tableAlias, $column, true, false, true, true, $position); return sprintf( diff --git a/src/lib/migrations/MysqlMigrationBuilder.php b/src/lib/migrations/MysqlMigrationBuilder.php index 352daed5..778a042f 100644 --- a/src/lib/migrations/MysqlMigrationBuilder.php +++ b/src/lib/migrations/MysqlMigrationBuilder.php @@ -256,7 +256,7 @@ public function setColumnsPositions() return; } - $takenIndices = []; + $takenIndices = $redundantIndices = []; # $redundantIndices are the unwanted ones which are created by moving of one or more columns. Example: if a column is moved from 2nd to 8th position then we will consider only one column is moved ignoring index/position change(-1) of 4rd to 8th column (4->3, 5->4 ...). So migration for this unwanted indices changes won't be generated foreach ($this->newColumns as $column) { /** @var \cebe\yii2openapi\db\ColumnSchema $column */ @@ -275,6 +275,33 @@ public function setColumnsPositions() $column->isPositionChanged = true; $takenIndices[] = [$column->fromPosition['index'], $column->toPosition['index']]; + + // ------- + if (($column->fromPosition['before'] !== $column->toPosition['before']) && + ($column->fromPosition['after'] !== $column->toPosition['after']) + ) { + $redundantIndices[] = [$column->fromPosition['index'], $column->toPosition['index']]; + } + } + + foreach ($this->newColumns as $column) { + /** @var \cebe\yii2openapi\db\ColumnSchema $column */ + + if (!isset($column->toPosition['index'], $column->fromPosition['index'])) { + continue; + } + $condition = (abs($column->toPosition['index'] - $column->fromPosition['index']) === count($redundantIndices)); + if (($column->fromPosition['before'] === $column->toPosition['before']) + && $condition + ) { + $column->isPositionChanged = false; + continue; + } + if (($column->fromPosition['after'] === $column->toPosition['after']) + && $condition + ) { + $column->isPositionChanged = false; + } } } } diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index f1d2410c..1c745376 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -1273,14 +1273,10 @@ public function up() $this->addColumn('{{%fruits}}', 'col_6', $this->boolean()->null()->defaultValue(null)); $this->dropColumn('{{%fruits}}', 'size'); $this->alterColumn('{{%fruits}}', 'colour', $this->tinyInteger(1)->null()->defaultValue(null)->after('id')); - $this->alterColumn('{{%fruits}}', 'name', $this->tinyInteger(1)->null()->defaultValue(null)->after('colour')); - $this->alterColumn('{{%fruits}}', 'description', $this->tinyInteger(1)->null()->defaultValue(null)->after('name')); } public function down() { - $this->alterColumn('{{%fruits}}', 'description', $this->tinyInteger(1)->null()->defaultValue(null)->after('name')); - $this->alterColumn('{{%fruits}}', 'name', $this->tinyInteger(1)->null()->defaultValue(null)->after('id')); $this->alterColumn('{{%fruits}}', 'colour', $this->tinyInteger(1)->null()->defaultValue(null)->after('description')); $this->addColumn('{{%fruits}}', 'size', $this->tinyInteger(1)->null()->defaultValue(null)); $this->dropColumn('{{%fruits}}', 'col_6'); @@ -1493,4 +1489,192 @@ public function down() // // $this->for58($schema, $expected, $columns); // } + + public function test58MoveAColAndChangeItsDataType() + { + $columns = [ + 'id' => 'pk', + 'name' => 'bool null', + 'description' => 'bool null', + 'colour' => 'bool null', + 'size' => 'bool null', + ]; + + $schema = <<alterColumn('{{%fruits}}', 'colour', $this->integer()->null()->defaultValue(null)); + $this->alterColumn('{{%fruits}}', 'name', $this->tinyInteger(1)->null()->defaultValue(null)->after('colour')); + } + + public function down() + { + $this->alterColumn('{{%fruits}}', 'name', $this->tinyInteger(1)->null()->defaultValue(null)->after('id')); + $this->alterColumn('{{%fruits}}', 'colour', $this->tinyInteger(1)->null()->defaultValue(null)); + } +} + +PHP; + + $this->for58($schema, $expected, $columns); + } + + public function test58MoveAColDownwards() + { + $columns = [ + 'id' => 'pk', + 'name' => 'bool null', + 'description' => 'bool null', + 'colour' => 'bool null', + 'size' => 'bool null', + ]; + + $schema = <<alterColumn('{{%fruits}}', 'name', $this->tinyInteger(1)->null()->defaultValue(null)->after('colour')); + } + + public function down() + { + $this->alterColumn('{{%fruits}}', 'name', $this->tinyInteger(1)->null()->defaultValue(null)->after('id')); + } +} + +PHP; + + $this->for58($schema, $expected, $columns); + } + + public function test58MoveAColUpwards() + { + $columns = [ + 'id' => 'pk', + 'name' => 'bool null', + 'description' => 'bool null', + 'colour' => 'bool null', + 'size' => 'bool null', + ]; + + $schema = <<alterColumn('{{%fruits}}', 'colour', $this->tinyInteger(1)->null()->defaultValue(null)->after('id')); + } + + public function down() + { + $this->alterColumn('{{%fruits}}', 'colour', $this->tinyInteger(1)->null()->defaultValue(null)->after('description')); + } +} + +PHP; + + $this->for58($schema, $expected, $columns); + } } From 7cb8ab86b71e5b133a0d75f04e9348a6d311e360 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Tue, 15 Oct 2024 18:46:39 +0530 Subject: [PATCH 261/358] Modify variable name --- src/lib/migrations/MysqlMigrationBuilder.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/lib/migrations/MysqlMigrationBuilder.php b/src/lib/migrations/MysqlMigrationBuilder.php index 778a042f..b28040a0 100644 --- a/src/lib/migrations/MysqlMigrationBuilder.php +++ b/src/lib/migrations/MysqlMigrationBuilder.php @@ -256,7 +256,7 @@ public function setColumnsPositions() return; } - $takenIndices = $redundantIndices = []; # $redundantIndices are the unwanted ones which are created by moving of one or more columns. Example: if a column is moved from 2nd to 8th position then we will consider only one column is moved ignoring index/position change(-1) of 4rd to 8th column (4->3, 5->4 ...). So migration for this unwanted indices changes won't be generated + $takenIndices = $nonRedundantIndices = []; # $nonRedundantIndices are the wanted ones which are created by moving of one or more columns. Example: if a column is moved from 2nd to 8th position then we will consider only one column is moved ignoring index/position change(-1) of 4rd to 8th column (4->3, 5->4 ...). So migration for this unwanted indices changes won't be generated. `$takenIndices` might have redundant indices foreach ($this->newColumns as $column) { /** @var \cebe\yii2openapi\db\ColumnSchema $column */ @@ -280,7 +280,7 @@ public function setColumnsPositions() if (($column->fromPosition['before'] !== $column->toPosition['before']) && ($column->fromPosition['after'] !== $column->toPosition['after']) ) { - $redundantIndices[] = [$column->fromPosition['index'], $column->toPosition['index']]; + $nonRedundantIndices[] = [$column->fromPosition['index'], $column->toPosition['index']]; } } @@ -290,7 +290,7 @@ public function setColumnsPositions() if (!isset($column->toPosition['index'], $column->fromPosition['index'])) { continue; } - $condition = (abs($column->toPosition['index'] - $column->fromPosition['index']) === count($redundantIndices)); + $condition = (abs($column->toPosition['index'] - $column->fromPosition['index']) === count($nonRedundantIndices)); if (($column->fromPosition['before'] === $column->toPosition['before']) && $condition ) { From abd59d42e996589ee8361cb0e701a6fef28e9bcc Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Thu, 17 Oct 2024 09:57:45 +0530 Subject: [PATCH 262/358] Create pull request --- .../mysql/x_db_default_expression_mysql.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/specs/x_db_default_expression/mysql/x_db_default_expression_mysql.php b/tests/specs/x_db_default_expression/mysql/x_db_default_expression_mysql.php index 5fd47d1b..dc4ebbb8 100644 --- a/tests/specs/x_db_default_expression/mysql/x_db_default_expression_mysql.php +++ b/tests/specs/x_db_default_expression/mysql/x_db_default_expression_mysql.php @@ -3,7 +3,7 @@ return [ 'openApiPath' => '@specs/x_db_default_expression/mysql/x_db_default_expression_mysql.yaml', 'generateUrls' => false, - 'generateModels' => false, + 'generateModels' => true, 'excludeModels' => [ 'Error', ], From 6ac19dcecb6d74b3e8197a7a8f0185d0ea4b147d Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Wed, 30 Oct 2024 17:58:01 +0530 Subject: [PATCH 263/358] Fix this issue --- src/generator/default/dbmodel.php | 8 ++++---- src/lib/ValidationRulesBuilder.php | 20 ++++++++++++++------ src/lib/items/DbModel.php | 13 +++++++++++-- tests/unit/IssueFixTest.php | 14 ++++++++++++++ 4 files changed, 43 insertions(+), 12 deletions(-) diff --git a/src/generator/default/dbmodel.php b/src/generator/default/dbmodel.php index 17fa4a84..a3d269b6 100644 --- a/src/generator/default/dbmodel.php +++ b/src/generator/default/dbmodel.php @@ -49,8 +49,8 @@ */ abstract class getClassName() ?> extends \yii\db\ActiveRecord { -getScenarios()): -foreach($scenarios as $scenario): ?> +getScenarios()): +foreach ($scenarios as $scenario): ?> /** * @@ -76,7 +76,7 @@ public static function tableName() { return getTableAlias()) ?>; } - + /** * Automatically generated scenarios from the model 'x-scenarios'. @@ -92,7 +92,7 @@ public function scenarios() $default = parent::scenarios()[self::SCENARIO_DEFAULT]; return [ - + self:: => $default, /** diff --git a/src/lib/ValidationRulesBuilder.php b/src/lib/ValidationRulesBuilder.php index 3f3c1398..f8e3bacf 100644 --- a/src/lib/ValidationRulesBuilder.php +++ b/src/lib/ValidationRulesBuilder.php @@ -10,8 +10,7 @@ use cebe\yii2openapi\lib\items\Attribute; use cebe\yii2openapi\lib\items\DbModel; use cebe\yii2openapi\lib\items\ValidationRule; -use yii\helpers\VarDumper; -use yii\validators\DateValidator; +use yii\db\Expression; use function count; use function implode; use function in_array; @@ -192,12 +191,11 @@ private function defaultRule(Attribute $attribute):void if ($attribute->defaultValue === null) { return; } - if ($attribute->defaultValue instanceof \yii\db\Expression) { - return; - } $params = []; - $params['value'] = $attribute->defaultValue; + $params['value'] = ($attribute->defaultValue instanceof \yii\db\Expression) ? + $this->f($attribute->defaultValue) : + $attribute->defaultValue; $key = $attribute->columnName . '_default'; $this->rules[$key] = new ValidationRule([$attribute->columnName], 'default', $params); } @@ -251,4 +249,14 @@ private function prepareTypeScope():void $this->typeScope['safe'][$attribute->columnName] = $attribute->columnName; } } + + private function f($dbExpr) // TODO rename + { + return new class($dbExpr->expression) extends Expression { + public function __toString() + { + return '-yii-db-expression-starts-("' . $this->expression . '")-yii-db-expression-ends-'; + } + }; + } } diff --git a/src/lib/items/DbModel.php b/src/lib/items/DbModel.php index 5c33c09b..2dbb3581 100644 --- a/src/lib/items/DbModel.php +++ b/src/lib/items/DbModel.php @@ -13,7 +13,6 @@ use yii\base\BaseObject; use yii\db\ColumnSchema; use yii\helpers\Inflector; -use yii\helpers\StringHelper; use yii\helpers\VarDumper; use function array_filter; use function array_map; @@ -109,7 +108,8 @@ public function getValidationRules():string $rules = Yii::createObject(ValidationRulesBuilder::class, [$this])->build(); $rules = array_map('strval', $rules); $rules = VarDumper::export($rules); - return str_replace([ + + $rules = str_replace([ PHP_EOL, "\'", "'[[", @@ -120,6 +120,15 @@ public function getValidationRules():string '[[', '],' ], $rules); + + $rules = str_replace( + ["'value' => '-yii-db-expression-starts-", "-yii-db-expression-ends-'"], + ["'value' => new \yii\db\Expression", ""], + $rules, + $count + ); + + return $rules; } /** diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index b6c7abdb..31c37c08 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -360,4 +360,18 @@ public function test158BugGiiapiGeneratedRulesEnumWithTrim() ]); $this->checkFiles($actualFiles, $expectedFiles); } + + // https://github.com/php-openapi/yii2-openapi/issues/65 + // public function test65DefaultValueByConstantAndExpressionInCrudModelsFakerEtc() + // { + // $testFile = Yii::getAlias("@specs/issue_fix/65_default_value_by_constant_and_expression_in_crud_models_faker_etc/index.php"); + // $this->runGenerator($testFile); + // $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ + // 'recursive' => true, + // ]); + // $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/65_default_value_by_constant_and_expression_in_crud_models_faker_etc/mysql"), [ + // 'recursive' => true, + // ]); + // // $this->checkFiles($actualFiles, $expectedFiles); // TODO + // } } From f85a93bf412b4c5f5f643218105ba14562c4c6d9 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Thu, 31 Oct 2024 18:04:46 +0530 Subject: [PATCH 264/358] Fix failing tests + refactor --- src/lib/ValidationRulesBuilder.php | 4 +- src/lib/items/DbModel.php | 1 - .../maria/simple/app/models/Fruit.php | 10 ++++ .../maria/simple/app/models/base/Fruit.php | 57 +++++++++++++++++++ .../mysql/simple/app/models/Fruit.php | 10 ++++ .../mysql/simple/app/models/base/Fruit.php | 57 +++++++++++++++++++ .../pgsql/simple/app/models/Fruit.php | 10 ++++ .../pgsql/simple/app/models/base/Fruit.php | 57 +++++++++++++++++++ 8 files changed, 203 insertions(+), 3 deletions(-) create mode 100644 tests/specs/x_db_default_expression/maria/simple/app/models/Fruit.php create mode 100644 tests/specs/x_db_default_expression/maria/simple/app/models/base/Fruit.php create mode 100644 tests/specs/x_db_default_expression/mysql/simple/app/models/Fruit.php create mode 100644 tests/specs/x_db_default_expression/mysql/simple/app/models/base/Fruit.php create mode 100644 tests/specs/x_db_default_expression/pgsql/simple/app/models/Fruit.php create mode 100644 tests/specs/x_db_default_expression/pgsql/simple/app/models/base/Fruit.php diff --git a/src/lib/ValidationRulesBuilder.php b/src/lib/ValidationRulesBuilder.php index f8e3bacf..87337a42 100644 --- a/src/lib/ValidationRulesBuilder.php +++ b/src/lib/ValidationRulesBuilder.php @@ -194,7 +194,7 @@ private function defaultRule(Attribute $attribute):void $params = []; $params['value'] = ($attribute->defaultValue instanceof \yii\db\Expression) ? - $this->f($attribute->defaultValue) : + $this->wrapDefaultExpression($attribute->defaultValue) : $attribute->defaultValue; $key = $attribute->columnName . '_default'; $this->rules[$key] = new ValidationRule([$attribute->columnName], 'default', $params); @@ -250,7 +250,7 @@ private function prepareTypeScope():void } } - private function f($dbExpr) // TODO rename + private function wrapDefaultExpression(Expression $dbExpr): Expression { return new class($dbExpr->expression) extends Expression { public function __toString() diff --git a/src/lib/items/DbModel.php b/src/lib/items/DbModel.php index 2dbb3581..b647544e 100644 --- a/src/lib/items/DbModel.php +++ b/src/lib/items/DbModel.php @@ -125,7 +125,6 @@ public function getValidationRules():string ["'value' => '-yii-db-expression-starts-", "-yii-db-expression-ends-'"], ["'value' => new \yii\db\Expression", ""], $rules, - $count ); return $rules; diff --git a/tests/specs/x_db_default_expression/maria/simple/app/models/Fruit.php b/tests/specs/x_db_default_expression/maria/simple/app/models/Fruit.php new file mode 100644 index 00000000..c74c53d9 --- /dev/null +++ b/tests/specs/x_db_default_expression/maria/simple/app/models/Fruit.php @@ -0,0 +1,10 @@ + [['ts', 'ts2', 'ts3', 'ts4', 'ts5', 'ts6', 'd', 'd2', 'd3', 'ts7'], 'trim'], + 'ts_datetime' => [['ts'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], + 'ts_default' => [['ts'], 'default', 'value' => new \yii\db\Expression("(CURRENT_TIMESTAMP)")], + 'ts2_datetime' => [['ts2'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], + 'ts2_default' => [['ts2'], 'default', 'value' => '2011-11-11 00:00:00'], + 'ts3_datetime' => [['ts3'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], + 'ts3_default' => [['ts3'], 'default', 'value' => '2022-11-11 00:00:00'], + 'ts4_string' => [['ts4'], 'string'], + 'ts4_default' => [['ts4'], 'default', 'value' => '2022-11-11 00:00:00'], + 'ts5_string' => [['ts5'], 'string'], + 'ts5_default' => [['ts5'], 'default', 'value' => new \yii\db\Expression("(CURRENT_TIMESTAMP)")], + 'ts6_string' => [['ts6'], 'string'], + 'ts6_default' => [['ts6'], 'default', 'value' => '2000-11-11 00:00:00'], + 'd_date' => [['d'], 'date', 'format' => 'php:Y-m-d'], + 'd_default' => [['d'], 'default', 'value' => new \yii\db\Expression("(CURRENT_DATE + INTERVAL 1 YEAR)")], + 'd2_string' => [['d2'], 'string'], + 'd2_default' => [['d2'], 'default', 'value' => new \yii\db\Expression("(CURRENT_DATE + INTERVAL 1 YEAR)")], + 'd3_string' => [['d3'], 'string'], + 'd3_default' => [['d3'], 'default', 'value' => 'text default'], + 'ts7_date' => [['ts7'], 'date', 'format' => 'php:Y-m-d'], + 'ts7_default' => [['ts7'], 'default', 'value' => new \yii\db\Expression("(CURRENT_DATE + INTERVAL 1 YEAR)")], + ]; + } +} diff --git a/tests/specs/x_db_default_expression/mysql/simple/app/models/Fruit.php b/tests/specs/x_db_default_expression/mysql/simple/app/models/Fruit.php new file mode 100644 index 00000000..c74c53d9 --- /dev/null +++ b/tests/specs/x_db_default_expression/mysql/simple/app/models/Fruit.php @@ -0,0 +1,10 @@ + [['ts', 'ts2', 'ts3', 'ts4', 'ts5', 'ts6', 'd', 'd2', 'd3', 'ts7'], 'trim'], + 'ts_datetime' => [['ts'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], + 'ts_default' => [['ts'], 'default', 'value' => new \yii\db\Expression("(CURRENT_TIMESTAMP)")], + 'ts2_datetime' => [['ts2'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], + 'ts2_default' => [['ts2'], 'default', 'value' => '2011-11-11 00:00:00'], + 'ts3_datetime' => [['ts3'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], + 'ts3_default' => [['ts3'], 'default', 'value' => '2022-11-11 00:00:00'], + 'ts4_string' => [['ts4'], 'string'], + 'ts4_default' => [['ts4'], 'default', 'value' => '2022-11-11 00:00:00'], + 'ts5_string' => [['ts5'], 'string'], + 'ts5_default' => [['ts5'], 'default', 'value' => new \yii\db\Expression("(CURRENT_TIMESTAMP)")], + 'ts6_string' => [['ts6'], 'string'], + 'ts6_default' => [['ts6'], 'default', 'value' => '2000-11-11 00:00:00'], + 'd_date' => [['d'], 'date', 'format' => 'php:Y-m-d'], + 'd_default' => [['d'], 'default', 'value' => new \yii\db\Expression("(CURRENT_DATE + INTERVAL 1 YEAR)")], + 'd2_string' => [['d2'], 'string'], + 'd2_default' => [['d2'], 'default', 'value' => new \yii\db\Expression("(CURRENT_DATE + INTERVAL 1 YEAR)")], + 'd3_string' => [['d3'], 'string'], + 'd3_default' => [['d3'], 'default', 'value' => 'text default'], + 'ts7_date' => [['ts7'], 'date', 'format' => 'php:Y-m-d'], + 'ts7_default' => [['ts7'], 'default', 'value' => new \yii\db\Expression("(CURRENT_DATE + INTERVAL 1 YEAR)")], + ]; + } +} diff --git a/tests/specs/x_db_default_expression/pgsql/simple/app/models/Fruit.php b/tests/specs/x_db_default_expression/pgsql/simple/app/models/Fruit.php new file mode 100644 index 00000000..c74c53d9 --- /dev/null +++ b/tests/specs/x_db_default_expression/pgsql/simple/app/models/Fruit.php @@ -0,0 +1,10 @@ + [['ts', 'ts2', 'ts3', 'ts4', 'ts5', 'ts6', 'd', 'd2', 'd3', 'ts7'], 'trim'], + 'ts_datetime' => [['ts'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], + 'ts_default' => [['ts'], 'default', 'value' => new \yii\db\Expression("(CURRENT_TIMESTAMP)")], + 'ts2_datetime' => [['ts2'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], + 'ts2_default' => [['ts2'], 'default', 'value' => '2011-11-11 00:00:00'], + 'ts3_datetime' => [['ts3'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], + 'ts3_default' => [['ts3'], 'default', 'value' => '2022-11-11 00:00:00'], + 'ts4_string' => [['ts4'], 'string'], + 'ts4_default' => [['ts4'], 'default', 'value' => '2022-11-11 00:00:00'], + 'ts5_string' => [['ts5'], 'string'], + 'ts5_default' => [['ts5'], 'default', 'value' => new \yii\db\Expression("(CURRENT_TIMESTAMP)")], + 'ts6_string' => [['ts6'], 'string'], + 'ts6_default' => [['ts6'], 'default', 'value' => '2000-11-11 00:00:00'], + 'd_date' => [['d'], 'date', 'format' => 'php:Y-m-d'], + 'd_default' => [['d'], 'default', 'value' => new \yii\db\Expression("(CURRENT_DATE + INTERVAL 1 YEAR)")], + 'd2_string' => [['d2'], 'string'], + 'd2_default' => [['d2'], 'default', 'value' => new \yii\db\Expression("(CURRENT_DATE + INTERVAL 1 YEAR)")], + 'd3_string' => [['d3'], 'string'], + 'd3_default' => [['d3'], 'default', 'value' => 'text default'], + 'ts7_date' => [['ts7'], 'date', 'format' => 'php:Y-m-d'], + 'ts7_default' => [['ts7'], 'default', 'value' => new \yii\db\Expression("(CURRENT_DATE + INTERVAL 1 YEAR)")], + ]; + } +} From 5b3f446ecf75372e24448ad17ab416f545e66975 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Thu, 31 Oct 2024 18:06:35 +0530 Subject: [PATCH 265/358] Fix another failing tests --- .../edit_expression/app/models/Fruit.php | 10 ++++ .../edit_expression/app/models/base/Fruit.php | 57 +++++++++++++++++++ .../edit_expression/app/models/Fruit.php | 10 ++++ .../edit_expression/app/models/base/Fruit.php | 57 +++++++++++++++++++ .../edit_expression/app/models/Fruit.php | 10 ++++ .../edit_expression/app/models/base/Fruit.php | 57 +++++++++++++++++++ 6 files changed, 201 insertions(+) create mode 100644 tests/specs/x_db_default_expression/maria/edit_expression/app/models/Fruit.php create mode 100644 tests/specs/x_db_default_expression/maria/edit_expression/app/models/base/Fruit.php create mode 100644 tests/specs/x_db_default_expression/mysql/edit_expression/app/models/Fruit.php create mode 100644 tests/specs/x_db_default_expression/mysql/edit_expression/app/models/base/Fruit.php create mode 100644 tests/specs/x_db_default_expression/pgsql/edit_expression/app/models/Fruit.php create mode 100644 tests/specs/x_db_default_expression/pgsql/edit_expression/app/models/base/Fruit.php diff --git a/tests/specs/x_db_default_expression/maria/edit_expression/app/models/Fruit.php b/tests/specs/x_db_default_expression/maria/edit_expression/app/models/Fruit.php new file mode 100644 index 00000000..c74c53d9 --- /dev/null +++ b/tests/specs/x_db_default_expression/maria/edit_expression/app/models/Fruit.php @@ -0,0 +1,10 @@ + [['ts', 'ts2', 'ts3', 'ts4', 'ts5', 'ts6', 'd', 'd2', 'd3', 'ts7'], 'trim'], + 'ts_datetime' => [['ts'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], + 'ts_default' => [['ts'], 'default', 'value' => new \yii\db\Expression("(CURRENT_TIMESTAMP)")], + 'ts2_datetime' => [['ts2'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], + 'ts2_default' => [['ts2'], 'default', 'value' => '2011-11-11 00:00:00'], + 'ts3_datetime' => [['ts3'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], + 'ts3_default' => [['ts3'], 'default', 'value' => '2022-11-11 00:00:00'], + 'ts4_string' => [['ts4'], 'string'], + 'ts4_default' => [['ts4'], 'default', 'value' => '2022-11-11 00:00:00'], + 'ts5_string' => [['ts5'], 'string'], + 'ts5_default' => [['ts5'], 'default', 'value' => new \yii\db\Expression("(CURRENT_TIMESTAMP)")], + 'ts6_string' => [['ts6'], 'string'], + 'ts6_default' => [['ts6'], 'default', 'value' => '2000-11-11 00:00:00'], + 'd_date' => [['d'], 'date', 'format' => 'php:Y-m-d'], + 'd_default' => [['d'], 'default', 'value' => new \yii\db\Expression("(CURRENT_DATE + INTERVAL 1 YEAR)")], + 'd2_string' => [['d2'], 'string'], + 'd2_default' => [['d2'], 'default', 'value' => new \yii\db\Expression("(CURRENT_DATE + INTERVAL 1 YEAR)")], + 'd3_string' => [['d3'], 'string'], + 'd3_default' => [['d3'], 'default', 'value' => 'text default'], + 'ts7_date' => [['ts7'], 'date', 'format' => 'php:Y-m-d'], + 'ts7_default' => [['ts7'], 'default', 'value' => new \yii\db\Expression("(CURRENT_DATE + INTERVAL 1 YEAR)")], + ]; + } +} diff --git a/tests/specs/x_db_default_expression/mysql/edit_expression/app/models/Fruit.php b/tests/specs/x_db_default_expression/mysql/edit_expression/app/models/Fruit.php new file mode 100644 index 00000000..c74c53d9 --- /dev/null +++ b/tests/specs/x_db_default_expression/mysql/edit_expression/app/models/Fruit.php @@ -0,0 +1,10 @@ + [['ts', 'ts2', 'ts3', 'ts4', 'ts5', 'ts6', 'd', 'd2', 'd3', 'ts7'], 'trim'], + 'ts_datetime' => [['ts'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], + 'ts_default' => [['ts'], 'default', 'value' => new \yii\db\Expression("(CURRENT_TIMESTAMP)")], + 'ts2_datetime' => [['ts2'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], + 'ts2_default' => [['ts2'], 'default', 'value' => '2011-11-11 00:00:00'], + 'ts3_datetime' => [['ts3'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], + 'ts3_default' => [['ts3'], 'default', 'value' => '2022-11-11 00:00:00'], + 'ts4_string' => [['ts4'], 'string'], + 'ts4_default' => [['ts4'], 'default', 'value' => '2022-11-11 00:00:00'], + 'ts5_string' => [['ts5'], 'string'], + 'ts5_default' => [['ts5'], 'default', 'value' => new \yii\db\Expression("(CURRENT_TIMESTAMP)")], + 'ts6_string' => [['ts6'], 'string'], + 'ts6_default' => [['ts6'], 'default', 'value' => '2000-11-11 00:00:00'], + 'd_date' => [['d'], 'date', 'format' => 'php:Y-m-d'], + 'd_default' => [['d'], 'default', 'value' => new \yii\db\Expression("(CURRENT_DATE + INTERVAL 1 YEAR)")], + 'd2_string' => [['d2'], 'string'], + 'd2_default' => [['d2'], 'default', 'value' => new \yii\db\Expression("(CURRENT_DATE + INTERVAL 1 YEAR)")], + 'd3_string' => [['d3'], 'string'], + 'd3_default' => [['d3'], 'default', 'value' => 'text default'], + 'ts7_date' => [['ts7'], 'date', 'format' => 'php:Y-m-d'], + 'ts7_default' => [['ts7'], 'default', 'value' => new \yii\db\Expression("(CURRENT_DATE + INTERVAL 1 YEAR)")], + ]; + } +} diff --git a/tests/specs/x_db_default_expression/pgsql/edit_expression/app/models/Fruit.php b/tests/specs/x_db_default_expression/pgsql/edit_expression/app/models/Fruit.php new file mode 100644 index 00000000..c74c53d9 --- /dev/null +++ b/tests/specs/x_db_default_expression/pgsql/edit_expression/app/models/Fruit.php @@ -0,0 +1,10 @@ + [['ts', 'ts2', 'ts3', 'ts4', 'ts5', 'ts6', 'd', 'd2', 'd3', 'ts7'], 'trim'], + 'ts_datetime' => [['ts'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], + 'ts_default' => [['ts'], 'default', 'value' => new \yii\db\Expression("(CURRENT_TIMESTAMP)")], + 'ts2_datetime' => [['ts2'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], + 'ts2_default' => [['ts2'], 'default', 'value' => '2011-11-11 00:00:00'], + 'ts3_datetime' => [['ts3'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], + 'ts3_default' => [['ts3'], 'default', 'value' => '2022-11-11 00:00:00'], + 'ts4_string' => [['ts4'], 'string'], + 'ts4_default' => [['ts4'], 'default', 'value' => '2022-11-11 00:00:00'], + 'ts5_string' => [['ts5'], 'string'], + 'ts5_default' => [['ts5'], 'default', 'value' => new \yii\db\Expression("(CURRENT_TIMESTAMP)")], + 'ts6_string' => [['ts6'], 'string'], + 'ts6_default' => [['ts6'], 'default', 'value' => '2000-11-11 00:00:00'], + 'd_date' => [['d'], 'date', 'format' => 'php:Y-m-d'], + 'd_default' => [['d'], 'default', 'value' => new \yii\db\Expression("(CURRENT_DATE + INTERVAL 1 YEAR)")], + 'd2_string' => [['d2'], 'string'], + 'd2_default' => [['d2'], 'default', 'value' => new \yii\db\Expression("(CURRENT_DATE + INTERVAL 1 YEAR)")], + 'd3_string' => [['d3'], 'string'], + 'd3_default' => [['d3'], 'default', 'value' => 'text default'], + 'ts7_date' => [['ts7'], 'date', 'format' => 'php:Y-m-d'], + 'ts7_default' => [['ts7'], 'default', 'value' => new \yii\db\Expression("(CURRENT_DATE + INTERVAL 1 YEAR)")], + ]; + } +} From 2a994684f77d46a4bdf560cfdd354f8d277a458f Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Thu, 31 Oct 2024 18:08:30 +0530 Subject: [PATCH 266/358] Fix another failing tests 2 --- .../maria/edit/app/models/Fruit.php | 10 ++++ .../maria/edit/app/models/base/Fruit.php | 57 +++++++++++++++++++ .../mysql/edit/app/models/Fruit.php | 10 ++++ .../mysql/edit/app/models/base/Fruit.php | 57 +++++++++++++++++++ .../pgsql/edit/app/models/Fruit.php | 10 ++++ .../pgsql/edit/app/models/base/Fruit.php | 57 +++++++++++++++++++ 6 files changed, 201 insertions(+) create mode 100644 tests/specs/x_db_default_expression/maria/edit/app/models/Fruit.php create mode 100644 tests/specs/x_db_default_expression/maria/edit/app/models/base/Fruit.php create mode 100644 tests/specs/x_db_default_expression/mysql/edit/app/models/Fruit.php create mode 100644 tests/specs/x_db_default_expression/mysql/edit/app/models/base/Fruit.php create mode 100644 tests/specs/x_db_default_expression/pgsql/edit/app/models/Fruit.php create mode 100644 tests/specs/x_db_default_expression/pgsql/edit/app/models/base/Fruit.php diff --git a/tests/specs/x_db_default_expression/maria/edit/app/models/Fruit.php b/tests/specs/x_db_default_expression/maria/edit/app/models/Fruit.php new file mode 100644 index 00000000..c74c53d9 --- /dev/null +++ b/tests/specs/x_db_default_expression/maria/edit/app/models/Fruit.php @@ -0,0 +1,10 @@ + [['ts', 'ts2', 'ts3', 'ts4', 'ts5', 'ts6', 'd', 'd2', 'd3', 'ts7'], 'trim'], + 'ts_datetime' => [['ts'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], + 'ts_default' => [['ts'], 'default', 'value' => new \yii\db\Expression("(CURRENT_TIMESTAMP)")], + 'ts2_datetime' => [['ts2'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], + 'ts2_default' => [['ts2'], 'default', 'value' => '2011-11-11 00:00:00'], + 'ts3_datetime' => [['ts3'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], + 'ts3_default' => [['ts3'], 'default', 'value' => '2022-11-11 00:00:00'], + 'ts4_string' => [['ts4'], 'string'], + 'ts4_default' => [['ts4'], 'default', 'value' => '2022-11-11 00:00:00'], + 'ts5_string' => [['ts5'], 'string'], + 'ts5_default' => [['ts5'], 'default', 'value' => new \yii\db\Expression("(CURRENT_TIMESTAMP)")], + 'ts6_string' => [['ts6'], 'string'], + 'ts6_default' => [['ts6'], 'default', 'value' => '2000-11-11 00:00:00'], + 'd_date' => [['d'], 'date', 'format' => 'php:Y-m-d'], + 'd_default' => [['d'], 'default', 'value' => new \yii\db\Expression("(CURRENT_DATE + INTERVAL 1 YEAR)")], + 'd2_string' => [['d2'], 'string'], + 'd2_default' => [['d2'], 'default', 'value' => new \yii\db\Expression("(CURRENT_DATE + INTERVAL 1 YEAR)")], + 'd3_string' => [['d3'], 'string'], + 'd3_default' => [['d3'], 'default', 'value' => 'text default'], + 'ts7_date' => [['ts7'], 'date', 'format' => 'php:Y-m-d'], + 'ts7_default' => [['ts7'], 'default', 'value' => new \yii\db\Expression("(CURRENT_DATE + INTERVAL 1 YEAR)")], + ]; + } +} diff --git a/tests/specs/x_db_default_expression/mysql/edit/app/models/Fruit.php b/tests/specs/x_db_default_expression/mysql/edit/app/models/Fruit.php new file mode 100644 index 00000000..c74c53d9 --- /dev/null +++ b/tests/specs/x_db_default_expression/mysql/edit/app/models/Fruit.php @@ -0,0 +1,10 @@ + [['ts', 'ts2', 'ts3', 'ts4', 'ts5', 'ts6', 'd', 'd2', 'd3', 'ts7'], 'trim'], + 'ts_datetime' => [['ts'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], + 'ts_default' => [['ts'], 'default', 'value' => new \yii\db\Expression("(CURRENT_TIMESTAMP)")], + 'ts2_datetime' => [['ts2'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], + 'ts2_default' => [['ts2'], 'default', 'value' => '2011-11-11 00:00:00'], + 'ts3_datetime' => [['ts3'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], + 'ts3_default' => [['ts3'], 'default', 'value' => '2022-11-11 00:00:00'], + 'ts4_string' => [['ts4'], 'string'], + 'ts4_default' => [['ts4'], 'default', 'value' => '2022-11-11 00:00:00'], + 'ts5_string' => [['ts5'], 'string'], + 'ts5_default' => [['ts5'], 'default', 'value' => new \yii\db\Expression("(CURRENT_TIMESTAMP)")], + 'ts6_string' => [['ts6'], 'string'], + 'ts6_default' => [['ts6'], 'default', 'value' => '2000-11-11 00:00:00'], + 'd_date' => [['d'], 'date', 'format' => 'php:Y-m-d'], + 'd_default' => [['d'], 'default', 'value' => new \yii\db\Expression("(CURRENT_DATE + INTERVAL 1 YEAR)")], + 'd2_string' => [['d2'], 'string'], + 'd2_default' => [['d2'], 'default', 'value' => new \yii\db\Expression("(CURRENT_DATE + INTERVAL 1 YEAR)")], + 'd3_string' => [['d3'], 'string'], + 'd3_default' => [['d3'], 'default', 'value' => 'text default'], + 'ts7_date' => [['ts7'], 'date', 'format' => 'php:Y-m-d'], + 'ts7_default' => [['ts7'], 'default', 'value' => new \yii\db\Expression("(CURRENT_DATE + INTERVAL 1 YEAR)")], + ]; + } +} diff --git a/tests/specs/x_db_default_expression/pgsql/edit/app/models/Fruit.php b/tests/specs/x_db_default_expression/pgsql/edit/app/models/Fruit.php new file mode 100644 index 00000000..c74c53d9 --- /dev/null +++ b/tests/specs/x_db_default_expression/pgsql/edit/app/models/Fruit.php @@ -0,0 +1,10 @@ + [['ts', 'ts2', 'ts3', 'ts4', 'ts5', 'ts6', 'd', 'd2', 'd3', 'ts7'], 'trim'], + 'ts_datetime' => [['ts'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], + 'ts_default' => [['ts'], 'default', 'value' => new \yii\db\Expression("(CURRENT_TIMESTAMP)")], + 'ts2_datetime' => [['ts2'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], + 'ts2_default' => [['ts2'], 'default', 'value' => '2011-11-11 00:00:00'], + 'ts3_datetime' => [['ts3'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], + 'ts3_default' => [['ts3'], 'default', 'value' => '2022-11-11 00:00:00'], + 'ts4_string' => [['ts4'], 'string'], + 'ts4_default' => [['ts4'], 'default', 'value' => '2022-11-11 00:00:00'], + 'ts5_string' => [['ts5'], 'string'], + 'ts5_default' => [['ts5'], 'default', 'value' => new \yii\db\Expression("(CURRENT_TIMESTAMP)")], + 'ts6_string' => [['ts6'], 'string'], + 'ts6_default' => [['ts6'], 'default', 'value' => '2000-11-11 00:00:00'], + 'd_date' => [['d'], 'date', 'format' => 'php:Y-m-d'], + 'd_default' => [['d'], 'default', 'value' => new \yii\db\Expression("(CURRENT_DATE + INTERVAL 1 YEAR)")], + 'd2_string' => [['d2'], 'string'], + 'd2_default' => [['d2'], 'default', 'value' => new \yii\db\Expression("(CURRENT_DATE + INTERVAL 1 YEAR)")], + 'd3_string' => [['d3'], 'string'], + 'd3_default' => [['d3'], 'default', 'value' => 'text default'], + 'ts7_date' => [['ts7'], 'date', 'format' => 'php:Y-m-d'], + 'ts7_default' => [['ts7'], 'default', 'value' => new \yii\db\Expression("(CURRENT_DATE + INTERVAL 1 YEAR)")], + ]; + } +} From ae1f6663a7980d500c7fe68c8de09a98eabbab35 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Thu, 31 Oct 2024 18:09:15 +0530 Subject: [PATCH 267/358] Fix another failing tests 3 --- tests/specs/blog/models/base/User.php | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/specs/blog/models/base/User.php b/tests/specs/blog/models/base/User.php index c7023d15..a2cff815 100644 --- a/tests/specs/blog/models/base/User.php +++ b/tests/specs/blog/models/base/User.php @@ -41,6 +41,7 @@ public function rules() 'flags_integer' => [['flags'], 'integer'], 'flags_default' => [['flags'], 'default', 'value' => 0], 'created_at_datetime' => [['created_at'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], + 'created_at_default' => [['created_at'], 'default', 'value' => new \yii\db\Expression("(CURRENT_TIMESTAMP)")], ]; } } From f8337b6226522d007d765a6b2a03961802083d5b Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Thu, 31 Oct 2024 18:12:49 +0530 Subject: [PATCH 268/358] Cleanup --- tests/unit/IssueFixTest.php | 14 -------------- 1 file changed, 14 deletions(-) diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index 31c37c08..b6c7abdb 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -360,18 +360,4 @@ public function test158BugGiiapiGeneratedRulesEnumWithTrim() ]); $this->checkFiles($actualFiles, $expectedFiles); } - - // https://github.com/php-openapi/yii2-openapi/issues/65 - // public function test65DefaultValueByConstantAndExpressionInCrudModelsFakerEtc() - // { - // $testFile = Yii::getAlias("@specs/issue_fix/65_default_value_by_constant_and_expression_in_crud_models_faker_etc/index.php"); - // $this->runGenerator($testFile); - // $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ - // 'recursive' => true, - // ]); - // $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/65_default_value_by_constant_and_expression_in_crud_models_faker_etc/mysql"), [ - // 'recursive' => true, - // ]); - // // $this->checkFiles($actualFiles, $expectedFiles); // TODO - // } } From f698ba3c8b72082c956f6d0d8b5728a3778850cb Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Thu, 31 Oct 2024 18:30:42 +0530 Subject: [PATCH 269/358] Create PR --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 1cd2090b..3bb79307 100644 --- a/README.md +++ b/README.md @@ -568,3 +568,4 @@ Professional support, consulting as well as software development services are av https://www.cebe.cc/en/contact Development of this library is sponsored by [cebe.:cloud: "Your Professional Deployment Platform"](https://cebe.cloud). + From c202b437c55fba608f8a8eceb27ac0635217d231 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Thu, 31 Oct 2024 18:31:33 +0530 Subject: [PATCH 270/358] Undo create PR --- README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/README.md b/README.md index 3bb79307..1cd2090b 100644 --- a/README.md +++ b/README.md @@ -568,4 +568,3 @@ Professional support, consulting as well as software development services are av https://www.cebe.cc/en/contact Development of this library is sponsored by [cebe.:cloud: "Your Professional Deployment Platform"](https://cebe.cloud). - From 8e14987cb12d0ab647bf3fa5d4ca430bd0d3bc72 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Thu, 31 Oct 2024 18:32:00 +0530 Subject: [PATCH 271/358] Add docs --- src/lib/items/DbModel.php | 1 + 1 file changed, 1 insertion(+) diff --git a/src/lib/items/DbModel.php b/src/lib/items/DbModel.php index b647544e..1586637f 100644 --- a/src/lib/items/DbModel.php +++ b/src/lib/items/DbModel.php @@ -121,6 +121,7 @@ public function getValidationRules():string '],' ], $rules); + // https://github.com/php-openapi/yii2-openapi/issues/65 $rules = str_replace( ["'value' => '-yii-db-expression-starts-", "-yii-db-expression-ends-'"], ["'value' => new \yii\db\Expression", ""], From 25063ca31866aa1cd01c95eea1814c05d9af0656 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Wed, 13 Nov 2024 18:21:22 +0530 Subject: [PATCH 272/358] Fix errors and failing tests --- composer.json | 4 ++-- src/lib/AttributeResolver.php | 4 ++-- src/lib/SchemaToDatabase.php | 1 - src/lib/items/Attribute.php | 2 ++ 4 files changed, 6 insertions(+), 5 deletions(-) diff --git a/composer.json b/composer.json index c8994ba8..115ef883 100644 --- a/composer.json +++ b/composer.json @@ -23,11 +23,11 @@ "yiisoft/yii2": "~2.0.48", "yiisoft/yii2-gii": "~2.0.0 | ~2.1.0 | ~2.2.0| ~2.3.0", "laminas/laminas-code": ">=3.4 <=4.13", - "php-openapi/yii2-fractal": "^1.0.0", + "php-openapi/yii2-fractal": "^1.4", "fakerphp/faker": "^1.9", "sam-it/yii2-mariadb": "^2.0", "symfony/var-exporter": "^5.4", - "symfony/polyfill-php80": "^1.30" + "symfony/polyfill-php80": "^1.31" }, "require-dev": { "cebe/indent": "*", diff --git a/src/lib/AttributeResolver.php b/src/lib/AttributeResolver.php index 3914a1a9..92014c6e 100644 --- a/src/lib/AttributeResolver.php +++ b/src/lib/AttributeResolver.php @@ -140,7 +140,7 @@ protected function resolveJunctionTableProperty(PropertySchema $property, bool $ ->setPhpType($junkAttribute['phpType']) ->setDbType($junkAttribute['dbType']) ->setForeignKeyColumnName($property->fkColName) - ->setTableName($this->schema->resolveTableName($this->schemaName)); + ->setTableName($this->componentSchema->resolveTableName($this->schemaName)); $relation = Yii::createObject(AttributeRelation::class, [ $property->getName(), $junkAttribute['relatedTableName'], @@ -229,7 +229,7 @@ protected function resolveProperty( ->setIsPrimary($property->isPrimaryKey()) ->setForeignKeyColumnName($property->fkColName) ->setFakerStub($this->guessFakerStub($attribute, $property)) - ->setTableName($this->schema->resolveTableName($this->schemaName)); + ->setTableName($this->componentSchema->resolveTableName($this->schemaName)); if ($property->isReference()) { if ($property->isVirtual()) { throw new InvalidDefinitionException('References not supported for virtual attributes'); diff --git a/src/lib/SchemaToDatabase.php b/src/lib/SchemaToDatabase.php index 6d8284ed..221a8cec 100644 --- a/src/lib/SchemaToDatabase.php +++ b/src/lib/SchemaToDatabase.php @@ -13,7 +13,6 @@ use cebe\yii2openapi\generator\ApiGenerator; use cebe\yii2openapi\lib\exceptions\InvalidDefinitionException; use cebe\yii2openapi\lib\items\Attribute; -use cebe\yii2openapi\lib\exceptions\InvalidDefinitionException; use cebe\yii2openapi\lib\items\AttributeRelation; use cebe\yii2openapi\lib\items\DbModel; use cebe\yii2openapi\lib\items\JunctionSchemas; diff --git a/src/lib/items/Attribute.php b/src/lib/items/Attribute.php index 0a841f60..8b0306c9 100644 --- a/src/lib/items/Attribute.php +++ b/src/lib/items/Attribute.php @@ -8,9 +8,11 @@ namespace cebe\yii2openapi\lib\items; use cebe\yii2openapi\db\ColumnSchema; +use cebe\yii2openapi\generator\ApiGenerator; use cebe\yii2openapi\lib\exceptions\InvalidDefinitionException; use cebe\yii2openapi\lib\helpers\FormatHelper; use cebe\yii2openapi\lib\openapi\PropertySchema; +use Yii; use yii\base\BaseObject; use yii\base\InvalidConfigException; use yii\base\NotSupportedException; From 353f61eabc45662c1017e746bfd9969bf3626f95 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Wed, 13 Nov 2024 19:18:17 +0530 Subject: [PATCH 273/358] Fix failing test: IssueFixTest::testCreateMigrationForDropTable132 --- .../mysql/models/base/Animal.php | 6 +++++- .../mysql/models/base/Bigpk.php | 6 +++++- .../mysql/models/base/Foo.php | 4 ++++ .../mysql/models/base/Fruit.php | 6 +++++- .../mysql/models/base/Mango.php | 6 +++++- .../mysql/models/base/Pristine.php | 6 +++++- .../mysql/models/base/Ubigpk.php | 6 +++++- .../mysql/models/base/Upk.php | 6 +++++- tests/unit/IssueFixTest.php | 20 ++++++++++++++++--- 9 files changed, 56 insertions(+), 10 deletions(-) diff --git a/tests/specs/issue_fix/132_create_migration_for_drop_table/mysql/models/base/Animal.php b/tests/specs/issue_fix/132_create_migration_for_drop_table/mysql/models/base/Animal.php index 607ec9ae..1e131508 100644 --- a/tests/specs/issue_fix/132_create_migration_for_drop_table/mysql/models/base/Animal.php +++ b/tests/specs/issue_fix/132_create_migration_for_drop_table/mysql/models/base/Animal.php @@ -1,9 +1,13 @@ deleteTablesForCreateMigrationForDropTable132(); $this->createTablesForCreateMigrationForDropTable132(); $this->runGenerator($testFile); $this->runActualMigrations('mysql', 8); @@ -343,16 +344,29 @@ private function createTablesForCreateMigrationForDropTable132() private function deleteTablesForCreateMigrationForDropTable132() { - Yii::$app->db->createCommand()->dropForeignKey('name', '{{%pristines}}')->execute(); + $tableSchema = Yii::$app->db->schema->getTableSchema('{{%pristines}}'); + if ($tableSchema && array_key_exists('name', $tableSchema->foreignKeys)) { + Yii::$app->db->createCommand()->dropForeignKey('name', '{{%pristines}}')->execute(); + } + Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%pristines}}')->execute(); - Yii::$app->db->createCommand()->dropForeignKey('name2', '{{%fruits}}')->execute(); + + $tableSchema = Yii::$app->db->schema->getTableSchema('{{%fruits}}'); + if ($tableSchema && array_key_exists('name2', $tableSchema->foreignKeys)) { + Yii::$app->db->createCommand()->dropForeignKey('name2', '{{%fruits}}')->execute(); + } + Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%fruits}}')->execute(); Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%upks}}')->execute(); Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%bigpks}}')->execute(); Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%ubigpks}}')->execute(); - Yii::$app->db->createCommand()->dropForeignKey('animal_fruit_fk', '{{%the_mango_table_name}}')->execute(); + $tableSchema = Yii::$app->db->schema->getTableSchema('{{%the_mango_table_name}}'); + if ($tableSchema && array_key_exists('animal_fruit_fk', $tableSchema->foreignKeys)) { + Yii::$app->db->createCommand()->dropForeignKey('animal_fruit_fk', '{{%the_mango_table_name}}')->execute(); + } + Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%the_mango_table_name}}')->execute(); Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%the_animal_table_name}}')->execute(); } From 4faa9372a1e585777020735a8b4474ea23f395d1 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Wed, 13 Nov 2024 19:22:48 +0530 Subject: [PATCH 274/358] Refactor test --- tests/DbTestCase.php | 8 ++++++++ tests/unit/IssueFixTest.php | 18 +++--------------- 2 files changed, 11 insertions(+), 15 deletions(-) diff --git a/tests/DbTestCase.php b/tests/DbTestCase.php index f36137e2..3c02fa95 100644 --- a/tests/DbTestCase.php +++ b/tests/DbTestCase.php @@ -184,4 +184,12 @@ protected function runDownMigrations(string $db = 'mysql', int $number = 2): voi $this->assertSame($downExitCode, 0); $this->assertSame($downOutput[$lastThird], $number.' '.(($number === 1) ? 'migration was' : 'migrations were').' reverted.'); } + + protected function dropFkIfExists(string $table, string $fk): void + { + $tableSchema = Yii::$app->db->schema->getTableSchema($table); + if ($tableSchema && array_key_exists($fk, $tableSchema->foreignKeys)) { + Yii::$app->db->createCommand()->dropForeignKey($fk, $table)->execute(); + } + } } diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index ea84ae69..f2a4f87f 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -344,29 +344,17 @@ private function createTablesForCreateMigrationForDropTable132() private function deleteTablesForCreateMigrationForDropTable132() { - $tableSchema = Yii::$app->db->schema->getTableSchema('{{%pristines}}'); - if ($tableSchema && array_key_exists('name', $tableSchema->foreignKeys)) { - Yii::$app->db->createCommand()->dropForeignKey('name', '{{%pristines}}')->execute(); - } - + $this->dropFkIfExists('{{%pristines}}', 'name'); Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%pristines}}')->execute(); - $tableSchema = Yii::$app->db->schema->getTableSchema('{{%fruits}}'); - if ($tableSchema && array_key_exists('name2', $tableSchema->foreignKeys)) { - Yii::$app->db->createCommand()->dropForeignKey('name2', '{{%fruits}}')->execute(); - } - + $this->dropFkIfExists('{{%fruits}}', 'name2'); Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%fruits}}')->execute(); Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%upks}}')->execute(); Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%bigpks}}')->execute(); Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%ubigpks}}')->execute(); - $tableSchema = Yii::$app->db->schema->getTableSchema('{{%the_mango_table_name}}'); - if ($tableSchema && array_key_exists('animal_fruit_fk', $tableSchema->foreignKeys)) { - Yii::$app->db->createCommand()->dropForeignKey('animal_fruit_fk', '{{%the_mango_table_name}}')->execute(); - } - + $this->dropFkIfExists('{{%the_mango_table_name}}', 'animal_fruit_fk'); Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%the_mango_table_name}}')->execute(); Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%the_animal_table_name}}')->execute(); } From c47deb82e26844b9089222909f54e0f66cd22f75 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Wed, 13 Nov 2024 19:28:51 +0530 Subject: [PATCH 275/358] Fix failing test: IssueFixTest::testCreateMigrationForDropTable132ForPgsql --- .../pgsql/models/base/Animal.php | 6 +++++- .../pgsql/models/base/Bigpk.php | 6 +++++- .../pgsql/models/base/Foo.php | 4 ++++ .../pgsql/models/base/Fruit.php | 6 +++++- .../pgsql/models/base/Mango.php | 6 +++++- .../pgsql/models/base/Pristine.php | 6 +++++- .../pgsql/models/base/Ubigpk.php | 6 +++++- .../pgsql/models/base/Upk.php | 6 +++++- tests/unit/IssueFixTest.php | 12 +++++++----- 9 files changed, 46 insertions(+), 12 deletions(-) diff --git a/tests/specs/issue_fix/132_create_migration_for_drop_table/pgsql/models/base/Animal.php b/tests/specs/issue_fix/132_create_migration_for_drop_table/pgsql/models/base/Animal.php index 607ec9ae..1e131508 100644 --- a/tests/specs/issue_fix/132_create_migration_for_drop_table/pgsql/models/base/Animal.php +++ b/tests/specs/issue_fix/132_create_migration_for_drop_table/pgsql/models/base/Animal.php @@ -1,9 +1,13 @@ changeDbToPgsql(); $testFile = Yii::getAlias("@specs/issue_fix/132_create_migration_for_drop_table/132_create_migration_for_drop_table.php"); + $this->deleteTablesForCreateMigrationForDropTable132ForPgsql(); $this->createTablesForCreateMigrationForDropTable132ForPgsql(); $this->runGenerator($testFile, 'pgsql'); $this->runActualMigrations('pgsql', 8); @@ -435,18 +436,19 @@ private function createTablesForCreateMigrationForDropTable132ForPgsql() private function deleteTablesForCreateMigrationForDropTable132ForPgsql() { - Yii::$app->db->createCommand()->dropForeignKey('name', '{{%pristines}}')->execute(); + $this->dropFkIfExists('{{%pristines}}', 'name'); Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%pristines}}')->execute(); - Yii::$app->db->createCommand()->dropForeignKey('name2', '{{%fruits}}')->execute(); + + $this->dropFkIfExists('{{%fruits}}', 'name2'); Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%fruits}}')->execute(); Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%upks}}')->execute(); - Yii::$app->db->createCommand('DROP TYPE mood')->execute(); - Yii::$app->db->createCommand('DROP TYPE enum_itt_upks_e2')->execute(); + Yii::$app->db->createCommand('DROP TYPE IF EXISTS mood')->execute(); + Yii::$app->db->createCommand('DROP TYPE IF EXISTS enum_itt_upks_e2')->execute(); Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%bigpks}}')->execute(); Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%ubigpks}}')->execute(); - Yii::$app->db->createCommand()->dropForeignKey('animal_fruit_fk', '{{%the_mango_table_name}}')->execute(); + $this->dropFkIfExists('{{%the_mango_table_name}}', 'animal_fruit_fk'); Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%the_mango_table_name}}')->execute(); Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%the_animal_table_name}}')->execute(); } From 3715ff28beb31707689822b2a96e138c55f74316 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Wed, 13 Nov 2024 19:34:19 +0530 Subject: [PATCH 276/358] Fix failing test: testCreateMigrationForDropTable132IndependentTablesDropSort --- .../mysql/models/base/Bigpk.php | 6 +++++- .../mysql/models/base/Foo.php | 4 ++++ .../mysql/models/base/Ubigpk.php | 6 +++++- .../mysql/models/base/Upk.php | 6 +++++- tests/unit/IssueFixTest.php | 10 +++++++--- 5 files changed, 26 insertions(+), 6 deletions(-) diff --git a/tests/specs/issue_fix/132_create_migration_for_drop_table/case_independent_tables_drop_sort/mysql/models/base/Bigpk.php b/tests/specs/issue_fix/132_create_migration_for_drop_table/case_independent_tables_drop_sort/mysql/models/base/Bigpk.php index 2bf05933..3c96ce51 100644 --- a/tests/specs/issue_fix/132_create_migration_for_drop_table/case_independent_tables_drop_sort/mysql/models/base/Bigpk.php +++ b/tests/specs/issue_fix/132_create_migration_for_drop_table/case_independent_tables_drop_sort/mysql/models/base/Bigpk.php @@ -1,9 +1,13 @@ db->createCommand('DROP TABLE IF EXISTS {{%ubigpks}}')->execute(); + Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%bigpks}}')->execute(); + Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%upks}}')->execute(); + }; + $dropTables(); Yii::$app->db->createCommand()->createTable('{{%upks}}', [ 'id' => 'upk', 'name' => 'string(150)', @@ -268,9 +274,7 @@ public function testCreateMigrationForDropTable132IndependentTablesDropSort() ]); $this->checkFiles($actualFiles, $expectedFiles); - Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%ubigpks}}')->execute(); - Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%bigpks}}')->execute(); - Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%upks}}')->execute(); + $dropTables(); } // Create migration for drop table if a entire schema is deleted from OpenAPI spec #132 From 165ea0c7077617325c0d60f7a2393cbf9506f827 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Wed, 13 Nov 2024 20:17:46 +0530 Subject: [PATCH 277/358] Fix more tests --- .../mysql/models/base/Fruit.php | 6 +- .../mysql/models/base/Pet.php | 10 +++- .../mysql/models/base/User.php | 6 +- .../mysql/models/base/Post.php | 6 +- .../mysql/models/base/User.php | 11 +++- .../mysql/models/base/User.php | 6 +- .../mysql/models/base/Animal.php | 5 ++ .../mysql/models/base/Fruit.php | 5 ++ .../mysql/models/base/Invoice.php | 22 ++++++-- .../mysql/models/base/User.php | 10 ++++ tests/unit/IssueFixTest.php | 56 +++++++++---------- 11 files changed, 101 insertions(+), 42 deletions(-) diff --git a/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/mysql/models/base/Fruit.php b/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/mysql/models/base/Fruit.php index 2106e69d..ccdbe894 100644 --- a/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/mysql/models/base/Fruit.php +++ b/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/mysql/models/base/Fruit.php @@ -1,9 +1,13 @@ hasMany(\app\models\User::class, ['pet_id' => 'id']); + return $this->hasMany(\app\models\User::class, ['pet_id' => 'id'])->inverseOf('pet'); } public function getUserRefObjArr() { - return $this->hasMany(\app\models\User::class, ['pet_id' => 'id']); + return $this->hasMany(\app\models\User::class, ['pet_id' => 'id'])->inverseOf('pet'); } } diff --git a/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/mysql/models/base/User.php b/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/mysql/models/base/User.php index 08e59880..bce4e105 100644 --- a/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/mysql/models/base/User.php +++ b/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/mysql/models/base/User.php @@ -1,9 +1,13 @@ [['name'], 'string'], ]; } + + public function getPost() + { + return $this->hasOne(\app\models\Post::class, ['user' => 'id'])->inverseOf('user'); + } } diff --git a/tests/specs/issue_fix/30_add_validation_rules_by_attribute_name_or_pattern/mysql/models/base/User.php b/tests/specs/issue_fix/30_add_validation_rules_by_attribute_name_or_pattern/mysql/models/base/User.php index 87027cf9..eed2ea63 100644 --- a/tests/specs/issue_fix/30_add_validation_rules_by_attribute_name_or_pattern/mysql/models/base/User.php +++ b/tests/specs/issue_fix/30_add_validation_rules_by_attribute_name_or_pattern/mysql/models/base/User.php @@ -1,9 +1,13 @@ [['name'], 'string'], ]; } + + public function getInvoice() + { + return $this->hasOne(\app\models\Invoice::class, ['animal_id' => 'id'])->inverseOf('animal'); + } } diff --git a/tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql/models/base/Fruit.php b/tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql/models/base/Fruit.php index ccdbe894..d56f106c 100644 --- a/tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql/models/base/Fruit.php +++ b/tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql/models/base/Fruit.php @@ -27,4 +27,9 @@ public function rules() 'name_string' => [['name'], 'string'], ]; } + + public function getInvoice() + { + return $this->hasOne(\app\models\Invoice::class, ['fruit_id' => 'id'])->inverseOf('fruit'); + } } diff --git a/tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql/models/base/Invoice.php b/tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql/models/base/Invoice.php index 1495d16b..73190e01 100644 --- a/tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql/models/base/Invoice.php +++ b/tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql/models/base/Invoice.php @@ -35,17 +35,17 @@ public function rules() { return [ 'reference_invoice_id_integer' => [['reference_invoice_id'], 'integer'], - 'reference_invoice_id_exist' => [['reference_invoice_id'], 'exist', 'targetRelation' => 'ReferenceInvoice'], + 'reference_invoice_id_exist' => [['reference_invoice_id'], 'exist', 'targetRelation' => 'referenceInvoice'], 'reference_invoice_2_id_integer' => [['reference_invoice_2_id'], 'integer'], - 'reference_invoice_2_id_exist' => [['reference_invoice_2_id'], 'exist', 'targetRelation' => 'ReferenceInvoice2'], + 'reference_invoice_2_id_exist' => [['reference_invoice_2_id'], 'exist', 'targetRelation' => 'referenceInvoice2'], 'user_id_integer' => [['user_id'], 'integer'], - 'user_id_exist' => [['user_id'], 'exist', 'targetRelation' => 'User'], + 'user_id_exist' => [['user_id'], 'exist', 'targetRelation' => 'user'], 'user_2_id_integer' => [['user_2_id'], 'integer'], - 'user_2_id_exist' => [['user_2_id'], 'exist', 'targetRelation' => 'User2'], + 'user_2_id_exist' => [['user_2_id'], 'exist', 'targetRelation' => 'user2'], 'fruit_id_integer' => [['fruit_id'], 'integer'], - 'fruit_id_exist' => [['fruit_id'], 'exist', 'targetRelation' => 'Fruit'], + 'fruit_id_exist' => [['fruit_id'], 'exist', 'targetRelation' => 'fruit'], 'animal_id_integer' => [['animal_id'], 'integer'], - 'animal_id_exist' => [['animal_id'], 'exist', 'targetRelation' => 'Animal'], + 'animal_id_exist' => [['animal_id'], 'exist', 'targetRelation' => 'animal'], ]; } @@ -78,4 +78,14 @@ public function getAnimal() { return $this->hasOne(\app\models\Animal::class, ['id' => 'animal_id']); } + + public function getInvoice() + { + return $this->hasOne(\app\models\Invoice::class, ['reference_invoice_id' => 'id'])->inverseOf('reference_invoice'); + } + + public function getInvoice2() + { + return $this->hasOne(\app\models\Invoice::class, ['reference_invoice_2_id' => 'id'])->inverseOf('reference_invoice_2'); + } } diff --git a/tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql/models/base/User.php b/tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql/models/base/User.php index bce4e105..a6ce6e79 100644 --- a/tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql/models/base/User.php +++ b/tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql/models/base/User.php @@ -27,4 +27,14 @@ public function rules() 'name_string' => [['name'], 'string'], ]; } + + public function getInvoice() + { + return $this->hasOne(\app\models\Invoice::class, ['user_id' => 'id'])->inverseOf('user'); + } + + public function getInvoice2() + { + return $this->hasOne(\app\models\Invoice::class, ['user_2_id' => 'id'])->inverseOf('user_2'); + } } diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index a2409053..9739f3ec 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -288,10 +288,10 @@ public function testCreateMigrationForDropTable132() $this->runActualMigrations('mysql', 8); $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ - 'recursive' => true, + 'recursive' => true, ]); $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/132_create_migration_for_drop_table/mysql"), [ - 'recursive' => true, + 'recursive' => true, ]); $this->checkFiles($actualFiles, $expectedFiles); @@ -366,25 +366,25 @@ private function deleteTablesForCreateMigrationForDropTable132() // Create migration for drop table if a entire schema is deleted from OpenAPI spec #132 // https://github.com/cebe/yii2-openapi/issues/132 // For PgSQL - public function testCreateMigrationForDropTable132ForPgsql() - { - $this->changeDbToPgsql(); - $testFile = Yii::getAlias("@specs/issue_fix/132_create_migration_for_drop_table/132_create_migration_for_drop_table.php"); - $this->deleteTablesForCreateMigrationForDropTable132ForPgsql(); - $this->createTablesForCreateMigrationForDropTable132ForPgsql(); - $this->runGenerator($testFile, 'pgsql'); - $this->runActualMigrations('pgsql', 8); - - $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ - 'recursive' => true, - ]); - $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/132_create_migration_for_drop_table/pgsql"), [ - 'recursive' => true, - ]); - $this->checkFiles($actualFiles, $expectedFiles); - - $this->deleteTablesForCreateMigrationForDropTable132ForPgsql(); - } + public function testCreateMigrationForDropTable132ForPgsql() + { + $this->changeDbToPgsql(); + $testFile = Yii::getAlias("@specs/issue_fix/132_create_migration_for_drop_table/132_create_migration_for_drop_table.php"); + $this->deleteTablesForCreateMigrationForDropTable132ForPgsql(); + $this->createTablesForCreateMigrationForDropTable132ForPgsql(); + $this->runGenerator($testFile, 'pgsql'); + $this->runActualMigrations('pgsql', 8); + + $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ + 'recursive' => true, + ]); + $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/132_create_migration_for_drop_table/pgsql"), [ + 'recursive' => true, + ]); + $this->checkFiles($actualFiles, $expectedFiles); + + $this->deleteTablesForCreateMigrationForDropTable132ForPgsql(); + } private function createTablesForCreateMigrationForDropTable132ForPgsql() { @@ -549,13 +549,13 @@ public function test29ExtensionFkColumnNameCauseErrorInCaseOfColumnNameWithoutUn { $testFile = Yii::getAlias("@specs/issue_fix/29_extension_fk_column_name_cause_error_in_case_of_column_name_without_underscore/index.php"); $this->runGenerator($testFile); - $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ - 'recursive' => true, - ]); - $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/29_extension_fk_column_name_cause_error_in_case_of_column_name_without_underscore/mysql"), [ - 'recursive' => true, - ]); - $this->checkFiles($actualFiles, $expectedFiles); + $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ + 'recursive' => true, + ]); + $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/29_extension_fk_column_name_cause_error_in_case_of_column_name_without_underscore/mysql"), [ + 'recursive' => true, + ]); + $this->checkFiles($actualFiles, $expectedFiles); } // https://github.com/php-openapi/yii2-openapi/issues/30 From ae229f4ce8d3ab280e9102e5733d5bedf03c09a0 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Wed, 13 Nov 2024 20:20:41 +0530 Subject: [PATCH 278/358] Fix more failing tests --- .../mysql/models/MenuFaker.php | 1 - .../mysql/models/base/Account.php | 14 +++++++++----- .../mysql/models/base/Menu.php | 8 ++++++-- .../mysql/models/base/User.php | 6 +++++- 4 files changed, 20 insertions(+), 9 deletions(-) diff --git a/tests/specs/issue_fix/25_generate_inverse_relations/mysql/models/MenuFaker.php b/tests/specs/issue_fix/25_generate_inverse_relations/mysql/models/MenuFaker.php index 76ede6b7..13448252 100644 --- a/tests/specs/issue_fix/25_generate_inverse_relations/mysql/models/MenuFaker.php +++ b/tests/specs/issue_fix/25_generate_inverse_relations/mysql/models/MenuFaker.php @@ -44,7 +44,6 @@ public static function dependentOn() { return [ // just model class names - 'Menu', ]; } diff --git a/tests/specs/issue_fix/25_generate_inverse_relations/mysql/models/base/Account.php b/tests/specs/issue_fix/25_generate_inverse_relations/mysql/models/base/Account.php index d0f43293..d3846586 100644 --- a/tests/specs/issue_fix/25_generate_inverse_relations/mysql/models/base/Account.php +++ b/tests/specs/issue_fix/25_generate_inverse_relations/mysql/models/base/Account.php @@ -1,5 +1,9 @@ [['name', 'paymentMethodName'], 'trim'], 'required' => [['name'], 'required'], 'user_id_integer' => [['user_id'], 'integer'], - 'user_id_exist' => [['user_id'], 'exist', 'targetRelation' => 'User'], + 'user_id_exist' => [['user_id'], 'exist', 'targetRelation' => 'user'], 'user2_id_integer' => [['user2_id'], 'integer'], - 'user2_id_exist' => [['user2_id'], 'exist', 'targetRelation' => 'User2'], + 'user2_id_exist' => [['user2_id'], 'exist', 'targetRelation' => 'user2'], 'user3_integer' => [['user3'], 'integer'], - 'user3_exist' => [['user3'], 'exist', 'targetRelation' => 'User3'], + 'user3_exist' => [['user3'], 'exist', 'targetRelation' => 'user3Rel'], 'name_string' => [['name'], 'string', 'max' => 128], 'paymentMethodName_string' => [['paymentMethodName'], 'string'], ]; @@ -49,7 +53,7 @@ public function getUser2() return $this->hasOne(\app\models\User::class, ['id' => 'user2_id']); } - public function getUser3() + public function getUser3Rel() { return $this->hasOne(\app\models\User::class, ['id' => 'user3']); } diff --git a/tests/specs/issue_fix/25_generate_inverse_relations/mysql/models/base/Menu.php b/tests/specs/issue_fix/25_generate_inverse_relations/mysql/models/base/Menu.php index ec3d0957..7f2eb9aa 100644 --- a/tests/specs/issue_fix/25_generate_inverse_relations/mysql/models/base/Menu.php +++ b/tests/specs/issue_fix/25_generate_inverse_relations/mysql/models/base/Menu.php @@ -1,9 +1,13 @@ [['name'], 'trim'], 'required' => [['name'], 'required'], 'parent_id_integer' => [['parent_id'], 'integer'], - 'parent_id_exist' => [['parent_id'], 'exist', 'targetRelation' => 'Parent'], + 'parent_id_exist' => [['parent_id'], 'exist', 'targetRelation' => 'parent'], 'name_string' => [['name'], 'string', 'min' => 3, 'max' => 100], ]; } diff --git a/tests/specs/issue_fix/25_generate_inverse_relations/mysql/models/base/User.php b/tests/specs/issue_fix/25_generate_inverse_relations/mysql/models/base/User.php index 5f70ce96..7e26bb25 100644 --- a/tests/specs/issue_fix/25_generate_inverse_relations/mysql/models/base/User.php +++ b/tests/specs/issue_fix/25_generate_inverse_relations/mysql/models/base/User.php @@ -1,9 +1,13 @@ Date: Wed, 13 Nov 2024 20:27:28 +0530 Subject: [PATCH 279/358] Refactor --- src/lib/SchemaToDatabase.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/lib/SchemaToDatabase.php b/src/lib/SchemaToDatabase.php index 221a8cec..ccb230a3 100644 --- a/src/lib/SchemaToDatabase.php +++ b/src/lib/SchemaToDatabase.php @@ -289,14 +289,14 @@ public static function dbModelsForDropTable(array $schemasToDrop): array $table = Yii::$app->db->schema->getTableSchema("{{%$tableName}}", true); if ($table) { - $dbModelHere = new DbModel([ + $localDbModel = new DbModel([ 'pkName' => $table->primaryKey[0], 'name' => $schemaName, 'tableName' => $tableName, 'attributes' => static::attributesFromColumnSchemas(static::enhanceColumnSchemas($table->columns)), 'drop' => true ]); - $dbModelsToDrop[$key] = $dbModelHere; + $dbModelsToDrop[$key] = $localDbModel; } } return $dbModelsToDrop; From db08939d89e050df48f2793e217a618c968e83b2 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Thu, 14 Nov 2024 16:51:42 +0530 Subject: [PATCH 280/358] Attempt to fix failing tests in Github Action --- src/lib/AttributeResolver.php | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/lib/AttributeResolver.php b/src/lib/AttributeResolver.php index 92014c6e..7c93c932 100644 --- a/src/lib/AttributeResolver.php +++ b/src/lib/AttributeResolver.php @@ -140,7 +140,8 @@ protected function resolveJunctionTableProperty(PropertySchema $property, bool $ ->setPhpType($junkAttribute['phpType']) ->setDbType($junkAttribute['dbType']) ->setForeignKeyColumnName($property->fkColName) - ->setTableName($this->componentSchema->resolveTableName($this->schemaName)); +// ->setTableName($this->componentSchema->resolveTableName($this->schemaName)) + ; $relation = Yii::createObject(AttributeRelation::class, [ $property->getName(), $junkAttribute['relatedTableName'], @@ -229,7 +230,8 @@ protected function resolveProperty( ->setIsPrimary($property->isPrimaryKey()) ->setForeignKeyColumnName($property->fkColName) ->setFakerStub($this->guessFakerStub($attribute, $property)) - ->setTableName($this->componentSchema->resolveTableName($this->schemaName)); +// ->setTableName($this->componentSchema->resolveTableName($this->schemaName)) + ; if ($property->isReference()) { if ($property->isVirtual()) { throw new InvalidDefinitionException('References not supported for virtual attributes'); From e4bcd7649a23da6093792539a9d6e299e4748dcd Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Thu, 14 Nov 2024 17:31:48 +0530 Subject: [PATCH 281/358] Attempt to fix failing tests: memory exhaust (in `phpunit --repeat 3`) issue --- src/lib/AttributeResolver.php | 6 ++---- tests/bootstrap.php | 1 + 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/src/lib/AttributeResolver.php b/src/lib/AttributeResolver.php index 7c93c932..92014c6e 100644 --- a/src/lib/AttributeResolver.php +++ b/src/lib/AttributeResolver.php @@ -140,8 +140,7 @@ protected function resolveJunctionTableProperty(PropertySchema $property, bool $ ->setPhpType($junkAttribute['phpType']) ->setDbType($junkAttribute['dbType']) ->setForeignKeyColumnName($property->fkColName) -// ->setTableName($this->componentSchema->resolveTableName($this->schemaName)) - ; + ->setTableName($this->componentSchema->resolveTableName($this->schemaName)); $relation = Yii::createObject(AttributeRelation::class, [ $property->getName(), $junkAttribute['relatedTableName'], @@ -230,8 +229,7 @@ protected function resolveProperty( ->setIsPrimary($property->isPrimaryKey()) ->setForeignKeyColumnName($property->fkColName) ->setFakerStub($this->guessFakerStub($attribute, $property)) -// ->setTableName($this->componentSchema->resolveTableName($this->schemaName)) - ; + ->setTableName($this->componentSchema->resolveTableName($this->schemaName)); if ($property->isReference()) { if ($property->isVirtual()) { throw new InvalidDefinitionException('References not supported for virtual attributes'); diff --git a/tests/bootstrap.php b/tests/bootstrap.php index 61f13cfc..d3e05290 100644 --- a/tests/bootstrap.php +++ b/tests/bootstrap.php @@ -3,6 +3,7 @@ error_reporting(-1); ini_set('display_errors', '1'); ini_set('display_startup_errors', '1'); +ini_set('memory_limit', '150M'); defined('YII_DEBUG') or define('YII_DEBUG', true); defined('YII_ENV') or define('YII_ENV', 'test'); From 26c8a261a8922f6747c9771f637c00c00aa541f9 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Thu, 14 Nov 2024 20:57:33 +0530 Subject: [PATCH 282/358] Fix failing tests --- tests/DbTestCase.php | 15 +++++++++++++++ .../mysql/models/base/Address.php | 4 ++++ .../m200000_000000_change_table_v3_pgcustom.php | 3 +-- tests/unit/IssueFixTest.php | 7 +++++-- 4 files changed, 25 insertions(+), 4 deletions(-) diff --git a/tests/DbTestCase.php b/tests/DbTestCase.php index aded408a..fd3eebb4 100644 --- a/tests/DbTestCase.php +++ b/tests/DbTestCase.php @@ -4,6 +4,7 @@ use cebe\yii2openapi\generator\ApiGenerator; use Yii; +use yii\db\IndexConstraint; use yii\di\Container; use yii\db\mysql\Schema as MySqlSchema; use yii\db\pgsql\Schema as PgSqlSchema; @@ -192,4 +193,18 @@ protected function dropFkIfExists(string $table, string $fk): void Yii::$app->db->createCommand()->dropForeignKey($fk, $table)->execute(); } } + + protected function indexExists(string $indexName): bool + { + $indices = Yii::$app->db->schema->schemaIndexes; + foreach ($indices as $subIndices) { + foreach ($subIndices as $index) { + /** @var IndexConstraint $index */ + if ($index->name === $indexName) { + return true; + } + } + } + return false; + } } diff --git a/tests/specs/issue_fix/3_bug_add_remove_property_and_at_the_same_time_change_it_at_x_indexes/mysql/models/base/Address.php b/tests/specs/issue_fix/3_bug_add_remove_property_and_at_the_same_time_change_it_at_x_indexes/mysql/models/base/Address.php index 829a231e..a429e822 100644 --- a/tests/specs/issue_fix/3_bug_add_remove_property_and_at_the_same_time_change_it_at_x_indexes/mysql/models/base/Address.php +++ b/tests/specs/issue_fix/3_bug_add_remove_property_and_at_the_same_time_change_it_at_x_indexes/mysql/models/base/Address.php @@ -1,5 +1,9 @@ createIndex('v3_pgcustom_search_gin_index', '{{%v3_pgcustom}}', 'search', 'gin(to_tsvector(\'english\', status))'); + $this->createIndex('v3_pgcustom_search_gin_index', '{{%v3_pgcustom}}', 'to_tsvector(\'english\', search::text)', 'gin'); $this->alterColumn('{{%v3_pgcustom}}', 'json1', "SET NOT NULL"); $this->alterColumn('{{%v3_pgcustom}}', 'json1', "SET DEFAULT '[]'"); $this->alterColumn('{{%v3_pgcustom}}', 'json2', "SET NOT NULL"); @@ -18,7 +18,6 @@ public function safeUp() $this->alterColumn('{{%v3_pgcustom}}', 'json4', "SET DEFAULT '{\"foo\":\"bar\",\"bar\":\"baz\"}'"); $this->alterColumn('{{%v3_pgcustom}}', 'status', "SET DEFAULT 'draft'"); $this->alterColumn('{{%v3_pgcustom}}', 'status_x', "SET DEFAULT 'draft'"); - $this->createIndex('v3_pgcustom_search_gin_index', '{{%v3_pgcustom}}', 'to_tsvector(\'english\', search::text)', 'gin'); } public function safeDown() diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index 5dc6bb4a..91a17357 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -547,6 +547,7 @@ public function test158BugGiiapiGeneratedRulesEnumWithTrim() // https://github.com/php-openapi/yii2-openapi/issues/3 public function test3BugAddRemovePropertyAndAtTheSameTimeChangeItAtXIndexes() { + $this->dropTestTableFor3BugAddRemovePropertyAndAtTheSameTimeChangeItAtXIndexes(); $this->createTestTableFor3BugAddRemovePropertyAndAtTheSameTimeChangeItAtXIndexes(); $testFile = Yii::getAlias("@specs/issue_fix/3_bug_add_remove_property_and_at_the_same_time_change_it_at_x_indexes/index.php"); $this->runGenerator($testFile); @@ -574,8 +575,10 @@ private function createTestTableFor3BugAddRemovePropertyAndAtTheSameTimeChangeIt private function dropTestTableFor3BugAddRemovePropertyAndAtTheSameTimeChangeItAtXIndexes() { - Yii::$app->db->createCommand()->dropIndex('addresses_shortName_postalCode_key', '{{%addresses}}')->execute(); - Yii::$app->db->createCommand()->dropTable('{{%addresses}}')->execute(); + if ($this->indexExists('addresses_shortName_postalCode_key')) { + Yii::$app->db->createCommand()->dropIndex('addresses_shortName_postalCode_key', '{{%addresses}}')->execute(); + } + Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%addresses}}')->execute(); } // https://github.com/php-openapi/yii2-openapi/issues/29 From 7fa9cde711f453ad21a9371aaca1317c838988a4 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Fri, 15 Nov 2024 18:13:50 +0530 Subject: [PATCH 283/358] Fix failing test --- .../m200000_000000_change_table_v2_posts.php | 1 - .../m200000_000001_create_table_accounts.php | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/tests/specs/blog_v2/migrations_maria_db/m200000_000000_change_table_v2_posts.php b/tests/specs/blog_v2/migrations_maria_db/m200000_000000_change_table_v2_posts.php index d0ee3b6a..5d9f6aa4 100644 --- a/tests/specs/blog_v2/migrations_maria_db/m200000_000000_change_table_v2_posts.php +++ b/tests/specs/blog_v2/migrations_maria_db/m200000_000000_change_table_v2_posts.php @@ -14,7 +14,6 @@ public function up() $this->alterColumn('{{%v2_posts}}', 'category_id', $this->bigInteger()->notNull()->comment('Category of posts')); $this->alterColumn('{{%v2_posts}}', 'active', $this->tinyInteger(1)->notNull()); $this->alterColumn('{{%v2_posts}}', 'created_by_id', $this->bigInteger()->null()->defaultValue(null)->comment('The User')); - $this->dropIndex('v2_posts_slug_key', '{{%v2_posts}}'); } public function down() diff --git a/tests/specs/issue_fix/25_generate_inverse_relations/mysql/migrations_mysql_db/m200000_000001_create_table_accounts.php b/tests/specs/issue_fix/25_generate_inverse_relations/mysql/migrations_mysql_db/m200000_000001_create_table_accounts.php index f2bc7b90..1bc93a24 100644 --- a/tests/specs/issue_fix/25_generate_inverse_relations/mysql/migrations_mysql_db/m200000_000001_create_table_accounts.php +++ b/tests/specs/issue_fix/25_generate_inverse_relations/mysql/migrations_mysql_db/m200000_000001_create_table_accounts.php @@ -9,7 +9,7 @@ public function up() { $this->createTable('{{%accounts}}', [ 'id' => $this->primaryKey(), - 'name' => $this->string(128)->notNull(), + 'name' => $this->string(128)->notNull()->comment('account name'), 'paymentMethodName' => $this->text()->null(), 'user_id' => $this->integer()->null()->defaultValue(null), 'user2_id' => $this->integer()->null()->defaultValue(null), From af961aa83c39b285764701ba3ab7dded642fa3cc Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Fri, 15 Nov 2024 19:48:56 +0530 Subject: [PATCH 284/358] Make this feature optional - WIP - https://github.com/php-openapi/yii2-openapi/pull/61#issuecomment-2478774878 --- src/lib/CustomSpecAttr.php | 4 ++++ src/lib/generators/MigrationsGenerator.php | 2 +- src/lib/migrations/BaseMigrationBuilder.php | 6 +++++- src/lib/migrations/MysqlMigrationBuilder.php | 13 +++++++++---- .../index.yml | 2 +- 5 files changed, 20 insertions(+), 7 deletions(-) diff --git a/src/lib/CustomSpecAttr.php b/src/lib/CustomSpecAttr.php index e4638746..72b88dc3 100644 --- a/src/lib/CustomSpecAttr.php +++ b/src/lib/CustomSpecAttr.php @@ -56,4 +56,8 @@ class CustomSpecAttr * Custom route (controller ID/action ID) instead of auto-generated. See README for usage docs. https://github.com/cebe/yii2-openapi/issues/144 */ public const ROUTE = 'x-route'; + + + // TODO docs here + in README.md + public const DESC_IS_COMMENT = 'x-description-is-comment'; } diff --git a/src/lib/generators/MigrationsGenerator.php b/src/lib/generators/MigrationsGenerator.php index 1c0dfb51..b14fbfc0 100644 --- a/src/lib/generators/MigrationsGenerator.php +++ b/src/lib/generators/MigrationsGenerator.php @@ -142,7 +142,7 @@ protected function createBuilder(DbModel $model):BaseMigrationBuilder if ($this->db->getDriverName() === 'pgsql') { return Yii::createObject(PostgresMigrationBuilder::class, [$this->db, $model]); } - return Yii::createObject(MysqlMigrationBuilder::class, [$this->db, $model]); + return Yii::createObject(MysqlMigrationBuilder::class, [$this->db, $model, $this->config]); } /** diff --git a/src/lib/migrations/BaseMigrationBuilder.php b/src/lib/migrations/BaseMigrationBuilder.php index 644da945..cff13460 100644 --- a/src/lib/migrations/BaseMigrationBuilder.php +++ b/src/lib/migrations/BaseMigrationBuilder.php @@ -9,6 +9,7 @@ use cebe\yii2openapi\generator\ApiGenerator; use cebe\yii2openapi\lib\ColumnToCode; +use cebe\yii2openapi\lib\Config; use cebe\yii2openapi\lib\items\DbModel; use cebe\yii2openapi\lib\items\ManyToManyRelation; use cebe\yii2openapi\lib\items\MigrationModel; @@ -53,6 +54,8 @@ abstract class BaseMigrationBuilder */ protected $recordBuilder; + public ?Config $config = null; + /** * MigrationBuilder constructor. * @param \yii\db\Connection $db @@ -60,12 +63,13 @@ abstract class BaseMigrationBuilder * @throws \yii\base\InvalidConfigException * @throws \yii\base\NotSupportedException */ - public function __construct(Connection $db, DbModel $model) + public function __construct(Connection $db, DbModel $model, ?Config $config = null) { $this->db = $db; $this->model = $model; $this->tableSchema = $db->getTableSchema($model->getTableAlias(), true); $this->recordBuilder = Yii::createObject(MigrationRecordBuilder::class, [$db->getSchema()]); + $this->config = $config; } /** diff --git a/src/lib/migrations/MysqlMigrationBuilder.php b/src/lib/migrations/MysqlMigrationBuilder.php index e9058a5c..b31a7619 100644 --- a/src/lib/migrations/MysqlMigrationBuilder.php +++ b/src/lib/migrations/MysqlMigrationBuilder.php @@ -9,6 +9,7 @@ use cebe\yii2openapi\generator\ApiGenerator; use cebe\yii2openapi\lib\ColumnToCode; +use cebe\yii2openapi\lib\CustomSpecAttr; use cebe\yii2openapi\lib\items\DbIndex; use yii\base\NotSupportedException; use yii\db\ColumnSchema; @@ -59,10 +60,14 @@ protected function compareColumns(ColumnSchema $current, ColumnSchema $desired): $this->modifyDesiredInContextOfCurrent($current, $desiredFromDb); $this->modifyDesiredFromDbInContextOfDesired($desired, $desiredFromDb); - foreach (['type', 'size', 'allowNull', 'defaultValue', 'enumValues' - , 'dbType', 'phpType' - , 'precision', 'scale', 'unsigned', 'comment' - ] as $attr) { + $properties = ['type', 'size', 'allowNull', 'defaultValue', 'enumValues' + , 'dbType', 'phpType' + , 'precision', 'scale', 'unsigned'#, 'comment' + ]; + if (!empty($this->config->getOpenApi()->{CustomSpecAttr::DESC_IS_COMMENT})) { + $properties[] = 'comment'; + } + foreach ($properties as $attr) { if ($attr === 'defaultValue') { if ($this->isDefaultValueChanged($current, $desiredFromDb)) { $changedAttributes[] = $attr; diff --git a/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/index.yml b/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/index.yml index cfefea9b..aad9014f 100644 --- a/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/index.yml +++ b/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/index.yml @@ -1,5 +1,5 @@ openapi: 3.0.3 - +x-description-is-comment: true info: title: 'Description of a property in spec must correspond to DB TABLE COLUMN COMMENT #60' version: 1.0.0 From d549831883c8f58b52f390bbf4e905825d26fdd6 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Mon, 18 Nov 2024 19:16:38 +0530 Subject: [PATCH 285/358] Implement for table/compo schema - WIP --- src/lib/AttributeResolver.php | 1 + src/lib/items/DbModel.php | 2 ++ src/lib/migrations/MysqlMigrationBuilder.php | 2 ++ 3 files changed, 5 insertions(+) diff --git a/src/lib/AttributeResolver.php b/src/lib/AttributeResolver.php index 92014c6e..736844cb 100644 --- a/src/lib/AttributeResolver.php +++ b/src/lib/AttributeResolver.php @@ -117,6 +117,7 @@ public function resolve(): DbModel //For valid primary keys for junction tables 'junctionCols' => $this->isJunctionSchema ? $this->junctions->junctionCols($this->schemaName) : [], 'isNotDb' => $this->componentSchema->isNonDb(), + 'descriptionIsComment' => $this->componentSchema->{CustomSpecAttr::DESC_IS_COMMENT}, ], ]); } diff --git a/src/lib/items/DbModel.php b/src/lib/items/DbModel.php index 1deb9fbc..08135d71 100644 --- a/src/lib/items/DbModel.php +++ b/src/lib/items/DbModel.php @@ -88,6 +88,8 @@ class DbModel extends BaseObject */ public $scenarioDefaultDescription = "Scenario {scenarioName}"; + public bool $descriptionIsComment = false; + /** * @var array Automatically generated scenarios from the model 'x-scenarios'. */ diff --git a/src/lib/migrations/MysqlMigrationBuilder.php b/src/lib/migrations/MysqlMigrationBuilder.php index b31a7619..50947555 100644 --- a/src/lib/migrations/MysqlMigrationBuilder.php +++ b/src/lib/migrations/MysqlMigrationBuilder.php @@ -66,6 +66,8 @@ protected function compareColumns(ColumnSchema $current, ColumnSchema $desired): ]; if (!empty($this->config->getOpenApi()->{CustomSpecAttr::DESC_IS_COMMENT})) { $properties[] = 'comment'; + } elseif ($this->model->descriptionIsComment) { // TODO + $properties[] = 'comment'; } foreach ($properties as $attr) { if ($attr === 'defaultValue') { From 53416d2533b9d5541a82361233e5df0f185e62c6 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Tue, 19 Nov 2024 19:47:50 +0530 Subject: [PATCH 286/358] WIP --- src/lib/AttributeResolver.php | 2 +- src/lib/migrations/BaseMigrationBuilder.php | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/lib/AttributeResolver.php b/src/lib/AttributeResolver.php index 736844cb..fd9beae1 100644 --- a/src/lib/AttributeResolver.php +++ b/src/lib/AttributeResolver.php @@ -117,7 +117,7 @@ public function resolve(): DbModel //For valid primary keys for junction tables 'junctionCols' => $this->isJunctionSchema ? $this->junctions->junctionCols($this->schemaName) : [], 'isNotDb' => $this->componentSchema->isNonDb(), - 'descriptionIsComment' => $this->componentSchema->{CustomSpecAttr::DESC_IS_COMMENT}, + 'descriptionIsComment' => !empty(($this->componentSchema->{CustomSpecAttr::DESC_IS_COMMENT})) ? $this->componentSchema->{CustomSpecAttr::DESC_IS_COMMENT} : false, ], ]); } diff --git a/src/lib/migrations/BaseMigrationBuilder.php b/src/lib/migrations/BaseMigrationBuilder.php index cff13460..c483351e 100644 --- a/src/lib/migrations/BaseMigrationBuilder.php +++ b/src/lib/migrations/BaseMigrationBuilder.php @@ -507,7 +507,8 @@ public function tmpSaveNewCol(string $tableAlias, \cebe\yii2openapi\db\ColumnSch public function newColStr(string $tableAlias, \cebe\yii2openapi\db\ColumnSchema $columnSchema): string { $ctc = new ColumnToCode(\Yii::$app->db->schema, $tableAlias, $columnSchema, false, false, true); - return ColumnToCode::undoEscapeQuotes($ctc->getCode()); +// return ColumnToCode::undoEscapeQuotes($ctc->getCode()); + return $ctc->getCode(); } public static function isEnum(\yii\db\ColumnSchema $columnSchema): bool From 3815cb3a64e65f0a9ebdfe78efb7d4b4e86a1628 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Wed, 20 Nov 2024 21:04:57 +0530 Subject: [PATCH 287/358] Implement for property level extension --- src/lib/AttributeResolver.php | 3 ++- src/lib/items/Attribute.php | 25 +++++++++++++------ src/lib/migrations/MysqlMigrationBuilder.php | 14 ++++++++--- .../index.yml | 17 ++++++++----- 4 files changed, 42 insertions(+), 17 deletions(-) diff --git a/src/lib/AttributeResolver.php b/src/lib/AttributeResolver.php index fd9beae1..a43aa8ba 100644 --- a/src/lib/AttributeResolver.php +++ b/src/lib/AttributeResolver.php @@ -117,7 +117,7 @@ public function resolve(): DbModel //For valid primary keys for junction tables 'junctionCols' => $this->isJunctionSchema ? $this->junctions->junctionCols($this->schemaName) : [], 'isNotDb' => $this->componentSchema->isNonDb(), - 'descriptionIsComment' => !empty(($this->componentSchema->{CustomSpecAttr::DESC_IS_COMMENT})) ? $this->componentSchema->{CustomSpecAttr::DESC_IS_COMMENT} : false, + 'descriptionIsComment' => !empty(($this->componentSchema->getSchema()->{CustomSpecAttr::DESC_IS_COMMENT})) ], ]); } @@ -226,6 +226,7 @@ protected function resolveProperty( ->setDefault($property->guessDefault()) ->setXDbType($property->getAttr(CustomSpecAttr::DB_TYPE)) ->setXDbDefaultExpression($property->getAttr(CustomSpecAttr::DB_DEFAULT_EXPRESSION)) + ->setXDescriptionIsComment($property->getAttr(CustomSpecAttr::DESC_IS_COMMENT)) ->setNullable($nullableValue) ->setIsPrimary($property->isPrimaryKey()) ->setForeignKeyColumnName($property->fkColName) diff --git a/src/lib/items/Attribute.php b/src/lib/items/Attribute.php index ffbbcba2..c079d06b 100644 --- a/src/lib/items/Attribute.php +++ b/src/lib/items/Attribute.php @@ -61,13 +61,6 @@ class Attribute extends BaseObject */ public $dbType = 'string'; - /** - * Custom db type - * string | null | false - * if `false` then this attribute is virtual - */ - public $xDbType; - /** * nullable * bool | null @@ -128,6 +121,18 @@ class Attribute extends BaseObject **/ public $isVirtual = false; + /** + * Custom db type + * string | null | false + * if `false` then this attribute is virtual + */ + public $xDbType; + + /** + * @see \cebe\yii2openapi\lib\CustomSpecAttr::DESC_IS_COMMENT + */ + public ?bool $xDescriptionIsComment = false; + public function __construct(string $propertyName, array $config = []) { $this->propertyName = $propertyName; @@ -397,4 +402,10 @@ public function handleDecimal(ColumnSchema $columnSchema): void $columnSchema->dbType = $decimalAttributes['dbType']; } } + + public function setXDescriptionIsComment($xDescriptionIsComment): Attribute + { + $this->xDescriptionIsComment = $xDescriptionIsComment; + return $this; + } } diff --git a/src/lib/migrations/MysqlMigrationBuilder.php b/src/lib/migrations/MysqlMigrationBuilder.php index 50947555..a860ac6d 100644 --- a/src/lib/migrations/MysqlMigrationBuilder.php +++ b/src/lib/migrations/MysqlMigrationBuilder.php @@ -64,9 +64,17 @@ protected function compareColumns(ColumnSchema $current, ColumnSchema $desired): , 'dbType', 'phpType' , 'precision', 'scale', 'unsigned'#, 'comment' ]; - if (!empty($this->config->getOpenApi()->{CustomSpecAttr::DESC_IS_COMMENT})) { - $properties[] = 'comment'; - } elseif ($this->model->descriptionIsComment) { // TODO + $comment = false; + if ($this->model->attributes[$desired->name]->xDescriptionIsComment) { + $comment = true; + } + if ($this->model->descriptionIsComment) { + $comment = true; + } + if ($this->config && !empty($this->config->getOpenApi()->{CustomSpecAttr::DESC_IS_COMMENT})) { + $comment = true; + } + if ($comment) { $properties[] = 'comment'; } foreach ($properties as $attr) { diff --git a/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/index.yml b/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/index.yml index aad9014f..d9272c32 100644 --- a/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/index.yml +++ b/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/index.yml @@ -1,5 +1,5 @@ openapi: 3.0.3 -x-description-is-comment: true +#x-description-is-comment: true info: title: 'Description of a property in spec must correspond to DB TABLE COLUMN COMMENT #60' version: 1.0.0 @@ -8,43 +8,48 @@ components: schemas: Fruit: type: object + # x-description-is-comment: true properties: id: type: integer name: type: string description: desc with ' quote + x-description-is-comment: true description: type: number x-db-type: double precision description: desc ' 2 + x-description-is-comment: true Animal: type: object + # x-description-is-comment: true properties: id: type: integer name: type: integer - # description: desc - # description: - # type: string - # x-db-type: varchar - # description: desc 2 + x-description-is-comment: true g: type: string description: desc for g + x-description-is-comment: true g2: type: string description: changed comment on g2 col + x-description-is-comment: true g3: type: string description: the comment on g3 col remains same + x-description-is-comment: true g4: type: integer description: data type changes but comment remains same + x-description-is-comment: true new_col: type: string description: new col added + x-description-is-comment: true paths: '/': From 8fd5b8b14e69ff338f117e94231a264a72419563 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Thu, 21 Nov 2024 12:24:12 +0530 Subject: [PATCH 288/358] Add more tests --- .../index.yml | 10 -- tests/unit/IssueFixTest.php | 132 ++++++++++++++++++ 2 files changed, 132 insertions(+), 10 deletions(-) diff --git a/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/index.yml b/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/index.yml index d9272c32..1b874edc 100644 --- a/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/index.yml +++ b/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/index.yml @@ -8,48 +8,38 @@ components: schemas: Fruit: type: object - # x-description-is-comment: true properties: id: type: integer name: type: string description: desc with ' quote - x-description-is-comment: true description: type: number x-db-type: double precision description: desc ' 2 - x-description-is-comment: true Animal: type: object - # x-description-is-comment: true properties: id: type: integer name: type: integer - x-description-is-comment: true g: type: string description: desc for g - x-description-is-comment: true g2: type: string description: changed comment on g2 col - x-description-is-comment: true g3: type: string description: the comment on g3 col remains same - x-description-is-comment: true g4: type: integer description: data type changes but comment remains same - x-description-is-comment: true new_col: type: string description: new col added - x-description-is-comment: true paths: '/': diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index e7fdf5f1..86a41d4c 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -580,6 +580,138 @@ public function test60DescriptionOfAPropertyInSpecMustCorrespondToDbTableColumnC $this->deleteTableFor60DescriptionOfAProperty(); } + // https://github.com/php-openapi/yii2-openapi/issues/60 + public function test60ComponentSchemaLevelExtension() + { + + + $schema = <<alterColumn('{{%fruits}}', 'name', $this->text()->notNull()->comment('Hi there')); + } + + public function down() + { + $this->alterColumn('{{%fruits}}', 'name', $this->text()->null()); + } +} + +PHP; + + $this->for60($schema, $expected); + } + + // https://github.com/php-openapi/yii2-openapi/issues/60 + public function test60PropertyLevelExtension() + { + $schema = <<alterColumn('{{%fruits}}', 'name', $this->text()->notNull()->comment('Hi there')); + } + + public function down() + { + $this->alterColumn('{{%fruits}}', 'name', $this->text()->null()); + } +} + +PHP; + + $this->for60($schema, $expected); + } + + private function for60($spec, $expected) + { + Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%fruits}}')->execute(); + Yii::$app->db->createCommand()->createTable('{{%fruits}}', [ + 'id' => 'pk', + 'name' => 'text', + ])->execute(); + $config = [ + 'openApiPath' => 'data://text/plain;base64,' . base64_encode($spec), + 'generateUrls' => false, + 'generateModels' => false, + 'generateControllers' => false, + 'generateMigrations' => true, + 'generateModelFaker' => false, + ]; + $tmpConfigFile = Yii::getAlias("@runtime") . "/tmp-config.php"; + file_put_contents($tmpConfigFile, 'runGenerator($tmpConfigFile); + $actual = file_get_contents(Yii::getAlias('@app') . '/migrations_mysql_db/m200000_000000_change_table_fruits.php'); + $this->assertSame($expected, $actual); + $this->runActualMigrations('mysql', 1); + Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%fruits}}')->execute(); + } + private function createTableFor60DescriptionOfAProperty() { Yii::$app->db->createCommand()->createTable('{{%animals}}', [ From 051900a800306660c39b9cecfd42e47aa034e4c8 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Thu, 21 Nov 2024 12:39:08 +0530 Subject: [PATCH 289/358] Fix failing tests --- src/lib/migrations/MysqlMigrationBuilder.php | 2 +- .../m200000_000000_change_table_v2_posts.php | 4 ++-- .../m200000_000005_change_table_v2_comments.php | 2 -- .../m200000_000000_change_table_v2_posts.php | 4 ++-- .../m200000_000005_change_table_v2_comments.php | 2 -- .../index.yml | 2 +- 6 files changed, 6 insertions(+), 10 deletions(-) diff --git a/src/lib/migrations/MysqlMigrationBuilder.php b/src/lib/migrations/MysqlMigrationBuilder.php index a860ac6d..1cc1dadc 100644 --- a/src/lib/migrations/MysqlMigrationBuilder.php +++ b/src/lib/migrations/MysqlMigrationBuilder.php @@ -65,7 +65,7 @@ protected function compareColumns(ColumnSchema $current, ColumnSchema $desired): , 'precision', 'scale', 'unsigned'#, 'comment' ]; $comment = false; - if ($this->model->attributes[$desired->name]->xDescriptionIsComment) { + if (isset($this->model->attributes[$desired->name]) && $this->model->attributes[$desired->name]->xDescriptionIsComment) { $comment = true; } if ($this->model->descriptionIsComment) { diff --git a/tests/specs/blog_v2/migrations_maria_db/m200000_000000_change_table_v2_posts.php b/tests/specs/blog_v2/migrations_maria_db/m200000_000000_change_table_v2_posts.php index 5d9f6aa4..5f50d0d7 100644 --- a/tests/specs/blog_v2/migrations_maria_db/m200000_000000_change_table_v2_posts.php +++ b/tests/specs/blog_v2/migrations_maria_db/m200000_000000_change_table_v2_posts.php @@ -11,9 +11,9 @@ public function up() $this->addColumn('{{%v2_posts}}', 'lang', 'enum("ru", "eng") NULL DEFAULT \'ru\' AFTER slug'); $this->dropIndex('v2_posts_slug_key', '{{%v2_posts}}'); $this->dropColumn('{{%v2_posts}}', 'uid'); - $this->alterColumn('{{%v2_posts}}', 'category_id', $this->bigInteger()->notNull()->comment('Category of posts')); + $this->alterColumn('{{%v2_posts}}', 'category_id', $this->bigInteger()->notNull()); $this->alterColumn('{{%v2_posts}}', 'active', $this->tinyInteger(1)->notNull()); - $this->alterColumn('{{%v2_posts}}', 'created_by_id', $this->bigInteger()->null()->defaultValue(null)->comment('The User')); + $this->alterColumn('{{%v2_posts}}', 'created_by_id', $this->bigInteger()->null()->defaultValue(null)); } public function down() diff --git a/tests/specs/blog_v2/migrations_maria_db/m200000_000005_change_table_v2_comments.php b/tests/specs/blog_v2/migrations_maria_db/m200000_000005_change_table_v2_comments.php index 4ded7be3..b34a7810 100644 --- a/tests/specs/blog_v2/migrations_maria_db/m200000_000005_change_table_v2_comments.php +++ b/tests/specs/blog_v2/migrations_maria_db/m200000_000005_change_table_v2_comments.php @@ -11,7 +11,6 @@ public function up() $this->dropForeignKey('fk_v2_comments_author_id_v2_users_id', '{{%v2_comments}}'); $this->addColumn('{{%v2_comments}}', 'user_id', $this->bigInteger()->null()->defaultValue(null)->after('post_id')->comment('The User')); $this->dropColumn('{{%v2_comments}}', 'author_id'); - $this->alterColumn('{{%v2_comments}}', 'post_id', $this->bigInteger(20)->notNull()->comment('A blog post (uid used as pk for test purposes)')); $this->alterColumn('{{%v2_comments}}', 'message', $this->text()->notNull()); $this->alterColumn('{{%v2_comments}}', 'meta_data', $this->string(300)->null()->defaultValue('')); $this->alterColumn('{{%v2_comments}}', 'created_at', $this->timestamp()->notNull()); @@ -26,7 +25,6 @@ public function down() $this->alterColumn('{{%v2_comments}}', 'created_at', $this->integer(11)->notNull()); $this->alterColumn('{{%v2_comments}}', 'meta_data', 'json NOT NULL DEFAULT \'[]\''); $this->alterColumn('{{%v2_comments}}', 'message', 'json NOT NULL DEFAULT \'[]\''); - $this->alterColumn('{{%v2_comments}}', 'post_id', $this->bigInteger(20)->notNull()); $this->addColumn('{{%v2_comments}}', 'author_id', $this->integer(11)->notNull()->after('post_id')); $this->dropColumn('{{%v2_comments}}', 'user_id'); $this->addForeignKey('fk_v2_comments_author_id_v2_users_id', '{{%v2_comments}}', 'author_id', 'itt_v2_users', 'id'); diff --git a/tests/specs/blog_v2/migrations_mysql_db/m200000_000000_change_table_v2_posts.php b/tests/specs/blog_v2/migrations_mysql_db/m200000_000000_change_table_v2_posts.php index 83ab62a1..eea03cca 100644 --- a/tests/specs/blog_v2/migrations_mysql_db/m200000_000000_change_table_v2_posts.php +++ b/tests/specs/blog_v2/migrations_mysql_db/m200000_000000_change_table_v2_posts.php @@ -11,9 +11,9 @@ public function up() $this->addColumn('{{%v2_posts}}', 'lang', 'enum("ru", "eng") NULL DEFAULT \'ru\' AFTER slug'); $this->dropIndex('v2_posts_slug_key', '{{%v2_posts}}'); $this->dropColumn('{{%v2_posts}}', 'uid'); - $this->alterColumn('{{%v2_posts}}', 'category_id', $this->bigInteger()->notNull()->comment('Category of posts')); + $this->alterColumn('{{%v2_posts}}', 'category_id', $this->bigInteger()->notNull()); $this->alterColumn('{{%v2_posts}}', 'active', $this->tinyInteger(1)->notNull()); - $this->alterColumn('{{%v2_posts}}', 'created_by_id', $this->bigInteger()->null()->defaultValue(null)->comment('The User')); + $this->alterColumn('{{%v2_posts}}', 'created_by_id', $this->bigInteger()->null()->defaultValue(null)); } public function down() diff --git a/tests/specs/blog_v2/migrations_mysql_db/m200000_000005_change_table_v2_comments.php b/tests/specs/blog_v2/migrations_mysql_db/m200000_000005_change_table_v2_comments.php index 3fa92fa8..8ac91b71 100644 --- a/tests/specs/blog_v2/migrations_mysql_db/m200000_000005_change_table_v2_comments.php +++ b/tests/specs/blog_v2/migrations_mysql_db/m200000_000005_change_table_v2_comments.php @@ -11,7 +11,6 @@ public function up() $this->dropForeignKey('fk_v2_comments_author_id_v2_users_id', '{{%v2_comments}}'); $this->addColumn('{{%v2_comments}}', 'user_id', $this->bigInteger()->null()->defaultValue(null)->after('post_id')->comment('The User')); $this->dropColumn('{{%v2_comments}}', 'author_id'); - $this->alterColumn('{{%v2_comments}}', 'post_id', $this->bigInteger()->notNull()->comment('A blog post (uid used as pk for test purposes)')); $this->alterColumn('{{%v2_comments}}', 'message', $this->text()->notNull()); $this->alterColumn('{{%v2_comments}}', 'meta_data', $this->string(300)->null()->defaultValue('')); $this->alterColumn('{{%v2_comments}}', 'created_at', $this->timestamp()->notNull()); @@ -26,7 +25,6 @@ public function down() $this->alterColumn('{{%v2_comments}}', 'created_at', $this->integer()->notNull()); $this->alterColumn('{{%v2_comments}}', 'meta_data', 'json NOT NULL'); $this->alterColumn('{{%v2_comments}}', 'message', 'json NOT NULL'); - $this->alterColumn('{{%v2_comments}}', 'post_id', $this->bigInteger()->notNull()); $this->addColumn('{{%v2_comments}}', 'author_id', $this->integer()->notNull()->after('post_id')); $this->dropColumn('{{%v2_comments}}', 'user_id'); $this->addForeignKey('fk_v2_comments_author_id_v2_users_id', '{{%v2_comments}}', 'author_id', 'itt_v2_users', 'id'); diff --git a/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/index.yml b/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/index.yml index 1b874edc..bafe0cf8 100644 --- a/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/index.yml +++ b/tests/specs/issue_fix/60_description_of_a_property_in_spec_must_correspond_to_db_table_column_comment/index.yml @@ -1,5 +1,5 @@ openapi: 3.0.3 -#x-description-is-comment: true +x-description-is-comment: true info: title: 'Description of a property in spec must correspond to DB TABLE COLUMN COMMENT #60' version: 1.0.0 From 9d4dc38ae6c644007a7f1dbad84a928f64a3fec0 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Thu, 21 Nov 2024 17:36:46 +0530 Subject: [PATCH 290/358] Add doc --- README.md | 54 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) diff --git a/README.md b/README.md index aae945c5..f68df469 100644 --- a/README.md +++ b/README.md @@ -465,6 +465,60 @@ Generated URL rules config for above is (in `urls.rest.php` or pertinent file): ``` `x-route` does not support [Yii Modules](https://www.yiiframework.com/doc/guide/2.0/en/structure-modules). +### `x-description-is-comment` + + boolean; default: false + +When a new database table is created from new OpenAPI component schema, description of a property will be used as +comment of column (of database table). + +This extension is used when a description is edited for existing property, and you want to generate migration for its +corresponding column comment changes. + +This extension can be used at 3 place: + +**1. root level (highest priority)** + +```yaml +openapi: 3.0.3 +x-description-is-comment: true +info: + title: Description +``` + +This will create migration of any changed description of component schema property present throughout the spec. + +**2. component schema level** + +```yaml +components: + schemas: + Fruit: + type: object + x-description-is-comment: true +``` + +This will create migration of changed description of only properties of component schema which have this extension. + +**3. property level (lowest priority)** + +```yaml +components: + schemas: + Fruit: + type: object + properties: + id: + type: integer + name: + type: string + nullable: false + x-description-is-comment: true + description: Hi there +``` + +Migrations will be only generated for changed description of properties having this extension. + ## Many-to-Many relation definition There are two ways for define many-to-many relations: From 20fad45320bd0a4f0ea7a4aa2bb4964325997cff Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Thu, 21 Nov 2024 17:40:05 +0530 Subject: [PATCH 291/358] Resolve TODO --- src/lib/CustomSpecAttr.php | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/lib/CustomSpecAttr.php b/src/lib/CustomSpecAttr.php index 72b88dc3..6234f7a9 100644 --- a/src/lib/CustomSpecAttr.php +++ b/src/lib/CustomSpecAttr.php @@ -58,6 +58,8 @@ class CustomSpecAttr public const ROUTE = 'x-route'; - // TODO docs here + in README.md + /** + * Generate migrations for changed description of property. More docs is present in README.md file + */ public const DESC_IS_COMMENT = 'x-description-is-comment'; } From 692c4aa1e3d40210153e6aa1256910cf928822f5 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Thu, 21 Nov 2024 18:34:31 +0530 Subject: [PATCH 292/358] Implement for PgSQL --- src/lib/generators/MigrationsGenerator.php | 3 +-- src/lib/migrations/BaseMigrationBuilder.php | 19 ++++++++++++++++++- src/lib/migrations/MysqlMigrationBuilder.php | 15 ++------------- .../migrations/PostgresMigrationBuilder.php | 11 ++++++++--- .../m200000_000000_change_table_v2_posts.php | 4 ---- ...200000_000005_change_table_v2_comments.php | 2 -- 6 files changed, 29 insertions(+), 25 deletions(-) diff --git a/src/lib/generators/MigrationsGenerator.php b/src/lib/generators/MigrationsGenerator.php index b14fbfc0..95426c13 100644 --- a/src/lib/generators/MigrationsGenerator.php +++ b/src/lib/generators/MigrationsGenerator.php @@ -12,7 +12,6 @@ use cebe\yii2openapi\lib\items\DbModel; use cebe\yii2openapi\lib\items\MigrationModel; use cebe\yii2openapi\lib\migrations\BaseMigrationBuilder; -use cebe\yii2openapi\lib\migrations\MigrationRecordBuilder; use cebe\yii2openapi\lib\migrations\MysqlMigrationBuilder; use cebe\yii2openapi\lib\migrations\PostgresMigrationBuilder; use Exception; @@ -140,7 +139,7 @@ public function buildMigrations():array protected function createBuilder(DbModel $model):BaseMigrationBuilder { if ($this->db->getDriverName() === 'pgsql') { - return Yii::createObject(PostgresMigrationBuilder::class, [$this->db, $model]); + return Yii::createObject(PostgresMigrationBuilder::class, [$this->db, $model, $this->config]); } return Yii::createObject(MysqlMigrationBuilder::class, [$this->db, $model, $this->config]); } diff --git a/src/lib/migrations/BaseMigrationBuilder.php b/src/lib/migrations/BaseMigrationBuilder.php index c483351e..2cf1702a 100644 --- a/src/lib/migrations/BaseMigrationBuilder.php +++ b/src/lib/migrations/BaseMigrationBuilder.php @@ -10,6 +10,7 @@ use cebe\yii2openapi\generator\ApiGenerator; use cebe\yii2openapi\lib\ColumnToCode; use cebe\yii2openapi\lib\Config; +use cebe\yii2openapi\lib\CustomSpecAttr; use cebe\yii2openapi\lib\items\DbModel; use cebe\yii2openapi\lib\items\ManyToManyRelation; use cebe\yii2openapi\lib\items\MigrationModel; @@ -54,7 +55,7 @@ abstract class BaseMigrationBuilder */ protected $recordBuilder; - public ?Config $config = null; + protected ?Config $config = null; /** * MigrationBuilder constructor. @@ -597,4 +598,20 @@ public function buildTablesDrop(): void abstract public function findPosition(ColumnSchema $column, bool $forDrop = false, bool $forAlter = false): ?string; abstract public function setColumnsPositions(); + + protected function shouldCompareComment(ColumnSchema $desired): bool + { + $comment = false; + if (isset($this->model->attributes[$desired->name]) && $this->model->attributes[$desired->name]->xDescriptionIsComment) { + $comment = true; + } + if ($this->model->descriptionIsComment) { + $comment = true; + } + if ($this->config !== null && + !empty($this->config->getOpenApi()->{CustomSpecAttr::DESC_IS_COMMENT})) { + $comment = true; + } + return $comment; + } } diff --git a/src/lib/migrations/MysqlMigrationBuilder.php b/src/lib/migrations/MysqlMigrationBuilder.php index 1cc1dadc..da3d967d 100644 --- a/src/lib/migrations/MysqlMigrationBuilder.php +++ b/src/lib/migrations/MysqlMigrationBuilder.php @@ -9,7 +9,6 @@ use cebe\yii2openapi\generator\ApiGenerator; use cebe\yii2openapi\lib\ColumnToCode; -use cebe\yii2openapi\lib\CustomSpecAttr; use cebe\yii2openapi\lib\items\DbIndex; use yii\base\NotSupportedException; use yii\db\ColumnSchema; @@ -62,19 +61,9 @@ protected function compareColumns(ColumnSchema $current, ColumnSchema $desired): $properties = ['type', 'size', 'allowNull', 'defaultValue', 'enumValues' , 'dbType', 'phpType' - , 'precision', 'scale', 'unsigned'#, 'comment' + , 'precision', 'scale', 'unsigned' ]; - $comment = false; - if (isset($this->model->attributes[$desired->name]) && $this->model->attributes[$desired->name]->xDescriptionIsComment) { - $comment = true; - } - if ($this->model->descriptionIsComment) { - $comment = true; - } - if ($this->config && !empty($this->config->getOpenApi()->{CustomSpecAttr::DESC_IS_COMMENT})) { - $comment = true; - } - if ($comment) { + if ($this->shouldCompareComment($desired)) { $properties[] = 'comment'; } foreach ($properties as $attr) { diff --git a/src/lib/migrations/PostgresMigrationBuilder.php b/src/lib/migrations/PostgresMigrationBuilder.php index 0be4298b..4f2379cf 100644 --- a/src/lib/migrations/PostgresMigrationBuilder.php +++ b/src/lib/migrations/PostgresMigrationBuilder.php @@ -141,10 +141,15 @@ protected function compareColumns(ColumnSchema $current, ColumnSchema $desired): $this->modifyDesiredInContextOfCurrent($current, $desiredFromDb); $this->modifyDesiredFromDbInContextOfDesired($desired, $desiredFromDb); - foreach (['type', 'size', 'allowNull', 'defaultValue', 'enumValues' + $properties = ['type', 'size', 'allowNull', 'defaultValue', 'enumValues' , 'dbType', 'phpType' - , 'precision', 'scale', 'unsigned', 'comment' - ] as $attr) { + , 'precision', 'scale', 'unsigned' + ]; + if ($this->shouldCompareComment($desired)) { + $properties[] = 'comment'; + } + + foreach ($properties as $attr) { if ($attr === 'defaultValue') { if ($this->isDefaultValueChanged($current, $desiredFromDb)) { $changedAttributes[] = $attr; diff --git a/tests/specs/blog_v2/migrations_pgsql_db/m200000_000000_change_table_v2_posts.php b/tests/specs/blog_v2/migrations_pgsql_db/m200000_000000_change_table_v2_posts.php index a9e52fbc..9444aef9 100644 --- a/tests/specs/blog_v2/migrations_pgsql_db/m200000_000000_change_table_v2_posts.php +++ b/tests/specs/blog_v2/migrations_pgsql_db/m200000_000000_change_table_v2_posts.php @@ -13,17 +13,13 @@ public function safeUp() $this->dropIndex('v2_posts_slug_key', '{{%v2_posts}}'); $this->dropColumn('{{%v2_posts}}', 'uid'); $this->alterColumn('{{%v2_posts}}', 'category_id', 'int8 NOT NULL USING "category_id"::int8'); - $this->addCommentOnColumn('{{%v2_posts}}', 'category_id', 'Category of posts'); $this->alterColumn('{{%v2_posts}}', 'active', "DROP DEFAULT"); $this->alterColumn('{{%v2_posts}}', 'created_by_id', 'int8 NULL USING "created_by_id"::int8'); - $this->addCommentOnColumn('{{%v2_posts}}', 'created_by_id', 'The User'); } public function safeDown() { - $this->dropCommentFromColumn('{{%v2_posts}}', 'created_by_id'); $this->alterColumn('{{%v2_posts}}', 'created_by_id', 'int4 NULL USING "created_by_id"::int4'); - $this->dropCommentFromColumn('{{%v2_posts}}', 'category_id'); $this->alterColumn('{{%v2_posts}}', 'category_id', 'int4 NOT NULL USING "category_id"::int4'); $this->addColumn('{{%v2_posts}}', 'uid', $this->bigInteger()->notNull()); $this->createIndex('v2_posts_slug_key', '{{%v2_posts}}', 'slug', true); diff --git a/tests/specs/blog_v2/migrations_pgsql_db/m200000_000005_change_table_v2_comments.php b/tests/specs/blog_v2/migrations_pgsql_db/m200000_000005_change_table_v2_comments.php index 8a12066d..e9ad9ff5 100644 --- a/tests/specs/blog_v2/migrations_pgsql_db/m200000_000005_change_table_v2_comments.php +++ b/tests/specs/blog_v2/migrations_pgsql_db/m200000_000005_change_table_v2_comments.php @@ -11,7 +11,6 @@ public function safeUp() $this->dropForeignKey('fk_v2_comments_post_id_v2_posts_uid', '{{%v2_comments}}'); $this->addColumn('{{%v2_comments}}', 'user_id', $this->bigInteger()->null()->defaultValue(null)->comment('The User')); $this->dropColumn('{{%v2_comments}}', 'author_id'); - $this->addCommentOnColumn('{{%v2_comments}}', 'post_id', 'A blog post (uid used as pk for test purposes)'); $this->alterColumn('{{%v2_comments}}', 'message', 'text NOT NULL USING "message"::text'); $this->alterColumn('{{%v2_comments}}', 'message', "DROP DEFAULT"); $this->alterColumn('{{%v2_comments}}', 'meta_data', 'varchar(300) NULL USING "meta_data"::varchar'); @@ -29,7 +28,6 @@ public function safeDown() $this->alterColumn('{{%v2_comments}}', 'created_at', 'int4 NOT NULL USING "created_at"::int4'); $this->alterColumn('{{%v2_comments}}', 'meta_data', 'jsonb NOT NULL USING "meta_data"::jsonb'); $this->alterColumn('{{%v2_comments}}', 'message', 'jsonb NOT NULL USING "message"::jsonb'); - $this->dropCommentFromColumn('{{%v2_comments}}', 'post_id'); $this->addColumn('{{%v2_comments}}', 'author_id', $this->integer()->notNull()); $this->dropColumn('{{%v2_comments}}', 'user_id'); $this->alterColumn('{{%v2_comments}}', 'message', "SET DEFAULT '[]'"); From d5be8ce78162f5c65847b269567f7e498b16498f Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Thu, 21 Nov 2024 18:46:17 +0530 Subject: [PATCH 293/358] Refactor --- src/lib/generators/MigrationsGenerator.php | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/lib/generators/MigrationsGenerator.php b/src/lib/generators/MigrationsGenerator.php index 95426c13..211e4639 100644 --- a/src/lib/generators/MigrationsGenerator.php +++ b/src/lib/generators/MigrationsGenerator.php @@ -138,10 +138,11 @@ public function buildMigrations():array */ protected function createBuilder(DbModel $model):BaseMigrationBuilder { + $params = [$this->db, $model, $this->config]; if ($this->db->getDriverName() === 'pgsql') { - return Yii::createObject(PostgresMigrationBuilder::class, [$this->db, $model, $this->config]); + return Yii::createObject(PostgresMigrationBuilder::class, $params); } - return Yii::createObject(MysqlMigrationBuilder::class, [$this->db, $model, $this->config]); + return Yii::createObject(MysqlMigrationBuilder::class, $params); } /** From d6499207a3ce78cbcf9f879d9464a140c47dc559 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Thu, 28 Nov 2024 20:41:17 +0530 Subject: [PATCH 294/358] Remove redundant code --- src/lib/ColumnToCode.php | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/lib/ColumnToCode.php b/src/lib/ColumnToCode.php index f4da8079..b407aaaf 100644 --- a/src/lib/ColumnToCode.php +++ b/src/lib/ColumnToCode.php @@ -407,8 +407,6 @@ private function getIsBuiltinType($type, $dbType) private function resolveEnumType():void { if (ApiGenerator::isPostgres()) { - // $rawTableName = $this->dbSchema->getRawTableName($this->tableAlias); - // $this->rawParts['type'] = '"enum_'.$rawTableName.'_' . $this->column->name.'"'; $this->rawParts['type'] = '"'.$this->column->dbType.'"'; return; } From 4f137bc24b0b6edd6db571b17dafaacb830f68ab Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Tue, 3 Dec 2024 19:54:56 +0530 Subject: [PATCH 295/358] Fix this issue --- src/lib/openapi/PropertySchema.php | 16 ++++++++++++++++ .../mysql/models/base/Invoice.php | 10 ---------- 2 files changed, 16 insertions(+), 10 deletions(-) diff --git a/src/lib/openapi/PropertySchema.php b/src/lib/openapi/PropertySchema.php index 38f1873c..b366e06b 100644 --- a/src/lib/openapi/PropertySchema.php +++ b/src/lib/openapi/PropertySchema.php @@ -269,6 +269,22 @@ public function isRefPointerToSchema():bool public function isRefPointerToSelf():bool { + $schema = Json::decode(Json::encode($this->schema->getSchema()->getSerializableData())); + + if (isset($schema['properties'][$this->name]['allOf'])) { # fixes https://github.com/php-openapi/yii2-openapi/issues/68 + $allOfs = $schema['properties'][$this->name]['allOf']; + $refCounter = 0; + foreach ($allOfs as $allOf) { + if (isset($allOf['$ref'])) { + $refCounter++; + } + } + if ($refCounter === 1) { + return $this->isRefPointerToSchema() + && str_ends_with($this->refPointer, '/' . $this->schema->getName()) !== false; + } + } + return $this->isRefPointerToSchema() && strpos($this->refPointer, '/' . $this->schema->getName() . '/') !== false && strpos($this->refPointer, '/properties/') !== false; diff --git a/tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql/models/base/Invoice.php b/tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql/models/base/Invoice.php index 73190e01..8e944b9b 100644 --- a/tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql/models/base/Invoice.php +++ b/tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql/models/base/Invoice.php @@ -78,14 +78,4 @@ public function getAnimal() { return $this->hasOne(\app\models\Animal::class, ['id' => 'animal_id']); } - - public function getInvoice() - { - return $this->hasOne(\app\models\Invoice::class, ['reference_invoice_id' => 'id'])->inverseOf('reference_invoice'); - } - - public function getInvoice2() - { - return $this->hasOne(\app\models\Invoice::class, ['reference_invoice_2_id' => 'id'])->inverseOf('reference_invoice_2'); - } } From ac7a7a4e11a1a0681ff1ed90cc27730f302f1395 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Fri, 6 Dec 2024 20:48:52 +0530 Subject: [PATCH 296/358] Implement - WIP --- src/lib/migrations/BaseMigrationBuilder.php | 25 +++++++++- .../63_just_column_name_rename/index.php | 13 +++++ .../63_just_column_name_rename/index.yml | 49 +++++++++++++++++++ tests/unit/IssueFixTest.php | 20 ++++++++ 4 files changed, 106 insertions(+), 1 deletion(-) create mode 100644 tests/specs/issue_fix/63_just_column_name_rename/index.php create mode 100644 tests/specs/issue_fix/63_just_column_name_rename/index.yml diff --git a/src/lib/migrations/BaseMigrationBuilder.php b/src/lib/migrations/BaseMigrationBuilder.php index 2cf1702a..b913c3dc 100644 --- a/src/lib/migrations/BaseMigrationBuilder.php +++ b/src/lib/migrations/BaseMigrationBuilder.php @@ -199,9 +199,10 @@ function (string $unknownColumn) { $columnsForChange = array_intersect($wantNames, $haveNames); + $columnsForRename = $this->findColumnsToRename($columnsForCreate, $columnsForDrop, $this->newColumns); + if ($this->model->drop) { $this->newColumns = []; - $wantNames = []; $columnsForCreate = []; $columnsForChange = []; $columnsForDrop = []; @@ -614,4 +615,26 @@ protected function shouldCompareComment(ColumnSchema $desired): bool } return $comment; } + + /** + * @param array $columnsForCreate + * @param array $columnsForDrop + * @param $newColumns + * @return string[] + */ + public function findColumnsToRename(array &$columnsForCreate, array &$columnsForDrop, $newColumns): array + { + $columnNames = []; + $existingColumns = $this->tableSchema->columns; + $existingColumnNames = array_flip(array_keys($existingColumns)); + $newColumnNames = array_flip(array_keys($newColumns)); + + foreach ($columnsForCreate as $name) { + if ($existingColumnNames[$name] === $newColumnNames[$name]) { + // TODO compare column + } + } + + return $columnNames; + } } diff --git a/tests/specs/issue_fix/63_just_column_name_rename/index.php b/tests/specs/issue_fix/63_just_column_name_rename/index.php new file mode 100644 index 00000000..4b56a405 --- /dev/null +++ b/tests/specs/issue_fix/63_just_column_name_rename/index.php @@ -0,0 +1,13 @@ + '@specs/issue_fix/63_just_column_name_rename/index.yml', + 'generateUrls' => false, + 'generateModels' => false, + 'excludeModels' => [ + 'Error', + ], + 'generateControllers' => false, + 'generateMigrations' => true, + 'generateModelFaker' => false, // `generateModels` must be `true` in order to use `generateModelFaker` as `true` +]; diff --git a/tests/specs/issue_fix/63_just_column_name_rename/index.yml b/tests/specs/issue_fix/63_just_column_name_rename/index.yml new file mode 100644 index 00000000..bafe0cf8 --- /dev/null +++ b/tests/specs/issue_fix/63_just_column_name_rename/index.yml @@ -0,0 +1,49 @@ +openapi: 3.0.3 +x-description-is-comment: true +info: + title: 'Description of a property in spec must correspond to DB TABLE COLUMN COMMENT #60' + version: 1.0.0 + +components: + schemas: + Fruit: + type: object + properties: + id: + type: integer + name: + type: string + description: desc with ' quote + description: + type: number + x-db-type: double precision + description: desc ' 2 + Animal: + type: object + properties: + id: + type: integer + name: + type: integer + g: + type: string + description: desc for g + g2: + type: string + description: changed comment on g2 col + g3: + type: string + description: the comment on g3 col remains same + g4: + type: integer + description: data type changes but comment remains same + new_col: + type: string + description: new col added + +paths: + '/': + get: + responses: + '200': + description: OK diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index 86a41d4c..7fe94a62 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -885,4 +885,24 @@ public function test25GenerateInverseRelations() ]); $this->checkFiles($actualFiles, $expectedFiles); } + + // https://github.com/php-openapi/yii2-openapi/issues/63 + public function test63JustColumnNameRename() + { + $this->assertTrue(4); + + return; + + + $testFile = Yii::getAlias("@specs/issue_fix/63_just_column_name_rename/index.php"); + $this->runGenerator($testFile); + $this->runActualMigrations('mysql', 1); + $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ + 'recursive' => true, + ]); + $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/63_just_column_name_rename/mysql"), [ + 'recursive' => true, + ]); + $this->checkFiles($actualFiles, $expectedFiles); + } } From dd46d783ed0b216801d7429d274d776aba2d0923 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Mon, 9 Dec 2024 16:41:37 +0530 Subject: [PATCH 297/358] Implement - WIP --- src/lib/migrations/BaseMigrationBuilder.php | 40 ++++++++++++++----- src/lib/migrations/MigrationRecordBuilder.php | 6 +++ .../63_just_column_name_rename/index.yml | 32 ++------------- tests/unit/IssueFixTest.php | 29 ++++++++------ 4 files changed, 57 insertions(+), 50 deletions(-) diff --git a/src/lib/migrations/BaseMigrationBuilder.php b/src/lib/migrations/BaseMigrationBuilder.php index b913c3dc..3749b2c8 100644 --- a/src/lib/migrations/BaseMigrationBuilder.php +++ b/src/lib/migrations/BaseMigrationBuilder.php @@ -199,7 +199,7 @@ function (string $unknownColumn) { $columnsForChange = array_intersect($wantNames, $haveNames); - $columnsForRename = $this->findColumnsToRename($columnsForCreate, $columnsForDrop, $this->newColumns); + $columnsForRename = $this->handleColumnsRename($columnsForCreate, $columnsForDrop, $this->newColumns); if ($this->model->drop) { $this->newColumns = []; @@ -620,21 +620,41 @@ protected function shouldCompareComment(ColumnSchema $desired): bool * @param array $columnsForCreate * @param array $columnsForDrop * @param $newColumns - * @return string[] */ - public function findColumnsToRename(array &$columnsForCreate, array &$columnsForDrop, $newColumns): array + public function handleColumnsRename(array &$columnsForCreate, array &$columnsForDrop, $newColumns) { - $columnNames = []; + $keys = []; $existingColumns = $this->tableSchema->columns; - $existingColumnNames = array_flip(array_keys($existingColumns)); + $existingColumnNames = array_keys($existingColumns); $newColumnNames = array_flip(array_keys($newColumns)); - - foreach ($columnsForCreate as $name) { - if ($existingColumnNames[$name] === $newColumnNames[$name]) { - // TODO compare column + foreach ($columnsForCreate as $key => $column) { + $index = $newColumnNames[$column->name]; + $previousColumnName = $existingColumnNames[$index] ?? null; + if ($previousColumnName) { + $current = $existingColumns[$previousColumnName]; + $desired = $newColumns[$column->name]; + $changedAttributes = $this->compareColumns($current, $desired); + if (empty($changedAttributes)) { + $keys[] = $key; + $dropKeyOut = null; + array_walk($columnsForDrop, function ($value, $dropKey) use ($previousColumnName, &$dropKeyOut) { + if ($value->name === $previousColumnName) { + $dropKeyOut = $dropKey; + } + }); + // existing column name should be removed from $columnsForDrop + unset($columnsForDrop[$dropKeyOut]); + + // Create ALTER COLUMN NAME query + $this->migration->addUpCode($this->recordBuilder->renameColumn($this->model->tableAlias, $previousColumnName, $column->name)) + ->addDownCode($this->recordBuilder->renameColumn($this->model->tableAlias, $column->name, $previousColumnName)); + } } } - return $columnNames; + // new column name should be removed from $columnsForCreate + foreach ($keys as $key) { + unset($columnsForCreate[$key], $columnsForDrop[$previousColumnName]); + } } } diff --git a/src/lib/migrations/MigrationRecordBuilder.php b/src/lib/migrations/MigrationRecordBuilder.php index 700cbe4e..14df1f6c 100644 --- a/src/lib/migrations/MigrationRecordBuilder.php +++ b/src/lib/migrations/MigrationRecordBuilder.php @@ -49,6 +49,7 @@ final class MigrationRecordBuilder public const ADD_COMMENT_ON_COLUMN = MigrationRecordBuilder::INDENT . "\$this->addCommentOnColumn('%s', '%s', %s);"; public const DROP_COMMENT_FROM_COLUMN = MigrationRecordBuilder::INDENT . "\$this->dropCommentFromColumn('%s', '%s');"; + public const RENAME_COLUMN = MigrationRecordBuilder::INDENT . "\$this->renameColumn('%s', '%s', '%s');"; /** * @var \yii\db\Schema @@ -387,4 +388,9 @@ public function dropCommentFromColumn($table, string $column): string { return sprintf(self::DROP_COMMENT_FROM_COLUMN, $table, $column); } + + public function renameColumn(string $table, string $fromColumn, string $toColumn): string + { + return sprintf(self::RENAME_COLUMN, $table, $fromColumn, $toColumn); + } } diff --git a/tests/specs/issue_fix/63_just_column_name_rename/index.yml b/tests/specs/issue_fix/63_just_column_name_rename/index.yml index bafe0cf8..64888952 100644 --- a/tests/specs/issue_fix/63_just_column_name_rename/index.yml +++ b/tests/specs/issue_fix/63_just_column_name_rename/index.yml @@ -1,7 +1,6 @@ openapi: 3.0.3 -x-description-is-comment: true info: - title: 'Description of a property in spec must correspond to DB TABLE COLUMN COMMENT #60' + title: '63_just_column_name_rename' version: 1.0.0 components: @@ -11,35 +10,12 @@ components: properties: id: type: integer - name: + name_2: type: string - description: desc with ' quote - description: - type: number - x-db-type: double precision - description: desc ' 2 - Animal: - type: object - properties: - id: - type: integer - name: - type: integer - g: - type: string - description: desc for g - g2: + description_2: type: string - description: changed comment on g2 col - g3: - type: string - description: the comment on g3 col remains same - g4: - type: integer - description: data type changes but comment remains same - new_col: + colour: type: string - description: new col added paths: '/': diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index 7fe94a62..0e7b9443 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -889,20 +889,25 @@ public function test25GenerateInverseRelations() // https://github.com/php-openapi/yii2-openapi/issues/63 public function test63JustColumnNameRename() { - $this->assertTrue(4); - - return; - + Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%fruits}}')->execute(); + Yii::$app->db->createCommand()->createTable('{{%fruits}}', [ + 'id' => 'pk', + 'name' => 'text', + 'description' => 'text', + 'colour' => 'text', + ])->execute(); $testFile = Yii::getAlias("@specs/issue_fix/63_just_column_name_rename/index.php"); $this->runGenerator($testFile); - $this->runActualMigrations('mysql', 1); - $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ - 'recursive' => true, - ]); - $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/63_just_column_name_rename/mysql"), [ - 'recursive' => true, - ]); - $this->checkFiles($actualFiles, $expectedFiles); +// $this->runActualMigrations('mysql', 1); +// $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ +// 'recursive' => true, +// ]); +// $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/63_just_column_name_rename/mysql"), [ +// 'recursive' => true, +// ]); +// $this->checkFiles($actualFiles, $expectedFiles); + + Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%fruits}}')->execute(); } } From 36c576ea4397831cb351696263ba345e72a163bf Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Tue, 10 Dec 2024 17:47:13 +0530 Subject: [PATCH 298/358] Fix bug, add test, fix failing test --- src/lib/migrations/BaseMigrationBuilder.php | 11 +++-- .../m200000_000000_change_table_fruits.php | 19 +++++++++ .../m200000_000000_change_table_fruits.php | 19 +++++++++ tests/unit/IssueFixTest.php | 40 ++++++++++++++----- 4 files changed, 77 insertions(+), 12 deletions(-) create mode 100644 tests/specs/issue_fix/63_just_column_name_rename/mysql/migrations_mysql_db/m200000_000000_change_table_fruits.php create mode 100644 tests/specs/issue_fix/63_just_column_name_rename/pgsql/migrations_pgsql_db/m200000_000000_change_table_fruits.php diff --git a/src/lib/migrations/BaseMigrationBuilder.php b/src/lib/migrations/BaseMigrationBuilder.php index 3749b2c8..690b03b1 100644 --- a/src/lib/migrations/BaseMigrationBuilder.php +++ b/src/lib/migrations/BaseMigrationBuilder.php @@ -199,7 +199,7 @@ function (string $unknownColumn) { $columnsForChange = array_intersect($wantNames, $haveNames); - $columnsForRename = $this->handleColumnsRename($columnsForCreate, $columnsForDrop, $this->newColumns); + $this->handleColumnsRename($columnsForCreate, $columnsForDrop, $this->newColumns); if ($this->model->drop) { $this->newColumns = []; @@ -625,6 +625,9 @@ public function handleColumnsRename(array &$columnsForCreate, array &$columnsFor { $keys = []; $existingColumns = $this->tableSchema->columns; + if (count($existingColumns) !== count($newColumns)) { + return; + } $existingColumnNames = array_keys($existingColumns); $newColumnNames = array_flip(array_keys($newColumns)); foreach ($columnsForCreate as $key => $column) { @@ -633,7 +636,7 @@ public function handleColumnsRename(array &$columnsForCreate, array &$columnsFor if ($previousColumnName) { $current = $existingColumns[$previousColumnName]; $desired = $newColumns[$column->name]; - $changedAttributes = $this->compareColumns($current, $desired); + $changedAttributes = $this->compareColumns(clone $current, clone $desired); if (empty($changedAttributes)) { $keys[] = $key; $dropKeyOut = null; @@ -645,6 +648,8 @@ public function handleColumnsRename(array &$columnsForCreate, array &$columnsFor // existing column name should be removed from $columnsForDrop unset($columnsForDrop[$dropKeyOut]); + // TODO check in `required` and `x-index` + // Create ALTER COLUMN NAME query $this->migration->addUpCode($this->recordBuilder->renameColumn($this->model->tableAlias, $previousColumnName, $column->name)) ->addDownCode($this->recordBuilder->renameColumn($this->model->tableAlias, $column->name, $previousColumnName)); @@ -654,7 +659,7 @@ public function handleColumnsRename(array &$columnsForCreate, array &$columnsFor // new column name should be removed from $columnsForCreate foreach ($keys as $key) { - unset($columnsForCreate[$key], $columnsForDrop[$previousColumnName]); + unset($columnsForCreate[$key]); } } } diff --git a/tests/specs/issue_fix/63_just_column_name_rename/mysql/migrations_mysql_db/m200000_000000_change_table_fruits.php b/tests/specs/issue_fix/63_just_column_name_rename/mysql/migrations_mysql_db/m200000_000000_change_table_fruits.php new file mode 100644 index 00000000..0db16b09 --- /dev/null +++ b/tests/specs/issue_fix/63_just_column_name_rename/mysql/migrations_mysql_db/m200000_000000_change_table_fruits.php @@ -0,0 +1,19 @@ +renameColumn('{{%fruits}}', 'name', 'name_2'); + $this->renameColumn('{{%fruits}}', 'description', 'description_2'); + } + + public function down() + { + $this->renameColumn('{{%fruits}}', 'description_2', 'description'); + $this->renameColumn('{{%fruits}}', 'name_2', 'name'); + } +} diff --git a/tests/specs/issue_fix/63_just_column_name_rename/pgsql/migrations_pgsql_db/m200000_000000_change_table_fruits.php b/tests/specs/issue_fix/63_just_column_name_rename/pgsql/migrations_pgsql_db/m200000_000000_change_table_fruits.php new file mode 100644 index 00000000..d1d26c5f --- /dev/null +++ b/tests/specs/issue_fix/63_just_column_name_rename/pgsql/migrations_pgsql_db/m200000_000000_change_table_fruits.php @@ -0,0 +1,19 @@ +renameColumn('{{%fruits}}', 'name', 'name_2'); + $this->renameColumn('{{%fruits}}', 'description', 'description_2'); + } + + public function safeDown() + { + $this->renameColumn('{{%fruits}}', 'description_2', 'description'); + $this->renameColumn('{{%fruits}}', 'name_2', 'name'); + } +} diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index 0e7b9443..324658c0 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -889,6 +889,9 @@ public function test25GenerateInverseRelations() // https://github.com/php-openapi/yii2-openapi/issues/63 public function test63JustColumnNameRename() { + $testFile = Yii::getAlias("@specs/issue_fix/63_just_column_name_rename/index.php"); + + // MySQL Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%fruits}}')->execute(); Yii::$app->db->createCommand()->createTable('{{%fruits}}', [ 'id' => 'pk', @@ -897,17 +900,36 @@ public function test63JustColumnNameRename() 'colour' => 'text', ])->execute(); - $testFile = Yii::getAlias("@specs/issue_fix/63_just_column_name_rename/index.php"); $this->runGenerator($testFile); -// $this->runActualMigrations('mysql', 1); -// $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ -// 'recursive' => true, -// ]); -// $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/63_just_column_name_rename/mysql"), [ -// 'recursive' => true, -// ]); -// $this->checkFiles($actualFiles, $expectedFiles); + $this->runActualMigrations('mysql', 1); + $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ + 'recursive' => true, + ]); + $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/63_just_column_name_rename/mysql"), [ + 'recursive' => true, + ]); + $this->checkFiles($actualFiles, $expectedFiles); + Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%fruits}}')->execute(); + // PgSQL + $this->changeDbToPgsql(); + Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%fruits}}')->execute(); + Yii::$app->db->createCommand()->createTable('{{%fruits}}', [ + 'id' => 'pk', + 'name' => 'text', + 'description' => 'text', + 'colour' => 'text', + ])->execute(); + $this->runGenerator($testFile, 'pgsql'); + $this->runActualMigrations('pgsql', 1); + $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ + 'recursive' => true, + 'except' => ['migrations_mysql_db'] + ]); + $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/63_just_column_name_rename/pgsql"), [ + 'recursive' => true, + ]); + $this->checkFiles($actualFiles, $expectedFiles); Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%fruits}}')->execute(); } } From c1402a964f781ff222355bfe43dda074cd8b80c9 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Wed, 11 Dec 2024 19:44:59 +0530 Subject: [PATCH 299/358] Implement feedback --- src/lib/openapi/PropertySchema.php | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/src/lib/openapi/PropertySchema.php b/src/lib/openapi/PropertySchema.php index b366e06b..519656cd 100644 --- a/src/lib/openapi/PropertySchema.php +++ b/src/lib/openapi/PropertySchema.php @@ -269,13 +269,15 @@ public function isRefPointerToSchema():bool public function isRefPointerToSelf():bool { - $schema = Json::decode(Json::encode($this->schema->getSchema()->getSerializableData())); + $allOfsInSchema = null; + if (isset($this->schema->getSchema()->properties[$this->name]->allOf)) { + $allOfsInSchema = $this->schema->getSchema()->properties[$this->name]->allOf; + } - if (isset($schema['properties'][$this->name]['allOf'])) { # fixes https://github.com/php-openapi/yii2-openapi/issues/68 - $allOfs = $schema['properties'][$this->name]['allOf']; + if ($allOfsInSchema) { # fixes https://github.com/php-openapi/yii2-openapi/issues/68 $refCounter = 0; - foreach ($allOfs as $allOf) { - if (isset($allOf['$ref'])) { + foreach ($allOfsInSchema as $allOf) { + if ($allOf instanceof Reference) { $refCounter++; } } From 89f1d2c9b4d86f58b02b43cdb4a04c5c1cbd1dc3 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Wed, 11 Dec 2024 20:17:34 +0530 Subject: [PATCH 300/358] Refactor: better variable naming --- src/lib/openapi/PropertySchema.php | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/lib/openapi/PropertySchema.php b/src/lib/openapi/PropertySchema.php index 519656cd..9ff64094 100644 --- a/src/lib/openapi/PropertySchema.php +++ b/src/lib/openapi/PropertySchema.php @@ -269,15 +269,15 @@ public function isRefPointerToSchema():bool public function isRefPointerToSelf():bool { - $allOfsInSchema = null; + $allOfInSchema = null; if (isset($this->schema->getSchema()->properties[$this->name]->allOf)) { - $allOfsInSchema = $this->schema->getSchema()->properties[$this->name]->allOf; + $allOfInSchema = $this->schema->getSchema()->properties[$this->name]->allOf; } - if ($allOfsInSchema) { # fixes https://github.com/php-openapi/yii2-openapi/issues/68 + if ($allOfInSchema) { # fixes https://github.com/php-openapi/yii2-openapi/issues/68 $refCounter = 0; - foreach ($allOfsInSchema as $allOf) { - if ($allOf instanceof Reference) { + foreach ($allOfInSchema as $aAllOfElement) { + if ($aAllOfElement instanceof Reference) { $refCounter++; } } From b8376e0dac04f75b0146b51a6317ac80282c7dd4 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Thu, 12 Dec 2024 19:54:11 +0530 Subject: [PATCH 301/358] Fix bug + failing tests --- src/lib/migrations/BaseMigrationBuilder.php | 31 ++++++++++++++----- ...00000_change_table_column_name_changes.php | 6 ++-- ...00000_change_table_column_name_changes.php | 6 ++-- ...00000_change_table_column_name_changes.php | 6 ++-- .../m200000_000000_change_table_addresses.php | 6 ++-- tests/unit/Issue58FixTest.php | 10 +++--- tests/unit/IssueFixTest.php | 2 +- 7 files changed, 37 insertions(+), 30 deletions(-) diff --git a/src/lib/migrations/BaseMigrationBuilder.php b/src/lib/migrations/BaseMigrationBuilder.php index 690b03b1..3d581572 100644 --- a/src/lib/migrations/BaseMigrationBuilder.php +++ b/src/lib/migrations/BaseMigrationBuilder.php @@ -199,7 +199,7 @@ function (string $unknownColumn) { $columnsForChange = array_intersect($wantNames, $haveNames); - $this->handleColumnsRename($columnsForCreate, $columnsForDrop, $this->newColumns); + $fromColNameToColName = $this->handleColumnsRename($columnsForCreate, $columnsForDrop, $this->newColumns); if ($this->model->drop) { $this->newColumns = []; @@ -219,7 +219,9 @@ function (string $unknownColumn) { } if (!$relation) { - $this->buildIndexChanges(); + $this->buildIndexChanges($fromColNameToColName); + } else { + $this->migrationForRenameColumn($fromColNameToColName); } $this->buildColumnsDrop($columnsForDrop); @@ -304,7 +306,7 @@ abstract protected function findTableIndexes():array; abstract public function handleCommentsMigration(); - protected function buildIndexChanges():void + protected function buildIndexChanges(array $fromColNameToColName): void { $haveIndexes = $this->findTableIndexes(); $wantIndexes = $this->model->indexes; @@ -339,6 +341,9 @@ function ($idx) use ($wantIndexes) { $this->migration->addUpCode($this->recordBuilder->dropIndex($tableName, $index->name)) ->addDownCode($downCode); } + + $this->migrationForRenameColumn($fromColNameToColName); + foreach ($forCreate as $index) { $upCode = $index->isUnique ? $this->recordBuilder->addUniqueIndex($tableName, $index->name, $index->columns) @@ -620,13 +625,15 @@ protected function shouldCompareComment(ColumnSchema $desired): bool * @param array $columnsForCreate * @param array $columnsForDrop * @param $newColumns + * @return array key is previous/old column name and value is new column name */ - public function handleColumnsRename(array &$columnsForCreate, array &$columnsForDrop, $newColumns) + public function handleColumnsRename(array &$columnsForCreate, array &$columnsForDrop, $newColumns): array { $keys = []; + $fromColNameToColName = []; $existingColumns = $this->tableSchema->columns; if (count($existingColumns) !== count($newColumns)) { - return; + return $fromColNameToColName; } $existingColumnNames = array_keys($existingColumns); $newColumnNames = array_flip(array_keys($newColumns)); @@ -649,10 +656,9 @@ public function handleColumnsRename(array &$columnsForCreate, array &$columnsFor unset($columnsForDrop[$dropKeyOut]); // TODO check in `required` and `x-index` - // Create ALTER COLUMN NAME query - $this->migration->addUpCode($this->recordBuilder->renameColumn($this->model->tableAlias, $previousColumnName, $column->name)) - ->addDownCode($this->recordBuilder->renameColumn($this->model->tableAlias, $column->name, $previousColumnName)); + // see `migrationForRenameColumn()` + $fromColNameToColName[$previousColumnName] = $column->name; } } } @@ -661,5 +667,14 @@ public function handleColumnsRename(array &$columnsForCreate, array &$columnsFor foreach ($keys as $key) { unset($columnsForCreate[$key]); } + return $fromColNameToColName; + } + + public function migrationForRenameColumn(array $fromColNameToColName): void + { + foreach ($fromColNameToColName as $previousColumnName => $columnName) { + $this->migration->addUpCode($this->recordBuilder->renameColumn($this->model->tableAlias, $previousColumnName, $columnName)) + ->addDownCode($this->recordBuilder->renameColumn($this->model->tableAlias, $columnName, $previousColumnName)); + } } } diff --git a/tests/specs/change_column_name/maria/app/migrations_maria_db/m200000_000000_change_table_column_name_changes.php b/tests/specs/change_column_name/maria/app/migrations_maria_db/m200000_000000_change_table_column_name_changes.php index 1a75dbd3..06662558 100644 --- a/tests/specs/change_column_name/maria/app/migrations_maria_db/m200000_000000_change_table_column_name_changes.php +++ b/tests/specs/change_column_name/maria/app/migrations_maria_db/m200000_000000_change_table_column_name_changes.php @@ -7,13 +7,11 @@ class m200000_000000_change_table_column_name_changes extends \yii\db\Migration { public function up() { - $this->db->createCommand('ALTER TABLE {{%column_name_changes}} ADD COLUMN updated_at_2 datetime NOT NULL')->execute(); - $this->dropColumn('{{%column_name_changes}}', 'updated_at'); + $this->renameColumn('{{%column_name_changes}}', 'updated_at', 'updated_at_2'); } public function down() { - $this->addColumn('{{%column_name_changes}}', 'updated_at', $this->datetime()->notNull()); - $this->dropColumn('{{%column_name_changes}}', 'updated_at_2'); + $this->renameColumn('{{%column_name_changes}}', 'updated_at_2', 'updated_at'); } } diff --git a/tests/specs/change_column_name/mysql/app/migrations_mysql_db/m200000_000000_change_table_column_name_changes.php b/tests/specs/change_column_name/mysql/app/migrations_mysql_db/m200000_000000_change_table_column_name_changes.php index 1a75dbd3..06662558 100644 --- a/tests/specs/change_column_name/mysql/app/migrations_mysql_db/m200000_000000_change_table_column_name_changes.php +++ b/tests/specs/change_column_name/mysql/app/migrations_mysql_db/m200000_000000_change_table_column_name_changes.php @@ -7,13 +7,11 @@ class m200000_000000_change_table_column_name_changes extends \yii\db\Migration { public function up() { - $this->db->createCommand('ALTER TABLE {{%column_name_changes}} ADD COLUMN updated_at_2 datetime NOT NULL')->execute(); - $this->dropColumn('{{%column_name_changes}}', 'updated_at'); + $this->renameColumn('{{%column_name_changes}}', 'updated_at', 'updated_at_2'); } public function down() { - $this->addColumn('{{%column_name_changes}}', 'updated_at', $this->datetime()->notNull()); - $this->dropColumn('{{%column_name_changes}}', 'updated_at_2'); + $this->renameColumn('{{%column_name_changes}}', 'updated_at_2', 'updated_at'); } } diff --git a/tests/specs/change_column_name/pgsql/app/migrations_pgsql_db/m200000_000000_change_table_column_name_changes.php b/tests/specs/change_column_name/pgsql/app/migrations_pgsql_db/m200000_000000_change_table_column_name_changes.php index 803cb366..c7ef8866 100644 --- a/tests/specs/change_column_name/pgsql/app/migrations_pgsql_db/m200000_000000_change_table_column_name_changes.php +++ b/tests/specs/change_column_name/pgsql/app/migrations_pgsql_db/m200000_000000_change_table_column_name_changes.php @@ -7,13 +7,11 @@ class m200000_000000_change_table_column_name_changes extends \yii\db\Migration { public function safeUp() { - $this->db->createCommand('ALTER TABLE {{%column_name_changes}} ADD COLUMN "updated_at_2" timestamp NOT NULL')->execute(); - $this->dropColumn('{{%column_name_changes}}', 'updated_at'); + $this->renameColumn('{{%column_name_changes}}', 'updated_at', 'updated_at_2'); } public function safeDown() { - $this->addColumn('{{%column_name_changes}}', 'updated_at', $this->timestamp()->notNull()); - $this->dropColumn('{{%column_name_changes}}', 'updated_at_2'); + $this->renameColumn('{{%column_name_changes}}', 'updated_at_2', 'updated_at'); } } diff --git a/tests/specs/issue_fix/3_bug_add_remove_property_and_at_the_same_time_change_it_at_x_indexes/mysql/migrations_mysql_db/m200000_000000_change_table_addresses.php b/tests/specs/issue_fix/3_bug_add_remove_property_and_at_the_same_time_change_it_at_x_indexes/mysql/migrations_mysql_db/m200000_000000_change_table_addresses.php index d86cdcc9..2e135d86 100644 --- a/tests/specs/issue_fix/3_bug_add_remove_property_and_at_the_same_time_change_it_at_x_indexes/mysql/migrations_mysql_db/m200000_000000_change_table_addresses.php +++ b/tests/specs/issue_fix/3_bug_add_remove_property_and_at_the_same_time_change_it_at_x_indexes/mysql/migrations_mysql_db/m200000_000000_change_table_addresses.php @@ -7,17 +7,15 @@ class m200000_000000_change_table_addresses extends \yii\db\Migration { public function up() { - $this->addColumn('{{%addresses}}', 'postCode', $this->string(64)->null()->defaultValue(null)); $this->dropIndex('addresses_shortName_postalCode_key', '{{%addresses}}'); + $this->renameColumn('{{%addresses}}', 'postalCode', 'postCode'); $this->createIndex('addresses_shortName_postCode_key', '{{%addresses}}', ["shortName", "postCode"], true); - $this->dropColumn('{{%addresses}}', 'postalCode'); } public function down() { - $this->addColumn('{{%addresses}}', 'postalCode', $this->string(64)->null()->defaultValue(null)); $this->dropIndex('addresses_shortName_postCode_key', '{{%addresses}}'); + $this->renameColumn('{{%addresses}}', 'postCode', 'postalCode'); $this->createIndex('addresses_shortName_postalCode_key', '{{%addresses}}', ["shortName", "postalCode"], true); - $this->dropColumn('{{%addresses}}', 'postCode'); } } diff --git a/tests/unit/Issue58FixTest.php b/tests/unit/Issue58FixTest.php index b88f0921..d4613e67 100644 --- a/tests/unit/Issue58FixTest.php +++ b/tests/unit/Issue58FixTest.php @@ -4,7 +4,6 @@ use tests\DbTestCase; use Yii; -use yii\base\InvalidArgumentException; use yii\helpers\FileHelper; // This class contains tests for various issues present at GitHub @@ -900,7 +899,7 @@ public function test58Move1Add1Del1Col() description: type: boolean col_6: - type: boolean + type: integer paths: '/': get: @@ -919,7 +918,7 @@ class m200000_000000_change_table_fruits extends \yii\db\Migration { public function up() { - $this->addColumn('{{%fruits}}', 'col_6', $this->boolean()->null()->defaultValue(null)); + $this->addColumn('{{%fruits}}', 'col_6', $this->integer()->null()->defaultValue(null)); $this->dropColumn('{{%fruits}}', 'size'); $this->alterColumn('{{%fruits}}', 'colour', $this->tinyInteger(1)->null()->defaultValue(null)->after('id')); } @@ -962,7 +961,8 @@ public function test58Add1Del1ColAtSamePosition() name: type: boolean description_new: - type: boolean + type: integer + default: 7 colour: type: boolean size: @@ -985,7 +985,7 @@ class m200000_000000_change_table_fruits extends \yii\db\Migration { public function up() { - $this->addColumn('{{%fruits}}', 'description_new', $this->boolean()->null()->defaultValue(null)->after('name')); + $this->addColumn('{{%fruits}}', 'description_new', $this->integer()->null()->defaultValue(7)->after('name')); $this->dropColumn('{{%fruits}}', 'description'); } diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index 5578c695..f1b2bfe8 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -742,7 +742,6 @@ public function test3BugAddRemovePropertyAndAtTheSameTimeChangeItAtXIndexes() $this->createTestTableFor3BugAddRemovePropertyAndAtTheSameTimeChangeItAtXIndexes(); $testFile = Yii::getAlias("@specs/issue_fix/3_bug_add_remove_property_and_at_the_same_time_change_it_at_x_indexes/index.php"); $this->runGenerator($testFile); - $this->runActualMigrations('mysql', 1); $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ 'recursive' => true, ]); @@ -750,6 +749,7 @@ public function test3BugAddRemovePropertyAndAtTheSameTimeChangeItAtXIndexes() 'recursive' => true, ]); $this->checkFiles($actualFiles, $expectedFiles); + $this->runActualMigrations('mysql', 1); $this->dropTestTableFor3BugAddRemovePropertyAndAtTheSameTimeChangeItAtXIndexes(); } From 2d97573d4028f36c86b3875e4fae1c641d631ad9 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Sat, 14 Dec 2024 19:04:19 +0530 Subject: [PATCH 302/358] Resolve TODO --- src/lib/migrations/BaseMigrationBuilder.php | 1 - 1 file changed, 1 deletion(-) diff --git a/src/lib/migrations/BaseMigrationBuilder.php b/src/lib/migrations/BaseMigrationBuilder.php index 3d581572..416311d9 100644 --- a/src/lib/migrations/BaseMigrationBuilder.php +++ b/src/lib/migrations/BaseMigrationBuilder.php @@ -655,7 +655,6 @@ public function handleColumnsRename(array &$columnsForCreate, array &$columnsFor // existing column name should be removed from $columnsForDrop unset($columnsForDrop[$dropKeyOut]); - // TODO check in `required` and `x-index` // Create ALTER COLUMN NAME query // see `migrationForRenameColumn()` $fromColNameToColName[$previousColumnName] = $column->name; From 369fdca5e9c9db52170818e6993f145b4ade8f0b Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Tue, 17 Dec 2024 18:50:41 +0530 Subject: [PATCH 303/358] Attempt to fix Github action CI --- docker-compose.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docker-compose.yml b/docker-compose.yml index 08d61292..2eda366e 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -41,7 +41,7 @@ services: MYSQL_DATABASE: testdb maria: - image: mariadb:10.8 + image: mariadb:10.8.2 ports: - '23306:3306' volumes: From c166b0581a235d9d8ca3e02a82a9a0e25a3c142a Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Wed, 18 Dec 2024 19:38:20 +0530 Subject: [PATCH 304/358] Add test --- .../index.php | 13 +++++++++ .../index.yml | 27 +++++++++++++++++++ .../m200000_000000_change_table_fruits.php | 17 ++++++++++++ tests/unit/IssueFixTest.php | 22 +++++++++++++++ 4 files changed, 79 insertions(+) create mode 100644 tests/specs/issue_fix/64_add_a_test_for_a_column_change_data_type_comment_position_all_3_are_changed/index.php create mode 100644 tests/specs/issue_fix/64_add_a_test_for_a_column_change_data_type_comment_position_all_3_are_changed/index.yml create mode 100644 tests/specs/issue_fix/64_add_a_test_for_a_column_change_data_type_comment_position_all_3_are_changed/mysql/migrations_mysql_db/m200000_000000_change_table_fruits.php diff --git a/tests/specs/issue_fix/64_add_a_test_for_a_column_change_data_type_comment_position_all_3_are_changed/index.php b/tests/specs/issue_fix/64_add_a_test_for_a_column_change_data_type_comment_position_all_3_are_changed/index.php new file mode 100644 index 00000000..f5db5212 --- /dev/null +++ b/tests/specs/issue_fix/64_add_a_test_for_a_column_change_data_type_comment_position_all_3_are_changed/index.php @@ -0,0 +1,13 @@ + '@specs/issue_fix/64_add_a_test_for_a_column_change_data_type_comment_position_all_3_are_changed/index.yml', + 'generateUrls' => false, + 'generateModels' => false, + 'excludeModels' => [ + 'Error', + ], + 'generateControllers' => false, + 'generateMigrations' => true, + 'generateModelFaker' => false, // `generateModels` must be `true` in order to use `generateModelFaker` as `true` +]; diff --git a/tests/specs/issue_fix/64_add_a_test_for_a_column_change_data_type_comment_position_all_3_are_changed/index.yml b/tests/specs/issue_fix/64_add_a_test_for_a_column_change_data_type_comment_position_all_3_are_changed/index.yml new file mode 100644 index 00000000..4132182f --- /dev/null +++ b/tests/specs/issue_fix/64_add_a_test_for_a_column_change_data_type_comment_position_all_3_are_changed/index.yml @@ -0,0 +1,27 @@ +openapi: 3.0.3 +x-description-is-comment: true +info: + title: 'Add a test for: a column change: data type + comment + position; all 3 are changed #64' + version: 1.0.0 + +components: + schemas: + Fruit: + type: object + properties: + id: + type: integer + description: + type: string + col: + type: string + name: + type: integer + description: new desc + +paths: + '/': + get: + responses: + '200': + description: OK diff --git a/tests/specs/issue_fix/64_add_a_test_for_a_column_change_data_type_comment_position_all_3_are_changed/mysql/migrations_mysql_db/m200000_000000_change_table_fruits.php b/tests/specs/issue_fix/64_add_a_test_for_a_column_change_data_type_comment_position_all_3_are_changed/mysql/migrations_mysql_db/m200000_000000_change_table_fruits.php new file mode 100644 index 00000000..772ab122 --- /dev/null +++ b/tests/specs/issue_fix/64_add_a_test_for_a_column_change_data_type_comment_position_all_3_are_changed/mysql/migrations_mysql_db/m200000_000000_change_table_fruits.php @@ -0,0 +1,17 @@ +alterColumn('{{%fruits}}', 'name', $this->integer()->null()->defaultValue(null)->after('col')->comment('new desc')); + } + + public function down() + { + $this->alterColumn('{{%fruits}}', 'name', $this->text()->null()->after('id')->comment('desc')); + } +} diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index b5d5868b..2fd0aef8 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -916,4 +916,26 @@ public function test35ResolveTodoReCheckOptionsRouteInRestAction() $this->checkFiles($actualFiles, $expectedFiles); } + public function test64AddATestForAColumnChangeDataTypeCommentPositionAll3AreChanged() + { + Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%fruits}}')->execute(); + Yii::$app->db->createCommand()->createTable('{{%fruits}}', [ + 'id' => 'pk', + 'name' => 'text comment "desc"', + 'description' => 'text', + 'col' => 'text', + ])->execute(); + + $testFile = Yii::getAlias("@specs/issue_fix/64_add_a_test_for_a_column_change_data_type_comment_position_all_3_are_changed/index.php"); + $this->runGenerator($testFile); + $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ + 'recursive' => true, + ]); + $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/64_add_a_test_for_a_column_change_data_type_comment_position_all_3_are_changed/mysql"), [ + 'recursive' => true, + ]); + $this->checkFiles($actualFiles, $expectedFiles); + $this->runActualMigrations('mysql', 1); + Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%fruits}}')->execute(); + } } From 9232b4525eea270f7b25a7a3004f830c943f470f Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Wed, 25 Dec 2024 18:49:50 +0530 Subject: [PATCH 305/358] Create PR --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index f68df469..4cc1d72a 100644 --- a/README.md +++ b/README.md @@ -779,3 +779,4 @@ Professional support, consulting as well as software development services are av https://www.cebe.cc/en/contact Development of this library is sponsored by [cebe.:cloud: "Your Professional Deployment Platform"](https://cebe.cloud). + From 626818b9d31dc901b3a14e6d3abcf5c46abb37d1 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Sat, 28 Dec 2024 18:58:06 +0530 Subject: [PATCH 306/358] Add failing test - WIP --- README.md | 1 - src/lib/AttributeResolver.php | 2 +- .../index.php | 14 +++++++++ .../index.yaml | 31 +++++++++++++++++++ tests/unit/IssueFixTest.php | 16 ++++++++++ 5 files changed, 62 insertions(+), 2 deletions(-) create mode 100644 tests/specs/issue_fix/74_invalid_schema_reference_error/index.php create mode 100644 tests/specs/issue_fix/74_invalid_schema_reference_error/index.yaml diff --git a/README.md b/README.md index 4cc1d72a..f68df469 100644 --- a/README.md +++ b/README.md @@ -779,4 +779,3 @@ Professional support, consulting as well as software development services are av https://www.cebe.cc/en/contact Development of this library is sponsored by [cebe.:cloud: "Your Professional Deployment Platform"](https://cebe.cloud). - diff --git a/src/lib/AttributeResolver.php b/src/lib/AttributeResolver.php index a43aa8ba..87e90541 100644 --- a/src/lib/AttributeResolver.php +++ b/src/lib/AttributeResolver.php @@ -498,7 +498,7 @@ protected function resolvePropertyRef(PropertySchema $property, Attribute $attri $attribute->setPhpType($fkProperty->guessPhpType()) ->setDbType($fkProperty->guessDbType(true)) ->setSize($fkProperty->getMaxLength()) - ->setDescription($fkProperty->getAttr('description')) + ->setDescription($fkProperty->getAttr('description', '')) ->setDefault($fkProperty->guessDefault()) ->setLimits($min, $max, $fkProperty->getMinLength()); $this->attributes[$property->getName()] = diff --git a/tests/specs/issue_fix/74_invalid_schema_reference_error/index.php b/tests/specs/issue_fix/74_invalid_schema_reference_error/index.php new file mode 100644 index 00000000..3b4df8b4 --- /dev/null +++ b/tests/specs/issue_fix/74_invalid_schema_reference_error/index.php @@ -0,0 +1,14 @@ + '@specs/issue_fix/74_invalid_schema_reference_error/index.yaml', + 'generateUrls' => true, + 'generateModels' => true, + 'excludeModels' => [ + 'Error', + ], + 'generateControllers' => true, + 'generateMigrations' => true, + 'generateModelFaker' => true, // `generateModels` must be `true` in order to use `generateModelFaker` as `true` + 'ignoreSpecErrors' => true, +]; diff --git a/tests/specs/issue_fix/74_invalid_schema_reference_error/index.yaml b/tests/specs/issue_fix/74_invalid_schema_reference_error/index.yaml new file mode 100644 index 00000000..d975fc79 --- /dev/null +++ b/tests/specs/issue_fix/74_invalid_schema_reference_error/index.yaml @@ -0,0 +1,31 @@ +openapi: "3.0.0" +info: + version: 1.0.0 + title: Invalid schema reference error \#74 +paths: + /: + get: + responses: + '200': + description: The information + +components: + schemas: + Invoice: + type: object + properties: + id: + type: integer + vat_rate: + $ref: '#/components/schemas/Product/properties/vat_rate' + Product: + type: object + properties: + id: + type: integer + vat_rate: + type: string + enum: + - normal + - none + default: normal diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index f1b2bfe8..f68dfc74 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -962,4 +962,20 @@ public function test63JustColumnNameRename() $this->checkFiles($actualFiles, $expectedFiles); Yii::$app->db->createCommand('DROP TABLE IF EXISTS {{%fruits}}')->execute(); } + + // https://github.com/php-openapi/yii2-openapi/issues/63 + public function test74InvalidSchemaReferenceError() + { + $testFile = Yii::getAlias("@specs/issue_fix/74_invalid_schema_reference_error/index.php"); + + $this->runGenerator($testFile); +// $this->runActualMigrations('mysql', 1); +// $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ +// 'recursive' => true, +// ]); +// $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/74_invalid_schema_reference_error/mysql"), [ +// 'recursive' => true, +// ]); +// $this->checkFiles($actualFiles, $expectedFiles); + } } From 0c41b52cd9da0634a84405e46e23da8660e9c73f Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Tue, 31 Dec 2024 15:39:05 +0530 Subject: [PATCH 307/358] Fix another bug --- src/lib/migrations/BaseMigrationBuilder.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/lib/migrations/BaseMigrationBuilder.php b/src/lib/migrations/BaseMigrationBuilder.php index 416311d9..ded9a7af 100644 --- a/src/lib/migrations/BaseMigrationBuilder.php +++ b/src/lib/migrations/BaseMigrationBuilder.php @@ -491,7 +491,7 @@ public function tmpSaveNewCol(string $tableAlias, \cebe\yii2openapi\db\ColumnSch Yii::$app->db->createCommand()->createTable($tmpTableName, $column)->execute(); if (ApiGenerator::isPostgres() && $columnSchema->comment) { - Yii::$app->db->createCommand("COMMENT ON COLUMN $tmpTableName.$columnSchema->name IS {$this->db->quoteValue($columnSchema->comment)}")->execute(); + Yii::$app->db->createCommand("COMMENT ON COLUMN $tmpTableName.\"$columnSchema->name\" IS {$this->db->quoteValue($columnSchema->comment)}")->execute(); } $table = Yii::$app->db->getTableSchema($tmpTableName); From 8ab381024b02afd0dd57e83e732b875ff1c8eaee Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Tue, 31 Dec 2024 19:12:48 +0530 Subject: [PATCH 308/358] Add failing test --- .../Product.yaml | 26 +++++++++++++++++++ .../index.yaml | 3 ++- 2 files changed, 28 insertions(+), 1 deletion(-) create mode 100644 tests/specs/issue_fix/74_invalid_schema_reference_error/Product.yaml diff --git a/tests/specs/issue_fix/74_invalid_schema_reference_error/Product.yaml b/tests/specs/issue_fix/74_invalid_schema_reference_error/Product.yaml new file mode 100644 index 00000000..bb23597a --- /dev/null +++ b/tests/specs/issue_fix/74_invalid_schema_reference_error/Product.yaml @@ -0,0 +1,26 @@ +# Product: +title: Product +x-table: products +type: object + +required: + - id + - vat_rate + + +properties: + + id: + type: integer + example: 12531 + readOnly: true + + + vat_rate: + type: string + enum: + - standard + - reduced + - custom + - none + default: standard diff --git a/tests/specs/issue_fix/74_invalid_schema_reference_error/index.yaml b/tests/specs/issue_fix/74_invalid_schema_reference_error/index.yaml index d975fc79..d2c8d1bb 100644 --- a/tests/specs/issue_fix/74_invalid_schema_reference_error/index.yaml +++ b/tests/specs/issue_fix/74_invalid_schema_reference_error/index.yaml @@ -17,7 +17,8 @@ components: id: type: integer vat_rate: - $ref: '#/components/schemas/Product/properties/vat_rate' + # $ref: '#/components/schemas/Product/properties/vat_rate' # issue is not observed + $ref: './Product.yaml#/properties/vat_rate' # issue is observed Product: type: object properties: From bccf2a8307f0db4148284bc84871bf4d8bf952e4 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Tue, 31 Dec 2024 21:20:48 +0530 Subject: [PATCH 309/358] In progress --- src/lib/openapi/PropertySchema.php | 12 +++++++++++- .../74_invalid_schema_reference_error/index.yaml | 2 +- tests/unit/IssueFixTest.php | 8 ++++++++ 3 files changed, 20 insertions(+), 2 deletions(-) diff --git a/src/lib/openapi/PropertySchema.php b/src/lib/openapi/PropertySchema.php index 9ff64094..a8b85424 100644 --- a/src/lib/openapi/PropertySchema.php +++ b/src/lib/openapi/PropertySchema.php @@ -70,6 +70,7 @@ class PropertySchema /** @var string $refPointer */ private $refPointer; + private $uri; /** @var \cebe\yii2openapi\lib\openapi\ComponentSchema $refSchema */ private $refSchema; @@ -170,6 +171,7 @@ private function initReference():void { $this->isReference = true; $this->refPointer = $this->property->getJsonReference()->getJsonPointer()->getPointer(); + $this->uri = $this->property->getJsonReference()->getDocumentUri(); $refSchemaName = $this->getRefSchemaName(); if ($this->isRefPointerToSelf()) { $this->refSchema = $this->schema; @@ -194,6 +196,7 @@ private function initItemsReference():void return; } $this->refPointer = $items->getJsonReference()->getJsonPointer()->getPointer(); + $this->uri = $this->property->getJsonReference()->getDocumentUri(); if ($this->isRefPointerToSelf()) { $this->refSchema = $this->schema; } elseif ($this->isRefPointerToSchema()) { @@ -301,8 +304,15 @@ public function getRefSchemaName():string '~^'.self::REFERENCE_PATH.'(?.+)/properties/(?.+)$~' : '~^'.self::REFERENCE_PATH.'(?.+)$~'; if (!\preg_match($pattern, $this->refPointer, $matches)) { - throw new InvalidDefinitionException('Invalid schema reference'); + $pattern = '/((\.\/)*)(?.+)(\.)(yml|yaml)(.*)/'; +// $pattern = '~^(?.+)(\.+)(yaml+)(.*)$~'; + if (strpos($this->uri, '#') !== false && !\preg_match($pattern, $this->uri, $matches)) { +// throw new InvalidDefinitionException('Invalid schema reference'); + } else { + throw new InvalidDefinitionException('Invalid schema reference'); + } } + var_dump($matches); return $matches['schemaName']; } diff --git a/tests/specs/issue_fix/74_invalid_schema_reference_error/index.yaml b/tests/specs/issue_fix/74_invalid_schema_reference_error/index.yaml index d2c8d1bb..014fe5c8 100644 --- a/tests/specs/issue_fix/74_invalid_schema_reference_error/index.yaml +++ b/tests/specs/issue_fix/74_invalid_schema_reference_error/index.yaml @@ -17,7 +17,7 @@ components: id: type: integer vat_rate: - # $ref: '#/components/schemas/Product/properties/vat_rate' # issue is not observed + # $ref: '#/components/schemas/Product/properties/vat_rate' # issue is not observed $ref: './Product.yaml#/properties/vat_rate' # issue is observed Product: type: object diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index f68dfc74..83878436 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -966,6 +966,14 @@ public function test63JustColumnNameRename() // https://github.com/php-openapi/yii2-openapi/issues/63 public function test74InvalidSchemaReferenceError() { +// $pattern = '~^(?.+)(\.+)(yaml+)(.*)$~'; +// $pattern = '/((\.\/)*)(?.+)(\.)(yml|yaml)(.*)/'; +// +// $pointer = './Product.yaml#/properties/vat_rate'; +// preg_match($pattern, $pointer, $matches); +// $this->assertSame('supda saf', $matches); +// return; + $testFile = Yii::getAlias("@specs/issue_fix/74_invalid_schema_reference_error/index.php"); $this->runGenerator($testFile); From b130a4febf96b0ac9ac4302f2dda85c1d80f700d Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Fri, 3 Jan 2025 18:08:24 +0530 Subject: [PATCH 310/358] Fix this issue --- src/lib/openapi/PropertySchema.php | 16 ++++++++-------- .../Product.yaml | 8 -------- .../74_invalid_schema_reference_error/index.yaml | 11 +---------- 3 files changed, 9 insertions(+), 26 deletions(-) diff --git a/src/lib/openapi/PropertySchema.php b/src/lib/openapi/PropertySchema.php index a8b85424..eade252e 100644 --- a/src/lib/openapi/PropertySchema.php +++ b/src/lib/openapi/PropertySchema.php @@ -196,7 +196,7 @@ private function initItemsReference():void return; } $this->refPointer = $items->getJsonReference()->getJsonPointer()->getPointer(); - $this->uri = $this->property->getJsonReference()->getDocumentUri(); + $this->uri = $items->getJsonReference()->getDocumentUri(); if ($this->isRefPointerToSelf()) { $this->refSchema = $this->schema; } elseif ($this->isRefPointerToSchema()) { @@ -267,7 +267,9 @@ public function getSelfTargetProperty():?PropertySchema public function isRefPointerToSchema():bool { - return $this->refPointer && strpos($this->refPointer, self::REFERENCE_PATH) === 0; + return $this->refPointer && + ((strpos($this->refPointer, self::REFERENCE_PATH) === 0) || + (str_ends_with($this->uri, '.yml')) || (str_ends_with($this->uri, '.yaml'))); } public function isRefPointerToSelf():bool @@ -303,16 +305,14 @@ public function getRefSchemaName():string $pattern = strpos($this->refPointer, '/properties/') !== false ? '~^'.self::REFERENCE_PATH.'(?.+)/properties/(?.+)$~' : '~^'.self::REFERENCE_PATH.'(?.+)$~'; + $separateFilePattern = '/((\.\/)*)(?.+)(\.)(yml|yaml)(.*)/'; # https://github.com/php-openapi/yii2-openapi/issues/74 if (!\preg_match($pattern, $this->refPointer, $matches)) { - $pattern = '/((\.\/)*)(?.+)(\.)(yml|yaml)(.*)/'; -// $pattern = '~^(?.+)(\.+)(yaml+)(.*)$~'; - if (strpos($this->uri, '#') !== false && !\preg_match($pattern, $this->uri, $matches)) { -// throw new InvalidDefinitionException('Invalid schema reference'); - } else { + if (!\preg_match($separateFilePattern, $this->uri, $separateFilePatternMatches)) { throw new InvalidDefinitionException('Invalid schema reference'); + } else { + return $separateFilePatternMatches['schemaName']; } } - var_dump($matches); return $matches['schemaName']; } diff --git a/tests/specs/issue_fix/74_invalid_schema_reference_error/Product.yaml b/tests/specs/issue_fix/74_invalid_schema_reference_error/Product.yaml index bb23597a..ca81d464 100644 --- a/tests/specs/issue_fix/74_invalid_schema_reference_error/Product.yaml +++ b/tests/specs/issue_fix/74_invalid_schema_reference_error/Product.yaml @@ -7,20 +7,12 @@ required: - id - vat_rate - properties: - id: type: integer - example: 12531 - readOnly: true - - vat_rate: type: string enum: - standard - - reduced - - custom - none default: standard diff --git a/tests/specs/issue_fix/74_invalid_schema_reference_error/index.yaml b/tests/specs/issue_fix/74_invalid_schema_reference_error/index.yaml index 014fe5c8..cc18b7d2 100644 --- a/tests/specs/issue_fix/74_invalid_schema_reference_error/index.yaml +++ b/tests/specs/issue_fix/74_invalid_schema_reference_error/index.yaml @@ -20,13 +20,4 @@ components: # $ref: '#/components/schemas/Product/properties/vat_rate' # issue is not observed $ref: './Product.yaml#/properties/vat_rate' # issue is observed Product: - type: object - properties: - id: - type: integer - vat_rate: - type: string - enum: - - normal - - none - default: normal + $ref: ./Product.yaml From ddf4a6b40b217096898fd585bc3420a4a965b98a Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Tue, 7 Jan 2025 18:02:22 +0530 Subject: [PATCH 311/358] Fix issue --- src/lib/AttributeResolver.php | 4 ++++ .../issue_fix/74_invalid_schema_reference_error/index.php | 5 ++--- .../issue_fix/74_invalid_schema_reference_error/index.yaml | 2 ++ 3 files changed, 8 insertions(+), 3 deletions(-) diff --git a/src/lib/AttributeResolver.php b/src/lib/AttributeResolver.php index 87e90541..cc41a6fb 100644 --- a/src/lib/AttributeResolver.php +++ b/src/lib/AttributeResolver.php @@ -501,6 +501,10 @@ protected function resolvePropertyRef(PropertySchema $property, Attribute $attri ->setDescription($fkProperty->getAttr('description', '')) ->setDefault($fkProperty->guessDefault()) ->setLimits($min, $max, $fkProperty->getMinLength()); + + if ($fkProperty->hasEnum()) { + $attribute->setEnumValues($fkProperty->getAttr('enum')); + } $this->attributes[$property->getName()] = $attribute->setFakerStub($this->guessFakerStub($attribute, $fkProperty)); } diff --git a/tests/specs/issue_fix/74_invalid_schema_reference_error/index.php b/tests/specs/issue_fix/74_invalid_schema_reference_error/index.php index 3b4df8b4..cbe2f6dc 100644 --- a/tests/specs/issue_fix/74_invalid_schema_reference_error/index.php +++ b/tests/specs/issue_fix/74_invalid_schema_reference_error/index.php @@ -2,13 +2,12 @@ return [ 'openApiPath' => '@specs/issue_fix/74_invalid_schema_reference_error/index.yaml', - 'generateUrls' => true, + 'generateUrls' => false, 'generateModels' => true, 'excludeModels' => [ 'Error', ], - 'generateControllers' => true, + 'generateControllers' => false, 'generateMigrations' => true, 'generateModelFaker' => true, // `generateModels` must be `true` in order to use `generateModelFaker` as `true` - 'ignoreSpecErrors' => true, ]; diff --git a/tests/specs/issue_fix/74_invalid_schema_reference_error/index.yaml b/tests/specs/issue_fix/74_invalid_schema_reference_error/index.yaml index cc18b7d2..271c63d1 100644 --- a/tests/specs/issue_fix/74_invalid_schema_reference_error/index.yaml +++ b/tests/specs/issue_fix/74_invalid_schema_reference_error/index.yaml @@ -13,6 +13,8 @@ components: schemas: Invoice: type: object + required: + - vat_rate properties: id: type: integer From 064673a29c64f097d889f1133e809d508f8d0b74 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Tue, 7 Jan 2025 18:05:47 +0530 Subject: [PATCH 312/358] Complete test --- .../m200000_000000_create_table_invoices.php | 20 +++ .../m200000_000001_create_table_products.php | 20 +++ .../mysql/models/BaseModelFaker.php | 144 ++++++++++++++++++ .../mysql/models/Invoice.php | 10 ++ .../mysql/models/InvoiceFaker.php | 41 +++++ .../mysql/models/Product.php | 10 ++ .../mysql/models/ProductFaker.php | 41 +++++ .../mysql/models/base/Invoice.php | 35 +++++ .../mysql/models/base/Product.php | 35 +++++ tests/unit/IssueFixTest.php | 25 +-- 10 files changed, 364 insertions(+), 17 deletions(-) create mode 100644 tests/specs/issue_fix/74_invalid_schema_reference_error/mysql/migrations_mysql_db/m200000_000000_create_table_invoices.php create mode 100644 tests/specs/issue_fix/74_invalid_schema_reference_error/mysql/migrations_mysql_db/m200000_000001_create_table_products.php create mode 100644 tests/specs/issue_fix/74_invalid_schema_reference_error/mysql/models/BaseModelFaker.php create mode 100644 tests/specs/issue_fix/74_invalid_schema_reference_error/mysql/models/Invoice.php create mode 100644 tests/specs/issue_fix/74_invalid_schema_reference_error/mysql/models/InvoiceFaker.php create mode 100644 tests/specs/issue_fix/74_invalid_schema_reference_error/mysql/models/Product.php create mode 100644 tests/specs/issue_fix/74_invalid_schema_reference_error/mysql/models/ProductFaker.php create mode 100644 tests/specs/issue_fix/74_invalid_schema_reference_error/mysql/models/base/Invoice.php create mode 100644 tests/specs/issue_fix/74_invalid_schema_reference_error/mysql/models/base/Product.php diff --git a/tests/specs/issue_fix/74_invalid_schema_reference_error/mysql/migrations_mysql_db/m200000_000000_create_table_invoices.php b/tests/specs/issue_fix/74_invalid_schema_reference_error/mysql/migrations_mysql_db/m200000_000000_create_table_invoices.php new file mode 100644 index 00000000..1e21544d --- /dev/null +++ b/tests/specs/issue_fix/74_invalid_schema_reference_error/mysql/migrations_mysql_db/m200000_000000_create_table_invoices.php @@ -0,0 +1,20 @@ +createTable('{{%invoices}}', [ + 'id' => $this->primaryKey(), + 'vat_rate' => 'enum("standard", "none") NOT NULL DEFAULT \'standard\'', + ]); + } + + public function down() + { + $this->dropTable('{{%invoices}}'); + } +} diff --git a/tests/specs/issue_fix/74_invalid_schema_reference_error/mysql/migrations_mysql_db/m200000_000001_create_table_products.php b/tests/specs/issue_fix/74_invalid_schema_reference_error/mysql/migrations_mysql_db/m200000_000001_create_table_products.php new file mode 100644 index 00000000..fcde7ba8 --- /dev/null +++ b/tests/specs/issue_fix/74_invalid_schema_reference_error/mysql/migrations_mysql_db/m200000_000001_create_table_products.php @@ -0,0 +1,20 @@ +createTable('{{%products}}', [ + 'id' => $this->primaryKey(), + 'vat_rate' => 'enum("standard", "none") NOT NULL DEFAULT \'standard\'', + ]); + } + + public function down() + { + $this->dropTable('{{%products}}'); + } +} diff --git a/tests/specs/issue_fix/74_invalid_schema_reference_error/mysql/models/BaseModelFaker.php b/tests/specs/issue_fix/74_invalid_schema_reference_error/mysql/models/BaseModelFaker.php new file mode 100644 index 00000000..c367fbb4 --- /dev/null +++ b/tests/specs/issue_fix/74_invalid_schema_reference_error/mysql/models/BaseModelFaker.php @@ -0,0 +1,144 @@ +faker = FakerFactory::create(str_replace('-', '_', \Yii::$app->language)); + $this->uniqueFaker = new UniqueGenerator($this->faker); + } + + abstract public function generateModel($attributes = []); + + public function getFaker():Generator + { + return $this->faker; + } + + public function getUniqueFaker():UniqueGenerator + { + return $this->uniqueFaker; + } + + public function setFaker(Generator $faker):void + { + $this->faker = $faker; + } + + public function setUniqueFaker(UniqueGenerator $faker):void + { + $this->uniqueFaker = $faker; + } + + /** + * Generate and return model + * @param array|callable $attributes + * @param UniqueGenerator|null $uniqueFaker + * @return \yii\db\ActiveRecord + * @example MyFaker::makeOne(['user_id' => 1, 'title' => 'foo']); + * @example MyFaker::makeOne( function($model, $faker) { + * $model->scenario = 'create'; + * $model->setAttributes(['user_id' => 1, 'title' => $faker->sentence]); + * return $model; + * }); + */ + public static function makeOne($attributes = [], ?UniqueGenerator $uniqueFaker = null) + { + $fakeBuilder = new static(); + if ($uniqueFaker !== null) { + $fakeBuilder->setUniqueFaker($uniqueFaker); + } + $model = $fakeBuilder->generateModel($attributes); + return $model; + } + + /** + * Generate, save and return model + * @param array|callable $attributes + * @param UniqueGenerator|null $uniqueFaker + * @return \yii\db\ActiveRecord + * @example MyFaker::saveOne(['user_id' => 1, 'title' => 'foo']); + * @example MyFaker::saveOne( function($model, $faker) { + * $model->scenario = 'create'; + * $model->setAttributes(['user_id' => 1, 'title' => $faker->sentence]); + * return $model; + * }); + */ + public static function saveOne($attributes = [], ?UniqueGenerator $uniqueFaker = null) + { + $model = static::makeOne($attributes, $uniqueFaker); + $model->save(); + return $model; + } + + /** + * Generate and return multiple models + * @param int $number + * @param array|callable $commonAttributes + * @return \yii\db\ActiveRecord[]|array + * @example TaskFaker::make(5, ['project_id'=>1, 'user_id' => 2]); + * @example TaskFaker::make(5, function($model, $faker, $uniqueFaker) { + * $model->setAttributes(['name' => $uniqueFaker->username, 'state'=>$faker->boolean(20)]); + * return $model; + * }); + */ + public static function make(int $number, $commonAttributes = [], ?UniqueGenerator $uniqueFaker = null):array + { + if ($number < 1) { + return []; + } + $fakeBuilder = new static(); + if ($uniqueFaker !== null) { + $fakeBuilder->setUniqueFaker($uniqueFaker); + } + return array_map(function () use ($commonAttributes, $fakeBuilder) { + $model = $fakeBuilder->generateModel($commonAttributes); + return $model; + }, range(0, $number -1)); + } + + /** + * Generate, save and return multiple models + * @param int $number + * @param array|callable $commonAttributes + * @return \yii\db\ActiveRecord[]|array + * @example TaskFaker::save(5, ['project_id'=>1, 'user_id' => 2]); + * @example TaskFaker::save(5, function($model, $faker, $uniqueFaker) { + * $model->setAttributes(['name' => $uniqueFaker->username, 'state'=>$faker->boolean(20)]); + * return $model; + * }); + */ + public static function save(int $number, $commonAttributes = [], ?UniqueGenerator $uniqueFaker = null):array + { + if ($number < 1) { + return []; + } + $fakeBuilder = new static(); + if ($uniqueFaker !== null) { + $fakeBuilder->setUniqueFaker($uniqueFaker); + } + return array_map(function () use ($commonAttributes, $fakeBuilder) { + $model = $fakeBuilder->generateModel($commonAttributes); + $model->save(); + return $model; + }, range(0, $number -1)); + } +} diff --git a/tests/specs/issue_fix/74_invalid_schema_reference_error/mysql/models/Invoice.php b/tests/specs/issue_fix/74_invalid_schema_reference_error/mysql/models/Invoice.php new file mode 100644 index 00000000..43e37fd3 --- /dev/null +++ b/tests/specs/issue_fix/74_invalid_schema_reference_error/mysql/models/Invoice.php @@ -0,0 +1,10 @@ +generateModels(['author_id' => 1]); + * $model = (new PostFaker())->generateModels(function($model, $faker, $uniqueFaker) { + * $model->scenario = 'create'; + * $model->author_id = 1; + * return $model; + * }); + **/ + public function generateModel($attributes = []) + { + $faker = $this->faker; + $uniqueFaker = $this->uniqueFaker; + $model = new Invoice(); + //$model->id = $uniqueFaker->numberBetween(0, 1000000); + $model->vat_rate = $faker->randomElement(['standard','none']); + if (!is_callable($attributes)) { + $model->setAttributes($attributes, false); + } else { + $model = $attributes($model, $faker, $uniqueFaker); + } + return $model; + } +} diff --git a/tests/specs/issue_fix/74_invalid_schema_reference_error/mysql/models/Product.php b/tests/specs/issue_fix/74_invalid_schema_reference_error/mysql/models/Product.php new file mode 100644 index 00000000..a8411efa --- /dev/null +++ b/tests/specs/issue_fix/74_invalid_schema_reference_error/mysql/models/Product.php @@ -0,0 +1,10 @@ +generateModels(['author_id' => 1]); + * $model = (new PostFaker())->generateModels(function($model, $faker, $uniqueFaker) { + * $model->scenario = 'create'; + * $model->author_id = 1; + * return $model; + * }); + **/ + public function generateModel($attributes = []) + { + $faker = $this->faker; + $uniqueFaker = $this->uniqueFaker; + $model = new Product(); + //$model->id = $uniqueFaker->numberBetween(0, 1000000); + $model->vat_rate = $faker->randomElement(['standard','none']); + if (!is_callable($attributes)) { + $model->setAttributes($attributes, false); + } else { + $model = $attributes($model, $faker, $uniqueFaker); + } + return $model; + } +} diff --git a/tests/specs/issue_fix/74_invalid_schema_reference_error/mysql/models/base/Invoice.php b/tests/specs/issue_fix/74_invalid_schema_reference_error/mysql/models/base/Invoice.php new file mode 100644 index 00000000..d81c8ce3 --- /dev/null +++ b/tests/specs/issue_fix/74_invalid_schema_reference_error/mysql/models/base/Invoice.php @@ -0,0 +1,35 @@ + [['vat_rate'], 'required'], + 'vat_rate_string' => [['vat_rate'], 'string'], + 'vat_rate_in' => [['vat_rate'], 'in', 'range' => [ + 'standard', + 'none', + ]], + 'vat_rate_default' => [['vat_rate'], 'default', 'value' => 'standard'], + ]; + } +} diff --git a/tests/specs/issue_fix/74_invalid_schema_reference_error/mysql/models/base/Product.php b/tests/specs/issue_fix/74_invalid_schema_reference_error/mysql/models/base/Product.php new file mode 100644 index 00000000..184a6395 --- /dev/null +++ b/tests/specs/issue_fix/74_invalid_schema_reference_error/mysql/models/base/Product.php @@ -0,0 +1,35 @@ + [['vat_rate'], 'required'], + 'vat_rate_string' => [['vat_rate'], 'string'], + 'vat_rate_in' => [['vat_rate'], 'in', 'range' => [ + 'standard', + 'none', + ]], + 'vat_rate_default' => [['vat_rate'], 'default', 'value' => 'standard'], + ]; + } +} diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index 83878436..11134111 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -966,24 +966,15 @@ public function test63JustColumnNameRename() // https://github.com/php-openapi/yii2-openapi/issues/63 public function test74InvalidSchemaReferenceError() { -// $pattern = '~^(?.+)(\.+)(yaml+)(.*)$~'; -// $pattern = '/((\.\/)*)(?.+)(\.)(yml|yaml)(.*)/'; -// -// $pointer = './Product.yaml#/properties/vat_rate'; -// preg_match($pattern, $pointer, $matches); -// $this->assertSame('supda saf', $matches); -// return; - $testFile = Yii::getAlias("@specs/issue_fix/74_invalid_schema_reference_error/index.php"); - $this->runGenerator($testFile); -// $this->runActualMigrations('mysql', 1); -// $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ -// 'recursive' => true, -// ]); -// $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/74_invalid_schema_reference_error/mysql"), [ -// 'recursive' => true, -// ]); -// $this->checkFiles($actualFiles, $expectedFiles); + $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ + 'recursive' => true, + ]); + $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/74_invalid_schema_reference_error/mysql"), [ + 'recursive' => true, + ]); + $this->checkFiles($actualFiles, $expectedFiles); + $this->runActualMigrations(); } } From 1704fb41347c4ec784b7e670fec13a3cad717542 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sigmar=20K=C3=BChlmann?= Date: Fri, 7 Feb 2025 14:14:59 +0100 Subject: [PATCH 313/358] x-scenarios README --- README.md | 218 ++++++++++++++++++++++++++++++ src/generator/ApiGenerator.php | 2 +- src/generator/default/dbmodel.php | 6 +- src/lib/Config.php | 2 +- src/lib/items/DbModel.php | 2 +- 5 files changed, 225 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index f68df469..82d1fc0b 100644 --- a/README.md +++ b/README.md @@ -186,6 +186,224 @@ Such values are not allowed: If `enum` and `x-db-type` both are provided then for database column schema (migrations), only `x-db-type` will be considered ignoring `enum`. +### `x-scenarios` + +Automatically generated scenarios from the model 'x-scenarios'. +Each scenario is assigned attributes as in the 'default' scenario. +The advantage is that the scenario can be used immediately. +This can be overridden in the child model if needed. + +The 'default' scenario and all scenarios mentioned in the rules() using 'on' and 'except' +are automatically included in the scenarios() function for the model. + +There are three ways to define the scenarios `description`: +- use scenario description default settings `public $scenarioDefaultDescription = "Scenario {scenarioName}"`. +- use custom `scenarioDefaultDescription` at `dbModel`. +- use custom `description` for individual scenario. + +1. Example with default setting. + ```yaml + Invoice: + type: object + x-scenarios: + - name: create + - name: update + ``` + + The following code is generated in the abstract model: + ```php + abstract class Invoice extends \yii\db\ActiveRecord + { + /** + * Scenario create + */ + public const SCENARIO_CREATE = 'create'; + + /** + * Scenario update + */ + public const SCENARIO_UPDATE = 'update'; + + /** + * Automatically generated scenarios from the model 'x-scenarios'. + * @return array a list of scenarios and the corresponding active attributes. + */ + public function scenarios() + { + $parentScenarios = parent::scenarios(); + + /** + * Each scenario is assigned attributes as in the 'default' scenario. + * The advantage is that the scenario can be used immediately. + * This can be overridden in the child model if needed. + */ + $default = $parentScenarios[self::SCENARIO_DEFAULT]; + + return [ + self::SCENARIO_CREATE => $default, + self::SCENARIO_UPDATE => $default, + /** + * The 'default' scenario and all scenarios mentioned in the rules() using 'on' and 'except' + * are automatically included in the scenarios() function for the model. + */ + ...$parentScenarios, + ]; + } + } + ``` + +2. Example with custom `description` for individual scenario. + ```yaml + Invoice: + type: object + x-scenarios: + - name: create + description: My custom description for scenario create + - name: update + ``` + + The following code is generated in the abstract model: + ```php + abstract class Invoice extends \yii\db\ActiveRecord + { + /** + * My custom description for scenario create + */ + public const SCENARIO_CREATE = 'create'; + + /** + * Scenario update + */ + public const SCENARIO_UPDATE = 'update'; + + /** + * Automatically generated scenarios from the model 'x-scenarios'. + * @return array a list of scenarios and the corresponding active attributes. + */ + public function scenarios() + {...} + } + ``` + +3. Example with custom `scenarioDefaultDescription`. + + Set custom `scenarioDefaultDescription` at `dbModel`. + `scenarioDefaultDescription` Accepted-Placeholder: {scenarioName}, {scenarioConst}, {modelName}. + + For example, for the `create` scenario in the `Invoice` model, the placeholders would result in the following: + `{scenarioName}` = `create` + `{scenarioConst}` = `SCENARIO_CREATE` + `{modelName}` = `Invoice` + + php-config-settings + ```php + $config['modules']['gii']['generators']['api'] = [ + 'class' => \cebe\yii2openapi\generator\ApiGenerator::class, + 'dbModel' => [ + /** Accepted-Placeholder: {scenarioName}, {scenarioConst}, {modelName}. @see DbModel::$scenarioDefaultDescription */ + 'scenarioDefaultDescription' => "This scenario \"{scenarioName}\" at Model \"{modelName}\" has Constant {scenarioConst}.", + ], + ... + ]; + ``` + + ```yaml + Invoice: + type: object + x-scenarios: + - name: create + description: My custom description for scenario create + - name: update + ``` + + The following code is generated in the abstract model: + ```php + abstract class Invoice extends \yii\db\ActiveRecord + { + /** + * My custom description for scenario create + */ + public const SCENARIO_CREATE = 'create'; + + /** + * This scenario "update" at Model "Invoice" has Constant SCENARIO_UPDATE. + */ + public const SCENARIO_UPDATE = 'update'; + + /** + * Automatically generated scenarios from the model 'x-scenarios'. + * @return array a list of scenarios and the corresponding active attributes. + */ + public function scenarios() + {...} + } + ``` + +4. Example with custom `scenarioDefaultDescription` + and use-case: both '\cebe\yii2openapi\generator\ApiGenerator::class' and '\common\client_generator\{your_ApiClientGenerator}::class' are used. + + Set custom `scenarioDefaultDescription` at `dbModel`. + `scenarioDefaultDescription` Accepted-Placeholder: {scenarioName}, {scenarioConst}, {modelName}. + + php-config-settings + ```php + $config['modules']['gii']['generators']['api'] = [ + 'class' => \cebe\yii2openapi\generator\ApiGenerator::class, + 'dbModel' => [ + /** Accepted-Placeholder: {scenarioName}, {scenarioConst}, {modelName}. @see DbModel::$scenarioDefaultDescription */ + 'scenarioDefaultDescription' => implode("\n", [ + "This Backend-Scenario \"{scenarioName}\" exist in both the frontend model and the backend model.", + "@see \common\client\models\{modelName}::{scenarioConst}", + ]), + ], + ... + ]; + + $config['modules']['gii']['generators']['api-client'] = [ + 'class' => \common\client_generator\{your_ApiClientGenerator}::class, + 'dbModel' => [ + /** AcceptedInputs: {scenarioName}, {scenarioConst}, {modelName}. @see DbModel::$scenarioDefaultDescription */ + 'scenarioDefaultDescription' => implode("\n", [ + "This Frontend-Scenario \"{scenarioName}\" exist in both the frontend model and the backend model.", + "@see \common\models\base\{modelName}::{scenarioConst}", + ]), + ], + ... + ``` + + ```yaml + Invoice: + type: object + x-scenarios: + - name: create + - name: update + ``` + + The following code is generated in the abstract model: + ```php + abstract class Invoice extends \yii\db\ActiveRecord + { + /** + * This Backend-Scenario "create" exist in both the frontend model and the backend model. + * @see \common\client\models\Invoice::SCENARIO_CREATE + */ + public const SCENARIO_CREATE = 'create'; + + /** + * This Backend-Scenario "update" exist in both the frontend model and the backend model. + * @see \common\client\models\Invoice::SCENARIO_UPDATE + */ + public const SCENARIO_UPDATE = 'update'; + + /** + * Automatically generated scenarios from the model 'x-scenarios'. + * @return array a list of scenarios and the corresponding active attributes. + */ + public function scenarios() + {...} + } + ``` + ### `x-indexes` Specify table indexes diff --git a/src/generator/ApiGenerator.php b/src/generator/ApiGenerator.php index 40df4315..d95405d5 100644 --- a/src/generator/ApiGenerator.php +++ b/src/generator/ApiGenerator.php @@ -143,7 +143,7 @@ class ApiGenerator extends Generator /** * @var array Map for custom dbModels * - * @see DbModel::$scenarioDefaultDescription with acceptedInputs: {scenarioName}, {scenarioConst}, {modelName}. + * @see DbModel::$scenarioDefaultDescription with Accepted-Placeholder: {scenarioName}, {scenarioConst}, {modelName}. * @example * 'dbModel' => [ * 'scenarioDefaultDescription' => "Scenario {scenarioName}", diff --git a/src/generator/default/dbmodel.php b/src/generator/default/dbmodel.php index a85fa7bb..f8c3ba3c 100644 --- a/src/generator/default/dbmodel.php +++ b/src/generator/default/dbmodel.php @@ -84,12 +84,14 @@ public static function tableName() */ public function scenarios() { + $parentScenarios = parent::scenarios(); + /** * Each scenario is assigned attributes as in the 'default' scenario. * The advantage is that the scenario can be used immediately. * This can be overridden in the child model if needed. */ - $default = parent::scenarios()[self::SCENARIO_DEFAULT]; + $default = $parentScenarios[self::SCENARIO_DEFAULT]; return [ @@ -99,7 +101,7 @@ public function scenarios() * The 'default' scenario and all scenarios mentioned in the rules() using 'on' and 'except' * are automatically included in the scenarios() function for the model. */ - ...parent::scenarios(), + ...$parentScenarios, ]; } diff --git a/src/lib/Config.php b/src/lib/Config.php index bd4934a0..a2531046 100644 --- a/src/lib/Config.php +++ b/src/lib/Config.php @@ -112,7 +112,7 @@ class Config extends BaseObject /** * @var array Map for custom dbModels * - * @see DbModel::$scenarioDefaultDescription with acceptedInputs: {scenarioName}, {scenarioConst}, {modelName}. + * @see DbModel::$scenarioDefaultDescription with Accepted-Placeholder: {scenarioName}, {scenarioConst}, {modelName}. * @example * 'dbModel' => [ * 'scenarioDefaultDescription' => "Scenario {scenarioName}", diff --git a/src/lib/items/DbModel.php b/src/lib/items/DbModel.php index 08135d71..fcfa6d40 100644 --- a/src/lib/items/DbModel.php +++ b/src/lib/items/DbModel.php @@ -84,7 +84,7 @@ class DbModel extends BaseObject /** * @var string * Here, you can set your own default description for the scenario. - * AcceptedInputs: {scenarioName}, {scenarioConst}, {modelName}. + * Accepted-Placeholder: {scenarioName}, {scenarioConst}, {modelName}. */ public $scenarioDefaultDescription = "Scenario {scenarioName}"; From cbb5adb788a8eb333741a828f90e728dfea4ba0f Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Wed, 12 Feb 2025 15:41:38 +0530 Subject: [PATCH 314/358] Create PR --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index f68df469..4cc1d72a 100644 --- a/README.md +++ b/README.md @@ -779,3 +779,4 @@ Professional support, consulting as well as software development services are av https://www.cebe.cc/en/contact Development of this library is sponsored by [cebe.:cloud: "Your Professional Deployment Platform"](https://cebe.cloud). + From ca8e804144cf3a13a03b480219694278d1bd099c Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Fri, 14 Feb 2025 15:28:15 +0530 Subject: [PATCH 315/358] Add passing test --- README.md | 1 - .../index.php | 13 ++ .../index.yaml | 24 +++ .../mysql/models/BaseModelFaker.php | 144 ++++++++++++++++++ .../mysql/models/Payment.php | 10 ++ .../mysql/models/PaymentFaker.php | 42 +++++ .../mysql/models/base/Payment.php | 31 ++++ tests/unit/IssueFixTest.php | 13 ++ 8 files changed, 277 insertions(+), 1 deletion(-) create mode 100644 tests/specs/issue_fix/78_properties_that_are_marked_as_readonly_are_not_read_only/index.php create mode 100644 tests/specs/issue_fix/78_properties_that_are_marked_as_readonly_are_not_read_only/index.yaml create mode 100644 tests/specs/issue_fix/78_properties_that_are_marked_as_readonly_are_not_read_only/mysql/models/BaseModelFaker.php create mode 100644 tests/specs/issue_fix/78_properties_that_are_marked_as_readonly_are_not_read_only/mysql/models/Payment.php create mode 100644 tests/specs/issue_fix/78_properties_that_are_marked_as_readonly_are_not_read_only/mysql/models/PaymentFaker.php create mode 100644 tests/specs/issue_fix/78_properties_that_are_marked_as_readonly_are_not_read_only/mysql/models/base/Payment.php diff --git a/README.md b/README.md index 4cc1d72a..f68df469 100644 --- a/README.md +++ b/README.md @@ -779,4 +779,3 @@ Professional support, consulting as well as software development services are av https://www.cebe.cc/en/contact Development of this library is sponsored by [cebe.:cloud: "Your Professional Deployment Platform"](https://cebe.cloud). - diff --git a/tests/specs/issue_fix/78_properties_that_are_marked_as_readonly_are_not_read_only/index.php b/tests/specs/issue_fix/78_properties_that_are_marked_as_readonly_are_not_read_only/index.php new file mode 100644 index 00000000..9a6fa0f2 --- /dev/null +++ b/tests/specs/issue_fix/78_properties_that_are_marked_as_readonly_are_not_read_only/index.php @@ -0,0 +1,13 @@ + '@specs/issue_fix/78_properties_that_are_marked_as_readonly_are_not_read_only/index.yaml', + 'generateUrls' => false, + 'generateModels' => true, + 'excludeModels' => [ + 'Error', + ], + 'generateControllers' => false, + 'generateMigrations' => false, + 'generateModelFaker' => true, // `generateModels` must be `true` in order to use `generateModelFaker` as `true` +]; diff --git a/tests/specs/issue_fix/78_properties_that_are_marked_as_readonly_are_not_read_only/index.yaml b/tests/specs/issue_fix/78_properties_that_are_marked_as_readonly_are_not_read_only/index.yaml new file mode 100644 index 00000000..8f748b8e --- /dev/null +++ b/tests/specs/issue_fix/78_properties_that_are_marked_as_readonly_are_not_read_only/index.yaml @@ -0,0 +1,24 @@ +openapi: 3.0.3 + +info: + title: '#78' + version: 1.0.0 + +paths: + /: + get: + responses: + '200': + description: The Response + +components: + schemas: + Payment: + properties: + id: + type: integer + amount: + type: integer + readOnly: true + currency: + type: string diff --git a/tests/specs/issue_fix/78_properties_that_are_marked_as_readonly_are_not_read_only/mysql/models/BaseModelFaker.php b/tests/specs/issue_fix/78_properties_that_are_marked_as_readonly_are_not_read_only/mysql/models/BaseModelFaker.php new file mode 100644 index 00000000..c367fbb4 --- /dev/null +++ b/tests/specs/issue_fix/78_properties_that_are_marked_as_readonly_are_not_read_only/mysql/models/BaseModelFaker.php @@ -0,0 +1,144 @@ +faker = FakerFactory::create(str_replace('-', '_', \Yii::$app->language)); + $this->uniqueFaker = new UniqueGenerator($this->faker); + } + + abstract public function generateModel($attributes = []); + + public function getFaker():Generator + { + return $this->faker; + } + + public function getUniqueFaker():UniqueGenerator + { + return $this->uniqueFaker; + } + + public function setFaker(Generator $faker):void + { + $this->faker = $faker; + } + + public function setUniqueFaker(UniqueGenerator $faker):void + { + $this->uniqueFaker = $faker; + } + + /** + * Generate and return model + * @param array|callable $attributes + * @param UniqueGenerator|null $uniqueFaker + * @return \yii\db\ActiveRecord + * @example MyFaker::makeOne(['user_id' => 1, 'title' => 'foo']); + * @example MyFaker::makeOne( function($model, $faker) { + * $model->scenario = 'create'; + * $model->setAttributes(['user_id' => 1, 'title' => $faker->sentence]); + * return $model; + * }); + */ + public static function makeOne($attributes = [], ?UniqueGenerator $uniqueFaker = null) + { + $fakeBuilder = new static(); + if ($uniqueFaker !== null) { + $fakeBuilder->setUniqueFaker($uniqueFaker); + } + $model = $fakeBuilder->generateModel($attributes); + return $model; + } + + /** + * Generate, save and return model + * @param array|callable $attributes + * @param UniqueGenerator|null $uniqueFaker + * @return \yii\db\ActiveRecord + * @example MyFaker::saveOne(['user_id' => 1, 'title' => 'foo']); + * @example MyFaker::saveOne( function($model, $faker) { + * $model->scenario = 'create'; + * $model->setAttributes(['user_id' => 1, 'title' => $faker->sentence]); + * return $model; + * }); + */ + public static function saveOne($attributes = [], ?UniqueGenerator $uniqueFaker = null) + { + $model = static::makeOne($attributes, $uniqueFaker); + $model->save(); + return $model; + } + + /** + * Generate and return multiple models + * @param int $number + * @param array|callable $commonAttributes + * @return \yii\db\ActiveRecord[]|array + * @example TaskFaker::make(5, ['project_id'=>1, 'user_id' => 2]); + * @example TaskFaker::make(5, function($model, $faker, $uniqueFaker) { + * $model->setAttributes(['name' => $uniqueFaker->username, 'state'=>$faker->boolean(20)]); + * return $model; + * }); + */ + public static function make(int $number, $commonAttributes = [], ?UniqueGenerator $uniqueFaker = null):array + { + if ($number < 1) { + return []; + } + $fakeBuilder = new static(); + if ($uniqueFaker !== null) { + $fakeBuilder->setUniqueFaker($uniqueFaker); + } + return array_map(function () use ($commonAttributes, $fakeBuilder) { + $model = $fakeBuilder->generateModel($commonAttributes); + return $model; + }, range(0, $number -1)); + } + + /** + * Generate, save and return multiple models + * @param int $number + * @param array|callable $commonAttributes + * @return \yii\db\ActiveRecord[]|array + * @example TaskFaker::save(5, ['project_id'=>1, 'user_id' => 2]); + * @example TaskFaker::save(5, function($model, $faker, $uniqueFaker) { + * $model->setAttributes(['name' => $uniqueFaker->username, 'state'=>$faker->boolean(20)]); + * return $model; + * }); + */ + public static function save(int $number, $commonAttributes = [], ?UniqueGenerator $uniqueFaker = null):array + { + if ($number < 1) { + return []; + } + $fakeBuilder = new static(); + if ($uniqueFaker !== null) { + $fakeBuilder->setUniqueFaker($uniqueFaker); + } + return array_map(function () use ($commonAttributes, $fakeBuilder) { + $model = $fakeBuilder->generateModel($commonAttributes); + $model->save(); + return $model; + }, range(0, $number -1)); + } +} diff --git a/tests/specs/issue_fix/78_properties_that_are_marked_as_readonly_are_not_read_only/mysql/models/Payment.php b/tests/specs/issue_fix/78_properties_that_are_marked_as_readonly_are_not_read_only/mysql/models/Payment.php new file mode 100644 index 00000000..660670f4 --- /dev/null +++ b/tests/specs/issue_fix/78_properties_that_are_marked_as_readonly_are_not_read_only/mysql/models/Payment.php @@ -0,0 +1,10 @@ +generateModels(['author_id' => 1]); + * $model = (new PostFaker())->generateModels(function($model, $faker, $uniqueFaker) { + * $model->scenario = 'create'; + * $model->author_id = 1; + * return $model; + * }); + **/ + public function generateModel($attributes = []) + { + $faker = $this->faker; + $uniqueFaker = $this->uniqueFaker; + $model = new Payment(); + //$model->id = $uniqueFaker->numberBetween(0, 1000000); + $model->amount = $faker->numberBetween(0, 1000000); + $model->currency = $faker->currencyCode; + if (!is_callable($attributes)) { + $model->setAttributes($attributes, false); + } else { + $model = $attributes($model, $faker, $uniqueFaker); + } + return $model; + } +} diff --git a/tests/specs/issue_fix/78_properties_that_are_marked_as_readonly_are_not_read_only/mysql/models/base/Payment.php b/tests/specs/issue_fix/78_properties_that_are_marked_as_readonly_are_not_read_only/mysql/models/base/Payment.php new file mode 100644 index 00000000..129cce90 --- /dev/null +++ b/tests/specs/issue_fix/78_properties_that_are_marked_as_readonly_are_not_read_only/mysql/models/base/Payment.php @@ -0,0 +1,31 @@ + [['currency'], 'trim'], + 'currency_string' => [['currency'], 'string'], + ]; + } +} diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index 64ca764d..c2d8796c 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -1001,4 +1001,17 @@ public function test74InvalidSchemaReferenceError() $this->runActualMigrations(); } + // https://github.com/php-openapi/yii2-openapi/issues/78 + public function test78PropertiesThatAreMarkedAsReadonlyAreNotReadOnly() + { + $testFile = Yii::getAlias("@specs/issue_fix/78_properties_that_are_marked_as_readonly_are_not_read_only/index.php"); + $this->runGenerator($testFile); + $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ + 'recursive' => true, + ]); + $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/78_properties_that_are_marked_as_readonly_are_not_read_only/mysql"), [ + 'recursive' => true, + ]); + $this->checkFiles($actualFiles, $expectedFiles); + } } From 5a5ee39dda80c30b22962291386f24610599a54a Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Fri, 14 Feb 2025 16:20:29 +0530 Subject: [PATCH 316/358] Create PR --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index f68df469..4cc1d72a 100644 --- a/README.md +++ b/README.md @@ -779,3 +779,4 @@ Professional support, consulting as well as software development services are av https://www.cebe.cc/en/contact Development of this library is sponsored by [cebe.:cloud: "Your Professional Deployment Platform"](https://cebe.cloud). + From 9ff2113221ee5d94cfab930fb5681443f99ffd56 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Wed, 19 Feb 2025 13:37:23 +0530 Subject: [PATCH 317/358] Implement --- README.md | 2 +- src/lib/AttributeResolver.php | 42 +++++++++++-------- .../mysql/models/base/Pet.php | 6 --- .../index.php | 13 ++++++ .../index.yaml | 35 ++++++++++++++++ tests/unit/IssueFixTest.php | 16 +++++++ 6 files changed, 90 insertions(+), 24 deletions(-) create mode 100644 tests/specs/issue_fix/23_consider_openapi_extension_x_no_relation_also_in_other_pertinent_place/index.php create mode 100644 tests/specs/issue_fix/23_consider_openapi_extension_x_no_relation_also_in_other_pertinent_place/index.yaml diff --git a/README.md b/README.md index 4cc1d72a..f7e1e789 100644 --- a/README.md +++ b/README.md @@ -350,7 +350,7 @@ related objects, `x-no-relation` (type: boolean, default: false) is used. This will not generate 'comments' column in database migrations. But it will generate `getComments()` relation in Yii model file. -In order to make it real database column, extension `x-no-relation` can be used. +In order to make it real database column, OpenAPI extension `x-no-relation` can be used. ```yaml comments: diff --git a/src/lib/AttributeResolver.php b/src/lib/AttributeResolver.php index cc41a6fb..09fe6b4f 100644 --- a/src/lib/AttributeResolver.php +++ b/src/lib/AttributeResolver.php @@ -278,7 +278,9 @@ protected function resolveProperty( if ($property->isRefPointerToSelf()) { $relation->asSelfReference(); } - $this->relations[$property->getName()] = $relation; + if (empty($property->getAttr(CustomSpecAttr::NO_RELATION))) { + $this->relations[$property->getName()] = $relation; + } if (!$property->isRefPointerToSelf()) { $this->addInverseRelation($relatedClassName, $attribute, $property, $fkProperty); } @@ -321,21 +323,25 @@ protected function resolveProperty( $fkProperty->getName(), '_id' )) { + if (empty($property->getAttr(CustomSpecAttr::NO_RELATION))) { + $this->relations[$property->getName()] = + Yii::createObject( + AttributeRelation::class, + [static::relationName($property->getName(), $property->fkColName), $relatedTableName, $relatedClassName] + ) + ->asHasMany([$fkProperty->getName() => $fkProperty->getName()])->asSelfReference(); + } + return; + } + $foreignPk = Inflector::camel2id($fkProperty->getName(), '_') . '_id'; + if (empty($property->getAttr(CustomSpecAttr::NO_RELATION))) { $this->relations[$property->getName()] = Yii::createObject( AttributeRelation::class, [static::relationName($property->getName(), $property->fkColName), $relatedTableName, $relatedClassName] ) - ->asHasMany([$fkProperty->getName() => $fkProperty->getName()])->asSelfReference(); - return; + ->asHasMany([$foreignPk => $this->componentSchema->getPkName()]); } - $foreignPk = Inflector::camel2id($fkProperty->getName(), '_') . '_id'; - $this->relations[$property->getName()] = - Yii::createObject( - AttributeRelation::class, - [static::relationName($property->getName(), $property->fkColName), $relatedTableName, $relatedClassName] - ) - ->asHasMany([$foreignPk => $this->componentSchema->getPkName()]); return; } $relatedClassName = $property->getRefClassName(); @@ -349,13 +355,15 @@ protected function resolveProperty( return; } $attribute->setPhpType($relatedClassName . '[]'); - $this->relations[$property->getName()] = - Yii::createObject( - AttributeRelation::class, - [static::relationName($property->getName(), $property->fkColName), $relatedTableName, $relatedClassName] - ) - ->asHasMany([Inflector::camel2id($this->schemaName, '_') . '_id' => $this->componentSchema->getPkName()]) - ->setInverse(Inflector::variablize($this->schemaName)); + if (empty($property->getAttr(CustomSpecAttr::NO_RELATION))) { + $this->relations[$property->getName()] = + Yii::createObject( + AttributeRelation::class, + [static::relationName($property->getName(), $property->fkColName), $relatedTableName, $relatedClassName] + ) + ->asHasMany([Inflector::camel2id($this->schemaName, '_') . '_id' => $this->componentSchema->getPkName()]) + ->setInverse(Inflector::variablize($this->schemaName)); + } return; } if ($this->componentSchema->isNonDb() && $attribute->isReference()) { diff --git a/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/mysql/models/base/Pet.php b/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/mysql/models/base/Pet.php index c0621fd6..25498979 100644 --- a/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/mysql/models/base/Pet.php +++ b/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/mysql/models/base/Pet.php @@ -29,7 +29,6 @@ * @property array $one_of_from_multi_ref_arr * * @property array|\app\models\User[] $userRefObjArrNormal - * @property array|\app\models\User[] $userRefObjArr */ abstract class Pet extends \yii\db\ActiveRecord { @@ -53,9 +52,4 @@ public function getUserRefObjArrNormal() { return $this->hasMany(\app\models\User::class, ['pet_id' => 'id'])->inverseOf('pet'); } - - public function getUserRefObjArr() - { - return $this->hasMany(\app\models\User::class, ['pet_id' => 'id'])->inverseOf('pet'); - } } diff --git a/tests/specs/issue_fix/23_consider_openapi_extension_x_no_relation_also_in_other_pertinent_place/index.php b/tests/specs/issue_fix/23_consider_openapi_extension_x_no_relation_also_in_other_pertinent_place/index.php new file mode 100644 index 00000000..d10773f1 --- /dev/null +++ b/tests/specs/issue_fix/23_consider_openapi_extension_x_no_relation_also_in_other_pertinent_place/index.php @@ -0,0 +1,13 @@ + '@specs/issue_fix/23_consider_openapi_extension_x_no_relation_also_in_other_pertinent_place/index.yaml', + 'generateUrls' => false, + 'generateModels' => true, + 'excludeModels' => [ + 'Error', + ], + 'generateControllers' => false, + 'generateMigrations' => true, + 'generateModelFaker' => true, // `generateModels` must be `true` in order to use `generateModelFaker` as `true` +]; diff --git a/tests/specs/issue_fix/23_consider_openapi_extension_x_no_relation_also_in_other_pertinent_place/index.yaml b/tests/specs/issue_fix/23_consider_openapi_extension_x_no_relation_also_in_other_pertinent_place/index.yaml new file mode 100644 index 00000000..669f6239 --- /dev/null +++ b/tests/specs/issue_fix/23_consider_openapi_extension_x_no_relation_also_in_other_pertinent_place/index.yaml @@ -0,0 +1,35 @@ +openapi: 3.0.3 + +info: + title: '#23' + version: 1.0.0 + +paths: + /: + get: + responses: + '200': + description: The Response + + + +components: + schemas: + Payments: + properties: + id: + type: integer + currency: + type: string + samples: + type: array + x-no-relation: true + items: + $ref: '#/components/schemas/Sample' + + Sample: + properties: + id: + type: integer + message: + type: string \ No newline at end of file diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index 64ca764d..4b03aa08 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -1001,4 +1001,20 @@ public function test74InvalidSchemaReferenceError() $this->runActualMigrations(); } + // https://github.com/php-openapi/yii2-openapi/issues/23 + public function test23ConsiderOpenapiExtensionXNoRelationAlsoInOtherPertinentPlace() + { +// 23-consider-openapi-extension-x-no-relation-also-in-other-pertinent-place +// 23_consider_openapi_extension_x_no_relation_also_in_other_pertinent_place + $testFile = Yii::getAlias("@specs/issue_fix/23_consider_openapi_extension_x_no_relation_also_in_other_pertinent_place/index.php"); + $this->runGenerator($testFile); +// $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ +// 'recursive' => true, +// ]); +// $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/23_consider_openapi_extension_x_no_relation_also_in_other_pertinent_place/mysql"), [ +// 'recursive' => true, +// ]); +// $this->checkFiles($actualFiles, $expectedFiles); +// $this->runActualMigrations(); + } } From 253da362e351238015449de27be3b6631ebf99c6 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Wed, 19 Feb 2025 15:33:19 +0530 Subject: [PATCH 318/358] WIP --- src/lib/openapi/PropertySchema.php | 1 + 1 file changed, 1 insertion(+) diff --git a/src/lib/openapi/PropertySchema.php b/src/lib/openapi/PropertySchema.php index eade252e..bc7296f6 100644 --- a/src/lib/openapi/PropertySchema.php +++ b/src/lib/openapi/PropertySchema.php @@ -497,6 +497,7 @@ public function guessDbType($forReference = false):string } return YiiDbSchema::TYPE_TEXT; case 'object': + case 'array': // TODO WIP Resume from here { return YiiDbSchema::TYPE_JSON; } From 0f9c0979047aa545edf44ac82a63c89b76826f2e Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Wed, 19 Feb 2025 16:23:55 +0530 Subject: [PATCH 319/358] Implement feedback --- src/lib/ValidationRulesBuilder.php | 55 +++++++++++++------ .../index.yaml | 1 + .../m200000_000000_create_table_accounts.php | 2 +- .../mysql/models/base/Account.php | 6 +- tests/unit/IssueFixTest.php | 3 +- 5 files changed, 45 insertions(+), 22 deletions(-) diff --git a/src/lib/ValidationRulesBuilder.php b/src/lib/ValidationRulesBuilder.php index ee82d546..b7d5ef47 100644 --- a/src/lib/ValidationRulesBuilder.php +++ b/src/lib/ValidationRulesBuilder.php @@ -53,30 +53,38 @@ public function build():array $this->rules['trim'] = new ValidationRule($this->typeScope['trim'], 'trim'); } - if (!empty($this->typeScope['ref'])) { - $this->addExistRules($this->typeScope['ref']); - } - foreach ($this->model->indexes as $index) { - if ($index->isUnique) { - $this->addUniqueRule($index->columns); + foreach ($this->model->attributes as $attribute) { + if ($this->isIdColumn($attribute)) { + continue; } + $this->defaultRule($attribute); + } + + if (!empty($this->typeScope['required'])) { + $this->rules['required'] = new ValidationRule($this->typeScope['required'], 'required'); } + foreach ($this->model->attributes as $attribute) { - // column/field/property with name `id` is considered as Primary Key by this library, and it is automatically handled by DB/Yii; so remove it from validation `rules()` - if (in_array($attribute->columnName, ['id', $this->model->pkName]) || - in_array($attribute->propertyName, ['id', $this->model->pkName]) - ) { + if ($this->isIdColumn($attribute)) { continue; } $this->resolveAttributeRules($attribute); } + foreach ($this->model->indexes as $index) { + if ($index->isUnique) { + $this->addUniqueRule($index->columns); + } + } + + if (!empty($this->typeScope['ref'])) { + $this->addExistRules($this->typeScope['ref']); + } + if (!empty($this->typeScope['safe'])) { $this->rules['safe'] = new ValidationRule($this->typeScope['safe'], 'safe'); } - if (!empty($this->typeScope['required'])) { - $this->rules['required'] = new ValidationRule($this->typeScope['required'], 'required'); - } + return $this->rules; } @@ -93,7 +101,7 @@ private function resolveAttributeRules(Attribute $attribute):void } if ($attribute->phpType === 'bool' || $attribute->phpType === 'boolean') { $this->rules[$attribute->columnName . '_boolean'] = new ValidationRule([$attribute->columnName], 'boolean'); - $this->defaultRule($attribute); +// $this->defaultRule($attribute); return; } @@ -111,13 +119,13 @@ private function resolveAttributeRules(Attribute $attribute):void } $this->rules[$key] = new ValidationRule([$attribute->columnName], $attribute->dbType, $params); - $this->defaultRule($attribute); +// $this->defaultRule($attribute); return; } if (in_array($attribute->phpType, ['int', 'integer', 'double', 'float']) && !$attribute->isReference()) { $this->addNumericRule($attribute); - $this->defaultRule($attribute); +// $this->defaultRule($attribute); return; } if ($attribute->phpType === 'string' && !$attribute->isReference()) { @@ -127,10 +135,10 @@ private function resolveAttributeRules(Attribute $attribute):void $key = $attribute->columnName . '_in'; $this->rules[$key] = new ValidationRule([$attribute->columnName], 'in', ['range' => $attribute->enumValues]); - $this->defaultRule($attribute); +// $this->defaultRule($attribute); // TODO remove return; } - $this->defaultRule($attribute); +// $this->defaultRule($attribute); $this->addRulesByAttributeName($attribute); } @@ -278,4 +286,15 @@ public function __toString() } }; } + + private function isIdColumn(Attribute $attribute): bool + { + // column/field/property with name `id` is considered as Primary Key by this library, and it is automatically handled by DB/Yii; so remove it from validation `rules()` + if (in_array($attribute->columnName, ['id', $this->model->pkName]) || + in_array($attribute->propertyName, ['id', $this->model->pkName]) + ) { + return true; + } + return false; + } } diff --git a/tests/specs/issue_fix/22_bug_rules_required_is_generated_before_default/index.yaml b/tests/specs/issue_fix/22_bug_rules_required_is_generated_before_default/index.yaml index 889ab5b3..7081de94 100644 --- a/tests/specs/issue_fix/22_bug_rules_required_is_generated_before_default/index.yaml +++ b/tests/specs/issue_fix/22_bug_rules_required_is_generated_before_default/index.yaml @@ -23,6 +23,7 @@ components: maxLength: 128 paymentMethodName: type: string + default: card verified: type: boolean default: false diff --git a/tests/specs/issue_fix/22_bug_rules_required_is_generated_before_default/mysql/migrations_mysql_db/m200000_000000_create_table_accounts.php b/tests/specs/issue_fix/22_bug_rules_required_is_generated_before_default/mysql/migrations_mysql_db/m200000_000000_create_table_accounts.php index e59c2946..584fc0ee 100644 --- a/tests/specs/issue_fix/22_bug_rules_required_is_generated_before_default/mysql/migrations_mysql_db/m200000_000000_create_table_accounts.php +++ b/tests/specs/issue_fix/22_bug_rules_required_is_generated_before_default/mysql/migrations_mysql_db/m200000_000000_create_table_accounts.php @@ -9,7 +9,7 @@ public function up() { $this->createTable('{{%accounts}}', [ 'id' => $this->primaryKey(), - 'name' => $this->string(128)->notNull(), + 'name' => $this->string(128)->notNull()->comment('account name'), 'paymentMethodName' => $this->text()->null(), 'verified' => $this->boolean()->notNull()->defaultValue(false), ]); diff --git a/tests/specs/issue_fix/22_bug_rules_required_is_generated_before_default/mysql/models/base/Account.php b/tests/specs/issue_fix/22_bug_rules_required_is_generated_before_default/mysql/models/base/Account.php index 96b515cf..ef3aba9e 100644 --- a/tests/specs/issue_fix/22_bug_rules_required_is_generated_before_default/mysql/models/base/Account.php +++ b/tests/specs/issue_fix/22_bug_rules_required_is_generated_before_default/mysql/models/base/Account.php @@ -1,5 +1,9 @@ [['name', 'paymentMethodName'], 'trim'], + 'required' => [['name', 'verified'], 'required'], 'name_string' => [['name'], 'string', 'max' => 128], 'paymentMethodName_string' => [['paymentMethodName'], 'string'], 'verified_boolean' => [['verified'], 'boolean'], 'verified_default' => [['verified'], 'default', 'value' => false], - 'required' => [['name', 'verified'], 'required'], ]; } } diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index dc67b4a9..ad3ff8fd 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -1001,7 +1001,7 @@ public function test74InvalidSchemaReferenceError() $this->runActualMigrations(); } - // https://github.com/php-openapi/yii2-openapi/issues/22 + // https://github.com/php-openapi/yii2-openapi/issues/22 public function test22BugRulesRequiredIsGeneratedBeforeDefault() { $testFile = Yii::getAlias("@specs/issue_fix/22_bug_rules_required_is_generated_before_default/index.php"); @@ -1014,5 +1014,4 @@ public function test22BugRulesRequiredIsGeneratedBeforeDefault() ]); $this->checkFiles($actualFiles, $expectedFiles); } - } From 6dd3242b93528c563582e72595c3aff509e32428 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Thu, 20 Feb 2025 15:16:56 +0530 Subject: [PATCH 320/358] Fix test --- .../mysql/models/base/Account.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/specs/issue_fix/22_bug_rules_required_is_generated_before_default/mysql/models/base/Account.php b/tests/specs/issue_fix/22_bug_rules_required_is_generated_before_default/mysql/models/base/Account.php index ef3aba9e..dc19672e 100644 --- a/tests/specs/issue_fix/22_bug_rules_required_is_generated_before_default/mysql/models/base/Account.php +++ b/tests/specs/issue_fix/22_bug_rules_required_is_generated_before_default/mysql/models/base/Account.php @@ -26,11 +26,12 @@ public function rules() { return [ 'trim' => [['name', 'paymentMethodName'], 'trim'], + 'paymentMethodName_default' => [['paymentMethodName'], 'default', 'value' => 'card'], + 'verified_default' => [['verified'], 'default', 'value' => false], 'required' => [['name', 'verified'], 'required'], 'name_string' => [['name'], 'string', 'max' => 128], 'paymentMethodName_string' => [['paymentMethodName'], 'string'], 'verified_boolean' => [['verified'], 'boolean'], - 'verified_default' => [['verified'], 'default', 'value' => false], ]; } } From bfaae12f1e8c753310dd464312de8894acec72cc Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Thu, 20 Feb 2025 15:44:38 +0530 Subject: [PATCH 321/358] Fix failing tests --- tests/specs/blog/models/base/Category.php | 6 +++--- tests/specs/blog/models/base/Comment.php | 8 ++++---- tests/specs/blog/models/base/Fakerable.php | 2 +- tests/specs/blog/models/base/Post.php | 16 +++++++-------- tests/specs/blog/models/base/User.php | 12 +++++------ tests/specs/blog_v2/models/base/Category.php | 2 +- tests/specs/blog_v2/models/base/Comment.php | 10 +++++----- tests/specs/blog_v2/models/base/Post.php | 14 ++++++------- tests/specs/blog_v2/models/base/Tag.php | 4 ++-- tests/specs/blog_v2/models/base/User.php | 8 ++++---- .../app/models/base/ColumnNameChange.php | 2 +- .../app/models/base/ColumnNameChange.php | 2 +- .../app/models/base/ColumnNameChange.php | 2 +- .../fk_col_name/app/models/base/User.php | 2 +- .../fk_col_name/app/models/base/Webhook.php | 2 +- .../app/models/base/User.php | 2 +- .../app/models/base/Webhook.php | 14 ++++++------- tests/specs/many2many/models/base/Photo.php | 2 +- tests/specs/many2many/models/base/Post.php | 2 +- .../many2many/models/base/PostsGallery.php | 2 +- tests/specs/many2many/models/base/Tag.php | 2 +- tests/specs/menu/models/base/Menu.php | 8 ++++---- tests/specs/petstore/models/base/Pet.php | 6 +++--- tests/specs/petstore/models/base/Store.php | 2 +- .../petstore_arrayref/models/base/Pet.php | 2 +- .../petstore_jsonapi/models/base/Doctor.php | 2 +- .../petstore_jsonapi/models/base/Pet.php | 2 +- .../models/base/PetStatistic.php | 4 ++-- .../petstore_namespace/mymodels/base/Pet.php | 6 +++--- .../mymodels/base/Store.php | 2 +- .../petstore_wrapped/models/base/Pet.php | 2 +- .../specs/petstore_xtable/models/base/Pet.php | 2 +- .../postgres_custom/models/base/Custom.php | 6 +++--- .../maria/edit/app/models/base/Fruit.php | 20 +++++++++---------- .../edit_expression/app/models/base/Fruit.php | 20 +++++++++---------- .../maria/simple/app/models/base/Fruit.php | 20 +++++++++---------- .../mysql/edit/app/models/base/Fruit.php | 20 +++++++++---------- .../edit_expression/app/models/base/Fruit.php | 20 +++++++++---------- .../mysql/simple/app/models/base/Fruit.php | 20 +++++++++---------- .../pgsql/edit/app/models/base/Fruit.php | 20 +++++++++---------- .../edit_expression/app/models/base/Fruit.php | 20 +++++++++---------- .../pgsql/simple/app/models/base/Fruit.php | 20 +++++++++---------- 42 files changed, 170 insertions(+), 170 deletions(-) diff --git a/tests/specs/blog/models/base/Category.php b/tests/specs/blog/models/base/Category.php index f232a812..188ec03c 100644 --- a/tests/specs/blog/models/base/Category.php +++ b/tests/specs/blog/models/base/Category.php @@ -26,11 +26,11 @@ public function rules() { return [ 'trim' => [['title'], 'trim'], - 'title_unique' => [['title'], 'unique'], - 'title_string' => [['title'], 'string', 'max' => 255], - 'active_boolean' => [['active'], 'boolean'], 'active_default' => [['active'], 'default', 'value' => false], 'required' => [['title', 'active'], 'required'], + 'title_string' => [['title'], 'string', 'max' => 255], + 'active_boolean' => [['active'], 'boolean'], + 'title_unique' => [['title'], 'unique'], ]; } diff --git a/tests/specs/blog/models/base/Comment.php b/tests/specs/blog/models/base/Comment.php index 8c61d482..f6e03bca 100644 --- a/tests/specs/blog/models/base/Comment.php +++ b/tests/specs/blog/models/base/Comment.php @@ -30,15 +30,15 @@ public function rules() { return [ 'trim' => [['post_id'], 'trim'], + 'message_default' => [['message'], 'default', 'value' => []], + 'meta_data_default' => [['meta_data'], 'default', 'value' => []], + 'required' => [['post_id', 'author_id', 'message', 'created_at'], 'required'], + 'created_at_integer' => [['created_at'], 'integer'], 'post_id_string' => [['post_id'], 'string', 'max' => 128], 'post_id_exist' => [['post_id'], 'exist', 'targetRelation' => 'post'], 'author_id_integer' => [['author_id'], 'integer'], 'author_id_exist' => [['author_id'], 'exist', 'targetRelation' => 'author'], - 'message_default' => [['message'], 'default', 'value' => []], - 'meta_data_default' => [['meta_data'], 'default', 'value' => []], - 'created_at_integer' => [['created_at'], 'integer'], 'safe' => [['message', 'meta_data'], 'safe'], - 'required' => [['post_id', 'author_id', 'message', 'created_at'], 'required'], ]; } diff --git a/tests/specs/blog/models/base/Fakerable.php b/tests/specs/blog/models/base/Fakerable.php index a00ac9ae..9ba7a049 100644 --- a/tests/specs/blog/models/base/Fakerable.php +++ b/tests/specs/blog/models/base/Fakerable.php @@ -37,12 +37,12 @@ public function rules() { return [ 'trim' => [['str_text', 'str_varchar', 'str_date', 'str_datetime', 'str_country'], 'trim'], + 'int_min_default' => [['int_min'], 'default', 'value' => 3], 'active_boolean' => [['active'], 'boolean'], 'floatval_double' => [['floatval'], 'double'], 'floatval_lim_double' => [['floatval_lim'], 'double', 'min' => 0, 'max' => 1], 'doubleval_double' => [['doubleval'], 'double'], 'int_min_integer' => [['int_min'], 'integer', 'min' => 5], - 'int_min_default' => [['int_min'], 'default', 'value' => 3], 'int_max_integer' => [['int_max'], 'integer', 'max' => 5], 'int_minmax_integer' => [['int_minmax'], 'integer', 'min' => 5, 'max' => 25], 'int_created_at_integer' => [['int_created_at'], 'integer'], diff --git a/tests/specs/blog/models/base/Post.php b/tests/specs/blog/models/base/Post.php index 88bcb422..633de3f4 100644 --- a/tests/specs/blog/models/base/Post.php +++ b/tests/specs/blog/models/base/Post.php @@ -32,18 +32,18 @@ public function rules() { return [ 'trim' => [['title', 'slug', 'created_at'], 'trim'], - 'category_id_integer' => [['category_id'], 'integer'], - 'category_id_exist' => [['category_id'], 'exist', 'targetRelation' => 'category'], - 'created_by_id_integer' => [['created_by_id'], 'integer'], - 'created_by_id_exist' => [['created_by_id'], 'exist', 'targetRelation' => 'createdBy'], - 'title_unique' => [['title'], 'unique'], - 'slug_unique' => [['slug'], 'unique'], + 'active_default' => [['active'], 'default', 'value' => false], + 'required' => [['title', 'category_id', 'active'], 'required'], 'title_string' => [['title'], 'string', 'max' => 255], 'slug_string' => [['slug'], 'string', 'min' => 1, 'max' => 200], 'active_boolean' => [['active'], 'boolean'], - 'active_default' => [['active'], 'default', 'value' => false], 'created_at_date' => [['created_at'], 'date', 'format' => 'php:Y-m-d'], - 'required' => [['title', 'category_id', 'active'], 'required'], + 'title_unique' => [['title'], 'unique'], + 'slug_unique' => [['slug'], 'unique'], + 'category_id_integer' => [['category_id'], 'integer'], + 'category_id_exist' => [['category_id'], 'exist', 'targetRelation' => 'category'], + 'created_by_id_integer' => [['created_by_id'], 'integer'], + 'created_by_id_exist' => [['created_by_id'], 'exist', 'targetRelation' => 'createdBy'], ]; } diff --git a/tests/specs/blog/models/base/User.php b/tests/specs/blog/models/base/User.php index 7d864029..dbd3a708 100644 --- a/tests/specs/blog/models/base/User.php +++ b/tests/specs/blog/models/base/User.php @@ -29,19 +29,19 @@ public function rules() { return [ 'trim' => [['username', 'email', 'password', 'role', 'created_at'], 'trim'], - 'username_unique' => [['username'], 'unique'], - 'email_unique' => [['email'], 'unique'], + 'role_default' => [['role'], 'default', 'value' => 'reader'], + 'flags_default' => [['flags'], 'default', 'value' => 0], + 'created_at_default' => [['created_at'], 'default', 'value' => new \yii\db\Expression("(CURRENT_TIMESTAMP)")], + 'required' => [['username', 'email', 'password'], 'required'], 'username_string' => [['username'], 'string', 'max' => 200], 'email_string' => [['email'], 'string', 'max' => 200], 'email_email' => [['email'], 'email'], 'password_string' => [['password'], 'string'], 'role_string' => [['role'], 'string', 'max' => 20], - 'role_default' => [['role'], 'default', 'value' => 'reader'], 'flags_integer' => [['flags'], 'integer'], - 'flags_default' => [['flags'], 'default', 'value' => 0], 'created_at_datetime' => [['created_at'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], - 'required' => [['username', 'email', 'password'], 'required'], - 'created_at_default' => [['created_at'], 'default', 'value' => new \yii\db\Expression("(CURRENT_TIMESTAMP)")], + 'username_unique' => [['username'], 'unique'], + 'email_unique' => [['email'], 'unique'], ]; } diff --git a/tests/specs/blog_v2/models/base/Category.php b/tests/specs/blog_v2/models/base/Category.php index 30004957..4207f516 100644 --- a/tests/specs/blog_v2/models/base/Category.php +++ b/tests/specs/blog_v2/models/base/Category.php @@ -27,10 +27,10 @@ public function rules() { return [ 'trim' => [['title', 'cover'], 'trim'], + 'required' => [['title', 'cover', 'active'], 'required'], 'title_string' => [['title'], 'string', 'max' => 100], 'cover_string' => [['cover'], 'string'], 'active_boolean' => [['active'], 'boolean'], - 'required' => [['title', 'cover', 'active'], 'required'], ]; } diff --git a/tests/specs/blog_v2/models/base/Comment.php b/tests/specs/blog_v2/models/base/Comment.php index bd8b158b..2b4f404a 100644 --- a/tests/specs/blog_v2/models/base/Comment.php +++ b/tests/specs/blog_v2/models/base/Comment.php @@ -30,15 +30,15 @@ public function rules() { return [ 'trim' => [['message', 'meta_data', 'created_at'], 'trim'], + 'meta_data_default' => [['meta_data'], 'default', 'value' => ''], + 'required' => [['post_id', 'message', 'created_at'], 'required'], + 'message_string' => [['message'], 'string'], + 'meta_data_string' => [['meta_data'], 'string', 'min' => 1, 'max' => 300], + 'created_at_datetime' => [['created_at'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], 'post_id_integer' => [['post_id'], 'integer'], 'post_id_exist' => [['post_id'], 'exist', 'targetRelation' => 'post'], 'user_id_integer' => [['user_id'], 'integer'], 'user_id_exist' => [['user_id'], 'exist', 'targetRelation' => 'user'], - 'message_string' => [['message'], 'string'], - 'meta_data_string' => [['meta_data'], 'string', 'min' => 1, 'max' => 300], - 'meta_data_default' => [['meta_data'], 'default', 'value' => ''], - 'created_at_datetime' => [['created_at'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], - 'required' => [['post_id', 'message', 'created_at'], 'required'], ]; } diff --git a/tests/specs/blog_v2/models/base/Post.php b/tests/specs/blog_v2/models/base/Post.php index 39abf38a..debc5008 100644 --- a/tests/specs/blog_v2/models/base/Post.php +++ b/tests/specs/blog_v2/models/base/Post.php @@ -34,11 +34,8 @@ public function rules() { return [ 'trim' => [['title', 'slug', 'created_at'], 'trim'], - 'category_id_integer' => [['category_id'], 'integer'], - 'category_id_exist' => [['category_id'], 'exist', 'targetRelation' => 'category'], - 'created_by_id_integer' => [['created_by_id'], 'integer'], - 'created_by_id_exist' => [['created_by_id'], 'exist', 'targetRelation' => 'createdBy'], - 'title_unique' => [['title'], 'unique'], + 'lang_default' => [['lang'], 'default', 'value' => 'ru'], + 'required' => [['title', 'category_id', 'active'], 'required'], 'title_string' => [['title'], 'string', 'max' => 255], 'slug_string' => [['slug'], 'string', 'min' => 1, 'max' => 200], 'lang_string' => [['lang'], 'string'], @@ -46,10 +43,13 @@ public function rules() 'ru', 'eng', ]], - 'lang_default' => [['lang'], 'default', 'value' => 'ru'], 'active_boolean' => [['active'], 'boolean'], 'created_at_date' => [['created_at'], 'date', 'format' => 'php:Y-m-d'], - 'required' => [['title', 'category_id', 'active'], 'required'], + 'title_unique' => [['title'], 'unique'], + 'category_id_integer' => [['category_id'], 'integer'], + 'category_id_exist' => [['category_id'], 'exist', 'targetRelation' => 'category'], + 'created_by_id_integer' => [['created_by_id'], 'integer'], + 'created_by_id_exist' => [['created_by_id'], 'exist', 'targetRelation' => 'createdBy'], ]; } diff --git a/tests/specs/blog_v2/models/base/Tag.php b/tests/specs/blog_v2/models/base/Tag.php index 9dcaeb4e..b81a84b2 100644 --- a/tests/specs/blog_v2/models/base/Tag.php +++ b/tests/specs/blog_v2/models/base/Tag.php @@ -26,14 +26,14 @@ public function rules() { return [ 'trim' => [['name'], 'trim'], - 'name_unique' => [['name'], 'unique'], + 'required' => [['name', 'lang'], 'required'], 'name_string' => [['name'], 'string', 'max' => 100], 'lang_string' => [['lang'], 'string'], 'lang_in' => [['lang'], 'in', 'range' => [ 'ru', 'eng', ]], - 'required' => [['name', 'lang'], 'required'], + 'name_unique' => [['name'], 'unique'], ]; } diff --git a/tests/specs/blog_v2/models/base/User.php b/tests/specs/blog_v2/models/base/User.php index 761092c8..45c5b4e0 100644 --- a/tests/specs/blog_v2/models/base/User.php +++ b/tests/specs/blog_v2/models/base/User.php @@ -29,8 +29,8 @@ public function rules() { return [ 'trim' => [['login', 'email', 'password', 'created_at'], 'trim'], - 'login_unique' => [['login'], 'unique'], - 'email_unique' => [['email'], 'unique'], + 'flags_default' => [['flags'], 'default', 'value' => 0], + 'required' => [['login', 'email', 'password'], 'required'], 'login_string' => [['login'], 'string'], 'email_string' => [['email'], 'string', 'max' => 255], 'email_email' => [['email'], 'email'], @@ -42,9 +42,9 @@ public function rules() 'reader', ]], 'flags_integer' => [['flags'], 'integer'], - 'flags_default' => [['flags'], 'default', 'value' => 0], 'created_at_datetime' => [['created_at'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], - 'required' => [['login', 'email', 'password'], 'required'], + 'login_unique' => [['login'], 'unique'], + 'email_unique' => [['email'], 'unique'], ]; } diff --git a/tests/specs/change_column_name/maria/app/models/base/ColumnNameChange.php b/tests/specs/change_column_name/maria/app/models/base/ColumnNameChange.php index f563af6d..0bd44cf8 100644 --- a/tests/specs/change_column_name/maria/app/models/base/ColumnNameChange.php +++ b/tests/specs/change_column_name/maria/app/models/base/ColumnNameChange.php @@ -25,8 +25,8 @@ public function rules() { return [ 'trim' => [['name'], 'trim'], - 'name_string' => [['name'], 'string', 'max' => 255], 'required' => [['name'], 'required'], + 'name_string' => [['name'], 'string', 'max' => 255], ]; } } diff --git a/tests/specs/change_column_name/mysql/app/models/base/ColumnNameChange.php b/tests/specs/change_column_name/mysql/app/models/base/ColumnNameChange.php index f563af6d..0bd44cf8 100644 --- a/tests/specs/change_column_name/mysql/app/models/base/ColumnNameChange.php +++ b/tests/specs/change_column_name/mysql/app/models/base/ColumnNameChange.php @@ -25,8 +25,8 @@ public function rules() { return [ 'trim' => [['name'], 'trim'], - 'name_string' => [['name'], 'string', 'max' => 255], 'required' => [['name'], 'required'], + 'name_string' => [['name'], 'string', 'max' => 255], ]; } } diff --git a/tests/specs/change_column_name/pgsql/app/models/base/ColumnNameChange.php b/tests/specs/change_column_name/pgsql/app/models/base/ColumnNameChange.php index f881503c..fc0e1abb 100644 --- a/tests/specs/change_column_name/pgsql/app/models/base/ColumnNameChange.php +++ b/tests/specs/change_column_name/pgsql/app/models/base/ColumnNameChange.php @@ -25,8 +25,8 @@ public function rules() { return [ 'trim' => [['name'], 'trim'], - 'name_string' => [['name'], 'string', 'max' => 255], 'required' => [['name'], 'required'], + 'name_string' => [['name'], 'string', 'max' => 255], ]; } } diff --git a/tests/specs/fk_col_name/app/models/base/User.php b/tests/specs/fk_col_name/app/models/base/User.php index f80a7de5..ede2e7c0 100644 --- a/tests/specs/fk_col_name/app/models/base/User.php +++ b/tests/specs/fk_col_name/app/models/base/User.php @@ -24,8 +24,8 @@ public function rules() { return [ 'trim' => [['name'], 'trim'], - 'name_string' => [['name'], 'string'], 'required' => [['name'], 'required'], + 'name_string' => [['name'], 'string'], ]; } diff --git a/tests/specs/fk_col_name/app/models/base/Webhook.php b/tests/specs/fk_col_name/app/models/base/Webhook.php index 5360f302..a4176122 100644 --- a/tests/specs/fk_col_name/app/models/base/Webhook.php +++ b/tests/specs/fk_col_name/app/models/base/Webhook.php @@ -28,11 +28,11 @@ public function rules() { return [ 'trim' => [['name'], 'trim'], + 'name_string' => [['name'], 'string'], 'user_id_integer' => [['user_id'], 'integer'], 'user_id_exist' => [['user_id'], 'exist', 'targetRelation' => 'user'], 'redelivery_of_integer' => [['redelivery_of'], 'integer'], 'redelivery_of_exist' => [['redelivery_of'], 'exist', 'targetRelation' => 'redeliveryOf'], - 'name_string' => [['name'], 'string'], ]; } diff --git a/tests/specs/fk_col_name_index/app/models/base/User.php b/tests/specs/fk_col_name_index/app/models/base/User.php index f80a7de5..ede2e7c0 100644 --- a/tests/specs/fk_col_name_index/app/models/base/User.php +++ b/tests/specs/fk_col_name_index/app/models/base/User.php @@ -24,8 +24,8 @@ public function rules() { return [ 'trim' => [['name'], 'trim'], - 'name_string' => [['name'], 'string'], 'required' => [['name'], 'required'], + 'name_string' => [['name'], 'string'], ]; } diff --git a/tests/specs/fk_col_name_index/app/models/base/Webhook.php b/tests/specs/fk_col_name_index/app/models/base/Webhook.php index 0325e083..433d8098 100644 --- a/tests/specs/fk_col_name_index/app/models/base/Webhook.php +++ b/tests/specs/fk_col_name_index/app/models/base/Webhook.php @@ -30,12 +30,7 @@ public function rules() { return [ 'trim' => [['name'], 'trim'], - 'user_id_integer' => [['user_id'], 'integer'], - 'user_id_exist' => [['user_id'], 'exist', 'targetRelation' => 'user'], - 'redelivery_of_integer' => [['redelivery_of'], 'integer'], - 'redelivery_of_exist' => [['redelivery_of'], 'exist', 'targetRelation' => 'redeliveryOf'], - 'rd_abc_2_integer' => [['rd_abc_2'], 'integer'], - 'rd_abc_2_exist' => [['rd_abc_2'], 'exist', 'targetRelation' => 'rd2'], + 'name_string' => [['name'], 'string', 'max' => 255], 'user_id_name_unique' => [['user_id', 'name'], 'unique', 'targetAttribute' => [ 'user_id', 'name', @@ -48,7 +43,12 @@ public function rules() 'rd_abc_2', 'name', ]], - 'name_string' => [['name'], 'string', 'max' => 255], + 'user_id_integer' => [['user_id'], 'integer'], + 'user_id_exist' => [['user_id'], 'exist', 'targetRelation' => 'user'], + 'redelivery_of_integer' => [['redelivery_of'], 'integer'], + 'redelivery_of_exist' => [['redelivery_of'], 'exist', 'targetRelation' => 'redeliveryOf'], + 'rd_abc_2_integer' => [['rd_abc_2'], 'integer'], + 'rd_abc_2_exist' => [['rd_abc_2'], 'exist', 'targetRelation' => 'rd2'], ]; } diff --git a/tests/specs/many2many/models/base/Photo.php b/tests/specs/many2many/models/base/Photo.php index b8fd3cd4..084ff2b9 100644 --- a/tests/specs/many2many/models/base/Photo.php +++ b/tests/specs/many2many/models/base/Photo.php @@ -30,8 +30,8 @@ public function rules() { return [ 'trim' => [['filename'], 'trim'], - 'filename_string' => [['filename'], 'string'], 'required' => [['filename'], 'required'], + 'filename_string' => [['filename'], 'string'], ]; } diff --git a/tests/specs/many2many/models/base/Post.php b/tests/specs/many2many/models/base/Post.php index 9cfe38cb..c802addc 100644 --- a/tests/specs/many2many/models/base/Post.php +++ b/tests/specs/many2many/models/base/Post.php @@ -31,8 +31,8 @@ public function rules() { return [ 'trim' => [['title'], 'trim'], - 'title_string' => [['title'], 'string'], 'required' => [['title'], 'required'], + 'title_string' => [['title'], 'string'], ]; } diff --git a/tests/specs/many2many/models/base/PostsGallery.php b/tests/specs/many2many/models/base/PostsGallery.php index 30e01949..f92d0508 100644 --- a/tests/specs/many2many/models/base/PostsGallery.php +++ b/tests/specs/many2many/models/base/PostsGallery.php @@ -26,11 +26,11 @@ public static function tableName() public function rules() { return [ + 'is_cover_boolean' => [['is_cover'], 'boolean'], 'image_id_integer' => [['image_id'], 'integer'], 'image_id_exist' => [['image_id'], 'exist', 'targetRelation' => 'image'], 'article_id_integer' => [['article_id'], 'integer'], 'article_id_exist' => [['article_id'], 'exist', 'targetRelation' => 'article'], - 'is_cover_boolean' => [['is_cover'], 'boolean'], ]; } diff --git a/tests/specs/many2many/models/base/Tag.php b/tests/specs/many2many/models/base/Tag.php index 30e370c1..16c0e038 100644 --- a/tests/specs/many2many/models/base/Tag.php +++ b/tests/specs/many2many/models/base/Tag.php @@ -25,8 +25,8 @@ public function rules() { return [ 'trim' => [['name'], 'trim'], - 'name_string' => [['name'], 'string'], 'required' => [['name'], 'required'], + 'name_string' => [['name'], 'string'], ]; } diff --git a/tests/specs/menu/models/base/Menu.php b/tests/specs/menu/models/base/Menu.php index 1850f2ed..db5a24da 100644 --- a/tests/specs/menu/models/base/Menu.php +++ b/tests/specs/menu/models/base/Menu.php @@ -29,9 +29,6 @@ public function rules() { return [ 'trim' => [['name'], 'trim'], - 'parent_id_integer' => [['parent_id'], 'integer'], - 'parent_id_exist' => [['parent_id'], 'exist', 'targetRelation' => 'parent'], - 'name_string' => [['name'], 'string', 'min' => 3, 'max' => 100], 'args_default' => [['args'], 'default', 'value' => [ 'foo', 'bar', @@ -45,8 +42,11 @@ public function rules() 'buzz' => 'fizz', ], ]], - 'safe' => [['args', 'kwargs'], 'safe'], 'required' => [['name'], 'required'], + 'name_string' => [['name'], 'string', 'min' => 3, 'max' => 100], + 'parent_id_integer' => [['parent_id'], 'integer'], + 'parent_id_exist' => [['parent_id'], 'exist', 'targetRelation' => 'parent'], + 'safe' => [['args', 'kwargs'], 'safe'], ]; } diff --git a/tests/specs/petstore/models/base/Pet.php b/tests/specs/petstore/models/base/Pet.php index 591cb37d..eb6fc009 100644 --- a/tests/specs/petstore/models/base/Pet.php +++ b/tests/specs/petstore/models/base/Pet.php @@ -27,11 +27,11 @@ public function rules() { return [ 'trim' => [['name', 'tag'], 'trim'], - 'store_id_integer' => [['store_id'], 'integer'], - 'store_id_exist' => [['store_id'], 'exist', 'targetRelation' => 'store'], + 'required' => [['name'], 'required'], 'name_string' => [['name'], 'string'], 'tag_string' => [['tag'], 'string'], - 'required' => [['name'], 'required'], + 'store_id_integer' => [['store_id'], 'integer'], + 'store_id_exist' => [['store_id'], 'exist', 'targetRelation' => 'store'], ]; } diff --git a/tests/specs/petstore/models/base/Store.php b/tests/specs/petstore/models/base/Store.php index 381b7718..9589d1b8 100644 --- a/tests/specs/petstore/models/base/Store.php +++ b/tests/specs/petstore/models/base/Store.php @@ -24,8 +24,8 @@ public function rules() { return [ 'trim' => [['name'], 'trim'], - 'name_string' => [['name'], 'string'], 'required' => [['name'], 'required'], + 'name_string' => [['name'], 'string'], ]; } diff --git a/tests/specs/petstore_arrayref/models/base/Pet.php b/tests/specs/petstore_arrayref/models/base/Pet.php index 60a1edab..2256302d 100644 --- a/tests/specs/petstore_arrayref/models/base/Pet.php +++ b/tests/specs/petstore_arrayref/models/base/Pet.php @@ -26,9 +26,9 @@ public function rules() { return [ 'trim' => [['name', 'tag'], 'trim'], + 'required' => [['name'], 'required'], 'name_string' => [['name'], 'string'], 'tag_string' => [['tag'], 'string'], - 'required' => [['name'], 'required'], ]; } diff --git a/tests/specs/petstore_jsonapi/models/base/Doctor.php b/tests/specs/petstore_jsonapi/models/base/Doctor.php index 32f6ca70..b13bdaa5 100644 --- a/tests/specs/petstore_jsonapi/models/base/Doctor.php +++ b/tests/specs/petstore_jsonapi/models/base/Doctor.php @@ -29,10 +29,10 @@ public function rules() { return [ 'trim' => [['name', 'surname'], 'trim'], + 'required' => [['name'], 'required'], 'name_string' => [['name'], 'string', 'max' => 200], 'surname_string' => [['surname'], 'string', 'max' => 200], 'safe' => [['phones'], 'safe'], - 'required' => [['name'], 'required'], ]; } } diff --git a/tests/specs/petstore_jsonapi/models/base/Pet.php b/tests/specs/petstore_jsonapi/models/base/Pet.php index fec70af0..6444cf28 100644 --- a/tests/specs/petstore_jsonapi/models/base/Pet.php +++ b/tests/specs/petstore_jsonapi/models/base/Pet.php @@ -52,10 +52,10 @@ public function rules() { return [ 'trim' => [['name', 'tag', 'petCode'], 'trim'], + 'required' => [['name'], 'required'], 'name_string' => [['name'], 'string'], 'tag_string' => [['tag'], 'string'], 'petCode_string' => [['petCode'], 'string', 'max' => 50], - 'required' => [['name'], 'required'], ]; } diff --git a/tests/specs/petstore_jsonapi/models/base/PetStatistic.php b/tests/specs/petstore_jsonapi/models/base/PetStatistic.php index adc6e8fd..444acfac 100644 --- a/tests/specs/petstore_jsonapi/models/base/PetStatistic.php +++ b/tests/specs/petstore_jsonapi/models/base/PetStatistic.php @@ -53,12 +53,12 @@ public function rules() { return [ 'trim' => [['title', 'summary'], 'trim'], - 'parentPet_id_integer' => [['parentPet_id'], 'integer'], - 'parentPet_id_exist' => [['parentPet_id'], 'exist', 'targetRelation' => 'parentPet'], 'title_string' => [['title'], 'string'], 'dogsCount_integer' => [['dogsCount'], 'integer'], 'catsCount_integer' => [['catsCount'], 'integer'], 'summary_string' => [['summary'], 'string'], + 'parentPet_id_integer' => [['parentPet_id'], 'integer'], + 'parentPet_id_exist' => [['parentPet_id'], 'exist', 'targetRelation' => 'parentPet'], ]; } } diff --git a/tests/specs/petstore_namespace/mymodels/base/Pet.php b/tests/specs/petstore_namespace/mymodels/base/Pet.php index 7bc2a903..4ab206a3 100644 --- a/tests/specs/petstore_namespace/mymodels/base/Pet.php +++ b/tests/specs/petstore_namespace/mymodels/base/Pet.php @@ -27,11 +27,11 @@ public function rules() { return [ 'trim' => [['name', 'tag'], 'trim'], - 'store_id_integer' => [['store_id'], 'integer'], - 'store_id_exist' => [['store_id'], 'exist', 'targetRelation' => 'store'], + 'required' => [['name'], 'required'], 'name_string' => [['name'], 'string'], 'tag_string' => [['tag'], 'string'], - 'required' => [['name'], 'required'], + 'store_id_integer' => [['store_id'], 'integer'], + 'store_id_exist' => [['store_id'], 'exist', 'targetRelation' => 'store'], ]; } diff --git a/tests/specs/petstore_namespace/mymodels/base/Store.php b/tests/specs/petstore_namespace/mymodels/base/Store.php index c8ac73b8..24d0f4e4 100644 --- a/tests/specs/petstore_namespace/mymodels/base/Store.php +++ b/tests/specs/petstore_namespace/mymodels/base/Store.php @@ -24,8 +24,8 @@ public function rules() { return [ 'trim' => [['name'], 'trim'], - 'name_string' => [['name'], 'string'], 'required' => [['name'], 'required'], + 'name_string' => [['name'], 'string'], ]; } diff --git a/tests/specs/petstore_wrapped/models/base/Pet.php b/tests/specs/petstore_wrapped/models/base/Pet.php index aeb66135..9a51e269 100644 --- a/tests/specs/petstore_wrapped/models/base/Pet.php +++ b/tests/specs/petstore_wrapped/models/base/Pet.php @@ -25,9 +25,9 @@ public function rules() { return [ 'trim' => [['name', 'tag'], 'trim'], + 'required' => [['name'], 'required'], 'name_string' => [['name'], 'string'], 'tag_string' => [['tag'], 'string'], - 'required' => [['name'], 'required'], ]; } } diff --git a/tests/specs/petstore_xtable/models/base/Pet.php b/tests/specs/petstore_xtable/models/base/Pet.php index aeb66135..9a51e269 100644 --- a/tests/specs/petstore_xtable/models/base/Pet.php +++ b/tests/specs/petstore_xtable/models/base/Pet.php @@ -25,9 +25,9 @@ public function rules() { return [ 'trim' => [['name', 'tag'], 'trim'], + 'required' => [['name'], 'required'], 'name_string' => [['name'], 'string'], 'tag_string' => [['tag'], 'string'], - 'required' => [['name'], 'required'], ]; } } diff --git a/tests/specs/postgres_custom/models/base/Custom.php b/tests/specs/postgres_custom/models/base/Custom.php index aa1eedd7..9f13aace 100644 --- a/tests/specs/postgres_custom/models/base/Custom.php +++ b/tests/specs/postgres_custom/models/base/Custom.php @@ -30,7 +30,6 @@ public static function tableName() public function rules() { return [ - 'num_integer' => [['num'], 'integer'], 'num_default' => [['num'], 'default', 'value' => 0], 'json1_default' => [['json1'], 'default', 'value' => []], 'json2_default' => [['json2'], 'default', 'value' => []], @@ -46,18 +45,19 @@ public function rules() 'foo' => 'bar', 'bar' => 'baz', ]], + 'status_default' => [['status'], 'default', 'value' => 'draft'], + 'status_x_default' => [['status_x'], 'default', 'value' => 'draft'], + 'num_integer' => [['num'], 'integer'], 'status_string' => [['status'], 'string'], 'status_in' => [['status'], 'in', 'range' => [ 'active', 'draft', ]], - 'status_default' => [['status'], 'default', 'value' => 'draft'], 'status_x_string' => [['status_x'], 'string', 'max' => 10], 'status_x_in' => [['status_x'], 'in', 'range' => [ 'active', 'draft', ]], - 'status_x_default' => [['status_x'], 'default', 'value' => 'draft'], 'safe' => [['json1', 'json2', 'json3', 'json4'], 'safe'], ]; } diff --git a/tests/specs/x_db_default_expression/maria/edit/app/models/base/Fruit.php b/tests/specs/x_db_default_expression/maria/edit/app/models/base/Fruit.php index 77c97900..adea7459 100644 --- a/tests/specs/x_db_default_expression/maria/edit/app/models/base/Fruit.php +++ b/tests/specs/x_db_default_expression/maria/edit/app/models/base/Fruit.php @@ -32,26 +32,26 @@ public function rules() { return [ 'trim' => [['ts', 'ts2', 'ts3', 'ts4', 'ts5', 'ts6', 'd', 'd2', 'd3', 'ts7'], 'trim'], - 'ts_datetime' => [['ts'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], 'ts_default' => [['ts'], 'default', 'value' => new \yii\db\Expression("(CURRENT_TIMESTAMP)")], - 'ts2_datetime' => [['ts2'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], 'ts2_default' => [['ts2'], 'default', 'value' => '2011-11-11 00:00:00'], - 'ts3_datetime' => [['ts3'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], 'ts3_default' => [['ts3'], 'default', 'value' => '2022-11-11 00:00:00'], - 'ts4_string' => [['ts4'], 'string'], 'ts4_default' => [['ts4'], 'default', 'value' => '2022-11-11 00:00:00'], - 'ts5_string' => [['ts5'], 'string'], 'ts5_default' => [['ts5'], 'default', 'value' => new \yii\db\Expression("(CURRENT_TIMESTAMP)")], - 'ts6_string' => [['ts6'], 'string'], 'ts6_default' => [['ts6'], 'default', 'value' => '2000-11-11 00:00:00'], - 'd_date' => [['d'], 'date', 'format' => 'php:Y-m-d'], 'd_default' => [['d'], 'default', 'value' => new \yii\db\Expression("(CURRENT_DATE + INTERVAL 1 YEAR)")], - 'd2_string' => [['d2'], 'string'], 'd2_default' => [['d2'], 'default', 'value' => new \yii\db\Expression("(CURRENT_DATE + INTERVAL 1 YEAR)")], - 'd3_string' => [['d3'], 'string'], 'd3_default' => [['d3'], 'default', 'value' => 'text default'], - 'ts7_date' => [['ts7'], 'date', 'format' => 'php:Y-m-d'], 'ts7_default' => [['ts7'], 'default', 'value' => new \yii\db\Expression("(CURRENT_DATE + INTERVAL 1 YEAR)")], + 'ts_datetime' => [['ts'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], + 'ts2_datetime' => [['ts2'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], + 'ts3_datetime' => [['ts3'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], + 'ts4_string' => [['ts4'], 'string'], + 'ts5_string' => [['ts5'], 'string'], + 'ts6_string' => [['ts6'], 'string'], + 'd_date' => [['d'], 'date', 'format' => 'php:Y-m-d'], + 'd2_string' => [['d2'], 'string'], + 'd3_string' => [['d3'], 'string'], + 'ts7_date' => [['ts7'], 'date', 'format' => 'php:Y-m-d'], ]; } } diff --git a/tests/specs/x_db_default_expression/maria/edit_expression/app/models/base/Fruit.php b/tests/specs/x_db_default_expression/maria/edit_expression/app/models/base/Fruit.php index 77c97900..adea7459 100644 --- a/tests/specs/x_db_default_expression/maria/edit_expression/app/models/base/Fruit.php +++ b/tests/specs/x_db_default_expression/maria/edit_expression/app/models/base/Fruit.php @@ -32,26 +32,26 @@ public function rules() { return [ 'trim' => [['ts', 'ts2', 'ts3', 'ts4', 'ts5', 'ts6', 'd', 'd2', 'd3', 'ts7'], 'trim'], - 'ts_datetime' => [['ts'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], 'ts_default' => [['ts'], 'default', 'value' => new \yii\db\Expression("(CURRENT_TIMESTAMP)")], - 'ts2_datetime' => [['ts2'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], 'ts2_default' => [['ts2'], 'default', 'value' => '2011-11-11 00:00:00'], - 'ts3_datetime' => [['ts3'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], 'ts3_default' => [['ts3'], 'default', 'value' => '2022-11-11 00:00:00'], - 'ts4_string' => [['ts4'], 'string'], 'ts4_default' => [['ts4'], 'default', 'value' => '2022-11-11 00:00:00'], - 'ts5_string' => [['ts5'], 'string'], 'ts5_default' => [['ts5'], 'default', 'value' => new \yii\db\Expression("(CURRENT_TIMESTAMP)")], - 'ts6_string' => [['ts6'], 'string'], 'ts6_default' => [['ts6'], 'default', 'value' => '2000-11-11 00:00:00'], - 'd_date' => [['d'], 'date', 'format' => 'php:Y-m-d'], 'd_default' => [['d'], 'default', 'value' => new \yii\db\Expression("(CURRENT_DATE + INTERVAL 1 YEAR)")], - 'd2_string' => [['d2'], 'string'], 'd2_default' => [['d2'], 'default', 'value' => new \yii\db\Expression("(CURRENT_DATE + INTERVAL 1 YEAR)")], - 'd3_string' => [['d3'], 'string'], 'd3_default' => [['d3'], 'default', 'value' => 'text default'], - 'ts7_date' => [['ts7'], 'date', 'format' => 'php:Y-m-d'], 'ts7_default' => [['ts7'], 'default', 'value' => new \yii\db\Expression("(CURRENT_DATE + INTERVAL 1 YEAR)")], + 'ts_datetime' => [['ts'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], + 'ts2_datetime' => [['ts2'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], + 'ts3_datetime' => [['ts3'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], + 'ts4_string' => [['ts4'], 'string'], + 'ts5_string' => [['ts5'], 'string'], + 'ts6_string' => [['ts6'], 'string'], + 'd_date' => [['d'], 'date', 'format' => 'php:Y-m-d'], + 'd2_string' => [['d2'], 'string'], + 'd3_string' => [['d3'], 'string'], + 'ts7_date' => [['ts7'], 'date', 'format' => 'php:Y-m-d'], ]; } } diff --git a/tests/specs/x_db_default_expression/maria/simple/app/models/base/Fruit.php b/tests/specs/x_db_default_expression/maria/simple/app/models/base/Fruit.php index 77c97900..adea7459 100644 --- a/tests/specs/x_db_default_expression/maria/simple/app/models/base/Fruit.php +++ b/tests/specs/x_db_default_expression/maria/simple/app/models/base/Fruit.php @@ -32,26 +32,26 @@ public function rules() { return [ 'trim' => [['ts', 'ts2', 'ts3', 'ts4', 'ts5', 'ts6', 'd', 'd2', 'd3', 'ts7'], 'trim'], - 'ts_datetime' => [['ts'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], 'ts_default' => [['ts'], 'default', 'value' => new \yii\db\Expression("(CURRENT_TIMESTAMP)")], - 'ts2_datetime' => [['ts2'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], 'ts2_default' => [['ts2'], 'default', 'value' => '2011-11-11 00:00:00'], - 'ts3_datetime' => [['ts3'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], 'ts3_default' => [['ts3'], 'default', 'value' => '2022-11-11 00:00:00'], - 'ts4_string' => [['ts4'], 'string'], 'ts4_default' => [['ts4'], 'default', 'value' => '2022-11-11 00:00:00'], - 'ts5_string' => [['ts5'], 'string'], 'ts5_default' => [['ts5'], 'default', 'value' => new \yii\db\Expression("(CURRENT_TIMESTAMP)")], - 'ts6_string' => [['ts6'], 'string'], 'ts6_default' => [['ts6'], 'default', 'value' => '2000-11-11 00:00:00'], - 'd_date' => [['d'], 'date', 'format' => 'php:Y-m-d'], 'd_default' => [['d'], 'default', 'value' => new \yii\db\Expression("(CURRENT_DATE + INTERVAL 1 YEAR)")], - 'd2_string' => [['d2'], 'string'], 'd2_default' => [['d2'], 'default', 'value' => new \yii\db\Expression("(CURRENT_DATE + INTERVAL 1 YEAR)")], - 'd3_string' => [['d3'], 'string'], 'd3_default' => [['d3'], 'default', 'value' => 'text default'], - 'ts7_date' => [['ts7'], 'date', 'format' => 'php:Y-m-d'], 'ts7_default' => [['ts7'], 'default', 'value' => new \yii\db\Expression("(CURRENT_DATE + INTERVAL 1 YEAR)")], + 'ts_datetime' => [['ts'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], + 'ts2_datetime' => [['ts2'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], + 'ts3_datetime' => [['ts3'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], + 'ts4_string' => [['ts4'], 'string'], + 'ts5_string' => [['ts5'], 'string'], + 'ts6_string' => [['ts6'], 'string'], + 'd_date' => [['d'], 'date', 'format' => 'php:Y-m-d'], + 'd2_string' => [['d2'], 'string'], + 'd3_string' => [['d3'], 'string'], + 'ts7_date' => [['ts7'], 'date', 'format' => 'php:Y-m-d'], ]; } } diff --git a/tests/specs/x_db_default_expression/mysql/edit/app/models/base/Fruit.php b/tests/specs/x_db_default_expression/mysql/edit/app/models/base/Fruit.php index 77c97900..adea7459 100644 --- a/tests/specs/x_db_default_expression/mysql/edit/app/models/base/Fruit.php +++ b/tests/specs/x_db_default_expression/mysql/edit/app/models/base/Fruit.php @@ -32,26 +32,26 @@ public function rules() { return [ 'trim' => [['ts', 'ts2', 'ts3', 'ts4', 'ts5', 'ts6', 'd', 'd2', 'd3', 'ts7'], 'trim'], - 'ts_datetime' => [['ts'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], 'ts_default' => [['ts'], 'default', 'value' => new \yii\db\Expression("(CURRENT_TIMESTAMP)")], - 'ts2_datetime' => [['ts2'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], 'ts2_default' => [['ts2'], 'default', 'value' => '2011-11-11 00:00:00'], - 'ts3_datetime' => [['ts3'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], 'ts3_default' => [['ts3'], 'default', 'value' => '2022-11-11 00:00:00'], - 'ts4_string' => [['ts4'], 'string'], 'ts4_default' => [['ts4'], 'default', 'value' => '2022-11-11 00:00:00'], - 'ts5_string' => [['ts5'], 'string'], 'ts5_default' => [['ts5'], 'default', 'value' => new \yii\db\Expression("(CURRENT_TIMESTAMP)")], - 'ts6_string' => [['ts6'], 'string'], 'ts6_default' => [['ts6'], 'default', 'value' => '2000-11-11 00:00:00'], - 'd_date' => [['d'], 'date', 'format' => 'php:Y-m-d'], 'd_default' => [['d'], 'default', 'value' => new \yii\db\Expression("(CURRENT_DATE + INTERVAL 1 YEAR)")], - 'd2_string' => [['d2'], 'string'], 'd2_default' => [['d2'], 'default', 'value' => new \yii\db\Expression("(CURRENT_DATE + INTERVAL 1 YEAR)")], - 'd3_string' => [['d3'], 'string'], 'd3_default' => [['d3'], 'default', 'value' => 'text default'], - 'ts7_date' => [['ts7'], 'date', 'format' => 'php:Y-m-d'], 'ts7_default' => [['ts7'], 'default', 'value' => new \yii\db\Expression("(CURRENT_DATE + INTERVAL 1 YEAR)")], + 'ts_datetime' => [['ts'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], + 'ts2_datetime' => [['ts2'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], + 'ts3_datetime' => [['ts3'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], + 'ts4_string' => [['ts4'], 'string'], + 'ts5_string' => [['ts5'], 'string'], + 'ts6_string' => [['ts6'], 'string'], + 'd_date' => [['d'], 'date', 'format' => 'php:Y-m-d'], + 'd2_string' => [['d2'], 'string'], + 'd3_string' => [['d3'], 'string'], + 'ts7_date' => [['ts7'], 'date', 'format' => 'php:Y-m-d'], ]; } } diff --git a/tests/specs/x_db_default_expression/mysql/edit_expression/app/models/base/Fruit.php b/tests/specs/x_db_default_expression/mysql/edit_expression/app/models/base/Fruit.php index 77c97900..adea7459 100644 --- a/tests/specs/x_db_default_expression/mysql/edit_expression/app/models/base/Fruit.php +++ b/tests/specs/x_db_default_expression/mysql/edit_expression/app/models/base/Fruit.php @@ -32,26 +32,26 @@ public function rules() { return [ 'trim' => [['ts', 'ts2', 'ts3', 'ts4', 'ts5', 'ts6', 'd', 'd2', 'd3', 'ts7'], 'trim'], - 'ts_datetime' => [['ts'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], 'ts_default' => [['ts'], 'default', 'value' => new \yii\db\Expression("(CURRENT_TIMESTAMP)")], - 'ts2_datetime' => [['ts2'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], 'ts2_default' => [['ts2'], 'default', 'value' => '2011-11-11 00:00:00'], - 'ts3_datetime' => [['ts3'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], 'ts3_default' => [['ts3'], 'default', 'value' => '2022-11-11 00:00:00'], - 'ts4_string' => [['ts4'], 'string'], 'ts4_default' => [['ts4'], 'default', 'value' => '2022-11-11 00:00:00'], - 'ts5_string' => [['ts5'], 'string'], 'ts5_default' => [['ts5'], 'default', 'value' => new \yii\db\Expression("(CURRENT_TIMESTAMP)")], - 'ts6_string' => [['ts6'], 'string'], 'ts6_default' => [['ts6'], 'default', 'value' => '2000-11-11 00:00:00'], - 'd_date' => [['d'], 'date', 'format' => 'php:Y-m-d'], 'd_default' => [['d'], 'default', 'value' => new \yii\db\Expression("(CURRENT_DATE + INTERVAL 1 YEAR)")], - 'd2_string' => [['d2'], 'string'], 'd2_default' => [['d2'], 'default', 'value' => new \yii\db\Expression("(CURRENT_DATE + INTERVAL 1 YEAR)")], - 'd3_string' => [['d3'], 'string'], 'd3_default' => [['d3'], 'default', 'value' => 'text default'], - 'ts7_date' => [['ts7'], 'date', 'format' => 'php:Y-m-d'], 'ts7_default' => [['ts7'], 'default', 'value' => new \yii\db\Expression("(CURRENT_DATE + INTERVAL 1 YEAR)")], + 'ts_datetime' => [['ts'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], + 'ts2_datetime' => [['ts2'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], + 'ts3_datetime' => [['ts3'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], + 'ts4_string' => [['ts4'], 'string'], + 'ts5_string' => [['ts5'], 'string'], + 'ts6_string' => [['ts6'], 'string'], + 'd_date' => [['d'], 'date', 'format' => 'php:Y-m-d'], + 'd2_string' => [['d2'], 'string'], + 'd3_string' => [['d3'], 'string'], + 'ts7_date' => [['ts7'], 'date', 'format' => 'php:Y-m-d'], ]; } } diff --git a/tests/specs/x_db_default_expression/mysql/simple/app/models/base/Fruit.php b/tests/specs/x_db_default_expression/mysql/simple/app/models/base/Fruit.php index 77c97900..adea7459 100644 --- a/tests/specs/x_db_default_expression/mysql/simple/app/models/base/Fruit.php +++ b/tests/specs/x_db_default_expression/mysql/simple/app/models/base/Fruit.php @@ -32,26 +32,26 @@ public function rules() { return [ 'trim' => [['ts', 'ts2', 'ts3', 'ts4', 'ts5', 'ts6', 'd', 'd2', 'd3', 'ts7'], 'trim'], - 'ts_datetime' => [['ts'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], 'ts_default' => [['ts'], 'default', 'value' => new \yii\db\Expression("(CURRENT_TIMESTAMP)")], - 'ts2_datetime' => [['ts2'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], 'ts2_default' => [['ts2'], 'default', 'value' => '2011-11-11 00:00:00'], - 'ts3_datetime' => [['ts3'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], 'ts3_default' => [['ts3'], 'default', 'value' => '2022-11-11 00:00:00'], - 'ts4_string' => [['ts4'], 'string'], 'ts4_default' => [['ts4'], 'default', 'value' => '2022-11-11 00:00:00'], - 'ts5_string' => [['ts5'], 'string'], 'ts5_default' => [['ts5'], 'default', 'value' => new \yii\db\Expression("(CURRENT_TIMESTAMP)")], - 'ts6_string' => [['ts6'], 'string'], 'ts6_default' => [['ts6'], 'default', 'value' => '2000-11-11 00:00:00'], - 'd_date' => [['d'], 'date', 'format' => 'php:Y-m-d'], 'd_default' => [['d'], 'default', 'value' => new \yii\db\Expression("(CURRENT_DATE + INTERVAL 1 YEAR)")], - 'd2_string' => [['d2'], 'string'], 'd2_default' => [['d2'], 'default', 'value' => new \yii\db\Expression("(CURRENT_DATE + INTERVAL 1 YEAR)")], - 'd3_string' => [['d3'], 'string'], 'd3_default' => [['d3'], 'default', 'value' => 'text default'], - 'ts7_date' => [['ts7'], 'date', 'format' => 'php:Y-m-d'], 'ts7_default' => [['ts7'], 'default', 'value' => new \yii\db\Expression("(CURRENT_DATE + INTERVAL 1 YEAR)")], + 'ts_datetime' => [['ts'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], + 'ts2_datetime' => [['ts2'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], + 'ts3_datetime' => [['ts3'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], + 'ts4_string' => [['ts4'], 'string'], + 'ts5_string' => [['ts5'], 'string'], + 'ts6_string' => [['ts6'], 'string'], + 'd_date' => [['d'], 'date', 'format' => 'php:Y-m-d'], + 'd2_string' => [['d2'], 'string'], + 'd3_string' => [['d3'], 'string'], + 'ts7_date' => [['ts7'], 'date', 'format' => 'php:Y-m-d'], ]; } } diff --git a/tests/specs/x_db_default_expression/pgsql/edit/app/models/base/Fruit.php b/tests/specs/x_db_default_expression/pgsql/edit/app/models/base/Fruit.php index 77c97900..adea7459 100644 --- a/tests/specs/x_db_default_expression/pgsql/edit/app/models/base/Fruit.php +++ b/tests/specs/x_db_default_expression/pgsql/edit/app/models/base/Fruit.php @@ -32,26 +32,26 @@ public function rules() { return [ 'trim' => [['ts', 'ts2', 'ts3', 'ts4', 'ts5', 'ts6', 'd', 'd2', 'd3', 'ts7'], 'trim'], - 'ts_datetime' => [['ts'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], 'ts_default' => [['ts'], 'default', 'value' => new \yii\db\Expression("(CURRENT_TIMESTAMP)")], - 'ts2_datetime' => [['ts2'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], 'ts2_default' => [['ts2'], 'default', 'value' => '2011-11-11 00:00:00'], - 'ts3_datetime' => [['ts3'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], 'ts3_default' => [['ts3'], 'default', 'value' => '2022-11-11 00:00:00'], - 'ts4_string' => [['ts4'], 'string'], 'ts4_default' => [['ts4'], 'default', 'value' => '2022-11-11 00:00:00'], - 'ts5_string' => [['ts5'], 'string'], 'ts5_default' => [['ts5'], 'default', 'value' => new \yii\db\Expression("(CURRENT_TIMESTAMP)")], - 'ts6_string' => [['ts6'], 'string'], 'ts6_default' => [['ts6'], 'default', 'value' => '2000-11-11 00:00:00'], - 'd_date' => [['d'], 'date', 'format' => 'php:Y-m-d'], 'd_default' => [['d'], 'default', 'value' => new \yii\db\Expression("(CURRENT_DATE + INTERVAL 1 YEAR)")], - 'd2_string' => [['d2'], 'string'], 'd2_default' => [['d2'], 'default', 'value' => new \yii\db\Expression("(CURRENT_DATE + INTERVAL 1 YEAR)")], - 'd3_string' => [['d3'], 'string'], 'd3_default' => [['d3'], 'default', 'value' => 'text default'], - 'ts7_date' => [['ts7'], 'date', 'format' => 'php:Y-m-d'], 'ts7_default' => [['ts7'], 'default', 'value' => new \yii\db\Expression("(CURRENT_DATE + INTERVAL 1 YEAR)")], + 'ts_datetime' => [['ts'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], + 'ts2_datetime' => [['ts2'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], + 'ts3_datetime' => [['ts3'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], + 'ts4_string' => [['ts4'], 'string'], + 'ts5_string' => [['ts5'], 'string'], + 'ts6_string' => [['ts6'], 'string'], + 'd_date' => [['d'], 'date', 'format' => 'php:Y-m-d'], + 'd2_string' => [['d2'], 'string'], + 'd3_string' => [['d3'], 'string'], + 'ts7_date' => [['ts7'], 'date', 'format' => 'php:Y-m-d'], ]; } } diff --git a/tests/specs/x_db_default_expression/pgsql/edit_expression/app/models/base/Fruit.php b/tests/specs/x_db_default_expression/pgsql/edit_expression/app/models/base/Fruit.php index 77c97900..adea7459 100644 --- a/tests/specs/x_db_default_expression/pgsql/edit_expression/app/models/base/Fruit.php +++ b/tests/specs/x_db_default_expression/pgsql/edit_expression/app/models/base/Fruit.php @@ -32,26 +32,26 @@ public function rules() { return [ 'trim' => [['ts', 'ts2', 'ts3', 'ts4', 'ts5', 'ts6', 'd', 'd2', 'd3', 'ts7'], 'trim'], - 'ts_datetime' => [['ts'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], 'ts_default' => [['ts'], 'default', 'value' => new \yii\db\Expression("(CURRENT_TIMESTAMP)")], - 'ts2_datetime' => [['ts2'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], 'ts2_default' => [['ts2'], 'default', 'value' => '2011-11-11 00:00:00'], - 'ts3_datetime' => [['ts3'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], 'ts3_default' => [['ts3'], 'default', 'value' => '2022-11-11 00:00:00'], - 'ts4_string' => [['ts4'], 'string'], 'ts4_default' => [['ts4'], 'default', 'value' => '2022-11-11 00:00:00'], - 'ts5_string' => [['ts5'], 'string'], 'ts5_default' => [['ts5'], 'default', 'value' => new \yii\db\Expression("(CURRENT_TIMESTAMP)")], - 'ts6_string' => [['ts6'], 'string'], 'ts6_default' => [['ts6'], 'default', 'value' => '2000-11-11 00:00:00'], - 'd_date' => [['d'], 'date', 'format' => 'php:Y-m-d'], 'd_default' => [['d'], 'default', 'value' => new \yii\db\Expression("(CURRENT_DATE + INTERVAL 1 YEAR)")], - 'd2_string' => [['d2'], 'string'], 'd2_default' => [['d2'], 'default', 'value' => new \yii\db\Expression("(CURRENT_DATE + INTERVAL 1 YEAR)")], - 'd3_string' => [['d3'], 'string'], 'd3_default' => [['d3'], 'default', 'value' => 'text default'], - 'ts7_date' => [['ts7'], 'date', 'format' => 'php:Y-m-d'], 'ts7_default' => [['ts7'], 'default', 'value' => new \yii\db\Expression("(CURRENT_DATE + INTERVAL 1 YEAR)")], + 'ts_datetime' => [['ts'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], + 'ts2_datetime' => [['ts2'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], + 'ts3_datetime' => [['ts3'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], + 'ts4_string' => [['ts4'], 'string'], + 'ts5_string' => [['ts5'], 'string'], + 'ts6_string' => [['ts6'], 'string'], + 'd_date' => [['d'], 'date', 'format' => 'php:Y-m-d'], + 'd2_string' => [['d2'], 'string'], + 'd3_string' => [['d3'], 'string'], + 'ts7_date' => [['ts7'], 'date', 'format' => 'php:Y-m-d'], ]; } } diff --git a/tests/specs/x_db_default_expression/pgsql/simple/app/models/base/Fruit.php b/tests/specs/x_db_default_expression/pgsql/simple/app/models/base/Fruit.php index 77c97900..adea7459 100644 --- a/tests/specs/x_db_default_expression/pgsql/simple/app/models/base/Fruit.php +++ b/tests/specs/x_db_default_expression/pgsql/simple/app/models/base/Fruit.php @@ -32,26 +32,26 @@ public function rules() { return [ 'trim' => [['ts', 'ts2', 'ts3', 'ts4', 'ts5', 'ts6', 'd', 'd2', 'd3', 'ts7'], 'trim'], - 'ts_datetime' => [['ts'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], 'ts_default' => [['ts'], 'default', 'value' => new \yii\db\Expression("(CURRENT_TIMESTAMP)")], - 'ts2_datetime' => [['ts2'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], 'ts2_default' => [['ts2'], 'default', 'value' => '2011-11-11 00:00:00'], - 'ts3_datetime' => [['ts3'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], 'ts3_default' => [['ts3'], 'default', 'value' => '2022-11-11 00:00:00'], - 'ts4_string' => [['ts4'], 'string'], 'ts4_default' => [['ts4'], 'default', 'value' => '2022-11-11 00:00:00'], - 'ts5_string' => [['ts5'], 'string'], 'ts5_default' => [['ts5'], 'default', 'value' => new \yii\db\Expression("(CURRENT_TIMESTAMP)")], - 'ts6_string' => [['ts6'], 'string'], 'ts6_default' => [['ts6'], 'default', 'value' => '2000-11-11 00:00:00'], - 'd_date' => [['d'], 'date', 'format' => 'php:Y-m-d'], 'd_default' => [['d'], 'default', 'value' => new \yii\db\Expression("(CURRENT_DATE + INTERVAL 1 YEAR)")], - 'd2_string' => [['d2'], 'string'], 'd2_default' => [['d2'], 'default', 'value' => new \yii\db\Expression("(CURRENT_DATE + INTERVAL 1 YEAR)")], - 'd3_string' => [['d3'], 'string'], 'd3_default' => [['d3'], 'default', 'value' => 'text default'], - 'ts7_date' => [['ts7'], 'date', 'format' => 'php:Y-m-d'], 'ts7_default' => [['ts7'], 'default', 'value' => new \yii\db\Expression("(CURRENT_DATE + INTERVAL 1 YEAR)")], + 'ts_datetime' => [['ts'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], + 'ts2_datetime' => [['ts2'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], + 'ts3_datetime' => [['ts3'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], + 'ts4_string' => [['ts4'], 'string'], + 'ts5_string' => [['ts5'], 'string'], + 'ts6_string' => [['ts6'], 'string'], + 'd_date' => [['d'], 'date', 'format' => 'php:Y-m-d'], + 'd2_string' => [['d2'], 'string'], + 'd3_string' => [['d3'], 'string'], + 'ts7_date' => [['ts7'], 'date', 'format' => 'php:Y-m-d'], ]; } } From cb0b3d5e790e7e0e9c40c151ef660dfba63d3207 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Thu, 20 Feb 2025 15:51:33 +0530 Subject: [PATCH 322/358] Fix failing tests 2 --- tests/specs/id_not_in_rules/app/models/base/Fruit.php | 2 +- .../mysql/models/base/Ubigpk.php | 2 +- .../app/models/base/Pristine.php | 2 +- .../maria/models/base/Mailing.php | 2 +- .../maria/models/base/Contact.php | 8 ++++---- .../maria/models/base/Mailing.php | 2 +- .../app/models/base/Order.php | 4 ++-- .../pgsql/models/base/Account.php | 2 +- .../pgsql/models/base/Contact.php | 8 ++++---- .../pgsql/models/base/PaymentMethod.php | 4 ++-- .../mysql/models/base/Account.php | 4 ++-- .../mysql/models/base/Menu.php | 2 +- .../mysql/models/base/Post.php | 2 +- .../mysql/models/base/Address.php | 6 +++--- .../app/models/base/Account.php | 2 +- .../app/models/base/E123.php | 2 +- .../specs/relations_in_faker/app/models/base/A123.php | 2 +- .../relations_in_faker/app/models/base/Account.php | 2 +- .../specs/relations_in_faker/app/models/base/B123.php | 2 +- .../relations_in_faker/app/models/base/Domain.php | 4 ++-- .../specs/relations_in_faker/app/models/base/E123.php | 2 +- .../relations_in_faker/app/models/base/Routing.php | 10 +++++----- 22 files changed, 38 insertions(+), 38 deletions(-) diff --git a/tests/specs/id_not_in_rules/app/models/base/Fruit.php b/tests/specs/id_not_in_rules/app/models/base/Fruit.php index d687de14..36a8f42f 100644 --- a/tests/specs/id_not_in_rules/app/models/base/Fruit.php +++ b/tests/specs/id_not_in_rules/app/models/base/Fruit.php @@ -24,8 +24,8 @@ public function rules() { return [ 'trim' => [['name'], 'trim'], - 'name_string' => [['name'], 'string'], 'required' => [['name'], 'required'], + 'name_string' => [['name'], 'string'], ]; } } diff --git a/tests/specs/issue_fix/132_create_migration_for_drop_table/mysql/models/base/Ubigpk.php b/tests/specs/issue_fix/132_create_migration_for_drop_table/mysql/models/base/Ubigpk.php index 5f8cbf5f..d1ebaa65 100644 --- a/tests/specs/issue_fix/132_create_migration_for_drop_table/mysql/models/base/Ubigpk.php +++ b/tests/specs/issue_fix/132_create_migration_for_drop_table/mysql/models/base/Ubigpk.php @@ -30,6 +30,7 @@ public function rules() { return [ 'trim' => [['name', 'f'], 'trim'], + 'size_default' => [['size'], 'default', 'value' => 'x-small'], 'name_string' => [['name'], 'string', 'max' => 150], 'size_string' => [['size'], 'string'], 'size_in' => [['size'], 'in', 'range' => [ @@ -39,7 +40,6 @@ public function rules() 'large', 'x-large', ]], - 'size_default' => [['size'], 'default', 'value' => 'x-small'], 'd_integer' => [['d'], 'integer'], 'e_integer' => [['e'], 'integer'], 'f_string' => [['f'], 'string', 'max' => 12], diff --git a/tests/specs/issue_fix/153_nullable_false_in_required/app/models/base/Pristine.php b/tests/specs/issue_fix/153_nullable_false_in_required/app/models/base/Pristine.php index f582815e..0aab2fad 100644 --- a/tests/specs/issue_fix/153_nullable_false_in_required/app/models/base/Pristine.php +++ b/tests/specs/issue_fix/153_nullable_false_in_required/app/models/base/Pristine.php @@ -23,9 +23,9 @@ public static function tableName() public function rules() { return [ - 'billing_factor_integer' => [['billing_factor'], 'integer'], 'billing_factor_default' => [['billing_factor'], 'default', 'value' => 100], 'required' => [['billing_factor'], 'required'], + 'billing_factor_integer' => [['billing_factor'], 'integer'], ]; } } diff --git a/tests/specs/issue_fix/158_bug_giiapi_generated_rules_enum_with_trim/maria/models/base/Mailing.php b/tests/specs/issue_fix/158_bug_giiapi_generated_rules_enum_with_trim/maria/models/base/Mailing.php index f5ac5ebc..83a982c1 100644 --- a/tests/specs/issue_fix/158_bug_giiapi_generated_rules_enum_with_trim/maria/models/base/Mailing.php +++ b/tests/specs/issue_fix/158_bug_giiapi_generated_rules_enum_with_trim/maria/models/base/Mailing.php @@ -25,6 +25,7 @@ public function rules() { return [ 'trim' => [['name'], 'trim'], + 'required' => [['name'], 'required'], 'name_string' => [['name'], 'string', 'max' => 128], 'paymentMethodName_string' => [['paymentMethodName'], 'string'], 'paymentMethodName_in' => [['paymentMethodName'], 'in', 'range' => [ @@ -32,7 +33,6 @@ public function rules() 'cash', 'ewallet', ]], - 'required' => [['name'], 'required'], ]; } } diff --git a/tests/specs/issue_fix/159_bug_giiapi_generated_rules_emailid/maria/models/base/Contact.php b/tests/specs/issue_fix/159_bug_giiapi_generated_rules_emailid/maria/models/base/Contact.php index d76590f3..a7df2b21 100644 --- a/tests/specs/issue_fix/159_bug_giiapi_generated_rules_emailid/maria/models/base/Contact.php +++ b/tests/specs/issue_fix/159_bug_giiapi_generated_rules_emailid/maria/models/base/Contact.php @@ -27,12 +27,12 @@ public function rules() { return [ 'trim' => [['nickname'], 'trim'], - 'mailing_id_integer' => [['mailing_id'], 'integer'], - 'mailing_id_exist' => [['mailing_id'], 'exist', 'targetRelation' => 'mailing'], - 'active_boolean' => [['active'], 'boolean'], 'active_default' => [['active'], 'default', 'value' => false], - 'nickname_string' => [['nickname'], 'string'], 'required' => [['mailing_id'], 'required'], + 'active_boolean' => [['active'], 'boolean'], + 'nickname_string' => [['nickname'], 'string'], + 'mailing_id_integer' => [['mailing_id'], 'integer'], + 'mailing_id_exist' => [['mailing_id'], 'exist', 'targetRelation' => 'mailing'], ]; } diff --git a/tests/specs/issue_fix/159_bug_giiapi_generated_rules_emailid/maria/models/base/Mailing.php b/tests/specs/issue_fix/159_bug_giiapi_generated_rules_emailid/maria/models/base/Mailing.php index e1edb8c2..57bb103f 100644 --- a/tests/specs/issue_fix/159_bug_giiapi_generated_rules_emailid/maria/models/base/Mailing.php +++ b/tests/specs/issue_fix/159_bug_giiapi_generated_rules_emailid/maria/models/base/Mailing.php @@ -25,9 +25,9 @@ public function rules() { return [ 'trim' => [['name', 'paymentMethodName'], 'trim'], + 'required' => [['name'], 'required'], 'name_string' => [['name'], 'string', 'max' => 128], 'paymentMethodName_string' => [['paymentMethodName'], 'string'], - 'required' => [['name'], 'required'], ]; } diff --git a/tests/specs/issue_fix/162_bug_dollarref_with_x_faker/app/models/base/Order.php b/tests/specs/issue_fix/162_bug_dollarref_with_x_faker/app/models/base/Order.php index 9f23f63a..722e3c53 100644 --- a/tests/specs/issue_fix/162_bug_dollarref_with_x_faker/app/models/base/Order.php +++ b/tests/specs/issue_fix/162_bug_dollarref_with_x_faker/app/models/base/Order.php @@ -27,10 +27,10 @@ public function rules() { return [ 'trim' => [['name', 'name2'], 'trim'], - 'invoice_id_integer' => [['invoice_id'], 'integer'], - 'invoice_id_exist' => [['invoice_id'], 'exist', 'targetRelation' => 'invoice'], 'name_string' => [['name'], 'string'], 'name2_string' => [['name2'], 'string'], + 'invoice_id_integer' => [['invoice_id'], 'integer'], + 'invoice_id_exist' => [['invoice_id'], 'exist', 'targetRelation' => 'invoice'], ]; } diff --git a/tests/specs/issue_fix/175_bug_allof_with_multiple_dollarrefs/pgsql/models/base/Account.php b/tests/specs/issue_fix/175_bug_allof_with_multiple_dollarrefs/pgsql/models/base/Account.php index 68499dfb..cd597631 100644 --- a/tests/specs/issue_fix/175_bug_allof_with_multiple_dollarrefs/pgsql/models/base/Account.php +++ b/tests/specs/issue_fix/175_bug_allof_with_multiple_dollarrefs/pgsql/models/base/Account.php @@ -25,9 +25,9 @@ public function rules() { return [ 'trim' => [['name', 'paymentMethodName'], 'trim'], + 'required' => [['name'], 'required'], 'name_string' => [['name'], 'string', 'max' => 128], 'paymentMethodName_string' => [['paymentMethodName'], 'string'], - 'required' => [['name'], 'required'], ]; } diff --git a/tests/specs/issue_fix/175_bug_allof_with_multiple_dollarrefs/pgsql/models/base/Contact.php b/tests/specs/issue_fix/175_bug_allof_with_multiple_dollarrefs/pgsql/models/base/Contact.php index 385f9ef5..47eeecc0 100644 --- a/tests/specs/issue_fix/175_bug_allof_with_multiple_dollarrefs/pgsql/models/base/Contact.php +++ b/tests/specs/issue_fix/175_bug_allof_with_multiple_dollarrefs/pgsql/models/base/Contact.php @@ -27,12 +27,12 @@ public function rules() { return [ 'trim' => [['nickname'], 'trim'], - 'account_id_integer' => [['account_id'], 'integer'], - 'account_id_exist' => [['account_id'], 'exist', 'targetRelation' => 'account'], - 'active_boolean' => [['active'], 'boolean'], 'active_default' => [['active'], 'default', 'value' => false], - 'nickname_string' => [['nickname'], 'string'], 'required' => [['account_id'], 'required'], + 'active_boolean' => [['active'], 'boolean'], + 'nickname_string' => [['nickname'], 'string'], + 'account_id_integer' => [['account_id'], 'integer'], + 'account_id_exist' => [['account_id'], 'exist', 'targetRelation' => 'account'], ]; } diff --git a/tests/specs/issue_fix/175_bug_allof_with_multiple_dollarrefs/pgsql/models/base/PaymentMethod.php b/tests/specs/issue_fix/175_bug_allof_with_multiple_dollarrefs/pgsql/models/base/PaymentMethod.php index 33575e05..0bc51c6d 100644 --- a/tests/specs/issue_fix/175_bug_allof_with_multiple_dollarrefs/pgsql/models/base/PaymentMethod.php +++ b/tests/specs/issue_fix/175_bug_allof_with_multiple_dollarrefs/pgsql/models/base/PaymentMethod.php @@ -24,9 +24,9 @@ public function rules() { return [ 'trim' => [['name'], 'trim'], - 'name_unique' => [['name'], 'unique'], - 'name_string' => [['name'], 'string', 'max' => 150], 'required' => [['name'], 'required'], + 'name_string' => [['name'], 'string', 'max' => 150], + 'name_unique' => [['name'], 'unique'], ]; } } diff --git a/tests/specs/issue_fix/25_generate_inverse_relations/mysql/models/base/Account.php b/tests/specs/issue_fix/25_generate_inverse_relations/mysql/models/base/Account.php index d3846586..dc8c02f8 100644 --- a/tests/specs/issue_fix/25_generate_inverse_relations/mysql/models/base/Account.php +++ b/tests/specs/issue_fix/25_generate_inverse_relations/mysql/models/base/Account.php @@ -32,14 +32,14 @@ public function rules() return [ 'trim' => [['name', 'paymentMethodName'], 'trim'], 'required' => [['name'], 'required'], + 'name_string' => [['name'], 'string', 'max' => 128], + 'paymentMethodName_string' => [['paymentMethodName'], 'string'], 'user_id_integer' => [['user_id'], 'integer'], 'user_id_exist' => [['user_id'], 'exist', 'targetRelation' => 'user'], 'user2_id_integer' => [['user2_id'], 'integer'], 'user2_id_exist' => [['user2_id'], 'exist', 'targetRelation' => 'user2'], 'user3_integer' => [['user3'], 'integer'], 'user3_exist' => [['user3'], 'exist', 'targetRelation' => 'user3Rel'], - 'name_string' => [['name'], 'string', 'max' => 128], - 'paymentMethodName_string' => [['paymentMethodName'], 'string'], ]; } diff --git a/tests/specs/issue_fix/25_generate_inverse_relations/mysql/models/base/Menu.php b/tests/specs/issue_fix/25_generate_inverse_relations/mysql/models/base/Menu.php index 7f2eb9aa..5360d9cd 100644 --- a/tests/specs/issue_fix/25_generate_inverse_relations/mysql/models/base/Menu.php +++ b/tests/specs/issue_fix/25_generate_inverse_relations/mysql/models/base/Menu.php @@ -28,9 +28,9 @@ public function rules() return [ 'trim' => [['name'], 'trim'], 'required' => [['name'], 'required'], + 'name_string' => [['name'], 'string', 'min' => 3, 'max' => 100], 'parent_id_integer' => [['parent_id'], 'integer'], 'parent_id_exist' => [['parent_id'], 'exist', 'targetRelation' => 'parent'], - 'name_string' => [['name'], 'string', 'min' => 3, 'max' => 100], ]; } diff --git a/tests/specs/issue_fix/29_extension_fk_column_name_cause_error_in_case_of_column_name_without_underscore/mysql/models/base/Post.php b/tests/specs/issue_fix/29_extension_fk_column_name_cause_error_in_case_of_column_name_without_underscore/mysql/models/base/Post.php index 3cc065c0..605dc271 100644 --- a/tests/specs/issue_fix/29_extension_fk_column_name_cause_error_in_case_of_column_name_without_underscore/mysql/models/base/Post.php +++ b/tests/specs/issue_fix/29_extension_fk_column_name_cause_error_in_case_of_column_name_without_underscore/mysql/models/base/Post.php @@ -26,9 +26,9 @@ public function rules() { return [ 'trim' => [['content'], 'trim'], + 'content_string' => [['content'], 'string'], 'user_integer' => [['user'], 'integer'], 'user_exist' => [['user'], 'exist', 'targetRelation' => 'userRel'], - 'content_string' => [['content'], 'string'], ]; } diff --git a/tests/specs/issue_fix/3_bug_add_remove_property_and_at_the_same_time_change_it_at_x_indexes/mysql/models/base/Address.php b/tests/specs/issue_fix/3_bug_add_remove_property_and_at_the_same_time_change_it_at_x_indexes/mysql/models/base/Address.php index a429e822..fba0ce27 100644 --- a/tests/specs/issue_fix/3_bug_add_remove_property_and_at_the_same_time_change_it_at_x_indexes/mysql/models/base/Address.php +++ b/tests/specs/issue_fix/3_bug_add_remove_property_and_at_the_same_time_change_it_at_x_indexes/mysql/models/base/Address.php @@ -26,13 +26,13 @@ public function rules() { return [ 'trim' => [['name', 'shortName', 'postCode'], 'trim'], + 'name_string' => [['name'], 'string', 'max' => 64], + 'shortName_string' => [['shortName'], 'string', 'max' => 64], + 'postCode_string' => [['postCode'], 'string', 'max' => 64], 'shortName_postCode_unique' => [['shortName', 'postCode'], 'unique', 'targetAttribute' => [ 'shortName', 'postCode', ]], - 'name_string' => [['name'], 'string', 'max' => 64], - 'shortName_string' => [['shortName'], 'string', 'max' => 64], - 'postCode_string' => [['postCode'], 'string', 'max' => 64], ]; } } diff --git a/tests/specs/issue_fix/model_name_more_than_once_in_faker_148/app/models/base/Account.php b/tests/specs/issue_fix/model_name_more_than_once_in_faker_148/app/models/base/Account.php index 7e67f18b..f875eadd 100644 --- a/tests/specs/issue_fix/model_name_more_than_once_in_faker_148/app/models/base/Account.php +++ b/tests/specs/issue_fix/model_name_more_than_once_in_faker_148/app/models/base/Account.php @@ -24,8 +24,8 @@ public function rules() { return [ 'trim' => [['name'], 'trim'], - 'name_string' => [['name'], 'string', 'max' => 40], 'required' => [['name'], 'required'], + 'name_string' => [['name'], 'string', 'max' => 40], ]; } diff --git a/tests/specs/issue_fix/model_name_more_than_once_in_faker_148/app/models/base/E123.php b/tests/specs/issue_fix/model_name_more_than_once_in_faker_148/app/models/base/E123.php index 74685405..f0f30935 100644 --- a/tests/specs/issue_fix/model_name_more_than_once_in_faker_148/app/models/base/E123.php +++ b/tests/specs/issue_fix/model_name_more_than_once_in_faker_148/app/models/base/E123.php @@ -30,13 +30,13 @@ public function rules() { return [ 'trim' => [['name'], 'trim'], + 'name_string' => [['name'], 'string'], 'account_id_integer' => [['account_id'], 'integer'], 'account_id_exist' => [['account_id'], 'exist', 'targetRelation' => 'account'], 'account_2_id_integer' => [['account_2_id'], 'integer'], 'account_2_id_exist' => [['account_2_id'], 'exist', 'targetRelation' => 'account2'], 'account_3_id_integer' => [['account_3_id'], 'integer'], 'account_3_id_exist' => [['account_3_id'], 'exist', 'targetRelation' => 'account3'], - 'name_string' => [['name'], 'string'], ]; } diff --git a/tests/specs/relations_in_faker/app/models/base/A123.php b/tests/specs/relations_in_faker/app/models/base/A123.php index 9be6a778..0c733222 100644 --- a/tests/specs/relations_in_faker/app/models/base/A123.php +++ b/tests/specs/relations_in_faker/app/models/base/A123.php @@ -26,9 +26,9 @@ public function rules() { return [ 'trim' => [['name'], 'trim'], + 'name_string' => [['name'], 'string'], 'b123_id_integer' => [['b123_id'], 'integer'], 'b123_id_exist' => [['b123_id'], 'exist', 'targetRelation' => 'b123'], - 'name_string' => [['name'], 'string'], ]; } diff --git a/tests/specs/relations_in_faker/app/models/base/Account.php b/tests/specs/relations_in_faker/app/models/base/Account.php index 5cba7dbf..e1198a95 100644 --- a/tests/specs/relations_in_faker/app/models/base/Account.php +++ b/tests/specs/relations_in_faker/app/models/base/Account.php @@ -24,8 +24,8 @@ public function rules() { return [ 'trim' => [['name'], 'trim'], - 'name_string' => [['name'], 'string', 'max' => 40], 'required' => [['name'], 'required'], + 'name_string' => [['name'], 'string', 'max' => 40], ]; } diff --git a/tests/specs/relations_in_faker/app/models/base/B123.php b/tests/specs/relations_in_faker/app/models/base/B123.php index f85ffee5..7ad4eb77 100644 --- a/tests/specs/relations_in_faker/app/models/base/B123.php +++ b/tests/specs/relations_in_faker/app/models/base/B123.php @@ -26,9 +26,9 @@ public function rules() { return [ 'trim' => [['name'], 'trim'], + 'name_string' => [['name'], 'string'], 'c123_id_integer' => [['c123_id'], 'integer'], 'c123_id_exist' => [['c123_id'], 'exist', 'targetRelation' => 'c123'], - 'name_string' => [['name'], 'string'], ]; } diff --git a/tests/specs/relations_in_faker/app/models/base/Domain.php b/tests/specs/relations_in_faker/app/models/base/Domain.php index 9b508a35..df6e0822 100644 --- a/tests/specs/relations_in_faker/app/models/base/Domain.php +++ b/tests/specs/relations_in_faker/app/models/base/Domain.php @@ -28,10 +28,10 @@ public function rules() { return [ 'trim' => [['name'], 'trim'], + 'required' => [['name', 'account_id'], 'required'], + 'name_string' => [['name'], 'string', 'max' => 128], 'account_id_integer' => [['account_id'], 'integer'], 'account_id_exist' => [['account_id'], 'exist', 'targetRelation' => 'account'], - 'name_string' => [['name'], 'string', 'max' => 128], - 'required' => [['name', 'account_id'], 'required'], ]; } diff --git a/tests/specs/relations_in_faker/app/models/base/E123.php b/tests/specs/relations_in_faker/app/models/base/E123.php index cefdb5ce..eb950129 100644 --- a/tests/specs/relations_in_faker/app/models/base/E123.php +++ b/tests/specs/relations_in_faker/app/models/base/E123.php @@ -26,9 +26,9 @@ public function rules() { return [ 'trim' => [['name'], 'trim'], + 'name_string' => [['name'], 'string'], 'b123_id_integer' => [['b123_id'], 'integer'], 'b123_id_exist' => [['b123_id'], 'exist', 'targetRelation' => 'b123'], - 'name_string' => [['name'], 'string'], ]; } diff --git a/tests/specs/relations_in_faker/app/models/base/Routing.php b/tests/specs/relations_in_faker/app/models/base/Routing.php index 0a6c00d2..f61885fc 100644 --- a/tests/specs/relations_in_faker/app/models/base/Routing.php +++ b/tests/specs/relations_in_faker/app/models/base/Routing.php @@ -34,17 +34,17 @@ public function rules() { return [ 'trim' => [['path', 'service'], 'trim'], + 'required' => [['domain_id'], 'required'], + 'path_string' => [['path'], 'string', 'max' => 255], + 'ssl_boolean' => [['ssl'], 'boolean'], + 'redirect_to_ssl_boolean' => [['redirect_to_ssl'], 'boolean'], + 'service_string' => [['service'], 'string', 'max' => 255], 'domain_id_integer' => [['domain_id'], 'integer'], 'domain_id_exist' => [['domain_id'], 'exist', 'targetRelation' => 'domain'], 'd123_id_integer' => [['d123_id'], 'integer'], 'd123_id_exist' => [['d123_id'], 'exist', 'targetRelation' => 'd123'], 'a123_id_integer' => [['a123_id'], 'integer'], 'a123_id_exist' => [['a123_id'], 'exist', 'targetRelation' => 'a123'], - 'path_string' => [['path'], 'string', 'max' => 255], - 'ssl_boolean' => [['ssl'], 'boolean'], - 'redirect_to_ssl_boolean' => [['redirect_to_ssl'], 'boolean'], - 'service_string' => [['service'], 'string', 'max' => 255], - 'required' => [['domain_id'], 'required'], ]; } From 754d1fe2c9e40eff8096556b8adcbe574dfe9756 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Thu, 20 Feb 2025 15:53:08 +0530 Subject: [PATCH 323/358] Fix failing tests --- .../models/mariamodel/base/Alldbdatatype.php | 20 ++++++++-------- .../app/models/mariamodel/base/Editcolumn.php | 14 +++++------ .../app/models/mariamodel/base/Newcolumn.php | 4 ++-- .../app/models/mariamodel/base/Pristine.php | 6 ++--- .../mysql/app/models/base/Alldbdatatype.php | 20 ++++++++-------- .../mysql/app/models/base/Editcolumn.php | 14 +++++------ .../mysql/app/models/base/Newcolumn.php | 4 ++-- .../mysql/app/models/base/Pristine.php | 6 ++--- .../models/pgsqlmodel/base/Alldbdatatype.php | 24 +++++++++---------- .../app/models/pgsqlmodel/base/Editcolumn.php | 13 +++++----- .../app/models/pgsqlmodel/base/Newcolumn.php | 6 ++--- .../app/models/pgsqlmodel/base/Pristine.php | 6 ++--- 12 files changed, 68 insertions(+), 69 deletions(-) diff --git a/tests/specs/x_db_type/rules_and_more/maria/app/models/mariamodel/base/Alldbdatatype.php b/tests/specs/x_db_type/rules_and_more/maria/app/models/mariamodel/base/Alldbdatatype.php index c0d7414c..dbbd7ebc 100644 --- a/tests/specs/x_db_type/rules_and_more/maria/app/models/mariamodel/base/Alldbdatatype.php +++ b/tests/specs/x_db_type/rules_and_more/maria/app/models/mariamodel/base/Alldbdatatype.php @@ -66,6 +66,16 @@ public function rules() { return [ 'trim' => [['string_col', 'varchar_col', 'text_col', 'varchar_4_col', 'char_4_col', 'char_5_col', 'char_6_col', 'char_7_col', 'char_8_col', 'date_col', 'time_col', 'datetime_col', 'timestamp_col', 'year_col', 'text_def'], 'trim'], + 'char_8_col_default' => [['char_8_col'], 'default', 'value' => 'd'], + 'mi_default' => [['mi'], 'default', 'value' => 7], + 'json_col_def_default' => [['json_col_def'], 'default', 'value' => []], + 'json_col_def_2_default' => [['json_col_def_2'], 'default', 'value' => []], + 'blob_def_default' => [['blob_def'], 'default', 'value' => 'the blob'], + 'text_def_default' => [['text_def'], 'default', 'value' => 'the text'], + 'json_def_default' => [['json_def'], 'default', 'value' => [ + 'a' => 'b', + ]], + 'required' => [['char_6_col', 'char_7_col'], 'required'], 'string_col_string' => [['string_col'], 'string', 'max' => 255], 'varchar_col_string' => [['varchar_col'], 'string', 'max' => 132], 'text_col_string' => [['text_col'], 'string'], @@ -75,7 +85,6 @@ public function rules() 'char_6_col_string' => [['char_6_col'], 'string'], 'char_7_col_string' => [['char_7_col'], 'string', 'max' => 6], 'char_8_col_string' => [['char_8_col'], 'string'], - 'char_8_col_default' => [['char_8_col'], 'default', 'value' => 'd'], 'decimal_col_double' => [['decimal_col'], 'double'], 'bit_col_integer' => [['bit_col'], 'integer'], 'bit_2_integer' => [['bit_2'], 'integer'], @@ -86,7 +95,6 @@ public function rules() 'si_col_integer' => [['si_col'], 'integer'], 'si_col_2_integer' => [['si_col_2'], 'integer'], 'mi_integer' => [['mi'], 'integer'], - 'mi_default' => [['mi'], 'default', 'value' => 7], 'bi_integer' => [['bi'], 'integer'], 'int_col_integer' => [['int_col'], 'integer'], 'int_col_2_integer' => [['int_col_2'], 'integer'], @@ -103,16 +111,8 @@ public function rules() 'datetime_col_datetime' => [['datetime_col'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], 'timestamp_col_string' => [['timestamp_col'], 'string'], 'year_col_string' => [['year_col'], 'string'], - 'json_col_def_default' => [['json_col_def'], 'default', 'value' => []], - 'json_col_def_2_default' => [['json_col_def_2'], 'default', 'value' => []], - 'blob_def_default' => [['blob_def'], 'default', 'value' => 'the blob'], 'text_def_string' => [['text_def'], 'string'], - 'text_def_default' => [['text_def'], 'default', 'value' => 'the text'], - 'json_def_default' => [['json_def'], 'default', 'value' => [ - 'a' => 'b', - ]], 'safe' => [['varbinary_col', 'blob_col', 'json_col', 'json_col_def', 'json_col_def_2', 'blob_def', 'json_def'], 'safe'], - 'required' => [['char_6_col', 'char_7_col'], 'required'], ]; } } diff --git a/tests/specs/x_db_type/rules_and_more/maria/app/models/mariamodel/base/Editcolumn.php b/tests/specs/x_db_type/rules_and_more/maria/app/models/mariamodel/base/Editcolumn.php index e80af28f..acaa29cf 100644 --- a/tests/specs/x_db_type/rules_and_more/maria/app/models/mariamodel/base/Editcolumn.php +++ b/tests/specs/x_db_type/rules_and_more/maria/app/models/mariamodel/base/Editcolumn.php @@ -34,22 +34,22 @@ public function rules() { return [ 'trim' => [['name', 'tag', 'first_name', 'string_col', 'str_col_def', 'json_col'], 'trim'], - 'name_string' => [['name'], 'string', 'max' => 254], 'name_default' => [['name'], 'default', 'value' => 'Horse-2'], + 'dec_col_default' => [['dec_col'], 'default', 'value' => 3.14], + 'json_col_default' => [['json_col'], 'default', 'value' => 'fox jumps over dog'], + 'json_col_2_default' => [['json_col_2'], 'default', 'value' => []], + 'json_col_def_n_default' => [['json_col_def_n'], 'default', 'value' => []], + 'json_col_def_n_2_default' => [['json_col_def_n_2'], 'default', 'value' => []], + 'required' => [['name', 'str_col_def', 'json_col', 'json_col_2'], 'required'], + 'name_string' => [['name'], 'string', 'max' => 254], 'tag_string' => [['tag'], 'string'], 'first_name_string' => [['first_name'], 'string', 'max' => 255], 'string_col_string' => [['string_col'], 'string'], 'dec_col_double' => [['dec_col'], 'double'], - 'dec_col_default' => [['dec_col'], 'default', 'value' => 3.14], 'str_col_def_string' => [['str_col_def'], 'string', 'max' => 3], 'json_col_string' => [['json_col'], 'string'], - 'json_col_default' => [['json_col'], 'default', 'value' => 'fox jumps over dog'], - 'json_col_2_default' => [['json_col_2'], 'default', 'value' => []], 'numeric_col_double' => [['numeric_col'], 'double'], - 'json_col_def_n_default' => [['json_col_def_n'], 'default', 'value' => []], - 'json_col_def_n_2_default' => [['json_col_def_n_2'], 'default', 'value' => []], 'safe' => [['json_col_2', 'json_col_def_n', 'json_col_def_n_2'], 'safe'], - 'required' => [['name', 'str_col_def', 'json_col', 'json_col_2'], 'required'], ]; } } diff --git a/tests/specs/x_db_type/rules_and_more/maria/app/models/mariamodel/base/Newcolumn.php b/tests/specs/x_db_type/rules_and_more/maria/app/models/mariamodel/base/Newcolumn.php index 7bd80227..15e18ee2 100644 --- a/tests/specs/x_db_type/rules_and_more/maria/app/models/mariamodel/base/Newcolumn.php +++ b/tests/specs/x_db_type/rules_and_more/maria/app/models/mariamodel/base/Newcolumn.php @@ -30,14 +30,14 @@ public function rules() { return [ 'trim' => [['name', 'last_name', 'varchar_col'], 'trim'], + 'json_col_def_n_default' => [['json_col_def_n'], 'default', 'value' => []], + 'required' => [['name'], 'required'], 'name_string' => [['name'], 'string', 'max' => 255], 'last_name_string' => [['last_name'], 'string'], 'dec_col_double' => [['dec_col'], 'double'], 'varchar_col_string' => [['varchar_col'], 'string', 'max' => 5], 'numeric_col_double' => [['numeric_col'], 'double'], - 'json_col_def_n_default' => [['json_col_def_n'], 'default', 'value' => []], 'safe' => [['json_col', 'json_col_def_n'], 'safe'], - 'required' => [['name'], 'required'], ]; } } diff --git a/tests/specs/x_db_type/rules_and_more/maria/app/models/mariamodel/base/Pristine.php b/tests/specs/x_db_type/rules_and_more/maria/app/models/mariamodel/base/Pristine.php index b109a4e2..fb393cc0 100644 --- a/tests/specs/x_db_type/rules_and_more/maria/app/models/mariamodel/base/Pristine.php +++ b/tests/specs/x_db_type/rules_and_more/maria/app/models/mariamodel/base/Pristine.php @@ -34,10 +34,12 @@ public function rules() { return [ 'trim' => [['name', 'tag', 'new_col', 'col_9', 'col_10', 'col_11'], 'trim'], + 'tag_default' => [['tag'], 'default', 'value' => '4 leg'], + 'price_default' => [['price'], 'default', 'value' => 0], + 'required' => [['custom_id_col', 'name'], 'required'], 'custom_id_col_integer' => [['custom_id_col'], 'integer'], 'name_string' => [['name'], 'string'], 'tag_string' => [['tag'], 'string'], - 'tag_default' => [['tag'], 'default', 'value' => '4 leg'], 'new_col_string' => [['new_col'], 'string', 'max' => 17], 'col_5_double' => [['col_5'], 'double'], 'col_6_double' => [['col_6'], 'double'], @@ -46,9 +48,7 @@ public function rules() 'col_10_string' => [['col_10'], 'string', 'max' => 10], 'col_11_string' => [['col_11'], 'string'], 'price_double' => [['price'], 'double'], - 'price_default' => [['price'], 'default', 'value' => 0], 'safe' => [['col_8'], 'safe'], - 'required' => [['custom_id_col', 'name'], 'required'], ]; } } diff --git a/tests/specs/x_db_type/rules_and_more/mysql/app/models/base/Alldbdatatype.php b/tests/specs/x_db_type/rules_and_more/mysql/app/models/base/Alldbdatatype.php index 2a9a4052..a9e08518 100644 --- a/tests/specs/x_db_type/rules_and_more/mysql/app/models/base/Alldbdatatype.php +++ b/tests/specs/x_db_type/rules_and_more/mysql/app/models/base/Alldbdatatype.php @@ -66,6 +66,16 @@ public function rules() { return [ 'trim' => [['string_col', 'varchar_col', 'text_col', 'varchar_4_col', 'char_4_col', 'char_5_col', 'char_6_col', 'char_7_col', 'char_8_col', 'date_col', 'time_col', 'datetime_col', 'timestamp_col', 'year_col', 'text_def'], 'trim'], + 'char_8_col_default' => [['char_8_col'], 'default', 'value' => 'd'], + 'mi_default' => [['mi'], 'default', 'value' => 7], + 'json_col_def_default' => [['json_col_def'], 'default', 'value' => []], + 'json_col_def_2_default' => [['json_col_def_2'], 'default', 'value' => []], + 'blob_def_default' => [['blob_def'], 'default', 'value' => 'the blob'], + 'text_def_default' => [['text_def'], 'default', 'value' => 'the text'], + 'json_def_default' => [['json_def'], 'default', 'value' => [ + 'a' => 'b', + ]], + 'required' => [['char_6_col', 'char_7_col'], 'required'], 'string_col_string' => [['string_col'], 'string', 'max' => 255], 'varchar_col_string' => [['varchar_col'], 'string', 'max' => 132], 'text_col_string' => [['text_col'], 'string'], @@ -75,7 +85,6 @@ public function rules() 'char_6_col_string' => [['char_6_col'], 'string'], 'char_7_col_string' => [['char_7_col'], 'string', 'max' => 6], 'char_8_col_string' => [['char_8_col'], 'string'], - 'char_8_col_default' => [['char_8_col'], 'default', 'value' => 'd'], 'decimal_col_double' => [['decimal_col'], 'double'], 'bit_col_integer' => [['bit_col'], 'integer'], 'bit_2_integer' => [['bit_2'], 'integer'], @@ -86,7 +95,6 @@ public function rules() 'si_col_integer' => [['si_col'], 'integer'], 'si_col_2_integer' => [['si_col_2'], 'integer'], 'mi_integer' => [['mi'], 'integer'], - 'mi_default' => [['mi'], 'default', 'value' => 7], 'bi_integer' => [['bi'], 'integer'], 'int_col_integer' => [['int_col'], 'integer'], 'int_col_2_integer' => [['int_col_2'], 'integer'], @@ -103,16 +111,8 @@ public function rules() 'datetime_col_datetime' => [['datetime_col'], 'datetime', 'format' => 'php:Y-m-d H:i:s'], 'timestamp_col_string' => [['timestamp_col'], 'string'], 'year_col_string' => [['year_col'], 'string'], - 'json_col_def_default' => [['json_col_def'], 'default', 'value' => []], - 'json_col_def_2_default' => [['json_col_def_2'], 'default', 'value' => []], - 'blob_def_default' => [['blob_def'], 'default', 'value' => 'the blob'], 'text_def_string' => [['text_def'], 'string'], - 'text_def_default' => [['text_def'], 'default', 'value' => 'the text'], - 'json_def_default' => [['json_def'], 'default', 'value' => [ - 'a' => 'b', - ]], 'safe' => [['varbinary_col', 'blob_col', 'json_col', 'json_col_def', 'json_col_def_2', 'blob_def', 'json_def'], 'safe'], - 'required' => [['char_6_col', 'char_7_col'], 'required'], ]; } } diff --git a/tests/specs/x_db_type/rules_and_more/mysql/app/models/base/Editcolumn.php b/tests/specs/x_db_type/rules_and_more/mysql/app/models/base/Editcolumn.php index dabb711c..fe2d46c5 100644 --- a/tests/specs/x_db_type/rules_and_more/mysql/app/models/base/Editcolumn.php +++ b/tests/specs/x_db_type/rules_and_more/mysql/app/models/base/Editcolumn.php @@ -34,22 +34,22 @@ public function rules() { return [ 'trim' => [['name', 'tag', 'first_name', 'string_col', 'str_col_def', 'json_col'], 'trim'], - 'name_string' => [['name'], 'string', 'max' => 254], 'name_default' => [['name'], 'default', 'value' => 'Horse-2'], + 'dec_col_default' => [['dec_col'], 'default', 'value' => 3.14], + 'json_col_default' => [['json_col'], 'default', 'value' => 'fox jumps over dog'], + 'json_col_2_default' => [['json_col_2'], 'default', 'value' => []], + 'json_col_def_n_default' => [['json_col_def_n'], 'default', 'value' => []], + 'json_col_def_n_2_default' => [['json_col_def_n_2'], 'default', 'value' => []], + 'required' => [['name', 'str_col_def', 'json_col', 'json_col_2'], 'required'], + 'name_string' => [['name'], 'string', 'max' => 254], 'tag_string' => [['tag'], 'string'], 'first_name_string' => [['first_name'], 'string', 'max' => 255], 'string_col_string' => [['string_col'], 'string'], 'dec_col_double' => [['dec_col'], 'double'], - 'dec_col_default' => [['dec_col'], 'default', 'value' => 3.14], 'str_col_def_string' => [['str_col_def'], 'string', 'max' => 3], 'json_col_string' => [['json_col'], 'string'], - 'json_col_default' => [['json_col'], 'default', 'value' => 'fox jumps over dog'], - 'json_col_2_default' => [['json_col_2'], 'default', 'value' => []], 'numeric_col_double' => [['numeric_col'], 'double'], - 'json_col_def_n_default' => [['json_col_def_n'], 'default', 'value' => []], - 'json_col_def_n_2_default' => [['json_col_def_n_2'], 'default', 'value' => []], 'safe' => [['json_col_2', 'json_col_def_n', 'json_col_def_n_2'], 'safe'], - 'required' => [['name', 'str_col_def', 'json_col', 'json_col_2'], 'required'], ]; } } diff --git a/tests/specs/x_db_type/rules_and_more/mysql/app/models/base/Newcolumn.php b/tests/specs/x_db_type/rules_and_more/mysql/app/models/base/Newcolumn.php index 7420dadd..57669a6e 100644 --- a/tests/specs/x_db_type/rules_and_more/mysql/app/models/base/Newcolumn.php +++ b/tests/specs/x_db_type/rules_and_more/mysql/app/models/base/Newcolumn.php @@ -30,14 +30,14 @@ public function rules() { return [ 'trim' => [['name', 'last_name', 'varchar_col'], 'trim'], + 'json_col_def_n_default' => [['json_col_def_n'], 'default', 'value' => []], + 'required' => [['name'], 'required'], 'name_string' => [['name'], 'string', 'max' => 255], 'last_name_string' => [['last_name'], 'string'], 'dec_col_double' => [['dec_col'], 'double'], 'varchar_col_string' => [['varchar_col'], 'string', 'max' => 5], 'numeric_col_double' => [['numeric_col'], 'double'], - 'json_col_def_n_default' => [['json_col_def_n'], 'default', 'value' => []], 'safe' => [['json_col', 'json_col_def_n'], 'safe'], - 'required' => [['name'], 'required'], ]; } } diff --git a/tests/specs/x_db_type/rules_and_more/mysql/app/models/base/Pristine.php b/tests/specs/x_db_type/rules_and_more/mysql/app/models/base/Pristine.php index 3bdbade5..20d17d29 100644 --- a/tests/specs/x_db_type/rules_and_more/mysql/app/models/base/Pristine.php +++ b/tests/specs/x_db_type/rules_and_more/mysql/app/models/base/Pristine.php @@ -34,10 +34,12 @@ public function rules() { return [ 'trim' => [['name', 'tag', 'new_col', 'col_9', 'col_10', 'col_11'], 'trim'], + 'tag_default' => [['tag'], 'default', 'value' => '4 leg'], + 'price_default' => [['price'], 'default', 'value' => 0], + 'required' => [['custom_id_col', 'name'], 'required'], 'custom_id_col_integer' => [['custom_id_col'], 'integer'], 'name_string' => [['name'], 'string'], 'tag_string' => [['tag'], 'string'], - 'tag_default' => [['tag'], 'default', 'value' => '4 leg'], 'new_col_string' => [['new_col'], 'string', 'max' => 17], 'col_5_double' => [['col_5'], 'double'], 'col_6_double' => [['col_6'], 'double'], @@ -46,9 +48,7 @@ public function rules() 'col_10_string' => [['col_10'], 'string', 'max' => 10], 'col_11_string' => [['col_11'], 'string'], 'price_double' => [['price'], 'double'], - 'price_default' => [['price'], 'default', 'value' => 0], 'safe' => [['col_8'], 'safe'], - 'required' => [['custom_id_col', 'name'], 'required'], ]; } } diff --git a/tests/specs/x_db_type/rules_and_more/pgsql/app/models/pgsqlmodel/base/Alldbdatatype.php b/tests/specs/x_db_type/rules_and_more/pgsql/app/models/pgsqlmodel/base/Alldbdatatype.php index 3483ccea..c1cdc2f2 100644 --- a/tests/specs/x_db_type/rules_and_more/pgsql/app/models/pgsqlmodel/base/Alldbdatatype.php +++ b/tests/specs/x_db_type/rules_and_more/pgsql/app/models/pgsqlmodel/base/Alldbdatatype.php @@ -116,6 +116,18 @@ public function rules() { return [ 'trim' => [['string_col', 'varchar_col', 'text_col', 'varchar_4_col', 'varchar_5_col', 'char_4_col', 'char_5_col', 'char_6_col', 'char_7_col', 'char_8_col', 'date_col', 'time_col', 'time_col_2', 'time_col_3', 'time_col_4', 'timetz_col', 'timetz_col_2', 'timestamp_col', 'timestamp_col_2', 'timestamp_col_3', 'timestamp_col_4', 'timestamptz_col', 'timestamptz_col_2', 'date2', 'timestamp_col_z', 'box_col', 'character_col', 'character_n', 'character_varying', 'character_varying_n', 'text_def', 'cidr_col', 'circle_col', 'date_col_z', 'inet_col', 'interval_col', 'interval_col_2', 'interval_col_3', 'line_col', 'lseg_col', 'macaddr_col', 'money_col', 'path_col', 'point_col', 'polygon_col', 'tsquery_col', 'tsvector_col', 'txid_snapshot_col', 'uuid_col', 'xml_col'], 'trim'], + 'char_8_col_default' => [['char_8_col'], 'default', 'value' => 'd'], + 'json_col_def_default' => [['json_col_def'], 'default', 'value' => []], + 'json_col_def_2_default' => [['json_col_def_2'], 'default', 'value' => []], + 'bytea_def_default' => [['bytea_def'], 'default', 'value' => 'the bytea blob default'], + 'text_def_default' => [['text_def'], 'default', 'value' => 'the text'], + 'json_def_default' => [['json_def'], 'default', 'value' => [ + 'a' => 'b', + ]], + 'jsonb_def_default' => [['jsonb_def'], 'default', 'value' => [ + 'ba' => 'bb', + ]], + 'required' => [['char_6_col', 'char_7_col', 'smallserial_col', 'serial2_col', 'bigserial_col', 'bigserial_col_2', 'serial_col', 'serial4_col'], 'required'], 'string_col_string' => [['string_col'], 'string'], 'varchar_col_string' => [['varchar_col'], 'string'], 'text_col_string' => [['text_col'], 'string'], @@ -126,7 +138,6 @@ public function rules() 'char_6_col_string' => [['char_6_col'], 'string'], 'char_7_col_string' => [['char_7_col'], 'string', 'max' => 6], 'char_8_col_string' => [['char_8_col'], 'string'], - 'char_8_col_default' => [['char_8_col'], 'default', 'value' => 'd'], 'decimal_col_double' => [['decimal_col'], 'double'], 'bit_col_integer' => [['bit_col'], 'integer'], 'bit_2_integer' => [['bit_2'], 'integer'], @@ -177,17 +188,7 @@ public function rules() 'character_n_string' => [['character_n'], 'string', 'max' => 12], 'character_varying_string' => [['character_varying'], 'string'], 'character_varying_n_string' => [['character_varying_n'], 'string', 'max' => 12], - 'json_col_def_default' => [['json_col_def'], 'default', 'value' => []], - 'json_col_def_2_default' => [['json_col_def_2'], 'default', 'value' => []], - 'bytea_def_default' => [['bytea_def'], 'default', 'value' => 'the bytea blob default'], 'text_def_string' => [['text_def'], 'string'], - 'text_def_default' => [['text_def'], 'default', 'value' => 'the text'], - 'json_def_default' => [['json_def'], 'default', 'value' => [ - 'a' => 'b', - ]], - 'jsonb_def_default' => [['jsonb_def'], 'default', 'value' => [ - 'ba' => 'bb', - ]], 'cidr_col_string' => [['cidr_col'], 'string'], 'circle_col_string' => [['circle_col'], 'string'], 'date_col_z_date' => [['date_col_z'], 'date', 'format' => 'php:Y-m-d'], @@ -212,7 +213,6 @@ public function rules() 'uuid_col_string' => [['uuid_col'], 'string'], 'xml_col_string' => [['xml_col'], 'string'], 'safe' => [['text_col_array', 'bytea_col_2', 'json_col', 'jsonb_col', 'json_col_def', 'json_col_def_2', 'bytea_def', 'json_def', 'jsonb_def'], 'safe'], - 'required' => [['char_6_col', 'char_7_col', 'smallserial_col', 'serial2_col', 'bigserial_col', 'bigserial_col_2', 'serial_col', 'serial4_col'], 'required'], ]; } } diff --git a/tests/specs/x_db_type/rules_and_more/pgsql/app/models/pgsqlmodel/base/Editcolumn.php b/tests/specs/x_db_type/rules_and_more/pgsql/app/models/pgsqlmodel/base/Editcolumn.php index 03c469d6..4cb00fee 100644 --- a/tests/specs/x_db_type/rules_and_more/pgsql/app/models/pgsqlmodel/base/Editcolumn.php +++ b/tests/specs/x_db_type/rules_and_more/pgsql/app/models/pgsqlmodel/base/Editcolumn.php @@ -35,23 +35,22 @@ public function rules() { return [ 'trim' => [['name', 'tag', 'first_name', 'string_col', 'str_col_def', 'json_col'], 'trim'], + 'name_default' => [['name'], 'default', 'value' => 'Horse-2'], + 'dec_col_default' => [['dec_col'], 'default', 'value' => 3.14], + 'json_col_default' => [['json_col'], 'default', 'value' => 'fox jumps over dog'], + 'json_col_2_default' => [['json_col_2'], 'default', 'value' => []], + 'json_col_def_n_default' => [['json_col_def_n'], 'default', 'value' => []], + 'json_col_def_n_2_default' => [['json_col_def_n_2'], 'default', 'value' => []], 'required' => [['name', 'str_col_def', 'json_col', 'json_col_2', 'numeric_col'], 'required'], 'name_string' => [['name'], 'string', 'max' => 254], - 'name_default' => [['name'], 'default', 'value' => 'Horse-2'], 'tag_string' => [['tag'], 'string'], 'first_name_string' => [['first_name'], 'string'], 'string_col_string' => [['string_col'], 'string'], 'dec_col_double' => [['dec_col'], 'double'], - 'dec_col_default' => [['dec_col'], 'default', 'value' => 3.14], 'str_col_def_string' => [['str_col_def'], 'string'], 'json_col_string' => [['json_col'], 'string'], - 'json_col_default' => [['json_col'], 'default', 'value' => 'fox jumps over dog'], - 'json_col_2_default' => [['json_col_2'], 'default', 'value' => []], 'numeric_col_double' => [['numeric_col'], 'double'], - 'json_col_def_n_default' => [['json_col_def_n'], 'default', 'value' => []], - 'json_col_def_n_2_default' => [['json_col_def_n_2'], 'default', 'value' => []], 'safe' => [['json_col_2', 'json_col_def_n', 'json_col_def_n_2', 'text_col_array'], 'safe'], - 'required' => [['name', 'str_col_def', 'json_col', 'json_col_2'], 'required'], ]; } } diff --git a/tests/specs/x_db_type/rules_and_more/pgsql/app/models/pgsqlmodel/base/Newcolumn.php b/tests/specs/x_db_type/rules_and_more/pgsql/app/models/pgsqlmodel/base/Newcolumn.php index 397f59a0..d1cf823e 100644 --- a/tests/specs/x_db_type/rules_and_more/pgsql/app/models/pgsqlmodel/base/Newcolumn.php +++ b/tests/specs/x_db_type/rules_and_more/pgsql/app/models/pgsqlmodel/base/Newcolumn.php @@ -33,16 +33,16 @@ public function rules() { return [ 'trim' => [['name', 'first_name', 'last_name', 'varchar_col'], 'trim'], + 'json_col_def_n_default' => [['json_col_def_n'], 'default', 'value' => []], + 'json_col_def_n_2_default' => [['json_col_def_n_2'], 'default', 'value' => []], + 'required' => [['name'], 'required'], 'name_string' => [['name'], 'string'], 'first_name_string' => [['first_name'], 'string'], 'last_name_string' => [['last_name'], 'string'], 'dec_col_double' => [['dec_col'], 'double'], 'varchar_col_string' => [['varchar_col'], 'string'], 'numeric_col_double' => [['numeric_col'], 'double'], - 'json_col_def_n_default' => [['json_col_def_n'], 'default', 'value' => []], - 'json_col_def_n_2_default' => [['json_col_def_n_2'], 'default', 'value' => []], 'safe' => [['json_col', 'json_col_def_n', 'json_col_def_n_2', 'text_col_array'], 'safe'], - 'required' => [['name'], 'required'], ]; } } diff --git a/tests/specs/x_db_type/rules_and_more/pgsql/app/models/pgsqlmodel/base/Pristine.php b/tests/specs/x_db_type/rules_and_more/pgsql/app/models/pgsqlmodel/base/Pristine.php index a4cfc368..60cc8b35 100644 --- a/tests/specs/x_db_type/rules_and_more/pgsql/app/models/pgsqlmodel/base/Pristine.php +++ b/tests/specs/x_db_type/rules_and_more/pgsql/app/models/pgsqlmodel/base/Pristine.php @@ -34,10 +34,12 @@ public function rules() { return [ 'trim' => [['name', 'tag', 'new_col', 'col_9', 'col_10', 'col_11'], 'trim'], + 'tag_default' => [['tag'], 'default', 'value' => '4 leg'], + 'price_default' => [['price'], 'default', 'value' => 0], + 'required' => [['custom_id_col', 'name'], 'required'], 'custom_id_col_integer' => [['custom_id_col'], 'integer'], 'name_string' => [['name'], 'string'], 'tag_string' => [['tag'], 'string'], - 'tag_default' => [['tag'], 'default', 'value' => '4 leg'], 'new_col_string' => [['new_col'], 'string'], 'col_5_double' => [['col_5'], 'double'], 'col_6_double' => [['col_6'], 'double'], @@ -46,9 +48,7 @@ public function rules() 'col_10_string' => [['col_10'], 'string'], 'col_11_string' => [['col_11'], 'string'], 'price_double' => [['price'], 'double'], - 'price_default' => [['price'], 'default', 'value' => 0], 'safe' => [['col_8'], 'safe'], - 'required' => [['custom_id_col', 'name'], 'required'], ]; } } From 27145e866506cea520a5e47046ceedf221958122 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Thu, 20 Feb 2025 15:54:16 +0530 Subject: [PATCH 324/358] Fix failing tests 3 --- .../mysql/models/base/Invoice.php | 2 +- .../mysql/models/base/Product.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/specs/issue_fix/74_invalid_schema_reference_error/mysql/models/base/Invoice.php b/tests/specs/issue_fix/74_invalid_schema_reference_error/mysql/models/base/Invoice.php index d81c8ce3..e46064b8 100644 --- a/tests/specs/issue_fix/74_invalid_schema_reference_error/mysql/models/base/Invoice.php +++ b/tests/specs/issue_fix/74_invalid_schema_reference_error/mysql/models/base/Invoice.php @@ -23,13 +23,13 @@ public static function tableName() public function rules() { return [ + 'vat_rate_default' => [['vat_rate'], 'default', 'value' => 'standard'], 'required' => [['vat_rate'], 'required'], 'vat_rate_string' => [['vat_rate'], 'string'], 'vat_rate_in' => [['vat_rate'], 'in', 'range' => [ 'standard', 'none', ]], - 'vat_rate_default' => [['vat_rate'], 'default', 'value' => 'standard'], ]; } } diff --git a/tests/specs/issue_fix/74_invalid_schema_reference_error/mysql/models/base/Product.php b/tests/specs/issue_fix/74_invalid_schema_reference_error/mysql/models/base/Product.php index 184a6395..e83f3b9e 100644 --- a/tests/specs/issue_fix/74_invalid_schema_reference_error/mysql/models/base/Product.php +++ b/tests/specs/issue_fix/74_invalid_schema_reference_error/mysql/models/base/Product.php @@ -23,13 +23,13 @@ public static function tableName() public function rules() { return [ + 'vat_rate_default' => [['vat_rate'], 'default', 'value' => 'standard'], 'required' => [['vat_rate'], 'required'], 'vat_rate_string' => [['vat_rate'], 'string'], 'vat_rate_in' => [['vat_rate'], 'in', 'range' => [ 'standard', 'none', ]], - 'vat_rate_default' => [['vat_rate'], 'default', 'value' => 'standard'], ]; } } From b87be747fc3e367d07dcfb86c9f4fbf51a4b7e5a Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Thu, 20 Feb 2025 15:56:30 +0530 Subject: [PATCH 325/358] Cleanup --- src/lib/ValidationRulesBuilder.php | 5 ----- 1 file changed, 5 deletions(-) diff --git a/src/lib/ValidationRulesBuilder.php b/src/lib/ValidationRulesBuilder.php index b7d5ef47..33a89949 100644 --- a/src/lib/ValidationRulesBuilder.php +++ b/src/lib/ValidationRulesBuilder.php @@ -101,7 +101,6 @@ private function resolveAttributeRules(Attribute $attribute):void } if ($attribute->phpType === 'bool' || $attribute->phpType === 'boolean') { $this->rules[$attribute->columnName . '_boolean'] = new ValidationRule([$attribute->columnName], 'boolean'); -// $this->defaultRule($attribute); return; } @@ -119,13 +118,11 @@ private function resolveAttributeRules(Attribute $attribute):void } $this->rules[$key] = new ValidationRule([$attribute->columnName], $attribute->dbType, $params); -// $this->defaultRule($attribute); return; } if (in_array($attribute->phpType, ['int', 'integer', 'double', 'float']) && !$attribute->isReference()) { $this->addNumericRule($attribute); -// $this->defaultRule($attribute); return; } if ($attribute->phpType === 'string' && !$attribute->isReference()) { @@ -135,10 +132,8 @@ private function resolveAttributeRules(Attribute $attribute):void $key = $attribute->columnName . '_in'; $this->rules[$key] = new ValidationRule([$attribute->columnName], 'in', ['range' => $attribute->enumValues]); -// $this->defaultRule($attribute); // TODO remove return; } -// $this->defaultRule($attribute); $this->addRulesByAttributeName($attribute); } From 618ce3b53f445540c562e0032308f2ab9218d5e6 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Fri, 21 Feb 2025 14:44:21 +0530 Subject: [PATCH 326/358] C --- tests/unit/IssueFixTest.php | 1 - 1 file changed, 1 deletion(-) diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index 6d22d403..d0e2b514 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -1031,5 +1031,4 @@ public function test23ConsiderOpenapiExtensionXNoRelationAlsoInOtherPertinentPla // $this->checkFiles($actualFiles, $expectedFiles); // $this->runActualMigrations(); } - } From d9e47b0e33852da88dd07059dd10f2f7560ada84 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Fri, 21 Feb 2025 14:44:36 +0530 Subject: [PATCH 327/358] Format --- README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/README.md b/README.md index f7e1e789..7d1c4c8a 100644 --- a/README.md +++ b/README.md @@ -779,4 +779,3 @@ Professional support, consulting as well as software development services are av https://www.cebe.cc/en/contact Development of this library is sponsored by [cebe.:cloud: "Your Professional Deployment Platform"](https://cebe.cloud). - From f5e5c01e719a2f7f58f480b4525736845bf0f0dc Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Fri, 21 Feb 2025 16:24:50 +0530 Subject: [PATCH 328/358] Implementation in progress --- src/lib/AttributeResolver.php | 24 +++++++++---------- src/lib/openapi/ComponentSchema.php | 6 ++--- src/lib/openapi/PropertySchema.php | 14 +++++++++++ .../index.yaml | 1 + 4 files changed, 30 insertions(+), 15 deletions(-) diff --git a/src/lib/AttributeResolver.php b/src/lib/AttributeResolver.php index 09fe6b4f..e7bf4970 100644 --- a/src/lib/AttributeResolver.php +++ b/src/lib/AttributeResolver.php @@ -278,9 +278,9 @@ protected function resolveProperty( if ($property->isRefPointerToSelf()) { $relation->asSelfReference(); } - if (empty($property->getAttr(CustomSpecAttr::NO_RELATION))) { - $this->relations[$property->getName()] = $relation; - } +// if (empty($property->getAttr(CustomSpecAttr::NO_RELATION))) { + $this->relations[$property->getName()] = $relation; +// } if (!$property->isRefPointerToSelf()) { $this->addInverseRelation($relatedClassName, $attribute, $property, $fkProperty); } @@ -323,25 +323,25 @@ protected function resolveProperty( $fkProperty->getName(), '_id' )) { - if (empty($property->getAttr(CustomSpecAttr::NO_RELATION))) { - $this->relations[$property->getName()] = +// if (empty($property->getAttr(CustomSpecAttr::NO_RELATION))) { + $this->relations[$property->getName()] = Yii::createObject( AttributeRelation::class, [static::relationName($property->getName(), $property->fkColName), $relatedTableName, $relatedClassName] ) ->asHasMany([$fkProperty->getName() => $fkProperty->getName()])->asSelfReference(); - } +// } return; } $foreignPk = Inflector::camel2id($fkProperty->getName(), '_') . '_id'; - if (empty($property->getAttr(CustomSpecAttr::NO_RELATION))) { - $this->relations[$property->getName()] = +// if (empty($property->getAttr(CustomSpecAttr::NO_RELATION))) { + $this->relations[$property->getName()] = Yii::createObject( AttributeRelation::class, [static::relationName($property->getName(), $property->fkColName), $relatedTableName, $relatedClassName] ) ->asHasMany([$foreignPk => $this->componentSchema->getPkName()]); - } +// } return; } $relatedClassName = $property->getRefClassName(); @@ -355,15 +355,15 @@ protected function resolveProperty( return; } $attribute->setPhpType($relatedClassName . '[]'); - if (empty($property->getAttr(CustomSpecAttr::NO_RELATION))) { - $this->relations[$property->getName()] = +// if (empty($property->getAttr(CustomSpecAttr::NO_RELATION))) { + $this->relations[$property->getName()] = Yii::createObject( AttributeRelation::class, [static::relationName($property->getName(), $property->fkColName), $relatedTableName, $relatedClassName] ) ->asHasMany([Inflector::camel2id($this->schemaName, '_') . '_id' => $this->componentSchema->getPkName()]) ->setInverse(Inflector::variablize($this->schemaName)); - } +// } return; } if ($this->componentSchema->isNonDb() && $attribute->isReference()) { diff --git a/src/lib/openapi/ComponentSchema.php b/src/lib/openapi/ComponentSchema.php index 809f0958..9386bf2a 100644 --- a/src/lib/openapi/ComponentSchema.php +++ b/src/lib/openapi/ComponentSchema.php @@ -14,8 +14,6 @@ use cebe\yii2openapi\lib\SchemaToDatabase; use Generator; use Yii; -use yii\helpers\Inflector; -use yii\helpers\StringHelper; use function in_array; class ComponentSchema @@ -106,7 +104,9 @@ public function isRequiredProperty(string $propName):bool public function isNonDb():bool { - return isset($this->schema->{CustomSpecAttr::TABLE}) && $this->schema->{CustomSpecAttr::TABLE} === false; + return + isset($this->schema->{CustomSpecAttr::TABLE}) && + $this->schema->{CustomSpecAttr::TABLE} === false; } public function resolveTableName(string $schemaName):string diff --git a/src/lib/openapi/PropertySchema.php b/src/lib/openapi/PropertySchema.php index bc7296f6..52459e11 100644 --- a/src/lib/openapi/PropertySchema.php +++ b/src/lib/openapi/PropertySchema.php @@ -145,6 +145,10 @@ public function __construct(SpecObjectInterface $property, string $name, Compone $property = $this->property; } + if ($this->getAttr(CustomSpecAttr::NO_RELATION)) { + return; + } + if ($property instanceof Reference) { $this->initReference(); } elseif ( @@ -182,6 +186,10 @@ private function initReference():void if ($this->refSchema && $this->refSchema->isNonDb()) { $this->isNonDbReference = true; } + if ($this->getAttr(CustomSpecAttr::NO_RELATION)) { + $this->isReference = false; + $this->isNonDbReference = true; + } } /** @@ -191,6 +199,9 @@ private function initReference():void private function initItemsReference():void { $this->isItemsReference = true; + if ($this->getAttr(CustomSpecAttr::NO_RELATION)) { + $this->isItemsReference = false; + } $items = $this->property->items ?? null; if (!$items) { return; @@ -206,6 +217,9 @@ private function initItemsReference():void if ($this->refSchema && $this->refSchema->isNonDb()) { $this->isNonDbReference = true; } + if ($this->getAttr(CustomSpecAttr::NO_RELATION)) { + $this->isNonDbReference = true; + } } public function setName(string $name):void diff --git a/tests/specs/issue_fix/23_consider_openapi_extension_x_no_relation_also_in_other_pertinent_place/index.yaml b/tests/specs/issue_fix/23_consider_openapi_extension_x_no_relation_also_in_other_pertinent_place/index.yaml index 669f6239..b872617b 100644 --- a/tests/specs/issue_fix/23_consider_openapi_extension_x_no_relation_also_in_other_pertinent_place/index.yaml +++ b/tests/specs/issue_fix/23_consider_openapi_extension_x_no_relation_also_in_other_pertinent_place/index.yaml @@ -25,6 +25,7 @@ components: type: array x-no-relation: true items: + # type: string $ref: '#/components/schemas/Sample' Sample: From fe9b00a2d3c4e60eec8766b53a92ce90d48eb342 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Sat, 22 Feb 2025 16:56:52 +0530 Subject: [PATCH 329/358] Change logic --- src/lib/AttributeResolver.php | 8 -------- src/lib/openapi/PropertySchema.php | 13 ++----------- 2 files changed, 2 insertions(+), 19 deletions(-) diff --git a/src/lib/AttributeResolver.php b/src/lib/AttributeResolver.php index e7bf4970..421c3f0a 100644 --- a/src/lib/AttributeResolver.php +++ b/src/lib/AttributeResolver.php @@ -278,9 +278,7 @@ protected function resolveProperty( if ($property->isRefPointerToSelf()) { $relation->asSelfReference(); } -// if (empty($property->getAttr(CustomSpecAttr::NO_RELATION))) { $this->relations[$property->getName()] = $relation; -// } if (!$property->isRefPointerToSelf()) { $this->addInverseRelation($relatedClassName, $attribute, $property, $fkProperty); } @@ -323,25 +321,21 @@ protected function resolveProperty( $fkProperty->getName(), '_id' )) { -// if (empty($property->getAttr(CustomSpecAttr::NO_RELATION))) { $this->relations[$property->getName()] = Yii::createObject( AttributeRelation::class, [static::relationName($property->getName(), $property->fkColName), $relatedTableName, $relatedClassName] ) ->asHasMany([$fkProperty->getName() => $fkProperty->getName()])->asSelfReference(); -// } return; } $foreignPk = Inflector::camel2id($fkProperty->getName(), '_') . '_id'; -// if (empty($property->getAttr(CustomSpecAttr::NO_RELATION))) { $this->relations[$property->getName()] = Yii::createObject( AttributeRelation::class, [static::relationName($property->getName(), $property->fkColName), $relatedTableName, $relatedClassName] ) ->asHasMany([$foreignPk => $this->componentSchema->getPkName()]); -// } return; } $relatedClassName = $property->getRefClassName(); @@ -355,7 +349,6 @@ protected function resolveProperty( return; } $attribute->setPhpType($relatedClassName . '[]'); -// if (empty($property->getAttr(CustomSpecAttr::NO_RELATION))) { $this->relations[$property->getName()] = Yii::createObject( AttributeRelation::class, @@ -363,7 +356,6 @@ protected function resolveProperty( ) ->asHasMany([Inflector::camel2id($this->schemaName, '_') . '_id' => $this->componentSchema->getPkName()]) ->setInverse(Inflector::variablize($this->schemaName)); -// } return; } if ($this->componentSchema->isNonDb() && $attribute->isReference()) { diff --git a/src/lib/openapi/PropertySchema.php b/src/lib/openapi/PropertySchema.php index 52459e11..56d6df7a 100644 --- a/src/lib/openapi/PropertySchema.php +++ b/src/lib/openapi/PropertySchema.php @@ -145,6 +145,7 @@ public function __construct(SpecObjectInterface $property, string $name, Compone $property = $this->property; } + // don't go reference part if `x-no-relation` is true if ($this->getAttr(CustomSpecAttr::NO_RELATION)) { return; } @@ -186,10 +187,6 @@ private function initReference():void if ($this->refSchema && $this->refSchema->isNonDb()) { $this->isNonDbReference = true; } - if ($this->getAttr(CustomSpecAttr::NO_RELATION)) { - $this->isReference = false; - $this->isNonDbReference = true; - } } /** @@ -199,9 +196,6 @@ private function initReference():void private function initItemsReference():void { $this->isItemsReference = true; - if ($this->getAttr(CustomSpecAttr::NO_RELATION)) { - $this->isItemsReference = false; - } $items = $this->property->items ?? null; if (!$items) { return; @@ -217,9 +211,6 @@ private function initItemsReference():void if ($this->refSchema && $this->refSchema->isNonDb()) { $this->isNonDbReference = true; } - if ($this->getAttr(CustomSpecAttr::NO_RELATION)) { - $this->isNonDbReference = true; - } } public function setName(string $name):void @@ -511,7 +502,7 @@ public function guessDbType($forReference = false):string } return YiiDbSchema::TYPE_TEXT; case 'object': - case 'array': // TODO WIP Resume from here + case 'array': { return YiiDbSchema::TYPE_JSON; } From 15d588a8e05f6b7c9905c2365e09a3df996499c0 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Sat, 22 Feb 2025 16:58:42 +0530 Subject: [PATCH 330/358] Format --- src/lib/AttributeResolver.php | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/src/lib/AttributeResolver.php b/src/lib/AttributeResolver.php index 421c3f0a..c8f11b52 100644 --- a/src/lib/AttributeResolver.php +++ b/src/lib/AttributeResolver.php @@ -322,20 +322,20 @@ protected function resolveProperty( '_id' )) { $this->relations[$property->getName()] = - Yii::createObject( - AttributeRelation::class, - [static::relationName($property->getName(), $property->fkColName), $relatedTableName, $relatedClassName] - ) - ->asHasMany([$fkProperty->getName() => $fkProperty->getName()])->asSelfReference(); - return; - } - $foreignPk = Inflector::camel2id($fkProperty->getName(), '_') . '_id'; - $this->relations[$property->getName()] = Yii::createObject( AttributeRelation::class, [static::relationName($property->getName(), $property->fkColName), $relatedTableName, $relatedClassName] ) - ->asHasMany([$foreignPk => $this->componentSchema->getPkName()]); + ->asHasMany([$fkProperty->getName() => $fkProperty->getName()])->asSelfReference(); + return; + } + $foreignPk = Inflector::camel2id($fkProperty->getName(), '_') . '_id'; + $this->relations[$property->getName()] = + Yii::createObject( + AttributeRelation::class, + [static::relationName($property->getName(), $property->fkColName), $relatedTableName, $relatedClassName] + ) + ->asHasMany([$foreignPk => $this->componentSchema->getPkName()]); return; } $relatedClassName = $property->getRefClassName(); From 73cfcc44b0cfd11e94122e77f256cdcd66c5ae54 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Sat, 22 Feb 2025 16:59:16 +0530 Subject: [PATCH 331/358] Format 2 --- src/lib/AttributeResolver.php | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/lib/AttributeResolver.php b/src/lib/AttributeResolver.php index c8f11b52..cc41a6fb 100644 --- a/src/lib/AttributeResolver.php +++ b/src/lib/AttributeResolver.php @@ -350,12 +350,12 @@ protected function resolveProperty( } $attribute->setPhpType($relatedClassName . '[]'); $this->relations[$property->getName()] = - Yii::createObject( - AttributeRelation::class, - [static::relationName($property->getName(), $property->fkColName), $relatedTableName, $relatedClassName] - ) - ->asHasMany([Inflector::camel2id($this->schemaName, '_') . '_id' => $this->componentSchema->getPkName()]) - ->setInverse(Inflector::variablize($this->schemaName)); + Yii::createObject( + AttributeRelation::class, + [static::relationName($property->getName(), $property->fkColName), $relatedTableName, $relatedClassName] + ) + ->asHasMany([Inflector::camel2id($this->schemaName, '_') . '_id' => $this->componentSchema->getPkName()]) + ->setInverse(Inflector::variablize($this->schemaName)); return; } if ($this->componentSchema->isNonDb() && $attribute->isReference()) { From 2a36d5d9d05e756620986c1e3fe426ca775e8838 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Sat, 22 Feb 2025 17:25:54 +0530 Subject: [PATCH 332/358] Fix test --- .../m200000_000001_create_table_pets.php | 30 +++++++++---------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/mysql/migrations_mysql_db/m200000_000001_create_table_pets.php b/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/mysql/migrations_mysql_db/m200000_000001_create_table_pets.php index 01df98f3..3099e6fe 100644 --- a/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/mysql/migrations_mysql_db/m200000_000001_create_table_pets.php +++ b/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/mysql/migrations_mysql_db/m200000_000001_create_table_pets.php @@ -11,21 +11,21 @@ public function up() 'id' => $this->primaryKey(), 'name' => $this->text()->notNull(), 'age' => $this->integer()->null()->defaultValue(null), - 'tags' => $this->text()->null(), - 'tags_arbit' => $this->text()->null(), - 'number_arr' => $this->text()->null(), - 'number_arr_min_uniq' => $this->text()->null(), - 'int_arr' => $this->text()->null(), - 'int_arr_min_uniq' => $this->text()->null(), - 'bool_arr' => $this->text()->null(), - 'arr_arr_int' => $this->text()->null(), - 'arr_arr_str' => $this->text()->null(), - 'arr_arr_arr_str' => $this->text()->null(), - 'arr_of_obj' => $this->text()->null(), - 'user_ref_obj_arr' => $this->string()->null()->defaultValue(null), - 'one_of_arr' => $this->text()->null(), - 'one_of_arr_complex' => $this->text()->null(), - 'one_of_from_multi_ref_arr' => $this->text()->null(), + 'tags' => 'json NOT NULL', + 'tags_arbit' => 'json NOT NULL', + 'number_arr' => 'json NOT NULL', + 'number_arr_min_uniq' => 'json NOT NULL', + 'int_arr' => 'json NOT NULL', + 'int_arr_min_uniq' => 'json NOT NULL', + 'bool_arr' => 'json NOT NULL', + 'arr_arr_int' => 'json NOT NULL', + 'arr_arr_str' => 'json NOT NULL', + 'arr_arr_arr_str' => 'json NOT NULL', + 'arr_of_obj' => 'json NOT NULL', + 'user_ref_obj_arr' => 'json NOT NULL', + 'one_of_arr' => 'json NOT NULL', + 'one_of_arr_complex' => 'json NOT NULL', + 'one_of_from_multi_ref_arr' => 'json NOT NULL', ]); } From c19c71e205228e2f8c5cd3f1e600493eccb6a0e7 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Sat, 22 Feb 2025 17:26:23 +0530 Subject: [PATCH 333/358] Fix test 2 --- .../mysql/models/base/Pet.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/mysql/models/base/Pet.php b/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/mysql/models/base/Pet.php index 25498979..ae87e515 100644 --- a/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/mysql/models/base/Pet.php +++ b/tests/specs/issue_fix/20_consider_openapi_spec_examples_in_faker_code_generation/mysql/models/base/Pet.php @@ -23,7 +23,7 @@ * @property array $arr_arr_str * @property array $arr_arr_arr_str * @property array $arr_of_obj - * @property User[] $user_ref_obj_arr + * @property array $user_ref_obj_arr * @property array $one_of_arr * @property array $one_of_arr_complex * @property array $one_of_from_multi_ref_arr From 9f10d85a6ec4c9a77b4996025d3981caa32bc03a Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Tue, 25 Feb 2025 14:33:04 +0530 Subject: [PATCH 334/358] Refactor + complete the test --- src/lib/ValidationRulesBuilder.php | 5 +- .../index.yaml | 1 - .../m200000_000000_create_table_payments.php | 21 +++ .../m200000_000001_create_table_samples.php | 20 +++ .../mysql/models/BaseModelFaker.php | 144 ++++++++++++++++++ .../mysql/models/Payments.php | 10 ++ .../mysql/models/PaymentsFaker.php | 44 ++++++ .../mysql/models/Sample.php | 10 ++ .../mysql/models/SampleFaker.php | 41 +++++ .../mysql/models/base/Payments.php | 32 ++++ .../mysql/models/base/Sample.php | 30 ++++ tests/unit/IssueFixTest.php | 18 +-- 12 files changed, 361 insertions(+), 15 deletions(-) create mode 100644 tests/specs/issue_fix/23_consider_openapi_extension_x_no_relation_also_in_other_pertinent_place/mysql/migrations_mysql_db/m200000_000000_create_table_payments.php create mode 100644 tests/specs/issue_fix/23_consider_openapi_extension_x_no_relation_also_in_other_pertinent_place/mysql/migrations_mysql_db/m200000_000001_create_table_samples.php create mode 100644 tests/specs/issue_fix/23_consider_openapi_extension_x_no_relation_also_in_other_pertinent_place/mysql/models/BaseModelFaker.php create mode 100644 tests/specs/issue_fix/23_consider_openapi_extension_x_no_relation_also_in_other_pertinent_place/mysql/models/Payments.php create mode 100644 tests/specs/issue_fix/23_consider_openapi_extension_x_no_relation_also_in_other_pertinent_place/mysql/models/PaymentsFaker.php create mode 100644 tests/specs/issue_fix/23_consider_openapi_extension_x_no_relation_also_in_other_pertinent_place/mysql/models/Sample.php create mode 100644 tests/specs/issue_fix/23_consider_openapi_extension_x_no_relation_also_in_other_pertinent_place/mysql/models/SampleFaker.php create mode 100644 tests/specs/issue_fix/23_consider_openapi_extension_x_no_relation_also_in_other_pertinent_place/mysql/models/base/Payments.php create mode 100644 tests/specs/issue_fix/23_consider_openapi_extension_x_no_relation_also_in_other_pertinent_place/mysql/models/base/Sample.php diff --git a/src/lib/ValidationRulesBuilder.php b/src/lib/ValidationRulesBuilder.php index 33a89949..33347314 100644 --- a/src/lib/ValidationRulesBuilder.php +++ b/src/lib/ValidationRulesBuilder.php @@ -243,10 +243,7 @@ private function prepareTypeScope():void if ($attribute->isReadOnly()) { continue; } - // column/field/property with name `id` is considered as Primary Key by this library, and it is automatically handled by DB/Yii; so remove it from validation `rules()` - if (in_array($attribute->columnName, ['id', $this->model->pkName]) || - in_array($attribute->propertyName, ['id', $this->model->pkName]) - ) { + if ($this->isIdColumn($attribute)) { continue; } if (/*$attribute->defaultValue === null &&*/ $attribute->isRequired()) { diff --git a/tests/specs/issue_fix/23_consider_openapi_extension_x_no_relation_also_in_other_pertinent_place/index.yaml b/tests/specs/issue_fix/23_consider_openapi_extension_x_no_relation_also_in_other_pertinent_place/index.yaml index b872617b..669f6239 100644 --- a/tests/specs/issue_fix/23_consider_openapi_extension_x_no_relation_also_in_other_pertinent_place/index.yaml +++ b/tests/specs/issue_fix/23_consider_openapi_extension_x_no_relation_also_in_other_pertinent_place/index.yaml @@ -25,7 +25,6 @@ components: type: array x-no-relation: true items: - # type: string $ref: '#/components/schemas/Sample' Sample: diff --git a/tests/specs/issue_fix/23_consider_openapi_extension_x_no_relation_also_in_other_pertinent_place/mysql/migrations_mysql_db/m200000_000000_create_table_payments.php b/tests/specs/issue_fix/23_consider_openapi_extension_x_no_relation_also_in_other_pertinent_place/mysql/migrations_mysql_db/m200000_000000_create_table_payments.php new file mode 100644 index 00000000..5579f4e7 --- /dev/null +++ b/tests/specs/issue_fix/23_consider_openapi_extension_x_no_relation_also_in_other_pertinent_place/mysql/migrations_mysql_db/m200000_000000_create_table_payments.php @@ -0,0 +1,21 @@ +createTable('{{%payments}}', [ + 'id' => $this->primaryKey(), + 'currency' => $this->text()->null(), + 'samples' => 'json NOT NULL', + ]); + } + + public function down() + { + $this->dropTable('{{%payments}}'); + } +} diff --git a/tests/specs/issue_fix/23_consider_openapi_extension_x_no_relation_also_in_other_pertinent_place/mysql/migrations_mysql_db/m200000_000001_create_table_samples.php b/tests/specs/issue_fix/23_consider_openapi_extension_x_no_relation_also_in_other_pertinent_place/mysql/migrations_mysql_db/m200000_000001_create_table_samples.php new file mode 100644 index 00000000..b5b3a86c --- /dev/null +++ b/tests/specs/issue_fix/23_consider_openapi_extension_x_no_relation_also_in_other_pertinent_place/mysql/migrations_mysql_db/m200000_000001_create_table_samples.php @@ -0,0 +1,20 @@ +createTable('{{%samples}}', [ + 'id' => $this->primaryKey(), + 'message' => $this->text()->null(), + ]); + } + + public function down() + { + $this->dropTable('{{%samples}}'); + } +} diff --git a/tests/specs/issue_fix/23_consider_openapi_extension_x_no_relation_also_in_other_pertinent_place/mysql/models/BaseModelFaker.php b/tests/specs/issue_fix/23_consider_openapi_extension_x_no_relation_also_in_other_pertinent_place/mysql/models/BaseModelFaker.php new file mode 100644 index 00000000..c367fbb4 --- /dev/null +++ b/tests/specs/issue_fix/23_consider_openapi_extension_x_no_relation_also_in_other_pertinent_place/mysql/models/BaseModelFaker.php @@ -0,0 +1,144 @@ +faker = FakerFactory::create(str_replace('-', '_', \Yii::$app->language)); + $this->uniqueFaker = new UniqueGenerator($this->faker); + } + + abstract public function generateModel($attributes = []); + + public function getFaker():Generator + { + return $this->faker; + } + + public function getUniqueFaker():UniqueGenerator + { + return $this->uniqueFaker; + } + + public function setFaker(Generator $faker):void + { + $this->faker = $faker; + } + + public function setUniqueFaker(UniqueGenerator $faker):void + { + $this->uniqueFaker = $faker; + } + + /** + * Generate and return model + * @param array|callable $attributes + * @param UniqueGenerator|null $uniqueFaker + * @return \yii\db\ActiveRecord + * @example MyFaker::makeOne(['user_id' => 1, 'title' => 'foo']); + * @example MyFaker::makeOne( function($model, $faker) { + * $model->scenario = 'create'; + * $model->setAttributes(['user_id' => 1, 'title' => $faker->sentence]); + * return $model; + * }); + */ + public static function makeOne($attributes = [], ?UniqueGenerator $uniqueFaker = null) + { + $fakeBuilder = new static(); + if ($uniqueFaker !== null) { + $fakeBuilder->setUniqueFaker($uniqueFaker); + } + $model = $fakeBuilder->generateModel($attributes); + return $model; + } + + /** + * Generate, save and return model + * @param array|callable $attributes + * @param UniqueGenerator|null $uniqueFaker + * @return \yii\db\ActiveRecord + * @example MyFaker::saveOne(['user_id' => 1, 'title' => 'foo']); + * @example MyFaker::saveOne( function($model, $faker) { + * $model->scenario = 'create'; + * $model->setAttributes(['user_id' => 1, 'title' => $faker->sentence]); + * return $model; + * }); + */ + public static function saveOne($attributes = [], ?UniqueGenerator $uniqueFaker = null) + { + $model = static::makeOne($attributes, $uniqueFaker); + $model->save(); + return $model; + } + + /** + * Generate and return multiple models + * @param int $number + * @param array|callable $commonAttributes + * @return \yii\db\ActiveRecord[]|array + * @example TaskFaker::make(5, ['project_id'=>1, 'user_id' => 2]); + * @example TaskFaker::make(5, function($model, $faker, $uniqueFaker) { + * $model->setAttributes(['name' => $uniqueFaker->username, 'state'=>$faker->boolean(20)]); + * return $model; + * }); + */ + public static function make(int $number, $commonAttributes = [], ?UniqueGenerator $uniqueFaker = null):array + { + if ($number < 1) { + return []; + } + $fakeBuilder = new static(); + if ($uniqueFaker !== null) { + $fakeBuilder->setUniqueFaker($uniqueFaker); + } + return array_map(function () use ($commonAttributes, $fakeBuilder) { + $model = $fakeBuilder->generateModel($commonAttributes); + return $model; + }, range(0, $number -1)); + } + + /** + * Generate, save and return multiple models + * @param int $number + * @param array|callable $commonAttributes + * @return \yii\db\ActiveRecord[]|array + * @example TaskFaker::save(5, ['project_id'=>1, 'user_id' => 2]); + * @example TaskFaker::save(5, function($model, $faker, $uniqueFaker) { + * $model->setAttributes(['name' => $uniqueFaker->username, 'state'=>$faker->boolean(20)]); + * return $model; + * }); + */ + public static function save(int $number, $commonAttributes = [], ?UniqueGenerator $uniqueFaker = null):array + { + if ($number < 1) { + return []; + } + $fakeBuilder = new static(); + if ($uniqueFaker !== null) { + $fakeBuilder->setUniqueFaker($uniqueFaker); + } + return array_map(function () use ($commonAttributes, $fakeBuilder) { + $model = $fakeBuilder->generateModel($commonAttributes); + $model->save(); + return $model; + }, range(0, $number -1)); + } +} diff --git a/tests/specs/issue_fix/23_consider_openapi_extension_x_no_relation_also_in_other_pertinent_place/mysql/models/Payments.php b/tests/specs/issue_fix/23_consider_openapi_extension_x_no_relation_also_in_other_pertinent_place/mysql/models/Payments.php new file mode 100644 index 00000000..ea2262fe --- /dev/null +++ b/tests/specs/issue_fix/23_consider_openapi_extension_x_no_relation_also_in_other_pertinent_place/mysql/models/Payments.php @@ -0,0 +1,10 @@ +generateModels(['author_id' => 1]); + * $model = (new PostFaker())->generateModels(function($model, $faker, $uniqueFaker) { + * $model->scenario = 'create'; + * $model->author_id = 1; + * return $model; + * }); + **/ + public function generateModel($attributes = []) + { + $faker = $this->faker; + $uniqueFaker = $this->uniqueFaker; + $model = new Payments(); + //$model->id = $uniqueFaker->numberBetween(0, 1000000); + $model->currency = $faker->currencyCode; + $model->samples = array_map(function () use ($faker, $uniqueFaker) { + return (new SampleFaker)->generateModel()->attributes; + }, range(1, 4)); + if (!is_callable($attributes)) { + $model->setAttributes($attributes, false); + } else { + $model = $attributes($model, $faker, $uniqueFaker); + } + return $model; + } +} diff --git a/tests/specs/issue_fix/23_consider_openapi_extension_x_no_relation_also_in_other_pertinent_place/mysql/models/Sample.php b/tests/specs/issue_fix/23_consider_openapi_extension_x_no_relation_also_in_other_pertinent_place/mysql/models/Sample.php new file mode 100644 index 00000000..4e8b4547 --- /dev/null +++ b/tests/specs/issue_fix/23_consider_openapi_extension_x_no_relation_also_in_other_pertinent_place/mysql/models/Sample.php @@ -0,0 +1,10 @@ +generateModels(['author_id' => 1]); + * $model = (new PostFaker())->generateModels(function($model, $faker, $uniqueFaker) { + * $model->scenario = 'create'; + * $model->author_id = 1; + * return $model; + * }); + **/ + public function generateModel($attributes = []) + { + $faker = $this->faker; + $uniqueFaker = $this->uniqueFaker; + $model = new Sample(); + //$model->id = $uniqueFaker->numberBetween(0, 1000000); + $model->message = $faker->sentence; + if (!is_callable($attributes)) { + $model->setAttributes($attributes, false); + } else { + $model = $attributes($model, $faker, $uniqueFaker); + } + return $model; + } +} diff --git a/tests/specs/issue_fix/23_consider_openapi_extension_x_no_relation_also_in_other_pertinent_place/mysql/models/base/Payments.php b/tests/specs/issue_fix/23_consider_openapi_extension_x_no_relation_also_in_other_pertinent_place/mysql/models/base/Payments.php new file mode 100644 index 00000000..6e797741 --- /dev/null +++ b/tests/specs/issue_fix/23_consider_openapi_extension_x_no_relation_also_in_other_pertinent_place/mysql/models/base/Payments.php @@ -0,0 +1,32 @@ + [['currency'], 'trim'], + 'currency_string' => [['currency'], 'string'], + 'safe' => [['samples'], 'safe'], + ]; + } +} diff --git a/tests/specs/issue_fix/23_consider_openapi_extension_x_no_relation_also_in_other_pertinent_place/mysql/models/base/Sample.php b/tests/specs/issue_fix/23_consider_openapi_extension_x_no_relation_also_in_other_pertinent_place/mysql/models/base/Sample.php new file mode 100644 index 00000000..656ff1eb --- /dev/null +++ b/tests/specs/issue_fix/23_consider_openapi_extension_x_no_relation_also_in_other_pertinent_place/mysql/models/base/Sample.php @@ -0,0 +1,30 @@ + [['message'], 'trim'], + 'message_string' => [['message'], 'string'], + ]; + } +} diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index d0e2b514..9d20ae4d 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -1018,17 +1018,15 @@ public function test22BugRulesRequiredIsGeneratedBeforeDefault() // https://github.com/php-openapi/yii2-openapi/issues/23 public function test23ConsiderOpenapiExtensionXNoRelationAlsoInOtherPertinentPlace() { -// 23-consider-openapi-extension-x-no-relation-also-in-other-pertinent-place -// 23_consider_openapi_extension_x_no_relation_also_in_other_pertinent_place $testFile = Yii::getAlias("@specs/issue_fix/23_consider_openapi_extension_x_no_relation_also_in_other_pertinent_place/index.php"); $this->runGenerator($testFile); -// $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ -// 'recursive' => true, -// ]); -// $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/23_consider_openapi_extension_x_no_relation_also_in_other_pertinent_place/mysql"), [ -// 'recursive' => true, -// ]); -// $this->checkFiles($actualFiles, $expectedFiles); -// $this->runActualMigrations(); + $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ + 'recursive' => true, + ]); + $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/23_consider_openapi_extension_x_no_relation_also_in_other_pertinent_place/mysql"), [ + 'recursive' => true, + ]); + $this->checkFiles($actualFiles, $expectedFiles); + $this->runActualMigrations(); } } From b050abdc8afb3b33797fbba7a4e01f07222683ff Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Sat, 1 Mar 2025 11:33:16 +0530 Subject: [PATCH 335/358] Failing test --- .../index.php | 13 +++++++ .../index.yaml | 33 ++++++++++++++++ .../mysql/models/Address.php | 10 +++++ .../mysql/models/Human.php | 10 +++++ .../mysql/models/base/Address.php | 30 ++++++++++++++ .../mysql/models/base/Human.php | 39 +++++++++++++++++++ tests/unit/IssueFixTest.php | 14 +++++++ 7 files changed, 149 insertions(+) create mode 100644 tests/specs/issue_fix/88_in_case_of_updating_a_model_generator_creates_redundant_inverse_relations/index.php create mode 100644 tests/specs/issue_fix/88_in_case_of_updating_a_model_generator_creates_redundant_inverse_relations/index.yaml create mode 100644 tests/specs/issue_fix/88_in_case_of_updating_a_model_generator_creates_redundant_inverse_relations/mysql/models/Address.php create mode 100644 tests/specs/issue_fix/88_in_case_of_updating_a_model_generator_creates_redundant_inverse_relations/mysql/models/Human.php create mode 100644 tests/specs/issue_fix/88_in_case_of_updating_a_model_generator_creates_redundant_inverse_relations/mysql/models/base/Address.php create mode 100644 tests/specs/issue_fix/88_in_case_of_updating_a_model_generator_creates_redundant_inverse_relations/mysql/models/base/Human.php diff --git a/tests/specs/issue_fix/88_in_case_of_updating_a_model_generator_creates_redundant_inverse_relations/index.php b/tests/specs/issue_fix/88_in_case_of_updating_a_model_generator_creates_redundant_inverse_relations/index.php new file mode 100644 index 00000000..59eb14b0 --- /dev/null +++ b/tests/specs/issue_fix/88_in_case_of_updating_a_model_generator_creates_redundant_inverse_relations/index.php @@ -0,0 +1,13 @@ + '@specs/issue_fix/88_in_case_of_updating_a_model_generator_creates_redundant_inverse_relations/index.yaml', + 'generateUrls' => false, + 'generateModels' => true, + 'excludeModels' => [ + 'Error', + ], + 'generateControllers' => false, + 'generateMigrations' => false, + 'generateModelFaker' => false, // `generateModels` must be `true` in order to use `generateModelFaker` as `true` +]; diff --git a/tests/specs/issue_fix/88_in_case_of_updating_a_model_generator_creates_redundant_inverse_relations/index.yaml b/tests/specs/issue_fix/88_in_case_of_updating_a_model_generator_creates_redundant_inverse_relations/index.yaml new file mode 100644 index 00000000..2e5ac94f --- /dev/null +++ b/tests/specs/issue_fix/88_in_case_of_updating_a_model_generator_creates_redundant_inverse_relations/index.yaml @@ -0,0 +1,33 @@ +openapi: "3.0.0" + +info: + version: 1.0.0 + title: '#88' + +paths: + /: + get: + responses: + '200': + description: The response + +components: + schemas: + Address: + type: object + properties: + id: + type: integer + name: + type: string + Human: + type: object + properties: + id: + type: integer + name: + type: string + address: + $ref: '#/components/schemas/Address' + + diff --git a/tests/specs/issue_fix/88_in_case_of_updating_a_model_generator_creates_redundant_inverse_relations/mysql/models/Address.php b/tests/specs/issue_fix/88_in_case_of_updating_a_model_generator_creates_redundant_inverse_relations/mysql/models/Address.php new file mode 100644 index 00000000..abfd7d59 --- /dev/null +++ b/tests/specs/issue_fix/88_in_case_of_updating_a_model_generator_creates_redundant_inverse_relations/mysql/models/Address.php @@ -0,0 +1,10 @@ + [['name'], 'trim'], + 'name_string' => [['name'], 'string'], + ]; + } +} diff --git a/tests/specs/issue_fix/88_in_case_of_updating_a_model_generator_creates_redundant_inverse_relations/mysql/models/base/Human.php b/tests/specs/issue_fix/88_in_case_of_updating_a_model_generator_creates_redundant_inverse_relations/mysql/models/base/Human.php new file mode 100644 index 00000000..dadaa276 --- /dev/null +++ b/tests/specs/issue_fix/88_in_case_of_updating_a_model_generator_creates_redundant_inverse_relations/mysql/models/base/Human.php @@ -0,0 +1,39 @@ + [['name'], 'trim'], + 'name_string' => [['name'], 'string'], + 'address_id_integer' => [['address_id'], 'integer'], + 'address_id_exist' => [['address_id'], 'exist', 'targetRelation' => 'address'], + ]; + } + + public function getAddress() + { + return $this->hasOne(\app\models\Address::class, ['id' => 'address_id']); + } +} diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index ad3ff8fd..c4af6abf 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -1014,4 +1014,18 @@ public function test22BugRulesRequiredIsGeneratedBeforeDefault() ]); $this->checkFiles($actualFiles, $expectedFiles); } + + // https://github.com/php-openapi/yii2-openapi/issues/88 + public function test88InCaseOfUpdatingAModelGeneratorCreatesRedundantInverseRelations() + { + $testFile = Yii::getAlias("@specs/issue_fix/88_in_case_of_updating_a_model_generator_creates_redundant_inverse_relations/index.php"); + $this->runGenerator($testFile); + $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ + 'recursive' => true, + ]); + $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/88_in_case_of_updating_a_model_generator_creates_redundant_inverse_relations/mysql"), [ + 'recursive' => true, + ]); + $this->checkFiles($actualFiles, $expectedFiles); + } } From 45f3f9050b5a06c1f55f1db5032aaebb14475301 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Sat, 1 Mar 2025 11:33:30 +0530 Subject: [PATCH 336/358] Fix --- src/lib/AttributeResolver.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/lib/AttributeResolver.php b/src/lib/AttributeResolver.php index cc41a6fb..2f917bdd 100644 --- a/src/lib/AttributeResolver.php +++ b/src/lib/AttributeResolver.php @@ -279,7 +279,7 @@ protected function resolveProperty( $relation->asSelfReference(); } $this->relations[$property->getName()] = $relation; - if (!$property->isRefPointerToSelf()) { + if (!$property->isRefPointerToSelf() && $property->hasRefItems()) { $this->addInverseRelation($relatedClassName, $attribute, $property, $fkProperty); } } From e69fc04d55f2e88844483872c8c2eb7d7bef46b5 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Mon, 3 Mar 2025 15:50:32 +0530 Subject: [PATCH 337/358] Fix failing tests --- tests/specs/blog/models/base/Category.php | 5 ----- tests/specs/blog/models/base/Post.php | 5 ----- tests/specs/blog/models/base/User.php | 10 ---------- tests/specs/blog_v2/models/base/Category.php | 5 ----- tests/specs/blog_v2/models/base/Post.php | 5 ----- tests/specs/blog_v2/models/base/User.php | 10 ---------- .../fk_col_name/app/models/base/Delivery.php | 5 ----- tests/specs/fk_col_name/app/models/base/User.php | 5 ----- .../app/models/base/Delivery.php | 10 ---------- .../fk_col_name_index/app/models/base/User.php | 5 ----- .../maria/models/base/Mailing.php | 5 ----- .../app/models/base/Invoice.php | 5 ----- .../pgsql/models/base/Account.php | 5 ----- .../mysql/models/base/User.php | 15 --------------- .../mysql/models/base/User.php | 5 ----- .../mysql/models/base/Animal.php | 5 ----- .../mysql/models/base/Fruit.php | 5 ----- .../mysql/models/base/User.php | 10 ---------- .../app/models/base/Account.php | 15 --------------- tests/specs/petstore/models/base/Store.php | 5 ----- tests/specs/petstore_jsonapi/models/base/Pet.php | 5 ----- .../petstore_namespace/mymodels/base/Store.php | 5 ----- .../relations_in_faker/app/models/base/A123.php | 5 ----- .../app/models/base/Account.php | 5 ----- .../relations_in_faker/app/models/base/B123.php | 10 ---------- .../relations_in_faker/app/models/base/C123.php | 5 ----- .../relations_in_faker/app/models/base/D123.php | 5 ----- .../relations_in_faker/app/models/base/Domain.php | 5 ----- 28 files changed, 185 deletions(-) diff --git a/tests/specs/blog/models/base/Category.php b/tests/specs/blog/models/base/Category.php index 188ec03c..36e7887a 100644 --- a/tests/specs/blog/models/base/Category.php +++ b/tests/specs/blog/models/base/Category.php @@ -38,9 +38,4 @@ public function getPosts() { return $this->hasMany(\app\models\Post::class, ['category_id' => 'id'])->inverseOf('category'); } - - public function getPost() - { - return $this->hasOne(\app\models\Post::class, ['category_id' => 'id'])->inverseOf('category'); - } } diff --git a/tests/specs/blog/models/base/Post.php b/tests/specs/blog/models/base/Post.php index 633de3f4..80393b08 100644 --- a/tests/specs/blog/models/base/Post.php +++ b/tests/specs/blog/models/base/Post.php @@ -61,9 +61,4 @@ public function getComments() { return $this->hasMany(\app\models\Comment::class, ['post_id' => 'uid'])->inverseOf('post'); } - - public function getComment() - { - return $this->hasOne(\app\models\Comment::class, ['post_id' => 'uid'])->inverseOf('post'); - } } diff --git a/tests/specs/blog/models/base/User.php b/tests/specs/blog/models/base/User.php index dbd3a708..c0d73705 100644 --- a/tests/specs/blog/models/base/User.php +++ b/tests/specs/blog/models/base/User.php @@ -44,14 +44,4 @@ public function rules() 'email_unique' => [['email'], 'unique'], ]; } - - public function getPost() - { - return $this->hasOne(\app\models\Post::class, ['created_by_id' => 'id'])->inverseOf('created_by'); - } - - public function getComment2() - { - return $this->hasOne(\app\models\Comment::class, ['author_id' => 'id'])->inverseOf('author'); - } } diff --git a/tests/specs/blog_v2/models/base/Category.php b/tests/specs/blog_v2/models/base/Category.php index 4207f516..7744c88a 100644 --- a/tests/specs/blog_v2/models/base/Category.php +++ b/tests/specs/blog_v2/models/base/Category.php @@ -38,9 +38,4 @@ public function getPosts() { return $this->hasMany(\app\models\Post::class, ['category_id' => 'id'])->inverseOf('category'); } - - public function getPost() - { - return $this->hasOne(\app\models\Post::class, ['category_id' => 'id'])->inverseOf('category'); - } } diff --git a/tests/specs/blog_v2/models/base/Post.php b/tests/specs/blog_v2/models/base/Post.php index debc5008..1913f0c2 100644 --- a/tests/specs/blog_v2/models/base/Post.php +++ b/tests/specs/blog_v2/models/base/Post.php @@ -73,9 +73,4 @@ public function getTags() return $this->hasMany(\app\models\Tag::class, ['id' => 'tag_id']) ->viaTable('posts2tags', ['post_id' => 'id']); } - - public function getComment() - { - return $this->hasOne(\app\models\Comment::class, ['post_id' => 'id'])->inverseOf('post'); - } } diff --git a/tests/specs/blog_v2/models/base/User.php b/tests/specs/blog_v2/models/base/User.php index 45c5b4e0..7123c988 100644 --- a/tests/specs/blog_v2/models/base/User.php +++ b/tests/specs/blog_v2/models/base/User.php @@ -47,14 +47,4 @@ public function rules() 'email_unique' => [['email'], 'unique'], ]; } - - public function getPost() - { - return $this->hasOne(\app\models\Post::class, ['created_by_id' => 'id'])->inverseOf('created_by'); - } - - public function getComment2() - { - return $this->hasOne(\app\models\Comment::class, ['user_id' => 'id'])->inverseOf('user'); - } } diff --git a/tests/specs/fk_col_name/app/models/base/Delivery.php b/tests/specs/fk_col_name/app/models/base/Delivery.php index 75a64400..214c5278 100644 --- a/tests/specs/fk_col_name/app/models/base/Delivery.php +++ b/tests/specs/fk_col_name/app/models/base/Delivery.php @@ -27,9 +27,4 @@ public function rules() 'title_string' => [['title'], 'string'], ]; } - - public function getWebhook() - { - return $this->hasOne(\app\models\Webhook::class, ['redelivery_of' => 'id'])->inverseOf('redelivery_of'); - } } diff --git a/tests/specs/fk_col_name/app/models/base/User.php b/tests/specs/fk_col_name/app/models/base/User.php index ede2e7c0..9c127aeb 100644 --- a/tests/specs/fk_col_name/app/models/base/User.php +++ b/tests/specs/fk_col_name/app/models/base/User.php @@ -28,9 +28,4 @@ public function rules() 'name_string' => [['name'], 'string'], ]; } - - public function getWebhook() - { - return $this->hasOne(\app\models\Webhook::class, ['user_id' => 'id'])->inverseOf('user'); - } } diff --git a/tests/specs/fk_col_name_index/app/models/base/Delivery.php b/tests/specs/fk_col_name_index/app/models/base/Delivery.php index a17531d1..214c5278 100644 --- a/tests/specs/fk_col_name_index/app/models/base/Delivery.php +++ b/tests/specs/fk_col_name_index/app/models/base/Delivery.php @@ -27,14 +27,4 @@ public function rules() 'title_string' => [['title'], 'string'], ]; } - - public function getWebhook() - { - return $this->hasOne(\app\models\Webhook::class, ['redelivery_of' => 'id'])->inverseOf('redelivery_of'); - } - - public function getWebhook2() - { - return $this->hasOne(\app\models\Webhook::class, ['rd_abc_2' => 'id'])->inverseOf('rd2'); - } } diff --git a/tests/specs/fk_col_name_index/app/models/base/User.php b/tests/specs/fk_col_name_index/app/models/base/User.php index ede2e7c0..9c127aeb 100644 --- a/tests/specs/fk_col_name_index/app/models/base/User.php +++ b/tests/specs/fk_col_name_index/app/models/base/User.php @@ -28,9 +28,4 @@ public function rules() 'name_string' => [['name'], 'string'], ]; } - - public function getWebhook() - { - return $this->hasOne(\app\models\Webhook::class, ['user_id' => 'id'])->inverseOf('user'); - } } diff --git a/tests/specs/issue_fix/159_bug_giiapi_generated_rules_emailid/maria/models/base/Mailing.php b/tests/specs/issue_fix/159_bug_giiapi_generated_rules_emailid/maria/models/base/Mailing.php index 57bb103f..ff8629b5 100644 --- a/tests/specs/issue_fix/159_bug_giiapi_generated_rules_emailid/maria/models/base/Mailing.php +++ b/tests/specs/issue_fix/159_bug_giiapi_generated_rules_emailid/maria/models/base/Mailing.php @@ -30,9 +30,4 @@ public function rules() 'paymentMethodName_string' => [['paymentMethodName'], 'string'], ]; } - - public function getContact() - { - return $this->hasOne(\app\models\Contact::class, ['mailing_id' => 'id'])->inverseOf('mailing'); - } } diff --git a/tests/specs/issue_fix/162_bug_dollarref_with_x_faker/app/models/base/Invoice.php b/tests/specs/issue_fix/162_bug_dollarref_with_x_faker/app/models/base/Invoice.php index cf4c0f73..21bfa112 100644 --- a/tests/specs/issue_fix/162_bug_dollarref_with_x_faker/app/models/base/Invoice.php +++ b/tests/specs/issue_fix/162_bug_dollarref_with_x_faker/app/models/base/Invoice.php @@ -23,9 +23,4 @@ public function rules() { return []; } - - public function getOrder() - { - return $this->hasOne(\app\models\Order::class, ['invoice_id' => 'id'])->inverseOf('invoice'); - } } diff --git a/tests/specs/issue_fix/175_bug_allof_with_multiple_dollarrefs/pgsql/models/base/Account.php b/tests/specs/issue_fix/175_bug_allof_with_multiple_dollarrefs/pgsql/models/base/Account.php index cd597631..e776fe40 100644 --- a/tests/specs/issue_fix/175_bug_allof_with_multiple_dollarrefs/pgsql/models/base/Account.php +++ b/tests/specs/issue_fix/175_bug_allof_with_multiple_dollarrefs/pgsql/models/base/Account.php @@ -30,9 +30,4 @@ public function rules() 'paymentMethodName_string' => [['paymentMethodName'], 'string'], ]; } - - public function getContact() - { - return $this->hasOne(\app\models\Contact::class, ['account_id' => 'id'])->inverseOf('account'); - } } diff --git a/tests/specs/issue_fix/25_generate_inverse_relations/mysql/models/base/User.php b/tests/specs/issue_fix/25_generate_inverse_relations/mysql/models/base/User.php index 7e26bb25..0240e1e5 100644 --- a/tests/specs/issue_fix/25_generate_inverse_relations/mysql/models/base/User.php +++ b/tests/specs/issue_fix/25_generate_inverse_relations/mysql/models/base/User.php @@ -34,19 +34,4 @@ public function getAccounts() { return $this->hasMany(\app\models\Account::class, ['user_id' => 'id'])->inverseOf('user'); } - - public function getAccount() - { - return $this->hasOne(\app\models\Account::class, ['user_id' => 'id'])->inverseOf('user'); - } - - public function getAccount2() - { - return $this->hasOne(\app\models\Account::class, ['user2_id' => 'id'])->inverseOf('user2'); - } - - public function getAccount3() - { - return $this->hasOne(\app\models\Account::class, ['user3' => 'id'])->inverseOf('user3'); - } } diff --git a/tests/specs/issue_fix/29_extension_fk_column_name_cause_error_in_case_of_column_name_without_underscore/mysql/models/base/User.php b/tests/specs/issue_fix/29_extension_fk_column_name_cause_error_in_case_of_column_name_without_underscore/mysql/models/base/User.php index 390d8bdb..bce4e105 100644 --- a/tests/specs/issue_fix/29_extension_fk_column_name_cause_error_in_case_of_column_name_without_underscore/mysql/models/base/User.php +++ b/tests/specs/issue_fix/29_extension_fk_column_name_cause_error_in_case_of_column_name_without_underscore/mysql/models/base/User.php @@ -27,9 +27,4 @@ public function rules() 'name_string' => [['name'], 'string'], ]; } - - public function getPost() - { - return $this->hasOne(\app\models\Post::class, ['user' => 'id'])->inverseOf('user'); - } } diff --git a/tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql/models/base/Animal.php b/tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql/models/base/Animal.php index 81e157ac..a99b34da 100644 --- a/tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql/models/base/Animal.php +++ b/tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql/models/base/Animal.php @@ -27,9 +27,4 @@ public function rules() 'name_string' => [['name'], 'string'], ]; } - - public function getInvoice() - { - return $this->hasOne(\app\models\Invoice::class, ['animal_id' => 'id'])->inverseOf('animal'); - } } diff --git a/tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql/models/base/Fruit.php b/tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql/models/base/Fruit.php index d56f106c..ccdbe894 100644 --- a/tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql/models/base/Fruit.php +++ b/tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql/models/base/Fruit.php @@ -27,9 +27,4 @@ public function rules() 'name_string' => [['name'], 'string'], ]; } - - public function getInvoice() - { - return $this->hasOne(\app\models\Invoice::class, ['fruit_id' => 'id'])->inverseOf('fruit'); - } } diff --git a/tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql/models/base/User.php b/tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql/models/base/User.php index a6ce6e79..bce4e105 100644 --- a/tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql/models/base/User.php +++ b/tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql/models/base/User.php @@ -27,14 +27,4 @@ public function rules() 'name_string' => [['name'], 'string'], ]; } - - public function getInvoice() - { - return $this->hasOne(\app\models\Invoice::class, ['user_id' => 'id'])->inverseOf('user'); - } - - public function getInvoice2() - { - return $this->hasOne(\app\models\Invoice::class, ['user_2_id' => 'id'])->inverseOf('user_2'); - } } diff --git a/tests/specs/issue_fix/model_name_more_than_once_in_faker_148/app/models/base/Account.php b/tests/specs/issue_fix/model_name_more_than_once_in_faker_148/app/models/base/Account.php index f875eadd..b90b713b 100644 --- a/tests/specs/issue_fix/model_name_more_than_once_in_faker_148/app/models/base/Account.php +++ b/tests/specs/issue_fix/model_name_more_than_once_in_faker_148/app/models/base/Account.php @@ -28,19 +28,4 @@ public function rules() 'name_string' => [['name'], 'string', 'max' => 40], ]; } - - public function getE123() - { - return $this->hasOne(\app\models\E123::class, ['account_id' => 'id'])->inverseOf('account'); - } - - public function getE1232() - { - return $this->hasOne(\app\models\E123::class, ['account_2_id' => 'id'])->inverseOf('account_2'); - } - - public function getE1233() - { - return $this->hasOne(\app\models\E123::class, ['account_3_id' => 'id'])->inverseOf('account_3'); - } } diff --git a/tests/specs/petstore/models/base/Store.php b/tests/specs/petstore/models/base/Store.php index 9589d1b8..b450803e 100644 --- a/tests/specs/petstore/models/base/Store.php +++ b/tests/specs/petstore/models/base/Store.php @@ -28,9 +28,4 @@ public function rules() 'name_string' => [['name'], 'string'], ]; } - - public function getPet() - { - return $this->hasOne(\app\models\Pet::class, ['store_id' => 'id'])->inverseOf('store'); - } } diff --git a/tests/specs/petstore_jsonapi/models/base/Pet.php b/tests/specs/petstore_jsonapi/models/base/Pet.php index 6444cf28..cf242429 100644 --- a/tests/specs/petstore_jsonapi/models/base/Pet.php +++ b/tests/specs/petstore_jsonapi/models/base/Pet.php @@ -63,9 +63,4 @@ public function getDuplicates() { return $this->hasMany(\app\models\Pet::class, ['tag' => 'tag']); } - - public function getPetStatistic() - { - return $this->hasOne(\app\models\PetStatistic::class, ['parentPet_id' => 'id'])->inverseOf('parentPet'); - } } diff --git a/tests/specs/petstore_namespace/mymodels/base/Store.php b/tests/specs/petstore_namespace/mymodels/base/Store.php index 24d0f4e4..8ae6c907 100644 --- a/tests/specs/petstore_namespace/mymodels/base/Store.php +++ b/tests/specs/petstore_namespace/mymodels/base/Store.php @@ -28,9 +28,4 @@ public function rules() 'name_string' => [['name'], 'string'], ]; } - - public function getPet() - { - return $this->hasOne(\app\mymodels\Pet::class, ['store_id' => 'id'])->inverseOf('store'); - } } diff --git a/tests/specs/relations_in_faker/app/models/base/A123.php b/tests/specs/relations_in_faker/app/models/base/A123.php index 0c733222..fb8681d6 100644 --- a/tests/specs/relations_in_faker/app/models/base/A123.php +++ b/tests/specs/relations_in_faker/app/models/base/A123.php @@ -36,9 +36,4 @@ public function getB123() { return $this->hasOne(\app\models\B123::class, ['id' => 'b123_id']); } - - public function getRouting() - { - return $this->hasOne(\app\models\Routing::class, ['a123_id' => 'id'])->inverseOf('a123'); - } } diff --git a/tests/specs/relations_in_faker/app/models/base/Account.php b/tests/specs/relations_in_faker/app/models/base/Account.php index e1198a95..b90b713b 100644 --- a/tests/specs/relations_in_faker/app/models/base/Account.php +++ b/tests/specs/relations_in_faker/app/models/base/Account.php @@ -28,9 +28,4 @@ public function rules() 'name_string' => [['name'], 'string', 'max' => 40], ]; } - - public function getDomain() - { - return $this->hasOne(\app\models\Domain::class, ['account_id' => 'id'])->inverseOf('account'); - } } diff --git a/tests/specs/relations_in_faker/app/models/base/B123.php b/tests/specs/relations_in_faker/app/models/base/B123.php index 7ad4eb77..9fee3543 100644 --- a/tests/specs/relations_in_faker/app/models/base/B123.php +++ b/tests/specs/relations_in_faker/app/models/base/B123.php @@ -36,14 +36,4 @@ public function getC123() { return $this->hasOne(\app\models\C123::class, ['id' => 'c123_id']); } - - public function getA123() - { - return $this->hasOne(\app\models\A123::class, ['b123_id' => 'id'])->inverseOf('b123'); - } - - public function getE1232() - { - return $this->hasOne(\app\models\E123::class, ['b123_id' => 'id'])->inverseOf('b123'); - } } diff --git a/tests/specs/relations_in_faker/app/models/base/C123.php b/tests/specs/relations_in_faker/app/models/base/C123.php index 6c5677dd..611526d8 100644 --- a/tests/specs/relations_in_faker/app/models/base/C123.php +++ b/tests/specs/relations_in_faker/app/models/base/C123.php @@ -27,9 +27,4 @@ public function rules() 'name_string' => [['name'], 'string'], ]; } - - public function getB123() - { - return $this->hasOne(\app\models\B123::class, ['c123_id' => 'id'])->inverseOf('c123'); - } } diff --git a/tests/specs/relations_in_faker/app/models/base/D123.php b/tests/specs/relations_in_faker/app/models/base/D123.php index 80a5017d..c45d7214 100644 --- a/tests/specs/relations_in_faker/app/models/base/D123.php +++ b/tests/specs/relations_in_faker/app/models/base/D123.php @@ -27,9 +27,4 @@ public function rules() 'name_string' => [['name'], 'string'], ]; } - - public function getRouting() - { - return $this->hasOne(\app\models\Routing::class, ['d123_id' => 'id'])->inverseOf('d123'); - } } diff --git a/tests/specs/relations_in_faker/app/models/base/Domain.php b/tests/specs/relations_in_faker/app/models/base/Domain.php index df6e0822..3c5ca1b1 100644 --- a/tests/specs/relations_in_faker/app/models/base/Domain.php +++ b/tests/specs/relations_in_faker/app/models/base/Domain.php @@ -44,9 +44,4 @@ public function getRoutings() { return $this->hasMany(\app\models\Routing::class, ['domain_id' => 'id'])->inverseOf('domain'); } - - public function getRouting() - { - return $this->hasOne(\app\models\Routing::class, ['domain_id' => 'id'])->inverseOf('domain'); - } } From 779c7cd398297489e22450e8d1367ecf5a513922 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Mon, 3 Mar 2025 15:59:16 +0530 Subject: [PATCH 338/358] Create PR --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index f68df469..4cc1d72a 100644 --- a/README.md +++ b/README.md @@ -779,3 +779,4 @@ Professional support, consulting as well as software development services are av https://www.cebe.cc/en/contact Development of this library is sponsored by [cebe.:cloud: "Your Professional Deployment Platform"](https://cebe.cloud). + From 7bc40e2e26033e40691bdb7e31d0eb226856a517 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Mon, 3 Mar 2025 16:01:35 +0530 Subject: [PATCH 339/358] Undo --- README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/README.md b/README.md index 4cc1d72a..f68df469 100644 --- a/README.md +++ b/README.md @@ -779,4 +779,3 @@ Professional support, consulting as well as software development services are av https://www.cebe.cc/en/contact Development of this library is sponsored by [cebe.:cloud: "Your Professional Deployment Platform"](https://cebe.cloud). - From ccbb320e0b4422136288f49270ad08be5ec3c6de Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Mon, 3 Mar 2025 17:49:48 +0530 Subject: [PATCH 340/358] Fix --- src/lib/openapi/PropertySchema.php | 8 ++-- .../Product.json | 22 +++++++++++ .../index.json | 39 +++++++++++++++++++ .../index.php | 13 +++++++ tests/unit/IssueFixTest.php | 15 +++++++ 5 files changed, 94 insertions(+), 3 deletions(-) create mode 100644 tests/specs/issue_fix/87_implement_for_json_in_is_ref_pointer_to_schema/Product.json create mode 100644 tests/specs/issue_fix/87_implement_for_json_in_is_ref_pointer_to_schema/index.json create mode 100644 tests/specs/issue_fix/87_implement_for_json_in_is_ref_pointer_to_schema/index.php diff --git a/src/lib/openapi/PropertySchema.php b/src/lib/openapi/PropertySchema.php index eade252e..e75f368b 100644 --- a/src/lib/openapi/PropertySchema.php +++ b/src/lib/openapi/PropertySchema.php @@ -268,8 +268,10 @@ public function getSelfTargetProperty():?PropertySchema public function isRefPointerToSchema():bool { return $this->refPointer && - ((strpos($this->refPointer, self::REFERENCE_PATH) === 0) || - (str_ends_with($this->uri, '.yml')) || (str_ends_with($this->uri, '.yaml'))); + ( + (strpos($this->refPointer, self::REFERENCE_PATH) === 0) || + (str_ends_with($this->uri, '.yml')) || (str_ends_with($this->uri, '.yaml')) || (str_ends_with($this->uri, '.json')) + ); } public function isRefPointerToSelf():bool @@ -305,7 +307,7 @@ public function getRefSchemaName():string $pattern = strpos($this->refPointer, '/properties/') !== false ? '~^'.self::REFERENCE_PATH.'(?.+)/properties/(?.+)$~' : '~^'.self::REFERENCE_PATH.'(?.+)$~'; - $separateFilePattern = '/((\.\/)*)(?.+)(\.)(yml|yaml)(.*)/'; # https://github.com/php-openapi/yii2-openapi/issues/74 + $separateFilePattern = '/((\.\/)*)(?.+)(\.)(yml|yaml|json)(.*)/'; # https://github.com/php-openapi/yii2-openapi/issues/74 if (!\preg_match($pattern, $this->refPointer, $matches)) { if (!\preg_match($separateFilePattern, $this->uri, $separateFilePatternMatches)) { throw new InvalidDefinitionException('Invalid schema reference'); diff --git a/tests/specs/issue_fix/87_implement_for_json_in_is_ref_pointer_to_schema/Product.json b/tests/specs/issue_fix/87_implement_for_json_in_is_ref_pointer_to_schema/Product.json new file mode 100644 index 00000000..91514ab4 --- /dev/null +++ b/tests/specs/issue_fix/87_implement_for_json_in_is_ref_pointer_to_schema/Product.json @@ -0,0 +1,22 @@ +{ + "title": "Product", + "x-table": "products", + "type": "object", + "required": [ + "id", + "vat_rate" + ], + "properties": { + "id": { + "type": "integer" + }, + "vat_rate": { + "type": "string", + "enum": [ + "standard", + "none" + ], + "default": "standard" + } + } +} \ No newline at end of file diff --git a/tests/specs/issue_fix/87_implement_for_json_in_is_ref_pointer_to_schema/index.json b/tests/specs/issue_fix/87_implement_for_json_in_is_ref_pointer_to_schema/index.json new file mode 100644 index 00000000..a879d24c --- /dev/null +++ b/tests/specs/issue_fix/87_implement_for_json_in_is_ref_pointer_to_schema/index.json @@ -0,0 +1,39 @@ +{ + "openapi": "3.0.0", + "info": { + "version": "1.0.0", + "title": "\\#87" + }, + "paths": { + "/": { + "get": { + "responses": { + "200": { + "description": "The information" + } + } + } + } + }, + "components": { + "schemas": { + "Invoice": { + "type": "object", + "required": [ + "vat_rate" + ], + "properties": { + "id": { + "type": "integer" + }, + "vat_rate": { + "$ref": "./Product.json#/properties/vat_rate" + } + } + }, + "Product": { + "$ref": "./Product.json" + } + } + } +} \ No newline at end of file diff --git a/tests/specs/issue_fix/87_implement_for_json_in_is_ref_pointer_to_schema/index.php b/tests/specs/issue_fix/87_implement_for_json_in_is_ref_pointer_to_schema/index.php new file mode 100644 index 00000000..0fd4dc27 --- /dev/null +++ b/tests/specs/issue_fix/87_implement_for_json_in_is_ref_pointer_to_schema/index.php @@ -0,0 +1,13 @@ + '@specs/issue_fix/87_implement_for_json_in_is_ref_pointer_to_schema/index.json', + 'generateUrls' => false, + 'generateModels' => true, + 'excludeModels' => [ + 'Error', + ], + 'generateControllers' => false, + 'generateMigrations' => true, + 'generateModelFaker' => true, +]; diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index ad3ff8fd..8f015934 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -1014,4 +1014,19 @@ public function test22BugRulesRequiredIsGeneratedBeforeDefault() ]); $this->checkFiles($actualFiles, $expectedFiles); } + + // https://github.com/php-openapi/yii2-openapi/issues/87 + public function test87ImplementForJsonInIsrefpointertoschema() + { + $testFile = Yii::getAlias("@specs/issue_fix/87_implement_for_json_in_is_ref_pointer_to_schema/index.php"); + $this->runGenerator($testFile); + $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ + 'recursive' => true, + ]); + $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/74_invalid_schema_reference_error/mysql"), [ + 'recursive' => true, + ]); + $this->checkFiles($actualFiles, $expectedFiles); + $this->runActualMigrations(); + } } From d88bdd3a78dff231a204ff999081857fe8d708d2 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Mon, 3 Mar 2025 17:52:55 +0530 Subject: [PATCH 341/358] Add comment --- tests/unit/IssueFixTest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index 8f015934..87b5962e 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -1023,7 +1023,7 @@ public function test87ImplementForJsonInIsrefpointertoschema() $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ 'recursive' => true, ]); - $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/74_invalid_schema_reference_error/mysql"), [ + $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/74_invalid_schema_reference_error/mysql"), [ # this is intentional 'recursive' => true, ]); $this->checkFiles($actualFiles, $expectedFiles); From ab6629bcfaa34d81d9fe47b6829b1736058c443a Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Mon, 3 Mar 2025 18:14:15 +0530 Subject: [PATCH 342/358] Create PR --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index f68df469..4cc1d72a 100644 --- a/README.md +++ b/README.md @@ -779,3 +779,4 @@ Professional support, consulting as well as software development services are av https://www.cebe.cc/en/contact Development of this library is sponsored by [cebe.:cloud: "Your Professional Deployment Platform"](https://cebe.cloud). + From 207228b8b7e8bdb60ff171869ea73555d7afcbbe Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Mon, 3 Mar 2025 18:23:26 +0530 Subject: [PATCH 343/358] Add test stub --- README.md | 1 - .../index.php | 13 ++++++++++ .../index.yaml | 26 +++++++++++++++++++ tests/unit/IssueFixTest.php | 14 ++++++++++ 4 files changed, 53 insertions(+), 1 deletion(-) create mode 100644 tests/specs/issue_fix/90_implement_belongs_to_relations_in_models/index.php create mode 100644 tests/specs/issue_fix/90_implement_belongs_to_relations_in_models/index.yaml diff --git a/README.md b/README.md index 4cc1d72a..f68df469 100644 --- a/README.md +++ b/README.md @@ -779,4 +779,3 @@ Professional support, consulting as well as software development services are av https://www.cebe.cc/en/contact Development of this library is sponsored by [cebe.:cloud: "Your Professional Deployment Platform"](https://cebe.cloud). - diff --git a/tests/specs/issue_fix/90_implement_belongs_to_relations_in_models/index.php b/tests/specs/issue_fix/90_implement_belongs_to_relations_in_models/index.php new file mode 100644 index 00000000..2c6dfb9b --- /dev/null +++ b/tests/specs/issue_fix/90_implement_belongs_to_relations_in_models/index.php @@ -0,0 +1,13 @@ + '@specs/issue_fix/90_implement_belongs_to_relations_in_models/index.yaml', + 'generateUrls' => false, + 'generateModels' => true, + 'excludeModels' => [ + 'Error', + ], + 'generateControllers' => false, + 'generateMigrations' => false, + 'generateModelFaker' => false, // `generateModels` must be `true` in order to use `generateModelFaker` as `true` +]; diff --git a/tests/specs/issue_fix/90_implement_belongs_to_relations_in_models/index.yaml b/tests/specs/issue_fix/90_implement_belongs_to_relations_in_models/index.yaml new file mode 100644 index 00000000..b62591f0 --- /dev/null +++ b/tests/specs/issue_fix/90_implement_belongs_to_relations_in_models/index.yaml @@ -0,0 +1,26 @@ +openapi: "3.0.0" +info: + version: 1.0.0 + title: \#90 +paths: + /: + get: + responses: + '200': + description: The information + +components: + schemas: + User: + type: object + properties: + id: + type: integer + + Address: + type: object + properties: + id: + type: integer + user: + $ref: '#/components/schemas/User' diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index ad3ff8fd..371c0657 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -1014,4 +1014,18 @@ public function test22BugRulesRequiredIsGeneratedBeforeDefault() ]); $this->checkFiles($actualFiles, $expectedFiles); } + + // https://github.com/php-openapi/yii2-openapi/issues/90 + public function test90ImplementBelongsToRelationsInModels() + { + $testFile = Yii::getAlias("@specs/issue_fix/90_implement_belongs_to_relations_in_models/index.php"); + $this->runGenerator($testFile); + $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ + 'recursive' => true, + ]); + $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/90_implement_belongs_to_relations_in_models/mysql"), [ + 'recursive' => true, + ]); + $this->checkFiles($actualFiles, $expectedFiles); + } } From 4c409f75d2a94c4c19b930628357dfb279137f01 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Tue, 4 Mar 2025 12:07:10 +0530 Subject: [PATCH 344/358] WIP --- src/lib/AttributeResolver.php | 1 + tests/unit/IssueFixTest.php | 14 +++++++------- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/src/lib/AttributeResolver.php b/src/lib/AttributeResolver.php index cc41a6fb..a49a1b65 100644 --- a/src/lib/AttributeResolver.php +++ b/src/lib/AttributeResolver.php @@ -232,6 +232,7 @@ protected function resolveProperty( ->setForeignKeyColumnName($property->fkColName) ->setFakerStub($this->guessFakerStub($attribute, $property)) ->setTableName($this->componentSchema->resolveTableName($this->schemaName)); + if ($property->isReference()) { if ($property->isVirtual()) { throw new InvalidDefinitionException('References not supported for virtual attributes'); diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index 371c0657..dd1bc1c1 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -1020,12 +1020,12 @@ public function test90ImplementBelongsToRelationsInModels() { $testFile = Yii::getAlias("@specs/issue_fix/90_implement_belongs_to_relations_in_models/index.php"); $this->runGenerator($testFile); - $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ - 'recursive' => true, - ]); - $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/90_implement_belongs_to_relations_in_models/mysql"), [ - 'recursive' => true, - ]); - $this->checkFiles($actualFiles, $expectedFiles); +// $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ +// 'recursive' => true, +// ]); +// $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/90_implement_belongs_to_relations_in_models/mysql"), [ +// 'recursive' => true, +// ]); +// $this->checkFiles($actualFiles, $expectedFiles); } } From 2eda480c5d8863b7bad28280d584870be1799fc5 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Tue, 4 Mar 2025 12:27:26 +0530 Subject: [PATCH 345/358] Refactor --- src/lib/AttributeResolver.php | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/src/lib/AttributeResolver.php b/src/lib/AttributeResolver.php index 2f917bdd..1a87557c 100644 --- a/src/lib/AttributeResolver.php +++ b/src/lib/AttributeResolver.php @@ -232,6 +232,7 @@ protected function resolveProperty( ->setForeignKeyColumnName($property->fkColName) ->setFakerStub($this->guessFakerStub($attribute, $property)) ->setTableName($this->componentSchema->resolveTableName($this->schemaName)); + if ($property->isReference()) { if ($property->isVirtual()) { throw new InvalidDefinitionException('References not supported for virtual attributes'); @@ -279,10 +280,8 @@ protected function resolveProperty( $relation->asSelfReference(); } $this->relations[$property->getName()] = $relation; - if (!$property->isRefPointerToSelf() && $property->hasRefItems()) { - $this->addInverseRelation($relatedClassName, $attribute, $property, $fkProperty); - } } + if (!$property->isReference() && !$property->hasRefItems()) { [$min, $max] = $property->guessMinMax(); $attribute->setIsVirtual($property->isVirtual()) @@ -337,7 +336,14 @@ protected function resolveProperty( ) ->asHasMany([$foreignPk => $this->componentSchema->getPkName()]); return; + } else { # handle inverse relation + if ($property->isReference()) { + $relatedClassName = $property->getRefClassName(); + $fkProperty = $property->getTargetProperty(); + $this->addInverseRelation($relatedClassName, $attribute, $property, $fkProperty); + } } + $relatedClassName = $property->getRefClassName(); $relatedTableName = $property->getRefSchema()->resolveTableName($relatedClassName); if ($this->catchManyToMany( From 12315315ef81ba1e6f50b61a1b7e2cab4f9081e5 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Tue, 4 Mar 2025 12:47:46 +0530 Subject: [PATCH 346/358] Refactor 2 --- src/generator/default/dbmodel.php | 8 -------- src/lib/AttributeResolver.php | 29 ----------------------------- src/lib/SchemaToDatabase.php | 11 ----------- src/lib/items/DbModel.php | 5 ----- 4 files changed, 53 deletions(-) diff --git a/src/generator/default/dbmodel.php b/src/generator/default/dbmodel.php index a85fa7bb..1f9d1b40 100644 --- a/src/generator/default/dbmodel.php +++ b/src/generator/default/dbmodel.php @@ -144,12 +144,4 @@ public function getgetCamelName() ?>() } -inverseRelations as $relationName => $relation): ?> - - public function getgetCamelName().($i===1 ? '' : $i) ?>() - { - return $this->getMethod() ?>(\\getClassName() ?>::class, linkToString() ?>)->inverseOf('getInverse() ?>'); - } - } diff --git a/src/lib/AttributeResolver.php b/src/lib/AttributeResolver.php index 1a87557c..b199e74c 100644 --- a/src/lib/AttributeResolver.php +++ b/src/lib/AttributeResolver.php @@ -60,11 +60,6 @@ class AttributeResolver private ?Config $config; - /** - * @var AttributeRelation[]|array - */ - public array $inverseRelations = []; - public function __construct(string $schemaName, ComponentSchema $schema, JunctionSchemas $junctions, ?Config $config = null) { $this->schemaName = $schemaName; @@ -336,12 +331,6 @@ protected function resolveProperty( ) ->asHasMany([$foreignPk => $this->componentSchema->getPkName()]); return; - } else { # handle inverse relation - if ($property->isReference()) { - $relatedClassName = $property->getRefClassName(); - $fkProperty = $property->getTargetProperty(); - $this->addInverseRelation($relatedClassName, $attribute, $property, $fkProperty); - } } $relatedClassName = $property->getRefClassName(); @@ -524,22 +513,4 @@ public static function relationName(string $propertyName, ?string $fkColumnName) } return $relationName; } - - /** - * @throws InvalidConfigException - */ - public function addInverseRelation( - string $relatedClassName, - Attribute $attribute, - PropertySchema $property, - PropertySchema $fkProperty - ): void { - $inverseRelation = Yii::createObject( - AttributeRelation::class, - [$this->schemaName, $this->tableName, $this->schemaName] - ) - ->asHasOne([$attribute->columnName => $fkProperty->getName()]); - $inverseRelation->setInverse($property->getName()); - $this->inverseRelations[$relatedClassName][] = $inverseRelation; - } } diff --git a/src/lib/SchemaToDatabase.php b/src/lib/SchemaToDatabase.php index ccb230a3..2c784a54 100644 --- a/src/lib/SchemaToDatabase.php +++ b/src/lib/SchemaToDatabase.php @@ -106,21 +106,10 @@ public function prepareModels(): array /** @var AttributeResolver $resolver */ $resolver = Yii::createObject(AttributeResolver::class, [$schemaName, $schema, $junctions, $this->config]); - // $models[$schemaName] = $resolver->resolve(); $resolvers[$schemaName] = $resolver; $models[$schemaName] = $resolvers[$schemaName]->resolve(); } - // handle inverse relation - foreach ($resolvers as $aResolver) { - foreach ($aResolver->inverseRelations as $name => $relations) { - foreach ($relations as $relation) { - /** @var AttributeRelation $relation */ - $models[$name]->inverseRelations[] = $relation; - } - } - } - foreach ($models as $model) { foreach ($model->many2many as $relation) { if (isset($models[$relation->viaModelName])) { diff --git a/src/lib/items/DbModel.php b/src/lib/items/DbModel.php index 08135d71..6ccceae9 100644 --- a/src/lib/items/DbModel.php +++ b/src/lib/items/DbModel.php @@ -67,11 +67,6 @@ class DbModel extends BaseObject */ public array $many2many = []; - /** - * @var array|AttributeRelation[] inverse relations - */ - public array $inverseRelations = []; - public array $junctionCols = []; /** From a69f43a4ac401b08826a96267c806b3b971c6b23 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Tue, 4 Mar 2025 14:46:50 +0530 Subject: [PATCH 347/358] Implement --- src/generator/default/dbmodel.php | 10 ++++++++++ src/lib/AttributeResolver.php | 12 ++++++++++++ src/lib/SchemaToDatabase.php | 10 ++++++++++ src/lib/items/DbModel.php | 9 +++++++-- 4 files changed, 39 insertions(+), 2 deletions(-) diff --git a/src/generator/default/dbmodel.php b/src/generator/default/dbmodel.php index 1f9d1b40..f975464f 100644 --- a/src/generator/default/dbmodel.php +++ b/src/generator/default/dbmodel.php @@ -144,4 +144,14 @@ public function getgetCamelName() ?>() } +belongsToRelations as $relationName => $relation): ?> + + # belongs to relation + public function getgetCamelName() . ($i === 1 ? '' : $i) ?>() + { + return $this->getMethod() ?>(\\getClassName() ?>::class, linkToString() ?>); + } + } diff --git a/src/lib/AttributeResolver.php b/src/lib/AttributeResolver.php index b199e74c..1e3f731a 100644 --- a/src/lib/AttributeResolver.php +++ b/src/lib/AttributeResolver.php @@ -37,6 +37,11 @@ class AttributeResolver */ public array $relations = []; + /** + * @var AttributeRelation[]|array + */ + public array $belongsToRelations = []; + /** * @var NonDbRelation[]|array */ @@ -273,6 +278,13 @@ protected function resolveProperty( $relation->onDeleteFkConstraint = $property->onDeleteFkConstraint; if ($property->isRefPointerToSelf()) { $relation->asSelfReference(); + } else { # belongs to relations https://github.com/php-openapi/yii2-openapi/issues/90 + $belongsToRelation = Yii::createObject( + AttributeRelation::class, + [$this->schemaName, $this->tableName, $this->schemaName] + ) + ->asHasOne([$attribute->columnName => $fkProperty->getName()]); + $this->belongsToRelations[$property->getRefClassName()][] = $belongsToRelation; } $this->relations[$property->getName()] = $relation; } diff --git a/src/lib/SchemaToDatabase.php b/src/lib/SchemaToDatabase.php index 2c784a54..929c8ee3 100644 --- a/src/lib/SchemaToDatabase.php +++ b/src/lib/SchemaToDatabase.php @@ -110,6 +110,16 @@ public function prepareModels(): array $models[$schemaName] = $resolvers[$schemaName]->resolve(); } + // handle belongs to relation + foreach ($resolvers as $aResolver) { + foreach ($aResolver->belongsToRelations as $name => $relations) { + foreach ($relations as $relation) { + /** @var AttributeRelation $relation */ + $models[$name]->belongsToRelations[] = $relation; + } + } + } + foreach ($models as $model) { foreach ($model->many2many as $relation) { if (isset($models[$relation->viaModelName])) { diff --git a/src/lib/items/DbModel.php b/src/lib/items/DbModel.php index 6ccceae9..f314b8e8 100644 --- a/src/lib/items/DbModel.php +++ b/src/lib/items/DbModel.php @@ -86,9 +86,9 @@ class DbModel extends BaseObject public bool $descriptionIsComment = false; /** - * @var array Automatically generated scenarios from the model 'x-scenarios'. + * @var array|AttributeRelation[] belongs to relations */ - private $_scenarios; + public array $belongsToRelations = []; /** * @var bool @@ -98,6 +98,11 @@ class DbModel extends BaseObject */ public $drop = false; + /** + * @var array Automatically generated scenarios from the model 'x-scenarios'. + */ + private $_scenarios; + public function getTableAlias(): string { return '{{%' . $this->tableName . '}}'; From f92b7824be1225ef15585ab0967ab66f0143dd89 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Tue, 4 Mar 2025 14:50:52 +0530 Subject: [PATCH 348/358] Complete the test --- .../mysql/models/Address.php | 10 ++++++ .../mysql/models/User.php | 10 ++++++ .../mysql/models/base/Address.php | 36 +++++++++++++++++++ .../mysql/models/base/User.php | 32 +++++++++++++++++ tests/unit/IssueFixTest.php | 14 ++++---- 5 files changed, 95 insertions(+), 7 deletions(-) create mode 100644 tests/specs/issue_fix/90_implement_belongs_to_relations_in_models/mysql/models/Address.php create mode 100644 tests/specs/issue_fix/90_implement_belongs_to_relations_in_models/mysql/models/User.php create mode 100644 tests/specs/issue_fix/90_implement_belongs_to_relations_in_models/mysql/models/base/Address.php create mode 100644 tests/specs/issue_fix/90_implement_belongs_to_relations_in_models/mysql/models/base/User.php diff --git a/tests/specs/issue_fix/90_implement_belongs_to_relations_in_models/mysql/models/Address.php b/tests/specs/issue_fix/90_implement_belongs_to_relations_in_models/mysql/models/Address.php new file mode 100644 index 00000000..abfd7d59 --- /dev/null +++ b/tests/specs/issue_fix/90_implement_belongs_to_relations_in_models/mysql/models/Address.php @@ -0,0 +1,10 @@ + [['user_id'], 'integer'], + 'user_id_exist' => [['user_id'], 'exist', 'targetRelation' => 'user'], + ]; + } + + public function getUser() + { + return $this->hasOne(\app\models\User::class, ['id' => 'user_id']); + } +} diff --git a/tests/specs/issue_fix/90_implement_belongs_to_relations_in_models/mysql/models/base/User.php b/tests/specs/issue_fix/90_implement_belongs_to_relations_in_models/mysql/models/base/User.php new file mode 100644 index 00000000..a6a35b66 --- /dev/null +++ b/tests/specs/issue_fix/90_implement_belongs_to_relations_in_models/mysql/models/base/User.php @@ -0,0 +1,32 @@ +hasOne(\app\models\Address::class, ['user_id' => 'id']); + } +} diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index 025128e6..f3f13a4b 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -1034,12 +1034,12 @@ public function test90ImplementBelongsToRelationsInModels() { $testFile = Yii::getAlias("@specs/issue_fix/90_implement_belongs_to_relations_in_models/index.php"); $this->runGenerator($testFile); -// $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ -// 'recursive' => true, -// ]); -// $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/90_implement_belongs_to_relations_in_models/mysql"), [ -// 'recursive' => true, -// ]); -// $this->checkFiles($actualFiles, $expectedFiles); + $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ + 'recursive' => true, + ]); + $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/90_implement_belongs_to_relations_in_models/mysql"), [ + 'recursive' => true, + ]); + $this->checkFiles($actualFiles, $expectedFiles); } } From 5b1ec545c62e4d54b0e98023819c40d88428b7f3 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Tue, 4 Mar 2025 15:28:05 +0530 Subject: [PATCH 349/358] Fix failing tests --- src/generator/default/dbmodel.php | 8 ++++---- tests/specs/blog/models/base/Category.php | 6 ++++++ tests/specs/blog/models/base/Post.php | 6 ++++++ tests/specs/blog/models/base/User.php | 12 ++++++++++++ tests/specs/blog_v2/models/base/Category.php | 6 ++++++ tests/specs/blog_v2/models/base/Post.php | 6 ++++++ tests/specs/blog_v2/models/base/User.php | 12 ++++++++++++ .../fk_col_name/app/models/base/Delivery.php | 6 ++++++ .../specs/fk_col_name/app/models/base/User.php | 6 ++++++ .../app/models/base/Delivery.php | 12 ++++++++++++ .../fk_col_name_index/app/models/base/User.php | 6 ++++++ .../maria/models/base/Mailing.php | 6 ++++++ .../app/models/base/Invoice.php | 6 ++++++ .../pgsql/models/base/Account.php | 6 ++++++ .../mysql/models/base/User.php | 18 ++++++++++++++++++ .../mysql/models/base/User.php | 6 ++++++ .../mysql/models/base/Animal.php | 6 ++++++ .../mysql/models/base/Fruit.php | 6 ++++++ .../mysql/models/base/User.php | 12 ++++++++++++ .../index.yaml | 2 -- .../mysql/models/base/Address.php | 6 ++++++ .../app/models/base/Account.php | 18 ++++++++++++++++++ tests/specs/petstore/models/base/Store.php | 6 ++++++ .../specs/petstore_jsonapi/models/base/Pet.php | 6 ++++++ .../petstore_namespace/mymodels/base/Store.php | 6 ++++++ .../app/models/base/A123.php | 6 ++++++ .../app/models/base/Account.php | 6 ++++++ .../app/models/base/B123.php | 12 ++++++++++++ .../app/models/base/C123.php | 6 ++++++ .../app/models/base/D123.php | 6 ++++++ .../app/models/base/Domain.php | 6 ++++++ 31 files changed, 232 insertions(+), 6 deletions(-) diff --git a/src/generator/default/dbmodel.php b/src/generator/default/dbmodel.php index f975464f..448aa5ba 100644 --- a/src/generator/default/dbmodel.php +++ b/src/generator/default/dbmodel.php @@ -144,14 +144,14 @@ public function getgetCamelName() ?>() } -belongsToRelations as $relationName => $relation): ?> +belongsToRelations as $relationName => $relation): ?>getCamelName(), $usedRelationNames) ? $i : '' ?> # belongs to relation - public function getgetCamelName() . ($i === 1 ? '' : $i) ?>() + public function getgetCamelName() . ($number) ?>() { return $this->getMethod() ?>(\\getClassName() ?>::class, linkToString() ?>); } - +getCamelName(); endforeach; ?> } diff --git a/tests/specs/blog/models/base/Category.php b/tests/specs/blog/models/base/Category.php index 36e7887a..287bdc9f 100644 --- a/tests/specs/blog/models/base/Category.php +++ b/tests/specs/blog/models/base/Category.php @@ -38,4 +38,10 @@ public function getPosts() { return $this->hasMany(\app\models\Post::class, ['category_id' => 'id'])->inverseOf('category'); } + + # belongs to relation + public function getPost() + { + return $this->hasOne(\app\models\Post::class, ['category_id' => 'id']); + } } diff --git a/tests/specs/blog/models/base/Post.php b/tests/specs/blog/models/base/Post.php index 80393b08..2a97d0fa 100644 --- a/tests/specs/blog/models/base/Post.php +++ b/tests/specs/blog/models/base/Post.php @@ -61,4 +61,10 @@ public function getComments() { return $this->hasMany(\app\models\Comment::class, ['post_id' => 'uid'])->inverseOf('post'); } + + # belongs to relation + public function getComment() + { + return $this->hasOne(\app\models\Comment::class, ['post_id' => 'uid']); + } } diff --git a/tests/specs/blog/models/base/User.php b/tests/specs/blog/models/base/User.php index c0d73705..557328f9 100644 --- a/tests/specs/blog/models/base/User.php +++ b/tests/specs/blog/models/base/User.php @@ -44,4 +44,16 @@ public function rules() 'email_unique' => [['email'], 'unique'], ]; } + + # belongs to relation + public function getPost() + { + return $this->hasOne(\app\models\Post::class, ['created_by_id' => 'id']); + } + + # belongs to relation + public function getComment() + { + return $this->hasOne(\app\models\Comment::class, ['author_id' => 'id']); + } } diff --git a/tests/specs/blog_v2/models/base/Category.php b/tests/specs/blog_v2/models/base/Category.php index 7744c88a..1b97af75 100644 --- a/tests/specs/blog_v2/models/base/Category.php +++ b/tests/specs/blog_v2/models/base/Category.php @@ -38,4 +38,10 @@ public function getPosts() { return $this->hasMany(\app\models\Post::class, ['category_id' => 'id'])->inverseOf('category'); } + + # belongs to relation + public function getPost() + { + return $this->hasOne(\app\models\Post::class, ['category_id' => 'id']); + } } diff --git a/tests/specs/blog_v2/models/base/Post.php b/tests/specs/blog_v2/models/base/Post.php index 1913f0c2..0b82cefc 100644 --- a/tests/specs/blog_v2/models/base/Post.php +++ b/tests/specs/blog_v2/models/base/Post.php @@ -73,4 +73,10 @@ public function getTags() return $this->hasMany(\app\models\Tag::class, ['id' => 'tag_id']) ->viaTable('posts2tags', ['post_id' => 'id']); } + + # belongs to relation + public function getComment() + { + return $this->hasOne(\app\models\Comment::class, ['post_id' => 'id']); + } } diff --git a/tests/specs/blog_v2/models/base/User.php b/tests/specs/blog_v2/models/base/User.php index 7123c988..820b8259 100644 --- a/tests/specs/blog_v2/models/base/User.php +++ b/tests/specs/blog_v2/models/base/User.php @@ -47,4 +47,16 @@ public function rules() 'email_unique' => [['email'], 'unique'], ]; } + + # belongs to relation + public function getPost() + { + return $this->hasOne(\app\models\Post::class, ['created_by_id' => 'id']); + } + + # belongs to relation + public function getComment() + { + return $this->hasOne(\app\models\Comment::class, ['user_id' => 'id']); + } } diff --git a/tests/specs/fk_col_name/app/models/base/Delivery.php b/tests/specs/fk_col_name/app/models/base/Delivery.php index 214c5278..3bb543a1 100644 --- a/tests/specs/fk_col_name/app/models/base/Delivery.php +++ b/tests/specs/fk_col_name/app/models/base/Delivery.php @@ -27,4 +27,10 @@ public function rules() 'title_string' => [['title'], 'string'], ]; } + + # belongs to relation + public function getWebhook() + { + return $this->hasOne(\app\models\Webhook::class, ['redelivery_of' => 'id']); + } } diff --git a/tests/specs/fk_col_name/app/models/base/User.php b/tests/specs/fk_col_name/app/models/base/User.php index 9c127aeb..7847f799 100644 --- a/tests/specs/fk_col_name/app/models/base/User.php +++ b/tests/specs/fk_col_name/app/models/base/User.php @@ -28,4 +28,10 @@ public function rules() 'name_string' => [['name'], 'string'], ]; } + + # belongs to relation + public function getWebhook() + { + return $this->hasOne(\app\models\Webhook::class, ['user_id' => 'id']); + } } diff --git a/tests/specs/fk_col_name_index/app/models/base/Delivery.php b/tests/specs/fk_col_name_index/app/models/base/Delivery.php index 214c5278..98b9c801 100644 --- a/tests/specs/fk_col_name_index/app/models/base/Delivery.php +++ b/tests/specs/fk_col_name_index/app/models/base/Delivery.php @@ -27,4 +27,16 @@ public function rules() 'title_string' => [['title'], 'string'], ]; } + + # belongs to relation + public function getWebhook() + { + return $this->hasOne(\app\models\Webhook::class, ['redelivery_of' => 'id']); + } + + # belongs to relation + public function getWebhook2() + { + return $this->hasOne(\app\models\Webhook::class, ['rd_abc_2' => 'id']); + } } diff --git a/tests/specs/fk_col_name_index/app/models/base/User.php b/tests/specs/fk_col_name_index/app/models/base/User.php index 9c127aeb..7847f799 100644 --- a/tests/specs/fk_col_name_index/app/models/base/User.php +++ b/tests/specs/fk_col_name_index/app/models/base/User.php @@ -28,4 +28,10 @@ public function rules() 'name_string' => [['name'], 'string'], ]; } + + # belongs to relation + public function getWebhook() + { + return $this->hasOne(\app\models\Webhook::class, ['user_id' => 'id']); + } } diff --git a/tests/specs/issue_fix/159_bug_giiapi_generated_rules_emailid/maria/models/base/Mailing.php b/tests/specs/issue_fix/159_bug_giiapi_generated_rules_emailid/maria/models/base/Mailing.php index ff8629b5..2639a486 100644 --- a/tests/specs/issue_fix/159_bug_giiapi_generated_rules_emailid/maria/models/base/Mailing.php +++ b/tests/specs/issue_fix/159_bug_giiapi_generated_rules_emailid/maria/models/base/Mailing.php @@ -30,4 +30,10 @@ public function rules() 'paymentMethodName_string' => [['paymentMethodName'], 'string'], ]; } + + # belongs to relation + public function getContact() + { + return $this->hasOne(\app\models\Contact::class, ['mailing_id' => 'id']); + } } diff --git a/tests/specs/issue_fix/162_bug_dollarref_with_x_faker/app/models/base/Invoice.php b/tests/specs/issue_fix/162_bug_dollarref_with_x_faker/app/models/base/Invoice.php index 21bfa112..1f685781 100644 --- a/tests/specs/issue_fix/162_bug_dollarref_with_x_faker/app/models/base/Invoice.php +++ b/tests/specs/issue_fix/162_bug_dollarref_with_x_faker/app/models/base/Invoice.php @@ -23,4 +23,10 @@ public function rules() { return []; } + + # belongs to relation + public function getOrder() + { + return $this->hasOne(\app\models\Order::class, ['invoice_id' => 'id']); + } } diff --git a/tests/specs/issue_fix/175_bug_allof_with_multiple_dollarrefs/pgsql/models/base/Account.php b/tests/specs/issue_fix/175_bug_allof_with_multiple_dollarrefs/pgsql/models/base/Account.php index e776fe40..079b93b9 100644 --- a/tests/specs/issue_fix/175_bug_allof_with_multiple_dollarrefs/pgsql/models/base/Account.php +++ b/tests/specs/issue_fix/175_bug_allof_with_multiple_dollarrefs/pgsql/models/base/Account.php @@ -30,4 +30,10 @@ public function rules() 'paymentMethodName_string' => [['paymentMethodName'], 'string'], ]; } + + # belongs to relation + public function getContact() + { + return $this->hasOne(\app\models\Contact::class, ['account_id' => 'id']); + } } diff --git a/tests/specs/issue_fix/25_generate_inverse_relations/mysql/models/base/User.php b/tests/specs/issue_fix/25_generate_inverse_relations/mysql/models/base/User.php index 0240e1e5..c1b63234 100644 --- a/tests/specs/issue_fix/25_generate_inverse_relations/mysql/models/base/User.php +++ b/tests/specs/issue_fix/25_generate_inverse_relations/mysql/models/base/User.php @@ -34,4 +34,22 @@ public function getAccounts() { return $this->hasMany(\app\models\Account::class, ['user_id' => 'id'])->inverseOf('user'); } + + # belongs to relation + public function getAccount() + { + return $this->hasOne(\app\models\Account::class, ['user_id' => 'id']); + } + + # belongs to relation + public function getAccount2() + { + return $this->hasOne(\app\models\Account::class, ['user2_id' => 'id']); + } + + # belongs to relation + public function getAccount3() + { + return $this->hasOne(\app\models\Account::class, ['user3' => 'id']); + } } diff --git a/tests/specs/issue_fix/29_extension_fk_column_name_cause_error_in_case_of_column_name_without_underscore/mysql/models/base/User.php b/tests/specs/issue_fix/29_extension_fk_column_name_cause_error_in_case_of_column_name_without_underscore/mysql/models/base/User.php index bce4e105..547aa903 100644 --- a/tests/specs/issue_fix/29_extension_fk_column_name_cause_error_in_case_of_column_name_without_underscore/mysql/models/base/User.php +++ b/tests/specs/issue_fix/29_extension_fk_column_name_cause_error_in_case_of_column_name_without_underscore/mysql/models/base/User.php @@ -27,4 +27,10 @@ public function rules() 'name_string' => [['name'], 'string'], ]; } + + # belongs to relation + public function getPost() + { + return $this->hasOne(\app\models\Post::class, ['user' => 'id']); + } } diff --git a/tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql/models/base/Animal.php b/tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql/models/base/Animal.php index a99b34da..bfd317f7 100644 --- a/tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql/models/base/Animal.php +++ b/tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql/models/base/Animal.php @@ -27,4 +27,10 @@ public function rules() 'name_string' => [['name'], 'string'], ]; } + + # belongs to relation + public function getInvoice() + { + return $this->hasOne(\app\models\Invoice::class, ['animal_id' => 'id']); + } } diff --git a/tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql/models/base/Fruit.php b/tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql/models/base/Fruit.php index ccdbe894..ab5c4054 100644 --- a/tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql/models/base/Fruit.php +++ b/tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql/models/base/Fruit.php @@ -27,4 +27,10 @@ public function rules() 'name_string' => [['name'], 'string'], ]; } + + # belongs to relation + public function getInvoice() + { + return $this->hasOne(\app\models\Invoice::class, ['fruit_id' => 'id']); + } } diff --git a/tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql/models/base/User.php b/tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql/models/base/User.php index bce4e105..c132c14b 100644 --- a/tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql/models/base/User.php +++ b/tests/specs/issue_fix/52_bug_dependenton_allof_with_x_faker_false/mysql/models/base/User.php @@ -27,4 +27,16 @@ public function rules() 'name_string' => [['name'], 'string'], ]; } + + # belongs to relation + public function getInvoice() + { + return $this->hasOne(\app\models\Invoice::class, ['user_id' => 'id']); + } + + # belongs to relation + public function getInvoice2() + { + return $this->hasOne(\app\models\Invoice::class, ['user_2_id' => 'id']); + } } diff --git a/tests/specs/issue_fix/88_in_case_of_updating_a_model_generator_creates_redundant_inverse_relations/index.yaml b/tests/specs/issue_fix/88_in_case_of_updating_a_model_generator_creates_redundant_inverse_relations/index.yaml index 2e5ac94f..8acbf164 100644 --- a/tests/specs/issue_fix/88_in_case_of_updating_a_model_generator_creates_redundant_inverse_relations/index.yaml +++ b/tests/specs/issue_fix/88_in_case_of_updating_a_model_generator_creates_redundant_inverse_relations/index.yaml @@ -29,5 +29,3 @@ components: type: string address: $ref: '#/components/schemas/Address' - - diff --git a/tests/specs/issue_fix/88_in_case_of_updating_a_model_generator_creates_redundant_inverse_relations/mysql/models/base/Address.php b/tests/specs/issue_fix/88_in_case_of_updating_a_model_generator_creates_redundant_inverse_relations/mysql/models/base/Address.php index aa298e27..e42f43c1 100644 --- a/tests/specs/issue_fix/88_in_case_of_updating_a_model_generator_creates_redundant_inverse_relations/mysql/models/base/Address.php +++ b/tests/specs/issue_fix/88_in_case_of_updating_a_model_generator_creates_redundant_inverse_relations/mysql/models/base/Address.php @@ -27,4 +27,10 @@ public function rules() 'name_string' => [['name'], 'string'], ]; } + + # belongs to relation + public function getHuman() + { + return $this->hasOne(\app\models\Human::class, ['address_id' => 'id']); + } } diff --git a/tests/specs/issue_fix/model_name_more_than_once_in_faker_148/app/models/base/Account.php b/tests/specs/issue_fix/model_name_more_than_once_in_faker_148/app/models/base/Account.php index b90b713b..a296c4c0 100644 --- a/tests/specs/issue_fix/model_name_more_than_once_in_faker_148/app/models/base/Account.php +++ b/tests/specs/issue_fix/model_name_more_than_once_in_faker_148/app/models/base/Account.php @@ -28,4 +28,22 @@ public function rules() 'name_string' => [['name'], 'string', 'max' => 40], ]; } + + # belongs to relation + public function getE123() + { + return $this->hasOne(\app\models\E123::class, ['account_id' => 'id']); + } + + # belongs to relation + public function getE1232() + { + return $this->hasOne(\app\models\E123::class, ['account_2_id' => 'id']); + } + + # belongs to relation + public function getE1233() + { + return $this->hasOne(\app\models\E123::class, ['account_3_id' => 'id']); + } } diff --git a/tests/specs/petstore/models/base/Store.php b/tests/specs/petstore/models/base/Store.php index b450803e..d9eafaca 100644 --- a/tests/specs/petstore/models/base/Store.php +++ b/tests/specs/petstore/models/base/Store.php @@ -28,4 +28,10 @@ public function rules() 'name_string' => [['name'], 'string'], ]; } + + # belongs to relation + public function getPet() + { + return $this->hasOne(\app\models\Pet::class, ['store_id' => 'id']); + } } diff --git a/tests/specs/petstore_jsonapi/models/base/Pet.php b/tests/specs/petstore_jsonapi/models/base/Pet.php index cf242429..0f057dc1 100644 --- a/tests/specs/petstore_jsonapi/models/base/Pet.php +++ b/tests/specs/petstore_jsonapi/models/base/Pet.php @@ -63,4 +63,10 @@ public function getDuplicates() { return $this->hasMany(\app\models\Pet::class, ['tag' => 'tag']); } + + # belongs to relation + public function getPetStatistic() + { + return $this->hasOne(\app\models\PetStatistic::class, ['parentPet_id' => 'id']); + } } diff --git a/tests/specs/petstore_namespace/mymodels/base/Store.php b/tests/specs/petstore_namespace/mymodels/base/Store.php index 8ae6c907..35aa907f 100644 --- a/tests/specs/petstore_namespace/mymodels/base/Store.php +++ b/tests/specs/petstore_namespace/mymodels/base/Store.php @@ -28,4 +28,10 @@ public function rules() 'name_string' => [['name'], 'string'], ]; } + + # belongs to relation + public function getPet() + { + return $this->hasOne(\app\mymodels\Pet::class, ['store_id' => 'id']); + } } diff --git a/tests/specs/relations_in_faker/app/models/base/A123.php b/tests/specs/relations_in_faker/app/models/base/A123.php index fb8681d6..74d782f2 100644 --- a/tests/specs/relations_in_faker/app/models/base/A123.php +++ b/tests/specs/relations_in_faker/app/models/base/A123.php @@ -36,4 +36,10 @@ public function getB123() { return $this->hasOne(\app\models\B123::class, ['id' => 'b123_id']); } + + # belongs to relation + public function getRouting() + { + return $this->hasOne(\app\models\Routing::class, ['a123_id' => 'id']); + } } diff --git a/tests/specs/relations_in_faker/app/models/base/Account.php b/tests/specs/relations_in_faker/app/models/base/Account.php index b90b713b..c5bfedb1 100644 --- a/tests/specs/relations_in_faker/app/models/base/Account.php +++ b/tests/specs/relations_in_faker/app/models/base/Account.php @@ -28,4 +28,10 @@ public function rules() 'name_string' => [['name'], 'string', 'max' => 40], ]; } + + # belongs to relation + public function getDomain() + { + return $this->hasOne(\app\models\Domain::class, ['account_id' => 'id']); + } } diff --git a/tests/specs/relations_in_faker/app/models/base/B123.php b/tests/specs/relations_in_faker/app/models/base/B123.php index 9fee3543..63727b75 100644 --- a/tests/specs/relations_in_faker/app/models/base/B123.php +++ b/tests/specs/relations_in_faker/app/models/base/B123.php @@ -36,4 +36,16 @@ public function getC123() { return $this->hasOne(\app\models\C123::class, ['id' => 'c123_id']); } + + # belongs to relation + public function getA123() + { + return $this->hasOne(\app\models\A123::class, ['b123_id' => 'id']); + } + + # belongs to relation + public function getE123() + { + return $this->hasOne(\app\models\E123::class, ['b123_id' => 'id']); + } } diff --git a/tests/specs/relations_in_faker/app/models/base/C123.php b/tests/specs/relations_in_faker/app/models/base/C123.php index 611526d8..7f516f78 100644 --- a/tests/specs/relations_in_faker/app/models/base/C123.php +++ b/tests/specs/relations_in_faker/app/models/base/C123.php @@ -27,4 +27,10 @@ public function rules() 'name_string' => [['name'], 'string'], ]; } + + # belongs to relation + public function getB123() + { + return $this->hasOne(\app\models\B123::class, ['c123_id' => 'id']); + } } diff --git a/tests/specs/relations_in_faker/app/models/base/D123.php b/tests/specs/relations_in_faker/app/models/base/D123.php index c45d7214..71555b18 100644 --- a/tests/specs/relations_in_faker/app/models/base/D123.php +++ b/tests/specs/relations_in_faker/app/models/base/D123.php @@ -27,4 +27,10 @@ public function rules() 'name_string' => [['name'], 'string'], ]; } + + # belongs to relation + public function getRouting() + { + return $this->hasOne(\app\models\Routing::class, ['d123_id' => 'id']); + } } diff --git a/tests/specs/relations_in_faker/app/models/base/Domain.php b/tests/specs/relations_in_faker/app/models/base/Domain.php index 3c5ca1b1..fa563120 100644 --- a/tests/specs/relations_in_faker/app/models/base/Domain.php +++ b/tests/specs/relations_in_faker/app/models/base/Domain.php @@ -44,4 +44,10 @@ public function getRoutings() { return $this->hasMany(\app\models\Routing::class, ['domain_id' => 'id'])->inverseOf('domain'); } + + # belongs to relation + public function getRouting() + { + return $this->hasOne(\app\models\Routing::class, ['domain_id' => 'id']); + } } From 2134ddf05336cb4c454caa31949eb312990df971 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Tue, 4 Mar 2025 15:59:03 +0530 Subject: [PATCH 350/358] Refactor and add docs --- src/lib/AttributeResolver.php | 2 +- src/lib/SchemaToDatabase.php | 6 ++---- src/lib/items/DbModel.php | 2 +- 3 files changed, 4 insertions(+), 6 deletions(-) diff --git a/src/lib/AttributeResolver.php b/src/lib/AttributeResolver.php index 1e3f731a..0c0c41c9 100644 --- a/src/lib/AttributeResolver.php +++ b/src/lib/AttributeResolver.php @@ -38,7 +38,7 @@ class AttributeResolver public array $relations = []; /** - * @var AttributeRelation[]|array + * @var array keys contains class names and value contains array of belongs to relations */ public array $belongsToRelations = []; diff --git a/src/lib/SchemaToDatabase.php b/src/lib/SchemaToDatabase.php index 929c8ee3..0c513b94 100644 --- a/src/lib/SchemaToDatabase.php +++ b/src/lib/SchemaToDatabase.php @@ -113,10 +113,8 @@ public function prepareModels(): array // handle belongs to relation foreach ($resolvers as $aResolver) { foreach ($aResolver->belongsToRelations as $name => $relations) { - foreach ($relations as $relation) { - /** @var AttributeRelation $relation */ - $models[$name]->belongsToRelations[] = $relation; - } + /** @var AttributeRelation[] $relations */ + $models[$name]->belongsToRelations = [...$models[$name]->belongsToRelations, ...$relations]; } } diff --git a/src/lib/items/DbModel.php b/src/lib/items/DbModel.php index f314b8e8..5b19d03c 100644 --- a/src/lib/items/DbModel.php +++ b/src/lib/items/DbModel.php @@ -86,7 +86,7 @@ class DbModel extends BaseObject public bool $descriptionIsComment = false; /** - * @var array|AttributeRelation[] belongs to relations + * @var AttributeRelation[] belongs to relations */ public array $belongsToRelations = []; From 0e6a427aa5837b57d33e8311a4cb97ba02003a81 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Tue, 4 Mar 2025 16:26:07 +0530 Subject: [PATCH 351/358] Change to `docker compose` --- .github/workflows/test.yml | 6 +++--- CONTRIBUTING.md | 2 +- Makefile | 30 +++++++++++++++--------------- docker-compose.yml | 2 +- 4 files changed, 20 insertions(+), 20 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 8487efc3..ff20d49f 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -33,12 +33,12 @@ jobs: uses: ndeloof/install-compose-action@v0.0.1 with: # version: v3.5 # defaults to 'latest' - legacy: true # will also install in PATH as `docker-compose` + legacy: true # will also install in PATH as `docker compose` - name: Clean run: make clean_all - - name: docker-compose up + - name: docker compose up run: make up # https://github.com/shivammathur/setup-php?tab=readme-ov-file#cache-composer-dependencies @@ -57,7 +57,7 @@ jobs: restore-keys: ${{ runner.os }}-composer- - name: Install Docker and composer dependencies - run: docker-compose exec php php -v && make installdocker + run: docker compose exec php php -v && make installdocker - name: Migrate run: make UID=0 migrate diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 053e65a9..534aba0d 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -84,7 +84,7 @@ Creating yii2-openapi_maria_1 ... done Creating yii2-openapi_mysql_1 ... done Creating yii2-openapi_postgres_1 ... done Creating yii2-openapi_php_1 ... done -docker-compose exec php bash +docker compose exec php bash root@f9928598f841:/app# php -v diff --git a/Makefile b/Makefile index 72e173f8..8c03eb48 100644 --- a/Makefile +++ b/Makefile @@ -10,7 +10,7 @@ check-style: vendor/bin/php-cs-fixer fix --diff --dry-run check-style-from-host: - docker-compose run --rm php sh -c 'vendor/bin/php-cs-fixer fix --diff --dry-run' + docker compose run --rm php sh -c 'vendor/bin/php-cs-fixer fix --diff --dry-run' fix-style: vendor/bin/indent --tabs composer.json @@ -24,7 +24,7 @@ test: php $(PHPARGS) vendor/bin/phpunit clean_all: - docker-compose down + docker compose down sudo rm -rf tests/tmp/* clean: @@ -32,38 +32,38 @@ clean: sudo rm -rf tests/tmp/docker_app/* down: - docker-compose down --remove-orphans + docker compose down --remove-orphans up: - docker-compose up -d + docker compose up -d echo "Waiting for mariadb to start up..." - docker-compose exec -T mysql timeout 60s sh -c "while ! (mysql -udbuser -pdbpass -h maria --execute 'SELECT 1;' > /dev/null 2>&1); do echo -n '.'; sleep 0.1 ; done; echo 'ok'" || (docker-compose ps; docker-compose logs; exit 1) + docker compose exec -T mysql timeout 60s sh -c "while ! (mysql -udbuser -pdbpass -h maria --execute 'SELECT 1;' > /dev/null 2>&1); do echo -n '.'; sleep 0.1 ; done; echo 'ok'" || (docker compose ps; docker compose logs; exit 1) echo "Waiting for Mysql to start up..." - docker-compose exec -T mysql timeout 60s sh -c "while ! (mysql -udbuser -pdbpass -h mysql --execute 'SELECT 1;' > /dev/null 2>&1); do echo -n '.'; sleep 0.1 ; done; echo 'ok'" || (docker-compose ps; docker-compose logs; exit 1) + docker compose exec -T mysql timeout 60s sh -c "while ! (mysql -udbuser -pdbpass -h mysql --execute 'SELECT 1;' > /dev/null 2>&1); do echo -n '.'; sleep 0.1 ; done; echo 'ok'" || (docker compose ps; docker compose logs; exit 1) cli: - docker-compose exec --user=$(UID) php bash + docker compose exec --user=$(UID) php bash cli_root: - docker-compose exec --user="root" php bash + docker compose exec --user="root" php bash cli_mysql: - docker-compose exec --user=$(UID) mysql bash + docker compose exec --user=$(UID) mysql bash migrate: - docker-compose run --user=$(UID) --rm php sh -c 'mkdir -p "tests/tmp/app"' - docker-compose run --user=$(UID) --rm php sh -c 'mkdir -p "tests/tmp/docker_app"' - docker-compose run --user=$(UID) --rm php sh -c 'cd /app/tests && ./yii migrate --interactive=0' + docker compose run --user=$(UID) --rm php sh -c 'mkdir -p "tests/tmp/app"' + docker compose run --user=$(UID) --rm php sh -c 'mkdir -p "tests/tmp/docker_app"' + docker compose run --user=$(UID) --rm php sh -c 'cd /app/tests && ./yii migrate --interactive=0' installdocker: - docker-compose run --user=$(UID) --rm php composer install && chmod +x tests/yii + docker compose run --user=$(UID) --rm php composer install && chmod +x tests/yii tests_dir_write_permission: - docker-compose run --user="root" --rm php chmod -R 777 tests/tmp/ # TODO avoid 777 https://github.com/cebe/yii2-openapi/issues/156 + docker compose run --user="root" --rm php chmod -R 777 tests/tmp/ # TODO avoid 777 https://github.com/cebe/yii2-openapi/issues/156 testdocker: - docker-compose run --user=$(UID) --rm php sh -c 'vendor/bin/phpunit --repeat 3' + docker compose run --user=$(UID) --rm php sh -c 'vendor/bin/phpunit --repeat 3' efs: clean_all up migrate # Everything From Scratch diff --git a/docker-compose.yml b/docker-compose.yml index 2eda366e..2005d415 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,4 +1,4 @@ -version: "3.5" +name: yii2-docker services: php: image: yii2-openapi-php:${PHP_VERSION:-8.3} From 98d57ac9a39e4c8e1ee1ff9bd2ee424fa6b8e040 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Wed, 5 Mar 2025 14:09:35 +0530 Subject: [PATCH 352/358] Remove legacy Docker Compose from GitHub Action --- .github/workflows/test.yml | 3 --- Makefile | 2 +- docker-compose.yml | 1 - 3 files changed, 1 insertion(+), 5 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index ff20d49f..462cb33e 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -31,9 +31,6 @@ jobs: # Run every tests inside Docker container - name: Docker Compose Setup uses: ndeloof/install-compose-action@v0.0.1 - with: - # version: v3.5 # defaults to 'latest' - legacy: true # will also install in PATH as `docker compose` - name: Clean run: make clean_all diff --git a/Makefile b/Makefile index 8c03eb48..9a23ae35 100644 --- a/Makefile +++ b/Makefile @@ -24,7 +24,7 @@ test: php $(PHPARGS) vendor/bin/phpunit clean_all: - docker compose down + docker compose down --remove-orphans sudo rm -rf tests/tmp/* clean: diff --git a/docker-compose.yml b/docker-compose.yml index 2005d415..67d220d1 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -73,4 +73,3 @@ networks: ipam: config: - subnet: 172.14.0.0/24 - From 426fecb1c5afcb2c100f2549112be9398f7091a8 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Fri, 7 Mar 2025 16:20:29 +0530 Subject: [PATCH 353/358] Modify a file to create pull request at GitHub --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index f68df469..4cc1d72a 100644 --- a/README.md +++ b/README.md @@ -779,3 +779,4 @@ Professional support, consulting as well as software development services are av https://www.cebe.cc/en/contact Development of this library is sponsored by [cebe.:cloud: "Your Professional Deployment Platform"](https://cebe.cloud). + From 49cd50e33135debecf375cff2b3ba81e7d4f821a Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Fri, 7 Mar 2025 18:18:19 +0530 Subject: [PATCH 354/358] Add message --- README.md | 1 - src/lib/generators/ControllersGenerator.php | 13 +++++-- .../index.php | 13 +++++++ .../index.yml | 36 +++++++++++++++++++ tests/unit/IssueFixTest.php | 14 ++++++++ 5 files changed, 73 insertions(+), 4 deletions(-) create mode 100644 tests/specs/issue_fix/79_response_status_codes_are_not_the_codes_defined_in_spec/index.php create mode 100644 tests/specs/issue_fix/79_response_status_codes_are_not_the_codes_defined_in_spec/index.yml diff --git a/README.md b/README.md index 4cc1d72a..f68df469 100644 --- a/README.md +++ b/README.md @@ -779,4 +779,3 @@ Professional support, consulting as well as software development services are av https://www.cebe.cc/en/contact Development of this library is sponsored by [cebe.:cloud: "Your Professional Deployment Platform"](https://cebe.cloud). - diff --git a/src/lib/generators/ControllersGenerator.php b/src/lib/generators/ControllersGenerator.php index bd749c9f..e3ddcf23 100644 --- a/src/lib/generators/ControllersGenerator.php +++ b/src/lib/generators/ControllersGenerator.php @@ -59,7 +59,7 @@ public function generate():CodeFiles $controllerPath = $path; /** * @var RestAction|FractalAction $action - **/ + **/ $action = $actions[0]; if ($action->prefix && !empty($action->prefixSettings)) { $controllerNamespace = trim($action->prefixSettings['namespace'], '\\'); @@ -126,15 +126,22 @@ protected function makeCustomController( ]; $reflection->addMethod('checkAccess', $params, AbstractMemberGenerator::FLAG_PUBLIC, '//TODO implement checkAccess'); foreach ($abstractActions as $action) { + + $responseHttpStatusCodes = ''; + foreach ($this->config->getOpenApi()->paths->getPaths()[$action->urlPath]->getOperations() as $verb => $operation) { + if ($verb === strtolower($action->requestMethod)) { + $responseHttpStatusCodes = implode(', ', array_keys($operation->responses->getResponses())); + } + } + $params = array_map(static function ($param) { return ['name' => $param]; }, $action->getParamNames()); - $reflection->addMethod( $action->actionMethodName, $params, AbstractMemberGenerator::FLAG_PUBLIC, - '//TODO implement ' . $action->actionMethodName + '// TODO implement ' . $action->actionMethodName . PHP_EOL . '// In order to conform with OpenAPI spec, response of this action must have one of the following HTTP status code: ' . $responseHttpStatusCodes ); } $classFileGenerator->setClasses([$reflection]); diff --git a/tests/specs/issue_fix/79_response_status_codes_are_not_the_codes_defined_in_spec/index.php b/tests/specs/issue_fix/79_response_status_codes_are_not_the_codes_defined_in_spec/index.php new file mode 100644 index 00000000..cf88e27a --- /dev/null +++ b/tests/specs/issue_fix/79_response_status_codes_are_not_the_codes_defined_in_spec/index.php @@ -0,0 +1,13 @@ + '@specs/issue_fix/79_response_status_codes_are_not_the_codes_defined_in_spec/index.yml', + 'generateUrls' => false, + 'generateModels' => false, + 'excludeModels' => [ + 'Error', + ], + 'generateControllers' => true, + 'generateMigrations' => false, + 'generateModelFaker' => false, +]; diff --git a/tests/specs/issue_fix/79_response_status_codes_are_not_the_codes_defined_in_spec/index.yml b/tests/specs/issue_fix/79_response_status_codes_are_not_the_codes_defined_in_spec/index.yml new file mode 100644 index 00000000..df5b1314 --- /dev/null +++ b/tests/specs/issue_fix/79_response_status_codes_are_not_the_codes_defined_in_spec/index.yml @@ -0,0 +1,36 @@ +openapi: "3.0.0" +info: + version: 1.0.0 + title: 79_response_status_codes_are_not_the_codes_defined_in_spec +paths: + /mango/cake: + get: + responses: + '200': + description: The information + '403': + description: The information + '404': + description: The information + post: + responses: + '201': + description: The information + '403': + description: The information + '404': + description: The information + '422': + description: The information + +components: + schemas: + Address: + type: object + description: desc + properties: + id: + type: integer + name: + type: string + maxLength: 64 diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index ad3ff8fd..cda4e714 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -1014,4 +1014,18 @@ public function test22BugRulesRequiredIsGeneratedBeforeDefault() ]); $this->checkFiles($actualFiles, $expectedFiles); } + + // https://github.com/php-openapi/yii2-openapi/issues/79 + public function test79ResponseStatusCodesAreNotTheCodesDefinedInSpec() + { + $testFile = Yii::getAlias("@specs/issue_fix/79_response_status_codes_are_not_the_codes_defined_in_spec/index.php"); + $this->runGenerator($testFile); +// $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ +// 'recursive' => true, +// ]); +// $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/79_response_status_codes_are_not_the_codes_defined_in_spec/mysql"), [ +// 'recursive' => true, +// ]); +// $this->checkFiles($actualFiles, $expectedFiles); + } } From ecbee9432dc6581367e0983c338be3656d125af1 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Fri, 7 Mar 2025 18:19:17 +0530 Subject: [PATCH 355/358] Complete the test --- .../mysql/controllers/MangoController.php | 27 +++++++++++++++ .../controllers/base/MangoController.php | 34 +++++++++++++++++++ tests/unit/IssueFixTest.php | 14 ++++---- 3 files changed, 68 insertions(+), 7 deletions(-) create mode 100644 tests/specs/issue_fix/79_response_status_codes_are_not_the_codes_defined_in_spec/mysql/controllers/MangoController.php create mode 100644 tests/specs/issue_fix/79_response_status_codes_are_not_the_codes_defined_in_spec/mysql/controllers/base/MangoController.php diff --git a/tests/specs/issue_fix/79_response_status_codes_are_not_the_codes_defined_in_spec/mysql/controllers/MangoController.php b/tests/specs/issue_fix/79_response_status_codes_are_not_the_codes_defined_in_spec/mysql/controllers/MangoController.php new file mode 100644 index 00000000..4b3e60e3 --- /dev/null +++ b/tests/specs/issue_fix/79_response_status_codes_are_not_the_codes_defined_in_spec/mysql/controllers/MangoController.php @@ -0,0 +1,27 @@ + [ + 'class' => \yii\rest\OptionsAction::class, + ], + ]; + } + + /** + * Checks the privilege of the current user. + * + * This method checks whether the current user has the privilege + * to run the specified action against the specified data model. + * If the user does not have access, a [[ForbiddenHttpException]] should be thrown. + * + * @param string $action the ID of the action to be executed + * @param object $model the model to be accessed. If null, it means no specific model is being accessed. + * @param array $params additional parameters + * @throws \yii\web\ForbiddenHttpException if the user does not have access + */ + abstract public function checkAccess($action, $model = null, $params = []); + + abstract public function actionCake(); + + abstract public function actionCreateCake(); + +} diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index cda4e714..13bf8702 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -1020,12 +1020,12 @@ public function test79ResponseStatusCodesAreNotTheCodesDefinedInSpec() { $testFile = Yii::getAlias("@specs/issue_fix/79_response_status_codes_are_not_the_codes_defined_in_spec/index.php"); $this->runGenerator($testFile); -// $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ -// 'recursive' => true, -// ]); -// $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/79_response_status_codes_are_not_the_codes_defined_in_spec/mysql"), [ -// 'recursive' => true, -// ]); -// $this->checkFiles($actualFiles, $expectedFiles); + $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ + 'recursive' => true, + ]); + $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/79_response_status_codes_are_not_the_codes_defined_in_spec/mysql"), [ + 'recursive' => true, + ]); + $this->checkFiles($actualFiles, $expectedFiles); } } From 229c0034438060e562aee47ad230c9db564ea8ee Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Sat, 8 Mar 2025 07:31:40 +0530 Subject: [PATCH 356/358] Refactor --- src/lib/generators/ControllersGenerator.php | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/lib/generators/ControllersGenerator.php b/src/lib/generators/ControllersGenerator.php index e3ddcf23..372af037 100644 --- a/src/lib/generators/ControllersGenerator.php +++ b/src/lib/generators/ControllersGenerator.php @@ -129,8 +129,9 @@ protected function makeCustomController( $responseHttpStatusCodes = ''; foreach ($this->config->getOpenApi()->paths->getPaths()[$action->urlPath]->getOperations() as $verb => $operation) { - if ($verb === strtolower($action->requestMethod)) { - $responseHttpStatusCodes = implode(', ', array_keys($operation->responses->getResponses())); + $codes = array_keys($operation->responses->getResponses()); + if ($verb === strtolower($action->requestMethod) && $codes !== [200]) { + $responseHttpStatusCodes = implode(', ', $codes); } } @@ -141,7 +142,7 @@ protected function makeCustomController( $action->actionMethodName, $params, AbstractMemberGenerator::FLAG_PUBLIC, - '// TODO implement ' . $action->actionMethodName . PHP_EOL . '// In order to conform with OpenAPI spec, response of this action must have one of the following HTTP status code: ' . $responseHttpStatusCodes + '//TODO implement ' . $action->actionMethodName . ($responseHttpStatusCodes ? PHP_EOL . '// In order to conform with OpenAPI spec, response of this action must have one of the following HTTP status code: ' . $responseHttpStatusCodes : '') ); } $classFileGenerator->setClasses([$reflection]); From d89fe286ae94d906092e809d36d09e6a7ee8b844 Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Sat, 8 Mar 2025 08:12:43 +0530 Subject: [PATCH 357/358] Refactor and fix failing test --- src/lib/generators/ControllersGenerator.php | 12 ++++++++++-- .../specs/blog_v2/controllers/CommentController.php | 2 ++ .../pgsql/controllers/ContactController.php | 2 ++ .../pgsql/controllers/AccountController.php | 1 + .../mysql/controllers/MangoController.php | 4 ++-- 5 files changed, 17 insertions(+), 4 deletions(-) diff --git a/src/lib/generators/ControllersGenerator.php b/src/lib/generators/ControllersGenerator.php index 372af037..ea0c73c4 100644 --- a/src/lib/generators/ControllersGenerator.php +++ b/src/lib/generators/ControllersGenerator.php @@ -126,11 +126,19 @@ protected function makeCustomController( ]; $reflection->addMethod('checkAccess', $params, AbstractMemberGenerator::FLAG_PUBLIC, '//TODO implement checkAccess'); foreach ($abstractActions as $action) { - $responseHttpStatusCodes = ''; foreach ($this->config->getOpenApi()->paths->getPaths()[$action->urlPath]->getOperations() as $verb => $operation) { $codes = array_keys($operation->responses->getResponses()); - if ($verb === strtolower($action->requestMethod) && $codes !== [200]) { + + $only200OrDefault = false; + if ($codes === [200] || $codes === ['default']) { + $only200OrDefault = true; + } + if (in_array('default', $codes) && in_array(200, $codes) && count($codes) === 2) { + $only200OrDefault = true; + } + + if ($verb === strtolower($action->requestMethod) && !$only200OrDefault) { $responseHttpStatusCodes = implode(', ', $codes); } } diff --git a/tests/specs/blog_v2/controllers/CommentController.php b/tests/specs/blog_v2/controllers/CommentController.php index 0448ec72..c46307ed 100644 --- a/tests/specs/blog_v2/controllers/CommentController.php +++ b/tests/specs/blog_v2/controllers/CommentController.php @@ -18,6 +18,7 @@ public function actionListForPost($postId) public function actionCreateForPost($postId) { //TODO implement actionCreateForPost + // In order to conform with OpenAPI spec, response of this action must have one of the following HTTP status code: 201, default } public function actionViewForPost($slug, $id) @@ -28,6 +29,7 @@ public function actionViewForPost($slug, $id) public function actionDeleteForPost($slug, $id) { //TODO implement actionDeleteForPost + // In order to conform with OpenAPI spec, response of this action must have one of the following HTTP status code: 204 } public function actionUpdateForPost($slug, $id) diff --git a/tests/specs/issue_fix/163_generator_crash_when_using_reference_inside_an_object/pgsql/controllers/ContactController.php b/tests/specs/issue_fix/163_generator_crash_when_using_reference_inside_an_object/pgsql/controllers/ContactController.php index 10422b18..5f21cabb 100644 --- a/tests/specs/issue_fix/163_generator_crash_when_using_reference_inside_an_object/pgsql/controllers/ContactController.php +++ b/tests/specs/issue_fix/163_generator_crash_when_using_reference_inside_an_object/pgsql/controllers/ContactController.php @@ -13,11 +13,13 @@ public function checkAccess($action, $model = null, $params = []) public function actionListForAccount($accountId) { //TODO implement actionListForAccount + // In order to conform with OpenAPI spec, response of this action must have one of the following HTTP status code: 200, 403 } public function actionViewForAccount($accountId, $contactId) { //TODO implement actionViewForAccount + // In order to conform with OpenAPI spec, response of this action must have one of the following HTTP status code: 200, 403 } diff --git a/tests/specs/issue_fix/175_bug_allof_with_multiple_dollarrefs/pgsql/controllers/AccountController.php b/tests/specs/issue_fix/175_bug_allof_with_multiple_dollarrefs/pgsql/controllers/AccountController.php index b4044b8f..cfa4a6d3 100644 --- a/tests/specs/issue_fix/175_bug_allof_with_multiple_dollarrefs/pgsql/controllers/AccountController.php +++ b/tests/specs/issue_fix/175_bug_allof_with_multiple_dollarrefs/pgsql/controllers/AccountController.php @@ -13,6 +13,7 @@ public function checkAccess($action, $model = null, $params = []) public function actionView($id) { //TODO implement actionView + // In order to conform with OpenAPI spec, response of this action must have one of the following HTTP status code: 200, 404 } diff --git a/tests/specs/issue_fix/79_response_status_codes_are_not_the_codes_defined_in_spec/mysql/controllers/MangoController.php b/tests/specs/issue_fix/79_response_status_codes_are_not_the_codes_defined_in_spec/mysql/controllers/MangoController.php index 4b3e60e3..46c40ad1 100644 --- a/tests/specs/issue_fix/79_response_status_codes_are_not_the_codes_defined_in_spec/mysql/controllers/MangoController.php +++ b/tests/specs/issue_fix/79_response_status_codes_are_not_the_codes_defined_in_spec/mysql/controllers/MangoController.php @@ -12,13 +12,13 @@ public function checkAccess($action, $model = null, $params = []) public function actionCake() { - // TODO implement actionCake + //TODO implement actionCake // In order to conform with OpenAPI spec, response of this action must have one of the following HTTP status code: 200, 403, 404 } public function actionCreateCake() { - // TODO implement actionCreateCake + //TODO implement actionCreateCake // In order to conform with OpenAPI spec, response of this action must have one of the following HTTP status code: 201, 403, 404, 422 } From 4aa7668657b8f56a9c434c5e7c62d7961124081d Mon Sep 17 00:00:00 2001 From: Sohel Ahmed Mesaniya Date: Sat, 8 Mar 2025 10:24:38 +0530 Subject: [PATCH 358/358] Fix --- src/lib/SchemaToDatabase.php | 4 +- .../index.php | 13 ++ .../index.yml | 13 ++ .../mysql/models/BaseModelFaker.php | 144 ++++++++++++++++++ tests/unit/IssueFixTest.php | 14 ++ 5 files changed, 186 insertions(+), 2 deletions(-) create mode 100644 tests/specs/issue_fix/96_component_schema_should_be_optional/index.php create mode 100644 tests/specs/issue_fix/96_component_schema_should_be_optional/index.yml create mode 100644 tests/specs/issue_fix/96_component_schema_should_be_optional/mysql/models/BaseModelFaker.php diff --git a/src/lib/SchemaToDatabase.php b/src/lib/SchemaToDatabase.php index ccb230a3..beb27180 100644 --- a/src/lib/SchemaToDatabase.php +++ b/src/lib/SchemaToDatabase.php @@ -94,7 +94,7 @@ public function prepareModels(): array $openApi = $this->config->getOpenApi(); $junctions = $this->findJunctionSchemas(); - foreach ($openApi->components->schemas as $schemaName => $openApiSchema) { + foreach ($openApi->components->schemas ?? [] as $schemaName => $openApiSchema) { $schema = Yii::createObject(ComponentSchema::class, [$openApiSchema, $schemaName]); if (!$this->canGenerateModel($schemaName, $schema)) { @@ -153,7 +153,7 @@ public function findJunctionSchemas(): JunctionSchemas { $junctions = []; $openApi = $this->config->getOpenApi(); - foreach ($openApi->components->schemas as $schemaName => $openApiSchema) { + foreach ($openApi->components->schemas ?? [] as $schemaName => $openApiSchema) { /**@var ComponentSchema $schema */ $schema = Yii::createObject(ComponentSchema::class, [$openApiSchema, $schemaName]); if ($schema->isNonDb()) { diff --git a/tests/specs/issue_fix/96_component_schema_should_be_optional/index.php b/tests/specs/issue_fix/96_component_schema_should_be_optional/index.php new file mode 100644 index 00000000..34db291a --- /dev/null +++ b/tests/specs/issue_fix/96_component_schema_should_be_optional/index.php @@ -0,0 +1,13 @@ + '@specs/issue_fix/96_component_schema_should_be_optional/index.yml', + 'generateUrls' => false, + 'generateModels' => true, + 'excludeModels' => [ + 'Error', + ], + 'generateControllers' => false, + 'generateMigrations' => false, + 'generateModelFaker' => true, +]; diff --git a/tests/specs/issue_fix/96_component_schema_should_be_optional/index.yml b/tests/specs/issue_fix/96_component_schema_should_be_optional/index.yml new file mode 100644 index 00000000..5dcbc3cb --- /dev/null +++ b/tests/specs/issue_fix/96_component_schema_should_be_optional/index.yml @@ -0,0 +1,13 @@ +openapi: "3.0.0" +info: + version: 1.0.0 + title: 96_component_schema_should_be_optional + +paths: + /: + get: + summary: List + operationId: list + responses: + '200': + description: The information diff --git a/tests/specs/issue_fix/96_component_schema_should_be_optional/mysql/models/BaseModelFaker.php b/tests/specs/issue_fix/96_component_schema_should_be_optional/mysql/models/BaseModelFaker.php new file mode 100644 index 00000000..c367fbb4 --- /dev/null +++ b/tests/specs/issue_fix/96_component_schema_should_be_optional/mysql/models/BaseModelFaker.php @@ -0,0 +1,144 @@ +faker = FakerFactory::create(str_replace('-', '_', \Yii::$app->language)); + $this->uniqueFaker = new UniqueGenerator($this->faker); + } + + abstract public function generateModel($attributes = []); + + public function getFaker():Generator + { + return $this->faker; + } + + public function getUniqueFaker():UniqueGenerator + { + return $this->uniqueFaker; + } + + public function setFaker(Generator $faker):void + { + $this->faker = $faker; + } + + public function setUniqueFaker(UniqueGenerator $faker):void + { + $this->uniqueFaker = $faker; + } + + /** + * Generate and return model + * @param array|callable $attributes + * @param UniqueGenerator|null $uniqueFaker + * @return \yii\db\ActiveRecord + * @example MyFaker::makeOne(['user_id' => 1, 'title' => 'foo']); + * @example MyFaker::makeOne( function($model, $faker) { + * $model->scenario = 'create'; + * $model->setAttributes(['user_id' => 1, 'title' => $faker->sentence]); + * return $model; + * }); + */ + public static function makeOne($attributes = [], ?UniqueGenerator $uniqueFaker = null) + { + $fakeBuilder = new static(); + if ($uniqueFaker !== null) { + $fakeBuilder->setUniqueFaker($uniqueFaker); + } + $model = $fakeBuilder->generateModel($attributes); + return $model; + } + + /** + * Generate, save and return model + * @param array|callable $attributes + * @param UniqueGenerator|null $uniqueFaker + * @return \yii\db\ActiveRecord + * @example MyFaker::saveOne(['user_id' => 1, 'title' => 'foo']); + * @example MyFaker::saveOne( function($model, $faker) { + * $model->scenario = 'create'; + * $model->setAttributes(['user_id' => 1, 'title' => $faker->sentence]); + * return $model; + * }); + */ + public static function saveOne($attributes = [], ?UniqueGenerator $uniqueFaker = null) + { + $model = static::makeOne($attributes, $uniqueFaker); + $model->save(); + return $model; + } + + /** + * Generate and return multiple models + * @param int $number + * @param array|callable $commonAttributes + * @return \yii\db\ActiveRecord[]|array + * @example TaskFaker::make(5, ['project_id'=>1, 'user_id' => 2]); + * @example TaskFaker::make(5, function($model, $faker, $uniqueFaker) { + * $model->setAttributes(['name' => $uniqueFaker->username, 'state'=>$faker->boolean(20)]); + * return $model; + * }); + */ + public static function make(int $number, $commonAttributes = [], ?UniqueGenerator $uniqueFaker = null):array + { + if ($number < 1) { + return []; + } + $fakeBuilder = new static(); + if ($uniqueFaker !== null) { + $fakeBuilder->setUniqueFaker($uniqueFaker); + } + return array_map(function () use ($commonAttributes, $fakeBuilder) { + $model = $fakeBuilder->generateModel($commonAttributes); + return $model; + }, range(0, $number -1)); + } + + /** + * Generate, save and return multiple models + * @param int $number + * @param array|callable $commonAttributes + * @return \yii\db\ActiveRecord[]|array + * @example TaskFaker::save(5, ['project_id'=>1, 'user_id' => 2]); + * @example TaskFaker::save(5, function($model, $faker, $uniqueFaker) { + * $model->setAttributes(['name' => $uniqueFaker->username, 'state'=>$faker->boolean(20)]); + * return $model; + * }); + */ + public static function save(int $number, $commonAttributes = [], ?UniqueGenerator $uniqueFaker = null):array + { + if ($number < 1) { + return []; + } + $fakeBuilder = new static(); + if ($uniqueFaker !== null) { + $fakeBuilder->setUniqueFaker($uniqueFaker); + } + return array_map(function () use ($commonAttributes, $fakeBuilder) { + $model = $fakeBuilder->generateModel($commonAttributes); + $model->save(); + return $model; + }, range(0, $number -1)); + } +} diff --git a/tests/unit/IssueFixTest.php b/tests/unit/IssueFixTest.php index ad3ff8fd..c92d1f70 100644 --- a/tests/unit/IssueFixTest.php +++ b/tests/unit/IssueFixTest.php @@ -1014,4 +1014,18 @@ public function test22BugRulesRequiredIsGeneratedBeforeDefault() ]); $this->checkFiles($actualFiles, $expectedFiles); } + + // https://github.com/php-openapi/yii2-openapi/issues/96 + public function test96ComponentSchemaShouldBeOptional() + { + $testFile = Yii::getAlias("@specs/issue_fix/96_component_schema_should_be_optional/index.php"); + $this->runGenerator($testFile); + $actualFiles = FileHelper::findFiles(Yii::getAlias('@app'), [ + 'recursive' => true, + ]); + $expectedFiles = FileHelper::findFiles(Yii::getAlias("@specs/issue_fix/96_component_schema_should_be_optional/mysql"), [ + 'recursive' => true, + ]); + $this->checkFiles($actualFiles, $expectedFiles); + } }