public function getDropTableDDL(Table $table)
 {
     $ret = '';
     foreach ($table->getForeignKeys() as $fk) {
         $ret .= "\nIF EXISTS (SELECT 1 FROM sysobjects WHERE type ='RI' AND name='" . $fk->getName() . "')\n    ALTER TABLE " . $this->quoteIdentifier($table->getName()) . " DROP CONSTRAINT " . $this->quoteIdentifier($fk->getName()) . ";\n";
     }
     self::$dropCount++;
     $ret .= "\nIF EXISTS (SELECT 1 FROM sysobjects WHERE type = 'U' AND name = '" . $table->getName() . "')\nBEGIN\n    DECLARE @reftable_" . self::$dropCount . " nvarchar(60), @constraintname_" . self::$dropCount . " nvarchar(60)\n    DECLARE refcursor CURSOR FOR\n    select reftables.name tablename, cons.name constraintname\n        from sysobjects tables,\n            sysobjects reftables,\n            sysobjects cons,\n            sysreferences ref\n        where tables.id = ref.rkeyid\n            and cons.id = ref.constid\n            and reftables.id = ref.fkeyid\n            and tables.name = '" . $table->getName() . "'\n    OPEN refcursor\n    FETCH NEXT from refcursor into @reftable_" . self::$dropCount . ", @constraintname_" . self::$dropCount . "\n    while @@FETCH_STATUS = 0\n    BEGIN\n        exec ('alter table '+@reftable_" . self::$dropCount . "+' drop constraint '+@constraintname_" . self::$dropCount . ")\n        FETCH NEXT from refcursor into @reftable_" . self::$dropCount . ", @constraintname_" . self::$dropCount . "\n    END\n    CLOSE refcursor\n    DEALLOCATE refcursor\n    DROP TABLE " . $this->quoteIdentifier($table->getName()) . "\nEND\n";
     return $ret;
 }
Example #2
0
 protected function validateTableColumns(Table $table)
 {
     if (!$table->hasPrimaryKey() && !$table->isSkipSql()) {
         $this->errors[] = sprintf('Table "%s" does not have a primary key defined. Propel requires all tables to have a primary key.', $table->getName());
     }
     $phpNames = [];
     foreach ($table->getColumns() as $column) {
         if (in_array($column->getPhpName(), $phpNames)) {
             $this->errors[] = sprintf('Column "%s" declares a phpName already used in table "%s"', $column->getName(), $table->getName());
         }
         $phpNames[] = $column->getPhpName();
     }
 }
 protected function addClosureColumn($name, Table $ct_table, Column $column)
 {
     $table = $this->getTable();
     $id_fieldname = $column->getName();
     $domain = $column->getDomain();
     if (!$ct_table->hasColumn($name)) {
         $column = new Column($name);
         $column->setDomain($domain);
         $column->setPrimaryKey(true);
         $ct_table->addColumn($column);
     } else {
         $column = $ct_table->getColumn($name);
     }
     $ct_tablename_normalized = str_replace('_', '', $ct_table->getName());
     $fk_name = $ct_tablename_normalized . '_' . $name . '_fk';
     if (!$ct_table->getColumnForeignKeys($name)) {
         $column_fk = new ForeignKey($fk_name);
         $column_fk->addReference($name, $table->getColumn($id_fieldname)->getName());
         $column_fk->setForeignTableCommonName($table->getName());
         $column_fk->setOnUpdate('cascade');
         $column_fk->setOnDelete('restrict');
         $ct_table->addForeignKey($column_fk);
     }
     $column_idx_name = $fk_name . '_idx';
     if (!$ct_table->hasIndex($column_idx_name)) {
         $column_idx = new Index($column_idx_name);
         $column_idx->addColumn(['name' => $column->getName()]);
         $ct_table->addIndex($column_idx);
     }
 }
 public function objectAttributes(ObjectBuilder $builder)
 {
     $tableName = $this->table->getName();
     $objectClassName = $builder->getObjectClassName();
     $script = "\n/**\n * Queries to be executed in the save transaction\n * @var        array\n */\nprotected \$nestedSetQueries = array();\n\n/**\n * Internal cache for children nodes\n * @var        null|ObjectCollection\n */\nprotected \$collNestedSetChildren = null;\n\n/**\n * Internal cache for parent node\n * @var        null|{$objectClassName}\n */\nprotected \$aNestedSetParent = null;\n\n/**\n * Left column for the set\n */\nconst LEFT_COL = '" . $tableName . '.' . $this->behavior->getColumnConstant('left_column') . "';\n\n/**\n * Right column for the set\n */\nconst RIGHT_COL = '" . $tableName . '.' . $this->behavior->getColumnConstant('right_column') . "';\n\n/**\n * Level column for the set\n */\nconst LEVEL_COL = '" . $tableName . '.' . $this->behavior->getColumnConstant('level_column') . "';\n";
     if ($this->behavior->useScope()) {
         $script .= "\n/**\n * Scope column for the set\n */\nconst SCOPE_COL = '" . $tableName . '.' . $this->behavior->getColumnConstant('scope_column') . "';\n";
     }
     return $script;
 }
