// handleOtherComparableSubq handles the queries like < any, < max, etc. For example, if the query is t.id < any (select s.id from s),
// it will be rewrote to t.id < (select max(s.id) from s).
164737
func (er *expressionRewriter) handleOtherComparableSubq(lexpr, rexpr expression.Expression, np LogicalPlan, useMin bool, cmpFunc string, all bool) {
	plan4Agg := LogicalAggregation{}.Init(er.ctx)
	plan4Agg.SetChildren(np)

	// Create a "max" or "min" aggregation.
	funcName := ast.AggFuncMax
	if useMin {
		funcName = ast.AggFuncMin
	}
	funcMaxOrMin := aggregation.NewAggFuncDesc(er.ctx, funcName, []expression.Expression{rexpr}, false)

	// Create a column and append it to the schema of that aggregation.
	colMaxOrMin := &expression.Column{
		ColName:  model.NewCIStr("agg_Col_0"),
		UniqueID: er.ctx.GetSessionVars().AllocPlanColumnID(),
		RetType:  funcMaxOrMin.RetTp,
	}
	schema := expression.NewSchema(colMaxOrMin)

	plan4Agg.SetSchema(schema)
	plan4Agg.AggFuncs = []*aggregation.AggFuncDesc{funcMaxOrMin}

	cond := expression.NewFunctionInternal(er.ctx, cmpFunc, types.NewFieldType(mysql.TypeTiny), lexpr, colMaxOrMin)
	er.buildQuantifierPlan(plan4Agg, cond, lexpr, rexpr, all)
}
942898
func (u *user) compareSubkeys(subkeys []keybase1.KID) error {
	return compareKeys(subkeys, u.subkeys)
}
523670
func QueryHandler(repo eh.ReadRepo) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.Method != "GET" {
			http.Error(w, "unsuported method: "+r.Method, http.StatusMethodNotAllowed)
			return
		}

		var (
			data interface{}
			err  error
		)
		// If there is a trailing slash in the URL we return all items,
		// otherwise we try to parse an ID from the last part to return one item.
		_, idStr := path.Split(r.URL.Path)
		if idStr == "" {
			if data, err = repo.FindAll(r.Context()); err != nil {
				http.Error(w, "could not find items: "+err.Error(), http.StatusInternalServerError)
				return
			}
		} else {
			id, err := uuid.Parse(idStr)
			if err != nil {
				http.Error(w, "could not parse ID: "+err.Error(), http.StatusBadRequest)
				return
			}

			if data, err = repo.Find(r.Context(), id); err != nil {
				if rrErr, ok := err.(eh.RepoError); ok && rrErr.Err == eh.ErrEntityNotFound {
					http.Error(w, "could not find item", http.StatusNotFound)
					return
				}

				http.Error(w, "could not find item: "+err.Error(), http.StatusInternalServerError)
				return
			}
		}

		b, err := json.Marshal(data)
		if err != nil {
			http.Error(w, "could not encode result: "+err.Error(), http.StatusInternalServerError)
			return
		}
		w.Write(b)
	})
}
1307539
func (m *SubscriptionManager) subscriptionHandler() {
	defer m.wg.Done()

	for {
		select {
		// A new subscription request has been received from a client.
		case msg := <-m.newSubscriptions:
			msg.errChan <- m.handleNewSubscription(msg)

		// A request to cancel an existing subscription has been
		// received from a client.
		case msg := <-m.cancelSubscriptions:
			m.handleCancelSubscription(msg)

		// A new block notification for the tip of the chain has been
		// received from the backing NotificationSource.
		case ntfn, ok := <-m.ntfnSource.Notifications():
			if !ok {
				log.Warn("Block source is unable to deliver " +
					"new updates")
				return
			}

			m.notifySubscribers(ntfn)

		case <-m.quit:
			return
		}
	}
}
1220554
func (sm *ServeMux) HandlerFunc(handler func(http.ResponseWriter, *http.Request) error) http.Handler {
	if sm.recoverPanic {
		return sm.MWErrorPanic(handler)
	}
	return sm.MWError(handler)
}
1189087
func isRemoteQSub(sub *subscription) bool {
	return sub != nil && sub.queue != nil && sub.client != nil && sub.client.kind == ROUTER
}
1053477
func (c *Conn) handleNextCommand(handler Handler) error {
	c.sequence = 0
	data, err := c.readEphemeralPacket()
	if err != nil {
		// Don't log EOF errors. They cause too much spam.
		// Note the EOF detection is not 100%
		// guaranteed, in the case where the client
		// connection is already closed before we call
		// 'readEphemeralPacket'.  This is a corner
		// case though, and very unlikely to happen,
		// and the only downside is we log a bit more then.
		if err != io.EOF {
			log.Errorf("Error reading packet from %s: %v", c, err)
		}
		return err
	}

	switch data[0] {
	case ComQuit:
		c.recycleReadPacket()
		return errors.New("ComQuit")
	case ComInitDB:
		db := c.parseComInitDB(data)
		c.recycleReadPacket()
		c.SchemaName = db
		if err := c.writeOKPacket(0, 0, c.StatusFlags, 0); err != nil {
			log.Errorf("Error writing ComInitDB result to %s: %v", c, err)
			return err
		}
	case ComQuery:
		// flush is called at the end of this block.
		// We cannot encapsulate it with a defer inside a func because
		// we have to return from this func if it fails.
		c.startWriterBuffering()

		queryStart := time.Now()
		query := c.parseComQuery(data)
		c.recycleReadPacket()

		var queries []string
		if c.Capabilities&CapabilityClientMultiStatements != 0 {
			queries, err = sqlparser.SplitStatementToPieces(query)
			if err != nil {
				log.Errorf("Conn %v: Error splitting query: %v", c, err)
				if werr := c.writeErrorPacketFromError(err); werr != nil {
					// If we can't even write the error, we're done.
					log.Errorf("Conn %v: Error writing query error: %v", c, werr)
					return werr
				}
			}
		} else {
			queries = []string{query}
		}
		for index, sql := range queries {
			more := false
			if index != len(queries)-1 {
				more = true
			}
			if err := c.execQuery(sql, handler, more); err != nil {
				return err
			}
		}

		timings.Record(queryTimingKey, queryStart)

		if err := c.flush(); err != nil {
			log.Errorf("Conn %v: Flush() failed: %v", c.ID(), err)
			return err
		}

	case ComPing:
		c.recycleReadPacket()
		// Return error if listener was shut down and OK otherwise
		if c.listener.isShutdown() {
			if err := c.writeErrorPacket(ERServerShutdown, SSServerShutdown, "Server shutdown in progress"); err != nil {
				log.Errorf("Error writing ComPing error to %s: %v", c, err)
				return err
			}
		} else {
			if err := c.writeOKPacket(0, 0, c.StatusFlags, 0); err != nil {
				log.Errorf("Error writing ComPing result to %s: %v", c, err)
				return err
			}
		}
	case ComSetOption:
		operation, ok := c.parseComSetOption(data)
		c.recycleReadPacket()
		if ok {
			switch operation {
			case 0:
				c.Capabilities |= CapabilityClientMultiStatements
			case 1:
				c.Capabilities &^= CapabilityClientMultiStatements
			default:
				log.Errorf("Got unhandled packet (ComSetOption default) from client %v, returning error: %v", c.ConnectionID, data)
				if err := c.writeErrorPacket(ERUnknownComError, SSUnknownComError, "error handling packet: %v", data); err != nil {
					log.Errorf("Error writing error packet to client: %v", err)
					return err
				}
			}
			if err := c.writeEndResult(false, 0, 0, 0); err != nil {
				log.Errorf("Error writeEndResult error %v ", err)
				return err
			}
		} else {
			log.Errorf("Got unhandled packet (ComSetOption else) from client %v, returning error: %v", c.ConnectionID, data)
			if err := c.writeErrorPacket(ERUnknownComError, SSUnknownComError, "error handling packet: %v", data); err != nil {
				log.Errorf("Error writing error packet to client: %v", err)
				return err
			}
		}
	default:
		log.Errorf("Got unhandled packet (default) from %s, returning error: %v", c, data)
		c.recycleReadPacket()
		if err := c.writeErrorPacket(ERUnknownComError, SSUnknownComError, "command handling not implemented yet: %v", data[0]); err != nil {
			log.Errorf("Error writing error packet to %s: %s", c, err)
			return err
		}
	}

	return nil
}
442216
func (p *PriorityQueue) flushUnschedulableQLeftover() {
	p.lock.Lock()
	defer p.lock.Unlock()

	var podsToMove []*podInfo
	currentTime := p.clock.Now()
	for _, pInfo := range p.unschedulableQ.podInfoMap {
		lastScheduleTime := pInfo.timestamp
		if currentTime.Sub(lastScheduleTime) > unschedulableQTimeInterval {
			podsToMove = append(podsToMove, pInfo)
		}
	}

	if len(podsToMove) > 0 {
		p.movePodsToActiveQueue(podsToMove)
	}
}
193067
func QueryTypeEqual(o1, o2 *QueryTypeOption) bool {
	if o1 != nil {
		return o1.Equal(o2)
	}
	if o2 != nil {
		return o2.Equal(o1)
	}
	return true
}
245647
func (f QueryHandlerFunc) ServeQuery(ctx context.Context, res QueryResponse, req *QueryRequest) error {
	return f(ctx, res, req)
}
1311301
func (c *Client) handleAuthAck(auth *AuthEvent) {
	if c.Authentication == SuccessfulAuthentication {
		err := c.subscriptions.activate(auth.SubID, auth.ChanID)
		if err != nil {
			c.log.Errorf("could not activate auth subscription: %s", err.Error())
		}
		c.checkResubscription()
	} else {
		c.log.Error("authentication failed")
	}
}
1178440
func (db *DB) HandleQuery(c *mysql.Conn, query string, callback func(*sqltypes.Result) error) error {
	if db.AllowAll {
		return callback(&sqltypes.Result{})
	}

	if db.t != nil {
		db.t.Logf("ComQuery(%v): client %v: %v", db.name, c.ConnectionID, query)
	}
	if db.orderMatters {
		result, err := db.comQueryOrdered(query)
		if err != nil {
			return err
		}
		return callback(result)
	}

	key := strings.ToLower(query)
	db.mu.Lock()
	defer db.mu.Unlock()
	db.queryCalled[key]++

	// Check if we should close the connection and provoke errno 2013.
	if db.shouldClose {
		c.Close()
		callback(&sqltypes.Result{})
		return nil
	}

	// Using special handling for 'SET NAMES utf8'.  The driver
	// may send this at connection time, and we don't want it to
	// interfere.
	if key == "set names utf8" {
		callback(&sqltypes.Result{})
		return nil
	}

	// check if we should reject it.
	if err, ok := db.rejectedData[key]; ok {
		return err
	}

	// Check explicit queries from AddQuery().
	result, ok := db.data[key]
	if ok {
		if f := result.BeforeFunc; f != nil {
			f()
		}
		return callback(result.Result)
	}

	// Check query patterns from AddQueryPattern().
	for _, pat := range db.patternData {
		if pat.expr.MatchString(query) {
			return callback(pat.result)
		}
	}

	// Nothing matched.
	return fmt.Errorf("query: '%s' is not supported on %v", query, db.name)
}
456626
func (s *Server) HandleConnz(w http.ResponseWriter, r *http.Request) {
	sortOpt := SortOpt(r.URL.Query().Get("sort"))
	auth, err := decodeBool(w, r, "auth")
	if err != nil {
		return
	}
	subs, err := decodeBool(w, r, "subs")
	if err != nil {
		return
	}
	offset, err := decodeInt(w, r, "offset")
	if err != nil {
		return
	}
	limit, err := decodeInt(w, r, "limit")
	if err != nil {
		return
	}
	cid, err := decodeUint64(w, r, "cid")
	if err != nil {
		return
	}
	state, err := decodeState(w, r)
	if err != nil {
		return
	}

	connzOpts := &ConnzOptions{
		Sort:          sortOpt,
		Username:      auth,
		Subscriptions: subs,
		Offset:        offset,
		Limit:         limit,
		CID:           cid,
		State:         state,
	}

	s.mu.Lock()
	s.httpReqStats[ConnzPath]++
	s.mu.Unlock()

	c, err := s.Connz(connzOpts)
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		w.Write([]byte(err.Error()))
		return
	}
	b, err := json.MarshalIndent(c, "", "  ")
	if err != nil {
		s.Errorf("Error marshaling response to /connz request: %v", err)
	}

	// Handle response
	ResponseHandler(w, r, b)
}
1065659
func isComparable(t reflect.Type) bool {
	switch t.Kind() {
	case reflect.Array:
		return isComparable(t.Elem())

	case reflect.Struct:
		for i := 0; i < t.NumField(); i++ {
			if !isComparable(t.Field(i).Type) {
				return false
			}
		}

		return true

	case reflect.Slice, reflect.Map, reflect.Func:
		return false
	}

	return true
}
720918
func (h *handler) handleSubscriptionResult(msg *jsonrpcMessage) {
	var result subscriptionResult
	if err := json.Unmarshal(msg.Params, &result); err != nil {
		h.log.Debug("Dropping invalid subscription message")
		return
	}
	if h.clientSubs[result.ID] != nil {
		h.clientSubs[result.ID].deliver(result.Result)
	}
}
641023
func (sc *StatementContext) HandleOverflow(err error, warnErr error) error {
	if err == nil {
		return nil
	}

	if sc.OverflowAsWarning {
		sc.AppendWarning(warnErr)
		return nil
	}
	return err
}
1354258
func (s *Server) handleQuery(query *dns.Msg, from net.Addr) error {
	if query.Opcode != dns.OpcodeQuery {
		// "In both multicast query and multicast response messages, the OPCODE MUST
		// be zero on transmission (only standard queries are currently supported
		// over multicast).  Multicast DNS messages received with an OPCODE other
		// than zero MUST be silently ignored."  Note: OpcodeQuery == 0
		return fmt.Errorf("mdns: received query with non-zero Opcode %v: %v", query.Opcode, *query)
	}
	if query.Rcode != 0 {
		// "In both multicast query and multicast response messages, the Response
		// Code MUST be zero on transmission.  Multicast DNS messages received with
		// non-zero Response Codes MUST be silently ignored."
		return fmt.Errorf("mdns: received query with non-zero Rcode %v: %v", query.Rcode, *query)
	}

	// TODO(reddaly): Handle "TC (Truncated) Bit":
	//    In query messages, if the TC bit is set, it means that additional
	//    Known-Answer records may be following shortly.  A responder SHOULD
	//    record this fact, and wait for those additional Known-Answer records,
	//    before deciding whether to respond.  If the TC bit is clear, it means
	//    that the querying host has no additional Known Answers.
	if query.Truncated {
		return fmt.Errorf("[ERR] mdns: support for DNS requests with high truncated bit not implemented: %v", *query)
	}

	var unicastAnswer, multicastAnswer []dns.RR

	// Handle each question
	for _, q := range query.Question {
		mrecs, urecs := s.handleQuestion(q)
		multicastAnswer = append(multicastAnswer, mrecs...)
		unicastAnswer = append(unicastAnswer, urecs...)
	}

	// See section 18 of RFC 6762 for rules about DNS headers.
	resp := func(unicast bool) *dns.Msg {
		// 18.1: ID (Query Identifier)
		// 0 for multicast response, query.Id for unicast response
		id := uint16(0)
		if unicast {
			id = query.Id
		}

		var answer []dns.RR
		if unicast {
			answer = unicastAnswer
		} else {
			answer = multicastAnswer
		}
		if len(answer) == 0 {
			return nil
		}

		return &dns.Msg{
			MsgHdr: dns.MsgHdr{
				Id: id,

				// 18.2: QR (Query/Response) Bit - must be set to 1 in response.
				Response: true,

				// 18.3: OPCODE - must be zero in response (OpcodeQuery == 0)
				Opcode: dns.OpcodeQuery,

				// 18.4: AA (Authoritative Answer) Bit - must be set to 1
				Authoritative: true,

				// The following fields must all be set to 0:
				// 18.5: TC (TRUNCATED) Bit
				// 18.6: RD (Recursion Desired) Bit
				// 18.7: RA (Recursion Available) Bit
				// 18.8: Z (Zero) Bit
				// 18.9: AD (Authentic Data) Bit
				// 18.10: CD (Checking Disabled) Bit
				// 18.11: RCODE (Response Code)
			},
			// 18.12 pertains to questions (handled by handleQuestion)
			// 18.13 pertains to resource records (handled by handleQuestion)

			// 18.14: Name Compression - responses should be compressed (though see
			// caveats in the RFC), so set the Compress bit (part of the dns library
			// API, not part of the DNS packet) to true.
			Compress: true,

			Answer: answer,
		}
	}

	if s.config.LogEmptyResponses && len(multicastAnswer) == 0 && len(unicastAnswer) == 0 {
		questions := make([]string, len(query.Question))
		for i, q := range query.Question {
			questions[i] = q.Name
		}
		log.Printf("no responses for query with questions: %s", strings.Join(questions, ", "))
	}

	if mresp := resp(false); mresp != nil {
		if err := s.sendResponse(mresp, from, false); err != nil {
			return fmt.Errorf("mdns: error sending multicast response: %v", err)
		}
	}
	if uresp := resp(true); uresp != nil {
		if err := s.sendResponse(uresp, from, true); err != nil {
			return fmt.Errorf("mdns: error sending unicast response: %v", err)
		}
	}
	return nil
}