Skip to content

fybedev/lightdb

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

25 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

LightDB

LightDB is a lightweight database library with two interfaces for different use cases:

  1. LightDB - Dictionary-like key-value store (simple & flexible)
  2. Table - Traditional SQL tables with schemas (powerful & queryable)

Choose the one that fits your needs, or use both together!

Features

  • 🎯 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

Which One Should I Use?

Use LightDB (Key-Value) when:

  • βœ… Storing configuration/settings
  • βœ… Caching data
  • βœ… Simple data structures
  • βœ… You want dict-like simplicity
  • βœ… Prototyping/small projects

Use Table (SQL) when:

  • βœ… 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

Installation

pip install -r requirements.txt

Quick Start - LightDB (Key-Value Store)

from 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()

Quick Start - Table (SQL Style)

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

Comparison

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

API Reference

Basic Operations

LightDB Operations (Key-Value)

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)

LightDB Methods

  • db.get(key, default=None) - Get value with fallback
  • db.keys() - List all keys
  • db.values() - List all values
  • db.items() - List all (key, value) pairs
  • db.update(dict) - Update from dictionary
  • db.clear() - Remove all entries
  • db.close() - Close database connection

Table Methods (SQL)

  • table.insert(record) - Insert a single record
  • table.insert_many(records) - Insert multiple records
  • table.find(**conditions) - Find all matching records
  • table.find_one(**conditions) - Find first matching record
  • table.all() - Get all records
  • table.update(conditions, updates) - Update matching records
  • table.delete(**conditions) - Delete matching records
  • table.count(**conditions) - Count matching records
  • table.clear() - Delete all records
  • table.drop() - Drop the table
  • len(table) - Get number of records

Advanced Usage

# 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)

Multiple Tables

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 settings

Perfect for applications that need separate data domains:

  • File sharing: users, files, permissions
  • E-commerce: products, orders, customers
  • CMS: posts, comments, authors

Auto-Saving Mutations

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!

LightDB CLI

To use the LightDB CLI (command-line-interface), run:

python -m cli [ARGS]

Requirements

  • Python 3.6+
  • sqlite3 (included in Python standard library)
  • PyYAML

License

See LICENSE file for details.

About

Lightweight Database

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages