예제 #1
0
파일: scope.go 프로젝트: nilslice/qor
func isLocalizable(scope *gorm.Scope) (isLocalizable bool) {
	if scope.GetModelStruct().ModelType == nil {
		return false
	}
	_, isLocalizable = reflect.New(scope.GetModelStruct().ModelType).Interface().(l10nInterface)
	return
}
예제 #2
0
파일: resource.go 프로젝트: caizengjun/qor
// PrimaryField return gorm's primary field
func (res *Resource) PrimaryField() *gorm.Field {
	if res.primaryField == nil {
		scope := gorm.Scope{Value: res.Value}
		res.primaryField = scope.PrimaryField()
	}
	return res.primaryField
}
예제 #3
0
파일: callbacks.go 프로젝트: 8legd/qor-qor
func assignCreatedBy(scope *gorm.Scope) {
	if isAuditable(scope) {
		if user, ok := getCurrentUser(scope); ok {
			scope.SetColumn("CreatedBy", user)
		}
	}
}
예제 #4
0
파일: models.go 프로젝트: thnguyn2/WebGPU
func updateTimeStampWhenCreate(scope *gorm.Scope) {
	if !scope.HasError() {
		now := time.Now()
		scope.SetColumn("Created", now)
		scope.SetColumn("Updated", now)
	}
}
예제 #5
0
func syncToProductionAfterDelete(scope *gorm.Scope) {
	if !scope.HasError() {
		if ok, clone := getModeAndNewScope(scope); ok {
			gorm.Delete(clone)
		}
	}
}
예제 #6
0
파일: callbacks.go 프로젝트: tomi-/qor
func beforeDelete(scope *gorm.Scope) {
	if isLocalizable(scope) {
		if locale, ok := getLocale(scope); ok { // is locale
			scope.Search.Where(fmt.Sprintf("%v.language_code = ?", scope.QuotedTableName()), locale)
		}
	}
}
예제 #7
0
파일: scope.go 프로젝트: nilslice/qor
func setLocale(scope *gorm.Scope, locale string) {
	for _, field := range scope.Fields() {
		if field.Name == "LanguageCode" {
			field.Set(locale)
		}
	}
}
예제 #8
0
파일: callbacks.go 프로젝트: qor/publish
func syncDeleteFromProductionToDraft(scope *gorm.Scope) {
	if !scope.HasError() {
		if ok, clone := isProductionModeAndNewScope(scope); ok {
			scope.DB().Callback().Delete().Get("gorm:delete")(clone)
		}
	}
}
예제 #9
0
파일: callbacks.go 프로젝트: 8legd/qor-qor
func syncDeleteFromProductionToDraft(scope *gorm.Scope) {
	if !scope.HasError() {
		if ok, clone := isProductionModeAndNewScope(scope); ok {
			gorm.Delete(clone)
		}
	}
}
예제 #10
0
파일: callbacks.go 프로젝트: kennylixi/qor
func isDraftMode(scope *gorm.Scope) bool {
	if draftMode, ok := scope.Get("publish:draft_mode"); ok {
		if isDraft, ok := draftMode.(bool); ok && isDraft {
			return true
		}
	}
	return false
}
예제 #11
0
파일: scope.go 프로젝트: nilslice/qor
func getLocale(scope *gorm.Scope) (locale string, ok bool) {
	if str, ok := scope.DB().Get("l10n:locale"); ok {
		if locale, ok := str.(string); ok {
			return locale, (locale != Global) && (locale != "")
		}
	}
	return Global, false
}
예제 #12
0
파일: scope.go 프로젝트: nilslice/qor
func syncColumns(scope *gorm.Scope) (columns []string) {
	for _, field := range scope.GetModelStruct().StructFields {
		if isSyncField(field) {
			columns = append(columns, field.DBName)
		}
	}
	return
}
예제 #13
0
파일: callbacks.go 프로젝트: kennylixi/qor
func validate(scope *gorm.Scope) {
	db := scope.DB()
	if _, ok := db.Get(settingKey); !ok {
		db.InstantSet(settingKey, map[string][]string{})
	}

	if result, ok := db.Get(skipValidations); !(ok && result.(bool)) {
		scope.CallMethodWithErrorCheck("Validate")
	}
}
예제 #14
0
파일: callbacks.go 프로젝트: kennylixi/qor
func syncToProductionAfterUpdate(scope *gorm.Scope) {
	if ok, clone := getModeAndNewScope(scope); ok {
		if updateAttrs, ok := scope.InstanceGet("gorm:update_attrs"); ok {
			table := originalTableName(scope.TableName())
			clone.Search = scope.Search
			clone.Search.Table(table)
			clone.InstanceSet("gorm:update_attrs", updateAttrs)
		}
		gorm.Update(clone)
	}
}
func (user *User) setEncryptedPassword(scope *gorm.Scope) error {
	pw, err := bcrypt.GenerateFromPassword([]byte(user.Password), 0)
	if err != nil {
		return err
	}

	scope.SetColumn("EncryptedPassword", string(pw))
	user.Password = ""

	return nil
}
예제 #16
0
파일: resolver.go 프로젝트: qor/publish
func toQueryCondition(scope *gorm.Scope, columns []string) string {
	var newColumns []string
	for _, column := range columns {
		newColumns = append(newColumns, scope.Quote(column))
	}

	if len(columns) > 1 {
		return fmt.Sprintf("(%v)", strings.Join(newColumns, ","))
	}
	return strings.Join(columns, ",")
}
예제 #17
0
파일: callbacks.go 프로젝트: nilslice/qor
func beforeCreate(scope *gorm.Scope) {
	if isLocalizable(scope) {
		if locale, ok := getLocale(scope); ok { // is locale
			if isLocaleCreateable(scope) || !scope.PrimaryKeyZero() {
				setLocale(scope, locale)
			} else {
				scope.Err(errors.New("permission denied to create from locale"))
			}
		} else {
			setLocale(scope, Global)
		}
	}
}
예제 #18
0
func (session *Session) BeforeCreate(scope *gorm.Scope) error {
	scope.SetColumn("Token", GenerateRandomString(64))
	scope.SetColumn("UUID", generateUUID())
	scope.SetColumn("Moment", time.Now().UTC().Unix())
	scope.SetColumn("ExpiresIn", expirationLengthForTokenType(session.TokenType))
	return nil
}
예제 #19
0
파일: base.go 프로젝트: gitter-badger/qor
func getFuncMap(scope *gorm.Scope, field *gorm.Field, filename string) template.FuncMap {
	hash := func() string { return strings.Replace(time.Now().Format("20060102150506.000000000"), ".", "", -1) }
	return template.FuncMap{
		"class":       scope.TableName,
		"primary_key": func() string { return fmt.Sprintf("%v", scope.PrimaryKeyValue()) },
		"column":      func() string { return field.Name },
		"filename":    func() string { return filename },
		"basename":    func() string { return strings.TrimSuffix(path.Base(filename), path.Ext(filename)) },
		"hash":        hash,
		"filename_with_hash": func() string {
			return fmt.Sprintf("%v.%v%v", strings.TrimSuffix(filename, path.Ext(filename)), hash(), path.Ext(filename))
		},
		"extension": func() string { return strings.TrimPrefix(path.Ext(filename), ".") },
	}
}
예제 #20
0
파일: base.go 프로젝트: qor/media_library
func getFuncMap(scope *gorm.Scope, field *gorm.Field, filename string) template.FuncMap {
	hash := func() string { return strings.Replace(time.Now().Format("20060102150506.000000000"), ".", "", -1) }
	return template.FuncMap{
		"class":       func() string { return inflection.Plural(utils.ToParamString(scope.GetModelStruct().ModelType.Name())) },
		"primary_key": func() string { return fmt.Sprintf("%v", scope.PrimaryKeyValue()) },
		"column":      func() string { return strings.ToLower(field.Name) },
		"filename":    func() string { return filename },
		"basename":    func() string { return strings.TrimSuffix(path.Base(filename), path.Ext(filename)) },
		"hash":        hash,
		"filename_with_hash": func() string {
			return urlReplacer.ReplaceAllString(fmt.Sprintf("%v.%v%v", strings.TrimSuffix(filename, path.Ext(filename)), hash(), path.Ext(filename)), "-")
		},
		"extension": func() string { return strings.TrimPrefix(path.Ext(filename), ".") },
	}
}
예제 #21
0
파일: callbacks.go 프로젝트: yanzay/qor
func beforeUpdate(scope *gorm.Scope) {
	if isLocalizable(scope) {
		locale, isLocale := getLocale(scope)

		switch mode, _ := scope.DB().Get("l10n:mode"); mode {
		case "unscoped":
		default:
			scope.Search.Where("language_code = ?", locale)
			setLocale(scope, locale)
		}

		if isLocale {
			scope.Search.Omit(syncColumns(scope)...)
		}
	}
}
예제 #22
0
파일: callbacks.go 프로젝트: qor/publish
func createPublishEvent(scope *gorm.Scope) {
	if _, ok := scope.InstanceGet("publish:creating_publish_event"); ok {
		if event, ok := scope.Get(publishEvent); ok {
			if event, ok := event.(*PublishEvent); ok {
				event.PublishStatus = DIRTY
				scope.Err(scope.NewDB().Save(&event).Error)
			}
		}
	}
}
예제 #23
0
파일: callbacks.go 프로젝트: kennylixi/qor
func getModeAndNewScope(scope *gorm.Scope) (isProduction bool, clone *gorm.Scope) {
	if draftMode, ok := scope.Get("publish:draft_mode"); !ok || !draftMode.(bool) {
		if _, ok := scope.InstanceGet("publish:supported_model"); ok {
			table := originalTableName(scope.TableName())
			clone := scope.New(scope.Value)
			clone.Search.Table(table)
			return true, clone
		}
	}
	return false, nil
}
예제 #24
0
파일: callbacks.go 프로젝트: qor/publish
func isProductionModeAndNewScope(scope *gorm.Scope) (isProduction bool, clone *gorm.Scope) {
	if !IsDraftMode(scope.DB()) {
		if _, ok := scope.InstanceGet("publish:supported_model"); ok {
			table := OriginalTableName(scope.TableName())
			clone := scope.New(scope.Value)
			clone.Search.Table(table)
			return true, clone
		}
	}
	return false, nil
}
예제 #25
0
func assignUpdatedBy(scope *gorm.Scope) {
	if isAuditable(scope) {
		if user, ok := scope.DB().Get("audited:current_user"); ok {
			var currentUser string
			if primaryField := scope.New(user).PrimaryField(); primaryField != nil {
				currentUser = fmt.Sprintf("%v", primaryField.Field.Interface())
			} else {
				currentUser = fmt.Sprintf("%v", user)
			}

			if attrs, ok := scope.InstanceGet("gorm:update_attrs"); ok {
				updateAttrs := attrs.(map[string]interface{})
				updateAttrs["updated_by"] = currentUser
				scope.InstanceSet("gorm:update_attrs", updateAttrs)
			} else {
				scope.SetColumn("UpdatedBy", currentUser)
			}
		}
	}
}
예제 #26
0
파일: callbacks.go 프로젝트: qor/publish
func syncUpdateFromProductionToDraft(scope *gorm.Scope) {
	if !scope.HasError() {
		if ok, clone := isProductionModeAndNewScope(scope); ok {
			if updateAttrs, ok := scope.InstanceGet("gorm:update_attrs"); ok {
				table := OriginalTableName(scope.TableName())
				clone.Search = scope.Search
				clone.Search.Table(table)
				clone.InstanceSet("gorm:update_attrs", updateAttrs)
			}
			scope.DB().Callback().Update().Get("gorm:update")(clone)
		}
	}
}
예제 #27
0
func cropField(field *gorm.Field, scope *gorm.Scope) (cropped bool) {
	if field.Field.CanAddr() {
		// TODO Handle scanner
		if media, ok := field.Field.Addr().Interface().(Media); ok && !media.Cropped() {
			option := parseTagOption(field.Tag.Get("media_library"))
			if media.GetFileHeader() != nil || media.NeedCrop() {
				var file multipart.File
				var err error
				if fileHeader := media.GetFileHeader(); fileHeader != nil {
					file, err = media.GetFileHeader().Open()
				} else {
					file, err = media.Retrieve(media.URL("original"))
				}

				if err != nil {
					scope.Err(err)
					return false
				}

				media.Cropped(true)

				if url := media.GetURL(option, scope, field, media); url == "" {
					scope.Err(errors.New("invalid URL"))
				} else {
					result, _ := json.Marshal(map[string]string{"Url": url})
					media.Scan(string(result))
				}

				if file != nil {
					defer file.Close()
					var handled = false
					for _, handler := range mediaHandlers {
						if handler.CouldHandle(media) {
							file.Seek(0, 0)
							if scope.Err(handler.Handle(media, file, option)) == nil {
								handled = true
							}
						}
					}

					// Save File
					if !handled {
						scope.Err(media.Store(media.URL(), option, file))
					}
				}
				return true
			}
		}
	}
	return false
}
예제 #28
0
파일: callbacks.go 프로젝트: tomi-/qor
func beforeQuery(scope *gorm.Scope) {
	if isLocalizable(scope) {
		quotedTableName := scope.QuotedTableName()
		locale, _ := getLocale(scope)
		switch mode, _ := scope.DB().Get("l10n:mode"); mode {
		case "locale":
			scope.Search.Where(fmt.Sprintf("%v.language_code = ?", quotedTableName), locale)
		case "global":
			scope.Search.Where(fmt.Sprintf("%v.language_code = ?", quotedTableName), Global)
		case "unscoped":
		default:
			quotedPrimaryKey := scope.Quote(scope.PrimaryKey())
			scope.Search.Unscoped = true
			if scope.Fields()["deleted_at"] != nil {
				scope.Search.Where(fmt.Sprintf("((%v NOT IN (SELECT DISTINCT(%v) FROM %v t2 WHERE t2.language_code = ? AND t2.deleted_at IS NULL) AND language_code = ?) OR language_code = ?) AND deleted_at IS NULL", quotedPrimaryKey, quotedPrimaryKey, quotedTableName), locale, Global, locale)
			} else {
				scope.Search.Where(fmt.Sprintf("(%v NOT IN (SELECT DISTINCT(%v) FROM %v t2 WHERE t2.language_code = ?) AND language_code = ?) OR (language_code = ?)", quotedPrimaryKey, quotedPrimaryKey, quotedTableName), locale, Global, locale)
			}
		}
	}
}
예제 #29
0
파일: callbacks.go 프로젝트: 8legd/qor-qor
func validate(scope *gorm.Scope) {
	if _, ok := scope.Get("gorm:update_column"); !ok {
		if result, ok := scope.DB().Get(skipValidations); !(ok && result.(bool)) {
			scope.CallMethodWithErrorCheck("Validate")
		}
	}
}
예제 #30
0
파일: db.go 프로젝트: alfateam123/nerdz-api
// Callback function: invoked after the creation/update of an object. To populate its default fields
func updateFields(scope *gorm.Scope) {
	if !scope.HasError() {
		newScope := scope.New(scope.Value)
		newScope.Search = newScope.Search.Table(scope.TableName())

		if scope.PrimaryKey() != "" {
			gorm.Query(newScope)
		} else {
			// TODO: find a way to populate fields of scope.Value selecting * matching on every fields

		}
		scope = newScope
	}
}