// AddDoc adds the document to storage and returns the new ID.
515174
func (s *backupsDocStorage) AddDoc(doc filestorage.Document) (string, error) {
	metadata, ok := doc.(*Metadata)
	if !ok {
		return "", errors.Errorf("doc must be of type *backups.Metadata")
	}
	metaDoc := newStorageMetaDoc(metadata)

	dbWrap := s.dbWrap.Copy()
	defer dbWrap.Close()

	id, err := addStorageMetadata(dbWrap, &metaDoc)
	return id, errors.Trace(err)
}
87129
func (p *contentProvider) setDocument(docID uint32) {
	fileStart := p.id.boundaries[docID]

	p.idx = docID
	p.fileSize = p.id.boundaries[docID+1] - fileStart

	p._nl = nil
	p._sects = nil
	p._data = nil
}
58634
func (col *Col) indexDoc(id int, doc map[string]interface{}) {
	for idxName, idxPath := range col.indexPaths {
		for _, idxVal := range GetIn(doc, idxPath) {
			if idxVal != nil {
				hashKey := StrHash(fmt.Sprint(idxVal))
				partNum := hashKey % col.db.numParts
				ht := col.hts[partNum][idxName]
				ht.Lock.Lock()
				ht.Put(hashKey, id)
				ht.Lock.Unlock()
			}
		}
	}
}
373499
func (b *BulkDocument) Save(doc interface{}, id, rev string) error {
	if id == "" {
		return fmt.Errorf("No ID specified")
	}
	b.docs = append(b.docs, bulkDoc{id, rev, false, doc})
	return nil
}
60679
func (s *InstanceIdentity) SetDocument(v string) *InstanceIdentity {
	s.Document = &v
	return s
}
32166
func GetDoc(w rest.ResponseWriter, r *rest.Request) {
	id := r.PathParam("id")
	collection := r.PathParam("collection")
	doc, err := get.Get(collection, id)
	if err != nil {
		rest.Error(w, "Not Found", 404)
		return
	}
	w.WriteHeader(http.StatusOK)
	if doc == nil {
		w.(http.ResponseWriter).Write(variables.BlankResponse)
		return
	}
	fmt.Println(doc)
	w.WriteJson(doc)
}
849473
func NewDocumentID(collection, key string) DocumentID {
	return DocumentID(pathEscape(collection) + "/" + pathEscape(key))
}
616161
func (i *IndexReader) DumpDoc(id string) chan interface{} {
	idBytes := []byte(id)

	rv := make(chan interface{})

	go func() {
		defer close(rv)

		back, err := backIndexRowForDoc(i.kvreader, []byte(id))
		if err != nil {
			rv <- err
			return
		}

		// no such doc
		if back == nil {
			return
		}
		// build sorted list of term keys
		keys := make(keyset, 0)
		for _, entry := range back.termsEntries {
			for i := range entry.Terms {
				tfr := NewTermFrequencyRow([]byte(entry.Terms[i]), uint16(*entry.Field), idBytes, 0, 0)
				key := tfr.Key()
				keys = append(keys, key)
			}
		}
		sort.Sort(keys)

		// first add all the stored rows
		storedRowPrefix := NewStoredRow(idBytes, 0, []uint64{}, 'x', []byte{}).ScanPrefixForDoc()
		dumpPrefix(i.kvreader, rv, storedRowPrefix)

		// now walk term keys in order and add them as well
		if len(keys) > 0 {
			it := i.kvreader.RangeIterator(keys[0], nil)
			defer func() {
				cerr := it.Close()
				if cerr != nil {
					rv <- cerr
				}
			}()

			for _, key := range keys {
				it.Seek(key)
				rkey, rval, valid := it.Current()
				if !valid {
					break
				}
				rck := make([]byte, len(rkey))
				copy(rck, key)
				rcv := make([]byte, len(rval))
				copy(rcv, rval)
				row, err := ParseFromKeyValue(rck, rcv)
				if err != nil {
					rv <- err
					return
				}
				rv <- row
			}
		}
	}()

	return rv
}
808189
func NewDocument(p unsafe.Pointer, contentLen int, inEncoding, outEncoding []byte) (doc *XmlDocument) {
	inEncoding = AppendCStringTerminator(inEncoding)
	outEncoding = AppendCStringTerminator(outEncoding)

	xmlNode := &XmlNode{Ptr: (*C.xmlNode)(p)}
	docPtr := (*C.xmlDoc)(p)
	doc = &XmlDocument{Ptr: docPtr, Node: xmlNode, InEncoding: inEncoding, OutEncoding: outEncoding, InputLen: contentLen}
	doc.UnlinkedNodes = make(map[*C.xmlNode]bool)
	doc.XPathCtx = xpath.NewXPath(p)
	doc.Type = xmlNode.NodeType()
	doc.fragments = make([]*DocumentFragment, 0, initialFragments)
	doc.Me = doc
	xmlNode.Document = doc
	//runtime.SetFinalizer(doc, (*XmlDocument).Free)
	return
}
631517
func (c *Client) AddRecord(domainID int, body Record) (*Record, error) {
	uri := fmt.Sprintf("/%d/records/", domainID)
	req, err := c.newRequest(http.MethodPost, uri, body)
	if err != nil {
		return nil, err
	}

	record := &Record{}
	_, err = c.do(req, record)
	if err != nil {
		return nil, err
	}

	return record, nil
}
192380
func (s *Segment) SetDocument(v string) *Segment {
	s.Document = &v
	return s
}
1251448
func (dbclient *CouchDatabase) ReadDoc(id string) (*CouchDoc, string, error) {
	var couchDoc CouchDoc
	attachments := []*AttachmentInfo{}
	dbName := dbclient.DBName

	logger.Debugf("[%s] Entering ReadDoc()  id=[%s]", dbName, id)
	if !utf8.ValidString(id) {
		return nil, "", errors.Errorf("doc id [%x] not a valid utf8 string", id)
	}

	readURL, err := url.Parse(dbclient.CouchInstance.conf.URL)
	if err != nil {
		logger.Errorf("URL parse error: %s", err)
		return nil, "", errors.Wrapf(err, "error parsing CouchDB URL: %s", dbclient.CouchInstance.conf.URL)
	}

	query := readURL.Query()
	query.Add("attachments", "true")

	//get the number of retries
	maxRetries := dbclient.CouchInstance.conf.MaxRetries

	resp, couchDBReturn, err := dbclient.handleRequest(http.MethodGet, "ReadDoc", readURL, nil, "", "", maxRetries, true, &query, id)
	if err != nil {
		if couchDBReturn != nil && couchDBReturn.StatusCode == 404 {
			logger.Debugf("[%s] Document not found (404), returning nil value instead of 404 error", dbclient.DBName)
			// non-existent document should return nil value instead of a 404 error
			// for details see https://github.com/hyperledger-archives/fabric/issues/936
			return nil, "", nil
		}
		logger.Debugf("[%s] couchDBReturn=%v\n", dbclient.DBName, couchDBReturn)
		return nil, "", err
	}
	defer closeResponseBody(resp)

	//Get the media type from the Content-Type header
	mediaType, params, err := mime.ParseMediaType(resp.Header.Get("Content-Type"))
	if err != nil {
		log.Fatal(err)
	}

	//Get the revision from header
	revision, err := getRevisionHeader(resp)
	if err != nil {
		return nil, "", err
	}

	//check to see if the is multipart,  handle as attachment if multipart is detected
	if strings.HasPrefix(mediaType, "multipart/") {
		//Set up the multipart reader based on the boundary
		multipartReader := multipart.NewReader(resp.Body, params["boundary"])
		for {
			p, err := multipartReader.NextPart()
			if err == io.EOF {
				break // processed all parts
			}
			if err != nil {
				return nil, "", errors.Wrap(err, "error reading next multipart")
			}

			defer p.Close()

			logger.Debugf("[%s] part header=%s", dbclient.DBName, p.Header)
			switch p.Header.Get("Content-Type") {
			case "application/json":
				partdata, err := ioutil.ReadAll(p)
				if err != nil {
					return nil, "", errors.Wrap(err, "error reading multipart data")
				}
				couchDoc.JSONValue = partdata
			default:

				//Create an attachment structure and load it
				attachment := &AttachmentInfo{}
				attachment.ContentType = p.Header.Get("Content-Type")
				contentDispositionParts := strings.Split(p.Header.Get("Content-Disposition"), ";")
				if strings.TrimSpace(contentDispositionParts[0]) == "attachment" {
					switch p.Header.Get("Content-Encoding") {
					case "gzip": //See if the part is gzip encoded

						var respBody []byte

						gr, err := gzip.NewReader(p)
						if err != nil {
							return nil, "", errors.Wrap(err, "error creating gzip reader")
						}
						respBody, err = ioutil.ReadAll(gr)
						if err != nil {
							return nil, "", errors.Wrap(err, "error reading gzip data")
						}

						logger.Debugf("[%s] Retrieved attachment data", dbclient.DBName)
						attachment.AttachmentBytes = respBody
						attachment.Length = uint64(len(attachment.AttachmentBytes))
						attachment.Name = p.FileName()
						attachments = append(attachments, attachment)

					default:

						//retrieve the data,  this is not gzip
						partdata, err := ioutil.ReadAll(p)
						if err != nil {
							return nil, "", errors.Wrap(err, "error reading multipart data")
						}
						logger.Debugf("[%s] Retrieved attachment data", dbclient.DBName)
						attachment.AttachmentBytes = partdata
						attachment.Length = uint64(len(attachment.AttachmentBytes))
						attachment.Name = p.FileName()
						attachments = append(attachments, attachment)

					} // end content-encoding switch
				} // end if attachment
			} // end content-type switch
		} // for all multiparts

		couchDoc.Attachments = attachments

		return &couchDoc, revision, nil
	}

	//handle as JSON document
	couchDoc.JSONValue, err = ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, "", errors.Wrap(err, "error reading response body")
	}

	logger.Debugf("[%s] Exiting ReadDoc()", dbclient.DBName)
	return &couchDoc, revision, nil
}
62134
func (h *handler) breakAndDeleteDoc(ctx context.Context, docRef blob.Ref) error {
	doc, err := h.fetchDocument(docRef)
	if err != nil {
		return fmt.Errorf("document %v not found: %v", docRef, err)
	}
	if err := h.deleteNode(ctx, docRef); err != nil {
		return fmt.Errorf("could not delete document %v: %v", docRef, err)
	}
	for _, page := range doc.pages {
		if err := h.delAttribute(ctx, page, "document", ""); err != nil {
			return fmt.Errorf("could not unset document of scan %v: %v", page, err)
		}
	}
	return nil
}
525252
func fetchDiscoveryDoc(c context.Context, url string) (*discoveryDoc, error) {
	if url == "" {
		return nil, ErrNotConfigured
	}

	fetcher := func() (interface{}, time.Duration, error) {
		doc := &discoveryDoc{}
		req := internal.Request{
			Method: "GET",
			URL:    url,
			Out:    doc,
		}
		if err := req.Do(c); err != nil {
			return nil, 0, err
		}
		return doc, time.Hour * 24, nil
	}

	// Cache the document in the process cache.
	cached, err := discoveryDocCache.LRU(c).GetOrCreate(c, url, fetcher)
	if err != nil {
		return nil, err
	}
	return cached.(*discoveryDoc), nil
}
1306321
func (doc *Document) GetDocument() ([]byte, error) {
	if doc.Id != "" {
		return doc.getDocFromId()
	}

	return nil, errors.New("An id required to search for the document.")
}
473105
func (vt *VirtualTable) AddRecord(ctx sessionctx.Context, r []types.Datum, opts ...*table.AddRecordOpt) (recordID int64, err error) {
	return 0, table.ErrUnsupportedOp
}
1060073
func (doc *Document) Create(data []byte) error {
	docResp, err := doc.createOrUpdate(data)

	if err != nil {
		return err
	}

	doc.Id = docResp.Id
	doc.Rev = docResp.Rev
	return err
}