A Python-based hybrid database system combining SQL and NoSQL paradigms with a modern web-based admin panel
- Features
- Quick Start
- Installation
- Usage
- Authentication
- Configuration
- API Documentation
- CLI Commands
- Examples
- Project Structure
- Testing
- Security
- License
- π Hybrid Data Model - SQL tables + NoSQL collections in one database
- πΎ Custom Storage Engine - Efficient
.phdbfile format with B-Tree indexing - π Unified Query Language - Execute both SQL and MongoDB-style queries
- π REST API - Complete FastAPI backend with auto-generated docs
- π¨ Web Admin Panel - Beautiful, responsive UI for database management
- π JWT Authentication - Secure token-based authentication
- π Role-Based Access Control - Admin, user, and readonly roles
- π Real-time Statistics - Dashboard with database metrics
- π ACID Transactions - Transaction support with commit/rollback
- π¦ Import/Export - JSON and CSV format support
- πΎ Backup & Restore - Automated backup with compression and rotation
- π Audit Logging - Complete activity tracking and compliance
- π₯ User Management - Full CRUD API for user administration
- π JOIN Operations - INNER, LEFT, RIGHT, FULL OUTER joins
- π Data Visualization - Charts and statistics generation
- π PostgreSQL Migration - Import from PostgreSQL databases
- π MongoDB Migration - Import from MongoDB collections
- π Encrypted Storage - AES encryption for data at rest
- B-Tree indexing for fast lookups
- Block-based storage with checksums
- Transaction logging with ACID compliance
- Query caching and optimization
- CORS support with configurable origins
- Environment-based configuration
- Comprehensive error handling
- SQLite-based audit logging
- Automatic backup rotation
- Password-based encryption
# Create virtual environment
python -m venv venv
# Activate virtual environment
.\venv\Scripts\activate
# Install dependencies
pip install -r requirements.txt
# Install package
pip install -e .python DEMO.pypython -m pyhybriddb.cli serve
# Server runs at http://localhost:8000
# API docs at http://localhost:8000/docsOpen admin/index.html in your web browser
Default Login:
- Username:
admin - Password:
admin123
from pyhybriddb import Database
# Create database
with Database(name="my_app", path="./data") as db:
# SQL-like tables
users = db.create_table("users", {
"name": "string",
"age": "integer",
"email": "string"
})
# Insert records
users.insert({"name": "Alice", "age": 30, "email": "alice@example.com"})
# Query records
all_users = users.select()
young_users = users.select(where={"age": 25})
# Update records
users.update(where={"name": "Alice"}, updates={"age": 31})
# NoSQL-like collections
posts = db.create_collection("posts")
# Insert documents
posts.insert_one({
"title": "Hello World",
"tags": ["intro", "hello"],
"author": {"name": "Alice"}
})
# Query documents
all_posts = posts.find()
alice_posts = posts.find({"author.name": "Alice"})from pyhybriddb.core.connection import Connection
with Database("my_db") as db:
conn = Connection(db)
# CREATE TABLE
conn.execute("CREATE TABLE products (name string, price float)")
# INSERT
conn.execute("INSERT INTO products (name, price) VALUES ('Laptop', 999.99)")
# SELECT
result = conn.execute("SELECT * FROM products WHERE price > 500")
# UPDATE
conn.execute("UPDATE products SET price = 899.99 WHERE name = 'Laptop'")
conn.commit()# MongoDB-style queries
conn.execute('db.posts.insertOne({"title": "Hello", "tags": ["intro"]})')
conn.execute('db.posts.find({"tags": "intro"})')
conn.execute('db.posts.updateOne({"title": "Hello"}, {"$set": {"views": 100}})')
conn.execute('db.posts.aggregate([{"$sort": {"views": -1}}, {"$limit": 10}])')PyHybridDB uses JWT (JSON Web Token) authentication to secure the API and admin panel.
- Username:
admin - Password:
admin123
import requests
# Login
response = requests.post('http://localhost:8000/api/auth/login', json={
'username': 'admin',
'password': 'admin123'
})
data = response.json()
token = data['access_token']
# Use token for authenticated requests
headers = {'Authorization': f'Bearer {token}'}
response = requests.post(
'http://localhost:8000/api/databases',
json={'name': 'my_db'},
headers=headers
)PyHybridDB uses environment variables for configuration. After installing via pip, you can configure it in multiple ways:
Create a .env file in your project directory:
# Create .env file
touch .env # Linux/Mac
# or
New-Item .env # Windows PowerShellAdd your configuration:
SECRET_KEY=your-super-secret-key-change-this
ADMIN_PASSWORD=your-secure-password
API_PORT=8000
DEFAULT_DB_PATH=./data# Windows PowerShell
$env:SECRET_KEY = "my-secret-key"
$env:ADMIN_PASSWORD = "secure-password"
$env:API_PORT = "8080"# Linux/Mac
export SECRET_KEY="my-secret-key"
export ADMIN_PASSWORD="secure-password"
export API_PORT="8080"import os
os.environ['SECRET_KEY'] = 'my-secret-key'
os.environ['DEFAULT_DB_PATH'] = './my_data'
from pyhybriddb import Database
db = Database("my_app")# Security
SECRET_KEY=your-super-secret-key-change-this
JWT_ALGORITHM=HS256
ACCESS_TOKEN_EXPIRE_MINUTES=30
# Admin Credentials
ADMIN_USERNAME=admin
ADMIN_PASSWORD=admin123
ADMIN_EMAIL=admin@pyhybriddb.com
# API Configuration
API_HOST=0.0.0.0
API_PORT=8000
# Database
DEFAULT_DB_PATH=./data
LOG_LEVEL=INFO
CORS_ORIGINS=*python -m pyhybriddb.cli configimport secrets
print(secrets.token_urlsafe(32))from pyhybriddb.utils.backup import BackupManager
backup_mgr = BackupManager()
# Create backup
backup_file = backup_mgr.create_backup("./data/my_db.phdb", compress=True)
# List backups
backups = backup_mgr.list_backups("my_db")
# Restore backup
restored = backup_mgr.restore_backup(backup_file)
# Auto-backup with rotation
backup_mgr.auto_backup("./data/my_db.phdb", max_backups=5)from pyhybriddb.utils.audit import get_audit_logger, AuditAction
audit = get_audit_logger()
# Log action
audit.log(
action=AuditAction.CREATE_DATABASE,
user="admin",
database_name="my_db",
success=True
)
# Get logs
logs = audit.get_logs(action=AuditAction.INSERT, limit=100)
# Get statistics
stats = audit.get_statistics()from pyhybriddb.query.joins import JoinExecutor, JoinType
# Execute JOIN
result = JoinExecutor.execute_join(
left_table=users.select(),
right_table=orders.select(),
left_key="id",
right_key="user_id",
join_type=JoinType.INNER
)from pyhybriddb.migration import PostgreSQLMigration
from pyhybriddb import Database
# Connect to PostgreSQL
pg_migration = PostgreSQLMigration({
'host': 'localhost',
'port': 5432,
'database': 'mydb',
'user': 'postgres',
'password': 'password'
})
# Migrate to PyHybridDB
with Database("migrated_db") as db:
results = pg_migration.migrate_database(db)
print(f"Migrated {sum(results.values())} records")from pyhybriddb.migration import MongoDBMigration
from pyhybriddb import Database
# Connect to MongoDB
mongo_migration = MongoDBMigration({
'host': 'localhost',
'port': 27017,
'database': 'mydb'
})
# Migrate to PyHybridDB
with Database("migrated_db") as db:
results = mongo_migration.migrate_database(db)
print(f"Migrated {sum(results.values())} documents")from pyhybriddb.utils.encryption import EncryptionManager
# Setup encryption
encryption = EncryptionManager()
# Encrypt data
encrypted = encryption.encrypt_string("sensitive data")
# Decrypt data
decrypted = encryption.decrypt_string(encrypted)
# Encrypt files
encryption.encrypt_file("data.phdb", "data.phdb.encrypted")
encryption.decrypt_file("data.phdb.encrypted", "data.phdb")http://localhost:8000/api
- Swagger UI: http://localhost:8000/docs
- ReDoc: http://localhost:8000/redoc
POST /api/auth/login- Login and get JWT tokenGET /api/auth/me- Get current user info
POST /api/databases- Create databaseGET /api/databases- List databasesGET /api/databases/{name}- Get database detailsDELETE /api/databases/{name}- Delete database
POST /api/databases/{name}/backup- Create backupGET /api/databases/{name}/backups- List backupsPOST /api/databases/{name}/restore- Restore backup
GET /api/audit/logs- Get audit logs (admin only)GET /api/audit/statistics- Get audit statistics (admin only)
POST /api/users- Create user (admin only)GET /api/users- List users (admin only)GET /api/users/{username}- Get user detailsPUT /api/users/{username}- Update user (admin only)DELETE /api/users/{username}- Delete user (admin only)
GET /api/databases/{db}/tables/{table}/visualize- Generate charts
POST /api/databases/{db}/tables- Create tableGET /api/databases/{db}/tables- List tablesPOST /api/databases/{db}/tables/{table}/records- Insert recordGET /api/databases/{db}/tables/{table}/records- Get records
POST /api/databases/{db}/collections- Create collectionPOST /api/databases/{db}/collections/{coll}/documents- Insert documentGET /api/databases/{db}/collections/{coll}/documents- Get documents
POST /api/databases/{db}/query- Execute query (SQL or NoSQL)
# Create database
python -m pyhybriddb.cli create my_database
# Database info
python -m pyhybriddb.cli info my_database# Start server
python -m pyhybriddb.cli serve
# Custom host and port
python -m pyhybriddb.cli serve --host 127.0.0.1 --port 8080
# Enable auto-reload
python -m pyhybriddb.cli serve --reload# Start shell
python -m pyhybriddb.cli shell my_database
# In shell:
phdb> CREATE TABLE users (name string, age integer)
phdb> INSERT INTO users (name, age) VALUES ('Alice', 30)
phdb> SELECT * FROM users
phdb> db.posts.insertOne({"title": "Hello"})
phdb> exit# View configuration
python -m pyhybriddb.cli configfrom pyhybriddb import Database
db = Database("example_db", path="./data")
db.create()
# Create table
users = db.create_table("users", {"name": "string", "age": "integer"})
# Insert
user_id = users.insert({"name": "Alice", "age": 30})
# Select
all_users = users.select()
# Update
users.update(where={"name": "Alice"}, updates={"age": 31})
# Delete
users.delete(where={"name": "Alice"})
db.close()from pyhybriddb import Database
with Database("blog_db") as db:
posts = db.create_collection("posts")
# Insert
posts.insert_one({
"title": "My First Post",
"tags": ["intro"],
"views": 0
})
# Find
all_posts = posts.find()
intro_posts = posts.find({"tags": "intro"})
# Update
posts.update_one(
{"title": "My First Post"},
{"$inc": {"views": 1}}
)
# Aggregate
popular = posts.aggregate([
{"$sort": {"views": -1}},
{"$limit": 5}
])See examples/basic_usage.py for more examples.
D:\python_db\
βββ pyhybriddb/ # Main package
β βββ config.py # Configuration
β βββ core/ # Database core
β β βββ database.py
β β βββ table.py
β β βββ collection.py
β βββ storage/ # Storage engine
β β βββ engine.py
β β βββ file_manager.py
β β βββ index.py
β βββ query/ # Query layer
β β βββ parser.py
β β βββ sql_parser.py
β β βββ nosql_parser.py
β β βββ joins.py # β¨ JOIN operations
β βββ api/ # REST API
β β βββ server.py
β β βββ models.py
β β βββ auth.py
β β βββ users.py # β¨ User management
β βββ utils/ # Utilities
β β βββ backup.py # β¨ Backup & restore
β β βββ audit.py # β¨ Audit logging
β β βββ encryption.py # β¨ Encryption
β β βββ visualization.py # β¨ Data visualization
β β βββ serializer.py
β β βββ logger.py
β βββ migration/ # β¨ Migration tools
β β βββ postgresql.py # PostgreSQL migration
β β βββ mongodb.py # MongoDB migration
β βββ cli.py # CLI
βββ admin/ # Web admin panel
β βββ index.html
β βββ app.js
β βββ auth.js
βββ examples/ # Examples
βββ tests/ # Tests
βββ DEMO.py # Demo script
βββ config.env # Config template
βββ requirements.txt
βββ setup.py
βββ README.md # This file
# Run all tests
python -m unittest discover tests
# Run specific test
python -m unittest tests.test_database.TestDatabaseimport unittest
from pyhybriddb import Database
class TestDatabase(unittest.TestCase):
def test_create_database(self):
db = Database("test_db", path="./test_data")
db.create()
self.assertTrue(db.db_file.exists())
db.close()-
Change Default Credentials
ADMIN_PASSWORD=YourSecurePassword123!
-
Use Strong SECRET_KEY
import secrets print(secrets.token_urlsafe(32))
-
Enable HTTPS in Production
-
Restrict CORS Origins
CORS_ORIGINS=https://yourdomain.com
-
Set Appropriate Log Level
LOG_LEVEL=WARNING
- β JWT token authentication
- β Password hashing with bcrypt
- β Token expiration (30 minutes)
- β CORS protection
- β Input validation
- β Environment-based secrets
- β Audit logging for compliance
- β Encrypted storage option
All features from the original PRD have been successfully implemented!
| Feature | Status | File Location |
|---|---|---|
| Core Features | ||
| Hybrid Data Model | β Complete | core/database.py, core/table.py, core/collection.py |
| Custom Storage Engine | β Complete | storage/engine.py, storage/file_manager.py |
| B-Tree Indexing | β Complete | storage/index.py |
| SQL Query Support | β Complete | query/sql_parser.py |
| NoSQL Query Support | β Complete | query/nosql_parser.py |
| ACID Transactions | β Complete | core/database.py |
| REST API | β Complete | api/server.py |
| Web Admin Panel | β Complete | admin/index.html |
| JWT Authentication | β Complete | api/auth.py |
| CLI Tools | β Complete | cli.py |
| Environment Config | β Complete | config.py |
| Advanced Features | ||
| Backup & Restore | β Complete | utils/backup.py |
| Audit Logging | β Complete | utils/audit.py |
| User Management | β Complete | api/users.py |
| JOIN Operations | β Complete | query/joins.py |
| Data Visualization | β Complete | utils/visualization.py |
| PostgreSQL Migration | β Complete | migration/postgresql.py |
| MongoDB Migration | β Complete | migration/mongodb.py |
| Encrypted Storage | β Complete | utils/encryption.py |
| Import/Export | β Complete | admin/app.js |
Total: 20/20 Features (100%)
- Python Modules: 40+
- Lines of Code: ~10,000+
- API Endpoints: 25+
- Test Coverage: Core functionality
- Documentation: Comprehensive
β
All core features implemented
β
All advanced features implemented
β
Security features complete
β
Operational tools ready
β
Migration tools available
β
Comprehensive documentation
β
Working examples provided
β
Server tested and running
# Clone repository
git clone https://github.com/Adrient-tech/PyHybridDB.git
cd PyHybridDB
# Create virtual environment
python -m venv venv
.\venv\Scripts\activate
# Install dependencies
pip install -r requirements.txt
# Install package
pip install -e .python -m pyhybriddb.cli serveServer will start at: http://localhost:8000
- API Docs: http://localhost:8000/docs
- Admin Panel: Open
admin/index.htmlin browser - Default Login: admin / admin123
python DEMO.py- GitHub Issues: Report bugs and request features
- Documentation: See this README and inline docs
- Examples: Check
examples/directory
Contributions are welcome! Please:
- Fork the repository
- Create a feature branch
- Make your changes
- Submit a pull request
# Install dev dependencies
pip install -r requirements.txt
# Run tests
python -m unittest discover tests
# Start with auto-reload
python -m pyhybriddb.cli serve --reload- Quick Start: This README
- API Reference: http://localhost:8000/docs (when server running)
- Examples:
examples/basic_usage.py - Demo Script:
python DEMO.py - Original PRD:
project.md
MIT License
Copyright (c) 2025 Adrient.com - Developed by Infant Nirmal
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.
- Issues: Report bugs on GitHub Issues
- Documentation: See this README and
project.md - Examples: Check
examples/directory - Demo: Run
python DEMO.py
- β Core storage engine
- β Hybrid data model
- β SQL & NoSQL query support
- β REST API
- β Admin panel
- β JWT Authentication
- β CLI Tools
- β Backup & Restore
- β Audit Logging
- β User Management
- β JOIN Operations
- β Data Visualization
- β PostgreSQL Migration
- β MongoDB Migration
- β Encrypted Storage
- β Import/Export
- Multi-Factor Authentication (2FA)
- Full-Text Search
- Compound Indexes
- Advanced Query Optimization
- Replication & High Availability
- Sharding & Horizontal Scaling
- GraphQL API
- Real-time Subscriptions
- Cloud Storage Backends (S3, Azure, GCP)
- Plugin System & Extensions
Inspired by:
- PostgreSQL - Relational model
- MongoDB - Document model
- SQLite - Embedded database
- phpMyAdmin - Admin interface
- Lines of Code: ~10,000+
- Python Modules: 40+
- Total Files: 45+
- API Endpoints: 25+
- Features: 20/20 (100% Complete)
- Version: 1.0.0 (Production Ready)
- Python: 3.10+
- Platform: Cross-platform
- License: MIT
Built with β€οΈ by Infant Nirmal at Adrient.com
GitHub: https://github.com/Adrient-tech/PyHybridDB.git
Last Updated: October 25, 2025