Using transactions to create records

Report a typo

Dave is working with the music SQLite database, below you can see the database diagram:

music database diagram

Dave is a big fan of the rock band Nirvana and wants to insert records of Nirvana into the music database using transactions.

Your task is to help Dave fill in the blanks in the code to:

  1. Start a transaction

  2. Create the artist with name "Nirvana" within the transaction.

  3. Handle potential errors by rolling back

  4. Set up GORM's association mode to insert 3 records into the songs and artist_songs join table within the transaction.

  5. Save the changes to the database if all operations are successful.

Fill in the gaps with the relevant elements
package main

import (
	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
	"log"
	"time"
)

type Artist struct { // Model for the `artists` table
	gorm.Model
	Name  string
	Songs []Song `gorm:"many2many:artist_songs"`
}

type Song struct { // Model for the `songs` table
	gorm.Model
	Title    string
	Duration time.Duration
	Artists  []Artist `gorm:"many2many:artist_songs"`
}

const DBName = "music.db"

func main() {
    db, err := gorm.Open(sqlite.Open(DBName), &gorm.Config{})
	if err != nil {
		log.Fatalf("cannot open %s: %v\n", DBName, err)
	}

	 := 

	artist := Artist{Name: "Nirvana"}
	result := 
	if result.Error != nil {
		log.Printf("cannot create Artist: %v\n", result.Error)
		
		return
	}

    songs := []Song{
        {Title: "Smells Like Teen Spirit", Duration: 5*time.Minute + 1*time.Second},
        {Title: "Come As You Are", Duration: 3*time.Minute + 38*time.Second},
        {Title: "Heart-Shaped Box", Duration: 4*time.Minute + 41*time.Second},
    }


	err = 
	if err != nil {
		log.Printf("cannot create Songs and/or artist_songs records (or both): %v\n", err)
        tx.Rollback()
        
	}

	
}
db.Model(&artist).Association("Songs").Append(&songs)tx.Create(&artist)db.Begin()db.Start()returntx.Save()txtx.Model(&artist).Association("Songs").Append(&songs)db.Create(&artist)tx.Rollback()tx.Commit()
___

Create a free account to access the full topic