@darkj/create-db 1.0.0 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,60 +1,61 @@
1
- Creá una nueva migración para este proyecto siguiendo el formato de carpetas.
1
+ Create a new migration for this project following the folder format.
2
2
 
3
- ## Paso 1 — Determinar el número siguiente
3
+ ## Step 1 — Determine the next number
4
4
 
5
- Listá las carpetas en `migrations/` en orden alfabético.
6
- El próximo número es el último + 1, con ceros a la izquierda (ej: si existe `004_...`, el siguiente es `005`).
5
+ List the folders in `migrations/` in alphabetical order.
6
+ The next number is the last one + 1, zero-padded (e.g. if `004_...` exists, the next is `005`).
7
7
 
8
- ## Paso 2 — Obtener información
8
+ ## Step 2 — Get information
9
9
 
10
- Si el usuario no la dio, preguntá:
11
- - ¿Qué cambio se quiere hacer?
12
- - ¿Hay contexto o razón detrás del cambio? (para decidir si crear README.md)
10
+ If the user didn't provide it, ask:
11
+ - What change do you want to make?
12
+ - Is there context or a reason behind the change? (to decide whether to create a README.md)
13
13
 
14
- Si el usuario pasó un script SQL directamente, usarlo como base para `up.sql` — ordenarlo y limpiarlo si hace falta.
14
+ If the user passed a SQL script directly, use it as the base for `up.sql` — order and clean it up if needed.
15
15
 
16
- ## Paso 3 — Crear la carpeta
16
+ ## Step 3 — Create the folder
17
17
 
18
- Nombre: `NNN_YYYYMMDD_HHMM_proposito_breve`
19
- - Fecha y hora actuales
20
- - Propósito en snake_case, breve (3-5 palabras máximo)
18
+ Name: `NNN_YYYYMMDD_HHMM_short_purpose`
19
+ - Current date and time
20
+ - Purpose in snake_case, short (3-5 words max)
21
21
 
22
22
  ```
23
- migrations/NNN_YYYYMMDD_HHMM_proposito_breve/
23
+ migrations/NNN_YYYYMMDD_HHMM_short_purpose/
24
24
  ├── up.sql
25
25
  ├── down.sql
26
- └── README.md ← solo si hay contexto claro
26
+ └── README.md ← only if there's clear context
27
27
  ```
28
28
 
29
- ## Paso 4 — Escribir up.sql
29
+ ## Step 4 — Write up.sql
30
30
 
31
- Aplicar el checklist:
32
- - ¿Columna NOT NULL nueva? → necesita DEFAULT o backfill previo
33
- - ¿Eliminás columna con datos? → primero migrar datos, luego DROP
34
- - ¿FK nueva? → la tabla referenciada ya debe existir
35
- - ¿Índice en tabla grande? → sugerir CONCURRENTLY
31
+ Apply the checklist:
32
+ - New NOT NULL column? → needs a DEFAULT or a prior backfill
33
+ - Dropping a column with data? → migrate the data first, then DROP
34
+ - New FK? → the referenced table must already exist
35
+ - Index on a large table? → suggest CONCURRENTLY
36
36
 
37
- ## Paso 5 — Escribir down.sql
37
+ ## Step 5 — Write down.sql
38
38
 
39
- SQL inverso al up.sql. Debe dejar la DB en el estado anterior exactamente.
40
- Siempre escribirlo, aunque el usuario no lo haya pedido.
39
+ SQL that reverses up.sql. It must leave the DB exactly in its previous state.
40
+ Always write it, even if the user didn't ask for it.
41
41
 
42
- ## Paso 6 — Crear README.md (solo si hay contexto)
42
+ ## Step 6 — Create README.md (only if there's context)
43
43
 
44
- Si la migración fue planeada o el usuario explicó la razón:
44
+ If the migration was planned or the user explained the reason:
45
45
  ```markdown
46
- # proposito_breve
46
+ # short_purpose
47
47
 
48
- {1-3 líneas del por qué, no del qué.}
48
+ {1-3 lines about why, not what.}
49
49
  ```
50
50
 
51
- Si el usuario pasó el script sin contexto: no crear README.md.
51
+ If the user passed the script with no context: don't create README.md.
52
52
 
53
- ## Paso 7 — Actualizar schema/
53
+ ## Step 7 — Update schema/
54
54
 
55
- Identificá qué archivos `create.sql` en `schema/` quedan desactualizados y actualizalos para reflejar el nuevo estado de las tablas afectadas.
55
+ Identify which `create.sql` files in `schema/` are now outdated and update them to reflect the
56
+ new state of the affected tables.
56
57
 
57
- ## Paso 8 — Mostrar el comando para aplicar
58
+ ## Step 8 — Show the command to apply it
58
59
 
