• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Golang schema.GetManager函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中github.com/cloudwan/gohan/schema.GetManager函数的典型用法代码示例。如果您正苦于以下问题:Golang GetManager函数的具体用法?Golang GetManager怎么用?Golang GetManager使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了GetManager函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。

示例1: loadSchemaIncludes

func (env *Environment) loadSchemaIncludes() error {
	manager := schema.GetManager()
	schemaIncludeValue, err := env.VM.Get(schemaIncludesVar)
	if err != nil {
		return fmt.Errorf("%s string array not specified", schemaIncludesVar)
	}
	schemaIncludesFilenames, err := gohan_otto.GetStringList(schemaIncludeValue)
	if err != nil {
		return fmt.Errorf("Bad type of %s - expected an array of strings but the type is %s",
			schemaIncludesVar, schemaIncludeValue.Class())
	}
	for _, schemaIncludes := range schemaIncludesFilenames {
		var data []byte

		if data, err = ioutil.ReadFile(schemaIncludes); err != nil {
			return err
		}

		schemas := strings.Split(string(data), "\n")

		for _, schema := range schemas {
			if schema == "" || strings.HasPrefix(schema, "#") {
				continue
			}

			if err = manager.LoadSchemaFromFile(schema); err != nil {
				return err
			}
		}
	}
	return nil
}
开发者ID:cloudwan,项目名称:gohan,代码行数:32,代码来源:environment.go


示例2: clearTable

func clearTable(tx transaction.Transaction, s *schema.Schema) error {
	if s.IsAbstract() {
		return nil
	}
	for _, schema := range schema.GetManager().Schemas() {
		if schema.ParentSchema == s {
			err := clearTable(tx, schema)
			if err != nil {
				return err
			}
		} else {
			for _, property := range schema.Properties {
				if property.Relation == s.Singular {
					err := clearTable(tx, schema)
					if err != nil {
						return err
					}
				}
			}
		}
	}
	resources, _, err := tx.List(s, nil, nil)
	if err != nil {
		return err
	}
	for _, resource := range resources {
		err = tx.Delete(s, resource.ID())
		if err != nil {
			return err
		}
	}
	return nil
}
开发者ID:vozhyk-,项目名称:gohan,代码行数:33,代码来源:server_test.go


示例3: loadSchemas

func (env *Environment) loadSchemas() error {
	schemaValue, err := env.VM.Get(schemasVar)
	if err != nil {
		return fmt.Errorf("%s string array not specified", schemasVar)
	}
	schemaFilenames, err := gohan_otto.GetStringList(schemaValue)
	if err != nil {
		return fmt.Errorf("Bad type of %s - expected an array of strings", schemasVar)
	}

	manager := schema.GetManager()
	for _, schema := range schemaFilenames {
		err = manager.LoadSchemaFromFile(schema)
		if err != nil {
			return err
		}
	}
	environmentManager := extension.GetManager()
	for schemaID := range manager.Schemas() {
		environmentManager.RegisterEnvironment(schemaID, env)
	}

	pathValue, err := env.VM.Get(pathVar)
	if err != nil || !pathValue.IsString() {
		return fmt.Errorf("%s string not specified", pathVar)
	}
	pathString, _ := pathValue.ToString()

	return env.LoadExtensionsForPath(manager.Extensions, pathString)
}
开发者ID:vozhyk-,项目名称:gohan,代码行数:30,代码来源:environment.go


示例4: GenTableDef

