Skip to content

Commit 0b0b6ff

Browse files
committed
added quries.sql file with all the commands and queries
1 parent 760fb4c commit 0b0b6ff

18 files changed

+850
-23
lines changed

.gitignore

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,5 +7,8 @@ __pycache__/
77

88
# Ignore the credentials (for obvious reasons)
99
credentials.env
10+
backup.env
11+
backup.log
12+
backup.bat
1013
videogames_register/migrations/__pycache__/
1114
Videogames_project/__pycache__/

scripts/backup.py

Lines changed: 28 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,47 @@
1+
#!/usr/bin/env python3
12
import os
23
import subprocess
34
from datetime import datetime
4-
5-
5+
from pathlib import Path
66
from dotenv import load_dotenv
7-
load_dotenv("../credentials.env")
7+
8+
project_root = Path(__file__).resolve().parent.parent
9+
env_path = project_root / "backup.env"
10+
if not env_path.is_file():
11+
raise FileNotFoundError(f"Could not find {env_path}")
12+
load_dotenv(dotenv_path=env_path)
813

914
db_name = os.getenv("DB_NAME")
1015
db_user = os.getenv("DB_USER")
16+
db_password = os.getenv("DB_PASSWORD")
1117
db_host = os.getenv("DB_HOST", "localhost")
12-
backup_dir = "../backups"
13-
os.makedirs(backup_dir, exist_ok=True)
18+
db_port = os.getenv("DB_PORT", "")
1419

15-
filename = f"{backup_dir}/videogames_backup_{datetime.now():%Y%m%d_%H%M%S}.sql"
20+
missing = [k for k,v in (("DB_NAME", db_name), ("DB_USER", db_user), ("DB_PASSWORD", db_password)) if not v]
21+
if missing:
22+
raise EnvironmentError(f"Missing environment variables in backup.env: {', '.join(missing)}")
23+
24+
backup_dir = project_root / "backups"
25+
backup_dir.mkdir(parents=True, exist_ok=True)
26+
27+
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
28+
filename = backup_dir / f"videogames_backup_{timestamp}.sql"
1629

1730
command = [
1831
"pg_dump",
1932
"-U", db_user,
2033
"-h", db_host,
2134
"-d", db_name,
22-
"-f", filename
35+
"-f", str(filename),
36+
"--no-owner",
37+
"--verbose"
2338
]
24-
39+
if db_port:
40+
command.extend(["-p", db_port])
2541

2642
env = os.environ.copy()
27-
env["PGPASSWORD"] = os.getenv("DB_PASSWORD")
43+
env["PGPASSWORD"] = db_password
2844

29-
print(f"🔁 Running backup to: {filename}")
30-
subprocess.run(command, env=env, check=True)
31-
print("✅ Backup complete!")
45+
result = subprocess.run(command, env=env)
46+
if result.returncode != 0:
47+
exit(result.returncode)

scripts/restore.py

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
#!/usr/bin/env python3
2+
import os
3+
import subprocess
4+
import glob
5+
from pathlib import Path
6+
from dotenv import load_dotenv
7+
from datetime import datetime
8+
9+
project_root = Path(__file__).resolve().parent.parent
10+
env_path = project_root / "backup.env"
11+
if not env_path.is_file():
12+
raise FileNotFoundError(f"Could not find {env_path}")
13+
load_dotenv(dotenv_path=env_path)
14+
15+
db_name = os.getenv("DB_NAME")
16+
db_user = os.getenv("DB_USER")
17+
db_pass = os.getenv("DB_PASSWORD")
18+
db_host = os.getenv("DB_HOST", "localhost")
19+
db_port = os.getenv("DB_PORT", "")
20+
21+
missing = [k for k,v in (("DB_NAME",db_name),("DB_USER",db_user),("DB_PASSWORD",db_pass)) if not v]
22+
if missing:
23+
raise EnvironmentError(f"Missing {', '.join(missing)} in backup.env")
24+
25+
backups_dir = project_root / "backups"
26+
sql_files = sorted(backups_dir.glob("videogames_backup_*.sql"))
27+
if not sql_files:
28+
raise FileNotFoundError("No backups found in backups/")
29+
30+
latest = sql_files[-1]
31+
test_db = f"{db_name}_restore_test"
32+
33+
env = os.environ.copy()
34+
env["PGPASSWORD"] = db_pass
35+
36+
37+
cmd = ["createdb", "-U", db_user, "-h", db_host]
38+
if db_port:
39+
cmd += ["-p", db_port]
40+
cmd.append(test_db)
41+
subprocess.run(cmd, env=env, check=True)
42+
43+
44+
cmd = ["psql", "-U", db_user, "-h", db_host, "-d", test_db, "-f", str(latest)]
45+
if db_port:
46+
cmd += ["-p", db_port]
47+
subprocess.run(cmd, env=env, check=True)
48+
49+
50+
canary = [
51+
"psql", "-U", db_user, "-h", db_host, "-d", test_db,
52+
"-t", "-c",
53+
"SELECT COUNT(*) FROM public.videogames_register_videogame;"
54+
]
55+
if db_port:
56+
canary += ["-p", db_port]
57+
result = subprocess.run(canary, env=env, check=True, stdout=subprocess.PIPE, text=True)
58+
count = result.stdout.strip()
59+
print(f" check: {count} rows in videogames_register_videogame")
60+
61+
62+
# cmd = ["dropdb", "-U", db_user, "-h", db_host]
63+
# if db_port:
64+
# cmd += ["-p", db_port]
65+
# cmd.append(test_db)
66+
# subprocess.run(cmd, env=env, check=True)
67+
# print("Restore test succeeded and test database dropped.")

