Examples
Part of Matsushiba Systems
Real-world examples and sample applications for MatsushibaDB.
const { MatsushibaDBClient } = require('matsushibadb');
async function basicExample() {
const client = new MatsushibaDBClient({
host: 'localhost',
port: 8000,
username: 'admin',
password: 'password'
});
try {
await client.connect();
console.log('Connected to MatsushibaDB');
// Create table
await client.query(`
CREATE TABLE IF NOT EXISTS products (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
price DECIMAL(10,2),
category TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
)
`);
// Insert data
const insertResult = await client.query(
'INSERT INTO products (name, price, category) VALUES (?, ?, ?)',
['Laptop', 999.99, 'Electronics']
);
console.log('Inserted product with ID:', insertResult.lastInsertId);
// Query data
const products = await client.query('SELECT * FROM products WHERE category = ?', ['Electronics']);
console.log('Electronics products:', products);
// Update data
await client.query(
'UPDATE products SET price = ? WHERE id = ?',
[899.99, insertResult.lastInsertId]
);
// Delete data
await client.query('DELETE FROM products WHERE id = ?', [insertResult.lastInsertId]);
} catch (error) {
console.error('Error:', error);
} finally {
await client.disconnect();
}
}
basicExample();
import asyncio
from matsushiba_db import MatsushibaDBClient
async def python_example():
client = MatsushibaDBClient(
host='localhost',
port=8000,
username='admin',
password='password'
)
try:
await client.connect()
print('Connected to MatsushibaDB')
# Create table
await client.query('''
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT UNIQUE NOT NULL,
email TEXT UNIQUE NOT NULL,
full_name TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
)
''')
# Insert multiple users
users = [
('john_doe', 'john@example.com', 'John Doe'),
('jane_smith', 'jane@example.com', 'Jane Smith'),
('bob_wilson', 'bob@example.com', 'Bob Wilson')
]
for username, email, full_name in users:
await client.query(
'INSERT INTO users (username, email, full_name) VALUES (?, ?, ?)',
[username, email, full_name]
)
# Query with pagination
page_size = 2
offset = 0
users_page = await client.query(
'SELECT * FROM users ORDER BY created_at DESC LIMIT ? OFFSET ?',
[page_size, offset]
)
print(f'Users (page 1): {users_page}')
# Count total users
count_result = await client.query('SELECT COUNT(*) as total FROM users')
total_users = count_result[0]['total']
print(f'Total users: {total_users}')
except Exception as error:
print(f'Error: {error}')
finally:
await client.disconnect()
# Run the example
asyncio.run(python_example())
const express = require('express');
const { MatsushibaDBClient } = require('matsushibadb');
const app = express();
app.use(express.json());
// Initialize database client
const db = new MatsushibaDBClient({
host: 'localhost',
port: 8000,
username: 'admin',
password: 'password'
});
// Connect to database
db.connect().then(() => {
console.log('Connected to MatsushibaDB');
}).catch(console.error);
// Middleware for error handling
const asyncHandler = (fn) => (req, res, next) => {
Promise.resolve(fn(req, res, next)).catch(next);
};
// Routes
app.get('/api/users', asyncHandler(async (req, res) => {
const { page = 1, limit = 10 } = req.query;
const offset = (page - 1) * limit;
const users = await db.query(
'SELECT * FROM users ORDER BY created_at DESC LIMIT ? OFFSET ?',
[parseInt(limit), offset]
);
const count = await db.query('SELECT COUNT(*) as total FROM users');
res.json({
users,
pagination: {
page: parseInt(page),
limit: parseInt(limit),
total: count[0].total,
pages: Math.ceil(count[0].total / limit)
}
});
}));
app.post('/api/users', asyncHandler(async (req, res) => {
const { username, email, full_name } = req.body;
const result = await db.query(
'INSERT INTO users (username, email, full_name) VALUES (?, ?, ?)',
[username, email, full_name]
);
const newUser = await db.query('SELECT * FROM users WHERE id = ?', [result.lastInsertId]);
res.status(201).json(newUser[0]);
}));
app.put('/api/users/:id', asyncHandler(async (req, res) => {
const { id } = req.params;
const { username, email, full_name } = req.body;
await db.query(
'UPDATE users SET username = ?, email = ?, full_name = ? WHERE id = ?',
[username, email, full_name, id]
);
const updatedUser = await db.query('SELECT * FROM users WHERE id = ?', [id]);
if (updatedUser.length === 0) {
return res.status(404).json({ error: 'User not found' });
}
res.json(updatedUser[0]);
}));
app.delete('/api/users/:id', asyncHandler(async (req, res) => {
const { id } = req.params;
const result = await db.query('DELETE FROM users WHERE id = ?', [id]);
if (result.rowsAffected === 0) {
return res.status(404).json({ error: 'User not found' });
}
res.status(204).send();
}));
// Error handling middleware
app.use((error, req, res, next) => {
console.error(error);
res.status(500).json({ error: 'Internal server error' });
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
from flask import Flask, request, jsonify
from matsushiba_db import MatsushibaDBClient
import os
app = Flask(__name__)
# Initialize database client
db = MatsushibaDBClient(
host='localhost',
port=8000,
username='admin',
password='password'
)
# Connect to database
try:
db.connect()
print('Connected to MatsushibaDB')
except Exception as e:
print(f'Database connection error: {e}')
@app.route('/api/posts', methods=['GET'])
def get_posts():
try:
page = int(request.args.get('page', 1))
limit = int(request.args.get('limit', 10))
offset = (page - 1) * limit
posts = db.query(
'SELECT * FROM posts ORDER BY created_at DESC LIMIT ? OFFSET ?',
[limit, offset]
)
count = db.query('SELECT COUNT(*) as total FROM posts')
return jsonify({
'posts': posts,
'pagination': {
'page': page,
'limit': limit,
'total': count[0]['total'],
'pages': (count[0]['total'] + limit - 1) // limit
}
})
except Exception as e:
return jsonify({'error': str(e)}), 500
@app.route('/api/posts', methods=['POST'])
def create_post():
try:
data = request.get_json()
title = data.get('title')
content = data.get('content')
author_id = data.get('author_id')
if not all([title, content, author_id]):
return jsonify({'error': 'Missing required fields'}), 400
result = db.query(
'INSERT INTO posts (title, content, author_id) VALUES (?, ?, ?)',
[title, content, author_id]
)
new_post = db.query('SELECT * FROM posts WHERE id = ?', [result['lastInsertId']])
return jsonify(new_post[0]), 201
except Exception as e:
return jsonify({'error': str(e)}), 500
@app.route('/api/posts/', methods=['GET'])
def get_post(post_id):
try:
posts = db.query('SELECT * FROM posts WHERE id = ?', [post_id])
if not posts:
return jsonify({'error': 'Post not found'}), 404
return jsonify(posts[0])
except Exception as e:
return jsonify({'error': str(e)}), 500
@app.route('/api/posts/', methods=['PUT'])
def update_post(post_id):
try:
data = request.get_json()
title = data.get('title')
content = data.get('content')
result = db.query(
'UPDATE posts SET title = ?, content = ? WHERE id = ?',
[title, content, post_id]
)
if result['rowsAffected'] == 0:
return jsonify({'error': 'Post not found'}), 404
updated_post = db.query('SELECT * FROM posts WHERE id = ?', [post_id])
return jsonify(updated_post[0])
except Exception as e:
return jsonify({'error': str(e)}), 500
@app.route('/api/posts/', methods=['DELETE'])
def delete_post(post_id):
try:
result = db.query('DELETE FROM posts WHERE id = ?', [post_id])
if result['rowsAffected'] == 0:
return jsonify({'error': 'Post not found'}), 404
return '', 204
except Exception as e:
return jsonify({'error': str(e)}), 500
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0', port=5000)
const WebSocket = require('ws');
const { MatsushibaDBClient } = require('matsushibadb');
// Initialize database
const db = new MatsushibaDBClient({
host: 'localhost',
port: 8000,
username: 'admin',
password: 'password'
});
// WebSocket server
const wss = new WebSocket.Server({ port: 8080 });
// Store connected clients
const clients = new Map();
wss.on('connection', (ws) => {
console.log('New client connected');
ws.on('message', async (message) => {
try {
const data = JSON.parse(message);
switch (data.type) {
case 'join':
clients.set(ws, { username: data.username, room: data.room });
await broadcastToRoom(data.room, {
type: 'user_joined',
username: data.username,
timestamp: new Date().toISOString()
});
break;
case 'message':
const client = clients.get(ws);
if (client) {
// Save message to database
await db.query(
'INSERT INTO messages (username, room, content, timestamp) VALUES (?, ?, ?, ?)',
[client.username, client.room, data.content, new Date().toISOString()]
);
// Broadcast to room
await broadcastToRoom(client.room, {
type: 'message',
username: client.username,
content: data.content,
timestamp: new Date().toISOString()
});
}
break;
case 'typing':
const typingClient = clients.get(ws);
if (typingClient) {
await broadcastToRoom(typingClient.room, {
type: 'typing',
username: typingClient.username,
isTyping: data.isTyping
});
}
break;
}
} catch (error) {
console.error('Error processing message:', error);
ws.send(JSON.stringify({
type: 'error',
message: 'Invalid message format'
}));
}
});
ws.on('close', async () => {
const client = clients.get(ws);
if (client) {
await broadcastToRoom(client.room, {
type: 'user_left',
username: client.username,
timestamp: new Date().toISOString()
});
}
clients.delete(ws);
console.log('Client disconnected');
});
});
async function broadcastToRoom(room, message) {
const messageStr = JSON.stringify(message);
for (const [ws, client] of clients) {
if (client.room === room && ws.readyState === WebSocket.OPEN) {
ws.send(messageStr);
}
}
}
// Initialize database tables
async function initDatabase() {
try {
await db.connect();
await db.query(`
CREATE TABLE IF NOT EXISTS messages (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT NOT NULL,
room TEXT NOT NULL,
content TEXT NOT NULL,
timestamp DATETIME NOT NULL
)
`);
console.log('Database initialized');
} catch (error) {
console.error('Database initialization error:', error);
}
}
initDatabase();
console.log('WebSocket server running on port 8080');
// Frontend JavaScript for real-time dashboard
const ws = new WebSocket('ws://localhost:8001');
const dashboard = document.getElementById('dashboard');
// Connect to MatsushibaDB WebSocket
ws.onopen = () => {
console.log('Connected to MatsushibaDB WebSocket');
// Subscribe to real-time updates
ws.send(JSON.stringify({
id: 'sub_1',
type: 'subscribe',
data: {
table: 'metrics',
events: ['insert', 'update']
}
}));
};
ws.onmessage = (event) => {
const message = JSON.parse(event.data);
switch (message.type) {
case 'table_change':
updateDashboard(message.data);
break;
case 'query_result':
if (message.id === 'metrics_query') {
displayMetrics(message.data);
}
break;
}
};
// Request current metrics
function requestMetrics() {
ws.send(JSON.stringify({
id: 'metrics_query',
type: 'query',
data: {
query: 'SELECT * FROM metrics ORDER BY timestamp DESC LIMIT 100'
}
}));
}
// Update dashboard with new data
function updateDashboard(data) {
const metricCard = document.getElementById(`metric-${data.metric_name}`);
if (metricCard) {
metricCard.querySelector('.value').textContent = data.value;
metricCard.querySelector('.timestamp').textContent =
new Date(data.timestamp).toLocaleTimeString();
// Add animation
metricCard.classList.add('updated');
setTimeout(() => metricCard.classList.remove('updated'), 1000);
}
}
// Display metrics
function displayMetrics(metrics) {
const container = document.getElementById('metrics-container');
container.innerHTML = '';
metrics.forEach(metric => {
const card = document.createElement('div');
card.className = 'metric-card';
card.id = `metric-${metric.metric_name}`;
card.innerHTML = `
${metric.metric_name}
${metric.value}
`;
container.appendChild(card);
});
}
// Request metrics every 5 seconds
setInterval(requestMetrics, 5000);
// Initial metrics request
requestMetrics();
const jwt = require('jsonwebtoken');
const { MatsushibaDBClient } = require('matsushibadb');
// Database client
const db = new MatsushibaDBClient({
host: 'localhost',
port: 8000,
username: 'admin',
password: 'password'
});
// JWT secret
const JWT_SECRET = process.env.JWT_SECRET || 'your-secret-key';
// Authentication middleware
const authenticateToken = async (req, res, next) => {
const authHeader = req.headers['authorization'];
const token = authHeader && authHeader.split(' ')[1];
if (!token) {
return res.status(401).json({ error: 'Access token required' });
}
try {
const decoded = jwt.verify(token, JWT_SECRET);
// Verify user exists and is active
const users = await db.query(
'SELECT id, username, role, active FROM users WHERE id = ? AND active = 1',
[decoded.userId]
);
if (users.length === 0) {
return res.status(401).json({ error: 'Invalid token' });
}
req.user = users[0];
next();
} catch (error) {
return res.status(403).json({ error: 'Invalid token' });
}
};
// Role-based authorization middleware
const requireRole = (roles) => {
return (req, res, next) => {
if (!req.user) {
return res.status(401).json({ error: 'Authentication required' });
}
if (!roles.includes(req.user.role)) {
return res.status(403).json({ error: 'Insufficient permissions' });
}
next();
};
};
// Login endpoint
app.post('/auth/login', async (req, res) => {
try {
const { username, password } = req.body;
// Verify credentials
const users = await db.query(
'SELECT id, username, role, password_hash FROM users WHERE username = ? AND active = 1',
[username]
);
if (users.length === 0) {
return res.status(401).json({ error: 'Invalid credentials' });
}
const user = users[0];
// Verify password (using bcrypt in real implementation)
const isValidPassword = await bcrypt.compare(password, user.password_hash);
if (!isValidPassword) {
return res.status(401).json({ error: 'Invalid credentials' });
}
// Generate JWT token
const token = jwt.sign(
{ userId: user.id, username: user.username, role: user.role },
JWT_SECRET,
{ expiresIn: '1h' }
);
// Update last login
await db.query(
'UPDATE users SET last_login = CURRENT_TIMESTAMP WHERE id = ?',
[user.id]
);
res.json({
success: true,
token,
user: {
id: user.id,
username: user.username,
role: user.role
}
});
} catch (error) {
res.status(500).json({ error: 'Login failed' });
}
});
// Protected routes
app.get('/api/profile', authenticateToken, (req, res) => {
res.json({ user: req.user });
});
app.get('/api/admin/users', authenticateToken, requireRole(['admin']), async (req, res) => {
try {
const users = await db.query('SELECT id, username, role, created_at, last_login FROM users');
res.json({ users });
} catch (error) {
res.status(500).json({ error: 'Failed to fetch users' });
}
});
app.post('/api/admin/users', authenticateToken, requireRole(['admin']), async (req, res) => {
try {
const { username, password, role } = req.body;
const passwordHash = await bcrypt.hash(password, 10);
const result = await db.query(
'INSERT INTO users (username, password_hash, role) VALUES (?, ?, ?)',
[username, passwordHash, role]
);
const newUser = await db.query('SELECT id, username, role FROM users WHERE id = ?', [result.lastInsertId]);
res.status(201).json(newUser[0]);
} catch (error) {
res.status(500).json({ error: 'Failed to create user' });
}
});
const { MatsushibaDBClient } = require('matsushibadb');
// Create connection pool
class DatabasePool {
constructor(config, poolSize = 10) {
this.config = config;
this.poolSize = poolSize;
this.pool = [];
this.used = new Set();
this.waiting = [];
}
async initialize() {
for (let i = 0; i < this.poolSize; i++) {
const client = new MatsushibaDBClient(this.config);
await client.connect();
this.pool.push(client);
}
console.log(`Initialized pool with ${this.poolSize} connections`);
}
async getConnection() {
return new Promise((resolve, reject) => {
if (this.pool.length > 0) {
const client = this.pool.pop();
this.used.add(client);
resolve(client);
} else {
this.waiting.push({ resolve, reject });
}
});
}
releaseConnection(client) {
if (this.used.has(client)) {
this.used.delete(client);
this.pool.push(client);
if (this.waiting.length > 0) {
const { resolve } = this.waiting.shift();
resolve(client);
}
}
}
async query(sql, params = []) {
const client = await this.getConnection();
try {
const result = await client.query(sql, params);
return result;
} finally {
this.releaseConnection(client);
}
}
}
// Usage
const pool = new DatabasePool({
host: 'localhost',
port: 8000,
username: 'admin',
password: 'password'
}, 20);
await pool.initialize();
// High-performance bulk insert
async function bulkInsert(records) {
const batchSize = 1000;
const batches = [];
for (let i = 0; i < records.length; i += batchSize) {
batches.push(records.slice(i, i + batchSize));
}
for (const batch of batches) {
await pool.query('BEGIN TRANSACTION');
for (const record of batch) {
await pool.query(
'INSERT INTO large_table (col1, col2, col3) VALUES (?, ?, ?)',
[record.col1, record.col2, record.col3]
);
}
await pool.query('COMMIT');
}
}
// Generate test data
const testData = Array.from({ length: 10000 }, (_, i) => ({
col1: `value_${i}`,
col2: Math.random() * 1000,
col3: new Date().toISOString()
}));
// Benchmark bulk insert
console.time('Bulk Insert');
await bulkInsert(testData);
console.timeEnd('Bulk Insert');
# docker-compose.prod.yml
version: '3.8'
services:
matsushibadb:
image: matsushiba/matsushibadb:latest
container_name: matsushibadb-prod
restart: unless-stopped
ports:
- "8000:8000"
- "8001:8001"
- "8002:8002"
- "8003:8003"
- "8004:8004"
- "8005:8005"
environment:
- MATSUSHIBA_MODE=production
- DATABASE_PATH=/app/data/matsushiba.db
- LOG_LEVEL=info
- LOG_FILE=/app/logs/matsushiba.log
- JWT_SECRET=${JWT_SECRET}
- HTTP_PORT=8000
- WS_PORT=8001
- TCP_PORT=8002
- ADMIN_PORT=8003
- METRICS_PORT=8004
- HEALTH_PORT=8005
- MAX_CONNECTIONS=100
- CACHE_SIZE=10000
- WAL_MODE=true
- SYNCHRONOUS=NORMAL
volumes:
- matsushiba_data:/app/data
- matsushiba_logs:/app/logs
- matsushiba_backups:/app/backups
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:8005/health"]
interval: 30s
timeout: 10s
retries: 3
start_period: 40s
networks:
- matsushiba-network
nginx:
image: nginx:alpine
container_name: matsushiba-nginx
restart: unless-stopped
ports:
- "80:80"
- "443:443"
volumes:
- ./nginx.conf:/etc/nginx/nginx.conf
- ./ssl:/etc/nginx/ssl
depends_on:
- matsushibadb
networks:
- matsushiba-network
prometheus:
image: prom/prometheus:latest
container_name: matsushiba-prometheus
restart: unless-stopped
ports:
- "9090:9090"
volumes:
- ./prometheus.yml:/etc/prometheus/prometheus.yml
- prometheus_data:/prometheus
command:
- '--config.file=/etc/prometheus/prometheus.yml'
- '--storage.tsdb.path=/prometheus'
- '--web.console.libraries=/etc/prometheus/console_libraries'
- '--web.console.templates=/etc/prometheus/consoles'
- '--storage.tsdb.retention.time=200h'
- '--web.enable-lifecycle'
networks:
- matsushiba-network
grafana:
image: grafana/grafana:latest
container_name: matsushiba-grafana
restart: unless-stopped
ports:
- "3000:3000"
environment:
- GF_SECURITY_ADMIN_PASSWORD=${GRAFANA_PASSWORD}
volumes:
- grafana_data:/var/lib/grafana
networks:
- matsushiba-network
volumes:
matsushiba_data:
driver: local
matsushiba_logs:
driver: local
matsushiba_backups:
driver: local
prometheus_data:
driver: local
grafana_data:
driver: local
networks:
matsushiba-network:
driver: bridge
# nginx.conf
events {
worker_connections 1024;
}
http {
upstream matsushibadb {
server matsushibadb:8000;
}
upstream matsushibadb_ws {
server matsushibadb:8001;
}
upstream matsushibadb_admin {
server matsushibadb:8003;
}
upstream matsushibadb_metrics {
server matsushibadb:8004;
}
# Rate limiting
limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
limit_req_zone $binary_remote_addr zone=admin:10m rate=5r/s;
# Main HTTP server
server {
listen 80;
server_name db.matsushiba.co;
# Redirect to HTTPS
return 301 https://$server_name$request_uri;
}
# HTTPS server
server {
listen 443 ssl http2;
server_name db.matsushiba.co;
ssl_certificate /etc/nginx/ssl/cert.pem;
ssl_certificate_key /etc/nginx/ssl/key.pem;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE-RSA-AES256-GCM-SHA512:DHE-RSA-AES256-GCM-SHA512;
ssl_prefer_server_ciphers off;
# Security headers
add_header X-Frame-Options DENY;
add_header X-Content-Type-Options nosniff;
add_header X-XSS-Protection "1; mode=block";
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
# API endpoints
location /api/ {
limit_req zone=api burst=20 nodelay;
proxy_pass http://matsushibadb;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_connect_timeout 30s;
proxy_send_timeout 30s;
proxy_read_timeout 30s;
}
# WebSocket endpoints
location /ws/ {
proxy_pass http://matsushibadb_ws;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_connect_timeout 7d;
proxy_send_timeout 7d;
proxy_read_timeout 7d;
}
# Admin interface
location /admin/ {
limit_req zone=admin burst=10 nodelay;
proxy_pass http://matsushibadb_admin;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
# Metrics endpoint
location /metrics {
allow 10.0.0.0/8;
allow 172.16.0.0/12;
allow 192.168.0.0/16;
deny all;
proxy_pass http://matsushibadb_metrics;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
# Health check
location /health {
proxy_pass http://matsushibadb/health;
access_log off;
}
}
}