Example #1
0
// DeleteCreatedEntities records all created entities on the gorm.DB connection
// and returns a function which can be called on defer to delete created
// entities in reverse order on function exit.
//
// In addition to that, the WIT cache is cleared as well in order to respect any
// deletions made to the db.
//
// Usage:
//
// func TestDatabaseActions(t *testing.T) {
//
// 	// setup database connection
// 	db := ....
// 	// setup auto clean up of created entities
// 	defer DeleteCreatedEntities(db)()
//
// 	repo := NewRepo(db)
// 	repo.Create(X)
// 	repo.Create(X)
// 	repo.Create(X)
// }
//
// Output:
//
// 2017/01/31 12:08:08 Deleting from x 6d143405-1232-40de-bc73-835b543cd972
// 2017/01/31 12:08:08 Deleting from x 0685068d-4934-4d9a-bac2-91eebbca9575
// 2017/01/31 12:08:08 Deleting from x 2d20944e-7952-40c1-bd15-f3fa1a70026d
func DeleteCreatedEntities(db *gorm.DB) func() {
	hookName := "mighti:record"
	type entity struct {
		table   string
		keyname string
		key     interface{}
	}
	var entires []entity
	db.Callback().Create().After("gorm:create").Register(hookName, func(scope *gorm.Scope) {
		entires = append(entires, entity{table: scope.TableName(), keyname: scope.PrimaryKey(), key: scope.PrimaryKeyValue()})
	})
	return func() {
		defer db.Callback().Create().Remove(hookName)
		tx := db.Begin()
		for i := len(entires) - 1; i >= 0; i-- {
			entry := entires[i]
			log.Debug(nil, map[string]interface{}{
				"pkg":   "cleaner",
				"table": entry.table,
				"key":   entry.key,
			}, "Deleting entities from %s with key %s", entry.table, entry.key)
			tx.Table(entry.table).Where(entry.keyname+" = ?", entry.key).Delete("")
		}

		// Delete the work item cache as well
		// NOTE: Feel free to add more cache freeing calls here as needed.
		workitem.ClearGlobalWorkItemTypeCache()

		tx.Commit()
	}
}
Example #2
0
func RegisterCallbacks(db *gorm.DB) {
	callback := db.Callback()

	callback.Create().Before("gorm:before_create").Register("l10n:before_create", beforeCreate)

	callback.Update().Before("gorm:before_update").Register("l10n:before_update", beforeUpdate)
	callback.Update().After("gorm:after_update").Register("l10n:after_update", afterUpdate)

	callback.Delete().Before("gorm:before_delete").Register("l10n:before_delete", beforeDelete)

	callback.RowQuery().Register("l10n:before_query", beforeQuery)
	callback.Query().Before("gorm:query").Register("l10n:before_query", beforeQuery)
}
Example #3
0
func RegisterCallbacks(db *gorm.DB) {
	db.Callback().Query().Before("gorm:query").Register("sorting:sort_by_position", beforeQuery)

	db.Callback().Create().Before("gorm:commit_or_rollback_transaction").
		Register("sorting:initalize_position", initalizePosition)
}
Example #4
0
func New(db *gorm.DB) *Publish {
	tableHandler := gorm.DefaultTableNameHandler
	gorm.DefaultTableNameHandler = func(db *gorm.DB, defaultTableName string) string {
		tableName := tableHandler(db, defaultTableName)

		if db != nil {
			if isPublishableModel(db.Value) {
				// Set join table handler
				typ := modelType(db.Value)
				if !injectedJoinTableHandler[typ] {
					injectedJoinTableHandler[typ] = true
					scope := db.NewScope(db.Value)
					for _, field := range scope.GetModelStruct().StructFields {
						if many2many := utils.ParseTagOption(field.Tag.Get("gorm"))["MANY2MANY"]; many2many != "" {
							db.SetJoinTableHandler(db.Value, field.Name, &publishJoinTableHandler{})
							db.AutoMigrate(db.Value)
						}
					}
				}

				var forceDraftMode = false
				if forceMode, ok := db.Get("publish:force_draft_mode"); ok {
					if forceMode, ok := forceMode.(bool); ok && forceMode {
						forceDraftMode = true
					}
				}

				if draftMode, ok := db.Get("publish:draft_mode"); ok {
					if isDraft, ok := draftMode.(bool); ok && isDraft || forceDraftMode {
						return draftTableName(tableName)
					}
				}
			}
		}
		return tableName
	}

	db.Callback().Create().Before("gorm:begin_transaction").Register("publish:set_table_to_draft", setTableAndPublishStatus(true))
	db.Callback().Create().Before("gorm:commit_or_rollback_transaction").
		Register("publish:sync_to_production_after_create", syncToProductionAfterCreate)

	db.Callback().Delete().Before("gorm:begin_transaction").Register("publish:set_table_to_draft", setTableAndPublishStatus(true))
	db.Callback().Delete().Replace("gorm:delete", deleteScope)
	db.Callback().Delete().Before("gorm:commit_or_rollback_transaction").
		Register("publish:sync_to_production_after_delete", syncToProductionAfterDelete)

	db.Callback().Update().Before("gorm:begin_transaction").Register("publish:set_table_to_draft", setTableAndPublishStatus(true))
	db.Callback().Update().Before("gorm:commit_or_rollback_transaction").
		Register("publish:sync_to_production", syncToProductionAfterUpdate)

	db.Callback().RowQuery().Register("publish:set_table_in_draft_mode", setTableAndPublishStatus(false))
	db.Callback().Query().Before("gorm:query").Register("publish:set_table_in_draft_mode", setTableAndPublishStatus(false))
	return &Publish{DB: db}
}
Example #5
0
func RegisterCallbacks(db *gorm.DB) {
	callback := db.Callback()
	callback.Create().After("gorm:before_create").Register("audited:assign_created_by", assignCreatedBy)
	callback.Update().After("gorm:before_update").Register("audited:assign_updated_by", assignUpdatedBy)
}
Example #6
0
func RegisterCallbacks(db *gorm.DB) {
	callback := db.Callback()
	callback.Create().Before("gorm:before_create").Register("validations:validate", validate)
	callback.Update().Before("gorm:before_update").Register("validations:validate", validate)
}
Example #7
0
// RegisterCallbacks register callbacks into gorm db instance
func RegisterCallbacks(db *gorm.DB) {
	db.Callback().Create().Before("gorm:create").Register("sorting:initalize_position", initalizePosition)
	db.Callback().Delete().After("gorm:after_delete").Register("sorting:reorder_positions", reorderPositions)
	db.Callback().Query().Before("gorm:query").Register("sorting:sort_by_position", beforeQuery)
}
Example #8
0
func RegisterCallbacks(db *gorm.DB) {
	db.Callback().Update().Before("gorm:before_update").Register("media_library:save_and_crop", SaveAndCropImage(false))
	db.Callback().Create().After("gorm:after_create").Register("media_library:save_and_crop", SaveAndCropImage(true))
}
Example #9
0
// New initialize a publish instance
func New(db *gorm.DB) *Publish {
	tableHandler := gorm.DefaultTableNameHandler
	gorm.DefaultTableNameHandler = func(db *gorm.DB, defaultTableName string) string {
		tableName := tableHandler(db, defaultTableName)

		if db != nil {
			if IsPublishableModel(db.Value) {
				// Set join table handler
				typ := utils.ModelType(db.Value)
				if !injectedJoinTableHandler[typ] {
					injectedJoinTableHandler[typ] = true
					scope := db.NewScope(db.Value)
					for _, field := range scope.GetModelStruct().StructFields {
						if many2many := utils.ParseTagOption(field.Tag.Get("gorm"))["MANY2MANY"]; many2many != "" {
							db.SetJoinTableHandler(db.Value, field.Name, &publishJoinTableHandler{})
							db.AutoMigrate(db.Value)
						}
					}
				}

				var forceDraftTable bool
				if forceDraft, ok := db.Get("publish:force_draft_table"); ok {
					if forceMode, ok := forceDraft.(bool); ok && forceMode {
						forceDraftTable = true
					}
				}

				if IsDraftMode(db) || forceDraftTable {
					return DraftTableName(tableName)
				}
			}
		}
		return tableName
	}

	db.AutoMigrate(&PublishEvent{})

	db.Callback().Create().Before("gorm:begin_transaction").Register("publish:set_table_to_draft", setTableAndPublishStatus(true))
	db.Callback().Create().Before("gorm:commit_or_rollback_transaction").
		Register("publish:sync_to_production_after_create", syncCreateFromProductionToDraft)
	db.Callback().Create().Before("gorm:commit_or_rollback_transaction").Register("gorm:create_publish_event", createPublishEvent)

	db.Callback().Delete().Before("gorm:begin_transaction").Register("publish:set_table_to_draft", setTableAndPublishStatus(true))
	deleteCallback := db.Callback().Delete().Get("gorm:delete")
	db.Callback().Delete().Replace("gorm:delete", deleteScope)
	db.Callback().Delete().Before("gorm:commit_or_rollback_transaction").
		Register("publish:sync_to_production_after_delete", syncDeleteFromProductionToDraft)
	db.Callback().Delete().Before("gorm:commit_or_rollback_transaction").Register("gorm:create_publish_event", createPublishEvent)

	db.Callback().Update().Before("gorm:begin_transaction").Register("publish:set_table_to_draft", setTableAndPublishStatus(true))
	db.Callback().Update().Before("gorm:commit_or_rollback_transaction").
		Register("publish:sync_to_production", syncUpdateFromProductionToDraft)
	db.Callback().Update().Before("gorm:commit_or_rollback_transaction").Register("gorm:create_publish_event", createPublishEvent)

	db.Callback().RowQuery().Register("publish:set_table_in_draft_mode", setTableAndPublishStatus(false))
	db.Callback().Query().Before("gorm:query").Register("publish:set_table_in_draft_mode", setTableAndPublishStatus(false))

	searchHandler := func(db *gorm.DB, context *qor.Context) *gorm.DB {
		return db.Unscoped()
	}
	return &Publish{SearchHandler: searchHandler, DB: db, deleteCallback: deleteCallback, logger: Logger}
}