Commit 88530939 authored by Anthony Jacob's avatar Anthony Jacob
Browse files

small refacto

parent 607776e5
Loading
Loading
Loading
Loading
+44 −63
Original line number Diff line number Diff line
@@ -2,7 +2,7 @@ from datetime import date
import traceback
from flask import current_app
from typing import Any, Literal
from psycopg.rows import dict_row
from helpers.db import db_cursor


def getAbouts():
@@ -10,14 +10,10 @@ def getAbouts():
    getAboutsQuery = """SELECT id FROM about"""

    try:
        with current_app.db_pool.connection() as conn:
            with conn.cursor(row_factory=dict_row) as cur:
        with db_cursor(dict_results=True) as (conn, cur):
            cur.execute(getAboutsQuery)
            rows = cur.fetchall()
                if not rows:
                    return []

                return [row["id"] for row in rows]
            return [row["id"] for row in rows] if rows else []

    except Exception as e:
        current_app.logger.error(f"Database error while retrieving abouts: {e}")
@@ -46,14 +42,10 @@ def getAboutsFull():
    """

    try:
        with current_app.db_pool.connection() as conn:
            with conn.cursor(row_factory=dict_row) as cur:
        with db_cursor(dict_results=True) as (conn, cur):
            cur.execute(getAboutsQuery)
            rows = cur.fetchall()
                if not rows:
                    return []

                return rows
            return rows if rows else []

    except Exception as e:
        current_app.logger.error(f"Database error while retrieving abouts: {e}")
@@ -82,14 +74,10 @@ def getAbout(AboutId: int) -> Any | Literal[-1] | Literal[False]:
    """

    try:
        with current_app.db_pool.connection() as conn:
            with conn.cursor(row_factory=dict_row) as cur:
        with db_cursor(dict_results=True) as (conn, cur):
            cur.execute(getAboutQuery, (AboutId,))
            row = cur.fetchone()
                if not row:
                    return -1
                else:
                    return row
            return row if row else -1

    except Exception as e:
        current_app.logger.error(f"Database error while retrieving abouts: {e}")
