/* Create-or-update a document: First fetch the existing revision, then
insert a new one.  Optional f_ShouldUpdate and f_Merge functions
control the specifics of merging.
778660
function updateDocument(existingDoc, newDoc, id, db, f_ShouldUpdate, shouldCreate, f_Merge, callback) {
    if (!f_ShouldUpdate) {
        f_ShouldUpdate = always;
    }

    if (!f_Merge) {
        f_Merge = useNewVersion;
    }

    // If we never grabbed the existing document from the DB, fetch it and try again.
    if (!existingDoc) {
        return db.get(id, function (err, r) {
            // If the fetch came back with nothing, attempt to do a fresh insert unless the user
            // doesn't want documents to be created.
            if (err && (err.error === "not_found")) {
                if (!shouldCreate)
                    // Don't create a document where one didn't exist, if the user so desires.
                    return callback(null, null);

                return db.insert(newDoc, id, function (err, r) {
                    // If someone beat us here, we should retry this whole operation.
                    if (err && err.error === "conflict")
                        return updateDocument(null, newDoc, id, db, f_ShouldUpdate, shouldCreate, f_Merge, callback);

                    // If anything else happened, we should bail.
                    if (err)
                        return callback("Could not fetch existing document: " + err.toString());

                    // The insert worked.  We're done.
                    return callback(null, extend({}, newDoc, {_rev: r.rev}));
                });
            }

            // If the fetch came back with any other error, bail.
            if (err)
                return callback("Could not fetch existing document: " + err.toString());

            // We got the document.  Let's try the update again.
            return updateDocument(r, newDoc, id, db, f_ShouldUpdate, shouldCreate, f_Merge, callback);
        });
    }

    if (!f_ShouldUpdate(existingDoc, newDoc)) {
        return callback(null, existingDoc);
    }

    // Before merging, record that we want to undelete a document that has been deleted.
    var mergedDoc = f_Merge(omit(existingDoc, "_deleted"), newDoc);
    if (!mergedDoc || typeof mergedDoc !== "object" || mergedDoc instanceof Error) {
        // Allow a user defined merge algorithm to say ``sorry...can't merge'' by returning a non-object or Error.
        // Bubble this error, so that the user can then test for it in their callback.
        return callback(mergedDoc);
    }

    // It's essential that we specify a revision or this will never terminate.
    // It's probably not a good idea to trust a user-specified merge function to do this.
    mergedDoc = extend({}, mergedDoc, { _rev: existingDoc._rev });

    // The document exists, and is out of date.  We need to overwrite it.
    db.insert(
        mergedDoc,
        id,
        function (err, result) {
            // If someone beat us here, we need to try the whole thing again.
            if (err && err.error === "conflict")
                return updateDocument(null, newDoc, id, db, f_ShouldUpdate, shouldCreate, f_Merge, callback);

            // If anything else happened, bail.
            if (err)
                return callback("Could not update the document to the proposed version: " + err.toString());

            // Update the new document's _rev
            mergedDoc._rev = result.rev;

            // The replacement worked.  We're done.  Finally!
            return callback(null, mergedDoc);
        }
    );
}
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
44851
function update(form) {
      // refuse to work with invalid data
      if (!vm.clientModelDoc._id || form && !form.$valid) {
        return;
      }

      ClientModelDocService.update(vm.clientModelDoc)
        .then(updateClientModelDocSuccess)
        .catch(updateClientModelDocCatch);

      function updateClientModelDocSuccess(updatedClientModelDoc) {
        // update the display name after successful save
        vm.displayName = updatedClientModelDoc.name;
        Toast.show({text: 'ClientModelDoc ' + vm.displayName + ' updated'});
        if (form) {
          form.$setPristine();
        }
      }

      function updateClientModelDocCatch(err) {
        Toast.show({
          type: 'warn',
          text: 'Error while updating ClientModelDoc ' + vm.displayName,
          link: {state: $state.$current, params: $stateParams}
        });

        if (form && err) {
          form.setResponseErrors(err.data);
        }
      }
    }
466136
function updated(docs) {
    // Refresh if any of the objects: have an ID which is in our results OR they match our query (this.query)
    var shouldRefresh = false;
    docs.forEach(function(doc) { // Avoid using .some since it would stop iterating after first match and we need to set _prefetched
      var interested = self._count || self._ids[doc._id] || document.match(doc, self.query); // _count queries never set _ids
      if (interested) self._prefetched[doc._id] = doc;
      shouldRefresh = shouldRefresh || interested;
    });
    if (shouldRefresh) refresh();
  }
44222
function upsertDocumentController(req, res) {
                    var modelName = req.params.modelName,
                        id = req.params.documentId,
                        user = req.admin_user,
                        data = _.extend({}, req.body, req.files),
                        modelConfig = registry.models[modelName],
                        form;

                    polymorphGetDocument(modelConfig.model, modelConfig.is_single, id).then(
                        function createTheForm(document) {
                            var action = document ? 'update' : 'create';
                            var docType = document && document._doc.__t;
                            if (docType) modelConfig = registry.models[docType];
                            var FormType = modelConfig.options.form;
                            if (!user.hasPermissions(modelConfig.modelName, action)) throw new Error('unauthorized');
                            form = new FormType(modelConfig.options, modelConfig.model, document, data);
                            return form.save();
                        }
                    ).then(
                        function (document) {
                            modelConfig.options.post(document);
                            return form;
                        },
                        function (err) {
                            err.modelConfig = modelConfig;
                            err.form = form;
                            if (!form) throw err;

                            form.errors = form.errors || {};
                            if (err.name == 'ValidationError') {
                                form.errors = _.merge(form.errors, err.errors);
                            } else if (err.name === 'MongoError' && err.code == 11000) {
                                form.errors.exception = err;
                                err.name = "Duplicate";
                                var msg = '{' + err.err.split('$').pop().split('{').pop();
                                var ObjectID = /ObjectId\(\'(\w+)\'\)/.exec(msg);
                                err.fields = '\n<br />';
                                err.fields += (ObjectID.length == 2) ? '<a href="' + ObjectID[1] + '" target="_blank">Click to open duplicate document</a>' :
                                    msg;
                            } else {
                                form.errors.exception = err;
                            }
                            if (_.isEmpty(form.errors)) return form;
                            throw err;
                        }
                    ).then(
                        function (form) {
                            res._debug_form = form;
                            var response = form.instance.toJSON();
                            response.id = response.id || form.instance._id;
                            response.label = response.label || form.instance.name || form.instance.title || form.instance.toString();
                            return response;
                        }
                    ).then(
                        function (response) {
                            res.json(200, response);
                        },
                        function (err) {
                            err.form = res._debug_form;
                            res.json(422, err);
                        }
                    ).end();
                }
1172343
private static BsonDocument withNewVersion(
      final BsonDocument document,
      final BsonDocument newVersion
  ) {
    final BsonDocument newDocument = BsonUtils.copyOfDocument(document);
    newDocument.put(DOCUMENT_VERSION_FIELD, newVersion);
    return newDocument;
  }
851855
def update(self, document_id, update_spec, namespace, timestamp):
        
        document = self.doc_dict[document_id].doc
        updated = self.apply_update(document, update_spec)
        if "_id" in updated:
            updated.pop("_id")
        updated[self.unique_key] = document_id
        self.upsert(updated, namespace, timestamp)
        return updated
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
          }));
        }
1330944
def find_and_modify(self, query=None, update=None):
        
        update = update or {}

        for document in self.find(query=query):
            document.update(update)
            self.update(document)
240139
function (data, fn) {
    this.store.generateBinId(data.length, 0, function generateBinId(err, id) {
      if (err) {
        return fn(err);
      }

      data.url = id;
      data.revision = 1;
      data.latest = true;
      data.streamingKey = this.createStreamingKey(id, data.revision);
      this.store.setBin(data, function (err, id) {
        data.id = id;
        fn(err || null, err ? undefined : data);
      });
    }.bind(this));
  }
551255
def update_or_create(self, attributes, values=None):
        
        instance = self.first_or_new(**attributes)

        instance.fill(values)

        instance.save()

        return instance
212021
@Override
    public synchronized void insertUpdate(DocumentEvent e) {
        int len = e.getLength();
        int off = e.getOffset();
        if (outputMark > off) {
            outputMark += len;
        }
    }
953741
@Override
  public <T> Update<T> createUpdate(Class<T> beanType, String ormUpdate) {
    methodCalls.add(MethodCall.of("createUpdate").with("beanType", beanType, "ormUpdate", ormUpdate));
    return delegate.createUpdate(beanType, ormUpdate);
  }
632990
def create_or_update(ctx, model, xmlid, values):
    
    if isinstance(model, basestring):
        model = ctx.env[model]

    record = ctx.env.ref(xmlid, raise_if_not_found=False)
    if record:
        record.update(values)
    else:
        record = model.create(values)
        add_xmlid(ctx, record, xmlid)
    return record
549544
def create_or_update(cls, object_version, key, value):
        """"""
        assert len(key) < 256
        assert len(value) < 256
        obj = cls.get(object_version, key)
        if obj:
            obj.value = value
            db.session.merge(obj)
        else:
            obj = cls.create(object_version, key, value)
        return obj
1040272
@Override
  protected void fireInsertUpdate( DocumentEvent evt )
  {

    super.fireInsertUpdate( evt );

    try
    {
      processChangedLines( evt.getOffset(), evt.getLength() );
    }
    catch( Exception ex )
    {
      System.out.println( "" + ex );
    }
  }
1180072
function _update(query, op, criteria, doc, options, force, callback) {
  query.op = op;

  if (Query.canMerge(criteria)) {
    query.merge(criteria);
  }

  if (doc) {
    query._mergeUpdate(doc);
  }

  if (utils.isObject(options)) {
    // { overwrite: true }
    query.setOptions(options);
  }

  // we are done if we don't have callback and they are
  // not forcing an unsafe write.
  if (!(force || callback)) {
    return query;
  }

  if (!query._update ||
      !query.options.overwrite && 0 === utils.keys(query._update).length) {
    callback && utils.soon(callback.bind(null, null, 0));
    return query;
  }

  options = query._optionsForExec();
  if (!callback) options.safe = false;

  criteria = query._conditions;
  doc = query._updateForExec();

  debug('update', query._collection.collectionName, criteria, doc, options);
  callback = query._wrapCallback(op, callback, {
    conditions: criteria,
    doc: doc,
    options: options
  });

  query._collection[op](criteria, doc, options, utils.tick(callback));

  return query;
}