Store multiple documents
    
    Args

    data <dict> data to store, use document ids as keys

    Returns

    revs <dict> dictionary of new revisions indexed by document ids
183482
def set_batch(self, data):
    
    

    # fetch existing documents to get current revisions
    rows = self.bucket.view("_all_docs", keys=data.keys(), include_docs=True)
    existing = {}
    for row in rows:
      key = row.id
      if key and not data[key].has_key("_rev"):
        data[key]["_rev"] = row.doc["_rev"]

    for id,item in data.items():
      data[id]["_id"] = id

    revs = {}
    for success, docid, rev_or_exc in self.bucket.update(data.values()):
      if not success and self.logger:
        self.logger.error("Document update conflict (batch) '%s', %s" % (docid, rev_or_exc))
      elif success:
        revs[docid] = rev_or_exc

    return revs
282676
def _retrieve_revisions(self):
        """"""
        response = self._swimlane.request(
            'get',
            'history',
            params={
                'type': 'Records',
                'id': self._record.id
            }
        )

        raw_revisions = response.json()

        return [Revision(self._record, raw) for raw in raw_revisions]
440260
function parseDoc(doc, newEdits) {

  var nRevNum;
  var newRevId;
  var revInfo;
  var opts = {status: 'available'};
  if (doc._deleted) {
    opts.deleted = true;
  }

  if (newEdits) {
    if (!doc._id) {
      doc._id = pouchdbUtils.uuid();
    }
    newRevId = pouchdbUtils.uuid(32, 16).toLowerCase();
    if (doc._rev) {
      revInfo = parseRevisionInfo(doc._rev);
      if (revInfo.error) {
        return revInfo;
      }
      doc._rev_tree = [{
        pos: revInfo.prefix,
        ids: [revInfo.id, {status: 'missing'}, [[newRevId, opts, []]]]
      }];
      nRevNum = revInfo.prefix + 1;
    } else {
      doc._rev_tree = [{
        pos: 1,
        ids : [newRevId, opts, []]
      }];
      nRevNum = 1;
    }
  } else {
    if (doc._revisions) {
      doc._rev_tree = makeRevTreeFromRevisions(doc._revisions, opts);
      nRevNum = doc._revisions.start;
      newRevId = doc._revisions.ids[0];
    }
    if (!doc._rev_tree) {
      revInfo = parseRevisionInfo(doc._rev);
      if (revInfo.error) {
        return revInfo;
      }
      nRevNum = revInfo.prefix;
      newRevId = revInfo.id;
      doc._rev_tree = [{
        pos: nRevNum,
        ids: [newRevId, opts, []]
      }];
    }
  }

  pouchdbUtils.invalidIdError(doc._id);

  doc._rev = nRevNum + '-' + newRevId;

  var result = {metadata : {}, data : {}};
  for (var key in doc) {
    /* istanbul ignore else */
    if (Object.prototype.hasOwnProperty.call(doc, key)) {
      var specialKey = key[0] === '_';
      if (specialKey && !reservedWords[key]) {
        var error = pouchdbErrors.createError(pouchdbErrors.DOC_VALIDATION, key);
        error.message = pouchdbErrors.DOC_VALIDATION.message + ': ' + key;
        throw error;
      } else if (specialKey && !dataWords[key]) {
        result.metadata[key.slice(1)] = doc[key];
      } else {
        result.data[key] = doc[key];
      }
    }
  }
  return result;
}
1201293
def load(self, data):
        
        objs = {}
        for mapper in self.entities:
            objs[mapper.name] = mapper.load(self.loader, data)

        for mapper in self.relations:
            objs[mapper.name] = mapper.load(self.loader, data, objs)
263069
def save_partial(self, data=None, allow_protected_fields=False, **kwargs):
        

        # Backwards compat, deprecated argument
        if "dotnotation" in kwargs:
            del kwargs["dotnotation"]

        if data is None:

            data = dotdict(self)
            if "_id" not in data:
                raise KeyError("_id must be set in order to do a save_partial()")
            del data["_id"]

        if len(data) == 0:
          return

        if not allow_protected_fields:
            self.mongokat_collection._check_protected_fields(data)

        apply_on = dotdict(self)

        self._initialized_with_doc = False

        self.mongokat_collection.update_one({"_id": self["_id"]}, {"$set": data}, **kwargs)

        for k, v in data.items():
            apply_on[k] = v

        self.update(dict(apply_on))
