# Options Flow Query - Raw SQL Setup

## Overview

The `optionsFlowQuery.js` module supports both:
1. **Raw SQL queries** (Script 1 style) - For complex analytical queries
2. **Query builder methods** - For simple CRUD operations

## Setting Up Raw SQL Queries

### Step 1: Create RPC Function in Supabase

Run the SQL in `../database/rpc_functions.sql` to create the `exec_sql` function that enables raw SQL execution.

### Step 2: Add Your Script 1 SQL

1. Open `optionsFlowQuery.sql` to see the template structure
2. Copy your complete Script 1 SQL query
3. Paste it into the `optionsFlowQuerySQL` constant in `optionsFlowQuery.js`
4. Replace all hardcoded values with parameter placeholders:
   - Dates: Use `$1::date`, `$2::date`, etc.
   - Numbers: Use `$3::numeric`, `$4::integer`, etc.
   - Strings: Use `$5::text`, etc.

### Step 3: Update Parameter Builder

Update the `buildOptionsFlowParams()` function to match your SQL parameter order:

```javascript
export function buildOptionsFlowParams(params = {}) {
  return [
    params.startDate,      // $1
    params.endDate,        // $2
    params.tolPct,         // $3
    params.minNotional,    // $4
    params.limit           // $5
    // ... add more as needed
  ];
}
```

### Step 4: Use Raw SQL in Routes

Enable raw SQL by passing `useRawSQL: true`:

```javascript
const flows = await OptionsFlowQuery.getRecentFlow(filters, true);
```

## Parameter Placeholder Examples

```sql
-- Dates
WHERE created_at >= $1::date
  AND created_at <= $2::date

-- Numerics
AND total_premium >= $3::numeric

-- Integers
LIMIT $4::integer

-- Text/Strings
AND symbol = $5::text
```

## Fallback Behavior

If raw SQL fails or isn't configured, the query automatically falls back to the query builder method, ensuring the API continues to work.

## Testing

Test your raw SQL query in Supabase SQL Editor first, then test via the API:

```bash
curl http://localhost:3001/api/options-flow?useRawSQL=true&startDate=2024-01-01
```

