flashorm 2.3.1b0.dev0
A powerful, database-agnostic ORM with multi-database support and type-safe code generation
Requires Python: >=3.7
Keywords: orm, database, migration, postgresql, mysql, sqlite, cli

# FlashORM

A powerful, database-agnostic migration CLI tool built in Go with multi-database support, visual database editor (FlashORM Studio), and type-safe code generation for JavaScript/TypeScript.

## ✨ Features

- 🎨 **FlashORM Studio**: Visual database editor with React-based schema visualization
- 🗃️ **Multi-Database Support**: PostgreSQL, MySQL, SQLite
- 🔄 **Migration Management**: Create, apply, and track migrations
- 🔒 **Safe Migration System**: Transaction-based execution with automatic rollback
- 📤 **Smart Export System**: Multiple formats (JSON, CSV, SQLite)
- 🔧 **Type-Safe Code Generation**: Generate fully typed JavaScript/TypeScript code
- ⚡ **Blazing Fast**: 2.5x faster than Drizzle, 10x faster than Prisma
- 💻 **Raw SQL Execution**: Execute SQL files or inline queries
- 🎯 **Prisma-like Commands**: Familiar CLI interface

## 📊 Performance

FlashORM significantly outperforms popular ORMs in real-world scenarios:

| Operation                                  | FlashORM   | SQLAlchemy  |
| ------------------------------------------ | ---------- | ----------- |
| Insert 1000 Users                          | **16ms**   | **299ms**       |
| Insert 10 Cat + 5K Posts + 15K Comments    | **440ms**  | **1333ms**      |
| Complex Query x500                         | **1199ms** | **10627ms**     |
| Mixed Workload x1000 (75% read, 25% write) | **248ms**  | **645ms**       |
| Stress Test Simple Query x2000             | **338ms**  | **984ms**       |
| **TOTAL**                                  | **2241ms** | **13888ms** |

## 🚀 Installation

Install from PyPI (recommended):

```bash
pip install flashorm
```

## 🏁 Quick Start

### 1. Initialize Project

```bash
flash init --postgresql  # or --mysql, --sqlite
```

This creates:

```
your-project/
├── flash.config.json
├── .env
└── db/
    ├── schema/
    │   └── schema.sql
    └── queries/
        └── users.sql
```

### 2. Configure Database

```bash
# .env file
DATABASE_URL=postgresql://user:password@localhost:5432/mydb
```

### 3. Define Schema

**db/schema/schema.sql**

```sql
CREATE TABLE users (
    id SERIAL PRIMARY KEY,
    name VARCHAR(255) NOT NULL,
    email VARCHAR(255) UNIQUE NOT NULL,
    created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
);
```

### 4. Write Queries

**db/queries/users.sql**

```sql
-- name: GetUser :one
SELECT id, name, email, created_at, updated_at FROM users
WHERE id = $1 LIMIT 1;

-- name: CreateUser :one
INSERT INTO users (name, email)
VALUES ($1, $2)
RETURNING id, name, email, created_at, updated_at;

-- name: ListUsers :many
SELECT id, name, email, created_at, updated_at FROM users
ORDER BY created_at DESC;

-- name: UpdateUser :one
UPDATE users
SET name = $2, email = $3, updated_at = NOW()
WHERE id = $1
RETURNING id, name, email, created_at, updated_at;

-- name: DeleteUser :exec
DELETE FROM users WHERE id = $1;
```

### 5. Create Migration

```bash
flash migrate "create users table"
```

### 6. Apply Migration

```bash
flash apply
```

### 7. Generate Type-Safe Code

```bash
flash gen
```

**Generated Table Types (flash_gen/models.py)**

```py

# Code generated by FlashORM. DO NOT EDIT.

from dataclasses import dataclass
from typing import Optional, Literal
from datetime import datetime
from decimal import Decimal

@dataclass
class Users:
    id: int
    name: str
    email: str
    created_at: datetime
    updated_at: datetime


```

### 8. Use in Your Code

**Async Example (default)**

```python
import asyncio
import asyncpg
import os
from flash_gen.database import new

DATABASE_URL = os.getenv('DATABASE_URL', 'postgresql://postgres:postgres@localhost:5432/FlashORM_test')

async def main():
    pool = await asyncpg.create_pool(DATABASE_URL)

    db = new(pool)

    newuser = await db.create_user('jack', 'jack@gmail.com')
    print('New user:', newuser)

    await pool.close()

if __name__ == '__main__':
    asyncio.run(main())
```

