Skip to content
Permalink
Browse files

Add Table::primaryKey()

Since we often need easy access to the columns in a table's primary
key make that easy to get with a simple method.
  • Loading branch information...
markstory committed Apr 27, 2013
1 parent a92cddf commit bdbb331847e081e67264cad64c2b354666bea162
Showing with 61 additions and 3 deletions.
  1. +28 −0 lib/Cake/Database/Schema/Table.php
  2. +33 −3 lib/Cake/Test/TestCase/Database/Schema/TableTest.php
@@ -210,4 +210,32 @@ public function indexes() {
return array_keys($this->_indexes);
}
/**
* Read information about an index based on name.
*
* @param string $name The name of the index.
* @return array|null Array of index data, or null
*/
public function index($name) {
if (!isset($this->_indexes[$name])) {
return null;
}
return $this->_indexes[$name];
}
/**
* Get the column(s) used for the primary key.
*
* @return array|null Column name(s) for the primary key.
* Null will be returned if a table has no primary key.
*/
public function primaryKey() {
foreach ($this->_indexes as $name => $data) {
if ($data['type'] === self::INDEX_PRIMARY) {
return $data['columns'];
}
}
return null;
}
}
@@ -119,6 +119,7 @@ public function testAddIndexErrorWhenFieldIsMissing() {
'columns' => ['author_id']
]);
}
/**
* Test that exceptions are raised when indexes
* are added with invalid types
@@ -142,13 +143,42 @@ public function testAddIndexErrorWrongType() {
*/
public function testAddIndexTypes() {
$table = new Table('articles');
$table->addColumn('title', 'string')
$table->addColumn('id', 'integer')
->addColumn('title', 'string')
->addColumn('author_id', 'integer');
$table->addIndex('author_idx', [
'fields' => ['author_id'],
'columns' => ['author_id'],
'type' => 'unique'
]);
])->addIndex('primary', [
'type' => 'primary',
'columns' => ['id']
]);
$this->assertEquals(
['author_idx', 'primary'],
$table->indexes()
);
}
/**
* Test getting the primary key.
*
* @return void
*/
public function testPrimaryKey() {
$table = new Table('articles');
$table->addColumn('id', 'integer')
->addColumn('title', 'string')
->addColumn('author_id', 'integer')
->addIndex('author_idx', [
'columns' => ['author_id'],
'type' => 'unique'
])->addIndex('primary', [
'type' => 'primary',
'columns' => ['id']
]);
$this->assertEquals(['id'], $table->primaryKey());
}
}

0 comments on commit bdbb331

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