bigbasealpha
Version:
Enterprise-Grade NoSQL Database System with Modular Logger & Offline HSM Security - Complete database platform with professional text-based logging, encryption, caching, indexing, JWT authentication, auto-generated REST API, real-time dashboard, and maste
413 lines (334 loc) ⢠15.1 kB
JavaScript
#!/usr/bin/env node
/**
* BigBaseAlpha v1.4.0 - Collection System & Performance Demo
* Demonstrates MongoDB-style collections and lazy write performance
*/
import BigBaseAlpha from '../src/alpha.js';
console.log('š BigBaseAlpha v1.4.0 - Collection System & Performance Demo');
console.log('ā'.repeat(65));
async function demonstrateCollections() {
const db = new BigBaseAlpha({
path: './DEMO_COLLECTIONS_DATA',
encryption: false,
apiGateway: { enabled: false },
security: { paranoidLogging: false }
});
try {
await db.init();
console.log('ā
Database initialized\n');
// =====================================================
// PART 1: MongoDB-Style Collections
// =====================================================
console.log('š PART 1: MongoDB-Style Collection System');
console.log('ā'.repeat(50));
// Get collections (auto-created)
const users = db.collection('users');
const logs = db.collection('logs');
const products = db.collection('products');
console.log('ā
Collections created:', db.listCollections());
// Insert documents
console.log('\nš Inserting documents...');
const user1 = await users.insert({
id: 1,
name: "Ahmet",
email: "ahmet@example.com",
age: 25,
city: "Istanbul"
});
const user2 = await users.insert({
id: 2,
name: "Fatma",
email: "fatma@example.com",
age: 30,
city: "Ankara"
});
await logs.insert({
type: "info",
message: "User logged in",
date: "2025-08-03",
userId: 1
});
await logs.insert({
type: "error",
message: "Connection failed",
date: "2025-08-02",
userId: 2
});
await logs.insert({
type: "warning",
message: "Disk space low",
date: "2025-08-01"
});
console.log('ā
Documents inserted');
// =====================================================
// PART 2: Advanced MongoDB-Style Queries
// =====================================================
console.log('\nš PART 2: Advanced Query System');
console.log('ā'.repeat(50));
// Basic find
console.log('\nš Basic queries:');
const allUsers = users.find();
console.log(`š Total users: ${allUsers.length}`);
const ahmet = users.findOne({ name: "Ahmet" });
console.log(`š¤ Found user: ${ahmet.name} (${ahmet.email})`);
// Advanced queries with operators
console.log('\nšÆ Advanced queries with operators:');
// $gt (greater than)
const olderUsers = users.find({ age: { $gt: 25 } });
console.log(`š„ Users older than 25: ${olderUsers.length}`);
// $in (in array)
const cityUsers = users.find({ city: { $in: ["Istanbul", "Izmir"] } });
console.log(`šļø Users in Istanbul/Izmir: ${cityUsers.length}`);
// $regex (regular expression)
const emailPattern = logs.find({ message: { $regex: "log" } });
console.log(`š§ Messages containing 'log': ${emailPattern.length}`);
// $and (logical AND)
const complexQuery = users.find({
$and: [
{ age: { $gte: 25 } },
{ city: "Istanbul" }
]
});
console.log(`š Complex query results: ${complexQuery.length}`);
// Date range queries
const recentLogs = logs.find({
date: { $gte: "2025-08-02" },
type: { $ne: "info" }
});
console.log(`š
Recent non-info logs: ${recentLogs.length}`);
// =====================================================
// PART 3: Sorting, Projection, Pagination
// =====================================================
console.log('\nš PART 3: Advanced Query Options');
console.log('ā'.repeat(50));
// Sorting
const sortedUsers = users.find({}, {
sort: { age: -1 } // Descending by age
});
console.log('š„ Users sorted by age (desc):',
sortedUsers.map(u => `${u.name}(${u.age})`));
// Projection (select specific fields)
const userEmails = users.find({}, {
projection: { name: 1, email: 1, _id: 0 }
});
console.log('š§ User emails only:', userEmails);
// Pagination
const paginatedUsers = users.find({}, {
skip: 0,
limit: 1
});
console.log('š First page (limit 1):', paginatedUsers.length, 'users');
// =====================================================
// PART 4: Updates and Modifications
// =====================================================
console.log('\nāļø PART 4: Document Updates');
console.log('ā'.repeat(50));
// $set operator
const updateResult1 = await users.update(
{ name: "Ahmet" },
{ $set: { age: 26, status: "active" } }
);
console.log(`š $set update: ${updateResult1.modifiedCount} documents`);
// $inc operator (increment)
await users.update(
{ name: "Fatma" },
{ $inc: { age: 1 } }
);
console.log('š $inc update: Fatma\'s age incremented');
// $push operator (add to array)
await users.update(
{ name: "Ahmet" },
{ $push: { hobbies: "reading" } }
);
console.log('š $push update: Added hobby to Ahmet');
// =====================================================
// PART 5: Indexing for Performance
// =====================================================
console.log('\nš PART 5: Indexing System');
console.log('ā'.repeat(50));
// Create indexes
users.createIndex({ email: 1 }, { name: 'email_index' });
users.createIndex({ city: 1, age: -1 }, { name: 'city_age_index' });
logs.createIndex({ type: 1 }, { name: 'type_index' });
console.log('š Indexes created for better performance');
// Query execution plan
const plan = db.explainQuery('users', { email: "ahmet@example.com" });
console.log('š Query execution plan:', {
indexUsed: plan.executionStats.indexUsed,
documentsExamined: plan.executionStats.documentsExamined
});
// =====================================================
// PART 6: Collection Statistics
// =====================================================
console.log('\nš PART 6: Collection Statistics');
console.log('ā'.repeat(50));
const userStats = db.getCollectionStats('users');
const logStats = db.getCollectionStats('logs');
console.log('š„ Users collection:', {
documents: userStats.documentCount,
indexes: userStats.indexes,
memoryKB: Math.round(userStats.memoryUsage / 1024)
});
console.log('š Logs collection:', {
documents: logStats.documentCount,
indexes: logStats.indexes,
memoryKB: Math.round(logStats.memoryUsage / 1024)
});
await db.close();
console.log('\nš Collection System Demo Completed Successfully!');
console.log('ā
MongoDB-style operations work perfectly');
console.log('ā
Advanced queries with operators supported');
console.log('ā
Indexing system provides performance optimization');
} catch (error) {
console.error('ā Demo error:', error);
await db.close();
}
}
async function demonstratePerformance() {
console.log('\n\nš PERFORMANCE ENGINE DEMO');
console.log('ā'.repeat(65));
const db = new BigBaseAlpha({
path: './DEMO_PERFORMANCE_DATA',
encryption: false,
apiGateway: { enabled: false },
security: { paranoidLogging: false }
});
try {
await db.init();
console.log('ā
Database initialized for performance testing\n');
// =====================================================
// PART 1: Enable Lazy Write Mode
// =====================================================
console.log('š¾ PART 1: Lazy Write Performance Mode');
console.log('ā'.repeat(50));
// Enable lazy write with custom settings
db.enableLazyWrite({
delay: 3000, // 3 seconds batch delay
batchSize: 50, // 50 operations per batch
compressionEnabled: true
});
console.log('š Lazy Write enabled: 3s delay, 50 batch size');
// =====================================================
// PART 2: High-Volume Operations
// =====================================================
console.log('\nā” PART 2: High-Volume Operations');
console.log('ā'.repeat(50));
const testCollection = db.collection('performance_test');
const startTime = Date.now();
// Insert many documents quickly (queued, not written immediately)
console.log('š Inserting 100 documents (lazy mode)...');
for (let i = 1; i <= 100; i++) {
await testCollection.insert({
id: i,
name: `Test User ${i}`,
score: Math.floor(Math.random() * 100),
category: i % 5 === 0 ? 'premium' : 'standard',
timestamp: new Date()
});
}
const insertTime = Date.now() - startTime;
console.log(`ā” 100 inserts completed in ${insertTime}ms (queued)`);
// Show performance stats
const perfStats = db.getPerformanceStats();
console.log('š Performance stats:', {
pendingOperations: perfStats.pendingCount,
totalOperations: perfStats.totalOperations,
batchesWritten: perfStats.batchesWritten
});
// =====================================================
// PART 3: Force Flush and Timing
// =====================================================
console.log('\nš¾ PART 3: Force Flush Operations');
console.log('ā'.repeat(50));
console.log('š Forcing flush of all pending operations...');
const flushStart = Date.now();
await db.flushOperations();
const flushTime = Date.now() - flushStart;
console.log(`ā
All operations flushed in ${flushTime}ms`);
// Updated stats
const newStats = db.getPerformanceStats();
console.log('š After flush:', {
pendingOperations: newStats.pendingCount,
batchesWritten: newStats.batchesWritten,
compressionRatio: Math.round(newStats.compressionRatio * 100) + '%'
});
// =====================================================
// PART 4: Performance Comparison
// =====================================================
console.log('\nāļø PART 4: Performance Comparison');
console.log('ā'.repeat(50));
// Disable lazy write for comparison
await db.disableLazyWrite();
console.log('š Lazy write disabled');
const immediateCollection = db.collection('immediate_test');
const immediateStart = Date.now();
// Insert with immediate write
console.log('š Inserting 50 documents (immediate mode)...');
for (let i = 1; i <= 50; i++) {
await immediateCollection.insert({
id: i,
name: `Immediate User ${i}`,
data: 'immediate_write_test'
});
}
const immediateTime = Date.now() - immediateStart;
console.log(`ā±ļø 50 immediate inserts: ${immediateTime}ms`);
// =====================================================
// PART 5: Query Performance
// =====================================================
console.log('\nš PART 5: Query Performance');
console.log('ā'.repeat(50));
// Create index for performance
testCollection.createIndex({ category: 1, score: -1 });
const queryStart = Date.now();
// Complex query
const results = testCollection.find({
$and: [
{ category: 'premium' },
{ score: { $gte: 50 } }
]
}, {
sort: { score: -1 },
limit: 10
});
const queryTime = Date.now() - queryStart;
console.log(`šÆ Complex query found ${results.length} results in ${queryTime}ms`);
// Show query plan
const queryPlan = db.explainQuery('performance_test', {
category: 'premium',
score: { $gte: 50 }
});
console.log('š Query optimization:', {
indexUsed: queryPlan.executionStats.indexUsed,
documentsExamined: queryPlan.executionStats.documentsExamined,
totalDocuments: queryPlan.totalDocuments
});
await db.close();
console.log('\nš Performance Demo Completed Successfully!');
console.log('ā
Lazy write provides significant performance boost');
console.log('ā
Batch processing optimizes disk I/O');
console.log('ā
Query optimization with indexes works perfectly');
} catch (error) {
console.error('ā Performance demo error:', error);
await db.close();
}
}
// Run both demos
async function runAllDemos() {
try {
await demonstrateCollections();
await demonstratePerformance();
console.log('\nš ALL DEMOS COMPLETED SUCCESSFULLY!');
console.log('ā'.repeat(65));
console.log('šÆ BigBaseAlpha v1.4.0 New Features:');
console.log(' ā
MongoDB-style collection system');
console.log(' ā
Advanced query engine with operators');
console.log(' ā
Performance optimization with lazy write');
console.log(' ā
Indexing system for better performance');
console.log(' ā
Comprehensive statistics and monitoring');
} catch (error) {
console.error('ā Demo execution error:', error);
process.exit(1);
}
}
runAllDemos();