Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor getForeignKeys() #584

Merged
merged 2 commits into from
Sep 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 17 additions & 17 deletions phpstan-baseline.neon
Original file line number Diff line number Diff line change
Expand Up @@ -475,6 +475,16 @@ parameters:
count: 2
path: src/Statements/CallStatement.php

-
message: "#^Cannot access property \\$database on PhpMyAdmin\\\\SqlParser\\\\Components\\\\Expression\\|null\\.$#"
count: 1
path: src/Statements/CreateStatement.php

-
message: "#^Cannot access property \\$table on PhpMyAdmin\\\\SqlParser\\\\Components\\\\Expression\\|null\\.$#"
count: 1
path: src/Statements/CreateStatement.php

-
message: "#^Cannot access property \\$value on PhpMyAdmin\\\\SqlParser\\\\Token\\|null\\.$#"
count: 2
Expand All @@ -497,14 +507,19 @@ parameters:

-
message: "#^Cannot call method has\\(\\) on PhpMyAdmin\\\\SqlParser\\\\Components\\\\OptionsArray\\|null\\.$#"
count: 8
count: 11
path: src/Statements/CreateStatement.php

-
message: "#^Parameter \\#1 \\$component of static method PhpMyAdmin\\\\SqlParser\\\\Parsers\\\\ParameterDefinitions\\:\\:buildAll\\(\\) expects array\\<PhpMyAdmin\\\\SqlParser\\\\Components\\\\ParameterDefinition\\>, array\\<PhpMyAdmin\\\\SqlParser\\\\Components\\\\ParameterDefinition\\>\\|null given\\.$#"
count: 1
path: src/Statements/CreateStatement.php

-
message: "#^Parameter \\#3 \\$subject of function str_replace expects array\\|string, mixed given\\.$#"
count: 2
path: src/Statements/CreateStatement.php

-
message: "#^Property PhpMyAdmin\\\\SqlParser\\\\Statements\\\\CreateStatement\\:\\:\\$fields \\(array\\<PhpMyAdmin\\\\SqlParser\\\\Components\\\\CreateDefinition\\>\\|PhpMyAdmin\\\\SqlParser\\\\Components\\\\ArrayObj\\|null\\) does not accept array\\<PhpMyAdmin\\\\SqlParser\\\\Component\\>\\|PhpMyAdmin\\\\SqlParser\\\\Components\\\\ArrayObj\\.$#"
count: 1
Expand Down Expand Up @@ -875,31 +890,16 @@ parameters:
count: 1
path: src/Utils/Query.php

-
message: "#^Cannot access property \\$database on PhpMyAdmin\\\\SqlParser\\\\Components\\\\Expression\\|null\\.$#"
count: 1
path: src/Utils/Table.php

-
message: "#^Cannot access property \\$table on PhpMyAdmin\\\\SqlParser\\\\Components\\\\Expression\\|null\\.$#"
count: 1
path: src/Utils/Table.php

-
message: "#^Cannot call method has\\(\\) on PhpMyAdmin\\\\SqlParser\\\\Components\\\\OptionsArray\\|null\\.$#"
count: 4
count: 1
path: src/Utils/Table.php

-
message: "#^Method PhpMyAdmin\\\\SqlParser\\\\Utils\\\\Table\\:\\:getFields\\(\\) should return array\\<string, array\\{type\\: string, timestamp_not_null\\: bool, default_value\\?\\: mixed, default_current_timestamp\\?\\: true, on_update_current_timestamp\\?\\: true, expr\\?\\: mixed\\}\\> but returns array\\<string, array\\{default_current_timestamp\\?\\: true, default_value\\?\\: mixed, expr\\?\\: mixed, on_update_current_timestamp\\?\\: true, timestamp_not_null\\: bool, type\\: string\\|null\\}\\>\\.$#"
count: 1
path: src/Utils/Table.php

-
message: "#^Parameter \\#3 \\$subject of function str_replace expects array\\|string, mixed given\\.$#"
count: 2
path: src/Utils/Table.php

