Creates the current document in the remote database and if successful,
        updates the locally cached Document object with the ``_id``
        and ``_rev`` returned as part of the successful response.
357685
def create(self):
        

        # Ensure that an existing document will not be "updated"
        doc = dict(self)
        if doc.get('_rev') is not None:
            doc.__delitem__('_rev')

        headers = {'Content-Type': 'application/json'}
        resp = self.r_session.post(
            self._database.database_url,
            headers=headers,
            data=json.dumps(doc, cls=self.encoder)
        )
        resp.raise_for_status()
        data = response_to_json_dict(resp)
        super(Document, self).__setitem__('_id', data['id'])
        super(Document, self).__setitem__('_rev', data['rev'])
417014
def _update_retryable(
            self, criteria, document, upsert=False,
            check_keys=True, multi=False, manipulate=False,
            write_concern=None, op_id=None, ordered=True,
            bypass_doc_val=False, collation=None, array_filters=None,
            session=None):
        """"""
        def _update(session, sock_info, retryable_write):
            return self._update(
                sock_info, criteria, document, upsert=upsert,
                check_keys=check_keys, multi=multi, manipulate=manipulate,
                write_concern=write_concern, op_id=op_id, ordered=ordered,
                bypass_doc_val=bypass_doc_val, collation=collation,
                array_filters=array_filters, session=session,
                retryable_write=retryable_write)

        return self.__database.client._retryable_write(
            (write_concern or self.write_concern).acknowledged and not multi,
            _update, session)
594959
def post(self, id=None):
        
        try:

            try:
                base_object = json_util.loads(self.request.body)
            except TypeError:
                base_object = json_util.loads(self.request.body.decode())

            #assert not hasattr(base_object, "_id")

            toa = self.request.headers.get("Caesium-TOA", None)

            if toa:
                # Async create flow
                stack = AsyncSchedulableDocumentRevisionStack(self.client.collection_name, self.settings)

                revision_id = yield stack.push(base_object, toa=int(toa), meta=self._get_meta_data())
                resource = yield stack.preview(revision_id)

                if isinstance(revision_id, str):
                    self.set_header("Caesium-TOA", toa)
                    self.return_resource(resource.get("snapshot"))
                else:
                    self.raise_error(404, "Revision not scheduled for object: %s" % id)

            else:

                id = yield self.client.insert(base_object)
                base_object = yield self.client.find_one_by_id(id)

                self.return_resource(base_object)

        except ValidationError as vex:
            self.logger.error("%s validation error" % self.object_name, vex)
            self.raise_error(400, "Your %s cannot be created because it is missing required fields, see docs" % self.object_name)
        except ValueError as ex:
            self.raise_error(400, "Invalid JSON Body, check formatting. %s" % ex[0])
        except Exception as ex:
            self.logger.error(ex)
            self.raise_error()
960211
def save(self):
        
        resp = self.r_session.put(
            self.document_url,
            data=self.json(),
            headers={'Content-Type': 'application/json'}
        )
        resp.raise_for_status()
533180
function _errorCb(err, result) {

          // if there is a conflict error, retrieve the document's revision first
          function _successCb(err, result) {

            // use the revision to update the existing documents
            // NOTE: it is not impossible that the revision of this document
            // is modified by other operations right before updating, Couchpenter
            // will only try once to avoid any possibility of retrying infinitely.
            doc._rev = result._rev;
            self.couch.use(dbName).insert(doc, self._handle(cb, {
              dbName: dbName,
              docId: doc._id,
              message: 'updated'
            }));
          }

          self.couch.use(dbName).get(doc._id, self._handle(cb, {
            dbName: dbName,
            docId: doc._id,
            successCb: _successCb
          }));
        }
966398
def create_or_update_record(data, pid_type, id_key, minter):
    """"""
    resolver = Resolver(
        pid_type=pid_type, object_type='rec', getter=Record.get_record)

    try:
        pid, record = resolver.resolve(data[id_key])
        data_c = deepcopy(data)
        del data_c['remote_modified']
        record_c = deepcopy(record)
        del record_c['remote_modified']
        # All grants on OpenAIRE are modified periodically even if nothing
        # has changed. We need to check for actual differences in the metadata
        if data_c != record_c:
            record.update(data)
            record.commit()
            record_id = record.id
            db.session.commit()
            RecordIndexer().index_by_id(str(record_id))
    except PIDDoesNotExistError:
        record = Record.create(data)
        record_id = record.id
        minter(record.id, data)
        db.session.commit()
        RecordIndexer().index_by_id(str(record_id))
40973
def set_document(request, doc_id, body, errors):
    
    if doc_id in DB:
        errors['doc_id'].add('Document already exists')

    if errors:
        raise errors

    body['doc_id'] = doc_id
    DB[doc_id] = body

    # dict response for jsonify middleware
    return body
906836
def update(self, resource, id_, updates):
        """"""
        args = self._es_args(resource, refresh=True)
        if self._get_retry_on_conflict():
            args['retry_on_conflict'] = self._get_retry_on_conflict()

        updates.pop('_id', None)
        updates.pop('_type', None)
        self._update_parent_args(resource, args, updates)
        return self.elastic(resource).update(id=id_, body={'doc': updates}, **args)
