Adds the getPrimaryKey() method for tables that contain a single-column primary key.
@param string &$script The script will be modified in this method.
763110
protected function addGetPrimaryKey_SinglePK(&$script)
    {
        $table = $this->getTable();
        $pkeys = $table->getPrimaryKey();
        $cptype = $pkeys[0]->getPhpType();

        $script .= "
    /**
     * Returns the primary key for this object (row).
     * @return $cptype
     */
    public function getPrimaryKey()
    {
        return \$this->get".$pkeys[0]->getPhpName()."();
    }
";
    }
733451
protected function addUseRefFkQuery(&$script, $fk)
    {
        $table = $this->getTable();
        $fkTable = $this->getTable()->getDatabase()->getTable($fk->getTableName());
        $fkQueryBuilder = $this->getNewStubQueryBuilder($fkTable);
        $queryClass = $fkQueryBuilder->getClassname();
        if ($namespace = $fkQueryBuilder->getNamespace()) {
            $queryClass = '\\' . $namespace . '\\' . $queryClass;
        }
        $relationName = $this->getRefFKPhpNameAffix($fk);
        $joinType = $this->getJoinType($fk);
        $this->addUseRelatedQuery($script, $fkTable, $queryClass, $relationName, $joinType);
    }
796066
public function getPrimaryKeyDDL(Table $table)
    {
        if ($table->hasPrimaryKey()) {

            $keys = $table->getPrimaryKey();

            //MySQL throws an 'Incorrect table definition; there can be only one auto column and it must be defined as a key'
            //if the primary key consists of multiple columns and if the first is not the autoIncrement one. So
            //this push the autoIncrement column to the first position if its not already.
            $autoIncrement = $table->getAutoIncrementPrimaryKey();
            if ($autoIncrement && $keys[0] != $autoIncrement) {
                $idx = array_search($autoIncrement, $keys);
                if ($idx !== false) {
                    unset($keys[$idx]);
                    array_unshift($keys, $autoIncrement);
                }
            }

            return 'PRIMARY KEY (' . $this->getColumnListDDL($keys) . ')';
        }
    }
103149
function getPrimaryKeys($tableName) {
        $primary_key_index = $this->schema->listTableDetails($tableName)->getPrimaryKey();
        return $primary_key_index ? $primary_key_index->getColumns() : [];
    }
982850
protected function addPKRefFKSet(&$script, ForeignKey $refFK)
    {
        $tblFK = $refFK->getTable();

        $joinedTableObjectBuilder = $this->getNewObjectBuilder($refFK->getTable());
        $className = $joinedTableObjectBuilder->getObjectClassname();

        $varName = $this->getPKRefFKVarName($refFK);

        $script .= "
    /**
     * Sets a single $className object as related to this object by a one-to-one relationship.
     *
     * @param                  $className \$v $className
     * @return "               . $this->getObjectClassname() . " The current object (for fluent API support)
     * @throws PropelException
     */
    public function set" . $this->getRefFKPhpNameAffix($refFK, $plural = false) . "($className \$v = null)
    {
        \$this->$varName = \$v;

        // Make sure that that the passed-in $className isn't already associated with this object
        if (\$v !== null && \$v->get" . $this->getFKPhpNameAffix($refFK, $plural = false) . "(null, false) === null) {
            \$v->set" . $this->getFKPhpNameAffix($refFK, $plural = false) . "(\$this);
        }

        return \$this;
    }
";
    }
