@prisma-psm/core 1.0.5 → 1.0.6

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.
Files changed (41) hide show
  1. package/README.en.md +189 -0
  2. package/README.md +98 -99
  3. package/README.pt.md +196 -0
  4. package/package.json +6 -3
  5. package/src/configs.d.ts +2 -0
  6. package/src/configs.d.ts.map +1 -1
  7. package/src/configs.ts +2 -0
  8. package/src/driver.d.ts +26 -7
  9. package/src/driver.d.ts.map +1 -1
  10. package/src/driver.ts +33 -4
  11. package/src/launcher/commands/{migrate.d.ts → commit.d.ts} +1 -1
  12. package/src/launcher/commands/commit.d.ts.map +1 -0
  13. package/src/launcher/commands/{migrate.js → commit.js} +8 -6
  14. package/src/launcher/commands/commit.js.map +1 -0
  15. package/src/launcher/commands/{migrate.ts → commit.ts} +6 -5
  16. package/src/launcher/commands/deploy.d.ts.map +1 -1
  17. package/src/launcher/commands/deploy.js +11 -3
  18. package/src/launcher/commands/deploy.js.map +1 -1
  19. package/src/launcher/commands/deploy.ts +11 -4
  20. package/src/launcher/commands/generate.d.ts.map +1 -1
  21. package/src/launcher/commands/generate.js +1 -1
  22. package/src/launcher/commands/generate.js.map +1 -1
  23. package/src/launcher/commands/generate.ts +1 -2
  24. package/src/launcher/index.js +25 -3
  25. package/src/launcher/index.js.map +1 -1
  26. package/src/launcher/index.ts +1 -4
  27. package/src/tools/deploy.d.ts +1 -0
  28. package/src/tools/deploy.d.ts.map +1 -1
  29. package/src/tools/deploy.js +151 -0
  30. package/src/tools/deploy.js.map +1 -1
  31. package/src/tools/deploy.ts +135 -0
  32. package/src/tools/generate.d.ts.map +1 -1
  33. package/src/tools/generate.js +9 -4
  34. package/src/tools/generate.js.map +1 -1
  35. package/src/tools/generate.ts +10 -5
  36. package/src/tools/migrate.d.ts.map +1 -1
  37. package/src/tools/migrate.js +22 -4
  38. package/src/tools/migrate.js.map +1 -1
  39. package/src/tools/migrate.ts +25 -5
  40. package/src/launcher/commands/migrate.d.ts.map +0 -1
  41. package/src/launcher/commands/migrate.js.map +0 -1
