A dict-like SQLite wrapper with APSW for instant persistence and memory caching
Project description
NyanSQLite
Pythonic SQLite with Pydantic models, Django-like queries, and FTS5 full-text search.
日本語
NyanSQLiteは、Pydanticモデルをそのままデータベーススキーマとして利用できる、型安全で高性能なSQLiteラッパーです。
複雑なSQLを書くことなく、Pythonの型ヒントと直感的なクエリでデータを管理できます。
🚀 主な特徴
| 機能 | 説明 |
|---|---|
| Pydanticベースのスキーマ | 型ヒントで自動バリデーション、JSON変換も透過的 |
| Djangoライクなクエリ | __gte, __in, __like など直感的なフィルタリング |
| FTS5全文検索 | テキストデータから高速に検索結果を取得 |
| 自動インデックス管理 | Indexed[T] アノテーションで B-tree インデックスを自動構築 |
| 複雑な型を透過的に処理 | dict や list を JSON で保存、自動で Python オブジェクトに戻す |
| パフォーマンス最適化 | WAL モード、バッチ処理による高速化 |
📦 インストール
pip install nyansqlite
Pydantic v2が必須です:
pip install "pydantic>=2.0"
⚡ 5分クイックスタート
from pydantic import BaseModel
from nyansqlite import NyanSQLite, Indexed, Searchable
# 1️⃣ スキーマ定義(型ヒント+Pydantic)
class Article(BaseModel):
id: int # idフィールドが自動的に主キーになる
author: Indexed[str] # インデックス付きカラム
title: Searchable[str] # 全文検索対象
body: Searchable[str] # 全文検索対象
views: int = 0
# 2️⃣ DB初期化&テーブル作成
db = NyanSQLite("blog.db")
db.register(Article)
# 3️⃣ データ挿入
db.insert(Article(
id=1,
author="neko",
title="SQLiteを使いこなそう",
body="NyanSQLiteで簡単にデータ管理ができます。"
))
# 4️⃣ クエリ実行(Django風)
articles = db.query(Article, author="neko", views__gte=0, order_by="id", desc=True)
# 5️⃣ 全文検索(FTS5)
results = db.search(Article, "SQLite")
for hit in results:
print(f"✨ {hit.title}")
db.close()
🔍 クエリ演算子リファレンス
# 完全一致
db.query(Article, author="neko")
# 演算子フィルタ
db.query(Article,
views__gt=10, # >
views__gte=10, # >=
views__lt=100, # <
views__lte=100, # <=
views__ne=50, # !=
)
# 文字列フィルタ
db.query(Article,
title__like="%Python%", # LIKE検索
)
# IN句
db.query(Article,
id__in=[1, 2, 3],
)
# NULL チェック
db.query(Article,
author__is_null=False,
)
🎯 実装例:ゲームのプレイヤーシステム
from datetime import datetime
from pydantic import BaseModel
class Player(BaseModel):
player_id: int # 主キー
username: Indexed[str] # ユーザー名でインデックス
level: Indexed[int] # レベルでインデックス
score: int = 0
created_at: datetime
db = NyanSQLite("game.db")
db.register(Player)
# バッチ登録(大量データが高速)
players = [
Player(player_id=i, username=f"player_{i}", level=i%50, created_at=datetime.now())
for i in range(1, 1001)
]
db.insert_many(players)
# ランキング取得
top_players = db.query(Player, order_by="score", desc=True, limit=10)
# 条件付き検索&更新
high_level = db.query(Player, level__gte=40, limit=100)
db.update(Player, where={"player_id": 1}, score=9999)
# 数を数える
player_count = db.count(Player)
active_count = db.count(Player, level__gte=30)
📊 パフォーマンス
NyanSQLiteは以下の最適化を実装しています:
- WAL モード: 読み書き同時実行性の向上
- トランザクション:
insert_many()はデフォルトでトランザクション内で実行 - パラメータ化クエリ: SQL インジェクション対策も兼ねた安全性
# 10万件をわずか0秒台で挿入(バッチ処理)
import time
players = [Player(player_id=i, ...) for i in range(100000)]
start = time.time()
db.insert_many(players)
print(f"Inserted in {time.time() - start:.4f}s") # 例: 0.3456s
🛠️ 高度な機能
複合インデックス
from nyansqlite import CompositeIndex
class Order(BaseModel):
__nyan_indexes__ = [
CompositeIndex("user_id", "created_at"),
CompositeIndex("product_id", "status", unique=True),
]
id: int
user_id: int
product_id: int
created_at: datetime
status: str
主キーのカスタマイズ
フィールド名が id でない場合:
class User(BaseModel):
__nyan_primary_key__ = "user_id"
user_id: int
email: str
name: str
コンテキストマネージャー
with NyanSQLite("app.db") as db:
db.register(Article)
db.insert(Article(...))
# 自動的にcloseされる
🧹 メンテナンス
# インデックスの再構築
db.rebuild_fts(Article)
# データベース最適化(ファイルサイズを縮小)
db.vacuum()
# 存在確認
if db.exists(Article, id=1):
print("Found!")
# 部分取得(カラムを指定)
titles = db.select(Article, ["title", "author"], views__gte=100)
🚨 型モデルのベストプラクティス
from pydantic import ConfigDict
class Article(BaseModel):
# Pydantic v2の設定
model_config = ConfigDict(
arbitrary_types_allowed=True, # 複雑な型をサポート
validate_assignment=True,
)
id: int
# ... その他フィールド
English
NyanSQLite is a type-safe, high-performance SQLite wrapper that transforms Pydantic models directly into database schemas. Write minimal SQL while leveraging the power of FTS5 full-text search and Django-inspired query syntax.
🚀 Features
| Feature | Benefit |
|---|---|
| Pydantic Integration | Type-safe validation and automatic JSON serialization |
| Django-like Queries | __gte, __in, __like and more—no SQL needed |
| FTS5 Search | Lightning-fast full-text search on Searchable[str] fields |
| Auto-Indexing | Create B-tree indexes with Indexed[T] annotations |
| Complex Types | Transparent handling of dict, list, and custom types |
| Performance Optimized | WAL mode, batch inserts, parameterized queries |
📦 Installation
pip install nyansqlite
Requires Python 3.9+ and Pydantic 2.0+.
⚡ Quick Start
from pydantic import BaseModel
from nyansqlite import NyanSQLite, Indexed, Searchable
class Post(BaseModel):
id: int
title: Searchable[str]
author: Indexed[str]
views: int = 0
db = NyanSQLite(":memory:")
db.register(Post)
# Insert
db.insert(Post(id=1, title="Hello SQLite", author="neko"))
# Query
posts = db.query(Post, author="neko", views__gte=0)
# Full-text search
results = db.search(Post, "SQLite")
db.close()
📚 API Reference
Core Methods:
register(model)– Introspect model and create tableinsert(obj)– Insert a single recordinsert_many(objs)– Bulk insert with transactionquery(**kwargs)– SELECT with filters, ordering, paginationsearch(query, limit)– FTS5 full-text searchget(**kwargs)– Fetch one record or Noneupdate(where, **fields)– Partial UPDATEdelete(**kwargs)– Conditional DELETEcount(**kwargs)– COUNT rows matching conditionexists(**kwargs)– Check if any row matchesselect(fields, **kwargs)– Fetch specific columns as dictsvacuum()– Optimize database fileclose()– Close connection
🔗 Resources
- Repository: github.com/disnana/nyansqlite
- Issues: Report bugs
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
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file nyansqlite-1.0.0.dev1.tar.gz.
File metadata
- Download URL: nyansqlite-1.0.0.dev1.tar.gz
- Upload date:
- Size: 22.6 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.13
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
3f1d3d51a6d458804528fdb0b74f5121b6481c3dca52ce778f3402c3edb84f72
|
|
| MD5 |
5d166fd4d649d14553c38c94b75ba873
|
|
| BLAKE2b-256 |
960fba864b940ec0d860d598a75b2e293277431ddf10946079fa8f599edc3eda
|
Provenance
The following attestation bundles were made for nyansqlite-1.0.0.dev1.tar.gz:
Publisher:
ci.yml on disnana/NyanSQLite
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
nyansqlite-1.0.0.dev1.tar.gz -
Subject digest:
3f1d3d51a6d458804528fdb0b74f5121b6481c3dca52ce778f3402c3edb84f72 - Sigstore transparency entry: 1546983219
- Sigstore integration time:
-
Permalink:
disnana/NyanSQLite@17d05312e6072310528a4756f7124e92ba311fd9 -
Branch / Tag:
refs/heads/main - Owner: https://github.com/disnana
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
ci.yml@17d05312e6072310528a4756f7124e92ba311fd9 -
Trigger Event:
push
-
Statement type:
File details
Details for the file nyansqlite-1.0.0.dev1-py3-none-any.whl.
File metadata
- Download URL: nyansqlite-1.0.0.dev1-py3-none-any.whl
- Upload date:
- Size: 19.5 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.13
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
672e3b650280614b667180c7ba7ae1b067563b4ef317114e6eddbb656c6e9775
|
|
| MD5 |
72072f104da4f91d4b40c5ced4dfcea3
|
|
| BLAKE2b-256 |
dcd7b6d42d6571fa5ef9c5778eff5514d265f23138cae4ea27a99e1eeb8545ae
|
Provenance
The following attestation bundles were made for nyansqlite-1.0.0.dev1-py3-none-any.whl:
Publisher:
ci.yml on disnana/NyanSQLite
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
nyansqlite-1.0.0.dev1-py3-none-any.whl -
Subject digest:
672e3b650280614b667180c7ba7ae1b067563b4ef317114e6eddbb656c6e9775 - Sigstore transparency entry: 1546983227
- Sigstore integration time:
-
Permalink:
disnana/NyanSQLite@17d05312e6072310528a4756f7124e92ba311fd9 -
Branch / Tag:
refs/heads/main - Owner: https://github.com/disnana
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
ci.yml@17d05312e6072310528a4756f7124e92ba311fd9 -
Trigger Event:
push
-
Statement type: