Skip to content

Commit

Permalink
Output rawSql() for execute() method (#230)
Browse files Browse the repository at this point in the history
  • Loading branch information
Tigrov committed Nov 7, 2023
1 parent 5ae8c9d commit d227ecd
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 7 deletions.
11 changes: 7 additions & 4 deletions src/MigrationBuilder.php
Expand Up @@ -20,6 +20,7 @@
use function rtrim;
use function sprintf;
use function substr;
use function trim;

final class MigrationBuilder extends AbstractMigrationBuilder
{
Expand Down Expand Up @@ -52,13 +53,15 @@ public function getDb(): ConnectionInterface
*/
public function execute(string $sql, array $params = []): void
{
$sqlOutput = $sql;
if ($this->maxSqlOutputLength !== null && $this->maxSqlOutputLength < strlen($sql)) {
$sqlOutput = ltrim(rtrim(substr($sql, 0, $this->maxSqlOutputLength)) . ' [... hidden]');
$command = $this->db->createCommand($sql)->bindValues($params);
$sqlOutput = trim($command->getRawSql());

if ($this->maxSqlOutputLength !== null && $this->maxSqlOutputLength < strlen($sqlOutput)) {
$sqlOutput = ltrim(rtrim(substr($sqlOutput, 0, $this->maxSqlOutputLength)) . ' [... hidden]');
}

$time = $this->beginCommand("Execute SQL: $sqlOutput");
$this->db->createCommand($sql)->bindValues($params)->execute();
$command->execute();
$this->endCommand($time);
}

Expand Down
8 changes: 6 additions & 2 deletions tests/Common/AbstractMigrationBuilderTest.php
Expand Up @@ -31,10 +31,14 @@ protected function setUp(): void
public function testExecute(): void
{
$this->builder->createTable('test', ['id' => $this->builder->integer()]);
$this->builder->execute('DROP TABLE {{test}}');

$sql = 'DROP TABLE {{test}}';
$this->builder->execute($sql);

$sqlOutput = $this->db->getQuoter()->quoteSql($sql);

$this->assertEmpty($this->db->getTableSchema('test_table'));
$this->assertInformerOutputContains(' > Execute SQL: DROP TABLE {{test}} ... Done in ');
$this->assertInformerOutputContains(" > Execute SQL: $sqlOutput ... Done in ");
}

public function testInsert(): void
Expand Down
2 changes: 1 addition & 1 deletion tests/Support/Migrations/M231015155500ExecuteSql.php
Expand Up @@ -17,7 +17,7 @@ public function up(MigrationBuilder $b): void
{
$b->execute(
<<<SQL
CREATE TABLE person (
CREATE TABLE person (
id INT,
first_name VARCHAR(100),
last_name VARCHAR(100)
Expand Down

0 comments on commit d227ecd

Please sign in to comment.