Skip to content

Commit

Permalink
Refactor: Drop MongoDB (#48)
Browse files Browse the repository at this point in the history
* feat: replace mongodb with sqllite

* feat: update docker compose to drop mongo

* chore: drop logs

* chore: cleanup

* fix: unit tests

* fix: workflow

* fix: workflow run
  • Loading branch information
jaypyles authored Nov 22, 2024
1 parent 7d80ff5 commit 563ca22
Show file tree
Hide file tree
Showing 26 changed files with 295 additions and 201 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/docker-image.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ on:

jobs:
build:
if: ${{ github.event.workflow_run.conclusion == 'success' && github.ref == 'refs/heads/master' && github.event_name != 'pull_request' }}
if: ${{ github.event.workflow_run.conclusion == 'success' && github.event.workflow_run.head_branch == 'master' }}
runs-on: ubuntu-latest
steps:
- name: Checkout
Expand Down
3 changes: 3 additions & 0 deletions .github/workflows/unit-tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ jobs:
- name: Checkout
uses: actions/checkout@v4

- name: Set env
run: echo "ENV=test" >> $GITHUB_ENV

- name: Install pdm
run: pip install pdm

Expand Down
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -187,3 +187,4 @@ cython_debug/
postgres_data
.vscode
ollama
data
8 changes: 8 additions & 0 deletions api/backend/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
from api.backend.routers.job_router import job_router
from api.backend.routers.log_router import log_router
from api.backend.routers.stats_router import stats_router
from api.backend.database.startup import init_database

log_level = os.getenv("LOG_LEVEL")
LOG_LEVEL = get_log_level(log_level)
Expand Down Expand Up @@ -41,3 +42,10 @@
app.include_router(job_router)
app.include_router(log_router)
app.include_router(stats_router)


@app.on_event("startup")
async def startup_event():
if os.getenv("ENV") != "test":
init_database()
LOG.info("Starting up...")
8 changes: 5 additions & 3 deletions api/backend/auth/auth_router.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@

# LOCAL
from api.backend.schemas import User, Token, UserCreate
from api.backend.database import get_user_collection
from api.backend.auth.auth_utils import (
ACCESS_TOKEN_EXPIRE_MINUTES,
get_current_user,
Expand All @@ -16,6 +15,8 @@
create_access_token,
)

from api.backend.database.common import update

auth_router = APIRouter()


Expand Down Expand Up @@ -43,12 +44,13 @@ async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends(

@auth_router.post("/auth/signup", response_model=User)
async def create_user(user: UserCreate):
users_collection = get_user_collection()
hashed_password = get_password_hash(user.password)
user_dict = user.model_dump()
user_dict["hashed_password"] = hashed_password
del user_dict["password"]
_ = await users_collection.insert_one(user_dict)

query = "INSERT INTO users (email, hashed_password, full_name) VALUES (?, ?, ?)"
_ = update(query, (user_dict["email"], hashed_password, user_dict["full_name"]))
return user_dict


Expand Down
7 changes: 4 additions & 3 deletions api/backend/auth/auth_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@

# LOCAL
from api.backend.schemas import User, UserInDB, TokenData
from api.backend.database import get_user_collection

from api.backend.database.common import query

LOG = logging.getLogger(__name__)

Expand All @@ -40,8 +41,8 @@ def get_password_hash(password: str):


async def get_user(email: str):
user_collection = get_user_collection()
user = await user_collection.find_one({"email": email})
user_query = "SELECT * FROM users WHERE email = ?"
user = query(user_query, (email,))[0]

if not user:
return
Expand Down
1 change: 1 addition & 0 deletions api/backend/constants.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
DATABASE_PATH = "data/database.db"
23 changes: 0 additions & 23 deletions api/backend/database.py

This file was deleted.

3 changes: 3 additions & 0 deletions api/backend/database/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from .common import insert, QUERIES, update

__all__ = ["insert", "QUERIES", "update"]
92 changes: 92 additions & 0 deletions api/backend/database/common.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
import sqlite3
from typing import Any, Optional
from api.backend.constants import DATABASE_PATH
from api.backend.utils import format_json, format_sql_row_to_python
from api.backend.database.schema import INIT_QUERY
from api.backend.database.queries import JOB_INSERT_QUERY, DELETE_JOB_QUERY
import logging

LOG = logging.getLogger(__name__)


def connect():
connection = sqlite3.connect(DATABASE_PATH)
connection.set_trace_callback(print)
cursor = connection.cursor()
return cursor


def insert(query: str, values: tuple[Any, ...]):
connection = sqlite3.connect(DATABASE_PATH)
cursor = connection.cursor()
copy = list(values)
format_json(copy)

try:
_ = cursor.execute(query, copy)
connection.commit()
except sqlite3.Error as e:
LOG.error(f"An error occurred: {e}")
finally:
cursor.close()
connection.close()


def query(query: str, values: Optional[tuple[Any, ...]] = None):
connection = sqlite3.connect(DATABASE_PATH)
connection.row_factory = sqlite3.Row
cursor = connection.cursor()
rows = []
try:
if values:
_ = cursor.execute(query, values)
else:
_ = cursor.execute(query)

rows = cursor.fetchall()

finally:
cursor.close()
connection.close()

formatted_rows: list[dict[str, Any]] = []

for row in rows:
row = dict(row)
formatted_row = format_sql_row_to_python(row)
formatted_rows.append(formatted_row)

return formatted_rows


def update(query: str, values: Optional[tuple[Any, ...]] = None):
connection = sqlite3.connect(DATABASE_PATH)
cursor = connection.cursor()

copy = None

if values:
copy = list(values)
format_json(copy)

try:
if copy:
res = cursor.execute(query, copy)
else:
res = cursor.execute(query)
connection.commit()
return res.rowcount
except sqlite3.Error as e:
LOG.error(f"An error occurred: {e}")
finally:
cursor.close()
connection.close()

return 0


QUERIES = {
"init": INIT_QUERY,
"insert_job": JOB_INSERT_QUERY,
"delete_job": DELETE_JOB_QUERY,
}
3 changes: 3 additions & 0 deletions api/backend/database/queries/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from .queries import JOB_INSERT_QUERY, DELETE_JOB_QUERY

__all__ = ["JOB_INSERT_QUERY", "DELETE_JOB_QUERY"]
9 changes: 9 additions & 0 deletions api/backend/database/queries/queries.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
JOB_INSERT_QUERY = """
INSERT INTO jobs
(id, url, elements, user, time_created, result, status, chat, job_options)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
"""

DELETE_JOB_QUERY = """
DELETE FROM jobs WHERE id IN ()
"""
3 changes: 3 additions & 0 deletions api/backend/database/schema/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from .schema import INIT_QUERY

__all__ = ["INIT_QUERY"]
20 changes: 20 additions & 0 deletions api/backend/database/schema/schema.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
INIT_QUERY = """
CREATE TABLE IF NOT EXISTS jobs (
id STRING PRIMARY KEY NOT NULL,
url STRING NOT NULL,
elements JSON NOT NULL,
user STRING,
time_created DATETIME NOT NULL,
result JSON NOT NULL,
status STRING NOT NULL,
chat JSON,
job_options JSON
);
CREATE TABLE IF NOT EXISTS users (
email STRING PRIMARY KEY NOT NULL,
hashed_password STRING NOT NULL,
full_name STRING,
disabled BOOLEAN
);
"""
15 changes: 15 additions & 0 deletions api/backend/database/startup.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
from api.backend.database.common import connect, QUERIES
import logging

LOG = logging.getLogger(__name__)


def init_database():
cursor = connect()

for query in QUERIES["init"].strip().split(";"):
if query.strip():
LOG.info(f"Executing query: {query}")
_ = cursor.execute(query)

cursor.close()
2 changes: 0 additions & 2 deletions api/backend/job/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
from .job import (
query,
insert,
update_job,
delete_jobs,
Expand All @@ -9,7 +8,6 @@
)

__all__ = [
"query",
"insert",
"update_job",
"delete_jobs",
Expand Down
Loading

0 comments on commit 563ca22

Please sign in to comment.