verify unique

@param  array $data
@param  array $where
@return \Wslim\Common\ErrorInfo
551853
protected function verifyUnique($data, $where=null)
    {
        $model = static::getQueryModel();
        
        if ($data && isset($model['primary_key']) && isset($model['unique_key'])) {
            if (isset($data[0]) && is_array($data[0])) {
                foreach ($data as $k => $v) {
                    $res = static::verifyUnique($v, $where);
                    if ($res->isError()) {
                        return $res;
                    }
                }
                return ErrorInfo::success();
            } else {
                $uks = StringHelper::toArray($model['unique_key']);
                $pk  = $model['primary_key'];
                $check = true;
                $where = is_numeric($where) ? [$pk => $where] : (array) $where;
                foreach ($uks as $v) {
                    if (!isset($data[$v]) || !$data[$v]) {
                        $check = false;
                        break;
                    }
                    $where[$v] = $data[$v];
                }
                if ($check) {
                    if (isset($data[$pk])) {
                        $where[$pk] = ['<>', intval($data[$pk])];
                    }
                    $exists = static::table($model['table_name'])->exists($where);
                    
                    if ($exists) {
                        return ErrorInfo::error(-101, '请检查记录唯一性');
                    }
                }
                
                return ErrorInfo::success();
            }
        } else {
            return ErrorInfo::success('do not need verify unique.');
        }
    }
761681
private function checkAllow($where, $that)
    {
        if (is_array($where) && !array_search('*', $where)) {
            $this->logger->info('Checking permissions '.$that.', in: '.var_export($where, true));

            return  in_array($that, $where) ? true : false;
        }

        if ($where == '*' || (is_array($where) && array_search('*', $where)) || (trim($where) == trim($that))) {
            $this->logger->info('Checking permissions '.$that.', in: '.$where);

            return true;
        }

        return false;
    }
911648
public function isOne(Array $where)
    {
        $param = '';
        foreach ($where as $key => $value) {
            if (is_int($key)) { //如果下标是数字，则不用下标拼装sql
                $param .= $value . ' AND ';
            } else {
                $param .= "$key='$value' AND ";
            }
        }
        $param = substr($param, 0, -4);
        $this->sql = "SELECT count(*) FROM { $this->_table } WHERE $param LIMIT 1";
        return $this->execute()->rowCount();
    }
453919
public function recordExists($data = [])
    {

        if (empty($data)) {
            $data = $this->getData();
        }
        $ignorestate = $this->ignore404();
        $this->ignore404(true);
        $keyColumn   = $this->getKeyColumn();
        $res         = $this->getColumnsFromFlexibee([$keyColumn],
            is_array($data) ? $data : [$keyColumn => $data]);

        if (empty($res) || (isset($res['success']) && ($res['success'] == 'false'))
            || ((isset($res) && is_array($res)) && !isset($res[0]) )) {
            $found = false;
        } else {
            $found = true;
        }
        $this->ignore404($ignorestate);
        return $found;
    }
181885
protected function whereBetween(array $where)
    {
        return $this->wrap($where['column']) . ' ' . ($where['not'] ? 'NOT BETWEEN' : 'BETWEEN') . ' ' . $this->param($where['value1']) . ' AND ' . $this->param($where['value2']);
    }
146078
public static function find(array $where) {
        $model = get_called_class();
        /* @var $t Record */
        $t = new $model;
        /* @var $db_cache DBCache */
        $db_cache = Ioc::get(DBCache::class);
        $data = $db_cache->recordWhereCache($model, $where);
        if ($data) {
            return $data;
        }
        /* @var $data Record */
        $select = DB::select($t->getTable())->where($where)->setRecord($model);
        Event::trigger('record_before_select', [$t, $select]);
        $data = $select->find();
        $db_cache->recordWhereCacheSave($model, $where, $data->_db_data);
        return $data;
    }
949335
public function update(array $data, array $where = [])
    {
        // Prepare query
        $query = $this->genUpdate($data, $where);
        $statement = $this->getInstance()->prepare($query);

        // Bind field values
        foreach ($data as $key => $value) {
            $statement->bindValue(":field_$key", $value, $this->isPdoInt($value));
        }

        // Bind where values
        foreach ($where as $key => $value) {
            $statement->bindValue(":where_$key", $value, $this->isPdoInt($value));
        }

        // Execute operation
        $statement->execute();

        // Return count of affected rows
        return $statement->rowCount();
    }
1101560
public function countWhere($where, array $values = [])
    {
        $sql = sprintf(
            "select count(*) as result from %s where :condition",
            $this->getStructure()->getRelation()
        );

        return $this->fetchSingleValue($sql, $where, $values);
    }
312314
private function genUpdate(array $data, array $where): string
    {
        // Current table
        $table = $this->getCollection();

        // Generate line with data for update
        $fieldDetails = !empty($data)
            ? $this->genFields($data)
            : '';

        // Generate where line
        $whereDetails = !empty($where)
            ? ' WHERE ' . $this->genWhere($where)
            : '';

        return "UPDATE $table SET $fieldDetails $whereDetails";
    }
1113318
public function where(array $where)
    {
        $this->applyCriteria();
        $this->applyScope();

        $this->applyConditions($where);

        return $this;
    }
