Skip to content

Commit

Permalink
[11.x] Added useCascadeTruncate method for PostgresGrammar (#53343)
Browse files Browse the repository at this point in the history
* Added `useCascadeTruncate` method for `PostgresGrammar`

* formatting

---------

Co-authored-by: Taylor Otwell <taylor@laravel.com>
  • Loading branch information
korkoshko and taylorotwell authored Oct 31, 2024
1 parent 9d974bb commit 79897cd
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 1 deletion.
20 changes: 19 additions & 1 deletion src/Illuminate/Database/Query/Grammars/PostgresGrammar.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,13 @@ class PostgresGrammar extends Grammar
'~', '&', '|', '#', '<<', '>>', '<<=', '>>=',
];

/**
* Indicates if the cascade option should be used when truncating.
*
* @var bool
*/
protected static $cascadeTruncate = true;

/**
* Compile a basic where clause.
*
Expand Down Expand Up @@ -653,7 +660,7 @@ protected function compileDeleteWithJoinsOrLimit(Builder $query)
*/
public function compileTruncate(Builder $query)
{
return ['truncate '.$this->wrapTable($query->from).' restart identity cascade' => []];
return ['truncate '.$this->wrapTable($query->from).' restart identity'.(static::$cascadeTruncate ? ' cascade' : '') => []];
}

/**
Expand Down Expand Up @@ -802,4 +809,15 @@ public static function customOperators(array $operators)
array_merge(static::$customOperators, array_filter(array_filter($operators, 'is_string')))
);
}

/**
* Enable or disable the "cascade" option when compiling the truncate statement.
*
* @param bool $value
* @return void
*/
public static function cascadeOnTrucate(bool $value = true)
{
static::$cascadeTruncate = $value;
}
}
24 changes: 24 additions & 0 deletions tests/Database/DatabasePostgresQueryGrammarTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace Illuminate\Tests\Database;

use Illuminate\Database\Connection;
use Illuminate\Database\Query\Builder;
use Illuminate\Database\Query\Grammars\PostgresGrammar;
use Mockery as m;
use PHPUnit\Framework\TestCase;
Expand Down Expand Up @@ -47,4 +48,27 @@ public function testCustomOperators()
$this->assertNotContains(1, $operators);
$this->assertSame(array_unique($operators), $operators);
}

public function testCompileTruncate()
{
$postgres = new PostgresGrammar;
$builder = m::mock(Builder::class);
$builder->from = 'users';

$this->assertEquals([
'truncate "users" restart identity cascade' => [],
], $postgres->compileTruncate($builder));

PostgresGrammar::cascadeOnTrucate(false);

$this->assertEquals([
'truncate "users" restart identity' => [],
], $postgres->compileTruncate($builder));

PostgresGrammar::cascadeOnTrucate();

$this->assertEquals([
'truncate "users" restart identity cascade' => [],
], $postgres->compileTruncate($builder));
}
}

0 comments on commit 79897cd

Please sign in to comment.