package/README.en.md ADDED
@@ -0,0 +1,189 @@
1
+ # PSM - Prisma Safe Migrate
2
+
3
+ ## Description
4
+
5
+ **PSM (Prisma Safe Migrate)** is an advanced tool for generating and safely applying SQL migrations based on the Prisma model. Its main objective is to ensure that database changes are applied without risk of data loss, something that Prisma's standard migration system does not fully guarantee.
6
+
7
+ ---
8
+
9
+ ## Motivation
10
+
11
+ Database migrations are critical processes that need to preserve the integrity of existing data. Prisma provides an efficient migration system, but it does not guarantee absolute data loss due to complex changes, such as renaming columns, changing data types, or dropping tables.
12
+
13
+ PSM fills this gap by creating an extra layer of validation, strict revision control, and safe incremental application in production environments.
14
+
15
+ ---
16
+
17
+ ## Installation
18
+
19
+ Install the PSM packages as development dependencies in your project:
20
+
21
+ ```bash
22
+ npm install --save-dev @prisma-psm/core @prisma-psm/pg
23
+ ```
24
+
25
+ ---
26
+
27
+ ## Configuration
28
+
29
+ In your `schema.prisma` file, configure the PSM generator to generate the SQL files and connect to the database:
30
+
31
+ ```prisma
32
+ generator psm {
33
+ provider = "psm generate"
34
+ output = "./psm/"
35
+ driver = "@prisma-psm/pg"
36
+ url = env("DATABASE_URL")
37
+ }
38
+ ```
39
+
40
+ - **provider**: PSM generator that replaces Prisma's default migration generator.
41
+ - **output**: directory where the SQL files and PSM artifacts will be generated. - **driver**: Database-specific driver (e.g., PostgreSQL).
42
+ - **url**: Environment variable containing the database connection string.
43
+
44
+ ---
45
+
46
+ ## How it works - General flow
47
+
48
+ ### 1. Migration generation (`npx prisma generate`)
49
+
50
+ - Generates Prisma artifacts normally.
51
+ - Generates two main files in the `next` folder:
52
+ - `migration.next.check.sql`: Script to validate whether the migration is consistent with the current database.
53
+ - `migration.next.sql`: Script that will apply the changes.
54
+ - If `DATABASE_URL` is configured:
55
+ - Automatically executes the check script.
56
+ - If successful: Keeps both files in the `next` folder.
57
+ - If failed: Keeps only `migration.next.check.sql` and an error file, removing `migration.next.sql` if it exists. - If `DATABASE_URL` is not defined:
58
+ - Only generates both files, without validating.
59
+ - Updates the `psm.yml` file with migration information, such as status, driver, URL, schema, and history.
60
+
61
+ ### 2. Applying the migration (`psm commit`)
62
+
63
+ - Validates the migration again by running `migration.next.check.sql`.
64
+ - If validated:
65
+ - Applies `migration.next.sql` to the database.
66
+ - Generates a definitive revision in `revision/${timestamp}-${label}/` with:
67
+ - Applied migration script.
68
+ - Updated `psm.yml` file.
69
+ - Registers the applied migration in the database for control.
70
+ - If failure occurs, abort and display the error.
71
+
72
+ ### 3. Deploy to production (`psm deploy`)
73
+
74
+ - Applies all pending revisions stored in the `revision/` folder incrementally. - Ensures the database is always synchronized with the migration history.
75
+
76
+ ---
77
+
78
+ ## Detailed Migration Engine
79
+
80
+ PSM uses a temporary shadow schema to ensure data security:
81
+
82
+ 1. Creates a temporary schema `shadow_${random}`.
83
+ 2. Creates temporary tables for each Prisma model, without constraints (e.g., `temp_1_user` for the `user` model).
84
+ 3. Copies data from the real tables to the temporary tables.
85
+ 4. Applies constraints (keys, indexes, relationships) to the temporary tables.
86
+ 5. If everything passes during validation (check):
87
+ - Removes the shadow schema and temporary tables.
88
+ 6. If everything passes during application (migrate next):
89
+ - Removes the real tables.
90
+ - Moves the temporary tables from the shadow schema to the final schema.
91
+ - Renames the temporary tables to their real names.
92
+ - Removes the shadow schema. - Records the applied migration in the database for control purposes.
93
+
94
+ This process prevents direct destructive changes to the actual tables before full validation, preventing data loss.
95
+
96
+ ---
97
+
98
+ ## Generated file structure
99
+
100
+ - **next/**
101
+ - `migration.next.check.sql` — script to validate the migration.
102
+ - `migration.next.sql` — script to apply the migration.
103
+ - (optional) error file in case of failure.
104
+ - **revision/${timestamp}-${label}/**
105
+ - `migration.sql` — final migration script.
106
+ - `psm.yml` — metadata and history of the applied migration.
107
+ - **psm.yml**
108
+ - Main file with status, configurations, history, and validation results.
109
+
110
+ ---
111
+
112
+ ## Environment Variable
113
+
114
+ Configure the connection to your database in the `.env` file or in the environment:
115
+
116
+ ```env
117
+ DATABASE_URL="postgresql://username:password@localhost:5432/yourbank"
118
+ ```
119
+
120
+ ---
121
+ ## Main Commands
122
+
123
+ | Command | Description |
124
+ |----------------------|------------------------------------------------------------------------|
125
+ | `npx prisma generate` | Generates the migration files in the `next` folder and validates them (if `DATABASE_URL` is set). |
126
+ | `psm commit` | Validates and applies the next migration. Creates the final revision in the `revision/` folder. |
127
+ | `psm deploy` | Applies all pending migrations from the `revision/` folder in the correct order. |
128
+
129
+ ---
130
+
131
+ ## Usage Example
132
+
133
+ ```bash
134
+ # Generate migration and validate (if DATABASE_URL is set)
135
+ npx prisma generate
136
+
137
+ # Validate and apply the generated migration
138
+ psm commit
139
+
140
+ # Apply all pending migrations in production
141
+ psm deploy
142
+ ```
143
+
144
+ ---
145
+
146
+ ## Benefits
147
+
148
+ - **Data loss guarantee** with strict validation. - Easy rollback and revision control.
149
+ - Automatic validation during migration generation.
150
+ - Detailed history of applied changes.
151
+ - Initial support for PostgreSQL, with expansion options.
152
+
153
+ ---
154
+
155
+ ## Roadmap
156
+
157
+ - Support for more databases (MySQL, SQLite, etc.).
158
+ - Graphical interface for migration management.
159
+ - Integration with CI/CD pipelines.
160
+ - Manual and custom migrations.
161
+ - Multi-schema and multi-tenant support.
162
+
163
+ ---
164
+
165
+ ## Contribution
166
+
167
+ Contributions are welcome! Open issues for bugs or suggestions, and send pull requests for improvements.
168
+
169
+ ---
170
+
171
+ ## License
172
+
173
+ Project licensed under [Apache 2.0](./LICENSE).
174
+
175
+ ---
176
+
177
+ ## Traduções
178
+
179
+ [Português](./README.pt.md) | [English](./README.en.md)
180
+
181
+ ---
182
+
183
+ ## Contact
184
+
185
+ For questions, suggestions, or support, open an issue or contact us via email.
186
+
187
+ ---
188
+
189
+ **PSM - Safe and reliable migrations for your database with Prisma.**
package/README.md CHANGED
@@ -1,23 +1,22 @@
1
-
2
1
  # PSM - Prisma Safe Migrate
3
2
 
4
- ## Descrição
3
+ ## Description
5
4
 
6
- **PSM (Prisma Safe Migrate)** é uma ferramenta avançada para geração e aplicação segura de migrações SQL baseadas no modelo Prisma. Seu principal objetivo é garantir que alterações no banco de dados sejam aplicadas sem risco de perda de dados, algo que o sistema padrão de migrações do Prisma não assegura completamente.
5
+ **PSM (Prisma Safe Migrate)** is an advanced tool for generating and safely applying SQL migrations based on the Prisma model. Its main objective is to ensure that database changes are applied without risk of data loss, something that Prisma's standard migration system does not fully guarantee.
7
6
 
8
7
  ---
9
8
 
10
- ## Motivação
9
+ ## Motivation
11
10
 
12
- Migrações de banco de dados são processos críticos que precisam preservar a integridade e os dados existentes. O Prisma fornece um sistema eficiente para migrações, porém sem garantias absolutas contra perda de dados em alterações complexas, como renomear colunas, alterar tipos de dados ou remover tabelas.
11
+ Database migrations are critical processes that need to preserve the integrity of existing data. Prisma provides an efficient migration system, but it does not guarantee absolute data loss due to complex changes, such as renaming columns, changing data types, or dropping tables.
13
12
 
14
- O PSM preenche essa lacuna ao criar uma camada extra de validação, controle rigoroso de revisões e aplicação incremental segura em ambientes de produção.
13
+ PSM fills this gap by creating an extra layer of validation, strict revision control, and safe incremental application in production environments.
15
14
 
16
15
  ---
17
16
 
18
- ## Instalação
17
+ ## Installation
19
18
 
20
- Instale os pacotes do PSM como dependências de desenvolvimento no seu projeto:
19
+ Install the PSM packages as development dependencies in your project:
21
20
 
22
21
  ```bash
23
22
  npm install --save-dev @prisma-psm/core @prisma-psm/pg
@@ -25,166 +24,166 @@ npm install --save-dev @prisma-psm/core @prisma-psm/pg
25
24
 
26
25
  ---
27
26
 
28
- ## Configuração
27
+ ## Configuration
29
28
 
30
- No seu arquivo `schema.prisma`, configure o gerador do PSM para gerar os arquivos SQL e conectar ao banco:
29
+ In your `schema.prisma` file, configure the PSM generator to generate the SQL files and connect to the database:
31
30
 
32
31
  ```prisma
33
32
  generator psm {
34
- provider = "psm migrate generate"
35
- output = "./psm/"
36
- driver = "@prisma-psm/pg"
37
- url = env("DATABASE_URL")
33
+ provider = "psm generate"
34
+ output = "./psm/"
35
+ driver = "@prisma-psm/pg"
36
+ url = env("DATABASE_URL")
38
37
  }
39
38
  ```
40
39
 
41
- - **provider**: gerador do PSM que substitui o padrão do Prisma para geração de migrações.
42
- - **output**: diretório onde serão gerados os arquivos SQL e artefatos do PSM.
43
- - **driver**: driver específico para o banco (exemplo: PostgreSQL).
44
- - **url**: variável de ambiente contendo a string de conexão ao banco.
40
+ - **provider**: PSM generator that replaces Prisma's default migration generator.
41
+ - **output**: directory where the SQL files and PSM artifacts will be generated. - **driver**: Database-specific driver (e.g., PostgreSQL).
42
+ - **url**: Environment variable containing the database connection string.
45
43
 
46
44
  ---
47
45
 
48
- ## Como funciona - Fluxo geral
46
+ ## How it works - General flow
49
47
 
50
- ### 1. Geração da migração (`npx prisma generate`)
48
+ ### 1. Migration generation (`npx prisma generate`)
51
49
 
52
- - Gera os artefatos do Prisma normalmente.
53
- - Gera dois arquivos principais na pasta `next`:
54
- - `migration.next.check.sql`: script para validar se a migração está consistente com o banco atual.
55
- - `migration.next.sql`: script que aplicará as alterações.
56
- - Se `DATABASE_URL` estiver configurada:
57
- - Executa automaticamente o script de check.
58
- - Se sucesso: mantém os dois arquivos na pasta `next`.
59
- - Se falha: mantém `migration.next.check.sql` e um arquivo de erro, removendo `migration.next.sql` se existir.
60
- - Se `DATABASE_URL` não estiver definida:
61
- - Apenas gera ambos os arquivos, sem validar.
62
- - Atualiza o arquivo `psm.yml` com informações da migração, como status, driver, URL, esquema, e histórico.
50
+ - Generates Prisma artifacts normally.
51
+ - Generates two main files in the `next` folder:
52
+ - `migration.next.check.sql`: Script to validate whether the migration is consistent with the current database.
53
+ - `migration.next.sql`: Script that will apply the changes.
54
+ - If `DATABASE_URL` is configured:
55
+ - Automatically executes the check script.
56
+ - If successful: Keeps both files in the `next` folder.
57
+ - If failed: Keeps only `migration.next.check.sql` and an error file, removing `migration.next.sql` if it exists. - If `DATABASE_URL` is not defined:
58
+ - Only generates both files, without validating.
59
+ - Updates the `psm.yml` file with migration information, such as status, driver, URL, schema, and history.
63
60
 
64
- ### 2. Aplicação da migração (`psm migrate commit`)
61
+ ### 2. Applying the migration (`psm commit`)
65
62
 
66
- - Valida novamente a migração executando `migration.next.check.sql`.
67
- - Se validado:
68
- - Aplica o `migration.next.sql` no banco.
69
- - Gera uma revisão definitiva em `revision/${timestamp}-${label}/` com:
70
- - Script da migração aplicada.
71
- - Arquivo `psm.yml` atualizado.
72
- - Registra no banco a migração aplicada para controle.
73
- - Se falha, aborta e mostra o erro.
63
+ - Validates the migration again by running `migration.next.check.sql`.
64
+ - If validated:
65
+ - Applies `migration.next.sql` to the database.
66
+ - Generates a definitive revision in `revision/${timestamp}-${label}/` with:
67
+ - Applied migration script.
68
+ - Updated `psm.yml` file.
69
+ - Registers the applied migration in the database for control.
70
+ - If failure occurs, abort and display the error.
74
71
 
75
- ### 3. Deploy em produção (`psm migrate deploy`)
72
+ ### 3. Deploy to production (`psm deploy`)
76
73
 
77
- - Aplica todas as revisões pendentes armazenadas na pasta `revision/` de forma incremental.
78
- - Garante que o banco esteja sempre sincronizado com o histórico de migrações.
74
+ - Applies all pending revisions stored in the `revision/` folder incrementally. - Ensures the database is always synchronized with the migration history.
79
75
 
80
76
  ---
81
77
 
82
- ## Motor de migração (engine) detalhado
78
+ ## Detailed Migration Engine
83
79
 
84
- O PSM usa um esquema shadow temporário para garantir segurança dos dados:
80
+ PSM uses a temporary shadow schema to ensure data security:
85
81
 
86
- 1. Cria um schema temporário `shadow_${random}`.
87
- 2. Cria tabelas temporárias para cada modelo Prisma, sem constraints (ex: `temp_1_user` para o modelo `user`).
88
- 3. Copia os dados das tabelas reais para as temporárias.
89
- 4. Aplica as constraints (chaves, índices, relacionamentos) nas tabelas temporárias.
90
- 5. Se na validação (check) tudo passar:
91
- - Remove o schema shadow e as tabelas temporárias.
92
- 6. Se na aplicação (migrate next) tudo passar:
93
- - Remove as tabelas reais.
94
- - Move as tabelas temporárias do schema shadow para o schema final.
95
- - Renomeia as tabelas temporárias para os nomes reais.
96
- - Remove o schema shadow.
97
- - Registra a migração aplicada no banco para controle.
82
+ 1. Creates a temporary schema `shadow_${random}`.
83
+ 2. Creates temporary tables for each Prisma model, without constraints (e.g., `temp_1_user` for the `user` model).
84
+ 3. Copies data from the real tables to the temporary tables.
85
+ 4. Applies constraints (keys, indexes, relationships) to the temporary tables.
86
+ 5. If everything passes during validation (check):
87
+ - Removes the shadow schema and temporary tables.
88
+ 6. If everything passes during application (migrate next):
89
+ - Removes the real tables.
90
+ - Moves the temporary tables from the shadow schema to the final schema.
91
+ - Renames the temporary tables to their real names.
92
+ - Removes the shadow schema. - Records the applied migration in the database for control purposes.
98
93
 
99
- Esse processo impede alterações destrutivas diretas nas tabelas reais antes da validação completa, evitando perda de dados.
94
+ This process prevents direct destructive changes to the actual tables before full validation, preventing data loss.
100
95
 
101
96
  ---
102
97
 
103
- ## Estrutura de arquivos gerados
98
+ ## Generated file structure
104
99
 
105
100
  - **next/**
106
- - `migration.next.check.sql` — script para validar a migração.
107
- - `migration.next.sql` — script para aplicar a migração.
108
- - (opcional) arquivo de erro em caso de falha.
101
+ - `migration.next.check.sql` — script to validate the migration.
102
+ - `migration.next.sql` — script to apply the migration.
103
+ - (optional) error file in case of failure.
109
104
  - **revision/${timestamp}-${label}/**
110
- - `migration.sql` — script definitivo da migração.
111
- - `psm.yml` — metadados e histórico da migração aplicada.
105
+ - `migration.sql` — final migration script.
106
+ - `psm.yml` — metadata and history of the applied migration.
112
107
  - **psm.yml**
113
- - Arquivo principal com estado, configurações, histórico e resultados das validações.
108
+ - Main file with status, configurations, history, and validation results.
114
109
 
115
110
  ---
116
111
 
117
- ## Variável de ambiente
112
+ ## Environment Variable
118
113
 
119
- Configure a conexão com seu banco no arquivo `.env` ou no ambiente:
114
+ Configure the connection to your database in the `.env` file or in the environment:
120
115
 
121
116
  ```env
122
- DATABASE_URL="postgresql://usuario:senha@localhost:5432/seubanco"
117
+ DATABASE_URL="postgresql://username:password@localhost:5432/yourbank"
123
118
  ```
124
119
 
125
120
  ---
121
+ ## Main Commands
126
122
 
127
- ## Comandos principais
128
-
129
- | Comando | Descrição |
130
- |-----------------------|---------------------------------------------------------------------------------------------|
131
- | `npx prisma generate` | Gera os arquivos de migração na pasta `next` e valida (se `DATABASE_URL` configurada). |
132
- | `psm migrate commit` | Valida e aplica a próxima migração. Cria revisão definitiva na pasta `revision/`. |
133
- | `psm migrate deploy` | Aplica todas as migrações pendentes da pasta `revision/` na ordem correta. |
123
+ | Command | Description |
124
+ |-----------------------|------------------------------------------------------------------------|
125
+ | `npx prisma generate` | Generates the migration files in the `next` folder and validates them (if `DATABASE_URL` is set). |
126
+ | `psm commit` | Validates and applies the next migration. Creates the final revision in the `revision/` folder. |
127
+ | `psm deploy` | Applies all pending migrations from the `revision/` folder in the correct order. |
134
128
 
135
129
  ---
136
130
 
137
- ## Exemplo de uso
131
+ ## Usage Example
138
132
 
139
133
  ```bash
140
- # Gerar migração e validar (se DATABASE_URL definida)
134
+ # Generate migration and validate (if DATABASE_URL is set)
141
135
  npx prisma generate
142
136
 
143
- # Validar e aplicar a migração gerada
144
- psm migrate commit
137
+ # Validate and apply the generated migration
138
+ psm commit
145
139
 
146
- # Aplicar todas as migrações pendentes em produção
147
- psm migrate deploy
140
+ # Apply all pending migrations in production
141
+ psm deploy
148
142
  ```
149
143
 
150
144
  ---
151
145
 
152
- ## Benefícios
146
+ ## Benefits
153
147
 
154
- - **Garantia contra perda de dados** com validação rigorosa.
155
- - **Rollback facilitado** e controle de revisões.
156
- - **Validação automática** durante geração de migrações.
157
- - **Histórico detalhado** das alterações aplicadas.
158
- - **Suporte inicial para PostgreSQL**, com possibilidade de expansão.
148
+ - **Data loss guarantee** with strict validation. - Easy rollback and revision control.
149
+ - Automatic validation during migration generation.
150
+ - Detailed history of applied changes.
151
+ - Initial support for PostgreSQL, with expansion options.
159
152
 
160
153
  ---
161
154
 
162
155
  ## Roadmap
163
156
 
164
- - Suporte a mais bancos (MySQL, SQLite, etc.).
165
- - Interface gráfica para gestão de migrações.
166
- - Integração com pipelines CI/CD.
167
- - Migrações manuais e customizadas.
168
- - Suporte multi-schema e multi-tenant.
157
+ - Support for more databases (MySQL, SQLite, etc.).
158
+ - Graphical interface for migration management.
159
+ - Integration with CI/CD pipelines.
160
+ - Manual and custom migrations.
161
+ - Multi-schema and multi-tenant support.
162
+
163
+ ---
164
+
165
+ ## Contribution
166
+
167
+ Contributions are welcome! Open issues for bugs or suggestions, and send pull requests for improvements.
169
168
 
170
169
  ---
171
170
 
172
- ## Contribuição
171
+ ## License
173
172
 
174
- Contribuições são bem-vindas! Abra issues para bugs ou sugestões, e envie pull requests para melhorias.
173
+ Project licensed under [Apache 2.0](./LICENSE).
175
174
 
176
175
  ---
177
176
 
178
- ## Licença
177
+ ## Traduções
179
178
 
180
- Projeto licenciado sob a [Apache 2.0](./LICENSE).
179
+ [Português](./README.pt.md) | [English](./README.en.md)
181
180
 
182
181
  ---
183
182
 
184
- ## Contato
183
+ ## Contact
185
184
 
186
- Para dúvidas, sugestões ou suporte, abra uma issue ou entre em contato via email.
185
+ For questions, suggestions, or support, open an issue or contact us via email.
187
186
 
188
187
  ---
189
188
 
190
- **PSM - Migrações seguras e confiáveis para seu banco de dados com Prisma.**
189
+ **PSM - Safe and reliable migrations for your database with Prisma.**