repo
stringlengths
5
67
path
stringlengths
4
218
func_name
stringlengths
0
151
original_string
stringlengths
52
373k
language
stringclasses
6 values
code
stringlengths
52
373k
code_tokens
listlengths
10
512
docstring
stringlengths
3
47.2k
docstring_tokens
listlengths
3
234
sha
stringlengths
40
40
url
stringlengths
85
339
partition
stringclasses
3 values
sajari/docconv
snappy/decode.go
DecodedLen
func DecodedLen(src []byte) (int, error) { v, _, err := decodedLen(src) return v, err }
go
func DecodedLen(src []byte) (int, error) { v, _, err := decodedLen(src) return v, err }
[ "func", "DecodedLen", "(", "src", "[", "]", "byte", ")", "(", "int", ",", "error", ")", "{", "v", ",", "_", ",", "err", ":=", "decodedLen", "(", "src", ")", "\n", "return", "v", ",", "err", "\n", "}" ]
// DecodedLen returns the length of the decoded block.
[ "DecodedLen", "returns", "the", "length", "of", "the", "decoded", "block", "." ]
eedabc494f8e97c31f94c70453273f16dbecbc6f
https://github.com/sajari/docconv/blob/eedabc494f8e97c31f94c70453273f16dbecbc6f/snappy/decode.go#L21-L24
train
sajari/docconv
snappy/decode.go
Reset
func (r *Reader) Reset(reader io.Reader) { r.r = reader r.err = nil r.i = 0 r.j = 0 r.readHeader = false }
go
func (r *Reader) Reset(reader io.Reader) { r.r = reader r.err = nil r.i = 0 r.j = 0 r.readHeader = false }
[ "func", "(", "r", "*", "Reader", ")", "Reset", "(", "reader", "io", ".", "Reader", ")", "{", "r", ".", "r", "=", "reader", "\n", "r", ".", "err", "=", "nil", "\n", "r", ".", "i", "=", "0", "\n", "r", ".", "j", "=", "0", "\n", "r", ".", ...
// Reset discards any buffered data, resets all state, and switches the Snappy // reader to read from r. This permits reusing a Reader rather than allocating // a new one.
[ "Reset", "discards", "any", "buffered", "data", "resets", "all", "state", "and", "switches", "the", "Snappy", "reader", "to", "read", "from", "r", ".", "This", "permits", "reusing", "a", "Reader", "rather", "than", "allocating", "a", "new", "one", "." ]
eedabc494f8e97c31f94c70453273f16dbecbc6f
https://github.com/sajari/docconv/blob/eedabc494f8e97c31f94c70453273f16dbecbc6f/snappy/decode.go#L156-L162
train
sajari/docconv
url.go
ConvertURL
func ConvertURL(input io.Reader, readability bool) (string, map[string]string, error) { meta := make(map[string]string) buf := new(bytes.Buffer) _, err := buf.ReadFrom(input) if err != nil { return "", nil, err } g := goose.New() article, err := g.ExtractFromURL(buf.String()) if err != nil { return "", nil, err } meta["title"] = article.Title meta["description"] = article.MetaDescription meta["image"] = article.TopImage return article.CleanedText, meta, nil }
go
func ConvertURL(input io.Reader, readability bool) (string, map[string]string, error) { meta := make(map[string]string) buf := new(bytes.Buffer) _, err := buf.ReadFrom(input) if err != nil { return "", nil, err } g := goose.New() article, err := g.ExtractFromURL(buf.String()) if err != nil { return "", nil, err } meta["title"] = article.Title meta["description"] = article.MetaDescription meta["image"] = article.TopImage return article.CleanedText, meta, nil }
[ "func", "ConvertURL", "(", "input", "io", ".", "Reader", ",", "readability", "bool", ")", "(", "string", ",", "map", "[", "string", "]", "string", ",", "error", ")", "{", "meta", ":=", "make", "(", "map", "[", "string", "]", "string", ")", "\n", "b...
// ConvertURL fetches the HTML page at the URL given in the io.Reader.
[ "ConvertURL", "fetches", "the", "HTML", "page", "at", "the", "URL", "given", "in", "the", "io", ".", "Reader", "." ]
eedabc494f8e97c31f94c70453273f16dbecbc6f
https://github.com/sajari/docconv/blob/eedabc494f8e97c31f94c70453273f16dbecbc6f/url.go#L11-L31
train
sajari/docconv
rtf.go
ConvertRTF
func ConvertRTF(r io.Reader) (string, map[string]string, error) { f, err := NewLocalFile(r, "/tmp", "sajari-convert-") if err != nil { return "", nil, fmt.Errorf("error creating local file: %v", err) } defer f.Done() var output string tmpOutput, err := exec.Command("unrtf", "--nopict", "--text", f.Name()).Output() if err != nil { return "", nil, fmt.Errorf("unrtf error: %v", err) } // Step through content looking for meta data and stripping out comments meta := make(map[string]string) for _, line := range strings.Split(string(tmpOutput), "\n") { if parts := strings.SplitN(line, ":", 2); len(parts) > 1 { meta[strings.TrimSpace(parts[0])] = strings.TrimSpace(parts[1]) } if len(line) > 4 && line[:4] != "### " { output += line + "\n" } } // Identify meta data if tmp, ok := meta["AUTHOR"]; ok { meta["Author"] = tmp } if tmp, ok := meta["### creation date"]; ok { if t, err := time.Parse("02 January 2006 15:04", tmp); err == nil { meta["CreatedDate"] = fmt.Sprintf("%d", t.Unix()) } } if tmp, ok := meta["### revision date"]; ok { if t, err := time.Parse("02 January 2006 15:04", tmp); err == nil { meta["ModifiedDate"] = fmt.Sprintf("%d", t.Unix()) } } return output, meta, nil }
go
func ConvertRTF(r io.Reader) (string, map[string]string, error) { f, err := NewLocalFile(r, "/tmp", "sajari-convert-") if err != nil { return "", nil, fmt.Errorf("error creating local file: %v", err) } defer f.Done() var output string tmpOutput, err := exec.Command("unrtf", "--nopict", "--text", f.Name()).Output() if err != nil { return "", nil, fmt.Errorf("unrtf error: %v", err) } // Step through content looking for meta data and stripping out comments meta := make(map[string]string) for _, line := range strings.Split(string(tmpOutput), "\n") { if parts := strings.SplitN(line, ":", 2); len(parts) > 1 { meta[strings.TrimSpace(parts[0])] = strings.TrimSpace(parts[1]) } if len(line) > 4 && line[:4] != "### " { output += line + "\n" } } // Identify meta data if tmp, ok := meta["AUTHOR"]; ok { meta["Author"] = tmp } if tmp, ok := meta["### creation date"]; ok { if t, err := time.Parse("02 January 2006 15:04", tmp); err == nil { meta["CreatedDate"] = fmt.Sprintf("%d", t.Unix()) } } if tmp, ok := meta["### revision date"]; ok { if t, err := time.Parse("02 January 2006 15:04", tmp); err == nil { meta["ModifiedDate"] = fmt.Sprintf("%d", t.Unix()) } } return output, meta, nil }
[ "func", "ConvertRTF", "(", "r", "io", ".", "Reader", ")", "(", "string", ",", "map", "[", "string", "]", "string", ",", "error", ")", "{", "f", ",", "err", ":=", "NewLocalFile", "(", "r", ",", "\"/tmp\"", ",", "\"sajari-convert-\"", ")", "\n", "if", ...
// ConvertRTF converts RTF files to text.
[ "ConvertRTF", "converts", "RTF", "files", "to", "text", "." ]
eedabc494f8e97c31f94c70453273f16dbecbc6f
https://github.com/sajari/docconv/blob/eedabc494f8e97c31f94c70453273f16dbecbc6f/rtf.go#L12-L52
train
sajari/docconv
docx.go
ConvertDocx
func ConvertDocx(r io.Reader) (string, map[string]string, error) { meta := make(map[string]string) var textHeader, textBody, textFooter string b, err := ioutil.ReadAll(r) if err != nil { return "", nil, err } zr, err := zip.NewReader(bytes.NewReader(b), int64(len(b))) if err != nil { return "", nil, fmt.Errorf("error unzipping data: %v", err) } // Regular expression for XML files to include in the text parsing reHeaderFile, _ := regexp.Compile("^word/header[0-9]+.xml$") reFooterFile, _ := regexp.Compile("^word/footer[0-9]+.xml$") for _, f := range zr.File { switch { case f.Name == "docProps/core.xml": rc, err := f.Open() if err != nil { return "", nil, fmt.Errorf("error opening '%v' from archive: %v", f.Name, err) } defer rc.Close() meta, err = XMLToMap(rc) if err != nil { return "", nil, fmt.Errorf("error parsing '%v': %v", f.Name, err) } if tmp, ok := meta["modified"]; ok { if t, err := time.Parse(time.RFC3339, tmp); err == nil { meta["ModifiedDate"] = fmt.Sprintf("%d", t.Unix()) } } if tmp, ok := meta["created"]; ok { if t, err := time.Parse(time.RFC3339, tmp); err == nil { meta["CreatedDate"] = fmt.Sprintf("%d", t.Unix()) } } case f.Name == "word/document.xml": textBody, err = parseDocxText(f) if err != nil { return "", nil, err } case reHeaderFile.MatchString(f.Name): header, err := parseDocxText(f) if err != nil { return "", nil, err } textHeader += header + "\n" case reFooterFile.MatchString(f.Name): footer, err := parseDocxText(f) if err != nil { return "", nil, err } textFooter += footer + "\n" } } return textHeader + "\n" + textBody + "\n" + textFooter, meta, nil }
go
func ConvertDocx(r io.Reader) (string, map[string]string, error) { meta := make(map[string]string) var textHeader, textBody, textFooter string b, err := ioutil.ReadAll(r) if err != nil { return "", nil, err } zr, err := zip.NewReader(bytes.NewReader(b), int64(len(b))) if err != nil { return "", nil, fmt.Errorf("error unzipping data: %v", err) } // Regular expression for XML files to include in the text parsing reHeaderFile, _ := regexp.Compile("^word/header[0-9]+.xml$") reFooterFile, _ := regexp.Compile("^word/footer[0-9]+.xml$") for _, f := range zr.File { switch { case f.Name == "docProps/core.xml": rc, err := f.Open() if err != nil { return "", nil, fmt.Errorf("error opening '%v' from archive: %v", f.Name, err) } defer rc.Close() meta, err = XMLToMap(rc) if err != nil { return "", nil, fmt.Errorf("error parsing '%v': %v", f.Name, err) } if tmp, ok := meta["modified"]; ok { if t, err := time.Parse(time.RFC3339, tmp); err == nil { meta["ModifiedDate"] = fmt.Sprintf("%d", t.Unix()) } } if tmp, ok := meta["created"]; ok { if t, err := time.Parse(time.RFC3339, tmp); err == nil { meta["CreatedDate"] = fmt.Sprintf("%d", t.Unix()) } } case f.Name == "word/document.xml": textBody, err = parseDocxText(f) if err != nil { return "", nil, err } case reHeaderFile.MatchString(f.Name): header, err := parseDocxText(f) if err != nil { return "", nil, err } textHeader += header + "\n" case reFooterFile.MatchString(f.Name): footer, err := parseDocxText(f) if err != nil { return "", nil, err } textFooter += footer + "\n" } } return textHeader + "\n" + textBody + "\n" + textFooter, meta, nil }
[ "func", "ConvertDocx", "(", "r", "io", ".", "Reader", ")", "(", "string", ",", "map", "[", "string", "]", "string", ",", "error", ")", "{", "meta", ":=", "make", "(", "map", "[", "string", "]", "string", ")", "\n", "var", "textHeader", ",", "textBo...
// ConvertDocx converts an MS Word docx file to text.
[ "ConvertDocx", "converts", "an", "MS", "Word", "docx", "file", "to", "text", "." ]
eedabc494f8e97c31f94c70453273f16dbecbc6f
https://github.com/sajari/docconv/blob/eedabc494f8e97c31f94c70453273f16dbecbc6f/docx.go#L14-L79
train
sajari/docconv
docx.go
DocxXMLToText
func DocxXMLToText(r io.Reader) (string, error) { return XMLToText(r, []string{"br", "p", "tab"}, []string{"instrText", "script"}, true) }
go
func DocxXMLToText(r io.Reader) (string, error) { return XMLToText(r, []string{"br", "p", "tab"}, []string{"instrText", "script"}, true) }
[ "func", "DocxXMLToText", "(", "r", "io", ".", "Reader", ")", "(", "string", ",", "error", ")", "{", "return", "XMLToText", "(", "r", ",", "[", "]", "string", "{", "\"br\"", ",", "\"p\"", ",", "\"tab\"", "}", ",", "[", "]", "string", "{", "\"instrTe...
// DocxXMLToText converts Docx XML into plain text.
[ "DocxXMLToText", "converts", "Docx", "XML", "into", "plain", "text", "." ]
eedabc494f8e97c31f94c70453273f16dbecbc6f
https://github.com/sajari/docconv/blob/eedabc494f8e97c31f94c70453273f16dbecbc6f/docx.go#L96-L98
train
sajari/docconv
html.go
ConvertHTML
func ConvertHTML(r io.Reader, readability bool) (string, map[string]string, error) { meta := make(map[string]string) buf := new(bytes.Buffer) _, err := buf.ReadFrom(r) if err != nil { return "", nil, err } cleanXML, err := Tidy(buf, false) if err != nil { log.Println("Tidy:", err) // Tidy failed, so we now manually tokenize instead clean := cleanHTML(buf, true) cleanXML = []byte(clean) // TODO: remove this log log.Println("Cleaned HTML using Golang tokenizer") } if readability { cleanXML = HTMLReadability(bytes.NewReader(cleanXML)) } return HTMLToText(bytes.NewReader(cleanXML)), meta, nil }
go
func ConvertHTML(r io.Reader, readability bool) (string, map[string]string, error) { meta := make(map[string]string) buf := new(bytes.Buffer) _, err := buf.ReadFrom(r) if err != nil { return "", nil, err } cleanXML, err := Tidy(buf, false) if err != nil { log.Println("Tidy:", err) // Tidy failed, so we now manually tokenize instead clean := cleanHTML(buf, true) cleanXML = []byte(clean) // TODO: remove this log log.Println("Cleaned HTML using Golang tokenizer") } if readability { cleanXML = HTMLReadability(bytes.NewReader(cleanXML)) } return HTMLToText(bytes.NewReader(cleanXML)), meta, nil }
[ "func", "ConvertHTML", "(", "r", "io", ".", "Reader", ",", "readability", "bool", ")", "(", "string", ",", "map", "[", "string", "]", "string", ",", "error", ")", "{", "meta", ":=", "make", "(", "map", "[", "string", "]", "string", ")", "\n", "buf"...
// ConvertHTML converts HTML into text.
[ "ConvertHTML", "converts", "HTML", "into", "text", "." ]
eedabc494f8e97c31f94c70453273f16dbecbc6f
https://github.com/sajari/docconv/blob/eedabc494f8e97c31f94c70453273f16dbecbc6f/html.go#L17-L40
train
sajari/docconv
html.go
acceptedHTMLTag
func acceptedHTMLTag(tagName string) bool { for _, tag := range acceptedHTMLTags { if tag == tagName { return true } } return false }
go
func acceptedHTMLTag(tagName string) bool { for _, tag := range acceptedHTMLTags { if tag == tagName { return true } } return false }
[ "func", "acceptedHTMLTag", "(", "tagName", "string", ")", "bool", "{", "for", "_", ",", "tag", ":=", "range", "acceptedHTMLTags", "{", "if", "tag", "==", "tagName", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// Tests for known friendly HTML parameters that tidy is unlikely to choke on
[ "Tests", "for", "known", "friendly", "HTML", "parameters", "that", "tidy", "is", "unlikely", "to", "choke", "on" ]
eedabc494f8e97c31f94c70453273f16dbecbc6f
https://github.com/sajari/docconv/blob/eedabc494f8e97c31f94c70453273f16dbecbc6f/html.go#L50-L57
train
sajari/docconv
html.go
HTMLReadability
func HTMLReadability(r io.Reader) []byte { jr := justext.NewReader(r) // TODO: Improve this! jr.Stoplist = readabilityStopList jr.LengthLow = HTMLReadabilityOptionsValues.LengthLow jr.LengthHigh = HTMLReadabilityOptionsValues.LengthHigh jr.StopwordsLow = HTMLReadabilityOptionsValues.StopwordsLow jr.StopwordsHigh = HTMLReadabilityOptionsValues.StopwordsHigh jr.MaxLinkDensity = HTMLReadabilityOptionsValues.MaxLinkDensity jr.MaxHeadingDistance = HTMLReadabilityOptionsValues.MaxHeadingDistance paragraphSet, err := jr.ReadAll() if err != nil { log.Println("Justext:", err) return nil } useClasses := strings.SplitN(HTMLReadabilityOptionsValues.ReadabilityUseClasses, ",", 10) output := "" for _, paragraph := range paragraphSet { for _, class := range useClasses { if paragraph.CfClass == class { output += paragraph.Text + "\n" } } } return []byte(output) }
go
func HTMLReadability(r io.Reader) []byte { jr := justext.NewReader(r) // TODO: Improve this! jr.Stoplist = readabilityStopList jr.LengthLow = HTMLReadabilityOptionsValues.LengthLow jr.LengthHigh = HTMLReadabilityOptionsValues.LengthHigh jr.StopwordsLow = HTMLReadabilityOptionsValues.StopwordsLow jr.StopwordsHigh = HTMLReadabilityOptionsValues.StopwordsHigh jr.MaxLinkDensity = HTMLReadabilityOptionsValues.MaxLinkDensity jr.MaxHeadingDistance = HTMLReadabilityOptionsValues.MaxHeadingDistance paragraphSet, err := jr.ReadAll() if err != nil { log.Println("Justext:", err) return nil } useClasses := strings.SplitN(HTMLReadabilityOptionsValues.ReadabilityUseClasses, ",", 10) output := "" for _, paragraph := range paragraphSet { for _, class := range useClasses { if paragraph.CfClass == class { output += paragraph.Text + "\n" } } } return []byte(output) }
[ "func", "HTMLReadability", "(", "r", "io", ".", "Reader", ")", "[", "]", "byte", "{", "jr", ":=", "justext", ".", "NewReader", "(", "r", ")", "\n", "jr", ".", "Stoplist", "=", "readabilityStopList", "\n", "jr", ".", "LengthLow", "=", "HTMLReadabilityOpti...
// HTMLReadability extracts the readable text in an HTML document
[ "HTMLReadability", "extracts", "the", "readable", "text", "in", "an", "HTML", "document" ]
eedabc494f8e97c31f94c70453273f16dbecbc6f
https://github.com/sajari/docconv/blob/eedabc494f8e97c31f94c70453273f16dbecbc6f/html.go#L130-L160
train
sajari/docconv
html.go
HTMLToText
func HTMLToText(input io.Reader) string { text, _ := XMLToText(input, []string{"br", "p", "h1", "h2", "h3", "h4"}, []string{}, false) return text }
go
func HTMLToText(input io.Reader) string { text, _ := XMLToText(input, []string{"br", "p", "h1", "h2", "h3", "h4"}, []string{}, false) return text }
[ "func", "HTMLToText", "(", "input", "io", ".", "Reader", ")", "string", "{", "text", ",", "_", ":=", "XMLToText", "(", "input", ",", "[", "]", "string", "{", "\"br\"", ",", "\"p\"", ",", "\"h1\"", ",", "\"h2\"", ",", "\"h3\"", ",", "\"h4\"", "}", "...
// HTMLToText converts HTML to plain text.
[ "HTMLToText", "converts", "HTML", "to", "plain", "text", "." ]
eedabc494f8e97c31f94c70453273f16dbecbc6f
https://github.com/sajari/docconv/blob/eedabc494f8e97c31f94c70453273f16dbecbc6f/html.go#L163-L166
train
sajari/docconv
docconv.go
Convert
func Convert(r io.Reader, mimeType string, readability bool) (*Response, error) { start := time.Now() var body string var meta map[string]string var err error switch mimeType { case "application/msword", "application/vnd.ms-word": body, meta, err = ConvertDoc(r) case "application/vnd.openxmlformats-officedocument.wordprocessingml.document": body, meta, err = ConvertDocx(r) case "application/vnd.oasis.opendocument.text": body, meta, err = ConvertODT(r) case "application/vnd.apple.pages", "application/x-iwork-pages-sffpages": body, meta, err = ConvertPages(r) case "application/pdf": body, meta, err = ConvertPDF(r) case "application/rtf", "application/x-rtf", "text/rtf", "text/richtext": body, meta, err = ConvertRTF(r) case "text/html": body, meta, err = ConvertHTML(r, readability) case "text/url": body, meta, err = ConvertURL(r, readability) case "text/xml", "application/xml": body, meta, err = ConvertXML(r) case "image/jpeg", "image/png", "image/tif", "image/tiff": body, meta, err = ConvertImage(r) case "text/plain": var b []byte b, err = ioutil.ReadAll(r) body = string(b) } if err != nil { return nil, fmt.Errorf("error converting data: %v", err) } return &Response{ Body: strings.TrimSpace(body), Meta: meta, MSecs: uint32(time.Since(start) / time.Millisecond), }, nil }
go
func Convert(r io.Reader, mimeType string, readability bool) (*Response, error) { start := time.Now() var body string var meta map[string]string var err error switch mimeType { case "application/msword", "application/vnd.ms-word": body, meta, err = ConvertDoc(r) case "application/vnd.openxmlformats-officedocument.wordprocessingml.document": body, meta, err = ConvertDocx(r) case "application/vnd.oasis.opendocument.text": body, meta, err = ConvertODT(r) case "application/vnd.apple.pages", "application/x-iwork-pages-sffpages": body, meta, err = ConvertPages(r) case "application/pdf": body, meta, err = ConvertPDF(r) case "application/rtf", "application/x-rtf", "text/rtf", "text/richtext": body, meta, err = ConvertRTF(r) case "text/html": body, meta, err = ConvertHTML(r, readability) case "text/url": body, meta, err = ConvertURL(r, readability) case "text/xml", "application/xml": body, meta, err = ConvertXML(r) case "image/jpeg", "image/png", "image/tif", "image/tiff": body, meta, err = ConvertImage(r) case "text/plain": var b []byte b, err = ioutil.ReadAll(r) body = string(b) } if err != nil { return nil, fmt.Errorf("error converting data: %v", err) } return &Response{ Body: strings.TrimSpace(body), Meta: meta, MSecs: uint32(time.Since(start) / time.Millisecond), }, nil }
[ "func", "Convert", "(", "r", "io", ".", "Reader", ",", "mimeType", "string", ",", "readability", "bool", ")", "(", "*", "Response", ",", "error", ")", "{", "start", ":=", "time", ".", "Now", "(", ")", "\n", "var", "body", "string", "\n", "var", "me...
// Convert a file to plain text.
[ "Convert", "a", "file", "to", "plain", "text", "." ]
eedabc494f8e97c31f94c70453273f16dbecbc6f
https://github.com/sajari/docconv/blob/eedabc494f8e97c31f94c70453273f16dbecbc6f/docconv.go#L57-L109
train
sajari/docconv
docconv.go
ConvertPath
func ConvertPath(path string) (*Response, error) { mimeType := MimeTypeByExtension(path) f, err := os.Open(path) if err != nil { return nil, err } defer f.Close() return Convert(f, mimeType, true) }
go
func ConvertPath(path string) (*Response, error) { mimeType := MimeTypeByExtension(path) f, err := os.Open(path) if err != nil { return nil, err } defer f.Close() return Convert(f, mimeType, true) }
[ "func", "ConvertPath", "(", "path", "string", ")", "(", "*", "Response", ",", "error", ")", "{", "mimeType", ":=", "MimeTypeByExtension", "(", "path", ")", "\n", "f", ",", "err", ":=", "os", ".", "Open", "(", "path", ")", "\n", "if", "err", "!=", "...
// ConvertPath converts a local path to text.
[ "ConvertPath", "converts", "a", "local", "path", "to", "text", "." ]
eedabc494f8e97c31f94c70453273f16dbecbc6f
https://github.com/sajari/docconv/blob/eedabc494f8e97c31f94c70453273f16dbecbc6f/docconv.go#L112-L122
train
sajari/docconv
docconv.go
ConvertPathReadability
func ConvertPathReadability(path string, readability bool) ([]byte, error) { mimeType := MimeTypeByExtension(path) f, err := os.Open(path) if err != nil { return nil, err } defer f.Close() data, err := Convert(f, mimeType, readability) if err != nil { return nil, err } return json.Marshal(data) }
go
func ConvertPathReadability(path string, readability bool) ([]byte, error) { mimeType := MimeTypeByExtension(path) f, err := os.Open(path) if err != nil { return nil, err } defer f.Close() data, err := Convert(f, mimeType, readability) if err != nil { return nil, err } return json.Marshal(data) }
[ "func", "ConvertPathReadability", "(", "path", "string", ",", "readability", "bool", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "mimeType", ":=", "MimeTypeByExtension", "(", "path", ")", "\n", "f", ",", "err", ":=", "os", ".", "Open", "(", "pa...
// ConvertPathReadability converts a local path to text, with the given readability // option.
[ "ConvertPathReadability", "converts", "a", "local", "path", "to", "text", "with", "the", "given", "readability", "option", "." ]
eedabc494f8e97c31f94c70453273f16dbecbc6f
https://github.com/sajari/docconv/blob/eedabc494f8e97c31f94c70453273f16dbecbc6f/docconv.go#L126-L140
train
sajari/docconv
client/client.go
New
func New(opts ...Opt) *Client { c := &Client{ endpoint: DefaultEndpoint, protocol: DefaultProtocol, httpClient: DefaultHTTPClient, } for _, opt := range opts { opt(c) } return c }
go
func New(opts ...Opt) *Client { c := &Client{ endpoint: DefaultEndpoint, protocol: DefaultProtocol, httpClient: DefaultHTTPClient, } for _, opt := range opts { opt(c) } return c }
[ "func", "New", "(", "opts", "...", "Opt", ")", "*", "Client", "{", "c", ":=", "&", "Client", "{", "endpoint", ":", "DefaultEndpoint", ",", "protocol", ":", "DefaultProtocol", ",", "httpClient", ":", "DefaultHTTPClient", ",", "}", "\n", "for", "_", ",", ...
// New creates a new docconv client for interacting with a docconv HTTP // server.
[ "New", "creates", "a", "new", "docconv", "client", "for", "interacting", "with", "a", "docconv", "HTTP", "server", "." ]
eedabc494f8e97c31f94c70453273f16dbecbc6f
https://github.com/sajari/docconv/blob/eedabc494f8e97c31f94c70453273f16dbecbc6f/client/client.go#L55-L66
train
sajari/docconv
client/client.go
Convert
func (c *Client) Convert(r io.Reader, filename string) (*Response, error) { buf := &bytes.Buffer{} w := multipart.NewWriter(buf) part, err := w.CreateFormFile("input", filename) if err != nil { return nil, err } if _, err := io.Copy(part, r); err != nil { return nil, err } if err := w.Close(); err != nil { return nil, err } req, err := http.NewRequest("POST", fmt.Sprintf("%v%v/convert", c.protocol, c.endpoint), buf) if err != nil { return nil, err } req.Header.Set("Content-Type", w.FormDataContentType()) resp, err := c.httpClient.Do(req) if err != nil { return nil, err } defer resp.Body.Close() res := &Response{} if err := json.NewDecoder(resp.Body).Decode(&res); err != nil { return nil, err } return res, nil }
go
func (c *Client) Convert(r io.Reader, filename string) (*Response, error) { buf := &bytes.Buffer{} w := multipart.NewWriter(buf) part, err := w.CreateFormFile("input", filename) if err != nil { return nil, err } if _, err := io.Copy(part, r); err != nil { return nil, err } if err := w.Close(); err != nil { return nil, err } req, err := http.NewRequest("POST", fmt.Sprintf("%v%v/convert", c.protocol, c.endpoint), buf) if err != nil { return nil, err } req.Header.Set("Content-Type", w.FormDataContentType()) resp, err := c.httpClient.Do(req) if err != nil { return nil, err } defer resp.Body.Close() res := &Response{} if err := json.NewDecoder(resp.Body).Decode(&res); err != nil { return nil, err } return res, nil }
[ "func", "(", "c", "*", "Client", ")", "Convert", "(", "r", "io", ".", "Reader", ",", "filename", "string", ")", "(", "*", "Response", ",", "error", ")", "{", "buf", ":=", "&", "bytes", ".", "Buffer", "{", "}", "\n", "w", ":=", "multipart", ".", ...
// Convert a file from a local path using the http client
[ "Convert", "a", "file", "from", "a", "local", "path", "using", "the", "http", "client" ]
eedabc494f8e97c31f94c70453273f16dbecbc6f
https://github.com/sajari/docconv/blob/eedabc494f8e97c31f94c70453273f16dbecbc6f/client/client.go#L85-L116
train
sajari/docconv
client/client.go
ConvertPath
func ConvertPath(c *Client, path string) (*Response, error) { f, err := os.Open(path) if err != nil { return nil, err } defer f.Close() return c.Convert(f, f.Name()) }
go
func ConvertPath(c *Client, path string) (*Response, error) { f, err := os.Open(path) if err != nil { return nil, err } defer f.Close() return c.Convert(f, f.Name()) }
[ "func", "ConvertPath", "(", "c", "*", "Client", ",", "path", "string", ")", "(", "*", "Response", ",", "error", ")", "{", "f", ",", "err", ":=", "os", ".", "Open", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "er...
// ConvertPath uses the docconv Client to convert the local file // found at path.
[ "ConvertPath", "uses", "the", "docconv", "Client", "to", "convert", "the", "local", "file", "found", "at", "path", "." ]
eedabc494f8e97c31f94c70453273f16dbecbc6f
https://github.com/sajari/docconv/blob/eedabc494f8e97c31f94c70453273f16dbecbc6f/client/client.go#L120-L128
train
sajari/docconv
doc.go
ConvertDoc
func ConvertDoc(r io.Reader) (string, map[string]string, error) { f, err := NewLocalFile(r, "/tmp", "sajari-convert-") if err != nil { return "", nil, fmt.Errorf("error creating local file: %v", err) } defer f.Done() // Meta data mc := make(chan map[string]string, 1) go func() { meta := make(map[string]string) metaStr, err := exec.Command("wvSummary", f.Name()).Output() if err != nil { // TODO: Remove this. log.Println("wvSummary:", err) } // Parse meta output for _, line := range strings.Split(string(metaStr), "\n") { if parts := strings.SplitN(line, "=", 2); len(parts) > 1 { meta[strings.TrimSpace(parts[0])] = strings.TrimSpace(parts[1]) } } // Convert parsed meta if tmp, ok := meta["Last Modified"]; ok { if t, err := time.Parse(time.RFC3339, tmp); err == nil { meta["ModifiedDate"] = fmt.Sprintf("%d", t.Unix()) } } if tmp, ok := meta["Created"]; ok { if t, err := time.Parse(time.RFC3339, tmp); err == nil { meta["CreatedDate"] = fmt.Sprintf("%d", t.Unix()) } } mc <- meta }() // Document body bc := make(chan string, 1) go func() { // Save output to a file outputFile, err := ioutil.TempFile("/tmp", "sajari-convert-") if err != nil { // TODO: Remove this. log.Println("TempFile Out:", err) return } defer os.Remove(outputFile.Name()) err = exec.Command("wvText", f.Name(), outputFile.Name()).Run() if err != nil { // TODO: Remove this. log.Println("wvText:", err) } var buf bytes.Buffer _, err = buf.ReadFrom(outputFile) if err != nil { // TODO: Remove this. log.Println("wvText:", err) } bc <- buf.String() }() // TODO: Should errors in either of the above Goroutines stop things from progressing? body := <-bc meta := <-mc // TODO: Check for errors instead of len(body) == 0? if len(body) == 0 { f.Seek(0, 0) return ConvertDocx(f) } return body, meta, nil }
go
func ConvertDoc(r io.Reader) (string, map[string]string, error) { f, err := NewLocalFile(r, "/tmp", "sajari-convert-") if err != nil { return "", nil, fmt.Errorf("error creating local file: %v", err) } defer f.Done() // Meta data mc := make(chan map[string]string, 1) go func() { meta := make(map[string]string) metaStr, err := exec.Command("wvSummary", f.Name()).Output() if err != nil { // TODO: Remove this. log.Println("wvSummary:", err) } // Parse meta output for _, line := range strings.Split(string(metaStr), "\n") { if parts := strings.SplitN(line, "=", 2); len(parts) > 1 { meta[strings.TrimSpace(parts[0])] = strings.TrimSpace(parts[1]) } } // Convert parsed meta if tmp, ok := meta["Last Modified"]; ok { if t, err := time.Parse(time.RFC3339, tmp); err == nil { meta["ModifiedDate"] = fmt.Sprintf("%d", t.Unix()) } } if tmp, ok := meta["Created"]; ok { if t, err := time.Parse(time.RFC3339, tmp); err == nil { meta["CreatedDate"] = fmt.Sprintf("%d", t.Unix()) } } mc <- meta }() // Document body bc := make(chan string, 1) go func() { // Save output to a file outputFile, err := ioutil.TempFile("/tmp", "sajari-convert-") if err != nil { // TODO: Remove this. log.Println("TempFile Out:", err) return } defer os.Remove(outputFile.Name()) err = exec.Command("wvText", f.Name(), outputFile.Name()).Run() if err != nil { // TODO: Remove this. log.Println("wvText:", err) } var buf bytes.Buffer _, err = buf.ReadFrom(outputFile) if err != nil { // TODO: Remove this. log.Println("wvText:", err) } bc <- buf.String() }() // TODO: Should errors in either of the above Goroutines stop things from progressing? body := <-bc meta := <-mc // TODO: Check for errors instead of len(body) == 0? if len(body) == 0 { f.Seek(0, 0) return ConvertDocx(f) } return body, meta, nil }
[ "func", "ConvertDoc", "(", "r", "io", ".", "Reader", ")", "(", "string", ",", "map", "[", "string", "]", "string", ",", "error", ")", "{", "f", ",", "err", ":=", "NewLocalFile", "(", "r", ",", "\"/tmp\"", ",", "\"sajari-convert-\"", ")", "\n", "if", ...
// ConvertDoc converts an MS Word .doc to text.
[ "ConvertDoc", "converts", "an", "MS", "Word", ".", "doc", "to", "text", "." ]
eedabc494f8e97c31f94c70453273f16dbecbc6f
https://github.com/sajari/docconv/blob/eedabc494f8e97c31f94c70453273f16dbecbc6f/doc.go#L16-L94
train
sajari/docconv
image_ocr.go
ConvertImage
func ConvertImage(r io.Reader) (string, map[string]string, error) { f, err := NewLocalFile(r, "/tmp", "sajari-convert-") if err != nil { return "", nil, fmt.Errorf("error creating local file: %v", err) } defer f.Done() meta := make(map[string]string) out := make(chan string, 1) // TODO: Why is this done in a separate goroutine when ConvertImage blocks until it returns? go func(file *LocalFile) { langs.RLock() body := gosseract.Must(gosseract.Params{Src: file.Name(), Languages: langs.lang}) langs.RUnlock() out <- string(body) }(f) return <-out, meta, nil }
go
func ConvertImage(r io.Reader) (string, map[string]string, error) { f, err := NewLocalFile(r, "/tmp", "sajari-convert-") if err != nil { return "", nil, fmt.Errorf("error creating local file: %v", err) } defer f.Done() meta := make(map[string]string) out := make(chan string, 1) // TODO: Why is this done in a separate goroutine when ConvertImage blocks until it returns? go func(file *LocalFile) { langs.RLock() body := gosseract.Must(gosseract.Params{Src: file.Name(), Languages: langs.lang}) langs.RUnlock() out <- string(body) }(f) return <-out, meta, nil }
[ "func", "ConvertImage", "(", "r", "io", ".", "Reader", ")", "(", "string", ",", "map", "[", "string", "]", "string", ",", "error", ")", "{", "f", ",", "err", ":=", "NewLocalFile", "(", "r", ",", "\"/tmp\"", ",", "\"sajari-convert-\"", ")", "\n", "if"...
// ConvertImage converts images to text. // Requires gosseract.
[ "ConvertImage", "converts", "images", "to", "text", ".", "Requires", "gosseract", "." ]
eedabc494f8e97c31f94c70453273f16dbecbc6f
https://github.com/sajari/docconv/blob/eedabc494f8e97c31f94c70453273f16dbecbc6f/image_ocr.go#L20-L39
train
sajari/docconv
image_ocr.go
SetImageLanguages
func SetImageLanguages(l string) { langs.Lock() langs.lang = l langs.Unlock() }
go
func SetImageLanguages(l string) { langs.Lock() langs.lang = l langs.Unlock() }
[ "func", "SetImageLanguages", "(", "l", "string", ")", "{", "langs", ".", "Lock", "(", ")", "\n", "langs", ".", "lang", "=", "l", "\n", "langs", ".", "Unlock", "(", ")", "\n", "}" ]
// SetImageLanguages sets the languages parameter passed to gosseract.
[ "SetImageLanguages", "sets", "the", "languages", "parameter", "passed", "to", "gosseract", "." ]
eedabc494f8e97c31f94c70453273f16dbecbc6f
https://github.com/sajari/docconv/blob/eedabc494f8e97c31f94c70453273f16dbecbc6f/image_ocr.go#L42-L46
train
sajari/docconv
pages.go
ConvertPages
func ConvertPages(r io.Reader) (string, map[string]string, error) { meta := make(map[string]string) var textBody string b, err := ioutil.ReadAll(r) if err != nil { return "", nil, fmt.Errorf("error reading data: %v", err) } zr, err := zip.NewReader(bytes.NewReader(b), int64(len(b))) if err != nil { return "", nil, fmt.Errorf("error unzipping data: %v", err) } for _, f := range zr.File { if strings.HasSuffix(f.Name, "Preview.pdf") { // There is a preview PDF version we can use if rc, err := f.Open(); err == nil { return ConvertPDF(rc) } } if f.Name == "index.xml" { // There's an XML version we can use if rc, err := f.Open(); err == nil { return ConvertXML(rc) } } if f.Name == "Index/Document.iwa" { rc, _ := f.Open() defer rc.Close() bReader := bufio.NewReader(snappy.NewReader(io.MultiReader(strings.NewReader("\xff\x06\x00\x00sNaPpY"), rc))) archiveLength, err := binary.ReadVarint(bReader) archiveInfoData, err := ioutil.ReadAll(io.LimitReader(bReader, archiveLength)) archiveInfo := &TSP.ArchiveInfo{} err = proto.Unmarshal(archiveInfoData, archiveInfo) fmt.Println("archiveInfo:", archiveInfo, err) } } return textBody, meta, nil }
go
func ConvertPages(r io.Reader) (string, map[string]string, error) { meta := make(map[string]string) var textBody string b, err := ioutil.ReadAll(r) if err != nil { return "", nil, fmt.Errorf("error reading data: %v", err) } zr, err := zip.NewReader(bytes.NewReader(b), int64(len(b))) if err != nil { return "", nil, fmt.Errorf("error unzipping data: %v", err) } for _, f := range zr.File { if strings.HasSuffix(f.Name, "Preview.pdf") { // There is a preview PDF version we can use if rc, err := f.Open(); err == nil { return ConvertPDF(rc) } } if f.Name == "index.xml" { // There's an XML version we can use if rc, err := f.Open(); err == nil { return ConvertXML(rc) } } if f.Name == "Index/Document.iwa" { rc, _ := f.Open() defer rc.Close() bReader := bufio.NewReader(snappy.NewReader(io.MultiReader(strings.NewReader("\xff\x06\x00\x00sNaPpY"), rc))) archiveLength, err := binary.ReadVarint(bReader) archiveInfoData, err := ioutil.ReadAll(io.LimitReader(bReader, archiveLength)) archiveInfo := &TSP.ArchiveInfo{} err = proto.Unmarshal(archiveInfoData, archiveInfo) fmt.Println("archiveInfo:", archiveInfo, err) } } return textBody, meta, nil }
[ "func", "ConvertPages", "(", "r", "io", ".", "Reader", ")", "(", "string", ",", "map", "[", "string", "]", "string", ",", "error", ")", "{", "meta", ":=", "make", "(", "map", "[", "string", "]", "string", ")", "\n", "var", "textBody", "string", "\n...
// ConvertPages converts a Pages file to text.
[ "ConvertPages", "converts", "a", "Pages", "file", "to", "text", "." ]
eedabc494f8e97c31f94c70453273f16dbecbc6f
https://github.com/sajari/docconv/blob/eedabc494f8e97c31f94c70453273f16dbecbc6f/pages.go#L20-L60
train
sajari/docconv
docd/main.go
convertPath
func convertPath(path string, readability bool) ([]byte, error) { mimeType := docconv.MimeTypeByExtension(path) if *logLevel >= 1 { log.Println("Converting file: " + path + " (" + mimeType + ")") } // Open file f, err := os.Open(path) if err != nil { return nil, err } defer f.Close() data, err := docconv.Convert(f, mimeType, readability) if err != nil { return nil, err } b, err := json.Marshal(data) if err != nil { return nil, err } if *logLevel >= 2 { log.Println(string(b)) } return b, nil }
go
func convertPath(path string, readability bool) ([]byte, error) { mimeType := docconv.MimeTypeByExtension(path) if *logLevel >= 1 { log.Println("Converting file: " + path + " (" + mimeType + ")") } // Open file f, err := os.Open(path) if err != nil { return nil, err } defer f.Close() data, err := docconv.Convert(f, mimeType, readability) if err != nil { return nil, err } b, err := json.Marshal(data) if err != nil { return nil, err } if *logLevel >= 2 { log.Println(string(b)) } return b, nil }
[ "func", "convertPath", "(", "path", "string", ",", "readability", "bool", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "mimeType", ":=", "docconv", ".", "MimeTypeByExtension", "(", "path", ")", "\n", "if", "*", "logLevel", ">=", "1", "{", "log",...
// Convert a file given a path
[ "Convert", "a", "file", "given", "a", "path" ]
eedabc494f8e97c31f94c70453273f16dbecbc6f
https://github.com/sajari/docconv/blob/eedabc494f8e97c31f94c70453273f16dbecbc6f/docd/main.go#L53-L78
train
sajari/docconv
docd/main.go
serve
func serve() { http.HandleFunc("/convert", func(w http.ResponseWriter, r *http.Request) { // Readability flag. Currently only used for HTML var readability bool if r.FormValue("readability") == "1" { readability = true if *logLevel >= 2 { log.Println("Readability is on") } } path := r.FormValue("path") if path != "" { b, err := docconv.ConvertPathReadability(path, readability) if err != nil { // TODO: return a sensible status code for errors like this. log.Printf("error converting path '%v': %v", path, err) return } w.Write(b) return } // Get uploaded file file, info, err := r.FormFile("input") if err != nil { log.Println("File upload", err) return } defer file.Close() // Abort if file doesn't have a mime type if len(info.Header["Content-Type"]) == 0 { log.Println("No content type", info.Filename) return } // If a generic mime type was provided then use file extension to determine mimetype mimeType := info.Header["Content-Type"][0] if mimeType == "application/octet-stream" { mimeType = docconv.MimeTypeByExtension(info.Filename) } if *logLevel >= 1 { log.Println("Received file: " + info.Filename + " (" + mimeType + ")") } data, err := docconv.Convert(file, mimeType, readability) if err != nil { log.Printf("error converting data: %v", err) data = &docconv.Response{ Error: err.Error(), } } if err := json.NewEncoder(w).Encode(data); err != nil { log.Printf("error marshaling JSON data: %v", err) return } }) // Start webserver log.Println("Setting log level to", *logLevel) log.Println("Starting docconv on", *listenAddr) log.Fatal(http.ListenAndServe(*listenAddr, nil)) }
go
func serve() { http.HandleFunc("/convert", func(w http.ResponseWriter, r *http.Request) { // Readability flag. Currently only used for HTML var readability bool if r.FormValue("readability") == "1" { readability = true if *logLevel >= 2 { log.Println("Readability is on") } } path := r.FormValue("path") if path != "" { b, err := docconv.ConvertPathReadability(path, readability) if err != nil { // TODO: return a sensible status code for errors like this. log.Printf("error converting path '%v': %v", path, err) return } w.Write(b) return } // Get uploaded file file, info, err := r.FormFile("input") if err != nil { log.Println("File upload", err) return } defer file.Close() // Abort if file doesn't have a mime type if len(info.Header["Content-Type"]) == 0 { log.Println("No content type", info.Filename) return } // If a generic mime type was provided then use file extension to determine mimetype mimeType := info.Header["Content-Type"][0] if mimeType == "application/octet-stream" { mimeType = docconv.MimeTypeByExtension(info.Filename) } if *logLevel >= 1 { log.Println("Received file: " + info.Filename + " (" + mimeType + ")") } data, err := docconv.Convert(file, mimeType, readability) if err != nil { log.Printf("error converting data: %v", err) data = &docconv.Response{ Error: err.Error(), } } if err := json.NewEncoder(w).Encode(data); err != nil { log.Printf("error marshaling JSON data: %v", err) return } }) // Start webserver log.Println("Setting log level to", *logLevel) log.Println("Starting docconv on", *listenAddr) log.Fatal(http.ListenAndServe(*listenAddr, nil)) }
[ "func", "serve", "(", ")", "{", "http", ".", "HandleFunc", "(", "\"/convert\"", ",", "func", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "var", "readability", "bool", "\n", "if", "r", ".", "FormValue", "(...
// Start the conversion web service
[ "Start", "the", "conversion", "web", "service" ]
eedabc494f8e97c31f94c70453273f16dbecbc6f
https://github.com/sajari/docconv/blob/eedabc494f8e97c31f94c70453273f16dbecbc6f/docd/main.go#L81-L146
train
sajari/docconv
xml.go
ConvertXML
func ConvertXML(r io.Reader) (string, map[string]string, error) { meta := make(map[string]string) cleanXML, err := Tidy(r, true) if err != nil { return "", nil, fmt.Errorf("tidy error: %v", err) } result, err := XMLToText(bytes.NewReader(cleanXML), []string{}, []string{}, true) if err != nil { return "", nil, fmt.Errorf("error from XMLToText: %v", err) } return result, meta, nil }
go
func ConvertXML(r io.Reader) (string, map[string]string, error) { meta := make(map[string]string) cleanXML, err := Tidy(r, true) if err != nil { return "", nil, fmt.Errorf("tidy error: %v", err) } result, err := XMLToText(bytes.NewReader(cleanXML), []string{}, []string{}, true) if err != nil { return "", nil, fmt.Errorf("error from XMLToText: %v", err) } return result, meta, nil }
[ "func", "ConvertXML", "(", "r", "io", ".", "Reader", ")", "(", "string", ",", "map", "[", "string", "]", "string", ",", "error", ")", "{", "meta", ":=", "make", "(", "map", "[", "string", "]", "string", ")", "\n", "cleanXML", ",", "err", ":=", "T...
// ConvertXML converts an XML file to text.
[ "ConvertXML", "converts", "an", "XML", "file", "to", "text", "." ]
eedabc494f8e97c31f94c70453273f16dbecbc6f
https://github.com/sajari/docconv/blob/eedabc494f8e97c31f94c70453273f16dbecbc6f/xml.go#L11-L22
train
sajari/docconv
xml.go
XMLToText
func XMLToText(r io.Reader, breaks []string, skip []string, strict bool) (string, error) { var result string dec := xml.NewDecoder(r) dec.Strict = strict for { t, err := dec.Token() if err != nil { if err == io.EOF { break } return "", err } switch v := t.(type) { case xml.CharData: result += string(v) case xml.StartElement: for _, breakElement := range breaks { if v.Name.Local == breakElement { result += "\n" } } for _, skipElement := range skip { if v.Name.Local == skipElement { depth := 1 for { t, err := dec.Token() if err != nil { // An io.EOF here is actually an error. return "", err } switch t.(type) { case xml.StartElement: depth++ case xml.EndElement: depth-- } if depth == 0 { break } } } } } } return result, nil }
go
func XMLToText(r io.Reader, breaks []string, skip []string, strict bool) (string, error) { var result string dec := xml.NewDecoder(r) dec.Strict = strict for { t, err := dec.Token() if err != nil { if err == io.EOF { break } return "", err } switch v := t.(type) { case xml.CharData: result += string(v) case xml.StartElement: for _, breakElement := range breaks { if v.Name.Local == breakElement { result += "\n" } } for _, skipElement := range skip { if v.Name.Local == skipElement { depth := 1 for { t, err := dec.Token() if err != nil { // An io.EOF here is actually an error. return "", err } switch t.(type) { case xml.StartElement: depth++ case xml.EndElement: depth-- } if depth == 0 { break } } } } } } return result, nil }
[ "func", "XMLToText", "(", "r", "io", ".", "Reader", ",", "breaks", "[", "]", "string", ",", "skip", "[", "]", "string", ",", "strict", "bool", ")", "(", "string", ",", "error", ")", "{", "var", "result", "string", "\n", "dec", ":=", "xml", ".", "...
// XMLToText converts XML to plain text given how to treat elements.
[ "XMLToText", "converts", "XML", "to", "plain", "text", "given", "how", "to", "treat", "elements", "." ]
eedabc494f8e97c31f94c70453273f16dbecbc6f
https://github.com/sajari/docconv/blob/eedabc494f8e97c31f94c70453273f16dbecbc6f/xml.go#L25-L74
train
sajari/docconv
xml.go
XMLToMap
func XMLToMap(r io.Reader) (map[string]string, error) { m := make(map[string]string) dec := xml.NewDecoder(r) var tagName string for { t, err := dec.Token() if err != nil { if err == io.EOF { break } return nil, err } switch v := t.(type) { case xml.StartElement: tagName = string(v.Name.Local) case xml.CharData: m[tagName] = string(v) } } return m, nil }
go
func XMLToMap(r io.Reader) (map[string]string, error) { m := make(map[string]string) dec := xml.NewDecoder(r) var tagName string for { t, err := dec.Token() if err != nil { if err == io.EOF { break } return nil, err } switch v := t.(type) { case xml.StartElement: tagName = string(v.Name.Local) case xml.CharData: m[tagName] = string(v) } } return m, nil }
[ "func", "XMLToMap", "(", "r", "io", ".", "Reader", ")", "(", "map", "[", "string", "]", "string", ",", "error", ")", "{", "m", ":=", "make", "(", "map", "[", "string", "]", "string", ")", "\n", "dec", ":=", "xml", ".", "NewDecoder", "(", "r", "...
// XMLToMap converts XML to a nested string map.
[ "XMLToMap", "converts", "XML", "to", "a", "nested", "string", "map", "." ]
eedabc494f8e97c31f94c70453273f16dbecbc6f
https://github.com/sajari/docconv/blob/eedabc494f8e97c31f94c70453273f16dbecbc6f/xml.go#L77-L98
train
go-pg/pg
orm/delete.go
ForceDelete
func ForceDelete(db DB, model interface{}) error { res, err := NewQuery(db, model).WherePK().ForceDelete() if err != nil { return err } return internal.AssertOneRow(res.RowsAffected()) }
go
func ForceDelete(db DB, model interface{}) error { res, err := NewQuery(db, model).WherePK().ForceDelete() if err != nil { return err } return internal.AssertOneRow(res.RowsAffected()) }
[ "func", "ForceDelete", "(", "db", "DB", ",", "model", "interface", "{", "}", ")", "error", "{", "res", ",", "err", ":=", "NewQuery", "(", "db", ",", "model", ")", ".", "WherePK", "(", ")", ".", "ForceDelete", "(", ")", "\n", "if", "err", "!=", "n...
// ForceDelete force deletes a given model from the db
[ "ForceDelete", "force", "deletes", "a", "given", "model", "from", "the", "db" ]
9ab5ba23b6047052b91007b7041d9216025219a8
https://github.com/go-pg/pg/blob/9ab5ba23b6047052b91007b7041d9216025219a8/orm/delete.go#L17-L23
train
go-pg/pg
urlvalues/decode.go
Decode
func Decode(strct interface{}, values Values) error { v := reflect.Indirect(reflect.ValueOf(strct)) meta := structfilter.GetStruct(v.Type()) for name, values := range values { name = strings.TrimPrefix(name, ":") name = strings.TrimSuffix(name, "[]") field := meta.Field(name) if field != nil && !field.NoDecode() { err := field.Scan(field.Value(v), values) if err != nil { return err } } } return nil }
go
func Decode(strct interface{}, values Values) error { v := reflect.Indirect(reflect.ValueOf(strct)) meta := structfilter.GetStruct(v.Type()) for name, values := range values { name = strings.TrimPrefix(name, ":") name = strings.TrimSuffix(name, "[]") field := meta.Field(name) if field != nil && !field.NoDecode() { err := field.Scan(field.Value(v), values) if err != nil { return err } } } return nil }
[ "func", "Decode", "(", "strct", "interface", "{", "}", ",", "values", "Values", ")", "error", "{", "v", ":=", "reflect", ".", "Indirect", "(", "reflect", ".", "ValueOf", "(", "strct", ")", ")", "\n", "meta", ":=", "structfilter", ".", "GetStruct", "(",...
// Decode decodes url values into the struct.
[ "Decode", "decodes", "url", "values", "into", "the", "struct", "." ]
9ab5ba23b6047052b91007b7041d9216025219a8
https://github.com/go-pg/pg/blob/9ab5ba23b6047052b91007b7041d9216025219a8/urlvalues/decode.go#L11-L29
train
go-pg/pg
options.go
ParseURL
func ParseURL(sURL string) (*Options, error) { parsedURL, err := url.Parse(sURL) if err != nil { return nil, err } // scheme if parsedURL.Scheme != "postgres" && parsedURL.Scheme != "postgresql" { return nil, errors.New("pg: invalid scheme: " + parsedURL.Scheme) } // host and port options := &Options{ Addr: parsedURL.Host, } if !strings.Contains(options.Addr, ":") { options.Addr += ":5432" } // username and password if parsedURL.User != nil { options.User = parsedURL.User.Username() if password, ok := parsedURL.User.Password(); ok { options.Password = password } } if options.User == "" { options.User = "postgres" } // database if len(strings.Trim(parsedURL.Path, "/")) > 0 { options.Database = parsedURL.Path[1:] } else { return nil, errors.New("pg: database name not provided") } // ssl mode query, err := url.ParseQuery(parsedURL.RawQuery) if err != nil { return nil, err } if sslMode, ok := query["sslmode"]; ok && len(sslMode) > 0 { switch sslMode[0] { case "allow", "prefer", "require": options.TLSConfig = &tls.Config{InsecureSkipVerify: true} //nolint case "disable": options.TLSConfig = nil default: return nil, fmt.Errorf("pg: sslmode '%v' is not supported", sslMode[0]) } } else { options.TLSConfig = &tls.Config{InsecureSkipVerify: true} //nolint } delete(query, "sslmode") if appName, ok := query["application_name"]; ok && len(appName) > 0 { options.ApplicationName = appName[0] } delete(query, "application_name") if len(query) > 0 { return nil, errors.New("pg: options other than 'sslmode' and 'application_name' are not supported") } return options, nil }
go
func ParseURL(sURL string) (*Options, error) { parsedURL, err := url.Parse(sURL) if err != nil { return nil, err } // scheme if parsedURL.Scheme != "postgres" && parsedURL.Scheme != "postgresql" { return nil, errors.New("pg: invalid scheme: " + parsedURL.Scheme) } // host and port options := &Options{ Addr: parsedURL.Host, } if !strings.Contains(options.Addr, ":") { options.Addr += ":5432" } // username and password if parsedURL.User != nil { options.User = parsedURL.User.Username() if password, ok := parsedURL.User.Password(); ok { options.Password = password } } if options.User == "" { options.User = "postgres" } // database if len(strings.Trim(parsedURL.Path, "/")) > 0 { options.Database = parsedURL.Path[1:] } else { return nil, errors.New("pg: database name not provided") } // ssl mode query, err := url.ParseQuery(parsedURL.RawQuery) if err != nil { return nil, err } if sslMode, ok := query["sslmode"]; ok && len(sslMode) > 0 { switch sslMode[0] { case "allow", "prefer", "require": options.TLSConfig = &tls.Config{InsecureSkipVerify: true} //nolint case "disable": options.TLSConfig = nil default: return nil, fmt.Errorf("pg: sslmode '%v' is not supported", sslMode[0]) } } else { options.TLSConfig = &tls.Config{InsecureSkipVerify: true} //nolint } delete(query, "sslmode") if appName, ok := query["application_name"]; ok && len(appName) > 0 { options.ApplicationName = appName[0] } delete(query, "application_name") if len(query) > 0 { return nil, errors.New("pg: options other than 'sslmode' and 'application_name' are not supported") } return options, nil }
[ "func", "ParseURL", "(", "sURL", "string", ")", "(", "*", "Options", ",", "error", ")", "{", "parsedURL", ",", "err", ":=", "url", ".", "Parse", "(", "sURL", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", ...
// ParseURL parses an URL into options that can be used to connect to PostgreSQL.
[ "ParseURL", "parses", "an", "URL", "into", "options", "that", "can", "be", "used", "to", "connect", "to", "PostgreSQL", "." ]
9ab5ba23b6047052b91007b7041d9216025219a8
https://github.com/go-pg/pg/blob/9ab5ba23b6047052b91007b7041d9216025219a8/options.go#L143-L214
train
go-pg/pg
internal/underscore.go
Underscore
func Underscore(s string) string { r := make([]byte, 0, len(s)+5) for i := 0; i < len(s); i++ { c := s[i] if IsUpper(c) { if i > 0 && i+1 < len(s) && (IsLower(s[i-1]) || IsLower(s[i+1])) { r = append(r, '_', ToLower(c)) } else { r = append(r, ToLower(c)) } } else { r = append(r, c) } } return string(r) }
go
func Underscore(s string) string { r := make([]byte, 0, len(s)+5) for i := 0; i < len(s); i++ { c := s[i] if IsUpper(c) { if i > 0 && i+1 < len(s) && (IsLower(s[i-1]) || IsLower(s[i+1])) { r = append(r, '_', ToLower(c)) } else { r = append(r, ToLower(c)) } } else { r = append(r, c) } } return string(r) }
[ "func", "Underscore", "(", "s", "string", ")", "string", "{", "r", ":=", "make", "(", "[", "]", "byte", ",", "0", ",", "len", "(", "s", ")", "+", "5", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "s", ")", ";", "i", "++", ...
// Underscore converts "CamelCasedString" to "camel_cased_string".
[ "Underscore", "converts", "CamelCasedString", "to", "camel_cased_string", "." ]
9ab5ba23b6047052b91007b7041d9216025219a8
https://github.com/go-pg/pg/blob/9ab5ba23b6047052b91007b7041d9216025219a8/internal/underscore.go#L20-L35
train
go-pg/pg
tx.go
Begin
func (db *baseDB) Begin() (*Tx, error) { tx := &Tx{ db: db.withPool(pool.NewSingleConnPool(db.pool)), ctx: db.db.Context(), } err := tx.begin() if err != nil { tx.close() return nil, err } return tx, nil }
go
func (db *baseDB) Begin() (*Tx, error) { tx := &Tx{ db: db.withPool(pool.NewSingleConnPool(db.pool)), ctx: db.db.Context(), } err := tx.begin() if err != nil { tx.close() return nil, err } return tx, nil }
[ "func", "(", "db", "*", "baseDB", ")", "Begin", "(", ")", "(", "*", "Tx", ",", "error", ")", "{", "tx", ":=", "&", "Tx", "{", "db", ":", "db", ".", "withPool", "(", "pool", ".", "NewSingleConnPool", "(", "db", ".", "pool", ")", ")", ",", "ctx...
// Begin starts a transaction. Most callers should use RunInTransaction instead.
[ "Begin", "starts", "a", "transaction", ".", "Most", "callers", "should", "use", "RunInTransaction", "instead", "." ]
9ab5ba23b6047052b91007b7041d9216025219a8
https://github.com/go-pg/pg/blob/9ab5ba23b6047052b91007b7041d9216025219a8/tx.go#L38-L51
train
go-pg/pg
tx.go
RunInTransaction
func (db *baseDB) RunInTransaction(fn func(*Tx) error) error { tx, err := db.Begin() if err != nil { return err } return tx.RunInTransaction(fn) }
go
func (db *baseDB) RunInTransaction(fn func(*Tx) error) error { tx, err := db.Begin() if err != nil { return err } return tx.RunInTransaction(fn) }
[ "func", "(", "db", "*", "baseDB", ")", "RunInTransaction", "(", "fn", "func", "(", "*", "Tx", ")", "error", ")", "error", "{", "tx", ",", "err", ":=", "db", ".", "Begin", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}"...
// RunInTransaction runs a function in a transaction. If function // returns an error transaction is rollbacked, otherwise transaction // is committed.
[ "RunInTransaction", "runs", "a", "function", "in", "a", "transaction", ".", "If", "function", "returns", "an", "error", "transaction", "is", "rollbacked", "otherwise", "transaction", "is", "committed", "." ]
9ab5ba23b6047052b91007b7041d9216025219a8
https://github.com/go-pg/pg/blob/9ab5ba23b6047052b91007b7041d9216025219a8/tx.go#L56-L62
train
go-pg/pg
tx.go
RunInTransaction
func (tx *Tx) RunInTransaction(fn func(*Tx) error) error { defer func() { if err := recover(); err != nil { _ = tx.Rollback() panic(err) } }() if err := fn(tx); err != nil { _ = tx.Rollback() return err } return tx.Commit() }
go
func (tx *Tx) RunInTransaction(fn func(*Tx) error) error { defer func() { if err := recover(); err != nil { _ = tx.Rollback() panic(err) } }() if err := fn(tx); err != nil { _ = tx.Rollback() return err } return tx.Commit() }
[ "func", "(", "tx", "*", "Tx", ")", "RunInTransaction", "(", "fn", "func", "(", "*", "Tx", ")", "error", ")", "error", "{", "defer", "func", "(", ")", "{", "if", "err", ":=", "recover", "(", ")", ";", "err", "!=", "nil", "{", "_", "=", "tx", "...
// RunInTransaction runs a function in the transaction. If function // returns an error transaction is rollbacked, otherwise transaction // is committed.
[ "RunInTransaction", "runs", "a", "function", "in", "the", "transaction", ".", "If", "function", "returns", "an", "error", "transaction", "is", "rollbacked", "otherwise", "transaction", "is", "committed", "." ]
9ab5ba23b6047052b91007b7041d9216025219a8
https://github.com/go-pg/pg/blob/9ab5ba23b6047052b91007b7041d9216025219a8/tx.go#L72-L84
train
go-pg/pg
tx.go
Stmt
func (tx *Tx) Stmt(stmt *Stmt) *Stmt { stmt, err := tx.Prepare(stmt.q) if err != nil { return &Stmt{stickyErr: err} } return stmt }
go
func (tx *Tx) Stmt(stmt *Stmt) *Stmt { stmt, err := tx.Prepare(stmt.q) if err != nil { return &Stmt{stickyErr: err} } return stmt }
[ "func", "(", "tx", "*", "Tx", ")", "Stmt", "(", "stmt", "*", "Stmt", ")", "*", "Stmt", "{", "stmt", ",", "err", ":=", "tx", ".", "Prepare", "(", "stmt", ".", "q", ")", "\n", "if", "err", "!=", "nil", "{", "return", "&", "Stmt", "{", "stickyEr...
// Stmt returns a transaction-specific prepared statement // from an existing statement.
[ "Stmt", "returns", "a", "transaction", "-", "specific", "prepared", "statement", "from", "an", "existing", "statement", "." ]
9ab5ba23b6047052b91007b7041d9216025219a8
https://github.com/go-pg/pg/blob/9ab5ba23b6047052b91007b7041d9216025219a8/tx.go#L96-L102
train
go-pg/pg
tx.go
ExecContext
func (tx *Tx) ExecContext(c context.Context, query interface{}, params ...interface{}) (Result, error) { return tx.exec(c, query, params...) }
go
func (tx *Tx) ExecContext(c context.Context, query interface{}, params ...interface{}) (Result, error) { return tx.exec(c, query, params...) }
[ "func", "(", "tx", "*", "Tx", ")", "ExecContext", "(", "c", "context", ".", "Context", ",", "query", "interface", "{", "}", ",", "params", "...", "interface", "{", "}", ")", "(", "Result", ",", "error", ")", "{", "return", "tx", ".", "exec", "(", ...
// ExecContext acts like Exec but additionally receives a context
[ "ExecContext", "acts", "like", "Exec", "but", "additionally", "receives", "a", "context" ]
9ab5ba23b6047052b91007b7041d9216025219a8
https://github.com/go-pg/pg/blob/9ab5ba23b6047052b91007b7041d9216025219a8/tx.go#L129-L131
train
go-pg/pg
tx.go
Model
func (tx *Tx) Model(model ...interface{}) *orm.Query { return orm.NewQuery(tx, model...) }
go
func (tx *Tx) Model(model ...interface{}) *orm.Query { return orm.NewQuery(tx, model...) }
[ "func", "(", "tx", "*", "Tx", ")", "Model", "(", "model", "...", "interface", "{", "}", ")", "*", "orm", ".", "Query", "{", "return", "orm", ".", "NewQuery", "(", "tx", ",", "model", "...", ")", "\n", "}" ]
// Model is an alias for DB.Model.
[ "Model", "is", "an", "alias", "for", "DB", ".", "Model", "." ]
9ab5ba23b6047052b91007b7041d9216025219a8
https://github.com/go-pg/pg/blob/9ab5ba23b6047052b91007b7041d9216025219a8/tx.go#L243-L245
train
go-pg/pg
tx.go
ModelContext
func (tx *Tx) ModelContext(c context.Context, model ...interface{}) *orm.Query { return orm.NewQueryContext(c, tx, model...) }
go
func (tx *Tx) ModelContext(c context.Context, model ...interface{}) *orm.Query { return orm.NewQueryContext(c, tx, model...) }
[ "func", "(", "tx", "*", "Tx", ")", "ModelContext", "(", "c", "context", ".", "Context", ",", "model", "...", "interface", "{", "}", ")", "*", "orm", ".", "Query", "{", "return", "orm", ".", "NewQueryContext", "(", "c", ",", "tx", ",", "model", "......
// ModelContext acts like Model but additionally receives a context
[ "ModelContext", "acts", "like", "Model", "but", "additionally", "receives", "a", "context" ]
9ab5ba23b6047052b91007b7041d9216025219a8
https://github.com/go-pg/pg/blob/9ab5ba23b6047052b91007b7041d9216025219a8/tx.go#L248-L250
train
go-pg/pg
tx.go
CreateTable
func (tx *Tx) CreateTable(model interface{}, opt *orm.CreateTableOptions) error { return orm.CreateTable(tx, model, opt) }
go
func (tx *Tx) CreateTable(model interface{}, opt *orm.CreateTableOptions) error { return orm.CreateTable(tx, model, opt) }
[ "func", "(", "tx", "*", "Tx", ")", "CreateTable", "(", "model", "interface", "{", "}", ",", "opt", "*", "orm", ".", "CreateTableOptions", ")", "error", "{", "return", "orm", ".", "CreateTable", "(", "tx", ",", "model", ",", "opt", ")", "\n", "}" ]
// CreateTable is an alias for DB.CreateTable.
[ "CreateTable", "is", "an", "alias", "for", "DB", ".", "CreateTable", "." ]
9ab5ba23b6047052b91007b7041d9216025219a8
https://github.com/go-pg/pg/blob/9ab5ba23b6047052b91007b7041d9216025219a8/tx.go#L278-L280
train
go-pg/pg
tx.go
DropTable
func (tx *Tx) DropTable(model interface{}, opt *orm.DropTableOptions) error { return orm.DropTable(tx, model, opt) }
go
func (tx *Tx) DropTable(model interface{}, opt *orm.DropTableOptions) error { return orm.DropTable(tx, model, opt) }
[ "func", "(", "tx", "*", "Tx", ")", "DropTable", "(", "model", "interface", "{", "}", ",", "opt", "*", "orm", ".", "DropTableOptions", ")", "error", "{", "return", "orm", ".", "DropTable", "(", "tx", ",", "model", ",", "opt", ")", "\n", "}" ]
// DropTable is an alias for DB.DropTable.
[ "DropTable", "is", "an", "alias", "for", "DB", ".", "DropTable", "." ]
9ab5ba23b6047052b91007b7041d9216025219a8
https://github.com/go-pg/pg/blob/9ab5ba23b6047052b91007b7041d9216025219a8/tx.go#L283-L285
train
go-pg/pg
tx.go
CopyFrom
func (tx *Tx) CopyFrom(r io.Reader, query interface{}, params ...interface{}) (res Result, err error) { err = tx.withConn(context.TODO(), func(cn *pool.Conn) error { res, err = tx.db.copyFrom(cn, r, query, params...) return err }) return res, err }
go
func (tx *Tx) CopyFrom(r io.Reader, query interface{}, params ...interface{}) (res Result, err error) { err = tx.withConn(context.TODO(), func(cn *pool.Conn) error { res, err = tx.db.copyFrom(cn, r, query, params...) return err }) return res, err }
[ "func", "(", "tx", "*", "Tx", ")", "CopyFrom", "(", "r", "io", ".", "Reader", ",", "query", "interface", "{", "}", ",", "params", "...", "interface", "{", "}", ")", "(", "res", "Result", ",", "err", "error", ")", "{", "err", "=", "tx", ".", "wi...
// CopyFrom is an alias for DB.CopyFrom.
[ "CopyFrom", "is", "an", "alias", "for", "DB", ".", "CopyFrom", "." ]
9ab5ba23b6047052b91007b7041d9216025219a8
https://github.com/go-pg/pg/blob/9ab5ba23b6047052b91007b7041d9216025219a8/tx.go#L288-L294
train
go-pg/pg
tx.go
CopyTo
func (tx *Tx) CopyTo(w io.Writer, query interface{}, params ...interface{}) (res Result, err error) { err = tx.withConn(context.TODO(), func(cn *pool.Conn) error { res, err = tx.db.copyTo(cn, w, query, params...) return err }) return res, err }
go
func (tx *Tx) CopyTo(w io.Writer, query interface{}, params ...interface{}) (res Result, err error) { err = tx.withConn(context.TODO(), func(cn *pool.Conn) error { res, err = tx.db.copyTo(cn, w, query, params...) return err }) return res, err }
[ "func", "(", "tx", "*", "Tx", ")", "CopyTo", "(", "w", "io", ".", "Writer", ",", "query", "interface", "{", "}", ",", "params", "...", "interface", "{", "}", ")", "(", "res", "Result", ",", "err", "error", ")", "{", "err", "=", "tx", ".", "with...
// CopyTo is an alias for DB.CopyTo.
[ "CopyTo", "is", "an", "alias", "for", "DB", ".", "CopyTo", "." ]
9ab5ba23b6047052b91007b7041d9216025219a8
https://github.com/go-pg/pg/blob/9ab5ba23b6047052b91007b7041d9216025219a8/tx.go#L297-L303
train
go-pg/pg
tx.go
FormatQuery
func (tx *Tx) FormatQuery(dst []byte, query string, params ...interface{}) []byte { return tx.db.FormatQuery(dst, query, params...) }
go
func (tx *Tx) FormatQuery(dst []byte, query string, params ...interface{}) []byte { return tx.db.FormatQuery(dst, query, params...) }
[ "func", "(", "tx", "*", "Tx", ")", "FormatQuery", "(", "dst", "[", "]", "byte", ",", "query", "string", ",", "params", "...", "interface", "{", "}", ")", "[", "]", "byte", "{", "return", "tx", ".", "db", ".", "FormatQuery", "(", "dst", ",", "quer...
// FormatQuery is an alias for DB.FormatQuery
[ "FormatQuery", "is", "an", "alias", "for", "DB", ".", "FormatQuery" ]
9ab5ba23b6047052b91007b7041d9216025219a8
https://github.com/go-pg/pg/blob/9ab5ba23b6047052b91007b7041d9216025219a8/tx.go#L306-L308
train
go-pg/pg
hook.go
UnformattedQuery
func (ev *QueryEvent) UnformattedQuery() (string, error) { b, err := queryString(ev.Query) if err != nil { return "", err } return string(b), nil }
go
func (ev *QueryEvent) UnformattedQuery() (string, error) { b, err := queryString(ev.Query) if err != nil { return "", err } return string(b), nil }
[ "func", "(", "ev", "*", "QueryEvent", ")", "UnformattedQuery", "(", ")", "(", "string", ",", "error", ")", "{", "b", ",", "err", ":=", "queryString", "(", "ev", ".", "Query", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"\"", ",", "err", ...
// UnformattedQuery returns the unformatted query of a query event
[ "UnformattedQuery", "returns", "the", "unformatted", "query", "of", "a", "query", "event" ]
9ab5ba23b6047052b91007b7041d9216025219a8
https://github.com/go-pg/pg/blob/9ab5ba23b6047052b91007b7041d9216025219a8/hook.go#L36-L42
train
go-pg/pg
hook.go
FormattedQuery
func (ev *QueryEvent) FormattedQuery() (string, error) { b, err := appendQuery(ev.DB, nil, ev.Query, ev.Params...) if err != nil { return "", err } return string(b), nil }
go
func (ev *QueryEvent) FormattedQuery() (string, error) { b, err := appendQuery(ev.DB, nil, ev.Query, ev.Params...) if err != nil { return "", err } return string(b), nil }
[ "func", "(", "ev", "*", "QueryEvent", ")", "FormattedQuery", "(", ")", "(", "string", ",", "error", ")", "{", "b", ",", "err", ":=", "appendQuery", "(", "ev", ".", "DB", ",", "nil", ",", "ev", ".", "Query", ",", "ev", ".", "Params", "...", ")", ...
// FormattedQuery returns the formatted query of a query event
[ "FormattedQuery", "returns", "the", "formatted", "query", "of", "a", "query", "event" ]
9ab5ba23b6047052b91007b7041d9216025219a8
https://github.com/go-pg/pg/blob/9ab5ba23b6047052b91007b7041d9216025219a8/hook.go#L45-L51
train
go-pg/pg
hook.go
AddQueryHook
func (db *baseDB) AddQueryHook(hook QueryHook) { db.queryHooks = append(db.queryHooks, hook) }
go
func (db *baseDB) AddQueryHook(hook QueryHook) { db.queryHooks = append(db.queryHooks, hook) }
[ "func", "(", "db", "*", "baseDB", ")", "AddQueryHook", "(", "hook", "QueryHook", ")", "{", "db", ".", "queryHooks", "=", "append", "(", "db", ".", "queryHooks", ",", "hook", ")", "\n", "}" ]
// AddQueryHook adds a hook into query processing.
[ "AddQueryHook", "adds", "a", "hook", "into", "query", "processing", "." ]
9ab5ba23b6047052b91007b7041d9216025219a8
https://github.com/go-pg/pg/blob/9ab5ba23b6047052b91007b7041d9216025219a8/hook.go#L65-L67
train
go-pg/pg
listener.go
Close
func (ln *Listener) Close() error { ln.mu.Lock() defer ln.mu.Unlock() if ln.closed { return errListenerClosed } ln.closed = true close(ln.exit) return ln._closeTheCn(errListenerClosed) }
go
func (ln *Listener) Close() error { ln.mu.Lock() defer ln.mu.Unlock() if ln.closed { return errListenerClosed } ln.closed = true close(ln.exit) return ln._closeTheCn(errListenerClosed) }
[ "func", "(", "ln", "*", "Listener", ")", "Close", "(", ")", "error", "{", "ln", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "ln", ".", "mu", ".", "Unlock", "(", ")", "\n", "if", "ln", ".", "closed", "{", "return", "errListenerClosed", "\n", ...
// Close closes the listener, releasing any open resources.
[ "Close", "closes", "the", "listener", "releasing", "any", "open", "resources", "." ]
9ab5ba23b6047052b91007b7041d9216025219a8
https://github.com/go-pg/pg/blob/9ab5ba23b6047052b91007b7041d9216025219a8/listener.go#L132-L143
train
go-pg/pg
listener.go
Listen
func (ln *Listener) Listen(channels ...string) error { // Always append channels so DB.Listen works correctly. ln.channels = appendIfNotExists(ln.channels, channels...) cn, err := ln.conn() if err != nil { return err } err = ln.listen(cn, channels...) if err != nil { ln.releaseConn(cn, err, false) return err } return nil }
go
func (ln *Listener) Listen(channels ...string) error { // Always append channels so DB.Listen works correctly. ln.channels = appendIfNotExists(ln.channels, channels...) cn, err := ln.conn() if err != nil { return err } err = ln.listen(cn, channels...) if err != nil { ln.releaseConn(cn, err, false) return err } return nil }
[ "func", "(", "ln", "*", "Listener", ")", "Listen", "(", "channels", "...", "string", ")", "error", "{", "ln", ".", "channels", "=", "appendIfNotExists", "(", "ln", ".", "channels", ",", "channels", "...", ")", "\n", "cn", ",", "err", ":=", "ln", ".",...
// Listen starts listening for notifications on channels.
[ "Listen", "starts", "listening", "for", "notifications", "on", "channels", "." ]
9ab5ba23b6047052b91007b7041d9216025219a8
https://github.com/go-pg/pg/blob/9ab5ba23b6047052b91007b7041d9216025219a8/listener.go#L146-L162
train
go-pg/pg
listener.go
Receive
func (ln *Listener) Receive() (channel string, payload string, err error) { return ln.ReceiveTimeout(0) }
go
func (ln *Listener) Receive() (channel string, payload string, err error) { return ln.ReceiveTimeout(0) }
[ "func", "(", "ln", "*", "Listener", ")", "Receive", "(", ")", "(", "channel", "string", ",", "payload", "string", ",", "err", "error", ")", "{", "return", "ln", ".", "ReceiveTimeout", "(", "0", ")", "\n", "}" ]
// Receive indefinitely waits for a notification. This is low-level API // and in most cases Channel should be used instead.
[ "Receive", "indefinitely", "waits", "for", "a", "notification", ".", "This", "is", "low", "-", "level", "API", "and", "in", "most", "cases", "Channel", "should", "be", "used", "instead", "." ]
9ab5ba23b6047052b91007b7041d9216025219a8
https://github.com/go-pg/pg/blob/9ab5ba23b6047052b91007b7041d9216025219a8/listener.go#L179-L181
train
go-pg/pg
listener.go
ReceiveTimeout
func (ln *Listener) ReceiveTimeout(timeout time.Duration) (channel, payload string, err error) { cn, err := ln.conn() if err != nil { return "", "", err } err = cn.WithReader(timeout, func(rd *internal.BufReader) error { channel, payload, err = readNotification(rd) return err }) if err != nil { ln.releaseConn(cn, err, timeout > 0) return "", "", err } return channel, payload, nil }
go
func (ln *Listener) ReceiveTimeout(timeout time.Duration) (channel, payload string, err error) { cn, err := ln.conn() if err != nil { return "", "", err } err = cn.WithReader(timeout, func(rd *internal.BufReader) error { channel, payload, err = readNotification(rd) return err }) if err != nil { ln.releaseConn(cn, err, timeout > 0) return "", "", err } return channel, payload, nil }
[ "func", "(", "ln", "*", "Listener", ")", "ReceiveTimeout", "(", "timeout", "time", ".", "Duration", ")", "(", "channel", ",", "payload", "string", ",", "err", "error", ")", "{", "cn", ",", "err", ":=", "ln", ".", "conn", "(", ")", "\n", "if", "err"...
// ReceiveTimeout waits for a notification until timeout is reached. // This is low-level API and in most cases Channel should be used instead.
[ "ReceiveTimeout", "waits", "for", "a", "notification", "until", "timeout", "is", "reached", ".", "This", "is", "low", "-", "level", "API", "and", "in", "most", "cases", "Channel", "should", "be", "used", "instead", "." ]
9ab5ba23b6047052b91007b7041d9216025219a8
https://github.com/go-pg/pg/blob/9ab5ba23b6047052b91007b7041d9216025219a8/listener.go#L185-L201
train
go-pg/pg
messages.go
writeBindExecuteMsg
func writeBindExecuteMsg(buf *pool.WriteBuffer, name string, params ...interface{}) error { buf.StartMessage(bindMsg) buf.WriteString("") buf.WriteString(name) buf.WriteInt16(0) buf.WriteInt16(int16(len(params))) for _, param := range params { buf.StartParam() bytes := types.Append(buf.Bytes, param, 0) if bytes != nil { buf.Bytes = bytes buf.FinishParam() } else { buf.FinishNullParam() } } buf.WriteInt16(0) buf.FinishMessage() buf.StartMessage(executeMsg) buf.WriteString("") buf.WriteInt32(0) buf.FinishMessage() writeSyncMsg(buf) return nil }
go
func writeBindExecuteMsg(buf *pool.WriteBuffer, name string, params ...interface{}) error { buf.StartMessage(bindMsg) buf.WriteString("") buf.WriteString(name) buf.WriteInt16(0) buf.WriteInt16(int16(len(params))) for _, param := range params { buf.StartParam() bytes := types.Append(buf.Bytes, param, 0) if bytes != nil { buf.Bytes = bytes buf.FinishParam() } else { buf.FinishNullParam() } } buf.WriteInt16(0) buf.FinishMessage() buf.StartMessage(executeMsg) buf.WriteString("") buf.WriteInt32(0) buf.FinishMessage() writeSyncMsg(buf) return nil }
[ "func", "writeBindExecuteMsg", "(", "buf", "*", "pool", ".", "WriteBuffer", ",", "name", "string", ",", "params", "...", "interface", "{", "}", ")", "error", "{", "buf", ".", "StartMessage", "(", "bindMsg", ")", "\n", "buf", ".", "WriteString", "(", "\"\...
// Writes BIND, EXECUTE and SYNC messages.
[ "Writes", "BIND", "EXECUTE", "and", "SYNC", "messages", "." ]
9ab5ba23b6047052b91007b7041d9216025219a8
https://github.com/go-pg/pg/blob/9ab5ba23b6047052b91007b7041d9216025219a8/messages.go#L535-L562
train
go-pg/pg
stmt.go
Exec
func (stmt *Stmt) Exec(params ...interface{}) (Result, error) { return stmt.exec(context.TODO(), params...) }
go
func (stmt *Stmt) Exec(params ...interface{}) (Result, error) { return stmt.exec(context.TODO(), params...) }
[ "func", "(", "stmt", "*", "Stmt", ")", "Exec", "(", "params", "...", "interface", "{", "}", ")", "(", "Result", ",", "error", ")", "{", "return", "stmt", ".", "exec", "(", "context", ".", "TODO", "(", ")", ",", "params", "...", ")", "\n", "}" ]
// Exec executes a prepared statement with the given parameters.
[ "Exec", "executes", "a", "prepared", "statement", "with", "the", "given", "parameters", "." ]
9ab5ba23b6047052b91007b7041d9216025219a8
https://github.com/go-pg/pg/blob/9ab5ba23b6047052b91007b7041d9216025219a8/stmt.go#L78-L80
train
go-pg/pg
stmt.go
ExecContext
func (stmt *Stmt) ExecContext(c context.Context, params ...interface{}) (Result, error) { return stmt.exec(c, params...) }
go
func (stmt *Stmt) ExecContext(c context.Context, params ...interface{}) (Result, error) { return stmt.exec(c, params...) }
[ "func", "(", "stmt", "*", "Stmt", ")", "ExecContext", "(", "c", "context", ".", "Context", ",", "params", "...", "interface", "{", "}", ")", "(", "Result", ",", "error", ")", "{", "return", "stmt", ".", "exec", "(", "c", ",", "params", "...", ")", ...
// ExecContext executes a prepared statement with the given parameters.
[ "ExecContext", "executes", "a", "prepared", "statement", "with", "the", "given", "parameters", "." ]
9ab5ba23b6047052b91007b7041d9216025219a8
https://github.com/go-pg/pg/blob/9ab5ba23b6047052b91007b7041d9216025219a8/stmt.go#L83-L85
train
go-pg/pg
stmt.go
Query
func (stmt *Stmt) Query(model interface{}, params ...interface{}) (Result, error) { return stmt.query(context.TODO(), model, params...) }
go
func (stmt *Stmt) Query(model interface{}, params ...interface{}) (Result, error) { return stmt.query(context.TODO(), model, params...) }
[ "func", "(", "stmt", "*", "Stmt", ")", "Query", "(", "model", "interface", "{", "}", ",", "params", "...", "interface", "{", "}", ")", "(", "Result", ",", "error", ")", "{", "return", "stmt", ".", "query", "(", "context", ".", "TODO", "(", ")", "...
// Query executes a prepared query statement with the given parameters.
[ "Query", "executes", "a", "prepared", "query", "statement", "with", "the", "given", "parameters", "." ]
9ab5ba23b6047052b91007b7041d9216025219a8
https://github.com/go-pg/pg/blob/9ab5ba23b6047052b91007b7041d9216025219a8/stmt.go#L135-L137
train
go-pg/pg
base.go
Exec
func (db *baseDB) Exec(query interface{}, params ...interface{}) (res Result, err error) { return db.exec(context.TODO(), query, params...) }
go
func (db *baseDB) Exec(query interface{}, params ...interface{}) (res Result, err error) { return db.exec(context.TODO(), query, params...) }
[ "func", "(", "db", "*", "baseDB", ")", "Exec", "(", "query", "interface", "{", "}", ",", "params", "...", "interface", "{", "}", ")", "(", "res", "Result", ",", "err", "error", ")", "{", "return", "db", ".", "exec", "(", "context", ".", "TODO", "...
// Exec executes a query ignoring returned rows. The params are for any // placeholders in the query.
[ "Exec", "executes", "a", "query", "ignoring", "returned", "rows", ".", "The", "params", "are", "for", "any", "placeholders", "in", "the", "query", "." ]
9ab5ba23b6047052b91007b7041d9216025219a8
https://github.com/go-pg/pg/blob/9ab5ba23b6047052b91007b7041d9216025219a8/base.go#L186-L188
train
go-pg/pg
base.go
Query
func (db *baseDB) Query(model, query interface{}, params ...interface{}) (res Result, err error) { return db.query(context.TODO(), model, query, params...) }
go
func (db *baseDB) Query(model, query interface{}, params ...interface{}) (res Result, err error) { return db.query(context.TODO(), model, query, params...) }
[ "func", "(", "db", "*", "baseDB", ")", "Query", "(", "model", ",", "query", "interface", "{", "}", ",", "params", "...", "interface", "{", "}", ")", "(", "res", "Result", ",", "err", "error", ")", "{", "return", "db", ".", "query", "(", "context", ...
// Query executes a query that returns rows, typically a SELECT. // The params are for any placeholders in the query.
[ "Query", "executes", "a", "query", "that", "returns", "rows", "typically", "a", "SELECT", ".", "The", "params", "are", "for", "any", "placeholders", "in", "the", "query", "." ]
9ab5ba23b6047052b91007b7041d9216025219a8
https://github.com/go-pg/pg/blob/9ab5ba23b6047052b91007b7041d9216025219a8/base.go#L239-L241
train
go-pg/pg
base.go
Model
func (db *baseDB) Model(model ...interface{}) *orm.Query { return orm.NewQuery(db.db, model...) }
go
func (db *baseDB) Model(model ...interface{}) *orm.Query { return orm.NewQuery(db.db, model...) }
[ "func", "(", "db", "*", "baseDB", ")", "Model", "(", "model", "...", "interface", "{", "}", ")", "*", "orm", ".", "Query", "{", "return", "orm", ".", "NewQuery", "(", "db", ".", "db", ",", "model", "...", ")", "\n", "}" ]
// Model returns new query for the model.
[ "Model", "returns", "new", "query", "for", "the", "model", "." ]
9ab5ba23b6047052b91007b7041d9216025219a8
https://github.com/go-pg/pg/blob/9ab5ba23b6047052b91007b7041d9216025219a8/base.go#L389-L391
train
go-pg/pg
base.go
Select
func (db *baseDB) Select(model interface{}) error { return orm.Select(db.db, model) }
go
func (db *baseDB) Select(model interface{}) error { return orm.Select(db.db, model) }
[ "func", "(", "db", "*", "baseDB", ")", "Select", "(", "model", "interface", "{", "}", ")", "error", "{", "return", "orm", ".", "Select", "(", "db", ".", "db", ",", "model", ")", "\n", "}" ]
// Select selects the model by primary key.
[ "Select", "selects", "the", "model", "by", "primary", "key", "." ]
9ab5ba23b6047052b91007b7041d9216025219a8
https://github.com/go-pg/pg/blob/9ab5ba23b6047052b91007b7041d9216025219a8/base.go#L398-L400
train
go-pg/pg
base.go
Insert
func (db *baseDB) Insert(model ...interface{}) error { return orm.Insert(db.db, model...) }
go
func (db *baseDB) Insert(model ...interface{}) error { return orm.Insert(db.db, model...) }
[ "func", "(", "db", "*", "baseDB", ")", "Insert", "(", "model", "...", "interface", "{", "}", ")", "error", "{", "return", "orm", ".", "Insert", "(", "db", ".", "db", ",", "model", "...", ")", "\n", "}" ]
// Insert inserts the model updating primary keys if they are empty.
[ "Insert", "inserts", "the", "model", "updating", "primary", "keys", "if", "they", "are", "empty", "." ]
9ab5ba23b6047052b91007b7041d9216025219a8
https://github.com/go-pg/pg/blob/9ab5ba23b6047052b91007b7041d9216025219a8/base.go#L403-L405
train
go-pg/pg
base.go
Update
func (db *baseDB) Update(model interface{}) error { return orm.Update(db.db, model) }
go
func (db *baseDB) Update(model interface{}) error { return orm.Update(db.db, model) }
[ "func", "(", "db", "*", "baseDB", ")", "Update", "(", "model", "interface", "{", "}", ")", "error", "{", "return", "orm", ".", "Update", "(", "db", ".", "db", ",", "model", ")", "\n", "}" ]
// Update updates the model by primary key.
[ "Update", "updates", "the", "model", "by", "primary", "key", "." ]
9ab5ba23b6047052b91007b7041d9216025219a8
https://github.com/go-pg/pg/blob/9ab5ba23b6047052b91007b7041d9216025219a8/base.go#L408-L410
train
go-pg/pg
base.go
Delete
func (db *baseDB) Delete(model interface{}) error { return orm.Delete(db.db, model) }
go
func (db *baseDB) Delete(model interface{}) error { return orm.Delete(db.db, model) }
[ "func", "(", "db", "*", "baseDB", ")", "Delete", "(", "model", "interface", "{", "}", ")", "error", "{", "return", "orm", ".", "Delete", "(", "db", ".", "db", ",", "model", ")", "\n", "}" ]
// Delete deletes the model by primary key.
[ "Delete", "deletes", "the", "model", "by", "primary", "key", "." ]
9ab5ba23b6047052b91007b7041d9216025219a8
https://github.com/go-pg/pg/blob/9ab5ba23b6047052b91007b7041d9216025219a8/base.go#L413-L415
train
go-pg/pg
base.go
DropTable
func (db *baseDB) DropTable(model interface{}, opt *orm.DropTableOptions) error { return orm.DropTable(db.db, model, opt) }
go
func (db *baseDB) DropTable(model interface{}, opt *orm.DropTableOptions) error { return orm.DropTable(db.db, model, opt) }
[ "func", "(", "db", "*", "baseDB", ")", "DropTable", "(", "model", "interface", "{", "}", ",", "opt", "*", "orm", ".", "DropTableOptions", ")", "error", "{", "return", "orm", ".", "DropTable", "(", "db", ".", "db", ",", "model", ",", "opt", ")", "\n...
// DropTable drops table for the model.
[ "DropTable", "drops", "table", "for", "the", "model", "." ]
9ab5ba23b6047052b91007b7041d9216025219a8
https://github.com/go-pg/pg/blob/9ab5ba23b6047052b91007b7041d9216025219a8/base.go#L431-L433
train
go-pg/pg
pg.go
ModelContext
func ModelContext(c context.Context, model ...interface{}) *orm.Query { return orm.NewQueryContext(c, nil, model...) }
go
func ModelContext(c context.Context, model ...interface{}) *orm.Query { return orm.NewQueryContext(c, nil, model...) }
[ "func", "ModelContext", "(", "c", "context", ".", "Context", ",", "model", "...", "interface", "{", "}", ")", "*", "orm", ".", "Query", "{", "return", "orm", ".", "NewQueryContext", "(", "c", ",", "nil", ",", "model", "...", ")", "\n", "}" ]
// ModelContext returns a new query for the optional model with a context
[ "ModelContext", "returns", "a", "new", "query", "for", "the", "optional", "model", "with", "a", "context" ]
9ab5ba23b6047052b91007b7041d9216025219a8
https://github.com/go-pg/pg/blob/9ab5ba23b6047052b91007b7041d9216025219a8/pg.go#L33-L35
train
go-pg/pg
pg.go
Q
func Q(query string, params ...interface{}) types.ValueAppender { return orm.Q(query, params...) }
go
func Q(query string, params ...interface{}) types.ValueAppender { return orm.Q(query, params...) }
[ "func", "Q", "(", "query", "string", ",", "params", "...", "interface", "{", "}", ")", "types", ".", "ValueAppender", "{", "return", "orm", ".", "Q", "(", "query", ",", "params", "...", ")", "\n", "}" ]
// Q replaces any placeholders found in the query.
[ "Q", "replaces", "any", "placeholders", "found", "in", "the", "query", "." ]
9ab5ba23b6047052b91007b7041d9216025219a8
https://github.com/go-pg/pg/blob/9ab5ba23b6047052b91007b7041d9216025219a8/pg.go#L44-L46
train
go-pg/pg
pg.go
Init
func (strings *Strings) Init() error { if s := *strings; len(s) > 0 { *strings = s[:0] } return nil }
go
func (strings *Strings) Init() error { if s := *strings; len(s) > 0 { *strings = s[:0] } return nil }
[ "func", "(", "strings", "*", "Strings", ")", "Init", "(", ")", "error", "{", "if", "s", ":=", "*", "strings", ";", "len", "(", "s", ")", ">", "0", "{", "*", "strings", "=", "s", "[", ":", "0", "]", "\n", "}", "\n", "return", "nil", "\n", "}...
// Init initializes the Strings slice
[ "Init", "initializes", "the", "Strings", "slice" ]
9ab5ba23b6047052b91007b7041d9216025219a8
https://github.com/go-pg/pg/blob/9ab5ba23b6047052b91007b7041d9216025219a8/pg.go#L113-L118
train
go-pg/pg
pg.go
ScanColumn
func (strings *Strings) ScanColumn(colIdx int, _ string, rd types.Reader, n int) error { b := make([]byte, n) _, err := io.ReadFull(rd, b) if err != nil { return err } *strings = append(*strings, internal.BytesToString(b)) return nil }
go
func (strings *Strings) ScanColumn(colIdx int, _ string, rd types.Reader, n int) error { b := make([]byte, n) _, err := io.ReadFull(rd, b) if err != nil { return err } *strings = append(*strings, internal.BytesToString(b)) return nil }
[ "func", "(", "strings", "*", "Strings", ")", "ScanColumn", "(", "colIdx", "int", ",", "_", "string", ",", "rd", "types", ".", "Reader", ",", "n", "int", ")", "error", "{", "b", ":=", "make", "(", "[", "]", "byte", ",", "n", ")", "\n", "_", ",",...
// ScanColumn scans the columns and appends them to `strings`
[ "ScanColumn", "scans", "the", "columns", "and", "appends", "them", "to", "strings" ]
9ab5ba23b6047052b91007b7041d9216025219a8
https://github.com/go-pg/pg/blob/9ab5ba23b6047052b91007b7041d9216025219a8/pg.go#L131-L140
train
go-pg/pg
pg.go
AppendValue
func (strings Strings) AppendValue(dst []byte, quote int) []byte { if len(strings) == 0 { return dst } for _, s := range strings { dst = types.AppendString(dst, s, 1) dst = append(dst, ',') } dst = dst[:len(dst)-1] return dst }
go
func (strings Strings) AppendValue(dst []byte, quote int) []byte { if len(strings) == 0 { return dst } for _, s := range strings { dst = types.AppendString(dst, s, 1) dst = append(dst, ',') } dst = dst[:len(dst)-1] return dst }
[ "func", "(", "strings", "Strings", ")", "AppendValue", "(", "dst", "[", "]", "byte", ",", "quote", "int", ")", "[", "]", "byte", "{", "if", "len", "(", "strings", ")", "==", "0", "{", "return", "dst", "\n", "}", "\n", "for", "_", ",", "s", ":="...
// AppendValue appends the values from `strings` to the given byte slice
[ "AppendValue", "appends", "the", "values", "from", "strings", "to", "the", "given", "byte", "slice" ]
9ab5ba23b6047052b91007b7041d9216025219a8
https://github.com/go-pg/pg/blob/9ab5ba23b6047052b91007b7041d9216025219a8/pg.go#L143-L154
train
go-pg/pg
pg.go
Init
func (ints *Ints) Init() error { if s := *ints; len(s) > 0 { *ints = s[:0] } return nil }
go
func (ints *Ints) Init() error { if s := *ints; len(s) > 0 { *ints = s[:0] } return nil }
[ "func", "(", "ints", "*", "Ints", ")", "Init", "(", ")", "error", "{", "if", "s", ":=", "*", "ints", ";", "len", "(", "s", ")", ">", "0", "{", "*", "ints", "=", "s", "[", ":", "0", "]", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Init initializes the Int slice
[ "Init", "initializes", "the", "Int", "slice" ]
9ab5ba23b6047052b91007b7041d9216025219a8
https://github.com/go-pg/pg/blob/9ab5ba23b6047052b91007b7041d9216025219a8/pg.go#L165-L170
train
go-pg/pg
pg.go
ScanColumn
func (ints *Ints) ScanColumn(colIdx int, colName string, rd types.Reader, n int) error { num, err := types.ScanInt64(rd, n) if err != nil { return err } *ints = append(*ints, num) return nil }
go
func (ints *Ints) ScanColumn(colIdx int, colName string, rd types.Reader, n int) error { num, err := types.ScanInt64(rd, n) if err != nil { return err } *ints = append(*ints, num) return nil }
[ "func", "(", "ints", "*", "Ints", ")", "ScanColumn", "(", "colIdx", "int", ",", "colName", "string", ",", "rd", "types", ".", "Reader", ",", "n", "int", ")", "error", "{", "num", ",", "err", ":=", "types", ".", "ScanInt64", "(", "rd", ",", "n", "...
// ScanColumn scans the columns and appends them to `ints`
[ "ScanColumn", "scans", "the", "columns", "and", "appends", "them", "to", "ints" ]
9ab5ba23b6047052b91007b7041d9216025219a8
https://github.com/go-pg/pg/blob/9ab5ba23b6047052b91007b7041d9216025219a8/pg.go#L183-L191
train
go-pg/pg
pg.go
AppendValue
func (ints Ints) AppendValue(dst []byte, quote int) []byte { if len(ints) == 0 { return dst } for _, v := range ints { dst = strconv.AppendInt(dst, v, 10) dst = append(dst, ',') } dst = dst[:len(dst)-1] return dst }
go
func (ints Ints) AppendValue(dst []byte, quote int) []byte { if len(ints) == 0 { return dst } for _, v := range ints { dst = strconv.AppendInt(dst, v, 10) dst = append(dst, ',') } dst = dst[:len(dst)-1] return dst }
[ "func", "(", "ints", "Ints", ")", "AppendValue", "(", "dst", "[", "]", "byte", ",", "quote", "int", ")", "[", "]", "byte", "{", "if", "len", "(", "ints", ")", "==", "0", "{", "return", "dst", "\n", "}", "\n", "for", "_", ",", "v", ":=", "rang...
// AppendValue appends the values from `ints` to the given byte slice
[ "AppendValue", "appends", "the", "values", "from", "ints", "to", "the", "given", "byte", "slice" ]
9ab5ba23b6047052b91007b7041d9216025219a8
https://github.com/go-pg/pg/blob/9ab5ba23b6047052b91007b7041d9216025219a8/pg.go#L194-L205
train
go-pg/pg
pg.go
Init
func (set *IntSet) Init() error { if len(*set) > 0 { *set = make(map[int64]struct{}) } return nil }
go
func (set *IntSet) Init() error { if len(*set) > 0 { *set = make(map[int64]struct{}) } return nil }
[ "func", "(", "set", "*", "IntSet", ")", "Init", "(", ")", "error", "{", "if", "len", "(", "*", "set", ")", ">", "0", "{", "*", "set", "=", "make", "(", "map", "[", "int64", "]", "struct", "{", "}", ")", "\n", "}", "\n", "return", "nil", "\n...
// Init initializes the IntSet
[ "Init", "initializes", "the", "IntSet" ]
9ab5ba23b6047052b91007b7041d9216025219a8
https://github.com/go-pg/pg/blob/9ab5ba23b6047052b91007b7041d9216025219a8/pg.go#L215-L220
train
go-pg/pg
pg.go
ScanColumn
func (set *IntSet) ScanColumn(colIdx int, colName string, rd types.Reader, n int) error { num, err := types.ScanInt64(rd, n) if err != nil { return err } setVal := *set if setVal == nil { *set = make(IntSet) setVal = *set } setVal[num] = struct{}{} return nil }
go
func (set *IntSet) ScanColumn(colIdx int, colName string, rd types.Reader, n int) error { num, err := types.ScanInt64(rd, n) if err != nil { return err } setVal := *set if setVal == nil { *set = make(IntSet) setVal = *set } setVal[num] = struct{}{} return nil }
[ "func", "(", "set", "*", "IntSet", ")", "ScanColumn", "(", "colIdx", "int", ",", "colName", "string", ",", "rd", "types", ".", "Reader", ",", "n", "int", ")", "error", "{", "num", ",", "err", ":=", "types", ".", "ScanInt64", "(", "rd", ",", "n", ...
// ScanColumn scans the columns and appends them to `IntSet`
[ "ScanColumn", "scans", "the", "columns", "and", "appends", "them", "to", "IntSet" ]
9ab5ba23b6047052b91007b7041d9216025219a8
https://github.com/go-pg/pg/blob/9ab5ba23b6047052b91007b7041d9216025219a8/pg.go#L233-L247
train
go-pg/pg
internal/buf_reader.go
Buffered
func (b *BufReader) Buffered() int { d := b.w - b.r if b.available != -1 && d > b.available { return b.available } return d }
go
func (b *BufReader) Buffered() int { d := b.w - b.r if b.available != -1 && d > b.available { return b.available } return d }
[ "func", "(", "b", "*", "BufReader", ")", "Buffered", "(", ")", "int", "{", "d", ":=", "b", ".", "w", "-", "b", ".", "r", "\n", "if", "b", ".", "available", "!=", "-", "1", "&&", "d", ">", "b", ".", "available", "{", "return", "b", ".", "ava...
// Buffered returns the number of bytes that can be read from the current buffer.
[ "Buffered", "returns", "the", "number", "of", "bytes", "that", "can", "be", "read", "from", "the", "current", "buffer", "." ]
9ab5ba23b6047052b91007b7041d9216025219a8
https://github.com/go-pg/pg/blob/9ab5ba23b6047052b91007b7041d9216025219a8/internal/buf_reader.go#L68-L74
train
go-pg/pg
orm/query.go
New
func (q *Query) New() *Query { cp := &Query{ ctx: q.ctx, db: q.db, model: q.model, implicitModel: true, deleted: q.deleted, } return cp }
go
func (q *Query) New() *Query { cp := &Query{ ctx: q.ctx, db: q.db, model: q.model, implicitModel: true, deleted: q.deleted, } return cp }
[ "func", "(", "q", "*", "Query", ")", "New", "(", ")", "*", "Query", "{", "cp", ":=", "&", "Query", "{", "ctx", ":", "q", ".", "ctx", ",", "db", ":", "q", ".", "db", ",", "model", ":", "q", ".", "model", ",", "implicitModel", ":", "true", ",...
// New returns new zero Query binded to the current db.
[ "New", "returns", "new", "zero", "Query", "binded", "to", "the", "current", "db", "." ]
9ab5ba23b6047052b91007b7041d9216025219a8
https://github.com/go-pg/pg/blob/9ab5ba23b6047052b91007b7041d9216025219a8/orm/query.go#L68-L77
train
go-pg/pg
orm/query.go
Copy
func (q *Query) Copy() *Query { var modelValues map[string]*queryParamsAppender if len(q.modelValues) > 0 { modelValues = make(map[string]*queryParamsAppender, len(q.modelValues)) for k, v := range q.modelValues { modelValues[k] = v } } copy := &Query{ ctx: q.ctx, db: q.db, stickyErr: q.stickyErr, model: q.model, implicitModel: q.implicitModel, deleted: q.deleted, with: q.with[:len(q.with):len(q.with)], tables: q.tables[:len(q.tables):len(q.tables)], columns: q.columns[:len(q.columns):len(q.columns)], set: q.set[:len(q.set):len(q.set)], modelValues: modelValues, where: q.where[:len(q.where):len(q.where)], updWhere: q.updWhere[:len(q.updWhere):len(q.updWhere)], joins: q.joins[:len(q.joins):len(q.joins)], group: q.group[:len(q.group):len(q.group)], having: q.having[:len(q.having):len(q.having)], order: q.order[:len(q.order):len(q.order)], onConflict: q.onConflict, returning: q.returning[:len(q.returning):len(q.returning)], limit: q.limit, offset: q.offset, selFor: q.selFor, } return copy }
go
func (q *Query) Copy() *Query { var modelValues map[string]*queryParamsAppender if len(q.modelValues) > 0 { modelValues = make(map[string]*queryParamsAppender, len(q.modelValues)) for k, v := range q.modelValues { modelValues[k] = v } } copy := &Query{ ctx: q.ctx, db: q.db, stickyErr: q.stickyErr, model: q.model, implicitModel: q.implicitModel, deleted: q.deleted, with: q.with[:len(q.with):len(q.with)], tables: q.tables[:len(q.tables):len(q.tables)], columns: q.columns[:len(q.columns):len(q.columns)], set: q.set[:len(q.set):len(q.set)], modelValues: modelValues, where: q.where[:len(q.where):len(q.where)], updWhere: q.updWhere[:len(q.updWhere):len(q.updWhere)], joins: q.joins[:len(q.joins):len(q.joins)], group: q.group[:len(q.group):len(q.group)], having: q.having[:len(q.having):len(q.having)], order: q.order[:len(q.order):len(q.order)], onConflict: q.onConflict, returning: q.returning[:len(q.returning):len(q.returning)], limit: q.limit, offset: q.offset, selFor: q.selFor, } return copy }
[ "func", "(", "q", "*", "Query", ")", "Copy", "(", ")", "*", "Query", "{", "var", "modelValues", "map", "[", "string", "]", "*", "queryParamsAppender", "\n", "if", "len", "(", "q", ".", "modelValues", ")", ">", "0", "{", "modelValues", "=", "make", ...
// Copy returns copy of the Query.
[ "Copy", "returns", "copy", "of", "the", "Query", "." ]
9ab5ba23b6047052b91007b7041d9216025219a8
https://github.com/go-pg/pg/blob/9ab5ba23b6047052b91007b7041d9216025219a8/orm/query.go#L80-L117
train
go-pg/pg
orm/query.go
Deleted
func (q *Query) Deleted() *Query { if q.model != nil { if err := q.model.Table().mustSoftDelete(); err != nil { return q.err(err) } } q.deleted = true return q }
go
func (q *Query) Deleted() *Query { if q.model != nil { if err := q.model.Table().mustSoftDelete(); err != nil { return q.err(err) } } q.deleted = true return q }
[ "func", "(", "q", "*", "Query", ")", "Deleted", "(", ")", "*", "Query", "{", "if", "q", ".", "model", "!=", "nil", "{", "if", "err", ":=", "q", ".", "model", ".", "Table", "(", ")", ".", "mustSoftDelete", "(", ")", ";", "err", "!=", "nil", "{...
// Deleted adds `WHERE deleted_at IS NOT NULL` clause for soft deleted models.
[ "Deleted", "adds", "WHERE", "deleted_at", "IS", "NOT", "NULL", "clause", "for", "soft", "deleted", "models", "." ]
9ab5ba23b6047052b91007b7041d9216025219a8
https://github.com/go-pg/pg/blob/9ab5ba23b6047052b91007b7041d9216025219a8/orm/query.go#L165-L173
train
go-pg/pg
orm/query.go
With
func (q *Query) With(name string, subq *Query) *Query { return q._with(name, newSelectQuery(subq)) }
go
func (q *Query) With(name string, subq *Query) *Query { return q._with(name, newSelectQuery(subq)) }
[ "func", "(", "q", "*", "Query", ")", "With", "(", "name", "string", ",", "subq", "*", "Query", ")", "*", "Query", "{", "return", "q", ".", "_with", "(", "name", ",", "newSelectQuery", "(", "subq", ")", ")", "\n", "}" ]
// With adds subq as common table expression with the given name.
[ "With", "adds", "subq", "as", "common", "table", "expression", "with", "the", "given", "name", "." ]
9ab5ba23b6047052b91007b7041d9216025219a8
https://github.com/go-pg/pg/blob/9ab5ba23b6047052b91007b7041d9216025219a8/orm/query.go#L176-L178
train
go-pg/pg
orm/query.go
WrapWith
func (q *Query) WrapWith(name string) *Query { wrapper := q.New() wrapper.with = q.with q.with = nil wrapper = wrapper.With(name, q) return wrapper }
go
func (q *Query) WrapWith(name string) *Query { wrapper := q.New() wrapper.with = q.with q.with = nil wrapper = wrapper.With(name, q) return wrapper }
[ "func", "(", "q", "*", "Query", ")", "WrapWith", "(", "name", "string", ")", "*", "Query", "{", "wrapper", ":=", "q", ".", "New", "(", ")", "\n", "wrapper", ".", "with", "=", "q", ".", "with", "\n", "q", ".", "with", "=", "nil", "\n", "wrapper"...
// WrapWith creates new Query and adds to it current query as // common table expression with the given name.
[ "WrapWith", "creates", "new", "Query", "and", "adds", "to", "it", "current", "query", "as", "common", "table", "expression", "with", "the", "given", "name", "." ]
9ab5ba23b6047052b91007b7041d9216025219a8
https://github.com/go-pg/pg/blob/9ab5ba23b6047052b91007b7041d9216025219a8/orm/query.go#L194-L200
train
go-pg/pg
orm/query.go
ColumnExpr
func (q *Query) ColumnExpr(expr string, params ...interface{}) *Query { q.columns = append(q.columns, &queryParamsAppender{expr, params}) return q }
go
func (q *Query) ColumnExpr(expr string, params ...interface{}) *Query { q.columns = append(q.columns, &queryParamsAppender{expr, params}) return q }
[ "func", "(", "q", "*", "Query", ")", "ColumnExpr", "(", "expr", "string", ",", "params", "...", "interface", "{", "}", ")", "*", "Query", "{", "q", ".", "columns", "=", "append", "(", "q", ".", "columns", ",", "&", "queryParamsAppender", "{", "expr",...
// ColumnExpr adds column expression to the Query.
[ "ColumnExpr", "adds", "column", "expression", "to", "the", "Query", "." ]
9ab5ba23b6047052b91007b7041d9216025219a8
https://github.com/go-pg/pg/blob/9ab5ba23b6047052b91007b7041d9216025219a8/orm/query.go#L242-L245
train
go-pg/pg
orm/query.go
ExcludeColumn
func (q *Query) ExcludeColumn(columns ...string) *Query { if q.columns == nil { for _, f := range q.model.Table().Fields { q.columns = append(q.columns, fieldAppender{f.SQLName}) } } for _, col := range columns { if !q.excludeColumn(col) { return q.err(fmt.Errorf("pg: can't find column=%q", col)) } } return q }
go
func (q *Query) ExcludeColumn(columns ...string) *Query { if q.columns == nil { for _, f := range q.model.Table().Fields { q.columns = append(q.columns, fieldAppender{f.SQLName}) } } for _, col := range columns { if !q.excludeColumn(col) { return q.err(fmt.Errorf("pg: can't find column=%q", col)) } } return q }
[ "func", "(", "q", "*", "Query", ")", "ExcludeColumn", "(", "columns", "...", "string", ")", "*", "Query", "{", "if", "q", ".", "columns", "==", "nil", "{", "for", "_", ",", "f", ":=", "range", "q", ".", "model", ".", "Table", "(", ")", ".", "Fi...
// ExcludeColumn excludes a column from the list of to be selected columns.
[ "ExcludeColumn", "excludes", "a", "column", "from", "the", "list", "of", "to", "be", "selected", "columns", "." ]
9ab5ba23b6047052b91007b7041d9216025219a8
https://github.com/go-pg/pg/blob/9ab5ba23b6047052b91007b7041d9216025219a8/orm/query.go#L248-L261
train
go-pg/pg
orm/query.go
Value
func (q *Query) Value(column string, value string, params ...interface{}) *Query { if !q.hasModel() { q.err(errModelNil) return q } table := q.model.Table() if _, ok := table.FieldsMap[column]; !ok { q.err(fmt.Errorf("%s does not have column=%q", table, column)) return q } if q.modelValues == nil { q.modelValues = make(map[string]*queryParamsAppender) } q.modelValues[column] = &queryParamsAppender{value, params} return q }
go
func (q *Query) Value(column string, value string, params ...interface{}) *Query { if !q.hasModel() { q.err(errModelNil) return q } table := q.model.Table() if _, ok := table.FieldsMap[column]; !ok { q.err(fmt.Errorf("%s does not have column=%q", table, column)) return q } if q.modelValues == nil { q.modelValues = make(map[string]*queryParamsAppender) } q.modelValues[column] = &queryParamsAppender{value, params} return q }
[ "func", "(", "q", "*", "Query", ")", "Value", "(", "column", "string", ",", "value", "string", ",", "params", "...", "interface", "{", "}", ")", "*", "Query", "{", "if", "!", "q", ".", "hasModel", "(", ")", "{", "q", ".", "err", "(", "errModelNil...
// Value overwrites model value for the column in INSERT and UPDATE queries.
[ "Value", "overwrites", "model", "value", "for", "the", "column", "in", "INSERT", "and", "UPDATE", "queries", "." ]
9ab5ba23b6047052b91007b7041d9216025219a8
https://github.com/go-pg/pg/blob/9ab5ba23b6047052b91007b7041d9216025219a8/orm/query.go#L345-L362
train
go-pg/pg
orm/query.go
JoinOn
func (q *Query) JoinOn(condition string, params ...interface{}) *Query { if q.joinAppendOn == nil { q.err(errors.New("pg: no joins to apply JoinOn")) return q } q.joinAppendOn(&condAppender{ sep: " AND ", cond: condition, params: params, }) return q }
go
func (q *Query) JoinOn(condition string, params ...interface{}) *Query { if q.joinAppendOn == nil { q.err(errors.New("pg: no joins to apply JoinOn")) return q } q.joinAppendOn(&condAppender{ sep: " AND ", cond: condition, params: params, }) return q }
[ "func", "(", "q", "*", "Query", ")", "JoinOn", "(", "condition", "string", ",", "params", "...", "interface", "{", "}", ")", "*", "Query", "{", "if", "q", ".", "joinAppendOn", "==", "nil", "{", "q", ".", "err", "(", "errors", ".", "New", "(", "\"...
// JoinOn appends join condition to the last join.
[ "JoinOn", "appends", "join", "condition", "to", "the", "last", "join", "." ]
9ab5ba23b6047052b91007b7041d9216025219a8
https://github.com/go-pg/pg/blob/9ab5ba23b6047052b91007b7041d9216025219a8/orm/query.go#L506-L517
train
go-pg/pg
orm/query.go
Order
func (q *Query) Order(orders ...string) *Query { loop: for _, order := range orders { if order == "" { continue } ind := strings.Index(order, " ") if ind != -1 { field := order[:ind] sort := order[ind+1:] switch internal.UpperString(sort) { case "ASC", "DESC", "ASC NULLS FIRST", "DESC NULLS FIRST", "ASC NULLS LAST", "DESC NULLS LAST": q = q.OrderExpr("? ?", types.F(field), types.Q(sort)) continue loop } } q.order = append(q.order, fieldAppender{order}) } return q }
go
func (q *Query) Order(orders ...string) *Query { loop: for _, order := range orders { if order == "" { continue } ind := strings.Index(order, " ") if ind != -1 { field := order[:ind] sort := order[ind+1:] switch internal.UpperString(sort) { case "ASC", "DESC", "ASC NULLS FIRST", "DESC NULLS FIRST", "ASC NULLS LAST", "DESC NULLS LAST": q = q.OrderExpr("? ?", types.F(field), types.Q(sort)) continue loop } } q.order = append(q.order, fieldAppender{order}) } return q }
[ "func", "(", "q", "*", "Query", ")", "Order", "(", "orders", "...", "string", ")", "*", "Query", "{", "loop", ":", "for", "_", ",", "order", ":=", "range", "orders", "{", "if", "order", "==", "\"\"", "{", "continue", "\n", "}", "\n", "ind", ":=",...
// Order adds sort order to the Query quoting column name. Does not expand params like ?TableAlias etc. // OrderExpr can be used to bypass quoting restriction or for params expansion.
[ "Order", "adds", "sort", "order", "to", "the", "Query", "quoting", "column", "name", ".", "Does", "not", "expand", "params", "like", "?TableAlias", "etc", ".", "OrderExpr", "can", "be", "used", "to", "bypass", "quoting", "restriction", "or", "for", "params",...
9ab5ba23b6047052b91007b7041d9216025219a8
https://github.com/go-pg/pg/blob/9ab5ba23b6047052b91007b7041d9216025219a8/orm/query.go#L551-L572
train
go-pg/pg
orm/query.go
OrderExpr
func (q *Query) OrderExpr(order string, params ...interface{}) *Query { if order != "" { q.order = append(q.order, &queryParamsAppender{order, params}) } return q }
go
func (q *Query) OrderExpr(order string, params ...interface{}) *Query { if order != "" { q.order = append(q.order, &queryParamsAppender{order, params}) } return q }
[ "func", "(", "q", "*", "Query", ")", "OrderExpr", "(", "order", "string", ",", "params", "...", "interface", "{", "}", ")", "*", "Query", "{", "if", "order", "!=", "\"\"", "{", "q", ".", "order", "=", "append", "(", "q", ".", "order", ",", "&", ...
// Order adds sort order to the Query.
[ "Order", "adds", "sort", "order", "to", "the", "Query", "." ]
9ab5ba23b6047052b91007b7041d9216025219a8
https://github.com/go-pg/pg/blob/9ab5ba23b6047052b91007b7041d9216025219a8/orm/query.go#L575-L580
train
go-pg/pg
orm/query.go
Apply
func (q *Query) Apply(fn func(*Query) (*Query, error)) *Query { qq, err := fn(q) if err != nil { q.err(err) return q } return qq }
go
func (q *Query) Apply(fn func(*Query) (*Query, error)) *Query { qq, err := fn(q) if err != nil { q.err(err) return q } return qq }
[ "func", "(", "q", "*", "Query", ")", "Apply", "(", "fn", "func", "(", "*", "Query", ")", "(", "*", "Query", ",", "error", ")", ")", "*", "Query", "{", "qq", ",", "err", ":=", "fn", "(", "q", ")", "\n", "if", "err", "!=", "nil", "{", "q", ...
// Apply calls the fn passing the Query as an argument.
[ "Apply", "calls", "the", "fn", "passing", "the", "Query", "as", "an", "argument", "." ]
9ab5ba23b6047052b91007b7041d9216025219a8
https://github.com/go-pg/pg/blob/9ab5ba23b6047052b91007b7041d9216025219a8/orm/query.go#L613-L620
train
go-pg/pg
orm/query.go
Count
func (q *Query) Count() (int, error) { if q.stickyErr != nil { return 0, q.stickyErr } var count int _, err := q.db.QueryOneContext( q.ctx, Scan(&count), q.countSelectQuery("count(*)"), q.model) return count, err }
go
func (q *Query) Count() (int, error) { if q.stickyErr != nil { return 0, q.stickyErr } var count int _, err := q.db.QueryOneContext( q.ctx, Scan(&count), q.countSelectQuery("count(*)"), q.model) return count, err }
[ "func", "(", "q", "*", "Query", ")", "Count", "(", ")", "(", "int", ",", "error", ")", "{", "if", "q", ".", "stickyErr", "!=", "nil", "{", "return", "0", ",", "q", ".", "stickyErr", "\n", "}", "\n", "var", "count", "int", "\n", "_", ",", "err...
// Count returns number of rows matching the query using count aggregate function.
[ "Count", "returns", "number", "of", "rows", "matching", "the", "query", "using", "count", "aggregate", "function", "." ]
9ab5ba23b6047052b91007b7041d9216025219a8
https://github.com/go-pg/pg/blob/9ab5ba23b6047052b91007b7041d9216025219a8/orm/query.go#L623-L632
train
go-pg/pg
orm/query.go
Select
func (q *Query) Select(values ...interface{}) error { if q.stickyErr != nil { return q.stickyErr } model, err := q.newModel(values...) if err != nil { return err } q, err = model.BeforeSelectQuery(q.ctx, q.db, q) if err != nil { return err } res, err := q.query(model, newSelectQuery(q)) if err != nil { return err } if res.RowsReturned() > 0 { if q.model != nil { if err := q.selectJoins(q.model.GetJoins()); err != nil { return err } } if err := model.AfterSelect(q.ctx, q.db); err != nil { return err } } return nil }
go
func (q *Query) Select(values ...interface{}) error { if q.stickyErr != nil { return q.stickyErr } model, err := q.newModel(values...) if err != nil { return err } q, err = model.BeforeSelectQuery(q.ctx, q.db, q) if err != nil { return err } res, err := q.query(model, newSelectQuery(q)) if err != nil { return err } if res.RowsReturned() > 0 { if q.model != nil { if err := q.selectJoins(q.model.GetJoins()); err != nil { return err } } if err := model.AfterSelect(q.ctx, q.db); err != nil { return err } } return nil }
[ "func", "(", "q", "*", "Query", ")", "Select", "(", "values", "...", "interface", "{", "}", ")", "error", "{", "if", "q", ".", "stickyErr", "!=", "nil", "{", "return", "q", ".", "stickyErr", "\n", "}", "\n", "model", ",", "err", ":=", "q", ".", ...
// Select selects the model.
[ "Select", "selects", "the", "model", "." ]
9ab5ba23b6047052b91007b7041d9216025219a8
https://github.com/go-pg/pg/blob/9ab5ba23b6047052b91007b7041d9216025219a8/orm/query.go#L672-L704
train
go-pg/pg
orm/query.go
SelectAndCount
func (q *Query) SelectAndCount(values ...interface{}) (count int, firstErr error) { if q.stickyErr != nil { return 0, q.stickyErr } var wg sync.WaitGroup var mu sync.Mutex if q.limit >= 0 { wg.Add(1) go func() { defer wg.Done() err := q.Select(values...) if err != nil { mu.Lock() if firstErr == nil { firstErr = err } mu.Unlock() } }() } wg.Add(1) go func() { defer wg.Done() var err error count, err = q.Count() if err != nil { mu.Lock() if firstErr == nil { firstErr = err } mu.Unlock() } }() wg.Wait() return count, firstErr }
go
func (q *Query) SelectAndCount(values ...interface{}) (count int, firstErr error) { if q.stickyErr != nil { return 0, q.stickyErr } var wg sync.WaitGroup var mu sync.Mutex if q.limit >= 0 { wg.Add(1) go func() { defer wg.Done() err := q.Select(values...) if err != nil { mu.Lock() if firstErr == nil { firstErr = err } mu.Unlock() } }() } wg.Add(1) go func() { defer wg.Done() var err error count, err = q.Count() if err != nil { mu.Lock() if firstErr == nil { firstErr = err } mu.Unlock() } }() wg.Wait() return count, firstErr }
[ "func", "(", "q", "*", "Query", ")", "SelectAndCount", "(", "values", "...", "interface", "{", "}", ")", "(", "count", "int", ",", "firstErr", "error", ")", "{", "if", "q", ".", "stickyErr", "!=", "nil", "{", "return", "0", ",", "q", ".", "stickyEr...
// SelectAndCount runs Select and Count in two goroutines, // waits for them to finish and returns the result. If query limit is -1 // it does not select any data and only counts the results.
[ "SelectAndCount", "runs", "Select", "and", "Count", "in", "two", "goroutines", "waits", "for", "them", "to", "finish", "and", "returns", "the", "result", ".", "If", "query", "limit", "is", "-", "1", "it", "does", "not", "select", "any", "data", "and", "o...
9ab5ba23b6047052b91007b7041d9216025219a8
https://github.com/go-pg/pg/blob/9ab5ba23b6047052b91007b7041d9216025219a8/orm/query.go#L723-L762
train
go-pg/pg
orm/query.go
ForEach
func (q *Query) ForEach(fn interface{}) error { m := newFuncModel(fn) return q.Select(m) }
go
func (q *Query) ForEach(fn interface{}) error { m := newFuncModel(fn) return q.Select(m) }
[ "func", "(", "q", "*", "Query", ")", "ForEach", "(", "fn", "interface", "{", "}", ")", "error", "{", "m", ":=", "newFuncModel", "(", "fn", ")", "\n", "return", "q", ".", "Select", "(", "m", ")", "\n", "}" ]
// ForEach calls the function for each row returned by the query // without loading all rows into the memory. // Function accepts a struct, pointer to a struct, orm.Model, // or values for columns in a row. Function must return an error.
[ "ForEach", "calls", "the", "function", "for", "each", "row", "returned", "by", "the", "query", "without", "loading", "all", "rows", "into", "the", "memory", ".", "Function", "accepts", "a", "struct", "pointer", "to", "a", "struct", "orm", ".", "Model", "or...
9ab5ba23b6047052b91007b7041d9216025219a8
https://github.com/go-pg/pg/blob/9ab5ba23b6047052b91007b7041d9216025219a8/orm/query.go#L812-L815
train
go-pg/pg
orm/query.go
Insert
func (q *Query) Insert(values ...interface{}) (Result, error) { if q.stickyErr != nil { return nil, q.stickyErr } model, err := q.newModel(values...) if err != nil { return nil, err } if q.model != nil && q.model.Table().HasFlag(BeforeInsertHookFlag) { err = q.model.BeforeInsert(q.ctx, q.db) if err != nil { return nil, err } } query := newInsertQuery(q) res, err := q.returningQuery(model, query) if err != nil { return nil, err } if q.model != nil { err = q.model.AfterInsert(q.ctx, q.db) if err != nil { return nil, err } } return res, nil }
go
func (q *Query) Insert(values ...interface{}) (Result, error) { if q.stickyErr != nil { return nil, q.stickyErr } model, err := q.newModel(values...) if err != nil { return nil, err } if q.model != nil && q.model.Table().HasFlag(BeforeInsertHookFlag) { err = q.model.BeforeInsert(q.ctx, q.db) if err != nil { return nil, err } } query := newInsertQuery(q) res, err := q.returningQuery(model, query) if err != nil { return nil, err } if q.model != nil { err = q.model.AfterInsert(q.ctx, q.db) if err != nil { return nil, err } } return res, nil }
[ "func", "(", "q", "*", "Query", ")", "Insert", "(", "values", "...", "interface", "{", "}", ")", "(", "Result", ",", "error", ")", "{", "if", "q", ".", "stickyErr", "!=", "nil", "{", "return", "nil", ",", "q", ".", "stickyErr", "\n", "}", "\n", ...
// Insert inserts the model.
[ "Insert", "inserts", "the", "model", "." ]
9ab5ba23b6047052b91007b7041d9216025219a8
https://github.com/go-pg/pg/blob/9ab5ba23b6047052b91007b7041d9216025219a8/orm/query.go#L860-L891
train
go-pg/pg
orm/query.go
SelectOrInsert
func (q *Query) SelectOrInsert(values ...interface{}) (inserted bool, _ error) { if q.stickyErr != nil { return false, q.stickyErr } var insertq *Query var insertErr error for i := 0; i < 5; i++ { if i >= 2 { time.Sleep(internal.RetryBackoff(i-2, 250*time.Millisecond, 5*time.Second)) } err := q.Select(values...) if err == nil { return false, nil } if err != internal.ErrNoRows { return false, err } if insertq == nil { insertq = q if len(insertq.columns) > 0 { insertq = insertq.Copy() insertq.columns = nil } } res, err := insertq.Insert(values...) if err != nil { insertErr = err if err == internal.ErrNoRows { continue } if pgErr, ok := err.(internal.PGError); ok { if pgErr.IntegrityViolation() { continue } if pgErr.Field('C') == "55000" { // Retry on "#55000 attempted to delete invisible tuple". continue } } return false, err } if res.RowsAffected() == 1 { return true, nil } } err := fmt.Errorf( "pg: SelectOrInsert: select returns no rows (insert fails with err=%q)", insertErr) return false, err }
go
func (q *Query) SelectOrInsert(values ...interface{}) (inserted bool, _ error) { if q.stickyErr != nil { return false, q.stickyErr } var insertq *Query var insertErr error for i := 0; i < 5; i++ { if i >= 2 { time.Sleep(internal.RetryBackoff(i-2, 250*time.Millisecond, 5*time.Second)) } err := q.Select(values...) if err == nil { return false, nil } if err != internal.ErrNoRows { return false, err } if insertq == nil { insertq = q if len(insertq.columns) > 0 { insertq = insertq.Copy() insertq.columns = nil } } res, err := insertq.Insert(values...) if err != nil { insertErr = err if err == internal.ErrNoRows { continue } if pgErr, ok := err.(internal.PGError); ok { if pgErr.IntegrityViolation() { continue } if pgErr.Field('C') == "55000" { // Retry on "#55000 attempted to delete invisible tuple". continue } } return false, err } if res.RowsAffected() == 1 { return true, nil } } err := fmt.Errorf( "pg: SelectOrInsert: select returns no rows (insert fails with err=%q)", insertErr) return false, err }
[ "func", "(", "q", "*", "Query", ")", "SelectOrInsert", "(", "values", "...", "interface", "{", "}", ")", "(", "inserted", "bool", ",", "_", "error", ")", "{", "if", "q", ".", "stickyErr", "!=", "nil", "{", "return", "false", ",", "q", ".", "stickyE...
// SelectOrInsert selects the model inserting one if it does not exist. // It returns true when model was inserted.
[ "SelectOrInsert", "selects", "the", "model", "inserting", "one", "if", "it", "does", "not", "exist", ".", "It", "returns", "true", "when", "model", "was", "inserted", "." ]
9ab5ba23b6047052b91007b7041d9216025219a8
https://github.com/go-pg/pg/blob/9ab5ba23b6047052b91007b7041d9216025219a8/orm/query.go#L895-L949
train
go-pg/pg
orm/query.go
Update
func (q *Query) Update(scan ...interface{}) (Result, error) { return q.update(scan, false) }
go
func (q *Query) Update(scan ...interface{}) (Result, error) { return q.update(scan, false) }
[ "func", "(", "q", "*", "Query", ")", "Update", "(", "scan", "...", "interface", "{", "}", ")", "(", "Result", ",", "error", ")", "{", "return", "q", ".", "update", "(", "scan", ",", "false", ")", "\n", "}" ]
// Update updates the model.
[ "Update", "updates", "the", "model", "." ]
9ab5ba23b6047052b91007b7041d9216025219a8
https://github.com/go-pg/pg/blob/9ab5ba23b6047052b91007b7041d9216025219a8/orm/query.go#L952-L954
train
go-pg/pg
orm/query.go
UpdateNotNull
func (q *Query) UpdateNotNull(scan ...interface{}) (Result, error) { return q.update(scan, true) }
go
func (q *Query) UpdateNotNull(scan ...interface{}) (Result, error) { return q.update(scan, true) }
[ "func", "(", "q", "*", "Query", ")", "UpdateNotNull", "(", "scan", "...", "interface", "{", "}", ")", "(", "Result", ",", "error", ")", "{", "return", "q", ".", "update", "(", "scan", ",", "true", ")", "\n", "}" ]
// Update updates the model omitting null columns.
[ "Update", "updates", "the", "model", "omitting", "null", "columns", "." ]
9ab5ba23b6047052b91007b7041d9216025219a8
https://github.com/go-pg/pg/blob/9ab5ba23b6047052b91007b7041d9216025219a8/orm/query.go#L957-L959
train
go-pg/pg
orm/query.go
Delete
func (q *Query) Delete(values ...interface{}) (Result, error) { if q.hasModel() { table := q.model.Table() if table.SoftDeleteField != nil { q.model.setSoftDeleteField() columns := q.columns q.columns = nil res, err := q.Column(table.SoftDeleteField.SQLName).Update(values...) q.columns = columns return res, err } } return q.ForceDelete(values...) }
go
func (q *Query) Delete(values ...interface{}) (Result, error) { if q.hasModel() { table := q.model.Table() if table.SoftDeleteField != nil { q.model.setSoftDeleteField() columns := q.columns q.columns = nil res, err := q.Column(table.SoftDeleteField.SQLName).Update(values...) q.columns = columns return res, err } } return q.ForceDelete(values...) }
[ "func", "(", "q", "*", "Query", ")", "Delete", "(", "values", "...", "interface", "{", "}", ")", "(", "Result", ",", "error", ")", "{", "if", "q", ".", "hasModel", "(", ")", "{", "table", ":=", "q", ".", "model", ".", "Table", "(", ")", "\n", ...
// Delete deletes the model. When model has deleted_at column the row // is soft deleted instead.
[ "Delete", "deletes", "the", "model", ".", "When", "model", "has", "deleted_at", "column", "the", "row", "is", "soft", "deleted", "instead", "." ]
9ab5ba23b6047052b91007b7041d9216025219a8
https://github.com/go-pg/pg/blob/9ab5ba23b6047052b91007b7041d9216025219a8/orm/query.go#L1006-L1019
train
go-pg/pg
orm/query.go
CopyFrom
func (q *Query) CopyFrom(r io.Reader, query interface{}, params ...interface{}) (Result, error) { params = append(params, q.model) return q.db.CopyFrom(r, query, params...) }
go
func (q *Query) CopyFrom(r io.Reader, query interface{}, params ...interface{}) (Result, error) { params = append(params, q.model) return q.db.CopyFrom(r, query, params...) }
[ "func", "(", "q", "*", "Query", ")", "CopyFrom", "(", "r", "io", ".", "Reader", ",", "query", "interface", "{", "}", ",", "params", "...", "interface", "{", "}", ")", "(", "Result", ",", "error", ")", "{", "params", "=", "append", "(", "params", ...
// CopyFrom is an alias from DB.CopyFrom.
[ "CopyFrom", "is", "an", "alias", "from", "DB", ".", "CopyFrom", "." ]
9ab5ba23b6047052b91007b7041d9216025219a8
https://github.com/go-pg/pg/blob/9ab5ba23b6047052b91007b7041d9216025219a8/orm/query.go#L1093-L1096
train
go-pg/pg
orm/query.go
CopyTo
func (q *Query) CopyTo(w io.Writer, query interface{}, params ...interface{}) (Result, error) { params = append(params, q.model) return q.db.CopyTo(w, query, params...) }
go
func (q *Query) CopyTo(w io.Writer, query interface{}, params ...interface{}) (Result, error) { params = append(params, q.model) return q.db.CopyTo(w, query, params...) }
[ "func", "(", "q", "*", "Query", ")", "CopyTo", "(", "w", "io", ".", "Writer", ",", "query", "interface", "{", "}", ",", "params", "...", "interface", "{", "}", ")", "(", "Result", ",", "error", ")", "{", "params", "=", "append", "(", "params", ",...
// CopyTo is an alias from DB.CopyTo.
[ "CopyTo", "is", "an", "alias", "from", "DB", ".", "CopyTo", "." ]
9ab5ba23b6047052b91007b7041d9216025219a8
https://github.com/go-pg/pg/blob/9ab5ba23b6047052b91007b7041d9216025219a8/orm/query.go#L1099-L1102
train
go-pg/pg
orm/query.go
Exists
func (q *Query) Exists() (bool, error) { cp := q.Copy() // copy to not change original query cp.columns = []QueryAppender{Q("1")} cp.order = nil cp.limit = 1 res, err := q.db.ExecContext(q.ctx, newSelectQuery(cp)) if err != nil { return false, err } return res.RowsAffected() > 0, nil }
go
func (q *Query) Exists() (bool, error) { cp := q.Copy() // copy to not change original query cp.columns = []QueryAppender{Q("1")} cp.order = nil cp.limit = 1 res, err := q.db.ExecContext(q.ctx, newSelectQuery(cp)) if err != nil { return false, err } return res.RowsAffected() > 0, nil }
[ "func", "(", "q", "*", "Query", ")", "Exists", "(", ")", "(", "bool", ",", "error", ")", "{", "cp", ":=", "q", ".", "Copy", "(", ")", "\n", "cp", ".", "columns", "=", "[", "]", "QueryAppender", "{", "Q", "(", "\"1\"", ")", "}", "\n", "cp", ...
// Exists returns true or false depending if there are any rows matching the query.
[ "Exists", "returns", "true", "or", "false", "depending", "if", "there", "are", "any", "rows", "matching", "the", "query", "." ]
9ab5ba23b6047052b91007b7041d9216025219a8
https://github.com/go-pg/pg/blob/9ab5ba23b6047052b91007b7041d9216025219a8/orm/query.go#L1111-L1121
train
go-pg/pg
db.go
Connect
func Connect(opt *Options) *DB { opt.init() return newDB( context.TODO(), &baseDB{ opt: opt, pool: newConnPool(opt), }, ) }
go
func Connect(opt *Options) *DB { opt.init() return newDB( context.TODO(), &baseDB{ opt: opt, pool: newConnPool(opt), }, ) }
[ "func", "Connect", "(", "opt", "*", "Options", ")", "*", "DB", "{", "opt", ".", "init", "(", ")", "\n", "return", "newDB", "(", "context", ".", "TODO", "(", ")", ",", "&", "baseDB", "{", "opt", ":", "opt", ",", "pool", ":", "newConnPool", "(", ...
// Connect connects to a database using provided options. // // The returned DB is safe for concurrent use by multiple goroutines // and maintains its own connection pool.
[ "Connect", "connects", "to", "a", "database", "using", "provided", "options", ".", "The", "returned", "DB", "is", "safe", "for", "concurrent", "use", "by", "multiple", "goroutines", "and", "maintains", "its", "own", "connection", "pool", "." ]
9ab5ba23b6047052b91007b7041d9216025219a8
https://github.com/go-pg/pg/blob/9ab5ba23b6047052b91007b7041d9216025219a8/db.go#L16-L25
train
go-pg/pg
db.go
Listen
func (db *DB) Listen(channels ...string) *Listener { ln := &Listener{ db: db, } ln.init() _ = ln.Listen(channels...) return ln }
go
func (db *DB) Listen(channels ...string) *Listener { ln := &Listener{ db: db, } ln.init() _ = ln.Listen(channels...) return ln }
[ "func", "(", "db", "*", "DB", ")", "Listen", "(", "channels", "...", "string", ")", "*", "Listener", "{", "ln", ":=", "&", "Listener", "{", "db", ":", "db", ",", "}", "\n", "ln", ".", "init", "(", ")", "\n", "_", "=", "ln", ".", "Listen", "("...
// Listen listens for notifications sent with NOTIFY command.
[ "Listen", "listens", "for", "notifications", "sent", "with", "NOTIFY", "command", "." ]
9ab5ba23b6047052b91007b7041d9216025219a8
https://github.com/go-pg/pg/blob/9ab5ba23b6047052b91007b7041d9216025219a8/db.go#L80-L87
train
go-pg/pg
db.go
Conn
func (db *DB) Conn() *Conn { return newConn(db.ctx, db.baseDB.withPool(pool.NewSingleConnPool(db.pool))) }
go
func (db *DB) Conn() *Conn { return newConn(db.ctx, db.baseDB.withPool(pool.NewSingleConnPool(db.pool))) }
[ "func", "(", "db", "*", "DB", ")", "Conn", "(", ")", "*", "Conn", "{", "return", "newConn", "(", "db", ".", "ctx", ",", "db", ".", "baseDB", ".", "withPool", "(", "pool", ".", "NewSingleConnPool", "(", "db", ".", "pool", ")", ")", ")", "\n", "}...
// Conn returns a single connection by either opening a new connection // or returning an existing connection from the connection pool. Conn will // block until either a connection is returned or ctx is canceled. // Queries run on the same Conn will be run in the same database session. // // Every Conn must be returned to the database pool after use by // calling Conn.Close.
[ "Conn", "returns", "a", "single", "connection", "by", "either", "opening", "a", "new", "connection", "or", "returning", "an", "existing", "connection", "from", "the", "connection", "pool", ".", "Conn", "will", "block", "until", "either", "a", "connection", "is...
9ab5ba23b6047052b91007b7041d9216025219a8
https://github.com/go-pg/pg/blob/9ab5ba23b6047052b91007b7041d9216025219a8/db.go#L111-L113
train
sendgrid/sendgrid-go
examples/helpers/mail/example.go
helloEmail
func helloEmail() []byte { address := "test@example.com" name := "Example User" from := mail.NewEmail(name, address) subject := "Hello World from the SendGrid Go Library" address = "test@example.com" name = "Example User" to := mail.NewEmail(name, address) content := mail.NewContent("text/plain", "some text here") m := mail.NewV3MailInit(from, subject, to, content) address = "test2@example.com" name = "Example User" email := mail.NewEmail(name, address) m.Personalizations[0].AddTos(email) return mail.GetRequestBody(m) }
go
func helloEmail() []byte { address := "test@example.com" name := "Example User" from := mail.NewEmail(name, address) subject := "Hello World from the SendGrid Go Library" address = "test@example.com" name = "Example User" to := mail.NewEmail(name, address) content := mail.NewContent("text/plain", "some text here") m := mail.NewV3MailInit(from, subject, to, content) address = "test2@example.com" name = "Example User" email := mail.NewEmail(name, address) m.Personalizations[0].AddTos(email) return mail.GetRequestBody(m) }
[ "func", "helloEmail", "(", ")", "[", "]", "byte", "{", "address", ":=", "\"test@example.com\"", "\n", "name", ":=", "\"Example User\"", "\n", "from", ":=", "mail", ".", "NewEmail", "(", "name", ",", "address", ")", "\n", "subject", ":=", "\"Hello World from ...
// Minimum required to send an email
[ "Minimum", "required", "to", "send", "an", "email" ]
df2105ec04e32aff6b9e9a2fd1ca8e5c16a836c5
https://github.com/sendgrid/sendgrid-go/blob/df2105ec04e32aff6b9e9a2fd1ca8e5c16a836c5/examples/helpers/mail/example.go#L14-L29
train
sendgrid/sendgrid-go
sendgrid.go
GetRequestSubuser
func GetRequestSubuser(key, endpoint, host, subuser string) rest.Request { return requestNew(options{key, endpoint, host, subuser}) }
go
func GetRequestSubuser(key, endpoint, host, subuser string) rest.Request { return requestNew(options{key, endpoint, host, subuser}) }
[ "func", "GetRequestSubuser", "(", "key", ",", "endpoint", ",", "host", ",", "subuser", "string", ")", "rest", ".", "Request", "{", "return", "requestNew", "(", "options", "{", "key", ",", "endpoint", ",", "host", ",", "subuser", "}", ")", "\n", "}" ]
// GetRequestSubuser like GetRequest but with On-Behalf of Subuser // @return [Request] a default request object
[ "GetRequestSubuser", "like", "GetRequest", "but", "with", "On", "-", "Behalf", "of", "Subuser" ]
df2105ec04e32aff6b9e9a2fd1ca8e5c16a836c5
https://github.com/sendgrid/sendgrid-go/blob/df2105ec04e32aff6b9e9a2fd1ca8e5c16a836c5/sendgrid.go#L47-L49
train