1292513
protected function addDoValidate(&$script)
    {
        $table = $this->getTable();
        $script .= "
    /**
     * Validates all modified columns of given " . $this->getObjectClassname() . " object.
     * If parameter \$columns is either a single column name or an array of column names
     * than only those columns are validated.
     *
     * NOTICE: This does not apply to primary or foreign keys for now.
     *
     * @param " . $this->getObjectClassname() . " \$obj The object to validate.
     * @param      mixed \$cols Column name or array of column names.
     *
     * @return mixed TRUE if all columns are valid or the error message of the first invalid column.
     */
    public static function doValidate(\$obj, \$cols = null)
    {
        \$columns = array();

        if (\$cols) {
            \$dbMap = Propel::getDatabaseMap(" . $this->getPeerClassname() . "::DATABASE_NAME);
            \$tableMap = \$dbMap->getTable(" . $this->getPeerClassname() . "::TABLE_NAME);

            if (! is_array(\$cols)) {
                \$cols = array(\$cols);
            }

            foreach (\$cols as \$colName) {
                if (\$tableMap->hasColumn(\$colName)) {
                    \$get = 'get' . \$tableMap->getColumn(\$colName)->getPhpName();
                    \$columns[\$colName] = \$obj->\$get();
                }
            }
        } else {
";
        foreach ($table->getValidators() as $val) {
            $col = $val->getColumn();
            if (!$col->isAutoIncrement()) {
                $script .= "
        if (\$obj->isNew() || \$obj->isColumnModified(" . $this->getColumnConstant($col) . "))
            \$columns[" . $this->getColumnConstant($col) . "] = \$obj->get" . $col->getPhpName() . "();
";
            } // if
        } // foreach

        $script .= "
        }

        return {$this->basePeerClassname}::doValidate(" . $this->getPeerClassname() . "::DATABASE_NAME, " . $this->getPeerClassname() . "::TABLE_NAME, \$columns);
    }
";
    }
1019689
protected function addBuildPkeyCriteriaBody(&$script)
    {
        $script .= "
        \$criteria = new Criteria(" . $this->getPeerClassname() . "::DATABASE_NAME);";
        foreach ($this->getTable()->getPrimaryKey() as $col) {
            $clo = strtolower($col->getName());
            $script .= "
        \$criteria->add(" . $this->getColumnConstant($col) . ", \$this->$clo);";
        }
    }
558547
public function getPrimaryKey ($db, $table)
	{
		
		// Get pk name
		
		return $this->db->query ('SHOW COLUMNS FROM ' . $db . '.' . $table . ' WHERE `Key` = \'PRI\'')->fetch (\PDO::FETCH_ASSOC);
		
	}
743293
protected function addFKMethods(&$script)
    {
        foreach ($this->getTable()->getForeignKeys() as $fk) {
            $this->declareClassFromBuilder($this->getNewStubObjectBuilder($fk->getForeignTable()), 'Child');
            $this->declareClassFromBuilder($this->getNewStubQueryBuilder($fk->getForeignTable()));
            $this->addFKMutator($script, $fk);
            $this->addFKAccessor($script, $fk);
        } // foreach fk
    }
936587
protected function addDoOnDeleteCascade(&$script)
    {
        $table = $this->getTable();
        $script .= "
    /**
     * This is a method for emulating ON DELETE CASCADE for DBs that don't support this
     * feature (like MySQL or SQLite).
     *
     * This method is not very speedy because it must perform a query first to get
     * the implicated records and then perform the deletes by calling those Peer classes.
     *
     * This method should be used within a transaction if possible.
     *
     * @param      Criteria \$criteria
     * @param      PropelPDO \$con
     * @return int The number of affected rows (if supported by underlying database driver).
     */
    protected static function doOnDeleteCascade(Criteria \$criteria, PropelPDO \$con)
    {
        // initialize var to track total num of affected rows
        \$affectedRows = 0;

        // first find the objects that are implicated by the \$criteria
        \$objects = " . $this->getPeerClassname() . "::doSelect(\$criteria, \$con);
        foreach (\$objects as \$obj) {
";

        foreach ($table->getReferrers() as $fk) {

            // $fk is the foreign key in the other table, so localTableName will
            // actually be the table name of other table
            $tblFK = $fk->getTable();

            $joinedTablePeerBuilder = $this->getNewPeerBuilder($tblFK);
            $tblFKPackage = $joinedTablePeerBuilder->getStubPeerBuilder()->getPackage();

            if (!$tblFK->isForReferenceOnly()) {
                // we can't perform operations on tables that are
                // not within the schema (i.e. that we have no map for, etc.)

                $fkClassName = $joinedTablePeerBuilder->getObjectClassname();

                if ($fk->getOnDelete() == ForeignKey::CASCADE) {

                    // backwards on purpose
                    $columnNamesF = $fk->getLocalColumns();
                    $columnNamesL = $fk->getForeignColumns();

                    $script .= "

            // delete related $fkClassName objects
            \$criteria = new Criteria(" . $joinedTablePeerBuilder->getPeerClassname() . "::DATABASE_NAME);
            ";
                    for ($x = 0, $xlen = count($columnNamesF); $x < $xlen; $x++) {
                        $columnFK = $tblFK->getColumn($columnNamesF[$x]);
                        $columnL = $table->getColumn($columnNamesL[$x]);

                        $script .= "
            \$criteria->add(" . $joinedTablePeerBuilder->getColumnConstant($columnFK) . ", \$obj->get" . $columnL->getPhpName() . "());";
                    }

                    $script .= "
            \$affectedRows += " . $joinedTablePeerBuilder->getPeerClassname() . "::doDelete(\$criteria, \$con);";
                } // if cascade && fkey table name != curr table name

            } // if not for ref only
        } // foreach foreign keys
        $script .= "
        }

        return \$affectedRows;
    }
";
    }
