Refactor Database to its own folder
This commit is contained in:
@@ -0,0 +1,46 @@
|
||||
from contextlib import contextmanager
|
||||
import duckdb
|
||||
import bcrypt
|
||||
from rich import print
|
||||
|
||||
|
||||
from lib import settings
|
||||
from models.user import UserIn, UserOut
|
||||
|
||||
|
||||
@contextmanager
|
||||
def get_db():
|
||||
try:
|
||||
conn = duckdb.connect(database=settings.db_url)
|
||||
yield conn
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def db_run(sql):
|
||||
with get_db() as conn:
|
||||
conn.execute(sql)
|
||||
|
||||
|
||||
def init_db():
|
||||
if settings.db_url.exists():
|
||||
# TODO: Development feature. Remove this in production
|
||||
from os import unlink
|
||||
|
||||
unlink(settings.db_url)
|
||||
# return
|
||||
sql = ""
|
||||
with open("lib/database/database.sql") as f:
|
||||
sql = f.read()
|
||||
|
||||
db_run(sql)
|
||||
|
||||
# Initialize default user
|
||||
|
||||
hashed_password = bcrypt.hashpw("password".encode("utf-8"), bcrypt.gensalt())
|
||||
|
||||
sql = f"INSERT INTO users (username, password, is_admin) VALUES ('admin', '{hashed_password.decode('utf-8')}', true)"
|
||||
db_run(sql)
|
||||
|
||||
sql = f"INSERT INTO users (username, password, is_admin) VALUES ('test', '{hashed_password.decode('utf-8')}', false)"
|
||||
db_run(sql)
|
||||
Reference in New Issue
Block a user