//GenTableDef generates create table sql
func (db *DB) GenTableDef(s *schema.Schema, cascade bool) string {
	schemaManager := schema.GetManager()
	cols, relations := db.genTableCols(s, cascade, nil)

	if s.Parent != "" {
		foreignSchema, _ := schemaManager.Schema(s.Parent)
		cascadeString := ""
		if cascade || s.OnParentDeleteCascade {
			cascadeString = "on delete cascade"
		}
		relations = append(relations, fmt.Sprintf("foreign key(`%s_id`) REFERENCES `%s`(id) %s",
			s.Parent, foreignSchema.GetDbTableName(), cascadeString))
	}

	if s.StateVersioning() {
		cols = append(cols, quote(configVersionColumnName)+"int not null default 1")
		cols = append(cols, quote(stateVersionColumnName)+"int not null default 0")
		cols = append(cols, quote(stateErrorColumnName)+"text not null default ''")
		cols = append(cols, quote(stateColumnName)+"text not null default ''")
		cols = append(cols, quote(stateMonitoringColumnName)+"text not null default ''")
	}

	cols = append(cols, relations...)
	tableSQL := fmt.Sprintf("create table `%s` (%s);\n", s.GetDbTableName(), strings.Join(cols, ","))
	log.Debug("Creating table: " + tableSQL)
	return tableSQL
}
开发者ID:vozhyk-,项目名称:gohan,代码行数:28,代码来源:sql.go


示例5: GetSchema

//GetSchema returns the schema filtered and trimmed for a specific user or nil when the user shouldn't see it at all
func GetSchema(s *schema.Schema, authorization schema.Authorization) (result *schema.Resource, err error) {
	manager := schema.GetManager()
	metaschema, _ := manager.Schema("schema")
	policy, _ := manager.PolicyValidate("read", s.GetPluralURL(), authorization)
	if policy == nil {
		return
	}
	if s.IsAbstract() {
		return
	}
	rawSchema := s.JSON()
	filteredSchema := util.ExtendMap(nil, s.JSONSchema)
	rawSchema["schema"] = filteredSchema
	schemaProperties, schemaPropertiesOrder, schemaRequired := policy.FilterSchema(
		util.MaybeMap(s.JSONSchema["properties"]),
		util.MaybeStringList(s.JSONSchema["propertiesOrder"]),
		util.MaybeStringList(s.JSONSchema["required"]))

	filteredSchema["properties"] = schemaProperties
	filteredSchema["propertiesOrder"] = schemaPropertiesOrder
	filteredSchema["required"] = schemaRequired

	result, err = schema.NewResource(metaschema, rawSchema)
	if err != nil {
		log.Warning("%s %s", result, err)
		return
	}
	return
}
开发者ID:vozhyk-,项目名称:gohan,代码行数:30,代码来源:editor.go


示例6: mapChildNamespaceRoute

// mapChildNamespaceRoute sets a handler returning a dictionary of resources
// supported by a certain API version identified by the given namespace
func mapChildNamespaceRoute(route martini.Router, namespace *schema.Namespace) {
	log.Debug("[Path] %s", namespace.GetFullPrefix())
	route.Get(
		namespace.GetFullPrefix(),
		func(w http.ResponseWriter, r *http.Request, p martini.Params, context martini.Context) {
			resources := []schema.NamespaceResource{}
			for _, s := range schema.GetManager().Schemas() {
				if s.NamespaceID == namespace.ID {
					resources = append(resources, schema.NamespaceResource{
						Links: []schema.Link{
							schema.Link{
								Href: s.GetPluralURL(),
								Rel:  "self",
							},
						},
						Name:       s.Singular,
						Collection: s.Plural,
					})
				}
			}

			routes.ServeJson(w, map[string][]schema.NamespaceResource{"resources": resources})
		},
	)
}
开发者ID:vozhyk-,项目名称:gohan,代码行数:27,代码来源:api.go


示例7: mapTopLevelNamespaceRoute

