本文整理汇总了Golang中github.com/cloudwan/gohan/schema.Schema类的典型用法代码示例。如果您正苦于以下问题:Golang Schema类的具体用法?Golang Schema怎么用?Golang Schema使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Schema类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: 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
}
示例2: 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
}
示例3: ActionResource
// ActionResource runs custom action on resource
func ActionResource(context middleware.Context, dataStore db.DB, identityService middleware.IdentityService,
resourceSchema *schema.Schema, action schema.Action, resourceID string, data interface{},
) error {
actionSchema := action.InputSchema
context["input"] = data
context["id"] = resourceID
environmentManager := extension.GetManager()
environment, ok := environmentManager.GetEnvironment(resourceSchema.ID)
if !ok {
return fmt.Errorf("No environment for schema")
}
if actionSchema != nil {
err := resourceSchema.Validate(actionSchema, data)
if err != nil {
return ResourceError{err, fmt.Sprintf("Validation error: %s", err), WrongData}
}
}
err := extension.HandleEvent(context, environment, action.ID)
if err != nil {
return err
}
if _, ok := context["response"]; ok {
return nil
}
return fmt.Errorf("no response")
}
示例4: addFilterToQuery
func addFilterToQuery(s *schema.Schema, q sq.SelectBuilder, filter map[string]interface{}, join bool) sq.SelectBuilder {
if filter == nil {
return q
}
for key, value := range filter {
property, err := s.GetPropertyByID(key)
var column string
if join {
column = makeColumn(s, *property)
} else {
column = quote(key)
}
if err != nil {
log.Notice(err.Error())
continue
}
if property.Type == "boolean" {
v := make([]bool, len(value.([]string)))
for i, j := range value.([]string) {
v[i], _ = strconv.ParseBool(j)
}
q = q.Where(sq.Eq{column: v})
} else {
q = q.Where(sq.Eq{column: value})
}
}
return q
}
示例5: StateFetch
//StateFetch fetches the state of the specified resource
func (tx *Transaction) StateFetch(s *schema.Schema, filter transaction.Filter) (state transaction.ResourceState, err error) {
if !s.StateVersioning() {
err = fmt.Errorf("Schema %s does not support state versioning.", s.ID)
return
}
cols := makeStateColumns(s)
q := sq.Select(cols...).From(quote(s.GetDbTableName()))
q, _ = addFilterToQuery(s, q, filter, true)
sql, args, err := q.ToSql()
if err != nil {
return
}
logQuery(sql, args...)
rows, err := tx.transaction.Queryx(sql, args...)
if err != nil {
return
}
defer rows.Close()
if !rows.Next() {
err = fmt.Errorf("No resource found")
return
}
data := map[string]interface{}{}
rows.MapScan(data)
err = decodeState(data, &state)
return
}
示例6: getArgsAsMap
func getArgsAsMap(args []string, s *schema.Schema) (map[string]interface{}, error) {
if len(args)%2 != 0 {
return nil, fmt.Errorf("Parameters should be in [--param-name value]... format")
}
result := map[string]interface{}{}
for i := 0; i < len(args); i += 2 {
key := strings.TrimPrefix(args[i], "--")
valueType := "string"
if property, err := s.GetPropertyByID(key); err == nil {
valueType = property.Type
}
rawValue := args[i+1]
var value interface{}
var err error
if rawValue == "<null>" {
value = nil
} else {
switch valueType {
case "integer", "number":
value, err = strconv.ParseInt(rawValue, 10, 64)
case "boolean":
value, err = strconv.ParseBool(rawValue)
case "array", "object":
err = json.Unmarshal([]byte(rawValue), &value)
default:
value = rawValue
}
if err != nil {
return nil, fmt.Errorf("Error parsing parameter '%v': %v", key, err)
}
}
result[key] = value
}
return result, nil
}
示例7: addFilterToQuery
func addFilterToQuery(s *schema.Schema, q sq.SelectBuilder, filter map[string]interface{}, join bool) (sq.SelectBuilder, error) {
if filter == nil {
return q, nil
}
for key, value := range filter {
property, err := s.GetPropertyByID(key)
if err != nil {
return q, err
}
var column string
if join {
column = makeColumn(s.GetDbTableName(), *property)
} else {
column = quote(key)
}
queryValues, ok := value.([]string)
if ok && property.Type == "boolean" {
v := make([]bool, len(queryValues))
for i, j := range queryValues {
v[i], _ = strconv.ParseBool(j)
}
q = q.Where(sq.Eq{column: v})
} else {
q = q.Where(sq.Eq{column: value})
}
}
return q, nil
}
示例8: Delete
//Delete delete resource from db
func (tx *Transaction) Delete(s *schema.Schema, resourceID interface{}) error {
sql, args, err := sq.Delete(quote(s.GetDbTableName())).Where(sq.Eq{"id": resourceID}).ToSql()
if err != nil {
return err
}
return tx.Exec(sql, args...)
}
示例9: createResourcesTable
func (gohanClientCLI *GohanClientCLI) createResourcesTable(s *schema.Schema, buffer *bytes.Buffer, resources []interface{}) {
table := tablewriter.NewWriter(buffer)
if len(resources) == 0 {
return
}
table.SetHeader(s.Titles())
for _, rawResource := range resources {
resourceSlice := []string{}
resource := rawResource.(map[string]interface{})
for _, property := range s.Properties {
v := ""
if val, ok := resource[property.ID]; ok && val != nil {
switch property.Type {
case "string":
v = fmt.Sprint(val)
if property.RelationProperty != "" {
relatedResource := resource[property.RelationProperty].(map[string]interface{})
v = relatedResource["name"].(string)
}
default:
v = fmt.Sprint(val)
}
}
resourceSlice = append(resourceSlice, v)
}
table.Append(resourceSlice)
}
table.Render()
}
示例10: DropTable
//DropTable drop table definition
func (db *DB) DropTable(s *schema.Schema) error {
if s.IsAbstract() {
return nil
}
sql := fmt.Sprintf("drop table if exists %s\n", quote(s.GetDbTableName()))
_, err := db.DB.Exec(sql)
return err
}
示例11: GenTableDef
//GenTableDef generates table create sql
func (db *DB) GenTableDef(s *schema.Schema, cascade bool) string {
schemaManager := schema.GetManager()
var cols []string
var relations []string
cascadeString := ""
if cascade {
cascadeString = "on delete cascade"
}
for _, property := range s.Properties {
handler := db.handlers[property.Type]
dataType := property.SQLType
if db.sqlType == "sqlite3" {
dataType = strings.Replace(dataType, "auto_increment", "autoincrement", 1)
}
if dataType == "" {
dataType = handler.dataType(&property)
if property.ID == "id" {
dataType += " primary key"
} else {
if property.Nullable {
dataType += " null"
} else {
dataType += " not null"
}
if property.Unique {
dataType += " unique"
}
}
}
sql := "`" + property.ID + "`" + dataType
cols = append(cols, sql)
if property.Relation != "" {
foreignSchema, _ := schemaManager.Schema(property.Relation)
if foreignSchema != nil {
relations = append(relations, fmt.Sprintf("foreign key(`%s`) REFERENCES `%s`(id) %s",
property.ID, foreignSchema.GetDbTableName(), cascadeString))
}
}
}
if s.Parent != "" {
foreignSchema, _ := schemaManager.Schema(s.Parent)
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
}
示例12: makeStateColumns
func makeStateColumns(s *schema.Schema) (cols []string) {
dbTableName := s.GetDbTableName()
cols = append(cols, dbTableName+"."+configVersionColumnName+" as "+quote(configVersionColumnName))
cols = append(cols, dbTableName+"."+stateVersionColumnName+" as "+quote(stateVersionColumnName))
cols = append(cols, dbTableName+"."+stateErrorColumnName+" as "+quote(stateErrorColumnName))
cols = append(cols, dbTableName+"."+stateColumnName+" as "+quote(stateColumnName))
cols = append(cols, dbTableName+"."+stateMonitoringColumnName+" as "+quote(stateMonitoringColumnName))
return cols
}
示例13: getTable
func (db *DB) getTable(s *schema.Schema) []interface{} {
rawTable, ok := db.data[s.GetDbTableName()]
if ok {
return rawTable.([]interface{})
}
newTable := []interface{}{}
db.data[s.GetDbTableName()] = newTable
return newTable
}
示例14: FilterFromQueryParameter
//FilterFromQueryParameter makes list filter from query
func FilterFromQueryParameter(resourceSchema *schema.Schema,
queryParameters map[string][]string) map[string]interface{} {
filter := map[string]interface{}{}
for key, value := range queryParameters {
if _, err := resourceSchema.GetPropertyByID(key); err != nil {
log.Info("Resource %s does not have %s property, ignoring filter.")
continue
}
filter[key] = value
}
return filter
}
示例15: DeleteResource
// DeleteResource deletes the resource specified by the schema and ID
func DeleteResource(context middleware.Context,
dataStore db.DB,
resourceSchema *schema.Schema,
resourceID string,
) error {
context["id"] = resourceID
environmentManager := extension.GetManager()
environment, ok := environmentManager.GetEnvironment(resourceSchema.ID)
if !ok {
return fmt.Errorf("No environment for schema")
}
auth := context["auth"].(schema.Authorization)
policy, err := loadPolicy(context, "delete", strings.Replace(resourceSchema.GetSingleURL(), ":id", resourceID, 1), auth)
if err != nil {
return err
}
context["policy"] = policy
preTransaction, err := dataStore.Begin()
if err != nil {
return fmt.Errorf("cannot create transaction: %v", err)
}
tenantIDs := policy.GetTenantIDFilter(schema.ActionDelete, auth.TenantID())
filter := transaction.IDFilter(resourceID)
if tenantIDs != nil {
filter["tenant_id"] = tenantIDs
}
resource, fetchErr := preTransaction.Fetch(resourceSchema, filter)
preTransaction.Close()
if resource != nil {
context["resource"] = resource.Data()
}
if err := extension.HandleEvent(context, environment, "pre_delete"); err != nil {
return err
}
if fetchErr != nil {
return ResourceError{err, "", NotFound}
}
if err := InTransaction(
context, dataStore,
transaction.GetIsolationLevel(resourceSchema, schema.ActionDelete),
func() error {
return DeleteResourceInTransaction(context, resourceSchema, resourceID)
},
); err != nil {
return err
}
if err := extension.HandleEvent(context, environment, "post_delete"); err != nil {
return err
}
return nil
}