PHPackages                             bangron-work/pocketdb - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. bangron-work/pocketdb

ActiveLibrary

bangron-work/pocketdb
=====================

MongoDB-like interface to SQLite

1.1.0(4mo ago)013↓100%MITPHPPHP &gt;=8.0CI failing

Since Dec 22Pushed 4mo agoCompare

[ Source](https://github.com/bangron-work/PocketDB)[ Packagist](https://packagist.org/packages/bangron-work/pocketdb)[ RSS](/packages/bangron-work-pocketdb/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (1)Versions (4)Used By (0)

PocketDB
========

[](#pocketdb)

**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
----------

[](#-features)

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

[](#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
--------------

[](#-installation)

### Requirements

[](#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)

[](#via-composer-recommended)

```
composer require bangron-work/pocketdb
```

### From GitHub

[](#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

[](#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:**
**Documentation:** [Full Documentation](docs/index.md)
**Version:** 1.0.1
**License:** MIT

⚡ Quick Start
-------------

[](#-quick-start)

### Basic Usage

[](#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
-------------------

[](#-advanced-features)

### 1. Event Hooks (`on`)

[](#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 &amp; Privacy

[](#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)

[](#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 &amp; Cursors

[](#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

[](#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

[](#6-database-attachdetach)

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

[](#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

[](#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

[](#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

[](#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 &amp; Metrics

[](#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

[](#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
--------------

[](#-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 &amp; Quality Assurance
---------------------------------

[](#-testing--quality-assurance)

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

### Test Coverage Statistics

[](#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

[](#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
-------------------

[](#-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
---------

[](#-license)

MIT License. See [LICENSE](https://www.google.com/search?q=LICENSE) for more information.

---

*Built with ❤️ using PHP and SQLite.*

###  Health Score

35

—

LowBetter than 80% of packages

Maintenance78

Regular maintenance activity

Popularity6

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity42

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~9 days

Total

3

Last Release

120d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/ef2f178b9b94ad5dc53a4a6569233258a0d45ac78211104ddf992a94b9a98a9b?d=identicon)[bangron-work](/maintainers/bangron-work)

---

Top Contributors

[![bangron-work](https://avatars.githubusercontent.com/u/248205217?v=4)](https://github.com/bangron-work "bangron-work (15 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/bangron-work-pocketdb/health.svg)

```
[![Health](https://phpackages.com/badges/bangron-work-pocketdb/health.svg)](https://phpackages.com/packages/bangron-work-pocketdb)
```

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
