bangron-work/pocketdb

MongoDB-like interface to SQLite

Maintainers

Package info

github.com/bangron-work/PocketDB

pkg:composer/bangron-work/pocketdb

Statistics

Installs: 13

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 0

1.1.0 2026-01-09 19:26 UTC

This package is auto-updated.

Last update: 2026-03-09 19:53:52 UTC


README

PocketDB is a lightweight, serverless NoSQL database library for PHP, built on top of the robust SQLite engine. It combines the flexibility of JSON document storage with the reliability, speed, and ACID properties of SQLite.

Ideal for applications that need a MongoDB-like API without the overhead of maintaining a separate database server.

๐Ÿš€ Features

Core Features

  • NoSQL API: Insert, update, and query JSON documents using a MongoDB-like syntax.
  • Serverless: Runs directly on SQLite (supports both file-based and :memory: storage).
  • Event-Driven Hooks: Powerful on('beforeInsert', ...) system for validation, triggers, and logic.
  • ๐Ÿ”’ Encryption: Built-in AES-256-CBC encryption for documents.
  • Searchable Encryption: Ability to index and search specific fields even within encrypted documents.
  • Relationships: populate helper to join documents across collections or different databases.
  • Flexible IDs: Supports UUID v4, Auto-Increment Prefixes (e.g., ORD-001), or Manual IDs.
  • Advanced Querying: Rich operators ($gt, $gte, $lt, $lte, $in, $nin, $exists, $regex, $fuzzy, $has, $all, $size, $mod, $func).
  • Database Attach/Detach: Join data across multiple SQLite files.
  • Fuzzy Search: Text similarity search using Levenshtein distance.
  • Upsert Operations: Save method for insert-or-update functionality.
  • Projection: Include/exclude specific fields in query results.
  • Zero Configuration: Just require and run.

Advanced Features

  • ๐Ÿฉบ Health Monitoring: Comprehensive database health checks and metrics
  • ๐Ÿ“Š Performance Analytics: Real-time performance monitoring and optimization
  • ๐Ÿ—‚๏ธ Collection Management: Rename collections, advanced maintenance operations
  • ๐Ÿ” Enhanced Indexing: JSON field indexing for query performance
  • ๐ŸŽฃ Advanced Hooks: Robust event system with exception handling
  • ๐Ÿ› ๏ธ Admin Panel: Built-in web interface for database management
  • ๐Ÿงช Enterprise Testing: 149+ comprehensive tests covering all features

๐Ÿ“ฆ Installation

Requirements

  • PHP: 8.0 or higher
  • Extensions: pdo, pdo_sqlite, json, mbstring
  • SQLite: 3.7.11 or higher (usually included with PHP)

Via Composer (Recommended)

composer require bangron-work/pocketdb

From GitHub

# Clone the repository
git clone https://github.com/bangron-work/PocketDB.git
cd PocketDB

# Include in your project
require_once 'src/Client.php';

Admin Panel Setup

# Copy admin panel files to your web directory
cp -r admin/ /path/to/your/web/root/

# Access admin panel at: http://your-domain/admin/
# Default credentials: admin / pocketdb123

GitHub Repository: https://github.com/bangron-work/PocketDB
Documentation: Full Documentation
Version: 1.0.1
License: MIT

โšก Quick Start

Basic Usage

use PocketDB\Client;

// Initialize (creates 'my_database.sqlite' if it doesn't exist)
$client = new Client(__DIR__ . '/data');
$db = $client->my_database;

// Access a collection (table)
$users = $db->users;

// 1. Insert a document
$userId = $users->insert([
    'username' => 'johndoe',
    'email'    => 'john@example.com',
    'profile'  => [
        'age'  => 28,
        'city' => 'Jakarta'
    ]
]);

// 2. Find a document
$user = $users->findOne(['username' => 'johndoe']);

// 3. Update a document (using dot notation)
$users->update(
    ['_id' => $userId],
    ['profile.city' => 'Bandung']
);

// 4. Delete
$users->remove(['_id' => $userId]);

๐Ÿ”ฅ Advanced Features

1. Event Hooks (on)

PocketDB allows you to intercept operations. This is perfect for validation, data mutation, or triggering side effects (logging, email, etc.).

Supported events: beforeInsert, afterInsert, beforeUpdate, afterUpdate, beforeRemove, afterRemove.

