Skip to content

Commit

Permalink
Very naive implementation of table truncation with postgres.
Browse files Browse the repository at this point in the history
I'm fairly certain that sequence names will need to be generated/handled
as the auto generated names are very unlikely to be the names given
to addConstraint()
  • Loading branch information
markstory committed May 25, 2013
1 parent 416d340 commit e97e0ef
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
28 changes: 28 additions & 0 deletions lib/Cake/Database/Schema/PostgresSchema.php
Expand Up @@ -342,4 +342,32 @@ public function dropTableSql(Table $table) {
return [sprintf('DROP TABLE "%s"', $table->name())];
}

/**
* Generate the SQL to truncate a table.
*
* @param Cake\Database\Schema\Table $table Table instance
* @return array SQL statements to drop truncate a table.
*/
public function truncateTableSql(Table $table) {
$name = $this->_driver->quoteIdentifier($table->name());
$sequence = null;
foreach ($table->constraints() as $seq) {
if ($table->constraint($seq)['type'] == Table::CONSTRAINT_PRIMARY) {
$sequence = $this->_driver->quoteIdentifier($seq);
break;
}
}

$out = [];
if ($sequence) {
$out[] = sprintf(
'ALTER SEQUENCE %s.%s RESTART WITH 1',
$name,
$sequence
);
}
$out[] = sprintf('DELETE FROM %s', $name);
return $out;
}

}
23 changes: 23 additions & 0 deletions lib/Cake/Test/TestCase/Database/Schema/PostgresSchemaTest.php
Expand Up @@ -562,6 +562,29 @@ public function testDropSql() {
$this->assertEquals('DROP TABLE "articles"', $result[0]);
}

/**
* Test truncateSql()
*
* @return void
*/
public function testTruncateSql() {
$driver = $this->_getMockedDriver();
$connection = $this->getMock('Cake\Database\Connection', array(), array(), '', false);
$connection->expects($this->any())->method('driver')
->will($this->returnValue($driver));

$table = new Table('articles');
$table->addColumn('id', 'integer')
->addConstraint('primary', [
'type' => 'primary',
'columns' => ['id']
]);
$result = $table->truncateSql($connection);
$this->assertCount(2, $result);
$this->assertEquals('ALTER SEQUENCE "articles"."primary" RESTART WITH 1', $result[0]);
$this->assertEquals('DELETE FROM "articles"', $result[1]);
}

/**
* Get a schema instance with a mocked driver/pdo instances
*
Expand Down

0 comments on commit e97e0ef

Please sign in to comment.