# CLI tool

The bundled migration CLI — generate DDL from your C# models and apply it to PostgreSQL.

## Overview

`Socigy.OpenSource.DB` ships a CLI tool (`Socigy.OpenSource.DB.Tool`) bundled inside the NuGet package. It loads your compiled assembly, inspects all `[Table]`-annotated classes via the `IDbTable` interface, and generates PostgreSQL DDL.

The tool is invoked through an MSBuild target that the package registers automatically — no separate `dotnet tool install` step is needed.

---

## Running the tool

Build your project in the `DB_Migration` configuration to trigger the migration target:

```bash
dotnet build MyApp.DB/MyApp.DB.csproj -c DB_Migration
```

The tool analyses the resulting assembly and writes SQL migration files to a configurable output directory.

---

## What gets generated

For each `[Table]` class the tool emits:

- `CREATE TABLE IF NOT EXISTS` with all columns, types, and `DEFAULT` expressions
- `PRIMARY KEY` constraint
- `FOREIGN KEY` constraints (from `[ForeignKey]`)
- `UNIQUE` constraints (from `[Unique]`)
- `CHECK` constraints (from `[Check]`, `[StringLength]`, `[Min]`, `[Max]`)
- `CREATE SEQUENCE IF NOT EXISTS` for `[AutoIncrement]` columns
- `INSERT … ON CONFLICT DO UPDATE` seed data for `[Table]`-annotated enums and `[FlaggedEnum]` reference tables

---

## Output files

By default, the tool writes to `migrations/` in the project directory. Each run produces a timestamped file, for example:

```plaintext
migrations/
└── 20260501_120000_initial.sql
```

---

## Connection string

Pass the target connection string when applying migrations:

```bash
dotnet run --project Socigy.OpenSource.DB.Tool -- \
  --connection "Host=localhost;Database=myapp;Username=postgres;Password=secret" \
  --assembly MyApp.DB/bin/DB_Migration/net10.0/MyApp.DB.dll
```

---

## Incremental migrations

On subsequent runs the tool compares the current schema against the previously generated baseline and emits only the `ALTER TABLE` / `CREATE` statements needed to bring the database up to date.

Supported drift types:
- New columns (`ALTER TABLE ... ADD COLUMN`)
- Removed columns (`ALTER TABLE ... DROP COLUMN`)
- Type changes (`ALTER TABLE ... ALTER COLUMN ... TYPE`)
- New or removed constraints

---

## Column renames

Use `[Renamed("old_name")]` to tell the tool a column was renamed rather than dropped and re-added:

```csharp
[Renamed("user_name")]
public string Username { get; set; }
```

Without `[Renamed]`, a renamed column is treated as a column drop followed by a column add — data is lost.

---

## Supported platforms

The tool ships two builds inside the package:

| Path in package | Target | Runs on |
|----------------|--------|---------|
| `tools/any/` | `net10.0` (framework-dependent) | Any OS with .NET 10 installed |
| `tools/win/` | `net10.0-windows` | Windows only |

> **NOTE** On Linux CI environments the MSBuild target automatically selects the `tools/any/` build.
