Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Demo app that writes few entries to mysql without a protected status
package main
import (
"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"`
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,
Name: babbler.Babble(),
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
}
}
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