创建单表操作的 insert 语句(批量)
@return string
@throws Exception
427195
protected function buildMultiSql()
    {
        $query = $this->getQuery();
        if (
            !isset($query['table']) || empty($query['table'])
            || !isset($query['multi-fields']) || empty($query['multi-fields'])
            || !isset($query['multi-data']) || empty($query['multi-data'])
        ) {
            throw new Exception(str_cover('"{type}"查询参数不完整', [
                '{type}' => 'multi-insert'
            ]), 101300302);
        }
        $KS = [];
        foreach ($query['multi-fields'] as $k) {
            $KS[] = $this->quoteColumnName($k);
        }
        $_VS = [];
        foreach ($query['multi-data'] as $data) {
            $bks = [];
            foreach ($data as $v) {
                if ($v instanceof Expression) {
                    $bks[] = $v->expression;
                    continue;
                }
                $bks[] = $bk = $this->getBindKey();
                $this->addParam($bk, $v);
            }
            $_VS[] = '(' . implode(',', $bks) . ')';
        }
        $sql = 'INSERT INTO '
            . $this->quoteTableName($query['table'])
            . ' (' . implode(',', $KS) . ') VALUES ' . implode(',', $_VS);
        return $sql;
    }
768037
public function insert()
    {
        Observer::dispatch(Observer::EVENT_ITEM_INSERT_BEFORE, array(
            'item' => $this
        ));

        $this->{static::DATEADDFIELD} = DateData::now();
        $insert = new Insert($this->_dbContainer);
        $insert->addFields($this->_fields);
        $insert->commit();
        $this->setId($insert->getId());
        $this->_origFields = $this->_fields;

        Observer::dispatch(Observer::EVENT_ITEM_INSERT_AFTER, array(
            'item' => $this
        ));

        return $this;
    }
46127
public function getAccessToken()
    {
        $param = [
            'grant_type' => 'client_credentials',
            'client_id' => $this->apiKey,
            'client_secret' => $this->secretKey
        ];
        $result = $this->client->post($this->accessTokenUrl(), $param);

        if (!is_array($result)) {
            throw new Exception('请求access token失败');
        }

        $content = json_decode($result['content'], true);
        $this->accessToken = $content['access_token'];
    }
273981
private function getInsertQuery()
    {
        return 'INSERT INTO '.$this->parts['from'][0]['table'].
               ' ('.implode(', ', array_keys($this->parts['set'])).')'.
               ' VALUES'.
               ' ('.implode(', ', $this->parts['set']).')';
    }
147339
function insert() {
		if ($this->id)
			return $this->update();
		$db=$this->db;
		$now=microtime(TRUE);
		while (($id=uniqid(NULL,TRUE)) &&
			($data=&$db->read($this->file)) && isset($data[$id]) &&
			!connection_aborted())
			usleep(mt_rand(0,100));
		$this->id=$id;
		$pkey=['_id'=>$this->id];
		if (isset($this->trigger['beforeinsert']) &&
			\Base::instance()->call($this->trigger['beforeinsert'],
				[$this,$pkey])===FALSE)
			return $this->document;
		$data[$id]=$this->document;
		$db->write($this->file,$data);
		$db->jot('('.sprintf('%.1f',1e3*(microtime(TRUE)-$now)).'ms) '.
			$this->file.' [insert] '.json_encode($this->document));
		if (isset($this->trigger['afterinsert']))
			\Base::instance()->call($this->trigger['afterinsert'],
				[$this,$pkey]);
		$this->load(['@_id=?',$this->id]);
		return $this->document;
	}