45800
public function update($data, $where = [])
    {
        /*
         | Trigger Before Update events if
         | defined by user into model class
         |
         */
        $this->triggerEvent('beforeUpdate');

        if (!empty($where)) {
            $whereStr = $this->buildWherePlaceholderName($where);
        } else {
            list($where, $whereStr) = $this->buildWhereForUpdate();
        }

        $sql = $this->getUpdateQuery($data, strtoupper(__FUNCTION__)).$whereStr;

        try {
            $stmt = $this->resolveConnection()->prepare($sql);

            //Bind all values to query statement
            foreach ($data as $key => $val) {
                $stmt->bindValue(":$key", $val);
            }

            foreach ($where as $key => $value) {
                $stmt->bindValue(":$key", $value);
            }

            static::$queries[] = $stmt->queryString;
            $affectedRow = $stmt->execute();

            /*
             | Trigger after update events if defined
             | into model class
             |
             */
            $this->triggerEvent('afterUpdate');

            return $affectedRow;
        } catch (\PDOException  $exception) {
            throw new \Exception($exception->getMessage());
        }
    }
642859
private function validateUnique(array $uniqueFields, array $data, $mode, $class)
    {
        $errors = [];

        foreach ($uniqueFields as $dataProp => $entityProp) {
            if (isset($data[$dataProp])) {
                $qb = $this->om->createQueryBuilder();

                $qb->select('DISTINCT o')
               ->from($class, 'o')
               ->where("o.{$entityProp} LIKE :{$entityProp}")
               ->setParameter($entityProp, $data[$dataProp]);

                if (self::UPDATE === $mode && isset($data['id'])) {
                    $parameter = is_numeric($data['id']) ? 'id' : 'uuid';
                    $value = is_numeric($data['id']) ? (int) $data['id'] : $data['id'];
                    $qb->setParameter($parameter, $value)->andWhere("o.{$parameter} != :{$parameter}");
                }

                $objects = $qb->getQuery()->getResult();

                if ((self::UPDATE === $mode && isset($data['id'])) || self::CREATE === $mode) {
                    if (count($objects) > 0) {
                        $errors[] = ['path' => $dataProp, 'message' => "{$entityProp} already exists and should be unique"];
                    }
                } else {
                    if (count($objects) > 1) {
                        $errors[] = ['path' => $dataProp, 'message' => "{$entityProp} already exists and should be unique"];
                    }
                }
            }
        }

        return $errors;
    }
1138816
public function update($tableName, array $data, $where = null)
    {
        return $this->pdo->update($tableName, $data, $where);
    }
125603
function update(array $where, array $data, $returning = "*") {
		$query = $this->getQueryWriter()->reset();
		$query->write("UPDATE", $this->conn->quoteName($this->name));
		$first = true;
		foreach ($data as $key => $val) {
			$query->write($first ? "SET" : ",", $key, "=", 
				$query->param($val, $this->getAttributes()->getColumn($key)->type));
			$first and $first = false;
		}
		$query->write("WHERE")->criteria($where);
		if (strlen($returning)) {
			$query->write("RETURNING", $returning);
		}
		return $this->execute($query);
	}
467248
public function update(array $data, $where, $table = null)
    {
        $table = ($table) ?: $this->getTable();
        $sql = $this->getSql();
        $update = $sql->update($table);

        $update->set($data)
            ->where($where);

        $statement = $sql->prepareStatementForSqlObject($update);
        $result = $statement->execute();

        return $result->getAffectedRows();
    }
414081
public function checkExistsAndInsertData($data = [], $wheres = [])
    {
        $this->connection();
        $db = DB::table($this->table);
        if (is_array($wheres) && count($wheres) > 0) {
            foreach ($wheres as $field => $value) {
                if (is_array($value)) {
                    $db->whereIn($field, $value);
                } else {
                    $db->where($field, self::OPERATOR_EQUAL_TO, $value);
                }
            }
        } else {
            $db->where($this->primaryKey, self::OPERATOR_EQUAL_TO, $wheres);
        }
        $checkExists = $db->count();
        $this->debug->debug(__FUNCTION__, 'Check Exists Data: ' . $checkExists);
        if (!$checkExists) {
            $id = $db->insertGetId($data);
            $this->debug->debug(__FUNCTION__, 'SQL Queries: ' . $db->toSql());
            $this->debug->debug(__FUNCTION__, 'Result Insert ID: ' . $id);

            return $id;
        } else {
            $this->debug->debug(__FUNCTION__, 'Đã tồn tại bản ghi, bỏ qua không ghi nữa');

            return FALSE;
        }
    }
1078183
public function destroy(array $where) {
        $where = $this->_createWhereClause($where, 'AND', false);
        try {
            /**
             * First, see if the user is allowed to update everything
             */
            $this->_checkAcl('destroy');
            $this->_model->delete($where);
        } catch (Garp_Auth_Exception $e) {
            /**
             * If that fails, check if the user is allowed to update her own material
             * AND if the current item is hers.
             */
            $this->_checkAcl('destroy_own');

            /**
             * Good, the user is allowed to 'destroy_own'. In that case we have to check
             * if the current item is actually the user's.
             */
            $rows = $this->_model->fetchAll($where);
            foreach ($rows as $row) {
                if (!$this->_itemBelongsToUser($row->toArray())) {
                    throw new Garp_Auth_Exception(
                        'You are only allowed to delete your own material.'
                    );
                }
                $row->delete();
            }
        }
    }