Execute the INSERT and return the ODocument object created.
512645
public Object execute(final Map<Object, Object> iArgs) {
    if (newRecords == null)
      throw new OCommandExecutionException("Cannot execute the command because it has not been parsed yet");

    final OCommandParameters commandParameters = new OCommandParameters(iArgs);
    if (indexName != null) {
      final OIndex<?> index = getDatabase().getMetadata().getIndexManager().getIndex(indexName);
      if (index == null)
        throw new OCommandExecutionException("Target index '" + indexName + "' not found");

      // BIND VALUES
      Map<String, Object> result = null;

      for (Map<String, Object> candidate : newRecords) {
        index.put(getIndexKeyValue(commandParameters, candidate), getIndexValue(commandParameters, candidate));
        result = candidate;
      }

      // RETURN LAST ENTRY
      return new ODocument(result);
    } else {

      // CREATE NEW DOCUMENTS
      final List<ODocument> docs = new ArrayList<ODocument>();
      for (Map<String, Object> candidate : newRecords) {
        final ODocument doc = className != null ? new ODocument(className) : new ODocument();
        OSQLHelper.bindParameters(doc, candidate, commandParameters);

        if (clusterName != null) {
          doc.save(clusterName);
        } else {
          doc.save();
        }
        docs.add(doc);
      }

      if (docs.size() == 1) {
        return docs.get(0);
      } else {
        return docs;
      }
    }
  }
1285403
def insert(self, **data):
        
        if self.where_clause:
            raise Invalid("Cannot insert with 'where' clause.")
        # Ensure that order is preserved
        data = data.items()
        cmd = "insert into {table} ({attrs}) values ({values})".format(
            table=self.table_name,
            attrs=", ".join(entry[0] for entry in data),
            values=", ".join(["?"] * len(data)),
        )
        handle = Repo.db.execute(cmd, [entry[1] for entry in data])
        # Return the id of the added row
        return handle.lastrowid
1101924
public void insert(Object object) {
        EntityManager entityManager = null;
        try {
            entityManager = entityManagers.poll();
            entityManager.getTransaction().begin();
            try {

                entityManager.persist(object);
                entityManager.getTransaction().commit();
            } catch (Exception e) {
                e.printStackTrace();
                entityManager.getTransaction().rollback();
            }
        } finally {
            if(entityManager != null)
                entityManagers.add(entityManager);
        }
    }
347006
def insert(self, data, return_object=False):
        

        obj = self(data)  # pylint: disable=E1102
        obj.save()

        if return_object:
            return obj
        else:
            return obj["_id"]
1252273
public void performInsert()
    {
        if(insertMap == null)
            return;
        else
        {
            PersistenceBroker broker = tx.getBroker();
            Iterator it = insertMap.values().iterator();
            while(it.hasNext())
            {
                NamedEntry namedEntry = (NamedEntry) it.next();
                namedEntry.prepareForStore(broker);
                broker.store(namedEntry, ObjectModification.INSERT);
            }
        }
    }
1007810
protected function _insert()
    {
        // set oxcreate
        $sNow = date('Y-m-d H:i:s', \OxidEsales\Eshop\Core\Registry::getUtilsDate()->getTime());
        $this->oxremark__oxcreate = new \OxidEsales\Eshop\Core\Field($sNow, \OxidEsales\Eshop\Core\Field::T_RAW);
        $this->oxremark__oxheader = new \OxidEsales\Eshop\Core\Field($sNow, \OxidEsales\Eshop\Core\Field::T_RAW);

        return parent::_insert();
    }
54823
private function internalInsert()
    {
        if ($this->triggerEvent(self::EVENT_NAME_BEFORE_INSERT)->isCancelled()) {
            return;
        }

        $document = $this->toArray();

        // try write document
        try {
            $this
                ->collection
                ->getMongoCollection()
                ->insert($document);
        } catch (\Exception $e) {
            throw new WriteException(
                $e->getMessage(),
                $e->getCode(),
                $e
            );
        }

        // set id
        $this->defineId($document['_id']);

        // after insert event
        $this->triggerEvent(self::EVENT_NAME_AFTER_INSERT);
    }
1053595
async def execute_insert(
        self, sql: str, parameters: Iterable[Any] = None
    ) -> Optional[sqlite3.Row]:
        """"""
        if parameters is None:
            parameters = []
        return await self._execute(self._execute_insert, sql, parameters)
268020
function insertDoc (doc, qs0, callback0) {
      const req = { db: dbName, body: doc, method: 'POST' }

      let { opts, callback } = getCallback(qs0, callback0)

      if (typeof opts === 'string') {
        opts = { docName: opts }
      }

      if (opts) {
        if (opts.docName) {
          req.doc = opts.docName
          req.method = 'PUT'
          delete opts.docName
        }
        req.qs = opts
      }

      return relax(req, callback)
    }
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();
        }
    }