// mapTopLevelNamespaceRoute maps route listing available subnamespaces (versions)
// for a top-level namespace
func mapTopLevelNamespaceRoute(route martini.Router, namespace *schema.Namespace) {
	log.Debug("[Path] %s/", namespace.GetFullPrefix())
	route.Get(
		namespace.GetFullPrefix()+"/",
		func(w http.ResponseWriter, r *http.Request, p martini.Params, context martini.Context) {
			versions := []schema.Version{}
			for _, childNamespace := range schema.GetManager().Namespaces() {
				if childNamespace.Parent == namespace.ID {
					versions = append(versions, schema.Version{
						Status: "SUPPORTED",
						ID:     childNamespace.Prefix,
						Links: []schema.Link{
							schema.Link{
								Href: childNamespace.GetFullPrefix() + "/",
								Rel:  "self",
							},
						},
					})
				}
			}

			if len(versions) != 0 {
				versions[len(versions)-1].Status = "CURRENT"
			}

			routes.ServeJson(w, map[string][]schema.Version{"versions": versions})
		})
}
开发者ID:vozhyk-,项目名称:gohan,代码行数:30,代码来源:api.go


示例8: getInitDbCommand

func getInitDbCommand() cli.Command {
	return cli.Command{
		Name:      "init-db",
		ShortName: "idb",
		Usage:     "Initialize DB backend with given schema file",
		Description: `
Initialize empty database with given schema.

Setting meta-schema option will additionaly populate meta-schema table with schema resources.
Useful for development purposes.`,
		Flags: []cli.Flag{
			cli.StringFlag{Name: "database-type, t", Value: "sqlite3", Usage: "Backend datebase type"},
			cli.StringFlag{Name: "database, d", Value: "gohan.db", Usage: "DB connection string"},
			cli.StringFlag{Name: "schema, s", Value: "etc/schema/gohan.json", Usage: "Schema definition"},
			cli.BoolFlag{Name: "drop-on-create", Usage: "If true, old database will be dropped"},
			cli.BoolFlag{Name: "cascade", Usage: "If true, FOREIGN KEYS in database will be created with ON DELETE CASCADE"},
			cli.StringFlag{Name: "meta-schema, m", Value: "", Usage: "Meta-schema file (optional)"},
		},
		Action: func(c *cli.Context) {
			dbType := c.String("database-type")
			dbConnection := c.String("database")
			schemaFile := c.String("schema")
			metaSchemaFile := c.String("meta-schema")
			dropOnCreate := c.Bool("drop-on-create")
			cascade := c.Bool("cascade")
			manager := schema.GetManager()
			manager.LoadSchemasFromFiles(schemaFile, metaSchemaFile)
			err := db.InitDBWithSchemas(dbType, dbConnection, dropOnCreate, cascade)
			if err != nil {
				util.ExitFatal(err)
			}
			fmt.Println("DB is initialized")
		},
	}
}
开发者ID:masaki-saeki,项目名称:gohan,代码行数:35,代码来源:cli.go


示例9: getValidateCommand

func getValidateCommand() cli.Command {
	return cli.Command{
		Name:      "validate",
		ShortName: "v",
		Usage:     "Validate document",
		Description: `
Validate document against schema.
It's especially useful to validate schema files against gohan meta-schema.`,
		Flags: []cli.Flag{
			cli.StringFlag{Name: "schema, s", Value: "etc/schema/gohan.json", Usage: "Schema path"},
			cli.StringFlag{Name: "document, d", Value: "etc/apps/example.json", Usage: "Document path"},
		},
		Action: func(c *cli.Context) {
			schemaPath := c.String("schema")
			documentPath := c.String("document")

			manager := schema.GetManager()
			err := manager.LoadSchemaFromFile(schemaPath)
			if err != nil {
				util.ExitFatal("Failed to parse schema:", err)
			}

			err = manager.LoadSchemaFromFile(documentPath)
			if err == nil {
				fmt.Println("Schema is valid")
			} else {
				util.ExitFatalf("Schema is not valid, see errors below:\n%s\n", err)
			}
		},
	}
}
开发者ID:masaki-saeki,项目名称:gohan,代码行数:31,代码来源:cli.go


示例10: DBList