Example #5
0
 /**
  * Returns the auto-increment string.
  *
  * @return string
  */
 public function getAutoIncrementString()
 {
     if ($this->isAutoIncrement() && IdMethod::NATIVE === $this->parentTable->getIdMethod()) {
         return $this->getPlatform()->getAutoIncrement();
     }
     if ($this->isAutoIncrement()) {
         throw new EngineException(sprintf('You have specified autoIncrement for column "%s", but you have not specified idMethod="native" for table "%s".', $this->name, $this->parentTable->getName()));
     }
     return '';
 }
 /**
  * Returns the string representation of this object.
  *
  * @return string
  */
 public function __toString()
 {
     $ret = '';
     $ret .= sprintf("  %s:\n", $this->fromTable->getName());
     if ($addedColumns = $this->getAddedColumns()) {
         $ret .= "    addedColumns:\n";
         foreach ($addedColumns as $colname => $column) {
             $ret .= sprintf("      - %s\n", $colname);
         }
     }
     if ($removedColumns = $this->getRemovedColumns()) {
         $ret .= "    removedColumns:\n";
         foreach ($removedColumns as $colname => $column) {
             $ret .= sprintf("      - %s\n", $colname);
         }
     }
     if ($modifiedColumns = $this->getModifiedColumns()) {
         $ret .= "    modifiedColumns:\n";
         foreach ($modifiedColumns as $colDiff) {
             $ret .= $colDiff->__toString();
         }
     }
     if ($renamedColumns = $this->getRenamedColumns()) {
         $ret .= "    renamedColumns:\n";
         foreach ($renamedColumns as $columnRenaming) {
             list($fromColumn, $toColumn) = $columnRenaming;
             $ret .= sprintf("      %s: %s\n", $fromColumn->getName(), $toColumn->getName());
         }
     }
     if ($addedIndices = $this->getAddedIndices()) {
         $ret .= "    addedIndices:\n";
         foreach ($addedIndices as $indexName => $index) {
             $ret .= sprintf("      - %s\n", $indexName);
         }
     }
     if ($removedIndices = $this->getRemovedIndices()) {
         $ret .= "    removedIndices:\n";
         foreach ($removedIndices as $indexName => $index) {
             $ret .= sprintf("      - %s\n", $indexName);
         }
     }
     if ($modifiedIndices = $this->getModifiedIndices()) {
         $ret .= "    modifiedIndices:\n";
         foreach ($modifiedIndices as $indexName => $indexDiff) {
             $ret .= sprintf("      - %s\n", $indexName);
         }
     }
     if ($addedFks = $this->getAddedFks()) {
         $ret .= "    addedFks:\n";
         foreach ($addedFks as $fkName => $fk) {
             $ret .= sprintf("      - %s\n", $fkName);
         }
     }
     if ($removedFks = $this->getRemovedFks()) {
         $ret .= "    removedFks:\n";
         foreach ($removedFks as $fkName => $fk) {
             $ret .= sprintf("      - %s\n", $fkName);
         }
     }
     if ($modifiedFks = $this->getModifiedFks()) {
         $ret .= "    modifiedFks:\n";
         foreach ($modifiedFks as $fkName => $fkFromTo) {
             $ret .= sprintf("      %s:\n", $fkName);
             list($fromFk, $toFk) = $fkFromTo;
             $fromLocalColumns = json_encode($fromFk->getLocalColumns());
             $toLocalColumns = json_encode($toFk->getLocalColumns());
             if ($fromLocalColumns != $toLocalColumns) {
                 $ret .= sprintf("          localColumns: from %s to %s\n", $fromLocalColumns, $toLocalColumns);
             }
             $fromForeignColumns = json_encode($fromFk->getForeignColumns());
             $toForeignColumns = json_encode($toFk->getForeignColumns());
             if ($fromForeignColumns != $toForeignColumns) {
                 $ret .= sprintf("          foreignColumns: from %s to %s\n", $fromForeignColumns, $toForeignColumns);
             }
             if ($fromFk->normalizeFKey($fromFk->getOnUpdate()) != $toFk->normalizeFKey($toFk->getOnUpdate())) {
                 $ret .= sprintf("          onUpdate: from %s to %s\n", $fromFk->getOnUpdate(), $toFk->getOnUpdate());
             }
             if ($fromFk->normalizeFKey($fromFk->getOnDelete()) != $toFk->normalizeFKey($toFk->getOnDelete())) {
                 $ret .= sprintf("          onDelete: from %s to %s\n", $fromFk->getOnDelete(), $toFk->getOnDelete());
             }
         }
     }
     return $ret;
 }