107331
protected function addDoOnDeleteSetNull(&$script)
    {
        $table = $this->getTable();
        $script .= "
    /**
     * This is a method for emulating ON DELETE SET NULL DBs that don't support this
     * feature (like MySQL or SQLite).
     *
     * This method is not very speedy because it must perform a query first to get
     * the implicated records and then perform the deletes by calling those Peer classes.
     *
     * This method should be used within a transaction if possible.
     *
     * @param      Criteria \$criteria
     * @param      PropelPDO \$con
     * @return void
     */
    protected static function doOnDeleteSetNull(Criteria \$criteria, PropelPDO \$con)
    {

        // first find the objects that are implicated by the \$criteria
        \$objects = " . $this->getPeerClassname() . "::doSelect(\$criteria, \$con);
        foreach (\$objects as \$obj) {
";

        // This logic is almost exactly the same as that in doOnDeleteCascade()
        // it may make sense to refactor this, provided that things don't
        // get too complicated.

        foreach ($table->getReferrers() as $fk) {

            // $fk is the foreign key in the other table, so localTableName will
            // actually be the table name of other table
            $tblFK = $fk->getTable();
            $refTablePeerBuilder = $this->getNewPeerBuilder($tblFK);

            if (!$tblFK->isForReferenceOnly()) {
                // we can't perform operations on tables that are
                // not within the schema (i.e. that we have no map for, etc.)

                $fkClassName = $refTablePeerBuilder->getObjectClassname();

                if ($fk->getOnDelete() == ForeignKey::SETNULL) {

                    // backwards on purpose
                    $columnNamesF = $fk->getLocalColumns();
                    $columnNamesL = $fk->getForeignColumns(); // should be same num as foreign
                    $script .= "
            // set fkey col in related $fkClassName rows to null
            \$selectCriteria = new Criteria(" . $this->getPeerClassname() . "::DATABASE_NAME);
            \$updateValues = new Criteria(" . $this->getPeerClassname() . "::DATABASE_NAME);";

                    for ($x = 0, $xlen = count($columnNamesF); $x < $xlen; $x++) {
                        $columnFK = $tblFK->getColumn($columnNamesF[$x]);
                        $columnL = $table->getColumn($columnNamesL[$x]);
                        $script .= "
            \$selectCriteria->add(" . $refTablePeerBuilder->getColumnConstant($columnFK) . ", \$obj->get" . $columnL->getPhpName() . "());
            \$updateValues->add(" . $refTablePeerBuilder->getColumnConstant($columnFK) . ", null);
";
                    }

                    $script .= "
            {$this->basePeerClassname}::doUpdate(\$selectCriteria, \$updateValues, \$con); // use BasePeer because generated Peer doUpdate() methods only update using pkey
";
                } // if setnull && fkey table name != curr table name
            } // if not for ref only
        } // foreach foreign keys

        $script .= "
        }
    }
";
    }