-
message: "#^Parameter \\#2 \\$list of static method PhpMyAdmin\\\\SqlParser\\\\Utils\\\\Query\\:\\:replaceClause\\(\\) expects PhpMyAdmin\\\\SqlParser\\\\TokensList, PhpMyAdmin\\\\SqlParser\\\\TokensList\\|null given\\.$#"
count: 1
Expand Down
39 changes: 26 additions & 13 deletions psalm-baseline.xml
Original file line number Diff line number Diff line change
Expand Up @@ -679,19 +679,31 @@
</file>
<file src="src/Statements/CreateStatement.php">
<MixedArgument>
<code><![CDATA[$opt]]></code>
<code><![CDATA[$opt]]></code>
<code><![CDATA[$this->$field]]></code>
</MixedArgument>
<MixedAssignment>
<code><![CDATA[$opt]]></code>
<code><![CDATA[$opt]]></code>
</MixedAssignment>
<MixedOperand>
<code><![CDATA[$this->$field]]></code>
</MixedOperand>
<PossiblyFalseOperand>
<code><![CDATA[$brackets]]></code>
<code><![CDATA[$brackets]]></code>
</PossiblyFalseOperand>
<PossiblyInvalidPropertyAssignmentValue>
<code><![CDATA[str_replace(' ', '_', $opt)]]></code>
<code><![CDATA[str_replace(' ', '_', $opt)]]></code>
</PossiblyInvalidPropertyAssignmentValue>
<PossiblyNullArgument>
<code><![CDATA[$this->parameters]]></code>
</PossiblyNullArgument>
<PossiblyNullPropertyFetch>
<code><![CDATA[$field->references->table->database]]></code>
<code><![CDATA[$field->references->table->table]]></code>
<code><![CDATA[$token->value]]></code>
<code><![CDATA[$token->value]]></code>
</PossiblyNullPropertyFetch>
Expand All @@ -713,6 +725,8 @@
<code><![CDATA[build]]></code>
<code><![CDATA[has]]></code>
<code><![CDATA[has]]></code>
<code><![CDATA[has]]></code>
<code><![CDATA[has]]></code>
</PossiblyNullReference>
<PropertyTypeCoercion>
<code><![CDATA[$token->value]]></code>
Expand All @@ -725,6 +739,7 @@
<code><![CDATA[ArrayObjs::parse($parser, $list)]]></code>
</PropertyTypeCoercion>
<RiskyTruthyFalsyComparison>
<code><![CDATA[empty($this->fields)]]></code>
<code><![CDATA[empty($this->partitionBy)]]></code>
<code><![CDATA[empty($this->partitionBy)]]></code>
<code><![CDATA[empty($this->partitions)]]></code>
Expand Down Expand Up @@ -1022,6 +1037,17 @@
<code><![CDATA[$obj instanceof Parser]]></code>
</RedundantConditionGivenDocblockType>
</file>
<file src="src/Utils/ForeignKey.php">
<PossiblyUnusedProperty>
<code><![CDATA[$constraint]]></code>
<code><![CDATA[$indexList]]></code>
<code><![CDATA[$onDelete]]></code>
<code><![CDATA[$onUpdate]]></code>
<code><![CDATA[$refDbName]]></code>
<code><![CDATA[$refIndexList]]></code>
<code><![CDATA[$refTableName]]></code>
</PossiblyUnusedProperty>
</file>
<file src="src/Utils/Formatter.php">
<InvalidArrayOffset>
<code><![CDATA[JoinKeyword::JOINS[$list->tokens[$list->idx - 2]->value]]]></code>
Expand Down Expand Up @@ -1165,13 +1191,7 @@
<LessSpecificReturnStatement>
<code><![CDATA[$ret]]></code>
</LessSpecificReturnStatement>
<MixedArgument>
<code><![CDATA[$opt]]></code>
<code><![CDATA[$opt]]></code>
</MixedArgument>
<MixedAssignment>
<code><![CDATA[$opt]]></code>
<code><![CDATA[$opt]]></code>
<code><![CDATA[$option]]></code>
<code><![CDATA[$option]]></code>
<code><![CDATA[$option]]></code>
Expand All @@ -1196,18 +1216,11 @@
<code><![CDATA[$ret]]></code>
<code><![CDATA[$ret]]></code>
</PossiblyNullArrayOffset>
<PossiblyNullPropertyFetch>
<code><![CDATA[$field->references->table->database]]></code>
<code><![CDATA[$field->references->table->table]]></code>
</PossiblyNullPropertyFetch>
<PossiblyNullReference>
<code><![CDATA[has]]></code>
<code><![CDATA[has]]></code>
<code><![CDATA[has]]></code>
</PossiblyNullReference>
<RiskyTruthyFalsyComparison>
<code><![CDATA[empty($statement->fields)]]></code>
<code><![CDATA[empty($statement->fields)]]></code>
</RiskyTruthyFalsyComparison>
</file>
<file src="tests/Builder/AlterStatementTest.php">
Expand Down
53 changes: 53 additions & 0 deletions src/Statements/CreateStatement.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,10 @@
use PhpMyAdmin\SqlParser\Token;
use PhpMyAdmin\SqlParser\TokensList;
use PhpMyAdmin\SqlParser\TokenType;
use PhpMyAdmin\SqlParser\Utils\ForeignKey;

