matsushibadb
v1.0.9
Published
MatsushibaDB - Next-Generation SQL Database with Local Support, Caching, and Async/Await
Maintainers
Readme
MatsushibaDB - Enhanced Node.js Client
Version 1.0.9 Next-Generation SQL Database with Local Support, Caching, and Async/Await
🚀 Features
✨ Local Database Support
- Standalone Database Integration - Use MatsushibaDB directly in your application
- No Server Required - Perfect for desktop apps, mobile apps, and embedded systems
- Hybrid Mode - Try local first, fallback to remote server
- Optimized Performance - WAL mode, optimized cache settings, foreign key support
- File Encryption - AES-256-GCM encryption for all database files
- Custom Format -
.msdbfiles with complete SQLite abstraction
⚡ Advanced Caching
- Intelligent Query Caching - Automatic caching of SELECT queries
- Configurable TTL - Customizable cache expiration times
- LRU Eviction - Smart memory management
- Cache Statistics - Monitor cache performance
🔄 Async/Await Support
- Native Promise Support - Full async/await compatibility
- Error Handling - Comprehensive error management
- Transaction Support - ACID-compliant transactions
- Connection Pooling - Optimized connection management
⚙️ Flexible Configuration
- Multiple Modes - Local, Remote, Hybrid operation
- Custom Settings - Fine-tune performance and behavior
- Environment Variables - Easy deployment configuration
- Runtime Configuration - Dynamic settings adjustment
📦 Installation
# Install globally
npm install -g matsushibadb
# Install locally
npm install matsushibadb
# Install with all dependencies
npm install matsushibadb --save🎯 Quick Start
Local Database Mode
const { MatsushibaDBClient } = require('matsushibadb');
// Create local database client
const db = new MatsushibaDBClient({
mode: 'local',
database: './myapp.db',
cache: {
enabled: true,
ttl: 300000, // 5 minutes
maxSize: 1000
}
});
async function main() {
await db.initialize();
// Create table
await db.execute(`
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
email TEXT UNIQUE
)
`);
// Insert data
await db.execute(
'INSERT INTO users (name, email) VALUES (?, ?)',
['John Doe', '[email protected]']
);
// Query with caching
const users = await db.execute('SELECT * FROM users');
console.log(users.rows);
await db.close();
}
main().catch(console.error);Remote Server Mode
const { MatsushibaDBClient } = require('matsushibadb');
// Create remote client
const db = new MatsushibaDBClient({
mode: 'remote',
protocol: 'http',
host: 'localhost',
port: 8000,
apiKey: 'your-api-key',
cache: {
enabled: true,
ttl: 60000 // 1 minute
}
});
async function main() {
await db.initialize();
// Execute queries
const result = await db.execute('SELECT * FROM products WHERE price > ?', [100]);
console.log(result.rows);
await db.close();
}
main().catch(console.error);Hybrid Mode (Local + Remote)
const { MatsushibaDBClient } = require('matsushibadb');
// Create hybrid client
const db = new MatsushibaDBClient({
mode: 'hybrid',
database: './local.db',
protocol: 'http',
host: 'api.matsushiba.co',
port: 8000,
apiKey: 'your-api-key',
cache: {
enabled: true,
ttl: 300000
}
});
async function main() {
await db.initialize();
// Will try local first, fallback to remote
const result = await db.execute('SELECT * FROM users WHERE active = ?', [true]);
console.log(result.rows);
await db.close();
}
main().catch(console.error);🔧 Configuration Options
Client Configuration
const db = new MatsushibaDBClient({
// Mode selection
mode: 'local' | 'remote' | 'hybrid',
// Local database settings
database: './app.db',
// Remote connection settings
protocol: 'http' | 'https' | 'tcp',
host: 'localhost',
port: 8000,
apiKey: 'your-api-key',
timeout: 30000,
// Cache configuration
cache: {
enabled: true,
ttl: 300000, // Cache TTL in milliseconds
maxSize: 1000 // Maximum cache entries
},
// Flexible configuration
config: {
local: {
journalMode: 'WAL',
synchronous: 'NORMAL',
cacheSize: -2000,
mmapSize: 268435456,
busyTimeout: 30000,
foreignKeys: true
},
remote: {
retries: 3,
retryDelay: 1000,
keepAlive: true,
compression: true
},
performance: {
connectionPooling: true,
maxConnections: 10,
queryTimeout: 30000
}
}
});📊 Advanced Features
Transaction Support
// Local transactions
const statements = [
{ sql: 'INSERT INTO users (name) VALUES (?)', params: ['Alice'] },
{ sql: 'INSERT INTO users (name) VALUES (?)', params: ['Bob'] },
{ sql: 'UPDATE users SET status = ? WHERE name = ?', params: ['active', 'Alice'] }
];
const results = await db.transaction(statements);
console.log('Transaction completed:', results);Cache Management
// Get cache statistics
const stats = db.getCacheStats();
console.log('Cache stats:', stats);
// Clear cache
db.clearCache();
// Disable cache for specific query
const result = await db.execute('SELECT * FROM users', [], { useCache: false });Error Handling
try {
await db.execute('SELECT * FROM non_existent_table');
} catch (error) {
if (error.message.includes('no such table')) {
console.log('Table does not exist, creating...');
await db.execute('CREATE TABLE non_existent_table (id INTEGER)');
} else {
console.error('Database error:', error.message);
}
}🏭 Factory Functions
Quick Client Creation
const {
createLocalClient,
createRemoteClient,
createHybridClient,
Local,
Remote,
Hybrid
} = require('matsushibadb');
// Using factory functions
const localDb = createLocalClient({ database: './app.db' });
const remoteDb = createRemoteClient({ host: 'api.example.com', port: 8000 });
const hybridDb = createHybridClient({ database: './local.db', host: 'api.example.com' });
// Using convenience exports
const localDb2 = Local({ database: './app.db' });
const remoteDb2 = Remote({ host: 'api.example.com', port: 8000 });
const hybridDb2 = Hybrid({ database: './local.db', host: 'api.example.com' });🖥️ CLI Usage
Local Mode
# Create local database and execute query
matsushiba-db local "CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)"
matsushiba-db local "INSERT INTO users (name) VALUES ('John')"
matsushiba-db local "SELECT * FROM users"Remote Mode
# Connect to remote server
matsushiba-db remote --protocol http --host localhost --port 8000 --api-key secret "SELECT * FROM users"Hybrid Mode
# Try local first, fallback to remote
matsushiba-db hybrid --database ./app.db --host api.example.com --port 8000 "SELECT * FROM products"Cache Options
# Enable caching with custom settings
matsushiba-db local --cache-enabled --cache-ttl 60000 --cache-max-size 500 "SELECT * FROM users"🔍 Performance Optimization
Local Database Tuning
const db = new MatsushibaDBClient({
mode: 'local',
database: './optimized.db',
config: {
local: {
journalMode: 'WAL', // Write-Ahead Logging
synchronous: 'NORMAL', // Balanced safety/performance
cacheSize: -2000, // 2MB cache
mmapSize: 268435456, // 256MB memory mapping
busyTimeout: 30000, // 30 second timeout
foreignKeys: true // Enable foreign key constraints
}
}
});Cache Optimization
const db = new MatsushibaDBClient({
cache: {
enabled: true,
ttl: 300000, // 5 minutes for most queries
maxSize: 1000 // Adjust based on memory usage
}
});
// Use cache for read-heavy operations
const users = await db.execute('SELECT * FROM users WHERE active = ?', [true]);
// Disable cache for real-time data
const liveData = await db.execute('SELECT * FROM live_updates', [], { useCache: false });🛠️ Development
Project Initialization
# Initialize new MatsushibaDB project
matsushiba-db init my-project
# This creates:
# - my-project/
# - package.json
# - src/
# - database.js
# - models/
# - config/
# - database.jsonEnvironment Configuration
# Set environment variables
export MATSUSHIBA_MODE=local
export MATSUSHIBA_DATABASE=./app.db
export MATSUSHIBA_CACHE_TTL=300000
export MATSUSHIBA_CACHE_MAX_SIZE=1000📈 Monitoring & Debugging
Connection Status
// Check if client is connected
if (db.isConnected()) {
console.log('Database connected');
} else {
console.log('Database not connected');
}
// Get server information
const info = await db.getServerInfo();
console.log('Server info:', info);Cache Statistics
const stats = db.getCacheStats();
console.log(`
Cache Statistics:
- Size: ${stats.size}/${stats.maxSize}
- TTL: ${stats.ttl}ms
- Enabled: ${stats.enabled}
`);🔒 Security Features
Local Database Security
const db = new MatsushibaDBClient({
mode: 'local',
database: './secure.db',
config: {
local: {
foreignKeys: true, // Enable foreign key constraints
synchronous: 'FULL' // Maximum data safety
}
}
});Remote Connection Security
const db = new MatsushibaDBClient({
mode: 'remote',
protocol: 'https',
host: 'secure-api.example.com',
port: 8443,
apiKey: process.env.MATSUSHIBA_API_KEY,
ssl: {
rejectUnauthorized: true,
ca: fs.readFileSync('./ca-cert.pem')
}
});📚 Examples
Express.js Integration
const express = require('express');
const { MatsushibaDBClient } = require('matsushibadb');
const app = express();
const db = new MatsushibaDBClient({
mode: 'local',
database: './api.db',
cache: { enabled: true, ttl: 60000 }
});
app.get('/api/users', async (req, res) => {
try {
const result = await db.execute('SELECT * FROM users WHERE active = ?', [true]);
res.json(result.rows);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
app.listen(3000);React Native Integration
import { MatsushibaDBClient } from 'matsushibadb';
const db = new MatsushibaDBClient({
mode: 'local',
database: './mobile.db',
cache: { enabled: true, ttl: 300000 }
});
export const DatabaseService = {
async initialize() {
await db.initialize();
},
async getUsers() {
const result = await db.execute('SELECT * FROM users');
return result.rows;
},
async createUser(name, email) {
const result = await db.execute(
'INSERT INTO users (name, email) VALUES (?, ?)',
[name, email]
);
return result.lastID;
}
};🆘 Troubleshooting
Common Issues
Database Engine Not Available
# Install database engine
npm install matsushibadb
# Or use without local features
const db = new MatsushibaDBClient({ mode: 'remote' });Cache Memory Issues
// Reduce cache size
const db = new MatsushibaDBClient({
cache: {
enabled: true,
maxSize: 100, // Reduce from default 1000
ttl: 60000 // Reduce TTL
}
});Connection Timeouts
// Increase timeout
const db = new MatsushibaDBClient({
timeout: 60000, // 60 seconds
config: {
remote: {
retries: 5,
retryDelay: 2000
}
}
});📞 Support
- Documentation: https://db.matsushiba.co/docs
- API Reference: https://db.matsushiba.co/api
- Support Email: [email protected]
- Website: https://www.matsushiba.co
📄 License
This software is licensed under the Matsushiba Proprietary License. See LICENSE for details.
© 2025 Matsushiba Foundation. All rights reserved.
MatsushibaDB Enhanced Client - Local database support with caching and async/await