567713
public function insert() {
        $sql = new Sql();
        $queryFields = '';
        $queryValues = '';
        $manyToMany = null;
        $transaction = Database::instance()->db()->inTransaction();

        if (!$transaction) {
            Database::instance()->db()->beginTransaction();
        }

        /** @var $fieldsInsertOneToMany \Gcs\Framework\Core\Orm\Entity\Entity[] */
        $fieldsInsertOneToMany = [];
        /** @var $fieldsUpdateOneToMany \Gcs\Framework\Core\Orm\Entity\Entity[] */
        $fieldsUpdateOneToMany = [];

        /** @var $fieldsInsertOneToMany \Gcs\Framework\Core\Orm\Entity\Entity[] */
        $fieldsInsertManyToMany = [];
        /** @var $fieldsUpdateOneToMany \Gcs\Framework\Core\Orm\Entity\Entity[] */
        $fieldsUpdateManyToMany = [];

        /** @var $field \Gcs\Framework\Core\Orm\Entity\Field */
        foreach ($this->_fields as $field) {
            if ($field->primary == false) {
                if ($field->foreign != null) {
                    switch ($field->foreign->type()) {
                        case ForeignKey::ONE_TO_ONE :
                            if (gettype($field->value) != 'object') {
                                if ($field->foreign->belong() == ForeignKey::COMPOSITION) {
                                    throw new MissingEntityException('The field "' . $field->name . '" in "' . $this->_name . '" must be an Entity');
                                }
                            }
                            if (!preg_match('#Orm\\\Entity\\\#isU', get_class($field->value))) {
                                throw new MissingEntityException('The foreign key "' . $field->name . '" in "' . $this->_name . '" must be an Entity object');
                            }

                            if ($field->value == null) {
                                throw new MissingEntityException('The field "' . $field->name . '" in "' . $this->_name . '" can\'t be null');
                            }
                            else {
                                $field->value->insert();
                                $queryFields .= $field->name . ', ';
                                $queryValues .= ':' . $field->name . ', ';
                                $sql->vars($field->name, $field->value->get($field->foreign->referenceField()));
                            }
                            break;

                        case ForeignKey::MANY_TO_ONE :
                            if (gettype($field->value) != 'object') {
                                if ($field->foreign->belong() == ForeignKey::COMPOSITION) {
                                    throw new MissingEntityException('The field "' . $field->name . '" in "' . $this->_name . '" must be an Entity');
                                }
                            }
                            if (!preg_match('#Orm\\\Entity\\\#isU', get_class($field->value))) {
                                //throw new MissingEntityException('The foreign key "'.$field->name.'" in "'.$this->_name.'" must be an Entity object');
                            }

                            if ($field->value == null) {
                                if ($field->beNull == false) {
                                    throw new MissingEntityException('The field "' . $field->name . '" in "' . $this->_name . '" can\'t be null');
                                }
                                else {
                                    $sql->vars($field->name, null);
                                    $queryFields .= $field->name . ', ';
                                    $queryValues .= ':' . $field->name . ', ';
                                }
                            }
                            else {
                                if ($field->value->get($field->value->primary()) == null) {
                                    $field->value->insert();
                                }

                                $sql->vars($field->name, $field->value->get($field->foreign->referenceField()));
                                $queryFields .= $field->name . ', ';
                                $queryValues .= ':' . $field->name . ', ';
                            }
                            break;

                        case ForeignKey::ONE_TO_MANY :
                            /** If we insert a new line and the are already sub-objects, we have to insert or update them */
                            if ($field->value != null) {
                                if (gettype($field->value) != 'object') {
                                    if ($field->foreign->belong() == ForeignKey::COMPOSITION) {
                                        throw new MissingEntityException('The field "' . $field->name . '" in "' . $this->_name . '" must be a Collection');
                                    }
                                }
                                if (get_class($field->value) != 'System\Collection\Collection') {
                                    throw new MissingEntityException('The field "' . $field->name . '" in "' . $this->_name . '" must be a Collection');
                                }

                                /** @var $entity \Gcs\Framework\Core\Orm\Entity\Entity */
                                foreach ($field->value as $entity) {
                                    if ($entity != null) {
                                        /** the field is not in database yet, so after the insert of the Entity, we will do an insert for it */
                                        if ($entity->get($entity->primary()) == null) {
                                            array_push($fieldsInsertOneToMany, $entity);
                                        }
                                        /** the field is already in database, so after the insert of the Entity, we will do an update for it */
                                        else if ($entity->get($entity->primary()) != null) {
                                            array_push($fieldsUpdateOneToMany, $entity);
                                        }
                                    }
                                    else {
                                        if ($field->foreign->belong() == ForeignKey::COMPOSITION) {
                                            throw new MissingEntityException('The Collection field "' . $field->name . '" in "' . $this->_name . '" can\'t have a null item because the relation is a composition');
                                        }
                                    }
                                }
                            }
                            else if ($field->beNull == false) {
                                throw new MissingEntityException('The field "' . $field->name . '" in "' . $this->_name . '" can\'t be null');
                            }
                            break;

                        case ForeignKey::MANY_TO_MANY :
                            /** If we insert a new line and the are already sub-objects, we have to insert or update them */
                            if ($field->value != null) {
                                if (gettype($field->value) != 'object') {
                                    throw new MissingEntityException('The field "' . $field->name . '" in "' . $this->_name . '" must be a Collection');
                                }
                                if (get_class($field->value) != 'System\Collection\Collection') {
                                    throw new MissingEntityException('The field "' . $field->name . '" in "' . $this->_name . '" must be a Collection');
                                }

                                $manyToMany = $field;

                                /** @var $entity \Gcs\Framework\Core\Orm\Entity\Entity */
                                foreach ($field->value as $entity) {
                                    if ($entity != null) {
                                        /** the field is not in database yet, so after the insert of the Entity, we will do an insert for it */
                                        if ($entity->get($entity->primary()) == null) {
                                            array_push($fieldsInsertManyToMany, $entity);
                                        }
                                        else {
                                            array_push($fieldsUpdateManyToMany, $entity);
                                        }
                                    }
                                    else {
                                        throw new MissingEntityException('The Entity "' . get_class($entity) . '" in "' . $this->_name . '" can\'t be null');
                                    }
                                }
                            }
                            else if ($field->beNull == false) {
                                throw new MissingEntityException('The field "' . $field->name . '" in "' . $this->_name . '" can\'t be null');
                            }
                            break;
                    }
                }
                else {
                    if ($field->value == null && $field->beNull == false && $field->default == '') {
                        throw new MissingEntityException('The field "' . $field->name . '" in "' . $this->_name . '" can\'t be null');
                    }

                    if ($field->value == null) {
                        $field->value = $field->default;
                    }

                    if (gettype($field->value) != 'object') {
                        if (in_array($field->type, [Field::INCREMENT, Field::INT, Field::FLOAT])) {
                            $sql->vars($field->name, [$field->value, Sql::PARAM_INT]);
                        }
                        else if (in_array($field->type, [Field::CHAR, Field::TEXT, Field::STRING, Field::DATE, Field::DATETIME, Field::TIMESTAMP])) {
                            $sql->vars($field->name, [$field->value, Sql::PARAM_STR]);
                        }
                        else if (in_array($field->type, [Field::BOOL])) {
                            $sql->vars($field->name, [$field->value, Sql::PARAM_BOOL]);
                        }
                        else {
                            $sql->vars($field->name, $field->value);
                        }
                    }
                    elseif (in_array($field->type, [Field::DATETIME, Field::TIMESTAMP])) {
                        $sql->vars($field->name, [$field->value->format("Y-m-d H:i:s"), Sql::PARAM_STR]);
                    }
                    elseif (in_array($field->type, [Field::DATE])) {
                        $sql->vars($field->name, [$field->value->format("Y-m-d"), Sql::PARAM_STR]);
                    }
                    else if (in_array($field->type, [Field::FILE])) {
                        $sql->vars($field->name, $field->value->value());
                        $field->value->save();
                    }

                    $queryFields .= $field->name . ', ';
                    $queryValues .= ':' . $field->name . ', ';
                }
            }
        }

        /** Execution of the query */
        $queryFields = substr(trim($queryFields, ','), 0, strlen($queryFields) - 2);
        $queryValues = substr(trim($queryValues, ','), 0, strlen($queryValues) - 2);

        $query = 'INSERT INTO ' . $this->_name . '(' . $queryFields . ') VALUES(' . $queryValues . ')';

        $sql->query('insert_' . $this->_name . '_' . $this->_token, $query);
        $sql->fetch('insert_' . $this->_name . '_' . $this->_token, Sql::PARAM_FETCHINSERT);

        /** Update primary key */
        $this->_fields[$this->_primary]->value = Database::instance()->db()->lastInsertId();

        /** ######################################################################## */
        /** One to many and many to many need more queries after the principal query */

        /** @var $field \Gcs\Framework\Core\Orm\Entity\Field */
        foreach ($fieldsInsertOneToMany as $fields) {
            $relation = '';

            /** @var $relationFields \Gcs\Framework\Core\Orm\Entity\Field */
            foreach ($fields->fields() as $relationFields) {
                if ($relationFields->foreign != null) {
                    if ($relationFields->foreign->referenceEntity() == ucfirst(strtolower($this->_name))) {
                        $relation = $relationFields->foreign->field();
                    }
                }
            }

            $fields->set($relation, $this);
            $fields->insert();
        }

        foreach ($fieldsUpdateOneToMany as $fields) {
            $relation = '';

            /** @var $relationFields \Gcs\Framework\Core\Orm\Entity\Field */
            foreach ($fields->fields() as $relationFields) {
                if ($relationFields->foreign != null) {
                    if ($relationFields->foreign->referenceEntity() == ucfirst(strtolower($this->_name))) {
                        $relation = $relationFields->foreign->field();
                    }
                }
            }

            $fields->set($relation, $this);
            $fields->update();
        }

        if ($manyToMany != null) {
            $currentEntity = $manyToMany->foreign->entity();
            $currentField = $manyToMany->foreign->field();
            $referenceEntity = $manyToMany->foreign->referenceEntity();
            $referenceField = $manyToMany->foreign->referenceField();

            $current = strtolower($currentEntity . $currentField);
            $reference = strtolower($referenceEntity . $referenceField);
            $table = [$current, $reference];
            sort($table, SORT_STRING);
            $table = ucfirst($table[0] . $table[1]);

            $class = '\Orm\Entity\\' . $manyToMany->foreign->referenceEntity();
            /** @var $referencedEntity \Gcs\Framework\Core\Orm\Entity\Entity */
            $referencedEntity = new $class();

            $sql = new Sql();
            $sql->query('orm-delete-many', 'DELETE FROM ' . $table . ' WHERE ' . $this->name() . '_' . $manyToMany->foreign->referenceField() . ' = ' . $this->_fields[$this->_primary]->value);
            $sql->fetch('orm-delete-many');

            /** @var $fields \Gcs\Framework\Core\Orm\Entity\Entity */
            foreach ($fieldsInsertManyToMany as $fields) {
                $fields->set($manyToMany->foreign->field(), $this);
                $fields->insert();

                $sql->query('orm-insert-many', 'INSERT INTO ' . $table . '(' . $this->name() . '_' . $manyToMany->foreign->referenceField() . ', ' . $referencedEntity->name() . '_' . $manyToMany->foreign->field() . ') VALUES (\'' . $this->_fields[$this->_primary]->value . '\', \'' . $fields->get($manyToMany->foreign->field()) . '\')');
                $sql->fetch('orm-insert-many');
            }

            /** @var $fields \Gcs\Framework\Core\Orm\Entity\Entity */
            foreach ($fieldsUpdateManyToMany as $fields) {
                $sql->query('orm-update-many', 'INSERT INTO ' . $table . '(' . $this->name() . '_' . $manyToMany->foreign->referenceField() . ', ' . $referencedEntity->name() . '_' . $manyToMany->foreign->field() . ') VALUES (\'' . $this->_fields[$this->_primary]->value . '\', \'' . $fields->get($manyToMany->foreign->field()) . '\')');
                $sql->fetch('orm-update-many');
            }
        }

        if (!$transaction) {
            Database::instance()->db()->commit();
        }
    }
