Metadata-Version: 2.4
Name: fastpluggy-sql-migration
Version: 0.1.15
Summary: SQL Migration plugin for FastPluggy - Simple per-plugin SQL migration system
Author: FastPluggy Team
License-Expression: MIT
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: FastPluggy<1,>=0.4.115
Requires-Dist: loguru
Provides-Extra: tests
Requires-Dist: pytest>=7.0; extra == "tests"
Requires-Dist: pytest-cov>=4.0; extra == "tests"
Provides-Extra: e2e
Requires-Dist: fastpluggy-cli; extra == "e2e"
Requires-Dist: playwright>=1.40.0; extra == "e2e"
Dynamic: license-file

# FastPluggy Plugin SQL Migration System

![SQL Migration](https://img.shields.io/badge/FastPluggy-SQL%20Migration-blue)
[![Release](https://gitlab.ggcorp.fr/open/fastpluggy/plugins/sql_migration/-/badges/release.svg)](https://gitlab.ggcorp.fr/open/fastpluggy/plugins/sql_migration/-/releases)
[![Pipeline Status](https://gitlab.ggcorp.fr/open/fastpluggy/plugins/sql_migration/badges/main/pipeline.svg?key_text=CI)](https://gitlab.ggcorp.fr/open/fastpluggy/plugins/sql_migration/-/pipelines?ignore_skipped=true)
[![Coverage](https://gitlab.ggcorp.fr/open/fastpluggy/plugins/sql_migration/badges/main/coverage.svg)](https://gitlab.ggcorp.fr/open/fastpluggy/plugins/sql_migration/-/pipelines)

This module provides a **simple SQL-based migration system** for plugins in the FastPluggy framework.  
Each plugin can manage its own set of `.sql` migration files independently, with version tracking and isolated execution.

---

## ✨ Features

### 🔧 Core Migration Engine
- ✅ **Per-plugin migrations** — Each plugin manages its own `migrations/` folder independently
- ✅ **Ordered execution** — Files are sorted and executed in numeric version order
- ✅ **Smart discovery** — Automatic detection of migration files across all plugins
- ✅ **Transactional safety** — Each migration runs in its own transaction with rollback support
- ✅ **Validation system** — File naming, SQL syntax, and content validation
- ✅ **Error handling** — Comprehensive error tracking with detailed messages

### 📊 Advanced Tracking & Monitoring
- ✅ **Central version tracking** — All migrations stored in a comprehensive database table
- ✅ **Status management** — Track pending, running, success, and failed states
- ✅ **Performance metrics** — Execution time tracking and statistics
- ✅ **Audit trail** — Complete history of all migration executions
- ✅ **Real-time statistics** — System-wide migration stats and success rates

### 🎨 Professional Web Interface
- ✅ **Modern dashboard** — Clean, responsive interface with Tabler.io styling
- ✅ **Plugin management** — Visual overview of all plugins and their migration status
- ✅ **Migration control** — Run individual migrations or bulk operations
- ✅ **Detailed logging** — Comprehensive logs with search and filtering
- ✅ **API endpoints** — JSON APIs for automation and integration

### 🚀 Advanced Operations
- ✅ **Bulk execution** — Run all pending migrations across all plugins
- ✅ **Migration validation** — Validate all migration files before execution
- ✅ **Auto-discovery** — Scan and discover new migration files automatically
- ✅ **FastPluggy integration** — Seamless integration with authentication and menu system

---

## 📁 Plugin Folder Structure

The `migrations/` directory sits next to the plugin's `plugin.py`:

```
src/                      # package-dir of fastpluggy_plugin.<plugin_name>
├── plugin.py
└── migrations/
    ├── 001_create_posts_table.sql
    ├── 002_add_index_to_title.sql
    └── ...
```

The same directory is found in a source checkout and in an installed wheel
(`site-packages/fastpluggy_plugin/<plugin_name>/migrations/`), so the wheel must ship it as package
data:

```toml
[tool.setuptools.package-data]
"fastpluggy_plugin.<plugin_name>" = ["migrations/*.sql"]
```

A plugin folder whose code is not in `src/` keeps its files in `<plugin folder>/src/migrations/`.

**Naming Convention**: Files must be named with a 3-digit numeric prefix followed by an underscore and description (e.g., `001_description.sql`) for proper ordering and validation.

---

## 🧪 Installation & Usage

### Installation

The SQL Migration plugin is included as part of the FastPluggy framework. To use it:

1. **Ensure FastPluggy is installed** with the sql_migration plugin enabled
2. **Plugin Auto-Discovery**: The plugin will be automatically discovered and loaded by FastPluggy
3. **Database Setup**: The plugin will automatically create the necessary migration tracking tables on first load
4. **Access the Interface**: Navigate to the admin panel and look for "SQL Migration" in the menu

**Manual Installation** (if needed):
```bash
# If installing from source
cd src/fastpluggy_plugin/sql_migration
pip install -e .
```

**Dependencies**: 
- FastPluggy framework
- SQLAlchemy
- FastAPI
- Loguru

### Usage

#### Via Web Interface

1. **Access the Dashboard**: Navigate to `/sql-migration/` in your FastPluggy admin panel
2. **View System Overview**: See migration statistics, plugin status, and recent activity
3. **Manage Plugins**: Go to "Manage Plugins" to see per-plugin migration status
4. **Run Migrations**: 
   - Use "Run All Pending Migrations" for bulk execution
   - Or run individual migrations from the migration management page
5. **Monitor Logs**: Check the logs section for detailed execution history

#### Plugin Directory Structure

Place your migration files in the `migrations/` directory next to your plugin's `plugin.py`
(see [Plugin Folder Structure](#-plugin-folder-structure)).

#### Migration File Format

```sql
-- 001_create_users_table.sql
CREATE TABLE users (
    id SERIAL PRIMARY KEY,
    username VARCHAR(50) UNIQUE NOT NULL,
    email VARCHAR(100) UNIQUE NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

CREATE INDEX idx_users_username ON users(username);
```

#### API Endpoints

**Web Interface Endpoints:**
- `GET /sql-migration/` - Dashboard
- `GET /sql-migration/plugins` - Plugin management
- `GET /sql-migration/migrations` - Migration management  
- `GET /sql-migration/logs` - Execution logs
- `GET /sql-migration/discover` - Discover new migrations
- `GET /sql-migration/validate-all` - Validate all migration files

**Migration Execution Endpoints:**
- `POST /sql-migration/run-migration/{plugin_name}/{version}` - Execute specific migration
- `POST /sql-migration/run-all-pending` - Execute all pending migrations

**JSON API Endpoints:**
- `GET /sql-migration/api/migration-status` - JSON API for migration status data
- `GET /sql-migration/api/migration-logs` - JSON API for migration logs with filtering


---


## 🛣 Roadmap

### ✅ Completed Features
- ✅ **Core Migration Engine**: Support `.sql` files with numeric order
- ✅ **Version Tracking**: Track migration version per plugin with comprehensive metadata
- ✅ **Smart Execution**: Auto-skip already-applied migrations
- ✅ **Transactional Safety**: Transactional `.sql` execution with rollback support
- ✅ **FastPluggy Integration**: Seamless plugin integration with authentication
- ✅ **Web Admin Interface**: Complete dashboard with migration management
- ✅ **Advanced Logging**: Detailed execution logs with performance metrics
- ✅ **Migration Validation**: File naming, SQL syntax, and content validation
- ✅ **Statistics & Monitoring**: Real-time stats, recent activity, and status tracking
- ✅ **Bulk Operations**: Run all pending migrations across plugins
- ✅ **Error Handling**: Comprehensive error tracking and reporting
- ✅ **API Endpoints**: JSON APIs for integration and automation

### 🛠️ Future Enhancements
- [ ] Real-time WebSocket updates for migration progress
- [ ] Migration file content editor in web interface
- [ ] Optional `.down.sql` support for development rollbacks
- [ ] CLI commands for `migrate all` or `migrate plugin-name`
- [ ] Migration dependency management between plugins
- [ ] Scheduled migration execution
- [ ] Migration backup and restore functionality

---

## 🎨 Web Interface Features

The plugin includes a comprehensive web administration interface built with modern Tabler.io framework:

### 📊 Dashboard
- **System Overview**: Statistics cards showing total plugins, pending/applied/failed migrations
- **Recent Activity Feed**: Real-time view of latest migration executions with status indicators
- **Quick Actions**: One-click button to run all pending migrations across all plugins
- **Performance Metrics**: Average execution times and success rates

### 🔧 Plugin Management
- **Plugin Status Table**: Complete overview of each plugin's migration status
- **Migration Progress**: Visual indicators showing applied vs pending migrations
- **Bulk Operations**: Discover new migrations across all plugins
- **Status Badges**: Color-coded indicators (Up-to-date, Has Failures, Pending)

### 📋 Migration Management
- **Comprehensive Migration List**: All migrations across all plugins with detailed status
- **File-Level Details**: Individual migration files with execution timestamps
- **Execution Controls**: Run individual migrations or validate all migration files
- **Content Viewer**: View SQL content and execution details
- **Status Tracking**: Visual indicators (Applied, Failed, Pending)

### 📝 Migration Logs
- **Detailed Execution History**: Complete audit trail of all migration runs
- **Advanced Filtering**: Filter by plugin, status, or time period
- **Error Details**: Full error messages and SQL content for failed migrations
- **Performance Data**: Execution times and detailed timing information
- **Export Capabilities**: Download logs for external analysis

### 🎨 Design Highlights
- **Modern Interface**: Professional Tabler.io styling with responsive design
- **Intuitive Navigation**: Clear menu structure with breadcrumb navigation
- **Status-Driven UI**: Consistent color coding and icons for quick recognition
- **Action-Oriented**: Context-appropriate buttons and bulk operation controls
- **Real-time Updates**: Live status updates and activity feeds

---

## 📜 License


Released under the MIT License, see [LICENSE](LICENSE).

## 🤝 Contributions

Feel free to open issues or PRs to improve functionality.  
Let’s build a solid, plugin-friendly migration ecosystem together!
