Skip to content

rishicool/GuruORM

Repository files navigation

guruORM

A powerful, elegant Node.js ORM inspired by Laravel and Illuminate

npm version License: MIT TypeScript JavaScript

🎯 Features

  • πŸš€ Fluent Query Builder - Elegant and expressive query building
  • πŸ”₯ Eloquent ORM - Active Record implementation for Node.js
  • πŸ—ƒοΈ Multiple Databases - MySQL, PostgreSQL, SQLite, SQL Server support
  • πŸ”„ Migrations - Version control for your database schema
  • 🌱 Seeding - Populate your database with test data
  • πŸ”— Relationships - Full relationship support (One-to-One, One-to-Many, Many-to-Many, Polymorphic)
  • πŸ“¦ JavaScript & TypeScript - Works with both! Full type safety optional
  • πŸ› οΈ CLI Tools - Powerful command-line interface
  • ✨ Zero Config - Works out of the box with JavaScript projects

πŸ‘‰ Complete Features List - See what's working and what's planned
πŸ‘‰ Complete Database Drivers Guide - MySQL, PostgreSQL, SQLite, SQL Server examples

πŸ™ Acknowledgment

Inspired by Laravel and Illuminate Database.

πŸ“¦ Installation

npm install guruorm

πŸš€ Quick Start

Works with Both JavaScript & TypeScript!

TypeScript:

import { Capsule } from 'guruorm';

const capsule = new Capsule();

capsule.addConnection({
  driver: 'mysql',
  host: 'localhost',
  port: 3306,
  database: 'mydb',
  username: 'root',
  password: 'password',
});

capsule.setAsGlobal();
capsule.bootEloquent();

JavaScript (CommonJS):

const { Capsule } = require('guruorm');

const capsule = new Capsule();

capsule.addConnection({
  driver: 'mysql',
  host: 'localhost',
  database: 'mydb',
  username: 'root',
  password: 'password',
});

capsule.setAsGlobal();
capsule.bootEloquent();

Your First Query

JavaScript:

const { DB, Schema } = require('guruorm');

// Create schema
await Schema.create('users', (table) => {
  table.id();
  table.string('name');
  table.string('email').unique();
  table.boolean('active').defaultTo(true);
  table.timestamps();
});

// Raw SQL queries
const users = await DB.select('SELECT * FROM users WHERE active = ?', [true]);

// Query builder
const activeUsers = await DB.table('users')
  .where('active', true)
  .orderBy('name')
  .get();

// Insert data
await DB.insert('INSERT INTO users (name, email) VALUES (?, ?)', [
  'John Doe',
  'john@example.com'
]);

// Or using query builder
await DB.table('users').insert({
  name: 'Jane Smith',
  email: 'jane@example.com'
});

Your First Model

JavaScript:

const { Model } = require('guruorm');

class User extends Model {
  constructor() {
    super();
    this.table = 'users';
    this.fillable = ['name', 'email', 'password'];
  }
  
  // Define relationship
  posts() {
    return this.hasMany(Post);
  }
}

// Use it
const user = await User.create({
  name: 'John Doe',
  email: 'john@example.com'
});

const users = await User.where('active', true).get();

TypeScript:

import { Model } from 'guruorm';

class User extends Model {
  protected table = 'users';
  protected fillable = ['name', 'email', 'password'];
  
  // Define relationship
  posts() {
    return this.hasMany(Post);
  }
}

// Use it
const user = await User.find(1);
const users = await User.where('active', true).get();
const newUser = await User.create({ 
  name: 'John Doe', 
  email: 'john@example.com' 
});

πŸ‘‰ See Complete Getting Started Guide


πŸ“– Documentation

GuruORM provides comprehensive, easy-to-follow documentation.

