Exemple #1
0
func reorderPositions(scope *gorm.Scope) {
	if !scope.HasError() {
		if _, ok := scope.Value.(sortingInterface); ok {
			table := scope.TableName()
			var additionalSQL []string
			var additionalValues []interface{}
			// with l10n
			if locale, ok := scope.DB().Get("l10n:locale"); ok && locale.(string) != "" {
				additionalSQL = append(additionalSQL, "language_code = ?")
				additionalValues = append(additionalValues, locale)
			}
			additionalValues = append(additionalValues, additionalValues...)

			// with soft delete
			if scope.HasColumn("DeletedAt") {
				additionalSQL = append(additionalSQL, "deleted_at IS NULL")
			}

			var sql = fmt.Sprintf("UPDATE %v SET position = (SELECT COUNT(pos) + 1 FROM (SELECT DISTINCT(position) AS pos FROM %v WHERE %v) AS t2 WHERE t2.pos < %v.position) WHERE %v", table, table, strings.Join(additionalSQL, " AND "), table, strings.Join(additionalSQL, " AND "))
			if scope.NewDB().Exec(sql, additionalValues...).Error == nil {
				// Create Publish Event
				createPublishEvent(scope.DB(), scope.Value)
			}
		}
	}
}
Exemple #2
0
func afterUpdate(scope *gorm.Scope) {
	if !scope.HasError() {
		if isLocalizable(scope) {
			if locale, ok := getLocale(scope); ok {
				if scope.DB().RowsAffected == 0 && !scope.PrimaryKeyZero() { //is locale and nothing updated
					var count int
					var query = fmt.Sprintf("%v.language_code = ? AND %v.%v = ?", scope.QuotedTableName(), scope.QuotedTableName(), scope.PrimaryKey())

					// if enabled soft delete, delete soft deleted records
					if scope.HasColumn("DeletedAt") {
						scope.NewDB().Unscoped().Where("deleted_at is not null").Where(query, locale, scope.PrimaryKeyValue()).Delete(scope.Value)
					}

					// if no localized records exist, localize it
					if scope.NewDB().Table(scope.TableName()).Where(query, locale, scope.PrimaryKeyValue()).Count(&count); count == 0 {
						scope.DB().Create(scope.Value)
					}
				}
			} else if syncColumns := syncColumns(scope); len(syncColumns) > 0 { // is global
				if mode, _ := scope.DB().Get("l10n:mode"); mode != "unscoped" {
					if scope.DB().RowsAffected > 0 {
						var primaryField = scope.PrimaryField()
						var syncAttrs = map[string]interface{}{}

						if updateAttrs, ok := scope.InstanceGet("gorm:update_attrs"); ok {
							for key, value := range updateAttrs.(map[string]interface{}) {
								for _, syncColumn := range syncColumns {
									if syncColumn == key {
										syncAttrs[syncColumn] = value
										break
									}
								}
							}
						} else {
							var fields = scope.Fields()
							for _, syncColumn := range syncColumns {
								if field, ok := fields[syncColumn]; ok && field.IsNormal {
									syncAttrs[syncColumn] = field.Field.Interface()
								}
							}
						}

						if len(syncAttrs) > 0 {
							db := scope.DB().Model(reflect.New(utils.ModelType(scope.Value)).Interface()).Set("l10n:mode", "unscoped").Where("language_code <> ?", Global)
							if !primaryField.IsBlank {
								db = db.Where(fmt.Sprintf("%v = ?", primaryField.DBName), primaryField.Field.Interface())
							}
							scope.Err(db.UpdateColumns(syncAttrs).Error)
						}
					}
				}
			}
		}
	}
}
Exemple #3
0
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
}
Exemple #4
0
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)
	}
}
Exemple #5
0
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
}
Exemple #6
0
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)
		}
	}
}
Exemple #7
0
// 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
	}
}
Exemple #8
0
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 scope.TableName() },
		"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 fmt.Sprintf("%v.%v%v", strings.TrimSuffix(filename, path.Ext(filename)), hash(), path.Ext(filename))
		},
		"extension": func() string { return strings.TrimPrefix(path.Ext(filename), ".") },
	}
}
Exemple #9
0
func afterUpdate(scope *gorm.Scope) {
	if !scope.HasError() {
		if isLocalizable(scope) {
			if locale, ok := getLocale(scope); ok {
				if scope.DB().RowsAffected == 0 && !scope.PrimaryKeyZero() { //is locale and nothing updated
					var count int
					var query = fmt.Sprintf("%v.language_code = ? AND %v.%v = ?", scope.QuotedTableName(), scope.QuotedTableName(), scope.PrimaryKey())
					if scope.NewDB().Table(scope.TableName()).Where(query, locale, scope.PrimaryKeyValue()).Count(&count); count == 0 {
						scope.DB().Create(scope.Value)
					}
				}
			} else if syncColumns := syncColumns(scope); len(syncColumns) > 0 { // is global
				if mode, _ := scope.DB().Get("l10n:mode"); mode != "unscoped" {
					if scope.DB().RowsAffected > 0 {
						primaryKey := scope.PrimaryKeyValue()

						if updateAttrs, ok := scope.InstanceGet("gorm:update_attrs"); ok {
							var syncAttrs = map[string]interface{}{}
							for key, value := range updateAttrs.(map[string]interface{}) {
								for _, syncColumn := range syncColumns {
									if syncColumn == key {
										syncAttrs[syncColumn] = value
										break
									}
								}
							}
							if len(syncAttrs) > 0 {
								scope.DB().Model(scope.Value).Set("l10n:mode", "unscoped").Where("language_code <> ?", Global).UpdateColumns(syncAttrs)
							}
						} else {
							scope.NewDB().Set("l10n:mode", "unscoped").Where(fmt.Sprintf("%v = ?", scope.PrimaryKey()), primaryKey).Select(syncColumns).Save(scope.Value)
						}
					}
				}
			}
		}
	}
}
Exemple #10
0
func setIdentityInsert(scope *gorm.Scope) {
	if scope.Dialect().GetName() == "mssql" {
		scope.NewDB().Exec(fmt.Sprintf("SET IDENTITY_INSERT %v ON", scope.TableName()))
	}
}