Skip to content

feat: INSERT...SELECT syntax implementation. #54

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

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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
13 changes: 10 additions & 3 deletions src/Parser/InsertParser.php
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
<?php

namespace Vimeo\MysqlEngine\Parser;

use Vimeo\MysqlEngine\Query\Expression\Expression;
use Vimeo\MysqlEngine\TokenType;
use Vimeo\MysqlEngine\Query\InsertQuery;
use Vimeo\MysqlEngine\TokenType;

final class InsertParser
{
Expand Down Expand Up @@ -130,6 +131,12 @@ public function parse()
list($this->pointer, $query->setClause) = $p->parse();
break;

case 'SELECT':
$select_parser = new SelectParser($this->pointer, $this->tokens, $this->sql);
$query->selectQuery = $select_parser->parse();
$this->pointer = $select_parser->getPointer();
break;

default:
throw new ParserException("Unexpected clause {$token->value}");
}
Expand Down Expand Up @@ -168,7 +175,7 @@ public function parse()
} else {
if ($this->currentClause === 'COLUMN_LIST' && $needs_comma && $token->value === ')') {
$needs_comma = false;
if (($this->tokens[$this->pointer + 1]->value ?? null) !== 'VALUES') {
if (!in_array($this->tokens[$this->pointer + 1]->value ?? null, ['VALUES', 'SELECT'])) {
throw new ParserException("Expected VALUES after insert column list");
}
break;
Expand Down Expand Up @@ -203,7 +210,7 @@ public function parse()

$this->pointer++;
}
if ((!$query->insertColumns || !$query->values) && !$query->setClause) {
if ((!$query->insertColumns || !$query->values) && !$query->setClause && !$query->selectQuery) {
throw new ParserException("Missing values to insert");
}
return $query;
Expand Down
6 changes: 6 additions & 0 deletions src/Parser/SelectParser.php
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
<?php

namespace Vimeo\MysqlEngine\Parser;

use Vimeo\MysqlEngine\Query\Expression\ColumnExpression;
Expand Down Expand Up @@ -48,6 +49,11 @@ public function __construct(int $pointer, array $tokens, string $sql)
$this->sql = $sql;
}

public function getPointer(): int
{
return $this->pointer;
}

public function parse() : SelectQuery
{
// if the first part of this query is nested, we should be able to unwrap it safely
Expand Down
56 changes: 55 additions & 1 deletion src/Processor/InsertProcessor.php
Original file line number Diff line number Diff line change
@@ -1,13 +1,18 @@
<?php

namespace Vimeo\MysqlEngine\Processor;

use Vimeo\MysqlEngine\DataIntegrity;
use Vimeo\MysqlEngine\Query\Expression\ColumnExpression;
use Vimeo\MysqlEngine\Query\InsertQuery;
use Vimeo\MysqlEngine\Schema\Column\IntegerColumn;

final class InsertProcessor extends Processor
{
/**
* @throws SQLFakeUniqueKeyViolation
* @throws ProcessorException
* @throws \Exception
*/
public static function process(
\Vimeo\MysqlEngine\FakePdoInterface $conn,
Scope $scope,
Expand Down Expand Up @@ -108,6 +113,55 @@ public static function process(
);
}

if ($stmt->selectQuery) {
$selectResult = SelectProcessor::process(
$conn,
$scope,
$stmt->selectQuery
)->rows;

foreach ($selectResult as $selected_param) {
$row = [];
foreach ($stmt->selectQuery->selectExpressions as $index => $expr) {
if (key_exists($index, $stmt->insertColumns)
&& (is_string($selected_param[$expr->name]) || is_int($selected_param[$expr->name]))) {
$row[$stmt->insertColumns[$index]] = $selected_param[$expr->name];
}
}

$row = DataIntegrity::coerceToSchema($conn, $row, $table_definition);

$result = DataIntegrity::checkUniqueConstraints($table, $row, $table_definition);

if ($result !== null) {
throw new SQLFakeUniqueKeyViolation($result[0]);
}

/**
* @psalm-suppress MixedAssignment
*/
foreach ($row as $column_name => $value) {
$column = $table_definition->columns[$column_name];

if ($column instanceof IntegerColumn && $column->isAutoIncrement() && is_int($value)) {
$last_incremented_value = $conn->getServer()->addAutoIncrementMinValue(
$database,
$table_name,
$column_name,
$value
);
}
}

$table[] = $row;
}

$conn->getServer()->saveTable($database, $table_name, $table);
$conn->setLastInsertId((string)($last_incremented_value ?? 0));

return count($selectResult);
}

return $rows_affected;
}
}
4 changes: 4 additions & 0 deletions src/Query/InsertQuery.php
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
<?php

namespace Vimeo\MysqlEngine\Query;

use Vimeo\MysqlEngine\Query\Expression\BinaryOperatorExpression;
Expand Down Expand Up @@ -41,6 +42,9 @@ final class InsertQuery
*/
public $setClause = null;

/** @var SelectQuery|null $selectExpression */
public $selectQuery = null;

public function __construct(string $table, string $sql, bool $ignoreDupes)
{
$this->table = $table;
Expand Down
34 changes: 34 additions & 0 deletions tests/EndToEndTest.php
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
<?php
namespace Vimeo\MysqlEngine\Tests;

use PDO;
use PDOException;

class EndToEndTest extends \PHPUnit\Framework\TestCase
Expand Down Expand Up @@ -911,6 +912,39 @@ public function testInsertWithNullAndEmpty()
);
}

public function testInsertWithSelect(): void
{
$pdo = self::getConnectionToFullDB(false);

$query = $pdo->prepare(
"INSERT INTO `video_game_characters`
(`name`, `type`, `profession`, `console`, `is_alive`, `powerups`, `skills`, `created_on`)
SELECT
'wario','villain','plumber','nes','1','3','{\"magic\":0, \"speed\":0, \"strength\":0, \"weapons\":0}', NOW(),
FROM `video_game_characters`"
);

$query->execute();

self::assertEquals($pdo->lastInsertId(), 32);

$query = $pdo->prepare(
'SELECT `id`, `name`
FROM `video_game_characters`
ORDER BY `id` DESC
LIMIT 1'
);

$query->execute();

$this->assertSame(
[
['id' => 32, 'name' => 'wario'],
],
$query->fetchAll(PDO::FETCH_ASSOC)
);
}

public function testOrderBySecondDimensionAliased()
{
$pdo = self::getConnectionToFullDB(false);
Expand Down
Loading