Core Concepts

  • Getting Started - Installation, setup, and basic configuration
  • Query Builder - Build complex database queries with a fluent, expressive API
  • Eloquent ORM - Work with your database using elegant Active Record models
  • Relationships - Define and query model relationships (One-to-One, One-to-Many, Many-to-Many)
  • Migrations - Version control for your database schema
  • Seeding - Populate your database with test data

Additional Topics

  • Collections - Work with collections of data
  • Events & Observers - Hook into model lifecycle events
  • Mutators & Casting - Transform model attributes
  • Advanced Queries - Subqueries, unions, and raw expressions
  • Testing - Test your database interactions

πŸ’‘ Examples

Query Builder Examples

// Basic where clauses
const users = await DB.table('users')
  .where('votes', '>', 100)
  .orWhere('name', 'John')
  .get();

// Joins
const users = await DB.table('users')
  .join('contacts', 'users.id', '=', 'contacts.user_id')
  .select('users.*', 'contacts.phone')
  .get();

// Aggregates
const count = await DB.table('users').count();
const max = await DB.table('users').max('votes');

// Chunking results for large datasets
await DB.table('users').chunk(100, async (users) => {
  for (const user of users) {
    // Process user
  }
});

Eloquent Model Examples

// Define models
class User extends Model {
  protected fillable = ['name', 'email'];
  
  posts() {
    return this.hasMany(Post);
  }
  
  roles() {
    return this.belongsToMany(Role);
  }
}

// Basic CRUD
const user = await User.create({ name: 'John', email: 'john@example.com' });
const user = await User.find(1);
await user.update({ name: 'Jane' });
await user.delete();

// Query scopes
const popularUsers = await User.where('votes', '>', 100)
  .orderBy('name')
  .get();

// Eager loading relationships
const users = await User.with(['posts', 'roles']).get();

// Constrained lazy eager loading (v1.12.0)
await user.load({
  posts: query => query.where('published', true).orderBy('created_at', 'desc')
});

// Querying relationships
const userPosts = await user.posts()
  .where('published', true)
  .orderBy('created_at', 'desc')
  .get();

// Touch timestamps (v1.11.0)
await user.touch(); // Update updated_at
await comment.touchOwners(); // Update parent timestamps

// Model observers (v1.10.0)
User.observe({
  creating: (user) => console.log('Creating user...'),
  created: (user) => console.log('User created!'),
  updating: (user) => console.log('Updating user...'),
  updated: (user) => console.log('User updated!')
});

Migration Examples

// Create table
await Schema.create('flights', (table) => {
  table.id();
  table.string('name');
  table.string('airline');
  table.timestamps();
});

// Modify table
await Schema.table('users', (table) => {
  table.string('avatar').nullable();
  table.index('email');
});

// Foreign keys
await Schema.create('posts', (table) => {
  table.id();
  table.foreignId('user_id').constrained().onDelete('cascade');
  table.string('title');
  table.text('body');
  table.timestamps();
});

πŸ”§ CLI Commands

GuruORM provides a powerful command-line interface:

Available Commands

Command Description
npx guruorm migrate Run migrations
npx guruorm migrate:rollback Rollback migrations
npx guruorm migrate:fresh Drop all & re-migrate
npx guruorm migrate:refresh Reset & re-migrate
npx guruorm migrate:status Show migration status
npx guruorm make:migration Create migration
npx guruorm db:seed Run seeders
npx guruorm make:seeder Create seeder
npx guruorm make:factory Create factory
npx guruorm model:prune Prune models

Examples

# Create a migration
npx guruorm make:migration create_users_table --create=users
npx guruorm make:migration add_status_to_users --table=users

# Run migrations
npx guruorm migrate
npx guruorm migrate --force  # Production
npx guruorm migrate --step=1  # Run one migration

# Rollback
npx guruorm migrate:rollback
npx guruorm migrate:rollback --step=2

# Fresh migration with seeding
npx guruorm migrate:fresh --seed

# Create seeder
npx guruorm make:seeder UserSeeder
npx guruorm make:seeder DatabaseSeeder

