From 4b3b94c8bffb15d137806b5b10aa141f3056aece Mon Sep 17 00:00:00 2001 From: faab Date: Sat, 2 Nov 2024 20:04:03 +0000 Subject: [PATCH] Add insert_data.sh --- insert_data.sh | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 insert_data.sh diff --git a/insert_data.sh b/insert_data.sh new file mode 100644 index 0000000..4a2c7da --- /dev/null +++ b/insert_data.sh @@ -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