1094989
public function generatePK()
    {
        $format = $this->pkFormat;
        $pk     = $this->_properties['primary_key'];
        if (isset($pk[1]))
            throw new Exception(sprintf(self::E_Composit, get_called_class(), __FUNCTION__), 1);

        $pk     = array_shift($pk);
        if (!$pk)
            throw new Exception(sprintf(self::E_PrimaryKey, get_called_class()), 1);

        $last = (int) $this
            ->select(($format['serial']?
                'right('.$pk.', '.$format['serial'].')':
                $pk).' as last')
            ->order($pk.' desc')
            ->read(1)
            ->last;

        // compile prefix format
        if (preg_match('/\{(?<date>.+)\}/', $format['prefix'], $match))
            $newPK = preg_replace('/\{.+\}/', date($match['date']), $format['prefix']);
        else
            $newPK = $format['prefix'];

        $newPK .= trim(str_pad($last+1, $format['serial'], $format['prefix']?'0':' ', STR_PAD_LEFT));

        return $newPK;
    }
677993
protected function getCrypt()
    {
        static $crypt;

        if (!$crypt) {
            if (empty($this->encodingAESKey) || empty($this->token)) {
                throw new Exception("加密模式下 'encodingAESKey' 与 'token' 都不能为空！");
            }

            $crypt = new Crypt($this->appId, $this->token, $this->encodingAESKey);
        }

        return $crypt;
    }