619156
protected function addDoUpdate(&$script)
    {
        $table = $this->getTable();
        $script .= "
    /**
     * Performs an UPDATE on the database, given a " . $this->getObjectClassname() . " or Criteria object.
     *
     * @param      mixed \$values Criteria or " . $this->getObjectClassname() . " object containing data that is used to create the UPDATE statement.
     * @param      PropelPDO \$con The connection to use (specify PropelPDO connection object to exert more control over transactions).
     * @return int             The number of affected rows (if supported by underlying database driver).
     * @throws PropelException Any exceptions caught during processing will be
     *		 rethrown wrapped into a PropelException.
     */
    public static function doUpdate(\$values, PropelPDO \$con = null)
    {
        if (\$con === null) {
            \$con = Propel::getConnection(" . $this->getPeerClassname() . "::DATABASE_NAME, Propel::CONNECTION_WRITE);
        }

        \$selectCriteria = new Criteria(" . $this->getPeerClassname() . "::DATABASE_NAME);

        if (\$values instanceof Criteria) {
            \$criteria = clone \$values; // rename for clarity
";
        foreach ($table->getColumns() as $col) {
            if ($col->isPrimaryKey()) {
                $script .= "
            \$comparison = \$criteria->getComparison(" . $this->getColumnConstant($col) . ");
            \$value = \$criteria->remove(" . $this->getColumnConstant($col) . ");
            if (\$value) {
                \$selectCriteria->add(" . $this->getColumnConstant($col) . ", \$value, \$comparison);
            } else {
                \$selectCriteria->setPrimaryTableName(" . $this->getPeerClassname() . "::TABLE_NAME);
            }
";
            } /* if col is prim key */
        } /* foreach */

        $script .= "
        } else { // \$values is " . $this->getObjectClassname() . " object
            \$criteria = \$values->buildCriteria(); // gets full criteria
            \$selectCriteria = \$values->buildPkeyCriteria(); // gets criteria w/ primary key(s)
        }

        // set the correct dbName
        \$criteria->setDbName(" . $this->getPeerClassname() . "::DATABASE_NAME);

        return {$this->basePeerClassname}::doUpdate(\$selectCriteria, \$criteria, \$con);
    }
";
    }
1272104
protected function addFKAccessor(&$script, ForeignKey $fk)
    {
        $table = $this->getTable();

        $varName = $this->getFKVarName($fk);

        $fkQueryBuilder = $this->getNewStubQueryBuilder($fk->getForeignTable());
        $fkObjectBuilder = $this->getNewObjectBuilder($fk->getForeignTable())->getStubObjectBuilder();
        $returnDesc = '';
        if ($interface = $fk->getInterface()) {
            $className = $this->declareClass($interface);
        } else {
            $className = $this->getClassNameFromBuilder($fkObjectBuilder); // get the ClassName that has maybe a prefix
            $returnDesc = "The associated $className object.";
        }

        $and = '';
        $conditional = '';
        $localColumns = []; // foreign key local attributes names

        // If the related columns are a primary key on the foreign table
        // then use findPk() instead of doSelect() to take advantage
        // of instance pooling
        $findPk = $fk->isForeignPrimaryKey();

        foreach ($fk->getMapping() as $mapping) {
            list($column, $rightValueOrColumn) = $mapping;

            $cptype = $column->getPhpType();
            $clo = $column->getLowercasedName();

            if ($rightValueOrColumn instanceof Column) {
                $localColumns[$rightValueOrColumn->getPosition()] = '$this->' . $clo;

                if ($cptype == "int" || $cptype == "float" || $cptype == "double") {
                    $conditional .= $and . "\$this->". $clo ." != 0";
                } elseif ($cptype == "string") {
                    $conditional .= $and . "(\$this->" . $clo ." !== \"\" && \$this->".$clo." !== null)";
                } else {
                    $conditional .= $and . "\$this->" . $clo ." !== null";
                }
            } else {
                $val = var_export($rightValueOrColumn, true);
                $conditional .= $and . "\$this->" . $clo ." === " . $val;
            }


            $and = " && ";
        }

        ksort($localColumns); // restoring the order of the foreign PK
        $localColumns = count($localColumns) > 1 ?
            ('array('.implode(', ', $localColumns).')') : reset($localColumns);

        $script .= "

    /**
     * Get the associated $className object
     *
     * @param  ConnectionInterface \$con Optional Connection object.
     * @return $className $returnDesc
     * @throws PropelException
     */
    public function get".$this->getFKPhpNameAffix($fk, false)."(ConnectionInterface \$con = null)
    {";
        $script .= "
        if (\$this->$varName === null && ($conditional)) {";
        if ($findPk) {
            $script .= "
            \$this->$varName = ".$this->getClassNameFromBuilder($fkQueryBuilder)."::create()->findPk($localColumns, \$con);";
        } else {
            $script .= "
            \$this->$varName = ".$this->getClassNameFromBuilder($fkQueryBuilder)."::create()
                ->filterBy" . $this->getRefFKPhpNameAffix($fk, $plural = false) . "(\$this) // here
                ->findOne(\$con);";
        }
        if ($fk->isLocalPrimaryKey()) {
            $script .= "
            // Because this foreign key represents a one-to-one relationship, we will create a bi-directional association.
            \$this->{$varName}->set".$this->getRefFKPhpNameAffix($fk, false)."(\$this);";
        } else {
            $script .= "
            /* The following can be used additionally to
                guarantee the related object contains a reference
                to this object.  This level of coupling may, however, be
                undesirable since it could result in an only partially populated collection
                in the referenced object.
                \$this->{$varName}->add".$this->getRefFKPhpNameAffix($fk, true)."(\$this);
             */";
        }

        $script .= "
        }

        return \$this->$varName;
    }
";

    }