Example #7
0
 public function getPrimaryKeyName(Table $table)
 {
     $tableName = $table->getName();
     return $tableName . '_pkey';
 }
 /**
  * Returns the DDL SQL to add the primary key of a table.
  *
  * @param  Table  $table From Table
  * @return string
  */
 public function getAddPrimaryKeyDDL(Table $table)
 {
     if (!$table->hasPrimaryKey()) {
         return '';
     }
     $pattern = "\nALTER TABLE %s ADD %s;\n";
     return sprintf($pattern, $this->quoteIdentifier($table->getName()), $this->getPrimaryKeyDDL($table));
 }
 /**
  * Adds Columns to the specified table.
  *
  * @param Table $table The Table model class to add columns to.
  * @param int   $oid   The table OID
  */
 protected function addColumns(Table $table, $oid)
 {
     // Get the columns, types, etc.
     // Based on code from pgAdmin3 (http://www.pgadmin.org/)
     $searchPath = '?';
     $params = [$table->getDatabase()->getSchema()];
     if ($schema = $table->getSchema()) {
         $searchPath = '?';
         $params = [$schema];
     } else {
         if (!$table->getDatabase()->getSchema()) {
             $stmt = $this->dbh->query('SHOW search_path');
             $searchPathString = $stmt->fetchColumn();
             $params = [];
             $searchPath = explode(',', $searchPathString);
             foreach ($searchPath as &$path) {
                 $params[] = $path;
                 $path = '?';
             }
             $searchPath = implode(', ', $searchPath);
         }
     }
     $stmt = $this->dbh->prepare("\n        SELECT\n            column_name,\n            data_type,\n            column_default,\n            is_nullable,\n            numeric_precision,\n            numeric_scale,\n            character_maximum_length\n        FROM information_schema.columns\n        WHERE\n            table_schema IN ({$searchPath}) AND table_name = ?\n        ");
     $params[] = $table->getCommonName();
     $stmt->execute($params);
     while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
         $size = $row['character_maximum_length'];
         if (!$size) {
             $size = $row['numeric_precision'];
         }
         $scale = $row['numeric_scale'];
         $name = $row['column_name'];
         $type = $row['data_type'];
         $default = $row['column_default'];
         $isNullable = true === $row['is_nullable'] || 'YES' === strtoupper($row['is_nullable']);
         // Check to ensure that this column isn't an array data type
         if ('ARRAY' === $type) {
             $this->warn(sprintf('Array datatypes are not currently supported [%s.%s]', $table->getName(), $name));
             continue;
         }
         $autoincrement = null;
         // if column has a default
         if (strlen(trim($default)) > 0) {
             if (!preg_match('/^nextval\\(/', $default)) {
                 $strDefault = preg_replace('/::[\\W\\D]*/', '', $default);
             } else {
                 $autoincrement = true;
                 $default = null;
             }
         } else {
             $default = null;
         }
         $propelType = $this->getMappedPropelType($type);
         if (!$propelType) {
             $propelType = Column::DEFAULT_TYPE;
             $this->warn('Column [' . $table->getName() . '.' . $name . '] has a column type (' . $type . ') that Propel does not support.');
         }
         if (isset(static::$defaultTypeSizes[$type]) && $size == static::$defaultTypeSizes[$type]) {
             $size = null;
         }
         if ('SERIAL' === substr(strtoupper($type), 0, 6)) {
             $autoincrement = true;
             $default = null;
         }
         $column = new Column($name);
         $column->setTable($table);
         $column->setDomainForType($propelType);
         $column->getDomain()->replaceSize($size);
         if ($scale) {
             $column->getDomain()->replaceScale($scale);
         }
         if (null !== $default) {
             if ("'" !== substr($default, 0, 1) && strpos($default, '(')) {
                 $defaultType = ColumnDefaultValue::TYPE_EXPR;
             } else {
                 $defaultType = ColumnDefaultValue::TYPE_VALUE;
                 $default = str_replace("'", '', $strDefault);
             }
             $column->getDomain()->setDefaultValue(new ColumnDefaultValue($default, $defaultType));
         }
         $column->setAutoIncrement($autoincrement);
         $column->setNotNull(!$isNullable);
         $table->addColumn($column);
     }
 }
 /**
  * Returns the trigger name.
  *
  * @param Table $table
  *
  * @return string
  */
 protected function getTriggerName(Table $table)
 {
     $tableName = $table->getName();
     /** @var CompositeNumberRangeBehavior $behavior */
     $behavior = $table->getBehavior(self::BEHAVIOR_NAME);
     $foreignTableName = $behavior->getForeignTable();
     return str_replace(' ', '', ucwords(str_replace('_', ' ', 'set' . ucfirst($foreignTableName) . ucfirst($tableName) . 'Id')));
 }
 /**
  * @dataProvider provideSchemaNames
  *
  */
 public function testGetNameWithPlatform($supportsSchemas, $schemaName, $expectedName)
 {
     $database = $this->getDatabaseMock($schemaName, array('platform' => $this->getPlatformMock($supportsSchemas)));
     $database->expects($supportsSchemas ? $this->once() : $this->never())->method('getSchemaDelimiter')->will($this->returnValue('.'));
     $table = new Table('books');
     $table->setSchema($schemaName);
     $table->setDatabase($database);
     $this->assertSame($expectedName, $table->getName());
 }
 /**
  * Loads the primary key for this table.
  */
 protected function addPrimaryKey(Table $table)
 {
     $dataFetcher = $this->dbh->query("SELECT COLUMN_NAME\n            FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS\n            INNER JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE ON\n            INFORMATION_SCHEMA.TABLE_CONSTRAINTS.CONSTRAINT_NAME = INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE.constraint_name\n            WHERE     (INFORMATION_SCHEMA.TABLE_CONSTRAINTS.CONSTRAINT_TYPE = 'PRIMARY KEY') AND\n            (INFORMATION_SCHEMA.TABLE_CONSTRAINTS.TABLE_NAME = '" . $table->getName() . "')");
     // Loop through the returned results, grouping the same key_name together
     // adding each column for that key.
     foreach ($dataFetcher as $row) {
         $name = $this->cleanDelimitedIdentifiers($row[0]);
         $table->getColumn($name)->setPrimaryKey(true);
     }
 }
