Validate details primary column

@param string $detail
@param string $primary_column
@param string $inactive_column
@param string $pk_column
@return int | null
968126
public function validateDetailsPrimaryColumn(string $detail, string $primary_column, string $inactive_column, string $pk_column, string & $key = null) {
		if (empty($this->values[$detail])) return null;
		$primary_found = 0;
		$primary_first_line = null;
		$primary_pk_id = null;
		foreach ($this->values[$detail] as $k => $v) {
			if (!isset($primary_first_line)) {
				$primary_first_line = "{$detail}[{$k}][{$primary_column}]";
			}
			if (!empty($v[$primary_column])) {
				$primary_pk_id = $v[$pk_column] ?? null;
				$primary_found++;
				if (!empty($v[$inactive_column])) {
					$this->error(DANGER, 'Primary cannot be inactive!', "{$detail}[{$k}][{$inactive_column}]");
				}
				if ($primary_found > 1) {
					$this->error(DANGER, 'There can be only one primary!', "{$detail}[{$k}][{$primary_column}]");
				}
				// we need to pass first primary back
				if ($primary_found == 1) {
					$key = $k;
				}
			}
		}
		if ($primary_found == 0) {
			$this->error(DANGER, 'You must select primary!', $primary_first_line);
		}
		return $primary_pk_id;
	}
892397
public function _cascadeUpdate($parentTableClassname, array $oldPrimaryKey, array $newPrimaryKey)
    {
        $this->_setupMetadata();
        $rowsAffected = 0;
        foreach ($this->_getReferenceMapNormalized() as $map) {
            if ($map[self::REF_TABLE_CLASS] == $parentTableClassname && isset($map[self::ON_UPDATE])) {
                switch ($map[self::ON_UPDATE]) {
                    case self::CASCADE:
                        $newRefs = array();
                        $where = array();
                        for ($i = 0; $i < count($map[self::COLUMNS]); ++$i) {
                            $col = $this->_db->foldCase($map[self::COLUMNS][$i]);
                            $refCol = $this->_db->foldCase($map[self::REF_COLUMNS][$i]);
                            if (array_key_exists($refCol, $newPrimaryKey)) {
                                $newRefs[$col] = $newPrimaryKey[$refCol];
                            }
                            $type = $this->_metadata[$col]['DATA_TYPE'];
                            $where[] = $this->_db->quoteInto(
                                $this->_db->quoteIdentifier($col, true) . ' = ?',
                                $oldPrimaryKey[$refCol], $type);
                        }
                        $rowsAffected += $this->update($newRefs, $where);
                        break;
                    default:
                        // no action
                        break;
                }
            }
        }
        return $rowsAffected;
    }
45171
public function validateUpdateDocument()
    {
        $this->_documentMustHavePrimaryData();
        $this->_primaryDataMustHaveType();
        $this->_primaryDataMustHaveId();
        $this->_primaryDataMayHaveRelationships();

        if ($this->_errorCollection->count() === 0) {
            return;
        }

        throw new ValidationException($this->_getErrorCollectionEntity());
    }
796713
private static void validate(@NotNull EntityMetadata entityMetadata) {
        if (StringUtils.isEmpty(entityMetadata.getTableName())) {
            throw new MetadataException(String.format("Invalid table name: \"%s\"", entityMetadata.getTableName()));
        }

        if (entityMetadata.getPartitionKeySize() < 1) {
            throw new MetadataException(String.format("Entity \"%s\"must contains primary key", entityMetadata.getTableName()));
        }
    }
