repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
list
docstring
stringlengths
6
2.61k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
85
252
partition
stringclasses
1 value
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", "!=", "\"", "\"", "{", "return", "func", "(", "c", "*", "gin", ".", "Context", ")", "{", "// Simulate behavior when route unspecified and", "// return 404 HTTP code", "c", ".", "String", "(", "404", ",", "\"", "\"", ")", "\n", "}", "\n", "}", "\n\n", "return", "CustomWrapHandler", "(", "config", ",", "h", ")", "\n", "}" ]
// 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", "}", ")", "\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", "{", "// dont want to panic here, but rather not break the API", "panic", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", ")", "\n", "}", "\n\n", "m", ":=", "make", "(", "map", "[", "string", "]", "bool", ",", "len", "(", "hostInfos", ")", ")", "\n", "for", "_", ",", "host", ":=", "range", "hostInfos", "{", "m", "[", "host", ".", "ConnectAddress", "(", ")", ".", "String", "(", ")", "]", "=", "true", "\n", "}", "\n\n", "return", "HostFilterFunc", "(", "func", "(", "host", "*", "HostInfo", ")", "bool", "{", "return", "m", "[", "host", ".", "ConnectAddress", "(", ")", ".", "String", "(", ")", "]", "\n", "}", ")", "\n", "}" ]
// 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", "(", "\"", "\"", ",", "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", "to", "be", "extracted", "from", "a", "map", "returned", "from", "SliceMap", "or", "MapScan", "." ]
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", ":", "\"", "\"", ",", "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", ",", "}", "\n", "return", "cfg", "\n", "}" ]
// 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", "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", "." ]
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", ")", "==", "0", "{", "return", "addr", ",", "port", "\n", "}", "\n", "newAddr", ",", "newPort", ":=", "cfg", ".", "AddressTranslator", ".", "Translate", "(", "addr", ",", "port", ")", "\n", "if", "gocqlDebug", "{", "Logger", ".", "Printf", "(", "\"", "\"", ",", "addr", ",", "port", ",", "newAddr", ",", "newPort", ")", "\n", "}", "\n", "return", "newAddr", ",", "newPort", "\n", "}" ]
// 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", "AddressTranslator", "or", "if", "an", "error", "occurs", "the", "given", "address", "and", "port", "will", "be", "returned", "." ]
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", ")", ")", ")", "\n", "return", "\n", "}" ]
// 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", "(", "\"", "\"", ",", "head", ".", "length", ")", "\n", "}", "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", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "return", "ErrFrameTooBig", "\n", "}", "\n\n", "if", "cap", "(", "f", ".", "readBuffer", ")", ">=", "head", ".", "length", "{", "f", ".", "rbuf", "=", "f", ".", "readBuffer", "[", ":", "head", ".", "length", "]", "\n", "}", "else", "{", "f", ".", "readBuffer", "=", "make", "(", "[", "]", "byte", ",", "head", ".", "length", ")", "\n", "f", ".", "rbuf", "=", "f", ".", "readBuffer", "\n", "}", "\n\n", "// assume the underlying reader takes care of timeouts and retries", "n", ",", "err", ":=", "io", ".", "ReadFull", "(", "f", ".", "r", ",", "f", ".", "rbuf", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "n", ",", "head", ".", "length", ",", "err", ")", "\n", "}", "\n\n", "if", "head", ".", "flags", "&", "flagCompress", "==", "flagCompress", "{", "if", "f", ".", "compres", "==", "nil", "{", "return", "NewErrProtocol", "(", "\"", "\"", ")", "\n", "}", "\n\n", "f", ".", "rbuf", ",", "err", "=", "f", ".", "compres", ".", "Decode", "(", "f", ".", "rbuf", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "f", ".", "header", "=", "head", "\n", "return", "nil", "\n", "}" ]
// 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", "...", ")", ".", "Consistency", "(", "One", ")", ".", "RoutingKey", "(", "[", "]", "byte", "{", "}", ")", ".", "Trace", "(", "nil", ")", "\n\n", "for", "{", "iter", "=", "c", ".", "withConn", "(", "func", "(", "conn", "*", "Conn", ")", "*", "Iter", "{", "return", "conn", ".", "executeQuery", "(", "context", ".", "TODO", "(", ")", ",", "q", ")", "\n", "}", ")", "\n\n", "if", "gocqlDebug", "&&", "iter", ".", "err", "!=", "nil", "{", "Logger", ".", "Printf", "(", "\"", "\\n", "\"", ",", "statement", ",", "iter", ".", "err", ")", "\n", "}", "\n\n", "q", ".", "AddAttempts", "(", "1", ",", "c", ".", "getConn", "(", ")", ".", "host", ")", "\n", "if", "iter", ".", "err", "==", "nil", "||", "!", "c", ".", "retry", ".", "Attempt", "(", "q", ")", "{", "break", "\n", "}", "\n", "}", "\n\n", "return", "\n", "}" ]
// 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", ")", "{", "// Check that hosts in the ClusterConfig is not empty", "if", "len", "(", "cfg", ".", "Hosts", ")", "<", "1", "{", "return", "nil", ",", "ErrNoHosts", "\n", "}", "\n\n", "// Check that either Authenticator is set or AuthProvider, not both", "if", "cfg", ".", "Authenticator", "!=", "nil", "&&", "cfg", ".", "AuthProvider", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "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", ",", "}", "\n\n", "s", ".", "schemaDescriber", "=", "newSchemaDescriber", "(", "s", ")", "\n\n", "s", ".", "nodeEvents", "=", "newEventDebouncer", "(", "\"", "\"", ",", "s", ".", "handleNodeEvent", ")", "\n", "s", ".", "schemaEvents", "=", "newEventDebouncer", "(", "\"", "\"", ",", "s", ".", "handleSchemaEvent", ")", "\n\n", "s", ".", "routingKeyInfoCache", ".", "lru", "=", "lru", ".", "New", "(", "cfg", ".", "MaxRoutingKeyInfo", ")", "\n\n", "s", ".", "hostSource", "=", "&", "ringDescriber", "{", "session", ":", "s", "}", "\n\n", "if", "cfg", ".", "PoolConfig", ".", "HostSelectionPolicy", "==", "nil", "{", "cfg", ".", "PoolConfig", ".", "HostSelectionPolicy", "=", "RoundRobinHostPolicy", "(", ")", "\n", "}", "\n", "s", ".", "pool", "=", "cfg", ".", "PoolConfig", ".", "buildPool", "(", "s", ")", "\n\n", "s", ".", "policy", "=", "cfg", ".", "PoolConfig", ".", "HostSelectionPolicy", "\n", "s", ".", "policy", ".", "Init", "(", "s", ")", "\n\n", "s", ".", "executor", "=", "&", "queryExecutor", "{", "pool", ":", "s", ".", "pool", ",", "policy", ":", "cfg", ".", "PoolConfig", ".", "HostSelectionPolicy", ",", "}", "\n\n", "s", ".", "queryObserver", "=", "cfg", ".", "QueryObserver", "\n", "s", ".", "batchObserver", "=", "cfg", ".", "BatchObserver", "\n", "s", ".", "connectObserver", "=", "cfg", ".", "ConnectObserver", "\n", "s", ".", "frameObserver", "=", "cfg", ".", "FrameHeaderObserver", "\n\n", "//Check the TLS Config before trying to connect to anything external", "connCfg", ",", "err", ":=", "connConfig", "(", "&", "s", ".", "cfg", ")", "\n", "if", "err", "!=", "nil", "{", "//TODO: Return a typed error", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "s", ".", "connCfg", "=", "connCfg", "\n\n", "if", "err", ":=", "s", ".", "init", "(", ")", ";", "err", "!=", "nil", "{", "s", ".", "Close", "(", ")", "\n", "if", "err", "==", "ErrNoConnectionsStarted", "{", "//This error used to be generated inside NewSession & returned directly", "//Forward it on up to be backwards compatible", "return", "nil", ",", "ErrNoConnectionsStarted", "\n", "}", "else", "{", "// TODO(zariel): dont wrap this error in fmt.Errorf, return a typed error", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "\n\n", "return", "s", ",", "nil", "\n", "}" ]
// 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", "=", "s", "\n", "qry", ".", "stmt", "=", "stmt", "\n", "qry", ".", "values", "=", "values", "\n", "qry", ".", "defaultsFromSession", "(", ")", "\n", "return", "qry", "\n", "}" ]
// 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", "executed", ".", "Query", "is", "automatically", "prepared", "if", "it", "has", "not", "previously", "been", "executed", "." ]
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", "(", ")", ".", "(", "*", "Query", ")", "\n", "qry", ".", "session", "=", "s", "\n", "qry", ".", "stmt", "=", "stmt", "\n", "qry", ".", "binding", "=", "b", "\n", "qry", ".", "defaultsFromSession", "(", ")", "\n", "return", "qry", "\n", "}" ]
// 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", "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", "." ]
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", ".", "isClosed", "=", "true", "\n\n", "if", "s", ".", "pool", "!=", "nil", "{", "s", ".", "pool", ".", "Close", "(", ")", "\n", "}", "\n\n", "if", "s", ".", "control", "!=", "nil", "{", "s", ".", "control", ".", "close", "(", ")", "\n", "}", "\n\n", "if", "s", ".", "nodeEvents", "!=", "nil", "{", "s", ".", "nodeEvents", ".", "stop", "(", ")", "\n", "}", "\n\n", "if", "s", ".", "schemaEvents", "!=", "nil", "{", "s", ".", "schemaEvents", ".", "stop", "(", ")", "\n", "}", "\n\n", "if", "s", ".", "quit", "!=", "nil", "{", "close", "(", "s", ".", "quit", ")", "\n", "}", "\n", "}" ]
// 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", ")", "{", "// fail fast", "if", "s", ".", "Closed", "(", ")", "{", "return", "nil", ",", "ErrSessionClosed", "\n", "}", "else", "if", "keyspace", "==", "\"", "\"", "{", "return", "nil", ",", "ErrNoKeyspace", "\n", "}", "\n\n", "return", "s", ".", "schemaDescriber", ".", "getSchema", "(", "keyspace", ")", "\n", "}" ]
// 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", "=", "s", ".", "executeBatch", "(", "batch", ")", "\n", "if", "err", ":=", "iter", ".", "checkErrAndNotFound", "(", ")", ";", "err", "!=", "nil", "{", "iter", ".", "Close", "(", ")", "\n", "return", "false", ",", "nil", ",", "err", "\n", "}", "\n", "iter", ".", "MapScan", "(", "dest", ")", "\n", "applied", "=", "dest", "[", "\"", "\"", "]", ".", "(", "bool", ")", "\n", "delete", "(", "dest", ",", "\"", "\"", ")", "\n\n", "// 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", "\n", "}" ]
// 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", "+=", "metric", ".", "Attempts", "\n", "}", "\n", "q", ".", "metrics", ".", "l", ".", "Unlock", "(", ")", "\n", "return", "attempts", "\n", "}" ]
//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", ".", "metrics", ".", "m", "{", "attempts", "+=", "metric", ".", "Attempts", "\n", "latency", "+=", "metric", ".", "TotalLatency", "\n", "}", "\n", "q", ".", "metrics", ".", "l", ".", "Unlock", "(", ")", "\n", "if", "attempts", ">", "0", "{", "return", "latency", "/", "int64", "(", "attempts", ")", "\n", "}", "\n", "return", "0", "\n", "}" ]
//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", "// TODO(chbannis): this should be parsed from the query or we should let", "// this be set by users.", "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", ".", "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", "\n", "}", "\n\n", "// try to determine the routing key", "routingKeyInfo", ",", "err", ":=", "q", ".", "session", ".", "routingKeyInfo", "(", "q", ".", "Context", "(", ")", ",", "q", ".", "stmt", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "routingKeyInfo", "==", "nil", "{", "return", "nil", ",", "nil", "\n", "}", "\n\n", "if", "len", "(", "routingKeyInfo", ".", "indexes", ")", "==", "1", "{", "// single column routing key", "routingKey", ",", "err", ":=", "Marshal", "(", "routingKeyInfo", ".", "types", "[", "0", "]", ",", "q", ".", "values", "[", "routingKeyInfo", ".", "indexes", "[", "0", "]", "]", ",", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "routingKey", ",", "nil", "\n", "}", "\n\n", "// 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", ")", "\n", "}", "\n\n", "// composite routing key", "buf", ":=", "bytes", ".", "NewBuffer", "(", "q", ".", "routingKeyBuffer", ")", "\n", "for", "i", ":=", "range", "routingKeyInfo", ".", "indexes", "{", "encoded", ",", "err", ":=", "Marshal", "(", "routingKeyInfo", ".", "types", "[", "i", "]", ",", "q", ".", "values", "[", "routingKeyInfo", ".", "indexes", "[", "i", "]", "]", ",", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "lenBuf", ":=", "[", "]", "byte", "{", "0x00", ",", "0x00", "}", "\n", "binary", ".", "BigEndian", ".", "PutUint16", "(", "lenBuf", ",", "uint16", "(", "len", "(", "encoded", ")", ")", ")", "\n", "buf", ".", "Write", "(", "lenBuf", ")", "\n", "buf", ".", "Write", "(", "encoded", ")", "\n", "buf", ".", "WriteByte", "(", "0x00", ")", "\n", "}", "\n", "routingKey", ":=", "buf", ".", "Bytes", "(", ")", "\n", "return", "routingKey", ",", "nil", "\n", "}" ]
// 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", "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", "." ]
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", ".", "executeQuery", "(", "q", ")", "\n", "}" ]
// 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", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "iter", ".", "MapScan", "(", "m", ")", "\n", "return", "iter", ".", "Close", "(", ")", "\n", "}" ]
// 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", "returned", "." ]
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", "{", "return", "err", "\n", "}", "\n", "iter", ".", "Scan", "(", "dest", "...", ")", "\n", "return", "iter", ".", "Close", "(", ")", "\n", "}" ]
// 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", "is", "returned", "." ]
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\n", "if", "iter", ".", "pos", ">=", "iter", ".", "numRows", "{", "if", "iter", ".", "next", "!=", "nil", "{", "*", "iter", "=", "*", "iter", ".", "next", ".", "fetch", "(", ")", "\n", "return", "iter", ".", "Scan", "(", "dest", "...", ")", "\n", "}", "\n", "return", "false", "\n", "}", "\n\n", "if", "iter", ".", "next", "!=", "nil", "&&", "iter", ".", "pos", ">=", "iter", ".", "next", ".", "pos", "{", "go", "iter", ".", "next", ".", "fetch", "(", ")", "\n", "}", "\n\n", "// 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", "(", "\"", "\"", ",", "len", "(", "dest", ")", ",", "iter", ".", "meta", ".", "actualColCount", ")", "\n", "return", "false", "\n", "}", "\n\n", "// i is the current position in dest, could posible replace it and just use", "// slices of dest", "i", ":=", "0", "\n", "for", "_", ",", "col", ":=", "range", "iter", ".", "meta", ".", "columns", "{", "colBytes", ",", "err", ":=", "iter", ".", "readColumn", "(", ")", "\n", "if", "err", "!=", "nil", "{", "iter", ".", "err", "=", "err", "\n", "return", "false", "\n", "}", "\n\n", "n", ",", "err", ":=", "scanColumn", "(", "colBytes", ",", "col", ",", "dest", "[", "i", ":", "]", ")", "\n", "if", "err", "!=", "nil", "{", "iter", ".", "err", "=", "err", "\n", "return", "false", "\n", "}", "\n", "i", "+=", "n", "\n", "}", "\n\n", "iter", ".", "pos", "++", "\n", "return", "true", "\n", "}" ]
// 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", "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", "." ]
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", ".", "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", "{", "}", ",", "}", "\n\n", "s", ".", "mu", ".", "RUnlock", "(", ")", "\n", "return", "batch", "\n", "}" ]
// 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\n", "var", "attempts", "int", "\n", "for", "_", ",", "metric", ":=", "range", "b", ".", "metrics", ".", "m", "{", "attempts", "+=", "metric", ".", "Attempts", "\n", "}", "\n", "return", "attempts", "\n", "}" ]
// 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\n", "var", "(", "attempts", "int", "\n", "latency", "int64", "\n", ")", "\n", "for", "_", ",", "metric", ":=", "range", "b", ".", "metrics", ".", "m", "{", "attempts", "+=", "metric", ".", "Attempts", "\n", "latency", "+=", "metric", ".", "TotalLatency", "\n", "}", "\n", "if", "attempts", ">", "0", "{", "return", "latency", "/", "int64", "(", "attempts", ")", "\n", "}", "\n", "return", "0", "\n", "}" ]
//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", ":", "args", "}", ")", "\n", "}" ]
// 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", ".", "Entries", ",", "BatchEntry", "{", "Stmt", ":", "stmt", ",", "binding", ":", "bind", "}", ")", "\n", "}" ]
// 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", "application", "to", "define", "which", "query", "argument", "values", "will", "be", "marshalled", "as", "part", "of", "the", "batch", "execution", "." ]
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", "return", "once", "the", "context", "is", "canceled", "." ]
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", "(", "\"", "\"", ")", "\n", "if", "err", ":=", "iter", ".", "err", ";", "err", "!=", "nil", "{", "if", "errf", ",", "ok", ":=", "err", ".", "(", "*", "errorFrame", ")", ";", "ok", "{", "if", "errf", ".", "code", "==", "errSyntax", "{", "return", "false", ",", "nil", "\n", "}", "\n", "}", "\n\n", "return", "false", ",", "err", "\n", "}", "\n\n", "return", "true", ",", "nil", "\n", "}" ]
// 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", ".", "withConnHost", "(", "func", "(", "ch", "*", "connHost", ")", "*", "Iter", "{", "hosts", "=", "append", "(", "hosts", ",", "ch", ".", "host", ")", "\n", "return", "ch", ".", "conn", ".", "query", "(", "context", ".", "TODO", "(", ")", ",", "\"", "\"", ")", "\n", "}", ")", "\n\n", "if", "iter", "==", "nil", "{", "return", "nil", ",", "errNoControl", "\n", "}", "\n\n", "rows", ",", "err", ":=", "iter", ".", "SliceMap", "(", ")", "\n", "if", "err", "!=", "nil", "{", "// TODO(zariel): make typed error", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "for", "_", ",", "row", ":=", "range", "rows", "{", "// extract all available info about the peer", "host", ",", "err", ":=", "r", ".", "session", ".", "hostInfoFromMap", "(", "row", ",", "r", ".", "session", ".", "cfg", ".", "Port", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "else", "if", "!", "isValidPeer", "(", "host", ")", "{", "// If it's not a valid peer", "Logger", ".", "Printf", "(", "\"", "\"", "+", "\"", "\"", ",", "host", ")", "\n", "continue", "\n", "}", "\n\n", "hosts", "=", "append", "(", "hosts", ",", "host", ")", "\n", "}", "\n\n", "return", "hosts", ",", "nil", "\n", "}" ]
// 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", "==", "\"", "\"", "||", "host", ".", "rack", "==", "\"", "\"", "||", "len", "(", "host", ".", "tokens", ")", "==", "0", ")", "\n", "}" ]
// 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\n", "hosts", ",", "err", ":=", "r", ".", "getClusterPeerInfo", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "r", ".", "prevHosts", ",", "r", ".", "prevPartitioner", ",", "err", "\n", "}", "\n\n", "var", "partitioner", "string", "\n", "if", "len", "(", "hosts", ")", ">", "0", "{", "partitioner", "=", "hosts", "[", "0", "]", ".", "Partitioner", "(", ")", "\n", "}", "\n\n", "return", "hosts", ",", "partitioner", ",", "nil", "\n", "}" ]
// 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", "!=", "nil", "{", "addr", "=", "net", ".", "JoinHostPort", "(", "addr", ",", "strconv", ".", "Itoa", "(", "port", ")", ")", "\n", "}", "\n", "return", "addr", "\n", "}" ]
//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", ",", "errorHandler", ")", "\n", "}" ]
// 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", ".", "connectObserver", "!=", "nil", "{", "obs", ".", "Host", "=", "host", "\n", "obs", ".", "Start", "=", "time", ".", "Now", "(", ")", "\n", "}", "\n\n", "conn", ",", "err", ":=", "s", ".", "dialWithoutObserver", "(", "host", ",", "connConfig", ",", "errorHandler", ")", "\n\n", "if", "s", ".", "connectObserver", "!=", "nil", "{", "obs", ".", "End", "=", "time", ".", "Now", "(", ")", "\n", "obs", ".", "Err", "=", "err", "\n", "s", ".", "connectObserver", ".", "ObserveConnect", "(", "obs", ")", "\n", "}", "\n\n", "return", "conn", ",", "err", "\n", "}" ]
// 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\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", "usually", "called", "in", "a", "separate", "goroutine", "." ]
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\n", "// 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", ")", "\n", "e", ".", "events", "=", "make", "(", "[", "]", "frame", ",", "0", ",", "eventBufferSize", ")", "\n", "}" ]
// 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", "(", "\"", "\"", ")", "\n", "}", "\n\n", "copy", "(", "u", "[", ":", "]", ",", "input", ")", "\n", "return", "u", ",", "nil", "\n", "}" ]
// 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", "VariantIETF", "\n", "}", "\n", "if", "x", "&", "0x20", "==", "0", "{", "return", "VariantMicrosoft", "\n", "}", "\n", "return", "VariantFuture", "\n", "}" ]
// 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", ":=", "t", "/", "1e7", "\n", "nsec", ":=", "(", "t", "%", "1e7", ")", "*", "100", "\n", "return", "time", ".", "Unix", "(", "sec", "+", "timeBase", ",", "nsec", ")", ".", "UTC", "(", ")", "\n", "}" ]
// 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", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "str", ")", "\n", "}", "\n\n", "parsed", ",", "err", ":=", "ParseUUID", "(", "str", ")", "\n", "if", "err", "==", "nil", "{", "copy", "(", "u", "[", ":", "]", ",", "parsed", "[", ":", "]", ")", "\n", "}", "\n\n", "return", "err", "\n", "}" ]
// 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\n", "metadata", ",", "found", ":=", "s", ".", "cache", "[", "keyspaceName", "]", "\n", "if", "!", "found", "{", "// refresh the cache for this keyspace", "err", ":=", "s", ".", "refreshSchema", "(", "keyspaceName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "metadata", "=", "s", ".", "cache", "[", "keyspaceName", "]", "\n", "}", "\n\n", "return", "metadata", ",", "nil", "\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\n", "delete", "(", "s", ".", "cache", ",", "keyspaceName", ")", "\n", "}" ]
// 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\n", "// query the system keyspace for schema data", "// TODO retrieve concurrently", "keyspace", ",", "err", ":=", "getKeyspaceMetadata", "(", "s", ".", "session", ",", "keyspaceName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "tables", ",", "err", ":=", "getTableMetadata", "(", "s", ".", "session", ",", "keyspaceName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "columns", ",", "err", ":=", "getColumnMetadata", "(", "s", ".", "session", ",", "keyspaceName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "functions", ",", "err", ":=", "getFunctionsMetadata", "(", "s", ".", "session", ",", "keyspaceName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "aggregates", ",", "err", ":=", "getAggregatesMetadata", "(", "s", ".", "session", ",", "keyspaceName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "views", ",", "err", ":=", "getViewsMetadata", "(", "s", ".", "session", ",", "keyspaceName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// organize the schema data", "compileMetadata", "(", "s", ".", "session", ".", "cfg", ".", "ProtoVersion", ",", "keyspace", ",", "tables", ",", "columns", ",", "functions", ",", "aggregates", ",", "views", ")", "\n\n", "// update the cache", "s", ".", "cache", "[", "keyspaceName", "]", "=", "keyspace", "\n\n", "return", "nil", "\n", "}" ]
// 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", "[", "]", "AggregateMetadata", ",", "views", "[", "]", "ViewMetadata", ",", ")", "{", "keyspace", ".", "Tables", "=", "make", "(", "map", "[", "string", "]", "*", "TableMetadata", ")", "\n", "for", "i", ":=", "range", "tables", "{", "tables", "[", "i", "]", ".", "Columns", "=", "make", "(", "map", "[", "string", "]", "*", "ColumnMetadata", ")", "\n\n", "keyspace", ".", "Tables", "[", "tables", "[", "i", "]", ".", "Name", "]", "=", "&", "tables", "[", "i", "]", "\n", "}", "\n", "keyspace", ".", "Functions", "=", "make", "(", "map", "[", "string", "]", "*", "FunctionMetadata", ",", "len", "(", "functions", ")", ")", "\n", "for", "i", ":=", "range", "functions", "{", "keyspace", ".", "Functions", "[", "functions", "[", "i", "]", ".", "Name", "]", "=", "&", "functions", "[", "i", "]", "\n", "}", "\n", "keyspace", ".", "Aggregates", "=", "make", "(", "map", "[", "string", "]", "*", "AggregateMetadata", ",", "len", "(", "aggregates", ")", ")", "\n", "for", "_", ",", "aggregate", ":=", "range", "aggregates", "{", "aggregate", ".", "FinalFunc", "=", "*", "keyspace", ".", "Functions", "[", "aggregate", ".", "finalFunc", "]", "\n", "aggregate", ".", "StateFunc", "=", "*", "keyspace", ".", "Functions", "[", "aggregate", ".", "stateFunc", "]", "\n", "keyspace", ".", "Aggregates", "[", "aggregate", ".", "Name", "]", "=", "&", "aggregate", "\n", "}", "\n", "keyspace", ".", "Views", "=", "make", "(", "map", "[", "string", "]", "*", "ViewMetadata", ",", "len", "(", "views", ")", ")", "\n", "for", "i", ":=", "range", "views", "{", "keyspace", ".", "Views", "[", "views", "[", "i", "]", ".", "Name", "]", "=", "&", "views", "[", "i", "]", "\n", "}", "\n\n", "// add columns from the schema data", "for", "i", ":=", "range", "columns", "{", "col", ":=", "&", "columns", "[", "i", "]", "\n", "// decode the validator for TypeInfo and order", "if", "col", ".", "ClusteringOrder", "!=", "\"", "\"", "{", "// Cassandra 3.x+", "col", ".", "Type", "=", "getCassandraType", "(", "col", ".", "Validator", ")", "\n", "col", ".", "Order", "=", "ASC", "\n", "if", "col", ".", "ClusteringOrder", "==", "\"", "\"", "{", "col", ".", "Order", "=", "DESC", "\n", "}", "\n", "}", "else", "{", "validatorParsed", ":=", "parseType", "(", "col", ".", "Validator", ")", "\n", "col", ".", "Type", "=", "validatorParsed", ".", "types", "[", "0", "]", "\n", "col", ".", "Order", "=", "ASC", "\n", "if", "validatorParsed", ".", "reversed", "[", "0", "]", "{", "col", ".", "Order", "=", "DESC", "\n", "}", "\n", "}", "\n\n", "table", ",", "ok", ":=", "keyspace", ".", "Tables", "[", "col", ".", "Table", "]", "\n", "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", "\n", "}", "\n\n", "table", ".", "Columns", "[", "col", ".", "Name", "]", "=", "col", "\n", "table", ".", "OrderedColumns", "=", "append", "(", "table", ".", "OrderedColumns", ",", "col", ".", "Name", ")", "\n", "}", "\n\n", "if", "protoVersion", "==", "protoVersion1", "{", "compileV1Metadata", "(", "tables", ")", "\n", "}", "else", "{", "compileV2Metadata", "(", "tables", ")", "\n", "}", "\n", "}" ]
// "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", "respectively", ";", "Links", "the", "metadata", "objects", "together", "and", "derives", "the", "column", "composition", "of", "the", "partition", "key", "and", "clustering", "key", "for", "a", "table", "." ]
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\n", "clusteringColumnCount", ":=", "componentColumnCountOfType", "(", "table", ".", "Columns", ",", "ColumnClusteringKey", ")", "\n", "table", ".", "ClusteringColumns", "=", "make", "(", "[", "]", "*", "ColumnMetadata", ",", "clusteringColumnCount", ")", "\n\n", "if", "table", ".", "KeyValidator", "!=", "\"", "\"", "{", "keyValidatorParsed", ":=", "parseType", "(", "table", ".", "KeyValidator", ")", "\n", "table", ".", "PartitionKey", "=", "make", "(", "[", "]", "*", "ColumnMetadata", ",", "len", "(", "keyValidatorParsed", ".", "types", ")", ")", "\n", "}", "else", "{", "// Cassandra 3.x+", "partitionKeyCount", ":=", "componentColumnCountOfType", "(", "table", ".", "Columns", ",", "ColumnPartitionKey", ")", "\n", "table", ".", "PartitionKey", "=", "make", "(", "[", "]", "*", "ColumnMetadata", ",", "partitionKeyCount", ")", "\n", "}", "\n\n", "for", "_", ",", "columnName", ":=", "range", "table", ".", "OrderedColumns", "{", "column", ":=", "table", ".", "Columns", "[", "columnName", "]", "\n", "if", "column", ".", "Kind", "==", "ColumnPartitionKey", "{", "table", ".", "PartitionKey", "[", "column", ".", "ComponentIndex", "]", "=", "column", "\n", "}", "else", "if", "column", ".", "Kind", "==", "ColumnClusteringKey", "{", "table", ".", "ClusteringColumns", "[", "column", ".", "ComponentIndex", "]", "=", "column", "\n", "}", "\n", "}", "\n", "}", "\n", "}" ]
// 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", "column", ".", "Kind", "==", "kind", "&&", "column", ".", "ComponentIndex", ">", "maxComponentIndex", "{", "maxComponentIndex", "=", "column", ".", "ComponentIndex", "\n", "}", "\n", "}", "\n", "return", "maxComponentIndex", "+", "1", "\n", "}" ]
// 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\n", "if", "session", ".", "useSystemSchema", "{", "// Cassandra 3.x+", "const", "stmt", "=", "`\n\t\tSELECT durable_writes, replication\n\t\tFROM system_schema.keyspaces\n\t\tWHERE keyspace_name = ?`", "\n\n", "var", "replication", "map", "[", "string", "]", "string", "\n\n", "iter", ":=", "session", ".", "control", ".", "query", "(", "stmt", ",", "keyspaceName", ")", "\n", "if", "iter", ".", "NumRows", "(", ")", "==", "0", "{", "return", "nil", ",", "ErrKeyspaceDoesNotExist", "\n", "}", "\n", "iter", ".", "Scan", "(", "&", "keyspace", ".", "DurableWrites", ",", "&", "replication", ")", "\n", "err", ":=", "iter", ".", "Close", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "keyspace", ".", "StrategyClass", "=", "replication", "[", "\"", "\"", "]", "\n", "delete", "(", "replication", ",", "\"", "\"", ")", "\n\n", "keyspace", ".", "StrategyOptions", "=", "make", "(", "map", "[", "string", "]", "interface", "{", "}", ",", "len", "(", "replication", ")", ")", "\n", "for", "k", ",", "v", ":=", "range", "replication", "{", "keyspace", ".", "StrategyOptions", "[", "k", "]", "=", "v", "\n", "}", "\n", "}", "else", "{", "const", "stmt", "=", "`\n\t\tSELECT durable_writes, strategy_class, strategy_options\n\t\tFROM system.schema_keyspaces\n\t\tWHERE keyspace_name = ?`", "\n\n", "var", "strategyOptionsJSON", "[", "]", "byte", "\n\n", "iter", ":=", "session", ".", "control", ".", "query", "(", "stmt", ",", "keyspaceName", ")", "\n", "if", "iter", ".", "NumRows", "(", ")", "==", "0", "{", "return", "nil", ",", "ErrKeyspaceDoesNotExist", "\n", "}", "\n", "iter", ".", "Scan", "(", "&", "keyspace", ".", "DurableWrites", ",", "&", "keyspace", ".", "StrategyClass", ",", "&", "strategyOptionsJSON", ")", "\n", "err", ":=", "iter", ".", "Close", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "err", "=", "json", ".", "Unmarshal", "(", "strategyOptionsJSON", ",", "&", "keyspace", ".", "StrategyOptions", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "strategyOptionsJSON", ",", "keyspace", ".", "Name", ",", "err", ",", ")", "\n", "}", "\n", "}", "\n\n", "return", "keyspace", ",", "nil", "\n", "}" ]
// 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\n", "// Deal with differences in protocol versions", "if", "session", ".", "cfg", ".", "ProtoVersion", "==", "1", "{", "columns", ",", "err", "=", "session", ".", "scanColumnMetadataV1", "(", "keyspaceName", ")", "\n", "}", "else", "if", "session", ".", "useSystemSchema", "{", "// Cassandra 3.x+", "columns", ",", "err", "=", "session", ".", "scanColumnMetadataSystem", "(", "keyspaceName", ")", "\n", "}", "else", "{", "columns", ",", "err", "=", "session", ".", "scanColumnMetadataV2", "(", "keyspaceName", ")", "\n", "}", "\n\n", "if", "err", "!=", "nil", "&&", "err", "!=", "ErrNotFound", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "return", "columns", ",", "nil", "\n", "}" ]
// 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\n", "if", "pool", ".", "closed", "{", "return", "nil", "\n", "}", "\n\n", "size", ":=", "len", "(", "pool", ".", "conns", ")", "\n", "if", "size", "<", "pool", ".", "size", "{", "// try to fill the pool", "go", "pool", ".", "fill", "(", ")", "\n\n", "if", "size", "==", "0", "{", "return", "nil", "\n", "}", "\n", "}", "\n\n", "pos", ":=", "int", "(", "atomic", ".", "AddUint32", "(", "&", "pool", ".", "pos", ",", "1", ")", "-", "1", ")", "\n\n", "var", "(", "leastBusyConn", "*", "Conn", "\n", "streamsAvailable", "int", "\n", ")", "\n\n", "// find the conn which has the most available streams, this is racy", "for", "i", ":=", "0", ";", "i", "<", "size", ";", "i", "++", "{", "conn", ":=", "pool", ".", "conns", "[", "(", "pos", "+", "i", ")", "%", "size", "]", "\n", "if", "streams", ":=", "conn", ".", "AvailableStreams", "(", ")", ";", "streams", ">", "streamsAvailable", "{", "leastBusyConn", "=", "conn", "\n", "streamsAvailable", "=", "streams", "\n", "}", "\n", "}", "\n\n", "return", "leastBusyConn", "\n", "}" ]
// 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\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\n", "if", "pool", ".", "closed", "{", "pool", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "\n", "}", "\n", "pool", ".", "closed", "=", "true", "\n\n", "// 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", "\n", "pool", ".", "conns", "=", "nil", "\n\n", "pool", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "// close the connections", "for", "_", ",", "conn", ":=", "range", "conns", "{", "conn", ".", "Close", "(", ")", "\n", "}", "\n", "}" ]
//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", "// avoid filling a closed pool, or concurrent filling", "if", "pool", ".", "closed", "||", "pool", ".", "filling", "{", "pool", ".", "mu", ".", "RUnlock", "(", ")", "\n", "return", "\n", "}", "\n\n", "// determine the filling work to be done", "startCount", ":=", "len", "(", "pool", ".", "conns", ")", "\n", "fillCount", ":=", "pool", ".", "size", "-", "startCount", "\n\n", "// avoid filling a full (or overfull) pool", "if", "fillCount", "<=", "0", "{", "pool", ".", "mu", ".", "RUnlock", "(", ")", "\n", "return", "\n", "}", "\n\n", "// switch from read to write lock", "pool", ".", "mu", ".", "RUnlock", "(", ")", "\n", "pool", ".", "mu", ".", "Lock", "(", ")", "\n\n", "// double check everything since the lock was released", "startCount", "=", "len", "(", "pool", ".", "conns", ")", "\n", "fillCount", "=", "pool", ".", "size", "-", "startCount", "\n", "if", "pool", ".", "closed", "||", "pool", ".", "filling", "||", "fillCount", "<=", "0", "{", "// looks like another goroutine already beat this", "// goroutine to the filling", "pool", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "\n", "}", "\n\n", "// ok fill the pool", "pool", ".", "filling", "=", "true", "\n\n", "// allow others to access the pool while filling", "pool", ".", "mu", ".", "Unlock", "(", ")", "\n", "// 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", "(", ")", "\n", "pool", ".", "logConnectErr", "(", "err", ")", "\n\n", "if", "err", "!=", "nil", "{", "// probably unreachable host", "pool", ".", "fillingStopped", "(", "true", ")", "\n\n", "// 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", ")", "\n", "}", "\n", "return", "\n", "}", "\n\n", "// filled one", "fillCount", "--", "\n", "}", "\n\n", "// fill the rest of the pool asynchronously", "go", "func", "(", ")", "{", "err", ":=", "pool", ".", "connectMany", "(", "fillCount", ")", "\n\n", "// mark the end of filling", "pool", ".", "fillingStopped", "(", "err", "!=", "nil", ")", "\n", "}", "(", ")", "\n", "}" ]
// 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", "{", "// 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", ")", "\n", "}", "\n\n", "pool", ".", "mu", ".", "Lock", "(", ")", "\n", "pool", ".", "filling", "=", "false", "\n", "pool", ".", "mu", ".", "Unlock", "(", ")", "\n", "}" ]
// 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", "connectErr", "error", "\n", ")", "\n", "wg", ".", "Add", "(", "count", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "count", ";", "i", "++", "{", "go", "func", "(", ")", "{", "defer", "wg", ".", "Done", "(", ")", "\n", "err", ":=", "pool", ".", "connect", "(", ")", "\n", "pool", ".", "logConnectErr", "(", "err", ")", "\n", "if", "err", "!=", "nil", "{", "mu", ".", "Lock", "(", ")", "\n", "connectErr", "=", "err", "\n", "mu", ".", "Unlock", "(", ")", "\n", "}", "\n", "}", "(", ")", "\n", "}", "\n", "// wait for all connections are done", "wg", ".", "Wait", "(", ")", "\n\n", "return", "connectErr", "\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", ")", "{", "// 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", "\n", "reconnectionPolicy", ":=", "pool", ".", "session", ".", "cfg", ".", "ReconnectionPolicy", "\n", "for", "i", ":=", "0", ";", "i", "<", "reconnectionPolicy", ".", "GetMaxRetries", "(", ")", ";", "i", "++", "{", "conn", ",", "err", "=", "pool", ".", "session", ".", "connect", "(", "pool", ".", "host", ",", "pool", ")", "\n", "if", "err", "==", "nil", "{", "break", "\n", "}", "\n", "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", "\n", "}", "\n", "}", "\n", "if", "gocqlDebug", "{", "Logger", ".", "Printf", "(", "\"", "\\n", "\"", ",", "pool", ".", "host", ".", "ConnectAddress", "(", ")", ",", "err", ",", "reconnectionPolicy", ")", "\n", "}", "\n", "time", ".", "Sleep", "(", "reconnectionPolicy", ".", "GetInterval", "(", "i", ")", ")", "\n", "}", "\n\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "pool", ".", "keyspace", "!=", "\"", "\"", "{", "// set the keyspace", "if", "err", "=", "conn", ".", "UseKeyspace", "(", "pool", ".", "keyspace", ")", ";", "err", "!=", "nil", "{", "conn", ".", "Close", "(", ")", "\n", "return", "err", "\n", "}", "\n", "}", "\n\n", "// add the Conn to the pool", "pool", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "pool", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "if", "pool", ".", "closed", "{", "conn", ".", "Close", "(", ")", "\n", "return", "nil", "\n", "}", "\n\n", "pool", ".", "conns", "=", "append", "(", "pool", ".", "conns", ",", "conn", ")", "\n\n", "return", "nil", "\n", "}" ]
// 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", "{", "// still an open connection, so continue using it", "return", "\n", "}", "\n\n", "// 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", "(", ")", "\n", "defer", "pool", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "if", "pool", ".", "closed", "{", "// pool closed", "return", "\n", "}", "\n\n", "// 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", "]", "\n\n", "// lost a connection, so fill the pool", "go", "pool", ".", "fill", "(", ")", "\n", "break", "\n", "}", "\n", "}", "\n", "}" ]
// 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", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "valueRef", ":=", "reflect", ".", "ValueOf", "(", "value", ")", ";", "valueRef", ".", "Kind", "(", ")", "==", "reflect", ".", "Ptr", "{", "if", "valueRef", ".", "IsNil", "(", ")", "{", "return", "nil", ",", "nil", "\n", "}", "else", "if", "v", ",", "ok", ":=", "value", ".", "(", "Marshaler", ")", ";", "ok", "{", "return", "v", ".", "MarshalCQL", "(", "info", ")", "\n", "}", "else", "{", "return", "Marshal", "(", "info", ",", "valueRef", ".", "Elem", "(", ")", ".", "Interface", "(", ")", ")", "\n", "}", "\n", "}", "\n\n", "if", "v", ",", "ok", ":=", "value", ".", "(", "Marshaler", ")", ";", "ok", "{", "return", "v", ".", "MarshalCQL", "(", "info", ")", "\n", "}", "\n\n", "switch", "info", ".", "Type", "(", ")", "{", "case", "TypeVarchar", ",", "TypeAscii", ",", "TypeBlob", ",", "TypeText", ":", "return", "marshalVarchar", "(", "info", ",", "value", ")", "\n", "case", "TypeBoolean", ":", "return", "marshalBool", "(", "info", ",", "value", ")", "\n", "case", "TypeTinyInt", ":", "return", "marshalTinyInt", "(", "info", ",", "value", ")", "\n", "case", "TypeSmallInt", ":", "return", "marshalSmallInt", "(", "info", ",", "value", ")", "\n", "case", "TypeInt", ":", "return", "marshalInt", "(", "info", ",", "value", ")", "\n", "case", "TypeBigInt", ",", "TypeCounter", ":", "return", "marshalBigInt", "(", "info", ",", "value", ")", "\n", "case", "TypeFloat", ":", "return", "marshalFloat", "(", "info", ",", "value", ")", "\n", "case", "TypeDouble", ":", "return", "marshalDouble", "(", "info", ",", "value", ")", "\n", "case", "TypeDecimal", ":", "return", "marshalDecimal", "(", "info", ",", "value", ")", "\n", "case", "TypeTime", ":", "return", "marshalTime", "(", "info", ",", "value", ")", "\n", "case", "TypeTimestamp", ":", "return", "marshalTimestamp", "(", "info", ",", "value", ")", "\n", "case", "TypeList", ",", "TypeSet", ":", "return", "marshalList", "(", "info", ",", "value", ")", "\n", "case", "TypeMap", ":", "return", "marshalMap", "(", "info", ",", "value", ")", "\n", "case", "TypeUUID", ",", "TypeTimeUUID", ":", "return", "marshalUUID", "(", "info", ",", "value", ")", "\n", "case", "TypeVarint", ":", "return", "marshalVarint", "(", "info", ",", "value", ")", "\n", "case", "TypeInet", ":", "return", "marshalInet", "(", "info", ",", "value", ")", "\n", "case", "TypeTuple", ":", "return", "marshalTuple", "(", "info", ",", "value", ")", "\n", "case", "TypeUDT", ":", "return", "marshalUDT", "(", "info", ",", "value", ")", "\n", "case", "TypeDate", ":", "return", "marshalDate", "(", "info", ",", "value", ")", "\n", "case", "TypeDuration", ":", "return", "marshalDuration", "(", "info", ",", "value", ")", "\n", "}", "\n\n", "// detect protocol 2 UDT", "if", "strings", ".", "HasPrefix", "(", "info", ".", "Custom", "(", ")", ",", "\"", "\"", ")", "&&", "info", ".", "Version", "(", ")", "<", "3", "{", "return", "nil", ",", "ErrorUDTUnavailable", "\n", "}", "\n\n", "// TODO(tux21b): add the remaining types", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "value", ",", "info", ")", "\n", "}" ]
// 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", ".", "UnmarshalCQL", "(", "info", ",", "data", ")", "\n", "}", "\n\n", "if", "isNullableValue", "(", "value", ")", "{", "return", "unmarshalNullable", "(", "info", ",", "data", ",", "value", ")", "\n", "}", "\n\n", "switch", "info", ".", "Type", "(", ")", "{", "case", "TypeVarchar", ",", "TypeAscii", ",", "TypeBlob", ",", "TypeText", ":", "return", "unmarshalVarchar", "(", "info", ",", "data", ",", "value", ")", "\n", "case", "TypeBoolean", ":", "return", "unmarshalBool", "(", "info", ",", "data", ",", "value", ")", "\n", "case", "TypeInt", ":", "return", "unmarshalInt", "(", "info", ",", "data", ",", "value", ")", "\n", "case", "TypeBigInt", ",", "TypeCounter", ":", "return", "unmarshalBigInt", "(", "info", ",", "data", ",", "value", ")", "\n", "case", "TypeVarint", ":", "return", "unmarshalVarint", "(", "info", ",", "data", ",", "value", ")", "\n", "case", "TypeSmallInt", ":", "return", "unmarshalSmallInt", "(", "info", ",", "data", ",", "value", ")", "\n", "case", "TypeTinyInt", ":", "return", "unmarshalTinyInt", "(", "info", ",", "data", ",", "value", ")", "\n", "case", "TypeFloat", ":", "return", "unmarshalFloat", "(", "info", ",", "data", ",", "value", ")", "\n", "case", "TypeDouble", ":", "return", "unmarshalDouble", "(", "info", ",", "data", ",", "value", ")", "\n", "case", "TypeDecimal", ":", "return", "unmarshalDecimal", "(", "info", ",", "data", ",", "value", ")", "\n", "case", "TypeTime", ":", "return", "unmarshalTime", "(", "info", ",", "data", ",", "value", ")", "\n", "case", "TypeTimestamp", ":", "return", "unmarshalTimestamp", "(", "info", ",", "data", ",", "value", ")", "\n", "case", "TypeList", ",", "TypeSet", ":", "return", "unmarshalList", "(", "info", ",", "data", ",", "value", ")", "\n", "case", "TypeMap", ":", "return", "unmarshalMap", "(", "info", ",", "data", ",", "value", ")", "\n", "case", "TypeTimeUUID", ":", "return", "unmarshalTimeUUID", "(", "info", ",", "data", ",", "value", ")", "\n", "case", "TypeUUID", ":", "return", "unmarshalUUID", "(", "info", ",", "data", ",", "value", ")", "\n", "case", "TypeInet", ":", "return", "unmarshalInet", "(", "info", ",", "data", ",", "value", ")", "\n", "case", "TypeTuple", ":", "return", "unmarshalTuple", "(", "info", ",", "data", ",", "value", ")", "\n", "case", "TypeUDT", ":", "return", "unmarshalUDT", "(", "info", ",", "data", ",", "value", ")", "\n", "case", "TypeDate", ":", "return", "unmarshalDate", "(", "info", ",", "data", ",", "value", ")", "\n", "case", "TypeDuration", ":", "return", "unmarshalDuration", "(", "info", ",", "data", ",", "value", ")", "\n", "}", "\n\n", "// detect protocol 2 UDT", "if", "strings", ".", "HasPrefix", "(", "info", ".", "Custom", "(", ")", ",", "\"", "\"", ")", "&&", "info", ".", "Version", "(", ")", "<", "3", "{", "return", "ErrorUDTUnavailable", "\n", "}", "\n\n", "// TODO(tux21b): add the remaining types", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "info", ",", "value", ")", "\n", "}" ]
// 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", "(", ")", "\n", "if", "b", "[", "0", "]", "&", "0x80", ">", "0", "{", "b", "=", "append", "(", "[", "]", "byte", "{", "0", "}", ",", "b", "...", ")", "\n", "}", "\n", "return", "b", "\n", "case", "-", "1", ":", "length", ":=", "uint", "(", "n", ".", "BitLen", "(", ")", "/", "8", "+", "1", ")", "*", "8", "\n", "b", ":=", "new", "(", "big", ".", "Int", ")", ".", "Add", "(", "n", ",", "new", "(", "big", ".", "Int", ")", ".", "Lsh", "(", "bigOne", ",", "length", ")", ")", ".", "Bytes", "(", ")", "\n", "// 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", ":", "]", "\n", "}", "\n", "return", "b", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// 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", ".", "UnmarshalCQL", "(", "info", ",", "data", ")", "\n", "}", "\n\n", "tuple", ":=", "info", ".", "(", "TupleTypeInfo", ")", "\n", "switch", "v", ":=", "value", ".", "(", "type", ")", "{", "case", "[", "]", "interface", "{", "}", ":", "for", "i", ",", "elem", ":=", "range", "tuple", ".", "Elems", "{", "// each element inside data is a [bytes]", "var", "p", "[", "]", "byte", "\n", "p", ",", "data", "=", "readBytes", "(", "data", ")", "\n\n", "err", ":=", "Unmarshal", "(", "elem", ",", "p", ",", "v", "[", "i", "]", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}", "\n\n", "rv", ":=", "reflect", ".", "ValueOf", "(", "value", ")", "\n", "if", "rv", ".", "Kind", "(", ")", "!=", "reflect", ".", "Ptr", "{", "return", "unmarshalErrorf", "(", "\"", "\"", ",", "value", ")", "\n", "}", "\n\n", "rv", "=", "rv", ".", "Elem", "(", ")", "\n", "t", ":=", "rv", ".", "Type", "(", ")", "\n", "k", ":=", "t", ".", "Kind", "(", ")", "\n\n", "switch", "k", "{", "case", "reflect", ".", "Struct", ":", "if", "v", ":=", "t", ".", "NumField", "(", ")", ";", "v", "!=", "len", "(", "tuple", ".", "Elems", ")", "{", "return", "unmarshalErrorf", "(", "\"", "\"", ",", "t", ",", "v", ",", "len", "(", "tuple", ".", "Elems", ")", ")", "\n", "}", "\n\n", "for", "i", ",", "elem", ":=", "range", "tuple", ".", "Elems", "{", "m", ":=", "readInt", "(", "data", ")", "\n", "data", "=", "data", "[", "4", ":", "]", "\n\n", "v", ":=", "elem", ".", "New", "(", ")", "\n", "if", "err", ":=", "Unmarshal", "(", "elem", ",", "data", "[", ":", "m", "]", ",", "v", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "rv", ".", "Field", "(", "i", ")", ".", "Set", "(", "reflect", ".", "ValueOf", "(", "v", ")", ".", "Elem", "(", ")", ")", "\n\n", "data", "=", "data", "[", "m", ":", "]", "\n", "}", "\n\n", "return", "nil", "\n", "case", "reflect", ".", "Slice", ",", "reflect", ".", "Array", ":", "if", "k", "==", "reflect", ".", "Array", "{", "size", ":=", "rv", ".", "Len", "(", ")", "\n", "if", "size", "!=", "len", "(", "tuple", ".", "Elems", ")", "{", "return", "unmarshalErrorf", "(", "\"", "\"", ",", "size", ",", "len", "(", "tuple", ".", "Elems", ")", ")", "\n", "}", "\n", "}", "else", "{", "rv", ".", "Set", "(", "reflect", ".", "MakeSlice", "(", "t", ",", "len", "(", "tuple", ".", "Elems", ")", ",", "len", "(", "tuple", ".", "Elems", ")", ")", ")", "\n", "}", "\n\n", "for", "i", ",", "elem", ":=", "range", "tuple", ".", "Elems", "{", "m", ":=", "readInt", "(", "data", ")", "\n", "data", "=", "data", "[", "4", ":", "]", "\n\n", "v", ":=", "elem", ".", "New", "(", ")", "\n", "if", "err", ":=", "Unmarshal", "(", "elem", ",", "data", "[", ":", "m", "]", ",", "v", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "rv", ".", "Index", "(", "i", ")", ".", "Set", "(", "reflect", ".", "ValueOf", "(", "v", ")", ".", "Elem", "(", ")", ")", "\n\n", "data", "=", "data", "[", "m", ":", "]", "\n", "}", "\n\n", "return", "nil", "\n", "}", "\n\n", "return", "unmarshalErrorf", "(", "\"", "\"", ",", "info", ",", "value", ")", "\n", "}" ]
// 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", "allow", "unmarshalling", "into", "custom", "tuple", "types", "." ]
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", "\"", "\"", "\n", "case", "TypeAscii", ":", "return", "\"", "\"", "\n", "case", "TypeBigInt", ":", "return", "\"", "\"", "\n", "case", "TypeBlob", ":", "return", "\"", "\"", "\n", "case", "TypeBoolean", ":", "return", "\"", "\"", "\n", "case", "TypeCounter", ":", "return", "\"", "\"", "\n", "case", "TypeDecimal", ":", "return", "\"", "\"", "\n", "case", "TypeDouble", ":", "return", "\"", "\"", "\n", "case", "TypeFloat", ":", "return", "\"", "\"", "\n", "case", "TypeInt", ":", "return", "\"", "\"", "\n", "case", "TypeText", ":", "return", "\"", "\"", "\n", "case", "TypeTimestamp", ":", "return", "\"", "\"", "\n", "case", "TypeUUID", ":", "return", "\"", "\"", "\n", "case", "TypeVarchar", ":", "return", "\"", "\"", "\n", "case", "TypeTimeUUID", ":", "return", "\"", "\"", "\n", "case", "TypeInet", ":", "return", "\"", "\"", "\n", "case", "TypeDate", ":", "return", "\"", "\"", "\n", "case", "TypeDuration", ":", "return", "\"", "\"", "\n", "case", "TypeTime", ":", "return", "\"", "\"", "\n", "case", "TypeSmallInt", ":", "return", "\"", "\"", "\n", "case", "TypeTinyInt", ":", "return", "\"", "\"", "\n", "case", "TypeList", ":", "return", "\"", "\"", "\n", "case", "TypeMap", ":", "return", "\"", "\"", "\n", "case", "TypeSet", ":", "return", "\"", "\"", "\n", "case", "TypeVarint", ":", "return", "\"", "\"", "\n", "case", "TypeTuple", ":", "return", "\"", "\"", "\n", "default", ":", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "t", ")", "\n", "}", "\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
gocql/gocql
policies.go
add
func (c *cowHostList) add(host *HostInfo) bool { c.mu.Lock() l := c.get() if n := len(l); n == 0 { l = []*HostInfo{host} } else { newL := make([]*HostInfo, n+1) for i := 0; i < n; i++ { if host.Equal(l[i]) { c.mu.Unlock() return false } newL[i] = l[i] } newL[n] = host l = newL } c.list.Store(&l) c.mu.Unlock() return true }
go
func (c *cowHostList) add(host *HostInfo) bool { c.mu.Lock() l := c.get() if n := len(l); n == 0 { l = []*HostInfo{host} } else { newL := make([]*HostInfo, n+1) for i := 0; i < n; i++ { if host.Equal(l[i]) { c.mu.Unlock() return false } newL[i] = l[i] } newL[n] = host l = newL } c.list.Store(&l) c.mu.Unlock() return true }
[ "func", "(", "c", "*", "cowHostList", ")", "add", "(", "host", "*", "HostInfo", ")", "bool", "{", "c", ".", "mu", ".", "Lock", "(", ")", "\n", "l", ":=", "c", ".", "get", "(", ")", "\n\n", "if", "n", ":=", "len", "(", "l", ")", ";", "n", "==", "0", "{", "l", "=", "[", "]", "*", "HostInfo", "{", "host", "}", "\n", "}", "else", "{", "newL", ":=", "make", "(", "[", "]", "*", "HostInfo", ",", "n", "+", "1", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "n", ";", "i", "++", "{", "if", "host", ".", "Equal", "(", "l", "[", "i", "]", ")", "{", "c", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "false", "\n", "}", "\n", "newL", "[", "i", "]", "=", "l", "[", "i", "]", "\n", "}", "\n", "newL", "[", "n", "]", "=", "host", "\n", "l", "=", "newL", "\n", "}", "\n\n", "c", ".", "list", ".", "Store", "(", "&", "l", ")", "\n", "c", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "true", "\n", "}" ]
// add will add a host if it not already in the list
[ "add", "will", "add", "a", "host", "if", "it", "not", "already", "in", "the", "list" ]
b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac
https://github.com/gocql/gocql/blob/b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac/policies.go#L47-L69
train
gocql/gocql
policies.go
Attempt
func (s *SimpleRetryPolicy) Attempt(q RetryableQuery) bool { return q.Attempts() <= s.NumRetries }
go
func (s *SimpleRetryPolicy) Attempt(q RetryableQuery) bool { return q.Attempts() <= s.NumRetries }
[ "func", "(", "s", "*", "SimpleRetryPolicy", ")", "Attempt", "(", "q", "RetryableQuery", ")", "bool", "{", "return", "q", ".", "Attempts", "(", ")", "<=", "s", ".", "NumRetries", "\n", "}" ]
// Attempt tells gocql to attempt the query again based on query.Attempts being less // than the NumRetries defined in the policy.
[ "Attempt", "tells", "gocql", "to", "attempt", "the", "query", "again", "based", "on", "query", ".", "Attempts", "being", "less", "than", "the", "NumRetries", "defined", "in", "the", "policy", "." ]
b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac
https://github.com/gocql/gocql/blob/b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac/policies.go#L179-L181
train
gocql/gocql
policies.go
getExponentialTime
func getExponentialTime(min time.Duration, max time.Duration, attempts int) time.Duration { if min <= 0 { min = 100 * time.Millisecond } if max <= 0 { max = 10 * time.Second } minFloat := float64(min) napDuration := minFloat * math.Pow(2, float64(attempts-1)) // add some jitter napDuration += rand.Float64()*minFloat - (minFloat / 2) if napDuration > float64(max) { return time.Duration(max) } return time.Duration(napDuration) }
go
func getExponentialTime(min time.Duration, max time.Duration, attempts int) time.Duration { if min <= 0 { min = 100 * time.Millisecond } if max <= 0 { max = 10 * time.Second } minFloat := float64(min) napDuration := minFloat * math.Pow(2, float64(attempts-1)) // add some jitter napDuration += rand.Float64()*minFloat - (minFloat / 2) if napDuration > float64(max) { return time.Duration(max) } return time.Duration(napDuration) }
[ "func", "getExponentialTime", "(", "min", "time", ".", "Duration", ",", "max", "time", ".", "Duration", ",", "attempts", "int", ")", "time", ".", "Duration", "{", "if", "min", "<=", "0", "{", "min", "=", "100", "*", "time", ".", "Millisecond", "\n", "}", "\n", "if", "max", "<=", "0", "{", "max", "=", "10", "*", "time", ".", "Second", "\n", "}", "\n", "minFloat", ":=", "float64", "(", "min", ")", "\n", "napDuration", ":=", "minFloat", "*", "math", ".", "Pow", "(", "2", ",", "float64", "(", "attempts", "-", "1", ")", ")", "\n", "// add some jitter", "napDuration", "+=", "rand", ".", "Float64", "(", ")", "*", "minFloat", "-", "(", "minFloat", "/", "2", ")", "\n", "if", "napDuration", ">", "float64", "(", "max", ")", "{", "return", "time", ".", "Duration", "(", "max", ")", "\n", "}", "\n", "return", "time", ".", "Duration", "(", "napDuration", ")", "\n", "}" ]
// used to calculate exponentially growing time
[ "used", "to", "calculate", "exponentially", "growing", "time" ]
b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac
https://github.com/gocql/gocql/blob/b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac/policies.go#L202-L217
train
gocql/gocql
policies.go
TokenAwareHostPolicy
func TokenAwareHostPolicy(fallback HostSelectionPolicy, opts ...func(*tokenAwareHostPolicy)) HostSelectionPolicy { p := &tokenAwareHostPolicy{fallback: fallback} for _, opt := range opts { opt(p) } return p }
go
func TokenAwareHostPolicy(fallback HostSelectionPolicy, opts ...func(*tokenAwareHostPolicy)) HostSelectionPolicy { p := &tokenAwareHostPolicy{fallback: fallback} for _, opt := range opts { opt(p) } return p }
[ "func", "TokenAwareHostPolicy", "(", "fallback", "HostSelectionPolicy", ",", "opts", "...", "func", "(", "*", "tokenAwareHostPolicy", ")", ")", "HostSelectionPolicy", "{", "p", ":=", "&", "tokenAwareHostPolicy", "{", "fallback", ":", "fallback", "}", "\n", "for", "_", ",", "opt", ":=", "range", "opts", "{", "opt", "(", "p", ")", "\n", "}", "\n", "return", "p", "\n", "}" ]
// TokenAwareHostPolicy is a token aware host selection policy, where hosts are // selected based on the partition key, so queries are sent to the host which // owns the partition. Fallback is used when routing information is not available.
[ "TokenAwareHostPolicy", "is", "a", "token", "aware", "host", "selection", "policy", "where", "hosts", "are", "selected", "based", "on", "the", "partition", "key", "so", "queries", "are", "sent", "to", "the", "host", "which", "owns", "the", "partition", ".", "Fallback", "is", "used", "when", "routing", "information", "is", "not", "available", "." ]
b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac
https://github.com/gocql/gocql/blob/b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac/policies.go#L393-L399
train
gocql/gocql
address_translators.go
IdentityTranslator
func IdentityTranslator() AddressTranslator { return AddressTranslatorFunc(func(addr net.IP, port int) (net.IP, int) { return addr, port }) }
go
func IdentityTranslator() AddressTranslator { return AddressTranslatorFunc(func(addr net.IP, port int) (net.IP, int) { return addr, port }) }
[ "func", "IdentityTranslator", "(", ")", "AddressTranslator", "{", "return", "AddressTranslatorFunc", "(", "func", "(", "addr", "net", ".", "IP", ",", "port", "int", ")", "(", "net", ".", "IP", ",", "int", ")", "{", "return", "addr", ",", "port", "\n", "}", ")", "\n", "}" ]
// IdentityTranslator will do nothing but return what it was provided. It is essentially a no-op.
[ "IdentityTranslator", "will", "do", "nothing", "but", "return", "what", "it", "was", "provided", ".", "It", "is", "essentially", "a", "no", "-", "op", "." ]
b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac
https://github.com/gocql/gocql/blob/b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac/address_translators.go#L22-L26
train
denisenkom/go-mssqldb
tds.go
normalizeOdbcKey
func normalizeOdbcKey(s string) string { return strings.ToLower(strings.TrimRightFunc(s, unicode.IsSpace)) }
go
func normalizeOdbcKey(s string) string { return strings.ToLower(strings.TrimRightFunc(s, unicode.IsSpace)) }
[ "func", "normalizeOdbcKey", "(", "s", "string", ")", "string", "{", "return", "strings", ".", "ToLower", "(", "strings", ".", "TrimRightFunc", "(", "s", ",", "unicode", ".", "IsSpace", ")", ")", "\n", "}" ]
// Normalizes the given string as an ODBC-format key
[ "Normalizes", "the", "given", "string", "as", "an", "ODBC", "-", "format", "key" ]
731ef375ac027e24d275c5432221dbec5007a647
https://github.com/denisenkom/go-mssqldb/blob/731ef375ac027e24d275c5432221dbec5007a647/tds.go#L867-L869
train
denisenkom/go-mssqldb
tds.go
dialConnection
func dialConnection(ctx context.Context, c *Connector, p connectParams) (conn net.Conn, err error) { var ips []net.IP ips, err = net.LookupIP(p.host) if err != nil { ip := net.ParseIP(p.host) if ip == nil { return nil, err } ips = []net.IP{ip} } if len(ips) == 1 { d := c.getDialer(&p) addr := net.JoinHostPort(ips[0].String(), strconv.Itoa(int(p.port))) conn, err = d.DialContext(ctx, "tcp", addr) } else { //Try Dials in parallel to avoid waiting for timeouts. connChan := make(chan net.Conn, len(ips)) errChan := make(chan error, len(ips)) portStr := strconv.Itoa(int(p.port)) for _, ip := range ips { go func(ip net.IP) { d := c.getDialer(&p) addr := net.JoinHostPort(ip.String(), portStr) conn, err := d.DialContext(ctx, "tcp", addr) if err == nil { connChan <- conn } else { errChan <- err } }(ip) } // Wait for either the *first* successful connection, or all the errors wait_loop: for i, _ := range ips { select { case conn = <-connChan: // Got a connection to use, close any others go func(n int) { for i := 0; i < n; i++ { select { case conn := <-connChan: conn.Close() case <-errChan: } } }(len(ips) - i - 1) // Remove any earlier errors we may have collected err = nil break wait_loop case err = <-errChan: } } } // Can't do the usual err != nil check, as it is possible to have gotten an error before a successful connection if conn == nil { f := "Unable to open tcp connection with host '%v:%v': %v" return nil, fmt.Errorf(f, p.host, p.port, err.Error()) } return conn, err }
go
func dialConnection(ctx context.Context, c *Connector, p connectParams) (conn net.Conn, err error) { var ips []net.IP ips, err = net.LookupIP(p.host) if err != nil { ip := net.ParseIP(p.host) if ip == nil { return nil, err } ips = []net.IP{ip} } if len(ips) == 1 { d := c.getDialer(&p) addr := net.JoinHostPort(ips[0].String(), strconv.Itoa(int(p.port))) conn, err = d.DialContext(ctx, "tcp", addr) } else { //Try Dials in parallel to avoid waiting for timeouts. connChan := make(chan net.Conn, len(ips)) errChan := make(chan error, len(ips)) portStr := strconv.Itoa(int(p.port)) for _, ip := range ips { go func(ip net.IP) { d := c.getDialer(&p) addr := net.JoinHostPort(ip.String(), portStr) conn, err := d.DialContext(ctx, "tcp", addr) if err == nil { connChan <- conn } else { errChan <- err } }(ip) } // Wait for either the *first* successful connection, or all the errors wait_loop: for i, _ := range ips { select { case conn = <-connChan: // Got a connection to use, close any others go func(n int) { for i := 0; i < n; i++ { select { case conn := <-connChan: conn.Close() case <-errChan: } } }(len(ips) - i - 1) // Remove any earlier errors we may have collected err = nil break wait_loop case err = <-errChan: } } } // Can't do the usual err != nil check, as it is possible to have gotten an error before a successful connection if conn == nil { f := "Unable to open tcp connection with host '%v:%v': %v" return nil, fmt.Errorf(f, p.host, p.port, err.Error()) } return conn, err }
[ "func", "dialConnection", "(", "ctx", "context", ".", "Context", ",", "c", "*", "Connector", ",", "p", "connectParams", ")", "(", "conn", "net", ".", "Conn", ",", "err", "error", ")", "{", "var", "ips", "[", "]", "net", ".", "IP", "\n", "ips", ",", "err", "=", "net", ".", "LookupIP", "(", "p", ".", "host", ")", "\n", "if", "err", "!=", "nil", "{", "ip", ":=", "net", ".", "ParseIP", "(", "p", ".", "host", ")", "\n", "if", "ip", "==", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "ips", "=", "[", "]", "net", ".", "IP", "{", "ip", "}", "\n", "}", "\n", "if", "len", "(", "ips", ")", "==", "1", "{", "d", ":=", "c", ".", "getDialer", "(", "&", "p", ")", "\n", "addr", ":=", "net", ".", "JoinHostPort", "(", "ips", "[", "0", "]", ".", "String", "(", ")", ",", "strconv", ".", "Itoa", "(", "int", "(", "p", ".", "port", ")", ")", ")", "\n", "conn", ",", "err", "=", "d", ".", "DialContext", "(", "ctx", ",", "\"", "\"", ",", "addr", ")", "\n\n", "}", "else", "{", "//Try Dials in parallel to avoid waiting for timeouts.", "connChan", ":=", "make", "(", "chan", "net", ".", "Conn", ",", "len", "(", "ips", ")", ")", "\n", "errChan", ":=", "make", "(", "chan", "error", ",", "len", "(", "ips", ")", ")", "\n", "portStr", ":=", "strconv", ".", "Itoa", "(", "int", "(", "p", ".", "port", ")", ")", "\n", "for", "_", ",", "ip", ":=", "range", "ips", "{", "go", "func", "(", "ip", "net", ".", "IP", ")", "{", "d", ":=", "c", ".", "getDialer", "(", "&", "p", ")", "\n", "addr", ":=", "net", ".", "JoinHostPort", "(", "ip", ".", "String", "(", ")", ",", "portStr", ")", "\n", "conn", ",", "err", ":=", "d", ".", "DialContext", "(", "ctx", ",", "\"", "\"", ",", "addr", ")", "\n", "if", "err", "==", "nil", "{", "connChan", "<-", "conn", "\n", "}", "else", "{", "errChan", "<-", "err", "\n", "}", "\n", "}", "(", "ip", ")", "\n", "}", "\n", "// Wait for either the *first* successful connection, or all the errors", "wait_loop", ":", "for", "i", ",", "_", ":=", "range", "ips", "{", "select", "{", "case", "conn", "=", "<-", "connChan", ":", "// Got a connection to use, close any others", "go", "func", "(", "n", "int", ")", "{", "for", "i", ":=", "0", ";", "i", "<", "n", ";", "i", "++", "{", "select", "{", "case", "conn", ":=", "<-", "connChan", ":", "conn", ".", "Close", "(", ")", "\n", "case", "<-", "errChan", ":", "}", "\n", "}", "\n", "}", "(", "len", "(", "ips", ")", "-", "i", "-", "1", ")", "\n", "// Remove any earlier errors we may have collected", "err", "=", "nil", "\n", "break", "wait_loop", "\n", "case", "err", "=", "<-", "errChan", ":", "}", "\n", "}", "\n", "}", "\n", "// Can't do the usual err != nil check, as it is possible to have gotten an error before a successful connection", "if", "conn", "==", "nil", "{", "f", ":=", "\"", "\"", "\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "f", ",", "p", ".", "host", ",", "p", ".", "port", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "return", "conn", ",", "err", "\n", "}" ]
// SQL Server AlwaysOn Availability Group Listeners are bound by DNS to a // list of IP addresses. So if there is more than one, try them all and // use the first one that allows a connection.
[ "SQL", "Server", "AlwaysOn", "Availability", "Group", "Listeners", "are", "bound", "by", "DNS", "to", "a", "list", "of", "IP", "addresses", ".", "So", "if", "there", "is", "more", "than", "one", "try", "them", "all", "and", "use", "the", "first", "one", "that", "allows", "a", "connection", "." ]
731ef375ac027e24d275c5432221dbec5007a647
https://github.com/denisenkom/go-mssqldb/blob/731ef375ac027e24d275c5432221dbec5007a647/tds.go#L1114-L1174
train
denisenkom/go-mssqldb
mssql_go110.go
Connect
func (c *Connector) Connect(ctx context.Context) (driver.Conn, error) { conn, err := c.driver.connect(ctx, c, c.params) if err == nil { err = conn.ResetSession(ctx) } return conn, err }
go
func (c *Connector) Connect(ctx context.Context) (driver.Conn, error) { conn, err := c.driver.connect(ctx, c, c.params) if err == nil { err = conn.ResetSession(ctx) } return conn, err }
[ "func", "(", "c", "*", "Connector", ")", "Connect", "(", "ctx", "context", ".", "Context", ")", "(", "driver", ".", "Conn", ",", "error", ")", "{", "conn", ",", "err", ":=", "c", ".", "driver", ".", "connect", "(", "ctx", ",", "c", ",", "c", ".", "params", ")", "\n", "if", "err", "==", "nil", "{", "err", "=", "conn", ".", "ResetSession", "(", "ctx", ")", "\n", "}", "\n", "return", "conn", ",", "err", "\n", "}" ]
// Connect to the server and return a TDS connection.
[ "Connect", "to", "the", "server", "and", "return", "a", "TDS", "connection", "." ]
731ef375ac027e24d275c5432221dbec5007a647
https://github.com/denisenkom/go-mssqldb/blob/731ef375ac027e24d275c5432221dbec5007a647/mssql_go110.go#L36-L42
train
denisenkom/go-mssqldb
batch/batch.go
Split
func Split(sql, separator string) []string { if len(separator) == 0 || len(sql) < len(separator) { return []string{sql} } l := &lexer{ Sql: sql, Sep: separator, At: 0, } state := stateWhitespace for state != nil { state = state(l) } l.AddCurrent(1) return l.Batch }
go
func Split(sql, separator string) []string { if len(separator) == 0 || len(sql) < len(separator) { return []string{sql} } l := &lexer{ Sql: sql, Sep: separator, At: 0, } state := stateWhitespace for state != nil { state = state(l) } l.AddCurrent(1) return l.Batch }
[ "func", "Split", "(", "sql", ",", "separator", "string", ")", "[", "]", "string", "{", "if", "len", "(", "separator", ")", "==", "0", "||", "len", "(", "sql", ")", "<", "len", "(", "separator", ")", "{", "return", "[", "]", "string", "{", "sql", "}", "\n", "}", "\n", "l", ":=", "&", "lexer", "{", "Sql", ":", "sql", ",", "Sep", ":", "separator", ",", "At", ":", "0", ",", "}", "\n", "state", ":=", "stateWhitespace", "\n", "for", "state", "!=", "nil", "{", "state", "=", "state", "(", "l", ")", "\n", "}", "\n", "l", ".", "AddCurrent", "(", "1", ")", "\n", "return", "l", ".", "Batch", "\n", "}" ]
// Split the provided SQL into multiple sql scripts based on a given // separator, often "GO". It also allows escaping newlines with a // backslash.
[ "Split", "the", "provided", "SQL", "into", "multiple", "sql", "scripts", "based", "on", "a", "given", "separator", "often", "GO", ".", "It", "also", "allows", "escaping", "newlines", "with", "a", "backslash", "." ]
731ef375ac027e24d275c5432221dbec5007a647
https://github.com/denisenkom/go-mssqldb/blob/731ef375ac027e24d275c5432221dbec5007a647/batch/batch.go#L20-L35
train
denisenkom/go-mssqldb
bulkcopy.go
AddRow
func (b *Bulk) AddRow(row []interface{}) (err error) { if !b.headerSent { err = b.sendBulkCommand(b.ctx) if err != nil { return } } if len(row) != len(b.bulkColumns) { return fmt.Errorf("Row does not have the same number of columns than the destination table %d %d", len(row), len(b.bulkColumns)) } bytes, err := b.makeRowData(row) if err != nil { return } _, err = b.cn.sess.buf.Write(bytes) if err != nil { return } b.numRows = b.numRows + 1 return }
go
func (b *Bulk) AddRow(row []interface{}) (err error) { if !b.headerSent { err = b.sendBulkCommand(b.ctx) if err != nil { return } } if len(row) != len(b.bulkColumns) { return fmt.Errorf("Row does not have the same number of columns than the destination table %d %d", len(row), len(b.bulkColumns)) } bytes, err := b.makeRowData(row) if err != nil { return } _, err = b.cn.sess.buf.Write(bytes) if err != nil { return } b.numRows = b.numRows + 1 return }
[ "func", "(", "b", "*", "Bulk", ")", "AddRow", "(", "row", "[", "]", "interface", "{", "}", ")", "(", "err", "error", ")", "{", "if", "!", "b", ".", "headerSent", "{", "err", "=", "b", ".", "sendBulkCommand", "(", "b", ".", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "}", "\n\n", "if", "len", "(", "row", ")", "!=", "len", "(", "b", ".", "bulkColumns", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "len", "(", "row", ")", ",", "len", "(", "b", ".", "bulkColumns", ")", ")", "\n", "}", "\n\n", "bytes", ",", "err", ":=", "b", ".", "makeRowData", "(", "row", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n\n", "_", ",", "err", "=", "b", ".", "cn", ".", "sess", ".", "buf", ".", "Write", "(", "bytes", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n\n", "b", ".", "numRows", "=", "b", ".", "numRows", "+", "1", "\n", "return", "\n", "}" ]
// AddRow immediately writes the row to the destination table. // The arguments are the row values in the order they were specified.
[ "AddRow", "immediately", "writes", "the", "row", "to", "the", "destination", "table", ".", "The", "arguments", "are", "the", "row", "values", "in", "the", "order", "they", "were", "specified", "." ]
731ef375ac027e24d275c5432221dbec5007a647
https://github.com/denisenkom/go-mssqldb/blob/731ef375ac027e24d275c5432221dbec5007a647/bulkcopy.go#L154-L179
train
denisenkom/go-mssqldb
mssql.go
OpenConnector
func (d *Driver) OpenConnector(dsn string) (*Connector, error) { params, err := parseConnectParams(dsn) if err != nil { return nil, err } return &Connector{ params: params, driver: d, }, nil }
go
func (d *Driver) OpenConnector(dsn string) (*Connector, error) { params, err := parseConnectParams(dsn) if err != nil { return nil, err } return &Connector{ params: params, driver: d, }, nil }
[ "func", "(", "d", "*", "Driver", ")", "OpenConnector", "(", "dsn", "string", ")", "(", "*", "Connector", ",", "error", ")", "{", "params", ",", "err", ":=", "parseConnectParams", "(", "dsn", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "Connector", "{", "params", ":", "params", ",", "driver", ":", "d", ",", "}", ",", "nil", "\n", "}" ]
// OpenConnector opens a new connector. Useful to dial with a context.
[ "OpenConnector", "opens", "a", "new", "connector", ".", "Useful", "to", "dial", "with", "a", "context", "." ]
731ef375ac027e24d275c5432221dbec5007a647
https://github.com/denisenkom/go-mssqldb/blob/731ef375ac027e24d275c5432221dbec5007a647/mssql.go#L54-L63
train
denisenkom/go-mssqldb
mssql.go
NewConnector
func NewConnector(dsn string) (*Connector, error) { params, err := parseConnectParams(dsn) if err != nil { return nil, err } c := &Connector{ params: params, driver: driverInstanceNoProcess, } return c, nil }
go
func NewConnector(dsn string) (*Connector, error) { params, err := parseConnectParams(dsn) if err != nil { return nil, err } c := &Connector{ params: params, driver: driverInstanceNoProcess, } return c, nil }
[ "func", "NewConnector", "(", "dsn", "string", ")", "(", "*", "Connector", ",", "error", ")", "{", "params", ",", "err", ":=", "parseConnectParams", "(", "dsn", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "c", ":=", "&", "Connector", "{", "params", ":", "params", ",", "driver", ":", "driverInstanceNoProcess", ",", "}", "\n", "return", "c", ",", "nil", "\n", "}" ]
// NewConnector creates a new connector from a DSN. // The returned connector may be used with sql.OpenDB.
[ "NewConnector", "creates", "a", "new", "connector", "from", "a", "DSN", ".", "The", "returned", "connector", "may", "be", "used", "with", "sql", ".", "OpenDB", "." ]
731ef375ac027e24d275c5432221dbec5007a647
https://github.com/denisenkom/go-mssqldb/blob/731ef375ac027e24d275c5432221dbec5007a647/mssql.go#L80-L90
train
denisenkom/go-mssqldb
mssql.go
connect
func (d *Driver) connect(ctx context.Context, c *Connector, params connectParams) (*Conn, error) { sess, err := connect(ctx, c, d.log, params) if err != nil { // main server failed, try fail-over partner if params.failOverPartner == "" { return nil, err } params.host = params.failOverPartner if params.failOverPort != 0 { params.port = params.failOverPort } sess, err = connect(ctx, c, d.log, params) if err != nil { // fail-over partner also failed, now fail return nil, err } } conn := &Conn{ connector: c, sess: sess, transactionCtx: context.Background(), processQueryText: d.processQueryText, connectionGood: true, } conn.sess.log = d.log return conn, nil }
go
func (d *Driver) connect(ctx context.Context, c *Connector, params connectParams) (*Conn, error) { sess, err := connect(ctx, c, d.log, params) if err != nil { // main server failed, try fail-over partner if params.failOverPartner == "" { return nil, err } params.host = params.failOverPartner if params.failOverPort != 0 { params.port = params.failOverPort } sess, err = connect(ctx, c, d.log, params) if err != nil { // fail-over partner also failed, now fail return nil, err } } conn := &Conn{ connector: c, sess: sess, transactionCtx: context.Background(), processQueryText: d.processQueryText, connectionGood: true, } conn.sess.log = d.log return conn, nil }
[ "func", "(", "d", "*", "Driver", ")", "connect", "(", "ctx", "context", ".", "Context", ",", "c", "*", "Connector", ",", "params", "connectParams", ")", "(", "*", "Conn", ",", "error", ")", "{", "sess", ",", "err", ":=", "connect", "(", "ctx", ",", "c", ",", "d", ".", "log", ",", "params", ")", "\n", "if", "err", "!=", "nil", "{", "// main server failed, try fail-over partner", "if", "params", ".", "failOverPartner", "==", "\"", "\"", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "params", ".", "host", "=", "params", ".", "failOverPartner", "\n", "if", "params", ".", "failOverPort", "!=", "0", "{", "params", ".", "port", "=", "params", ".", "failOverPort", "\n", "}", "\n\n", "sess", ",", "err", "=", "connect", "(", "ctx", ",", "c", ",", "d", ".", "log", ",", "params", ")", "\n", "if", "err", "!=", "nil", "{", "// fail-over partner also failed, now fail", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n\n", "conn", ":=", "&", "Conn", "{", "connector", ":", "c", ",", "sess", ":", "sess", ",", "transactionCtx", ":", "context", ".", "Background", "(", ")", ",", "processQueryText", ":", "d", ".", "processQueryText", ",", "connectionGood", ":", "true", ",", "}", "\n", "conn", ".", "sess", ".", "log", "=", "d", ".", "log", "\n\n", "return", "conn", ",", "nil", "\n", "}" ]
// connect to the server, using the provided context for dialing only.
[ "connect", "to", "the", "server", "using", "the", "provided", "context", "for", "dialing", "only", "." ]
731ef375ac027e24d275c5432221dbec5007a647
https://github.com/denisenkom/go-mssqldb/blob/731ef375ac027e24d275c5432221dbec5007a647/mssql.go#L327-L357
train
denisenkom/go-mssqldb
mssql.go
isProc
func isProc(s string) bool { if len(s) == 0 { return false } const ( outside = iota text escaped ) st := outside var rn1, rPrev rune for _, r := range s { rPrev = rn1 rn1 = r switch r { // No newlines or string sequences. case '\n', '\r', '\'', ';': return false } switch st { case outside: switch { case unicode.IsSpace(r): return false case r == '[': st = escaped continue case r == ']' && rPrev == ']': st = escaped continue case unicode.IsLetter(r): st = text } case text: switch { case r == '.': st = outside continue case unicode.IsSpace(r): return false } case escaped: switch { case r == ']': st = outside continue } } } return true }
go
func isProc(s string) bool { if len(s) == 0 { return false } const ( outside = iota text escaped ) st := outside var rn1, rPrev rune for _, r := range s { rPrev = rn1 rn1 = r switch r { // No newlines or string sequences. case '\n', '\r', '\'', ';': return false } switch st { case outside: switch { case unicode.IsSpace(r): return false case r == '[': st = escaped continue case r == ']' && rPrev == ']': st = escaped continue case unicode.IsLetter(r): st = text } case text: switch { case r == '.': st = outside continue case unicode.IsSpace(r): return false } case escaped: switch { case r == ']': st = outside continue } } } return true }
[ "func", "isProc", "(", "s", "string", ")", "bool", "{", "if", "len", "(", "s", ")", "==", "0", "{", "return", "false", "\n", "}", "\n", "const", "(", "outside", "=", "iota", "\n", "text", "\n", "escaped", "\n", ")", "\n", "st", ":=", "outside", "\n", "var", "rn1", ",", "rPrev", "rune", "\n", "for", "_", ",", "r", ":=", "range", "s", "{", "rPrev", "=", "rn1", "\n", "rn1", "=", "r", "\n", "switch", "r", "{", "// No newlines or string sequences.", "case", "'\\n'", ",", "'\\r'", ",", "'\\''", ",", "';'", ":", "return", "false", "\n", "}", "\n", "switch", "st", "{", "case", "outside", ":", "switch", "{", "case", "unicode", ".", "IsSpace", "(", "r", ")", ":", "return", "false", "\n", "case", "r", "==", "'['", ":", "st", "=", "escaped", "\n", "continue", "\n", "case", "r", "==", "']'", "&&", "rPrev", "==", "']'", ":", "st", "=", "escaped", "\n", "continue", "\n", "case", "unicode", ".", "IsLetter", "(", "r", ")", ":", "st", "=", "text", "\n", "}", "\n", "case", "text", ":", "switch", "{", "case", "r", "==", "'.'", ":", "st", "=", "outside", "\n", "continue", "\n", "case", "unicode", ".", "IsSpace", "(", "r", ")", ":", "return", "false", "\n", "}", "\n", "case", "escaped", ":", "switch", "{", "case", "r", "==", "']'", ":", "st", "=", "outside", "\n", "continue", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "true", "\n", "}" ]
// isProc takes the query text in s and determines if it is a stored proc name // or SQL text.
[ "isProc", "takes", "the", "query", "text", "in", "s", "and", "determines", "if", "it", "is", "a", "stored", "proc", "name", "or", "SQL", "text", "." ]
731ef375ac027e24d275c5432221dbec5007a647
https://github.com/denisenkom/go-mssqldb/blob/731ef375ac027e24d275c5432221dbec5007a647/mssql.go#L485-L535
train
denisenkom/go-mssqldb
mssql.go
ColumnTypeNullable
func (r *Rows) ColumnTypeNullable(index int) (nullable, ok bool) { nullable = r.cols[index].Flags&colFlagNullable != 0 ok = true return }
go
func (r *Rows) ColumnTypeNullable(index int) (nullable, ok bool) { nullable = r.cols[index].Flags&colFlagNullable != 0 ok = true return }
[ "func", "(", "r", "*", "Rows", ")", "ColumnTypeNullable", "(", "index", "int", ")", "(", "nullable", ",", "ok", "bool", ")", "{", "nullable", "=", "r", ".", "cols", "[", "index", "]", ".", "Flags", "&", "colFlagNullable", "!=", "0", "\n", "ok", "=", "true", "\n", "return", "\n", "}" ]
// The nullable value should // be true if it is known the column may be null, or false if the column is known // to be not nullable. // If the column nullability is unknown, ok should be false.
[ "The", "nullable", "value", "should", "be", "true", "if", "it", "is", "known", "the", "column", "may", "be", "null", "or", "false", "if", "the", "column", "is", "known", "to", "be", "not", "nullable", ".", "If", "the", "column", "nullability", "is", "unknown", "ok", "should", "be", "false", "." ]
731ef375ac027e24d275c5432221dbec5007a647
https://github.com/denisenkom/go-mssqldb/blob/731ef375ac027e24d275c5432221dbec5007a647/mssql.go#L779-L783
train
denisenkom/go-mssqldb
mssql.go
Ping
func (c *Conn) Ping(ctx context.Context) error { if !c.connectionGood { return driver.ErrBadConn } stmt := &Stmt{c, `select 1;`, 0, nil} _, err := stmt.ExecContext(ctx, nil) return err }
go
func (c *Conn) Ping(ctx context.Context) error { if !c.connectionGood { return driver.ErrBadConn } stmt := &Stmt{c, `select 1;`, 0, nil} _, err := stmt.ExecContext(ctx, nil) return err }
[ "func", "(", "c", "*", "Conn", ")", "Ping", "(", "ctx", "context", ".", "Context", ")", "error", "{", "if", "!", "c", ".", "connectionGood", "{", "return", "driver", ".", "ErrBadConn", "\n", "}", "\n", "stmt", ":=", "&", "Stmt", "{", "c", ",", "`select 1;`", ",", "0", ",", "nil", "}", "\n", "_", ",", "err", ":=", "stmt", ".", "ExecContext", "(", "ctx", ",", "nil", ")", "\n", "return", "err", "\n", "}" ]
// Ping is used to check if the remote server is available and satisfies the Pinger interface.
[ "Ping", "is", "used", "to", "check", "if", "the", "remote", "server", "is", "available", "and", "satisfies", "the", "Pinger", "interface", "." ]
731ef375ac027e24d275c5432221dbec5007a647
https://github.com/denisenkom/go-mssqldb/blob/731ef375ac027e24d275c5432221dbec5007a647/mssql.go#L898-L905
train
denisenkom/go-mssqldb
mssql.go
BeginTx
func (c *Conn) BeginTx(ctx context.Context, opts driver.TxOptions) (driver.Tx, error) { if !c.connectionGood { return nil, driver.ErrBadConn } if opts.ReadOnly { return nil, errors.New("Read-only transactions are not supported") } var tdsIsolation isoLevel switch sql.IsolationLevel(opts.Isolation) { case sql.LevelDefault: tdsIsolation = isolationUseCurrent case sql.LevelReadUncommitted: tdsIsolation = isolationReadUncommited case sql.LevelReadCommitted: tdsIsolation = isolationReadCommited case sql.LevelWriteCommitted: return nil, errors.New("LevelWriteCommitted isolation level is not supported") case sql.LevelRepeatableRead: tdsIsolation = isolationRepeatableRead case sql.LevelSnapshot: tdsIsolation = isolationSnapshot case sql.LevelSerializable: tdsIsolation = isolationSerializable case sql.LevelLinearizable: return nil, errors.New("LevelLinearizable isolation level is not supported") default: return nil, errors.New("Isolation level is not supported or unknown") } return c.begin(ctx, tdsIsolation) }
go
func (c *Conn) BeginTx(ctx context.Context, opts driver.TxOptions) (driver.Tx, error) { if !c.connectionGood { return nil, driver.ErrBadConn } if opts.ReadOnly { return nil, errors.New("Read-only transactions are not supported") } var tdsIsolation isoLevel switch sql.IsolationLevel(opts.Isolation) { case sql.LevelDefault: tdsIsolation = isolationUseCurrent case sql.LevelReadUncommitted: tdsIsolation = isolationReadUncommited case sql.LevelReadCommitted: tdsIsolation = isolationReadCommited case sql.LevelWriteCommitted: return nil, errors.New("LevelWriteCommitted isolation level is not supported") case sql.LevelRepeatableRead: tdsIsolation = isolationRepeatableRead case sql.LevelSnapshot: tdsIsolation = isolationSnapshot case sql.LevelSerializable: tdsIsolation = isolationSerializable case sql.LevelLinearizable: return nil, errors.New("LevelLinearizable isolation level is not supported") default: return nil, errors.New("Isolation level is not supported or unknown") } return c.begin(ctx, tdsIsolation) }
[ "func", "(", "c", "*", "Conn", ")", "BeginTx", "(", "ctx", "context", ".", "Context", ",", "opts", "driver", ".", "TxOptions", ")", "(", "driver", ".", "Tx", ",", "error", ")", "{", "if", "!", "c", ".", "connectionGood", "{", "return", "nil", ",", "driver", ".", "ErrBadConn", "\n", "}", "\n", "if", "opts", ".", "ReadOnly", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "var", "tdsIsolation", "isoLevel", "\n", "switch", "sql", ".", "IsolationLevel", "(", "opts", ".", "Isolation", ")", "{", "case", "sql", ".", "LevelDefault", ":", "tdsIsolation", "=", "isolationUseCurrent", "\n", "case", "sql", ".", "LevelReadUncommitted", ":", "tdsIsolation", "=", "isolationReadUncommited", "\n", "case", "sql", ".", "LevelReadCommitted", ":", "tdsIsolation", "=", "isolationReadCommited", "\n", "case", "sql", ".", "LevelWriteCommitted", ":", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "case", "sql", ".", "LevelRepeatableRead", ":", "tdsIsolation", "=", "isolationRepeatableRead", "\n", "case", "sql", ".", "LevelSnapshot", ":", "tdsIsolation", "=", "isolationSnapshot", "\n", "case", "sql", ".", "LevelSerializable", ":", "tdsIsolation", "=", "isolationSerializable", "\n", "case", "sql", ".", "LevelLinearizable", ":", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "default", ":", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "c", ".", "begin", "(", "ctx", ",", "tdsIsolation", ")", "\n", "}" ]
// BeginTx satisfies ConnBeginTx.
[ "BeginTx", "satisfies", "ConnBeginTx", "." ]
731ef375ac027e24d275c5432221dbec5007a647
https://github.com/denisenkom/go-mssqldb/blob/731ef375ac027e24d275c5432221dbec5007a647/mssql.go#L910-L940
train
denisenkom/go-mssqldb
types.go
encodeDateTime
func encodeDateTime(t time.Time) (res []byte) { // base date in days since Jan 1st 1900 basedays := gregorianDays(1900, 1) // days since Jan 1st 1900 (same TZ as t) days := gregorianDays(t.Year(), t.YearDay()) - basedays tm := 300*(t.Second()+t.Minute()*60+t.Hour()*60*60) + t.Nanosecond()*300/1e9 // minimum and maximum possible mindays := gregorianDays(1753, 1) - basedays maxdays := gregorianDays(9999, 365) - basedays if days < mindays { days = mindays tm = 0 } if days > maxdays { days = maxdays tm = (23*60*60+59*60+59)*300 + 299 } res = make([]byte, 8) binary.LittleEndian.PutUint32(res[0:4], uint32(days)) binary.LittleEndian.PutUint32(res[4:8], uint32(tm)) return }
go
func encodeDateTime(t time.Time) (res []byte) { // base date in days since Jan 1st 1900 basedays := gregorianDays(1900, 1) // days since Jan 1st 1900 (same TZ as t) days := gregorianDays(t.Year(), t.YearDay()) - basedays tm := 300*(t.Second()+t.Minute()*60+t.Hour()*60*60) + t.Nanosecond()*300/1e9 // minimum and maximum possible mindays := gregorianDays(1753, 1) - basedays maxdays := gregorianDays(9999, 365) - basedays if days < mindays { days = mindays tm = 0 } if days > maxdays { days = maxdays tm = (23*60*60+59*60+59)*300 + 299 } res = make([]byte, 8) binary.LittleEndian.PutUint32(res[0:4], uint32(days)) binary.LittleEndian.PutUint32(res[4:8], uint32(tm)) return }
[ "func", "encodeDateTime", "(", "t", "time", ".", "Time", ")", "(", "res", "[", "]", "byte", ")", "{", "// base date in days since Jan 1st 1900", "basedays", ":=", "gregorianDays", "(", "1900", ",", "1", ")", "\n", "// days since Jan 1st 1900 (same TZ as t)", "days", ":=", "gregorianDays", "(", "t", ".", "Year", "(", ")", ",", "t", ".", "YearDay", "(", ")", ")", "-", "basedays", "\n", "tm", ":=", "300", "*", "(", "t", ".", "Second", "(", ")", "+", "t", ".", "Minute", "(", ")", "*", "60", "+", "t", ".", "Hour", "(", ")", "*", "60", "*", "60", ")", "+", "t", ".", "Nanosecond", "(", ")", "*", "300", "/", "1e9", "\n", "// minimum and maximum possible", "mindays", ":=", "gregorianDays", "(", "1753", ",", "1", ")", "-", "basedays", "\n", "maxdays", ":=", "gregorianDays", "(", "9999", ",", "365", ")", "-", "basedays", "\n", "if", "days", "<", "mindays", "{", "days", "=", "mindays", "\n", "tm", "=", "0", "\n", "}", "\n", "if", "days", ">", "maxdays", "{", "days", "=", "maxdays", "\n", "tm", "=", "(", "23", "*", "60", "*", "60", "+", "59", "*", "60", "+", "59", ")", "*", "300", "+", "299", "\n", "}", "\n", "res", "=", "make", "(", "[", "]", "byte", ",", "8", ")", "\n", "binary", ".", "LittleEndian", ".", "PutUint32", "(", "res", "[", "0", ":", "4", "]", ",", "uint32", "(", "days", ")", ")", "\n", "binary", ".", "LittleEndian", ".", "PutUint32", "(", "res", "[", "4", ":", "8", "]", ",", "uint32", "(", "tm", ")", ")", "\n", "return", "\n", "}" ]
// encodes datetime value // type identifier is typeDateTimeN
[ "encodes", "datetime", "value", "type", "identifier", "is", "typeDateTimeN" ]
731ef375ac027e24d275c5432221dbec5007a647
https://github.com/denisenkom/go-mssqldb/blob/731ef375ac027e24d275c5432221dbec5007a647/types.go#L279-L300
train
denisenkom/go-mssqldb
types.go
encodeTimeInt
func encodeTimeInt(seconds, ns, scale int, buf []byte) { ns_total := int64(seconds)*1000*1000*1000 + int64(ns) t := ns_total / int64(math.Pow10(int(scale)*-1)*1e9) buf[0] = byte(t) buf[1] = byte(t >> 8) buf[2] = byte(t >> 16) buf[3] = byte(t >> 24) buf[4] = byte(t >> 32) }
go
func encodeTimeInt(seconds, ns, scale int, buf []byte) { ns_total := int64(seconds)*1000*1000*1000 + int64(ns) t := ns_total / int64(math.Pow10(int(scale)*-1)*1e9) buf[0] = byte(t) buf[1] = byte(t >> 8) buf[2] = byte(t >> 16) buf[3] = byte(t >> 24) buf[4] = byte(t >> 32) }
[ "func", "encodeTimeInt", "(", "seconds", ",", "ns", ",", "scale", "int", ",", "buf", "[", "]", "byte", ")", "{", "ns_total", ":=", "int64", "(", "seconds", ")", "*", "1000", "*", "1000", "*", "1000", "+", "int64", "(", "ns", ")", "\n", "t", ":=", "ns_total", "/", "int64", "(", "math", ".", "Pow10", "(", "int", "(", "scale", ")", "*", "-", "1", ")", "*", "1e9", ")", "\n", "buf", "[", "0", "]", "=", "byte", "(", "t", ")", "\n", "buf", "[", "1", "]", "=", "byte", "(", "t", ">>", "8", ")", "\n", "buf", "[", "2", "]", "=", "byte", "(", "t", ">>", "16", ")", "\n", "buf", "[", "3", "]", "=", "byte", "(", "t", ">>", "24", ")", "\n", "buf", "[", "4", "]", "=", "byte", "(", "t", ">>", "32", ")", "\n", "}" ]
// writes time value into a field buffer // buffer should be at least calcTimeSize long
[ "writes", "time", "value", "into", "a", "field", "buffer", "buffer", "should", "be", "at", "least", "calcTimeSize", "long" ]
731ef375ac027e24d275c5432221dbec5007a647
https://github.com/denisenkom/go-mssqldb/blob/731ef375ac027e24d275c5432221dbec5007a647/types.go#L899-L907
train
denisenkom/go-mssqldb
types.go
gregorianDays
func gregorianDays(year, yearday int) int { year0 := year - 1 return year0*365 + year0/4 - year0/100 + year0/400 + yearday - 1 }
go
func gregorianDays(year, yearday int) int { year0 := year - 1 return year0*365 + year0/4 - year0/100 + year0/400 + yearday - 1 }
[ "func", "gregorianDays", "(", "year", ",", "yearday", "int", ")", "int", "{", "year0", ":=", "year", "-", "1", "\n", "return", "year0", "*", "365", "+", "year0", "/", "4", "-", "year0", "/", "100", "+", "year0", "/", "400", "+", "yearday", "-", "1", "\n", "}" ]
// returns days since Jan 1st 0001 in Gregorian calendar
[ "returns", "days", "since", "Jan", "1st", "0001", "in", "Gregorian", "calendar" ]
731ef375ac027e24d275c5432221dbec5007a647
https://github.com/denisenkom/go-mssqldb/blob/731ef375ac027e24d275c5432221dbec5007a647/types.go#L966-L969
train
nsqio/go-nsq
config.go
HandlesOption
func (h *structTagsConfig) HandlesOption(c *Config, option string) bool { val := reflect.ValueOf(c).Elem() typ := val.Type() for i := 0; i < typ.NumField(); i++ { field := typ.Field(i) opt := field.Tag.Get("opt") if opt == option { return true } } return false }
go
func (h *structTagsConfig) HandlesOption(c *Config, option string) bool { val := reflect.ValueOf(c).Elem() typ := val.Type() for i := 0; i < typ.NumField(); i++ { field := typ.Field(i) opt := field.Tag.Get("opt") if opt == option { return true } } return false }
[ "func", "(", "h", "*", "structTagsConfig", ")", "HandlesOption", "(", "c", "*", "Config", ",", "option", "string", ")", "bool", "{", "val", ":=", "reflect", ".", "ValueOf", "(", "c", ")", ".", "Elem", "(", ")", "\n", "typ", ":=", "val", ".", "Type", "(", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "typ", ".", "NumField", "(", ")", ";", "i", "++", "{", "field", ":=", "typ", ".", "Field", "(", "i", ")", "\n", "opt", ":=", "field", ".", "Tag", ".", "Get", "(", "\"", "\"", ")", "\n", "if", "opt", "==", "option", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// Handle options that are listed in StructTags
[ "Handle", "options", "that", "are", "listed", "in", "StructTags" ]
61f49c096d0d767be61e4de06f724e1cb5fd85d7
https://github.com/nsqio/go-nsq/blob/61f49c096d0d767be61e4de06f724e1cb5fd85d7/config.go#L259-L270
train
nsqio/go-nsq
config.go
Set
func (h *structTagsConfig) Set(c *Config, option string, value interface{}) error { val := reflect.ValueOf(c).Elem() typ := val.Type() for i := 0; i < typ.NumField(); i++ { field := typ.Field(i) opt := field.Tag.Get("opt") if option != opt { continue } min := field.Tag.Get("min") max := field.Tag.Get("max") fieldVal := val.FieldByName(field.Name) dest := unsafeValueOf(fieldVal) coercedVal, err := coerce(value, field.Type) if err != nil { return fmt.Errorf("failed to coerce option %s (%v) - %s", option, value, err) } if min != "" { coercedMinVal, _ := coerce(min, field.Type) if valueCompare(coercedVal, coercedMinVal) == -1 { return fmt.Errorf("invalid %s ! %v < %v", option, coercedVal.Interface(), coercedMinVal.Interface()) } } if max != "" { coercedMaxVal, _ := coerce(max, field.Type) if valueCompare(coercedVal, coercedMaxVal) == 1 { return fmt.Errorf("invalid %s ! %v > %v", option, coercedVal.Interface(), coercedMaxVal.Interface()) } } if coercedVal.Type().String() == "nsq.BackoffStrategy" { v := coercedVal.Interface().(BackoffStrategy) if v, ok := v.(interface { setConfig(*Config) }); ok { v.setConfig(c) } } dest.Set(coercedVal) return nil } return fmt.Errorf("unknown option %s", option) }
go
func (h *structTagsConfig) Set(c *Config, option string, value interface{}) error { val := reflect.ValueOf(c).Elem() typ := val.Type() for i := 0; i < typ.NumField(); i++ { field := typ.Field(i) opt := field.Tag.Get("opt") if option != opt { continue } min := field.Tag.Get("min") max := field.Tag.Get("max") fieldVal := val.FieldByName(field.Name) dest := unsafeValueOf(fieldVal) coercedVal, err := coerce(value, field.Type) if err != nil { return fmt.Errorf("failed to coerce option %s (%v) - %s", option, value, err) } if min != "" { coercedMinVal, _ := coerce(min, field.Type) if valueCompare(coercedVal, coercedMinVal) == -1 { return fmt.Errorf("invalid %s ! %v < %v", option, coercedVal.Interface(), coercedMinVal.Interface()) } } if max != "" { coercedMaxVal, _ := coerce(max, field.Type) if valueCompare(coercedVal, coercedMaxVal) == 1 { return fmt.Errorf("invalid %s ! %v > %v", option, coercedVal.Interface(), coercedMaxVal.Interface()) } } if coercedVal.Type().String() == "nsq.BackoffStrategy" { v := coercedVal.Interface().(BackoffStrategy) if v, ok := v.(interface { setConfig(*Config) }); ok { v.setConfig(c) } } dest.Set(coercedVal) return nil } return fmt.Errorf("unknown option %s", option) }
[ "func", "(", "h", "*", "structTagsConfig", ")", "Set", "(", "c", "*", "Config", ",", "option", "string", ",", "value", "interface", "{", "}", ")", "error", "{", "val", ":=", "reflect", ".", "ValueOf", "(", "c", ")", ".", "Elem", "(", ")", "\n", "typ", ":=", "val", ".", "Type", "(", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "typ", ".", "NumField", "(", ")", ";", "i", "++", "{", "field", ":=", "typ", ".", "Field", "(", "i", ")", "\n", "opt", ":=", "field", ".", "Tag", ".", "Get", "(", "\"", "\"", ")", "\n\n", "if", "option", "!=", "opt", "{", "continue", "\n", "}", "\n\n", "min", ":=", "field", ".", "Tag", ".", "Get", "(", "\"", "\"", ")", "\n", "max", ":=", "field", ".", "Tag", ".", "Get", "(", "\"", "\"", ")", "\n\n", "fieldVal", ":=", "val", ".", "FieldByName", "(", "field", ".", "Name", ")", "\n", "dest", ":=", "unsafeValueOf", "(", "fieldVal", ")", "\n", "coercedVal", ",", "err", ":=", "coerce", "(", "value", ",", "field", ".", "Type", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "option", ",", "value", ",", "err", ")", "\n", "}", "\n", "if", "min", "!=", "\"", "\"", "{", "coercedMinVal", ",", "_", ":=", "coerce", "(", "min", ",", "field", ".", "Type", ")", "\n", "if", "valueCompare", "(", "coercedVal", ",", "coercedMinVal", ")", "==", "-", "1", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "option", ",", "coercedVal", ".", "Interface", "(", ")", ",", "coercedMinVal", ".", "Interface", "(", ")", ")", "\n", "}", "\n", "}", "\n", "if", "max", "!=", "\"", "\"", "{", "coercedMaxVal", ",", "_", ":=", "coerce", "(", "max", ",", "field", ".", "Type", ")", "\n", "if", "valueCompare", "(", "coercedVal", ",", "coercedMaxVal", ")", "==", "1", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "option", ",", "coercedVal", ".", "Interface", "(", ")", ",", "coercedMaxVal", ".", "Interface", "(", ")", ")", "\n", "}", "\n", "}", "\n", "if", "coercedVal", ".", "Type", "(", ")", ".", "String", "(", ")", "==", "\"", "\"", "{", "v", ":=", "coercedVal", ".", "Interface", "(", ")", ".", "(", "BackoffStrategy", ")", "\n", "if", "v", ",", "ok", ":=", "v", ".", "(", "interface", "{", "setConfig", "(", "*", "Config", ")", "\n", "}", ")", ";", "ok", "{", "v", ".", "setConfig", "(", "c", ")", "\n", "}", "\n", "}", "\n", "dest", ".", "Set", "(", "coercedVal", ")", "\n", "return", "nil", "\n", "}", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "option", ")", "\n", "}" ]
// Set values based on parameters in StructTags
[ "Set", "values", "based", "on", "parameters", "in", "StructTags" ]
61f49c096d0d767be61e4de06f724e1cb5fd85d7
https://github.com/nsqio/go-nsq/blob/61f49c096d0d767be61e4de06f724e1cb5fd85d7/config.go#L273-L320
train