Browse Source

Merge pull request #519 from gevik/issue-466

Issue 466 (add/drop PrimaryKeys)
tags/2.0.0-beta
Qiang Xue 12 years ago
parent
commit
44f78f04df
  1. 26
      framework/yii/db/Command.php
  2. 35
      framework/yii/db/QueryBuilder.php
  3. 11
      framework/yii/db/mysql/QueryBuilder.php
  4. 4
      framework/yii/db/pgsql/QueryBuilder.php
  5. 2
      framework/yii/db/pgsql/Schema.php
  6. 26
      framework/yii/db/sqlite/QueryBuilder.php
  7. 8
      tests/unit/data/mysql.sql
  8. 7
      tests/unit/data/postgres.sql
  9. 31
      tests/unit/framework/db/QueryBuilderTest.php
  10. 76
      tests/unit/framework/db/pgsql/PostgreSQLQueryBuilderTest.php
  11. 8
      tests/unit/framework/db/sqlite/SqliteQueryBuilderTest.php

26
framework/yii/db/Command.php

@ -654,6 +654,32 @@ class Command extends \yii\base\Component
} }
/** /**
* Creates a SQL command for adding a primary key constraint to an existing table.
* The method will properly quote the table and column names.
* @param string $name the name of the primary key constraint.
* @param string $table the table that the primary key constraint will be added to.
* @param string|array $columns comma separated string or array of columns that the primary key will consist of.
* @return Command the command object itself.
*/
public function addPrimaryKey($name, $table, $columns)
{
$sql = $this->db->getQueryBuilder()->addPrimaryKey($name, $table, $columns);
return $this->setSql($sql);
}
/**
* Creates a SQL command for removing a primary key constraint to an existing table.
* @param string $name the name of the primary key constraint to be removed.
* @param string $table the table that the primary key constraint will be removed from.
* @return Command the command object itself
*/
public function dropPrimarykey($name, $table)
{
$sql = $this->db->getQueryBuilder()->dropPrimarykey($name, $table);
return $this->setSql($sql);
}
/**
* Creates a SQL command for adding a foreign key constraint to an existing table. * Creates a SQL command for adding a foreign key constraint to an existing table.
* The method will properly quote the table and column names. * The method will properly quote the table and column names.
* @param string $name the name of the foreign key constraint. * @param string $name the name of the foreign key constraint.

35
framework/yii/db/QueryBuilder.php

@ -270,6 +270,41 @@ class QueryBuilder extends \yii\base\Object
} }
/** /**
* Builds a SQL statement for adding a primary key constraint to an existing table.
* @param string $name the name of the primary key constraint.
* @param string $table the table that the primary key constraint will be added to.
* @param string|array $columns comma separated string or array of columns that the primary key will consist of.
* @return string the SQL statement for adding a primary key constraint to an existing table.
*/
public function addPrimaryKey($name, $table, $columns)
{
if (is_string($columns)) {
$columns=preg_split('/\s*,\s*/',$columns,-1,PREG_SPLIT_NO_EMPTY);
}
foreach ($columns as $i=>$col) {
$columns[$i]=$this->db->quoteColumnName($col);
}
return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' ADD CONSTRAINT '
. $this->db->quoteColumnName($name) . ' PRIMARY KEY ('
. implode(', ', $columns). ' )';
}
/**
* Builds a SQL statement for removing a primary key constraint to an existing table.
* @param string $name the name of the primary key constraint to be removed.
* @param string $table the table that the primary key constraint will be removed from.
* @return string the SQL statement for removing a primary key constraint from an existing table. *
*/
public function dropPrimarykey($name, $table)
{
return 'ALTER TABLE ' . $this->db->quoteTableName($table)
. ' DROP CONSTRAINT ' . $this->db->quoteColumnName($name);
}
/**
* Builds a SQL statement for truncating a DB table. * Builds a SQL statement for truncating a DB table.
* @param string $table the table to be truncated. The name will be properly quoted by the method. * @param string $table the table to be truncated. The name will be properly quoted by the method.
* @return string the SQL statement for truncating a DB table. * @return string the SQL statement for truncating a DB table.

11
framework/yii/db/mysql/QueryBuilder.php

@ -89,6 +89,17 @@ class QueryBuilder extends \yii\db\QueryBuilder
} }
/** /**
* Builds a SQL statement for removing a primary key constraint to an existing table.
* @param string $name the name of the primary key constraint to be removed.
* @param string $table the table that the primary key constraint will be removed from.
* @return string the SQL statement for removing a primary key constraint from an existing table. *
*/
public function dropPrimarykey($name, $table)
{
return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' DROP PRIMARY KEY';
}
/**
* Creates a SQL statement for resetting the sequence value of a table's primary key. * Creates a SQL statement for resetting the sequence value of a table's primary key.
* The sequence will be reset such that the primary key of the next new row inserted * The sequence will be reset such that the primary key of the next new row inserted
* will have the specified value or 1. * will have the specified value or 1.

4
framework/yii/db/pgsql/QueryBuilder.php

@ -22,13 +22,13 @@ class QueryBuilder extends \yii\db\QueryBuilder
*/ */
public $typeMap = array( public $typeMap = array(
Schema::TYPE_PK => 'serial not null primary key', Schema::TYPE_PK => 'serial not null primary key',
Schema::TYPE_STRING => 'varchar', Schema::TYPE_STRING => 'varchar(255)',
Schema::TYPE_TEXT => 'text', Schema::TYPE_TEXT => 'text',
Schema::TYPE_SMALLINT => 'smallint', Schema::TYPE_SMALLINT => 'smallint',
Schema::TYPE_INTEGER => 'integer', Schema::TYPE_INTEGER => 'integer',
Schema::TYPE_BIGINT => 'bigint', Schema::TYPE_BIGINT => 'bigint',
Schema::TYPE_FLOAT => 'double precision', Schema::TYPE_FLOAT => 'double precision',
Schema::TYPE_DECIMAL => 'numeric', Schema::TYPE_DECIMAL => 'numeric(10,0)',
Schema::TYPE_DATETIME => 'timestamp', Schema::TYPE_DATETIME => 'timestamp',
Schema::TYPE_TIMESTAMP => 'timestamp', Schema::TYPE_TIMESTAMP => 'timestamp',
Schema::TYPE_TIME => 'time', Schema::TYPE_TIME => 'time',

2
framework/yii/db/pgsql/Schema.php

@ -43,6 +43,7 @@ class Schema extends \yii\db\Schema
'circle' => self::TYPE_STRING, 'circle' => self::TYPE_STRING,
'date' => self::TYPE_DATE, 'date' => self::TYPE_DATE,
'real' => self::TYPE_FLOAT, 'real' => self::TYPE_FLOAT,
'decimal' => self::TYPE_DECIMAL,
'double precision' => self::TYPE_DECIMAL, 'double precision' => self::TYPE_DECIMAL,
'inet' => self::TYPE_STRING, 'inet' => self::TYPE_STRING,
'smallint' => self::TYPE_SMALLINT, 'smallint' => self::TYPE_SMALLINT,
@ -55,7 +56,6 @@ class Schema extends \yii\db\Schema
'money' => self::TYPE_MONEY, 'money' => self::TYPE_MONEY,
'name' => self::TYPE_STRING, 'name' => self::TYPE_STRING,
'numeric' => self::TYPE_STRING, 'numeric' => self::TYPE_STRING,
'numrange' => self::TYPE_DECIMAL,
'oid' => self::TYPE_BIGINT, // should not be used. it's pg internal! 'oid' => self::TYPE_BIGINT, // should not be used. it's pg internal!
'path' => self::TYPE_STRING, 'path' => self::TYPE_STRING,
'point' => self::TYPE_STRING, 'point' => self::TYPE_STRING,

26
framework/yii/db/sqlite/QueryBuilder.php

@ -179,4 +179,30 @@ class QueryBuilder extends \yii\db\QueryBuilder
{ {
throw new NotSupportedException(__METHOD__ . ' is not supported by SQLite.'); throw new NotSupportedException(__METHOD__ . ' is not supported by SQLite.');
} }
/**
* Builds a SQL statement for adding a primary key constraint to an existing table.
* @param string $name the name of the primary key constraint.
* @param string $table the table that the primary key constraint will be added to.
* @param string|array $columns comma separated string or array of columns that the primary key will consist of.
* @return string the SQL statement for adding a primary key constraint to an existing table.
* @throws NotSupportedException this is not supported by SQLite
*/
public function addPrimaryKey($name, $table, $columns)
{
throw new NotSupportedException(__METHOD__ . ' is not supported by SQLite.');
}
/**
* Builds a SQL statement for removing a primary key constraint to an existing table.
* @param string $name the name of the primary key constraint to be removed.
* @param string $table the table that the primary key constraint will be removed from.
* @return string the SQL statement for removing a primary key constraint from an existing table.
* @throws NotSupportedException this is not supported by SQLite *
*/
public function dropPrimarykey($name, $table)
{
throw new NotSupportedException(__METHOD__ . ' is not supported by SQLite.');
}
} }

