pallas-db
v1.5.3
Published
All in the name
Downloads
107
Maintainers
Readme
PallasDB
PallasDB is a database management library supporting SQLite, PostgreSQL, MySQL, JSON files, and in-memory storage, focusing on simple key-value operations with nested key support.
Installation
npm install pallas-dbCreating an Instance
// IF ESM
import { PallasDB } from 'pallas-db';
// IF CommonJS
const { PallasDB } = require("pallas-db");
// SQLite Example
const db = new PallasDB({
dialect: 'sqlite',
filePath: './database.sqlite', // Path for SQLite
tables: ['users', 'settings'], // List of tables
enableVerbose: true, // For logging
});
// PostgreSQL Example
const pgDb = new PallasDB({
dialect: 'postgres',
login: {
host: 'localhost',
port: 5432,
username: 'myuser',
password: 'mypassword'
},
tables: ['users', 'settings'],
});
// MySQL Example
const mysqlDb = new PallasDB({
dialect: 'mysql',
login: {
host: 'localhost',
port: 3306,
username: 'myuser',
password: 'mypassword'
},
tables: ['users', 'settings'],
});
// Memory Example (New!)
const memoryDb = new PallasDB({
dialect: 'memory',
tables: ['users', 'settings'],
enableVerbose: true,
});
// JSON File Example (New!)
const jsonDb = new PallasDB({
dialect: 'json',
filePath: './data/database.json', // Optional, defaults to ./database.json
tables: ['users', 'settings'],
enableVerbose: true,
});Methods
1. get(key: string, defaultValue?: any): Promise<any>
Retrieve a value by its key.
const value = await db.get('settings.language', 'en');2. set(key: string, value: any): Promise<void>
Set a value by its key.
await db.set('settings.language', 'en');3. add(key: string, amount: number): Promise<void>
Increment a numeric value by the specified amount.
await db.add('stats.score', 10);4. sub(key: string, amount: number): Promise<void>
Decrement a numeric value by the specified amount.
await db.sub('stats.score', 5);5. delete(key: string): Promise<void>
Remove a key and its value.
await db.delete('settings.language');6. has(key: string): Promise<boolean>
Check if a key exists.
const exists = await db.has('settings.language');7. all(): Promise<Array<{ id: string; value: any }>>
Retrieve all data from the current table.
const records = await db.all();8. push(key: string, element: any): Promise<void>
Add an element to an array.
await db.push('users.favorites', 'new-item');9. pull(key: string, element: any): Promise<void>
Remove an element from an array.
await db.pull('users.favorites', 'unwanted-item');10. cache(key: string, value: any, time: number): Promise<void>
Set a temporary value that expires after the specified time.
await db.cache('temp.key', 'value', 5000); // Deletes after 5 seconds11. deleteAll(): Promise<void>
Remove all records from the current table.
await db.deleteAll();12. table(name: string): PallasDB
Switch to another table.
const settingsTable = db.table('settings');13. repair(): Promise<void>
Clean up invalid or corrupted data from the database.
await db.repair();14. forceSync(): Promise<void>
Force synchronization of database tables (recreates them).
await db.forceSync();15. getMemoryStats(): { [tableName: string]: number } | null (Memory & JSON dialects)
Get statistics about usage for each table.
const stats = db.getMemoryStats();
console.log(stats); // { users: 5, settings: 3 }Example Usage
// Set nested data
await db.set('users.anais', { age: 19, role: 'admin' });
// Get nested data
const user = await db.get('users.anais');
console.log(user.age); // 19
// Increment a nested numeric value
await db.add('users.anais.age', 1);
// Delete a nested property
await db.delete('users.anais.role');
// Work with arrays
await db.set('users.anais.hobbies', ['reading', 'coding']);
await db.push('users.anais.hobbies', 'gaming');
await db.pull('users.anais.hobbies', 'reading');
// Switch between tables
const settingsTable = db.table('settings');
await settingsTable.set('theme', 'dark');
// Check existence
if (await db.has('users.anais.email')) {
console.log('Email exists!');
}
// Get all records
const allUsers = await db.all();
console.log(allUsers);Supported Dialects
| Dialect | Description | Use Case | |---------|-------------|----------| | sqlite | Lightweight file-based database | Development, small applications | | postgres | PostgreSQL database | Production applications, complex queries | | mysql | MySQL database | Web applications, legacy systems | | memory | In-memory storage using Maps | Testing, caching, temporary data | | json | JSON file-based storage | Configuration files, simple persistence, human-readable data |
Features
✅ Nested Keys: Support for dot notation (key.subkey.value)
✅ Multiple Dialects: SQLite, PostgreSQL, MySQL, Memory, and JSON
✅ Type Safety: Full TypeScript support
✅ Automatic Validation: Built-in data validation
✅ Array Operations: Push/pull operations for arrays
✅ Temporary Storage: Cache with automatic expiration
✅ Database Repair: Automatic cleanup of invalid data
✅ Table Switching: Easy switching between tables
✅ File-based Storage: JSON and SQLite file persistence
✅ Human-readable: JSON files can be manually edited
Configuration Options
interface PallasDBOptions {
dialect: 'postgres' | 'sqlite' | 'mysql' | 'memory' | 'json';
login?: {
host?: string;
port?: number;
username?: string;
password?: string;
};
filePath?: string; // SQLite and JSON only
tables: string[];
enableVerbose?: boolean;
}Memory & JSON Dialect Benefits
The memory and JSON dialects offer several advantages:
Memory Dialect
- Ultra-fast performance: No I/O operations
- Perfect for testing: No database setup required
- Development friendly: Quick prototyping and debugging
- Session persistence: Data survives between requests (within same process)
JSON Dialect
- Human-readable: Files can be manually edited
- Version control friendly: Easy to track changes with git
- No dependencies: Works without database servers
- Cross-platform: JSON files work everywhere
- Backup friendly: Simple file copying for backups
// Memory dialect example
const memDb = new PallasDB({
dialect: 'memory',
tables: ['cache', 'sessions'],
enableVerbose: true
});
await memDb.set('user.session', { token: 'abc123', expires: Date.now() });
const stats = memDb.getMemoryStats(); // { cache: 0, sessions: 1 }
// JSON dialect example
const jsonDb = new PallasDB({
dialect: 'json',
filePath: './config/app-data.json',
tables: ['settings', 'users']
});
await jsonDb.set('settings.theme', 'dark');
// Creates/updates: ./config/app-data.jsonLicense
This project is licensed under the MIT License.