scripts/seed_data.py

Lines changed: 134 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,134 @@
1+
import os
2+
import django
3+
import random
4+
import sys
5+
from faker import Faker
6+
7+
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
8+
9+
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Videogames_project.settings')
10+
django.setup()
11+
12+
from videogames_register.models import VideoGame, Genre, Developer, UserProfile, Review, Copy
13+
from django.contrib.auth.models import User
14+
15+
fake = Faker()
16+
17+
def seed():
18+
19+
Copy.objects.all().delete()
20+
Review.objects.all().delete()
21+
VideoGame.objects.all().delete()
22+
Developer.objects.all().delete()
23+
UserProfile.objects.all().delete()
24+
User.objects.exclude(is_superuser=True).delete()
25+
Genre.objects.all().delete()
26+
27+
GENRE_NAMES = ['Action', 'Adventure', 'RPG', 'Shooter', 'Puzzle', 'Strategy', 'Sports']
28+
for name in GENRE_NAMES:
29+
Genre.objects.get_or_create(title=name)
30+
31+
GAME_TITLES = [
32+
"Shadowblade", "Galactic Titans", "Mystic Quest", "Steel Reign",
33+
"Cyber Drift", "Knightfall Chronicles", "Inferno Squad", "Frostbound",
34+
"Echoes of Oblivion", "Nova Arena", "Crystal Rift", "Phantom Protocol",
35+
"Neon Shards", "Eternal Siege", "Dark Horizon", "Turbo Strikers",
36+
"Skyfall Bastion", "Quantum Rift", "Blood Circuit", "Ashen Crown"
37+
]
38+
39+
GAME_DESCRIPTIONS = [
40+
"A fast-paced action game set in a dystopian future.",
41+
"Explore ancient ruins and uncover hidden secrets.",
42+
"Command your troops in a real-time strategy battlefield.",
43+
"Join the rebellion against the galactic empire.",
44+
"A fantasy RPG with immersive storytelling and rich lore.",
45+
"Drive high-tech vehicles in a neon cyberpunk city.",
46+
"Survive endless waves of enemies in post-apocalyptic arenas.",
47+
"Build and manage your own medieval kingdom.",
48+
"Compete in futuristic sports tournaments with deadly consequences.",
49+
"Navigate political intrigue and betrayal in a space federation.",
50+
"Hack into networks while avoiding elite AI defenders.",
51+
"Fly elite starfighters in tactical interstellar battles.",
52+
"Uncover the mystery behind vanishing cities.",
53+
"Combine magic and technology to restore a broken world.",
54+
"Control mythical creatures in turn-based combat.",
55+
"Battle rogue AIs in a derelict digital wasteland.",
56+
"Rescue colonies lost to alien infestations.",
57+
"Rebuild civilization after a massive solar storm.",
58+
"Explore underwater cities and defend against sea monsters.",
59+
"Join secret guilds and shape the fate of nations."
60+
]
61+
62+
for _ in range(5):
63+
Developer.objects.create(
64+
name=fake.company(),
65+
founded_year=random.randint(2000, 2025)
66+
)
67+
68+
all_genres = list(Genre.objects.all())
69+
all_devs = list(Developer.objects.all())
70+
# Create only curated games
71+
games = []
72+
for i in range(len(GAME_TITLES)):
73+
game = VideoGame.objects.create(
74+
title=GAME_TITLES[i],
75+
description=GAME_DESCRIPTIONS[i],
76+
release_date=fake.date_between(start_date='-10y', end_date='today'),
77+
genre=random.choice(all_genres),
78+
)
79+
games.append(game)
80+
81+
82+
for _ in range(5):
83+
user = User.objects.create_user(
84+
username=fake.user_name(),
85+
email=fake.email(),
86+
password="testpass123"
87+
)
88+
UserProfile.objects.create(
89+
user=user,
90+
country=fake.country(),
91+
age=random.randint(18, 50)
92+
)
93+
users = list(User.objects.all())
94+
95+
96+
97+
for i in range(len(GAME_TITLES)):
98+
VideoGame.objects.create(
99+
title=GAME_TITLES[i],
100+
description=GAME_DESCRIPTIONS[i],
101+
release_date=fake.date_between(start_date='-10y', end_date='today'),
102+
genre=random.choice(all_genres),
103+
104+
)
105+
106+
for game in games:
107+
for _ in range(random.randint(1, 3)):
108+
Copy.objects.create(
109+
game=game,
110+
serial_number=fake.uuid4(),
111+
condition=random.choice(['New', 'Used', 'Mint'])
112+
)
113+
114+
for _ in range(30):
115+
Review.objects.create(
116+
user=random.choice(users),
117+
game=random.choice(games),
118+
rating=random.randint(1, 10),
119+
comment=fake.sentence()
120+
)
121+
122+
123+
for game in games:
124+
for _ in range(random.randint(1, 3)):
125+
Copy.objects.create(
126+
game=game,
127+
serial_number=fake.uuid4(),
128+
condition=random.choice(['New', 'Used', 'Mint'])
129+
)
130+
131+
print("Done seeding data.")
132+
133+
if __name__ == "__main__":
134+
seed()

0 commit comments

Comments
 (0)