Example #1
0
func fetchCardIDs(ctx context.Context, db *cql.DB) ([]string, error) {
	ids := []string{}

	rows, err := db.QueryC(ctx, "SELECT id FROM cards")
	if err != nil {
		return ids, err
	}

	defer rows.Close()
	for rows.Next() {
		var id string
		if err := rows.Scan(&id); err != nil {
			return ids, err
		}
		ids = append(ids, id)
	}
	return ids, rows.Err()
}
Example #2
0
func CreateCollection(db *cql.DB, r brew.Reader, collection MTGCollection) error {
	ctx := context.TODO()
	sets, cards := TransformCollection(collection)

	// Load the current cards and sets
	currentSets, err := r.GetSets(ctx)
	if err != nil {
		return err
	}

	currentCards, err := fetchCardIDs(ctx, db)
	if err != nil {
		return err
	}

	tx, err := db.Begin()
	if err != nil {
		return err
	}
	for _, s := range sets {
		if existingSet(currentSets, s.Id) {
			continue
		}
		_, err := tx.Exec(queryInsertSet, s.Id, s.Name, s.Border, s.Type)
		if err != nil {
			tx.Rollback()
			return fmt.Errorf("error intserting set %+v %s", s, err)
		}
	}

	i := 0
	for _, c := range cards {
		blob, err := json.Marshal(c)
		if err != nil {
			tx.Rollback()
			return err
		}
		if existingCard(currentCards, c.Id) {
			_, err = tx.Exec(queryUpdateCard,
				c.Name, blob, c.Text, c.ManaCost, c.ConvertedCost,
				c.Power, c.Toughness, c.Loyalty, c.Multicolor(),
				sarray(c.Rarities()), sarray(c.Types),
				sarray(c.Subtypes), sarray(c.Supertypes),
				sarray(c.Colors), sarray(c.Sets()),
				sarray(c.Formats()), sarray(c.Status()),
				sarray(c.MultiverseIds()), c.Id)
		} else {
			_, err = tx.Exec(queryInsertCard,
				c.Id, c.Name, blob, c.Text, c.ManaCost, c.ConvertedCost,
				c.Power, c.Toughness, c.Loyalty, c.Multicolor(),
				sarray(c.Rarities()), sarray(c.Types),
				sarray(c.Subtypes), sarray(c.Supertypes),
				sarray(c.Colors), sarray(c.Sets()),
				sarray(c.Formats()), sarray(c.Status()),
				sarray(c.MultiverseIds()))
		}
		if err != nil {
			tx.Rollback()
			return fmt.Errorf("error inserting / updating card %+v %s", c, err)
		}
		i += 1
	}
	return tx.Commit()
}