//DBList lists data from database.
func DBList(tx transaction.Transaction, schemaID string, filter map[string]interface{}) ([]interface{}, error) {
	manager := schema.GetManager()
	schemaObj, ok := manager.Schema(schemaID)
	if !ok {
		return nil, fmt.Errorf("Schema %s not found", schemaID)
	}
	for key, value := range filter {
		switch v := value.(type) {
		case string:
			filter[key] = []string{v}
		case bool:
			filter[key] = []string{fmt.Sprintf("%v", v)}
		case int:
			filter[key] = []string{fmt.Sprintf("%v", v)}
		case []interface{}:
			filterList := make([]string, len(v))
			for _, item := range v {
				filterList = append(filterList, fmt.Sprintf("%v", item))
			}
			filter[key] = filterList
		}
	}
	resources, _, err := tx.List(schemaObj, filter, nil)
	resp := []interface{}{}
	for _, resource := range resources {
		resp = append(resp, resource.Data())
	}
	return resp, err
}
开发者ID:marcin-ptaszynski,项目名称:gohan,代码行数:30,代码来源:gohan.go


示例11: InitDBWithSchemas

//InitDBWithSchemas initializes database using schemas stored in Manager
func InitDBWithSchemas(dbType, dbConnection string, dropOnCreate, cascade bool) error {
	aDb, err := ConnectDB(dbType, dbConnection)
	if err != nil {
		return err
	}
	schemaManager := schema.GetManager()
	schemas := schemaManager.OrderedSchemas()
	if len(schemas) == 0 {
		return fmt.Errorf(noSchemasInManagerError)
	}
	if dropOnCreate {
		for i := len(schemas) - 1; i >= 0; i-- {
			s := schemas[i]
			log.Debug("Dropping table '%s'", s.Plural)
			err = aDb.DropTable(s)
			if err != nil {
				log.Fatal("Error during deleting table:", err.Error())
			}
		}
	}
	for _, s := range schemas {
		log.Debug("Registering schema %s", s.ID)
		err = aDb.RegisterTable(s, cascade)
		if err != nil {
			message := "Error during registering table: %s"
			if strings.Contains(err.Error(), "already exists") {
				log.Warning(message, err.Error())
			} else {
				log.Fatal(message, err.Error())
			}
		}
	}
	return nil
}
开发者ID:masaki-saeki,项目名称:gohan,代码行数:35,代码来源:db.go


示例12: GohanModelCreate

//GohanModelCreate creates gohan resource and running extensions
func GohanModelCreate(context map[string]interface{}, schemaID string,
	dataMap map[string]interface{}) (interface{}, error) {

	currentSchema, err := getSchema(schemaID)
	if err != nil {
		return nil, err
	}
	context["schema"] = currentSchema
	context["path"] = currentSchema.GetPluralURL()

	manager := schema.GetManager()
	resourceObj, err := manager.LoadResource(currentSchema.ID, dataMap)
	if err != nil {
		return nil, err
	}

	if err := resources.CreateResourceInTransaction(
		context, resourceObj); err != nil {
		return nil, err
	}
	response, ok := context["response"].(map[string]interface{})
	if !ok {
		return nil, fmt.Errorf("No response")
	}
	return response[currentSchema.Singular], nil
}
开发者ID:vozhyk-,项目名称:gohan,代码行数:27,代码来源:gohan_resource_management.go


示例13: getValidateCommand

