pythonpostgresqlprisma

How to insert String data as enum into Postgres database in Python


I'm trying to add a String type data into a postgresql database in Python by Prisma. The culumn in database is defined as a specific enum type in Prisma schema. I tried to insert by a String mapping. However the insert was failed with not support with String type. What should I do?

from enum import Enum
from prisma import Prisma

db = Prisma()
os.environ['DATABASE_URL'] = ''
db.connect()

class DifficultyLevel(Enum):
    EASY = 'EASY'
    MEDIUM = 'MEDIUM'
    HARD = 'HARD'
    LUCK = 'LUCK'

def map_question_difficulty(generated_difficulty):
    difficulty_mapping = {
        'Easy': DifficultyLevel.EASY,
        'Medium': DifficultyLevel.MEDIUM,
        'Hard': DifficultyLevel.HARD,
        'LUCK': DifficultyLevel.LUCK
    }
    return difficulty_mapping.get(generated_difficulty, DifficultyLevel.EASY).value  # Default to EASY if difficulty not found

async def insert_questions_to_db(questions):
    try:
        for question in questions:
            db.elementgenerated.create(
                data={
                    "difficulty": map_question_difficulty(question['difficulty'])
                }
            )
        logging.info(f"Successfully inserted {len(questions)} questions into the database.")
    except Exception as e:
        logging.error(f"Error inserting questions into the database: {e}")
        raise

Definition in Prisma schema:

enum DifficultyLevel {
  EASY
  MEDIUM
  HARD
}

Here the Program gave feedback with: 'prisma.errors.DataError: Error converting field "difficulty" of expected non-nullable type "String", found incompatible value of "EASY".' The question['difficulty'] is a String object like 'Easy', 'Medium' or 'Hard'.


Solution

  • missing enumerated value

    Your prisma schema should also include LUCK. A discrepancy between python and prisma seems like a Bad Thing.

    read the diagnostic

    prisma.errors.DataError: Error converting field "difficulty" of expected non-nullable type "String", found incompatible value of "EASY".' The question['difficulty'] is a String object like 'Easy', 'Medium' or 'Hard'.

    This suggests revising your Enum class to be:

    class DifficultyLevel(Enum):
        EASY = 'Easy'
        MEDIUM = 'Medium'
        HARD = 'Hard'
        LUCK = 'Luck'
    

    auto()

    Side note: consider DRYing up the class by defining it this way:

    from enum import Enum, auto
    
    class DifficultyLevel(Enum):
        EASY = auto()
        MEDIUM = auto()
        HARD = auto()
        LUCK = auto()
    
        def __str__(self):
            return self.name.title()
    

    And then use f-string or str() rather than .value.