791987
def re_sort(data):
    
    keys = sorted(data.keys())
    new_data = {}
    for number, key in enumerate(keys):
        new_data[number] = data[key]
    return new_data
231063
def insert_multiple(self, documents):
        

        doc_ids = []
        data = self._read()

        for doc in documents:
            doc_id = self._get_doc_id(doc)
            doc_ids.append(doc_id)

            data[doc_id] = dict(doc)

        self._write(data)

        return doc_ids
318773
def delete_doc(self, doc_id, revision):
        ''''''
        d = defer.Deferred()

        self.increase_stat('delete_doc')

        try:
            doc = self._get_doc(doc_id)
            if doc['_rev'] != revision:
                raise ConflictError("Document update conflict.")
            if doc.get('_deleted', None):
                raise NotFoundError('%s deleted' % doc_id)
            doc['_deleted'] = True
            self._expire_cache(doc['_id'])
            for key in doc.keys():
                if key in ['_rev', '_deleted', '_id']:
                    continue
                del(doc[key])
            self.log('Marking document %r as deleted', doc_id)
            del self._attachments[doc['_id']]
            self._update_rev(doc)
            self._analize_changes(doc)
            d.callback(Response(ok=True, id=doc_id, rev=doc['_rev']))
        except (ConflictError, NotFoundError, ) as e:
            d.errback(e)

        return d
1345289
function(args, callback) {
      // Make sure the ID exists
      var t = this, model = args.model;
      if (!model || !model.id) {
        return callback({msg:'SyncProbe create - Data model with ID not present'});
      }

      // Make sure the file doesn't already exist
      t.getFullPath(model.id, function(error, response) {
        if (error) {
          return callback(error);
        }

        if (response.stats) {
          return callback({msg:'Document with this ID already exists'});
        }

        // Forward to the update control
        t.update_control(args, callback);
      });
    }
1112442
def _store(self, uid, content, data=None):
        """"""
        doc = dict(uid=uid)
        if data:
            gfs = gridfs.GridFS(self.db)
            id = gfs.put(data, encoding='utf-8')
            doc.update(data_id=id)
        doc.update(content)
        self.db.pastes.insert_one(doc)
435198
def set_all_revisions_to_in_process(self, ids):
        

        predicate = {
            "_id" : {
                "$in" : [ ObjectId(id) for id in ids ]
            }
        }

        set = {"$set": { "inProcess": True }}

        yield self.revisions.collection.update(predicate, set, multi=True)
1077225
def update(self, data):
        
        for key, value in data.items():
            setattr(self, key, value)
73830
def set_data(self, data):
        
        # Make sure a dict got passed it
        if not isinstance(data, type({})):
            raise TypeError("This attribute must be a dictionary.")
        # Set the attribute
        self.__dict__['data'] = DocumentDataDict(data)
411704
def dataStoreRecords(mimeData, record_items):
        
        record_data = []
        for record_item in record_items:
            record = record_item.record()
            if record is None:
                continue
            
            repro = '%s(%s)' % (record.schema().name(), record.primaryKey())
            record_data.append(repro)
        
        if not record_data:
            return
        
        record_data = ';'.join(record_data)
        mimeData.setData('application/x-orb-records', QByteArray(record_data))
        
        # store the associated mime data for the individual record
        if len(record_items) == 1:
            for format, value in record_items[0].dragData().items():
                mimeData.setData(format, QByteArray(value))
1259082
def load_design_docs():
    
    url = ':'.join([options.url_registry_db, str(options.db_port)])
    client = partial(couch.BlockingCouch, couch_url=url)

    for name, docs in _views.items():
        db = client(db_name=name)
        views = []

        for doc in docs:
            try:
                current_doc = db.get_doc(doc['_id'])

                # use the current _rev if not provided
                if '_rev' not in doc:
                    doc['_rev'] = current_doc['_rev']
            except couch.NotFound:
                pass

            views.append(doc)

        db.save_docs(views)
961611
def persist_trie_data_dict(self, trie_data_dict: Dict[Hash32, bytes]) -> None:
        
        with self.db.atomic_batch() as db:
            for key, value in trie_data_dict.items():
                db[key] = value
1274348
def append(self, rev):
        
        if not isinstance(rev, Revision):
            results = self._connection.ls(rev)
            if not results:
                self._connection.add(rev, self)
                return

            rev = results[0]

        if not rev in self:
            if rev.isMapped:
                rev.edit(self)

            self._files.append(rev)
            rev.changelist = self

            self._dirty = True