Skip to content

Commit c2f2dfb

Browse files
Add insert data bash
1 parent 391fdbf commit c2f2dfb

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed

insert_data..sh

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
#! /bin/bash
2+
3+
if [[ $1 == "test" ]]
4+
then
5+
PSQL="psql --username=postgres --dbname=worldcuptest -t --no-align -c"
6+
else
7+
PSQL="psql --username=freecodecamp --dbname=worldcup -t --no-align -c"
8+
fi
9+
10+
# Do not change code above this line. Use the PSQL variable above to query your database.
11+
12+
cat games.csv | while IFS="," read YEAR ROUND WINNER OPPONENT WINNER_GOALS OPPONENT_GOALS
13+
do
14+
if [[ $WINNER != "winner" && $OPPONENT != "opponent" ]]
15+
then
16+
#get teams_id
17+
18+
WINNER_ID=$($PSQL "SELECT team_id FROM teams WHERE name='$WINNER'")
19+
OPPONENT_ID=$($PSQL "SELECT team_id FROM teams WHERE name='$OPPONENT'")
20+
21+
# if not found winner
22+
if [[ -z $WINNER_ID ]]
23+
then
24+
# insert winner
25+
INSERT_WINNER_RESULT=$($PSQL "INSERT INTO teams(name) VALUES('$WINNER')")
26+
# it was succesfull
27+
if [[ INSERT_WINNER_RESULT == "INSERT 0 1" ]]
28+
then
29+
echo "Inserted into teams, $WINNER"
30+
fi
31+
32+
#get new WINNER_ID
33+
WINNER_ID=$($PSQL "SELECT team_id FROM teams WHERE name='$WINNER'")
34+
fi
35+
36+
# if not found opponent
37+
if [[ -z $OPPONENT_ID ]]
38+
then
39+
# insert opponent
40+
INSERT_OPPONENT_RESULT=$($PSQL "INSERT INTO teams(name) VALUES('$OPPONENT')")
41+
# it was succesfull
42+
if [[ INSERT_OPPONENT_RESULT == "INSERT 0 1" ]]
43+
then
44+
echo "Inserted into teams, $OPPONENT"
45+
fi
46+
47+
#get new OPPONENT_ID
48+
OPPONENT_ID=$($PSQL "SELECT team_id FROM teams WHERE name='$OPPONENT'")
49+
fi
50+
51+
# insert data into games
52+
53+
INSERT_GAMES_RESULT=$($PSQL "INSERT INTO games(year, round, winner_id, opponent_id, winner_goals, opponent_goals) VALUES('$YEAR', '$ROUND', '$WINNER_ID', '$OPPONENT_ID', '$WINNER_GOALS', '$OPPONENT_GOALS')")
54+
if [[ $INSERT_GAMES_RESULT == "Insert 0 1" ]]
55+
then
56+
echo "Game inserted: '$WINNER' vs '$OPPONENT'"
57+
fi
58+
59+
fi
60+
done

0 commit comments

Comments
 (0)