// convert2PhysicalPlan implements the LogicalPlan convert2PhysicalPlan interface.
431671
func (p *Projection) convert2PhysicalPlan(prop *requiredProperty) (*physicalPlanInfo, error) {
	info, err := p.getPlanInfo(prop)
	if err != nil {
		return nil, errors.Trace(err)
	}
	if info != nil {
		return info, nil
	}
	newProp := &requiredProperty{
		props:      make([]*columnProp, 0, len(prop.props)),
		sortKeyLen: prop.sortKeyLen,
		limit:      prop.limit}
	childSchema := p.GetChildByIndex(0).GetSchema()
	usedCols := make([]bool, childSchema.Len())
	canPassSort := true
loop:
	for _, c := range prop.props {
		idx := p.schema.GetColumnIndex(c.col)
		switch v := p.Exprs[idx].(type) {
		case *expression.Column:
			childIdx := childSchema.GetColumnIndex(v)
			if !usedCols[childIdx] {
				usedCols[childIdx] = true
				newProp.props = append(newProp.props, &columnProp{col: v, desc: c.desc})
			}
		case *expression.ScalarFunction:
			newProp = nil
			canPassSort = false
			break loop
		default:
			newProp.sortKeyLen--
		}
	}
	if !canPassSort {
		return &physicalPlanInfo{cost: math.MaxFloat64}, nil
	}
	info, err = p.GetChildByIndex(0).(LogicalPlan).convert2PhysicalPlan(newProp)
	if err != nil {
		return nil, errors.Trace(err)
	}
	info = addPlanToResponse(p, info)
	p.storePlanInfo(prop, info)
	return info, nil
}
107804
func NewInsufficientPlan(Message string) *InsufficientPlan {
	s := new(InsufficientPlan)
	s.Message = Message
	return s
}
136368
func (p *Aggregation) convert2PhysicalPlanFinalHash(x physicalDistSQLPlan, childInfo *physicalPlanInfo) *physicalPlanInfo {
	agg := &PhysicalAggregation{
		AggType:      FinalAgg,
		AggFuncs:     p.AggFuncs,
		GroupByItems: p.GroupByItems,
	}
	agg.tp = "HashAgg"
	agg.allocator = p.allocator
	agg.initIDAndContext(p.ctx)
	agg.SetSchema(p.schema)
	agg.HasGby = len(p.GroupByItems) > 0
	schema := x.addAggregation(p.ctx, agg)
	if schema.Len() == 0 {
		return nil
	}
	x.(PhysicalPlan).SetSchema(schema)
	info := addPlanToResponse(agg, childInfo)
	info.count = uint64(float64(info.count) * aggFactor)
	// if we build the final aggregation, it must be the best plan.
	info.cost = 0
	return info
}
1137417
func (p *Aggregation) convert2PhysicalPlanCompleteHash(childInfo *physicalPlanInfo) *physicalPlanInfo {
	agg := &PhysicalAggregation{
		AggType:      CompleteAgg,
		AggFuncs:     p.AggFuncs,
		GroupByItems: p.GroupByItems,
	}
	agg.tp = "HashAgg"
	agg.allocator = p.allocator
	agg.initIDAndContext(p.ctx)
	agg.HasGby = len(p.GroupByItems) > 0
	agg.SetSchema(p.schema)
	info := addPlanToResponse(agg, childInfo)
	info.cost += float64(info.count) * memoryFactor
	info.count = uint64(float64(info.count) * aggFactor)
	return info
}
147045
func (p *DataSource) tryToConvert2DummyScan(prop *requiredProperty) (*physicalPlanInfo, error) {
	sel, isSel := p.GetParentByIndex(0).(*Selection)
	if !isSel {
		return nil, nil
	}

	for _, cond := range sel.Conditions {
		if con, ok := cond.(*expression.Constant); ok {
			result, err := expression.EvalBool(con, nil, p.ctx)
			if err != nil {
				return nil, errors.Trace(err)
			}
			if !result {
				dummy := &PhysicalDummyScan{}
				dummy.tp = "Dummy"
				dummy.allocator = p.allocator
				dummy.initIDAndContext(p.ctx)
				dummy.SetSchema(p.schema)
				info := &physicalPlanInfo{p: dummy}
				p.storePlanInfo(prop, info)
				return info, nil
			}
		}
	}
	return nil, nil
}
1212805
func (p *basePhysicalPlan) ToPB(_ sessionctx.Context) (*tipb.Executor, error) {
	return nil, errors.Errorf("plan %s fails converts to PB", p.basePlan.ExplainID())
}
621699
func (s *NetworkService) CreatePhysicalNetwork(p *CreatePhysicalNetworkParams) (*CreatePhysicalNetworkResponse, error) {
	resp, err := s.cs.newRequest("createPhysicalNetwork", p.toURLValues())
	if err != nil {
		return nil, err
	}

	var r CreatePhysicalNetworkResponse
	if err := json.Unmarshal(resp, &r); err != nil {
		return nil, err
	}

	// If we have a async client, we need to wait for the async result
	if s.cs.async {
		b, err := s.cs.GetAsyncJobResult(r.JobID, s.cs.timeout)
		if err != nil {
			if err == AsyncTimeoutErr {
				return &r, err
			}
			return nil, err
		}

		b, err = getRawValue(b)
		if err != nil {
			return nil, err
		}

		if err := json.Unmarshal(b, &r); err != nil {
			return nil, err
		}
	}

	return &r, nil
}
1082499
func createPhysicalHost(c context.Context, h *crimson.PhysicalHost) (*crimson.PhysicalHost, error) {
	if err := validatePhysicalHostForCreation(h); err != nil {
		return nil, err
	}
	ip, _ := common.ParseIPv4(h.Ipv4)
	tx, err := database.Begin(c)
	if err != nil {
		return nil, errors.Annotate(err, "failed to begin transaction").Err()
	}
	defer tx.MaybeRollback(c)

	// TODO(smut): Support the case where the NIC already has a hostname and IP assigned.
	hostnameId, err := model.AssignHostnameAndIP(c, tx, h.Name, ip)
	if err != nil {
		return nil, err
	}

	// By setting hostname_id, machine_id, nic_id, and os_id as FOREIGN KEY and NOT NULL when setting up the
	// database, we can avoid checking if the given values are valid. MySQL will ensure the given values exist.
	res, err := tx.ExecContext(c, `
		INSERT INTO physical_hosts (
			hostname_id,
			machine_id,
			nic_id,
			os_id,
			vm_slots,
			virtual_datacenter,
			description,
			deployment_ticket
		)
		VALUES (
			?,
			(SELECT id FROM machines WHERE name = ?),
			(SELECT n.id FROM machines m, nics n WHERE n.machine_id = m.id AND m.name = ? AND n.name = ? AND n.hostname_id IS NULL),
			(SELECT id FROM oses WHERE name = ?),
			?,
			?,
			?,
			?
		)
	`, hostnameId, h.Machine, h.Machine, h.Nic, h.Os, h.VmSlots, h.VirtualDatacenter, h.Description, h.DeploymentTicket)
	if err != nil {
		switch e, ok := err.(*mysql.MySQLError); {
		case !ok:
			// Type assertion failed.
		case e.Number == mysqlerr.ER_DUP_ENTRY && strings.Contains(e.Message, "'machine_id'"):
			// e.g. "Error 1062: Duplicate entry '1' for key 'machine_id'".
			return nil, status.Errorf(codes.AlreadyExists, "duplicate physical host for machine %q", h.Machine)
		case e.Number == mysqlerr.ER_BAD_NULL_ERROR && strings.Contains(e.Message, "'machine_id'"):
			// e.g. "Error 1048: Column 'machine_id' cannot be null".
			return nil, status.Errorf(codes.NotFound, "machine %q does not exist", h.Machine)
		case e.Number == mysqlerr.ER_BAD_NULL_ERROR && strings.Contains(e.Message, "'nic_id'"):
			// e.g. "Error 1048: Column 'nic_id' cannot be null".
			return nil, status.Errorf(codes.NotFound, "NIC %q of machine %q does not exist or already has a hostname", h.Nic, h.Machine)
		case e.Number == mysqlerr.ER_BAD_NULL_ERROR && strings.Contains(e.Message, "'os_id'"):
			// e.g. "Error 1048: Column 'os_id' cannot be null".
			return nil, status.Errorf(codes.NotFound, "operating system %q does not exist", h.Os)
		}
		return nil, errors.Annotate(err, "failed to create physical host").Err()
	}
	hostId, err := res.LastInsertId()
	if err != nil {
		return nil, errors.Annotate(err, "failed to fetch physical host").Err()
	}

	// Hostname is also stored with the backing NIC.
	_, err = tx.ExecContext(c, `
		UPDATE nics
		SET hostname_id = ?
		WHERE id = (SELECT nic_id FROM physical_hosts WHERE id = ?)
	`, hostnameId, hostId)
	if err != nil {
		return nil, errors.Annotate(err, "failed to update NIC").Err()
	}

	// Physical host state is stored with the backing machine. Update if necessary.
	if h.State != states.State_STATE_UNSPECIFIED {
		_, err := tx.ExecContext(c, `
			UPDATE machines
			SET state = ?
			WHERE name = ?
		`, h.State, h.Machine)
		if err != nil {
			return nil, errors.Annotate(err, "failed to update machine").Err()
		}
	}

	hosts, err := listPhysicalHosts(c, tx, &crimson.ListPhysicalHostsRequest{
		Names: []string{h.Name},
	})
	if err != nil {
		return nil, errors.Annotate(err, "failed to fetch created physical host").Err()
	}

	if err := tx.Commit(); err != nil {
		return nil, errors.Annotate(err, "failed to commit transaction").Err()
	}
	return hosts[0], nil
}
939204
func ConvertAreaSimple(request *http.Request, id interface{}) (*app.GenericData, *app.GenericLinks) {
	t := area.APIStringTypeAreas
	i := fmt.Sprint(id)
	data := &app.GenericData{
		Type: &t,
		ID:   &i,
	}
	relatedURL := rest.AbsoluteURL(request, app.AreaHref(i))
	links := &app.GenericLinks{
		Self:    &relatedURL,
		Related: &relatedURL,
	}
	return data, links
}
708661
func (c unsafeObjectConvertor) ConvertToVersion(in Object, outVersion GroupVersioner) (Object, error) {
	return c.Scheme.UnsafeConvertToVersion(in, outVersion)
}
351088
func (s *Connection) SetPhysicalConnectionRequirements(v *PhysicalConnectionRequirements) *Connection {
	s.PhysicalConnectionRequirements = v
	return s
}
775865
func (s *StackResource) SetPhysicalResourceId(v string) *StackResource {
	s.PhysicalResourceId = &v
	return s
}
428110
func (_class SRClass) SetPhysicalUtilisation(sessionID SessionRef, self SRRef, value int) (_err error) {
	_method := "SR.set_physical_utilisation"
	_sessionIDArg, _err := convertSessionRefToXen(fmt.Sprintf("%s(%s)", _method, "session_id"), sessionID)
	if _err != nil {
		return
	}
	_selfArg, _err := convertSRRefToXen(fmt.Sprintf("%s(%s)", _method, "self"), self)
	if _err != nil {
		return
	}
	_valueArg, _err := convertIntToXen(fmt.Sprintf("%s(%s)", _method, "value"), value)
	if _err != nil {
		return
	}
	_, _err =  _class.client.APICall(_method, _sessionIDArg, _selfArg, _valueArg)
	return
}
16425
func ConvertSpaceToModel(appSpace app.Space) space.Space {
	modelSpace := space.Space{}

	if appSpace.ID != nil {
		modelSpace.ID = *appSpace.ID
	}
	if appSpace.Attributes != nil {
		if appSpace.Attributes.CreatedAt != nil {
			modelSpace.CreatedAt = *appSpace.Attributes.CreatedAt
		}
		if appSpace.Attributes.UpdatedAt != nil {
			modelSpace.UpdatedAt = *appSpace.Attributes.UpdatedAt
		}
		if appSpace.Attributes.Version != nil {
			modelSpace.Version = *appSpace.Attributes.Version
		}
		if appSpace.Attributes.Name != nil {
			modelSpace.Name = *appSpace.Attributes.Name
		}
		if appSpace.Attributes.Description != nil {
			modelSpace.Description = *appSpace.Attributes.Description
		}
	}
	if appSpace.Relationships != nil && appSpace.Relationships.OwnedBy != nil &&
		appSpace.Relationships.OwnedBy.Data != nil && appSpace.Relationships.OwnedBy.Data.ID != nil {
		modelSpace.OwnerID = *appSpace.Relationships.OwnedBy.Data.ID
	}
	if appSpace.Relationships != nil && appSpace.Relationships.SpaceTemplate != nil &&
		appSpace.Relationships.SpaceTemplate.Data != nil {
		modelSpace.SpaceTemplateID = appSpace.Relationships.SpaceTemplate.Data.ID
	}
	return modelSpace
}
288060
func convertConstraints2(cons constraints.Value) gomaasapi.AllocateMachineArgs {
	params := gomaasapi.AllocateMachineArgs{}
	if cons.Arch != nil {
		params.Architecture = *cons.Arch
	}
	if cons.CpuCores != nil {
		params.MinCPUCount = int(*cons.CpuCores)
	}
	if cons.Mem != nil {
		params.MinMemory = int(*cons.Mem)
	}
	if cons.Tags != nil {
		positives, negatives := parseDelimitedValues(*cons.Tags)
		if len(positives) > 0 {
			params.Tags = positives
		}
		if len(negatives) > 0 {
			params.NotTags = negatives
		}
	}
	if cons.CpuPower != nil {
		logger.Warningf("ignoring unsupported constraint 'cpu-power'")
	}
	return params
}
498150
func listPhysicalHosts(c context.Context, q database.QueryerContext, req *crimson.ListPhysicalHostsRequest) ([]*crimson.PhysicalHost, error) {
	mac48s, err := parseMAC48s(req.MacAddresses)
	if err != nil {
		return nil, err
	}
	ipv4s, err := parseIPv4s(req.Ipv4S)
	if err != nil {
		return nil, err
	}

	stmt := squirrel.Select(
		"hp.name",
		"hp.vlan_id",
		"m.name",
		"n.name",
		"n.mac_address",
		"o.name",
		"h.vm_slots",
		"h.virtual_datacenter",
		"h.description",
		"h.deployment_ticket",
		"i.ipv4",
		"m.state",
	)
	stmt = stmt.From("(physical_hosts h, hostnames hp, machines m, nics n, oses o, ips i)")
	if len(req.Datacenters) > 0 {
		stmt = stmt.Join("racks r ON m.rack_id = r.id")
		stmt = stmt.Join("datacenters d ON r.datacenter_id = d.id")
	} else if len(req.Racks) > 0 {
		stmt = stmt.Join("racks r ON m.rack_id = r.id")
	}
	if len(req.Platforms) > 0 {
		stmt = stmt.Join("platforms p ON m.platform_id = p.id")
	}
	stmt = stmt.Where("n.hostname_id = hp.id").
		Where("h.machine_id = m.id").
		Where("h.nic_id = n.id").
		Where("h.os_id = o.id").
		Where("i.hostname_id = hp.id")
	stmt = selectInString(stmt, "hp.name", req.Names)
	stmt = selectInInt64(stmt, "hp.vlan_id", req.Vlans)
	stmt = selectInString(stmt, "m.name", req.Machines)
	stmt = selectInString(stmt, "n.name", req.Nics)
	stmt = selectInUint64(stmt, "n.mac_address", mac48s)
	stmt = selectInString(stmt, "o.name", req.Oses)
	stmt = selectInString(stmt, "h.virtual_datacenter", req.VirtualDatacenters)
	stmt = selectInInt64(stmt, "i.ipv4", ipv4s)
	stmt = selectInState(stmt, "m.state", req.States)
	stmt = selectInString(stmt, "d.name", req.Datacenters)
	stmt = selectInString(stmt, "r.name", req.Racks)
	stmt = selectInString(stmt, "p.name", req.Platforms)
	query, args, err := stmt.ToSql()
	if err != nil {
		return nil, errors.Annotate(err, "failed to generate statement").Err()
	}

	rows, err := q.QueryContext(c, query, args...)
	if err != nil {
		return nil, errors.Annotate(err, "failed to fetch physical hosts").Err()
	}
	defer rows.Close()
	var hosts []*crimson.PhysicalHost
	for rows.Next() {
		h := &crimson.PhysicalHost{}
		var mac48 common.MAC48
		var ipv4 common.IPv4
		if err = rows.Scan(
			&h.Name,
			&h.Vlan,
			&h.Machine,
			&h.Nic,
			&mac48,
			&h.Os,
			&h.VmSlots,
			&h.VirtualDatacenter,
			&h.Description,
			&h.DeploymentTicket,
			&ipv4,
			&h.State,
		); err != nil {
			return nil, errors.Annotate(err, "failed to fetch physical host").Err()
		}
		h.MacAddress = mac48.String()
		h.Ipv4 = ipv4.String()
		hosts = append(hosts, h)
	}
	return hosts, nil
}
194013
func convertStructContainerReservation(in *ContainerReservation) *proto.ContainerReservation {
	if in == nil {
		return nil
	}

	return &proto.ContainerReservation{
		Envs:    in.Envs,
		Mounts:  convertStructMounts(in.Mounts),
		Devices: convertStructDeviceSpecs(in.Devices),
	}
}