// buildView builds a view definition given an attribute and a corresponding media type.
491159
func buildView(name string, mt *design.MediaTypeDefinition, at *design.AttributeDefinition) (*design.ViewDefinition, error) {
	if at.Type == nil || !at.Type.IsObject() {
		return nil, fmt.Errorf("invalid view DSL")
	}
	o := at.Type.ToObject()
	if o != nil {
		mto := mt.Type.ToObject()
		if mto == nil {
			mto = mt.Type.ToArray().ElemType.Type.ToObject()
		}
		for n, cat := range o {
			if existing, ok := mto[n]; ok {
				dup := design.DupAtt(existing)
				dup.View = cat.View
				o[n] = dup
			} else if n != "links" {
				return nil, fmt.Errorf("unknown attribute %#v", n)
			}
		}
	}
	return &design.ViewDefinition{
		AttributeDefinition: at,
		Name:                name,
		Parent:              mt,
	}, nil
}
1290078
func (m *DB) View(fn func(*bolt.Tx) error) error {
	return m.db.View(fn)
}
66972
func (c *Calcium) BuildImage(ctx context.Context, opts *enginetypes.BuildOptions) (chan *types.BuildImageMessage, error) {
	// Disable build API if scm not set
	if c.source == nil {
		return nil, types.ErrSCMNotSet
	}
	// select nodes
	node, err := c.selectBuildNode(ctx)
	if err != nil {
		return nil, err
	}
	log.Infof("[BuildImage] Building image at pod %s node %s", node.Podname, node.Name)
	// get refs
	refs := node.Engine.BuildRefs(ctx, opts.Name, opts.Tags)
	// support raw build
	buildContent := opts.Tar
	if opts.Builds != nil {
		buildContent, err = node.Engine.BuildContent(ctx, c.source, opts)
		if err != nil {
			return nil, err
		}
	}

	return c.doBuildImage(ctx, buildContent, node, refs)
}
50113
func (b *PlanBuilder) BuildDataSourceFromView(dbName model.CIStr, tableInfo *model.TableInfo) (LogicalPlan, error) {
	charset, collation := b.ctx.GetSessionVars().GetCharsetInfo()
	viewParser := parser.New()
	viewParser.EnableWindowFunc(b.ctx.GetSessionVars().EnableWindowFunction)
	selectNode, err := viewParser.ParseOneStmt(tableInfo.View.SelectStmt, charset, collation)
	if err != nil {
		return nil, err
	}
	originalVisitInfo := b.visitInfo
	b.visitInfo = make([]visitInfo, 0)
	selectLogicalPlan, err := b.Build(selectNode)
	if err != nil {
		return nil, err
	}

	if tableInfo.View.Security == model.SecurityDefiner {
		if pm := privilege.GetPrivilegeManager(b.ctx); pm != nil {
			for _, v := range b.visitInfo {
				if !pm.RequestVerificationWithUser(v.db, v.table, v.column, v.privilege, tableInfo.View.Definer) {
					return nil, ErrViewInvalid.GenWithStackByArgs(dbName.O, tableInfo.Name.O)
				}
			}
		}
		b.visitInfo = b.visitInfo[:0]
	}
	b.visitInfo = append(originalVisitInfo, b.visitInfo...)

	projSchema := expression.NewSchema(make([]*expression.Column, 0, len(tableInfo.View.Cols))...)
	projExprs := make([]expression.Expression, 0, len(tableInfo.View.Cols))
	for i := range tableInfo.View.Cols {
		col := selectLogicalPlan.Schema().FindColumnByName(tableInfo.View.Cols[i].L)
		if col == nil {
			return nil, ErrViewInvalid.GenWithStackByArgs(dbName.O, tableInfo.Name.O)
		}
		projSchema.Append(&expression.Column{
			UniqueID:    b.ctx.GetSessionVars().AllocPlanColumnID(),
			TblName:     col.TblName,
			OrigTblName: col.OrigTblName,
			ColName:     tableInfo.Cols()[i].Name,
			OrigColName: tableInfo.View.Cols[i],
			DBName:      col.DBName,
			RetType:     col.GetType(),
		})
		projExprs = append(projExprs, col)
	}

	projUponView := LogicalProjection{Exprs: projExprs}.Init(b.ctx)
	projUponView.SetChildren(selectLogicalPlan.(LogicalPlan))
	projUponView.SetSchema(projSchema)
	return projUponView, nil
}
908190
func (m *MediaTypeDefinition) IterateViews(it ViewIterator) error {
	o := m.Views
	// gather names and sort them
	names := make([]string, len(o))
	i := 0
	for n := range o {
		names[i] = n
		i++
	}
	sort.Strings(names)
	// iterate
	for _, n := range names {
		if err := it(o[n]); err != nil {
			return err
		}
	}
	return nil
}
26788
func buildCodec(st map[string]*Codec, enclosingNamespace string, schema interface{}) (*Codec, error) {
	switch schemaType := schema.(type) {
	case map[string]interface{}:
		return buildCodecForTypeDescribedByMap(st, enclosingNamespace, schemaType)
	case string:
		return buildCodecForTypeDescribedByString(st, enclosingNamespace, schemaType, nil)
	case []interface{}:
		return buildCodecForTypeDescribedBySlice(st, enclosingNamespace, schemaType)
	default:
		return nil, fmt.Errorf("unknown schema type: %T", schema)
	}
}
984059
func (d *database) CreateArangoSearchView(ctx context.Context, name string, options *ArangoSearchViewProperties) (ArangoSearchView, error) {
	input := struct {
		Name                       string   `json:"name"`
		Type                       ViewType `json:"type"`
		ArangoSearchViewProperties          // `json:"properties"`
	}{
		Name: name,
		Type: ViewTypeArangoSearch,
	}
	if options != nil {
		input.ArangoSearchViewProperties = *options
	}
	req, err := d.conn.NewRequest("POST", path.Join(d.relPath(), "_api/view"))
	if err != nil {
		return nil, WithStack(err)
	}
	if _, err := req.SetBody(input); err != nil {
		return nil, WithStack(err)
	}
	applyContextSettings(ctx, req)
	resp, err := d.conn.Do(ctx, req)
	if err != nil {
		return nil, WithStack(err)
	}
	if err := resp.CheckStatus(201); err != nil {
		return nil, WithStack(err)
	}
	view, err := newView(name, input.Type, d)
	if err != nil {
		return nil, WithStack(err)
	}
	result, err := view.ArangoSearchView()
	if err != nil {
		return nil, WithStack(err)
	}

	return result, nil
}
1166558
func (s *Service) UpdateView(ctx context.Context, id platform.ID, upd platform.ViewUpdate) (*platform.View, error) {
	c, err := s.FindViewByID(ctx, id)
	if err != nil {
		return nil, &platform.Error{
			Err: err,
			Op:  OpPrefix + platform.OpUpdateView,
		}
	}

	if upd.Name != nil {
		c.Name = *upd.Name
	}

	if upd.Properties != nil {
		c.Properties = upd.Properties
	}

	s.viewKV.Store(c.ID.String(), c)

	return c, nil
}
441453
func (app *Application) RegisterView(viewEngine view.Engine) {
	app.view.Register(viewEngine)
}
315533
func newView(name string, viewType ViewType, db *database) (View, error) {
	if name == "" {
		return nil, WithStack(InvalidArgumentError{Message: "name is empty"})
	}
	if viewType == "" {
		return nil, WithStack(InvalidArgumentError{Message: "viewType is empty"})
	}
	if db == nil {
		return nil, WithStack(InvalidArgumentError{Message: "db is nil"})
	}
	return &view{
		name:     name,
		viewType: viewType,
		db:       db,
		conn:     db.conn,
	}, nil
}
261969
func (p *Pages) AddView(addr string, v Views) {
	v.UseHistory(p.HistoryProvider)
	p.UseState(addr, v)
}
724966
func (s *Service) DeleteView(ctx context.Context, id platform.ID) error {
	if _, err := s.FindViewByID(ctx, id); err != nil {
		return &platform.Error{
			Err: err,
			Op:  OpPrefix + platform.OpDeleteView,
		}
	}
	s.viewKV.Delete(id.String())
	return nil
}
871839
func (t Texture) View() (float32, float32, float32, float32) {
	return t.viewport.Min.X, t.viewport.Min.Y, t.viewport.Max.X, t.viewport.Max.Y
}
666095
func (s *IndicesGetTemplateService) buildURL() (string, url.Values, error) {
	// Build URL
	var err error
	var path string
	if len(s.name) > 0 {
		path, err = uritemplates.Expand("/_template/{name}", map[string]string{
			"name": strings.Join(s.name, ","),
		})
	} else {
		path = "/_template"
	}
	if err != nil {
		return "", url.Values{}, err
	}

	// Add query string parameters
	params := url.Values{}
	if s.pretty {
		params.Set("pretty", "true")
	}
	if s.flatSettings != nil {
		params.Set("flat_settings", fmt.Sprintf("%v", *s.flatSettings))
	}
	if s.local != nil {
		params.Set("local", fmt.Sprintf("%v", *s.local))
	}
	return path, params, nil
}
145172
func (mb *configManifestBuilder) Build(ctx context.Context) (m distribution.Manifest, err error) {
	type imageRootFS struct {
		Type      string   `json:"type"`
		DiffIDs   []diffID `json:"diff_ids,omitempty"`
		BaseLayer string   `json:"base_layer,omitempty"`
	}

	type imageHistory struct {
		Created    time.Time `json:"created"`
		Author     string    `json:"author,omitempty"`
		CreatedBy  string    `json:"created_by,omitempty"`
		Comment    string    `json:"comment,omitempty"`
		EmptyLayer bool      `json:"empty_layer,omitempty"`
	}

	type imageConfig struct {
		RootFS       *imageRootFS   `json:"rootfs,omitempty"`
		History      []imageHistory `json:"history,omitempty"`
		Architecture string         `json:"architecture,omitempty"`
	}

	var img imageConfig

	if err := json.Unmarshal(mb.configJSON, &img); err != nil {
		return nil, err
	}

	if len(img.History) == 0 {
		return nil, errors.New("empty history when trying to create schema1 manifest")
	}

	if len(img.RootFS.DiffIDs) != len(mb.descriptors) {
		return nil, fmt.Errorf("number of descriptors and number of layers in rootfs must match: len(%v) != len(%v)", img.RootFS.DiffIDs, mb.descriptors)
	}

	// Generate IDs for each layer
	// For non-top-level layers, create fake V1Compatibility strings that
	// fit the format and don't collide with anything else, but don't
	// result in runnable images on their own.
	type v1Compatibility struct {
		ID              string    `json:"id"`
		Parent          string    `json:"parent,omitempty"`
		Comment         string    `json:"comment,omitempty"`
		Created         time.Time `json:"created"`
		ContainerConfig struct {
			Cmd []string
		} `json:"container_config,omitempty"`
		Author    string `json:"author,omitempty"`
		ThrowAway bool   `json:"throwaway,omitempty"`
	}

	fsLayerList := make([]FSLayer, len(img.History))
	history := make([]History, len(img.History))

	parent := ""
	layerCounter := 0
	for i, h := range img.History[:len(img.History)-1] {
		var blobsum digest.Digest
		if h.EmptyLayer {
			if blobsum, err = mb.emptyTar(ctx); err != nil {
				return nil, err
			}
		} else {
			if len(img.RootFS.DiffIDs) <= layerCounter {
				return nil, errors.New("too many non-empty layers in History section")
			}
			blobsum = mb.descriptors[layerCounter].Digest
			layerCounter++
		}

		v1ID := digest.FromBytes([]byte(blobsum.Hex() + " " + parent)).Hex()

		if i == 0 && img.RootFS.BaseLayer != "" {
			// windows-only baselayer setup
			baseID := sha512.Sum384([]byte(img.RootFS.BaseLayer))
			parent = fmt.Sprintf("%x", baseID[:32])
		}

		v1Compatibility := v1Compatibility{
			ID:      v1ID,
			Parent:  parent,
			Comment: h.Comment,
			Created: h.Created,
			Author:  h.Author,
		}
		v1Compatibility.ContainerConfig.Cmd = []string{img.History[i].CreatedBy}
		if h.EmptyLayer {
			v1Compatibility.ThrowAway = true
		}
		jsonBytes, err := json.Marshal(&v1Compatibility)
		if err != nil {
			return nil, err
		}

		reversedIndex := len(img.History) - i - 1
		history[reversedIndex].V1Compatibility = string(jsonBytes)
		fsLayerList[reversedIndex] = FSLayer{BlobSum: blobsum}

		parent = v1ID
	}

	latestHistory := img.History[len(img.History)-1]

	var blobsum digest.Digest
	if latestHistory.EmptyLayer {
		if blobsum, err = mb.emptyTar(ctx); err != nil {
			return nil, err
		}
	} else {
		if len(img.RootFS.DiffIDs) <= layerCounter {
			return nil, errors.New("too many non-empty layers in History section")
		}
		blobsum = mb.descriptors[layerCounter].Digest
	}

	fsLayerList[0] = FSLayer{BlobSum: blobsum}
	dgst := digest.FromBytes([]byte(blobsum.Hex() + " " + parent + " " + string(mb.configJSON)))

	// Top-level v1compatibility string should be a modified version of the
	// image config.
	transformedConfig, err := MakeV1ConfigFromConfig(mb.configJSON, dgst.Hex(), parent, latestHistory.EmptyLayer)
	if err != nil {
		return nil, err
	}

	history[0].V1Compatibility = string(transformedConfig)

	tag := ""
	if tagged, isTagged := mb.ref.(reference.Tagged); isTagged {
		tag = tagged.Tag()
	}

	mfst := Manifest{
		Versioned: manifest.Versioned{
			SchemaVersion: 1,
		},
		Name:         mb.ref.Name(),
		Tag:          tag,
		Architecture: img.Architecture,
		FSLayers:     fsLayerList,
		History:      history,
	}

	return Sign(&mfst, mb.pk)
}
367418
func (h *Holder) view(index, field, name string) *view {
	f := h.Field(index, field)
	if f == nil {
		return nil
	}
	return f.view(name)
}
1068807
func buildMediaTypeSchema(api *design.APIDefinition, mt *design.MediaTypeDefinition, view string, s *JSONSchema) {
	s.Media = &JSONMedia{Type: mt.Identifier}
	projected, linksUT, err := mt.Project(view)
	if err != nil {
		panic(fmt.Sprintf("failed to project media type %#v: %s", mt.Identifier, err)) // bug
	}
	if linksUT != nil {
		links := linksUT.Type.ToObject()
		lnames := make([]string, len(links))
		i := 0
		for n := range links {
			lnames[i] = n
			i++
		}
		sort.Strings(lnames)
		for _, ln := range lnames {
			var (
				att  = links[ln]
				lmt  = att.Type.(*design.MediaTypeDefinition)
				r    = lmt.Resource
				href string
			)
			if r != nil {
				href = toSchemaHref(api, r.CanonicalAction().Routes[0])
			}
			sm := NewJSONSchema()
			sm.Ref = MediaTypeRef(api, lmt, "default")
			s.Links = append(s.Links, &JSONLink{
				Title:        ln,
				Rel:          ln,
				Description:  att.Description,
				Href:         href,
				Method:       "GET",
				TargetSchema: sm,
				MediaType:    lmt.Identifier,
			})
		}
	}
	buildAttributeSchema(api, s, projected.AttributeDefinition)
}