Vlodia ORM User Guide

Complete guide to using Vlodia ORM in your TypeScript projects

🚀 Quick Start

1. Installation

npm install vlodia npm install pg mysql sqlite redis npm install -D @types/pg @types/mysql

2. Project Initialization

# Initialize Vlodia project vlodia init # Or with specific database vlodia init --database postgres --host localhost --username postgres --password password --name myapp

3. Basic Setup

import { Vlodia } from 'vlodia'; import { User } from './entities/User'; const orm = new Vlodia({ database: { type: 'postgres', host: 'localhost', port: 5432, username: 'postgres', password: 'password', database: 'myapp' }, entities: [User] }); await orm.initialize();

📊 Entity Definition

Creating Entities

import { Entity, Column, PrimaryKey, OneToMany } from 'vlodia'; @Entity({ tableName: 'users' }) export class User { @PrimaryKey() @Column({ type: 'number', generated: true }) id!: number; @Column({ type: 'string', length: 100 }) name!: string; @Column({ type: 'string', unique: true }) email!: string; @Column({ type: 'string' }) password!: string; @Column({ type: 'boolean', default: true }) active!: boolean; @Column({ type: 'date', default: () => 'CURRENT_TIMESTAMP' }) createdAt!: Date; @OneToMany(() => Post, 'authorId') posts!: Post[]; }

Relations

// One-to-Many @OneToMany(() => Post, 'authorId') posts!: Post[]; // Many-to-One @ManyToOne(() => User, 'posts') author!: User; // One-to-One @OneToOne(() => Profile, 'userId') profile!: Profile; // Many-to-Many @ManyToMany(() => Tag, 'user_tags') tags!: Tag[];

🔍 Database Operations

Basic CRUD Operations

// Create const user = new User(); user.name = 'John Doe'; user.email = 'john@example.com'; user.password = 'password123'; const savedUser = await orm.manager.save(user); // Read const users = await orm.manager.find(User, {}); const user = await orm.manager.findOne(User, { where: { id: 1 } }); // Update user.name = 'Jane Doe'; await orm.manager.save(user); // Delete await orm.manager.remove(user);

Advanced Queries

// Complex queries const users = await orm.manager.find(User, { where: { active: true }, relations: ['posts'], orderBy: { createdAt: 'DESC' }, limit: 10, offset: 0 }); // Custom queries const result = await orm.manager.query( 'SELECT * FROM users WHERE age > ? AND city = ?', [18, 'New York'] );

🔄 Transactions

Transaction Management

// Basic transaction await orm.transaction(async (manager) => { const user = new User(); user.name = 'John Doe'; await manager.save(user); const post = new Post(); post.title = 'My First Post'; post.author = user; await manager.save(post); }); // Nested transactions await orm.transaction(async (manager) => { await orm.transaction(async (nestedManager) => { // Nested transaction logic }); });

⚡ Performance & Caching

Query Optimization

// Enable query analysis const orm = new Vlodia({ database: { /* ... */ }, logging: { level: 'debug', queries: true, slowQueries: true, slowQueryThreshold: 1000 } }); // Get performance metrics const metrics = orm.getPerformanceMetrics(); console.log('Performance score:', metrics.performanceScore);

Caching

// Enable caching const orm = new Vlodia({ database: { /* ... */ }, cache: { enabled: true, type: 'redis', ttl: 3600, maxSize: 10000 } }); // Manual cache operations await orm.cacheInstance.set('user:1', user, 3600); const cachedUser = await orm.cacheInstance.get('user:1');

🌐 Real-time Features

WebSocket Integration

// Enable real-time features const orm = new Vlodia({ database: { /* ... */ }, realtime: { enabled: true, port: 8080, path: '/ws' } }); // Get WebSocket manager const wsManager = orm.getWebSocketManager(); wsManager?.subscribe('user_created', (data) => { console.log('New user created:', data); });

🔧 CLI Commands

Available Commands

# Project management vlodia init vlodia generate:entity User vlodia generate:entity Post --with-relations # Migration management vlodia migration:create AddUserTable vlodia migration:run vlodia migration:revert # Schema management vlodia schema:sync vlodia schema:validate # Real-time features vlodia realtime:start --port 8080 # Performance analysis vlodia performance:analyze vlodia performance:report

📚 Best Practices

Entity Design

  • Use descriptive entity and column names
  • Define proper relationships between entities
  • Use appropriate data types and constraints
  • Add validation rules where necessary

Query Optimization

  • Use relations to avoid N+1 queries
  • Implement pagination for large datasets
  • Use specific field selection when possible
  • Monitor query performance regularly

Error Handling

try { const user = await orm.manager.save(newUser); console.log('User created:', user); } catch (error) { if (error instanceof VlodiaError) { console.error('Vlodia error:', error.message); } else { console.error('Unexpected error:', error); } }

🔗 Additional Resources

Documentation Links