TheMathemagicians/sevenkeys/database/operations/inserts.go

77 lines
1.8 KiB
Go
Raw Normal View History

2024-04-28 14:13:47 +00:00
package operations
import (
"database/sql"
"errors"
"log"
"sevenkeys/scryfall/types"
2024-05-19 14:01:18 +00:00
"time"
2024-04-28 14:13:47 +00:00
)
var ErrGamepieceExists error = errors.New("Gamepiece already exists in database")
func insertGamepiece(db *sql.DB, cardName string) (int, error) {
gamepieceInsertQuery := "INSERT INTO Gamepiece (Name) VALUES (?);"
gamepieceInsert, err := db.Prepare(gamepieceInsertQuery)
defer gamepieceInsert.Close()
if err != nil {
log.Fatal(err)
}
existingGamepiece, err := GetGamepieceByName(db, cardName)
if err != sql.ErrNoRows {
return existingGamepiece.Id, ErrGamepieceExists
}
result, err := gamepieceInsert.Exec(cardName)
if err != nil {
log.Fatal(err)
}
gamepieceId, err := result.LastInsertId()
if err != nil {
log.Fatal(err)
}
return int(gamepieceId), nil
}
func insertCardPrinting(db *sql.DB, gamepieceId int, setCode string, imageUrl string) {
cardPrintingInsertQuery := "INSERT INTO CardPrinting (GamepieceId, SetCode, ImageUrl) VALUES (?, ?, ?);"
cardPrintingInsert, err := db.Prepare(cardPrintingInsertQuery)
defer cardPrintingInsert.Close()
if err != nil {
log.Fatal(err)
}
_, err = cardPrintingInsert.Exec(gamepieceId, setCode, imageUrl)
if err != nil {
log.Fatal(err)
}
}
func InsertCards(db *sql.DB, cards []types.Card) {
for index := range cards {
card := cards[index]
gamepieceId, _ := insertGamepiece(db, card.Name)
insertCardPrinting(db, gamepieceId, card.Set, card.ImageUris["png"])
}
}
2024-05-19 14:01:18 +00:00
func InsertOrUpdateCacheTimestampByType(db *sql.DB, cacheType string, stamp time.Time) error {
query := `INSERT INTO CacheTimestamps (CacheType, Stamp) VALUES (?, ?) ON DUPLICATE KEY UPDATE Stamp = ?;`
insertOrUpdate, err := db.Prepare(query)
defer insertOrUpdate.Close()
if err != nil {
return err
}
_, err = insertOrUpdate.Exec(cacheType, stamp, stamp)
if err != nil {
return err
}
return nil
}