Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Demo app that writes few entries to mysql using a protected status set per business logic
package main
import (
var dsn = "root:pass@tcp("
var babbler = babble.NewBabbler()
type Banner struct {
BannerId string `gorm:"primaryKey"`
ContentID string `gorm:"uniqueIndex:unique_live_banner_idx,priority=1,length:20"`
BannerStatus string `gorm:"uniqueIndex:unique_live_banner_idx,priority=2,length:20"`
IngestionStatus string `gorm:"uniqueIndex:unique_live_banner_idx,priority=3,length:20"`
ProtectedStatus sql.NullBool `gorm:"uniqueIndex:unique_live_banner_idx,priority=4"`
Name string
CreatedAt time.Time
UpdatedAt time.Time
func NewBanner(contentId, bannerStatus, ingestionStatus string) *Banner {
return &Banner{
BannerId: ksuid.New().String(),
ContentID: contentId,
BannerStatus: bannerStatus,
IngestionStatus: ingestionStatus,
ProtectedStatus: sql.NullBool{},
Name: babbler.Babble(),
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
func (b *Banner) BeforeCreate(*gorm.DB) (err error) {
if b.BannerStatus == b.IngestionStatus && b.BannerStatus == "LIVE" {
b.ProtectedStatus = sql.NullBool{Bool: true, Valid: true}
func main() {
db := setup()
defer cleanup(db)
// Create business queries
db.Create(NewBanner("C1", "LIVE", "LIVE"))
db.Create(NewBanner("C1", "LIVE", "DRAFT")) // Okay [Business]
db.Create(NewBanner("C2", "DRAFT", "DRAFT"))
db.Create(NewBanner("C2", "DRAFT", "DRAFT")) // Okay [Business]
db.Create(NewBanner("C1", "LIVE", "LIVE")) // Not Okay :| [Business]
func setup() *gorm.DB {
var db *gorm.DB
var err error
logger, _ := zap.NewDevelopment()
if db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{}); err != nil {
logger.Error("Couldn't connect to the database %v", zap.Error(err))
logger.Info("Database is up ", zap.String("name", db.Name()))
// Delete rows for a fresh start and auto-populate schema
_ = db.Migrator().DropTable(Banner{})
_ = db.AutoMigrate(Banner{})
return db
func cleanup(db *gorm.DB) {
sqlDB, _ := db.DB()
_ = sqlDB.Close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment