# VibeDB Complete Reference

Detailed API documentation and advanced features.

## Database API

### VibeDB()
```python
db = VibeDB(
    path="app.db",                # File path or ":memory:"
    auto_index_hints=True,        # Enable index suggestions
    log_slow_queries=True,        # Track slow queries
    slow_query_threshold_ms=100   # Slow query threshold
)
```

### Methods
- `collection(name)` → Get/create collection
- `collections()` → List all collection names
- `drop_collection(name)` → Delete collection
- `collection_info(name)` → Get collection metadata
- `stats()` → Database statistics
- `vacuum()` → Optimize database
- `close()` → Close connection

## Collection API

### CRUD Methods
- `insert(doc)` → Insert document, returns ID
- `insert_many(docs)` → Bulk insert, returns IDs
- `get(id)` → Get by ID
- `find(query)` → Find documents (returns Cursor)
- `find_one(query)` → Find first match
- `update(id, updates)` → Update document
- `update_many(query, updates)` → Bulk update
- `upsert(query, doc)` → Update or insert
- `delete(id)` → Delete document
- `delete_many(query)` → Bulk delete
- `count(query)` → Count documents

### Index Methods
- `create_index(fields, unique=False, name=None)` → Create index
- `list_indexes()` → List indexes
- `drop_index(name)` → Drop index
- `index_suggestions()` → Get auto-suggestions

### Schema Methods
- `set_schema(schema)` → Set validation schema
- `get_schema()` → Get current schema
- `drop_schema()` → Remove schema

## Query Operators

### Comparison
| Operator | Dict | Q Builder |
|----------|------|-----------|
| Equal | `{"field": value}` | `Q.eq("field", value)` |
| Not equal | `{"field": {"$ne": value}}` | `Q.ne("field", value)` |
| Greater | `{"field": {"$gt": value}}` | `Q.gt("field", value)` |
| Greater/equal | `{"field": {"$gte": value}}` | `Q.gte("field", value)` |
| Less | `{"field": {"$lt": value}}` | `Q.lt("field", value)` |
| Less/equal | `{"field": {"$lte": value}}` | `Q.lte("field", value)` |
| In | `{"field": {"$in": [...]}}` | `Q.in_("field", [...])` |
| Not in | `{"field": {"$nin": [...]}}` | `Q.nin("field", [...])` |
| Exists | `{"field": {"$exists": True}}` | `Q.exists("field", True)` |

### String Operators
- `Q.prefix("field", "str")` - Starts with
- `Q.contains("field", "str")` - Contains substring
- `Q.regex("field", r"pattern")` - Regex match

### Array Operators
- `Q.has("field", value)` - Array contains value
- `Q.has_any("field", [values])` - Contains any of
- `Q.has_all("field", [values])` - Contains all of

### Logical Operators
```python
# AND
Q.gte("age", 25) & Q.lt("age", 40)
Q.gte("age", 25).and_(Q.lt("age", 40))

# OR
Q.eq("role", "admin") | Q.eq("role", "mod")
Q.eq("role", "admin").or_(Q.eq("role", "mod"))

# NOT
~Q.eq("role", "user")
Q.eq("role", "user").not_()
```

## Cursor API

Methods (chainable):
- `sort(field, direction)` - Sort (1=asc, -1=desc)
- `limit(n)` - Limit results
- `skip(n)` - Skip results
- `to_list()` - Execute and get list
- `first()` - Get first result
- `count()` - Count results
- Iteration: `for doc in cursor:`

Example:
```python
results = users.find(Q.gte("age", 25)) \
    .sort("age", -1) \
    .skip(10) \
    .limit(10) \
    .to_list()
```

## Document API

Access patterns:
```python
doc = users.get(user_id)

# Dict notation (always works)
doc["name"]
doc["_id"]
doc["address"]["city"]

# Dot notation (top-level only)
doc.name
doc.age

# Methods
doc.update({"age": 29})
doc.delete()
doc.to_dict()
doc.id  # Shortcut for doc["_id"]
```

## Schema Validation

### Field Types
- `string` - Text
- `integer` - Whole numbers
- `number` - Int or float
- `boolean` - True/False
- `array` - Lists
- `object` - Nested objects

### Constraints
```python
schema = {
    "field": {
        "type": "string",              # Required type
        "required": True,              # Must exist
        "min": 1,                      # Min value/length
        "max": 100,                    # Max value/length
        "enum": ["val1", "val2"],      # Allowed values
        "pattern": r"^regex$",         # Regex validation
        "default": "default",          # Default value
        "unique": True,                # Must be unique
        "items": {"type": "string"}    # Array item validation
    }
}
```

Example:
```python
users.set_schema({
    "email": {
        "type": "string",
        "required": True,
        "unique": True,
        "pattern": r"^[^@]+@[^@]+\.[^@]+$"
    },
    "age": {
        "type": "integer",
        "min": 0,
        "max": 150
    },
    "role": {
        "type": "string",
        "enum": ["admin", "user", "moderator"],
        "default": "user"
    }
})
```

## Error Handling

```python
from vibedb.errors import ValidationError

try:
    users.insert(data)
except ValidationError as e:
    print(f"Validation failed: {e}")
    print(f"Field: {e.field}")
    print(f"Constraint: {e.constraint}")
```

## Performance Tips

1. **Create indexes** on frequently queried fields
2. **Use bulk operations** (`insert_many` vs loop)
3. **Limit results** for large datasets
4. **Use count()** not `len(find().to_list())`
5. **Vacuum periodically** to reclaim space

## Transactions

```python
with db._engine.transaction():
    users.insert({"name": "Alice"})
    logs.insert({"action": "user_created"})
    # Both commit together or both rollback
```
