repo stringlengths 5 54 | path stringlengths 4 155 | func_name stringlengths 1 118 | original_string stringlengths 52 85.5k | language stringclasses 1 value | code stringlengths 52 85.5k | code_tokens list | docstring stringlengths 6 2.61k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 85 252 | partition stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|
emicklei/go-restful | web_service.go | Method | func (w *WebService) Method(httpMethod string) *RouteBuilder {
return new(RouteBuilder).typeNameHandler(w.typeNameHandleFunc).servicePath(w.rootPath).Method(httpMethod)
} | go | func (w *WebService) Method(httpMethod string) *RouteBuilder {
return new(RouteBuilder).typeNameHandler(w.typeNameHandleFunc).servicePath(w.rootPath).Method(httpMethod)
} | [
"func",
"(",
"w",
"*",
"WebService",
")",
"Method",
"(",
"httpMethod",
"string",
")",
"*",
"RouteBuilder",
"{",
"return",
"new",
"(",
"RouteBuilder",
")",
".",
"typeNameHandler",
"(",
"w",
".",
"typeNameHandleFunc",
")",
".",
"servicePath",
"(",
"w",
".",
... | // Method creates a new RouteBuilder and initialize its http method | [
"Method",
"creates",
"a",
"new",
"RouteBuilder",
"and",
"initialize",
"its",
"http",
"method"
] | d2b8501d30f1b2c552dafdb21e3434bbafdaa124 | https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/web_service.go#L198-L200 | train |
emicklei/go-restful | web_service.go | Produces | func (w *WebService) Produces(contentTypes ...string) *WebService {
w.produces = contentTypes
return w
} | go | func (w *WebService) Produces(contentTypes ...string) *WebService {
w.produces = contentTypes
return w
} | [
"func",
"(",
"w",
"*",
"WebService",
")",
"Produces",
"(",
"contentTypes",
"...",
"string",
")",
"*",
"WebService",
"{",
"w",
".",
"produces",
"=",
"contentTypes",
"\n",
"return",
"w",
"\n",
"}"
] | // Produces specifies that this WebService can produce one or more MIME types.
// Http requests must have one of these values set for the Accept header. | [
"Produces",
"specifies",
"that",
"this",
"WebService",
"can",
"produce",
"one",
"or",
"more",
"MIME",
"types",
".",
"Http",
"requests",
"must",
"have",
"one",
"of",
"these",
"values",
"set",
"for",
"the",
"Accept",
"header",
"."
] | d2b8501d30f1b2c552dafdb21e3434bbafdaa124 | https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/web_service.go#L204-L207 | train |
emicklei/go-restful | web_service.go | Consumes | func (w *WebService) Consumes(accepts ...string) *WebService {
w.consumes = accepts
return w
} | go | func (w *WebService) Consumes(accepts ...string) *WebService {
w.consumes = accepts
return w
} | [
"func",
"(",
"w",
"*",
"WebService",
")",
"Consumes",
"(",
"accepts",
"...",
"string",
")",
"*",
"WebService",
"{",
"w",
".",
"consumes",
"=",
"accepts",
"\n",
"return",
"w",
"\n",
"}"
] | // Consumes specifies that this WebService can consume one or more MIME types.
// Http requests must have one of these values set for the Content-Type header. | [
"Consumes",
"specifies",
"that",
"this",
"WebService",
"can",
"consume",
"one",
"or",
"more",
"MIME",
"types",
".",
"Http",
"requests",
"must",
"have",
"one",
"of",
"these",
"values",
"set",
"for",
"the",
"Content",
"-",
"Type",
"header",
"."
] | d2b8501d30f1b2c552dafdb21e3434bbafdaa124 | https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/web_service.go#L211-L214 | train |
emicklei/go-restful | web_service.go | Routes | func (w *WebService) Routes() []Route {
if !w.dynamicRoutes {
return w.routes
}
// Make a copy of the array to prevent concurrency problems
w.routesLock.RLock()
defer w.routesLock.RUnlock()
result := make([]Route, len(w.routes))
for ix := range w.routes {
result[ix] = w.routes[ix]
}
return result
} | go | func (w *WebService) Routes() []Route {
if !w.dynamicRoutes {
return w.routes
}
// Make a copy of the array to prevent concurrency problems
w.routesLock.RLock()
defer w.routesLock.RUnlock()
result := make([]Route, len(w.routes))
for ix := range w.routes {
result[ix] = w.routes[ix]
}
return result
} | [
"func",
"(",
"w",
"*",
"WebService",
")",
"Routes",
"(",
")",
"[",
"]",
"Route",
"{",
"if",
"!",
"w",
".",
"dynamicRoutes",
"{",
"return",
"w",
".",
"routes",
"\n",
"}",
"\n",
"// Make a copy of the array to prevent concurrency problems",
"w",
".",
"routesLo... | // Routes returns the Routes associated with this WebService | [
"Routes",
"returns",
"the",
"Routes",
"associated",
"with",
"this",
"WebService"
] | d2b8501d30f1b2c552dafdb21e3434bbafdaa124 | https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/web_service.go#L217-L229 | train |
emicklei/go-restful | web_service.go | Filter | func (w *WebService) Filter(filter FilterFunction) *WebService {
w.filters = append(w.filters, filter)
return w
} | go | func (w *WebService) Filter(filter FilterFunction) *WebService {
w.filters = append(w.filters, filter)
return w
} | [
"func",
"(",
"w",
"*",
"WebService",
")",
"Filter",
"(",
"filter",
"FilterFunction",
")",
"*",
"WebService",
"{",
"w",
".",
"filters",
"=",
"append",
"(",
"w",
".",
"filters",
",",
"filter",
")",
"\n",
"return",
"w",
"\n",
"}"
] | // Filter adds a filter function to the chain of filters applicable to all its Routes | [
"Filter",
"adds",
"a",
"filter",
"function",
"to",
"the",
"chain",
"of",
"filters",
"applicable",
"to",
"all",
"its",
"Routes"
] | d2b8501d30f1b2c552dafdb21e3434bbafdaa124 | https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/web_service.go#L242-L245 | train |
emicklei/go-restful | web_service.go | Doc | func (w *WebService) Doc(plainText string) *WebService {
w.documentation = plainText
return w
} | go | func (w *WebService) Doc(plainText string) *WebService {
w.documentation = plainText
return w
} | [
"func",
"(",
"w",
"*",
"WebService",
")",
"Doc",
"(",
"plainText",
"string",
")",
"*",
"WebService",
"{",
"w",
".",
"documentation",
"=",
"plainText",
"\n",
"return",
"w",
"\n",
"}"
] | // Doc is used to set the documentation of this service. | [
"Doc",
"is",
"used",
"to",
"set",
"the",
"documentation",
"of",
"this",
"service",
"."
] | d2b8501d30f1b2c552dafdb21e3434bbafdaa124 | https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/web_service.go#L248-L251 | train |
emicklei/go-restful | parameter.go | Required | func (p *Parameter) Required(required bool) *Parameter {
p.data.Required = required
return p
} | go | func (p *Parameter) Required(required bool) *Parameter {
p.data.Required = required
return p
} | [
"func",
"(",
"p",
"*",
"Parameter",
")",
"Required",
"(",
"required",
"bool",
")",
"*",
"Parameter",
"{",
"p",
".",
"data",
".",
"Required",
"=",
"required",
"\n",
"return",
"p",
"\n",
"}"
] | // Required sets the required field and returns the receiver | [
"Required",
"sets",
"the",
"required",
"field",
"and",
"returns",
"the",
"receiver"
] | d2b8501d30f1b2c552dafdb21e3434bbafdaa124 | https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/parameter.go#L98-L101 | train |
emicklei/go-restful | parameter.go | AllowMultiple | func (p *Parameter) AllowMultiple(multiple bool) *Parameter {
p.data.AllowMultiple = multiple
return p
} | go | func (p *Parameter) AllowMultiple(multiple bool) *Parameter {
p.data.AllowMultiple = multiple
return p
} | [
"func",
"(",
"p",
"*",
"Parameter",
")",
"AllowMultiple",
"(",
"multiple",
"bool",
")",
"*",
"Parameter",
"{",
"p",
".",
"data",
".",
"AllowMultiple",
"=",
"multiple",
"\n",
"return",
"p",
"\n",
"}"
] | // AllowMultiple sets the allowMultiple field and returns the receiver | [
"AllowMultiple",
"sets",
"the",
"allowMultiple",
"field",
"and",
"returns",
"the",
"receiver"
] | d2b8501d30f1b2c552dafdb21e3434bbafdaa124 | https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/parameter.go#L104-L107 | train |
emicklei/go-restful | parameter.go | AllowableValues | func (p *Parameter) AllowableValues(values map[string]string) *Parameter {
p.data.AllowableValues = values
return p
} | go | func (p *Parameter) AllowableValues(values map[string]string) *Parameter {
p.data.AllowableValues = values
return p
} | [
"func",
"(",
"p",
"*",
"Parameter",
")",
"AllowableValues",
"(",
"values",
"map",
"[",
"string",
"]",
"string",
")",
"*",
"Parameter",
"{",
"p",
".",
"data",
".",
"AllowableValues",
"=",
"values",
"\n",
"return",
"p",
"\n",
"}"
] | // AllowableValues sets the allowableValues field and returns the receiver | [
"AllowableValues",
"sets",
"the",
"allowableValues",
"field",
"and",
"returns",
"the",
"receiver"
] | d2b8501d30f1b2c552dafdb21e3434bbafdaa124 | https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/parameter.go#L110-L113 | train |
emicklei/go-restful | parameter.go | DataType | func (p *Parameter) DataType(typeName string) *Parameter {
p.data.DataType = typeName
return p
} | go | func (p *Parameter) DataType(typeName string) *Parameter {
p.data.DataType = typeName
return p
} | [
"func",
"(",
"p",
"*",
"Parameter",
")",
"DataType",
"(",
"typeName",
"string",
")",
"*",
"Parameter",
"{",
"p",
".",
"data",
".",
"DataType",
"=",
"typeName",
"\n",
"return",
"p",
"\n",
"}"
] | // DataType sets the dataType field and returns the receiver | [
"DataType",
"sets",
"the",
"dataType",
"field",
"and",
"returns",
"the",
"receiver"
] | d2b8501d30f1b2c552dafdb21e3434bbafdaa124 | https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/parameter.go#L116-L119 | train |
emicklei/go-restful | parameter.go | DataFormat | func (p *Parameter) DataFormat(formatName string) *Parameter {
p.data.DataFormat = formatName
return p
} | go | func (p *Parameter) DataFormat(formatName string) *Parameter {
p.data.DataFormat = formatName
return p
} | [
"func",
"(",
"p",
"*",
"Parameter",
")",
"DataFormat",
"(",
"formatName",
"string",
")",
"*",
"Parameter",
"{",
"p",
".",
"data",
".",
"DataFormat",
"=",
"formatName",
"\n",
"return",
"p",
"\n",
"}"
] | // DataFormat sets the dataFormat field for Swagger UI | [
"DataFormat",
"sets",
"the",
"dataFormat",
"field",
"for",
"Swagger",
"UI"
] | d2b8501d30f1b2c552dafdb21e3434bbafdaa124 | https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/parameter.go#L122-L125 | train |
emicklei/go-restful | parameter.go | DefaultValue | func (p *Parameter) DefaultValue(stringRepresentation string) *Parameter {
p.data.DefaultValue = stringRepresentation
return p
} | go | func (p *Parameter) DefaultValue(stringRepresentation string) *Parameter {
p.data.DefaultValue = stringRepresentation
return p
} | [
"func",
"(",
"p",
"*",
"Parameter",
")",
"DefaultValue",
"(",
"stringRepresentation",
"string",
")",
"*",
"Parameter",
"{",
"p",
".",
"data",
".",
"DefaultValue",
"=",
"stringRepresentation",
"\n",
"return",
"p",
"\n",
"}"
] | // DefaultValue sets the default value field and returns the receiver | [
"DefaultValue",
"sets",
"the",
"default",
"value",
"field",
"and",
"returns",
"the",
"receiver"
] | d2b8501d30f1b2c552dafdb21e3434bbafdaa124 | https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/parameter.go#L128-L131 | train |
emicklei/go-restful | parameter.go | Description | func (p *Parameter) Description(doc string) *Parameter {
p.data.Description = doc
return p
} | go | func (p *Parameter) Description(doc string) *Parameter {
p.data.Description = doc
return p
} | [
"func",
"(",
"p",
"*",
"Parameter",
")",
"Description",
"(",
"doc",
"string",
")",
"*",
"Parameter",
"{",
"p",
".",
"data",
".",
"Description",
"=",
"doc",
"\n",
"return",
"p",
"\n",
"}"
] | // Description sets the description value field and returns the receiver | [
"Description",
"sets",
"the",
"description",
"value",
"field",
"and",
"returns",
"the",
"receiver"
] | d2b8501d30f1b2c552dafdb21e3434bbafdaa124 | https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/parameter.go#L134-L137 | train |
emicklei/go-restful | parameter.go | CollectionFormat | func (p *Parameter) CollectionFormat(format CollectionFormat) *Parameter {
p.data.CollectionFormat = format.String()
return p
} | go | func (p *Parameter) CollectionFormat(format CollectionFormat) *Parameter {
p.data.CollectionFormat = format.String()
return p
} | [
"func",
"(",
"p",
"*",
"Parameter",
")",
"CollectionFormat",
"(",
"format",
"CollectionFormat",
")",
"*",
"Parameter",
"{",
"p",
".",
"data",
".",
"CollectionFormat",
"=",
"format",
".",
"String",
"(",
")",
"\n",
"return",
"p",
"\n",
"}"
] | // CollectionFormat sets the collection format for an array type | [
"CollectionFormat",
"sets",
"the",
"collection",
"format",
"for",
"an",
"array",
"type"
] | d2b8501d30f1b2c552dafdb21e3434bbafdaa124 | https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/parameter.go#L140-L143 | train |
emicklei/go-restful | response.go | NewResponse | func NewResponse(httpWriter http.ResponseWriter) *Response {
hijacker, _ := httpWriter.(http.Hijacker)
return &Response{ResponseWriter: httpWriter, routeProduces: []string{}, statusCode: http.StatusOK, prettyPrint: PrettyPrintResponses, hijacker: hijacker}
} | go | func NewResponse(httpWriter http.ResponseWriter) *Response {
hijacker, _ := httpWriter.(http.Hijacker)
return &Response{ResponseWriter: httpWriter, routeProduces: []string{}, statusCode: http.StatusOK, prettyPrint: PrettyPrintResponses, hijacker: hijacker}
} | [
"func",
"NewResponse",
"(",
"httpWriter",
"http",
".",
"ResponseWriter",
")",
"*",
"Response",
"{",
"hijacker",
",",
"_",
":=",
"httpWriter",
".",
"(",
"http",
".",
"Hijacker",
")",
"\n",
"return",
"&",
"Response",
"{",
"ResponseWriter",
":",
"httpWriter",
... | // NewResponse creates a new response based on a http ResponseWriter. | [
"NewResponse",
"creates",
"a",
"new",
"response",
"based",
"on",
"a",
"http",
"ResponseWriter",
"."
] | d2b8501d30f1b2c552dafdb21e3434bbafdaa124 | https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/response.go#L34-L37 | train |
emicklei/go-restful | response.go | Hijack | func (r *Response) Hijack() (net.Conn, *bufio.ReadWriter, error) {
if r.hijacker == nil {
return nil, nil, errors.New("http.Hijacker not implemented by underlying http.ResponseWriter")
}
return r.hijacker.Hijack()
} | go | func (r *Response) Hijack() (net.Conn, *bufio.ReadWriter, error) {
if r.hijacker == nil {
return nil, nil, errors.New("http.Hijacker not implemented by underlying http.ResponseWriter")
}
return r.hijacker.Hijack()
} | [
"func",
"(",
"r",
"*",
"Response",
")",
"Hijack",
"(",
")",
"(",
"net",
".",
"Conn",
",",
"*",
"bufio",
".",
"ReadWriter",
",",
"error",
")",
"{",
"if",
"r",
".",
"hijacker",
"==",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"errors",
".",
"N... | // Hijack implements the http.Hijacker interface. This expands
// the Response to fulfill http.Hijacker if the underlying
// http.ResponseWriter supports it. | [
"Hijack",
"implements",
"the",
"http",
".",
"Hijacker",
"interface",
".",
"This",
"expands",
"the",
"Response",
"to",
"fulfill",
"http",
".",
"Hijacker",
"if",
"the",
"underlying",
"http",
".",
"ResponseWriter",
"supports",
"it",
"."
] | d2b8501d30f1b2c552dafdb21e3434bbafdaa124 | https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/response.go#L58-L63 | train |
emicklei/go-restful | response.go | WriteError | func (r *Response) WriteError(httpStatus int, err error) error {
r.err = err
return r.WriteErrorString(httpStatus, err.Error())
} | go | func (r *Response) WriteError(httpStatus int, err error) error {
r.err = err
return r.WriteErrorString(httpStatus, err.Error())
} | [
"func",
"(",
"r",
"*",
"Response",
")",
"WriteError",
"(",
"httpStatus",
"int",
",",
"err",
"error",
")",
"error",
"{",
"r",
".",
"err",
"=",
"err",
"\n",
"return",
"r",
".",
"WriteErrorString",
"(",
"httpStatus",
",",
"err",
".",
"Error",
"(",
")",
... | // WriteError write the http status and the error string on the response. | [
"WriteError",
"write",
"the",
"http",
"status",
"and",
"the",
"error",
"string",
"on",
"the",
"response",
"."
] | d2b8501d30f1b2c552dafdb21e3434bbafdaa124 | https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/response.go#L178-L181 | train |
emicklei/go-restful | response.go | WriteServiceError | func (r *Response) WriteServiceError(httpStatus int, err ServiceError) error {
r.err = err
return r.WriteHeaderAndEntity(httpStatus, err)
} | go | func (r *Response) WriteServiceError(httpStatus int, err ServiceError) error {
r.err = err
return r.WriteHeaderAndEntity(httpStatus, err)
} | [
"func",
"(",
"r",
"*",
"Response",
")",
"WriteServiceError",
"(",
"httpStatus",
"int",
",",
"err",
"ServiceError",
")",
"error",
"{",
"r",
".",
"err",
"=",
"err",
"\n",
"return",
"r",
".",
"WriteHeaderAndEntity",
"(",
"httpStatus",
",",
"err",
")",
"\n",... | // WriteServiceError is a convenience method for a responding with a status and a ServiceError | [
"WriteServiceError",
"is",
"a",
"convenience",
"method",
"for",
"a",
"responding",
"with",
"a",
"status",
"and",
"a",
"ServiceError"
] | d2b8501d30f1b2c552dafdb21e3434bbafdaa124 | https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/response.go#L184-L187 | train |
emicklei/go-restful | response.go | WriteErrorString | func (r *Response) WriteErrorString(httpStatus int, errorReason string) error {
if r.err == nil {
// if not called from WriteError
r.err = errors.New(errorReason)
}
r.WriteHeader(httpStatus)
if _, err := r.Write([]byte(errorReason)); err != nil {
return err
}
return nil
} | go | func (r *Response) WriteErrorString(httpStatus int, errorReason string) error {
if r.err == nil {
// if not called from WriteError
r.err = errors.New(errorReason)
}
r.WriteHeader(httpStatus)
if _, err := r.Write([]byte(errorReason)); err != nil {
return err
}
return nil
} | [
"func",
"(",
"r",
"*",
"Response",
")",
"WriteErrorString",
"(",
"httpStatus",
"int",
",",
"errorReason",
"string",
")",
"error",
"{",
"if",
"r",
".",
"err",
"==",
"nil",
"{",
"// if not called from WriteError",
"r",
".",
"err",
"=",
"errors",
".",
"New",
... | // WriteErrorString is a convenience method for an error status with the actual error | [
"WriteErrorString",
"is",
"a",
"convenience",
"method",
"for",
"an",
"error",
"status",
"with",
"the",
"actual",
"error"
] | d2b8501d30f1b2c552dafdb21e3434bbafdaa124 | https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/response.go#L190-L200 | train |
emicklei/go-restful | response.go | Flush | func (r *Response) Flush() {
if f, ok := r.ResponseWriter.(http.Flusher); ok {
f.Flush()
} else if trace {
traceLogger.Printf("ResponseWriter %v doesn't support Flush", r)
}
} | go | func (r *Response) Flush() {
if f, ok := r.ResponseWriter.(http.Flusher); ok {
f.Flush()
} else if trace {
traceLogger.Printf("ResponseWriter %v doesn't support Flush", r)
}
} | [
"func",
"(",
"r",
"*",
"Response",
")",
"Flush",
"(",
")",
"{",
"if",
"f",
",",
"ok",
":=",
"r",
".",
"ResponseWriter",
".",
"(",
"http",
".",
"Flusher",
")",
";",
"ok",
"{",
"f",
".",
"Flush",
"(",
")",
"\n",
"}",
"else",
"if",
"trace",
"{",... | // Flush implements http.Flusher interface, which sends any buffered data to the client. | [
"Flush",
"implements",
"http",
".",
"Flusher",
"interface",
"which",
"sends",
"any",
"buffered",
"data",
"to",
"the",
"client",
"."
] | d2b8501d30f1b2c552dafdb21e3434bbafdaa124 | https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/response.go#L203-L209 | train |
emicklei/go-restful | response.go | WriteHeader | func (r *Response) WriteHeader(httpStatus int) {
r.statusCode = httpStatus
r.ResponseWriter.WriteHeader(httpStatus)
} | go | func (r *Response) WriteHeader(httpStatus int) {
r.statusCode = httpStatus
r.ResponseWriter.WriteHeader(httpStatus)
} | [
"func",
"(",
"r",
"*",
"Response",
")",
"WriteHeader",
"(",
"httpStatus",
"int",
")",
"{",
"r",
".",
"statusCode",
"=",
"httpStatus",
"\n",
"r",
".",
"ResponseWriter",
".",
"WriteHeader",
"(",
"httpStatus",
")",
"\n",
"}"
] | // WriteHeader is overridden to remember the Status Code that has been written.
// Changes to the Header of the response have no effect after this. | [
"WriteHeader",
"is",
"overridden",
"to",
"remember",
"the",
"Status",
"Code",
"that",
"has",
"been",
"written",
".",
"Changes",
"to",
"the",
"Header",
"of",
"the",
"response",
"have",
"no",
"effect",
"after",
"this",
"."
] | d2b8501d30f1b2c552dafdb21e3434bbafdaa124 | https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/response.go#L213-L216 | train |
emicklei/go-restful | response.go | StatusCode | func (r Response) StatusCode() int {
if 0 == r.statusCode {
// no status code has been written yet; assume OK
return http.StatusOK
}
return r.statusCode
} | go | func (r Response) StatusCode() int {
if 0 == r.statusCode {
// no status code has been written yet; assume OK
return http.StatusOK
}
return r.statusCode
} | [
"func",
"(",
"r",
"Response",
")",
"StatusCode",
"(",
")",
"int",
"{",
"if",
"0",
"==",
"r",
".",
"statusCode",
"{",
"// no status code has been written yet; assume OK",
"return",
"http",
".",
"StatusOK",
"\n",
"}",
"\n",
"return",
"r",
".",
"statusCode",
"\... | // StatusCode returns the code that has been written using WriteHeader. | [
"StatusCode",
"returns",
"the",
"code",
"that",
"has",
"been",
"written",
"using",
"WriteHeader",
"."
] | d2b8501d30f1b2c552dafdb21e3434bbafdaa124 | https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/response.go#L219-L225 | train |
emicklei/go-restful | response.go | Write | func (r *Response) Write(bytes []byte) (int, error) {
written, err := r.ResponseWriter.Write(bytes)
r.contentLength += written
return written, err
} | go | func (r *Response) Write(bytes []byte) (int, error) {
written, err := r.ResponseWriter.Write(bytes)
r.contentLength += written
return written, err
} | [
"func",
"(",
"r",
"*",
"Response",
")",
"Write",
"(",
"bytes",
"[",
"]",
"byte",
")",
"(",
"int",
",",
"error",
")",
"{",
"written",
",",
"err",
":=",
"r",
".",
"ResponseWriter",
".",
"Write",
"(",
"bytes",
")",
"\n",
"r",
".",
"contentLength",
"... | // Write writes the data to the connection as part of an HTTP reply.
// Write is part of http.ResponseWriter interface. | [
"Write",
"writes",
"the",
"data",
"to",
"the",
"connection",
"as",
"part",
"of",
"an",
"HTTP",
"reply",
".",
"Write",
"is",
"part",
"of",
"http",
".",
"ResponseWriter",
"interface",
"."
] | d2b8501d30f1b2c552dafdb21e3434bbafdaa124 | https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/response.go#L229-L233 | train |
emicklei/go-restful | mime.go | insertMime | func insertMime(l []mime, e mime) []mime {
for i, each := range l {
// if current mime has lower quality then insert before
if e.quality > each.quality {
left := append([]mime{}, l[0:i]...)
return append(append(left, e), l[i:]...)
}
}
return append(l, e)
} | go | func insertMime(l []mime, e mime) []mime {
for i, each := range l {
// if current mime has lower quality then insert before
if e.quality > each.quality {
left := append([]mime{}, l[0:i]...)
return append(append(left, e), l[i:]...)
}
}
return append(l, e)
} | [
"func",
"insertMime",
"(",
"l",
"[",
"]",
"mime",
",",
"e",
"mime",
")",
"[",
"]",
"mime",
"{",
"for",
"i",
",",
"each",
":=",
"range",
"l",
"{",
"// if current mime has lower quality then insert before",
"if",
"e",
".",
"quality",
">",
"each",
".",
"qua... | // insertMime adds a mime to a list and keeps it sorted by quality. | [
"insertMime",
"adds",
"a",
"mime",
"to",
"a",
"list",
"and",
"keeps",
"it",
"sorted",
"by",
"quality",
"."
] | d2b8501d30f1b2c552dafdb21e3434bbafdaa124 | https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/mime.go#L14-L23 | train |
davecgh/go-spew | spew/bypass.go | flagField | func flagField(v *reflect.Value) *flag {
return (*flag)(unsafe.Pointer(uintptr(unsafe.Pointer(v)) + flagValOffset))
} | go | func flagField(v *reflect.Value) *flag {
return (*flag)(unsafe.Pointer(uintptr(unsafe.Pointer(v)) + flagValOffset))
} | [
"func",
"flagField",
"(",
"v",
"*",
"reflect",
".",
"Value",
")",
"*",
"flag",
"{",
"return",
"(",
"*",
"flag",
")",
"(",
"unsafe",
".",
"Pointer",
"(",
"uintptr",
"(",
"unsafe",
".",
"Pointer",
"(",
"v",
")",
")",
"+",
"flagValOffset",
")",
")",
... | // flagField returns a pointer to the flag field of a reflect.Value. | [
"flagField",
"returns",
"a",
"pointer",
"to",
"the",
"flag",
"field",
"of",
"a",
"reflect",
".",
"Value",
"."
] | d8f796af33cc11cb798c1aaeb27a4ebc5099927d | https://github.com/davecgh/go-spew/blob/d8f796af33cc11cb798c1aaeb27a4ebc5099927d/spew/bypass.go#L80-L82 | train |
davecgh/go-spew | spew/bypass.go | init | func init() {
field, ok := reflect.TypeOf(reflect.Value{}).FieldByName("flag")
if !ok {
panic("reflect.Value has no flag field")
}
if field.Type.Kind() != reflect.TypeOf(flag(0)).Kind() {
panic("reflect.Value flag field has changed kind")
}
type t0 int
var t struct {
A t0
// t0 will have flagEmbedRO set.
t0
// a will have flagStickyRO set
a t0
}
vA := reflect.ValueOf(t).FieldByName("A")
va := reflect.ValueOf(t).FieldByName("a")
vt0 := reflect.ValueOf(t).FieldByName("t0")
// Infer flagRO from the difference between the flags
// for the (otherwise identical) fields in t.
flagPublic := *flagField(&vA)
flagWithRO := *flagField(&va) | *flagField(&vt0)
flagRO = flagPublic ^ flagWithRO
// Infer flagAddr from the difference between a value
// taken from a pointer and not.
vPtrA := reflect.ValueOf(&t).Elem().FieldByName("A")
flagNoPtr := *flagField(&vA)
flagPtr := *flagField(&vPtrA)
flagAddr = flagNoPtr ^ flagPtr
// Check that the inferred flags tally with one of the known versions.
for _, f := range okFlags {
if flagRO == f.ro && flagAddr == f.addr {
return
}
}
panic("reflect.Value read-only flag has changed semantics")
} | go | func init() {
field, ok := reflect.TypeOf(reflect.Value{}).FieldByName("flag")
if !ok {
panic("reflect.Value has no flag field")
}
if field.Type.Kind() != reflect.TypeOf(flag(0)).Kind() {
panic("reflect.Value flag field has changed kind")
}
type t0 int
var t struct {
A t0
// t0 will have flagEmbedRO set.
t0
// a will have flagStickyRO set
a t0
}
vA := reflect.ValueOf(t).FieldByName("A")
va := reflect.ValueOf(t).FieldByName("a")
vt0 := reflect.ValueOf(t).FieldByName("t0")
// Infer flagRO from the difference between the flags
// for the (otherwise identical) fields in t.
flagPublic := *flagField(&vA)
flagWithRO := *flagField(&va) | *flagField(&vt0)
flagRO = flagPublic ^ flagWithRO
// Infer flagAddr from the difference between a value
// taken from a pointer and not.
vPtrA := reflect.ValueOf(&t).Elem().FieldByName("A")
flagNoPtr := *flagField(&vA)
flagPtr := *flagField(&vPtrA)
flagAddr = flagNoPtr ^ flagPtr
// Check that the inferred flags tally with one of the known versions.
for _, f := range okFlags {
if flagRO == f.ro && flagAddr == f.addr {
return
}
}
panic("reflect.Value read-only flag has changed semantics")
} | [
"func",
"init",
"(",
")",
"{",
"field",
",",
"ok",
":=",
"reflect",
".",
"TypeOf",
"(",
"reflect",
".",
"Value",
"{",
"}",
")",
".",
"FieldByName",
"(",
"\"",
"\"",
")",
"\n",
"if",
"!",
"ok",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\... | // Sanity checks against future reflect package changes
// to the type or semantics of the Value.flag field. | [
"Sanity",
"checks",
"against",
"future",
"reflect",
"package",
"changes",
"to",
"the",
"type",
"or",
"semantics",
"of",
"the",
"Value",
".",
"flag",
"field",
"."
] | d8f796af33cc11cb798c1aaeb27a4ebc5099927d | https://github.com/davecgh/go-spew/blob/d8f796af33cc11cb798c1aaeb27a4ebc5099927d/spew/bypass.go#L105-L145 | train |
davecgh/go-spew | spew/format.go | buildDefaultFormat | func (f *formatState) buildDefaultFormat() (format string) {
buf := bytes.NewBuffer(percentBytes)
for _, flag := range supportedFlags {
if f.fs.Flag(int(flag)) {
buf.WriteRune(flag)
}
}
buf.WriteRune('v')
format = buf.String()
return format
} | go | func (f *formatState) buildDefaultFormat() (format string) {
buf := bytes.NewBuffer(percentBytes)
for _, flag := range supportedFlags {
if f.fs.Flag(int(flag)) {
buf.WriteRune(flag)
}
}
buf.WriteRune('v')
format = buf.String()
return format
} | [
"func",
"(",
"f",
"*",
"formatState",
")",
"buildDefaultFormat",
"(",
")",
"(",
"format",
"string",
")",
"{",
"buf",
":=",
"bytes",
".",
"NewBuffer",
"(",
"percentBytes",
")",
"\n\n",
"for",
"_",
",",
"flag",
":=",
"range",
"supportedFlags",
"{",
"if",
... | // buildDefaultFormat recreates the original format string without precision
// and width information to pass in to fmt.Sprintf in the case of an
// unrecognized type. Unless new types are added to the language, this
// function won't ever be called. | [
"buildDefaultFormat",
"recreates",
"the",
"original",
"format",
"string",
"without",
"precision",
"and",
"width",
"information",
"to",
"pass",
"in",
"to",
"fmt",
".",
"Sprintf",
"in",
"the",
"case",
"of",
"an",
"unrecognized",
"type",
".",
"Unless",
"new",
"ty... | d8f796af33cc11cb798c1aaeb27a4ebc5099927d | https://github.com/davecgh/go-spew/blob/d8f796af33cc11cb798c1aaeb27a4ebc5099927d/spew/format.go#L47-L60 | train |
davecgh/go-spew | spew/format.go | constructOrigFormat | func (f *formatState) constructOrigFormat(verb rune) (format string) {
buf := bytes.NewBuffer(percentBytes)
for _, flag := range supportedFlags {
if f.fs.Flag(int(flag)) {
buf.WriteRune(flag)
}
}
if width, ok := f.fs.Width(); ok {
buf.WriteString(strconv.Itoa(width))
}
if precision, ok := f.fs.Precision(); ok {
buf.Write(precisionBytes)
buf.WriteString(strconv.Itoa(precision))
}
buf.WriteRune(verb)
format = buf.String()
return format
} | go | func (f *formatState) constructOrigFormat(verb rune) (format string) {
buf := bytes.NewBuffer(percentBytes)
for _, flag := range supportedFlags {
if f.fs.Flag(int(flag)) {
buf.WriteRune(flag)
}
}
if width, ok := f.fs.Width(); ok {
buf.WriteString(strconv.Itoa(width))
}
if precision, ok := f.fs.Precision(); ok {
buf.Write(precisionBytes)
buf.WriteString(strconv.Itoa(precision))
}
buf.WriteRune(verb)
format = buf.String()
return format
} | [
"func",
"(",
"f",
"*",
"formatState",
")",
"constructOrigFormat",
"(",
"verb",
"rune",
")",
"(",
"format",
"string",
")",
"{",
"buf",
":=",
"bytes",
".",
"NewBuffer",
"(",
"percentBytes",
")",
"\n\n",
"for",
"_",
",",
"flag",
":=",
"range",
"supportedFla... | // constructOrigFormat recreates the original format string including precision
// and width information to pass along to the standard fmt package. This allows
// automatic deferral of all format strings this package doesn't support. | [
"constructOrigFormat",
"recreates",
"the",
"original",
"format",
"string",
"including",
"precision",
"and",
"width",
"information",
"to",
"pass",
"along",
"to",
"the",
"standard",
"fmt",
"package",
".",
"This",
"allows",
"automatic",
"deferral",
"of",
"all",
"form... | d8f796af33cc11cb798c1aaeb27a4ebc5099927d | https://github.com/davecgh/go-spew/blob/d8f796af33cc11cb798c1aaeb27a4ebc5099927d/spew/format.go#L65-L87 | train |
davecgh/go-spew | spew/format.go | unpackValue | func (f *formatState) unpackValue(v reflect.Value) reflect.Value {
if v.Kind() == reflect.Interface {
f.ignoreNextType = false
if !v.IsNil() {
v = v.Elem()
}
}
return v
} | go | func (f *formatState) unpackValue(v reflect.Value) reflect.Value {
if v.Kind() == reflect.Interface {
f.ignoreNextType = false
if !v.IsNil() {
v = v.Elem()
}
}
return v
} | [
"func",
"(",
"f",
"*",
"formatState",
")",
"unpackValue",
"(",
"v",
"reflect",
".",
"Value",
")",
"reflect",
".",
"Value",
"{",
"if",
"v",
".",
"Kind",
"(",
")",
"==",
"reflect",
".",
"Interface",
"{",
"f",
".",
"ignoreNextType",
"=",
"false",
"\n",
... | // unpackValue returns values inside of non-nil interfaces when possible and
// ensures that types for values which have been unpacked from an interface
// are displayed when the show types flag is also set.
// This is useful for data types like structs, arrays, slices, and maps which
// can contain varying types packed inside an interface. | [
"unpackValue",
"returns",
"values",
"inside",
"of",
"non",
"-",
"nil",
"interfaces",
"when",
"possible",
"and",
"ensures",
"that",
"types",
"for",
"values",
"which",
"have",
"been",
"unpacked",
"from",
"an",
"interface",
"are",
"displayed",
"when",
"the",
"sho... | d8f796af33cc11cb798c1aaeb27a4ebc5099927d | https://github.com/davecgh/go-spew/blob/d8f796af33cc11cb798c1aaeb27a4ebc5099927d/spew/format.go#L94-L102 | train |
davecgh/go-spew | spew/format.go | formatPtr | func (f *formatState) formatPtr(v reflect.Value) {
// Display nil if top level pointer is nil.
showTypes := f.fs.Flag('#')
if v.IsNil() && (!showTypes || f.ignoreNextType) {
f.fs.Write(nilAngleBytes)
return
}
// Remove pointers at or below the current depth from map used to detect
// circular refs.
for k, depth := range f.pointers {
if depth >= f.depth {
delete(f.pointers, k)
}
}
// Keep list of all dereferenced pointers to possibly show later.
pointerChain := make([]uintptr, 0)
// Figure out how many levels of indirection there are by derferencing
// pointers and unpacking interfaces down the chain while detecting circular
// references.
nilFound := false
cycleFound := false
indirects := 0
ve := v
for ve.Kind() == reflect.Ptr {
if ve.IsNil() {
nilFound = true
break
}
indirects++
addr := ve.Pointer()
pointerChain = append(pointerChain, addr)
if pd, ok := f.pointers[addr]; ok && pd < f.depth {
cycleFound = true
indirects--
break
}
f.pointers[addr] = f.depth
ve = ve.Elem()
if ve.Kind() == reflect.Interface {
if ve.IsNil() {
nilFound = true
break
}
ve = ve.Elem()
}
}
// Display type or indirection level depending on flags.
if showTypes && !f.ignoreNextType {
f.fs.Write(openParenBytes)
f.fs.Write(bytes.Repeat(asteriskBytes, indirects))
f.fs.Write([]byte(ve.Type().String()))
f.fs.Write(closeParenBytes)
} else {
if nilFound || cycleFound {
indirects += strings.Count(ve.Type().String(), "*")
}
f.fs.Write(openAngleBytes)
f.fs.Write([]byte(strings.Repeat("*", indirects)))
f.fs.Write(closeAngleBytes)
}
// Display pointer information depending on flags.
if f.fs.Flag('+') && (len(pointerChain) > 0) {
f.fs.Write(openParenBytes)
for i, addr := range pointerChain {
if i > 0 {
f.fs.Write(pointerChainBytes)
}
printHexPtr(f.fs, addr)
}
f.fs.Write(closeParenBytes)
}
// Display dereferenced value.
switch {
case nilFound:
f.fs.Write(nilAngleBytes)
case cycleFound:
f.fs.Write(circularShortBytes)
default:
f.ignoreNextType = true
f.format(ve)
}
} | go | func (f *formatState) formatPtr(v reflect.Value) {
// Display nil if top level pointer is nil.
showTypes := f.fs.Flag('#')
if v.IsNil() && (!showTypes || f.ignoreNextType) {
f.fs.Write(nilAngleBytes)
return
}
// Remove pointers at or below the current depth from map used to detect
// circular refs.
for k, depth := range f.pointers {
if depth >= f.depth {
delete(f.pointers, k)
}
}
// Keep list of all dereferenced pointers to possibly show later.
pointerChain := make([]uintptr, 0)
// Figure out how many levels of indirection there are by derferencing
// pointers and unpacking interfaces down the chain while detecting circular
// references.
nilFound := false
cycleFound := false
indirects := 0
ve := v
for ve.Kind() == reflect.Ptr {
if ve.IsNil() {
nilFound = true
break
}
indirects++
addr := ve.Pointer()
pointerChain = append(pointerChain, addr)
if pd, ok := f.pointers[addr]; ok && pd < f.depth {
cycleFound = true
indirects--
break
}
f.pointers[addr] = f.depth
ve = ve.Elem()
if ve.Kind() == reflect.Interface {
if ve.IsNil() {
nilFound = true
break
}
ve = ve.Elem()
}
}
// Display type or indirection level depending on flags.
if showTypes && !f.ignoreNextType {
f.fs.Write(openParenBytes)
f.fs.Write(bytes.Repeat(asteriskBytes, indirects))
f.fs.Write([]byte(ve.Type().String()))
f.fs.Write(closeParenBytes)
} else {
if nilFound || cycleFound {
indirects += strings.Count(ve.Type().String(), "*")
}
f.fs.Write(openAngleBytes)
f.fs.Write([]byte(strings.Repeat("*", indirects)))
f.fs.Write(closeAngleBytes)
}
// Display pointer information depending on flags.
if f.fs.Flag('+') && (len(pointerChain) > 0) {
f.fs.Write(openParenBytes)
for i, addr := range pointerChain {
if i > 0 {
f.fs.Write(pointerChainBytes)
}
printHexPtr(f.fs, addr)
}
f.fs.Write(closeParenBytes)
}
// Display dereferenced value.
switch {
case nilFound:
f.fs.Write(nilAngleBytes)
case cycleFound:
f.fs.Write(circularShortBytes)
default:
f.ignoreNextType = true
f.format(ve)
}
} | [
"func",
"(",
"f",
"*",
"formatState",
")",
"formatPtr",
"(",
"v",
"reflect",
".",
"Value",
")",
"{",
"// Display nil if top level pointer is nil.",
"showTypes",
":=",
"f",
".",
"fs",
".",
"Flag",
"(",
"'#'",
")",
"\n",
"if",
"v",
".",
"IsNil",
"(",
")",
... | // formatPtr handles formatting of pointers by indirecting them as necessary. | [
"formatPtr",
"handles",
"formatting",
"of",
"pointers",
"by",
"indirecting",
"them",
"as",
"necessary",
"."
] | d8f796af33cc11cb798c1aaeb27a4ebc5099927d | https://github.com/davecgh/go-spew/blob/d8f796af33cc11cb798c1aaeb27a4ebc5099927d/spew/format.go#L105-L195 | train |
davecgh/go-spew | spew/format.go | Format | func (f *formatState) Format(fs fmt.State, verb rune) {
f.fs = fs
// Use standard formatting for verbs that are not v.
if verb != 'v' {
format := f.constructOrigFormat(verb)
fmt.Fprintf(fs, format, f.value)
return
}
if f.value == nil {
if fs.Flag('#') {
fs.Write(interfaceBytes)
}
fs.Write(nilAngleBytes)
return
}
f.format(reflect.ValueOf(f.value))
} | go | func (f *formatState) Format(fs fmt.State, verb rune) {
f.fs = fs
// Use standard formatting for verbs that are not v.
if verb != 'v' {
format := f.constructOrigFormat(verb)
fmt.Fprintf(fs, format, f.value)
return
}
if f.value == nil {
if fs.Flag('#') {
fs.Write(interfaceBytes)
}
fs.Write(nilAngleBytes)
return
}
f.format(reflect.ValueOf(f.value))
} | [
"func",
"(",
"f",
"*",
"formatState",
")",
"Format",
"(",
"fs",
"fmt",
".",
"State",
",",
"verb",
"rune",
")",
"{",
"f",
".",
"fs",
"=",
"fs",
"\n\n",
"// Use standard formatting for verbs that are not v.",
"if",
"verb",
"!=",
"'v'",
"{",
"format",
":=",
... | // Format satisfies the fmt.Formatter interface. See NewFormatter for usage
// details. | [
"Format",
"satisfies",
"the",
"fmt",
".",
"Formatter",
"interface",
".",
"See",
"NewFormatter",
"for",
"usage",
"details",
"."
] | d8f796af33cc11cb798c1aaeb27a4ebc5099927d | https://github.com/davecgh/go-spew/blob/d8f796af33cc11cb798c1aaeb27a4ebc5099927d/spew/format.go#L371-L390 | train |
davecgh/go-spew | spew/format.go | newFormatter | func newFormatter(cs *ConfigState, v interface{}) fmt.Formatter {
fs := &formatState{value: v, cs: cs}
fs.pointers = make(map[uintptr]int)
return fs
} | go | func newFormatter(cs *ConfigState, v interface{}) fmt.Formatter {
fs := &formatState{value: v, cs: cs}
fs.pointers = make(map[uintptr]int)
return fs
} | [
"func",
"newFormatter",
"(",
"cs",
"*",
"ConfigState",
",",
"v",
"interface",
"{",
"}",
")",
"fmt",
".",
"Formatter",
"{",
"fs",
":=",
"&",
"formatState",
"{",
"value",
":",
"v",
",",
"cs",
":",
"cs",
"}",
"\n",
"fs",
".",
"pointers",
"=",
"make",
... | // newFormatter is a helper function to consolidate the logic from the various
// public methods which take varying config states. | [
"newFormatter",
"is",
"a",
"helper",
"function",
"to",
"consolidate",
"the",
"logic",
"from",
"the",
"various",
"public",
"methods",
"which",
"take",
"varying",
"config",
"states",
"."
] | d8f796af33cc11cb798c1aaeb27a4ebc5099927d | https://github.com/davecgh/go-spew/blob/d8f796af33cc11cb798c1aaeb27a4ebc5099927d/spew/format.go#L394-L398 | train |
davecgh/go-spew | spew/dump.go | indent | func (d *dumpState) indent() {
if d.ignoreNextIndent {
d.ignoreNextIndent = false
return
}
d.w.Write(bytes.Repeat([]byte(d.cs.Indent), d.depth))
} | go | func (d *dumpState) indent() {
if d.ignoreNextIndent {
d.ignoreNextIndent = false
return
}
d.w.Write(bytes.Repeat([]byte(d.cs.Indent), d.depth))
} | [
"func",
"(",
"d",
"*",
"dumpState",
")",
"indent",
"(",
")",
"{",
"if",
"d",
".",
"ignoreNextIndent",
"{",
"d",
".",
"ignoreNextIndent",
"=",
"false",
"\n",
"return",
"\n",
"}",
"\n",
"d",
".",
"w",
".",
"Write",
"(",
"bytes",
".",
"Repeat",
"(",
... | // indent performs indentation according to the depth level and cs.Indent
// option. | [
"indent",
"performs",
"indentation",
"according",
"to",
"the",
"depth",
"level",
"and",
"cs",
".",
"Indent",
"option",
"."
] | d8f796af33cc11cb798c1aaeb27a4ebc5099927d | https://github.com/davecgh/go-spew/blob/d8f796af33cc11cb798c1aaeb27a4ebc5099927d/spew/dump.go#L62-L68 | train |
davecgh/go-spew | spew/dump.go | unpackValue | func (d *dumpState) unpackValue(v reflect.Value) reflect.Value {
if v.Kind() == reflect.Interface && !v.IsNil() {
v = v.Elem()
}
return v
} | go | func (d *dumpState) unpackValue(v reflect.Value) reflect.Value {
if v.Kind() == reflect.Interface && !v.IsNil() {
v = v.Elem()
}
return v
} | [
"func",
"(",
"d",
"*",
"dumpState",
")",
"unpackValue",
"(",
"v",
"reflect",
".",
"Value",
")",
"reflect",
".",
"Value",
"{",
"if",
"v",
".",
"Kind",
"(",
")",
"==",
"reflect",
".",
"Interface",
"&&",
"!",
"v",
".",
"IsNil",
"(",
")",
"{",
"v",
... | // unpackValue returns values inside of non-nil interfaces when possible.
// This is useful for data types like structs, arrays, slices, and maps which
// can contain varying types packed inside an interface. | [
"unpackValue",
"returns",
"values",
"inside",
"of",
"non",
"-",
"nil",
"interfaces",
"when",
"possible",
".",
"This",
"is",
"useful",
"for",
"data",
"types",
"like",
"structs",
"arrays",
"slices",
"and",
"maps",
"which",
"can",
"contain",
"varying",
"types",
... | d8f796af33cc11cb798c1aaeb27a4ebc5099927d | https://github.com/davecgh/go-spew/blob/d8f796af33cc11cb798c1aaeb27a4ebc5099927d/spew/dump.go#L73-L78 | train |
davecgh/go-spew | spew/dump.go | dumpPtr | func (d *dumpState) dumpPtr(v reflect.Value) {
// Remove pointers at or below the current depth from map used to detect
// circular refs.
for k, depth := range d.pointers {
if depth >= d.depth {
delete(d.pointers, k)
}
}
// Keep list of all dereferenced pointers to show later.
pointerChain := make([]uintptr, 0)
// Figure out how many levels of indirection there are by dereferencing
// pointers and unpacking interfaces down the chain while detecting circular
// references.
nilFound := false
cycleFound := false
indirects := 0
ve := v
for ve.Kind() == reflect.Ptr {
if ve.IsNil() {
nilFound = true
break
}
indirects++
addr := ve.Pointer()
pointerChain = append(pointerChain, addr)
if pd, ok := d.pointers[addr]; ok && pd < d.depth {
cycleFound = true
indirects--
break
}
d.pointers[addr] = d.depth
ve = ve.Elem()
if ve.Kind() == reflect.Interface {
if ve.IsNil() {
nilFound = true
break
}
ve = ve.Elem()
}
}
// Display type information.
d.w.Write(openParenBytes)
d.w.Write(bytes.Repeat(asteriskBytes, indirects))
d.w.Write([]byte(ve.Type().String()))
d.w.Write(closeParenBytes)
// Display pointer information.
if !d.cs.DisablePointerAddresses && len(pointerChain) > 0 {
d.w.Write(openParenBytes)
for i, addr := range pointerChain {
if i > 0 {
d.w.Write(pointerChainBytes)
}
printHexPtr(d.w, addr)
}
d.w.Write(closeParenBytes)
}
// Display dereferenced value.
d.w.Write(openParenBytes)
switch {
case nilFound:
d.w.Write(nilAngleBytes)
case cycleFound:
d.w.Write(circularBytes)
default:
d.ignoreNextType = true
d.dump(ve)
}
d.w.Write(closeParenBytes)
} | go | func (d *dumpState) dumpPtr(v reflect.Value) {
// Remove pointers at or below the current depth from map used to detect
// circular refs.
for k, depth := range d.pointers {
if depth >= d.depth {
delete(d.pointers, k)
}
}
// Keep list of all dereferenced pointers to show later.
pointerChain := make([]uintptr, 0)
// Figure out how many levels of indirection there are by dereferencing
// pointers and unpacking interfaces down the chain while detecting circular
// references.
nilFound := false
cycleFound := false
indirects := 0
ve := v
for ve.Kind() == reflect.Ptr {
if ve.IsNil() {
nilFound = true
break
}
indirects++
addr := ve.Pointer()
pointerChain = append(pointerChain, addr)
if pd, ok := d.pointers[addr]; ok && pd < d.depth {
cycleFound = true
indirects--
break
}
d.pointers[addr] = d.depth
ve = ve.Elem()
if ve.Kind() == reflect.Interface {
if ve.IsNil() {
nilFound = true
break
}
ve = ve.Elem()
}
}
// Display type information.
d.w.Write(openParenBytes)
d.w.Write(bytes.Repeat(asteriskBytes, indirects))
d.w.Write([]byte(ve.Type().String()))
d.w.Write(closeParenBytes)
// Display pointer information.
if !d.cs.DisablePointerAddresses && len(pointerChain) > 0 {
d.w.Write(openParenBytes)
for i, addr := range pointerChain {
if i > 0 {
d.w.Write(pointerChainBytes)
}
printHexPtr(d.w, addr)
}
d.w.Write(closeParenBytes)
}
// Display dereferenced value.
d.w.Write(openParenBytes)
switch {
case nilFound:
d.w.Write(nilAngleBytes)
case cycleFound:
d.w.Write(circularBytes)
default:
d.ignoreNextType = true
d.dump(ve)
}
d.w.Write(closeParenBytes)
} | [
"func",
"(",
"d",
"*",
"dumpState",
")",
"dumpPtr",
"(",
"v",
"reflect",
".",
"Value",
")",
"{",
"// Remove pointers at or below the current depth from map used to detect",
"// circular refs.",
"for",
"k",
",",
"depth",
":=",
"range",
"d",
".",
"pointers",
"{",
"i... | // dumpPtr handles formatting of pointers by indirecting them as necessary. | [
"dumpPtr",
"handles",
"formatting",
"of",
"pointers",
"by",
"indirecting",
"them",
"as",
"necessary",
"."
] | d8f796af33cc11cb798c1aaeb27a4ebc5099927d | https://github.com/davecgh/go-spew/blob/d8f796af33cc11cb798c1aaeb27a4ebc5099927d/spew/dump.go#L81-L157 | train |
davecgh/go-spew | spew/dump.go | fdump | func fdump(cs *ConfigState, w io.Writer, a ...interface{}) {
for _, arg := range a {
if arg == nil {
w.Write(interfaceBytes)
w.Write(spaceBytes)
w.Write(nilAngleBytes)
w.Write(newlineBytes)
continue
}
d := dumpState{w: w, cs: cs}
d.pointers = make(map[uintptr]int)
d.dump(reflect.ValueOf(arg))
d.w.Write(newlineBytes)
}
} | go | func fdump(cs *ConfigState, w io.Writer, a ...interface{}) {
for _, arg := range a {
if arg == nil {
w.Write(interfaceBytes)
w.Write(spaceBytes)
w.Write(nilAngleBytes)
w.Write(newlineBytes)
continue
}
d := dumpState{w: w, cs: cs}
d.pointers = make(map[uintptr]int)
d.dump(reflect.ValueOf(arg))
d.w.Write(newlineBytes)
}
} | [
"func",
"fdump",
"(",
"cs",
"*",
"ConfigState",
",",
"w",
"io",
".",
"Writer",
",",
"a",
"...",
"interface",
"{",
"}",
")",
"{",
"for",
"_",
",",
"arg",
":=",
"range",
"a",
"{",
"if",
"arg",
"==",
"nil",
"{",
"w",
".",
"Write",
"(",
"interfaceB... | // fdump is a helper function to consolidate the logic from the various public
// methods which take varying writers and config states. | [
"fdump",
"is",
"a",
"helper",
"function",
"to",
"consolidate",
"the",
"logic",
"from",
"the",
"various",
"public",
"methods",
"which",
"take",
"varying",
"writers",
"and",
"config",
"states",
"."
] | d8f796af33cc11cb798c1aaeb27a4ebc5099927d | https://github.com/davecgh/go-spew/blob/d8f796af33cc11cb798c1aaeb27a4ebc5099927d/spew/dump.go#L453-L468 | train |
davecgh/go-spew | spew/dump.go | Sdump | func Sdump(a ...interface{}) string {
var buf bytes.Buffer
fdump(&Config, &buf, a...)
return buf.String()
} | go | func Sdump(a ...interface{}) string {
var buf bytes.Buffer
fdump(&Config, &buf, a...)
return buf.String()
} | [
"func",
"Sdump",
"(",
"a",
"...",
"interface",
"{",
"}",
")",
"string",
"{",
"var",
"buf",
"bytes",
".",
"Buffer",
"\n",
"fdump",
"(",
"&",
"Config",
",",
"&",
"buf",
",",
"a",
"...",
")",
"\n",
"return",
"buf",
".",
"String",
"(",
")",
"\n",
"... | // Sdump returns a string with the passed arguments formatted exactly the same
// as Dump. | [
"Sdump",
"returns",
"a",
"string",
"with",
"the",
"passed",
"arguments",
"formatted",
"exactly",
"the",
"same",
"as",
"Dump",
"."
] | d8f796af33cc11cb798c1aaeb27a4ebc5099927d | https://github.com/davecgh/go-spew/blob/d8f796af33cc11cb798c1aaeb27a4ebc5099927d/spew/dump.go#L478-L482 | train |
jackc/pgx | pgtype/uuid.go | parseUUID | func parseUUID(src string) (dst [16]byte, err error) {
if len(src) < 36 {
return dst, errors.Errorf("cannot parse UUID %v", src)
}
src = src[0:8] + src[9:13] + src[14:18] + src[19:23] + src[24:]
buf, err := hex.DecodeString(src)
if err != nil {
return dst, err
}
copy(dst[:], buf)
return dst, err
} | go | func parseUUID(src string) (dst [16]byte, err error) {
if len(src) < 36 {
return dst, errors.Errorf("cannot parse UUID %v", src)
}
src = src[0:8] + src[9:13] + src[14:18] + src[19:23] + src[24:]
buf, err := hex.DecodeString(src)
if err != nil {
return dst, err
}
copy(dst[:], buf)
return dst, err
} | [
"func",
"parseUUID",
"(",
"src",
"string",
")",
"(",
"dst",
"[",
"16",
"]",
"byte",
",",
"err",
"error",
")",
"{",
"if",
"len",
"(",
"src",
")",
"<",
"36",
"{",
"return",
"dst",
",",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"src",
")",
... | // parseUUID converts a string UUID in standard form to a byte array. | [
"parseUUID",
"converts",
"a",
"string",
"UUID",
"in",
"standard",
"form",
"to",
"a",
"byte",
"array",
"."
] | 25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc | https://github.com/jackc/pgx/blob/25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc/pgtype/uuid.go#L89-L101 | train |
jackc/pgx | pgtype/uuid.go | encodeUUID | func encodeUUID(src [16]byte) string {
return fmt.Sprintf("%x-%x-%x-%x-%x", src[0:4], src[4:6], src[6:8], src[8:10], src[10:16])
} | go | func encodeUUID(src [16]byte) string {
return fmt.Sprintf("%x-%x-%x-%x-%x", src[0:4], src[4:6], src[6:8], src[8:10], src[10:16])
} | [
"func",
"encodeUUID",
"(",
"src",
"[",
"16",
"]",
"byte",
")",
"string",
"{",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"src",
"[",
"0",
":",
"4",
"]",
",",
"src",
"[",
"4",
":",
"6",
"]",
",",
"src",
"[",
"6",
":",
"8",
"]",
... | // encodeUUID converts a uuid byte array to UUID standard string form. | [
"encodeUUID",
"converts",
"a",
"uuid",
"byte",
"array",
"to",
"UUID",
"standard",
"string",
"form",
"."
] | 25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc | https://github.com/jackc/pgx/blob/25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc/pgtype/uuid.go#L104-L106 | train |
jackc/pgx | pgtype/pgtype.go | DeepCopy | func (ci *ConnInfo) DeepCopy() *ConnInfo {
ci2 := &ConnInfo{
oidToDataType: make(map[OID]*DataType, len(ci.oidToDataType)),
nameToDataType: make(map[string]*DataType, len(ci.nameToDataType)),
reflectTypeToDataType: make(map[reflect.Type]*DataType, len(ci.reflectTypeToDataType)),
}
for _, dt := range ci.oidToDataType {
ci2.RegisterDataType(DataType{
Value: reflect.New(reflect.ValueOf(dt.Value).Elem().Type()).Interface().(Value),
Name: dt.Name,
OID: dt.OID,
})
}
return ci2
} | go | func (ci *ConnInfo) DeepCopy() *ConnInfo {
ci2 := &ConnInfo{
oidToDataType: make(map[OID]*DataType, len(ci.oidToDataType)),
nameToDataType: make(map[string]*DataType, len(ci.nameToDataType)),
reflectTypeToDataType: make(map[reflect.Type]*DataType, len(ci.reflectTypeToDataType)),
}
for _, dt := range ci.oidToDataType {
ci2.RegisterDataType(DataType{
Value: reflect.New(reflect.ValueOf(dt.Value).Elem().Type()).Interface().(Value),
Name: dt.Name,
OID: dt.OID,
})
}
return ci2
} | [
"func",
"(",
"ci",
"*",
"ConnInfo",
")",
"DeepCopy",
"(",
")",
"*",
"ConnInfo",
"{",
"ci2",
":=",
"&",
"ConnInfo",
"{",
"oidToDataType",
":",
"make",
"(",
"map",
"[",
"OID",
"]",
"*",
"DataType",
",",
"len",
"(",
"ci",
".",
"oidToDataType",
")",
")... | // DeepCopy makes a deep copy of the ConnInfo. | [
"DeepCopy",
"makes",
"a",
"deep",
"copy",
"of",
"the",
"ConnInfo",
"."
] | 25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc | https://github.com/jackc/pgx/blob/25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc/pgtype/pgtype.go#L192-L208 | train |
jackc/pgx | pgtype/timestamp.go | Set | func (dst *Timestamp) Set(src interface{}) error {
if src == nil {
*dst = Timestamp{Status: Null}
return nil
}
switch value := src.(type) {
case time.Time:
*dst = Timestamp{Time: time.Date(value.Year(), value.Month(), value.Day(), value.Hour(), value.Minute(), value.Second(), value.Nanosecond(), time.UTC), Status: Present}
default:
if originalSrc, ok := underlyingTimeType(src); ok {
return dst.Set(originalSrc)
}
return errors.Errorf("cannot convert %v to Timestamp", value)
}
return nil
} | go | func (dst *Timestamp) Set(src interface{}) error {
if src == nil {
*dst = Timestamp{Status: Null}
return nil
}
switch value := src.(type) {
case time.Time:
*dst = Timestamp{Time: time.Date(value.Year(), value.Month(), value.Day(), value.Hour(), value.Minute(), value.Second(), value.Nanosecond(), time.UTC), Status: Present}
default:
if originalSrc, ok := underlyingTimeType(src); ok {
return dst.Set(originalSrc)
}
return errors.Errorf("cannot convert %v to Timestamp", value)
}
return nil
} | [
"func",
"(",
"dst",
"*",
"Timestamp",
")",
"Set",
"(",
"src",
"interface",
"{",
"}",
")",
"error",
"{",
"if",
"src",
"==",
"nil",
"{",
"*",
"dst",
"=",
"Timestamp",
"{",
"Status",
":",
"Null",
"}",
"\n",
"return",
"nil",
"\n",
"}",
"\n\n",
"switc... | // Set converts src into a Timestamp and stores in dst. If src is a
// time.Time in a non-UTC time zone, the time zone is discarded. | [
"Set",
"converts",
"src",
"into",
"a",
"Timestamp",
"and",
"stores",
"in",
"dst",
".",
"If",
"src",
"is",
"a",
"time",
".",
"Time",
"in",
"a",
"non",
"-",
"UTC",
"time",
"zone",
"the",
"time",
"zone",
"is",
"discarded",
"."
] | 25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc | https://github.com/jackc/pgx/blob/25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc/pgtype/timestamp.go#L27-L44 | train |
jackc/pgx | pgtype/timestamp.go | DecodeText | func (dst *Timestamp) DecodeText(ci *ConnInfo, src []byte) error {
if src == nil {
*dst = Timestamp{Status: Null}
return nil
}
sbuf := string(src)
switch sbuf {
case "infinity":
*dst = Timestamp{Status: Present, InfinityModifier: Infinity}
case "-infinity":
*dst = Timestamp{Status: Present, InfinityModifier: -Infinity}
default:
tim, err := time.Parse(pgTimestampFormat, sbuf)
if err != nil {
return err
}
*dst = Timestamp{Time: tim, Status: Present}
}
return nil
} | go | func (dst *Timestamp) DecodeText(ci *ConnInfo, src []byte) error {
if src == nil {
*dst = Timestamp{Status: Null}
return nil
}
sbuf := string(src)
switch sbuf {
case "infinity":
*dst = Timestamp{Status: Present, InfinityModifier: Infinity}
case "-infinity":
*dst = Timestamp{Status: Present, InfinityModifier: -Infinity}
default:
tim, err := time.Parse(pgTimestampFormat, sbuf)
if err != nil {
return err
}
*dst = Timestamp{Time: tim, Status: Present}
}
return nil
} | [
"func",
"(",
"dst",
"*",
"Timestamp",
")",
"DecodeText",
"(",
"ci",
"*",
"ConnInfo",
",",
"src",
"[",
"]",
"byte",
")",
"error",
"{",
"if",
"src",
"==",
"nil",
"{",
"*",
"dst",
"=",
"Timestamp",
"{",
"Status",
":",
"Null",
"}",
"\n",
"return",
"n... | // DecodeText decodes from src into dst. The decoded time is considered to
// be in UTC. | [
"DecodeText",
"decodes",
"from",
"src",
"into",
"dst",
".",
"The",
"decoded",
"time",
"is",
"considered",
"to",
"be",
"in",
"UTC",
"."
] | 25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc | https://github.com/jackc/pgx/blob/25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc/pgtype/timestamp.go#L84-L106 | train |
jackc/pgx | pgtype/timestamp.go | EncodeText | func (src *Timestamp) EncodeText(ci *ConnInfo, buf []byte) ([]byte, error) {
switch src.Status {
case Null:
return nil, nil
case Undefined:
return nil, errUndefined
}
if src.Time.Location() != time.UTC {
return nil, errors.Errorf("cannot encode non-UTC time into timestamp")
}
var s string
switch src.InfinityModifier {
case None:
s = src.Time.Format(pgTimestampFormat)
case Infinity:
s = "infinity"
case NegativeInfinity:
s = "-infinity"
}
return append(buf, s...), nil
} | go | func (src *Timestamp) EncodeText(ci *ConnInfo, buf []byte) ([]byte, error) {
switch src.Status {
case Null:
return nil, nil
case Undefined:
return nil, errUndefined
}
if src.Time.Location() != time.UTC {
return nil, errors.Errorf("cannot encode non-UTC time into timestamp")
}
var s string
switch src.InfinityModifier {
case None:
s = src.Time.Format(pgTimestampFormat)
case Infinity:
s = "infinity"
case NegativeInfinity:
s = "-infinity"
}
return append(buf, s...), nil
} | [
"func",
"(",
"src",
"*",
"Timestamp",
")",
"EncodeText",
"(",
"ci",
"*",
"ConnInfo",
",",
"buf",
"[",
"]",
"byte",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"switch",
"src",
".",
"Status",
"{",
"case",
"Null",
":",
"return",
"nil",
",",... | // EncodeText writes the text encoding of src into w. If src.Time is not in
// the UTC time zone it returns an error. | [
"EncodeText",
"writes",
"the",
"text",
"encoding",
"of",
"src",
"into",
"w",
".",
"If",
"src",
".",
"Time",
"is",
"not",
"in",
"the",
"UTC",
"time",
"zone",
"it",
"returns",
"an",
"error",
"."
] | 25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc | https://github.com/jackc/pgx/blob/25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc/pgtype/timestamp.go#L138-L161 | train |
jackc/pgx | pgtype/timestamp.go | EncodeBinary | func (src *Timestamp) EncodeBinary(ci *ConnInfo, buf []byte) ([]byte, error) {
switch src.Status {
case Null:
return nil, nil
case Undefined:
return nil, errUndefined
}
if src.Time.Location() != time.UTC {
return nil, errors.Errorf("cannot encode non-UTC time into timestamp")
}
var microsecSinceY2K int64
switch src.InfinityModifier {
case None:
microsecSinceUnixEpoch := src.Time.Unix()*1000000 + int64(src.Time.Nanosecond())/1000
microsecSinceY2K = microsecSinceUnixEpoch - microsecFromUnixEpochToY2K
case Infinity:
microsecSinceY2K = infinityMicrosecondOffset
case NegativeInfinity:
microsecSinceY2K = negativeInfinityMicrosecondOffset
}
return pgio.AppendInt64(buf, microsecSinceY2K), nil
} | go | func (src *Timestamp) EncodeBinary(ci *ConnInfo, buf []byte) ([]byte, error) {
switch src.Status {
case Null:
return nil, nil
case Undefined:
return nil, errUndefined
}
if src.Time.Location() != time.UTC {
return nil, errors.Errorf("cannot encode non-UTC time into timestamp")
}
var microsecSinceY2K int64
switch src.InfinityModifier {
case None:
microsecSinceUnixEpoch := src.Time.Unix()*1000000 + int64(src.Time.Nanosecond())/1000
microsecSinceY2K = microsecSinceUnixEpoch - microsecFromUnixEpochToY2K
case Infinity:
microsecSinceY2K = infinityMicrosecondOffset
case NegativeInfinity:
microsecSinceY2K = negativeInfinityMicrosecondOffset
}
return pgio.AppendInt64(buf, microsecSinceY2K), nil
} | [
"func",
"(",
"src",
"*",
"Timestamp",
")",
"EncodeBinary",
"(",
"ci",
"*",
"ConnInfo",
",",
"buf",
"[",
"]",
"byte",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"switch",
"src",
".",
"Status",
"{",
"case",
"Null",
":",
"return",
"nil",
",... | // EncodeBinary writes the binary encoding of src into w. If src.Time is not in
// the UTC time zone it returns an error. | [
"EncodeBinary",
"writes",
"the",
"binary",
"encoding",
"of",
"src",
"into",
"w",
".",
"If",
"src",
".",
"Time",
"is",
"not",
"in",
"the",
"UTC",
"time",
"zone",
"it",
"returns",
"an",
"error",
"."
] | 25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc | https://github.com/jackc/pgx/blob/25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc/pgtype/timestamp.go#L165-L188 | train |
jackc/pgx | batch.go | Queue | func (b *Batch) Queue(query string, arguments []interface{}, parameterOIDs []pgtype.OID, resultFormatCodes []int16) {
b.items = append(b.items, &batchItem{
query: query,
arguments: arguments,
parameterOIDs: parameterOIDs,
resultFormatCodes: resultFormatCodes,
})
} | go | func (b *Batch) Queue(query string, arguments []interface{}, parameterOIDs []pgtype.OID, resultFormatCodes []int16) {
b.items = append(b.items, &batchItem{
query: query,
arguments: arguments,
parameterOIDs: parameterOIDs,
resultFormatCodes: resultFormatCodes,
})
} | [
"func",
"(",
"b",
"*",
"Batch",
")",
"Queue",
"(",
"query",
"string",
",",
"arguments",
"[",
"]",
"interface",
"{",
"}",
",",
"parameterOIDs",
"[",
"]",
"pgtype",
".",
"OID",
",",
"resultFormatCodes",
"[",
"]",
"int16",
")",
"{",
"b",
".",
"items",
... | // Queue queues a query to batch b. parameterOIDs are required if there are
// parameters and query is not the name of a prepared statement.
// resultFormatCodes are required if there is a result. | [
"Queue",
"queues",
"a",
"query",
"to",
"batch",
"b",
".",
"parameterOIDs",
"are",
"required",
"if",
"there",
"are",
"parameters",
"and",
"query",
"is",
"not",
"the",
"name",
"of",
"a",
"prepared",
"statement",
".",
"resultFormatCodes",
"are",
"required",
"if... | 25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc | https://github.com/jackc/pgx/blob/25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc/batch.go#L49-L56 | train |
jackc/pgx | batch.go | ExecResults | func (b *Batch) ExecResults() (CommandTag, error) {
if b.err != nil {
return "", b.err
}
select {
case <-b.ctx.Done():
b.die(b.ctx.Err())
return "", b.ctx.Err()
default:
}
if err := b.ensureCommandComplete(); err != nil {
b.die(err)
return "", err
}
b.resultsRead++
b.pendingCommandComplete = true
for {
msg, err := b.conn.rxMsg()
if err != nil {
return "", err
}
switch msg := msg.(type) {
case *pgproto3.CommandComplete:
b.pendingCommandComplete = false
return CommandTag(msg.CommandTag), nil
default:
if err := b.conn.processContextFreeMsg(msg); err != nil {
return "", err
}
}
}
} | go | func (b *Batch) ExecResults() (CommandTag, error) {
if b.err != nil {
return "", b.err
}
select {
case <-b.ctx.Done():
b.die(b.ctx.Err())
return "", b.ctx.Err()
default:
}
if err := b.ensureCommandComplete(); err != nil {
b.die(err)
return "", err
}
b.resultsRead++
b.pendingCommandComplete = true
for {
msg, err := b.conn.rxMsg()
if err != nil {
return "", err
}
switch msg := msg.(type) {
case *pgproto3.CommandComplete:
b.pendingCommandComplete = false
return CommandTag(msg.CommandTag), nil
default:
if err := b.conn.processContextFreeMsg(msg); err != nil {
return "", err
}
}
}
} | [
"func",
"(",
"b",
"*",
"Batch",
")",
"ExecResults",
"(",
")",
"(",
"CommandTag",
",",
"error",
")",
"{",
"if",
"b",
".",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"b",
".",
"err",
"\n",
"}",
"\n\n",
"select",
"{",
"case",
"<-",
"b",
... | // ExecResults reads the results from the next query in the batch as if the
// query has been sent with Exec. | [
"ExecResults",
"reads",
"the",
"results",
"from",
"the",
"next",
"query",
"in",
"the",
"batch",
"as",
"if",
"the",
"query",
"has",
"been",
"sent",
"with",
"Exec",
"."
] | 25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc | https://github.com/jackc/pgx/blob/25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc/batch.go#L163-L200 | train |
jackc/pgx | batch.go | QueryResults | func (b *Batch) QueryResults() (*Rows, error) {
rows := b.conn.getRows("batch query", nil)
if b.err != nil {
rows.fatal(b.err)
return rows, b.err
}
select {
case <-b.ctx.Done():
b.die(b.ctx.Err())
rows.fatal(b.err)
return rows, b.ctx.Err()
default:
}
if err := b.ensureCommandComplete(); err != nil {
b.die(err)
rows.fatal(err)
return rows, err
}
b.resultsRead++
b.pendingCommandComplete = true
fieldDescriptions, err := b.conn.readUntilRowDescription()
if err != nil {
b.die(err)
rows.fatal(b.err)
return rows, err
}
rows.batch = b
rows.fields = fieldDescriptions
return rows, nil
} | go | func (b *Batch) QueryResults() (*Rows, error) {
rows := b.conn.getRows("batch query", nil)
if b.err != nil {
rows.fatal(b.err)
return rows, b.err
}
select {
case <-b.ctx.Done():
b.die(b.ctx.Err())
rows.fatal(b.err)
return rows, b.ctx.Err()
default:
}
if err := b.ensureCommandComplete(); err != nil {
b.die(err)
rows.fatal(err)
return rows, err
}
b.resultsRead++
b.pendingCommandComplete = true
fieldDescriptions, err := b.conn.readUntilRowDescription()
if err != nil {
b.die(err)
rows.fatal(b.err)
return rows, err
}
rows.batch = b
rows.fields = fieldDescriptions
return rows, nil
} | [
"func",
"(",
"b",
"*",
"Batch",
")",
"QueryResults",
"(",
")",
"(",
"*",
"Rows",
",",
"error",
")",
"{",
"rows",
":=",
"b",
".",
"conn",
".",
"getRows",
"(",
"\"",
"\"",
",",
"nil",
")",
"\n\n",
"if",
"b",
".",
"err",
"!=",
"nil",
"{",
"rows"... | // QueryResults reads the results from the next query in the batch as if the
// query has been sent with Query. | [
"QueryResults",
"reads",
"the",
"results",
"from",
"the",
"next",
"query",
"in",
"the",
"batch",
"as",
"if",
"the",
"query",
"has",
"been",
"sent",
"with",
"Query",
"."
] | 25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc | https://github.com/jackc/pgx/blob/25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc/batch.go#L204-L240 | train |
jackc/pgx | batch.go | QueryRowResults | func (b *Batch) QueryRowResults() *Row {
rows, _ := b.QueryResults()
return (*Row)(rows)
} | go | func (b *Batch) QueryRowResults() *Row {
rows, _ := b.QueryResults()
return (*Row)(rows)
} | [
"func",
"(",
"b",
"*",
"Batch",
")",
"QueryRowResults",
"(",
")",
"*",
"Row",
"{",
"rows",
",",
"_",
":=",
"b",
".",
"QueryResults",
"(",
")",
"\n",
"return",
"(",
"*",
"Row",
")",
"(",
"rows",
")",
"\n\n",
"}"
] | // QueryRowResults reads the results from the next query in the batch as if the
// query has been sent with QueryRow. | [
"QueryRowResults",
"reads",
"the",
"results",
"from",
"the",
"next",
"query",
"in",
"the",
"batch",
"as",
"if",
"the",
"query",
"has",
"been",
"sent",
"with",
"QueryRow",
"."
] | 25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc | https://github.com/jackc/pgx/blob/25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc/batch.go#L244-L248 | train |
jackc/pgx | batch.go | Close | func (b *Batch) Close() (err error) {
if b.err != nil {
return b.err
}
defer func() {
err = b.conn.termContext(err)
if b.conn != nil && b.connPool != nil {
b.connPool.Release(b.conn)
}
}()
for i := b.resultsRead; i < len(b.items); i++ {
if _, err = b.ExecResults(); err != nil {
return err
}
}
if err = b.conn.ensureConnectionReadyForQuery(); err != nil {
return err
}
return nil
} | go | func (b *Batch) Close() (err error) {
if b.err != nil {
return b.err
}
defer func() {
err = b.conn.termContext(err)
if b.conn != nil && b.connPool != nil {
b.connPool.Release(b.conn)
}
}()
for i := b.resultsRead; i < len(b.items); i++ {
if _, err = b.ExecResults(); err != nil {
return err
}
}
if err = b.conn.ensureConnectionReadyForQuery(); err != nil {
return err
}
return nil
} | [
"func",
"(",
"b",
"*",
"Batch",
")",
"Close",
"(",
")",
"(",
"err",
"error",
")",
"{",
"if",
"b",
".",
"err",
"!=",
"nil",
"{",
"return",
"b",
".",
"err",
"\n",
"}",
"\n\n",
"defer",
"func",
"(",
")",
"{",
"err",
"=",
"b",
".",
"conn",
".",... | // Close closes the batch operation. Any error that occured during a batch
// operation may have made it impossible to resyncronize the connection with the
// server. In this case the underlying connection will have been closed. | [
"Close",
"closes",
"the",
"batch",
"operation",
".",
"Any",
"error",
"that",
"occured",
"during",
"a",
"batch",
"operation",
"may",
"have",
"made",
"it",
"impossible",
"to",
"resyncronize",
"the",
"connection",
"with",
"the",
"server",
".",
"In",
"this",
"ca... | 25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc | https://github.com/jackc/pgx/blob/25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc/batch.go#L253-L276 | train |
jackc/pgx | tx.go | Begin | func (c *Conn) Begin() (*Tx, error) {
return c.BeginEx(context.Background(), nil)
} | go | func (c *Conn) Begin() (*Tx, error) {
return c.BeginEx(context.Background(), nil)
} | [
"func",
"(",
"c",
"*",
"Conn",
")",
"Begin",
"(",
")",
"(",
"*",
"Tx",
",",
"error",
")",
"{",
"return",
"c",
".",
"BeginEx",
"(",
"context",
".",
"Background",
"(",
")",
",",
"nil",
")",
"\n",
"}"
] | // Begin starts a transaction with the default transaction mode for the
// current connection. To use a specific transaction mode see BeginEx. | [
"Begin",
"starts",
"a",
"transaction",
"with",
"the",
"default",
"transaction",
"mode",
"for",
"the",
"current",
"connection",
".",
"To",
"use",
"a",
"specific",
"transaction",
"mode",
"see",
"BeginEx",
"."
] | 25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc | https://github.com/jackc/pgx/blob/25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc/tx.go#L84-L86 | train |
jackc/pgx | tx.go | CommitEx | func (tx *Tx) CommitEx(ctx context.Context) error {
if tx.status != TxStatusInProgress {
return ErrTxClosed
}
commandTag, err := tx.conn.ExecEx(ctx, "commit", nil)
if err == nil && commandTag == "COMMIT" {
tx.status = TxStatusCommitSuccess
} else if err == nil && commandTag == "ROLLBACK" {
tx.status = TxStatusCommitFailure
tx.err = ErrTxCommitRollback
} else {
tx.status = TxStatusCommitFailure
tx.err = err
// A commit failure leaves the connection in an undefined state
tx.conn.die(errors.New("commit failed"))
}
if tx.connPool != nil {
tx.connPool.Release(tx.conn)
}
return tx.err
} | go | func (tx *Tx) CommitEx(ctx context.Context) error {
if tx.status != TxStatusInProgress {
return ErrTxClosed
}
commandTag, err := tx.conn.ExecEx(ctx, "commit", nil)
if err == nil && commandTag == "COMMIT" {
tx.status = TxStatusCommitSuccess
} else if err == nil && commandTag == "ROLLBACK" {
tx.status = TxStatusCommitFailure
tx.err = ErrTxCommitRollback
} else {
tx.status = TxStatusCommitFailure
tx.err = err
// A commit failure leaves the connection in an undefined state
tx.conn.die(errors.New("commit failed"))
}
if tx.connPool != nil {
tx.connPool.Release(tx.conn)
}
return tx.err
} | [
"func",
"(",
"tx",
"*",
"Tx",
")",
"CommitEx",
"(",
"ctx",
"context",
".",
"Context",
")",
"error",
"{",
"if",
"tx",
".",
"status",
"!=",
"TxStatusInProgress",
"{",
"return",
"ErrTxClosed",
"\n",
"}",
"\n\n",
"commandTag",
",",
"err",
":=",
"tx",
".",
... | // CommitEx commits the transaction with a context. | [
"CommitEx",
"commits",
"the",
"transaction",
"with",
"a",
"context",
"."
] | 25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc | https://github.com/jackc/pgx/blob/25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc/tx.go#L120-L143 | train |
jackc/pgx | tx.go | RollbackEx | func (tx *Tx) RollbackEx(ctx context.Context) error {
if tx.status != TxStatusInProgress {
return ErrTxClosed
}
_, tx.err = tx.conn.ExecEx(ctx, "rollback", nil)
if tx.err == nil {
tx.status = TxStatusRollbackSuccess
} else {
tx.status = TxStatusRollbackFailure
// A rollback failure leaves the connection in an undefined state
tx.conn.die(errors.New("rollback failed"))
}
if tx.connPool != nil {
tx.connPool.Release(tx.conn)
}
return tx.err
} | go | func (tx *Tx) RollbackEx(ctx context.Context) error {
if tx.status != TxStatusInProgress {
return ErrTxClosed
}
_, tx.err = tx.conn.ExecEx(ctx, "rollback", nil)
if tx.err == nil {
tx.status = TxStatusRollbackSuccess
} else {
tx.status = TxStatusRollbackFailure
// A rollback failure leaves the connection in an undefined state
tx.conn.die(errors.New("rollback failed"))
}
if tx.connPool != nil {
tx.connPool.Release(tx.conn)
}
return tx.err
} | [
"func",
"(",
"tx",
"*",
"Tx",
")",
"RollbackEx",
"(",
"ctx",
"context",
".",
"Context",
")",
"error",
"{",
"if",
"tx",
".",
"status",
"!=",
"TxStatusInProgress",
"{",
"return",
"ErrTxClosed",
"\n",
"}",
"\n\n",
"_",
",",
"tx",
".",
"err",
"=",
"tx",
... | // RollbackEx is the context version of Rollback | [
"RollbackEx",
"is",
"the",
"context",
"version",
"of",
"Rollback"
] | 25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc | https://github.com/jackc/pgx/blob/25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc/tx.go#L156-L175 | train |
jackc/pgx | pgtype/convert.go | underlyingNumberType | func underlyingNumberType(val interface{}) (interface{}, bool) {
refVal := reflect.ValueOf(val)
switch refVal.Kind() {
case reflect.Ptr:
if refVal.IsNil() {
return nil, false
}
convVal := refVal.Elem().Interface()
return convVal, true
case reflect.Int:
convVal := int(refVal.Int())
return convVal, reflect.TypeOf(convVal) != refVal.Type()
case reflect.Int8:
convVal := int8(refVal.Int())
return convVal, reflect.TypeOf(convVal) != refVal.Type()
case reflect.Int16:
convVal := int16(refVal.Int())
return convVal, reflect.TypeOf(convVal) != refVal.Type()
case reflect.Int32:
convVal := int32(refVal.Int())
return convVal, reflect.TypeOf(convVal) != refVal.Type()
case reflect.Int64:
convVal := int64(refVal.Int())
return convVal, reflect.TypeOf(convVal) != refVal.Type()
case reflect.Uint:
convVal := uint(refVal.Uint())
return convVal, reflect.TypeOf(convVal) != refVal.Type()
case reflect.Uint8:
convVal := uint8(refVal.Uint())
return convVal, reflect.TypeOf(convVal) != refVal.Type()
case reflect.Uint16:
convVal := uint16(refVal.Uint())
return convVal, reflect.TypeOf(convVal) != refVal.Type()
case reflect.Uint32:
convVal := uint32(refVal.Uint())
return convVal, reflect.TypeOf(convVal) != refVal.Type()
case reflect.Uint64:
convVal := uint64(refVal.Uint())
return convVal, reflect.TypeOf(convVal) != refVal.Type()
case reflect.Float32:
convVal := float32(refVal.Float())
return convVal, reflect.TypeOf(convVal) != refVal.Type()
case reflect.Float64:
convVal := refVal.Float()
return convVal, reflect.TypeOf(convVal) != refVal.Type()
case reflect.String:
convVal := refVal.String()
return convVal, reflect.TypeOf(convVal) != refVal.Type()
}
return nil, false
} | go | func underlyingNumberType(val interface{}) (interface{}, bool) {
refVal := reflect.ValueOf(val)
switch refVal.Kind() {
case reflect.Ptr:
if refVal.IsNil() {
return nil, false
}
convVal := refVal.Elem().Interface()
return convVal, true
case reflect.Int:
convVal := int(refVal.Int())
return convVal, reflect.TypeOf(convVal) != refVal.Type()
case reflect.Int8:
convVal := int8(refVal.Int())
return convVal, reflect.TypeOf(convVal) != refVal.Type()
case reflect.Int16:
convVal := int16(refVal.Int())
return convVal, reflect.TypeOf(convVal) != refVal.Type()
case reflect.Int32:
convVal := int32(refVal.Int())
return convVal, reflect.TypeOf(convVal) != refVal.Type()
case reflect.Int64:
convVal := int64(refVal.Int())
return convVal, reflect.TypeOf(convVal) != refVal.Type()
case reflect.Uint:
convVal := uint(refVal.Uint())
return convVal, reflect.TypeOf(convVal) != refVal.Type()
case reflect.Uint8:
convVal := uint8(refVal.Uint())
return convVal, reflect.TypeOf(convVal) != refVal.Type()
case reflect.Uint16:
convVal := uint16(refVal.Uint())
return convVal, reflect.TypeOf(convVal) != refVal.Type()
case reflect.Uint32:
convVal := uint32(refVal.Uint())
return convVal, reflect.TypeOf(convVal) != refVal.Type()
case reflect.Uint64:
convVal := uint64(refVal.Uint())
return convVal, reflect.TypeOf(convVal) != refVal.Type()
case reflect.Float32:
convVal := float32(refVal.Float())
return convVal, reflect.TypeOf(convVal) != refVal.Type()
case reflect.Float64:
convVal := refVal.Float()
return convVal, reflect.TypeOf(convVal) != refVal.Type()
case reflect.String:
convVal := refVal.String()
return convVal, reflect.TypeOf(convVal) != refVal.Type()
}
return nil, false
} | [
"func",
"underlyingNumberType",
"(",
"val",
"interface",
"{",
"}",
")",
"(",
"interface",
"{",
"}",
",",
"bool",
")",
"{",
"refVal",
":=",
"reflect",
".",
"ValueOf",
"(",
"val",
")",
"\n\n",
"switch",
"refVal",
".",
"Kind",
"(",
")",
"{",
"case",
"re... | // underlyingNumberType gets the underlying type that can be converted to Int2, Int4, Int8, Float4, or Float8 | [
"underlyingNumberType",
"gets",
"the",
"underlying",
"type",
"that",
"can",
"be",
"converted",
"to",
"Int2",
"Int4",
"Int8",
"Float4",
"or",
"Float8"
] | 25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc | https://github.com/jackc/pgx/blob/25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc/pgtype/convert.go#L16-L68 | train |
jackc/pgx | pgtype/convert.go | underlyingBoolType | func underlyingBoolType(val interface{}) (interface{}, bool) {
refVal := reflect.ValueOf(val)
switch refVal.Kind() {
case reflect.Ptr:
if refVal.IsNil() {
return nil, false
}
convVal := refVal.Elem().Interface()
return convVal, true
case reflect.Bool:
convVal := refVal.Bool()
return convVal, reflect.TypeOf(convVal) != refVal.Type()
}
return nil, false
} | go | func underlyingBoolType(val interface{}) (interface{}, bool) {
refVal := reflect.ValueOf(val)
switch refVal.Kind() {
case reflect.Ptr:
if refVal.IsNil() {
return nil, false
}
convVal := refVal.Elem().Interface()
return convVal, true
case reflect.Bool:
convVal := refVal.Bool()
return convVal, reflect.TypeOf(convVal) != refVal.Type()
}
return nil, false
} | [
"func",
"underlyingBoolType",
"(",
"val",
"interface",
"{",
"}",
")",
"(",
"interface",
"{",
"}",
",",
"bool",
")",
"{",
"refVal",
":=",
"reflect",
".",
"ValueOf",
"(",
"val",
")",
"\n\n",
"switch",
"refVal",
".",
"Kind",
"(",
")",
"{",
"case",
"refl... | // underlyingBoolType gets the underlying type that can be converted to Bool | [
"underlyingBoolType",
"gets",
"the",
"underlying",
"type",
"that",
"can",
"be",
"converted",
"to",
"Bool"
] | 25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc | https://github.com/jackc/pgx/blob/25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc/pgtype/convert.go#L71-L87 | train |
jackc/pgx | pgtype/convert.go | underlyingPtrType | func underlyingPtrType(val interface{}) (interface{}, bool) {
refVal := reflect.ValueOf(val)
switch refVal.Kind() {
case reflect.Ptr:
if refVal.IsNil() {
return nil, false
}
convVal := refVal.Elem().Interface()
return convVal, true
}
return nil, false
} | go | func underlyingPtrType(val interface{}) (interface{}, bool) {
refVal := reflect.ValueOf(val)
switch refVal.Kind() {
case reflect.Ptr:
if refVal.IsNil() {
return nil, false
}
convVal := refVal.Elem().Interface()
return convVal, true
}
return nil, false
} | [
"func",
"underlyingPtrType",
"(",
"val",
"interface",
"{",
"}",
")",
"(",
"interface",
"{",
"}",
",",
"bool",
")",
"{",
"refVal",
":=",
"reflect",
".",
"ValueOf",
"(",
"val",
")",
"\n\n",
"switch",
"refVal",
".",
"Kind",
"(",
")",
"{",
"case",
"refle... | // underlyingPtrType dereferences a pointer | [
"underlyingPtrType",
"dereferences",
"a",
"pointer"
] | 25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc | https://github.com/jackc/pgx/blob/25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc/pgtype/convert.go#L130-L143 | train |
jackc/pgx | pgtype/convert.go | underlyingTimeType | func underlyingTimeType(val interface{}) (interface{}, bool) {
refVal := reflect.ValueOf(val)
switch refVal.Kind() {
case reflect.Ptr:
if refVal.IsNil() {
return time.Time{}, false
}
convVal := refVal.Elem().Interface()
return convVal, true
}
timeType := reflect.TypeOf(time.Time{})
if refVal.Type().ConvertibleTo(timeType) {
return refVal.Convert(timeType).Interface(), true
}
return time.Time{}, false
} | go | func underlyingTimeType(val interface{}) (interface{}, bool) {
refVal := reflect.ValueOf(val)
switch refVal.Kind() {
case reflect.Ptr:
if refVal.IsNil() {
return time.Time{}, false
}
convVal := refVal.Elem().Interface()
return convVal, true
}
timeType := reflect.TypeOf(time.Time{})
if refVal.Type().ConvertibleTo(timeType) {
return refVal.Convert(timeType).Interface(), true
}
return time.Time{}, false
} | [
"func",
"underlyingTimeType",
"(",
"val",
"interface",
"{",
"}",
")",
"(",
"interface",
"{",
"}",
",",
"bool",
")",
"{",
"refVal",
":=",
"reflect",
".",
"ValueOf",
"(",
"val",
")",
"\n\n",
"switch",
"refVal",
".",
"Kind",
"(",
")",
"{",
"case",
"refl... | // underlyingTimeType gets the underlying type that can be converted to time.Time | [
"underlyingTimeType",
"gets",
"the",
"underlying",
"type",
"that",
"can",
"be",
"converted",
"to",
"time",
".",
"Time"
] | 25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc | https://github.com/jackc/pgx/blob/25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc/pgtype/convert.go#L146-L164 | train |
jackc/pgx | pgtype/convert.go | underlyingSliceType | func underlyingSliceType(val interface{}) (interface{}, bool) {
refVal := reflect.ValueOf(val)
switch refVal.Kind() {
case reflect.Ptr:
if refVal.IsNil() {
return nil, false
}
convVal := refVal.Elem().Interface()
return convVal, true
case reflect.Slice:
baseSliceType := reflect.SliceOf(refVal.Type().Elem())
if refVal.Type().ConvertibleTo(baseSliceType) {
convVal := refVal.Convert(baseSliceType)
return convVal.Interface(), reflect.TypeOf(convVal.Interface()) != refVal.Type()
}
}
return nil, false
} | go | func underlyingSliceType(val interface{}) (interface{}, bool) {
refVal := reflect.ValueOf(val)
switch refVal.Kind() {
case reflect.Ptr:
if refVal.IsNil() {
return nil, false
}
convVal := refVal.Elem().Interface()
return convVal, true
case reflect.Slice:
baseSliceType := reflect.SliceOf(refVal.Type().Elem())
if refVal.Type().ConvertibleTo(baseSliceType) {
convVal := refVal.Convert(baseSliceType)
return convVal.Interface(), reflect.TypeOf(convVal.Interface()) != refVal.Type()
}
}
return nil, false
} | [
"func",
"underlyingSliceType",
"(",
"val",
"interface",
"{",
"}",
")",
"(",
"interface",
"{",
"}",
",",
"bool",
")",
"{",
"refVal",
":=",
"reflect",
".",
"ValueOf",
"(",
"val",
")",
"\n\n",
"switch",
"refVal",
".",
"Kind",
"(",
")",
"{",
"case",
"ref... | // underlyingSliceType gets the underlying slice type | [
"underlyingSliceType",
"gets",
"the",
"underlying",
"slice",
"type"
] | 25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc | https://github.com/jackc/pgx/blob/25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc/pgtype/convert.go#L167-L186 | train |
jackc/pgx | pgtype/bpchar.go | AssignTo | func (src *BPChar) AssignTo(dst interface{}) error {
if src.Status == Present {
switch v := dst.(type) {
case *rune:
runes := []rune(src.String)
if len(runes) == 1 {
*v = runes[0]
return nil
}
}
}
return (*Text)(src).AssignTo(dst)
} | go | func (src *BPChar) AssignTo(dst interface{}) error {
if src.Status == Present {
switch v := dst.(type) {
case *rune:
runes := []rune(src.String)
if len(runes) == 1 {
*v = runes[0]
return nil
}
}
}
return (*Text)(src).AssignTo(dst)
} | [
"func",
"(",
"src",
"*",
"BPChar",
")",
"AssignTo",
"(",
"dst",
"interface",
"{",
"}",
")",
"error",
"{",
"if",
"src",
".",
"Status",
"==",
"Present",
"{",
"switch",
"v",
":=",
"dst",
".",
"(",
"type",
")",
"{",
"case",
"*",
"rune",
":",
"runes",... | // AssignTo assigns from src to dst. | [
"AssignTo",
"assigns",
"from",
"src",
"to",
"dst",
"."
] | 25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc | https://github.com/jackc/pgx/blob/25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc/pgtype/bpchar.go#L22-L34 | train |
jackc/pgx | log/zerologadapter/adapter.go | NewLogger | func NewLogger(logger zerolog.Logger) *Logger {
return &Logger{
logger: logger.With().Str("module", "pgx").Logger(),
}
} | go | func NewLogger(logger zerolog.Logger) *Logger {
return &Logger{
logger: logger.With().Str("module", "pgx").Logger(),
}
} | [
"func",
"NewLogger",
"(",
"logger",
"zerolog",
".",
"Logger",
")",
"*",
"Logger",
"{",
"return",
"&",
"Logger",
"{",
"logger",
":",
"logger",
".",
"With",
"(",
")",
".",
"Str",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
".",
"Logger",
"(",
")",
",",
... | // NewLogger accepts a zerolog.Logger as input and returns a new custom pgx
// logging fascade as output. | [
"NewLogger",
"accepts",
"a",
"zerolog",
".",
"Logger",
"as",
"input",
"and",
"returns",
"a",
"new",
"custom",
"pgx",
"logging",
"fascade",
"as",
"output",
"."
] | 25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc | https://github.com/jackc/pgx/blob/25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc/log/zerologadapter/adapter.go#L15-L19 | train |
jackc/pgx | messages.go | appendParse | func appendParse(buf []byte, name string, query string, parameterOIDs []pgtype.OID) []byte {
buf = append(buf, 'P')
sp := len(buf)
buf = pgio.AppendInt32(buf, -1)
buf = append(buf, name...)
buf = append(buf, 0)
buf = append(buf, query...)
buf = append(buf, 0)
buf = pgio.AppendInt16(buf, int16(len(parameterOIDs)))
for _, oid := range parameterOIDs {
buf = pgio.AppendUint32(buf, uint32(oid))
}
pgio.SetInt32(buf[sp:], int32(len(buf[sp:])))
return buf
} | go | func appendParse(buf []byte, name string, query string, parameterOIDs []pgtype.OID) []byte {
buf = append(buf, 'P')
sp := len(buf)
buf = pgio.AppendInt32(buf, -1)
buf = append(buf, name...)
buf = append(buf, 0)
buf = append(buf, query...)
buf = append(buf, 0)
buf = pgio.AppendInt16(buf, int16(len(parameterOIDs)))
for _, oid := range parameterOIDs {
buf = pgio.AppendUint32(buf, uint32(oid))
}
pgio.SetInt32(buf[sp:], int32(len(buf[sp:])))
return buf
} | [
"func",
"appendParse",
"(",
"buf",
"[",
"]",
"byte",
",",
"name",
"string",
",",
"query",
"string",
",",
"parameterOIDs",
"[",
"]",
"pgtype",
".",
"OID",
")",
"[",
"]",
"byte",
"{",
"buf",
"=",
"append",
"(",
"buf",
",",
"'P'",
")",
"\n",
"sp",
"... | // appendParse appends a PostgreSQL wire protocol parse message to buf and returns it. | [
"appendParse",
"appends",
"a",
"PostgreSQL",
"wire",
"protocol",
"parse",
"message",
"to",
"buf",
"and",
"returns",
"it",
"."
] | 25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc | https://github.com/jackc/pgx/blob/25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc/messages.go#L113-L129 | train |
jackc/pgx | messages.go | appendDescribe | func appendDescribe(buf []byte, objectType byte, name string) []byte {
buf = append(buf, 'D')
sp := len(buf)
buf = pgio.AppendInt32(buf, -1)
buf = append(buf, objectType)
buf = append(buf, name...)
buf = append(buf, 0)
pgio.SetInt32(buf[sp:], int32(len(buf[sp:])))
return buf
} | go | func appendDescribe(buf []byte, objectType byte, name string) []byte {
buf = append(buf, 'D')
sp := len(buf)
buf = pgio.AppendInt32(buf, -1)
buf = append(buf, objectType)
buf = append(buf, name...)
buf = append(buf, 0)
pgio.SetInt32(buf[sp:], int32(len(buf[sp:])))
return buf
} | [
"func",
"appendDescribe",
"(",
"buf",
"[",
"]",
"byte",
",",
"objectType",
"byte",
",",
"name",
"string",
")",
"[",
"]",
"byte",
"{",
"buf",
"=",
"append",
"(",
"buf",
",",
"'D'",
")",
"\n",
"sp",
":=",
"len",
"(",
"buf",
")",
"\n",
"buf",
"=",
... | // appendDescribe appends a PostgreSQL wire protocol describe message to buf and returns it. | [
"appendDescribe",
"appends",
"a",
"PostgreSQL",
"wire",
"protocol",
"describe",
"message",
"to",
"buf",
"and",
"returns",
"it",
"."
] | 25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc | https://github.com/jackc/pgx/blob/25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc/messages.go#L132-L142 | train |
jackc/pgx | messages.go | appendSync | func appendSync(buf []byte) []byte {
buf = append(buf, 'S')
buf = pgio.AppendInt32(buf, 4)
return buf
} | go | func appendSync(buf []byte) []byte {
buf = append(buf, 'S')
buf = pgio.AppendInt32(buf, 4)
return buf
} | [
"func",
"appendSync",
"(",
"buf",
"[",
"]",
"byte",
")",
"[",
"]",
"byte",
"{",
"buf",
"=",
"append",
"(",
"buf",
",",
"'S'",
")",
"\n",
"buf",
"=",
"pgio",
".",
"AppendInt32",
"(",
"buf",
",",
"4",
")",
"\n\n",
"return",
"buf",
"\n",
"}"
] | // appendSync appends a PostgreSQL wire protocol sync message to buf and returns it. | [
"appendSync",
"appends",
"a",
"PostgreSQL",
"wire",
"protocol",
"sync",
"message",
"to",
"buf",
"and",
"returns",
"it",
"."
] | 25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc | https://github.com/jackc/pgx/blob/25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc/messages.go#L145-L150 | train |
jackc/pgx | messages.go | appendBind | func appendBind(
buf []byte,
destinationPortal,
preparedStatement string,
connInfo *pgtype.ConnInfo,
parameterOIDs []pgtype.OID,
arguments []interface{},
resultFormatCodes []int16,
) ([]byte, error) {
buf = append(buf, 'B')
sp := len(buf)
buf = pgio.AppendInt32(buf, -1)
buf = append(buf, destinationPortal...)
buf = append(buf, 0)
buf = append(buf, preparedStatement...)
buf = append(buf, 0)
var err error
arguments, err = convertDriverValuers(arguments)
if err != nil {
return nil, err
}
buf = pgio.AppendInt16(buf, int16(len(parameterOIDs)))
for i, oid := range parameterOIDs {
buf = pgio.AppendInt16(buf, chooseParameterFormatCode(connInfo, oid, arguments[i]))
}
buf = pgio.AppendInt16(buf, int16(len(arguments)))
for i, oid := range parameterOIDs {
var err error
buf, err = encodePreparedStatementArgument(connInfo, buf, oid, arguments[i])
if err != nil {
return nil, err
}
}
buf = pgio.AppendInt16(buf, int16(len(resultFormatCodes)))
for _, fc := range resultFormatCodes {
buf = pgio.AppendInt16(buf, fc)
}
pgio.SetInt32(buf[sp:], int32(len(buf[sp:])))
return buf, nil
} | go | func appendBind(
buf []byte,
destinationPortal,
preparedStatement string,
connInfo *pgtype.ConnInfo,
parameterOIDs []pgtype.OID,
arguments []interface{},
resultFormatCodes []int16,
) ([]byte, error) {
buf = append(buf, 'B')
sp := len(buf)
buf = pgio.AppendInt32(buf, -1)
buf = append(buf, destinationPortal...)
buf = append(buf, 0)
buf = append(buf, preparedStatement...)
buf = append(buf, 0)
var err error
arguments, err = convertDriverValuers(arguments)
if err != nil {
return nil, err
}
buf = pgio.AppendInt16(buf, int16(len(parameterOIDs)))
for i, oid := range parameterOIDs {
buf = pgio.AppendInt16(buf, chooseParameterFormatCode(connInfo, oid, arguments[i]))
}
buf = pgio.AppendInt16(buf, int16(len(arguments)))
for i, oid := range parameterOIDs {
var err error
buf, err = encodePreparedStatementArgument(connInfo, buf, oid, arguments[i])
if err != nil {
return nil, err
}
}
buf = pgio.AppendInt16(buf, int16(len(resultFormatCodes)))
for _, fc := range resultFormatCodes {
buf = pgio.AppendInt16(buf, fc)
}
pgio.SetInt32(buf[sp:], int32(len(buf[sp:])))
return buf, nil
} | [
"func",
"appendBind",
"(",
"buf",
"[",
"]",
"byte",
",",
"destinationPortal",
",",
"preparedStatement",
"string",
",",
"connInfo",
"*",
"pgtype",
".",
"ConnInfo",
",",
"parameterOIDs",
"[",
"]",
"pgtype",
".",
"OID",
",",
"arguments",
"[",
"]",
"interface",
... | // appendBind appends a PostgreSQL wire protocol bind message to buf and returns it. | [
"appendBind",
"appends",
"a",
"PostgreSQL",
"wire",
"protocol",
"bind",
"message",
"to",
"buf",
"and",
"returns",
"it",
"."
] | 25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc | https://github.com/jackc/pgx/blob/25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc/messages.go#L153-L197 | train |
jackc/pgx | messages.go | appendExecute | func appendExecute(buf []byte, portal string, maxRows uint32) []byte {
buf = append(buf, 'E')
sp := len(buf)
buf = pgio.AppendInt32(buf, -1)
buf = append(buf, portal...)
buf = append(buf, 0)
buf = pgio.AppendUint32(buf, maxRows)
pgio.SetInt32(buf[sp:], int32(len(buf[sp:])))
return buf
} | go | func appendExecute(buf []byte, portal string, maxRows uint32) []byte {
buf = append(buf, 'E')
sp := len(buf)
buf = pgio.AppendInt32(buf, -1)
buf = append(buf, portal...)
buf = append(buf, 0)
buf = pgio.AppendUint32(buf, maxRows)
pgio.SetInt32(buf[sp:], int32(len(buf[sp:])))
return buf
} | [
"func",
"appendExecute",
"(",
"buf",
"[",
"]",
"byte",
",",
"portal",
"string",
",",
"maxRows",
"uint32",
")",
"[",
"]",
"byte",
"{",
"buf",
"=",
"append",
"(",
"buf",
",",
"'E'",
")",
"\n",
"sp",
":=",
"len",
"(",
"buf",
")",
"\n",
"buf",
"=",
... | // appendExecute appends a PostgreSQL wire protocol execute message to buf and returns it. | [
"appendExecute",
"appends",
"a",
"PostgreSQL",
"wire",
"protocol",
"execute",
"message",
"to",
"buf",
"and",
"returns",
"it",
"."
] | 25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc | https://github.com/jackc/pgx/blob/25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc/messages.go#L216-L228 | train |
jackc/pgx | messages.go | appendQuery | func appendQuery(buf []byte, query string) []byte {
buf = append(buf, 'Q')
sp := len(buf)
buf = pgio.AppendInt32(buf, -1)
buf = append(buf, query...)
buf = append(buf, 0)
pgio.SetInt32(buf[sp:], int32(len(buf[sp:])))
return buf
} | go | func appendQuery(buf []byte, query string) []byte {
buf = append(buf, 'Q')
sp := len(buf)
buf = pgio.AppendInt32(buf, -1)
buf = append(buf, query...)
buf = append(buf, 0)
pgio.SetInt32(buf[sp:], int32(len(buf[sp:])))
return buf
} | [
"func",
"appendQuery",
"(",
"buf",
"[",
"]",
"byte",
",",
"query",
"string",
")",
"[",
"]",
"byte",
"{",
"buf",
"=",
"append",
"(",
"buf",
",",
"'Q'",
")",
"\n",
"sp",
":=",
"len",
"(",
"buf",
")",
"\n",
"buf",
"=",
"pgio",
".",
"AppendInt32",
... | // appendQuery appends a PostgreSQL wire protocol query message to buf and returns it. | [
"appendQuery",
"appends",
"a",
"PostgreSQL",
"wire",
"protocol",
"query",
"message",
"to",
"buf",
"and",
"returns",
"it",
"."
] | 25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc | https://github.com/jackc/pgx/blob/25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc/messages.go#L231-L240 | train |
jackc/pgx | stdlib/sql.go | ConnectionString | func (c *DriverConfig) ConnectionString(original string) string {
if c.driver == nil {
panic("DriverConfig must be registered before calling ConnectionString")
}
buf := make([]byte, 9)
binary.BigEndian.PutUint64(buf[1:], uint64(c.id))
buf = append(buf, original...)
return string(buf)
} | go | func (c *DriverConfig) ConnectionString(original string) string {
if c.driver == nil {
panic("DriverConfig must be registered before calling ConnectionString")
}
buf := make([]byte, 9)
binary.BigEndian.PutUint64(buf[1:], uint64(c.id))
buf = append(buf, original...)
return string(buf)
} | [
"func",
"(",
"c",
"*",
"DriverConfig",
")",
"ConnectionString",
"(",
"original",
"string",
")",
"string",
"{",
"if",
"c",
".",
"driver",
"==",
"nil",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"buf",
":=",
"make",
"(",
"[",
"]",
"byte",... | // ConnectionString encodes the DriverConfig into the original connection
// string. DriverConfig must be registered before calling ConnectionString. | [
"ConnectionString",
"encodes",
"the",
"DriverConfig",
"into",
"the",
"original",
"connection",
"string",
".",
"DriverConfig",
"must",
"be",
"registered",
"before",
"calling",
"ConnectionString",
"."
] | 25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc | https://github.com/jackc/pgx/blob/25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc/stdlib/sql.go#L188-L197 | train |
jackc/pgx | stdlib/sql.go | ColumnTypeDatabaseTypeName | func (r *Rows) ColumnTypeDatabaseTypeName(index int) string {
return strings.ToUpper(r.rows.FieldDescriptions()[index].DataTypeName)
} | go | func (r *Rows) ColumnTypeDatabaseTypeName(index int) string {
return strings.ToUpper(r.rows.FieldDescriptions()[index].DataTypeName)
} | [
"func",
"(",
"r",
"*",
"Rows",
")",
"ColumnTypeDatabaseTypeName",
"(",
"index",
"int",
")",
"string",
"{",
"return",
"strings",
".",
"ToUpper",
"(",
"r",
".",
"rows",
".",
"FieldDescriptions",
"(",
")",
"[",
"index",
"]",
".",
"DataTypeName",
")",
"\n",
... | // ColumnTypeDatabaseTypeName return the database system type name. | [
"ColumnTypeDatabaseTypeName",
"return",
"the",
"database",
"system",
"type",
"name",
"."
] | 25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc | https://github.com/jackc/pgx/blob/25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc/stdlib/sql.go#L491-L493 | train |
jackc/pgx | stdlib/sql.go | ColumnTypeLength | func (r *Rows) ColumnTypeLength(index int) (int64, bool) {
return r.rows.FieldDescriptions()[index].Length()
} | go | func (r *Rows) ColumnTypeLength(index int) (int64, bool) {
return r.rows.FieldDescriptions()[index].Length()
} | [
"func",
"(",
"r",
"*",
"Rows",
")",
"ColumnTypeLength",
"(",
"index",
"int",
")",
"(",
"int64",
",",
"bool",
")",
"{",
"return",
"r",
".",
"rows",
".",
"FieldDescriptions",
"(",
")",
"[",
"index",
"]",
".",
"Length",
"(",
")",
"\n",
"}"
] | // ColumnTypeLength returns the length of the column type if the column is a
// variable length type. If the column is not a variable length type ok
// should return false. | [
"ColumnTypeLength",
"returns",
"the",
"length",
"of",
"the",
"column",
"type",
"if",
"the",
"column",
"is",
"a",
"variable",
"length",
"type",
".",
"If",
"the",
"column",
"is",
"not",
"a",
"variable",
"length",
"type",
"ok",
"should",
"return",
"false",
".... | 25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc | https://github.com/jackc/pgx/blob/25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc/stdlib/sql.go#L498-L500 | train |
jackc/pgx | stdlib/sql.go | ColumnTypePrecisionScale | func (r *Rows) ColumnTypePrecisionScale(index int) (precision, scale int64, ok bool) {
return r.rows.FieldDescriptions()[index].PrecisionScale()
} | go | func (r *Rows) ColumnTypePrecisionScale(index int) (precision, scale int64, ok bool) {
return r.rows.FieldDescriptions()[index].PrecisionScale()
} | [
"func",
"(",
"r",
"*",
"Rows",
")",
"ColumnTypePrecisionScale",
"(",
"index",
"int",
")",
"(",
"precision",
",",
"scale",
"int64",
",",
"ok",
"bool",
")",
"{",
"return",
"r",
".",
"rows",
".",
"FieldDescriptions",
"(",
")",
"[",
"index",
"]",
".",
"P... | // ColumnTypePrecisionScale should return the precision and scale for decimal
// types. If not applicable, ok should be false. | [
"ColumnTypePrecisionScale",
"should",
"return",
"the",
"precision",
"and",
"scale",
"for",
"decimal",
"types",
".",
"If",
"not",
"applicable",
"ok",
"should",
"be",
"false",
"."
] | 25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc | https://github.com/jackc/pgx/blob/25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc/stdlib/sql.go#L504-L506 | train |
jackc/pgx | stdlib/sql.go | ColumnTypeScanType | func (r *Rows) ColumnTypeScanType(index int) reflect.Type {
return r.rows.FieldDescriptions()[index].Type()
} | go | func (r *Rows) ColumnTypeScanType(index int) reflect.Type {
return r.rows.FieldDescriptions()[index].Type()
} | [
"func",
"(",
"r",
"*",
"Rows",
")",
"ColumnTypeScanType",
"(",
"index",
"int",
")",
"reflect",
".",
"Type",
"{",
"return",
"r",
".",
"rows",
".",
"FieldDescriptions",
"(",
")",
"[",
"index",
"]",
".",
"Type",
"(",
")",
"\n",
"}"
] | // ColumnTypeScanType returns the value type that can be used to scan types into. | [
"ColumnTypeScanType",
"returns",
"the",
"value",
"type",
"that",
"can",
"be",
"used",
"to",
"scan",
"types",
"into",
"."
] | 25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc | https://github.com/jackc/pgx/blob/25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc/stdlib/sql.go#L509-L511 | train |
jackc/pgx | examples/url_shortener/main.go | afterConnect | func afterConnect(conn *pgx.Conn) (err error) {
_, err = conn.Prepare("getUrl", `
select url from shortened_urls where id=$1
`)
if err != nil {
return
}
_, err = conn.Prepare("deleteUrl", `
delete from shortened_urls where id=$1
`)
if err != nil {
return
}
_, err = conn.Prepare("putUrl", `
insert into shortened_urls(id, url) values ($1, $2)
on conflict (id) do update set url=excluded.url
`)
return
} | go | func afterConnect(conn *pgx.Conn) (err error) {
_, err = conn.Prepare("getUrl", `
select url from shortened_urls where id=$1
`)
if err != nil {
return
}
_, err = conn.Prepare("deleteUrl", `
delete from shortened_urls where id=$1
`)
if err != nil {
return
}
_, err = conn.Prepare("putUrl", `
insert into shortened_urls(id, url) values ($1, $2)
on conflict (id) do update set url=excluded.url
`)
return
} | [
"func",
"afterConnect",
"(",
"conn",
"*",
"pgx",
".",
"Conn",
")",
"(",
"err",
"error",
")",
"{",
"_",
",",
"err",
"=",
"conn",
".",
"Prepare",
"(",
"\"",
"\"",
",",
"`\n select url from shortened_urls where id=$1\n `",
")",
"\n",
"if",
"err",
"!=",
... | // afterConnect creates the prepared statements that this application uses | [
"afterConnect",
"creates",
"the",
"prepared",
"statements",
"that",
"this",
"application",
"uses"
] | 25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc | https://github.com/jackc/pgx/blob/25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc/examples/url_shortener/main.go#L16-L36 | train |
jackc/pgx | chunkreader/chunkreader.go | Next | func (r *ChunkReader) Next(n int) (buf []byte, err error) {
// n bytes already in buf
if (r.wp - r.rp) >= n {
buf = r.buf[r.rp : r.rp+n]
r.rp += n
return buf, err
}
// available space in buf is less than n
if len(r.buf) < n {
r.copyBufContents(r.newBuf(n))
}
// buf is large enough, but need to shift filled area to start to make enough contiguous space
minReadCount := n - (r.wp - r.rp)
if (len(r.buf) - r.wp) < minReadCount {
newBuf := r.newBuf(n)
r.copyBufContents(newBuf)
}
if err := r.appendAtLeast(minReadCount); err != nil {
return nil, err
}
buf = r.buf[r.rp : r.rp+n]
r.rp += n
return buf, nil
} | go | func (r *ChunkReader) Next(n int) (buf []byte, err error) {
// n bytes already in buf
if (r.wp - r.rp) >= n {
buf = r.buf[r.rp : r.rp+n]
r.rp += n
return buf, err
}
// available space in buf is less than n
if len(r.buf) < n {
r.copyBufContents(r.newBuf(n))
}
// buf is large enough, but need to shift filled area to start to make enough contiguous space
minReadCount := n - (r.wp - r.rp)
if (len(r.buf) - r.wp) < minReadCount {
newBuf := r.newBuf(n)
r.copyBufContents(newBuf)
}
if err := r.appendAtLeast(minReadCount); err != nil {
return nil, err
}
buf = r.buf[r.rp : r.rp+n]
r.rp += n
return buf, nil
} | [
"func",
"(",
"r",
"*",
"ChunkReader",
")",
"Next",
"(",
"n",
"int",
")",
"(",
"buf",
"[",
"]",
"byte",
",",
"err",
"error",
")",
"{",
"// n bytes already in buf",
"if",
"(",
"r",
".",
"wp",
"-",
"r",
".",
"rp",
")",
">=",
"n",
"{",
"buf",
"=",
... | // Next returns buf filled with the next n bytes. If an error occurs, buf will
// be nil. | [
"Next",
"returns",
"buf",
"filled",
"with",
"the",
"next",
"n",
"bytes",
".",
"If",
"an",
"error",
"occurs",
"buf",
"will",
"be",
"nil",
"."
] | 25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc | https://github.com/jackc/pgx/blob/25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc/chunkreader/chunkreader.go#L43-L70 | train |
jackc/pgx | conn.go | Sanitize | func (ident Identifier) Sanitize() string {
parts := make([]string, len(ident))
for i := range ident {
parts[i] = `"` + strings.Replace(ident[i], `"`, `""`, -1) + `"`
}
return strings.Join(parts, ".")
} | go | func (ident Identifier) Sanitize() string {
parts := make([]string, len(ident))
for i := range ident {
parts[i] = `"` + strings.Replace(ident[i], `"`, `""`, -1) + `"`
}
return strings.Join(parts, ".")
} | [
"func",
"(",
"ident",
"Identifier",
")",
"Sanitize",
"(",
")",
"string",
"{",
"parts",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"len",
"(",
"ident",
")",
")",
"\n",
"for",
"i",
":=",
"range",
"ident",
"{",
"parts",
"[",
"i",
"]",
"=",
"`\"`",
... | // Sanitize returns a sanitized string safe for SQL interpolation. | [
"Sanitize",
"returns",
"a",
"sanitized",
"string",
"safe",
"for",
"SQL",
"interpolation",
"."
] | 25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc | https://github.com/jackc/pgx/blob/25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc/conn.go#L190-L196 | train |
jackc/pgx | conn.go | Connect | func Connect(config ConnConfig) (c *Conn, err error) {
return connect(config, minimalConnInfo)
} | go | func Connect(config ConnConfig) (c *Conn, err error) {
return connect(config, minimalConnInfo)
} | [
"func",
"Connect",
"(",
"config",
"ConnConfig",
")",
"(",
"c",
"*",
"Conn",
",",
"err",
"error",
")",
"{",
"return",
"connect",
"(",
"config",
",",
"minimalConnInfo",
")",
"\n",
"}"
] | // Connect establishes a connection with a PostgreSQL server using config.
// config.Host must be specified. config.User will default to the OS user name.
// Other config fields are optional. | [
"Connect",
"establishes",
"a",
"connection",
"with",
"a",
"PostgreSQL",
"server",
"using",
"config",
".",
"config",
".",
"Host",
"must",
"be",
"specified",
".",
"config",
".",
"User",
"will",
"default",
"to",
"the",
"OS",
"user",
"name",
".",
"Other",
"con... | 25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc | https://github.com/jackc/pgx/blob/25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc/conn.go#L225-L227 | train |
jackc/pgx | conn.go | initConnInfoEnumArray | func (c *Conn) initConnInfoEnumArray(cinfo *pgtype.ConnInfo) error {
nameOIDs := make(map[string]pgtype.OID, 16)
rows, err := c.Query(`select t.oid, t.typname
from pg_type t
join pg_type base_type on t.typelem=base_type.oid
where t.typtype = 'b'
and base_type.typtype = 'e'`)
if err != nil {
return err
}
for rows.Next() {
var oid pgtype.OID
var name pgtype.Text
if err := rows.Scan(&oid, &name); err != nil {
return err
}
nameOIDs[name.String] = oid
}
if rows.Err() != nil {
return rows.Err()
}
for name, oid := range nameOIDs {
cinfo.RegisterDataType(pgtype.DataType{
Value: &pgtype.EnumArray{},
Name: name,
OID: oid,
})
}
return nil
} | go | func (c *Conn) initConnInfoEnumArray(cinfo *pgtype.ConnInfo) error {
nameOIDs := make(map[string]pgtype.OID, 16)
rows, err := c.Query(`select t.oid, t.typname
from pg_type t
join pg_type base_type on t.typelem=base_type.oid
where t.typtype = 'b'
and base_type.typtype = 'e'`)
if err != nil {
return err
}
for rows.Next() {
var oid pgtype.OID
var name pgtype.Text
if err := rows.Scan(&oid, &name); err != nil {
return err
}
nameOIDs[name.String] = oid
}
if rows.Err() != nil {
return rows.Err()
}
for name, oid := range nameOIDs {
cinfo.RegisterDataType(pgtype.DataType{
Value: &pgtype.EnumArray{},
Name: name,
OID: oid,
})
}
return nil
} | [
"func",
"(",
"c",
"*",
"Conn",
")",
"initConnInfoEnumArray",
"(",
"cinfo",
"*",
"pgtype",
".",
"ConnInfo",
")",
"error",
"{",
"nameOIDs",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"pgtype",
".",
"OID",
",",
"16",
")",
"\n",
"rows",
",",
"err",
... | // initConnInfoEnumArray introspects for arrays of enums and registers a data type for them. | [
"initConnInfoEnumArray",
"introspects",
"for",
"arrays",
"of",
"enums",
"and",
"registers",
"a",
"data",
"type",
"for",
"them",
"."
] | 25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc | https://github.com/jackc/pgx/blob/25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc/conn.go#L459-L493 | train |
jackc/pgx | conn.go | initConnInfoDomains | func (c *Conn) initConnInfoDomains(cinfo *pgtype.ConnInfo) error {
type domain struct {
oid pgtype.OID
name pgtype.Text
baseOID pgtype.OID
}
domains := make([]*domain, 0, 16)
rows, err := c.Query(`select t.oid, t.typname, t.typbasetype
from pg_type t
join pg_type base_type on t.typbasetype=base_type.oid
where t.typtype = 'd'
and base_type.typtype = 'b'`)
if err != nil {
return err
}
for rows.Next() {
var d domain
if err := rows.Scan(&d.oid, &d.name, &d.baseOID); err != nil {
return err
}
domains = append(domains, &d)
}
if rows.Err() != nil {
return rows.Err()
}
for _, d := range domains {
baseDataType, ok := cinfo.DataTypeForOID(d.baseOID)
if ok {
cinfo.RegisterDataType(pgtype.DataType{
Value: reflect.New(reflect.ValueOf(baseDataType.Value).Elem().Type()).Interface().(pgtype.Value),
Name: d.name.String,
OID: d.oid,
})
}
}
return nil
} | go | func (c *Conn) initConnInfoDomains(cinfo *pgtype.ConnInfo) error {
type domain struct {
oid pgtype.OID
name pgtype.Text
baseOID pgtype.OID
}
domains := make([]*domain, 0, 16)
rows, err := c.Query(`select t.oid, t.typname, t.typbasetype
from pg_type t
join pg_type base_type on t.typbasetype=base_type.oid
where t.typtype = 'd'
and base_type.typtype = 'b'`)
if err != nil {
return err
}
for rows.Next() {
var d domain
if err := rows.Scan(&d.oid, &d.name, &d.baseOID); err != nil {
return err
}
domains = append(domains, &d)
}
if rows.Err() != nil {
return rows.Err()
}
for _, d := range domains {
baseDataType, ok := cinfo.DataTypeForOID(d.baseOID)
if ok {
cinfo.RegisterDataType(pgtype.DataType{
Value: reflect.New(reflect.ValueOf(baseDataType.Value).Elem().Type()).Interface().(pgtype.Value),
Name: d.name.String,
OID: d.oid,
})
}
}
return nil
} | [
"func",
"(",
"c",
"*",
"Conn",
")",
"initConnInfoDomains",
"(",
"cinfo",
"*",
"pgtype",
".",
"ConnInfo",
")",
"error",
"{",
"type",
"domain",
"struct",
"{",
"oid",
"pgtype",
".",
"OID",
"\n",
"name",
"pgtype",
".",
"Text",
"\n",
"baseOID",
"pgtype",
".... | // initConnInfoDomains introspects for domains and registers a data type for them. | [
"initConnInfoDomains",
"introspects",
"for",
"domains",
"and",
"registers",
"a",
"data",
"type",
"for",
"them",
"."
] | 25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc | https://github.com/jackc/pgx/blob/25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc/conn.go#L496-L539 | train |
jackc/pgx | conn.go | crateDBTypesQuery | func (c *Conn) crateDBTypesQuery(err error) (*pgtype.ConnInfo, error) {
// CrateDB 2.1.6 is a database that implements the PostgreSQL wire protocol,
// but not perfectly. In particular, the pg_catalog schema containing the
// pg_type table is not visible by default and the pg_type.typtype column is
// not implemented. Therefor the query above currently returns the following
// error:
//
// pgx.PgError{Severity:"ERROR", Code:"XX000",
// Message:"TableUnknownException: Table 'test.pg_type' unknown",
// Detail:"", Hint:"", Position:0, InternalPosition:0, InternalQuery:"",
// Where:"", SchemaName:"", TableName:"", ColumnName:"", DataTypeName:"",
// ConstraintName:"", File:"Schemas.java", Line:99, Routine:"getTableInfo"}
//
// If CrateDB was to fix the pg_type table visbility in the future, we'd
// still get this error until typtype column is implemented:
//
// pgx.PgError{Severity:"ERROR", Code:"XX000",
// Message:"ColumnUnknownException: Column typtype unknown", Detail:"",
// Hint:"", Position:0, InternalPosition:0, InternalQuery:"", Where:"",
// SchemaName:"", TableName:"", ColumnName:"", DataTypeName:"",
// ConstraintName:"", File:"FullQualifiedNameFieldProvider.java", Line:132,
//
// Additionally CrateDB doesn't implement Postgres error codes [2], and
// instead always returns "XX000" (internal_error). The code below uses all
// of this knowledge as a heuristic to detect CrateDB. If CrateDB is
// detected, a CrateDB specific pg_type query is executed instead.
//
// The heuristic is designed to still work even if CrateDB fixes [2] or
// renames its internal exception names. If both are changed but pg_types
// isn't fixed, this code will need to be changed.
//
// There is also a small chance the heuristic will yield a false positive for
// non-CrateDB databases (e.g. if a real Postgres instance returns a XX000
// error), but hopefully there will be no harm in attempting the alternative
// query in this case.
//
// CrateDB also uses the type varchar for the typname column which required
// adding varchar to the minimalConnInfo init code.
//
// Also see the discussion here [3].
//
// [1] https://crate.io/
// [2] https://github.com/crate/crate/issues/5027
// [3] https://github.com/jackc/pgx/issues/320
if pgErr, ok := err.(PgError); ok &&
(pgErr.Code == "XX000" ||
strings.Contains(pgErr.Message, "TableUnknownException") ||
strings.Contains(pgErr.Message, "ColumnUnknownException")) {
var (
nameOIDs map[string]pgtype.OID
)
if nameOIDs, err = connInfoFromRows(c.Query(`select oid, typname from pg_catalog.pg_type`)); err != nil {
return nil, err
}
cinfo := pgtype.NewConnInfo()
cinfo.InitializeDataTypes(nameOIDs)
return cinfo, err
}
return nil, err
} | go | func (c *Conn) crateDBTypesQuery(err error) (*pgtype.ConnInfo, error) {
// CrateDB 2.1.6 is a database that implements the PostgreSQL wire protocol,
// but not perfectly. In particular, the pg_catalog schema containing the
// pg_type table is not visible by default and the pg_type.typtype column is
// not implemented. Therefor the query above currently returns the following
// error:
//
// pgx.PgError{Severity:"ERROR", Code:"XX000",
// Message:"TableUnknownException: Table 'test.pg_type' unknown",
// Detail:"", Hint:"", Position:0, InternalPosition:0, InternalQuery:"",
// Where:"", SchemaName:"", TableName:"", ColumnName:"", DataTypeName:"",
// ConstraintName:"", File:"Schemas.java", Line:99, Routine:"getTableInfo"}
//
// If CrateDB was to fix the pg_type table visbility in the future, we'd
// still get this error until typtype column is implemented:
//
// pgx.PgError{Severity:"ERROR", Code:"XX000",
// Message:"ColumnUnknownException: Column typtype unknown", Detail:"",
// Hint:"", Position:0, InternalPosition:0, InternalQuery:"", Where:"",
// SchemaName:"", TableName:"", ColumnName:"", DataTypeName:"",
// ConstraintName:"", File:"FullQualifiedNameFieldProvider.java", Line:132,
//
// Additionally CrateDB doesn't implement Postgres error codes [2], and
// instead always returns "XX000" (internal_error). The code below uses all
// of this knowledge as a heuristic to detect CrateDB. If CrateDB is
// detected, a CrateDB specific pg_type query is executed instead.
//
// The heuristic is designed to still work even if CrateDB fixes [2] or
// renames its internal exception names. If both are changed but pg_types
// isn't fixed, this code will need to be changed.
//
// There is also a small chance the heuristic will yield a false positive for
// non-CrateDB databases (e.g. if a real Postgres instance returns a XX000
// error), but hopefully there will be no harm in attempting the alternative
// query in this case.
//
// CrateDB also uses the type varchar for the typname column which required
// adding varchar to the minimalConnInfo init code.
//
// Also see the discussion here [3].
//
// [1] https://crate.io/
// [2] https://github.com/crate/crate/issues/5027
// [3] https://github.com/jackc/pgx/issues/320
if pgErr, ok := err.(PgError); ok &&
(pgErr.Code == "XX000" ||
strings.Contains(pgErr.Message, "TableUnknownException") ||
strings.Contains(pgErr.Message, "ColumnUnknownException")) {
var (
nameOIDs map[string]pgtype.OID
)
if nameOIDs, err = connInfoFromRows(c.Query(`select oid, typname from pg_catalog.pg_type`)); err != nil {
return nil, err
}
cinfo := pgtype.NewConnInfo()
cinfo.InitializeDataTypes(nameOIDs)
return cinfo, err
}
return nil, err
} | [
"func",
"(",
"c",
"*",
"Conn",
")",
"crateDBTypesQuery",
"(",
"err",
"error",
")",
"(",
"*",
"pgtype",
".",
"ConnInfo",
",",
"error",
")",
"{",
"// CrateDB 2.1.6 is a database that implements the PostgreSQL wire protocol,",
"// but not perfectly. In particular, the pg_catal... | // crateDBTypesQuery checks if the given err is likely to be the result of
// CrateDB not implementing the pg_types table correctly. If yes, a CrateDB
// specific query against pg_types is executed and its results are returned. If
// not, the original error is returned. | [
"crateDBTypesQuery",
"checks",
"if",
"the",
"given",
"err",
"is",
"likely",
"to",
"be",
"the",
"result",
"of",
"CrateDB",
"not",
"implementing",
"the",
"pg_types",
"table",
"correctly",
".",
"If",
"yes",
"a",
"CrateDB",
"specific",
"query",
"against",
"pg_type... | 25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc | https://github.com/jackc/pgx/blob/25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc/conn.go#L545-L609 | train |
jackc/pgx | conn.go | LocalAddr | func (c *Conn) LocalAddr() (net.Addr, error) {
if !c.IsAlive() {
return nil, errors.New("connection not ready")
}
return c.conn.LocalAddr(), nil
} | go | func (c *Conn) LocalAddr() (net.Addr, error) {
if !c.IsAlive() {
return nil, errors.New("connection not ready")
}
return c.conn.LocalAddr(), nil
} | [
"func",
"(",
"c",
"*",
"Conn",
")",
"LocalAddr",
"(",
")",
"(",
"net",
".",
"Addr",
",",
"error",
")",
"{",
"if",
"!",
"c",
".",
"IsAlive",
"(",
")",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"r... | // LocalAddr returns the underlying connection's local address | [
"LocalAddr",
"returns",
"the",
"underlying",
"connection",
"s",
"local",
"address"
] | 25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc | https://github.com/jackc/pgx/blob/25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc/conn.go#L617-L622 | train |
jackc/pgx | conn.go | Close | func (c *Conn) Close() (err error) {
c.mux.Lock()
defer c.mux.Unlock()
if c.status < connStatusIdle {
return nil
}
c.status = connStatusClosed
defer func() {
c.conn.Close()
c.causeOfDeath = errors.New("Closed")
if c.shouldLog(LogLevelInfo) {
c.log(LogLevelInfo, "closed connection", nil)
}
}()
err = c.conn.SetDeadline(time.Time{})
if err != nil && c.shouldLog(LogLevelWarn) {
c.log(LogLevelWarn, "failed to clear deadlines to send close message", map[string]interface{}{"err": err})
return err
}
_, err = c.conn.Write([]byte{'X', 0, 0, 0, 4})
if err != nil && c.shouldLog(LogLevelWarn) {
c.log(LogLevelWarn, "failed to send terminate message", map[string]interface{}{"err": err})
return err
}
err = c.conn.SetReadDeadline(time.Now().Add(5 * time.Second))
if err != nil && c.shouldLog(LogLevelWarn) {
c.log(LogLevelWarn, "failed to set read deadline to finish closing", map[string]interface{}{"err": err})
return err
}
_, err = c.conn.Read(make([]byte, 1))
if err != io.EOF {
return err
}
return nil
} | go | func (c *Conn) Close() (err error) {
c.mux.Lock()
defer c.mux.Unlock()
if c.status < connStatusIdle {
return nil
}
c.status = connStatusClosed
defer func() {
c.conn.Close()
c.causeOfDeath = errors.New("Closed")
if c.shouldLog(LogLevelInfo) {
c.log(LogLevelInfo, "closed connection", nil)
}
}()
err = c.conn.SetDeadline(time.Time{})
if err != nil && c.shouldLog(LogLevelWarn) {
c.log(LogLevelWarn, "failed to clear deadlines to send close message", map[string]interface{}{"err": err})
return err
}
_, err = c.conn.Write([]byte{'X', 0, 0, 0, 4})
if err != nil && c.shouldLog(LogLevelWarn) {
c.log(LogLevelWarn, "failed to send terminate message", map[string]interface{}{"err": err})
return err
}
err = c.conn.SetReadDeadline(time.Now().Add(5 * time.Second))
if err != nil && c.shouldLog(LogLevelWarn) {
c.log(LogLevelWarn, "failed to set read deadline to finish closing", map[string]interface{}{"err": err})
return err
}
_, err = c.conn.Read(make([]byte, 1))
if err != io.EOF {
return err
}
return nil
} | [
"func",
"(",
"c",
"*",
"Conn",
")",
"Close",
"(",
")",
"(",
"err",
"error",
")",
"{",
"c",
".",
"mux",
".",
"Lock",
"(",
")",
"\n",
"defer",
"c",
".",
"mux",
".",
"Unlock",
"(",
")",
"\n\n",
"if",
"c",
".",
"status",
"<",
"connStatusIdle",
"{... | // Close closes a connection. It is safe to call Close on a already closed
// connection. | [
"Close",
"closes",
"a",
"connection",
".",
"It",
"is",
"safe",
"to",
"call",
"Close",
"on",
"a",
"already",
"closed",
"connection",
"."
] | 25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc | https://github.com/jackc/pgx/blob/25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc/conn.go#L626-L667 | train |
jackc/pgx | conn.go | Merge | func (old ConnConfig) Merge(other ConnConfig) ConnConfig {
cc := old
if other.Host != "" {
cc.Host = other.Host
}
if other.Port != 0 {
cc.Port = other.Port
}
if other.Database != "" {
cc.Database = other.Database
}
if other.User != "" {
cc.User = other.User
}
if other.Password != "" {
cc.Password = other.Password
}
if other.TLSConfig != nil {
cc.TLSConfig = other.TLSConfig
cc.UseFallbackTLS = other.UseFallbackTLS
cc.FallbackTLSConfig = other.FallbackTLSConfig
}
if other.Logger != nil {
cc.Logger = other.Logger
}
if other.LogLevel != 0 {
cc.LogLevel = other.LogLevel
}
if other.Dial != nil {
cc.Dial = other.Dial
}
cc.PreferSimpleProtocol = old.PreferSimpleProtocol || other.PreferSimpleProtocol
cc.RuntimeParams = make(map[string]string)
for k, v := range old.RuntimeParams {
cc.RuntimeParams[k] = v
}
for k, v := range other.RuntimeParams {
cc.RuntimeParams[k] = v
}
return cc
} | go | func (old ConnConfig) Merge(other ConnConfig) ConnConfig {
cc := old
if other.Host != "" {
cc.Host = other.Host
}
if other.Port != 0 {
cc.Port = other.Port
}
if other.Database != "" {
cc.Database = other.Database
}
if other.User != "" {
cc.User = other.User
}
if other.Password != "" {
cc.Password = other.Password
}
if other.TLSConfig != nil {
cc.TLSConfig = other.TLSConfig
cc.UseFallbackTLS = other.UseFallbackTLS
cc.FallbackTLSConfig = other.FallbackTLSConfig
}
if other.Logger != nil {
cc.Logger = other.Logger
}
if other.LogLevel != 0 {
cc.LogLevel = other.LogLevel
}
if other.Dial != nil {
cc.Dial = other.Dial
}
cc.PreferSimpleProtocol = old.PreferSimpleProtocol || other.PreferSimpleProtocol
cc.RuntimeParams = make(map[string]string)
for k, v := range old.RuntimeParams {
cc.RuntimeParams[k] = v
}
for k, v := range other.RuntimeParams {
cc.RuntimeParams[k] = v
}
return cc
} | [
"func",
"(",
"old",
"ConnConfig",
")",
"Merge",
"(",
"other",
"ConnConfig",
")",
"ConnConfig",
"{",
"cc",
":=",
"old",
"\n\n",
"if",
"other",
".",
"Host",
"!=",
"\"",
"\"",
"{",
"cc",
".",
"Host",
"=",
"other",
".",
"Host",
"\n",
"}",
"\n",
"if",
... | // Merge returns a new ConnConfig with the attributes of old and other
// combined. When an attribute is set on both, other takes precedence.
//
// As a security precaution, if the other TLSConfig is nil, all old TLS
// attributes will be preserved. | [
"Merge",
"returns",
"a",
"new",
"ConnConfig",
"with",
"the",
"attributes",
"of",
"old",
"and",
"other",
"combined",
".",
"When",
"an",
"attribute",
"is",
"set",
"on",
"both",
"other",
"takes",
"precedence",
".",
"As",
"a",
"security",
"precaution",
"if",
"... | 25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc | https://github.com/jackc/pgx/blob/25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc/conn.go#L674-L721 | train |
jackc/pgx | conn.go | ParseURI | func ParseURI(uri string) (ConnConfig, error) {
var cp ConnConfig
url, err := url.Parse(uri)
if err != nil {
return cp, err
}
if url.User != nil {
cp.User = url.User.Username()
cp.Password, _ = url.User.Password()
}
parts := strings.SplitN(url.Host, ":", 2)
cp.Host = parts[0]
if len(parts) == 2 {
p, err := strconv.ParseUint(parts[1], 10, 16)
if err != nil {
return cp, err
}
cp.Port = uint16(p)
}
cp.Database = strings.TrimLeft(url.Path, "/")
if pgtimeout := url.Query().Get("connect_timeout"); pgtimeout != "" {
timeout, err := strconv.ParseInt(pgtimeout, 10, 64)
if err != nil {
return cp, err
}
d := defaultDialer()
d.Timeout = time.Duration(timeout) * time.Second
cp.Dial = d.Dial
}
tlsArgs := configTLSArgs{
sslCert: url.Query().Get("sslcert"),
sslKey: url.Query().Get("sslkey"),
sslMode: url.Query().Get("sslmode"),
sslRootCert: url.Query().Get("sslrootcert"),
}
err = configTLS(tlsArgs, &cp)
if err != nil {
return cp, err
}
ignoreKeys := map[string]struct{}{
"connect_timeout": {},
"sslcert": {},
"sslkey": {},
"sslmode": {},
"sslrootcert": {},
}
cp.RuntimeParams = make(map[string]string)
for k, v := range url.Query() {
if _, ok := ignoreKeys[k]; ok {
continue
}
if k == "host" {
cp.Host = v[0]
continue
}
cp.RuntimeParams[k] = v[0]
}
if cp.Password == "" {
pgpass(&cp)
}
return cp, nil
} | go | func ParseURI(uri string) (ConnConfig, error) {
var cp ConnConfig
url, err := url.Parse(uri)
if err != nil {
return cp, err
}
if url.User != nil {
cp.User = url.User.Username()
cp.Password, _ = url.User.Password()
}
parts := strings.SplitN(url.Host, ":", 2)
cp.Host = parts[0]
if len(parts) == 2 {
p, err := strconv.ParseUint(parts[1], 10, 16)
if err != nil {
return cp, err
}
cp.Port = uint16(p)
}
cp.Database = strings.TrimLeft(url.Path, "/")
if pgtimeout := url.Query().Get("connect_timeout"); pgtimeout != "" {
timeout, err := strconv.ParseInt(pgtimeout, 10, 64)
if err != nil {
return cp, err
}
d := defaultDialer()
d.Timeout = time.Duration(timeout) * time.Second
cp.Dial = d.Dial
}
tlsArgs := configTLSArgs{
sslCert: url.Query().Get("sslcert"),
sslKey: url.Query().Get("sslkey"),
sslMode: url.Query().Get("sslmode"),
sslRootCert: url.Query().Get("sslrootcert"),
}
err = configTLS(tlsArgs, &cp)
if err != nil {
return cp, err
}
ignoreKeys := map[string]struct{}{
"connect_timeout": {},
"sslcert": {},
"sslkey": {},
"sslmode": {},
"sslrootcert": {},
}
cp.RuntimeParams = make(map[string]string)
for k, v := range url.Query() {
if _, ok := ignoreKeys[k]; ok {
continue
}
if k == "host" {
cp.Host = v[0]
continue
}
cp.RuntimeParams[k] = v[0]
}
if cp.Password == "" {
pgpass(&cp)
}
return cp, nil
} | [
"func",
"ParseURI",
"(",
"uri",
"string",
")",
"(",
"ConnConfig",
",",
"error",
")",
"{",
"var",
"cp",
"ConnConfig",
"\n\n",
"url",
",",
"err",
":=",
"url",
".",
"Parse",
"(",
"uri",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"cp",
",",
... | // ParseURI parses a database URI into ConnConfig
//
// Query parameters not used by the connection process are parsed into ConnConfig.RuntimeParams. | [
"ParseURI",
"parses",
"a",
"database",
"URI",
"into",
"ConnConfig",
"Query",
"parameters",
"not",
"used",
"by",
"the",
"connection",
"process",
"are",
"parsed",
"into",
"ConnConfig",
".",
"RuntimeParams",
"."
] | 25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc | https://github.com/jackc/pgx/blob/25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc/conn.go#L726-L797 | train |
jackc/pgx | conn.go | ParseConnectionString | func ParseConnectionString(s string) (ConnConfig, error) {
if u, err := url.Parse(s); err == nil && u.Scheme != "" {
return ParseURI(s)
}
return ParseDSN(s)
} | go | func ParseConnectionString(s string) (ConnConfig, error) {
if u, err := url.Parse(s); err == nil && u.Scheme != "" {
return ParseURI(s)
}
return ParseDSN(s)
} | [
"func",
"ParseConnectionString",
"(",
"s",
"string",
")",
"(",
"ConnConfig",
",",
"error",
")",
"{",
"if",
"u",
",",
"err",
":=",
"url",
".",
"Parse",
"(",
"s",
")",
";",
"err",
"==",
"nil",
"&&",
"u",
".",
"Scheme",
"!=",
"\"",
"\"",
"{",
"retur... | // ParseConnectionString parses either a URI or a DSN connection string.
// see ParseURI and ParseDSN for details. | [
"ParseConnectionString",
"parses",
"either",
"a",
"URI",
"or",
"a",
"DSN",
"connection",
"string",
".",
"see",
"ParseURI",
"and",
"ParseDSN",
"for",
"details",
"."
] | 25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc | https://github.com/jackc/pgx/blob/25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc/conn.go#L870-L875 | train |
jackc/pgx | conn.go | Deallocate | func (c *Conn) Deallocate(name string) error {
return c.deallocateContext(context.Background(), name)
} | go | func (c *Conn) Deallocate(name string) error {
return c.deallocateContext(context.Background(), name)
} | [
"func",
"(",
"c",
"*",
"Conn",
")",
"Deallocate",
"(",
"name",
"string",
")",
"error",
"{",
"return",
"c",
".",
"deallocateContext",
"(",
"context",
".",
"Background",
"(",
")",
",",
"name",
")",
"\n",
"}"
] | // Deallocate released a prepared statement | [
"Deallocate",
"released",
"a",
"prepared",
"statement"
] | 25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc | https://github.com/jackc/pgx/blob/25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc/conn.go#L1155-L1157 | train |
jackc/pgx | conn.go | Unlisten | func (c *Conn) Unlisten(channel string) error {
_, err := c.Exec("unlisten " + quoteIdentifier(channel))
if err != nil {
return err
}
delete(c.channels, channel)
return nil
} | go | func (c *Conn) Unlisten(channel string) error {
_, err := c.Exec("unlisten " + quoteIdentifier(channel))
if err != nil {
return err
}
delete(c.channels, channel)
return nil
} | [
"func",
"(",
"c",
"*",
"Conn",
")",
"Unlisten",
"(",
"channel",
"string",
")",
"error",
"{",
"_",
",",
"err",
":=",
"c",
".",
"Exec",
"(",
"\"",
"\"",
"+",
"quoteIdentifier",
"(",
"channel",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return"... | // Unlisten unsubscribes from a listen channel | [
"Unlisten",
"unsubscribes",
"from",
"a",
"listen",
"channel"
] | 25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc | https://github.com/jackc/pgx/blob/25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc/conn.go#L1231-L1239 | train |
jackc/pgx | conn.go | WaitForNotification | func (c *Conn) WaitForNotification(ctx context.Context) (notification *Notification, err error) {
// Return already received notification immediately
if len(c.notifications) > 0 {
notification := c.notifications[0]
c.notifications = c.notifications[1:]
return notification, nil
}
err = c.waitForPreviousCancelQuery(ctx)
if err != nil {
return nil, err
}
err = c.initContext(ctx)
if err != nil {
return nil, err
}
defer func() {
err = c.termContext(err)
}()
if err = c.lock(); err != nil {
return nil, err
}
defer func() {
if unlockErr := c.unlock(); unlockErr != nil && err == nil {
err = unlockErr
}
}()
if err := c.ensureConnectionReadyForQuery(); err != nil {
return nil, err
}
for {
msg, err := c.rxMsg()
if err != nil {
return nil, err
}
err = c.processContextFreeMsg(msg)
if err != nil {
return nil, err
}
if len(c.notifications) > 0 {
notification := c.notifications[0]
c.notifications = c.notifications[1:]
return notification, nil
}
}
} | go | func (c *Conn) WaitForNotification(ctx context.Context) (notification *Notification, err error) {
// Return already received notification immediately
if len(c.notifications) > 0 {
notification := c.notifications[0]
c.notifications = c.notifications[1:]
return notification, nil
}
err = c.waitForPreviousCancelQuery(ctx)
if err != nil {
return nil, err
}
err = c.initContext(ctx)
if err != nil {
return nil, err
}
defer func() {
err = c.termContext(err)
}()
if err = c.lock(); err != nil {
return nil, err
}
defer func() {
if unlockErr := c.unlock(); unlockErr != nil && err == nil {
err = unlockErr
}
}()
if err := c.ensureConnectionReadyForQuery(); err != nil {
return nil, err
}
for {
msg, err := c.rxMsg()
if err != nil {
return nil, err
}
err = c.processContextFreeMsg(msg)
if err != nil {
return nil, err
}
if len(c.notifications) > 0 {
notification := c.notifications[0]
c.notifications = c.notifications[1:]
return notification, nil
}
}
} | [
"func",
"(",
"c",
"*",
"Conn",
")",
"WaitForNotification",
"(",
"ctx",
"context",
".",
"Context",
")",
"(",
"notification",
"*",
"Notification",
",",
"err",
"error",
")",
"{",
"// Return already received notification immediately",
"if",
"len",
"(",
"c",
".",
"... | // WaitForNotification waits for a PostgreSQL notification. | [
"WaitForNotification",
"waits",
"for",
"a",
"PostgreSQL",
"notification",
"."
] | 25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc | https://github.com/jackc/pgx/blob/25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc/conn.go#L1242-L1293 | train |
jackc/pgx | conn.go | processContextFreeMsg | func (c *Conn) processContextFreeMsg(msg pgproto3.BackendMessage) (err error) {
switch msg := msg.(type) {
case *pgproto3.ErrorResponse:
return c.rxErrorResponse(msg)
case *pgproto3.NoticeResponse:
c.rxNoticeResponse(msg)
case *pgproto3.NotificationResponse:
c.rxNotificationResponse(msg)
case *pgproto3.ReadyForQuery:
c.rxReadyForQuery(msg)
case *pgproto3.ParameterStatus:
c.rxParameterStatus(msg)
}
return nil
} | go | func (c *Conn) processContextFreeMsg(msg pgproto3.BackendMessage) (err error) {
switch msg := msg.(type) {
case *pgproto3.ErrorResponse:
return c.rxErrorResponse(msg)
case *pgproto3.NoticeResponse:
c.rxNoticeResponse(msg)
case *pgproto3.NotificationResponse:
c.rxNotificationResponse(msg)
case *pgproto3.ReadyForQuery:
c.rxReadyForQuery(msg)
case *pgproto3.ParameterStatus:
c.rxParameterStatus(msg)
}
return nil
} | [
"func",
"(",
"c",
"*",
"Conn",
")",
"processContextFreeMsg",
"(",
"msg",
"pgproto3",
".",
"BackendMessage",
")",
"(",
"err",
"error",
")",
"{",
"switch",
"msg",
":=",
"msg",
".",
"(",
"type",
")",
"{",
"case",
"*",
"pgproto3",
".",
"ErrorResponse",
":"... | // Processes messages that are not exclusive to one context such as
// authentication or query response. The response to these messages is the same
// regardless of when they occur. It also ignores messages that are only
// meaningful in a given context. These messages can occur due to a context
// deadline interrupting message processing. For example, an interrupted query
// may have left DataRow messages on the wire. | [
"Processes",
"messages",
"that",
"are",
"not",
"exclusive",
"to",
"one",
"context",
"such",
"as",
"authentication",
"or",
"query",
"response",
".",
"The",
"response",
"to",
"these",
"messages",
"is",
"the",
"same",
"regardless",
"of",
"when",
"they",
"occur",
... | 25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc | https://github.com/jackc/pgx/blob/25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc/conn.go#L1383-L1398 | train |
jackc/pgx | conn.go | SetLogger | func (c *Conn) SetLogger(logger Logger) Logger {
oldLogger := c.logger
c.logger = logger
return oldLogger
} | go | func (c *Conn) SetLogger(logger Logger) Logger {
oldLogger := c.logger
c.logger = logger
return oldLogger
} | [
"func",
"(",
"c",
"*",
"Conn",
")",
"SetLogger",
"(",
"logger",
"Logger",
")",
"Logger",
"{",
"oldLogger",
":=",
"c",
".",
"logger",
"\n",
"c",
".",
"logger",
"=",
"logger",
"\n",
"return",
"oldLogger",
"\n",
"}"
] | // SetLogger replaces the current logger and returns the previous logger. | [
"SetLogger",
"replaces",
"the",
"current",
"logger",
"and",
"returns",
"the",
"previous",
"logger",
"."
] | 25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc | https://github.com/jackc/pgx/blob/25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc/conn.go#L1630-L1634 | train |
jackc/pgx | conn.go | SetLogLevel | func (c *Conn) SetLogLevel(lvl LogLevel) (LogLevel, error) {
oldLvl := c.logLevel
if lvl < LogLevelNone || lvl > LogLevelTrace {
return oldLvl, ErrInvalidLogLevel
}
c.logLevel = lvl
return lvl, nil
} | go | func (c *Conn) SetLogLevel(lvl LogLevel) (LogLevel, error) {
oldLvl := c.logLevel
if lvl < LogLevelNone || lvl > LogLevelTrace {
return oldLvl, ErrInvalidLogLevel
}
c.logLevel = lvl
return lvl, nil
} | [
"func",
"(",
"c",
"*",
"Conn",
")",
"SetLogLevel",
"(",
"lvl",
"LogLevel",
")",
"(",
"LogLevel",
",",
"error",
")",
"{",
"oldLvl",
":=",
"c",
".",
"logLevel",
"\n\n",
"if",
"lvl",
"<",
"LogLevelNone",
"||",
"lvl",
">",
"LogLevelTrace",
"{",
"return",
... | // SetLogLevel replaces the current log level and returns the previous log
// level. | [
"SetLogLevel",
"replaces",
"the",
"current",
"log",
"level",
"and",
"returns",
"the",
"previous",
"log",
"level",
"."
] | 25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc | https://github.com/jackc/pgx/blob/25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc/conn.go#L1638-L1647 | train |
jackc/pgx | conn.go | WaitUntilReady | func (c *Conn) WaitUntilReady(ctx context.Context) error {
err := c.waitForPreviousCancelQuery(ctx)
if err != nil {
return err
}
return c.ensureConnectionReadyForQuery()
} | go | func (c *Conn) WaitUntilReady(ctx context.Context) error {
err := c.waitForPreviousCancelQuery(ctx)
if err != nil {
return err
}
return c.ensureConnectionReadyForQuery()
} | [
"func",
"(",
"c",
"*",
"Conn",
")",
"WaitUntilReady",
"(",
"ctx",
"context",
".",
"Context",
")",
"error",
"{",
"err",
":=",
"c",
".",
"waitForPreviousCancelQuery",
"(",
"ctx",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n... | // WaitUntilReady will return when the connection is ready for another query | [
"WaitUntilReady",
"will",
"return",
"when",
"the",
"connection",
"is",
"ready",
"for",
"another",
"query"
] | 25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc | https://github.com/jackc/pgx/blob/25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc/conn.go#L1904-L1910 | train |
jackc/pgx | replication.go | SendStandbyStatus | func (rc *ReplicationConn) SendStandbyStatus(k *StandbyStatus) (err error) {
buf := rc.wbuf
buf = append(buf, copyData)
sp := len(buf)
buf = pgio.AppendInt32(buf, -1)
buf = append(buf, standbyStatusUpdate)
buf = pgio.AppendInt64(buf, int64(k.WalWritePosition))
buf = pgio.AppendInt64(buf, int64(k.WalFlushPosition))
buf = pgio.AppendInt64(buf, int64(k.WalApplyPosition))
buf = pgio.AppendInt64(buf, int64(k.ClientTime))
buf = append(buf, k.ReplyRequested)
pgio.SetInt32(buf[sp:], int32(len(buf[sp:])))
_, err = rc.conn.Write(buf)
if err != nil {
rc.die(err)
}
return
} | go | func (rc *ReplicationConn) SendStandbyStatus(k *StandbyStatus) (err error) {
buf := rc.wbuf
buf = append(buf, copyData)
sp := len(buf)
buf = pgio.AppendInt32(buf, -1)
buf = append(buf, standbyStatusUpdate)
buf = pgio.AppendInt64(buf, int64(k.WalWritePosition))
buf = pgio.AppendInt64(buf, int64(k.WalFlushPosition))
buf = pgio.AppendInt64(buf, int64(k.WalApplyPosition))
buf = pgio.AppendInt64(buf, int64(k.ClientTime))
buf = append(buf, k.ReplyRequested)
pgio.SetInt32(buf[sp:], int32(len(buf[sp:])))
_, err = rc.conn.Write(buf)
if err != nil {
rc.die(err)
}
return
} | [
"func",
"(",
"rc",
"*",
"ReplicationConn",
")",
"SendStandbyStatus",
"(",
"k",
"*",
"StandbyStatus",
")",
"(",
"err",
"error",
")",
"{",
"buf",
":=",
"rc",
".",
"wbuf",
"\n",
"buf",
"=",
"append",
"(",
"buf",
",",
"copyData",
")",
"\n",
"sp",
":=",
... | // Send standby status to the server, which both acts as a keepalive
// message to the server, as well as carries the WAL position of the
// client, which then updates the server's replication slot position. | [
"Send",
"standby",
"status",
"to",
"the",
"server",
"which",
"both",
"acts",
"as",
"a",
"keepalive",
"message",
"to",
"the",
"server",
"as",
"well",
"as",
"carries",
"the",
"WAL",
"position",
"of",
"the",
"client",
"which",
"then",
"updates",
"the",
"serve... | 25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc | https://github.com/jackc/pgx/blob/25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc/replication.go#L193-L214 | train |
jackc/pgx | replication.go | CreateReplicationSlot | func (rc *ReplicationConn) CreateReplicationSlot(slotName, outputPlugin string) (err error) {
_, err = rc.Exec(fmt.Sprintf("CREATE_REPLICATION_SLOT %s LOGICAL %s NOEXPORT_SNAPSHOT", slotName, outputPlugin))
return
} | go | func (rc *ReplicationConn) CreateReplicationSlot(slotName, outputPlugin string) (err error) {
_, err = rc.Exec(fmt.Sprintf("CREATE_REPLICATION_SLOT %s LOGICAL %s NOEXPORT_SNAPSHOT", slotName, outputPlugin))
return
} | [
"func",
"(",
"rc",
"*",
"ReplicationConn",
")",
"CreateReplicationSlot",
"(",
"slotName",
",",
"outputPlugin",
"string",
")",
"(",
"err",
"error",
")",
"{",
"_",
",",
"err",
"=",
"rc",
".",
"Exec",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"s... | // Create the replication slot, using the given name and output plugin. | [
"Create",
"the",
"replication",
"slot",
"using",
"the",
"given",
"name",
"and",
"output",
"plugin",
"."
] | 25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc | https://github.com/jackc/pgx/blob/25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc/replication.go#L443-L446 | train |
jackc/pgx | replication.go | CreateReplicationSlotEx | func (rc *ReplicationConn) CreateReplicationSlotEx(slotName, outputPlugin string) (consistentPoint string, snapshotName string, err error) {
var dummy string
var rows *Rows
rows, err = rc.sendReplicationModeQuery(fmt.Sprintf("CREATE_REPLICATION_SLOT %s LOGICAL %s", slotName, outputPlugin))
defer rows.Close()
for rows.Next() {
rows.Scan(&dummy, &consistentPoint, &snapshotName, &dummy)
}
return
} | go | func (rc *ReplicationConn) CreateReplicationSlotEx(slotName, outputPlugin string) (consistentPoint string, snapshotName string, err error) {
var dummy string
var rows *Rows
rows, err = rc.sendReplicationModeQuery(fmt.Sprintf("CREATE_REPLICATION_SLOT %s LOGICAL %s", slotName, outputPlugin))
defer rows.Close()
for rows.Next() {
rows.Scan(&dummy, &consistentPoint, &snapshotName, &dummy)
}
return
} | [
"func",
"(",
"rc",
"*",
"ReplicationConn",
")",
"CreateReplicationSlotEx",
"(",
"slotName",
",",
"outputPlugin",
"string",
")",
"(",
"consistentPoint",
"string",
",",
"snapshotName",
"string",
",",
"err",
"error",
")",
"{",
"var",
"dummy",
"string",
"\n",
"var... | // Create the replication slot, using the given name and output plugin, and return the consistent_point and snapshot_name values. | [
"Create",
"the",
"replication",
"slot",
"using",
"the",
"given",
"name",
"and",
"output",
"plugin",
"and",
"return",
"the",
"consistent_point",
"and",
"snapshot_name",
"values",
"."
] | 25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc | https://github.com/jackc/pgx/blob/25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc/replication.go#L449-L458 | train |
jackc/pgx | replication.go | DropReplicationSlot | func (rc *ReplicationConn) DropReplicationSlot(slotName string) (err error) {
_, err = rc.Exec(fmt.Sprintf("DROP_REPLICATION_SLOT %s", slotName))
return
} | go | func (rc *ReplicationConn) DropReplicationSlot(slotName string) (err error) {
_, err = rc.Exec(fmt.Sprintf("DROP_REPLICATION_SLOT %s", slotName))
return
} | [
"func",
"(",
"rc",
"*",
"ReplicationConn",
")",
"DropReplicationSlot",
"(",
"slotName",
"string",
")",
"(",
"err",
"error",
")",
"{",
"_",
",",
"err",
"=",
"rc",
".",
"Exec",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"slotName",
")",
")",
"... | // Drop the replication slot for the given name | [
"Drop",
"the",
"replication",
"slot",
"for",
"the",
"given",
"name"
] | 25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc | https://github.com/jackc/pgx/blob/25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc/replication.go#L461-L464 | train |
jackc/pgx | auth_scram.go | scramAuth | func (c *Conn) scramAuth(serverAuthMechanisms []string) error {
sc, err := newScramClient(serverAuthMechanisms, c.config.Password)
if err != nil {
return err
}
// Send client-first-message in a SASLInitialResponse
saslInitialResponse := &pgproto3.SASLInitialResponse{
AuthMechanism: "SCRAM-SHA-256",
Data: sc.clientFirstMessage(),
}
_, err = c.conn.Write(saslInitialResponse.Encode(nil))
if err != nil {
return err
}
// Receive server-first-message payload in a AuthenticationSASLContinue.
authMsg, err := c.rxAuthMsg(pgproto3.AuthTypeSASLContinue)
if err != nil {
return err
}
err = sc.recvServerFirstMessage(authMsg.SASLData)
if err != nil {
return err
}
// Send client-final-message in a SASLResponse
saslResponse := &pgproto3.SASLResponse{
Data: []byte(sc.clientFinalMessage()),
}
_, err = c.conn.Write(saslResponse.Encode(nil))
if err != nil {
return err
}
// Receive server-final-message payload in a AuthenticationSASLFinal.
authMsg, err = c.rxAuthMsg(pgproto3.AuthTypeSASLFinal)
if err != nil {
return err
}
return sc.recvServerFinalMessage(authMsg.SASLData)
} | go | func (c *Conn) scramAuth(serverAuthMechanisms []string) error {
sc, err := newScramClient(serverAuthMechanisms, c.config.Password)
if err != nil {
return err
}
// Send client-first-message in a SASLInitialResponse
saslInitialResponse := &pgproto3.SASLInitialResponse{
AuthMechanism: "SCRAM-SHA-256",
Data: sc.clientFirstMessage(),
}
_, err = c.conn.Write(saslInitialResponse.Encode(nil))
if err != nil {
return err
}
// Receive server-first-message payload in a AuthenticationSASLContinue.
authMsg, err := c.rxAuthMsg(pgproto3.AuthTypeSASLContinue)
if err != nil {
return err
}
err = sc.recvServerFirstMessage(authMsg.SASLData)
if err != nil {
return err
}
// Send client-final-message in a SASLResponse
saslResponse := &pgproto3.SASLResponse{
Data: []byte(sc.clientFinalMessage()),
}
_, err = c.conn.Write(saslResponse.Encode(nil))
if err != nil {
return err
}
// Receive server-final-message payload in a AuthenticationSASLFinal.
authMsg, err = c.rxAuthMsg(pgproto3.AuthTypeSASLFinal)
if err != nil {
return err
}
return sc.recvServerFinalMessage(authMsg.SASLData)
} | [
"func",
"(",
"c",
"*",
"Conn",
")",
"scramAuth",
"(",
"serverAuthMechanisms",
"[",
"]",
"string",
")",
"error",
"{",
"sc",
",",
"err",
":=",
"newScramClient",
"(",
"serverAuthMechanisms",
",",
"c",
".",
"config",
".",
"Password",
")",
"\n",
"if",
"err",
... | // Perform SCRAM authentication. | [
"Perform",
"SCRAM",
"authentication",
"."
] | 25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc | https://github.com/jackc/pgx/blob/25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc/auth_scram.go#L32-L73 | train |
jackc/pgx | copy_from.go | CopyFrom | func (c *Conn) CopyFrom(tableName Identifier, columnNames []string, rowSrc CopyFromSource) (int, error) {
ct := ©From{
conn: c,
tableName: tableName,
columnNames: columnNames,
rowSrc: rowSrc,
readerErrChan: make(chan error),
}
return ct.run()
} | go | func (c *Conn) CopyFrom(tableName Identifier, columnNames []string, rowSrc CopyFromSource) (int, error) {
ct := ©From{
conn: c,
tableName: tableName,
columnNames: columnNames,
rowSrc: rowSrc,
readerErrChan: make(chan error),
}
return ct.run()
} | [
"func",
"(",
"c",
"*",
"Conn",
")",
"CopyFrom",
"(",
"tableName",
"Identifier",
",",
"columnNames",
"[",
"]",
"string",
",",
"rowSrc",
"CopyFromSource",
")",
"(",
"int",
",",
"error",
")",
"{",
"ct",
":=",
"&",
"copyFrom",
"{",
"conn",
":",
"c",
",",... | // CopyFrom uses the PostgreSQL copy protocol to perform bulk data insertion.
// It returns the number of rows copied and an error.
//
// CopyFrom requires all values use the binary format. Almost all types
// implemented by pgx use the binary format by default. Types implementing
// Encoder can only be used if they encode to the binary format. | [
"CopyFrom",
"uses",
"the",
"PostgreSQL",
"copy",
"protocol",
"to",
"perform",
"bulk",
"data",
"insertion",
".",
"It",
"returns",
"the",
"number",
"of",
"rows",
"copied",
"and",
"an",
"error",
".",
"CopyFrom",
"requires",
"all",
"values",
"use",
"the",
"binar... | 25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc | https://github.com/jackc/pgx/blob/25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc/copy_from.go#L274-L284 | train |
jackc/pgx | copy_from.go | CopyFromReader | func (c *Conn) CopyFromReader(r io.Reader, sql string) (CommandTag, error) {
if err := c.sendSimpleQuery(sql); err != nil {
return "", err
}
if err := c.readUntilCopyInResponse(); err != nil {
return "", err
}
buf := c.wbuf
buf = append(buf, copyData)
sp := len(buf)
for {
n, err := r.Read(buf[5:cap(buf)])
if err == io.EOF && n == 0 {
break
}
buf = buf[0 : n+5]
pgio.SetInt32(buf[sp:], int32(n+4))
if _, err := c.conn.Write(buf); err != nil {
return "", err
}
}
buf = buf[:0]
buf = append(buf, copyDone)
buf = pgio.AppendInt32(buf, 4)
if _, err := c.conn.Write(buf); err != nil {
return "", err
}
for {
msg, err := c.rxMsg()
if err != nil {
return "", err
}
switch msg := msg.(type) {
case *pgproto3.ReadyForQuery:
c.rxReadyForQuery(msg)
return "", err
case *pgproto3.CommandComplete:
return CommandTag(msg.CommandTag), nil
case *pgproto3.ErrorResponse:
return "", c.rxErrorResponse(msg)
default:
return "", c.processContextFreeMsg(msg)
}
}
} | go | func (c *Conn) CopyFromReader(r io.Reader, sql string) (CommandTag, error) {
if err := c.sendSimpleQuery(sql); err != nil {
return "", err
}
if err := c.readUntilCopyInResponse(); err != nil {
return "", err
}
buf := c.wbuf
buf = append(buf, copyData)
sp := len(buf)
for {
n, err := r.Read(buf[5:cap(buf)])
if err == io.EOF && n == 0 {
break
}
buf = buf[0 : n+5]
pgio.SetInt32(buf[sp:], int32(n+4))
if _, err := c.conn.Write(buf); err != nil {
return "", err
}
}
buf = buf[:0]
buf = append(buf, copyDone)
buf = pgio.AppendInt32(buf, 4)
if _, err := c.conn.Write(buf); err != nil {
return "", err
}
for {
msg, err := c.rxMsg()
if err != nil {
return "", err
}
switch msg := msg.(type) {
case *pgproto3.ReadyForQuery:
c.rxReadyForQuery(msg)
return "", err
case *pgproto3.CommandComplete:
return CommandTag(msg.CommandTag), nil
case *pgproto3.ErrorResponse:
return "", c.rxErrorResponse(msg)
default:
return "", c.processContextFreeMsg(msg)
}
}
} | [
"func",
"(",
"c",
"*",
"Conn",
")",
"CopyFromReader",
"(",
"r",
"io",
".",
"Reader",
",",
"sql",
"string",
")",
"(",
"CommandTag",
",",
"error",
")",
"{",
"if",
"err",
":=",
"c",
".",
"sendSimpleQuery",
"(",
"sql",
")",
";",
"err",
"!=",
"nil",
"... | // CopyFromReader uses the PostgreSQL textual format of the copy protocol | [
"CopyFromReader",
"uses",
"the",
"PostgreSQL",
"textual",
"format",
"of",
"the",
"copy",
"protocol"
] | 25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc | https://github.com/jackc/pgx/blob/25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc/copy_from.go#L287-L338 | train |
jackc/pgx | query.go | Close | func (rows *Rows) Close() {
if rows.closed {
return
}
if rows.unlockConn {
rows.conn.unlock()
rows.unlockConn = false
}
rows.closed = true
rows.err = rows.conn.termContext(rows.err)
if rows.err == nil {
if rows.conn.shouldLog(LogLevelInfo) {
endTime := time.Now()
rows.conn.log(LogLevelInfo, "Query", map[string]interface{}{"sql": rows.sql, "args": logQueryArgs(rows.args), "time": endTime.Sub(rows.startTime), "rowCount": rows.rowCount})
}
} else if rows.conn.shouldLog(LogLevelError) {
rows.conn.log(LogLevelError, "Query", map[string]interface{}{"sql": rows.sql, "args": logQueryArgs(rows.args)})
}
if rows.batch != nil && rows.err != nil {
rows.batch.die(rows.err)
}
if rows.connPool != nil {
rows.connPool.Release(rows.conn)
}
} | go | func (rows *Rows) Close() {
if rows.closed {
return
}
if rows.unlockConn {
rows.conn.unlock()
rows.unlockConn = false
}
rows.closed = true
rows.err = rows.conn.termContext(rows.err)
if rows.err == nil {
if rows.conn.shouldLog(LogLevelInfo) {
endTime := time.Now()
rows.conn.log(LogLevelInfo, "Query", map[string]interface{}{"sql": rows.sql, "args": logQueryArgs(rows.args), "time": endTime.Sub(rows.startTime), "rowCount": rows.rowCount})
}
} else if rows.conn.shouldLog(LogLevelError) {
rows.conn.log(LogLevelError, "Query", map[string]interface{}{"sql": rows.sql, "args": logQueryArgs(rows.args)})
}
if rows.batch != nil && rows.err != nil {
rows.batch.die(rows.err)
}
if rows.connPool != nil {
rows.connPool.Release(rows.conn)
}
} | [
"func",
"(",
"rows",
"*",
"Rows",
")",
"Close",
"(",
")",
"{",
"if",
"rows",
".",
"closed",
"{",
"return",
"\n",
"}",
"\n\n",
"if",
"rows",
".",
"unlockConn",
"{",
"rows",
".",
"conn",
".",
"unlock",
"(",
")",
"\n",
"rows",
".",
"unlockConn",
"="... | // Close closes the rows, making the connection ready for use again. It is safe
// to call Close after rows is already closed. | [
"Close",
"closes",
"the",
"rows",
"making",
"the",
"connection",
"ready",
"for",
"use",
"again",
".",
"It",
"is",
"safe",
"to",
"call",
"Close",
"after",
"rows",
"is",
"already",
"closed",
"."
] | 25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc | https://github.com/jackc/pgx/blob/25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc/query.go#L67-L97 | train |
jackc/pgx | query.go | fatal | func (rows *Rows) fatal(err error) {
if rows.err != nil {
return
}
rows.err = err
rows.Close()
} | go | func (rows *Rows) fatal(err error) {
if rows.err != nil {
return
}
rows.err = err
rows.Close()
} | [
"func",
"(",
"rows",
"*",
"Rows",
")",
"fatal",
"(",
"err",
"error",
")",
"{",
"if",
"rows",
".",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n\n",
"rows",
".",
"err",
"=",
"err",
"\n",
"rows",
".",
"Close",
"(",
")",
"\n",
"}"
] | // fatal signals an error occurred after the query was sent to the server. It
// closes the rows automatically. | [
"fatal",
"signals",
"an",
"error",
"occurred",
"after",
"the",
"query",
"was",
"sent",
"to",
"the",
"server",
".",
"It",
"closes",
"the",
"rows",
"automatically",
"."
] | 25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc | https://github.com/jackc/pgx/blob/25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc/query.go#L105-L112 | train |
jackc/pgx | query.go | Next | func (rows *Rows) Next() bool {
if rows.closed {
return false
}
rows.rowCount++
rows.columnIdx = 0
for {
msg, err := rows.conn.rxMsg()
if err != nil {
rows.fatal(err)
return false
}
switch msg := msg.(type) {
case *pgproto3.RowDescription:
rows.fields = rows.conn.rxRowDescription(msg)
for i := range rows.fields {
if dt, ok := rows.conn.ConnInfo.DataTypeForOID(rows.fields[i].DataType); ok {
rows.fields[i].DataTypeName = dt.Name
rows.fields[i].FormatCode = TextFormatCode
} else {
fd := rows.fields[i]
rows.fatal(errors.Errorf("unknown oid: %d, name: %s", fd.DataType, fd.Name))
return false
}
}
case *pgproto3.DataRow:
if len(msg.Values) != len(rows.fields) {
rows.fatal(ProtocolError(fmt.Sprintf("Row description field count (%v) and data row field count (%v) do not match", len(rows.fields), len(msg.Values))))
return false
}
rows.values = msg.Values
return true
case *pgproto3.CommandComplete:
if rows.batch != nil {
rows.batch.pendingCommandComplete = false
}
rows.Close()
return false
default:
err = rows.conn.processContextFreeMsg(msg)
if err != nil {
rows.fatal(err)
return false
}
}
}
} | go | func (rows *Rows) Next() bool {
if rows.closed {
return false
}
rows.rowCount++
rows.columnIdx = 0
for {
msg, err := rows.conn.rxMsg()
if err != nil {
rows.fatal(err)
return false
}
switch msg := msg.(type) {
case *pgproto3.RowDescription:
rows.fields = rows.conn.rxRowDescription(msg)
for i := range rows.fields {
if dt, ok := rows.conn.ConnInfo.DataTypeForOID(rows.fields[i].DataType); ok {
rows.fields[i].DataTypeName = dt.Name
rows.fields[i].FormatCode = TextFormatCode
} else {
fd := rows.fields[i]
rows.fatal(errors.Errorf("unknown oid: %d, name: %s", fd.DataType, fd.Name))
return false
}
}
case *pgproto3.DataRow:
if len(msg.Values) != len(rows.fields) {
rows.fatal(ProtocolError(fmt.Sprintf("Row description field count (%v) and data row field count (%v) do not match", len(rows.fields), len(msg.Values))))
return false
}
rows.values = msg.Values
return true
case *pgproto3.CommandComplete:
if rows.batch != nil {
rows.batch.pendingCommandComplete = false
}
rows.Close()
return false
default:
err = rows.conn.processContextFreeMsg(msg)
if err != nil {
rows.fatal(err)
return false
}
}
}
} | [
"func",
"(",
"rows",
"*",
"Rows",
")",
"Next",
"(",
")",
"bool",
"{",
"if",
"rows",
".",
"closed",
"{",
"return",
"false",
"\n",
"}",
"\n\n",
"rows",
".",
"rowCount",
"++",
"\n",
"rows",
".",
"columnIdx",
"=",
"0",
"\n\n",
"for",
"{",
"msg",
",",... | // Next prepares the next row for reading. It returns true if there is another
// row and false if no more rows are available. It automatically closes rows
// when all rows are read. | [
"Next",
"prepares",
"the",
"next",
"row",
"for",
"reading",
".",
"It",
"returns",
"true",
"if",
"there",
"is",
"another",
"row",
"and",
"false",
"if",
"no",
"more",
"rows",
"are",
"available",
".",
"It",
"automatically",
"closes",
"rows",
"when",
"all",
... | 25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc | https://github.com/jackc/pgx/blob/25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc/query.go#L117-L168 | train |
jackc/pgx | query.go | Values | func (rows *Rows) Values() ([]interface{}, error) {
if rows.closed {
return nil, errors.New("rows is closed")
}
values := make([]interface{}, 0, len(rows.fields))
for range rows.fields {
buf, fd, _ := rows.nextColumn()
if buf == nil {
values = append(values, nil)
continue
}
if dt, ok := rows.conn.ConnInfo.DataTypeForOID(fd.DataType); ok {
value := reflect.New(reflect.ValueOf(dt.Value).Elem().Type()).Interface().(pgtype.Value)
switch fd.FormatCode {
case TextFormatCode:
decoder := value.(pgtype.TextDecoder)
if decoder == nil {
decoder = &pgtype.GenericText{}
}
err := decoder.DecodeText(rows.conn.ConnInfo, buf)
if err != nil {
rows.fatal(err)
}
values = append(values, decoder.(pgtype.Value).Get())
case BinaryFormatCode:
decoder := value.(pgtype.BinaryDecoder)
if decoder == nil {
decoder = &pgtype.GenericBinary{}
}
err := decoder.DecodeBinary(rows.conn.ConnInfo, buf)
if err != nil {
rows.fatal(err)
}
values = append(values, value.Get())
default:
rows.fatal(errors.New("Unknown format code"))
}
} else {
rows.fatal(errors.New("Unknown type"))
}
if rows.Err() != nil {
return nil, rows.Err()
}
}
return values, rows.Err()
} | go | func (rows *Rows) Values() ([]interface{}, error) {
if rows.closed {
return nil, errors.New("rows is closed")
}
values := make([]interface{}, 0, len(rows.fields))
for range rows.fields {
buf, fd, _ := rows.nextColumn()
if buf == nil {
values = append(values, nil)
continue
}
if dt, ok := rows.conn.ConnInfo.DataTypeForOID(fd.DataType); ok {
value := reflect.New(reflect.ValueOf(dt.Value).Elem().Type()).Interface().(pgtype.Value)
switch fd.FormatCode {
case TextFormatCode:
decoder := value.(pgtype.TextDecoder)
if decoder == nil {
decoder = &pgtype.GenericText{}
}
err := decoder.DecodeText(rows.conn.ConnInfo, buf)
if err != nil {
rows.fatal(err)
}
values = append(values, decoder.(pgtype.Value).Get())
case BinaryFormatCode:
decoder := value.(pgtype.BinaryDecoder)
if decoder == nil {
decoder = &pgtype.GenericBinary{}
}
err := decoder.DecodeBinary(rows.conn.ConnInfo, buf)
if err != nil {
rows.fatal(err)
}
values = append(values, value.Get())
default:
rows.fatal(errors.New("Unknown format code"))
}
} else {
rows.fatal(errors.New("Unknown type"))
}
if rows.Err() != nil {
return nil, rows.Err()
}
}
return values, rows.Err()
} | [
"func",
"(",
"rows",
"*",
"Rows",
")",
"Values",
"(",
")",
"(",
"[",
"]",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"if",
"rows",
".",
"closed",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"v... | // Values returns an array of the row values | [
"Values",
"returns",
"an",
"array",
"of",
"the",
"row",
"values"
] | 25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc | https://github.com/jackc/pgx/blob/25c2375fd84652ac32aa0ecc9a6b872a4ab25cdc/query.go#L276-L328 | train |
Subsets and Splits
SQL Console for semeru/code-text-go
Retrieves a limited set of code samples with their languages, with a specific case adjustment for 'Go' language.