Example #13
0
 /**
  * Override to provide sequence names that conform to postgres' standard when
  * no id-method-parameter specified.
  *
  * @param Table $table
  *
  * @return string
  */
 public function getSequenceName(Table $table)
 {
     $result = null;
     if ($table->getIdMethod() == IdMethod::NATIVE) {
         $idMethodParams = $table->getIdMethodParameters();
         if (empty($idMethodParams)) {
             $result = null;
             // We're going to ignore a check for max length (mainly
             // because I'm not sure how Postgres would handle this w/ SERIAL anyway)
             foreach ($table->getColumns() as $col) {
                 if ($col->isAutoIncrement()) {
                     $result = $table->getName() . '_' . $col->getName() . '_seq';
                     break;
                     // there's only one auto-increment column allowed
                 }
             }
         } else {
             $result = $idMethodParams[0]->getValue();
         }
     }
     return $result;
 }
 /**
  * Adds vendor-specific info for table.
  *
  * @param      Table $table
  */
 protected function addTableVendorInfo(Table $table)
 {
     $stmt = $this->dbh->query("SHOW TABLE STATUS LIKE '" . $table->getName() . "'");
     $row = $stmt->fetch(PDO::FETCH_ASSOC);
     $vi = $this->getNewVendorInfoObject($row);
     $table->addVendorInfo($vi);
 }
 /**
  * Adds vendor-specific info for table.
  *
  * @param Table $table
  */
 protected function addTableVendorInfo(Table $table)
 {
     $stmt = $this->dbh->query("SHOW TABLE STATUS LIKE '" . $table->getName() . "'");
     $row = $stmt->fetch(\PDO::FETCH_ASSOC);
     if (!$this->addVendorInfo) {
         // since we depend on `Engine` in the MysqlPlatform, we always have to extract this vendor information
         $row = array('Engine' => $row['Engine']);
     }
     $vi = $this->getNewVendorInfoObject($row);
     $table->addVendorInfo($vi);
 }