# Run seeder
npx guruorm db:seed
npx guruorm db:seed --class=UserSeeder
npx guruorm db:seed --force  # Production

# Create factory
npx guruorm make:factory UserFactory --model=User
npx guruorm make:factory PostFactory

# Prune models
npx guruorm model:prune
npx guruorm model:prune --model=OldLog

CLI Features

βœ… Powerful Commands - Intuitive syntax βœ… Flags Support - --force, --step, --class, etc. βœ… Auto-complete Ready - Tab completion support βœ… Helpful Output - Clear success/error messages βœ… File Generators - Create migrations, seeders, factories βœ… Production Guards - Prevents accidental production runs


🌟 Why guruORM?

  • βœ… Elegant API - Clean, expressive syntax
  • βœ… JavaScript & TypeScript - Works with both! No TypeScript required
  • βœ… Type Safety - Optional TypeScript support with intelligent autocompletion
  • βœ… Battle-Tested Patterns - Proven architecture
  • βœ… Production Ready - Comprehensive testing and error handling
  • βœ… Great DX - Clear error messages, helpful documentation, powerful CLI
  • βœ… Zero Config - Install and start coding immediately

Works with Plain JavaScript!

No TypeScript? No Problem!

// Pure JavaScript - No compilation needed
const { Model, DB } = require('guruorm');

class User extends Model {
  constructor() {
    super();
    this.table = 'users';
    this.fillable = ['name', 'email'];
  }
}

// Works perfectly!
const users = await User.where('active', true).get();
const john = await User.find(1);

Feature Coverage

Component Completion Status
Query Builder 98% ⭐⭐⭐⭐⭐
Eloquent ORM 97% ⭐⭐⭐⭐⭐
Relationships 97% ⭐⭐⭐⭐⭐
Schema Builder 90% ⭐⭐⭐⭐
Migrations 90% ⭐⭐⭐⭐
Seeding 95% ⭐⭐⭐⭐⭐
Events & Observers 95% ⭐⭐⭐⭐⭐
Testing Utilities 70% ⭐⭐⭐
Overall ~94% ⭐⭐⭐⭐⭐

⚑ Performance

Faster Than Sequelize in Key Areas

GuruORM uses Active Record pattern, which is lighter and more efficient than Sequelize's Data Mapper pattern.

Memory Efficiency:

// Process 100k records

// Other ORMs - Load all into memory
const users = await OtherORM.findAll({ limit: 100000 }); // πŸ’₯ ~450MB

// GuruORM - Stream with chunking
await User.chunk(1000, (users) => {
  // Process 1000 at a time
}); // ⚑ ~15MB

Cursor Pagination (Constant Speed):

// Offset pagination gets slower with pages
// Page 1: fast, Page 1000: SLOW

// GuruORM cursor pagination - always fast!
const { data, nextCursor } = await User.cursorPaginate(100);
// Same speed on page 1 or page 10,000! πŸš€

Lazy Loading (Stream Processing):

// Memory-efficient streaming
for await (const user of User.lazy()) {
  // Process one at a time, minimal memory
}

Run the benchmark:

node examples/performance-benchmark.js

πŸ“Š View Complete Performance Comparison - Detailed benchmarks vs Sequelize, TypeORM, Prisma, Knex, Objection, MikroORM, Bookshelf


🀝 Contributing

We welcome contributions! Please see CONTRIBUTING.md for details.

⚠️ Important: All contributions must follow our Coding Standards. This ensures consistency and professional quality throughout the codebase.

πŸ“š Documentation

πŸ“ License

guruORM is open-sourced software licensed under the MIT license.

πŸ”— Links

πŸ’– Special Thanks

Inspired by Laravel and Illuminate.


Made with ❀️ by the guruORM team

About

Best ORM for Nodejs | Inspired from Laravel Eloquent

Resources

License

Contributing

Stars

Watchers

Forks

Packages

No packages published