8
tests/unit/data/mysql.sql

@ -9,6 +9,14 @@ DROP TABLE IF EXISTS tbl_order CASCADE;
DROP TABLE IF EXISTS tbl_category CASCADE; DROP TABLE IF EXISTS tbl_category CASCADE;
DROP TABLE IF EXISTS tbl_customer CASCADE; DROP TABLE IF EXISTS tbl_customer CASCADE;
DROP TABLE IF EXISTS tbl_type CASCADE; DROP TABLE IF EXISTS tbl_type CASCADE;
DROP TABLE IF EXISTS tbl_constraints CASCADE;
CREATE TABLE `tbl_constraints`
(
`id` integer not null,
`field1` varchar(255)
);
CREATE TABLE `tbl_customer` ( CREATE TABLE `tbl_customer` (
`id` int(11) NOT NULL AUTO_INCREMENT, `id` int(11) NOT NULL AUTO_INCREMENT,

7
tests/unit/data/postgres.sql

@ -10,6 +10,13 @@ DROP TABLE IF EXISTS tbl_order CASCADE;
DROP TABLE IF EXISTS tbl_category CASCADE; DROP TABLE IF EXISTS tbl_category CASCADE;
DROP TABLE IF EXISTS tbl_customer CASCADE; DROP TABLE IF EXISTS tbl_customer CASCADE;
DROP TABLE IF EXISTS tbl_type CASCADE; DROP TABLE IF EXISTS tbl_type CASCADE;
DROP TABLE IF EXISTS tbl_constraints CASCADE;
CREATE TABLE tbl_constraints
(
id integer not null,
field1 varchar(255)
);
CREATE TABLE tbl_customer ( CREATE TABLE tbl_customer (
id serial not null primary key, id serial not null primary key,

31
tests/unit/framework/db/QueryBuilderTest.php

@ -7,23 +7,26 @@ use yii\db\Schema;
use yii\db\mysql\QueryBuilder as MysqlQueryBuilder; use yii\db\mysql\QueryBuilder as MysqlQueryBuilder;
use yii\db\sqlite\QueryBuilder as SqliteQueryBuilder; use yii\db\sqlite\QueryBuilder as SqliteQueryBuilder;
use yii\db\mssql\QueryBuilder as MssqlQueryBuilder; use yii\db\mssql\QueryBuilder as MssqlQueryBuilder;
use yii\db\pgsql\QueryBuilder as PgsqlQueryBuilder;
class QueryBuilderTest extends DatabaseTestCase class QueryBuilderTest extends DatabaseTestCase
{ {
/** /**
* @throws \Exception * @throws \Exception
* @return QueryBuilder * @return QueryBuilder
*/ */
protected function getQueryBuilder() protected function getQueryBuilder()
{ {
switch($this->driverName) switch ($this->driverName) {
{
case 'mysql': case 'mysql':
return new MysqlQueryBuilder($this->getConnection()); return new MysqlQueryBuilder($this->getConnection());
case 'sqlite': case 'sqlite':
return new SqliteQueryBuilder($this->getConnection()); return new SqliteQueryBuilder($this->getConnection());
case 'mssql': case 'mssql':
return new MssqlQueryBuilder($this->getConnection()); return new MssqlQueryBuilder($this->getConnection());
case 'pgsql':
return new PgsqlQueryBuilder($this->getConnection());
} }
throw new \Exception('Test is not implemented for ' . $this->driverName); throw new \Exception('Test is not implemented for ' . $this->driverName);
} }
@ -95,15 +98,31 @@ class QueryBuilderTest extends DatabaseTestCase
); );
} }
/**
*
*/
public function testGetColumnType() public function testGetColumnType()
{ {
$qb = $this->getQueryBuilder(); $qb = $this->getQueryBuilder();
foreach($this->columnTypes() as $item) { foreach ($this->columnTypes() as $item) {
list ($column, $expected) = $item; list ($column, $expected) = $item;
$this->assertEquals($expected, $qb->getColumnType($column)); $this->assertEquals($expected, $qb->getColumnType($column));
} }
} }
public function testAddDropPrimayKey()
{
$tableName = 'tbl_constraints';
$pkeyName = $tableName . "_pkey";
// ADD
$qb = $this->getQueryBuilder();
$qb->db->createCommand()->addPrimaryKey($pkeyName, $tableName, array('id'))->execute();
$tableSchema = $qb->db->getSchema()->getTableSchema($tableName);
$this->assertEquals(1, count($tableSchema->primaryKey));
//DROP
$qb->db->createCommand()->dropPrimarykey($pkeyName, $tableName)->execute();
$qb = $this->getQueryBuilder(); // resets the schema
$tableSchema = $qb->db->getSchema()->getTableSchema($tableName);
$this->assertEquals(0, count($tableSchema->primaryKey));
}
} }

