Skip to main content

A dict-like SQLite wrapper with APSW for instant persistence and memory caching

Project description

NanaSQLite

PyPI version Python versions License: MIT Downloads Tests

A dict-like SQLite wrapper with instant persistence and intelligent caching.

English | 日本語


English

🚀 Features

  • Dict-like Interface: Use familiar db["key"] = value syntax
  • Instant Persistence: All writes are immediately saved to SQLite
  • Smart Caching: Lazy load (on-access) or bulk load (all at once)
  • Nested Structures: Full support for nested dicts and lists (up to 30+ levels)
  • High Performance: WAL mode, mmap, and batch operations for maximum speed
  • Security & Stability (v1.2.0): SQL validation, ReDoS protection, and strict connection management
  • Zero Configuration: Works out of the box with sensible defaults

📦 Installation

pip install nanasqlite

⚡ Quick Start

from nanasqlite import NanaSQLite

# Create or open a database
db = NanaSQLite("mydata.db")

# Use it like a dict
db["user"] = {"name": "Nana", "age": 20, "tags": ["admin", "active"]}
print(db["user"])  # {'name': 'Nana', 'age': 20, 'tags': ['admin', 'active']}

# Data persists automatically
db.close()

# Reopen later - data is still there!
db = NanaSQLite("mydata.db")
print(db["user"]["name"])  # 'Nana'

🔧 Advanced Usage

# Bulk load for faster repeated access
db = NanaSQLite("mydata.db", bulk_load=True)

# Batch operations for high-speed reads/writes
db.batch_update({"k1": "v1", "k2": "v2"})
results = db.batch_get(["k1", "k2"])

# Context manager support
with NanaSQLite("mydata.db") as db:
    db["temp"] = "value"

📚 Documentation

✨ v1.3.0 New Features

Flexible Cache Strategies:

from nanasqlite import NanaSQLite, CacheType

# Default: Unbounded cache (same as before)
db = NanaSQLite("app.db")

# LRU cache: Keep only latest N items (memory-efficient)
db = NanaSQLite("app.db", cache_strategy=CacheType.LRU, cache_size=1000)

# Per-table settings
logs = db.table("logs", cache_strategy=CacheType.LRU, cache_size=100)

# Speed boost: Install optional C extension
# pip install nanasqlite[speed]

✨ v1.2.0 New Features

Security Enhancements & Strict Connection Management:

# v1.2.0 Security Features
db = NanaSQLite("mydata.db", 
    strict_sql_validation=True,  # Disallow unauthorized SQL functions
    max_clause_length=500        # Limit SQL length to prevent ReDoS
)

# v1.2.0 Read-Only Connection Pool (Async only)
async with AsyncNanaSQLite("mydata.db", read_pool_size=5) as db:
    # Heavy read operations (query, fetch_all) use the pool automatically
    # allowing parallel execution without blocking writes or other reads
    results = await asyncio.gather(
        db.query("logs", where="level=?", parameters=("ERROR",)),
        db.query("logs", where="level=?", parameters=("INFO",)),
        db.query("logs", where="level=?", parameters=("WARN",))
    )

# Strict Connection Management
with db.transaction():
    sub_db = db.table("sub")
    # ... operations ...
db.close()
# Accessing sub_db now raises NanaSQLiteClosedError for safety!

Read Secure Development Guide ↗

✨ v1.1.0 New Features

Safely operate multiple tables in the same database with shared connections:

from nanasqlite import NanaSQLite

# Create main table instance
main_db = NanaSQLite("mydata.db", table="users")

# Get another table instance sharing the same connection
products_db = main_db.table("products")
orders_db = main_db.table("orders")

# Each table has isolated cache and operations
main_db["user1"] = {"name": "Alice", "email": "alice@example.com"}
products_db["prod1"] = {"name": "Laptop", "price": 999}
orders_db["order1"] = {"user": "user1", "product": "prod1"}

Transaction Support & Error Handling (v1.1.0+):

from nanasqlite import NanaSQLite, NanaSQLiteTransactionError

with db.transaction():
    db["key1"] = "value1"
    db["key2"] = "value2"

Explore Multi-table & Transactions ↗

✨ v1.0.3+ Legacy Features

Pydantic Support & Direct SQL:

# Pydantic support
db.set_model("user", User(name="Nana", age=20))

# Direct SQL execution
db.execute("SELECT * FROM data WHERE key LIKE ?", ("user%",))

# 22 new SQLite wrapper functions (sql_insert, sql_update, count, etc.)
db.sql_insert("users", {"name": "Alice", "age": 25})



日本語

🚀 特徴

  • dict風インターフェース: おなじみの db["key"] = value 構文で操作
  • 即時永続化: 書き込みは即座にSQLiteに保存
  • スマートキャッシュ: 遅延ロード(アクセス時)または一括ロード(起動時)
  • ネスト構造対応: 30階層以上のネストしたdict/listをサポート
  • 高性能: WALモード、mmap、バッチ操作で最高速度を実現
  • セキュリティと安定性 (v1.2.0): SQL検証、ReDoS対策、厳格な接続管理を導入
  • 設定不要: 合理的なデフォルト設定でそのまま動作

📦 インストール

pip install nanasqlite

⚡ クイックスタート

from nanasqlite import NanaSQLite

# データベースを作成または開く
db = NanaSQLite("mydata.db")

# dictのように使う
db["user"] = {"name": "Nana", "age": 20, "tags": ["admin", "active"]}
print(db["user"])  # {'name': 'Nana', 'age': 20, 'tags': ['admin', 'active']}

# データは自動的に永続化
db.close()

# 後で再度開いても、データはそのまま!
db = NanaSQLite("mydata.db")
print(db["user"]["name"])  # 'Nana'

🔧 高度な使い方

# 一括ロードで繰り返しアクセスを高速化
db = NanaSQLite("mydata.db", bulk_load=True)

# バッチ操作で高速な読み書き
db.batch_update({"k1": "v1", "k2": "v2"})
results = db.batch_get(["k1", "k2"])

# コンテキストマネージャ対応
with NanaSQLite("mydata.db") as db:
    db["temp"] = "value"

📚 ドキュメント

✨ v1.3.0 新機能

柔軟なキャッシュ戦略:

from nanasqlite import NanaSQLite, CacheType

# デフォルト: 無制限キャッシュ(従来動作)
db = NanaSQLite("app.db")

# LRUキャッシュ: 最新N件のみ保持(省メモリ)
db = NanaSQLite("app.db", cache_strategy=CacheType.LRU, cache_size=1000)

# テーブル別設定
logs = db.table("logs", cache_strategy=CacheType.LRU, cache_size=100)

# 高速化: オプションのC拡張をインストール
# pip install nanasqlite[speed]

✨ v1.2.0 新機能

セキュリティ強化と厳格な接続管理:

# v1.2.0 セキュリティ機能
db = NanaSQLite("mydata.db", 
    strict_sql_validation=True,  # 未許可のSQL関数を禁止
    max_clause_length=500        # SQLの長さを制限してReDoSを防止
)

# v1.2.0 読み取り専用接続プール(非同期のみ)
async with AsyncNanaSQLite("mydata.db", read_pool_size=5) as db:
    # 重い読み取り操作(query, fetch_all)は自動的にプールを使用
    results = await asyncio.gather(
        db.query("logs", where="level=?", parameters=("ERROR",)),
        db.query("logs", where="level=?", parameters=("INFO",))
    )

# 厳格な接続管理
db.close()
# 無効化されたインスタンスへのアクセスは NanaSQLiteClosedError を送出します。

セキュリティ詳細を見る ↗

✨ v1.1.0 新機能

同一データベース内の複数テーブルを接続共有で安全に操作:

from nanasqlite import NanaSQLite

# メインテーブルインスタンスを作成
main_db = NanaSQLite("mydata.db", table="users")

# 同じ接続を共有する別のテーブルインスタンスを取得
products_db = main_db.table("products")
orders_db = main_db.table("orders")

# 各テーブルは独立したキャッシュと操作を持つ
main_db["user1"] = {"name": "Alice"}
products_db["prod1"] = {"name": "Laptop"}

トランザクションサポートとエラーハンドリング (v1.1.0+):

from nanasqlite import NanaSQLite, NanaSQLiteTransactionError

with db.transaction():
    db["key1"] = "value1"
    db["key2"] = "value2"

マルチテーブルと非同期を詳しく ↗

✨ v1.0.3+ レガシー機能

Pydantic互換性と直接SQL実行:

# Pydantic互換性
db.set_model("user", User(name="Nana", age=20))

# 直接SQL実行
db.execute("SELECT * FROM data WHERE key LIKE ?", ("user%",))

# 22種類のSQLiteラッパー関数 (sql_insert, sql_update, count等)
db.sql_insert("users", {"name": "Alice", "age": 25})


License

MIT License - see LICENSE for details.

Project details


Release history Release notifications | RSS feed

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

nanasqlite-1.3.0.dev1.tar.gz (84.6 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

nanasqlite-1.3.0.dev1-py3-none-any.whl (41.7 kB view details)

Uploaded Python 3

File details

Details for the file nanasqlite-1.3.0.dev1.tar.gz.

File metadata

  • Download URL: nanasqlite-1.3.0.dev1.tar.gz
  • Upload date:
  • Size: 84.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for nanasqlite-1.3.0.dev1.tar.gz
Algorithm Hash digest
SHA256 6894dd0f7cf10b63f4e176710199f45b9b25215da1558cc34631f94932044d59
MD5 f6cadf052c7881a6db3af6b3a49c3f48
BLAKE2b-256 2bdbdf90887b1c66ea974cf438d9b760ea1994548fcef7bc61a00ef88450ba28

See more details on using hashes here.

Provenance

The following attestation bundles were made for nanasqlite-1.3.0.dev1.tar.gz:

Publisher: ci.yml on disnana/NanaSQLite

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file nanasqlite-1.3.0.dev1-py3-none-any.whl.

File metadata

File hashes

Hashes for nanasqlite-1.3.0.dev1-py3-none-any.whl
Algorithm Hash digest
SHA256 3e20b1bbdc04d1c7dadf7b3cea145e05af710710e0fec5c224e215e5a24cbc11
MD5 ec9be1578947f4e50a05910548ca3c89
BLAKE2b-256 a26b763f85c84fb58d86919037bb96aba3d8b39cd611c1bf9a9c18bc34ffb3ab

See more details on using hashes here.

Provenance

The following attestation bundles were made for nanasqlite-1.3.0.dev1-py3-none-any.whl:

Publisher: ci.yml on disnana/NanaSQLite

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page