use function is_array;
use function str_replace;
use function trim;

/**
Expand Down Expand Up @@ -425,7 +427,7 @@
$partition = '';

if (! empty($this->partitionBy)) {
$partition .= "\nPARTITION BY " . $this->partitionBy;

Check warning on line 430 in src/Statements/CreateStatement.php

View workflow job for this annotation

GitHub Actions / Mutation tests with PHP 8.2

Escaped Mutant for Mutator "Assignment": --- Original +++ New @@ @@ } $partition = ''; if (!empty($this->partitionBy)) { - $partition .= "\nPARTITION BY " . $this->partitionBy; + $partition = "\nPARTITION BY " . $this->partitionBy; } if (!empty($this->partitionsNum)) { $partition .= "\nPARTITIONS " . $this->partitionsNum;
}

if (! empty($this->partitionsNum)) {
Expand Down Expand Up @@ -460,12 +462,12 @@
$builtStatement = $this->with->build();
}

return 'CREATE '

Check warning on line 465 in src/Statements/CreateStatement.php

View workflow job for this annotation

GitHub Actions / Mutation tests with PHP 8.2

Escaped Mutant for Mutator "Concat": --- Original +++ New @@ @@ } elseif ($this->with !== null) { $builtStatement = $this->with->build(); } - return 'CREATE ' . $this->options->build() . ' ' . $this->name->build() . ' ' . $fields . ' AS ' . $builtStatement . TokensList::buildFromArray($this->body) . ' ' . ($this->entityOptions?->build() ?? ''); + return 'CREATE ' . $this->options->build() . ' ' . $this->name->build() . ' ' . $fields . ' AS ' . $builtStatement . TokensList::buildFromArray($this->body) . ($this->entityOptions?->build() ?? '') . ' '; } if ($this->options->has('TRIGGER')) { return 'CREATE ' . $this->options->build() . ' ' . $this->name->build() . ' ' . $this->entityOptions->build() . ' ' . 'ON ' . $this->table->build() . ' ' . 'FOR EACH ROW ' . TokensList::buildFromArray($this->body);

Check warning on line 465 in src/Statements/CreateStatement.php

View workflow job for this annotation

GitHub Actions / Mutation tests with PHP 8.2

Escaped Mutant for Mutator "ConcatOperandRemoval": --- Original +++ New @@ @@ } elseif ($this->with !== null) { $builtStatement = $this->with->build(); } - return 'CREATE ' . $this->options->build() . ' ' . $this->name->build() . ' ' . $fields . ' AS ' . $builtStatement . TokensList::buildFromArray($this->body) . ' ' . ($this->entityOptions?->build() ?? ''); + return 'CREATE ' . $this->options->build() . ' ' . $this->name->build() . ' ' . $fields . ' AS ' . $builtStatement . TokensList::buildFromArray($this->body) . ' '; } if ($this->options->has('TRIGGER')) { return 'CREATE ' . $this->options->build() . ' ' . $this->name->build() . ' ' . $this->entityOptions->build() . ' ' . 'ON ' . $this->table->build() . ' ' . 'FOR EACH ROW ' . TokensList::buildFromArray($this->body);
. $this->options->build() . ' '
. $this->name->build() . ' '
. $fields . ' AS ' . $builtStatement
. TokensList::buildFromArray($this->body) . ' '
. ($this->entityOptions?->build() ?? '');

Check warning on line 470 in src/Statements/CreateStatement.php

View workflow job for this annotation

GitHub Actions / Mutation tests with PHP 8.2

Escaped Mutant for Mutator "Coalesce": --- Original +++ New @@ @@ } elseif ($this->with !== null) { $builtStatement = $this->with->build(); } - return 'CREATE ' . $this->options->build() . ' ' . $this->name->build() . ' ' . $fields . ' AS ' . $builtStatement . TokensList::buildFromArray($this->body) . ' ' . ($this->entityOptions?->build() ?? ''); + return 'CREATE ' . $this->options->build() . ' ' . $this->name->build() . ' ' . $fields . ' AS ' . $builtStatement . TokensList::buildFromArray($this->body) . ' ' . ('' ?? $this->entityOptions?->build()); } if ($this->options->has('TRIGGER')) { return 'CREATE ' . $this->options->build() . ' ' . $this->name->build() . ' ' . $this->entityOptions->build() . ' ' . 'ON ' . $this->table->build() . ' ' . 'FOR EACH ROW ' . TokensList::buildFromArray($this->body);
}

if ($this->options->has('TRIGGER')) {
Expand Down Expand Up @@ -532,7 +534,7 @@
* Token parsed at this moment.
*/
$token = $list->tokens[$list->idx];
$nextidx = $list->idx + 1;

