Metadata-Version: 2.4
Name: cachedb_lite
Version: 0.1.0
Summary: A lightweight persistent function result caching library with SQLite and Pickle support
Author-email: ciaranchen <ciaranchen@qq.com>
License: MIT License
        
        Copyright (c) 2026 ciaranchen
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
        
Project-URL: Homepage, https://github.com/ciaranchen/cachelite
Project-URL: Issues, https://github.com/ciaranchen/cachelite/issues
Keywords: cache,caching,sqlite,pickle,decorator,performance,persistent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: Database
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
Dynamic: license-file

# CacheDB Lite

A lightweight persistent function result caching library for Python with SQLite and Pickle support.

## Features

- 🚀 **Easy to use**: Simple decorator-based API
- 💾 **Dual storage**: SQLite database or Pickle files
- 🎯 **Flexible key configuration**: Specify which parameters to use as cache keys
- 📦 **BLOB support**: Automatic serialization for complex objects
- 🔑 **Auto-increment ID**: Internal primary key for better database design
- ⏰ **Cache expiration**: Set custom expiration time for cache entries
- 🔒 **Secure**: Parameterized queries for SQLite storage
- 🔄 **Backward compatible**: Existing code continues to work without changes
- 📦 **Lightweight**: No external dependencies

## Installation

### Using pip

```bash
pip install cachedb-lite
```

### From source

```bash
git clone https://github.com/ciaranchen/cachelite.git
cd cachelite
pip install -e .
```

## Quick Start

### Basic Usage

```python
from cachedb_lite import cache_result

@cache_result()
def expensive_function(a, b):
    # Simulate a time-consuming operation
    import time
    time.sleep(2)
    return a + b

# First call: executes the function and caches the result
result1 = expensive_function(1, 2)  # Takes ~2 seconds

# Second call: returns cached result immediately
result2 = expensive_function(1, 2)  # Takes ~0 seconds
```

### Using SQLite Storage

```python
@cache_result(
    storage_type='sqlite',
    cache_dir='./cache.db'
)
def expensive_function(a, b):
    return a + b
```

### Using Pickle Storage

```python
@cache_result(
    storage_type='pickle',
    cache_dir='./cache'
)
def expensive_function(a, b):
    return a + b
```

### Specifying Cache Keys

```python
# Use only specific parameters as cache keys
@cache_result(key_params=['a'])
def expensive_function(a, b):
    return a + b

# With parameter types
@cache_result(key_params={'a': 'int', 'b': 'str'})
def expensive_function(a, b):
    return f"{a}_{b}"

# With BLOB type (automatically serializes complex objects)
@cache_result(key_params={'data': 'blob'})
def process_data(data):
    # data can be bytes or complex objects (dict, list, etc.)
    return f"Processed {len(data)} bytes"
```

### Cache Expiration

```python
# Cache expires after 1 hour (3600 seconds)
@cache_result(expire_after=3600)
def expensive_function(a, b):
    return a + b
```

## Advanced Usage with CacheManager

For more advanced control, use the `CacheManager` class:

```python
from cachedb_lite import CacheManager

# Initialize cache manager
cache_manager = CacheManager(db_path='./cache.db')

# Create a custom cache table
cache_manager.create_table(
    table_name='user_data',
    columns={'user_id': 'INTEGER', 'date': 'TEXT', 'data': 'BLOB'}
)

# Use the cache manager decorator
@cache_manager.cache_result(
    table_name='user_data',
    key_mapping={'user_id': 'user_id', 'date': 'date', 'data': 'data'},
    expire_after=3600
)
def get_user_data(user_id, date, data):
    # data will be automatically serialized if it's not bytes
    return f"User {user_id} data for {date}"
```

**Note**: Tables created with `CacheManager` automatically include an internal `_cachelite_id` field as the primary key, and use special field names (`_cachelite_value`, `_cachelite_created_at`, `_cachelite_expire_at`) to avoid conflicts with your column names.

## CacheManager API

### Initialization

```python
cache_manager = CacheManager(db_path='./cache.db')
```

### Methods

- `create_table(table_name, columns)`: Create a new cache table
- `cache_result(table_name, key_mapping, expire_after=None, ignore_errors=False)`: Cache decorator
- `delete(table_name, key_values)`: Delete specific cache entry
- `clear(table_name)`: Clear all cache entries in a table
- `clear_all()`: Clear all cache entries in all tables

## Configuration

### Storage Types

- `sqlite`: SQLite database storage (default)
- `pickle`: File-based storage using Pickle

### Cache Key Types

- `int`: Integer
- `float`: Float
- `str`: String
- `bool`: Boolean
- `datetime`: Date and time
- `date`: Date
- `blob`: Binary data (automatically serializes complex objects using Pickle)

**BLOB Type Note**: When using `blob` type, the parameter can be either:
- `bytes`: Used directly without modification
- Complex objects (dict, list, etc.): Automatically serialized using Pickle

## Best Practices

1. **Use meaningful cache keys**: Only include relevant parameters
2. **Set appropriate expiration times**: Balance between freshness and performance
3. **Use SQLite for large datasets**: Better performance for many cache entries
4. **Use Pickle for simplicity**: Easy to inspect cache files
5. **Handle errors gracefully**: Use `ignore_errors=True` in production
6. **Use BLOB type for complex data**: Automatically serializes dictionaries, lists, and other objects
7. **Avoid naming conflicts**: Don't use column names starting with `_cachelite_` (reserved for internal use)

## Testing

Run tests using pytest:

```bash
pytest
```

## License

MIT License

## Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

## Issues

If you encounter any issues, please report them on GitHub.