Example #16
0
 public function removeTable(Table $table)
 {
     if ($this->hasTable($table->getName(), true)) {
         foreach ($this->tables as $id => $tableExam) {
             if ($table->getName() === $tableExam->getName()) {
                 unset($this->tables[$id]);
             }
         }
         unset($this->tablesByName[$table->getName()]);
         unset($this->tablesByLowercaseName[strtolower($table->getName())]);
         unset($this->tablesByPhpName[$table->getPhpName()]);
     }
 }
Example #17
0
 /**
  * Adds Columns to the specified table.
  *
  * @param      Table $table The Table model class to add columns to.
  * @param      int $oid The table OID
  * @param      string $version The database version.
  */
 protected function addColumns(Table $table, $oid, $version)
 {
     // Get the columns, types, etc.
     // Based on code from pgAdmin3 (http://www.pgadmin.org/)
     $stmt = $this->dbh->prepare("SELECT\n                                        att.attname,\n                                        att.atttypmod,\n                                        att.atthasdef,\n                                        att.attnotnull,\n                                        def.adsrc,\n                                        CASE WHEN att.attndims > 0 THEN 1 ELSE 0 END AS isarray,\n                                        CASE\n                                            WHEN ty.typname = 'bpchar'\n                                                THEN 'char'\n                                            WHEN ty.typname = '_bpchar'\n                                                THEN '_char'\n                                            ELSE\n                                                ty.typname\n                                        END AS typname,\n                                        ty.typtype\n                                    FROM pg_attribute att\n                                        JOIN pg_type ty ON ty.oid=att.atttypid\n                                        LEFT OUTER JOIN pg_attrdef def ON adrelid=att.attrelid AND adnum=att.attnum\n                                    WHERE att.attrelid = ? AND att.attnum > 0\n                                        AND att.attisdropped IS FALSE\n                                    ORDER BY att.attnum");
     $stmt->bindValue(1, $oid, PDO::PARAM_INT);
     $stmt->execute();
     while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
         $size = null;
         $precision = null;
         $scale = null;
         // Check to ensure that this column isn't an array data type
         if ((int) $row['isarray'] === 1) {
             throw new EngineException(sprintf("Array datatypes are not currently supported [%s.%s]", $this->name, $row['attname']));
         }
         // if (((int) $row['isarray']) === 1)
         $name = $row['attname'];
         // If they type is a domain, Process it
         if (strtolower($row['typtype']) == 'd') {
             $arrDomain = $this->processDomain($row['typname']);
             $type = $arrDomain['type'];
             $size = $arrDomain['length'];
             $precision = $size;
             $scale = $arrDomain['scale'];
             $boolHasDefault = strlen(trim($row['atthasdef'])) > 0 ? $row['atthasdef'] : $arrDomain['hasdefault'];
             $default = strlen(trim($row['adsrc'])) > 0 ? $row['adsrc'] : $arrDomain['default'];
             $isNullable = strlen(trim($row['attnotnull'])) > 0 ? $row['attnotnull'] : $arrDomain['notnull'];
             $isNullable = $isNullable == 't' ? false : true;
         } else {
             $type = $row['typname'];
             $arrLengthPrecision = $this->processLengthScale($row['atttypmod'], $type);
             $size = $arrLengthPrecision['length'];
             $precision = $size;
             $scale = $arrLengthPrecision['scale'];
             $boolHasDefault = $row['atthasdef'];
             $default = $row['adsrc'];
             $isNullable = $row['attnotnull'] == 't' ? false : true;
         }
         // else (strtolower ($row['typtype']) == 'd')
         $autoincrement = null;
         // if column has a default
         if ($boolHasDefault == 't' && strlen(trim($default)) > 0) {
             if (!preg_match('/^nextval\\(/', $default)) {
                 $strDefault = preg_replace('/::[\\W\\D]*/', '', $default);
                 $default = preg_replace('/(\'?)\'/', '${1}', $strDefault);
             } else {
                 $autoincrement = true;
                 $default = null;
             }
         } else {
             $default = null;
         }
         $propelType = $this->getMappedPropelType($type);
         if (!$propelType) {
             $propelType = Column::DEFAULT_TYPE;
             $this->warn("Column [" . $table->getName() . "." . $name . "] has a column type (" . $type . ") that Propel does not support.");
         }
         $column = new Column($name);
         $column->setTable($table);
         $column->setDomainForType($propelType);
         // We may want to provide an option to include this:
         // $column->getDomain()->replaceSqlType($type);
         $column->getDomain()->replaceSize($size);
         $column->getDomain()->replaceScale($scale);
         if ($default !== null) {
             if (in_array($default, array('now()'))) {
                 $type = ColumnDefaultValue::TYPE_EXPR;
             } else {
                 $type = ColumnDefaultValue::TYPE_VALUE;
             }
             $column->getDomain()->setDefaultValue(new ColumnDefaultValue($default, $type));
         }
         $column->setAutoIncrement($autoincrement);
         $column->setNotNull(!$isNullable);
         $table->addColumn($column);
     }
 }
