// convert2PhysicalPlan implements the LogicalPlan convert2PhysicalPlan interface.
422774
func (p *Limit) convert2PhysicalPlan(prop *requiredProperty) (*physicalPlanInfo, error) {
	info, err := p.getPlanInfo(prop)
	if err != nil {
		return nil, errors.Trace(err)
	}
	if info != nil {
		return info, nil
	}
	info, err = p.GetChildByIndex(0).(LogicalPlan).convert2PhysicalPlan(limitProperty(&Limit{Offset: p.Offset, Count: p.Count}))
	if err != nil {
		return nil, errors.Trace(err)
	}
	info = enforceProperty(prop, info)
	p.storePlanInfo(prop, info)
	return info, nil
}
576052
func convertProtoDeviceSpec(in *proto.DeviceSpec) *DeviceSpec {
	if in == nil {
		return nil
	}

	return &DeviceSpec{
		TaskPath:    in.TaskPath,
		HostPath:    in.HostPath,
		CgroupPerms: in.Permissions,
	}
}
978693
func (*Service) CreatePhysicalHost(c context.Context, req *crimson.CreatePhysicalHostRequest) (*crimson.PhysicalHost, error) {
	return createPhysicalHost(c, req.Host)
}
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
}
358376
func eliminatePhysicalProjection(p PhysicalPlan) PhysicalPlan {
	oldSchema := p.Schema()
	newRoot := doPhysicalProjectionElimination(p)
	newCols := newRoot.Schema().Columns
	for i, oldCol := range oldSchema.Columns {
		oldCol.Index = newCols[i].Index
		newRoot.Schema().Columns[i] = oldCol
	}
	return newRoot
}
284897
func DoOptimize(flag uint64, logic LogicalPlan) (PhysicalPlan, error) {
	logic, err := logicalOptimize(flag, logic)
	if err != nil {
		return nil, err
	}
	if !AllowCartesianProduct.Load() && existsCartesianProduct(logic) {
		return nil, errors.Trace(ErrCartesianProductUnsupported)
	}
	physical, err := physicalOptimize(logic)
	if err != nil {
		return nil, err
	}
	finalPlan := postOptimize(physical)
	return finalPlan, nil
}
820778
func (a *Account) ChangeFrequencyPlan(gatewayID, plan string) error {
	return a.EditGateway(gatewayID, GatewayEdits{
		FrequencyPlan: plan,
	})
}
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
}
709393
func (p *Join) convert2PhysicalPlanSemi(prop *requiredProperty) (*physicalPlanInfo, error) {
	lChild := p.GetChildByIndex(0).(LogicalPlan)
	rChild := p.GetChildByIndex(1).(LogicalPlan)
	allLeft := true
	for _, col := range prop.props {
		if lChild.GetSchema().GetColumnIndex(col.col) == -1 {
			allLeft = false
		}
	}
	join := &PhysicalHashSemiJoin{
		WithAux:         LeftOuterSemiJoin == p.JoinType,
		EqualConditions: p.EqualConditions,
		LeftConditions:  p.LeftConditions,
		RightConditions: p.RightConditions,
		OtherConditions: p.OtherConditions,
		Anti:            p.anti,
	}
	join.ctx = p.ctx
	join.tp = "HashSemiJoin"
	join.allocator = p.allocator
	join.initIDAndContext(p.ctx)
	join.SetSchema(p.schema)
	lProp := prop
	if !allLeft {
		lProp = &requiredProperty{}
	}
	if p.JoinType == SemiJoin {
		lProp = removeLimit(lProp)
	}
	lInfo, err := lChild.convert2PhysicalPlan(lProp)
	if err != nil {
		return nil, errors.Trace(err)
	}
	rInfo, err := rChild.convert2PhysicalPlan(&requiredProperty{})
	if err != nil {
		return nil, errors.Trace(err)
	}
	resultInfo := join.matchProperty(prop, lInfo, rInfo)
	if p.JoinType == SemiJoin {
		resultInfo.count = uint64(float64(lInfo.count) * selectionFactor)
	} else {
		resultInfo.count = lInfo.count
	}
	if !allLeft {
		resultInfo = enforceProperty(prop, resultInfo)
	} else if p.JoinType == SemiJoin {
		resultInfo = enforceProperty(limitProperty(prop.limit), resultInfo)
	}
	return resultInfo, nil
}
520414
func (b *FooJSONBuilder) Convert(orig *Foo) (*FooJSON, error) {
	if orig == nil {
		return nil, nil
	}
	ret := &FooJSON{}

	for _, info := range b._properties {
		if err := info.Encoder(orig, ret); err != nil {
			return nil, err
		}
	}

	return ret, 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),
	}
}
787049
func (s *NetworkService) GetPhysicalNetworkByName(name string, opts ...OptionFunc) (*PhysicalNetwork, int, error) {
	id, count, err := s.GetPhysicalNetworkID(name, opts...)
	if err != nil {
		return nil, count, err
	}

	r, count, err := s.GetPhysicalNetworkByID(id, opts...)
	if err != nil {
		return nil, count, err
	}
	return r, count, nil
}
783211
func ConvertSpaceTemplate(appl application.Application, request *http.Request, st spacetemplate.SpaceTemplate, additional ...SpaceTemplateConvertFunc) *app.SpaceTemplate {

	// template := base64.StdEncoding.EncodeToString([]byte(st.Template))
	i := &app.SpaceTemplate{
		Type: APISpaceTemplates,
		ID:   &st.ID,
		Attributes: &app.SpaceTemplateAttributes{
			Name:         &st.Name,
			CreatedAt:    &st.CreatedAt,
			UpdatedAt:    &st.UpdatedAt,
			Version:      &st.Version,
			Description:  st.Description,
			CanConstruct: &st.CanConstruct,
			// Template:    &template,
		},
		Relationships: &app.SpaceTemplateRelationships{
			Workitemtypes: &app.RelationGeneric{
				Links: &app.GenericLinks{
					Related: ptr.String(rest.AbsoluteURL(request, app.SpaceTemplateHref(st.ID)+"/workitemtypes")),
				},
			},
			Workitemlinktypes: &app.RelationGeneric{
				Links: &app.GenericLinks{
					Related: ptr.String(rest.AbsoluteURL(request, app.SpaceTemplateHref(st.ID)+"/workitemlinktypes")),
				},
			},
			Workitemtypegroups: &app.RelationGeneric{
				Links: &app.GenericLinks{
					Related: ptr.String(rest.AbsoluteURL(request, app.SpaceTemplateHref(st.ID)+"/workitemtypegroups")),
				},
			},
			Workitemboards: &app.RelationGeneric{
				Links: &app.GenericLinks{
					Related: ptr.String(rest.AbsoluteURL(request, app.SpaceTemplateHref(st.ID)+"/workitemboards")),
				},
			},
		},
		Links: &app.GenericLinks{
			Self: ptr.String(rest.AbsoluteURL(request, app.SpaceTemplateHref(st.ID))),
		},
	}

	for _, add := range additional {
		add(appl, request, &st, i)
	}
	return i
}
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
}
903334
func validatePhysicalHostForCreation(h *crimson.PhysicalHost) error {
	switch {
	case h == nil:
		return status.Error(codes.InvalidArgument, "physical host specification is required")
	case h.Name == "":
		return status.Error(codes.InvalidArgument, "hostname is required and must be non-empty")
	case h.Vlan != 0:
		return status.Error(codes.InvalidArgument, "VLAN must not be specified, use IP address instead")
	case h.Machine == "":
		return status.Error(codes.InvalidArgument, "machine is required and must be non-empty")
	case h.Nic == "":
		return status.Error(codes.InvalidArgument, "NIC is required and must be non-empty")
	case h.MacAddress != "":
		return status.Error(codes.InvalidArgument, "MAC address must not be specified, use NIC instead")
	case h.Os == "":
		return status.Error(codes.InvalidArgument, "operating system is required and must be non-empty")
	case h.VmSlots < 0:
		return status.Error(codes.InvalidArgument, "VM slots must be non-negative")
	default:
		_, err := common.ParseIPv4(h.Ipv4)
		if err != nil {
			return status.Errorf(codes.InvalidArgument, "invalid IPv4 address %q", h.Ipv4)
		}
		return nil
	}
}
1199088
func (api *ServerAPI) ChangePlan(serverID int64, plan *sacloud.ProductServer) (*sacloud.Server, error) {
	var (
		method = "PUT"
		uri    = fmt.Sprintf("%s/%d/plan", api.getResourceURL(), serverID)
		body   = &sacloud.ProductServer{}
	)
	body.CPU = plan.CPU
	body.MemoryMB = plan.MemoryMB
	body.Generation = plan.Generation

	return api.request(func(res *sacloud.Response) error {
		return api.baseAPI.request(method, uri, body, res)
	})
}
167671
func (p *Aggregation) convert2PhysicalPlanStream(prop *requiredProperty) (*physicalPlanInfo, error) {
	for _, aggFunc := range p.AggFuncs {
		if aggFunc.GetMode() == expression.FinalMode {
			return &physicalPlanInfo{cost: math.MaxFloat64}, nil
		}
	}
	agg := &PhysicalAggregation{
		AggType:      StreamedAgg,
		AggFuncs:     p.AggFuncs,
		GroupByItems: p.GroupByItems,
	}
	agg.tp = "StreamAgg"
	agg.allocator = p.allocator
	agg.initIDAndContext(p.ctx)
	agg.HasGby = len(p.GroupByItems) > 0
	agg.SetSchema(p.schema)
	// TODO: Consider distinct key.
	info := &physicalPlanInfo{cost: math.MaxFloat64}
	gbyCols := p.groupByCols
	if len(gbyCols) != len(p.GroupByItems) {
		// group by a + b is not interested in any order.
		return info, nil
	}
	isSortKey := make([]bool, len(gbyCols))
	newProp := &requiredProperty{
		props: make([]*columnProp, 0, len(gbyCols)),
	}
	for _, pro := range prop.props {
		idx := p.getGbyColIndex(pro.col)
		if idx == -1 {
			return info, nil
		}
		isSortKey[idx] = true
		// We should add columns in aggregation in order to keep index right.
		newProp.props = append(newProp.props, &columnProp{col: gbyCols[idx], desc: pro.desc})
	}
	newProp.sortKeyLen = len(newProp.props)
	for i, col := range gbyCols {
		if !isSortKey[i] {
			newProp.props = append(newProp.props, &columnProp{col: col})
		}
	}
	childInfo, err := p.children[0].(LogicalPlan).convert2PhysicalPlan(newProp)
	if err != nil {
		return nil, errors.Trace(err)
	}
	info = addPlanToResponse(agg, childInfo)
	info.cost += float64(info.count) * cpuFactor
	info.count = uint64(float64(info.count) * aggFactor)
	return info, nil
}