Skip to content
Permalink
Browse files

Very naive implementation of table truncation with postgres.

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 e97e0efe68d04b108d53507299a8600525692b06
@@ -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;
}
}
@@ -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
*

0 comments on commit e97e0ef

Please sign in to comment.
You can’t perform that action at this time.