Add insert_data.sh

This commit is contained in:
2024-11-02 20:04:03 +00:00
parent 2d601ccf8d
commit 4b3b94c8bf

46
insert_data.sh Normal file
View File

@@ -0,0 +1,46 @@
#! /bin/bash
if [[ $1 == "test" ]]
then
PSQL="psql --username=postgres --dbname=worldcuptest -t --no-align -c"
else
PSQL="psql --username=freecodecamp --dbname=worldcup -t --no-align -c"
fi
# Do not change code above this line. Use the PSQL variable above to query your database.
echo $($PSQL "TRUNCATE teams,games")
cat games.csv | while IFS="," read year round winner opponent winner_goals opponent_goals; do
if [[ $year == "year" ]]; then
continue
fi
# Check if winner exists
WINNER_CHECK=$($PSQL "SELECT team_id FROM teams WHERE name = '$winner'")
if [[ -z $WINNER_CHECK ]]; then
INSERT_WINNER_RESULT=$($PSQL "INSERT INTO teams(name) VALUES('$winner')")
if [[ $INSERT_WINNER_RESULT == "INSERT 0 1" ]]; then
echo "Inserted $winner into teams"
fi
fi
# Check if opponent exists
OPPONENT_CHECK=$($PSQL "SELECT team_id FROM teams WHERE name = '$opponent'")
if [[ -z $OPPONENT_CHECK ]]; then
INSERT_OPPONENT_RESULT=$($PSQL "INSERT INTO teams(name) VALUES('$opponent')")
if [[ $INSERT_OPPONENT_RESULT == "INSERT 0 1" ]]; then
echo "Inserted $opponent into teams"
fi
fi
WINNER_ID=$($PSQL "SELECT team_id FROM teams WHERE name = '$winner'")
OPPONENT_ID=$($PSQL "SELECT team_id FROM teams WHERE name = '$opponent'")
INSERT_GAME_RESULT=$($PSQL "INSERT INTO games(winner_id, opponent_id, winner_goals, opponent_goals, year, round) VALUES ($WINNER_ID, $OPPONENT_ID, $winner_goals, $opponent_goals, $year, '$round')")
if [[ $INSERT_GAME_RESULT == "INSERT 0 1" ]]; then
echo "Inserted $year $round: $winner $winner_goals - $opponent_goals $opponent into games"
else
echo $INSERT_GAME_RESULT
fi