func getValidateCommand() cli.Command {
	return cli.Command{
		Name:      "validate",
		ShortName: "v",
		Usage:     "Validate document",
		Description: `
Validate document against schema.
It's especially useful to validate schema files against gohan meta-schema.`,
		Flags: []cli.Flag{
			cli.StringFlag{Name: "schema, s", Value: "etc/schema/gohan.json", Usage: "Schema path"},
			cli.StringSliceFlag{Name: "document, d", Usage: "Document path"},
		},
		Action: func(c *cli.Context) {
			schemaPath := c.String("schema")
			documentPaths := c.StringSlice("document")
			if len(documentPaths) == 0 {
				util.ExitFatalf("At least one document should be specified for validation\n")
			}

			manager := schema.GetManager()
			err := manager.LoadSchemaFromFile(schemaPath)
			if err != nil {
				util.ExitFatal("Failed to parse schema:", err)
			}

			for _, documentPath := range documentPaths {
				err = manager.LoadSchemaFromFile(documentPath)
				if err != nil {
					util.ExitFatalf("Schema is not valid, see errors below:\n%s\n", err)
				}
			}
			fmt.Println("Schema is valid")
		},
	}
}
开发者ID:vozhyk-,项目名称:gohan,代码行数:35,代码来源:cli.go


示例14: logEvent

func (tl *transactionEventLogger) logEvent(eventType string, resource *schema.Resource, version int64) error {
	schemaManager := schema.GetManager()
	eventSchema, ok := schemaManager.Schema("event")
	if !ok {
		return fmt.Errorf("event schema not found")
	}

	if resource.Schema().Metadata["nosync"] == true {
		log.Debug("skipping event logging for schema: %s", resource.Schema().ID)
		return nil
	}
	body, err := resource.JSONString()
	if err != nil {
		return fmt.Errorf("Error during event resource deserialisation: %s", err.Error())
	}
	eventResource, err := schema.NewResource(eventSchema, map[string]interface{}{
		"type":      eventType,
		"path":      resource.Path(),
		"version":   version,
		"body":      body,
		"timestamp": int64(time.Now().Unix()),
	})
	tl.eventLogged = true
	return tl.Transaction.Create(eventResource)
}
开发者ID:vozhyk-,项目名称:gohan,代码行数:25,代码来源:sync.go


示例15: UpdateResourceInTransaction

// UpdateResourceInTransaction updates resource in db in transaction
func UpdateResourceInTransaction(
	context middleware.Context,
	resourceSchema *schema.Schema, resourceID string,
	dataMap map[string]interface{}, tenantIDs []string) error {

	manager := schema.GetManager()
	mainTransaction := context["transaction"].(transaction.Transaction)
	environmentManager := extension.GetManager()
	environment, ok := environmentManager.GetEnvironment(resourceSchema.ID)
	if !ok {
		return fmt.Errorf("No environment for schema")
	}
	resource, err := mainTransaction.Fetch(
		resourceSchema, resourceID, tenantIDs)
	if err != nil {
		return ResourceError{err, err.Error(), WrongQuery}
	}

	policy := context["policy"].(*schema.Policy)
	// apply property filter
	err = policy.ApplyPropertyConditionFilter(schema.ActionUpdate, resource.Data(), dataMap)
	if err != nil {
		return ResourceError{err, "", Unauthorized}
	}

	err = resource.Update(dataMap)
	if err != nil {
		return ResourceError{err, err.Error(), WrongData}
	}
	context["resource"] = resource.Data()

	if err := extension.HandleEvent(context, environment, "pre_update_in_transaction"); err != nil {
		return err
	}

	dataMap, ok = context["resource"].(map[string]interface{})
	if !ok {
		return fmt.Errorf("Resource not JSON: %s", err)
	}
	resource, err = manager.LoadResource(resourceSchema.ID, dataMap)
	if err != nil {
		return fmt.Errorf("Loading Resource failed: %s", err)
	}

	err = mainTransaction.Update(resource)
	if err != nil {
		return ResourceError{err, fmt.Sprintf("Failed to store data in database: %v", err), UpdateFailed}
	}

	response := map[string]interface{}{}
	response[resourceSchema.Singular] = resource.Data()
	context["response"] = response

	if err := extension.HandleEvent(context, environment, "post_update_in_transaction"); err != nil {
		return err
	}

	return nil
}
开发者ID:marcin-ptaszynski,项目名称:gohan,代码行数:60,代码来源:resource_management.go


示例16: DBUpdate

