# Quick Start Guide - StructuredStore

Get started with StructuredStore in 5 minutes!

## Prerequisites Check

```bash
# 1. Check if PostgreSQL is running
docker ps | grep postgres

# 2. Check if database exists
psql -h localhost -U postgres -l | grep dsol

# 3. Check Python environment
python --version  # Should be 3.12+
pip list | grep sqlalchemy  # Should show sqlalchemy 2.0+
```

## Step 1: Start Database

```bash
# Option A: Using docker-compose (recommended)
docker-compose up -d postgres

# Option B: Using existing PostgreSQL
# Make sure it's running on localhost:5432
```

## Step 2: Apply Migrations

```bash
# Navigate to project root
cd /home/neil/Documents/DSOL

# Run migrations to create tables
alembic upgrade head
```

## Step 3: Set Environment Variable

```bash
# Set database URL (adjust credentials if needed)
export DATABASE_URL="postgresql+asyncpg://postgres:postgres@localhost:5432/dsol"

# Verify it's set
echo $DATABASE_URL
```

## Step 4: Test StructuredStore

### Quick Test with Python

```python
# test_structured_store_quick.py
import asyncio
from uuid import uuid4
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy.orm import sessionmaker
import os
import sys
from pathlib import Path

# Add project to path
sys.path.insert(0, str(Path.cwd()))

from src.extraction.models import ExtractedRecord
from src.knowledge.structured_store import StructuredStore

async def quick_test():
    """Quick test of StructuredStore."""
    # Get database URL
    db_url = os.getenv("DATABASE_URL", "postgresql+asyncpg://postgres:postgres@localhost:5432/dsol")

    # Create engine and session
    engine = create_async_engine(db_url, echo=False)
    async_session = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)

    async with async_session() as session:
        # Create a test record
        doc_id = uuid4()
        record = ExtractedRecord(
            content={"Item": "Test Item", "Code": "TEST-001"},
            headers=["Item", "Code"],
            _source={
                "document_id": str(doc_id),
                "filename": "test.xlsx",
                "sheet": "Sheet1",
                "table_id": 1,
                "row": 1,
                "col_range": "A:B"
            }
        )

        # Store the record
        store = StructuredStore(session)
        count = await store.store_records([record], doc_id)

        print(f"✅ Success! Stored {count} record(s)")
        print(f"   Document ID: {doc_id}")
        return True

    await engine.dispose()

if __name__ == "__main__":
    try:
        asyncio.run(quick_test())
        print("\n🎉 StructuredStore is working correctly!")
    except Exception as e:
        print(f"\n❌ Error: {e}")
        print("\n💡 Check:")
        print("  1. Is PostgreSQL running? (docker ps)")
        print("  2. Are migrations applied? (alembic upgrade head)")
        print("  3. Is DATABASE_URL correct?")
```

Save this as `test_quick.py` and run:

```bash
python test_quick.py
```

### Run Unit Tests

```bash
# Run all knowledge module tests
python -m pytest tests/knowledge/test_structured_store.py -v

# Expected output: 10 passed
```

## Step 5: Run Examples

```bash
# Run the usage examples
python examples/structured_store_usage.py

# Or run specific example
python -c "
import asyncio
from examples.structured_store_usage import example_1_basic_storage
asyncio.run(example_1_basic_storage())
"
```

## Common Issues & Solutions

### Issue: "Connection refused"

```bash
# Solution: Start PostgreSQL
docker-compose up -d postgres

# Wait a few seconds for it to start
sleep 5
```

### Issue: "Table 'extracted_records' does not exist"

```bash
# Solution: Run migrations
alembic upgrade head
```

### Issue: "ModuleNotFoundError: No module named 'src'"

```bash
# Solution: Run from project root
cd /home/neil/Documents/DSOL
python examples/structured_store_usage.py
```

### Issue: "Password authentication failed"

```bash
# Solution: Update DATABASE_URL with correct credentials
export DATABASE_URL="postgresql+asyncpg://YOUR_USER:YOUR_PASS@localhost:5432/dsol"

# Check your docker-compose.yml for correct credentials
cat docker-compose.yml | grep POSTGRES
```

## Next Steps

1. **Read the Integration Guide:**
   ```bash
   cat docs/integration-guide-structured-store.md
   ```

2. **Try the Query Helper:**
   ```python
   from src.knowledge.query_helper import StructuredQueryHelper

   query = StructuredQueryHelper(session)
   records = await query.find_by_exact_field(doc_id, "Item", "Test Item")
   ```

3. **Add to Your API:**
   See `docs/integration-guide-structured-store.md` for endpoint examples

4. **Run Integration Tests:**
   ```bash
   # Setup test database
   ./scripts/setup-test-db.sh

   # Run integration tests
   python -m pytest tests/knowledge/test_structured_store_integration.py -v
   ```

## Quick Reference

```python
# Store records
from src.knowledge.structured_store import StructuredStore
store = StructuredStore(session)
count = await store.store_records(records, document_id)

# Query records
from src.knowledge.query_helper import StructuredQueryHelper
query = StructuredQueryHelper(session)

# Exact match (< 50ms)
records = await query.find_by_exact_field(doc_id, "Item Code", "2024-4_0001")

# Containment (< 100ms)
records = await query.find_by_containment(doc_id, {"Screen": "○"})

# By sheet (< 20ms)
records = await query.find_by_sheet(doc_id, "Sheet1")
```

## Help

If you're still stuck:
1. Check Story 4.1: `docs/sprint-artifacts/4-1-structured-store-postgresql.md`
2. Check the integration guide: `docs/integration-guide-structured-store.md`
3. Look at the examples: `examples/structured_store_usage.py`
4. Check test fixtures: `tests/knowledge/conftest.py`