805186
public function values()
    {

        $arg_list = func_get_args();

        $numargs = func_num_args();

        if (($this->oosql_numargs !== 0 && $numargs !== $this->oosql_numargs) || $numargs === 0) {
            $msg = 'Insert numargs: ' . $this->oosql_numargs . ' | values numargs = ' . $numargs . ', Columns and passed data do not match! ' . $this->sql();
            throw new \Exception($msg, 9809, null);
        }

        $this->sql(' VALUES (');

        for ($i = 0; $i < $numargs; $i++) {
            if ($i != 0 && $numargs > 1) {
                $this->sql(',');
            }

            if (is_array($arg_list[$i])) {
                $this->sql(rtrim(str_repeat('?,', count($arg_list[$i])), ','));
                $this->oosql_conValues += $arg_list[$i];
            } else {
                $this->oosql_conValues[] = $arg_list[$i];
                $this->sql(' ?');
            }
        }


        $this->sql(')');

        $this->oosql_fromFlag = false;
        return $this;
    }
975364
public function dump()
	{
		$pdo = $this->pdo();

		$sql = '';

		foreach ($this->list_tables() as $table)
		{
			$query = $pdo->query("SELECT * FROM `{$table}`");

			while ($row = $query->fetch(\PDO::FETCH_NUM)) 
			{
				$values = array();

				foreach ($row as $column) 
				{
					$values[] = is_null($column) ? 'NULL' : $pdo->quote($column);
				}

				$sql .= "INSERT INTO `{$table}` VALUES (".join(',', $values). ");\n";
			}
		}

		return $sql;
	}
954758
public function getSQL(): string
    {
        if ($this->query === null) {
            throw new Exception('Query wasn\'t set');
        }

        if (is_object($this->query)) {
            if (method_exists($this->query, '__toString')) {
                return $this->query->__toString();
            }
        } else {
            return trim($this->query);
        }

        $className = get_class($this->query);
        throw new Exception("Can not use class={$className} as database query because it can't be used as string");
    }
863754
public function insert()
    {
        $data = $this->data;
        $ret = $this->conn()->selectCollection($this->table_name)->insert($data);
        $this->sql = array('table'=> $this->table_name,'insert_data'=> $this->data);

        $this->_clear_var();
        if ($ret) {
            return $data['_id'];
        } else {
            return false;
        }
    }
803998
private function createExist(): string
    {
        // 先构造子查询
        $this->createSelect();

        // 使用子查询构造存在查询
        $this->prepare = $this->db->createExist($this->prepare);
        $this->sql = $this->db->createExist($this->sql);

        $this->tables = [$this->table];
        return $this->prepare;
    }
586495
public function execute()
	{
		$query  = $this->factory->builder($this->insert)->process();
		$result = $this->pdo->query($query);
		if(!$result)
		{
			throw new \Exception('An error is while the insertion occurred! (query: "' . $query . '")');
		}

		return $this->pdo->lastInsertId();
	}