59
60
  ```bash
60
61
  npm run migrate
@@ -3,109 +3,116 @@ paths:
3
3
  - "migrations/**"
4
4
  ---
5
5
 
6
- # Reglas para trabajar en migrations/
6
+ # Rules for working in migrations/
7
7
 
8
- ## Principio fundamental
8
+ ## Fundamental principle
9
9
 
10
- `migrations/` es **append-only** e **inmutable**. Solo se agregan carpetas nuevas al final.
11
- Nunca editar `up.sql` de una migración ya aplicada si hay un error, crear una nueva migración que lo corrija.
10
+ `migrations/` is **append-only** and **immutable**. Only new folders get added, at the end.
11
+ Never edit the `up.sql` of an already-applied migrationif there's a mistake, create a new
12
+ migration that fixes it.
12
13
 
13
- ## Estructura de cada migración
14
+ ## Structure of each migration
14
15
 
15
- Cada migración es una **carpeta**, no un archivo suelto:
16
+ Each migration is a **folder**, not a loose file:
16
17
 
17
18
  ```
18
19
  migrations/
19
- └── NNN_YYYYMMDD_HHMM_proposito_breve/
20
- ├── up.sql ← cambios a aplicar (obligatorio)
21
- ├── down.sql ← cómo revertirlos (obligatorio)
22
- └── README.md ← contexto y razón (solo si fue planeado o tiene contexto claro)
20
+ └── NNN_YYYYMMDD_HHMM_short_purpose/
21
+ ├── up.sql ← changes to apply (required)
22
+ ├── down.sql ← how to revert them (required)
23
+ └── README.md ← context and reason (only if it was planned or has clear context)
23
24
  ```
24
25
 
25
- ## Naming de la carpeta
26
+ ## Folder naming
26
27
 
27
28
  ```
28
- NNN_YYYYMMDD_HHMM_proposito_breve
29
+ NNN_YYYYMMDD_HHMM_short_purpose
29
30
  ```
30
31
 
31
- - `NNN` — número secuencial con ceros (`001`, `002`, `003`...)
32
- - `YYYYMMDD` — fecha de creación
33
- - `HHMM` — hora de creación
34
- - `proposito_breve` — descripción corta en `snake_case`
32
+ - `NNN` — sequential number with leading zeros (`001`, `002`, `003`...)
33
+ - `YYYYMMDD` — creation date
34
+ - `HHMM` — creation time
35
+ - `short_purpose` — short description in `snake_case`
35
36
 
36
- Ejemplos:
37
+ Examples:
37
38
  - `003_20260524_1430_add_phone_to_users`
38
39
  - `004_20260525_0900_create_index_orders_status`
39
40
  - `005_20260526_1100_rename_column_amount_to_total`
40
41
  - `006_20260527_1600_drop_deprecated_sessions`
41
42
 
42
- ## up.sql — los cambios
43
+ ## up.sql — the changes
43
44
 
44
- SQL que transforma la DB del estado anterior al nuevo. Es lo que `npm run migrate` ejecuta.
45
+ SQL that transforms the DB from the previous state to the new one. This is what `npm run migrate` runs.
45
46
 
46
- ## down.sql — el reverso
47
+ ## down.sql — the reverse
47
48
 
48
- SQL inverso al `up.sql`. Debe dejar la DB exactamente como estaba antes de aplicar esta migración.
49
- Siempre escribirlo aunque no se planee usarloes la documentación del efecto contrario.
49
+ SQL that reverses `up.sql`. It must leave the DB exactly as it was before this migration was applied.
50
+ Always write it even if it's not planned to be used it documents the opposite effect.
50
51
 
51
- ## README.md — contexto (opcional)
52
+ ## README.md — context (optional)
52
53
 
53
- Solo crearlo si la migración fue **planeada** o tiene **contexto conocido** (decisión de negocio, bug fix, refactor coordinado).
54
- Si el usuario pasa un script sin contexto, generar solo `up.sql` y `down.sql`, sin `README.md`.
54
+ Only create it if the migration was **planned** or has **known context** (business decision, bug
55
+ fix, coordinated refactor). If the user passes a script with no context, generate only `up.sql`
56
+ and `down.sql`, without `README.md`.
55
57
 
56
- Formato del README.md:
58
+ README.md format:
57
59
  ```markdown
58
- # proposito_breve
60
+ # short_purpose
59
61
 