Example #18
0
 /**
  * @param Table $table
  * @return bool
  */
 protected function isTableExcluded(Table $table)
 {
     $tablename = $table->getName();
     if (in_array($tablename, $this->excludedTables)) {
         return true;
     }
     foreach ($this->excludedTables as $exclude_tablename) {
         if (preg_match('/^' . str_replace('*', '.*', $exclude_tablename) . '$/', $tablename)) {
             return true;
         }
     }
     return false;
 }
 /**
  * @param Table $table
  * @return bool
  */
 protected function isTableExcluded(Table $table)
 {
     return in_array($table->getName(), $this->excludedTables);
 }
 /**
  * Loads the primary key for this table.
  *
  * @param Table $table The Table model class to add PK to.
  */
 protected function addPrimaryKey(Table $table)
 {
     $stmt = $this->dbh->query("SELECT COLS.COLUMN_NAME FROM USER_CONSTRAINTS CONS, USER_CONS_COLUMNS COLS WHERE CONS.CONSTRAINT_NAME = COLS.CONSTRAINT_NAME AND CONS.TABLE_NAME = '" . $table->getName() . "' AND CONS.CONSTRAINT_TYPE = 'P'");
     while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
         // This fixes a strange behavior by PDO. Sometimes the
         // row values are inside an index 0 of an array
         if (isset($row[0])) {
             $row = $row[0];
         }
         $table->getColumn($row['COLUMN_NAME'])->setPrimaryKey(true);
     }
 }
Example #21
0
 /**
  * Load indexes for this table
  */
 protected function addIndexes(Table $table)
 {
     $stmt = $this->dbh->query("PRAGMA index_list('" . $table->getName() . "')");
     while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
         $name = $row['name'];
         $index = new Index($name);
         $stmt2 = $this->dbh->query("PRAGMA index_info('" . $name . "')");
         while ($row2 = $stmt2->fetch(\PDO::FETCH_ASSOC)) {
             $colname = $row2['name'];
             $index->addColumn($table->getColumn($colname));
         }
         $table->addIndex($index);
     }
 }
 /**
  * Builds the DDL SQL to drop the primary key of a table.
  *
  * @param  Table  $table
  * @return string
  */
 public function getDropPrimaryKeyDDL(Table $table)
 {
     if (!$table->hasPrimaryKey()) {
         return '';
     }
     $pattern = "\nALTER TABLE %s DROP PRIMARY KEY;\n";
     return sprintf($pattern, $this->quoteIdentifier($table->getName()));
 }