51370
def _generate_doc(ret):
    '''
    
    '''

    # Create a copy of the object that we will return.
    retc = ret.copy()

    # Set the ID of the document to be the JID.
    retc["_id"] = ret["jid"]

    # Add a timestamp field to the document
    retc["timestamp"] = time.time()

    return retc
88257
def set_document_revision(document_id, revision_number, opts={})
    options = { 
      :file => '', 
      :file_name => '',
      :document_name => nil
    }.merge! opts
    
    # Raise an exception of we try to pass :file, but not :file_name
    if (!options[:file].empty? && options[:file_name].empty?)
      raise ArgumentError, ":file_name must be specified if :file is specified"
    end
    
    # If no document_name is given, use the file_name
    options[:document_name] ||= options[:file_name]
    
    login! unless logged_in?
    
    json = <<-EOF
      {
        "session": "#{@sugar_session_id}",
        "document_revision": {
           "id": "#{document_id}",
           "document_name": "#{options[:document_name]}",
           "revision": "#{revision_number}",
           "filename": "#{options[:file_name]}",
           "file": "#{b64_encode(options[:file])}"
        }
      }
    EOF
    json.gsub!(/^\s{6}/,'')
    send!(:set_document_revision, json)
  end
672965
def update(self, doc: dict, doc_id: str):
        
        body = {
            'doc': doc
        }
        self.instance.update(self.index, self.doc_type, doc_id, body=body)
569237
def prepare_revision
      return if new_record?
      if (respond_to?(:fragments_attributes_changed) && fragments_attributes_changed) ||
        !(changed & revision_fields).empty?
        self.revision_data = revision_fields.each_with_object({}) do |field, c|
          c[field] = send("#{field}_was")
        end
      end
    end
1180496
private Status update(Database _db, String docID, Body body, boolean deleting) {
        Status status = new Status();

        if (docID != null && docID.isEmpty() == false) {
            // On PUT/DELETE, get revision ID from either ?rev= query or doc body:
            String revParam = getQuery("rev");
            String ifMatch = getRequestHeaderValue("If-Match");
            if (ifMatch != null) {
                if (revParam == null)
                    revParam = ifMatch;
                else if (!ifMatch.equals(revParam))
                    return new Status(Status.BAD_REQUEST);
            }
            if (revParam != null && body != null) {
                String revProp = (String) body.getProperties().get("_rev");
                if (revProp == null) {
                    // No _rev property in body, so use ?rev= query param instead:
                    body.getProperties().put("_rev", revParam);
                    //body = new Body(bodyDict);
                } else if (!revParam.equals(revProp)) {
                    throw new IllegalArgumentException("Mismatch between _rev and rev");
                }
            }
        }

        RevisionInternal rev = update(_db, docID, body, deleting, false, status);
        if (status.isSuccessful()) {
            cacheWithEtag(rev.getRevID());  // set ETag
            if (!deleting) {
                URL url = connection.getURL();
                String urlString = url.toExternalForm();
                if (docID != null) {
                    urlString += '/' + rev.getDocID();
                    try {
                        url = new URL(urlString);
                    } catch (MalformedURLException e) {
                        Log.w("Malformed URL", e);
                    }
                }
                setResponseLocation(url);
            }
            Map<String, Object> result = new HashMap<String, Object>();
            result.put("ok", true);
            result.put("id", rev.getDocID());
            result.put("rev", rev.getRevID());
            connection.setResponseBody(new Body(result));
        }
        return status;
    }
316756
def replicate_from(other_db, continuous = false, create_target = false, doc_ids = nil)
      replicate(other_db, continuous, :target => name, :create_target => create_target, :doc_ids => doc_ids)
    end
1351639
def update_doc(doc_id, params = {}, update_limit = 10)
      resp = {'ok' => false}
      last_fail = nil

      until resp['ok'] or update_limit <= 0
        doc = self.get(doc_id, params)
        yield doc
        begin
          resp = self.save_doc doc
        rescue CouchRest::RequestFailed => e
          if e.http_code == 409 # Update collision
            update_limit -= 1
            last_fail = e
          else
            raise e
          end
        end
      end

      raise last_fail unless resp['ok']
      doc
    end
1122309
def update(self, document_id, update_spec, namespace, timestamp):
        
        # Commit outstanding changes so that the document to be updated is the
        # same version to which the changes apply.
        self.commit()
        # Need to escape special characters in the document_id.
        document_id = ''.join(map(
            lambda c: '\\' + c if c in ESCAPE_CHARACTERS else c,
            u(document_id)
        ))

        query = "%s:%s" % (self.unique_key, document_id)
        results = self.solr.search(query)
        if not len(results):
            # Document may not be retrievable yet
            self.commit()
            results = self.solr.search(query)
        # Results is an iterable containing only 1 result
        for doc in results:
            # Remove metadata previously stored by Mongo Connector.
            doc.pop('ns')
            doc.pop('_ts')
            updated = self.apply_update(doc, update_spec)
            # A _version_ of 0 will always apply the update
            updated['_version_'] = 0
            self.upsert(updated, namespace, timestamp)
            return updated
689582
def reload_root_document
      {}.merge(collection.find({ _id: _id }, session: _session).read(mode: :primary).first || {})
    end