repo stringlengths 5 67 | path stringlengths 4 218 | func_name stringlengths 0 151 | original_string stringlengths 52 373k | language stringclasses 6 values | code stringlengths 52 373k | code_tokens listlengths 10 512 | docstring stringlengths 3 47.2k | docstring_tokens listlengths 3 234 | sha stringlengths 40 40 | url stringlengths 85 339 | partition stringclasses 3 values |
|---|---|---|---|---|---|---|---|---|---|---|---|
theupdateframework/notary | storage/filestore.go | NewFileStore | func NewFileStore(baseDir, fileExt string) (*FilesystemStore, error) {
baseDir = filepath.Clean(baseDir)
if err := createDirectory(baseDir, notary.PrivExecPerms); err != nil {
return nil, err
}
if !strings.HasPrefix(fileExt, ".") {
fileExt = "." + fileExt
}
return &FilesystemStore{
baseDir: baseDir,
ext: fileExt,
}, nil
} | go | func NewFileStore(baseDir, fileExt string) (*FilesystemStore, error) {
baseDir = filepath.Clean(baseDir)
if err := createDirectory(baseDir, notary.PrivExecPerms); err != nil {
return nil, err
}
if !strings.HasPrefix(fileExt, ".") {
fileExt = "." + fileExt
}
return &FilesystemStore{
baseDir: baseDir,
ext: fileExt,
}, nil
} | [
"func",
"NewFileStore",
"(",
"baseDir",
",",
"fileExt",
"string",
")",
"(",
"*",
"FilesystemStore",
",",
"error",
")",
"{",
"baseDir",
"=",
"filepath",
".",
"Clean",
"(",
"baseDir",
")",
"\n",
"if",
"err",
":=",
"createDirectory",
"(",
"baseDir",
",",
"n... | // NewFileStore creates a fully configurable file store | [
"NewFileStore",
"creates",
"a",
"fully",
"configurable",
"file",
"store"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/storage/filestore.go#L18-L31 | train |
theupdateframework/notary | storage/filestore.go | NewPrivateKeyFileStorage | func NewPrivateKeyFileStorage(baseDir, fileExt string) (*FilesystemStore, error) {
baseDir = filepath.Join(baseDir, notary.PrivDir)
myStore, err := NewFileStore(baseDir, fileExt)
myStore.migrateTo0Dot4()
return myStore, err
} | go | func NewPrivateKeyFileStorage(baseDir, fileExt string) (*FilesystemStore, error) {
baseDir = filepath.Join(baseDir, notary.PrivDir)
myStore, err := NewFileStore(baseDir, fileExt)
myStore.migrateTo0Dot4()
return myStore, err
} | [
"func",
"NewPrivateKeyFileStorage",
"(",
"baseDir",
",",
"fileExt",
"string",
")",
"(",
"*",
"FilesystemStore",
",",
"error",
")",
"{",
"baseDir",
"=",
"filepath",
".",
"Join",
"(",
"baseDir",
",",
"notary",
".",
"PrivDir",
")",
"\n",
"myStore",
",",
"err"... | // NewPrivateKeyFileStorage initializes a new filestore for private keys, appending
// the notary.PrivDir to the baseDir. | [
"NewPrivateKeyFileStorage",
"initializes",
"a",
"new",
"filestore",
"for",
"private",
"keys",
"appending",
"the",
"notary",
".",
"PrivDir",
"to",
"the",
"baseDir",
"."
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/storage/filestore.go#L35-L40 | train |
theupdateframework/notary | storage/filestore.go | Get | func (f *FilesystemStore) Get(name string) ([]byte, error) {
p, err := f.getPath(name)
if err != nil {
return nil, err
}
meta, err := ioutil.ReadFile(p)
if err != nil {
if os.IsNotExist(err) {
err = ErrMetaNotFound{Resource: name}
}
return nil, err
}
return meta, nil
} | go | func (f *FilesystemStore) Get(name string) ([]byte, error) {
p, err := f.getPath(name)
if err != nil {
return nil, err
}
meta, err := ioutil.ReadFile(p)
if err != nil {
if os.IsNotExist(err) {
err = ErrMetaNotFound{Resource: name}
}
return nil, err
}
return meta, nil
} | [
"func",
"(",
"f",
"*",
"FilesystemStore",
")",
"Get",
"(",
"name",
"string",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"p",
",",
"err",
":=",
"f",
".",
"getPath",
"(",
"name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",... | // Get returns the meta for the given name. | [
"Get",
"returns",
"the",
"meta",
"for",
"the",
"given",
"name",
"."
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/storage/filestore.go#L166-L179 | train |
theupdateframework/notary | storage/filestore.go | SetMulti | func (f *FilesystemStore) SetMulti(metas map[string][]byte) error {
for role, blob := range metas {
err := f.Set(role, blob)
if err != nil {
return err
}
}
return nil
} | go | func (f *FilesystemStore) SetMulti(metas map[string][]byte) error {
for role, blob := range metas {
err := f.Set(role, blob)
if err != nil {
return err
}
}
return nil
} | [
"func",
"(",
"f",
"*",
"FilesystemStore",
")",
"SetMulti",
"(",
"metas",
"map",
"[",
"string",
"]",
"[",
"]",
"byte",
")",
"error",
"{",
"for",
"role",
",",
"blob",
":=",
"range",
"metas",
"{",
"err",
":=",
"f",
".",
"Set",
"(",
"role",
",",
"blo... | // SetMulti sets the metadata for multiple roles in one operation | [
"SetMulti",
"sets",
"the",
"metadata",
"for",
"multiple",
"roles",
"in",
"one",
"operation"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/storage/filestore.go#L182-L190 | train |
theupdateframework/notary | storage/filestore.go | Set | func (f *FilesystemStore) Set(name string, meta []byte) error {
fp, err := f.getPath(name)
if err != nil {
return err
}
// Ensures the parent directories of the file we are about to write exist
err = os.MkdirAll(filepath.Dir(fp), notary.PrivExecPerms)
if err != nil {
return err
}
// if something already exists, just delete it and re-write it
os.RemoveAll(fp)
// Write the file to disk
return ioutil.WriteFile(fp, meta, notary.PrivNoExecPerms)
} | go | func (f *FilesystemStore) Set(name string, meta []byte) error {
fp, err := f.getPath(name)
if err != nil {
return err
}
// Ensures the parent directories of the file we are about to write exist
err = os.MkdirAll(filepath.Dir(fp), notary.PrivExecPerms)
if err != nil {
return err
}
// if something already exists, just delete it and re-write it
os.RemoveAll(fp)
// Write the file to disk
return ioutil.WriteFile(fp, meta, notary.PrivNoExecPerms)
} | [
"func",
"(",
"f",
"*",
"FilesystemStore",
")",
"Set",
"(",
"name",
"string",
",",
"meta",
"[",
"]",
"byte",
")",
"error",
"{",
"fp",
",",
"err",
":=",
"f",
".",
"getPath",
"(",
"name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
... | // Set sets the meta for a single role | [
"Set",
"sets",
"the",
"meta",
"for",
"a",
"single",
"role"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/storage/filestore.go#L193-L210 | train |
theupdateframework/notary | storage/httpstore.go | NewNotaryServerStore | func NewNotaryServerStore(serverURL string, gun data.GUN, roundTrip http.RoundTripper) (RemoteStore, error) {
return NewHTTPStore(
serverURL+"/v2/"+gun.String()+"/_trust/tuf/",
"",
"json",
"key",
roundTrip,
)
} | go | func NewNotaryServerStore(serverURL string, gun data.GUN, roundTrip http.RoundTripper) (RemoteStore, error) {
return NewHTTPStore(
serverURL+"/v2/"+gun.String()+"/_trust/tuf/",
"",
"json",
"key",
roundTrip,
)
} | [
"func",
"NewNotaryServerStore",
"(",
"serverURL",
"string",
",",
"gun",
"data",
".",
"GUN",
",",
"roundTrip",
"http",
".",
"RoundTripper",
")",
"(",
"RemoteStore",
",",
"error",
")",
"{",
"return",
"NewHTTPStore",
"(",
"serverURL",
"+",
"\"/v2/\"",
"+",
"gun... | // NewNotaryServerStore returns a new HTTPStore against a URL which should represent a notary
// server | [
"NewNotaryServerStore",
"returns",
"a",
"new",
"HTTPStore",
"against",
"a",
"URL",
"which",
"should",
"represent",
"a",
"notary",
"server"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/storage/httpstore.go#L116-L124 | train |
theupdateframework/notary | storage/httpstore.go | NewHTTPStore | func NewHTTPStore(baseURL, metaPrefix, metaExtension, keyExtension string, roundTrip http.RoundTripper) (RemoteStore, error) {
base, err := url.Parse(baseURL)
if err != nil {
return nil, err
}
if !base.IsAbs() {
return nil, errors.New("HTTPStore requires an absolute baseURL")
}
if roundTrip == nil {
return &OfflineStore{}, nil
}
return &HTTPStore{
baseURL: *base,
metaPrefix: metaPrefix,
metaExtension: metaExtension,
keyExtension: keyExtension,
roundTrip: roundTrip,
}, nil
} | go | func NewHTTPStore(baseURL, metaPrefix, metaExtension, keyExtension string, roundTrip http.RoundTripper) (RemoteStore, error) {
base, err := url.Parse(baseURL)
if err != nil {
return nil, err
}
if !base.IsAbs() {
return nil, errors.New("HTTPStore requires an absolute baseURL")
}
if roundTrip == nil {
return &OfflineStore{}, nil
}
return &HTTPStore{
baseURL: *base,
metaPrefix: metaPrefix,
metaExtension: metaExtension,
keyExtension: keyExtension,
roundTrip: roundTrip,
}, nil
} | [
"func",
"NewHTTPStore",
"(",
"baseURL",
",",
"metaPrefix",
",",
"metaExtension",
",",
"keyExtension",
"string",
",",
"roundTrip",
"http",
".",
"RoundTripper",
")",
"(",
"RemoteStore",
",",
"error",
")",
"{",
"base",
",",
"err",
":=",
"url",
".",
"Parse",
"... | // NewHTTPStore initializes a new store against a URL and a number of configuration options.
//
// In case of a nil `roundTrip`, a default offline store is used instead. | [
"NewHTTPStore",
"initializes",
"a",
"new",
"store",
"against",
"a",
"URL",
"and",
"a",
"number",
"of",
"configuration",
"options",
".",
"In",
"case",
"of",
"a",
"nil",
"roundTrip",
"a",
"default",
"offline",
"store",
"is",
"used",
"instead",
"."
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/storage/httpstore.go#L129-L147 | train |
theupdateframework/notary | storage/httpstore.go | GetSized | func (s HTTPStore) GetSized(name string, size int64) ([]byte, error) {
url, err := s.buildMetaURL(name)
if err != nil {
return nil, err
}
req, err := http.NewRequest("GET", url.String(), nil)
if err != nil {
return nil, err
}
resp, err := s.roundTrip.RoundTrip(req)
if err != nil {
return nil, NetworkError{Wrapped: err}
}
defer resp.Body.Close()
if err := translateStatusToError(resp, name); err != nil {
logrus.Debugf("received HTTP status %d when requesting %s.", resp.StatusCode, name)
return nil, err
}
if size == NoSizeLimit {
size = notary.MaxDownloadSize
}
if resp.ContentLength > size {
return nil, ErrMaliciousServer{}
}
logrus.Debugf("%d when retrieving metadata for %s", resp.StatusCode, name)
b := io.LimitReader(resp.Body, size)
body, err := ioutil.ReadAll(b)
if err != nil {
return nil, err
}
return body, nil
} | go | func (s HTTPStore) GetSized(name string, size int64) ([]byte, error) {
url, err := s.buildMetaURL(name)
if err != nil {
return nil, err
}
req, err := http.NewRequest("GET", url.String(), nil)
if err != nil {
return nil, err
}
resp, err := s.roundTrip.RoundTrip(req)
if err != nil {
return nil, NetworkError{Wrapped: err}
}
defer resp.Body.Close()
if err := translateStatusToError(resp, name); err != nil {
logrus.Debugf("received HTTP status %d when requesting %s.", resp.StatusCode, name)
return nil, err
}
if size == NoSizeLimit {
size = notary.MaxDownloadSize
}
if resp.ContentLength > size {
return nil, ErrMaliciousServer{}
}
logrus.Debugf("%d when retrieving metadata for %s", resp.StatusCode, name)
b := io.LimitReader(resp.Body, size)
body, err := ioutil.ReadAll(b)
if err != nil {
return nil, err
}
return body, nil
} | [
"func",
"(",
"s",
"HTTPStore",
")",
"GetSized",
"(",
"name",
"string",
",",
"size",
"int64",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"url",
",",
"err",
":=",
"s",
".",
"buildMetaURL",
"(",
"name",
")",
"\n",
"if",
"err",
"!=",
"nil",
... | // GetSized downloads the named meta file with the given size. A short body
// is acceptable because in the case of timestamp.json, the size is a cap,
// not an exact length.
// If size is "NoSizeLimit", this corresponds to "infinite," but we cut off at a
// predefined threshold "notary.MaxDownloadSize". | [
"GetSized",
"downloads",
"the",
"named",
"meta",
"file",
"with",
"the",
"given",
"size",
".",
"A",
"short",
"body",
"is",
"acceptable",
"because",
"in",
"the",
"case",
"of",
"timestamp",
".",
"json",
"the",
"size",
"is",
"a",
"cap",
"not",
"an",
"exact",... | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/storage/httpstore.go#L191-L222 | train |
theupdateframework/notary | storage/httpstore.go | Set | func (s HTTPStore) Set(name string, blob []byte) error {
return s.SetMulti(map[string][]byte{name: blob})
} | go | func (s HTTPStore) Set(name string, blob []byte) error {
return s.SetMulti(map[string][]byte{name: blob})
} | [
"func",
"(",
"s",
"HTTPStore",
")",
"Set",
"(",
"name",
"string",
",",
"blob",
"[",
"]",
"byte",
")",
"error",
"{",
"return",
"s",
".",
"SetMulti",
"(",
"map",
"[",
"string",
"]",
"[",
"]",
"byte",
"{",
"name",
":",
"blob",
"}",
")",
"\n",
"}"
... | // Set sends a single piece of metadata to the TUF server | [
"Set",
"sends",
"a",
"single",
"piece",
"of",
"metadata",
"to",
"the",
"TUF",
"server"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/storage/httpstore.go#L225-L227 | train |
theupdateframework/notary | storage/httpstore.go | NewMultiPartMetaRequest | func NewMultiPartMetaRequest(url string, metas map[string][]byte) (*http.Request, error) {
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
for role, blob := range metas {
part, err := writer.CreateFormFile("files", role)
if err != nil {
return nil, err
}
_, err = io.Copy(part, bytes.NewBuffer(blob))
if err != nil {
return nil, err
}
}
err := writer.Close()
if err != nil {
return nil, err
}
req, err := http.NewRequest("POST", url, body)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", writer.FormDataContentType())
return req, nil
} | go | func NewMultiPartMetaRequest(url string, metas map[string][]byte) (*http.Request, error) {
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
for role, blob := range metas {
part, err := writer.CreateFormFile("files", role)
if err != nil {
return nil, err
}
_, err = io.Copy(part, bytes.NewBuffer(blob))
if err != nil {
return nil, err
}
}
err := writer.Close()
if err != nil {
return nil, err
}
req, err := http.NewRequest("POST", url, body)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", writer.FormDataContentType())
return req, nil
} | [
"func",
"NewMultiPartMetaRequest",
"(",
"url",
"string",
",",
"metas",
"map",
"[",
"string",
"]",
"[",
"]",
"byte",
")",
"(",
"*",
"http",
".",
"Request",
",",
"error",
")",
"{",
"body",
":=",
"&",
"bytes",
".",
"Buffer",
"{",
"}",
"\n",
"writer",
... | // NewMultiPartMetaRequest builds a request with the provided metadata updates
// in multipart form | [
"NewMultiPartMetaRequest",
"builds",
"a",
"request",
"with",
"the",
"provided",
"metadata",
"updates",
"in",
"multipart",
"form"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/storage/httpstore.go#L237-L260 | train |
theupdateframework/notary | storage/httpstore.go | SetMulti | func (s HTTPStore) SetMulti(metas map[string][]byte) error {
url, err := s.buildMetaURL("")
if err != nil {
return err
}
req, err := NewMultiPartMetaRequest(url.String(), metas)
if err != nil {
return err
}
resp, err := s.roundTrip.RoundTrip(req)
if err != nil {
return NetworkError{Wrapped: err}
}
defer resp.Body.Close()
// if this 404's something is pretty wrong
return translateStatusToError(resp, "POST metadata endpoint")
} | go | func (s HTTPStore) SetMulti(metas map[string][]byte) error {
url, err := s.buildMetaURL("")
if err != nil {
return err
}
req, err := NewMultiPartMetaRequest(url.String(), metas)
if err != nil {
return err
}
resp, err := s.roundTrip.RoundTrip(req)
if err != nil {
return NetworkError{Wrapped: err}
}
defer resp.Body.Close()
// if this 404's something is pretty wrong
return translateStatusToError(resp, "POST metadata endpoint")
} | [
"func",
"(",
"s",
"HTTPStore",
")",
"SetMulti",
"(",
"metas",
"map",
"[",
"string",
"]",
"[",
"]",
"byte",
")",
"error",
"{",
"url",
",",
"err",
":=",
"s",
".",
"buildMetaURL",
"(",
"\"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err... | // SetMulti does a single batch upload of multiple pieces of TUF metadata.
// This should be preferred for updating a remote server as it enable the server
// to remain consistent, either accepting or rejecting the complete update. | [
"SetMulti",
"does",
"a",
"single",
"batch",
"upload",
"of",
"multiple",
"pieces",
"of",
"TUF",
"metadata",
".",
"This",
"should",
"be",
"preferred",
"for",
"updating",
"a",
"remote",
"server",
"as",
"it",
"enable",
"the",
"server",
"to",
"remain",
"consisten... | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/storage/httpstore.go#L265-L281 | train |
theupdateframework/notary | storage/httpstore.go | RemoveAll | func (s HTTPStore) RemoveAll() error {
url, err := s.buildMetaURL("")
if err != nil {
return err
}
req, err := http.NewRequest("DELETE", url.String(), nil)
if err != nil {
return err
}
resp, err := s.roundTrip.RoundTrip(req)
if err != nil {
return NetworkError{Wrapped: err}
}
defer resp.Body.Close()
return translateStatusToError(resp, "DELETE metadata for GUN endpoint")
} | go | func (s HTTPStore) RemoveAll() error {
url, err := s.buildMetaURL("")
if err != nil {
return err
}
req, err := http.NewRequest("DELETE", url.String(), nil)
if err != nil {
return err
}
resp, err := s.roundTrip.RoundTrip(req)
if err != nil {
return NetworkError{Wrapped: err}
}
defer resp.Body.Close()
return translateStatusToError(resp, "DELETE metadata for GUN endpoint")
} | [
"func",
"(",
"s",
"HTTPStore",
")",
"RemoveAll",
"(",
")",
"error",
"{",
"url",
",",
"err",
":=",
"s",
".",
"buildMetaURL",
"(",
"\"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"req",
",",
"err",
":=",
"http",
... | // RemoveAll will attempt to delete all TUF metadata for a GUN | [
"RemoveAll",
"will",
"attempt",
"to",
"delete",
"all",
"TUF",
"metadata",
"for",
"a",
"GUN"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/storage/httpstore.go#L284-L299 | train |
theupdateframework/notary | storage/httpstore.go | GetKey | func (s HTTPStore) GetKey(role data.RoleName) ([]byte, error) {
url, err := s.buildKeyURL(role)
if err != nil {
return nil, err
}
req, err := http.NewRequest("GET", url.String(), nil)
if err != nil {
return nil, err
}
resp, err := s.roundTrip.RoundTrip(req)
if err != nil {
return nil, NetworkError{Wrapped: err}
}
defer resp.Body.Close()
if err := translateStatusToError(resp, role.String()+" key"); err != nil {
return nil, err
}
b := io.LimitReader(resp.Body, MaxKeySize)
body, err := ioutil.ReadAll(b)
if err != nil {
return nil, err
}
return body, nil
} | go | func (s HTTPStore) GetKey(role data.RoleName) ([]byte, error) {
url, err := s.buildKeyURL(role)
if err != nil {
return nil, err
}
req, err := http.NewRequest("GET", url.String(), nil)
if err != nil {
return nil, err
}
resp, err := s.roundTrip.RoundTrip(req)
if err != nil {
return nil, NetworkError{Wrapped: err}
}
defer resp.Body.Close()
if err := translateStatusToError(resp, role.String()+" key"); err != nil {
return nil, err
}
b := io.LimitReader(resp.Body, MaxKeySize)
body, err := ioutil.ReadAll(b)
if err != nil {
return nil, err
}
return body, nil
} | [
"func",
"(",
"s",
"HTTPStore",
")",
"GetKey",
"(",
"role",
"data",
".",
"RoleName",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"url",
",",
"err",
":=",
"s",
".",
"buildKeyURL",
"(",
"role",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"re... | // GetKey retrieves a public key from the remote server | [
"GetKey",
"retrieves",
"a",
"public",
"key",
"from",
"the",
"remote",
"server"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/storage/httpstore.go#L325-L348 | train |
go-gomail/gomail | send.go | Send | func Send(s Sender, msg ...*Message) error {
for i, m := range msg {
if err := send(s, m); err != nil {
return fmt.Errorf("gomail: could not send email %d: %v", i+1, err)
}
}
return nil
} | go | func Send(s Sender, msg ...*Message) error {
for i, m := range msg {
if err := send(s, m); err != nil {
return fmt.Errorf("gomail: could not send email %d: %v", i+1, err)
}
}
return nil
} | [
"func",
"Send",
"(",
"s",
"Sender",
",",
"msg",
"...",
"*",
"Message",
")",
"error",
"{",
"for",
"i",
",",
"m",
":=",
"range",
"msg",
"{",
"if",
"err",
":=",
"send",
"(",
"s",
",",
"m",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",... | // Send sends emails using the given Sender. | [
"Send",
"sends",
"emails",
"using",
"the",
"given",
"Sender",
"."
] | 81ebce5c23dfd25c6c67194b37d3dd3f338c98b1 | https://github.com/go-gomail/gomail/blob/81ebce5c23dfd25c6c67194b37d3dd3f338c98b1/send.go#L36-L44 | train |
go-gomail/gomail | smtp.go | NewDialer | func NewDialer(host string, port int, username, password string) *Dialer {
return &Dialer{
Host: host,
Port: port,
Username: username,
Password: password,
SSL: port == 465,
}
} | go | func NewDialer(host string, port int, username, password string) *Dialer {
return &Dialer{
Host: host,
Port: port,
Username: username,
Password: password,
SSL: port == 465,
}
} | [
"func",
"NewDialer",
"(",
"host",
"string",
",",
"port",
"int",
",",
"username",
",",
"password",
"string",
")",
"*",
"Dialer",
"{",
"return",
"&",
"Dialer",
"{",
"Host",
":",
"host",
",",
"Port",
":",
"port",
",",
"Username",
":",
"username",
",",
"... | // NewDialer returns a new SMTP Dialer. The given parameters are used to connect
// to the SMTP server. | [
"NewDialer",
"returns",
"a",
"new",
"SMTP",
"Dialer",
".",
"The",
"given",
"parameters",
"are",
"used",
"to",
"connect",
"to",
"the",
"SMTP",
"server",
"."
] | 81ebce5c23dfd25c6c67194b37d3dd3f338c98b1 | https://github.com/go-gomail/gomail/blob/81ebce5c23dfd25c6c67194b37d3dd3f338c98b1/smtp.go#L40-L48 | train |
go-gomail/gomail | smtp.go | Dial | func (d *Dialer) Dial() (SendCloser, error) {
conn, err := netDialTimeout("tcp", addr(d.Host, d.Port), 10*time.Second)
if err != nil {
return nil, err
}
if d.SSL {
conn = tlsClient(conn, d.tlsConfig())
}
c, err := smtpNewClient(conn, d.Host)
if err != nil {
return nil, err
}
if d.LocalName != "" {
if err := c.Hello(d.LocalName); err != nil {
return nil, err
}
}
if !d.SSL {
if ok, _ := c.Extension("STARTTLS"); ok {
if err := c.StartTLS(d.tlsConfig()); err != nil {
c.Close()
return nil, err
}
}
}
if d.Auth == nil && d.Username != "" {
if ok, auths := c.Extension("AUTH"); ok {
if strings.Contains(auths, "CRAM-MD5") {
d.Auth = smtp.CRAMMD5Auth(d.Username, d.Password)
} else if strings.Contains(auths, "LOGIN") &&
!strings.Contains(auths, "PLAIN") {
d.Auth = &loginAuth{
username: d.Username,
password: d.Password,
host: d.Host,
}
} else {
d.Auth = smtp.PlainAuth("", d.Username, d.Password, d.Host)
}
}
}
if d.Auth != nil {
if err = c.Auth(d.Auth); err != nil {
c.Close()
return nil, err
}
}
return &smtpSender{c, d}, nil
} | go | func (d *Dialer) Dial() (SendCloser, error) {
conn, err := netDialTimeout("tcp", addr(d.Host, d.Port), 10*time.Second)
if err != nil {
return nil, err
}
if d.SSL {
conn = tlsClient(conn, d.tlsConfig())
}
c, err := smtpNewClient(conn, d.Host)
if err != nil {
return nil, err
}
if d.LocalName != "" {
if err := c.Hello(d.LocalName); err != nil {
return nil, err
}
}
if !d.SSL {
if ok, _ := c.Extension("STARTTLS"); ok {
if err := c.StartTLS(d.tlsConfig()); err != nil {
c.Close()
return nil, err
}
}
}
if d.Auth == nil && d.Username != "" {
if ok, auths := c.Extension("AUTH"); ok {
if strings.Contains(auths, "CRAM-MD5") {
d.Auth = smtp.CRAMMD5Auth(d.Username, d.Password)
} else if strings.Contains(auths, "LOGIN") &&
!strings.Contains(auths, "PLAIN") {
d.Auth = &loginAuth{
username: d.Username,
password: d.Password,
host: d.Host,
}
} else {
d.Auth = smtp.PlainAuth("", d.Username, d.Password, d.Host)
}
}
}
if d.Auth != nil {
if err = c.Auth(d.Auth); err != nil {
c.Close()
return nil, err
}
}
return &smtpSender{c, d}, nil
} | [
"func",
"(",
"d",
"*",
"Dialer",
")",
"Dial",
"(",
")",
"(",
"SendCloser",
",",
"error",
")",
"{",
"conn",
",",
"err",
":=",
"netDialTimeout",
"(",
"\"tcp\"",
",",
"addr",
"(",
"d",
".",
"Host",
",",
"d",
".",
"Port",
")",
",",
"10",
"*",
"time... | // Dial dials and authenticates to an SMTP server. The returned SendCloser
// should be closed when done using it. | [
"Dial",
"dials",
"and",
"authenticates",
"to",
"an",
"SMTP",
"server",
".",
"The",
"returned",
"SendCloser",
"should",
"be",
"closed",
"when",
"done",
"using",
"it",
"."
] | 81ebce5c23dfd25c6c67194b37d3dd3f338c98b1 | https://github.com/go-gomail/gomail/blob/81ebce5c23dfd25c6c67194b37d3dd3f338c98b1/smtp.go#L60-L115 | train |
go-gomail/gomail | message.go | SetBody | func (m *Message) SetBody(contentType, body string, settings ...PartSetting) {
m.parts = []*part{m.newPart(contentType, newCopier(body), settings)}
} | go | func (m *Message) SetBody(contentType, body string, settings ...PartSetting) {
m.parts = []*part{m.newPart(contentType, newCopier(body), settings)}
} | [
"func",
"(",
"m",
"*",
"Message",
")",
"SetBody",
"(",
"contentType",
",",
"body",
"string",
",",
"settings",
"...",
"PartSetting",
")",
"{",
"m",
".",
"parts",
"=",
"[",
"]",
"*",
"part",
"{",
"m",
".",
"newPart",
"(",
"contentType",
",",
"newCopier... | // SetBody sets the body of the message. It replaces any content previously set
// by SetBody, AddAlternative or AddAlternativeWriter. | [
"SetBody",
"sets",
"the",
"body",
"of",
"the",
"message",
".",
"It",
"replaces",
"any",
"content",
"previously",
"set",
"by",
"SetBody",
"AddAlternative",
"or",
"AddAlternativeWriter",
"."
] | 81ebce5c23dfd25c6c67194b37d3dd3f338c98b1 | https://github.com/go-gomail/gomail/blob/81ebce5c23dfd25c6c67194b37d3dd3f338c98b1/message.go#L187-L189 | train |
swaggo/gin-swagger | swaggerFiles/ab0x.go | Open | func (hfs *HTTPFS) Open(path string) (http.File, error) {
f, err := FS.OpenFile(CTX, path, os.O_RDONLY, 0644)
if err != nil {
return nil, err
}
return f, nil
} | go | func (hfs *HTTPFS) Open(path string) (http.File, error) {
f, err := FS.OpenFile(CTX, path, os.O_RDONLY, 0644)
if err != nil {
return nil, err
}
return f, nil
} | [
"func",
"(",
"hfs",
"*",
"HTTPFS",
")",
"Open",
"(",
"path",
"string",
")",
"(",
"http",
".",
"File",
",",
"error",
")",
"{",
"f",
",",
"err",
":=",
"FS",
".",
"OpenFile",
"(",
"CTX",
",",
"path",
",",
"os",
".",
"O_RDONLY",
",",
"0644",
")",
... | // Open a file | [
"Open",
"a",
"file"
] | dbf6ef410096ed3b4a467a14040e019fd7a0f85a | https://github.com/swaggo/gin-swagger/blob/dbf6ef410096ed3b4a467a14040e019fd7a0f85a/swaggerFiles/ab0x.go#L50-L57 | train |
swaggo/gin-swagger | swaggerFiles/ab0x.go | ReadFile | func ReadFile(path string) ([]byte, error) {
f, err := FS.OpenFile(CTX, path, os.O_RDONLY, 0644)
if err != nil {
return nil, err
}
buf := bytes.NewBuffer(make([]byte, 0, bytes.MinRead))
// If the buffer overflows, we will get bytes.ErrTooLarge.
// Return that as an error. Any other panic remains.
defer func() {
e := recover()
if e == nil {
return
}
if panicErr, ok := e.(error); ok && panicErr == bytes.ErrTooLarge {
err = panicErr
} else {
panic(e)
}
}()
_, err = buf.ReadFrom(f)
return buf.Bytes(), err
} | go | func ReadFile(path string) ([]byte, error) {
f, err := FS.OpenFile(CTX, path, os.O_RDONLY, 0644)
if err != nil {
return nil, err
}
buf := bytes.NewBuffer(make([]byte, 0, bytes.MinRead))
// If the buffer overflows, we will get bytes.ErrTooLarge.
// Return that as an error. Any other panic remains.
defer func() {
e := recover()
if e == nil {
return
}
if panicErr, ok := e.(error); ok && panicErr == bytes.ErrTooLarge {
err = panicErr
} else {
panic(e)
}
}()
_, err = buf.ReadFrom(f)
return buf.Bytes(), err
} | [
"func",
"ReadFile",
"(",
"path",
"string",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"f",
",",
"err",
":=",
"FS",
".",
"OpenFile",
"(",
"CTX",
",",
"path",
",",
"os",
".",
"O_RDONLY",
",",
"0644",
")",
"\n",
"if",
"err",
"!=",
"nil",
... | // ReadFile is adapTed from ioutil | [
"ReadFile",
"is",
"adapTed",
"from",
"ioutil"
] | dbf6ef410096ed3b4a467a14040e019fd7a0f85a | https://github.com/swaggo/gin-swagger/blob/dbf6ef410096ed3b4a467a14040e019fd7a0f85a/swaggerFiles/ab0x.go#L60-L83 | train |
swaggo/gin-swagger | swagger.go | WrapHandler | func WrapHandler(h *webdav.Handler, confs ...func(c *Config)) gin.HandlerFunc {
defaultConfig := &Config{
URL: "doc.json",
}
for _, c := range confs {
c(defaultConfig)
}
return CustomWrapHandler(defaultConfig, h)
} | go | func WrapHandler(h *webdav.Handler, confs ...func(c *Config)) gin.HandlerFunc {
defaultConfig := &Config{
URL: "doc.json",
}
for _, c := range confs {
c(defaultConfig)
}
return CustomWrapHandler(defaultConfig, h)
} | [
"func",
"WrapHandler",
"(",
"h",
"*",
"webdav",
".",
"Handler",
",",
"confs",
"...",
"func",
"(",
"c",
"*",
"Config",
")",
")",
"gin",
".",
"HandlerFunc",
"{",
"defaultConfig",
":=",
"&",
"Config",
"{",
"URL",
":",
"\"doc.json\"",
",",
"}",
"\n",
"fo... | // WrapHandler wraps `http.Handler` into `gin.HandlerFunc`. | [
"WrapHandler",
"wraps",
"http",
".",
"Handler",
"into",
"gin",
".",
"HandlerFunc",
"."
] | dbf6ef410096ed3b4a467a14040e019fd7a0f85a | https://github.com/swaggo/gin-swagger/blob/dbf6ef410096ed3b4a467a14040e019fd7a0f85a/swagger.go#L29-L39 | train |
swaggo/gin-swagger | swagger.go | CustomWrapHandler | func CustomWrapHandler(config *Config, h *webdav.Handler) gin.HandlerFunc {
//create a template with name
t := template.New("swagger_index.html")
index, _ := t.Parse(swagger_index_templ)
var rexp = regexp.MustCompile(`(.*)(index\.html|doc\.json|favicon-16x16\.png|favicon-32x32\.png|/oauth2-redirect\.html|swagger-ui\.css|swagger-ui\.css\.map|swagger-ui\.js|swagger-ui\.js\.map|swagger-ui-bundle\.js|swagger-ui-bundle\.js\.map|swagger-ui-standalone-preset\.js|swagger-ui-standalone-preset\.js\.map)[\?|.]*`)
return func(c *gin.Context) {
type swaggerUIBundle struct {
URL string
}
var matches []string
if matches = rexp.FindStringSubmatch(c.Request.RequestURI); len(matches) != 3 {
c.Status(404)
c.Writer.Write([]byte("404 page not found"))
return
}
path := matches[2]
prefix := matches[1]
h.Prefix = prefix
if strings.HasSuffix(path, ".html") {
c.Header("Content-Type", "text/html; charset=utf-8")
} else if strings.HasSuffix(path, ".css") {
c.Header("Content-Type", "text/css; charset=utf-8")
} else if strings.HasSuffix(path, ".js") {
c.Header("Content-Type", "application/javascript")
} else if strings.HasSuffix(path, ".json") {
c.Header("Content-Type", "application/json")
}
switch path {
case "index.html":
index.Execute(c.Writer, &swaggerUIBundle{
URL: config.URL,
})
case "doc.json":
doc, err := swag.ReadDoc()
if err != nil {
panic(err)
}
c.Writer.Write([]byte(doc))
return
default:
h.ServeHTTP(c.Writer, c.Request)
}
}
} | go | func CustomWrapHandler(config *Config, h *webdav.Handler) gin.HandlerFunc {
//create a template with name
t := template.New("swagger_index.html")
index, _ := t.Parse(swagger_index_templ)
var rexp = regexp.MustCompile(`(.*)(index\.html|doc\.json|favicon-16x16\.png|favicon-32x32\.png|/oauth2-redirect\.html|swagger-ui\.css|swagger-ui\.css\.map|swagger-ui\.js|swagger-ui\.js\.map|swagger-ui-bundle\.js|swagger-ui-bundle\.js\.map|swagger-ui-standalone-preset\.js|swagger-ui-standalone-preset\.js\.map)[\?|.]*`)
return func(c *gin.Context) {
type swaggerUIBundle struct {
URL string
}
var matches []string
if matches = rexp.FindStringSubmatch(c.Request.RequestURI); len(matches) != 3 {
c.Status(404)
c.Writer.Write([]byte("404 page not found"))
return
}
path := matches[2]
prefix := matches[1]
h.Prefix = prefix
if strings.HasSuffix(path, ".html") {
c.Header("Content-Type", "text/html; charset=utf-8")
} else if strings.HasSuffix(path, ".css") {
c.Header("Content-Type", "text/css; charset=utf-8")
} else if strings.HasSuffix(path, ".js") {
c.Header("Content-Type", "application/javascript")
} else if strings.HasSuffix(path, ".json") {
c.Header("Content-Type", "application/json")
}
switch path {
case "index.html":
index.Execute(c.Writer, &swaggerUIBundle{
URL: config.URL,
})
case "doc.json":
doc, err := swag.ReadDoc()
if err != nil {
panic(err)
}
c.Writer.Write([]byte(doc))
return
default:
h.ServeHTTP(c.Writer, c.Request)
}
}
} | [
"func",
"CustomWrapHandler",
"(",
"config",
"*",
"Config",
",",
"h",
"*",
"webdav",
".",
"Handler",
")",
"gin",
".",
"HandlerFunc",
"{",
"t",
":=",
"template",
".",
"New",
"(",
"\"swagger_index.html\"",
")",
"\n",
"index",
",",
"_",
":=",
"t",
".",
"Pa... | // CustomWrapHandler wraps `http.Handler` into `gin.HandlerFunc` | [
"CustomWrapHandler",
"wraps",
"http",
".",
"Handler",
"into",
"gin",
".",
"HandlerFunc"
] | dbf6ef410096ed3b4a467a14040e019fd7a0f85a | https://github.com/swaggo/gin-swagger/blob/dbf6ef410096ed3b4a467a14040e019fd7a0f85a/swagger.go#L42-L91 | train |
swaggo/gin-swagger | swagger.go | DisablingWrapHandler | func DisablingWrapHandler(h *webdav.Handler, envName string) gin.HandlerFunc {
eFlag := os.Getenv(envName)
if eFlag != "" {
return func(c *gin.Context) {
// Simulate behavior when route unspecified and
// return 404 HTTP code
c.String(404, "")
}
}
return WrapHandler(h)
} | go | func DisablingWrapHandler(h *webdav.Handler, envName string) gin.HandlerFunc {
eFlag := os.Getenv(envName)
if eFlag != "" {
return func(c *gin.Context) {
// Simulate behavior when route unspecified and
// return 404 HTTP code
c.String(404, "")
}
}
return WrapHandler(h)
} | [
"func",
"DisablingWrapHandler",
"(",
"h",
"*",
"webdav",
".",
"Handler",
",",
"envName",
"string",
")",
"gin",
".",
"HandlerFunc",
"{",
"eFlag",
":=",
"os",
".",
"Getenv",
"(",
"envName",
")",
"\n",
"if",
"eFlag",
"!=",
"\"\"",
"{",
"return",
"func",
"... | // DisablingWrapHandler turn handler off
// if specified environment variable passed | [
"DisablingWrapHandler",
"turn",
"handler",
"off",
"if",
"specified",
"environment",
"variable",
"passed"
] | dbf6ef410096ed3b4a467a14040e019fd7a0f85a | https://github.com/swaggo/gin-swagger/blob/dbf6ef410096ed3b4a467a14040e019fd7a0f85a/swagger.go#L95-L106 | train |
swaggo/gin-swagger | swagger.go | DisablingCustomWrapHandler | func DisablingCustomWrapHandler(config *Config, h *webdav.Handler, envName string) gin.HandlerFunc {
eFlag := os.Getenv(envName)
if eFlag != "" {
return func(c *gin.Context) {
// Simulate behavior when route unspecified and
// return 404 HTTP code
c.String(404, "")
}
}
return CustomWrapHandler(config, h)
} | go | func DisablingCustomWrapHandler(config *Config, h *webdav.Handler, envName string) gin.HandlerFunc {
eFlag := os.Getenv(envName)
if eFlag != "" {
return func(c *gin.Context) {
// Simulate behavior when route unspecified and
// return 404 HTTP code
c.String(404, "")
}
}
return CustomWrapHandler(config, h)
} | [
"func",
"DisablingCustomWrapHandler",
"(",
"config",
"*",
"Config",
",",
"h",
"*",
"webdav",
".",
"Handler",
",",
"envName",
"string",
")",
"gin",
".",
"HandlerFunc",
"{",
"eFlag",
":=",
"os",
".",
"Getenv",
"(",
"envName",
")",
"\n",
"if",
"eFlag",
"!="... | // DisablingCustomWrapHandler turn handler off
// if specified environment variable passed | [
"DisablingCustomWrapHandler",
"turn",
"handler",
"off",
"if",
"specified",
"environment",
"variable",
"passed"
] | dbf6ef410096ed3b4a467a14040e019fd7a0f85a | https://github.com/swaggo/gin-swagger/blob/dbf6ef410096ed3b4a467a14040e019fd7a0f85a/swagger.go#L110-L121 | train |
gocql/gocql | filters.go | DataCentreHostFilter | func DataCentreHostFilter(dataCentre string) HostFilter {
return HostFilterFunc(func(host *HostInfo) bool {
return host.DataCenter() == dataCentre
})
} | go | func DataCentreHostFilter(dataCentre string) HostFilter {
return HostFilterFunc(func(host *HostInfo) bool {
return host.DataCenter() == dataCentre
})
} | [
"func",
"DataCentreHostFilter",
"(",
"dataCentre",
"string",
")",
"HostFilter",
"{",
"return",
"HostFilterFunc",
"(",
"func",
"(",
"host",
"*",
"HostInfo",
")",
"bool",
"{",
"return",
"host",
".",
"DataCenter",
"(",
")",
"==",
"dataCentre",
"\n",
"}",
")",
... | // DataCentreHostFilter filters all hosts such that they are in the same data centre
// as the supplied data centre. | [
"DataCentreHostFilter",
"filters",
"all",
"hosts",
"such",
"that",
"they",
"are",
"in",
"the",
"same",
"data",
"centre",
"as",
"the",
"supplied",
"data",
"centre",
"."
] | b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac | https://github.com/gocql/gocql/blob/b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac/filters.go#L34-L38 | train |
gocql/gocql | filters.go | WhiteListHostFilter | func WhiteListHostFilter(hosts ...string) HostFilter {
hostInfos, err := addrsToHosts(hosts, 9042)
if err != nil {
// dont want to panic here, but rather not break the API
panic(fmt.Errorf("unable to lookup host info from address: %v", err))
}
m := make(map[string]bool, len(hostInfos))
for _, host := range hostInfos {
m[host.ConnectAddress().String()] = true
}
return HostFilterFunc(func(host *HostInfo) bool {
return m[host.ConnectAddress().String()]
})
} | go | func WhiteListHostFilter(hosts ...string) HostFilter {
hostInfos, err := addrsToHosts(hosts, 9042)
if err != nil {
// dont want to panic here, but rather not break the API
panic(fmt.Errorf("unable to lookup host info from address: %v", err))
}
m := make(map[string]bool, len(hostInfos))
for _, host := range hostInfos {
m[host.ConnectAddress().String()] = true
}
return HostFilterFunc(func(host *HostInfo) bool {
return m[host.ConnectAddress().String()]
})
} | [
"func",
"WhiteListHostFilter",
"(",
"hosts",
"...",
"string",
")",
"HostFilter",
"{",
"hostInfos",
",",
"err",
":=",
"addrsToHosts",
"(",
"hosts",
",",
"9042",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"fmt",
".",
"Errorf",
"(",
"\"unable t... | // WhiteListHostFilter filters incoming hosts by checking that their address is
// in the initial hosts whitelist. | [
"WhiteListHostFilter",
"filters",
"incoming",
"hosts",
"by",
"checking",
"that",
"their",
"address",
"is",
"in",
"the",
"initial",
"hosts",
"whitelist",
"."
] | b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac | https://github.com/gocql/gocql/blob/b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac/filters.go#L42-L57 | train |
gocql/gocql | helpers.go | TupleColumnName | func TupleColumnName(c string, n int) string {
return fmt.Sprintf("%s[%d]", c, n)
} | go | func TupleColumnName(c string, n int) string {
return fmt.Sprintf("%s[%d]", c, n)
} | [
"func",
"TupleColumnName",
"(",
"c",
"string",
",",
"n",
"int",
")",
"string",
"{",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"%s[%d]\"",
",",
"c",
",",
"n",
")",
"\n",
"}"
] | // TupeColumnName will return the column name of a tuple value in a column named
// c at index n. It should be used if a specific element within a tuple is needed
// to be extracted from a map returned from SliceMap or MapScan. | [
"TupeColumnName",
"will",
"return",
"the",
"column",
"name",
"of",
"a",
"tuple",
"value",
"in",
"a",
"column",
"named",
"c",
"at",
"index",
"n",
".",
"It",
"should",
"be",
"used",
"if",
"a",
"specific",
"element",
"within",
"a",
"tuple",
"is",
"needed",
... | b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac | https://github.com/gocql/gocql/blob/b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac/helpers.go#L292-L294 | train |
gocql/gocql | cluster.go | NewCluster | func NewCluster(hosts ...string) *ClusterConfig {
cfg := &ClusterConfig{
Hosts: hosts,
CQLVersion: "3.0.0",
Timeout: 600 * time.Millisecond,
ConnectTimeout: 600 * time.Millisecond,
Port: 9042,
NumConns: 2,
Consistency: Quorum,
MaxPreparedStmts: defaultMaxPreparedStmts,
MaxRoutingKeyInfo: 1000,
PageSize: 5000,
DefaultTimestamp: true,
MaxWaitSchemaAgreement: 60 * time.Second,
ReconnectInterval: 60 * time.Second,
ConvictionPolicy: &SimpleConvictionPolicy{},
ReconnectionPolicy: &ConstantReconnectionPolicy{MaxRetries: 3, Interval: 1 * time.Second},
WriteCoalesceWaitTime: 200 * time.Microsecond,
}
return cfg
} | go | func NewCluster(hosts ...string) *ClusterConfig {
cfg := &ClusterConfig{
Hosts: hosts,
CQLVersion: "3.0.0",
Timeout: 600 * time.Millisecond,
ConnectTimeout: 600 * time.Millisecond,
Port: 9042,
NumConns: 2,
Consistency: Quorum,
MaxPreparedStmts: defaultMaxPreparedStmts,
MaxRoutingKeyInfo: 1000,
PageSize: 5000,
DefaultTimestamp: true,
MaxWaitSchemaAgreement: 60 * time.Second,
ReconnectInterval: 60 * time.Second,
ConvictionPolicy: &SimpleConvictionPolicy{},
ReconnectionPolicy: &ConstantReconnectionPolicy{MaxRetries: 3, Interval: 1 * time.Second},
WriteCoalesceWaitTime: 200 * time.Microsecond,
}
return cfg
} | [
"func",
"NewCluster",
"(",
"hosts",
"...",
"string",
")",
"*",
"ClusterConfig",
"{",
"cfg",
":=",
"&",
"ClusterConfig",
"{",
"Hosts",
":",
"hosts",
",",
"CQLVersion",
":",
"\"3.0.0\"",
",",
"Timeout",
":",
"600",
"*",
"time",
".",
"Millisecond",
",",
"Co... | // NewCluster generates a new config for the default cluster implementation.
//
// The supplied hosts are used to initially connect to the cluster then the rest of
// the ring will be automatically discovered. It is recommended to use the value set in
// the Cassandra config for broadcast_address or listen_address, an IP address not
// a domain name. This is because events from Cassandra will use the configured IP
// address, which is used to index connected hosts. If the domain name specified
// resolves to more than 1 IP address then the driver may connect multiple times to
// the same host, and will not mark the node being down or up from events. | [
"NewCluster",
"generates",
"a",
"new",
"config",
"for",
"the",
"default",
"cluster",
"implementation",
".",
"The",
"supplied",
"hosts",
"are",
"used",
"to",
"initially",
"connect",
"to",
"the",
"cluster",
"then",
"the",
"rest",
"of",
"the",
"ring",
"will",
"... | b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac | https://github.com/gocql/gocql/blob/b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac/cluster.go#L160-L180 | train |
gocql/gocql | cluster.go | translateAddressPort | func (cfg *ClusterConfig) translateAddressPort(addr net.IP, port int) (net.IP, int) {
if cfg.AddressTranslator == nil || len(addr) == 0 {
return addr, port
}
newAddr, newPort := cfg.AddressTranslator.Translate(addr, port)
if gocqlDebug {
Logger.Printf("gocql: translating address '%v:%d' to '%v:%d'", addr, port, newAddr, newPort)
}
return newAddr, newPort
} | go | func (cfg *ClusterConfig) translateAddressPort(addr net.IP, port int) (net.IP, int) {
if cfg.AddressTranslator == nil || len(addr) == 0 {
return addr, port
}
newAddr, newPort := cfg.AddressTranslator.Translate(addr, port)
if gocqlDebug {
Logger.Printf("gocql: translating address '%v:%d' to '%v:%d'", addr, port, newAddr, newPort)
}
return newAddr, newPort
} | [
"func",
"(",
"cfg",
"*",
"ClusterConfig",
")",
"translateAddressPort",
"(",
"addr",
"net",
".",
"IP",
",",
"port",
"int",
")",
"(",
"net",
".",
"IP",
",",
"int",
")",
"{",
"if",
"cfg",
".",
"AddressTranslator",
"==",
"nil",
"||",
"len",
"(",
"addr",
... | // translateAddressPort is a helper method that will use the given AddressTranslator
// if defined, to translate the given address and port into a possibly new address
// and port, If no AddressTranslator or if an error occurs, the given address and
// port will be returned. | [
"translateAddressPort",
"is",
"a",
"helper",
"method",
"that",
"will",
"use",
"the",
"given",
"AddressTranslator",
"if",
"defined",
"to",
"translate",
"the",
"given",
"address",
"and",
"port",
"into",
"a",
"possibly",
"new",
"address",
"and",
"port",
"If",
"no... | b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac | https://github.com/gocql/gocql/blob/b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac/cluster.go#L192-L201 | train |
gocql/gocql | frame.go | ParseConsistencyWrapper | func ParseConsistencyWrapper(s string) (consistency Consistency, err error) {
err = consistency.UnmarshalText([]byte(strings.ToUpper(s)))
return
} | go | func ParseConsistencyWrapper(s string) (consistency Consistency, err error) {
err = consistency.UnmarshalText([]byte(strings.ToUpper(s)))
return
} | [
"func",
"ParseConsistencyWrapper",
"(",
"s",
"string",
")",
"(",
"consistency",
"Consistency",
",",
"err",
"error",
")",
"{",
"err",
"=",
"consistency",
".",
"UnmarshalText",
"(",
"[",
"]",
"byte",
"(",
"strings",
".",
"ToUpper",
"(",
"s",
")",
")",
")",... | // ParseConsistencyWrapper wraps gocql.ParseConsistency to provide an err
// return instead of a panic | [
"ParseConsistencyWrapper",
"wraps",
"gocql",
".",
"ParseConsistency",
"to",
"provide",
"an",
"err",
"return",
"instead",
"of",
"a",
"panic"
] | b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac | https://github.com/gocql/gocql/blob/b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac/frame.go#L253-L256 | train |
gocql/gocql | frame.go | readFrame | func (f *framer) readFrame(head *frameHeader) error {
if head.length < 0 {
return fmt.Errorf("frame body length can not be less than 0: %d", head.length)
} else if head.length > maxFrameSize {
// need to free up the connection to be used again
_, err := io.CopyN(ioutil.Discard, f.r, int64(head.length))
if err != nil {
return fmt.Errorf("error whilst trying to discard frame with invalid length: %v", err)
}
return ErrFrameTooBig
}
if cap(f.readBuffer) >= head.length {
f.rbuf = f.readBuffer[:head.length]
} else {
f.readBuffer = make([]byte, head.length)
f.rbuf = f.readBuffer
}
// assume the underlying reader takes care of timeouts and retries
n, err := io.ReadFull(f.r, f.rbuf)
if err != nil {
return fmt.Errorf("unable to read frame body: read %d/%d bytes: %v", n, head.length, err)
}
if head.flags&flagCompress == flagCompress {
if f.compres == nil {
return NewErrProtocol("no compressor available with compressed frame body")
}
f.rbuf, err = f.compres.Decode(f.rbuf)
if err != nil {
return err
}
}
f.header = head
return nil
} | go | func (f *framer) readFrame(head *frameHeader) error {
if head.length < 0 {
return fmt.Errorf("frame body length can not be less than 0: %d", head.length)
} else if head.length > maxFrameSize {
// need to free up the connection to be used again
_, err := io.CopyN(ioutil.Discard, f.r, int64(head.length))
if err != nil {
return fmt.Errorf("error whilst trying to discard frame with invalid length: %v", err)
}
return ErrFrameTooBig
}
if cap(f.readBuffer) >= head.length {
f.rbuf = f.readBuffer[:head.length]
} else {
f.readBuffer = make([]byte, head.length)
f.rbuf = f.readBuffer
}
// assume the underlying reader takes care of timeouts and retries
n, err := io.ReadFull(f.r, f.rbuf)
if err != nil {
return fmt.Errorf("unable to read frame body: read %d/%d bytes: %v", n, head.length, err)
}
if head.flags&flagCompress == flagCompress {
if f.compres == nil {
return NewErrProtocol("no compressor available with compressed frame body")
}
f.rbuf, err = f.compres.Decode(f.rbuf)
if err != nil {
return err
}
}
f.header = head
return nil
} | [
"func",
"(",
"f",
"*",
"framer",
")",
"readFrame",
"(",
"head",
"*",
"frameHeader",
")",
"error",
"{",
"if",
"head",
".",
"length",
"<",
"0",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"frame body length can not be less than 0: %d\"",
",",
"head",
".",
"l... | // reads a frame form the wire into the framers buffer | [
"reads",
"a",
"frame",
"form",
"the",
"wire",
"into",
"the",
"framers",
"buffer"
] | b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac | https://github.com/gocql/gocql/blob/b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac/frame.go#L504-L542 | train |
gocql/gocql | frame.go | writeInt | func (f *framer) writeInt(n int32) {
f.wbuf = appendInt(f.wbuf, n)
} | go | func (f *framer) writeInt(n int32) {
f.wbuf = appendInt(f.wbuf, n)
} | [
"func",
"(",
"f",
"*",
"framer",
")",
"writeInt",
"(",
"n",
"int32",
")",
"{",
"f",
".",
"wbuf",
"=",
"appendInt",
"(",
"f",
".",
"wbuf",
",",
"n",
")",
"\n",
"}"
] | // these are protocol level binary types | [
"these",
"are",
"protocol",
"level",
"binary",
"types"
] | b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac | https://github.com/gocql/gocql/blob/b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac/frame.go#L2011-L2013 | train |
gocql/gocql | control.go | query | func (c *controlConn) query(statement string, values ...interface{}) (iter *Iter) {
q := c.session.Query(statement, values...).Consistency(One).RoutingKey([]byte{}).Trace(nil)
for {
iter = c.withConn(func(conn *Conn) *Iter {
return conn.executeQuery(context.TODO(), q)
})
if gocqlDebug && iter.err != nil {
Logger.Printf("control: error executing %q: %v\n", statement, iter.err)
}
q.AddAttempts(1, c.getConn().host)
if iter.err == nil || !c.retry.Attempt(q) {
break
}
}
return
} | go | func (c *controlConn) query(statement string, values ...interface{}) (iter *Iter) {
q := c.session.Query(statement, values...).Consistency(One).RoutingKey([]byte{}).Trace(nil)
for {
iter = c.withConn(func(conn *Conn) *Iter {
return conn.executeQuery(context.TODO(), q)
})
if gocqlDebug && iter.err != nil {
Logger.Printf("control: error executing %q: %v\n", statement, iter.err)
}
q.AddAttempts(1, c.getConn().host)
if iter.err == nil || !c.retry.Attempt(q) {
break
}
}
return
} | [
"func",
"(",
"c",
"*",
"controlConn",
")",
"query",
"(",
"statement",
"string",
",",
"values",
"...",
"interface",
"{",
"}",
")",
"(",
"iter",
"*",
"Iter",
")",
"{",
"q",
":=",
"c",
".",
"session",
".",
"Query",
"(",
"statement",
",",
"values",
"..... | // query will return nil if the connection is closed or nil | [
"query",
"will",
"return",
"nil",
"if",
"the",
"connection",
"is",
"closed",
"or",
"nil"
] | b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac | https://github.com/gocql/gocql/blob/b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac/control.go#L450-L469 | train |
gocql/gocql | session.go | NewSession | func NewSession(cfg ClusterConfig) (*Session, error) {
// Check that hosts in the ClusterConfig is not empty
if len(cfg.Hosts) < 1 {
return nil, ErrNoHosts
}
// Check that either Authenticator is set or AuthProvider, not both
if cfg.Authenticator != nil && cfg.AuthProvider != nil {
return nil, errors.New("Can't use both Authenticator and AuthProvider in cluster config.")
}
s := &Session{
cons: cfg.Consistency,
prefetch: 0.25,
cfg: cfg,
pageSize: cfg.PageSize,
stmtsLRU: &preparedLRU{lru: lru.New(cfg.MaxPreparedStmts)},
quit: make(chan struct{}),
connectObserver: cfg.ConnectObserver,
}
s.schemaDescriber = newSchemaDescriber(s)
s.nodeEvents = newEventDebouncer("NodeEvents", s.handleNodeEvent)
s.schemaEvents = newEventDebouncer("SchemaEvents", s.handleSchemaEvent)
s.routingKeyInfoCache.lru = lru.New(cfg.MaxRoutingKeyInfo)
s.hostSource = &ringDescriber{session: s}
if cfg.PoolConfig.HostSelectionPolicy == nil {
cfg.PoolConfig.HostSelectionPolicy = RoundRobinHostPolicy()
}
s.pool = cfg.PoolConfig.buildPool(s)
s.policy = cfg.PoolConfig.HostSelectionPolicy
s.policy.Init(s)
s.executor = &queryExecutor{
pool: s.pool,
policy: cfg.PoolConfig.HostSelectionPolicy,
}
s.queryObserver = cfg.QueryObserver
s.batchObserver = cfg.BatchObserver
s.connectObserver = cfg.ConnectObserver
s.frameObserver = cfg.FrameHeaderObserver
//Check the TLS Config before trying to connect to anything external
connCfg, err := connConfig(&s.cfg)
if err != nil {
//TODO: Return a typed error
return nil, fmt.Errorf("gocql: unable to create session: %v", err)
}
s.connCfg = connCfg
if err := s.init(); err != nil {
s.Close()
if err == ErrNoConnectionsStarted {
//This error used to be generated inside NewSession & returned directly
//Forward it on up to be backwards compatible
return nil, ErrNoConnectionsStarted
} else {
// TODO(zariel): dont wrap this error in fmt.Errorf, return a typed error
return nil, fmt.Errorf("gocql: unable to create session: %v", err)
}
}
return s, nil
} | go | func NewSession(cfg ClusterConfig) (*Session, error) {
// Check that hosts in the ClusterConfig is not empty
if len(cfg.Hosts) < 1 {
return nil, ErrNoHosts
}
// Check that either Authenticator is set or AuthProvider, not both
if cfg.Authenticator != nil && cfg.AuthProvider != nil {
return nil, errors.New("Can't use both Authenticator and AuthProvider in cluster config.")
}
s := &Session{
cons: cfg.Consistency,
prefetch: 0.25,
cfg: cfg,
pageSize: cfg.PageSize,
stmtsLRU: &preparedLRU{lru: lru.New(cfg.MaxPreparedStmts)},
quit: make(chan struct{}),
connectObserver: cfg.ConnectObserver,
}
s.schemaDescriber = newSchemaDescriber(s)
s.nodeEvents = newEventDebouncer("NodeEvents", s.handleNodeEvent)
s.schemaEvents = newEventDebouncer("SchemaEvents", s.handleSchemaEvent)
s.routingKeyInfoCache.lru = lru.New(cfg.MaxRoutingKeyInfo)
s.hostSource = &ringDescriber{session: s}
if cfg.PoolConfig.HostSelectionPolicy == nil {
cfg.PoolConfig.HostSelectionPolicy = RoundRobinHostPolicy()
}
s.pool = cfg.PoolConfig.buildPool(s)
s.policy = cfg.PoolConfig.HostSelectionPolicy
s.policy.Init(s)
s.executor = &queryExecutor{
pool: s.pool,
policy: cfg.PoolConfig.HostSelectionPolicy,
}
s.queryObserver = cfg.QueryObserver
s.batchObserver = cfg.BatchObserver
s.connectObserver = cfg.ConnectObserver
s.frameObserver = cfg.FrameHeaderObserver
//Check the TLS Config before trying to connect to anything external
connCfg, err := connConfig(&s.cfg)
if err != nil {
//TODO: Return a typed error
return nil, fmt.Errorf("gocql: unable to create session: %v", err)
}
s.connCfg = connCfg
if err := s.init(); err != nil {
s.Close()
if err == ErrNoConnectionsStarted {
//This error used to be generated inside NewSession & returned directly
//Forward it on up to be backwards compatible
return nil, ErrNoConnectionsStarted
} else {
// TODO(zariel): dont wrap this error in fmt.Errorf, return a typed error
return nil, fmt.Errorf("gocql: unable to create session: %v", err)
}
}
return s, nil
} | [
"func",
"NewSession",
"(",
"cfg",
"ClusterConfig",
")",
"(",
"*",
"Session",
",",
"error",
")",
"{",
"if",
"len",
"(",
"cfg",
".",
"Hosts",
")",
"<",
"1",
"{",
"return",
"nil",
",",
"ErrNoHosts",
"\n",
"}",
"\n",
"if",
"cfg",
".",
"Authenticator",
... | // NewSession wraps an existing Node. | [
"NewSession",
"wraps",
"an",
"existing",
"Node",
"."
] | b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac | https://github.com/gocql/gocql/blob/b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac/session.go#L105-L174 | train |
gocql/gocql | session.go | SetConsistency | func (s *Session) SetConsistency(cons Consistency) {
s.mu.Lock()
s.cons = cons
s.mu.Unlock()
} | go | func (s *Session) SetConsistency(cons Consistency) {
s.mu.Lock()
s.cons = cons
s.mu.Unlock()
} | [
"func",
"(",
"s",
"*",
"Session",
")",
"SetConsistency",
"(",
"cons",
"Consistency",
")",
"{",
"s",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"s",
".",
"cons",
"=",
"cons",
"\n",
"s",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"}"
] | // SetConsistency sets the default consistency level for this session. This
// setting can also be changed on a per-query basis and the default value
// is Quorum. | [
"SetConsistency",
"sets",
"the",
"default",
"consistency",
"level",
"for",
"this",
"session",
".",
"This",
"setting",
"can",
"also",
"be",
"changed",
"on",
"a",
"per",
"-",
"query",
"basis",
"and",
"the",
"default",
"value",
"is",
"Quorum",
"."
] | b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac | https://github.com/gocql/gocql/blob/b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac/session.go#L295-L299 | train |
gocql/gocql | session.go | SetPageSize | func (s *Session) SetPageSize(n int) {
s.mu.Lock()
s.pageSize = n
s.mu.Unlock()
} | go | func (s *Session) SetPageSize(n int) {
s.mu.Lock()
s.pageSize = n
s.mu.Unlock()
} | [
"func",
"(",
"s",
"*",
"Session",
")",
"SetPageSize",
"(",
"n",
"int",
")",
"{",
"s",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"s",
".",
"pageSize",
"=",
"n",
"\n",
"s",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"}"
] | // SetPageSize sets the default page size for this session. A value <= 0 will
// disable paging. This setting can also be changed on a per-query basis. | [
"SetPageSize",
"sets",
"the",
"default",
"page",
"size",
"for",
"this",
"session",
".",
"A",
"value",
"<",
"=",
"0",
"will",
"disable",
"paging",
".",
"This",
"setting",
"can",
"also",
"be",
"changed",
"on",
"a",
"per",
"-",
"query",
"basis",
"."
] | b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac | https://github.com/gocql/gocql/blob/b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac/session.go#L303-L307 | train |
gocql/gocql | session.go | SetTrace | func (s *Session) SetTrace(trace Tracer) {
s.mu.Lock()
s.trace = trace
s.mu.Unlock()
} | go | func (s *Session) SetTrace(trace Tracer) {
s.mu.Lock()
s.trace = trace
s.mu.Unlock()
} | [
"func",
"(",
"s",
"*",
"Session",
")",
"SetTrace",
"(",
"trace",
"Tracer",
")",
"{",
"s",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"s",
".",
"trace",
"=",
"trace",
"\n",
"s",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"}"
] | // SetTrace sets the default tracer for this session. This setting can also
// be changed on a per-query basis. | [
"SetTrace",
"sets",
"the",
"default",
"tracer",
"for",
"this",
"session",
".",
"This",
"setting",
"can",
"also",
"be",
"changed",
"on",
"a",
"per",
"-",
"query",
"basis",
"."
] | b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac | https://github.com/gocql/gocql/blob/b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac/session.go#L321-L325 | train |
gocql/gocql | session.go | Query | func (s *Session) Query(stmt string, values ...interface{}) *Query {
qry := queryPool.Get().(*Query)
qry.session = s
qry.stmt = stmt
qry.values = values
qry.defaultsFromSession()
return qry
} | go | func (s *Session) Query(stmt string, values ...interface{}) *Query {
qry := queryPool.Get().(*Query)
qry.session = s
qry.stmt = stmt
qry.values = values
qry.defaultsFromSession()
return qry
} | [
"func",
"(",
"s",
"*",
"Session",
")",
"Query",
"(",
"stmt",
"string",
",",
"values",
"...",
"interface",
"{",
"}",
")",
"*",
"Query",
"{",
"qry",
":=",
"queryPool",
".",
"Get",
"(",
")",
".",
"(",
"*",
"Query",
")",
"\n",
"qry",
".",
"session",
... | // Query generates a new query object for interacting with the database.
// Further details of the query may be tweaked using the resulting query
// value before the query is executed. Query is automatically prepared
// if it has not previously been executed. | [
"Query",
"generates",
"a",
"new",
"query",
"object",
"for",
"interacting",
"with",
"the",
"database",
".",
"Further",
"details",
"of",
"the",
"query",
"may",
"be",
"tweaked",
"using",
"the",
"resulting",
"query",
"value",
"before",
"the",
"query",
"is",
"exe... | b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac | https://github.com/gocql/gocql/blob/b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac/session.go#L331-L338 | train |
gocql/gocql | session.go | Bind | func (s *Session) Bind(stmt string, b func(q *QueryInfo) ([]interface{}, error)) *Query {
qry := queryPool.Get().(*Query)
qry.session = s
qry.stmt = stmt
qry.binding = b
qry.defaultsFromSession()
return qry
} | go | func (s *Session) Bind(stmt string, b func(q *QueryInfo) ([]interface{}, error)) *Query {
qry := queryPool.Get().(*Query)
qry.session = s
qry.stmt = stmt
qry.binding = b
qry.defaultsFromSession()
return qry
} | [
"func",
"(",
"s",
"*",
"Session",
")",
"Bind",
"(",
"stmt",
"string",
",",
"b",
"func",
"(",
"q",
"*",
"QueryInfo",
")",
"(",
"[",
"]",
"interface",
"{",
"}",
",",
"error",
")",
")",
"*",
"Query",
"{",
"qry",
":=",
"queryPool",
".",
"Get",
"(",... | // Bind generates a new query object based on the query statement passed in.
// The query is automatically prepared if it has not previously been executed.
// The binding callback allows the application to define which query argument
// values will be marshalled as part of the query execution.
// During execution, the meta data of the prepared query will be routed to the
// binding callback, which is responsible for producing the query argument values. | [
"Bind",
"generates",
"a",
"new",
"query",
"object",
"based",
"on",
"the",
"query",
"statement",
"passed",
"in",
".",
"The",
"query",
"is",
"automatically",
"prepared",
"if",
"it",
"has",
"not",
"previously",
"been",
"executed",
".",
"The",
"binding",
"callba... | b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac | https://github.com/gocql/gocql/blob/b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac/session.go#L353-L360 | train |
gocql/gocql | session.go | Close | func (s *Session) Close() {
s.closeMu.Lock()
defer s.closeMu.Unlock()
if s.isClosed {
return
}
s.isClosed = true
if s.pool != nil {
s.pool.Close()
}
if s.control != nil {
s.control.close()
}
if s.nodeEvents != nil {
s.nodeEvents.stop()
}
if s.schemaEvents != nil {
s.schemaEvents.stop()
}
if s.quit != nil {
close(s.quit)
}
} | go | func (s *Session) Close() {
s.closeMu.Lock()
defer s.closeMu.Unlock()
if s.isClosed {
return
}
s.isClosed = true
if s.pool != nil {
s.pool.Close()
}
if s.control != nil {
s.control.close()
}
if s.nodeEvents != nil {
s.nodeEvents.stop()
}
if s.schemaEvents != nil {
s.schemaEvents.stop()
}
if s.quit != nil {
close(s.quit)
}
} | [
"func",
"(",
"s",
"*",
"Session",
")",
"Close",
"(",
")",
"{",
"s",
".",
"closeMu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"closeMu",
".",
"Unlock",
"(",
")",
"\n",
"if",
"s",
".",
"isClosed",
"{",
"return",
"\n",
"}",
"\n",
"s",
"."... | // Close closes all connections. The session is unusable after this
// operation. | [
"Close",
"closes",
"all",
"connections",
".",
"The",
"session",
"is",
"unusable",
"after",
"this",
"operation",
"."
] | b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac | https://github.com/gocql/gocql/blob/b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac/session.go#L364-L392 | train |
gocql/gocql | session.go | KeyspaceMetadata | func (s *Session) KeyspaceMetadata(keyspace string) (*KeyspaceMetadata, error) {
// fail fast
if s.Closed() {
return nil, ErrSessionClosed
} else if keyspace == "" {
return nil, ErrNoKeyspace
}
return s.schemaDescriber.getSchema(keyspace)
} | go | func (s *Session) KeyspaceMetadata(keyspace string) (*KeyspaceMetadata, error) {
// fail fast
if s.Closed() {
return nil, ErrSessionClosed
} else if keyspace == "" {
return nil, ErrNoKeyspace
}
return s.schemaDescriber.getSchema(keyspace)
} | [
"func",
"(",
"s",
"*",
"Session",
")",
"KeyspaceMetadata",
"(",
"keyspace",
"string",
")",
"(",
"*",
"KeyspaceMetadata",
",",
"error",
")",
"{",
"if",
"s",
".",
"Closed",
"(",
")",
"{",
"return",
"nil",
",",
"ErrSessionClosed",
"\n",
"}",
"else",
"if",... | // KeyspaceMetadata returns the schema metadata for the keyspace specified. Returns an error if the keyspace does not exist. | [
"KeyspaceMetadata",
"returns",
"the",
"schema",
"metadata",
"for",
"the",
"keyspace",
"specified",
".",
"Returns",
"an",
"error",
"if",
"the",
"keyspace",
"does",
"not",
"exist",
"."
] | b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac | https://github.com/gocql/gocql/blob/b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac/session.go#L425-L434 | train |
gocql/gocql | session.go | ExecuteBatch | func (s *Session) ExecuteBatch(batch *Batch) error {
iter := s.executeBatch(batch)
return iter.Close()
} | go | func (s *Session) ExecuteBatch(batch *Batch) error {
iter := s.executeBatch(batch)
return iter.Close()
} | [
"func",
"(",
"s",
"*",
"Session",
")",
"ExecuteBatch",
"(",
"batch",
"*",
"Batch",
")",
"error",
"{",
"iter",
":=",
"s",
".",
"executeBatch",
"(",
"batch",
")",
"\n",
"return",
"iter",
".",
"Close",
"(",
")",
"\n",
"}"
] | // ExecuteBatch executes a batch operation and returns nil if successful
// otherwise an error is returned describing the failure. | [
"ExecuteBatch",
"executes",
"a",
"batch",
"operation",
"and",
"returns",
"nil",
"if",
"successful",
"otherwise",
"an",
"error",
"is",
"returned",
"describing",
"the",
"failure",
"."
] | b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac | https://github.com/gocql/gocql/blob/b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac/session.go#L613-L616 | train |
gocql/gocql | session.go | MapExecuteBatchCAS | func (s *Session) MapExecuteBatchCAS(batch *Batch, dest map[string]interface{}) (applied bool, iter *Iter, err error) {
iter = s.executeBatch(batch)
if err := iter.checkErrAndNotFound(); err != nil {
iter.Close()
return false, nil, err
}
iter.MapScan(dest)
applied = dest["[applied]"].(bool)
delete(dest, "[applied]")
// we usually close here, but instead of closing, just returin an error
// if MapScan failed. Although Close just returns err, using Close
// here might be confusing as we are not actually closing the iter
return applied, iter, iter.err
} | go | func (s *Session) MapExecuteBatchCAS(batch *Batch, dest map[string]interface{}) (applied bool, iter *Iter, err error) {
iter = s.executeBatch(batch)
if err := iter.checkErrAndNotFound(); err != nil {
iter.Close()
return false, nil, err
}
iter.MapScan(dest)
applied = dest["[applied]"].(bool)
delete(dest, "[applied]")
// we usually close here, but instead of closing, just returin an error
// if MapScan failed. Although Close just returns err, using Close
// here might be confusing as we are not actually closing the iter
return applied, iter, iter.err
} | [
"func",
"(",
"s",
"*",
"Session",
")",
"MapExecuteBatchCAS",
"(",
"batch",
"*",
"Batch",
",",
"dest",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"(",
"applied",
"bool",
",",
"iter",
"*",
"Iter",
",",
"err",
"error",
")",
"{",
"iter",
"=... | // MapExecuteBatchCAS executes a batch operation much like ExecuteBatchCAS,
// however it accepts a map rather than a list of arguments for the initial
// scan. | [
"MapExecuteBatchCAS",
"executes",
"a",
"batch",
"operation",
"much",
"like",
"ExecuteBatchCAS",
"however",
"it",
"accepts",
"a",
"map",
"rather",
"than",
"a",
"list",
"of",
"arguments",
"for",
"the",
"initial",
"scan",
"."
] | b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac | https://github.com/gocql/gocql/blob/b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac/session.go#L643-L657 | train |
gocql/gocql | session.go | Attempts | func (q *Query) Attempts() int {
q.metrics.l.Lock()
var attempts int
for _, metric := range q.metrics.m {
attempts += metric.Attempts
}
q.metrics.l.Unlock()
return attempts
} | go | func (q *Query) Attempts() int {
q.metrics.l.Lock()
var attempts int
for _, metric := range q.metrics.m {
attempts += metric.Attempts
}
q.metrics.l.Unlock()
return attempts
} | [
"func",
"(",
"q",
"*",
"Query",
")",
"Attempts",
"(",
")",
"int",
"{",
"q",
".",
"metrics",
".",
"l",
".",
"Lock",
"(",
")",
"\n",
"var",
"attempts",
"int",
"\n",
"for",
"_",
",",
"metric",
":=",
"range",
"q",
".",
"metrics",
".",
"m",
"{",
"... | //Attempts returns the number of times the query was executed. | [
"Attempts",
"returns",
"the",
"number",
"of",
"times",
"the",
"query",
"was",
"executed",
"."
] | b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac | https://github.com/gocql/gocql/blob/b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac/session.go#L740-L748 | train |
gocql/gocql | session.go | Latency | func (q *Query) Latency() int64 {
q.metrics.l.Lock()
var attempts int
var latency int64
for _, metric := range q.metrics.m {
attempts += metric.Attempts
latency += metric.TotalLatency
}
q.metrics.l.Unlock()
if attempts > 0 {
return latency / int64(attempts)
}
return 0
} | go | func (q *Query) Latency() int64 {
q.metrics.l.Lock()
var attempts int
var latency int64
for _, metric := range q.metrics.m {
attempts += metric.Attempts
latency += metric.TotalLatency
}
q.metrics.l.Unlock()
if attempts > 0 {
return latency / int64(attempts)
}
return 0
} | [
"func",
"(",
"q",
"*",
"Query",
")",
"Latency",
"(",
")",
"int64",
"{",
"q",
".",
"metrics",
".",
"l",
".",
"Lock",
"(",
")",
"\n",
"var",
"attempts",
"int",
"\n",
"var",
"latency",
"int64",
"\n",
"for",
"_",
",",
"metric",
":=",
"range",
"q",
... | //Latency returns the average amount of nanoseconds per attempt of the query. | [
"Latency",
"returns",
"the",
"average",
"amount",
"of",
"nanoseconds",
"per",
"attempt",
"of",
"the",
"query",
"."
] | b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac | https://github.com/gocql/gocql/blob/b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac/session.go#L758-L771 | train |
gocql/gocql | session.go | Consistency | func (q *Query) Consistency(c Consistency) *Query {
q.cons = c
return q
} | go | func (q *Query) Consistency(c Consistency) *Query {
q.cons = c
return q
} | [
"func",
"(",
"q",
"*",
"Query",
")",
"Consistency",
"(",
"c",
"Consistency",
")",
"*",
"Query",
"{",
"q",
".",
"cons",
"=",
"c",
"\n",
"return",
"q",
"\n",
"}"
] | // Consistency sets the consistency level for this query. If no consistency
// level have been set, the default consistency level of the cluster
// is used. | [
"Consistency",
"sets",
"the",
"consistency",
"level",
"for",
"this",
"query",
".",
"If",
"no",
"consistency",
"level",
"have",
"been",
"set",
"the",
"default",
"consistency",
"level",
"of",
"the",
"cluster",
"is",
"used",
"."
] | b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac | https://github.com/gocql/gocql/blob/b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac/session.go#L783-L786 | train |
gocql/gocql | session.go | Keyspace | func (q *Query) Keyspace() string {
if q.session == nil {
return ""
}
// TODO(chbannis): this should be parsed from the query or we should let
// this be set by users.
return q.session.cfg.Keyspace
} | go | func (q *Query) Keyspace() string {
if q.session == nil {
return ""
}
// TODO(chbannis): this should be parsed from the query or we should let
// this be set by users.
return q.session.cfg.Keyspace
} | [
"func",
"(",
"q",
"*",
"Query",
")",
"Keyspace",
"(",
")",
"string",
"{",
"if",
"q",
".",
"session",
"==",
"nil",
"{",
"return",
"\"\"",
"\n",
"}",
"\n",
"return",
"q",
".",
"session",
".",
"cfg",
".",
"Keyspace",
"\n",
"}"
] | // Keyspace returns the keyspace the query will be executed against. | [
"Keyspace",
"returns",
"the",
"keyspace",
"the",
"query",
"will",
"be",
"executed",
"against",
"."
] | b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac | https://github.com/gocql/gocql/blob/b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac/session.go#L914-L921 | train |
gocql/gocql | session.go | GetRoutingKey | func (q *Query) GetRoutingKey() ([]byte, error) {
if q.routingKey != nil {
return q.routingKey, nil
} else if q.binding != nil && len(q.values) == 0 {
// If this query was created using session.Bind we wont have the query
// values yet, so we have to pass down to the next policy.
// TODO: Remove this and handle this case
return nil, nil
}
// try to determine the routing key
routingKeyInfo, err := q.session.routingKeyInfo(q.Context(), q.stmt)
if err != nil {
return nil, err
}
if routingKeyInfo == nil {
return nil, nil
}
if len(routingKeyInfo.indexes) == 1 {
// single column routing key
routingKey, err := Marshal(
routingKeyInfo.types[0],
q.values[routingKeyInfo.indexes[0]],
)
if err != nil {
return nil, err
}
return routingKey, nil
}
// We allocate that buffer only once, so that further re-bind/exec of the
// same query don't allocate more memory.
if q.routingKeyBuffer == nil {
q.routingKeyBuffer = make([]byte, 0, 256)
}
// composite routing key
buf := bytes.NewBuffer(q.routingKeyBuffer)
for i := range routingKeyInfo.indexes {
encoded, err := Marshal(
routingKeyInfo.types[i],
q.values[routingKeyInfo.indexes[i]],
)
if err != nil {
return nil, err
}
lenBuf := []byte{0x00, 0x00}
binary.BigEndian.PutUint16(lenBuf, uint16(len(encoded)))
buf.Write(lenBuf)
buf.Write(encoded)
buf.WriteByte(0x00)
}
routingKey := buf.Bytes()
return routingKey, nil
} | go | func (q *Query) GetRoutingKey() ([]byte, error) {
if q.routingKey != nil {
return q.routingKey, nil
} else if q.binding != nil && len(q.values) == 0 {
// If this query was created using session.Bind we wont have the query
// values yet, so we have to pass down to the next policy.
// TODO: Remove this and handle this case
return nil, nil
}
// try to determine the routing key
routingKeyInfo, err := q.session.routingKeyInfo(q.Context(), q.stmt)
if err != nil {
return nil, err
}
if routingKeyInfo == nil {
return nil, nil
}
if len(routingKeyInfo.indexes) == 1 {
// single column routing key
routingKey, err := Marshal(
routingKeyInfo.types[0],
q.values[routingKeyInfo.indexes[0]],
)
if err != nil {
return nil, err
}
return routingKey, nil
}
// We allocate that buffer only once, so that further re-bind/exec of the
// same query don't allocate more memory.
if q.routingKeyBuffer == nil {
q.routingKeyBuffer = make([]byte, 0, 256)
}
// composite routing key
buf := bytes.NewBuffer(q.routingKeyBuffer)
for i := range routingKeyInfo.indexes {
encoded, err := Marshal(
routingKeyInfo.types[i],
q.values[routingKeyInfo.indexes[i]],
)
if err != nil {
return nil, err
}
lenBuf := []byte{0x00, 0x00}
binary.BigEndian.PutUint16(lenBuf, uint16(len(encoded)))
buf.Write(lenBuf)
buf.Write(encoded)
buf.WriteByte(0x00)
}
routingKey := buf.Bytes()
return routingKey, nil
} | [
"func",
"(",
"q",
"*",
"Query",
")",
"GetRoutingKey",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"if",
"q",
".",
"routingKey",
"!=",
"nil",
"{",
"return",
"q",
".",
"routingKey",
",",
"nil",
"\n",
"}",
"else",
"if",
"q",
".",
"bin... | // GetRoutingKey gets the routing key to use for routing this query. If
// a routing key has not been explicitly set, then the routing key will
// be constructed if possible using the keyspace's schema and the query
// info for this query statement. If the routing key cannot be determined
// then nil will be returned with no error. On any error condition,
// an error description will be returned. | [
"GetRoutingKey",
"gets",
"the",
"routing",
"key",
"to",
"use",
"for",
"routing",
"this",
"query",
".",
"If",
"a",
"routing",
"key",
"has",
"not",
"been",
"explicitly",
"set",
"then",
"the",
"routing",
"key",
"will",
"be",
"constructed",
"if",
"possible",
"... | b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac | https://github.com/gocql/gocql/blob/b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac/session.go#L929-L985 | train |
gocql/gocql | session.go | SetSpeculativeExecutionPolicy | func (q *Query) SetSpeculativeExecutionPolicy(sp SpeculativeExecutionPolicy) *Query {
q.spec = sp
return q
} | go | func (q *Query) SetSpeculativeExecutionPolicy(sp SpeculativeExecutionPolicy) *Query {
q.spec = sp
return q
} | [
"func",
"(",
"q",
"*",
"Query",
")",
"SetSpeculativeExecutionPolicy",
"(",
"sp",
"SpeculativeExecutionPolicy",
")",
"*",
"Query",
"{",
"q",
".",
"spec",
"=",
"sp",
"\n",
"return",
"q",
"\n",
"}"
] | // SetSpeculativeExecutionPolicy sets the execution policy | [
"SetSpeculativeExecutionPolicy",
"sets",
"the",
"execution",
"policy"
] | b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac | https://github.com/gocql/gocql/blob/b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac/session.go#L1024-L1027 | train |
gocql/gocql | session.go | Iter | func (q *Query) Iter() *Iter {
if isUseStatement(q.stmt) {
return &Iter{err: ErrUseStmt}
}
return q.session.executeQuery(q)
} | go | func (q *Query) Iter() *Iter {
if isUseStatement(q.stmt) {
return &Iter{err: ErrUseStmt}
}
return q.session.executeQuery(q)
} | [
"func",
"(",
"q",
"*",
"Query",
")",
"Iter",
"(",
")",
"*",
"Iter",
"{",
"if",
"isUseStatement",
"(",
"q",
".",
"stmt",
")",
"{",
"return",
"&",
"Iter",
"{",
"err",
":",
"ErrUseStmt",
"}",
"\n",
"}",
"\n",
"return",
"q",
".",
"session",
".",
"e... | // Iter executes the query and returns an iterator capable of iterating
// over all results. | [
"Iter",
"executes",
"the",
"query",
"and",
"returns",
"an",
"iterator",
"capable",
"of",
"iterating",
"over",
"all",
"results",
"."
] | b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac | https://github.com/gocql/gocql/blob/b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac/session.go#L1099-L1104 | train |
gocql/gocql | session.go | MapScan | func (q *Query) MapScan(m map[string]interface{}) error {
iter := q.Iter()
if err := iter.checkErrAndNotFound(); err != nil {
return err
}
iter.MapScan(m)
return iter.Close()
} | go | func (q *Query) MapScan(m map[string]interface{}) error {
iter := q.Iter()
if err := iter.checkErrAndNotFound(); err != nil {
return err
}
iter.MapScan(m)
return iter.Close()
} | [
"func",
"(",
"q",
"*",
"Query",
")",
"MapScan",
"(",
"m",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"error",
"{",
"iter",
":=",
"q",
".",
"Iter",
"(",
")",
"\n",
"if",
"err",
":=",
"iter",
".",
"checkErrAndNotFound",
"(",
")",
";",
... | // MapScan executes the query, copies the columns of the first selected
// row into the map pointed at by m and discards the rest. If no rows
// were selected, ErrNotFound is returned. | [
"MapScan",
"executes",
"the",
"query",
"copies",
"the",
"columns",
"of",
"the",
"first",
"selected",
"row",
"into",
"the",
"map",
"pointed",
"at",
"by",
"m",
"and",
"discards",
"the",
"rest",
".",
"If",
"no",
"rows",
"were",
"selected",
"ErrNotFound",
"is"... | b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac | https://github.com/gocql/gocql/blob/b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac/session.go#L1109-L1116 | train |
gocql/gocql | session.go | Scan | func (q *Query) Scan(dest ...interface{}) error {
iter := q.Iter()
if err := iter.checkErrAndNotFound(); err != nil {
return err
}
iter.Scan(dest...)
return iter.Close()
} | go | func (q *Query) Scan(dest ...interface{}) error {
iter := q.Iter()
if err := iter.checkErrAndNotFound(); err != nil {
return err
}
iter.Scan(dest...)
return iter.Close()
} | [
"func",
"(",
"q",
"*",
"Query",
")",
"Scan",
"(",
"dest",
"...",
"interface",
"{",
"}",
")",
"error",
"{",
"iter",
":=",
"q",
".",
"Iter",
"(",
")",
"\n",
"if",
"err",
":=",
"iter",
".",
"checkErrAndNotFound",
"(",
")",
";",
"err",
"!=",
"nil",
... | // Scan executes the query, copies the columns of the first selected
// row into the values pointed at by dest and discards the rest. If no rows
// were selected, ErrNotFound is returned. | [
"Scan",
"executes",
"the",
"query",
"copies",
"the",
"columns",
"of",
"the",
"first",
"selected",
"row",
"into",
"the",
"values",
"pointed",
"at",
"by",
"dest",
"and",
"discards",
"the",
"rest",
".",
"If",
"no",
"rows",
"were",
"selected",
"ErrNotFound",
"... | b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac | https://github.com/gocql/gocql/blob/b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac/session.go#L1121-L1128 | train |
gocql/gocql | session.go | Scan | func (iter *Iter) Scan(dest ...interface{}) bool {
if iter.err != nil {
return false
}
if iter.pos >= iter.numRows {
if iter.next != nil {
*iter = *iter.next.fetch()
return iter.Scan(dest...)
}
return false
}
if iter.next != nil && iter.pos >= iter.next.pos {
go iter.next.fetch()
}
// currently only support scanning into an expand tuple, such that its the same
// as scanning in more values from a single column
if len(dest) != iter.meta.actualColCount {
iter.err = fmt.Errorf("gocql: not enough columns to scan into: have %d want %d", len(dest), iter.meta.actualColCount)
return false
}
// i is the current position in dest, could posible replace it and just use
// slices of dest
i := 0
for _, col := range iter.meta.columns {
colBytes, err := iter.readColumn()
if err != nil {
iter.err = err
return false
}
n, err := scanColumn(colBytes, col, dest[i:])
if err != nil {
iter.err = err
return false
}
i += n
}
iter.pos++
return true
} | go | func (iter *Iter) Scan(dest ...interface{}) bool {
if iter.err != nil {
return false
}
if iter.pos >= iter.numRows {
if iter.next != nil {
*iter = *iter.next.fetch()
return iter.Scan(dest...)
}
return false
}
if iter.next != nil && iter.pos >= iter.next.pos {
go iter.next.fetch()
}
// currently only support scanning into an expand tuple, such that its the same
// as scanning in more values from a single column
if len(dest) != iter.meta.actualColCount {
iter.err = fmt.Errorf("gocql: not enough columns to scan into: have %d want %d", len(dest), iter.meta.actualColCount)
return false
}
// i is the current position in dest, could posible replace it and just use
// slices of dest
i := 0
for _, col := range iter.meta.columns {
colBytes, err := iter.readColumn()
if err != nil {
iter.err = err
return false
}
n, err := scanColumn(colBytes, col, dest[i:])
if err != nil {
iter.err = err
return false
}
i += n
}
iter.pos++
return true
} | [
"func",
"(",
"iter",
"*",
"Iter",
")",
"Scan",
"(",
"dest",
"...",
"interface",
"{",
"}",
")",
"bool",
"{",
"if",
"iter",
".",
"err",
"!=",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n",
"if",
"iter",
".",
"pos",
">=",
"iter",
".",
"numRows",
... | // Scan consumes the next row of the iterator and copies the columns of the
// current row into the values pointed at by dest. Use nil as a dest value
// to skip the corresponding column. Scan might send additional queries
// to the database to retrieve the next set of rows if paging was enabled.
//
// Scan returns true if the row was successfully unmarshaled or false if the
// end of the result set was reached or if an error occurred. Close should
// be called afterwards to retrieve any potential errors. | [
"Scan",
"consumes",
"the",
"next",
"row",
"of",
"the",
"iterator",
"and",
"copies",
"the",
"columns",
"of",
"the",
"current",
"row",
"into",
"the",
"values",
"pointed",
"at",
"by",
"dest",
".",
"Use",
"nil",
"as",
"a",
"dest",
"value",
"to",
"skip",
"t... | b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac | https://github.com/gocql/gocql/blob/b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac/session.go#L1348-L1392 | train |
gocql/gocql | session.go | Warnings | func (iter *Iter) Warnings() []string {
if iter.framer != nil {
return iter.framer.header.warnings
}
return nil
} | go | func (iter *Iter) Warnings() []string {
if iter.framer != nil {
return iter.framer.header.warnings
}
return nil
} | [
"func",
"(",
"iter",
"*",
"Iter",
")",
"Warnings",
"(",
")",
"[",
"]",
"string",
"{",
"if",
"iter",
".",
"framer",
"!=",
"nil",
"{",
"return",
"iter",
".",
"framer",
".",
"header",
".",
"warnings",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Warnings returns any warnings generated if given in the response from Cassandra.
//
// This is only available starting with CQL Protocol v4. | [
"Warnings",
"returns",
"any",
"warnings",
"generated",
"if",
"given",
"in",
"the",
"response",
"from",
"Cassandra",
".",
"This",
"is",
"only",
"available",
"starting",
"with",
"CQL",
"Protocol",
"v4",
"."
] | b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac | https://github.com/gocql/gocql/blob/b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac/session.go#L1408-L1413 | train |
gocql/gocql | session.go | WillSwitchPage | func (iter *Iter) WillSwitchPage() bool {
return iter.pos >= iter.numRows && iter.next != nil
} | go | func (iter *Iter) WillSwitchPage() bool {
return iter.pos >= iter.numRows && iter.next != nil
} | [
"func",
"(",
"iter",
"*",
"Iter",
")",
"WillSwitchPage",
"(",
")",
"bool",
"{",
"return",
"iter",
".",
"pos",
">=",
"iter",
".",
"numRows",
"&&",
"iter",
".",
"next",
"!=",
"nil",
"\n",
"}"
] | // WillSwitchPage detects if iterator reached end of current page
// and the next page is available. | [
"WillSwitchPage",
"detects",
"if",
"iterator",
"reached",
"end",
"of",
"current",
"page",
"and",
"the",
"next",
"page",
"is",
"available",
"."
] | b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac | https://github.com/gocql/gocql/blob/b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac/session.go#L1429-L1431 | train |
gocql/gocql | session.go | NewBatch | func (s *Session) NewBatch(typ BatchType) *Batch {
s.mu.RLock()
batch := &Batch{
Type: typ,
rt: s.cfg.RetryPolicy,
serialCons: s.cfg.SerialConsistency,
observer: s.batchObserver,
Cons: s.cons,
defaultTimestamp: s.cfg.DefaultTimestamp,
keyspace: s.cfg.Keyspace,
metrics: &queryMetrics{m: make(map[string]*hostMetrics)},
spec: &NonSpeculativeExecution{},
}
s.mu.RUnlock()
return batch
} | go | func (s *Session) NewBatch(typ BatchType) *Batch {
s.mu.RLock()
batch := &Batch{
Type: typ,
rt: s.cfg.RetryPolicy,
serialCons: s.cfg.SerialConsistency,
observer: s.batchObserver,
Cons: s.cons,
defaultTimestamp: s.cfg.DefaultTimestamp,
keyspace: s.cfg.Keyspace,
metrics: &queryMetrics{m: make(map[string]*hostMetrics)},
spec: &NonSpeculativeExecution{},
}
s.mu.RUnlock()
return batch
} | [
"func",
"(",
"s",
"*",
"Session",
")",
"NewBatch",
"(",
"typ",
"BatchType",
")",
"*",
"Batch",
"{",
"s",
".",
"mu",
".",
"RLock",
"(",
")",
"\n",
"batch",
":=",
"&",
"Batch",
"{",
"Type",
":",
"typ",
",",
"rt",
":",
"s",
".",
"cfg",
".",
"Ret... | // NewBatch creates a new batch operation using defaults defined in the cluster | [
"NewBatch",
"creates",
"a",
"new",
"batch",
"operation",
"using",
"defaults",
"defined",
"in",
"the",
"cluster"
] | b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac | https://github.com/gocql/gocql/blob/b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac/session.go#L1499-L1515 | train |
gocql/gocql | session.go | Observer | func (b *Batch) Observer(observer BatchObserver) *Batch {
b.observer = observer
return b
} | go | func (b *Batch) Observer(observer BatchObserver) *Batch {
b.observer = observer
return b
} | [
"func",
"(",
"b",
"*",
"Batch",
")",
"Observer",
"(",
"observer",
"BatchObserver",
")",
"*",
"Batch",
"{",
"b",
".",
"observer",
"=",
"observer",
"\n",
"return",
"b",
"\n",
"}"
] | // Observer enables batch-level observer on this batch.
// The provided observer will be called every time this batched query is executed. | [
"Observer",
"enables",
"batch",
"-",
"level",
"observer",
"on",
"this",
"batch",
".",
"The",
"provided",
"observer",
"will",
"be",
"called",
"every",
"time",
"this",
"batched",
"query",
"is",
"executed",
"."
] | b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac | https://github.com/gocql/gocql/blob/b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac/session.go#L1532-L1535 | train |
gocql/gocql | session.go | Attempts | func (b *Batch) Attempts() int {
b.metrics.l.Lock()
defer b.metrics.l.Unlock()
var attempts int
for _, metric := range b.metrics.m {
attempts += metric.Attempts
}
return attempts
} | go | func (b *Batch) Attempts() int {
b.metrics.l.Lock()
defer b.metrics.l.Unlock()
var attempts int
for _, metric := range b.metrics.m {
attempts += metric.Attempts
}
return attempts
} | [
"func",
"(",
"b",
"*",
"Batch",
")",
"Attempts",
"(",
")",
"int",
"{",
"b",
".",
"metrics",
".",
"l",
".",
"Lock",
"(",
")",
"\n",
"defer",
"b",
".",
"metrics",
".",
"l",
".",
"Unlock",
"(",
")",
"\n",
"var",
"attempts",
"int",
"\n",
"for",
"... | // Attempts returns the number of attempts made to execute the batch. | [
"Attempts",
"returns",
"the",
"number",
"of",
"attempts",
"made",
"to",
"execute",
"the",
"batch",
"."
] | b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac | https://github.com/gocql/gocql/blob/b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac/session.go#L1542-L1551 | train |
gocql/gocql | session.go | Latency | func (b *Batch) Latency() int64 {
b.metrics.l.Lock()
defer b.metrics.l.Unlock()
var (
attempts int
latency int64
)
for _, metric := range b.metrics.m {
attempts += metric.Attempts
latency += metric.TotalLatency
}
if attempts > 0 {
return latency / int64(attempts)
}
return 0
} | go | func (b *Batch) Latency() int64 {
b.metrics.l.Lock()
defer b.metrics.l.Unlock()
var (
attempts int
latency int64
)
for _, metric := range b.metrics.m {
attempts += metric.Attempts
latency += metric.TotalLatency
}
if attempts > 0 {
return latency / int64(attempts)
}
return 0
} | [
"func",
"(",
"b",
"*",
"Batch",
")",
"Latency",
"(",
")",
"int64",
"{",
"b",
".",
"metrics",
".",
"l",
".",
"Lock",
"(",
")",
"\n",
"defer",
"b",
".",
"metrics",
".",
"l",
".",
"Unlock",
"(",
")",
"\n",
"var",
"(",
"attempts",
"int",
"\n",
"l... | //Latency returns the average number of nanoseconds to execute a single attempt of the batch. | [
"Latency",
"returns",
"the",
"average",
"number",
"of",
"nanoseconds",
"to",
"execute",
"a",
"single",
"attempt",
"of",
"the",
"batch",
"."
] | b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac | https://github.com/gocql/gocql/blob/b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac/session.go#L1561-L1577 | train |
gocql/gocql | session.go | Query | func (b *Batch) Query(stmt string, args ...interface{}) {
b.Entries = append(b.Entries, BatchEntry{Stmt: stmt, Args: args})
} | go | func (b *Batch) Query(stmt string, args ...interface{}) {
b.Entries = append(b.Entries, BatchEntry{Stmt: stmt, Args: args})
} | [
"func",
"(",
"b",
"*",
"Batch",
")",
"Query",
"(",
"stmt",
"string",
",",
"args",
"...",
"interface",
"{",
"}",
")",
"{",
"b",
".",
"Entries",
"=",
"append",
"(",
"b",
".",
"Entries",
",",
"BatchEntry",
"{",
"Stmt",
":",
"stmt",
",",
"Args",
":",... | // Query adds the query to the batch operation | [
"Query",
"adds",
"the",
"query",
"to",
"the",
"batch",
"operation"
] | b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac | https://github.com/gocql/gocql/blob/b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac/session.go#L1624-L1626 | train |
gocql/gocql | session.go | Bind | func (b *Batch) Bind(stmt string, bind func(q *QueryInfo) ([]interface{}, error)) {
b.Entries = append(b.Entries, BatchEntry{Stmt: stmt, binding: bind})
} | go | func (b *Batch) Bind(stmt string, bind func(q *QueryInfo) ([]interface{}, error)) {
b.Entries = append(b.Entries, BatchEntry{Stmt: stmt, binding: bind})
} | [
"func",
"(",
"b",
"*",
"Batch",
")",
"Bind",
"(",
"stmt",
"string",
",",
"bind",
"func",
"(",
"q",
"*",
"QueryInfo",
")",
"(",
"[",
"]",
"interface",
"{",
"}",
",",
"error",
")",
")",
"{",
"b",
".",
"Entries",
"=",
"append",
"(",
"b",
".",
"E... | // Bind adds the query to the batch operation and correlates it with a binding callback
// that will be invoked when the batch is executed. The binding callback allows the application
// to define which query argument values will be marshalled as part of the batch execution. | [
"Bind",
"adds",
"the",
"query",
"to",
"the",
"batch",
"operation",
"and",
"correlates",
"it",
"with",
"a",
"binding",
"callback",
"that",
"will",
"be",
"invoked",
"when",
"the",
"batch",
"is",
"executed",
".",
"The",
"binding",
"callback",
"allows",
"the",
... | b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac | https://github.com/gocql/gocql/blob/b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac/session.go#L1631-L1633 | train |
gocql/gocql | session.go | RetryPolicy | func (b *Batch) RetryPolicy(r RetryPolicy) *Batch {
b.rt = r
return b
} | go | func (b *Batch) RetryPolicy(r RetryPolicy) *Batch {
b.rt = r
return b
} | [
"func",
"(",
"b",
"*",
"Batch",
")",
"RetryPolicy",
"(",
"r",
"RetryPolicy",
")",
"*",
"Batch",
"{",
"b",
".",
"rt",
"=",
"r",
"\n",
"return",
"b",
"\n",
"}"
] | // RetryPolicy sets the retry policy to use when executing the batch operation | [
"RetryPolicy",
"sets",
"the",
"retry",
"policy",
"to",
"use",
"when",
"executing",
"the",
"batch",
"operation"
] | b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac | https://github.com/gocql/gocql/blob/b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac/session.go#L1640-L1643 | train |
gocql/gocql | session.go | WithContext | func (b *Batch) WithContext(ctx context.Context) *Batch {
b2 := *b
b2.context = ctx
return &b2
} | go | func (b *Batch) WithContext(ctx context.Context) *Batch {
b2 := *b
b2.context = ctx
return &b2
} | [
"func",
"(",
"b",
"*",
"Batch",
")",
"WithContext",
"(",
"ctx",
"context",
".",
"Context",
")",
"*",
"Batch",
"{",
"b2",
":=",
"*",
"b",
"\n",
"b2",
".",
"context",
"=",
"ctx",
"\n",
"return",
"&",
"b2",
"\n",
"}"
] | // WithContext returns a shallow copy of b with its context
// set to ctx.
//
// The provided context controls the entire lifetime of executing a
// query, queries will be canceled and return once the context is
// canceled. | [
"WithContext",
"returns",
"a",
"shallow",
"copy",
"of",
"b",
"with",
"its",
"context",
"set",
"to",
"ctx",
".",
"The",
"provided",
"context",
"controls",
"the",
"entire",
"lifetime",
"of",
"executing",
"a",
"query",
"queries",
"will",
"be",
"canceled",
"and"... | b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac | https://github.com/gocql/gocql/blob/b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac/session.go#L1655-L1659 | train |
gocql/gocql | session.go | NewTraceWriter | func NewTraceWriter(session *Session, w io.Writer) Tracer {
return &traceWriter{session: session, w: w}
} | go | func NewTraceWriter(session *Session, w io.Writer) Tracer {
return &traceWriter{session: session, w: w}
} | [
"func",
"NewTraceWriter",
"(",
"session",
"*",
"Session",
",",
"w",
"io",
".",
"Writer",
")",
"Tracer",
"{",
"return",
"&",
"traceWriter",
"{",
"session",
":",
"session",
",",
"w",
":",
"w",
"}",
"\n",
"}"
] | // NewTraceWriter returns a simple Tracer implementation that outputs
// the event log in a textual format. | [
"NewTraceWriter",
"returns",
"a",
"simple",
"Tracer",
"implementation",
"that",
"outputs",
"the",
"event",
"log",
"in",
"a",
"textual",
"format",
"."
] | b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac | https://github.com/gocql/gocql/blob/b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac/session.go#L1817-L1819 | train |
gocql/gocql | host_source.go | checkSystemSchema | func checkSystemSchema(control *controlConn) (bool, error) {
iter := control.query("SELECT * FROM system_schema.keyspaces")
if err := iter.err; err != nil {
if errf, ok := err.(*errorFrame); ok {
if errf.code == errSyntax {
return false, nil
}
}
return false, err
}
return true, nil
} | go | func checkSystemSchema(control *controlConn) (bool, error) {
iter := control.query("SELECT * FROM system_schema.keyspaces")
if err := iter.err; err != nil {
if errf, ok := err.(*errorFrame); ok {
if errf.code == errSyntax {
return false, nil
}
}
return false, err
}
return true, nil
} | [
"func",
"checkSystemSchema",
"(",
"control",
"*",
"controlConn",
")",
"(",
"bool",
",",
"error",
")",
"{",
"iter",
":=",
"control",
".",
"query",
"(",
"\"SELECT * FROM system_schema.keyspaces\"",
")",
"\n",
"if",
"err",
":=",
"iter",
".",
"err",
";",
"err",
... | // Returns true if we are using system_schema.keyspaces instead of system.schema_keyspaces | [
"Returns",
"true",
"if",
"we",
"are",
"using",
"system_schema",
".",
"keyspaces",
"instead",
"of",
"system",
".",
"schema_keyspaces"
] | b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac | https://github.com/gocql/gocql/blob/b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac/host_source.go#L436-L449 | train |
gocql/gocql | host_source.go | getClusterPeerInfo | func (r *ringDescriber) getClusterPeerInfo() ([]*HostInfo, error) {
var hosts []*HostInfo
iter := r.session.control.withConnHost(func(ch *connHost) *Iter {
hosts = append(hosts, ch.host)
return ch.conn.query(context.TODO(), "SELECT * FROM system.peers")
})
if iter == nil {
return nil, errNoControl
}
rows, err := iter.SliceMap()
if err != nil {
// TODO(zariel): make typed error
return nil, fmt.Errorf("unable to fetch peer host info: %s", err)
}
for _, row := range rows {
// extract all available info about the peer
host, err := r.session.hostInfoFromMap(row, r.session.cfg.Port)
if err != nil {
return nil, err
} else if !isValidPeer(host) {
// If it's not a valid peer
Logger.Printf("Found invalid peer '%s' "+
"Likely due to a gossip or snitch issue, this host will be ignored", host)
continue
}
hosts = append(hosts, host)
}
return hosts, nil
} | go | func (r *ringDescriber) getClusterPeerInfo() ([]*HostInfo, error) {
var hosts []*HostInfo
iter := r.session.control.withConnHost(func(ch *connHost) *Iter {
hosts = append(hosts, ch.host)
return ch.conn.query(context.TODO(), "SELECT * FROM system.peers")
})
if iter == nil {
return nil, errNoControl
}
rows, err := iter.SliceMap()
if err != nil {
// TODO(zariel): make typed error
return nil, fmt.Errorf("unable to fetch peer host info: %s", err)
}
for _, row := range rows {
// extract all available info about the peer
host, err := r.session.hostInfoFromMap(row, r.session.cfg.Port)
if err != nil {
return nil, err
} else if !isValidPeer(host) {
// If it's not a valid peer
Logger.Printf("Found invalid peer '%s' "+
"Likely due to a gossip or snitch issue, this host will be ignored", host)
continue
}
hosts = append(hosts, host)
}
return hosts, nil
} | [
"func",
"(",
"r",
"*",
"ringDescriber",
")",
"getClusterPeerInfo",
"(",
")",
"(",
"[",
"]",
"*",
"HostInfo",
",",
"error",
")",
"{",
"var",
"hosts",
"[",
"]",
"*",
"HostInfo",
"\n",
"iter",
":=",
"r",
".",
"session",
".",
"control",
".",
"withConnHos... | // Ask the control node for host info on all it's known peers | [
"Ask",
"the",
"control",
"node",
"for",
"host",
"info",
"on",
"all",
"it",
"s",
"known",
"peers"
] | b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac | https://github.com/gocql/gocql/blob/b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac/host_source.go#L559-L592 | train |
gocql/gocql | host_source.go | isValidPeer | func isValidPeer(host *HostInfo) bool {
return !(len(host.RPCAddress()) == 0 ||
host.hostId == "" ||
host.dataCenter == "" ||
host.rack == "" ||
len(host.tokens) == 0)
} | go | func isValidPeer(host *HostInfo) bool {
return !(len(host.RPCAddress()) == 0 ||
host.hostId == "" ||
host.dataCenter == "" ||
host.rack == "" ||
len(host.tokens) == 0)
} | [
"func",
"isValidPeer",
"(",
"host",
"*",
"HostInfo",
")",
"bool",
"{",
"return",
"!",
"(",
"len",
"(",
"host",
".",
"RPCAddress",
"(",
")",
")",
"==",
"0",
"||",
"host",
".",
"hostId",
"==",
"\"\"",
"||",
"host",
".",
"dataCenter",
"==",
"\"\"",
"|... | // Return true if the host is a valid peer | [
"Return",
"true",
"if",
"the",
"host",
"is",
"a",
"valid",
"peer"
] | b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac | https://github.com/gocql/gocql/blob/b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac/host_source.go#L595-L601 | train |
gocql/gocql | host_source.go | GetHosts | func (r *ringDescriber) GetHosts() ([]*HostInfo, string, error) {
r.mu.Lock()
defer r.mu.Unlock()
hosts, err := r.getClusterPeerInfo()
if err != nil {
return r.prevHosts, r.prevPartitioner, err
}
var partitioner string
if len(hosts) > 0 {
partitioner = hosts[0].Partitioner()
}
return hosts, partitioner, nil
} | go | func (r *ringDescriber) GetHosts() ([]*HostInfo, string, error) {
r.mu.Lock()
defer r.mu.Unlock()
hosts, err := r.getClusterPeerInfo()
if err != nil {
return r.prevHosts, r.prevPartitioner, err
}
var partitioner string
if len(hosts) > 0 {
partitioner = hosts[0].Partitioner()
}
return hosts, partitioner, nil
} | [
"func",
"(",
"r",
"*",
"ringDescriber",
")",
"GetHosts",
"(",
")",
"(",
"[",
"]",
"*",
"HostInfo",
",",
"string",
",",
"error",
")",
"{",
"r",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"r",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"ho... | // Return a list of hosts the cluster knows about | [
"Return",
"a",
"list",
"of",
"hosts",
"the",
"cluster",
"knows",
"about"
] | b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac | https://github.com/gocql/gocql/blob/b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac/host_source.go#L604-L619 | train |
gocql/gocql | conn.go | JoinHostPort | func JoinHostPort(addr string, port int) string {
addr = strings.TrimSpace(addr)
if _, _, err := net.SplitHostPort(addr); err != nil {
addr = net.JoinHostPort(addr, strconv.Itoa(port))
}
return addr
} | go | func JoinHostPort(addr string, port int) string {
addr = strings.TrimSpace(addr)
if _, _, err := net.SplitHostPort(addr); err != nil {
addr = net.JoinHostPort(addr, strconv.Itoa(port))
}
return addr
} | [
"func",
"JoinHostPort",
"(",
"addr",
"string",
",",
"port",
"int",
")",
"string",
"{",
"addr",
"=",
"strings",
".",
"TrimSpace",
"(",
"addr",
")",
"\n",
"if",
"_",
",",
"_",
",",
"err",
":=",
"net",
".",
"SplitHostPort",
"(",
"addr",
")",
";",
"err... | //JoinHostPort is a utility to return a address string that can be used
//gocql.Conn to form a connection with a host. | [
"JoinHostPort",
"is",
"a",
"utility",
"to",
"return",
"a",
"address",
"string",
"that",
"can",
"be",
"used",
"gocql",
".",
"Conn",
"to",
"form",
"a",
"connection",
"with",
"a",
"host",
"."
] | b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac | https://github.com/gocql/gocql/blob/b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac/conn.go#L46-L52 | train |
gocql/gocql | conn.go | connect | func (s *Session) connect(host *HostInfo, errorHandler ConnErrorHandler) (*Conn, error) {
return s.dial(host, s.connCfg, errorHandler)
} | go | func (s *Session) connect(host *HostInfo, errorHandler ConnErrorHandler) (*Conn, error) {
return s.dial(host, s.connCfg, errorHandler)
} | [
"func",
"(",
"s",
"*",
"Session",
")",
"connect",
"(",
"host",
"*",
"HostInfo",
",",
"errorHandler",
"ConnErrorHandler",
")",
"(",
"*",
"Conn",
",",
"error",
")",
"{",
"return",
"s",
".",
"dial",
"(",
"host",
",",
"s",
".",
"connCfg",
",",
"errorHand... | // connect establishes a connection to a Cassandra node using session's connection config. | [
"connect",
"establishes",
"a",
"connection",
"to",
"a",
"Cassandra",
"node",
"using",
"session",
"s",
"connection",
"config",
"."
] | b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac | https://github.com/gocql/gocql/blob/b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac/conn.go#L163-L165 | train |
gocql/gocql | conn.go | dial | func (s *Session) dial(host *HostInfo, connConfig *ConnConfig, errorHandler ConnErrorHandler) (*Conn, error) {
var obs ObservedConnect
if s.connectObserver != nil {
obs.Host = host
obs.Start = time.Now()
}
conn, err := s.dialWithoutObserver(host, connConfig, errorHandler)
if s.connectObserver != nil {
obs.End = time.Now()
obs.Err = err
s.connectObserver.ObserveConnect(obs)
}
return conn, err
} | go | func (s *Session) dial(host *HostInfo, connConfig *ConnConfig, errorHandler ConnErrorHandler) (*Conn, error) {
var obs ObservedConnect
if s.connectObserver != nil {
obs.Host = host
obs.Start = time.Now()
}
conn, err := s.dialWithoutObserver(host, connConfig, errorHandler)
if s.connectObserver != nil {
obs.End = time.Now()
obs.Err = err
s.connectObserver.ObserveConnect(obs)
}
return conn, err
} | [
"func",
"(",
"s",
"*",
"Session",
")",
"dial",
"(",
"host",
"*",
"HostInfo",
",",
"connConfig",
"*",
"ConnConfig",
",",
"errorHandler",
"ConnErrorHandler",
")",
"(",
"*",
"Conn",
",",
"error",
")",
"{",
"var",
"obs",
"ObservedConnect",
"\n",
"if",
"s",
... | // dial establishes a connection to a Cassandra node and notifies the session's connectObserver. | [
"dial",
"establishes",
"a",
"connection",
"to",
"a",
"Cassandra",
"node",
"and",
"notifies",
"the",
"session",
"s",
"connectObserver",
"."
] | b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac | https://github.com/gocql/gocql/blob/b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac/conn.go#L168-L184 | train |
gocql/gocql | conn.go | serve | func (c *Conn) serve() {
var err error
for err == nil {
err = c.recv()
}
c.closeWithError(err)
} | go | func (c *Conn) serve() {
var err error
for err == nil {
err = c.recv()
}
c.closeWithError(err)
} | [
"func",
"(",
"c",
"*",
"Conn",
")",
"serve",
"(",
")",
"{",
"var",
"err",
"error",
"\n",
"for",
"err",
"==",
"nil",
"{",
"err",
"=",
"c",
".",
"recv",
"(",
")",
"\n",
"}",
"\n",
"c",
".",
"closeWithError",
"(",
"err",
")",
"\n",
"}"
] | // Serve starts the stream multiplexer for this connection, which is required
// to execute any queries. This method runs as long as the connection is
// open and is therefore usually called in a separate goroutine. | [
"Serve",
"starts",
"the",
"stream",
"multiplexer",
"for",
"this",
"connection",
"which",
"is",
"required",
"to",
"execute",
"any",
"queries",
".",
"This",
"method",
"runs",
"as",
"long",
"as",
"the",
"connection",
"is",
"open",
"and",
"is",
"therefore",
"usu... | b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac | https://github.com/gocql/gocql/blob/b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac/conn.go#L509-L516 | train |
gocql/gocql | token.go | ParseString | func (p murmur3Partitioner) ParseString(str string) token {
val, _ := strconv.ParseInt(str, 10, 64)
return murmur3Token(val)
} | go | func (p murmur3Partitioner) ParseString(str string) token {
val, _ := strconv.ParseInt(str, 10, 64)
return murmur3Token(val)
} | [
"func",
"(",
"p",
"murmur3Partitioner",
")",
"ParseString",
"(",
"str",
"string",
")",
"token",
"{",
"val",
",",
"_",
":=",
"strconv",
".",
"ParseInt",
"(",
"str",
",",
"10",
",",
"64",
")",
"\n",
"return",
"murmur3Token",
"(",
"val",
")",
"\n",
"}"
... | // murmur3 little-endian, 128-bit hash, but returns only h1 | [
"murmur3",
"little",
"-",
"endian",
"128",
"-",
"bit",
"hash",
"but",
"returns",
"only",
"h1"
] | b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac | https://github.com/gocql/gocql/blob/b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac/token.go#L46-L49 | train |
gocql/gocql | events.go | flush | func (e *eventDebouncer) flush() {
if len(e.events) == 0 {
return
}
// if the flush interval is faster than the callback then we will end up calling
// the callback multiple times, probably a bad idea. In this case we could drop
// frames?
go e.callback(e.events)
e.events = make([]frame, 0, eventBufferSize)
} | go | func (e *eventDebouncer) flush() {
if len(e.events) == 0 {
return
}
// if the flush interval is faster than the callback then we will end up calling
// the callback multiple times, probably a bad idea. In this case we could drop
// frames?
go e.callback(e.events)
e.events = make([]frame, 0, eventBufferSize)
} | [
"func",
"(",
"e",
"*",
"eventDebouncer",
")",
"flush",
"(",
")",
"{",
"if",
"len",
"(",
"e",
".",
"events",
")",
"==",
"0",
"{",
"return",
"\n",
"}",
"\n",
"go",
"e",
".",
"callback",
"(",
"e",
".",
"events",
")",
"\n",
"e",
".",
"events",
"=... | // flush must be called with mu locked | [
"flush",
"must",
"be",
"called",
"with",
"mu",
"locked"
] | b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac | https://github.com/gocql/gocql/blob/b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac/events.go#L56-L66 | train |
gocql/gocql | uuid.go | UUIDFromBytes | func UUIDFromBytes(input []byte) (UUID, error) {
var u UUID
if len(input) != 16 {
return u, errors.New("UUIDs must be exactly 16 bytes long")
}
copy(u[:], input)
return u, nil
} | go | func UUIDFromBytes(input []byte) (UUID, error) {
var u UUID
if len(input) != 16 {
return u, errors.New("UUIDs must be exactly 16 bytes long")
}
copy(u[:], input)
return u, nil
} | [
"func",
"UUIDFromBytes",
"(",
"input",
"[",
"]",
"byte",
")",
"(",
"UUID",
",",
"error",
")",
"{",
"var",
"u",
"UUID",
"\n",
"if",
"len",
"(",
"input",
")",
"!=",
"16",
"{",
"return",
"u",
",",
"errors",
".",
"New",
"(",
"\"UUIDs must be exactly 16 b... | // UUIDFromBytes converts a raw byte slice to an UUID. | [
"UUIDFromBytes",
"converts",
"a",
"raw",
"byte",
"slice",
"to",
"an",
"UUID",
"."
] | b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac | https://github.com/gocql/gocql/blob/b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac/uuid.go#L88-L96 | train |
gocql/gocql | uuid.go | Variant | func (u UUID) Variant() int {
x := u[8]
if x&0x80 == 0 {
return VariantNCSCompat
}
if x&0x40 == 0 {
return VariantIETF
}
if x&0x20 == 0 {
return VariantMicrosoft
}
return VariantFuture
} | go | func (u UUID) Variant() int {
x := u[8]
if x&0x80 == 0 {
return VariantNCSCompat
}
if x&0x40 == 0 {
return VariantIETF
}
if x&0x20 == 0 {
return VariantMicrosoft
}
return VariantFuture
} | [
"func",
"(",
"u",
"UUID",
")",
"Variant",
"(",
")",
"int",
"{",
"x",
":=",
"u",
"[",
"8",
"]",
"\n",
"if",
"x",
"&",
"0x80",
"==",
"0",
"{",
"return",
"VariantNCSCompat",
"\n",
"}",
"\n",
"if",
"x",
"&",
"0x40",
"==",
"0",
"{",
"return",
"Var... | // Variant returns the variant of this UUID. This package will only generate
// UUIDs in the IETF variant. | [
"Variant",
"returns",
"the",
"variant",
"of",
"this",
"UUID",
".",
"This",
"package",
"will",
"only",
"generate",
"UUIDs",
"in",
"the",
"IETF",
"variant",
"."
] | b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac | https://github.com/gocql/gocql/blob/b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac/uuid.go#L182-L194 | train |
gocql/gocql | uuid.go | Time | func (u UUID) Time() time.Time {
if u.Version() != 1 {
return time.Time{}
}
t := u.Timestamp()
sec := t / 1e7
nsec := (t % 1e7) * 100
return time.Unix(sec+timeBase, nsec).UTC()
} | go | func (u UUID) Time() time.Time {
if u.Version() != 1 {
return time.Time{}
}
t := u.Timestamp()
sec := t / 1e7
nsec := (t % 1e7) * 100
return time.Unix(sec+timeBase, nsec).UTC()
} | [
"func",
"(",
"u",
"UUID",
")",
"Time",
"(",
")",
"time",
".",
"Time",
"{",
"if",
"u",
".",
"Version",
"(",
")",
"!=",
"1",
"{",
"return",
"time",
".",
"Time",
"{",
"}",
"\n",
"}",
"\n",
"t",
":=",
"u",
".",
"Timestamp",
"(",
")",
"\n",
"sec... | // Time is like Timestamp, except that it returns a time.Time. | [
"Time",
"is",
"like",
"Timestamp",
"except",
"that",
"it",
"returns",
"a",
"time",
".",
"Time",
"."
] | b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac | https://github.com/gocql/gocql/blob/b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac/uuid.go#L235-L243 | train |
gocql/gocql | uuid.go | UnmarshalJSON | func (u *UUID) UnmarshalJSON(data []byte) error {
str := strings.Trim(string(data), `"`)
if len(str) > 36 {
return fmt.Errorf("invalid JSON UUID %s", str)
}
parsed, err := ParseUUID(str)
if err == nil {
copy(u[:], parsed[:])
}
return err
} | go | func (u *UUID) UnmarshalJSON(data []byte) error {
str := strings.Trim(string(data), `"`)
if len(str) > 36 {
return fmt.Errorf("invalid JSON UUID %s", str)
}
parsed, err := ParseUUID(str)
if err == nil {
copy(u[:], parsed[:])
}
return err
} | [
"func",
"(",
"u",
"*",
"UUID",
")",
"UnmarshalJSON",
"(",
"data",
"[",
"]",
"byte",
")",
"error",
"{",
"str",
":=",
"strings",
".",
"Trim",
"(",
"string",
"(",
"data",
")",
",",
"`\"`",
")",
"\n",
"if",
"len",
"(",
"str",
")",
">",
"36",
"{",
... | // Unmarshaling for JSON | [
"Unmarshaling",
"for",
"JSON"
] | b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac | https://github.com/gocql/gocql/blob/b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac/uuid.go#L251-L263 | train |
gocql/gocql | metadata.go | newSchemaDescriber | func newSchemaDescriber(session *Session) *schemaDescriber {
return &schemaDescriber{
session: session,
cache: map[string]*KeyspaceMetadata{},
}
} | go | func newSchemaDescriber(session *Session) *schemaDescriber {
return &schemaDescriber{
session: session,
cache: map[string]*KeyspaceMetadata{},
}
} | [
"func",
"newSchemaDescriber",
"(",
"session",
"*",
"Session",
")",
"*",
"schemaDescriber",
"{",
"return",
"&",
"schemaDescriber",
"{",
"session",
":",
"session",
",",
"cache",
":",
"map",
"[",
"string",
"]",
"*",
"KeyspaceMetadata",
"{",
"}",
",",
"}",
"\n... | // creates a session bound schema describer which will query and cache
// keyspace metadata | [
"creates",
"a",
"session",
"bound",
"schema",
"describer",
"which",
"will",
"query",
"and",
"cache",
"keyspace",
"metadata"
] | b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac | https://github.com/gocql/gocql/blob/b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac/metadata.go#L183-L188 | train |
gocql/gocql | metadata.go | getSchema | func (s *schemaDescriber) getSchema(keyspaceName string) (*KeyspaceMetadata, error) {
s.mu.Lock()
defer s.mu.Unlock()
metadata, found := s.cache[keyspaceName]
if !found {
// refresh the cache for this keyspace
err := s.refreshSchema(keyspaceName)
if err != nil {
return nil, err
}
metadata = s.cache[keyspaceName]
}
return metadata, nil
} | go | func (s *schemaDescriber) getSchema(keyspaceName string) (*KeyspaceMetadata, error) {
s.mu.Lock()
defer s.mu.Unlock()
metadata, found := s.cache[keyspaceName]
if !found {
// refresh the cache for this keyspace
err := s.refreshSchema(keyspaceName)
if err != nil {
return nil, err
}
metadata = s.cache[keyspaceName]
}
return metadata, nil
} | [
"func",
"(",
"s",
"*",
"schemaDescriber",
")",
"getSchema",
"(",
"keyspaceName",
"string",
")",
"(",
"*",
"KeyspaceMetadata",
",",
"error",
")",
"{",
"s",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n... | // returns the cached KeyspaceMetadata held by the describer for the named
// keyspace. | [
"returns",
"the",
"cached",
"KeyspaceMetadata",
"held",
"by",
"the",
"describer",
"for",
"the",
"named",
"keyspace",
"."
] | b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac | https://github.com/gocql/gocql/blob/b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac/metadata.go#L192-L208 | train |
gocql/gocql | metadata.go | clearSchema | func (s *schemaDescriber) clearSchema(keyspaceName string) {
s.mu.Lock()
defer s.mu.Unlock()
delete(s.cache, keyspaceName)
} | go | func (s *schemaDescriber) clearSchema(keyspaceName string) {
s.mu.Lock()
defer s.mu.Unlock()
delete(s.cache, keyspaceName)
} | [
"func",
"(",
"s",
"*",
"schemaDescriber",
")",
"clearSchema",
"(",
"keyspaceName",
"string",
")",
"{",
"s",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"delete",
"(",
"s",
".",
"cache",
",",
"ke... | // clears the already cached keyspace metadata | [
"clears",
"the",
"already",
"cached",
"keyspace",
"metadata"
] | b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac | https://github.com/gocql/gocql/blob/b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac/metadata.go#L211-L216 | train |
gocql/gocql | metadata.go | refreshSchema | func (s *schemaDescriber) refreshSchema(keyspaceName string) error {
var err error
// query the system keyspace for schema data
// TODO retrieve concurrently
keyspace, err := getKeyspaceMetadata(s.session, keyspaceName)
if err != nil {
return err
}
tables, err := getTableMetadata(s.session, keyspaceName)
if err != nil {
return err
}
columns, err := getColumnMetadata(s.session, keyspaceName)
if err != nil {
return err
}
functions, err := getFunctionsMetadata(s.session, keyspaceName)
if err != nil {
return err
}
aggregates, err := getAggregatesMetadata(s.session, keyspaceName)
if err != nil {
return err
}
views, err := getViewsMetadata(s.session, keyspaceName)
if err != nil {
return err
}
// organize the schema data
compileMetadata(s.session.cfg.ProtoVersion, keyspace, tables, columns, functions, aggregates, views)
// update the cache
s.cache[keyspaceName] = keyspace
return nil
} | go | func (s *schemaDescriber) refreshSchema(keyspaceName string) error {
var err error
// query the system keyspace for schema data
// TODO retrieve concurrently
keyspace, err := getKeyspaceMetadata(s.session, keyspaceName)
if err != nil {
return err
}
tables, err := getTableMetadata(s.session, keyspaceName)
if err != nil {
return err
}
columns, err := getColumnMetadata(s.session, keyspaceName)
if err != nil {
return err
}
functions, err := getFunctionsMetadata(s.session, keyspaceName)
if err != nil {
return err
}
aggregates, err := getAggregatesMetadata(s.session, keyspaceName)
if err != nil {
return err
}
views, err := getViewsMetadata(s.session, keyspaceName)
if err != nil {
return err
}
// organize the schema data
compileMetadata(s.session.cfg.ProtoVersion, keyspace, tables, columns, functions, aggregates, views)
// update the cache
s.cache[keyspaceName] = keyspace
return nil
} | [
"func",
"(",
"s",
"*",
"schemaDescriber",
")",
"refreshSchema",
"(",
"keyspaceName",
"string",
")",
"error",
"{",
"var",
"err",
"error",
"\n",
"keyspace",
",",
"err",
":=",
"getKeyspaceMetadata",
"(",
"s",
".",
"session",
",",
"keyspaceName",
")",
"\n",
"i... | // forcibly updates the current KeyspaceMetadata held by the schema describer
// for a given named keyspace. | [
"forcibly",
"updates",
"the",
"current",
"KeyspaceMetadata",
"held",
"by",
"the",
"schema",
"describer",
"for",
"a",
"given",
"named",
"keyspace",
"."
] | b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac | https://github.com/gocql/gocql/blob/b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac/metadata.go#L220-L257 | train |
gocql/gocql | metadata.go | compileMetadata | func compileMetadata(
protoVersion int,
keyspace *KeyspaceMetadata,
tables []TableMetadata,
columns []ColumnMetadata,
functions []FunctionMetadata,
aggregates []AggregateMetadata,
views []ViewMetadata,
) {
keyspace.Tables = make(map[string]*TableMetadata)
for i := range tables {
tables[i].Columns = make(map[string]*ColumnMetadata)
keyspace.Tables[tables[i].Name] = &tables[i]
}
keyspace.Functions = make(map[string]*FunctionMetadata, len(functions))
for i := range functions {
keyspace.Functions[functions[i].Name] = &functions[i]
}
keyspace.Aggregates = make(map[string]*AggregateMetadata, len(aggregates))
for _, aggregate := range aggregates {
aggregate.FinalFunc = *keyspace.Functions[aggregate.finalFunc]
aggregate.StateFunc = *keyspace.Functions[aggregate.stateFunc]
keyspace.Aggregates[aggregate.Name] = &aggregate
}
keyspace.Views = make(map[string]*ViewMetadata, len(views))
for i := range views {
keyspace.Views[views[i].Name] = &views[i]
}
// add columns from the schema data
for i := range columns {
col := &columns[i]
// decode the validator for TypeInfo and order
if col.ClusteringOrder != "" { // Cassandra 3.x+
col.Type = getCassandraType(col.Validator)
col.Order = ASC
if col.ClusteringOrder == "desc" {
col.Order = DESC
}
} else {
validatorParsed := parseType(col.Validator)
col.Type = validatorParsed.types[0]
col.Order = ASC
if validatorParsed.reversed[0] {
col.Order = DESC
}
}
table, ok := keyspace.Tables[col.Table]
if !ok {
// if the schema is being updated we will race between seeing
// the metadata be complete. Potentially we should check for
// schema versions before and after reading the metadata and
// if they dont match try again.
continue
}
table.Columns[col.Name] = col
table.OrderedColumns = append(table.OrderedColumns, col.Name)
}
if protoVersion == protoVersion1 {
compileV1Metadata(tables)
} else {
compileV2Metadata(tables)
}
} | go | func compileMetadata(
protoVersion int,
keyspace *KeyspaceMetadata,
tables []TableMetadata,
columns []ColumnMetadata,
functions []FunctionMetadata,
aggregates []AggregateMetadata,
views []ViewMetadata,
) {
keyspace.Tables = make(map[string]*TableMetadata)
for i := range tables {
tables[i].Columns = make(map[string]*ColumnMetadata)
keyspace.Tables[tables[i].Name] = &tables[i]
}
keyspace.Functions = make(map[string]*FunctionMetadata, len(functions))
for i := range functions {
keyspace.Functions[functions[i].Name] = &functions[i]
}
keyspace.Aggregates = make(map[string]*AggregateMetadata, len(aggregates))
for _, aggregate := range aggregates {
aggregate.FinalFunc = *keyspace.Functions[aggregate.finalFunc]
aggregate.StateFunc = *keyspace.Functions[aggregate.stateFunc]
keyspace.Aggregates[aggregate.Name] = &aggregate
}
keyspace.Views = make(map[string]*ViewMetadata, len(views))
for i := range views {
keyspace.Views[views[i].Name] = &views[i]
}
// add columns from the schema data
for i := range columns {
col := &columns[i]
// decode the validator for TypeInfo and order
if col.ClusteringOrder != "" { // Cassandra 3.x+
col.Type = getCassandraType(col.Validator)
col.Order = ASC
if col.ClusteringOrder == "desc" {
col.Order = DESC
}
} else {
validatorParsed := parseType(col.Validator)
col.Type = validatorParsed.types[0]
col.Order = ASC
if validatorParsed.reversed[0] {
col.Order = DESC
}
}
table, ok := keyspace.Tables[col.Table]
if !ok {
// if the schema is being updated we will race between seeing
// the metadata be complete. Potentially we should check for
// schema versions before and after reading the metadata and
// if they dont match try again.
continue
}
table.Columns[col.Name] = col
table.OrderedColumns = append(table.OrderedColumns, col.Name)
}
if protoVersion == protoVersion1 {
compileV1Metadata(tables)
} else {
compileV2Metadata(tables)
}
} | [
"func",
"compileMetadata",
"(",
"protoVersion",
"int",
",",
"keyspace",
"*",
"KeyspaceMetadata",
",",
"tables",
"[",
"]",
"TableMetadata",
",",
"columns",
"[",
"]",
"ColumnMetadata",
",",
"functions",
"[",
"]",
"FunctionMetadata",
",",
"aggregates",
"[",
"]",
... | // "compiles" derived information about keyspace, table, and column metadata
// for a keyspace from the basic queried metadata objects returned by
// getKeyspaceMetadata, getTableMetadata, and getColumnMetadata respectively;
// Links the metadata objects together and derives the column composition of
// the partition key and clustering key for a table. | [
"compiles",
"derived",
"information",
"about",
"keyspace",
"table",
"and",
"column",
"metadata",
"for",
"a",
"keyspace",
"from",
"the",
"basic",
"queried",
"metadata",
"objects",
"returned",
"by",
"getKeyspaceMetadata",
"getTableMetadata",
"and",
"getColumnMetadata",
... | b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac | https://github.com/gocql/gocql/blob/b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac/metadata.go#L264-L331 | train |
gocql/gocql | metadata.go | compileV2Metadata | func compileV2Metadata(tables []TableMetadata) {
for i := range tables {
table := &tables[i]
clusteringColumnCount := componentColumnCountOfType(table.Columns, ColumnClusteringKey)
table.ClusteringColumns = make([]*ColumnMetadata, clusteringColumnCount)
if table.KeyValidator != "" {
keyValidatorParsed := parseType(table.KeyValidator)
table.PartitionKey = make([]*ColumnMetadata, len(keyValidatorParsed.types))
} else { // Cassandra 3.x+
partitionKeyCount := componentColumnCountOfType(table.Columns, ColumnPartitionKey)
table.PartitionKey = make([]*ColumnMetadata, partitionKeyCount)
}
for _, columnName := range table.OrderedColumns {
column := table.Columns[columnName]
if column.Kind == ColumnPartitionKey {
table.PartitionKey[column.ComponentIndex] = column
} else if column.Kind == ColumnClusteringKey {
table.ClusteringColumns[column.ComponentIndex] = column
}
}
}
} | go | func compileV2Metadata(tables []TableMetadata) {
for i := range tables {
table := &tables[i]
clusteringColumnCount := componentColumnCountOfType(table.Columns, ColumnClusteringKey)
table.ClusteringColumns = make([]*ColumnMetadata, clusteringColumnCount)
if table.KeyValidator != "" {
keyValidatorParsed := parseType(table.KeyValidator)
table.PartitionKey = make([]*ColumnMetadata, len(keyValidatorParsed.types))
} else { // Cassandra 3.x+
partitionKeyCount := componentColumnCountOfType(table.Columns, ColumnPartitionKey)
table.PartitionKey = make([]*ColumnMetadata, partitionKeyCount)
}
for _, columnName := range table.OrderedColumns {
column := table.Columns[columnName]
if column.Kind == ColumnPartitionKey {
table.PartitionKey[column.ComponentIndex] = column
} else if column.Kind == ColumnClusteringKey {
table.ClusteringColumns[column.ComponentIndex] = column
}
}
}
} | [
"func",
"compileV2Metadata",
"(",
"tables",
"[",
"]",
"TableMetadata",
")",
"{",
"for",
"i",
":=",
"range",
"tables",
"{",
"table",
":=",
"&",
"tables",
"[",
"i",
"]",
"\n",
"clusteringColumnCount",
":=",
"componentColumnCountOfType",
"(",
"table",
".",
"Col... | // The simpler compile case for V2+ protocol | [
"The",
"simpler",
"compile",
"case",
"for",
"V2",
"+",
"protocol"
] | b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac | https://github.com/gocql/gocql/blob/b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac/metadata.go#L445-L469 | train |
gocql/gocql | metadata.go | componentColumnCountOfType | func componentColumnCountOfType(columns map[string]*ColumnMetadata, kind ColumnKind) int {
maxComponentIndex := -1
for _, column := range columns {
if column.Kind == kind && column.ComponentIndex > maxComponentIndex {
maxComponentIndex = column.ComponentIndex
}
}
return maxComponentIndex + 1
} | go | func componentColumnCountOfType(columns map[string]*ColumnMetadata, kind ColumnKind) int {
maxComponentIndex := -1
for _, column := range columns {
if column.Kind == kind && column.ComponentIndex > maxComponentIndex {
maxComponentIndex = column.ComponentIndex
}
}
return maxComponentIndex + 1
} | [
"func",
"componentColumnCountOfType",
"(",
"columns",
"map",
"[",
"string",
"]",
"*",
"ColumnMetadata",
",",
"kind",
"ColumnKind",
")",
"int",
"{",
"maxComponentIndex",
":=",
"-",
"1",
"\n",
"for",
"_",
",",
"column",
":=",
"range",
"columns",
"{",
"if",
"... | // returns the count of coluns with the given "kind" value. | [
"returns",
"the",
"count",
"of",
"coluns",
"with",
"the",
"given",
"kind",
"value",
"."
] | b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac | https://github.com/gocql/gocql/blob/b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac/metadata.go#L472-L480 | train |
gocql/gocql | metadata.go | getKeyspaceMetadata | func getKeyspaceMetadata(session *Session, keyspaceName string) (*KeyspaceMetadata, error) {
keyspace := &KeyspaceMetadata{Name: keyspaceName}
if session.useSystemSchema { // Cassandra 3.x+
const stmt = `
SELECT durable_writes, replication
FROM system_schema.keyspaces
WHERE keyspace_name = ?`
var replication map[string]string
iter := session.control.query(stmt, keyspaceName)
if iter.NumRows() == 0 {
return nil, ErrKeyspaceDoesNotExist
}
iter.Scan(&keyspace.DurableWrites, &replication)
err := iter.Close()
if err != nil {
return nil, fmt.Errorf("Error querying keyspace schema: %v", err)
}
keyspace.StrategyClass = replication["class"]
delete(replication, "class")
keyspace.StrategyOptions = make(map[string]interface{}, len(replication))
for k, v := range replication {
keyspace.StrategyOptions[k] = v
}
} else {
const stmt = `
SELECT durable_writes, strategy_class, strategy_options
FROM system.schema_keyspaces
WHERE keyspace_name = ?`
var strategyOptionsJSON []byte
iter := session.control.query(stmt, keyspaceName)
if iter.NumRows() == 0 {
return nil, ErrKeyspaceDoesNotExist
}
iter.Scan(&keyspace.DurableWrites, &keyspace.StrategyClass, &strategyOptionsJSON)
err := iter.Close()
if err != nil {
return nil, fmt.Errorf("Error querying keyspace schema: %v", err)
}
err = json.Unmarshal(strategyOptionsJSON, &keyspace.StrategyOptions)
if err != nil {
return nil, fmt.Errorf(
"Invalid JSON value '%s' as strategy_options for in keyspace '%s': %v",
strategyOptionsJSON, keyspace.Name, err,
)
}
}
return keyspace, nil
} | go | func getKeyspaceMetadata(session *Session, keyspaceName string) (*KeyspaceMetadata, error) {
keyspace := &KeyspaceMetadata{Name: keyspaceName}
if session.useSystemSchema { // Cassandra 3.x+
const stmt = `
SELECT durable_writes, replication
FROM system_schema.keyspaces
WHERE keyspace_name = ?`
var replication map[string]string
iter := session.control.query(stmt, keyspaceName)
if iter.NumRows() == 0 {
return nil, ErrKeyspaceDoesNotExist
}
iter.Scan(&keyspace.DurableWrites, &replication)
err := iter.Close()
if err != nil {
return nil, fmt.Errorf("Error querying keyspace schema: %v", err)
}
keyspace.StrategyClass = replication["class"]
delete(replication, "class")
keyspace.StrategyOptions = make(map[string]interface{}, len(replication))
for k, v := range replication {
keyspace.StrategyOptions[k] = v
}
} else {
const stmt = `
SELECT durable_writes, strategy_class, strategy_options
FROM system.schema_keyspaces
WHERE keyspace_name = ?`
var strategyOptionsJSON []byte
iter := session.control.query(stmt, keyspaceName)
if iter.NumRows() == 0 {
return nil, ErrKeyspaceDoesNotExist
}
iter.Scan(&keyspace.DurableWrites, &keyspace.StrategyClass, &strategyOptionsJSON)
err := iter.Close()
if err != nil {
return nil, fmt.Errorf("Error querying keyspace schema: %v", err)
}
err = json.Unmarshal(strategyOptionsJSON, &keyspace.StrategyOptions)
if err != nil {
return nil, fmt.Errorf(
"Invalid JSON value '%s' as strategy_options for in keyspace '%s': %v",
strategyOptionsJSON, keyspace.Name, err,
)
}
}
return keyspace, nil
} | [
"func",
"getKeyspaceMetadata",
"(",
"session",
"*",
"Session",
",",
"keyspaceName",
"string",
")",
"(",
"*",
"KeyspaceMetadata",
",",
"error",
")",
"{",
"keyspace",
":=",
"&",
"KeyspaceMetadata",
"{",
"Name",
":",
"keyspaceName",
"}",
"\n",
"if",
"session",
... | // query only for the keyspace metadata for the specified keyspace from system.schema_keyspace | [
"query",
"only",
"for",
"the",
"keyspace",
"metadata",
"for",
"the",
"specified",
"keyspace",
"from",
"system",
".",
"schema_keyspace"
] | b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac | https://github.com/gocql/gocql/blob/b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac/metadata.go#L483-L540 | train |
gocql/gocql | metadata.go | getColumnMetadata | func getColumnMetadata(session *Session, keyspaceName string) ([]ColumnMetadata, error) {
var (
columns []ColumnMetadata
err error
)
// Deal with differences in protocol versions
if session.cfg.ProtoVersion == 1 {
columns, err = session.scanColumnMetadataV1(keyspaceName)
} else if session.useSystemSchema { // Cassandra 3.x+
columns, err = session.scanColumnMetadataSystem(keyspaceName)
} else {
columns, err = session.scanColumnMetadataV2(keyspaceName)
}
if err != nil && err != ErrNotFound {
return nil, fmt.Errorf("Error querying column schema: %v", err)
}
return columns, nil
} | go | func getColumnMetadata(session *Session, keyspaceName string) ([]ColumnMetadata, error) {
var (
columns []ColumnMetadata
err error
)
// Deal with differences in protocol versions
if session.cfg.ProtoVersion == 1 {
columns, err = session.scanColumnMetadataV1(keyspaceName)
} else if session.useSystemSchema { // Cassandra 3.x+
columns, err = session.scanColumnMetadataSystem(keyspaceName)
} else {
columns, err = session.scanColumnMetadataV2(keyspaceName)
}
if err != nil && err != ErrNotFound {
return nil, fmt.Errorf("Error querying column schema: %v", err)
}
return columns, nil
} | [
"func",
"getColumnMetadata",
"(",
"session",
"*",
"Session",
",",
"keyspaceName",
"string",
")",
"(",
"[",
"]",
"ColumnMetadata",
",",
"error",
")",
"{",
"var",
"(",
"columns",
"[",
"]",
"ColumnMetadata",
"\n",
"err",
"error",
"\n",
")",
"\n",
"if",
"ses... | // query for only the column metadata in the specified keyspace from system.schema_columns | [
"query",
"for",
"only",
"the",
"column",
"metadata",
"in",
"the",
"specified",
"keyspace",
"from",
"system",
".",
"schema_columns"
] | b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac | https://github.com/gocql/gocql/blob/b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac/metadata.go#L841-L861 | train |
gocql/gocql | metadata.go | parseType | func parseType(def string) typeParserResult {
parser := &typeParser{input: def}
return parser.parse()
} | go | func parseType(def string) typeParserResult {
parser := &typeParser{input: def}
return parser.parse()
} | [
"func",
"parseType",
"(",
"def",
"string",
")",
"typeParserResult",
"{",
"parser",
":=",
"&",
"typeParser",
"{",
"input",
":",
"def",
"}",
"\n",
"return",
"parser",
".",
"parse",
"(",
")",
"\n",
"}"
] | // Parse the type definition used for validator and comparator schema data | [
"Parse",
"the",
"type",
"definition",
"used",
"for",
"validator",
"and",
"comparator",
"schema",
"data"
] | b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac | https://github.com/gocql/gocql/blob/b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac/metadata.go#L1043-L1046 | train |
gocql/gocql | connectionpool.go | Pick | func (pool *hostConnPool) Pick() *Conn {
pool.mu.RLock()
defer pool.mu.RUnlock()
if pool.closed {
return nil
}
size := len(pool.conns)
if size < pool.size {
// try to fill the pool
go pool.fill()
if size == 0 {
return nil
}
}
pos := int(atomic.AddUint32(&pool.pos, 1) - 1)
var (
leastBusyConn *Conn
streamsAvailable int
)
// find the conn which has the most available streams, this is racy
for i := 0; i < size; i++ {
conn := pool.conns[(pos+i)%size]
if streams := conn.AvailableStreams(); streams > streamsAvailable {
leastBusyConn = conn
streamsAvailable = streams
}
}
return leastBusyConn
} | go | func (pool *hostConnPool) Pick() *Conn {
pool.mu.RLock()
defer pool.mu.RUnlock()
if pool.closed {
return nil
}
size := len(pool.conns)
if size < pool.size {
// try to fill the pool
go pool.fill()
if size == 0 {
return nil
}
}
pos := int(atomic.AddUint32(&pool.pos, 1) - 1)
var (
leastBusyConn *Conn
streamsAvailable int
)
// find the conn which has the most available streams, this is racy
for i := 0; i < size; i++ {
conn := pool.conns[(pos+i)%size]
if streams := conn.AvailableStreams(); streams > streamsAvailable {
leastBusyConn = conn
streamsAvailable = streams
}
}
return leastBusyConn
} | [
"func",
"(",
"pool",
"*",
"hostConnPool",
")",
"Pick",
"(",
")",
"*",
"Conn",
"{",
"pool",
".",
"mu",
".",
"RLock",
"(",
")",
"\n",
"defer",
"pool",
".",
"mu",
".",
"RUnlock",
"(",
")",
"\n",
"if",
"pool",
".",
"closed",
"{",
"return",
"nil",
"... | // Pick a connection from this connection pool for the given query. | [
"Pick",
"a",
"connection",
"from",
"this",
"connection",
"pool",
"for",
"the",
"given",
"query",
"."
] | b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac | https://github.com/gocql/gocql/blob/b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac/connectionpool.go#L297-L332 | train |
gocql/gocql | connectionpool.go | Size | func (pool *hostConnPool) Size() int {
pool.mu.RLock()
defer pool.mu.RUnlock()
return len(pool.conns)
} | go | func (pool *hostConnPool) Size() int {
pool.mu.RLock()
defer pool.mu.RUnlock()
return len(pool.conns)
} | [
"func",
"(",
"pool",
"*",
"hostConnPool",
")",
"Size",
"(",
")",
"int",
"{",
"pool",
".",
"mu",
".",
"RLock",
"(",
")",
"\n",
"defer",
"pool",
".",
"mu",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"len",
"(",
"pool",
".",
"conns",
")",
"\n",
"}"... | //Size returns the number of connections currently active in the pool | [
"Size",
"returns",
"the",
"number",
"of",
"connections",
"currently",
"active",
"in",
"the",
"pool"
] | b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac | https://github.com/gocql/gocql/blob/b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac/connectionpool.go#L335-L340 | train |
gocql/gocql | connectionpool.go | Close | func (pool *hostConnPool) Close() {
pool.mu.Lock()
if pool.closed {
pool.mu.Unlock()
return
}
pool.closed = true
// ensure we dont try to reacquire the lock in handleError
// TODO: improve this as the following can happen
// 1) we have locked pool.mu write lock
// 2) conn.Close calls conn.closeWithError(nil)
// 3) conn.closeWithError calls conn.Close() which returns an error
// 4) conn.closeWithError calls pool.HandleError with the error from conn.Close
// 5) pool.HandleError tries to lock pool.mu
// deadlock
// empty the pool
conns := pool.conns
pool.conns = nil
pool.mu.Unlock()
// close the connections
for _, conn := range conns {
conn.Close()
}
} | go | func (pool *hostConnPool) Close() {
pool.mu.Lock()
if pool.closed {
pool.mu.Unlock()
return
}
pool.closed = true
// ensure we dont try to reacquire the lock in handleError
// TODO: improve this as the following can happen
// 1) we have locked pool.mu write lock
// 2) conn.Close calls conn.closeWithError(nil)
// 3) conn.closeWithError calls conn.Close() which returns an error
// 4) conn.closeWithError calls pool.HandleError with the error from conn.Close
// 5) pool.HandleError tries to lock pool.mu
// deadlock
// empty the pool
conns := pool.conns
pool.conns = nil
pool.mu.Unlock()
// close the connections
for _, conn := range conns {
conn.Close()
}
} | [
"func",
"(",
"pool",
"*",
"hostConnPool",
")",
"Close",
"(",
")",
"{",
"pool",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"if",
"pool",
".",
"closed",
"{",
"pool",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"\n",
"}",
"\n",
"pool",
".",
... | //Close the connection pool | [
"Close",
"the",
"connection",
"pool"
] | b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac | https://github.com/gocql/gocql/blob/b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac/connectionpool.go#L343-L371 | train |
gocql/gocql | connectionpool.go | fill | func (pool *hostConnPool) fill() {
pool.mu.RLock()
// avoid filling a closed pool, or concurrent filling
if pool.closed || pool.filling {
pool.mu.RUnlock()
return
}
// determine the filling work to be done
startCount := len(pool.conns)
fillCount := pool.size - startCount
// avoid filling a full (or overfull) pool
if fillCount <= 0 {
pool.mu.RUnlock()
return
}
// switch from read to write lock
pool.mu.RUnlock()
pool.mu.Lock()
// double check everything since the lock was released
startCount = len(pool.conns)
fillCount = pool.size - startCount
if pool.closed || pool.filling || fillCount <= 0 {
// looks like another goroutine already beat this
// goroutine to the filling
pool.mu.Unlock()
return
}
// ok fill the pool
pool.filling = true
// allow others to access the pool while filling
pool.mu.Unlock()
// only this goroutine should make calls to fill/empty the pool at this
// point until after this routine or its subordinates calls
// fillingStopped
// fill only the first connection synchronously
if startCount == 0 {
err := pool.connect()
pool.logConnectErr(err)
if err != nil {
// probably unreachable host
pool.fillingStopped(true)
// this is call with the connection pool mutex held, this call will
// then recursively try to lock it again. FIXME
if pool.session.cfg.ConvictionPolicy.AddFailure(err, pool.host) {
go pool.session.handleNodeDown(pool.host.ConnectAddress(), pool.port)
}
return
}
// filled one
fillCount--
}
// fill the rest of the pool asynchronously
go func() {
err := pool.connectMany(fillCount)
// mark the end of filling
pool.fillingStopped(err != nil)
}()
} | go | func (pool *hostConnPool) fill() {
pool.mu.RLock()
// avoid filling a closed pool, or concurrent filling
if pool.closed || pool.filling {
pool.mu.RUnlock()
return
}
// determine the filling work to be done
startCount := len(pool.conns)
fillCount := pool.size - startCount
// avoid filling a full (or overfull) pool
if fillCount <= 0 {
pool.mu.RUnlock()
return
}
// switch from read to write lock
pool.mu.RUnlock()
pool.mu.Lock()
// double check everything since the lock was released
startCount = len(pool.conns)
fillCount = pool.size - startCount
if pool.closed || pool.filling || fillCount <= 0 {
// looks like another goroutine already beat this
// goroutine to the filling
pool.mu.Unlock()
return
}
// ok fill the pool
pool.filling = true
// allow others to access the pool while filling
pool.mu.Unlock()
// only this goroutine should make calls to fill/empty the pool at this
// point until after this routine or its subordinates calls
// fillingStopped
// fill only the first connection synchronously
if startCount == 0 {
err := pool.connect()
pool.logConnectErr(err)
if err != nil {
// probably unreachable host
pool.fillingStopped(true)
// this is call with the connection pool mutex held, this call will
// then recursively try to lock it again. FIXME
if pool.session.cfg.ConvictionPolicy.AddFailure(err, pool.host) {
go pool.session.handleNodeDown(pool.host.ConnectAddress(), pool.port)
}
return
}
// filled one
fillCount--
}
// fill the rest of the pool asynchronously
go func() {
err := pool.connectMany(fillCount)
// mark the end of filling
pool.fillingStopped(err != nil)
}()
} | [
"func",
"(",
"pool",
"*",
"hostConnPool",
")",
"fill",
"(",
")",
"{",
"pool",
".",
"mu",
".",
"RLock",
"(",
")",
"\n",
"if",
"pool",
".",
"closed",
"||",
"pool",
".",
"filling",
"{",
"pool",
".",
"mu",
".",
"RUnlock",
"(",
")",
"\n",
"return",
... | // Fill the connection pool | [
"Fill",
"the",
"connection",
"pool"
] | b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac | https://github.com/gocql/gocql/blob/b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac/connectionpool.go#L374-L443 | train |
gocql/gocql | connectionpool.go | fillingStopped | func (pool *hostConnPool) fillingStopped(hadError bool) {
if hadError {
// wait for some time to avoid back-to-back filling
// this provides some time between failed attempts
// to fill the pool for the host to recover
time.Sleep(time.Duration(rand.Int31n(100)+31) * time.Millisecond)
}
pool.mu.Lock()
pool.filling = false
pool.mu.Unlock()
} | go | func (pool *hostConnPool) fillingStopped(hadError bool) {
if hadError {
// wait for some time to avoid back-to-back filling
// this provides some time between failed attempts
// to fill the pool for the host to recover
time.Sleep(time.Duration(rand.Int31n(100)+31) * time.Millisecond)
}
pool.mu.Lock()
pool.filling = false
pool.mu.Unlock()
} | [
"func",
"(",
"pool",
"*",
"hostConnPool",
")",
"fillingStopped",
"(",
"hadError",
"bool",
")",
"{",
"if",
"hadError",
"{",
"time",
".",
"Sleep",
"(",
"time",
".",
"Duration",
"(",
"rand",
".",
"Int31n",
"(",
"100",
")",
"+",
"31",
")",
"*",
"time",
... | // transition back to a not-filling state. | [
"transition",
"back",
"to",
"a",
"not",
"-",
"filling",
"state",
"."
] | b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac | https://github.com/gocql/gocql/blob/b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac/connectionpool.go#L459-L470 | train |
gocql/gocql | connectionpool.go | connectMany | func (pool *hostConnPool) connectMany(count int) error {
if count == 0 {
return nil
}
var (
wg sync.WaitGroup
mu sync.Mutex
connectErr error
)
wg.Add(count)
for i := 0; i < count; i++ {
go func() {
defer wg.Done()
err := pool.connect()
pool.logConnectErr(err)
if err != nil {
mu.Lock()
connectErr = err
mu.Unlock()
}
}()
}
// wait for all connections are done
wg.Wait()
return connectErr
} | go | func (pool *hostConnPool) connectMany(count int) error {
if count == 0 {
return nil
}
var (
wg sync.WaitGroup
mu sync.Mutex
connectErr error
)
wg.Add(count)
for i := 0; i < count; i++ {
go func() {
defer wg.Done()
err := pool.connect()
pool.logConnectErr(err)
if err != nil {
mu.Lock()
connectErr = err
mu.Unlock()
}
}()
}
// wait for all connections are done
wg.Wait()
return connectErr
} | [
"func",
"(",
"pool",
"*",
"hostConnPool",
")",
"connectMany",
"(",
"count",
"int",
")",
"error",
"{",
"if",
"count",
"==",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"var",
"(",
"wg",
"sync",
".",
"WaitGroup",
"\n",
"mu",
"sync",
".",
"Mutex",
"\n... | // connectMany creates new connections concurrent. | [
"connectMany",
"creates",
"new",
"connections",
"concurrent",
"."
] | b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac | https://github.com/gocql/gocql/blob/b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac/connectionpool.go#L473-L499 | train |
gocql/gocql | connectionpool.go | connect | func (pool *hostConnPool) connect() (err error) {
// TODO: provide a more robust connection retry mechanism, we should also
// be able to detect hosts that come up by trying to connect to downed ones.
// try to connect
var conn *Conn
reconnectionPolicy := pool.session.cfg.ReconnectionPolicy
for i := 0; i < reconnectionPolicy.GetMaxRetries(); i++ {
conn, err = pool.session.connect(pool.host, pool)
if err == nil {
break
}
if opErr, isOpErr := err.(*net.OpError); isOpErr {
// if the error is not a temporary error (ex: network unreachable) don't
// retry
if !opErr.Temporary() {
break
}
}
if gocqlDebug {
Logger.Printf("connection failed %q: %v, reconnecting with %T\n",
pool.host.ConnectAddress(), err, reconnectionPolicy)
}
time.Sleep(reconnectionPolicy.GetInterval(i))
}
if err != nil {
return err
}
if pool.keyspace != "" {
// set the keyspace
if err = conn.UseKeyspace(pool.keyspace); err != nil {
conn.Close()
return err
}
}
// add the Conn to the pool
pool.mu.Lock()
defer pool.mu.Unlock()
if pool.closed {
conn.Close()
return nil
}
pool.conns = append(pool.conns, conn)
return nil
} | go | func (pool *hostConnPool) connect() (err error) {
// TODO: provide a more robust connection retry mechanism, we should also
// be able to detect hosts that come up by trying to connect to downed ones.
// try to connect
var conn *Conn
reconnectionPolicy := pool.session.cfg.ReconnectionPolicy
for i := 0; i < reconnectionPolicy.GetMaxRetries(); i++ {
conn, err = pool.session.connect(pool.host, pool)
if err == nil {
break
}
if opErr, isOpErr := err.(*net.OpError); isOpErr {
// if the error is not a temporary error (ex: network unreachable) don't
// retry
if !opErr.Temporary() {
break
}
}
if gocqlDebug {
Logger.Printf("connection failed %q: %v, reconnecting with %T\n",
pool.host.ConnectAddress(), err, reconnectionPolicy)
}
time.Sleep(reconnectionPolicy.GetInterval(i))
}
if err != nil {
return err
}
if pool.keyspace != "" {
// set the keyspace
if err = conn.UseKeyspace(pool.keyspace); err != nil {
conn.Close()
return err
}
}
// add the Conn to the pool
pool.mu.Lock()
defer pool.mu.Unlock()
if pool.closed {
conn.Close()
return nil
}
pool.conns = append(pool.conns, conn)
return nil
} | [
"func",
"(",
"pool",
"*",
"hostConnPool",
")",
"connect",
"(",
")",
"(",
"err",
"error",
")",
"{",
"var",
"conn",
"*",
"Conn",
"\n",
"reconnectionPolicy",
":=",
"pool",
".",
"session",
".",
"cfg",
".",
"ReconnectionPolicy",
"\n",
"for",
"i",
":=",
"0",... | // create a new connection to the host and add it to the pool | [
"create",
"a",
"new",
"connection",
"to",
"the",
"host",
"and",
"add",
"it",
"to",
"the",
"pool"
] | b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac | https://github.com/gocql/gocql/blob/b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac/connectionpool.go#L502-L551 | train |
gocql/gocql | connectionpool.go | HandleError | func (pool *hostConnPool) HandleError(conn *Conn, err error, closed bool) {
if !closed {
// still an open connection, so continue using it
return
}
// TODO: track the number of errors per host and detect when a host is dead,
// then also have something which can detect when a host comes back.
pool.mu.Lock()
defer pool.mu.Unlock()
if pool.closed {
// pool closed
return
}
// find the connection index
for i, candidate := range pool.conns {
if candidate == conn {
// remove the connection, not preserving order
pool.conns[i], pool.conns = pool.conns[len(pool.conns)-1], pool.conns[:len(pool.conns)-1]
// lost a connection, so fill the pool
go pool.fill()
break
}
}
} | go | func (pool *hostConnPool) HandleError(conn *Conn, err error, closed bool) {
if !closed {
// still an open connection, so continue using it
return
}
// TODO: track the number of errors per host and detect when a host is dead,
// then also have something which can detect when a host comes back.
pool.mu.Lock()
defer pool.mu.Unlock()
if pool.closed {
// pool closed
return
}
// find the connection index
for i, candidate := range pool.conns {
if candidate == conn {
// remove the connection, not preserving order
pool.conns[i], pool.conns = pool.conns[len(pool.conns)-1], pool.conns[:len(pool.conns)-1]
// lost a connection, so fill the pool
go pool.fill()
break
}
}
} | [
"func",
"(",
"pool",
"*",
"hostConnPool",
")",
"HandleError",
"(",
"conn",
"*",
"Conn",
",",
"err",
"error",
",",
"closed",
"bool",
")",
"{",
"if",
"!",
"closed",
"{",
"return",
"\n",
"}",
"\n",
"pool",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"de... | // handle any error from a Conn | [
"handle",
"any",
"error",
"from",
"a",
"Conn"
] | b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac | https://github.com/gocql/gocql/blob/b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac/connectionpool.go#L554-L581 | train |
gocql/gocql | marshal.go | Marshal | func Marshal(info TypeInfo, value interface{}) ([]byte, error) {
if info.Version() < protoVersion1 {
panic("protocol version not set")
}
if valueRef := reflect.ValueOf(value); valueRef.Kind() == reflect.Ptr {
if valueRef.IsNil() {
return nil, nil
} else if v, ok := value.(Marshaler); ok {
return v.MarshalCQL(info)
} else {
return Marshal(info, valueRef.Elem().Interface())
}
}
if v, ok := value.(Marshaler); ok {
return v.MarshalCQL(info)
}
switch info.Type() {
case TypeVarchar, TypeAscii, TypeBlob, TypeText:
return marshalVarchar(info, value)
case TypeBoolean:
return marshalBool(info, value)
case TypeTinyInt:
return marshalTinyInt(info, value)
case TypeSmallInt:
return marshalSmallInt(info, value)
case TypeInt:
return marshalInt(info, value)
case TypeBigInt, TypeCounter:
return marshalBigInt(info, value)
case TypeFloat:
return marshalFloat(info, value)
case TypeDouble:
return marshalDouble(info, value)
case TypeDecimal:
return marshalDecimal(info, value)
case TypeTime:
return marshalTime(info, value)
case TypeTimestamp:
return marshalTimestamp(info, value)
case TypeList, TypeSet:
return marshalList(info, value)
case TypeMap:
return marshalMap(info, value)
case TypeUUID, TypeTimeUUID:
return marshalUUID(info, value)
case TypeVarint:
return marshalVarint(info, value)
case TypeInet:
return marshalInet(info, value)
case TypeTuple:
return marshalTuple(info, value)
case TypeUDT:
return marshalUDT(info, value)
case TypeDate:
return marshalDate(info, value)
case TypeDuration:
return marshalDuration(info, value)
}
// detect protocol 2 UDT
if strings.HasPrefix(info.Custom(), "org.apache.cassandra.db.marshal.UserType") && info.Version() < 3 {
return nil, ErrorUDTUnavailable
}
// TODO(tux21b): add the remaining types
return nil, fmt.Errorf("can not marshal %T into %s", value, info)
} | go | func Marshal(info TypeInfo, value interface{}) ([]byte, error) {
if info.Version() < protoVersion1 {
panic("protocol version not set")
}
if valueRef := reflect.ValueOf(value); valueRef.Kind() == reflect.Ptr {
if valueRef.IsNil() {
return nil, nil
} else if v, ok := value.(Marshaler); ok {
return v.MarshalCQL(info)
} else {
return Marshal(info, valueRef.Elem().Interface())
}
}
if v, ok := value.(Marshaler); ok {
return v.MarshalCQL(info)
}
switch info.Type() {
case TypeVarchar, TypeAscii, TypeBlob, TypeText:
return marshalVarchar(info, value)
case TypeBoolean:
return marshalBool(info, value)
case TypeTinyInt:
return marshalTinyInt(info, value)
case TypeSmallInt:
return marshalSmallInt(info, value)
case TypeInt:
return marshalInt(info, value)
case TypeBigInt, TypeCounter:
return marshalBigInt(info, value)
case TypeFloat:
return marshalFloat(info, value)
case TypeDouble:
return marshalDouble(info, value)
case TypeDecimal:
return marshalDecimal(info, value)
case TypeTime:
return marshalTime(info, value)
case TypeTimestamp:
return marshalTimestamp(info, value)
case TypeList, TypeSet:
return marshalList(info, value)
case TypeMap:
return marshalMap(info, value)
case TypeUUID, TypeTimeUUID:
return marshalUUID(info, value)
case TypeVarint:
return marshalVarint(info, value)
case TypeInet:
return marshalInet(info, value)
case TypeTuple:
return marshalTuple(info, value)
case TypeUDT:
return marshalUDT(info, value)
case TypeDate:
return marshalDate(info, value)
case TypeDuration:
return marshalDuration(info, value)
}
// detect protocol 2 UDT
if strings.HasPrefix(info.Custom(), "org.apache.cassandra.db.marshal.UserType") && info.Version() < 3 {
return nil, ErrorUDTUnavailable
}
// TODO(tux21b): add the remaining types
return nil, fmt.Errorf("can not marshal %T into %s", value, info)
} | [
"func",
"Marshal",
"(",
"info",
"TypeInfo",
",",
"value",
"interface",
"{",
"}",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"if",
"info",
".",
"Version",
"(",
")",
"<",
"protoVersion1",
"{",
"panic",
"(",
"\"protocol version not set\"",
")",
"... | // Marshal returns the CQL encoding of the value for the Cassandra
// internal type described by the info parameter. | [
"Marshal",
"returns",
"the",
"CQL",
"encoding",
"of",
"the",
"value",
"for",
"the",
"Cassandra",
"internal",
"type",
"described",
"by",
"the",
"info",
"parameter",
"."
] | b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac | https://github.com/gocql/gocql/blob/b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac/marshal.go#L47-L116 | train |
gocql/gocql | marshal.go | Unmarshal | func Unmarshal(info TypeInfo, data []byte, value interface{}) error {
if v, ok := value.(Unmarshaler); ok {
return v.UnmarshalCQL(info, data)
}
if isNullableValue(value) {
return unmarshalNullable(info, data, value)
}
switch info.Type() {
case TypeVarchar, TypeAscii, TypeBlob, TypeText:
return unmarshalVarchar(info, data, value)
case TypeBoolean:
return unmarshalBool(info, data, value)
case TypeInt:
return unmarshalInt(info, data, value)
case TypeBigInt, TypeCounter:
return unmarshalBigInt(info, data, value)
case TypeVarint:
return unmarshalVarint(info, data, value)
case TypeSmallInt:
return unmarshalSmallInt(info, data, value)
case TypeTinyInt:
return unmarshalTinyInt(info, data, value)
case TypeFloat:
return unmarshalFloat(info, data, value)
case TypeDouble:
return unmarshalDouble(info, data, value)
case TypeDecimal:
return unmarshalDecimal(info, data, value)
case TypeTime:
return unmarshalTime(info, data, value)
case TypeTimestamp:
return unmarshalTimestamp(info, data, value)
case TypeList, TypeSet:
return unmarshalList(info, data, value)
case TypeMap:
return unmarshalMap(info, data, value)
case TypeTimeUUID:
return unmarshalTimeUUID(info, data, value)
case TypeUUID:
return unmarshalUUID(info, data, value)
case TypeInet:
return unmarshalInet(info, data, value)
case TypeTuple:
return unmarshalTuple(info, data, value)
case TypeUDT:
return unmarshalUDT(info, data, value)
case TypeDate:
return unmarshalDate(info, data, value)
case TypeDuration:
return unmarshalDuration(info, data, value)
}
// detect protocol 2 UDT
if strings.HasPrefix(info.Custom(), "org.apache.cassandra.db.marshal.UserType") && info.Version() < 3 {
return ErrorUDTUnavailable
}
// TODO(tux21b): add the remaining types
return fmt.Errorf("can not unmarshal %s into %T", info, value)
} | go | func Unmarshal(info TypeInfo, data []byte, value interface{}) error {
if v, ok := value.(Unmarshaler); ok {
return v.UnmarshalCQL(info, data)
}
if isNullableValue(value) {
return unmarshalNullable(info, data, value)
}
switch info.Type() {
case TypeVarchar, TypeAscii, TypeBlob, TypeText:
return unmarshalVarchar(info, data, value)
case TypeBoolean:
return unmarshalBool(info, data, value)
case TypeInt:
return unmarshalInt(info, data, value)
case TypeBigInt, TypeCounter:
return unmarshalBigInt(info, data, value)
case TypeVarint:
return unmarshalVarint(info, data, value)
case TypeSmallInt:
return unmarshalSmallInt(info, data, value)
case TypeTinyInt:
return unmarshalTinyInt(info, data, value)
case TypeFloat:
return unmarshalFloat(info, data, value)
case TypeDouble:
return unmarshalDouble(info, data, value)
case TypeDecimal:
return unmarshalDecimal(info, data, value)
case TypeTime:
return unmarshalTime(info, data, value)
case TypeTimestamp:
return unmarshalTimestamp(info, data, value)
case TypeList, TypeSet:
return unmarshalList(info, data, value)
case TypeMap:
return unmarshalMap(info, data, value)
case TypeTimeUUID:
return unmarshalTimeUUID(info, data, value)
case TypeUUID:
return unmarshalUUID(info, data, value)
case TypeInet:
return unmarshalInet(info, data, value)
case TypeTuple:
return unmarshalTuple(info, data, value)
case TypeUDT:
return unmarshalUDT(info, data, value)
case TypeDate:
return unmarshalDate(info, data, value)
case TypeDuration:
return unmarshalDuration(info, data, value)
}
// detect protocol 2 UDT
if strings.HasPrefix(info.Custom(), "org.apache.cassandra.db.marshal.UserType") && info.Version() < 3 {
return ErrorUDTUnavailable
}
// TODO(tux21b): add the remaining types
return fmt.Errorf("can not unmarshal %s into %T", info, value)
} | [
"func",
"Unmarshal",
"(",
"info",
"TypeInfo",
",",
"data",
"[",
"]",
"byte",
",",
"value",
"interface",
"{",
"}",
")",
"error",
"{",
"if",
"v",
",",
"ok",
":=",
"value",
".",
"(",
"Unmarshaler",
")",
";",
"ok",
"{",
"return",
"v",
".",
"UnmarshalCQ... | // Unmarshal parses the CQL encoded data based on the info parameter that
// describes the Cassandra internal data type and stores the result in the
// value pointed by value. | [
"Unmarshal",
"parses",
"the",
"CQL",
"encoded",
"data",
"based",
"on",
"the",
"info",
"parameter",
"that",
"describes",
"the",
"Cassandra",
"internal",
"data",
"type",
"and",
"stores",
"the",
"result",
"in",
"the",
"value",
"pointed",
"by",
"value",
"."
] | b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac | https://github.com/gocql/gocql/blob/b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac/marshal.go#L121-L182 | train |
gocql/gocql | marshal.go | encBigInt2C | func encBigInt2C(n *big.Int) []byte {
switch n.Sign() {
case 0:
return []byte{0}
case 1:
b := n.Bytes()
if b[0]&0x80 > 0 {
b = append([]byte{0}, b...)
}
return b
case -1:
length := uint(n.BitLen()/8+1) * 8
b := new(big.Int).Add(n, new(big.Int).Lsh(bigOne, length)).Bytes()
// When the most significant bit is on a byte
// boundary, we can get some extra significant
// bits, so strip them off when that happens.
if len(b) >= 2 && b[0] == 0xff && b[1]&0x80 != 0 {
b = b[1:]
}
return b
}
return nil
} | go | func encBigInt2C(n *big.Int) []byte {
switch n.Sign() {
case 0:
return []byte{0}
case 1:
b := n.Bytes()
if b[0]&0x80 > 0 {
b = append([]byte{0}, b...)
}
return b
case -1:
length := uint(n.BitLen()/8+1) * 8
b := new(big.Int).Add(n, new(big.Int).Lsh(bigOne, length)).Bytes()
// When the most significant bit is on a byte
// boundary, we can get some extra significant
// bits, so strip them off when that happens.
if len(b) >= 2 && b[0] == 0xff && b[1]&0x80 != 0 {
b = b[1:]
}
return b
}
return nil
} | [
"func",
"encBigInt2C",
"(",
"n",
"*",
"big",
".",
"Int",
")",
"[",
"]",
"byte",
"{",
"switch",
"n",
".",
"Sign",
"(",
")",
"{",
"case",
"0",
":",
"return",
"[",
"]",
"byte",
"{",
"0",
"}",
"\n",
"case",
"1",
":",
"b",
":=",
"n",
".",
"Bytes... | // encBigInt2C returns the big-endian two's complement
// form of n. | [
"encBigInt2C",
"returns",
"the",
"big",
"-",
"endian",
"two",
"s",
"complement",
"form",
"of",
"n",
"."
] | b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac | https://github.com/gocql/gocql/blob/b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac/marshal.go#L1073-L1095 | train |
gocql/gocql | marshal.go | unmarshalTuple | func unmarshalTuple(info TypeInfo, data []byte, value interface{}) error {
if v, ok := value.(Unmarshaler); ok {
return v.UnmarshalCQL(info, data)
}
tuple := info.(TupleTypeInfo)
switch v := value.(type) {
case []interface{}:
for i, elem := range tuple.Elems {
// each element inside data is a [bytes]
var p []byte
p, data = readBytes(data)
err := Unmarshal(elem, p, v[i])
if err != nil {
return err
}
}
return nil
}
rv := reflect.ValueOf(value)
if rv.Kind() != reflect.Ptr {
return unmarshalErrorf("can not unmarshal into non-pointer %T", value)
}
rv = rv.Elem()
t := rv.Type()
k := t.Kind()
switch k {
case reflect.Struct:
if v := t.NumField(); v != len(tuple.Elems) {
return unmarshalErrorf("can not unmarshal tuple into struct %v, not enough fields have %d need %d", t, v, len(tuple.Elems))
}
for i, elem := range tuple.Elems {
m := readInt(data)
data = data[4:]
v := elem.New()
if err := Unmarshal(elem, data[:m], v); err != nil {
return err
}
rv.Field(i).Set(reflect.ValueOf(v).Elem())
data = data[m:]
}
return nil
case reflect.Slice, reflect.Array:
if k == reflect.Array {
size := rv.Len()
if size != len(tuple.Elems) {
return unmarshalErrorf("can not unmarshal tuple into array of length %d need %d elements", size, len(tuple.Elems))
}
} else {
rv.Set(reflect.MakeSlice(t, len(tuple.Elems), len(tuple.Elems)))
}
for i, elem := range tuple.Elems {
m := readInt(data)
data = data[4:]
v := elem.New()
if err := Unmarshal(elem, data[:m], v); err != nil {
return err
}
rv.Index(i).Set(reflect.ValueOf(v).Elem())
data = data[m:]
}
return nil
}
return unmarshalErrorf("cannot unmarshal %s into %T", info, value)
} | go | func unmarshalTuple(info TypeInfo, data []byte, value interface{}) error {
if v, ok := value.(Unmarshaler); ok {
return v.UnmarshalCQL(info, data)
}
tuple := info.(TupleTypeInfo)
switch v := value.(type) {
case []interface{}:
for i, elem := range tuple.Elems {
// each element inside data is a [bytes]
var p []byte
p, data = readBytes(data)
err := Unmarshal(elem, p, v[i])
if err != nil {
return err
}
}
return nil
}
rv := reflect.ValueOf(value)
if rv.Kind() != reflect.Ptr {
return unmarshalErrorf("can not unmarshal into non-pointer %T", value)
}
rv = rv.Elem()
t := rv.Type()
k := t.Kind()
switch k {
case reflect.Struct:
if v := t.NumField(); v != len(tuple.Elems) {
return unmarshalErrorf("can not unmarshal tuple into struct %v, not enough fields have %d need %d", t, v, len(tuple.Elems))
}
for i, elem := range tuple.Elems {
m := readInt(data)
data = data[4:]
v := elem.New()
if err := Unmarshal(elem, data[:m], v); err != nil {
return err
}
rv.Field(i).Set(reflect.ValueOf(v).Elem())
data = data[m:]
}
return nil
case reflect.Slice, reflect.Array:
if k == reflect.Array {
size := rv.Len()
if size != len(tuple.Elems) {
return unmarshalErrorf("can not unmarshal tuple into array of length %d need %d elements", size, len(tuple.Elems))
}
} else {
rv.Set(reflect.MakeSlice(t, len(tuple.Elems), len(tuple.Elems)))
}
for i, elem := range tuple.Elems {
m := readInt(data)
data = data[4:]
v := elem.New()
if err := Unmarshal(elem, data[:m], v); err != nil {
return err
}
rv.Index(i).Set(reflect.ValueOf(v).Elem())
data = data[m:]
}
return nil
}
return unmarshalErrorf("cannot unmarshal %s into %T", info, value)
} | [
"func",
"unmarshalTuple",
"(",
"info",
"TypeInfo",
",",
"data",
"[",
"]",
"byte",
",",
"value",
"interface",
"{",
"}",
")",
"error",
"{",
"if",
"v",
",",
"ok",
":=",
"value",
".",
"(",
"Unmarshaler",
")",
";",
"ok",
"{",
"return",
"v",
".",
"Unmars... | // currently only support unmarshal into a list of values, this makes it possible
// to support tuples without changing the query API. In the future this can be extend
// to allow unmarshalling into custom tuple types. | [
"currently",
"only",
"support",
"unmarshal",
"into",
"a",
"list",
"of",
"values",
"this",
"makes",
"it",
"possible",
"to",
"support",
"tuples",
"without",
"changing",
"the",
"query",
"API",
".",
"In",
"the",
"future",
"this",
"can",
"be",
"extend",
"to",
"... | b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac | https://github.com/gocql/gocql/blob/b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac/marshal.go#L1867-L1945 | train |
gocql/gocql | marshal.go | String | func (t Type) String() string {
switch t {
case TypeCustom:
return "custom"
case TypeAscii:
return "ascii"
case TypeBigInt:
return "bigint"
case TypeBlob:
return "blob"
case TypeBoolean:
return "boolean"
case TypeCounter:
return "counter"
case TypeDecimal:
return "decimal"
case TypeDouble:
return "double"
case TypeFloat:
return "float"
case TypeInt:
return "int"
case TypeText:
return "text"
case TypeTimestamp:
return "timestamp"
case TypeUUID:
return "uuid"
case TypeVarchar:
return "varchar"
case TypeTimeUUID:
return "timeuuid"
case TypeInet:
return "inet"
case TypeDate:
return "date"
case TypeDuration:
return "duration"
case TypeTime:
return "time"
case TypeSmallInt:
return "smallint"
case TypeTinyInt:
return "tinyint"
case TypeList:
return "list"
case TypeMap:
return "map"
case TypeSet:
return "set"
case TypeVarint:
return "varint"
case TypeTuple:
return "tuple"
default:
return fmt.Sprintf("unknown_type_%d", t)
}
} | go | func (t Type) String() string {
switch t {
case TypeCustom:
return "custom"
case TypeAscii:
return "ascii"
case TypeBigInt:
return "bigint"
case TypeBlob:
return "blob"
case TypeBoolean:
return "boolean"
case TypeCounter:
return "counter"
case TypeDecimal:
return "decimal"
case TypeDouble:
return "double"
case TypeFloat:
return "float"
case TypeInt:
return "int"
case TypeText:
return "text"
case TypeTimestamp:
return "timestamp"
case TypeUUID:
return "uuid"
case TypeVarchar:
return "varchar"
case TypeTimeUUID:
return "timeuuid"
case TypeInet:
return "inet"
case TypeDate:
return "date"
case TypeDuration:
return "duration"
case TypeTime:
return "time"
case TypeSmallInt:
return "smallint"
case TypeTinyInt:
return "tinyint"
case TypeList:
return "list"
case TypeMap:
return "map"
case TypeSet:
return "set"
case TypeVarint:
return "varint"
case TypeTuple:
return "tuple"
default:
return fmt.Sprintf("unknown_type_%d", t)
}
} | [
"func",
"(",
"t",
"Type",
")",
"String",
"(",
")",
"string",
"{",
"switch",
"t",
"{",
"case",
"TypeCustom",
":",
"return",
"\"custom\"",
"\n",
"case",
"TypeAscii",
":",
"return",
"\"ascii\"",
"\n",
"case",
"TypeBigInt",
":",
"return",
"\"bigint\"",
"\n",
... | // String returns the name of the identifier. | [
"String",
"returns",
"the",
"name",
"of",
"the",
"identifier",
"."
] | b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac | https://github.com/gocql/gocql/blob/b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac/marshal.go#L2326-L2383 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.