1146968
public function verifyData($data, $excluded_fields=null, $strict_mode=false)
    {
        $model = static::getQueryModel();
        
        if (!isset($model['fields']) || !isset($model['primary_key'])) {
            return ErrorInfo::error('table has not any fields.');
        }
        
        $errinfo = [];
        if ($data) {
            if (isset($data[0]) && is_array($data[0])) {
                foreach ($data as $k => $v) {
                    $res = static::verifyData($v);
                    if ($res['errcode']) {
                        return $res;
                    }
                }
            } else {
                foreach ($data as $k => $v) {
                    if (isset($model['fields'][$k])) {
                        $field = $model['fields'][$k];
                        
                        $v = FieldInputHandler::formatValue($model['fields'][$k], $v);    // don't modify $data
                        
                        $field_title = isset($model['fields'][$k]['field_title']) ? $model['fields'][$k]['field_title'] : $model['fields'][$k]['field_name'];
                        
                        if (empty($excluded_fields) || !in_array($k, $excluded_fields)) {
                            
                            // check is_nullable and min_length
                            $is_nullable = isset($model['fields'][$k]['is_nullable']) && $model['fields'][$k]['is_nullable'] == 0 ? false : true;
                            $min_length = isset($model['fields'][$k]['min_length']) ? intval($model['fields'][$k]['min_length']) : 0;
                            $min_length = (!$is_nullable) ? $min_length : 0;
                            $is_primary = isset($field['is_primary']) && $field['is_primary'] ? : 0;
                            if (!$is_primary && $min_length && strlen($v) < $min_length) {
                                $errinfo['errcode'] = -201;
                                $errinfo['errmsg'] = $field_title . '不允许为空';    //'至少' . $min_length . '位';
                                break;
                            }
                            
                            // check code type
                            if (isset($model['fields'][$k]['base_type'])) {
                                $base_type = $model['fields'][$k]['base_type'];
                                if (in_array($base_type, ['name', 'code']) && strlen($v) > 0 && !DataHelper::verify_code($v)) {
                                    $errinfo['errcode']  = -202;
                                    $errinfo['errmsg']   = $field_title . '只能取数字字母下划线';
                                    break;
                                }
                            }
                        }
                        
                        // check data_length
                        if (!empty($v) && !empty($model['fields'][$k]['data_length']) && (strlen($v) > $model['fields'][$k]['data_length']) ) {
                            $errinfo['errcode'] = -221;
                            $errinfo['errmsg'] = $field_title . '最大长度为: ' . $model['fields'][$k]['data_length'];
                            break;
                        }
                    } elseif ($strict_mode) {
                        $errinfo['errcode'] = -1;
                        $errinfo['errmsg'] = '数据不正确，不存在字段' . $k;
                        break;
                    }
                }
            }
        }
        
        return ErrorInfo::instance($errinfo);
    }
1223774
public function update()
	{
		//get params from request
		$this->primaryKey = yii::app()->request->getParam('pk');
		$this->attribute = yii::app()->request->getParam('name');
		$this->value = yii::app()->request->getParam('value');

		//checking params
		if (empty($this->attribute)) {
			throw new CException(Yii::t('TbEditableSaver.editable', 'Property "attribute" should be defined.'));
		}
		if (empty($this->primaryKey)) {
			throw new CException(Yii::t('TbEditableSaver.editable', 'Property "primaryKey" should be defined.'));
		}

		//loading model
		$this->model = CActiveRecord::model($this->modelClass)->findByPk($this->primaryKey);
		if (!$this->model) {
			throw new CException(Yii::t(
				'TbEditableSaver.editable',
				'Model {class} not found by primary key "{pk}"',
				array(
					'{class}' => get_class($this->model),
					'{pk}' => is_array($this->primaryKey) ? CJSON::encode($this->primaryKey) : $this->primaryKey
				)
			));
		}

		//set scenario
		$this->model->setScenario($this->scenario);

		//commented to be able to work with virtual attributes
		//see https://github.com/vitalets/yii-bootstrap-editable/issues/15
		/*
		//is attribute exists
		if (!$this->model->hasAttribute($this->attribute)) {
			throw new CException(Yii::t('EditableSaver.editable', 'Model {class} does not have attribute "{attr}"', array(
			  '{class}'=>get_class($this->model), '{attr}'=>$this->attribute)));
		}
		*/

		//is attribute safe
		if (!$this->model->isAttributeSafe($this->attribute)) {
			throw new CException(Yii::t(
				'editable',
				'Model {class} rules do not allow to update attribute "{attr}"',
				array(
					'{class}' => get_class($this->model),
					'{attr}' => $this->attribute
				)
			));
		}

		//setting new value
		$this->setAttribute($this->attribute, $this->value);

		//validate attribute
		$this->model->validate(array($this->attribute));
		$this->checkErrors();

		//trigger beforeUpdate event
		$this->beforeUpdate();
		$this->checkErrors();

		//saving (no validation, only changed attributes)
		if ($this->model->save(false, $this->changedAttributes)) {
			//trigger afterUpdate event
			$this->afterUpdate();
		} else {
			$this->error(Yii::t('TbEditableSaver.editable', 'Error while saving record!'));
		}
	}
