ADD sqlalchemy and refact database module.

pull/3/head
kevincaires 3 years ago
parent 9cd0477fe6
commit cbdb0d73cb

@ -0,0 +1,16 @@
from settings.config import SQLACHEMY
from sqlalchemy import Table
from sqlalchemy.orm import declarative_base
Base = declarative_base()
class Quotes(Base):
"""
Quotes model class.
"""
__table__ = Table(
"neeble_quotes",
Base.metadata,
autoload=True,
autoload_with=SQLACHEMY
)

@ -4,6 +4,8 @@ BOT configuration.
import logging.config as logger import logging.config as logger
import os import os
from sqlalchemy import create_engine
# Discord token. # Discord token.
DISCORD_BOT_TOKEN = os.environ.get('DISCORD_BOT_TOKEN') DISCORD_BOT_TOKEN = os.environ.get('DISCORD_BOT_TOKEN')
@ -16,6 +18,16 @@ MYSQL_CONFIG = {
'password': os.environ.get('MYSQL_PASSWORD', 'neeble'), 'password': os.environ.get('MYSQL_PASSWORD', 'neeble'),
} }
SQLACHEMY = create_engine(
'mysql://%s:%s@%s:%s/%s' % (
os.environ.get('MYSQL_USER', 'neeble'),
os.environ.get('MYSQL_PASSWORD', 'neeble'),
os.environ.get('MYSQL_HOST', 'localhost'),
int(os.environ.get('MYSQL_PORT', '3306')),
os.environ.get('MYSQL_DATABASE', 'neeble'),
)
)
# Define the log level # Define the log level
LOGLEVEL = os.environ.get('LOGLEVEL', 'info').upper() LOGLEVEL = os.environ.get('LOGLEVEL', 'info').upper()

@ -140,11 +140,9 @@ async def quote_count(bot: object) -> str:
""" """
Outputs a quote count from the database Outputs a quote count from the database
""" """
# For len(amount) to work, first it needs to be converted into str # For len(amount) to work, first it needs to be converted into str
amount = count_quotes() amount = count_quotes()
amount = str(amount) amount = str(amount)
amount = amount[1:len(amount)][:-2]
msg = "Quote count: `" + amount + "`" msg = "Quote count: `" + amount + "`"

@ -2,10 +2,12 @@
Database utils module. Database utils module.
""" """
import logging import logging
from collections import namedtuple
import MySQLdb import MySQLdb
from settings.config import MYSQL_CONFIG from models.quotes import Quotes
from settings.config import MYSQL_CONFIG, SQLACHEMY
from sqlalchemy import select
from sqlalchemy.orm import Session
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@ -61,79 +63,51 @@ def set_quote(user: str, quote: str) -> None:
""" """
Set a quote into database. Set a quote into database.
""" """
_sql = f''' with Session(SQLACHEMY) as session:
insert into neeble_quotes(user, quote) session.add(Quotes(
value("{user}", "{quote}"); quote=quote,
''' user=user,
with Cursor(MYSQL_CONFIG) as cursor: ))
cursor.execute(_sql) session.commit()
def get_quotes(ids: list) -> tuple: def get_quotes(ids: list) -> tuple:
""" """
Get the saved quotes. Get the saved quotes.
ids: List of quote ID's ids: List of quote ID's
""" """
_sql = f''' with Session(SQLACHEMY) as session:
select quote, user, id _sql = select(Quotes).where(Quotes.id.not_in(ids))
from neeble_quotes return [item for item in session.scalars(_sql)]
'''
_sql = _sql + f' where id not in ({",".join([str(id) for id in ids])});' if ids else _sql + ';'
response = []
obj = namedtuple('Quotes', ['quote', 'user', 'id'])
with Cursor(MYSQL_CONFIG) as cursor:
cursor.execute(_sql)
response = cursor.fetchall()
return tuple(obj(*r) for r in response)
def get_by_id(id: int) -> object: def get_by_id(id: int) -> object:
""" """
Get one quote by ID. Get one quote by ID.
""" """
obj = namedtuple('Quotes', ['quote', 'user', 'id']) with Session(SQLACHEMY) as session:
_sql = f''' result = [s for s in session.query(Quotes).filter(Quotes.id==id)]
select quote, user, id return result[0] if result else None
from neeble_quotes
where id={id};
'''
with Cursor(MYSQL_CONFIG) as cursor:
cursor.execute(_sql)
quote = cursor.fetchone()
if not quote:
return None
return obj(*quote)
def remove_quote(_id: int) -> bool: def remove_quote(_id: int) -> bool:
""" """
Delete one quote by database ID. Delete one quote by database ID.
""" """
_sql = f'''
delete from neeble_quotes
where id={_id};
'''
try: try:
with Cursor(MYSQL_CONFIG) as cursor: with Session(SQLACHEMY) as session:
cursor.execute(_sql) item = get_by_id(_id)
session.delete(item)
session.commit()
return True return True
except Exception: except Exception:
return False return False
def count_quotes() -> int: def count_quotes() -> int:
""" """
Counts the amount of quotes in the database Counts the amount of quotes in the database
""" """
_sql = f''' with Session(SQLACHEMY) as session:
select count(*) from neeble_quotes response = session.query(Quotes.id).count()
''' return response
with Cursor(MYSQL_CONFIG) as cursor:
cursor.execute(_sql)
count = cursor.fetchone()
return count

Loading…
Cancel
Save