@@ -109,8 +97,7 @@ def insertUpdateAbout(
                            AND language_id = (SELECT id FROM language WHERE language_code = %s);"""

    try:
        with current_app.db_pool.connection() as conn:
            with conn.cursor() as cur:
        with db_cursor() as (conn, cur):
            for AboutTranslation in translations:
                if isAboutTranslationExists(
                    1, AboutTranslation["language_code"]
@@ -141,8 +128,7 @@ def deleteAbout(AboutId: int) -> bool:
    deleteAboutsQuery = """DELETE FROM about WHERE id = %s"""

    try:
        with current_app.db_pool.connection() as conn:
            with conn.cursor() as cur:
        with db_cursor() as (conn, cur):
            cur.execute(deleteAboutsQuery, (AboutId,))
            conn.commit()
            return True
@@ -164,14 +150,10 @@ def isAboutTranslationExists(aboutID: int, LanguageCode: str) -> bool:
    """

    try:
        with current_app.db_pool.connection() as conn:
            with conn.cursor() as cur:
        with db_cursor() as (conn, cur):
            cur.execute(getAboutTranslationQuery, (aboutID, LanguageCode))
            row = cur.fetchone()
                if not row:
                    return False
                else:
                    return True
            return True if row else False

    except Exception as e:
        current_app.logger.error(f"Database error while retrieving abouts: {e}")
@@ -186,8 +168,7 @@ def updateAboutPicture(aboutID: int, filename: str) -> bool:
    """

    try:
        with current_app.db_pool.connection() as conn:
            with conn.cursor() as cur:
        with db_cursor() as (conn, cur):
            cur.execute(getAboutTranslationQuery, (filename, aboutID))
            conn.commit()
            return True
+73 −84
Original line number Diff line number Diff line
@@ -2,22 +2,17 @@ from datetime import date
import traceback
from flask import current_app
from typing import Any, Literal
from psycopg.rows import dict_row

from helpers.db import db_cursor

def getDiplomas():

    getDiplomasQuery = """SELECT id FROM diploma"""

    try:
        with current_app.db_pool.connection() as conn:
            with conn.cursor(row_factory=dict_row) as cur:
        with db_cursor(dict_results=True) as (conn, cur):
            cur.execute(getDiplomasQuery)
            rows = cur.fetchall()
                if not rows:
                    return []

                return [row["id"] for row in rows]
            return [row["id"] for row in rows] if rows else []

    except Exception as e:
        current_app.logger.error(f"Database error while retrieving diplomas: {e}")
@@ -51,14 +46,10 @@ def getDiplomasFull():
    """

    try:
        with current_app.db_pool.connection() as conn:
            with conn.cursor(row_factory=dict_row) as cur:
        with db_cursor(dict_results=True) as (conn, cur):
            cur.execute(getDiplomasQuery)
            rows = cur.fetchall()
                if not rows:
                    return []

                return rows
            return rows if rows else []

    except Exception as e:
        current_app.logger.error(f"Database error while retrieving diplomas: {e}")
@@ -93,14 +84,10 @@ def getDiploma(DiplomaId: int) -> Any | Literal[-1] | Literal[False]:
    """

    try:
        with current_app.db_pool.connection() as conn:
            with conn.cursor(row_factory=dict_row) as cur:
        with db_cursor(dict_results=True) as (conn, cur):
                cur.execute(getDiplomaQuery, (DiplomaId,))
                row = cur.fetchone()
                if not row:
                    return -1
                else:
                    return row
                return row if row else -1

    except Exception as e:
        current_app.logger.error(f"Database error while retrieving diplomas: {e}")
@@ -115,8 +102,10 @@ def insertDiploma(
               VALUES (%s, %s) RETURNING id;"""

    try:
        with current_app.db_pool.connection() as conn:
            with conn.cursor() as cur:
        with db_cursor() as (conn, cur):
            # Start transaction
            conn.execute("BEGIN")
            try:
                cur.execute(InsertDiplomaQuery, (start_date, end_date))
                diploma_id = cur.fetchone()[0]
                conn.commit()
@@ -130,8 +119,11 @@ def insertDiploma(
                        raise Exception(
                            f"Database error while inserting diploma translation for {DiplomaTranslation['language_code']}"
                        )

                conn.execute("COMMIT")
                return diploma_id
            except Exception as e:
                conn.execute("ROLLBACK")
                raise e

    except Exception as e:
        current_app.logger.error(f"Database error while inserting diploma: {e}")
@@ -149,8 +141,7 @@ def insertDiplomaTranslation(
    description = None if description == "NULL" else description

    try:
        with current_app.db_pool.connection() as conn:
            with conn.cursor() as cur:
        with db_cursor() as (conn, cur):
            cur.execute(
                InsertDiplomaQuery, (diplomaID, language_code, title, description)
            )
@@ -167,8 +158,7 @@ def updateDiplomaTranslation(
    diplomaID: int, language_code: str, title: str, description: str
):
    try:
        with current_app.db_pool.connection() as conn:
            with conn.cursor() as cur:
        with db_cursor() as (conn, cur):

            update_fields = []
            update_values = []
@@ -213,8 +203,7 @@ def deleteDiploma(DiplomaId: int) -> bool:
    deleteDiplomasQuery = """DELETE FROM diploma WHERE id = %s"""

    try:
        with current_app.db_pool.connection() as conn:
            with conn.cursor() as cur:
        with db_cursor() as (conn, cur):
            cur.execute(deleteDiplomasQuery, (DiplomaId,))
            conn.commit()
            return True
@@ -232,8 +221,7 @@ def deleteDiplomaTranslation(DiplomaId: int, language_code: str) -> bool:
                                AND language_id = (SELECT id FROM language WHERE language_code = %s)"""

    try:
        with current_app.db_pool.connection() as conn:
            with conn.cursor() as cur:
        with db_cursor() as (conn, cur):
            cur.execute(deleteDiplomasQuery, (DiplomaId,language_code))
            conn.commit()
            return True
@@ -247,9 +235,10 @@ def updateDiploma(
    id: int, start_date: date, end_date: date, translations: list[dict[str, str]]
):
    try:
        with current_app.db_pool.connection() as conn:
            with conn.cursor() as cur:

        with db_cursor() as (conn, cur):
            # Start transaction
            conn.execute("BEGIN")
            try:
                update_fields = []
                update_values = []

@@ -304,11 +293,15 @@ def updateDiploma(
                            raise Exception(
                                f"Database error while inserting diploma translation for {id} / {diplomaTranslation['language_code']}"
                            )

                    conn.execute("COMMIT")
                    return id  # Returning the updated diploma ID

                return False  # No update performed

            except Exception as e:
                conn.execute("ROLLBACK")
                raise e

    except Exception as e:
        # Capture full traceback for debugging
        error_details = traceback.format_exc()
@@ -335,14 +328,10 @@ def isDiplomaTranslationExists(diplomaID: int, LanguageCode: str) -> bool:
    """

    try:
        with current_app.db_pool.connection() as conn:
            with conn.cursor() as cur:
        with db_cursor() as (conn, cur):
            cur.execute(getDiplomaTranslationQuery, (diplomaID, LanguageCode))
            row = cur.fetchone()
                if not row:
                    return False
                else:
                    return True
            return True if row else False

    except Exception as e:
        current_app.logger.error(f"Database error while retrieving diplomas: {e}")
+120 −139
Original line number Diff line number Diff line
@@ -2,22 +2,14 @@ from datetime import date
import traceback
from flask import current_app
from typing import Any, Literal
from psycopg.rows import dict_row

from helpers.db import db_cursor

def getExperiences():

    getExperiencesQuery = """SELECT id FROM experience"""

    try:
        with current_app.db_pool.connection() as conn:
            with conn.cursor(row_factory=dict_row) as cur:
                cur.execute(getExperiencesQuery)
        with db_cursor(dict_results=True) as (conn, cur):
            cur.execute("SELECT id FROM experience")
            rows = cur.fetchall()
                if not rows:
                    return []

                return [row["id"] for row in rows]
            return [row["id"] for row in rows] if rows else []

    except Exception as e:
        current_app.logger.error(f"Database error while retrieving experiences: {e}")
@@ -56,14 +48,10 @@ def getExperiencesFull():
    """

    try:
        with current_app.db_pool.connection() as conn:
            with conn.cursor(row_factory=dict_row) as cur:
        with db_cursor(dict_results=True) as (conn, cur):
            cur.execute(getExperiencesQuery)
            rows = cur.fetchall()
                if not rows:
                    return []

                return rows
            return rows if rows else []

    except Exception as e:
        current_app.logger.error(f"Database error while retrieving experiences: {e}")
@@ -103,14 +91,9 @@ def getExperience(ExperienceId: int) -> Any | Literal[-1] | Literal[False]:
    """

    try:
        with current_app.db_pool.connection() as conn:
            with conn.cursor(row_factory=dict_row) as cur:
         with db_cursor(dict_results=True) as (conn, cur):
            cur.execute(getExperienceQuery, (ExperienceId,))
                row = cur.fetchone()
                if not row:
                    return -1
                else:
                    return row
            return cur.fetchone() or -1

    except Exception as e:
        current_app.logger.error(f"Database error while retrieving experiences: {e}")
@@ -128,14 +111,17 @@ def insertExperience(
               VALUES (%s, %s, %s) RETURNING id;"""

    try:
        with current_app.db_pool.connection() as conn:
            with conn.cursor() as cur:
         with db_cursor() as (conn, cur):
                # Start transaction
                conn.execute("BEGIN")
                try:
                    # Insert experience and fetch the generated ID
                    cur.execute(
                        InsertExperienceQuery,
                        (experience_start_date, experience_end_date, website),
                    )
                    experience_id = cur.fetchone()[0]
                conn.commit()

                    for ExperienceTranslation in translations:
                        if not insertExperienceTranslation(
                            experience_id,
@@ -148,8 +134,14 @@ def insertExperience(
                                f"Database error while inserting experience translation for {ExperienceTranslation['language_code']}"
                            )

                    conn.execute("COMMIT")
                    current_app.logger.info(f"Successfully inserted experience with ID {experience_id}")
                    return experience_id

                except Exception as e:
                    conn.execute("ROLLBACK")
                    raise e

    except Exception as e:
        current_app.logger.error(f"Database error while inserting experience: {e}")
        return False
@@ -171,8 +163,7 @@ def insertExperienceTranslation(
    job_place = None if job_place == "NULL" else job_place

    try:
        with current_app.db_pool.connection() as conn:
            with conn.cursor() as cur:
         with db_cursor() as (conn, cur):
                cur.execute(
                    InsertExperienceQuery,
                    (
@@ -184,7 +175,6 @@ def insertExperienceTranslation(
                    ),
                )
                conn.commit()

                return True

    except Exception as e:
@@ -200,8 +190,7 @@ def updateExperienceTranslation(
    job_place: str,
):
    try:
        with current_app.db_pool.connection() as conn:
            with conn.cursor() as cur:
        with db_cursor(dict_results=True) as (conn, cur):

                update_fields = []
                update_values = []
@@ -253,8 +242,7 @@ def deleteExperience(ExperienceId: int) -> bool:
    deleteExperiencesQuery = """DELETE FROM experience WHERE id = %s"""

    try:
        with current_app.db_pool.connection() as conn:
            with conn.cursor() as cur:
        with db_cursor(dict_results=True) as (conn, cur):
            cur.execute(deleteExperiencesQuery, (ExperienceId,))
            conn.commit()
            return True
@@ -271,8 +259,7 @@ def deleteExperienceTranslation(ExperienceId: int, language_code: str) -> bool:
                                AND language_id = (SELECT id FROM language WHERE language_code = %s)"""

    try:
        with current_app.db_pool.connection() as conn:
            with conn.cursor() as cur:
        with db_cursor(dict_results=True) as (conn, cur):
            cur.execute(deleteExperiencesQuery, (ExperienceId,language_code))
            conn.commit()
            return True
@@ -289,8 +276,7 @@ def updateExperience(
    translations: list[dict[str, str]],
):
    try:
        with current_app.db_pool.connection() as conn:
            with conn.cursor() as cur:
        with db_cursor(dict_results=True) as (conn, cur):

            update_fields = []
            update_values = []
@@ -397,14 +383,10 @@ def isExperienceTranslationExists(experienceID: int, LanguageCode: str) -> bool:
    """

    try:
        with current_app.db_pool.connection() as conn:
            with conn.cursor() as cur:
        with db_cursor(dict_results=True) as (conn, cur):
            cur.execute(getExperienceTranslationQuery, (experienceID, LanguageCode))
            row = cur.fetchone()
                if not row:
                    return False
                else:
                    return True
            return True if row else False

    except Exception as e:
        current_app.logger.error(f"Database error while retrieving experiences: {e}")
@@ -419,8 +401,7 @@ def updateExperienceLogo(experienceID: int, filename: str) -> bool:
    """

    try:
        with current_app.db_pool.connection() as conn:
            with conn.cursor() as cur:
        with db_cursor(dict_results=True) as (conn, cur):
            cur.execute(getExperienceTranslationQuery, (filename, experienceID))
            conn.commit()
            return True
+55 −79
Original line number Diff line number Diff line
from flask import current_app
from typing import Any, Literal
from psycopg.rows import dict_row
from helpers.db import db_cursor


def getKeywords():
@@ -8,14 +8,10 @@ def getKeywords():
    getKeywordsQuery = """SELECT id FROM keyword"""

    try:
        with current_app.db_pool.connection() as conn:
            with conn.cursor(row_factory=dict_row) as cur:
        with db_cursor(dict_results=True) as (conn, cur):
            cur.execute(getKeywordsQuery)
            rows = cur.fetchall()
                if not rows:
                    return []

                return [row["id"] for row in rows]
            return [row["id"] for row in rows] if rows else []

    except Exception as e:
        current_app.logger.error(f"Database error while retrieving keywords: {e}")
@@ -37,14 +33,10 @@ def getKeywordsFull():
                            k.position"""

    try:
        with current_app.db_pool.connection() as conn:
            with conn.cursor(row_factory=dict_row) as cur:
        with db_cursor(dict_results=True) as (conn, cur):
            cur.execute(getKeywordsQuery)
            rows = cur.fetchall()
                if not rows:
                    return []

                return rows
            return rows if rows else []

    except Exception as e:
        current_app.logger.error(f"Database error while retrieving keywords: {e}")
@@ -65,14 +57,10 @@ def getKeyword(keywordId: int) -> Any | Literal[-1] | Literal[False]:
                        """

    try:
        with current_app.db_pool.connection() as conn:
            with conn.cursor(row_factory=dict_row) as cur:
        with db_cursor(dict_results=True) as (conn, cur):
            cur.execute(getKeywordQuery, (keywordId,))
            row = cur.fetchone()
                if not row:
                    return -1
                else:
                    return row
            return row if row else -1

    except Exception as e:
        current_app.logger.error(f"Database error while retrieving keywords: {e}")
@@ -96,8 +84,7 @@ def getKeywordByCode(
                        """

    try:
        with current_app.db_pool.connection() as conn:
            with conn.cursor(row_factory=dict_row) as cur:
        with db_cursor(dict_results=True) as (conn, cur):
            cur.execute(
                getKeywordQuery,
                (
@@ -106,10 +93,7 @@ def getKeywordByCode(
                ),
            )
            row = cur.fetchone()
                if not row:
                    return -1
                else:
                    return row
            return row if row else -1

    except Exception as e:
        current_app.logger.error(f"Database error while retrieving keywords: {e}")
@@ -118,8 +102,7 @@ def getKeywordByCode(

def insertKeyword(keyword: str, languageID: str, position: int = None) -> bool | int:
    try:
        with current_app.db_pool.connection() as conn:
            with conn.cursor() as cur:
        with db_cursor() as (conn, cur):
            cur.execute(
                "SELECT public.insertKeyword(%s, %s, %s);",
                (
@@ -142,8 +125,7 @@ def deleteKeyword(keywordId: int) -> bool:
    deleteKeywordsQuery = """SELECT public.deleteKeyword(%s)"""

    try:
        with current_app.db_pool.connection() as conn:
            with conn.cursor() as cur:
        with db_cursor() as (conn, cur):
            cur.execute(deleteKeywordsQuery, (keywordId,))
            conn.commit()
            return True
@@ -161,8 +143,7 @@ def updateKeyword(id: int, keyword: str, language_id: int, position: int):
    deleteKeywordsQuery = """"""

    try:
        with current_app.db_pool.connection() as conn:
            with conn.cursor() as cur:
        with db_cursor() as (conn, cur):
            cur.execute(
                "SELECT public.updateKeyword(%s, %s, %s, %s)",
                (id, keyword, language_id, position),
@@ -186,8 +167,7 @@ def getLastPosition(LanguageCode: str) -> int:
                                AND l.language_code = %s"""

    try:
        with current_app.db_pool.connection() as conn:
            with conn.cursor() as cur:
        with db_cursor() as (conn, cur):
            cur.execute(getLastPositionQuery, (LanguageCode,))
            lastPosition = cur.fetchone()[0]
            conn.commit()
@@ -212,14 +192,10 @@ def isKeywordExists(Keyword: str, LanguageCode: str) -> bool:
    """

    try:
        with current_app.db_pool.connection() as conn:
            with conn.cursor() as cur:
        with db_cursor() as (conn, cur):
            cur.execute(getKeywordQuery, (Keyword, LanguageCode))
            row = cur.fetchone()
                if not row:
                    return False
                else:
                    return True
            return True if row else False

    except Exception as e:
        current_app.logger.error(f"Database error while retrieving keyword: {e}")
+56 −75
Original line number Diff line number Diff line
from flask import current_app
from typing import Any, Literal
from psycopg.rows import dict_row
from helpers.db import db_cursor


def getLanguages():
@@ -8,14 +8,10 @@ def getLanguages():
    getLanguagesQuery = """SELECT id FROM language"""

    try:
        with current_app.db_pool.connection() as conn:
            with conn.cursor(row_factory=dict_row) as cur:
        with db_cursor(dict_results=True) as (conn, cur):
            cur.execute(getLanguagesQuery)
            rows = cur.fetchall()
                if not rows:
                    return []

                return [row["id"] for row in rows]
            return [row["id"] for row in rows] if rows else []

    except Exception as e:
        current_app.logger.error(f"Database error while retrieving languages: {e}")
@@ -27,14 +23,10 @@ def getLanguagesFull():
    getLanguagesQuery = """SELECT id, language_code FROM language"""

    try:
        with current_app.db_pool.connection() as conn:
            with conn.cursor(row_factory=dict_row) as cur:
        with db_cursor(dict_results=True) as (conn, cur):
            cur.execute(getLanguagesQuery)
            rows = cur.fetchall()
                if not rows:
                    return []

                return rows
            return rows if rows else []

    except Exception as e:
        current_app.logger.error(f"Database error while retrieving languages: {e}")
@@ -46,14 +38,10 @@ def getLanguage(languageId: int) -> Any | Literal[-1] | Literal[False]:
    getLanguageQuery = """SELECT id, language_code FROM language WHERE id = %s"""

    try:
        with current_app.db_pool.connection() as conn:
            with conn.cursor(row_factory=dict_row) as cur:
        with db_cursor(dict_results=True) as (conn, cur):
                cur.execute(getLanguageQuery, (languageId,))
                row = cur.fetchone()
                if not row:
                    return -1
                else:
                    return row
                return row if row else -1

    except Exception as e:
        current_app.logger.error(f"Database error while retrieving languages: {e}")
@@ -67,14 +55,10 @@ def getLanguageByCode(languageCode: str) -> Any | Literal[-1] | Literal[False]:
    )

    try:
        with current_app.db_pool.connection() as conn:
            with conn.cursor(row_factory=dict_row) as cur:
        with db_cursor(dict_results=True) as (conn, cur):
            cur.execute(getLanguageQuery, (languageCode,))
            row = cur.fetchone()
                if not row:
                    return -1
                else:
                    return row
            return row if row else -1

    except Exception as e:
        current_app.logger.error(f"Database error while retrieving languages: {e}")
@@ -99,8 +83,7 @@ def insertLanguage(languageCode: str, enabled: bool) -> bool | int:
               VALUES (%s, %s) RETURNING id;"""

    try:
        with current_app.db_pool.connection() as conn:
            with conn.cursor() as cur:
        with db_cursor() as (conn, cur):
            cur.execute(getLanguageQuery, (languageCode,))
            row = cur.fetchone()
            if row:
@@ -123,8 +106,7 @@ def deleteLanguage(languageId: int) -> bool:
    deleteLanguagesQuery = """DELETE FROM language WHERE id = %s"""

    try:
        with current_app.db_pool.connection() as conn:
            with conn.cursor() as cur:
        with db_cursor() as (conn, cur):
            cur.execute(deleteLanguagesQuery, (languageId,))
            conn.commit()
            return True
@@ -142,8 +124,7 @@ def updateLanguage(id: int, languageCode: str, enabled: bool):
    getLanguageIdQuery = """SELECT id FROM language WHERE id = %s"""

    try:
        with current_app.db_pool.connection() as conn:
            with conn.cursor() as cur:
        with db_cursor() as (conn, cur):
            cur.execute(getLanguageIdQuery, (id,))
            LanguageIDToUpdate = cur.fetchone()

Loading