Check warning on line 537 in src/Statements/CreateStatement.php

View workflow job for this annotation

GitHub Actions / Mutation tests with PHP 8.2

Escaped Mutant for Mutator "IncrementInteger": --- Original +++ New @@ @@ * Token parsed at this moment. */ $token = $list->tokens[$list->idx]; - $nextidx = $list->idx + 1; + $nextidx = $list->idx + 2; while ($nextidx < $list->count && $list->tokens[$nextidx]->type === TokenType::Whitespace) { ++$nextidx; }
while ($nextidx < $list->count && $list->tokens[$nextidx]->type === TokenType::Whitespace) {
++$nextidx;
}
Expand All @@ -547,7 +549,7 @@
/* CREATE TABLE WITH */
$this->with = new WithStatement($parser, $list);
} elseif (
($token->type === TokenType::Keyword) && ($token->keyword === 'AS')

Check warning on line 552 in src/Statements/CreateStatement.php

View workflow job for this annotation

GitHub Actions / Mutation tests with PHP 8.2

Escaped Mutant for Mutator "LogicalAnd": --- Original +++ New @@ @@ } elseif ($token->type === TokenType::Keyword && $token->keyword === 'WITH') { /* CREATE TABLE WITH */ $this->with = new WithStatement($parser, $list); - } elseif ($token->type === TokenType::Keyword && $token->keyword === 'AS' && $list->tokens[$nextidx]->type === TokenType::Keyword) { + } elseif (($token->type === TokenType::Keyword || $token->keyword === 'AS') && $list->tokens[$nextidx]->type === TokenType::Keyword) { if ($list->tokens[$nextidx]->value === 'SELECT') { /* CREATE TABLE ... AS SELECT */ $list->idx = $nextidx;
&& ($list->tokens[$nextidx]->type === TokenType::Keyword)
) {
if ($list->tokens[$nextidx]->value === 'SELECT') {
Expand All @@ -559,7 +561,7 @@
$list->idx = $nextidx;
$this->with = new WithStatement($parser, $list);
}
} elseif ($token->type === TokenType::Keyword && $token->keyword === 'LIKE') {

Check warning on line 564 in src/Statements/CreateStatement.php

View workflow job for this annotation

GitHub Actions / Mutation tests with PHP 8.2

Escaped Mutant for Mutator "LogicalAnd": --- Original +++ New @@ @@ $list->idx = $nextidx; $this->with = new WithStatement($parser, $list); } - } elseif ($token->type === TokenType::Keyword && $token->keyword === 'LIKE') { + } elseif ($token->type === TokenType::Keyword || $token->keyword === 'LIKE') { /* CREATE TABLE `new_tbl` LIKE 'orig_tbl' */ $list->idx = $nextidx; $this->like = Expressions::parse($parser, $list, ['parseField' => 'table', 'breakOnAlias' => true]);
/* CREATE TABLE `new_tbl` LIKE 'orig_tbl' */
$list->idx = $nextidx;
$this->like = Expressions::parse(
Expand All @@ -567,7 +569,7 @@
$list,
[
'parseField' => 'table',
'breakOnAlias' => true,

Check warning on line 572 in src/Statements/CreateStatement.php

View workflow job for this annotation

GitHub Actions / Mutation tests with PHP 8.2

Escaped Mutant for Mutator "TrueValue": --- Original +++ New @@ @@ } elseif ($token->type === TokenType::Keyword && $token->keyword === 'LIKE') { /* CREATE TABLE `new_tbl` LIKE 'orig_tbl' */ $list->idx = $nextidx; - $this->like = Expressions::parse($parser, $list, ['parseField' => 'table', 'breakOnAlias' => true]); + $this->like = Expressions::parse($parser, $list, ['parseField' => 'table', 'breakOnAlias' => false]); // The 'LIKE' keyword was found, but no table_name was found next to it if ($this->like === null) { $parser->error('A table name was expected.', $list->tokens[$list->idx]);
],
);
// The 'LIKE' keyword was found, but no table_name was found next to it
Expand Down Expand Up @@ -595,12 +597,12 @@
* previously. At least one bracket is required to validate the
* expression.
*/
$brackets = false;

Check warning on line 600 in src/Statements/CreateStatement.php

View workflow job for this annotation

GitHub Actions / Mutation tests with PHP 8.2

Escaped Mutant for Mutator "FalseValue": --- Original +++ New @@ @@ * previously. At least one bracket is required to validate the * expression. */ - $brackets = false; + $brackets = true; /* * Handles partitions. */

/*
* Handles partitions.
*/
for (; $list->idx < $list->count; ++$list->idx) {

Check warning on line 605 in src/Statements/CreateStatement.php

View workflow job for this annotation

GitHub Actions / Mutation tests with PHP 8.2

Escaped Mutant for Mutator "LessThan": --- Original +++ New @@ @@ /* * Handles partitions. */ - for (; $list->idx < $list->count; ++$list->idx) { + for (; $list->idx <= $list->count; ++$list->idx) { /** * Token parsed at this moment. */
/**
* Token parsed at this moment.
*/
Expand Down Expand Up @@ -775,4 +777,55 @@
}
}
}

/** @return list<ForeignKey> */
public function getForeignKeys(): array
{
if (empty($this->fields) || (! is_array($this->fields)) || (! $this->options->has('TABLE'))) {
return [];
}

$ret = [];

foreach ($this->fields as $field) {
if ($field->key === null || $field->key->type !== 'FOREIGN KEY') {
continue;
}

$columns = [];
foreach ($field->key->columns as $column) {
if (! isset($column['name'])) {
continue;
}

$columns[] = $column['name'];
}

$foreignKey = new ForeignKey();
$foreignKey->constraint = $field->name;
$foreignKey->indexList = $columns;

if ($field->references !== null) {
$foreignKey->refDbName = $field->references->table->database;
$foreignKey->refTableName = $field->references->table->table;
$foreignKey->refIndexList = $field->references->columns;

$opt = $field->references->options->has('ON UPDATE');

if ($opt) {
$foreignKey->onUpdate = str_replace(' ', '_', $opt);
}

$opt = $field->references->options->has('ON DELETE');

if ($opt) {
$foreignKey->onDelete = str_replace(' ', '_', $opt);
}
}

$ret[] = $foreignKey;
}

return $ret;
}
}
23 changes: 23 additions & 0 deletions src/Utils/ForeignKey.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?php