// Example: Validate stock before order insertion
$db->orders->on('beforeInsert', function (&$order) use ($db) {
    $product = $db->products->findOne(['_id' => $order['product_id']]);

    // Validation
    if ($product['stock'] < $order['qty']) {
        return false; // Cancel insertion
    }

    // Mutation: Calculate total automatically
    $order['total_price'] = $product['price'] * $order['qty'];
    $order['created_at']  = date('Y-m-d H:i:s');

    return $order; // Return the modified document
});

// Example: Update ledger after successful order
$db->orders->on('afterInsert', function ($order) use ($db) {
    $db->ledger->insert([
        'description' => 'Sales Order ' . $order['_id'],
        'amount'      => $order['total_price'],
        'type'        => 'CREDIT'
    ]);
});

2. Encryption & Privacy

You can encrypt entire documents (except _id). You can also configure specific fields to be "Searchable" (hashed or plain) so you can still query them despite encryption.

// 1. Initialize with an encryption key
$db = $client->selectDB('secure_db', [
    'encryption_key' => 'your-secret-32-char-key-here'
]);

// 2. Configure searchable fields
// 'email' will be hashed (secure search, exact match only)
// 'role' will be plain text (allows LIKE/Regex search)
$db->users->setSearchableFields([
    'email' => ['hash' => true],
    'role'  => ['hash' => false]
]);

// 3. Insert (Data is stored encrypted on disk)
$db->users->insert(['email' => 'ceo@company.com', 'role' => 'admin', 'salary' => 50000]);

// 4. You can still find it!
$user = $db->users->findOne(['email' => 'ceo@company.com']);
// Output: Decrypted document

3. Relationships (Populate)

Join data from different collections (similar to SQL JOIN or Mongoose Populate).

// Assume we have 'orders' containing 'customer_id'
$orders = $db->orders->find()->toArray();

// Populate user data into 'customer_details' field
$results = $db->orders->populate(
    $orders,           // Source data
    'customer_id',     // Foreign key in 'orders'
    'users',           // Target collection name
    '_id',             // Primary key in 'users'
    'customer_details' // Output field name
);

4. Querying & Cursors

Use a fluent chainable API for advanced queries.

$results = $db->products->find([
        'price' => ['$gte' => 1000000],   // Price >= 1M
        'tags'  => ['$in' => ['promo', 'new']] // Tag is in array
    ])
    ->sort(['price' => -1]) // Sort Descending
    ->limit(10)
    ->skip(0)
    ->toArray();

Supported Operators: $eq, $gt, $gte, $lt, $lte, $in, $nin, $exists, $regex, $fuzzy, $has, $all, $size, $mod, $func.

5. ID Management

Control how _id is generated.

// Mode: Auto (Default) -> UUID v4
$db->logs->setIdModeAuto();

// Mode: Prefix -> 'TRX-000001', 'TRX-000002'
$db->orders->setIdModePrefix('TRX-');

// Mode: Manual -> You must provide '_id'
$db->users->setIdModeManual();

6. Database Attach/Detach

Join data across multiple SQLite database files.

// Attach another database
$db->attach('/path/to/other/database.sqlite', 'other_db');

// Query across databases
$sql = "SELECT * FROM main_table m
        JOIN other_db.other_table o
        ON json_extract(m.document, '$.foreign_id') = json_extract(o.document, '$._id')";

// Detach when done
$db->detach('other_db');

7. Fuzzy Search

Find documents with similar text using Levenshtein distance.

$results = $db->users->find([
    'name' => ['$fuzzy' => ['search' => 'John', 'distance' => 2, 'minScore' => 0.7]]
]);

8. Advanced Query Operators

Beyond basic operators, PocketDB supports advanced matching:

// Check if array contains value
$docs = $collection->find(['tags' => ['$has' => 'featured']]);

// Check if array contains all values
$docs = $collection->find(['permissions' => ['$all' => ['read', 'write']]]);

// Check array size
$docs = $collection->find(['tags' => ['$size' => 3]]);

// Modulo operation
$docs = $collection->find(['counter' => ['$mod' => [5, 0]]]); // counter % 5 == 0

// Custom function
$docs = $collection->find(['score' => ['$func' => function($val) {
    return $val > 50 && $val < 100;
}]]);

9. Projection

Control which fields are returned in query results.

// Include only specific fields (+ _id always included)
$users = $db->users->find()->project(['name' => 1, 'email' => 1])->toArray();

// Exclude specific fields
$users = $db->users->find()->project(['password' => 0, 'secret_notes' => 0])->toArray();

10. Upsert Operations