1108732
protected function addRefFKGet(&$script, ForeignKey $refFK)
    {
        $fkQueryClassName = $this->getClassNameFromBuilder($this->getNewStubQueryBuilder($refFK->getTable()));
        $relCol = $this->getRefFKPhpNameAffix($refFK, $plural = true);
        $collName = $this->getRefFKCollVarName($refFK);

        $className = $this->getClassNameFromTable($refFK->getTable());

        $script .= "
    /**
     * Gets an array of $className objects which contain a foreign key that references this object.
     *
     * If the \$criteria is not null, it is used to always fetch the results from the database.
     * Otherwise the results are fetched from the database the first time, then cached.
     * Next time the same method is called without \$criteria, the cached collection is returned.
     * If this ".$this->getObjectClassName()." is new, it will return
     * an empty collection or the current collection; the criteria is ignored on a new object.
     *
     * @param      Criteria \$criteria optional Criteria object to narrow the query
     * @param      ConnectionInterface \$con optional connection object
     * @return ObjectCollection|{$className}[] List of $className objects
     * @throws PropelException
     */
    public function get$relCol(Criteria \$criteria = null, ConnectionInterface \$con = null)
    {
        \$partial = \$this->{$collName}Partial && !\$this->isNew();
        if (null === \$this->$collName || null !== \$criteria  || \$partial) {
            if (\$this->isNew() && null === \$this->$collName) {
                // return empty collection
                \$this->init" . $this->getRefFKPhpNameAffix($refFK, $plural = true) . "();
            } else {
                \$$collName = $fkQueryClassName::create(null, \$criteria)
                    ->filterBy" . $this->getFKPhpNameAffix($refFK) . "(\$this)
                    ->find(\$con);

                if (null !== \$criteria) {
                    if (false !== \$this->{$collName}Partial && count(\$$collName)) {
                        \$this->init" . $this->getRefFKPhpNameAffix($refFK, $plural = true) . "(false);

                        foreach (\$$collName as \$obj) {
                            if (false == \$this->{$collName}->contains(\$obj)) {
                                \$this->{$collName}->append(\$obj);
                            }
                        }

                        \$this->{$collName}Partial = true;
                    }

                    return \$$collName;
                }

                if (\$partial && \$this->$collName) {
                    foreach (\$this->$collName as \$obj) {
                        if (\$obj->isNew()) {
                            \${$collName}[] = \$obj;
                        }
                    }
                }

                \$this->$collName = \$$collName;
                \$this->{$collName}Partial = false;
            }
        }

        return \$this->$collName;
    }
";
    }