40642
public function delete_many($primary_values)
    {
        $primary_values = $this->trigger('before_delete', $primary_values);

        $this->_database->where_in($this->primary_key, $primary_values);

        if ($this->soft_delete)
        {
            $result = $this->_database->update($this->_table, array( $this->soft_delete_key => TRUE ));
        }
        else
        {
            $result = $this->_database->delete($this->_table);
        }

        $this->trigger('after_delete', $result);

        return $result;
    }
1342472
private function _validateOnArguments(ColumnInterface $firstColumn, ColumnInterface $secondColumn)
	{
		$initialJoinArray = array('way' => null, 'tables' => null, 'conditionType' => null, 'condition' => null);
		if($this->joinArray === $initialJoinArray)
		{
			throw new \Exception('method to set join way have call before!');
		}
		if(!$firstColumn->getTableName() || !$secondColumn->getTableName())
		{
			throw new \Exception('column arguments require a referenced table!');
		}
//		if($firstColumn->getColumnName() !== $secondColumn->getColumnName())
//		{
//			throw new \Exception('column arguments require a equivalent column names!');
//		}
	}
881164
public function redrawItem($id, $primary_where_column = null)
	{
		$this->snippets_set = true;

		$this->redraw_item = [($primary_where_column ?: $this->primary_key) => $id];

		$this->redrawControl('items');

		$this->getPresenter()->payload->_datagrid_url = $this->refresh_url;

		$this->onRedraw();
	}
1082100
private void validateIfRequiredByParent(JDBCStorageConnection conn, ResultSet resultSet) throws RepositoryException,
      SQLException, IllegalNameException
   {
      String parentId = getIdentifier(resultSet, DBConstants.COLUMN_PARENTID);
      InternalQName nodeName = InternalQName.parse(resultSet.getString(DBConstants.COLUMN_NAME));

      NodeData parent = null;
      try
      {
         parent = (NodeData)conn.getItemData(parentId);
      }
      catch (PrimaryTypeNotFoundException e)
      {
         // It is possible, parent also without primaryType property
         return;
      }

      // parent already removed in previous check
      if (parent == null)
      {
         return;
      }

      NodeDefinitionData def =
         nodeTypeManager.getChildNodeDefinition(nodeName, parent.getPrimaryTypeName(), parent.getMixinTypeNames());

      if (!def.isResidualSet())
      {
         throw new SQLException("Node is required by its parent.");
      }
   }
251921
public function isColumnInPK(TablePrimaryKey $pk): bool
    {
        return in_array($this->name, $pk->columns, true);
    }
109195
public function findByPK(array $primary_key)
    {
        $where = $this
            ->checkPrimaryKey($primary_key)
            ->getWhereFrom($primary_key)
            ;

        $iterator = $this->findWhere($where);

        return $iterator->isEmpty() ? null : $iterator->current();
    }
475699
function PrimaryKeyIsAutoIncrement()
	{
		$pk = $this->GetPrimaryKeyName(false);
		return $pk && $this->Columns[$pk]->Extra == "auto_increment";
	}
1254839
public static function isCustomerPlanIdValid($postedParam)
	{
		$isCustomerPlanIdEmpty = true;
		$isValidCustomerPlanId = false;

		if(isset($postedParam['customerPlanId'])) {
			$isCustomerPlanIdEmpty = CheckoutApi_Lib_Validator::isEmpty($postedParam['customerPlanId']);
		}

		if(!$isCustomerPlanIdEmpty) {

			$isValidCustomerPlanId = CheckoutApi_Lib_Validator::isString($postedParam['customerPlanId']);
		}

		return !$isCustomerPlanIdEmpty && $isValidCustomerPlanId;
	}