Example #23
0
 /**
  * Adds the switch-statement for looking up the array-key name for toArray
  * @see toArray
  */
 protected function addToArrayKeyLookUp($phpName, Table $table, $plural)
 {
     if ($phpName == "") {
         $phpName = $table->getPhpName();
     }
     $camelCaseName = $table->getCamelCaseName();
     $fieldName = $table->getName();
     if ($plural) {
         $phpName = $this->getPluralizer()->getPluralForm($phpName);
         $camelCaseName = $this->getPluralizer()->getPluralForm($camelCaseName);
         $fieldName = $this->getPluralizer()->getPluralForm($fieldName);
     }
     return "\n                switch (\$keyType) {\n                    case TableMap::TYPE_CAMELNAME:\n                        \$key = '" . $camelCaseName . "';\n                        break;\n                    case TableMap::TYPE_FIELDNAME:\n                        \$key = '" . $fieldName . "';\n                        break;\n                    default:\n                        \$key = '" . $phpName . "';\n                }\n        ";
 }
Example #24
0
 /**
  * Loads the primary key for this table.
  */
 protected function addPrimaryKey(Table $table)
 {
     $stmt = $this->dbh->query("SELECT COLUMN_NAME\n            FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS\n            INNER JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE ON\n            INFORMATION_SCHEMA.TABLE_CONSTRAINTS.CONSTRAINT_NAME = INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE.constraint_name\n            WHERE     (INFORMATION_SCHEMA.TABLE_CONSTRAINTS.CONSTRAINT_TYPE = 'PRIMARY KEY') AND\n            (INFORMATION_SCHEMA.TABLE_CONSTRAINTS.TABLE_NAME = '" . $table->getName() . "')");
     // Loop through the returned results, grouping the same key_name together
     // adding each column for that key.
     while ($row = $stmt->fetch(PDO::FETCH_NUM)) {
         $name = $row[0];
         $table->getColumn($name)->setPrimaryKey(true);
     }
 }
 /**
  * Load indexes for this table
  */
 protected function addIndexes(Table $table)
 {
     $stmt = $this->dbh->query('PRAGMA index_list("' . $table->getName() . '")');
     while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
         $name = $row['name'];
         $internalName = $name;
         if (0 === strpos($name, 'sqlite_autoindex')) {
             $internalName = '';
         }
         $index = $row['unique'] ? new Unique($internalName) : new Index($internalName);
         $stmt2 = $this->dbh->query("PRAGMA index_info('" . $name . "')");
         while ($row2 = $stmt2->fetch(\PDO::FETCH_ASSOC)) {
             $colname = $row2['name'];
             $index->addColumn($table->getColumn($colname));
         }
         if (1 === count($table->getPrimaryKey()) && 1 === count($index->getColumns())) {
             // exclude the primary unique index, since it's autogenerated by sqlite
             if ($table->getPrimaryKey()[0]->getName() === $index->getColumns()[0]) {
                 continue;
             }
         }
         if ($index instanceof Unique) {
             $table->addUnique($index);
         } else {
             $table->addIndex($index);
         }
     }
 }
Example #26
0
 /**
  * @dataProvider provideSchemaNames
  *
  */
 public function testGetNameWithPlatform($supportsSchemas, $schemaName, $expectedName)
 {
     $platform = $this->getPlatformMock($supportsSchemas);
     $database = $this->getDatabaseMock('bookstore', array('platform' => $platform));
     $table = new Table('books');
     $table->setDatabase($database);
     $this->assertSame('books', $table->getName());
 }
Example #27
0
 public function getPrimaryKeyName(Table $table)
 {
     $tableName = $table->getName();
     // pk constraint name must be 30 chars at most
     $tableName = substr($tableName, 0, min(27, strlen($tableName)));
     return $tableName . '_pk';
 }
 /**
  * Returns the name of the table the foreign key is in.
  *
  * @return string
  */
 public function getTableName()
 {
     return $this->parentTable->getName();
 }
Example #29
0
 public function testQualifiedName()
 {
     $table = new Table();
     $table->setSchema("foo");
     $table->setCommonName("bar");
     $this->assertEquals($table->getName(), "bar");
     $this->assertEquals($table->getCommonName(), "bar");
     $database = new Database();
     $database->addTable($table);
     $database->setPlatform(new NoSchemaPlatform());
     $this->assertEquals($table->getName(), "bar");
     $database->setPlatform(new SchemaPlatform());
     $this->assertEquals($table->getName(), "foo.bar");
 }
Example #30
0
 public function getDropTableDDL(Table $table)
 {
     return "\nDROP TABLE IF EXISTS " . $table->getName() . ";\n";
 }