Skip to content

Instantly share code, notes, and snippets.

@isopropylcyanide
Last active October 17, 2021 17:10
Show Gist options
  • Save isopropylcyanide/421d0e89aec91e16647646d1c7e59532 to your computer and use it in GitHub Desktop.
Save isopropylcyanide/421d0e89aec91e16647646d1c7e59532 to your computer and use it in GitHub Desktop.
Demo app that writes few entries to mysql using a protected status set per business logic
package main
import (
"database/sql"
"time"
"github.com/segmentio/ksuid"
"github.com/tjarratt/babble"
"go.uber.org/zap"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
var dsn = "root:pass@tcp(127.0.0.1:3306)/sample?charset=utf8mb4&parseTime=True&loc=Local"
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}
}
return
}
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