935415
def insert(self):
    """"""
    if not self.curs:
      raise LIGOLwDBError, "Database connection not initalized"
    if len(self.table) == 0:
      raise LIGOLwDBError, 'attempt to insert empty table'
    for tab in self.table.keys():
      # find and add any missing unique ids
      generate = []
      missingcols = [k for k in self.ldb.uniqueids[tab] 
        if k not in self.table[tab]['column']]
      for m in missingcols:
        generate.append(',BLOB(GENERATE_UNIQUE())')
        self.table[tab]['orderedcol'].append(m)
      # and construct the sql query
      self.table[tab]['query'] = ' '.join( 
        ['INSERT INTO', tab, '(', ','.join(self.table[tab]['orderedcol']), 
        ') VALUES (', ','.join(['?' for x in self.table[tab]['column']]) , 
        ''.join(generate), ')'])
    for tabtup in self.ldb.tables:
      tab = tabtup[0].lower()
      try:
        try: 
          self.curs.executemany(self.table[tab]['query'],
            self.table[tab]['stream'])
          rowcount = self.curs.rowcount
        except DB2.Error, e:
          self.curs.execute('rollback')
          msg = e[2] 
          msg += self.xml() + '\n' 
          msg += str(self.table[tab]['query']) + '\n' 
          msg += str(self.table[tab]['stream']) + '\n'
          raise LIGOLwDBError, msg
        except DB2.Warning, e:
          self.curs.execute('rollback')
          raise LIGOLwDBError, e[2]
        #except Exception, e:
        #  self.curs.execute('rollback')
        #  raise LIGOLwDBError, e[2]
      except KeyError:
        pass
    self.curs.execute('commit')
    return rowcount
375631
def bulk_insert(self, resource, docs, **kwargs):
        """"""
        kwargs.update(self._es_args(resource))
        parent_type = self._get_parent_type(resource)
        if parent_type:
            for doc in docs:
                if doc.get(parent_type.get('field')):
                    doc['_parent'] = doc.get(parent_type.get('field'))

        res = bulk(self.elastic(resource), docs, stats_only=False, **kwargs)
        self._refresh_resource_index(resource)
        return res
439109
def insert(self, schema, fields, **kwargs):
        
        r = 0

        with self.connection(**kwargs) as connection:
            kwargs['connection'] = connection
            try:
                with self.transaction(**kwargs):
                    r = self._insert(schema, fields, **kwargs)

            except Exception as e:
                exc_info = sys.exc_info()
                if self.handle_error(schema, e, **kwargs):
                    r = self._insert(schema, fields, **kwargs)
                else:
                    self.raise_error(e, exc_info)

        return r
99825
function(o, callback) {
    var self = this;

    // Validate, 
    var err = this.validateProperties(o);
    
    if (err) callback.call(self, err);
    
    else {

      // Convert object types to strings
      this.convertTypes(o);

      // Set model defaults
      this.setDefaults(o);

      // Convert `id` to `_id`
      convertMongoID(o);

      // Save data into the database
      this.driver.insertInto({
        collection: this.context,
        values: o
      }, function(err, docs) {
        if (err) callback.call(self, err, null);
        else {
          callback.call(self, null, docs[0]._id);
        }
      });
      
    }
    
  }
1209295
public function insert($document): ?PostInsertId
    {
        /** @var DocumentMetadata $class */
        $class = $this->dm->getClassMetadata(get_class($document));
        $idGenerator = $this->dm->getUnitOfWork()->getIdGenerator($class->idGeneratorType);
        $postIdGenerator = $idGenerator->isPostInsertGenerator();

        $id = $postIdGenerator ? null : $class->getSingleIdentifier($document);
        $body = $this->prepareUpdateData($document)['body'];

        $response = $this->collection->create($id, $body);
        $data = $response->getData();

        foreach ($class->attributesMetadata as $field) {
            if (! $field instanceof FieldMetadata) {
                continue;
            }

            if ($field->indexName) {
                $field->setValue($document, $data['_index'] ?? null);
            }

            if ($field->typeName) {
                $field->setValue($document, $data['_type'] ?? null);
            }
        }

        $postInsertId = null;
        if ($postIdGenerator) {
            $postInsertId = new PostInsertId($document, $this->collection->getLastInsertedId());
        }

        return $postInsertId;
    }
142149
def create(handler, item_document):
    """"""
    data = {'operation': 'create',
            'item': json.load(item_document)}
    handler.invoke(data)
322791
def insert(self, **kwargs):
        
        if self.is_valid:
            before = self.before_insert()
            if before:
                return before

            try:
                self._document['_id'] = self.insert_one(self._document)

                self.after_insert()

                return self._document
            except PyMongoException as exc:
                return PyMongoError(
                    error_message=exc.details.get(
                        'errmsg', exc.details.get('err', 'PyMongoError.')
                    ),
                    operation='insert', collection=type(self).__name__,
                    document=self._document,
                )

        return self._errors