60
- {1-3 líneas explicando por qué se hace este cambio, no qué hace el SQL.}
62
+ {1-3 lines explaining why this change is being made, not what the SQL does.}
61
63
  ```
62
64
 
63
- ## Checklist antes de escribir up.sql
65
+ ## Checklist before writing up.sql
64
66
 
65
- 1. ¿El cambio afecta datos existentes? → incluir `UPDATE`/backfill antes del `ALTER`
66
- 2. ¿Se agrega columna `NOT NULL`?necesita `DEFAULT` o backfill previo
67
- 3. ¿Se elimina columna con datos? → primero migrar los datos, luego `DROP`
68
- 4. ¿Hay FK nueva? → la tabla referenciada ya debe existir
69
- 5. ¿Se crea índice en tabla grande? → considerar `CREATE INDEX CONCURRENTLY`
70
- 6. ¿El SQL es idempotente donde sea posible? → usar `IF NOT EXISTS`, `IF EXISTS`, `CREATE OR REPLACE`
67
+ 1. Does the change affect existing data? → include `UPDATE`/backfill before the `ALTER`
68
+ 2. Adding a `NOT NULL` column? needs a `DEFAULT` or a prior backfill
69
+ 3. Dropping a column with data? → migrate the data first, then `DROP`
70
+ 4. New FK? → the referenced table must already exist
71
+ 5. Creating an index on a large table? → consider `CREATE INDEX CONCURRENTLY`
72
+ 6. Is the SQL idempotent where possible? → use `IF NOT EXISTS`, `IF EXISTS`, `CREATE OR REPLACE`
71
73
 
72
- ## Cómo aplica npm run migrate
74
+ ## How npm run migrate applies changes
73
75
 
74
- 1. Conecta a la DB leyendo `.env`
75
- 2. Crea tabla `_migrations` si no existe
76
- 3. Lista las **carpetas** de `migrations/` en orden alfabético
77
- 4. Ejecuta `up.sql` de las carpetas no registradas en `_migrations`
78
- 5. Registra el **nombre de la carpeta** con timestamp al aplicarla
79
- 6. Cada migración se ejecuta en una transacción si falla, hace ROLLBACK y para
76
+ 1. Connects to the DB by reading `.env`
77
+ 2. Creates the `migrations` tracking table if it doesn't exist (named to match the convention
78
+ TypeORM/NestJS uses, no leading underscore)
79
+ 3. Lists the **folders** in `migrations/` in alphabetical order
80
+ 4. Runs the `up.sql` of the folders not yet registered in the `migrations` table
81
+ 5. Registers each **folder name** with a timestamp once applied
82
+ 6. The whole run is **one transaction** — if any migration in the batch fails, every migration
83
+ applied earlier in that same run is rolled back too, not just the failing one
80
84
 
81
- ## También actualizar schema/
85
+ ## Also update schema/
82
86
 
83
- Al crear una migración, actualizar también el `create.sql` correspondiente en `schema/` para que refleje el estado actual. `schema/` es el diseño vigente; `migrations/` es cómo llegamos ahí.
87
+ When creating a migration, also update the corresponding `create.sql` in `schema/` so it reflects
88
+ the current state. `schema/` is the current design; `migrations/` is how we got there.
84
89
 
85
- ## Cómo revertir migraciones (npm run rollback)
90
+ ## How to revert migrations (npm run rollback)
86
91
 
87
- `rollback.ts` elimina el registro de `_migrations` y luego ejecuta el `down.sql` dentro de la misma transacción — en ese orden, para que si el `down.sql` dropa la tabla `_migrations`, la transacción igual cierre limpia.
92
+ `rollback.ts` deletes each `migrations` table record and then runs its `down.sql`, in that order,
93
+ so that if a `down.sql` drops the `migrations` table itself, the transaction still closes cleanly.
88
94
 
89
95
  ```bash
90
- # Revertir la última migración aplicada
96
+ # Revert the last applied migration
91
97
  npm run rollback
92
98
 
93
- # Revertir las últimas N migraciones (en orden inverso)
99
+ # Revert the last N migrations (in reverse order)
94
100
  npm run rollback 3
95
101
  ```
96
102
 
97
- Cómo funciona:
98
- 1. Verifica que la tabla `_migrations` existasi no, no hay nada que revertir
99
- 2. Consulta `_migrations ORDER BY migration DESC` para obtener las últimas N
100
- 3. Por cada una, en transacción: `DELETE FROM _migrations` ejecuta `down.sql` → `COMMIT`
101
- 4. Si `down.sql` falla, hace `ROLLBACK` y para
103
+ How it works:
104
+ 1. Checks that the `migrations` table exists if not, there's nothing to revert
105
+ 2. Queries `migrations ORDER BY migration DESC` to get the last N
106
+ 3. Wraps the whole batch in **one transaction**: for each one, `DELETE FROM migrations` → runs
107
+ `down.sql`; if any step fails, everything reverted so far in that run rolls back too
108
+ 4. Commits once, only after every migration in the batch reverted successfully
102
109
 
103
- **El `down.sql` debe existir.** Si no existe, el script para sin revertir nada.
110
+ **`down.sql` must exist.** If it doesn't, the script stops without reverting anything.
104
111
 
105
- ## Error común
112
+ ## Common error
106
113
 
107
- Si `npm run migrate` dice que ya está al día pero los cambios no aparecen:
114
+ If `npm run migrate` says it's up to date but the changes don't show up:
108
115
  ```sql
109
- DELETE FROM _migrations WHERE migration = 'NNN_YYYYMMDD_HHMM_nombre';
116
+ DELETE FROM migrations WHERE migration = 'NNN_YYYYMMDD_HHMM_name';
110
117
  ```
111
- Luego volver a correr `npm run migrate`. O crear una nueva migración con el cambio faltante.
118
+ Then run `npm run migrate` again. Or create a new migration with the missing change.