From e15e4b93c203ba94f413e97955c48d8761a70423 Mon Sep 17 00:00:00 2001 From: Unto Markkanen Date: Sun, 3 Dec 2023 12:13:04 +0200 Subject: Moving user related database commands to separate class and file. --- db/db.py | 27 +++------------------------ db/user.py | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 24 deletions(-) create mode 100644 db/user.py (limited to 'db') diff --git a/db/db.py b/db/db.py index ad6f3ac..8261cf5 100644 --- a/db/db.py +++ b/db/db.py @@ -6,35 +6,14 @@ from sqlalchemy.sql import text from app import app +from db.user import DBUser + class DB: def __init__(self): self.db = SQLAlchemy() self.db.init_app(app) + self.user = DBUser(self.db) - def user_new(self, nick): - sql = "INSERT \ - INTO users (nick, created) \ - VALUES (:nick, :created) \ - RETURNING id ;" - result = self.db.session.execute( - text(sql), { "nick":nick, "created":int(time()) } - ) - self.db.session.commit() - return result.fetchone()[0] - - def user_get_nick(self, id): - sql = "SELECT nick \ - FROM users \ - WHERE id=(:id);" - result = self.db.session.execute(text(sql), { "id":id }).fetchone() - return result[0] if result else result - - def user_exists(self, nick): - sql = "SELECT COUNT(id) \ - FROM users \ - WHERE nick=(:nick);" - return self.db.session.execute(text(sql), { "nick":nick }).scalar() - def question_new(self, question, neg_ans, pos_ans ): sql = "INSERT \ INTO questions (question, neg_answer, pos_answer, created) \ diff --git a/db/user.py b/db/user.py new file mode 100644 index 0000000..a129a13 --- /dev/null +++ b/db/user.py @@ -0,0 +1,32 @@ +from time import time + +from sqlalchemy.sql import text + +class DBUser: + def __init__(self, db): + self.db = db + + def get_nick(self, id): + sql = "SELECT nick \ + FROM users \ + WHERE id=(:id);" + result = self.db.session.execute(text(sql), { "id":id }).fetchone() + return result[0] if result else result + + def new(self, nick): + sql = "INSERT \ + INTO users (nick, created) \ + VALUES (:nick, :created) \ + RETURNING id ;" + result = self.db.session.execute( + text(sql), { "nick":nick, "created":int(time()) } + ) + self.db.session.commit() + return result.fetchone()[0] + + def exists(self, nick): + sql = "SELECT COUNT(id) \ + FROM users \ + WHERE nick=(:nick);" + return self.db.session.execute(text(sql), { "nick":nick }).scalar() + -- cgit v1.2.3