//DBUpdate updates a resource in a db.
func DBUpdate(tx transaction.Transaction, schemaID string, data map[string]interface{}) error {
	manager := schema.GetManager()
	resource, err := manager.LoadResource(schemaID, data)
	if err != nil {
		return err
	}
	return tx.Update(resource)
}
开发者ID:marcin-ptaszynski,项目名称:gohan,代码行数:9,代码来源:gohan.go


示例17: DBColumn

//DBColumn makes partiall part of sql query from schema
func DBColumn(schemaID string, join bool) (string, error) {
	manager := schema.GetManager()
	schemaObj, ok := manager.Schema(schemaID)
	if !ok {
		return "", fmt.Errorf("Schema %s not found", schemaID)
	}
	return strings.Join(sql.MakeColumns(schemaObj, schemaObj.GetDbTableName(), join), ", "), nil
}
开发者ID:marcin-ptaszynski,项目名称:gohan,代码行数:9,代码来源:gohan.go


示例18: DBDelete

//DBDelete deletes a resource in a db.
func DBDelete(tx transaction.Transaction, schemaID string, id string) error {
	manager := schema.GetManager()
	schemaObj, ok := manager.Schema(schemaID)
	if !ok {
		return fmt.Errorf("Schema %s not found", schemaID)
	}
	return tx.Delete(schemaObj, id)
}
开发者ID:marcin-ptaszynski,项目名称:gohan,代码行数:9,代码来源:gohan.go


示例19: getSchema

func getSchema(schemaID string) (*schema.Schema, error) {
	manager := schema.GetManager()
	schema, ok := manager.Schema(schemaID)
	if !ok {
		return nil, fmt.Errorf(unknownSchemaErrorMesssageFormat, schemaID)
	}
	return schema, nil
}
开发者ID:marcin-ptaszynski,项目名称:gohan,代码行数:8,代码来源:otto.go


示例20: syncEvent

func (server *Server) syncEvent(resource *schema.Resource) error {
	schemaManager := schema.GetManager()
	eventSchema, _ := schemaManager.Schema("event")
	tx, err := server.db.Begin()
	if err != nil {
		return err
	}
	defer tx.Close()
	eventType := resource.Get("type").(string)
	resourcePath := resource.Get("path").(string)
	body := resource.Get("body").(string)

	path := generatePath(resourcePath, body)

	version, ok := resource.Get("version").(int)
	if !ok {
		log.Debug("cannot cast version value in int for %s", path)
	}
	log.Debug("event %s", eventType)

	if eventType == "create" || eventType == "update" {
		log.Debug("set %s on sync", path)
		content, err := json.Marshal(map[string]interface{}{
			"body":    body,
			"version": version,
		})
		if err != nil {
			log.Error(fmt.Sprintf("When marshalling sync object: %s", err))
			return err
		}
		err = server.sync.Update(path, string(content))
		if err != nil {
			log.Error(fmt.Sprintf("%s on sync", err))
			return err
		}
	} else if eventType == "delete" {
		log.Debug("delete %s", path)
		err = server.sync.Delete(path)
		if err != nil {
			log.Error(fmt.Sprintf("Delete from sync failed %s", err))
			return err
		}
	}
	log.Debug("delete event %d", resource.Get("id"))
	id := resource.Get("id")
	err = tx.Delete(eventSchema, id)
	if err != nil {
		log.Error(fmt.Sprintf("delete failed: %s", err))
		return err
	}

	err = tx.Commit()
	if err != nil {
		log.Error(fmt.Sprintf("commit failed: %s", err))
		return err
	}
	return nil
}
开发者ID:marcin-ptaszynski,项目名称:gohan,代码行数:58,代码来源:sync.go



注:本文中的github.com/cloudwan/gohan/schema.GetManager函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang schema.NewAuthorization函数代码示例发布时间:2022-05-23
下一篇:
Golang schema.ClearManager函数代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap