LightDB is a lightweight database library with two interfaces for different use cases:
- LightDB - Dictionary-like key-value store (simple & flexible)
- Table - Traditional SQL tables with schemas (powerful & queryable)
Choose the one that fits your needs, or use both together!
- π― Two interfaces - Key-value store OR SQL tables
- β‘ Automatic SQL translation - No need to write SQL queries
- πΎ SQLite backend - Reliable and fast persistence
- π¦ JSON serialization - Store any JSON-serializable Python object (LightDB)
- π SQL injection protection - Parameterized queries keep your data safe
- π Auto-saving mutations - Lists and dicts automatically persist changes (LightDB)
- π Multiple tables - Organize data with separate table instances
- π Queryable - Find, filter, count records efficiently (Table)
- π§ Simple API - Get started in seconds
- β Storing configuration/settings
- β Caching data
- β Simple data structures
- β You want dict-like simplicity
- β Prototyping/small projects
- β Storing many records (users, products, posts)
- β Need to search/filter data efficiently
- β Have structured data with defined columns
- β Building production applications
- β Need traditional database features
pip install -r requirements.txtfrom lightdb import LightDB
# Create a database instance
db = LightDB()
# Set values (INSERT/UPDATE)
db['username'] = 'andrew'
db['age'] = 25
db['settings'] = {'theme': 'dark', 'notifications': True}
db['items'] = ['apple', 'banana', 'cherry']
# Get values (SELECT)
print(db['username']) # 'andrew'
print(db['settings']) # {'theme': 'dark', 'notifications': True}
# Check existence
if 'username' in db:
print("User exists!")
# Delete values (DELETE)
del db['age']
# Get with default value
email = db.get('email', 'default@example.com')
# Get database size
print(len(db)) # Number of entries
# Iterate over keys
for key in db:
print(key)
# Get all items
for key, value in db.items():
print(f"{key}: {value}")
# Update from dict
db.update({'role': 'developer', 'status': 'active'})
# Clear all entries
db.clear()from lightdb import Table
# Define table schema
users = Table('users', schema={
'id': 'TEXT PRIMARY KEY',
'username': 'TEXT NOT NULL',
'email': 'TEXT',
'role': 'TEXT DEFAULT "user"'
})
# Insert records
users.insert({
'id': 'user_001',
'username': 'andrew',
'email': 'andrew@example.com',
'role': 'admin'
})
# Insert multiple at once
users.insert_many([
{'id': 'user_002', 'username': 'fybe', 'email': 'fybe@example.com'},
{'id': 'user_003', 'username': 'alice', 'email': 'alice@example.com'}
])
# Find records
andrew = users.find_one(username='andrew')
print(andrew) # {'id': 'user_001', 'username': 'andrew', ...}
# Query records
admins = users.find(role='admin')
all_users = users.all()
# Count records
total = users.count()
admin_count = users.count(role='admin')
# Update records
users.update(
conditions={'username': 'andrew'},
updates={'email': 'new@example.com'}
)
# Delete records
users.delete(id='user_003')
# Get table size
print(len(users)) # Number of records| Feature | LightDB (Key-Value) | Table (SQL) |
|---|---|---|
| Setup | db = LightDB() |
Table('name', schema={...}) |
| Store | db['key'] = value |
table.insert({...}) |
| Retrieve | value = db['key'] |
table.find(col=val) |
| Data type | Any JSON structure | Defined columns |
| Search | Python iteration | SQL queries |
| Best for | Config, cache, simple data | Users, products, records |
| Learning curve | Easiest | Easy-Moderate |
| Flexibility | Highest | Structured |
| Scalability | Small-Medium data | Large data |
| Operation | SQL Translation | Example |
|---|---|---|
db[key] = value |
INSERT OR REPLACE INTO ... |
db['name'] = 'John' |
value = db[key] |
SELECT ... WHERE key = ? |
name = db['name'] |
del db[key] |
DELETE ... WHERE key = ? |
del db['name'] |
key in db |
SELECT 1 ... WHERE key = ? |
'name' in db |
len(db) |
SELECT COUNT(*) FROM ... |
count = len(db) |
db.get(key, default=None)- Get value with fallbackdb.keys()- List all keysdb.values()- List all valuesdb.items()- List all (key, value) pairsdb.update(dict)- Update from dictionarydb.clear()- Remove all entriesdb.close()- Close database connection
table.insert(record)- Insert a single recordtable.insert_many(records)- Insert multiple recordstable.find(**conditions)- Find all matching recordstable.find_one(**conditions)- Find first matching recordtable.all()- Get all recordstable.update(conditions, updates)- Update matching recordstable.delete(**conditions)- Delete matching recordstable.count(**conditions)- Count matching recordstable.clear()- Delete all recordstable.drop()- Drop the tablelen(table)- Get number of records
# Use custom table name
db = LightDB(table_name='my_data')
# Use custom connection
import sqlite3
conn = sqlite3.connect('my_database.db')
db = LightDB(connection=conn)Use multiple LightDB instances with different table names to organize your data:
from lightdb import LightDB
# Create separate tables for different purposes
users_db = LightDB(table_name='users')
files_db = LightDB(table_name='files')
settings_db = LightDB(table_name='settings')
# Each table operates independently
users_db['user_001'] = {'username': 'andrew', 'email': 'andrew@example.com'}
files_db['file_001'] = {'filename': 'doc.pdf', 'owner': 'user_001'}
settings_db['theme'] = {'mode': 'dark', 'color': '#007acc'}
# Tables don't interfere with each other
print(len(users_db)) # Number of users
print(len(files_db)) # Number of files
print(len(settings_db)) # Number of settingsPerfect for applications that need separate data domains:
- File sharing:
users,files,permissions - E-commerce:
products,orders,customers - CMS:
posts,comments,authors
Lists and dicts retrieved from LightDB automatically save changes:
db = LightDB()
# Lists auto-save on mutations
db['tags'] = ['python']
db['tags'].append('sqlite') # Automatically saved!
db['tags'].extend(['orm', 'database']) # Saved!
# Dicts also auto-save
db['config'] = {'theme': 'dark'}
db['config']['language'] = 'en' # Automatically saved!
# Works with nested structures
db['users'] = []
db['users'].append({'name': 'andrew', 'role': 'admin'}) # Saved!To use the LightDB CLI (command-line-interface), run:
python -m cli [ARGS]- Python 3.6+
- sqlite3 (included in Python standard library)
- PyYAML
See LICENSE file for details.