// gatherExtraSchemas produces a sorted list of extra schemas.
//
// ExtraSchemas are inlined types rendered in the same model file.
498032
func gatherExtraSchemas(extraMap map[string]GenSchema) (extras GenSchemaList) {
	var extraKeys []string
	for k := range extraMap {
		extraKeys = append(extraKeys, k)
	}
	sort.Strings(extraKeys)
	for _, k := range extraKeys {
		// figure out if top level validations are needed
		p := extraMap[k]
		p.HasValidations = shallowValidationLookup(p)
		extras = append(extras, p)
	}
	return
}
585158
func (c *Connector) UpsertSchema(ctx context.Context, scope, namePrefix string, ed []*dosa.EntityDefinition) (*dosa.SchemaStatus, error) {
	if c.Next == nil {
		return nil, NewErrNoMoreConnector()
	}
	return c.Next.UpsertSchema(ctx, scope, namePrefix, ed)
}
1092812
func (client *Client) GetSchema(ctx context.Context, tablet *topodatapb.Tablet, tables, excludeTables []string, includeViews bool) (*tabletmanagerdatapb.SchemaDefinition, error) {
	cc, c, err := client.dial(tablet)
	if err != nil {
		return nil, err
	}
	defer cc.Close()
	response, err := c.GetSchema(ctx, &tabletmanagerdatapb.GetSchemaRequest{
		Tables:        tables,
		ExcludeTables: excludeTables,
		IncludeViews:  includeViews,
	})
	if err != nil {
		return nil, err
	}
	return response.SchemaDefinition, nil
}
1234093
func GenerateExtension(schemaFile string, outDir string) error {
	outFileBaseName := getBaseFileNameWithoutExt(schemaFile)
	extensionNameWithoutXDashPrefix := outFileBaseName[len("x-"):]
	outDir = path.Join(outDir, "gnostic-x-"+extensionNameWithoutXDashPrefix)
	protoPackage := toProtoPackageName(extensionNameWithoutXDashPrefix)
	protoPackageName := strings.ToLower(protoPackage)
	goPackageName := protoPackageName

	protoOutDirectory := outDir + "/" + "proto"
	var err error

	projectRoot := os.Getenv("GOPATH") + "/src/github.com/googleapis/gnostic/"
	baseSchema, err := jsonschema.NewSchemaFromFile(projectRoot + "jsonschema/schema.json")
	if err != nil {
		return err
	}
	baseSchema.ResolveRefs()
	baseSchema.ResolveAllOfs()

	openapiSchema, err := jsonschema.NewSchemaFromFile(schemaFile)
	if err != nil {
		return err
	}
	openapiSchema.ResolveRefs()
	openapiSchema.ResolveAllOfs()

	// build a simplified model of the types described by the schema
	cc := NewDomain(openapiSchema, "v2") // TODO fix for OpenAPI v3

	// create a type for each object defined in the schema
	extensionNameToMessageName := make(map[string]generatedTypeInfo)
	schemaErrors := make([]error, 0)
	supportedPrimitives := make([]string, 0)
	for key := range supportedPrimitiveTypeInfos {
		supportedPrimitives = append(supportedPrimitives, key)
	}
	sort.Strings(supportedPrimitives)
	if cc.Schema.Definitions != nil {
		for _, pair := range *(cc.Schema.Definitions) {
			definitionName := pair.Name
			definitionSchema := pair.Value
			// ensure the id field is set
			if definitionSchema.ID == nil || len(*(definitionSchema.ID)) == 0 {
				schemaErrors = append(schemaErrors,
					fmt.Errorf("schema %s has no 'id' field, which must match the "+
						"name of the OpenAPI extension that the schema represents",
						definitionName))
			} else {
				if _, ok := extensionNameToMessageName[*(definitionSchema.ID)]; ok {
					schemaErrors = append(schemaErrors,
						fmt.Errorf("schema %s and %s have the same 'id' field value",
							definitionName, extensionNameToMessageName[*(definitionSchema.ID)].schemaName))
				} else if (definitionSchema.Type == nil) || (*definitionSchema.Type.String == "object") {
					extensionNameToMessageName[*(definitionSchema.ID)] = generatedTypeInfo{schemaName: definitionName}
				} else {
					// this is a primitive type
					if val, ok := supportedPrimitiveTypeInfos[*definitionSchema.Type.String]; ok {
						extensionNameToMessageName[*(definitionSchema.ID)] = generatedTypeInfo{schemaName: definitionName, optionalPrimitiveTypeInfo: &val}
					} else {
						schemaErrors = append(schemaErrors,
							fmt.Errorf("Schema %s has type '%s' which is "+
								"not supported. Supported primitive types are "+
								"%s.\n", definitionName,
								*definitionSchema.Type.String,
								supportedPrimitives))
					}
				}
			}
			typeName := cc.TypeNameForStub(definitionName)
			typeModel := cc.BuildTypeForDefinition(typeName, definitionName, definitionSchema)
			if typeModel != nil {
				cc.TypeModels[typeName] = typeModel
			}
		}
	}
	if len(schemaErrors) > 0 {
		// error has been reported.
		return compiler.NewErrorGroupOrNil(schemaErrors)
	}

	err = os.MkdirAll(outDir, os.ModePerm)
	if err != nil {
		return err
	}

	err = os.MkdirAll(protoOutDirectory, os.ModePerm)
	if err != nil {
		return err
	}

	// generate the protocol buffer description
	protoOptions := append(protoOptionsForExtensions,
		ProtoOption{Name: "java_package", Value: "org.openapi.extension." + strings.ToLower(protoPackage), Comment: "// The Java package name must be proto package name with proper prefix."},
		ProtoOption{Name: "objc_class_prefix", Value: strings.ToLower(protoPackage),
			Comment: "// A reasonable prefix for the Objective-C symbols generated from the package.\n" +
				"// It should at a minimum be 3 characters long, all uppercase, and convention\n" +
				"// is to use an abbreviation of the package name. Something short, but\n" +
				"// hopefully unique enough to not conflict with things that may come along in\n" +
				"// the future. 'GPB' is reserved for the protocol buffer implementation itself.",
		})

	proto := cc.generateProto(protoPackageName, License, protoOptions, nil)
	protoFilename := path.Join(protoOutDirectory, outFileBaseName+".proto")

	err = ioutil.WriteFile(protoFilename, []byte(proto), 0644)
	if err != nil {
		return err
	}

	// generate the compiler
	compiler := cc.GenerateCompiler(goPackageName, License, []string{
		"fmt",
		"regexp",
		"strings",
		"github.com/googleapis/gnostic/compiler",
		"gopkg.in/yaml.v2",
	})
	goFilename := path.Join(protoOutDirectory, outFileBaseName+".go")
	err = ioutil.WriteFile(goFilename, []byte(compiler), 0644)
	if err != nil {
		return err
	}
	err = exec.Command(runtime.GOROOT()+"/bin/gofmt", "-w", goFilename).Run()

	// generate the main file.
	outDirRelativeToGoPathSrc := strings.Replace(outDir, path.Join(os.Getenv("GOPATH"), "src")+"/", "", 1)

	var extensionNameKeys []string
	for k := range extensionNameToMessageName {
		extensionNameKeys = append(extensionNameKeys, k)
	}
	sort.Strings(extensionNameKeys)

	wrapperTypeIncluded := false
	var cases string
	for _, extensionName := range extensionNameKeys {
		if extensionNameToMessageName[extensionName].optionalPrimitiveTypeInfo == nil {
			cases += fmt.Sprintf(caseStringForObjectTypes, extensionName, goPackageName, extensionNameToMessageName[extensionName].schemaName)
		} else {
			wrapperTypeIncluded = true
			cases += fmt.Sprintf(caseStringForWrapperTypes, extensionName, extensionNameToMessageName[extensionName].optionalPrimitiveTypeInfo.goTypeName, extensionNameToMessageName[extensionName].optionalPrimitiveTypeInfo.wrapperProtoName)
		}

	}
	extMainCode := fmt.Sprintf(additionalCompilerCodeWithMain, cases)
	imports := []string{
		"github.com/golang/protobuf/proto",
		"github.com/googleapis/gnostic/extensions",
		"github.com/googleapis/gnostic/compiler",
		"gopkg.in/yaml.v2",
		outDirRelativeToGoPathSrc + "/" + "proto",
	}
	if wrapperTypeIncluded {
		imports = append(imports, "github.com/golang/protobuf/ptypes/wrappers")
	}
	main := generateMainFile("main", License, extMainCode, imports)
	mainFileName := path.Join(outDir, "main.go")
	err = ioutil.WriteFile(mainFileName, []byte(main), 0644)
	if err != nil {
		return err
	}

	// format the compiler
	return exec.Command(runtime.GOROOT()+"/bin/gofmt", "-w", mainFileName).Run()
}
931977
func (wr *Wrangler) compareSchemas(ctx context.Context, sourceAlias, destAlias *topodatapb.TabletAlias, tables, excludeTables []string, includeViews bool) ([]string, error) {
	sourceSd, err := wr.GetSchema(ctx, sourceAlias, tables, excludeTables, includeViews)
	if err != nil {
		return nil, fmt.Errorf("failed to get schema from tablet %v. err: %v", sourceAlias, err)
	}
	destSd, err := wr.GetSchema(ctx, destAlias, tables, excludeTables, includeViews)
	if err != nil {
		return nil, fmt.Errorf("failed to get schema from tablet %v. err: %v", destAlias, err)
	}
	return tmutils.DiffSchemaToArray("source", sourceSd, "dest", destSd), nil
}
14163
func MySchema(args *internal.ArgType) (string, error) {
	var err error

	// sql query
	const sqlstr = `SELECT SCHEMA()`

	var schema string

	// run query
	models.XOLog(sqlstr)
	err = args.DB.QueryRow(sqlstr).Scan(&schema)
	if err != nil {
		return "", err
	}

	return schema, nil
}
642831
func addTrustSchema(extra environschema.Fields) (environschema.Fields, error) {
	fields := make(environschema.Fields)
	for name, field := range trustFields {
		fields[name] = field
	}
	for name, field := range extra {
		if _, ok := trustFields[name]; ok {
			return nil, errors.Errorf("config field %q clashes with common config", name)
		}
		fields[name] = field
	}
	return fields, nil
}
567042
func (u user) GetExtra() map[string][]string {
	m := map[string][]string{}
	for k, v := range u.Extra {
		m[k] = []string(v)
	}
	return m
}
591574
func HashSchema(schema *Schema) SchemaSetFunc {
	return func(v interface{}) int {
		var buf bytes.Buffer
		SerializeValueForHash(&buf, v, schema)
		return hashcode.String(buf.String())
	}
}
699227
func GetClusterConfigSchema(extensionSchema string) string {
	var clusterConfigSchema string
	if clusterConfigSchema == "" {
		clusterConfigSchema = fmt.Sprintf(ClusterConfigSpecSchemaTemplate, "")
	} else {
		clusterConfigSchema = fmt.Sprintf(ClusterConfigSpecSchemaTemplate, ","+extensionSchema)
	}
	return fmt.Sprintf(V2SchemaTemplate, MetadataSchema, clusterConfigSchema, DefaultDefinitions)
}
627294
func Schema(extra environschema.Fields) (environschema.Fields, error) {
	fields := make(environschema.Fields)
	for name, field := range configSchema {
		if controller.ControllerOnlyAttribute(name) {
			return nil, errors.Errorf("config field %q clashes with controller config", name)
		}
		fields[name] = field
	}
	for name, field := range extra {
		if controller.ControllerOnlyAttribute(name) {
			return nil, errors.Errorf("config field %q clashes with controller config", name)
		}
		if _, ok := fields[name]; ok {
			return nil, errors.Errorf("config field %q clashes with global config", name)
		}
		fields[name] = field
	}
	return fields, nil
}
403964
func (rc *Connector) UpsertSchema(ctx context.Context, scope, namePrefix string, ed []*dosa.EntityDefinition) (*dosa.SchemaStatus, error) {
	connector, err := rc.getConnector(scope, namePrefix)
	if err != nil {
		return nil, err
	}
	return connector.UpsertSchema(ctx, scope, namePrefix, ed)
}
1034702
func (h *Handler) handleGetSchema(w http.ResponseWriter, r *http.Request) {
	if !validHeaderAcceptJSON(r.Header) {
		http.Error(w, "JSON only acceptable response", http.StatusNotAcceptable)
		return
	}

	schema := h.api.Schema(r.Context())
	if err := json.NewEncoder(w).Encode(map[string]interface{}{"indexes": schema}); err != nil { // TODO: use pilosa.Schema instead of map[string]interface{} here?
		h.logger.Printf("write schema response error: %s", err)
	}
}
806984
func (parser *Parser) parseTypeExpr(pkgName, typeName string, typeExpr ast.Expr) (spec.Schema, error) {
	//TODO: return pointer to spec.Schema

	switch expr := typeExpr.(type) {
	// type Foo struct {...}
	case *ast.StructType:
		refTypeName := fullTypeName(pkgName, typeName)
		if schema, isParsed := parser.swagger.Definitions[refTypeName]; isParsed {
			return schema, nil
		}

		extraRequired := make([]string, 0)
		properties := make(map[string]spec.Schema)
		for _, field := range expr.Fields.List {
			var fieldProps map[string]spec.Schema
			var requiredFromAnon []string
			if field.Names == nil {
				var err error
				fieldProps, requiredFromAnon, err = parser.parseAnonymousField(pkgName, field)
				if err != nil {
					return spec.Schema{}, err
				}
				extraRequired = append(extraRequired, requiredFromAnon...)
			} else {
				var err error
				fieldProps, err = parser.parseStruct(pkgName, field)
				if err != nil {
					return spec.Schema{}, err
				}
			}

			for k, v := range fieldProps {
				properties[k] = v
			}
		}

		// collect requireds from our properties and anonymous fields
		required := parser.collectRequiredFields(pkgName, properties, extraRequired)

		// unset required from properties because we've collected them
		for k, prop := range properties {
			tname := prop.SchemaProps.Type[0]
			if tname != "object" {
				prop.SchemaProps.Required = make([]string, 0)
			}
			properties[k] = prop
		}

		return spec.Schema{
			SchemaProps: spec.SchemaProps{
				Type:       []string{"object"},
				Properties: properties,
				Required:   required,
			}}, nil

	// type Foo Baz
	case *ast.Ident:
		refTypeName := fullTypeName(pkgName, expr.Name)
		if _, isParsed := parser.swagger.Definitions[refTypeName]; !isParsed {
			if typedef, ok := parser.TypeDefinitions[pkgName][expr.Name]; ok {
				parser.ParseDefinition(pkgName, expr.Name, typedef)
			}
		}
		return parser.swagger.Definitions[refTypeName], nil

	// type Foo *Baz
	case *ast.StarExpr:
		return parser.parseTypeExpr(pkgName, typeName, expr.X)

	// type Foo []Baz
	case *ast.ArrayType:
		itemSchema, err := parser.parseTypeExpr(pkgName, "", expr.Elt)
		if err != nil {
			return spec.Schema{}, err
		}
		return spec.Schema{
			SchemaProps: spec.SchemaProps{
				Type: []string{"array"},
				Items: &spec.SchemaOrArray{
					Schema: &itemSchema,
				},
			},
		}, nil

	// type Foo pkg.Bar
	case *ast.SelectorExpr:
		if xIdent, ok := expr.X.(*ast.Ident); ok {
			pkgName = xIdent.Name
			typeName = expr.Sel.Name
			refTypeName := fullTypeName(pkgName, typeName)
			if _, isParsed := parser.swagger.Definitions[refTypeName]; !isParsed {
				typedef := parser.TypeDefinitions[pkgName][typeName]
				parser.ParseDefinition(pkgName, typeName, typedef)
			}
			return parser.swagger.Definitions[refTypeName], nil
		}

	// type Foo map[string]Bar
	case *ast.MapType:
		itemSchema, err := parser.parseTypeExpr(pkgName, "", expr.Value)
		if err != nil {
			return spec.Schema{}, err
		}
		return spec.Schema{
			SchemaProps: spec.SchemaProps{
				Type: []string{"object"},
				AdditionalProperties: &spec.SchemaOrBool{
					Schema: &itemSchema,
				},
			},
		}, nil
	// ...
	default:
		Printf("Type definition of type '%T' is not supported yet. Using 'object' instead.\n", typeExpr)
	}

	return spec.Schema{
		SchemaProps: spec.SchemaProps{
			Type: []string{"object"},
		},
	}, nil
}
289515
func (agent *ActionAgent) GetSchema(ctx context.Context, tables, excludeTables []string, includeViews bool) (*tabletmanagerdatapb.SchemaDefinition, error) {
	return agent.MysqlDaemon.GetSchema(topoproto.TabletDbName(agent.Tablet()), tables, excludeTables, includeViews)
}
55869
func (ovs OvsdbClient) GetSchema(dbName string) (*DatabaseSchema, error) {
	args := NewGetSchemaArgs(dbName)
	var reply DatabaseSchema
	err := ovs.rpcClient.Call("get_schema", args, &reply)
	if err != nil {
		return nil, err
	}
	ovs.Schema[dbName] = reply
	return &reply, err
}
2043
func (client *FakeTabletManagerClient) ApplySchema(ctx context.Context, tablet *topodatapb.Tablet, change *tmutils.SchemaChange) (*tabletmanagerdatapb.SchemaChangeResult, error) {
	return &tabletmanagerdatapb.SchemaChangeResult{}, nil
}