# Setting Up the Vocabulary Feature

This document provides instructions for setting up the vocabulary feature's database table.

## Background

The application uses Flask-Migrate for database migrations. The vocabulary feature requires a new table in the database, but it appears that the migration has not been applied yet.

## Option 1: Using Flask-Migrate (Recommended)

1. Navigate to the project root directory:
   ```
   cd "c:\Users\SO\OneDrive - Higher Education Commission\Desktop\prot-final"
   ```

2. Create a merge migration to handle multiple heads (if needed):
   ```
   python -m flask db merge heads
   ```

3. Apply all migrations:
   ```
   python -m flask db upgrade
   ```

## Option 2: Manual Database Creation

If you're experiencing issues with Flask-Migrate, you can manually create the vocabulary table using a direct SQL approach:

1. Open a Python console in the project directory:
   ```
   python
   ```

2. Run the following Python code:
   ```python
   from app import create_app, db
   app = create_app()
   with app.app_context():
       db.engine.execute("""
       CREATE TABLE IF NOT EXISTS vocabulary (
           id INTEGER PRIMARY KEY AUTOINCREMENT,
           student_id INTEGER NOT NULL,
           word VARCHAR(100) NOT NULL,
           pronunciation VARCHAR(100),
           definition TEXT NOT NULL,
           synonyms TEXT,
           antonyms TEXT,
           example TEXT,
           date_added DATETIME,
           FOREIGN KEY (student_id) REFERENCES user (id)
       )
       """)
       print("Vocabulary table created successfully!")
   ```

## Option 3: Using SQLite Directly

If you prefer to work directly with SQLite:

1. Find the path to your SQLite database file (typically `instance/app.db` or `app.db` in the project root)

2. Use SQLite command line or a tool like SQLite Browser to execute:
   ```sql
   CREATE TABLE IF NOT EXISTS vocabulary (
       id INTEGER PRIMARY KEY AUTOINCREMENT,
       student_id INTEGER NOT NULL,
       word VARCHAR(100) NOT NULL,
       pronunciation VARCHAR(100),
       definition TEXT NOT NULL,
       synonyms TEXT,
       antonyms TEXT,
       example TEXT,
       date_added DATETIME,
       FOREIGN KEY (student_id) REFERENCES user (id)
   );
   ```

## Troubleshooting

### Database Issues

If you encounter errors about "no such table: vocabulary", it means the table hasn't been created yet. Try one of the methods above.

If you see errors about "multiple head revisions", you need to run the merge migration command before upgrading.

### Template Errors

If you encounter a TypeError like "object of type 'int' has no len()" in the vocabulary template, it indicates an issue with the vocabulary list handling in the template. 

This can happen when:

1. The vocabulary variable is not a list (possibly an int or None)
2. The template is trying to call length methods on non-iterable types

The best solution is to ensure the route always returns a list for vocabulary and the template has proper checks:

```python
# In routes/student.py
@student_bp.route('/vocabulary')
def vocabulary():
    vocabulary_items = []
    try:
        # Fetch vocabulary items
        vocabulary_items = Vocabulary.query.filter_by(student_id=current_user.id).all()
        if vocabulary_items is None:
            vocabulary_items = []
    except Exception as e:
        logger.error(f"Error accessing vocabulary: {str(e)}")
        vocabulary_items = []  # Always ensure it's a list
    
    return render_template('student/vocabulary.html', vocabulary=vocabulary_items)
```

And in the template, always check if vocabulary exists and is iterable:

```html
{% if vocabulary is defined and vocabulary|length > 0 %}
    <!-- Process vocabulary items -->
{% else %}
    <!-- Show empty state -->
{% endif %}
```

## Note

The application has been modified to gracefully handle the missing vocabulary table, so it will continue to function without errors even if the table doesn't exist yet. However, vocabulary words won't be saved to the database until the table is created.