diff --git a/cluster.go b/cluster.go index 2f9619134..8e7a8ad84 100644 --- a/cluster.go +++ b/cluster.go @@ -335,7 +335,7 @@ func (cfg *ClusterConfig) filterHost(host *HostInfo) bool { } var ( - ErrNoHosts = errors.New("no hosts provided") - ErrNoConnectionsStarted = errors.New("no connections were made when creating the session") - ErrHostQueryFailed = errors.New("unable to populate Hosts") + ErrAuthenticatorAndAuthProvider = errors.New("gocql: Can't use both Authenticator and AuthProvider in cluster config.") + ErrNoHosts = errors.New("gocql: no hosts provided") + ErrNoConnectionsStarted = errors.New("gocql: no connections were made when creating the session") ) diff --git a/conn.go b/conn.go index d2f83d742..ae7644ec6 100644 --- a/conn.go +++ b/conn.go @@ -87,7 +87,7 @@ type PasswordAuthenticator struct { func (p PasswordAuthenticator) Challenge(req []byte) ([]byte, Authenticator, error) { if !approve(string(req), p.AllowedAuthenticators) { - return nil, nil, fmt.Errorf("unexpected authenticator %q", req) + return nil, nil, fmt.Errorf("gocql: unexpected authenticator %q", req) } resp := make([]byte, 2+len(p.Username)+len(p.Password)) resp[0] = 0 @@ -459,7 +459,7 @@ func (s *startupCoordinator) startup(ctx context.Context, supported map[string][ func (s *startupCoordinator) authenticateHandshake(ctx context.Context, authFrame *authenticateFrame, startupCompleted *atomic.Bool) error { if s.conn.auth == nil { - return fmt.Errorf("authentication required (using %q)", authFrame.class) + return fmt.Errorf("gocql: authentication required (using %q)", authFrame.class) } resp, challenger, err := s.conn.auth.Challenge([]byte(authFrame.class)) @@ -492,7 +492,7 @@ func (s *startupCoordinator) authenticateHandshake(ctx context.Context, authFram data: resp, } default: - return fmt.Errorf("unknown frame response during authentication: %v", v) + return fmt.Errorf("gocql: unknown frame response during authentication: %v", v) } } } @@ -1166,7 +1166,7 @@ func (c *Conn) addCall(call *callReq) error { } existingCall := c.calls[call.streamID] if existingCall != nil { - return fmt.Errorf("attempting to use stream already in use: %d -> %d", call.streamID, + return fmt.Errorf("gocql: attempting to use stream already in use: %d -> %d", call.streamID, existingCall.streamID) } c.calls[call.streamID] = call @@ -1451,7 +1451,7 @@ func (c *Conn) prepareStatement(ctx context.Context, stmt string, tracer Tracer, response: x.respMeta, } case error: - flight.err = x + flight.err = fmt.Errorf("cassandra: %w", x) default: flight.err = NewErrProtocol("Unknown type in response to prepare frame: %s", x) } @@ -1727,7 +1727,7 @@ func (c *Conn) UseKeyspace(keyspace string) error { switch x := resp.(type) { case *resultKeyspaceFrame: case error: - return x + return fmt.Errorf("cassandra: %w", x) default: return NewErrProtocol("unknown frame in response to USE: %v", x) } @@ -1845,7 +1845,7 @@ func (c *Conn) executeBatch(ctx context.Context, batch *Batch) *Iter { return iter case error: - return &Iter{err: x, framer: framer} + return &Iter{err: fmt.Errorf("cassandra: %w", x), framer: framer} default: return &Iter{err: NewErrProtocol("Unknown type in response to batch statement: %s", x), framer: framer} } diff --git a/control.go b/control.go index 95ba1c02b..e18e7863d 100644 --- a/control.go +++ b/control.go @@ -159,7 +159,7 @@ func hostInfo(addr string, defaultPort int) ([]*HostInfo, error) { if err != nil { return nil, err } else if len(ips) == 0 { - return nil, fmt.Errorf("no IP's returned from DNS lookup for %q", addr) + return nil, fmt.Errorf("gocql: no IP's returned from DNS lookup for %q", addr) } // Filter to v4 addresses if any present @@ -284,7 +284,7 @@ func (c *controlConn) connect(hosts []*HostInfo) error { conn = nil } if conn == nil { - return fmt.Errorf("unable to connect to initial hosts: %v", err) + return fmt.Errorf("gocql: unable to connect to initial hosts: %w", err) } // we could fetch the initial ring here and update initial host data. So that @@ -311,11 +311,11 @@ func (c *controlConn) setupConn(conn *Conn) error { host = c.session.ring.addOrUpdate(host) if c.session.cfg.filterHost(host) { - return fmt.Errorf("host was filtered: %v", host.ConnectAddress()) + return fmt.Errorf("gocql: host was filtered: %v", host.ConnectAddress()) } if err := c.registerEvents(conn); err != nil { - return fmt.Errorf("register events: %v", err) + return fmt.Errorf("gocql: register events: %w", err) } ch := &connHost{ @@ -365,7 +365,7 @@ func (c *controlConn) registerEvents(conn *Conn) error { if err != nil { return err } else if _, ok := frame.(*readyFrame); !ok { - return fmt.Errorf("unexpected frame in response to register: got %T: %v\n", frame, frame) + return fmt.Errorf("gocql: unexpected frame in response to register: got %T: %v\n", frame, frame) } return nil @@ -422,7 +422,7 @@ func (c *controlConn) attemptReconnect() (*Conn, error) { // changed their IPs while keeping the same hostname(s). initialHosts, resolvErr := addrsToHosts(c.session.cfg.Hosts, c.session.cfg.Port, c.session.logger) if resolvErr != nil { - return nil, fmt.Errorf("resolve contact points' hostnames: %v", resolvErr) + return nil, fmt.Errorf("gocql: resolve contact points' hostnames: %w", resolvErr) } return c.attemptReconnectToAnyOfHosts(initialHosts) diff --git a/dial.go b/dial.go index 8c7251d62..84b817cc8 100644 --- a/dial.go +++ b/dial.go @@ -64,9 +64,9 @@ func (hd *defaultHostDialer) DialHost(ctx context.Context, host *HostInfo) (*Dia port := host.Port() if !validIpAddr(ip) { - return nil, fmt.Errorf("host missing connect ip address: %v", ip) + return nil, fmt.Errorf("gocql: host missing connect ip address: %v", ip) } else if port == 0 { - return nil, fmt.Errorf("host missing port: %v", port) + return nil, fmt.Errorf("gocql: host missing port: %v", port) } connAddr := host.ConnectAddressAndPort() diff --git a/filters.go b/filters.go index 312bd0d1a..78f17cc76 100644 --- a/filters.go +++ b/filters.go @@ -73,7 +73,7 @@ func WhiteListHostFilter(hosts ...string) HostFilter { hostInfos, err := addrsToHosts(hosts, 9042, nopLogger{}) 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)) + panic(fmt.Errorf("gocql: unable to lookup host info from address: %w", err)) } m := make(map[string]bool, len(hostInfos)) diff --git a/frame.go b/frame.go index 99b07e289..603d5ea1f 100644 --- a/frame.go +++ b/frame.go @@ -25,9 +25,7 @@ package gocql import ( - "bytes" "context" - "encoding/binary" "errors" "fmt" "io" @@ -273,7 +271,7 @@ func (c *Consistency) UnmarshalText(text []byte) error { case "LOCAL_SERIAL": *c = LocalSerial default: - return fmt.Errorf("invalid consistency %q", string(text)) + return fmt.Errorf("gocql: invalid consistency %q", string(text)) } return nil @@ -303,7 +301,7 @@ const ( ) var ( - ErrFrameTooBig = errors.New("frame length is bigger than the maximum allowed") + ErrFrameTooBig = errors.New("gocql: frame length is bigger than the maximum allowed") ) const maxFrameHeaderSize = 9 @@ -446,7 +444,7 @@ func readHeader(r io.Reader, p []byte) (head frameHeader, err error) { if version > protoVersion2 { if len(p) != 9 { - return frameHeader{}, fmt.Errorf("not enough bytes to read header require 9 got: %d", len(p)) + return frameHeader{}, fmt.Errorf("gocql: not enough bytes to read header require 9 got: %d", len(p)) } head.stream = int(int16(p[2])<<8 | int16(p[3])) @@ -454,7 +452,7 @@ func readHeader(r io.Reader, p []byte) (head frameHeader, err error) { head.length = int(readInt(p[5:])) } else { if len(p) != 8 { - return frameHeader{}, fmt.Errorf("not enough bytes to read header require 8 got: %d", len(p)) + return frameHeader{}, fmt.Errorf("gocql: not enough bytes to read header require 8 got: %d", len(p)) } head.stream = int(int8(p[2])) @@ -478,12 +476,12 @@ func (f *framer) payload() { // reads a frame form the wire into the framers buffer func (f *framer) readFrame(r io.Reader, head *frameHeader) error { if head.length < 0 { - return fmt.Errorf("frame body length can not be less than 0: %d", head.length) + return fmt.Errorf("gocql: 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, r, int64(head.length)) if err != nil { - return fmt.Errorf("error whilst trying to discard frame with invalid length: %v", err) + return fmt.Errorf("gocql: error whilst trying to discard frame with invalid length: %w", err) } return ErrFrameTooBig } @@ -498,7 +496,7 @@ func (f *framer) readFrame(r io.Reader, head *frameHeader) error { // assume the underlying reader takes care of timeouts and retries n, err := io.ReadFull(r, f.buf) if err != nil { - return fmt.Errorf("unable to read frame body: read %d/%d bytes: %v", n, head.length, err) + return fmt.Errorf("gocql: unable to read frame body: read %d/%d bytes: %w", n, head.length, err) } if f.proto < protoVersion5 && head.flags&flagCompress == flagCompress { @@ -508,7 +506,7 @@ func (f *framer) readFrame(r io.Reader, head *frameHeader) error { f.buf, err = f.compres.AppendDecompressedWithLength(nil, f.buf) if err != nil { - return err + return fmt.Errorf("gocql: %w", err) } } @@ -684,7 +682,7 @@ func (f *framer) parseErrorFrame() frame { // TODO(zariel): we should have some distinct types for these errors return errD default: - panic(fmt.Errorf("unknown error code: 0x%x", errD.code)) + panic(fmt.Errorf("gocql: unknown error code: 0x%x", errD.code)) } } @@ -753,7 +751,7 @@ func (f *framer) finish() error { // TODO: only compress frames which are big enough compressed, err := f.compres.AppendCompressedWithLength(nil, f.buf[f.headSize:]) if err != nil { - return err + return fmt.Errorf("gocql: %w", err) } f.buf = append(f.buf[:f.headSize], compressed...) @@ -833,7 +831,7 @@ func (w *writePrepareFrame) buildFrame(f *framer, streamID int) error { if f.proto > protoVersion4 { flags |= flagWithPreparedKeyspace } else { - panic(fmt.Errorf("the keyspace can only be set with protocol 5 or higher")) + panic(fmt.Errorf("gocql: the keyspace can only be set with protocol 5 or higher")) } } if f.proto > protoVersion4 { @@ -932,7 +930,7 @@ func (f *framer) parsePreparedMetadata() preparedMetadata { meta.flags = f.readInt() meta.colCount = f.readInt() if meta.colCount < 0 { - panic(fmt.Errorf("received negative column count: %d", meta.colCount)) + panic(fmt.Errorf("gocql: received negative column count: %d", meta.colCount)) } meta.actualColCount = meta.colCount @@ -1035,7 +1033,7 @@ func (f *framer) parseResultMetadata() resultMetadata { meta.flags = f.readInt() meta.colCount = f.readInt() if meta.colCount < 0 { - panic(fmt.Errorf("received negative column count: %d", meta.colCount)) + panic(fmt.Errorf("gocql: received negative column count: %d", meta.colCount)) } meta.actualColCount = meta.colCount @@ -1126,7 +1124,7 @@ func (f *framer) parseResultRows() frame { result.numRows = f.readInt() if result.numRows < 0 { - panic(fmt.Errorf("invalid row_count in result frame: %d", result.numRows)) + panic(fmt.Errorf("gocql: invalid row_count in result frame: %d", result.numRows)) } return result @@ -1499,14 +1497,14 @@ func (f *framer) writeQueryParams(opts *queryParams) { if opts.keyspace != "" { if f.proto < protoVersion5 { - panic(fmt.Errorf("the keyspace can only be set with protocol 5 or higher")) + panic(fmt.Errorf("gocql: the keyspace can only be set with protocol 5 or higher")) } flags |= flagWithKeyspace } if opts.nowInSeconds != nil { if f.proto < protoVersion5 { - panic(fmt.Errorf("now_in_seconds can only be set with protocol 5 or higher")) + panic(fmt.Errorf("gocql: now_in_seconds can only be set with protocol 5 or higher")) } flags |= flagWithNowInSeconds } @@ -1737,14 +1735,14 @@ func (f *framer) writeBatchFrame(streamID int, w *writeBatchFrame, customPayload if w.keyspace != "" { if f.proto < protoVersion5 { - panic(fmt.Errorf("the keyspace can only be set with protocol 5 or higher")) + panic(fmt.Errorf("gocql: the keyspace can only be set with protocol 5 or higher")) } flags |= flagWithKeyspace } if w.nowInSeconds != nil { if f.proto < protoVersion5 { - panic(fmt.Errorf("now_in_seconds can only be set with protocol 5 or higher")) + panic(fmt.Errorf("gocql: now_in_seconds can only be set with protocol 5 or higher")) } flags |= flagWithNowInSeconds } @@ -1808,7 +1806,7 @@ func (f *framer) writeRegisterFrame(streamID int, w *writeRegisterFrame) error { func (f *framer) readByte() byte { if len(f.buf) < 1 { - panic(fmt.Errorf("not enough bytes in buffer to read byte require 1 got: %d", len(f.buf))) + panic(fmt.Errorf("gocql: not enough bytes in buffer to read byte require 1 got: %d", len(f.buf))) } b := f.buf[0] @@ -1818,7 +1816,7 @@ func (f *framer) readByte() byte { func (f *framer) readInt() (n int) { if len(f.buf) < 4 { - panic(fmt.Errorf("not enough bytes in buffer to read int require 4 got: %d", len(f.buf))) + panic(fmt.Errorf("gocql: not enough bytes in buffer to read int require 4 got: %d", len(f.buf))) } n = int(int32(f.buf[0])<<24 | int32(f.buf[1])<<16 | int32(f.buf[2])<<8 | int32(f.buf[3])) @@ -1828,7 +1826,7 @@ func (f *framer) readInt() (n int) { func (f *framer) readShort() (n uint16) { if len(f.buf) < 2 { - panic(fmt.Errorf("not enough bytes in buffer to read short require 2 got: %d", len(f.buf))) + panic(fmt.Errorf("gocql: not enough bytes in buffer to read short require 2 got: %d", len(f.buf))) } n = uint16(f.buf[0])<<8 | uint16(f.buf[1]) f.buf = f.buf[2:] @@ -1839,7 +1837,7 @@ func (f *framer) readString() (s string) { size := f.readShort() if len(f.buf) < int(size) { - panic(fmt.Errorf("not enough bytes in buffer to read string require %d got: %d", size, len(f.buf))) + panic(fmt.Errorf("gocql: not enough bytes in buffer to read string require %d got: %d", size, len(f.buf))) } s = string(f.buf[:size]) @@ -1851,7 +1849,7 @@ func (f *framer) readLongString() (s string) { size := f.readInt() if len(f.buf) < size { - panic(fmt.Errorf("not enough bytes in buffer to read long string require %d got: %d", size, len(f.buf))) + panic(fmt.Errorf("gocql: not enough bytes in buffer to read long string require %d got: %d", size, len(f.buf))) } s = string(f.buf[:size]) @@ -1861,7 +1859,7 @@ func (f *framer) readLongString() (s string) { func (f *framer) readUUID() *UUID { if len(f.buf) < 16 { - panic(fmt.Errorf("not enough bytes in buffer to read uuid require %d got: %d", 16, len(f.buf))) + panic(fmt.Errorf("gocql: not enough bytes in buffer to read uuid require %d got: %d", 16, len(f.buf))) } // TODO: how to handle this error, if it is a uuid, then sureley, problems? @@ -1888,7 +1886,7 @@ func (f *framer) readBytesInternal() ([]byte, error) { } if len(f.buf) < size { - return nil, fmt.Errorf("not enough bytes in buffer to read bytes require %d got: %d", size, len(f.buf)) + return nil, fmt.Errorf("gocql: not enough bytes in buffer to read bytes require %d got: %d", size, len(f.buf)) } l := f.buf[:size] @@ -1909,7 +1907,7 @@ func (f *framer) readBytes() []byte { func (f *framer) readShortBytes() []byte { size := f.readShort() if len(f.buf) < int(size) { - panic(fmt.Errorf("not enough bytes in buffer to read short bytes: require %d got %d", size, len(f.buf))) + panic(fmt.Errorf("gocql: not enough bytes in buffer to read short bytes: require %d got %d", size, len(f.buf))) } l := f.buf[:size] @@ -1920,18 +1918,18 @@ func (f *framer) readShortBytes() []byte { func (f *framer) readInetAdressOnly() net.IP { if len(f.buf) < 1 { - panic(fmt.Errorf("not enough bytes in buffer to read inet size require %d got: %d", 1, len(f.buf))) + panic(fmt.Errorf("gocql: not enough bytes in buffer to read inet size require %d got: %d", 1, len(f.buf))) } size := f.buf[0] f.buf = f.buf[1:] if !(size == 4 || size == 16) { - panic(fmt.Errorf("invalid IP size: %d", size)) + panic(fmt.Errorf("gocql: invalid IP size: %d", size)) } if len(f.buf) < 1 { - panic(fmt.Errorf("not enough bytes in buffer to read inet require %d got: %d", size, len(f.buf))) + panic(fmt.Errorf("gocql: not enough bytes in buffer to read inet require %d got: %d", size, len(f.buf))) } ip := make([]byte, size) @@ -2024,7 +2022,7 @@ func appendLong(p []byte, n int64) []byte { func (f *framer) writeCustomPayload(customPayload *map[string][]byte) { if len(*customPayload) > 0 { if f.proto < protoVersion4 { - panic("Custom payload is not supported with version V3 or less") + panic("gocql: Custom payload is not supported with version V3 or less") } f.writeBytesMap(*customPayload) } @@ -2112,7 +2110,7 @@ func (f *framer) writeBytesMap(m map[string][]byte) { func (f *framer) prepareModernLayout() error { // Ensure protocol version is V5 or higher if f.proto < protoVersion5 { - panic("Modern layout is not supported with version V4 or less") + panic("gocql: Modern layout is not supported with version V4 or less") } selfContained := true diff --git a/helpers.go b/helpers.go index 823c10689..8884a11d6 100644 --- a/helpers.go +++ b/helpers.go @@ -97,7 +97,7 @@ func goType(t TypeInfo) (reflect.Type, error) { case TypeDuration: return reflect.TypeOf(*new(Duration)), nil default: - return nil, fmt.Errorf("cannot create Go type for unknown CQL type %s", t) + return nil, fmt.Errorf("gocql: cannot create Go type for unknown CQL type %s", t) } } diff --git a/host_source.go b/host_source.go index ffe54cf28..45911f38f 100644 --- a/host_source.go +++ b/host_source.go @@ -36,8 +36,10 @@ import ( ) var ( - ErrCannotFindHost = errors.New("cannot find host") - ErrHostAlreadyExists = errors.New("host already exists") + ErrRefreshWhenStopRequested = errors.New("gocql: could not refresh ring because stop was requested") + ErrCannotFindHost = errors.New("gocql: cannot find host") + ErrHostAlreadyExists = errors.New("gocql: host already exists") + ErrZeroRowsReturned = errors.New("gocql: query returned 0 rows") ) type nodeState int32 @@ -79,24 +81,24 @@ func (c *cassVersion) unmarshal(data []byte) error { v := strings.Split(version, ".") if len(v) < 2 { - return fmt.Errorf("invalid version string: %s", data) + return fmt.Errorf("gocql: invalid version string: %s", data) } var err error c.Major, err = strconv.Atoi(v[0]) if err != nil { - return fmt.Errorf("invalid major version %v: %v", v[0], err) + return fmt.Errorf("gocql: invalid major version %v: %v", v[0], err) } c.Minor, err = strconv.Atoi(v[1]) if err != nil { vMinor := strings.Split(v[1], "-") if len(vMinor) < 2 { - return fmt.Errorf("invalid minor version %v: %v", v[1], err) + return fmt.Errorf("gocql: invalid minor version %v: %v", v[1], err) } c.Minor, err = strconv.Atoi(vMinor[0]) if err != nil { - return fmt.Errorf("invalid minor version %v: %v", v[1], err) + return fmt.Errorf("gocql: invalid minor version %v: %v", v[1], err) } c.Qualifier = v[1][strings.Index(v[1], "-")+1:] return nil @@ -107,11 +109,11 @@ func (c *cassVersion) unmarshal(data []byte) error { if err != nil { vPatch := strings.Split(v[2], "-") if len(vPatch) < 2 { - return fmt.Errorf("invalid patch version %v: %v", v[2], err) + return fmt.Errorf("gocql: invalid patch version %v: %v", v[2], err) } c.Patch, err = strconv.Atoi(vPatch[0]) if err != nil { - return fmt.Errorf("invalid patch version %v: %v", v[2], err) + return fmt.Errorf("gocql: invalid patch version %v: %v", v[2], err) } c.Qualifier = v[2][strings.Index(v[2], "-")+1:] } @@ -183,7 +185,7 @@ type HostInfo struct { func newHostInfo(addr net.IP, port int) (*HostInfo, error) { if !validIpAddr(addr) { - return nil, errors.New("invalid host address") + return nil, errors.New("gocql: invalid host address") } host := &HostInfo{} host.hostname = addr.String() @@ -497,7 +499,7 @@ func (s *Session) newHostInfoFromMap(addr net.IP, port int, row map[string]inter // Given a map that represents a row from either system.local or system.peers // return as much information as we can in *HostInfo func (s *Session) hostInfoFromMap(row map[string]interface{}, host *HostInfo) (*HostInfo, error) { - const assertErrorMsg = "Assertion failed for %s" + const assertErrorMsg = "gocql: Assertion failed for %s" var ok bool // Default to our connected port if the cluster doesn't have port information @@ -610,7 +612,7 @@ func (s *Session) hostInfoFromMap(row map[string]interface{}, host *HostInfo) (* ip, port := s.cfg.translateAddressPort(host.ConnectAddress(), host.port) if !validIpAddr(ip) { - return nil, fmt.Errorf("invalid host address (before translation: %v:%v, after translation: %v:%v)", host.ConnectAddress(), host.port, ip.String(), port) + return nil, fmt.Errorf("gocql: invalid host address (before translation: %v:%v, after translation: %v:%v)", host.ConnectAddress(), host.port, ip.String(), port) } host.connectAddress = ip host.port = port @@ -626,7 +628,7 @@ func (s *Session) hostInfoFromIter(iter *Iter, connectAddress net.IP, defaultPor } if len(rows) == 0 { - return nil, errors.New("query returned 0 rows") + return nil, ErrZeroRowsReturned } host, err := s.newHostInfoFromMap(connectAddress, defaultPort, rows[0]) @@ -652,7 +654,7 @@ func (r *ringDescriber) getLocalHostInfo() (*HostInfo, error) { host, err := r.session.hostInfoFromIter(iter, nil, r.session.cfg.Port) if err != nil { - return nil, fmt.Errorf("could not retrieve local host info: %w", err) + return nil, fmt.Errorf("gocql: could not retrieve local host info: %w", err) } return host, nil } @@ -675,7 +677,7 @@ func (r *ringDescriber) getClusterPeerInfo(localHost *HostInfo) ([]*HostInfo, er rows, err := iter.SliceMap() if err != nil { // TODO(zariel): make typed error - return nil, fmt.Errorf("unable to fetch peer host info: %s", err) + return nil, fmt.Errorf("gocql: unable to fetch peer host info: %w", err) } for _, row := range rows { @@ -738,7 +740,7 @@ func (s *Session) debounceRingRefresh() { func (s *Session) refreshRing() error { err, ok := <-s.ringRefresher.refreshNow() if !ok { - return errors.New("could not refresh ring because stop was requested") + return ErrRefreshWhenStopRequested } return err @@ -764,7 +766,7 @@ func refreshRing(r *ringDescriber) error { newHostID := h.HostID() existing, ok := prevHosts[newHostID] if !ok { - return fmt.Errorf("get existing host=%s from prevHosts: %w", h, ErrCannotFindHost) + return fmt.Errorf("gocql: get existing host=%s from prevHosts: %w", h, ErrCannotFindHost) } if h.connectAddress.Equal(existing.connectAddress) && h.nodeToNodeAddress().Equal(existing.nodeToNodeAddress()) { // no host IP change @@ -774,7 +776,7 @@ func refreshRing(r *ringDescriber) error { // remove old HostInfo (w/old IP) r.session.removeHost(existing) if _, alreadyExists := r.session.ring.addHostIfMissing(h); alreadyExists { - return fmt.Errorf("add new host=%s after removal: %w", h, ErrHostAlreadyExists) + return fmt.Errorf("gocql: add new host=%s after removal: %w", h, ErrHostAlreadyExists) } // add new HostInfo (same hostID, new IP) r.session.startPoolFill(h) diff --git a/marshal.go b/marshal.go index 719a62281..99fefe651 100644 --- a/marshal.go +++ b/marshal.go @@ -47,7 +47,7 @@ var ( ) var ( - ErrorUDTUnavailable = errors.New("UDT are not available on protocols less than 3, please update config") + ErrorUDTUnavailable = errors.New("gocql: UDT are not available on protocols less than 3, please update config") ) // Marshaler is the interface implemented by objects that can marshal @@ -180,7 +180,7 @@ func Marshal(info TypeInfo, value interface{}) ([]byte, error) { } // TODO(tux21b): add the remaining types - return nil, fmt.Errorf("can not marshal %T into %s", value, info) + return nil, marshalErrorf("can not marshal %T into %s", value, info) } // Unmarshal parses the CQL encoded data based on the info parameter that @@ -284,7 +284,7 @@ func Unmarshal(info TypeInfo, data []byte, value interface{}) error { } // TODO(tux21b): add the remaining types - return fmt.Errorf("can not unmarshal %s into %T", info, value) + return unmarshalErrorf("can not unmarshal %s into %T", info, value) } func isNullableValue(value interface{}) bool { @@ -2700,15 +2700,17 @@ func (m MarshalError) Error() string { } func marshalErrorf(format string, args ...interface{}) MarshalError { - return MarshalError(fmt.Sprintf(format, args...)) + return MarshalError(fmt.Sprintf(gocqlErr+format, args...)) } type UnmarshalError string +const gocqlErr = "gocql: " + func (m UnmarshalError) Error() string { return string(m) } func unmarshalErrorf(format string, args ...interface{}) UnmarshalError { - return UnmarshalError(fmt.Sprintf(format, args...)) + return UnmarshalError(fmt.Sprintf(gocqlErr+format, args...)) } diff --git a/metadata.go b/metadata.go index 63e27aeb6..b7a3e9668 100644 --- a/metadata.go +++ b/metadata.go @@ -212,7 +212,7 @@ func columnKindFromSchema(kind string) (ColumnKind, error) { case "static": return ColumnStatic, nil default: - return -1, fmt.Errorf("unknown column kind: %q", kind) + return -1, fmt.Errorf("gocql: unknown column kind: %q", kind) } } @@ -563,7 +563,7 @@ func getKeyspaceMetadata(session *Session, keyspaceName string) (*KeyspaceMetada iter.Scan(&keyspace.DurableWrites, &replication) err := iter.Close() if err != nil { - return nil, fmt.Errorf("error querying keyspace schema: %v", err) + return nil, fmt.Errorf("gocql: error querying keyspace schema: %w", err) } keyspace.StrategyClass = replication["class"] @@ -589,7 +589,7 @@ func getKeyspaceMetadata(session *Session, keyspaceName string) (*KeyspaceMetada iter.Scan(&keyspace.DurableWrites, &keyspace.StrategyClass, &strategyOptionsJSON) err := iter.Close() if err != nil { - return nil, fmt.Errorf("error querying keyspace schema: %v", err) + return nil, fmt.Errorf("gocql: error querying keyspace schema: %w", err) } err = json.Unmarshal(strategyOptionsJSON, &keyspace.StrategyOptions) @@ -732,7 +732,7 @@ func getTableMetadata(session *Session, keyspaceName string) ([]TableMetadata, e err := iter.Close() if err != nil && err != ErrNotFound { - return nil, fmt.Errorf("error querying table schema: %v", err) + return nil, fmt.Errorf("gocql: error querying table schema: %w", err) } return tables, nil @@ -919,7 +919,7 @@ func getColumnMetadata(session *Session, keyspaceName string) ([]ColumnMetadata, } if err != nil && err != ErrNotFound { - return nil, fmt.Errorf("error querying column schema: %v", err) + return nil, fmt.Errorf("gocql: error querying column schema: %w", err) } return columns, nil diff --git a/policies.go b/policies.go index ed0b02f3e..eae88abc2 100644 --- a/policies.go +++ b/policies.go @@ -133,7 +133,7 @@ const ( // ErrUnknownRetryType is returned if the retry policy returns a retry type // unknown to the query executor. -var ErrUnknownRetryType = errors.New("unknown retry type returned by retry policy") +var ErrUnknownRetryType = errors.New("gocql: unknown retry type returned by retry policy") // RetryPolicy interface is used by gocql to determine if a query can be attempted // again after a retryable error has been received. The interface allows gocql diff --git a/session.go b/session.go index ed1a078d3..5e8cb3773 100644 --- a/session.go +++ b/session.go @@ -127,7 +127,7 @@ func addrsToHosts(addrs []string, defaultPort int, logger StdLogger) ([]*HostInf hosts = append(hosts, resolvedHosts...) } if len(hosts) == 0 { - return nil, errors.New("failed to resolve any of the provided hostnames") + return nil, ErrFailedResolveHostnames } return hosts, nil } @@ -141,7 +141,7 @@ func NewSession(cfg ClusterConfig) (*Session, error) { // 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.") + return nil, ErrAuthenticatorAndAuthProvider } if cfg.SerialConsistency > 0 && !cfg.SerialConsistency.isSerial() { @@ -196,7 +196,7 @@ func NewSession(cfg ClusterConfig) (*Session, error) { connCfg, err := connConfig(&s.cfg) if err != nil { //TODO: Return a typed error - return nil, fmt.Errorf("gocql: unable to create session: %v", err) + return nil, fmt.Errorf("gocql: unable to create session: %w", err) } s.connCfg = connCfg @@ -208,7 +208,7 @@ func NewSession(cfg ClusterConfig) (*Session, error) { 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 nil, fmt.Errorf("gocql: unable to create session: %w", err) } } @@ -227,9 +227,9 @@ func (s *Session) init() error { if s.cfg.ProtoVersion == 0 { proto, err := s.control.discoverProtocol(hosts) if err != nil { - return fmt.Errorf("unable to discover protocol version: %v", err) + return fmt.Errorf("gocql: unable to discover protocol version: %w", err) } else if proto == 0 { - return errors.New("unable to discovery protocol version") + return errors.New("gocql: unable to discovery protocol version") } // TODO(zariel): we really only need this in 1 place @@ -2387,22 +2387,22 @@ func (e Error) Error() string { } var ( - ErrNotFound = errors.New("not found") - ErrUnavailable = errors.New("unavailable") - ErrUnsupported = errors.New("feature not supported") - ErrTooManyStmts = errors.New("too many statements") - ErrUseStmt = errors.New("use statements aren't supported. Please see https://github.com/apache/cassandra-gocql-driver for explanation.") - ErrSessionClosed = errors.New("session has been closed") - ErrNoConnections = errors.New("gocql: no hosts available in the pool") - ErrNoKeyspace = errors.New("no keyspace provided") - ErrKeyspaceDoesNotExist = errors.New("keyspace does not exist") - ErrNoMetadata = errors.New("no metadata available") + ErrNotFound = errors.New("gocql: not found") + ErrUnsupported = errors.New("gocql: feature not supported") + ErrTooManyStmts = errors.New("gocql: too many statements") + ErrUseStmt = errors.New("gocql: use statements aren't supported. Please see https://github.com/apache/cassandra-gocql-driver for explanation.") + ErrSessionClosed = errors.New("gocql: session has been closed") + ErrNoConnections = errors.New("gocql: no hosts available in the pool") + ErrNoKeyspace = errors.New("gocql: no keyspace provided") + ErrKeyspaceDoesNotExist = errors.New("gocql: keyspace does not exist") + ErrNoMetadata = errors.New("gocql: no metadata available") + ErrFailedResolveHostnames = errors.New("gocql: failed to resolve any of the provided hostnames") ) type ErrProtocol struct{ error } func NewErrProtocol(format string, args ...interface{}) error { - return ErrProtocol{fmt.Errorf(format, args...)} + return ErrProtocol{fmt.Errorf(gocqlErr+format, args...)} } // BatchSizeMaximum is the maximum number of statements a batch operation can have. diff --git a/token.go b/token.go index 7502ea713..e7b6b0423 100644 --- a/token.go +++ b/token.go @@ -177,7 +177,7 @@ func newTokenRing(partitioner string, hosts []*HostInfo) (*tokenRing, error) { } else if strings.HasSuffix(partitioner, "RandomPartitioner") { tokenRing.partitioner = randomPartitioner{} } else { - return nil, fmt.Errorf("unsupported partitioner '%s'", partitioner) + return nil, fmt.Errorf("gocql: unsupported partitioner '%s'", partitioner) } for _, host := range hosts { diff --git a/topology.go b/topology.go index 2fc38a887..ae2f888ce 100644 --- a/topology.go +++ b/topology.go @@ -74,19 +74,19 @@ func getReplicationFactorFromOpts(val interface{}) (int, error) { switch v := val.(type) { case int: if v < 0 { - return 0, fmt.Errorf("invalid replication_factor %d", v) + return 0, fmt.Errorf("gocql: invalid replication_factor %d", v) } return v, nil case string: n, err := strconv.Atoi(v) if err != nil { - return 0, fmt.Errorf("invalid replication_factor %q: %v", v, err) + return 0, fmt.Errorf("gocql: invalid replication_factor %q: %w", v, err) } else if n < 0 { - return 0, fmt.Errorf("invalid replication_factor %d", n) + return 0, fmt.Errorf("gocql: invalid replication_factor %d", n) } return n, nil default: - return 0, fmt.Errorf("unknown replication_factor type %T", v) + return 0, fmt.Errorf("gocql: unknown replication_factor type %T", v) } } diff --git a/udt_test.go b/udt_test.go index f1980f243..7c7e67d21 100644 --- a/udt_test.go +++ b/udt_test.go @@ -180,7 +180,7 @@ func TestUDT_Proto2error(t *testing.T) { // TODO(zariel): move this to marshal test? _, err := Marshal(NativeType{custom: "org.apache.cassandra.db.marshal.UserType.Type", proto: 2}, 1) if err != ErrorUDTUnavailable { - t.Fatalf("expected %v got %v", ErrUnavailable, err) + t.Fatalf("expected %v got %v", ErrorUDTUnavailable, err) } } diff --git a/uuid.go b/uuid.go index cc5f1c21f..561b4a142 100644 --- a/uuid.go +++ b/uuid.go @@ -95,12 +95,12 @@ func ParseUUID(input string) (UUID, error) { case r >= 'A' && r <= 'F' && j < 32: u[j/2] |= byte(r-'A'+10) << uint(4-j&1*4) default: - return UUID{}, fmt.Errorf("invalid UUID %q", input) + return UUID{}, fmt.Errorf("gocql: invalid UUID %q", input) } j += 1 } if j != 32 { - return UUID{}, fmt.Errorf("invalid UUID %q", input) + return UUID{}, fmt.Errorf("gocql: invalid UUID %q", input) } return u, nil } @@ -323,7 +323,7 @@ func (u UUID) MarshalJSON() ([]byte, error) { func (u *UUID) UnmarshalJSON(data []byte) error { str := strings.Trim(string(data), `"`) if len(str) > 36 { - return fmt.Errorf("invalid JSON UUID %s", str) + return fmt.Errorf("gocql: invalid JSON UUID %s", str) } parsed, err := ParseUUID(str)