Insert or update documents based on existence of _id.

// Save will insert if _id doesn't exist, update if it does
$db->users->save([
    '_id' => 'user-123',  // Will update if exists
    'name' => 'Updated Name',
    'email' => 'updated@example.com'
]);

11. Health Monitoring & Metrics

Monitor database health, performance, and get optimization recommendations.

// Get comprehensive health metrics
$metrics = $db->getHealthMetrics();

// Get health report with recommendations
$report = $db->getHealthReport();

echo "Database Status: " . $report['status'] . "\n";
echo "Total Collections: " . $metrics['metrics']['total_collections'] . "\n";
echo "Total Documents: " . $metrics['metrics']['total_documents'] . "\n";

// Check integrity
$integrity = $db->checkIntegrity();
echo "Integrity Status: " . $integrity['status'] . "\n";

12. Admin Panel

PocketDB includes a built-in web admin panel for database management.

// Start admin panel (requires web server)
require_once 'admin/index.php';
// Access at: http://localhost/admin/

Features:

  • ๐Ÿ“Š Dashboard with system overview
  • ๐Ÿ—ƒ๏ธ Database and collection management
  • ๐Ÿ“ Content CRUD operations
  • ๐Ÿ–ผ๏ธ Media library management
  • โš™๏ธ System settings and configuration
  • ๐Ÿ“ˆ Real-time health monitoring
  • ๐Ÿ” Advanced search and filtering

๐Ÿ›  Architecture

  • Client: Manages the directory of database files.
  • Database: Wrapper around PDO (SQLite), handles transactions and encryption keys.
  • Collection: Handles logic, hooks, ID generation, and query building.
  • Cursor: Handles iteration, sorting, pagination, and lazy loading.

๐Ÿงช Testing & Quality Assurance

PocketDB is thoroughly tested with 149 comprehensive tests covering all features and edge cases.

Test Coverage Statistics

  • Total Tests: 149 (95 original + 54 new)
  • Total Assertions: 447
  • Coverage: 95%+ of all features
  • Test Categories:
    • โœ… Core CRUD Operations (15 tests)
    • โœ… Database Management (16 tests)
    • โœ… Query Operations (23 tests)
    • โœ… JSON Where Queries (9 tests)
    • โœ… Encryption (2 tests)
    • โœ… Relationships/Populate (6 tests)
    • โœ… Event Hooks (11 tests) - NEW
    • โœ… Fuzzy Search (8 tests) - NEW
    • โœ… JSON Indexing (8 tests) - NEW
    • โœ… Collection Management (7 tests) - NEW
    • โœ… Health Monitoring (10 tests) - NEW

Running Tests

# Run all tests
composer test

# Run specific test file
vendor/bin/phpunit tests/CollectionHooksTest.php

# Run with coverage report
vendor/bin/phpunit --coverage-html coverage/

๐Ÿ“ Project Structure

pocketdb/
โ”œโ”€โ”€ src/                    # Core library code
โ”‚   โ”œโ”€โ”€ Client.php         # Database client management
โ”‚   โ”œโ”€โ”€ Database.php       # Database operations & health monitoring
โ”‚   โ”œโ”€โ”€ Collection.php     # Collection operations & hooks
โ”‚   โ””โ”€โ”€ Cursor.php         # Query results & iteration
โ”œโ”€โ”€ admin/                  # Built-in admin panel
โ”‚   โ”œโ”€โ”€ index.php         # Admin entry point
โ”‚   โ”œโ”€โ”€ pages/            # Admin pages
โ”‚   โ”œโ”€โ”€ includes/         # Admin utilities
โ”‚   โ””โ”€โ”€ assets/           # CSS, JS, templates
โ”œโ”€โ”€ tests/                 # Comprehensive test suite
โ”‚   โ”œโ”€โ”€ CollectionHooksTest.php
โ”‚   โ”œโ”€โ”€ CollectionFuzzySearchTest.php
โ”‚   โ”œโ”€โ”€ CollectionIndexingTest.php
โ”‚   โ”œโ”€โ”€ DatabaseHealthTest.php
โ”‚   โ””โ”€โ”€ ... (149 total test files)
โ”œโ”€โ”€ docs/                  # Documentation
โ”œโ”€โ”€ examples/              # Usage examples
โ””โ”€โ”€ tools/                 # Benchmarking tools

๐Ÿ“„ License

MIT License. See LICENSE for more information.

Built with โค๏ธ using PHP and SQLite.