**Sync Example (set `"async": false` in config)**

```python
import psycopg2
import os
from flash_gen.database import new

DATABASE_URL = os.getenv('DATABASE_URL', 'postgresql://postgres:postgres@localhost:5432/FlashORM_test')

def main():
    conn = psycopg2.connect(DATABASE_URL)

    db = new(conn)

    newuser = db.create_user('jack', 'jack@gmail.com')
    print('New user:', newuser)

    conn.close()

if __name__ == '__main__':
    main()
```

## 📋 All Commands

### Visual Database Editor

```bash
# Launch FlashORM Studio (web-based database editor)
flash studio

# Launch on custom port
flash studio --port 3000

# Connect to any database directly
flash studio --db "postgresql://user:pass@localhost:5432/mydb"

# Launch without opening browser
flash studio --browser=false
```

**Studio Features:**

- 📊 **Data Browser**: View and edit table data with inline editing
- 💻 **SQL Editor**: Execute queries with CodeMirror syntax highlighting
- 🎨 **Schema Visualization**: Interactive database diagram with React + ReactFlow
- 🔍 **Search & Filter**: Search across all tables
- ⚡ **Real-time Updates**: See changes immediately

### Project Setup

```bash
# Initialize new project
flash init --postgresql
flash init --mysql
flash init --sqlite
```

### Migrations

```bash
# Create new migration
flash migrate "migration name"

# Create empty migration
flash migrate "custom migration" --empty

# Apply all pending migrations
flash apply

# Apply with force (skip confirmations)
flash apply --force

# Check migration status
flash status
```

### Code Generation

```bash
# Generate type-safe code
flash gen
```

### Schema Management

```bash
# Pull schema from existing database
flash pull

# Pull with backup
flash pull --backup

# Pull to custom file
flash pull --output custom-schema.sql
```

### Database Export

```bash
# Export as JSON (default)
flash export
flash export --json

# Export as CSV
flash export --csv

# Export as SQLite
flash export --sqlite
```

### Database Operations

```bash
# Reset database (destructive!)
flash reset

# Reset with force
flash reset --force

# Execute raw SQL file
flash raw script.sql
flash raw migrations/seed.sql

# Execute inline SQL query
flash raw -q "SELECT * FROM users WHERE active = true"
flash raw "SELECT COUNT(*) FROM orders"

# Force file mode
flash raw --file queries/complex.sql
```

### Help & Info

```bash
# Launch FlashORM Studio
flash studio

# Show version
flash --version
flash -v

# Show help
flash --help
flash <command> --help
```

## ⚙️ Configuration

**flash.config.json**

```json
{
  "version": "2",
  "schema_path": "db/schema/schema.sql",
  "queries": "db/queries/",
  "migrations_path": "db/migrations",
  "export_path": "db/export",
  "database": {
    "provider": "postgresql",
    "url_env": "DATABASE_URL"
  },
  "gen": {
    
    "python": {
      "enabled": true,
      "async": false
    }
  }
}
```

**Python Generation Options:**

- `async`: Set to `true` for async/await code generation (default), `false` for synchronous code generation.

## 🎨 PostgreSQL ENUM Support

**Schema with ENUMs**

```sql
CREATE TYPE user_role AS ENUM ('admin', 'user', 'guest');

CREATE TABLE users (
    id SERIAL PRIMARY KEY,
    name VARCHAR(255) NOT NULL,
    role user_role NOT NULL DEFAULT 'user'
);
```

## 🔒 Safe Migrations

Every migration runs in a transaction with automatic rollback on failure:

```bash
$ flash apply
📦 Applying 2 migration(s)...
  [1/2] 20251103_create_users
      ✅ Applied
  [2/2] 20251103_add_email_index
      ✅ Applied
✅ All migrations applied successfully
```

If a migration fails:

```bash
❌ Failed at migration: 20251103_bad_migration
   Error: syntax error at or near "INVALID"
   Transaction rolled back. Fix the error and run 'flash apply' again.
```

## 🛡️ Conflict Detection

FlashORM automatically detects schema conflicts:

```bash
⚠️  Migration conflicts detected:
  - Table 'users' already exists
  - Column 'email' conflicts with existing column

Reset database to resolve conflicts? (y/n): y
Create export before applying? (y/n): y
📦 Creating export...
✅ Export created successfully
🔄 Resetting database and applying all migrations...
```