76
tests/unit/framework/db/pgsql/PostgreSQLQueryBuilderTest.php

@ -0,0 +1,76 @@
<?php
namespace yiiunit\framework\db\pgsql;
use yii\base\NotSupportedException;
use yii\db\pgsql\Schema;
use yiiunit\framework\db\QueryBuilderTest;
class PostgreSQLQueryBuilderTest extends QueryBuilderTest
{
public $driverName = 'pgsql';
public function columnTypes()
{
return array(
array(Schema::TYPE_PK, 'serial not null primary key'),
array(Schema::TYPE_PK . '(8)', 'serial not null primary key'),
array(Schema::TYPE_PK . ' CHECK (value > 5)', 'serial not null primary key CHECK (value > 5)'),
array(Schema::TYPE_PK . '(8) CHECK (value > 5)', 'serial not null primary key CHECK (value > 5)'),
array(Schema::TYPE_STRING, 'varchar(255)'),
array(Schema::TYPE_STRING . '(32)', 'varchar(32)'),
array(Schema::TYPE_STRING . ' CHECK (value LIKE "test%")', 'varchar(255) CHECK (value LIKE "test%")'),
array(Schema::TYPE_STRING . '(32) CHECK (value LIKE "test%")', 'varchar(32) CHECK (value LIKE "test%")'),
array(Schema::TYPE_STRING . ' NOT NULL', 'varchar(255) NOT NULL'),
array(Schema::TYPE_TEXT, 'text'),
array(Schema::TYPE_TEXT . '(255)', 'text'),
array(Schema::TYPE_TEXT . ' CHECK (value LIKE "test%")', 'text CHECK (value LIKE "test%")'),
array(Schema::TYPE_TEXT . '(255) CHECK (value LIKE "test%")', 'text CHECK (value LIKE "test%")'),
array(Schema::TYPE_TEXT . ' NOT NULL', 'text NOT NULL'),
array(Schema::TYPE_TEXT . '(255) NOT NULL', 'text NOT NULL'),
array(Schema::TYPE_SMALLINT, 'smallint'),
array(Schema::TYPE_SMALLINT . '(8)', 'smallint'),
array(Schema::TYPE_INTEGER, 'integer'),
array(Schema::TYPE_INTEGER . '(8)', 'integer'),
array(Schema::TYPE_INTEGER . ' CHECK (value > 5)', 'integer CHECK (value > 5)'),
array(Schema::TYPE_INTEGER . '(8) CHECK (value > 5)', 'integer CHECK (value > 5)'),
array(Schema::TYPE_INTEGER . ' NOT NULL', 'integer NOT NULL'),
array(Schema::TYPE_BIGINT, 'bigint'),
array(Schema::TYPE_BIGINT . '(8)', 'bigint'),
array(Schema::TYPE_BIGINT . ' CHECK (value > 5)', 'bigint CHECK (value > 5)'),
array(Schema::TYPE_BIGINT . '(8) CHECK (value > 5)', 'bigint CHECK (value > 5)'),
array(Schema::TYPE_BIGINT . ' NOT NULL', 'bigint NOT NULL'),
array(Schema::TYPE_FLOAT, 'double precision'),
array(Schema::TYPE_FLOAT . ' CHECK (value > 5.6)', 'double precision CHECK (value > 5.6)'),
array(Schema::TYPE_FLOAT . '(16,5) CHECK (value > 5.6)', 'double precision CHECK (value > 5.6)'),
array(Schema::TYPE_FLOAT . ' NOT NULL', 'double precision NOT NULL'),
array(Schema::TYPE_DECIMAL, 'numeric(10,0)'),
array(Schema::TYPE_DECIMAL . '(12,4)', 'numeric(12,4)'),
array(Schema::TYPE_DECIMAL . ' CHECK (value > 5.6)', 'numeric(10,0) CHECK (value > 5.6)'),
array(Schema::TYPE_DECIMAL . '(12,4) CHECK (value > 5.6)', 'numeric(12,4) CHECK (value > 5.6)'),
array(Schema::TYPE_DECIMAL . ' NOT NULL', 'numeric(10,0) NOT NULL'),
array(Schema::TYPE_DATETIME, 'timestamp'),
array(Schema::TYPE_DATETIME . " CHECK(value BETWEEN '2011-01-01' AND '2013-01-01')", "timestamp CHECK(value BETWEEN '2011-01-01' AND '2013-01-01')"),
array(Schema::TYPE_DATETIME . ' NOT NULL', 'timestamp NOT NULL'),
array(Schema::TYPE_TIMESTAMP, 'timestamp'),
array(Schema::TYPE_TIMESTAMP . " CHECK(value BETWEEN '2011-01-01' AND '2013-01-01')", "timestamp CHECK(value BETWEEN '2011-01-01' AND '2013-01-01')"),
array(Schema::TYPE_TIMESTAMP . ' NOT NULL', 'timestamp NOT NULL'),
array(Schema::TYPE_TIME, 'time'),
array(Schema::TYPE_TIME . " CHECK(value BETWEEN '12:00:00' AND '13:01:01')", "time CHECK(value BETWEEN '12:00:00' AND '13:01:01')"),
array(Schema::TYPE_TIME . ' NOT NULL', 'time NOT NULL'),
array(Schema::TYPE_DATE, 'date'),
array(Schema::TYPE_DATE . " CHECK(value BETWEEN '2011-01-01' AND '2013-01-01')", "date CHECK(value BETWEEN '2011-01-01' AND '2013-01-01')"),
array(Schema::TYPE_DATE . ' NOT NULL', 'date NOT NULL'),
array(Schema::TYPE_BINARY, 'bytea'),
array(Schema::TYPE_BOOLEAN, 'boolean'),
array(Schema::TYPE_BOOLEAN . ' NOT NULL DEFAULT 1', 'boolean NOT NULL DEFAULT 1'),
array(Schema::TYPE_MONEY, 'numeric(19,4)'),
array(Schema::TYPE_MONEY . '(16,2)', 'numeric(16,2)'),
array(Schema::TYPE_MONEY . ' CHECK (value > 0.0)', 'numeric(19,4) CHECK (value > 0.0)'),
array(Schema::TYPE_MONEY . '(16,2) CHECK (value > 0.0)', 'numeric(16,2) CHECK (value > 0.0)'),
array(Schema::TYPE_MONEY . ' NOT NULL', 'numeric(19,4) NOT NULL'),
);
}
}

8
tests/unit/framework/db/sqlite/SqliteQueryBuilderTest.php

@ -2,6 +2,7 @@
namespace yiiunit\framework\db\sqlite; namespace yiiunit\framework\db\sqlite;
use yii\base\NotSupportedException;
use yii\db\sqlite\Schema; use yii\db\sqlite\Schema;
use yiiunit\framework\db\QueryBuilderTest; use yiiunit\framework\db\QueryBuilderTest;
@ -71,4 +72,11 @@ class SqliteQueryBuilderTest extends QueryBuilderTest
array(Schema::TYPE_MONEY . ' NOT NULL', 'decimal(19,4) NOT NULL'), array(Schema::TYPE_MONEY . ' NOT NULL', 'decimal(19,4) NOT NULL'),
); );
} }
public function testAddDropPrimayKey()
{
$this->setExpectedException('yii\base\NotSupportedException');
parent::testAddDropPrimayKey();
}
} }
Loading…
Cancel
Save