declare(strict_types=1);

namespace PhpMyAdmin\SqlParser\Utils;

final class ForeignKey
{
/**
* @param (int|string)[] $indexList
* @param string[] $refIndexList
*/
public function __construct(
public string|null $constraint = null,
public array $indexList = [],
public string|null $refDbName = null,
public string|null $refTableName = null,
public array $refIndexList = [],
public string|null $onUpdate = null,
public string|null $onDelete = null,
) {
}
}
66 changes: 0 additions & 66 deletions src/Utils/Table.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,78 +7,12 @@
use PhpMyAdmin\SqlParser\Statements\CreateStatement;

use function is_array;
use function str_replace;

/**
* Table utilities.
*/
class Table
{
/**
* Gets the foreign keys of the table.
*
* @return list<(string|string[]|null)[]>
* @psalm-return list<array{
* constraint: string|null,
* index_list: (int|string)[],
* ref_db_name?: string|null,
* ref_table_name?: string|null,
* ref_index_list?: string[],
* on_update?: string|string[],
* on_delete?: string|string[],
* }>
*/
public static function getForeignKeys(CreateStatement $statement): array
{
if (empty($statement->fields) || (! is_array($statement->fields)) || (! $statement->options->has('TABLE'))) {
return [];
}

$ret = [];

foreach ($statement->fields as $field) {
if (empty($field->key) || ($field->key->type !== 'FOREIGN KEY')) {
continue;
}

$columns = [];
foreach ($field->key->columns as $column) {
if (! isset($column['name'])) {
continue;
}

$columns[] = $column['name'];
}

$tmp = [
'constraint' => $field->name,
'index_list' => $columns,
];

if (! empty($field->references)) {
$tmp['ref_db_name'] = $field->references->table->database;
$tmp['ref_table_name'] = $field->references->table->table;
$tmp['ref_index_list'] = $field->references->columns;

$opt = $field->references->options->has('ON UPDATE');

if ($opt) {
$tmp['on_update'] = str_replace(' ', '_', $opt);
}

$opt = $field->references->options->has('ON DELETE');

if ($opt) {
$tmp['on_delete'] = str_replace(' ', '_', $opt);
}
}

$ret[] = $tmp;
}

return $ret;
}

/**
* Gets fields of the table.
*
Expand Down
Loading
Loading