## 📤 Export Formats

### JSON Export

```bash
flash export --json
```

```json
{
  "timestamp": "2025-11-03 16:30:00",
  "version": "1.0",
  "tables": {
    "users": [{ "id": 1, "name": "Alice", "email": "alice@example.com" }]
  }
}
```

### CSV Export

```bash
flash export --csv
```

Creates directory with individual CSV files per table.

### SQLite Export

```bash
flash export --sqlite
```

Creates portable `.db` file.

## 🎨 FlashORM Studio

Launch the visual database editor:

```bash
flash studio
```

Open http://localhost:5555 (or your custom port)

**Features:**

### 1. Data Browser (`/`)

- View all tables in sidebar
- Click any table to view/edit data
- Double-click cells for inline editing
- Add/delete rows with intuitive modals
- Pagination (50 rows per page)
- Search across tables
- Foreign key hints

### 2. SQL Editor (`/sql`)

- Execute custom SQL queries
- CodeMirror editor with syntax highlighting
- Press Ctrl+Enter to run queries
- Export results to CSV
- Resizable split-pane interface
- Query history

### 3. Schema Visualization (`/schema`)

- Interactive database diagram
- React + ReactFlow rendering
- Automatic layout with Dagre algorithm
- Drag and drop tables
- Zoom and pan controls
- Foreign key relationship arrows
- MiniMap for navigation

## 💻 Raw SQL Execution

Execute SQL files or inline queries:

```bash
# Execute SQL file
flash raw script.sql

# Execute inline query
flash raw -q "SELECT * FROM users LIMIT 10"

# Auto-detection (file if exists, otherwise query)
flash raw "SELECT COUNT(*) FROM orders"
```

**Features:**

- ✅ Beautiful table output for SELECT queries
- ✅ Multi-statement execution
- ✅ Transaction support
- ✅ Auto-detection of file vs query
- ✅ Formatted error messages

**Example Output:**

```bash
$ flash raw -q "SELECT id, name, email FROM users LIMIT 3"

🎯 Database: postgresql

⚡ Executing query...
✅ Query executed successfully
📊 3 row(s) returned

┌────┬────────────┬─────────────────────┐
│ id │ name       │ email               │
├────┼────────────┼─────────────────────┤
│ 1  │ Alice      │ alice@example.com   │
│ 2  │ Bob        │ bob@example.com     │
│ 3  │ Charlie    │ charlie@example.com │
└────┴────────────┴─────────────────────┘
```

d

## 📚 Examples

Check out complete examples:

- [Python Example](https://github.com/Lumos-Labs-HQ/flash/tree/main/example/python)
- [TypeScript Example](https://github.com/Lumos-Labs-HQ/flash/tree/main/example/ts)
- [Go Example](https://github.com/Lumos-Labs-HQ/flash/tree/main/example/go)

## 🐛 Troubleshooting

### Bun Postinstall Blocked

```bash
bun pm trust flashorm
```

### Binary Not Found

```bash
npm install -g flashorm --force
```

### Database Connection Failed

Check your `DATABASE_URL` in `.env` file.

### Studio Not Loading

Make sure port 5555 is not in use, or specify a different port:

```bash
flash studio --port 3000
```

## 📖 Documentation

- [Full Documentation](https://github.com/Lumos-Labs-HQ/flash)
- [How It Works](https://github.com/Lumos-Labs-HQ/flash/blob/main/docs/HOW_IT_WORKS.md)
- [Technology Stack](https://github.com/Lumos-Labs-HQ/flash/blob/main/docs/TECHNOLOGY_STACK.md)
- [Contributing](https://github.com/Lumos-Labs-HQ/flash/blob/main/docs/CONTRIBUTING.md)

## 🌟 Key Highlights

- **Visual Database Editor**: Manage your database visually with FlashORM Studio
- **Raw SQL Support**: Execute SQL files or queries directly from CLI
- **Type-Safe**: Full TypeScript support with generated types
- **Fast**: 2.5x-10x faster than popular ORMs
- **Multi-DB**: PostgreSQL, MySQL, and SQLite support
- **Zero Config**: Works out of the box with sensible defaults

## 📄 License

MIT License - see [LICENSE](https://github.com/Lumos-Labs-HQ/flash/blob/main/LICENSE)

---