Skip to content

Commit 034c232

Browse files
committed
Refactor database configuration and initialization
- Update .env_example to include DATABASE_URL - Modify config/boot.py to create database tables using SQLAlchemy - Add database/db.py to define SQLAlchemy models and session management
1 parent 095b963 commit 034c232

File tree

3 files changed

+75
-2
lines changed

3 files changed

+75
-2
lines changed

.env_example

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,4 +11,5 @@ DB_HOST= # Database Host, for local use '127.0.0.1'
1111
DB_PORT= # Database Port
1212
DB_DATABASE= # Database Name
1313
DB_USERNAME= # Database Username
14-
DB_PASSWORD= # Database Password
14+
DB_PASSWORD= # Database Password
15+
DATABASE_URL= # Database URL, for local use 'sqlite:///database.db'

config/boot.py

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,9 +33,15 @@
3333
import glob
3434
from disnake.ext import commands
3535
import glob
36+
from database.db import engine, Base
37+
3638
# Add the project root to the Python path
3739
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
3840

41+
# Create the database tables
42+
Base.metadata.create_all(bind=engine)
43+
44+
# Check if the Flask app and Discord bot are enabled
3945
flask_enabled = os.environ.get('FLASK_HOST') # Check if the FLASK_HOST environment variable is set
4046
discord_enabled = os.environ.get('DISCORD_TOKEN') # Check if the DISCORD_BOT_TOKEN environment variable is set
4147

@@ -56,12 +62,14 @@ def run_flask():
5662
print("Discord bot enabled")
5763
intents = discord.Intents.all() # Define the bot's intents
5864
bot = commands.Bot(command_prefix=os.environ.get('DISCORD_PREFIX','!'), intents=intents,)
59-
65+
66+
# Define the bot's event listeners
6067
@bot.event
6168
async def on_ready():
6269
print(f'Logged in as {bot.user}') # Print the bot's username when it's ready
6370

6471
def load_cogs(bot):
72+
# Load all cogs in the 'app/Commands/Context' and 'app/Commands/Slash' directories
6573
cog_directories = ['app/Commands/Context', 'app/Commands/Slash']
6674
for directory in cog_directories:
6775
for filename in glob.glob(f'{directory}/*.py'):
@@ -74,6 +82,7 @@ def load_cogs(bot):
7482
print(f'Failed to load cog {cog}: {e}') # Print the name of the cog that failed to load
7583

7684
def run_discord_bot():
85+
# Start the Discord bot
7786
try:
7887
print("Starting Discord bot...")
7988
load_cogs(bot)

database/db.py

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
import os
2+
from sqlalchemy import create_engine, Column, Integer
3+
from sqlalchemy.ext.declarative import declarative_base
4+
from sqlalchemy.orm import sessionmaker, scoped_session
5+
6+
DATABASE_URL = os.environ.get("DATABASE_URL")
7+
8+
engine = create_engine(DATABASE_URL)
9+
SessionLocal = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=engine))
10+
Base = declarative_base()
11+
12+
def get_db():
13+
db = SessionLocal()
14+
try:
15+
yield db
16+
finally:
17+
db.close()
18+
19+
class BaseModel(Base):
20+
__abstract__ = True
21+
22+
id = Column(Integer, primary_key=True, index=True)
23+
24+
@classmethod
25+
def create(cls, db_session, **kwargs):
26+
instance = cls(**kwargs)
27+
db_session.add(instance)
28+
db_session.commit()
29+
db_session.refresh(instance)
30+
return instance
31+
32+
@classmethod
33+
def get(cls, db_session, id):
34+
return db_session.query(cls).filter(cls.id == id).first()
35+
36+
@classmethod
37+
def all(cls, db_session):
38+
return db_session.query(cls).all()
39+
40+
@classmethod
41+
def update(cls, db_session, id, **kwargs):
42+
instance = db_session.query(cls).filter(cls.id == id).first()
43+
if instance:
44+
for key, value in kwargs.items():
45+
setattr(instance, key, value)
46+
db_session.commit()
47+
db_session.refresh(instance)
48+
return instance
49+
50+
@classmethod
51+
def delete(cls, db_session, id):
52+
instance = db_session.query(cls).filter(cls.id == id).first()
53+
if instance:
54+
db_session.delete(instance)
55+
db_session.commit()
56+
return instance
57+
58+
@classmethod
59+
def filter(cls, db_session, **kwargs):
60+
query = db_session.query(cls)
61+
for key, value in kwargs.items():
62+
query = query.filter(getattr(cls, key) == value)
63+
return query.all()

0 commit comments

Comments
 (0)