1180371
private function _insert($attrs, $calling, $pk, $pk_value)
    {
        $escape        = Driver::$escape_char;
        $vals          = array();
        $create_column = self::hasColumn("created_at");
        $update_column = self::hasColumn("updated_at");

        $sql = "insert into $escape".$calling::getTableName()."$escape (";

        // remove the current value when need to insert a NULL value to create 
        // the autoincrement value
        if (Driver::$primary_key_behaviour == Driver::PRIMARY_KEY_DELETE && !$pk_value) {
            unset($attrs[$pk]);
        }

        if (Driver::$primary_key_behaviour == Driver::PRIMARY_KEY_SEQUENCE && empty($pk_value)) {
            $seq_name   = self::resolveSequenceName();

            // check if the sequence exists
            self::_checkSequence();
            if (!self::_sequenceExists()) {
                $this->_addError($pk, "Sequence $seq_name could not be created");
                return false;
            }

            // get the sequence next value
            $attrs[$pk] = self::sequenceNextVal($seq_name);
        } 

        // use sequence, but there is already a value on the primary key.
        // remember that it will allow this only if is really a record that
        // wasn't found when checking for the primary key, specifying that its 
        // a new record!
        if (Driver::$primary_key_behaviour == Driver::PRIMARY_KEY_SEQUENCE && !empty($pk_value)) {
            $attrs[$pk] = $pk_value;
        }

        if ($create_column && array_key_exists($create_column, $attrs)) {
            unset($attrs[$create_column]);
        }

        if ($update_column && array_key_exists($update_column, $attrs)) {
            unset($attrs[$update_column]);
        }

        // marks to insert values on prepared statement
        $marks = array();

        foreach ($attrs as $attr => $value) {
            $sql .= "$escape".self::$_mapping[$calling][$attr]."$escape,";
            array_push($marks, "?");
        }

        // if is there a 'created_at' column ...
        if ($create_column) {
            $sql .= "$escape".self::$_mapping[$calling][$create_column]."$escape,";
            array_push($marks, Driver::$current_timestamp);
        }

        // if is there an 'updated_at' column ...
        if ($update_column) {
            $sql .= "$escape".self::$_mapping[$calling][$update_column]."$escape,";
            array_push($marks, Driver::$current_timestamp);
        }

        $marks = join(",", $marks);
        $sql   = substr($sql, 0, strlen($sql)-1);
        $sql  .= ") values ($marks)";

        // now fill the $vals array with all values to be inserted on the 
        // prepared statement
        foreach ($attrs as $attr => $value) {
            array_push($vals, $value);
        }
        $rtn = self::executePrepared($sql, $vals)->rowCount()==1;

        // if inserted
        if ($rtn) {
            // check for last inserted value
            $lid = null;
            if (Driver::$last_id_supported) {
                $lid = self::resolveConnection()->lastInsertId();
                if (empty($this->_data[$pk]) && !empty($lid)) {
                    $this->_data[$pk] = $lid;
                }
            }

            // or, like Oracle, if the database does not support last inserted id
            if (empty($this->_data[$pk]) && empty($lid) && !empty($attrs[$pk])) {
                $this->_data[$pk] = $attrs[$pk];
            }

            // check for database filled columns
            if ($this->_data[$pk]) {
                $found = self::find($this->_data[$pk]);
                if ($found) {
                    if ($create_column) {
                        $this->_data[$create_column] = $found->get($create_column);
                    }
                }
            }

            // push later objects
            foreach ($this->_push_later as $obj) {
                $this->push($obj);
            }
            $this->_push_later = array();
        }
        return $rtn;
    }
1153280
public function getPrimaryKeyMetadata(): ?ColumnMetadata
    {
        $filteredColumnList = array_filter($this->columnMetadataList, function (ColumnMetadata $columnMetadata) {
            return $columnMetadata->isPrimaryKey();
        });

        return (count($filteredColumnList)) ? current($filteredColumnList) : null;
    }
894039
public function has(int $primaryKey) : bool
    {
        foreach ($this->rows as $row) {
            if ($row->getColumn($this->primaryKey) === $primaryKey) {
                return true;
            }
        }

        return false;
    }