1027488
public function addPrimaryKey($columns)
    {
        $schema = self::SELECT.' EXISTS
                   (
                       '.self::SELECT.' * FROM '.$this->_informationSchema.'.COLUMNS
                       WHERE '.$this->_tableSchema."= '".$this->database."' AND
                       TABLE_NAME ='".$this->tableName."' AND
                       COLUMN_KEY = 'PRI'

                   ) AS has_primary_key;";

        $hasPrimaryKey = $this->_connection->prepare($schema)->execute();

        if ($hasPrimaryKey === true) {
            $query = '';
            $query = self::ALTER_TABLE.'`'.$this->tableName.'` CHANGE
             `'.$this->primaryKey.'` `'.$this->primaryKey.'` INT( 11 ) NOT NULL';
            $primaryKey = $this->_connection->prepare($query)->execute();

            $schemaString = '';
            $schemaString = $this->commands($columns);

            $this->schema = static::ALTER_TABLE.' `'.$this->database.'`.`'.$this->tableName.'` DROP PRIMARY KEY,
                ADD CONSTRAINT PK_'.strtoupper($this->tableName).'_ID
                PRIMARY KEY ('.$schemaString.')';
        } else {
            $this->schema = static::ALTER_TABLE.' `'.$this->database.'`.`'.$this->tableName.'` ADD
            '.'PRIMARY KEY ('.$columns.')';
        }

        return $this;
    }
222655
public function addInheritanceColumnConstants(&$script)
    {
        if (!$col = $this->getTable()->getChildrenColumn()) {
            return;
        }

        if (!$col->isEnumeratedClasses()) {
            return;
        }

        foreach ($col->getChildren() as $child) {
            $childBuilder = $this->getMultiExtendObjectBuilder();
            $childBuilder->setChild($child);
            $fqcn = addslashes($childBuilder->getFullyQualifiedClassName());

            $script .= "
    /** A key representing a particular subclass */
    const CLASSKEY_".$child->getConstantSuffix()." = '" . $child->getKey() . "';
";

            if (strtoupper($child->getClassName()) != $child->getConstantSuffix()) {
                $script .= "
    /** A key representing a particular subclass */
    const CLASSKEY_".strtoupper($child->getClassname())." = '" . $fqcn . "';
";
            }

            $script .= "
    /** A class that can be returned by this tableMap. */
    const CLASSNAME_".$child->getConstantSuffix()." = '". $fqcn . "';
";
        }
    }
1033613
protected function addGetPrimaryKeyHash(&$script)
    {
        // We have to iterate through all the columns so that we know the offset of the primary
        // key columns.
        $n = 0;
        $pk = [];
        $cond = [];
        foreach ($this->getTable()->getColumns() as $col) {
            if (!$col->isLazyLoad()) {
                if ($col->isPrimaryKey()) {
                    $part = "\$row[TableMap::TYPE_NUM == \$indexType ? $n + \$offset : static::translateFieldName('{$col->getPhpName()}', TableMap::TYPE_PHPNAME, \$indexType)]";
                    $cond[] = $part . " === null";
                    $pk[] = $part;
                }
                $n++;
            }
        }

        $script .= "
    /**
     * Retrieves a string version of the primary key from the DB resultset row that can be used to uniquely identify a row in this table.
     *
     * For tables with a single-column primary key, that simple pkey value will be returned.  For tables with
     * a multi-column primary key, a serialize()d version of the primary key will be returned.
     *
     * @param array  \$row       resultset row.
     * @param int    \$offset    The 0-based offset for reading from the resultset row.
     * @param string \$indexType One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_CAMELNAME
     *                           TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM
     *
     * @return string The primary key hash of the row
     */
    public static function getPrimaryKeyHashFromRow(\$row, \$offset = 0, \$indexType = TableMap::TYPE_NUM)
    {";
        if (count($pk) > 0) {
            $script .= "
        // If the PK cannot be derived from the row, return NULL.
        if (".implode(' && ', $cond).") {
            return null;
        }

        return ".$this->getInstancePoolKeySnippet($pk).";
    }
";
        } else {
            $script .= "
        return null;
    }
";
        }
    }