@carno.js/cli 0.1.61

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.
package/README.md ADDED
@@ -0,0 +1,109 @@
1
+ ## Carno.js CLI
2
+ The CLI (Command Line Interface) for Carno.js.
3
+
4
+ ### Instalação
5
+ To install, you can use npm or bun:
6
+ ```bash
7
+ bun install @carnojs/cli
8
+ ```
9
+
10
+ ### Uso
11
+ Você pode usar a CLI com npx ou bunx.
12
+
13
+ ### Gerar uma nova migração
14
+ Para gerar uma nova migração, use o comando
15
+ ```bash
16
+ bunx cli migration:generate
17
+ ```
18
+ Isso irá gerar um novo arquivo de migração com apenas as diferenças desde a última migration.
19
+
20
+ Partial indexes (Postgres) definidos nas entidades também são gerados automaticamente no SQL de migration. Em MySQL, predicates em índices não são suportados.
21
+
22
+ #### Sistema de Snapshot
23
+ O CLI mantém um arquivo `schema-snapshot.json` no diretório de migrations que armazena o estado atual do schema. Isso garante que:
24
+ - Apenas as mudanças desde a última migration sejam geradas
25
+ - Não há regeneração de queries já executadas
26
+ - O histórico de mudanças é mantido de forma incremental
27
+
28
+ O snapshot é atualizado automaticamente após cada migration gerada.
29
+
30
+ ### Executar todas as migrações pendentes
31
+ Para executar todas as migrações pendentes, use o comando
32
+ ```bash
33
+ bunx cli migration:run
34
+ ```
35
+
36
+ ### Exemplo de Fluxo de Trabalho
37
+
38
+ ```bash
39
+ # 1. Defina suas entidades
40
+ # src/entities/user.entity.ts
41
+ @Entity()
42
+ class User extends BaseEntity {
43
+ @PrimaryKey()
44
+ id: number;
45
+
46
+ @Property()
47
+ email: string;
48
+ }
49
+
50
+ # 2. Gere a primeira migration
51
+ bunx cli migration:generate
52
+ # Cria: database/migrations/migration_20231021120000.sql
53
+ # Cria: database/migrations/schema-snapshot.json
54
+
55
+ # 3. Execute a migration
56
+ bunx cli migration:run
57
+
58
+ # 4. Adicione uma nova coluna
59
+ @Entity()
60
+ class User extends BaseEntity {
61
+ @PrimaryKey()
62
+ id: number;
63
+
64
+ @Property()
65
+ email: string;
66
+
67
+ @Property()
68
+ password: string; // Nova coluna
69
+ }
70
+
71
+ # 5. Gere apenas o diff
72
+ bunx cli migration:generate
73
+ # Cria: database/migrations/migration_20231021120100.sql
74
+ # Atualiza: database/migrations/schema-snapshot.json
75
+ # Contém apenas: ALTER TABLE user ADD COLUMN password...
76
+
77
+ # 6. Execute a nova migration
78
+ bunx cli migration:run
79
+ ```
80
+
81
+ ### Troubleshooting
82
+
83
+ #### Erro: "undefined is not an object (evaluating 'bdCol.type.includes')"
84
+ Este erro ocorre quando o snapshot está corrompido ou incompleto. O CLI agora detecta e limpa automaticamente snapshots corrompidos. Se o problema persistir:
85
+
86
+ 1. Delete o arquivo `schema-snapshot.json` do diretório de migrations
87
+ 2. Execute `bunx carno migration:generate` novamente
88
+ 3. O snapshot será recriado do zero
89
+
90
+ #### Snapshot Corrompido
91
+ Se você suspeita que o snapshot está corrompido (colunas duplicadas, colunas sem type, etc.):
92
+
93
+ ```bash
94
+ # Opção 1: Deixe o CLI limpar automaticamente
95
+ bunx carno migration:generate
96
+
97
+ # Opção 2: Delete e recrie manualmente
98
+ rm src/migrations/schema-snapshot.json
99
+ bunx carno migration:generate
100
+ ```
101
+
102
+ O CLI agora gera snapshots corretamente:
103
+ - ✅ Cada tabela tem apenas suas próprias colunas
104
+ - ✅ Não há duplicação de colunas entre tabelas
105
+ - ✅ Não há warnings desnecessários
106
+ - ✅ Migrations são geradas apenas quando há mudanças reais
107
+
108
+ ### Contribuição
109
+ Contribuições são bem-vindas. Por favor, abra um problema ou faça um pull request com suas mudanças.
package/dist/bin.js ADDED
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env bun
2
+
3
+ // Load the compiled CLI (CommonJS)
4
+ require('./src/cli.js');
package/dist/cli.ts ADDED
@@ -0,0 +1,29 @@
1
+ #!/usr/bin/env node
2
+
3
+ import 'reflect-metadata';
4
+ import { Command } from 'commander';
5
+ import { Migrator } from './migrator/migrator';
6
+
7
+ const program = new Command();
8
+
9
+ program.name('[npx|bunx] cli').description('CLI to Carno.js ORM ');
10
+
11
+ program
12
+ .command('migration:generate')
13
+ .description('generate a new migration file with a diff')
14
+ .action(async (str, options) => {
15
+ const migrator = new Migrator();
16
+ await migrator.generateMigration();
17
+ process.exit(0);
18
+ });
19
+
20
+ program
21
+ .command('migration:run')
22
+ .description('run all pending migrations')
23
+ .action(async (str, options) => {
24
+ const migrator = new Migrator();
25
+ await migrator.migrate();
26
+ process.exit(0);
27
+ });
28
+
29
+ program.parse();
package/dist/index.ts ADDED
@@ -0,0 +1,5 @@
1
+ import 'reflect-metadata';
2
+
3
+ export * from './migrator/migrator';
4
+ export * from './migrator/snapshot-manager';
5
+ export * from './migrator/snapshot-cleaner';
@@ -0,0 +1,2 @@
1
+ #!/bin/bash
2
+ node --experimental-modules ./node_modules/@carno.js/cli/dist/cli.js "$@"
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ import 'reflect-metadata';
@@ -0,0 +1,26 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ require("reflect-metadata");
5
+ const commander_1 = require("commander");
6
+ const migrator_1 = require("./migrator/migrator");
7
+ const program = new commander_1.Command();
8
+ program.name('[npx|bunx] cli').description('CLI to Carno.js ORM ');
9
+ program
10
+ .command('migration:generate')
11
+ .description('generate a new migration file with a diff')
12
+ .action(async (str, options) => {
13
+ const migrator = new migrator_1.Migrator();
14
+ await migrator.generateMigration();
15
+ process.exit(0);
16
+ });
17
+ program
18
+ .command('migration:run')
19
+ .description('run all pending migrations')
20
+ .action(async (str, options) => {
21
+ const migrator = new migrator_1.Migrator();
22
+ await migrator.migrate();
23
+ process.exit(0);
24
+ });
25
+ program.parse();
26
+ //# sourceMappingURL=cli.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli.js","sourceRoot":"","sources":["../../src/cli.ts"],"names":[],"mappings":";;;AAEA,4BAA0B;AAC1B,yCAAoC;AACpC,kDAA+C;AAE/C,MAAM,OAAO,GAAG,IAAI,mBAAO,EAAE,CAAC;AAE9B,OAAO,CAAC,IAAI,CAAC,gBAAgB,CAAC,CAAC,WAAW,CAAC,sBAAsB,CAAC,CAAC;AAEnE,OAAO;KACJ,OAAO,CAAC,oBAAoB,CAAC;KAC7B,WAAW,CAAC,2CAA2C,CAAC;KACxD,MAAM,CAAC,KAAK,EAAE,GAAG,EAAE,OAAO,EAAE,EAAE;IAC7B,MAAM,QAAQ,GAAG,IAAI,mBAAQ,EAAE,CAAC;IAChC,MAAM,QAAQ,CAAC,iBAAiB,EAAE,CAAC;IACnC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AAClB,CAAC,CAAC,CAAC;AAEL,OAAO;KACJ,OAAO,CAAC,eAAe,CAAC;KACxB,WAAW,CAAC,4BAA4B,CAAC;KACzC,MAAM,CAAC,KAAK,EAAE,GAAG,EAAE,OAAO,EAAE,EAAE;IAC7B,MAAM,QAAQ,GAAG,IAAI,mBAAQ,EAAE,CAAC;IAChC,MAAM,QAAQ,CAAC,OAAO,EAAE,CAAC;IACzB,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AAClB,CAAC,CAAC,CAAC;AAEL,OAAO,CAAC,KAAK,EAAE,CAAC"}
@@ -0,0 +1,4 @@
1
+ import 'reflect-metadata';
2
+ export * from './migrator/migrator';
3
+ export * from './migrator/snapshot-manager';
4
+ export * from './migrator/snapshot-cleaner';
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ require("reflect-metadata");
18
+ __exportStar(require("./migrator/migrator"), exports);
19
+ __exportStar(require("./migrator/snapshot-manager"), exports);
20
+ __exportStar(require("./migrator/snapshot-cleaner"), exports);
21
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,4BAA0B;AAE1B,sDAAoC;AACpC,8DAA4C;AAC5C,8DAA4C"}
@@ -0,0 +1,33 @@
1
+ import { DriverInterface, EntityStorage } from '@carno.js/orm';
2
+ import { ColDiff, ColumnsInfo, SnapshotTable, TableDiff } from './migrator';
3
+ export declare class DiffCalculator {
4
+ private driver;
5
+ private entities;
6
+ constructor(entities: EntityStorage, driver: DriverInterface);
7
+ diff(snapshotBd: SnapshotTable[], snapshotEntities: SnapshotTable[]): TableDiff[];
8
+ private checkIndexes;
9
+ private checkUniques;
10
+ private buildUniqueTable;
11
+ private uniqueChanged;
12
+ private normalizeUniqueColumns;
13
+ private formatUniqueName;
14
+ private buildIndexTable;
15
+ private buildIndexChangeDiff;
16
+ private indexChanged;
17
+ private normalizeIndexColumns;
18
+ private normalizeIndexWhere;
19
+ private cleanIndexToken;
20
+ private formatIndexName;
21
+ private createNewColumn;
22
+ private diffColumnType;
23
+ private normalizeType;
24
+ private diffColumnDefault;
25
+ private diffColumnPrimary;
26
+ private diffColumnUnique;
27
+ private diffForeignKey;
28
+ private diffColumnSql;
29
+ diffColumnPrecisionAndScale(bdCol: ColumnsInfo, entityCol: ColumnsInfo, colDiffs: ColDiff[]): void;
30
+ private diffColumnNullable;
31
+ private convertEntityTypeToSqlType;
32
+ private diffEnum;
33
+ }