---
paths: "**/*.sql,docs/service-auto/migrations/**"
---

# Oracle SQL Migration Script Rules

You are an Oracle SQL migration script writer. Transform raw DDL/DML into idempotent migration scripts following these rules:

## STRUCTURE
- Header comment: `-- brief description` (e.g. `-- adaugare coloana nom_firme.caen_revizie`)
- Body (idempotency rules below)
- Footer: `exec pack_migrare.UpdateVersiune('<filename_without_.sql>'); commit;`

## IDEMPOTENCY RULES

1. **ALTER TABLE ADD COLUMN** → wrap in:
   ```sql
   BEGIN
     IF PACK_MIGRARE.COLUMNEXIST('TABLE','COL')=0 THEN
       EXECUTE IMMEDIATE '...';
     END IF;
   END;
   /
   ```

2. **CREATE OR REPLACE VIEW/PROCEDURE/FUNCTION** → keep as-is (already idempotent)

3. **INSERT** → replace with:
   ```sql
   MERGE INTO table USING DUAL ON (key condition)
   WHEN NOT MATCHED THEN INSERT (cols) VALUES (vals);
   ```

4. **UPDATE** → keep as-is

5. **CREATE TABLE** → wrap in:
   ```sql
   BEGIN
     IF PACK_MIGRARE.OBJECTEXIST('TABLE','TABLE')=0 THEN
       EXECUTE IMMEDIATE '...';
     END IF;
   END;
   /
   ```

6. **DROP** → wrap in:
   ```sql
   BEGIN
     IF PACK_MIGRARE.OBJECTEXIST('OBJ')=1 THEN
       EXECUTE IMMEDIATE 'DROP...';
     END IF;
   END;
   /
   ```

7. **COMMENT ON** → keep as plain DDL (not inside EXECUTE IMMEDIATE)

8. In MERGE/INSERT: omit NULL-valued columns and CLOB columns entirely

## FILENAME CONVENTION

```
ff_YYYY_MM_DD_NN_<MODULE>.sql
```
- `YYYY_MM_DD` — data migrării
- `NN` — secvență 2 cifre (01, 02...)
- `<MODULE>` — modulul căruia îi aparține migrarea (ex: AUTO, FACTURARE, CONTAB)

## LANGUAGE
Comments: write in Romanian.
Output: only the SQL script, no explanation.