393521
protected function insert() {
		$conn = static::getConnection();
		$pk = static::getPrimaryKey();

		$fields = array();
		$values = array();
		$placeholders = array();
		foreach (static::$_columns as $column_name => &$type) {
			$value = $this->$column_name;
			if ($value === null && !$this->isColumnModified($column_name))
				continue;
			$fields[] = $conn->quoteIdentifier($column_name, true);
			$values[] = $value;
			$placeholders[] = '?';
		}

		$quoted_table = $conn->quoteIdentifier(static::getTableName(), true);
		$query_s = 'INSERT INTO ' . $quoted_table . ' (' . implode(', ', $fields) . ')';

		if ($pk && $this->isAutoIncrement() && $conn instanceof DBMSSQL) {
			$query_s .= " OUTPUT inserted.$pk";
		}

		$query_s .= ' VALUES (' . implode(', ', $placeholders) . ') ';

		if ($pk && $this->isAutoIncrement() && $conn instanceof DBPostgres) {
			$query_s .= ' RETURNING ' . $conn->quoteIdentifier($pk, true);
		}

		$statement = new QueryStatement($conn);
		$statement->setString($query_s);
		$statement->setParams($values);

		$result = $statement->bindAndExecute();
		$count = $result->rowCount();

		if ($pk && $this->isAutoIncrement()) {
			$id = null;
			if (($conn instanceof DBPostgres) || ($conn instanceof DBMSSQL)) {
				$id = $result->fetchColumn(0);
			} elseif ($conn->isGetIdAfterInsert()) {
				$id = $conn->lastInsertId();
				if (empty($id) && $conn instanceof DBRedshift) {
					$id = $conn->query('SELECT MAX(' . $conn->quoteIdentifier($pk) . ") FROM $quoted_table")->fetchColumn();
				}
			}
			if (null !== $id) {
				$this->{"set$pk"}($id);
			}
		}

		$this->resetModified();
		$this->setNew(false);

		$this->insertIntoPool($this);

		return $count;
	}
526644
final public function commit()
    {
        if (!$this->pdo) {
            throw  new Exception('您还没有连接数据库', Exception::CODE_DATABASE_ERROR);
        }
        $this->_begintransaction = false;
        return $this->pdo->commit();
    }
327654
protected function getSelectString(): string
    {
        $statement = '';
        $fieldSelect    = $this->builder->getSelect();
        $aggregate = $this->builder->getAggregate();
        if (empty($fieldSelect) && empty($aggregate)) {
            return $statement;
        }

        $select = $this->getAggregateStatement($fieldSelect, $aggregate);

        // 字段组拼
        foreach ($select as $column => $alias) {
            // Filter db keyword
            if (array_key_exists($column, $fieldSelect) && trim($column) != '*' && strpos($column, '.') === false) {
                // 判断是否为函数调用
                if (strpos($column, '(') || strpos($column, ')')) {
                    $column = sprintf('%s', $column);
                } else {
                    $column = sprintf('`%s`', $column);
                }
            }

            $statement .= $column;
            if ($alias !== null) {
                $statement .= sprintf(' AS `%s`', $alias);
            }
            $statement .= ', ';
        }

        //select组拼
        $statement = substr($statement, 0, -2);
        if (!empty($statement)) {
            $statement = 'SELECT ' . $statement;
        }

        return $statement;
    }